Skip to content

feat(terminal): detach live tabs into secondary windows - #16203

Open
DEOWL-kan wants to merge 64 commits into
stablyai:mainfrom
DEOWL-kan:feat/detachable-terminal-tabs
Open

DEOWL-kan wants to merge 64 commits into
stablyai:mainfrom
DEOWL-kan:feat/detachable-terminal-tabs

Conversation

@DEOWL-kan

Copy link
Copy Markdown
Contributor

ELI5

Drag a live terminal tab out of Orca to move it into its own window without restarting the terminal or losing its scrollback. Closing or promoting windows keeps the surviving terminals attached to the correct window.

What Changed

  • Adds a transactional terminal-tab transfer flow across control and secondary Electron windows, preserving the PTY ID, live process, scrollback, layout, and agent/session identity.
  • Adds per-window session persistence, PTY renderer ownership transfer, control-window election/promotion, quit merge, crash recovery, and close-time retirement fences.
  • Adds unit and real Electron coverage for detach, reattach, user close, control promotion, quit merge, rollback, reload/crash recovery, SSH/folder-workspace boundaries, and PTY incarnation reuse.

Why

Reopening a terminal in a floating window loses the live process and terminal state. The transfer is staged and committed atomically so a failed drag or window loss rolls back safely, while successful moves retain the original execution session.

Linked Issue

Part of #7811. This PR implements the terminal-tab portion; browser, editor, and other tab types remain out of scope.

Visual Proof

N/A — rendered styling is unchanged. The interaction and live-state preservation are verified by the Electron E2E cases listed below, including exact PTY identity and post-transfer input/output assertions.

Testing

Tested locally on macOS with Node 24.19.0:

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below
  • Electron Playwright: 5/5 passed (headless detach; headful user close, control promotion, quit merge, live detach/reattach).
  • Changed unit suite: 93/93 files; 2171 passed, 1 skipped.
  • typecheck:node, typecheck:web, Electron build, CLI build, changed native/type-aware quality, strict React Doctor, max-lines ratchet, reliability gates, and git diff --check passed.
  • Full repository typecheck:e2e still reports pre-existing diagnostics in unrelated specs; the new detachable-window E2E specs have no diagnostics.
  • Real rendered validation was run through the repository Playwright Electron/CDP harness because the $electron skill was unavailable in this environment.
  • Linux, Windows, and live SSH hosts were not available for manual Electron validation; their compatibility boundaries are covered by runtime guards and automated tests.

AI Disclosure

OpenAI Codex assisted with implementation, debugging, tests, and review.

Review

Final specification review: approved, no P0/P1 findings. Independent quality review: approved, no P0/P1/P2 findings.

Agent skill upstream boundary

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

  • No remote wire opcode or incompatible payload change.
  • SSH loss remains unverifiable, never inferred as process exit.
  • PTY close authority is incarnation-, owner-, connection-, and provider-ownership-fenced.
  • The worktree and feature branch remain available for review follow-up.

Checklist

  • This PR is small and focused
  • I explained what changed and why (including ELI5)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

@greptile-apps

greptile-apps Bot commented Aug 24, 2026

Copy link
Copy Markdown

Too many files changed for review (186 files, 100 file limit).

Bypass the limit by tagging @greptile-apps to review.

@coderabbitai

coderabbitai Bot commented Aug 24, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Adds secondary terminal windows with PTY ownership handoff, renderer recovery, session persistence, and control-window promotion. PTY IPC now validates trusted main-frame senders and owner access, and routes delivery to the owning renderer. Terminal transfer commands support validation, acknowledgements, rollback, and recovery. Window close handling retires terminal state and confirms running-process closures. Renderer drag-out creates terminal transfers. Preload APIs, persistence registries, runtime parked layouts, SSH broadcasts, and macOS E2E coverage support the new lifecycle.

Merge Risk: 🟠 High · up to d7a50

This PR changes live terminal ownership across windows, but unresolved paths can lose detached terminal state during quit, leave the application without control services, kill a PTY still used by another tab, or drop queued runtime updates. These are high-impact correctness and availability risks, so the PR should not merge until they are fixed and covered by regression tests.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the primary change: detaching live terminal tabs into secondary windows.
Description check ✅ Passed The description covers the required change, rationale, issue, testing, AI disclosure, scope, and compatibility considerations, with only checklist items left unchecked.
Docstring Coverage ✅ Passed Docstring check was indeterminate for this PR — some files could not be analyzed in time. Not blocking.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 1
⚔️ Resolve merge conflicts 💡
  • Resolve merge conflict in branch feat/detachable-terminal-tabs

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 10

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/main/runtime/orca-runtime.ts (1)

12731-12739: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Preserve active mobile presence while a terminal claim is parked.

mobileSubscribers remains populated, but this early return hides it from hasRemoteTerminalViewSubscriber. With no separate raw subscriber, daemon keep-tail thinning can affect an attached mobile stream, and shouldAnswerQueriesForLiveChunk can let main answer queries owned by the mobile xterm. Keep active mobile subscribers visible and add a parked-with-mobile regression test.

🧹 Nitpick comments (6)
src/main/ipc/terminal-window-transfer.ts (1)

182-192: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Remove the overwritten disposeTargetRenderer assignment.

Lines 182-184 assign disposeTargetRenderer, and lines 186-192 replace it unconditionally. Nothing can invoke the first version, because this.#registerRenderer does not call the disposer. Keep only the final assignment.

♻️ Proposed cleanup
         transfer.targetBefore = getDefaultWorkspaceSession()
