fix: abort mobile terminal pty waits on disconnect (#3747)

* fix: abort mobile terminal pty waits on disconnect

* test: cover mobile multiplex pty wait abort

Co-authored-by: Orca <help@stably.ai>

---------

Co-authored-by: Jinwoo-H <jinwoo0825@gmail.com>
Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
Neil
2026-05-30 11:42:46 -07:00
committed by GitHub
co-authored by Orca Jinwoo-H
parent da8a1be9c2
commit b1aec76b2d
5 changed files with 192 additions and 14 deletions
+24
View File
@@ -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)
+30 -10
View File
@@ -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<string> {
waitForLeafPtyId(handle: string, timeoutMs = 10_000, signal?: AbortSignal): Promise<string> {
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<string>((resolve, reject) => {
const timer = setTimeout(() => {
let timer: ReturnType<typeof setTimeout> | 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)
+10 -4
View File
@@ -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
}
}
@@ -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<ArrayBufferLike>[] = []
const controller = new AbortController()
const handlers = new Map<
number,
(frame: NonNullable<ReturnType<typeof decodeTerminalStreamFrame>>) => void
>()
const cleanups = new Map<string, () => void>()
const runtime = stubRuntime({
resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: null }),
waitForLeafPtyId: vi.fn(
(_handle: string, _timeoutMs?: number, signal?: AbortSignal) =>
new Promise<string>((_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 {
@@ -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<string>((_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({