Repository navigation
Conversation
Allows opening multiple Superset windows simultaneously, one per
workspace, so several projects can be viewed side-by-side.
Main process:
- New windows/manager.ts registry tracking every BrowserWindow with its
workspaceId and focus recency; replaces the single-window assumption.
- MainWindow() accepts { workspaceId, stagger } and per-key persisted
window state (window-state.json is now a keyed map with automatic
migration from the legacy single-state shape; no cross-key fallback).
- App-level singletons lifted out of the window lifecycle into
lib/app-services.ts: notifications HTTP server (single port bind),
NotificationManager, terminal-exit forwarder. Window close handlers
now only clean up their own panes and IPC binding.
- tRPC createContext resolves the calling window per IPC event via the
manager (walking webview hostWebContents), so procedures act on the
window that actually issued the call.
- BrowserManager.unregisterAllForWindow() scopes pane cleanup to the
closing window using webContents.hostWebContents ownership.
- Deep links, OAuth callback fallback, tray, and macOS activate now
route through the manager instead of getAllWindows()[0].
- "New Window" menu item (Cmd/Ctrl+Shift+N) spawns a staggered window.
Renderer:
- Window URLs carry ?workspaceId= in the hash; the root route validates
it and navigates straight to /workspace/$workspaceId without touching
lastViewedWorkspaceId, so secondary windows don't hijack restore.
Tests: window-state keyed map + migration, window manager registry,
browser-manager per-window pane ownership.
…ndows Accessing window.webContents inside the 'closed' handler throws "Object has been destroyed" because the window is already gone by the time the event fires. Capture the webContents id at registration and use it for cleanup instead. The fakes in manager.test.ts kept webContents readable after close, which is why the existing test missed this; a new test makes the getter throw the way real Electron does.
Two windows on the same workspace used to mirror each other: tab/pane selection is keyed by workspace in the persisted tabs state, and the whole blob is written last-writer-wins, so concurrent windows clobbered each other's structure. Selection (activeTabIds, focusedPaneIds, history) now stays local to each window. The persisted values only act as a seed at boot. Structure stays consistent through a new uiState.tabs.onChange subscription: every persisted write is broadcast with the source webContents id, other windows merge the remote tabs/panes while keeping their own selection, and the storage adapter drops the echo write (including any stale local write still sitting in the debounce window, which would otherwise resurrect a remotely-closed tab). Dangling selection after a remote close is repaired through the existing MRU resolver. New ways to get a second window: "Open in New Window" on the workspace context menu and "Open Tab in New Window" on the tab strip, backed by a window.openWorkspaceWindow mutation and a focusTabId query param so the new window lands on the right tab. window.self exposes the caller's identity for the echo filtering. Known limitation, documented in the plan doc: persistence is still an unversioned full snapshot, so two structural edits inside the same 300ms debounce window can lose one write. Structural edits are human-paced, so this is accepted for now; the plan sketches a versioning scheme if it ever matters. The storage adapter moved to trpc-storage-adapter.ts so the suppression path could get unit tests without dragging in the electron client.
📝 WalkthroughWalkthroughThis PR implements multi-window support for the Superset desktop app by introducing a managed window registry, refactoring tRPC routers to use request context instead of injected callbacks, migrating to per-window keyed state persistence, moving app services to boot-time initialization, and adding cross-window tab-state synchronization with renderer storage suppression. ChangesMulti-window per-workspace architecture
Estimated code review effort🎯 5 (Critical) | ⏱️ ~120 minutes Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
|
Ready to review this PR? Stage has broken it down into 8 individual chapters for you: Chapters generated by Stage for commit 58794a1 on Jun 8, 2026 6:05pm UTC. |
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (1)
apps/desktop/src/renderer/stores/tabs/cross-window-sync.ts (1)
56-63: ⚡ Quick winType cast obscures structural intent; consider explicit field selection.
Lines 59 and 73 cast
TabsStatetoRemoteTabsStateviaas unknown as. This works becausemergeRemoteTabsStateonly reads.tabsand.panes, ignoring selection fields. However, the cast silences TypeScript's detection of the mismatch between what the tRPC endpoint returns (full state) and what the merge semantically expects (structure only).♻️ Suggested refactor to make intent explicit
Option 1: Destructure only the fields needed:
.query() -.then((state) => - applyRemoteTabsState(state as unknown as RemoteTabsState), -) +.then((state) => { + const { tabs, panes } = state; + applyRemoteTabsState({ tabs, panes }); +})Apply the same pattern on line 73:
-applyRemoteTabsState(event.state as unknown as RemoteTabsState); +const { tabs, panes } = event.state; +applyRemoteTabsState({ tabs, panes });Option 2: Change
RemoteTabsStatetoTabsStateand document that merge ignores selection fields (though option 1 is clearer).🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/desktop/src/renderer/stores/tabs/cross-window-sync.ts` around lines 56 - 63, The code currently uses a double-cast (as unknown as RemoteTabsState) when calling electronTrpcClient.uiState.tabs.get.query and then applyRemoteTabsState, which hides a structural mismatch between the endpoint's TabsState and the merge routine's expected shape; instead, explicitly pick the fields the merge needs (e.g., destructure { tabs, panes } from the fetched state) before passing them to applyRemoteTabsState or mergeRemoteTabsState, or alternatively update RemoteTabsState to match TabsState with clear documentation — locate the call to electronTrpcClient.uiState.tabs.get.query and replace the cast with an explicit selection of the required properties (tabs, panes) and pass that object into applyRemoteTabsState/mergeRemoteTabsState.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@apps/desktop/src/lib/trpc/routers/ui-state/index.ts`:
- Around line 263-272: The tabs.set mutation builds a TabsStateChangeEvent using
ctx.window?.webContents.id without checking window lifetime; update the code to
safely obtain a webContentsId by first checking ctx.window exists and
!ctx.window.isDestroyed() (or better: capture webContentsId in the request
context during createContext and use that value here) and use null if the window
is missing/destroyed; apply the same defensive pattern used in other routers
(e.g., window router/self) to avoid reading webContents.id from a destroyed
BrowserWindow when constructing the TabsStateChangeEvent in the mutation.
In `@apps/desktop/src/main/windows/main.ts`:
- Around line 201-210: Update the comment in createContext to accurately reflect
that TrpcContext.window can be null instead of claiming it "always resolves" to
a BrowserWindow; mention that we walk to hostWebContents to prefer resolving the
owning BrowserWindow (and that dialog procedures are no-ops when it remains
null). Reference the createContext function and TrpcContext.window (ctx.window)
in the comment so readers know the code prefers senderManaged?.window or
BrowserWindowCtor.fromWebContents(host) but still may yield null.
In `@apps/desktop/src/renderer/lib/trpc-storage-adapter.ts`:
- Around line 119-120: The version is being persisted to localStorage before
awaiting the tRPC write (localStorage.setItem is called before await
config.set), which can leave version/state inconsistent if the mutation fails;
change the sequence in the flush handler so you first await
config.set(parsed.state) (the existing config.set call in this function), then
on success assign lastFlushedValue = parsed.state (or the existing
lastFlushedValue update), and only after those succeed call
localStorage.setItem(`${name}:version`, String(parsed.version)); this ensures
localStorage version is updated only after a confirmed successful write (refer
to localStorage.setItem, config.set, and lastFlushedValue in the function).
---
Nitpick comments:
In `@apps/desktop/src/renderer/stores/tabs/cross-window-sync.ts`:
- Around line 56-63: The code currently uses a double-cast (as unknown as
RemoteTabsState) when calling electronTrpcClient.uiState.tabs.get.query and then
applyRemoteTabsState, which hides a structural mismatch between the endpoint's
TabsState and the merge routine's expected shape; instead, explicitly pick the
fields the merge needs (e.g., destructure { tabs, panes } from the fetched
state) before passing them to applyRemoteTabsState or mergeRemoteTabsState, or
alternatively update RemoteTabsState to match TabsState with clear documentation
— locate the call to electronTrpcClient.uiState.tabs.get.query and replace the
cast with an explicit selection of the required properties (tabs, panes) and
pass that object into applyRemoteTabsState/mergeRemoteTabsState.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: ed66f0ad-2c81-4645-88fe-0bc4a4121a63
📒 Files selected for processing (35)
apps/desktop/plans/20260517-multi-window-per-workspace.mdapps/desktop/plans/20260607-per-window-panel-selection-and-sync.mdapps/desktop/src/lib/electron-app/factories/app/setup.tsapps/desktop/src/lib/electron-app/factories/windows/create.tsapps/desktop/src/lib/trpc/index.tsapps/desktop/src/lib/trpc/routers/index.tsapps/desktop/src/lib/trpc/routers/notifications.tsapps/desktop/src/lib/trpc/routers/projects/projects.tsapps/desktop/src/lib/trpc/routers/ringtone/index.tsapps/desktop/src/lib/trpc/routers/ui-state/index.tsapps/desktop/src/lib/trpc/routers/window.tsapps/desktop/src/lib/window-loader.tsapps/desktop/src/main/index.tsapps/desktop/src/main/lib/app-services.tsapps/desktop/src/main/lib/browser/browser-manager.test.tsapps/desktop/src/main/lib/browser/browser-manager.tsapps/desktop/src/main/lib/menu.tsapps/desktop/src/main/lib/notifications/server.tsapps/desktop/src/main/lib/window-state/index.tsapps/desktop/src/main/lib/window-state/window-state-map.test.tsapps/desktop/src/main/lib/window-state/window-state.tsapps/desktop/src/main/windows/main.tsapps/desktop/src/main/windows/manager.test.tsapps/desktop/src/main/windows/manager.tsapps/desktop/src/renderer/index.tsxapps/desktop/src/renderer/lib/trpc-storage-adapter.test.tsapps/desktop/src/renderer/lib/trpc-storage-adapter.tsapps/desktop/src/renderer/lib/trpc-storage.tsapps/desktop/src/renderer/routes/page.tsxapps/desktop/src/renderer/screens/main/components/WorkspaceSidebar/WorkspaceListItem/WorkspaceContextMenu.tsxapps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/GroupStrip/GroupItem.tsxapps/desktop/src/renderer/stores/tabs/cross-window-sync.tsapps/desktop/src/renderer/stores/tabs/merge-remote-state.test.tsapps/desktop/src/renderer/stores/tabs/merge-remote-state.tsapps/desktop/src/renderer/stores/tabs/remote-apply.ts
| .mutation(async ({ ctx, input }) => { | ||
| appState.data.tabsState = input; | ||
| await appState.write(); | ||
| const event: TabsStateChangeEvent = { | ||
| state: input, | ||
| sourceWebContentsId: ctx.window?.webContents.id ?? null, | ||
| }; | ||
| tabsStateEvents.emit(TABS_STATE_CHANGED, event); | ||
| return { success: true }; | ||
| }), |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Check if other routers guard webContents access
rg -n -C3 'webContents\.id' --type=ts -g 'apps/desktop/src/lib/trpc/routers/**'Repository: superset-sh/superset
Length of output: 1284
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== Search for webContents id access patterns (guards/cached IDs) =="
rg -n --type=ts \
'(webContents\.id|webContents\?\.id|isDestroyed\(\)|getWebContents.*Id|sourceWebContentsId)' \
apps/desktop/src/lib/trpc/routers
echo
echo "== Search for isDestroyed() usage in the Electron desktop code (broader) =="
rg -n --type=ts 'isDestroyed\(\)' apps/desktop/srcRepository: superset-sh/superset
Length of output: 2202
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== Locate where trpc ctx.window is created/typed =="
# Find the ctx builder (common names vary); start with window in ctx type usages.
rg -n --type=ts 'ctx\.window|window\?: .*webContents|type .*Ctx|createTRPC' apps/desktop/src/lib/trpc
echo
echo "== Also check for router context factory outside lib/trpc =="
rg -n --type=ts 'createContext|createTRPCContext|getTRPCContext|ctx\W*=\W*' apps/desktop/src/main apps/desktop/src/lib/trpcRepository: superset-sh/superset
Length of output: 4986
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== apps/desktop/src/main/windows/main.ts around createContext =="
nl -ba apps/desktop/src/main/windows/main.ts | sed -n '160,260p'
echo
echo "== apps/desktop/src/lib/trpc/index.ts ctx.window docs/types =="
nl -ba apps/desktop/src/lib/trpc/index.ts | sed -n '1,220p'
echo
echo "== apps/desktop/src/lib/trpc/routers/ui-state/index.ts around tabsState mutation (approx) =="
nl -ba apps/desktop/src/lib/trpc/routers/ui-state/index.ts | sed -n '230,330p'
echo
echo "== apps/desktop/src/lib/trpc/routers/window.ts around webContentsId read =="
nl -ba apps/desktop/src/lib/trpc/routers/window.ts | sed -n '1,120p'Repository: superset-sh/superset
Length of output: 190
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== apps/desktop/src/main/windows/main.ts around createContext =="
cat -n apps/desktop/src/main/windows/main.ts | sed -n '160,260p'
echo
echo "== apps/desktop/src/lib/trpc/index.ts ctx.window docs/types =="
cat -n apps/desktop/src/lib/trpc/index.ts | sed -n '1,220p'
echo
echo "== apps/desktop/src/lib/trpc/routers/ui-state/index.ts around tabsState mutation (approx) =="
cat -n apps/desktop/src/lib/trpc/routers/ui-state/index.ts | sed -n '230,330p'
echo
echo "== apps/desktop/src/lib/trpc/routers/window.ts around webContentsId read =="
cat -n apps/desktop/src/lib/trpc/routers/window.ts | sed -n '1,140p'Repository: superset-sh/superset
Length of output: 14525
Guard ctx.window?.webContents.id in tabs.set (UI-state router)
apps/desktop/src/lib/trpc/routers/ui-state/index.ts reads ctx.window?.webContents.id when building TabsStateChangeEvent. ctx.window is resolved from the IPC sender in apps/desktop/src/main/windows/main.ts with no isDestroyed()/lifetime guard, so if the window is destroyed mid-mutation this could still be a risk. Also, apps/desktop/src/lib/trpc/routers/window.ts (self) reads ctx.window.webContents.id without isDestroyed(), reinforcing the need for a consistent defensive pattern (e.g., capture webContentsId in createContext, or guard with ctx.window.isDestroyed() before reading).
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@apps/desktop/src/lib/trpc/routers/ui-state/index.ts` around lines 263 - 272,
The tabs.set mutation builds a TabsStateChangeEvent using
ctx.window?.webContents.id without checking window lifetime; update the code to
safely obtain a webContentsId by first checking ctx.window exists and
!ctx.window.isDestroyed() (or better: capture webContentsId in the request
context during createContext and use that value here) and use null if the window
is missing/destroyed; apply the same defensive pattern used in other routers
(e.g., window router/self) to avoid reading webContents.id from a destroyed
BrowserWindow when constructing the TabsStateChangeEvent in the mutation.
There was a problem hiding this comment.
Fixed in 58794a1. Captured webContentsId once in createContext (added to TrpcContext) — the one moment the sender is provably alive — and tabs.set now reads ctx.webContentsId. Also applied to window.ts self for the consistent defensive pattern you flagged. Reading .webContents off a stored BrowserWindow later (the destroyed-mid-mutation case) is now avoided entirely.
| createContext: async ({ event }) => { | ||
| // IPC may originate from a <webview> pane, not the host renderer. | ||
| // Walk to hostWebContents so ctx.window always resolves to the | ||
| // owning BrowserWindow (otherwise dialog procedures no-op). | ||
| const host = event.sender.hostWebContents ?? event.sender; | ||
| const senderManaged = getManagedWindowByWebContents(host.id); | ||
| const senderWindow = | ||
| senderManaged?.window ?? BrowserWindowCtor.fromWebContents(host); | ||
| return { window: senderWindow }; | ||
| }, |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Search for TrpcContext type definition to confirm window field type
rg -n -A5 -B2 'type TrpcContext|interface TrpcContext' --type=tsRepository: superset-sh/superset
Length of output: 502
Clarify ctx.window nullability in createContext
TrpcContext.window is typed as BrowserWindow | null, so the comment wording “ctx.window always resolves to the owning BrowserWindow” is inaccurate even though dialog procedures no-op when it can’t be resolved.
Doc fix
-// Walk to hostWebContents so ctx.window always resolves to the
-// owning BrowserWindow (otherwise dialog procedures no-op).
+// Walk to hostWebContents to find the owning BrowserWindow.
+// If not found, ctx.window will be null and dialog procedures no-op.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@apps/desktop/src/main/windows/main.ts` around lines 201 - 210, Update the
comment in createContext to accurately reflect that TrpcContext.window can be
null instead of claiming it "always resolves" to a BrowserWindow; mention that
we walk to hostWebContents to prefer resolving the owning BrowserWindow (and
that dialog procedures are no-ops when it remains null). Reference the
createContext function and TrpcContext.window (ctx.window) in the comment so
readers know the code prefers senderManaged?.window or
BrowserWindowCtor.fromWebContents(host) but still may yield null.
There was a problem hiding this comment.
Fixed in 58794a1. Comment now says we walk to hostWebContents to prefer resolving the owning BrowserWindow, and that ctx.window stays null (dialog procedures no-op) when it can't be resolved.
| localStorage.setItem(`${name}:version`, String(parsed.version)); | ||
| await config.set(parsed.state); |
There was a problem hiding this comment.
Move version persistence after successful state write.
The version is written to localStorage at line 119 before awaiting the config.set() call at line 120. If the tRPC mutation fails, the catch block at line 130 will skip setting lastFlushedValue (line 121), but the version in localStorage will already have been incremented. On the next getItem() call, the canonical snapshot will combine the new version from localStorage with the old state from config.get(), creating a version/state mismatch that could mask persistence failures.
🛡️ Proposed fix: persist version only after successful write
isFlushing = true;
try {
const parsed = JSON.parse(valueToFlush) as {
state: unknown;
version: number;
};
- // Persist version in localStorage, bare state via tRPC.
- localStorage.setItem(`${name}:version`, String(parsed.version));
await config.set(parsed.state);
+ // Persist version in localStorage only after successful tRPC write.
+ localStorage.setItem(`${name}:version`, String(parsed.version));
lastFlushedValue = valueToFlush;📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| localStorage.setItem(`${name}:version`, String(parsed.version)); | |
| await config.set(parsed.state); | |
| isFlushing = true; | |
| try { | |
| const parsed = JSON.parse(valueToFlush) as { | |
| state: unknown; | |
| version: number; | |
| }; | |
| await config.set(parsed.state); | |
| // Persist version in localStorage only after successful tRPC write. | |
| localStorage.setItem(`${name}:version`, String(parsed.version)); | |
| lastFlushedValue = valueToFlush; |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@apps/desktop/src/renderer/lib/trpc-storage-adapter.ts` around lines 119 -
120, The version is being persisted to localStorage before awaiting the tRPC
write (localStorage.setItem is called before await config.set), which can leave
version/state inconsistent if the mutation fails; change the sequence in the
flush handler so you first await config.set(parsed.state) (the existing
config.set call in this function), then on success assign lastFlushedValue =
parsed.state (or the existing lastFlushedValue update), and only after those
succeed call localStorage.setItem(`${name}:version`, String(parsed.version));
this ensures localStorage version is updated only after a confirmed successful
write (refer to localStorage.setItem, config.set, and lastFlushedValue in the
function).
There was a problem hiding this comment.
Fixed in 58794a1. Moved localStorage.setItem(version) to after await config.set(state). On a rejected write the version now stays at its prior value, so the next getItem() rebuilds a consistent version+state snapshot instead of masking the failure.
There was a problem hiding this comment.
1 issue found across 35 files
Architecture diagram
sequenceDiagram
participant R1 as Renderer Window A
participant R2 as Renderer Window B
participant TRPC as tRPC Router
participant Main as Main Process
participant Mgr as Window Manager
participant State as appState (lowdb)
participant Adapter as Storage Adapter
participant Sync as Cross-Window Sync
participant Merge as Merge Remote State
Note over R1,Merge: Multi-window tabs sync flow
R1->>R1: User creates/renames/closes tab
R1->>Adapter: setItem(tabs, snapshot)
Adapter->>Adapter: Debounce 300ms
Adapter->>TRPC: uiState.tabs.set(state)
TRPC->>State: Write to lowdb
TRPC->>TRPC: Emit TABS_STATE_CHANGED event
TRPC-->>Main: Broadcast {state, sourceWebContentsId}
Note over Main,Sync: Cross-window broadcast
Main->>Sync: uiState.tabs.onChange subscription
Sync->>TRPC: window.self query (identity)
TRPC-->>Sync: {webContentsId, workspaceId}
Sync->>Merge: applyRemoteTabsState(remoteState)
Merge->>Merge: Only structure (tabs, panes) from remote
Merge->>R2: setState({tabs, panes})
R2->>R2: Keep local activeTabIds, focusedPaneIds
alt Focused tab closed remotely
Merge->>R2: Reconcile: fallback to MRU
R2->>R2: Set activeTabId from tabHistoryStacks
else Focused pane closed remotely
Merge->>R2: Reconcile: fallback to first pane in tab
end
Note over R2,Adapter: Echo suppression
R2->>Adapter: setItem(tabs, value) [from remote apply]
Adapter->>Adapter: shouldSuppressWrite() returns true
Adapter->>Adapter: Drop write, cancel pending flush
alt Stale local write in debounce window
Note over R1,Adapter: Before remote apply, R1 had pending write
R1->>Adapter: setItem(tabs, staleLocalValue)
R1->>R1: Remote merge applied
R1->>Adapter: setItem(tabs, sameAsRemote)
Adapter->>Adapter: Identical to lastFlushedValue → skip
end
Note over R1,R2: New window creation
R1->>R1: Right-click workspace → "Open in New Window"
R1->>TRPC: window.openWorkspaceWindow({workspaceId, focusTabId})
TRPC->>Main: Import MainWindow, create window
Main->>Mgr: registerWindow(window, {workspaceId})
Main->>R2: Load URL with ?workspaceId&focusTabId
R2->>R2: Apply focusTabId after hydration
Note over R1,Mgr: Per-window selection
R1->>TRPC: uiState.tabs.get (catch-up on subscribe)
TRPC-->>R1: Current persisted state
R1->>R1: Seed initial paint, keep local selection
Note over Mgr,State: Window state persistence
Main->>Mgr: Window close
Mgr->>State: saveWindowStateForKey(workspaceId, bounds)
State->>State: Write to window-state.json (keyed map)
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
Greptile SummaryThis PR adds multi-window support to the desktop app: each window can display a different workspace and maintain independent tab selection, while tab/pane structure (create, close, rename) stays in sync across windows via a new
Confidence Score: 3/5Two real defects in newly-introduced code paths should be fixed before shipping: a null-dereference crash (silently caught but mislogged) in the cross-window catch-up, and a read-modify-write race in window-state persistence that can silently drop one window's saved bounds when two workspace windows close at the same time. The cross-window sync catch-up in cross-window-sync.ts calls mergeRemoteTabsState without guarding for a null result from appState.data.tabsState, producing a silent TypeError that is caught and mislogged. Separately, saveWindowStateForKey in window-state.ts performs an unguarded read-modify-write: two windows closing within the same millisecond window each read the pre-write map, patch only their own key, and the second writer silently discards the first window's bounds. Both issues are in code paths directly exercised by the core feature of this PR. apps/desktop/src/renderer/stores/tabs/cross-window-sync.ts (null guard), apps/desktop/src/main/lib/window-state/window-state.ts (concurrent-write safety)
|
| Filename | Overview |
|---|---|
| apps/desktop/src/renderer/stores/tabs/cross-window-sync.ts | New cross-window subscription module; unguarded null in catch-up fetch causes a silent merge crash when no tabs state is persisted yet. |
| apps/desktop/src/main/lib/window-state/window-state.ts | Migrated to keyed map storage; the read-modify-write in saveWindowStateForKey is not atomic between concurrent callers, risking one window's bounds being silently dropped when two windows close at the same time. |
| apps/desktop/src/renderer/lib/trpc-storage-adapter.ts | Extracted storage adapter with suppression flag for remote-apply writes; logic is correct and well-tested. |
| apps/desktop/src/renderer/stores/tabs/merge-remote-state.ts | Well-implemented merge function; preserves local selection and MRU history while taking remote structure, with comprehensive unit test coverage. |
| apps/desktop/src/main/windows/manager.ts | New window registry; correctly captures webContentsId at registration to avoid destroyed-window access in the closed handler. |
| apps/desktop/src/main/lib/app-services.ts | Correctly lifts notification server, NotificationManager, and terminal-exit listener out of MainWindow into an app-level singleton that survives any single window's lifecycle. |
| apps/desktop/src/main/windows/main.ts | Refactored to support multiple windows with per-workspace state keys, stagger logic, and ctx-based IPC routing; context factory correctly walks hostWebContents for webview callers. |
| apps/desktop/src/lib/trpc/routers/ui-state/index.ts | Adds tabs.onChange subscription using EventEmitter with echo suppression via sourceWebContentsId; max-listeners set to 100 to avoid spurious warnings. |
| apps/desktop/src/lib/trpc/routers/window.ts | Refactored from getWindow closure to ctx.window; adds window.self and openWorkspaceWindow procedures for multi-window support. |
| apps/desktop/src/renderer/routes/page.tsx | Adds workspaceId and focusTabId query param handling; focusTabApplied module-level guard is correct per-renderer-process. |
Sequence Diagram
sequenceDiagram
participant WA as Window A (renderer)
participant Main as Main Process (tRPC/appState)
participant WB as Window B (renderer)
Note over WA,WB: Window B opens — catches up
WB->>Main: uiState.tabs.onChange.subscribe()
WB->>Main: uiState.tabs.get (catch-up)
Main-->>WB: "TabsState {tabs, panes}"
WB->>WB: "mergeRemoteTabsState(local, remote) structure=remote, selection=local"
Note over WA,WB: Window A closes a tab
WA->>WA: store.setState → closeTab
WA->>Main: uiState.tabs.set (debounced 300ms)
Main->>Main: appState.write()
Main->>Main: "tabsStateEvents.emit TABS_STATE_CHANGED sourceWebContentsId=A"
Main-->>WA: "onChange event (sourceWebContentsId=A)"
WA->>WA: drop (own echo)
Main-->>WB: "onChange event (sourceWebContentsId=A)"
WB->>WB: runWithRemoteTabsApply → mergeRemoteTabsState suppress echo write
WB->>WB: if activeTab was closed → MRU fallback
Prompt To Fix All With AI
Fix the following 2 code review issues. Work through them one at a time, proposing concise fixes.
---
### Issue 1 of 2
apps/desktop/src/renderer/stores/tabs/cross-window-sync.ts:56-63
**Unguarded null in catch-up apply crashes silently**
The catch-up query result is cast directly to `RemoteTabsState` without a null guard. When `appState.data.tabsState` is null (fresh install, corrupted state file, or a second window opened before any tabs have been written), `mergeRemoteTabsState` immediately throws `TypeError: Cannot read properties of null (reading 'panes')` at the first `Object.entries(remote.panes)` call. The error is caught by `.catch` and mislogged as "catch-up fetch failed" — a network-error label for what is actually a null-dereference crash in the merge function. The window silently skips the structural catch-up and may show stale tab structure until the next write from another window arrives.
The fix is a one-line null guard in the `.then` callback: `.then((state) => { if (state) applyRemoteTabsState(state as unknown as RemoteTabsState); })`.
### Issue 2 of 2
apps/desktop/src/main/lib/window-state/window-state.ts:102-110
**Read-modify-write race on concurrent window closes**
`saveWindowStateForKey` reads the entire map, patches one key, and writes the file back. When two keyed windows close within the same ~few-millisecond window (e.g. the user quits the app with two workspace windows open, or rapidly closes two windows), both read the pre-write map, each patches only its own key, and the second write discards the first window's key entirely. The individual write is atomic (temp + rename) but the read-modify-write cycle is not. The affected window's bounds revert to defaults on next launch. Introducing a write-lock or using a `Map` kept in memory (written on every save, read only on first access) would avoid the race.
Reviews (1): Last reviewed commit: "feat(desktop): per-window panel selectio..." | Re-trigger Greptile
| electronTrpcClient.uiState.tabs.get | ||
| .query() | ||
| .then((state) => | ||
| applyRemoteTabsState(state as unknown as RemoteTabsState), | ||
| ) | ||
| .catch((err) => { | ||
| console.error("[cross-window-sync] catch-up fetch failed:", err); | ||
| }); |
There was a problem hiding this comment.
Unguarded null in catch-up apply crashes silently
The catch-up query result is cast directly to RemoteTabsState without a null guard. When appState.data.tabsState is null (fresh install, corrupted state file, or a second window opened before any tabs have been written), mergeRemoteTabsState immediately throws TypeError: Cannot read properties of null (reading 'panes') at the first Object.entries(remote.panes) call. The error is caught by .catch and mislogged as "catch-up fetch failed" — a network-error label for what is actually a null-dereference crash in the merge function. The window silently skips the structural catch-up and may show stale tab structure until the next write from another window arrives.
The fix is a one-line null guard in the .then callback: .then((state) => { if (state) applyRemoteTabsState(state as unknown as RemoteTabsState); }).
Prompt To Fix With AI
This is a comment left during a code review.
Path: apps/desktop/src/renderer/stores/tabs/cross-window-sync.ts
Line: 56-63
Comment:
**Unguarded null in catch-up apply crashes silently**
The catch-up query result is cast directly to `RemoteTabsState` without a null guard. When `appState.data.tabsState` is null (fresh install, corrupted state file, or a second window opened before any tabs have been written), `mergeRemoteTabsState` immediately throws `TypeError: Cannot read properties of null (reading 'panes')` at the first `Object.entries(remote.panes)` call. The error is caught by `.catch` and mislogged as "catch-up fetch failed" — a network-error label for what is actually a null-dereference crash in the merge function. The window silently skips the structural catch-up and may show stale tab structure until the next write from another window arrives.
The fix is a one-line null guard in the `.then` callback: `.then((state) => { if (state) applyRemoteTabsState(state as unknown as RemoteTabsState); })`.
How can I resolve this? If you propose a fix, please make it concise.There was a problem hiding this comment.
Addressed in 58794a1, with a correction. The runtime null-deref you describe can't actually occur: appState.data.tabsState is typed BaseTabsState (non-null) and defaulted on load (...(data.tabsState ?? {}) with tabs: [], panes: {}), so get never returns null and mergeRemoteTabsState never sees null panes. The real issue was the one CodeRabbit flagged on the same lines — the as unknown as RemoteTabsState cast was hiding a genuine structural mismatch (persisted tabs type is BaseTab[], no layout). Replaced both casts with a documented toRemoteStructure() helper that selects { tabs, panes } and downcasts BaseTab[] -> Tab[] (layout is guaranteed at runtime by tabsStateSchema).
| export function saveWindowStateForKey( | ||
| key: string, | ||
| state: WindowState, | ||
| filePath: string = WINDOW_STATE_PATH, | ||
| ): void { | ||
| const map = readWindowStateMap(filePath); | ||
| map[key] = state; | ||
| writeWindowStateMap(map, filePath); | ||
| } |
There was a problem hiding this comment.
Read-modify-write race on concurrent window closes
saveWindowStateForKey reads the entire map, patches one key, and writes the file back. When two keyed windows close within the same ~few-millisecond window (e.g. the user quits the app with two workspace windows open, or rapidly closes two windows), both read the pre-write map, each patches only its own key, and the second write discards the first window's key entirely. The individual write is atomic (temp + rename) but the read-modify-write cycle is not. The affected window's bounds revert to defaults on next launch. Introducing a write-lock or using a Map kept in memory (written on every save, read only on first access) would avoid the race.
Prompt To Fix With AI
This is a comment left during a code review.
Path: apps/desktop/src/main/lib/window-state/window-state.ts
Line: 102-110
Comment:
**Read-modify-write race on concurrent window closes**
`saveWindowStateForKey` reads the entire map, patches one key, and writes the file back. When two keyed windows close within the same ~few-millisecond window (e.g. the user quits the app with two workspace windows open, or rapidly closes two windows), both read the pre-write map, each patches only its own key, and the second write discards the first window's key entirely. The individual write is atomic (temp + rename) but the read-modify-write cycle is not. The affected window's bounds revert to defaults on next launch. Introducing a write-lock or using a `Map` kept in memory (written on every save, read only on first access) would avoid the race.
How can I resolve this? If you propose a fix, please make it concise.There was a problem hiding this comment.
Looked into this — it's not a race, and I added a comment in 58794a1 explaining why. saveWindowStateForKey is fully synchronous: readWindowStateMap uses readFileSync and writeWindowStateMap uses writeFileSync+renameSync, with no await anywhere between read and write. Both call sites (close/resize handlers in main.ts) invoke it synchronously too. Node runs each call to completion before any other JS, so two windows closing 'simultaneously' queue their handlers — the second call's read only runs after the first's write has landed. No key is dropped. The added comment documents this invariant so a future async refactor doesn't silently reintroduce the race you'd otherwise be right about.
- ctx.webContentsId: capture the sender's webContents id once in createContext (when the window is provably alive) and add it to TrpcContext. tabs.set and window.self now read ctx.webContentsId instead of ctx.window.webContents.id, which could throw "Object has been destroyed" if the window closed mid-mutation. (coderabbit, cubic) - trpc-storage-adapter: write state via config.set() before bumping the localStorage version. Persisting the version first meant a failed config.set left a bumped version paired with stale state on the next getItem(), masking the failure. (coderabbit, critical) - cross-window-sync: replace the opaque `as unknown as RemoteTabsState` casts with a documented toRemoteStructure() helper that selects tabs+panes and downcasts BaseTab[] -> Tab[] (layout is guaranteed at runtime by tabsStateSchema). Makes the structural intent explicit. (coderabbit nitpick, greptile) - createContext: correct the comment to say ctx.window may be null rather than "always resolves". (coderabbit) - saveWindowStateForKey: document the synchronous read-modify-write invariant. The flagged "concurrent close race" cannot occur — the function is fully synchronous (readFileSync -> writeFileSync) so Node runs each call to completion with no interleaving. Comment guards against a future async refactor reintroducing the race. (greptile)
What
You can now open the same workspace in several windows and keep a different tab focused in each one. Tab structure (create, close, rename, layout) stays in sync between windows; which tab you're looking at does not.
Two new entry points: right-click a workspace in the sidebar for "Open in New Window", or right-click a tab for "Open Tab in New Window", which opens the new window already focused on that tab. Cmd+Shift+N still works as before. Each window can also sit on a different workspace entirely, and sidebar/panel visibility is per-window.
Why
The tabs store keys selection by workspace (
activeTabIds[workspaceId]), and the whole state persists as a single blob with no change notifications between windows. Open the same workspace twice and both windows boot with identical state, then silently overwrite each other's writes. In practice a second window was useless: same panel everywhere, and closing a tab in one window could resurrect it from the other window's stale write.How
uiState.tabs.setnow broadcasts each write through a newuiState.tabs.onChangesubscription (observable, per the trpc-electron constraint), tagged with the source webContents id. Windows merge remote structure and keep local selection. If a remote close orphans the focused tab, the existing MRU resolver picks the replacement.trpc-storage-adapter.test.ts). The adapter moved to its own file so those tests don't pull in the electron client.window.selfandwindow.openWorkspaceWindoware new tRPC procedures;focusTabIdrides the window query string next toworkspaceId.There's also a small fix in
windows/manager.ts: theclosedhandler readwindow.webContentsafter destruction, which throws in real Electron. The id is now captured at registration.Known limitation
Persistence is still an unversioned full snapshot, so two structural edits from different windows inside the same 300ms debounce can lose one write. Structural edits are human-paced so I've accepted this for now; the plan doc (
apps/desktop/plans/20260607-per-window-panel-selection-and-sync.md) describes abasedOnVersionscheme if it ever becomes a problem.Testing
bun testfor the desktop app: 454 pass under the touched trees (merge logic, adapter suppression, window manager), 0 fail. Three pre-existingshell-wrappersfailures reproduce on a clean checkout and are unrelated.tsc --noEmitand Biome clean.Summary by cubic
Enables true multi-window use in the desktop app. Open the same workspace in several windows with independent tab focus; tab/pane structure stays in sync across windows. Recent changes harden persistence and IPC for reliability.
New Features
window.self.Bug Fixes
trpc-storage-adapternow writes via tRPC before bumping the local snapshot version to avoid masking failed writes.webContentsIdonce and using it inwindow.selfanduiState.tabs.set, and by capturing ids before window cleanup.Written for commit 58794a1. Summary will update on new commits.
Summary by CodeRabbit
Release Notes