Skip to content

Commit f4f990a

Browse files
steipetePeter Steinberger
andauthored
fix(agents): use canonical subagent terminal status across views (#116991)
Co-authored-by: Peter Steinberger <[email protected]>
1 parent 47c39b1 commit f4f990a

8 files changed

Lines changed: 183 additions & 62 deletions

File tree

‎src/agents/subagent-list.test.ts‎

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import path from "node:path";
66
import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
77
import type { OpenClawConfig } from "../config/config.js";
88
import { replaceSessionEntry } from "../config/sessions/session-accessor.js";
9+
import { SUBAGENT_ENDED_REASON_KILLED } from "./subagent-lifecycle-events.js";
910
import { buildSubagentList } from "./subagent-list.js";
1011
import {
1112
addSubagentRunForTests,
@@ -108,6 +109,64 @@ describe("buildSubagentList", () => {
108109
expect(list.active[0]?.line).toContain("review_subagents: Review worker");
109110
});
110111

112+
it.each([
113+
{
114+
name: "a killed run with a provider failure",
115+
endedReason: SUBAGENT_ENDED_REASON_KILLED,
116+
outcome: { status: "error", error: "agent run aborted" } as const,
117+
expectedStatus: "killed",
118+
},
119+
{
120+
name: "a killed run with an earlier successful provider outcome",
121+
endedReason: SUBAGENT_ENDED_REASON_KILLED,
122+
outcome: { status: "ok" } as const,
123+
expectedStatus: "killed",
124+
},
125+
{
126+
name: "a failed run",
127+
outcome: { status: "error", error: "provider rejected the request" } as const,
128+
expectedStatus: "failed",
129+
},
130+
{
131+
name: "a timed-out run",
132+
outcome: { status: "timeout" } as const,
133+
expectedStatus: "timeout",
134+
},
135+
{
136+
name: "a completed run",
137+
outcome: { status: "ok" } as const,
138+
expectedStatus: "done",
139+
},
140+
])(
141+
"projects the canonical terminal status for $name",
142+
({ endedReason, outcome, expectedStatus }) => {
143+
const now = Date.now();
144+
const run = {
145+
runId: `run-status-${expectedStatus}`,
146+
childSessionKey: `agent:main:subagent:status-${expectedStatus}`,
147+
requesterSessionKey: "agent:main:main",
148+
requesterDisplayKey: "main",
149+
task: "report the actual child outcome",
150+
cleanup: "keep",
151+
createdAt: now - 2_000,
152+
startedAt: now - 2_000,
153+
endedAt: now - 1_000,
154+
...(endedReason ? { endedReason } : {}),
155+
outcome,
156+
} satisfies SubagentRunRecord;
157+
addSubagentRunForTests(run);
158+
159+
const list = buildSubagentList({
160+
cfg: {} as OpenClawConfig,
161+
runs: [run],
162+
recentMinutes: 30,
163+
});
164+
165+
expect(list.recent[0]?.status).toBe(expectedStatus);
166+
expect(list.recent[0]?.line).toContain(` ${expectedStatus}`);
167+
},
168+
);
169+
111170
it("keeps ended orchestrators active while descendants remain pending", () => {
112171
// Parent orchestrators can finish their own turn before child workers do;
113172
// list output should keep them active until descendants settle.

‎src/agents/subagent-list.ts‎

Lines changed: 2 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -26,10 +26,10 @@ import {
2626
import { getSubagentRunsSnapshotForRead } from "./subagent-registry-state.js";
2727
import type { SubagentRunRecord } from "./subagent-registry.types.js";
2828
import {
29-
hasSubagentRunEnded,
3029
isLiveUnendedSubagentRun,
3130
shouldKeepSubagentRunChildLink,
3231
} from "./subagent-run-liveness.js";
32+
import { resolveSubagentDisplayStatus } from "./subagent-session-metrics.js";
3333

3434
type SubagentListItem = {
3535
index: number;
@@ -144,25 +144,6 @@ function isActiveSubagentRun(
144144
return isLiveUnendedSubagentRun(entry) || pendingDescendantCount(entry.childSessionKey) > 0;
145145
}
146146

147-
function resolveRunStatus(entry: SubagentRunRecord, options?: { pendingDescendants?: number }) {
148-
const pendingDescendants = Math.max(0, options?.pendingDescendants ?? 0);
149-
if (pendingDescendants > 0) {
150-
const childLabel = pendingDescendants === 1 ? "child" : "children";
151-
return `active (waiting on ${pendingDescendants} ${childLabel})`;
152-
}
153-
if (!hasSubagentRunEnded(entry)) {
154-
return "running";
155-
}
156-
const status = entry.outcome?.status ?? "done";
157-
if (status === "ok") {
158-
return "done";
159-
}
160-
if (status === "error") {
161-
return "failed";
162-
}
163-
return status;
164-
}
165-
166147
function resolveModelRef(entry?: SessionEntry, fallbackModel?: string) {
167148
return resolveModelDisplayRef({
168149
runtimeProvider: entry?.modelProvider,
@@ -240,9 +221,7 @@ export function buildSubagentList(params: {
240221
const totalTokens = resolveTotalTokens(sessionEntry);
241222
const usageText = formatTokenUsageDisplay(sessionEntry);
242223
const pendingDescendants = pendingDescendantCount(entry.childSessionKey);
243-
const status = resolveRunStatus(entry, {
244-
pendingDescendants,
245-
});
224+
const status = resolveSubagentDisplayStatus(entry, pendingDescendants);
246225
const childSessions = childSessionsByController.get(entry.childSessionKey) ?? [];
247226
const runtime = formatDurationCompact(runtimeMs) ?? "n/a";
248227
const label = truncateLine(resolveSubagentLabel(entry), 48);

‎src/agents/subagent-session-metrics.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,3 +76,16 @@ export function resolveSubagentSessionStatus(
7676
}
7777
return "done";
7878
}
79+
80+
/** Formats the authoritative run status while preserving unfinished descendants. */
81+
export function resolveSubagentDisplayStatus(
82+
entry: Pick<SubagentRunRecord, "endedAt" | "endedReason" | "outcome">,
83+
pendingDescendants = 0,
84+
): string {
85+
const pending = Math.max(0, pendingDescendants);
86+
if (pending > 0) {
87+
const childLabel = pending === 1 ? "child" : "children";
88+
return `active (waiting on ${pending} ${childLabel})`;
89+
}
90+
return resolveSubagentSessionStatus(entry) ?? "done";
91+
}

‎src/agents/tools/subagents-tool.test.ts‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,12 @@
22
import { describe, expect, it, vi } from "vitest";
33
import type { TaskRecord, TaskRuntime, TaskStatus } from "../../tasks/task-registry.types.js";
44
import { TASK_STATUS_DETAIL_MAX_CHARS } from "../../tasks/task-status.js";
5+
import { SUBAGENT_ENDED_REASON_KILLED } from "../subagent-lifecycle-events.js";
6+
import {
7+
addSubagentRunForTests,
8+
resetSubagentRegistryForTests,
9+
} from "../subagent-registry.test-helpers.js";
10+
import type { SubagentRunRecord } from "../subagent-registry.types.js";
511
import { createSubagentsTool } from "./subagents-tool.js";
612

713
function task(params: {
@@ -47,6 +53,44 @@ describe("subagents tool", () => {
4753
);
4854
});
4955

56+
it("reports a killed subagent truthfully through the actual list tool", async () => {
57+
resetSubagentRegistryForTests();
58+
const now = Date.now();
59+
const run = {
60+
runId: "run-tool-killed",
61+
childSessionKey: "agent:main:subagent:tool-killed",
62+
controllerSessionKey: "agent:main:main",
63+
requesterSessionKey: "agent:main:main",
64+
requesterDisplayKey: "main",
65+
task: "report the killed child",
66+
cleanup: "keep",
67+
createdAt: now - 2_000,
68+
startedAt: now - 2_000,
69+
endedAt: now - 1_000,
70+
endedReason: SUBAGENT_ENDED_REASON_KILLED,
71+
outcome: { status: "error", error: "agent run aborted" },
72+
} satisfies SubagentRunRecord;
73+
addSubagentRunForTests(run);
74+
75+
try {
76+
const tool = createSubagentsTool({
77+
agentSessionKey: "agent:main:main",
78+
config: {},
79+
listTasks: () => [],
80+
});
81+
82+
const result = await tool.execute("list-killed", { action: "list" });
83+
84+
expect(result.details).toMatchObject({
85+
status: "ok",
86+
recent: [expect.objectContaining({ runId: run.runId, status: "killed" })],
87+
});
88+
expect((result.details as { text: string }).text).toContain(" killed");
89+
} finally {
90+
resetSubagentRegistryForTests();
91+
}
92+
});
93+
5094
it("lists cross-runtime tasks in the caller session tree", async () => {
5195
const tasks = [
5296
task({

‎src/auto-reply/reply/commands-subagents.test.ts‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import os from "node:os";
88
import path from "node:path";
99
import { beforeEach, describe, expect, it, vi } from "vitest";
10+
import { SUBAGENT_ENDED_REASON_KILLED } from "../../agents/subagent-lifecycle-events.js";
1011
import { subagentRuns } from "../../agents/subagent-registry-memory.js";
1112
import {
1213
countPendingDescendantRunsFromRuns,
@@ -26,6 +27,7 @@ import type { ReplyPayload } from "../types.js";
2627
import { buildSubagentsStatusLine } from "./commands-status-subagents.js";
2728
import { extractMessageText } from "./commands-subagents-text.js";
2829
import { handleSubagentsInfoAction } from "./commands-subagents/action-info.js";
30+
import { handleSubagentsListAction } from "./commands-subagents/action-list.js";
2931
import { handleSubagentsLogAction } from "./commands-subagents/action-log.js";
3032
import { resolveFocusTargetSession } from "./commands-subagents/shared.js";
3133
import {
@@ -233,6 +235,62 @@ describe("subagents info", () => {
233235
expect(text).toContain("Task summary: Completed the requested task");
234236
});
235237

238+
it.each([
239+
{
240+
name: "a killed run despite its provider error",
241+
endedReason: SUBAGENT_ENDED_REASON_KILLED,
242+
outcome: { status: "error", error: "agent run aborted" } as const,
243+
expectedStatus: "killed",
244+
},
245+
{
246+
name: "a killed run despite its earlier successful result",
247+
endedReason: SUBAGENT_ENDED_REASON_KILLED,
248+
outcome: { status: "ok" } as const,
249+
expectedStatus: "killed",
250+
},
251+
{
252+
name: "a failed run",
253+
outcome: { status: "error", error: "provider rejected the request" } as const,
254+
expectedStatus: "failed",
255+
},
256+
{
257+
name: "a timed-out run",
258+
outcome: { status: "timeout" } as const,
259+
expectedStatus: "timeout",
260+
},
261+
])(
262+
"keeps /subagents info and list aligned for $name",
263+
({ endedReason, outcome, expectedStatus }) => {
264+
const now = Date.now();
265+
const run = {
266+
runId: `commands-subagents-status-${expectedStatus}`,
267+
childSessionKey: `agent:main:subagent:commands-status-${expectedStatus}`,
268+
requesterSessionKey: "agent:main:main",
269+
requesterDisplayKey: "main",
270+
task: "report the actual child outcome",
271+
cleanup: "keep",
272+
createdAt: now - 2_000,
273+
startedAt: now - 2_000,
274+
endedAt: now - 1_000,
275+
...(endedReason ? { endedReason } : {}),
276+
outcome,
277+
} satisfies SubagentRunRecord;
278+
addSubagentRunForTests(run);
279+
const context = buildInfoContext({
280+
cfg: buildCommandTestConfig(),
281+
runs: [run],
282+
restTokens: ["1"],
283+
});
284+
285+
expect(requireReplyText(handleSubagentsInfoAction(context).reply)).toContain(
286+
`Status: ${expectedStatus}`,
287+
);
288+
expect(requireReplyText(handleSubagentsListAction(context).reply)).toContain(
289+
` ${expectedStatus}`,
290+
);
291+
},
292+
);
293+
236294
it("omits Date-invalid subagent timestamps", () => {
237295
const runId = "commands-subagents-info-invalid-date-run";
238296
const childSessionKey = "agent:main:subagent:commands-info-invalid-date";

‎src/auto-reply/reply/commands-subagents/action-info.ts‎

Lines changed: 6 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { timestampMsToIsoString } from "@openclaw/normalization-core/number-coer
33
import { subagentRuns } from "../../../agents/subagent-registry-memory.js";
44
import { countPendingDescendantRunsFromRuns } from "../../../agents/subagent-registry-queries.js";
55
import { getSubagentRunsSnapshotForRead } from "../../../agents/subagent-registry-state.js";
6+
import { resolveSubagentDisplayStatus } from "../../../agents/subagent-session-metrics.js";
67
import { resolveStorePath } from "../../../config/sessions/paths.js";
78
import { loadSessionEntryReadOnly } from "../../../config/sessions/session-accessor.js";
89
import { formatTimeAgo } from "../../../infra/format-time/format-relative.ts";
@@ -11,7 +12,7 @@ import { formatDurationCompact } from "../../../shared/subagents-format.js";
1112
import { findTaskByRunIdForOwner } from "../../../tasks/task-owner-access.js";
1213
import { sanitizeTaskStatusText } from "../../../tasks/task-status.js";
1314
import type { CommandHandlerResult } from "../commands-types.js";
14-
import { formatRunLabel, formatRunStatus } from "../subagents-utils.js";
15+
import { formatRunLabel } from "../subagents-utils.js";
1516
import {
1617
resolveSubagentEntryForToken,
1718
stopWithText,
@@ -29,19 +30,6 @@ function formatTimestampWithAge(valueMs?: number) {
2930
return `${timestamp} (${formatTimeAgo(Date.now() - valueMs, { fallback: "n/a" })})`;
3031
}
3132

32-
function resolveDisplayStatus(
33-
entry: SubagentsCommandContext["runs"][number],
34-
options?: { pendingDescendants?: number },
35-
) {
36-
const pendingDescendants = Math.max(0, options?.pendingDescendants ?? 0);
37-
if (pendingDescendants > 0) {
38-
const childLabel = pendingDescendants === 1 ? "child" : "children";
39-
return `active (waiting on ${pendingDescendants} ${childLabel})`;
40-
}
41-
const status = formatRunStatus(entry);
42-
return status === "error" ? "failed" : status;
43-
}
44-
4533
function loadSubagentSessionEntry(params: SubagentsCommandContext["params"], childKey: string) {
4634
const parsed = parseAgentSessionKey(childKey);
4735
const storePath = resolveStorePath(params.cfg.session?.store, {
@@ -91,12 +79,13 @@ export function handleSubagentsInfoAction(ctx: SubagentsCommandContext): Command
9179

9280
const lines = [
9381
"ℹ️ Subagent info",
94-
`Status: ${resolveDisplayStatus(run, {
95-
pendingDescendants: countPendingDescendantRunsFromRuns(
82+
`Status: ${resolveSubagentDisplayStatus(
83+
run,
84+
countPendingDescendantRunsFromRuns(
9685
getSubagentRunsSnapshotForRead(subagentRuns),
9786
run.childSessionKey,
9887
),
99-
})}`,
88+
)}`,
10089
`Label: ${formatRunLabel(run)}`,
10190
`Task: ${taskText}`,
10291
`Run: ${run.runId}`,

‎src/auto-reply/reply/reply-plumbing.test.ts‎

Lines changed: 1 addition & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -14,12 +14,7 @@ import {
1414
import type { TemplateContext } from "../templating.js";
1515
import { buildThreadingToolContext } from "./agent-runner-utils.js";
1616
import { applyReplyThreading } from "./reply-payloads.js";
17-
import {
18-
formatRunLabel,
19-
formatRunStatus,
20-
resolveSubagentLabel,
21-
sortSubagentRuns,
22-
} from "./subagents-utils.js";
17+
import { formatRunLabel, resolveSubagentLabel, sortSubagentRuns } from "./subagents-utils.js";
2318

2419
function createSlackThreadingPlugin(): ChannelPlugin {
2520
return {
@@ -484,14 +479,6 @@ describe("subagents utils", () => {
484479
expect(sorted.map((run) => run.runId)).toEqual(["run-2", "run-1", "run-3"]);
485480
});
486481

487-
it("formats run status from outcome and timestamps", () => {
488-
expect(formatRunStatus({ ...baseRun })).toBe("running");
489-
expect(formatRunStatus({ ...baseRun, endedAt: 2000, outcome: { status: "ok" } })).toBe("done");
490-
expect(formatRunStatus({ ...baseRun, endedAt: 2000, outcome: { status: "timeout" } })).toBe(
491-
"timeout",
492-
);
493-
});
494-
495482
it("formats duration compact for seconds and minutes", () => {
496483
expect(formatDurationCompact(45_000)).toBe("45s");
497484
expect(formatDurationCompact(65_000)).toBe("1m5s");

‎src/auto-reply/reply/subagents-utils.ts‎

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -21,14 +21,6 @@ export function formatRunLabel(entry: SubagentRunRecord, options?: { maxLength?:
2121
return raw.length > maxLength ? `${truncateUtf16Safe(raw, maxLength).trimEnd()}…` : raw;
2222
}
2323

24-
export function formatRunStatus(entry: SubagentRunRecord) {
25-
if (!entry.endedAt) {
26-
return "running";
27-
}
28-
const status = entry.outcome?.status ?? "done";
29-
return status === "ok" ? "done" : status;
30-
}
31-
3224
export function sortSubagentRuns(runs: SubagentRunRecord[]) {
3325
return [...runs].toSorted((a, b) => {
3426
const aTime = a.startedAt ?? a.createdAt ?? 0;

0 commit comments

Comments
 (0)