diff --git a/src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-headless-mailbox-pointer.test.ts b/src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-headless-mailbox-pointer.test.ts index efa557e1fec..d4057745f37 100644 --- a/src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-headless-mailbox-pointer.test.ts +++ b/src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-headless-mailbox-pointer.test.ts @@ -5,14 +5,19 @@ import '../../db/messages/mailbox-routing-page' import '../../db/dispatch-row-writer' import '../../db/attempt-outcome-projection' import type { OrcaRuntimeService } from '../../../orca-runtime' +import { readRuntimeFixture } from '../../../terminal/wait/agent-transcript-replay-test-harness' +import { settledWriteStub } from '../../../../providers/testing/settled-pty-write-stub' import { + createBoundRun, + insertDirectRunMessage, createRuntime, PANE_KEY, pointerCount, PTY_ID, TAB_ID, LEAF_ID, - WORKTREE_ID + WORKTREE_ID, + TERMINAL_HANDLE } from './orchestration-mailbox-notification-test-harness' type Host = 'headless' | 'window-empty-graph' | 'window-graph-unavailable' @@ -61,6 +66,52 @@ describe('orchestration mailbox pointer for a terminal no pane shows', () => { vi.useRealTimers() }) + it('does not assign an earlier synchronized frame to a later command in the same read', async () => { + const db = new OrchestrationDb(':memory:') + const { runtime } = createRuntime(db, { launchAgent: null, headless: true }) + const write = vi.fn<(id: string, data: string) => boolean>(() => true) + runtime.setPtyController({ + write, + writeWithSettlement: settledWriteStub(write), + kill: vi.fn(), + getSize: () => ({ cols: 120, rows: 40 }), + getForegroundProcess: async () => 'zsh' + }) + const run = createBoundRun(db, 'coalesced predecessor frame') + await runtime.listTerminals() + runtime.terminalRunFacts.recordSpawnCommit({ id: PTY_ID }) + // Freebuff 0.1.2's recorded initial alternate screen, at its recorded grid size. + const recording = readRuntimeFixture('freebuff-ready') + const readyFrame = recording.slice(recording.indexOf('\x1b[?1049h')) + try { + runtime.onPtyData( + PTY_ID, + `\x1b]133;C\x07\x1b]0;Freebuff: \x07${readyFrame}\x1b[?1049l\x1b]133;D;0\x07\x1b]133;A\x07\x1b]133;C\x07\x1b]0;claude\x07new invocation hook\r\n`, + Date.now() + ) + const settled = vi.fn() + const wait = runtime.waitForTerminal(TERMINAL_HANDLE, { + condition: 'tui-idle', + timeoutMs: 60_000 + }) + wait.then(settled, () => {}) + insertDirectRunMessage(db, run.id, 'After current readiness') + runtime.notifyMessageArrived(`run:${run.id}`, 'status') + await vi.advanceTimersByTimeAsync(12_000) + expect(settled).not.toHaveBeenCalled() + expect(write).not.toHaveBeenCalled() + runtime.onPtyData(PTY_ID, '\x1b]7501;state=idle:app=claude-code\x07', Date.now()) + await vi.advanceTimersByTimeAsync(5_000) + await expect(wait).resolves.toMatchObject({ satisfied: true }) + expect(write.mock.calls.map(([, data]) => data)).toEqual([ + expect.stringContaining('You have 1 orchestration message'), + '\r' + ]) + } finally { + db.close() + } + }) + it('points an already idle coordinator at Run mail', async () => { const { db, runtime, write, sendRunMail } = await coordinator() await goIdle(runtime) diff --git a/src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-open-dialog-delivery-hold.test.ts b/src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-open-dialog-delivery-hold.test.ts index 9cbe5bbbe85..2a5691ec3d1 100644 --- a/src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-open-dialog-delivery-hold.test.ts +++ b/src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-open-dialog-delivery-hold.test.ts @@ -78,6 +78,53 @@ describe('mailbox delivery with current adopted agent evidence', () => { } }) + it.each(['\x1b]133;D;0\x07\x1b]133;A\x07', ''])( + 'does not renew a retired root from child-only reports across replacement (%j)', + async (exit) => { + vi.useFakeTimers() + const db = createDatabase('orca-retired-root-') + const { runtime } = createRuntime(db, { launchAgent: null }) + const write = vi.fn<(id: string, data: string) => boolean>(() => true) + runtime.setPtyController({ + write, + writeWithSettlement: settledWriteStub(write), + kill: vi.fn(), + getForegroundProcess: async () => 'zsh' + }) + const run = createBoundRun(db, 'retired root') + await runtime.listTerminals() + runtime.terminalRunFacts.recordSpawnCommit({ id: PTY_ID }) + const ingest = (data: string) => runtime.onPtyData(PTY_ID, data, Date.now()) + try { + ingest( + '\x1b]133;C\x07\x1b]0;claude\x07\x1b[?2031h\x1b[?2004h❯\u00a0\x1b]7501;state=done:app=claude-code\x07\x1b]7501;state=done:id=job\x07' + ) + ingest(`${exit}\x1b]133;C\x07\x1b]0;claude\x07new hook\r\n`) + ingest('\x1b]7501;state=clear:id=job\x07') + const settled = vi.fn() + const wait = runtime.waitForTerminal(TERMINAL_HANDLE, { + condition: 'tui-idle', + timeoutMs: 60_000 + }) + wait.then(settled, () => {}) + insertDirectRunMessage(db, run.id, 'Current invocation only') + runtime.notifyMessageArrived(`run:${run.id}`, 'status') + await vi.advanceTimersByTimeAsync(12_000) + expect(settled).not.toHaveBeenCalled() + expect(write).not.toHaveBeenCalled() + ingest('\x1b]7501;state=idle:app=claude-code\x07') + await vi.advanceTimersByTimeAsync(5_000) + await expect(wait).resolves.toMatchObject({ satisfied: true }) + expect(write.mock.calls.map(([, data]) => data)).toEqual([ + expect.stringContaining('You have 1 orchestration message'), + '\r' + ]) + } finally { + db.close() + } + } + ) + it('delivers working-turn mail only after an adopted wrapper has current composer evidence', async () => { vi.useFakeTimers() const db = createDatabase('orca-adopted-working-mail-') diff --git a/src/main/runtime/terminal/lifecycle/terminal-view-resources.ts b/src/main/runtime/terminal/lifecycle/terminal-view-resources.ts index 3a58b49be24..0d5e92bd0ac 100644 --- a/src/main/runtime/terminal/lifecycle/terminal-view-resources.ts +++ b/src/main/runtime/terminal/lifecycle/terminal-view-resources.ts @@ -16,7 +16,7 @@ import type { } from '../records/runtime-terminal-state-records' import type { TerminalKittyKeyboardModeTracker } from '../../../../shared/terminal/protocol/input-modes/terminal-kitty-keyboard-mode-tracker' import type { PtyProviderBufferSnapshot } from '../../../providers/pty/provider-contract' -import type { createAgentStatusOscProcessor } from '../../../../shared/agent-status/transport/agent-status-osc' +import type { createTerminalAgentStatusProcessor } from '../../../../shared/program-status/terminal-agent-status-processor' import { RuntimeTerminalViewSubscribers } from '../view/runtime-terminal-view-subscribers' import { MainDaemonAttachments } from './main-daemon-attachments' import { parseAppSshPtyId } from '../../../../shared/ssh-pty-id' @@ -145,7 +145,7 @@ export abstract class OrcaRuntimeWithFitOverrideListeners extends OrcaRuntimeWit // OSC 9999 status frames can span PTY chunks. protected agentStatusOscProcessorsByPtyId = new Map< string, - ReturnType + ReturnType >() // PTYs whose last OSC 7501 facet dies with the program; their exit must clear it. diff --git a/src/main/runtime/terminal/output/headless-terminal-hydration.ts b/src/main/runtime/terminal/output/headless-terminal-hydration.ts index 39fe9a5ccf2..1dd836894b1 100644 --- a/src/main/runtime/terminal/output/headless-terminal-hydration.ts +++ b/src/main/runtime/terminal/output/headless-terminal-hydration.ts @@ -225,7 +225,8 @@ export abstract class OrcaRuntimeWithMaybeHydrateHeadlessFromRenderer extends Or data: string, outputSequence: number, forwardQueryReplies = false, - isCurrentAction = this.ptyForegroundAgent.captureGeneration(ptyId) + isCurrentAction = this.ptyForegroundAgent.captureGeneration(ptyId), + actionBoundary = -1 ): void { const state = this.getOrCreateHeadlessTerminal(ptyId) const outputObservedAt = Date.now() @@ -248,13 +249,15 @@ export abstract class OrcaRuntimeWithMaybeHydrateHeadlessFromRenderer extends Or await state.emulator.write(escapeTail) } } + let frameEnd = 0 for (const chunk of splitFreebuffScreenUpdates(data, state.emulator.partialEscapeTailAnsi)) { + frameEnd += chunk.length await state.emulator.write(chunk, { forwardQueryReplies }) const pty = this.ptysById.get(ptyId) if (!pty || this.headlessTerminals.get(ptyId) !== state) { continue } - if (!isCurrentAction()) { + if (frameEnd <= actionBoundary || !isCurrentAction()) { continue } const command = this.terminalSpawnCommandsByPtyId.get(ptyId) diff --git a/src/main/runtime/terminal/output/pty-output-ingestion.ts b/src/main/runtime/terminal/output/pty-output-ingestion.ts index 74794d93088..e971c95232d 100644 --- a/src/main/runtime/terminal/output/pty-output-ingestion.ts +++ b/src/main/runtime/terminal/output/pty-output-ingestion.ts @@ -29,7 +29,8 @@ export abstract class OrcaRuntimeWithOnPtyData extends OrcaRuntimeWithPreparePty ): { cwd: string | null; cwdChanged: boolean } protected abstract processAgentStatusOscForPty( ptyId: string, - data: string + data: string, + readinessBoundary?: number ): ProcessedAgentStatusChunk protected abstract recordRecentPtyOutput(ptyId: string, data: string): void protected abstract shouldAnswerQueriesForLiveChunk(ptyId: string): boolean @@ -39,7 +40,8 @@ export abstract class OrcaRuntimeWithOnPtyData extends OrcaRuntimeWithPreparePty data: string, outputSequence: number, forwardQueryReplies?: boolean, - isCurrentAction?: () => boolean + isCurrentAction?: () => boolean, + actionBoundary?: number ): void protected abstract getOrCreatePtyWorktreeRecord(ptyId: string): RuntimePtyWorktreeRecord | null protected abstract scheduleWaitBlockedCheck(ptyId: string, appendedText: string, at: number): void @@ -106,7 +108,6 @@ export abstract class OrcaRuntimeWithOnPtyData extends OrcaRuntimeWithPreparePty const osc7Metadata = this.recordOsc7MetadataForPty(ptyId, data) const cwd = osc7Metadata.cwd const cwdChanged = osc7Metadata.cwdChanged - const agentStatusChunk = this.processAgentStatusOscForPty(ptyId, data) this.recordRecentPtyOutput(ptyId, data) // Use advertised dev-server URLs for workspace ports instead of kernel bind addresses. advertisedUrlWatcher.ingest(ptyId, data, at) @@ -162,12 +163,15 @@ export abstract class OrcaRuntimeWithOnPtyData extends OrcaRuntimeWithPreparePty this.scheduleWaitBlockedCheck(ptyId, normalized.text, at) } + const actionBoundary = pty?.commandPaint?.lastBoundaryEnd ?? -1 + const agentStatusChunk = this.processAgentStatusOscForPty(ptyId, data, actionBoundary) this.trackHeadlessTerminalData( ptyId, data, outputSequence, forwardQueryReplies, - this.ptyForegroundAgent.captureGeneration(ptyId) + this.ptyForegroundAgent.captureGeneration(ptyId), + actionBoundary ) for (const leaf of this.getLeavesForPty(ptyId)) { diff --git a/src/main/runtime/terminal/wait/runtime-terminal-idle-polls.test.ts b/src/main/runtime/terminal/wait/runtime-terminal-idle-polls.test.ts index 6acaf294076..e8cca2accdf 100644 --- a/src/main/runtime/terminal/wait/runtime-terminal-idle-polls.test.ts +++ b/src/main/runtime/terminal/wait/runtime-terminal-idle-polls.test.ts @@ -49,6 +49,86 @@ describe('RuntimeTerminalIdlePolls timer budget', () => { vi.useRealTimers() }) + it.each([100, 1000])( + 'materializes unchanged tails at most once per sweep for %i pending panes', + async (population) => { + const lines = ['ordinary hook output'] + const scans = vi.spyOn(lines, 'map') + const resolved = vi.fn() + const polls = new RuntimeTerminalIdlePolls({ + intervalMs: INTERVAL_MS, + quiescenceMs: 1500, + getForegroundProcess: () => null, + hasCommandPainted: () => false, + getAdoptedPtyIdleStatus: () => null, + getPaneAgent: () => null, + getFirstPartyAgentStatus: () => null, + readScreenLines: () => null, + readVisibleScreen: async () => null, + startupObservation: { + read: () => ({ kind: 'pending', candidate: 'claude' }), + watch: () => () => {}, + refresh: () => {} + }, + resolve: resolved + }) + const waiters = Array.from({ length: population }, (_, index) => { + const waiter = makeWaiter(`pending-${index}`) + polls.start(waiter, makePty(`pty-${index}`, { tailBuffer: lines })) + return waiter + }) + try { + await vi.advanceTimersByTimeAsync(60_000) + // Thirty required sweeps, one tail materialization each; awaits must not multiply it. + expect(scans.mock.calls.length).toBeGreaterThan(0) + expect(scans.mock.calls.length).toBeLessThanOrEqual(population * 30) + expect(resolved).not.toHaveBeenCalled() + } finally { + for (const waiter of waiters) { + waiter.cancelIdlePoll?.() + } + scans.mockRestore() + } + } + ) + + it('rebuilds a changed tail and re-ranks current readiness after an awaited screen read', async () => { + const before = ['before read'] + const after = ['after read'] + const beforeScan = vi.spyOn(before, 'map') + const afterScan = vi.spyOn(after, 'map') + const pty = makePty('changing-pty', { tailBuffer: before }) + const resolved = vi.fn() + const polls = new RuntimeTerminalIdlePolls({ + intervalMs: INTERVAL_MS, + quiescenceMs: 1500, + getForegroundProcess: () => null, + hasCommandPainted: () => true, + getAdoptedPtyIdleStatus: () => null, + getPaneAgent: () => null, + getFirstPartyAgentStatus: () => null, + readScreenLines: () => null, + readVisibleScreen: async () => { + pty.tailBuffer = after + pty.lastAgentStatus = 'idle' + return null + }, + resolve: resolved + }) + const waiter = makeWaiter('changing') + polls.start(waiter, pty) + try { + await vi.advanceTimersByTimeAsync(INTERVAL_MS) + expect(beforeScan).toHaveBeenCalledTimes(1) + expect(afterScan).toHaveBeenCalledTimes(1) + expect(resolved).toHaveBeenCalledWith(waiter, expect.objectContaining({ satisfied: true })) + } finally { + waiter.cancelIdlePoll?.() + beforeScan.mockRestore() + afterScan.mockRestore() + } + }) + it('allocates one interval for 20 concurrent waiters and still resolves them on the first tick', () => { const resolved: { handle: string; result: RuntimeTerminalWait }[] = [] const polls = new RuntimeTerminalIdlePolls({ diff --git a/src/main/runtime/terminal/wait/terminal-idle-polls.ts b/src/main/runtime/terminal/wait/terminal-idle-polls.ts index e535e6d00e3..266279549b6 100644 --- a/src/main/runtime/terminal/wait/terminal-idle-polls.ts +++ b/src/main/runtime/terminal/wait/terminal-idle-polls.ts @@ -8,7 +8,7 @@ import { buildPtyTerminalWaitBlockedResult, buildPtyTerminalWaitResult } from './terminal-wait-results' -import { buildTerminalWaitText } from './terminal-wait-tail-state' +import { createTerminalWaitTailReader } from './terminal-wait-tail-state' import { evaluateTuiIdle, type QuietForegroundLane, type TuiIdleVerdict } from './tui-idle-evidence' import { outputClockOf, @@ -119,15 +119,16 @@ export class RuntimeTerminalIdlePolls { } } - private sample(entry: IdlePollEntry): IdlePollSample { + private sample( + entry: IdlePollEntry, + tail: ReturnType + ): IdlePollSample { const { handle } = entry.waiter // PTY records mutate in place, so this captured reference remains live. const { pty } = entry - const readWaitText = () => - buildTerminalWaitText(pty.tailBuffer, pty.tailPartialLine, pty.preview) return { verdict: evaluateTuiIdle({ - ...ptyTuiIdleEvidence(this.deps, pty, readWaitText), + ...ptyTuiIdleEvidence(this.deps, pty, tail.readText, tail.readBlockedReason), launchReadiness: entry.waiter.launchReadiness }), ptyId: pty.ptyId, @@ -146,7 +147,8 @@ export class RuntimeTerminalIdlePolls { } let startedForegroundPoll = false try { - let sample = this.sample(entry) + const tail = createTerminalWaitTailReader(entry.pty) + let sample = this.sample(entry, tail) let { verdict } = sample const { ptyId } = sample const isCurrent = this.deps.captureGeneration?.(ptyId) ?? (() => true) @@ -171,7 +173,7 @@ export class RuntimeTerminalIdlePolls { return } if (screenRead) { - sample = this.sample(entry) + sample = this.sample(entry, tail) verdict = sample.verdict if (verdict.kind === 'ready-strong' || verdict.kind === 'blocked') { this.settle( @@ -212,7 +214,7 @@ export class RuntimeTerminalIdlePolls { if (!this.entries.has(entry) || !isCurrent()) { return } - sample = this.sample(entry) + sample = this.sample(entry, tail) const latest = sample.verdict if (latest.kind === 'blocked') { this.settle(entry, sample.blocked(latest.reason)) diff --git a/src/main/runtime/terminal/wait/terminal-wait-blocked-checks.ts b/src/main/runtime/terminal/wait/terminal-wait-blocked-checks.ts index ddf61562cbe..da6d7157a85 100644 --- a/src/main/runtime/terminal/wait/terminal-wait-blocked-checks.ts +++ b/src/main/runtime/terminal/wait/terminal-wait-blocked-checks.ts @@ -162,13 +162,17 @@ export abstract class OrcaRuntimeWithScheduleWaitBlockedCheck extends OrcaRuntim this.waitBlockedCheckStateByPtyId.delete(ptyId) } - protected processAgentStatusOscForPty(ptyId: string, data: string): ProcessedAgentStatusChunk { + protected processAgentStatusOscForPty( + ptyId: string, + data: string, + readinessBoundary?: number + ): ProcessedAgentStatusChunk { let processor = this.agentStatusOscProcessorsByPtyId.get(ptyId) if (!processor) { processor = createTerminalAgentStatusProcessor() this.agentStatusOscProcessorsByPtyId.set(ptyId, processor) } - return processor(data) + return processor(data, readinessBoundary) } /** Emit the facts batched while applying one chunk/frame as a single diff --git a/src/main/runtime/terminal/wait/terminal-wait-tail-state.ts b/src/main/runtime/terminal/wait/terminal-wait-tail-state.ts index d1f7342c6dd..52d1240a162 100644 --- a/src/main/runtime/terminal/wait/terminal-wait-tail-state.ts +++ b/src/main/runtime/terminal/wait/terminal-wait-tail-state.ts @@ -1,7 +1,10 @@ import type { RuntimeTerminalWaitBlockedReason } from '../../../../shared/runtime-terminal-contracts' import { buildTailLines } from '../output/tail/terminal-tail-state' import { tailMayContainBlockedSignal } from '../output/tail/terminal-tail-sentinel-index' -import { findActionableTerminalWaitBlockedSignal } from './terminal-wait-detection' +import { + detectTerminalWaitBlockedReason, + findActionableTerminalWaitBlockedSignal +} from './terminal-wait-detection' import { terminalWaitBlockedSentinelRe } from '../../agent-state-rules/blocked-text-layer' export function buildTerminalWaitText( @@ -17,6 +20,43 @@ export function buildTerminalWaitText( return waitText.length > 0 ? waitText : preview } +/** Re-rank live state after awaits without rebuilding an unchanged tail within that tick. */ +export function createTerminalWaitTailReader(record: { + tailBuffer: string[] + tailPartialLine: string + preview: string +}) { + let lines: string[] | undefined + let partialLine = '' + let preview = '' + let text: string | undefined + let blocked: RuntimeTerminalWaitBlockedReason | null | undefined + const readText = () => { + if ( + lines !== record.tailBuffer || + partialLine !== record.tailPartialLine || + preview !== record.preview + ) { + lines = record.tailBuffer + partialLine = record.tailPartialLine + preview = record.preview + text = undefined + blocked = undefined + } + return (text ??= buildTerminalWaitText(record.tailBuffer, partialLine, preview)) + } + return { + readText, + readBlockedReason: () => { + const current = readText() + if (blocked === undefined) { + blocked = detectTerminalWaitBlockedReason(current) + } + return blocked + } + } +} + export type TerminalTailWaitState = { waitText: string signal: { reason: RuntimeTerminalWaitBlockedReason; index: number } | null diff --git a/src/main/runtime/terminal/wait/tui-idle-evidence-source.ts b/src/main/runtime/terminal/wait/tui-idle-evidence-source.ts index a77e0c3a537..97f135aed78 100644 --- a/src/main/runtime/terminal/wait/tui-idle-evidence-source.ts +++ b/src/main/runtime/terminal/wait/tui-idle-evidence-source.ts @@ -2,6 +2,7 @@ import type { AgentStatus } from '../../../../shared/agent-status/title/agent-title-core' import type { TuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent' import type { TerminalAgent } from '../../../../shared/agent-status/identity/terminal-agent' +import type { RuntimeTerminalWaitBlockedReason } from '../../../../shared/runtime-terminal-contracts' import { isTuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent-config' import type { RuntimePtyWorktreeRecord } from '../records/runtime-terminal-state-records' import { @@ -125,7 +126,8 @@ function lazyWaitText(readWaitText: () => string): () => string { export function ptyTuiIdleEvidence( source: TuiIdleEvidenceSource, pty: RuntimePtyWorktreeRecord, - readWaitText: () => string + readWaitText: () => string, + readTailBlockedReason?: () => RuntimeTerminalWaitBlockedReason | null ): TuiIdleEvaluationInput { const waitText = lazyWaitText(readWaitText) const startup = source.startupObservation?.read(pty.ptyId) @@ -141,7 +143,8 @@ export function ptyTuiIdleEvidence( const record = evidenceRecord(source, pty) return { record, - readTailBlockedReason: () => detectTerminalWaitBlockedReason(waitText()), + readTailBlockedReason: + readTailBlockedReason ?? (() => detectTerminalWaitBlockedReason(waitText())), readPositiveBodyEvidence: () => (agent !== 'qoder' && agent !== 'qoder-cn' && diff --git a/src/shared/program-status/agent-status-projector.ts b/src/shared/program-status/agent-status-projector.ts index a5c3337fc57..843a2ba942b 100644 --- a/src/shared/program-status/agent-status-projector.ts +++ b/src/shared/program-status/agent-status-projector.ts @@ -7,7 +7,7 @@ import type { AgentSubagentSnapshot, AgentSubagentState } from '../agent-status/contracts/agent-status-subagent-snapshot' -import { AGENT_SUBAGENT_ID_MAX_LENGTH } from '../agent-status/contracts/agent-status-subagent-snapshot' +import { boundedProgramStatusChildId } from './program-status-child-id' import type { AgentTurnOutcome } from '../agent-status/lifecycle/agent-turn-outcome' import { foldMainAgentWithRowChildWork } from '../agent-hook-listener/state/agent-hook-row-child-work-fold' import { @@ -39,19 +39,6 @@ function agentTypeForProgramStatusApp(app: string | undefined): string | undefin return Object.hasOwn(APP_TO_AGENT_TYPE, app) ? APP_TO_AGENT_TYPE[app] : app } -/** A child id within the snapshot cap; long ids keep their leaf and a hash of the whole path. */ -function boundedChildId(id: string): string { - if (id.length <= AGENT_SUBAGENT_ID_MAX_LENGTH) { - return id - } - let hash = 0x811c9dc5 - for (let index = 0; index < id.length; index += 1) { - hash = Math.imul(hash ^ id.charCodeAt(index), 0x01000193) >>> 0 - } - const prefix = `${hash.toString(16).padStart(8, '0')}~` - return prefix + id.slice(-(AGENT_SUBAGENT_ID_MAX_LENGTH - prefix.length)) -} - function blockedState(record: ProgramStatusRecord): 'waiting' | 'blocked' { // Why: Orca's hooks report approvals and questions as `waiting`. return isTurnScopedProgramStatusKind(record.kind) ? 'waiting' : 'blocked' @@ -114,7 +101,10 @@ export function lapsedProgramStatusChildHold( type ProgramStatusProjector = { /** Return lifecycle payloads/root changes in chunk order (including unchanged store projections); facet is new, null when removed, * or absent when unchanged. */ - process: (data: string) => { + process: ( + data: string, + readinessBoundary?: number + ) => { payloads: ProgramStatusPayload[] readiness?: { payload: ParsedAgentStatusPayload | null; offset: number } rootChanges: ProgramStatusRootChange[] @@ -135,6 +125,7 @@ export function createProgramStatusProjector(now: () => number = Date.now): Prog // Set when the program ends; the next projection starts a new invocation. let invocationEnded = false let reportedSinceEnd = false + let rootReadinessCurrent = false const childStartedAt = new Map() const projectRoot = ( @@ -183,7 +174,7 @@ export function createProgramStatusProjector(now: () => number = Date.now): Prog if (record.id === null || state === null) { continue } - const id = boundedChildId(record.id) + const id = boundedProgramStatusChildId(record.id) live.add(id) const startedAt = childStartedAt.get(id) ?? at childStartedAt.set(id, startedAt) @@ -271,7 +262,10 @@ export function createProgramStatusProjector(now: () => number = Date.now): Prog } return { - process: (data) => { + process: (data, readinessBoundary = -1) => { + if (readinessBoundary >= 0) { + rootReadinessCurrent = false + } const events = scan(data) const payloads: ProgramStatusPayload[] = [] const rootChanges: ProgramStatusRootChange[] = [] @@ -295,6 +289,11 @@ export function createProgramStatusProjector(now: () => number = Date.now): Prog break } const ended = event.type !== 'report' + if (ended) { + rootReadinessCurrent = false + } else if (event.report.id === null) { + rootReadinessCurrent = event.report.state !== 'clear' && event.offset >= readinessBoundary + } const endsInvocation = ended && reportedSinceEnd if (endsInvocation) { // The kept done/error record is for display; the program itself no longer speaks. @@ -321,9 +320,13 @@ export function createProgramStatusProjector(now: () => number = Date.now): Prog payloads.push({ payload, offset: event.offset }) } } - readiness = { - payload: !ended && records.root() ? latestProjection : null, - offset: event.offset + if (ended || (event.type === 'report' && event.report.id === null)) { + readiness = { + payload: rootReadinessCurrent ? latestProjection : null, + offset: event.offset + } + } else if (rootReadinessCurrent) { + readiness = { payload: latestProjection, offset: event.offset } } // After the ending event's own projection, so only the next report opens a new invocation. if (endsInvocation) { diff --git a/src/shared/program-status/program-status-child-id.ts b/src/shared/program-status/program-status-child-id.ts new file mode 100644 index 00000000000..95b745982be --- /dev/null +++ b/src/shared/program-status/program-status-child-id.ts @@ -0,0 +1,14 @@ +import { AGENT_SUBAGENT_ID_MAX_LENGTH } from '../agent-status/contracts/agent-status-subagent-snapshot' + +/** A child id within the snapshot cap; long ids keep their leaf and a hash of the whole path. */ +export function boundedProgramStatusChildId(id: string): string { + if (id.length <= AGENT_SUBAGENT_ID_MAX_LENGTH) { + return id + } + let hash = 0x811c9dc5 + for (let index = 0; index < id.length; index += 1) { + hash = Math.imul(hash ^ id.charCodeAt(index), 0x01000193) >>> 0 + } + const prefix = `${hash.toString(16).padStart(8, '0')}~` + return prefix + id.slice(-(AGENT_SUBAGENT_ID_MAX_LENGTH - prefix.length)) +} diff --git a/src/shared/program-status/terminal-agent-status-processor.ts b/src/shared/program-status/terminal-agent-status-processor.ts index 5746c3a9a86..989b94c51ab 100644 --- a/src/shared/program-status/terminal-agent-status-processor.ts +++ b/src/shared/program-status/terminal-agent-status-processor.ts @@ -21,12 +21,16 @@ type ProgramStatusSideEffectScan = { /** Stateful per-PTY OSC 7501 reader for side effects: status payloads, activity and the facet. */ export function createProgramStatusSideEffectScanner(): ( - data: string + data: string, + readinessBoundary?: number ) => ProgramStatusSideEffectScan { const programStatus = createProgramStatusProjector() let lastActivity: AgentStatus | null = null - return (data) => { - const { payloads, rootChanges, facet, readiness } = programStatus.process(data) + return (data, readinessBoundary) => { + const { payloads, rootChanges, facet, readiness } = programStatus.process( + data, + readinessBoundary + ) const activity: ProgramActivityChange[] = [] for (const change of rootChanges) { const next = programStatusActivity(change.root) @@ -60,7 +64,10 @@ function mergeInBandStatusPayloads( } /** Merge stripped OSC 9999 and retained OSC 7501 statuses for main’s side-effect scan. */ -export function createTerminalAgentStatusProcessor(): (data: string) => ProcessedAgentStatusChunk { +export function createTerminalAgentStatusProcessor(): ( + data: string, + readinessBoundary?: number +) => ProcessedAgentStatusChunk { let rawStart = 0 const stripped: { cleanOffset: number; rawEnd: number }[] = [] let latestHook: ProcessedAgentStatusChunk['readinessStatus'] @@ -78,9 +85,20 @@ export function createTerminalAgentStatusProcessor(): (data: string) => Processe } }) const scanProgramStatus = createProgramStatusSideEffectScanner() - return (data) => { + return (data, readinessBoundary = -1) => { const chunk = processAgentStatusOsc(data) - const scan = scanProgramStatus(chunk.cleanData) + let cleanBoundary = readinessBoundary + if (readinessBoundary >= 0) { + let delta = rawStart + for (const frame of stripped) { + if (frame.rawEnd > readinessBoundary) { + break + } + delta = frame.rawEnd - frame.cleanOffset + } + cleanBoundary -= delta + } + const scan = scanProgramStatus(chunk.cleanData, cleanBoundary) let readinessStatus = latestHook if (scan.readiness) { let delta = rawStart