Multiplayer agent harness for work.
Show subagent activity in the parent session (#1710)
Joshua France484bb3872830
diff --git a/plugins/web-ui/server/index.ts b/plugins/web-ui/server/index.tsindex 3aef5f508..e0d54a1ca 100644--- a/plugins/web-ui/server/index.ts+++ b/plugins/web-ui/server/index.ts@@ -2409,7 +2409,8 @@ const apiRoutes: readonly WebRoute[] = [const threadRef =typeof record.request?.conversation?.threadRef === "string" ? record.request.conversation.threadRef : "";const actor = typeof record.request?.actor?.externalId === "string" ? record.request.actor.externalId : "";- if ((!threadRef.startsWith("web:") && !threadRef.startsWith("swarm:")) || actor !== user || !record.request) {+ const delegated = threadRef.startsWith("swarm:") || threadRef.startsWith(SUBAGENT_THREAD_PREFIX);+ if ((!threadRef.startsWith("web:") && !delegated) || actor !== user || !record.request) {return json(res, 404, { error: "not_found" });}if (/^web:.+:inbox$/.test(threadRef)) {@@ -2426,10 +2427,10 @@ const apiRoutes: readonly WebRoute[] = [): null;if (visible?.status !== 200) return json(res, 404, { error: "not_found" });- if (threadRef.startsWith("swarm:")) {+ if (delegated) {const session = (JSON.parse(visible.text) as { session?: { threadRef?: string; surface?: string } }).session;- if (session?.surface !== "swarm" || session.threadRef !== threadRef)- return json(res, 404, { error: "not_found" });+ const surfaceOk = threadRef.startsWith("swarm:") ? session?.surface === "swarm" : true;+ if (!surfaceOk || session?.threadRef !== threadRef) return json(res, 404, { error: "not_found" });}}diff --git a/plugins/web-ui/src/chat.ts b/plugins/web-ui/src/chat.tsindex 62b2ec6bc..64a34529a 100644--- a/plugins/web-ui/src/chat.ts+++ b/plugins/web-ui/src/chat.ts@@ -59,6 +59,7 @@ import {Rocket,ScrollText,SquareTerminal as Terminal,+ TriangleAlert,Wrench,X,type IconNode,@@ -155,6 +156,7 @@ import {relTime,sheenLabel,waveLoader,+ workingWave,} from "./ui";import { appState, renderSidebarTop, switchView, syncUrlFromState } from "./shell";import { contextsState, scopeTitle } from "./contexts";@@ -171,6 +173,7 @@ import {sessionSlackUrl,surfaceOf,openSession,+ syncWorkingPulse,} from "./sessions";import {backgroundLabel,@@ -183,6 +186,15 @@ import {} from "./session-list";import { liveTurnThreadRef } from "./working-dot";import { goalElapsedLabel, goalObjectiveLabel, latestGoal } from "./goal-strip";+import {+ ackKey,+ peekLines,+ subagentRows,+ subagentSummary,+ visibleSubagents,+ type PeekLine,+ type SubagentRow,+} from "./subagent-activity";import { newChatDraftKey, saveDraft, storedDraft } from "./drafts";import { createForkOriginController, forkOriginView } from "./fork-origin";import { base64ToBytes } from "./paste-text";@@ -1512,7 +1524,8 @@ export function createChatSurface(status: liveWorkStatus(agent),busy: agent.state.isStreaming,showPrompts: !messages.length,- toolbar: html`${goalStrip(agent)} ${ctx.composer.queuedStrip(agent)} ${backgroundActivityStrip()}`,+ toolbar: html`${goalStrip(agent)} ${ctx.composer.queuedStrip(agent)} ${subagentStrip()}+ ${backgroundActivityStrip()}`,composer: ctx.composer.composerForm(agent),onPrompt: (prompt) => ctx.composer.fillSuggestedPrompt(prompt, agent),onDragEnter: (event) => ctx.composer.onDragEnter(event),@@ -1557,7 +1570,7 @@ export function createChatSurface(</div></section><div class="chat-bottom-dock">- ${goalStrip(agent)} ${ctx.composer.queuedStrip(agent)} ${backgroundActivityStrip()}+ ${goalStrip(agent)} ${ctx.composer.queuedStrip(agent)} ${subagentStrip()} ${backgroundActivityStrip()}${ctx.composer.composerForm(agent)} ${ctx.pane ? nothing : suggestions}</div></div>@@ -2330,7 +2343,8 @@ export function createChatSurface(}function backgroundActivityStrip(): TemplateResult | typeof nothing {- const row = conversationBackground(sessionsState.list, chatState.sessionId, chatState.threadRef);+ const counts = conversationBackground(sessionsState.list, chatState.sessionId, chatState.threadRef);+ const row = counts ? backgroundLabel(counts.jobs, counts.watches, counts.crons) : null;const live =bgPanel.open && bgPanel.detail? backgroundLabel(bgPanel.detail.jobs.length, bgPanel.detail.watches.length, bgPanel.detail.crons.length)@@ -2428,6 +2442,194 @@ export function createChatSurface(`;}+ const SUBAGENT_ACK_KEY = "qm.subagentAck";+ const subagentUi = {+ expanded: false,+ peekId: null as string | null,+ peek: null as PeekLine[] | null,+ timer: null as ReturnType<typeof setInterval> | null,+ approvals: new Map<string, PendingApproval[]>(),+ approvalsKey: "",+ acknowledged: new Set<string>(+ (() => {+ try {+ return JSON.parse(localStorage.getItem(SUBAGENT_ACK_KEY) ?? "[]") as string[];+ } catch {+ return [];+ }+ })(),+ ),+ };++ function stopSubagentPeek(): void {+ if (subagentUi.timer) clearInterval(subagentUi.timer);+ subagentUi.timer = null;+ subagentUi.peekId = null;+ subagentUi.peek = null;+ }++ async function refreshSubagentPeek(id: string): Promise<void> {+ const page = await fetchTranscript(id, { tailTurns: 1 }).catch(() => null);+ if (subagentUi.peekId !== id) return;+ subagentUi.peek = page ? peekLines(page.entries) : [];+ drawActiveChat();+ }++ function toggleSubagentPeek(row: SubagentRow): void {+ const id = row.session.id;+ const same = subagentUi.peekId === id;+ stopSubagentPeek();+ if (same) return drawActiveChat();+ subagentUi.peekId = id;+ void refreshSubagentPeek(id);+ if (row.state === "working") subagentUi.timer = setInterval(() => void refreshSubagentPeek(id), 4000);+ drawActiveChat();+ }++ function acknowledgeSubagent(row: SubagentRow): void {+ subagentUi.acknowledged.add(ackKey(row));+ try {+ localStorage.setItem(SUBAGENT_ACK_KEY, JSON.stringify([...subagentUi.acknowledged].slice(-200)));+ } catch {+ return drawActiveChat();+ }+ if (subagentUi.peekId === row.session.id) stopSubagentPeek();+ drawActiveChat();+ }++ function syncSubagentApprovals(rows: readonly SubagentRow[]): void {+ const waiting = rows.filter((row) => row.state === "waiting").map((row) => row.session.id);+ const key = waiting.join(",");+ if (key === subagentUi.approvalsKey) return;+ subagentUi.approvalsKey = key;+ for (const id of subagentUi.approvals.keys()) if (!waiting.includes(id)) subagentUi.approvals.delete(id);+ for (const id of waiting)+ void fetchSessionApprovals(id).then((r) => {+ if (!subagentUi.approvalsKey.split(",").includes(id)) return;+ subagentUi.approvals.set(id, r?.approvals ?? []);+ drawActiveChat();+ });+ }++ function resolveSubagentApproval(childId: string, decision: ApprovalDecision): void {+ if (chatState.resolvingApprovals.has(decision.requestId)) return;+ chatState.resolvingApprovals.add(decision.requestId);+ ctx.composer.state.error = "";+ drawActiveChat();+ void resolveApproval(decision)+ .then(() => {+ subagentUi.approvals.set(+ childId,+ (subagentUi.approvals.get(childId) ?? []).filter((a) => a.requestId !== decision.requestId),+ );+ })+ .catch((err: unknown) => {+ ctx.composer.state.error = err instanceof Error ? err.message : "Could not send the approval.";+ })+ .finally(() => {+ chatState.resolvingApprovals.delete(decision.requestId);+ subagentUi.approvalsKey = "";+ void refreshSessions({ silent: true }).finally(() => drawActiveChat());+ });+ }++ const SUBAGENT_STATE_LABEL: Record<SubagentRow["state"], string> = {+ working: "working",+ waiting: "waiting",+ done: "done",+ failed: "failed",+ };++ function subagentRowTpl(row: SubagentRow): TemplateResult {+ const now = Date.now();+ const elapsed = goalElapsedLabel(row.startedAt, row.endedAt ?? now);+ const peeking = subagentUi.peekId === row.session.id;+ const title = row.session.title?.trim() || "Subagent";+ return html`<div+ class="subagent-row ${row.state} ${peeking ? "peeking" : ""}"+ style=${`--subagent-depth:${row.depth - 1}`}+ >+ <button+ type="button"+ class="subagent-row-head"+ aria-expanded=${String(peeking)}+ @click=${() => toggleSubagentPeek(row)}+ >+ ${row.state === "working" ? html`<span class="working-mark" ${ref(syncWorkingPulse)}>${workingWave()}</span>` : nothing}+ ${row.state === "waiting" ? html`<span class="awaiting-dot" aria-hidden="true"></span>` : nothing}+ ${row.state === "failed" ? html`<span class="subagent-failed-mark">${icon(TriangleAlert, 12)}</span>` : nothing}+ <span class="subagent-row-title" dir="auto">${title}</span>+ <span class="subagent-row-meta">${SUBAGENT_STATE_LABEL[row.state]} · ${elapsed}</span>+ </button>+ ${+ row.state === "failed"+ ? html`<button type="button" class="subagent-row-action" @click=${() => acknowledgeSubagent(row)}>+ Dismiss+ </button>`+ : nothing+ }+ <button type="button" class="subagent-row-action" @click=${() => void openSessionById(row.session.id)}>+ Open+ </button>+ ${+ subagentUi.approvals.get(row.session.id)?.length+ ? ctx.composer.composerApprovalPanel(subagentUi.approvals.get(row.session.id)!, (decision) =>+ resolveSubagentApproval(row.session.id, decision),+ )+ : nothing+ }+ ${peeking ? subagentPeekTpl() : nothing}+ </div>`;+ }++ function subagentPeekTpl(): TemplateResult {+ const lines = subagentUi.peek;+ if (!lines) return html`<div class="subagent-peek bg-panel-note">Loading…</div>`;+ if (!lines.length) return html`<div class="subagent-peek bg-panel-note">No activity yet</div>`;+ return html`<ol class="subagent-peek" aria-live="polite">+ ${lines.map(+ (line) =>+ html`<li class="subagent-peek-line ${line.kind}">+ ${line.kind === "tool" ? icon(Wrench, 11) : nothing}<span dir="auto">${line.text}</span>+ </li>`,+ )}+ </ol>`;+ }++ function subagentStrip(): TemplateResult | typeof nothing {+ const rootId = chatState.sessionId;+ if (!rootId) return nothing;+ const rows = visibleSubagents(subagentRows(sessionsState.list, rootId), subagentUi.acknowledged);+ if (subagentUi.peekId && !rows.some((row) => row.session.id === subagentUi.peekId)) stopSubagentPeek();+ syncSubagentApprovals(rows);+ if (!rows.length) return nothing;+ const single = rows.length === 1;+ const expanded = single || subagentUi.expanded || rows.some((row) => row.state === "waiting");+ const failed = rows.some((row) => row.state === "failed");+ return html`+ <section class="bg-activity subagent-activity ${expanded ? "expanded" : ""} ${failed ? "has-failed" : ""}">+ ${+ single+ ? nothing+ : html`<button+ type="button"+ class="bg-activity-strip"+ aria-expanded=${String(expanded)}+ @click=${() => {+ subagentUi.expanded = !subagentUi.expanded;+ if (!subagentUi.expanded) stopSubagentPeek();+ drawActiveChat();+ }}+ >+ ${icon(Bot, 13)}<span class="bg-activity-label">${subagentSummary(rows)}</span>+ <span class="bg-activity-toggle">${icon(ChevronRight, 14)}</span>+ </button>`+ }+ ${expanded ? html`<div class="subagent-list ${single ? "single" : "bg-panel"}">${rows.map(subagentRowTpl)}</div>` : nothing}+ </section>+ `;+ }+function goalStrip(agent: Agent): TemplateResult | typeof nothing {const goal = latestGoal(visibleMessages(agent));if (!goal || (goal.status !== "active" && goal.status !== "paused")) return nothing;diff --git a/plugins/web-ui/src/composer.ts b/plugins/web-ui/src/composer.tsindex 6c99e9394..775914b7c 100644--- a/plugins/web-ui/src/composer.ts+++ b/plugins/web-ui/src/composer.ts@@ -936,9 +936,12 @@ export function createComposerSurface(ctx: ConvCtx, options: ComposerOptions = {`;}- function composerApprovalPanel(approvals: PendingApproval[]): TemplateResult {+ function composerApprovalPanel(+ approvals: PendingApproval[],+ resolve: (decision: ApprovalDecision) => void = ctx.chat.resolveCommandApproval,+ ): TemplateResult {const decide = (decision: ApprovalDecision): void => {- if (!ctx.chat.state.resolvingApprovals.has(decision.requestId)) ctx.chat.resolveCommandApproval(decision);+ if (!ctx.chat.state.resolvingApprovals.has(decision.requestId)) resolve(decision);};return html`<div class="composer-approval-panel" role="group" aria-label="Command approval">${approvals.map(diff --git a/plugins/web-ui/src/conv-types.ts b/plugins/web-ui/src/conv-types.tsindex 0b11e6cec..d42ac9659 100644--- a/plugins/web-ui/src/conv-types.ts+++ b/plugins/web-ui/src/conv-types.ts@@ -127,7 +127,7 @@ interface ComposerState {}export interface ComposerSurface {- composerApprovalPanel(approvals: PendingApproval[]): TemplateResult;+ composerApprovalPanel(approvals: PendingApproval[], resolve?: (decision: ApprovalDecision) => void): TemplateResult;submit(instruction?: string): Promise<void>;restageAttachments(attachments: Attachment[], note: string): void;state: ComposerState;diff --git a/plugins/web-ui/src/core-bridge.ts b/plugins/web-ui/src/core-bridge.tsindex 139fff672..da8e7a1c1 100644--- a/plugins/web-ui/src/core-bridge.ts+++ b/plugins/web-ui/src/core-bridge.ts@@ -139,6 +139,7 @@ export interface CoreSession {lastActivityAt?: number;working?: boolean;awaitingInput?: boolean;+ lastTurnFailed?: boolean;backgroundJobs?: number;watches?: number;crons?: number;diff --git a/plugins/web-ui/src/session-list.ts b/plugins/web-ui/src/session-list.tsindex 85e6b0a0d..6fa2964de 100644--- a/plugins/web-ui/src/session-list.ts+++ b/plugins/web-ui/src/session-list.ts@@ -1,4 +1,5 @@import { sharedContextLabel, type CoreContext, type CoreProject, type CoreSession } from "./core-bridge.ts";+import { subagentCounts } from "./subagent-activity.ts";import { relTime } from "./ui.ts";type ProjectAwareContext = CoreContext & { project?: CoreProject };@@ -179,31 +180,57 @@ export function applySessionState(export interface RowIndicators {working: boolean;awaiting: boolean;- background: { jobs: number; watches: number; crons: number; label: string } | null;+ background: BackgroundCounts | null;+}++export interface BackgroundCounts {+ jobs: number;+ watches: number;+ crons: number;+ subagents: number;+ label: string;}export function backgroundLabel(jobs: number,watches: number,crons: number,-): { jobs: number; watches: number; crons: number; label: string } | null {+ subagents = 0,+ subagentsWaiting = 0,+): BackgroundCounts | null {const parts: string[] = [];+ if (subagents > 0) parts.push(`${subagents} subagent${subagents === 1 ? "" : "s"} running`);+ if (subagentsWaiting > 0)+ parts.push(`${subagentsWaiting} subagent${subagentsWaiting === 1 ? " needs" : "s need"} you`);if (jobs > 0) parts.push(`${jobs} background job${jobs === 1 ? "" : "s"} running`);if (watches > 0) parts.push(`${watches} watch${watches === 1 ? "" : "es"} armed`);if (crons > 0) parts.push(`${crons} cron${crons === 1 ? "" : "s"} scheduled here`);- return parts.length ? { jobs, watches, crons, label: parts.join(" · ") } : null;+ return parts.length+ ? { jobs, watches, crons, subagents: subagents + subagentsWaiting, label: parts.join(" · ") }+ : null;}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): RowIndicators {+export function rowIndicators(+ s: CoreSession,+ liveThreads: ReadonlySet<string> | string | null,+ list: readonly CoreSession[] = [],+): RowIndicators {const live = typeof liveThreads === "string" ? new Set([liveThreads]) : (liveThreads ?? new Set<string>());+ const children = subagentCounts(list, s.id);return {working: Boolean(s.working) || (Boolean(s.threadRef) && live.has(s.threadRef)),- awaiting: Boolean(s.awaitingInput),- background: backgroundLabel(s.backgroundJobs ?? 0, s.watches ?? 0, s.crons ?? 0),+ awaiting: Boolean(s.awaitingInput) || children.waiting > 0,+ background: backgroundLabel(+ s.backgroundJobs ?? 0,+ s.watches ?? 0,+ s.crons ?? 0,+ children.running,+ children.waiting,+ ),};}@@ -213,7 +240,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).background : null;+ return row ? rowIndicators(row, null, list).background : null;}export function shouldStartProactiveOpener(state: {diff --git a/plugins/web-ui/src/sessions.ts b/plugins/web-ui/src/sessions.tsindex 774760b4d..1aa54c78a 100644--- a/plugins/web-ui/src/sessions.ts+++ b/plugins/web-ui/src/sessions.ts@@ -8,6 +8,7 @@ import {Archive,Ban,Binoculars,+ Bot,ArchiveRestore,ChevronDown,ChevronRight,@@ -756,7 +757,7 @@ function sessionWorking(s: CoreSession): boolean {}function statusMarks(s: CoreSession): TemplateResult {- const ind = rowIndicators(s, liveThreads());+ const ind = rowIndicators(s, liveThreads(), sessionsState.list);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}${@@ -771,7 +772,7 @@ function statusMarks(s: CoreSession): TemplateResult {@keydown=${(e: KeyboardEvent) => (e.key === "Enter" || e.key === " ") && openBackgroundInspector(e, s)}>${ind.background.jobs > 0 ? icon(Cog, 11) : nothing}${ind.background.watches > 0 ? icon(Binoculars, 11) : nothing- }${ind.background.crons > 0 ? icon(Clock3, 11) : nothing}</span+ }${ind.background.crons > 0 ? icon(Clock3, 11) : nothing}${ind.background.subagents > 0 ? icon(Bot, 11) : nothing}</span>`: nothing}`;diff --git a/plugins/web-ui/src/shell.css b/plugins/web-ui/src/shell.cssindex 38b47ffe5..2d9815081 100644--- a/plugins/web-ui/src/shell.css+++ b/plugins/web-ui/src/shell.css@@ -3271,6 +3271,102 @@ qm-markdown .tok-in {transform: rotate(90deg);}+.subagent-activity.has-failed > .bg-activity-strip {+ color: var(--destructive, #c0392b);+}+.subagent-list {+ display: flex;+ flex-direction: column;+ gap: 2px;+}+.subagent-list.bg-panel {+ margin-top: 6px;+}+.subagent-row {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 4px;+ padding-left: calc(var(--subagent-depth, 0) * 14px);+ border-radius: 8px;+}+.subagent-row.peeking {+ background: color-mix(in srgb, var(--muted-foreground) 8%, transparent);+}+.subagent-row-head {+ appearance: none;+ display: flex;+ flex: 1 1 0;+ min-width: 0;+ align-items: center;+ gap: 6px;+ padding: 3px 6px;+ border: none;+ background: none;+ color: inherit;+ font: inherit;+ font-size: 12px;+ text-align: left;+ cursor: pointer;+}+.subagent-row-head:hover,+.subagent-row-action:hover {+ color: var(--foreground);+}+.subagent-row-title {+ min-width: 0;+ overflow: hidden;+ white-space: nowrap;+ text-overflow: ellipsis;+ color: var(--foreground);+}+.subagent-row-meta {+ flex: 0 0 auto;+ font-variant-numeric: tabular-nums;+}+.subagent-row.failed .subagent-row-meta,+.subagent-failed-mark {+ display: inline-flex;+ color: var(--destructive, #c0392b);+}+.subagent-row-action {+ appearance: none;+ flex: 0 0 auto;+ padding: 2px 6px;+ border: none;+ border-radius: 6px;+ background: none;+ color: inherit;+ font: inherit;+ font-size: 12px;+ cursor: pointer;+}+.subagent-peek {+ flex: 1 0 100%;+ margin: 0;+ padding: 2px 8px 6px 26px;+ list-style: none;+ display: flex;+ flex-direction: column;+ gap: 2px;+ font-size: 12px;+}+.subagent-peek-line {+ display: flex;+ align-items: baseline;+ gap: 5px;+ min-width: 0;+}+.subagent-peek-line > span {+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.subagent-peek-line.tool {+ font-family: var(--font-mono, ui-monospace, monospace);+ font-size: 11px;+}+.bg-panel {margin-top: 6px;border: 1px solid var(--border);@@ -10558,7 +10654,7 @@ h3.ambient-field-label {.loop-health-failing,.loop-health-quarantined {background: color-mix(in srgb, var(--destructive) 12%, var(--background));- color: var(--destructive);+ color: var(--destructive, #c0392b);}.loop-health-reason {color: var(--muted-foreground, #667085);@@ -10715,7 +10811,7 @@ h3.ambient-field-label {color: var(--muted-foreground, #667085);}.loop-item-failed {- color: var(--destructive);+ color: var(--destructive, #c0392b);}.loop-item-shipped {color: var(--success);diff --git a/plugins/web-ui/src/split.ts b/plugins/web-ui/src/split.tsindex 9a868224e..d3e22e5b7 100644--- a/plugins/web-ui/src/split.ts+++ b/plugins/web-ui/src/split.ts@@ -7,6 +7,7 @@ import {Archive,ArrowUpLeft,Binoculars,+ Bot,Box,Brain,Clock3,@@ -78,7 +79,7 @@ import {archiveSessionById,syncWorkingPulse,} from "./sessions";-import { conversationBackground, type RowIndicators } from "./session-list";+import { conversationBackground, rowIndicators, type RowIndicators } from "./session-list";import { scopeToolCount, setScopedSession, type SessionTool } from "./session-scope";import {fetchTranscript,@@ -905,7 +906,8 @@ function paneIsWorking(panel: IDockviewPanel): boolean {}function paneAwaitsInput(panel: IDockviewPanel): boolean {- return Boolean(paneSession(panel)?.awaitingInput);+ const session = paneSession(panel);+ return session ? rowIndicators(session, null, sessionsState.list).awaiting : false;}function paneBackground(panel: IDockviewPanel): RowIndicators["background"] {@@ -1231,7 +1233,7 @@ class PaneTab implements ITabRenderer {? html`<span class="bg-chip" aria-label=${background.label} ${tip(background.label)}>${background.jobs > 0 ? icon(Cog, 11) : nothing}${background.watches > 0 ? icon(Binoculars, 11) : nothing- }${background.crons > 0 ? icon(Clock3, 11) : nothing}</span+ }${background.crons > 0 ? icon(Clock3, 11) : nothing}${background.subagents > 0 ? icon(Bot, 11) : nothing}</span>`: nothing}diff --git a/plugins/web-ui/src/subagent-activity.ts b/plugins/web-ui/src/subagent-activity.tsnew file mode 100644index 000000000..617666f5d--- /dev/null+++ b/plugins/web-ui/src/subagent-activity.ts@@ -0,0 +1,114 @@+import type { CoreSession, SessionEntry } from "./core-bridge.ts";++type SubagentState = "working" | "waiting" | "done" | "failed";++export interface SubagentRow {+ session: CoreSession;+ state: SubagentState;+ depth: number;+ startedAt: number;+ endedAt: number | null;+}++type SessionLink = Pick<CoreSession, "id" | "parentSessionId" | "working" | "awaitingInput">;++export function descendantsOf<T extends SessionLink>(+ list: readonly T[],+ rootId: string,+): { session: T; depth: number }[] {+ const out: { session: T; depth: number }[] = [];+ const seen = new Set([rootId]);+ let frontier = [rootId];+ for (let depth = 1; frontier.length; depth++) {+ const parents = new Set(frontier);+ frontier = [];+ for (const session of list) {+ if (!session.parentSessionId || !parents.has(session.parentSessionId) || seen.has(session.id)) continue;+ seen.add(session.id);+ out.push({ session, depth });+ frontier.push(session.id);+ }+ }+ 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";+ if (session.awaitingInput) state = "waiting";+ else if (session.working) state = "working";+ else if (session.lastTurnFailed) state = "failed";+ const live = state === "working" || state === "waiting";+ return {+ session,+ state,+ depth,+ startedAt: session.createdAt,+ endedAt: live ? null : (session.lastActivityAt ?? session.createdAt),+ };+ });+}++export function visibleSubagents(rows: readonly SubagentRow[], acknowledged: ReadonlySet<string>): SubagentRow[] {+ return rows.filter((row) => row.state !== "done" && !(row.state === "failed" && acknowledged.has(ackKey(row))));+}++export function ackKey(row: Pick<SubagentRow, "session" | "endedAt">): string {+ return `${row.session.id}@${row.endedAt ?? 0}`;+}++export function subagentSummary(rows: readonly SubagentRow[]): string {+ const count = (state: SubagentState) => rows.filter((row) => row.state === state).length;+ const parts: string[] = [];+ const working = count("working");+ const waiting = count("waiting");+ const failed = count("failed");+ if (working) parts.push(`${working} subagent${working === 1 ? "" : "s"} running`);+ if (waiting) parts.push(`${waiting} need${waiting === 1 ? "s" : ""} you`);+ if (failed) parts.push(`${failed} failed`);+ return parts.join(", ");+}++export interface PeekLine {+ kind: "tool" | "text";+ text: string;+}++function clip(text: string, max: number): string {+ const flat = text.replace(/\s+/g, " ").trim();+ return flat.length > max ? `${flat.slice(0, max - 1)}…` : flat;+}++function toolLine(payload: { tool?: unknown; action?: unknown; command?: unknown }): string | null {+ if (typeof payload.tool !== "string" || !payload.tool) return null;+ const action = typeof payload.action === "string" && payload.action ? ` ${payload.action}` : "";+ const command = typeof payload.command === "string" && payload.command ? ` · ${payload.command}` : "";+ return clip(`${payload.tool}${action}${command}`, 120);+}++export function peekLines(entries: readonly SessionEntry[], max = 4): PeekLine[] {+ const lines: PeekLine[] = [];+ for (const entry of entries) {+ const payload = (entry.payload ?? {}) as { tool?: unknown; action?: unknown; command?: unknown; text?: unknown };+ const tool = entry.type === "tool_call" ? toolLine(payload) : null;+ if (tool) lines.push({ kind: "tool", text: tool });+ else if ((entry.type === "assistant" || entry.type === "text") && typeof payload.text === "string") {+ const text = clip(payload.text, 240);+ if (text) lines.push({ kind: "text", text });+ }+ }+ return lines.slice(-max);+}diff --git a/plugins/web-ui/test/approvals-server-route.test.ts b/plugins/web-ui/test/approvals-server-route.test.tsindex 74fcbbf1c..00c7f8cd5 100644--- a/plugins/web-ui/test/approvals-server-route.test.ts+++ b/plugins/web-ui/test/approvals-server-route.test.ts@@ -65,6 +65,26 @@ const core = createServer((req: IncomingMessage, res) => {);return;}+ if (url.startsWith("/v1/approvals/a-sub")) {+ let sessionId = "child";+ if (url.includes("hidden")) sessionId = "hidden";+ if (url.includes("mismatch")) sessionId = "child-mismatch";+ res.end(+ JSON.stringify({+ sessionId,+ request: { ...storedRequest, conversation: { kind: "dm", threadRef: "agent:main:subagent:c1" } },+ }),+ );+ return;+ }+ if (url.startsWith("/v1/sessions/child-mismatch")) {+ res.end(JSON.stringify({ session: { id: "child-mismatch", threadRef: "agent:main:subagent:other" } }));+ return;+ }+ if (url.startsWith("/v1/sessions/child")) {+ res.end(JSON.stringify({ session: { id: "child", threadRef: "agent:main:subagent:c1" } }));+ return;+ }if (url.startsWith("/v1/sessions/hidden")) {res.statusCode = 403;res.end(JSON.stringify({ error: "forbidden" }));@@ -212,6 +232,33 @@ test("worker replay rejects a mismatched thread or non-worker session", async ()}});+test("a visible subagent approval replays onto the child thread so the parent can unblock it", async () => {+ const before = calls.length;+ const r = await fetch(`${base}/api/approvals/a-sub`, {+ method: "POST",+ headers,+ body: JSON.stringify({ approved: true, scope: "once" }),+ });+ assert.equal(r.status, 200);+ const posts = turnPosts(before);+ assert.equal(posts.length, 1);+ assert.equal((posts[0]!.body.conversation as { threadRef: string }).threadRef, "agent:main:subagent:c1");+ assert.deepEqual(posts[0]!.body.approval, { requestId: "a-sub", approved: true, scope: "once" });+});++test("subagent approvals require the child session to be visible and on the same thread", async () => {+ for (const id of ["a-sub-hidden", "a-sub-mismatch"]) {+ const before = calls.length;+ const response = await fetch(`${base}/api/approvals/${id}`, {+ method: "POST",+ headers,+ body: JSON.stringify({ approved: true }),+ });+ assert.equal(response.status, 404);+ assert.equal(turnPosts(before).length, 0);+ }+});+test("inbox approval replay requires both current gates and preserves the screened snapshot", async () => {const previous = process.env.INBOX_USERS;try {diff --git a/plugins/web-ui/test/pinned-composer-polish.test.ts b/plugins/web-ui/test/pinned-composer-polish.test.tsindex aca2af7da..3759e298b 100644--- a/plugins/web-ui/test/pinned-composer-polish.test.ts+++ b/plugins/web-ui/test/pinned-composer-polish.test.ts@@ -16,7 +16,7 @@ test("transcript top spacing and prompt gap stay compact at every density", () =test("background activity shares the queued inset above the composer", () => {assert.match(chat,- /ctx\.composer\.queuedStrip\(agent\)\} \$\{backgroundActivityStrip\(\)\}\s*\$\{ctx\.composer\.composerForm\(agent\)\}/,+ /ctx\.composer\.queuedStrip\(agent\)\} \$\{subagentStrip\(\)\} \$\{backgroundActivityStrip\(\)\}\s*\$\{ctx\.composer\.composerForm\(agent\)\}/,);assert.match(css, /\.queued-strip,\s*\.chat-bottom-dock > \.bg-activity \{/);assert.doesNotMatch(css, /\.composer-wrap > \.bg-activity/);diff --git a/plugins/web-ui/test/session-list.test.ts b/plugins/web-ui/test/session-list.test.tsindex 64eb7e4d4..4b5a1e826 100644--- a/plugins/web-ui/test/session-list.test.ts+++ b/plugins/web-ui/test/session-list.test.ts@@ -387,19 +387,33 @@ test("rowIndicators: awaitingInput maps through", () => {});test("backgroundLabel: jobs, watches and crons fold into one chip with a spoken label", () => {- assert.deepEqual(backgroundLabel(1, 0, 0), { jobs: 1, watches: 0, crons: 0, label: "1 background job running" });+ assert.deepEqual(backgroundLabel(1, 0, 0), {+ jobs: 1,+ watches: 0,+ crons: 0,+ subagents: 0,+ label: "1 background job running",+ });assert.deepEqual(backgroundLabel(2, 1, 0), {jobs: 2,watches: 1,crons: 0,+ subagents: 0,label: "2 background jobs running · 1 watch armed",});- assert.deepEqual(backgroundLabel(0, 2, 0), { jobs: 0, watches: 2, crons: 0, label: "2 watches armed" });- assert.deepEqual(backgroundLabel(0, 0, 1), { jobs: 0, watches: 0, crons: 1, label: "1 cron scheduled here" });+ assert.deepEqual(backgroundLabel(0, 2, 0), { jobs: 0, watches: 2, crons: 0, subagents: 0, label: "2 watches armed" });+ assert.deepEqual(backgroundLabel(0, 0, 1), {+ jobs: 0,+ watches: 0,+ crons: 1,+ subagents: 0,+ label: "1 cron scheduled here",+ });assert.deepEqual(backgroundLabel(0, 1, 2), {jobs: 0,watches: 1,crons: 2,+ subagents: 0,label: "1 watch armed · 2 crons scheduled here",});assert.equal(backgroundLabel(0, 0, 0), null, "nothing running, nothing to say");@@ -417,10 +431,17 @@ test("rowIndicators: background counts flow through backgroundLabel — zero coujobs: 2,watches: 1,crons: 0,+ subagents: 0,label: "2 background jobs running · 1 watch armed",});const cronOnly = rowIndicators({ ...saved("1", "web:u:x"), crons: 3 }, null);- assert.deepEqual(cronOnly.background, { jobs: 0, watches: 0, crons: 3, label: "3 crons scheduled here" });+ assert.deepEqual(cronOnly.background, {+ jobs: 0,+ watches: 0,+ crons: 3,+ subagents: 0,+ label: "3 crons scheduled here",+ });assert.equal(rowIndicators({ ...saved("1", "web:u:x"), backgroundJobs: 0, watches: 0, crons: 0 }, null).background,null,@@ -434,6 +455,7 @@ test("conversationBackground: resolves the mounted conversation by session id",jobs: 2,watches: 1,crons: 0,+ subagents: 0,label: "2 background jobs running · 1 watch armed",});});@@ -444,6 +466,7 @@ test("conversationBackground: falls back to threadRef while the conversation isjobs: 0,watches: 1,crons: 0,+ subagents: 0,label: "1 watch armed",});});diff --git a/plugins/web-ui/test/subagent-activity.test.ts b/plugins/web-ui/test/subagent-activity.test.tsnew file mode 100644index 000000000..5fc83904b--- /dev/null+++ b/plugins/web-ui/test/subagent-activity.test.ts@@ -0,0 +1,113 @@+import test from "node:test";+import assert from "node:assert/strict";+import type { CoreSession, SessionEntry } from "../src/core-bridge.ts";+import {+ ackKey,+ descendantsOf,+ peekLines,+ subagentCounts,+ subagentRows,+ subagentSummary,+ visibleSubagents,+} from "../src/subagent-activity.ts";+import { backgroundLabel, conversationBackground, rowIndicators } from "../src/session-list.ts";++function row(id: string, parentSessionId?: string, extra: Partial<CoreSession> = {}): CoreSession {+ return {+ id,+ type: "dm",+ scopeId: "personal:a",+ threadRef: `agent:main:subagent:${id}`,+ createdAt: 1_000,+ lastActivityAt: 61_000,+ ...(parentSessionId ? { parentSessionId } : {}),+ ...extra,+ };+}++const list = [+ row("root"),+ row("a", "root", { working: true }),+ row("b", "root", { lastTurnFailed: true }),+ row("c", "root", { awaitingInput: true }),+ row("a1", "a", { working: true }),+ row("other"),+];++test("descendants roll grandchildren up to the top-level parent", () => {+ assert.deepEqual(+ descendantsOf(list, "root").map(({ session, depth }) => [session.id, depth]),+ [+ ["a", 1],+ ["b", 1],+ ["c", 1],+ ["a1", 2],+ ],+ );+ assert.deepEqual(+ descendantsOf([row("x", "y"), row("y", "x")], "x").map(({ session }) => session.id),+ ["y"],+ );+});++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), {+ jobs: 0,+ watches: 0,+ crons: 0,+ subagents: 3,+ label: "2 subagents running · 1 subagent needs you",+ });+ assert.equal(backgroundLabel(1, 0, 0, 1)?.label, "1 subagent running · 1 background job running");+});++test("rows derive working, waiting, done and failed; done folds away, failed stays until acknowledged", () => {+ const rows = subagentRows(list, "root");+ assert.deepEqual(+ rows.map((r) => [r.session.id, r.state]),+ [+ ["a", "working"],+ ["b", "failed"],+ ["c", "waiting"],+ ["a1", "working"],+ ],+ );+ assert.equal(rows[0]!.endedAt, null);+ assert.equal(rows[1]!.endedAt, 61_000);+ assert.equal(subagentSummary(rows), "2 subagents running, 1 needs you, 1 failed");+ const failed = rows[1]!;+ assert.deepEqual(+ visibleSubagents(rows, new Set([ackKey(failed)])).map((r) => r.session.id),+ ["a", "c", "a1"],+ );+ const done = subagentRows(+ list.map((s) => (s.id === "b" ? { ...s, lastTurnFailed: false } : s)),+ "root",+ );+ assert.equal(+ visibleSubagents(done, new Set()).some((r) => r.session.id === "b"),+ false,+ );+});++test("peek shows the latest tool steps and message", () => {+ const entry = (type: SessionEntry["type"], payload: unknown): SessionEntry => ({ type, payload, createdAt: 0 });+ const lines = peekLines(+ [+ entry("user", { text: "go" }),+ entry("tool_call", { tool: "sandbox", action: "exec", command: "npm test" }),+ entry("tool_result", { tool: "sandbox", ok: true }),+ entry("text", { text: "Tests pass.\nOpening PR" }),+ entry("tool_call", { tool: "github" }),+ ],+ 3,+ );+ assert.deepEqual(lines, [+ { kind: "tool", text: "sandbox exec · npm test" },+ { kind: "text", text: "Tests pass. Opening PR" },+ { kind: "tool", text: "github" },+ ]);+});diff --git a/src/api/app-sessions.ts b/src/api/app-sessions.tsindex 80582be6a..a1ac429c8 100644--- a/src/api/app-sessions.ts+++ b/src/api/app-sessions.ts@@ -430,9 +430,16 @@ export function createSessionMethods(if (!c.enabled || c.archived || !c.destination) continue;cronCounts.set(c.destination.target, (cronCounts.get(c.destination.target) ?? 0) + 1);}+ const failedChildren = new Set<string>();+ for (const s of sessions) {+ if (!s.parentSessionId || workingThreadRefs.has(s.threadRef) || waiting.has(s.id)) continue;+ const run = await deps.runs.latestForThread(s.threadRef);+ if (run?.status === "failed" || run?.result?.status === "failed") failedChildren.add(s.id);+ }if (workingThreadRefs.size === 0 &&waiting.size === 0 &&+ failedChildren.size === 0 &&jobCounts.size === 0 &&watchCounts.size === 0 &&cronCounts.size === 0@@ -442,6 +449,7 @@ export function createSessionMethods(...s,...(workingThreadRefs.has(s.threadRef) ? { working: true } : {}),...(waiting.has(s.id) ? { awaitingInput: true } : {}),+ ...(failedChildren.has(s.id) ? { lastTurnFailed: true } : {}),...(jobCounts.has(s.threadRef) ? { backgroundJobs: jobCounts.get(s.threadRef)! } : {}),...(watchCounts.has(s.threadRef) ? { watches: watchCounts.get(s.threadRef)! } : {}),...(cronCounts.has(s.threadRef) ? { crons: cronCounts.get(s.threadRef)! } : {}),diff --git a/src/types.ts b/src/types.tsindex 2879bb0c6..f08c55e88 100644--- a/src/types.ts+++ b/src/types.ts@@ -115,6 +115,7 @@ export interface Session {hasEntries?: boolean;working?: boolean;awaitingInput?: boolean;+ lastTurnFailed?: boolean;backgroundJobs?: number;watches?: number;crons?: number;diff --git a/test/sessions-working.test.ts b/test/sessions-working.test.tsindex d70510311..4c9c8572d 100644--- a/test/sessions-working.test.ts+++ b/test/sessions-working.test.ts@@ -68,3 +68,26 @@ test("the working flag clears once the in-flight run settles", async () => {"the flag clears once the run is terminal",);});++test("listSessions flags a subagent whose latest turn failed, and only while it stays failed", async () => {+ const { app, runs, sessions } = freshApp();+ const parent = await app.turn(dm("parent", "web:U1:parent"));+ const child = await app.turn(dm("child", "web:U1:child"));+ const loose = await app.turn(dm("loose", "web:U1:loose"));+ await sessions.setParentSession(child.sessionId!, parent.sessionId!);++ for (const thread of ["web:U1:child", "web:U1:loose"]) {+ await runs.enqueue({ sessionId: thread, request: enqueueRequest() });+ const claimed = await runs.claim("w1", 5_000);+ await runs.complete(claimed!.id, claimed!.leaseToken ?? "", { status: "failed", reason: "boom" });+ }++ const list = await app.listSessions("U1");+ assert.equal(list.find((s) => s.id === child.sessionId)?.lastTurnFailed, true);+ assert.ok(!list.find((s) => s.id === loose.sessionId)?.lastTurnFailed, "only subagents carry the flag");++ await runs.enqueue({ sessionId: "web:U1:child", request: enqueueRequest() });+ const retry = await runs.claim("w1", 5_000);+ await runs.complete(retry!.id, retry!.leaseToken ?? "", { status: "ok", reply: "fine" });+ assert.ok(!(await app.listSessions("U1")).find((s) => s.id === child.sessionId)?.lastTurnFailed);+});