From aaca3a262b1fe5a6c3ab88dc1e1cfc5e00213716 Mon Sep 17 00:00:00 2001 From: jon Date: Thu, 16 Jul 2026 19:38:35 +0100 Subject: [PATCH 1/3] fix(runtime): prune stale headless session tabs --- src/main/runtime/orca-runtime.test.ts | 258 +++++++++++++++++++++++++- src/main/runtime/orca-runtime.ts | 145 ++++++++++++--- 2 files changed, 373 insertions(+), 30 deletions(-) diff --git a/src/main/runtime/orca-runtime.test.ts b/src/main/runtime/orca-runtime.test.ts index 50f196f26693..a784105636e7 100644 --- a/src/main/runtime/orca-runtime.test.ts +++ b/src/main/runtime/orca-runtime.test.ts @@ -58,7 +58,8 @@ import { import { HeadlessEmulator } from '../daemon/headless-emulator' import { HEADLESS_RUNTIME_WINDOW_ID, - type RuntimeMobileSessionTabsResult + type RuntimeMobileSessionTabsResult, + type RuntimeMobileSessionTabsSnapshot } from '../../shared/runtime-types' import type { TerminalSideEffectBatch } from '../../shared/terminal-side-effect-facts' import { @@ -873,6 +874,26 @@ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0- const HEADLESS_LEAF_ID = '11111111-1111-4111-8111-111111111111' const HEADLESS_SECOND_LEAF_ID = '22222222-2222-4222-8222-222222222222' +const DEAD_SERVE_SESSION_SNAPSHOT: RuntimeMobileSessionTabsSnapshot = { + worktree: TEST_WORKTREE_ID, + publicationEpoch: 'headless:stale', + snapshotVersion: 1, + activeGroupId: 'group-1', + activeTabId: `stale-tab::${HEADLESS_LEAF_ID}`, + activeTabType: 'terminal', + tabs: [ + { + type: 'terminal', + id: `stale-tab::${HEADLESS_LEAF_ID}`, + parentTabId: 'stale-tab', + leafId: HEADLESS_LEAF_ID, + title: 'Stale Agent', + ptyId: 'serve-stale-pty', + isActive: true + } + ] +} + function isOriginMainBaseRefProbe(args: string[]): boolean { return ( args[0] === 'rev-parse' && @@ -17965,6 +17986,233 @@ describe('OrcaRuntimeService', () => { ]) }) + it('prunes an unpersisted dead serve-owned tab omitted by the desktop graph', async () => { + const runtime = new OrcaRuntimeService(store) + runtime.setPtyController({ + write: () => true, + kill: () => true, + getForegroundProcess: async () => null, + listProcesses: async () => [] + }) + runtime.syncWindowGraph(1, { + tabs: [], + leaves: [], + mobileSessionTabs: [DEAD_SERVE_SESSION_SNAPSHOT] + }) + + const listed = await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`) + + expect(listed.tabs).toEqual([]) + }) + + it('does not materialize a dead serve-owned tab selected before a refresh', async () => { + const spawn = vi.fn() + const runtime = new OrcaRuntimeService(store) + runtime.setPtyController({ + spawn, + write: () => true, + kill: () => true, + getForegroundProcess: async () => null, + listProcesses: async () => [] + }) + runtime.syncWindowGraph(1, { + tabs: [], + leaves: [], + mobileSessionTabs: [DEAD_SERVE_SESSION_SNAPSHOT] + }) + + await expect( + runtime.activateMobileSessionTab(`id:${TEST_WORKTREE_ID}`, 'stale-tab') + ).rejects.toThrow('tab_not_found') + expect(spawn).not.toHaveBeenCalled() + }) + + it('treats a stale serve-owned tab closed after reconciliation as closed', async () => { + const runtime = new OrcaRuntimeService(store) + runtime.setPtyController({ + write: () => true, + kill: () => true, + getForegroundProcess: async () => null, + listProcesses: async () => [] + }) + runtime.syncWindowGraph(1, { + tabs: [], + leaves: [], + mobileSessionTabs: [DEAD_SERVE_SESSION_SNAPSHOT] + }) + + await expect( + runtime.closeMobileSessionTab(`id:${TEST_WORKTREE_ID}`, 'stale-tab') + ).resolves.toEqual({ closed: true }) + }) + + it('prunes dead serve-owned tabs from listAll results', async () => { + const runtime = new OrcaRuntimeService(store) + runtime.setPtyController({ + write: () => true, + kill: () => true, + getForegroundProcess: async () => null, + listProcesses: async () => [] + }) + runtime.syncWindowGraph(1, { + tabs: [], + leaves: [], + mobileSessionTabs: [DEAD_SERVE_SESSION_SNAPSHOT] + }) + + const snapshots = await runtime.listAllMobileSessionTabs() + + expect(snapshots.find((snapshot) => snapshot.worktree === TEST_WORKTREE_ID)?.tabs).toEqual([]) + }) + + it('publishes pruned serve-owned tabs during navigation-free worktree refresh', async () => { + const events: RuntimeMobileSessionTabsResult[] = [] + const runtime = new OrcaRuntimeService(store) + runtime.onMobileSessionTabsChanged((snapshot) => events.push(snapshot)) + runtime.setPtyController({ + write: () => true, + kill: () => true, + getForegroundProcess: async () => null, + listProcesses: async () => [] + }) + runtime.syncWindowGraph(1, { + tabs: [], + leaves: [], + mobileSessionTabs: [DEAD_SERVE_SESSION_SNAPSHOT] + }) + events.length = 0 + + await runtime.activateManagedWorktree(`id:${TEST_WORKTREE_ID}`, { notifyClients: false }) + + expect(events.at(-1)?.tabs).toEqual([]) + }) + + it('keeps a serve-owned tab when its PTY is still live', async () => { + const runtime = new OrcaRuntimeService(store) + runtime.setPtyController({ + write: () => true, + kill: () => true, + getForegroundProcess: async () => null, + listProcesses: async () => [ + { id: 'serve-stale-pty', cwd: TEST_WORKTREE_PATH, title: 'Live Agent' } + ] + }) + runtime.syncWindowGraph(1, { + tabs: [], + leaves: [], + mobileSessionTabs: [DEAD_SERVE_SESSION_SNAPSHOT] + }) + + const listed = await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`) + + expect(listed.tabs).toContainEqual( + expect.objectContaining({ type: 'terminal', parentTabId: 'stale-tab' }) + ) + }) + + it('keeps a stale-looking tab when PTY liveness cannot be confirmed', async () => { + const runtime = new OrcaRuntimeService(store) + runtime.setPtyController({ + write: () => true, + kill: () => true, + getForegroundProcess: async () => null, + listProcesses: async () => { + throw new Error('controller unavailable') + } + }) + runtime.syncWindowGraph(1, { + tabs: [], + leaves: [], + mobileSessionTabs: [DEAD_SERVE_SESSION_SNAPSHOT] + }) + + const listed = await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`) + + expect(listed.tabs).toHaveLength(1) + }) + + it('does not prune a pinned headless tab automatically', async () => { + const runtime = new OrcaRuntimeService(store) + runtime.setPtyController({ + write: () => true, + kill: () => true, + getForegroundProcess: async () => null, + listProcesses: async () => [] + }) + runtime.syncWindowGraph(1, { + tabs: [], + leaves: [], + mobileSessionTabs: [ + { + ...DEAD_SERVE_SESSION_SNAPSHOT, + tabs: DEAD_SERVE_SESSION_SNAPSHOT.tabs.map((tab) => ({ ...tab, isPinned: true })) + } + ] + }) + + const listed = await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`) + + expect(listed.tabs).toHaveLength(1) + }) + + it('prunes only the dead serve-owned parent from a mixed snapshot', async () => { + const liveParentTabId = 'live-tab' + const liveLeafId = HEADLESS_SECOND_LEAF_ID + const livePtyId = 'live-renderer-pty' + const stale = DEAD_SERVE_SESSION_SNAPSHOT + const runtime = new OrcaRuntimeService(store) + runtime.setPtyController({ + write: () => true, + kill: () => true, + getForegroundProcess: async () => null, + listProcesses: async () => [{ id: livePtyId, cwd: TEST_WORKTREE_PATH, title: 'Live' }] + }) + runtime.syncWindowGraph(1, { + tabs: [ + { + tabId: liveParentTabId, + worktreeId: TEST_WORKTREE_ID, + title: 'Live', + activeLeafId: liveLeafId, + layout: null + } + ], + leaves: [ + { + tabId: liveParentTabId, + worktreeId: TEST_WORKTREE_ID, + leafId: liveLeafId, + paneRuntimeId: 2, + ptyId: livePtyId, + paneTitle: 'Live' + } + ], + mobileSessionTabs: [ + { + ...stale, + tabs: [ + ...stale.tabs, + { + type: 'terminal', + id: `${liveParentTabId}::${liveLeafId}`, + parentTabId: liveParentTabId, + leafId: liveLeafId, + title: 'Live', + ptyId: livePtyId, + isActive: false + } + ] + } + ] + }) + + const listed = await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`) + + expect(listed.tabs).toEqual([ + expect.objectContaining({ type: 'terminal', parentTabId: liveParentTabId }) + ]) + }) + it('publishes laptop-created remote runtime terminals to phone session tabs', async () => { const spawn = vi.fn().mockResolvedValue({ id: 'laptop-created-pty' }) const runtime = new OrcaRuntimeService(store) @@ -20288,6 +20536,7 @@ describe('OrcaRuntimeService', () => { ) const kill = vi.fn(() => true) const closeTerminal = vi.fn() + const closeTerminalTab = vi.fn() const runtime = new OrcaRuntimeService(runtimeStore as never) runtime.setPtyController({ write: () => true, @@ -20295,9 +20544,9 @@ describe('OrcaRuntimeService', () => { getForegroundProcess: async () => null, listProcesses: async () => [] }) - // Why: an attached renderer means closeTerminal exists, so the close goes - // down the renderer-attached path that historically leaked serve-owned tabs. - runtime.setNotifier({ closeTerminal } as never) + // Why: even with the durable renderer close available, serve-owned state + // must be removed by the runtime that owns its persisted PTY binding. + runtime.setNotifier({ closeTerminal, closeTerminalTab } as never) runtime.syncWindowGraph(1, { tabs: [ { @@ -20328,6 +20577,7 @@ describe('OrcaRuntimeService', () => { expect(getSession().terminalLayoutsByTabId['host-tab']).toBeUndefined() // Best-effort renderer notify so no adopted pane is left dead. expect(closeTerminal).toHaveBeenCalledWith('host-tab') + expect(closeTerminalTab).not.toHaveBeenCalled() }) it('delegates a renderer-owned daemon-session (worktreeId@@uuid) local terminal to the renderer', async () => { diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index da1bbfbe603c..a97c2f1cfb8f 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -3397,19 +3397,20 @@ export class OrcaRuntimeService { async listMobileSessionTabs(worktreeSelector: string): Promise { const explicitWorktreeId = this.getValidatedExplicitWorktreeIdSelector(worktreeSelector) if (explicitWorktreeId) { - this.hydrateHeadlessMobileSessionTabsFromWorkspaceSession(explicitWorktreeId) - await this.refreshMobileSessionPtyRecords() + await this.prepareMobileSessionTabsForWorktree(explicitWorktreeId) return this.getMobileSessionTabsForWorktree(explicitWorktreeId) } const worktree = await this.resolveWorktreeSelector(worktreeSelector) - this.hydrateHeadlessMobileSessionTabsFromWorkspaceSession(worktree.id) - await this.refreshMobileSessionPtyRecords() + await this.prepareMobileSessionTabsForWorktree(worktree.id) return this.getMobileSessionTabsForWorktree(worktree.id) } async listAllMobileSessionTabs(): Promise { this.hydrateHeadlessMobileSessionTabsFromWorkspaceSession() - await this.refreshMobileSessionPtyRecords() + const livePtyIds = await this.refreshMobileSessionPtyRecords() + for (const worktreeId of this.mobileSessionTabsByWorktree.keys()) { + this.reconcileDeadServeSessionTabs(worktreeId, livePtyIds) + } return [...this.mobileSessionTabsByWorktree.values()].map((snapshot) => this.toMobileSessionTabsResult(snapshot) ) @@ -4365,12 +4366,99 @@ export class OrcaRuntimeService { } } - private async refreshMobileSessionPtyRecords(): Promise { + private async refreshMobileSessionPtyRecords(): Promise | null> { if (!this.ptyController?.listProcesses) { - return + return null } const resolvedWorktrees = await this.listResolvedWorktrees() - await this.refreshPtyWorktreeRecordsFromController(resolvedWorktrees) + return this.refreshPtyWorktreeRecordsFromController(resolvedWorktrees) + } + + private async prepareMobileSessionTabsForWorktree( + worktreeId: string, + options: { allowAttachedWindow?: boolean } = {} + ): Promise { + this.hydrateHeadlessMobileSessionTabsFromWorkspaceSession(worktreeId, options) + const livePtyIds = await this.refreshMobileSessionPtyRecords() + this.reconcileDeadServeSessionTabs(worktreeId, livePtyIds) + } + + private reconcileDeadServeSessionTabs( + worktreeId: string, + livePtyIds: ReadonlySet | null + ): void { + if (!livePtyIds || this.authoritativeWindowId === null || this.graphStatus !== 'ready') { + return + } + const snapshot = this.mobileSessionTabsByWorktree.get(worktreeId) + if (!snapshot) { + return + } + const persistedParentIds = new Set( + (this.store?.getWorkspaceSession?.()?.tabsByWorktree[worktreeId] ?? []).map((tab) => tab.id) + ) + const terminalTabsByParent = new Map() + for (const tab of snapshot.tabs) { + if (tab.type !== 'terminal') { + continue + } + const siblings = terminalTabsByParent.get(tab.parentTabId) + if (siblings) { + siblings.push(tab) + } else { + terminalTabsByParent.set(tab.parentTabId, [tab]) + } + } + const deadParentIds = new Set() + for (const [parentTabId, tabs] of terminalTabsByParent) { + if ( + this.tabs.has(parentTabId) || + persistedParentIds.has(parentTabId) || + tabs.some((tab) => tab.isPinned === true) || + this.pendingMobileTerminalCreatesByKey.has(`${worktreeId}::${parentTabId}`) + ) { + continue + } + const ptyIds = new Set( + tabs.flatMap((tab) => [ + ...(tab.ptyId ? [tab.ptyId] : []), + ...Object.values(tab.parentLayout?.ptyIdsByLeafId ?? {}).filter( + (ptyId): ptyId is string => typeof ptyId === 'string' + ) + ]) + ) + if ( + ptyIds.size > 0 && + [...ptyIds].every((ptyId) => this.isServeOwnedPtyId(ptyId) && !livePtyIds.has(ptyId)) + ) { + deadParentIds.add(parentTabId) + } + } + if (deadParentIds.size === 0) { + return + } + const tabs = snapshot.tabs.filter( + (tab) => tab.type !== 'terminal' || !deadParentIds.has(tab.parentTabId) + ) + const active = tabs.find((tab) => tab.id === snapshot.activeTabId) ?? tabs[0] ?? null + const nextSnapshot: RuntimeMobileSessionTabsSnapshot = { + ...snapshot, + // Why: the desktop graph, durable session, and successful PTY listing all + // agree these serve-owned parents no longer exist. + publicationEpoch: `headless:pruned:${Date.now().toString(36)}`, + snapshotVersion: snapshot.snapshotVersion + 1, + activeTabId: active?.id ?? null, + activeTabType: active?.type ?? null, + tabGroups: this.buildHeadlessMobileSessionTabGroups( + worktreeId, + tabs, + active, + snapshot.tabGroups + ), + tabs + } + this.mobileSessionTabsByWorktree.set(worktreeId, nextSnapshot) + this.emitMobileSessionTabsSnapshot(nextSnapshot) } async activateMobileSessionTab( @@ -4382,8 +4470,7 @@ export class OrcaRuntimeService { const explicitWorktreeId = this.getValidatedExplicitWorktreeIdSelector(worktreeSelector) const worktreeId = explicitWorktreeId ?? (await this.resolveWorktreeSelector(worktreeSelector)).id - this.hydrateHeadlessMobileSessionTabsFromWorkspaceSession(worktreeId) - await this.refreshMobileSessionPtyRecords() + await this.prepareMobileSessionTabsForWorktree(worktreeId) const snapshot = this.mobileSessionTabsByWorktree.get(worktreeId) const directTab = snapshot?.tabs.find((candidate) => candidate.id === tabId) const tab = leafId @@ -4659,7 +4746,15 @@ export class OrcaRuntimeService { const worktreeId = explicitWorktreeId ?? (await this.resolveWorktreeSelector(worktreeSelector)).id this.hydrateHeadlessMobileSessionTabsFromWorkspaceSession(worktreeId) - await this.refreshMobileSessionPtyRecords() + const tabBeforeReconciliation = this.mobileSessionTabsByWorktree + .get(worktreeId) + ?.tabs.find( + (candidate) => + candidate.id === tabId || + (candidate.type === 'terminal' && candidate.parentTabId === tabId) || + (candidate.type === 'browser' && candidate.browserWorkspaceId === tabId) + ) + await this.prepareMobileSessionTabsForWorktree(worktreeId) const snapshot = this.mobileSessionTabsByWorktree.get(worktreeId) const tab = snapshot?.tabs.find((candidate) => candidate.id === tabId) ?? @@ -4670,6 +4765,9 @@ export class OrcaRuntimeService { (candidate) => candidate.type === 'browser' && candidate.browserWorkspaceId === tabId ) if (!tab) { + if (tabBeforeReconciliation) { + return { closed: true } + } throw new Error('tab_not_found') } if (tab.type === 'terminal') { @@ -4677,8 +4775,16 @@ export class OrcaRuntimeService { (candidate) => candidate.type === 'terminal' && candidate.parentTabId === tab.parentTabId ).length const closingWholeParent = tab.id !== tabId || parentLeafCount <= 1 + // Why: runtime-owned headless parents are not guaranteed to exist in the + // renderer, so renderer acknowledgement can flush unchanged stale state. + if (closingWholeParent && this.isRuntimeOwnedHeadlessMobileTab(worktreeId, tab)) { + this.closeHeadlessMobileTerminalTab(worktreeId, snapshot!, tab) + this.notifier?.closeTerminal(tab.parentTabId) + this.store?.flushOrThrow?.() + return { closed: true } + } if (closingWholeParent && this.notifier?.closeTerminalTab) { - // Why: whole-tab close is a lifecycle transaction. The renderer reply + // Why: renderer-owned whole-tab close is a lifecycle transaction. The reply // arrives only after canonical retirement and a forced session flush. await this.notifier.closeTerminalTab(tab.parentTabId) return { closed: true } @@ -4688,18 +4794,6 @@ export class OrcaRuntimeService { this.store?.flushOrThrow?.() return { closed: true } } - // Why: a runtime-owned headless tab whose whole parent is being closed must - // be torn down authoritatively even with a renderer attached — kill the - // PTY, drop the persisted binding, and prune+emit — or syncMobileSessionTabs - // keeps republishing the "closed" tab with a live PTY. Best-effort notify the - // renderer too so any adopted pane closes (no dead pane). A single split leaf - // (exact id, multi-leaf parent) keeps the per-leaf path so siblings survive. - if (closingWholeParent && this.isRuntimeOwnedHeadlessMobileTab(worktreeId, tab)) { - this.closeHeadlessMobileTerminalTab(worktreeId, snapshot!, tab) - this.notifier?.closeTerminal(tab.parentTabId) - this.store?.flushOrThrow?.() - return { closed: true } - } if (tab.id === tabId) { const pty = this.findPtyForMobileTerminalTab(worktreeId, tab) if (pty) { @@ -14731,10 +14825,9 @@ export class OrcaRuntimeService { } else { // Why: mobile/web selection needs fresh session surfaces without forcing // every attached desktop renderer to navigate to the phone's workspace. - this.hydrateHeadlessMobileSessionTabsFromWorkspaceSession(worktree.id, { + await this.prepareMobileSessionTabsForWorktree(worktree.id, { allowAttachedWindow: true }) - await this.refreshMobileSessionPtyRecords() this.notifyMobileSessionTabsChanged(worktree.id) // Why: a phone open must also wake the worktree's slept agents (experimental // agent sleep). Only the host renderer holds the sleeping records + wake From b151bd454acf087205c8993f9cd1b5e2f07ce453 Mon Sep 17 00:00:00 2001 From: jon Date: Tue, 21 Jul 2026 12:01:54 +0100 Subject: [PATCH 2/3] fix(runtime): reconcile worktree status with live terminals --- src/main/index.ts | 4 + src/main/runtime/orca-runtime.test.ts | 125 +++++++++++++++++++++++++- src/main/runtime/orca-runtime.ts | 96 +++++++++++--------- 3 files changed, 180 insertions(+), 45 deletions(-) diff --git a/src/main/index.ts b/src/main/index.ts index 21c4a9ab51ef..60ff3c563a78 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -1837,6 +1837,10 @@ app.whenReady().then(async () => { // Why: hook-reported agent status is the same source the desktop sidebar // reads. worktree.ps pulls it at query time so mobile shows the same agents. getAgentStatusSnapshot: () => agentHookServer.getStatusSnapshot(), + // Why: terminal close must retire persisted hook rows too, or completed + // agents can reappear in worktree.ps after a restart with no live tab. + dropAgentStatusEntriesByTabPrefix: (tabId) => + agentHookServer.dropStatusEntriesByTabPrefix(tabId), // Why: source codex-home here (runs in BOTH window and serve modes) so the // aiVault.listSessions RPC includes managed-Codex sessions on remote/SSH // hosts; the window-only registerCoreHandlers path never runs under serve. diff --git a/src/main/runtime/orca-runtime.test.ts b/src/main/runtime/orca-runtime.test.ts index a784105636e7..ea019b243e0c 100644 --- a/src/main/runtime/orca-runtime.test.ts +++ b/src/main/runtime/orca-runtime.test.ts @@ -20537,7 +20537,10 @@ describe('OrcaRuntimeService', () => { const kill = vi.fn(() => true) const closeTerminal = vi.fn() const closeTerminalTab = vi.fn() - const runtime = new OrcaRuntimeService(runtimeStore as never) + const dropAgentStatusEntriesByTabPrefix = vi.fn() + const runtime = new OrcaRuntimeService(runtimeStore as never, undefined, { + dropAgentStatusEntriesByTabPrefix + }) runtime.setPtyController({ write: () => true, kill, @@ -20578,6 +20581,7 @@ describe('OrcaRuntimeService', () => { // Best-effort renderer notify so no adopted pane is left dead. expect(closeTerminal).toHaveBeenCalledWith('host-tab') expect(closeTerminalTab).not.toHaveBeenCalled() + expect(dropAgentStatusEntriesByTabPrefix).toHaveBeenCalledWith('host-tab') }) it('delegates a renderer-owned daemon-session (worktreeId@@uuid) local terminal to the renderer', async () => { @@ -22991,6 +22995,76 @@ describe('OrcaRuntimeService', () => { }) }) + it('does not count a saved final tab as live after the provider confirms its PTY closed', async () => { + const { runtimeStore } = makeRuntimeStoreWithWorkspaceSession( + makeWorkspaceSessionWithHeadlessTerminal() + ) + const runtime = new OrcaRuntimeService(runtimeStore as never) + runtime.setPtyController({ + write: vi.fn(() => true), + kill: vi.fn(() => true), + getForegroundProcess: vi.fn(async () => null), + listProcesses: vi.fn(async () => []) + }) + + const terminals = await runtime.listTerminals(undefined, 100, { + requireFreshPtyLiveness: true + }) + const { worktrees } = await runtime.getWorktreePs() + + expect(terminals.terminals).toEqual([]) + expect(worktrees[0]).toMatchObject({ + worktreeId: TEST_WORKTREE_ID, + liveTerminalCount: 0, + hasAttachedPty: false, + status: 'inactive' + }) + }) + + it('does not count a retained graph leaf after fresh provider liveness excludes its PTY', async () => { + const runtime = new OrcaRuntimeService(store) + runtime.attachWindow(1) + runtime.syncWindowGraph(1, { + tabs: [ + { + tabId: 'stale-tab', + worktreeId: TEST_WORKTREE_ID, + title: 'Stale', + activeLeafId: HEADLESS_LEAF_ID, + layout: null + } + ], + leaves: [ + { + tabId: 'stale-tab', + worktreeId: TEST_WORKTREE_ID, + leafId: HEADLESS_LEAF_ID, + paneRuntimeId: 1, + ptyId: 'stale-pty' + } + ] + }) + runtime.setPtyController({ + write: vi.fn(() => true), + kill: vi.fn(() => true), + getForegroundProcess: vi.fn(async () => null), + listProcesses: vi.fn(async () => []) + }) + + const terminals = await runtime.listTerminals(undefined, 100, { + requireFreshPtyLiveness: true + }) + const { worktrees } = await runtime.getWorktreePs() + + expect(terminals.terminals).toEqual([]) + expect(worktrees[0]).toMatchObject({ + worktreeId: TEST_WORKTREE_ID, + liveTerminalCount: 0, + hasAttachedPty: false, + status: 'inactive' + }) + }) + it('marks saved session tabs with live PTYs as host sidebar activity', async () => { const { runtimeStore } = makeRuntimeStoreWithWorkspaceSession( makeWorkspaceSessionWithHeadlessTerminal() @@ -23090,7 +23164,10 @@ describe('OrcaRuntimeService', () => { expect(worktrees[0]).toMatchObject({ worktreeId: TEST_WORKTREE_ID, - hasHostSidebarActivity: true + hasHostSidebarActivity: true, + liveTerminalCount: 0, + hasAttachedPty: false, + status: 'inactive' }) }) @@ -23471,6 +23548,50 @@ describe('OrcaRuntimeService', () => { } ) + it('omits a retained done hook row after its terminal tab is no longer live', async () => { + const now = Date.now() + const { runtimeStore } = makeRuntimeStoreWithWorkspaceSession( + makeWorkspaceSessionWithHeadlessTerminal({ + tabsByWorktree: { + [TEST_WORKTREE_ID]: [ + { + id: 'closed-tab', + ptyId: null, + worktreeId: TEST_WORKTREE_ID, + title: 'Completed', + customTitle: null, + color: null, + sortOrder: 0, + createdAt: 1 + } + ] + }, + terminalLayoutsByTabId: {} + }) + ) + const runtime = new OrcaRuntimeService(runtimeStore as never, undefined, { + getAgentStatusSnapshot: () => [ + { + paneKey: 'closed-tab:33333333-3333-4333-8333-333333333333', + worktreeId: TEST_WORKTREE_ID, + tabId: 'closed-tab', + state: 'done', + prompt: 'completed before close', + agentType: 'codex', + connectionId: null, + receivedAt: now, + stateStartedAt: now - 100 + } + ] + }) + + const { worktrees } = await runtime.getWorktreePs() + + expect(worktrees.find((worktree) => worktree.worktreeId === TEST_WORKTREE_ID)?.agents).toEqual( + [] + ) + }) + it('marks the desktop-active worktree as isActive', async () => { const { runtimeStore } = makeRuntimeStoreWithWorkspaceSession( makeWorkspaceSessionWithHeadlessTerminal() diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index a97c2f1cfb8f..b736739f88b7 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -2565,6 +2565,7 @@ export class OrcaRuntimeService { private readonly onTerminalSideEffects: ((batch: TerminalSideEffectBatch) => void) | null private terminalSideEffectConsumerAvailable = false private readonly getAgentStatusSnapshotFn: (() => AgentStatusIpcPayload[]) | null + private readonly dropAgentStatusEntriesByTabPrefixFn: ((tabId: string) => void) | null private readonly buildAgentHookPtyEnv: (() => Record) | null private readonly getDesktopWindowStatusFn: () => RuntimeDesktopWindowStatus private accountServices: RuntimeAccountServices | null = null @@ -2595,6 +2596,7 @@ export class OrcaRuntimeService { // terminal output. worktree.ps reads this at query time so mobile shows the // same inline agent rows the desktop sidebar does — same source, 1:1. getAgentStatusSnapshot?: () => AgentStatusIpcPayload[] + dropAgentStatusEntriesByTabPrefix?: (tabId: string) => void // Why: codex-home paths for the Agent Session History scan must be sourced // here, not via the window-only registerCoreHandlers path — that path never // runs under `orca serve`, so remote/SSH hosts would silently drop @@ -2610,6 +2612,7 @@ export class OrcaRuntimeService { this.agentDetector = new AgentDetector(stats) } this.getAgentStatusSnapshotFn = deps?.getAgentStatusSnapshot ?? null + this.dropAgentStatusEntriesByTabPrefixFn = deps?.dropAgentStatusEntriesByTabPrefix ?? null // Why: configure the shared AiVault scan cache from a serve-mode-reachable // seam so the aiVault.listSessions RPC includes managed-Codex + WSL sessions // even on headless `orca serve` hosts where registerCoreHandlers never runs. @@ -4766,6 +4769,9 @@ export class OrcaRuntimeService { ) if (!tab) { if (tabBeforeReconciliation) { + if (tabBeforeReconciliation.type === 'terminal') { + this.dropAgentStatusEntriesForClosedTab(tabBeforeReconciliation.parentTabId) + } return { closed: true } } throw new Error('tab_not_found') @@ -4787,6 +4793,7 @@ export class OrcaRuntimeService { // Why: renderer-owned whole-tab close is a lifecycle transaction. The reply // arrives only after canonical retirement and a forced session flush. await this.notifier.closeTerminalTab(tab.parentTabId) + this.dropAgentStatusEntriesForClosedTab(tab.parentTabId) return { closed: true } } if (!this.notifier?.closeTerminal) { @@ -4807,6 +4814,9 @@ export class OrcaRuntimeService { // just whichever leaf happened to be first in the session snapshot. this.notifier?.closeTerminal(tab.parentTabId) } + if (closingWholeParent) { + this.dropAgentStatusEntriesForClosedTab(tab.parentTabId) + } } else if (tab.type === 'browser' && this.offscreenBrowserBackend) { // Why: headless browser tabs are offscreen WebContents with no renderer to // route closeSessionTab to. Close the page directly and drop it from the @@ -4960,6 +4970,7 @@ export class OrcaRuntimeService { tabs: nextTabs } this.mobileSessionTabsByWorktree.set(worktreeId, nextSnapshot) + this.dropAgentStatusEntriesForClosedTab(closedParentTabId) this.emitMobileSessionTabsSnapshot(nextSnapshot) } @@ -6886,6 +6897,15 @@ export class OrcaRuntimeService { } } + private dropAgentStatusEntriesForClosedTab(tabId: string): void { + for (const paneKey of this.latestAgentStatusByPaneKey.keys()) { + if (parsePaneKey(paneKey)?.tabId === tabId) { + this.latestAgentStatusByPaneKey.delete(paneKey) + } + } + this.dropAgentStatusEntriesByTabPrefixFn?.(tabId) + } + getPtyOutputSequence(ptyId: string): number { return this.ptyOutputSequenceById.get(ptyId) ?? 0 } @@ -11662,7 +11682,8 @@ export class OrcaRuntimeService { ) // Why: worktree.ps backs the mobile sidebar, so it must use the same // host-owned imported-worktree visibility gate as worktree.list/desktop. - await this.refreshPtyWorktreeRecordsFromController(resolvedWorktrees) + const refreshedLivePtyIds = + await this.refreshPtyWorktreeRecordsFromController(resolvedWorktrees) const repoById = new Map((this.store?.getRepos() ?? []).map((repo) => [repo.id, repo])) const platformByRepoId = resolvedWorktreeSnapshot.platformByRepoId const summaries = new Map() @@ -11800,7 +11821,15 @@ export class OrcaRuntimeService { ) const missingRuntimeWorktreeIds = new Set() const countedPtyIds = new Set() + const liveTerminalTabIds = new Set() for (const leaf of this.leaves.values()) { + const ptyId = leaf.ptyId + const leafIsLive = + ptyId !== null && + (refreshedLivePtyIds !== null ? refreshedLivePtyIds.has(ptyId) : leaf.connected) + if (!leafIsLive || ptyId === null) { + continue + } const summary = this.getSummaryForRuntimeWorktreeId( summaries, runtimeWorktreeSummaryPathIndex, @@ -11810,15 +11839,12 @@ export class OrcaRuntimeService { if (!summary) { continue } - if (leaf.ptyId) { - countedPtyIds.add(leaf.ptyId) - } - if (leaf.ptyId && leaf.connected) { - summary.hasHostSidebarActivity = true - } + countedPtyIds.add(ptyId) + liveTerminalTabIds.add(leaf.tabId) + summary.hasHostSidebarActivity = true const previousLastOutputAt = summary.lastOutputAt summary.liveTerminalCount += 1 - summary.hasAttachedPty = summary.hasAttachedPty || leaf.connected + summary.hasAttachedPty = true summary.lastOutputAt = maxTimestamp(summary.lastOutputAt, leaf.lastOutputAt) summary.status = mergeWorktreeStatus( summary.status, @@ -11833,7 +11859,11 @@ export class OrcaRuntimeService { } for (const pty of this.ptysById.values()) { - if (!pty.connected || countedPtyIds.has(pty.ptyId)) { + if ( + !pty.connected || + countedPtyIds.has(pty.ptyId) || + (refreshedLivePtyIds !== null && !refreshedLivePtyIds.has(pty.ptyId)) + ) { continue } const summary = this.getSummaryForRuntimeWorktreeId( @@ -11845,6 +11875,9 @@ export class OrcaRuntimeService { if (!summary) { continue } + if (pty.tabId) { + liveTerminalTabIds.add(pty.tabId) + } const previousLastOutputAt = summary.lastOutputAt summary.liveTerminalCount += 1 summary.hasAttachedPty = true @@ -11873,34 +11906,8 @@ export class OrcaRuntimeService { summary.hasHostSidebarActivity = true } } - for (const [worktreeId, tabs] of Object.entries(session?.tabsByWorktree ?? {})) { - if (tabs.length === 0) { - continue - } - const summary = this.getSummaryForRuntimeWorktreeId( - summaries, - runtimeWorktreeSummaryPathIndex, - missingRuntimeWorktreeIds, - worktreeId - ) - if (!summary) { - continue - } - // Why: desktop can show terminal tabs that are not mounted as renderer - // leaves and are not currently visible in the PTY provider list. Mobile - // still needs those worktrees to show as terminal-bearing entries. - summary.liveTerminalCount = Math.max(summary.liveTerminalCount, tabs.length) - summary.hasAttachedPty = summary.hasAttachedPty || tabs.some((tab) => tab.ptyId !== null) - if (tabs.some((tab) => tab.ptyId !== null && this.ptysById.get(tab.ptyId)?.connected)) { - summary.hasHostSidebarActivity = true - } - for (const tab of tabs) { - summary.status = mergeWorktreeStatus( - summary.status, - getSavedTabWorktreeStatus(tab.title, tab.ptyId !== null) - ) - } - } + // Why: persisted terminal tabs are restore candidates, not liveness proof. + // Live counts and attachment state come only from the refreshed graph/PTYs above. for (const [worktreeId, tabs] of Object.entries(session?.browserTabsByWorktree ?? {})) { if (tabs.length === 0) { @@ -11952,7 +11959,8 @@ export class OrcaRuntimeService { summaries, runtimeWorktreeSummaryPathIndex, missingRuntimeWorktreeIds, - mirroredWorktreeIdByTabId + mirroredWorktreeIdByTabId, + liveTerminalTabIds ) const sorted = [...summaries.values()].sort(compareWorktreePs) @@ -11971,7 +11979,8 @@ export class OrcaRuntimeService { summaries: Map, runtimeWorktreeSummaryPathIndex: RuntimeWorktreeSummaryPathIndex, missingRuntimeWorktreeIds: Set, - mirroredWorktreeIdByTabId: ReadonlyMap + mirroredWorktreeIdByTabId: ReadonlyMap, + liveTerminalTabIds: ReadonlySet ): void { // Why: most agents report via hooks (agent-hooks/server), not OSC, so the // hook snapshot is the primary source — same one the desktop sidebar reads. @@ -12047,6 +12056,11 @@ export class OrcaRuntimeService { if (!worktreeId) { continue } + // Why: completed/stale hook snapshots can survive on disk for days. Keep + // fresh active rows through transient tab gaps, but never revive a closed tab. + if (!liveTerminalTabIds.has(tabId ?? '') && !isFreshNonDoneAgentStatus(src, now)) { + continue + } const summary = this.getSummaryForRuntimeWorktreeId( summaries, runtimeWorktreeSummaryPathIndex, @@ -27731,10 +27745,6 @@ function getLatestAgentCandidateTitleInfo( return latest } -function getSavedTabWorktreeStatus(title: string, hasPty: boolean): RuntimeWorktreeStatus { - return getDetectedWorktreeStatus(detectAgentStatusFromTitle(title), hasPty) -} - function getDetectedWorktreeStatus( detected: AgentStatus | null, hasPty: boolean From d3a1d30474dfee5a0f42b68dc8945cd57cabdb67 Mon Sep 17 00:00:00 2001 From: jon Date: Tue, 21 Jul 2026 12:20:16 +0100 Subject: [PATCH 3/3] fix(runtime): clear legacy pane status on tab close --- src/main/runtime/orca-runtime.test.ts | 6 ++++++ src/main/runtime/orca-runtime.ts | 10 ++++++++-- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/src/main/runtime/orca-runtime.test.ts b/src/main/runtime/orca-runtime.test.ts index 0b9a706d7f28..2e33f947d052 100644 --- a/src/main/runtime/orca-runtime.test.ts +++ b/src/main/runtime/orca-runtime.test.ts @@ -22064,6 +22064,11 @@ describe('OrcaRuntimeService', () => { const runtime = new OrcaRuntimeService(runtimeStore as never, undefined, { dropAgentStatusEntriesByTabPrefix }) + const retainedAgentRows = ( + runtime as unknown as { latestAgentStatusByPaneKey: Map } + ).latestAgentStatusByPaneKey + retainedAgentRows.set('host-tab:1', {}) + retainedAgentRows.set('host-tab-sibling:1', {}) runtime.setPtyController({ write: () => true, kill, @@ -22103,6 +22108,7 @@ describe('OrcaRuntimeService', () => { // Best-effort renderer notify so no adopted pane is left dead. expect(closeTerminal).toHaveBeenCalledWith('host-tab') expect(dropAgentStatusEntriesByTabPrefix).toHaveBeenCalledWith('host-tab') + expect([...retainedAgentRows.keys()]).toEqual(['host-tab-sibling:1']) }) it('delegates a renderer-owned daemon-session (worktreeId@@uuid) local terminal to the renderer', async () => { diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index 9ec1703cf235..c4aa36a2bfb6 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -220,7 +220,12 @@ import { } from '../../shared/setup-agent-sequencing' import { TASK_PROVIDERS } from '../../shared/task-providers' import { FIRST_PANE_ID } from '../../shared/pane-key' -import { isTerminalLeafId, makePaneKey, parsePaneKey } from '../../shared/stable-pane-id' +import { + isTerminalLeafId, + makePaneKey, + parseLegacyNumericPaneKey, + parsePaneKey +} from '../../shared/stable-pane-id' import { parseAppSshPtyId } from '../../shared/ssh-pty-id' import { isValidHostTerminalTabId, isValidTerminalTabId } from '../../shared/terminal-tab-id' import { @@ -7577,7 +7582,8 @@ export class OrcaRuntimeService { private dropAgentStatusEntriesForClosedTab(tabId: string): void { for (const paneKey of this.latestAgentStatusByPaneKey.keys()) { - if (parsePaneKey(paneKey)?.tabId === tabId) { + const paneTabId = parsePaneKey(paneKey)?.tabId ?? parseLegacyNumericPaneKey(paneKey)?.tabId + if (paneTabId === tabId) { this.latestAgentStatusByPaneKey.delete(paneKey) } }