Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

fix: close open tool calls when a turn aborts

Samrat Talukdar8cd398aa570d
diff --git a/apps/server/src/context/PARITY.sha256 b/apps/server/src/context/PARITY.sha256
index 20bb33ce..d4fe0803 100644
--- a/apps/server/src/context/PARITY.sha256
+++ b/apps/server/src/context/PARITY.sha256
@@ -7,6 +7,7 @@ e13f86577014b52affc4c2336630eedcac277b974939c6741119a62b7fda439b ephemeral.ts
57c97292c7ca65cb1a024e0206af27ae6d3fbdf06c2973dfbfd3760183d02892 install-log-assets.ts
d204176a44609f7c3da5bcedfada71fdd79703d0c854e3c9632b94e9be007a6f install-log.ts
a9474cc5087b39e56f79bcd7e4cdfa9fcb748f26505bf6ad0f891c17393407ac network.ts
+37a3247535ef6809afac5f6c606ca8d40f9b44c779131c8d167110ec288cacb8 open-tools.ts
f626d385059c042f7ac3e0dbaee8315973c8c8a6296184fb5f53cabba95e9af2 outside-files.ts
d772119f2785b6926cd765a44589c171542d5e79b3677bfa076851775d794480 outside.ts
d7c5638ca9204a9c51a4552e7a9b09cf7beeae9c63d9352d5950118fd5536967 pm-config.ts
diff --git a/apps/server/src/context/open-tools.ts b/apps/server/src/context/open-tools.ts
new file mode 100644
index 00000000..0677d022
--- /dev/null
+++ b/apps/server/src/context/open-tools.ts
@@ -0,0 +1,68 @@
+// Tool calls the engine left open (pending or running) when a turn ended
+// without them: the model's stream died after it asked for a tool, the user
+// stopped the turn, or the app quit while a tool ran. The engine closes them
+// itself on a clean stop ("Tool execution aborted", metadata.interrupted);
+// when its cleanup never ran (a killed engine) or had not run yet when the
+// turn was read, the uploaded copy closes them the same way, so no tool call
+// reads as still running in a turn that is over. Identical in the CLI and
+// the desktop app.
+
+export const TOOL_ABORTED_ERROR = "Tool execution aborted";
+
+const OPEN_STATUSES = new Set(["pending", "running"]);
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+function finiteNumber(value: unknown): number | null {
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
+}
+
+/** Whether an assistant message is over: it completed, failed or has a finish reason. */
+function messageEnded(info: Record<string, unknown>): boolean {
+ const time = isRecord(info.time) ? info.time : {};
+ return finiteNumber(time.completed) !== null || info.error != null || (typeof info.finish === "string" && info.finish !== "");
+}
+
+/**
+ * The messages with every open tool part of an ended turn closed as aborted
+ * (status "error", error "Tool execution aborted", metadata.interrupted, an
+ * end time: the message's completion, else `now`). `engineIdle`: the session
+ * no longer runs (idle, quit, recovered after a kill), so every open tool
+ * part is over; otherwise only those of assistant messages that ended.
+ * Messages without an open tool part are returned as they are.
+ */
+export function closeOpenToolParts<T>(messages: readonly T[], options: { engineIdle: boolean; now?: number }): { messages: T[]; closed: number } {
+ let closed = 0;
+ const out = messages.map((message) => {
+ if (!isRecord(message) || !isRecord(message.info) || !Array.isArray(message.parts)) return message;
+ const info = message.info;
+ if ((info.role ?? info.type) !== "assistant") return message;
+ if (!options.engineIdle && !messageEnded(info)) return message;
+ let changed = false;
+ const time = isRecord(info.time) ? info.time : {};
+ const end = finiteNumber(time.completed) ?? options.now ?? Date.now();
+ const parts = message.parts.map((part: unknown) => {
+ if (!isRecord(part) || part.type !== "tool" || !isRecord(part.state) || !OPEN_STATUSES.has(String(part.state.status))) return part;
+ const state = part.state;
+ const started = isRecord(state.time) ? finiteNumber(state.time.start) : null;
+ const metadata = isRecord(state.metadata) ? state.metadata : {};
+ changed = true;
+ closed += 1;
+ return {
+ ...part,
+ state: {
+ ...state,
+ status: "error",
+ input: isRecord(state.input) ? state.input : {},
+ error: TOOL_ABORTED_ERROR,
+ metadata: { ...metadata, interrupted: true },
+ time: { start: started ?? end, end: Math.max(end, started ?? end) },
+ },
+ };
+ });
+ return changed ? ({ ...message, parts } as T) : message;
+ });
+ return { messages: out, closed };
+}
diff --git a/apps/server/src/open-tools.test.ts b/apps/server/src/open-tools.test.ts
new file mode 100644
index 00000000..184cf1c1
--- /dev/null
+++ b/apps/server/src/open-tools.test.ts
@@ -0,0 +1,38 @@
+import { describe, expect, test } from "bun:test";
+
+import { closeOpenToolParts, TOOL_ABORTED_ERROR } from "./context/open-tools.js";
+
+// The same cases as the CLI's test/tool-abort.test.js (open-tools.ts is shared, PARITY.sha256).
+const tool = (status: string, extra: Record<string, unknown> = {}) => ({ id: "prt_1", type: "tool", tool: "edit", callID: "call_a|fc_b", state: { status, input: { filePath: "a.ts" }, ...extra } });
+const dropped = (part: unknown) => ({
+ info: { id: "a1", role: "assistant", time: { created: 10, completed: 50 }, finish: "error", error: { name: "APIError" } },
+ parts: [{ type: "step-start" }, part, { type: "step-finish", reason: "error" }],
+});
+
+describe("closeOpenToolParts", () => {
+ test("a running call of an answer that ended is closed as aborted, at the answer's end", () => {
+ const { messages, closed } = closeOpenToolParts([dropped(tool("running", { time: { start: 40 } }))], { engineIdle: false });
+ expect(closed).toBe(1);
+ expect((messages[0] as { parts: Array<{ state: unknown }> }).parts[1]!.state).toEqual({
+ status: "error", input: { filePath: "a.ts" }, error: TOOL_ABORTED_ERROR, metadata: { interrupted: true }, time: { start: 40, end: 50 },
+ });
+ });
+
+ test("an answer still streaming keeps its calls open while the engine runs, and not once it stopped", () => {
+ const live = { info: { id: "a1", role: "assistant", time: { created: 10 } }, parts: [tool("pending")] };
+ expect(closeOpenToolParts([live], { engineIdle: false })).toEqual({ messages: [live], closed: 0 });
+ const idle = closeOpenToolParts([live], { engineIdle: true, now: 99 });
+ expect(idle.closed).toBe(1);
+ expect((idle.messages[0] as unknown as { parts: Array<{ state: { time: unknown } }> }).parts[0]!.state.time).toEqual({ start: 99, end: 99 });
+ expect(live.parts[0]!.state.status).toBe("pending");
+ });
+
+ test("finished calls and user messages are untouched", () => {
+ const done = dropped(tool("completed", { output: "ok", time: { start: 1, end: 2 } }));
+ const user = { info: { id: "u1", role: "user" }, parts: [{ type: "tool", state: { status: "running" } }] };
+ const { messages, closed } = closeOpenToolParts([user, done], { engineIdle: true });
+ expect(closed).toBe(0);
+ expect(messages[0]).toBe(user);
+ expect(messages[1]).toBe(done);
+ });
+});
diff --git a/apps/server/src/session-upload-observer.test.ts b/apps/server/src/session-upload-observer.test.ts
index a715978e..e041f1a1 100644
--- a/apps/server/src/session-upload-observer.test.ts
+++ b/apps/server/src/session-upload-observer.test.ts
@@ -375,6 +375,43 @@ describe("session upload observer", () => {
expect(sessionUploader.entries.find((entry) => entry.kind === "flush")).toMatchObject({ final: { outcome: "aborted" } });
});
+ test("a turn whose model stream died right after a tool call goes up with that call closed as aborted", async () => {
+ const clock = fakeClock();
+ const engine = startEngine();
+ const sessionUploader = new FakeUploader();
+ const archive = fakeArchive();
+ const dropped = message("msg_assistant_0001", "assistant", "Editing");
+ dropped.info = { ...dropped.info, time: { created: 1, completed: 50 }, finish: "error", error: { name: "APIError", data: { message: "The upstream stream ended" } } };
+ const call = { id: "prt_tool_0001", messageID: "msg_assistant_0001", sessionID: SESSION, type: "tool", tool: "edit", callID: "call_x|fc_y", state: { status: "running", input: { filePath: "a.ts" }, time: { start: 40 } } };
+ dropped.parts = [...dropped.parts, call];
+ engine.control.messages = [message("msg_user_0001", "user", "Edit a.ts"), dropped];
+ engine.control.status = () => (clock.elapsed() < 60_000 ? "busy" : "idle");
+
+ await observe({ sessionUploader, archive, observers: createSessionObservers(), target: engine.target, timing: clock.timing });
+
+ expect(sessionUploader.trace("turn.tools_closed")).toEqual([{ count: 1 }]);
+ const final = sessionUploader.entries.find((entry) => entry.kind === "flush" && entry.final !== undefined) as { final: { messages: EngineMessage[] } };
+ const part = final.final.messages[1]!.parts[1] as { callID: string; state: Record<string, unknown> };
+ expect(part.callID).toBe("call_x|fc_y");
+ expect(part.state).toEqual({ status: "error", input: { filePath: "a.ts" }, error: "Tool execution aborted", metadata: { interrupted: true }, time: { start: 40, end: 50 } });
+ // The engine's own copy is left as it is.
+ expect((engine.control.messages[1]!.parts[1] as { state: { status: string } }).state.status).toBe("running");
+ });
+
+ test("a turn whose calls all finished records no closing", async () => {
+ const clock = fakeClock();
+ const engine = startEngine();
+ const sessionUploader = new FakeUploader();
+ const reply = message("msg_assistant_0001", "assistant", "Done");
+ reply.parts = [...reply.parts, { id: "prt_tool_0001", type: "tool", tool: "read", callID: "c1", state: { status: "completed", input: {}, output: "ok", time: { start: 1, end: 2 } } }];
+ engine.control.messages = [message("msg_user_0001", "user", "Read"), reply];
+ engine.control.status = () => (clock.elapsed() < 60_000 ? "busy" : "idle");
+
+ await observe({ sessionUploader, archive: fakeArchive(), observers: createSessionObservers(), target: engine.target, timing: clock.timing });
+
+ expect(sessionUploader.trace("turn.tools_closed")).toEqual([]);
+ });
+
test("a status read that times out twice, then answers, does not end the observation", async () => {
const clock = fakeClock();
const engine = startEngine();
diff --git a/apps/server/src/session-upload-observer.ts b/apps/server/src/session-upload-observer.ts
index 461bdae1..3438c5b5 100644
--- a/apps/server/src/session-upload-observer.ts
+++ b/apps/server/src/session-upload-observer.ts
@@ -15,6 +15,7 @@ import { watchToolCallEnds } from "./session-archive/files-used.js";
import { turnWriters, type WriterSessionMessages } from "./session-archive/turn-writers.js";
import { watchToolStarts } from "./session-archive/tool-start.js";
import { watchToolEvents } from "./context/tool-events.js";
+import { closeOpenToolParts } from "./context/open-tools.js";
import type { ContextCapture } from "./context/index.js";
/** The engine a captured request went to: base URL, request headers (the engine's auth), query and API generation. */
@@ -339,7 +340,8 @@ async function captureChildSessions(input: {
input.visited.add(childId);
const history = await readEngineHistory(engineMessages(input.fetchEngine, `/session/${encodeURIComponent(childId)}/message`, true), input.checkpoints[childId])
.catch(nullOnErrorStatus);
- const newMessages = history?.delta ?? [];
+ // A sub-agent may still run: only the calls of its answers that ended are closed.
+ const newMessages = history ? closeOpenToolParts(history.delta, { engineIdle: false }).messages : [];
if (newMessages.length > 0) input.onChild?.(childId, input.depth, newMessages);
if (history && history.omitted > 0) {
input.sessionUploader.recordTrace(input.rootSessionId, "session.messages_omitted", { child_session_id: childId, count: history.omitted });
@@ -843,7 +845,8 @@ export async function readSessionTranscript(target: EngineTarget, sessionId: str
const path = v2 ? `/api/session/${encodeURIComponent(sessionId)}/context` : `/session/${encodeURIComponent(sessionId)}/message`;
try {
const history = await readEngineHistory(engineMessages(fetchEngine, path, !v2), undefined, MAX_BACKLOG_MESSAGE_BYTES);
- return messageParts(history.delta, history.sizes).map((part) => part.messages);
+ // The session may be running: only the calls of answers that ended are closed.
+ return messageParts(closeOpenToolParts(history.delta, { engineIdle: false }).messages, history.sizes).map((part) => part.messages);
} catch {
return null;
}
@@ -855,6 +858,20 @@ export async function readSessionTranscript(target: EngineTarget, sessionId: str
* the last part, and each earlier part takes the next older ones. One part,
* empty, when there are no messages.
*/
+/**
+ * A turn that is over keeps no tool call open: those the engine left pending
+ * or running (a dropped model stream, a stop, an engine gone with the app)
+ * go up closed as aborted (context/open-tools.ts), and the trace says how
+ * many. While the engine still runs (a turn cut by the next prompt), only
+ * the calls of answers that ended are closed.
+ */
+function closeTurnTools(uploader: Pick<SessionUploader, "recordTrace">, sessionId: string, history: EngineHistory, engineIdle: boolean): void {
+ const { messages, closed } = closeOpenToolParts(history.delta, { engineIdle });
+ if (closed === 0) return;
+ history.delta = messages;
+ uploader.recordTrace(sessionId, "turn.tools_closed", { count: closed });
+}
+
function messageParts(messages: readonly unknown[], sizes: readonly number[], maxBytes = MAX_TURN_MESSAGE_BYTES): MessagePart[] {
const parts: MessagePart[] = [];
let part: MessagePart = { messages: [], bytes: 0 };
@@ -1045,6 +1062,7 @@ export function observeUploadedSession(input: {
observer.lastMessageIds.set(sessionId, lastId);
void sessionUploader.setSessionCheckpoint(sessionId, lastId);
}
+ closeTurnTools(sessionUploader, sessionId, history, status === "idle" || status === "quit");
if (history.checkpointMissing && !v2) {
// The messages the last upload ended with are gone: a revert was made
// final. Earlier uploads still hold the reverted turns, so the trace