Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/main/ipc/pty/provider/bind-listeners.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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() ||
Expand Down
17 changes: 17 additions & 0 deletions src/main/ipc/pty/pty-write-ipc-validation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
161 changes: 160 additions & 1 deletion src/main/runtime/terminal-subscriber-driven-daemon-attach.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ type RuntimeInternals = {
worktrees: [],
targetWorktreeId: string | null
) => Promise<unknown>
// Optional so this suite still runs, and fails on behavior, against a runtime without it.
notePtyEndpointLoss?: (ptyId: string) => void
}

function internals(runtime: OrcaRuntimeService): RuntimeInternals {
Expand All @@ -48,10 +50,18 @@ function createDaemonProviderModel(opts: { snapshotCapable: boolean }) {
const sessions = new Map<string, DaemonSessionModel>()
const attachCalls: string[] = []
const resizeCalls: [string, number, number][] = []
const writes: string[] = []
let nextAttachBarrier: { promise: Promise<void>; 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 () =>
Expand Down Expand Up @@ -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<void>((resolve) => {
Expand Down Expand Up @@ -483,3 +500,145 @@ 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. 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<typeof setupNeverAttachedDaemonSession> {
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<typeof createDaemonProviderModel>
): void {
model.dropAttachments()
// What the local provider's write-unavailable fan-out reports for every session it held.
internals(runtime).notePtyEndpointLoss?.(PTY_ID)
}

it('takes back the stream of a session no view shows', async () => {
const { runtime, model, handle } = setupSpawnedAttachedSession()

loseEndpoint(runtime, model)

await vi.waitFor(() => expect(model.attachCalls).toEqual([PTY_ID]))
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('holds input sent while the re-attach is in flight instead of refusing it', 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: '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('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)
loseEndpoint(runtime, model)
releaseAttach()
await vi.waitFor(() => expect(model.attachCalls).toEqual([PTY_ID]))

await runtime.sendTerminal(handle, { text: 'a' }, { inputKind: 'driving' }).catch(() => {})
await runtime.sendTerminal(handle, { text: 'b' }, { inputKind: 'driving' }).catch(() => {})
expect(model.attachCalls).toEqual([PTY_ID])

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, 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 () => {
// 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 } = setupSpawnedAttachedSession()
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)
})
})
13 changes: 13 additions & 0 deletions src/main/runtime/terminal/input/terminal-input-dispatch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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) {
Expand Down Expand Up @@ -244,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) {
Expand Down
58 changes: 58 additions & 0 deletions src/main/runtime/terminal/layout/terminal-view-presence.ts
Original file line number Diff line number Diff line change
@@ -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'
Expand All @@ -11,6 +12,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,
Expand Down Expand Up @@ -69,6 +73,60 @@ export abstract class OrcaRuntimeWithNotifyRemoteTerminalViewPresenceChanged ext
return this.mainDaemonAttachments.isKnownUnattachedLocal(ptyId)
}

/** 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 waits, bounded, for main's in-flight re-attach after an endpoint loss instead of being refused. */
protected async waitForPtyEndpointReattach(
ptyId: string | undefined,
signal?: AbortSignal
): Promise<void> {
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<boolean>,
signal?: AbortSignal
): Promise<void> {
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: Promise<boolean> | undefined = first
while (reattach) {
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)
}
}

/** Mark a raw-output viewer without transferring terminal query authority. */
registerRawTerminalViewSubscriber(ptyId: string): () => void {
return this.terminalViewSubscribers.registerRaw(ptyId)
Expand Down
Loading
Loading