@@ -2870,11 +2870,32 @@ function initializeExtension() {
28702870 // Read current session from SQLite via background to get authoritative agentBoxes —
28712871 // storageGet() routes through storageWrapper which may fall back to Chrome Storage
28722872 // (empty for session_ keys), causing agentBoxes to be silently zeroed on every agent save.
2873- const doSaveSession = (storedBoxes: any[]) => {
2873+ const doSaveSession = (storedBoxes: any[], storedGrids: any[] ) => {
28742874 if (storedBoxes.length > completeSessionData.agentBoxes.length) {
28752875 completeSessionData.agentBoxes = storedBoxes
28762876 }
28772877
2878+ // Merge displayGrids from SQLite with in-memory displayGrids — keep the
2879+ // most-recent entry per layout so a stale in-memory session never overwrites
2880+ // agentNumber (or other slot config) that was just saved by SAVE_AGENT_BOX_TO_SQLITE.
2881+ if (storedGrids.length > 0) {
2882+ const incomingGrids: any[] = completeSessionData.displayGrids || []
2883+ const mergedMap = new Map<string, any>()
2884+ // Seed with stored (SQLite) grids — these are authoritative
2885+ storedGrids.forEach((g: any) => {
2886+ mergedMap.set(g.layout || g.sessionId, g)
2887+ })
2888+ // Overlay with incoming only when incoming is genuinely newer
2889+ incomingGrids.forEach((inGrid: any) => {
2890+ const key = inGrid.layout || inGrid.sessionId
2891+ const existing = mergedMap.get(key)
2892+ const existTs = existing ? new Date(existing.timestamp || 0).getTime() : -1
2893+ const inTs = new Date(inGrid.timestamp || 0).getTime()
2894+ if (!existing || inTs > existTs) mergedMap.set(key, inGrid)
2895+ })
2896+ completeSessionData.displayGrids = Array.from(mergedMap.values())
2897+ }
2898+
28782899
28792900 // Save directly via SAVE_SESSION_TO_SQLITE (background.ts HTTP) to avoid
28802901 // storageWrapper/adapter race conditions. Chrome Storage is skipped intentionally —
@@ -2914,14 +2935,15 @@ function initializeExtension() {
29142935 chrome.runtime.sendMessage({ type: 'GET_SESSION_FROM_SQLITE', sessionKey }, (response) => {
29152936 if (chrome.runtime.lastError) {
29162937 console.warn('[TRACE] ensureSessionInHistory: could not read SQLite, proceeding without merge:', chrome.runtime.lastError.message)
2917- doSaveSession([])
2938+ doSaveSession([], [] )
29182939 return
29192940 }
29202941 const storedBoxes: any[] = response?.session?.agentBoxes || []
2921- doSaveSession(storedBoxes)
2942+ const storedGrids: any[] = response?.session?.displayGrids || []
2943+ doSaveSession(storedBoxes, storedGrids)
29222944 })
29232945 } else {
2924- doSaveSession([])
2946+ doSaveSession([], [] )
29252947 }
29262948
29272949 }
0 commit comments