From d285a67c0a3ce1007b87764b81c8a4356a99f34b Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 25 Sep 2026 13:28:26 -0700 Subject: [PATCH 01/15] fix(terminal): every explicit terminal close commits through one main transaction A renderer save cannot shrink terminal membership once main owns a repo's topology, so desktop tab and pane closes, CLI split-pane closes and mobile split-pane closes only became durable when the killed process's exit retired the surface. A close whose kill failed or threw, or whose exit was never certified, came back after a reload. Every close now reaches closeTerminalSurface: the renderer sends an explicit intent for user and cleanup closes, the CLI and mobile split-pane closes commit the pane after their stop, and the headless and relayed mobile closes reuse the same commit. A failed flush keeps the in-memory removal and no longer cancels the kill. Exit retirement is unchanged. --- .../register-core-handlers.test.ts | 2 +- .../register-core-handlers.ts | 2 +- src/main/ipc/session.ts | 18 +- ...ld-headless-mobile-session-browser-tabs.ts | 61 ++++--- ...time-close-headless-mobile-terminal-tab.ts | 9 +- .../orca-runtime-close-mobile-session-tab.ts | 8 +- ...runtime-stop-explicitly-closed-tab-ptys.ts | 12 +- ...-runtime-terminal-close-continuity.test.ts | 30 ++-- ...rca-runtime-terminal-surface-close.test.ts | 169 ++++++++++++++++++ src/main/runtime/terminal-surface-close.ts | 42 +++++ src/preload/api/session-bridge.ts | 1 + src/preload/api/workspace-session-api.ts | 6 + .../terminal-pane/pending-split-close.test.ts | 12 ++ .../use-terminal-pane-close-actions.ts | 5 +- .../terminal-surface-close-intent.ts | 12 ++ .../terminal-tab-close-intent.test.ts | 87 +++++++++ .../src/store/terminals/terminal-tab-close.ts | 4 + .../preload-api/web-workspace-session-api.ts | 2 + 18 files changed, 433 insertions(+), 49 deletions(-) create mode 100644 src/main/runtime/orca-runtime-terminal-surface-close.test.ts create mode 100644 src/main/runtime/terminal-surface-close.ts create mode 100644 src/renderer/src/store/terminals/terminal-surface-close-intent.ts create mode 100644 src/renderer/src/store/terminals/terminal-tab-close-intent.test.ts diff --git a/src/main/ipc/register-core-handlers/register-core-handlers.test.ts b/src/main/ipc/register-core-handlers/register-core-handlers.test.ts index 0d4f04046b02..f1cd4447dfea 100644 --- a/src/main/ipc/register-core-handlers/register-core-handlers.test.ts +++ b/src/main/ipc/register-core-handlers/register-core-handlers.test.ts @@ -552,7 +552,7 @@ describe('registerCoreHandlers', () => { expect(registerLocalhostWorktreeLabelHandlersMock).toHaveBeenCalledWith(store) expect(registerTelemetryHandlersMock).toHaveBeenCalledWith(store) expect(registerOrcaProfileHandlersMock).toHaveBeenCalledWith(store, { onBeforeRelaunch }) - expect(registerSessionHandlersMock).toHaveBeenCalledWith(store) + expect(registerSessionHandlersMock).toHaveBeenCalledWith(store, runtime) expect(registerUIHandlersMock).toHaveBeenCalledWith(store, { isDashboardPopoutRenderer: isDashboardPopoutRendererMock }) diff --git a/src/main/ipc/register-core-handlers/register-core-handlers.ts b/src/main/ipc/register-core-handlers/register-core-handlers.ts index 0b329335755a..698d3e8de5fd 100644 --- a/src/main/ipc/register-core-handlers/register-core-handlers.ts +++ b/src/main/ipc/register-core-handlers/register-core-handlers.ts @@ -202,7 +202,7 @@ export function registerCoreHandlers( registerBrowserHandlers() registerShellHandlers(store) registerPetHandlers() - registerSessionHandlers(store) + registerSessionHandlers(store, runtime) registerUIHandlers(store, { isDashboardPopoutRenderer }) registerEmulatorFrameStreamHandlers() registerEmulatorVideoStreamHandlers() diff --git a/src/main/ipc/session.ts b/src/main/ipc/session.ts index 9fdfd8214b27..4309ec388af4 100644 --- a/src/main/ipc/session.ts +++ b/src/main/ipc/session.ts @@ -1,11 +1,12 @@ import { ipcMain } from 'electron' import type { Store } from '../persistence' +import type { OrcaRuntimeService } from '../runtime/orca-runtime' import type { WorkspaceSessionPatch, WorkspaceSessionState } from '../../shared/workspace-session-state-types' -export function registerSessionHandlers(store: Store): void { +export function registerSessionHandlers(store: Store, runtime: OrcaRuntimeService): void { // Why: hostId is an optional second arg so an older renderer that invokes // these channels without it keeps reading/writing the 'local' partition // exactly as before. Channel names stay stable. @@ -28,6 +29,21 @@ export function registerSessionHandlers(store: Store): void { store.patchWorkspaceSession(args, hostId) }) + // Why: a renderer save cannot shrink membership main owns, so each close commits it explicitly. + ipcMain.handle( + 'session:close-terminal-surface', + (_event, args: { worktreeId: string; tabId: string; leafId?: string }) => { + if (typeof args?.worktreeId !== 'string' || typeof args.tabId !== 'string') { + throw new Error('invalid_terminal_surface') + } + runtime.closeTerminalSurfaceFromRenderer({ + worktreeId: args.worktreeId, + tabId: args.tabId, + ...(typeof args.leafId === 'string' ? { leafId: args.leafId } : {}) + }) + } + ) + ipcMain.handle('session:flush', () => { // Why: durable lifecycle RPCs must propagate disk failures instead of // returning success through Store.flush(), which intentionally only logs. diff --git a/src/main/runtime/orca-runtime-build-headless-mobile-session-browser-tabs.ts b/src/main/runtime/orca-runtime-build-headless-mobile-session-browser-tabs.ts index 5aa6e46cc589..d942a1e065c5 100644 --- a/src/main/runtime/orca-runtime-build-headless-mobile-session-browser-tabs.ts +++ b/src/main/runtime/orca-runtime-build-headless-mobile-session-browser-tabs.ts @@ -7,11 +7,9 @@ import type { } from '../../shared/runtime-types' import { getRuntimeBrowserPageRegistry } from './runtime-browser-page-registry' import type { Tab } from '../../shared/tab-types' -import { closeTerminalTabInWorkspaceSession } from '../../shared/workspace-session-terminal-tab-close' -import { advanceTerminalTopologyRevision } from './workspace-session-terminal-membership-authority' +import { closeTerminalSurfaceInWorkspaceSession } from './terminal-surface-close' import type { PtyControllerInventory } from './runtime-pty-controller-contract' import { FLOATING_TERMINAL_WORKTREE_ID } from '../../shared/constants' -import { rollbackWorkspaceSessionAfterFailedAsyncWrite } from './workspace-session-failed-write-rollback' export class OrcaRuntimeWithBuildHeadlessMobileSessionBrowserTabs extends OrcaRuntimeWithPersistTerminalSurfaceRetirements { // Why: headless serve backs browser panes with offscreen WebContents that live @@ -78,18 +76,20 @@ export class OrcaRuntimeWithBuildHeadlessMobileSessionBrowserTabs extends OrcaRu return tab ? { color: tab.color, isPinned: tab.isPinned } : null } - protected commitHeadlessTerminalTabRetirement( + /** + * The one close transaction every explicit terminal close reaches: commit the membership + * removal in the owning host's partition, then flush. Callers publish and kill afterwards. + */ + protected closeTerminalSurface( worktreeId: string, - parentTabId: string, - options: { allowMissing?: boolean; force?: boolean } = {} + tabId: string, + options: { leafId?: string; allowMissing?: boolean; force?: boolean } = {} ): string[] { const session = this.getWorkspaceSessionForWorktree(worktreeId) if (!session || !this.store?.setWorkspaceSession || !this.store.flushOrThrow) { throw new Error('workspace_session_unavailable') } - const result = closeTerminalTabInWorkspaceSession(session, worktreeId, parentTabId, { - force: options.force - }) + const result = closeTerminalSurfaceInWorkspaceSession(session, worktreeId, tabId, options) if (result.pinned) { throw new Error('terminal_tab_pinned') } @@ -97,27 +97,44 @@ export class OrcaRuntimeWithBuildHeadlessMobileSessionBrowserTabs extends OrcaRu if (!options.allowMissing) { throw new Error('tab_not_found') } + return [] } - const persisted = result.closed - ? advanceTerminalTopologyRevision(result.session, worktreeId) - : session - this.setWorkspaceSessionForWorktree(worktreeId, persisted) - const staged = this.getWorkspaceSessionForWorktree(worktreeId) + this.setWorkspaceSessionForWorktree(worktreeId, result.session) try { this.store.flushOrThrow() } catch (error) { - const current = this.getWorkspaceSessionForWorktree(worktreeId) - if (staged && current) { - const rolledBack = rollbackWorkspaceSessionAfterFailedAsyncWrite(session, staged, current) - if (rolledBack !== current) { - this.setWorkspaceSessionForWorktree(worktreeId, rolledBack) - } - } - throw error + // Why no rollback: bookkeeping must not undo a user's close or skip its kill; the removal + // stays in memory and the next flush writes it. Only host-started retirements roll back. + console.error('[runtime] failed to flush terminal close:', error) } return result.ptyIdsToKill } + /** The desktop renderer's close intent: the renderer already ran its pin guard and owns the kill. */ + closeTerminalSurfaceFromRenderer(args: { + worktreeId: string + tabId: string + leafId?: string + }): void { + this.closeTerminalSurface(args.worktreeId, args.tabId, { + leafId: args.leafId, + allowMissing: true, + force: true + }) + } + + /** Commits a split pane's close once its process was stopped; no session means nothing persisted. */ + protected closeTerminalLeaf(worktreeId: string, tabId: string, leafId: string): void { + try { + // Why force: the process is already stopped, so a pin must not fail the close after the fact. + this.closeTerminalSurface(worktreeId, tabId, { leafId, allowMissing: true, force: true }) + } catch (error) { + if (!(error instanceof Error) || error.message !== 'workspace_session_unavailable') { + throw error + } + } + } + protected persistHeadlessTerminalTabOrder(worktreeId: string, tabOrder: readonly string[]): void { const session = this.getWorkspaceSessionForWorktree(worktreeId) if (!session || !this.store?.setWorkspaceSession) { diff --git a/src/main/runtime/orca-runtime-close-headless-mobile-terminal-tab.ts b/src/main/runtime/orca-runtime-close-headless-mobile-terminal-tab.ts index b326d00ec6c3..74e9c3f4288f 100644 --- a/src/main/runtime/orca-runtime-close-headless-mobile-terminal-tab.ts +++ b/src/main/runtime/orca-runtime-close-headless-mobile-terminal-tab.ts @@ -36,11 +36,10 @@ export class OrcaRuntimeWithCloseHeadlessMobileTerminalTab extends OrcaRuntimeWi ) return proof ? [proof] : [] }) - const projectedPtyIds = this.commitHeadlessTerminalTabRetirement( - worktreeId, - closedParentTabId, - { allowMissing: options.allowMissingPersistedTab, force: options.force } - ) + const projectedPtyIds = this.closeTerminalSurface(worktreeId, closedParentTabId, { + allowMissing: options.allowMissingPersistedTab, + force: options.force + }) this.clearRuntimeSessionOwnershipForMobileTab(worktreeId, snapshot, closedParentTabId) if (options.authorizedPty) { options.authorizedPty.runtimeSessionOwned = false diff --git a/src/main/runtime/orca-runtime-close-mobile-session-tab.ts b/src/main/runtime/orca-runtime-close-mobile-session-tab.ts index 2ef5b77069d6..8ac3f252b5c0 100644 --- a/src/main/runtime/orca-runtime-close-mobile-session-tab.ts +++ b/src/main/runtime/orca-runtime-close-mobile-session-tab.ts @@ -238,9 +238,9 @@ export class OrcaRuntimeWithCloseMobileSessionTab extends OrcaRuntimeWithRefuseU }) this.notifyRendererOfHeadlessTerminalClose(tab.parentTabId) } else if (retirement.hasPersistedTab) { - this.commitHeadlessTerminalTabRetirement(worktreeId, tab.parentTabId, { - force: options.force - }) + // Why: the renderer's close normally commits this through its own intent; this covers + // a renderer that acknowledged a tab it no longer listed. + this.closeTerminalSurface(worktreeId, tab.parentTabId, { force: options.force }) } this.clearRuntimeSessionOwnershipForMobileTab(worktreeId, snapshot, tab.parentTabId) return finishCommittedClose() @@ -268,6 +268,8 @@ export class OrcaRuntimeWithCloseMobileSessionTab extends OrcaRuntimeWithRefuseU if (this.ptyController?.kill(pty.ptyId) !== true) { throw new Error('terminal_close_failed') } + // Why: the pane's removal is this close's own commit, not a side effect of its exit. + this.closeTerminalLeaf(worktreeId, tab.parentTabId, tab.leafId) return finishCommittedClose() } this.notifier.closeTerminal(tab.parentTabId) diff --git a/src/main/runtime/orca-runtime-stop-explicitly-closed-tab-ptys.ts b/src/main/runtime/orca-runtime-stop-explicitly-closed-tab-ptys.ts index 196845d09ef9..ed926fc27fea 100644 --- a/src/main/runtime/orca-runtime-stop-explicitly-closed-tab-ptys.ts +++ b/src/main/runtime/orca-runtime-stop-explicitly-closed-tab-ptys.ts @@ -5,6 +5,7 @@ import { SSH_PROVIDER_UNREGISTERED_REASON } from '../../shared/pty-liveness-verd import type { RuntimeTerminalClose } from '../../shared/runtime-types' import { countTerminalLayoutLeaves } from './headless-terminal-split-layout' import type { RuntimePtyTabCloseAuthority } from './runtime-terminal-state-records' +import { parsePaneKey } from '../../shared/stable-pane-id' export class OrcaRuntimeWithStopExplicitlyClosedTabPtys extends OrcaRuntimeWithFocusTerminal { protected async stopExplicitlyClosedTabPtys( @@ -155,6 +156,11 @@ export class OrcaRuntimeWithStopExplicitlyClosedTabPtys extends OrcaRuntimeWithF return this.describeTerminalClose(handle, tabId, pty.pty.ptyId, ptyKilled) } const ptyKilled = await this.stopExplicitlyClosedTabPtys([pty.pty.ptyId], pty.pty.ptyId) + const leafId = surface?.tab.leafId ?? parsePaneKey(pty.pty.paneKey ?? '')?.leafId + if (ptyKilled && siblingCount > 1 && leafId) { + // Why: the pane's removal is this close's own commit, not a side effect of its exit. + this.closeTerminalLeaf(pty.pty.worktreeId, tabId, leafId) + } if (!ptyKilled || siblingCount <= 1) { if (surface) { // Why: paired viewers keep ended streams mounted until the HUB publishes removal, so explicit close uses the durable host-tab transaction instead of viewer-local exit handling. @@ -176,7 +182,8 @@ export class OrcaRuntimeWithStopExplicitlyClosedTabPtys extends OrcaRuntimeWithF } this.assertGraphReady() const { leaf } = this.getLiveLeafForHandle(handle) - // Why: in a multi-pane tab, killing the PTY is enough (renderer's exit handler closes the pane); an extra IPC close would race it and close the whole tab. + // Why: in a multi-pane tab the renderer's exit handler removes the killed pane from view; an + // extra IPC close would race it and close the whole tab. Membership is committed below. const siblingCount = this.countLeavesInTab(leaf.tabId) const ptyIdsToKill = siblingCount <= 1 @@ -190,6 +197,9 @@ export class OrcaRuntimeWithStopExplicitlyClosedTabPtys extends OrcaRuntimeWithF const ptyKilled = leaf.ptyId ? await this.stopExplicitlyClosedTabPtys(ptyIdsToKill, leaf.ptyId) : false + if (siblingCount > 1) { + this.closeTerminalLeaf(leaf.worktreeId, leaf.tabId, leaf.leafId) + } if (siblingCount > 1 ? !ptyKilled : !this.notifier?.closeTerminalTab) { this.notifier?.closeTerminal(leaf.tabId, leaf.paneRuntimeId) } diff --git a/src/main/runtime/orca-runtime-terminal-close-continuity.test.ts b/src/main/runtime/orca-runtime-terminal-close-continuity.test.ts index ef24301c7cf5..0f6237af5f2f 100644 --- a/src/main/runtime/orca-runtime-terminal-close-continuity.test.ts +++ b/src/main/runtime/orca-runtime-terminal-close-continuity.test.ts @@ -72,25 +72,27 @@ describe('terminal close and handle incarnation continuity', () => { unsubscribe() }) - it('publishes no retirement or absence when the durable headless close fails', async () => { + it('still kills and keeps the removal when the durable headless close fails to flush', async () => { const harness = await createStaleTabCloseHarness({ headless: true }) - const published = vi.fn() - const unsubscribe = harness.runtime.onMobileSessionTabsChanged(published) + const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined) harness.rejectPersistenceFlush(new Error('disk-full')) - await expect(harness.runtime.closeTerminalTab(harness.terminal.handle)).rejects.toThrow( - 'disk-full' - ) + await expect(harness.runtime.closeTerminalTab(harness.terminal.handle)).resolves.toMatchObject({ + tabId: TAB_ID, + closeMode: 'tab' + }) - expect(harness.kill).not.toHaveBeenCalled() - expect(published).not.toHaveBeenCalled() - expect(harness.getSession().tabsByWorktree[WORKTREE_ID]).toHaveLength(1) + // Why: a failed flush is bookkeeping; the user's close still stops its process and the + // in-memory removal stays for the next flush to write. + expect(harness.kill).toHaveBeenCalledWith(RUNTIME_OWNED_PTY_ID) + expect(harness.getSession().tabsByWorktree[WORKTREE_ID]).toEqual([]) const snapshot = await harness.runtime.listMobileSessionTabs(`id:${WORKTREE_ID}`) - expect(snapshot).toMatchObject({ - tabs: [expect.objectContaining({ parentTabId: TAB_ID, leafId: LEAF_ID })] - }) - expect(snapshot.retiredTerminalSurfaces).toBeUndefined() - unsubscribe() + expect(snapshot.tabs).toEqual([]) + expect(errorSpy).toHaveBeenCalledWith( + '[runtime] failed to flush terminal close:', + expect.any(Error) + ) + errorSpy.mockRestore() }) it('publishes each split leaf retirement with its own terminal handle', async () => { diff --git a/src/main/runtime/orca-runtime-terminal-surface-close.test.ts b/src/main/runtime/orca-runtime-terminal-surface-close.test.ts new file mode 100644 index 000000000000..296b4bab8920 --- /dev/null +++ b/src/main/runtime/orca-runtime-terminal-surface-close.test.ts @@ -0,0 +1,169 @@ +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, expect, it } from 'vitest' +import { makePaneKey } from '../../shared/stable-pane-id' +import type { WorkspaceSessionState } from '../../shared/workspace-session-state-types' +import { Store } from '../persistence/loading-store/store' +import { OrcaRuntimeService } from './orca-runtime' +import { + LEAF_ID, + PTY_ID, + REPO_ID, + SIBLING_LEAF_ID, + SIBLING_PTY_ID, + TAB_ID, + WORKTREE_ID, + WORKTREE_PATH, + createHarness, + makeSession +} from './__fixtures__/orca-runtime-terminal-close-continuity-fixtures' +import { advanceTerminalTopologyRevision } from './workspace-session-terminal-membership-authority' + +const splitLayout = { + root: { + type: 'split' as const, + direction: 'horizontal' as const, + first: { type: 'leaf' as const, leafId: LEAF_ID }, + second: { type: 'leaf' as const, leafId: SIBLING_LEAF_ID } + }, + activeLeafId: LEAF_ID, + expandedLeafId: null, + ptyIdsByLeafId: { [LEAF_ID]: PTY_ID, [SIBLING_LEAF_ID]: SIBLING_PTY_ID } +} + +function splitSession(): WorkspaceSessionState { + return { ...makeSession(), terminalLayoutsByTabId: { [TAB_ID]: splitLayout } } +} + +const directories: string[] = [] +afterEach(() => { + for (const directory of directories.splice(0)) { + rmSync(directory, { recursive: true, force: true }) + } +}) + +/** A real store whose repo already has host-authoritative membership, as any repo with an exit does. */ +function createPersistedRuntime(session: WorkspaceSessionState) { + const directory = mkdtempSync(join(tmpdir(), 'orca-surface-close-')) + directories.push(directory) + const dataFile = join(directory, 'orca-data.json') + const store = new Store({ dataFile }) + store.addRepo({ + id: REPO_ID, + path: WORKTREE_PATH, + displayName: 'Fixture', + badgeColor: 'gray', + addedAt: 1 + }) + store.setWorkspaceSession(advanceTerminalTopologyRevision(session, WORKTREE_ID)) + store.flushOrThrow() + return { + store, + runtime: new OrcaRuntimeService(store), + reload: async () => { + store.flush() + store.freezeWrites() + await store.waitForPendingWrite() + return new Store({ dataFile }).getWorkspaceSession() + } + } +} + +/** What a renderer save carries after its own close: membership without the closed surface. */ +function rendererSaveWithout( + session: WorkspaceSessionState, + leafId?: string +): WorkspaceSessionState { + const { terminalTopologyRevisionByRepoId: _hostPrivate, ...rendererView } = session + if (!leafId) { + return { ...rendererView, tabsByWorktree: { [WORKTREE_ID]: [] }, terminalLayoutsByTabId: {} } + } + return { + ...rendererView, + terminalLayoutsByTabId: { + [TAB_ID]: { + root: { type: 'leaf', leafId: SIBLING_LEAF_ID }, + activeLeafId: SIBLING_LEAF_ID, + expandedLeafId: null, + ptyIdsByLeafId: { [SIBLING_LEAF_ID]: SIBLING_PTY_ID } + } + } + } +} + +describe('renderer close intents', () => { + it('keeps a closed tab closed across a renderer save and a reload', async () => { + const { store, runtime, reload } = createPersistedRuntime(makeSession()) + + runtime.closeTerminalSurfaceFromRenderer({ worktreeId: WORKTREE_ID, tabId: TAB_ID }) + store.setWorkspaceSession(rendererSaveWithout(store.getWorkspaceSession())) + + expect((await reload()).tabsByWorktree[WORKTREE_ID]).toEqual([]) + }) + + it('keeps a closed split pane closed across a renderer save and a reload', async () => { + const { store, runtime, reload } = createPersistedRuntime(splitSession()) + + runtime.closeTerminalSurfaceFromRenderer({ + worktreeId: WORKTREE_ID, + tabId: TAB_ID, + leafId: LEAF_ID + }) + store.setWorkspaceSession(rendererSaveWithout(store.getWorkspaceSession(), LEAF_ID)) + + const reloaded = await reload() + expect(reloaded.tabsByWorktree[WORKTREE_ID]).toEqual([expect.objectContaining({ id: TAB_ID })]) + expect(reloaded.terminalLayoutsByTabId[TAB_ID]?.root).toEqual({ + type: 'leaf', + leafId: SIBLING_LEAF_ID + }) + expect(reloaded.terminalPtyIncarnationsByPaneKey?.[makePaneKey(TAB_ID, LEAF_ID)]).toBe( + undefined + ) + }) +}) + +describe('CLI close of one pane in a split tab', () => { + it('commits the pane removal without waiting for its process exit', async () => { + const harness = createHarness() + harness.syncSplitFixtureGraph() + // A verified stop that never reports an exit: membership must not ride on one. + harness.setVerifiedStopResult(true) + const terminal = (await harness.runtime.listTerminals(`id:${WORKTREE_ID}`)).terminals.find( + (candidate) => candidate.ptyId === PTY_ID + )! + + await expect(harness.runtime.closeTerminal(terminal.handle)).resolves.toMatchObject({ + tabId: TAB_ID, + ptyKilled: true + }) + + const session = harness.getSession() + expect(session.tabsByWorktree[WORKTREE_ID]).toEqual([expect.objectContaining({ id: TAB_ID })]) + expect(session.terminalLayoutsByTabId[TAB_ID]).toMatchObject({ + root: { type: 'leaf', leafId: SIBLING_LEAF_ID }, + ptyIdsByLeafId: { [SIBLING_LEAF_ID]: SIBLING_PTY_ID } + }) + expect(harness.closeTerminalTab).not.toHaveBeenCalled() + expect(harness.closeTerminal).not.toHaveBeenCalled() + }) +}) + +describe('mobile close of one pane in a split tab', () => { + it('commits the pane removal alongside its kill', async () => { + const harness = createHarness({ publishMobileSurface: true, registerPtyBacked: true }) + harness.syncSplitFixtureGraph() + + await expect( + harness.runtime.closeMobileSessionTab(`id:${WORKTREE_ID}`, `${TAB_ID}::${LEAF_ID}`, { + reason: 'user' + }) + ).resolves.toMatchObject({ closed: true }) + + expect(harness.kill).toHaveBeenCalledWith(PTY_ID) + expect(harness.getSession().terminalLayoutsByTabId[TAB_ID]).toMatchObject({ + root: { type: 'leaf', leafId: SIBLING_LEAF_ID } + }) + }) +}) diff --git a/src/main/runtime/terminal-surface-close.ts b/src/main/runtime/terminal-surface-close.ts new file mode 100644 index 000000000000..55841e2fe9ca --- /dev/null +++ b/src/main/runtime/terminal-surface-close.ts @@ -0,0 +1,42 @@ +import type { WorkspaceSessionState } from '../../shared/workspace-session-state-types' +import { + closeTerminalTabInWorkspaceSession, + type WorkspaceSessionTerminalTabCloseResult +} from '../../shared/workspace-session-terminal-tab-close' +import { layoutContainsLeafId } from '../persistence/restoring-sessions/terminal-layout-normalization' +import { countTerminalLayoutLeaves } from './headless-terminal-split-layout' +import { retireTerminalSurfaceFromPersistence } from './mobile-session-terminal-persistence-retirement' +import { advanceTerminalTopologyRevision } from './workspace-session-terminal-membership-authority' + +/** + * The membership half of every explicit terminal close: removes a tab, or one leaf of a split + * tab, and advances the repo's topology revision so a stale renderer save cannot restore it. + * Closing a tab's last leaf closes the tab. + */ +export function closeTerminalSurfaceInWorkspaceSession( + session: WorkspaceSessionState, + worktreeId: string, + tabId: string, + options: { leafId?: string; force?: boolean } = {} +): WorkspaceSessionTerminalTabCloseResult { + const layout = session.terminalLayoutsByTabId[tabId] + if (options.leafId && layout && countTerminalLayoutLeaves(layout.root) > 1) { + if (!layoutContainsLeafId(layout.root, options.leafId)) { + return { session, ptyIdsToKill: [], closed: false, pinned: false } + } + // The leaf's own binding is passed so the retirement's stale-binding fence always admits it. + const retired = retireTerminalSurfaceFromPersistence(session, { + worktreeId, + parentTabId: tabId, + leafId: options.leafId, + ptyId: layout.ptyIdsByLeafId?.[options.leafId] ?? '' + }) + return { session: retired, ptyIdsToKill: [], closed: true, pinned: false } + } + const result = closeTerminalTabInWorkspaceSession(session, worktreeId, tabId, { + force: options.force + }) + return result.closed + ? { ...result, session: advanceTerminalTopologyRevision(result.session, worktreeId) } + : result +} diff --git a/src/preload/api/session-bridge.ts b/src/preload/api/session-bridge.ts index 22d342cd2c1f..537e15179ddd 100644 --- a/src/preload/api/session-bridge.ts +++ b/src/preload/api/session-bridge.ts @@ -7,6 +7,7 @@ export const sessionApi = { listHostIds: () => ipcRenderer.invoke('session:list-host-ids'), set: (args, hostId) => ipcRenderer.invoke('session:set', args, hostId), patch: (args, hostId) => ipcRenderer.invoke('session:patch', args, hostId), + closeTerminalSurface: (args) => ipcRenderer.invoke('session:close-terminal-surface', args), flush: () => ipcRenderer.invoke('session:flush'), readTerminalScrollback: (args) => ipcRenderer.sendSync('session:read-terminal-scrollback-sync', args), diff --git a/src/preload/api/workspace-session-api.ts b/src/preload/api/workspace-session-api.ts index 4c31b6e5db87..fb42ec3bd27b 100644 --- a/src/preload/api/workspace-session-api.ts +++ b/src/preload/api/workspace-session-api.ts @@ -19,6 +19,12 @@ export type WorkspaceSessionApi = { listHostIds: () => Promise set: (args: WorkspaceSessionState, hostId?: ExecutionHostId) => Promise patch: (args: WorkspaceSessionPatch, hostId?: ExecutionHostId) => Promise + /** Commits a terminal tab (or split pane, with leafId) close into main's membership. */ + closeTerminalSurface: (args: { + worktreeId: string + tabId: string + leafId?: string + }) => Promise flush: () => Promise readTerminalScrollback: (args: { ref: string }) => string | null setSync: (args: WorkspaceSessionState, hostId?: ExecutionHostId) => void diff --git a/src/renderer/src/components/terminal-pane/pending-split-close.test.ts b/src/renderer/src/components/terminal-pane/pending-split-close.test.ts index 5a022ef9c993..edeb731ce78d 100644 --- a/src/renderer/src/components/terminal-pane/pending-split-close.test.ts +++ b/src/renderer/src/components/terminal-pane/pending-split-close.test.ts @@ -191,3 +191,15 @@ it('retires a local folder-workspace split without a git worktree row', async () await p.connecting expect(window.api.pty.kill).toHaveBeenCalledTimes(2) }) + +it('commits the explicit split close in main by its leaf', async () => { + const p = await preparePendingSplitClose() + const closeTerminalSurface = vi.fn().mockResolvedValue(undefined) + Object.assign(window.api, { session: { ...window.api.session, closeTerminalSurface } }) + p.actions.executeClosePane(1) + expect(closeTerminalSurface).toHaveBeenCalledExactlyOnceWith({ + worktreeId: 'workspace', + tabId: p.tabId, + leafId: p.leafId + }) +}) diff --git a/src/renderer/src/components/terminal-pane/use-terminal-pane-close-actions.ts b/src/renderer/src/components/terminal-pane/use-terminal-pane-close-actions.ts index 3e8dd463a30e..c1adb8976413 100644 --- a/src/renderer/src/components/terminal-pane/use-terminal-pane-close-actions.ts +++ b/src/renderer/src/components/terminal-pane/use-terminal-pane-close-actions.ts @@ -16,6 +16,7 @@ import { clearPaneTerminalError } from './terminal-error-accumulation' import type { TerminalPaneBindingController } from './use-terminal-pane-layout-bindings' import { retireUnboundIpcTerminalPane } from './retire-unbound-ipc-terminal-pane' import { capturePendingTerminalPaneClose } from './terminal-pane-close-admission' +import { commitTerminalSurfaceClose } from '@/store/terminals/terminal-surface-close-intent' export function useTerminalPaneCloseActions(controller: TerminalPaneBindingController) { const confirmedCloseRef = useRef<(() => void) | null>(null) @@ -50,6 +51,7 @@ export function useTerminalPaneCloseActions(controller: TerminalPaneBindingContr clearSessionRestoredBannerForPane(paneId) const leafId = manager.getLeafId(paneId) if (leafId) { + commitTerminalSurfaceClose({ worktreeId, tabId, leafId }) retireUnboundIpcTerminalPane({ getState: useAppStore.getState, tabId, @@ -82,7 +84,8 @@ export function useTerminalPaneCloseActions(controller: TerminalPaneBindingContr onCloseTab, syncPanePtyLayoutBinding, syncPanePtyLayoutBindingForLeaf, - tabId + tabId, + worktreeId ] ) const getCloseDialogCopyKind = useCallback( diff --git a/src/renderer/src/store/terminals/terminal-surface-close-intent.ts b/src/renderer/src/store/terminals/terminal-surface-close-intent.ts new file mode 100644 index 000000000000..6b231449f427 --- /dev/null +++ b/src/renderer/src/store/terminals/terminal-surface-close-intent.ts @@ -0,0 +1,12 @@ +/** Commits a terminal tab or split-pane close in main, which owns membership: a renderer save + * cannot shrink it, so without this the close would ride on the PTY exit. */ +export function commitTerminalSurfaceClose(args: { + worktreeId: string + tabId: string + leafId?: string +}): void { + // Why optional: an older preload can linger through an in-place renderer reload. + void globalThis.window?.api?.session?.closeTerminalSurface?.(args)?.catch((error: unknown) => { + console.warn('[terminal-close] main did not commit the close', error) + }) +} diff --git a/src/renderer/src/store/terminals/terminal-tab-close-intent.test.ts b/src/renderer/src/store/terminals/terminal-tab-close-intent.test.ts new file mode 100644 index 000000000000..cf10e3fec9d7 --- /dev/null +++ b/src/renderer/src/store/terminals/terminal-tab-close-intent.test.ts @@ -0,0 +1,87 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' +import type * as AgentStatusModule from '@/lib/agent-status' +import { + TEST_REPO, + createTestStore, + makeTab, + makeWorktree, + seedStore +} from '../slices/store-test-helpers' +import { createStoreCascadesMockApi } from '../slices/store-cascades-test-harness' + +vi.mock('sonner', () => ({ + toast: { info: vi.fn(), success: vi.fn(), error: vi.fn(), warning: vi.fn() } +})) + +vi.mock('@/components/terminal-pane/pty-dispatcher', () => ({ + restorePtyDataHandlersAfterFailedShutdown: vi.fn(), + unregisterPtyDataHandlers: vi.fn<() => unknown[]>(() => []) +})) + +vi.mock('@/lib/agent-status', async (importOriginal) => ({ + ...(await importOriginal()), + detectAgentStatusFromTitle: vi.fn().mockReturnValue(null) +})) + +const mockApi = createStoreCascadesMockApi() +const closeTerminalSurface = vi.fn() +Object.assign(mockApi, { session: { closeTerminalSurface } }) + +const SSH_WORKTREE = 'remote-repo::/srv/app' +const SSH_PTY = 'ssh:target@@pty2:1:1' + +function storeWithSshTab(): ReturnType { + const store = createTestStore() + seedStore(store, { + repos: [{ ...TEST_REPO, id: 'remote-repo', path: '/srv/app', connectionId: 'ssh-1' }], + worktreesByRepo: { + 'remote-repo': [makeWorktree({ id: SSH_WORKTREE, repoId: 'remote-repo', path: '/srv/app' })] + }, + tabsByWorktree: { + [SSH_WORKTREE]: [makeTab({ id: 'ssh-tab', worktreeId: SSH_WORKTREE, ptyId: SSH_PTY })] + }, + ptyIdsByTabId: { 'ssh-tab': [SSH_PTY] } + }) + return store +} + +describe('closeTab close intent', () => { + beforeEach(() => { + vi.clearAllMocks() + closeTerminalSurface.mockResolvedValue(undefined) + mockApi.worktrees.updateMeta.mockResolvedValue({}) + }) + + it('commits the close in main even when the SSH shutdown throws', async () => { + mockApi.pty.kill.mockRejectedValue(new Error('relay shutdown failed')) + const store = storeWithSshTab() + + store.getState().closeTab('ssh-tab') + await Promise.resolve() + + expect(mockApi.pty.kill).toHaveBeenCalledWith(SSH_PTY) + expect(closeTerminalSurface).toHaveBeenCalledWith({ + worktreeId: SSH_WORKTREE, + tabId: 'ssh-tab' + }) + }) + + it.each([['user'], ['cleanup']] as const)('sends the intent for a %s close', (reason) => { + storeWithSshTab().getState().closeTab('ssh-tab', { reason }) + + expect(closeTerminalSurface).toHaveBeenCalledTimes(1) + }) + + // Why: exits still retire through main's own exit handling until main decides exits itself. + it('sends nothing for a pty-exit close', () => { + storeWithSshTab().getState().closeTab('ssh-tab', { reason: 'pty-exit' }) + + expect(closeTerminalSurface).not.toHaveBeenCalled() + }) + + it('sends nothing when a paired host owns the close', () => { + storeWithSshTab().getState().closeTab('ssh-tab', { remoteCloseOwnedByHost: true }) + + expect(closeTerminalSurface).not.toHaveBeenCalled() + }) +}) diff --git a/src/renderer/src/store/terminals/terminal-tab-close.ts b/src/renderer/src/store/terminals/terminal-tab-close.ts index b4ff87f4f105..ee5f5255838a 100644 --- a/src/renderer/src/store/terminals/terminal-tab-close.ts +++ b/src/renderer/src/store/terminals/terminal-tab-close.ts @@ -15,6 +15,7 @@ import { } from '../slices/terminal-tab-retirement' import type { TerminalSlice, TerminalStoreGet, TerminalStoreSet } from './terminal-state' import { startTerminalTabProviderRetirement } from './terminal-tab-close-providers' +import { commitTerminalSurfaceClose } from './terminal-surface-close-intent' import { omitUnverifiedPtyLossTabIds } from './terminal-unverified-pty-loss' import { removePaneKeysByTabPrefix } from '../slices/agent-status-pane-keyed-records' import { omitRecordKeys } from '../slices/worktrees/teardown/record-key-omission' @@ -248,6 +249,9 @@ export function createTerminalTabCloseActions( : {}) } }) + if (retiresSession && closingWorktreeId && opts?.remoteCloseOwnedByHost !== true) { + commitTerminalSurfaceClose({ worktreeId: closingWorktreeId, tabId }) + } // Why shared with the paired snapshot apply: every path that removes a tab owes it the same sweep, and a second copy of the list is how one path silently misses a new entry. sweepRetiredTerminalTabState(get(), tabId, closingWorktreeId) for (const tabs of Object.values(get().unifiedTabsByWorktree)) { diff --git a/src/renderer/src/web/preload-api/web-workspace-session-api.ts b/src/renderer/src/web/preload-api/web-workspace-session-api.ts index 2a8abc03b616..553b065c9923 100644 --- a/src/renderer/src/web/preload-api/web-workspace-session-api.ts +++ b/src/renderer/src/web/preload-api/web-workspace-session-api.ts @@ -81,6 +81,8 @@ export function createWebWorkspaceSessionApi(): Partial { }) ) }, + // Why a no-op: web closes reach the host through its session-tab and terminal close RPCs. + closeTerminalSurface: async () => {}, // localStorage writes synchronously, so there is no deferred web flush. flush: async () => {}, readTerminalScrollback: () => null, From 7012c3eaed3bf3de68ab0cd6087804698a0731ba Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 25 Sep 2026 14:27:24 -0700 Subject: [PATCH 02/15] fix(terminal): tell the desktop renderer to drop a split pane main closed A CLI or mobile close of one pane in a split commits the pane in main, but the desktop kept showing it until reload when no exit arrived to remove it. The close now sends a leaf-addressed notice: a mounted pane closes by leaf id, and a parked tab collapses its stored layout. Addressing by leaf makes the notice and the renderer's exit handling no-ops after each other, which replaces the numeric pane-id notice that could close the whole tab when the exit won. --- ...ld-headless-mobile-session-browser-tabs.ts | 8 +- ...runtime-stop-explicitly-closed-tab-ptys.ts | 7 +- ...rca-runtime-terminal-surface-close.test.ts | 4 +- ...rca-runtime-test-scenario-builders.spec.ts | 4 +- src/main/runtime/runtime-notifier-contract.ts | 3 +- src/main/window/runtime-window-lifecycle.ts | 2 +- ...ui-bridge-clipboard-and-window-controls.ts | 6 +- src/preload/api/ui-command-event-api.ts | 4 +- .../closed-terminal-leaf-notice.test.ts | 103 ++++++++++++++++++ .../closed-terminal-leaf-notice.ts | 16 +++ .../terminal-parked-pty-watcher.ts | 12 +- .../ipc-events-close-routing-test-harness.ts | 2 +- .../mobile-terminal-close-ipc-bridge.ts | 11 +- 13 files changed, 153 insertions(+), 29 deletions(-) create mode 100644 src/renderer/src/components/terminal-pane/closed-terminal-leaf-notice.test.ts create mode 100644 src/renderer/src/components/terminal-pane/closed-terminal-leaf-notice.ts diff --git a/src/main/runtime/orca-runtime-build-headless-mobile-session-browser-tabs.ts b/src/main/runtime/orca-runtime-build-headless-mobile-session-browser-tabs.ts index d942a1e065c5..9e44701331cb 100644 --- a/src/main/runtime/orca-runtime-build-headless-mobile-session-browser-tabs.ts +++ b/src/main/runtime/orca-runtime-build-headless-mobile-session-browser-tabs.ts @@ -123,7 +123,10 @@ export class OrcaRuntimeWithBuildHeadlessMobileSessionBrowserTabs extends OrcaRu }) } - /** Commits a split pane's close once its process was stopped; no session means nothing persisted. */ + /** + * Commits a split pane's close that main started once its process was stopped, then tells the + * desktop renderer to drop that leaf. No session means nothing persisted to remove. + */ protected closeTerminalLeaf(worktreeId: string, tabId: string, leafId: string): void { try { // Why force: the process is already stopped, so a pin must not fail the close after the fact. @@ -133,6 +136,9 @@ export class OrcaRuntimeWithBuildHeadlessMobileSessionBrowserTabs extends OrcaRu throw error } } + // Why: no exit may ever arrive to remove the pane. The notice is leaf-addressed, so it and the + // renderer's exit handling are each a no-op after the other. + this.notifier?.closeTerminal(tabId, leafId) } protected persistHeadlessTerminalTabOrder(worktreeId: string, tabOrder: readonly string[]): void { diff --git a/src/main/runtime/orca-runtime-stop-explicitly-closed-tab-ptys.ts b/src/main/runtime/orca-runtime-stop-explicitly-closed-tab-ptys.ts index ed926fc27fea..8565671363ce 100644 --- a/src/main/runtime/orca-runtime-stop-explicitly-closed-tab-ptys.ts +++ b/src/main/runtime/orca-runtime-stop-explicitly-closed-tab-ptys.ts @@ -182,8 +182,6 @@ export class OrcaRuntimeWithStopExplicitlyClosedTabPtys extends OrcaRuntimeWithF } this.assertGraphReady() const { leaf } = this.getLiveLeafForHandle(handle) - // Why: in a multi-pane tab the renderer's exit handler removes the killed pane from view; an - // extra IPC close would race it and close the whole tab. Membership is committed below. const siblingCount = this.countLeavesInTab(leaf.tabId) const ptyIdsToKill = siblingCount <= 1 @@ -199,9 +197,8 @@ export class OrcaRuntimeWithStopExplicitlyClosedTabPtys extends OrcaRuntimeWithF : false if (siblingCount > 1) { this.closeTerminalLeaf(leaf.worktreeId, leaf.tabId, leaf.leafId) - } - if (siblingCount > 1 ? !ptyKilled : !this.notifier?.closeTerminalTab) { - this.notifier?.closeTerminal(leaf.tabId, leaf.paneRuntimeId) + } else if (!this.notifier?.closeTerminalTab) { + this.notifier?.closeTerminal(leaf.tabId) } return this.describeTerminalClose(handle, leaf.tabId, leaf.ptyId ?? null, ptyKilled) } diff --git a/src/main/runtime/orca-runtime-terminal-surface-close.test.ts b/src/main/runtime/orca-runtime-terminal-surface-close.test.ts index 296b4bab8920..97d4f67c2472 100644 --- a/src/main/runtime/orca-runtime-terminal-surface-close.test.ts +++ b/src/main/runtime/orca-runtime-terminal-surface-close.test.ts @@ -145,8 +145,9 @@ describe('CLI close of one pane in a split tab', () => { root: { type: 'leaf', leafId: SIBLING_LEAF_ID }, ptyIdsByLeafId: { [SIBLING_LEAF_ID]: SIBLING_PTY_ID } }) + // No exit arrives to remove the pane, so the desktop renderer is told to drop that leaf. + expect(harness.closeTerminal).toHaveBeenCalledExactlyOnceWith(TAB_ID, LEAF_ID) expect(harness.closeTerminalTab).not.toHaveBeenCalled() - expect(harness.closeTerminal).not.toHaveBeenCalled() }) }) @@ -165,5 +166,6 @@ describe('mobile close of one pane in a split tab', () => { expect(harness.getSession().terminalLayoutsByTabId[TAB_ID]).toMatchObject({ root: { type: 'leaf', leafId: SIBLING_LEAF_ID } }) + expect(harness.closeTerminal).toHaveBeenCalledExactlyOnceWith(TAB_ID, LEAF_ID) }) }) diff --git a/src/main/runtime/orca-runtime-test-scenario-builders.spec.ts b/src/main/runtime/orca-runtime-test-scenario-builders.spec.ts index 1f87d901c817..5dab4ac35077 100644 --- a/src/main/runtime/orca-runtime-test-scenario-builders.spec.ts +++ b/src/main/runtime/orca-runtime-test-scenario-builders.spec.ts @@ -34,7 +34,7 @@ type MobileCreateTestNotifier = { revealTerminalSession: TestMock splitTerminal: TestMock renameTerminal: TestMock - closeTerminal: (tabId: string, paneRuntimeId?: number) => void + closeTerminal: (tabId: string, leafId?: string) => void closeSessionTab: TestMock sleepWorktree: TestMock terminalFitOverrideChanged: TestMock @@ -326,7 +326,7 @@ function makePendingAgentTabActivationRuntime(opts: { disabledTuiAgents?: string // Why: the five #7587 mobile-create tests share one notifier factory so interface changes live in one place. function createMobileCreateTestNotifier( - closeTerminal: (tabId: string, paneRuntimeId?: number) => void + closeTerminal: (tabId: string, leafId?: string) => void ): MobileCreateTestNotifier { return { focusTerminal: vi.fn(), diff --git a/src/main/runtime/runtime-notifier-contract.ts b/src/main/runtime/runtime-notifier-contract.ts index 9cdc365e1ba9..97adc3feb07c 100644 --- a/src/main/runtime/runtime-notifier-contract.ts +++ b/src/main/runtime/runtime-notifier-contract.ts @@ -117,7 +117,8 @@ export type RuntimeNotifier = { baseVersion: string, content: string ): Promise - closeTerminal(tabId: string, paneRuntimeId?: number): void + /** With leafId, drops that one split pane main already closed; without it, closes the tab. */ + closeTerminal(tabId: string, leafId?: string): void closeTerminalTab?( tabId: string, options?: { localPtyTeardownOwnedExternally?: boolean; force?: boolean } diff --git a/src/main/window/runtime-window-lifecycle.ts b/src/main/window/runtime-window-lifecycle.ts index 78c5f2ec4263..07eff2789238 100644 --- a/src/main/window/runtime-window-lifecycle.ts +++ b/src/main/window/runtime-window-lifecycle.ts @@ -198,7 +198,7 @@ export function registerRuntimeWindowLifecycle( baseVersion, content }) as Promise, - closeTerminal: (tabId, paneRuntimeId) => send('ui:closeTerminal', { tabId, paneRuntimeId }), + closeTerminal: (tabId, leafId) => send('ui:closeTerminal', { tabId, leafId }), closeTerminalTab: (tabId, options) => requestTerminalTabCloseFromRenderer(mainWindow, tabId, options), sleepWorktree: (worktreeId) => send('ui:sleepWorktree', { worktreeId }), diff --git a/src/preload/api/ui-bridge-clipboard-and-window-controls.ts b/src/preload/api/ui-bridge-clipboard-and-window-controls.ts index 1738cb46d2a5..dd45edb16ee4 100644 --- a/src/preload/api/ui-bridge-clipboard-and-window-controls.ts +++ b/src/preload/api/ui-bridge-clipboard-and-window-controls.ts @@ -49,12 +49,10 @@ export const uiClipboardAndWindowControlsApi = { respondMobileMarkdownRequest: (response: RuntimeMobileMarkdownResponse): void => { ipcRenderer.send('ui:mobileMarkdownResponse', response) }, - onCloseTerminal: ( - callback: (data: { tabId: string; paneRuntimeId?: number }) => void - ): (() => void) => { + onCloseTerminal: (callback: (data: { tabId: string; leafId?: string }) => void): (() => void) => { const listener = ( _event: Electron.IpcRendererEvent, - data: { tabId: string; paneRuntimeId?: number } + data: { tabId: string; leafId?: string } ) => callback(data) ipcRenderer.on('ui:closeTerminal', listener) return () => ipcRenderer.removeListener('ui:closeTerminal', listener) diff --git a/src/preload/api/ui-command-event-api.ts b/src/preload/api/ui-command-event-api.ts index d20ce87718b1..a0bef9e23553 100644 --- a/src/preload/api/ui-command-event-api.ts +++ b/src/preload/api/ui-command-event-api.ts @@ -236,9 +236,7 @@ export type UiCommandEventApi = { ) => () => void onMobileMarkdownRequest: (callback: (request: RuntimeMobileMarkdownRequest) => void) => () => void respondMobileMarkdownRequest: (response: RuntimeMobileMarkdownResponse) => void - onCloseTerminal: ( - callback: (data: { tabId: string; paneRuntimeId?: number }) => void - ) => () => void + onCloseTerminal: (callback: (data: { tabId: string; leafId?: string }) => void) => () => void onTerminalTabCloseRequest: (callback: (request: TerminalTabCloseRequest) => void) => () => void respondTerminalTabClose: (response: TerminalTabCloseResponse) => void onSleepWorktree: (callback: (data: { worktreeId: string }) => void) => () => void diff --git a/src/renderer/src/components/terminal-pane/closed-terminal-leaf-notice.test.ts b/src/renderer/src/components/terminal-pane/closed-terminal-leaf-notice.test.ts new file mode 100644 index 000000000000..cfb0ab967252 --- /dev/null +++ b/src/renderer/src/components/terminal-pane/closed-terminal-leaf-notice.test.ts @@ -0,0 +1,103 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { TerminalLayoutSnapshot } from '../../../../shared/terminal-tab-types' +import { CLOSE_TERMINAL_PANE_EVENT } from '@/constants/terminal' + +const TAB_ID = 'tab-1' +const LEAF_ID = '11111111-1111-4111-8111-111111111111' +const SIBLING_LEAF_ID = '22222222-2222-4222-8222-222222222222' + +const splitLayout: TerminalLayoutSnapshot = { + root: { + type: 'split', + direction: 'vertical', + first: { type: 'leaf', leafId: LEAF_ID }, + second: { type: 'leaf', leafId: SIBLING_LEAF_ID } + }, + activeLeafId: LEAF_ID, + expandedLeafId: null, + ptyIdsByLeafId: { [LEAF_ID]: 'pty-closed', [SIBLING_LEAF_ID]: 'pty-sibling' } +} + +const layouts: Record = {} +const state = { + tabsByWorktree: {}, + terminalLayoutsByTabId: layouts, + runtimePaneTitlesByTabId: {}, + clearTabLaunchAgent: vi.fn(), + updateTabTitle: vi.fn(), + setTabLayout: vi.fn((tabId: string, layout: TerminalLayoutSnapshot) => { + state.terminalLayoutsByTabId[tabId] = layout + }) +} + +vi.mock('@/store', () => ({ useAppStore: { getState: () => state } })) + +import { applyClosedTerminalLeafNotice } from './closed-terminal-leaf-notice' +import { applyTerminalPaneCloseRequest } from './terminal-pane-lifecycle-close' +import { parkedWatchersByTabId } from './terminal-parked-watcher-registry' + +function leafIds(layout: TerminalLayoutSnapshot | undefined): string[] { + return Object.keys(layout?.ptyIdsByLeafId ?? {}) +} + +beforeEach(() => { + state.terminalLayoutsByTabId = { [TAB_ID]: splitLayout } + state.setTabLayout.mockClear() + vi.stubGlobal('window', new EventTarget()) +}) + +afterEach(() => { + parkedWatchersByTabId.clear() + vi.unstubAllGlobals() +}) + +describe('a split pane main already closed', () => { + it('reaches a mounted pane as a leaf-addressed close', () => { + const details: unknown[] = [] + window.addEventListener(CLOSE_TERMINAL_PANE_EVENT, (event) => + details.push(event instanceof CustomEvent ? event.detail : null) + ) + + applyClosedTerminalLeafNotice(TAB_ID, LEAF_ID) + + expect(details).toEqual([{ tabId: TAB_ID, leafId: LEAF_ID }]) + }) + + it('is ignored by a mounted pane whose exit already removed that leaf', () => { + const manager = { + closePane: vi.fn(), + detachPaneForExternalMove: vi.fn(), + retirePanePreservingPty: vi.fn(), + getNumericIdForLeaf: () => null, + getPanes: () => [{ id: 2 }] + } + const closeTab = vi.fn() + + const result = applyTerminalPaneCloseRequest({ + detail: { tabId: TAB_ID, leafId: LEAF_ID }, + manager, + closeTab, + closeTabPreservingPty: vi.fn() + }) + + // Why: a numeric pane id would have reached the last-pane branch and closed the whole tab. + expect(result).toBe('ignored') + expect(closeTab).not.toHaveBeenCalled() + expect(manager.closePane).not.toHaveBeenCalled() + }) + + it('collapses a parked tab stored layout once, whichever of notice or exit lands first', () => { + parkedWatchersByTabId.set(TAB_ID, { + worktreeId: 'repo::/worktree', + tabPtyId: 'pty-closed', + disposersByPtyId: new Map([['pty-closed', vi.fn()]]), + paneIdByPtyId: new Map() + }) + + applyClosedTerminalLeafNotice(TAB_ID, LEAF_ID) + applyClosedTerminalLeafNotice(TAB_ID, LEAF_ID) + + expect(leafIds(state.terminalLayoutsByTabId[TAB_ID])).toEqual([SIBLING_LEAF_ID]) + expect(state.setTabLayout).toHaveBeenCalledTimes(1) + }) +}) diff --git a/src/renderer/src/components/terminal-pane/closed-terminal-leaf-notice.ts b/src/renderer/src/components/terminal-pane/closed-terminal-leaf-notice.ts new file mode 100644 index 000000000000..2b465db28781 --- /dev/null +++ b/src/renderer/src/components/terminal-pane/closed-terminal-leaf-notice.ts @@ -0,0 +1,16 @@ +import { CLOSE_TERMINAL_PANE_EVENT, type CloseTerminalPaneDetail } from '@/constants/terminal' +import { collapseParkedTerminalLeaf } from './terminal-parked-pty-watcher' +import { isTerminalTabParked } from './terminal-parked-watcher-registry' + +/** + * Drops a split pane main already closed. Addressed by leaf, so it is a no-op once the pane's own + * exit handling removed it, and the exit is a no-op after it: whichever lands first wins. + */ +export function applyClosedTerminalLeafNotice(tabId: string, leafId: string): void { + if (isTerminalTabParked(tabId)) { + collapseParkedTerminalLeaf(tabId, leafId) + return + } + const detail: CloseTerminalPaneDetail = { tabId, leafId } + window.dispatchEvent(new CustomEvent(CLOSE_TERMINAL_PANE_EVENT, { detail })) +} diff --git a/src/renderer/src/components/terminal-pane/terminal-parked-pty-watcher.ts b/src/renderer/src/components/terminal-pane/terminal-parked-pty-watcher.ts index 158d03e8bb02..f70599f148c6 100644 --- a/src/renderer/src/components/terminal-pane/terminal-parked-pty-watcher.ts +++ b/src/renderer/src/components/terminal-pane/terminal-parked-pty-watcher.ts @@ -181,9 +181,15 @@ export function collapseParkedExitedLeaf(tabId: string, ptyId: string): void { const leafId = capturedPanesByTabId.get(tabId)?.panes.find((pane) => pane.ptyId === ptyId)?.leafId ?? Object.entries(layout?.ptyIdsByLeafId ?? {}).find(([, boundPtyId]) => boundPtyId === ptyId)?.[0] - if (!leafId) { - return + if (leafId) { + collapseParkedTerminalLeaf(tabId, leafId, ptyId) } +} + +/** Removes one leaf from a parked tab's stored layout; a no-op once the leaf is gone. */ +export function collapseParkedTerminalLeaf(tabId: string, leafId: string, ptyId?: string): void { + const state = useAppStore.getState() + const layout = state.terminalLayoutsByTabId[tabId] const detached = detachTerminalLayoutLeaf(layout, leafId) if (!detached) { return @@ -191,7 +197,7 @@ export function collapseParkedExitedLeaf(tabId: string, ptyId: string): void { const terminalTab = Object.values(state.tabsByWorktree) .flat() .find((candidate) => candidate.id === tabId) - if (shouldClearLaunchAgentForClosedPane(terminalTab, ptyId)) { + if (shouldClearLaunchAgentForClosedPane(terminalTab, ptyId ?? layout?.ptyIdsByLeafId?.[leafId])) { state.clearTabLaunchAgent(tabId) } state.setTabLayout(tabId, detached.sourceLayout) diff --git a/src/renderer/src/hooks/ipc-events-close-routing-test-harness.ts b/src/renderer/src/hooks/ipc-events-close-routing-test-harness.ts index 3883f7ac8af6..371b145fa2e3 100644 --- a/src/renderer/src/hooks/ipc-events-close-routing-test-harness.ts +++ b/src/renderer/src/hooks/ipc-events-close-routing-test-harness.ts @@ -12,7 +12,7 @@ export type RequestTabCloseListener = (data: { export type CloseActiveTabListener = (payload?: { sourceId: string }) => void export type CloseFloatingItemListener = (payload: { sourceId: string }) => void export type SelectFloatingIndexListener = (payload: { index: number }) => void -export type CloseTerminalListener = (data: { tabId: string; paneRuntimeId?: number | null }) => void +export type CloseTerminalListener = (data: { tabId: string; leafId?: string | null }) => void export type CloseSessionTabListener = (data: { tabId: string; worktreeId: string }) => void export type SessionTabCloseRequestListener = (data: { requestId: string diff --git a/src/renderer/src/hooks/ipc-events/mobile-terminal-close-ipc-bridge.ts b/src/renderer/src/hooks/ipc-events/mobile-terminal-close-ipc-bridge.ts index aaf1686e702f..cd6e668ae9ec 100644 --- a/src/renderer/src/hooks/ipc-events/mobile-terminal-close-ipc-bridge.ts +++ b/src/renderer/src/hooks/ipc-events/mobile-terminal-close-ipc-bridge.ts @@ -1,5 +1,4 @@ -import { CLOSE_TERMINAL_PANE_EVENT } from '@/constants/terminal' -import type { CloseTerminalPaneDetail } from '@/constants/terminal' +import { applyClosedTerminalLeafNotice } from '@/components/terminal-pane/closed-terminal-leaf-notice' import { closeTerminalTab } from '@/components/terminal/terminal-tab-actions' import { detectLanguage } from '@/lib/language-detect' import { runSleepWorktree } from '@/components/sidebar/sleep-worktree-flow' @@ -53,11 +52,9 @@ export function registerMobileAndTerminalCloseIpcBridge( ) unsubs.push( - window.api.ui.onCloseTerminal(({ tabId, paneRuntimeId }) => { - 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 } - window.dispatchEvent(new CustomEvent(CLOSE_TERMINAL_PANE_EVENT, { detail })) + window.api.ui.onCloseTerminal(({ tabId, leafId }) => { + if (leafId != null) { + applyClosedTerminalLeafNotice(tabId, leafId) } else { // Why: the CLI/RPC caller is answered immediately, so it cannot wait on a modal. closeTerminalTab(tabId, { skipRunningProcessConfirm: true }) From fc5cac5c32dc4e383a6670536a70d34136f1cef1 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 25 Sep 2026 15:04:10 -0700 Subject: [PATCH 03/15] fix(terminal): a pane close never widens into a whole-tab close A leaf-addressed close fell through to the whole-tab close whenever main's layout no longer held that leaf as one of several. Main's exit handling retires an exited split pane from the saved layout, so closing that pane afterwards (the exited-pane overlay's Close, or a CLI close whose stop delivers the exit first) removed the whole tab, live sibling included, and the next renderer save could not restore it. A pane close is now a no-op unless its leaf is in a multi-pane layout. Also updates two mobile split-close assertions to expect the leaf-addressed notice, and adds a test that a relayed mobile close of a renderer-listed tab still reaches the renderer's pin guard. --- ...rca-runtime-terminal-surface-close.test.ts | 78 +++++++++++++++++++ .../mobile-session-tabs-part-10.spec.ts | 8 +- .../mobile-session-tabs.spec.ts | 3 +- src/main/runtime/terminal-surface-close.ts | 11 ++- 4 files changed, 94 insertions(+), 6 deletions(-) diff --git a/src/main/runtime/orca-runtime-terminal-surface-close.test.ts b/src/main/runtime/orca-runtime-terminal-surface-close.test.ts index 97d4f67c2472..d8f26d0a3e53 100644 --- a/src/main/runtime/orca-runtime-terminal-surface-close.test.ts +++ b/src/main/runtime/orca-runtime-terminal-surface-close.test.ts @@ -18,6 +18,7 @@ import { createHarness, makeSession } from './__fixtures__/orca-runtime-terminal-close-continuity-fixtures' +import { retireTerminalSurfaceFromPersistence } from './mobile-session-terminal-persistence-retirement' import { advanceTerminalTopologyRevision } from './workspace-session-terminal-membership-authority' const splitLayout = { @@ -36,6 +37,27 @@ function splitSession(): WorkspaceSessionState { return { ...makeSession(), terminalLayoutsByTabId: { [TAB_ID]: splitLayout } } } +function splitSessionAfterExitRetired(): WorkspaceSessionState { + return retireTerminalSurfaceFromPersistence(splitSession(), { + worktreeId: WORKTREE_ID, + parentTabId: TAB_ID, + leafId: LEAF_ID, + ptyId: PTY_ID + }) +} + +function withPinnedTab(session: WorkspaceSessionState): WorkspaceSessionState { + return { + ...session, + tabsByWorktree: { + [WORKTREE_ID]: (session.tabsByWorktree[WORKTREE_ID] ?? []).map((tab) => ({ + ...tab, + isPinned: true + })) + } + } +} + const directories: string[] = [] afterEach(() => { for (const directory of directories.splice(0)) { @@ -122,6 +144,25 @@ describe('renderer close intents', () => { undefined ) }) + + // e.g. the exited-pane overlay's Close, after main's exit handling already retired that leaf. + it.each([ + ['its exit already retired the pane', () => splitSessionAfterExitRetired()], + ['the tab is pinned', () => withPinnedTab(splitSessionAfterExitRetired())], + ['the tab has no saved layout', () => ({ ...makeSession(), terminalLayoutsByTabId: {} })] + ])('never widens a pane close into a tab close when %s', async (_case, session) => { + const { runtime, reload } = createPersistedRuntime(session()) + + runtime.closeTerminalSurfaceFromRenderer({ + worktreeId: WORKTREE_ID, + tabId: TAB_ID, + leafId: LEAF_ID + }) + + expect((await reload()).tabsByWorktree[WORKTREE_ID]).toEqual([ + expect.objectContaining({ id: TAB_ID }) + ]) + }) }) describe('CLI close of one pane in a split tab', () => { @@ -149,6 +190,25 @@ describe('CLI close of one pane in a split tab', () => { expect(harness.closeTerminal).toHaveBeenCalledExactlyOnceWith(TAB_ID, LEAF_ID) expect(harness.closeTerminalTab).not.toHaveBeenCalled() }) + + it('keeps the sibling when the stop delivers the exit before the pane commit', async () => { + const harness = createHarness() + harness.syncSplitFixtureGraph() + harness.setStopAndWaitAction((stoppingPtyId) => harness.runtime.onPtyExit(stoppingPtyId, 0)) + harness.setVerifiedStopResult(true) + const terminal = (await harness.runtime.listTerminals(`id:${WORKTREE_ID}`)).terminals.find( + (candidate) => candidate.ptyId === PTY_ID + )! + + await harness.runtime.closeTerminal(terminal.handle) + + const session = harness.getSession() + expect(session.tabsByWorktree[WORKTREE_ID]).toEqual([expect.objectContaining({ id: TAB_ID })]) + expect(session.terminalLayoutsByTabId[TAB_ID]?.root).toEqual({ + type: 'leaf', + leafId: SIBLING_LEAF_ID + }) + }) }) describe('mobile close of one pane in a split tab', () => { @@ -169,3 +229,21 @@ describe('mobile close of one pane in a split tab', () => { expect(harness.closeTerminal).toHaveBeenCalledExactlyOnceWith(TAB_ID, LEAF_ID) }) }) + +describe('mobile close of a tab the desktop renderer lists', () => { + // Pins are renderer presentation that main's session can lag, so only the renderer can refuse. + it('still asks the renderer, whose pin guard can refuse it', async () => { + const harness = createHarness({ publishMobileSurface: true, registerPtyBacked: true }) + harness.rejectTerminalTabClose(new Error('terminal_tab_pinned')) + + await expect( + harness.runtime.closeMobileSessionTab(`id:${WORKTREE_ID}`, TAB_ID, { reason: 'user' }) + ).rejects.toThrow('terminal_tab_pinned') + + expect(harness.closeTerminalTab).toHaveBeenCalledWith(TAB_ID) + expect(harness.kill).not.toHaveBeenCalled() + expect(harness.getSession().tabsByWorktree[WORKTREE_ID]).toEqual([ + expect.objectContaining({ id: TAB_ID }) + ]) + }) +}) diff --git a/src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-10.spec.ts b/src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-10.spec.ts index b37fa4963d4d..be367668212f 100644 --- a/src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-10.spec.ts +++ b/src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-10.spec.ts @@ -524,8 +524,12 @@ describe('OrcaRuntimeService', () => { // Exact split leaf: kill only that leaf's PTY, keep the sibling, don't tear down the parent. expect(kill).toHaveBeenCalledWith('serve-right') expect(kill).not.toHaveBeenCalledWith('serve-left') - expect(closeTerminal).not.toHaveBeenCalled() + // Only the leaf-addressed notice for the closed pane; never a whole-tab close. + expect(closeTerminal).toHaveBeenCalledExactlyOnceWith('host-tab', HEADLESS_SECOND_LEAF_ID) expect(getSession().tabsByWorktree[TEST_WORKTREE_ID]).toHaveLength(1) - expect(getSession().terminalLayoutsByTabId['host-tab']).toBeDefined() + expect(getSession().terminalLayoutsByTabId['host-tab']?.root).toEqual({ + type: 'leaf', + leafId: HEADLESS_LEAF_ID + }) }) }) diff --git a/src/main/runtime/orca-runtime-tests/mobile-session-tabs.spec.ts b/src/main/runtime/orca-runtime-tests/mobile-session-tabs.spec.ts index c3000e90bd29..462b83b10e5c 100644 --- a/src/main/runtime/orca-runtime-tests/mobile-session-tabs.spec.ts +++ b/src/main/runtime/orca-runtime-tests/mobile-session-tabs.spec.ts @@ -313,7 +313,8 @@ describe('OrcaRuntimeService', () => { await runtime.closeMobileSessionTab(`id:${TEST_WORKTREE_ID}`, `tab-1::${rightLeafId}`) expect(kill).toHaveBeenCalledWith('pty-right') - expect(closeTerminal).not.toHaveBeenCalled() + // Only the leaf-addressed notice for the closed pane; never a whole-tab close. + expect(closeTerminal).toHaveBeenCalledExactlyOnceWith('tab-1', rightLeafId) }) it('closes the whole mobile terminal tab when addressed by parent tab id', async () => { diff --git a/src/main/runtime/terminal-surface-close.ts b/src/main/runtime/terminal-surface-close.ts index 55841e2fe9ca..5f6b84343ed1 100644 --- a/src/main/runtime/terminal-surface-close.ts +++ b/src/main/runtime/terminal-surface-close.ts @@ -11,7 +11,7 @@ import { advanceTerminalTopologyRevision } from './workspace-session-terminal-me /** * The membership half of every explicit terminal close: removes a tab, or one leaf of a split * tab, and advances the repo's topology revision so a stale renderer save cannot restore it. - * Closing a tab's last leaf closes the tab. + * A leaf close never removes its tab: callers close the last pane with a tab close. */ export function closeTerminalSurfaceInWorkspaceSession( session: WorkspaceSessionState, @@ -20,8 +20,13 @@ export function closeTerminalSurfaceInWorkspaceSession( options: { leafId?: string; force?: boolean } = {} ): WorkspaceSessionTerminalTabCloseResult { const layout = session.terminalLayoutsByTabId[tabId] - if (options.leafId && layout && countTerminalLayoutLeaves(layout.root) > 1) { - if (!layoutContainsLeafId(layout.root, options.leafId)) { + if (options.leafId) { + // Why: the exit may already have retired this leaf, leaving only live siblings to lose. + if ( + !layout || + countTerminalLayoutLeaves(layout.root) <= 1 || + !layoutContainsLeafId(layout.root, options.leafId) + ) { return { session, ptyIdsToKill: [], closed: false, pinned: false } } // The leaf's own binding is passed so the retirement's stale-binding fence always admits it. From 95abe041592320226f7adf68aabcd36fc664d820 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 25 Sep 2026 15:17:29 -0700 Subject: [PATCH 04/15] test(terminal): cover the PTY-handle branch of a CLI split-pane close The existing CLI split test resolves its handle through the renderer graph, so the branch that closes a runtime-owned pane by its PTY handle had no test failing without its commit. --- ...rca-runtime-terminal-surface-close.test.ts | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/src/main/runtime/orca-runtime-terminal-surface-close.test.ts b/src/main/runtime/orca-runtime-terminal-surface-close.test.ts index d8f26d0a3e53..d162e1ef170f 100644 --- a/src/main/runtime/orca-runtime-terminal-surface-close.test.ts +++ b/src/main/runtime/orca-runtime-terminal-surface-close.test.ts @@ -191,6 +191,29 @@ describe('CLI close of one pane in a split tab', () => { expect(harness.closeTerminalTab).not.toHaveBeenCalled() }) + it('commits the pane removal when the handle names a live PTY', async () => { + const harness = createHarness({ publishMobileSurface: true, registerPtyBacked: true }) + harness.syncSplitFixtureGraph() + // Graph without the leaf: the handle resolves through the PTY, as for a runtime-owned pane. + harness.syncFixtureTabWithoutLeaf() + harness.setVerifiedStopResult(true) + const terminal = (await harness.runtime.listTerminals(`id:${WORKTREE_ID}`)).terminals.find( + (candidate) => candidate.ptyId === PTY_ID + )! + + await expect(harness.runtime.closeTerminal(terminal.handle)).resolves.toMatchObject({ + tabId: TAB_ID, + ptyKilled: true + }) + + expect(harness.getSession().terminalLayoutsByTabId[TAB_ID]?.root).toEqual({ + type: 'leaf', + leafId: SIBLING_LEAF_ID + }) + expect(harness.closeTerminal).toHaveBeenCalledExactlyOnceWith(TAB_ID, LEAF_ID) + expect(harness.closeTerminalTab).not.toHaveBeenCalled() + }) + it('keeps the sibling when the stop delivers the exit before the pane commit', async () => { const harness = createHarness() harness.syncSplitFixtureGraph() From bc8bbd7abf2aed9c96955c9f21772005c3576e94 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 25 Sep 2026 16:14:42 -0700 Subject: [PATCH 05/15] fix(terminal): a CLI pane close with an unconfirmed stop closes only that pane `orca terminal close ` on one pane of a split used to close the whole tab, live sibling included, whenever that pane's stop could not be confirmed (for example an unreachable SSH host). An unconfirmed stop is unverifiable, not a reason to drop siblings: the close now commits only that leaf, tells the renderer to drop that leaf, and leaves the owed kill to the controller's existing SSH pending-kill path. On a host where no renderer lists the tab, main now also removes the closed pane from the paired-client snapshot (with its retirement proof), since no exit may arrive to do it. --- ...ld-headless-mobile-session-browser-tabs.ts | 32 +++++++++ ...runtime-stop-explicitly-closed-tab-ptys.ts | 36 +++++----- ...rca-runtime-terminal-surface-close.test.ts | 72 ++++++++++++++++++- 3 files changed, 121 insertions(+), 19 deletions(-) diff --git a/src/main/runtime/orca-runtime-build-headless-mobile-session-browser-tabs.ts b/src/main/runtime/orca-runtime-build-headless-mobile-session-browser-tabs.ts index 9e44701331cb..5803d42413d7 100644 --- a/src/main/runtime/orca-runtime-build-headless-mobile-session-browser-tabs.ts +++ b/src/main/runtime/orca-runtime-build-headless-mobile-session-browser-tabs.ts @@ -8,6 +8,7 @@ import type { import { getRuntimeBrowserPageRegistry } from './runtime-browser-page-registry' import type { Tab } from '../../shared/tab-types' import { closeTerminalSurfaceInWorkspaceSession } from './terminal-surface-close' +import { retireTerminalSurfacesFromSnapshot } from './mobile-session-terminal-retirement' import type { PtyControllerInventory } from './runtime-pty-controller-contract' import { FLOATING_TERMINAL_WORKTREE_ID } from '../../shared/constants' @@ -138,9 +139,40 @@ export class OrcaRuntimeWithBuildHeadlessMobileSessionBrowserTabs extends OrcaRu } // Why: no exit may ever arrive to remove the pane. The notice is leaf-addressed, so it and the // renderer's exit handling are each a no-op after the other. + this.retireClosedTerminalLeafFromMobileSnapshot(worktreeId, tabId, leafId) this.notifier?.closeTerminal(tabId, leafId) } + private retireClosedTerminalLeafFromMobileSnapshot( + worktreeId: string, + tabId: string, + leafId: string + ): void { + const snapshot = this.mobileSessionTabsByWorktree.get(worktreeId) + const tab = snapshot?.tabs.find( + (candidate) => + candidate.type === 'terminal' && + candidate.parentTabId === tabId && + candidate.leafId === leafId + ) + // Why: a renderer that lists the tab republishes its own snapshot once it drops the pane. + if (!snapshot || !tab || this.tabs.has(tabId)) { + return + } + const proof = this.getMobileSessionTerminalRetirementProof(worktreeId, tab) + const retired = retireTerminalSurfacesFromSnapshot({ + snapshot, + ptyId: tab.ptyId ?? tab.parentLayout?.ptyIdsByLeafId?.[leafId] ?? '', + exactSurfaces: [{ parentTabId: tabId, leafId }], + exactOnly: true, + ...(proof ? { retirementProofs: [proof] } : {}) + }) + if (retired) { + this.storeMobileSessionSnapshot(worktreeId, retired.snapshot) + this.notifyMobileSessionTabsChanged(worktreeId) + } + } + protected persistHeadlessTerminalTabOrder(worktreeId: string, tabOrder: readonly string[]): void { const session = this.getWorkspaceSessionForWorktree(worktreeId) if (!session || !this.store?.setWorkspaceSession) { diff --git a/src/main/runtime/orca-runtime-stop-explicitly-closed-tab-ptys.ts b/src/main/runtime/orca-runtime-stop-explicitly-closed-tab-ptys.ts index 8565671363ce..9bb138d615be 100644 --- a/src/main/runtime/orca-runtime-stop-explicitly-closed-tab-ptys.ts +++ b/src/main/runtime/orca-runtime-stop-explicitly-closed-tab-ptys.ts @@ -156,27 +156,27 @@ export class OrcaRuntimeWithStopExplicitlyClosedTabPtys extends OrcaRuntimeWithF return this.describeTerminalClose(handle, tabId, pty.pty.ptyId, ptyKilled) } const ptyKilled = await this.stopExplicitlyClosedTabPtys([pty.pty.ptyId], pty.pty.ptyId) - const leafId = surface?.tab.leafId ?? parsePaneKey(pty.pty.paneKey ?? '')?.leafId - if (ptyKilled && siblingCount > 1 && leafId) { - // Why: the pane's removal is this close's own commit, not a side effect of its exit. - this.closeTerminalLeaf(pty.pty.worktreeId, tabId, leafId) - } - if (!ptyKilled || siblingCount <= 1) { - if (surface) { - // Why: paired viewers keep ended streams mounted until the HUB publishes removal, so explicit close uses the durable host-tab transaction instead of viewer-local exit handling. - try { - await this.closeMobileSessionTab(`id:${pty.pty.worktreeId}`, tabId, { - localPtyTeardownOwnedExternally: true - }) - } catch (error) { - if (!(error instanceof Error) || error.message !== 'workspace_session_unavailable') { - throw error - } - this.notifier?.closeTerminal(tabId) + if (siblingCount > 1) { + const leafId = surface?.tab.leafId ?? parsePaneKey(pty.pty.paneKey ?? '')?.leafId + // Why: the pane's removal is this close's own commit, not a side effect of its exit. An + // unconfirmed stop is unverifiable, never a reason to close the live siblings with it. + if (leafId) { + this.closeTerminalLeaf(pty.pty.worktreeId, tabId, leafId) + } + } else if (surface) { + // Why: paired viewers keep ended streams mounted until the HUB publishes removal, so explicit close uses the durable host-tab transaction instead of viewer-local exit handling. + try { + await this.closeMobileSessionTab(`id:${pty.pty.worktreeId}`, tabId, { + localPtyTeardownOwnedExternally: true + }) + } catch (error) { + if (!(error instanceof Error) || error.message !== 'workspace_session_unavailable') { + throw error } - } else { this.notifier?.closeTerminal(tabId) } + } else { + this.notifier?.closeTerminal(tabId) } return this.describeTerminalClose(handle, tabId, pty.pty.ptyId, ptyKilled) } diff --git a/src/main/runtime/orca-runtime-terminal-surface-close.test.ts b/src/main/runtime/orca-runtime-terminal-surface-close.test.ts index d162e1ef170f..c107ff542300 100644 --- a/src/main/runtime/orca-runtime-terminal-surface-close.test.ts +++ b/src/main/runtime/orca-runtime-terminal-surface-close.test.ts @@ -18,7 +18,10 @@ import { createHarness, makeSession } from './__fixtures__/orca-runtime-terminal-close-continuity-fixtures' -import { retireTerminalSurfaceFromPersistence } from './mobile-session-terminal-persistence-retirement' +import { + retireTerminalSurfaceFromPersistence, + sanitizeWorkspaceSessionTerminalRetirements +} from './mobile-session-terminal-persistence-retirement' import { advanceTerminalTopologyRevision } from './workspace-session-terminal-membership-authority' const splitLayout = { @@ -214,6 +217,73 @@ describe('CLI close of one pane in a split tab', () => { expect(harness.closeTerminalTab).not.toHaveBeenCalled() }) + it.each([ + ['reports no exit', false], + ['throws, as an unreachable SSH host does', new Error('ssh_host_unreachable')] + ] as const)( + 'closes only that pane, never the live sibling, when its stop %s', + async (_case, stopResult) => { + const harness = createHarness({ publishMobileSurface: true, registerPtyBacked: true }) + harness.syncSplitFixtureGraph() + harness.syncFixtureTabWithoutLeaf() + harness.setVerifiedStopResult(stopResult) + // A renderer that honours a whole-tab close, so a widened close shows as the lost sibling. + harness.setCloseTerminalTabAction(() => harness.retirePersistedTab()) + const terminal = (await harness.runtime.listTerminals(`id:${WORKTREE_ID}`)).terminals.find( + (candidate) => candidate.ptyId === PTY_ID + )! + + const receipt = await harness.runtime.closeTerminal(terminal.handle) + + // A stale renderer save that still lists the pane can neither restore it nor drop the sibling. + const saved = sanitizeWorkspaceSessionTerminalRetirements( + { ...harness.getSession(), terminalLayoutsByTabId: { [TAB_ID]: splitLayout } }, + harness.getSession() + ) + expect(saved.tabsByWorktree[WORKTREE_ID]).toEqual([expect.objectContaining({ id: TAB_ID })]) + expect(saved.terminalLayoutsByTabId[TAB_ID]?.root).toEqual({ + type: 'leaf', + leafId: SIBLING_LEAF_ID + }) + expect(harness.closeTerminal).toHaveBeenCalledExactlyOnceWith(TAB_ID, LEAF_ID) + expect(harness.closeTerminalTab).not.toHaveBeenCalled() + // The owed stop still goes out through the controller's kill, which records SSH pending kills. + expect(harness.kill).toHaveBeenCalledWith(PTY_ID) + expect(harness.kill).not.toHaveBeenCalledWith(SIBLING_PTY_ID) + expect(receipt).toMatchObject({ + tabId: TAB_ID, + ptyKilled: false, + ptyStopVerdict: 'unverifiable' + }) + } + ) + + it('drops only that pane from paired clients on a host with no renderer listing the tab', async () => { + const harness = createHarness({ publishMobileSurface: true, registerPtyBacked: true }) + harness.syncSplitFixtureGraph() + harness.syncFixtureTabWithoutLeaf() + const terminal = (await harness.runtime.listTerminals(`id:${WORKTREE_ID}`)).terminals.find( + (candidate) => candidate.ptyId === PTY_ID + )! + harness.syncEmptyGraph() + // No exit arrives to retire the pane from the published snapshot. + harness.setVerifiedStopResult(new Error('ssh_host_unreachable')) + + await harness.runtime.closeTerminal(terminal.handle) + + const snapshot = await harness.runtime.listMobileSessionTabs(`id:${WORKTREE_ID}`) + expect(snapshot.tabs).toEqual([ + expect.objectContaining({ parentTabId: TAB_ID, leafId: SIBLING_LEAF_ID }) + ]) + expect(snapshot.retiredTerminalSurfaces).toEqual([ + expect.objectContaining({ parentTabId: TAB_ID, leafId: LEAF_ID, ptyId: PTY_ID }) + ]) + expect(harness.getSession().terminalLayoutsByTabId[TAB_ID]?.root).toEqual({ + type: 'leaf', + leafId: SIBLING_LEAF_ID + }) + }) + it('keeps the sibling when the stop delivers the exit before the pane commit', async () => { const harness = createHarness() harness.syncSplitFixtureGraph() From f860b7d920b31246591c8a75229407db2fb107fa Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 25 Sep 2026 19:27:56 -0700 Subject: [PATCH 06/15] refactor(terminal): one resolver decides whether a pane close becomes a tab close Every explicit close now states its target as `{kind:'tab'}` or `{kind:'pane', leafId}`; no optional leaf id silently means the whole tab. Main resolves a close it started in exactly one place, reading the copy of the tab's panes its layout owner holds (the renderer-published layout for tabs the desktop renderer lists, main's session layout otherwise). Only `last-pane` escalates, through the existing tab path so the renderer's pin guard still runs; an unknown pane never widens. - The CLI and phone paths drop their per-site sibling counts for the resolver. - The notifier splits into a tab-only close and a leaf-addressed pane close. - The headless tab closer takes a parent tab id, so a pane row cannot reach it. - A phone close of one pane on a host with no desktop window now stops and closes only that pane. - A phone close of one pane with no live process record closes that pane, not its tab. --- src/main/ipc/session.ts | 12 +- ...time-terminal-close-continuity-fixtures.ts | 19 +- ...terminal-close-continuity-state-fixture.ts | 8 + ...less-close-keeps-publication-epoch.test.ts | 4 +- ...ld-headless-mobile-session-browser-tabs.ts | 84 ++++-- ...time-close-headless-mobile-terminal-tab.ts | 18 +- .../orca-runtime-close-mobile-session-tab.ts | 68 ++--- ...runtime-stop-explicitly-closed-tab-ptys.ts | 49 ++-- ...runtime-terminal-close-no-widening.test.ts | 263 ++++++++++++++++++ ...rca-runtime-terminal-surface-close.test.ts | 18 +- .../mobile-session-tabs-part-10.spec.ts | 7 +- .../mobile-session-tabs.spec.ts | 5 +- .../orca-runtime-wait-for-leaf-pty-id.ts | 10 - src/main/runtime/runtime-notifier-contract.ts | 6 +- src/main/runtime/terminal-surface-close.ts | 143 ++++++++-- src/main/window/runtime-window-lifecycle.ts | 3 +- ...ui-bridge-clipboard-and-window-controls.ts | 9 +- src/preload/api/ui-command-event-api.ts | 3 +- src/preload/api/workspace-session-api.ts | 6 +- .../terminal-pane/pending-split-close.test.ts | 3 +- .../use-terminal-pane-close-actions.ts | 2 +- .../ipc-events-close-routing-test-harness.ts | 3 +- .../mobile-terminal-close-ipc-bridge.ts | 8 +- ...cEvents-close-routing-session-tabs.test.ts | 2 +- .../terminal-surface-close-intent.ts | 19 +- .../terminal-tab-close-intent.test.ts | 2 +- .../src/store/terminals/terminal-tab-close.ts | 2 +- src/shared/terminal-surface-close-target.ts | 28 ++ 28 files changed, 614 insertions(+), 190 deletions(-) create mode 100644 src/main/runtime/orca-runtime-terminal-close-no-widening.test.ts create mode 100644 src/shared/terminal-surface-close-target.ts diff --git a/src/main/ipc/session.ts b/src/main/ipc/session.ts index 4309ec388af4..eed2f65010ce 100644 --- a/src/main/ipc/session.ts +++ b/src/main/ipc/session.ts @@ -1,6 +1,7 @@ import { ipcMain } from 'electron' import type { Store } from '../persistence' import type { OrcaRuntimeService } from '../runtime/orca-runtime' +import { parseTerminalSurfaceCloseTarget } from '../../shared/terminal-surface-close-target' import type { WorkspaceSessionPatch, WorkspaceSessionState @@ -32,15 +33,12 @@ export function registerSessionHandlers(store: Store, runtime: OrcaRuntimeServic // Why: a renderer save cannot shrink membership main owns, so each close commits it explicitly. ipcMain.handle( 'session:close-terminal-surface', - (_event, args: { worktreeId: string; tabId: string; leafId?: string }) => { - if (typeof args?.worktreeId !== 'string' || typeof args.tabId !== 'string') { + (_event, args: { worktreeId?: unknown; target?: unknown } | undefined) => { + const target = parseTerminalSurfaceCloseTarget(args?.target) + if (typeof args?.worktreeId !== 'string' || !target) { throw new Error('invalid_terminal_surface') } - runtime.closeTerminalSurfaceFromRenderer({ - worktreeId: args.worktreeId, - tabId: args.tabId, - ...(typeof args.leafId === 'string' ? { leafId: args.leafId } : {}) - }) + runtime.closeTerminalSurfaceFromRenderer(args.worktreeId, target) } ) diff --git a/src/main/runtime/__fixtures__/orca-runtime-terminal-close-continuity-fixtures.ts b/src/main/runtime/__fixtures__/orca-runtime-terminal-close-continuity-fixtures.ts index 945284816224..71488b11999f 100644 --- a/src/main/runtime/__fixtures__/orca-runtime-terminal-close-continuity-fixtures.ts +++ b/src/main/runtime/__fixtures__/orca-runtime-terminal-close-continuity-fixtures.ts @@ -20,6 +20,7 @@ import { WORKTREE_ID, WORKTREE_PATH, canaryProcess, + makeDeferred, makeSession } from './orca-runtime-terminal-close-continuity-state-fixture' import { createCloseContinuityGraphFixture } from './orca-runtime-terminal-close-continuity-graph-fixture' @@ -45,18 +46,11 @@ export { makeSession } from './orca-runtime-terminal-close-continuity-state-fixture' -function makeDeferred() { - let resolve!: () => void - const promise = new Promise((settle) => { - resolve = settle - }) - return { promise, resolve } -} - export type CloseContinuityHarness = { runtime: OrcaRuntimeService acknowledged: ReturnType closeTerminal: Mock<(...args: unknown[]) => unknown> + closeTerminalPane: Mock<(...args: unknown[]) => unknown> closeTerminalTab: Mock<(...args: unknown[]) => unknown> flushOrThrow: Mock<() => void> kill: Mock<(ptyId: string) => boolean> @@ -67,6 +61,7 @@ export type CloseContinuityHarness = { syncFixtureTabWithoutLeaf: () => void syncSplitFixtureGraph: () => void getSession: () => WorkspaceSessionState + editSession: (edit: (session: WorkspaceSessionState) => WorkspaceSessionState) => void makeSessionUnavailable: () => void removeVictimFromInventory: () => void retirePersistedTab: () => void @@ -122,6 +117,7 @@ function createHarness( let closeTerminalTabError: Error | null = null let closeTerminalTabAction: (() => void | Promise) | null = null const closeTerminal = vi.fn() + const closeTerminalPane = vi.fn() const closeTerminalTab = vi.fn(() => { if (closeTerminalTabError) { return Promise.reject(closeTerminalTabError) @@ -162,7 +158,8 @@ function createHarness( ...(options.includeCanary ? [canaryProcess] : []) ]) const runtime = new OrcaRuntimeService(store as never) - runtime.setNotifier({ closeTerminal, closeTerminalTab } as never) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: these close paths call only the listed notifier methods. + runtime.setNotifier({ closeTerminal, closeTerminalPane, closeTerminalTab } as never) runtime.setPtyController({ write: () => true, kill, @@ -205,12 +202,16 @@ function createHarness( runtime, acknowledged, closeTerminal, + closeTerminalPane, closeTerminalTab, flushOrThrow: store.flushOrThrow, kill, stopAndWait, ...graph, getSession: () => session, + editSession: (edit) => { + session = edit(session) + }, makeSessionUnavailable: () => { sessionAvailable = false }, diff --git a/src/main/runtime/__fixtures__/orca-runtime-terminal-close-continuity-state-fixture.ts b/src/main/runtime/__fixtures__/orca-runtime-terminal-close-continuity-state-fixture.ts index d304ff57d232..21013296dafe 100644 --- a/src/main/runtime/__fixtures__/orca-runtime-terminal-close-continuity-state-fixture.ts +++ b/src/main/runtime/__fixtures__/orca-runtime-terminal-close-continuity-state-fixture.ts @@ -106,3 +106,11 @@ export function makeSession(ptyId = PTY_ID, includeCanary = false): WorkspaceSes } } } + +export function makeDeferred() { + let resolve!: () => void + const promise = new Promise((settle) => { + resolve = settle + }) + return { promise, resolve } +} diff --git a/src/main/runtime/headless-close-keeps-publication-epoch.test.ts b/src/main/runtime/headless-close-keeps-publication-epoch.test.ts index b33579b783c1..d5c46d3fa718 100644 --- a/src/main/runtime/headless-close-keeps-publication-epoch.test.ts +++ b/src/main/runtime/headless-close-keeps-publication-epoch.test.ts @@ -78,13 +78,13 @@ function closeOneTab(): RuntimeMobileSessionTabsSnapshot { closeHeadlessMobileTerminalTab: ( worktreeId: string, snapshot: RuntimeMobileSessionTabsSnapshot, - tab: RuntimeMobileSessionTerminalTab, + parentTabId: string, options?: Record ) => void mobileSessionTabsByWorktree: Map } internals.mobileSessionTabsByWorktree.set(WORKTREE_ID, snapshot) - internals.closeHeadlessMobileTerminalTab(WORKTREE_ID, snapshot, closedTab, { + internals.closeHeadlessMobileTerminalTab(WORKTREE_ID, snapshot, closedTab.parentTabId, { allowMissingPersistedTab: true, killPtys: false }) diff --git a/src/main/runtime/orca-runtime-build-headless-mobile-session-browser-tabs.ts b/src/main/runtime/orca-runtime-build-headless-mobile-session-browser-tabs.ts index 5803d42413d7..e4d2f3c894cd 100644 --- a/src/main/runtime/orca-runtime-build-headless-mobile-session-browser-tabs.ts +++ b/src/main/runtime/orca-runtime-build-headless-mobile-session-browser-tabs.ts @@ -3,11 +3,21 @@ import { OrcaRuntimeWithPersistTerminalSurfaceRetirements } from './orca-runtime import type { RuntimeMobileSessionBrowserTab, RuntimeMobileSessionTabsResult, - RuntimeMobileSessionTabsSnapshot + RuntimeMobileSessionTabsSnapshot, + RuntimeMobileSessionTerminalTab } from '../../shared/runtime-types' +import { parseAppSshPtyId } from '../../shared/ssh-pty-id' import { getRuntimeBrowserPageRegistry } from './runtime-browser-page-registry' import type { Tab } from '../../shared/tab-types' -import { closeTerminalSurfaceInWorkspaceSession } from './terminal-surface-close' +import { + closeTerminalSurfaceInWorkspaceSession, + resolveTerminalCloseTarget, + type PaneCloseResolution +} from './terminal-surface-close' +import type { + TerminalPaneCloseTarget, + TerminalSurfaceCloseTarget +} from '../../shared/terminal-surface-close-target' import { retireTerminalSurfacesFromSnapshot } from './mobile-session-terminal-retirement' import type { PtyControllerInventory } from './runtime-pty-controller-contract' import { FLOATING_TERMINAL_WORKTREE_ID } from '../../shared/constants' @@ -83,14 +93,14 @@ export class OrcaRuntimeWithBuildHeadlessMobileSessionBrowserTabs extends OrcaRu */ protected closeTerminalSurface( worktreeId: string, - tabId: string, - options: { leafId?: string; allowMissing?: boolean; force?: boolean } = {} + target: TerminalSurfaceCloseTarget, + options: { allowMissing?: boolean; force?: boolean } = {} ): string[] { const session = this.getWorkspaceSessionForWorktree(worktreeId) if (!session || !this.store?.setWorkspaceSession || !this.store.flushOrThrow) { throw new Error('workspace_session_unavailable') } - const result = closeTerminalSurfaceInWorkspaceSession(session, worktreeId, tabId, options) + const result = closeTerminalSurfaceInWorkspaceSession(session, worktreeId, target, options) if (result.pinned) { throw new Error('terminal_tab_pinned') } @@ -112,26 +122,42 @@ export class OrcaRuntimeWithBuildHeadlessMobileSessionBrowserTabs extends OrcaRu } /** The desktop renderer's close intent: the renderer already ran its pin guard and owns the kill. */ - closeTerminalSurfaceFromRenderer(args: { - worktreeId: string - tabId: string - leafId?: string - }): void { - this.closeTerminalSurface(args.worktreeId, args.tabId, { - leafId: args.leafId, - allowMissing: true, - force: true + closeTerminalSurfaceFromRenderer(worktreeId: string, target: TerminalSurfaceCloseTarget): void { + this.closeTerminalSurface(worktreeId, target, { allowMissing: true, force: true }) + } + + /** Resolves a close main started against the copy of the tab's panes its layout owner holds. */ + protected resolveTerminalCloseTarget( + worktreeId: string, + target: TerminalSurfaceCloseTarget + ): PaneCloseResolution | 'tab' { + const session = this.getWorkspaceSessionForWorktree(worktreeId) + const graphLeafIds: string[] = [] + for (const leaf of this.leaves.values()) { + if (leaf.tabId === target.tabId) { + graphLeafIds.push(leaf.leafId) + } + } + return resolveTerminalCloseTarget(target, { + rendererListsTab: this.tabs.has(target.tabId), + snapshotRows: (this.mobileSessionTabsByWorktree.get(worktreeId)?.tabs ?? []).filter( + (row) => row.type === 'terminal' && row.parentTabId === target.tabId + ), + graphLeafIds, + sessionLayout: session?.terminalLayoutsByTabId?.[target.tabId], + sessionListsTab: Object.values(session?.tabsByWorktree ?? {}).some((tabs) => + tabs.some((tab) => tab.id === target.tabId) + ) }) } /** - * Commits a split pane's close that main started once its process was stopped, then tells the - * desktop renderer to drop that leaf. No session means nothing persisted to remove. + * Commits a split pane's close that main started, then tells the desktop renderer to drop that + * pane. Never touches the tab: a pane the session no longer lists commits nothing. */ - protected closeTerminalLeaf(worktreeId: string, tabId: string, leafId: string): void { + protected closeTerminalPane(worktreeId: string, target: TerminalPaneCloseTarget): void { try { - // Why force: the process is already stopped, so a pin must not fail the close after the fact. - this.closeTerminalSurface(worktreeId, tabId, { leafId, allowMissing: true, force: true }) + this.closeTerminalSurface(worktreeId, target, { allowMissing: true }) } catch (error) { if (!(error instanceof Error) || error.message !== 'workspace_session_unavailable') { throw error @@ -139,8 +165,24 @@ export class OrcaRuntimeWithBuildHeadlessMobileSessionBrowserTabs extends OrcaRu } // Why: no exit may ever arrive to remove the pane. The notice is leaf-addressed, so it and the // renderer's exit handling are each a no-op after the other. - this.retireClosedTerminalLeafFromMobileSnapshot(worktreeId, tabId, leafId) - this.notifier?.closeTerminal(tabId, leafId) + this.retireClosedTerminalLeafFromMobileSnapshot(worktreeId, target.tabId, target.leafId) + this.notifier?.closeTerminalPane?.(target.tabId, target.leafId) + } + + /** A paired client's close of one pane: stops only that pane's process, commits only that pane. */ + protected closeMobileSessionTerminalPane( + worktreeId: string, + tab: RuntimeMobileSessionTerminalTab + ): void { + const pty = this.findPtyForMobileTerminalTab(worktreeId, tab) + if (pty && this.ptyController?.kill(pty.ptyId) !== true) { + throw new Error('terminal_close_failed') + } + if (!pty && !this.tabs.has(tab.parentTabId) && tab.ptyId && parseAppSshPtyId(tab.ptyId)) { + // Why: with no renderer to own the kill, a dormant SSH pane's durable id is its stop order. + this.ptyController?.kill(tab.ptyId) + } + this.closeTerminalPane(worktreeId, { kind: 'pane', tabId: tab.parentTabId, leafId: tab.leafId }) } private retireClosedTerminalLeafFromMobileSnapshot( diff --git a/src/main/runtime/orca-runtime-close-headless-mobile-terminal-tab.ts b/src/main/runtime/orca-runtime-close-headless-mobile-terminal-tab.ts index 74e9c3f4288f..a344c8ed508a 100644 --- a/src/main/runtime/orca-runtime-close-headless-mobile-terminal-tab.ts +++ b/src/main/runtime/orca-runtime-close-headless-mobile-terminal-tab.ts @@ -3,8 +3,7 @@ import { OrcaRuntimeWithCloseStructuredAgentSessionTab } from './orca-runtime-cl import type { RuntimeMobileSessionTabMove, RuntimeMobileSessionTabMoveResult, - RuntimeMobileSessionTabsSnapshot, - RuntimeMobileSessionTerminalTab + RuntimeMobileSessionTabsSnapshot } from '../../shared/runtime-types' import { parseAppSshPtyId } from '../../shared/ssh-pty-id' import { buildHeadlessMobileSessionTabGroups } from './mobile-session-layout-projection' @@ -16,7 +15,7 @@ export class OrcaRuntimeWithCloseHeadlessMobileTerminalTab extends OrcaRuntimeWi protected closeHeadlessMobileTerminalTab( worktreeId: string, snapshot: RuntimeMobileSessionTabsSnapshot, - tab: RuntimeMobileSessionTerminalTab, + closedParentTabId: string, options: { allowMissingPersistedTab?: boolean killPtys?: boolean @@ -24,7 +23,6 @@ export class OrcaRuntimeWithCloseHeadlessMobileTerminalTab extends OrcaRuntimeWi force?: boolean } = {} ): void { - const closedParentTabId = tab.parentTabId const retirementProofs = snapshot.tabs.flatMap((candidate) => { if (candidate.type !== 'terminal' || candidate.parentTabId !== closedParentTabId) { return [] @@ -36,10 +34,14 @@ export class OrcaRuntimeWithCloseHeadlessMobileTerminalTab extends OrcaRuntimeWi ) return proof ? [proof] : [] }) - const projectedPtyIds = this.closeTerminalSurface(worktreeId, closedParentTabId, { - allowMissing: options.allowMissingPersistedTab, - force: options.force - }) + const projectedPtyIds = this.closeTerminalSurface( + worktreeId, + { kind: 'tab', tabId: closedParentTabId }, + { + allowMissing: options.allowMissingPersistedTab, + force: options.force + } + ) this.clearRuntimeSessionOwnershipForMobileTab(worktreeId, snapshot, closedParentTabId) if (options.authorizedPty) { options.authorizedPty.runtimeSessionOwned = false diff --git a/src/main/runtime/orca-runtime-close-mobile-session-tab.ts b/src/main/runtime/orca-runtime-close-mobile-session-tab.ts index 8ac3f252b5c0..e57a37fe732b 100644 --- a/src/main/runtime/orca-runtime-close-mobile-session-tab.ts +++ b/src/main/runtime/orca-runtime-close-mobile-session-tab.ts @@ -120,10 +120,14 @@ export class OrcaRuntimeWithCloseMobileSessionTab extends OrcaRuntimeWithRefuseU closedSelectionTabIds ) if (tab.type === 'terminal') { - const parentLeafCount = snapshot.tabs.filter( - (candidate) => candidate.type === 'terminal' && candidate.parentTabId === tab.parentTabId - ).length - const closingWholeParent = tab.id !== tabId || parentLeafCount <= 1 + // Why: the wire id carries the intent — `parent::leaf` names a pane, `parent` its tab. + const resolution = this.resolveTerminalCloseTarget( + worktreeId, + tab.id === tabId + ? { kind: 'pane', tabId: tab.parentTabId, leafId: tab.leafId } + : { kind: 'tab', tabId: tab.parentTabId } + ) + const closingWholeParent = resolution === 'tab' || resolution === 'last-pane' if (closingWholeParent) { closedSelectionTabIds = snapshot.tabs.flatMap((candidate) => candidate.type === 'terminal' && candidate.parentTabId === tab.parentTabId @@ -167,7 +171,7 @@ export class OrcaRuntimeWithCloseMobileSessionTab extends OrcaRuntimeWithRefuseU // the relay when no renderer owns the parent: an adopted tab needs the // renderer's live pin guard and durable close transaction. if (closingWholeParent && !this.tabs.has(tab.parentTabId)) { - this.closeHeadlessMobileTerminalTab(worktreeId, snapshot, tab, { + this.closeHeadlessMobileTerminalTab(worktreeId, snapshot, tab.parentTabId, { allowMissingPersistedTab: Boolean(ptyCloseAuthority), force: options.force, killPtys: @@ -230,7 +234,7 @@ export class OrcaRuntimeWithCloseMobileSessionTab extends OrcaRuntimeWithRefuseU ? this.resolvePtyTabCloseSurfaceAuthority(options.expectedPtyCloseAuthority) : null // Why: after relay recovery the renderer can acknowledge a tab it no longer mirrors; the HUB must still retire its SSH-owned surface. - this.closeHeadlessMobileTerminalTab(worktreeId, remainingSnapshot, remainingTab, { + this.closeHeadlessMobileTerminalTab(worktreeId, remainingSnapshot, tab.parentTabId, { // Why: the renderer may already have durably removed the tab before acknowledging. allowMissingPersistedTab: true, force: options.force, @@ -240,47 +244,35 @@ export class OrcaRuntimeWithCloseMobileSessionTab extends OrcaRuntimeWithRefuseU } else if (retirement.hasPersistedTab) { // Why: the renderer's close normally commits this through its own intent; this covers // a renderer that acknowledged a tab it no longer listed. - this.closeTerminalSurface(worktreeId, tab.parentTabId, { force: options.force }) + this.closeTerminalSurface( + worktreeId, + { kind: 'tab', tabId: tab.parentTabId }, + { force: options.force } + ) } this.clearRuntimeSessionOwnershipForMobileTab(worktreeId, snapshot, tab.parentTabId) return finishCommittedClose() } - // Why: notifier implementations without the acknowledged relay may expose - // only raw pane close. Runtime-owned parents still need de-persist + kill. - if (closingWholeParent && this.isRuntimeOwnedHeadlessMobileTab(worktreeId, tab)) { - this.closeHeadlessMobileTerminalTab(worktreeId, snapshot, tab, { - force: options.force, - ...(ptyCloseAuthority ? { authorizedPty: ptyCloseAuthority.pty } : {}) - }) - this.notifyRendererOfHeadlessTerminalClose(tab.parentTabId) - return finishCommittedClose() - } - if (!this.notifier?.closeTerminal) { - this.closeHeadlessMobileTerminalTab(worktreeId, snapshot, tab, { - force: options.force, - ...(ptyCloseAuthority ? { authorizedPty: ptyCloseAuthority.pty } : {}) - }) - return finishCommittedClose() - } - if (tab.id === tabId) { - const pty = this.findPtyForMobileTerminalTab(worktreeId, tab) - if (pty) { - if (this.ptyController?.kill(pty.ptyId) !== true) { - throw new Error('terminal_close_failed') - } - // Why: the pane's removal is this close's own commit, not a side effect of its exit. - this.closeTerminalLeaf(worktreeId, tab.parentTabId, tab.leafId) + if (closingWholeParent) { + // Why: notifier implementations without the acknowledged relay may expose + // only raw pane close. Runtime-owned parents still need de-persist + kill. + if ( + !this.notifier?.closeTerminal || + this.isRuntimeOwnedHeadlessMobileTab(worktreeId, tab) + ) { + this.closeHeadlessMobileTerminalTab(worktreeId, snapshot, tab.parentTabId, { + force: options.force, + ...(ptyCloseAuthority ? { authorizedPty: ptyCloseAuthority.pty } : {}) + }) + this.notifyRendererOfHeadlessTerminalClose(tab.parentTabId) return finishCommittedClose() } this.notifier.closeTerminal(tab.parentTabId) + this.clearRuntimeSessionOwnershipForMobileTab(worktreeId, snapshot, tab.parentTabId) return delegatedMobileSessionTabClose() } - // Why: paired web tab bars represent a split terminal with one local - // parent tab id. Closing that parent should close the desktop tab, not - // just whichever leaf happened to be first in the session snapshot. - this.notifier.closeTerminal(tab.parentTabId) - this.clearRuntimeSessionOwnershipForMobileTab(worktreeId, snapshot, tab.parentTabId) - return delegatedMobileSessionTabClose() + this.closeMobileSessionTerminalPane(worktreeId, tab) + return finishCommittedClose() } else if (tab.type === 'browser') { // Why: a browser tab can be hosted by a client, by the offscreen backend, // or by the renderer; each surface owns a different retirement path. diff --git a/src/main/runtime/orca-runtime-stop-explicitly-closed-tab-ptys.ts b/src/main/runtime/orca-runtime-stop-explicitly-closed-tab-ptys.ts index 9bb138d615be..ee1bb6d8bb7f 100644 --- a/src/main/runtime/orca-runtime-stop-explicitly-closed-tab-ptys.ts +++ b/src/main/runtime/orca-runtime-stop-explicitly-closed-tab-ptys.ts @@ -3,7 +3,6 @@ import { OrcaRuntimeWithFocusTerminal } from './orca-runtime-focus-terminal' import { EXPLICIT_TERMINAL_CLOSE_STOP_TIMEOUT_MS } from './orca-runtime-core' import { SSH_PROVIDER_UNREGISTERED_REASON } from '../../shared/pty-liveness-verdict' import type { RuntimeTerminalClose } from '../../shared/runtime-types' -import { countTerminalLayoutLeaves } from './headless-terminal-split-layout' import type { RuntimePtyTabCloseAuthority } from './runtime-terminal-state-records' import { parsePaneKey } from '../../shared/stable-pane-id' @@ -107,11 +106,13 @@ export class OrcaRuntimeWithStopExplicitlyClosedTabPtys extends OrcaRuntimeWithF ? spawnSurface : null) const tabId = surface?.tab.parentTabId ?? pty.pty.tabId ?? pty.record.tabId - // Why: relay recovery can leave stale renderer leaves; the persisted HUB layout defines whether closing this PTY closes the whole surface. - const siblingCount = surface?.tab.parentLayout - ? countTerminalLayoutLeaves(surface.tab.parentLayout.root) - : this.countLeavesInTab(tabId) - if (siblingCount <= 1 && surface && this.tabs.has(tabId) && this.notifier?.closeTerminalTab) { + const leafId = surface?.tab.leafId ?? parsePaneKey(pty.pty.paneKey ?? '')?.leafId + const paneTarget = leafId ? { kind: 'pane' as const, tabId, leafId } : null + // Why: a PTY with no pane identity cannot be placed in any tab's layout, so it closes nothing. + const closesTab = + paneTarget !== null && + this.resolveTerminalCloseTarget(pty.pty.worktreeId, paneTarget) === 'last-pane' + if (closesTab && surface && this.tabs.has(tabId) && this.notifier?.closeTerminalTab) { const ptyIdsToKill = this.getPtyIdsForExplicitTabClose(pty.pty.worktreeId, tabId) try { await this.closeMobileSessionTab(`id:${pty.pty.worktreeId}`, tabId, { @@ -126,12 +127,7 @@ export class OrcaRuntimeWithStopExplicitlyClosedTabPtys extends OrcaRuntimeWithF const ptyKilled = await this.stopExplicitlyClosedTabPtys(ptyIdsToKill, pty.pty.ptyId) return this.describeTerminalClose(handle, tabId, pty.pty.ptyId, ptyKilled) } - if ( - siblingCount <= 1 && - surface && - ptyCloseAuthority && - !this.tabs.has(surface.tab.parentTabId) - ) { + if (closesTab && surface && ptyCloseAuthority && !this.tabs.has(surface.tab.parentTabId)) { try { await this.closeMobileSessionTab(`id:${pty.pty.worktreeId}`, tabId, { reason: 'user', @@ -149,19 +145,18 @@ export class OrcaRuntimeWithStopExplicitlyClosedTabPtys extends OrcaRuntimeWithF const ptyKilled = await this.stopExplicitlyClosedTabPtys([pty.pty.ptyId], pty.pty.ptyId) return this.describeTerminalClose(handle, tabId, pty.pty.ptyId, ptyKilled) } - if (siblingCount <= 1 && !surface && pty.pty.tabId && this.notifier?.closeTerminalTab) { + if (closesTab && !surface && pty.pty.tabId && this.notifier?.closeTerminalTab) { const ptyIdsToKill = this.getPtyIdsForExplicitTabClose(pty.pty.worktreeId, tabId) await this.notifier.closeTerminalTab(tabId, { localPtyTeardownOwnedExternally: true }) const ptyKilled = await this.stopExplicitlyClosedTabPtys(ptyIdsToKill, pty.pty.ptyId) return this.describeTerminalClose(handle, tabId, pty.pty.ptyId, ptyKilled) } const ptyKilled = await this.stopExplicitlyClosedTabPtys([pty.pty.ptyId], pty.pty.ptyId) - if (siblingCount > 1) { - const leafId = surface?.tab.leafId ?? parsePaneKey(pty.pty.paneKey ?? '')?.leafId + if (!closesTab) { // Why: the pane's removal is this close's own commit, not a side effect of its exit. An // unconfirmed stop is unverifiable, never a reason to close the live siblings with it. - if (leafId) { - this.closeTerminalLeaf(pty.pty.worktreeId, tabId, leafId) + if (paneTarget) { + this.closeTerminalPane(pty.pty.worktreeId, paneTarget) } } else if (surface) { // Why: paired viewers keep ended streams mounted until the HUB publishes removal, so explicit close uses the durable host-tab transaction instead of viewer-local exit handling. @@ -182,21 +177,21 @@ export class OrcaRuntimeWithStopExplicitlyClosedTabPtys extends OrcaRuntimeWithF } this.assertGraphReady() const { leaf } = this.getLiveLeafForHandle(handle) - const siblingCount = this.countLeavesInTab(leaf.tabId) - const ptyIdsToKill = - siblingCount <= 1 - ? this.getPtyIdsForExplicitTabClose(leaf.worktreeId, leaf.tabId) - : leaf.ptyId - ? [leaf.ptyId] - : [] - if (siblingCount <= 1 && this.notifier?.closeTerminalTab) { + const paneTarget = { kind: 'pane' as const, tabId: leaf.tabId, leafId: leaf.leafId } + const closesTab = this.resolveTerminalCloseTarget(leaf.worktreeId, paneTarget) === 'last-pane' + const ptyIdsToKill = closesTab + ? this.getPtyIdsForExplicitTabClose(leaf.worktreeId, leaf.tabId) + : leaf.ptyId + ? [leaf.ptyId] + : [] + if (closesTab && this.notifier?.closeTerminalTab) { await this.notifier.closeTerminalTab(leaf.tabId, { localPtyTeardownOwnedExternally: true }) } const ptyKilled = leaf.ptyId ? await this.stopExplicitlyClosedTabPtys(ptyIdsToKill, leaf.ptyId) : false - if (siblingCount > 1) { - this.closeTerminalLeaf(leaf.worktreeId, leaf.tabId, leaf.leafId) + if (!closesTab) { + this.closeTerminalPane(leaf.worktreeId, paneTarget) } else if (!this.notifier?.closeTerminalTab) { this.notifier?.closeTerminal(leaf.tabId) } diff --git a/src/main/runtime/orca-runtime-terminal-close-no-widening.test.ts b/src/main/runtime/orca-runtime-terminal-close-no-widening.test.ts new file mode 100644 index 000000000000..6b51be8e78ad --- /dev/null +++ b/src/main/runtime/orca-runtime-terminal-close-no-widening.test.ts @@ -0,0 +1,263 @@ +import { describe, expect, it } from 'vitest' +import { + LEAF_ID, + PTY_ID, + SIBLING_LEAF_ID, + SIBLING_PTY_ID, + TAB_ID, + WORKTREE_ID, + createHarness, + type CloseContinuityHarness +} from './__fixtures__/orca-runtime-terminal-close-continuity-fixtures' +import { retireTerminalSurfaceFromPersistence } from './mobile-session-terminal-persistence-retirement' + +/** + * Every explicit close of one pane, from every entry point, under every condition that has ever + * widened one into a whole-tab close: the live sibling survives and no tab-level close goes out. + */ + +type Entry = 'renderer' | 'cli-graph' | 'cli-pty' | 'phone-desktop' | 'phone-headless' +type Condition = + | 'normal' + | 'stop-unconfirmed' + | 'stop-throws' + | 'leaf-already-retired' + | 'unbound-sibling' + | 'pinned' + | 'no-saved-layout' + | 'no-live-pty' + +/** The desktop renderer's split tab as it publishes it, with the given PTY bindings. */ +function syncRendererSplit( + harness: CloseContinuityHarness, + ptyIdsByLeafId: Record, + livePtyIdsByLeafId = ptyIdsByLeafId +): void { + const parentLayout = { + root: { + type: 'split' as const, + direction: 'horizontal' as const, + first: { type: 'leaf' as const, leafId: LEAF_ID }, + second: { type: 'leaf' as const, leafId: SIBLING_LEAF_ID } + }, + activeLeafId: LEAF_ID, + expandedLeafId: null, + ptyIdsByLeafId + } + const leaves = [LEAF_ID, SIBLING_LEAF_ID].map((leafId, index) => ({ + tabId: TAB_ID, + worktreeId: WORKTREE_ID, + leafId, + paneRuntimeId: 7 + index, + ptyId: livePtyIdsByLeafId[leafId] ?? null + })) + harness.runtime.syncWindowGraph(1, { + tabs: [ + { + tabId: TAB_ID, + worktreeId: WORKTREE_ID, + title: 'Fixture shell', + activeLeafId: LEAF_ID, + layout: parentLayout.root + } + ], + leaves, + mobileSessionTabs: [ + { + worktree: WORKTREE_ID, + publicationEpoch: 'renderer:unbound-pane', + snapshotVersion: 3, + activeGroupId: null, + activeTabId: `${TAB_ID}::${LEAF_ID}`, + activeTabType: 'terminal' as const, + tabs: leaves.map((leaf) => ({ + type: 'terminal' as const, + id: `${TAB_ID}::${leaf.leafId}`, + parentTabId: TAB_ID, + leafId: leaf.leafId, + ...(ptyIdsByLeafId[leaf.leafId] ? { ptyId: ptyIdsByLeafId[leaf.leafId] } : {}), + title: 'Fixture shell', + parentLayout, + isActive: leaf.leafId === LEAF_ID + })) + } + ] + }) +} + +function arrange(entry: Entry, condition: Condition): CloseContinuityHarness { + const usesPtyRecord = entry !== 'cli-graph' && entry !== 'renderer' && condition !== 'no-live-pty' + const harness = createHarness({ publishMobileSurface: true, registerPtyBacked: usesPtyRecord }) + if (condition === 'unbound-sibling') { + // A pane the renderer just split: no PTY bound yet, so main's saved layout lacks it. + syncRendererSplit(harness, { [LEAF_ID]: PTY_ID }) + } else { + harness.syncSplitFixtureGraph() + } + if (condition === 'no-live-pty') { + // The closed pane's process already exited, so main holds no record of its PTY. + syncRendererSplit( + harness, + { [LEAF_ID]: 'pty-exited', [SIBLING_LEAF_ID]: SIBLING_PTY_ID }, + { [SIBLING_LEAF_ID]: SIBLING_PTY_ID } + ) + } + if (entry === 'cli-pty') { + // Graph without the leaf: the handle resolves through the PTY, as for a runtime-owned pane. + harness.syncFixtureTabWithoutLeaf() + } + if (condition === 'stop-unconfirmed') { + harness.setVerifiedStopResult(false) + } else if (condition === 'stop-throws') { + harness.setVerifiedStopResult(new Error('ssh_host_unreachable')) + } else { + harness.setVerifiedStopResult(true) + } + if (condition === 'leaf-already-retired') { + harness.editSession((session) => + retireTerminalSurfaceFromPersistence(session, { + worktreeId: WORKTREE_ID, + parentTabId: TAB_ID, + leafId: LEAF_ID, + ptyId: PTY_ID + }) + ) + } else if (condition === 'pinned') { + harness.editSession((session) => ({ + ...session, + tabsByWorktree: { + [WORKTREE_ID]: (session.tabsByWorktree[WORKTREE_ID] ?? []).map((tab) => ({ + ...tab, + isPinned: true + })) + } + })) + } else if (condition === 'no-saved-layout') { + harness.editSession((session) => ({ ...session, terminalLayoutsByTabId: {} })) + } + // A renderer that honours a whole-tab close, so a widened close shows as the lost sibling. + harness.setCloseTerminalTabAction(() => harness.retirePersistedTab()) + return harness +} + +async function closePane(entry: Entry, harness: CloseContinuityHarness): Promise { + if (entry === 'renderer') { + harness.runtime.closeTerminalSurfaceFromRenderer(WORKTREE_ID, { + kind: 'pane', + tabId: TAB_ID, + leafId: LEAF_ID + }) + return + } + if (entry === 'cli-graph' || entry === 'cli-pty') { + const terminal = (await harness.runtime.listTerminals(`id:${WORKTREE_ID}`)).terminals.find( + (candidate) => candidate.ptyId === PTY_ID + ) + if (!terminal) { + throw new Error('fixture pane has no terminal handle') + } + await harness.runtime.closeTerminal(terminal.handle) + return + } + if (entry === 'phone-headless') { + harness.runtime.setNotifier(null) + harness.syncEmptyGraph() + } + await harness.runtime.closeMobileSessionTab(`id:${WORKTREE_ID}`, `${TAB_ID}::${LEAF_ID}`, { + reason: 'user' + }) +} + +const rows: [Entry, Condition][] = [ + // e.g. the exited-pane overlay's Close after main's exit handling retired that pane (fc5cac5c32). + ['renderer', 'leaf-already-retired'], + ['renderer', 'unbound-sibling'], + ['renderer', 'pinned'], + ['renderer', 'no-saved-layout'], + ['cli-graph', 'normal'], + ['cli-graph', 'stop-unconfirmed'], + ['cli-graph', 'leaf-already-retired'], + ['cli-graph', 'unbound-sibling'], + ['cli-pty', 'normal'], + // An unconfirmed stop once chose the tab close (bc8bbd7abf). + ['cli-pty', 'stop-unconfirmed'], + ['cli-pty', 'stop-throws'], + ['cli-pty', 'unbound-sibling'], + ['phone-desktop', 'normal'], + ['phone-desktop', 'pinned'], + ['phone-desktop', 'unbound-sibling'], + ['phone-desktop', 'no-saved-layout'], + // A pane with no live process record once sent a tab-level close notice. + ['phone-desktop', 'no-live-pty'], + // A host with no desktop window once closed the whole tab for one pane. + ['phone-headless', 'normal'], + ['phone-headless', 'leaf-already-retired'], + ['phone-headless', 'pinned'], + ['phone-headless', 'no-saved-layout'] +] + +describe('an explicit close of one pane never widens into its tab', () => { + it.each(rows)('%s close, %s', async (entry, condition) => { + const harness = arrange(entry, condition) + const siblingWasPersisted = Boolean( + harness.getSession().terminalLayoutsByTabId[TAB_ID]?.ptyIdsByLeafId?.[SIBLING_LEAF_ID] + ) + + await closePane(entry, harness) + + const session = harness.getSession() + expect(session.tabsByWorktree[WORKTREE_ID]).toEqual([expect.objectContaining({ id: TAB_ID })]) + if (siblingWasPersisted) { + expect(session.terminalLayoutsByTabId[TAB_ID]?.root).toEqual({ + type: 'leaf', + leafId: SIBLING_LEAF_ID + }) + } + expect(harness.closeTerminalTab).not.toHaveBeenCalled() + expect(harness.closeTerminal).not.toHaveBeenCalled() + expect(harness.kill).not.toHaveBeenCalledWith(SIBLING_PTY_ID) + if (entry === 'renderer') { + return + } + if (entry === 'phone-headless') { + const snapshot = await harness.runtime.listMobileSessionTabs(`id:${WORKTREE_ID}`) + expect(snapshot.tabs.map((tab) => tab.id)).toEqual([`${TAB_ID}::${SIBLING_LEAF_ID}`]) + expect(harness.kill).toHaveBeenCalledWith(PTY_ID) + return + } + expect(harness.closeTerminalPane).toHaveBeenCalledExactlyOnceWith(TAB_ID, LEAF_ID) + }) +}) + +describe("a close of a tab's last pane still closes the tab", () => { + it('on a host with no desktop window, closes the whole tab in main and for paired clients', async () => { + const harness = createHarness({ publishMobileSurface: true, registerPtyBacked: true }) + harness.runtime.setNotifier(null) + harness.syncEmptyGraph() + + await harness.runtime.closeMobileSessionTab(`id:${WORKTREE_ID}`, `${TAB_ID}::${LEAF_ID}`, { + reason: 'user' + }) + + expect(harness.getSession().tabsByWorktree[WORKTREE_ID]).toEqual([]) + expect((await harness.runtime.listMobileSessionTabs(`id:${WORKTREE_ID}`)).tabs).toEqual([]) + expect(harness.kill).toHaveBeenCalledWith(PTY_ID) + }) + + it.each(['phone-desktop', 'cli-graph'] as const)( + 'from %s, goes through the renderer tab close so its pin guard still runs', + async (entry) => { + const harness = createHarness({ + publishMobileSurface: true, + registerPtyBacked: entry === 'phone-desktop' + }) + harness.setVerifiedStopResult(true) + harness.setCloseTerminalTabAction(() => harness.retirePersistedTab()) + + await closePane(entry, harness) + + expect(harness.closeTerminalTab.mock.calls.map((call) => call[0])).toEqual([TAB_ID]) + expect(harness.closeTerminalPane).not.toHaveBeenCalled() + } + ) +}) diff --git a/src/main/runtime/orca-runtime-terminal-surface-close.test.ts b/src/main/runtime/orca-runtime-terminal-surface-close.test.ts index c107ff542300..1312b36f873a 100644 --- a/src/main/runtime/orca-runtime-terminal-surface-close.test.ts +++ b/src/main/runtime/orca-runtime-terminal-surface-close.test.ts @@ -121,7 +121,7 @@ describe('renderer close intents', () => { it('keeps a closed tab closed across a renderer save and a reload', async () => { const { store, runtime, reload } = createPersistedRuntime(makeSession()) - runtime.closeTerminalSurfaceFromRenderer({ worktreeId: WORKTREE_ID, tabId: TAB_ID }) + runtime.closeTerminalSurfaceFromRenderer(WORKTREE_ID, { kind: 'tab', tabId: TAB_ID }) store.setWorkspaceSession(rendererSaveWithout(store.getWorkspaceSession())) expect((await reload()).tabsByWorktree[WORKTREE_ID]).toEqual([]) @@ -130,8 +130,8 @@ describe('renderer close intents', () => { it('keeps a closed split pane closed across a renderer save and a reload', async () => { const { store, runtime, reload } = createPersistedRuntime(splitSession()) - runtime.closeTerminalSurfaceFromRenderer({ - worktreeId: WORKTREE_ID, + runtime.closeTerminalSurfaceFromRenderer(WORKTREE_ID, { + kind: 'pane', tabId: TAB_ID, leafId: LEAF_ID }) @@ -156,8 +156,8 @@ describe('renderer close intents', () => { ])('never widens a pane close into a tab close when %s', async (_case, session) => { const { runtime, reload } = createPersistedRuntime(session()) - runtime.closeTerminalSurfaceFromRenderer({ - worktreeId: WORKTREE_ID, + runtime.closeTerminalSurfaceFromRenderer(WORKTREE_ID, { + kind: 'pane', tabId: TAB_ID, leafId: LEAF_ID }) @@ -190,7 +190,7 @@ describe('CLI close of one pane in a split tab', () => { ptyIdsByLeafId: { [SIBLING_LEAF_ID]: SIBLING_PTY_ID } }) // No exit arrives to remove the pane, so the desktop renderer is told to drop that leaf. - expect(harness.closeTerminal).toHaveBeenCalledExactlyOnceWith(TAB_ID, LEAF_ID) + expect(harness.closeTerminalPane).toHaveBeenCalledExactlyOnceWith(TAB_ID, LEAF_ID) expect(harness.closeTerminalTab).not.toHaveBeenCalled() }) @@ -213,7 +213,7 @@ describe('CLI close of one pane in a split tab', () => { type: 'leaf', leafId: SIBLING_LEAF_ID }) - expect(harness.closeTerminal).toHaveBeenCalledExactlyOnceWith(TAB_ID, LEAF_ID) + expect(harness.closeTerminalPane).toHaveBeenCalledExactlyOnceWith(TAB_ID, LEAF_ID) expect(harness.closeTerminalTab).not.toHaveBeenCalled() }) @@ -245,7 +245,7 @@ describe('CLI close of one pane in a split tab', () => { type: 'leaf', leafId: SIBLING_LEAF_ID }) - expect(harness.closeTerminal).toHaveBeenCalledExactlyOnceWith(TAB_ID, LEAF_ID) + expect(harness.closeTerminalPane).toHaveBeenCalledExactlyOnceWith(TAB_ID, LEAF_ID) expect(harness.closeTerminalTab).not.toHaveBeenCalled() // The owed stop still goes out through the controller's kill, which records SSH pending kills. expect(harness.kill).toHaveBeenCalledWith(PTY_ID) @@ -319,7 +319,7 @@ describe('mobile close of one pane in a split tab', () => { expect(harness.getSession().terminalLayoutsByTabId[TAB_ID]).toMatchObject({ root: { type: 'leaf', leafId: SIBLING_LEAF_ID } }) - expect(harness.closeTerminal).toHaveBeenCalledExactlyOnceWith(TAB_ID, LEAF_ID) + expect(harness.closeTerminalPane).toHaveBeenCalledExactlyOnceWith(TAB_ID, LEAF_ID) }) }) diff --git a/src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-10.spec.ts b/src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-10.spec.ts index be367668212f..6974a6f7f8f2 100644 --- a/src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-10.spec.ts +++ b/src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-10.spec.ts @@ -478,6 +478,7 @@ describe('OrcaRuntimeService', () => { ) const kill = vi.fn(() => true) const closeTerminal = vi.fn() + const closeTerminalPane = vi.fn() const runtime = new OrcaRuntimeService(runtimeStore as never) runtime.setPtyController({ write: () => true, @@ -485,7 +486,8 @@ describe('OrcaRuntimeService', () => { getForegroundProcess: async () => null, listProcesses: async () => [] }) - runtime.setNotifier({ closeTerminal } as never) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: these close paths call only the listed notifier methods. + runtime.setNotifier({ closeTerminal, closeTerminalPane } as never) runtime.syncWindowGraph(1, { tabs: [ { @@ -525,7 +527,8 @@ describe('OrcaRuntimeService', () => { expect(kill).toHaveBeenCalledWith('serve-right') expect(kill).not.toHaveBeenCalledWith('serve-left') // Only the leaf-addressed notice for the closed pane; never a whole-tab close. - expect(closeTerminal).toHaveBeenCalledExactlyOnceWith('host-tab', HEADLESS_SECOND_LEAF_ID) + expect(closeTerminalPane).toHaveBeenCalledExactlyOnceWith('host-tab', HEADLESS_SECOND_LEAF_ID) + expect(closeTerminal).not.toHaveBeenCalled() expect(getSession().tabsByWorktree[TEST_WORKTREE_ID]).toHaveLength(1) expect(getSession().terminalLayoutsByTabId['host-tab']?.root).toEqual({ type: 'leaf', diff --git a/src/main/runtime/orca-runtime-tests/mobile-session-tabs.spec.ts b/src/main/runtime/orca-runtime-tests/mobile-session-tabs.spec.ts index 462b83b10e5c..fe8f7e08fab4 100644 --- a/src/main/runtime/orca-runtime-tests/mobile-session-tabs.spec.ts +++ b/src/main/runtime/orca-runtime-tests/mobile-session-tabs.spec.ts @@ -235,6 +235,7 @@ describe('OrcaRuntimeService', () => { it('closes the matching mobile terminal UUID leaf without closing the whole tab', async () => { const closeTerminal = vi.fn() + const closeTerminalPane = vi.fn() const kill = vi.fn(() => true) const runtime = new OrcaRuntimeService(store) runtime.setPtyController({ @@ -253,6 +254,7 @@ describe('OrcaRuntimeService', () => { renameTerminal: vi.fn(), focusTerminal: vi.fn(), closeTerminal, + closeTerminalPane, sleepWorktree: vi.fn(), terminalFitOverrideChanged: vi.fn(), terminalDriverChanged: vi.fn() @@ -314,7 +316,8 @@ describe('OrcaRuntimeService', () => { expect(kill).toHaveBeenCalledWith('pty-right') // Only the leaf-addressed notice for the closed pane; never a whole-tab close. - expect(closeTerminal).toHaveBeenCalledExactlyOnceWith('tab-1', rightLeafId) + expect(closeTerminalPane).toHaveBeenCalledExactlyOnceWith('tab-1', rightLeafId) + expect(closeTerminal).not.toHaveBeenCalled() }) it('closes the whole mobile terminal tab when addressed by parent tab id', async () => { diff --git a/src/main/runtime/orca-runtime-wait-for-leaf-pty-id.ts b/src/main/runtime/orca-runtime-wait-for-leaf-pty-id.ts index 37ac8c5a8394..b3749ec6dba7 100644 --- a/src/main/runtime/orca-runtime-wait-for-leaf-pty-id.ts +++ b/src/main/runtime/orca-runtime-wait-for-leaf-pty-id.ts @@ -142,16 +142,6 @@ export class OrcaRuntimeWithWaitForLeafPtyId extends OrcaRuntimeWithRestoreLiveP } // Why: a leaf exists before its PTY spawns; a handle issued while ptyId is null gets invalidated on the next sync, so wait for a connected PTY. - protected countLeavesInTab(tabId: string): number { - let count = 0 - for (const leaf of this.leaves.values()) { - if (leaf.tabId === tabId) { - count++ - } - } - return count - } - protected resolveHandleForTab(tabId: string): string | null { for (const leaf of this.leaves.values()) { if (leaf.tabId === tabId && leaf.ptyId !== null) { diff --git a/src/main/runtime/runtime-notifier-contract.ts b/src/main/runtime/runtime-notifier-contract.ts index 97adc3feb07c..fa87d839cd5c 100644 --- a/src/main/runtime/runtime-notifier-contract.ts +++ b/src/main/runtime/runtime-notifier-contract.ts @@ -117,8 +117,10 @@ export type RuntimeNotifier = { baseVersion: string, content: string ): Promise - /** With leafId, drops that one split pane main already closed; without it, closes the tab. */ - closeTerminal(tabId: string, leafId?: string): void + /** Closes the whole tab. */ + closeTerminal(tabId: string): void + /** Drops one split pane main already closed; never closes its tab. */ + closeTerminalPane?(tabId: string, leafId: string): void closeTerminalTab?( tabId: string, options?: { localPtyTeardownOwnedExternally?: boolean; force?: boolean } diff --git a/src/main/runtime/terminal-surface-close.ts b/src/main/runtime/terminal-surface-close.ts index 5f6b84343ed1..4d9d94450191 100644 --- a/src/main/runtime/terminal-surface-close.ts +++ b/src/main/runtime/terminal-surface-close.ts @@ -1,47 +1,140 @@ import type { WorkspaceSessionState } from '../../shared/workspace-session-state-types' +import type { + TerminalLayoutSnapshot, + TerminalPaneLayoutNode +} from '../../shared/terminal-tab-types' +import type { TerminalSurfaceCloseTarget } from '../../shared/terminal-surface-close-target' import { closeTerminalTabInWorkspaceSession, type WorkspaceSessionTerminalTabCloseResult } from '../../shared/workspace-session-terminal-tab-close' -import { layoutContainsLeafId } from '../persistence/restoring-sessions/terminal-layout-normalization' -import { countTerminalLayoutLeaves } from './headless-terminal-split-layout' import { retireTerminalSurfaceFromPersistence } from './mobile-session-terminal-persistence-retirement' import { advanceTerminalTopologyRevision } from './workspace-session-terminal-membership-authority' +/** Where a pane close lands: its own removal, its tab's last pane, or a pane the copy lacks. */ +export type PaneCloseResolution = 'pane' | 'last-pane' | 'absent' + +export function collectTerminalLayoutLeafIds( + node: TerminalPaneLayoutNode | null | undefined +): string[] { + if (!node) { + return [] + } + if (node.type === 'leaf') { + return [node.leafId] + } + return [...collectTerminalLayoutLeafIds(node.first), ...collectTerminalLayoutLeafIds(node.second)] +} + /** - * The membership half of every explicit terminal close: removes a tab, or one leaf of a split + * Resolves a pane close against one copy of its tab's panes. `null` means the copy has no record + * of the tab; an empty list means it knows the tab but records no split, so it is one pane. + */ +export function resolvePaneClose( + leafIds: readonly string[] | null, + leafId: string +): PaneCloseResolution { + if (!leafIds) { + return 'absent' + } + if (leafIds.length === 0) { + return 'last-pane' + } + if (!leafIds.includes(leafId)) { + return 'absent' + } + return leafIds.length === 1 ? 'last-pane' : 'pane' +} + +/** Every copy of a tab's panes main can read when it resolves a close it started. */ +export type TerminalCloseLayoutCopies = { + /** The desktop renderer lists the tab, so it owns the tab's panes. */ + rendererListsTab: boolean + /** The tab's rows in the published session snapshot. */ + snapshotRows: readonly { leafId: string; parentLayout?: TerminalLayoutSnapshot }[] + /** The tab's panes in the renderer-published runtime graph. */ + graphLeafIds: readonly string[] + sessionLayout: TerminalLayoutSnapshot | undefined + sessionListsTab: boolean +} + +/** Reads the panes from whoever owns the tab's layout; `null` means no copy records the tab. */ +function readLayoutOwnerLeafIds(copies: TerminalCloseLayoutCopies): string[] | null { + const publishedLayout = copies.snapshotRows.find((row) => row.parentLayout)?.parentLayout + const published = publishedLayout ? collectTerminalLayoutLeafIds(publishedLayout.root) : null + if (copies.rendererListsTab) { + // Why: main's saved layout lacks a renderer split whose PTY binding has not committed yet; + // the published layout outranks the graph, which relay recovery can leave with stale panes. + return published ?? [...copies.graphLeafIds] + } + if (copies.sessionLayout) { + return collectTerminalLayoutLeafIds(copies.sessionLayout.root) + } + if (published) { + return published + } + if (copies.snapshotRows.length > 0) { + return copies.snapshotRows.map((row) => row.leafId) + } + return copies.sessionListsTab ? [] : null +} + +/** + * The only place main turns a pane close into its tab's close: `last-pane` sends callers down + * the tab path (and its renderer pin guard); anything else closes that pane or nothing. + * D1 (main as the single layout writer) collapses the owner read to main's session layout alone. + */ +export function resolveTerminalCloseTarget( + target: TerminalSurfaceCloseTarget, + copies: TerminalCloseLayoutCopies +): PaneCloseResolution | 'tab' { + return target.kind === 'tab' + ? 'tab' + : resolvePaneClose(readLayoutOwnerLeafIds(copies), target.leafId) +} + +export type TerminalSurfaceCloseResult = WorkspaceSessionTerminalTabCloseResult & { + resolution: PaneCloseResolution | 'tab' +} + +/** + * The membership half of every explicit terminal close: removes a tab, or one pane of a split * tab, and advances the repo's topology revision so a stale renderer save cannot restore it. - * A leaf close never removes its tab: callers close the last pane with a tab close. + * A pane close only ever removes that pane; the resolution says why anything else was a no-op. */ export function closeTerminalSurfaceInWorkspaceSession( session: WorkspaceSessionState, worktreeId: string, - tabId: string, - options: { leafId?: string; force?: boolean } = {} -): WorkspaceSessionTerminalTabCloseResult { - const layout = session.terminalLayoutsByTabId[tabId] - if (options.leafId) { - // Why: the exit may already have retired this leaf, leaving only live siblings to lose. - if ( - !layout || - countTerminalLayoutLeaves(layout.root) <= 1 || - !layoutContainsLeafId(layout.root, options.leafId) - ) { - return { session, ptyIdsToKill: [], closed: false, pinned: false } + target: TerminalSurfaceCloseTarget, + options: { force?: boolean } = {} +): TerminalSurfaceCloseResult { + if (target.kind === 'pane') { + const layout = session.terminalLayoutsByTabId[target.tabId] + const resolution = resolvePaneClose( + layout ? collectTerminalLayoutLeafIds(layout.root) : null, + target.leafId + ) + // Why: the exit may already have retired this pane, leaving only live siblings to lose. + if (!layout || resolution !== 'pane') { + return { session, ptyIdsToKill: [], closed: false, pinned: false, resolution } } - // The leaf's own binding is passed so the retirement's stale-binding fence always admits it. + // The pane's own binding is passed so the retirement's stale-binding fence always admits it. const retired = retireTerminalSurfaceFromPersistence(session, { worktreeId, - parentTabId: tabId, - leafId: options.leafId, - ptyId: layout.ptyIdsByLeafId?.[options.leafId] ?? '' + parentTabId: target.tabId, + leafId: target.leafId, + ptyId: layout.ptyIdsByLeafId?.[target.leafId] ?? '' }) - return { session: retired, ptyIdsToKill: [], closed: true, pinned: false } + return { session: retired, ptyIdsToKill: [], closed: true, pinned: false, resolution } } - const result = closeTerminalTabInWorkspaceSession(session, worktreeId, tabId, { + const result = closeTerminalTabInWorkspaceSession(session, worktreeId, target.tabId, { force: options.force }) - return result.closed - ? { ...result, session: advanceTerminalTopologyRevision(result.session, worktreeId) } - : result + return { + ...result, + ...(result.closed + ? { session: advanceTerminalTopologyRevision(result.session, worktreeId) } + : {}), + resolution: 'tab' + } } diff --git a/src/main/window/runtime-window-lifecycle.ts b/src/main/window/runtime-window-lifecycle.ts index 07eff2789238..142389099c0f 100644 --- a/src/main/window/runtime-window-lifecycle.ts +++ b/src/main/window/runtime-window-lifecycle.ts @@ -198,7 +198,8 @@ export function registerRuntimeWindowLifecycle( baseVersion, content }) as Promise, - closeTerminal: (tabId, leafId) => send('ui:closeTerminal', { tabId, leafId }), + closeTerminal: (tabId) => send('ui:closeTerminal', { kind: 'tab', tabId }), + closeTerminalPane: (tabId, leafId) => send('ui:closeTerminal', { kind: 'pane', tabId, leafId }), closeTerminalTab: (tabId, options) => requestTerminalTabCloseFromRenderer(mainWindow, tabId, options), sleepWorktree: (worktreeId) => send('ui:sleepWorktree', { worktreeId }), diff --git a/src/preload/api/ui-bridge-clipboard-and-window-controls.ts b/src/preload/api/ui-bridge-clipboard-and-window-controls.ts index dd45edb16ee4..80f2c2dd3830 100644 --- a/src/preload/api/ui-bridge-clipboard-and-window-controls.ts +++ b/src/preload/api/ui-bridge-clipboard-and-window-controls.ts @@ -10,6 +10,7 @@ import { type RichMarkdownContextMenuTableTarget } from '../../shared/rich-markdown-context-menu' import type { NativeFileDropPayload } from '../../shared/native-file-drop' +import type { TerminalSurfaceCloseTarget } from '../../shared/terminal-surface-close-target' import type { ClipboardImageThumbnail } from '../../shared/clipboard-image' import type { ReadClipboardTextOptions } from '../../shared/clipboard-text' import { subscribeNativeFileDrop } from '../preload-runtime-support' @@ -49,11 +50,9 @@ export const uiClipboardAndWindowControlsApi = { respondMobileMarkdownRequest: (response: RuntimeMobileMarkdownResponse): void => { ipcRenderer.send('ui:mobileMarkdownResponse', response) }, - onCloseTerminal: (callback: (data: { tabId: string; leafId?: string }) => void): (() => void) => { - const listener = ( - _event: Electron.IpcRendererEvent, - data: { tabId: string; leafId?: string } - ) => callback(data) + onCloseTerminal: (callback: (target: TerminalSurfaceCloseTarget) => void): (() => void) => { + const listener = (_event: Electron.IpcRendererEvent, target: TerminalSurfaceCloseTarget) => + callback(target) ipcRenderer.on('ui:closeTerminal', listener) return () => ipcRenderer.removeListener('ui:closeTerminal', listener) }, diff --git a/src/preload/api/ui-command-event-api.ts b/src/preload/api/ui-command-event-api.ts index a0bef9e23553..f6bb247bf91e 100644 --- a/src/preload/api/ui-command-event-api.ts +++ b/src/preload/api/ui-command-event-api.ts @@ -1,6 +1,7 @@ import type { MarkdownDocument } from '../../shared/filesystem-entry-types' import type { PersistedUIState } from '../../shared/persisted-ui-state-types' import type { TuiAgent } from '../../shared/tui-agent' +import type { TerminalSurfaceCloseTarget } from '../../shared/terminal-surface-close-target' import type { WorktreeDefaultTabsLaunch, WorktreeSetupLaunch, @@ -236,7 +237,7 @@ export type UiCommandEventApi = { ) => () => void onMobileMarkdownRequest: (callback: (request: RuntimeMobileMarkdownRequest) => void) => () => void respondMobileMarkdownRequest: (response: RuntimeMobileMarkdownResponse) => void - onCloseTerminal: (callback: (data: { tabId: string; leafId?: string }) => void) => () => void + onCloseTerminal: (callback: (target: TerminalSurfaceCloseTarget) => void) => () => void onTerminalTabCloseRequest: (callback: (request: TerminalTabCloseRequest) => void) => () => void respondTerminalTabClose: (response: TerminalTabCloseResponse) => void onSleepWorktree: (callback: (data: { worktreeId: string }) => void) => () => void diff --git a/src/preload/api/workspace-session-api.ts b/src/preload/api/workspace-session-api.ts index fb42ec3bd27b..434b3795df1d 100644 --- a/src/preload/api/workspace-session-api.ts +++ b/src/preload/api/workspace-session-api.ts @@ -4,6 +4,7 @@ import type { WorkspaceSessionState } from '../../shared/workspace-session-state-types' import type { ExecutionHostId } from '../../shared/execution-host' +import type { TerminalSurfaceCloseTarget } from '../../shared/terminal-surface-close-target' import type { RemoteWorkspaceChangedEvent, RemoteWorkspaceConnectedClient, @@ -19,11 +20,10 @@ export type WorkspaceSessionApi = { listHostIds: () => Promise set: (args: WorkspaceSessionState, hostId?: ExecutionHostId) => Promise patch: (args: WorkspaceSessionPatch, hostId?: ExecutionHostId) => Promise - /** Commits a terminal tab (or split pane, with leafId) close into main's membership. */ + /** Commits a terminal tab or split-pane close into main's membership. */ closeTerminalSurface: (args: { worktreeId: string - tabId: string - leafId?: string + target: TerminalSurfaceCloseTarget }) => Promise flush: () => Promise readTerminalScrollback: (args: { ref: string }) => string | null diff --git a/src/renderer/src/components/terminal-pane/pending-split-close.test.ts b/src/renderer/src/components/terminal-pane/pending-split-close.test.ts index edeb731ce78d..48843d39613d 100644 --- a/src/renderer/src/components/terminal-pane/pending-split-close.test.ts +++ b/src/renderer/src/components/terminal-pane/pending-split-close.test.ts @@ -199,7 +199,6 @@ it('commits the explicit split close in main by its leaf', async () => { p.actions.executeClosePane(1) expect(closeTerminalSurface).toHaveBeenCalledExactlyOnceWith({ worktreeId: 'workspace', - tabId: p.tabId, - leafId: p.leafId + target: { kind: 'pane', tabId: p.tabId, leafId: p.leafId } }) }) diff --git a/src/renderer/src/components/terminal-pane/use-terminal-pane-close-actions.ts b/src/renderer/src/components/terminal-pane/use-terminal-pane-close-actions.ts index c1adb8976413..bcdbd9b41b30 100644 --- a/src/renderer/src/components/terminal-pane/use-terminal-pane-close-actions.ts +++ b/src/renderer/src/components/terminal-pane/use-terminal-pane-close-actions.ts @@ -51,7 +51,7 @@ export function useTerminalPaneCloseActions(controller: TerminalPaneBindingContr clearSessionRestoredBannerForPane(paneId) const leafId = manager.getLeafId(paneId) if (leafId) { - commitTerminalSurfaceClose({ worktreeId, tabId, leafId }) + commitTerminalSurfaceClose(worktreeId, { kind: 'pane', tabId, leafId }) retireUnboundIpcTerminalPane({ getState: useAppStore.getState, tabId, diff --git a/src/renderer/src/hooks/ipc-events-close-routing-test-harness.ts b/src/renderer/src/hooks/ipc-events-close-routing-test-harness.ts index 371b145fa2e3..249e435b9a47 100644 --- a/src/renderer/src/hooks/ipc-events-close-routing-test-harness.ts +++ b/src/renderer/src/hooks/ipc-events-close-routing-test-harness.ts @@ -3,6 +3,7 @@ calls back out would duplicate them into all 4 specs. */ import type * as ReactModule from 'react' import { vi } from 'vitest' +import type { TerminalSurfaceCloseTarget } from '../../../shared/terminal-surface-close-target' export type RequestTabCloseListener = (data: { requestId: string @@ -12,7 +13,7 @@ export type RequestTabCloseListener = (data: { export type CloseActiveTabListener = (payload?: { sourceId: string }) => void export type CloseFloatingItemListener = (payload: { sourceId: string }) => void export type SelectFloatingIndexListener = (payload: { index: number }) => void -export type CloseTerminalListener = (data: { tabId: string; leafId?: string | null }) => void +export type CloseTerminalListener = (target: TerminalSurfaceCloseTarget) => void export type CloseSessionTabListener = (data: { tabId: string; worktreeId: string }) => void export type SessionTabCloseRequestListener = (data: { requestId: string diff --git a/src/renderer/src/hooks/ipc-events/mobile-terminal-close-ipc-bridge.ts b/src/renderer/src/hooks/ipc-events/mobile-terminal-close-ipc-bridge.ts index cd6e668ae9ec..43a7e5905585 100644 --- a/src/renderer/src/hooks/ipc-events/mobile-terminal-close-ipc-bridge.ts +++ b/src/renderer/src/hooks/ipc-events/mobile-terminal-close-ipc-bridge.ts @@ -52,12 +52,12 @@ export function registerMobileAndTerminalCloseIpcBridge( ) unsubs.push( - window.api.ui.onCloseTerminal(({ tabId, leafId }) => { - if (leafId != null) { - applyClosedTerminalLeafNotice(tabId, leafId) + window.api.ui.onCloseTerminal((target) => { + if (target.kind === 'pane') { + applyClosedTerminalLeafNotice(target.tabId, target.leafId) } else { // Why: the CLI/RPC caller is answered immediately, so it cannot wait on a modal. - closeTerminalTab(tabId, { skipRunningProcessConfirm: true }) + closeTerminalTab(target.tabId, { skipRunningProcessConfirm: true }) } }) ) diff --git a/src/renderer/src/hooks/useIpcEvents-close-routing-session-tabs.test.ts b/src/renderer/src/hooks/useIpcEvents-close-routing-session-tabs.test.ts index 5240ea803f7a..e22c6b41e0f9 100644 --- a/src/renderer/src/hooks/useIpcEvents-close-routing-session-tabs.test.ts +++ b/src/renderer/src/hooks/useIpcEvents-close-routing-session-tabs.test.ts @@ -92,7 +92,7 @@ describe('useIpcEvents browser tab close routing', () => { getState: () => ({}) }) - closeTerminalListenerRef.current?.({ tabId: 'terminal-1' }) + closeTerminalListenerRef.current?.({ kind: 'tab', tabId: 'terminal-1' }) // The CLI/RPC caller is answered immediately, so this close must never raise a modal. expect(closeTerminalTabMock).toHaveBeenCalledWith('terminal-1', { diff --git a/src/renderer/src/store/terminals/terminal-surface-close-intent.ts b/src/renderer/src/store/terminals/terminal-surface-close-intent.ts index 6b231449f427..0ee2d5aead42 100644 --- a/src/renderer/src/store/terminals/terminal-surface-close-intent.ts +++ b/src/renderer/src/store/terminals/terminal-surface-close-intent.ts @@ -1,12 +1,15 @@ +import type { TerminalSurfaceCloseTarget } from '../../../../shared/terminal-surface-close-target' + /** Commits a terminal tab or split-pane close in main, which owns membership: a renderer save * cannot shrink it, so without this the close would ride on the PTY exit. */ -export function commitTerminalSurfaceClose(args: { - worktreeId: string - tabId: string - leafId?: string -}): void { +export function commitTerminalSurfaceClose( + worktreeId: string, + target: TerminalSurfaceCloseTarget +): void { // Why optional: an older preload can linger through an in-place renderer reload. - void globalThis.window?.api?.session?.closeTerminalSurface?.(args)?.catch((error: unknown) => { - console.warn('[terminal-close] main did not commit the close', error) - }) + void globalThis.window?.api?.session + ?.closeTerminalSurface?.({ worktreeId, target }) + ?.catch((error: unknown) => { + console.warn('[terminal-close] main did not commit the close', error) + }) } diff --git a/src/renderer/src/store/terminals/terminal-tab-close-intent.test.ts b/src/renderer/src/store/terminals/terminal-tab-close-intent.test.ts index cf10e3fec9d7..31ec06be2cdc 100644 --- a/src/renderer/src/store/terminals/terminal-tab-close-intent.test.ts +++ b/src/renderer/src/store/terminals/terminal-tab-close-intent.test.ts @@ -62,7 +62,7 @@ describe('closeTab close intent', () => { expect(mockApi.pty.kill).toHaveBeenCalledWith(SSH_PTY) expect(closeTerminalSurface).toHaveBeenCalledWith({ worktreeId: SSH_WORKTREE, - tabId: 'ssh-tab' + target: { kind: 'tab', tabId: 'ssh-tab' } }) }) diff --git a/src/renderer/src/store/terminals/terminal-tab-close.ts b/src/renderer/src/store/terminals/terminal-tab-close.ts index ee5f5255838a..4d27d680afdf 100644 --- a/src/renderer/src/store/terminals/terminal-tab-close.ts +++ b/src/renderer/src/store/terminals/terminal-tab-close.ts @@ -250,7 +250,7 @@ export function createTerminalTabCloseActions( } }) if (retiresSession && closingWorktreeId && opts?.remoteCloseOwnedByHost !== true) { - commitTerminalSurfaceClose({ worktreeId: closingWorktreeId, tabId }) + commitTerminalSurfaceClose(closingWorktreeId, { kind: 'tab', tabId }) } // Why shared with the paired snapshot apply: every path that removes a tab owes it the same sweep, and a second copy of the list is how one path silently misses a new entry. sweepRetiredTerminalTabState(get(), tabId, closingWorktreeId) diff --git a/src/shared/terminal-surface-close-target.ts b/src/shared/terminal-surface-close-target.ts new file mode 100644 index 000000000000..39624d063405 --- /dev/null +++ b/src/shared/terminal-surface-close-target.ts @@ -0,0 +1,28 @@ +/** What an explicit terminal close removes. A pane close never stands in for its tab. */ +export type TerminalSurfaceCloseTarget = + | { kind: 'tab'; tabId: string } + | { kind: 'pane'; tabId: string; leafId: string } + +export type TerminalPaneCloseTarget = Extract + +function readNonEmptyString(value: object, key: string): string | null { + const field: unknown = Reflect.get(value, key) + return typeof field === 'string' && field.length > 0 ? field : null +} + +/** Validates a close target that crossed a process boundary; anything malformed is rejected. */ +export function parseTerminalSurfaceCloseTarget(value: unknown): TerminalSurfaceCloseTarget | null { + if (typeof value !== 'object' || value === null) { + return null + } + const kind: unknown = Reflect.get(value, 'kind') + const tabId = readNonEmptyString(value, 'tabId') + if (!tabId) { + return null + } + if (kind === 'tab') { + return { kind, tabId } + } + const leafId = readNonEmptyString(value, 'leafId') + return kind === 'pane' && leafId ? { kind, tabId, leafId } : null +} From 25e31cb88eae0361190e5bf1a6bd5aea3c65d4ba Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 25 Sep 2026 19:28:13 -0700 Subject: [PATCH 07/15] fix(cli): an unverifiable stop says the close happened `orca terminal close` still exits 1 when the process stop cannot be verified, but its message now says the terminal was closed and names the host's reason, instead of "close failed". It promises that the kill retries on reconnect only when the SSH relay itself never answered the stop, the one case a recorded kill order backs. --- src/cli/handlers/terminal-close.ts | 20 ++++++--- src/cli/handlers/terminal.test.ts | 72 +++++++++++++++++------------- src/cli/terminal-format.test.ts | 16 +++++++ src/cli/terminal-format.ts | 4 +- src/shared/pty-liveness-verdict.ts | 15 +++++++ 5 files changed, 86 insertions(+), 41 deletions(-) diff --git a/src/cli/handlers/terminal-close.ts b/src/cli/handlers/terminal-close.ts index 5ba8a25b64a1..58fe6267218c 100644 --- a/src/cli/handlers/terminal-close.ts +++ b/src/cli/handlers/terminal-close.ts @@ -6,6 +6,7 @@ import type { CommandHandler } from '../dispatch' import { formatTerminalClose, reportCliError, printResult } from '../format' import { RuntimeClientError } from '../runtime-client' import { getRequiredWorktreeSelector, getTerminalHandle } from '../selectors' +import { describeUnconfirmedStopWithRetry } from '../../shared/pty-liveness-verdict' /** A false stop receipt is an error only when the host supplied a liveness verdict. */ function terminalCloseFailure(close: RuntimeTerminalClose): RuntimeClientError | null { @@ -13,14 +14,19 @@ function terminalCloseFailure(close: RuntimeTerminalClose): RuntimeClientError | return null } - const verdict = close.ptyStopVerdict - const detail = - verdict === 'live' - ? 'The PTY is live.' - : `The PTY was not confirmed stopped: ${close.ptyStopReason ?? 'its host could not be reached'}.` + if (close.ptyStopVerdict === 'live') { + return new RuntimeClientError( + 'terminal_stop_live', + `Terminal ${close.handle} close failed to confirm the PTY stopped (live). The PTY is live.`, + { close } + ) + } + // Why: the close itself committed; only the process stop is unproven, so say which. return new RuntimeClientError( - verdict === 'live' ? 'terminal_stop_live' : 'terminal_stop_unverifiable', - `Terminal ${close.handle} close failed to confirm the PTY stopped (${verdict}). ${detail}`, + 'terminal_stop_unverifiable', + `Closed terminal ${close.handle}. ${describeUnconfirmedStopWithRetry( + close.ptyStopReason ?? 'its host could not be reached' + )}`, { close } ) } diff --git a/src/cli/handlers/terminal.test.ts b/src/cli/handlers/terminal.test.ts index 06df95f55a94..dfd2a618f0b8 100644 --- a/src/cli/handlers/terminal.test.ts +++ b/src/cli/handlers/terminal.test.ts @@ -42,40 +42,48 @@ describe('terminal close CLI', () => { expect(process.exitCode).toBeUndefined() }) - it('reports an unverifiable PTY stop as a failing JSON outcome', async () => { - process.exitCode = undefined - const close = { - handle: 'term-remote', - tabId: 'tab-1', - ptyKilled: false, - ptyStopVerdict: 'unverifiable' as const, - ptyStopReason: 'its SSH provider is no longer registered' - } - const call = vi.fn().mockResolvedValue({ - id: 'req-close', - ok: true, - result: { close }, - _meta: { runtimeId: 'runtime-1' } - }) - const log = vi.spyOn(console, 'log').mockImplementation(() => {}) + it.each([ + [ + 'its SSH provider is no longer registered', + 'Closed terminal term-remote. The PTY was not confirmed stopped: its SSH provider is no longer registered.' + ], + [ + 'Request "pty.shutdown" timed out after 14250ms', + 'Closed terminal term-remote. The PTY was not confirmed stopped: Request "pty.shutdown" timed out after 14250ms. The kill retries when the host reconnects.' + ] + ])( + 'reports an unverifiable stop (%s) as a committed close with exit code 1', + async (ptyStopReason, message) => { + process.exitCode = undefined + const close = { + handle: 'term-remote', + tabId: 'tab-1', + ptyKilled: false, + ptyStopVerdict: 'unverifiable' as const, + ptyStopReason + } + const call = vi.fn().mockResolvedValue({ + id: 'req-close', + ok: true, + result: { close }, + _meta: { runtimeId: 'runtime-1' } + }) + const log = vi.spyOn(console, 'log').mockImplementation(() => {}) - await TERMINAL_HANDLERS['terminal close']({ - flags: new Map([['terminal', close.handle]]), - client: { call } as unknown as RuntimeClient, - cwd: '/tmp/worktree', - json: true - }) + await TERMINAL_HANDLERS['terminal close']({ + flags: new Map([['terminal', close.handle]]), + client: { call } as unknown as RuntimeClient, + cwd: '/tmp/worktree', + json: true + }) - expect(JSON.parse(String(log.mock.calls[0]?.[0]))).toMatchObject({ - ok: false, - error: { - code: 'terminal_stop_unverifiable', - message: expect.stringContaining('unverifiable'), - data: { close } - } - }) - expect(process.exitCode).toBe(1) - }) + expect(JSON.parse(String(log.mock.calls[0]?.[0]))).toMatchObject({ + ok: false, + error: { code: 'terminal_stop_unverifiable', message, data: { close } } + }) + expect(process.exitCode).toBe(1) + } + ) it('reports a live PTY stop as a failing human outcome', async () => { process.exitCode = undefined diff --git a/src/cli/terminal-format.test.ts b/src/cli/terminal-format.test.ts index 294fbc09ceeb..670188a44e3c 100644 --- a/src/cli/terminal-format.test.ts +++ b/src/cli/terminal-format.test.ts @@ -57,6 +57,22 @@ describe('formatTerminalClose', () => { ) }) + it('promises the reconnect replay only for a stop the SSH relay never answered', () => { + expect( + formatTerminalClose({ + close: { + handle: 'term_remote', + tabId: 'tab-1', + ptyKilled: false, + ptyStopVerdict: 'unverifiable', + ptyStopReason: 'SSH connection lost, reconnecting...' + } + }) + ).toBe( + 'Closed terminal term_remote. The PTY was not confirmed stopped: SSH connection lost, reconnecting... The kill retries when the host reconnects.' + ) + }) + it('names a PTY known to be live', () => { expect( formatTerminalClose({ diff --git a/src/cli/terminal-format.ts b/src/cli/terminal-format.ts index 97e117b2229e..03012ec554f1 100644 --- a/src/cli/terminal-format.ts +++ b/src/cli/terminal-format.ts @@ -1,4 +1,4 @@ -import { PTY_LIVE_NOTE, describeUnconfirmedStop } from '../shared/pty-liveness-verdict' +import { PTY_LIVE_NOTE, describeUnconfirmedStopWithRetry } from '../shared/pty-liveness-verdict' import { describeTerminalWaitBlockedReason } from '../shared/terminal-wait-blocked-reason-legacy-alias' import { formatListingHostScope, type WithAnnotatedHostScope } from './omitted-host-scope-selectors' import type { @@ -254,7 +254,7 @@ function describePtyStop(close: RuntimeTerminalClose): string { return ` ${PTY_LIVE_NOTE}` } if (close.ptyStopVerdict === 'unverifiable') { - return ` ${describeUnconfirmedStop(close.ptyStopReason ?? 'its host could not be reached')}` + return ` ${describeUnconfirmedStopWithRetry(close.ptyStopReason ?? 'its host could not be reached')}` } return '' } diff --git a/src/shared/pty-liveness-verdict.ts b/src/shared/pty-liveness-verdict.ts index 0dd650161f38..fb6789468cc1 100644 --- a/src/shared/pty-liveness-verdict.ts +++ b/src/shared/pty-liveness-verdict.ts @@ -27,6 +27,21 @@ export function describeUnconfirmedStop(reason: string): string { return `The PTY was not confirmed stopped: ${endSentence(reason)}` } +// The SSH relay transport's own failure texts (ssh-channel-multiplexer.ts). A stop that failed +// this way is followed by a kill whose failure is recorded and replayed on the next handshake. +const UNDELIVERED_SSH_STOP_REASONS = [ + /^Request "pty\.shutdown" timed out after \d+ms$/u, + /^SSH connection lost, reconnecting/u +] + +/** The unconfirmed-stop sentence, plus the reconnect replay only where a kill order backs it. */ +export function describeUnconfirmedStopWithRetry(reason: string): string { + const retries = UNDELIVERED_SSH_STOP_REASONS.some((pattern) => pattern.test(reason.trim())) + return retries + ? `${describeUnconfirmedStop(reason)} The kill retries when the host reconnects.` + : describeUnconfirmedStop(reason) +} + /** Words a close whose PTY teardown was never confirmed, for a stop receipt. */ export function describeUnconfirmedAgentStop(close: { ptyStopVerdict?: 'live' | 'unverifiable' From 07496c14c112a6c72ab226b86d0c733c5e08a24e Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 25 Sep 2026 19:53:12 -0700 Subject: [PATCH 08/15] fix(terminal): a phone pane close commits even when its kill fails A paired client's close of one pane threw `terminal_close_failed` before committing anything when the controller reported the kill failed, so the pane stayed. The kill is now best-effort, as it is for a whole-tab close: the pane's removal always commits and the failure stays on the PTY's liveness verdict. --- ...-runtime-build-headless-mobile-session-browser-tabs.ts | 8 ++++---- .../orca-runtime-terminal-close-no-widening.test.ts | 6 ++++++ 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/src/main/runtime/orca-runtime-build-headless-mobile-session-browser-tabs.ts b/src/main/runtime/orca-runtime-build-headless-mobile-session-browser-tabs.ts index e4d2f3c894cd..c6e819cedb0d 100644 --- a/src/main/runtime/orca-runtime-build-headless-mobile-session-browser-tabs.ts +++ b/src/main/runtime/orca-runtime-build-headless-mobile-session-browser-tabs.ts @@ -174,11 +174,11 @@ export class OrcaRuntimeWithBuildHeadlessMobileSessionBrowserTabs extends OrcaRu worktreeId: string, tab: RuntimeMobileSessionTerminalTab ): void { + // Why best-effort, as for a tab: a failed kill must not keep a pane the user closed. const pty = this.findPtyForMobileTerminalTab(worktreeId, tab) - if (pty && this.ptyController?.kill(pty.ptyId) !== true) { - throw new Error('terminal_close_failed') - } - if (!pty && !this.tabs.has(tab.parentTabId) && tab.ptyId && parseAppSshPtyId(tab.ptyId)) { + if (pty) { + this.ptyController?.kill(pty.ptyId) + } else if (!this.tabs.has(tab.parentTabId) && tab.ptyId && parseAppSshPtyId(tab.ptyId)) { // Why: with no renderer to own the kill, a dormant SSH pane's durable id is its stop order. this.ptyController?.kill(tab.ptyId) } diff --git a/src/main/runtime/orca-runtime-terminal-close-no-widening.test.ts b/src/main/runtime/orca-runtime-terminal-close-no-widening.test.ts index 6b51be8e78ad..de1e0d5cfb0b 100644 --- a/src/main/runtime/orca-runtime-terminal-close-no-widening.test.ts +++ b/src/main/runtime/orca-runtime-terminal-close-no-widening.test.ts @@ -26,6 +26,7 @@ type Condition = | 'pinned' | 'no-saved-layout' | 'no-live-pty' + | 'kill-fails' /** The desktop renderer's split tab as it publishes it, with the given PTY bindings. */ function syncRendererSplit( @@ -106,6 +107,9 @@ function arrange(entry: Entry, condition: Condition): CloseContinuityHarness { // Graph without the leaf: the handle resolves through the PTY, as for a runtime-owned pane. harness.syncFixtureTabWithoutLeaf() } + if (condition === 'kill-fails') { + harness.kill.mockReturnValue(false) + } if (condition === 'stop-unconfirmed') { harness.setVerifiedStopResult(false) } else if (condition === 'stop-throws') { @@ -189,8 +193,10 @@ const rows: [Entry, Condition][] = [ ['phone-desktop', 'no-saved-layout'], // A pane with no live process record once sent a tab-level close notice. ['phone-desktop', 'no-live-pty'], + ['phone-desktop', 'kill-fails'], // A host with no desktop window once closed the whole tab for one pane. ['phone-headless', 'normal'], + ['phone-headless', 'kill-fails'], ['phone-headless', 'leaf-already-retired'], ['phone-headless', 'pinned'], ['phone-headless', 'no-saved-layout'] From a201c7904474af41d208d3434ecbe84a31675ae9 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 25 Sep 2026 20:08:33 -0700 Subject: [PATCH 09/15] fix(terminal): a pane close widens only when a copy shows it is the last pane The close resolver read an owner copy that records no panes as "the tab has one pane", so a CLI close of one pane of a split, addressed while the renderer listed the tab before publishing its panes, closed the whole tab. Every copy now counts only if it records at least one pane, read in the owner's order with the published rows as the last fallback, and a pane close widens only when a copy lists that pane as the tab's only one. An unsplit tab whose saved layout predates its pane still closes: its published row names the pane. --- ...ld-headless-mobile-session-browser-tabs.ts | 7 +- ...runtime-terminal-close-no-widening.test.ts | 63 ++++++++++++++ .../runtime/terminal-surface-close.test.ts | 85 +++++++++++++++++++ src/main/runtime/terminal-surface-close.ts | 46 ++++------ 4 files changed, 167 insertions(+), 34 deletions(-) create mode 100644 src/main/runtime/terminal-surface-close.test.ts diff --git a/src/main/runtime/orca-runtime-build-headless-mobile-session-browser-tabs.ts b/src/main/runtime/orca-runtime-build-headless-mobile-session-browser-tabs.ts index c6e819cedb0d..bcae463db0e5 100644 --- a/src/main/runtime/orca-runtime-build-headless-mobile-session-browser-tabs.ts +++ b/src/main/runtime/orca-runtime-build-headless-mobile-session-browser-tabs.ts @@ -131,7 +131,6 @@ export class OrcaRuntimeWithBuildHeadlessMobileSessionBrowserTabs extends OrcaRu worktreeId: string, target: TerminalSurfaceCloseTarget ): PaneCloseResolution | 'tab' { - const session = this.getWorkspaceSessionForWorktree(worktreeId) const graphLeafIds: string[] = [] for (const leaf of this.leaves.values()) { if (leaf.tabId === target.tabId) { @@ -144,10 +143,8 @@ export class OrcaRuntimeWithBuildHeadlessMobileSessionBrowserTabs extends OrcaRu (row) => row.type === 'terminal' && row.parentTabId === target.tabId ), graphLeafIds, - sessionLayout: session?.terminalLayoutsByTabId?.[target.tabId], - sessionListsTab: Object.values(session?.tabsByWorktree ?? {}).some((tabs) => - tabs.some((tab) => tab.id === target.tabId) - ) + sessionLayout: + this.getWorkspaceSessionForWorktree(worktreeId)?.terminalLayoutsByTabId?.[target.tabId] }) } diff --git a/src/main/runtime/orca-runtime-terminal-close-no-widening.test.ts b/src/main/runtime/orca-runtime-terminal-close-no-widening.test.ts index de1e0d5cfb0b..8a2bdc1ba24a 100644 --- a/src/main/runtime/orca-runtime-terminal-close-no-widening.test.ts +++ b/src/main/runtime/orca-runtime-terminal-close-no-widening.test.ts @@ -11,6 +11,8 @@ import { } from './__fixtures__/orca-runtime-terminal-close-continuity-fixtures' import { retireTerminalSurfaceFromPersistence } from './mobile-session-terminal-persistence-retirement' +const emptyLayout = { root: null, activeLeafId: null, expandedLeafId: null } + /** * Every explicit close of one pane, from every entry point, under every condition that has ever * widened one into a whole-tab close: the live sibling survives and no tab-level close goes out. @@ -27,6 +29,7 @@ type Condition = | 'no-saved-layout' | 'no-live-pty' | 'kill-fails' + | 'nothing-published' /** The desktop renderer's split tab as it publishes it, with the given PTY bindings. */ function syncRendererSplit( @@ -107,6 +110,32 @@ function arrange(entry: Entry, condition: Condition): CloseContinuityHarness { // Graph without the leaf: the handle resolves through the PTY, as for a runtime-owned pane. harness.syncFixtureTabWithoutLeaf() } + if (condition === 'nothing-published') { + // The renderer lists the tab before its panes register and before it publishes any row. + harness.runtime.syncWindowGraph(1, { + tabs: [ + { + tabId: TAB_ID, + worktreeId: WORKTREE_ID, + title: 'Fixture shell', + activeLeafId: null, + layout: null + } + ], + leaves: [], + mobileSessionTabs: [ + { + worktree: WORKTREE_ID, + publicationEpoch: 'renderer:nothing-published', + snapshotVersion: 4, + activeGroupId: null, + activeTabId: null, + activeTabType: null, + tabs: [] + } + ] + }) + } if (condition === 'kill-fails') { harness.kill.mockReturnValue(false) } @@ -187,6 +216,8 @@ const rows: [Entry, Condition][] = [ ['cli-pty', 'stop-unconfirmed'], ['cli-pty', 'stop-throws'], ['cli-pty', 'unbound-sibling'], + // An owner copy with no panes once read as "one pane", so the close took the whole tab. + ['cli-pty', 'nothing-published'], ['phone-desktop', 'normal'], ['phone-desktop', 'pinned'], ['phone-desktop', 'unbound-sibling'], @@ -250,6 +281,38 @@ describe("a close of a tab's last pane still closes the tab", () => { expect(harness.kill).toHaveBeenCalledWith(PTY_ID) }) + it.each([ + ['no saved layout', () => ({})], + ['a layout saved before its pane mounted', () => ({ [TAB_ID]: emptyLayout })] + ] as const)( + 'on a host with no desktop window, closes an unsplit tab with %s', + async (_name, layouts) => { + const harness = createHarness({ publishMobileSurface: true, registerPtyBacked: true }) + harness.runtime.setNotifier(null) + harness.syncEmptyGraph() + harness.editSession((session) => ({ ...session, terminalLayoutsByTabId: layouts() })) + + await harness.runtime.closeMobileSessionTab(`id:${WORKTREE_ID}`, `${TAB_ID}::${LEAF_ID}`, { + reason: 'user' + }) + + expect(harness.getSession().tabsByWorktree[WORKTREE_ID]).toEqual([]) + expect(harness.kill).toHaveBeenCalledWith(PTY_ID) + } + ) + + it('from the CLI by PTY, closes an unsplit tab whose renderer graph lists no panes yet', async () => { + const harness = createHarness({ publishMobileSurface: true, registerPtyBacked: true }) + harness.syncFixtureTabWithoutLeaf() + harness.setVerifiedStopResult(true) + harness.setCloseTerminalTabAction(() => harness.retirePersistedTab()) + + await closePane('cli-pty', harness) + + expect(harness.closeTerminalTab.mock.calls.map((call) => call[0])).toEqual([TAB_ID]) + expect(harness.closeTerminalPane).not.toHaveBeenCalled() + }) + it.each(['phone-desktop', 'cli-graph'] as const)( 'from %s, goes through the renderer tab close so its pin guard still runs', async (entry) => { diff --git a/src/main/runtime/terminal-surface-close.test.ts b/src/main/runtime/terminal-surface-close.test.ts new file mode 100644 index 000000000000..e149958ff340 --- /dev/null +++ b/src/main/runtime/terminal-surface-close.test.ts @@ -0,0 +1,85 @@ +import { describe, expect, it } from 'vitest' +import type { TerminalLayoutSnapshot } from '../../shared/terminal-tab-types' +import { + resolveTerminalCloseTarget, + type TerminalCloseLayoutCopies +} from './terminal-surface-close' + +const PANE = { kind: 'pane', tabId: 'tab-1', leafId: 'leaf-a' } as const + +function layout(...leafIds: string[]): TerminalLayoutSnapshot { + const [first, second] = leafIds + return { + root: + first === undefined + ? null + : second === undefined + ? { type: 'leaf', leafId: first } + : { + type: 'split', + direction: 'horizontal', + first: { type: 'leaf', leafId: first }, + second: { type: 'leaf', leafId: second } + }, + activeLeafId: first ?? null, + expandedLeafId: null + } +} + +function copies(overrides: Partial): TerminalCloseLayoutCopies { + return { + rendererListsTab: false, + snapshotRows: [], + graphLeafIds: [], + sessionLayout: undefined, + ...overrides + } +} + +describe('resolveTerminalCloseTarget', () => { + it('never widens a pane close when the owner copy records no panes', () => { + // A renderer tab registered before its panes, with nothing published for it yet. + expect(resolveTerminalCloseTarget(PANE, copies({ rendererListsTab: true }))).toBe('absent') + // A main-owned tab whose layout was saved before its pane mounted, and no other copy. + expect(resolveTerminalCloseTarget(PANE, copies({ sessionLayout: layout() }))).toBe('absent') + }) + + it("closes the tab only when a copy positively shows this pane as the tab's one pane", () => { + const cases: [string, Partial][] = [ + ['renderer graph', { rendererListsTab: true, graphLeafIds: ['leaf-a'] }], + [ + 'renderer rows with no layout or graph panes', + { rendererListsTab: true, snapshotRows: [{ leafId: 'leaf-a' }] } + ], + ['main session layout', { sessionLayout: layout('leaf-a') }], + [ + 'rows published for a main-owned tab whose saved layout is empty', + { sessionLayout: layout(), snapshotRows: [{ leafId: 'leaf-a', parentLayout: layout() }] } + ] + ] + for (const [name, overrides] of cases) { + expect([name, resolveTerminalCloseTarget(PANE, copies(overrides))]).toEqual([ + name, + 'last-pane' + ]) + } + }) + + it('reads past an empty copy to one that records the split', () => { + expect( + resolveTerminalCloseTarget( + PANE, + copies({ + sessionLayout: layout(), + snapshotRows: [{ leafId: 'leaf-a', parentLayout: layout('leaf-a', 'leaf-b') }] + }) + ) + ).toBe('pane') + }) + + it('treats a pane the owner copy lacks as absent', () => { + expect( + resolveTerminalCloseTarget(PANE, copies({ rendererListsTab: true, graphLeafIds: ['leaf-b'] })) + ).toBe('absent') + }) +}) diff --git a/src/main/runtime/terminal-surface-close.ts b/src/main/runtime/terminal-surface-close.ts index 4d9d94450191..c583e4c732bb 100644 --- a/src/main/runtime/terminal-surface-close.ts +++ b/src/main/runtime/terminal-surface-close.ts @@ -27,20 +27,14 @@ export function collectTerminalLayoutLeafIds( } /** - * Resolves a pane close against one copy of its tab's panes. `null` means the copy has no record - * of the tab; an empty list means it knows the tab but records no split, so it is one pane. + * Resolves a pane close against the panes one copy records. Only a copy that positively shows this + * pane as its tab's one pane widens the close; a copy recording no panes knows nothing about it. */ export function resolvePaneClose( leafIds: readonly string[] | null, leafId: string ): PaneCloseResolution { - if (!leafIds) { - return 'absent' - } - if (leafIds.length === 0) { - return 'last-pane' - } - if (!leafIds.includes(leafId)) { + if (!leafIds?.includes(leafId)) { return 'absent' } return leafIds.length === 1 ? 'last-pane' : 'pane' @@ -55,28 +49,22 @@ export type TerminalCloseLayoutCopies = { /** The tab's panes in the renderer-published runtime graph. */ graphLeafIds: readonly string[] sessionLayout: TerminalLayoutSnapshot | undefined - sessionListsTab: boolean } -/** Reads the panes from whoever owns the tab's layout; `null` means no copy records the tab. */ -function readLayoutOwnerLeafIds(copies: TerminalCloseLayoutCopies): string[] | null { - const publishedLayout = copies.snapshotRows.find((row) => row.parentLayout)?.parentLayout - const published = publishedLayout ? collectTerminalLayoutLeafIds(publishedLayout.root) : null - if (copies.rendererListsTab) { - // Why: main's saved layout lacks a renderer split whose PTY binding has not committed yet; - // the published layout outranks the graph, which relay recovery can leave with stale panes. - return published ?? [...copies.graphLeafIds] - } - if (copies.sessionLayout) { - return collectTerminalLayoutLeafIds(copies.sessionLayout.root) - } - if (published) { - return published - } - if (copies.snapshotRows.length > 0) { - return copies.snapshotRows.map((row) => row.leafId) - } - return copies.sessionListsTab ? [] : null +/** Reads the panes from whoever owns the tab's layout; `null` means no copy records any. */ +function readLayoutOwnerLeafIds(copies: TerminalCloseLayoutCopies): readonly string[] | null { + const published = + copies.snapshotRows + .map((row) => collectTerminalLayoutLeafIds(row.parentLayout?.root)) + .find((leafIds) => leafIds.length > 0) ?? [] + const rows = copies.snapshotRows.map((row) => row.leafId) + // Why: main's saved layout lacks a renderer split whose PTY binding has not committed yet; + // the published layout outranks the graph, which relay recovery can leave with stale panes. + const ownerCopies = copies.rendererListsTab + ? [published, copies.graphLeafIds, rows] + : [collectTerminalLayoutLeafIds(copies.sessionLayout?.root), published, rows] + // Why: a layout saved before its pane mounted (or a graph before its panes register) is empty. + return ownerCopies.find((leafIds) => leafIds.length > 0) ?? null } /** From 0a808aeda33b7ad439521383fc0ba855c10194f6 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 25 Sep 2026 20:20:05 -0700 Subject: [PATCH 10/15] fix(cli): promise a kill retry only when the host recorded the kill The close receipt inferred "the kill retries when the host reconnects" from the stop reason's text, which a new transport message or a reworded error would silently break. An explicit close now records the replayable kill order when its stop goes unconfirmed, before sending the follow-up kill (whose own failure is recorded only once its RPC settles), and reports that on the receipt as an optional `pendingKillRecorded`. The CLI promises the retry only from that field, so an older host, which never sends it, gets no promise. --- src/cli/handlers/terminal-close.ts | 6 +- src/cli/handlers/terminal.test.ts | 15 ++++- src/cli/terminal-format.test.ts | 24 +++---- src/cli/terminal-format.ts | 4 +- src/main/ipc/pty-ssh-undelivered-kill.test.ts | 43 ++++++++++++ src/main/ipc/pty/runtime/controller.ts | 7 ++ .../ipc/pty/runtime/undelivered-ssh-kill.ts | 25 +++++-- ...runtime-stop-explicitly-closed-tab-ptys.ts | 66 +++++++++++-------- ...-runtime-terminal-close-continuity.test.ts | 30 +++++++++ .../runtime-pty-controller-contract.ts | 3 + ...rminal-close-observed-exit-test-fixture.ts | 4 +- src/shared/pty-liveness-verdict.ts | 22 +++---- src/shared/runtime-terminal-contracts.ts | 3 + 13 files changed, 182 insertions(+), 70 deletions(-) diff --git a/src/cli/handlers/terminal-close.ts b/src/cli/handlers/terminal-close.ts index 58fe6267218c..9e65b2f5f473 100644 --- a/src/cli/handlers/terminal-close.ts +++ b/src/cli/handlers/terminal-close.ts @@ -6,7 +6,7 @@ import type { CommandHandler } from '../dispatch' import { formatTerminalClose, reportCliError, printResult } from '../format' import { RuntimeClientError } from '../runtime-client' import { getRequiredWorktreeSelector, getTerminalHandle } from '../selectors' -import { describeUnconfirmedStopWithRetry } from '../../shared/pty-liveness-verdict' +import { describeUnconfirmedCloseStop } from '../../shared/pty-liveness-verdict' /** A false stop receipt is an error only when the host supplied a liveness verdict. */ function terminalCloseFailure(close: RuntimeTerminalClose): RuntimeClientError | null { @@ -24,9 +24,7 @@ function terminalCloseFailure(close: RuntimeTerminalClose): RuntimeClientError | // Why: the close itself committed; only the process stop is unproven, so say which. return new RuntimeClientError( 'terminal_stop_unverifiable', - `Closed terminal ${close.handle}. ${describeUnconfirmedStopWithRetry( - close.ptyStopReason ?? 'its host could not be reached' - )}`, + `Closed terminal ${close.handle}. ${describeUnconfirmedCloseStop(close)}`, { close } ) } diff --git a/src/cli/handlers/terminal.test.ts b/src/cli/handlers/terminal.test.ts index dfd2a618f0b8..c0d9e8acda54 100644 --- a/src/cli/handlers/terminal.test.ts +++ b/src/cli/handlers/terminal.test.ts @@ -45,22 +45,31 @@ describe('terminal close CLI', () => { it.each([ [ 'its SSH provider is no longer registered', + false, 'Closed terminal term-remote. The PTY was not confirmed stopped: its SSH provider is no longer registered.' ], [ 'Request "pty.shutdown" timed out after 14250ms', + true, 'Closed terminal term-remote. The PTY was not confirmed stopped: Request "pty.shutdown" timed out after 14250ms. The kill retries when the host reconnects.' + ], + // An older host never reports a recorded kill, so the same reason promises nothing. + [ + 'Request "pty.shutdown" timed out after 14250ms', + false, + 'Closed terminal term-remote. The PTY was not confirmed stopped: Request "pty.shutdown" timed out after 14250ms.' ] ])( - 'reports an unverifiable stop (%s) as a committed close with exit code 1', - async (ptyStopReason, message) => { + 'reports an unverifiable stop (%s, kill recorded: %s) as a committed close with exit code 1', + async (ptyStopReason, pendingKillRecorded, message) => { process.exitCode = undefined const close = { handle: 'term-remote', tabId: 'tab-1', ptyKilled: false, ptyStopVerdict: 'unverifiable' as const, - ptyStopReason + ptyStopReason, + ...(pendingKillRecorded ? { pendingKillRecorded: true as const } : {}) } const call = vi.fn().mockResolvedValue({ id: 'req-close', diff --git a/src/cli/terminal-format.test.ts b/src/cli/terminal-format.test.ts index 670188a44e3c..ee0a985441ea 100644 --- a/src/cli/terminal-format.test.ts +++ b/src/cli/terminal-format.test.ts @@ -57,20 +57,20 @@ describe('formatTerminalClose', () => { ) }) - it('promises the reconnect replay only for a stop the SSH relay never answered', () => { - expect( - formatTerminalClose({ - close: { - handle: 'term_remote', - tabId: 'tab-1', - ptyKilled: false, - ptyStopVerdict: 'unverifiable', - ptyStopReason: 'SSH connection lost, reconnecting...' - } - }) - ).toBe( + it('promises the reconnect replay only when the host recorded the kill for it', () => { + const close = { + handle: 'term_remote', + tabId: 'tab-1', + ptyKilled: false, + ptyStopVerdict: 'unverifiable' as const, + ptyStopReason: 'SSH connection lost, reconnecting...' + } + expect(formatTerminalClose({ close: { ...close, pendingKillRecorded: true } })).toBe( 'Closed terminal term_remote. The PTY was not confirmed stopped: SSH connection lost, reconnecting... The kill retries when the host reconnects.' ) + expect(formatTerminalClose({ close })).toBe( + 'Closed terminal term_remote. The PTY was not confirmed stopped: SSH connection lost, reconnecting...' + ) }) it('names a PTY known to be live', () => { diff --git a/src/cli/terminal-format.ts b/src/cli/terminal-format.ts index 03012ec554f1..5a67a6413aae 100644 --- a/src/cli/terminal-format.ts +++ b/src/cli/terminal-format.ts @@ -1,4 +1,4 @@ -import { PTY_LIVE_NOTE, describeUnconfirmedStopWithRetry } from '../shared/pty-liveness-verdict' +import { PTY_LIVE_NOTE, describeUnconfirmedCloseStop } from '../shared/pty-liveness-verdict' import { describeTerminalWaitBlockedReason } from '../shared/terminal-wait-blocked-reason-legacy-alias' import { formatListingHostScope, type WithAnnotatedHostScope } from './omitted-host-scope-selectors' import type { @@ -254,7 +254,7 @@ function describePtyStop(close: RuntimeTerminalClose): string { return ` ${PTY_LIVE_NOTE}` } if (close.ptyStopVerdict === 'unverifiable') { - return ` ${describeUnconfirmedStopWithRetry(close.ptyStopReason ?? 'its host could not be reached')}` + return ` ${describeUnconfirmedCloseStop(close)}` } return '' } diff --git a/src/main/ipc/pty-ssh-undelivered-kill.test.ts b/src/main/ipc/pty-ssh-undelivered-kill.test.ts index d59d7d8543a1..910def8d844b 100644 --- a/src/main/ipc/pty-ssh-undelivered-kill.test.ts +++ b/src/main/ipc/pty-ssh-undelivered-kill.test.ts @@ -92,6 +92,7 @@ describe('undelivered SSH stops', () => { kill: (ptyId: string) => boolean stopAndWait: (ptyId: string, opts?: { keepHistory?: boolean }) => Promise markReversibleStops: (ptyIds: readonly string[]) => () => void + recordUnconfirmedStop: (ptyId: string) => boolean runtime: ReturnType['runtime'] } { const { runtime } = installController(handlers as never) @@ -107,11 +108,13 @@ describe('undelivered SSH stops', () => { kill: (ptyId: string) => boolean stopAndWait: (ptyId: string, opts?: { keepHistory?: boolean }) => Promise markReversibleStops: (ptyIds: readonly string[]) => () => void + recordUnconfirmedStop: (ptyId: string) => boolean } return { kill: controller.kill, stopAndWait: controller.stopAndWait, markReversibleStops: controller.markReversibleStops, + recordUnconfirmedStop: controller.recordUnconfirmedStop, runtime } } @@ -348,4 +351,44 @@ describe('undelivered SSH stops', () => { deletePtyOwnership('ssh:ssh-1@@pty-8') } }) + + // An explicit close records its order when the stop goes unconfirmed, before the follow-up kill, + // so its receipt can promise the reconnect retry from the record itself. + it("records an explicit close's unconfirmed stop and says so", () => { + const store = createKillStore() + setPtyOwnership(SCOPED_PTY_ID, 'ssh-1') + restorePtyIncarnation(SCOPED_PTY_ID, 'inc-g') + const { recordUnconfirmedStop } = install(store) + + try { + expect(recordUnconfirmedStop(SCOPED_PTY_ID)).toBe(true) + expect(store.recordSshRemotePtyKillIntent).toHaveBeenCalledWith( + 'ssh-1', + 'pty-7', + expect.objectContaining({ incarnationId: 'inc-g', attempts: 0 }) + ) + } finally { + deletePtyOwnership(SCOPED_PTY_ID) + } + }) + + it('reports no recorded order for a local or reversibly stopped PTY', () => { + const store = createKillStore() + setPtyOwnership('local-pty', null) + restorePtyIncarnation('local-pty', 'inc-h') + setPtyOwnership(SCOPED_PTY_ID, 'ssh-1') + restorePtyIncarnation(SCOPED_PTY_ID, 'inc-i') + const { recordUnconfirmedStop, markReversibleStops } = install(store) + const release = markReversibleStops([SCOPED_PTY_ID]) + + try { + expect(recordUnconfirmedStop('local-pty')).toBe(false) + expect(recordUnconfirmedStop(SCOPED_PTY_ID)).toBe(false) + expect(store.recordSshRemotePtyKillIntent).not.toHaveBeenCalled() + } finally { + release() + deletePtyOwnership('local-pty') + deletePtyOwnership(SCOPED_PTY_ID) + } + }) }) diff --git a/src/main/ipc/pty/runtime/controller.ts b/src/main/ipc/pty/runtime/controller.ts index 8512bc7c16bc..06ce1891b694 100644 --- a/src/main/ipc/pty/runtime/controller.ts +++ b/src/main/ipc/pty/runtime/controller.ts @@ -27,6 +27,7 @@ import { waitForRendererSerializerFromRuntimeController, writePtyFromRuntimeController } from './operations' +import { recordUnconfirmedExplicitSshStop } from './undelivered-ssh-kill' import { supportsForegroundProcessEvidenceFromRuntimeController } from './foreground-process-evidence-capability' import { listProcessesFromRuntimeController, @@ -58,6 +59,12 @@ export function installPtyRuntimeController(deps: PtyRuntimeControllerDeps): voi retireRejectedPtyFromRuntimeController(deps, ptyId, stopConfirmed), markReversibleStops: (ptyIds) => markReversibleStopsFromRuntimeController(deps, ptyIds), stopAndWait: (ptyId, opts) => stopAndWaitPtyFromRuntimeController(deps, ptyId, opts), + recordUnconfirmedStop: (ptyId) => + recordUnconfirmedExplicitSshStop({ + store: deps.store, + ptyId, + reversible: deps.reversibleStopOwnersByPtyId.has(ptyId) + }), getForegroundProcess: (ptyId) => getForegroundProcessFromRuntimeController(ptyId), inspectProcess: (ptyId, options) => inspectProcessFromRuntimeController(ptyId, options), confirmForegroundProcess: (ptyId) => confirmForegroundProcessFromRuntimeController(ptyId), diff --git a/src/main/ipc/pty/runtime/undelivered-ssh-kill.ts b/src/main/ipc/pty/runtime/undelivered-ssh-kill.ts index e41b16290979..00d23478eaac 100644 --- a/src/main/ipc/pty/runtime/undelivered-ssh-kill.ts +++ b/src/main/ipc/pty/runtime/undelivered-ssh-kill.ts @@ -1,5 +1,6 @@ import type { Store } from '../../../persistence' -import { ptyIncarnationById } from '../provider/ownership-state' +import { parseAppSshPtyId } from '../../../providers/ssh-pty-id' +import { ptyIncarnationById, ptyOwnership } from '../provider/ownership-state' import { getRelayPtyId } from '../provider/registry' export type UndeliveredSshPtyKill = { @@ -30,24 +31,38 @@ export type UndeliveredSshPtyKill = { * or worse, guessed at. * - **an id naming another connection**: `getRelayPtyId` throws on those, and this runs inside * promise `.catch` handlers where that would surface as an unhandled rejection. */ -export function recordUndeliveredSshPtyKill(args: UndeliveredSshPtyKill): void { +export function recordUndeliveredSshPtyKill(args: UndeliveredSshPtyKill): boolean { const { store, ptyId, connectionId } = args if (!store || !connectionId || args.reversible) { - return + return false } const incarnationId = args.incarnationId ?? ptyIncarnationById.get(ptyId) if (!incarnationId) { - return + return false } let relayPtyId: string try { relayPtyId = getRelayPtyId(connectionId, ptyId) } catch { - return + return false } store.recordSshRemotePtyKillIntent(connectionId, relayPtyId, { requestedAt: args.now ?? Date.now(), incarnationId, attempts: 0 }) + return true +} + +/** Records the replay order for an explicit close whose stop went unconfirmed, before its follow-up + * kill is sent, so the close receipt can promise the retry only when an order really exists. */ +export function recordUnconfirmedExplicitSshStop(args: { + store: Store | undefined + ptyId: string + reversible: boolean +}): boolean { + return recordUndeliveredSshPtyKill({ + ...args, + connectionId: ptyOwnership.get(args.ptyId) ?? parseAppSshPtyId(args.ptyId)?.connectionId + }) } diff --git a/src/main/runtime/orca-runtime-stop-explicitly-closed-tab-ptys.ts b/src/main/runtime/orca-runtime-stop-explicitly-closed-tab-ptys.ts index ee1bb6d8bb7f..d0bd6a1449d2 100644 --- a/src/main/runtime/orca-runtime-stop-explicitly-closed-tab-ptys.ts +++ b/src/main/runtime/orca-runtime-stop-explicitly-closed-tab-ptys.ts @@ -6,17 +6,23 @@ import type { RuntimeTerminalClose } from '../../shared/runtime-types' import type { RuntimePtyTabCloseAuthority } from './runtime-terminal-state-records' import { parsePaneKey } from '../../shared/stable-pane-id' +/** How an explicit close's stop of its addressed PTY ended. */ +type ExplicitCloseStop = { stopped: boolean; pendingKillRecorded: boolean } + +const NO_STOP: ExplicitCloseStop = { stopped: false, pendingKillRecorded: false } + export class OrcaRuntimeWithStopExplicitlyClosedTabPtys extends OrcaRuntimeWithFocusTerminal { protected async stopExplicitlyClosedTabPtys( ptyIds: readonly string[], addressedPtyId: string - ): Promise { - let addressedPtyStopped = false + ): Promise { + let addressedPtyStop = NO_STOP const deadlineMs = Date.now() + EXPLICIT_TERMINAL_CLOSE_STOP_TIMEOUT_MS for (const ptyId of ptyIds) { this.markPtyStopRequested(ptyId) const expectedIncarnationId = this.ptysById.get(ptyId)?.incarnationId let stopped = false + let pendingKillRecorded = false if (this.ptyController?.stopAndWait) { try { stopped = await this.ptyController.stopAndWait(ptyId, { deadlineMs }) @@ -41,6 +47,8 @@ export class OrcaRuntimeWithStopExplicitlyClosedTabPtys extends OrcaRuntimeWithF verdict?.status === 'unverifiable' && verdict.reason === SSH_PROVIDER_UNREGISTERED_REASON if (!providerAlreadyRetiredPty) { + // Why before the kill: its own failure is recorded only once its RPC settles. + pendingKillRecorded = this.ptyController.recordUnconfirmedStop?.(ptyId) === true this.ptyController.kill(ptyId) if (!verdict || verdict.status === 'live') { this.markPtyLivenessUnverifiable( @@ -54,35 +62,35 @@ export class OrcaRuntimeWithStopExplicitlyClosedTabPtys extends OrcaRuntimeWithF stopped = this.ptyController?.kill(ptyId) ?? false } if (ptyId === addressedPtyId) { - addressedPtyStopped = stopped + addressedPtyStop = { stopped, pendingKillRecorded } } } - return addressedPtyStopped + return addressedPtyStop } protected describeTerminalClose( handle: string, tabId: string, ptyId: string | null, - ptyKilled: boolean + stop: ExplicitCloseStop ): RuntimeTerminalClose { - if (ptyKilled || !ptyId) { - return { handle, tabId, ptyKilled } + const close: RuntimeTerminalClose = { + handle, + tabId, + ptyKilled: stop.stopped, + ...(stop.pendingKillRecorded ? { pendingKillRecorded: true as const } : {}) + } + if (stop.stopped || !ptyId) { + return close } const verdict = this.getPtyLivenessVerdict(ptyId) if (verdict?.status === 'unverifiable') { - return { - handle, - tabId, - ptyKilled, - ptyStopVerdict: 'unverifiable', - ptyStopReason: verdict.reason - } + return { ...close, ptyStopVerdict: 'unverifiable', ptyStopReason: verdict.reason } } if (verdict?.status === 'live') { - return { handle, tabId, ptyKilled, ptyStopVerdict: 'live' } + return { ...close, ptyStopVerdict: 'live' } } - return { handle, tabId, ptyKilled } + return close } async closeTerminal(handle: string): Promise { @@ -124,8 +132,8 @@ export class OrcaRuntimeWithStopExplicitlyClosedTabPtys extends OrcaRuntimeWithF } this.notifier.closeTerminal?.(tabId) } - const ptyKilled = await this.stopExplicitlyClosedTabPtys(ptyIdsToKill, pty.pty.ptyId) - return this.describeTerminalClose(handle, tabId, pty.pty.ptyId, ptyKilled) + const stop = await this.stopExplicitlyClosedTabPtys(ptyIdsToKill, pty.pty.ptyId) + return this.describeTerminalClose(handle, tabId, pty.pty.ptyId, stop) } if (closesTab && surface && ptyCloseAuthority && !this.tabs.has(surface.tab.parentTabId)) { try { @@ -138,20 +146,20 @@ export class OrcaRuntimeWithStopExplicitlyClosedTabPtys extends OrcaRuntimeWithF if (!(error instanceof Error) || error.message !== 'workspace_session_unavailable') { throw error } - const ptyKilled = await this.stopExplicitlyClosedTabPtys([pty.pty.ptyId], pty.pty.ptyId) + const stop = await this.stopExplicitlyClosedTabPtys([pty.pty.ptyId], pty.pty.ptyId) this.notifier?.closeTerminal(tabId) - return this.describeTerminalClose(handle, tabId, pty.pty.ptyId, ptyKilled) + return this.describeTerminalClose(handle, tabId, pty.pty.ptyId, stop) } - const ptyKilled = await this.stopExplicitlyClosedTabPtys([pty.pty.ptyId], pty.pty.ptyId) - return this.describeTerminalClose(handle, tabId, pty.pty.ptyId, ptyKilled) + const stop = await this.stopExplicitlyClosedTabPtys([pty.pty.ptyId], pty.pty.ptyId) + return this.describeTerminalClose(handle, tabId, pty.pty.ptyId, stop) } if (closesTab && !surface && pty.pty.tabId && this.notifier?.closeTerminalTab) { const ptyIdsToKill = this.getPtyIdsForExplicitTabClose(pty.pty.worktreeId, tabId) await this.notifier.closeTerminalTab(tabId, { localPtyTeardownOwnedExternally: true }) - const ptyKilled = await this.stopExplicitlyClosedTabPtys(ptyIdsToKill, pty.pty.ptyId) - return this.describeTerminalClose(handle, tabId, pty.pty.ptyId, ptyKilled) + const stop = await this.stopExplicitlyClosedTabPtys(ptyIdsToKill, pty.pty.ptyId) + return this.describeTerminalClose(handle, tabId, pty.pty.ptyId, stop) } - const ptyKilled = await this.stopExplicitlyClosedTabPtys([pty.pty.ptyId], pty.pty.ptyId) + const stop = await this.stopExplicitlyClosedTabPtys([pty.pty.ptyId], pty.pty.ptyId) if (!closesTab) { // Why: the pane's removal is this close's own commit, not a side effect of its exit. An // unconfirmed stop is unverifiable, never a reason to close the live siblings with it. @@ -173,7 +181,7 @@ export class OrcaRuntimeWithStopExplicitlyClosedTabPtys extends OrcaRuntimeWithF } else { this.notifier?.closeTerminal(tabId) } - return this.describeTerminalClose(handle, tabId, pty.pty.ptyId, ptyKilled) + return this.describeTerminalClose(handle, tabId, pty.pty.ptyId, stop) } this.assertGraphReady() const { leaf } = this.getLiveLeafForHandle(handle) @@ -187,15 +195,15 @@ export class OrcaRuntimeWithStopExplicitlyClosedTabPtys extends OrcaRuntimeWithF if (closesTab && this.notifier?.closeTerminalTab) { await this.notifier.closeTerminalTab(leaf.tabId, { localPtyTeardownOwnedExternally: true }) } - const ptyKilled = leaf.ptyId + const stop = leaf.ptyId ? await this.stopExplicitlyClosedTabPtys(ptyIdsToKill, leaf.ptyId) - : false + : NO_STOP if (!closesTab) { this.closeTerminalPane(leaf.worktreeId, paneTarget) } else if (!this.notifier?.closeTerminalTab) { this.notifier?.closeTerminal(leaf.tabId) } - return this.describeTerminalClose(handle, leaf.tabId, leaf.ptyId ?? null, ptyKilled) + return this.describeTerminalClose(handle, leaf.tabId, leaf.ptyId ?? null, stop) } async closeTerminalTab(handle: string): Promise { diff --git a/src/main/runtime/orca-runtime-terminal-close-continuity.test.ts b/src/main/runtime/orca-runtime-terminal-close-continuity.test.ts index 0f6237af5f2f..6ec08949dd9a 100644 --- a/src/main/runtime/orca-runtime-terminal-close-continuity.test.ts +++ b/src/main/runtime/orca-runtime-terminal-close-continuity.test.ts @@ -368,6 +368,36 @@ describe('terminal close and handle incarnation continuity', () => { expect(harness.kill).toHaveBeenCalledWith(PTY_ID) }) + it.each([true, false])( + 'promises a retry only when the stop recorded a replayable kill (recorded: %s)', + async (recorded) => { + const harness = createHarness() + const [{ handle }] = (await harness.runtime.listTerminals(`id:${WORKTREE_ID}`)).terminals + harness.setVerifiedStopResult(false) + const recordUnconfirmedStop = vi.fn(() => { + // The order must exist before the follow-up kill, whose own failure lands only later. + expect(harness.kill).not.toHaveBeenCalled() + return recorded + }) + const controller = harness.runtime['ptyController'] + if (!controller) { + throw new Error('fixture has no PTY controller') + } + Object.assign(controller, { recordUnconfirmedStop }) + + const closing = harness.runtime.closeTerminal(handle) + await vi.waitFor(() => expect(harness.closeTerminalTab).toHaveBeenCalled()) + harness.retirePersistedTab() + harness.acknowledged.resolve() + + const close = await closing + expect(recordUnconfirmedStop).toHaveBeenCalledWith(PTY_ID) + expect(harness.kill).toHaveBeenCalledWith(PTY_ID) + expect(close.ptyStopVerdict).toBe('unverifiable') + expect(close.pendingKillRecorded).toBe(recorded ? true : undefined) + } + ) + it('leaves a confirmed kill receipt free of any stop verdict', async () => { const harness = createHarness() const [{ handle }] = (await harness.runtime.listTerminals(`id:${WORKTREE_ID}`)).terminals diff --git a/src/main/runtime/runtime-pty-controller-contract.ts b/src/main/runtime/runtime-pty-controller-contract.ts index bb23548ae6f5..54aae2321ad5 100644 --- a/src/main/runtime/runtime-pty-controller-contract.ts +++ b/src/main/runtime/runtime-pty-controller-contract.ts @@ -107,6 +107,9 @@ export type RuntimePtyController = { opts?: { keepHistory?: boolean; deadlineMs?: number } ): Promise markReversibleStops?(ptyIds: readonly string[]): () => void + /** Durably records a kill order for an explicit close's unconfirmed stop, replayed when its SSH + * host reconnects. True only when an order was written; local PTYs have no later host to ask. */ + recordUnconfirmedStop?(ptyId: string): boolean getCwd?(ptyId: string): Promise getForegroundProcess(ptyId: string): Promise inspectProcess?( diff --git a/src/main/runtime/terminal-close-observed-exit-test-fixture.ts b/src/main/runtime/terminal-close-observed-exit-test-fixture.ts index 468508f896dd..628139923b0a 100644 --- a/src/main/runtime/terminal-close-observed-exit-test-fixture.ts +++ b/src/main/runtime/terminal-close-observed-exit-test-fixture.ts @@ -103,8 +103,8 @@ const BINDING = { } class ObservedExitRuntime extends OrcaRuntimeService { - closeControl(): Promise { - return this.stopExplicitlyClosedTabPtys([CONTROL_PTY_ID], CONTROL_PTY_ID) + async closeControl(): Promise { + return (await this.stopExplicitlyClosedTabPtys([CONTROL_PTY_ID], CONTROL_PTY_ID)).stopped } } diff --git a/src/shared/pty-liveness-verdict.ts b/src/shared/pty-liveness-verdict.ts index fb6789468cc1..ae1632572428 100644 --- a/src/shared/pty-liveness-verdict.ts +++ b/src/shared/pty-liveness-verdict.ts @@ -27,19 +27,15 @@ export function describeUnconfirmedStop(reason: string): string { return `The PTY was not confirmed stopped: ${endSentence(reason)}` } -// The SSH relay transport's own failure texts (ssh-channel-multiplexer.ts). A stop that failed -// this way is followed by a kill whose failure is recorded and replayed on the next handshake. -const UNDELIVERED_SSH_STOP_REASONS = [ - /^Request "pty\.shutdown" timed out after \d+ms$/u, - /^SSH connection lost, reconnecting/u -] - -/** The unconfirmed-stop sentence, plus the reconnect replay only where a kill order backs it. */ -export function describeUnconfirmedStopWithRetry(reason: string): string { - const retries = UNDELIVERED_SSH_STOP_REASONS.some((pattern) => pattern.test(reason.trim())) - return retries - ? `${describeUnconfirmedStop(reason)} The kill retries when the host reconnects.` - : describeUnconfirmedStop(reason) +/** A close's unconfirmed-stop sentence; it promises a retry only when the host recorded one. */ +export function describeUnconfirmedCloseStop(close: { + ptyStopReason?: string + pendingKillRecorded?: true +}): string { + const sentence = describeUnconfirmedStop(close.ptyStopReason ?? 'its host could not be reached') + return close.pendingKillRecorded === true + ? `${sentence} The kill retries when the host reconnects.` + : sentence } /** Words a close whose PTY teardown was never confirmed, for a stop receipt. */ diff --git a/src/shared/runtime-terminal-contracts.ts b/src/shared/runtime-terminal-contracts.ts index 235ef1e6b798..63adc2d67f82 100644 --- a/src/shared/runtime-terminal-contracts.ts +++ b/src/shared/runtime-terminal-contracts.ts @@ -322,6 +322,9 @@ export type RuntimeTerminalClose = { ptyKilled: boolean ptyStopVerdict?: 'live' | 'unverifiable' ptyStopReason?: string + /** The host durably recorded a kill order it replays when the PTY's SSH host reconnects. + * Older hosts never send it, so a client promises no retry without it. */ + pendingKillRecorded?: true } export type RuntimeTerminalWaitCondition = 'exit' | 'tui-idle' From 28613ffa347dd7509da94e9bad54171949eb6fbb Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 25 Sep 2026 20:30:32 -0700 Subject: [PATCH 11/15] test(pty): justify the controller cast the recorded-stop tests extend --- src/main/ipc/pty-ssh-undelivered-kill.test.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/ipc/pty-ssh-undelivered-kill.test.ts b/src/main/ipc/pty-ssh-undelivered-kill.test.ts index 910def8d844b..bf231fdc2350 100644 --- a/src/main/ipc/pty-ssh-undelivered-kill.test.ts +++ b/src/main/ipc/pty-ssh-undelivered-kill.test.ts @@ -104,6 +104,7 @@ describe('undelivered SSH stops', () => { undefined, store as never ) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: registerPtyHandlers installs the runtime PTY controller, which implements these members. const controller = runtime.setPtyController.mock.calls[0]?.[0] as { kill: (ptyId: string) => boolean stopAndWait: (ptyId: string, opts?: { keepHistory?: boolean }) => Promise From e17f7a6095bf33d0f3c65355f1f8da2c848f0a09 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 25 Sep 2026 22:11:56 -0700 Subject: [PATCH 12/15] fix(terminal): parse the close target with typed narrowing The low-evidence lint gate rejects Reflect.get and broad object parameters, which failed static analysis. Narrow with 'in' checks instead and cover the boundary parser's accept and reject cases. --- .../terminal-surface-close-target.test.ts | 28 +++++++++++++++++++ src/shared/terminal-surface-close-target.ts | 18 ++++++------ 2 files changed, 37 insertions(+), 9 deletions(-) create mode 100644 src/shared/terminal-surface-close-target.test.ts diff --git a/src/shared/terminal-surface-close-target.test.ts b/src/shared/terminal-surface-close-target.test.ts new file mode 100644 index 000000000000..54613ca879ba --- /dev/null +++ b/src/shared/terminal-surface-close-target.test.ts @@ -0,0 +1,28 @@ +import { describe, expect, it } from 'vitest' +import { parseTerminalSurfaceCloseTarget } from './terminal-surface-close-target' + +describe('parseTerminalSurfaceCloseTarget', () => { + it('keeps a well-formed tab or pane target', () => { + expect(parseTerminalSurfaceCloseTarget({ kind: 'tab', tabId: 't', leafId: 'x' })).toEqual({ + kind: 'tab', + tabId: 't' + }) + expect(parseTerminalSurfaceCloseTarget({ kind: 'pane', tabId: 't', leafId: 'l' })).toEqual({ + kind: 'pane', + tabId: 't', + leafId: 'l' + }) + }) + + it.each([ + null, + 'tab', + { tabId: 't' }, + { kind: 'tab', tabId: '' }, + { kind: 'pane', tabId: 't' }, + { kind: 'pane', tabId: 't', leafId: '' }, + { kind: 'leaf', tabId: 't', leafId: 'l' } + ])('rejects %j', (value) => { + expect(parseTerminalSurfaceCloseTarget(value)).toBeNull() + }) +}) diff --git a/src/shared/terminal-surface-close-target.ts b/src/shared/terminal-surface-close-target.ts index 39624d063405..d2b4d5fa6d2c 100644 --- a/src/shared/terminal-surface-close-target.ts +++ b/src/shared/terminal-surface-close-target.ts @@ -5,24 +5,24 @@ export type TerminalSurfaceCloseTarget = export type TerminalPaneCloseTarget = Extract -function readNonEmptyString(value: object, key: string): string | null { - const field: unknown = Reflect.get(value, key) - return typeof field === 'string' && field.length > 0 ? field : null +function isNonEmptyString(value: unknown): value is string { + return typeof value === 'string' && value.length > 0 } /** Validates a close target that crossed a process boundary; anything malformed is rejected. */ export function parseTerminalSurfaceCloseTarget(value: unknown): TerminalSurfaceCloseTarget | null { - if (typeof value !== 'object' || value === null) { + if (typeof value !== 'object' || value === null || !('kind' in value) || !('tabId' in value)) { return null } - const kind: unknown = Reflect.get(value, 'kind') - const tabId = readNonEmptyString(value, 'tabId') - if (!tabId) { + const { kind, tabId } = value + if (!isNonEmptyString(tabId)) { return null } if (kind === 'tab') { return { kind, tabId } } - const leafId = readNonEmptyString(value, 'leafId') - return kind === 'pane' && leafId ? { kind, tabId, leafId } : null + if (kind !== 'pane' || !('leafId' in value) || !isNonEmptyString(value.leafId)) { + return null + } + return { kind, tabId, leafId: value.leafId } } From 3e786908e87dd89df37908c5d7673a3addf03516 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 25 Sep 2026 23:50:10 -0700 Subject: [PATCH 13/15] fix(terminal): a desktop tab close is not refused by a split that bound while it waited The renderer has already removed and killed a tab it closes, so its close intent now skips the owner fence phone and CLI closes use. Before, a split pane whose binding was admitted between the close request and its durable write made main refuse the close, and the tab came back on the next launch whenever its processes did not exit. --- .../terminal-close-async-durability.test.ts | 33 +++++++++++++++++++ ...ld-headless-mobile-session-browser-tabs.ts | 15 +++++---- 2 files changed, 41 insertions(+), 7 deletions(-) diff --git a/src/main/persistence/loading-store/terminal-close-async-durability.test.ts b/src/main/persistence/loading-store/terminal-close-async-durability.test.ts index d446d3ac6ba2..4e74eea38ae5 100644 --- a/src/main/persistence/loading-store/terminal-close-async-durability.test.ts +++ b/src/main/persistence/loading-store/terminal-close-async-durability.test.ts @@ -177,3 +177,36 @@ it('commits nothing for a pane that restarted while its close waited for the wri expect(liveLeafIds()).toEqual([binding.leafId, siblingLeafId]) }) + +it('commits a renderer tab close whose split pane bound while the close waited for the writer', async () => { + const { authority, store, runtime, persistedLeafIds, liveLeafIds } = await closeFixture() + const gate = authority.pause() + const session = store.getWorkspaceSession() + store.setWorkspaceSession({ ...session, activeTabIdByWorktree: { [binding.worktreeId]: null } }) + const earlierWrite = store.flushPendingOrThrowAsync() + await gate.started.promise + // The split's binding is queued first, so it grows the tab after the close was asked. + const split = store.persistPtyBinding({ + ...binding, + leafId: siblingLeafId, + ptyId: 'sibling-pty', + incarnationId: 'eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee', + expectedSourceBinding: binding + }) + const closing = runtime.closeTerminalSurfaceFromRenderer(binding.worktreeId, { + kind: 'tab', + tabId: binding.tabId + }) + gate.finish.resolve() + await earlierWrite + await expect(split).resolves.toBe(true) + await expect(closing).resolves.toBeUndefined() + + expect(persistedLeafIds()).toEqual([]) + expect(liveLeafIds()).toEqual([]) + expect( + store + .getWorkspaceSession() + .tabsByWorktree[binding.worktreeId]?.some((tab) => tab.id === binding.tabId) + ).toBe(false) +}) diff --git a/src/main/runtime/orca-runtime-build-headless-mobile-session-browser-tabs.ts b/src/main/runtime/orca-runtime-build-headless-mobile-session-browser-tabs.ts index e39862edc6c3..502309e37eb9 100644 --- a/src/main/runtime/orca-runtime-build-headless-mobile-session-browser-tabs.ts +++ b/src/main/runtime/orca-runtime-build-headless-mobile-session-browser-tabs.ts @@ -113,14 +113,17 @@ export class OrcaRuntimeWithBuildHeadlessMobileSessionBrowserTabs extends OrcaRu protected async closeTerminalSurface( worktreeId: string, target: TerminalSurfaceCloseTarget, - options: { allowMissing?: boolean; force?: boolean } = {} + options: { allowMissing?: boolean; force?: boolean; closedByLayoutOwner?: boolean } = {} ): Promise { const store = this.store if (!store?.getWorkspaceSession || !store.setWorkspaceSession || !store.runDurableMutation) { throw new Error('workspace_session_unavailable') } + // Why: a tab its layout owner already removed has no newer owner; refusing would only strand it. const acknowledgeTabRetirement = - target.kind === 'tab' ? this.captureTerminalTabRetirement(worktreeId, target.tabId) : null + target.kind === 'tab' && !options.closedByLayoutOwner + ? this.captureTerminalTabRetirement(worktreeId, target.tabId) + : null let ptyIdsToKill: string[] = [] let refusal: Error | undefined try { @@ -149,11 +152,9 @@ export class OrcaRuntimeWithBuildHeadlessMobileSessionBrowserTabs extends OrcaRu } /** The desktop renderer's close intent: it already guarded, removed and killed; this only reports. */ - async closeTerminalSurfaceFromRenderer( - worktreeId: string, - target: TerminalSurfaceCloseTarget - ): Promise { - await this.closeTerminalSurface(worktreeId, target, { allowMissing: true, force: true }) + async closeTerminalSurfaceFromRenderer(worktreeId: string, target: TerminalSurfaceCloseTarget) { + const options = { allowMissing: true, force: true, closedByLayoutOwner: true } + await this.closeTerminalSurface(worktreeId, target, options) } /** Resolves a close main started against the copy of the tab's panes its layout owner holds. */ From b6db605cbc0835364ca7ad0168441bf619a513f2 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 25 Sep 2026 23:59:14 -0700 Subject: [PATCH 14/15] chore(terminal): note that closedByLayoutOwner goes away once main owns the terminal layout --- .../orca-runtime-build-headless-mobile-session-browser-tabs.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/runtime/orca-runtime-build-headless-mobile-session-browser-tabs.ts b/src/main/runtime/orca-runtime-build-headless-mobile-session-browser-tabs.ts index 502309e37eb9..e2e1e2337fcc 100644 --- a/src/main/runtime/orca-runtime-build-headless-mobile-session-browser-tabs.ts +++ b/src/main/runtime/orca-runtime-build-headless-mobile-session-browser-tabs.ts @@ -113,6 +113,7 @@ export class OrcaRuntimeWithBuildHeadlessMobileSessionBrowserTabs extends OrcaRu protected async closeTerminalSurface( worktreeId: string, target: TerminalSurfaceCloseTarget, + // closedByLayoutOwner goes away with D1, once main owns the terminal layout. options: { allowMissing?: boolean; force?: boolean; closedByLayoutOwner?: boolean } = {} ): Promise { const store = this.store From 1c2c599877719166391788dbf49a12b7c623767a Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 27 Sep 2026 11:50:46 -0700 Subject: [PATCH 15/15] test(terminal): reload the close-intent fixture through the SQLite profile store Main now requires a SQLite profile-state authority for a writable Store, so the save-and-reload close tests build and reopen their store through the shared SQLite test harness. --- .../runtime/orca-runtime-terminal-surface-close.test.ts | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/main/runtime/orca-runtime-terminal-surface-close.test.ts b/src/main/runtime/orca-runtime-terminal-surface-close.test.ts index 1415f09dae00..df39087c6888 100644 --- a/src/main/runtime/orca-runtime-terminal-surface-close.test.ts +++ b/src/main/runtime/orca-runtime-terminal-surface-close.test.ts @@ -5,6 +5,7 @@ import { afterEach, describe, expect, it } from 'vitest' import { makePaneKey } from '../../shared/stable-pane-id' import type { WorkspaceSessionState } from '../../shared/workspace-session-state-types' import { Store } from '../persistence/loading-store/store' +import { closeTestStores, createSqliteTestStore } from '../persistence-test-harness' import { OrcaRuntimeService } from './orca-runtime' import { LEAF_ID, @@ -62,7 +63,8 @@ function withPinnedTab(session: WorkspaceSessionState): WorkspaceSessionState { } const directories: string[] = [] -afterEach(() => { +afterEach(async () => { + await closeTestStores() for (const directory of directories.splice(0)) { rmSync(directory, { recursive: true, force: true }) } @@ -73,7 +75,7 @@ function createPersistedRuntime(session: WorkspaceSessionState) { const directory = mkdtempSync(join(tmpdir(), 'orca-surface-close-')) directories.push(directory) const dataFile = join(directory, 'orca-data.json') - const store = new Store({ dataFile }) + const store = createSqliteTestStore(Store, { dataFile }) store.addRepo({ id: REPO_ID, path: WORKTREE_PATH, @@ -90,7 +92,7 @@ function createPersistedRuntime(session: WorkspaceSessionState) { store.flush() store.freezeWrites() await store.waitForPendingWrite() - return new Store({ dataFile }).getWorkspaceSession() + return createSqliteTestStore(Store, { dataFile }).getWorkspaceSession() } } }