-        transfer.disposeTargetRenderer = () => {
-          this.#owners.removeRenderer(transfer.targetRenderer!)
-        }
         const dispose = this.#registerRenderer(transfer.targetRenderer)
         transfer.disposeTargetRenderer = () => {
tests/e2e/helpers/terminal-window-drag.ts (1)

7-12: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Add a platform guard inside warpCursor.

warpCursor runs the macOS-only binary /usr/bin/swift. The macOS check currently lives only in the callers (tests/e2e/detachable-terminal-tab.spec.ts lines 123, 142, 208, and 226). If a future spec calls this helper without that skip, the failure surfaces as an opaque ENOENT. Add an explicit runtime check so the helper reports the platform requirement itself.

As per coding guidelines: "Keep platform-dependent behavior behind runtime checks for macOS, Linux, and Windows."

♻️ Proposed guard
 function warpCursor(point: Point): void {
+  if (process.platform !== 'darwin') {
+    throw new Error('warpCursor requires macOS CoreGraphics')
+  }
   execFileSync('/usr/bin/swift', [

Source: Coding guidelines

tests/e2e/terminal-window-detach-live.spec.ts (1)

166-176: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Remove the trailing debug log.

This console.log asserts nothing and prints on every run. The identifiers it prints are already covered by the assertions above. Playwright reports the failing assertion with its own diff, so the log adds no diagnostic value.

🧹 Proposed cleanup
-  console.log(
-    JSON.stringify({
-      tabId,
-      ptyId: originalPtyId,
-      token,
-      beforeDetachMarker,
-      afterDetachMarker,
-      rollbackMarker,
-      afterReturnMarker
-    })
-  )
 })
src/main/ipc/terminal-window-transfer-session-patch.ts (1)

306-312: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Move the getDefaultWorkspaceSession import to the top of the file.

The import statement is placed after the last function declaration. Module imports are hoisted, so the runtime behavior is correct, but the placement is inconsistent with the other imports at lines 1-9 and will confuse readers and most import-order lint rules.

♻️ Proposed fix
+import { getDefaultWorkspaceSession } from '../../shared/constants'
 import type { Tab, TabGroup, TabGroupLayoutNode } from '../../shared/tab-types'
 import type { TerminalTab } from '../../shared/terminal-tab-types'
 export function removeTransferredTerminalSessionBacking(
   current: WorkspaceSessionState,
   seed: TerminalWindowTransferSeed
 ): WorkspaceSessionState {
   return removeTransferredTerminalSession(current, getDefaultWorkspaceSession(), seed)
 }
-import { getDefaultWorkspaceSession } from '../../shared/constants'
src/shared/terminal-window-transfer.ts (1)

19-23: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Derive the phase list from a single source.

TerminalWindowTransferPhase and the string array in isTerminalWindowTransferAck declare the same four phases in two places. A new phase added to the union will not be accepted by the runtime guard, and the compiler will not report the gap.

Declare the phases once as a const tuple and derive both the type and the guard from it.

♻️ Proposed refactor
-export type TerminalWindowTransferPhase =
-  | 'target-import'
-  | 'target-remove'
-  | 'source-remove'
-  | 'source-restore'
+export const TERMINAL_WINDOW_TRANSFER_PHASES = [
+  'target-import',
+  'target-remove',
+  'source-remove',
+  'source-restore'
+] as const
+
+export type TerminalWindowTransferPhase = (typeof TERMINAL_WINDOW_TRANSFER_PHASES)[number]
-    ['target-import', 'target-remove', 'source-remove', 'source-restore'].includes(
-      ack.phase ?? ''
-    ) &&
+    (TERMINAL_WINDOW_TRANSFER_PHASES as readonly string[]).includes(ack.phase ?? '') &&

Also applies to: 59-61

src/renderer/src/store/slices/tab-group-layout-removal.ts (1)

68-74: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Avoid writing undefined into activeGroupIdByWorktree.

The return value is typed Record<string, string>. If siblingId, fallbackGroupId, and the existing entry are all absent, line 72 stores an explicit undefined under worktreeId. The key then exists with a value that violates the declared type. buildTransferredTerminalRemovalPatch re-derives the active group afterwards, so this is currently harmless there, but other callers and any persistence of this record would carry the bad entry.

Delete the key instead when no group id resolves.

♻️ Proposed fix
-  return {
-    layoutByWorktree: nextLayoutByWorktree,
-    activeGroupIdByWorktree: {
-      ...activeGroupIdByWorktree,
-      [worktreeId]: siblingId ?? fallbackGroupId ?? activeGroupIdByWorktree[worktreeId]
-    }
-  }
+  const nextActiveGroupId =
+    siblingId ?? fallbackGroupId ?? activeGroupIdByWorktree[worktreeId] ?? null
+  const nextActiveGroupIdByWorktree = { ...activeGroupIdByWorktree }
+  if (nextActiveGroupId) {
+    nextActiveGroupIdByWorktree[worktreeId] = nextActiveGroupId
+  } else {
+    delete nextActiveGroupIdByWorktree[worktreeId]
+  }
+  return {
+    layoutByWorktree: nextLayoutByWorktree,
+    activeGroupIdByWorktree: nextActiveGroupIdByWorktree
+  }

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 7c391fa5-6011-41e8-93d3-a971eee781f0

📥 Commits

Reviewing files that changed from the base of the PR and between 4bc9e6b and d7a5007.

📒 Files selected for processing (186)
  • package.json
  • src/main/index.ts
  • src/main/ipc/browser-renderer-trust.test.ts
  • src/main/ipc/browser-renderer-trust.ts
  • src/main/ipc/browser-session-profile-ipc.test.ts
  • src/main/ipc/browser.test.ts
  • src/main/ipc/pty-applied-size-reporting.test.ts
  • src/main/ipc/pty-buffer-snapshot-dispatch.test.ts
  • src/main/ipc/pty-control-promotion-reload.test.ts
  • src/main/ipc/pty-cumulative-ack-accounting.test.ts
  • src/main/ipc/pty-daemon-ssh-lease-lifecycle.test.ts
  • src/main/ipc/pty-delivery-health-heal.test.ts
  • src/main/ipc/pty-dispatcher-handshake-osc-answers.test.ts
  • src/main/ipc/pty-hidden-delivery-gate.ts
  • src/main/ipc/pty-ipc-hidden-delivery-gate.test.ts
  • src/main/ipc/pty-ipc-listener-accessors.ts
  • src/main/ipc/pty-ipc-producer-flow-control.test.ts
  • src/main/ipc/pty-ipc-suite-environment.ts
  • src/main/ipc/pty-listener-teardown-and-orphans.test.ts
  • src/main/ipc/pty-management.test.ts
  • src/main/ipc/pty-management.ts
  • src/main/ipc/pty-output-drain-rounds.test.ts
  • src/main/ipc/pty-pane-claim-arbitration.test.ts
  • src/main/ipc/pty-pending-output-cap.test.ts
  • src/main/ipc/pty-renderer-inflight-credit.test.ts
  • src/main/ipc/pty-renderer-lifecycle-delivery-reset.test.ts
  • src/main/ipc/pty-renderer-owners.test.ts
  • src/main/ipc/pty-renderer-owners.ts
  • src/main/ipc/pty-renderer-send-failure-recovery.test.ts
  • src/main/ipc/pty-runtime-kill-and-exit.test.ts
  • src/main/ipc/pty-runtime-ssh-binding-persistence.test.ts
  • src/main/ipc/pty-serializer-settlement-mapping.test.ts
  • src/main/ipc/pty-session-liveness-and-ownership.test.ts
  • src/main/ipc/pty-spawn-runtime-handle-binding.test.ts
  • src/main/ipc/pty-ssh-stop-verdict.test.ts
  • src/main/ipc/pty-startup-barrier-and-listing.test.ts
  • src/main/ipc/pty-write-ipc-validation.test.ts
  • src/main/ipc/pty.ts
  • src/main/ipc/register-core-handlers.test.ts
  • src/main/ipc/register-core-handlers.ts
  • src/main/ipc/renderer-ipc-frame-trust.ts
  • src/main/ipc/renderer-shutdown-checkpoint.test.ts
  • src/main/ipc/renderer-shutdown-checkpoint.ts
  • src/main/ipc/repos-remote-client-events.test.ts
  • src/main/ipc/repos.ts
  • src/main/ipc/runtime.test.ts
  • src/main/ipc/runtime.ts
  • src/main/ipc/session.test.ts
  • src/main/ipc/session.ts
  • src/main/ipc/skill-ipc-main-window.test.ts
  • src/main/ipc/skill-ipc-main-window.ts
  • src/main/ipc/ssh-app-shutdown.test.ts
  • src/main/ipc/ssh-handler-reregistration.test.ts
  • src/main/ipc/ssh-ipc-module-mocks.ts
  • src/main/ipc/ssh-ipc-test-harness.ts
  • src/main/ipc/ssh-passphrase.test.ts
  • src/main/ipc/ssh-passphrase.ts
  • src/main/ipc/ssh-target-registry.test.ts
  • src/main/ipc/ssh.test.ts
  • src/main/ipc/ssh.ts
  • src/main/ipc/terminal-window-transfer-command.ts
  • src/main/ipc/terminal-window-transfer-coordinator-options.ts
  • src/main/ipc/terminal-window-transfer-fence.ts
  • src/main/ipc/terminal-window-transfer-lifecycle.test.ts
  • src/main/ipc/terminal-window-transfer-operation.ts
  • src/main/ipc/terminal-window-transfer-preflight.test.ts
  • src/main/ipc/terminal-window-transfer-recovery.ts
  • src/main/ipc/terminal-window-transfer-registration.ts
  • src/main/ipc/terminal-window-transfer-rollback.test.ts
  • src/main/ipc/terminal-window-transfer-seed-validation.ts
  • src/main/ipc/terminal-window-transfer-session-partition.test.ts
  • src/main/ipc/terminal-window-transfer-session-patch.test.ts
  • src/main/ipc/terminal-window-transfer-session-patch.ts
  • src/main/ipc/terminal-window-transfer-session-selectors.ts
  • src/main/ipc/terminal-window-transfer-target-import.ts
  • src/main/ipc/terminal-window-transfer-test-fixture.ts
  • src/main/ipc/terminal-window-transfer.test.ts
  • src/main/ipc/terminal-window-transfer.ts
  • src/main/ipc/ui.test.ts
  • src/main/ipc/ui.ts
  • src/main/persistence/window-session-merge.ts
  • src/main/persistence/window-session-registry-store.test.ts
  • src/main/persistence/window-session-registry.test.ts
  • src/main/persistence/window-session-registry.ts
  • src/main/providers/local-pty-provider-shutdown.test.ts
  • src/main/providers/local-pty-provider.ts
  • src/main/runtime/orca-runtime-parked-layout.test.ts
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/orca-runtime.ts
  • src/main/ssh/ssh-relay-session-relay-loss.test.ts
  • src/main/ssh/ssh-relay-session-test-fixtures.ts
  • src/main/ssh/ssh-relay-session.test.ts
  • src/main/ssh/ssh-relay-session.ts
  • src/main/startup/desktop-startup-ordering.test.ts
  • src/main/window/attach-main-window-services.test.ts
  • src/main/window/attach-main-window-services.ts
  • src/main/window/clipboard-dashboard-popout-access.test.ts
  • src/main/window/clipboard-ipc-handlers.test.ts
  • src/main/window/clipboard-ipc-handlers.ts
  • src/main/window/control-window-handoff.test.ts
  • src/main/window/control-window-handoff.ts
  • src/main/window/createMainWindow-close-confirmation.test.ts
  • src/main/window/createMainWindow-markdown-editor-focus.test.ts
  • src/main/window/createMainWindow-multi-window.test.ts
  • src/main/window/createMainWindow-renderer-crash-recovery.test.ts
  • src/main/window/createMainWindow-terminal-close-transaction.test.ts
  • src/main/window/createMainWindow-tray-minimize-close.test.ts
  • src/main/window/createMainWindow.test.ts
  • src/main/window/createMainWindow.ts
  • src/main/window/orca-window-broadcast.test.ts
  • src/main/window/orca-window-broadcast.ts
  • src/main/window/orca-window-manager.test.ts
  • src/main/window/orca-window-manager.ts
  • src/main/window/promoted-control-reload.test.ts
  • src/main/window/promoted-control-reload.ts
  • src/main/window/updater-package-recovery-ipc.test.ts
  • src/main/window/web-contents-timed-flag.test.ts
  • src/main/window/web-contents-timed-flag.ts
  • src/main/window/window-quit-lifecycle.test.ts
  • src/main/window/window-quit-lifecycle.ts
  • src/preload/api-types.ts
  • src/preload/api/pty-api.ts
  • src/preload/api/terminal-window-api.ts
  • src/preload/api/ui-window-api.ts
  • src/preload/app-restart-checkpoint-routing.test.ts
  • src/preload/index.ts
  • src/preload/terminal-window-api-ipc.test.ts
  • src/renderer/src/App.tsx
  • src/renderer/src/app-shell/use-app-shell-services.ts
  • src/renderer/src/app-shell/use-runtime-graph-sync.ts
  • src/renderer/src/components/Terminal.tsx
  • src/renderer/src/components/WindowCloseRunningProcessDialog.tsx
  • src/renderer/src/components/tab-group/tab-drag-drop-commit.test.ts
  • src/renderer/src/components/tab-group/tab-drag-drop-commit.ts
  • src/renderer/src/components/tab-group/tab-drag-gesture-lifecycle.ts
  • src/renderer/src/components/tab-group/tab-drag-missed-end-listeners.test.ts
  • src/renderer/src/components/tab-group/tab-drag-missed-end-listeners.ts
  • src/renderer/src/components/tab-group/tab-drag-pointer-sensor.ts
  • src/renderer/src/components/tab-group/tab-drag-pointer.test.ts
  • src/renderer/src/components/tab-group/tab-drag-pointer.ts
  • src/renderer/src/components/tab-group/useTabDragSplit-window-detach.test.ts
  • src/renderer/src/components/tab-group/useTabDragSplit.test.ts
  • src/renderer/src/components/tab-group/useTabDragSplit.ts
  • src/renderer/src/components/terminal-pane/terminal-tab-window-transfer.test.ts
  • src/renderer/src/components/terminal-pane/terminal-tab-window-transfer.ts
  • src/renderer/src/components/terminal-pane/use-terminal-window-transfer-rollback.test.ts
  • src/renderer/src/components/terminal-pane/use-terminal-window-transfer.test.ts
  • src/renderer/src/components/terminal-pane/use-terminal-window-transfer.ts
  • src/renderer/src/components/terminal/terminal-tab-actions.ts
  • src/renderer/src/components/terminal/terminal-window-close-retirement.test.ts
  • src/renderer/src/components/terminal/terminal-window-close-retirement.ts
  • src/renderer/src/components/terminal/terminal-window-retirement-close-actions.test.ts
  • src/renderer/src/components/window-close-request-coordinator.test.ts
  • src/renderer/src/components/window-close-request-coordinator.ts
  • src/renderer/src/hooks/ipc-events-close-routing-test-harness.ts
  • src/renderer/src/hooks/useIpcEvents-close-routing-session-tabs.test.ts
  • src/renderer/src/hooks/useIpcEvents.ts
  • src/renderer/src/lib/workspace-session-host-persistence.test.ts
  • src/renderer/src/lib/workspace-session-host-persistence.ts
  • src/renderer/src/store/slices/tab-group-layout-removal.ts
  • src/renderer/src/store/slices/tabs.ts
  • src/renderer/src/store/slices/terminal-tab-retirement-store.test.ts
  • src/renderer/src/store/slices/terminal-tab-retirement.test.ts
  • src/renderer/src/store/slices/terminal-tab-retirement.ts
  • src/renderer/src/store/slices/terminal-window-transfer-command-rollback.ts
  • src/renderer/src/store/slices/terminal-window-transfer-import-validation.ts
  • src/renderer/src/store/slices/terminal-window-transfer-local-projection.ts
  • src/renderer/src/store/slices/terminal-window-transfer-projection-rollback.ts
  • src/renderer/src/store/slices/terminal-window-transfer-removal-rollback.ts
  • src/renderer/src/store/slices/terminal-window-transfer-removal-state.ts
  • src/renderer/src/store/slices/terminal-window-transfer-state.ts
  • src/renderer/src/store/slices/terminal-window-transfer-worktree-scope.ts
  • src/renderer/src/store/slices/terminals.ts
  • src/renderer/src/web/web-preload-api-terminal-window.test.ts
  • src/renderer/src/web/web-preload-api.ts
  • src/shared/terminal-window-transfer.test.ts
  • src/shared/terminal-window-transfer.ts
  • src/shared/window-session-terminal-membership.ts
  • src/shared/workspace-session-persistence-host.test.ts
  • src/shared/workspace-session-persistence-host.ts
  • src/shared/workspace-session-rowless-terminal-close.ts
  • src/shared/workspace-session-terminal-tab-close.test.ts
  • src/shared/workspace-session-terminal-tab-close.ts
  • tests/e2e/detachable-terminal-tab.spec.ts
  • tests/e2e/helpers/terminal-window-drag.ts
  • tests/e2e/terminal-window-detach-live.spec.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.

Comment thread src/main/index.ts
Comment on lines +1644 to +1647
const secondaryId = secondary.id
secondary.on('closed', () => {
getWindowSessionRegistry(store!).retire(secondaryId, 'user-close')
})

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Guard the secondary-window retirement with isQuitting.

The control window path retires its session only when the app is not quitting (Line 1589). The secondary window path retires unconditionally. During quit, Electron closes secondary windows and emits closed, so each secondary session is retired as user-close. That contradicts the quit-time staging performed by stageAllKnownHostsBeforeQuit() and can drop persisted terminal state for detached windows on the next launch.

🐛 Proposed fix
       const secondaryId = secondary.id
       secondary.on('closed', () => {
+        if (isQuitting) {
+          return
+        }
         getWindowSessionRegistry(store!).retire(secondaryId, 'user-close')
       })
📝 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.

Suggested change
const secondaryId = secondary.id
secondary.on('closed', () => {
getWindowSessionRegistry(store!).retire(secondaryId, 'user-close')
})
const secondaryId = secondary.id
secondary.on('closed', () => {
if (isQuitting) {
return
}
getWindowSessionRegistry(store!).retire(secondaryId, 'user-close')
})

Comment on lines +201 to +204
expect(h.source.listenerCount('close')).toBe(0)
expect(h.target.listenerCount('close')).toBe(0)
expect(h.source.webContents.listenerCount('render-process-gone')).toBe(0)
expect(h.target.webContents.listenerCount('render-process-gone')).toBe(0)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Assert the closed event, not close.

installTerminalWindowTransferAbortListeners registers the window listener on closed (see terminal-window-transfer-operation.ts lines 174 and 176). The assertions on lines 201-202 count listeners for close, which is never registered. Both assertions pass regardless of cleanup, so the window-listener leak invariant is not covered.

💚 Proposed fix for the event name
-    expect(h.source.listenerCount('close')).toBe(0)
-    expect(h.target.listenerCount('close')).toBe(0)
+    expect(h.source.listenerCount('closed')).toBe(0)
+    expect(h.target.listenerCount('closed')).toBe(0)
     expect(h.source.webContents.listenerCount('render-process-gone')).toBe(0)
     expect(h.target.webContents.listenerCount('render-process-gone')).toBe(0)
📝 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.

Suggested change
expect(h.source.listenerCount('close')).toBe(0)
expect(h.target.listenerCount('close')).toBe(0)
expect(h.source.webContents.listenerCount('render-process-gone')).toBe(0)
expect(h.target.webContents.listenerCount('render-process-gone')).toBe(0)
expect(h.source.listenerCount('closed')).toBe(0)
expect(h.target.listenerCount('closed')).toBe(0)
expect(h.source.webContents.listenerCount('render-process-gone')).toBe(0)
expect(h.target.webContents.listenerCount('render-process-gone')).toBe(0)

Comment on lines +64 to +73
get(windowId: number, hostId?: string | null): WorkspaceSessionState {
const resolved = resolveHostId(hostId)
const existing = this.#records.get(windowId)?.get(resolved)
if (existing && !existing.retired) {
return cloneSession(existing.state)
}
const initial = cloneSession(this.#store.getWorkspaceSession(resolved))
this.#setRecord(windowId, initial, resolved)
return cloneSession(initial)
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Description: Find callers of WindowSessionRegistry.get/patch and the retire call sites to check ordering.
set -euo pipefail

fd -t f 'window-session-registry.ts' -x echo "definition: {}"

rg -nP -C4 '\b(getWindowSessionRegistry|windowSessionRegistry|sessionRegistry|sessions)\s*[.!?]*\.(get|patch|retire|markRendererUnavailable)\s*\(' --type=ts -g '!**/*.test.ts'

Repository: stablyai/orca

Length of output: 213


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '--- registry outline ---'
ast-grep outline src/main/persistence/window-session-registry.ts

echo '--- registry implementation ---'
cat -n src/main/persistence/window-session-registry.ts

echo '--- registry symbol references ---'
rg -n -C5 'WindowSessionRegistry|window-session-registry|\.retire\(|\.patch\(|\.get\(' src --glob '*.{ts,tsx,js,jsx}' --glob '!**/*.test.ts' --glob '!**/*.spec.ts'

Repository: stablyai/orca

Length of output: 50370


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '--- registry ---'
cat -n src/main/persistence/window-session-registry.ts

echo '--- imports and registry construction ---'
rg -n -C6 'window-session-registry|WindowSessionRegistry' src --glob '*.{ts,tsx,js,jsx}' --glob '!**/*.test.ts' --glob '!**/*.spec.ts'

echo '--- lifecycle and session event references ---'
rg -n -C8 'session:patch|session.*retir|retir.*session|markRendererUnavailable|mergeHost|window.*close|close.*window' src/main src/renderer --glob '*.{ts,tsx,js,jsx}' --glob '!**/*.test.ts' --glob '!**/*.spec.ts'

Repository: stablyai/orca

Length of output: 50370


🏁 Script executed:

#!/bin/bash
set -euo pipefail

log=/tmp/coderabbit-shell-logs/shell-output-HHGBYQ

echo '--- registry section from prior output ---'
rg -n -m1 'src/main/persistence/window-session-registry.ts' "$log" || true
sed -n '1,260p' "$log"

echo '--- exact registry references ---'
rg -n -C4 'window-session-registry|WindowSessionRegistry' src/main src/renderer --glob '*.{ts,tsx,js,jsx}' --glob '!**/*.test.ts' --glob '!**/*.spec.ts' | head -n 400

echo '--- session IPC and window-id helpers ---'
cat -n src/main/ipc/session.ts | sed -n '1,180p'
rg -n -C8 'function requireWindowId|const requireWindowId|requireWindowId\(' src/main --glob '*.{ts,tsx}'

Repository: stablyai/orca

Length of output: 35150


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '--- renderer session API calls ---'
rg -n -C5 'session\.(get|set|patch)|session:(get|set|patch|set-sync)|setSync|setSession|patchSession' src/renderer src/preload src/shared --glob '*.{ts,tsx,js,jsx}' --glob '!**/*.test.ts' --glob '!**/*.spec.ts' | head -n 800

echo '--- renderer shutdown checkpoint ---'
cat -n src/main/ipc/renderer-shutdown-checkpoint.ts | sed -n '1,180p'

echo '--- main window close lifecycle ---'
cat -n src/main/window/createMainWindow.ts | sed -n '1060,1235p'
cat -n src/main/index.ts | sed -n '1540,1660p'

Repository: stablyai/orca

Length of output: 50369


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '--- all session API call sites ---'
rg -n -C3 'window\.api\.session\.(get|set|patch|setSync|flush)' src --glob '*.{ts,tsx,js,jsx}' --glob '!**/*.test.ts' --glob '!**/*.spec.ts'

echo '--- close-retirement implementation ---'
cat -n src/renderer/src/components/terminal/terminal-window-close-retirement.ts | sed -n '1,180p'

echo '--- persistence lifecycle call sites ---'
rg -n -C6 'persistWorkspaceSession|buildWorkspaceSessionHostSnapshots|stageBeforeUnload|beforeunload|onWindowClosed|retire\(' src/main src/renderer --glob '*.{ts,tsx,js,jsx}' --glob '!**/*.test.ts' --glob '!**/*.spec.ts' | head -n 1000

Repository: stablyai/orca

Length of output: 50369


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '--- host persistence implementation ---'
cat -n src/renderer/src/lib/workspace-session-host-persistence.ts | sed -n '1,360p'

echo '--- session write subscriber ---'
cat -n src/renderer/src/lib/session-write-subscriber.ts | sed -n '1,300p'

echo '--- app session persistence ---'
cat -n src/renderer/src/app-shell/use-app-session-persistence.ts | sed -n '1,240p'

echo '--- all patchWorkspaceSessionByHost references ---'
rg -n -C8 'patchWorkspaceSessionByHost|createSessionWriteSubscriber|api\.patch\(' src/renderer --glob '*.{ts,tsx,js,jsx}' --glob '!**/*.test.ts' --glob '!**/*.spec.ts'

Repository: stablyai/orca

Length of output: 46222


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '--- sender-to-window mapping ---'
rg -n -C10 'getWindowForSender|register.*Window|unregister.*Window|\.on\(['\"']closed['\"']' src/main/window src/main --glob '*.{ts,tsx}' | head -n 800

echo '--- renderer close flow after retirement planning ---'
cat -n src/renderer/src/components/terminal/terminal-window-close-retirement.ts | sed -n '160,380p'

echo '--- transfer commit and retirement ordering ---'
cat -n src/main/ipc/terminal-window-transfer.ts | sed -n '180,285p'
cat -n src/main/ipc/terminal-window-transfer-recovery.ts | sed -n '90,155p'

echo '--- close request implementation ---'
cat -n src/main/window/createMainWindow.ts | sed -n '1080,1215p'

Repository: stablyai/orca

Length of output: 50369


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '--- OrcaWindowManager lifecycle ---'
cat -n src/main/window/orca-window-manager.ts | sed -n '1,190p'

echo '--- close handlers ---'
cat -n src/main/window/createMainWindow.ts | sed -n '1110,1210p'
cat -n src/main/index.ts | sed -n '1568,1652p'

echo '--- renderer close retirement flow ---'
cat -n src/renderer/src/components/terminal/terminal-window-close-retirement.ts | sed -n '175,360p'

echo '--- registry tests ---'
fd -t f -i 'window-session-registry' src | sort
rg -n -C8 'retired|resurrect|get\(|patch\(' src/main/persistence --glob '*window-session*test*' --glob '*window-session*spec*' || true

Repository: stablyai/orca

Length of output: 31630


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '--- registry lifecycle tests ---'
cat -n src/main/persistence/window-session-registry.test.ts | sed -n '380,620p'

echo '--- close-retirement tests ---'
rg -n -C10 'retireWindowTerminalTabsAndConfirmClose|session\.get|persistRetiredSessionTabs|beforeunload|confirmWindowClose' src/renderer/src/components/terminal --glob '*close*test*' --glob '*retirement*test*' --glob '*.test.ts' --glob '*.test.tsx' | head -n 1000

echo '--- close lifecycle test ordering ---'
rg -n -C12 'retire|closed|session|getWindowSessionRegistry|session:patch' src/main/window src/main/ipc --glob '*.test.ts' --glob '*.test.tsx' | head -n 1200

Repository: stablyai/orca

Length of output: 50370


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '--- transfer commit region ---'
sed -n '220,275p' src/main/ipc/terminal-window-transfer.ts

echo '--- transfer operation definitions ---'
rg -n -C12 'finishCommittedTerminalWindowTransfer|retireSource|emptyClose|sourceAck|source.*close|close\(' src/main/ipc/terminal-window-transfer-operation.ts src/main/ipc/terminal-window-transfer*.ts --glob '!**/*.test.ts'

echo '--- live-entry implementation ---'
rg -n -C8 '`#liveEntries`|`#liveEntry`' src/main/window/orca-window-manager.ts

echo '--- close request coordinator and beforeunload callers ---'
rg -n -C10 'dispatchWindowCloseRequest|retireWindowTerminalTabsAndConfirmClose|confirmWindowClose|beforeunload' src/renderer/src/components/window-close-request-coordinator.ts src/renderer/src --glob '*.{ts,tsx}' --glob '!**/*.test.ts' --glob '!**/*.spec.ts' | head -n 1000

Repository: stablyai/orca

Length of output: 50370


🏁 Script executed:

#!/bin/bash
set -euo pipefail

python3 - <<'PY'
from pathlib import Path

registry = Path("src/main/persistence/window-session-registry.ts").read_text()
session_ipc = Path("src/main/ipc/session.ts").read_text()
manager = Path("src/main/window/orca-window-manager.ts").read_text()
transfer = Path("src/main/ipc/terminal-window-transfer-operation.ts").read_text()
app_persistence = Path("src/renderer/src/app-shell/use-app-session-persistence.ts").read_text()
close_retirement = Path("src/renderer/src/components/terminal/terminal-window-close-retirement.ts").read_text()

checks = {
    "get_resets_retired": "if (existing && !existing.retired)" in registry
        and "this.#setRecord(windowId, initial, resolved)" in registry,
    "patch_calls_get": "const current = this.get(windowId, resolved)" in registry,
    "ipc_patch_requires_live_sender": "sessions.patch(requireWindowId(event), args, hostId)" in session_ipc
        and "if (!window)" in session_ipc,
    "sender_lookup_rejects_destroyed_sender": "if (sender.isDestroyed())" in manager
        and "return null" in manager[manager.index("if (sender.isDestroyed())"):manager.index("if (sender.isDestroyed())")+100],
    "transfer_retires_before_source_close": transfer.index("retireSource()") < transfer.index("source.close()"),
    "debounced_writer_calls_host_patch": "patchWorkspaceSessionByHost(window.api.session, patch, state)" in app_persistence,
    "close_path_reads_before_confirm": close_retirement.index("getWindowSessionState") < close_retirement.index("confirmWindowClose"),
}

for name, result in checks.items():
    print(f"{name}={result}")

print("registry_stage_before_unload_resets_retired=" +
      str("this.#setRecord(windowId, state, resolved)" in registry))
PY

Repository: stablyai/orca

Length of output: 443


Reject reads and patches for retired records.

The transfer path retires the source before source.close(), while the debounced writer can still issue session:patch. get re-seeds the retired record, and patch then marks it live. Return the existing retired state and make patch a no-op for retired records. Add a regression test.

(intentionalStopIncarnation === null || intentionalStopIncarnation === incarnationId)
advertisedUrlWatcher.unbindPty(ptyId)
// Clean up new mobile state for this PTY
this.parkedTerminalGraphClaims.delete(ptyId)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Parked claims are not removed when a PTY record is pruned without an exit.

onPtyExit deletes the parked claim, and reconcileWindowTerminalClaims deletes it on restore. dropDisconnectedPtyRecord prunes PTY records without an exit callback, but it does not delete parkedTerminalGraphClaims. Each orphaned entry retains two Map instances of registration snapshots for the life of the process.

Delete the parked claim in dropDisconnectedPtyRecord as well.

🧹 Proposed fix in dropDisconnectedPtyRecord
     this.advancePtyLifecycleGeneration(ptyId)
     this.pairedRendererSessionOwnedPtyIds.delete(ptyId)
+    this.parkedTerminalGraphClaims.delete(ptyId)
     this.ptysById.delete(ptyId)

Comment on lines +301 to +322
it('uses the tested quit lifecycle before side effects and stages merged hosts before flush', () => {
const source = readFileSync(join(process.cwd(), 'src/main/index.ts'), 'utf8')
const beforeQuitStart = source.indexOf("app.on('before-quit'")
const willQuitStart = source.indexOf("app.on('will-quit'", beforeQuitStart)
const windowAllClosedStart = source.indexOf("app.on('window-all-closed'", willQuitStart)
const beforeQuit = source.slice(beforeQuitStart, willQuitStart)
const willQuit = source.slice(willQuitStart, windowAllClosedStart)
const lifecycleBegin = beforeQuit.indexOf('windowQuitLifecycle.begin()')
const relayFence = beforeQuit.indexOf('desktopRelayService?.fenceAndCloseNow()')
const transferFence = willQuit.indexOf('terminalWindowQuitFence')
const stageSessions = willQuit.indexOf('stageAllKnownHostsBeforeQuit()')
const sshShutdown = willQuit.indexOf('beginSshShutdown()')
const killPty = willQuit.indexOf('killAllPty()')
const storeFlush = willQuit.indexOf('store?.flushAsync()')

expect(lifecycleBegin).toBeGreaterThanOrEqual(0)
expect(relayFence).toBeGreaterThan(lifecycleBegin)
expect(stageSessions).toBeGreaterThan(transferFence)
expect(sshShutdown).toBeGreaterThan(stageSessions)
expect(killPty).toBeGreaterThan(sshShutdown)
expect(storeFlush).toBeGreaterThan(killPty)
})

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Bound the terminalWindowQuitFence anchor.

transferFence is never asserted to be non-negative. If the anchor text disappears, indexOf returns -1 and line 318 becomes stageSessions > -1, which passes for any found position. The ordering assertion then no longer verifies that fencing precedes host staging. This matches the convention already stated in this file at lines 19 and 91-92.

💚 Proposed fix
     expect(lifecycleBegin).toBeGreaterThanOrEqual(0)
     expect(relayFence).toBeGreaterThan(lifecycleBegin)
+    expect(transferFence).toBeGreaterThanOrEqual(0)
     expect(stageSessions).toBeGreaterThan(transferFence)
📝 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.

Suggested change
it('uses the tested quit lifecycle before side effects and stages merged hosts before flush', () => {
const source = readFileSync(join(process.cwd(), 'src/main/index.ts'), 'utf8')
const beforeQuitStart = source.indexOf("app.on('before-quit'")
const willQuitStart = source.indexOf("app.on('will-quit'", beforeQuitStart)
const windowAllClosedStart = source.indexOf("app.on('window-all-closed'", willQuitStart)
const beforeQuit = source.slice(beforeQuitStart, willQuitStart)
const willQuit = source.slice(willQuitStart, windowAllClosedStart)
const lifecycleBegin = beforeQuit.indexOf('windowQuitLifecycle.begin()')
const relayFence = beforeQuit.indexOf('desktopRelayService?.fenceAndCloseNow()')
const transferFence = willQuit.indexOf('terminalWindowQuitFence')
const stageSessions = willQuit.indexOf('stageAllKnownHostsBeforeQuit()')
const sshShutdown = willQuit.indexOf('beginSshShutdown()')
const killPty = willQuit.indexOf('killAllPty()')
const storeFlush = willQuit.indexOf('store?.flushAsync()')
expect(lifecycleBegin).toBeGreaterThanOrEqual(0)
expect(relayFence).toBeGreaterThan(lifecycleBegin)
expect(stageSessions).toBeGreaterThan(transferFence)
expect(sshShutdown).toBeGreaterThan(stageSessions)
expect(killPty).toBeGreaterThan(sshShutdown)
expect(storeFlush).toBeGreaterThan(killPty)
})
it('uses the tested quit lifecycle before side effects and stages merged hosts before flush', () => {
const source = readFileSync(join(process.cwd(), 'src/main/index.ts'), 'utf8')
const beforeQuitStart = source.indexOf("app.on('before-quit'")
const willQuitStart = source.indexOf("app.on('will-quit'", beforeQuitStart)
const windowAllClosedStart = source.indexOf("app.on('window-all-closed'", willQuitStart)
const beforeQuit = source.slice(beforeQuitStart, willQuitStart)
const willQuit = source.slice(willQuitStart, windowAllClosedStart)
const lifecycleBegin = beforeQuit.indexOf('windowQuitLifecycle.begin()')
const relayFence = beforeQuit.indexOf('desktopRelayService?.fenceAndCloseNow()')
const transferFence = willQuit.indexOf('terminalWindowQuitFence')
const stageSessions = willQuit.indexOf('stageAllKnownHostsBeforeQuit()')
const sshShutdown = willQuit.indexOf('beginSshShutdown()')
const killPty = willQuit.indexOf('killAllPty()')
const storeFlush = willQuit.indexOf('store?.flushAsync()')
expect(lifecycleBegin).toBeGreaterThanOrEqual(0)
expect(relayFence).toBeGreaterThan(lifecycleBegin)
expect(transferFence).toBeGreaterThanOrEqual(0)
expect(stageSessions).toBeGreaterThan(transferFence)
expect(sshShutdown).toBeGreaterThan(stageSessions)
expect(killPty).toBeGreaterThan(sshShutdown)
expect(storeFlush).toBeGreaterThan(killPty)
})

Comment on lines +57 to +65
void pendingTransfers
.then(finishHandoff, () => false)
.then((completed) => {
if (completed) {
options.releaseTransferFence?.()
} else if (completed === false) {
options.onVacated()
}
})

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Finish the control transition when the transfer fence rejects.

Line 58 maps a rejected fenceAndSettleTransfers() to false, which skips finishHandoff entirely. finishControlTransition(transitionToken) is then never called, so the transition stays pending in OrcaWindowManager.

The test at Lines 68-70 shows that windows registered during a pending transition are assigned the secondary role and getControlWindow() stays null. If the fence rejects, no later window can become the control window, and the app keeps running without control services.

Run finishHandoff on both settlement paths so the token is always released.

🐛 Proposed fix
     void pendingTransfers
-      .then(finishHandoff, () => false)
+      .then(finishHandoff, finishHandoff)
       .then((completed) => {
📝 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.

Suggested change
void pendingTransfers
.then(finishHandoff, () => false)
.then((completed) => {
if (completed) {
options.releaseTransferFence?.()
} else if (completed === false) {
options.onVacated()
}
})
void pendingTransfers
.then(finishHandoff, finishHandoff)
.then((completed) => {
if (completed) {
options.releaseTransferFence?.()
} else if (completed === false) {
options.onVacated()
}
})

Comment on lines +337 to +349
for (const handler of ipcHandlers.get('window:confirm-close') ?? []) {
handler({ sender: second.instance.webContents })
}

expect(first.instance.close).not.toHaveBeenCalled()
expect(second.instance.close).toHaveBeenCalledOnce()

const secondConfirmHandler = ipcHandlers.get('window:confirm-close')?.[1]
second.windowHandlers.get('closed')?.forEach((handler) => handler())
expect(ipcMain.removeListener).toHaveBeenCalledWith(
'window:confirm-close',
secondConfirmHandler
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Assert event.returnValue in the multi-window confirm-close test.

The test passes a plain object with no returnValue property, so it cannot detect a non-owning listener overwriting the synchronous result. ipcMain runs every listener registered on window:confirm-close. Pass a mutable event object and assert the final returnValue is true for the owning window. This covers the root cause described in src/main/window/createMainWindow.ts lines 1190-1194.

💚 Proposed change
-    for (const handler of ipcHandlers.get('window:confirm-close') ?? []) {
-      handler({ sender: second.instance.webContents })
-    }
+    const confirmEvent = {
+      sender: second.instance.webContents,
+      returnValue: undefined as boolean | undefined
+    }
+    for (const handler of ipcHandlers.get('window:confirm-close') ?? []) {
+      handler(confirmEvent)
+    }
+    expect(confirmEvent.returnValue).toBe(true)
📝 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.

Suggested change
for (const handler of ipcHandlers.get('window:confirm-close') ?? []) {
handler({ sender: second.instance.webContents })
}
expect(first.instance.close).not.toHaveBeenCalled()
expect(second.instance.close).toHaveBeenCalledOnce()
const secondConfirmHandler = ipcHandlers.get('window:confirm-close')?.[1]
second.windowHandlers.get('closed')?.forEach((handler) => handler())
expect(ipcMain.removeListener).toHaveBeenCalledWith(
'window:confirm-close',
secondConfirmHandler
)
const confirmEvent = {
sender: second.instance.webContents,
returnValue: undefined as boolean | undefined
}
for (const handler of ipcHandlers.get('window:confirm-close') ?? []) {
handler(confirmEvent)
}
expect(confirmEvent.returnValue).toBe(true)
expect(first.instance.close).not.toHaveBeenCalled()
expect(second.instance.close).toHaveBeenCalledOnce()
const secondConfirmHandler = ipcHandlers.get('window:confirm-close')?.[1]
second.windowHandlers.get('closed')?.forEach((handler) => handler())
expect(ipcMain.removeListener).toHaveBeenCalledWith(
'window:confirm-close',
secondConfirmHandler
)

Comment on lines +1188 to 1212
const ownsSender = (event: Electron.IpcMainEvent): boolean =>
event.sender.id === rendererWebContentsId
const onConfirmClose = (event: Electron.IpcMainEvent): void => {
if (!ownsSender(event)) {
event.returnValue = false
return
}
clearQuitRendererAckTimer()
const isQuitting = opts?.getIsQuitting?.() ?? false
const canClose =
isQuitting ||
(windowCloseRequestActive &&
(!store || !getWindowSessionRegistry(store).hasWindowTerminalMembership(mainWindow.id)) &&
isPtyRendererCloseReady(mainWindow.webContents) &&
opts?.hasPendingTerminalTransferForWindow?.(mainWindow.id) !== true)
event.returnValue = canClose
if (!canClose) {
endWindowCloseTransaction()
return
}
windowCloseConfirmed = true
if (!mainWindow.isDestroyed()) {
mainWindow.close()
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Shared window:confirm-close sendSync channel lets a non-owning window overwrite the result. Every window registers a listener on the same channel. ipcMain runs all listeners for one sendSync call, and the last assignment to event.returnValue wins, so a non-owning listener can report false after the owning listener already approved the close.

  • src/main/window/createMainWindow.ts#L1188-L1212: in onConfirmClose, return without assigning event.returnValue when ownsSender(event) is false.
  • src/main/window/createMainWindow-multi-window.test.ts#L337-L349: pass a mutable event object to every registered window:confirm-close handler and assert the final returnValue is true for the owning window.
📍 Affects 2 files
  • src/main/window/createMainWindow.ts#L1188-L1212 (this comment)
  • src/main/window/createMainWindow-multi-window.test.ts#L337-L349

const store = useAppStore.getState()
const browserTarget = resolveBrowserSessionTabTarget(store, worktreeId, tabId)
if (browserTarget) {
if (ownsControlCloseRequests) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Do not key the whole IPC effect on ownsControlCloseRequests.

The effect body registers every renderer IPC subscription, not only the close-request listeners. Adding ownsControlCloseRequests to the dependency array makes the full effect tear down and re-run whenever ownership changes.

App.tsx derives the flag from terminalWindowContext?.role === 'control' && !terminalWindowContext.transitionFenced, so the flag flips during control-window promotion and during each transfer transition fence.

On each flip the cleanup at Lines 3972-4001 discards pendingAgentStatusEvents, liveAgentStatusBurstQueue, and pendingMobileStateEvents, then the re-run repeats startup hydration: ssh.listTargets, agentStatus.getSnapshot, runtime.getTerminalFitOverrides, and every runtime client-event subscription. Queued agent-status events for panes that had not yet hydrated are lost, and the window issues a burst of redundant IPC.

Move the two gated listener blocks into a separate useEffect keyed on ownsControlCloseRequests, and restore the main effect's empty dependency array.

♻️ Proposed structure
-export function useIpcEvents(ownsControlCloseRequests = true): void {
+export function useIpcEvents(ownsControlCloseRequests = true): void {
+  useEffect(() => {
+    if (!ownsControlCloseRequests) {
+      return
+    }
+    const unsubs: (() => void)[] = []
+    // move the onCloseSessionTab / onSessionTabCloseRequest / onCloseTerminal /
+    // onTerminalTabCloseRequest registrations here
+    return () => unsubs.forEach((fn) => fn())
+  }, [ownsControlCloseRequests])
+
   useEffect(() => {
-  }, [ownsControlCloseRequests])
+  }, [])
 }

Also applies to: 2163-2163, 4002-4002

Comment on lines +39 to +54
const otherTabIds = new Set(Object.keys(session.terminalLayoutsByTabId))
for (const tabs of Object.values(session.tabsByWorktree)) {
for (const tab of tabs) {
otherTabIds.add(tab.id)
}
}
otherTabIds.delete(tabId)
const otherPtyIds = new Set<string>()
for (const otherTabId of otherTabIds) {
for (const ptyId of collectWorkspaceSessionTerminalPtyIds(session, otherTabId)) {
otherPtyIds.add(ptyId)
}
}
const ptyIdsToKill = [...collectWorkspaceSessionTerminalPtyIds(session, tabId)].filter(
(ptyId) => !otherPtyIds.has(ptyId)
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Include every other terminal tab and its row PTY when computing otherPtyIds.

The "other tabs" set is built only from terminalLayoutsByTabId keys and tabsByWorktree rows, and collectWorkspaceSessionTerminalPtyIds is called without rowPtyId. Two PTYs can therefore be reported as killable while another tab still owns them:

  • A tab that exists only in unifiedTabs or only in remoteSessionIdsByTabId is not enumerated, so its remote session id is not protected.
  • A row tab whose ptyId is not mirrored in its layout is not protected, because tab.ptyId is never passed.

closeTerminalTabInWorkspaceSession passes tab.ptyId for the same computation (Line 162 of src/shared/workspace-session-terminal-tab-close.ts), so the two close paths disagree. The result is a live PTY placed in ptyIdsToKill.

Reuse collectWindowSessionTerminalTabIds for enumeration and track row PTYs.

🐛 Proposed fix
-  const otherTabIds = new Set(Object.keys(session.terminalLayoutsByTabId))
-  for (const tabs of Object.values(session.tabsByWorktree)) {
-    for (const tab of tabs) {
-      otherTabIds.add(tab.id)
-    }
-  }
-  otherTabIds.delete(tabId)
-  const otherPtyIds = new Set<string>()
-  for (const otherTabId of otherTabIds) {
-    for (const ptyId of collectWorkspaceSessionTerminalPtyIds(session, otherTabId)) {
-      otherPtyIds.add(ptyId)
-    }
-  }
+  const otherTabIds = collectWindowSessionTerminalTabIds(session)
+  otherTabIds.delete(tabId)
+  const rowPtyIdByTabId = new Map<string, string | null | undefined>()
+  for (const tabs of Object.values(session.tabsByWorktree)) {
+    for (const tab of tabs) {
+      rowPtyIdByTabId.set(tab.id, tab.ptyId)
+    }
+  }
+  const otherPtyIds = new Set<string>()
+  for (const otherTabId of otherTabIds) {
+    for (const ptyId of collectWorkspaceSessionTerminalPtyIds(
+      session,
+      otherTabId,
+      rowPtyIdByTabId.get(otherTabId)
+    )) {
+      otherPtyIds.add(ptyId)
+    }
+  }

Add the import:

 import type { WorkspaceSessionState } from './workspace-session-state-types'
+import { collectWindowSessionTerminalTabIds } from './window-session-terminal-membership'
📝 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.

Suggested change
const otherTabIds = new Set(Object.keys(session.terminalLayoutsByTabId))
for (const tabs of Object.values(session.tabsByWorktree)) {
for (const tab of tabs) {
otherTabIds.add(tab.id)
}
}
otherTabIds.delete(tabId)
const otherPtyIds = new Set<string>()
for (const otherTabId of otherTabIds) {
for (const ptyId of collectWorkspaceSessionTerminalPtyIds(session, otherTabId)) {
otherPtyIds.add(ptyId)
}
}
const ptyIdsToKill = [...collectWorkspaceSessionTerminalPtyIds(session, tabId)].filter(
(ptyId) => !otherPtyIds.has(ptyId)
)
import type { WorkspaceSessionState } from './workspace-session-state-types'
import { collectWindowSessionTerminalTabIds } from './window-session-terminal-membership'
Suggested change
const otherTabIds = new Set(Object.keys(session.terminalLayoutsByTabId))
for (const tabs of Object.values(session.tabsByWorktree)) {
for (const tab of tabs) {
otherTabIds.add(tab.id)
}
}
otherTabIds.delete(tabId)
const otherPtyIds = new Set<string>()
for (const otherTabId of otherTabIds) {
for (const ptyId of collectWorkspaceSessionTerminalPtyIds(session, otherTabId)) {
otherPtyIds.add(ptyId)
}
}
const ptyIdsToKill = [...collectWorkspaceSessionTerminalPtyIds(session, tabId)].filter(
(ptyId) => !otherPtyIds.has(ptyId)
)
const otherTabIds = collectWindowSessionTerminalTabIds(session)
otherTabIds.delete(tabId)
const rowPtyIdByTabId = new Map<string, string | null | undefined>()
for (const tabs of Object.values(session.tabsByWorktree)) {
for (const tab of tabs) {
rowPtyIdByTabId.set(tab.id, tab.ptyId)
}
}
const otherPtyIds = new Set<string>()
for (const otherTabId of otherTabIds) {
for (const ptyId of collectWorkspaceSessionTerminalPtyIds(
session,
otherTabId,
rowPtyIdByTabId.get(otherTabId)
)) {
otherPtyIds.add(ptyId)
}
}
const ptyIdsToKill = [...collectWorkspaceSessionTerminalPtyIds(session, tabId)].filter(
(ptyId) => !otherPtyIds.has(ptyId)
)

@nwparker

nwparker commented Oct 5, 2026

Copy link
Copy Markdown
Contributor

@DEOWL-kan This PR is pretty big

I like the idea 🙏 , but might take longer to get through

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants