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..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 @@ -2,8 +2,14 @@ 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 { + queueWebSessionCloseReplay, + resetWebSessionCloseReplaysForTests, + takeDueWebSessionCloseReplays +} from './web-session-close-replay' import { peekWebSessionFocusIntent, resetWebSessionFocusIntentForTests @@ -87,7 +93,10 @@ vi.mock('./web-runtime-browser-materialization', () => ({ hasMaterializedWebRuntimeBrowserPage: mocks.hasMaterializedWebRuntimeBrowserPage })) -afterEach(() => resetWebSessionCloseIntentForTests()) +afterEach(() => { + resetWebSessionCloseIntentForTests() + resetWebSessionCloseReplaysForTests() +}) describe('web runtime session tab actions', () => { beforeEach(() => { @@ -595,6 +604,148 @@ 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('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 { + 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 }) + 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')) }) + + 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..6240cab600a0 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, @@ -21,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' @@ -74,10 +84,88 @@ 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) } +// 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) + 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, + 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', + ...(replay.owner.pairingRevision !== undefined + ? { expectedPairingRevision: replay.owner.pairingRevision } + : {}) + }) + const settled = settleWebSessionCloseReplay(replay, outcome !== 'failed') + if (settled === 'retry') { + scheduleWebSessionCloseReplayRelist(environmentId, replay.worktreeId) + continue + } + if (settled === 'done') { + 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) + } + // The unchanged snapshot that made this replay due would otherwise be refused as stale. + await refreshWebRuntimeSessionTabsSnapshot(environmentId, replay.worktreeId, { + acceptCurrentSnapshot: true + }) + } +} + function resolveTabEnvironmentId(environmentId: string | null | undefined): string | null { return ( environmentId?.trim() ?? @@ -97,13 +185,22 @@ async function callWebRuntimeSessionTabMethod( terminalHandle?: string | null leafId?: string | null expectedCurrentLocalTabId?: string | null + expectedPairingRevision?: number } ): 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) + 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 @@ -215,11 +312,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..dab8088a9133 --- /dev/null +++ b/src/renderer/src/runtime/web-session-close-replay.test.ts @@ -0,0 +1,148 @@ +// 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_PENDING_WEB_SESSION_CLOSE_REPLAYS, + MAX_WEB_SESSION_CLOSE_REPLAY_ATTEMPTS, + queueWebSessionCloseReplay, + resetWebSessionCloseReplaysForTests, + settleWebSessionCloseReplay, + 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, + 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('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']))).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', () => { + 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('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]) + + // 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') + ) + 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..b1ac92cb8686 --- /dev/null +++ b/src/renderer/src/runtime/web-session-close-replay.ts @@ -0,0 +1,158 @@ +// 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 type { RuntimeMobileSessionTabsResult } from '../../../shared/runtime-types' +import { + clearWebSessionCloseIntent, + 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. */ +export const MAX_WEB_SESSION_CLOSE_REPLAY_ATTEMPTS = 3 +export 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.entries().next() + if (oldest.done) { + break + } + 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 }) +} + +/** 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. 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 due: WebSessionCloseReplay[] = [] + for (const replay of listHeldWebSessionCloseReplays(owner, worktreeId, presentHostTabIds)) { + 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' +} + +/** 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 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) + ) +} + +export function resetWebSessionCloseReplaysForTests(): void { + pendingReplays.clear() +} 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..4be0049e8bf9 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 ( @@ -111,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.