fix(session-tabs): retire a mirrored pane once the host has closed its tab (#40692)

A mirrored pane whose leaf lost its PTY binding (for example after its agent
exited) is resolved by pane key. Once the host had closed the tab, recovery
never treated the host's answer as proof the pane was gone, so it re-injected a
pending row into every frame and the closed tab stayed in the tab strip and the
saved session forever.

- Host: an exited PTY record outlives its tab, so terminal.resolvePane kept
  answering "disconnected" for a closed tab's pane. It now answers
  terminal_not_found when no leaf holds the pane, its PTY is not connected
  and the tab is gone from the host's workspace session.
- Client: unbound panes now follow the same rules as bound ones. A close
  record for the pane retires it at once; otherwise two authoritative absences
  (the frame omits the pane and the host cannot resolve it, or resolves it only
  as a disconnected leftover) retire it. Any sign the host still owns the pane
  restarts the count.

Refs #9194
This commit is contained in:
Neil
2026-11-10 00:03:27 -08:00
committed by GitHub
parent 643411cfa3
commit a9db2a6571
5 changed files with 202 additions and 12 deletions
@@ -0,0 +1,45 @@
import { describe, expect, it } from 'vitest'
import { makePaneKey } from '../../../../shared/workspace-layout/stable-pane-id'
import {
LEAF_ID,
PTY_ID,
TAB_ID,
WORKTREE_ID
} from '../../__fixtures__/orca-runtime-terminal-close-continuity-state-fixture'
import { createHarness } from '../../__fixtures__/orca-runtime-terminal-close-continuity-fixtures'
// #9194: a paired client asks for a pane by key; a tab the host closed after its agent exited must
// read as gone, or the client keeps the closed tab forever.
async function exitedPaneWithoutTab() {
const harness = createHarness({ publishMobileSurface: true, registerPtyBacked: true })
harness.runtime.setNotifier(null)
harness.syncEmptyGraph()
harness.removeVictimFromInventory()
const before = harness.getSession()
// With no desktop window, the exit itself closes the tab's last pane and so the tab.
await harness.runtime.onPtyExit(PTY_ID, 0)
expect(harness.getSession().tabsByWorktree[WORKTREE_ID]).toEqual([])
return { harness, before }
}
const resolve = (harness: Awaited<ReturnType<typeof exitedPaneWithoutTab>>['harness']) =>
harness.runtime.resolveTerminalPane(makePaneKey(TAB_ID, LEAF_ID), WORKTREE_ID)
describe('resolving a pane of a tab the host closed', () => {
it('answers terminal_not_found once the exited pane has no tab', async () => {
const { harness } = await exitedPaneWithoutTab()
expect(() => resolve(harness)).toThrow('terminal_not_found')
})
it('still resolves an exited pane whose tab the host keeps', async () => {
const { harness, before } = await exitedPaneWithoutTab()
harness.editSession(() => before)
expect(resolve(harness)).toMatchObject({ connected: false })
})
it('still resolves the pane while the host session is unreadable', async () => {
const { harness } = await exitedPaneWithoutTab()
harness.makeSessionUnavailable()
expect(resolve(harness)).toMatchObject({ connected: false })
})
})
@@ -24,6 +24,7 @@ import {
import { getTerminalState } from '../wait/terminal-wait-results'
import { readStructuredWorkerTerminal } from '../../orchestration/terminal-authority/structured-sessions/structured-worker-terminal-read'
import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/layout-owner-switch'
import { workspaceSessionListsTerminalTab } from '../../../../shared/workspace-session/workspace-session-terminal-tab-close'
export abstract class OrcaRuntimeWithResolveTerminalPane extends OrcaRuntimeWithRestoredHandlePaneStart {
protected abstract assertLiveTerminalHandleTargetsPty(handle: string, expectedPtyId: string): void
@@ -79,6 +80,17 @@ export abstract class OrcaRuntimeWithResolveTerminalPane extends OrcaRuntimeWith
// Why: pane coordinates restored by a paired client must not cross workspace ownership.
throw new Error('terminal_not_found')
}
if (parsed && !leaf && pty && !pty.connected && worktreeId) {
// An exited PTY outlives its tab; once the host closed that tab the pane is gone, and a client
// must not read the leftover record as a pane the host still owns (#9194).
const session = this.getWorkspaceSessionForWorktree(worktreeId)
if (
session?.tabsByWorktree[worktreeId] &&
!workspaceSessionListsTerminalTab(session, worktreeId, parsed.tabId)
) {
throw new Error('terminal_not_found')
}
}
return {
handle,
tabId: parsed?.tabId ?? record?.tabId ?? '',
@@ -131,7 +131,7 @@ function buildPaneResolutionFingerprint(
function inventoryAbsenceCoordinates(args: {
environmentId: string
snapshot: RuntimeMobileSessionTabsResult
surface: RecoverySurface
surface: RecoverySurface | UnresolvedRecoverySurface
expectedEnvironmentPairingRevision?: number
}): { key: string; fingerprint: string } {
return {
@@ -142,15 +142,15 @@ function inventoryAbsenceCoordinates(args: {
expectedEnvironmentPairingRevision: args.expectedEnvironmentPairingRevision
}),
// Absence fingerprints identify surfaces, not publicationEpoch: including epoch resets evidence on republication and prevents two independent inventories confirming absence.
fingerprint: [args.surface.handle, args.surface.expectedPtyId ?? ''].join('\0')
fingerprint: [args.surface.handle ?? '', args.surface.expectedPtyId ?? ''].join('\0')
}
}
/** Returns true after two authoritative inventories omit the same surface identity. */
/** Returns true after two authoritative inventories (terminal listings, or pane resolutions for unbound panes) omit the same surface identity. */
export function confirmSurfaceInventoryAbsence(args: {
environmentId: string
snapshot: RuntimeMobileSessionTabsResult
surface: RecoverySurface
surface: RecoverySurface | UnresolvedRecoverySurface
expectedEnvironmentPairingRevision?: number
}): boolean {
const { key, fingerprint } = inventoryAbsenceCoordinates(args)
@@ -174,7 +174,7 @@ export function confirmSurfaceInventoryAbsence(args: {
export function clearSurfaceInventoryAbsence(args: {
environmentId: string
snapshot: RuntimeMobileSessionTabsResult
surface: RecoverySurface
surface: RecoverySurface | UnresolvedRecoverySurface
expectedEnvironmentPairingRevision?: number
}): void {
surfaceInventoryAbsences.delete(inventoryAbsenceCoordinates(args).key)
@@ -5,8 +5,12 @@ import { makePaneKey } from '../../../../../../shared/workspace-layout/stable-pa
import { runInTerminalRecoveryRpcLane } from '../scheduling/web-session-terminal-orphan-recovery-rpc-lane'
import {
cacheStablePaneResolutionFailure,
clearSurfaceInventoryAbsence,
confirmSurfaceInventoryAbsence,
readStablePaneResolutionFailure
} from '../evidence/web-session-terminal-orphan-recovery-cache'
import { latestTerminalRetirementProof } from '../surfaces/web-session-terminal-orphan-recovery-surface-index'
import { hostSnapshotAffirmsWorktreeContents } from '../../../web-session-tabs-sync/hydration/host-session-snapshot-authority'
import type {
RecoverySurface,
UnresolvedRecoverySurface
@@ -25,6 +29,9 @@ type PaneResolution = {
unresolved: UnresolvedRecoverySurface[]
}
/** `absent`: the host has no terminal for the pane; `owned`: it has one, just not attachable yet. */
type PaneOutcome = RecoverySurface | 'absent' | 'owned' | null
type ResolvedPaneResponse =
| { kind: 'connected'; terminal: RuntimeTerminalResolvePane }
| { kind: 'disconnected' }
@@ -96,7 +103,7 @@ async function resolveOne(args: {
call: RuntimeCall
expectedEnvironmentPairingRevision?: number
isCurrent: () => boolean
}): Promise<RecoverySurface | null> {
}): Promise<PaneOutcome> {
const { surface, snapshot, environmentId, call, expectedEnvironmentPairingRevision, isCurrent } =
args
if (!isCurrent()) {
@@ -147,6 +154,11 @@ async function resolveOne(args: {
if (response?.error.code === 'method_not_found') {
cacheFailure()
}
// The host also answers this for a live leaf between PTYs, so it is an absence only when the
// frame omits the pane too; a pending row means the host still owns it.
if (response?.error.code === 'terminal_not_found' && surface.incoming === undefined) {
return 'absent'
}
return null
}
const resolution = readResolvedPane(response.result)
@@ -155,11 +167,13 @@ async function resolveOne(args: {
return null
}
if (resolution.kind === 'disconnected') {
return null
// Older hosts keep resolving a closed tab's exited pane as disconnected; only the frame can
// tell that apart from a live tab between PTYs.
return surface.incoming === undefined ? 'absent' : 'owned'
}
const { terminal } = resolution
if (!matchesSurface(terminal, surface, snapshot.worktree)) {
return null
return 'owned'
}
return resolvedSurface(surface, terminal)
} catch {
@@ -167,6 +181,9 @@ async function resolveOne(args: {
}
}
/** Unbound panes have no handle to list, so they are retired by pane: the host's close record for
* the pane, or the same two consecutive authoritative absences that retire listed handles. Any
* sign the host still owns the pane restarts the count. Retired panes are in neither result list. */
export async function resolvePersistedTerminalSurfaces(args: {
surfaces: readonly UnresolvedRecoverySurface[]
snapshot: RuntimeMobileSessionTabsResult
@@ -175,7 +192,11 @@ export async function resolvePersistedTerminalSurfaces(args: {
expectedEnvironmentPairingRevision?: number
isCurrent: () => boolean
}): Promise<PaneResolution | null> {
const { surfaces, isCurrent } = args
const { snapshot, isCurrent } = args
const surfaces = args.surfaces.filter(
(surface) =>
surface.incoming !== undefined || latestTerminalRetirementProof(snapshot, surface) === null
)
if (surfaces.length === 0) {
return { resolved: [], unresolved: [] }
}
@@ -191,8 +212,26 @@ export async function resolvePersistedTerminalSurfaces(args: {
if (!isCurrent()) {
return null
}
return {
resolved: outcomes.flatMap(({ resolved }) => (resolved ? [resolved] : [])),
unresolved: outcomes.flatMap(({ surface, resolved }) => (resolved ? [] : [surface]))
const resolved: RecoverySurface[] = []
const unresolved: UnresolvedRecoverySurface[] = []
for (const { surface, resolved: outcome } of outcomes) {
const evidence = { ...args, surface }
if (outcome !== 'absent') {
if (outcome !== null || surface.incoming !== undefined) {
clearSurfaceInventoryAbsence(evidence)
}
if (outcome !== null && outcome !== 'owned') {
resolved.push(outcome)
} else {
unresolved.push(surface)
}
} else if (
// A frame the host did not publish affirms nothing, so it is never an absence.
!hostSnapshotAffirmsWorktreeContents(snapshot) ||
!confirmSurfaceInventoryAbsence(evidence)
) {
unresolved.push(surface)
}
}
return { resolved, unresolved }
}
@@ -5,6 +5,8 @@ import {
recoverWebSessionTerminalOrphansBeforeApply
} from '../web-session-terminal-orphan-recovery'
import type { TerminalOrphanRecoveryState } from '../surfaces/web-session-terminal-orphan-recovery-surface'
import type { TerminalOrphanRecoveryCall } from '../adoption/web-session-terminal-orphan-recovery-adoption'
import type { RuntimeMobileSessionTabsResult } from '../../../../../../shared/runtime-session-contracts'
import '../../../rpc/testing/runtime-environment-bridge-fixture'
const ENVIRONMENT_ID = 'remote-runtime'
@@ -254,4 +256,96 @@ describe('web session pending terminal handle recovery', () => {
]
})
})
describe('an unbound pane whose host tab was closed (#9194)', () => {
const closedPaneCall = vi.fn<TerminalOrphanRecoveryCall>()
beforeEach(() => {
closedPaneCall.mockReset()
closedPaneCall.mockImplementation(async ({ method }) =>
method === 'terminal.resolvePane'
? {
id: 'resolve',
ok: false,
error: { code: 'terminal_not_found', message: 'terminal_not_found' }
}
: { id: method, ok: false, error: { code: 'unexpected_method', message: method } }
)
})
function closedTabFrame(snapshotVersion: number): RuntimeMobileSessionTabsResult {
return { ...pendingSnapshot(), activeTabId: null, snapshotVersion, tabs: [] }
}
function recover(frame: RuntimeMobileSessionTabsResult) {
return recoverWebSessionTerminalOrphansBeforeApply(
stateWithEmptyBinding(),
frame,
ENVIRONMENT_ID,
{ call: closedPaneCall }
)
}
const keepsPane = { tabs: [expect.objectContaining({ parentTabId: HOST_TAB_ID })] }
it('retires the pane after two authoritative absences', async () => {
await expect(recover(closedTabFrame(3))).resolves.toMatchObject(keepsPane)
await expect(recover(closedTabFrame(4))).resolves.toMatchObject({ tabs: [] })
})
it('retires the pane at once when the frame carries its close record', async () => {
const frame = {
...closedTabFrame(3),
retiredTerminalSurfaces: [
{
parentTabId: HOST_TAB_ID,
leafId: LEAF_ID,
terminal: TERMINAL_HANDLE,
ptyId: 'pty-live'
}
]
}
await expect(recover(frame)).resolves.toMatchObject({ tabs: [] })
expect(closedPaneCall).not.toHaveBeenCalled()
})
it('restarts the count when the host publishes the pane again', async () => {
await recover(closedTabFrame(3))
await recover({ ...pendingSnapshot(), snapshotVersion: 4 })
await expect(recover(closedTabFrame(5))).resolves.toMatchObject(keepsPane)
})
it('retires a closed tab whose exited pane an older host still resolves as disconnected', async () => {
closedPaneCall.mockImplementation(async ({ method }) =>
method === 'terminal.resolvePane'
? {
id: 'resolve',
ok: true,
_meta: { runtimeId: 'runtime-1' },
result: {
terminal: {
handle: TERMINAL_HANDLE,
tabId: HOST_TAB_ID,
leafId: LEAF_ID,
ptyId: 'pty-live',
connected: false,
worktreeId: WORKTREE_ID
}
}
}
: { id: method, ok: false, error: { code: 'unexpected_method', message: method } }
)
await expect(recover(closedTabFrame(3))).resolves.toMatchObject(keepsPane)
await expect(recover(closedTabFrame(4))).resolves.toMatchObject({ tabs: [] })
})
it('keeps a pane the host still publishes, whatever the pane lookup says', async () => {
for (const snapshotVersion of [3, 4, 5]) {
await expect(recover({ ...pendingSnapshot(), snapshotVersion })).resolves.toMatchObject(
keepsPane
)
}
})
it('never counts a frame the host did not publish', async () => {
await recover({ ...closedTabFrame(3), publicationEpoch: 'none' })
await expect(recover(closedTabFrame(4))).resolves.toMatchObject(keepsPane)
})
})
})