From b39dff7adbf5fd5724a2ca7d24e4b71816295ad9 Mon Sep 17 00:00:00 2001 From: OrcaWin <293788423+OrcaWin@users.noreply.github.com> Date: Sun, 19 Jul 2026 22:54:20 -0700 Subject: [PATCH] fix(runtime): make remote terminal lifecycle host-owned Co-authored-by: Orca --- .../app/h/[hostId]/session/[worktreeId].tsx | 3 +- mobile/src/transport/protocol-compat.test.ts | 9 + mobile/src/transport/protocol-version.ts | 4 +- src/main/runtime/orca-runtime.test.ts | 1780 +++++++++++++---- src/main/runtime/orca-runtime.ts | 661 +++++- .../rpc/methods/session-tabs-schemas.ts | 6 + .../runtime/rpc/methods/session-tabs.test.ts | 27 + src/main/runtime/rpc/methods/session-tabs.ts | 3 +- .../window/attach-main-window-services.ts | 6 +- .../terminal-tab-close-request-relay.test.ts | 24 +- .../terminal-tab-close-request-relay.ts | 10 +- src/preload/api-types.ts | 7 +- src/preload/index.ts | 14 +- .../automation-target-availability.test.ts | 8 +- .../sidebar/sidebar-host-options.test.ts | 8 +- .../useTabGroupWorkspaceModel.focus.test.ts | 12 +- .../remote-runtime-pty-transport.test.ts | 10 +- .../remote-runtime-pty-transport.ts | 6 +- .../terminal/terminal-tab-actions.test.ts | 122 +- .../terminal/terminal-tab-actions.ts | 68 +- src/renderer/src/hooks/useIpcEvents.test.ts | 155 +- src/renderer/src/hooks/useIpcEvents.ts | 94 +- .../lib/windows-terminal-capabilities.test.ts | 12 +- .../src/runtime/runtime-rpc-call-error.ts | 19 + .../src/runtime/runtime-rpc-client.ts | 51 +- .../runtime-session-compatibility.test.ts | 137 ++ .../runtime/runtime-subscription-client.ts | 27 + .../src/runtime/sync-runtime-graph.test.ts | 56 + .../src/runtime/sync-runtime-graph.ts | 7 + .../src/runtime/web-runtime-session.test.ts | 210 +- .../src/runtime/web-runtime-session.ts | 245 +-- .../src/runtime/web-session-tabs-sync.ts | 256 ++- .../repos-project-host-capability.test.ts | 20 +- .../store/slices/terminal-tab-retirement.ts | 16 + src/shared/protocol-compat.test.ts | 30 + src/shared/protocol-version.ts | 10 +- .../terminal-layout-leaf-retirement.test.ts | 72 + src/shared/terminal-layout-leaf-retirement.ts | 86 + src/shared/terminal-tab-close.ts | 7 + ...e-session-terminal-leaf-retirement.test.ts | 95 + ...kspace-session-terminal-leaf-retirement.ts | 66 + .../workspace-session-terminal-tab-close.ts | 8 +- 42 files changed, 3647 insertions(+), 820 deletions(-) create mode 100644 src/renderer/src/runtime/runtime-rpc-call-error.ts create mode 100644 src/renderer/src/runtime/runtime-session-compatibility.test.ts create mode 100644 src/renderer/src/runtime/runtime-subscription-client.ts create mode 100644 src/shared/terminal-layout-leaf-retirement.test.ts create mode 100644 src/shared/terminal-layout-leaf-retirement.ts create mode 100644 src/shared/workspace-session-terminal-leaf-retirement.test.ts create mode 100644 src/shared/workspace-session-terminal-leaf-retirement.ts diff --git a/mobile/app/h/[hostId]/session/[worktreeId].tsx b/mobile/app/h/[hostId]/session/[worktreeId].tsx index bd361b93c630..099f109412cc 100644 --- a/mobile/app/h/[hostId]/session/[worktreeId].tsx +++ b/mobile/app/h/[hostId]/session/[worktreeId].tsx @@ -4099,7 +4099,8 @@ export default function SessionScreen() { try { const response = await client.sendRequest('session.tabs.close', { worktree: `id:${worktreeId}`, - tabId: tab.id + tabId: tab.id, + intent: 'user' }) if (response.ok) { if (tab.type === 'terminal' && typeof tab.terminal === 'string') { diff --git a/mobile/src/transport/protocol-compat.test.ts b/mobile/src/transport/protocol-compat.test.ts index d70ffd61bb1b..06e1cbe33455 100644 --- a/mobile/src/transport/protocol-compat.test.ts +++ b/mobile/src/transport/protocol-compat.test.ts @@ -2,6 +2,15 @@ import { describe, expect, it } from 'vitest' import { evaluateCompat } from './protocol-compat' describe('evaluateCompat', () => { + it('allows the current mobile app to connect to the ownership-fenced desktop', () => { + expect( + evaluateCompat({ + desktopProtocolVersion: 4, + desktopMinCompatibleMobileVersion: 4 + }) + ).toEqual({ kind: 'ok' }) + }) + it('allows the current mobile app to connect before a protocol-2 desktop updates', () => { expect( evaluateCompat({ diff --git a/mobile/src/transport/protocol-version.ts b/mobile/src/transport/protocol-version.ts index 8dc9229681f0..f0f8ab465a85 100644 --- a/mobile/src/transport/protocol-version.ts +++ b/mobile/src/transport/protocol-version.ts @@ -16,5 +16,7 @@ // server feature added at a specific runtime protocol version. This // triggers a hard-block screen for users paired to older servers. -export const MOBILE_PROTOCOL_VERSION = 3 +// Why: desktop protocol 4 fences clients that could confuse mirror teardown +// with explicit terminal close; mobile only sends close from explicit UI actions. +export const MOBILE_PROTOCOL_VERSION = 4 export const MIN_COMPATIBLE_DESKTOP_VERSION = 2 diff --git a/src/main/runtime/orca-runtime.test.ts b/src/main/runtime/orca-runtime.test.ts index 4939d056a466..eeea4aa5c631 100644 --- a/src/main/runtime/orca-runtime.test.ts +++ b/src/main/runtime/orca-runtime.test.ts @@ -12729,6 +12729,30 @@ describe('OrcaRuntimeService', () => { expect(revealTerminalSession).not.toHaveBeenCalled() }) + it('does not let an exited synthetic handle control a reused PTY id', async () => { + const kill = vi.fn(() => true) + const runtime = new OrcaRuntimeService(store) + runtime.setPtyController({ + spawn: vi.fn().mockResolvedValue({ id: 'pty-reused' }), + write: () => true, + kill, + getForegroundProcess: async () => null + }) + runtime.attachWindow(1) + runtime.syncWindowGraph(1, { tabs: [], leaves: [] }) + const first = await runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`) + runtime.onPtyExit('pty-reused', 0) + const replacement = await runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`) + + expect(replacement.handle).not.toBe(first.handle) + await expect(runtime.closeTerminal(first.handle)).rejects.toThrow('terminal_handle_stale') + await expect(runtime.closeTerminal(replacement.handle)).resolves.toMatchObject({ + handle: replacement.handle, + ptyKilled: true + }) + expect(kill).toHaveBeenCalledTimes(1) + }) + it('renames background terminal handles without requiring a visible tab', async () => { const runtime = new OrcaRuntimeService(store) runtime.setPtyController({ @@ -19421,19 +19445,212 @@ describe('OrcaRuntimeService', () => { expect(kill).toHaveBeenCalledWith('laptop-created-pty') }) - it('waits for renderer acknowledgement before returning a whole-tab close receipt', async () => { + it('rejects a stale whole-tab handle after the exact durable leaf rebinds', async () => { + const { runtimeStore, getSession } = makeRuntimeStoreWithWorkspaceSession( + makeWorkspaceSessionWithHeadlessTerminal() + ) + const spawn = vi + .fn() + .mockResolvedValueOnce({ id: 'serve-old' }) + .mockResolvedValueOnce({ id: 'serve-replacement' }) + const kill = vi.fn(() => true) + const runtime = new OrcaRuntimeService(runtimeStore as never) + runtime.setPtyController({ + spawn, + write: () => true, + kill, + getForegroundProcess: async () => null + }) + const first = await runtime.createTerminal(`id:${TEST_WORKTREE_ID}`, { + tabId: 'host-tab', + leafId: HEADLESS_LEAF_ID + }) + ;( + runtimeStore.persistPtyBinding as unknown as (args: { + worktreeId: string + tabId: string + leafId: string + ptyId: string + }) => void + )({ + worktreeId: TEST_WORKTREE_ID, + tabId: 'host-tab', + leafId: HEADLESS_LEAF_ID, + ptyId: 'serve-old' + }) + await runtime.closeTerminal(first.handle) + runtime.onPtyExit('serve-old', 0) + + const replacement = await runtime.createTerminal(`id:${TEST_WORKTREE_ID}`, { + tabId: 'host-tab', + leafId: HEADLESS_LEAF_ID + }) + ;(runtimeStore.setWorkspaceSession as unknown as (session: WorkspaceSessionState) => void)( + makeWorkspaceSessionWithHeadlessTerminal({ + tabsByWorktree: { + [TEST_WORKTREE_ID]: [ + { + id: 'host-tab', + ptyId: 'serve-replacement', + worktreeId: TEST_WORKTREE_ID, + title: 'Replacement Terminal', + customTitle: null, + color: null, + sortOrder: 0, + createdAt: 2 + } + ] + }, + terminalLayoutsByTabId: { + 'host-tab': makeHeadlessTerminalLayout({ + [HEADLESS_LEAF_ID]: 'serve-replacement' + }) + } + }) + ) + expect(replacement.handle).not.toBe(first.handle) + expect(getSession().terminalLayoutsByTabId['host-tab']?.ptyIdsByLeafId).toEqual({ + [HEADLESS_LEAF_ID]: 'serve-replacement' + }) + + await expect(runtime.closeTerminalTab(first.handle)).rejects.toThrow('terminal_handle_stale') + expect(kill).toHaveBeenCalledTimes(1) + await expect(runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`)).resolves.toMatchObject({ + tabs: [ + expect.objectContaining({ + parentTabId: 'host-tab', + leafId: HEADLESS_LEAF_ID, + status: 'ready', + terminal: replacement.handle + }) + ] + }) + + await expect(runtime.closeTerminalTab(replacement.handle)).resolves.toMatchObject({ + handle: replacement.handle, + tabId: 'host-tab', + closeMode: 'tab' + }) + expect(kill).toHaveBeenCalledTimes(2) + }) + + it('revalidates a whole-tab handle after process refresh before destructive commit', async () => { const { runtimeStore } = makeRuntimeStoreWithWorkspaceSession( makeWorkspaceSessionWithHeadlessTerminal() ) - const acknowledged = makeDeferred() - const closeTerminalTab = vi.fn(() => acknowledged.promise) + const spawn = vi + .fn() + .mockResolvedValueOnce({ id: 'serve-racing-old' }) + .mockResolvedValueOnce({ id: 'serve-racing-replacement' }) + const refreshStarted = makeDeferred() + let releaseRefresh: (processes: { id: string; cwd: string; title: string }[]) => void = () => { + throw new Error('refresh was not started') + } + let refreshCalls = 0 + const kill = vi.fn(() => true) const runtime = new OrcaRuntimeService(runtimeStore as never) - runtime.setNotifier({ closeTerminal: vi.fn(), closeTerminalTab } as never) runtime.setPtyController({ + spawn, write: () => true, - kill: () => true, + kill, getForegroundProcess: async () => null, - listProcesses: async () => [] + listProcesses: () => { + refreshCalls += 1 + if (refreshCalls > 1) { + return Promise.resolve([ + { id: 'serve-racing-replacement', cwd: TEST_WORKTREE_PATH, title: 'Replacement' } + ]) + } + return new Promise((resolve) => { + releaseRefresh = resolve + refreshStarted.resolve() + }) + } + }) + const first = await runtime.createTerminal(`id:${TEST_WORKTREE_ID}`, { + tabId: 'host-tab', + leafId: HEADLESS_LEAF_ID + }) + ;( + runtimeStore.persistPtyBinding as unknown as (args: { + worktreeId: string + tabId: string + leafId: string + ptyId: string + }) => void + )({ + worktreeId: TEST_WORKTREE_ID, + tabId: 'host-tab', + leafId: HEADLESS_LEAF_ID, + ptyId: 'serve-racing-old' + }) + + const pendingClose = runtime.closeTerminalTab(first.handle) + await refreshStarted.promise + runtime.onPtyExit('serve-racing-old', 0) + const replacement = await runtime.createTerminal(`id:${TEST_WORKTREE_ID}`, { + tabId: 'host-tab', + leafId: HEADLESS_LEAF_ID + }) + ;(runtimeStore.setWorkspaceSession as unknown as (session: WorkspaceSessionState) => void)( + makeWorkspaceSessionWithHeadlessTerminal({ + tabsByWorktree: { + [TEST_WORKTREE_ID]: [ + { + id: 'host-tab', + ptyId: 'serve-racing-replacement', + worktreeId: TEST_WORKTREE_ID, + title: 'Racing Replacement', + customTitle: null, + color: null, + sortOrder: 0, + createdAt: 2 + } + ] + }, + terminalLayoutsByTabId: { + 'host-tab': makeHeadlessTerminalLayout({ + [HEADLESS_LEAF_ID]: 'serve-racing-replacement' + }) + } + }) + ) + releaseRefresh([ + { id: 'serve-racing-replacement', cwd: TEST_WORKTREE_PATH, title: 'Replacement' } + ]) + + await expect(pendingClose).rejects.toThrow('terminal_handle_stale') + expect(kill).not.toHaveBeenCalled() + await expect(runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`)).resolves.toMatchObject({ + tabs: [ + expect.objectContaining({ + status: 'ready', + terminal: replacement.handle + }) + ] + }) + }) + + it('tears down a generation-checked whole tab after renderer validation', async () => { + const { runtimeStore, getSession } = makeRuntimeStoreWithWorkspaceSession( + makeWorkspaceSessionWithHeadlessTerminal() + ) + const closeTerminal = vi.fn() + const closeTerminalTab = vi.fn( + async (_tabId: string, options?: { validateOnly?: boolean; expectedPtyIds?: string[] }) => { + expect(options).toEqual({ validateOnly: true, expectedPtyIds: ['persisted-pty'] }) + } + ) + const kill = vi.fn(() => true) + const runtime = new OrcaRuntimeService(runtimeStore as never) + runtime.setNotifier({ closeTerminal, closeTerminalTab } as never) + runtime.setPtyController({ + write: () => true, + kill, + getForegroundProcess: async () => null, + listProcesses: async () => [ + { id: 'persisted-pty', cwd: TEST_WORKTREE_PATH, title: 'Durable' } + ] }) runtime.syncWindowGraph(1, { tabs: [ @@ -19453,231 +19670,612 @@ describe('OrcaRuntimeService', () => { paneRuntimeId: 1, ptyId: 'persisted-pty' } + ], + mobileSessionTabs: [ + { + worktree: TEST_WORKTREE_ID, + publicationEpoch: 'renderer-stale-close-snapshot', + snapshotVersion: 1, + activeGroupId: 'group-1', + activeTabId: `host-tab::${HEADLESS_LEAF_ID}`, + activeTabType: 'terminal', + tabGroups: [{ id: 'group-1', activeTabId: 'host-tab', tabOrder: ['host-tab'] }], + tabs: [ + { + type: 'terminal', + id: `host-tab::${HEADLESS_LEAF_ID}`, + title: 'Stale renderer snapshot', + parentTabId: 'host-tab', + leafId: HEADLESS_LEAF_ID, + ptyId: 'stale-snapshot-pty', + isActive: true + } + ] + } ] }) - const [terminal] = (await runtime.listTerminals()).terminals - const pending = runtime.closeTerminalTab(terminal.handle) - let settled = false - void pending.finally(() => { - settled = true - }) - - await vi.waitFor(() => expect(closeTerminalTab).toHaveBeenCalledWith('host-tab')) - expect(settled).toBe(false) - - acknowledged.resolve() - await expect(pending).resolves.toEqual({ - handle: terminal.handle, + const sessionTabs = await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`) + const terminal = sessionTabs.tabs.find( + (tab) => tab.type === 'terminal' && tab.status === 'ready' + ) + expect(terminal?.type === 'terminal' && terminal.terminal).toBeTruthy() + const terminalHandle = terminal?.type === 'terminal' ? terminal.terminal : null + await expect(runtime.closeTerminalTab(terminalHandle!)).resolves.toEqual({ + handle: terminalHandle, tabId: 'host-tab', closeMode: 'tab', ptyKilled: false }) + expect(closeTerminalTab).toHaveBeenCalledWith('host-tab', { + validateOnly: true, + expectedPtyIds: ['persisted-pty'] + }) + expect(kill).toHaveBeenCalledWith('persisted-pty') + expect(getSession().tabsByWorktree[TEST_WORKTREE_ID]).toEqual([]) + expect(closeTerminal).toHaveBeenCalledWith('host-tab', undefined, { + mirrorOnly: true, + expectedPtyIds: ['persisted-pty'] + }) }) - it('durably closes every split leaf without a renderer', async () => { + it('does not kill a PTY that another durable terminal tab still owns', async () => { + const sharedPtyId = 'ssh:ssh-1@@shared-live-pty' const { runtimeStore, getSession } = makeRuntimeStoreWithWorkspaceSession( makeWorkspaceSessionWithHeadlessTerminal({ tabsByWorktree: { [TEST_WORKTREE_ID]: [ { - id: 'durable-tab', - ptyId: null, + id: 'host-tab', + ptyId: sharedPtyId, worktreeId: TEST_WORKTREE_ID, - title: 'Durable', + title: 'Target', customTitle: null, color: null, sortOrder: 0, createdAt: 1 + }, + { + id: 'sibling-tab', + ptyId: sharedPtyId, + worktreeId: TEST_WORKTREE_ID, + title: 'Sibling owner', + customTitle: null, + color: null, + sortOrder: 1, + createdAt: 2 } ] }, terminalLayoutsByTabId: { - 'durable-tab': makeHeadlessTerminalLayout({ [HEADLESS_LEAF_ID]: undefined }) + 'host-tab': makeHeadlessTerminalLayout({ [HEADLESS_LEAF_ID]: sharedPtyId }), + 'sibling-tab': makeHeadlessTerminalLayout({ + [HEADLESS_SECOND_LEAF_ID]: sharedPtyId + }) } }) ) - const flushOrThrow = vi.fn() - const spawn = vi - .fn() - .mockResolvedValueOnce({ id: 'headless-left' }) - .mockResolvedValueOnce({ id: 'headless-right' }) const kill = vi.fn(() => true) - const runtime = new OrcaRuntimeService({ ...runtimeStore, flushOrThrow } as never) + const closeTerminal = vi.fn() + const closeTerminalTab = vi.fn() + const runtime = new OrcaRuntimeService(runtimeStore as never) + runtime.setNotifier({ closeTerminal, closeTerminalTab } as never) runtime.setPtyController({ - spawn, write: () => true, kill, - getForegroundProcess: async () => null + getForegroundProcess: async () => null, + listProcesses: async () => [{ id: sharedPtyId, cwd: TEST_WORKTREE_PATH, title: 'Shared' }] }) - runtime.syncWindowGraph(0, { tabs: [], leaves: [] }) - const terminal = await runtime.createTerminal(`id:${TEST_WORKTREE_ID}`, { - tabId: 'durable-tab', - leafId: HEADLESS_LEAF_ID + runtime.syncWindowGraph(1, { + tabs: [ + { + tabId: 'host-tab', + worktreeId: TEST_WORKTREE_ID, + title: 'Target', + activeLeafId: HEADLESS_LEAF_ID, + layout: null + } + ], + leaves: [ + { + tabId: 'host-tab', + worktreeId: TEST_WORKTREE_ID, + leafId: HEADLESS_LEAF_ID, + paneRuntimeId: 1, + ptyId: sharedPtyId + } + ] }) - await runtime.splitTerminal(terminal.handle, { direction: 'vertical' }) - - await runtime.closeTerminalTab(terminal.handle) - - expect(kill).toHaveBeenCalledWith('headless-left') - expect(kill).toHaveBeenCalledWith('headless-right') - expect(getSession().tabsByWorktree[TEST_WORKTREE_ID]).toEqual([]) - expect(getSession().terminalLayoutsByTabId['durable-tab']).toBeUndefined() - expect(flushOrThrow).toHaveBeenCalledTimes(1) - }) + const listed = await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`) + const terminal = listed.tabs.find( + (tab) => tab.type === 'terminal' && tab.parentTabId === 'host-tab' + ) + const handle = terminal?.type === 'terminal' ? terminal.terminal : null - it('lists PTY-backed mobile session terminals without a renderer graph', async () => { - const spawn = vi.fn().mockResolvedValue({ id: 'laptop-created-pty' }) - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - spawn, - write: () => true, - kill: () => true, - getForegroundProcess: async () => null + await expect(runtime.closeTerminalTab(handle!)).resolves.toMatchObject({ + handle, + tabId: 'host-tab', + closeMode: 'tab' }) - const laptopTerminal = await runtime.createTerminal(`id:${TEST_WORKTREE_ID}`, { - tabId: 'laptop-tab', - leafId: HEADLESS_LEAF_ID + expect(closeTerminalTab).toHaveBeenCalledWith('host-tab', { + validateOnly: true, + expectedPtyIds: [sharedPtyId] }) - runtime.onPtyData('laptop-created-pty', '\x1b]0;Claude working\x07hello\r\n', 123) + expect(kill).not.toHaveBeenCalled() + expect(getSession().tabsByWorktree[TEST_WORKTREE_ID]).toEqual([ + expect.objectContaining({ id: 'sibling-tab', ptyId: sharedPtyId }) + ]) + expect(getSession().terminalLayoutsByTabId['sibling-tab']).toBeDefined() + }) - await expect(runtime.listTerminals(`id:${TEST_WORKTREE_ID}`)).resolves.toMatchObject({ - terminals: [ - expect.objectContaining({ - handle: laptopTerminal.handle, - worktreeId: TEST_WORKTREE_ID, - title: 'Claude working', - connected: true, - preview: 'hello' - }) - ], - totalCount: 1, - truncated: false - }) - }) - - it('shows and resolves active PTY-backed mobile session terminals without a renderer graph', async () => { - const spawn = vi.fn().mockResolvedValue({ id: 'laptop-created-pty' }) - const runtime = new OrcaRuntimeService(store) + it('does not kill a shared SSH PTY owned by a snapshot-only sibling', async () => { + const sharedPtyId = 'ssh:ssh-1@@snapshot-shared-pty' + const { runtimeStore } = makeRuntimeStoreWithWorkspaceSession( + makeWorkspaceSessionWithHeadlessTerminal({ + tabsByWorktree: { + [TEST_WORKTREE_ID]: [ + { + id: 'host-tab', + ptyId: sharedPtyId, + worktreeId: TEST_WORKTREE_ID, + title: 'Persisted target', + customTitle: null, + color: null, + sortOrder: 0, + createdAt: 1 + } + ] + }, + terminalLayoutsByTabId: { + 'host-tab': makeHeadlessTerminalLayout({ [HEADLESS_LEAF_ID]: sharedPtyId }) + } + }) + ) + const kill = vi.fn(() => true) + const runtime = new OrcaRuntimeService(runtimeStore as never) + runtime.setNotifier({ closeTerminal: vi.fn(), closeTerminalTab: vi.fn() } as never) runtime.setPtyController({ - spawn, write: () => true, - kill: () => true, - getForegroundProcess: async () => null - }) - - const laptopTerminal = await runtime.createTerminal(`id:${TEST_WORKTREE_ID}`, { - tabId: 'laptop-tab', - leafId: HEADLESS_LEAF_ID, - activate: true - }) - runtime.onPtyData('laptop-created-pty', '\x1b]0;Claude working\x07hello\r\n', 123) - - await expect(runtime.resolveActiveTerminal(`id:${TEST_WORKTREE_ID}`)).resolves.toBe( - laptopTerminal.handle - ) - await expect(runtime.showTerminal(laptopTerminal.handle)).resolves.toMatchObject({ - handle: laptopTerminal.handle, - tabId: 'laptop-tab', - leafId: HEADLESS_LEAF_ID, - worktreeId: TEST_WORKTREE_ID, - title: 'Claude working', - connected: true, - ptyId: 'laptop-created-pty' + kill, + getForegroundProcess: async () => null, + listProcesses: async () => [{ id: sharedPtyId, cwd: TEST_WORKTREE_PATH, title: 'Shared SSH' }] }) - }) - - it('keeps split sibling headless mobile terminal leaves when a desktop renderer omits them', async () => { - const runtime = new OrcaRuntimeService(store) - runtime.syncWindowGraph(0, { - tabs: [], - leaves: [], + runtime.syncWindowGraph(1, { + tabs: [ + { + tabId: 'host-tab', + worktreeId: TEST_WORKTREE_ID, + title: 'Persisted target', + activeLeafId: HEADLESS_LEAF_ID, + layout: null + } + ], + leaves: [ + { + tabId: 'host-tab', + worktreeId: TEST_WORKTREE_ID, + leafId: HEADLESS_LEAF_ID, + paneRuntimeId: 1, + ptyId: sharedPtyId + } + ], mobileSessionTabs: [ { worktree: TEST_WORKTREE_ID, - publicationEpoch: 'headless:split-siblings', + publicationEpoch: 'renderer-snapshot-only-shared-ssh', snapshotVersion: 1, - activeGroupId: 'headless-group', - activeTabId: 'host-tab::pane:2', + activeGroupId: 'group-1', + activeTabId: `host-tab::${HEADLESS_LEAF_ID}`, activeTabType: 'terminal', tabGroups: [ { - id: 'headless-group', + id: 'group-1', activeTabId: 'host-tab', - tabOrder: ['host-tab'] + tabOrder: ['host-tab', 'snapshot-sibling'] } ], tabs: [ { type: 'terminal', - id: 'host-tab::pane:1', + id: `host-tab::${HEADLESS_LEAF_ID}`, + title: 'Persisted target', parentTabId: 'host-tab', - leafId: 'pane:1', - title: 'left', - isActive: false + leafId: HEADLESS_LEAF_ID, + ptyId: sharedPtyId, + isActive: true }, { type: 'terminal', - id: 'host-tab::pane:2', - parentTabId: 'host-tab', - leafId: 'pane:2', - title: 'right', - isActive: true + id: `snapshot-sibling::${HEADLESS_SECOND_LEAF_ID}`, + title: 'Snapshot-only sibling', + parentTabId: 'snapshot-sibling', + leafId: HEADLESS_SECOND_LEAF_ID, + ptyId: sharedPtyId, + isActive: false } ] } ] }) + const listed = await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`) + const target = listed.tabs.find( + (tab) => tab.type === 'terminal' && tab.parentTabId === 'host-tab' + ) + const handle = target?.type === 'terminal' ? target.terminal : null - runtime.syncWindowGraph(0, { - tabs: [], - leaves: [], - mobileSessionTabs: [ + await runtime.closeTerminalTab(handle!) + + expect(kill).not.toHaveBeenCalled() + await expect(runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`)).resolves.toMatchObject({ + tabs: [expect.objectContaining({ parentTabId: 'snapshot-sibling' })] + }) + }) + + it('revalidates a same-id PTY generation after renderer validation', async () => { + const { runtimeStore } = makeRuntimeStoreWithWorkspaceSession( + makeWorkspaceSessionWithHeadlessTerminal() + ) + const closeRequested = makeDeferred() + const closeAcknowledged = makeDeferred() + const closeTerminalTab = vi.fn(async () => { + closeRequested.resolve() + await closeAcknowledged.promise + }) + const kill = vi.fn(() => true) + const runtime = new OrcaRuntimeService(runtimeStore as never) + runtime.setNotifier({ closeTerminal: vi.fn(), closeTerminalTab } as never) + runtime.setPtyController({ + write: () => true, + kill, + getForegroundProcess: async () => null, + listProcesses: async () => [ + { id: 'persisted-pty', cwd: TEST_WORKTREE_PATH, title: 'Current generation' } + ] + }) + runtime.syncWindowGraph(1, { + tabs: [ { - worktree: TEST_WORKTREE_ID, - publicationEpoch: 'renderer-empty', - snapshotVersion: 2, - activeGroupId: null, - activeTabId: null, - activeTabType: null, - tabs: [] + tabId: 'host-tab', + worktreeId: TEST_WORKTREE_ID, + title: 'Durable', + activeLeafId: HEADLESS_LEAF_ID, + layout: null + } + ], + leaves: [ + { + tabId: 'host-tab', + worktreeId: TEST_WORKTREE_ID, + leafId: HEADLESS_LEAF_ID, + paneRuntimeId: 1, + ptyId: 'persisted-pty' } ] }) + const sessionTabs = await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`) + const terminal = sessionTabs.tabs.find( + (tab) => tab.type === 'terminal' && tab.status === 'ready' + ) + const terminalHandle = terminal?.type === 'terminal' ? terminal.terminal : null - const listed = await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`) - - expect(listed.tabs).toEqual([ - expect.objectContaining({ - type: 'terminal', - id: 'host-tab::pane:1', - parentTabId: 'host-tab', - leafId: 'pane:1' - }), - expect.objectContaining({ - type: 'terminal', - id: 'host-tab::pane:2', - parentTabId: 'host-tab', - leafId: 'pane:2' + const pendingClose = runtime.closeTerminalTab(terminalHandle!) + await closeRequested.promise + runtime.onPtyExit('persisted-pty', 0) + ;(runtimeStore.setWorkspaceSession as (session: WorkspaceSessionState) => void)( + makeWorkspaceSessionWithHeadlessTerminal({ + tabsByWorktree: { + [TEST_WORKTREE_ID]: [ + { + id: 'host-tab', + ptyId: 'persisted-pty', + worktreeId: TEST_WORKTREE_ID, + title: 'Replacement generation', + customTitle: null, + color: null, + sortOrder: 0, + createdAt: 2 + } + ] + }, + terminalLayoutsByTabId: { + 'host-tab': makeHeadlessTerminalLayout({ [HEADLESS_LEAF_ID]: 'persisted-pty' }) + } }) - ]) - expect(listed.activeTabId).toBe('host-tab::pane:2') + ) + runtime.registerPty('persisted-pty', TEST_WORKTREE_ID, null, { + tabId: 'host-tab', + leafId: HEADLESS_LEAF_ID + }) + runtime.syncWindowGraph(1, { + tabs: [ + { + tabId: 'host-tab', + worktreeId: TEST_WORKTREE_ID, + title: 'Replacement generation', + activeLeafId: HEADLESS_LEAF_ID, + layout: null + } + ], + leaves: [ + { + tabId: 'host-tab', + worktreeId: TEST_WORKTREE_ID, + leafId: HEADLESS_LEAF_ID, + paneRuntimeId: 2, + ptyId: 'persisted-pty' + } + ] + }) + closeAcknowledged.resolve() + + await expect(pendingClose).rejects.toThrow('terminal_handle_stale') + expect(kill).not.toHaveBeenCalled() + expect( + (runtimeStore.getWorkspaceSession as () => WorkspaceSessionState)().tabsByWorktree[ + TEST_WORKTREE_ID + ] + ).toEqual([expect.objectContaining({ id: 'host-tab', title: 'Replacement generation' })]) }) - it('keeps a headless tab-group split alive when a new tab is created', async () => { - // Regression: drag-to-split-group was client-only and the headless host rejected it, coalescing groups on new-tab; the host must model + persist the split. - let ptyCounter = 0 - const runtime = new OrcaRuntimeService(store) + it('durably closes every split leaf without a renderer', async () => { + const { runtimeStore, getSession } = makeRuntimeStoreWithWorkspaceSession( + makeWorkspaceSessionWithHeadlessTerminal({ + tabsByWorktree: { + [TEST_WORKTREE_ID]: [ + { + id: 'durable-tab', + ptyId: null, + worktreeId: TEST_WORKTREE_ID, + title: 'Durable', + customTitle: null, + color: null, + sortOrder: 0, + createdAt: 1 + } + ] + }, + terminalLayoutsByTabId: { + 'durable-tab': makeHeadlessTerminalLayout({ [HEADLESS_LEAF_ID]: undefined }) + } + }) + ) + const flushOrThrow = vi.fn() + const spawn = vi + .fn() + .mockResolvedValueOnce({ id: 'headless-left' }) + .mockResolvedValueOnce({ id: 'headless-right' }) + const kill = vi.fn(() => true) + const runtime = new OrcaRuntimeService({ ...runtimeStore, flushOrThrow } as never) runtime.setPtyController({ - spawn: vi.fn(async () => ({ id: `split-group-pty-${++ptyCounter}` })), + spawn, write: () => true, - kill: () => true, - getForegroundProcess: async () => null + kill, + getForegroundProcess: async () => null, + listProcesses: async () => [ + { id: 'headless-left', cwd: TEST_WORKTREE_PATH, title: 'Left' }, + { id: 'headless-right', cwd: TEST_WORKTREE_PATH, title: 'Right' } + ] }) - - const first = await runtime.createTerminal(`id:${TEST_WORKTREE_ID}`, { activate: true }) - const second = await runtime.createTerminal(`id:${TEST_WORKTREE_ID}`, { activate: true }) - + runtime.syncWindowGraph(0, { tabs: [], leaves: [] }) + const terminal = await runtime.createTerminal(`id:${TEST_WORKTREE_ID}`, { + tabId: 'durable-tab', + leafId: HEADLESS_LEAF_ID + }) + await runtime.splitTerminal(terminal.handle, { direction: 'vertical' }) + + await runtime.closeTerminalTab(terminal.handle) + + expect(kill).toHaveBeenCalledWith('headless-left') + expect(kill).toHaveBeenCalledWith('headless-right') + expect(getSession().tabsByWorktree[TEST_WORKTREE_ID]).toEqual([]) + expect(getSession().terminalLayoutsByTabId['durable-tab']).toBeUndefined() + expect(flushOrThrow).toHaveBeenCalledTimes(1) + }) + + it('restores headless session state and leaves the PTY alive when persistence fails', async () => { + const { runtimeStore, getSession } = makeRuntimeStoreWithWorkspaceSession( + makeWorkspaceSessionWithHeadlessTerminal({ + tabsByWorktree: { + [TEST_WORKTREE_ID]: [ + { + id: 'durable-tab', + ptyId: null, + worktreeId: TEST_WORKTREE_ID, + title: 'Durable', + customTitle: null, + color: null, + sortOrder: 0, + createdAt: 1 + } + ] + }, + terminalLayoutsByTabId: { + 'durable-tab': makeHeadlessTerminalLayout({ [HEADLESS_LEAF_ID]: undefined }) + } + }) + ) + const flushError = new Error('disk full') + const flushOrThrow = vi.fn(() => { + throw flushError + }) + const kill = vi.fn(() => true) + const runtime = new OrcaRuntimeService({ ...runtimeStore, flushOrThrow } as never) + runtime.setPtyController({ + spawn: vi.fn().mockResolvedValue({ id: 'headless-live' }), + write: () => true, + kill, + getForegroundProcess: async () => null, + listProcesses: async () => [ + { id: 'headless-live', cwd: TEST_WORKTREE_PATH, title: 'Durable' } + ] + }) + runtime.syncWindowGraph(0, { tabs: [], leaves: [] }) + const terminal = await runtime.createTerminal(`id:${TEST_WORKTREE_ID}`, { + tabId: 'durable-tab', + leafId: HEADLESS_LEAF_ID + }) + const sessionBeforeClose = getSession() + + await expect(runtime.closeTerminalTab(terminal.handle)).rejects.toThrow(flushError) + + expect(flushOrThrow).toHaveBeenCalledTimes(1) + expect(kill).not.toHaveBeenCalled() + expect(getSession()).toEqual(sessionBeforeClose) + }) + + it('lists PTY-backed mobile session terminals without a renderer graph', async () => { + const spawn = vi.fn().mockResolvedValue({ id: 'laptop-created-pty' }) + const runtime = new OrcaRuntimeService(store) + runtime.setPtyController({ + spawn, + write: () => true, + kill: () => true, + getForegroundProcess: async () => null + }) + + const laptopTerminal = await runtime.createTerminal(`id:${TEST_WORKTREE_ID}`, { + tabId: 'laptop-tab', + leafId: HEADLESS_LEAF_ID + }) + runtime.onPtyData('laptop-created-pty', '\x1b]0;Claude working\x07hello\r\n', 123) + + await expect(runtime.listTerminals(`id:${TEST_WORKTREE_ID}`)).resolves.toMatchObject({ + terminals: [ + expect.objectContaining({ + handle: laptopTerminal.handle, + worktreeId: TEST_WORKTREE_ID, + title: 'Claude working', + connected: true, + preview: 'hello' + }) + ], + totalCount: 1, + truncated: false + }) + }) + + it('shows and resolves active PTY-backed mobile session terminals without a renderer graph', async () => { + const spawn = vi.fn().mockResolvedValue({ id: 'laptop-created-pty' }) + const runtime = new OrcaRuntimeService(store) + runtime.setPtyController({ + spawn, + write: () => true, + kill: () => true, + getForegroundProcess: async () => null + }) + + const laptopTerminal = await runtime.createTerminal(`id:${TEST_WORKTREE_ID}`, { + tabId: 'laptop-tab', + leafId: HEADLESS_LEAF_ID, + activate: true + }) + runtime.onPtyData('laptop-created-pty', '\x1b]0;Claude working\x07hello\r\n', 123) + + await expect(runtime.resolveActiveTerminal(`id:${TEST_WORKTREE_ID}`)).resolves.toBe( + laptopTerminal.handle + ) + await expect(runtime.showTerminal(laptopTerminal.handle)).resolves.toMatchObject({ + handle: laptopTerminal.handle, + tabId: 'laptop-tab', + leafId: HEADLESS_LEAF_ID, + worktreeId: TEST_WORKTREE_ID, + title: 'Claude working', + connected: true, + ptyId: 'laptop-created-pty' + }) + }) + + it('keeps split sibling headless mobile terminal leaves when a desktop renderer omits them', async () => { + const runtime = new OrcaRuntimeService(store) + runtime.syncWindowGraph(0, { + tabs: [], + leaves: [], + mobileSessionTabs: [ + { + worktree: TEST_WORKTREE_ID, + publicationEpoch: 'headless:split-siblings', + snapshotVersion: 1, + activeGroupId: 'headless-group', + activeTabId: 'host-tab::pane:2', + activeTabType: 'terminal', + tabGroups: [ + { + id: 'headless-group', + activeTabId: 'host-tab', + tabOrder: ['host-tab'] + } + ], + tabs: [ + { + type: 'terminal', + id: 'host-tab::pane:1', + parentTabId: 'host-tab', + leafId: 'pane:1', + title: 'left', + isActive: false + }, + { + type: 'terminal', + id: 'host-tab::pane:2', + parentTabId: 'host-tab', + leafId: 'pane:2', + title: 'right', + isActive: true + } + ] + } + ] + }) + + runtime.syncWindowGraph(0, { + tabs: [], + leaves: [], + mobileSessionTabs: [ + { + worktree: TEST_WORKTREE_ID, + publicationEpoch: 'renderer-empty', + snapshotVersion: 2, + activeGroupId: null, + activeTabId: null, + activeTabType: null, + tabs: [] + } + ] + }) + + const listed = await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`) + + expect(listed.tabs).toEqual([ + expect.objectContaining({ + type: 'terminal', + id: 'host-tab::pane:1', + parentTabId: 'host-tab', + leafId: 'pane:1' + }), + expect.objectContaining({ + type: 'terminal', + id: 'host-tab::pane:2', + parentTabId: 'host-tab', + leafId: 'pane:2' + }) + ]) + expect(listed.activeTabId).toBe('host-tab::pane:2') + }) + + it('keeps a headless tab-group split alive when a new tab is created', async () => { + // Regression: drag-to-split-group was client-only and the headless host rejected it, coalescing groups on new-tab; the host must model + persist the split. + let ptyCounter = 0 + const runtime = new OrcaRuntimeService(store) + runtime.setPtyController({ + spawn: vi.fn(async () => ({ id: `split-group-pty-${++ptyCounter}` })), + write: () => true, + kill: () => true, + getForegroundProcess: async () => null + }) + + const first = await runtime.createTerminal(`id:${TEST_WORKTREE_ID}`, { activate: true }) + const second = await runtime.createTerminal(`id:${TEST_WORKTREE_ID}`, { activate: true }) + const beforeSplit = await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`) expect(beforeSplit.tabGroups).toHaveLength(1) const sourceGroupId = beforeSplit.tabGroups![0]!.id @@ -20733,7 +21331,10 @@ describe('OrcaRuntimeService', () => { expect(closeTerminalTab).not.toHaveBeenCalled() expect(kill).toHaveBeenCalledWith(persistedPtyId) - expect(closeTerminal).toHaveBeenCalledWith('host-tab') + expect(closeTerminal).toHaveBeenCalledWith('host-tab', undefined, { + mirrorOnly: true, + expectedPtyIds: [] + }) expect(flushOrThrow).toHaveBeenCalledTimes(1) expect(warn).toHaveBeenCalledWith( '[runtime] failed to notify renderer after headless terminal close', @@ -20813,56 +21414,154 @@ describe('OrcaRuntimeService', () => { expect(getSession().terminalLayoutsByTabId['host-tab']).toBeDefined() }) - it('materializes hydrated pending headless terminals with the persisted session identity', async () => { - const { runtimeStore } = makeRuntimeStoreWithWorkspaceSession( - makeWorkspaceSessionWithHeadlessTerminal() - ) - const spawn = vi.fn().mockResolvedValue({ id: 'persisted-pty' }) - const runtime = new OrcaRuntimeService(runtimeStore as never) - runtime.setPtyController({ - spawn, - write: () => true, - kill: () => true, - getForegroundProcess: async () => null, - listProcesses: async () => [] - }) - runtime.syncWindowGraph(0, { tabs: [], leaves: [] }) - - const activated = await runtime.activateMobileSessionTab(`id:${TEST_WORKTREE_ID}`, 'host-tab') - - expect(spawn).toHaveBeenCalledWith( - expect.objectContaining({ - tabId: 'host-tab', - leafId: HEADLESS_LEAF_ID, - sessionId: 'persisted-pty', - persistHostSessionBinding: true, - worktreeId: TEST_WORKTREE_ID - }) - ) - expect(activated.tabs[0]).toMatchObject({ - type: 'terminal', - parentTabId: 'host-tab', - leafId: HEADLESS_LEAF_ID, - status: 'ready', - terminal: expect.stringMatching(/^term_/) - }) - }) - - it('reattaches hydrated SSH headless terminals with the persisted relay identity', async () => { - const { runtimeStore } = makeRuntimeStoreWithWorkspaceSession( + it('rejects when the live renderer transaction reports pinned despite a stale snapshot', async () => { + const servePtyId = 'serve-live-pinned' + const { runtimeStore, getSession } = makeRuntimeStoreWithWorkspaceSession( makeWorkspaceSessionWithHeadlessTerminal({ tabsByWorktree: { [TEST_WORKTREE_ID]: [ { id: 'host-tab', - ptyId: 'ssh:ssh-1@@relay-pty', + ptyId: servePtyId, worktreeId: TEST_WORKTREE_ID, - title: 'Remote Terminal', + title: 'Pinned live terminal', customTitle: null, color: null, sortOrder: 0, - createdAt: 1 - } + createdAt: 1, + isPinned: false + } + ] + }, + terminalLayoutsByTabId: { + 'host-tab': makeHeadlessTerminalLayout({ [HEADLESS_LEAF_ID]: servePtyId }) + } + }) + ) + const kill = vi.fn(() => true) + const closeTerminal = vi.fn() + const closeTerminalTab = vi.fn(async () => { + throw new Error('terminal_tab_pinned') + }) + const runtime = new OrcaRuntimeService(runtimeStore as never) + runtime.setPtyController({ + write: () => true, + kill, + getForegroundProcess: async () => null, + listProcesses: async () => [{ id: servePtyId, cwd: TEST_WORKTREE_PATH, title: 'Pinned' }] + }) + runtime.setNotifier({ closeTerminal, closeTerminalTab } as never) + runtime.syncWindowGraph(1, { + tabs: [ + { + tabId: 'host-tab', + worktreeId: TEST_WORKTREE_ID, + title: 'Pinned live terminal', + activeLeafId: HEADLESS_LEAF_ID, + layout: null + } + ], + leaves: [ + { + tabId: 'host-tab', + worktreeId: TEST_WORKTREE_ID, + leafId: HEADLESS_LEAF_ID, + paneRuntimeId: 1, + ptyId: servePtyId + } + ], + mobileSessionTabs: [ + { + worktree: TEST_WORKTREE_ID, + publicationEpoch: 'renderer-live-pinned', + snapshotVersion: 1, + activeGroupId: 'group-1', + activeTabId: `host-tab::${HEADLESS_LEAF_ID}`, + activeTabType: 'terminal', + tabGroups: [{ id: 'group-1', activeTabId: 'host-tab', tabOrder: ['host-tab'] }], + tabs: [ + { + type: 'terminal', + id: `host-tab::${HEADLESS_LEAF_ID}`, + title: 'Pinned live terminal', + parentTabId: 'host-tab', + leafId: HEADLESS_LEAF_ID, + ptyId: servePtyId, + isPinned: false, + isActive: true + } + ] + } + ] + }) + const listed = await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`) + const terminal = listed.tabs.find((tab) => tab.type === 'terminal') + expect(terminal?.type === 'terminal' ? terminal.terminal : null).toBeTruthy() + + await expect( + runtime.closeTerminalTab(terminal?.type === 'terminal' ? terminal.terminal! : '') + ).rejects.toThrow('terminal_tab_pinned') + + expect(kill).not.toHaveBeenCalled() + expect(closeTerminal).not.toHaveBeenCalled() + expect(closeTerminalTab).toHaveBeenCalledWith('host-tab', { + validateOnly: true, + expectedPtyIds: [servePtyId] + }) + expect(getSession().tabsByWorktree[TEST_WORKTREE_ID]).toHaveLength(1) + expect(getSession().terminalLayoutsByTabId['host-tab']).toBeDefined() + }) + + it('materializes hydrated pending headless terminals with the persisted session identity', async () => { + const { runtimeStore } = makeRuntimeStoreWithWorkspaceSession( + makeWorkspaceSessionWithHeadlessTerminal() + ) + const spawn = vi.fn().mockResolvedValue({ id: 'persisted-pty' }) + const runtime = new OrcaRuntimeService(runtimeStore as never) + runtime.setPtyController({ + spawn, + write: () => true, + kill: () => true, + getForegroundProcess: async () => null, + listProcesses: async () => [] + }) + runtime.syncWindowGraph(0, { tabs: [], leaves: [] }) + + const activated = await runtime.activateMobileSessionTab(`id:${TEST_WORKTREE_ID}`, 'host-tab') + + expect(spawn).toHaveBeenCalledWith( + expect.objectContaining({ + tabId: 'host-tab', + leafId: HEADLESS_LEAF_ID, + sessionId: 'persisted-pty', + persistHostSessionBinding: true, + worktreeId: TEST_WORKTREE_ID + }) + ) + expect(activated.tabs[0]).toMatchObject({ + type: 'terminal', + parentTabId: 'host-tab', + leafId: HEADLESS_LEAF_ID, + status: 'ready', + terminal: expect.stringMatching(/^term_/) + }) + }) + + it('reattaches hydrated SSH headless terminals with the persisted relay identity', async () => { + const { runtimeStore } = makeRuntimeStoreWithWorkspaceSession( + makeWorkspaceSessionWithHeadlessTerminal({ + tabsByWorktree: { + [TEST_WORKTREE_ID]: [ + { + id: 'host-tab', + ptyId: 'ssh:ssh-1@@relay-pty', + worktreeId: TEST_WORKTREE_ID, + title: 'Remote Terminal', + customTitle: null, + color: null, + sortOrder: 0, + createdAt: 1 + } ] }, terminalLayoutsByTabId: { @@ -21086,115 +21785,519 @@ describe('OrcaRuntimeService', () => { webContents: { send: vi.fn() } }) - const events: RuntimeMobileSessionTabsResult[] = [] - runtime.onMobileSessionTabsChanged((snapshot) => events.push(snapshot)) - - await runtime.activateMobileSessionTab(`id:${TEST_WORKTREE_ID}`, 'tab-b') + const events: RuntimeMobileSessionTabsResult[] = [] + runtime.onMobileSessionTabsChanged((snapshot) => events.push(snapshot)) + + await runtime.activateMobileSessionTab(`id:${TEST_WORKTREE_ID}`, 'tab-b') + + // The headless persist is gated off by the authoritative window — nothing emitted. + expect(events).toHaveLength(0) + }) + + it('does not persist active server-side for a `:headless-merge:` snapshot after renderer detach', async () => { + // Why: after renderer detach, merged snapshots have no authoritative window but still carry renderer-owned group state. + let nextPty = 0 + const spawn = vi.fn().mockImplementation(async () => ({ id: `merge-pty-${++nextPty}` })) + const runtime = new OrcaRuntimeService(store) + runtime.setPtyController({ + spawn, + write: () => true, + kill: () => true, + getForegroundProcess: async () => null + }) + + const LEAF_A = '77777777-7777-4777-8777-777777777777' + const LEAF_B = '88888888-8888-4888-8888-888888888888' + // tab-a (first-created) is the snapshot's active tab. + await runtime.createTerminal(`id:${TEST_WORKTREE_ID}`, { tabId: 'tab-a', leafId: LEAF_A }) + await runtime.createTerminal(`id:${TEST_WORKTREE_ID}`, { tabId: 'tab-b', leafId: LEAF_B }) + + // Simulate a post-detach merged snapshot with no authoritative window. + const current = runtime['mobileSessionTabsByWorktree'].get(TEST_WORKTREE_ID)! + runtime['mobileSessionTabsByWorktree'].set(TEST_WORKTREE_ID, { + ...current, + publicationEpoch: `renderer:headless-merge:${current.publicationEpoch}` + }) + + const events: RuntimeMobileSessionTabsResult[] = [] + runtime.onMobileSessionTabsChanged((snapshot) => events.push(snapshot)) + + // The merge exclusion must suppress server-side active rewrites. + await runtime.activateMobileSessionTab(`id:${TEST_WORKTREE_ID}`, 'tab-b') + + expect(events).toHaveLength(0) + }) + + it('spawns fresh SSH terminals when hydrated persistence has no relay identity', async () => { + const { runtimeStore } = makeRuntimeStoreWithWorkspaceSession( + makeWorkspaceSessionWithHeadlessTerminal({ + tabsByWorktree: { + [TEST_WORKTREE_ID]: [ + { + id: 'host-tab', + ptyId: null, + worktreeId: TEST_WORKTREE_ID, + title: 'Remote Terminal', + customTitle: null, + color: null, + sortOrder: 0, + createdAt: 1 + } + ] + }, + terminalLayoutsByTabId: { + 'host-tab': makeHeadlessTerminalLayout({ [HEADLESS_LEAF_ID]: undefined }) + } + }) + ) + const remoteRepo = { ...store.getRepo(TEST_REPO_ID)!, connectionId: 'ssh-1' } + const remoteStore = { + ...runtimeStore, + getRepos: () => [remoteRepo], + getRepo: (id: string) => (id === TEST_REPO_ID ? remoteRepo : undefined) + } + const spawn = vi.fn().mockResolvedValue({ id: 'ssh:ssh-1@@fresh-pty' }) + const runtime = new OrcaRuntimeService(remoteStore as never) + runtime.setPtyController({ + spawn, + write: () => true, + kill: () => true, + getForegroundProcess: async () => null, + listProcesses: async () => [] + }) + runtime.syncWindowGraph(0, { tabs: [], leaves: [] }) + + await runtime.activateMobileSessionTab(`id:${TEST_WORKTREE_ID}`, 'host-tab') + + expect(spawn).toHaveBeenCalledWith( + expect.objectContaining({ + connectionId: 'ssh-1', + tabId: 'host-tab', + leafId: HEADLESS_LEAF_ID, + persistHostSessionBinding: true + }) + ) + expect(spawn.mock.calls[0]?.[0]).not.toHaveProperty('sessionId') + }) + + it('materializes the requested hydrated split leaf instead of the first sibling', async () => { + const layout = makeHeadlessTerminalLayout({ + [HEADLESS_LEAF_ID]: 'pty-a', + [HEADLESS_SECOND_LEAF_ID]: 'pty-b' + }) + const { runtimeStore } = makeRuntimeStoreWithWorkspaceSession( + makeWorkspaceSessionWithHeadlessTerminal({ + tabsByWorktree: { + [TEST_WORKTREE_ID]: [ + { + id: 'host-tab', + ptyId: 'pty-a', + worktreeId: TEST_WORKTREE_ID, + title: 'Persisted Split Terminal', + customTitle: null, + color: null, + sortOrder: 0, + createdAt: 1 + } + ] + }, + terminalLayoutsByTabId: { 'host-tab': layout } + }) + ) + const spawn = vi.fn().mockResolvedValue({ id: 'pty-b' }) + const runtime = new OrcaRuntimeService(runtimeStore as never) + runtime.setPtyController({ + spawn, + write: () => true, + kill: () => true, + getForegroundProcess: async () => null, + listProcesses: async () => [] + }) + runtime.syncWindowGraph(0, { tabs: [], leaves: [] }) + + const activated = await runtime.activateMobileSessionTab( + `id:${TEST_WORKTREE_ID}`, + 'host-tab', + HEADLESS_SECOND_LEAF_ID + ) + + expect(spawn).toHaveBeenCalledWith( + expect.objectContaining({ + tabId: 'host-tab', + leafId: HEADLESS_SECOND_LEAF_ID, + sessionId: 'pty-b' + }) + ) + expect(activated.tabs).toContainEqual( + expect.objectContaining({ + type: 'terminal', + parentTabId: 'host-tab', + leafId: HEADLESS_SECOND_LEAF_ID, + status: 'ready' + }) + ) + }) + + it('rejects missing requested split leaves instead of activating a sibling', async () => { + const layout = makeHeadlessTerminalLayout({ + [HEADLESS_LEAF_ID]: 'pty-a' + }) + const { runtimeStore } = makeRuntimeStoreWithWorkspaceSession( + makeWorkspaceSessionWithHeadlessTerminal({ + terminalLayoutsByTabId: { 'host-tab': layout } + }) + ) + const spawn = vi.fn().mockResolvedValue({ id: 'unexpected-pty' }) + const runtime = new OrcaRuntimeService(runtimeStore as never) + runtime.setPtyController({ + spawn, + write: () => true, + kill: () => true, + getForegroundProcess: async () => null, + listProcesses: async () => [] + }) + runtime.syncWindowGraph(0, { tabs: [], leaves: [] }) + + await expect( + runtime.activateMobileSessionTab( + `id:${TEST_WORKTREE_ID}`, + 'host-tab', + HEADLESS_SECOND_LEAF_ID + ) + ).rejects.toThrow('tab_not_found') + expect(spawn).not.toHaveBeenCalled() + }) + + it('closes persisted headless terminal parents and kills every live leaf', async () => { + const layout = makeHeadlessTerminalLayout({ + [HEADLESS_LEAF_ID]: 'pty-a', + [HEADLESS_SECOND_LEAF_ID]: 'pty-b' + }) + const { runtimeStore, getSession } = makeRuntimeStoreWithWorkspaceSession( + makeWorkspaceSessionWithHeadlessTerminal({ + tabsByWorktree: { + [TEST_WORKTREE_ID]: [ + { + id: 'host-tab', + ptyId: 'pty-a', + worktreeId: TEST_WORKTREE_ID, + title: 'Persisted Terminal', + customTitle: null, + color: null, + sortOrder: 0, + createdAt: 1 + } + ] + }, + terminalLayoutsByTabId: { 'host-tab': layout } + }) + ) + const kill = vi.fn(() => true) + const runtime = new OrcaRuntimeService(runtimeStore as never) + runtime.setPtyController({ + write: () => true, + kill, + getForegroundProcess: async () => null, + listProcesses: async () => [] + }) + runtime.syncWindowGraph(1, { + tabs: [ + { + tabId: 'host-tab', + worktreeId: TEST_WORKTREE_ID, + title: 'Persisted Terminal', + activeLeafId: HEADLESS_LEAF_ID, + layout: null + } + ], + leaves: [ + { + tabId: 'host-tab', + worktreeId: TEST_WORKTREE_ID, + leafId: HEADLESS_LEAF_ID, + paneRuntimeId: 1, + ptyId: 'pty-a', + paneTitle: 'A' + }, + { + tabId: 'host-tab', + worktreeId: TEST_WORKTREE_ID, + leafId: HEADLESS_SECOND_LEAF_ID, + paneRuntimeId: 2, + ptyId: 'pty-b', + paneTitle: 'B' + } + ] + }) + + await runtime.closeMobileSessionTab(`id:${TEST_WORKTREE_ID}`, 'host-tab') + + expect(kill).toHaveBeenCalledWith('pty-a') + expect(kill).toHaveBeenCalledWith('pty-b') + expect(getSession().tabsByWorktree[TEST_WORKTREE_ID]).toEqual([]) + expect(getSession().terminalLayoutsByTabId['host-tab']).toBeUndefined() + }) + + it('retires only the exact naturally exited headless split leaf', async () => { + const layout = makeHeadlessTerminalLayout({ + [HEADLESS_LEAF_ID]: 'serve-left', + [HEADLESS_SECOND_LEAF_ID]: 'serve-right' + }) + const { runtimeStore, getSession } = makeRuntimeStoreWithWorkspaceSession( + makeWorkspaceSessionWithHeadlessTerminal({ + tabsByWorktree: { + [TEST_WORKTREE_ID]: [ + { + id: 'host-tab', + ptyId: 'serve-left', + worktreeId: TEST_WORKTREE_ID, + title: 'Split Terminal', + customTitle: null, + color: null, + sortOrder: 0, + createdAt: 1 + } + ] + }, + terminalLayoutsByTabId: { 'host-tab': layout } + }) + ) + const kill = vi.fn(() => true) + const runtime = new OrcaRuntimeService(runtimeStore as never) + runtime.setPtyController({ + write: () => true, + kill, + getForegroundProcess: async () => null, + listProcesses: async () => [] + }) + runtime.syncWindowGraph(1, { + tabs: [], + leaves: [ + { + tabId: 'host-tab', + worktreeId: TEST_WORKTREE_ID, + leafId: HEADLESS_LEAF_ID, + paneRuntimeId: 1, + ptyId: 'serve-left' + }, + { + tabId: 'host-tab', + worktreeId: TEST_WORKTREE_ID, + leafId: HEADLESS_SECOND_LEAF_ID, + paneRuntimeId: 2, + ptyId: 'serve-right' + } + ] + }) + + runtime.onPtyExit('serve-right', 0) + + expect(kill).not.toHaveBeenCalled() + expect(getSession().tabsByWorktree[TEST_WORKTREE_ID]).toEqual([ + expect.objectContaining({ id: 'host-tab', ptyId: 'serve-left' }) + ]) + expect(getSession().terminalLayoutsByTabId['host-tab']).toMatchObject({ + root: { type: 'leaf', leafId: HEADLESS_LEAF_ID }, + activeLeafId: HEADLESS_LEAF_ID, + ptyIdsByLeafId: { [HEADLESS_LEAF_ID]: 'serve-left' } + }) + + const sessionSnapshot = (ptyId: string) => ({ + worktree: TEST_WORKTREE_ID, + publicationEpoch: `renderer-${ptyId}`, + snapshotVersion: 2, + activeGroupId: 'group-1', + activeTabId: `host-tab::${HEADLESS_SECOND_LEAF_ID}`, + activeTabType: 'terminal' as const, + tabGroups: [{ id: 'group-1', activeTabId: 'host-tab', tabOrder: ['host-tab'] }], + tabs: [ + { + type: 'terminal' as const, + id: `host-tab::${HEADLESS_SECOND_LEAF_ID}`, + parentTabId: 'host-tab', + leafId: HEADLESS_SECOND_LEAF_ID, + ptyId, + title: 'Right', + isActive: true + } + ] + }) + runtime.syncWindowGraph(1, { + tabs: [], + leaves: [], + mobileSessionTabs: [sessionSnapshot('serve-right')] + }) + let listed = await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`) + expect(listed.tabs).not.toContainEqual(expect.objectContaining({ ptyId: 'serve-right' })) + + const setWorkspaceSession = runtimeStore.setWorkspaceSession as unknown as ( + session: WorkspaceSessionState + ) => void + setWorkspaceSession({ + ...getSession(), + terminalLayoutsByTabId: { + ...getSession().terminalLayoutsByTabId, + 'host-tab': makeHeadlessTerminalLayout({ + [HEADLESS_LEAF_ID]: 'serve-left', + [HEADLESS_SECOND_LEAF_ID]: 'serve-rebound' + }) + } + }) + runtime.registerPty('serve-rebound', TEST_WORKTREE_ID, null, { + tabId: 'host-tab', + leafId: HEADLESS_SECOND_LEAF_ID + }) + runtime.syncWindowGraph(1, { + tabs: [], + leaves: [ + { + tabId: 'host-tab', + worktreeId: TEST_WORKTREE_ID, + leafId: HEADLESS_SECOND_LEAF_ID, + paneRuntimeId: 2, + ptyId: 'serve-rebound' + } + ], + mobileSessionTabs: [sessionSnapshot('serve-rebound')] + }) + listed = await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`) + expect(listed.tabs).toContainEqual(expect.objectContaining({ ptyId: 'serve-rebound' })) - // The headless persist is gated off by the authoritative window — nothing emitted. - expect(events).toHaveLength(0) - }) + runtime.onPtyExit('serve-rebound', 0) + setWorkspaceSession({ + ...getSession(), + terminalLayoutsByTabId: { + ...getSession().terminalLayoutsByTabId, + 'host-tab': makeHeadlessTerminalLayout({ + [HEADLESS_LEAF_ID]: 'serve-left', + [HEADLESS_SECOND_LEAF_ID]: 'serve-rebound' + }) + } + }) + runtime.registerPty('serve-rebound', TEST_WORKTREE_ID, null, { + tabId: 'host-tab', + leafId: HEADLESS_SECOND_LEAF_ID + }) + runtime.syncWindowGraph(1, { + tabs: [], + leaves: [ + { + tabId: 'host-tab', + worktreeId: TEST_WORKTREE_ID, + leafId: HEADLESS_SECOND_LEAF_ID, + paneRuntimeId: 2, + ptyId: 'serve-rebound' + } + ], + mobileSessionTabs: [sessionSnapshot('serve-rebound')] + }) + listed = await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`) + expect(listed.tabs).toContainEqual(expect.objectContaining({ ptyId: 'serve-rebound' })) - it('does not persist active server-side for a `:headless-merge:` snapshot after renderer detach', async () => { - // Why: after renderer detach, merged snapshots have no authoritative window but still carry renderer-owned group state. - let nextPty = 0 - const spawn = vi.fn().mockImplementation(async () => ({ id: `merge-pty-${++nextPty}` })) - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - spawn, + const restartedRuntime = new OrcaRuntimeService(runtimeStore as never) + restartedRuntime.setPtyController({ write: () => true, kill: () => true, getForegroundProcess: async () => null }) - - const LEAF_A = '77777777-7777-4777-8777-777777777777' - const LEAF_B = '88888888-8888-4888-8888-888888888888' - // tab-a (first-created) is the snapshot's active tab. - await runtime.createTerminal(`id:${TEST_WORKTREE_ID}`, { tabId: 'tab-a', leafId: LEAF_A }) - await runtime.createTerminal(`id:${TEST_WORKTREE_ID}`, { tabId: 'tab-b', leafId: LEAF_B }) - - // Simulate a post-detach merged snapshot with no authoritative window. - const current = runtime['mobileSessionTabsByWorktree'].get(TEST_WORKTREE_ID)! - runtime['mobileSessionTabsByWorktree'].set(TEST_WORKTREE_ID, { - ...current, - publicationEpoch: `renderer:headless-merge:${current.publicationEpoch}` + restartedRuntime.syncWindowGraph(1, { + tabs: [], + leaves: [], + mobileSessionTabs: [sessionSnapshot('serve-right')] }) + const afterRestart = await restartedRuntime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`) + expect(afterRestart.tabs).toContainEqual(expect.objectContaining({ ptyId: 'serve-rebound' })) + expect(afterRestart.tabs).not.toContainEqual(expect.objectContaining({ ptyId: 'serve-right' })) - const events: RuntimeMobileSessionTabsResult[] = [] - runtime.onMobileSessionTabsChanged((snapshot) => events.push(snapshot)) - - // The merge exclusion must suppress server-side active rewrites. - await runtime.activateMobileSessionTab(`id:${TEST_WORKTREE_ID}`, 'tab-b') - - expect(events).toHaveLength(0) + restartedRuntime.syncWindowGraph(1, { + tabs: [ + { + tabId: 'host-tab', + worktreeId: TEST_WORKTREE_ID, + title: 'Renderer Replacement', + activeLeafId: HEADLESS_SECOND_LEAF_ID, + layout: null + } + ], + leaves: [ + { + tabId: 'host-tab', + worktreeId: TEST_WORKTREE_ID, + leafId: HEADLESS_SECOND_LEAF_ID, + paneRuntimeId: 2, + ptyId: 'renderer-p3' + } + ], + mobileSessionTabs: [sessionSnapshot('renderer-p3')] + }) + const beforePersistenceCatchup = await restartedRuntime.listMobileSessionTabs( + `id:${TEST_WORKTREE_ID}` + ) + expect(beforePersistenceCatchup.tabs).toContainEqual( + expect.objectContaining({ ptyId: 'renderer-p3', status: 'ready' }) + ) + expect(getSession().terminalLayoutsByTabId['host-tab']?.ptyIdsByLeafId).toEqual({ + [HEADLESS_LEAF_ID]: 'serve-left', + [HEADLESS_SECOND_LEAF_ID]: 'serve-rebound' + }) }) - it('spawns fresh SSH terminals when hydrated persistence has no relay identity', async () => { - const { runtimeStore } = makeRuntimeStoreWithWorkspaceSession( + it('retires the final naturally exited pinned headless leaf without another kill', () => { + const { runtimeStore, getSession } = makeRuntimeStoreWithWorkspaceSession( makeWorkspaceSessionWithHeadlessTerminal({ tabsByWorktree: { [TEST_WORKTREE_ID]: [ { id: 'host-tab', - ptyId: null, + ptyId: 'serve-only', worktreeId: TEST_WORKTREE_ID, - title: 'Remote Terminal', + title: 'Pinned Terminal', customTitle: null, color: null, + isPinned: true, sortOrder: 0, createdAt: 1 } ] }, terminalLayoutsByTabId: { - 'host-tab': makeHeadlessTerminalLayout({ [HEADLESS_LEAF_ID]: undefined }) + 'host-tab': makeHeadlessTerminalLayout({ [HEADLESS_LEAF_ID]: 'serve-only' }) } }) ) - const remoteRepo = { ...store.getRepo(TEST_REPO_ID)!, connectionId: 'ssh-1' } - const remoteStore = { - ...runtimeStore, - getRepos: () => [remoteRepo], - getRepo: (id: string) => (id === TEST_REPO_ID ? remoteRepo : undefined) - } - const spawn = vi.fn().mockResolvedValue({ id: 'ssh:ssh-1@@fresh-pty' }) - const runtime = new OrcaRuntimeService(remoteStore as never) - runtime.setPtyController({ - spawn, - write: () => true, - kill: () => true, - getForegroundProcess: async () => null, - listProcesses: async () => [] + const kill = vi.fn(() => true) + const runtime = new OrcaRuntimeService(runtimeStore as never) + runtime.setPtyController({ write: () => true, kill, getForegroundProcess: async () => null }) + runtime.syncWindowGraph(0, { + tabs: [], + leaves: [ + { + tabId: 'host-tab', + worktreeId: TEST_WORKTREE_ID, + leafId: HEADLESS_LEAF_ID, + paneRuntimeId: 1, + ptyId: 'serve-only' + } + ] }) - runtime.syncWindowGraph(0, { tabs: [], leaves: [] }) - await runtime.activateMobileSessionTab(`id:${TEST_WORKTREE_ID}`, 'host-tab') + runtime.onPtyExit('serve-only', 0) - expect(spawn).toHaveBeenCalledWith( - expect.objectContaining({ - connectionId: 'ssh-1', - tabId: 'host-tab', - leafId: HEADLESS_LEAF_ID, - persistHostSessionBinding: true - }) - ) - expect(spawn.mock.calls[0]?.[0]).not.toHaveProperty('sessionId') + expect(kill).not.toHaveBeenCalled() + expect(getSession().tabsByWorktree[TEST_WORKTREE_ID]).toEqual([]) + expect(getSession().terminalLayoutsByTabId['host-tab']).toBeUndefined() }) - it('materializes the requested hydrated split leaf instead of the first sibling', async () => { - const layout = makeHeadlessTerminalLayout({ - [HEADLESS_LEAF_ID]: 'pty-a', - [HEADLESS_SECOND_LEAF_ID]: 'pty-b' - }) - const { runtimeStore } = makeRuntimeStoreWithWorkspaceSession( + it('does not retire a replacement headless binding from a stale PTY exit', () => { + const { runtimeStore, getSession } = makeRuntimeStoreWithWorkspaceSession( makeWorkspaceSessionWithHeadlessTerminal({ tabsByWorktree: { [TEST_WORKTREE_ID]: [ { id: 'host-tab', - ptyId: 'pty-a', + ptyId: 'serve-live', worktreeId: TEST_WORKTREE_ID, - title: 'Persisted Split Terminal', + title: 'Replacement Terminal', customTitle: null, color: null, sortOrder: 0, @@ -21202,87 +22305,50 @@ describe('OrcaRuntimeService', () => { } ] }, - terminalLayoutsByTabId: { 'host-tab': layout } + terminalLayoutsByTabId: { + 'host-tab': makeHeadlessTerminalLayout({ [HEADLESS_LEAF_ID]: 'serve-live' }) + } }) ) - const spawn = vi.fn().mockResolvedValue({ id: 'pty-b' }) const runtime = new OrcaRuntimeService(runtimeStore as never) runtime.setPtyController({ - spawn, write: () => true, kill: () => true, - getForegroundProcess: async () => null, - listProcesses: async () => [] + getForegroundProcess: async () => null + }) + runtime.syncWindowGraph(0, { + tabs: [], + leaves: [ + { + tabId: 'host-tab', + worktreeId: TEST_WORKTREE_ID, + leafId: HEADLESS_LEAF_ID, + paneRuntimeId: 1, + ptyId: 'serve-old' + } + ] }) - runtime.syncWindowGraph(0, { tabs: [], leaves: [] }) - - const activated = await runtime.activateMobileSessionTab( - `id:${TEST_WORKTREE_ID}`, - 'host-tab', - HEADLESS_SECOND_LEAF_ID - ) - expect(spawn).toHaveBeenCalledWith( - expect.objectContaining({ - tabId: 'host-tab', - leafId: HEADLESS_SECOND_LEAF_ID, - sessionId: 'pty-b' - }) - ) - expect(activated.tabs).toContainEqual( - expect.objectContaining({ - type: 'terminal', - parentTabId: 'host-tab', - leafId: HEADLESS_SECOND_LEAF_ID, - status: 'ready' - }) - ) - }) + runtime.onPtyExit('serve-old', 0) - it('rejects missing requested split leaves instead of activating a sibling', async () => { - const layout = makeHeadlessTerminalLayout({ - [HEADLESS_LEAF_ID]: 'pty-a' - }) - const { runtimeStore } = makeRuntimeStoreWithWorkspaceSession( - makeWorkspaceSessionWithHeadlessTerminal({ - terminalLayoutsByTabId: { 'host-tab': layout } - }) - ) - const spawn = vi.fn().mockResolvedValue({ id: 'unexpected-pty' }) - const runtime = new OrcaRuntimeService(runtimeStore as never) - runtime.setPtyController({ - spawn, - write: () => true, - kill: () => true, - getForegroundProcess: async () => null, - listProcesses: async () => [] + expect(getSession().tabsByWorktree[TEST_WORKTREE_ID]).toEqual([ + expect.objectContaining({ id: 'host-tab', ptyId: 'serve-live' }) + ]) + expect(getSession().terminalLayoutsByTabId['host-tab']?.ptyIdsByLeafId).toEqual({ + [HEADLESS_LEAF_ID]: 'serve-live' }) - runtime.syncWindowGraph(0, { tabs: [], leaves: [] }) - - await expect( - runtime.activateMobileSessionTab( - `id:${TEST_WORKTREE_ID}`, - 'host-tab', - HEADLESS_SECOND_LEAF_ID - ) - ).rejects.toThrow('tab_not_found') - expect(spawn).not.toHaveBeenCalled() }) - it('closes persisted headless terminal parents and kills every live leaf', async () => { - const layout = makeHeadlessTerminalLayout({ - [HEADLESS_LEAF_ID]: 'pty-a', - [HEADLESS_SECOND_LEAF_ID]: 'pty-b' - }) - const { runtimeStore, getSession } = makeRuntimeStoreWithWorkspaceSession( + it('leaves renderer-owned terminal persistence to the renderer exit transaction', () => { + const { runtimeStore } = makeRuntimeStoreWithWorkspaceSession( makeWorkspaceSessionWithHeadlessTerminal({ tabsByWorktree: { [TEST_WORKTREE_ID]: [ { id: 'host-tab', - ptyId: 'pty-a', + ptyId: 'daemon-pty', worktreeId: TEST_WORKTREE_ID, - title: 'Persisted Terminal', + title: 'Renderer Terminal', customTitle: null, color: null, sortOrder: 0, @@ -21290,23 +22356,23 @@ describe('OrcaRuntimeService', () => { } ] }, - terminalLayoutsByTabId: { 'host-tab': layout } + terminalLayoutsByTabId: { + 'host-tab': makeHeadlessTerminalLayout({ [HEADLESS_LEAF_ID]: 'daemon-pty' }) + } }) ) - const kill = vi.fn(() => true) const runtime = new OrcaRuntimeService(runtimeStore as never) runtime.setPtyController({ write: () => true, - kill, - getForegroundProcess: async () => null, - listProcesses: async () => [] + kill: () => true, + getForegroundProcess: async () => null }) runtime.syncWindowGraph(1, { tabs: [ { tabId: 'host-tab', worktreeId: TEST_WORKTREE_ID, - title: 'Persisted Terminal', + title: 'Renderer Terminal', activeLeafId: HEADLESS_LEAF_ID, layout: null } @@ -21317,26 +22383,15 @@ describe('OrcaRuntimeService', () => { worktreeId: TEST_WORKTREE_ID, leafId: HEADLESS_LEAF_ID, paneRuntimeId: 1, - ptyId: 'pty-a', - paneTitle: 'A' - }, - { - tabId: 'host-tab', - worktreeId: TEST_WORKTREE_ID, - leafId: HEADLESS_SECOND_LEAF_ID, - paneRuntimeId: 2, - ptyId: 'pty-b', - paneTitle: 'B' + ptyId: 'daemon-pty' } ] }) + runtimeStore.setWorkspaceSession.mockClear() - await runtime.closeMobileSessionTab(`id:${TEST_WORKTREE_ID}`, 'host-tab') + runtime.onPtyExit('daemon-pty', 0) - expect(kill).toHaveBeenCalledWith('pty-a') - expect(kill).toHaveBeenCalledWith('pty-b') - expect(getSession().tabsByWorktree[TEST_WORKTREE_ID]).toEqual([]) - expect(getSession().terminalLayoutsByTabId['host-tab']).toBeUndefined() + expect(runtimeStore.setWorkspaceSession).not.toHaveBeenCalled() }) it('closes persisted headless terminal parents before any prior list call', async () => { @@ -21421,7 +22476,10 @@ describe('OrcaRuntimeService', () => { expect(getSession().tabsByWorktree[TEST_WORKTREE_ID]).toEqual([]) expect(getSession().terminalLayoutsByTabId['host-tab']).toBeUndefined() // Best-effort renderer notify so no adopted pane is left dead. - expect(closeTerminal).toHaveBeenCalledWith('host-tab') + expect(closeTerminal).toHaveBeenCalledWith('host-tab', undefined, { + mirrorOnly: true, + expectedPtyIds: [] + }) }) it('delegates a renderer-owned daemon-session (worktreeId@@uuid) local terminal to the renderer', async () => { @@ -21531,7 +22589,10 @@ describe('OrcaRuntimeService', () => { expect(getSession().tabsByWorktree[TEST_WORKTREE_ID]).toEqual([]) expect(getSession().terminalLayoutsByTabId['host-tab']).toBeUndefined() - expect(closeTerminal).toHaveBeenCalledWith('host-tab') + expect(closeTerminal).toHaveBeenCalledWith('host-tab', undefined, { + mirrorOnly: true, + expectedPtyIds: [] + }) }) it('defers a renderer-published pending tab to the renderer instead of tearing it down', async () => { @@ -21613,7 +22674,10 @@ describe('OrcaRuntimeService', () => { expect(kill).not.toHaveBeenCalled() expect(getSession().tabsByWorktree[TEST_WORKTREE_ID]).toEqual([]) expect(getSession().terminalLayoutsByTabId['host-tab']).toBeUndefined() - expect(closeTerminal).toHaveBeenCalledWith('host-tab') + expect(closeTerminal).toHaveBeenCalledWith('host-tab', undefined, { + mirrorOnly: true, + expectedPtyIds: [] + }) }) it('closes only the addressed serve-owned split leaf so siblings survive even with a renderer attached', async () => { diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index fe9eb66574d7..7a6b02ced417 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -155,6 +155,7 @@ import type { RuntimeClientEvent } from '../../shared/runtime-client-events' import { toRuntimeActivateWorktreeEvent } from '../../shared/runtime-client-events' import type { SshConnectionState } from '../../shared/ssh-types' import { closeTerminalTabInWorkspaceSession } from '../../shared/workspace-session-terminal-tab-close' +import { retireTerminalLeafInWorkspaceSession } from '../../shared/workspace-session-terminal-leaf-retirement' import type { LinearCurrentIssueContextHints, LinearAttachResult, @@ -1445,8 +1446,15 @@ type RuntimeNotifier = { baseVersion: string, content: string ): Promise - closeTerminal(tabId: string, paneRuntimeId?: number): void - closeTerminalTab?(tabId: string): Promise + closeTerminal( + tabId: string, + paneRuntimeId?: number, + options?: { mirrorOnly?: boolean; expectedPtyIds?: string[] } + ): void + closeTerminalTab?( + tabId: string, + options?: { validateOnly?: boolean; expectedPtyIds?: string[] } + ): Promise sleepWorktree(worktreeId: string): void // Why: a phone opening a worktree wakes its slept agents by asking the host // renderer to run its own navigation-free wake (experimental agent sleep); @@ -1480,6 +1488,18 @@ type TerminalHandleRecord = { ptyGeneration: number } +type RuntimeOwnedPtyExitCandidate = { + ptyId: string + worktreeId: string + parentTabId: string + leafId: string + lifecycleGeneration: number +} + +type RuntimeTerminalTabCloseExpectation = RuntimeOwnedPtyExitCandidate & { + handle: string +} + type TerminalWaiter = { handle: string condition: RuntimeTerminalWaitCondition @@ -2265,6 +2285,7 @@ export class OrcaRuntimeService { private handles = new Map() private handleByLeafKey = new Map() private handleByPtyId = new Map() + private retiredRuntimeOwnedTerminalBindings = new Map() private detachedPreAllocatedLeaves = new Map() private graphSyncCallbacks: (() => void)[] = [] private waitersByHandle = new Map>() @@ -3370,7 +3391,7 @@ export class OrcaRuntimeService { } this.tabs = new Map(graph.tabs.map((tab) => [tab.tabId, tab])) - this.syncMobileSessionTabs(graph.mobileSessionTabs) + this.syncMobileSessionTabs(graph.mobileSessionTabs, graph.leaves) const nextLeaves = new Map() const graphSyncedAt = this.nextTitleObservationSequence() @@ -4846,12 +4867,19 @@ export class OrcaRuntimeService { }) } - async closeMobileSessionTab(worktreeSelector: string, tabId: string): Promise<{ closed: true }> { + async closeMobileSessionTab( + worktreeSelector: string, + tabId: string, + expected?: RuntimeTerminalTabCloseExpectation + ): Promise<{ closed: true }> { const explicitWorktreeId = this.getValidatedExplicitWorktreeIdSelector(worktreeSelector) const worktreeId = explicitWorktreeId ?? (await this.resolveWorktreeSelector(worktreeSelector)).id this.hydrateHeadlessMobileSessionTabsFromWorkspaceSession(worktreeId) await this.refreshMobileSessionPtyRecords() + if (expected) { + this.assertCurrentTerminalTabCloseExpectation(expected) + } const snapshot = this.mobileSessionTabsByWorktree.get(worktreeId) const tab = snapshot?.tabs.find((candidate) => candidate.id === tabId) ?? @@ -4869,6 +4897,61 @@ export class OrcaRuntimeService { (candidate) => candidate.type === 'terminal' && candidate.parentTabId === tab.parentTabId ).length const closingWholeParent = tab.id !== tabId || parentLeafCount <= 1 + if (closingWholeParent && expected) { + if ( + snapshot!.tabs.some( + (candidate) => + candidate.type === 'terminal' && + candidate.parentTabId === tab.parentTabId && + candidate.isPinned + ) + ) { + throw new Error('terminal_tab_pinned') + } + const expectedBindings = this.captureTerminalParentCloseBindings( + worktreeId, + snapshot!, + tab.parentTabId + ) + if (!expectedBindings.some((binding) => binding.ptyId === expected.ptyId)) { + throw new Error('terminal_handle_stale') + } + this.assertCurrentTerminalParentCloseBindings(expectedBindings) + if (this.tabs.has(tab.parentTabId) && this.notifier?.closeTerminalTab) { + // Why: renderer validation reads the live pin and exact mirror set but + // mutates nothing; main remains the sole destructive transaction owner. + await this.notifier.closeTerminalTab(tab.parentTabId, { + validateOnly: true, + expectedPtyIds: expectedBindings.map((binding) => binding.ptyId) + }) + await this.refreshMobileSessionPtyRecords() + this.assertCurrentTerminalParentCloseBindings(expectedBindings) + this.closeHeadlessMobileTerminalTab( + worktreeId, + snapshot!, + tab, + expectedBindings.map((binding) => binding.ptyId) + ) + this.notifyRendererOfHeadlessTerminalClose( + tab.parentTabId, + expectedBindings.map((binding) => binding.ptyId) + ) + return { closed: true } + } + // Why: generation authority lives in main. Headless tabs have no live + // renderer transaction, so main commits durability before provider teardown. + this.closeHeadlessMobileTerminalTab( + worktreeId, + snapshot!, + tab, + expectedBindings.map((binding) => binding.ptyId) + ) + this.notifyRendererOfHeadlessTerminalClose( + tab.parentTabId, + expectedBindings.map((binding) => binding.ptyId) + ) + return { closed: true } + } // Why: a runtime-owned headless tab is absent from renderer state, so the // closeTerminalTab relay below would ack success without killing its PTY, // and syncMobileSessionTabs would republish the "closed" tab. Only bypass @@ -4877,7 +4960,6 @@ export class OrcaRuntimeService { if (closingWholeParent && !this.tabs.has(tab.parentTabId)) { this.closeHeadlessMobileTerminalTab(worktreeId, snapshot!, tab) this.notifyRendererOfHeadlessTerminalClose(tab.parentTabId) - this.store?.flushOrThrow?.() return { closed: true } } if (closingWholeParent && this.notifier?.closeTerminalTab) { @@ -4891,12 +4973,10 @@ export class OrcaRuntimeService { if (closingWholeParent && this.isRuntimeOwnedHeadlessMobileTab(worktreeId, tab)) { this.closeHeadlessMobileTerminalTab(worktreeId, snapshot!, tab) this.notifyRendererOfHeadlessTerminalClose(tab.parentTabId) - this.store?.flushOrThrow?.() return { closed: true } } if (!this.notifier?.closeTerminal) { this.closeHeadlessMobileTerminalTab(worktreeId, snapshot!, tab) - this.store?.flushOrThrow?.() return { closed: true } } if (tab.id === tabId) { @@ -4923,11 +5003,105 @@ export class OrcaRuntimeService { return { closed: true } } - private notifyRendererOfHeadlessTerminalClose(parentTabId: string): void { + private captureTerminalParentCloseBindings( + worktreeId: string, + snapshot: RuntimeMobileSessionTabsSnapshot, + parentTabId: string + ): RuntimeOwnedPtyExitCandidate[] { + const bindings = new Map() + for (const tab of snapshot.tabs) { + if (tab.type !== 'terminal' || tab.parentTabId !== parentTabId) { + continue + } + const liveLeaf = this.leaves.get(this.getLeafKey(tab.parentTabId, tab.leafId)) ?? null + const pty = + liveLeaf?.connected && liveLeaf.ptyId + ? (this.ptysById.get(liveLeaf.ptyId) ?? null) + : this.findPtyForMobileTerminalTab(worktreeId, tab) + const pane = parsePaneKey(pty?.paneKey ?? '') + if (!pty?.connected || !pane || pane.tabId !== parentTabId || pane.leafId !== tab.leafId) { + continue + } + const binding: RuntimeOwnedPtyExitCandidate = { + ptyId: pty.ptyId, + worktreeId, + parentTabId, + leafId: tab.leafId, + lifecycleGeneration: this.getPtyLifecycleGeneration(pty.ptyId) + } + const prior = bindings.get(pty.ptyId) + if (prior && prior.leafId !== binding.leafId) { + throw new Error('terminal_handle_stale') + } + bindings.set(pty.ptyId, binding) + } + return [...bindings.values()] + } + + private assertCurrentTerminalParentCloseBindings( + expectedBindings: readonly RuntimeOwnedPtyExitCandidate[] + ): void { + const expectedKeys = new Set( + expectedBindings.map((binding) => + JSON.stringify([binding.ptyId, binding.leafId, binding.lifecycleGeneration]) + ) + ) + for (const expected of expectedBindings) { + const pty = this.ptysById.get(expected.ptyId) + const pane = parsePaneKey(pty?.paneKey ?? '') + if ( + !pty?.connected || + pty.worktreeId !== expected.worktreeId || + pty.tabId !== expected.parentTabId || + pane?.tabId !== expected.parentTabId || + pane.leafId !== expected.leafId || + this.getPtyLifecycleGeneration(expected.ptyId) !== expected.lifecycleGeneration + ) { + throw new Error('terminal_handle_stale') + } + } + const first = expectedBindings[0] + if (!first) { + throw new Error('terminal_handle_stale') + } + const currentKeys = new Set() + for (const pty of this.ptysById.values()) { + if ( + !pty.connected || + pty.worktreeId !== first.worktreeId || + pty.tabId !== first.parentTabId + ) { + continue + } + const pane = parsePaneKey(pty.paneKey ?? '') + if (!pane || pane.tabId !== first.parentTabId) { + throw new Error('terminal_handle_stale') + } + currentKeys.add( + JSON.stringify([pty.ptyId, pane.leafId, this.getPtyLifecycleGeneration(pty.ptyId)]) + ) + } + if (currentKeys.size !== expectedKeys.size) { + throw new Error('terminal_handle_stale') + } + for (const key of currentKeys) { + if (!expectedKeys.has(key)) { + throw new Error('terminal_handle_stale') + } + } + } + + private notifyRendererOfHeadlessTerminalClose( + parentTabId: string, + expectedPtyIds: string[] = [] + ): void { // Why: this relay is advisory after main owns teardown; renderer failure must // not prevent the authoritative session flush or turn the close into failure. try { - this.notifier?.closeTerminal(parentTabId) + this.notifier?.closeTerminal(parentTabId, undefined, { + mirrorOnly: true, + expectedPtyIds + }) } catch (error) { console.warn('[runtime] failed to notify renderer after headless terminal close', { parentTabId, @@ -5026,14 +5200,35 @@ export class OrcaRuntimeService { private closeHeadlessMobileTerminalTab( worktreeId: string, snapshot: RuntimeMobileSessionTabsSnapshot, - tab: RuntimeMobileSessionTerminalTab + tab: RuntimeMobileSessionTerminalTab, + authoritativePtyIds: readonly string[] = [] ): void { const closedParentTabId = tab.parentTabId + const priorSession = this.store?.getWorkspaceSession?.() const projectedPtyIds = this.removePersistedHeadlessTerminalTab(worktreeId, closedParentTabId) + try { + this.store?.flushOrThrow?.() + } catch (error) { + // Why: provider teardown must never outrun durable explicit-close state. + // Restore the in-memory session when the flush refuses the transaction. + if (priorSession) { + this.store?.setWorkspaceSession?.(priorSession) + } + throw error + } // Why: local provider ids can be reused after restart, so a dormant // persisted id is not kill authority. SSH relay ids remain durable exact // identities even before pane metadata reconnects. - const ptyIdsToKill = new Set(projectedPtyIds.filter((ptyId) => parseAppSshPtyId(ptyId))) + const exclusiveAuthoritativePtyIds = authoritativePtyIds.filter( + (ptyId) => + !this.terminalPtyHasOtherOwner(priorSession, snapshot, worktreeId, closedParentTabId, ptyId) + ) + const exclusiveProjectedSshPtyIds = projectedPtyIds.filter( + (ptyId) => + parseAppSshPtyId(ptyId) && + !this.terminalPtyHasOtherOwner(priorSession, snapshot, worktreeId, closedParentTabId, ptyId) + ) + const ptyIdsToKill = new Set([...exclusiveAuthoritativePtyIds, ...exclusiveProjectedSshPtyIds]) for (const candidate of snapshot.tabs) { if (candidate.type !== 'terminal' || candidate.parentTabId !== closedParentTabId) { continue @@ -5056,12 +5251,57 @@ export class OrcaRuntimeService { for (const ptyId of ptyIdsToKill) { this.ptyController?.kill(ptyId) } - const nextTabs = snapshot.tabs.filter((candidate) => { - if (candidate.type !== 'terminal' || candidate.parentTabId !== closedParentTabId) { - return true - } + this.removeTerminalParentFromMobileSnapshot(worktreeId, snapshot, closedParentTabId) + } + + private terminalPtyHasOtherOwner( + session: WorkspaceSessionState | undefined, + snapshot: RuntimeMobileSessionTabsSnapshot, + worktreeId: string, + parentTabId: string, + ptyId: string + ): boolean { + if ( + snapshot.tabs.some( + (tab) => + tab.type === 'terminal' && + tab.parentTabId !== parentTabId && + (tab.ptyId === ptyId || + Object.values(tab.parentLayout?.ptyIdsByLeafId ?? {}).includes(ptyId)) + ) + ) { + return true + } + if (!session) { return false - }) + } + for (const [ownerWorktreeId, tabs] of Object.entries(session.tabsByWorktree)) { + for (const tab of tabs) { + if (ownerWorktreeId === worktreeId && tab.id === parentTabId) { + continue + } + if ( + tab.ptyId === ptyId || + session.remoteSessionIdsByTabId?.[tab.id] === ptyId || + Object.values(session.terminalLayoutsByTabId[tab.id]?.ptyIdsByLeafId ?? {}).includes( + ptyId + ) + ) { + return true + } + } + } + return false + } + + private removeTerminalParentFromMobileSnapshot( + worktreeId: string, + snapshot: RuntimeMobileSessionTabsSnapshot, + parentTabId: string + ): void { + const nextTabs = snapshot.tabs.filter( + (candidate) => candidate.type !== 'terminal' || candidate.parentTabId !== parentTabId + ) const active = nextTabs.find((candidate) => candidate.isActive) ?? nextTabs[0] ?? null const nextSnapshot: RuntimeMobileSessionTabsSnapshot = { ...snapshot, @@ -9244,7 +9484,156 @@ export class OrcaRuntimeService { } } + private getRuntimeOwnedTerminalBindingKey( + binding: Pick + ): string { + return JSON.stringify([binding.worktreeId, binding.parentTabId, binding.leafId, binding.ptyId]) + } + + private captureRuntimeOwnedPtyExitCandidate(ptyId: string): RuntimeOwnedPtyExitCandidate | null { + const pty = this.ptysById.get(ptyId) + const pane = parsePaneKey(pty?.paneKey ?? '') + const parentTabId = pty?.tabId ?? pane?.tabId ?? null + if (!pty || !pane || !parentTabId || pane.tabId !== parentTabId) { + return null + } + const persistedLayout = this.store?.getWorkspaceSession?.()?.terminalLayoutsByTabId[parentTabId] + if (persistedLayout?.ptyIdsByLeafId?.[pane.leafId] !== ptyId) { + return null + } + const snapshotTab = this.mobileSessionTabsByWorktree + .get(pty.worktreeId) + ?.tabs.find( + (tab): tab is RuntimeMobileSessionTerminalTab => + tab.type === 'terminal' && + tab.parentTabId === parentTabId && + tab.leafId === pane.leafId && + (tab.ptyId === ptyId || tab.parentLayout?.ptyIdsByLeafId?.[pane.leafId] === ptyId) + ) + const runtimeOwned = snapshotTab + ? this.isRuntimeOwnedHeadlessMobileTab(pty.worktreeId, snapshotTab) + : this.isServeOrSshOwnedPtyId(ptyId) || !this.tabs.has(parentTabId) + if (!runtimeOwned) { + return null + } + return { + ptyId, + worktreeId: pty.worktreeId, + parentTabId, + leafId: pane.leafId, + lifecycleGeneration: this.getPtyLifecycleGeneration(ptyId) + } + } + + private retireRuntimeOwnedPtyExit(candidate: RuntimeOwnedPtyExitCandidate): boolean { + const session = this.store?.getWorkspaceSession?.() + if (!session || !this.store?.setWorkspaceSession) { + return false + } + const retirement = retireTerminalLeafInWorkspaceSession(session, candidate.worktreeId, { + parentTabId: candidate.parentTabId, + leafId: candidate.leafId, + expectedPtyId: candidate.ptyId + }) + if (!retirement.retired) { + return false + } + try { + this.store.setWorkspaceSession(retirement.session) + this.store.flushOrThrow?.() + } catch (error) { + // Why: publication must never outrun durable headless ownership; restore + // the prior in-memory session when persistence refuses the retirement. + this.store.setWorkspaceSession(session) + throw error + } + this.retiredRuntimeOwnedTerminalBindings.set( + this.getRuntimeOwnedTerminalBindingKey(candidate), + candidate + ) + if (this.retiredRuntimeOwnedTerminalBindings.size > 512) { + const oldest = this.retiredRuntimeOwnedTerminalBindings.keys().next().value + if (oldest) { + this.retiredRuntimeOwnedTerminalBindings.delete(oldest) + } + } + + const snapshot = this.mobileSessionTabsByWorktree.get(candidate.worktreeId) + if (!snapshot) { + return true + } + const isExitedSurface = (tab: RuntimeMobileSessionSnapshotTab): boolean => + tab.type === 'terminal' && + tab.parentTabId === candidate.parentTabId && + tab.leafId === candidate.leafId && + (tab.ptyId === candidate.ptyId || + tab.parentLayout?.ptyIdsByLeafId?.[candidate.leafId] === candidate.ptyId) + const removedWasActive = snapshot.tabs.some( + (tab) => isExitedSurface(tab) && tab.id === snapshot.activeTabId + ) + const persistedLayout = retirement.session.terminalLayoutsByTabId[candidate.parentTabId] + let nextTabs = snapshot.tabs + .filter((tab) => !isExitedSurface(tab)) + .map((tab) => + tab.type === 'terminal' && tab.parentTabId === candidate.parentTabId && persistedLayout + ? { ...tab, parentLayout: this.cloneTerminalLayoutSnapshot(persistedLayout) } + : tab + ) + const active = + (!removedWasActive + ? nextTabs.find((tab) => tab.id === snapshot.activeTabId) + : nextTabs.find( + (tab) => tab.type === 'terminal' && tab.parentTabId === candidate.parentTabId + )) ?? + nextTabs.find((tab) => tab.isActive) ?? + nextTabs[0] ?? + null + nextTabs = nextTabs.map((tab) => ({ ...tab, isActive: tab.id === active?.id })) + const parentStillPresent = nextTabs.some( + (tab) => tab.type === 'terminal' && tab.parentTabId === candidate.parentTabId + ) + const tabGroups = (snapshot.tabGroups ?? []) + .map((group) => { + const tabOrder = parentStillPresent + ? group.tabOrder + : group.tabOrder.filter((id) => id !== candidate.parentTabId) + return { + ...group, + tabOrder, + activeTabId: + group.activeTabId && tabOrder.includes(group.activeTabId) + ? group.activeTabId + : (tabOrder[0] ?? null) + } + }) + .filter((group) => group.tabOrder.length > 0) + const pureHeadless = + snapshot.publicationEpoch.startsWith('headless:') || + snapshot.publicationEpoch.startsWith('headless-hydrated:') + const preservedTabs = nextTabs.filter( + (tab) => tab.type === 'terminal' && this.hasServeOwnedPtyBinding(tab) + ) + const nextSnapshot: RuntimeMobileSessionTabsSnapshot = { + ...snapshot, + publicationEpoch: pureHeadless + ? `headless:${Date.now().toString(36)}` + : this.getMergedMobileSessionPublicationEpoch(snapshot, preservedTabs), + snapshotVersion: pureHeadless ? snapshot.snapshotVersion + 1 : snapshot.snapshotVersion, + activeGroupId: tabGroups.some((group) => group.id === snapshot.activeGroupId) + ? snapshot.activeGroupId + : (tabGroups[0]?.id ?? null), + activeTabId: active?.id ?? null, + activeTabType: active?.type ?? null, + tabGroups, + tabs: nextTabs + } + this.mobileSessionTabsByWorktree.set(candidate.worktreeId, nextSnapshot) + this.emitMobileSessionTabsSnapshot(nextSnapshot) + return true + } + onPtyExit(ptyId: string, exitCode: number): void { + const runtimeOwnedExit = this.captureRuntimeOwnedPtyExitCandidate(ptyId) this.advancePtyLifecycleGeneration(ptyId) advertisedUrlWatcher.unbindPty(ptyId) // Clean up new mobile state for this PTY @@ -9326,7 +9715,6 @@ export class OrcaRuntimeService { pty.lastExitCode = exitCode this.resolvePtyExitWaiters(pty, ptyId) this.pruneDisconnectedPtyTranscript(pty) - this.touchMobileSessionSnapshotsForPty(ptyId, { immediate: true }) } for (const leaf of this.getLeavesForPty(ptyId)) { @@ -9337,6 +9725,26 @@ export class OrcaRuntimeService { this.resolveExitWaiters(leaf) this.failActiveDispatchOnExit(leaf, exitCode) } + if (runtimeOwnedExit) { + try { + this.retireRuntimeOwnedPtyExit(runtimeOwnedExit) + } catch (error) { + console.warn('[runtime] failed to retire exited headless terminal leaf:', error) + } + } else { + for (const snapshot of this.mobileSessionTabsByWorktree.values()) { + const containsExitedPty = snapshot.tabs.some( + (tab) => + tab.type === 'terminal' && + (tab.ptyId === ptyId || tab.parentLayout?.ptyIdsByLeafId?.[tab.leafId] === ptyId) + ) + if (containsExitedPty) { + // Why: renderer graph versions remain source-owned. The exit event + // may refresh derived readiness, but must not forge a newer revision. + this.emitMobileSessionTabsSnapshot(snapshot) + } + } + } this.pruneDisconnectedPtyRecords() } @@ -20121,10 +20529,20 @@ export class OrcaRuntimeService { const pty = this.getLivePtyForHandle(handle) if (pty) { const tabId = pty.pty.tabId - if (!tabId) { - throw new Error('terminal_tab_not_found') + const pane = parsePaneKey(pty.pty.paneKey ?? '') + if (!tabId || !pane || pane.tabId !== tabId) { + throw new Error('terminal_handle_stale') } - await this.closeMobileSessionTab(`id:${pty.pty.worktreeId}`, tabId) + const expected: RuntimeTerminalTabCloseExpectation = { + handle, + ptyId: pty.pty.ptyId, + worktreeId: pty.pty.worktreeId, + parentTabId: tabId, + leafId: pane.leafId, + lifecycleGeneration: pty.record.ptyGeneration + } + this.assertCurrentTerminalTabCloseExpectation(expected) + await this.closeMobileSessionTab(`id:${pty.pty.worktreeId}`, tabId, expected) this.claudeAgentTeams.removeTeamForLeaderHandle(handle) return { handle, tabId, closeMode: 'tab', ptyKilled: false } } @@ -20135,6 +20553,43 @@ export class OrcaRuntimeService { return { handle, tabId: leaf.tabId, closeMode: 'tab', ptyKilled: false } } + private assertCurrentTerminalTabCloseExpectation( + expected: RuntimeTerminalTabCloseExpectation + ): void { + const record = this.handles.get(expected.handle) + const pty = this.ptysById.get(expected.ptyId) + const pane = parsePaneKey(pty?.paneKey ?? '') + const snapshot = this.mobileSessionTabsByWorktree.get(expected.worktreeId) + const surface = snapshot?.tabs.find( + (tab): tab is RuntimeMobileSessionTerminalTab => + tab.type === 'terminal' && + tab.parentTabId === expected.parentTabId && + tab.leafId === expected.leafId + ) + const publicSurface = + snapshot && surface + ? this.toMobileSessionTabsResult({ ...snapshot, tabs: [surface] }).tabs[0] + : null + if ( + !record || + record.ptyId !== expected.ptyId || + record.ptyGeneration !== expected.lifecycleGeneration || + !pty?.connected || + pty.worktreeId !== expected.worktreeId || + pty.tabId !== expected.parentTabId || + pane?.tabId !== expected.parentTabId || + pane.leafId !== expected.leafId || + this.getPtyLifecycleGeneration(expected.ptyId) !== expected.lifecycleGeneration || + publicSurface?.type !== 'terminal' || + publicSurface.status !== 'ready' || + publicSurface.terminal !== expected.handle + ) { + // Why: a disconnected generation can retain the same tab/leaf names + // after a replacement binds there; whole-tab close must fail closed. + throw new Error('terminal_handle_stale') + } + } + async splitTerminal( handle: string, opts: { @@ -22008,7 +22463,10 @@ export class OrcaRuntimeService { } } - private syncMobileSessionTabs(snapshots: RuntimeMobileSessionTabsSnapshot[] | undefined): void { + private syncMobileSessionTabs( + snapshots: RuntimeMobileSessionTabsSnapshot[] | undefined, + incomingLeaves: readonly RuntimeSyncedLeaf[] + ): void { if (snapshots === undefined) { return } @@ -22021,7 +22479,12 @@ export class OrcaRuntimeService { for (const snapshot of snapshots) { nextWorktrees.add(snapshot.worktree) const existing = this.mobileSessionTabsByWorktree.get(snapshot.worktree) - const nextSnapshot = this.mergePreservedHeadlessMobileSessionTabs(snapshot, existing) + const filteredSnapshot = this.filterRetiredRuntimeOwnedTerminalTabs( + snapshot, + existing, + incomingLeaves + ) + const nextSnapshot = this.mergePreservedHeadlessMobileSessionTabs(filteredSnapshot, existing) if ( !existing || nextSnapshot.publicationEpoch !== existing.publicationEpoch || @@ -22046,6 +22509,140 @@ export class OrcaRuntimeService { } } + private filterRetiredRuntimeOwnedTerminalTabs( + snapshot: RuntimeMobileSessionTabsSnapshot, + existing: RuntimeMobileSessionTabsSnapshot | undefined, + incomingLeaves: readonly RuntimeSyncedLeaf[] + ): RuntimeMobileSessionTabsSnapshot { + const incomingRendererBindings = new Set( + incomingLeaves + .filter((leaf) => leaf.worktreeId === snapshot.worktree && leaf.ptyId) + .map((leaf) => + this.getRuntimeOwnedTerminalBindingKey({ + worktreeId: leaf.worktreeId, + parentTabId: leaf.tabId, + leafId: leaf.leafId, + ptyId: leaf.ptyId! + }) + ) + ) + const authoritativePersistedPtyByPane = new Map() + for (const tab of existing?.tabs ?? []) { + if (tab.type !== 'terminal') { + continue + } + const ptyId = tab.ptyId ?? tab.parentLayout?.ptyIdsByLeafId?.[tab.leafId] ?? null + if (!ptyId) { + continue + } + const binding = { + worktreeId: snapshot.worktree, + parentTabId: tab.parentTabId, + leafId: tab.leafId, + ptyId + } + if ( + this.isLivePersistedTerminalBinding(binding) || + this.isPersistedRuntimeOwnedTerminalBinding(binding) + ) { + authoritativePersistedPtyByPane.set(JSON.stringify([tab.parentTabId, tab.leafId]), ptyId) + } + } + const tabs = snapshot.tabs.filter((tab) => { + if (tab.type !== 'terminal') { + return true + } + const boundPtyId = tab.ptyId ?? tab.parentLayout?.ptyIdsByLeafId?.[tab.leafId] ?? null + const authoritativePersistedPtyId = authoritativePersistedPtyByPane.get( + JSON.stringify([tab.parentTabId, tab.leafId]) + ) + const incomingBindingKey = boundPtyId + ? this.getRuntimeOwnedTerminalBindingKey({ + worktreeId: snapshot.worktree, + parentTabId: tab.parentTabId, + leafId: tab.leafId, + ptyId: boundPtyId + }) + : null + if ( + authoritativePersistedPtyId && + authoritativePersistedPtyId !== boundPtyId && + (!incomingBindingKey || !incomingRendererBindings.has(incomingBindingKey)) + ) { + // Why: after host restart or tombstone eviction, a stale renderer P1 + // must not shadow durable P2, while an exact live graph P3 can publish + // before the renderer's debounced persistence catches up. + return false + } + if (!boundPtyId) { + return true + } + const incomingBinding = { + worktreeId: snapshot.worktree, + parentTabId: tab.parentTabId, + leafId: tab.leafId, + ptyId: boundPtyId + } + for (const [key, retired] of this.retiredRuntimeOwnedTerminalBindings) { + if ( + retired.worktreeId === snapshot.worktree && + retired.parentTabId === tab.parentTabId && + retired.leafId === tab.leafId && + (retired.ptyId !== boundPtyId || + retired.lifecycleGeneration !== this.getPtyLifecycleGeneration(boundPtyId)) && + this.isLivePersistedTerminalBinding(incomingBinding) + ) { + // Why: only a live, durably rebound P2 can retire the P1 tombstone; + // an unverified renderer graph is not proof of replacement ownership. + this.retiredRuntimeOwnedTerminalBindings.delete(key) + } + } + return !this.retiredRuntimeOwnedTerminalBindings.has( + this.getRuntimeOwnedTerminalBindingKey(incomingBinding) + ) + }) + if (tabs.length === snapshot.tabs.length) { + return snapshot + } + const active = + tabs.find((tab) => tab.id === snapshot.activeTabId) ?? + tabs.find((tab) => tab.isActive) ?? + tabs[0] ?? + null + return { + ...snapshot, + activeTabId: active?.id ?? null, + activeTabType: active?.type ?? null, + tabs: tabs.map((tab) => ({ ...tab, isActive: tab.id === active?.id })) + } + } + + private isLivePersistedTerminalBinding( + binding: Pick + ): boolean { + const pty = this.ptysById.get(binding.ptyId) + const pane = parsePaneKey(pty?.paneKey ?? '') + return ( + pty?.connected === true && + pty.worktreeId === binding.worktreeId && + pty.tabId === binding.parentTabId && + pane?.tabId === binding.parentTabId && + pane.leafId === binding.leafId && + this.store?.getWorkspaceSession?.()?.terminalLayoutsByTabId[binding.parentTabId] + ?.ptyIdsByLeafId?.[binding.leafId] === binding.ptyId + ) + } + + private isPersistedRuntimeOwnedTerminalBinding( + binding: Pick + ): boolean { + return ( + this.isServeOrSshOwnedPtyId(binding.ptyId) && + this.store?.getWorkspaceSession?.()?.terminalLayoutsByTabId[binding.parentTabId] + ?.ptyIdsByLeafId?.[binding.leafId] === binding.ptyId + ) + } + private mergePreservedHeadlessMobileSessionTabs( snapshot: RuntimeMobileSessionTabsSnapshot, existing: RuntimeMobileSessionTabsSnapshot | undefined @@ -22080,7 +22677,9 @@ export class OrcaRuntimeService { snapshot, normalizedPreservedTabs ), - snapshotVersion: Math.max(snapshot.snapshotVersion, existing.snapshotVersion), + // Why: preserved host-owned tabs alter the publication epoch signature, + // not the renderer-owned source revision used to order graph ingestion. + snapshotVersion: snapshot.snapshotVersion, activeGroupId: snapshot.activeGroupId ?? existing.activeGroupId, activeTabId: activeTab?.id ?? null, activeTabType: activeTab?.type ?? null, @@ -23217,7 +23816,10 @@ export class OrcaRuntimeService { if (!pty || pty.ptyId !== record.ptyId) { return null } - // Why: renderer adoption can race with CLI reads; keep ptyId → handle populated so summaries don't mint a second handle for the same terminal. + if (record.ptyGeneration !== this.getPtyLifecycleGeneration(record.ptyId) && pty.connected) { + throw new Error('terminal_handle_stale') + } + // Why: renderer adoption can race with CLI reads; retain the valid synthetic handle so summaries don't mint a duplicate. this.handleByPtyId.set(record.ptyId, handle) return { record, pty } } @@ -23311,6 +23913,7 @@ export class OrcaRuntimeService { } private issuePtyHandle(pty: RuntimePtyWorktreeRecord): string { + const ptyGeneration = this.getPtyLifecycleGeneration(pty.ptyId) const existingHandle = this.handleByPtyId.get(pty.ptyId) ?? this.findHandleForPtyRecord(pty.ptyId) if (existingHandle) { @@ -23318,14 +23921,18 @@ export class OrcaRuntimeService { if ( existingRecord && existingRecord.runtimeId === this.runtimeId && - existingRecord.ptyId === pty.ptyId + existingRecord.ptyId === pty.ptyId && + existingRecord.ptyGeneration === ptyGeneration ) { this.handleByPtyId.set(pty.ptyId, existingHandle) return existingHandle } } - const handle = existingHandle ?? `term_${randomUUID()}` + // Why: a reused provider PTY id is a new destructive-control identity; + // never let its replacement inherit a handle from the exited generation. + const handle = + existingHandle && !this.handles.has(existingHandle) ? existingHandle : `term_${randomUUID()}` const syntheticId = `pty:${pty.ptyId}` this.handles.set(handle, { handle, @@ -23335,7 +23942,7 @@ export class OrcaRuntimeService { tabId: syntheticId, leafId: syntheticId, ptyId: pty.ptyId, - ptyGeneration: 0 + ptyGeneration }) this.handleByPtyId.set(pty.ptyId, handle) return handle diff --git a/src/main/runtime/rpc/methods/session-tabs-schemas.ts b/src/main/runtime/rpc/methods/session-tabs-schemas.ts index beab4b7460ce..0b2f7d14f95a 100644 --- a/src/main/runtime/rpc/methods/session-tabs-schemas.ts +++ b/src/main/runtime/rpc/methods/session-tabs-schemas.ts @@ -25,6 +25,12 @@ export const ActivateTab = WorktreeTabSelector.extend({ notifyClients: OptionalBoolean }) +export const CloseTab = ActivateTab.extend({ + // Why: protocol-v3 clients cannot distinguish user closes from mirror exits; + // requiring explicit intent makes their ambiguous destructive call fail safe. + intent: z.literal('user') +}) + export type TerminalPaneLayoutNodeInput = | { type: 'leaf'; leafId: string } | { diff --git a/src/main/runtime/rpc/methods/session-tabs.test.ts b/src/main/runtime/rpc/methods/session-tabs.test.ts index 55818f3dedcf..5126667270b2 100644 --- a/src/main/runtime/rpc/methods/session-tabs.test.ts +++ b/src/main/runtime/rpc/methods/session-tabs.test.ts @@ -9,6 +9,33 @@ function makeRequest(method: string, params?: unknown): RpcRequest { } describe('session tab RPC methods', () => { + it('rejects ambiguous legacy closes before they reach the runtime', async () => { + const runtime = { + getRuntimeId: () => 'test-runtime', + closeMobileSessionTab: vi.fn() + } as unknown as OrcaRuntimeService + const dispatcher = new RpcDispatcher({ runtime, methods: SESSION_TAB_METHODS }) + + const legacyResponse = await dispatcher.dispatch( + makeRequest('session.tabs.close', { + worktree: 'id:wt-1', + tabId: 'tab-1' + }) + ) + const explicitResponse = await dispatcher.dispatch( + makeRequest('session.tabs.close', { + worktree: 'id:wt-1', + tabId: 'tab-1', + intent: 'user' + }) + ) + + expect(legacyResponse.ok).toBe(false) + expect(explicitResponse.ok).toBe(true) + expect(runtime.closeMobileSessionTab).toHaveBeenCalledTimes(1) + expect(runtime.closeMobileSessionTab).toHaveBeenCalledWith('id:wt-1', 'tab-1') + }) + it('routes mobile-only activation without notifying desktop clients', async () => { const runtime = { getRuntimeId: () => 'test-runtime', diff --git a/src/main/runtime/rpc/methods/session-tabs.ts b/src/main/runtime/rpc/methods/session-tabs.ts index 63929afb2bd6..dd79ee20fd64 100644 --- a/src/main/runtime/rpc/methods/session-tabs.ts +++ b/src/main/runtime/rpc/methods/session-tabs.ts @@ -2,6 +2,7 @@ import { z } from 'zod' import { defineMethod, defineStreamingMethod, type RpcAnyMethod } from '../core' import { ActivateTab, + CloseTab, CreateTerminalTab, MoveTab, SaveMarkdownTab, @@ -34,7 +35,7 @@ export const SESSION_TAB_METHODS: RpcAnyMethod[] = [ }), defineMethod({ name: 'session.tabs.close', - params: ActivateTab, + params: CloseTab, handler: async (params, { runtime }) => runtime.closeMobileSessionTab(params.worktree, params.tabId) }), diff --git a/src/main/window/attach-main-window-services.ts b/src/main/window/attach-main-window-services.ts index 062e848c31d1..4a73673d0b5f 100644 --- a/src/main/window/attach-main-window-services.ts +++ b/src/main/window/attach-main-window-services.ts @@ -356,8 +356,10 @@ function registerRuntimeWindowLifecycle( baseVersion, content }) as Promise, - closeTerminal: (tabId, paneRuntimeId) => send('ui:closeTerminal', { tabId, paneRuntimeId }), - closeTerminalTab: (tabId) => requestTerminalTabCloseFromRenderer(mainWindow, tabId), + closeTerminal: (tabId, paneRuntimeId, options) => + send('ui:closeTerminal', { tabId, paneRuntimeId, ...options }), + closeTerminalTab: (tabId, options) => + requestTerminalTabCloseFromRenderer(mainWindow, tabId, options), sleepWorktree: (worktreeId) => send('ui:sleepWorktree', { worktreeId }), resumeSleepingAgents: (worktreeId) => send('ui:resumeSleepingAgents', { worktreeId }), terminalFitOverrideChanged: (ptyId, mode, cols, rows) => diff --git a/src/main/window/terminal-tab-close-request-relay.test.ts b/src/main/window/terminal-tab-close-request-relay.test.ts index 49eee1ce2995..2709e567fd50 100644 --- a/src/main/window/terminal-tab-close-request-relay.test.ts +++ b/src/main/window/terminal-tab-close-request-relay.test.ts @@ -1,5 +1,9 @@ import { EventEmitter } from 'node:events' import { beforeEach, describe, expect, it, vi } from 'vitest' +import { + TERMINAL_TAB_CLOSE_RENDERER_TIMEOUT_MS, + TERMINAL_TAB_CLOSE_RUNTIME_RPC_TIMEOUT_MS +} from '../../shared/terminal-tab-close' const ipcEmitter = new EventEmitter() const ipcMainMock = { @@ -20,16 +24,32 @@ describe('requestTerminalTabCloseFromRenderer', () => { ipcMainMock.removeListener.mockClear() }) + it('keeps the outer runtime RPC budget above renderer adjudication', () => { + expect(TERMINAL_TAB_CLOSE_RUNTIME_RPC_TIMEOUT_MS).toBeGreaterThan( + TERMINAL_TAB_CLOSE_RENDERER_TIMEOUT_MS + ) + }) + it('waits for the targeted renderer durability acknowledgement', async () => { const { requestTerminalTabCloseFromRenderer } = await import('./terminal-tab-close-request-relay') const webContents = { isDestroyed: () => false, send: vi.fn() } const otherWebContents = {} const mainWindow = { isDestroyed: () => false, webContents } - const pending = requestTerminalTabCloseFromRenderer(mainWindow as never, 'tab-1') - const request = webContents.send.mock.calls[0]?.[1] as { requestId: string; tabId: string } + const pending = requestTerminalTabCloseFromRenderer(mainWindow as never, 'tab-1', { + validateOnly: true, + expectedPtyIds: ['pty-1'] + }) + const request = webContents.send.mock.calls[0]?.[1] as { + requestId: string + tabId: string + validateOnly?: boolean + expectedPtyIds?: string[] + } expect(request.tabId).toBe('tab-1') + expect(request.validateOnly).toBe(true) + expect(request.expectedPtyIds).toEqual(['pty-1']) ipcEmitter.emit( 'ui:terminalTabCloseResponse', { sender: otherWebContents }, diff --git a/src/main/window/terminal-tab-close-request-relay.ts b/src/main/window/terminal-tab-close-request-relay.ts index c788f79a95b4..89600ac55340 100644 --- a/src/main/window/terminal-tab-close-request-relay.ts +++ b/src/main/window/terminal-tab-close-request-relay.ts @@ -2,16 +2,16 @@ import { randomUUID } from 'node:crypto' import { ipcMain } from 'electron' import type { BrowserWindow } from 'electron' +import { TERMINAL_TAB_CLOSE_RENDERER_TIMEOUT_MS } from '../../shared/terminal-tab-close' import type { TerminalTabCloseRequest, TerminalTabCloseResponse } from '../../shared/terminal-tab-close' -const TERMINAL_TAB_CLOSE_TIMEOUT_MS = 20_000 - export async function requestTerminalTabCloseFromRenderer( mainWindow: BrowserWindow, - tabId: string + tabId: string, + options?: { validateOnly?: boolean; expectedPtyIds?: string[] } ): Promise { if (mainWindow.isDestroyed() || mainWindow.webContents.isDestroyed()) { throw new Error('renderer_unavailable') @@ -21,7 +21,7 @@ export async function requestTerminalTabCloseFromRenderer( const timeout = setTimeout(() => { ipcMain.removeListener('ui:terminalTabCloseResponse', onResponse) reject(new Error('terminal_tab_close_timeout')) - }, TERMINAL_TAB_CLOSE_TIMEOUT_MS) + }, TERMINAL_TAB_CLOSE_RENDERER_TIMEOUT_MS) const onResponse = (event: Electron.IpcMainEvent, response: TerminalTabCloseResponse): void => { // Why: request IDs are visible to renderer code; only the selected main // window may commit or reject its lifecycle transaction. @@ -37,7 +37,7 @@ export async function requestTerminalTabCloseFromRenderer( } } ipcMain.on('ui:terminalTabCloseResponse', onResponse) - const request: TerminalTabCloseRequest = { requestId, tabId } + const request: TerminalTabCloseRequest = { requestId, tabId, ...options } mainWindow.webContents.send('ui:terminalTabCloseRequest', request) }) } diff --git a/src/preload/api-types.ts b/src/preload/api-types.ts index b4bb2be8b3b3..caca4b974589 100644 --- a/src/preload/api-types.ts +++ b/src/preload/api-types.ts @@ -2910,7 +2910,12 @@ export type PreloadApi = { ) => () => void respondMobileMarkdownRequest: (response: RuntimeMobileMarkdownResponse) => void onCloseTerminal: ( - callback: (data: { tabId: string; paneRuntimeId?: number }) => void + callback: (data: { + tabId: string + paneRuntimeId?: number + mirrorOnly?: boolean + expectedPtyIds?: string[] + }) => void ) => () => void onTerminalTabCloseRequest: (callback: (request: TerminalTabCloseRequest) => void) => () => void respondTerminalTabClose: (response: TerminalTabCloseResponse) => void diff --git a/src/preload/index.ts b/src/preload/index.ts index eed959cd2cb2..831224b114db 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -3607,11 +3607,21 @@ const api = { ipcRenderer.send('ui:mobileMarkdownResponse', response) }, onCloseTerminal: ( - callback: (data: { tabId: string; paneRuntimeId?: number }) => void + callback: (data: { + tabId: string + paneRuntimeId?: number + mirrorOnly?: boolean + expectedPtyIds?: string[] + }) => void ): (() => void) => { const listener = ( _event: Electron.IpcRendererEvent, - data: { tabId: string; paneRuntimeId?: number } + data: { + tabId: string + paneRuntimeId?: number + mirrorOnly?: boolean + expectedPtyIds?: string[] + } ) => callback(data) ipcRenderer.on('ui:closeTerminal', listener) return () => ipcRenderer.removeListener('ui:closeTerminal', listener) diff --git a/src/renderer/src/components/automations/automation-target-availability.test.ts b/src/renderer/src/components/automations/automation-target-availability.test.ts index 8c9ab713e886..150f438cdcca 100644 --- a/src/renderer/src/components/automations/automation-target-availability.test.ts +++ b/src/renderer/src/components/automations/automation-target-availability.test.ts @@ -1,5 +1,9 @@ import { describe, expect, it } from 'vitest' import type { Automation } from '../../../../shared/automations-types' +import { + MIN_COMPATIBLE_RUNTIME_CLIENT_VERSION, + RUNTIME_PROTOCOL_VERSION +} from '../../../../shared/protocol-version' import type { RuntimeStatus } from '../../../../shared/runtime-types' import type { ProjectHostSetup, Repo, Worktree } from '../../../../shared/types' import { getAutomationTargetAvailability } from './automation-target-availability' @@ -78,8 +82,8 @@ function makeRuntimeStatus(overrides: Partial = {}): RuntimeStatu authoritativeWindowId: null, liveTabCount: 0, liveLeafCount: 0, - runtimeProtocolVersion: 3, - minCompatibleRuntimeClientVersion: 2, + runtimeProtocolVersion: RUNTIME_PROTOCOL_VERSION, + minCompatibleRuntimeClientVersion: MIN_COMPATIBLE_RUNTIME_CLIENT_VERSION, ...overrides } } diff --git a/src/renderer/src/components/sidebar/sidebar-host-options.test.ts b/src/renderer/src/components/sidebar/sidebar-host-options.test.ts index 454268c24c4d..41118ba08236 100644 --- a/src/renderer/src/components/sidebar/sidebar-host-options.test.ts +++ b/src/renderer/src/components/sidebar/sidebar-host-options.test.ts @@ -1,5 +1,9 @@ import { describe, expect, it } from 'vitest' import { getExecutionHostLabel } from '../../../../shared/execution-host' +import { + MIN_COMPATIBLE_RUNTIME_CLIENT_VERSION, + RUNTIME_PROTOCOL_VERSION +} from '../../../../shared/protocol-version' import { buildSidebarHostOptions, buildSidebarHostScopeOptions, @@ -155,8 +159,8 @@ describe('sidebar host options', () => { authoritativeWindowId: null, liveTabCount: 0, liveLeafCount: 0, - runtimeProtocolVersion: 3, - minCompatibleRuntimeClientVersion: 3 + runtimeProtocolVersion: RUNTIME_PROTOCOL_VERSION, + minCompatibleRuntimeClientVersion: MIN_COMPATIBLE_RUNTIME_CLIENT_VERSION } } ] diff --git a/src/renderer/src/components/tab-group/useTabGroupWorkspaceModel.focus.test.ts b/src/renderer/src/components/tab-group/useTabGroupWorkspaceModel.focus.test.ts index da137c5d6af6..e547261121b0 100644 --- a/src/renderer/src/components/tab-group/useTabGroupWorkspaceModel.focus.test.ts +++ b/src/renderer/src/components/tab-group/useTabGroupWorkspaceModel.focus.test.ts @@ -10,6 +10,7 @@ const mocks = vi.hoisted(() => ({ closeTab: vi.fn(), closeUnifiedTab: vi.fn(), closeWebRuntimeSessionTab: vi.fn(), + closeWebRuntimeTerminalTab: vi.fn(), createBrowserTab: vi.fn(), createEmptySplitGroup: vi.fn(), createTab: vi.fn(), @@ -70,6 +71,7 @@ vi.mock('../../lib/focus-terminal-tab-surface', () => ({ vi.mock('../../runtime/web-runtime-session', () => ({ activateWebRuntimeSessionTab: mocks.activateWebRuntimeSessionTab, closeWebRuntimeSessionTab: mocks.closeWebRuntimeSessionTab, + closeWebRuntimeTerminalTab: mocks.closeWebRuntimeTerminalTab, createWebRuntimeSessionBrowserTab: vi.fn(), createWebRuntimeSessionTerminal: vi.fn(), isWebRuntimeSessionActive: mocks.isWebRuntimeSessionActive, @@ -134,7 +136,11 @@ function resetStore(): void { reconcileWorktreeTabModel: vi.fn(() => ({ renderableTabCount: 0 })), settings: { activeRuntimeEnvironmentId: null }, tabsByWorktree: { 'wt-1': [terminalTab] }, + ptyIdsByTabId: { 'terminal-1': ['pty-1'] }, terminalLayoutsByTabId: {}, + lastKnownRelayPtyIdByTabId: {}, + deferredSshSessionIdsByTabId: {}, + pendingReconnectPtyIdByTabId: {}, unifiedTabsByWorktree: { 'wt-1': [unifiedTab] }, activateTab: mocks.activateTab, closeBrowserTab: mocks.closeBrowserTab, @@ -293,10 +299,10 @@ describe('useTabGroupWorkspaceModel terminal activation focus', () => { 'terminal-2', expect.objectContaining({ remoteCloseOwnedByHost: true }) ) - expect(mocks.closeWebRuntimeSessionTab).toHaveBeenCalledWith({ + expect(mocks.closeWebRuntimeTerminalTab).toHaveBeenCalledWith({ worktreeId: 'wt-1', - tabId: 'terminal-2', - environmentId: 'env-1' + environmentId: 'env-1', + terminal: 'pty-2' }) }) diff --git a/src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.test.ts b/src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.test.ts index 09d163012d34..e2d2fbb786e6 100644 --- a/src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.test.ts +++ b/src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.test.ts @@ -428,10 +428,12 @@ describe('createRemoteRuntimePtyTransport', () => { it('does not close host-owned terminal handles attached from session snapshots', async () => { const { createRemoteRuntimePtyTransport } = await import('./remote-runtime-pty-transport') + const onPtyExit = vi.fn() const transport = createRemoteRuntimePtyTransport('env-1', { worktreeId: 'wt-1', tabId: 'web-terminal-tab-1', - leafId: 'pane:1' + leafId: 'pane:1', + onPtyExit }) transport.attach({ @@ -450,14 +452,17 @@ describe('createRemoteRuntimePtyTransport', () => { method: 'terminal.close' }) ) + expect(onPtyExit).not.toHaveBeenCalled() }) it('detaches laptop-created remote runtime terminals without closing the server session', async () => { const { createRemoteRuntimePtyTransport } = await import('./remote-runtime-pty-transport') + const onPtyExit = vi.fn() const transport = createRemoteRuntimePtyTransport('env-1', { worktreeId: 'wt-1', tabId: 'tab-1', - leafId: 'pane:1' + leafId: 'pane:1', + onPtyExit }) await transport.connect({ url: '', callbacks: {} }) @@ -471,6 +476,7 @@ describe('createRemoteRuntimePtyTransport', () => { method: 'terminal.close' }) ) + expect(onPtyExit).not.toHaveBeenCalled() }) it('keeps the regular TUI and draft through inventory failure and stale-handle reconnect', async () => { diff --git a/src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts b/src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts index af519bf240d9..94b353ad2a24 100644 --- a/src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts +++ b/src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts @@ -876,14 +876,12 @@ export function createRemoteRuntimePtyTransport( } connected = false clearPendingViewportClaim() - const id = remotePtyId closeMultiplexedStream() handle = null remotePtyId = null storedCallbacks.onDisconnect?.() - if (id) { - onPtyExit?.(id) - } + // Why: this transport only owns a viewer. Runtime switches and pane + // unmounts must unsubscribe without masquerading as host PTY exit. }, detach() { diff --git a/src/renderer/src/components/terminal/terminal-tab-actions.test.ts b/src/renderer/src/components/terminal/terminal-tab-actions.test.ts index 7c7bb511efc0..341d3775dd2a 100644 --- a/src/renderer/src/components/terminal/terminal-tab-actions.test.ts +++ b/src/renderer/src/components/terminal/terminal-tab-actions.test.ts @@ -3,6 +3,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' const { activateWebRuntimeSessionTabMock, closeWebRuntimeSessionTabMock, + closeWebRuntimeTerminalTabMock, createWebRuntimeSessionTerminalMock, getStateMock, isWebRuntimeSessionActiveMock, @@ -12,6 +13,7 @@ const { } = vi.hoisted(() => ({ activateWebRuntimeSessionTabMock: vi.fn(), closeWebRuntimeSessionTabMock: vi.fn(), + closeWebRuntimeTerminalTabMock: vi.fn(), createWebRuntimeSessionTerminalMock: vi.fn(), getStateMock: vi.fn(), isWebRuntimeSessionActiveMock: vi.fn(), @@ -29,6 +31,7 @@ vi.mock('@/store', () => ({ vi.mock('@/runtime/web-runtime-session', () => ({ activateWebRuntimeSessionTab: activateWebRuntimeSessionTabMock, closeWebRuntimeSessionTab: closeWebRuntimeSessionTabMock, + closeWebRuntimeTerminalTab: closeWebRuntimeTerminalTabMock, createWebRuntimeSessionTerminal: createWebRuntimeSessionTerminalMock, isWebRuntimeSessionActive: isWebRuntimeSessionActiveMock, isWebTerminalSurfaceTabId: isWebTerminalSurfaceTabIdMock, @@ -180,15 +183,24 @@ describe('closeTerminalTab', () => { isWebTerminalSurfaceTabIdMock.mockReturnValue(false) }) - it('delegates host-backed terminal closes to the paired runtime', () => { + it('delegates ready host-backed terminal closes through their exact handle', () => { const closeTab = vi.fn() isWebRuntimeSessionActiveMock.mockReturnValue(true) resolveHostSessionTabIdForWebSessionTabMock.mockReturnValue('host-tab-1') getStateMock.mockReturnValue({ settings: { activeRuntimeEnvironmentId: 'web-runtime' }, tabsByWorktree: { - 'wt-1': [{ id: 'local-tab-1' }, { id: 'local-tab-2' }] + 'wt-1': [ + { id: 'local-tab-1', ptyId: 'remote:web-runtime@@terminal-1' }, + { id: 'local-tab-2' } + ] }, + unifiedTabsByWorktree: {}, + ptyIdsByTabId: { 'local-tab-1': ['remote:web-runtime@@terminal-1'] }, + terminalLayoutsByTabId: {}, + lastKnownRelayPtyIdByTabId: {}, + deferredSshSessionIdsByTabId: {}, + pendingReconnectPtyIdByTabId: {}, activeWorktreeId: 'wt-1', activeTabId: 'local-tab-1', closeTab, @@ -199,13 +211,20 @@ describe('closeTerminalTab', () => { expect(closeTab).toHaveBeenCalledWith('local-tab-1', { reason: undefined, - remoteCloseOwnedByHost: true + remoteCloseOwnedByHost: true, + precomputedRetirementPlan: expect.objectContaining({ + tabId: 'local-tab-1', + runtimeTerminals: [ + expect.objectContaining({ environmentId: 'web-runtime', handle: 'terminal-1' }) + ] + }) }) - expect(closeWebRuntimeSessionTabMock).toHaveBeenCalledWith({ + expect(closeWebRuntimeTerminalTabMock).toHaveBeenCalledWith({ + environmentId: 'web-runtime', worktreeId: 'wt-1', - tabId: 'host-tab-1', - environmentId: 'web-runtime' + terminal: 'terminal-1' }) + expect(closeWebRuntimeSessionTabMock).not.toHaveBeenCalled() }) it('closes unified-only terminal tabs when tabsByWorktree is missing the row', () => { @@ -317,6 +336,12 @@ describe('closeTerminalTab', () => { tabsByWorktree: { 'wt-1': [{ id: 'plain-uuid-tab' }, { id: 'local-tab-2' }] }, + unifiedTabsByWorktree: {}, + ptyIdsByTabId: {}, + terminalLayoutsByTabId: {}, + lastKnownRelayPtyIdByTabId: {}, + deferredSshSessionIdsByTabId: {}, + pendingReconnectPtyIdByTabId: {}, activeWorktreeId: 'wt-1', activeTabId: 'plain-uuid-tab', openFiles: [], @@ -328,7 +353,11 @@ describe('closeTerminalTab', () => { expect(closeTab).toHaveBeenCalledWith('plain-uuid-tab', { reason: undefined, - remoteCloseOwnedByHost: true + remoteCloseOwnedByHost: true, + precomputedRetirementPlan: expect.objectContaining({ + tabId: 'plain-uuid-tab', + runtimeTerminals: [] + }) }) expect(closeWebRuntimeSessionTabMock).toHaveBeenCalledWith({ worktreeId: 'wt-1', @@ -337,6 +366,38 @@ describe('closeTerminalTab', () => { }) }) + it('keeps a remote PTY-exit observation local without sending a close RPC', () => { + const closeTab = vi.fn() + isWebRuntimeSessionActiveMock.mockReturnValue(true) + getStateMock.mockReturnValue({ + settings: { activeRuntimeEnvironmentId: 'web-runtime' }, + tabsByWorktree: { + 'wt-1': [{ id: 'local-tab-1', ptyId: 'remote:web-runtime@@terminal-1' }] + }, + unifiedTabsByWorktree: {}, + ptyIdsByTabId: { 'local-tab-1': ['remote:web-runtime@@terminal-1'] }, + terminalLayoutsByTabId: {}, + lastKnownRelayPtyIdByTabId: {}, + deferredSshSessionIdsByTabId: {}, + pendingReconnectPtyIdByTabId: {}, + activeWorktreeId: 'wt-1', + activeTabId: 'local-tab-1', + openFiles: [], + browserTabsByWorktree: {}, + closeTab, + setActiveTab: vi.fn() + }) + + closeTerminalTab('local-tab-1', { reason: 'pty-exit' }) + + expect(closeTab).toHaveBeenCalledWith( + 'local-tab-1', + expect.objectContaining({ reason: 'pty-exit', remoteCloseOwnedByHost: true }) + ) + expect(closeWebRuntimeTerminalTabMock).not.toHaveBeenCalled() + expect(closeWebRuntimeSessionTabMock).not.toHaveBeenCalled() + }) + function makePinnedTabState( overrides: { confirmClosePinnedTab: boolean } & Record ): Record { @@ -581,6 +642,16 @@ describe('closeOtherTerminalTabs', () => { tabsByWorktree: { 'wt-1': [{ id: 'keep' }, { id: 'close-a' }, { id: 'close-b' }] }, + unifiedTabsByWorktree: {}, + ptyIdsByTabId: {}, + terminalLayoutsByTabId: {}, + lastKnownRelayPtyIdByTabId: {}, + deferredSshSessionIdsByTabId: {}, + pendingReconnectPtyIdByTabId: {}, + activeWorktreeId: 'wt-1', + activeTabId: 'keep', + openFiles: [], + browserTabsByWorktree: {}, setActiveTab, closeTab }) @@ -599,7 +670,7 @@ describe('closeOtherTerminalTabs', () => { tabId: 'close-b', environmentId: 'web-runtime' }) - expect(closeTab).not.toHaveBeenCalled() + expect(closeTab).toHaveBeenCalledTimes(2) }) }) @@ -613,19 +684,26 @@ describe('closeTerminalTabsToRight', () => { const closeTab = vi.fn() const closeFile = vi.fn() isWebRuntimeSessionActiveMock.mockReturnValue(true) - getStateMock - .mockReturnValueOnce({ - settings: { activeRuntimeEnvironmentId: 'web-runtime' }, - tabsByWorktree: { - 'wt-1': [{ id: 'term-a' }, { id: 'term-b' }, { id: 'term-c' }] - }, - openFiles: [{ id: 'file-b', worktreeId: 'wt-1' }], - tabBarOrderByWorktree: { 'wt-1': ['term-a', 'file-b', 'term-b', 'term-c'] }, - closeTab - }) - .mockReturnValue({ - closeFile - }) + getStateMock.mockReturnValue({ + settings: { activeRuntimeEnvironmentId: 'web-runtime' }, + tabsByWorktree: { + 'wt-1': [{ id: 'term-a' }, { id: 'term-b' }, { id: 'term-c' }] + }, + unifiedTabsByWorktree: {}, + ptyIdsByTabId: {}, + terminalLayoutsByTabId: {}, + lastKnownRelayPtyIdByTabId: {}, + deferredSshSessionIdsByTabId: {}, + pendingReconnectPtyIdByTabId: {}, + activeWorktreeId: 'wt-1', + activeTabId: 'term-a', + openFiles: [{ id: 'file-b', worktreeId: 'wt-1' }], + browserTabsByWorktree: {}, + tabBarOrderByWorktree: { 'wt-1': ['term-a', 'file-b', 'term-b', 'term-c'] }, + closeTab, + closeFile, + setActiveTab: vi.fn() + }) closeTerminalTabsToRight('term-a', 'wt-1') @@ -641,6 +719,6 @@ describe('closeTerminalTabsToRight', () => { environmentId: 'web-runtime' }) expect(closeFile).toHaveBeenCalledWith('file-b') - expect(closeTab).not.toHaveBeenCalled() + expect(closeTab).toHaveBeenCalledTimes(2) }) }) diff --git a/src/renderer/src/components/terminal/terminal-tab-actions.ts b/src/renderer/src/components/terminal/terminal-tab-actions.ts index ebd861e6952e..dbef5e8f68a8 100644 --- a/src/renderer/src/components/terminal/terminal-tab-actions.ts +++ b/src/renderer/src/components/terminal/terminal-tab-actions.ts @@ -5,15 +5,17 @@ import { reconcileTabOrder } from '../tab-bar/reconcile-order' import { activateWebRuntimeSessionTab, closeWebRuntimeSessionTab, + closeWebRuntimeTerminalTab, isWebRuntimeSessionActive, toHostSessionTabId } from '@/runtime/web-runtime-session' import { resolveHostSessionTabIdForWebSessionTab } from '@/runtime/web-session-tabs-sync' import { getRuntimeEnvironmentIdForWorktree } from '@/lib/worktree-runtime-owner' import { guardPinnedTabClose, resolvePinnedTabLabel } from '@/store/pinned-tab-close-guard' -import type { - TerminalTabCloseReason, - TerminalTabRetirementPlan +import { + buildTerminalTabRetirementPlan, + type TerminalTabCloseReason, + type TerminalTabRetirementPlan } from '@/store/slices/terminal-tab-retirement' import { closeLocalTerminalTabState } from './close-local-terminal-tab-state' import { @@ -96,15 +98,17 @@ export function closeTerminalTab( const runtimeEnvironmentId = getRuntimeEnvironmentIdForWorktree(state, owningWorktreeId) if (runtimeEnvironmentId && isWebRuntimeSessionActive(runtimeEnvironmentId)) { - // Why: a remote-owned worktree's tabs are host-authoritative, so the close - // MUST reach the host or its next snapshot re-adds the tab (the "close then - // snaps back" bug). When the local→host map has no entry, decode the id - // itself (toHostSessionTabId is a no-op for non-mirrored host ids like plain - // UUIDs) — mirroring what activate/move do. The old - // `isWebTerminalSurfaceTabId ? id : null` gate returned null for plain-UUID - // host tabs, so close silently fell back to a local-only prune and the host's - // next snapshot re-added the tab. A truly local id the host doesn't know is - // harmless: the host close no-ops and the local prune still stands. + const retirementPlan = + options?.precomputedRetirementPlan?.tabId === terminalTabId + ? options.precomputedRetirementPlan + : buildTerminalTabRetirementPlan(state, terminalTabId) + const runtimeTerminal = + retirementPlan.runtimeTerminals.find( + (terminal) => !terminal.environmentId || terminal.environmentId === runtimeEnvironmentId + ) ?? retirementPlan.runtimeTerminals[0] + // Why: pending surfaces have no generation-bound terminal handle yet. A + // user close may still dismiss them by host tab id, but lifecycle exits + // never send either destructive RPC. const hostBackedTabId = resolveHostSessionTabIdForWebSessionTab(state, { environmentId: runtimeEnvironmentId, @@ -122,15 +126,23 @@ export function closeTerminalTab( ...(options?.localPtyTeardownOwnedExternally ? { localPtyTeardownOwnedExternally: true } : {}), - ...(options?.precomputedRetirementPlan - ? { precomputedRetirementPlan: options.precomputedRetirementPlan } - : {}) - }) - void closeWebRuntimeSessionTab({ - worktreeId: owningWorktreeId, - tabId: hostBackedTabId, - environmentId: runtimeEnvironmentId + precomputedRetirementPlan: retirementPlan }) + if (options?.reason !== 'pty-exit') { + if (runtimeTerminal) { + closeWebRuntimeTerminalTab({ + environmentId: runtimeTerminal.environmentId ?? runtimeEnvironmentId, + worktreeId: owningWorktreeId, + terminal: runtimeTerminal.handle + }) + } else { + void closeWebRuntimeSessionTab({ + worktreeId: owningWorktreeId, + tabId: hostBackedTabId, + environmentId: runtimeEnvironmentId + }) + } + } options?.onClosed?.() return } @@ -213,13 +225,7 @@ export function closeOtherTerminalTabs(tabId: string, activeWorktreeId: string | continue } if (closeHostTerminalTabs) { - // Why: paired web tabs are host-owned; local-only bulk close leaves - // the host to re-publish the supposedly closed terminal tabs. - void closeWebRuntimeSessionTab({ - worktreeId: activeWorktreeId, - tabId: tab.id, - environmentId: runtimeEnvironmentId - }) + closeTerminalTab(tab.id) } else { state.closeTab(tab.id) } @@ -256,13 +262,7 @@ export function closeTerminalTabsToRight(tabId: string, activeWorktreeId: string } if (terminalIdSet.has(id)) { if (closeHostTerminalTabs) { - // Why: paired web tabs are host-owned; local-only bulk close leaves - // the host to re-publish the supposedly closed terminal tabs. - void closeWebRuntimeSessionTab({ - worktreeId: activeWorktreeId, - tabId: id, - environmentId: runtimeEnvironmentId - }) + closeTerminalTab(id) } else { state.closeTab(id) } diff --git a/src/renderer/src/hooks/useIpcEvents.test.ts b/src/renderer/src/hooks/useIpcEvents.test.ts index 40e598417515..7b220f180305 100644 --- a/src/renderer/src/hooks/useIpcEvents.test.ts +++ b/src/renderer/src/hooks/useIpcEvents.test.ts @@ -2818,9 +2818,19 @@ describe('useIpcEvents browser tab close routing', () => { worktreeId?: string }) => void type CloseActiveTabListener = () => void - type CloseTerminalListener = (data: { tabId: string; paneRuntimeId?: number | null }) => void + type CloseTerminalListener = (data: { + tabId: string + paneRuntimeId?: number | null + mirrorOnly?: boolean + expectedPtyIds?: string[] + }) => void type CloseSessionTabListener = (data: { tabId: string; worktreeId: string }) => void - type TerminalTabCloseRequestListener = (data: { requestId: string; tabId: string }) => void + type TerminalTabCloseRequestListener = (data: { + requestId: string + tabId: string + validateOnly?: boolean + expectedPtyIds?: string[] + }) => void async function useIpcEventsForCloseRouting({ closeActiveTabListenerRef, @@ -3132,6 +3142,147 @@ describe('useIpcEvents browser tab close routing', () => { expect(closeTerminalTabMock).toHaveBeenCalledWith('terminal-1') }) + it('prunes only the exact renderer mirror after main commits terminal teardown', async () => { + const closeTerminalListenerRef: { current: CloseTerminalListener | null } = { current: null } + await useIpcEventsForCloseRouting({ + closeTerminalListenerRef, + getState: () => ({ + settings: { activeRuntimeEnvironmentId: null, terminalFontSize: 13 }, + tabsByWorktree: { 'wt-1': [{ id: 'terminal-1', ptyId: 'pty-1' }] }, + ptyIdsByTabId: { 'terminal-1': ['pty-1'] }, + terminalLayoutsByTabId: { 'terminal-1': { ptyIdsByLeafId: { leaf: 'pty-1' } } }, + lastKnownRelayPtyIdByTabId: { 'terminal-1': 'pty-retained-alias' }, + deferredSshSessionIdsByTabId: {}, + pendingReconnectPtyIdByTabId: {} + }) + }) + + closeTerminalListenerRef.current?.({ + tabId: 'terminal-1', + mirrorOnly: true, + expectedPtyIds: ['pty-1'] + }) + + expect(closeTerminalTabMock).toHaveBeenCalledWith( + 'terminal-1', + expect.objectContaining({ + reason: 'pty-exit', + captureRecentlyClosed: false, + localPtyTeardownOwnedExternally: true + }) + ) + }) + + it('ignores a mirror prune after the renderer binding has changed', async () => { + const closeTerminalListenerRef: { current: CloseTerminalListener | null } = { current: null } + await useIpcEventsForCloseRouting({ + closeTerminalListenerRef, + getState: () => ({ + settings: { activeRuntimeEnvironmentId: null, terminalFontSize: 13 }, + tabsByWorktree: { 'wt-1': [{ id: 'terminal-1', ptyId: 'pty-replacement' }] }, + ptyIdsByTabId: { 'terminal-1': ['pty-replacement'] }, + terminalLayoutsByTabId: { + 'terminal-1': { ptyIdsByLeafId: { leaf: 'pty-replacement' } } + }, + lastKnownRelayPtyIdByTabId: { 'terminal-1': 'pty-retained-alias' }, + deferredSshSessionIdsByTabId: {}, + pendingReconnectPtyIdByTabId: {} + }) + }) + + closeTerminalListenerRef.current?.({ + tabId: 'terminal-1', + mirrorOnly: true, + expectedPtyIds: ['pty-old'] + }) + + expect(closeTerminalTabMock).not.toHaveBeenCalled() + }) + + it('validates an exact unpinned terminal binding without mutating renderer state', async () => { + const listenerRef: { current: TerminalTabCloseRequestListener | null } = { current: null } + const persistWorkspaceSession = vi.fn().mockResolvedValue(undefined) + const respondTerminalTabClose = vi.fn() + await useIpcEventsForCloseRouting({ + getState: () => ({ + tabsByWorktree: { 'wt-1': [{ id: 'terminal-1', ptyId: 'pty-1' }] }, + unifiedTabsByWorktree: { + 'wt-1': [ + { + id: 'unified-terminal-1', + entityId: 'terminal-1', + contentType: 'terminal', + isPinned: false + } + ] + }, + ptyIdsByTabId: { 'terminal-1': ['pty-1'] }, + terminalLayoutsByTabId: { + 'terminal-1': { ptyIdsByLeafId: { leaf: 'pty-1' } } + }, + lastKnownRelayPtyIdByTabId: { 'terminal-1': 'pty-retained-alias' }, + deferredSshSessionIdsByTabId: {}, + pendingReconnectPtyIdByTabId: {} + }), + terminalTabCloseRequestListenerRef: listenerRef, + respondTerminalTabClose, + persistWorkspaceSession + }) + + listenerRef.current?.({ + requestId: 'validate-1', + tabId: 'terminal-1', + validateOnly: true, + expectedPtyIds: ['pty-1'] + }) + + expect(respondTerminalTabClose).toHaveBeenCalledWith({ requestId: 'validate-1' }) + expect(closeTerminalTabMock).not.toHaveBeenCalled() + expect(persistWorkspaceSession).not.toHaveBeenCalled() + }) + + it('rejects validation when the renderer terminal binding has changed', async () => { + const listenerRef: { current: TerminalTabCloseRequestListener | null } = { current: null } + const respondTerminalTabClose = vi.fn() + await useIpcEventsForCloseRouting({ + getState: () => ({ + tabsByWorktree: { 'wt-1': [{ id: 'terminal-1', ptyId: 'pty-replacement' }] }, + unifiedTabsByWorktree: { + 'wt-1': [ + { + id: 'unified-terminal-1', + entityId: 'terminal-1', + contentType: 'terminal', + isPinned: false + } + ] + }, + ptyIdsByTabId: { 'terminal-1': ['pty-replacement'] }, + terminalLayoutsByTabId: { + 'terminal-1': { ptyIdsByLeafId: { leaf: 'pty-replacement' } } + }, + lastKnownRelayPtyIdByTabId: {}, + deferredSshSessionIdsByTabId: {}, + pendingReconnectPtyIdByTabId: {} + }), + terminalTabCloseRequestListenerRef: listenerRef, + respondTerminalTabClose + }) + + listenerRef.current?.({ + requestId: 'validate-stale', + tabId: 'terminal-1', + validateOnly: true, + expectedPtyIds: ['pty-old'] + }) + + expect(respondTerminalTabClose).toHaveBeenCalledWith({ + requestId: 'validate-stale', + error: 'terminal_handle_stale' + }) + expect(closeTerminalTabMock).not.toHaveBeenCalled() + }) + it('acknowledges whole-tab close only after the fresh session is durably persisted', async () => { const listenerRef: { current: TerminalTabCloseRequestListener | null } = { current: null } let finishPersist!: () => void diff --git a/src/renderer/src/hooks/useIpcEvents.ts b/src/renderer/src/hooks/useIpcEvents.ts index eeadaed9deac..5af2e1f33779 100644 --- a/src/renderer/src/hooks/useIpcEvents.ts +++ b/src/renderer/src/hooks/useIpcEvents.ts @@ -131,6 +131,10 @@ import { getRuntimeEnvironmentIdForWorktree } from '@/lib/worktree-runtime-owner import { resolveAgentPaneAuthorityKey } from '@/store/slices/agent-pane-authority' import { translate } from '@/i18n/i18n' import { closeTerminalTab } from '@/components/terminal/terminal-tab-actions' +import { + buildTerminalTabRetirementPlan, + collectCurrentTerminalPtyIdsForTab +} from '@/store/slices/terminal-tab-retirement' import { initialAgentTabViewModeProps } from '@/lib/native-chat-initial-view-mode' import { getConnectionIdFromState } from '@/lib/connection-context' import { isNativeChatTranscriptLocalReadable } from '@/lib/native-chat-transcript-readability' @@ -1910,7 +1914,27 @@ export function useIpcEvents(): void { ) unsubs.push( - window.api.ui.onCloseTerminal(({ tabId, paneRuntimeId }) => { + window.api.ui.onCloseTerminal(({ tabId, paneRuntimeId, mirrorOnly, expectedPtyIds = [] }) => { + if (mirrorOnly) { + const state = useAppStore.getState() + const retirementPlan = buildTerminalTabRetirementPlan(state, tabId) + const currentPtyIds = new Set(collectCurrentTerminalPtyIdsForTab(state, tabId)) + if ( + currentPtyIds.size !== expectedPtyIds.length || + expectedPtyIds.some((ptyId) => !currentPtyIds.has(ptyId)) + ) { + return + } + // Why: main already committed the generation-checked provider + // teardown; renderer only prunes the matching local mirror. + closeTerminalTab(tabId, { + reason: 'pty-exit', + captureRecentlyClosed: false, + localPtyTeardownOwnedExternally: true, + precomputedRetirementPlan: retirementPlan + }) + return + } if (paneRuntimeId != null) { // Why: route pane closes via the lifecycle hook for sibling promotion (falls through to closeTab on the last pane). const detail: CloseTerminalPaneDetail = { tabId, paneRuntimeId } @@ -1924,33 +1948,53 @@ export function useIpcEvents(): void { // Why: during an in-place renderer reload an older preload can linger; keep this listener additive at that seam. if (window.api.ui.onTerminalTabCloseRequest) { unsubs.push( - window.api.ui.onTerminalTabCloseRequest(({ requestId, tabId }) => { - let responded = false - const respond = (error?: string): void => { - if (responded) { - return + window.api.ui.onTerminalTabCloseRequest( + ({ requestId, tabId, validateOnly, expectedPtyIds = [] }) => { + let responded = false + const respond = (error?: string): void => { + if (responded) { + return + } + responded = true + window.api.ui.respondTerminalTabClose({ requestId, ...(error ? { error } : {}) }) } - responded = true - window.api.ui.respondTerminalTabClose({ requestId, ...(error ? { error } : {}) }) - } - closeTerminalTab(tabId, { - rejectPinned: true, - onCancel: () => respond('terminal_tab_pinned'), - onClosed: () => { - void (async () => { - const state = useAppStore.getState() - await persistWorkspaceSessionByHost( - window.api.session, - buildWorkspaceSessionPayload(state), - state - ) + if (validateOnly) { + const state = useAppStore.getState() + const retirementPlan = buildTerminalTabRetirementPlan(state, tabId) + const currentPtyIds = new Set(collectCurrentTerminalPtyIdsForTab(state, tabId)) + if (!retirementPlan.worktreeId) { + respond('terminal_tab_not_found') + } else if ( + currentPtyIds.size !== expectedPtyIds.length || + expectedPtyIds.some((ptyId) => !currentPtyIds.has(ptyId)) + ) { + respond('terminal_handle_stale') + } else if (isPinnedSessionTab(state, retirementPlan.worktreeId, tabId)) { + respond('terminal_tab_pinned') + } else { respond() - })().catch((error: unknown) => { - respond(error instanceof Error ? error.message : 'terminal_tab_close_failed') - }) + } + return } - }) - }) + closeTerminalTab(tabId, { + rejectPinned: true, + onCancel: () => respond('terminal_tab_pinned'), + onClosed: () => { + void (async () => { + const state = useAppStore.getState() + await persistWorkspaceSessionByHost( + window.api.session, + buildWorkspaceSessionPayload(state), + state + ) + respond() + })().catch((error: unknown) => { + respond(error instanceof Error ? error.message : 'terminal_tab_close_failed') + }) + } + }) + } + ) ) } diff --git a/src/renderer/src/lib/windows-terminal-capabilities.test.ts b/src/renderer/src/lib/windows-terminal-capabilities.test.ts index 18f00b5b44c9..e0ca21420279 100644 --- a/src/renderer/src/lib/windows-terminal-capabilities.test.ts +++ b/src/renderer/src/lib/windows-terminal-capabilities.test.ts @@ -3,6 +3,10 @@ import { act, createElement } from 'react' import { createRoot, type Root } from 'react-dom/client' import { afterEach, describe, expect, it, vi } from 'vitest' +import { + MIN_COMPATIBLE_RUNTIME_CLIENT_VERSION, + RUNTIME_PROTOCOL_VERSION +} from '../../../shared/protocol-version' import { getCachedWindowsTerminalCapabilities, getWindowsTerminalCapabilityOwnerKey, @@ -216,8 +220,8 @@ describe('windows terminal capabilities', () => { const resultByMethod: Record = { 'status.get': { hostPlatform: 'win32', - runtimeProtocolVersion: 3, - minCompatibleRuntimeClientVersion: 2 + runtimeProtocolVersion: RUNTIME_PROTOCOL_VERSION, + minCompatibleRuntimeClientVersion: MIN_COMPATIBLE_RUNTIME_CLIENT_VERSION }, 'host.wsl.isAvailable': true, 'host.wsl.listDistros': ['Ubuntu'], @@ -391,8 +395,8 @@ describe('windows terminal capabilities', () => { const resultByMethod: Record = { 'status.get': { hostPlatform: 'linux', - runtimeProtocolVersion: 3, - minCompatibleRuntimeClientVersion: 2 + runtimeProtocolVersion: RUNTIME_PROTOCOL_VERSION, + minCompatibleRuntimeClientVersion: MIN_COMPATIBLE_RUNTIME_CLIENT_VERSION }, 'preflight.detectRemoteWindowsTerminalCapabilities': { wslAvailable: true, diff --git a/src/renderer/src/runtime/runtime-rpc-call-error.ts b/src/renderer/src/runtime/runtime-rpc-call-error.ts new file mode 100644 index 000000000000..6eae09f2642b --- /dev/null +++ b/src/renderer/src/runtime/runtime-rpc-call-error.ts @@ -0,0 +1,19 @@ +import type { RuntimeRpcFailure } from '../../../shared/runtime-rpc-envelope' + +export class RuntimeRpcCallError extends Error { + readonly code: string + readonly response: RuntimeRpcFailure + + constructor(response: RuntimeRpcFailure) { + super(response.error.message) + this.name = 'RuntimeRpcCallError' + this.code = response.error.code + this.response = response + } +} + +// Why: mobile-scope device tokens are denied non-allowlisted runtime methods +// with code 'forbidden'. Callers use this to surface one scope-mismatch banner. +export function isRuntimeScopeForbiddenError(error: unknown): boolean { + return error instanceof RuntimeRpcCallError && error.code === 'forbidden' +} diff --git a/src/renderer/src/runtime/runtime-rpc-client.ts b/src/renderer/src/runtime/runtime-rpc-client.ts index 1f024c1a67f3..be7ed78bc7c9 100644 --- a/src/renderer/src/runtime/runtime-rpc-client.ts +++ b/src/renderer/src/runtime/runtime-rpc-client.ts @@ -1,5 +1,5 @@ import type { GlobalSettings } from '../../../shared/types' -import type { RuntimeRpcFailure, RuntimeRpcResponse } from '../../../shared/runtime-rpc-envelope' +import type { RuntimeRpcResponse } from '../../../shared/runtime-rpc-envelope' import type { RuntimeStatus } from '../../../shared/runtime-types' import type { RuntimeCapability } from '../../../shared/protocol-version' import { withBrowserPaneUiRuntimeRpcSource } from '../../../shared/runtime-rpc-feature-interaction-source' @@ -8,6 +8,9 @@ import { callAbortableRuntimeEnvironment, createRuntimeRpcAbortError } from './abortable-runtime-environment-call' +import { RuntimeRpcCallError } from './runtime-rpc-call-error' + +export { RuntimeRpcCallError, isRuntimeScopeForbiddenError } from './runtime-rpc-call-error' export type RuntimeClientTarget = { kind: 'local' } | { kind: 'environment'; environmentId: string } @@ -21,31 +24,13 @@ type RuntimeCompatibilityCacheEntry = { failedAt: number | null // False while probing so recovery can drop a doomed pending compatibility check. provenCompatible: boolean + freshProbe: boolean status: RuntimeStatus | null statusCheckedAt: number | null } const runtimeCompatibilityChecks = new Map() -export class RuntimeRpcCallError extends Error { - readonly code: string - readonly response: RuntimeRpcFailure - - constructor(response: RuntimeRpcFailure) { - super(response.error.message) - this.name = 'RuntimeRpcCallError' - this.code = response.error.code - this.response = response - } -} - -// Why: mobile-scope device tokens are denied non-allowlisted runtime methods -// with code 'forbidden'. Callers use this to surface one scope-mismatch banner -// instead of silently swallowing the failure into empty/retry-looping UI. -export function isRuntimeScopeForbiddenError(error: unknown): boolean { - return error instanceof RuntimeRpcCallError && error.code === 'forbidden' -} - export function getActiveRuntimeTarget( settings: Pick | null | undefined ): RuntimeClientTarget { @@ -75,6 +60,7 @@ export async function callRuntimeRpc( timeoutMs?: number suppressFeatureInteraction?: boolean reuseRecentCompatibilityFailure?: boolean + forceCompatibilityRefresh?: boolean signal?: AbortSignal } = {} ): Promise { @@ -107,10 +93,24 @@ export async function callRuntimeRpc( return unwrapRuntimeRpcResult(response as RuntimeRpcResponse) } -async function ensureRuntimeEnvironmentCompatible( +export async function ensureRuntimeEnvironmentCompatible( environmentId: string, - options: { timeoutMs?: number; reuseRecentCompatibilityFailure?: boolean } = {} + options: { + timeoutMs?: number + reuseRecentCompatibilityFailure?: boolean + forceCompatibilityRefresh?: boolean + } = {} ): Promise { + if (options.forceCompatibilityRefresh) { + // Why: destructive closes are cold-path operations; re-probe so a host + // rollback/replacement cannot reuse an indefinitely cached safe verdict. + const cached = runtimeCompatibilityChecks.get(environmentId) + const canShareInFlightFreshProbe = + cached?.freshProbe === true && !cached.provenCompatible && cached.failedAt === null + if (!canShareInFlightFreshProbe) { + runtimeCompatibilityChecks.delete(environmentId) + } + } const cached = getCachedRuntimeCompatibilityCheck(environmentId, options) if (cached) { await cached.check @@ -120,6 +120,7 @@ async function ensureRuntimeEnvironmentCompatible( check: Promise.resolve(), failedAt: null, provenCompatible: false, + freshProbe: options.forceCompatibilityRefresh === true, status: null, statusCheckedAt: null } @@ -224,6 +225,7 @@ export function markRuntimeEnvironmentCompatible(environmentId: string): void { check: Promise.resolve(), failedAt: null, provenCompatible: true, + freshProbe: false, status: null, statusCheckedAt: null }) @@ -238,6 +240,7 @@ export async function getRuntimeEnvironmentStatus( check: Promise.resolve(), failedAt: null, provenCompatible: false, + freshProbe: false, status: null, statusCheckedAt: null } @@ -328,9 +331,7 @@ export async function assertRuntimeEnvironmentCapability( } } -export function clearRuntimeCompatibilityCacheForTests(): void { - clearRuntimeCompatibilityCache() -} +export const clearRuntimeCompatibilityCacheForTests = clearRuntimeCompatibilityCache export function unwrapRuntimeRpcResult(response: RuntimeRpcResponse): TResult { if (response.ok === false) { diff --git a/src/renderer/src/runtime/runtime-session-compatibility.test.ts b/src/renderer/src/runtime/runtime-session-compatibility.test.ts new file mode 100644 index 000000000000..68cae18caf0e --- /dev/null +++ b/src/renderer/src/runtime/runtime-session-compatibility.test.ts @@ -0,0 +1,137 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { + MIN_COMPATIBLE_RUNTIME_CLIENT_VERSION, + RUNTIME_PROTOCOL_VERSION +} from '../../../shared/protocol-version' +import { callRuntimeRpc, clearRuntimeCompatibilityCacheForTests } from './runtime-rpc-client' +import { subscribeRuntimeRpc } from './runtime-subscription-client' + +const runtimeEnvironmentCall = vi.fn() +const runtimeEnvironmentSubscribe = vi.fn() + +beforeEach(() => { + clearRuntimeCompatibilityCacheForTests() + runtimeEnvironmentCall.mockReset() + runtimeEnvironmentSubscribe.mockReset() + vi.stubGlobal('window', { + api: { + runtimeEnvironments: { + call: runtimeEnvironmentCall, + subscribe: runtimeEnvironmentSubscribe + } + } + }) +}) + +describe('runtime session compatibility fence', () => { + it('blocks saved-runtime subscriptions before opening an incompatible stream', async () => { + runtimeEnvironmentCall.mockResolvedValue({ + id: 'status', + ok: true, + result: { + runtimeId: 'remote-runtime', + runtimeProtocolVersion: RUNTIME_PROTOCOL_VERSION - 1, + minCompatibleRuntimeClientVersion: MIN_COMPATIBLE_RUNTIME_CLIENT_VERSION - 1 + }, + _meta: { runtimeId: 'remote-runtime' } + }) + + await expect( + subscribeRuntimeRpc( + { selector: 'saved-env', method: 'session.tabs.subscribeAll', params: {} }, + { onResponse: vi.fn() } + ) + ).rejects.toThrow('too old for this client') + + expect(runtimeEnvironmentCall).toHaveBeenCalledWith({ + selector: 'saved-env', + method: 'status.get', + timeoutMs: undefined + }) + expect(runtimeEnvironmentSubscribe).not.toHaveBeenCalled() + }) + + it('rechecks destructive calls after a cached host rollback', async () => { + let statusProtocol = RUNTIME_PROTOCOL_VERSION + runtimeEnvironmentCall.mockImplementation(({ method }: { method: string }) => { + if (method === 'status.get') { + return Promise.resolve({ + id: 'status', + ok: true, + result: { + runtimeId: 'remote-runtime', + runtimeProtocolVersion: statusProtocol, + minCompatibleRuntimeClientVersion: statusProtocol + }, + _meta: { runtimeId: 'remote-runtime' } + }) + } + return Promise.resolve({ + id: method, + ok: true, + result: {}, + _meta: { runtimeId: 'remote-runtime' } + }) + }) + const target = { kind: 'environment' as const, environmentId: 'saved-env' } + + await expect(callRuntimeRpc(target, 'repo.list')).resolves.toEqual({}) + statusProtocol = RUNTIME_PROTOCOL_VERSION - 1 + await expect( + callRuntimeRpc( + target, + 'terminal.close', + { terminal: 'stale-terminal' }, + { + forceCompatibilityRefresh: true + } + ) + ).rejects.toThrow('too old for this client') + + expect(runtimeEnvironmentCall.mock.calls.map((call) => call[0].method)).toEqual([ + 'status.get', + 'repo.list', + 'status.get' + ]) + }) + + it('coalesces concurrent fresh probes for destructive bulk closes', async () => { + let resolveStatus!: (response: unknown) => void + runtimeEnvironmentCall.mockImplementation(({ method }: { method: string }) => { + if (method === 'status.get') { + return new Promise((resolve) => { + resolveStatus = resolve + }) + } + return Promise.resolve({ + id: method, + ok: true, + result: {}, + _meta: { runtimeId: 'remote-runtime' } + }) + }) + const target = { kind: 'environment' as const, environmentId: 'bulk-env' } + const options = { forceCompatibilityRefresh: true } + + const first = callRuntimeRpc(target, 'terminal.close', { terminal: 'one' }, options) + const second = callRuntimeRpc(target, 'terminal.closeTab', { terminal: 'two' }, options) + await vi.waitFor(() => expect(runtimeEnvironmentCall).toHaveBeenCalledTimes(1)) + resolveStatus({ + id: 'status', + ok: true, + result: { + runtimeId: 'remote-runtime', + runtimeProtocolVersion: RUNTIME_PROTOCOL_VERSION, + minCompatibleRuntimeClientVersion: MIN_COMPATIBLE_RUNTIME_CLIENT_VERSION + }, + _meta: { runtimeId: 'remote-runtime' } + }) + + await expect(Promise.all([first, second])).resolves.toEqual([{}, {}]) + expect(runtimeEnvironmentCall.mock.calls.map((call) => call[0].method)).toEqual([ + 'status.get', + 'terminal.close', + 'terminal.closeTab' + ]) + }) +}) diff --git a/src/renderer/src/runtime/runtime-subscription-client.ts b/src/renderer/src/runtime/runtime-subscription-client.ts new file mode 100644 index 000000000000..f9afef99e4cb --- /dev/null +++ b/src/renderer/src/runtime/runtime-subscription-client.ts @@ -0,0 +1,27 @@ +import type { RuntimeRpcResponse } from '../../../shared/runtime-rpc-envelope' +import { ensureRuntimeEnvironmentCompatible } from './runtime-rpc-client' + +type RuntimeEnvironmentSubscriptionHandle = { + unsubscribe: () => void + sendBinary: (bytes: Uint8Array) => void +} + +export async function subscribeRuntimeRpc( + args: { + selector: string + method: string + params?: unknown + timeoutMs?: number + }, + callbacks: { + onResponse: (response: RuntimeRpcResponse) => void + onBinary?: (bytes: Uint8Array) => void + onError?: (error: { code: string; message: string }) => void + onClose?: () => void + } +): Promise { + // Why: subscriptions bypass callRuntimeRpc, but must share its compatibility + // fence before opening any saved runtime's long-lived session stream. + await ensureRuntimeEnvironmentCompatible(args.selector, { timeoutMs: args.timeoutMs }) + return window.api.runtimeEnvironments.subscribe(args, callbacks) +} diff --git a/src/renderer/src/runtime/sync-runtime-graph.test.ts b/src/renderer/src/runtime/sync-runtime-graph.test.ts index d1082d89cab0..36564df29a42 100644 --- a/src/renderer/src/runtime/sync-runtime-graph.test.ts +++ b/src/renderer/src/runtime/sync-runtime-graph.test.ts @@ -554,6 +554,62 @@ describe('getRuntimeMobileSessionSyncKey', () => { }) describe('buildMobileSessionTabSnapshots', () => { + it('publishes live terminal color and pin state from the unified tab', () => { + const leafId = '11111111-1111-4111-8111-111111111111' + const state = makeState({ + activeGroupIdByWorktree: { 'wt-1': 'group-1' }, + groupsByWorktree: { + 'wt-1': [ + { + id: 'group-1', + worktreeId: 'wt-1', + activeTabId: 'terminal-tab-1', + tabOrder: ['terminal-tab-1'], + recentTabIds: ['terminal-tab-1'] + } + ] + }, + unifiedTabsByWorktree: { + 'wt-1': [ + { + id: 'terminal-tab-1', + entityId: 'term-1', + groupId: 'group-1', + worktreeId: 'wt-1', + contentType: 'terminal', + label: 'Pinned terminal', + customLabel: null, + color: '#3b82f6', + sortOrder: 0, + createdAt: 1, + isPreview: false, + isPinned: true + } + ] + }, + tabsByWorktree: { + 'wt-1': [{ id: 'term-1', title: 'Terminal', customTitle: null, ptyId: 'pty-1' }] + } as unknown as AppState['tabsByWorktree'], + terminalLayoutsByTabId: { + 'term-1': { + root: { type: 'leaf', leafId }, + activeLeafId: leafId, + expandedLeafId: null, + ptyIdsByLeafId: { [leafId]: 'pty-1' } + } + } as AppState['terminalLayoutsByTabId'] + }) + + expect(buildMobileSessionTabSnapshots(state)[0]?.tabs).toMatchObject([ + { + type: 'terminal', + parentTabId: 'term-1', + color: '#3b82f6', + isPinned: true + } + ]) + }) + it('publishes browser and editor color + pin state from unified tabs', () => { const fileId = '/repo/README.md' const state = makeState({ diff --git a/src/renderer/src/runtime/sync-runtime-graph.ts b/src/renderer/src/runtime/sync-runtime-graph.ts index 4a4e12fddc5c..9615104a209e 100644 --- a/src/renderer/src/runtime/sync-runtime-graph.ts +++ b/src/renderer/src/runtime/sync-runtime-graph.ts @@ -1227,6 +1227,9 @@ function buildMobileTerminalSurfaceTabs( systemPrefersDark: boolean, unifiedTabId?: string ): RuntimeMobileSessionSnapshotTab[] { + const unifiedTab = unifiedTabId + ? state.unifiedTabsByWorktree[worktreeId]?.find((tab) => tab.id === unifiedTabId) + : undefined const registered = registeredTabs.get(terminal.id) const isDesktopTabActive = unifiedTabId ? state.groupsByWorktree[worktreeId]?.some( @@ -1310,6 +1313,10 @@ function buildMobileTerminalSurfaceTabs( ...(terminalTheme ? { terminalTheme } : {}), ...(agentStatus ? { agentStatus } : {}), ...(terminal.launchAgent ? { launchAgent: terminal.launchAgent } : {}), + color: unifiedTab?.color ?? terminal.color ?? null, + // Why: main adjudicates generation-bound closes after an async refresh, + // so the renderer's current pin state must travel in the same snapshot. + isPinned: unifiedTab ? unifiedTab.isPinned === true : terminal.isPinned === true, parentLayout, isActive: isDesktopTabActive && leafId === activeLeafId } diff --git a/src/renderer/src/runtime/web-runtime-session.test.ts b/src/renderer/src/runtime/web-runtime-session.test.ts index af47e5a03506..78521d905e3f 100644 --- a/src/renderer/src/runtime/web-runtime-session.test.ts +++ b/src/renderer/src/runtime/web-runtime-session.test.ts @@ -1,10 +1,15 @@ /* eslint-disable max-lines */ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { RuntimeMobileSessionTabsResult } from '../../../shared/runtime-types' +import { + MIN_COMPATIBLE_RUNTIME_CLIENT_VERSION, + RUNTIME_PROTOCOL_VERSION +} from '../../../shared/protocol-version' import { activateWebRuntimeSessionWorktree, activateWebRuntimeSessionTab, closeWebRuntimeTerminal, + closeWebRuntimeTerminalTab, closeWebRuntimeSessionTab, consumePendingWebRuntimeSplitMirrorTelemetry, createWebRuntimeSessionBrowserTab, @@ -14,6 +19,10 @@ import { setWebRuntimeTabProps, splitWebRuntimeTerminal } from './web-runtime-session' +import { + clearRuntimeCompatibilityCacheForTests, + markRuntimeEnvironmentCompatible +} from './runtime-rpc-client' const mocks = vi.hoisted(() => ({ getState: vi.fn(), @@ -24,6 +33,7 @@ const mocks = vi.hoisted(() => ({ focusBrowserTabInWorktree: vi.fn(), applyFreshWebSessionTabsSnapshot: vi.fn(), resolveHostSessionTabIdForWebSessionTab: vi.fn(), + acceptReplayedWebSessionTabsSnapshot: vi.fn(), trackTerminalPaneSplit: vi.fn(), getRuntimeEnvironmentIdForWorktree: vi.fn() })) @@ -37,6 +47,7 @@ vi.mock('../store', () => ({ vi.mock('./web-session-tabs-sync', () => ({ applyFreshWebSessionTabsSnapshot: mocks.applyFreshWebSessionTabsSnapshot, + acceptReplayedWebSessionTabsSnapshot: mocks.acceptReplayedWebSessionTabsSnapshot, applyWebSessionTabsStorePatch: (buildPatch: (state: unknown) => unknown) => mocks.setState(buildPatch), resolveHostSessionTabIdForWebSessionTab: mocks.resolveHostSessionTabIdForWebSessionTab @@ -53,6 +64,15 @@ vi.mock('@/lib/worktree-runtime-owner', () => ({ const ENVIRONMENT_ID = 'web-env-1' const WORKTREE_ID = 'repo::/worktree' +beforeEach(() => { + clearRuntimeCompatibilityCacheForTests() + markRuntimeEnvironmentCompatible(ENVIRONMENT_ID) +}) + +afterEach(() => { + clearRuntimeCompatibilityCacheForTests() +}) + function makeSnapshot(): RuntimeMobileSessionTabsResult { return { worktree: WORKTREE_ID, @@ -65,6 +85,19 @@ function makeSnapshot(): RuntimeMobileSessionTabsResult { } } +function makeCompatibleStatusResponse() { + return { + id: 'status', + ok: true, + result: { + runtimeId: 'remote-runtime', + runtimeProtocolVersion: RUNTIME_PROTOCOL_VERSION, + minCompatibleRuntimeClientVersion: MIN_COMPATIBLE_RUNTIME_CLIENT_VERSION + }, + _meta: { runtimeId: 'remote-runtime' } + } +} + describe('activateWebRuntimeSessionWorktree', () => { beforeEach(() => { vi.stubGlobal('__ORCA_WEB_CLIENT__', true) @@ -807,23 +840,16 @@ describe('web runtime session tab actions', () => { }) it('maps mirrored local browser unified ids for activate and close', async () => { - const runtimeCall = vi - .fn() - .mockResolvedValueOnce({ - id: 'activate', - ok: true, - result: {} - }) - .mockResolvedValueOnce({ - id: 'close', - ok: true, - result: {} - }) - .mockResolvedValueOnce({ - id: 'list', + const runtimeCall = vi.fn(({ method }: { method: string }) => { + if (method === 'status.get') { + return Promise.resolve(makeCompatibleStatusResponse()) + } + return Promise.resolve({ + id: method, ok: true, - result: makeSnapshot() + result: method === 'session.tabs.list' ? makeSnapshot() : {} }) + }) vi.stubGlobal('window', { api: { @@ -856,15 +882,21 @@ describe('web runtime session tab actions', () => { timeoutMs: 15_000 }) expect(runtimeCall).toHaveBeenNthCalledWith(2, { + selector: ENVIRONMENT_ID, + method: 'status.get', + timeoutMs: 15_000 + }) + expect(runtimeCall).toHaveBeenNthCalledWith(3, { selector: ENVIRONMENT_ID, method: 'session.tabs.close', params: { worktree: `id:${WORKTREE_ID}`, - tabId: 'host-browser-unified' + tabId: 'host-browser-unified', + intent: 'user' }, timeoutMs: 15_000 }) - expect(runtimeCall).toHaveBeenNthCalledWith(3, { + expect(runtimeCall).toHaveBeenNthCalledWith(4, { selector: ENVIRONMENT_ID, method: 'session.tabs.list', params: { @@ -994,16 +1026,21 @@ describe('closeWebRuntimeTerminal', () => { }) it('delegates remote pane close to the host runtime', async () => { - const runtimeCall = vi.fn().mockResolvedValue({ - id: 'close', - ok: true, - result: { - close: { - handle: 'terminal-1', - tabId: 'tab-1', - ptyKilled: true - } + const runtimeCall = vi.fn(({ method }: { method: string }) => { + if (method === 'status.get') { + return Promise.resolve(makeCompatibleStatusResponse()) } + return Promise.resolve({ + id: 'close', + ok: true, + result: { + close: { + handle: 'terminal-1', + tabId: 'tab-1', + ptyKilled: true + } + } + }) }) vi.stubGlobal('window', { api: { @@ -1015,7 +1052,7 @@ describe('closeWebRuntimeTerminal', () => { expect(closeWebRuntimeTerminal('remote:web-env-1@@terminal-1')).toBe(true) - await vi.waitFor(() => expect(runtimeCall).toHaveBeenCalledTimes(1)) + await vi.waitFor(() => expect(runtimeCall).toHaveBeenCalledTimes(2)) expect(runtimeCall).toHaveBeenCalledWith({ selector: 'web-env-1', method: 'terminal.close', @@ -1026,6 +1063,125 @@ describe('closeWebRuntimeTerminal', () => { }) }) + it('blocks a saved v4 client from closing through an older host contract', async () => { + clearRuntimeCompatibilityCacheForTests() + const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}) + const runtimeCall = vi.fn().mockResolvedValue({ + id: 'status', + ok: true, + result: { + runtimeId: 'old-runtime', + runtimeProtocolVersion: 3, + minCompatibleRuntimeClientVersion: 2 + }, + _meta: { runtimeId: 'old-runtime' } + }) + vi.stubGlobal('window', { + api: { + runtimeEnvironments: { + call: runtimeCall + } + } + }) + + expect(closeWebRuntimeTerminal('remote:web-env-1@@stale-terminal')).toBe(true) + + await vi.waitFor(() => expect(warnSpy).toHaveBeenCalled()) + expect(runtimeCall.mock.calls.map((call) => call[0].method)).toEqual(['status.get']) + }) + + it('delegates explicit whole-tab close through the generation-bound handle', async () => { + const runtimeCall = vi.fn(({ method }: { method: string }) => { + if (method === 'status.get') { + return Promise.resolve(makeCompatibleStatusResponse()) + } + return Promise.resolve({ + id: 'close-tab', + ok: true, + result: { + close: { + handle: 'terminal-1', + tabId: 'tab-1', + closeMode: 'tab', + ptyKilled: false + } + } + }) + }) + vi.stubGlobal('window', { + api: { + runtimeEnvironments: { + call: runtimeCall + } + } + }) + + expect( + closeWebRuntimeTerminalTab({ + environmentId: 'web-env-1', + worktreeId: WORKTREE_ID, + terminal: 'terminal-1' + }) + ).toBe(true) + + await vi.waitFor(() => expect(runtimeCall).toHaveBeenCalledTimes(2)) + expect(runtimeCall).toHaveBeenCalledWith({ + selector: 'web-env-1', + method: 'terminal.closeTab', + params: { terminal: 'terminal-1' }, + timeoutMs: 30_000 + }) + }) + + it('restores the authoritative mirror when a generation-bound tab close is stale', async () => { + const snapshot = makeSnapshot() + const runtimeCall = vi.fn(({ method }: { method: string }) => { + if (method === 'status.get') { + return Promise.resolve(makeCompatibleStatusResponse()) + } + if (method === 'terminal.closeTab') { + return Promise.reject(new Error('terminal_handle_stale')) + } + return Promise.resolve({ id: 'list', ok: true, result: snapshot }) + }) + vi.stubGlobal('window', { + api: { + runtimeEnvironments: { + call: runtimeCall + } + } + }) + mocks.applyFreshWebSessionTabsSnapshot.mockReturnValue({ state: 'restored' }) + mocks.setState.mockImplementation((updater: (state: unknown) => unknown) => { + updater({ state: 'locally-pruned' }) + }) + + expect( + closeWebRuntimeTerminalTab({ + environmentId: 'web-env-1', + worktreeId: WORKTREE_ID, + terminal: 'terminal-stale' + }) + ).toBe(true) + + await vi.waitFor(() => expect(runtimeCall).toHaveBeenCalledTimes(3)) + expect(mocks.acceptReplayedWebSessionTabsSnapshot).toHaveBeenCalledWith( + 'web-env-1', + WORKTREE_ID + ) + expect(runtimeCall).toHaveBeenNthCalledWith(3, { + selector: 'web-env-1', + method: 'session.tabs.list', + params: { worktree: `id:${WORKTREE_ID}` }, + timeoutMs: 15_000 + }) + expect(mocks.applyFreshWebSessionTabsSnapshot).toHaveBeenCalledWith( + { state: 'locally-pruned' }, + snapshot, + 'web-env-1' + ) + }) + it('ignores local panes but delegates remote runtime panes from desktop or web clients', async () => { const runtimeCall = vi.fn().mockResolvedValue({ id: 'close', diff --git a/src/renderer/src/runtime/web-runtime-session.ts b/src/renderer/src/runtime/web-runtime-session.ts index de8b9603e6b0..748f4b2d83cf 100644 --- a/src/renderer/src/runtime/web-runtime-session.ts +++ b/src/renderer/src/runtime/web-runtime-session.ts @@ -1,5 +1,4 @@ /* eslint-disable max-lines */ -import type { RuntimeRpcResponse } from '../../../shared/runtime-rpc-envelope' import type { BrowserTabCreateResult, RuntimeMobileSessionCreateTerminalResult, @@ -13,10 +12,11 @@ import type { TerminalPaneSplitSource } from '../../../shared/feature-education- import type { StartupCommandDelivery } from '../../../shared/codex-startup-delivery' import type { SleepingAgentLaunchConfig } from '../../../shared/agent-session-resume' import type { TerminalPaneLayoutNode, TuiAgent } from '../../../shared/types' +import { TERMINAL_TAB_CLOSE_RUNTIME_RPC_TIMEOUT_MS } from '../../../shared/terminal-tab-close' import type { AppState } from '../store/types' import { getRuntimeEnvironmentIdForWorktree } from '../lib/worktree-runtime-owner' import { useAppStore } from '../store' -import { unwrapRuntimeRpcResult } from './runtime-rpc-client' +import { callRuntimeRpc } from './runtime-rpc-client' import { parseRemoteRuntimePtyId } from './runtime-terminal-stream' import { toRuntimeWorktreeSelector } from './runtime-worktree-selector' import { recordWebSessionFocusIntent } from './web-session-focus-intent' @@ -71,10 +71,10 @@ export async function createWebRuntimeSessionTerminal(args: { selectWebRuntimeSessionWorktree(args.worktreeId) } try { - const response = await window.api.runtimeEnvironments.call({ - selector: environmentId, - method: 'session.tabs.createTerminal', - params: { + const createdTerminal = await callRuntimeRpc( + { kind: 'environment', environmentId }, + 'session.tabs.createTerminal', + { worktree: toRuntimeWorktreeSelector(args.worktreeId), afterTabId: args.afterTabId ? toHostSessionTabId(args.afterTabId) : undefined, targetGroupId: args.targetGroupId, @@ -88,10 +88,7 @@ export async function createWebRuntimeSessionTerminal(args: { ...(args.viewMode ? { viewMode: args.viewMode } : {}), activate: args.activate !== false }, - timeoutMs: 15_000 - }) - const createdTerminal = unwrapRuntimeRpcResult( - response as RuntimeRpcResponse + { timeoutMs: 15_000 } ) if (args.activate !== false) { // Why: record focus intent so the reconcile follows to this new terminal instead of sticky-keeping the prior tab. @@ -130,10 +127,10 @@ export async function createWebRuntimeSessionBrowserTab(args: { selectWebRuntimeSessionWorktree(args.worktreeId) } try { - const response = await window.api.runtimeEnvironments.call({ - selector: environmentId, - method: 'browser.tabCreate', - params: { + const created = await callRuntimeRpc( + { kind: 'environment', environmentId }, + 'browser.tabCreate', + { worktree: toRuntimeWorktreeSelector(args.worktreeId), url: args.url, profileId: args.profileId ?? undefined, @@ -144,9 +141,8 @@ export async function createWebRuntimeSessionBrowserTab(args: { // Why: web clients need the local tab now; waiting for host webview registration makes the workspace appear to close. waitForRegistration: false }, - timeoutMs: 15_000 - }) - const created = unwrapRuntimeRpcResult(response as RuntimeRpcResponse) + { timeoutMs: 15_000 } + ) // Why: record focus intent (tab id === browserPageId on a headless host) so the reconcile follows to the new browser tab. recordWebSessionFocusIntent(args.worktreeId, created.browserPageId) stageWebRuntimeBrowserTab({ @@ -245,16 +241,11 @@ async function refreshWebRuntimeSessionTabsSnapshot( worktreeId: string ): Promise { try { - const response = await window.api.runtimeEnvironments.call({ - selector: environmentId, - method: 'session.tabs.list', - params: { - worktree: toRuntimeWorktreeSelector(worktreeId) - }, - timeoutMs: 15_000 - }) - const snapshot = unwrapRuntimeRpcResult( - response as RuntimeRpcResponse + const snapshot = await callRuntimeRpc( + { kind: 'environment', environmentId }, + 'session.tabs.list', + { worktree: toRuntimeWorktreeSelector(worktreeId) }, + { timeoutMs: 15_000 } ) const { applyFreshWebSessionTabsSnapshot, applyWebSessionTabsStorePatch } = await import('./web-session-tabs-sync') @@ -286,16 +277,15 @@ export async function activateWebRuntimeSessionWorktree(args: { } try { - const response = await window.api.runtimeEnvironments.call({ - selector: environmentId, - method: 'worktree.activate', - params: { + await callRuntimeRpc( + { kind: 'environment', environmentId }, + 'worktree.activate', + { worktree: toRuntimeWorktreeSelector(args.worktreeId), notifyClients: args.notifyDesktop !== false }, - timeoutMs: 15_000 - }) - unwrapRuntimeRpcResult(response as RuntimeRpcResponse) + { timeoutMs: 15_000 } + ) return true } catch (error) { console.warn( @@ -400,13 +390,12 @@ export async function moveWebRuntimeSessionTab( // Why: web groups can contain local-only tabs, so host insertion indexes count only the filtered host-backed order. index: targetHostIndex } - const response = await window.api.runtimeEnvironments.call({ - selector: environmentId, - method: 'session.tabs.move', - params: move, - timeoutMs: 15_000 - }) - unwrapRuntimeRpcResult(response as RuntimeRpcResponse) + await callRuntimeRpc( + { kind: 'environment', environmentId }, + 'session.tabs.move', + move, + { timeoutMs: 15_000 } + ) return true } catch (error) { console.warn( @@ -451,16 +440,19 @@ async function callWebRuntimeSessionTabMethod( // Why: suppress until the host confirms removal, else an in-flight pre-close snapshot flashes the tab back. recordWebSessionCloseIntent(args.worktreeId, hostTabId, Date.now()) } - const response = await window.api.runtimeEnvironments.call({ - selector: environmentId, + await callRuntimeRpc( + { kind: 'environment', environmentId }, method, - params: { + { worktree: toRuntimeWorktreeSelector(args.worktreeId), - tabId: hostTabId + tabId: hostTabId, + ...(method === 'session.tabs.close' ? { intent: 'user' as const } : {}) }, - timeoutMs: 15_000 - }) - unwrapRuntimeRpcResult(response as RuntimeRpcResponse) + { + timeoutMs: 15_000, + forceCompatibilityRefresh: method === 'session.tabs.close' + } + ) if (method === 'session.tabs.close') { await refreshWebRuntimeSessionTabsSnapshot(environmentId, args.worktreeId) } @@ -495,27 +487,22 @@ export function splitWebRuntimeTerminal( direction, pendingMirrorSuppressionId ) - void window.api.runtimeEnvironments - .call({ - selector: environmentId, - method: 'terminal.split', - params: { - terminal: remote.handle, - direction, - telemetrySource - }, - timeoutMs: 15_000 - }) - .then((response) => { - unwrapRuntimeRpcResult(response as RuntimeRpcResponse<{ split: RuntimeTerminalSplit }>) - }) - .catch((error) => { - releasePendingMirrorSuppression() - console.warn( - '[web-runtime-session] failed to split terminal:', - error instanceof Error ? error.message : String(error) - ) - }) + void callRuntimeRpc<{ split: RuntimeTerminalSplit }>( + { kind: 'environment', environmentId }, + 'terminal.split', + { + terminal: remote.handle, + direction, + telemetrySource + }, + { timeoutMs: 15_000 } + ).catch((error) => { + releasePendingMirrorSuppression() + console.warn( + '[web-runtime-session] failed to split terminal:', + error instanceof Error ? error.message : String(error) + ) + }) return true } @@ -605,28 +592,55 @@ export function closeWebRuntimeTerminal(ptyId: string | null | undefined): boole } // Why: host owns the real pane graph; close the host terminal first so later snapshots can't resurrect the removed pane. - void window.api.runtimeEnvironments - .call({ - selector: environmentId, - method: 'terminal.close', - params: { - terminal: remote.handle - }, - timeoutMs: 15_000 - }) - .then((response) => { - unwrapRuntimeRpcResult(response as RuntimeRpcResponse<{ close: RuntimeTerminalClose }>) - }) - .catch((error) => { - console.warn( - '[web-runtime-session] failed to close terminal pane:', - error instanceof Error ? error.message : String(error) - ) - }) + void callRuntimeRpc<{ close: RuntimeTerminalClose }>( + { kind: 'environment', environmentId }, + 'terminal.close', + { terminal: remote.handle }, + { timeoutMs: 15_000, forceCompatibilityRefresh: true } + ).catch((error) => { + console.warn( + '[web-runtime-session] failed to close terminal pane:', + error instanceof Error ? error.message : String(error) + ) + }) + return true +} + +export function closeWebRuntimeTerminalTab(args: { + environmentId: string + worktreeId: string + terminal: string +}): boolean { + const environmentId = args.environmentId.trim() + if (!environmentId || !isWebRuntimeSessionActive(environmentId)) { + return false + } + + // Why: a ready remote terminal handle is generation-bound; explicit tab + // closes must not authorize a mutable snapshot/tab id that may have rebound. + void callRuntimeRpc<{ close: RuntimeTerminalClose }>( + { kind: 'environment', environmentId }, + 'terminal.closeTab', + { terminal: args.terminal }, + { + timeoutMs: TERMINAL_TAB_CLOSE_RUNTIME_RPC_TIMEOUT_MS, + forceCompatibilityRefresh: true + } + ).catch(async (error) => { + console.warn( + '[web-runtime-session] failed to close terminal tab:', + error instanceof Error ? error.message : String(error) + ) + const { acceptReplayedWebSessionTabsSnapshot } = await import('./web-session-tabs-sync') + // Why: the optimistic local prune may have targeted an obsolete handle; + // accept the host's unchanged snapshot so its live replacement reappears. + acceptReplayedWebSessionTabsSnapshot(environmentId, args.worktreeId) + await refreshWebRuntimeSessionTabsSnapshot(environmentId, args.worktreeId) + }) return true } -// Why: pane geometry is host-authoritative for remote tabs; local-only changes revert on next snapshot, so push to host. +// Why: pane geometry is host-authoritative for remote tabs; local-only changes revert on the next snapshot. export async function updateWebRuntimePaneLayout(args: { worktreeId: string tabId: string @@ -643,19 +657,18 @@ export async function updateWebRuntimePaneLayout(args: { ? toHostSessionTabId(args.tabId) : args.tabId try { - const response = await window.api.runtimeEnvironments.call({ - selector: environmentId, - method: 'session.tabs.updatePaneLayout', - params: { + await callRuntimeRpc<{ updated: true }>( + { kind: 'environment', environmentId }, + 'session.tabs.updatePaneLayout', + { worktree: toRuntimeWorktreeSelector(args.worktreeId), tabId: hostTabId, root: args.root, expandedLeafId: args.expandedLeafId, ...(args.titlesByLeafId ? { titlesByLeafId: args.titlesByLeafId } : {}) }, - timeoutMs: 15_000 - }) - unwrapRuntimeRpcResult(response as RuntimeRpcResponse<{ updated: true }>) + { timeoutMs: 15_000 } + ) return true } catch (error) { console.warn( @@ -688,21 +701,18 @@ export function setWebRuntimeTabProps(args: { worktreeId: args.worktreeId, tabId: args.tabId }) ?? (isWebTerminalSurfaceTabId(args.tabId) ? toHostSessionTabId(args.tabId) : args.tabId) - return window.api.runtimeEnvironments.call({ - selector: environmentId, - method: 'session.tabs.setTabProps', - params: { + return callRuntimeRpc<{ updated: true }>( + { kind: 'environment', environmentId }, + 'session.tabs.setTabProps', + { worktree: toRuntimeWorktreeSelector(args.worktreeId), tabId: hostTabId, ...(args.color !== undefined ? { color: args.color } : {}), ...(args.isPinned !== undefined ? { isPinned: args.isPinned } : {}), ...(args.viewMode !== undefined ? { viewMode: args.viewMode } : {}) }, - timeoutMs: 15_000 - }) - }) - .then((response) => { - unwrapRuntimeRpcResult(response as RuntimeRpcResponse<{ updated: true }>) + { timeoutMs: 15_000 } + ) }) .catch((error) => { console.warn( @@ -723,21 +733,16 @@ export function clearWebRuntimeTerminalBuffer(ptyId: string | null | undefined): if (!remote || !environmentId || !isWebRuntimeSessionActive(environmentId)) { return false } - void window.api.runtimeEnvironments - .call({ - selector: environmentId, - method: 'terminal.clearBuffer', - params: { terminal: remote.handle }, - timeoutMs: 15_000 - }) - .then((response) => { - unwrapRuntimeRpcResult(response as RuntimeRpcResponse<{ clear: unknown }>) - }) - .catch((error) => { - console.warn( - '[web-runtime-session] failed to clear terminal buffer:', - error instanceof Error ? error.message : String(error) - ) - }) + void callRuntimeRpc<{ clear: unknown }>( + { kind: 'environment', environmentId }, + 'terminal.clearBuffer', + { terminal: remote.handle }, + { timeoutMs: 15_000 } + ).catch((error) => { + console.warn( + '[web-runtime-session] failed to clear terminal buffer:', + error instanceof Error ? error.message : String(error) + ) + }) return true } diff --git a/src/renderer/src/runtime/web-session-tabs-sync.ts b/src/renderer/src/runtime/web-session-tabs-sync.ts index 3dddb45fc0b3..af30074533e8 100644 --- a/src/renderer/src/runtime/web-session-tabs-sync.ts +++ b/src/renderer/src/runtime/web-session-tabs-sync.ts @@ -43,6 +43,8 @@ import { toWebTerminalSurfaceTabId, WEB_TERMINAL_SURFACE_TAB_PREFIX } from './web-runtime-session' +import { callRuntimeRpc } from './runtime-rpc-client' +import { subscribeRuntimeRpc } from './runtime-subscription-client' import { normalizeCompatibleAgentStatusEntryForOwner, normalizeCompatibleAgentTitleForOwner @@ -2480,22 +2482,16 @@ export function useWebSessionTabsSync(): void { ) { continue } - void window.api.runtimeEnvironments - .call({ - selector: environmentId, - method: 'session.tabs.listAll', - params: {}, - timeoutMs: 15_000 - }) - .then((response: RuntimeRpcResponse) => { + void callRuntimeRpc<{ snapshots: RuntimeMobileSessionTabsResult[] }>( + { kind: 'environment', environmentId }, + 'session.tabs.listAll', + {}, + { timeoutMs: 15_000 } + ) + .then((result) => { if (disposed) { return } - if (response.ok === false) { - console.warn('[web-session-tabs-sync] initial listAll failed:', response.error.message) - return - } - const result = response.result if (!isSessionTabsListAllResult(result)) { console.warn('[web-session-tabs-sync] initial listAll returned an invalid payload') return @@ -2513,54 +2509,53 @@ export function useWebSessionTabsSync(): void { } }) - void window.api.runtimeEnvironments - .subscribe( - { - selector: environmentId, - method: 'session.tabs.subscribeAll', - params: {}, - timeoutMs: 15_000 - }, - { - onResponse: (response: RuntimeRpcResponse) => { - if (disposed) { - return - } - if (response.ok === false) { - console.warn( - '[web-session-tabs-sync] global subscription failed:', - response.error.message - ) - return - } - const event = response.result as SessionTabsStreamEvent - const replayed = isRuntimeSubscriptionReplayResponse(response) - if (event.type === 'snapshots') { - if (replayed) { - for (const snapshot of event.snapshots) { - acceptReplayedWebSessionTabsSnapshot(environmentId, snapshot.worktree) - } - } - applyWebSessionTabsStorePatch((state) => - applyFreshWebSessionTabsSnapshots(state, event.snapshots, environmentId) - ) - return - } - if (event.type !== 'snapshot' && event.type !== 'updated') { - return - } + void subscribeRuntimeRpc( + { + selector: environmentId, + method: 'session.tabs.subscribeAll', + params: {}, + timeoutMs: 15_000 + }, + { + onResponse: (response: RuntimeRpcResponse) => { + if (disposed) { + return + } + if (response.ok === false) { + console.warn( + '[web-session-tabs-sync] global subscription failed:', + response.error.message + ) + return + } + const event = response.result as SessionTabsStreamEvent + const replayed = isRuntimeSubscriptionReplayResponse(response) + if (event.type === 'snapshots') { if (replayed) { - acceptReplayedWebSessionTabsSnapshot(environmentId, event.worktree) + for (const snapshot of event.snapshots) { + acceptReplayedWebSessionTabsSnapshot(environmentId, snapshot.worktree) + } } applyWebSessionTabsStorePatch((state) => - applyFreshWebSessionTabsSnapshot(state, event, environmentId) + applyFreshWebSessionTabsSnapshots(state, event.snapshots, environmentId) ) - }, - onError: (error) => { - console.warn('[web-session-tabs-sync] global subscription error:', error.message) + return } + if (event.type !== 'snapshot' && event.type !== 'updated') { + return + } + if (replayed) { + acceptReplayedWebSessionTabsSnapshot(environmentId, event.worktree) + } + applyWebSessionTabsStorePatch((state) => + applyFreshWebSessionTabsSnapshot(state, event, environmentId) + ) + }, + onError: (error) => { + console.warn('[web-session-tabs-sync] global subscription error:', error.message) } - ) + } + ) .then((handle) => { if (disposed) { handle.unsubscribe() @@ -2608,87 +2603,86 @@ export function useWebSessionTabsSync(): void { let requestedInitialTerminal = false let requestedRespawnAfterWake = false let unsubscribe: (() => void) | null = null - void window.api.runtimeEnvironments - .subscribe( - { - selector: environmentId, - method: 'session.tabs.subscribe', - params: { worktree: toRuntimeWorktreeSelector(activeWorktreeId) }, - timeoutMs: 15_000 - }, - { - onResponse: (response: RuntimeRpcResponse) => { - if (disposed) { - return - } - if (response.ok === false) { - console.warn('[web-session-tabs-sync] subscription failed:', response.error.message) - return - } - const event = response.result as SessionTabsStreamEvent - if (event.type !== 'snapshot' && event.type !== 'updated') { - return - } - if (isRuntimeSubscriptionReplayResponse(response)) { - acceptReplayedWebSessionTabsSnapshot(environmentId, event.worktree) - } - const fresh = shouldApplyWebSessionTabsSnapshot(event, environmentId) - const syncState = useAppStore.getState() - const localWorktreeTabs = syncState.tabsByWorktree[activeWorktreeId] ?? [] - const localTerminalCount = localWorktreeTabs.length - const hasLiveLocalPty = localWorktreeTabs.some( - (tab) => (syncState.ptyIdsByTabId[tab.id] ?? []).length > 0 + void subscribeRuntimeRpc( + { + selector: environmentId, + method: 'session.tabs.subscribe', + params: { worktree: toRuntimeWorktreeSelector(activeWorktreeId) }, + timeoutMs: 15_000 + }, + { + onResponse: (response: RuntimeRpcResponse) => { + if (disposed) { + return + } + if (response.ok === false) { + console.warn('[web-session-tabs-sync] subscription failed:', response.error.message) + return + } + const event = response.result as SessionTabsStreamEvent + if (event.type !== 'snapshot' && event.type !== 'updated') { + return + } + if (isRuntimeSubscriptionReplayResponse(response)) { + acceptReplayedWebSessionTabsSnapshot(environmentId, event.worktree) + } + const fresh = shouldApplyWebSessionTabsSnapshot(event, environmentId) + const syncState = useAppStore.getState() + const localWorktreeTabs = syncState.tabsByWorktree[activeWorktreeId] ?? [] + const localTerminalCount = localWorktreeTabs.length + const hasLiveLocalPty = localWorktreeTabs.some( + (tab) => (syncState.ptyIdsByTabId[tab.id] ?? []).length > 0 + ) + const shouldBootstrapInitialTerminal = shouldBootstrapInitialWebRuntimeTerminal({ + event, + activeWorktreeId, + requestedInitialTerminal, + snapshotIsFresh: fresh, + localTerminalCount + }) + const shouldRespawnAfterWake = shouldRespawnWebRuntimeTerminalAfterWake({ + event, + activeWorktreeId, + requestedRespawnAfterWake, + snapshotIsFresh: fresh, + localTerminalCount, + hasLiveLocalPty, + skipWakeRespawn: shouldSkipWebRuntimeWakeTerminalRespawn(activeWorktreeId) + }) + if (fresh) { + applyWebSessionTabsStorePatch((state) => + applyWebSessionTabsSnapshot(state, event, environmentId) ) - const shouldBootstrapInitialTerminal = shouldBootstrapInitialWebRuntimeTerminal({ - event, - activeWorktreeId, - requestedInitialTerminal, - snapshotIsFresh: fresh, - localTerminalCount + } + if (!disposed && shouldBootstrapInitialTerminal) { + requestedInitialTerminal = true + void createWebRuntimeSessionTerminal({ + worktreeId: activeWorktreeId, + environmentId, + activate: true }) - const shouldRespawnAfterWake = shouldRespawnWebRuntimeTerminalAfterWake({ - event, - activeWorktreeId, - requestedRespawnAfterWake, - snapshotIsFresh: fresh, - localTerminalCount, - hasLiveLocalPty, - skipWakeRespawn: shouldSkipWebRuntimeWakeTerminalRespawn(activeWorktreeId) + } else if ( + !disposed && + shouldRespawnAfterWake && + beginWebRuntimeWakeTerminalRespawn(activeWorktreeId) + ) { + requestedRespawnAfterWake = true + // Why: recreate the terminal without changing selected worktree to avoid re-triggering activation churn. + void createWebRuntimeSessionTerminal({ + worktreeId: activeWorktreeId, + environmentId, + activate: true, + selectWorktree: false + }).finally(() => { + endWebRuntimeWakeTerminalRespawn(activeWorktreeId) }) - if (fresh) { - applyWebSessionTabsStorePatch((state) => - applyWebSessionTabsSnapshot(state, event, environmentId) - ) - } - if (!disposed && shouldBootstrapInitialTerminal) { - requestedInitialTerminal = true - void createWebRuntimeSessionTerminal({ - worktreeId: activeWorktreeId, - environmentId, - activate: true - }) - } else if ( - !disposed && - shouldRespawnAfterWake && - beginWebRuntimeWakeTerminalRespawn(activeWorktreeId) - ) { - requestedRespawnAfterWake = true - // Why: recreate the terminal without changing selected worktree to avoid re-triggering activation churn. - void createWebRuntimeSessionTerminal({ - worktreeId: activeWorktreeId, - environmentId, - activate: true, - selectWorktree: false - }).finally(() => { - endWebRuntimeWakeTerminalRespawn(activeWorktreeId) - }) - } - }, - onError: (error) => { - console.warn('[web-session-tabs-sync] subscription error:', error.message) } + }, + onError: (error) => { + console.warn('[web-session-tabs-sync] subscription error:', error.message) } - ) + } + ) .then((handle) => { if (disposed) { handle.unsubscribe() diff --git a/src/renderer/src/store/slices/repos-project-host-capability.test.ts b/src/renderer/src/store/slices/repos-project-host-capability.test.ts index 862babeb51ce..4bc549f0b9aa 100644 --- a/src/renderer/src/store/slices/repos-project-host-capability.test.ts +++ b/src/renderer/src/store/slices/repos-project-host-capability.test.ts @@ -3,6 +3,7 @@ import type { Repo } from '../../../../shared/types' import { PROJECT_HOST_SETUP_RUNTIME_CAPABILITY } from '../../../../shared/protocol-version' import { clearRuntimeCompatibilityCacheForTests } from '../../runtime/runtime-rpc-client' import type { RuntimeEnvironmentCallRequest } from '../../runtime/runtime-compatibility-test-fixture' +import { createCompatibleRuntimeStatusResponse } from '../../runtime/runtime-compatibility-test-fixture' import { createTestStore } from './store-test-helpers' const remoteRepo: Repo = { @@ -21,21 +22,16 @@ const runtimeEnvironmentTransportCall = vi.fn() let runtimeCapabilities: string[] = [] function runtimeStatusWithoutProjectHostSetup() { + const response = createCompatibleRuntimeStatusResponse('runtime-remote') + if (!response.ok) { + throw new Error('compatible runtime fixture must succeed') + } return { - id: 'status', - ok: true, + ...response, result: { - runtimeId: 'runtime-remote', - rendererGraphEpoch: 0, - graphStatus: 'ready', - authoritativeWindowId: null, - liveTabCount: 0, - liveLeafCount: 0, - runtimeProtocolVersion: 3, - minCompatibleRuntimeClientVersion: 2, + ...response.result, capabilities: runtimeCapabilities - }, - _meta: { runtimeId: 'runtime-remote' } + } } } diff --git a/src/renderer/src/store/slices/terminal-tab-retirement.ts b/src/renderer/src/store/slices/terminal-tab-retirement.ts index e7b26582e7b6..9e6ae3ded543 100644 --- a/src/renderer/src/store/slices/terminal-tab-retirement.ts +++ b/src/renderer/src/store/slices/terminal-tab-retirement.ts @@ -76,6 +76,22 @@ function collectPtyIdsForTab( return [...ids] } +export function collectCurrentTerminalPtyIdsForTab( + state: TerminalTabRetirementState, + tabId: string +): string[] { + const owner = collectLiveTerminalTabs(state).get(tabId) + const ids = new Set() + for (const ptyId of state.ptyIdsByTabId[tabId] ?? []) { + appendPtyId(ids, ptyId) + } + appendPtyId(ids, owner?.rowPtyId) + for (const ptyId of Object.values(state.terminalLayoutsByTabId[tabId]?.ptyIdsByLeafId ?? {})) { + appendPtyId(ids, ptyId) + } + return [...ids] +} + function collectLiveTerminalTabs( state: TerminalTabRetirementState ): Map { diff --git a/src/shared/protocol-compat.test.ts b/src/shared/protocol-compat.test.ts index 8b9734c77860..b027a7e394c1 100644 --- a/src/shared/protocol-compat.test.ts +++ b/src/shared/protocol-compat.test.ts @@ -167,6 +167,36 @@ describe('evaluateRuntimeCompat', () => { expect(verdict).toMatchObject({ kind: 'ok' }) }) + it('blocks pre-ownership-fix clients from current terminal hosts', () => { + const verdict = evaluateRuntimeCompat({ + clientProtocolVersion: RUNTIME_PROTOCOL_VERSION - 1, + minCompatibleServerProtocolVersion: MIN_COMPATIBLE_RUNTIME_SERVER_VERSION, + serverProtocolVersion: RUNTIME_PROTOCOL_VERSION, + serverMinCompatibleClientProtocolVersion: MIN_COMPATIBLE_RUNTIME_CLIENT_VERSION + }) + + expect(verdict).toMatchObject({ + kind: 'blocked', + reason: 'client-too-old', + requiredClientProtocolVersion: RUNTIME_PROTOCOL_VERSION + }) + }) + + it('blocks current clients from hosts without generation-safe explicit close', () => { + const verdict = evaluateRuntimeCompat({ + clientProtocolVersion: RUNTIME_PROTOCOL_VERSION, + minCompatibleServerProtocolVersion: MIN_COMPATIBLE_RUNTIME_SERVER_VERSION, + serverProtocolVersion: RUNTIME_PROTOCOL_VERSION - 1, + serverMinCompatibleClientProtocolVersion: 2 + }) + + expect(verdict).toMatchObject({ + kind: 'blocked', + reason: 'server-too-old', + requiredServerProtocolVersion: RUNTIME_PROTOCOL_VERSION + }) + }) + it('allows client and server app versions to skew when protocol ranges overlap', () => { const verdict = evaluateRuntimeCompat({ clientProtocolVersion: RUNTIME_PROTOCOL_VERSION, diff --git a/src/shared/protocol-version.ts b/src/shared/protocol-version.ts index a5ecb6213705..42fd5f2f834d 100644 --- a/src/shared/protocol-version.ts +++ b/src/shared/protocol-version.ts @@ -17,9 +17,13 @@ // this client build requires a newer server. Exact app-version equality is // never required; these numbers define the supported compatibility window. -export const RUNTIME_PROTOCOL_VERSION = 3 -export const MIN_COMPATIBLE_RUNTIME_CLIENT_VERSION = 2 -export const MIN_COMPATIBLE_RUNTIME_SERVER_VERSION = 2 +// Why: protocol <=3 clients can turn mirror teardown into an ambiguous +// reasonless terminal close, which a host cannot distinguish from user intent. +export const RUNTIME_PROTOCOL_VERSION = 4 +export const MIN_COMPATIBLE_RUNTIME_CLIENT_VERSION = 4 +// Why: protocol <=3 hosts close by mutable tab id after async refresh; a v4 +// handle cannot safely fall back without reopening the destructive TOCTOU. +export const MIN_COMPATIBLE_RUNTIME_SERVER_VERSION = 4 export const PROJECT_HOST_SETUP_RUNTIME_CAPABILITY = 'project-host-setup.v1' as const export const TASK_SOURCE_CONTEXT_RUNTIME_CAPABILITY = 'task-source-context.v1' as const diff --git a/src/shared/terminal-layout-leaf-retirement.test.ts b/src/shared/terminal-layout-leaf-retirement.test.ts new file mode 100644 index 000000000000..ef958a491bd0 --- /dev/null +++ b/src/shared/terminal-layout-leaf-retirement.test.ts @@ -0,0 +1,72 @@ +import { describe, expect, it } from 'vitest' +import type { TerminalLayoutSnapshot } from './types' +import { retireTerminalLayoutLeaf } from './terminal-layout-leaf-retirement' + +function splitLayout(): TerminalLayoutSnapshot { + return { + root: { + type: 'split', + direction: 'horizontal', + first: { type: 'leaf', leafId: 'leaf-a' }, + second: { + type: 'split', + direction: 'vertical', + first: { type: 'leaf', leafId: 'leaf-b' }, + second: { type: 'leaf', leafId: 'leaf-c' } + } + }, + activeLeafId: 'leaf-b', + expandedLeafId: 'leaf-b', + ptyIdsByLeafId: { 'leaf-a': 'pty-a', 'leaf-b': 'pty-b', 'leaf-c': 'pty-c' }, + buffersByLeafId: { 'leaf-a': 'a', 'leaf-b': 'b', 'leaf-c': 'c' }, + scrollbackRefsByLeafId: { 'leaf-a': 'ra', 'leaf-b': 'rb', 'leaf-c': 'rc' }, + titlesByLeafId: { 'leaf-a': 'A', 'leaf-b': 'B', 'leaf-c': 'C' } + } +} + +describe('retireTerminalLayoutLeaf', () => { + it('collapses only the exact nested leaf and its metadata', () => { + const result = retireTerminalLayoutLeaf(splitLayout(), { + leafId: 'leaf-b', + expectedPtyId: 'pty-b' + }) + + expect(result?.layout).toEqual({ + root: { + type: 'split', + direction: 'horizontal', + first: { type: 'leaf', leafId: 'leaf-a' }, + second: { type: 'leaf', leafId: 'leaf-c' } + }, + activeLeafId: 'leaf-a', + expandedLeafId: null, + ptyIdsByLeafId: { 'leaf-a': 'pty-a', 'leaf-c': 'pty-c' }, + buffersByLeafId: { 'leaf-a': 'a', 'leaf-c': 'c' }, + scrollbackRefsByLeafId: { 'leaf-a': 'ra', 'leaf-c': 'rc' }, + titlesByLeafId: { 'leaf-a': 'A', 'leaf-c': 'C' } + }) + }) + + it('refuses a stale PTY binding for the same leaf', () => { + expect( + retireTerminalLayoutLeaf(splitLayout(), { + leafId: 'leaf-b', + expectedPtyId: 'pty-old' + }) + ).toBeNull() + }) + + it('returns a removed parent for the final exact leaf', () => { + expect( + retireTerminalLayoutLeaf( + { + root: { type: 'leaf', leafId: 'leaf-a' }, + activeLeafId: 'leaf-a', + expandedLeafId: null, + ptyIdsByLeafId: { 'leaf-a': 'pty-a' } + }, + { leafId: 'leaf-a', expectedPtyId: 'pty-a' } + ) + ).toEqual({ layout: null, removedPtyId: 'pty-a' }) + }) +}) diff --git a/src/shared/terminal-layout-leaf-retirement.ts b/src/shared/terminal-layout-leaf-retirement.ts new file mode 100644 index 000000000000..90eb4130c49f --- /dev/null +++ b/src/shared/terminal-layout-leaf-retirement.ts @@ -0,0 +1,86 @@ +import type { TerminalLayoutSnapshot, TerminalPaneLayoutNode } from './types' + +export type TerminalLayoutLeafRetirement = { + layout: TerminalLayoutSnapshot | null + removedPtyId: string +} + +function removeLeaf(node: TerminalPaneLayoutNode, leafId: string): TerminalPaneLayoutNode | null { + if (node.type === 'leaf') { + return node.leafId === leafId ? null : node + } + const first = removeLeaf(node.first, leafId) + const second = removeLeaf(node.second, leafId) + if (!first) { + return second + } + if (!second) { + return first + } + return { ...node, first, second } +} + +function containsLeaf(node: TerminalPaneLayoutNode | null, leafId: string): boolean { + if (!node) { + return false + } + return node.type === 'leaf' + ? node.leafId === leafId + : containsLeaf(node.first, leafId) || containsLeaf(node.second, leafId) +} + +function firstLeafId(node: TerminalPaneLayoutNode): string { + return node.type === 'leaf' ? node.leafId : firstLeafId(node.first) +} + +function omitLeaf( + records: Record | undefined, + leafId: string +): Record | undefined { + if (!records || !Object.prototype.hasOwnProperty.call(records, leafId)) { + return records + } + const next = { ...records } + delete next[leafId] + return Object.keys(next).length > 0 ? next : undefined +} + +export function retireTerminalLayoutLeaf( + layout: TerminalLayoutSnapshot | null | undefined, + args: { leafId: string; expectedPtyId: string } +): TerminalLayoutLeafRetirement | null { + if ( + !layout?.root || + !containsLeaf(layout.root, args.leafId) || + layout.ptyIdsByLeafId?.[args.leafId] !== args.expectedPtyId + ) { + return null + } + const root = removeLeaf(layout.root, args.leafId) + if (!root) { + return { layout: null, removedPtyId: args.expectedPtyId } + } + const ptyIdsByLeafId = omitLeaf(layout.ptyIdsByLeafId, args.leafId) + const buffersByLeafId = omitLeaf(layout.buffersByLeafId, args.leafId) + const scrollbackRefsByLeafId = omitLeaf(layout.scrollbackRefsByLeafId, args.leafId) + const titlesByLeafId = omitLeaf(layout.titlesByLeafId, args.leafId) + const activeLeafId = + layout.activeLeafId && containsLeaf(root, layout.activeLeafId) + ? layout.activeLeafId + : firstLeafId(root) + return { + removedPtyId: args.expectedPtyId, + layout: { + root, + activeLeafId, + expandedLeafId: + layout.expandedLeafId && containsLeaf(root, layout.expandedLeafId) + ? layout.expandedLeafId + : null, + ...(ptyIdsByLeafId ? { ptyIdsByLeafId } : {}), + ...(buffersByLeafId ? { buffersByLeafId } : {}), + ...(scrollbackRefsByLeafId ? { scrollbackRefsByLeafId } : {}), + ...(titlesByLeafId ? { titlesByLeafId } : {}) + } + } +} diff --git a/src/shared/terminal-tab-close.ts b/src/shared/terminal-tab-close.ts index 55186d8046c8..3c985b63ae27 100644 --- a/src/shared/terminal-tab-close.ts +++ b/src/shared/terminal-tab-close.ts @@ -1,6 +1,13 @@ +// Why: the outer runtime RPC must outlive renderer durability adjudication; +// otherwise a valid close can look failed locally before the host commits it. +export const TERMINAL_TAB_CLOSE_RENDERER_TIMEOUT_MS = 20_000 +export const TERMINAL_TAB_CLOSE_RUNTIME_RPC_TIMEOUT_MS = 30_000 + export type TerminalTabCloseRequest = { requestId: string tabId: string + validateOnly?: boolean + expectedPtyIds?: string[] } export type TerminalTabCloseResponse = { diff --git a/src/shared/workspace-session-terminal-leaf-retirement.test.ts b/src/shared/workspace-session-terminal-leaf-retirement.test.ts new file mode 100644 index 000000000000..9d0a160ee948 --- /dev/null +++ b/src/shared/workspace-session-terminal-leaf-retirement.test.ts @@ -0,0 +1,95 @@ +import { describe, expect, it } from 'vitest' +import { getDefaultWorkspaceSession } from './constants' +import type { WorkspaceSessionState } from './types' +import { retireTerminalLeafInWorkspaceSession } from './workspace-session-terminal-leaf-retirement' + +const WORKTREE_ID = 'worktree-1' +const TAB_ID = 'terminal-1' +const LEAF_A = '11111111-1111-4111-8111-111111111111' +const LEAF_B = '22222222-2222-4222-8222-222222222222' + +function session(): WorkspaceSessionState { + return { + ...getDefaultWorkspaceSession(), + activeWorktreeId: WORKTREE_ID, + activeTabId: TAB_ID, + tabsByWorktree: { + [WORKTREE_ID]: [ + { + id: TAB_ID, + ptyId: 'pty-b', + worktreeId: WORKTREE_ID, + title: 'Terminal', + customTitle: null, + color: null, + sortOrder: 0, + createdAt: 1 + } + ] + }, + terminalLayoutsByTabId: { + [TAB_ID]: { + root: { + type: 'split', + direction: 'horizontal', + first: { type: 'leaf', leafId: LEAF_A }, + second: { type: 'leaf', leafId: LEAF_B } + }, + activeLeafId: LEAF_B, + expandedLeafId: null, + ptyIdsByLeafId: { [LEAF_A]: 'pty-a', [LEAF_B]: 'pty-b' } + } + }, + remoteSessionIdsByTabId: { [TAB_ID]: 'pty-b' }, + sleepingAgentSessionsByPaneKey: { + [`${TAB_ID}:${LEAF_A}`]: { + paneKey: `${TAB_ID}:${LEAF_A}`, + worktreeId: WORKTREE_ID, + agent: 'codex', + providerSession: { key: 'session_id', id: 'a' }, + prompt: '', + state: 'done', + capturedAt: 1, + updatedAt: 1 + }, + [`${TAB_ID}:${LEAF_B}`]: { + paneKey: `${TAB_ID}:${LEAF_B}`, + worktreeId: WORKTREE_ID, + agent: 'codex', + providerSession: { key: 'session_id', id: 'b' }, + prompt: '', + state: 'done', + capturedAt: 1, + updatedAt: 1 + } + } + } +} + +describe('retireTerminalLeafInWorkspaceSession', () => { + it('rebinds parent metadata to the surviving leaf and removes only exited pane state', () => { + const result = retireTerminalLeafInWorkspaceSession(session(), WORKTREE_ID, { + parentTabId: TAB_ID, + leafId: LEAF_B, + expectedPtyId: 'pty-b' + }) + + expect(result).toMatchObject({ retired: true, parentRemoved: false }) + expect(result.session.tabsByWorktree[WORKTREE_ID]?.[0]?.ptyId).toBe('pty-a') + expect(result.session.remoteSessionIdsByTabId?.[TAB_ID]).toBe('pty-a') + expect(result.session.sleepingAgentSessionsByPaneKey).toHaveProperty(`${TAB_ID}:${LEAF_A}`) + expect(result.session.sleepingAgentSessionsByPaneKey).not.toHaveProperty(`${TAB_ID}:${LEAF_B}`) + }) + + it('refuses a stale exit after the leaf has rebound', () => { + const original = session() + const result = retireTerminalLeafInWorkspaceSession(original, WORKTREE_ID, { + parentTabId: TAB_ID, + leafId: LEAF_B, + expectedPtyId: 'pty-old' + }) + + expect(result).toEqual({ session: expect.any(Object), retired: false, parentRemoved: false }) + expect(result.session).toBe(original) + }) +}) diff --git a/src/shared/workspace-session-terminal-leaf-retirement.ts b/src/shared/workspace-session-terminal-leaf-retirement.ts new file mode 100644 index 000000000000..bdf9d1b64f4a --- /dev/null +++ b/src/shared/workspace-session-terminal-leaf-retirement.ts @@ -0,0 +1,66 @@ +import { makePaneKey } from './stable-pane-id' +import { retireTerminalLayoutLeaf } from './terminal-layout-leaf-retirement' +import type { WorkspaceSessionState } from './types' +import { closeTerminalTabInWorkspaceSession } from './workspace-session-terminal-tab-close' + +export type WorkspaceSessionTerminalLeafRetirement = { + session: WorkspaceSessionState + retired: boolean + parentRemoved: boolean +} + +export function retireTerminalLeafInWorkspaceSession( + session: WorkspaceSessionState, + worktreeId: string, + args: { parentTabId: string; leafId: string; expectedPtyId: string } +): WorkspaceSessionTerminalLeafRetirement { + const layout = session.terminalLayoutsByTabId[args.parentTabId] + const retirement = retireTerminalLayoutLeaf(layout, args) + if (!retirement) { + return { session, retired: false, parentRemoved: false } + } + if (!retirement.layout) { + const closed = closeTerminalTabInWorkspaceSession(session, worktreeId, args.parentTabId, { + allowPinnedRetirement: true + }) + return { + session: closed.closed ? closed.session : session, + retired: closed.closed, + parentRemoved: closed.closed + } + } + + const replacementPtyId = + retirement.layout.ptyIdsByLeafId?.[retirement.layout.activeLeafId ?? ''] ?? + Object.values(retirement.layout.ptyIdsByLeafId ?? {})[0] ?? + null + const tabs = (session.tabsByWorktree[worktreeId] ?? []).map((tab) => + tab.id === args.parentTabId && tab.ptyId === args.expectedPtyId + ? { ...tab, ptyId: replacementPtyId } + : tab + ) + const remoteSessionIdsByTabId = { ...session.remoteSessionIdsByTabId } + if (remoteSessionIdsByTabId[args.parentTabId] === args.expectedPtyId) { + if (replacementPtyId) { + remoteSessionIdsByTabId[args.parentTabId] = replacementPtyId + } else { + delete remoteSessionIdsByTabId[args.parentTabId] + } + } + const sleepingAgentSessionsByPaneKey = { ...session.sleepingAgentSessionsByPaneKey } + delete sleepingAgentSessionsByPaneKey[makePaneKey(args.parentTabId, args.leafId)] + return { + retired: true, + parentRemoved: false, + session: { + ...session, + tabsByWorktree: { ...session.tabsByWorktree, [worktreeId]: tabs }, + terminalLayoutsByTabId: { + ...session.terminalLayoutsByTabId, + [args.parentTabId]: retirement.layout + }, + remoteSessionIdsByTabId, + sleepingAgentSessionsByPaneKey + } + } +} diff --git a/src/shared/workspace-session-terminal-tab-close.ts b/src/shared/workspace-session-terminal-tab-close.ts index 2b0b17a9d3af..9beec4164981 100644 --- a/src/shared/workspace-session-terminal-tab-close.ts +++ b/src/shared/workspace-session-terminal-tab-close.ts @@ -156,14 +156,18 @@ function deriveActiveSurface( export function closeTerminalTabInWorkspaceSession( session: WorkspaceSessionState, worktreeId: string, - tabId: string + tabId: string, + options: { allowPinnedRetirement?: boolean } = {} ): WorkspaceSessionTerminalTabCloseResult { const terminalRow = session.tabsByWorktree[worktreeId]?.find((tab) => tab.id === tabId) const unifiedTerminalTabs = findUnifiedTerminalTabs(session, worktreeId, tabId) if (!terminalRow && unifiedTerminalTabs.length === 0) { return { session, ptyIdsToKill: [], closed: false, pinned: false } } - if (terminalRow?.isPinned || unifiedTerminalTabs.some((tab) => tab.isPinned)) { + if ( + options.allowPinnedRetirement !== true && + (terminalRow?.isPinned || unifiedTerminalTabs.some((tab) => tab.isPinned)) + ) { return { session, ptyIdsToKill: [], closed: false, pinned: true } }