Skip to content
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { TerminalMultiplexConnection } from './terminal-multiplex-connection'
import { getAckPendingOutputText } from './terminal-stream-replay'

export function installMultiplexCleanup(state: TerminalMultiplexConnection): void {
const { runtime, streams, pendingPtyWaitControllers, emit, signal } = state
Expand All @@ -11,12 +12,17 @@ export function installMultiplexCleanup(state: TerminalMultiplexConnection): voi
stream.outputBatcher.dispose()
state.ackTotalInFlightBytes = Math.max(0, state.ackTotalInFlightBytes - stream.ackInFlightBytes)
stream.ackInFlightBytes = 0
const discardedAckPendingText = getAckPendingOutputText(stream)
stream.ackPendingOutput = []
stream.ackPendingOutputBytes = 0
stream.ackPendingOutputOverflowed = false
stream.ackRecoverySnapshotInFlight = false
stream.ackRecoveryHistoryOwed = false
stream.unsubscribeData()
if (discardedAckPendingText) {
// Why: after the view registration is released, main owns the replies this view never received.
runtime.answerYieldedTerminalQueries(stream.ptyId, discardedAckPendingText)
}
stream.unsubscribeResize()
stream.unsubscribeFit()
stream.unsubscribeDriver()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
import { getTerminalInputSequenceLedger } from './terminal-input-sequence-ledger'
import { handleMultiplexInputFrame } from './terminal-multiplex-input-frame'
import {
getAckPendingOutputText,
getOutputAfterSnapshotSeq,
normalizeMultiplexSnapshotScrollbackRows
} from './terminal-stream-replay'
Expand Down Expand Up @@ -88,6 +89,10 @@ export function installMultiplexSlotFrames(state: TerminalMultiplexConnection):
stream.pausedOutputDropNoticeSent = false
const discardsQueuedOutput =
stream.ackPendingOutput.length > 0 || stream.ackPendingOutputOverflowed
if (stream.ackPendingOutput.length > 0) {
// Why: main yielded these chunks' query replies to this view, which will now never receive them.
runtime.answerYieldedTerminalQueries(stream.ptyId, getAckPendingOutputText(stream))
}
stream.ackPendingOutput = []
stream.ackPendingOutputBytes = 0
stream.ackPendingOutputOverflowed = false
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { TerminalReplyQuerySequence } from '../../../../../shared/terminal-reply-query-scan'
import {
decodeTerminalOutputFrameChunkText,
iterateTerminalOutputFrameChunks,
type TerminalOutputFrameChunk,
type TerminalOutputMeta
Expand Down Expand Up @@ -100,6 +101,10 @@ export function appendAckPendingOutput(
stream.ackPendingOutputOverflowed ||= trimmed.overflowed
}

export function getAckPendingOutputText(stream: TerminalMultiplexStream): string {
return stream.ackPendingOutput.map(decodeTerminalOutputFrameChunkText).join('')
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

export function trimPendingOutputToBudget(
pendingOutput: TerminalOutputChunk[],
pendingOutputBytes: number
Expand Down
29 changes: 27 additions & 2 deletions src/main/runtime/rpc/terminal-multiplex-paused-output-drop.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,14 @@ import {
encodeTerminalStreamFrame,
encodeTerminalStreamJson
} from '../../../shared/terminal-stream-protocol'
import { TERMINAL_MULTIPLEX_ACK_STREAM_INITIAL_WINDOW_BYTES } from '../../../shared/terminal-multiplex-flow-control'
import { startDesktopMultiplexSubscribe } from './terminal-multiplex-test-harness'
import { RuntimeTerminalViewSubscribers } from '../runtime-terminal-view-subscribers'

async function subscribePausable(capabilities: Record<string, 1>) {
async function subscribePausable(
capabilities: Record<string, 1>,
answerYieldedTerminalQueries = vi.fn()
) {
const listeners: ((data: string, meta?: RuntimeTerminalDataMeta) => void)[] = []
const viewSubscribers = new RuntimeTerminalViewSubscribers({
notifyPresenceChanged: () => {},
Expand All @@ -25,7 +29,8 @@ async function subscribePausable(capabilities: Record<string, 1>) {
return vi.fn()
}),
registerRemoteTerminalViewSubscriber: (ptyId, isOutputPaused) =>
viewSubscribers.registerRemote(ptyId, isOutputPaused)
viewSubscribers.registerRemote(ptyId, isOutputPaused),
answerYieldedTerminalQueries
})
await vi.waitFor(() => expect(harness.handlers.has(0)).toBe(true))
harness.handlers.get(0)?.(
Expand Down Expand Up @@ -127,6 +132,26 @@ describe('terminal multiplex paused-output drop notice', () => {
await host.close()
})

// #32944: output parked behind a full ACK window is discarded on pause; main must answer its queries.
it('hands queries in discarded ACK-pending output back to main', async () => {
const answerYieldedTerminalQueries = vi.fn()
const host = await subscribePausable(
{ ackOutput: 1, outputPause: 1, outputPauseDropNotice: 1 },
answerYieldedTerminalQueries
)
for (let i = 0; i <= TERMINAL_MULTIPLEX_ACK_STREAM_INITIAL_WINDOW_BYTES / (64 * 1024); i++) {
host.emitOutput('x'.repeat(64 * 1024))
}
host.emitOutput('prompt\x1b[c')
host.setPaused(true)
expect(host.outputText()).not.toContain('\x1b[c')
expect(answerYieldedTerminalQueries).toHaveBeenCalledWith(
'pty-1',
expect.stringContaining('prompt\x1b[c')
)
await host.close()
})

// #32944: the dropped output can carry a query, so main must answer it while this view is paused.
it('yields query authority while paused and takes it back on resume and close', async () => {
const host = await subscribePausable({ ackOutput: 1, outputPause: 1, outputPauseDropNotice: 1 })
Expand Down
1 change: 1 addition & 0 deletions src/main/runtime/rpc/terminal-multiplex-test-harness.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ export function stubRuntime(overrides: Partial<OrcaRuntimeService> = {}): OrcaRu
subscribeToPtyExit: vi.fn(() => vi.fn()),
// View registration suppresses competing query responders (terminal-query-authority.md).
registerRemoteTerminalViewSubscriber: () => () => {},
answerYieldedTerminalQueries: vi.fn(),
// Default guarded handle lookup to live PTY for legacy harness stubs; null/stale cases override it (#7718).
resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }),
requestRendererTerminalTabMount: vi.fn().mockReturnValue(true),
Expand Down
10 changes: 10 additions & 0 deletions src/main/runtime/rpc/terminal-output-frame-chunks.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import {
TerminalStreamOpcode,
decodeTerminalStreamJson,
decodeTerminalStreamText,
encodeTerminalStreamJson,
encodeTerminalStreamText
} from '../../../shared/terminal-stream-protocol'
Expand All @@ -20,6 +22,14 @@ export type TerminalOutputFrameChunk = {
opcode?: TerminalStreamOpcode
}

export function decodeTerminalOutputFrameChunkText(chunk: TerminalOutputFrameChunk): string {
if (chunk.opcode === TerminalStreamOpcode.OutputSpan) {
const span = decodeTerminalStreamJson<{ data?: unknown }>(chunk.bytes)
return typeof span?.data === 'string' ? span.data : ''
}
return decodeTerminalStreamText(chunk.bytes)
}

/** `span` only for subscribers that decode OutputSpan (the multiplex); `text` is the opcode-1 encoding every client reads. */
export type TerminalOutputFrameEncoding = 'span' | 'text'

Expand Down
18 changes: 18 additions & 0 deletions src/main/runtime/terminal-query-responder.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,24 @@ describe('reply ownership matrix', () => {
expect(replies).toHaveLength(2)
})

// #32944: a pause discards output parked behind a full ACK window, after main yielded its replies.
it('answers yielded stateless queries once the view stops receiving', async () => {
const { runtime, replies } = createResponderRuntime()
markHiddenRendererPty('pty-yield')
let paused = false
const release = runtime.registerRemoteTerminalViewSubscriber('pty-yield', () => paused)
runtime.onPtyData('pty-yield', 'prompt\x1b[c', Date.now())
runtime.answerYieldedTerminalQueries('pty-yield', 'prompt\x1b[c')
await settle(runtime, 'pty-yield')
expect(replies).toEqual([])

paused = true
runtime.answerYieldedTerminalQueries('pty-yield', 'prompt\x1b[c\x1b[6n')
await settle(runtime, 'pty-yield')
expect(replies.map((reply) => reply.data)).toEqual(['\x1b[?1;2c'])
release()
})

it('keeps raw preview presence separate from terminal query authority', async () => {
const { runtime, replies } = createResponderRuntime()
markHiddenRendererPty('pty-preview')
Expand Down
18 changes: 18 additions & 0 deletions src/main/runtime/terminal/output/headless-terminal-hydration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
normalizeTerminalTitle
} from '../../../../shared/agent-detection'
import { shouldModelAnswerHiddenPtyQueries } from '../../terminal-model-query-authority'
import { extractHiddenStartupRendererQueryData } from '../../../../shared/terminal-reply-query-extraction'

export abstract class OrcaRuntimeWithMaybeHydrateHeadlessFromRenderer extends OrcaRuntimeWithSerializeMainTerminalBuffer {
protected abstract getOrCreateHeadlessTerminal(ptyId: string): RuntimeHeadlessTerminal
Expand Down Expand Up @@ -148,6 +149,23 @@ export abstract class OrcaRuntimeWithMaybeHydrateHeadlessFromRenderer extends Or
})
}

/** Answer stateless queries in output a remote view yielded at ingestion but will never receive. */
answerYieldedTerminalQueries(ptyId: string, data: string): void {
const state = this.headlessTerminals.get(ptyId)
const { statelessQueryData } = extractHiddenStartupRendererQueryData(data, '')
if (!state || !statelessQueryData || !this.shouldAnswerQueriesForLiveChunk(ptyId)) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Major · Functional Correctness · Heavy lift

🔎 Supported by static analysis

Script executed:

#!/bin/bash
# Inspect subscription replay and the remote-view query policy.
rg -n -C 6 'hasRemoteTerminalViewSubscriber\s*\(|registerRemoteTerminalViewSubscriber\s*\(|shouldModelAnswerHiddenPtyQueries\s*\(' src/main/runtime
rg -n -C 6 'readTerminal\s*\(|subscribeToTerminalData\s*\(|sendRequestedSnapshot\s*\(' src/main/runtime/rpc/methods/terminal

Repository: stablyai/orca

Length of output: 41384


Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- headless hydration ---'
nl -ba src/main/runtime/terminal/output/headless-terminal-hydration.ts | sed -n '135,190p'
printf '%s\n' '--- subscriber registry ---'
rg -n -F --glob '*.ts' -e 'class RuntimeTerminalViewSubscribers' -e 'hasRemoteReceivingOutput' -e 'registerRemote(' src/main/runtime
printf '%s\n' '--- registry implementation ---'
rg -l -F --glob '*.ts' 'hasRemoteReceivingOutput' src/main/runtime | while read -r f; do
  echo "### $f"
  nl -ba "$f" | sed -n '1,180p'
done
printf '%s\n' '--- changed salvage call sites ---'
rg -n -C 12 -F --glob '*.ts' -e 'answerYieldedTerminalQueries' -e 'notePausedOutputDropped' -e 'detachStream' src/main/runtime
printf '%s\n' '--- snapshot/replay paths ---'
rg -n -C 8 -F --glob '*.ts' -e 'pendingOutput' -e 'readTerminal(params.terminal)' -e 'readTerminal(request.terminal)' src/main/runtime/rpc/methods/terminal/terminal-multiplex* src/main/runtime/rpc/methods/terminal/terminal-subscribe-binary* src/main/runtime/rpc/methods/terminal/terminal-subscribe-method.ts
printf '%s\n' '--- relevant tests ---'
nl -ba src/main/runtime/terminal-query-responder.test.ts | sed -n '220,310p'

Repository: stablyai/orca

Length of output: 43069


Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- complete snapshot replay block ---'
nl -ba src/main/runtime/rpc/methods/terminal/terminal-subscribe-binary-snapshot.ts | sed -n '270,320p'
printf '%s\n' '--- query sequence definitions and consumers ---'
rg -n -C 10 -F --glob '*.ts' -e 'pendingQuerySequences' -e 'queryReplayData' -e 'pendingQueryOverflowed' -e 'TerminalReplyQuerySequence' src/main/runtime/rpc src/main/runtime shared
printf '%s\n' '--- initial subscription and replay ordering ---'
nl -ba src/main/runtime/rpc/methods/terminal/terminal-subscribe-binary.ts | sed -n '115,170p'
nl -ba src/main/runtime/rpc/methods/terminal/terminal-subscribe-binary-snapshot.ts | sed -n '1,90p'

Repository: stablyai/orca

Length of output: 41728


Base salvage on the discarded chunk’s recipients.

If view A parks a DA1 query and view B subscribes afterward, B makes hasRemoteReceivingOutput(ptyId) return true when A pauses. answerYieldedTerminalQueries then skips A’s discarded query, although B did not receive that earlier chunk.

Subscription replay only replays queries captured in B’s own pending buffer. It cannot replay a query received before B subscribed. Track query ownership or chunk recipients at ingestion, while preserving suppression when another view actually received the bytes.

return
}
state.writeChain = state.writeChain
.then(async () => {
// Why: injecting mid-escape would abort the live sequence and print its tail as text.
if (state.emulator.partialEscapeTailAnsi === '') {
await state.emulator.write(statelessQueryData, { forwardQueryReplies: true })
Comment on lines +169 to +173

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor · Functional Correctness · Quick win

Check query age when the queued write executes.

If hydration or earlier terminal writes hold state.writeChain for more than five seconds, this callback can forward a reply after the cutoff applied by answerUndeliveredYieldedQueries. Pass the query deadline to this operation and skip the write when that deadline has passed.

}
})
.catch(() => {})
}

protected trackHeadlessTerminalData(
ptyId: string,
data: string,
Expand Down
Loading