Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Take subagent counts from the server rollup for every row (#2527)

Joshua Francea12097f1b73f
diff --git a/plugins/web-ui/src/conversations.ts b/plugins/web-ui/src/conversations.ts
index 6412ae5f1..327bf131f 100644
--- a/plugins/web-ui/src/conversations.ts
+++ b/plugins/web-ui/src/conversations.ts
@@ -102,8 +102,8 @@ export function ensureDeliveryStream(): void {
if (matched) {
sessionsState.list = list;
renderList();
- if (event.state === "idle") void refreshSessions({ silent: true });
const parentId = list.find((session) => session.threadRef === event.threadRef)?.parentSessionId;
+ if (event.state === "idle" || parentId) void refreshSessions({ silent: true });
if (parentId) for (const conv of live) if (conv.state.sessionId === parentId) conv.redraw();
} else {
void refreshSessions({ silent: true });
diff --git a/plugins/web-ui/src/session-list.ts b/plugins/web-ui/src/session-list.ts
index f116e4687..7378da78a 100644
--- a/plugins/web-ui/src/session-list.ts
+++ b/plugins/web-ui/src/session-list.ts
@@ -5,7 +5,7 @@ import {
type CoreSession,
type SessionBackgroundView,
} from "./core-bridge.ts";
-import { descendantsOf, subagentCounts } from "./subagent-activity.ts";
+import { descendantsOf } from "./subagent-activity.ts";
import { goalFloorLabel, goalWorkedLabel } from "./goal-strip.ts";
import { relTime } from "./ui.ts";
@@ -275,13 +275,9 @@ export function watchActivityLabel(w: { lastFiredAt?: number }): string {
return w.lastFiredAt ? `still watching · last check ${relTime(w.lastFiredAt)}` : "still watching";
}
-export function rowIndicators(
- s: CoreSession,
- liveThreads: ReadonlySet<string> | string | null,
- list: readonly CoreSession[] = [],
-): RowIndicators {
+export function rowIndicators(s: CoreSession, liveThreads: ReadonlySet<string> | string | null): RowIndicators {
const live = typeof liveThreads === "string" ? new Set([liveThreads]) : (liveThreads ?? new Set<string>());
- const children = !s.subagents || descendantsOf(list, s.id).length ? subagentCounts(list, s.id) : s.subagents;
+ const children = s.subagents ?? { running: 0, waiting: 0 };
return {
working: Boolean(s.working) || (Boolean(s.threadRef) && live.has(s.threadRef)),
awaiting: Boolean(s.awaitingInput) || children.waiting > 0,
@@ -302,7 +298,7 @@ export function conversationBackground(
threadRef: string | null,
): RowIndicators["background"] {
const row = list.find((s) => (sessionId ? s.id === sessionId : Boolean(threadRef) && s.threadRef === threadRef));
- return row ? rowIndicators(row, null, list).background : null;
+ return row ? rowIndicators(row, null).background : null;
}
export function shouldStartProactiveOpener(state: {
diff --git a/plugins/web-ui/src/sessions.ts b/plugins/web-ui/src/sessions.ts
index 83d422615..29cbf7348 100644
--- a/plugins/web-ui/src/sessions.ts
+++ b/plugins/web-ui/src/sessions.ts
@@ -769,7 +769,7 @@ function sessionWorking(s: CoreSession): boolean {
}
function statusMarks(s: CoreSession): TemplateResult {
- const ind = rowIndicators(s, liveThreads(), sessionsState.list);
+ const ind = rowIndicators(s, liveThreads());
return html`${ind.working ? html`<span class="working-mark" ${ref(syncWorkingPulse)}>${workingWave()}</span>` : nothing}${
ind.awaiting ? html`<span class="awaiting-dot" aria-label="Waiting for your reply"></span>` : nothing
}${
@@ -1796,13 +1796,15 @@ async function runSessionsRefresh(
try {
const surface = sessionsState.webOnly ? "web" : undefined;
const roots = [...new Set(openConversationIds())];
- const [page, children] = await Promise.all([
+ const nested = roots.filter((id) => sessionsState.list.some((row) => row.id === id && row.parentSessionId));
+ const [page, children, nestedRows] = await Promise.all([
fetchSessionPage({ limit: SESSION_BATCH_SIZE, ...(surface ? { surface } : {}) }),
Promise.all(
roots.map(
async (id) => [id, await fetchSessionChildren(id).catch(swallowAs("web-ui: load subagents", null))] as const,
),
),
+ Promise.all(nested.map((id) => fetchSessionRow({ id }).catch(swallowAs("web-ui: refresh subagent", null)))),
]);
if (seq !== sessionRefreshSeq) return sessionsState.loaded || ((await newerRun()) ?? false);
if (patchEpoch !== sessionPatchEpoch) {
@@ -1821,6 +1823,10 @@ async function runSessionsRefresh(
openConversationIds(),
);
for (const [id, rows] of children) if (rows) list = mergeChildren(list, id, rows);
+ list = upsertSessions(
+ list,
+ nestedRows.filter((row) => row !== null),
+ );
sessionsState.list = list;
sessionsState.hasArchived = Boolean(page.hasArchived);
if (!activePaged) activeCursor = page.nextCursor;
diff --git a/plugins/web-ui/src/split.ts b/plugins/web-ui/src/split.ts
index 9077a4544..8daf0014f 100644
--- a/plugins/web-ui/src/split.ts
+++ b/plugins/web-ui/src/split.ts
@@ -920,7 +920,7 @@ function paneIsWorking(panel: IDockviewPanel): boolean {
function paneAwaitsInput(panel: IDockviewPanel): boolean {
const session = paneSession(panel);
- return session ? rowIndicators(session, null, sessionsState.list).awaiting : false;
+ return session ? rowIndicators(session, null).awaiting : false;
}
function paneBackground(panel: IDockviewPanel): RowIndicators["background"] {
diff --git a/plugins/web-ui/src/subagent-activity.ts b/plugins/web-ui/src/subagent-activity.ts
index 9e6277f92..13ca52ce0 100644
--- a/plugins/web-ui/src/subagent-activity.ts
+++ b/plugins/web-ui/src/subagent-activity.ts
@@ -50,19 +50,6 @@ export function descendantsOf<T extends SessionLink>(
return out;
}
-export function subagentCounts(
- list: readonly SessionLink[],
- rootId: string | null | undefined,
-): { running: number; waiting: number } {
- const counts = { running: 0, waiting: 0 };
- if (!rootId) return counts;
- for (const { session } of descendantsOf(list, rootId)) {
- if (session.awaitingInput) counts.waiting++;
- else if (session.working) counts.running++;
- }
- return counts;
-}
-
export function subagentRows(list: readonly CoreSession[], rootId: string): SubagentRow[] {
return descendantsOf(list, rootId).map(({ session, depth }) => {
let state: SubagentState = "done";
diff --git a/plugins/web-ui/test/session-list.test.ts b/plugins/web-ui/test/session-list.test.ts
index 9cfee801d..172453cdd 100644
--- a/plugins/web-ui/test/session-list.test.ts
+++ b/plugins/web-ui/test/session-list.test.ts
@@ -185,13 +185,12 @@ test("children of a root are replaced by what the server returns", () => {
assert.deepEqual(next.map((s) => s.id).sort(), ["b", "other", "root"]);
});
-test("a row uses the server's subagent counts until its children are loaded", () => {
+test("a row's subagent indicators come from the server's counts, whatever children are cached", () => {
const row = at("root", "web:u:root", 9, { subagents: { running: 2, waiting: 1 } });
- assert.equal(rowIndicators(row, null, [row]).awaiting, true);
- assert.equal(rowIndicators(row, null, [row]).background?.subagents, 3);
- const loaded = [row, at("c", "subagent:root:c", 1, { parentSessionId: "root", working: true })];
- assert.equal(rowIndicators(row, null, loaded).awaiting, false, "loaded children are fresher than the rollup");
- assert.equal(rowIndicators(row, null, loaded).background?.subagents, 1);
+ const cached = [row, at("c", "subagent:root:c", 1, { parentSessionId: "root" })];
+ assert.equal(rowIndicators(row, null).awaiting, true);
+ assert.equal(conversationBackground(cached, "root", null)?.subagents, 3);
+ assert.equal(rowIndicators(at("idle", "web:u:idle", 9), null).background, null);
});
test("upsertSessions replaces rows by id and keeps the rest", () => {
diff --git a/plugins/web-ui/test/subagent-activity.test.ts b/plugins/web-ui/test/subagent-activity.test.ts
index 1f1dc02c4..2a0cf4b69 100644
--- a/plugins/web-ui/test/subagent-activity.test.ts
+++ b/plugins/web-ui/test/subagent-activity.test.ts
@@ -5,7 +5,6 @@ import {
ackKey,
descendantsOf,
peekLines,
- subagentCounts,
subagentRows,
subagentSummary,
visibleSubagents,
@@ -57,16 +56,18 @@ test("descendants keep list order across parents and follow a replaced list", ()
["p", "q", "q1", "p1"],
);
const before = [row("root"), row("a", "root")];
- assert.deepEqual(subagentCounts(before, "root"), { running: 0, waiting: 0 });
const after = [...before, row("b", "root", { working: true })];
- assert.deepEqual(subagentCounts(after, "root"), { running: 1, waiting: 0 }, "a new list array sees its new children");
+ assert.deepEqual(
+ descendantsOf(after, "root").map(({ session }) => session.id),
+ ["a", "b"],
+ "a new list array sees its new children",
+ );
});
-test("running and waiting counts feed the sidebar and tab badge", () => {
- assert.deepEqual(subagentCounts(list, "root"), { running: 2, waiting: 1 });
- assert.deepEqual(subagentCounts(list, "other"), { running: 0, waiting: 0 });
- assert.equal(rowIndicators(list[0]!, null, list).awaiting, true, "a child waiting on approval lights the parent");
- assert.deepEqual(conversationBackground(list, "root", null), {
+test("the server's running and waiting counts feed the sidebar and tab badge", () => {
+ const rolled = list.map((s) => (s.id === "root" ? { ...s, subagents: { running: 2, waiting: 1 } } : s));
+ assert.equal(rowIndicators(rolled[0]!, null).awaiting, true, "a child waiting on approval lights the parent");
+ assert.deepEqual(conversationBackground(rolled, "root", null), {
jobs: 0,
watches: 0,
crons: 0,
diff --git a/src/api/app-sessions.ts b/src/api/app-sessions.ts
index dedf2842c..9d0baac73 100644
--- a/src/api/app-sessions.ts
+++ b/src/api/app-sessions.ts
@@ -255,7 +255,7 @@ export function createSessionMethods(
async function decorateSessions(principalId: string, all: Session[]): Promise<Session[]> {
const visibleById = new Map(all.map((session) => [session.id, session]));
- const roots = all.filter((session) => !session.parentSessionId).map((session) => session.id);
+ const roots = all.map((session) => session.id);
const descendants = roots.length ? await deps.sessions.descendantsOf(roots) : [];
const descendantIds = new Set(descendants.map((d) => d.id));
const approvalRows: PendingApprovalRecord[] = [];
diff --git a/src/sessions/memory-session-store.ts b/src/sessions/memory-session-store.ts
index 7c1306f3c..72e7c5871 100644
--- a/src/sessions/memory-session-store.ts
+++ b/src/sessions/memory-session-store.ts
@@ -567,21 +567,22 @@ export function createMemorySessionStore(opts: StoreOptions = {}): SessionStore
},
async descendantsOf(rootIds): Promise<SessionDescendant[]> {
- const out: SessionDescendant[] = [];
- const seen = new Set(rootIds);
- let frontier = rootIds.map((id) => ({ id, rootId: id }));
- while (frontier.length) {
- const next: { id: string; rootId: string }[] = [];
- for (const s of sessions.values()) {
- const parent = frontier.find((f) => f.id === s.parentSessionId);
- if (!parent || seen.has(s.id)) continue;
- seen.add(s.id);
- out.push({ id: s.id, rootId: parent.rootId, threadRef: s.threadRef });
- next.push({ id: s.id, rootId: parent.rootId });
+ return [...new Set(rootIds)].flatMap((rootId) => {
+ const out: SessionDescendant[] = [];
+ const seen = new Set([rootId]);
+ let frontier = [rootId];
+ while (frontier.length) {
+ const next: string[] = [];
+ for (const s of sessions.values()) {
+ if (!s.parentSessionId || !frontier.includes(s.parentSessionId) || seen.has(s.id)) continue;
+ seen.add(s.id);
+ out.push({ id: s.id, rootId, threadRef: s.threadRef });
+ next.push(s.id);
+ }
+ frontier = next;
}
- frontier = next;
- }
- return out;
+ return out;
+ });
},
async listDescendantsForParticipant(rootId, principalId, limit) {
diff --git a/test/session-list-paging.test.ts b/test/session-list-paging.test.ts
index 9f4900091..d735a3595 100644
--- a/test/session-list-paging.test.ts
+++ b/test/session-list-paging.test.ts
@@ -118,6 +118,13 @@ test("a parent row counts its running subagents and its children load on demand"
const children = (await get(`/v1/sessions/${parent.id}/children?principalId=U1`)).body as { sessions: Session[] };
assert.deepEqual(children.sessions.map((s) => s.id).sort(), [child.id, grandchild.id].sort());
assert.equal(children.sessions.find((s) => s.id === grandchild.id)?.working, true);
+ assert.deepEqual(
+ children.sessions.find((s) => s.id === child.id)?.subagents,
+ { running: 1, waiting: 0 },
+ "a subagent row counts its own subagents",
+ );
+ const childRow = (await get(`/v1/sessions/row?id=${child.id}&principalId=U1`)).body as { session: Session };
+ assert.deepEqual(childRow.session.subagents, { running: 1, waiting: 0 });
assert.equal((await get(`/v1/sessions/${parent.id}/children?principalId=U2`)).status, 404);
});
});