diff --git a/src/main/services/TerminalManager.ts b/src/main/services/TerminalManager.ts index 9e05ee78f..c3266f802 100644 --- a/src/main/services/TerminalManager.ts +++ b/src/main/services/TerminalManager.ts @@ -145,7 +145,7 @@ interface ManagedSession { turnStarts?: number; /** turnStarts when the last submitted prompt was delivered; undefined while none was. */ promptTurnMark?: number; - /** The last turn's final answer its hook or plugin reported (captureResult only); cleared when a turn starts. */ + /** The last turn's final answer its hook or plugin reported (captureResult only); cleared when a prompt is submitted or a turn starts. */ answer?: { text: string; truncated: boolean; at: number }; /** * Plugin options, environment ref (or, until the plugin has prepared it, the launcher's environment choice) @@ -1174,6 +1174,7 @@ export class TerminalManager { prompt.receipt.stage = "not-written"; return finish("The terminal no longer accepts input."); } + if (prompt.submit) clearSubmittedPromptAnswer(session); return finish(); } screen ??= new SessionScreen({ geometry: (id) => this.geometry(id), readBuffer: launchOutput }, id); @@ -1214,6 +1215,7 @@ export class TerminalManager { prompt.receipt.stage = "pasted"; return finish("The paste was observed but the submit key could not be written."); } + clearSubmittedPromptAnswer(session); session.incompletePrompt = false; const acceptanceDeadline = Math.min(deadline, Date.now() + 1_000); while (prompt.receipt.acceptance === "unconfirmed" && !invalidated() && Date.now() < acceptanceDeadline) { @@ -1236,6 +1238,7 @@ export class TerminalManager { else delete session.codexDraftEpoch; if (data.endsWith("\r")) { session.promptTurnMark = mark; + clearSubmittedPromptAnswer(session); session.automatedSubmit = { epoch, outputOffset: outputBeforeWrite }; } return { delivered: true }; @@ -2644,6 +2647,15 @@ function environmentBadge(environment: PersistedEnvironmentRef): NonNullable; tokenDigest: Buffer; activeTurnId: string | null; + /** A turn started and has not reported idle yet; between turns an unseen turn id may open the next one. */ + turnOpen: boolean; /** Turn ids this session already reported (bounded, oldest dropped): a late start of one of them is stale. */ seenTurnIds: Set; latest: RuntimeLifecycleSignal | null; @@ -288,6 +290,7 @@ export class RuntimeGateway { provider, tokenDigest: tokenDigest(capabilityToken), activeTurnId: null, + turnOpen: false, seenTurnIds: new Set(), latest: null, captureResult: captureResultOrGrantExpiresAt === true, @@ -482,21 +485,32 @@ export class RuntimeGateway { throw new Error("Answer capture is not authorized for this session."); } - if (message.turnId && isTurnStart(message.event)) { + const startsTurn = isTurnStart(message.event); + if (message.turnId && startsTurn) { // Each hook runs on its own connection, so a start of an earlier turn can arrive after the next turn began; // it must not make that newer turn's events look stale. if (message.turnId !== lease.activeTurnId && lease.seenTurnIds.has(message.turnId)) return null; lease.activeTurnId = message.turnId; + lease.turnOpen = true; + rememberTurn(lease, message.turnId); + } else if (message.turnId && message.turnId !== lease.activeTurnId) { + // A turn whose start hook was lost (it timed out, or the CLI skipped it) still counts: after an idle, an + // unseen id opens the next turn. During an open turn, or for an id already seen, the event is out of order. + if (lease.activeTurnId && lease.seenTurnIds.has(message.turnId)) return null; + if (lease.activeTurnId && lease.turnOpen) { + // Its turn ran before this one, so a later event of it (its Stop once this turn ends) is stale as well. + rememberTurn(lease, message.turnId); + return null; + } + lease.activeTurnId = message.turnId; + lease.turnOpen = true; rememberTurn(lease, message.turnId); - } else if ( - message.turnId - && lease.activeTurnId - && message.turnId !== lease.activeTurnId - ) { - return null; } else if (message.turnId) { rememberTurn(lease, message.turnId); + } else if (startsTurn) { + lease.turnOpen = true; } + if (message.state === "idle") lease.turnOpen = false; const signal: RuntimeLifecycleSignal = { state: message.state, event: message.event, diff --git a/tests/agent-runtime-gateway.test.mjs b/tests/agent-runtime-gateway.test.mjs index 61ec999da..bbd702318 100644 --- a/tests/agent-runtime-gateway.test.mjs +++ b/tests/agent-runtime-gateway.test.mjs @@ -158,6 +158,53 @@ test("RuntimeGateway: a late start of an earlier turn does not take over from th assert.equal(gateway.currentStatus("terminal-turns"), "idle"); }); +test("RuntimeGateway: a turn whose start hook was lost still counts after an idle, but not while another turn runs", POSIX_RUNTIME_GATEWAY_TEST, async (t) => { + const root = await fixture(t); + const signals = []; + const gateway = new RuntimeGateway({ runtimeDirectory: root, onSignal: (id, signal) => signals.push({ id, signal }) }); + await gateway.start(); + t.after(() => gateway.close()); + const capability = gateway.registerSession("terminal-lost-start", "codex"); + await send(capability.address, message(capability, "working", "UserPromptSubmit", "turn-1")); + // An event of another turn while turn 1 runs is out of order. + await send(capability.address, message(capability, "working", "PostToolUse", "turn-x")); + await send(capability.address, message(capability, "idle", "Stop", "turn-1")); + // Turn 2's UserPromptSubmit never arrived: its own events still report it. + await send(capability.address, message(capability, "working", "PostToolUse", "turn-2")); + assert.equal(gateway.currentStatus("terminal-lost-start"), "working"); + // A late event of the earlier turn stays stale. + await send(capability.address, message(capability, "idle", "Stop", "turn-1")); + await send(capability.address, message(capability, "idle", "Stop", "turn-2")); + // After that idle, an id already seen does not open a turn again. + await send(capability.address, message(capability, "working", "PostToolUse", "turn-1")); + // A turn that reports only its Stop (its start hook was lost) still ends with it. + await send(capability.address, message(capability, "idle", "Stop", "turn-3")); + await new Promise((resolve) => setImmediate(resolve)); + assert.deepEqual(signals.map(({ signal }) => `${signal.state}:${signal.event}:${signal.turnId}`), [ + "working:UserPromptSubmit:turn-1", "idle:Stop:turn-1", "working:PostToolUse:turn-2", "idle:Stop:turn-2", "idle:Stop:turn-3" + ]); + assert.equal(gateway.currentStatus("terminal-lost-start"), "idle"); +}); + +test("RuntimeGateway: an earlier turn rejected while the next one ran cannot replace it after that turn ends", POSIX_RUNTIME_GATEWAY_TEST, async (t) => { + const root = await fixture(t); + const signals = []; + const gateway = new RuntimeGateway({ runtimeDirectory: root, onSignal: (id, signal) => signals.push({ id, signal }) }); + await gateway.start(); + t.after(() => gateway.close()); + const capability = gateway.registerSession("terminal-stale-turn", "codex"); + // Turn A's start hook was lost; its events arrive out of order around turn B. + await send(capability.address, message(capability, "working", "UserPromptSubmit", "turn-b")); + await send(capability.address, message(capability, "working", "PostToolUse", "turn-a")); + await send(capability.address, message(capability, "idle", "Stop", "turn-b")); + await send(capability.address, message(capability, "idle", "Stop", "turn-a")); + await new Promise((resolve) => setImmediate(resolve)); + assert.deepEqual(signals.map(({ signal }) => `${signal.state}:${signal.event}:${signal.turnId}`), [ + "working:UserPromptSubmit:turn-b", "idle:Stop:turn-b" + ]); + assert.equal(gateway.currentStatus("terminal-stale-turn"), "idle"); +}); + test("RuntimeGateway propagates threadId for codex sessions with canonical UUID", POSIX_RUNTIME_GATEWAY_TEST, async (t) => { const root = await fixture(t); const signals = []; diff --git a/tests/opencode-result.test.mjs b/tests/opencode-result.test.mjs index 9689b60a6..1c6f0de10 100644 --- a/tests/opencode-result.test.mjs +++ b/tests/opencode-result.test.mjs @@ -170,3 +170,53 @@ test("wait_for_agent ignores an idle before the prompt's turn and returns that t assert.equal(done.reason, "idle"); assert.deepEqual(done.answer, { text: "part A done", truncated: false }); }); + +test("a follow-up prompt is never answered with the previous turn's answer", async (t) => { + const root = await realpath(await mkdtemp(join(tmpdir(), "ctty-ocr-"))); + t.after(() => rm(root, { recursive: true, force: true })); + const calls = []; + const terminals = new TerminalManager(() => undefined, availableRegistry(), undefined, undefined, true, fakeSpawner(calls)); + t.after(() => terminals.disposeAll()); + const orchestrator = terminals.create({ provider: "codex", cwd: root, profile: "normal", position: { x: 0, y: 0 }, role: "orchestrator" }); + const handler = new ScopedOrchestrationHandler(new AgentControlService(terminals, { waitTiming: { checkMs: 5, settleMs: 10, quietMs: 60 } })); + const execute = (tool, args) => handler.execute(orchestrator.id, { id: tool, tool, arguments: args }); + const spawning = execute("spawn_agent", { provider: "opencode", cwd: root, prompt: "do part A" }); + await openCodeInputReady(calls, 1); + const child = await spawning; + terminals.applyProviderSignal(child.sessionId, { kind: "lifecycle", state: "working", event: "session.status:busy" }); + terminals.applyProviderSignal(child.sessionId, { kind: "lifecycle", state: "idle", event: "session.idle" }); + terminals.recordAnswer(child.sessionId, { text: "part A done", truncated: false }); + assert.deepEqual((await execute("get_agent_result", { sessionId: child.sessionId })).answer, { text: "part A done", truncated: false }); + + // Part B was submitted, but its turn has not reported a start (its hook was slow or lost): nothing answers it yet. + await execute("send_to_agent", { sessionId: child.sessionId, prompt: "do part B" }); + assert.equal((await execute("get_agent_result", { sessionId: child.sessionId })).answer, undefined, "part A's answer is not part B's"); + const quiet = await execute("wait_for_agent", { sessionId: child.sessionId, timeoutSeconds: 5 }); + assert.deepEqual([quiet.reason, quiet.answer], ["quiet", undefined]); + + // The answer that part B's turn reports is returned. + terminals.recordAnswer(child.sessionId, { text: "part B done", truncated: false }); + assert.deepEqual((await execute("get_agent_result", { sessionId: child.sessionId })).answer, { text: "part B done", truncated: false }); +}); + +test("a prompt that was not written keeps the previous turn's answer", async (t) => { + const root = await realpath(await mkdtemp(join(tmpdir(), "ctty-ocr-"))); + t.after(() => rm(root, { recursive: true, force: true })); + const calls = []; + const terminals = new TerminalManager(() => undefined, availableRegistry(), undefined, undefined, true, fakeSpawner(calls)); + t.after(() => terminals.disposeAll()); + const orchestrator = terminals.create({ provider: "codex", cwd: root, profile: "normal", position: { x: 0, y: 0 }, role: "orchestrator" }); + const handler = new ScopedOrchestrationHandler(new AgentControlService(terminals, { waitTiming: { checkMs: 5, settleMs: 10, quietMs: 60 } })); + const execute = (tool, args) => handler.execute(orchestrator.id, { id: tool, tool, arguments: args }); + const spawning = execute("spawn_agent", { provider: "opencode", cwd: root, prompt: "do part A" }); + await openCodeInputReady(calls, 1); + const child = await spawning; + terminals.applyProviderSignal(child.sessionId, { kind: "lifecycle", state: "working", event: "session.status:busy" }); + terminals.applyProviderSignal(child.sessionId, { kind: "lifecycle", state: "idle", event: "session.idle" }); + terminals.recordAnswer(child.sessionId, { text: "part A done", truncated: false }); + + calls[1].process.write = () => { throw new Error("PTY closed"); }; + const sent = await execute("send_to_agent", { sessionId: child.sessionId, prompt: "do part B" }).catch((error) => ({ error })); + assert.notEqual(sent.delivered, true, "the failed write delivered nothing"); + assert.deepEqual((await execute("get_agent_result", { sessionId: child.sessionId })).answer, { text: "part A done", truncated: false }); +}); diff --git a/tests/prompt-delivery.test.mjs b/tests/prompt-delivery.test.mjs index d76691126..e7a7d4273 100644 --- a/tests/prompt-delivery.test.mjs +++ b/tests/prompt-delivery.test.mjs @@ -205,3 +205,27 @@ test("the archive's unstyled Codex placeholder needs current native idle and unt assert.equal((await f.send("must not append")).delivered, false); assert.equal(f.writes.length, count); }); + +test("a staged prompt clears the previous answer only once its Enter is written", async t => { + for (const failure of ["veto", "enter-write", "none"]) { + const calls = [], writes = []; + const manager = new TerminalManager(() => {}, availableRegistry(), undefined, undefined, true, + fakeSpawner(calls, { onWrite: (data) => writes.push(data) })); + t.after(() => manager.disposeAll()); + const session = manager.create({ provider: "codex", cwd: process.cwd(), profile: "normal", position: { x: 0, y: 0 } }, { captureResult: true }); + const pty = calls.at(-1).process; + pty.emitData(frame("codex")); + manager.recordAnswer(session.id, { text: "previous answer", truncated: false }); + if (failure === "enter-write") { + const write = pty.write; + pty.write = data => { if (data === "\r") throw new Error("PTY closed"); write(data); }; + } + const pending = manager.deliverPrompt(session.id, "task", true, undefined, + { waitMs: 150, ...(failure === "veto" ? { beforeSubmit: () => false } : {}) }); + await until(() => writes.length === 1); + pty.emitData(frame("codex", "task")); + const result = await pending; + assert.equal(result.receipt.stage, failure === "none" ? "submitted" : "pasted", failure); + assert.equal(manager.answer(session.id)?.text, failure === "none" ? undefined : "previous answer", failure); + } +});