Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

fix: new engine chats keep sub-agents and compactions

ogsamrat2c6aa6285e74
diff --git a/apps/server/src/auto-compact-engine.test.ts b/apps/server/src/auto-compact-engine.test.ts
index 495d5ffd..a87b30fb 100644
--- a/apps/server/src/auto-compact-engine.test.ts
+++ b/apps/server/src/auto-compact-engine.test.ts
@@ -7,7 +7,7 @@ import { AutoCompactor } from "./session-archive/auto-compact.js";
const MODEL = { id: "gpt-6-astra", providerID: "omnirush" };
-/** A 2.x engine for one chat: its stored messages (GET /api/session/:id/context) and the compact call. */
+/** A 2.x engine for one chat: its stored messages (GET /api/session/:id/message, newest first) and the compact call. */
function v2Engine() {
const stored: Record<string, unknown>[] = [{ id: "msg_switch", type: "model-switched", time: { created: 1 }, model: MODEL }];
const compacts: string[] = [];
@@ -34,6 +34,7 @@ function v2Engine() {
return Response.json({ data: { id } });
}
if (path.endsWith("/message") && url.searchParams.get("type") === "compaction") return Response.json({ data: stored.filter((item) => item.type === "compaction").reverse() });
+ if (path.endsWith("/message") && !url.searchParams.has("type")) return Response.json({ data: [...stored].reverse(), cursor: {} });
if (/\/api\/session\/ses_v2$/.test(path)) return Response.json({ data: { id: "ses_v2", model: MODEL } });
throw new Error(`unexpected ${init.method ?? "GET"} ${path}`);
};
diff --git a/apps/server/src/session-archive/lifecycle.ts b/apps/server/src/session-archive/lifecycle.ts
index 959a181c..fbb44bfa 100644
--- a/apps/server/src/session-archive/lifecycle.ts
+++ b/apps/server/src/session-archive/lifecycle.ts
@@ -29,7 +29,7 @@ export type ProjectArchiver = Pick<
export type ArchiveEngineReads = {
/** The session record (v1 `/session/:id`, v2 `/api/session/:id`). */
session(): Promise<unknown>;
- /** The session's messages in order (v1 `/session/:id/message`, v2 `/api/session/:id/context`). */
+ /** The session's messages in order (v1 `/session/:id/message`, v2 `/api/session/:id/message`). */
messages(): Promise<unknown>;
};
diff --git a/apps/server/src/session-upload-observer-v2.test.ts b/apps/server/src/session-upload-observer-v2.test.ts
new file mode 100644
index 00000000..3d74c65d
--- /dev/null
+++ b/apps/server/src/session-upload-observer-v2.test.ts
@@ -0,0 +1,154 @@
+import { afterEach, describe, expect, test } from "bun:test";
+
+import {
+ createSessionObservers,
+ observeUploadedSession,
+ type EngineTarget,
+ type ObservedUploader,
+ type ObserverTiming,
+} from "./session-upload-observer.js";
+import type { UploadChildSession } from "./session-uploader.js";
+
+/**
+ * The turn observer against a fake 2.x engine: a chat's stored messages come
+ * from GET /api/session/:id/message (newest first, cursor pages), never from
+ * /context, which starts at the last compaction; its sub-agents are listed by
+ * GET /api/session?parentID= and their own messages captured.
+ */
+
+const SESSION = "ses_v2_observed_01";
+const CHILD = "ses_v2_child_0001";
+
+const cleanups: Array<() => void | Promise<void>> = [];
+afterEach(async () => {
+ while (cleanups.length) await cleanups.pop()?.();
+});
+
+type V2Message = Record<string, unknown> & { id: string };
+
+const user = (id: string, text: string): V2Message => ({ id, type: "user", text, time: { created: 1 } });
+const answer = (id: string, content: unknown[] = [{ type: "text", text: `answer ${id}` }]): V2Message => ({
+ id, type: "assistant", agent: "build", model: { id: "gpt-6-astra", providerID: "omnirush" }, content, finish: "stop", time: { created: 1, completed: 2 },
+});
+
+/** A fake 2.x engine: stored messages by session, children by parent; `/context` answers only what follows the last compaction. */
+function startV2Engine() {
+ const control = {
+ messages: {} as Record<string, V2Message[]>,
+ children: {} as Record<string, Array<{ id: string }>>,
+ contextReads: 0,
+ pageSize: 2,
+ };
+ const server = Bun.serve({
+ hostname: "127.0.0.1",
+ port: 0,
+ fetch(request) {
+ const url = new URL(request.url);
+ if (url.pathname === "/api/session/active") return Response.json({ data: {} });
+ if (url.pathname === "/api/session" && url.searchParams.has("parentID")) {
+ return Response.json({ data: control.children[url.searchParams.get("parentID")!] ?? [], cursor: {} });
+ }
+ const route = /^\/api\/session\/([^/]+)(\/message|\/context)?$/.exec(url.pathname);
+ const id = route ? decodeURIComponent(route[1]!) : null;
+ if (!id || !(id in control.messages)) return Response.json({ code: "not_found" }, { status: 404 });
+ const stored = control.messages[id]!;
+ if (route![2] === "/context") {
+ control.contextReads += 1;
+ const cut = stored.map((message) => message.type).lastIndexOf("compaction");
+ return Response.json({ data: cut < 0 ? stored : stored.slice(cut + 1) });
+ }
+ if (route![2] === "/message") {
+ // Newest first, `pageSize` at a time; the cursor is the index the next page starts at.
+ const newestFirst = [...stored].reverse();
+ const start = url.searchParams.has("cursor") ? Number(url.searchParams.get("cursor")) : 0;
+ const page = newestFirst.slice(start, start + control.pageSize);
+ const next = start + control.pageSize < newestFirst.length ? String(start + control.pageSize) : undefined;
+ return Response.json({ data: page, cursor: next ? { next } : {} });
+ }
+ return Response.json({ data: { id } });
+ },
+ });
+ cleanups.push(() => server.stop(true));
+ const target: EngineTarget = { baseUrl: `http://127.0.0.1:${server.port}`, headers: [["authorization", "Basic ZW5naW5l"]], search: "?directory=%2Ftmp%2Fproject", engine: "v2" };
+ return { control, target };
+}
+
+const timing: Partial<ObserverTiming> = {
+ now: () => Date.parse("2026-10-26T00:00:00.000Z"),
+ sleep: async () => undefined,
+ progressMs: 0,
+};
+
+/** What the observer hands the uploader: each turn's messages, the sub-agent sessions and the ids noted. */
+class FakeUploader implements ObservedUploader {
+ readonly enabled = true;
+ checkpoint: string | undefined;
+ readonly turns: unknown[][] = [];
+ readonly children: UploadChildSession[] = [];
+
+ async sessionCheckpoint(): Promise<{ resumed: boolean; lastMessageId?: string }> {
+ return { resumed: false, ...(this.checkpoint ? { lastMessageId: this.checkpoint } : {}) };
+ }
+ async setSessionCheckpoint(_sessionId: string, messageId: string): Promise<void> {
+ this.checkpoint = messageId;
+ }
+ recordTrace(): void {}
+ recordSessionModel(): void {}
+ async childCheckpoints(): Promise<Record<string, string>> {
+ return {};
+ }
+ async childSessionIds(): Promise<string[]> {
+ return [];
+ }
+ recordChildSession(_sessionId: string, child: UploadChildSession): void {
+ this.children.push(child);
+ }
+ noteChildSessionIds(_sessionId: string, ids: readonly string[]): number {
+ return ids.length;
+ }
+ captureSnapshot(): void {}
+ flushTrace(_sessionId: string, finalTrace?: unknown): void {
+ const messages = (finalTrace as { messages?: unknown[] } | undefined)?.messages;
+ if (messages) this.turns.push(messages);
+ }
+}
+
+const archive = { turnFollowed: () => undefined, turnCompleted: () => undefined, turnIncomplete: () => undefined };
+const idsOf = (messages: readonly unknown[]) => messages.map((message) => String((message as { id?: unknown }).id));
+
+function observe(uploader: FakeUploader, target: EngineTarget) {
+ return observeUploadedSession({ sessionUploader: uploader, archive, observers: createSessionObservers(), target, timing, sessionId: SESSION, recovered: true });
+}
+
+describe("the 2.x engine's chats", () => {
+ test("a sub-agent's own session is listed by parentID and captured with its messages", async () => {
+ const { control, target } = startV2Engine();
+ const call = { type: "tool", id: "call_1", name: "subagent", state: { status: "completed", input: { prompt: "look" }, metadata: { sessionID: CHILD }, content: [{ type: "text", text: "found it" }] } };
+ control.messages[SESSION] = [user("msg_u1", "Split the work"), answer("msg_a1", [call]), answer("msg_a2")];
+ control.messages[CHILD] = [user("msg_cu1", "look"), answer("msg_ca1", [{ type: "text", text: "the child's own answer" }])];
+ control.children[SESSION] = [{ id: CHILD }];
+ const uploader = new FakeUploader();
+
+ await observe(uploader, target);
+
+ expect(uploader.children.map((child) => child.childSessionId)).toEqual([CHILD]);
+ expect(uploader.children[0]).toMatchObject({ parentSessionId: SESSION, depth: 1 });
+ expect(idsOf(uploader.children[0]!.messages)).toEqual(["msg_cu1", "msg_ca1"]);
+ });
+
+ test("a compaction does not cut the history: the turn after it reads on from its checkpoint, the compaction and its summary included", async () => {
+ const { control, target } = startV2Engine();
+ const compaction = { id: "msg_c1", type: "compaction", reason: "manual", status: "completed", summary: "## Goal\nthe summary", time: { created: 3, completed: 4 } };
+ control.messages[SESSION] = [user("msg_u1", "First"), answer("msg_a1"), compaction, user("msg_u2", "Second"), answer("msg_a2")];
+ const uploader = new FakeUploader();
+ uploader.checkpoint = "msg_a1";
+
+ await observe(uploader, target);
+
+ expect(control.contextReads).toBe(0);
+ expect(uploader.turns).toHaveLength(1);
+ expect(idsOf(uploader.turns[0]!)).toEqual(["msg_c1", "msg_u2", "msg_a2"]);
+ expect(uploader.turns[0]![0]).toMatchObject({ type: "compaction", summary: "## Goal\nthe summary" });
+ expect(uploader.checkpoint).toBe("msg_a2");
+ });
+});
diff --git a/apps/server/src/session-upload-observer.ts b/apps/server/src/session-upload-observer.ts
index 88b97189..919bb477 100644
--- a/apps/server/src/session-upload-observer.ts
+++ b/apps/server/src/session-upload-observer.ts
@@ -352,16 +352,17 @@ async function captureChildSessions(input: {
*/
progress?: TurnProgress | null;
ahead?: boolean;
+ /** A 2.x engine: children listed by parentID, their stored messages read whole (engineMessagesV2). */
+ v2?: boolean;
}): Promise<void> {
if (input.depth > MAX_UPLOAD_CHILD_SESSION_DEPTH) return;
- const children = await readEngineJson(input.fetchEngine, `/session/${encodeURIComponent(input.parentSessionId)}/children`, 1024 * 1024)
- .catch(nullOnErrorStatus);
- if (!Array.isArray(children)) return;
+ const children = await engineChildren(input.fetchEngine, input.parentSessionId, input.v2 === true);
+ if (!children) return;
for (const child of children.slice(0, 200)) {
const childId = isRecord(child) && typeof child.id === "string" && child.id ? child.id : null;
if (!childId || childId === input.rootSessionId || input.visited.has(childId)) continue;
input.visited.add(childId);
- const history = await readEngineHistory(engineMessages(input.fetchEngine, `/session/${encodeURIComponent(childId)}/message`, true), input.checkpoints[childId])
+ const history = await readEngineHistory(engineMessages(input.fetchEngine, messagesPathOf(childId, input.v2 === true), input.v2 ? "v2" : true), input.checkpoints[childId])
.catch(nullOnErrorStatus);
if (input.ahead) {
if (history && input.progress && history.omitted === 0 && !history.checkpointMissing) {
@@ -415,16 +416,15 @@ async function captureChildSessions(input: {
* at most MAX_UPLOAD_CHILD_SESSION_DEPTH layers down. A layer the engine
* cannot list (an error status) is left out.
*/
-async function childSessionIdsBelow(fetchEngine: EngineFetch, rootSessionId: string): Promise<string[]> {
+async function childSessionIdsBelow(fetchEngine: EngineFetch, rootSessionId: string, v2 = false): Promise<string[]> {
const ids: string[] = [];
const seen = new Set([rootSessionId]);
let layer = [rootSessionId];
for (let depth = 1; depth <= MAX_UPLOAD_CHILD_SESSION_DEPTH && layer.length > 0; depth += 1) {
const next: string[] = [];
for (const parent of layer) {
- const children = await readEngineJson(fetchEngine, `/session/${encodeURIComponent(parent)}/children`, 1024 * 1024)
- .catch(nullOnErrorStatus);
- if (!Array.isArray(children)) continue;
+ const children = await engineChildren(fetchEngine, parent, v2);
+ if (!children) continue;
for (const child of children.slice(0, 200)) {
const id = isRecord(child) && typeof child.id === "string" && child.id ? child.id : null;
if (!id || seen.has(id)) continue;
@@ -491,7 +491,9 @@ async function readObservedResponse(response: Response, maxBytes = MAX_ENGINE_RE
/** One engine read under the cap; an error status throws EngineReadError. */
async function readEngineJson(fetchEngine: EngineFetch, path: string, maxBytes?: number): Promise<unknown> {
- const response = await fetchEngine(path);
+ // A query in `path` (`/api/session?parentID=…`) goes with the target's own search.
+ const [route, query] = path.split("?");
+ const response = await fetchEngine(route!, query ? Object.fromEntries(new URLSearchParams(query)) : undefined);
if (!response.ok) {
await response.body?.cancel().catch(() => undefined);
throw new EngineReadError(response.status);
@@ -643,15 +645,57 @@ function rewritten(path: string, message: unknown): unknown {
}
}
+/**
+ * The 2.x engine's stored messages, newest first: `GET /api/session/:id/message`
+ * pages of at most 200 (`order=desc`, then `cursor`), every message as the
+ * engine stores it (compacted ones too, unlike /context, which starts at the
+ * last compaction). The CLI reads them the same way (collector-observer.ts).
+ */
+async function* engineMessagesV2(fetchEngine: EngineFetch, path: string): AsyncGenerator<EngineMessage> {
+ let cursor: string | null = null;
+ while (true) {
+ const response = await fetchEngine(path, cursor ? { cursor, limit: "200" } : { order: "desc", limit: "200" });
+ if (!response.ok) {
+ await response.body?.cancel().catch(() => undefined);
+ throw new EngineReadError(response.status);
+ }
+ const payload = await readObservedResponse(response, MAX_ENGINE_READ_BYTES);
+ const list = isRecord(payload) && Array.isArray(payload.data) ? payload.data : null;
+ if (!list) throw new Error("the engine messages could not be read");
+ for (const message of list) yield { message: slimEngineMessage(rewritten(path, message), null), whole: true };
+ const next = isRecord(payload) && isRecord(payload.cursor) && typeof payload.cursor.next === "string" ? payload.cursor.next : null;
+ if (!next || next === cursor || list.length === 0) return;
+ cursor = next;
+ }
+}
+
+/** A session's stored messages: v1 `/session/:id/message`, v2 `/api/session/:id/message`. */
+function messagesPathOf(sessionId: string, v2: boolean): string {
+ return `${v2 ? "/api/session" : "/session"}/${encodeURIComponent(sessionId)}/message`;
+}
+
+/** A session's sub-agent sessions: v1 `/session/:id/children`, v2 `GET /api/session?parentID=` (its `data`). */
+async function engineChildren(fetchEngine: EngineFetch, parentSessionId: string, v2: boolean): Promise<unknown[] | null> {
+ const listed = await readEngineJson(fetchEngine, v2 ? `/api/session?parentID=${encodeURIComponent(parentSessionId)}&limit=200` : `/session/${encodeURIComponent(parentSessionId)}/children`, 1024 * 1024)
+ .catch(nullOnErrorStatus);
+ const children = v2 && isRecord(listed) ? listed.data : listed;
+ return Array.isArray(children) ? children : null;
+}
+
/**
* A session's messages, newest first. A v1 engine is read a page at a
* time, each page parsed under the read cap: after a page over it, the
* newest message is asked for alone and later pages are at most half that
* size, and a message over the cap on its own is known by the info that
- * leads it. The v2 daemon has no pages; its list is read whole under the
- * cap. Throws when the engine cannot be read.
+ * leads it. A v2 engine is read in its cursor pages (engineMessagesV2);
+ * unpaged, a list is read whole under the cap. Throws when the engine
+ * cannot be read.
*/
-async function* engineMessages(fetchEngine: EngineFetch, path: string, paged: boolean): AsyncGenerator<EngineMessage> {
+async function* engineMessages(fetchEngine: EngineFetch, path: string, paged: boolean | "v2"): AsyncGenerator<EngineMessage> {
+ if (paged === "v2") {
+ yield* engineMessagesV2(fetchEngine, path);
+ return;
+ }
if (!paged) {
const payload = await readEngineJson(fetchEngine, path);
const list = isRecord(payload) && "data" in payload ? payload.data : payload;
@@ -911,9 +955,9 @@ type MessagePart = { messages: unknown[]; bytes: number };
export async function readSessionTranscript(target: EngineTarget, sessionId: string, signal: AbortSignal): Promise<unknown[][] | null> {
const fetchEngine = engineFetch(() => target, () => AbortSignal.any([signal, AbortSignal.timeout(20_000)]));
const v2 = target.engine === "v2";
- const path = v2 ? `/api/session/${encodeURIComponent(sessionId)}/context` : `/session/${encodeURIComponent(sessionId)}/message`;
+ const path = messagesPathOf(sessionId, v2);
try {
- const history = await readEngineHistory(engineMessages(fetchEngine, path, !v2), undefined, MAX_BACKLOG_MESSAGE_BYTES);
+ const history = await readEngineHistory(engineMessages(fetchEngine, path, v2 ? "v2" : true), undefined, MAX_BACKLOG_MESSAGE_BYTES);
// 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 {
@@ -988,7 +1032,7 @@ export function projectArchiveEngineReads(target: EngineTarget | (() => EngineTa
return v2 && isRecord(payload) && "data" in payload ? payload.data : payload;
},
// The same messages the observer counts turns from at turn end, in outline.
- messages: () => messageOutlines(engineMessages(fetchEngine, v2 ? `${session}/context` : `${session}/message`, !v2)),
+ messages: () => messageOutlines(engineMessages(fetchEngine, `${session}/message`, v2 ? "v2" : true)),
};
}
@@ -1065,8 +1109,8 @@ export function observeUploadedSession(input: {
const target = () => session.target;
const fetchStatus = engineFetch(target, () => AbortSignal.any([stopped, AbortSignal.timeout(timing.statusTimeoutMs)]));
const fetchEngine = engineFetch(target, () => AbortSignal.any([stopped, AbortSignal.timeout(timing.readTimeoutMs)]));
- const messagesPath = v2 ? `/api/session/${encodeURIComponent(sessionId)}/context` : `/session/${encodeURIComponent(sessionId)}/message`;
- const messages = () => engineMessages(fetchEngine, messagesPath, !v2);
+ const messagesPath = messagesPathOf(sessionId, v2);
+ const messages = () => engineMessages(fetchEngine, messagesPath, v2 ? "v2" : true);
const enginePayload = (payload: unknown) => (v2 && isRecord(payload) && "data" in payload ? payload.data : payload);
const falseUnlessStopped = (error: unknown): false => {
if (stopped.aborted) throw error;
@@ -1197,9 +1241,10 @@ export function observeUploadedSession(input: {
} catch (error) {
if (stopped.aborted) throw error;
}
- if (!v2) {
+ {
try {
await captureChildSessions({
+ v2,
onChild: (_childId, _depth, sent) => {
childMessages += sent.length;
},
@@ -1298,10 +1343,10 @@ export function observeUploadedSession(input: {
const children: WriterSessionMessages[] = [];
// Quitting (the engine closes with the app) or recovered: the sub-agents' calls end with it.
const childTools = { engineIdle: status === "quit" || recovered, closed: 0 };
- // The v2 daemon has no subagent children route; only its root turn is captured.
- if (!v2) {
+ {
try {
await captureChildSessions({
+ v2,
onChild: (childId, depth, childMessages) => children.push({ sessionId: childId, role: "child", depth, messages: childMessages }),
sessionUploader,
rootSessionId: sessionId,
@@ -1453,11 +1498,10 @@ export function observeUploadedSession(input: {
current.flushed(timing.now());
}
}
- // The v2 daemon has no children route: nothing to list there.
- if (!v2 && timing.now() - childIdsAt >= CHILD_IDS_INTERVAL_MS) {
+ if (timing.now() - childIdsAt >= CHILD_IDS_INTERVAL_MS) {
childIdsAt = timing.now();
try {
- sessionUploader.noteChildSessionIds(sessionId, await childSessionIdsBelow(fetchEngine, sessionId));
+ sessionUploader.noteChildSessionIds(sessionId, await childSessionIdsBelow(fetchEngine, sessionId, v2));
} catch (error) {
if (stopped.aborted) throw error;
}
diff --git a/apps/server/src/session-uploader.server.e2e.test.ts b/apps/server/src/session-uploader.server.e2e.test.ts
index 6786b886..46de0aba 100644
--- a/apps/server/src/session-uploader.server.e2e.test.ts
+++ b/apps/server/src/session-uploader.server.e2e.test.ts
@@ -287,7 +287,9 @@ function startMockV2Engine(input: { provider: string; model: string }) {
setTimeout(() => { busy = false; }, 50);
return Response.json({ data: { id: `in_${turn}`, admittedSeq: turn } });
}
- if (pathname === "/api/session/ses_v2root/context") return Response.json({ data: context });
+ // The stored messages, newest first (the observer reads them all; /context starts at the last compaction).
+ if (pathname === "/api/session/ses_v2root/message") return Response.json({ data: [...context].reverse(), cursor: {} });
+ if (pathname === "/api/session" && url.searchParams.get("parentID") === "ses_v2root") return Response.json({ data: [], cursor: {} });
if (pathname === "/api/session/ses_v2root" && request.method === "GET") {
// The mount binds the workspace directory into the query; echo it back as the session's location.
return Response.json({ data: { id: "ses_v2root", title: "Root task", location: { directory: url.searchParams.get("location[directory]") } } });
@@ -922,7 +924,8 @@ describe("collection gaps: the v2 mount and local workflow steps", () => {
expect(trace.session).toEqual({ provider_id: "anthropic", model_id: "claude-sonnet-4-5", variant: "high", child_session_ids: [] });
// The observer used the daemon's own routes, and the inline attachment never left the client.
expect(v2.received).toContain("GET /api/session/active");
- expect(v2.received).toContain("GET /api/session/ses_v2root/context");
+ expect(v2.received).toContain("GET /api/session/ses_v2root/message");
+ expect(v2.received).not.toContain("GET /api/session/ses_v2root/context");
expect(JSON.stringify(gateway.uploads)).not.toContain("sk-1234567890abcdefghijklmnop");
expect(JSON.stringify(gateway.uploads)).not.toContain(noteUri.slice(0, 60));
}, 60_000);