From 8ee33c660f08e154f6a36f1e480f864bb4c5d551 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 27 Aug 2026 15:44:26 -0700 Subject: [PATCH 1/4] fix(relay): scope PTY ids to mint epochs --- src/relay/pty-handler-attach-replay.test.ts | 59 +++++++------ .../pty-handler-dispose-lifecycle.test.ts | 21 +++-- .../pty-handler-output-streaming.test.ts | 57 ++++++------ src/relay/pty-handler-revive.test.ts | 41 +++++---- .../pty-handler-shutdown-signals.test.ts | 33 +++---- .../pty-handler-source-publication.test.ts | 13 +-- src/relay/pty-handler-spawn-admission.test.ts | 86 ++++++++++++++++--- .../pty-handler-spawn-environment.test.ts | 20 +++-- ...y-handler-startup-command-delivery.test.ts | 27 +++--- src/relay/pty-handler-test-harness.ts | 12 ++- src/relay/pty-handler.ts | 12 ++- 11 files changed, 243 insertions(+), 138 deletions(-) diff --git a/src/relay/pty-handler-attach-replay.test.ts b/src/relay/pty-handler-attach-replay.test.ts index 7de5242f2aeb..6af9faec0478 100644 --- a/src/relay/pty-handler-attach-replay.test.ts +++ b/src/relay/pty-handler-attach-replay.test.ts @@ -32,15 +32,18 @@ vi.mock('../main/shell-prompt-readiness-probe', () => ({ createShellPromptReadinessProbe: mockCreateShellPromptReadinessProbe })) -import { PtyHandler, attachIdentityMismatches } from './pty-handler' -import type { RelayDispatcher } from './dispatcher' +import { attachIdentityMismatches, type PtyHandler } from './pty-handler' import { beginPtyHandlerTest, createPtyRequestHelpers, + createTestPtyHandler, + testPtyId, endPtyHandlerTest } from './pty-handler-test-harness' import type { MockDispatcher } from './pty-handler-test-harness' +const PTY_1 = testPtyId(1) + describe('PtyHandler', () => { let dispatcher: MockDispatcher let handler: PtyHandler @@ -83,19 +86,19 @@ describe('PtyHandler', () => { const aliveSpy = vi.spyOn(ptyShellUtils, 'isProcessAlive').mockReturnValue(false) try { await expect( - dispatcher.callRequest('pty.attach', { id: 'pty-1', suppressReplayNotification: true }) - ).rejects.toThrow('PTY "pty-1" not found') + dispatcher.callRequest('pty.attach', { id: PTY_1, suppressReplayNotification: true }) + ).rejects.toThrow(`PTY "${PTY_1}" not found`) } finally { aliveSpy.mockRestore() } // The stale entry is reaped: cache-eviction observers fire and the map slot // is freed so a later attach also cleanly reports not-found. - expect(exits).toEqual([{ id: 'pty-1', paneKey: 'tab-dead:0' }]) + expect(exits).toEqual([{ id: PTY_1, paneKey: 'tab-dead:0' }]) expect(handler.activePtyCount).toBe(0) await expect( - dispatcher.callRequest('pty.attach', { id: 'pty-1', suppressReplayNotification: true }) - ).rejects.toThrow('PTY "pty-1" not found') + dispatcher.callRequest('pty.attach', { id: PTY_1, suppressReplayNotification: true }) + ).rejects.toThrow(`PTY "${PTY_1}" not found`) }) it('settles concurrent immediate shutdown when attach proves the shell exited', async () => { @@ -110,12 +113,12 @@ describe('PtyHandler', () => { let shutdown: Promise | undefined const aliveSpy = vi.spyOn(ptyShellUtils, 'isProcessAlive').mockImplementation(() => { - shutdown = dispatcher.callRequest('pty.shutdown', { id: 'pty-1', immediate: true }) + shutdown = dispatcher.callRequest('pty.shutdown', { id: PTY_1, immediate: true }) return false }) try { - await expect(dispatcher.callRequest('pty.attach', { id: 'pty-1' })).rejects.toThrow( - 'PTY "pty-1" not found' + await expect(dispatcher.callRequest('pty.attach', { id: PTY_1 })).rejects.toThrow( + `PTY "${PTY_1}" not found` ) await expect(shutdown).resolves.toBeUndefined() } finally { @@ -144,7 +147,7 @@ describe('PtyHandler', () => { const aliveSpy = vi.spyOn(ptyShellUtils, 'isProcessAlive').mockReturnValue(true) try { const result = await attachPty({ - id: 'pty-1', + id: PTY_1, suppressReplayNotification: true }) expect(result).toEqual({ incarnationId: spawn.incarnationId, replay: 'prompt$ ' }) @@ -168,7 +171,7 @@ describe('PtyHandler', () => { dataCallback!('buffered output') const result = await attachPty({ - id: 'pty-1', + id: PTY_1, suppressReplayNotification: true }) @@ -197,7 +200,7 @@ describe('PtyHandler', () => { } as never) const result = await attachPty({ - id: 'pty-1', + id: PTY_1, suppressReplayNotification: true }) @@ -264,11 +267,11 @@ describe('PtyHandler', () => { dataCallback!('buffered output') dispatcher.notify.mockClear() - const result = await attachPty({ id: 'pty-1' }) + const result = await attachPty({ id: PTY_1 }) expect(result).toEqual({ incarnationId: spawn.incarnationId }) expect(dispatcher.notify).toHaveBeenCalledWith('pty.replay', { - id: 'pty-1', + id: PTY_1, data: 'buffered output' }) vi.advanceTimersByTime(8) @@ -306,15 +309,15 @@ describe('PtyHandler', () => { await expect( attachPty({ - id: 'pty-1', + id: PTY_1, expectedPaneKey: 'tab-b:leaf-b', expectedTabId: 'tab-b' }) - ).rejects.toThrow('PTY "pty-1" not found') + ).rejects.toThrow(`PTY "${PTY_1}" not found`) await expect( attachPty({ - id: 'pty-1', + id: PTY_1, expectedPaneKey: 'tab-a:leaf-a', expectedTabId: 'tab-a' }) @@ -336,7 +339,7 @@ describe('PtyHandler', () => { exitCallback!({ exitCode: 0 }) expect(dispatcher.notify).toHaveBeenCalledWith('pty.exit', { - id: 'pty-1', + id: PTY_1, code: 0, incarnationId: spawn.incarnationId }) @@ -356,7 +359,7 @@ describe('PtyHandler', () => { tryNotifyPtyExit, legacyRetentionBelowLowWater: true }) - handler = new PtyHandler(dispatcher as unknown as RelayDispatcher) + handler = createTestPtyHandler(dispatcher) let exitCallback: ((info: { exitCode: number }) => void) | undefined mockPtySpawn.mockReturnValue({ ...mockPtyInstance, @@ -372,7 +375,7 @@ describe('PtyHandler', () => { capacityListener?.() expect(tryNotifyPtyExit).toHaveBeenLastCalledWith({ - id: 'pty-1', + id: PTY_1, code: 0, incarnationId: spawn.incarnationId }) @@ -397,11 +400,11 @@ describe('PtyHandler', () => { exitCallback!({ exitCode: 0 }) expect(dispatcher.notify).toHaveBeenNthCalledWith(1, 'pty.data', { - id: 'pty-1', + id: PTY_1, data: 'final output' }) expect(dispatcher.notify).toHaveBeenNthCalledWith(2, 'pty.exit', { - id: 'pty-1', + id: PTY_1, code: 0, incarnationId: spawn.incarnationId }) @@ -427,7 +430,7 @@ describe('PtyHandler', () => { dataCallback!('initial output') const r1 = await attachPty({ - id: 'pty-1', + id: PTY_1, suppressReplayNotification: true }) expect(r1).toEqual({ incarnationId: spawn.incarnationId, replay: 'initial output' }) @@ -435,7 +438,7 @@ describe('PtyHandler', () => { dataCallback!(' more') const r2 = await attachPty({ - id: 'pty-1', + id: PTY_1, suppressReplayNotification: true }) expect(r2).toEqual({ incarnationId: spawn.incarnationId, replay: 'initial output more' }) @@ -457,7 +460,7 @@ describe('PtyHandler', () => { dataCallback!('Mon Apr 28\r\n') const firstAttach = await attachPty({ - id: 'pty-1', + id: PTY_1, suppressReplayNotification: true }) expect(firstAttach.incarnationId).toBe(spawn.incarnationId) @@ -465,7 +468,7 @@ describe('PtyHandler', () => { dataCallback!('Tue Apr 29\r\n') const secondAttach = await attachPty({ - id: 'pty-1', + id: PTY_1, suppressReplayNotification: true }) expect(secondAttach.incarnationId).toBe(spawn.incarnationId) @@ -473,7 +476,7 @@ describe('PtyHandler', () => { dataCallback!('Wed Apr 30\r\n') const result = await attachPty({ - id: 'pty-1', + id: PTY_1, suppressReplayNotification: true }) expect(result).toEqual({ diff --git a/src/relay/pty-handler-dispose-lifecycle.test.ts b/src/relay/pty-handler-dispose-lifecycle.test.ts index a67327c12b48..0553f92a4e5d 100644 --- a/src/relay/pty-handler-dispose-lifecycle.test.ts +++ b/src/relay/pty-handler-dispose-lifecycle.test.ts @@ -32,9 +32,12 @@ vi.mock('../main/shell-prompt-readiness-probe', () => ({ })) import { IMMEDIATE_PTY_EXIT_TIMEOUT_MS, type PtyHandler } from './pty-handler' -import { beginPtyHandlerTest, endPtyHandlerTest } from './pty-handler-test-harness' +import { beginPtyHandlerTest, endPtyHandlerTest, testPtyId } from './pty-handler-test-harness' import type { MockDispatcher } from './pty-handler-test-harness' +const PTY_1 = testPtyId(1) +const PTY_2 = testPtyId(2) + describe('PtyHandler', () => { let dispatcher: MockDispatcher let handler: PtyHandler @@ -71,7 +74,7 @@ describe('PtyHandler', () => { expect(onExitCb).toBeDefined() onExitCb!({ exitCode: 0 }) - expect(exits).toEqual([{ id: 'pty-1', paneKey: 'tab-2:1' }]) + expect(exits).toEqual([{ id: PTY_1, paneKey: 'tab-2:1' }]) }) it('keeps immediate shutdown pending until onExit and invokes the exit listener once', async () => { @@ -92,7 +95,7 @@ describe('PtyHandler', () => { env: { ORCA_PANE_KEY: 'tab-shutdown:0' } }) let settled = false - const shutdown = dispatcher.callRequest('pty.shutdown', { id: 'pty-1', immediate: true }) + const shutdown = dispatcher.callRequest('pty.shutdown', { id: PTY_1, immediate: true }) void shutdown.then(() => { settled = true }) @@ -105,7 +108,7 @@ describe('PtyHandler', () => { await shutdown expect(mockKill).toHaveBeenCalledWith('SIGKILL') - expect(exits).toEqual([{ id: 'pty-1', paneKey: 'tab-shutdown:0' }]) + expect(exits).toEqual([{ id: PTY_1, paneKey: 'tab-shutdown:0' }]) expect(handler.activePtyCount).toBe(0) }) @@ -170,14 +173,14 @@ describe('PtyHandler', () => { }) await dispatcher.callRequest('pty.spawn', {}) - const shutdown = dispatcher.callRequest('pty.shutdown', { id: 'pty-1', immediate: true }) + const shutdown = dispatcher.callRequest('pty.shutdown', { id: PTY_1, immediate: true }) const rejected = expect(shutdown).rejects.toThrow('Timed out waiting for PTY process exit') await vi.advanceTimersByTimeAsync(IMMEDIATE_PTY_EXIT_TIMEOUT_MS) await rejected expect(mockKill).toHaveBeenCalledTimes(1) expect(handler.activePtyCount).toBe(1) - const retry = dispatcher.callRequest('pty.shutdown', { id: 'pty-1', immediate: true }) + const retry = dispatcher.callRequest('pty.shutdown', { id: PTY_1, immediate: true }) expect(mockKill).toHaveBeenCalledTimes(1) onExitCb!({ exitCode: 137 }) await retry @@ -275,7 +278,7 @@ describe('PtyHandler', () => { }) await dispatcher.callRequest('pty.spawn', {}) - await dispatcher.callRequest('pty.shutdown', { id: 'pty-1', immediate: false }) + await dispatcher.callRequest('pty.shutdown', { id: PTY_1, immediate: false }) vi.advanceTimersByTime(5000) expect(mockKill.mock.calls).toEqual([['SIGTERM'], ['SIGKILL']]) expect(vi.getTimerCount()).toBe(1) @@ -325,8 +328,8 @@ describe('PtyHandler', () => { } await dispose expect(exits).toEqual([ - { id: 'pty-1', paneKey: 'tab-dispose:0' }, - { id: 'pty-2', paneKey: 'tab-dispose:1' } + { id: PTY_1, paneKey: 'tab-dispose:0' }, + { id: PTY_2, paneKey: 'tab-dispose:1' } ]) expect(handler.activePtyCount).toBe(0) }) diff --git a/src/relay/pty-handler-output-streaming.test.ts b/src/relay/pty-handler-output-streaming.test.ts index 75bf570687d5..acfa5d07456b 100644 --- a/src/relay/pty-handler-output-streaming.test.ts +++ b/src/relay/pty-handler-output-streaming.test.ts @@ -35,9 +35,16 @@ vi.mock('../main/shell-prompt-readiness-probe', () => ({ import { PtyHandler } from './pty-handler' import { RelayDispatcher } from './dispatcher' import { encodeJsonRpcFrame } from './protocol' -import { beginPtyHandlerTest, endPtyHandlerTest } from './pty-handler-test-harness' +import { + beginPtyHandlerTest, + createTestPtyHandler, + endPtyHandlerTest, + testPtyId +} from './pty-handler-test-harness' import type { MockDispatcher } from './pty-handler-test-harness' +const PTY_1 = testPtyId(1) + describe('PtyHandler', () => { let dispatcher: MockDispatcher let handler: PtyHandler @@ -84,7 +91,7 @@ describe('PtyHandler', () => { writableHighWaterMark: () => 4 * 1024 * 1024 } ) - const boundedHandler = new PtyHandler(boundedDispatcher) + const boundedHandler = new PtyHandler(boundedDispatcher, undefined, 'bounded-test-mint-epoch') try { boundedDispatcher.feed( encodeJsonRpcFrame({ jsonrpc: '2.0', id: 1, method: 'pty.spawn', params: {} }, 1, 0) @@ -125,7 +132,7 @@ describe('PtyHandler', () => { dataCallback!('hello world') expect(dispatcher.notify).not.toHaveBeenCalledWith('pty.data', expect.anything()) vi.advanceTimersByTime(8) - expect(dispatcher.notify).toHaveBeenCalledWith('pty.data', { id: 'pty-1', data: 'hello world' }) + expect(dispatcher.notify).toHaveBeenCalledWith('pty.data', { id: PTY_1, data: 'hello world' }) }) it('consumes capable startup queries before relay replay and fanout', async () => { @@ -153,16 +160,16 @@ describe('PtyHandler', () => { expect(term.write).toHaveBeenCalledWith('\x1b]10;rgb:2e2e/3434/3434\x1b\\') expect(dispatcher.notify).toHaveBeenCalledWith('pty.data', { - id: 'pty-1', + id: PTY_1, data: '', rawLength: query.length, seq: query.length, transformed: true }) - expect(dispatcher.notify).toHaveBeenCalledWith('pty.data', { id: 'pty-1', data: 'prompt' }) + expect(dispatcher.notify).toHaveBeenCalledWith('pty.data', { id: PTY_1, data: 'prompt' }) await expect( dispatcher.callRequest('pty.attach', { - id: 'pty-1', + id: PTY_1, suppressReplayNotification: true }) ).resolves.toEqual({ replay: 'prompt', incarnationId: expect.any(String) }) @@ -184,7 +191,7 @@ describe('PtyHandler', () => { tryNotifyPtyExit: vi.fn(() => true), legacyRetentionBelowLowWater: true }) - handler = new PtyHandler(dispatcher as unknown as RelayDispatcher) + handler = createTestPtyHandler(dispatcher) let dataCallback: ((data: string) => void) | undefined mockPtySpawn.mockReturnValue({ ...mockPtyInstance, @@ -210,13 +217,13 @@ describe('PtyHandler', () => { expect(tryNotifyPtyData).toHaveBeenCalledTimes(3) expect(admitted).toEqual([ { - id: 'pty-1', + id: PTY_1, data: '', rawLength: query.length, seq: query.length, transformed: true }, - { id: 'pty-1', data: 'fresh' } + { id: PTY_1, data: 'fresh' } ]) }) @@ -250,7 +257,7 @@ describe('PtyHandler', () => { Math.min(maxChars, data.length, limit ?? data.length) ) }) - handler = new PtyHandler(dispatcher as unknown as RelayDispatcher) + handler = createTestPtyHandler(dispatcher) dataCallback = undefined mockPtySpawn.mockReturnValue({ ...mockPtyInstance, @@ -278,7 +285,7 @@ describe('PtyHandler', () => { expect(admitted.map((frame) => frame.data).join('')).toBe('a'.repeat(20_000) + 'b'.repeat(10)) expect((admitted[0].data as string).length).toBe(5_000) // Why: remainder frames must not leak transformed/rawLength/seq keys. - expect(admitted[1]).toStrictEqual({ id: 'pty-1', data: expect.any(String) }) + expect(admitted[1]).toStrictEqual({ id: PTY_1, data: expect.any(String) }) }) it('keeps a tail appended after a failed flush under constant capacity', async () => { @@ -331,8 +338,8 @@ describe('PtyHandler', () => { await vi.runAllTimersAsync() expect(admitted).toEqual([ - { id: 'pty-1', data: '', rawLength: 7, seq: 7, transformed: true }, - { id: 'pty-1', data: '', rawLength: 7, seq: 14, transformed: true } + { id: PTY_1, data: '', rawLength: 7, seq: 7, transformed: true }, + { id: PTY_1, data: '', rawLength: 7, seq: 14, transformed: true } ]) }) }) @@ -363,7 +370,7 @@ describe('PtyHandler', () => { vi.advanceTimersByTime(8) expect(term.write).not.toHaveBeenCalled() - expect(dispatcher.notify).toHaveBeenCalledWith('pty.data', { id: 'pty-1', data: query }) + expect(dispatcher.notify).toHaveBeenCalledWith('pty.data', { id: PTY_1, data: query }) } finally { if (originalPlatform) { Object.defineProperty(process, 'platform', originalPlatform) @@ -391,7 +398,7 @@ describe('PtyHandler', () => { expect(term.write).not.toHaveBeenCalled() expect(dispatcher.notify).toHaveBeenCalledWith('pty.data', { - id: 'pty-1', + id: PTY_1, data: '', rawLength: '\x1b]10;?\x07'.length, seq: '\x1b]10;?\x07'.length, @@ -422,7 +429,7 @@ describe('PtyHandler', () => { dataCallback!(query) vi.advanceTimersByTime(8) - expect(dispatcher.notify).toHaveBeenCalledWith('pty.data', { id: 'pty-1', data: query }) + expect(dispatcher.notify).toHaveBeenCalledWith('pty.data', { id: PTY_1, data: query }) } finally { if (originalPlatform) { Object.defineProperty(process, 'platform', originalPlatform) @@ -451,10 +458,10 @@ describe('PtyHandler', () => { dataCallback!('\x1b]11;?\x07') vi.advanceTimersByTime(8) - dispatcher.callNotification('pty.data', { id: 'pty-1', data: reply }) + dispatcher.callNotification('pty.data', { id: PTY_1, data: reply }) expect(dispatcher.notify).toHaveBeenCalledWith('pty.data', { - id: 'pty-1', + id: PTY_1, data: '\x1b]11;?\x07' }) expect(term.write).toHaveBeenCalledWith(reply) @@ -482,7 +489,7 @@ describe('PtyHandler', () => { expect(dispatcher.notify).not.toHaveBeenCalledWith('pty.data', expect.anything()) vi.advanceTimersByTime(8) expect(dispatcher.notify).toHaveBeenCalledWith('pty.data', { - id: 'pty-1', + id: PTY_1, data: 'hello world' }) }) @@ -498,13 +505,13 @@ describe('PtyHandler', () => { }) await dispatcher.callRequest('pty.spawn', {}) - dispatcher.callNotification('pty.data', { id: 'pty-1', data: 'a' }) + dispatcher.callNotification('pty.data', { id: PTY_1, data: 'a' }) dispatcher.notify.mockClear() dataCallback!('\x1b[20;2Hredraw') expect(dispatcher.notify).toHaveBeenCalledWith('pty.data', { - id: 'pty-1', + id: PTY_1, data: '\x1b[20;2Hredraw' }) vi.advanceTimersByTime(8) @@ -528,14 +535,14 @@ describe('PtyHandler', () => { vi.advanceTimersByTime(8) expect(dispatcher.notify).toHaveBeenCalledTimes(1) expect(dispatcher.notify).toHaveBeenNthCalledWith(1, 'pty.data', { - id: 'pty-1', + id: PTY_1, data: firstChunk }) vi.advanceTimersByTime(1) expect(dispatcher.notify).toHaveBeenCalledTimes(2) expect(dispatcher.notify).toHaveBeenNthCalledWith(2, 'pty.data', { - id: 'pty-1', + id: PTY_1, data: 'tail' }) }) @@ -550,7 +557,7 @@ describe('PtyHandler', () => { }) await dispatcher.callRequest('pty.spawn', {}) - dispatcher.callNotification('pty.data', { id: 'pty-1', data: 'ls\n' }) + dispatcher.callNotification('pty.data', { id: PTY_1, data: 'ls\n' }) expect(mockWrite).toHaveBeenCalledWith('ls\n') }) @@ -564,7 +571,7 @@ describe('PtyHandler', () => { }) await dispatcher.callRequest('pty.spawn', {}) - dispatcher.callNotification('pty.resize', { id: 'pty-1', cols: 120, rows: 40 }) + dispatcher.callNotification('pty.resize', { id: PTY_1, cols: 120, rows: 40 }) expect(mockResize).toHaveBeenCalledWith(120, 40) }) diff --git a/src/relay/pty-handler-revive.test.ts b/src/relay/pty-handler-revive.test.ts index 9350067da3b6..c43a9af576a1 100644 --- a/src/relay/pty-handler-revive.test.ts +++ b/src/relay/pty-handler-revive.test.ts @@ -35,15 +35,18 @@ vi.mock('../main/shell-prompt-readiness-probe', () => ({ createShellPromptReadinessProbe: mockCreateShellPromptReadinessProbe })) -import { MAX_RELAY_PTY_SESSIONS, PtyHandler } from './pty-handler' -import type { RelayDispatcher } from './dispatcher' +import { MAX_RELAY_PTY_SESSIONS, type PtyHandler } from './pty-handler' import { beginPtyHandlerTest, createMockDispatcher, + createTestPtyHandler, + testPtyId, endPtyHandlerTest } from './pty-handler-test-harness' import type { MockDispatcher } from './pty-handler-test-harness' +const PTY_1 = testPtyId(1) + describe('PtyHandler', () => { let dispatcher: MockDispatcher let handler: PtyHandler @@ -72,12 +75,12 @@ describe('PtyHandler', () => { ORCA_WORKTREE_ID: 'wt-5' } }) - const state = (await dispatcher.callRequest('pty.serialize', { ids: ['pty-1'] })) as string + const state = (await dispatcher.callRequest('pty.serialize', { ids: [PTY_1] })) as string await handler.dispose({ waitForPhysicalExit: false }) mockPtySpawn.mockClear() dispatcher = createMockDispatcher() - handler = new PtyHandler(dispatcher as unknown as RelayDispatcher) + handler = createTestPtyHandler(dispatcher) handler.addEnvAugmenter(() => ({ ORCA_AGENT_HOOK_PORT: '12345', ORCA_AGENT_HOOK_TOKEN: 'abc-uuid' @@ -200,13 +203,13 @@ describe('PtyHandler', () => { await dispatcher.callRequest('pty.spawn', { command: 'claude' }) - const state = (await dispatcher.callRequest('pty.serialize', { ids: ['pty-1'] })) as string + const state = (await dispatcher.callRequest('pty.serialize', { ids: [PTY_1] })) as string expect(JSON.parse(state)[0]?.gitCredentialPromptGuarded).toBe(true) handler.dispose() mockPtySpawn.mockClear() dispatcher = createMockDispatcher() - handler = new PtyHandler(dispatcher as unknown as RelayDispatcher) + handler = createTestPtyHandler(dispatcher) const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true) try { await dispatcher.callRequest('pty.revive', { state }) @@ -270,7 +273,7 @@ describe('PtyHandler', () => { expect(initialEnv.name).toBe('xterm-256color') expect(initialEnv.env.TERM).toBe('xterm-256color') - const state = (await dispatcher.callRequest('pty.serialize', { ids: ['pty-1'] })) as string + const state = (await dispatcher.callRequest('pty.serialize', { ids: [PTY_1] })) as string const [serialized] = JSON.parse(state) as { explicitTerm?: string envToDelete?: string[] @@ -281,7 +284,7 @@ describe('PtyHandler', () => { await handler.dispose({ waitForPhysicalExit: false }) mockPtySpawn.mockClear() dispatcher = createMockDispatcher() - handler = new PtyHandler(dispatcher as unknown as RelayDispatcher) + handler = createTestPtyHandler(dispatcher) handler.addEnvAugmenter(() => ({ ORCA_STALE_TEST_ENV: '/tmp/revived-stale' })) @@ -347,14 +350,14 @@ describe('PtyHandler', () => { env: { TERM: 'screen-256color' }, envToDelete: ['ORCA_STALE_TEST_ENV'] }) - let state = (await dispatcher.callRequest('pty.serialize', { ids: ['pty-1'] })) as string + let state = (await dispatcher.callRequest('pty.serialize', { ids: [PTY_1] })) as string const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true) try { await handler.dispose({ waitForPhysicalExit: false }) mockPtySpawn.mockClear() dispatcher = createMockDispatcher() - handler = new PtyHandler(dispatcher as unknown as RelayDispatcher) + handler = createTestPtyHandler(dispatcher) handler.addEnvAugmenter(() => ({ ORCA_STALE_TEST_ENV: '/tmp/first-revive' })) @@ -367,7 +370,7 @@ describe('PtyHandler', () => { expect(firstRevivedEnv.name).toBe('screen-256color') expect(firstRevivedEnv.env.TERM).toBe('screen-256color') expect(firstRevivedEnv.env.ORCA_STALE_TEST_ENV).toBeUndefined() - state = (await dispatcher.callRequest('pty.serialize', { ids: ['pty-1'] })) as string + state = (await dispatcher.callRequest('pty.serialize', { ids: [PTY_1] })) as string expect(JSON.parse(state)).toMatchObject([ { explicitTerm: 'screen-256color', @@ -378,7 +381,7 @@ describe('PtyHandler', () => { await handler.dispose({ waitForPhysicalExit: false }) mockPtySpawn.mockClear() dispatcher = createMockDispatcher() - handler = new PtyHandler(dispatcher as unknown as RelayDispatcher) + handler = createTestPtyHandler(dispatcher) handler.addEnvAugmenter(() => ({ ORCA_STALE_TEST_ENV: '/tmp/second-revive' })) @@ -447,12 +450,12 @@ describe('PtyHandler', () => { process.env.ORCA_TAB_ID = oldTabId } } - const state = (await dispatcher.callRequest('pty.serialize', { ids: ['pty-1'] })) as string + const state = (await dispatcher.callRequest('pty.serialize', { ids: [PTY_1] })) as string await handler.dispose({ waitForPhysicalExit: false }) mockPtySpawn.mockClear() dispatcher = createMockDispatcher() - handler = new PtyHandler(dispatcher as unknown as RelayDispatcher) + handler = createTestPtyHandler(dispatcher) const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true) delete process.env.ORCA_PANE_KEY delete process.env.ORCA_TAB_ID @@ -478,11 +481,11 @@ describe('PtyHandler', () => { await expect( dispatcher.callRequest('pty.attach', { - id: 'pty-1', + id: PTY_1, expectedPaneKey: 'tab-other:leaf', expectedTabId: 'tab-other' }) - ).rejects.toThrow('PTY "pty-1" not found') + ).rejects.toThrow(`PTY "${PTY_1}" not found`) }) describe('a Windows relay reviving a WSL pane', () => { @@ -517,13 +520,13 @@ describe('PtyHandler', () => { worktreeId, historyIsolationEnabled: true }) - const state = (await dispatcher.callRequest('pty.serialize', { ids: ['pty-1'] })) as string + const state = (await dispatcher.callRequest('pty.serialize', { ids: [PTY_1] })) as string await handler.dispose({ waitForPhysicalExit: false }) mockPtySpawn.mockClear() rmSync(historyFile, { force: true }) dispatcher = createMockDispatcher() - handler = new PtyHandler(dispatcher as unknown as RelayDispatcher) + handler = createTestPtyHandler(dispatcher) const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true) try { @@ -559,7 +562,7 @@ describe('PtyHandler', () => { it('keeps the override across a second serialize/revive round trip', async () => { await reviveWslPane() - const state = (await dispatcher.callRequest('pty.serialize', { ids: ['pty-1'] })) as string + const state = (await dispatcher.callRequest('pty.serialize', { ids: [PTY_1] })) as string expect(JSON.parse(state)[0]).toMatchObject({ shellOverride: 'wsl.exe', diff --git a/src/relay/pty-handler-shutdown-signals.test.ts b/src/relay/pty-handler-shutdown-signals.test.ts index 22c10bbda2b4..951ce7209e06 100644 --- a/src/relay/pty-handler-shutdown-signals.test.ts +++ b/src/relay/pty-handler-shutdown-signals.test.ts @@ -35,10 +35,13 @@ import type { PtyHandler } from './pty-handler' import { beginPtyHandlerTest, createPtyRequestHelpers, - endPtyHandlerTest + endPtyHandlerTest, + testPtyId } from './pty-handler-test-harness' import type { MockDispatcher } from './pty-handler-test-harness' +const PTY_1 = testPtyId(1) + describe('PtyHandler', () => { let dispatcher: MockDispatcher let handler: PtyHandler @@ -96,7 +99,7 @@ describe('PtyHandler', () => { it('accepts SIGWINCH for restored TUI repaint', async () => { await dispatcher.callRequest('pty.spawn', {}) - await dispatcher.callRequest('pty.sendSignal', { id: 'pty-1', signal: 'SIGWINCH' }) + await dispatcher.callRequest('pty.sendSignal', { id: PTY_1, signal: 'SIGWINCH' }) const term = mockPtySpawn.mock.results[0].value expect(term.kill).toHaveBeenCalledWith('SIGWINCH') @@ -112,7 +115,7 @@ describe('PtyHandler', () => { }) await dispatcher.callRequest('pty.spawn', {}) - await dispatcher.callRequest('pty.shutdown', { id: 'pty-1', immediate: false }) + await dispatcher.callRequest('pty.shutdown', { id: PTY_1, immediate: false }) expect(mockKill).toHaveBeenCalledWith('SIGTERM') }) @@ -153,7 +156,7 @@ describe('PtyHandler', () => { await withWindowsPlatform(async () => { const mockKill = mockKillablePty() await dispatcher.callRequest('pty.spawn', {}) - await dispatcher.callRequest('pty.shutdown', { id: 'pty-1', immediate: false }) + await dispatcher.callRequest('pty.shutdown', { id: PTY_1, immediate: false }) expectBareKills(mockKill, 1) }) }) @@ -171,7 +174,7 @@ describe('PtyHandler', () => { }) }) await dispatcher.callRequest('pty.spawn', {}) - const shutdown = dispatcher.callRequest('pty.shutdown', { id: 'pty-1', immediate: true }) + const shutdown = dispatcher.callRequest('pty.shutdown', { id: PTY_1, immediate: true }) onExitCb!({ exitCode: 137 }) await shutdown expectBareKills(mockKill, 1) @@ -193,9 +196,9 @@ describe('PtyHandler', () => { }) }) await dispatcher.callRequest('pty.spawn', {}) - await dispatcher.callRequest('pty.shutdown', { id: 'pty-1', immediate: false }) + await dispatcher.callRequest('pty.shutdown', { id: PTY_1, immediate: false }) const immediate = dispatcher.callRequest('pty.shutdown', { - id: 'pty-1', + id: PTY_1, immediate: true }) @@ -227,7 +230,7 @@ describe('PtyHandler', () => { await withWindowsPlatform(async () => { const mockKill = mockKillablePty() await dispatcher.callRequest('pty.spawn', {}) - await dispatcher.callRequest('pty.shutdown', { id: 'pty-1', immediate: false }) + await dispatcher.callRequest('pty.shutdown', { id: PTY_1, immediate: false }) expectBareKills(mockKill, 1) vi.advanceTimersByTime(5000) expectBareKills(mockKill, 1) @@ -270,12 +273,12 @@ describe('PtyHandler', () => { await dispatcher.callRequest('pty.spawn', {}) dataCallback!('last words') - const shutdown = dispatcher.callRequest('pty.shutdown', { id: 'pty-1', immediate: true }) + const shutdown = dispatcher.callRequest('pty.shutdown', { id: PTY_1, immediate: true }) onExitCb!({ exitCode: 137 }) await shutdown expect(dispatcher.notify).toHaveBeenNthCalledWith(1, 'pty.data', { - id: 'pty-1', + id: PTY_1, data: 'last words' }) expect(mockKill).toHaveBeenCalledWith('SIGKILL') @@ -296,7 +299,7 @@ describe('PtyHandler', () => { handler.setExitListener((evt) => exits.push(evt)) const spawn = await spawnPty({ env: { ORCA_PANE_KEY: 'tab-fallback:0' } }) - await dispatcher.callRequest('pty.shutdown', { id: 'pty-1', immediate: false }) + await dispatcher.callRequest('pty.shutdown', { id: PTY_1, immediate: false }) vi.advanceTimersByTime(5000) expect(handler.activePtyCount).toBe(1) @@ -307,11 +310,11 @@ describe('PtyHandler', () => { expect(mockKill).toHaveBeenCalledWith('SIGTERM') expect(mockKill).toHaveBeenCalledWith('SIGKILL') expect(dispatcher.notify).toHaveBeenCalledWith('pty.exit', { - id: 'pty-1', + id: PTY_1, code: 137, incarnationId: spawn.incarnationId }) - expect(exits).toEqual([{ id: 'pty-1', paneKey: 'tab-fallback:0' }]) + expect(exits).toEqual([{ id: PTY_1, paneKey: 'tab-fallback:0' }]) expect(handler.activePtyCount).toBe(0) }) @@ -333,7 +336,7 @@ describe('PtyHandler', () => { }) await dispatcher.callRequest('pty.spawn', {}) - await dispatcher.callRequest('pty.shutdown', { id: 'pty-1', immediate: false }) + await dispatcher.callRequest('pty.shutdown', { id: PTY_1, immediate: false }) vi.advanceTimersByTime(5000) expect(mockKill.mock.calls).toEqual([['SIGTERM'], ['SIGKILL']]) @@ -362,7 +365,7 @@ describe('PtyHandler', () => { }) await dispatcher.callRequest('pty.spawn', {}) - const shutdown = dispatcher.callRequest('pty.shutdown', { id: 'pty-1', immediate: true }) + const shutdown = dispatcher.callRequest('pty.shutdown', { id: PTY_1, immediate: true }) onExitCb!({ exitCode: 137 }) await shutdown expect(mockKill).toHaveBeenCalledWith('SIGKILL') diff --git a/src/relay/pty-handler-source-publication.test.ts b/src/relay/pty-handler-source-publication.test.ts index f0041a57ce5a..cee7637019d5 100644 --- a/src/relay/pty-handler-source-publication.test.ts +++ b/src/relay/pty-handler-source-publication.test.ts @@ -7,11 +7,14 @@ import { } from './dispatcher' import { encodeJsonRpcFrame, MessageType } from './protocol' import { PtyHandler } from './pty-handler' +import { TEST_PTY_ID_MINT_EPOCH, testPtyId } from './pty-handler-test-harness' import { RelayPtySourcePublication } from './relay-pty-source-publication' import { SshPtyConsumerSessionAdapter } from './ssh-pty-consumer-session-adapter' const { mockPtySpawn } = vi.hoisted(() => ({ mockPtySpawn: vi.fn() })) +const PTY_1 = testPtyId(1) + vi.mock('node-pty', () => ({ spawn: mockPtySpawn })) const endpointIdentity: RelayClientSessionIdentity = { @@ -127,7 +130,7 @@ describe('PtyHandler negotiated source publication', () => { }, endpointIdentity ) - handler = new PtyHandler(dispatcher) + handler = new PtyHandler(dispatcher, undefined, TEST_PTY_ID_MINT_EPOCH) adapter = new SshPtyConsumerSessionAdapter(dispatcher, 'build-a', undefined, (id) => publication.onCreditAvailable(id) ) @@ -656,14 +659,14 @@ describe('PtyHandler negotiated source publication', () => { expect( responseResult(replacementWrites.find((buffer) => responseResult(buffer, 4))!, 4) ).toMatchObject({ - id: 'pty-1', + id: PTY_1, incarnationId: expect.any(String), sourceActivation: expect.objectContaining({ deliveryToken: expect.any(String) }) }) expect( replacementWrites.map(notification).find((frame) => frame?.method === 'pty.data')?.params ).toMatchObject({ - id: 'pty-1', + id: PTY_1, data: 'prompt', sourceLengthSu: 6, sourceEndSu: 6 @@ -685,7 +688,7 @@ describe('PtyHandler negotiated source publication', () => { await vi.advanceTimersByTimeAsync(8) expect(projectSpy).toHaveBeenCalledTimes(1) - handler.handleSourcePublicationCapacity('pty-1') + handler.handleSourcePublicationCapacity(PTY_1) await vi.advanceTimersByTimeAsync(8) // Retried projection carries the byte-identical span params. @@ -780,7 +783,7 @@ describe('PtyHandler negotiated source publication', () => { describe('a second attach for the same client', () => { async function attach(id: number, params: Record) { writes = [] - dispatcher.feed(requestFrame(id, 'pty.attach', { id: 'pty-1', ...params })) + dispatcher.feed(requestFrame(id, 'pty.attach', { id: PTY_1, ...params })) await vi.advanceTimersByTimeAsync(0) return writes.map((buffer) => responseResult(buffer, id)).find(Boolean) } diff --git a/src/relay/pty-handler-spawn-admission.test.ts b/src/relay/pty-handler-spawn-admission.test.ts index aae35a2e1668..056220648211 100644 --- a/src/relay/pty-handler-spawn-admission.test.ts +++ b/src/relay/pty-handler-spawn-admission.test.ts @@ -38,6 +38,8 @@ import { beginPtyHandlerTest, createMockDispatcher, createPtyRequestHelpers, + createTestPtyHandler, + testPtyId, endPtyHandlerTest } from './pty-handler-test-harness' import type { MockDispatcher } from './pty-handler-test-harness' @@ -93,7 +95,7 @@ describe('PtyHandler', () => { it('spawns a PTY and returns an id', async () => { const result = await spawnPty({ cols: 80, rows: 24 }) - expect(result).toEqual({ id: 'pty-1', incarnationId: expect.any(String) }) + expect(result).toEqual({ id: testPtyId(1), incarnationId: expect.any(String) }) expect(mockPtySpawn).toHaveBeenCalled() expect(handler.activePtyCount).toBe(1) }) @@ -112,7 +114,7 @@ describe('PtyHandler', () => { agentSessionCreateOperationId: operationId }) - expect(replayed).toEqual({ id: 'pty-1', incarnationId: expect.any(String) }) + expect(replayed).toEqual({ id: testPtyId(1), incarnationId: expect.any(String) }) expect(mockPtySpawn).toHaveBeenCalledOnce() expect(mockPtyInstance.kill).not.toHaveBeenCalled() expect(handler.activePtyCount).toBe(1) @@ -166,7 +168,7 @@ describe('PtyHandler', () => { loadPty.mockResolvedValue({ spawn: mockPtySpawn }) await expect(dispatcher.callRequest('pty.spawn', request)).resolves.toMatchObject({ - id: expect.stringMatching(/^pty-/) + id: testPtyId(2) }) expect(mockPtySpawn).toHaveBeenCalledOnce() }) @@ -207,11 +209,11 @@ describe('PtyHandler', () => { })) as Record expect(first).toMatchObject({ - id: 'pty-1', + id: testPtyId(1), agentSessionEnsure: { disposition: 'created' } }) expect(second).toMatchObject({ - id: 'pty-1', + id: testPtyId(1), agentSessionEnsure: { disposition: 'adopted' } }) expect(second.agentSessionEnsure).toMatchObject({ @@ -283,7 +285,9 @@ describe('PtyHandler', () => { const descriptor = Object.getOwnPropertyDescriptor(Array.prototype, 'toReversed') Reflect.deleteProperty(Array.prototype, 'toReversed') try { - await expect(dispatcher.callRequest('pty.spawn', {})).resolves.toMatchObject({ id: 'pty-1' }) + await expect(dispatcher.callRequest('pty.spawn', {})).resolves.toMatchObject({ + id: testPtyId(1) + }) expect(handler.activePtyCount).toBe(1) } finally { if (descriptor) { @@ -295,8 +299,62 @@ describe('PtyHandler', () => { it('increments PTY ids on each spawn', async () => { const r1 = await dispatcher.callRequest('pty.spawn', {}) const r2 = await dispatcher.callRequest('pty.spawn', {}) - expect((r1 as { id: string }).id).toBe('pty-1') - expect((r2 as { id: string }).id).toBe('pty-2') + expect((r1 as { id: string }).id).toBe(testPtyId(1)) + expect((r2 as { id: string }).id).toBe(testPtyId(2)) + }) + + it('does not remint a PTY id across handler lifetimes', async () => { + const first = (await dispatcher.callRequest('pty.spawn', {})) as { id: string } + await handler.dispose({ waitForPhysicalExit: false }) + dispatcher = createMockDispatcher() + handler = new PtyHandler(dispatcher as unknown as RelayDispatcher) + + const second = (await dispatcher.callRequest('pty.spawn', {})) as { id: string } + + expect(first.id).toMatch(/^pty2:[^:]+:1$/) + expect(second.id).toMatch(/^pty2:[^:]+:1$/) + expect(second.id).not.toBe(first.id) + }) + + it('revives a legacy id and advances the legacy sequence', async () => { + const state = JSON.stringify([ + { id: 'pty-7', pid: process.pid, cols: 80, rows: 24, cwd: process.cwd() } + ]) + const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true) + try { + await dispatcher.callRequest('pty.revive', { state }) + } finally { + killSpy.mockRestore() + } + + const serialized = (await dispatcher.callRequest('pty.serialize', { + ids: ['pty-7'] + })) as string + const spawned = (await dispatcher.callRequest('pty.spawn', {})) as { id: string } + + expect(JSON.parse(serialized)).toMatchObject([{ id: 'pty-7' }]) + expect(spawned.id).toBe(testPtyId(8)) + }) + + it('does not advance its sequence from a revived foreign mint epoch', async () => { + const foreignId = 'pty2:previous-mint-epoch:40' + const state = JSON.stringify([ + { id: foreignId, pid: process.pid, cols: 80, rows: 24, cwd: process.cwd() } + ]) + const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true) + try { + await dispatcher.callRequest('pty.revive', { state }) + } finally { + killSpy.mockRestore() + } + + const serialized = (await dispatcher.callRequest('pty.serialize', { + ids: [foreignId] + })) as string + const spawned = (await dispatcher.callRequest('pty.spawn', {})) as { id: string } + + expect(JSON.parse(serialized)).toMatchObject([{ id: foreignId }]) + expect(spawned.id).toBe(testPtyId(1)) }) it('admits default-cwd spawns through the worktree removal coordinator', async () => { @@ -370,9 +428,9 @@ describe('PtyHandler', () => { const aliveSpy = vi.spyOn(ptyShellUtils, 'isProcessAlive').mockReturnValue(false) try { - await expect(attachPty({ id: 'pty-1', suppressReplayNotification: true })).rejects.toThrow( - 'PTY "pty-1" not found' - ) + await expect( + attachPty({ id: testPtyId(1), suppressReplayNotification: true }) + ).rejects.toThrow(`PTY "${testPtyId(1)}" not found`) } finally { aliveSpy.mockRestore() } @@ -477,10 +535,12 @@ describe('PtyHandler', () => { it('fires for a revived PTY whose creation was admitted before the pool was empty', async () => { await spawnPty({ cols: 80, rows: 24, cwd: '/tmp' }) - const state = (await dispatcher.callRequest('pty.serialize', { ids: ['pty-1'] })) as string + const state = (await dispatcher.callRequest('pty.serialize', { + ids: [testPtyId(1)] + })) as string await handler.dispose({ waitForPhysicalExit: false }) dispatcher = createMockDispatcher() - handler = new PtyHandler(dispatcher as unknown as RelayDispatcher) + handler = createTestPtyHandler(dispatcher) mockPtySpawn.mockReturnValue({ ...mockPtyInstance, onData: vi.fn(), onExit: vi.fn() }) const poolActive = vi.fn() handler.onPtyPoolActive(poolActive) diff --git a/src/relay/pty-handler-spawn-environment.test.ts b/src/relay/pty-handler-spawn-environment.test.ts index 39c5a207a481..8879686821ea 100644 --- a/src/relay/pty-handler-spawn-environment.test.ts +++ b/src/relay/pty-handler-spawn-environment.test.ts @@ -41,15 +41,19 @@ vi.mock('../main/shell-prompt-readiness-probe', () => ({ createShellPromptReadinessProbe: mockCreateShellPromptReadinessProbe })) -import { PtyHandler } from './pty-handler' -import type { RelayDispatcher } from './dispatcher' +import type { PtyHandler } from './pty-handler' import { beginPtyHandlerTest, createMockDispatcher, + createTestPtyHandler, + testPtyId, endPtyHandlerTest } from './pty-handler-test-harness' import type { MockDispatcher } from './pty-handler-test-harness' +const PTY_1 = testPtyId(1) +const PTY_2 = testPtyId(2) + describe('PtyHandler', () => { let dispatcher: MockDispatcher let handler: PtyHandler @@ -184,12 +188,12 @@ describe('PtyHandler', () => { expect(spawnedEnv.env.ORCA_ATTRIBUTION_SHIM_DIR).toBeUndefined() const state = (await dispatcher.callRequest('pty.serialize', { - ids: ['pty-1'] + ids: [PTY_1] })) as string await handler.dispose({ waitForPhysicalExit: false }) mockPtySpawn.mockClear() dispatcher = createMockDispatcher() - handler = new PtyHandler(dispatcher as unknown as RelayDispatcher) + handler = createTestPtyHandler(dispatcher) const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true) try { await dispatcher.callRequest('pty.revive', { state }) @@ -498,7 +502,7 @@ describe('PtyHandler', () => { expect(userEnv.GIT_CONFIG_COUNT).toBe('1') expect(userEnv.GIT_CONFIG_KEY_0).toBe('core.quotePath') expect(userEnv.GIT_CONFIG_KEY_1).toBeUndefined() - const state = (await dispatcher.callRequest('pty.serialize', { ids: ['pty-1'] })) as string + const state = (await dispatcher.callRequest('pty.serialize', { ids: [PTY_1] })) as string expect(JSON.parse(state)[0]?.gitCredentialPromptGuarded).toBe(false) } finally { Object.defineProperty(process, 'platform', { @@ -557,14 +561,14 @@ describe('PtyHandler', () => { const firstEnv = mockPtySpawn.mock.calls[0][2] as { env: Record } const secondEnv = mockPtySpawn.mock.calls[1][2] as { env: Record } expect(seenContexts[0]).toMatchObject({ - id: 'pty-1', + id: PTY_1, paneKey: 'tab-context:0', launchAgent: 'pi', env: { ORCA_PANE_KEY: 'tab-context:0' } }) - expect(seenContexts[1]).toMatchObject({ id: 'pty-2', paneKey: undefined }) + expect(seenContexts[1]).toMatchObject({ id: PTY_2, paneKey: undefined }) expect(firstEnv.env.OVERLAY_ID).toBe('tab-context:0') - expect(secondEnv.env.OVERLAY_ID).toBe('pty-2') + expect(secondEnv.env.OVERLAY_ID).toBe(PTY_2) }) it('passes process and renderer env to env augmenters before augmenter overrides are applied', async () => { diff --git a/src/relay/pty-handler-startup-command-delivery.test.ts b/src/relay/pty-handler-startup-command-delivery.test.ts index 8e522e68f596..817ca7563854 100644 --- a/src/relay/pty-handler-startup-command-delivery.test.ts +++ b/src/relay/pty-handler-startup-command-delivery.test.ts @@ -40,10 +40,13 @@ import type { PtyHandler } from './pty-handler' import { beginPtyHandlerTest, createPtyRequestHelpers, - endPtyHandlerTest + endPtyHandlerTest, + testPtyId } from './pty-handler-test-harness' import type { MockDispatcher } from './pty-handler-test-harness' +const PTY_1 = testPtyId(1) + describe('PtyHandler', () => { let dispatcher: MockDispatcher let handler: PtyHandler @@ -293,7 +296,7 @@ describe('PtyHandler', () => { expect(handler.retainedStartupCommandCount).toBe(0) vi.advanceTimersByTime(8) expect(dispatcher.notify).toHaveBeenCalledWith('pty.data', { - id: 'pty-1', + id: PTY_1, data: 'user@remote $ ' }) } @@ -340,7 +343,7 @@ describe('PtyHandler', () => { mockCreateShellPromptReadinessProbe.mock.results[0]?.value.notifyOutput ).toHaveBeenCalledWith('\x1b[?2004hremote $ ') expect(dispatcher.notify).toHaveBeenCalledWith('pty.data', { - id: 'pty-1', + id: PTY_1, data: '\x1b[?2004hremote $ ' }) promptOptions.onPromptReady() @@ -384,7 +387,7 @@ describe('PtyHandler', () => { dataCallback?.(`\x1b]777;orca-shell-start:${process.pid}\x07\x1b[?2004hremote $ `) await vi.advanceTimersByTimeAsync(8) expect(dispatcher.notify).toHaveBeenCalledWith('pty.data', { - id: 'pty-1', + id: PTY_1, data: '\x1b[?2004hremote $ ' }) @@ -396,7 +399,7 @@ describe('PtyHandler', () => { expect(term.write).not.toHaveBeenCalled() expect(dispatcher.notify).toHaveBeenCalledWith('pty.data', { - id: 'pty-1', + id: PTY_1, data: '\x1b]777;orca-shell-ready\x07' }) expect(handler.retainedStartupCommandCount).toBe(0) @@ -439,7 +442,7 @@ describe('PtyHandler', () => { await vi.advanceTimersByTimeAsync(8) expect(dispatcher.notify).toHaveBeenCalledWith('pty.data', { - id: 'pty-1', + id: PTY_1, data: '\x1b]777;orca-shell-ready\x07remote $ ' }) expect(handler.retainedStartupCommandCount).toBe(0) @@ -484,7 +487,7 @@ describe('PtyHandler', () => { expect(probe.notifyOutput).not.toHaveBeenCalled() expect(probe.dispose).toHaveBeenCalledOnce() expect(dispatcher.notify).toHaveBeenCalledWith('pty.data', { - id: 'pty-1', + id: PTY_1, data: '\x1b]777;orca-shell-ready\x07remote $ ' }) expect(handler.retainedStartupCommandCount).toBe(0) @@ -563,12 +566,12 @@ describe('PtyHandler', () => { expect(term.write).toHaveBeenCalledWith('echo fallback\n') vi.advanceTimersByTime(8) expect(dispatcher.notify).toHaveBeenCalledWith('pty.data', { - id: 'pty-1', + id: PTY_1, data: '\x1b]777;orca-shell-ready' }) const result = await attachPty({ - id: 'pty-1', + id: PTY_1, suppressReplayNotification: true }) expect(result).toEqual({ @@ -609,8 +612,8 @@ describe('PtyHandler', () => { const aliveSpy = vi.spyOn(ptyShellUtils, 'isProcessAlive').mockReturnValue(false) try { - await expect(dispatcher.callRequest('pty.attach', { id: 'pty-1' })).rejects.toThrow( - 'PTY "pty-1" not found' + await expect(dispatcher.callRequest('pty.attach', { id: PTY_1 })).rejects.toThrow( + `PTY "${PTY_1}" not found` ) } finally { aliveSpy.mockRestore() @@ -658,7 +661,7 @@ describe('PtyHandler', () => { }) expect(handler.retainedStartupCommandCount).toBe(1) - const shutdown = dispatcher.callRequest('pty.shutdown', { id: 'pty-1', immediate: true }) + const shutdown = dispatcher.callRequest('pty.shutdown', { id: PTY_1, immediate: true }) onExitCb!({ exitCode: 137 }) await shutdown vi.advanceTimersByTime(50) diff --git a/src/relay/pty-handler-test-harness.ts b/src/relay/pty-handler-test-harness.ts index 04dc828e5078..4a82aada1970 100644 --- a/src/relay/pty-handler-test-harness.ts +++ b/src/relay/pty-handler-test-harness.ts @@ -4,6 +4,16 @@ import * as ptyShellUtils from './pty-shell-utils' import { PtyHandler } from './pty-handler' import type { RelayDispatcher } from './dispatcher' +export const TEST_PTY_ID_MINT_EPOCH = 'test-mint-epoch' + +export function testPtyId(sequence: number): string { + return `pty2:${TEST_PTY_ID_MINT_EPOCH}:${sequence}` +} + +export function createTestPtyHandler(dispatcher: MockDispatcher): PtyHandler { + return new PtyHandler(dispatcher as unknown as RelayDispatcher, undefined, TEST_PTY_ID_MINT_EPOCH) +} + export type TestRequestContext = { isStale: () => boolean signal?: AbortSignal @@ -108,7 +118,7 @@ export function beginPtyHandlerTest(mocks: PtyHandlerTestMocks): { mockPtySpawn.mockReturnValue({ ...mockPtyInstance }) const dispatcher = createMockDispatcher() - const handler = new PtyHandler(dispatcher as unknown as RelayDispatcher) + const handler = createTestPtyHandler(dispatcher) return { dispatcher, handler, originalPlatform } } diff --git a/src/relay/pty-handler.ts b/src/relay/pty-handler.ts index a9fd21a4fe23..79c5344c1fa5 100644 --- a/src/relay/pty-handler.ts +++ b/src/relay/pty-handler.ts @@ -393,7 +393,7 @@ type PtyIdentity = { paneKey?: string; tabId?: string } /** * True when a reattach's expected pane identity contradicts the target PTY's own. - * Rejects cross-relay-generation id collisions (a reset relay reuses `pty-N`). + * Rejects legacy cross-relay-generation id collisions (a reset relay reused `pty-N`). * Only compares fields present on both sides; absent identity stays permissive. */ export function attachIdentityMismatches(expected: PtyIdentity, managed: PtyIdentity): boolean { @@ -419,6 +419,7 @@ export type RelayPtyWorktreeRemovalCoordinator = { export class PtyHandler { private ptys = new Map() + private readonly ptyIdMintEpoch: string private nextId = 1 private dispatcher: RelayDispatcher private graceTimeMs: number @@ -453,9 +454,14 @@ export class PtyHandler { Promise >() - constructor(dispatcher: RelayDispatcher, graceTimeMs = DEFAULT_GRACE_TIME_MS) { + constructor( + dispatcher: RelayDispatcher, + graceTimeMs = DEFAULT_GRACE_TIME_MS, + ptyIdMintEpoch: string = randomUUID() + ) { this.dispatcher = dispatcher this.graceTimeMs = graceTimeMs + this.ptyIdMintEpoch = ptyIdMintEpoch this.registerHandlers() this.removeLegacyCapacityListener = this.dispatcher.onLegacyPtyCapacity?.(() => this.handleLegacyCapacity()) ?? null @@ -1580,7 +1586,7 @@ export class PtyHandler { const shell = resolvedShellOverride || requestedEnvShell || resolveDefaultShell() let id: string do { - id = `pty-${this.nextId++}` + id = `pty2:${encodeURIComponent(this.ptyIdMintEpoch)}:${this.nextId++}` } while (this.ptys.has(id) || this.pendingReviveIds.has(id)) // Why: augmenter values override renderer env so remote paths and hook coords win over local userData. From 557d0b596979ef29aff22e67bf3db285421c8aa3 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 27 Aug 2026 16:56:12 -0700 Subject: [PATCH 2/4] test(relay): treat minted PTY ids as opaque --- src/relay/pty-handler-output-drain-differential.test.ts | 8 ++++++-- src/relay/subprocess.test.ts | 4 ++-- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/src/relay/pty-handler-output-drain-differential.test.ts b/src/relay/pty-handler-output-drain-differential.test.ts index 22ba265cd10a..cbaee4bcb75e 100644 --- a/src/relay/pty-handler-output-drain-differential.test.ts +++ b/src/relay/pty-handler-output-drain-differential.test.ts @@ -159,16 +159,20 @@ describe('relay PTY output drain — differential vs the pre-optimization snapsh async function spawnPtys(count: number): Promise { const ids: string[] = [] for (let i = 0; i < count; i++) { + let dataCallback!: (data: string) => void + let exitCallback!: (event: { exitCode: number }) => void mockPtySpawn.mockReturnValueOnce({ ...mockPtyInstance, onData: vi.fn((cb: (data: string) => void) => { - dataCallbacks.set(`pty-${i + 1}`, cb) + dataCallback = cb }), onExit: vi.fn((cb: (event: { exitCode: number }) => void) => { - exitCallbacks.set(`pty-${i + 1}`, cb) + exitCallback = cb }) }) const spawned = (await dispatcher.callRequest('pty.spawn', {})) as { id: string } + dataCallbacks.set(spawned.id, dataCallback) + exitCallbacks.set(spawned.id, exitCallback) ids.push(spawned.id) } return ids diff --git a/src/relay/subprocess.test.ts b/src/relay/subprocess.test.ts index 18d837bb4ef5..1aea75a800dc 100644 --- a/src/relay/subprocess.test.ts +++ b/src/relay/subprocess.test.ts @@ -204,7 +204,7 @@ describe('Subprocess: Relay entry point', () => { const repairedId = relay.send('pty.spawn', { cols: 80, rows: 24 }) const repaired = await relay.waitForResponse(repairedId) expect(repaired.error).toBeUndefined() - expect(repaired.result).toMatchObject({ id: 'pty-1' }) + expect(repaired.result).toMatchObject({ id: expect.any(String) }) }, 10_000) it('reloads node-pty after a late native binding failure without restarting', async () => { @@ -228,7 +228,7 @@ describe('Subprocess: Relay entry point', () => { const repairedId = relay.send('pty.spawn', { cols: 80, rows: 24 }) const repaired = await relay.waitForResponse(repairedId) expect(repaired.error).toBeUndefined() - expect(repaired.result).toMatchObject({ id: 'pty-2' }) + expect(repaired.result).toMatchObject({ id: expect.any(String) }) }, 10_000) it('responds to fs.stat over stdin/stdout', async () => { From 810b6ba71def571611ab6092db12b0fe0c7274ad Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 28 Aug 2026 02:47:02 -0700 Subject: [PATCH 3/4] test(relay): pin mint-epoch id shape and restore spawn-sequence assertions The epoch escaping had no test: dropping encodeURIComponent left the whole relay suite green. Pin the three-field id shape against an epoch that carries both separators, and cover a colon-bearing relay id through the unchanged app-side SSH id wrapper. subprocess.test.ts had traded `pty-1`/`pty-2` for `expect.any(String)`, which discarded the invariant those two cases exist to prove: an early node-pty load failure burns no sequence, a late spawn failure burns one. --- src/relay/pty-handler-spawn-admission.test.ts | 18 ++++++++++++++++++ src/relay/pty-handler.ts | 2 +- src/relay/subprocess.test.ts | 6 ++++-- src/shared/ssh-pty-id.test.ts | 18 ++++++++++++++++++ 4 files changed, 41 insertions(+), 3 deletions(-) diff --git a/src/relay/pty-handler-spawn-admission.test.ts b/src/relay/pty-handler-spawn-admission.test.ts index 056220648211..2df29b954202 100644 --- a/src/relay/pty-handler-spawn-admission.test.ts +++ b/src/relay/pty-handler-spawn-admission.test.ts @@ -316,6 +316,24 @@ describe('PtyHandler', () => { expect(second.id).not.toBe(first.id) }) + it('escapes the mint epoch so it cannot forge the id separators', async () => { + await handler.dispose({ waitForPhysicalExit: false }) + dispatcher = createMockDispatcher() + // Why: the epoch is constructor-supplied. Encoding is what keeps a minted id + // exactly three fields, so it can never be read as another epoch/sequence and + // can never smuggle the `@@` that app-side SSH id routing splits on. + handler = new PtyHandler(dispatcher as unknown as RelayDispatcher, undefined, 'a:b@@c:9') + + const spawned = (await dispatcher.callRequest('pty.spawn', {})) as { id: string } + + const [prefix, epoch, sequence, ...extra] = spawned.id.split(':') + expect(extra).toEqual([]) + expect(prefix).toBe('pty2') + expect(decodeURIComponent(epoch)).toBe('a:b@@c:9') + expect(sequence).toBe('1') + expect(spawned.id).not.toContain('@@') + }) + it('revives a legacy id and advances the legacy sequence', async () => { const state = JSON.stringify([ { id: 'pty-7', pid: process.pid, cols: 80, rows: 24, cwd: process.cwd() } diff --git a/src/relay/pty-handler.ts b/src/relay/pty-handler.ts index 79c5344c1fa5..2e28bda5ddde 100644 --- a/src/relay/pty-handler.ts +++ b/src/relay/pty-handler.ts @@ -1795,7 +1795,7 @@ export class PtyHandler { throw new Error(`PTY "${id}" not found`) } - // Why: generation resets can reuse PTY IDs; reject conflicting identities. + // Why: legacy `pty-N` ids repeated across relay generations; reject conflicting identities. const mismatch = attachIdentityMismatches( { paneKey: typeof params.expectedPaneKey === 'string' ? params.expectedPaneKey : undefined, diff --git a/src/relay/subprocess.test.ts b/src/relay/subprocess.test.ts index 1aea75a800dc..0c7eea107656 100644 --- a/src/relay/subprocess.test.ts +++ b/src/relay/subprocess.test.ts @@ -204,7 +204,8 @@ describe('Subprocess: Relay entry point', () => { const repairedId = relay.send('pty.spawn', { cols: 80, rows: 24 }) const repaired = await relay.waitForResponse(repairedId) expect(repaired.error).toBeUndefined() - expect(repaired.result).toMatchObject({ id: expect.any(String) }) + // Why: a spawn that never loaded node-pty must not burn a mint sequence, so the repair is still :1. + expect(repaired.result).toMatchObject({ id: expect.stringMatching(/^pty2:[^:]+:1$/) }) }, 10_000) it('reloads node-pty after a late native binding failure without restarting', async () => { @@ -228,7 +229,8 @@ describe('Subprocess: Relay entry point', () => { const repairedId = relay.send('pty.spawn', { cols: 80, rows: 24 }) const repaired = await relay.waitForResponse(repairedId) expect(repaired.error).toBeUndefined() - expect(repaired.result).toMatchObject({ id: expect.any(String) }) + // Why: the late failure happens after the id is minted, so the repair lands on the next sequence. + expect(repaired.result).toMatchObject({ id: expect.stringMatching(/^pty2:[^:]+:2$/) }) }, 10_000) it('responds to fs.stat over stdin/stdout', async () => { diff --git a/src/shared/ssh-pty-id.test.ts b/src/shared/ssh-pty-id.test.ts index b8fcfd8d373d..7e105307433c 100644 --- a/src/shared/ssh-pty-id.test.ts +++ b/src/shared/ssh-pty-id.test.ts @@ -27,6 +27,24 @@ describe('ssh pty id routing', () => { expect(toAppSshPtyId(HOST_ID, 'pty-7')).toBe('ssh:ssh-1779863656395-57g1q1@@pty-7') }) + // Why: relays mint epoch-scoped ids (`pty2::`) that carry colons, while + // this wrapper — unchanged here, and the version shipped in older clients — splits + // an app id on the FIRST `@@` after `ssh:`. Pin the round trip so a colon-bearing + // relay id stays routable instead of losing its owning connection. + it('round-trips a mint-epoch relay pty id', () => { + const relayPtyId = 'pty2:0f8fad5b-d9cb-469f-a165-70867728950e:12' + const appId = toAppSshPtyId(CONNECTION, relayPtyId) + + expect(appId).toBe(`ssh:${CONNECTION}@@${relayPtyId}`) + expect(parseAppSshPtyId(appId)).toEqual({ connectionId: CONNECTION, relayPtyId }) + expect(toRelaySshPtyId(CONNECTION, appId)).toBe(relayPtyId) + expect(toRelaySshPtyId(HOST_ID, appId)).toBe(relayPtyId) + expect(toAppSshPtyId(CONNECTION, appId)).toBe(appId) + expect(() => toRelaySshPtyId('ssh-other', appId)).toThrow( + `belongs to SSH connection "${CONNECTION}"` + ) + }) + it('still rejects a pty id owned by a genuinely different connection', () => { expect(() => toRelaySshPtyId('ssh-other', APP_ID)).toThrow( `belongs to SSH connection "${CONNECTION}"` From b5c3215645f2cedd54dab1726da8ef32d0bb8328 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 28 Aug 2026 02:49:24 -0700 Subject: [PATCH 4/4] test(relay): mirror production epoch escaping in testPtyId The harness built the expected id without the encodeURIComponent production applies at the mint site. A test epoch carrying a reserved character would diverge silently across ~40 assertions in 11 files. --- src/relay/pty-handler-test-harness.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/relay/pty-handler-test-harness.ts b/src/relay/pty-handler-test-harness.ts index 4a82aada1970..e3d99213ea55 100644 --- a/src/relay/pty-handler-test-harness.ts +++ b/src/relay/pty-handler-test-harness.ts @@ -6,8 +6,10 @@ import type { RelayDispatcher } from './dispatcher' export const TEST_PTY_ID_MINT_EPOCH = 'test-mint-epoch' +// Why encoded: production escapes the epoch at the mint site. A test epoch with a +// reserved character would otherwise diverge silently across ~40 assertions. export function testPtyId(sequence: number): string { - return `pty2:${TEST_PTY_ID_MINT_EPOCH}:${sequence}` + return `pty2:${encodeURIComponent(TEST_PTY_ID_MINT_EPOCH)}:${sequence}` } export function createTestPtyHandler(dispatcher: MockDispatcher): PtyHandler {