Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(subagents): keep parent-error interruptions resumable

xjxb2486d2a2f2f
diff --git a/docs/adr/0279-resumable-subagent-delegations.md b/docs/adr/0279-resumable-subagent-delegations.md
index 1a7a46aaf..b699c20cb 100644
--- a/docs/adr/0279-resumable-subagent-delegations.md
+++ b/docs/adr/0279-resumable-subagent-delegations.md
@@ -115,8 +115,11 @@ the same conversation to a different model with no trace.
A `failed` run's reads and findings still have value; its failed assistant row
is dropped by the converter like any other error row. `stopped` and `aborted`
-encode the user's or the parent's decision to abandon that line of work, and
-resuming it would contradict the stop. `interrupted` (the app closed while the
+encode an explicit Stop or runtime disposal, and resuming it would contradict
+the cancellation. A terminal parent error still cancels active execution, but
+its interrupted delegates settle as `failed` with `SUBAGENT_PARENT_FAILED`
+instead: this system interruption preserves manual resume eligibility (#680).
+`interrupted` (the app closed while the
run still worked) means the same thing for this purpose: the delegate never
settled, so there is nothing trustworthy to continue. (`timed_out` is a vestigial
status — ADR 0119's timeouts were withdrawn by D328 — and is treated as `failed`
diff --git a/docs/spec/03-runtime/02-agent-runtime.md b/docs/spec/03-runtime/02-agent-runtime.md
index 139ca9421..4d0ffdc15 100644
--- a/docs/spec/03-runtime/02-agent-runtime.md
+++ b/docs/spec/03-runtime/02-agent-runtime.md
@@ -983,7 +983,10 @@ ends at the provider's output-token limit (`stopReason: "length"` or
bounded partial report remains under the failure explanation for diagnosis. A
later delegate turn that ends normally clears the marker and can complete. A
terminal parent error also aborts leftover delegates, skips the resume prompt,
-and returns the session to idle so Continue is not `AGENT_BUSY` (D352).
+and returns the session to idle so Continue is not `AGENT_BUSY` (D352). The
+interrupted delegates settle as `failed` with `SUBAGENT_PARENT_FAILED` and keep
+their transcript-backed resume eligibility. This does not automatically restart
+them; user Stop, TaskStop and dispose still settle as non-resumable cancellations.
**Resumable delegations (ADR 0279).** `Task` accepts an optional `resume`
parameter carrying the `delegationId` of a settled delegation in the same
diff --git a/docs/spec/03-runtime/08-error-codes.md b/docs/spec/03-runtime/08-error-codes.md
index 8e0a6edff..222ebe340 100644
--- a/docs/spec/03-runtime/08-error-codes.md
+++ b/docs/spec/03-runtime/08-error-codes.md
@@ -114,6 +114,7 @@ does not turn temporary thread pressure into a host process exit.
| `SUBAGENT_DURATION_TIMEOUT` | no | withdrawn (D328): duration watchdogs are not armed; the code remains for stored results |
| `SUBAGENT_CONTEXT_OVERFLOW` | no | a delegate's own model context exceeded its safe budget and neither automatic turn-boundary compaction nor the degraded retry that keeps only the task brief and the most recent messages brought it back below the limit; the failure names the actionable recovery instead of the provider's overflow text |
| `SUBAGENT_OUTPUT_TRUNCATED` | no | a delegate's report ended at the model output-token limit; the partial report is preserved for diagnosis, but the run is failed rather than presented as a completed delegation |
+| `SUBAGENT_PARENT_FAILED` | no | parent failure interrupted a running delegate; its chain remains manually resumable with Task, subject to the existing history and read-budget gates |
### 3.3 Workspace / tools / permissions
| code | retriable | meaning |
diff --git a/docs/spec/03-runtime/10-session-state-machine.md b/docs/spec/03-runtime/10-session-state-machine.md
index 11f18f1e3..2bd5f3e9c 100644
--- a/docs/spec/03-runtime/10-session-state-machine.md
+++ b/docs/spec/03-runtime/10-session-state-machine.md
@@ -158,7 +158,9 @@ turn that has ended.
snapshot.
17. A terminal parent provider/stream error aborts leftover delegates and
returns the session to idle so Continue is accepted. Parent idle with
- running delegates still keeps the turn open (D328 / D352).
+ running delegates still keeps the turn open (D328 / D352). System-interrupted
+ delegates settle as failed and remain manually resumable; explicit Stop and
+ dispose remain non-resumable cancellations.
## 4. Persistence points
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index dc1b2ab1e..b404aecf6 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -16554,3 +16554,21 @@ startup probing. Explicit selections keep their bin directory first. Missing
installations still return `npm-unavailable` and retain native picker recovery.
The executable integration fixture uses real isolated child processes and checks
registry-only installation and credential isolation.
+
+
+#### E2E-CHAT-subagent-parent-error-resume
+
+- **Preconditions**: Built agent runtime and a loopback provider fixture; real
+ Agent, SDK transport, Task/TaskStop and delegate history. Host Read is a fixture.
+- **Steps**: Spawn two delegates, let each finish a Read, then leave both provider
+ streams active. Fail the parent request, send a later prompt with both resume
+ ids, and inspect the resumed requests. Repeat with user Stop and TaskStop.
+- **Expected**: Parent failure returns the session to idle; both delegates settle
+ failed with SUBAGENT_PARENT_FAILED and resume with their own prior Read context.
+ Explicit Stop/TaskStop produce aborted/stopped; both resume attempts are rejected
+ without starting another delegate. No automatic restart occurs.
+- **Specs linked**: 03-runtime/02-agent-runtime.md §5f; ADR 0279.
+- **Acceptance**: C, E, Quality. **Milestone**: Maintenance.
+- **Status**: Automated headless runtime/provider integration via
+ `node scripts/e2e-subagent-parent-error.mjs`; no real accounts or Desktop data.
+ Runtime tests separately cover exhausted parent 429 and Stop racing settlement.
diff --git a/docs/zh-CN/spec/03-runtime/02-agent-runtime.md b/docs/zh-CN/spec/03-runtime/02-agent-runtime.md
index 03346fba5..9b52cdda6 100644
--- a/docs/zh-CN/spec/03-runtime/02-agent-runtime.md
+++ b/docs/zh-CN/spec/03-runtime/02-agent-runtime.md
@@ -702,7 +702,9 @@ Stop / 运行时销毁。主 Agent 用 `TaskStop` 判断要不要取消;运行
`SUBAGENT_OUTPUT_TRUNCATED` 和 `outputTruncated: true` 结算;有界的部分报告会保留在失败说明
下,供诊断截断原因。后续以正常原因结束的委派回合会清除该标记并可以成功完成。
父级终态错误还会中止残留委托、跳过续跑提示,并把会话恢复为空闲,这样
-“继续”不会变成 `AGENT_BUSY`(D352)。
+“继续”不会变成 `AGENT_BUSY`(D352)。 被系统中断的委托以
+`failed` 和 `SUBAGENT_PARENT_FAILED` 结算,保留基于历史的恢复资格,但不会自动重启。
+用户 Stop、TaskStop 与运行时销毁仍按不可恢复的取消处理。
**可恢复的委托(ADR 0279)。** `Task` 接受一个可选的 `resume` 参数,携带同一会话中
某个已结算委托的 `delegationId`。恢复后的委托是一个新的 `SubagentRun`,以该链此前的
diff --git a/docs/zh-CN/spec/03-runtime/08-error-codes.md b/docs/zh-CN/spec/03-runtime/08-error-codes.md
index 8b0fbb458..a7d42bc46 100644
--- a/docs/zh-CN/spec/03-runtime/08-error-codes.md
+++ b/docs/zh-CN/spec/03-runtime/08-error-codes.md
@@ -115,6 +115,7 @@ stdio 与 Tokio 的动态阻塞池隔离,因此后一种情况
| `SUBAGENT_DURATION_TIMEOUT` | 不 | 已撤回(D328):时长看门狗不再武装;代码仅为已存储结果保留 |
| `SUBAGENT_CONTEXT_OVERFLOW` | 不 | 委派自身的模型上下文超出其安全预算,自动的回合边界压缩与仅保留任务简报和最近消息的降级重试都没能把它带回限制以内;该失败给出可执行的恢复方式,而不是提供商的溢出文本 |
| `SUBAGENT_OUTPUT_TRUNCATED` | 不 | 委派报告在模型输出 token 上限处结束;保留部分报告用于诊断,但该运行报告为失败,不会被呈现为已完成的委派 |
+| `SUBAGENT_PARENT_FAILED` | 不 | 父级失败中断了运行中的委托;可通过 Task 手动恢复,仍受现有历史与读取预算限制 |
### 3. 3 工作空间/工具/权限
diff --git a/docs/zh-CN/spec/03-runtime/10-session-state-machine.md b/docs/zh-CN/spec/03-runtime/10-session-state-machine.md
index aed1a8a09..c2cd99233 100644
--- a/docs/zh-CN/spec/03-runtime/10-session-state-machine.md
+++ b/docs/zh-CN/spec/03-runtime/10-session-state-machine.md
@@ -103,7 +103,7 @@ accept_prompt
工具行开始,中止保留部分转录本并恢复不
草稿。
4. 权限超时变为工具被拒绝,然后代理可以根据运行时处理继续或结束
-5. 终端回合状态持久后,会话状态返回空闲状态。父级终态错误会中止残留委托,因此“继续”不会变成 `AGENT_BUSY`(D352)
+5. 终端回合状态持久后,会话状态返回空闲状态。父级终态错误会中止残留委托,因此“继续”不会变成 `AGENT_BUSY`(D352)。系统中断的委托以失败结算并保留手动恢复资格;显式 Stop 和销毁仍不可恢复
6. 更改渲染器的活动 project/session 不会转换或中止
任何后台会话
7. 工具转换保留原始会话的持久项目根;
diff --git a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
index 30d26e19d..e2d60e875 100644
--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
@@ -9337,3 +9337,20 @@ the latest destination. These assertions measure work counts, not device FPS.
校验和 npm 两个安装阶段都必须使用该安装,同时保留应用自身的 `PATH`,且不探测 shell 启动文件。
显式选择的 npm 仍优先使用其所在目录。缺少安装时仍返回 `npm-unavailable` 并保留原生选择器恢复路径。
可执行集成 fixture 使用真实隔离子进程,并检查仅注册表安装和凭据隔离。
+
+
+#### E2E-CHAT-subagent-parent-error-resume
+
+- **前置条件**:编译后的运行时与本地 provider 模拟服务;使用真实 Agent、SDK 传输、
+ Task/TaskStop 和委托历史,仅模拟 Host Read 边界。
+- **步骤**:启动两个委托,各自完成一次 Read,再让两条 provider 流保持活动。
+ 使父级请求失败;在后续提示中恢复两个 id,并检查恢复请求。分别重复用户 Stop
+ 和 TaskStop 场景。
+- **预期**:父级失败后会话回到空闲;两个委托以 failed 和 SUBAGENT_PARENT_FAILED
+ 结算,并各自带着原来的 Read 上下文恢复。显式 Stop/TaskStop 产生 aborted/stopped;
+ 两个恢复请求均被拒绝,不再启动委托。不会自动重启。
+- **关联规格**:03-runtime/02-agent-runtime.md §5f;ADR 0279。
+- **验收**:C、E、Quality。**里程碑**:维护。
+- **状态**:通过 `node scripts/e2e-subagent-parent-error.mjs` 自动验证无头运行时与
+ provider 集成;不使用真实账户或桌面数据。运行时测试另行覆盖父级 429 耗尽与
+ Stop 和结算之间的竞态。
diff --git a/package.json b/package.json
index 6a1ee20a2..da4d23bc2 100644
--- a/package.json
+++ b/package.json
@@ -55,6 +55,7 @@
"test:e2e:work-panel-reorder": "node scripts/e2e-work-panel-reorder.mjs",
"test:e2e:supervision": "node scripts/e2e-supervision.mjs",
"test:e2e:subagents": "node scripts/e2e-subagents.mjs",
+ "test:e2e:subagent-parent-error": "node scripts/e2e-subagent-parent-error.mjs",
"test:e2e:subagent-models": "node scripts/e2e-subagent-models.mjs",
"check:marketplace": "node scripts/check-marketplace-catalog.mjs",
"check:pi-dependencies": "node scripts/check-pi-dependencies.mjs",
diff --git a/packages/agent-runtime/src/runtime.test.ts b/packages/agent-runtime/src/runtime.test.ts
index e84ea5fa4..ab5949882 100644
--- a/packages/agent-runtime/src/runtime.test.ts
+++ b/packages/agent-runtime/src/runtime.test.ts
@@ -7916,7 +7916,7 @@ describe("DesktopAgentRuntime subagents", () => {
await runtime.dispose();
});
- it("aborts leftover delegates on parent rate-limit exhaustion so the session can continue", async () => {
+ it("keeps interrupted delegates resumable after parent rate-limit exhaustion", async () => {
const onEvent = vi.fn();
const runtime = createRuntime({ subagents: [explorer], onEvent });
subagentRuns.calls.length = 0;
@@ -7971,9 +7971,12 @@ describe("DesktopAgentRuntime subagents", () => {
await vi.waitFor(() => {
expect((runtime as any).delegations.get(delegationId).status).toBe(
- "aborted",
+ "failed",
);
});
+ expect((runtime as any).delegationChains.resolveResume({
+ resume: delegationId, agentName: "explorer", runningDelegationIds: new Set(),
+ }).ok).toBe(true);
const prompt = vi.fn(async () => undefined);
(runtime as any).agent.prompt = prompt;
@@ -8564,6 +8567,78 @@ describe("DesktopAgentRuntime subagents", () => {
};
}
+ it("resumes both delegates interrupted by parent failure with their own history", async () => {
+ const runtime = createRuntime({ subagents: [explorer] });
+ const internals = runtime as any;
+ subagentRuns.calls.length = 0;
+ subagentRuns.instances.length = 0;
+ subagentRuns.result = undefined;
+ subagentRuns.deferred = true;
+ try {
+ const ids: string[] = [];
+ for (let index = 0; index < 2; index++) {
+ const callId = `original-${index}`;
+ const started = await startTask(runtime, callId, { agent: "explorer", task: `Task ${index}` });
+ ids.push((started.details as any).delegationId);
+ subagentRuns.calls[index].onEvent(delegateEnvelope(callId, { type: "message_end", message: {
+ id: `child-${index}`, role: "assistant", content: `Finding ${index}`,
+ createdAt: "2026-10-04T00:00:00.000Z", status: "complete",
+ } }));
+ }
+ internals.terminateParentTurn();
+ await vi.waitFor(() => {
+ expect(ids.map((id) => internals.delegations.get(id).status)).toEqual(["failed", "failed"]);
+ });
+ expect(internals.runningDelegations()).toHaveLength(0);
+ for (const id of ids) {
+ expect(internals.delegations.get(id).result).toMatchObject({ status: "failed",
+ error: { code: "SUBAGENT_PARENT_FAILED", resumeId: id } });
+ }
+ internals.agent.prompt = vi.fn(async () => undefined);
+ internals.agent.waitForIdle = vi.fn(async () => undefined);
+ await runtime.prompt("Continue the failed delegates");
+ subagentRuns.deferred = false;
+ for (let index = 0; index < 2; index++) {
+ const result = await startTask(runtime, `resumed-${index}`, {
+ agent: "explorer", task: "Continue", resume: ids[index],
+ });
+ expect((result.details as any).resumedFrom).toBe(ids[index]);
+ const context = JSON.stringify(subagentRuns.calls.at(-1).initialMessages);
+ expect(context).toContain(`Finding ${index}`);
+ expect(context).not.toContain(`Finding ${1 - index}`);
+ }
+ } finally {
+ subagentRuns.deferred = false;
+ await runtime.dispose();
+ }
+ });
+
+ it.each(["abort", "TaskStop"])("explicit %s wins over a pending parent-error interruption", async (action) => {
+ const runtime = createRuntime({ subagents: [explorer] });
+ const internals = runtime as any;
+ subagentRuns.calls.length = 0;
+ subagentRuns.instances.length = 0;
+ subagentRuns.deferred = true;
+ subagentRuns.ignoreAbort = true;
+ try {
+ const started = await startTask(runtime, "original", { agent: "explorer", task: "Find it" });
+ const id = (started.details as any).delegationId;
+ internals.terminateParentTurn();
+ const cancelled = action === "abort" ? runtime.abort() : internals.agent.state.tools
+ .find((tool: any) => tool.name === "TaskStop").execute("stop", { delegationIds: [id] });
+ subagentRuns.resolveRun?.({ agentName: "explorer", status: "aborted", report: "Aborted",
+ turns: 1, toolCalls: 0 });
+ await cancelled;
+ await vi.waitFor(() => expect(internals.delegations.get(id).status).toBe(action === "abort" ? "aborted" : "stopped"));
+ expect(internals.delegationChains.resolveResume({ resume: id, agentName: "explorer",
+ runningDelegationIds: new Set() }).ok).toBe(false);
+ } finally {
+ subagentRuns.ignoreAbort = false;
+ subagentRuns.deferred = false;
+ await runtime.dispose();
+ }
+ });
+
it("records a delegate's reads in-session so the same session can resume them", async () => {
const runtime = createRuntime({ subagents: [explorer] });
const internals = runtime as any;
@@ -8687,9 +8762,10 @@ describe("DesktopAgentRuntime subagents", () => {
await runtime.dispose();
});
- it("resumes a chain a restart rebuilt from a completed Task row", async () => {
+ it.each(["completed", "failed"])("resumes a chain a restart rebuilt from a %s Task row", async (status) => {
const history: UiMessage[] = [
- restartedTaskRow("task-1", "del-1", { status: "completed" }),
+ restartedTaskRow("task-1", "del-1", { status,
+ ...(status === "failed" ? { error: { code: "SUBAGENT_PARENT_FAILED" } } : {}) }),
delegateRow("child-1", "task-1"),
];
const runtime = createRuntime({ subagents: [explorer], history });
diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.ts
index 97fa98d24..7fcf036af 100644
--- a/packages/agent-runtime/src/runtime.ts
+++ b/packages/agent-runtime/src/runtime.ts
@@ -190,6 +190,7 @@ import {
} from "./output-cap.js";
import {
composeSubagentSystemPrompt,
+ MAX_SUBAGENT_REPORT_CHARS,
SubagentRun,
SUBAGENT_LIST_TOOL_NAME,
SUBAGENT_STOP_TOOL_NAME,
@@ -533,6 +534,8 @@ export type DelegationRecord = {
/** True when `TaskStop` asked for this stop, so an aborted run reads as
* `stopped` rather than `aborted`. */
stopRequested: boolean;
+ /** System interruption preserves resume eligibility; explicit Stop wins. */
+ parentErrorInterrupted?: boolean;
turns: number;
toolCalls: number;
lastToolName?: string;
@@ -4787,6 +4790,15 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
result: SubagentRunResult,
): void {
if (record.status !== "running") return;
+ if (result.status === "aborted" && record.parentErrorInterrupted && !record.stopRequested) {
+ const message = `The parent turn failed and interrupted this delegation. Continue it with Task(resume: "${record.delegationId}").`;
+ result = {
+ ...result,
+ status: "failed",
+ report: truncateTextWithMarker(`${message}\n\n${result.report}`, MAX_SUBAGENT_REPORT_CHARS, "\n[report truncated]\n"),
+ error: { code: "SUBAGENT_PARENT_FAILED", message, resumeId: record.delegationId },
+ };
+ }
record.status =
record.stopRequested && result.status === "aborted"
? "stopped"
@@ -4852,8 +4864,9 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
}
/** Abort every running delegation (user Stop, dispose, parent fatal error). */
- private abortRunningDelegations(): void {
+ private abortRunningDelegations(parentErrorInterrupted = false): void {
for (const record of this.runningDelegations()) {
+ record.parentErrorInterrupted = parentErrorInterrupted;
record.abort();
}
}
@@ -4897,7 +4910,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
this.acceptingSteering = false;
this.steeringWaitAbort?.abort();
this.retainPendingSteering();
- this.abortRunningDelegations();
+ this.abortRunningDelegations(!this.runCancelled && !this.disposed);
this.delegationWaitTargets = undefined;
this.clearAgentActivity();
}
diff --git a/scripts/e2e-subagent-parent-error.mjs b/scripts/e2e-subagent-parent-error.mjs
new file mode 100644
index 000000000..ff17d2a39
--- /dev/null
+++ b/scripts/e2e-subagent-parent-error.mjs
@@ -0,0 +1,173 @@
+import assert from "node:assert/strict";
+import { createServer } from "node:http";
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { DesktopAgentRuntime } from "../packages/agent-runtime/dist/runtime.js";
+
+// Real runtime, Agent and provider transport. Only the remote provider and
+// Host tool boundary are fixtures; no account or running Desktop is used.
+let scenario;
+let sequence = 0;
+const until = async (check) => {
+ const deadline = Date.now() + 15_000;
+ while (!check()) {
+ assert.ok(Date.now() < deadline, `scenario timed out: ${scenario?.mode}`);
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ }
+};
+const bounded = async (promise) => {
+ let timer;
+ try {
+ return await Promise.race([promise, new Promise((_, reject) => {
+ timer = setTimeout(() => reject(new Error(`runtime prompt timed out: ${scenario.mode}`)), 20_000);
+ })]);
+ } finally {
+ clearTimeout(timer);
+ }
+};
+function reply(res, model, calls, text = "Finished") {
+ res.writeHead(200, { "content-type": "text/event-stream" });
+ const chunk = (delta, finish_reason) => res.write(`data: ${JSON.stringify({
+ id: `fixture-${++sequence}`, object: "chat.completion.chunk", created: 1, model,
+ choices: [{ index: 0, delta, finish_reason }],
+ })}\n\n`);
+ chunk(calls ? { role: "assistant", tool_calls: calls.map((call, index) => ({
+ index, id: call.id, type: "function", function: { name: call.name, arguments: JSON.stringify(call.args) },
+ })) } : { role: "assistant", content: text }, null);
+ chunk({}, calls ? "tool_calls" : "stop");
+ res.end("data: [DONE]\n\n");
+}
+const server = createServer(async (req, res) => {
+ try {
+ let raw = "";
+ for await (const part of req) raw += part;
+ const body = JSON.parse(raw);
+ const s = scenario;
+ assert.ok(s);
+ const users = body.messages.filter((message) => message.role === "user");
+ const latest = JSON.stringify(users.at(-1)?.content);
+ if (body.model === "worker") {
+ if (latest.includes("Continue")) {
+ s.replayed.push(body);
+ reply(res, body.model, null, "Resumed successfully");
+ } else if (!body.messages.some((message) => message.role === "tool")) {
+ const label = latest.includes("Task A") ? "A" : "B";
+ reply(res, body.model, [{ id: `read_${label}`, name: "Read", args: { path: `fixture-${label}.txt` } }]);
+ } else {
+ s.waiting.add(res);
+ res.on("close", () => s.waiting.delete(res));
+ // A live provider stream stops cooperatively on the real abort signal.
+ res.writeHead(200, { "content-type": "text/event-stream" });
+ res.write(": waiting\n\n");
+ }
+ return;
+ }
+ if (latest.includes("Resume")) {
+ if (!s.resumeSent) {
+ s.resumeSent = true;
+ reply(res, body.model, [...s.ids.values()].map((id, index) => ({ id: `resume_${index}`,
+ name: "Task", args: { agent: "explorer", task: "Continue", resume: id } })));
+ } else reply(res, body.model, null);
+ return;
+ }
+ if (!s.started) {
+ s.started = true;
+ reply(res, body.model, ["A", "B"].map((label) => ({ id: `task_${label}`, name: "Task",
+ args: { agent: "explorer", task: `Task ${label}` } })));
+ } else if (s.stopSent) {
+ reply(res, body.model, null);
+ } else {
+ await until(() => s.waiting.size === 2);
+ s.parentWaiting = true;
+ if (s.mode === "error") {
+ res.writeHead(401, { "content-type": "application/json" });
+ res.end(JSON.stringify({ error: { message: "fixture parent authentication failure" } }));
+ } else if (s.mode === "stop") {
+ s.stopSent = true;
+ reply(res, body.model, [{ id: "stop_all", name: "TaskStop", args: { delegationIds: [...s.ids.values()] } }]);
+ }
+ // User-abort case leaves the parent's request open until Stop cancels it.
+ }
+ } catch (error) {
+ scenario.errors.push(error);
+ if (!res.headersSent) res.writeHead(500);
+ res.end(String(error));
+ }
+});
+await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
+const baseUrl = `http://127.0.0.1:${server.address().port}/v1`;
+const provider = (modelId) => ({ id: "fixture", name: "Fixture", modelId, baseUrl,
+ apiKey: "", authKind: "none", apiStyle: "openai-chat", supportsReasoning: false,
+ supportedThinkingLevels: ["off"] });
+const projectPath = mkdtempSync(join(tmpdir(), "pi-subagent-parent-error-"));
+const results = [];
+try {
+ for (const mode of ["error", "abort", "stop"]) {
+ const s = scenario = { mode, ids: new Map(), settled: new Map(), waiting: new Set(),
+ errors: [], replayed: [], rejected: [], parentErrors: [] };
+ const runtime = new DesktopAgentRuntime({
+ sessionId: `fixture-${mode}`, mode: "agent", provider: provider("parent"), thinkingLevel: "off", projectPath,
+ commandShell: { id: "bash", label: "Bash", dialect: "posix", available: true, isDefault: true },
+ subagents: [{ name: "explorer", description: "Fixture reader", prompt: "Read the task's file",
+ tools: ["Read"], source: "user", model: { providerId: "fixture", modelId: "worker" } }],
+ subagentProviders: { "fixture/worker": provider("worker") },
+ host: { onNotification: () => () => {}, call: async (method, params) => {
+ if (method === "project.instructions.resolve") return { entries: [] };
+ if (method === "tools.execute") {
+ assert.equal(params.toolName, "Read");
+ return { ok: true, content: { path: params.args.path, text: `Finding from ${params.args.path}` } };
+ }
+ return {};
+ } },
+ onEvent: ({ event, parentToolCallId }) => {
+ if (parentToolCallId) return;
+ if (event.type === "error") s.parentErrors.push(event.error);
+ if (event.type === "tool_end" && event.result?.details?.delegationId && event.toolCallId.startsWith("task_")) {
+ s.ids.set(event.toolCallId, event.result.details.delegationId);
+ }
+ if (event.type === "tool_end" && event.toolCallId.startsWith("resume_") && event.isError) s.rejected.push(event);
+ const message = event.type === "message_end" ? event.message : undefined;
+ if (message?.toolName === "Task" && message.toolResult?.details?.status !== "running") {
+ s.settled.set(message.toolCallId, message.toolResult.details);
+ }
+ },
+ });
+ try {
+ const running = bounded(runtime.prompt("Start two delegates"));
+ if (mode === "abort") {
+ await until(() => s.parentWaiting);
+ await runtime.abort();
+ }
+ await running;
+ await until(() => ["task_A", "task_B"].every((id) => s.settled.has(id)));
+ assert.equal(runtime.getStatus().isRunning, false);
+ assert.equal(s.ids.size, 2);
+ for (const id of ["task_A", "task_B"]) {
+ assert.equal(s.settled.get(id).status, mode === "error" ? "failed" : mode === "stop" ? "stopped" : "aborted");
+ if (mode === "error") assert.equal(s.settled.get(id).error.code, "SUBAGENT_PARENT_FAILED");
+ }
+ if (mode === "error") assert.equal(s.parentErrors.length, 1);
+ await bounded(runtime.prompt("Resume both delegates"));
+ if (mode === "error") {
+ assert.equal(s.replayed.length, 2);
+ assert.equal(s.rejected.length, 0);
+ const histories = s.replayed.map((body) => JSON.stringify(body.messages));
+ assert.ok(histories.some((body) => body.includes("fixture-A.txt") && !body.includes("fixture-B.txt")));
+ assert.ok(histories.some((body) => body.includes("fixture-B.txt") && !body.includes("fixture-A.txt")));
+ } else {
+ assert.equal(s.replayed.length, 0);
+ assert.equal(s.rejected.length, 2);
+ }
+ assert.deepEqual(s.errors, []);
+ results.push({ mode, resumed: s.replayed.length, rejected: s.rejected.length });
+ } finally {
+ await runtime.dispose();
+ }
+ }
+ console.log(JSON.stringify({ ok: true, results }));
+} finally {
+ server.closeAllConnections();
+ await new Promise((resolve) => server.close(resolve));
+ rmSync(projectPath, { recursive: true, force: true });
+}