From a469c00fc18952d5a2ccfb7b36afe4cbf2c62eae Mon Sep 17 00:00:00 2001 From: registered2nd <39094401+registered2nd@users.noreply.github.com> Date: Wed, 4 Nov 2026 23:31:36 -0800 Subject: [PATCH 1/3] fix(remote): re-attach terminals a daemon reconnect detached, for remote views and input When the host's main process loses and re-makes its daemon connection, the daemon drops main's attachments and the adapter refuses input to every session until it is attached again. Only a pane mounted in the host's own window re-attaches by itself; a session with no pane there stays silent and refuses every keystroke from a paired desktop, a phone or `orca terminal send`, while `terminal list` still calls it connected and writable. A client remount or restart did not help: its new subscription never re-attached the session. Main now notes each session the provider's endpoint loss names, re-attaches it once a remote view shows it (at the loss or when a view subscribes later), and holds input for it until that attach lands instead of refusing it. Co-Authored-By: Claude Opus 5.5 --- src/main/ipc/pty/provider/bind-listeners.ts | 1 + .../pty-endpoint-loss-runtime-notify.test.ts | 73 +++++++++ ...al-subscriber-driven-daemon-attach.test.ts | 152 +++++++++++++++++- .../terminal/input/terminal-input-dispatch.ts | 8 + .../terminal/layout/terminal-view-presence.ts | 24 +++ .../lifecycle/main-daemon-attachments.ts | 45 +++++- .../lifecycle/terminal-view-resources.ts | 3 +- 7 files changed, 302 insertions(+), 4 deletions(-) create mode 100644 src/main/ipc/pty/pty-endpoint-loss-runtime-notify.test.ts diff --git a/src/main/ipc/pty/provider/bind-listeners.ts b/src/main/ipc/pty/provider/bind-listeners.ts index fadc255b33aa..b8813dba24e2 100644 --- a/src/main/ipc/pty/provider/bind-listeners.ts +++ b/src/main/ipc/pty/provider/bind-listeners.ts @@ -30,6 +30,7 @@ export function bindProviderListeners(session: PtyIpcSession): void { localProvider.onWriteUnavailable?.((payload) => { // Before the window check: a headless host has no window, only remote streams. publishPtyEndpointLoss(payload.id) + session.runtime?.notePtyEndpointLoss(payload.id) if ( !session.mainWindow || session.mainWindow.isDestroyed() || diff --git a/src/main/ipc/pty/pty-endpoint-loss-runtime-notify.test.ts b/src/main/ipc/pty/pty-endpoint-loss-runtime-notify.test.ts new file mode 100644 index 000000000000..ec2ae8650b22 --- /dev/null +++ b/src/main/ipc/pty/pty-endpoint-loss-runtime-notify.test.ts @@ -0,0 +1,73 @@ +import { describe, expect, it, vi } from 'vitest' +import { OrcaRuntimeService } from '../../runtime/orca-runtime' +import { setupPtyIpcSuite } from './pty-ipc-test-harness' +import { registerPtyHandlers } from './register-handlers' + +vi.mock('electron', () => import('./pty-ipc-mock-registry').then((m) => m.electronModuleMock())) +vi.mock('fs', () => import('./pty-ipc-mock-registry').then((m) => m.fsModuleMock())) +vi.mock('node-pty', () => import('./pty-ipc-mock-registry').then((m) => m.nodePtyModuleMock())) +vi.mock('node:child_process', async (importOriginal) => + (await import('./pty-ipc-mock-registry')).childProcessModuleMock(await importOriginal()) +) +vi.mock('../../opencode/hook-service', () => + import('./pty-ipc-mock-registry').then((m) => m.openCodeHookServiceModuleMock()) +) +vi.mock('../../mimo/hook-service', () => + import('./pty-ipc-mock-registry').then((m) => m.mimoHookServiceModuleMock()) +) +vi.mock('../../agent-hooks/server', () => + import('./pty-ipc-mock-registry').then((m) => m.agentHookServerModuleMock()) +) +vi.mock('../../pi/titlebar-extension-service', () => + import('./pty-ipc-mock-registry').then((m) => m.piTitlebarExtensionModuleMock()) +) +vi.mock('../../pty/shell-startup/pwsh', () => + import('./pty-ipc-mock-registry').then((m) => m.pwshModuleMock()) +) +vi.mock('../../wsl/filesystem/unc-path-access', async (importOriginal) => + (await import('./pty-ipc-mock-registry')).wslModuleMock(await importOriginal()) +) +vi.mock('../../telemetry/client', () => + import('./pty-ipc-mock-registry').then((m) => m.telemetryClientModuleMock()) +) +vi.mock('../../telemetry/classify-error', () => + import('./pty-ipc-mock-registry').then((m) => m.classifyErrorModuleMock()) +) +vi.mock('../../cli/linux-terminal-orca-cli-shim', () => + import('./pty-ipc-mock-registry').then((m) => m.linuxCliShimModuleMock()) +) +vi.mock('../../memory/pty-registry', () => + import('./pty-ipc-mock-registry').then((m) => m.ptyRegistryModuleMock()) +) +vi.mock('../../agent-hooks/migration-unsupported-pty-state', () => + import('./pty-ipc-mock-registry').then((m) => m.migrationUnsupportedPtyModuleMock()) +) +vi.mock('../../codex/configuration/homes/codex-pane-account-registry', () => + import('./pty-ipc-mock-registry').then((m) => m.codexPaneAccountRegistryModuleMock()) +) +vi.mock('../../codex/history/index/codex-state-db-backfill-recovery', () => + import('./pty-ipc-mock-registry').then((m) => m.codexBackfillRecoveryModuleMock()) +) + +describe('pty:writeUnavailable daemon-death fan-out', () => { + const { mainWindow, installDaemonTestProvider } = setupPtyIpcSuite() + + it('tells the runtime, which re-attaches the terminal for its remote views', () => { + let fanout: ((payload: { id: string }) => void) | null = null + installDaemonTestProvider({ + onWriteUnavailable: vi.fn((callback: (payload: { id: string }) => void) => { + fanout = callback + return () => {} + }) + }) + const runtime = new OrcaRuntimeService() + const notePtyEndpointLoss = vi.spyOn(runtime, 'notePtyEndpointLoss') + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: a mocked BrowserWindow; the handlers reach only its webContents, which the mock provides. + registerPtyHandlers(mainWindow as never, runtime) + mainWindow.webContents.isDestroyed.mockReturnValue(true) + + fanout!({ id: 'pane-1' }) + + expect(notePtyEndpointLoss).toHaveBeenCalledWith('pane-1') + }) +}) diff --git a/src/main/runtime/terminal-subscriber-driven-daemon-attach.test.ts b/src/main/runtime/terminal-subscriber-driven-daemon-attach.test.ts index b3e1a50123fe..887af413c768 100644 --- a/src/main/runtime/terminal-subscriber-driven-daemon-attach.test.ts +++ b/src/main/runtime/terminal-subscriber-driven-daemon-attach.test.ts @@ -29,6 +29,8 @@ type RuntimeInternals = { worktrees: [], targetWorktreeId: string | null ) => Promise + // Optional so this suite still runs, and fails on behavior, against a runtime without it. + notePtyEndpointLoss?: (ptyId: string) => void } function internals(runtime: OrcaRuntimeService): RuntimeInternals { @@ -48,10 +50,18 @@ function createDaemonProviderModel(opts: { snapshotCapable: boolean }) { const sessions = new Map() const attachCalls: string[] = [] const resizeCalls: [string, number, number][] = [] + const writes: string[] = [] let nextAttachBarrier: { promise: Promise; result: boolean } | null = null let runtime: OrcaRuntimeService | null = null const controller = { - write: () => true, + // The adapter refuses input to a session until this app attaches it again. + write: (ptyId: string, data: string) => { + if (!sessions.get(ptyId)?.attached) { + return false + } + writes.push(data) + return true + }, kill: () => true, getForegroundProcess: async () => null, listProcesses: async () => @@ -110,6 +120,13 @@ function createDaemonProviderModel(opts: { snapshotCapable: boolean }) { sessions, attachCalls, resizeCalls, + writes, + /** Main's daemon link dropped and came back: the daemon released this app's attachments. */ + dropAttachments(): void { + for (const session of sessions.values()) { + session.attached = false + } + }, deferNextAttach(result: boolean): () => void { let release!: () => void const promise = new Promise((resolve) => { @@ -483,3 +500,136 @@ describe('subscriber-driven daemon attach (never-activated tab)', () => { expect(read.tail.join('\n')).not.toContain('stale provider frame') }) }) + +/** A session this app spawned and attached; then main's daemon link drops and returns. The daemon + * releases every attachment of the reconnecting client, and only a pane mounted in this window + * re-attaches on its own (its remount). A paired client's pane, a phone or a CLI send must not stay + * refused and silent until someone opens the tab on the host. */ +describe('re-attach after a daemon reconnect detached a spawned session', () => { + function setupSpawnedAttachedSession(): ReturnType { + const setup = setupNeverAttachedDaemonSession({ + snapshotCapable: true, + screen: 'agent screen\r\n' + }) + setup.runtime.onPtySpawned(PTY_ID, undefined, { awaitsRegistration: false }) + setup.model.sessions.get(PTY_ID)!.attached = true + return setup + } + + function loseEndpoint( + runtime: OrcaRuntimeService, + model: ReturnType + ): void { + model.dropAttachments() + // What the local provider's write-unavailable fan-out reports for every session it held. + internals(runtime).notePtyEndpointLoss?.(PTY_ID) + } + + it('re-attaches at once for a remote view that is already streaming the terminal', async () => { + const { runtime, model, handle } = setupSpawnedAttachedSession() + const harness = startMultiplex(runtime) + await vi.waitFor(() => expect(harness.handlers.has(0)).toBe(true)) + sendSubscribe(harness, 1, handle) + await waitForSubscribed(harness, 1) + expect(model.attachCalls).toEqual([]) + + loseEndpoint(runtime, model) + + await vi.waitFor(() => expect(model.attachCalls).toEqual([PTY_ID])) + expect(model.emitData(PTY_ID, 'after reconnect\r\n')).toBe(true) + await vi.waitFor(() => expect(outputText(harness)).toContain('after reconnect')) + await runtime.sendTerminal(handle, { text: 'typed' }, { inputKind: 'driving' }) + expect(model.writes).toEqual(['typed']) + }) + + it("re-attaches when a client's pane subscribes after the loss", async () => { + const { runtime, model, handle } = setupSpawnedAttachedSession() + // No remote view at the loss: the paired client mounts the pane later (a restart, a remount). + loseEndpoint(runtime, model) + expect(model.attachCalls).toEqual([]) + expect(model.emitData(PTY_ID, 'unseen\r\n')).toBe(false) + + const harness = startMultiplex(runtime) + await vi.waitFor(() => expect(harness.handlers.has(0)).toBe(true)) + sendSubscribe(harness, 1, handle) + await waitForSubscribed(harness, 1) + + await vi.waitFor(() => expect(model.attachCalls).toEqual([PTY_ID])) + expect(model.emitData(PTY_ID, 'live again\r\n')).toBe(true) + await vi.waitFor(() => expect(outputText(harness)).toContain('live again')) + + // Once re-attached, later subscribers do not attach again. + sendSubscribe(harness, 2, handle, 'client-b') + await waitForSubscribed(harness, 2) + expect(model.attachCalls).toEqual([PTY_ID]) + }) + + it('re-attaches before writing input that arrives with no view at all', async () => { + const { runtime, model, handle } = setupSpawnedAttachedSession() + loseEndpoint(runtime, model) + + await runtime.sendTerminal(handle, { text: 'orca terminal send' }, { inputKind: 'driving' }) + + expect(model.attachCalls).toEqual([PTY_ID]) + expect(model.writes).toEqual(['orca terminal send']) + }) + + it('holds input sent while the re-attach is in flight instead of refusing it', async () => { + const { runtime, model, handle } = setupSpawnedAttachedSession() + const harness = startMultiplex(runtime) + await vi.waitFor(() => expect(harness.handlers.has(0)).toBe(true)) + sendSubscribe(harness, 1, handle) + await waitForSubscribed(harness, 1) + const releaseAttach = model.deferNextAttach(true) + + loseEndpoint(runtime, model) + await vi.waitFor(() => expect(model.attachCalls).toEqual([PTY_ID])) + const send = runtime.sendTerminal(handle, { text: 'early key' }, { inputKind: 'driving' }) + await Promise.resolve() + expect(model.writes).toEqual([]) + releaseAttach() + + await expect(send).resolves.toMatchObject({ accepted: true }) + expect(model.writes).toEqual(['early key']) + }) + + it('redoes an earlier subscriber-driven attach that the loss undid', async () => { + // Never-attached session: the first remote subscribe attaches it (the restored-tab path). + const { runtime, model, handle } = setupNeverAttachedDaemonSession({ snapshotCapable: false }) + const harness = startMultiplex(runtime) + await vi.waitFor(() => expect(harness.handlers.has(0)).toBe(true)) + sendSubscribe(harness, 1, handle) + await waitForSubscribed(harness, 1) + await vi.waitFor(() => expect(model.attachCalls).toEqual([PTY_ID])) + + loseEndpoint(runtime, model) + + await vi.waitFor(() => expect(model.attachCalls).toEqual([PTY_ID, PTY_ID])) + expect(model.emitData(PTY_ID, 'second life\r\n')).toBe(true) + await vi.waitFor(() => expect(outputText(harness)).toContain('second life')) + }) + + it('attaches again when another loss lands while the re-attach is in flight', async () => { + const { runtime, model, handle } = setupSpawnedAttachedSession() + const harness = startMultiplex(runtime) + await vi.waitFor(() => expect(harness.handlers.has(0)).toBe(true)) + sendSubscribe(harness, 1, handle) + await waitForSubscribed(harness, 1) + const releaseFirst = model.deferNextAttach(true) + + loseEndpoint(runtime, model) + await vi.waitFor(() => expect(model.attachCalls).toEqual([PTY_ID])) + loseEndpoint(runtime, model) + releaseFirst() + + await vi.waitFor(() => expect(model.attachCalls).toEqual([PTY_ID, PTY_ID])) + expect(model.emitData(PTY_ID, 'after both\r\n')).toBe(true) + }) + + it('leaves a session alone when no view or input needs it', async () => { + const { runtime, model } = setupSpawnedAttachedSession() + loseEndpoint(runtime, model) + await Promise.resolve() + expect(model.attachCalls).toEqual([]) + }) +}) diff --git a/src/main/runtime/terminal/input/terminal-input-dispatch.ts b/src/main/runtime/terminal/input/terminal-input-dispatch.ts index 8aede49dc600..f63d10474290 100644 --- a/src/main/runtime/terminal/input/terminal-input-dispatch.ts +++ b/src/main/runtime/terminal/input/terminal-input-dispatch.ts @@ -149,6 +149,10 @@ export abstract class OrcaRuntimeWithControllerKnowsPtyIsLive extends OrcaRuntim throw new Error('invalid_terminal_send') } await assertTerminalInputWithinLimitWithYield(action.text) + const reattach = this.waitForPtyEndpointReattach(pty.pty.ptyId) + if (reattach) { + await reattach + } if (!(await this.launchComposerAdmitsSubmit(pty.pty.ptyId, action, options))) { return { handle, accepted: false, bytesWritten: 0 } } @@ -182,6 +186,10 @@ export abstract class OrcaRuntimeWithControllerKnowsPtyIsLive extends OrcaRuntim if (await this.isLeafPtyProvenAbsent(leaf.ptyId)) { throw new Error('terminal_not_writable') } + const reattach = this.waitForPtyEndpointReattach(leaf.ptyId) + if (reattach) { + await reattach + } if (!(await this.launchComposerAdmitsSubmit(leaf.ptyId, action, options))) { return { handle, accepted: false, bytesWritten: 0 } } diff --git a/src/main/runtime/terminal/layout/terminal-view-presence.ts b/src/main/runtime/terminal/layout/terminal-view-presence.ts index 290d7a169b8c..efee0b29b161 100644 --- a/src/main/runtime/terminal/layout/terminal-view-presence.ts +++ b/src/main/runtime/terminal/layout/terminal-view-presence.ts @@ -11,6 +11,9 @@ import type { RuntimeTerminalBufferSnapshot } from '../records/runtime-terminal- import { AUTHORITATIVE_TERMINAL_SNAPSHOT_TIMEOUT_MS } from '../output/provider-snapshot-budget' import { assertTerminalInputWithinLimitWithYield } from '../../terminal-send-payload' +// Covers a daemon reconnect plus the attach; past it the write proceeds and is refused as before. +const ENDPOINT_REATTACH_INPUT_WAIT_MS = 10_000 + export abstract class OrcaRuntimeWithNotifyRemoteTerminalViewPresenceChanged extends OrcaRuntimeWithRecordAgentPromptLifecycleState { protected abstract serializeTerminalBufferFromAvailableState( ptyId: string, @@ -69,6 +72,27 @@ export abstract class OrcaRuntimeWithNotifyRemoteTerminalViewPresenceChanged ext return this.mainDaemonAttachments.isKnownUnattachedLocal(ptyId) } + /** The local provider lost this PTY's endpoint; a remote view re-attaches it once the daemon is back. */ + notePtyEndpointLoss(ptyId: string): void { + this.mainDaemonAttachments.noteEndpointLoss(ptyId) + } + + /** Input for a PTY an endpoint loss detached re-attaches it and waits for that, bounded, instead of being + * refused; null (no wait at all) when no re-attach is owed. */ + protected waitForPtyEndpointReattach(ptyId: string): Promise | null { + const reattached = this.mainDaemonAttachments.reattachForInput(ptyId) + if (!reattached) { + return null + } + let timer: ReturnType | undefined + return Promise.race([ + reattached, + new Promise((resolve) => { + timer = setTimeout(resolve, ENDPOINT_REATTACH_INPUT_WAIT_MS) + }) + ]).finally(() => clearTimeout(timer)) + } + /** Mark a raw-output viewer without transferring terminal query authority. */ registerRawTerminalViewSubscriber(ptyId: string): () => void { return this.terminalViewSubscribers.registerRaw(ptyId) diff --git a/src/main/runtime/terminal/lifecycle/main-daemon-attachments.ts b/src/main/runtime/terminal/lifecycle/main-daemon-attachments.ts index a6cedb8379cb..c0157218c105 100644 --- a/src/main/runtime/terminal/lifecycle/main-daemon-attachments.ts +++ b/src/main/runtime/terminal/lifecycle/main-daemon-attachments.ts @@ -1,6 +1,7 @@ type MainDaemonAttachmentDependencies = { isUnattachedLocalCandidate: (ptyId: string) => boolean attachProvider: (ptyId: string) => Promise | null + hasRemoteView: (ptyId: string) => boolean } // Why capped: 100 concurrent snapshot attaches delayed the visible terminal's first echo by ~0.7 s. @@ -13,6 +14,8 @@ export class MainDaemonAttachments { private readonly attaching = new Map>() private readonly queued: (() => void)[] = [] private running = 0 + // Endpoint losses per session since main last re-attached it; present while a re-attach is owed. + private readonly endpointLosses = new Map() constructor(private readonly deps: MainDaemonAttachmentDependencies) {} @@ -24,12 +27,30 @@ export class MainDaemonAttachments { forget(ptyId: string): void { this.attached.delete(ptyId) this.attaching.delete(ptyId) + this.endpointLosses.delete(ptyId) } isKnownUnattachedLocal(ptyId: string): boolean { return !this.attached.has(ptyId) && this.deps.isUnattachedLocalCandidate(ptyId) } + /** A daemon reconnect drops main's attachment, and with it the session's output and input; only a pane + * in this window re-attaches on its own, so main re-attaches the ones remote views show or input targets. */ + noteEndpointLoss(ptyId: string): void { + this.endpointLosses.set(ptyId, (this.endpointLosses.get(ptyId) ?? 0) + 1) + this.attached.delete(ptyId) + this.ensure(ptyId) + } + + /** Input for a session an endpoint loss detached re-attaches it first; null when no re-attach is owed. */ + reattachForInput(ptyId: string): Promise | null { + if (!this.endpointLosses.has(ptyId)) { + return null + } + const attempt = this.attaching.get(ptyId) ?? this.start(ptyId) + return attempt.then(() => undefined) + } + /** Inventory proved the session live; attach it, or retry once an in-flight refusal settles. */ reconcile(ptyId: string): void { const attempt = this.attaching.get(ptyId) @@ -45,9 +66,19 @@ export class MainDaemonAttachments { } ensure(ptyId: string): void { - if (this.attaching.has(ptyId) || !this.isKnownUnattachedLocal(ptyId)) { + if (this.attaching.has(ptyId)) { return } + const owed = this.endpointLosses.has(ptyId) + ? this.deps.hasRemoteView(ptyId) + : this.isKnownUnattachedLocal(ptyId) + if (owed) { + this.start(ptyId) + } + } + + private start(ptyId: string): Promise { + const lossCount = this.endpointLosses.get(ptyId) const attempt: Promise = this.acquireSlot().then(() => this.attach(ptyId, attempt)) this.attaching.set(ptyId, attempt) void attempt.then((attached) => { @@ -55,10 +86,17 @@ export class MainDaemonAttachments { return } this.attaching.delete(ptyId) + // A loss during the attempt can undo an attach made just before it. + if (this.endpointLosses.get(ptyId) !== lossCount) { + this.ensure(ptyId) + return + } if (attached) { this.attached.add(ptyId) + this.endpointLosses.delete(ptyId) } }) + return attempt } private acquireSlot(): Promise { @@ -73,7 +111,10 @@ export class MainDaemonAttachments { private async attach(ptyId: string, attempt: Promise): Promise { try { // While this queued, an exit or respawn may have superseded it, or a pane may have attached. - if (this.attaching.get(ptyId) !== attempt || !this.isKnownUnattachedLocal(ptyId)) { + if ( + this.attaching.get(ptyId) !== attempt || + !(this.endpointLosses.has(ptyId) || this.isKnownUnattachedLocal(ptyId)) + ) { return false } return (await this.deps.attachProvider(ptyId)) ?? false diff --git a/src/main/runtime/terminal/lifecycle/terminal-view-resources.ts b/src/main/runtime/terminal/lifecycle/terminal-view-resources.ts index e08111d044fa..50718b0e8b7b 100644 --- a/src/main/runtime/terminal/lifecycle/terminal-view-resources.ts +++ b/src/main/runtime/terminal/lifecycle/terminal-view-resources.ts @@ -207,7 +207,8 @@ export abstract class OrcaRuntimeWithFitOverrideListeners extends OrcaRuntimeWit const pty = this.ptysById.get(ptyId) return pty !== undefined && pty.connectionId === null && pty.connected }, - attachProvider: (ptyId) => this.ptyController?.attach?.(ptyId) ?? null + attachProvider: (ptyId) => this.ptyController?.attach?.(ptyId) ?? null, + hasRemoteView: (ptyId) => this.terminalViewSubscribers.hasRemote(ptyId) }) // Remote xterms own query replies; ref-count streams and retain suppression through mobile soft-leave grace (terminal-query-authority.md). From f6d845992ff349daa8716e380292559dd883a7dc Mon Sep 17 00:00:00 2001 From: Neil Date: Thu, 5 Nov 2026 02:07:09 -0800 Subject: [PATCH 2/3] fix(runtime): main re-attaches every session an endpoint loss detached --- .../pty-endpoint-loss-runtime-notify.test.ts | 73 ----------------- .../ipc/pty/pty-write-ipc-validation.test.ts | 17 ++++ ...al-subscriber-driven-daemon-attach.test.ts | 82 ++++++------------- .../terminal/input/terminal-input-dispatch.ts | 12 +-- .../terminal/layout/terminal-view-presence.ts | 37 +++++---- .../lifecycle/main-daemon-attachments.ts | 54 ++++++------ .../lifecycle/terminal-view-resources.ts | 14 ++-- 7 files changed, 99 insertions(+), 190 deletions(-) delete mode 100644 src/main/ipc/pty/pty-endpoint-loss-runtime-notify.test.ts diff --git a/src/main/ipc/pty/pty-endpoint-loss-runtime-notify.test.ts b/src/main/ipc/pty/pty-endpoint-loss-runtime-notify.test.ts deleted file mode 100644 index ec2ae8650b22..000000000000 --- a/src/main/ipc/pty/pty-endpoint-loss-runtime-notify.test.ts +++ /dev/null @@ -1,73 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { OrcaRuntimeService } from '../../runtime/orca-runtime' -import { setupPtyIpcSuite } from './pty-ipc-test-harness' -import { registerPtyHandlers } from './register-handlers' - -vi.mock('electron', () => import('./pty-ipc-mock-registry').then((m) => m.electronModuleMock())) -vi.mock('fs', () => import('./pty-ipc-mock-registry').then((m) => m.fsModuleMock())) -vi.mock('node-pty', () => import('./pty-ipc-mock-registry').then((m) => m.nodePtyModuleMock())) -vi.mock('node:child_process', async (importOriginal) => - (await import('./pty-ipc-mock-registry')).childProcessModuleMock(await importOriginal()) -) -vi.mock('../../opencode/hook-service', () => - import('./pty-ipc-mock-registry').then((m) => m.openCodeHookServiceModuleMock()) -) -vi.mock('../../mimo/hook-service', () => - import('./pty-ipc-mock-registry').then((m) => m.mimoHookServiceModuleMock()) -) -vi.mock('../../agent-hooks/server', () => - import('./pty-ipc-mock-registry').then((m) => m.agentHookServerModuleMock()) -) -vi.mock('../../pi/titlebar-extension-service', () => - import('./pty-ipc-mock-registry').then((m) => m.piTitlebarExtensionModuleMock()) -) -vi.mock('../../pty/shell-startup/pwsh', () => - import('./pty-ipc-mock-registry').then((m) => m.pwshModuleMock()) -) -vi.mock('../../wsl/filesystem/unc-path-access', async (importOriginal) => - (await import('./pty-ipc-mock-registry')).wslModuleMock(await importOriginal()) -) -vi.mock('../../telemetry/client', () => - import('./pty-ipc-mock-registry').then((m) => m.telemetryClientModuleMock()) -) -vi.mock('../../telemetry/classify-error', () => - import('./pty-ipc-mock-registry').then((m) => m.classifyErrorModuleMock()) -) -vi.mock('../../cli/linux-terminal-orca-cli-shim', () => - import('./pty-ipc-mock-registry').then((m) => m.linuxCliShimModuleMock()) -) -vi.mock('../../memory/pty-registry', () => - import('./pty-ipc-mock-registry').then((m) => m.ptyRegistryModuleMock()) -) -vi.mock('../../agent-hooks/migration-unsupported-pty-state', () => - import('./pty-ipc-mock-registry').then((m) => m.migrationUnsupportedPtyModuleMock()) -) -vi.mock('../../codex/configuration/homes/codex-pane-account-registry', () => - import('./pty-ipc-mock-registry').then((m) => m.codexPaneAccountRegistryModuleMock()) -) -vi.mock('../../codex/history/index/codex-state-db-backfill-recovery', () => - import('./pty-ipc-mock-registry').then((m) => m.codexBackfillRecoveryModuleMock()) -) - -describe('pty:writeUnavailable daemon-death fan-out', () => { - const { mainWindow, installDaemonTestProvider } = setupPtyIpcSuite() - - it('tells the runtime, which re-attaches the terminal for its remote views', () => { - let fanout: ((payload: { id: string }) => void) | null = null - installDaemonTestProvider({ - onWriteUnavailable: vi.fn((callback: (payload: { id: string }) => void) => { - fanout = callback - return () => {} - }) - }) - const runtime = new OrcaRuntimeService() - const notePtyEndpointLoss = vi.spyOn(runtime, 'notePtyEndpointLoss') - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: a mocked BrowserWindow; the handlers reach only its webContents, which the mock provides. - registerPtyHandlers(mainWindow as never, runtime) - mainWindow.webContents.isDestroyed.mockReturnValue(true) - - fanout!({ id: 'pane-1' }) - - expect(notePtyEndpointLoss).toHaveBeenCalledWith('pane-1') - }) -}) diff --git a/src/main/ipc/pty/pty-write-ipc-validation.test.ts b/src/main/ipc/pty/pty-write-ipc-validation.test.ts index 31ad95dd98ab..32a27562a6b7 100644 --- a/src/main/ipc/pty/pty-write-ipc-validation.test.ts +++ b/src/main/ipc/pty/pty-write-ipc-validation.test.ts @@ -113,6 +113,23 @@ describe('registerPtyHandlers', () => { id: result.id }) }) + it('tells the runtime about a daemon endpoint loss even with no window', () => { + let fanout: ((payload: { id: string }) => void) | undefined + installDaemonTestProvider({ + onWriteUnavailable: vi.fn((callback: (payload: { id: string }) => void) => { + fanout = callback + return () => {} + }) + }) + const runtime = new OrcaRuntimeService() + const notePtyEndpointLoss = vi.spyOn(runtime, 'notePtyEndpointLoss') + registerPtyHandlers(mainWindow as never, runtime) + mainWindow.webContents.isDestroyed.mockReturnValue(true) + + fanout?.({ id: 'pane-1' }) + + expect(notePtyEndpointLoss).toHaveBeenCalledWith('pane-1') + }) it('rejects malformed and cross-window pty write IPC before provider writes', async () => { const mockProc = createMockProc() spawnMock.mockReturnValue(mockProc.proc) diff --git a/src/main/runtime/terminal-subscriber-driven-daemon-attach.test.ts b/src/main/runtime/terminal-subscriber-driven-daemon-attach.test.ts index 887af413c768..7acdf7081a49 100644 --- a/src/main/runtime/terminal-subscriber-driven-daemon-attach.test.ts +++ b/src/main/runtime/terminal-subscriber-driven-daemon-attach.test.ts @@ -503,8 +503,8 @@ describe('subscriber-driven daemon attach (never-activated tab)', () => { /** A session this app spawned and attached; then main's daemon link drops and returns. The daemon * releases every attachment of the reconnecting client, and only a pane mounted in this window - * re-attaches on its own (its remount). A paired client's pane, a phone or a CLI send must not stay - * refused and silent until someone opens the tab on the host. */ + * re-attaches on its own. Main must take back every other session's stream so background agents' + * records stay fresh and a paired client, phone or CLI send is not refused. */ describe('re-attach after a daemon reconnect detached a spawned session', () => { function setupSpawnedAttachedSession(): ReturnType { const setup = setupNeverAttachedDaemonSession({ @@ -525,72 +525,51 @@ describe('re-attach after a daemon reconnect detached a spawned session', () => internals(runtime).notePtyEndpointLoss?.(PTY_ID) } - it('re-attaches at once for a remote view that is already streaming the terminal', async () => { + it('takes back the stream of a session no view shows', async () => { const { runtime, model, handle } = setupSpawnedAttachedSession() - const harness = startMultiplex(runtime) - await vi.waitFor(() => expect(harness.handlers.has(0)).toBe(true)) - sendSubscribe(harness, 1, handle) - await waitForSubscribed(harness, 1) - expect(model.attachCalls).toEqual([]) loseEndpoint(runtime, model) await vi.waitFor(() => expect(model.attachCalls).toEqual([PTY_ID])) - expect(model.emitData(PTY_ID, 'after reconnect\r\n')).toBe(true) - await vi.waitFor(() => expect(outputText(harness)).toContain('after reconnect')) - await runtime.sendTerminal(handle, { text: 'typed' }, { inputKind: 'driving' }) + expect(model.emitData(PTY_ID, 'background agent output\r\n')).toBe(true) + await expect( + runtime.sendTerminal(handle, { text: 'typed' }, { inputKind: 'driving' }) + ).resolves.toMatchObject({ accepted: true }) expect(model.writes).toEqual(['typed']) }) - it("re-attaches when a client's pane subscribes after the loss", async () => { + it('holds input sent while the re-attach is in flight instead of refusing it', async () => { const { runtime, model, handle } = setupSpawnedAttachedSession() - // No remote view at the loss: the paired client mounts the pane later (a restart, a remount). - loseEndpoint(runtime, model) - expect(model.attachCalls).toEqual([]) - expect(model.emitData(PTY_ID, 'unseen\r\n')).toBe(false) - - const harness = startMultiplex(runtime) - await vi.waitFor(() => expect(harness.handlers.has(0)).toBe(true)) - sendSubscribe(harness, 1, handle) - await waitForSubscribed(harness, 1) + const releaseAttach = model.deferNextAttach(true) + loseEndpoint(runtime, model) await vi.waitFor(() => expect(model.attachCalls).toEqual([PTY_ID])) - expect(model.emitData(PTY_ID, 'live again\r\n')).toBe(true) - await vi.waitFor(() => expect(outputText(harness)).toContain('live again')) + const send = runtime.sendTerminal(handle, { text: 'early key' }, { inputKind: 'driving' }) + await Promise.resolve() + expect(model.writes).toEqual([]) + releaseAttach() - // Once re-attached, later subscribers do not attach again. - sendSubscribe(harness, 2, handle, 'client-b') - await waitForSubscribed(harness, 2) - expect(model.attachCalls).toEqual([PTY_ID]) + await expect(send).resolves.toMatchObject({ accepted: true }) + expect(model.writes).toEqual(['early key']) }) - it('re-attaches before writing input that arrives with no view at all', async () => { + it('leaves a failed re-attach to the next view or inventory pass, not to each keystroke', async () => { const { runtime, model, handle } = setupSpawnedAttachedSession() + const releaseAttach = model.deferNextAttach(false) loseEndpoint(runtime, model) + releaseAttach() + await vi.waitFor(() => expect(model.attachCalls).toEqual([PTY_ID])) - await runtime.sendTerminal(handle, { text: 'orca terminal send' }, { inputKind: 'driving' }) - + await runtime.sendTerminal(handle, { text: 'a' }, { inputKind: 'driving' }).catch(() => {}) + await runtime.sendTerminal(handle, { text: 'b' }, { inputKind: 'driving' }).catch(() => {}) expect(model.attachCalls).toEqual([PTY_ID]) - expect(model.writes).toEqual(['orca terminal send']) - }) - it('holds input sent while the re-attach is in flight instead of refusing it', async () => { - const { runtime, model, handle } = setupSpawnedAttachedSession() const harness = startMultiplex(runtime) await vi.waitFor(() => expect(harness.handlers.has(0)).toBe(true)) sendSubscribe(harness, 1, handle) await waitForSubscribed(harness, 1) - const releaseAttach = model.deferNextAttach(true) - - loseEndpoint(runtime, model) - await vi.waitFor(() => expect(model.attachCalls).toEqual([PTY_ID])) - const send = runtime.sendTerminal(handle, { text: 'early key' }, { inputKind: 'driving' }) - await Promise.resolve() - expect(model.writes).toEqual([]) - releaseAttach() - - await expect(send).resolves.toMatchObject({ accepted: true }) - expect(model.writes).toEqual(['early key']) + await vi.waitFor(() => expect(model.attachCalls).toEqual([PTY_ID, PTY_ID])) + expect(model.emitData(PTY_ID, 'live again\r\n')).toBe(true) }) it('redoes an earlier subscriber-driven attach that the loss undid', async () => { @@ -610,11 +589,7 @@ describe('re-attach after a daemon reconnect detached a spawned session', () => }) it('attaches again when another loss lands while the re-attach is in flight', async () => { - const { runtime, model, handle } = setupSpawnedAttachedSession() - const harness = startMultiplex(runtime) - await vi.waitFor(() => expect(harness.handlers.has(0)).toBe(true)) - sendSubscribe(harness, 1, handle) - await waitForSubscribed(harness, 1) + const { runtime, model } = setupSpawnedAttachedSession() const releaseFirst = model.deferNextAttach(true) loseEndpoint(runtime, model) @@ -625,11 +600,4 @@ describe('re-attach after a daemon reconnect detached a spawned session', () => await vi.waitFor(() => expect(model.attachCalls).toEqual([PTY_ID, PTY_ID])) expect(model.emitData(PTY_ID, 'after both\r\n')).toBe(true) }) - - it('leaves a session alone when no view or input needs it', async () => { - const { runtime, model } = setupSpawnedAttachedSession() - loseEndpoint(runtime, model) - await Promise.resolve() - expect(model.attachCalls).toEqual([]) - }) }) diff --git a/src/main/runtime/terminal/input/terminal-input-dispatch.ts b/src/main/runtime/terminal/input/terminal-input-dispatch.ts index f63d10474290..9a98cff379bf 100644 --- a/src/main/runtime/terminal/input/terminal-input-dispatch.ts +++ b/src/main/runtime/terminal/input/terminal-input-dispatch.ts @@ -149,10 +149,7 @@ export abstract class OrcaRuntimeWithControllerKnowsPtyIsLive extends OrcaRuntim throw new Error('invalid_terminal_send') } await assertTerminalInputWithinLimitWithYield(action.text) - const reattach = this.waitForPtyEndpointReattach(pty.pty.ptyId) - if (reattach) { - await reattach - } + await this.waitForPtyEndpointReattach(pty.pty.ptyId, options.signal) if (!(await this.launchComposerAdmitsSubmit(pty.pty.ptyId, action, options))) { return { handle, accepted: false, bytesWritten: 0 } } @@ -186,10 +183,7 @@ export abstract class OrcaRuntimeWithControllerKnowsPtyIsLive extends OrcaRuntim if (await this.isLeafPtyProvenAbsent(leaf.ptyId)) { throw new Error('terminal_not_writable') } - const reattach = this.waitForPtyEndpointReattach(leaf.ptyId) - if (reattach) { - await reattach - } + await this.waitForPtyEndpointReattach(leaf.ptyId, options.signal) if (!(await this.launchComposerAdmitsSubmit(leaf.ptyId, action, options))) { return { handle, accepted: false, bytesWritten: 0 } } @@ -259,6 +253,7 @@ export abstract class OrcaRuntimeWithControllerKnowsPtyIsLive extends OrcaRuntim } const payload = payloadFor(pty.pty.ptyId) await assertTerminalInputWithinLimitWithYield(payload) + await this.waitForPtyEndpointReattach(pty.pty.ptyId, agentPromptObservationSignal(options)) // Only opted-in calls take the extra layer, so every default caller's timing is untouched. if (agentPromptWriteOptsIn(options)) { return await this.submitTerminalAgentPrompt(handle, pty.pty.ptyId, prompt, payload, options) @@ -295,6 +290,7 @@ export abstract class OrcaRuntimeWithControllerKnowsPtyIsLive extends OrcaRuntim if (await this.isLeafPtyProvenAbsent(leaf.ptyId)) { throw new Error('terminal_not_writable') } + await this.waitForPtyEndpointReattach(leaf.ptyId, agentPromptObservationSignal(options)) if (agentPromptWriteOptsIn(options)) { return await this.submitTerminalAgentPrompt(handle, leaf.ptyId, prompt, payload, options) } diff --git a/src/main/runtime/terminal/layout/terminal-view-presence.ts b/src/main/runtime/terminal/layout/terminal-view-presence.ts index efee0b29b161..410e28601b7a 100644 --- a/src/main/runtime/terminal/layout/terminal-view-presence.ts +++ b/src/main/runtime/terminal/layout/terminal-view-presence.ts @@ -1,3 +1,4 @@ +import { setTimeout as delay } from 'node:timers/promises' import { OrcaRuntimeWithRecordAgentPromptLifecycleState } from '../output/terminal-output-generation' import type { TerminalOscLinkRange } from '../../../../shared/terminal/links/terminal-osc-link-ranges' import type { PtyProviderBufferSnapshot } from '../../../providers/pty-provider-contract' @@ -72,25 +73,33 @@ export abstract class OrcaRuntimeWithNotifyRemoteTerminalViewPresenceChanged ext return this.mainDaemonAttachments.isKnownUnattachedLocal(ptyId) } - /** The local provider lost this PTY's endpoint; a remote view re-attaches it once the daemon is back. */ + /** The local provider lost this PTY's endpoint; main re-attaches it so its output and input resume. */ notePtyEndpointLoss(ptyId: string): void { this.mainDaemonAttachments.noteEndpointLoss(ptyId) } - /** Input for a PTY an endpoint loss detached re-attaches it and waits for that, bounded, instead of being - * refused; null (no wait at all) when no re-attach is owed. */ - protected waitForPtyEndpointReattach(ptyId: string): Promise | null { - const reattached = this.mainDaemonAttachments.reattachForInput(ptyId) - if (!reattached) { - return null + /** Input waits, bounded, for main's in-flight re-attach after an endpoint loss instead of being refused. */ + protected async waitForPtyEndpointReattach(ptyId: string, signal?: AbortSignal): Promise { + const deadline = performance.now() + ENDPOINT_REATTACH_INPUT_WAIT_MS + // A further loss mid-attach starts another attempt; keep waiting within the same bound. + let reattach = this.mainDaemonAttachments.pendingReattach(ptyId) + while (reattach && signal?.aborted !== true) { + const remainingMs = deadline - performance.now() + if (remainingMs <= 0) { + return + } + const stopWaiting = new AbortController() + const waitSignal = signal ? AbortSignal.any([signal, stopWaiting.signal]) : stopWaiting.signal + const settled = await Promise.race([ + reattach.then(() => true), + delay(remainingMs, false, { signal: waitSignal }).catch(() => false) + ]) + stopWaiting.abort() + if (!settled) { + return + } + reattach = this.mainDaemonAttachments.pendingReattach(ptyId) } - let timer: ReturnType | undefined - return Promise.race([ - reattached, - new Promise((resolve) => { - timer = setTimeout(resolve, ENDPOINT_REATTACH_INPUT_WAIT_MS) - }) - ]).finally(() => clearTimeout(timer)) } /** Mark a raw-output viewer without transferring terminal query authority. */ diff --git a/src/main/runtime/terminal/lifecycle/main-daemon-attachments.ts b/src/main/runtime/terminal/lifecycle/main-daemon-attachments.ts index c0157218c105..2fe432a4aa94 100644 --- a/src/main/runtime/terminal/lifecycle/main-daemon-attachments.ts +++ b/src/main/runtime/terminal/lifecycle/main-daemon-attachments.ts @@ -1,7 +1,9 @@ type MainDaemonAttachmentDependencies = { - isUnattachedLocalCandidate: (ptyId: string) => boolean + /** A live local daemon session main may attach now (no spawn admission in flight). */ + isAttachableLocalSession: (ptyId: string) => boolean + /** Main already holds this session's screen, so an attach began before this run's tracking. */ + hasMainTerminalState: (ptyId: string) => boolean attachProvider: (ptyId: string) => Promise | null - hasRemoteView: (ptyId: string) => boolean } // Why capped: 100 concurrent snapshot attaches delayed the visible terminal's first echo by ~0.7 s. @@ -14,13 +16,14 @@ export class MainDaemonAttachments { private readonly attaching = new Map>() private readonly queued: (() => void)[] = [] private running = 0 - // Endpoint losses per session since main last re-attached it; present while a re-attach is owed. + // Endpoint losses per session while main owes it a re-attach; a count so a loss mid-attach is noticed. private readonly endpointLosses = new Map() constructor(private readonly deps: MainDaemonAttachmentDependencies) {} markSpawnPublished(ptyId: string): void { this.attached.add(ptyId) + this.endpointLosses.delete(ptyId) } /** Exit or respawn ends the generation whose stream this described. */ @@ -31,24 +34,23 @@ export class MainDaemonAttachments { } isKnownUnattachedLocal(ptyId: string): boolean { - return !this.attached.has(ptyId) && this.deps.isUnattachedLocalCandidate(ptyId) + return ( + !this.attached.has(ptyId) && + this.deps.isAttachableLocalSession(ptyId) && + !this.deps.hasMainTerminalState(ptyId) + ) } - /** A daemon reconnect drops main's attachment, and with it the session's output and input; only a pane - * in this window re-attaches on its own, so main re-attaches the ones remote views show or input targets. */ + /** The daemon dropped this run's attachment, so main re-attaches like at adoption; a mounted pane alone would leave background sessions silent. */ noteEndpointLoss(ptyId: string): void { this.endpointLosses.set(ptyId, (this.endpointLosses.get(ptyId) ?? 0) + 1) this.attached.delete(ptyId) this.ensure(ptyId) } - /** Input for a session an endpoint loss detached re-attaches it first; null when no re-attach is owed. */ - reattachForInput(ptyId: string): Promise | null { - if (!this.endpointLosses.has(ptyId)) { - return null - } - const attempt = this.attaching.get(ptyId) ?? this.start(ptyId) - return attempt.then(() => undefined) + /** Main's re-attach after an endpoint loss, while in flight; input waits on it instead of being refused. */ + pendingReattach(ptyId: string): Promise | undefined { + return this.endpointLosses.has(ptyId) ? this.attaching.get(ptyId) : undefined } /** Inventory proved the session live; attach it, or retry once an in-flight refusal settles. */ @@ -66,18 +68,9 @@ export class MainDaemonAttachments { } ensure(ptyId: string): void { - if (this.attaching.has(ptyId)) { + if (this.attaching.has(ptyId) || !this.isAttachOwed(ptyId)) { return } - const owed = this.endpointLosses.has(ptyId) - ? this.deps.hasRemoteView(ptyId) - : this.isKnownUnattachedLocal(ptyId) - if (owed) { - this.start(ptyId) - } - } - - private start(ptyId: string): Promise { const lossCount = this.endpointLosses.get(ptyId) const attempt: Promise = this.acquireSlot().then(() => this.attach(ptyId, attempt)) this.attaching.set(ptyId, attempt) @@ -86,8 +79,8 @@ export class MainDaemonAttachments { return } this.attaching.delete(ptyId) - // A loss during the attempt can undo an attach made just before it. if (this.endpointLosses.get(ptyId) !== lossCount) { + // A loss during the attempt can undo the attach it made. this.ensure(ptyId) return } @@ -96,7 +89,13 @@ export class MainDaemonAttachments { this.endpointLosses.delete(ptyId) } }) - return attempt + } + + // A lost session needs its stream back even though main still holds its screen. + private isAttachOwed(ptyId: string): boolean { + return this.endpointLosses.has(ptyId) + ? !this.attached.has(ptyId) && this.deps.isAttachableLocalSession(ptyId) + : this.isKnownUnattachedLocal(ptyId) } private acquireSlot(): Promise { @@ -111,10 +110,7 @@ export class MainDaemonAttachments { private async attach(ptyId: string, attempt: Promise): Promise { try { // While this queued, an exit or respawn may have superseded it, or a pane may have attached. - if ( - this.attaching.get(ptyId) !== attempt || - !(this.endpointLosses.has(ptyId) || this.isKnownUnattachedLocal(ptyId)) - ) { + if (this.attaching.get(ptyId) !== attempt || !this.isAttachOwed(ptyId)) { return false } return (await this.deps.attachProvider(ptyId)) ?? false diff --git a/src/main/runtime/terminal/lifecycle/terminal-view-resources.ts b/src/main/runtime/terminal/lifecycle/terminal-view-resources.ts index 50718b0e8b7b..f39353518e74 100644 --- a/src/main/runtime/terminal/lifecycle/terminal-view-resources.ts +++ b/src/main/runtime/terminal/lifecycle/terminal-view-resources.ts @@ -195,20 +195,16 @@ export abstract class OrcaRuntimeWithFitOverrideListeners extends OrcaRuntimeWit >() protected readonly mainDaemonAttachments = new MainDaemonAttachments({ - isUnattachedLocalCandidate: (ptyId) => { - if ( - this.headlessTerminals.has(ptyId) || - this.providerSnapshotPreferredPtys.has(ptyId) || - this.pendingPtyRegistrationIncarnations.has(ptyId) || - parseAppSshPtyId(ptyId) - ) { + isAttachableLocalSession: (ptyId) => { + if (this.pendingPtyRegistrationIncarnations.has(ptyId) || parseAppSshPtyId(ptyId)) { return false } const pty = this.ptysById.get(ptyId) return pty !== undefined && pty.connectionId === null && pty.connected }, - attachProvider: (ptyId) => this.ptyController?.attach?.(ptyId) ?? null, - hasRemoteView: (ptyId) => this.terminalViewSubscribers.hasRemote(ptyId) + hasMainTerminalState: (ptyId) => + this.headlessTerminals.has(ptyId) || this.providerSnapshotPreferredPtys.has(ptyId), + attachProvider: (ptyId) => this.ptyController?.attach?.(ptyId) ?? null }) // Remote xterms own query replies; ref-count streams and retain suppression through mobile soft-leave grace (terminal-query-authority.md). From 10c70da2ff950b597703afacb0777ed94278ac63 Mon Sep 17 00:00:00 2001 From: Neil Date: Thu, 5 Nov 2026 14:32:36 -0800 Subject: [PATCH 3/3] fix(runtime): held input honours cancellation and the session it was sent to Fixes #38433 --- ...al-subscriber-driven-daemon-attach.test.ts | 41 +++++++++++++++++++ .../terminal/input/terminal-input-dispatch.ts | 17 ++++++-- .../terminal/layout/terminal-view-presence.ts | 31 ++++++++++++-- 3 files changed, 82 insertions(+), 7 deletions(-) diff --git a/src/main/runtime/terminal-subscriber-driven-daemon-attach.test.ts b/src/main/runtime/terminal-subscriber-driven-daemon-attach.test.ts index 7acdf7081a49..77e13a45b904 100644 --- a/src/main/runtime/terminal-subscriber-driven-daemon-attach.test.ts +++ b/src/main/runtime/terminal-subscriber-driven-daemon-attach.test.ts @@ -553,6 +553,47 @@ describe('re-attach after a daemon reconnect detached a spawned session', () => expect(model.writes).toEqual(['early key']) }) + it('drops input cancelled while the re-attach is in flight', async () => { + const { runtime, model, handle } = setupSpawnedAttachedSession() + const releaseAttach = model.deferNextAttach(true) + loseEndpoint(runtime, model) + await vi.waitFor(() => expect(model.attachCalls).toEqual([PTY_ID])) + const cancel = new AbortController() + const send = runtime.sendTerminal( + handle, + { text: 'cancelled key' }, + { inputKind: 'driving', signal: cancel.signal } + ) + await Promise.resolve() + + cancel.abort() + releaseAttach() + + await expect(send).rejects.toThrow('request_aborted') + expect(model.writes).toEqual([]) + }) + + it('does not hand held input to a terminal that replaced the one it was sent to', async () => { + const { runtime, model, handle } = setupSpawnedAttachedSession() + const releaseAttach = model.deferNextAttach(true) + loseEndpoint(runtime, model) + await vi.waitFor(() => expect(model.attachCalls).toEqual([PTY_ID])) + const send = runtime.sendTerminal( + handle, + { text: 'for the old shell' }, + { inputKind: 'driving' } + ) + await Promise.resolve() + + await runtime.onPtyExit(PTY_ID, 0) + runtime.onPtySpawned(PTY_ID, undefined, { awaitsRegistration: false }) + model.sessions.get(PTY_ID)!.attached = true + releaseAttach() + + await expect(send).rejects.toThrow() + expect(model.writes).toEqual([]) + }) + it('leaves a failed re-attach to the next view or inventory pass, not to each keystroke', async () => { const { runtime, model, handle } = setupSpawnedAttachedSession() const releaseAttach = model.deferNextAttach(false) diff --git a/src/main/runtime/terminal/input/terminal-input-dispatch.ts b/src/main/runtime/terminal/input/terminal-input-dispatch.ts index 9a98cff379bf..bd0ceb01f99d 100644 --- a/src/main/runtime/terminal/input/terminal-input-dispatch.ts +++ b/src/main/runtime/terminal/input/terminal-input-dispatch.ts @@ -125,6 +125,13 @@ export abstract class OrcaRuntimeWithControllerKnowsPtyIsLive extends OrcaRuntim return probe } + /** The PTY a handle names right now, read without resolving or refusing the handle. */ + private handlePtyId(handle: string): string | undefined { + return ( + this.getLivePtyForHandle(handle)?.pty.ptyId ?? this.handles.get(handle)?.ptyId ?? undefined + ) + } + /** sendTerminal once plugin hooks decided (terminal-plugin-hooked-input.ts). */ protected async sendTerminalAfterPluginHooks( handle: string, @@ -139,6 +146,8 @@ export abstract class OrcaRuntimeWithControllerKnowsPtyIsLive extends OrcaRuntim const target = await starting return { ...(await this.sendTerminalAfterPluginHooks(target, action, options)), handle } } + // Before resolving the target: a terminal closed or replaced during the wait is then refused, not written. + await this.waitForPtyEndpointReattach(this.handlePtyId(handle), options.signal) const pty = this.getLivePtyForHandle(handle) if (pty) { if (!pty.pty.connected) { @@ -149,7 +158,6 @@ export abstract class OrcaRuntimeWithControllerKnowsPtyIsLive extends OrcaRuntim throw new Error('invalid_terminal_send') } await assertTerminalInputWithinLimitWithYield(action.text) - await this.waitForPtyEndpointReattach(pty.pty.ptyId, options.signal) if (!(await this.launchComposerAdmitsSubmit(pty.pty.ptyId, action, options))) { return { handle, accepted: false, bytesWritten: 0 } } @@ -183,7 +191,6 @@ export abstract class OrcaRuntimeWithControllerKnowsPtyIsLive extends OrcaRuntim if (await this.isLeafPtyProvenAbsent(leaf.ptyId)) { throw new Error('terminal_not_writable') } - await this.waitForPtyEndpointReattach(leaf.ptyId, options.signal) if (!(await this.launchComposerAdmitsSubmit(leaf.ptyId, action, options))) { return { handle, accepted: false, bytesWritten: 0 } } @@ -246,6 +253,10 @@ export abstract class OrcaRuntimeWithControllerKnowsPtyIsLive extends OrcaRuntim const target = await starting return { ...(await this.sendAgentPromptAfterPluginHooks(target, prompt, options)), handle } } + await this.waitForPtyEndpointReattach( + this.handlePtyId(handle), + agentPromptObservationSignal(options) + ) const pty = this.getLivePtyForHandle(handle) if (pty) { if (!pty.pty.connected) { @@ -253,7 +264,6 @@ export abstract class OrcaRuntimeWithControllerKnowsPtyIsLive extends OrcaRuntim } const payload = payloadFor(pty.pty.ptyId) await assertTerminalInputWithinLimitWithYield(payload) - await this.waitForPtyEndpointReattach(pty.pty.ptyId, agentPromptObservationSignal(options)) // Only opted-in calls take the extra layer, so every default caller's timing is untouched. if (agentPromptWriteOptsIn(options)) { return await this.submitTerminalAgentPrompt(handle, pty.pty.ptyId, prompt, payload, options) @@ -290,7 +300,6 @@ export abstract class OrcaRuntimeWithControllerKnowsPtyIsLive extends OrcaRuntim if (await this.isLeafPtyProvenAbsent(leaf.ptyId)) { throw new Error('terminal_not_writable') } - await this.waitForPtyEndpointReattach(leaf.ptyId, agentPromptObservationSignal(options)) if (agentPromptWriteOptsIn(options)) { return await this.submitTerminalAgentPrompt(handle, leaf.ptyId, prompt, payload, options) } diff --git a/src/main/runtime/terminal/layout/terminal-view-presence.ts b/src/main/runtime/terminal/layout/terminal-view-presence.ts index 410e28601b7a..0c818d0c2985 100644 --- a/src/main/runtime/terminal/layout/terminal-view-presence.ts +++ b/src/main/runtime/terminal/layout/terminal-view-presence.ts @@ -79,11 +79,36 @@ export abstract class OrcaRuntimeWithNotifyRemoteTerminalViewPresenceChanged ext } /** Input waits, bounded, for main's in-flight re-attach after an endpoint loss instead of being refused. */ - protected async waitForPtyEndpointReattach(ptyId: string, signal?: AbortSignal): Promise { + protected async waitForPtyEndpointReattach( + ptyId: string | undefined, + signal?: AbortSignal + ): Promise { + const reattach = + ptyId === undefined ? undefined : this.mainDaemonAttachments.pendingReattach(ptyId) + if (ptyId === undefined || !reattach) { + return + } + const generation = this.getPtyLifecycleGeneration(ptyId) + await this.settleEndpointReattach(ptyId, reattach, signal) + if (signal?.aborted) { + // A cancelled send must not be written once the terminal is back. + throw new Error('request_aborted') + } + // Input held for one process must not reach a process that replaced it under the same id. + if (this.getPtyLifecycleGeneration(ptyId) !== generation) { + throw new Error('terminal_handle_stale') + } + } + + private async settleEndpointReattach( + ptyId: string, + first: Promise, + signal?: AbortSignal + ): Promise { const deadline = performance.now() + ENDPOINT_REATTACH_INPUT_WAIT_MS // A further loss mid-attach starts another attempt; keep waiting within the same bound. - let reattach = this.mainDaemonAttachments.pendingReattach(ptyId) - while (reattach && signal?.aborted !== true) { + let reattach: Promise | undefined = first + while (reattach) { const remainingMs = deadline - performance.now() if (remainingMs <= 0) { return