A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
fix: count busy descendants in the agents-view subagents indicator (#1986)
Sebastian Müller616557280fd3
diff --git a/packages/coding-agent/.changes/res-1253-busy-descendant-indicator.md b/packages/coding-agent/.changes/res-1253-busy-descendant-indicator.mdnew file mode 100644index 0000000000..c33b011c82--- /dev/null+++ b/packages/coding-agent/.changes/res-1253-busy-descendant-indicator.md@@ -0,0 +1,2 @@+- Fixed the agents view undercounting running subagents: the "N subagents running" indicator now counts busy descendants at any depth, stays visible on collapsed groups, and idle sessions with busy subagents sort above plain idle sessions.+- Changed the agents view Running section to mean the session's own work: sessions whose only activity is delegated to subagents now list as Idle with the running-subagents badge.diff --git a/packages/coding-agent/src/core/agent-session.ts b/packages/coding-agent/src/core/agent-session.tsindex 28b8fd49d0..260da669e6 100644--- a/packages/coding-agent/src/core/agent-session.ts+++ b/packages/coding-agent/src/core/agent-session.ts@@ -10431,7 +10431,15 @@ export class AgentSession {else run.suppressTerminalNotice = true;return true;}- return this._cancelRlmChildRun(run, reason);+ // Cancel AND descend: the abort cascade only reaches active runs, never+ // running work retained under a settled descendant.+ const cancelled = this._cancelRlmChildRun(run, reason);+ const descendantsCancelled = run.session?.cancelRunningRlmDescendants(reason) ?? false;+ return cancelled || descendantsCancelled;+ }+ const retainedTarget = this._rlmChildSessions.get(childId)?.session;+ if (retainedTarget?.cancelRunningRlmDescendants(reason)) {+ return true;}for (const candidate of this._activeRlmChildRuns.values()) {if (candidate.session?.cancelRlmChildRun(childId, reason)) {@@ -10446,6 +10454,25 @@ export class AgentSession {return false;}+ /** Cancel every running or queued run in this session's subtree; cancel AND descend at every node. */+ cancelRunningRlmDescendants(reason = "Cancelled by user"): boolean {+ let cancelled = false;+ for (const run of this._activeRlmChildRuns.values()) {+ if (run.status === "running" || run.status === "queued") {+ if (this._cancelRlmChildRun(run, reason)) cancelled = true;+ }+ if (run.session?.cancelRunningRlmDescendants(reason)) {+ cancelled = true;+ }+ }+ for (const { session } of this._rlmChildSessions.values()) {+ if (session.cancelRunningRlmDescendants(reason)) {+ cancelled = true;+ }+ }+ return cancelled;+ }+private async _assertRlmSubagentSessionNameAvailable(name: string, ignorePendingReservation = false): Promise<void> {const depth = this._rlmDepth + 1;if (!ignorePendingReservation && this._pendingRlmSubagentSessionNames.has(name)) {diff --git a/packages/coding-agent/src/modes/agents-view/agents-view-mode.ts b/packages/coding-agent/src/modes/agents-view/agents-view-mode.tsindex abfb726614..e97c8c9649 100644--- a/packages/coding-agent/src/modes/agents-view/agents-view-mode.ts+++ b/packages/coding-agent/src/modes/agents-view/agents-view-mode.ts@@ -1949,7 +1949,7 @@ export class AgentsViewMode implements Component, Focusable {}private async killSubagent(pending: PendingKillSubagent, currentRow: AgentsViewRow): Promise<void> {- const running = currentRow.section === "running";+ const running = hasLiveWork(currentRow);const client = this.requireClient();this.setStatusMessage(running ? "Stopping subagent..." : "Deleting subagent...");try {@@ -2015,7 +2015,7 @@ export class AgentsViewMode implements Component, Focusable {this.showDeleteConfirmation();return;}- if (!isRunningSessionSummary(row.summary)) {+ if (!hasLiveWork(row)) {this.pendingDeleteAgent = {identity,activeSessionId,@@ -2528,7 +2528,8 @@ export class AgentsViewMode implements Component, Focusable {if (row.kind === "subagent-summary") {const indent = " ".repeat(row.depth);const hint = row.hasSpawnCode ? theme.fg("dim", ` · ${keyText("app.agents.program")} show program`) : "";- const label = `${theme.fg("dim", `${row.expanded ? "▾" : "▸"} ${row.title}`)}${hint}`;+ const titleColor = row.runningSubagentCount > 0 ? ("success" as const) : ("dim" as const);+ const label = `${theme.fg(titleColor, `${row.expanded ? "▾" : "▸"} ${row.title}`)}${hint}`;const line = padLine(truncateToWidth(`${indent}${label}`, width, ""), width);return selected ? `${SELECTED_ROW_MARKER}${line}` : line;}@@ -2558,7 +2559,7 @@ export class AgentsViewMode implements Component, Focusable {const title = pendingDelete? `${heartbeatWarning}${this.getPendingDeleteTitle()}`: pendingKill- ? `${heartbeatWarning}${keyText("app.agents.delete")} again to ${row.section === "running" ? "stop" : "delete"}`+ ? `${heartbeatWarning}${keyText("app.agents.delete")} again to ${hasLiveWork(row) ? "stop" : "delete"}`: styleRowTitle(row);// Keep stable model information ahead of the variable summary so narrow rows truncate the summary first.const summaryText = !pendingDelete && !pendingKill ? row.summary.summary : undefined;@@ -2820,8 +2821,9 @@ function rowHasSpawnCode(row: AgentsViewRow): boolean {return typeof code === "string" && code.trim().length > 0;}-function isRunningSessionSummary(summary: SessionSummary): boolean {- return summary.activity === "working";+// Destructive actions gate on live work anywhere in the subtree, never on the display section.+function hasLiveWork(row: AgentsViewRow): boolean {+ return row.section === "running" || row.runningSubagentCount > 0 || row.summary.hasRunningRlmChildren === true;}// Explicit session names read bold so they stand out from fallback titlesdiff --git a/packages/coding-agent/src/modes/agents-view/agents-view-state.ts b/packages/coding-agent/src/modes/agents-view/agents-view-state.tsindex 52388973db..2e2b3c03d4 100644--- a/packages/coding-agent/src/modes/agents-view/agents-view-state.ts+++ b/packages/coding-agent/src/modes/agents-view/agents-view-state.ts@@ -715,13 +715,25 @@ export function buildAgentsViewRows(continue;}nestedRows.add(row);- if (row.section === "running") {- parent.runningSubagentCount += 1;- }const siblings = childrenByParent.get(parent) ?? [];siblings.push(row);childrenByParent.set(parent, siblings);}+ // Busy-descendant tally from the live rows: iterative over the parent forest so deep chains cannot overflow.+ const tallyOrder = baseRows.filter((row) => !nestedRows.has(row));+ for (let index = 0; index < tallyOrder.length; index++) {+ for (const child of childrenByParent.get(tallyOrder[index]!) ?? []) {+ tallyOrder.push(child);+ }+ }+ for (let index = tallyOrder.length - 1; index >= 0; index--) {+ const row = tallyOrder[index]!;+ let count = 0;+ for (const child of childrenByParent.get(row) ?? []) {+ count += (child.section === "running" ? 1 : 0) + child.runningSubagentCount;+ }+ row.runningSubagentCount = count;+ }const roots = baseRows.filter((row) => !nestedRows.has(row));const flattened: AgentsViewRow[] = [];@@ -880,6 +892,10 @@ function compareAgentsViewRows(a: AgentsViewRow, b: AgentsViewRow): number {}}if (a.section !== "running") {+ const busyDescendantsDiff = Number(b.runningSubagentCount > 0) - Number(a.runningSubagentCount > 0);+ if (busyDescendantsDiff !== 0) {+ return busyDescendantsDiff;+ }const activityDiff = getTimestamp(b.summary.lastActivityAt) - getTimestamp(a.summary.lastActivityAt);if (activityDiff !== 0) {return activityDiff;@@ -1008,9 +1024,6 @@ function getSessionStatusLabel(summary: SessionSummary, heartbeat?: UnifiedSessiif (summary.isBashRunning === true) {return "running bash";}- if (summary.hasRunningRlmChildren === true) {- return "subagents running";- }if (summary.sessionActions.active) {return summary.sessionActions.active.label ?? summary.sessionActions.active.kind.replace("_", " ");}diff --git a/packages/coding-agent/src/modes/daemon/agent-roster.ts b/packages/coding-agent/src/modes/daemon/agent-roster.tsindex e2d73c029f..7365a5c9dd 100644--- a/packages/coding-agent/src/modes/daemon/agent-roster.ts+++ b/packages/coding-agent/src/modes/daemon/agent-roster.ts@@ -9,7 +9,7 @@ export interface AgentStatusInput {resident: boolean;/** Admitted child run whose session has not materialized yet. */queuedChild: boolean;- /** Actively working: streaming, running tools/bash, or running children. */+ /** Actively working: streaming or running tools/bash. */busy: boolean;}@@ -19,6 +19,7 @@ export function classifyAgentStatus(input: AgentStatusInput): AgentRosterStatusreturn input.busy ? "running" : "idle";}+// Residency/shutdown-safety busy: delegated child work counts; the section classifier deliberately does not use it.export function isSessionSummaryBusy(summary: Pick<SessionSummary, "isSessionActive" | "hasRunningRlmChildren">,): boolean {@@ -26,13 +27,13 @@ export function isSessionSummaryBusy(}export function classifySessionRosterStatus(- summary: Pick<SessionSummary, "activeSessionId" | "activity" | "isSessionActive" | "hasRunningRlmChildren">,+ summary: Pick<SessionSummary, "activeSessionId" | "activity" | "isSessionActive">,queuedChild = false,): AgentRosterStatus {return classifyAgentStatus({resident: !!summary.activeSessionId,queuedChild,- busy: summary.activity === "working" || isSessionSummaryBusy(summary),+ busy: summary.activity === "working" || summary.isSessionActive === true,});}diff --git a/packages/coding-agent/src/modes/daemon/daemon-mode.ts b/packages/coding-agent/src/modes/daemon/daemon-mode.tsindex 599c5359d4..28e6e1108f 100644--- a/packages/coding-agent/src/modes/daemon/daemon-mode.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-mode.ts@@ -171,8 +171,8 @@ import {buildRlmChildSnapshots,buildSessionList,classifySessionRosterStatus,+ hasLiveSessionWork,inactiveLifecycleForSession,- isActiveSessionBusy,type SessionSummary,scheduledJobRegistrations,summaryForActiveSession,@@ -6048,8 +6048,7 @@ export class AgentDaemon {if (state.runtime.metadata.kind === "subagent") {return false;}- // A running bash or in-flight turn means there is live work to preserve.- if (state.runtime.session.isBashRunning || isActiveSessionBusy(state)) {+ if (state.runtime.session.isBashRunning || hasLiveSessionWork(state)) {return false;}return this.isEmptyDraftContent(state);@@ -6974,7 +6973,7 @@ export class AgentDaemon {}const session = state.runtime.session;const busy =- busyOverride ?? (isActiveSessionBusy(state) || session.isRetrying || session.hasAcceptedPromptInFlight);+ busyOverride ?? (hasLiveSessionWork(state) || session.isRetrying || session.hasAcceptedPromptInFlight);try {this.recoveryJournal.record({activeSessionId: state.activeSessionId,diff --git a/packages/coding-agent/src/modes/daemon/daemon-session-list.ts b/packages/coding-agent/src/modes/daemon/daemon-session-list.tsindex 07144dfc0a..6dd9fc4953 100644--- a/packages/coding-agent/src/modes/daemon/daemon-session-list.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-session-list.ts@@ -407,15 +407,15 @@ function readMessageText(content: unknown): string {.join("\n");}-// Agent doing work, ignoring the classification verdict.-export function isActiveSessionBusy(activeSession: ActiveSessionState): boolean {+// Live work that dies with the worker; the display activity axis deliberately excludes delegated work.+export function hasLiveSessionWork(activeSession: ActiveSessionState): boolean {const session = activeSession.runtime.session;- // Background subagents keep the parent "working" even after its own turn ends.return session.isSessionActive || session.hasRunningRlmChildren();}export function activeActivityForSession(activeSession: ActiveSessionState): SessionActivity {- if (isActiveSessionBusy(activeSession)) {+ // The session's own work only, ignoring the classification verdict.+ if (activeSession.runtime.session.isSessionActive) {return "working";}// A finished subagent is resident but never gets a summarizer verdict, so don't holddiff --git a/packages/coding-agent/test/agent-roster.test.ts b/packages/coding-agent/test/agent-roster.test.tsindex f050abb2e4..0aa0e366d4 100644--- a/packages/coding-agent/test/agent-roster.test.ts+++ b/packages/coding-agent/test/agent-roster.test.ts@@ -52,4 +52,11 @@ describe("classifyAgentStatus", () => {expect(classifySessionRosterStatus(summaryFor(false, false, true))).toBe("inactive");expect(classifySubagentSnapshotStatus(childFor(false, false))).toBe("inactive");});++ it("keeps a session with only delegated child work out of running", () => {+ const delegating: SessionSummary = { ...summaryFor(true, false, false), hasRunningRlmChildren: true };+ expect(classifySessionRosterStatus(delegating)).toBe("idle");+ const streaming: SessionSummary = { ...summaryFor(true, true, false), hasRunningRlmChildren: true };+ expect(classifySessionRosterStatus(streaming)).toBe("running");+ });});diff --git a/packages/coding-agent/test/agent-session-recursion.test.ts b/packages/coding-agent/test/agent-session-recursion.test.tsindex 579ad3fc5a..f03eab82ed 100644--- a/packages/coding-agent/test/agent-session-recursion.test.ts+++ b/packages/coding-agent/test/agent-session-recursion.test.ts@@ -3105,9 +3105,33 @@ describe("AgentSession rlm recursion", () => {expect(root.cancelRlmChildRun("unknown-child")).toBe(false);expect(run?.status).toBe("running");+ // Running work retained under the LIVE child: the abort cascade only+ // reaches active runs, so the cancel walk must descend here itself.+ await waitFor(() => run?.session !== undefined);+ const deepHost = createSession({ rlmSessionDir: join(tempDir, "deep-host") });+ const deepAbort = vi.fn();+ const deepRun = {+ id: "deep-1",+ status: "running",+ settled: false,+ abort: deepAbort,+ publication: { reject: vi.fn() },+ emitUpdate: vi.fn(),+ };+ (deepHost as unknown as { _activeRlmChildRuns: Map<string, typeof deepRun> })._activeRlmChildRuns.set(+ "deep-1",+ deepRun,+ );+ (run?.session as unknown as { _rlmChildSessions: Map<string, { session: AgentSession }> })._rlmChildSessions.set(+ "deep-host",+ { session: deepHost },+ );+expect(root.cancelRlmChildRun(childId)).toBe(true);expect(run?.status).toBe("cancelled");expect(run?.error).toBe("Cancelled by user");+ expect(deepRun.status).toBe("cancelled");+ expect(deepAbort).toHaveBeenCalled();// The cancelled update is pushed at cancel time, before the (possibly// stuck) child unwinds; viewers must not keep showing a running child.expect(childStatuses[childStatuses.length - 1]).toBe("cancelled");@@ -3120,6 +3144,45 @@ describe("AgentSession rlm recursion", () => {expect(root.cancelRlmChildRun(childId)).toBe(false);});+ it("stops live descendants when the targeted child run already settled", async () => {+ const root = createSession({+ streamFn: (_model, context) => {+ const stream = createAssistantMessageEventStream();+ stream.push({+ type: "done",+ reason: "stop",+ message: assistantMessage(`child answer: ${userText(context)}`),+ });+ return stream;+ },+ });++ await root.runRlmChild("quick shard");+ const runs = (root as unknown as InspectableRlmSession)._activeRlmChildRuns;+ await waitFor(() => runs.size === 0);+ const retained = (root as unknown as { _rlmChildSessions: Map<string, { session: AgentSession }> })+ ._rlmChildSessions;+ expect(retained.size).toBe(1);+ const [childId, { session: childSession }] = [...retained.entries()][0]!;+ const abort = vi.fn();+ const grandchild = {+ id: "grandchild-1",+ status: "running",+ settled: false,+ abort,+ publication: { reject: vi.fn() },+ emitUpdate: vi.fn(),+ };+ (childSession as unknown as { _activeRlmChildRuns: Map<string, typeof grandchild> })._activeRlmChildRuns.set(+ "grandchild-1",+ grandchild,+ );++ expect(root.cancelRlmChildRun(childId)).toBe(true);+ expect(grandchild.status).toBe("cancelled");+ expect(abort).toHaveBeenCalled();+ });+it("reports a shared running outcome to concurrent inactive-delete callers", async () => {let runningChecks = 0;const isExternallyRunning = () => ++runningChecks >= 5;diff --git a/packages/coding-agent/test/agents-view-mode.test.ts b/packages/coding-agent/test/agents-view-mode.test.tsindex b4a30cdac1..331745822f 100644--- a/packages/coding-agent/test/agents-view-mode.test.ts+++ b/packages/coding-agent/test/agents-view-mode.test.ts@@ -133,6 +133,35 @@ describe("AgentsViewMode", () => {expect(self.savedSearchFetchStarted).toBe(true);});+ it("stops instead of deleting when an idle row's subtree still works", async () => {+ const request = vi.fn(async () => ({ success: true as const, data: { cancelled: true } }));+ const self = {+ requireClient: () => ({ request, supportsServerCapability: () => true }),+ setStatusMessage: vi.fn(),+ refreshSessions: vi.fn(async () => true),+ };+ const idleWithBusyCrew = {+ kind: "subagent",+ section: "idle",+ runningSubagentCount: 1,+ summary: summary({ id: "crew-parent", activeSessionId: "crew-parent", sessionId: "crew-parent-session" }),+ };++ await invoke(+ "killSubagent",+ self,+ { identity: "child-row", rootActiveSessionId: "root-active", childId: "crew-parent-child" },+ idleWithBusyCrew,+ );++ expect(request).toHaveBeenCalledWith({+ type: "cancel_rlm_child",+ activeSessionId: "root-active",+ childId: "crew-parent-child",+ });+ expect(request).not.toHaveBeenCalledWith(expect.objectContaining({ type: "delete_rlm_subagent" }));+ });+it("re-resolves subagent state before choosing stop or delete intent", async () => {const child = summary({id: "passive-child-session",@@ -241,7 +270,7 @@ describe("AgentsViewMode", () => {"killSubagent",self,{ identity: "child-row", rootActiveSessionId: "root-active", childId: "passive-child" },- { section: "inactive" },+ { section: "inactive", runningSubagentCount: 0, summary: summary() },);expect(request).toHaveBeenCalledWith({type: "cancel_rlm_child",@@ -688,6 +717,38 @@ describe("AgentsViewMode", () => {}});+ it("renders a collapsed group's busy-subagent badge legibly instead of dimmed", () => {+ const parent = summary({ id: "parent", activeSessionId: "parent", sessionId: "parent-session" });+ const busyChild = summary({+ id: "busy-child",+ activeSessionId: "busy-child",+ sessionId: "busy-child-session",+ sessionFile: "/tmp/busy-child.jsonl",+ runtimeKind: "subagent",+ parentActiveSessionId: "parent",+ activity: "working",+ isSessionActive: true,+ isStreaming: true,+ });+ const idleChild = { ...busyChild, activity: "idle" as const, isSessionActive: false, isStreaming: false };+ const view = new AgentsViewMode({ config: {}, uiServices: createUiServices() }, {});++ try {+ const busyRows = buildAgentsViewRows([parent, busyChild]);+ const busySummaryRow = busyRows.find((row) => row.kind === "subagent-summary");+ expect(busySummaryRow).toMatchObject({ section: "idle", title: "1 subagent running" });+ Reflect.set(view, "rows", busyRows);+ expect(invoke("renderRow", view, busySummaryRow, 160)).toContain(theme.fg("success", "▸ 1 subagent running"));++ const idleRows = buildAgentsViewRows([parent, idleChild]);+ const idleSummaryRow = idleRows.find((row) => row.kind === "subagent-summary");+ Reflect.set(view, "rows", idleRows);+ expect(invoke("renderRow", view, idleSummaryRow, 160)).toContain(theme.fg("dim", "▸ 1 subagent"));+ } finally {+ stopThemeWatcher();+ }+ });+it("dims a paused-only heartbeat badge and keeps active badges in the error color", () => {const job = (status: "active" | "paused") => ({job: {diff --git a/packages/coding-agent/test/agents-view-state.test.ts b/packages/coding-agent/test/agents-view-state.test.tsindex 970f0cebfb..b2f89d33c8 100644--- a/packages/coding-agent/test/agents-view-state.test.ts+++ b/packages/coding-agent/test/agents-view-state.test.ts@@ -414,6 +414,166 @@ describe("agents view state", () => {});});+ test("counts a busy grandchild on every idle ancestor without promoting them", () => {+ const summaries = [+ makeSummary({+ id: "parent-active",+ activeSessionId: "parent-active",+ sessionId: "parent-session",+ sessionName: "Parent",+ activity: "idle",+ taskState: "completed",+ hasRunningRlmChildren: true,+ messageCount: 2,+ }),+ makeSummary({+ id: "child-active",+ activeSessionId: "child-active",+ sessionId: "child-session",+ sessionName: "Child",+ runtimeKind: "subagent",+ parentActiveSessionId: "parent-active",+ activity: "idle",+ taskState: "completed",+ }),+ makeSummary({+ id: "grandchild-active",+ activeSessionId: "grandchild-active",+ sessionId: "grandchild-session",+ sessionName: "Grandchild",+ runtimeKind: "subagent",+ parentActiveSessionId: "child-active",+ activity: "working",+ isSessionActive: true,+ isStreaming: true,+ }),+ ];++ const collapsed = buildAgentsViewRows(summaries);+ expect(collapsed[0]).toMatchObject({ kind: "agent", section: "idle", runningSubagentCount: 1 });+ expect(collapsed[0]?.statusLabel).toBe("completed");+ expect(collapsed[1]).toMatchObject({ kind: "subagent-summary", section: "idle", title: "1 subagent running" });++ const expanded = buildAgentsViewRows(summaries, new Set([collapsed[0]?.identity ?? ""]));+ const childRow = expanded.find((row) => row.title === "Child");+ expect(childRow).toMatchObject({ kind: "subagent", section: "idle", runningSubagentCount: 1 });+ });++ test("keeps heartbeat-armed descendants out of the busy tally", () => {+ const summaries = [+ makeSummary({+ id: "parent-active",+ activeSessionId: "parent-active",+ sessionId: "parent-session",+ sessionName: "Parent",+ activity: "idle",+ taskState: "completed",+ messageCount: 2,+ }),+ makeSummary({+ id: "child-active",+ activeSessionId: "child-active",+ sessionId: "child-session",+ sessionName: "Child",+ runtimeKind: "subagent",+ parentActiveSessionId: "parent-active",+ activity: "idle",+ taskState: "completed",+ }),+ makeSummary({+ id: "grandchild-active",+ activeSessionId: "grandchild-active",+ sessionId: "grandchild-session",+ sessionName: "Heartbeat grandchild",+ runtimeKind: "subagent",+ parentActiveSessionId: "child-active",+ hasActiveHeartbeat: true,+ activity: "idle",+ }),+ ];++ const collapsed = buildAgentsViewRows(summaries);+ expect(collapsed[0]?.runningSubagentCount).toBe(0);+ expect(collapsed[1]).toMatchObject({ kind: "subagent-summary", section: "idle", title: "1 subagent" });+ const expanded = buildAgentsViewRows(summaries, new Set([collapsed[0]?.identity ?? ""]));+ expect(expanded.find((row) => row.title === "Child")?.runningSubagentCount).toBe(0);+ });++ test("tallies a very deep child chain without overflowing the stack", () => {+ const summaries = [+ makeSummary({+ id: "chain-root",+ activeSessionId: "chain-root",+ sessionId: "chain-root-session",+ sessionName: "Chain root",+ activity: "idle",+ taskState: "completed",+ messageCount: 2,+ }),+ ];+ const depth = 10_000;+ for (let level = 1; level <= depth; level++) {+ summaries.push(+ makeSummary({+ id: `chain-${level}`,+ activeSessionId: `chain-${level}`,+ sessionId: `chain-${level}-session`,+ sessionName: `Chain ${level}`,+ runtimeKind: "subagent",+ parentActiveSessionId: level === 1 ? "chain-root" : `chain-${level - 1}`,+ ...(level === depth+ ? { activity: "working" as const, isSessionActive: true, isStreaming: true }+ : { activity: "idle" as const, taskState: "completed" as const }),+ }),+ );+ }++ const rows = buildAgentsViewRows(summaries);+ expect(rows[0]).toMatchObject({ kind: "agent", section: "idle", runningSubagentCount: 1 });+ });++ test("ranks idle rows with busy descendants above plain idle rows", () => {+ const rows = buildAgentsViewRows([+ makeSummary({+ id: "plain-idle",+ activeSessionId: "plain-idle",+ sessionId: "plain-session",+ sessionName: "Plain idle",+ activity: "idle",+ taskState: "completed",+ messageCount: 2,+ lastActivityAt: "2026-09-02T00:00:00Z",+ }),+ makeSummary({+ id: "parent-active",+ activeSessionId: "parent-active",+ sessionId: "parent-session",+ sessionName: "Busy-subtree parent",+ activity: "idle",+ taskState: "completed",+ hasRunningRlmChildren: true,+ messageCount: 2,+ lastActivityAt: "2026-08-01T00:00:00Z",+ }),+ makeSummary({+ id: "busy-child",+ activeSessionId: "busy-child",+ sessionId: "busy-child-session",+ sessionName: "Busy child",+ runtimeKind: "subagent",+ parentActiveSessionId: "parent-active",+ activity: "working",+ isSessionActive: true,+ isStreaming: true,+ }),+ ]);++ expect(rows.filter((row) => row.kind === "agent").map((row) => [row.title, row.section])).toEqual([+ ["Busy-subtree parent", "idle"],+ ["Plain idle", "idle"],+ ]);+ });+test("keeps idle heartbeating subagents out of the running count", () => {const heartbeatChildren = Array.from({ length: 10 }, (_, index) =>makeSummary({@@ -600,7 +760,7 @@ describe("agents view state", () => {const oneLevel = buildAgentsViewRows(summaries, new Set([rootIdentity]));expect(oneLevel.map((row) => [row.title, row.kind])).toEqual([["Root", "agent"],- ["1 subagent running", "subagent-summary"],+ ["2 subagents running", "subagent-summary"],["Child", "subagent"],["1 subagent running", "subagent-summary"],]);@@ -609,7 +769,7 @@ describe("agents view state", () => {const twoLevel = buildAgentsViewRows(summaries, new Set([rootIdentity, childIdentity]));expect(twoLevel.map((row) => [row.title, row.kind, row.depth])).toEqual([["Root", "agent", 0],- ["1 subagent running", "subagent-summary", 1],+ ["2 subagents running", "subagent-summary", 1],["Child", "subagent", 1],["1 subagent running", "subagent-summary", 2],["Grandchild", "subagent", 2],diff --git a/packages/coding-agent/test/daemon-mode.test.ts b/packages/coding-agent/test/daemon-mode.test.tsindex 51ec6aee69..0638f19895 100644--- a/packages/coding-agent/test/daemon-mode.test.ts+++ b/packages/coding-agent/test/daemon-mode.test.ts@@ -64,9 +64,10 @@ import {type DaemonOutbound,failure,} from "../src/modes/daemon/daemon-protocol.js";-import type { SessionSummary } from "../src/modes/daemon/daemon-session-list.js";+import { activeActivityForSession, type SessionSummary } from "../src/modes/daemon/daemon-session-list.js";import { DAEMON_WORKER_SUPERVISOR_SOCKET_ENV } from "../src/modes/daemon/daemon-worker-protocol.js";import { RlmSpawnLedger } from "../src/modes/daemon/rlm-ledger.js";+import { WorkerRecoveryJournal } from "../src/modes/daemon/worker-recovery-journal.js";describe("daemon mode helpers", () => {it("preserves envelope client identity while registering prompt admission", () => {@@ -529,7 +530,7 @@ describe("daemon mode helpers", () => {});});- it("classifies local roster status from running-child activity, not armed heartbeats", () => {+ it("classifies local roster status from the session's own work, not heartbeats or delegated children", () => {const daemon = new AgentDaemon("/tmp/prime-agent-status-test.sock", {defaultSessionConfig: { agentDir: "/tmp", cwd: "/tmp" },createRuntime: vi.fn(),@@ -558,7 +559,7 @@ describe("daemon mode helpers", () => {vi.spyOn(internals.cronStore, "getHeartbeat").mockReturnValue({ status: "active" } as AgentCronJob);vi.spyOn(internals.cronStore, "listRlmHeartbeats").mockReturnValue([{ status: "active" } as AgentCronJob]);- expect(internals.createAgentMessageAgentSummary(state).status).toBe("running");+ expect(internals.createAgentMessageAgentSummary(state).status).toBe("idle");hasRunningChildren = false;state.runtime = {...state.runtime,@@ -567,6 +568,50 @@ describe("daemon mode helpers", () => {expect(internals.createAgentMessageAgentSummary(state).status).toBe("idle");});+ it("records live delegated child work as busy for worker recovery while activity stays idle", () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-recovery-busy-"));+ try {+ const daemon = new AgentDaemon(join(tempDir, "daemon.sock"), {+ defaultSessionConfig: { agentDir: tempDir, cwd: tempDir },+ createRuntime: vi.fn(),+ worker: { authenticationToken: "worker-token" },+ });+ const state = makeState("delegating-parent");+ state.runtime = {+ ...state.runtime,+ cwd: tempDir,+ metadata: { kind: "top-level", createdAt: 1 },+ session: {+ sessionId: "delegating-session",+ sessionFile: join(tempDir, "delegating.jsonl"),+ isSessionActive: false,+ isStreaming: false,+ isRetrying: false,+ hasAcceptedPromptInFlight: false,+ messages: [],+ hasRunningRlmChildren: () => true,+ },+ } as never;+ const journalPath = join(tempDir, "recovery.jsonl");+ const internals = daemon as unknown as {+ recoveryJournal?: WorkerRecoveryJournal;+ recordWorkerRecoveryState(state: ActiveSessionState, operation: string): void;+ };+ Object.assign(internals, { recoveryJournal: new WorkerRecoveryJournal(journalPath) });++ internals.recordWorkerRecoveryState(state, "turn_end");++ // Recovery: the child dies with the worker, so the parent had work in flight.+ expect(WorkerRecoveryJournal.readLatest(journalPath)).toEqual([+ expect.objectContaining({ activeSessionId: "delegating-parent", busy: true, operation: "turn_end" }),+ ]);+ // Display: the same state's activity axis reports the session's own (idle) work.+ expect(activeActivityForSession(state)).toBe("idle");+ } finally {+ rmSync(tempDir, { recursive: true, force: true });+ }+ });+it("reserves a session name across equivalent session-relative parent headers", async () => {const daemon = new AgentDaemon("/tmp/prime-agent-name-reservation.sock", {defaultSessionConfig: { agentDir: "/tmp", cwd: "/tmp" },diff --git a/packages/coding-agent/test/daemon-session-list.test.ts b/packages/coding-agent/test/daemon-session-list.test.tsindex df7ab94ddd..75f2a0b50f 100644--- a/packages/coding-agent/test/daemon-session-list.test.ts+++ b/packages/coding-agent/test/daemon-session-list.test.ts@@ -127,7 +127,7 @@ describe("buildSessionList", () => {expect(summary.lastActivityAt).toBe(new Date(validTimestamp).toISOString());});- it("keeps a session working while background subagents run", () => {+ it("keeps background subagents on the wire while the settled parent goes idle", () => {const oneMessage = [{ role: "user", content: "hi" }] as unknown as AgentMessage[];const entries = buildSessionList([@@ -142,7 +142,7 @@ describe("buildSessionList", () => {],[],);- expect(entries[0]?.activity).toBe("working");+ expect(entries[0]?.activity).toBe("idle");expect(entries[0]?.hasRunningRlmChildren).toBe(true);});