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
14 changes: 13 additions & 1 deletion src/main/services/TerminalManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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) {
Expand All @@ -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 };
Expand Down Expand Up @@ -2644,6 +2647,15 @@ function environmentBadge(environment: PersistedEnvironmentRef): NonNullable<Ses
* card they alone end a turn. After a confirmed end, a delayed spinner cannot start it again; the next prompt hook
* starts the next turn. Without hooks (or a remote run without a bridge) the title's idle stands.
*/
/**
* A submitted prompt starts a new task: wait_for_agent and get_agent_result answer it with the reply of a turn that
* started after it, never with the one stored from the turn before. Called once the submit was written; a prompt that
* was not submitted leaves the last answer in place.
*/
function clearSubmittedPromptAnswer(session: ManagedSession): void {
delete session.answer;
}

function resetLaunchSignals(session: ManagedSession): void {
// Nor is its conversation: its answer and turn counts would answer a wait for the new one.
delete session.answer;
Expand Down
28 changes: 21 additions & 7 deletions src/main/services/agent-runtime/RuntimeGateway.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,8 @@ interface RuntimeLease {
provider: Exclude<ProviderId, "terminal">;
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<string>;
latest: RuntimeLifecycleSignal | null;
Expand Down Expand Up @@ -288,6 +290,7 @@ export class RuntimeGateway {
provider,
tokenDigest: tokenDigest(capabilityToken),
activeTurnId: null,
turnOpen: false,
seenTurnIds: new Set(),
latest: null,
captureResult: captureResultOrGrantExpiresAt === true,
Expand Down Expand Up @@ -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,
Expand Down
47 changes: 47 additions & 0 deletions tests/agent-runtime-gateway.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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 = [];
Expand Down
50 changes: 50 additions & 0 deletions tests/opencode-result.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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 });
});
24 changes: 24 additions & 0 deletions tests/prompt-delivery.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
});
Loading