After a lot of digging, this is what I found out (if useful to anyone else, also to dig deeper into this problem):
In Settings -> Desktop & Dock -> Mission Control, I had flagged:
- Automatically rearrange Spaces based on most recent use
- Displays have separate Spaces
With this settings, with the macbook opened and connected to the external monitor, I couldn't use different wallpapers on the two different monitors (the external and the macbook's one, which have different ratio): as explained in the request, plugging and unplugging the external monitor caused one monitor to inherit the wallpaper that was set on the other (one way or the other, based on which monitor's Space the wallpaper was set).
The FIX I found (not a solution) is to uncheck in Settings: Displays have separate Spaces.
Doing that, you need to set the external monitor as primary monitor when connected, so the dock will appear on the external monitor and the macbook will become an extension of the external monitor.
But doing so will let you set different wallpapers on the macbook and the external monitor and keep them when plugging/unplugging the external monitor.
Said that, here are some nerdy technical stuff I figured out (using macOS Ventura).
The wallpapers settings are stored in this file:
/Users/tommy/Library/Application\ Support/Dock/desktoppicture.db
It's an SQLite database, you can open it with "DB Browser for SQLite".
Inside there are these tables:
- Data: the currently used wallpapers paths and directories
- Displays: the used displays (in my case the macbook's one and the external monitor)
- Spaces: all the used spaces
- Pictures: the mapping of spaces in displays (+ NULL ??)
- Preferences: the mapping of pictures and data (+ key??)
- Prefs: empty (not needed??)
If you use "DB Browser for SQLite", right click on the table columns header to show the rowID (it's all based on rowIDs).
After some tests, watching the results, my opinion is that the code managing the wallpapers needs a lot of improvements, if not fixes:
- displays and spaces are not cleaned up when removed (maybe are cached)
- it's not obvious the meaning of NULL in Pictures for both spaces and displays
- the "jump" of spaces from one display (when unplugged) to another seems bugged at least
- in Preferences, the data should be updated accordingly to which display a space is "jumped to"