diff --git a/src/main/runtime/orca-runtime.test.ts b/src/main/runtime/orca-runtime.test.ts index 07722afcf..c2cafc046 100644 --- a/src/main/runtime/orca-runtime.test.ts +++ b/src/main/runtime/orca-runtime.test.ts @@ -5962,6 +5962,30 @@ describe('OrcaRuntimeService', () => { expect(elapsed).toBeLessThan(500) }) + it('rejects leaf PTY waits when the request signal aborts', async () => { + vi.useFakeTimers() + try { + const runtime = new OrcaRuntimeService(store) + const controller = new AbortController() + + const waitPromise = runtime + .waitForLeafPtyId('missing-handle', 60_000, controller.signal) + .then(() => 'resolved') + .catch((error: Error) => error.message) + + controller.abort() + const outcomePromise = Promise.race([ + waitPromise, + new Promise<'pending'>((resolve) => setTimeout(() => resolve('pending'), 0)) + ]) + await vi.advanceTimersByTimeAsync(0) + + expect(await outcomePromise).toBe('request_aborted') + } finally { + vi.useRealTimers() + } + }) + it('fails terminal waits closed when the handle goes stale during reload', async () => { const runtime = new OrcaRuntimeService(store) diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index 8626d8c4f..817ac932a 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -9584,7 +9584,7 @@ export class OrcaRuntimeService { // Why: mobile clients may subscribe before the PTY spawns (the left pane // of a new workspace). Instead of bailing with a bare scrollback+end, // wait for the PTY to appear so the subscribe can proceed with phone-fit. - waitForLeafPtyId(handle: string, timeoutMs = 10_000): Promise { + waitForLeafPtyId(handle: string, timeoutMs = 10_000, signal?: AbortSignal): Promise { const leaf = this.resolveLeafForHandle(handle) if (leaf?.ptyId) { return Promise.resolve(leaf.ptyId) @@ -9598,15 +9598,40 @@ export class OrcaRuntimeService { const savedLeafId = record?.leafId ?? null return new Promise((resolve, reject) => { - const timer = setTimeout(() => { + let timer: ReturnType | null = null + let check: () => void = () => {} + const cleanup = (): void => { + if (timer) { + clearTimeout(timer) + timer = null + } const idx = this.graphSyncCallbacks.indexOf(check) if (idx !== -1) { this.graphSyncCallbacks.splice(idx, 1) } - reject(new Error('Timed out waiting for PTY to spawn')) + signal?.removeEventListener('abort', onAbort) + } + const finish = (ptyId: string): void => { + cleanup() + resolve(ptyId) + } + const fail = (error: Error): void => { + cleanup() + reject(error) + } + const onAbort = (): void => { + fail(new Error('request_aborted')) + } + if (signal?.aborted) { + reject(new Error('request_aborted')) + return + } + signal?.addEventListener('abort', onAbort, { once: true }) + timer = setTimeout(() => { + fail(new Error('Timed out waiting for PTY to spawn')) }, timeoutMs) - const check = (): void => { + check = (): void => { // Try the handle first (works if handle wasn't invalidated yet) let ptyId = this.resolveLeafForHandle(handle)?.ptyId // Why: when ptyId transitions null→real, issueHandle invalidates the @@ -9616,12 +9641,7 @@ export class OrcaRuntimeService { ptyId = directLeaf?.ptyId ?? null } if (ptyId) { - clearTimeout(timer) - const idx = this.graphSyncCallbacks.indexOf(check) - if (idx !== -1) { - this.graphSyncCallbacks.splice(idx, 1) - } - resolve(ptyId) + finish(ptyId) } } this.graphSyncCallbacks.push(check) diff --git a/src/main/runtime/rpc/methods/terminal.ts b/src/main/runtime/rpc/methods/terminal.ts index 0bcbb965a..d54a47e73 100644 --- a/src/main/runtime/rpc/methods/terminal.ts +++ b/src/main/runtime/rpc/methods/terminal.ts @@ -692,7 +692,7 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [ params: TerminalMultiplex, handler: async ( _params, - { runtime, connectionId, sendBinary, registerBinaryStreamHandler }, + { runtime, connectionId, sendBinary, registerBinaryStreamHandler, signal }, emit ) => { if (!sendBinary || !registerBinaryStreamHandler || !connectionId) { @@ -809,9 +809,12 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [ const isMobile = request.client?.type === 'mobile' if (!leaf?.ptyId && isMobile) { try { - const ptyId = await runtime.waitForLeafPtyId(request.terminal) + const ptyId = await runtime.waitForLeafPtyId(request.terminal, 10_000, signal) leaf = { ptyId } } catch { + if (closed || signal?.aborted) { + return + } // Fall through to the explicit no_connected_pty error below. } } @@ -997,7 +1000,7 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [ params: TerminalSubscribe, handler: async ( params, - { runtime, connectionId, sendBinary, registerBinaryStreamHandler }, + { runtime, connectionId, sendBinary, registerBinaryStreamHandler, signal }, emit ) => { let leaf = runtime.resolveLeafForHandle(params.terminal) @@ -1010,9 +1013,12 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [ // the subscribe can proceed normally. if (!leaf?.ptyId && isMobile) { try { - const ptyId = await runtime.waitForLeafPtyId(params.terminal) + const ptyId = await runtime.waitForLeafPtyId(params.terminal, 10_000, signal) leaf = { ptyId } } catch { + if (signal?.aborted) { + return + } // PTY wait timed out — fall through to scrollback-only path below } } diff --git a/src/main/runtime/rpc/terminal-multiplex.test.ts b/src/main/runtime/rpc/terminal-multiplex.test.ts index 4a8815ec2..a8260b0e2 100644 --- a/src/main/runtime/rpc/terminal-multiplex.test.ts +++ b/src/main/runtime/rpc/terminal-multiplex.test.ts @@ -555,6 +555,83 @@ describe('terminal multiplex RPC', () => { await dispatchPromise }) + it('settles mobile multiplex PTY waits when the stream signal aborts before PTY spawn', async () => { + const messages: string[] = [] + const binaryFrames: Uint8Array[] = [] + const controller = new AbortController() + const handlers = new Map< + number, + (frame: NonNullable>) => void + >() + const cleanups = new Map void>() + const runtime = stubRuntime({ + resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: null }), + waitForLeafPtyId: vi.fn( + (_handle: string, _timeoutMs?: number, signal?: AbortSignal) => + new Promise((_resolve, reject) => { + signal?.addEventListener('abort', () => reject(new Error('request_aborted')), { + once: true + }) + }) + ), + readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), + 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), + { + signal: controller.signal, + connectionId: 'conn-phone-multiplex', + 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: 7, + terminal: 'terminal-1', + client: { id: 'phone-1', type: 'mobile' } + }) + }) + )! + ) + + await vi.waitFor(() => expect(runtime.waitForLeafPtyId).toHaveBeenCalled()) + expect(runtime.waitForLeafPtyId).toHaveBeenCalledWith('terminal-1', 10_000, controller.signal) + + controller.abort() + await Promise.resolve() + await Promise.resolve() + + expect(runtime.readTerminal).not.toHaveBeenCalled() + expect( + messages.map((msg) => JSON.parse(msg).result).filter((result) => result?.streamId === 7) + ).toEqual([]) + expect(binaryFrames.map((frame) => decodeTerminalStreamFrame(frame)?.opcode)).not.toContain( + TerminalStreamOpcode.Error + ) + + cleanups.get('terminal-multiplex:conn-phone-multiplex')?.() + await dispatchPromise + }) + it('bounds live output queued while a multiplex snapshot is loading', async () => { vi.useFakeTimers() try { diff --git a/src/main/runtime/rpc/terminal-subscribe-buffer.test.ts b/src/main/runtime/rpc/terminal-subscribe-buffer.test.ts index 37684303f..48b6f602d 100644 --- a/src/main/runtime/rpc/terminal-subscribe-buffer.test.ts +++ b/src/main/runtime/rpc/terminal-subscribe-buffer.test.ts @@ -1,3 +1,4 @@ +/* oxlint-disable max-lines -- Why: terminal subscribe buffering tests share a live dispatcher harness; splitting would duplicate stream setup and weaken lifecycle coverage. */ import { describe, expect, it, vi } from 'vitest' import { RpcDispatcher } from './dispatcher' import type { RpcRequest } from './core' @@ -23,6 +24,56 @@ function makeRequest(method: string, params?: unknown): RpcRequest { } describe('terminal subscribe buffering', () => { + it('settles mobile subscribe waits when the stream signal aborts before PTY spawn', async () => { + vi.useFakeTimers() + try { + const messages: string[] = [] + const controller = new AbortController() + const runtime = stubRuntime({ + resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: null }), + waitForLeafPtyId: vi.fn( + (_handle: string, _timeoutMs?: number, signal?: AbortSignal) => + new Promise((_resolve, reject) => { + signal?.addEventListener('abort', () => reject(new Error('request_aborted')), { + once: true + }) + }) + ), + readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }) + }) + const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) + + const dispatchPromise = dispatcher.dispatchStreaming( + makeRequest('terminal.subscribe', { + terminal: 'terminal-1', + client: { id: 'phone-1', type: 'mobile' }, + capabilities: { terminalBinaryStream: 1 } + }), + (msg) => messages.push(msg), + { + signal: controller.signal, + connectionId: 'conn-phone', + sendBinary: vi.fn(), + registerBinaryStreamHandler: vi.fn(() => vi.fn()) + } + ) + + expect(runtime.waitForLeafPtyId).toHaveBeenCalled() + controller.abort() + const outcomePromise = Promise.race([ + dispatchPromise.then(() => 'settled'), + new Promise<'pending'>((resolve) => setTimeout(() => resolve('pending'), 0)) + ]) + await vi.advanceTimersByTimeAsync(0) + + expect(await outcomePromise).toBe('settled') + expect(runtime.readTerminal).not.toHaveBeenCalled() + expect(messages).toEqual([]) + } finally { + vi.useRealTimers() + } + }) + it('marks scrollback-only subscribed previews truncated when the uncursored read is limited', async () => { const messages: string[] = [] const runtime = stubRuntime({