Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

fix(engine2): keep a running sub-agent's child session on message reads

Anurag Pappula0d5871d97c1d
diff --git a/apps/server/src/engine2/events.ts b/apps/server/src/engine2/events.ts
index abdf8449..68ee0e51 100644
--- a/apps/server/src/engine2/events.ts
+++ b/apps/server/src/engine2/events.ts
@@ -77,16 +77,39 @@ function modelRef(value: unknown): ModelRef | undefined {
return variant && variant !== "default" ? { providerID, modelID, variant } : { providerID, modelID };
}
+/** How many sub-agent calls' child sessions the translator remembers. */
+const MAX_CHILD_SESSIONS = 2000;
+
export class EventTranslator {
private readonly sessions = new Map<string, SessionState>();
private readonly live = new Map<string, LiveAssistant>();
private readonly questions = new Map<string, QuestionMapping>();
+ /**
+ * `<session>\0<call>` → the child session a sub-agent call runs in. The 2.x
+ * engine names the child only in the call's progress events; its message
+ * list leaves a running call's metadata without it until the call ends.
+ */
+ private readonly childSessions = new Map<string, string>();
private readonly options: EventTranslatorOptions;
constructor(options: EventTranslatorOptions) {
this.options = options;
}
+ /** The child session of a sub-agent call, when its progress named one. */
+ childSessionOf(sessionID: string, callID: string): string | undefined {
+ return this.childSessions.get(`${sessionID}\u0000${callID}`);
+ }
+
+ private noteChildSession(sessionID: string, callID: string, metadata: unknown): void {
+ const child = isRecord(metadata) && typeof metadata.sessionID === "string" && metadata.sessionID ? metadata.sessionID : undefined;
+ if (!child) return;
+ const key = `${sessionID}\u0000${callID}`;
+ this.childSessions.delete(key);
+ this.childSessions.set(key, child);
+ if (this.childSessions.size > MAX_CHILD_SESSIONS) this.childSessions.delete(this.childSessions.keys().next().value as string);
+ }
+
/** The 1.x status of every session the stream saw busy or retrying. */
statuses(): Record<string, JsonRecord> {
const out: Record<string, JsonRecord> = {};
@@ -156,6 +179,7 @@ export class EventTranslator {
agent: state.agent,
model: state.model,
child: Boolean(state.parentID),
+ childSessionOf: (callID: string) => this.childSessionOf(sessionID, callID),
};
}
@@ -525,8 +549,10 @@ export class EventTranslator {
return this.assistantEvents(live, partId(String(live.message.id), "c", callID), false);
}
case "session.tool.progress": {
- const live = this.liveFor(data);
const callID = str(data, "id");
+ // Remembered even without a live message: a later read of the session fills it in.
+ if (sessionID && callID) this.noteChildSession(sessionID, callID, data.metadata);
+ const live = this.liveFor(data);
if (!live || !callID) return [];
const entry = this.toolEntry(live, callID);
const state = record(entry, "state") ?? {};
diff --git a/apps/server/src/engine2/facade.ts b/apps/server/src/engine2/facade.ts
index 00ba6de3..7a7385fe 100644
--- a/apps/server/src/engine2/facade.ts
+++ b/apps/server/src/engine2/facade.ts
@@ -361,6 +361,8 @@ export async function startEngineFacade(options: EngineFacadeOptions): Promise<E
agent: info ? str(info, "agent") : undefined,
model,
child: Boolean(info && str(info, "parentID")),
+ // A running sub-agent call keeps the child session its progress named (the read leaves it out).
+ childSessionOf: (callID) => translator.childSessionOf(sessionID, callID),
});
await attachTurnDiffs(sessionID, mapped);
return mapped;
diff --git a/apps/server/src/engine2/shapes.test.ts b/apps/server/src/engine2/shapes.test.ts
index 3e00a87a..6a74422e 100644
--- a/apps/server/src/engine2/shapes.test.ts
+++ b/apps/server/src/engine2/shapes.test.ts
@@ -385,6 +385,47 @@ describe("live events and read-back agree", () => {
}
});
+ test("a read of running sub-agent calls names their child sessions, as their progress did", async () => {
+ // The 2.x engine's read of a running subagent call leaves out the child session; only the
+ // call's progress events name it. A re-read (the app reloads the session's messages) used to
+ // drop the child from the task card until the call ended.
+ const tree = fixture("v2-sub");
+ const parent = (tree.session as { id: string }).id;
+ const running = JSON.parse(JSON.stringify(tree.messages)) as Array<Record<string, unknown>>;
+ for (const message of running) {
+ for (const entry of (Array.isArray(message.content) ? message.content : []) as Array<Record<string, any>>) {
+ if (entry.type === "tool" && entry.name === "subagent") entry.state = { status: "running", input: entry.state.input, metadata: {} };
+ }
+ }
+ const translator = new EventTranslator({ version: "2.0.18" });
+ const events = JSON.parse(readFileSync(join(import.meta.dir, "fixtures", "v2-sub-events.json"), "utf8")) as Array<{ type: string; data: Record<string, any> }>;
+ const progressed = new Map<string, string>();
+ for (const event of events) {
+ await translator.translate(event);
+ if (event.type === "session.tool.progress" && event.data.sessionID === parent && typeof event.data.metadata?.sessionID === "string") {
+ progressed.set(String(event.data.id), event.data.metadata.sessionID);
+ }
+ if (event.type === "session.tool.success") break;
+ }
+ expect(progressed.size).toBe(2);
+ const read = (childSessionOf?: (callID: string) => string | undefined) =>
+ (v1Messages(running, { sessionID: parent, directory: "/work/proj", root: "/", model: { providerID: "mock", modelID: "mock-model" }, childSessionOf })
+ .flatMap((message) => message.parts)
+ .filter((part) => part.type === "tool") as Array<{ callID: string; tool: string; state: { status: string; metadata: Record<string, unknown> } }>);
+
+ const tasks = read((callID) => translator.childSessionOf(parent, callID));
+ expect(tasks.map((task) => [task.tool, task.state.status])).toEqual([["task", "running"], ["task", "running"]]);
+ for (const task of tasks) expect(task.state.metadata.sessionId).toBe(progressed.get(task.callID));
+ // Without the progress it was read with no child (the bug), and a stored child is never replaced.
+ expect(read().map((task) => task.state.metadata.sessionId)).toEqual([undefined, undefined]);
+ const stored = JSON.parse(JSON.stringify(running)) as Array<Record<string, any>>;
+ for (const message of stored) for (const entry of message.content ?? []) if (entry.type === "tool") entry.state.metadata = { sessionID: "ses_stored" };
+ const kept = v1Messages(stored, { sessionID: parent, childSessionOf: () => "ses_from_progress" }).flatMap((message) => message.parts).filter((part) => part.type === "tool") as Array<{ state: { metadata: Record<string, unknown> } }>;
+ expect(kept.map((task) => task.state.metadata.sessionId)).toEqual(["ses_stored", "ses_stored"]);
+ // Only this session's calls: another session's call of the same id names no child.
+ expect(translator.childSessionOf("ses_other", tasks[0]!.callID)).toBeUndefined();
+ });
+
test("busy and idle come from the execution lifecycle", async () => {
const translator = new EventTranslator({ version: "2.0.18" });
const started = await translator.translate({ type: "session.execution.started", data: { sessionID: "ses_a" } });
diff --git a/apps/server/src/engine2/shapes.ts b/apps/server/src/engine2/shapes.ts
index 2cf77953..b90658c3 100644
--- a/apps/server/src/engine2/shapes.ts
+++ b/apps/server/src/engine2/shapes.ts
@@ -135,7 +135,14 @@ function v1TaskOutput(text: string): string {
return `<task id="${match[1]}" state="${match[2]}">\n<task_result>\n${match[3]}\n</task_result>\n</task>`;
}
-type ToolContext = { sessionID: string; directory?: string; root?: string; parentModel?: { providerID: string; modelID: string } };
+type ToolContext = {
+ sessionID: string;
+ directory?: string;
+ root?: string;
+ parentModel?: { providerID: string; modelID: string };
+ /** The child session a sub-agent call's progress named (MessageContext.childSessionOf). */
+ childSessionOf?: (callID: string) => string | undefined;
+};
function v1ToolTitle(name: string, input: JsonRecord, ctx: ToolContext): string {
switch (name) {
@@ -341,7 +348,11 @@ export function v1ToolPart(
if (status === "streaming" || status === "pending") {
return { ...base, state: { status: "pending", input, raw: typeof state.input === "string" ? state.input : JSON.stringify(state.input ?? {}) } };
}
- const { __title: pluginTitle, ...metadata } = record(state, "metadata") ?? {};
+ const { __title: pluginTitle, ...stored } = record(state, "metadata") ?? {};
+ // The engine's read of a running sub-agent call leaves out its child session (only the
+ // call's progress events name it): the child the progress named, so the card can open it.
+ const child = name === "subagent" && typeof stored.sessionID !== "string" ? ctx.childSessionOf?.(callID) : undefined;
+ const metadata: JsonRecord = child ? { ...stored, sessionID: child } : stored;
const title = (fallback: string) => (typeof pluginTitle === "string" && pluginTitle ? pluginTitle : fallback);
if (status === "running") {
const runningTitle = title(v1ToolTitle(name, rawInput, ctx));
@@ -460,6 +471,11 @@ export type MessageContext = {
model?: { providerID: string; modelID: string; variant?: string };
/** Whether the session is a sub-agent's (its first user message then has the 2.x task preamble). */
child?: boolean;
+ /**
+ * The child session of one of this session's sub-agent calls, as its progress events named it
+ * (EventTranslator.childSessionOf): a read of a running call does not carry it.
+ */
+ childSessionOf?: (callID: string) => string | undefined;
};
type ModelRef = { providerID: string; modelID: string; variant?: string };
@@ -483,7 +499,7 @@ export function v1AssistantMessage(message: JsonRecord, ctx: MessageContext, par
const model = modelRef(message.model) ?? ctx.model;
const agent = str(message, "agent") ?? ctx.agent ?? "build";
const ids = { messageID: id, sessionID: ctx.sessionID };
- const toolCtx: ToolContext = { sessionID: ctx.sessionID, directory: ctx.directory, root: ctx.root, parentModel: model };
+ const toolCtx: ToolContext = { sessionID: ctx.sessionID, directory: ctx.directory, root: ctx.root, parentModel: model, childSessionOf: ctx.childSessionOf };
const tokens = v1Tokens(message.tokens);
const cost = num(message, "cost") ?? 0;
const finish = str(message, "finish");