From 6c988356e227a6085c106da4cfccdd764a652be4 Mon Sep 17 00:00:00 2001 From: Jinwoo Hong <73622457+Jinwoo-H@users.noreply.github.com> Date: Wed, 8 Jul 2026 12:08:27 -0700 Subject: [PATCH] =?UTF-8?q?fix:=20Remote=20Orca=20Server=20reconnect=20liv?= =?UTF-8?q?eness=20=E2=80=94=20recover=20mirrors,=20input=20routing,=20and?= =?UTF-8?q?=20creates=20after=20tunnel=20drops=20(#7827)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Orca --- src/main/runtime/orca-runtime.test.ts | 222 ++++++++++++++++++ src/main/runtime/orca-runtime.ts | 100 +++++++- src/main/runtime/rpc/methods/session-tabs.ts | 7 +- src/main/runtime/rpc/methods/terminal.ts | 18 +- .../terminal-multiplex-escape-tail.test.ts | 2 +- .../runtime/rpc/terminal-multiplex.test.ts | 94 +++++++- src/main/runtime/rpc/terminal-send.test.ts | 39 ++- .../remote-runtime-pty-transport.test.ts | 109 +++++++++ .../remote-runtime-pty-transport.ts | 48 +++- .../src/runtime/web-session-tabs-sync.test.ts | 41 ++++ .../src/runtime/web-session-tabs-sync.ts | 25 ++ src/shared/remote-runtime-client.test.ts | 36 ++- src/shared/remote-runtime-client.ts | 50 +++- .../remote-runtime-request-websocket.ts | 10 + ...-runtime-shared-control-connection.test.ts | 88 ++++++- ...emote-runtime-shared-control-connection.ts | 50 ++-- .../remote-runtime-shared-control-open.ts | 68 +++++- .../remote-runtime-shared-control-requests.ts | 16 +- ...remote-runtime-shared-control-stability.ts | 32 +++ .../remote-runtime-shared-control-state.ts | 10 +- ...te-runtime-shared-control-subscriptions.ts | 6 + .../remote-runtime-shared-control-types.ts | 4 + src/shared/remote-runtime-socket-liveness.ts | 75 ++++++ src/shared/runtime-subscription-replay.ts | 25 ++ 24 files changed, 1110 insertions(+), 65 deletions(-) create mode 100644 src/shared/remote-runtime-socket-liveness.ts create mode 100644 src/shared/runtime-subscription-replay.ts diff --git a/src/main/runtime/orca-runtime.test.ts b/src/main/runtime/orca-runtime.test.ts index 5836b7277..ced9387d4 100644 --- a/src/main/runtime/orca-runtime.test.ts +++ b/src/main/runtime/orca-runtime.test.ts @@ -26897,4 +26897,226 @@ describe('OrcaRuntimeService', () => { expect(preDaemonProvider.shutdown).not.toHaveBeenCalled() }) }) + describe('stale terminal handle resolution (#7718)', () => { + function syncSingleTerminalGraph(runtime: OrcaRuntimeService, ptyId: string): void { + runtime.syncWindowGraph(1, { + tabs: [ + { + tabId: 'tab-1', + worktreeId: TEST_WORKTREE_ID, + title: 'Terminal 1', + activeLeafId: 'pane:1', + layout: null + } + ], + leaves: [ + { + tabId: 'tab-1', + worktreeId: TEST_WORKTREE_ID, + leafId: 'pane:1', + paneRuntimeId: 1, + ptyId, + paneTitle: 'Terminal 1' + } + ], + mobileSessionTabs: [ + { + worktree: TEST_WORKTREE_ID, + publicationEpoch: 'epoch-1', + snapshotVersion: 1, + activeGroupId: 'group-1', + activeTabId: 'tab-1::pane:1', + activeTabType: 'terminal', + tabs: [ + { + type: 'terminal', + id: 'tab-1::pane:1', + parentTabId: 'tab-1', + leafId: 'pane:1', + title: 'Terminal 1', + isActive: true + } + ] + } + ] + }) + } + + // Why: session-tab mirrors travel as PTY handles, but client-created + // terminals (terminal.create) hold LEAF handles — the kind that can + // diverge from the pane's current PTY across reconnects. Issue one + // directly from the leaf record to pin the resolver semantics. + function issueLeafHandle(runtime: OrcaRuntimeService, ptyId: string): string { + const internals = runtime as unknown as { + leaves: Map + issueHandle: (leaf: unknown) => string + } + const leaf = Array.from(internals.leaves.values()).find( + (candidate) => candidate.ptyId === ptyId + ) + if (!leaf) { + throw new Error('expected leaf record') + } + return internals.issueHandle(leaf) + } + + it('errors with terminal_handle_stale instead of adopting a replacement PTY', async () => { + const runtime = new OrcaRuntimeService(store) + runtime.attachWindow(1) + syncSingleTerminalGraph(runtime, 'pty-a') + const handle = issueLeafHandle(runtime, 'pty-a') + + // Simulate the pane's PTY being replaced while the remote client still + // holds the old handle (the record missed the swap, e.g. across a + // renderer graph reload that preserved live PTY records). + const internals = runtime as unknown as { + leaves: Map + } + for (const leaf of internals.leaves.values()) { + if (leaf.ptyId === 'pty-a') { + leaf.ptyId = 'pty-b' + } + } + + // The unguarded resolver silently adopts the new PTY — the misroute. + expect(runtime.resolveLeafForHandle(handle)).toEqual({ ptyId: 'pty-b' }) + // The guarded resolver surfaces the staleness so clients can re-derive. + expect(() => runtime.resolveLiveLeafForHandle(handle)).toThrow('terminal_handle_stale') + }) + + it('lets a handle issued before its first PTY adopt that PTY without erroring', async () => { + const runtime = new OrcaRuntimeService(store) + runtime.attachWindow(1) + syncSingleTerminalGraph(runtime, 'pty-a') + const handle = issueLeafHandle(runtime, 'pty-a') + + // Simulate the mobile pre-spawn flow: the handle record predates the + // PTY (ptyId null); the pane's first PTY must still resolve. + const internals = runtime as unknown as { + handles: Map + } + const record = internals.handles.get(handle) + if (!record) { + throw new Error('expected handle record') + } + record.ptyId = null + + expect(runtime.resolveLiveLeafForHandle(handle)).toEqual({ ptyId: 'pty-a' }) + }) + }) + + describe('mobile terminal create resilience (#7718)', () => { + it('cancels the surface wait without rolling back when the client connection dies', async () => { + vi.useFakeTimers() + try { + const closeTerminal = vi.fn() + const runtime = new OrcaRuntimeService(store) + runtime.setNotifier(createMobileCreateTestNotifier(closeTerminal)) + const abort = new AbortController() + const webContents = { send: vi.fn() } + const send = vi.fn((_channel: string, payload: { requestId: string }) => { + ipcMain.emit( + 'terminal:tabCreateReply', + { sender: webContents }, + { requestId: payload.requestId, tabId: 'tab-abort', title: 'Terminal' } + ) + }) + webContents.send = send + runtime.attachWindow(1) + runtime.syncWindowGraph(1, { tabs: [], leaves: [] }) + electronMocks.BrowserWindow.fromId.mockReturnValue({ + isDestroyed: () => false, + webContents + }) + + const create = runtime.createMobileSessionTerminal(`id:${TEST_WORKTREE_ID}`, { + activate: false, + signal: abort.signal + }) + const settled = create.then( + () => ({ ok: true as const }), + (error: Error) => ({ ok: false as const, error }) + ) + await vi.waitFor(() => expect(send).toHaveBeenCalledTimes(1)) + + // The client's socket dies mid-wait. The create must settle right away + // (not run down the 10s surface timeout) and must NOT close the tab — + // the renderer spawned a real terminal the host user can see. + abort.abort() + await vi.advanceTimersByTimeAsync(0) + const outcome = await settled + + expect(outcome.ok).toBe(false) + if (outcome.ok === false) { + expect(outcome.error.message).toBe('client_disconnected') + } + expect(closeTerminal).not.toHaveBeenCalled() + } finally { + vi.useRealTimers() + } + }) + + it('keeps a mobile-created terminal alive when its live shell has no registered pane key', async () => { + vi.useFakeTimers() + try { + const closeTerminal = vi.fn() + const runtime = new OrcaRuntimeService(store) + runtime.setNotifier(createMobileCreateTestNotifier(closeTerminal)) + const webContents = { send: vi.fn() } + const send = vi.fn((_channel: string, payload: { requestId: string }) => { + ipcMain.emit( + 'terminal:tabCreateReply', + { sender: webContents }, + { requestId: payload.requestId, tabId: 'tab-stall', title: 'Terminal' } + ) + }) + webContents.send = send + runtime.attachWindow(1) + runtime.syncWindowGraph(1, { tabs: [], leaves: [] }) + electronMocks.BrowserWindow.fromId.mockReturnValue({ + isDestroyed: () => false, + webContents + }) + + const create = runtime.createMobileSessionTerminal(`id:${TEST_WORKTREE_ID}`, { + activate: false + }) + const settled = create.then( + () => ({ ok: true as const }), + (error: Error) => ({ ok: false as const, error }) + ) + await vi.waitFor(() => expect(send).toHaveBeenCalledTimes(1)) + + // A live shell backs the tab, but its leaf id is not a terminal UUID + // so no pane key registers: the surface rescue can't publish it, and + // the surface itself never publishes (stalled renderer publication). + runtime.syncWindowGraph(1, { + tabs: [], + leaves: [ + { + tabId: 'tab-stall', + worktreeId: TEST_WORKTREE_ID, + leafId: 'pane:1', + paneRuntimeId: 1, + ptyId: 'pty-stall', + paneTitle: null + } + ] + }) + + await vi.advanceTimersByTimeAsync(11_000) + const outcome = await settled + + // The create still fails (nothing to return), but the timeout must not + // kill the live terminal — that is the "tab dies after ~10s" symptom. + expect(outcome.ok).toBe(false) + if (outcome.ok === false) { + expect(outcome.error.message).toContain('Timed out') + } + expect(closeTerminal).not.toHaveBeenCalled() + } finally { + vi.useRealTimers() + } + }) + }) }) diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index bb09d201a..c245c9d83 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -1184,6 +1184,10 @@ const RECENT_PTY_PATH_CANDIDATE_LIMIT = 1024 const RECENT_PTY_PATH_CANDIDATE_MAX_BYTES = 4 * 1024 const RECENT_PTY_PATH_CANDIDATE_TOTAL_BYTES = 64 * 1024 +function isClientDisconnectedError(error: unknown): boolean { + return error instanceof Error && error.message === 'client_disconnected' +} + function createTerminalRevealWarning(handle: string, error?: unknown): string { const reason = error instanceof Error && error.message.trim().length > 0 @@ -6239,6 +6243,32 @@ export class OrcaRuntimeService { return { ptyId: leaf.ptyId } } + // Why: remote clients hold handles across transport reconnects. A handle + // minted for a concrete PTY must never silently adopt a different PTY that + // later occupies the same pane — that misroutes keystrokes (#7718). Handles + // still awaiting their first PTY (ptyId null) may adopt it, which preserves + // the mobile pre-spawn subscribe flow. + resolveLiveLeafForHandle(handle: string): { ptyId: string | null } | null { + const record = this.handles.get(handle) + if (!record) { + return null + } + if (record.tabId.startsWith('pty:')) { + return { ptyId: record.ptyId } + } + const leaf = this.leaves.get(this.getLeafKey(record.tabId, record.leafId)) + if (!leaf) { + return null + } + if ( + record.ptyId !== null && + (leaf.ptyId !== record.ptyId || leaf.ptyGeneration !== record.ptyGeneration) + ) { + throw new Error('terminal_handle_stale') + } + return { ptyId: leaf.ptyId } + } + async resolveTerminalCwd(handle: string): Promise { const ptyId = this.resolveLeafForHandle(handle)?.ptyId if (!ptyId) { @@ -16263,6 +16293,7 @@ export class OrcaRuntimeService { launchAgent?: TuiAgent activate?: boolean clientMutationId?: string + signal?: AbortSignal } = {} ): Promise { const mutationId = opts.clientMutationId @@ -16304,6 +16335,7 @@ export class OrcaRuntimeService { launchAgent?: TuiAgent activate?: boolean clientMutationId?: string + signal?: AbortSignal } = {} ): Promise { this.assertGraphReady() @@ -16343,8 +16375,16 @@ export class OrcaRuntimeService { const reply = await new Promise<{ tabId: string; title: string }>((resolve, reject) => { const timer = setTimeout(() => { ipcMain.removeListener('terminal:tabCreateReply', handler) + opts.signal?.removeEventListener('abort', onAbort) reject(new Error('Terminal creation timed out')) }, 10_000) + // Why: a dead client connection cancels the wait; the renderer tab (and + // its shell) stays alive for the host and mirrors on reconnect (#7718). + const onAbort = (): void => { + clearTimeout(timer) + ipcMain.removeListener('terminal:tabCreateReply', handler) + reject(new Error('client_disconnected')) + } const handler = ( event: Electron.IpcMainEvent, @@ -16355,12 +16395,14 @@ export class OrcaRuntimeService { } clearTimeout(timer) ipcMain.removeListener('terminal:tabCreateReply', handler) + opts.signal?.removeEventListener('abort', onAbort) if (r.error) { reject(new Error(r.error)) } else { resolve({ tabId: r.tabId!, title: r.title ?? '' }) } } + opts.signal?.addEventListener('abort', onAbort, { once: true }) ipcMain.on('terminal:tabCreateReply', handler) win.webContents.send('terminal:requestTabCreate', { requestId, @@ -16398,18 +16440,25 @@ export class OrcaRuntimeService { // wait resolves without depending on a graph sync. this.ensurePtyBackedMobileSurfaceForRendererTab(worktreeId, reply.tabId) const surface = await this.waitForMobileTerminalSurface(worktreeId, reply.tabId, { - timeoutMs: MOBILE_TERMINAL_SURFACE_TIMEOUT_MS + timeoutMs: MOBILE_TERMINAL_SURFACE_TIMEOUT_MS, + signal: opts.signal }) if (this.isReadyMobileTerminalSurface(surface)) { return surface } const readySurface = await this.waitForMobileTerminalSurface(worktreeId, reply.tabId, { timeoutMs: MOBILE_TERMINAL_READY_FALLBACK_MS, - requireReady: true + requireReady: true, + signal: opts.signal }).catch(() => null) if (readySurface) { return readySurface } + if (opts.signal?.aborted) { + // Why: nobody is waiting for this create anymore; do not materialize + // or roll back — the renderer's own publication settles the tab. + throw new Error('client_disconnected') + } const pendingSurface = this.findMobileTerminalSurface(worktreeId, reply.tabId) if (!pendingSurface) { throw new Error('Timed out waiting for terminal surface after creation') @@ -16443,6 +16492,16 @@ export class OrcaRuntimeService { return rescued } } + // Why: don't roll back when (a) the client connection died — the wait + // was cancelled, not the spawn — or (b) a live shell already backs the + // tab (its pane key may simply not be registered yet). Killing a real + // terminal the host user can see is the "tab dies after ~10s" bug (#7718). + if ( + isClientDisconnectedError(error) || + this.hasLiveShellForRendererTab(worktreeId, reply.tabId) + ) { + throw error + } // Why: the renderer created the tab but no live PTY backs it (true PTY // spawn/handle failure). Roll the half-created tab back via the renderer // close path so it can't linger as a ghost in mobile snapshots, then @@ -16662,33 +16721,44 @@ export class OrcaRuntimeService { private waitForMobileTerminalSurface( worktreeId: string, parentTabId: string, - options: { timeoutMs?: number; requireReady?: boolean } = {} + options: { timeoutMs?: number; requireReady?: boolean; signal?: AbortSignal } = {} ): Promise { const timeoutMs = options.timeoutMs ?? MOBILE_TERMINAL_SURFACE_TIMEOUT_MS const existing = this.findMobileTerminalSurface(worktreeId, parentTabId, options) if (existing) { return Promise.resolve(existing) } + if (options.signal?.aborted) { + return Promise.reject(new Error('client_disconnected')) + } return new Promise((resolve, reject) => { - const timer = setTimeout(() => { + const cleanup = (): void => { + clearTimeout(timer) + options.signal?.removeEventListener('abort', onAbort) const idx = this.graphSyncCallbacks.indexOf(check) if (idx !== -1) { this.graphSyncCallbacks.splice(idx, 1) } + } + const timer = setTimeout(() => { + cleanup() reject(new Error('Timed out waiting for terminal surface after creation')) }, timeoutMs) + // Why: a dead client connection cancels the wait immediately instead of + // running down the timeout and triggering rollback (#7718). + const onAbort = (): void => { + cleanup() + reject(new Error('client_disconnected')) + } + options.signal?.addEventListener('abort', onAbort, { once: true }) const check = (): void => { const next = this.findMobileTerminalSurface(worktreeId, parentTabId, options) if (!next) { return } - clearTimeout(timer) - const idx = this.graphSyncCallbacks.indexOf(check) - if (idx !== -1) { - this.graphSyncCallbacks.splice(idx, 1) - } + cleanup() resolve(next) } this.graphSyncCallbacks.push(check) @@ -16778,6 +16848,18 @@ export class OrcaRuntimeService { return null } + // Why: rollback guard, looser than findLiveRegisteredPtyForRendererTab — a + // shell whose pane key hasn't registered yet can't be surface-rescued, but + // it is still a real terminal the create timeout must not kill (#7718). + private hasLiveShellForRendererTab(worktreeId: string, tabId: string): boolean { + for (const pty of this.ptysById.values()) { + if (pty.worktreeId === worktreeId && pty.tabId === tabId && pty.connected) { + return true + } + } + return false + } + private isReadyMobileTerminalSurface( surface: RuntimeMobileSessionCreateTerminalResult | null ): boolean { diff --git a/src/main/runtime/rpc/methods/session-tabs.ts b/src/main/runtime/rpc/methods/session-tabs.ts index f2bf1641b..d27d771f3 100644 --- a/src/main/runtime/rpc/methods/session-tabs.ts +++ b/src/main/runtime/rpc/methods/session-tabs.ts @@ -41,7 +41,7 @@ export const SESSION_TAB_METHODS: RpcAnyMethod[] = [ defineMethod({ name: 'session.tabs.createTerminal', params: CreateTerminalTab, - handler: async (params, { runtime }) => + handler: async (params, { runtime, signal }) => runtime.createMobileSessionTerminal(params.worktree, { afterTabId: params.afterTabId, targetGroupId: params.targetGroupId, @@ -54,7 +54,10 @@ export const SESSION_TAB_METHODS: RpcAnyMethod[] = [ ...(params.launchToken ? { launchToken: params.launchToken } : {}), ...(params.launchAgent ? { launchAgent: params.launchAgent } : {}), activate: params.activate, - clientMutationId: params.clientMutationId + clientMutationId: params.clientMutationId, + // Why: a dead client connection must cancel the surface wait instead + // of running down the timeout and rolling back a live tab (#7718). + signal }) }), defineMethod({ diff --git a/src/main/runtime/rpc/methods/terminal.ts b/src/main/runtime/rpc/methods/terminal.ts index 4ebe78149..a750438e0 100644 --- a/src/main/runtime/rpc/methods/terminal.ts +++ b/src/main/runtime/rpc/methods/terminal.ts @@ -904,7 +904,10 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [ params: TerminalSend, handler: async (params, { runtime }) => { await assertTerminalSendTextWithinLimit(params.text) - const leaf = runtime.resolveLeafForHandle(params.terminal) + // Why: guarded resolution — a stale handle must fail with + // terminal_handle_stale (clients recover by re-deriving the handle) + // instead of evaluating driver/lock state against the wrong PTY (#7718). + const leaf = runtime.resolveLiveLeafForHandle(params.terminal) const driver = leaf?.ptyId ? runtime.getDriver(leaf.ptyId) : null if (leaf?.ptyId && isTerminalInputLockedForClient(runtime, leaf.ptyId, params.client)) { return { @@ -1436,8 +1439,19 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [ const request = parsed.data detachStream(request.streamId, false) - let leaf = runtime.resolveLeafForHandle(request.terminal) const isMobile = request.client?.type === 'mobile' + let leaf: { ptyId: string | null } | null + try { + // Why: guarded resolution — binding the output stream to whatever + // PTY now occupies a stale handle's pane silently mirrors the wrong + // terminal after a reconnect (#7718). terminal_handle_stale lets the + // client re-derive the handle from the current session snapshot. + leaf = runtime.resolveLiveLeafForHandle(request.terminal) + } catch { + sendStreamError(request.streamId, 'terminal_handle_stale') + emit({ type: 'end', streamId: request.streamId }) + return + } if (!leaf?.ptyId && isMobile) { try { const ptyId = await runtime.waitForLeafPtyId(request.terminal, 10_000, signal) diff --git a/src/main/runtime/rpc/terminal-multiplex-escape-tail.test.ts b/src/main/runtime/rpc/terminal-multiplex-escape-tail.test.ts index ab2558562..59e4d2d1b 100644 --- a/src/main/runtime/rpc/terminal-multiplex-escape-tail.test.ts +++ b/src/main/runtime/rpc/terminal-multiplex-escape-tail.test.ts @@ -41,7 +41,7 @@ describe('terminal.multiplex pending-escape-tail threading (#7329)', () => { >() const cleanups = new Map void>() const runtime = stubRuntime({ - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), + resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), serializeTerminalBuffer: vi.fn().mockResolvedValue({ data: 'user@host:~$ ', diff --git a/src/main/runtime/rpc/terminal-multiplex.test.ts b/src/main/runtime/rpc/terminal-multiplex.test.ts index 5ceee818d..69e956aa1 100644 --- a/src/main/runtime/rpc/terminal-multiplex.test.ts +++ b/src/main/runtime/rpc/terminal-multiplex.test.ts @@ -41,7 +41,7 @@ describe('terminal multiplex RPC', () => { current?: (data: string, meta?: { seq?: number; rawLength?: number }) => void } = {} const runtime = stubRuntime({ - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), + resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), serializeTerminalBuffer: vi.fn().mockResolvedValue({ data: 'snapshot', @@ -258,7 +258,7 @@ describe('terminal multiplex RPC', () => { | undefined const restreamResolves: ((value: { data: string; cols: number; rows: number }) => void)[] = [] const runtime = stubRuntime({ - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), + resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), serializeTerminalBuffer: vi .fn() @@ -371,7 +371,7 @@ describe('terminal multiplex RPC', () => { current?: (data: string, meta?: { seq?: number; rawLength?: number }) => void } = {} const runtime = stubRuntime({ - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), + resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), serializeTerminalBuffer: vi.fn().mockResolvedValue({ data: 'snapshot', @@ -477,7 +477,7 @@ describe('terminal multiplex RPC', () => { >() const cleanups = new Map void>() const runtime = stubRuntime({ - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), + resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), readTerminal: vi .fn() .mockResolvedValue({ tail: ['line 120'], truncated: false, limited: true }), @@ -573,7 +573,7 @@ describe('terminal multiplex RPC', () => { >() const cleanups = new Map void>() const runtime = stubRuntime({ - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), + resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), serializeTerminalBuffer: vi .fn() @@ -681,7 +681,7 @@ describe('terminal multiplex RPC', () => { >() const cleanups = new Map void>() const runtime = stubRuntime({ - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), + resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), serializeTerminalBuffer: vi.fn().mockResolvedValue(null), getTerminalSize: vi.fn().mockReturnValue({ cols: 120, rows: 40 }), @@ -781,7 +781,7 @@ describe('terminal multiplex RPC', () => { >() const cleanups = new Map void>() const runtime = stubRuntime({ - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), + resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), serializeTerminalBuffer: vi.fn().mockResolvedValue(null), getTerminalSize: vi.fn().mockReturnValue({ cols: 120, rows: 40 }), @@ -1305,7 +1305,7 @@ describe('terminal multiplex RPC', () => { >() const cleanups = new Map void>() const runtime = stubRuntime({ - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: null }), + resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: null }), waitForLeafPtyId: vi.fn( (_handle: string, _timeoutMs?: number, signal?: AbortSignal) => new Promise((_resolve, reject) => { @@ -1372,6 +1372,78 @@ describe('terminal multiplex RPC', () => { await dispatchPromise }) + it('rejects a stale terminal handle with terminal_handle_stale instead of binding the wrong PTY', async () => { + // Why: after a reconnect a client can resubscribe with a handle whose + // pane now hosts a different PTY. Binding the stream anyway would mirror + // (and type into) the wrong terminal (#7718); the client recovers from + // terminal_handle_stale by re-deriving the handle from the next snapshot. + const messages: string[] = [] + const binaryFrames: Uint8Array[] = [] + const handlers = new Map< + number, + (frame: NonNullable>) => void + >() + const cleanups = new Map void>() + const runtime = stubRuntime({ + resolveLiveLeafForHandle: vi.fn(() => { + throw new Error('terminal_handle_stale') + }), + subscribeToTerminalData: vi.fn().mockReturnValue(vi.fn()), + registerSubscriptionCleanup: vi.fn((id: string, cleanup: () => void) => { + cleanups.set(id, cleanup) + }) + }) + const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) + + const dispatchPromise = dispatcher.dispatchStreaming( + makeRequest('terminal.multiplex', {}), + (msg) => messages.push(msg), + { + connectionId: 'conn-stale-handle', + sendBinary: (bytes) => binaryFrames.push(bytes), + registerBinaryStreamHandler: (streamId, handler) => { + handlers.set(streamId, handler) + return () => handlers.delete(streamId) + } + } + ) + + await vi.waitFor(() => + expect(messages.some((msg) => JSON.parse(msg).result?.type === 'ready')).toBe(true) + ) + handlers.get(0)?.( + decodeTerminalStreamFrame( + encodeTerminalStreamFrame({ + opcode: TerminalStreamOpcode.Subscribe, + streamId: 0, + seq: 1, + payload: encodeTerminalStreamJson({ + streamId: 9, + terminal: 'stale-terminal', + client: { id: 'desktop-1', type: 'desktop' } + }) + }) + )! + ) + + await vi.waitFor(() => + expect( + messages + .map((msg) => JSON.parse(msg).result) + .some((result) => result?.type === 'end' && result.streamId === 9) + ).toBe(true) + ) + const errorFrame = binaryFrames + .map((frame) => decodeTerminalStreamFrame(frame)) + .find((frame) => frame?.opcode === TerminalStreamOpcode.Error) + expect(errorFrame && decodeTerminalStreamText(errorFrame.payload)).toBe('terminal_handle_stale') + // The stream must never have bound to any PTY. + expect(runtime.subscribeToTerminalData).not.toHaveBeenCalled() + + cleanups.get('terminal-multiplex:conn-stale-handle')?.() + await dispatchPromise + }) + it('bounds live output queued while a multiplex snapshot is loading', async () => { vi.useFakeTimers() try { @@ -1385,7 +1457,7 @@ describe('terminal multiplex RPC', () => { const dataListenerRef: { current?: (data: string) => void } = {} const snapshotResolves: ((value: { data: string; cols: number; rows: number }) => void)[] = [] const runtime = stubRuntime({ - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), + resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), serializeTerminalBuffer: vi.fn( () => @@ -1494,7 +1566,7 @@ describe('terminal multiplex RPC', () => { const dataListenerRef: { current?: (data: string) => void } = {} const snapshotResolves: ((value: { data: string; cols: number; rows: number }) => void)[] = [] const runtime = stubRuntime({ - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), + resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), serializeTerminalBuffer: vi.fn( () => @@ -1607,7 +1679,7 @@ describe('terminal multiplex RPC', () => { rows: number }) => void = () => {} const runtime = stubRuntime({ - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), + resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), serializeTerminalBuffer: vi .fn() diff --git a/src/main/runtime/rpc/terminal-send.test.ts b/src/main/runtime/rpc/terminal-send.test.ts index 82e471000..b778f8149 100644 --- a/src/main/runtime/rpc/terminal-send.test.ts +++ b/src/main/runtime/rpc/terminal-send.test.ts @@ -75,9 +75,34 @@ describe('terminal send RPC', () => { expect(runtime.getTerminalAgentStatus).toHaveBeenCalledWith('terminal-1') }) + it('fails terminal.send with terminal_handle_stale for a stale handle instead of probing the wrong PTY', async () => { + const runtime = stubRuntime({ + resolveLiveLeafForHandle: vi.fn(() => { + throw new Error('terminal_handle_stale') + }), + sendTerminal: vi.fn() + }) + const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) + + const response = await dispatcher.dispatch( + makeRequest('terminal.send', { + terminal: 'stale-terminal', + text: 'x', + client: { id: 'desktop-1', type: 'desktop' } + }) + ) + + expect(response.ok).toBe(false) + if (response.ok) { + throw new Error('expected stale handle error') + } + expect(response.error.message).toContain('terminal_handle_stale') + expect(runtime.sendTerminal).not.toHaveBeenCalled() + }) + it('drops desktop input while a mobile client owns the terminal floor', async () => { const runtime = stubRuntime({ - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), + resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), getDriver: vi.fn().mockReturnValue({ kind: 'mobile', clientId: 'mobile-1' }), sendTerminal: vi.fn(), mobileTookFloor: vi.fn() @@ -109,7 +134,7 @@ describe('terminal send RPC', () => { it('accepts legacy clientless mobile input when the current driver is mobile', async () => { const runtime = stubRuntime({ - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), + resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), getDriver: vi.fn().mockReturnValue({ kind: 'mobile', clientId: 'mobile-1' }), sendTerminal: vi.fn().mockResolvedValue({ handle: 'terminal-1', @@ -198,7 +223,7 @@ describe('terminal send RPC', () => { vi.useFakeTimers() const text = 'é'.repeat(CLIPBOARD_TEXT_MEASURE_YIELD_CODE_UNITS + 1) const runtime = stubRuntime({ - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), + resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), getDriver: vi.fn().mockReturnValue({ kind: 'desktop' }), sendTerminal: vi.fn().mockResolvedValue({ handle: 'terminal-1', @@ -236,7 +261,7 @@ describe('terminal send RPC', () => { it('refuses guarded terminal sends when the agent needs permission', async () => { const runtime = stubRuntime({ - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), + resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), getDriver: vi.fn().mockReturnValue({ kind: 'desktop' }), getTerminalAgentStatus: vi.fn().mockResolvedValue({ handle: 'terminal-1', @@ -274,7 +299,7 @@ describe('terminal send RPC', () => { it('allows guarded terminal sends when the agent is sendable', async () => { const runtime = stubRuntime({ - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), + resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), getDriver: vi.fn().mockReturnValue({ kind: 'desktop' }), getTerminalAgentStatus: vi.fn().mockResolvedValue({ handle: 'terminal-1', @@ -316,7 +341,7 @@ describe('terminal send RPC', () => { it('refuses guarded combined text and submit sends before any PTY write', async () => { const runtime = stubRuntime({ - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), + resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), getDriver: vi.fn().mockReturnValue({ kind: 'desktop' }), getTerminalAgentStatus: vi.fn(), sendTerminal: vi.fn() @@ -350,7 +375,7 @@ describe('terminal send RPC', () => { it('rechecks the mobile floor lock immediately before guarded PTY writes', async () => { const runtime = stubRuntime({ - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), + resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), getDriver: vi .fn() .mockReturnValueOnce({ kind: 'desktop' }) diff --git a/src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.test.ts b/src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.test.ts index 148acb6c0..698059809 100644 --- a/src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.test.ts +++ b/src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.test.ts @@ -215,6 +215,115 @@ describe('createRemoteRuntimePtyTransport', () => { }) }) + it('re-derives the host session handle after a transport close instead of resubscribing the stale one', async () => { + const { createRemoteRuntimePtyTransport } = await import('./remote-runtime-pty-transport') + const onPtySpawn = vi.fn() + const transport = createRemoteRuntimePtyTransport('env-1', { + worktreeId: 'wt-1', + tabId: 'web-terminal-tab-1', + leafId: 'pane:1', + onPtySpawn + }) + + transport.attach({ + existingPtyId: 'remote:env-1@@terminal-1', + cols: 80, + rows: 24, + callbacks: {} + }) + await vi.waitFor(() => expect(subscriptionSendBinary).toHaveBeenCalled()) + expect(latestSubscribePayload()).toMatchObject({ terminal: 'terminal-1' }) + + // Why: while the tunnel was down the host re-minted this pane's handle; + // resubscribing the stale closure handle would bind the mirror to a + // different PTY (#7718). The transport must re-derive from the snapshot. + runtimeCall.mockImplementation(async (args: { method: string }) => + args.method === 'session.tabs.list' + ? { + ok: true, + result: { + worktree: 'wt-1', + publicationEpoch: 'epoch-1', + snapshotVersion: 2, + activeGroupId: null, + activeTabId: 'tab-1::pane:1', + activeTabType: 'terminal', + tabs: [ + { + type: 'terminal', + id: 'tab-1::pane:1', + parentTabId: 'tab-1', + leafId: 'pane:1', + title: 'Terminal', + isActive: true, + status: 'ready', + terminal: 'terminal-2' + } + ] + } + } + : { ok: true, result: {} } + ) + const subscribeCallsBefore = runtimeSubscribe.mock.calls.length + + // The dedicated multiplex socket dies (liveness/close) → onTransportClose. + subscriptionCallbacks?.onClose?.() + + await vi.waitFor(() => + expect(runtimeSubscribe.mock.calls.length).toBeGreaterThan(subscribeCallsBefore) + ) + await vi.waitFor(() => + expect(latestSubscribePayload()).toMatchObject({ terminal: 'terminal-2' }) + ) + expect(transport.getPtyId()).toContain('terminal-2') + expect(onPtySpawn).toHaveBeenCalledWith(expect.stringContaining('terminal-2')) + }) + + it('retires the mirror when the host no longer publishes the surface after a transport close', async () => { + const { createRemoteRuntimePtyTransport } = await import('./remote-runtime-pty-transport') + const onPtyExit = vi.fn() + const onError = vi.fn() + const transport = createRemoteRuntimePtyTransport('env-1', { + worktreeId: 'wt-1', + tabId: 'web-terminal-tab-1', + leafId: 'pane:1', + onPtyExit + }) + + transport.attach({ + existingPtyId: 'remote:env-1@@terminal-1', + cols: 80, + rows: 24, + callbacks: { onError } + }) + await vi.waitFor(() => expect(subscriptionSendBinary).toHaveBeenCalled()) + + runtimeCall.mockImplementation(async (args: { method: string }) => + args.method === 'session.tabs.list' + ? { + ok: true, + result: { + worktree: 'wt-1', + publicationEpoch: 'epoch-1', + snapshotVersion: 2, + activeGroupId: null, + activeTabId: null, + activeTabType: null, + tabs: [] + } + } + : { ok: true, result: {} } + ) + + subscriptionCallbacks?.onClose?.() + + // Why: no red xterm error — retire quietly and let the next session-tabs + // snapshot drive respawn/removal. + await vi.waitFor(() => expect(onPtyExit).toHaveBeenCalledWith('remote:env-1@@terminal-1')) + expect(transport.getPtyId()).toBeNull() + expect(onError).not.toHaveBeenCalled() + }) + it('does not close host-owned terminal handles attached from session snapshots', async () => { const { createRemoteRuntimePtyTransport } = await import('./remote-runtime-pty-transport') const transport = createRemoteRuntimePtyTransport('env-1', { diff --git a/src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts b/src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts index 9caf62104..e9a8f361f 100644 --- a/src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts +++ b/src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts @@ -182,6 +182,16 @@ export function createRemoteRuntimePtyTransport( return null } + async function listHostSessionHandle(hostTabId: string): Promise { + if (!worktreeId) { + return null + } + const listed = await callRuntime('session.tabs.list', { + worktree: toRuntimeWorktreeSelector(worktreeId) + }) + return findReadyHostSessionHandle(listed, hostTabId) + } + async function attachHostSessionMirror( options: Parameters[0] ): Promise { @@ -280,7 +290,9 @@ export function createRemoteRuntimePtyTransport( } return true } catch (error) { - storedCallbacks.onError?.(runtimeTerminalErrorMessage(error)) + // Why: stale-handle errors must retire the mirror (recoverable via the + // next snapshot) rather than dead-end in a red xterm banner (#7718). + handleRemoteTerminalError(error) return false } } @@ -298,7 +310,7 @@ export function createRemoteRuntimePtyTransport( text, client: { id: clientId, type: 'desktop' } }).catch((error) => { - storedCallbacks.onError?.(runtimeTerminalErrorMessage(error)) + handleRemoteTerminalError(error) }) }) @@ -371,6 +383,31 @@ export function createRemoteRuntimePtyTransport( storedCallbacks.onError?.(message) } + // Why: after a transport drop the host may have re-minted this pane's + // handle (reconnect, epoch or PTY change). Re-derive it from the current + // session snapshot instead of resubscribing the stale closure value, which + // would mirror (and type into) whatever PTY now sits behind it (#7718). + async function resubscribeAfterTransportClose(previousHandle: string): Promise { + if (tabId && isWebTerminalSurfaceTabId(tabId)) { + const nextHandle = await listHostSessionHandle(toHostSessionTabId(tabId)) + if (destroyed || !connected || handle !== previousHandle) { + return + } + if (!nextHandle) { + // Why: the host no longer publishes this surface; retire quietly and + // let the next session-tabs snapshot drive respawn/removal. + retireRemoteTerminalId() + return + } + if (nextHandle !== previousHandle) { + handle = nextHandle + remotePtyId = toRemoteRuntimePtyId(nextHandle, currentRuntimeEnvironmentId) + onPtySpawn?.(remotePtyId) + } + } + await subscribeToHandle() + } + async function subscribeToHandle(): Promise { if (!handle) { return @@ -453,10 +490,9 @@ export function createRemoteRuntimePtyTransport( } resubscribing = true const resubscribeHandle = handle - const resubscribePtyId = remotePtyId - void subscribeToHandle() + void resubscribeAfterTransportClose(resubscribeHandle) .catch((error) => { - if (isCurrentRemoteTerminal(resubscribeHandle, resubscribePtyId)) { + if (!destroyed && connected && handle) { handleRemoteTerminalError(error) } }) @@ -659,7 +695,7 @@ export function createRemoteRuntimePtyTransport( text, client: { id: clientId, type: 'desktop' } }).catch((error) => { - storedCallbacks.onError?.(runtimeTerminalErrorMessage(error)) + handleRemoteTerminalError(error) }) return true }, diff --git a/src/renderer/src/runtime/web-session-tabs-sync.test.ts b/src/renderer/src/runtime/web-session-tabs-sync.test.ts index be97ef98b..7090ac68b 100644 --- a/src/renderer/src/runtime/web-session-tabs-sync.test.ts +++ b/src/renderer/src/runtime/web-session-tabs-sync.test.ts @@ -22,6 +22,7 @@ import type { BrowserPage, BrowserWorkspace, Tab, TerminalTab } from '../../../s import type { OpenFile } from '../store/slices/editor' import { _getWebSessionTabsTrackingCountsForTest, + acceptReplayedWebSessionTabsSnapshot, applyFreshWebSessionTabsSnapshot, applyWebSessionTabsSnapshot, applyWebSessionTabsSnapshots, @@ -145,6 +146,46 @@ describe('applyWebSessionTabsSnapshot', () => { expect(shouldApplyWebSessionTabsSnapshot(sameEpochOlder, ENV)).toBe(false) }) + it('accepts a replayed same-epoch same-version snapshot after a transport reconnect', () => { + // Why: after a shared-control reconnect the server re-emits the current + // snapshot with an UNCHANGED epoch/version (the host did not restart). + // Without the replay reset the monotonic gate rejects it and the mirror + // stays frozen (#7718). + const snapshot = makeSnapshot([], { snapshotVersion: 5, activeTabType: null }) + + expect(shouldApplyWebSessionTabsSnapshot(snapshot, ENV)).toBe(true) + // Same frame again during normal operation: still rejected as stale. + expect(shouldApplyWebSessionTabsSnapshot(snapshot, ENV)).toBe(false) + + acceptReplayedWebSessionTabsSnapshot(ENV, snapshot.worktree) + expect(shouldApplyWebSessionTabsSnapshot(snapshot, ENV)).toBe(true) + + // The replay reset re-primes tracking: ordering protection resumes for + // subsequent frames (an older same-epoch frame is still rejected). + const older = makeSnapshot([], { snapshotVersion: 4, activeTabType: null }) + expect(shouldApplyWebSessionTabsSnapshot(older, ENV)).toBe(false) + const newer = makeSnapshot([], { snapshotVersion: 6, activeTabType: null }) + expect(shouldApplyWebSessionTabsSnapshot(newer, ENV)).toBe(true) + }) + + it('scopes the replay reset to the replayed environment and worktree', () => { + const snapshot = makeSnapshot([], { snapshotVersion: 5, activeTabType: null }) + const otherWorktree = makeSnapshot([], { + worktree: 'repo::/other-worktree', + snapshotVersion: 5, + activeTabType: null + }) + + expect(shouldApplyWebSessionTabsSnapshot(snapshot, ENV)).toBe(true) + expect(shouldApplyWebSessionTabsSnapshot(otherWorktree, ENV)).toBe(true) + + acceptReplayedWebSessionTabsSnapshot(ENV, snapshot.worktree) + + // Only the replayed worktree re-applies; the other stays gated. + expect(shouldApplyWebSessionTabsSnapshot(otherWorktree, ENV)).toBe(false) + expect(shouldApplyWebSessionTabsSnapshot(snapshot, ENV)).toBe(true) + }) + it('ignores remote snapshots for the local floating workspace', () => { const floatingTab: TerminalTab = { id: 'floating-tab-1', diff --git a/src/renderer/src/runtime/web-session-tabs-sync.ts b/src/renderer/src/runtime/web-session-tabs-sync.ts index 8d0eba136..47942c674 100644 --- a/src/renderer/src/runtime/web-session-tabs-sync.ts +++ b/src/renderer/src/runtime/web-session-tabs-sync.ts @@ -66,6 +66,7 @@ import { endWebRuntimeWakeTerminalRespawn, shouldSkipWebRuntimeWakeTerminalRespawn } from './web-runtime-wake-terminal-respawn' +import { isRuntimeSubscriptionReplayResponse } from '../../../shared/runtime-subscription-replay' const WEB_SESSION_GROUP_PREFIX = 'web-session-tabs:' @@ -172,6 +173,18 @@ export function getLastKnownHostTerminalTabCount( ) } +// Why: a post-reconnect subscription replay re-emits the current snapshot with +// an unchanged epoch/version; dropping the freshness entry lets the monotonic +// gate accept that replay as authoritative instead of freezing the mirror +// (#7718). Normal-operation ordering protection is untouched — this only runs +// for responses the connection tagged as reconnect replays. +export function acceptReplayedWebSessionTabsSnapshot( + environmentId: string, + worktreeId: string +): void { + latestSessionTabsSnapshotByWorktree.delete(sessionTabsFreshnessKey(environmentId, worktreeId)) +} + export function shouldApplyWebSessionTabsSnapshot( snapshot: RuntimeMobileSessionTabsResult, environmentId: string @@ -2500,7 +2513,13 @@ export function useWebSessionTabsSync(): void { return } const event = response.result as SessionTabsStreamEvent + const replayed = isRuntimeSubscriptionReplayResponse(response) if (event.type === 'snapshots') { + if (replayed) { + for (const snapshot of event.snapshots) { + acceptReplayedWebSessionTabsSnapshot(environmentId, snapshot.worktree) + } + } useAppStore.setState((state) => applyFreshWebSessionTabsSnapshots(state, event.snapshots, environmentId) ) @@ -2509,6 +2528,9 @@ export function useWebSessionTabsSync(): void { if (event.type !== 'snapshot' && event.type !== 'updated') { return } + if (replayed) { + acceptReplayedWebSessionTabsSnapshot(environmentId, event.worktree) + } useAppStore.setState((state) => applyFreshWebSessionTabsSnapshot(state, event, environmentId) ) @@ -2587,6 +2609,9 @@ export function useWebSessionTabsSync(): void { if (event.type !== 'snapshot' && event.type !== 'updated') { return } + if (isRuntimeSubscriptionReplayResponse(response)) { + acceptReplayedWebSessionTabsSnapshot(environmentId, event.worktree) + } const fresh = shouldApplyWebSessionTabsSnapshot(event, environmentId) const syncState = useAppStore.getState() const localWorktreeTabs = syncState.tabsByWorktree[activeWorktreeId] ?? [] diff --git a/src/shared/remote-runtime-client.test.ts b/src/shared/remote-runtime-client.test.ts index ccb09c15d..5febb2f2d 100644 --- a/src/shared/remote-runtime-client.test.ts +++ b/src/shared/remote-runtime-client.test.ts @@ -104,6 +104,37 @@ describe('subscribeRemoteRuntimeRequest', () => { } }) + it('closes a half-open subscription socket via client liveness so callers can resubscribe', async () => { + // Why: dedicated stream sockets (terminal.multiplex, browser.screencast) + // must not hang forever when a tunnel goes half-open — no close frame, no + // pongs, no data (#7718). Client liveness surfaces onError/onClose so the + // renderer's onTransportClose resubscribe path can run. + const server = await createSubscriptionServer({ disableAutoPong: true }) + const onResponse = vi.fn() + const onError = vi.fn() + const onClose = vi.fn() + + const subscription = await subscribeRemoteRuntimeRequest( + server.pairing, + 'terminal.multiplex', + {}, + 1000, + { onResponse, onError, onClose }, + { pingIntervalMs: 50, livenessTimeoutMs: 200 } + ) + + await vi.waitFor(() => expect(onResponse).toHaveBeenCalled()) + await vi.waitFor( + () => + expect(onError).toHaveBeenCalledWith( + expect.objectContaining({ code: 'remote_runtime_unavailable' }) + ), + { timeout: 5000 } + ) + expect(onClose).toHaveBeenCalledOnce() + subscription.close() + }) + it('closes established subscription sockets after terminal protocol errors', async () => { const offSpy = vi.spyOn(WebSocketClient.prototype, 'off') try { @@ -223,6 +254,9 @@ describe('sendRemoteRuntimeRequest', () => { async function createSubscriptionServer( options: { sendMismatchedResponseAfterSubscribe?: boolean + // Why: half-open simulation — the socket stays open but never answers + // protocol pings, like a wedged tunnel that swallows frames silently. + disableAutoPong?: boolean } = {} ): Promise<{ pairing: PairingOffer @@ -233,7 +267,7 @@ async function createSubscriptionServer( const nextBinary = new Promise((resolve) => { resolveBinary = resolve }) - const wss = new WebSocketServer({ port: 0 }) + const wss = new WebSocketServer({ port: 0, autoPong: options.disableAutoPong !== true }) servers.push(wss) wss.on('connection', (ws) => { diff --git a/src/shared/remote-runtime-client.ts b/src/shared/remote-runtime-client.ts index 2f9c2f59b..ecd9f1df7 100644 --- a/src/shared/remote-runtime-client.ts +++ b/src/shared/remote-runtime-client.ts @@ -24,6 +24,11 @@ import { // unaffected; the class lives in a ws-free module so type-only consumers // (and mobile's typecheck) don't compile this file's Node-only deps. import { RemoteRuntimeClientError } from './remote-runtime-client-error' +import { + startRemoteRuntimeSocketLiveness, + type RemoteRuntimeSocketLivenessMonitor, + type RemoteRuntimeSocketLivenessOptions +} from './remote-runtime-socket-liveness' export { RemoteRuntimeClientError } from './remote-runtime-client-error' @@ -354,7 +359,8 @@ export async function subscribeRemoteRuntimeRequest( method: string, params: unknown, timeoutMs: number, - callbacks: RemoteRuntimeSubscriptionCallbacks + callbacks: RemoteRuntimeSubscriptionCallbacks, + livenessOptions?: RemoteRuntimeSocketLivenessOptions ): Promise { return await new Promise((resolve, reject) => { const requestId = randomUUID() @@ -364,8 +370,11 @@ export async function subscribeRemoteRuntimeRequest( let state: HandshakeState = 'awaiting_ready' let settled = false let ws: WebSocket | null = null + let liveness: RemoteRuntimeSocketLivenessMonitor | null = null const cleanupSocketListeners = (): WebSocket | null => { + liveness?.stop() + liveness = null const socket = ws if (!socket) { return null @@ -374,6 +383,8 @@ export async function subscribeRemoteRuntimeRequest( socket.off('error', onError) socket.off('close', onClose) socket.off('message', onMessage) + socket.off('pong', onLivenessSignal) + socket.off('ping', onLivenessSignal) ws = null // Why: startup failures detach Orca callbacks before closing the ws, // but ws can still emit a late transport error while close is in flight. @@ -485,6 +496,7 @@ export async function subscribeRemoteRuntimeRequest( } function onMessage(data: WebSocket.RawData, isBinary: boolean): void { + liveness?.noteActivity() if (isBinary) { handleBinaryFrame(new Uint8Array(data as Buffer)) return @@ -515,10 +527,46 @@ export async function subscribeRemoteRuntimeRequest( handleRpcFrame(plaintext) } + function onLivenessSignal(): void { + liveness?.noteActivity() + } + ws.once('open', onOpen) ws.once('error', onError) ws.on('close', onClose) ws.on('message', onMessage) + ws.on('pong', onLivenessSignal) + ws.on('ping', onLivenessSignal) + + // Why: dedicated stream sockets (terminal.multiplex, browser.screencast) + // ride the same tunnels as shared control; a half-open drop must surface + // as a close so the renderer's onTransportClose resubscribe path runs + // instead of freezing the stream forever (#7718/#7489). + const monitoredWs = ws + liveness = startRemoteRuntimeSocketLiveness({ + ping: () => { + if (monitoredWs.readyState === WebSocket.OPEN) { + monitoredWs.ping() + } + }, + onDead: () => { + // Why: fail() first so listeners detach before terminate's close event; + // otherwise the close handler would emit a second onClose to callers. + fail( + new RemoteRuntimeClientError( + 'remote_runtime_unavailable', + 'Remote Orca runtime stopped responding; the stream connection was reset.' + ) + ) + try { + // Why: close() on a half-open socket can hang for the OS TCP timeout. + monitoredWs.terminate() + } catch { + // Best-effort terminate; the subscription is already settled. + } + }, + options: livenessOptions + }) function handleReadyFrame(frame: string): void { let ready: unknown diff --git a/src/shared/remote-runtime-request-websocket.ts b/src/shared/remote-runtime-request-websocket.ts index 40b4e999d..e5b0ad821 100644 --- a/src/shared/remote-runtime-request-websocket.ts +++ b/src/shared/remote-runtime-request-websocket.ts @@ -22,6 +22,10 @@ export type RemoteRuntimeWebSocketCallbacks = { onClose: (ws: WebSocket, code: number, reason: Buffer) => void onError: (ws: WebSocket, error: RemoteRuntimeClientError) => void onTextFrame: (ws: WebSocket, frame: string) => void + // Why: protocol-level pongs (and server heartbeat pings) are the liveness + // signal for detecting half-open tunnels that never deliver `close` (#7718). + onPong?: (ws: WebSocket) => void + onPing?: (ws: WebSocket) => void } export function openRemoteRuntimeWebSocket( @@ -64,6 +68,8 @@ export function openRemoteRuntimeWebSocket( } callbacks.onTextFrame(ws, data.toString()) } + const onPong = (): void => callbacks.onPong?.(ws) + const onPing = (): void => callbacks.onPing?.(ws) const cleanup = (): void => { if (cleanedUp) { return @@ -73,6 +79,8 @@ export function openRemoteRuntimeWebSocket( ws.off('error', onError) ws.off('close', onClose) ws.off('message', onMessage) + ws.off('pong', onPong) + ws.off('ping', onPing) // Why: a manually closed ws can still emit a late transport error; keep // that from becoming an unhandled EventEmitter error after detaching Orca. if (ws.readyState !== WebSocket.CLOSED) { @@ -84,6 +92,8 @@ export function openRemoteRuntimeWebSocket( ws.on('error', onError) ws.on('close', onClose) ws.on('message', onMessage) + ws.on('pong', onPong) + ws.on('ping', onPing) return { ok: true, socket: { ws, sharedKey, cleanup } } } diff --git a/src/shared/remote-runtime-shared-control-connection.test.ts b/src/shared/remote-runtime-shared-control-connection.test.ts index e807a519b..250ec27bf 100644 --- a/src/shared/remote-runtime-shared-control-connection.test.ts +++ b/src/shared/remote-runtime-shared-control-connection.test.ts @@ -13,6 +13,7 @@ import { import { encodePairingOffer, parsePairingCode, type PairingOffer } from './pairing' import { RemoteRuntimeSharedControlConnection } from './remote-runtime-shared-control-connection' import * as sharedControlProtocol from './remote-runtime-shared-control-protocol' +import { isRuntimeSubscriptionReplayResponse } from './runtime-subscription-replay' const TEST_PROJECT_PATH = path.join('tmp', 'project') @@ -406,6 +407,83 @@ describe('RemoteRuntimeSharedControlConnection', () => { connection.close() }) + it('detects a half-open socket via client liveness, reconnects, and tags the replayed response', async () => { + // Why: the server keeps the TCP connection open but stops answering — + // no close frame, no pongs (autoPong disabled), no responses. This is the + // half-open devtunnel scenario from #7718: edge-triggered reconnect never + // fires, so client liveness must terminate the socket itself. + const server = await createServer({ disableAutoPong: true }) + const connection = new RemoteRuntimeSharedControlConnection(server.pairing, { + liveness: { pingIntervalMs: 50, livenessTimeoutMs: 200 } + }) + const onResponse = vi.fn() + const onClose = vi.fn() + + await connection.subscribe('runtime.clientEvents.subscribe', null, 1000, { + onResponse, + onError: vi.fn(), + onClose + }) + await vi.waitFor(() => expect(onResponse).toHaveBeenCalled()) + expect(isRuntimeSubscriptionReplayResponse(onResponse.mock.calls[0]?.[0])).toBe(false) + + // Liveness terminates the silent socket and the reconnect path replays + // the subscription on a fresh connection. + await vi.waitFor(() => expect(server.connectionCount()).toBeGreaterThanOrEqual(2), { + timeout: 5000 + }) + await vi.waitFor( + () => + expect( + server.requests.filter((request) => request.method === 'runtime.clientEvents.subscribe') + .length + ).toBeGreaterThanOrEqual(2), + { timeout: 5000 } + ) + // The first response after the reconnect replay carries the replay tag so + // snapshot freshness gates can accept the re-emitted snapshot. + await vi.waitFor( + () => + expect( + onResponse.mock.calls.some(([response]) => isRuntimeSubscriptionReplayResponse(response)) + ).toBe(true), + { timeout: 5000 } + ) + expect(onClose).not.toHaveBeenCalled() + + connection.close() + }) + + it('tears down the socket when a request times out and reconnects active subscriptions', async () => { + const server = await createServer({ silentMethods: ['worktree.hang'] }) + const connection = new RemoteRuntimeSharedControlConnection(server.pairing) + const onResponse = vi.fn() + const onClose = vi.fn() + + await connection.subscribe('runtime.clientEvents.subscribe', null, 1000, { + onResponse, + onError: vi.fn(), + onClose + }) + await vi.waitFor(() => expect(onResponse).toHaveBeenCalled()) + + // Why: mirrors RemoteRuntimeRequestConnection — a request the server never + // answered marks the socket as suspect and must not leave it 'ready'. + await expect(connection.request('worktree.hang', undefined, 50)).rejects.toThrow('Timed out') + + await vi.waitFor(() => expect(server.connectionCount()).toBe(2), { timeout: 5000 }) + await vi.waitFor( + () => + expect( + server.requests.filter((request) => request.method === 'runtime.clientEvents.subscribe') + ).toHaveLength(2), + { timeout: 5000 } + ) + expect(onClose).not.toHaveBeenCalled() + + connection.close() + }) + it('rejects pending requests and records close diagnostics when the socket closes', async () => { const server = await createServer({ closeBeforeResponse: true }) const connection = new RemoteRuntimeSharedControlConnection(server.pairing) @@ -434,6 +512,10 @@ async function createServer( closeAfterFirstStreamingResponse?: boolean closeBeforeResponse?: boolean suppressReadyFrame?: boolean + // Why: half-open simulation — the socket stays open but never answers + // protocol pings, like a wedged tunnel that swallows frames silently. + disableAutoPong?: boolean + silentMethods?: string[] } = {} ): Promise { const serverKeyPair = generateKeyPair() @@ -441,7 +523,7 @@ async function createServer( const delayedResponses: (() => void)[] = [] let connectionCount = 0 let closedAfterFirstStreamingResponse = false - const wss = new WebSocketServer({ port: 0 }) + const wss = new WebSocketServer({ port: 0, autoPong: options.disableAutoPong !== true }) servers.push(wss) wss.on('connection', (ws) => { @@ -531,10 +613,14 @@ function handleRequest( sendUnknownResponseBeforeResponse?: boolean closeAfterStreamingResponse?: () => boolean closeBeforeResponse?: boolean + silentMethods?: string[] }, delayedResponses: (() => void)[] ): void { requests.push(request) + if (options.silentMethods?.includes(request.method)) { + return + } if (options.closeBeforeResponse) { ws.close(4001, 'test close') return diff --git a/src/shared/remote-runtime-shared-control-connection.ts b/src/shared/remote-runtime-shared-control-connection.ts index 2ea957e9f..585d3478c 100644 --- a/src/shared/remote-runtime-shared-control-connection.ts +++ b/src/shared/remote-runtime-shared-control-connection.ts @@ -12,13 +12,14 @@ import { } from './remote-runtime-shared-control-ready' import { scheduleSharedControlReconnectOrFinish } from './remote-runtime-shared-control-reconnect' import { requestSharedControl } from './remote-runtime-shared-control-requests' -import { scheduleSharedControlStableReset } from './remote-runtime-shared-control-stability' +import { SharedControlReadyStableResetTimer } from './remote-runtime-shared-control-stability' import * as sharedControlState from './remote-runtime-shared-control-state' import { sendSharedControlRequest, sendSharedControlSubscription } from './remote-runtime-shared-control-send' import { closeSharedControlSocket } from './remote-runtime-shared-control-socket-close' +import type { RemoteRuntimeSocketLivenessOptions } from './remote-runtime-socket-liveness' import * as sharedControlSubscriptions from './remote-runtime-shared-control-subscriptions' import { startSharedControlSubscription } from './remote-runtime-shared-control-subscription-start' import type { @@ -37,7 +38,7 @@ export class RemoteRuntimeSharedControlConnection { private sharedKey: Uint8Array | null = null private socketCleanup: (() => void) | null = null private reconnectTimer: ReturnType | null = null - private readyStableTimer: ReturnType | null = null + private readonly readyStableReset: SharedControlReadyStableResetTimer private reconnectAttempt = 0 private intentionallyClosed = false private lastConnectedAt: number | null = null @@ -46,11 +47,20 @@ export class RemoteRuntimeSharedControlConnection { private readonly pendingRequests = new Map>() private readonly subscriptions = new Map>() private readonly readyWaiters: SharedControlReadyWaiter[] = [] + private everReady = false constructor( private readonly pairing: PairingOffer, - private readonly options: { environmentId?: string; reconnectStableResetMs?: number } = {} - ) {} + private readonly options: { + environmentId?: string + reconnectStableResetMs?: number + liveness?: RemoteRuntimeSocketLivenessOptions + } = {} + ) { + this.readyStableReset = new SharedControlReadyStableResetTimer( + options.reconnectStableResetMs ?? 30_000 + ) + } request( method: string, @@ -64,7 +74,10 @@ export class RemoteRuntimeSharedControlConnection { timeoutMs, ensureReady: () => this.ensureReadyWithTimeout(timeoutMs), send: (requestId, requestMethod, requestParams) => - this.sendRequest(requestId, requestMethod, requestParams) + this.sendRequest(requestId, requestMethod, requestParams), + // Why: a timed-out request marks the socket as suspect (#7718) — tear + // it down so reconnect+replay runs instead of keeping a zombie socket. + onTimeout: (error) => this.handleSocketClosed(error) }) } @@ -145,7 +158,11 @@ export class RemoteRuntimeSharedControlConnection { this.lastError = error.message this.handleSocketClosed(error) }, - onTextFrame: (frame) => this.handleTextFrame(frame) + onTextFrame: (frame) => this.handleTextFrame(frame), + liveness: { + options: this.options.liveness, + onDead: (error) => this.handleSocketClosed(error) + } }) if (!opened.ok) { this.handleSocketClosed(opened.error) @@ -205,8 +222,11 @@ export class RemoteRuntimeSharedControlConnection { private replaySubscriptions(): void { sharedControlSubscriptions.replaySharedControlSubscriptions({ subscriptions: this.subscriptions, - send: (subscription) => this.sendSubscription(subscription) + send: (subscription) => this.sendSubscription(subscription), + // Why: only reconnects tag replays; first connects stay on the gated path. + tagReplayedResponses: this.everReady }) + this.everReady = true } private closeSubscription(requestId: string): void { @@ -260,7 +280,7 @@ export class RemoteRuntimeSharedControlConnection { socketCleanup: cleanup, ws, error, - clearReadyStableTimer: () => this.clearReadyStableTimer() + clearReadyStableTimer: () => this.readyStableReset.clear() }) this.ws = null this.sharedKey = null @@ -292,24 +312,12 @@ export class RemoteRuntimeSharedControlConnection { } private scheduleReconnectAttemptReset(): void { - this.clearReadyStableTimer() - this.readyStableTimer = scheduleSharedControlStableReset({ - delayMs: this.options.reconnectStableResetMs ?? 30_000, + this.readyStableReset.schedule({ getState: () => this.state, getSocket: () => this.ws, reset: () => { this.reconnectAttempt = 0 - }, - clearCurrent: () => { - this.readyStableTimer = null } }) } - - private clearReadyStableTimer(): void { - if (this.readyStableTimer) { - clearTimeout(this.readyStableTimer) - this.readyStableTimer = null - } - } } diff --git a/src/shared/remote-runtime-shared-control-open.ts b/src/shared/remote-runtime-shared-control-open.ts index 6381f58dd..ddb3eb0cd 100644 --- a/src/shared/remote-runtime-shared-control-open.ts +++ b/src/shared/remote-runtime-shared-control-open.ts @@ -7,6 +7,10 @@ import { type RemoteRuntimeWebSocket } from './remote-runtime-request-websocket' import { formatSharedControlCloseMessage } from './remote-runtime-shared-control-protocol' +import { + startRemoteRuntimeSocketLiveness, + type RemoteRuntimeSocketLivenessOptions +} from './remote-runtime-socket-liveness' export function openSharedControlSocket( pairing: PairingOffer, @@ -15,9 +19,17 @@ export function openSharedControlSocket( onClose: (close: { code: number; reason: string }, error: RemoteRuntimeClientError) => void onError: (error: RemoteRuntimeClientError) => void onTextFrame: (frame: string) => void + // Why: reconnect is edge-triggered on `close`, but a half-open tunnel + // never delivers one. Liveness pings and declares the socket dead when + // the server goes silent, so the close/reconnect path can run (#7718). + liveness?: { + options?: RemoteRuntimeSocketLivenessOptions + onDead: (error: RemoteRuntimeClientError) => void + } } ): { ok: true; socket: RemoteRuntimeWebSocket } | { ok: false; error: RemoteRuntimeClientError } { - return openRemoteRuntimeWebSocket(pairing, { + let noteActivity: () => void = () => {} + const opened = openRemoteRuntimeWebSocket(pairing, { onClose: (ws, code, reason) => { if (callbacks.getCurrentSocket() === ws) { callbacks.onClose( @@ -33,8 +45,62 @@ export function openSharedControlSocket( }, onTextFrame: (ws, frame) => { if (callbacks.getCurrentSocket() === ws) { + noteActivity() callbacks.onTextFrame(frame) } + }, + onPong: (ws) => { + if (callbacks.getCurrentSocket() === ws) { + noteActivity() + } + }, + onPing: (ws) => { + if (callbacks.getCurrentSocket() === ws) { + noteActivity() + } } }) + if (!opened.ok || !callbacks.liveness) { + return opened + } + + const { ws, sharedKey, cleanup } = opened.socket + const liveness = callbacks.liveness + const monitor = startRemoteRuntimeSocketLiveness({ + ping: () => { + if (ws.readyState === 1) { + ws.ping() + } + }, + onDead: () => { + if (callbacks.getCurrentSocket() !== ws) { + return + } + try { + // Why: close() on a half-open socket can hang for the OS TCP timeout. + ws.terminate() + } catch { + // Best-effort terminate; the dead callback resets connection state. + } + liveness.onDead( + remoteRuntimeUnavailableError( + 'Remote Orca runtime stopped responding; resetting the control connection.' + ) + ) + }, + options: liveness.options + }) + noteActivity = monitor.noteActivity + + return { + ok: true, + socket: { + ws, + sharedKey, + cleanup: () => { + monitor.stop() + cleanup() + } + } + } } diff --git a/src/shared/remote-runtime-shared-control-requests.ts b/src/shared/remote-runtime-shared-control-requests.ts index bbd8900b9..5f8d0ca2b 100644 --- a/src/shared/remote-runtime-shared-control-requests.ts +++ b/src/shared/remote-runtime-shared-control-requests.ts @@ -1,5 +1,9 @@ import { randomUUID } from 'node:crypto' -import { remoteRuntimeTimeoutError } from './remote-runtime-request-frames' +import type { RemoteRuntimeClientError } from './remote-runtime-client-error' +import { + remoteRuntimeTimeoutError, + remoteRuntimeUnavailableError +} from './remote-runtime-request-frames' import type { RuntimeRpcResponse } from './runtime-rpc-envelope' import { toRemoteRuntimeClientError } from './remote-runtime-shared-control-protocol' import { rejectSharedControlPendingRequest } from './remote-runtime-shared-control-state' @@ -12,6 +16,7 @@ export function requestSharedControl(args: { timeoutMs: number ensureReady: () => Promise send: (requestId: string, method: string, params: unknown) => void + onTimeout?: (error: RemoteRuntimeClientError) => void }): Promise> { const requestId = randomUUID() return new Promise>((resolve, reject) => { @@ -22,6 +27,15 @@ export function requestSharedControl(args: { } args.pendingRequests.delete(requestId) pending.reject(remoteRuntimeTimeoutError()) + // Why: a request the server never answered means the socket is suspect + // (half-open tunnels swallow frames silently); mirror + // RemoteRuntimeRequestConnection and hand the connection a teardown + // error so reconnect+replay runs instead of keeping a zombie socket. + args.onTimeout?.( + remoteRuntimeUnavailableError( + 'Remote Orca runtime did not answer in time; resetting the control connection.' + ) + ) }, args.timeoutMs) args.pendingRequests.set(requestId, { method: args.method, diff --git a/src/shared/remote-runtime-shared-control-stability.ts b/src/shared/remote-runtime-shared-control-stability.ts index 9e1024e69..867d5a654 100644 --- a/src/shared/remote-runtime-shared-control-stability.ts +++ b/src/shared/remote-runtime-shared-control-stability.ts @@ -21,3 +21,35 @@ export function scheduleSharedControlStableReset(args: { } return timer } + +// Why: owns the ready-stable timer's lifecycle so the connection only wires +// state accessors; scheduling always replaces any earlier pending timer. +export class SharedControlReadyStableResetTimer { + private timer: ReturnType | null = null + + constructor(private readonly delayMs: number) {} + + schedule(args: { + getState: () => SharedControlConnectionState + getSocket: () => WebSocket | null + reset: () => void + }): void { + this.clear() + this.timer = scheduleSharedControlStableReset({ + delayMs: this.delayMs, + getState: args.getState, + getSocket: args.getSocket, + reset: args.reset, + clearCurrent: () => { + this.timer = null + } + }) + } + + clear(): void { + if (this.timer) { + clearTimeout(this.timer) + this.timer = null + } + } +} diff --git a/src/shared/remote-runtime-shared-control-state.ts b/src/shared/remote-runtime-shared-control-state.ts index 9c22198f7..72f139a49 100644 --- a/src/shared/remote-runtime-shared-control-state.ts +++ b/src/shared/remote-runtime-shared-control-state.ts @@ -9,6 +9,7 @@ import type { SharedControlReadyWaiter } from './remote-runtime-shared-control-types' import { getSubscriptionId, isEndResult } from './remote-runtime-shared-control-protocol' +import { tagRuntimeSubscriptionReplayResponse } from './runtime-subscription-replay' export function buildSharedControlDiagnostics(args: { state: SharedControlConnectionState @@ -149,7 +150,14 @@ export function handleSharedControlSubscriptionResponse( subscription.remoteSubscriptionId = subscriptionId } } - subscription.callbacks.onResponse(response) + let delivered = response + if (subscription.pendingReplayTag) { + subscription.pendingReplayTag = false + if (response.ok) { + delivered = tagRuntimeSubscriptionReplayResponse(response) + } + } + subscription.callbacks.onResponse(delivered) if (response.ok && isEndResult(response.result)) { finishSharedControlSubscription(subscriptions, subscription, false) } diff --git a/src/shared/remote-runtime-shared-control-subscriptions.ts b/src/shared/remote-runtime-shared-control-subscriptions.ts index 466d11354..d4122eac9 100644 --- a/src/shared/remote-runtime-shared-control-subscriptions.ts +++ b/src/shared/remote-runtime-shared-control-subscriptions.ts @@ -90,6 +90,9 @@ export function sendSharedControlCleanupRequest(args: { export function replaySharedControlSubscriptions(args: { subscriptions: Map> send: (subscription: SharedControlLogicalSubscription) => void + // Why: true only for a reconnect of a previously-ready connection; first + // connects deliver their initial snapshot through the normal gated path. + tagReplayedResponses?: boolean }): void { for (const subscription of args.subscriptions.values()) { if (subscription.closeAfterReady) { @@ -97,6 +100,9 @@ export function replaySharedControlSubscriptions(args: { } subscription.sent = false subscription.remoteSubscriptionId = null + if (args.tagReplayedResponses) { + subscription.pendingReplayTag = true + } args.send(subscription) } } diff --git a/src/shared/remote-runtime-shared-control-types.ts b/src/shared/remote-runtime-shared-control-types.ts index 9f784faa8..4eb671ea3 100644 --- a/src/shared/remote-runtime-shared-control-types.ts +++ b/src/shared/remote-runtime-shared-control-types.ts @@ -30,6 +30,10 @@ export type SharedControlLogicalSubscription = { closed: boolean closeAfterReady: boolean remoteSubscriptionId: string | null + // Why: set while awaiting the first response after a reconnect replay; that + // response is the authoritative re-emitted snapshot and gets tagged so + // monotonic freshness gates don't drop it (#7718). + pendingReplayTag?: boolean } export type SharedControlReadyWaiter = { diff --git a/src/shared/remote-runtime-socket-liveness.ts b/src/shared/remote-runtime-socket-liveness.ts new file mode 100644 index 000000000..2903a72c7 --- /dev/null +++ b/src/shared/remote-runtime-socket-liveness.ts @@ -0,0 +1,75 @@ +// Why: a half-open tunnel (devtunnel/NAT drop) never delivers a ws `close`, +// so edge-triggered reconnect logic on the client side never fires while the +// server has long since reaped its end (#7718/#7489). This monitor gives +// client sockets a level-based liveness check: ping on a cadence and declare +// the socket dead when no inbound traffic (frames, pings, or pongs) arrives +// within the window, so the existing close/reconnect path can run. + +// Why: pings ride the RFC 6455 control-frame layer, which every supported +// server (and the `ws` package it embeds) answers automatically — this stays +// backward compatible with old servers that predate client-side liveness. +export const REMOTE_RUNTIME_SOCKET_PING_INTERVAL_MS = 10_000 +// Why: just under two server heartbeat periods (15s), so a dead link is +// detected on a similar horizon to the server's own ping/terminate reaper. +export const REMOTE_RUNTIME_SOCKET_LIVENESS_TIMEOUT_MS = 25_000 + +export type RemoteRuntimeSocketLivenessOptions = { + pingIntervalMs?: number + livenessTimeoutMs?: number +} + +export type RemoteRuntimeSocketLivenessMonitor = { + noteActivity: () => void + stop: () => void +} + +export function startRemoteRuntimeSocketLiveness(args: { + ping: () => void + onDead: () => void + options?: RemoteRuntimeSocketLivenessOptions + now?: () => number +}): RemoteRuntimeSocketLivenessMonitor { + const now = args.now ?? Date.now + const pingIntervalMs = args.options?.pingIntervalMs ?? REMOTE_RUNTIME_SOCKET_PING_INTERVAL_MS + const livenessTimeoutMs = + args.options?.livenessTimeoutMs ?? REMOTE_RUNTIME_SOCKET_LIVENESS_TIMEOUT_MS + let lastActivityAt = now() + let stopped = false + + const timer = setInterval(() => { + if (stopped) { + return + } + if (now() - lastActivityAt > livenessTimeoutMs) { + stop() + args.onDead() + return + } + try { + args.ping() + } catch { + // Why: ping() can throw while a socket is mid-teardown; the liveness + // window (or the close handler) settles the socket's fate either way. + } + }, pingIntervalMs) + // Why: mobile typechecks shared code with DOM timer types where unref is absent. + const unrefable = timer as unknown as { unref?: () => void } + if (typeof unrefable.unref === 'function') { + unrefable.unref() + } + + function stop(): void { + if (stopped) { + return + } + stopped = true + clearInterval(timer) + } + + return { + noteActivity: () => { + lastActivityAt = now() + }, + stop + } +} diff --git a/src/shared/runtime-subscription-replay.ts b/src/shared/runtime-subscription-replay.ts new file mode 100644 index 000000000..b290f1f2c --- /dev/null +++ b/src/shared/runtime-subscription-replay.ts @@ -0,0 +1,25 @@ +// Why: after a shared-control reconnect, the client replays its logical +// subscriptions and the server re-emits each stream's current snapshot. When +// the host did not restart, that snapshot carries the same publicationEpoch/ +// snapshotVersion the client already applied, so monotonic freshness gates +// (e.g. shouldApplyWebSessionTabsSnapshot) would silently drop it and leave +// mirrors frozen (#7718). The connection tags the first response delivered +// after a replay so consumers can treat it as authoritative. The tag is added +// client-side after wire parsing — nothing changes on the protocol, so old +// servers are unaffected. + +const RUNTIME_SUBSCRIPTION_REPLAY_FLAG = '_replayedAfterReconnect' + +export function tagRuntimeSubscriptionReplayResponse( + response: TResponse +): TResponse { + return { ...response, [RUNTIME_SUBSCRIPTION_REPLAY_FLAG]: true } +} + +export function isRuntimeSubscriptionReplayResponse(response: unknown): boolean { + return ( + typeof response === 'object' && + response !== null && + (response as Record)[RUNTIME_SUBSCRIPTION_REPLAY_FLAG] === true + ) +}