From 816bf8a2375c89045b9a81cfd48cac074921b77d Mon Sep 17 00:00:00 2001 From: Neil Date: Thu, 15 Oct 2026 22:33:04 -0700 Subject: [PATCH 1/6] fix(remote): send again a tab close the paired host never received Closing a paired host's tab prunes the local mirror at once and asks the host to close it. When the connection dropped mid-close the renderer cleared its close intent, so the host's next snapshot after reconnect brought the tab back. A user close that fails without reaching the host is now held: the tab stays hidden, and the close is sent again when a snapshot proves the host is reachable and still lists it, up to three times before the tab is shown. --- ...runtime-session-tab-activate-close.test.ts | 80 +++++++++++- .../web-runtime-session-tab-lifecycle.ts | 86 ++++++++++++- .../runtime/web-session-close-replay.test.ts | 110 +++++++++++++++++ .../src/runtime/web-session-close-replay.ts | 114 ++++++++++++++++++ .../apply-preparation-base.ts | 13 +- .../global-session-subscription.ts | 2 + 6 files changed, 395 insertions(+), 10 deletions(-) create mode 100644 src/renderer/src/runtime/web-session-close-replay.test.ts create mode 100644 src/renderer/src/runtime/web-session-close-replay.ts diff --git a/src/renderer/src/runtime/web-runtime-session-tab-activate-close.test.ts b/src/renderer/src/runtime/web-runtime-session-tab-activate-close.test.ts index 212897a92090..5dcbee1f5d5b 100644 --- a/src/renderer/src/runtime/web-runtime-session-tab-activate-close.test.ts +++ b/src/renderer/src/runtime/web-runtime-session-tab-activate-close.test.ts @@ -2,8 +2,13 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type * as TrackingDecisions from './web-session-tabs-sync/tracking-decisions' import { activateWebRuntimeSessionTab, - closeWebRuntimeSessionTab + closeWebRuntimeSessionTab, + replayWebSessionTabCloses } from './web-runtime-session-tab-lifecycle' +import { + resetWebSessionCloseReplaysForTests, + takeDueWebSessionCloseReplays +} from './web-session-close-replay' import { peekWebSessionFocusIntent, resetWebSessionFocusIntentForTests @@ -87,7 +92,10 @@ vi.mock('./web-runtime-browser-materialization', () => ({ hasMaterializedWebRuntimeBrowserPage: mocks.hasMaterializedWebRuntimeBrowserPage })) -afterEach(() => resetWebSessionCloseIntentForTests()) +afterEach(() => { + resetWebSessionCloseIntentForTests() + resetWebSessionCloseReplaysForTests() +}) describe('web runtime session tab actions', () => { beforeEach(() => { @@ -595,6 +603,74 @@ describe('web runtime session tab actions', () => { expect(mocks.acceptReplayedWebSessionTabsSnapshot).not.toHaveBeenCalled() }) + // STA-6224: clearing on a dropped connection let the host's next snapshot re-add the tab. + it('holds a user close the host never received and sends it again once reachable', async () => { + const runtimeCall = vi + .fn() + .mockRejectedValueOnce(new Error('socket hang up')) + .mockResolvedValueOnce({ id: 'close', ok: true, result: { closed: true } }) + .mockResolvedValue({ id: 'list', ok: true, result: makeSnapshot() }) + stubRuntimeEnvironmentBridge({ call: runtimeCall }) + const owner = { environmentId: ENVIRONMENT_ID } + + await expect( + closeWebRuntimeSessionTab({ + worktreeId: WORKTREE_ID, + tabId: 'local-browser-unified', + reason: 'user' + }) + ).resolves.toBe('failed') + + // Durable: a reconnect long after the RPC timeout must still not re-show it. + expect( + isWebSessionCloseIntentPending( + owner, + WORKTREE_ID, + 'host-browser-unified', + Date.now() + 60_000 + ) + ).toBe(true) + const due = takeDueWebSessionCloseReplays(owner, WORKTREE_ID, new Set(['host-browser-unified'])) + expect(due.map((replay) => replay.hostTabIds[0])).toEqual(['host-browser-unified']) + + await replayWebSessionTabCloses(ENVIRONMENT_ID, due) + + const closeCalls = runtimeCall.mock.calls.filter( + ([request]: unknown[]) => + typeof request === 'object' && + request !== null && + 'method' in request && + request.method === 'session.tabs.close' + ) + expect(closeCalls).toHaveLength(2) + expect(closeCalls[1]?.[0]).toMatchObject({ + params: { tabId: 'host-browser-unified', reason: 'user' } + }) + expect( + takeDueWebSessionCloseReplays(owner, WORKTREE_ID, new Set(['host-browser-unified'])) + ).toEqual([]) + }) + + it('does not hold a lifecycle close the host never received', async () => { + stubRuntimeEnvironmentBridge({ call: vi.fn().mockRejectedValue(new Error('socket hang up')) }) + + await closeWebRuntimeSessionTab({ + worktreeId: WORKTREE_ID, + tabId: 'local-browser-unified', + reason: 'cleanup', + publicationEpoch: 'epoch-1', + terminalHandle: 'term-1' + }) + + expect( + takeDueWebSessionCloseReplays( + { environmentId: ENVIRONMENT_ID }, + WORKTREE_ID, + new Set(['host-browser-unified']) + ) + ).toEqual([]) + }) + it('clears an optimistic close intent when pairing CAS rejects the host call', async () => { const runtimeCall = vi.fn().mockResolvedValue({ id: 'close-rejected', diff --git a/src/renderer/src/runtime/web-runtime-session-tab-lifecycle.ts b/src/renderer/src/runtime/web-runtime-session-tab-lifecycle.ts index f308587fd543..a8e0803cbdd8 100644 --- a/src/renderer/src/runtime/web-runtime-session-tab-lifecycle.ts +++ b/src/renderer/src/runtime/web-runtime-session-tab-lifecycle.ts @@ -4,13 +4,22 @@ import type { RuntimeSessionTabCloseReason } from '../../../shared/runtime-types' import { useAppStore } from '../store' -import { hasRuntimeRpcErrorCode, unwrapRuntimeRpcResult } from './runtime-rpc-result' +import { + hasRuntimeRpcErrorCode, + RuntimeRpcCallError, + unwrapRuntimeRpcResult +} from './runtime-rpc-result' import { toRuntimeWorktreeSelector } from './runtime-worktree-selector' import { clearWebSessionCloseIntent, makeWebSessionCloseIntentDurable, recordWebSessionCloseIntent } from './web-session-close-intent' +import { + queueWebSessionCloseReplay, + settleWebSessionCloseReplay, + type WebSessionCloseReplay +} from './web-session-close-replay' import { clearWebSessionFocusIntent, clearWebSessionFocusIntentIfMatches, @@ -78,6 +87,55 @@ export async function closeWebRuntimeSessionTab(args: { return callWebRuntimeSessionTabMethod('session.tabs.close', args) } +// Why these and a bare rejection only: they mean the close never reached the host, so sending it +// again is the user's own close. A structured refusal (e.g. a re-paired host) is an answer. +const UNDELIVERED_CLOSE_CODES = new Set([ + 'runtime_unavailable', + 'remote_runtime_unavailable', + 'runtime_timeout', + 'remote_runtime_timeout' +]) + +function isUndeliveredCloseFailure(error: unknown): boolean { + return !(error instanceof RuntimeRpcCallError) || UNDELIVERED_CLOSE_CODES.has(error.code) +} + +/** Keeps a user close the host never received, hiding the tab until a replay reaches the host. */ +function holdUndeliveredUserClose( + intentOwner: ReturnType, + worktreeId: string, + hostTabIds: readonly string[] +): void { + for (const hostTabId of hostTabIds) { + recordWebSessionCloseIntent(intentOwner, worktreeId, hostTabId, Date.now()) + makeWebSessionCloseIntentDurable(intentOwner, worktreeId, hostTabId) + } + queueWebSessionCloseReplay(intentOwner, worktreeId, hostTabIds) +} + +/** Sends again the user closes a host snapshot proved reachable; see `takeDueWebSessionCloseReplays`. */ +export async function replayWebSessionTabCloses( + environmentId: string, + replays: readonly WebSessionCloseReplay[] +): Promise { + for (const replay of replays) { + const outcome = await closeWebRuntimeSessionTab({ + worktreeId: replay.worktreeId, + tabId: replay.hostTabIds[0], + environmentId, + reason: 'user' + }) + if (settleWebSessionCloseReplay(replay, outcome !== 'failed') !== 'gave-up') { + continue + } + // The host kept failing the close; show the tab again rather than hide a live one forever. + for (const hostTabId of replay.hostTabIds) { + clearWebSessionCloseIntent(replay.owner, replay.worktreeId, hostTabId) + } + await refreshWebRuntimeSessionTabsSnapshot(environmentId, replay.worktreeId) + } +} + function resolveTabEnvironmentId(environmentId: string | null | undefined): string | null { return ( environmentId?.trim() ?? @@ -101,6 +159,11 @@ async function callWebRuntimeSessionTabMethod( ): Promise { const environmentId = resolveTabEnvironmentId(args.environmentId) if (!environmentId || !isWebRuntimeSessionActive(environmentId)) { + if (environmentId && method === 'session.tabs.close' && args.reason === 'user') { + holdUndeliveredUserClose(captureWebSessionIntentOwner(environmentId), args.worktreeId, [ + toHostSessionTabId(args.tabId) + ]) + } return 'failed' } const intentOwner = captureWebSessionIntentOwner(environmentId) @@ -215,11 +278,22 @@ async function callWebRuntimeSessionTabMethod( const hostHasNoSuchTab = hasRuntimeRpcErrorCode(error, 'tab_not_found') || hasRuntimeRpcErrorCode(error, 'terminal_tab_not_found') - for (const hostTabId of closeIntentTabIds) { - if (hostHasNoSuchTab) { - makeWebSessionCloseIntentDurable(intentOwner, args.worktreeId, hostTabId) - } else { - clearWebSessionCloseIntent(intentOwner, args.worktreeId, hostTabId) + if ( + isClose && + args.reason === 'user' && + !hostHasNoSuchTab && + isUndeliveredCloseFailure(error) + ) { + // Why: clearing here let the host's next snapshot bring back a tab the user closed (STA-6224). + // The resolved host id was added last and is the one the host knows. + holdUndeliveredUserClose(intentOwner, args.worktreeId, [...closeIntentTabIds].toReversed()) + } else { + for (const hostTabId of closeIntentTabIds) { + if (hostHasNoSuchTab) { + makeWebSessionCloseIntentDurable(intentOwner, args.worktreeId, hostTabId) + } else { + clearWebSessionCloseIntent(intentOwner, args.worktreeId, hostTabId) + } } } if (isLifecycleClose) { diff --git a/src/renderer/src/runtime/web-session-close-replay.test.ts b/src/renderer/src/runtime/web-session-close-replay.test.ts new file mode 100644 index 000000000000..42c5a317be40 --- /dev/null +++ b/src/renderer/src/runtime/web-session-close-replay.test.ts @@ -0,0 +1,110 @@ +// STA-6224: a user's close the paired host never received must be sent again, not dropped. +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { toWebTerminalSurfaceTabId } from '../../../shared/terminal-surface-id' +import { + MAX_WEB_SESSION_CLOSE_REPLAY_ATTEMPTS, + queueWebSessionCloseReplay, + resetWebSessionCloseReplaysForTests, + settleWebSessionCloseReplay, + takeDueWebSessionCloseReplays +} from './web-session-close-replay' +import { recordWebSessionCloseIntent } from './web-session-close-intent' +import { applyWebSessionTabsSnapshot } from './web-session-tabs-sync/snapshot-api' +import { + ENV, + HOST_SURFACE_ID, + LEAF_ID, + NOW, + WT, + makeSnapshot, + makeState, + resetWebSessionTabsSyncTestState +} from './web-session-tabs-sync-test-harness' + +const { replayWebSessionTabCloses } = vi.hoisted(() => ({ + replayWebSessionTabCloses: vi.fn(async () => {}) +})) + +vi.mock('../store', () => ({ useAppStore: { setState: vi.fn() } })) +vi.mock('@/hooks/agent-hook-completion-notifications', () => ({ + observeAgentHookCompletionForNotification: vi.fn() +})) +vi.mock('./web-runtime-session-tab-lifecycle', () => ({ replayWebSessionTabCloses })) + +const OWNER = { environmentId: ENV } +const SURFACE = { + type: 'terminal' as const, + id: HOST_SURFACE_ID, + parentTabId: 'host-tab-1', + leafId: LEAF_ID, + title: 'Terminal', + status: 'ready' as const, + terminal: 'term_host', + isActive: true +} + +beforeEach(resetWebSessionTabsSyncTestState) +afterEach(() => { + resetWebSessionCloseReplaysForTests() + replayWebSessionTabCloses.mockClear() +}) + +describe('web session close replay', () => { + it('is due once a snapshot shows the host still holds the tab, and not twice in flight', () => { + queueWebSessionCloseReplay(OWNER, WT, ['host-tab-1']) + + const [due] = takeDueWebSessionCloseReplays(OWNER, WT, new Set(['host-tab-1'])) + expect(due).toMatchObject({ worktreeId: WT, hostTabIds: ['host-tab-1'], attempts: 1 }) + expect(takeDueWebSessionCloseReplays(OWNER, WT, new Set(['host-tab-1']))).toEqual([]) + + expect(settleWebSessionCloseReplay(due!, true)).toBe('done') + expect(takeDueWebSessionCloseReplays(OWNER, WT, new Set(['host-tab-1']))).toEqual([]) + }) + + it('is done without a send when the host no longer lists the tab', () => { + queueWebSessionCloseReplay(OWNER, WT, ['host-tab-1']) + + expect(takeDueWebSessionCloseReplays(OWNER, WT, new Set())).toEqual([]) + expect(takeDueWebSessionCloseReplays(OWNER, WT, new Set(['host-tab-1']))).toEqual([]) + }) + + it('gives up after a bounded number of undelivered sends', () => { + queueWebSessionCloseReplay(OWNER, WT, ['host-tab-1']) + const outcomes: string[] = [] + for (let attempt = 0; attempt < MAX_WEB_SESSION_CLOSE_REPLAY_ATTEMPTS; attempt += 1) { + const [due] = takeDueWebSessionCloseReplays(OWNER, WT, new Set(['host-tab-1'])) + // A repeat failure re-queues the same close; it must not reset the attempt count. + queueWebSessionCloseReplay(OWNER, WT, ['host-tab-1']) + outcomes.push(settleWebSessionCloseReplay(due!, false)) + } + expect(outcomes).toEqual(['retry', 'retry', 'gave-up']) + expect(takeDueWebSessionCloseReplays(OWNER, WT, new Set(['host-tab-1']))).toEqual([]) + }) + + it('never replays a close to a re-paired host', () => { + queueWebSessionCloseReplay({ environmentId: ENV, pairingRevision: 1 }, WT, ['host-tab-1']) + + expect( + takeDueWebSessionCloseReplays( + { environmentId: ENV, pairingRevision: 2 }, + WT, + new Set(['host-tab-1']) + ) + ).toEqual([]) + }) + + it('sends the held close when a host snapshot arrives, while keeping the tab hidden', async () => { + recordWebSessionCloseIntent(OWNER, WT, 'host-tab-1', NOW) + queueWebSessionCloseReplay(OWNER, WT, ['host-tab-1']) + + const patch = applyWebSessionTabsSnapshot(makeState(), makeSnapshot([SURFACE]), ENV, NOW) + + expect((patch.tabsByWorktree?.[WT] ?? []).map((tab) => tab.id)).not.toContain( + toWebTerminalSurfaceTabId('host-tab-1') + ) + await vi.waitFor(() => expect(replayWebSessionTabCloses).toHaveBeenCalledOnce()) + expect(replayWebSessionTabCloses).toHaveBeenCalledWith(ENV, [ + expect.objectContaining({ worktreeId: WT, hostTabIds: ['host-tab-1'] }) + ]) + }) +}) diff --git a/src/renderer/src/runtime/web-session-close-replay.ts b/src/renderer/src/runtime/web-session-close-replay.ts new file mode 100644 index 000000000000..ecfe9d9507ea --- /dev/null +++ b/src/renderer/src/runtime/web-session-close-replay.ts @@ -0,0 +1,114 @@ +// Why: a user's close of a paired host's tab prunes the local mirror at once, so a close the host +// never received (the connection dropped) would otherwise be lost and the host's next snapshot +// brings the tab back. The close is kept here and sent again once the host is reachable. + +import { webSessionIntentOwnerKey, type WebSessionIntentOwner } from './web-session-intent-owner' + +/** Bounded so a host that keeps failing the close hands the tab back instead of hiding it forever. */ +export const MAX_WEB_SESSION_CLOSE_REPLAY_ATTEMPTS = 3 +const MAX_PENDING_WEB_SESSION_CLOSE_REPLAYS = 256 + +export type WebSessionCloseReplay = { + owner: WebSessionIntentOwner + worktreeId: string + /** Every host id the close suppressed; the first is the one sent. */ + hostTabIds: readonly string[] + attempts: number + inFlight: boolean +} + +const pendingReplays = new Map() + +function replayPartitionPrefix(owner: WebSessionIntentOwner, worktreeId: string): string { + return `${webSessionIntentOwnerKey(owner)}\0${worktreeId}\0` +} + +function replayKey(owner: WebSessionIntentOwner, worktreeId: string, hostTabId: string): string { + return `${replayPartitionPrefix(owner, worktreeId)}${hostTabId}` +} + +/** Keeps an unsent user close; a repeat for the same tab keeps its attempt count. */ +export function queueWebSessionCloseReplay( + owner: WebSessionIntentOwner, + worktreeId: string, + hostTabIds: readonly string[] +): void { + const [primary] = hostTabIds + if (!worktreeId || !primary) { + return + } + const key = replayKey(owner, worktreeId, primary) + if (pendingReplays.has(key)) { + return + } + while (pendingReplays.size >= MAX_PENDING_WEB_SESSION_CLOSE_REPLAYS) { + const oldest = pendingReplays.keys().next() + if (oldest.done) { + break + } + pendingReplays.delete(oldest.value) + } + pendingReplays.set(key, { owner, worktreeId, hostTabIds, attempts: 0, inFlight: false }) +} + +/** + * The replays a host snapshot makes due: one that still lists the tab proves the host is reachable + * and still holds it. A replay whose tab the snapshot no longer lists is done -- the host removed it. + */ +export function takeDueWebSessionCloseReplays( + owner: WebSessionIntentOwner, + worktreeId: string, + presentHostTabIds: ReadonlySet +): WebSessionCloseReplay[] { + const prefix = replayPartitionPrefix(owner, worktreeId) + const due: WebSessionCloseReplay[] = [] + for (const [key, replay] of pendingReplays) { + if (!key.startsWith(prefix)) { + continue + } + if (!replay.hostTabIds.some((hostTabId) => presentHostTabIds.has(hostTabId))) { + pendingReplays.delete(key) + continue + } + if (!replay.inFlight) { + replay.inFlight = true + replay.attempts += 1 + due.push(replay) + } + } + return due +} + +/** 'gave-up' means the caller must stop hiding the tab: the host kept refusing the close. */ +export function settleWebSessionCloseReplay( + replay: WebSessionCloseReplay, + delivered: boolean +): 'done' | 'retry' | 'gave-up' { + const key = replayKey(replay.owner, replay.worktreeId, replay.hostTabIds[0]) + if (pendingReplays.get(key) !== replay) { + return 'done' + } + if (delivered) { + pendingReplays.delete(key) + return 'done' + } + replay.inFlight = false + if (replay.attempts >= MAX_WEB_SESSION_CLOSE_REPLAY_ATTEMPTS) { + pendingReplays.delete(key) + return 'gave-up' + } + return 'retry' +} + +export function clearWebSessionCloseReplaysForOwner(owner: WebSessionIntentOwner): void { + const prefix = `${webSessionIntentOwnerKey(owner)}\0` + for (const key of pendingReplays.keys()) { + if (key.startsWith(prefix)) { + pendingReplays.delete(key) + } + } +} + +export function resetWebSessionCloseReplaysForTests(): void { + pendingReplays.clear() +} diff --git a/src/renderer/src/runtime/web-session-tabs-sync/apply-preparation-base.ts b/src/renderer/src/runtime/web-session-tabs-sync/apply-preparation-base.ts index 65166ab8e790..5de3155537f0 100644 --- a/src/renderer/src/runtime/web-session-tabs-sync/apply-preparation-base.ts +++ b/src/renderer/src/runtime/web-session-tabs-sync/apply-preparation-base.ts @@ -10,6 +10,7 @@ import { reconcileWebSessionCloseIntents, isWebSessionCloseIntentPending } from '../web-session-close-intent' +import { takeDueWebSessionCloseReplays } from '../web-session-close-replay' import { peekWebSessionFocusIntent, resolveWebSessionVisibleTabId, @@ -42,11 +43,19 @@ export function prepareWebSessionTabsSnapshotBase( ) { const snapshotHostTabId = (tab: RuntimeMobileSessionTabsResult['tabs'][number]): string => tab.type === 'terminal' ? tab.parentTabId : tab.id - reconcileWebSessionCloseIntents( + const presentHostTabIds = new Set(rawSnapshot.tabs.map((tab) => snapshotHostTabId(tab))) + reconcileWebSessionCloseIntents({ environmentId }, worktreeId, presentHostTabIds) + // A snapshot proves the host reachable again, so a close it never received is sent now. + const dueCloseReplays = takeDueWebSessionCloseReplays( { environmentId }, worktreeId, - new Set(rawSnapshot.tabs.map((tab) => snapshotHostTabId(tab))) + presentHostTabIds ) + if (dueCloseReplays.length > 0) { + void import('../web-runtime-session-tab-lifecycle').then(({ replayWebSessionTabCloses }) => + replayWebSessionTabCloses(environmentId, dueCloseReplays) + ) + } const snapshot: RuntimeMobileSessionTabsResult = rawSnapshot.tabs.some((tab) => isWebSessionCloseIntentPending({ environmentId }, worktreeId, snapshotHostTabId(tab), now) ) diff --git a/src/renderer/src/runtime/web-session-tabs-sync/global-session-subscription.ts b/src/renderer/src/runtime/web-session-tabs-sync/global-session-subscription.ts index 9fde3b75ad84..08a5a116762a 100644 --- a/src/renderer/src/runtime/web-session-tabs-sync/global-session-subscription.ts +++ b/src/renderer/src/runtime/web-session-tabs-sync/global-session-subscription.ts @@ -1,5 +1,6 @@ import { getRuntimeEnvironmentRevision } from '../runtime-environment-revision' import { clearWebSessionCloseIntentsForOwner } from '../web-session-close-intent' +import { clearWebSessionCloseReplaysForOwner } from '../web-session-close-replay' import { clearWebSessionFocusIntentsForOwner } from '../web-session-focus-intent' import { clearWebSessionReorderIntentsForOwner } from '../web-session-reorder-intent' import { @@ -213,6 +214,7 @@ export function installGlobalSessionTabsSubscriptions({ for (const { environmentId, expectedEnvironmentPairingRevision } of environments) { const owner = { environmentId, pairingRevision: expectedEnvironmentPairingRevision } clearWebSessionCloseIntentsForOwner(owner) + clearWebSessionCloseReplaysForOwner(owner) clearWebSessionFocusIntentsForOwner(owner) clearWebSessionReorderIntentsForOwner(owner) } From ab88832867dfe9fb7ea30d93c4dc259cb9f2fb55 Mon Sep 17 00:00:00 2001 From: Neil Date: Thu, 15 Oct 2026 22:40:12 -0700 Subject: [PATCH 2/6] fix(remote): replay held closes at snapshot receipt, pinned to their pairing Codex review: an unchanged reconnect snapshot is filtered before apply, so the replay now fires when any snapshot is received; a replay is refused once the environment is re-paired; replays survive a subscription reinstall and re-assert their hide; giving up re-accepts the current snapshot so the tab actually returns. --- ...runtime-session-tab-activate-close.test.ts | 15 ++++++++ .../web-runtime-session-tab-lifecycle.ts | 26 +++++++++++--- .../runtime/web-session-close-replay.test.ts | 8 +++-- .../src/runtime/web-session-close-replay.ts | 34 ++++++++++++++++--- .../apply-preparation-base.ts | 13 ++----- .../global-session-subscription.ts | 2 -- .../runtime/web-session-tabs-sync/tracking.ts | 4 +++ 7 files changed, 77 insertions(+), 25 deletions(-) diff --git a/src/renderer/src/runtime/web-runtime-session-tab-activate-close.test.ts b/src/renderer/src/runtime/web-runtime-session-tab-activate-close.test.ts index 5dcbee1f5d5b..1fe4d5305bb8 100644 --- a/src/renderer/src/runtime/web-runtime-session-tab-activate-close.test.ts +++ b/src/renderer/src/runtime/web-runtime-session-tab-activate-close.test.ts @@ -6,6 +6,7 @@ import { replayWebSessionTabCloses } from './web-runtime-session-tab-lifecycle' import { + queueWebSessionCloseReplay, resetWebSessionCloseReplaysForTests, takeDueWebSessionCloseReplays } from './web-session-close-replay' @@ -651,6 +652,20 @@ describe('web runtime session tab actions', () => { ).toEqual([]) }) + it('never replays a held close to an environment re-paired since', async () => { + const runtimeCall = vi.fn() + stubRuntimeEnvironmentBridge({ call: runtimeCall }) + const staleOwner = { environmentId: ENVIRONMENT_ID, pairingRevision: 99 } + queueWebSessionCloseReplay(staleOwner, WORKTREE_ID, ['host-browser-unified']) + + await replayWebSessionTabCloses( + ENVIRONMENT_ID, + takeDueWebSessionCloseReplays(staleOwner, WORKTREE_ID, new Set(['host-browser-unified'])) + ) + + expect(runtimeCall).not.toHaveBeenCalled() + }) + it('does not hold a lifecycle close the host never received', async () => { stubRuntimeEnvironmentBridge({ call: vi.fn().mockRejectedValue(new Error('socket hang up')) }) diff --git a/src/renderer/src/runtime/web-runtime-session-tab-lifecycle.ts b/src/renderer/src/runtime/web-runtime-session-tab-lifecycle.ts index a8e0803cbdd8..7c19fa07b34c 100644 --- a/src/renderer/src/runtime/web-runtime-session-tab-lifecycle.ts +++ b/src/renderer/src/runtime/web-runtime-session-tab-lifecycle.ts @@ -30,7 +30,8 @@ import { toHostSessionTabId } from '../../../shared/terminal-surface-id' import { captureRuntimeEnvironmentCall, captureWebSessionIntentOwner, - isWebRuntimeSessionActive + isWebRuntimeSessionActive, + matchesWebSessionIntentOwner } from './web-runtime-session-environment' import { refreshWebRuntimeSessionTabsSnapshot } from './web-runtime-session-snapshot' @@ -83,6 +84,8 @@ export async function closeWebRuntimeSessionTab(args: { reason: RuntimeSessionTabCloseReason publicationEpoch?: string | null terminalHandle?: string | null + /** A replay's pairing; the call is refused if the environment was re-paired since. */ + expectedPairingRevision?: number }): Promise { return callWebRuntimeSessionTabMethod('session.tabs.close', args) } @@ -119,11 +122,19 @@ export async function replayWebSessionTabCloses( replays: readonly WebSessionCloseReplay[] ): Promise { for (const replay of replays) { + // Why: the close was the old pairing's; a replacement host must never receive it. + if (!matchesWebSessionIntentOwner(replay.owner)) { + settleWebSessionCloseReplay(replay, true) + continue + } const outcome = await closeWebRuntimeSessionTab({ worktreeId: replay.worktreeId, tabId: replay.hostTabIds[0], environmentId, - reason: 'user' + reason: 'user', + ...(replay.owner.pairingRevision !== undefined + ? { expectedPairingRevision: replay.owner.pairingRevision } + : {}) }) if (settleWebSessionCloseReplay(replay, outcome !== 'failed') !== 'gave-up') { continue @@ -132,7 +143,10 @@ export async function replayWebSessionTabCloses( for (const hostTabId of replay.hostTabIds) { clearWebSessionCloseIntent(replay.owner, replay.worktreeId, hostTabId) } - await refreshWebRuntimeSessionTabsSnapshot(environmentId, replay.worktreeId) + // The unchanged snapshot that made this replay due would otherwise be refused as stale. + await refreshWebRuntimeSessionTabsSnapshot(environmentId, replay.worktreeId, { + acceptCurrentSnapshot: true + }) } } @@ -155,6 +169,7 @@ async function callWebRuntimeSessionTabMethod( terminalHandle?: string | null leafId?: string | null expectedCurrentLocalTabId?: string | null + expectedPairingRevision?: number } ): Promise { const environmentId = resolveTabEnvironmentId(args.environmentId) @@ -166,7 +181,10 @@ async function callWebRuntimeSessionTabMethod( } return 'failed' } - const intentOwner = captureWebSessionIntentOwner(environmentId) + const intentOwner = + args.expectedPairingRevision !== undefined + ? { environmentId, pairingRevision: args.expectedPairingRevision } + : captureWebSessionIntentOwner(environmentId) const callEnvironment = captureRuntimeEnvironmentCall(environmentId, intentOwner.pairingRevision) const closeIntentTabIds = new Set() let activationHostTabId: string | null = null diff --git a/src/renderer/src/runtime/web-session-close-replay.test.ts b/src/renderer/src/runtime/web-session-close-replay.test.ts index 42c5a317be40..e61e2d02a3c6 100644 --- a/src/renderer/src/runtime/web-session-close-replay.test.ts +++ b/src/renderer/src/runtime/web-session-close-replay.test.ts @@ -8,7 +8,7 @@ import { settleWebSessionCloseReplay, takeDueWebSessionCloseReplays } from './web-session-close-replay' -import { recordWebSessionCloseIntent } from './web-session-close-intent' +import { recordReceivedWebSessionTabsSnapshot } from './web-session-tabs-sync/tracking' import { applyWebSessionTabsSnapshot } from './web-session-tabs-sync/snapshot-api' import { ENV, @@ -94,10 +94,12 @@ describe('web session close replay', () => { }) it('sends the held close when a host snapshot arrives, while keeping the tab hidden', async () => { - recordWebSessionCloseIntent(OWNER, WT, 'host-tab-1', NOW) queueWebSessionCloseReplay(OWNER, WT, ['host-tab-1']) + const snapshot = makeSnapshot([SURFACE]) - const patch = applyWebSessionTabsSnapshot(makeState(), makeSnapshot([SURFACE]), ENV, NOW) + // Receipt, not apply: the reconnect snapshot is unchanged, so it may never be applied. + recordReceivedWebSessionTabsSnapshot(ENV, snapshot) + const patch = applyWebSessionTabsSnapshot(makeState(), snapshot, ENV, NOW) expect((patch.tabsByWorktree?.[WT] ?? []).map((tab) => tab.id)).not.toContain( toWebTerminalSurfaceTabId('host-tab-1') diff --git a/src/renderer/src/runtime/web-session-close-replay.ts b/src/renderer/src/runtime/web-session-close-replay.ts index ecfe9d9507ea..682ed225a7f7 100644 --- a/src/renderer/src/runtime/web-session-close-replay.ts +++ b/src/renderer/src/runtime/web-session-close-replay.ts @@ -2,6 +2,11 @@ // never received (the connection dropped) would otherwise be lost and the host's next snapshot // brings the tab back. The close is kept here and sent again once the host is reachable. +import type { RuntimeMobileSessionTabsResult } from '../../../shared/runtime-types' +import { + makeWebSessionCloseIntentDurable, + recordWebSessionCloseIntent +} from './web-session-close-intent' import { webSessionIntentOwnerKey, type WebSessionIntentOwner } from './web-session-intent-owner' /** Bounded so a host that keeps failing the close hands the tab back instead of hiding it forever. */ @@ -100,13 +105,32 @@ export function settleWebSessionCloseReplay( return 'retry' } -export function clearWebSessionCloseReplaysForOwner(owner: WebSessionIntentOwner): void { - const prefix = `${webSessionIntentOwnerKey(owner)}\0` - for (const key of pendingReplays.keys()) { - if (key.startsWith(prefix)) { - pendingReplays.delete(key) +/** Sends the closes a received host snapshot made due; see `takeDueWebSessionCloseReplays`. */ +export function replayWebSessionClosesDueForSnapshot( + environmentId: string, + snapshot: RuntimeMobileSessionTabsResult | { worktree: string; removed: true } +): void { + if (pendingReplays.size === 0 || !('tabs' in snapshot)) { + return + } + const presentHostTabIds = new Set( + snapshot.tabs.map((tab) => (tab.type === 'terminal' ? tab.parentTabId : tab.id)) + ) + const due = takeDueWebSessionCloseReplays({ environmentId }, snapshot.worktree, presentHostTabIds) + if (due.length === 0) { + return + } + // Why re-assert: a subscription reinstall clears close intents, and this snapshot lists the tab. + for (const replay of due) { + for (const hostTabId of replay.hostTabIds) { + recordWebSessionCloseIntent(replay.owner, replay.worktreeId, hostTabId, Date.now()) + makeWebSessionCloseIntentDurable(replay.owner, replay.worktreeId, hostTabId) } } + // Lazy: the lifecycle module reaches the store, which loads this module. + void import('./web-runtime-session-tab-lifecycle').then(({ replayWebSessionTabCloses }) => + replayWebSessionTabCloses(environmentId, due) + ) } export function resetWebSessionCloseReplaysForTests(): void { diff --git a/src/renderer/src/runtime/web-session-tabs-sync/apply-preparation-base.ts b/src/renderer/src/runtime/web-session-tabs-sync/apply-preparation-base.ts index 5de3155537f0..65166ab8e790 100644 --- a/src/renderer/src/runtime/web-session-tabs-sync/apply-preparation-base.ts +++ b/src/renderer/src/runtime/web-session-tabs-sync/apply-preparation-base.ts @@ -10,7 +10,6 @@ import { reconcileWebSessionCloseIntents, isWebSessionCloseIntentPending } from '../web-session-close-intent' -import { takeDueWebSessionCloseReplays } from '../web-session-close-replay' import { peekWebSessionFocusIntent, resolveWebSessionVisibleTabId, @@ -43,19 +42,11 @@ export function prepareWebSessionTabsSnapshotBase( ) { const snapshotHostTabId = (tab: RuntimeMobileSessionTabsResult['tabs'][number]): string => tab.type === 'terminal' ? tab.parentTabId : tab.id - const presentHostTabIds = new Set(rawSnapshot.tabs.map((tab) => snapshotHostTabId(tab))) - reconcileWebSessionCloseIntents({ environmentId }, worktreeId, presentHostTabIds) - // A snapshot proves the host reachable again, so a close it never received is sent now. - const dueCloseReplays = takeDueWebSessionCloseReplays( + reconcileWebSessionCloseIntents( { environmentId }, worktreeId, - presentHostTabIds + new Set(rawSnapshot.tabs.map((tab) => snapshotHostTabId(tab))) ) - if (dueCloseReplays.length > 0) { - void import('../web-runtime-session-tab-lifecycle').then(({ replayWebSessionTabCloses }) => - replayWebSessionTabCloses(environmentId, dueCloseReplays) - ) - } const snapshot: RuntimeMobileSessionTabsResult = rawSnapshot.tabs.some((tab) => isWebSessionCloseIntentPending({ environmentId }, worktreeId, snapshotHostTabId(tab), now) ) diff --git a/src/renderer/src/runtime/web-session-tabs-sync/global-session-subscription.ts b/src/renderer/src/runtime/web-session-tabs-sync/global-session-subscription.ts index 08a5a116762a..9fde3b75ad84 100644 --- a/src/renderer/src/runtime/web-session-tabs-sync/global-session-subscription.ts +++ b/src/renderer/src/runtime/web-session-tabs-sync/global-session-subscription.ts @@ -1,6 +1,5 @@ import { getRuntimeEnvironmentRevision } from '../runtime-environment-revision' import { clearWebSessionCloseIntentsForOwner } from '../web-session-close-intent' -import { clearWebSessionCloseReplaysForOwner } from '../web-session-close-replay' import { clearWebSessionFocusIntentsForOwner } from '../web-session-focus-intent' import { clearWebSessionReorderIntentsForOwner } from '../web-session-reorder-intent' import { @@ -214,7 +213,6 @@ export function installGlobalSessionTabsSubscriptions({ for (const { environmentId, expectedEnvironmentPairingRevision } of environments) { const owner = { environmentId, pairingRevision: expectedEnvironmentPairingRevision } clearWebSessionCloseIntentsForOwner(owner) - clearWebSessionCloseReplaysForOwner(owner) clearWebSessionFocusIntentsForOwner(owner) clearWebSessionReorderIntentsForOwner(owner) } diff --git a/src/renderer/src/runtime/web-session-tabs-sync/tracking.ts b/src/renderer/src/runtime/web-session-tabs-sync/tracking.ts index 2fd995d09286..6020b0abfb92 100644 --- a/src/renderer/src/runtime/web-session-tabs-sync/tracking.ts +++ b/src/renderer/src/runtime/web-session-tabs-sync/tracking.ts @@ -23,6 +23,7 @@ import { recordReceivedWebSessionTabsEnvironmentFrame } from './publisher-identity-fences' import { hostSnapshotAffirmsWorktreeContents } from '../host-session-snapshot-authority' +import { replayWebSessionClosesDueForSnapshot } from '../web-session-close-replay' export function isSessionTabsListAllResult(value: unknown): value is SessionTabsListAllResult { return ( @@ -102,6 +103,9 @@ export function recordReceivedWebSessionTabsSnapshot( return frame } recordReceivedWebSessionTabsEnvironmentFrame(environmentId, frame) + // Why at receipt: an unchanged snapshot is filtered before it is applied, and the reconnect + // snapshot is unchanged precisely when the host never received the close. + replayWebSessionClosesDueForSnapshot(environmentId, snapshot) const publicationEpoch = snapshot.publicationEpoch const isRetraction = 'removed' in snapshot && snapshot.removed === true const history = sessionTabsPublicationEpochHistoryByWorktree.get(key) From 82b60d8e3e254c0c70931abd016c8b38ec63557a Mon Sep 17 00:00:00 2001 From: Neil Date: Thu, 15 Oct 2026 22:44:34 -0700 Subject: [PATCH 3/6] fix(remote): consume held closes only on authoritative snapshots, and unhide evicted ones Codex review: an unpublished or retired-epoch frame could drop a pending replay, and an evicted replay kept its tab hidden with nothing left to send. --- .../runtime/web-session-close-replay.test.ts | 25 +++++++++++++++++++ .../src/runtime/web-session-close-replay.ts | 12 ++++++--- .../runtime/web-session-tabs-sync/tracking.ts | 9 ++++--- 3 files changed, 40 insertions(+), 6 deletions(-) diff --git a/src/renderer/src/runtime/web-session-close-replay.test.ts b/src/renderer/src/runtime/web-session-close-replay.test.ts index e61e2d02a3c6..d7dda3b68c2b 100644 --- a/src/renderer/src/runtime/web-session-close-replay.test.ts +++ b/src/renderer/src/runtime/web-session-close-replay.test.ts @@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { toWebTerminalSurfaceTabId } from '../../../shared/terminal-surface-id' import { + MAX_PENDING_WEB_SESSION_CLOSE_REPLAYS, MAX_WEB_SESSION_CLOSE_REPLAY_ATTEMPTS, queueWebSessionCloseReplay, resetWebSessionCloseReplaysForTests, @@ -9,6 +10,11 @@ import { takeDueWebSessionCloseReplays } from './web-session-close-replay' import { recordReceivedWebSessionTabsSnapshot } from './web-session-tabs-sync/tracking' +import { + isWebSessionCloseIntentPending, + makeWebSessionCloseIntentDurable, + recordWebSessionCloseIntent +} from './web-session-close-intent' import { applyWebSessionTabsSnapshot } from './web-session-tabs-sync/snapshot-api' import { ENV, @@ -93,6 +99,25 @@ describe('web session close replay', () => { ).toEqual([]) }) + it('keeps a held close through a snapshot that cannot state the worktree contents', () => { + queueWebSessionCloseReplay(OWNER, WT, ['host-tab-1']) + + recordReceivedWebSessionTabsSnapshot(ENV, makeSnapshot([], { publicationEpoch: 'none' })) + + expect(takeDueWebSessionCloseReplays(OWNER, WT, new Set(['host-tab-1']))).toHaveLength(1) + }) + + it('stops hiding a tab whose held close is evicted', () => { + queueWebSessionCloseReplay(OWNER, WT, ['host-tab-0']) + recordWebSessionCloseIntent(OWNER, WT, 'host-tab-0', NOW) + makeWebSessionCloseIntentDurable(OWNER, WT, 'host-tab-0') + for (let index = 1; index <= MAX_PENDING_WEB_SESSION_CLOSE_REPLAYS; index += 1) { + queueWebSessionCloseReplay(OWNER, WT, [`host-tab-${index}`]) + } + + expect(isWebSessionCloseIntentPending(OWNER, WT, 'host-tab-0', NOW)).toBe(false) + }) + it('sends the held close when a host snapshot arrives, while keeping the tab hidden', async () => { queueWebSessionCloseReplay(OWNER, WT, ['host-tab-1']) const snapshot = makeSnapshot([SURFACE]) diff --git a/src/renderer/src/runtime/web-session-close-replay.ts b/src/renderer/src/runtime/web-session-close-replay.ts index 682ed225a7f7..877f56713af4 100644 --- a/src/renderer/src/runtime/web-session-close-replay.ts +++ b/src/renderer/src/runtime/web-session-close-replay.ts @@ -4,6 +4,7 @@ import type { RuntimeMobileSessionTabsResult } from '../../../shared/runtime-types' import { + clearWebSessionCloseIntent, makeWebSessionCloseIntentDurable, recordWebSessionCloseIntent } from './web-session-close-intent' @@ -11,7 +12,7 @@ import { webSessionIntentOwnerKey, type WebSessionIntentOwner } from './web-sess /** Bounded so a host that keeps failing the close hands the tab back instead of hiding it forever. */ export const MAX_WEB_SESSION_CLOSE_REPLAY_ATTEMPTS = 3 -const MAX_PENDING_WEB_SESSION_CLOSE_REPLAYS = 256 +export const MAX_PENDING_WEB_SESSION_CLOSE_REPLAYS = 256 export type WebSessionCloseReplay = { owner: WebSessionIntentOwner @@ -47,11 +48,16 @@ export function queueWebSessionCloseReplay( return } while (pendingReplays.size >= MAX_PENDING_WEB_SESSION_CLOSE_REPLAYS) { - const oldest = pendingReplays.keys().next() + const oldest = pendingReplays.entries().next() if (oldest.done) { break } - pendingReplays.delete(oldest.value) + const [oldestKey, evicted] = oldest.value + pendingReplays.delete(oldestKey) + // An evicted close is never sent again, so it must stop hiding its tab. + for (const hostTabId of evicted.hostTabIds) { + clearWebSessionCloseIntent(evicted.owner, evicted.worktreeId, hostTabId) + } } pendingReplays.set(key, { owner, worktreeId, hostTabIds, attempts: 0, inFlight: false }) } diff --git a/src/renderer/src/runtime/web-session-tabs-sync/tracking.ts b/src/renderer/src/runtime/web-session-tabs-sync/tracking.ts index 6020b0abfb92..4be0049e8bf9 100644 --- a/src/renderer/src/runtime/web-session-tabs-sync/tracking.ts +++ b/src/renderer/src/runtime/web-session-tabs-sync/tracking.ts @@ -103,9 +103,6 @@ export function recordReceivedWebSessionTabsSnapshot( return frame } recordReceivedWebSessionTabsEnvironmentFrame(environmentId, frame) - // Why at receipt: an unchanged snapshot is filtered before it is applied, and the reconnect - // snapshot is unchanged precisely when the host never received the close. - replayWebSessionClosesDueForSnapshot(environmentId, snapshot) const publicationEpoch = snapshot.publicationEpoch const isRetraction = 'removed' in snapshot && snapshot.removed === true const history = sessionTabsPublicationEpochHistoryByWorktree.get(key) @@ -115,6 +112,12 @@ export function recordReceivedWebSessionTabsSnapshot( if (isRetiredSessionTabsPublicationEpoch(key, publicationEpoch)) { return frame } + // Why at receipt: an unchanged snapshot is filtered before it is applied, and the reconnect + // snapshot is unchanged precisely when the host never received the close. Only a frame that + // states the worktree's contents may prove the host still holds, or no longer holds, the tab. + if (!isRetraction && hostSnapshotAffirmsWorktreeContents(snapshot)) { + replayWebSessionClosesDueForSnapshot(environmentId, snapshot) + } // Neither a retraction nor a "nothing published yet" placeholder takes over publishing this // worktree, so neither may be noted as current: doing so retires the generation that is still // live and fences its next frame out of its own worktree. From 34fe7fe6937fb4f1c38bd883ecef3f49da68af3b Mon Sep 17 00:00:00 2001 From: Neil Date: Thu, 15 Oct 2026 22:49:11 -0700 Subject: [PATCH 4/6] fix(remote): keep held closes through incomplete inventories, and re-hide in-flight ones Codex review: a real-epoch snapshot can omit tabs it is unsure of, so absence no longer drops a held close; and a snapshot listing a tab whose close is in flight re-asserts its hide after a subscription reinstall. --- .../runtime/web-session-close-replay.test.ts | 15 +++++- .../src/runtime/web-session-close-replay.ts | 46 ++++++++++++------- 2 files changed, 43 insertions(+), 18 deletions(-) diff --git a/src/renderer/src/runtime/web-session-close-replay.test.ts b/src/renderer/src/runtime/web-session-close-replay.test.ts index d7dda3b68c2b..dab8088a9133 100644 --- a/src/renderer/src/runtime/web-session-close-replay.test.ts +++ b/src/renderer/src/runtime/web-session-close-replay.test.ts @@ -67,11 +67,22 @@ describe('web session close replay', () => { expect(takeDueWebSessionCloseReplays(OWNER, WT, new Set(['host-tab-1']))).toEqual([]) }) - it('is done without a send when the host no longer lists the tab', () => { + it('keeps a held close through a snapshot that omits the tab', () => { queueWebSessionCloseReplay(OWNER, WT, ['host-tab-1']) + // An incomplete inventory omits tabs too, so absence is not proof the host removed it. expect(takeDueWebSessionCloseReplays(OWNER, WT, new Set())).toEqual([]) - expect(takeDueWebSessionCloseReplays(OWNER, WT, new Set(['host-tab-1']))).toEqual([]) + expect(takeDueWebSessionCloseReplays(OWNER, WT, new Set(['host-tab-1']))).toHaveLength(1) + }) + + it('re-hides a tab whose close is in flight when a snapshot lists it again', () => { + queueWebSessionCloseReplay(OWNER, WT, ['host-tab-1']) + takeDueWebSessionCloseReplays(OWNER, WT, new Set(['host-tab-1'])) + + recordReceivedWebSessionTabsSnapshot(ENV, makeSnapshot([SURFACE])) + + expect(isWebSessionCloseIntentPending(OWNER, WT, 'host-tab-1', NOW)).toBe(true) + expect(replayWebSessionTabCloses).not.toHaveBeenCalled() }) it('gives up after a bounded number of undelivered sends', () => { diff --git a/src/renderer/src/runtime/web-session-close-replay.ts b/src/renderer/src/runtime/web-session-close-replay.ts index 877f56713af4..b1ac92cb8686 100644 --- a/src/renderer/src/runtime/web-session-close-replay.ts +++ b/src/renderer/src/runtime/web-session-close-replay.ts @@ -62,25 +62,33 @@ export function queueWebSessionCloseReplay( pendingReplays.set(key, { owner, worktreeId, hostTabIds, attempts: 0, inFlight: false }) } +/** Held closes whose tab this snapshot lists, in flight or not. */ +function listHeldWebSessionCloseReplays( + owner: WebSessionIntentOwner, + worktreeId: string, + presentHostTabIds: ReadonlySet +): WebSessionCloseReplay[] { + const prefix = replayPartitionPrefix(owner, worktreeId) + return [...pendingReplays].flatMap(([key, replay]) => + key.startsWith(prefix) && + replay.hostTabIds.some((hostTabId) => presentHostTabIds.has(hostTabId)) + ? [replay] + : [] + ) +} + /** * The replays a host snapshot makes due: one that still lists the tab proves the host is reachable - * and still holds it. A replay whose tab the snapshot no longer lists is done -- the host removed it. + * and still holds it. Absence is not treated as removal, because an incomplete inventory omits + * tabs too; a close whose tab never returns ends at delivery, give-up, or eviction. */ export function takeDueWebSessionCloseReplays( owner: WebSessionIntentOwner, worktreeId: string, presentHostTabIds: ReadonlySet ): WebSessionCloseReplay[] { - const prefix = replayPartitionPrefix(owner, worktreeId) const due: WebSessionCloseReplay[] = [] - for (const [key, replay] of pendingReplays) { - if (!key.startsWith(prefix)) { - continue - } - if (!replay.hostTabIds.some((hostTabId) => presentHostTabIds.has(hostTabId))) { - pendingReplays.delete(key) - continue - } + for (const replay of listHeldWebSessionCloseReplays(owner, worktreeId, presentHostTabIds)) { if (!replay.inFlight) { replay.inFlight = true replay.attempts += 1 @@ -122,17 +130,23 @@ export function replayWebSessionClosesDueForSnapshot( const presentHostTabIds = new Set( snapshot.tabs.map((tab) => (tab.type === 'terminal' ? tab.parentTabId : tab.id)) ) - const due = takeDueWebSessionCloseReplays({ environmentId }, snapshot.worktree, presentHostTabIds) - if (due.length === 0) { - return - } - // Why re-assert: a subscription reinstall clears close intents, and this snapshot lists the tab. - for (const replay of due) { + const owner = { environmentId } + // Why every held close, in flight too: a subscription reinstall clears close intents, and this + // snapshot lists the tab. + for (const replay of listHeldWebSessionCloseReplays( + owner, + snapshot.worktree, + presentHostTabIds + )) { for (const hostTabId of replay.hostTabIds) { recordWebSessionCloseIntent(replay.owner, replay.worktreeId, hostTabId, Date.now()) makeWebSessionCloseIntentDurable(replay.owner, replay.worktreeId, hostTabId) } } + const due = takeDueWebSessionCloseReplays(owner, snapshot.worktree, presentHostTabIds) + if (due.length === 0) { + return + } // Lazy: the lifecycle module reaches the store, which loads this module. void import('./web-runtime-session-tab-lifecycle').then(({ replayWebSessionTabCloses }) => replayWebSessionTabCloses(environmentId, due) From d9ce98746355c738641f1b94a544ce56440b2a94 Mon Sep 17 00:00:00 2001 From: Neil Date: Thu, 15 Oct 2026 22:53:50 -0700 Subject: [PATCH 5/6] fix(remote): re-list the worktree after a failed close replay Codex review: subscriptions are change-driven, so an idle worktree might never publish the snapshot that makes the next attempt due. --- ...runtime-session-tab-activate-close.test.ts | 30 +++++++++++++++++++ .../web-runtime-session-tab-lifecycle.ts | 13 +++++++- 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/src/renderer/src/runtime/web-runtime-session-tab-activate-close.test.ts b/src/renderer/src/runtime/web-runtime-session-tab-activate-close.test.ts index 1fe4d5305bb8..cde5e008c4a7 100644 --- a/src/renderer/src/runtime/web-runtime-session-tab-activate-close.test.ts +++ b/src/renderer/src/runtime/web-runtime-session-tab-activate-close.test.ts @@ -652,6 +652,36 @@ describe('web runtime session tab actions', () => { ).toEqual([]) }) + it('re-lists the worktree after a failed replay so an idle host still gets the next attempt', async () => { + vi.useFakeTimers() + try { + const runtimeCall = vi.fn().mockRejectedValue(new Error('socket hang up')) + stubRuntimeEnvironmentBridge({ call: runtimeCall }) + const owner = { environmentId: ENVIRONMENT_ID } + queueWebSessionCloseReplay(owner, WORKTREE_ID, ['host-browser-unified']) + + await replayWebSessionTabCloses( + ENVIRONMENT_ID, + takeDueWebSessionCloseReplays(owner, WORKTREE_ID, new Set(['host-browser-unified'])) + ) + const callsAfterReplay = runtimeCall.mock.calls.length + await vi.advanceTimersByTimeAsync(5_000) + + const relisted = runtimeCall.mock.calls + .slice(callsAfterReplay) + .some( + ([request]: unknown[]) => + typeof request === 'object' && + request !== null && + 'method' in request && + request.method === 'session.tabs.list' + ) + expect(relisted).toBe(true) + } finally { + vi.useRealTimers() + } + }) + it('never replays a held close to an environment re-paired since', async () => { const runtimeCall = vi.fn() stubRuntimeEnvironmentBridge({ call: runtimeCall }) diff --git a/src/renderer/src/runtime/web-runtime-session-tab-lifecycle.ts b/src/renderer/src/runtime/web-runtime-session-tab-lifecycle.ts index 7c19fa07b34c..998cb32e99fb 100644 --- a/src/renderer/src/runtime/web-runtime-session-tab-lifecycle.ts +++ b/src/renderer/src/runtime/web-runtime-session-tab-lifecycle.ts @@ -116,6 +116,8 @@ function holdUndeliveredUserClose( queueWebSessionCloseReplay(intentOwner, worktreeId, hostTabIds) } +const WEB_SESSION_CLOSE_REPLAY_RETRY_DELAY_MS = 5_000 + /** Sends again the user closes a host snapshot proved reachable; see `takeDueWebSessionCloseReplays`. */ export async function replayWebSessionTabCloses( environmentId: string, @@ -136,7 +138,16 @@ export async function replayWebSessionTabCloses( ? { expectedPairingRevision: replay.owner.pairingRevision } : {}) }) - if (settleWebSessionCloseReplay(replay, outcome !== 'failed') !== 'gave-up') { + const settled = settleWebSessionCloseReplay(replay, outcome !== 'failed') + if (settled === 'retry') { + // Why a re-list: subscriptions are change-driven, so an idle worktree may never publish the + // snapshot that makes the next attempt due. The re-list's receipt does. + setTimeout(() => { + void refreshWebRuntimeSessionTabsSnapshot(environmentId, replay.worktreeId) + }, WEB_SESSION_CLOSE_REPLAY_RETRY_DELAY_MS) + continue + } + if (settled === 'done') { continue } // The host kept failing the close; show the tab again rather than hide a live one forever. From e79d3c7bc41901edf1aa9d89c45835874c80d8e3 Mon Sep 17 00:00:00 2001 From: Neil Date: Thu, 15 Oct 2026 22:57:53 -0700 Subject: [PATCH 6/6] fix(remote): re-list the worktree as soon as a close is held Codex review: an idle host may publish nothing after a held close, so the first replay also needs a scheduled re-list. --- ...runtime-session-tab-activate-close.test.ts | 30 +++++++++++++++++++ .../web-runtime-session-tab-lifecycle.ts | 15 ++++++---- 2 files changed, 40 insertions(+), 5 deletions(-) diff --git a/src/renderer/src/runtime/web-runtime-session-tab-activate-close.test.ts b/src/renderer/src/runtime/web-runtime-session-tab-activate-close.test.ts index cde5e008c4a7..5592956f9807 100644 --- a/src/renderer/src/runtime/web-runtime-session-tab-activate-close.test.ts +++ b/src/renderer/src/runtime/web-runtime-session-tab-activate-close.test.ts @@ -652,6 +652,36 @@ describe('web runtime session tab actions', () => { ).toEqual([]) }) + it('re-lists the worktree after holding a close so an idle host still gets the first replay', async () => { + vi.useFakeTimers() + try { + const runtimeCall = vi.fn().mockRejectedValue(new Error('socket hang up')) + stubRuntimeEnvironmentBridge({ call: runtimeCall }) + + await closeWebRuntimeSessionTab({ + worktreeId: WORKTREE_ID, + tabId: 'local-browser-unified', + reason: 'user' + }) + const callsAfterClose = runtimeCall.mock.calls.length + await vi.advanceTimersByTimeAsync(5_000) + + expect( + runtimeCall.mock.calls + .slice(callsAfterClose) + .some( + ([request]: unknown[]) => + typeof request === 'object' && + request !== null && + 'method' in request && + request.method === 'session.tabs.list' + ) + ).toBe(true) + } finally { + vi.useRealTimers() + } + }) + it('re-lists the worktree after a failed replay so an idle host still gets the next attempt', async () => { vi.useFakeTimers() try { diff --git a/src/renderer/src/runtime/web-runtime-session-tab-lifecycle.ts b/src/renderer/src/runtime/web-runtime-session-tab-lifecycle.ts index 998cb32e99fb..6240cab600a0 100644 --- a/src/renderer/src/runtime/web-runtime-session-tab-lifecycle.ts +++ b/src/renderer/src/runtime/web-runtime-session-tab-lifecycle.ts @@ -114,10 +114,19 @@ function holdUndeliveredUserClose( makeWebSessionCloseIntentDurable(intentOwner, worktreeId, hostTabId) } queueWebSessionCloseReplay(intentOwner, worktreeId, hostTabIds) + scheduleWebSessionCloseReplayRelist(intentOwner.environmentId, worktreeId) } const WEB_SESSION_CLOSE_REPLAY_RETRY_DELAY_MS = 5_000 +// Why a re-list: subscriptions are change-driven, so an idle worktree may never publish the +// snapshot that makes the next attempt due. The re-list's receipt does. +function scheduleWebSessionCloseReplayRelist(environmentId: string, worktreeId: string): void { + setTimeout(() => { + void refreshWebRuntimeSessionTabsSnapshot(environmentId, worktreeId) + }, WEB_SESSION_CLOSE_REPLAY_RETRY_DELAY_MS) +} + /** Sends again the user closes a host snapshot proved reachable; see `takeDueWebSessionCloseReplays`. */ export async function replayWebSessionTabCloses( environmentId: string, @@ -140,11 +149,7 @@ export async function replayWebSessionTabCloses( }) const settled = settleWebSessionCloseReplay(replay, outcome !== 'failed') if (settled === 'retry') { - // Why a re-list: subscriptions are change-driven, so an idle worktree may never publish the - // snapshot that makes the next attempt due. The re-list's receipt does. - setTimeout(() => { - void refreshWebRuntimeSessionTabsSnapshot(environmentId, replay.worktreeId) - }, WEB_SESSION_CLOSE_REPLAY_RETRY_DELAY_MS) + scheduleWebSessionCloseReplayRelist(environmentId, replay.worktreeId) continue } if (settled === 'done') {