Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

fix: list helper ids early

ogsamrat384fe42a73f8
diff --git a/apps/server/src/session-upload-observer.test.ts b/apps/server/src/session-upload-observer.test.ts
index 9c38d8eb..16fa5219 100644
--- a/apps/server/src/session-upload-observer.test.ts
+++ b/apps/server/src/session-upload-observer.test.ts
@@ -78,6 +78,9 @@ function startEngine() {
authorizations: [] as string[],
/** Runs once a page of messages was read. */
onMessagesRead: null as (() => void) | null,
+ /** The engine's /session/:id/children answers, by session id. */
+ children: {} as Record<string, Array<{ id: string }>>,
+ childrenReads: 0,
};
const server = Bun.serve({
hostname: "127.0.0.1",
@@ -97,7 +100,12 @@ function startEngine() {
control.onMessagesRead?.();
return page;
}
- if (url.pathname === `/session/${SESSION}/children`) return Response.json([]);
+ const childrenOf = /^\/session\/([^/]+)\/children$/.exec(url.pathname);
+ if (childrenOf) {
+ control.childrenReads += 1;
+ const id = decodeURIComponent(childrenOf[1]!);
+ return id === SESSION || id in control.children ? Response.json(control.children[id] ?? []) : Response.json({ code: "not_found" }, { status: 404 });
+ }
if (url.pathname === `/session/${SESSION}`) return Response.json({ id: SESSION });
return Response.json({ code: "not_found" }, { status: 404 });
},
@@ -174,6 +182,14 @@ class FakeUploader implements ObservedUploader {
recordChildSession(_sessionId: string, _child: UploadChildSession): void {}
+ /** Every batch of ids noted while a turn ran. */
+ readonly notedChildIds: string[][] = [];
+
+ noteChildSessionIds(_sessionId: string, ids: readonly string[]): number {
+ this.notedChildIds.push([...ids]);
+ return ids.length;
+ }
+
captureSnapshot(_sessionId: string, trigger: "prompt" | "turn_completed", outcome?: "aborted"): void {
this.entries.push({ kind: "snapshot", trigger, ...(outcome ? { outcome } : {}) });
}
@@ -308,6 +324,30 @@ describe("session upload observer", () => {
expect(engine.control.statusReads).toBeLessThan(1_300);
});
+ test("the sub-agents below a running turn are listed about once a minute, ids only, before the turn settles", async () => {
+ const clock = fakeClock();
+ const engine = startEngine();
+ const sessionUploader = new FakeUploader();
+ engine.control.messages = [message("msg_user_0001", "user", "Split the work")];
+ engine.control.status = () => (clock.elapsed() < 5 * 60_000 ? "busy" : "idle");
+ clock.at(90_000, () => {
+ engine.control.children[SESSION] = [{ id: "ses_child_1" }, { id: "ses_child_2" }];
+ engine.control.children.ses_child_1 = [{ id: "ses_grand_1" }];
+ engine.control.children.ses_grand_1 = [{ id: "ses_great_1" }];
+ engine.control.children.ses_great_1 = [{ id: "ses_too_deep" }];
+ });
+ clock.at(5 * 60_000, () => engine.control.messages.push(message("msg_assistant_0001", "assistant", "Done")));
+
+ await observe({ sessionUploader, archive: fakeArchive(), observers: createSessionObservers(), target: engine.target, timing: clock.timing });
+
+ // About one listing a minute while busy (the first finds none yet), three layers down.
+ expect(sessionUploader.notedChildIds.length).toBeGreaterThanOrEqual(3);
+ expect(sessionUploader.notedChildIds.length).toBeLessThanOrEqual(5);
+ expect(sessionUploader.notedChildIds[0]).toEqual([]);
+ expect(sessionUploader.notedChildIds.at(-1)).toEqual(["ses_child_1", "ses_child_2", "ses_grand_1", "ses_great_1"]);
+ expect(sessionUploader.labels()).toEqual(["session.idle", "snapshot:turn_completed", "flush:turn"]);
+ });
+
test("a turn stopped with Esc is recorded as aborted: session.idle outcome, the snapshot's outcome and turn.completed's", 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 78301ca2..d757bcda 100644
--- a/apps/server/src/session-upload-observer.ts
+++ b/apps/server/src/session-upload-observer.ts
@@ -136,6 +136,7 @@ export type ObservedUploader = Pick<
| "childCheckpoints"
| "childSessionIds"
| "recordChildSession"
+ | "noteChildSessionIds"
| "captureSnapshot"
| "flushTrace"
>;
@@ -224,6 +225,8 @@ const ENGINE_UNAVAILABLE_TRACE_MS = 60_000;
const NEVER_BUSY_SETTLE_MS = 10 * 60_000;
/** A turn ended by the next prompt waits at most this long for that prompt's message to show up in the engine before it settles as it is. */
const CUT_PROMPT_WAIT_MS = 15_000;
+/** While a turn runs, the subagent sessions below it are listed (ids only) about this often. */
+const CHILD_IDS_INTERVAL_MS = 60_000;
/** A settled turn whose messages the engine did not answer for (a timeout, a dropped connection) is read again after these waits. */
const HISTORY_RETRY_DELAYS_MS = [2_000, 5_000];
@@ -324,6 +327,34 @@ async function captureChildSessions(input: {
}
}
+/**
+ * The ids of the subagent sessions below `rootSessionId`, children first,
+ * 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[]> {
+ 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;
+ 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;
+ seen.add(id);
+ ids.push(id);
+ next.push(id);
+ }
+ }
+ layer = next;
+ }
+ return ids;
+}
+
function sum(values: readonly number[]): number {
return values.reduce((total, value) => total + value, 0);
}
@@ -954,6 +985,8 @@ export function observeUploadedSession(input: {
let readTarget = session.target;
// When the observer first saw that the next prompt ended this turn.
let cutSeenAt: number | null = null;
+ // When the subagent sessions below were last listed.
+ let childIdsAt = startedAt;
while (timing.now() - startedAt < timing.maxTurnMs) {
// An engine that took over from a closed one is read at once, without the closed one's backoff.
if (session.target !== readTarget) {
@@ -1012,6 +1045,15 @@ export function observeUploadedSession(input: {
if (status !== "idle") {
observedBusy = true;
idleReads = 0;
+ // The v2 daemon has no children route: nothing to list there.
+ if (!v2 && timing.now() - childIdsAt >= CHILD_IDS_INTERVAL_MS) {
+ childIdsAt = timing.now();
+ try {
+ sessionUploader.noteChildSessionIds(sessionId, await childSessionIdsBelow(fetchEngine, sessionId));
+ } catch (error) {
+ if (stopped.aborted) throw error;
+ }
+ }
continue;
}
if (idleReads === 0) {
diff --git a/apps/server/src/session-uploader.test.ts b/apps/server/src/session-uploader.test.ts
index 68210074..cf7383b0 100644
--- a/apps/server/src/session-uploader.test.ts
+++ b/apps/server/src/session-uploader.test.ts
@@ -1545,6 +1545,39 @@ describe("session uploader trace additions", () => {
await second.stop();
});
+ test("child ids noted while the turn runs are listed at once, deduped, and kept across a restart without a transcript event", async () => {
+ const root = await mkdtemp(join(tmpdir(), "omnirush-upload-child-ids-"));
+ const stateDir = await mkdtemp(join(tmpdir(), "omnirush-upload-child-ids-state-"));
+ roots.push(root, stateDir);
+ await writeFile(join(root, "app.txt"), "hello\n");
+ const { uploads, upload } = makeUploads();
+ const makeUploader = () => new SessionUploader({ stateDir, upload, fallbackScanMs: 60_000 });
+ const sessionId = "session-child-ids-1234";
+
+ const first = makeUploader();
+ first.startSession(sessionId, "workspace-child-ids", root);
+ await first.idle(sessionId);
+ expect(first.noteChildSessionIds(sessionId, ["ses_child_1", "ses_grandchild_1"])).toBe(2);
+ expect(first.noteChildSessionIds(sessionId, ["ses_child_1", sessionId, "bad id!", "ses_child_2"])).toBe(1);
+ expect(first.noteChildSessionIds("session-unknown", ["ses_child_9"])).toBe(0);
+ expect(await first.childSessionIds(sessionId)).toEqual(["ses_child_1", "ses_grandchild_1", "ses_child_2"]);
+ // The next envelope (here a trace flush) lists them.
+ first.recordTrace(sessionId, "session.idle", { status: "busy" });
+ first.flushTrace(sessionId);
+ await first.idle(sessionId);
+ expect(uploads.at(-1)!.session).toMatchObject({ child_session_ids: ["ses_child_1", "ses_grandchild_1", "ses_child_2"] });
+ // Ids only: the transcripts still come when the turn settles.
+ expect(traceEvents(uploads).filter((event) => event.type === "session.child")).toEqual([]);
+ // The app quits before the turn settles: the next start still lists them.
+ await first.stop();
+ const second = makeUploader();
+ second.startSession(sessionId, "workspace-child-ids", root);
+ await second.idle(sessionId);
+ const resumedStart = uploads.find((item) => item.snapshot_type === "start" && item.session_segment === 2)!;
+ expect(resumedStart.session).toMatchObject({ child_session_ids: ["ses_child_1", "ses_grandchild_1", "ses_child_2"] });
+ await second.stop();
+ });
+
test("sub-agents on their own models keep them; a gateway fallback records the model that really answered", async () => {
const root = await mkdtemp(join(tmpdir(), "omnirush-upload-subagent-model-"));
roots.push(root);
diff --git a/apps/server/src/session-uploader.ts b/apps/server/src/session-uploader.ts
index e05b62f3..a341b628 100644
--- a/apps/server/src/session-uploader.ts
+++ b/apps/server/src/session-uploader.ts
@@ -5090,6 +5090,26 @@ export class SessionUploader {
return [...state.childSessionIds];
}
+ /**
+ * Notes the subagent session ids seen below this root session while its
+ * turn still runs: ids only (their messages still come when the turn
+ * settles), kept in the ledger so the next envelope lists them even when
+ * the app quits before the turn settles. Returns how many were new.
+ */
+ noteChildSessionIds(sessionId: string, ids: readonly string[]): number {
+ const state = this.sessions.get(sessionId);
+ if (!state || state.finished) return 0;
+ let added = 0;
+ for (const id of ids) {
+ if (id === sessionId || !/^[A-Za-z0-9._:-]{1,256}$/.test(id) || state.childSessionIds.includes(id)) continue;
+ if (state.childSessionIds.length >= MAX_CHILD_SESSIONS) break;
+ state.childSessionIds.push(id);
+ added += 1;
+ }
+ if (added > 0) void this.persistOnceReady(state);
+ return added;
+ }
+
/**
* Records a task-tool subagent session (child, grandchild, ...) captured
* once the root turn settled: one "session.child" event carrying the child's