diff --git a/.gitignore b/.gitignore
index e6692fa08d..725e4f49cf 100644
--- a/.gitignore
+++ b/.gitignore
@@ -61,3 +61,4 @@ qdrant_storage/
plans/
roo-cli-*.tar.gz*
+.zoocode/
diff --git a/apps/cli/src/ui/components/__tests__/ChatHistoryItem.parallelSubtasks.test.tsx b/apps/cli/src/ui/components/__tests__/ChatHistoryItem.parallelSubtasks.test.tsx
new file mode 100644
index 0000000000..1223333ed3
--- /dev/null
+++ b/apps/cli/src/ui/components/__tests__/ChatHistoryItem.parallelSubtasks.test.tsx
@@ -0,0 +1,40 @@
+import { render } from "ink-testing-library"
+
+import type { TUIMessage } from "../../types.js"
+import { extractToolData } from "../../utils/tools.js"
+import ChatHistoryItem from "../ChatHistoryItem.js"
+import { resetNerdFontCache } from "../Icon.js"
+
+describe("ChatHistoryItem parallel subtasks row", () => {
+ beforeEach(() => {
+ // Use fallback icons in tests so they render as visible characters
+ process.env.ROOCODE_NERD_FONT = "0"
+ resetNerdFontCache()
+ })
+
+ afterEach(() => {
+ delete process.env.ROOCODE_NERD_FONT
+ resetNerdFontCache()
+ })
+
+ it("shows the tool label and delegation icon instead of the generic fallback", () => {
+ const payload = {
+ tool: "parallelSubtasks",
+ tasks: [{ label: "api", mode: "architect", message: "Map the REST surface" }],
+ }
+ const message: TUIMessage = {
+ id: "1",
+ role: "tool",
+ content: JSON.stringify(payload),
+ toolName: "parallelSubtasks",
+ toolData: extractToolData(payload),
+ }
+
+ const { lastFrame } = render()
+ const output = lastFrame()
+
+ expect(output).toContain("Parallel Subtasks")
+ expect(output).not.toContain("⚙")
+ expect(output).not.toContain("parallelSubtasks")
+ })
+})
diff --git a/apps/cli/src/ui/components/tools/__tests__/toolDisplayMapping.test.ts b/apps/cli/src/ui/components/tools/__tests__/toolDisplayMapping.test.ts
new file mode 100644
index 0000000000..4751bbd387
--- /dev/null
+++ b/apps/cli/src/ui/components/tools/__tests__/toolDisplayMapping.test.ts
@@ -0,0 +1,37 @@
+import type { IconName } from "../../Icon.js"
+import type { ToolCategory } from "../types.js"
+import { getToolCategory } from "../types.js"
+import { getToolDisplayName, getToolIconName } from "../utils.js"
+
+describe("parallel subtasks display mapping", () => {
+ it.each(["parallelSubtasks", "parallel_subtasks"])("returns a friendly display name for %s", (toolName) => {
+ expect(getToolDisplayName(toolName)).toBe("Parallel Subtasks")
+ })
+
+ it.each(["parallelSubtasks", "parallel_subtasks"])("returns the delegation icon for %s", (toolName) => {
+ expect(getToolIconName(toolName)).toBe("switch")
+ })
+
+ it.each(["parallelSubtasks", "parallel_subtasks"])("routes %s to the generic renderer", (toolName) => {
+ // ModeTool renders only an icon for tools whose name lacks "switch", so the
+ // label would disappear if this row were routed to the mode category.
+ expect(getToolCategory(toolName)).toBe("other")
+ })
+})
+
+describe("existing tool display mapping", () => {
+ const cases: Array<{ tool: string; displayName: string; icon: IconName; category: ToolCategory }> = [
+ { tool: "newTask", displayName: "New Task", icon: "switch", category: "mode" },
+ { tool: "new_task", displayName: "New Task", icon: "switch", category: "mode" },
+ { tool: "finishTask", displayName: "Finish Task", icon: "check", category: "mode" },
+ { tool: "switchMode", displayName: "Switch Mode", icon: "switch", category: "mode" },
+ { tool: "switch_mode", displayName: "Switch Mode", icon: "switch", category: "mode" },
+ { tool: "attempt_completion", displayName: "Task Complete", icon: "check", category: "completion" },
+ ]
+
+ it.each(cases)("keeps the $tool mapping intact", ({ tool, displayName, icon, category }) => {
+ expect(getToolDisplayName(tool)).toBe(displayName)
+ expect(getToolIconName(tool)).toBe(icon)
+ expect(getToolCategory(tool)).toBe(category)
+ })
+})
diff --git a/apps/cli/src/ui/components/tools/utils.ts b/apps/cli/src/ui/components/tools/utils.ts
index af4972cbac..3ae4dc4080 100644
--- a/apps/cli/src/ui/components/tools/utils.ts
+++ b/apps/cli/src/ui/components/tools/utils.ts
@@ -70,6 +70,10 @@ export function getToolDisplayName(toolName: string): string {
new_task: "New Task",
finishTask: "Finish Task",
+ // Parallel subtask operations
+ parallelSubtasks: "Parallel Subtasks",
+ parallel_subtasks: "Parallel Subtasks",
+
// Completion operations
attempt_completion: "Task Complete",
attemptCompletion: "Task Complete",
@@ -122,6 +126,10 @@ export function getToolIconName(toolName: string): IconName {
new_task: "switch",
finishTask: "check",
+ // Parallel subtask operations
+ parallelSubtasks: "switch",
+ parallel_subtasks: "switch",
+
// Completion operations
attempt_completion: "check",
attemptCompletion: "check",
diff --git a/apps/cli/src/ui/types.ts b/apps/cli/src/ui/types.ts
index b3c8944c22..0c35287ab5 100644
--- a/apps/cli/src/ui/types.ts
+++ b/apps/cli/src/ui/types.ts
@@ -62,6 +62,19 @@ export interface ToolData {
}>
}>
+ // Parallel subtask fields
+ /** Child rows reported by the parallel_subtasks tool (approval asks use `tasks`, progress rows use `subtasks`) */
+ subtasks?: Array<{
+ taskId?: string
+ label?: string
+ mode?: string
+ message?: string
+ status?: string
+ reportPath?: string
+ summary?: string
+ error?: string
+ }>
+
// Question/completion fields
/** Question text for ask_followup_question */
question?: string
diff --git a/apps/cli/src/ui/utils/__tests__/tools.test.ts b/apps/cli/src/ui/utils/__tests__/tools.test.ts
new file mode 100644
index 0000000000..79a535806f
--- /dev/null
+++ b/apps/cli/src/ui/utils/__tests__/tools.test.ts
@@ -0,0 +1,83 @@
+import { extractToolData } from "../tools.js"
+
+describe("extractToolData for parallel subtasks", () => {
+ it("extracts the approval rows sent under tasks", () => {
+ const toolData = extractToolData({
+ tool: "parallelSubtasks",
+ tasks: [
+ { label: "api", mode: "architect", message: "Map the REST surface" },
+ { label: "tests", mode: "ask", message: "Find untested modules" },
+ ],
+ })
+
+ expect(toolData.tool).toBe("parallelSubtasks")
+ expect(toolData.subtasks).toHaveLength(2)
+ expect(toolData.subtasks?.[0]).toMatchObject({
+ label: "api",
+ mode: "architect",
+ message: "Map the REST surface",
+ })
+ expect(toolData.subtasks?.[1]).toMatchObject({
+ label: "tests",
+ mode: "ask",
+ message: "Find untested modules",
+ })
+ })
+
+ it("extracts the terminal progress rows sent under subtasks", () => {
+ const toolData = extractToolData({
+ tool: "parallelSubtasks",
+ subtasks: [
+ {
+ taskId: "child-1",
+ label: "api",
+ mode: "architect",
+ status: "completed",
+ reportPath: "/workspace/.zoocode/subtask-reports/parent/api-child-1.md",
+ summary: "3 endpoints mapped",
+ },
+ {
+ taskId: "child-2",
+ label: "tests",
+ mode: "ask",
+ status: "failed",
+ error: "denied write_to_file",
+ },
+ ],
+ })
+
+ expect(toolData.subtasks).toHaveLength(2)
+ expect(toolData.subtasks?.[0]).toMatchObject({
+ taskId: "child-1",
+ label: "api",
+ mode: "architect",
+ status: "completed",
+ reportPath: "/workspace/.zoocode/subtask-reports/parent/api-child-1.md",
+ summary: "3 endpoints mapped",
+ })
+ expect(toolData.subtasks?.[1]).toMatchObject({
+ taskId: "child-2",
+ status: "failed",
+ error: "denied write_to_file",
+ })
+ })
+
+ it("prefers subtasks over tasks when both are present", () => {
+ const toolData = extractToolData({
+ tool: "parallelSubtasks",
+ tasks: [{ label: "stale", mode: "code", message: "approval row" }],
+ subtasks: [{ label: "live", mode: "code", status: "running" }],
+ })
+
+ expect(toolData.subtasks).toHaveLength(1)
+ expect(toolData.subtasks?.[0]).toMatchObject({ label: "live", status: "running" })
+ })
+
+ it.each([
+ { name: "a missing tasks array", payload: { tool: "parallelSubtasks" }, expected: undefined },
+ { name: "a non-array tasks value", payload: { tool: "parallelSubtasks", tasks: "nope" }, expected: undefined },
+ { name: "an empty tasks array", payload: { tool: "parallelSubtasks", tasks: [] }, expected: [] },
+ ])("tolerates $name", ({ payload, expected }) => {
+ expect(extractToolData(payload).subtasks).toEqual(expected)
+ })
+})
diff --git a/apps/cli/src/ui/utils/tools.ts b/apps/cli/src/ui/utils/tools.ts
index b79a506571..44bc0b1247 100644
--- a/apps/cli/src/ui/utils/tools.ts
+++ b/apps/cli/src/ui/utils/tools.ts
@@ -80,6 +80,22 @@ export function extractToolData(toolInfo: Record): ToolData {
}))
}
+ // Extract parallel subtask rows (approval asks send "tasks", progress rows send "subtasks")
+ const subtaskRows = Array.isArray(toolInfo.subtasks) ? toolInfo.subtasks : toolInfo.tasks
+
+ if (Array.isArray(subtaskRows)) {
+ toolData.subtasks = (subtaskRows as Array>).map((s) => ({
+ taskId: s.taskId as string | undefined,
+ label: s.label as string | undefined,
+ mode: s.mode as string | undefined,
+ message: s.message as string | undefined,
+ status: s.status as string | undefined,
+ reportPath: s.reportPath as string | undefined,
+ summary: s.summary as string | undefined,
+ error: s.error as string | undefined,
+ }))
+ }
+
// Extract question/completion fields
if (toolInfo.question !== undefined) {
toolData.question = toolInfo.question as string
diff --git a/apps/vscode-e2e/fixtures/parallel-subtasks.json b/apps/vscode-e2e/fixtures/parallel-subtasks.json
new file mode 100644
index 0000000000..562ac6b64b
--- /dev/null
+++ b/apps/vscode-e2e/fixtures/parallel-subtasks.json
@@ -0,0 +1,198 @@
+{
+ "fixtures": [
+ {
+ "match": { "model": "pst-e2e-fanout", "userMessage": "PST_E2E_SMOKE_A", "sequenceIndex": 0 },
+ "response": {
+ "toolCalls": [
+ {
+ "name": "parallel_subtasks",
+ "arguments": "{\"tasks\":[{\"label\":\"api-surface\",\"mode\":\"code\",\"message\":\"PST_E2E_CHILD_A: Read the file parallel-subtasks-probe.txt in the current working directory and report what it contains.\"},{\"label\":\"debug-logs\",\"mode\":\"debug\",\"message\":\"PST_E2E_CHILD_B: Read the file parallel-subtasks-probe.txt in the current working directory and report what it contains.\"},{\"label\":\"test-plan\",\"mode\":\"ask\",\"message\":\"PST_E2E_CHILD_C: Read the file parallel-subtasks-probe.txt in the current working directory and report what it contains.\"}]}",
+ "id": "call_pst_a_ps_001"
+ }
+ ]
+ }
+ },
+ {
+ "match": { "model": "pst-e2e-fanout", "userMessage": "PST_E2E_CHILD_A", "sequenceIndex": 0 },
+ "response": {
+ "toolCalls": [
+ {
+ "name": "read_file",
+ "arguments": "{\"path\":\"parallel-subtasks-probe.txt\",\"mode\":\"slice\",\"offset\":1,\"limit\":50}",
+ "id": "call_pst_a_child_a_read_001"
+ }
+ ]
+ }
+ },
+ {
+ "match": { "model": "pst-e2e-fanout", "userMessage": "PST_E2E_CHILD_B", "sequenceIndex": 0 },
+ "response": {
+ "toolCalls": [
+ {
+ "name": "read_file",
+ "arguments": "{\"path\":\"parallel-subtasks-probe.txt\",\"mode\":\"slice\",\"offset\":1,\"limit\":50}",
+ "id": "call_pst_a_child_b_read_001"
+ }
+ ]
+ }
+ },
+ {
+ "match": { "model": "pst-e2e-fanout", "userMessage": "PST_E2E_CHILD_C", "sequenceIndex": 0 },
+ "response": {
+ "toolCalls": [
+ {
+ "name": "read_file",
+ "arguments": "{\"path\":\"parallel-subtasks-probe.txt\",\"mode\":\"slice\",\"offset\":1,\"limit\":50}",
+ "id": "call_pst_a_child_c_read_001"
+ }
+ ]
+ }
+ },
+ {
+ "match": {
+ "model": "pst-e2e-fanout",
+ "systemMessage": "highly skilled software engineer with extensive knowledge"
+ },
+ "response": {
+ "toolCalls": [
+ {
+ "name": "attempt_completion",
+ "arguments": "{\"result\":\"PST_E2E_CHILD_A_RESULT: probe file lists the three fan-out markers.\"}",
+ "id": "call_pst_a_child_a_done_001"
+ }
+ ]
+ }
+ },
+ {
+ "match": {
+ "model": "pst-e2e-fanout",
+ "systemMessage": "expert software debugger specializing in systematic problem diagnosis"
+ },
+ "response": {
+ "toolCalls": [
+ {
+ "name": "attempt_completion",
+ "arguments": "{\"result\":\"PST_E2E_CHILD_B_RESULT: probe file lists the three fan-out markers.\"}",
+ "id": "call_pst_a_child_b_done_001"
+ }
+ ]
+ }
+ },
+ {
+ "match": {
+ "model": "pst-e2e-fanout",
+ "systemMessage": "knowledgeable technical assistant focused on answering questions"
+ },
+ "response": {
+ "toolCalls": [
+ {
+ "name": "attempt_completion",
+ "arguments": "{\"result\":\"PST_E2E_CHILD_C_RESULT: probe file lists the three fan-out markers.\"}",
+ "id": "call_pst_a_child_c_done_001"
+ }
+ ]
+ }
+ },
+ {
+ "match": { "model": "pst-e2e-fanout", "systemMessage": "experienced technical leader who is inquisitive" },
+ "response": {
+ "toolCalls": [
+ {
+ "name": "attempt_completion",
+ "arguments": "{\"result\":\"PST_E2E_PARENT_A_RESULT\"}",
+ "id": "call_pst_a_parent_done_001"
+ }
+ ]
+ }
+ },
+ {
+ "match": { "model": "pst-e2e-cancel", "userMessage": "PST_E2E_CANCEL", "sequenceIndex": 0 },
+ "response": {
+ "toolCalls": [
+ {
+ "name": "parallel_subtasks",
+ "arguments": "{\"tasks\":[{\"label\":\"slow-a\",\"mode\":\"code\",\"message\":\"PST_E2E_CANCEL_CHILD_A: Read the file parallel-subtasks-probe.txt in the current working directory and report what it contains.\"},{\"label\":\"slow-b\",\"mode\":\"debug\",\"message\":\"PST_E2E_CANCEL_CHILD_B: Read the file parallel-subtasks-probe.txt in the current working directory and report what it contains.\"}]}",
+ "id": "call_pst_b_ps_001"
+ }
+ ]
+ }
+ },
+ {
+ "match": { "model": "pst-e2e-cancel", "userMessage": "PST_E2E_CANCEL_CHILD_A", "sequenceIndex": 0 },
+ "streamingProfile": { "ttft": 15000 },
+ "response": {
+ "toolCalls": [
+ {
+ "name": "read_file",
+ "arguments": "{\"path\":\"parallel-subtasks-probe.txt\",\"mode\":\"slice\",\"offset\":1,\"limit\":50}",
+ "id": "call_pst_b_child_a_read_001"
+ }
+ ]
+ }
+ },
+ {
+ "match": { "model": "pst-e2e-cancel", "userMessage": "PST_E2E_CANCEL_CHILD_B", "sequenceIndex": 0 },
+ "streamingProfile": { "ttft": 15000 },
+ "response": {
+ "toolCalls": [
+ {
+ "name": "read_file",
+ "arguments": "{\"path\":\"parallel-subtasks-probe.txt\",\"mode\":\"slice\",\"offset\":1,\"limit\":50}",
+ "id": "call_pst_b_child_b_read_001"
+ }
+ ]
+ }
+ },
+ {
+ "match": { "model": "pst-e2e-depth1", "userMessage": "PST_E2E_DEPTH1", "sequenceIndex": 0 },
+ "response": {
+ "toolCalls": [
+ {
+ "name": "parallel_subtasks",
+ "arguments": "{\"tasks\":[{\"label\":\"depth1-probe\",\"mode\":\"code\",\"message\":\"PST_E2E_DEPTH1_CHILD: You are investigating alone. Try to spawn a nested parallel_subtasks child, observe the outcome, then read the file parallel-subtasks-probe.txt and report what it contains.\"}]}",
+ "id": "call_pst_c_ps_001"
+ }
+ ]
+ }
+ },
+ {
+ "match": { "model": "pst-e2e-depth1", "userMessage": "PST_E2E_DEPTH1_CHILD", "sequenceIndex": 0 },
+ "response": {
+ "toolCalls": [
+ {
+ "name": "parallel_subtasks",
+ "arguments": "{\"tasks\":[{\"label\":\"grandchild\",\"mode\":\"code\",\"message\":\"PST_E2E_DEPTH1_GRANDCHILD: read the probe file.\"}]}",
+ "id": "call_pst_c_child_ps_001"
+ }
+ ]
+ }
+ },
+ {
+ "match": {
+ "model": "pst-e2e-depth1",
+ "systemMessage": "highly skilled software engineer with extensive knowledge"
+ },
+ "response": {
+ "toolCalls": [
+ {
+ "name": "attempt_completion",
+ "arguments": "{\"result\":\"PST_E2E_DEPTH1_CHILD_RESULT: nested fan-out was rejected, probe file contents reported instead.\"}",
+ "id": "call_pst_c_child_done_001"
+ }
+ ]
+ }
+ },
+ {
+ "match": { "model": "pst-e2e-depth1", "systemMessage": "experienced technical leader who is inquisitive" },
+ "response": {
+ "toolCalls": [
+ {
+ "name": "attempt_completion",
+ "arguments": "{\"result\":\"PST_E2E_DEPTH1_PARENT_RESULT\"}",
+ "id": "call_pst_c_parent_done_001"
+ }
+ ]
+ }
+ }
+ ]
+}
diff --git a/apps/vscode-e2e/src/suite/parallel-subtasks.test.ts b/apps/vscode-e2e/src/suite/parallel-subtasks.test.ts
new file mode 100644
index 0000000000..aa1bf29a63
--- /dev/null
+++ b/apps/vscode-e2e/src/suite/parallel-subtasks.test.ts
@@ -0,0 +1,679 @@
+import * as assert from "assert"
+import * as fs from "fs/promises"
+import * as path from "path"
+import * as vscode from "vscode"
+
+import {
+ RooCodeEventName,
+ type ClineMessage,
+ type Experiments,
+ type ParallelSubtaskInfo,
+ type RooCodeSettings,
+} from "@roo-code/types"
+
+import { setDefaultSuiteTimeout } from "./test-utils"
+import { sleep, waitFor, waitUntilCompleted } from "./utils"
+
+// Probe tags are matched by substring against the LAST user message of each API
+// request. They are unique to this suite and timestamp-free by construction; the
+// parent prompts never embed a child tag, so a child fixture can never fire on a
+// parent request (see fixtures/parallel-subtasks.json).
+//
+// Turn-2 matching: this extension appends a trailing `` user
+// message after every tool result, so a tool-result turn's LAST user message no
+// longer carries the probe, and aimock's toolCallId/toolResultContains matchers
+// (last-message-only) can never see it. Every post-tool turn instead matches on
+// the mode-specific roleDefinition that the host puts in the system prompt, and
+// each scenario pins its own model id (via the public settings API) so fixtures
+// are scoped per scenario and can never collide with other suites or with the
+// global `` fallback fixture in runTest.ts.
+//
+// Request-shape assertions read captured request bodies from the fetch
+// interceptor below, not the aimock journal: the journal caps bodies at 64 KB
+// and this extension's requests (full system prompt) always exceed that.
+const FANOUT_PARENT_PROMPT =
+ "PST_E2E_SMOKE_A: Use the parallel_subtasks tool to run the three read-only investigations, then complete with the final summary."
+const CANCEL_PARENT_PROMPT =
+ "PST_E2E_CANCEL: Use the parallel_subtasks tool to run the two read-only investigations, then complete with the final summary."
+const DEPTH1_PARENT_PROMPT =
+ "PST_E2E_DEPTH1: Use the parallel_subtasks tool to run the single read-only investigation, then complete with the final summary."
+
+const FANOUT_MODEL_ID = "pst-e2e-fanout"
+const CANCEL_MODEL_ID = "pst-e2e-cancel"
+const DEPTH1_MODEL_ID = "pst-e2e-depth1"
+
+const FANOUT_PARENT_RESULT = "PST_E2E_PARENT_A_RESULT"
+const DEPTH1_PARENT_RESULT = "PST_E2E_DEPTH1_PARENT_RESULT"
+
+// Written into the probe file in suiteSetup; a successfully approved child read
+// returns it in the read_file tool result, so it doubles as the content marker
+// the fan-out test asserts on.
+const PROBE_FILE_CONTENT_MARKER = "parallel-subtasks probe: fan-out markers"
+
+const FANOUT_CHILDREN = [
+ { key: "a", label: "api-surface", tag: "PST_E2E_CHILD_A", marker: "PST_E2E_CHILD_A_RESULT" },
+ { key: "b", label: "debug-logs", tag: "PST_E2E_CHILD_B", marker: "PST_E2E_CHILD_B_RESULT" },
+ { key: "c", label: "test-plan", tag: "PST_E2E_CHILD_C", marker: "PST_E2E_CHILD_C_RESULT" },
+]
+
+const CANCEL_CHILD_TTFT_MS = 15_000
+const CANCEL_DRAIN_GRACE_MS = 500
+
+// The parent runs in architect mode so its post-tool turns are matched by the
+// architect roleDefinition, never colliding with the code/debug/ask children.
+// D4 contract: this configuration sets autoApprovalEnabled: true but grants no
+// read access, so a child's read_file ask is not globally auto-approved; it is
+// the D4 background-child carve-out (resolveBackgroundChildAsk in Task.ts)
+// that approves the read. Non-read asks fail closed (auto-denied). The
+// approval fields are pinned explicitly (not merely omitted): startNewTask
+// persists this configuration through setValues, so an alwaysAllowReadOnly /
+// allowed*Files value inherited from a previously persisted configuration or
+// an earlier suite would otherwise reach these tasks and let the read bypass
+// the carve-out, masking a regression. The read-result content assertion in
+// the fan-out test is the tripwire: remove the carve-out and the result
+// carries the denial text instead of the probe file contents.
+const scenarioConfiguration: RooCodeSettings = {
+ mode: "architect",
+ alwaysAllowModeSwitch: true,
+ alwaysAllowSubtasks: true,
+ autoApprovalEnabled: true,
+ enableCheckpoints: false,
+ alwaysAllowReadOnly: false,
+ allowedReadFiles: [],
+ allowedWriteFiles: [],
+}
+
+const TERMINAL_SUBTASK_STATUSES = new Set(["completed", "failed", "aborted"])
+
+// Request capture. aimock's journal caps request bodies at 64 KB and replaces
+// larger ones (every real request here carries the full system prompt) with a
+// truncation marker, so journal-based content assertions cannot work. The suite
+// instead records the exact chat-completion request bodies through a fetch
+// interceptor, which also captures the requests that never reach the mock
+// (cancelled in-flight children). The interceptor is installed before any task
+// starts because the OpenAI SDK resolves fetch at client construction.
+type CapturedRequestMessage = {
+ role?: string
+ content?: unknown
+ tool_call_id?: string
+}
+
+type CapturedChatRequest = {
+ model?: string
+ messages?: CapturedRequestMessage[]
+}
+
+type CapturedRequest = {
+ observedAt: number
+ body: CapturedChatRequest
+}
+
+const capturedRequests: CapturedRequest[] = []
+
+let restoreFetch: (() => void) | undefined
+
+const installFetchCapture = () => {
+ const original = globalThis.fetch
+ globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit): Promise => {
+ try {
+ const url = typeof input === "string" ? input : input instanceof URL ? input.href : (input as Request).url
+ if (url.includes("/chat/completions") && typeof init?.body === "string") {
+ capturedRequests.push({ observedAt: Date.now(), body: JSON.parse(init.body) as CapturedChatRequest })
+ }
+ } catch {
+ // Capture is best-effort; it must never break a request.
+ }
+ return original.call(globalThis, input, init)
+ }) as typeof globalThis.fetch
+ restoreFetch = () => {
+ globalThis.fetch = original
+ }
+}
+
+const requestContentText = (content: unknown): string => {
+ if (typeof content === "string") {
+ return content
+ }
+ if (Array.isArray(content)) {
+ return content
+ .map((part) =>
+ typeof part === "object" && part !== null && "text" in part
+ ? String((part as { text?: unknown }).text ?? "")
+ : "",
+ )
+ .join("")
+ }
+ return ""
+}
+
+// Joined text of every user message in the captured request. aimock fixtures match
+// on the last user message; joining all of them keeps these helpers a strict
+// superset, which is fine because the probe tags only ever appear in task prompts.
+const capturedUserText = (captured: CapturedRequest) =>
+ (captured.body.messages ?? [])
+ .filter((message) => message.role === "user")
+ .map((message) => requestContentText(message.content))
+ .join("")
+
+const findCapturedToolMessage = (captured: CapturedRequest | undefined, toolCallId: string) =>
+ captured?.body.messages?.find((message) => message.role === "tool" && message.tool_call_id === toolCallId)
+
+// Waits for a request carrying `probe` in a user message to be captured and
+// returns the capture time, so post-test drains can anchor to the exact request
+// this test created (never earlier traffic).
+const waitForCapturedRequest = async (probe: string): Promise => {
+ let observedAt: number | undefined
+
+ await waitFor(() => {
+ const match = capturedRequests.find((captured) => capturedUserText(captured).includes(probe))
+ if (match) {
+ observedAt = match.observedAt
+ }
+ return match !== undefined
+ })
+
+ return observedAt
+}
+
+// The cancelled children's first SSE chunks are delayed by CANCEL_CHILD_TTFT_MS.
+// Wait out the remainder of that window before the next test can open another
+// streamed request against the same mock, anchored to the captured request times.
+const waitForCancelledChildStreamDrain = async (...requestTimes: Array) => {
+ const anchored = requestTimes.filter((time): time is number => time !== undefined)
+ if (anchored.length === 0) {
+ return
+ }
+
+ const deadlineMs = Math.max(...anchored) + CANCEL_CHILD_TTFT_MS + CANCEL_DRAIN_GRACE_MS
+ const remainingMs = deadlineMs - Date.now()
+ if (remainingMs > 0) {
+ await sleep(remainingMs)
+ }
+}
+
+type ParallelSubtasksPanel = { tool: string; subtasks: ParallelSubtaskInfo[] }
+
+type PanelRow = { partial: boolean | undefined; panel: ParallelSubtasksPanel }
+
+// The emitter mutates one message object in place (a partial row's `partial` flips
+// to false when finalized), so collectors must snapshot primitives at event time;
+// keeping the reference would erase the partial flag before assertions run.
+type MessageSnapshot = {
+ type: string | undefined
+ say: string | undefined
+ text: string | undefined
+ partial: boolean | undefined
+}
+
+// Every panel update is a say:"tool" row whose text is the panel JSON. The host
+// creates one partial row while children run and finalizes it (partial cleared)
+// when the join settles, so the snapshots carry one entry per update.
+const parsePanelRows = (messages: MessageSnapshot[] | undefined): PanelRow[] =>
+ (messages ?? []).flatMap((message) => {
+ if (message.type !== "say" || message.say !== "tool" || typeof message.text !== "string") {
+ return []
+ }
+ try {
+ const parsed = JSON.parse(message.text) as ParallelSubtasksPanel
+ return parsed.tool === "parallelSubtasks" && Array.isArray(parsed.subtasks) && parsed.subtasks.length > 0
+ ? [{ partial: message.partial, panel: parsed }]
+ : []
+ } catch {
+ return []
+ }
+ })
+
+const collectMessages = () => {
+ const byTask: Record = {}
+ const handler = ({ taskId, message }: { taskId: string; message: ClineMessage }) => {
+ const messages = (byTask[taskId] ??= [])
+ messages.push({ type: message.type, say: message.say, text: message.text, partial: message.partial })
+ }
+ globalThis.api.on(RooCodeEventName.Message, handler)
+ return {
+ byTask,
+ stop: () => globalThis.api.off(RooCodeEventName.Message, handler),
+ }
+}
+
+const completionResultOf = (messages: MessageSnapshot[] | undefined) =>
+ (messages ?? [])
+ .filter((message) => message.type === "say" && message.say === "completion_result" && message.partial === false)
+ .map((message) => message.text?.trim())
+ .find((text): text is string => !!text)
+
+suite("Roo Code Parallel Subtasks", function () {
+ setDefaultSuiteTimeout(this)
+
+ const api = globalThis.api
+
+ let workspaceDir: string
+ let probeFilePath: string
+ let reportsRoot: string
+ let priorExperiments: Experiments | undefined
+ let priorModelId: string | undefined
+ let priorMode: string | undefined
+ let priorAlwaysAllowModeSwitch: boolean | undefined
+ let priorAlwaysAllowSubtasks: boolean | undefined
+ let priorAutoApprovalEnabled: boolean | undefined
+ let priorEnableCheckpoints: boolean | undefined
+ let priorAlwaysAllowReadOnly: boolean | undefined
+ let priorAllowedReadFiles: string[] | undefined
+ let priorAllowedWriteFiles: string[] | undefined
+
+ suiteSetup(async () => {
+ // Install before any task starts: the OpenAI SDK resolves fetch at client
+ // construction, and suiteSetup runs before every test in this suite.
+ installFetchCapture()
+ workspaceDir = vscode.workspace.workspaceFolders?.[0]?.uri.fsPath ?? ""
+ assert.ok(workspaceDir, "parallel-subtasks e2e requires an open workspace folder")
+ probeFilePath = path.join(workspaceDir, "parallel-subtasks-probe.txt")
+ await fs.writeFile(
+ probeFilePath,
+ `${PROBE_FILE_CONTENT_MARKER} PST_E2E_CHILD_A PST_E2E_CHILD_B PST_E2E_CHILD_C\n`,
+ )
+ reportsRoot = path.join(workspaceDir, ".zoocode", "subtask-reports")
+ const priorConfiguration = api.getConfiguration()
+ priorExperiments = priorConfiguration.experiments
+ priorModelId = priorConfiguration.openRouterModelId
+ // startNewTask persists scenarioConfiguration through setValues (see the
+ // scenarioConfiguration comment below), so every field it pins must be
+ // captured here and restored through the same setConfiguration cleanup
+ // path, including fields whose prior value is unset.
+ priorMode = priorConfiguration.mode
+ priorAlwaysAllowModeSwitch = priorConfiguration.alwaysAllowModeSwitch
+ priorAlwaysAllowSubtasks = priorConfiguration.alwaysAllowSubtasks
+ priorAutoApprovalEnabled = priorConfiguration.autoApprovalEnabled
+ priorEnableCheckpoints = priorConfiguration.enableCheckpoints
+ // scenarioConfiguration pins these approval fields for the D4 tripwire;
+ // capture the prior values so suiteTeardown can restore them through
+ // the same setConfiguration cleanup path as the experiments restore.
+ priorAlwaysAllowReadOnly = priorConfiguration.alwaysAllowReadOnly
+ priorAllowedReadFiles = priorConfiguration.allowedReadFiles
+ priorAllowedWriteFiles = priorConfiguration.allowedWriteFiles
+ // parallel_subtasks is gated behind the parallelSubtasks experiment (default
+ // off). Enable it through the public settings API for the duration of this
+ // suite; no test-only backdoor exists or is needed.
+ await api.setConfiguration({ experiments: { ...priorExperiments, parallelSubtasks: true } })
+ })
+
+ suiteTeardown(async () => {
+ try {
+ while (api.getCurrentTaskStack().length > 0) {
+ await api.clearCurrentTask()
+ }
+ // Restore every field the suite pinned through startNewTask's persisted
+ // configuration. Unset priors are restored as explicit undefined: the
+ // public setConfiguration path writes each key through ContextProxy, so
+ // skipping an unset key would leave the scenario's pinned value behind.
+ await api.setConfiguration({
+ experiments: priorExperiments,
+ openRouterModelId: priorModelId,
+ mode: priorMode,
+ alwaysAllowModeSwitch: priorAlwaysAllowModeSwitch,
+ alwaysAllowSubtasks: priorAlwaysAllowSubtasks,
+ autoApprovalEnabled: priorAutoApprovalEnabled,
+ enableCheckpoints: priorEnableCheckpoints,
+ alwaysAllowReadOnly: priorAlwaysAllowReadOnly,
+ allowedReadFiles: priorAllowedReadFiles,
+ allowedWriteFiles: priorAllowedWriteFiles,
+ })
+ } finally {
+ // The interceptor and the shared capture buffer must be released even
+ // when task or settings cleanup rejects above: otherwise the next suite
+ // inherits a fetch that still appends request bodies to this buffer.
+ restoreFetch?.()
+ restoreFetch = undefined
+ capturedRequests.length = 0
+ }
+ if (path.resolve(reportsRoot).startsWith(path.resolve(workspaceDir) + path.sep)) {
+ await fs.rm(reportsRoot, { recursive: true, force: true }).catch(() => {})
+ }
+ await fs.unlink(probeFilePath).catch(() => {})
+ })
+
+ setup(() => {
+ // A fresh capture buffer per test: every assertion below is scoped by
+ // its own probe tag, so stale requests from an earlier test can never
+ // satisfy a find(). Late requests from a previous task may still land
+ // after this clear; the probe tags are the source of truth.
+ capturedRequests.length = 0
+ })
+
+ test("cancelling the parent mid-fan-out aborts every child", async function () {
+ const { byTask, stop } = collectMessages()
+ // Attach the abort listener before the task starts: TaskAborted fires during
+ // the awaited cancelCurrentTask, so subscribing after the cancel would miss it.
+ const abortedTaskIds = new Set()
+ const abortedAtByTask = new Map()
+ const onTaskAborted = (taskId: string) => {
+ abortedTaskIds.add(taskId)
+ abortedAtByTask.set(taskId, Date.now())
+ }
+ api.on(RooCodeEventName.TaskAborted, onTaskAborted)
+ let childARequestAt: number | undefined
+ let childBRequestAt: number | undefined
+
+ try {
+ await api.setConfiguration({ openRouterModelId: CANCEL_MODEL_ID })
+ const parentTaskId = await api.startNewTask({
+ configuration: scenarioConfiguration,
+ text: CANCEL_PARENT_PROMPT,
+ })
+
+ // Both children must be in-flight (ttft-delayed) at the mock before the
+ // cancel lands; otherwise the cascade has nothing to abort.
+ childARequestAt = await waitForCapturedRequest("PST_E2E_CANCEL_CHILD_A")
+ childBRequestAt = await waitForCapturedRequest("PST_E2E_CANCEL_CHILD_B")
+
+ await waitFor(() => parsePanelRows(byTask[parentTaskId]).length > 0)
+ const panelRow = parsePanelRows(byTask[parentTaskId])[0]
+ assert.ok(panelRow, "panel row should arrive once the fan-out starts")
+ const spawned = panelRow.panel.subtasks
+ assert.strictEqual(spawned.length, 2, "two children should be spawned for the cancel scenario")
+ // Streaming-progress contract, proven in the pending window: both child
+ // requests are captured above and their first chunks are ttft-delayed by
+ // CANCEL_CHILD_TTFT_MS, so the children are genuinely in flight here.
+ // The panel row observed now must be partial with no child in a terminal
+ // status; a host that buffered every panel update until the join settled
+ // could not produce this row. Final-state rows are asserted separately
+ // after completion in the fan-out test below.
+ assert.strictEqual(
+ panelRow.partial,
+ true,
+ "panel row should stream as partial while the ttft-delayed children are pending",
+ )
+ for (const subtask of spawned) {
+ assert.ok(
+ !TERMINAL_SUBTASK_STATUSES.has(subtask.status),
+ `child ${subtask.label} should still be pending while its first chunk is delayed (got ${subtask.status})`,
+ )
+ }
+ const childTaskIds = spawned.map((subtask) => subtask.taskId)
+
+ const cancelledAt = Date.now()
+ await api.cancelCurrentTask()
+ await waitFor(() => abortedTaskIds.has(parentTaskId), { timeout: 30_000 })
+
+ // The cancelled children's first chunks are delayed by
+ // CANCEL_CHILD_TTFT_MS, so a child continuation that survived the
+ // cancel lands inside that window. Wait it out before the settle
+ // and traffic assertions: afterwards every surviving child request
+ // has been captured and every child status flip has been observed.
+ // (The finally drain below is then a no-op on the success path and
+ // remains as failure cleanup.)
+ await waitForCancelledChildStreamDrain(childARequestAt, childBRequestAt)
+
+ // The fan-out settles: every child persists as interrupted, never completed.
+ for (const childTaskId of childTaskIds) {
+ await waitFor(async () => (await api.getTaskHistoryItem(childTaskId))?.status === "interrupted")
+ }
+
+ // The parent must not resume or complete after the cancel. Its persisted
+ // history status is expected to be "interrupted", but a known production
+ // race (reported with this suite) leaves the field unset when the cancel
+ // lands mid-tool, so the strict invariant asserted here is the fan-out
+ // contract: never completed, and the abort was observed above.
+ const parentHistory = await api.getTaskHistoryItem(parentTaskId)
+ assert.notStrictEqual(
+ parentHistory?.status,
+ "completed",
+ "parent must not complete after the mid-fan-out cancel",
+ )
+
+ // No child keeps running: no captured request sent after the cancel
+ // carries a child probe in a user message. The drain above already
+ // covered the delayed-stream window, so this filter sees every
+ // child continuation that could still exist.
+ const lateChildTraffic = capturedRequests.filter(
+ (captured) =>
+ captured.observedAt > cancelledAt && /PST_E2E_CANCEL_CHILD_[AB]/.test(capturedUserText(captured)),
+ )
+ assert.deepStrictEqual(lateChildTraffic, [], "no child should keep calling the API after the parent cancel")
+
+ // The parent must not resume either. The cancel fixtures provide no
+ // parent turn-2 response, so a parent that sent another model request
+ // after the abort would 404 and stall: the history assertion above
+ // still passes (never "completed"), which is why the parent traffic
+ // itself is checked here. Only requests observed after the parent's
+ // own TaskAborted event are rejected; its turn-1 request (sent long
+ // before the abort) stays permitted through the abort timestamp.
+ const parentAbortedAt = abortedAtByTask.get(parentTaskId)
+ assert.ok(parentAbortedAt !== undefined, "parent TaskAborted should carry an observation timestamp")
+ const lateParentTraffic = capturedRequests.filter(
+ (captured) =>
+ captured.observedAt > parentAbortedAt && capturedUserText(captured).includes(CANCEL_PARENT_PROMPT),
+ )
+ assert.deepStrictEqual(lateParentTraffic, [], "parent should not call the API again after its abort")
+ } finally {
+ api.off(RooCodeEventName.TaskAborted, onTaskAborted)
+ stop()
+ while (api.getCurrentTaskStack().length > 0) {
+ await api.clearCurrentTask()
+ }
+ await waitForCancelledChildStreamDrain(childARequestAt, childBRequestAt)
+ }
+ })
+
+ test("3-way fan-out spawns children, writes reports, and resumes the parent", async function () {
+ const { byTask, stop } = collectMessages()
+
+ try {
+ // Scope this scenario's fixtures to its own model id (see file header).
+ await api.setConfiguration({ openRouterModelId: FANOUT_MODEL_ID })
+ const parentTaskId = await waitUntilCompleted({
+ api,
+ start: () =>
+ api.startNewTask({
+ configuration: scenarioConfiguration,
+ text: FANOUT_PARENT_PROMPT,
+ }),
+ })
+
+ const parentMessages = byTask[parentTaskId] ?? []
+
+ // The parent resumed after the fan-out and completed with its marker: the
+ // whole chain (spawn -> children run -> join -> tool result) really happened.
+ assert.strictEqual(
+ completionResultOf(parentMessages),
+ FANOUT_PARENT_RESULT,
+ "parent should resume and complete after the fan-out",
+ )
+
+ // The progress panel streamed partial updates and finalized with every
+ // child in a terminal status.
+ const rows = parsePanelRows(parentMessages)
+ assert.ok(rows.length > 0, "parent should emit at least one parallelSubtasks panel row")
+ assert.ok(
+ rows.some((row) => row.partial === true),
+ "panel should stream partial updates while children run",
+ )
+ const finalRow = rows.at(-1)
+ assert.ok(finalRow, "final panel row should exist")
+ assert.notStrictEqual(finalRow.partial, true, "final panel row should be finalized (partial cleared)")
+ assert.deepStrictEqual(
+ finalRow.panel.subtasks.map((subtask) => subtask.label),
+ FANOUT_CHILDREN.map((child) => child.label),
+ "final panel row should name every requested child in order",
+ )
+ for (const subtask of finalRow.panel.subtasks) {
+ assert.ok(TERMINAL_SUBTASK_STATUSES.has(subtask.status), `child ${subtask.label} should be terminal`)
+ assert.strictEqual(subtask.status, "completed", `child ${subtask.label} should complete`)
+ assert.ok(subtask.taskId, `child ${subtask.label} should carry its task id`)
+ assert.ok(
+ subtask.reportPath !== undefined && /\.zoocode[/\\]subtask-reports[/\\]/.test(subtask.reportPath),
+ `child ${subtask.label} should carry a report path under .zoocode/subtask-reports (got ${subtask.reportPath})`,
+ )
+ assert.ok(
+ subtask.reportPath!.includes(parentTaskId),
+ `child ${subtask.label} report should live under the parent's report directory`,
+ )
+ }
+ const childTaskIds = finalRow.panel.subtasks.map((subtask) => subtask.taskId)
+ assert.strictEqual(
+ new Set(childTaskIds).size,
+ FANOUT_CHILDREN.length,
+ "every child should have its own task id",
+ )
+
+ // Reports exist on disk and carry the per-child markers.
+ for (const [index, subtask] of finalRow.panel.subtasks.entries()) {
+ const report = await fs.readFile(subtask.reportPath!, "utf8")
+ const marker = FANOUT_CHILDREN[index]?.marker
+ assert.ok(
+ marker !== undefined && report.includes(marker),
+ `report for ${subtask.label} should contain the child marker`,
+ )
+ }
+
+ // Children persisted as completed background children; the parent registered them.
+ for (const subtask of finalRow.panel.subtasks) {
+ const history = await api.getTaskHistoryItem(subtask.taskId)
+ assert.strictEqual(history?.status, "completed", `child ${subtask.label} history should be completed`)
+ assert.strictEqual(
+ history?.parentTaskId,
+ parentTaskId,
+ `child ${subtask.label} should point at the parent`,
+ )
+ assert.strictEqual(
+ history?.backgroundParentTaskId,
+ parentTaskId,
+ `child ${subtask.label} should carry the background parent stamp`,
+ )
+ }
+ const parentHistory = await api.getTaskHistoryItem(parentTaskId)
+ for (const subtask of finalRow.panel.subtasks) {
+ assert.ok(
+ parentHistory?.childIds?.includes(subtask.taskId),
+ `parent childIds should include ${subtask.taskId}`,
+ )
+ }
+
+ // The tool result the parent model actually received names every child and
+ // pairs it with that child's own report path (matched against the final
+ // panel row, not just any path-shaped string): a parent that received the
+ // first child's path for every label would pass a label-only check.
+ const parentResumeCaptured = capturedRequests.find(
+ (captured) =>
+ capturedUserText(captured).includes("PST_E2E_SMOKE_A") &&
+ findCapturedToolMessage(captured, "call_pst_a_ps_001"),
+ )
+ const toolResultText = requestContentText(
+ findCapturedToolMessage(parentResumeCaptured, "call_pst_a_ps_001")?.content,
+ )
+ assert.ok(
+ toolResultText.includes("parallel_subtasks finished: 3/3"),
+ "parent tool result should report 3/3 children completed",
+ )
+ const reportPathByLabel = new Map(
+ finalRow.panel.subtasks.map((subtask) => [subtask.label, subtask.reportPath]),
+ )
+ for (const child of FANOUT_CHILDREN) {
+ const reportPath = reportPathByLabel.get(child.label)
+ assert.ok(
+ reportPath !== undefined &&
+ toolResultText.includes(`- ${child.label}: completed. Report: ${reportPath}`),
+ `parent tool result should pair child ${child.label} with its own report path`,
+ )
+ }
+
+ // Every child ran its own API turns: the read_file result for each child's
+ // call left the extension in a follow-up request carrying that child's probe.
+ // The assertion is on the RESULT CONTENT, not the message's existence: a
+ // denied read produces a tool message under the same tool_call_id carrying
+ // the background_policy denial text (the result is replaced without
+ // counting a mistake), and the turn-2 fixtures serve attempt_completion
+ // regardless of the tool result, so an existence-only check would pass
+ // with the D4 carve-out removed. Only an approved read carries the probe
+ // file's contents.
+ for (const child of FANOUT_CHILDREN) {
+ const readResultCaptured = capturedRequests.find(
+ (captured) =>
+ capturedUserText(captured).includes(child.tag) &&
+ findCapturedToolMessage(captured, `call_pst_a_child_${child.key}_read_001`),
+ )
+ assert.ok(readResultCaptured, `child ${child.label} should send its read_file result back to the API`)
+ const readResultText = requestContentText(
+ findCapturedToolMessage(readResultCaptured, `call_pst_a_child_${child.key}_read_001`)?.content,
+ )
+ assert.ok(
+ readResultText.includes(PROBE_FILE_CONTENT_MARKER),
+ `child ${child.label} read_file result must carry the probe file content (got: ${readResultText.slice(0, 160)}...)`,
+ )
+ }
+ } finally {
+ stop()
+ while (api.getCurrentTaskStack().length > 0) {
+ await api.clearCurrentTask()
+ }
+ }
+ })
+
+ test("a child calling parallel_subtasks gets a validation error and no grandchild spawns", async function () {
+ const { byTask, stop } = collectMessages()
+
+ try {
+ await api.setConfiguration({ openRouterModelId: DEPTH1_MODEL_ID })
+ const parentTaskId = await waitUntilCompleted({
+ api,
+ start: () =>
+ api.startNewTask({
+ configuration: scenarioConfiguration,
+ text: DEPTH1_PARENT_PROMPT,
+ }),
+ })
+
+ assert.strictEqual(
+ completionResultOf(byTask[parentTaskId]),
+ DEPTH1_PARENT_RESULT,
+ "parent should resume and complete after the single-child fan-out",
+ )
+
+ const rows = parsePanelRows(byTask[parentTaskId])
+ assert.ok(rows.length > 0, "parent should emit at least one parallelSubtasks panel row")
+ const finalRowEntry = rows.at(-1)
+ assert.ok(finalRowEntry, "final panel row should exist")
+ const finalRow = finalRowEntry.panel
+ assert.strictEqual(finalRow.subtasks.length, 1, "exactly one child should ever be tracked for the parent")
+ const onlySubtask = finalRow.subtasks[0]
+ assert.ok(onlySubtask, "the depth-1 child row should exist")
+ assert.strictEqual(onlySubtask.status, "completed", "the depth-1 child should still complete")
+
+ // The child's own report survives, proving the child itself completed.
+ assert.ok(onlySubtask.reportPath, "the depth-1 child should carry a report path")
+ const report = await fs.readFile(onlySubtask.reportPath, "utf8")
+ assert.ok(report.includes("PST_E2E_DEPTH1_CHILD_RESULT"), "child report should contain the child marker")
+
+ // The nested parallel_subtasks call was answered with a tool validation
+ // error that reached the child model as an error tool result. The child
+ // sends several requests, so the denial is located inside the tool
+ // result message for the fixture's nested call id (not anywhere in the
+ // captured request) and asserted on that message's content.
+ const childErrorCaptured = capturedRequests.find(
+ (captured) =>
+ capturedUserText(captured).includes("PST_E2E_DEPTH1_CHILD") &&
+ findCapturedToolMessage(captured, "call_pst_c_child_ps_001") !== undefined,
+ )
+ assert.ok(childErrorCaptured, "child should send the nested parallel_subtasks result back to the API")
+ const nestedErrorText = requestContentText(
+ findCapturedToolMessage(childErrorCaptured, "call_pst_c_child_ps_001")?.content,
+ )
+ assert.ok(
+ nestedErrorText.includes("is not allowed in"),
+ `child should receive the validation error for the nested parallel_subtasks call (got: ${nestedErrorText.slice(0, 160)}...)`,
+ )
+
+ // Depth is structurally capped at 1: the grandchild probe never appears as a
+ // user (task) message, so no grandchild task ever started an API turn.
+ const grandchildCaptured = capturedRequests.find((captured) =>
+ capturedUserText(captured).includes("PST_E2E_DEPTH1_GRANDCHILD"),
+ )
+ assert.strictEqual(grandchildCaptured, undefined, "no grandchild task should spawn from a background child")
+ } finally {
+ stop()
+ while (api.getCurrentTaskStack().length > 0) {
+ await api.clearCurrentTask()
+ }
+ }
+ })
+})
diff --git a/packages/types/src/experiment.ts b/packages/types/src/experiment.ts
index f4b3a1c0a8..7e12914fa0 100644
--- a/packages/types/src/experiment.ts
+++ b/packages/types/src/experiment.ts
@@ -12,6 +12,7 @@ export const experimentIds = [
"runSlashCommand",
"customTools",
"parallelToolExecution",
+ "parallelSubtasks",
"dynamicThinkingEffort",
] as const
@@ -29,6 +30,7 @@ export const experimentsSchema = z.object({
runSlashCommand: z.boolean().optional(),
customTools: z.boolean().optional(),
parallelToolExecution: z.boolean().optional(),
+ parallelSubtasks: z.boolean().optional(),
dynamicThinkingEffort: z.boolean().optional(),
})
diff --git a/packages/types/src/history.ts b/packages/types/src/history.ts
index 1ba91b02e4..73d31bb171 100644
--- a/packages/types/src/history.ts
+++ b/packages/types/src/history.ts
@@ -48,6 +48,11 @@ export const historyItemSchema = z.object({
delegatedToId: z.string().optional(), // Last child this parent delegated to
childIds: z.array(z.string()).optional(), // All children spawned by this task
awaitingChildId: z.string().optional(), // Child currently awaited (set when delegated)
+ // Marks a read-only background child (design D10/D11): the parent registers the
+ // child in `childIds` and stamps the child with `backgroundParentTaskId`, but the
+ // singular `awaitingChildId` field is never written for a background child, so the
+ // delegation state machine is untouched.
+ backgroundParentTaskId: z.string().optional(),
completedByChildId: z.string().optional(), // Child that completed and resumed this parent
completionResultSummary: z.string().optional(), // Summary from completed child
pendingAction: pendingTaskActionSchema.optional(),
diff --git a/packages/types/src/tool.ts b/packages/types/src/tool.ts
index 03c10bc3e7..4443335cae 100644
--- a/packages/types/src/tool.ts
+++ b/packages/types/src/tool.ts
@@ -40,6 +40,7 @@ export const toolNames = [
"attempt_completion",
"switch_mode",
"new_task",
+ "parallel_subtasks",
"codebase_search",
"update_todo_list",
"run_slash_command",
diff --git a/packages/types/src/vscode-extension-host.ts b/packages/types/src/vscode-extension-host.ts
index 2e9ea7ccb8..589b21169c 100644
--- a/packages/types/src/vscode-extension-host.ts
+++ b/packages/types/src/vscode-extension-host.ts
@@ -941,6 +941,32 @@ export interface LanguageModelChatSelector {
id?: string
}
+/**
+ * One row of the parallel-subtasks progress panel.
+ *
+ * Mirrors `BackgroundChildEntry` in the extension package's
+ * `src/core/background-subtasks/types.ts`; keep the two in step.
+ */
+export interface ParallelSubtaskInfo {
+ /** Stable id of the spawned child task. */
+ taskId: string
+ /** Sibling-unique label from the tool call. */
+ label: string
+ /** Mode slug the child runs in. */
+ mode: string
+ status: "queued" | "running" | "completed" | "failed" | "aborted"
+ /** Absolute path of the saved report .md, once the child completed. */
+ reportPath?: string
+ /** One-line summary the host returns to the parent model. */
+ summary?: string
+ /** Why the child failed or was aborted. */
+ error?: string
+ /** Epoch ms the child started. */
+ startedAt?: number
+ /** Epoch ms the child reached a terminal state. */
+ finishedAt?: number
+}
+
export interface ClineSayTool {
tool:
| "editedExistingFile"
@@ -960,6 +986,7 @@ export interface ClineSayTool {
| "runSlashCommand"
| "updateTodoList"
| "skill"
+ | "parallelSubtasks"
path?: string
// For readCommandOutput
readStart?: number
@@ -1019,6 +1046,8 @@ export interface ClineSayTool {
description?: string
// Properties for skill tool
skill?: string
+ // Properties for parallel_subtasks tool
+ subtasks?: ParallelSubtaskInfo[]
}
export interface ClineAskUseMcpServer {
diff --git a/src/__tests__/ClineProvider.delegation.spec.ts b/src/__tests__/ClineProvider.delegation.spec.ts
index ab9201b01b..5f05f3e24c 100644
--- a/src/__tests__/ClineProvider.delegation.spec.ts
+++ b/src/__tests__/ClineProvider.delegation.spec.ts
@@ -9,8 +9,19 @@ import type { HistoryItem } from "@roo-code/types"
import { providerIdentifiers, RooCodeEventName } from "@roo-code/types"
import { ClineProvider } from "../core/webview/ClineProvider"
import { TaskScheduler } from "../core/task/TaskScheduler"
+import { TaskRegistry } from "../core/task/TaskRegistry"
import { LifecycleTransitionError } from "../core/task-persistence"
+/**
+ * Delegation drives real ClineProvider prototype methods against a plain
+ * double. `resolveLineageRoot` (D-01) reads `taskRegistry` from `this`, so
+ * every provider double carries a real (empty) registry; an empty registry
+ * is the production-reachable state for these tests (the root is absent).
+ */
+function makeProviderDouble(fields: Record): ClineProvider {
+ return { taskRegistry: new TaskRegistry(), ...fields } as unknown as ClineProvider
+}
+
const parentHistoryItem: HistoryItem = {
id: "parent-1",
task: "Parent",
@@ -69,13 +80,13 @@ describe("ClineProvider.delegateParentAndOpenChild()", () => {
},
}),
})
- const provider = {
+ const provider = makeProviderDouble({
getCurrentTask: vi.fn(() => parentTask),
removeClineFromStack,
createTask,
handleModeSwitch,
taskHistoryStore,
- } as unknown as ClineProvider
+ })
await expect(
ClineProvider.prototype.delegateParentAndOpenChild.call(provider, {
@@ -114,7 +125,7 @@ describe("ClineProvider.delegateParentAndOpenChild()", () => {
}
const parentTask = makeParentTask()
const child = { taskId: "child-1", run: vi.fn().mockResolvedValue(undefined) }
- const provider = {
+ const provider = makeProviderDouble({
taskScheduler: new TaskScheduler(),
emit: vi.fn(),
getCurrentTask: vi.fn(() => parentTask),
@@ -124,7 +135,7 @@ describe("ClineProvider.delegateParentAndOpenChild()", () => {
log: vi.fn(),
isViewLaunched: false,
taskHistoryStore,
- } as unknown as ClineProvider
+ })
await ClineProvider.prototype.delegateParentAndOpenChild.call(provider, {
parentTaskId: "parent-1",
@@ -164,7 +175,7 @@ describe("ClineProvider.delegateParentAndOpenChild()", () => {
})
const deleteTaskWithId = vi.fn().mockResolvedValue(undefined)
const createTaskWithHistoryItem = vi.fn().mockResolvedValue(undefined)
- const provider = {
+ const provider = makeProviderDouble({
taskScheduler: new TaskScheduler(),
emit: vi.fn(),
getCurrentTask,
@@ -177,7 +188,7 @@ describe("ClineProvider.delegateParentAndOpenChild()", () => {
log: vi.fn(),
isViewLaunched: false,
taskHistoryStore,
- } as unknown as ClineProvider
+ })
await expect(
ClineProvider.prototype.delegateParentAndOpenChild.call(provider, {
@@ -204,7 +215,7 @@ describe("ClineProvider.delegateParentAndOpenChild()", () => {
const handleModeSwitch = vi.fn().mockResolvedValue(undefined)
const taskHistoryStore = makeStoreStub()
- const provider = {
+ const provider = makeProviderDouble({
taskScheduler: new TaskScheduler(),
emit: providerEmit,
getCurrentTask: vi.fn(() => parentTask),
@@ -215,7 +226,7 @@ describe("ClineProvider.delegateParentAndOpenChild()", () => {
isViewLaunched: false,
recentTasksCache: undefined,
taskHistoryStore,
- } as unknown as ClineProvider
+ })
const child = await ClineProvider.prototype.delegateParentAndOpenChild.call(provider, {
parentTaskId: "parent-1",
@@ -243,6 +254,10 @@ describe("ClineProvider.delegateParentAndOpenChild()", () => {
initialTodos: [],
initialStatus: "active",
startTask: false,
+ // D-01: the lineage root is captured before removeClineFromStack and
+ // passed explicitly; with an empty registry and no in-memory
+ // parentTask the parent itself is the root.
+ rootTask: parentTask,
})
// Delegation metadata written via atomicReadAndUpdate with correct taskId
@@ -284,7 +299,7 @@ describe("ClineProvider.delegateParentAndOpenChild()", () => {
getCurrentProfileName: vi.fn(),
}
const workspaceGet = vi.fn().mockReturnValue(false)
- const provider = {
+ const provider = makeProviderDouble({
taskScheduler: new TaskScheduler(),
emit: vi.fn(),
getCurrentTask: vi.fn(() => parentTask),
@@ -297,7 +312,7 @@ describe("ClineProvider.delegateParentAndOpenChild()", () => {
// No window-local choice is recorded, so the lookup reaches the shared manager.
getModeConfigId: (mode: string) => providerSettingsManager.getModeConfigId(mode),
context: { workspaceState: { get: workspaceGet } },
- } as unknown as ClineProvider
+ })
await ClineProvider.prototype.delegateParentAndOpenChild.call(provider, {
parentTaskId: "parent-1",
@@ -339,7 +354,7 @@ describe("ClineProvider.delegateParentAndOpenChild()", () => {
openRouterModelId: "openai/gpt-4.1-mini",
})
const sharedGetModeConfigId = vi.fn().mockResolvedValue("other-window-profile-id")
- const provider = {
+ const provider = makeProviderDouble({
taskScheduler: new TaskScheduler(),
emit: vi.fn(),
getCurrentTask: vi.fn(() => parentTask),
@@ -352,7 +367,7 @@ describe("ClineProvider.delegateParentAndOpenChild()", () => {
// This window's own choice differs from the shared value another window wrote.
getModeConfigId: vi.fn().mockResolvedValue("local-profile-id"),
context: { workspaceState: { get: vi.fn().mockReturnValue(false) } },
- } as unknown as ClineProvider
+ })
await ClineProvider.prototype.delegateParentAndOpenChild.call(provider, {
parentTaskId: "parent-1",
@@ -396,7 +411,7 @@ describe("ClineProvider.delegateParentAndOpenChild()", () => {
: vi.fn().mockResolvedValue(savedProfile)
const log = vi.fn()
const getModeConfigId = vi.fn().mockResolvedValue(savedConfigId)
- const provider = {
+ const provider = makeProviderDouble({
taskScheduler: new TaskScheduler(),
emit: vi.fn(),
getCurrentTask: vi.fn(() => parentTask),
@@ -409,7 +424,7 @@ describe("ClineProvider.delegateParentAndOpenChild()", () => {
// No window-local choice is recorded, so the lookup reaches the shared manager.
getModeConfigId,
context: { workspaceState: { get: vi.fn().mockReturnValue(false) } },
- } as unknown as ClineProvider
+ })
await ClineProvider.prototype.delegateParentAndOpenChild.call(provider, {
parentTaskId: "parent-1",
@@ -450,7 +465,7 @@ describe("ClineProvider.delegateParentAndOpenChild()", () => {
get: vi.fn().mockReturnValueOnce(parentHistoryItem).mockReturnValue(updatedParent),
})
- const provider = {
+ const provider = makeProviderDouble({
taskScheduler: new TaskScheduler(),
emit: vi.fn(),
getCurrentTask: vi.fn(() => parentTask),
@@ -462,7 +477,7 @@ describe("ClineProvider.delegateParentAndOpenChild()", () => {
isViewLaunched: true,
recentTasksCache: undefined,
taskHistoryStore,
- } as unknown as ClineProvider
+ })
await ClineProvider.prototype.delegateParentAndOpenChild.call(provider, {
parentTaskId: "parent-1",
@@ -484,7 +499,7 @@ describe("ClineProvider.delegateParentAndOpenChild()", () => {
get: vi.fn().mockReturnValue(undefined),
})
- const provider = {
+ const provider = makeProviderDouble({
taskScheduler: new TaskScheduler(),
emit: vi.fn(),
getCurrentTask: vi.fn(() => parentTask),
@@ -496,7 +511,7 @@ describe("ClineProvider.delegateParentAndOpenChild()", () => {
isViewLaunched: true,
recentTasksCache: undefined,
taskHistoryStore,
- } as unknown as ClineProvider
+ })
await ClineProvider.prototype.delegateParentAndOpenChild.call(provider, {
parentTaskId: "parent-1",
@@ -526,7 +541,7 @@ describe("ClineProvider.delegateParentAndOpenChild()", () => {
}),
})
- const provider = {
+ const provider = makeProviderDouble({
taskScheduler: new TaskScheduler(),
emit: vi.fn(),
getCurrentTask: vi.fn(() => parentTask),
@@ -537,7 +552,7 @@ describe("ClineProvider.delegateParentAndOpenChild()", () => {
isViewLaunched: false,
recentTasksCache: undefined,
taskHistoryStore,
- } as unknown as ClineProvider
+ })
await ClineProvider.prototype.delegateParentAndOpenChild.call(provider, {
parentTaskId: "parent-1",
@@ -573,7 +588,7 @@ describe("ClineProvider.delegateParentAndOpenChild()", () => {
}),
})
- const provider = {
+ const provider = makeProviderDouble({
taskScheduler: new TaskScheduler(),
emit: vi.fn(),
getCurrentTask: vi.fn(() => makeParentTask()),
@@ -584,7 +599,7 @@ describe("ClineProvider.delegateParentAndOpenChild()", () => {
isViewLaunched: false,
recentTasksCache: undefined,
taskHistoryStore,
- } as unknown as ClineProvider
+ })
await ClineProvider.prototype.delegateParentAndOpenChild.call(provider, {
parentTaskId: "parent-1",
@@ -634,7 +649,7 @@ describe("ClineProvider.delegateParentAndOpenChild()", () => {
}),
})
- const provider = {
+ const provider = makeProviderDouble({
taskScheduler: new TaskScheduler(),
emit: vi.fn(),
getCurrentTask,
@@ -648,7 +663,7 @@ describe("ClineProvider.delegateParentAndOpenChild()", () => {
isViewLaunched: false,
recentTasksCache: undefined,
taskHistoryStore,
- } as unknown as ClineProvider
+ })
await expect(
ClineProvider.prototype.delegateParentAndOpenChild.call(provider, {
@@ -670,12 +685,12 @@ describe("ClineProvider.delegateParentAndOpenChild()", () => {
const taskHistoryStore = makeStoreStub({
get: vi.fn().mockReturnValue({ ...parentHistoryItem, status: "delegated" }),
})
- const provider = {
+ const provider = makeProviderDouble({
getCurrentTask: vi.fn(() => parentTask),
removeClineFromStack: vi.fn(),
createTask: vi.fn(),
taskHistoryStore,
- } as unknown as ClineProvider
+ })
await expect(
ClineProvider.prototype.delegateParentAndOpenChild.call(provider, {
@@ -713,7 +728,7 @@ describe("ClineProvider.delegateParentAndOpenChild()", () => {
return [durableParent]
}),
}
- const provider = {
+ const provider = makeProviderDouble({
taskScheduler: new TaskScheduler(),
emit: vi.fn(),
getCurrentTask: vi.fn(() => parent),
@@ -722,7 +737,7 @@ describe("ClineProvider.delegateParentAndOpenChild()", () => {
log: vi.fn(),
isViewLaunched: false,
taskHistoryStore: store,
- } as unknown as ClineProvider
+ })
return { provider, child, removeClineFromStack }
}
@@ -775,7 +790,7 @@ describe("ClineProvider.delegateParentAndOpenChild()", () => {
return child
})
- const provider = {
+ const provider = makeProviderDouble({
taskScheduler: new TaskScheduler(),
emit: vi.fn(),
getCurrentTask,
@@ -789,7 +804,7 @@ describe("ClineProvider.delegateParentAndOpenChild()", () => {
isViewLaunched: false,
recentTasksCache: undefined,
taskHistoryStore,
- } as unknown as ClineProvider
+ })
await expect(
ClineProvider.prototype.delegateParentAndOpenChild.call(provider, {
@@ -842,7 +857,7 @@ describe("ClineProvider.delegateParentAndOpenChild()", () => {
return current
}),
}
- const provider = {
+ const provider = makeProviderDouble({
taskScheduler: new TaskScheduler(),
recentTasksCache: [parentHistoryItem],
emit: vi.fn(),
@@ -856,7 +871,7 @@ describe("ClineProvider.delegateParentAndOpenChild()", () => {
log: vi.fn(),
isViewLaunched: false,
taskHistoryStore,
- } as unknown as ClineProvider
+ })
await expect(
ClineProvider.prototype.delegateParentAndOpenChild.call(provider, {
@@ -905,7 +920,7 @@ describe("ClineProvider.delegateParentAndOpenChild()", () => {
const clearPendingActionIfMatching = vi.fn()
const deleteTaskWithId = vi.fn().mockResolvedValue(undefined)
const createTaskWithHistoryItem = vi.fn().mockResolvedValue(undefined)
- const provider = {
+ const provider = makeProviderDouble({
taskScheduler: new TaskScheduler(),
emit: vi.fn(),
getCurrentTask,
@@ -923,7 +938,7 @@ describe("ClineProvider.delegateParentAndOpenChild()", () => {
atomicReadAndUpdate,
clearPendingActionIfMatching,
},
- } as unknown as ClineProvider
+ })
let rejection: unknown
try {
@@ -969,7 +984,7 @@ describe("ClineProvider.delegateParentAndOpenChild()", () => {
const atomicReadAndUpdate = vi.fn().mockRejectedValue(persistenceError)
const clearPendingActionIfMatching = vi.fn().mockResolvedValue(interruptedParent)
const createTaskWithHistoryItem = vi.fn().mockResolvedValue(undefined)
- const provider = {
+ const provider = makeProviderDouble({
taskScheduler: new TaskScheduler(),
emit: vi.fn(),
getCurrentTask,
@@ -987,7 +1002,7 @@ describe("ClineProvider.delegateParentAndOpenChild()", () => {
atomicReadAndUpdate,
clearPendingActionIfMatching,
},
- } as unknown as ClineProvider
+ })
await expect(
ClineProvider.prototype.delegateParentAndOpenChild.call(provider, {
@@ -1034,7 +1049,7 @@ describe("ClineProvider.delegateParentAndOpenChild()", () => {
})
const clearPendingActionIfMatching = vi.fn().mockRejectedValue(settlementError)
const createTaskWithHistoryItem = vi.fn().mockResolvedValue(undefined)
- const provider = {
+ const provider = makeProviderDouble({
taskScheduler: new TaskScheduler(),
emit: vi.fn(),
getCurrentTask,
@@ -1052,7 +1067,7 @@ describe("ClineProvider.delegateParentAndOpenChild()", () => {
atomicReadAndUpdate,
clearPendingActionIfMatching,
},
- } as unknown as ClineProvider
+ })
await expect(
ClineProvider.prototype.delegateParentAndOpenChild.call(provider, {
@@ -1098,7 +1113,7 @@ describe("ClineProvider.delegateParentAndOpenChild()", () => {
})
const clearPendingActionIfMatching = vi.fn().mockResolvedValue(completedParent)
const createTaskWithHistoryItem = vi.fn().mockResolvedValue(undefined)
- const provider = {
+ const provider = makeProviderDouble({
taskScheduler: new TaskScheduler(),
emit: vi.fn(),
getCurrentTask,
@@ -1119,7 +1134,7 @@ describe("ClineProvider.delegateParentAndOpenChild()", () => {
}),
clearPendingActionIfMatching,
},
- } as unknown as ClineProvider
+ })
await expect(
ClineProvider.prototype.delegateParentAndOpenChild.call(provider, {
@@ -1165,7 +1180,7 @@ describe("ClineProvider.delegateParentAndOpenChild()", () => {
})
const clearPendingActionIfMatching = vi.fn(async (_taskId: string, _actionId: string) => replacedParent)
const createTaskWithHistoryItem = vi.fn().mockResolvedValue(undefined)
- const provider = {
+ const provider = makeProviderDouble({
taskScheduler: new TaskScheduler(),
emit: vi.fn(),
getCurrentTask,
@@ -1186,7 +1201,7 @@ describe("ClineProvider.delegateParentAndOpenChild()", () => {
}),
clearPendingActionIfMatching,
},
- } as unknown as ClineProvider
+ })
await expect(
ClineProvider.prototype.delegateParentAndOpenChild.call(provider, {
@@ -1242,7 +1257,7 @@ describe("ClineProvider.delegateParentAndOpenChild()", () => {
})
const clearPendingActionIfMatching = vi.fn(async () => settledParent)
- const provider = {
+ const provider = makeProviderDouble({
taskScheduler: new TaskScheduler(),
recentTasksCache: [parentHistoryItem],
emit: vi.fn(),
@@ -1271,7 +1286,7 @@ describe("ClineProvider.delegateParentAndOpenChild()", () => {
clearPendingActionIfMatching,
deleteMany: vi.fn().mockResolvedValue(undefined),
},
- } as unknown as ClineProvider
+ })
try {
await expect(
diff --git a/src/core/assistant-message/NativeToolCallParser.ts b/src/core/assistant-message/NativeToolCallParser.ts
index 90da07cc8d..50ec617a8c 100644
--- a/src/core/assistant-message/NativeToolCallParser.ts
+++ b/src/core/assistant-message/NativeToolCallParser.ts
@@ -24,6 +24,19 @@ import { MCP_TOOL_PREFIX, MCP_TOOL_SEPARATOR, parseMcpToolName, normalizeMcpTool
*/
type NativeArgsFor = TName extends keyof NativeToolArgs ? NativeToolArgs[TName] : never
+/**
+ * Hard ceiling on the `tasks` array of one `parallel_subtasks` call. The tool
+ * documents a per-call fan-out of 6 with excess entries dropped; this ceiling
+ * bounds the call itself so one model response cannot post an unbounded
+ * approval payload, mint N-6 progress rows, or drive the label de-duplication
+ * in the tool with an unbounded entry count. The parser keeps one entry past
+ * the ceiling so the tool can tell an over-limit request from an at-limit one.
+ */
+export const MAX_REQUESTED_PARALLEL_SUBTASKS = 50
+
+/** Collection stops here; one past the ceiling is what makes an over-limit call detectable. */
+const MAX_COLLECTED_PARALLEL_SUBTASKS = MAX_REQUESTED_PARALLEL_SUBTASKS + 1
+
/**
* Parser for native tool calls (OpenAI-style function calling).
* Converts native tool call format to ToolUse format for compatibility
@@ -440,6 +453,59 @@ export class NativeToolCallParser {
})
}
+ /**
+ * Normalize raw `parallel_subtasks` task entries into the tool's native args
+ * shape. Accepts the array directly or a JSON-stringified array (some models
+ * double-stringify), and drops entries that lack a string mode and message so
+ * a partially streamed call surfaces only the entries that are complete.
+ * Collection stops one past `MAX_REQUESTED_PARALLEL_SUBTASKS`, so the array
+ * is bounded at parse time and the tool can still report an over-limit call.
+ *
+ * @returns The qualifying tasks, or undefined when no entry qualifies yet.
+ */
+ private static normalizeParallelSubtaskTasks(
+ value: unknown,
+ ): NativeToolArgs["parallel_subtasks"]["tasks"] | undefined {
+ let entries: unknown[] | undefined
+ if (Array.isArray(value)) {
+ entries = value
+ } else if (typeof value === "string") {
+ try {
+ const parsed: unknown = JSON.parse(value)
+ if (Array.isArray(parsed)) {
+ entries = parsed
+ }
+ } catch {
+ // Not valid JSON (yet); nothing to surface.
+ }
+ }
+
+ if (!entries) {
+ return undefined
+ }
+
+ const tasks: NativeToolArgs["parallel_subtasks"]["tasks"] = []
+ for (const entry of entries) {
+ if (tasks.length >= MAX_COLLECTED_PARALLEL_SUBTASKS) {
+ break
+ }
+ if (typeof entry !== "object" || entry === null) {
+ continue
+ }
+ const record = entry as Record
+ if (typeof record.mode !== "string" || typeof record.message !== "string") {
+ continue
+ }
+ tasks.push({
+ ...(typeof record.label === "string" ? { label: record.label } : {}),
+ mode: record.mode,
+ message: record.message,
+ })
+ }
+
+ return tasks.length > 0 ? tasks : undefined
+ }
+
/**
* Create a partial ToolUse from currently parsed arguments.
* Used during streaming to show progress.
@@ -712,6 +778,14 @@ export class NativeToolCallParser {
}
break
+ case "parallel_subtasks": {
+ const tasks = this.normalizeParallelSubtaskTasks(partialArgs.tasks)
+ if (tasks) {
+ nativeArgs = { tasks }
+ }
+ break
+ }
+
default:
break
}
@@ -1067,6 +1141,14 @@ export class NativeToolCallParser {
}
break
+ case "parallel_subtasks": {
+ const tasks = this.normalizeParallelSubtaskTasks(args.tasks)
+ if (tasks) {
+ nativeArgs = { tasks } as NativeArgsFor
+ }
+ break
+ }
+
default:
if (customToolRegistry.has(resolvedName)) {
nativeArgs = args as NativeArgsFor
diff --git a/src/core/assistant-message/__tests__/NativeToolCallParser-parallel-subtasks.spec.ts b/src/core/assistant-message/__tests__/NativeToolCallParser-parallel-subtasks.spec.ts
new file mode 100644
index 0000000000..cd3a3edcc6
--- /dev/null
+++ b/src/core/assistant-message/__tests__/NativeToolCallParser-parallel-subtasks.spec.ts
@@ -0,0 +1,174 @@
+// npx vitest src/core/assistant-message/__tests__/NativeToolCallParser-parallel-subtasks.spec.ts
+
+import { describe, it, expect, vi } from "vitest"
+
+import type { McpToolUse, ToolUse } from "../../../shared/tools"
+import { MAX_REQUESTED_PARALLEL_SUBTASKS, NativeToolCallParser } from "../NativeToolCallParser"
+
+const parseComplete = (args: unknown) =>
+ NativeToolCallParser.parseToolCall({
+ id: "call_parallel",
+ name: "parallel_subtasks",
+ arguments: JSON.stringify(args),
+ })
+
+/** Narrow the parser union to the native tool branch these tests exercise. */
+function asToolUse(result: ToolUse<"parallel_subtasks"> | McpToolUse | null): ToolUse<"parallel_subtasks"> {
+ if (!result || result.type !== "tool_use") {
+ throw new Error("expected a parallel_subtasks tool_use result")
+ }
+ return result
+}
+
+function parsePartial(argumentsJson: string): ToolUse<"parallel_subtasks"> | null {
+ const scope = NativeToolCallParser.createScope()
+ NativeToolCallParser.startStreamingToolCall("call_parallel_partial", "parallel_subtasks", scope)
+ const key = NativeToolCallParser.makeStreamingKey("call_parallel_partial", "parallel_subtasks")
+ // The streaming parser types the name as the full union; this call started a
+ // parallel_subtasks tool call, so narrow at the seam.
+ return NativeToolCallParser.processStreamingChunk(key, argumentsJson, scope) as ToolUse<"parallel_subtasks"> | null
+}
+
+describe("NativeToolCallParser - parallel_subtasks", () => {
+ describe("complete calls", () => {
+ it("keeps mode, message and label", () => {
+ const result = parseComplete({
+ tasks: [
+ { label: "api-surface", mode: "code", message: "Map the task API." },
+ { label: "test-gaps", mode: "debug", message: "Find untested branches." },
+ ],
+ })
+
+ expect(result?.type).toBe("tool_use")
+ expect(asToolUse(result).nativeArgs).toEqual({
+ tasks: [
+ { label: "api-surface", mode: "code", message: "Map the task API." },
+ { label: "test-gaps", mode: "debug", message: "Find untested branches." },
+ ],
+ })
+ })
+
+ it("treats a null label as absent", () => {
+ const result = parseComplete({
+ tasks: [{ label: null, mode: "code", message: "Map the task API." }],
+ })
+
+ expect(asToolUse(result).nativeArgs).toEqual({
+ tasks: [{ mode: "code", message: "Map the task API." }],
+ })
+ })
+
+ it("drops entries that lack a string mode or message", () => {
+ const result = parseComplete({
+ tasks: [
+ { label: "no-message", mode: "code" },
+ { label: "no-mode", message: "Investigate." },
+ { label: "numeric-mode", mode: 7, message: "Investigate." },
+ { label: "valid", mode: "debug", message: "Investigate." },
+ ],
+ })
+
+ expect(asToolUse(result).nativeArgs).toEqual({
+ tasks: [{ label: "valid", mode: "debug", message: "Investigate." }],
+ })
+ })
+
+ it("preserves more than six entries because the cap is enforced at spawn time", () => {
+ const tasks = Array.from({ length: 7 }, (_, index) => ({
+ label: `investigation-${index}`,
+ mode: "code",
+ message: `Investigation ${index}.`,
+ }))
+
+ const result = parseComplete({ tasks })
+
+ expect(asToolUse(result).nativeArgs).toEqual({ tasks })
+ })
+
+ it("preserves a list exactly at the requested-entry ceiling", () => {
+ const tasks = Array.from({ length: MAX_REQUESTED_PARALLEL_SUBTASKS }, (_, index) => ({
+ label: `investigation-${index}`,
+ mode: "code",
+ message: `Investigation ${index}.`,
+ }))
+
+ expect(asToolUse(parseComplete({ tasks })).nativeArgs).toEqual({ tasks })
+ })
+
+ it("stops one past the ceiling so the tool can reject an oversized call", () => {
+ const tasks = Array.from({ length: MAX_REQUESTED_PARALLEL_SUBTASKS + 150 }, (_, index) => ({
+ label: `investigation-${index}`,
+ mode: "code",
+ message: `Investigation ${index}.`,
+ }))
+
+ const bounded = asToolUse(parseComplete({ tasks })).nativeArgs?.tasks ?? []
+
+ expect(bounded).toHaveLength(MAX_REQUESTED_PARALLEL_SUBTASKS + 1)
+ expect(bounded[0]).toEqual(tasks[0])
+ expect(bounded.at(-1)).toEqual(tasks[MAX_REQUESTED_PARALLEL_SUBTASKS])
+ })
+
+ it.each([
+ ["a missing task list", {}],
+ ["an empty task list", { tasks: [] }],
+ ["a task list with no qualifying entry", { tasks: [{ label: "broken" }] }],
+ ["a non-array task list", { tasks: "not-an-array" }],
+ ])("rejects %s as an invalid tool call", (_case, args) => {
+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => undefined)
+ try {
+ expect(parseComplete(args)).toBeNull()
+ } finally {
+ errorSpy.mockRestore()
+ }
+ })
+ })
+
+ describe("partial calls", () => {
+ it("uses a streamed task array directly", () => {
+ const partial = parsePartial('{"tasks":[{"label":"api","mode":"code","message":"Map it."}]}')
+
+ expect(partial?.name).toBe("parallel_subtasks")
+ expect(partial?.partial).toBe(true)
+ expect(partial?.nativeArgs).toEqual({
+ tasks: [{ label: "api", mode: "code", message: "Map it." }],
+ })
+ })
+
+ it("parses a JSON-stringified task array", () => {
+ const tasks = JSON.stringify([{ label: "api", mode: "code", message: "Map it." }])
+ const partial = parsePartial(JSON.stringify({ tasks }))
+
+ expect(partial?.nativeArgs).toEqual({
+ tasks: [{ label: "api", mode: "code", message: "Map it." }],
+ })
+ })
+
+ it("only surfaces entries that are already complete", () => {
+ const partial = parsePartial(
+ '{"tasks":[{"label":"api","mode":"code","message":"Map it."},{"label":"next"}]}',
+ )
+
+ expect(partial?.nativeArgs).toEqual({
+ tasks: [{ label: "api", mode: "code", message: "Map it." }],
+ })
+ })
+
+ it("leaves nativeArgs undefined until a task arrives", () => {
+ expect(parsePartial('{"note":"filling in"}')?.nativeArgs).toBeUndefined()
+ expect(parsePartial('{"tasks":[]}')?.nativeArgs).toBeUndefined()
+ })
+
+ it("bounds a streamed oversized array the same way as a complete call", () => {
+ const tasks = Array.from({ length: MAX_REQUESTED_PARALLEL_SUBTASKS + 150 }, (_, index) => ({
+ label: `investigation-${index}`,
+ mode: "code",
+ message: `Investigation ${index}.`,
+ }))
+
+ const partial = parsePartial(JSON.stringify({ tasks }))
+
+ expect(partial?.nativeArgs?.tasks).toHaveLength(MAX_REQUESTED_PARALLEL_SUBTASKS + 1)
+ })
+ })
+})
diff --git a/src/core/assistant-message/__tests__/presentAssistantMessage-parallel-subtasks.spec.ts b/src/core/assistant-message/__tests__/presentAssistantMessage-parallel-subtasks.spec.ts
new file mode 100644
index 0000000000..34c8049e2c
--- /dev/null
+++ b/src/core/assistant-message/__tests__/presentAssistantMessage-parallel-subtasks.spec.ts
@@ -0,0 +1,252 @@
+// npx vitest src/core/assistant-message/__tests__/presentAssistantMessage-parallel-subtasks.spec.ts
+
+import { describe, it, expect, beforeEach, vi } from "vitest"
+
+import { DispatchState } from "../../task/dispatchState"
+import type { Task } from "../../task/Task"
+import type { RequestPolicySnapshot } from "../../prompts/tools/effective-tool-policy"
+import { clearAllMocks } from "../../../test-utils/reset"
+
+import { presentAssistantMessage } from "../presentAssistantMessage"
+import { validateToolUse } from "../../tools/validateToolUse"
+
+vi.mock("../../task/Task")
+vi.mock("../../tools/validateToolUse", async (importOriginal) => {
+ const actual = await importOriginal()
+ return {
+ ...actual,
+ // Keep the real validator: it enforces the parallelSubtasks experiment
+ // gate, so a presenter that stops forwarding the request's experiments
+ // fails here instead of silently dispatching and spawning.
+ validateToolUse: vi.fn(actual.validateToolUse),
+ // The presenter maps a validated tool name to its telemetry key through this
+ // predicate, so the double must know the tool it is asked about.
+ isValidToolName: vi.fn((toolName: string) => toolName === "parallel_subtasks"),
+ }
+})
+vi.mock("@roo-code/core", () => ({
+ customToolRegistry: {
+ has: vi.fn(),
+ get: vi.fn(),
+ },
+}))
+vi.mock("@roo-code/telemetry", () => ({
+ TelemetryService: {
+ instance: {
+ captureToolUsage: vi.fn(),
+ captureConsecutiveMistakeError: vi.fn(),
+ captureEvent: vi.fn(),
+ },
+ },
+}))
+
+const baseSnapshot: RequestPolicySnapshot = {
+ disabledTools: [],
+ customModes: [],
+ experiments: { customTools: false },
+}
+
+/**
+ * The members `presentAssistantMessage` reads on the block and tool paths these
+ * tests exercise. A real `Task` needs the extension host.
+ */
+interface TaskDouble {
+ taskId: string
+ instanceId: string
+ abort: boolean
+ dispatchState: DispatchState
+ pendingWork: { mode: "serial" } | null
+ currentStreamingContentIndex: number
+ assistantMessageContent: unknown[]
+ userMessageContent: unknown[]
+ didCompleteReadingStream: boolean
+ didRejectTool: boolean
+ didAlreadyUseTool: boolean
+ activeToolContexts: Map
+ consecutiveMistakeCount: number
+ consecutiveMistakeLimit: number
+ userMessageContentReady: boolean
+ getTaskMode: () => Promise
+ api: { getModel: () => { id: string; info: Record } }
+ recordToolUsage: (toolName: string) => void
+ recordToolError: (toolName: string, error?: string) => void
+ toolRepetitionDetector: { check: (block: unknown) => { action: string } }
+ providerRef: {
+ deref: () => {
+ getState: () => Promise>
+ spawnBackgroundChildren: (
+ parent: unknown,
+ specs: Array<{ label: string; mode: string; message: string }>,
+ ) => Promise<{ children: unknown[]; started: boolean }>
+ abortBackgroundChildren: (parentTaskId: string) => Promise
+ }
+ }
+ providerDouble: {
+ getState: ReturnType
+ spawnBackgroundChildren: ReturnType
+ abortBackgroundChildren: ReturnType
+ }
+ once: (event: string, listener: () => void) => void
+ off: (event: string, listener: () => void) => void
+ say: (type: string, text?: string, images?: unknown, partial?: boolean) => Promise
+ ask: (type: string, text?: string) => Promise<{ response: string; text?: string; images?: unknown[] }>
+ pushToolResultToUserContent: (block: unknown) => boolean
+ persistQueuedFeedbackAndAcknowledge: () => Promise
+ finalizePartialToolAsk: () => Promise
+}
+
+function createTaskDouble(): TaskDouble {
+ const providerDouble = {
+ getState: vi.fn().mockResolvedValue({ mode: "code", customModes: [] }),
+ spawnBackgroundChildren: vi.fn().mockResolvedValue({ children: [], started: false }),
+ abortBackgroundChildren: vi.fn().mockResolvedValue(undefined),
+ }
+ return {
+ taskId: "test-task-id",
+ instanceId: "test-instance",
+ abort: false,
+ dispatchState: DispatchState.IDLE,
+ pendingWork: null,
+ currentStreamingContentIndex: 0,
+ assistantMessageContent: [],
+ userMessageContent: [],
+ didCompleteReadingStream: true,
+ didRejectTool: false,
+ didAlreadyUseTool: false,
+ activeToolContexts: new Map(),
+ consecutiveMistakeCount: 0,
+ consecutiveMistakeLimit: 3,
+ userMessageContentReady: false,
+ getTaskMode: vi.fn().mockResolvedValue("code"),
+ api: { getModel: () => ({ id: "test-model", info: {} }) },
+ recordToolUsage: vi.fn(),
+ recordToolError: vi.fn(),
+ toolRepetitionDetector: { check: vi.fn().mockReturnValue({ action: "allow" }) },
+ providerDouble,
+ providerRef: { deref: () => providerDouble },
+ once: vi.fn(),
+ off: vi.fn(),
+ say: vi.fn().mockResolvedValue(undefined),
+ ask: vi.fn().mockResolvedValue({ response: "yesButtonClicked" }),
+ pushToolResultToUserContent: vi.fn().mockReturnValue(true),
+ persistQueuedFeedbackAndAcknowledge: vi.fn().mockResolvedValue(undefined),
+ finalizePartialToolAsk: vi.fn().mockResolvedValue(undefined),
+ }
+}
+
+function parallelSubtasksBlock(nativeArgs: unknown) {
+ return {
+ type: "tool_use",
+ id: "tool_call_parallel",
+ name: "parallel_subtasks",
+ params: {},
+ nativeArgs,
+ partial: false,
+ }
+}
+
+describe("presentAssistantMessage - parallel_subtasks", () => {
+ let taskDouble: TaskDouble
+ let task: Task
+
+ beforeEach(() => {
+ clearAllMocks()
+ taskDouble = createTaskDouble()
+ // The double stands in for a Task on the paths under test only.
+ task = taskDouble as unknown as Task
+ })
+
+ describe("tool description", () => {
+ it.each([
+ [
+ "two investigations",
+ {
+ tasks: [
+ { label: "api", mode: "code", message: "Map it." },
+ { mode: "debug", message: "Check it." },
+ ],
+ },
+ "2",
+ ],
+ ["no parsed tasks yet", undefined, "0"],
+ ])("names the child count for %s", async (_case, nativeArgs, expectedCount) => {
+ taskDouble.assistantMessageContent = [parallelSubtasksBlock(nativeArgs)]
+ // The rejected-tool path is the presenter's description surface: it
+ // reports the skipped tool with the same string the approval row uses.
+ taskDouble.didRejectTool = true
+
+ await presentAssistantMessage(task, baseSnapshot)
+
+ expect(taskDouble.pushToolResultToUserContent).toHaveBeenCalledWith(
+ expect.objectContaining({
+ content: `Skipping tool [parallel_subtasks for ${expectedCount} read-only investigation(s)] due to user rejecting a previous tool.`,
+ }),
+ )
+ })
+ })
+
+ describe("execution dispatch", () => {
+ it("routes a complete block out of validation and into the handler", async () => {
+ taskDouble.assistantMessageContent = [
+ parallelSubtasksBlock({ tasks: [{ label: "api", mode: "code", message: "Map it." }] }),
+ ]
+ // The real validator rejects parallel_subtasks unless the request's
+ // experiment snapshot enables it — the snapshot attemptApiRequest
+ // publishes when the host flag is on.
+ const snapshot: RequestPolicySnapshot = {
+ ...baseSnapshot,
+ experiments: { ...baseSnapshot.experiments, parallelSubtasks: true },
+ }
+
+ await presentAssistantMessage(task, snapshot)
+
+ const validateToolUseMock = vi.mocked(validateToolUse)
+ expect(validateToolUseMock).toHaveBeenCalledOnce()
+ expect(validateToolUseMock.mock.calls[0][0]).toBe("parallel_subtasks")
+ // The presenter must forward the request's experiment gate to the
+ // validator; without it the real validator rejects the dispatch this
+ // test asserts on.
+ expect(validateToolUseMock.mock.calls[0][5]).toEqual(snapshot.experiments)
+ expect(taskDouble.recordToolUsage).toHaveBeenCalledWith("parallel_subtasks")
+ expect(taskDouble.recordToolError).not.toHaveBeenCalled()
+ expect(taskDouble.consecutiveMistakeCount).toBe(0)
+ // The handler itself ran with the presenter's four callbacks: it asked
+ // for approval, spawned zero children for the block, and pushed its
+ // tool result back through the presenter.
+ expect(taskDouble.providerDouble.spawnBackgroundChildren).toHaveBeenCalledOnce()
+ expect(taskDouble.pushToolResultToUserContent).toHaveBeenCalled()
+ })
+
+ it.each([
+ ["false", { ...baseSnapshot.experiments, parallelSubtasks: false }],
+ ["absent", baseSnapshot.experiments],
+ ])("rejects the block and spawns nothing when the experiment flag is %s", async (_case, experiments) => {
+ taskDouble.assistantMessageContent = [
+ parallelSubtasksBlock({ tasks: [{ label: "api", mode: "code", message: "Map it." }] }),
+ ]
+ const snapshot: RequestPolicySnapshot = { ...baseSnapshot, experiments }
+
+ await presentAssistantMessage(task, snapshot)
+
+ // The real validator enforces the gate: an absent flag reads as off,
+ // same as false, so the block fails before any handler runs. The
+ // message is JSON-encoded inside the tool_result, so match a
+ // quote-free fragment.
+ expect(taskDouble.pushToolResultToUserContent).toHaveBeenCalledWith(
+ expect.objectContaining({
+ is_error: true,
+ content: expect.stringContaining("not allowed in code mode"),
+ }),
+ )
+ expect(taskDouble.recordToolError).toHaveBeenCalledWith(
+ "parallel_subtasks",
+ 'Tool "parallel_subtasks" is not allowed in code mode.',
+ )
+ expect(taskDouble.consecutiveMistakeCount).toBe(1)
+ // Gate closed: no usage recorded, no approval asked, no children spawned.
+ expect(taskDouble.recordToolUsage).not.toHaveBeenCalled()
+ expect(taskDouble.ask).not.toHaveBeenCalled()
+ expect(taskDouble.providerDouble.spawnBackgroundChildren).not.toHaveBeenCalled()
+ })
+ })
+})
diff --git a/src/core/assistant-message/presentAssistantMessage.ts b/src/core/assistant-message/presentAssistantMessage.ts
index 73d48b2e7c..2c33ee695c 100644
--- a/src/core/assistant-message/presentAssistantMessage.ts
+++ b/src/core/assistant-message/presentAssistantMessage.ts
@@ -38,6 +38,7 @@ import { updateTodoListTool } from "../tools/UpdateTodoListTool"
import { runSlashCommandTool } from "../tools/RunSlashCommandTool"
import { skillTool } from "../tools/SkillTool"
import { generateImageTool } from "../tools/GenerateImageTool"
+import { parallelSubtasksTool } from "../tools/ParallelSubtasksTool"
import { applyDiffTool as applyDiffToolClass } from "../tools/ApplyDiffTool"
import { isValidToolName, validateToolUse } from "../tools/validateToolUse"
import { buildToolRequirements, type RequestPolicySnapshot } from "../prompts/tools/effective-tool-policy"
@@ -524,6 +525,10 @@ async function presentAssistantMessageBlock(cline: Task, policySnapshot: Request
const modeName = getModeBySlug(mode, customModes)?.name ?? mode
return `[${block.name} in ${modeName} mode: '${message}']`
}
+ case "parallel_subtasks": {
+ const taskCount = block.nativeArgs?.tasks?.length ?? 0
+ return `[${block.name} for ${taskCount} read-only investigation(s)]`
+ }
case "run_slash_command":
return `[${block.name} for '${block.params.command}'${block.params.args ? ` with args: ${block.params.args}` : ""}]`
case "skill":
@@ -1031,6 +1036,15 @@ async function presentAssistantMessageBlock(cline: Task, policySnapshot: Request
toolCallId,
})
break
+ case "parallel_subtasks": {
+ await parallelSubtasksTool.handle(cline, block as ToolUse<"parallel_subtasks">, {
+ askApproval,
+ handleError,
+ pushToolResult,
+ toolCallId,
+ })
+ break
+ }
case "attempt_completion": {
const completionCallbacks: AttemptCompletionCallbacks = {
askApproval,
diff --git a/src/core/auto-approval/__tests__/parallelSubtasks.spec.ts b/src/core/auto-approval/__tests__/parallelSubtasks.spec.ts
new file mode 100644
index 0000000000..209c8dccb8
--- /dev/null
+++ b/src/core/auto-approval/__tests__/parallelSubtasks.spec.ts
@@ -0,0 +1,74 @@
+// npx vitest run src/core/auto-approval/__tests__/parallelSubtasks.spec.ts
+
+import { checkAutoApproval } from ".."
+
+import { CWD, baseState } from "./fixtures"
+
+const parallelSubtasksAsk = JSON.stringify({
+ tool: "parallelSubtasks",
+ tasks: [{ label: "api-surface", mode: "code", message: "Map the public API." }],
+})
+
+describe("alwaysAllowSubtasks covers parallelSubtasks", () => {
+ it("approves the fan-out when the subtask switch is on", async () => {
+ await expect(
+ checkAutoApproval({
+ state: { ...baseState, alwaysAllowSubtasks: true },
+ cwd: CWD,
+ ask: "tool",
+ text: parallelSubtasksAsk,
+ }),
+ ).resolves.toEqual({ decision: "approve" })
+ })
+
+ it("asks when the subtask switch is off", async () => {
+ await expect(
+ checkAutoApproval({ state: baseState, cwd: CWD, ask: "tool", text: parallelSubtasksAsk }),
+ ).resolves.toEqual({
+ decision: "ask",
+ })
+ })
+})
+
+describe("alwaysAllowSubtasks mapping for newTask and finishTask", () => {
+ it.each(["newTask", "finishTask"])("approves %s when the switch is on", async (tool) => {
+ await expect(
+ checkAutoApproval({
+ state: { ...baseState, alwaysAllowSubtasks: true },
+ cwd: CWD,
+ ask: "tool",
+ text: JSON.stringify({ tool }),
+ }),
+ ).resolves.toEqual({ decision: "approve" })
+ })
+
+ it.each(["newTask", "finishTask"])("asks for %s when the switch is off", async (tool) => {
+ await expect(
+ checkAutoApproval({ state: baseState, cwd: CWD, ask: "tool", text: JSON.stringify({ tool }) }),
+ ).resolves.toEqual({ decision: "ask" })
+ })
+})
+
+describe("scope of the subtask switch", () => {
+ it("does not approve an unrelated file read", async () => {
+ await expect(
+ checkAutoApproval({
+ state: { ...baseState, alwaysAllowSubtasks: true },
+ cwd: CWD,
+ ask: "tool",
+ text: JSON.stringify({ tool: "readFile", path: "src/index.ts" }),
+ }),
+ ).resolves.toEqual({ decision: "ask" })
+ })
+
+ it("asks for the fan-out when auto-approval is disabled entirely", async () => {
+ await expect(
+ checkAutoApproval({
+ state: { ...baseState, autoApprovalEnabled: false, alwaysAllowSubtasks: true },
+ cwd: CWD,
+ ask: "tool",
+ text: parallelSubtasksAsk,
+ }),
+ ).resolves.toEqual({ decision: "ask" })
+ })
+})
diff --git a/src/core/auto-approval/autoDenyReason.ts b/src/core/auto-approval/autoDenyReason.ts
index b13d438b46..6e6fb03139 100644
--- a/src/core/auto-approval/autoDenyReason.ts
+++ b/src/core/auto-approval/autoDenyReason.ts
@@ -8,10 +8,18 @@
* `Task.ask` to `presentAssistantMessage`, where it selects the structured
* `formatResponse.toolAutoDenied` payload instead of the user-rejection
* wording — and marks the denial as scoped to its own tool call, so it never
- * aborts the rest of the turn.
+ * aborts the rest of the turn. The `background_policy` kind is used when a
+ * background child's ask is resolved by policy rather than by a user click.
*/
export type AutoDenyDetail = {
- kind: "dcg" | "denylist" | "not_allowlisted" | "dangerous_substitution" | "malformed_command" | "guard_unavailable"
+ kind:
+ | "dcg"
+ | "denylist"
+ | "not_allowlisted"
+ | "dangerous_substitution"
+ | "malformed_command"
+ | "guard_unavailable"
+ | "background_policy"
/** Offending sub-command text (or the full command when no single offending sub-command applies). */
command?: string
/** Matched denied prefix, for `denylist` denials. */
@@ -48,5 +56,7 @@ export function buildAutoDenyReason(detail: AutoDenyDetail): string {
}
case "guard_unavailable":
return `Command \`${detail.command ?? "(unknown)"}\` was not executed: the Destructive Command Guard is enabled but supplied no verdict, which is an internal guard-state inconsistency, not a policy denial. You may retry the same command.`
+ case "background_policy":
+ return "This task is a read-only background sub-task and cannot ask you anything. Complete the investigation with the read-only tools you have and report your findings through attempt_completion."
}
}
diff --git a/src/core/auto-approval/index.ts b/src/core/auto-approval/index.ts
index fcfa5c40b9..baf0612d4d 100644
--- a/src/core/auto-approval/index.ts
+++ b/src/core/auto-approval/index.ts
@@ -419,7 +419,9 @@ export async function checkAutoApproval({
return state.alwaysAllowModeSwitch === true ? { decision: "approve" } : { decision: "ask" }
}
- if (["newTask", "finishTask"].includes(tool?.tool)) {
+ // `parallelSubtasks` is the parallel fan-out counterpart of `newTask`, so
+ // the same subtask switch approves it: one approval point for spawning work.
+ if (["newTask", "finishTask", "parallelSubtasks"].includes(tool?.tool)) {
return state.alwaysAllowSubtasks === true ? { decision: "approve" } : { decision: "ask" }
}
diff --git a/src/core/background-subtasks/__tests__/backgroundHistoryItem.spec.ts b/src/core/background-subtasks/__tests__/backgroundHistoryItem.spec.ts
new file mode 100644
index 0000000000..d201c85747
--- /dev/null
+++ b/src/core/background-subtasks/__tests__/backgroundHistoryItem.spec.ts
@@ -0,0 +1,45 @@
+import { historyItemSchema } from "@roo-code/types"
+
+const baseItem = {
+ id: "task-1",
+ number: 1,
+ ts: 1,
+ task: "Original prompt",
+ tokensIn: 0,
+ tokensOut: 0,
+ totalCost: 0,
+}
+
+describe("historyItemSchema backgroundParentTaskId (D10)", () => {
+ it("parses an item with the background parent stamp", () => {
+ const parsed = historyItemSchema.parse({ ...baseItem, backgroundParentTaskId: "parent-1" })
+
+ expect(parsed.backgroundParentTaskId).toBe("parent-1")
+ })
+
+ it("round-trips the stamp through serialization and re-parse", () => {
+ const parsed = historyItemSchema.parse({ ...baseItem, backgroundParentTaskId: "parent-1" })
+ const serialized = JSON.parse(JSON.stringify(parsed)) as unknown
+
+ expect(historyItemSchema.parse(serialized).backgroundParentTaskId).toBe("parent-1")
+ })
+
+ it("parses an item without the stamp and leaves it unset", () => {
+ const parsed = historyItemSchema.parse(baseItem)
+
+ expect(parsed).not.toHaveProperty("backgroundParentTaskId")
+ })
+
+ it("keeps the field optional alongside the delegation fields", () => {
+ const withStamp = historyItemSchema.parse({
+ ...baseItem,
+ status: "active",
+ childIds: ["child-1"],
+ awaitingChildId: "child-1",
+ backgroundParentTaskId: "parent-1",
+ })
+
+ expect(withStamp.awaitingChildId).toBe("child-1")
+ expect(withStamp.backgroundParentTaskId).toBe("parent-1")
+ })
+})
diff --git a/src/core/background-subtasks/__tests__/policy.spec.ts b/src/core/background-subtasks/__tests__/policy.spec.ts
new file mode 100644
index 0000000000..73c27b2abf
--- /dev/null
+++ b/src/core/background-subtasks/__tests__/policy.spec.ts
@@ -0,0 +1,211 @@
+// npx vitest run core/background-subtasks/__tests__/policy.spec.ts
+
+import { customToolRegistry } from "@roo-code/core"
+import type { ToolName } from "@roo-code/types"
+
+import { modes } from "../../../shared/modes"
+import { ALWAYS_AVAILABLE_TOOLS } from "../../../shared/tools"
+
+import { buildAutoDenyReason } from "../../auto-approval/autoDenyReason"
+import { buildToolRequirements } from "../../prompts/tools/effective-tool-policy"
+import { isToolAllowedForMode, validateToolUse } from "../../tools/validateToolUse"
+
+import { BACKGROUND_CHILD_DISABLED_TOOLS, BACKGROUND_CHILD_EXPERIMENTS, mergeBackgroundToolPolicy } from "../policy"
+
+describe("mergeBackgroundToolPolicy", () => {
+ it("returns empty results when both inputs are absent", () => {
+ expect(mergeBackgroundToolPolicy(undefined, undefined)).toEqual({ disabledTools: [], experiments: undefined })
+ })
+
+ it("returns state values only when the policy is absent", () => {
+ const state = { disabledTools: ["read_file"], experiments: { customTools: true } }
+ const merged = mergeBackgroundToolPolicy(undefined, state)
+ expect(merged.disabledTools).toEqual(["read_file"])
+ expect(merged.experiments).toEqual({ customTools: true })
+ })
+
+ it("returns policy values only when the state is absent", () => {
+ const merged = mergeBackgroundToolPolicy({ disabledTools: ["write_to_file"] }, undefined)
+ expect(merged.disabledTools).toEqual(["write_to_file"])
+ expect(merged.experiments).toBeUndefined()
+ })
+
+ it("unions disabledTools state-first with duplicates removed", () => {
+ const state = { disabledTools: ["read_file", "execute_command"] }
+ const policy = { disabledTools: ["write_to_file", "execute_command", "read_file"] }
+ const merged = mergeBackgroundToolPolicy(policy, state)
+ expect(merged.disabledTools).toEqual(["read_file", "execute_command", "write_to_file"])
+ })
+
+ it("merges experiments with the background policy winning on conflict", () => {
+ const state = { experiments: { customTools: true, imageGeneration: true } }
+ const policy = { experiments: { customTools: false } }
+ const merged = mergeBackgroundToolPolicy(policy, state)
+ expect(merged.experiments).toEqual({ customTools: false, imageGeneration: true })
+ })
+
+ it("passes through state experiments untouched when the policy has none", () => {
+ const state = { experiments: { customTools: true } }
+ const merged = mergeBackgroundToolPolicy(undefined, state)
+ expect(merged.experiments).toEqual({ customTools: true })
+ })
+
+ it("never mutates its inputs and never aliases their containers", () => {
+ const state = {
+ disabledTools: ["read_file"],
+ experiments: { customTools: true },
+ }
+ const policy = {
+ disabledTools: ["write_to_file"],
+ experiments: { customTools: false },
+ }
+ const stateDisabledTools = state.disabledTools
+ const stateExperiments = state.experiments
+ const merged = mergeBackgroundToolPolicy(policy, state)
+ // The union must be a fresh array and a fresh experiments object, so a
+ // later snapshot capture can never write through into provider state.
+ expect(merged.disabledTools).not.toBe(stateDisabledTools)
+ expect(merged.disabledTools).not.toBe(policy.disabledTools)
+ expect(merged.experiments).not.toBe(stateExperiments)
+ expect(merged.experiments).not.toBe(policy.experiments)
+ expect(state).toEqual({ disabledTools: ["read_file"], experiments: { customTools: true } })
+ expect(policy).toEqual({ disabledTools: ["write_to_file"], experiments: { customTools: false } })
+ })
+})
+
+describe("BACKGROUND_CHILD_DISABLED_TOOLS", () => {
+ it("blocks exactly the read-only child block list", () => {
+ expect([...BACKGROUND_CHILD_DISABLED_TOOLS]).toEqual([
+ "write_to_file",
+ "apply_diff",
+ "edit",
+ "search_and_replace",
+ "search_replace",
+ "edit_file",
+ "apply_patch",
+ "generate_image",
+ "execute_command",
+ "read_command_output",
+ "run_slash_command",
+ "skill",
+ "switch_mode",
+ "new_task",
+ "parallel_subtasks",
+ "ask_followup_question",
+ "use_mcp_tool",
+ "access_mcp_resource",
+ ])
+ })
+
+ it("keeps the custom-tools experiment off for a background child", () => {
+ expect(BACKGROUND_CHILD_EXPERIMENTS).toEqual({ customTools: false })
+ })
+})
+
+describe("background block list precedence over always-available tools (F2)", () => {
+ const codeMode = modes.find((m) => m.slug === "code")?.slug || "code"
+ const requirements = buildToolRequirements([...BACKGROUND_CHILD_DISABLED_TOOLS])
+
+ it.each(["new_task", "switch_mode", "ask_followup_question"])(
+ "blocks the always-available tool %s that a mode grant alone cannot",
+ (tool) => {
+ // Control: without the requirements map the always-available
+ // short-circuit grants the tool in any mode.
+ expect(ALWAYS_AVAILABLE_TOOLS).toContain(tool)
+ expect(isToolAllowedForMode(tool, codeMode, [])).toBe(true)
+ // The requirements map built from the block list is evaluated first,
+ // so the tool is rejected even though it is always available.
+ expect(isToolAllowedForMode(tool, codeMode, [], requirements)).toBe(false)
+ },
+ )
+
+ it.each(["write_to_file", "execute_command", "use_mcp_tool", "access_mcp_resource"])(
+ "blocks the mode-granted tool %s through the same requirements map",
+ (tool) => {
+ // Control: code mode grants these through its edit/command/mcp groups.
+ expect(isToolAllowedForMode(tool, codeMode, [])).toBe(true)
+ expect(isToolAllowedForMode(tool, codeMode, [], requirements)).toBe(false)
+ },
+ )
+
+ it("blocks parallel_subtasks so a child can never fan out further", () => {
+ // parallel_subtasks is a registered, always-available ToolName (Phase 3,
+ // packages/types/src/tool.ts), so the always-available short-circuit
+ // would grant it in any mode; the requirements map built from the block
+ // list is evaluated first and rejects it.
+ expect(isToolAllowedForMode("parallel_subtasks", codeMode, [], requirements)).toBe(false)
+ expect(requirements["parallel_subtasks"]).toBe(false)
+ })
+})
+
+describe("custom tools against a background child policy snapshot (F-16)", () => {
+ const codeMode = modes.find((m) => m.slug === "code")?.slug || "code"
+
+ it("rejects a registered custom tool even when ambient state enables customTools", () => {
+ customToolRegistry.register({
+ name: "shadow_child_tool",
+ description: "test double",
+ execute: async () => "ok",
+ })
+ try {
+ // Ambient provider state has the custom-tools experiment on; the
+ // child policy snapshot must still close that path. The block list
+ // carries no `custom_tool` key (custom tools validate under their own
+ // registered name, so it would never key-match); the protection is
+ // BACKGROUND_CHILD_EXPERIMENTS.customTools = false.
+ const state = { experiments: { customTools: true } }
+ const policy = {
+ disabledTools: BACKGROUND_CHILD_DISABLED_TOOLS,
+ experiments: BACKGROUND_CHILD_EXPERIMENTS,
+ }
+ const merged = mergeBackgroundToolPolicy(policy, state)
+ expect(merged.experiments).toEqual({ customTools: false })
+ expect(merged.disabledTools).not.toContain("custom_tool")
+
+ // The custom tool's registered name is not a static ToolName, so the
+ // cast stands in for the parser's dynamic name.
+ const requirements = buildToolRequirements(merged.disabledTools)
+ expect(() =>
+ validateToolUse(
+ "shadow_child_tool" as ToolName,
+ codeMode,
+ [],
+ requirements,
+ undefined,
+ merged.experiments,
+ ),
+ ).toThrow(/Unknown tool/)
+ } finally {
+ customToolRegistry.clear()
+ }
+ })
+
+ it("control: the same registered custom tool is callable without the child policy", () => {
+ customToolRegistry.register({
+ name: "shadow_child_tool",
+ description: "test double",
+ execute: async () => "ok",
+ })
+ try {
+ expect(() =>
+ validateToolUse("shadow_child_tool" as ToolName, codeMode, [], undefined, undefined, {
+ customTools: true,
+ }),
+ ).not.toThrow()
+ } finally {
+ customToolRegistry.clear()
+ }
+ })
+})
+
+describe("buildAutoDenyReason background_policy", () => {
+ it("returns a non-empty denial that never suggests asking the user", () => {
+ const reason = buildAutoDenyReason({ kind: "background_policy" })
+ expect(reason.length).toBeGreaterThan(0)
+ // The denial must steer the model to read-only tools and
+ // attempt_completion, not back to a user prompt.
+ expect(reason).not.toContain("ask the user")
+ expect(reason).toContain("attempt_completion")
+ expect(reason).toContain("read-only")
+ })
+})
diff --git a/src/core/background-subtasks/policy.ts b/src/core/background-subtasks/policy.ts
new file mode 100644
index 0000000000..e5267d0f95
--- /dev/null
+++ b/src/core/background-subtasks/policy.ts
@@ -0,0 +1,101 @@
+/**
+ * Task-local tool policy for background (read-only) child tasks, design
+ * decision D3 of the sub-subtasks feature.
+ *
+ * Invariant: a background child's effective tool policy must never depend on,
+ * or mutate, shared/global state. The child's block list and experiment
+ * overrides are injected per task through `TaskOptions.backgroundToolPolicy`
+ * and folded into the per-request policy snapshot at capture time, so the
+ * prompt layer and the execution-time validator always block exactly the same
+ * tool set while every other task keeps reading the ambient provider state.
+ */
+import type { ToolName } from "@roo-code/types"
+
+/**
+ * Tool names a background child can never call. `parallel_subtasks` is a
+ * registered `ToolName` (Phase 3), so the alias is plain `ToolName`.
+ */
+export type BackgroundBlockedToolName = ToolName
+
+/**
+ * The read-only child block list.
+ *
+ * Depth-1 fan-out is enforced structurally by `parallel_subtasks` being in
+ * this list: even after Phase 3 registers the tool, a child can never spawn
+ * its own children.
+ *
+ * MCP is blocked by naming both `use_mcp_tool` and `access_mcp_resource`.
+ * Both the wrapper tool and the dynamic `mcp_*` native calls validate under
+ * the canonical `use_mcp_tool` name (see presentAssistantMessage), so one
+ * entry covers both paths.
+ *
+ * Custom tools are deliberately NOT listed here: a custom tool validates under
+ * its own registered name, so a `custom_tool` entry would never key-match.
+ * The real protection is `BACKGROUND_CHILD_EXPERIMENTS.customTools = false`,
+ * which closes the custom-tool path at both the prompt layer and
+ * `validateToolUse` (see the pinning test in policy.spec.ts).
+ */
+export const BACKGROUND_CHILD_DISABLED_TOOLS: readonly BackgroundBlockedToolName[] = [
+ "write_to_file",
+ "apply_diff",
+ "edit",
+ "search_and_replace",
+ "search_replace",
+ "edit_file",
+ "apply_patch",
+ "generate_image",
+ "execute_command",
+ "read_command_output",
+ "run_slash_command",
+ "skill",
+ "switch_mode",
+ "new_task",
+ "parallel_subtasks",
+ "ask_followup_question",
+ "use_mcp_tool",
+ "access_mcp_resource",
+]
+
+/**
+ * Experiment overrides injected into a background child's policy snapshot.
+ * `customTools: false` closes the experiment-gated custom-tool path at both
+ * the prompt layer and `validateToolUse`, which read the same snapshot.
+ */
+export const BACKGROUND_CHILD_EXPERIMENTS: Record = { customTools: false }
+
+/**
+ * Union a background child's task-local policy with the ambient provider
+ * state, without mutating either input.
+ *
+ * The union direction is deliberate: a background child must be at least as
+ * restricted as the user's global policy, never less. `disabledTools` entries
+ * come state-first, then policy entries, de-duplicated by first occurrence;
+ * `experiments` merge with the policy entries winning on conflict.
+ *
+ * @returns `disabledTools: []` and `experiments: undefined` when both inputs
+ * are absent or empty.
+ */
+export function mergeBackgroundToolPolicy(
+ policy: { disabledTools?: readonly string[]; experiments?: Record } | undefined,
+ state: { disabledTools?: string[]; experiments?: Record } | undefined,
+): { disabledTools: string[]; experiments: Record | undefined } {
+ const disabledTools: string[] = []
+ const seen = new Set()
+ for (const entry of state?.disabledTools ?? []) {
+ if (!seen.has(entry)) {
+ seen.add(entry)
+ disabledTools.push(entry)
+ }
+ }
+ for (const entry of policy?.disabledTools ?? []) {
+ if (!seen.has(entry)) {
+ seen.add(entry)
+ disabledTools.push(entry)
+ }
+ }
+ const experiments =
+ state?.experiments === undefined && policy?.experiments === undefined
+ ? undefined
+ : { ...state?.experiments, ...policy?.experiments }
+ return { disabledTools, experiments }
+}
diff --git a/src/core/background-subtasks/types.ts b/src/core/background-subtasks/types.ts
new file mode 100644
index 0000000000..43ae9eef88
--- /dev/null
+++ b/src/core/background-subtasks/types.ts
@@ -0,0 +1,67 @@
+/**
+ * Shared contract for the sub-subtasks feature (design §6): parallel,
+ * read-only background child tasks spawned through the `parallel_subtasks`
+ * tool.
+ *
+ * Background children run outside the lifecycle reducer: the singular
+ * `awaitingChildId` invariant is preserved, so a parent can await one
+ * delegated child while any number of background children run beside it.
+ * Only two things cross into persistence: `childIds` registration on the
+ * parent (via `addBackgroundChild`, design D10) and the
+ * `backgroundParentTaskId` stamp on the child's HistoryItem (design D10/D11).
+ *
+ * Phase 2 Units B and C code against this module; keep the shapes stable.
+ */
+
+/** One requested read-only investigation, as passed to the parallel_subtasks tool. */
+export interface BackgroundSubtaskSpec {
+ /** Short sibling-unique label used for the report filename and the UI row. */
+ label: string
+ /** Mode slug the child runs in (must exist in the user's custom modes). */
+ mode: string
+ /** The investigation prompt. */
+ message: string
+}
+
+/** Live state of one spawned background child. */
+export type BackgroundChildStatus = "queued" | "running" | "completed" | "failed" | "aborted"
+
+export interface BackgroundChildEntry {
+ taskId: string
+ label: string
+ mode: string
+ status: BackgroundChildStatus
+ /** Markdown the child reported through attempt_completion, once completed. */
+ result?: string
+ /** Why the child failed or was aborted, for the parent's summary. */
+ error?: string
+ startedAt: number
+ finishedAt?: number
+}
+
+/** A handle the spawning tool holds so it can await or abort the fan-out. */
+export interface BackgroundChildHandle {
+ taskId: string
+ label: string
+ mode: string
+ /** Resolves when the child reaches a terminal state; never rejects. */
+ done: Promise
+}
+
+export interface SpawnBackgroundChildrenResult {
+ children: BackgroundChildHandle[]
+ /** True when at least one child was queued (i.e. the fan-out is live). */
+ started: boolean
+}
+
+/**
+ * The subset of `ClineProvider` a background child needs at completion time.
+ * Declared here so `AttemptCompletionTool` can resolve a child without
+ * importing the provider (which would create a cycle).
+ */
+export interface BackgroundSubtaskHost {
+ /** Resolve a completed background child and settle its parent's promise. */
+ resolveBackgroundChild(childTaskId: string, result: string): void
+ /** Record a failed/aborted background child and settle its parent's promise. */
+ failBackgroundChild(childTaskId: string, error: string): void
+}
diff --git a/src/core/prompts/tools/__tests__/parallel-subtasks-experiment-gate.spec.ts b/src/core/prompts/tools/__tests__/parallel-subtasks-experiment-gate.spec.ts
new file mode 100644
index 0000000000..2a5c3db685
--- /dev/null
+++ b/src/core/prompts/tools/__tests__/parallel-subtasks-experiment-gate.spec.ts
@@ -0,0 +1,88 @@
+// npx vitest run src/core/prompts/tools/__tests__/parallel-subtasks-experiment-gate.spec.ts
+
+import type OpenAI from "openai"
+import { DEFAULT_MODES, type ModeConfig } from "@roo-code/types"
+
+import { getToolsForMode } from "../../../../shared/modes"
+
+import { getNativeTools } from "../native-tools"
+import { filterNativeToolsForMode } from "../filter-tools-for-mode"
+import { resolveEffectiveToolPolicy } from "../effective-tool-policy"
+
+const ON = { parallelSubtasks: true }
+
+function advertisedNames(tools: OpenAI.Chat.ChatCompletionTool[]): string[] {
+ return tools.map((tool) => ("function" in tool && tool.function ? tool.function.name : ""))
+}
+
+function filter(experiments?: Record, disabledTools?: string[]) {
+ return filterNativeToolsForMode(getNativeTools(), "code", undefined, experiments, undefined, { disabledTools })
+}
+
+describe("parallel_subtasks prompt-layer gate", () => {
+ describe("filterNativeToolsForMode", () => {
+ it.each<[string, Record | undefined]>([
+ ["omitted", undefined],
+ ["empty", {}],
+ ["explicitly off", { parallelSubtasks: false }],
+ ])("drops the definition when experiments are %s", (_label, experiments) => {
+ const names = advertisedNames(filter(experiments))
+ expect(names).not.toContain("parallel_subtasks")
+ // Control: the filter is still admitting other always-available tools.
+ expect(names).toContain("new_task")
+ })
+
+ it("advertises the definition when the flag is on", () => {
+ expect(advertisedNames(filter(ON))).toContain("parallel_subtasks")
+ })
+
+ it("still drops the definition when disabledTools names it despite the flag", () => {
+ expect(advertisedNames(filter(ON, ["parallel_subtasks"]))).not.toContain("parallel_subtasks")
+ })
+ })
+
+ describe("resolveEffectiveToolPolicy", () => {
+ it("excludes the tool from the effective set while the flag is off", () => {
+ expect(resolveEffectiveToolPolicy({ mode: "code" }).tools.has("parallel_subtasks")).toBe(false)
+ expect(resolveEffectiveToolPolicy({ mode: "code", experiments: {} }).tools.has("parallel_subtasks")).toBe(
+ false,
+ )
+ })
+
+ it("includes the tool for built-in modes when the flag is on", () => {
+ for (const mode of ["code", "debug", "architect", "ask"]) {
+ expect(resolveEffectiveToolPolicy({ mode, experiments: ON }).tools.has("parallel_subtasks")).toBe(true)
+ }
+ })
+
+ it("includes the tool for a custom mode with no groups when the flag is on", () => {
+ const customMode: ModeConfig = {
+ slug: "empty-groups",
+ name: "Empty",
+ roleDefinition: "",
+ groups: [],
+ }
+ const policy = resolveEffectiveToolPolicy({
+ mode: "empty-groups",
+ customModes: [customMode],
+ experiments: ON,
+ })
+ expect(policy.tools.has("parallel_subtasks")).toBe(true)
+ })
+ })
+
+ describe("getToolsForMode raw roster", () => {
+ it("lists the tool unconditionally; the resolver is what applies the flag", () => {
+ // The roster helper takes no experiments argument, so its one production
+ // consumer (resolveEffectiveToolPolicy) has to be the gate. Pinning both
+ // halves keeps a future caller from mistaking the raw list for the
+ // advertised set.
+ const codeMode = DEFAULT_MODES.find((mode) => mode.slug === "code")
+ if (!codeMode) {
+ throw new Error("code mode missing from DEFAULT_MODES")
+ }
+ expect(getToolsForMode(codeMode.groups)).toContain("parallel_subtasks")
+ expect(resolveEffectiveToolPolicy({ mode: "code" }).tools.has("parallel_subtasks")).toBe(false)
+ })
+ })
+})
diff --git a/src/core/prompts/tools/__tests__/parallel-subtasks-registration.spec.ts b/src/core/prompts/tools/__tests__/parallel-subtasks-registration.spec.ts
new file mode 100644
index 0000000000..c09984139a
--- /dev/null
+++ b/src/core/prompts/tools/__tests__/parallel-subtasks-registration.spec.ts
@@ -0,0 +1,120 @@
+// npx vitest src/core/prompts/tools/__tests__/parallel-subtasks-registration.spec.ts
+
+import type OpenAI from "openai"
+import { describe, it, expect } from "vitest"
+
+import type { AssertEqual, Equals } from "@roo-code/types"
+import { toolNames, toolNamesSchema } from "@roo-code/types"
+
+import { ALWAYS_AVAILABLE_TOOLS, toolParamNames, type NativeToolArgs } from "../../../../shared/tools"
+import { isToolAllowedForMode } from "../../../tools/validateToolUse"
+import { BACKGROUND_CHILD_DISABLED_TOOLS } from "../../../background-subtasks/policy"
+import { buildToolRequirements } from "../effective-tool-policy"
+import { getNativeTools } from "../native-tools"
+import parallelSubtasks from "../native-tools/parallel_subtasks"
+
+// Compile-time only: `check-types` fails if the native args shape drifts from
+// the contract the tool schema and the parser both implement.
+type _AssertParallelSubtasksArgs = AssertEqual<
+ Equals }>
+>
+
+type FunctionTool = OpenAI.Chat.ChatCompletionFunctionTool
+
+describe("parallel_subtasks registration surface", () => {
+ describe("tool name enum", () => {
+ it("registers the tool name and admits it through the schema", () => {
+ expect(toolNames).toContain("parallel_subtasks")
+ expect(toolNamesSchema.parse("parallel_subtasks")).toBe("parallel_subtasks")
+ })
+
+ it("advertises the tool in every mode", () => {
+ expect(ALWAYS_AVAILABLE_TOOLS).toContain("parallel_subtasks")
+ })
+
+ it("registers the parameters the parser reads", () => {
+ expect(toolParamNames).toContain("tasks")
+ expect(toolParamNames).toContain("label")
+ })
+ })
+
+ describe("native tool schema", () => {
+ const fn = parallelSubtasks.function
+ const tasksSchema = fn.parameters.properties.tasks
+
+ it("declares the tool as a strict function", () => {
+ expect(parallelSubtasks.type).toBe("function")
+ expect(fn.name).toBe("parallel_subtasks")
+ expect(fn.strict).toBe(true)
+ })
+
+ it("closes both object levels and requires the task list", () => {
+ expect(fn.parameters.additionalProperties).toBe(false)
+ expect(fn.parameters.required).toEqual(["tasks"])
+ expect(tasksSchema.type).toBe("array")
+ expect(tasksSchema.items.additionalProperties).toBe(false)
+ // Strict schemas must require every declared property; an unused
+ // label arrives as null rather than being omitted.
+ expect(tasksSchema.items.required).toEqual(["label", "mode", "message"])
+ })
+
+ it("types label as nullable and mode/message as strings", () => {
+ expect(tasksSchema.items.properties.label.type).toEqual(["string", "null"])
+ expect(tasksSchema.items.properties.mode.type).toBe("string")
+ expect(tasksSchema.items.properties.message.type).toBe("string")
+ })
+
+ it("states the read-only parallel report contract", () => {
+ const description = fn.description
+ expect(description).toMatch(/read-only/i)
+ expect(description).toMatch(/parallel/i)
+ expect(description).toMatch(/attempt_completion/)
+ expect(description).toMatch(/\.md/)
+ expect(description).toMatch(/label must be unique/i)
+ expect(description).toMatch(/at most 6/i)
+ })
+
+ it("describes tasks[].label as optional with a default instead of required", () => {
+ const description = fn.description
+ expect(description).not.toMatch(/tasks\[\]\.label: \(required\)/)
+ expect(description).toMatch(/tasks\[\]\.label: \(optional\)/)
+ expect(description).toMatch(/defaults to child-N/i)
+ const labelDescription = tasksSchema.items.properties.label.description
+ expect(labelDescription).toMatch(/optional/i)
+ expect(labelDescription).toMatch(/defaults to child-N/i)
+ })
+ })
+
+ describe("getNativeTools", () => {
+ it("includes the tool definition", () => {
+ const names = getNativeTools()
+ .filter((tool): tool is FunctionTool => tool.type === "function")
+ .map((tool) => tool.function.name)
+ expect(names).toContain("parallel_subtasks")
+ })
+ })
+
+ describe("background child depth limit", () => {
+ const childRequirements = buildToolRequirements([...BACKGROUND_CHILD_DISABLED_TOOLS])
+
+ it("allows the tool for an ordinary code task once the experiment flag is on", () => {
+ expect(isToolAllowedForMode("parallel_subtasks", "code", [], {}, {}, { parallelSubtasks: true })).toBe(true)
+ })
+
+ it("keeps the tool unavailable for an ordinary task while the flag is off", () => {
+ expect(isToolAllowedForMode("parallel_subtasks", "code", [], {}, {}, {})).toBe(false)
+ expect(isToolAllowedForMode("parallel_subtasks", "code", [], {}, {}, { parallelSubtasks: false })).toBe(
+ false,
+ )
+ })
+
+ it("blocks the tool for a background child despite the always-available class", () => {
+ expect(childRequirements.parallel_subtasks).toBe(false)
+ expect(isToolAllowedForMode("parallel_subtasks", "code", [], childRequirements, {}, {})).toBe(false)
+ })
+
+ it("keeps read-only tools outside the child block list allowed", () => {
+ expect(isToolAllowedForMode("read_file", "code", [], childRequirements, {}, {})).toBe(true)
+ })
+ })
+})
diff --git a/src/core/prompts/tools/native-tools/index.ts b/src/core/prompts/tools/native-tools/index.ts
index d5f75b590c..fc0bc3cc60 100644
--- a/src/core/prompts/tools/native-tools/index.ts
+++ b/src/core/prompts/tools/native-tools/index.ts
@@ -10,6 +10,7 @@ import executeCommand from "./execute_command"
import generateImage from "./generate_image"
import listFiles from "./list_files"
import newTask from "./new_task"
+import parallelSubtasks from "./parallel_subtasks"
import readCommandOutput from "./read_command_output"
import { createReadFileTool, type ReadFileToolOptions } from "./read_file"
import runSlashCommand from "./run_slash_command"
@@ -57,6 +58,7 @@ export function getNativeTools(options: NativeToolsOptions = {}): OpenAI.Chat.Ch
generateImage,
listFiles,
newTask,
+ parallelSubtasks,
readCommandOutput,
createReadFileTool(readFileOptions),
runSlashCommand,
diff --git a/src/core/prompts/tools/native-tools/parallel_subtasks.ts b/src/core/prompts/tools/native-tools/parallel_subtasks.ts
new file mode 100644
index 0000000000..f6a30eaf23
--- /dev/null
+++ b/src/core/prompts/tools/native-tools/parallel_subtasks.ts
@@ -0,0 +1,69 @@
+import type OpenAI from "openai"
+
+const PARALLEL_SUBTASKS_DESCRIPTION = `Spawn up to 6 read-only investigation tasks that run in parallel in the background and report their findings back to you.
+
+Contract:
+- Each child can ONLY read and report. It cannot write files, run commands, switch modes, spawn its own subtasks, or ask you anything.
+- Each child reports its findings through attempt_completion. The host saves each report to a .md file and returns a summary plus the report paths to you, so you can act on the findings in a later step.
+- label must be unique among the tasks of one call. It names the child's report file and its UI row, so keep it short and descriptive (for example "api-surface").
+- mode is the mode slug the child runs in (e.g., code, debug, architect). Different modes may use different models, so pick the mode that fits each investigation.
+
+Use this tool when several independent investigations can run at once. Do NOT use it for work that must be sequential, and do NOT use it for anything that changes files because children have no write access.
+
+Parameters:
+- tasks: (required) The investigations to run in parallel. At most 6 children per call; excess requests are dropped. A call that lists more than 50 tasks is rejected instead of run.
+- tasks[].label: (optional) Sibling-unique short label used for the report filename and the UI row. When omitted or blank it defaults to child-N (the task's 1-based position); duplicate labels gain a numeric suffix to stay sibling-unique.
+- tasks[].mode: (required) Mode slug the child runs in.
+- tasks[].message: (required) The investigation prompt for the child.
+
+Example: Two independent investigations
+{ "tasks": [{ "label": "api-surface", "mode": "code", "message": "Map the public API of src/core/task." }, { "label": "test-gaps", "mode": "debug", "message": "Find untested branches in the task scheduler." }] }`
+
+const TASKS_PARAMETER_DESCRIPTION = `Read-only investigations to run in parallel; at most 6 per call, excess requests are dropped (a call listing more than 50 tasks is rejected)`
+
+const LABEL_PARAMETER_DESCRIPTION = `Sibling-unique short label used for the report filename and the UI row; optional, defaults to child-N (1-based position) when omitted or blank, duplicates get a numeric suffix`
+
+const MODE_PARAMETER_DESCRIPTION = `Mode slug the child runs in (e.g., code, debug, architect)`
+
+const MESSAGE_PARAMETER_DESCRIPTION = `Investigation prompt for the child; the child reports findings back through attempt_completion`
+
+export default {
+ type: "function",
+ function: {
+ name: "parallel_subtasks",
+ description: PARALLEL_SUBTASKS_DESCRIPTION,
+ strict: true,
+ parameters: {
+ type: "object",
+ properties: {
+ tasks: {
+ type: "array",
+ description: TASKS_PARAMETER_DESCRIPTION,
+ items: {
+ type: "object",
+ properties: {
+ label: {
+ type: ["string", "null"],
+ description: LABEL_PARAMETER_DESCRIPTION,
+ },
+ mode: {
+ type: "string",
+ description: MODE_PARAMETER_DESCRIPTION,
+ },
+ message: {
+ type: "string",
+ description: MESSAGE_PARAMETER_DESCRIPTION,
+ },
+ },
+ // Strict schemas must list every declared property as
+ // required; an unused label arrives as null.
+ required: ["label", "mode", "message"],
+ additionalProperties: false,
+ },
+ },
+ },
+ required: ["tasks"],
+ additionalProperties: false,
+ },
+ },
+} satisfies OpenAI.Chat.ChatCompletionTool
diff --git a/src/core/subtask-reports/__tests__/writeReport.spec.ts b/src/core/subtask-reports/__tests__/writeReport.spec.ts
new file mode 100644
index 0000000000..2ef507bdae
--- /dev/null
+++ b/src/core/subtask-reports/__tests__/writeReport.spec.ts
@@ -0,0 +1,452 @@
+// pnpm --dir src exec vitest run core/subtask-reports/__tests__/writeReport.spec.ts
+
+import * as fs from "fs/promises"
+import * as os from "os"
+import * as path from "path"
+
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+
+import { getSubtaskReportsDir, resolveReportPath, sanitizeReportLabel, writeSubtaskReport } from ".."
+
+// Rename is forced to fail in the atomicity test, open is wrapped to plant a
+// decoy in the exclusive-create test, and writeFile is wrapped to fail after
+// the exclusive create in the write-failure test; everything else stays real
+// so the suite exercises the true filesystem path.
+vi.mock("fs/promises", async (importOriginal) => {
+ const actual = await importOriginal()
+ return {
+ ...actual,
+ open: vi.fn(actual.open),
+ rename: vi.fn(actual.rename),
+ writeFile: vi.fn(actual.writeFile),
+ }
+})
+
+import { open, rename, writeFile } from "fs/promises"
+
+const openMock = vi.mocked(open)
+const renameMock = vi.mocked(rename)
+const writeFileMock = vi.mocked(writeFile)
+
+describe("subtask-reports", () => {
+ let cwd: string
+
+ beforeEach(async () => {
+ cwd = await fs.mkdtemp(path.join(os.tmpdir(), "subtask-reports-"))
+ openMock.mockClear()
+ renameMock.mockClear()
+ writeFileMock.mockClear()
+ })
+
+ afterEach(async () => {
+ await fs.rm(cwd, { recursive: true, force: true })
+ })
+
+ describe("sanitizeReportLabel", () => {
+ it("replaces path separators and Windows-illegal characters with dashes", () => {
+ expect(sanitizeReportLabel('a/b\\c:d*e?f"gi|j')).toBe("a-b-c-d-e-f-g-h-i-j")
+ })
+
+ it("strips control characters", () => {
+ const label = "re" + String.fromCharCode(1) + "port"
+ expect(sanitizeReportLabel(label)).toBe("re-port")
+ })
+
+ it("falls back to 'subtask' when nothing safe remains", () => {
+ expect(sanitizeReportLabel("..")).toBe("subtask")
+ expect(sanitizeReportLabel(" ")).toBe("subtask")
+ })
+
+ it("prefixes Windows-reserved device names, with or without an extension", () => {
+ expect(sanitizeReportLabel("CON")).toBe("_CON")
+ expect(sanitizeReportLabel("con.txt")).toBe("_con.txt")
+ expect(sanitizeReportLabel("lpt3")).toBe("_lpt3")
+ expect(sanitizeReportLabel("console")).toBe("console")
+ })
+
+ it("truncates long labels to 60 characters", () => {
+ const long = "a".repeat(100)
+ expect(sanitizeReportLabel(long)).toBe("a".repeat(60))
+ })
+ })
+
+ describe("writeSubtaskReport naming", () => {
+ it("writes to /.zoocode/subtask-reports//-.md", async () => {
+ const report = await writeSubtaskReport({
+ cwd,
+ parentTaskId: "parent-1",
+ childTaskId: "child-1",
+ label: "api-surface",
+ markdown: "# Findings",
+ })
+
+ const expectedDir = getSubtaskReportsDir(cwd, "parent-1")
+ expect(expectedDir).toBe(path.join(cwd, ".zoocode", "subtask-reports", "parent-1"))
+ expect(report.path).toBe(path.join(expectedDir, "api-surface-child-1.md"))
+ expect(path.basename(report.path)).toBe("api-surface-child-1.md")
+ expect(await fs.readFile(report.path, "utf8")).toBe("# Findings")
+ })
+
+ it("gives two siblings with identical labels different paths", async () => {
+ const first = await writeSubtaskReport({
+ cwd,
+ parentTaskId: "parent-1",
+ childTaskId: "child-a",
+ label: "dupe",
+ markdown: "first",
+ })
+ const second = await writeSubtaskReport({
+ cwd,
+ parentTaskId: "parent-1",
+ childTaskId: "child-b",
+ label: "dupe",
+ markdown: "second",
+ })
+
+ expect(first.path).not.toBe(second.path)
+ expect(await fs.readFile(first.path, "utf8")).toBe("first")
+ expect(await fs.readFile(second.path, "utf8")).toBe("second")
+ })
+
+ it("keeps a sanitized traversal label inside the reports directory", async () => {
+ const report = await writeSubtaskReport({
+ cwd,
+ parentTaskId: "parent-1",
+ childTaskId: "child-1",
+ label: "../../escape",
+ markdown: "content",
+ })
+
+ const root = path.resolve(getSubtaskReportsDir(cwd, "parent-1"))
+ expect(path.resolve(report.path).startsWith(root + path.sep)).toBe(true)
+ expect(path.basename(report.path)).toBe("..-..-escape-child-1.md")
+ // Nothing was written outside the reports directory.
+ const outside = path.resolve(cwd, ".zoocode", "escape-child-1.md")
+ await expect(fs.access(outside)).rejects.toThrow()
+ })
+
+ it("rejects a path that resolves outside the reports directory", async () => {
+ const reportsDir = getSubtaskReportsDir(cwd, "parent-1")
+ // The child task id is host-generated in production; a separator-laden
+ // value proves the containment guard fires regardless of the input.
+ await expect(resolveReportPath(reportsDir, "safe", "../../../escape")).rejects.toThrow(
+ /escapes the reports directory/,
+ )
+ })
+
+ it("truncates a long label in the filename", async () => {
+ const report = await writeSubtaskReport({
+ cwd,
+ parentTaskId: "parent-1",
+ childTaskId: "child-1",
+ label: "x".repeat(100),
+ markdown: "content",
+ })
+ expect(path.basename(report.path)).toBe(`${"x".repeat(60)}-child-1.md`)
+ })
+
+ it("writes a long Unicode label whose full destination basename approaches the 255-byte limit", async () => {
+ // 60 label characters at 3 UTF-8 bytes each plus a 36-character child
+ // id puts the destination basename near ext4's 255-byte component cap.
+ // The old temp name embedded the destination basename and overflowed
+ // that cap; the short temp name must keep the write working.
+ const label = "界".repeat(60)
+ const childTaskId = "0b8c1f6e-3c2a-4e6b-9d8b-1f2e3d4c5b6a"
+ const markdown = "# 유니코드 보고서\n\n본문 내용이 그대로 저장된다."
+ const report = await writeSubtaskReport({
+ cwd,
+ parentTaskId: "parent-1",
+ childTaskId,
+ label,
+ markdown,
+ })
+
+ expect(path.basename(report.path)).toBe(`${label}-${childTaskId}.md`)
+ expect(Buffer.byteLength(path.basename(report.path), "utf8")).toBeLessThanOrEqual(255)
+ const tempPath = renameMock.mock.calls[0][0] as string
+ expect(path.dirname(tempPath)).toBe(path.dirname(report.path))
+ expect(Buffer.byteLength(path.basename(tempPath), "utf8")).toBeLessThanOrEqual(255)
+ expect(await fs.readFile(report.path, "utf8")).toBe(markdown)
+ const dirEntries = await fs.readdir(path.dirname(report.path))
+ expect(dirEntries).toEqual([path.basename(report.path)])
+ })
+
+ it("handles a Windows-reserved label", async () => {
+ const report = await writeSubtaskReport({
+ cwd,
+ parentTaskId: "parent-1",
+ childTaskId: "child-1",
+ label: "CON",
+ markdown: "content",
+ })
+ expect(path.basename(report.path)).toBe("_CON-child-1.md")
+ })
+ })
+
+ describe("writeSubtaskReport atomicity", () => {
+ it("commits by rename: the temp file is gone and only the target exists", async () => {
+ const report = await writeSubtaskReport({
+ cwd,
+ parentTaskId: "parent-1",
+ childTaskId: "child-1",
+ label: "api",
+ markdown: "# Report",
+ })
+
+ expect(renameMock).toHaveBeenCalledOnce()
+ const [tempPath, targetPath] = renameMock.mock.calls[0]
+ expect(targetPath).toBe(report.path)
+ await expect(fs.access(tempPath as string)).rejects.toThrow()
+ await expect(fs.access(report.path)).resolves.toBeUndefined()
+
+ const dirEntries = await fs.readdir(path.dirname(report.path))
+ expect(dirEntries).toEqual(["api-child-1.md"])
+ })
+
+ it("throws on a failed rename and leaves no partial target or temp file", async () => {
+ renameMock.mockRejectedValueOnce(new Error("rename boom"))
+
+ await expect(
+ writeSubtaskReport({
+ cwd,
+ parentTaskId: "parent-1",
+ childTaskId: "child-1",
+ label: "api",
+ markdown: "# Report",
+ }),
+ ).rejects.toThrow("rename boom")
+
+ const reportsDir = getSubtaskReportsDir(cwd, "parent-1")
+ await expect(fs.access(path.join(reportsDir, "api-child-1.md"))).rejects.toThrow()
+ const dirEntries = await fs.readdir(reportsDir)
+ expect(dirEntries.filter((entry) => entry.startsWith(".tmp-"))).toEqual([])
+ })
+
+ it("lands concurrent writes to different paths", async () => {
+ const [first, second] = await Promise.all([
+ writeSubtaskReport({
+ cwd,
+ parentTaskId: "parent-1",
+ childTaskId: "child-a",
+ label: "same-label",
+ markdown: "a",
+ }),
+ writeSubtaskReport({
+ cwd,
+ parentTaskId: "parent-1",
+ childTaskId: "child-b",
+ label: "same-label",
+ markdown: "b",
+ }),
+ ])
+
+ expect(first.path).not.toBe(second.path)
+ expect(await fs.readFile(first.path, "utf8")).toBe("a")
+ expect(await fs.readFile(second.path, "utf8")).toBe("b")
+ })
+
+ it("creates the temp file exclusively: a pre-planted temp path fails the write and the decoy survives", async () => {
+ const realFs = await vi.importActual("fs/promises")
+ let decoyPath = ""
+ openMock.mockImplementationOnce(async (file, flags) => {
+ // Plant a decoy at the exact temp path before the writer's own
+ // exclusive create, standing in for a symlink or concurrent writer
+ // planted between path generation and the create.
+ decoyPath = file as string
+ await realFs.writeFile(decoyPath, "planted-decoy", "utf8")
+ return realFs.open(decoyPath, flags as string)
+ })
+
+ await expect(
+ writeSubtaskReport({
+ cwd,
+ parentTaskId: "parent-1",
+ childTaskId: "child-1",
+ label: "api",
+ markdown: "# Report",
+ }),
+ ).rejects.toThrow(/EEXIST/)
+
+ // The writer must pass the O_EXCL-style flag to the create, not a
+ // plain overwrite.
+ expect(openMock.mock.calls[0][1]).toBe("wx")
+
+ // The decoy was planted by someone else: the failed exclusive create
+ // must not delete it, and the rename must never run against it. Only
+ // the acquired-temp cleanup path may remove files.
+ expect(decoyPath).not.toBe("")
+ expect(path.basename(decoyPath)).toMatch(/^\.tmp-/)
+ expect(await fs.readFile(decoyPath, "utf8")).toBe("planted-decoy")
+ expect(renameMock).not.toHaveBeenCalled()
+
+ // The real target never received a report.
+ const reportsDir = getSubtaskReportsDir(cwd, "parent-1")
+ await expect(fs.access(path.join(reportsDir, "api-child-1.md"))).rejects.toThrow()
+ })
+
+ it("removes the owned temp file when the write fails after the exclusive create", async () => {
+ const realFs = await vi.importActual("fs/promises")
+ writeFileMock.mockImplementationOnce(async (file, data, options) => {
+ // The exclusive create already succeeded and the writer owns the
+ // temp file; the data write itself then fails, as a full disk
+ // fails only after Node opens the file. The fragment really
+ // exists on disk, so the cleanup assertion below cannot pass
+ // vacuously.
+ await realFs.writeFile(file, data, options)
+ throw new Error("disk full")
+ })
+
+ await expect(
+ writeSubtaskReport({
+ cwd,
+ parentTaskId: "parent-1",
+ childTaskId: "child-1",
+ label: "api",
+ markdown: "# Report",
+ }),
+ ).rejects.toThrow("disk full")
+
+ // The writer owned the temp file even though the write failed, so
+ // the failure cleanup must remove it: no .tmp- fragment remains and
+ // the target was never published.
+ const reportsDir = getSubtaskReportsDir(cwd, "parent-1")
+ await expect(fs.access(path.join(reportsDir, "api-child-1.md"))).rejects.toThrow()
+ const dirEntries = await fs.readdir(reportsDir)
+ expect(dirEntries.filter((entry) => entry.startsWith(".tmp-"))).toEqual([])
+ })
+
+ it("does not publish the report when closing the temp file fails after a successful write", async () => {
+ const realFs = await vi.importActual("fs/promises")
+ openMock.mockImplementationOnce(async (file, flags) => {
+ // Some filesystems (NFS) report a quota or space failure at
+ // close() time, after the write itself resolved. The close
+ // rejection must fail the write, not be swallowed into a rename.
+ const handle = await realFs.open(file as string, flags as string)
+ const realClose = handle.close.bind(handle)
+ handle.close = async () => {
+ await realClose()
+ throw new Error("close boom")
+ }
+ return handle
+ })
+
+ await expect(
+ writeSubtaskReport({
+ cwd,
+ parentTaskId: "parent-1",
+ childTaskId: "child-1",
+ label: "api",
+ markdown: "# Report",
+ }),
+ ).rejects.toThrow("close boom")
+
+ // The close failure reached the owned-temp cleanup: the rename
+ // never ran, the target was never published, and no .tmp- fragment
+ // remains.
+ expect(renameMock).not.toHaveBeenCalled()
+ const reportsDir = getSubtaskReportsDir(cwd, "parent-1")
+ await expect(fs.access(path.join(reportsDir, "api-child-1.md"))).rejects.toThrow()
+ const dirEntries = await fs.readdir(reportsDir)
+ expect(dirEntries.filter((entry) => entry.startsWith(".tmp-"))).toEqual([])
+ })
+
+ it("preserves the original write error when the close also fails", async () => {
+ const realFs = await vi.importActual("fs/promises")
+ openMock.mockImplementationOnce(async (file, flags) => {
+ const handle = await realFs.open(file as string, flags as string)
+ const realClose = handle.close.bind(handle)
+ handle.close = async () => {
+ await realClose()
+ throw new Error("close boom")
+ }
+ return handle
+ })
+ writeFileMock.mockImplementationOnce(async (file, data, options) => {
+ await realFs.writeFile(file, data, options)
+ throw new Error("disk full")
+ })
+
+ await expect(
+ writeSubtaskReport({
+ cwd,
+ parentTaskId: "parent-1",
+ childTaskId: "child-1",
+ label: "api",
+ markdown: "# Report",
+ }),
+ ).rejects.toThrow("disk full")
+
+ expect(renameMock).not.toHaveBeenCalled()
+ })
+ })
+
+ describe("writeSubtaskReport workspace containment", () => {
+ it("rejects a .zoocode symlink that resolves outside the workspace", async () => {
+ const outside = await fs.mkdtemp(path.join(os.tmpdir(), "subtask-reports-outside-"))
+ try {
+ // A directory junction works on Windows without symlink
+ // privileges and realpath resolves it like any symlink.
+ await fs.symlink(outside, path.join(cwd, ".zoocode"), "junction")
+
+ await expect(
+ writeSubtaskReport({
+ cwd,
+ parentTaskId: "parent-1",
+ childTaskId: "child-1",
+ label: "api",
+ markdown: "# Report",
+ }),
+ ).rejects.toThrow(/escapes the workspace/)
+
+ // The rejection fires before anything is created outside.
+ expect(await fs.readdir(outside)).toEqual([])
+ expect(renameMock).not.toHaveBeenCalled()
+ } finally {
+ await fs.rm(outside, { recursive: true, force: true })
+ }
+ })
+
+ it("rejects a subtask-reports symlink nested in the workspace that resolves outside it", async () => {
+ const outside = await fs.mkdtemp(path.join(os.tmpdir(), "subtask-reports-outside-"))
+ try {
+ await fs.mkdir(path.join(cwd, ".zoocode"), { recursive: true })
+ await fs.symlink(outside, path.join(cwd, ".zoocode", "subtask-reports"), "junction")
+
+ await expect(
+ writeSubtaskReport({
+ cwd,
+ parentTaskId: "parent-1",
+ childTaskId: "child-1",
+ label: "api",
+ markdown: "# Report",
+ }),
+ ).rejects.toThrow(/escapes the workspace/)
+
+ expect(await fs.readdir(outside)).toEqual([])
+ expect(renameMock).not.toHaveBeenCalled()
+ } finally {
+ await fs.rm(outside, { recursive: true, force: true })
+ }
+ })
+
+ it("writes normally when .zoocode is a symlink to a directory inside the workspace", async () => {
+ const realHome = path.join(cwd, "real-home")
+ await fs.mkdir(realHome, { recursive: true })
+ await fs.symlink(realHome, path.join(cwd, ".zoocode"), "junction")
+
+ const report = await writeSubtaskReport({
+ cwd,
+ parentTaskId: "parent-1",
+ childTaskId: "child-1",
+ label: "api",
+ markdown: "# Findings",
+ })
+
+ expect(report.path).toBe(path.join(getSubtaskReportsDir(cwd, "parent-1"), "api-child-1.md"))
+ expect(await fs.readFile(report.path, "utf8")).toBe("# Findings")
+ // The content landed in the symlink's target, still in the workspace.
+ const canonicalCopy = path.join(realHome, "subtask-reports", "parent-1", "api-child-1.md")
+ expect(await fs.readFile(canonicalCopy, "utf8")).toBe("# Findings")
+ })
+ })
+})
diff --git a/src/core/subtask-reports/index.ts b/src/core/subtask-reports/index.ts
new file mode 100644
index 0000000000..31a74d8079
--- /dev/null
+++ b/src/core/subtask-reports/index.ts
@@ -0,0 +1,10 @@
+/**
+ * Public API of the host-side subtask report store (design D6).
+ *
+ * Invariant: the host owns report persistence; children only return markdown
+ * through attempt_completion. Reports live under
+ * `/.zoocode/subtask-reports//` and are written atomically.
+ */
+export { getSubtaskReportsDir, writeSubtaskReport } from "./writeReport"
+export type { SubtaskReport, WriteSubtaskReportParams } from "./writeReport"
+export { sanitizeReportLabel, resolveReportPath } from "./naming"
diff --git a/src/core/subtask-reports/naming.ts b/src/core/subtask-reports/naming.ts
new file mode 100644
index 0000000000..8f2c3adb25
--- /dev/null
+++ b/src/core/subtask-reports/naming.ts
@@ -0,0 +1,112 @@
+/**
+ * Report filename construction for the sub-subtasks feature (design D6).
+ *
+ * Invariant: the host owns report persistence; children only return markdown
+ * through attempt_completion. Filenames therefore derive from host-side facts
+ * (the parent's task id, the child's task id) plus a model-supplied label that
+ * is treated as untrusted input and sanitized before it touches the filesystem.
+ */
+import * as fs from "fs/promises"
+import * as path from "path"
+
+/** Upper bound for the sanitized label portion of a report filename. */
+const MAX_LABEL_LENGTH = 60
+
+/** Candidate names tried before giving up on a colliding report filename. */
+const MAX_COLLISION_ATTEMPTS = 100
+
+const WINDOWS_RESERVED_NAMES = new Set([
+ "CON",
+ "PRN",
+ "AUX",
+ "NUL",
+ "COM1",
+ "COM2",
+ "COM3",
+ "COM4",
+ "COM5",
+ "COM6",
+ "COM7",
+ "COM8",
+ "COM9",
+ "LPT1",
+ "LPT2",
+ "LPT3",
+ "LPT4",
+ "LPT5",
+ "LPT6",
+ "LPT7",
+ "LPT8",
+ "LPT9",
+])
+
+/**
+ * Reduces an arbitrary model-supplied label to a filesystem-safe stem:
+ * path separators and control characters become dashes, Windows-reserved
+ * device names are prefixed, and the result is truncated. Never throws;
+ * a label that sanitizes to nothing falls back to "subtask".
+ */
+export function sanitizeReportLabel(label: string): string {
+ // Control characters first: they are invalid in every filesystem and
+ // can smuggle traversal bytes past naive separator checks. A char-code
+ // loop keeps the matcher free of control-character regexes.
+ let safe = ""
+ for (const char of label) {
+ safe += char.charCodeAt(0) < 32 ? "-" : char
+ }
+ safe = safe
+ // Path separators and the characters Windows forbids in filenames.
+ .replace(/[\\/:*?"<>|]/g, "-")
+ .trim()
+ // Trailing dots and spaces are invalid on Windows and survive trim().
+ safe = safe.replace(/[. ]+$/, "")
+ if (safe === "") {
+ safe = "subtask"
+ }
+ // Windows reserves device names with or without a trailing dot or space
+ // (CON, con.txt, "CON " are all reserved), so test the first dot segment.
+ const firstSegment = safe.split(".")[0].trimEnd().toUpperCase()
+ if (WINDOWS_RESERVED_NAMES.has(firstSegment)) {
+ safe = `_${safe}`
+ }
+ if (safe.length > MAX_LABEL_LENGTH) {
+ safe = safe.slice(0, MAX_LABEL_LENGTH)
+ }
+ return safe
+}
+
+/**
+ * Computes `/-.md`, appending a numeric
+ * suffix when the name is already taken. The child task id is globally unique,
+ * so two siblings can never target the same path even with identical labels;
+ * the suffix only fires on a same-child rewrite or a hostile label that
+ * sanitized to a colliding stem.
+ *
+ * Throws when the resolved path would escape `reportsDir` (path traversal) or
+ * when every candidate name up to `MAX_COLLISION_ATTEMPTS` is already taken.
+ */
+export async function resolveReportPath(reportsDir: string, label: string, childTaskId: string): Promise {
+ const safeLabel = sanitizeReportLabel(label)
+ const stem = `${safeLabel}-${childTaskId}`
+ const root = path.resolve(reportsDir)
+
+ for (let attempt = 0; attempt < MAX_COLLISION_ATTEMPTS; attempt++) {
+ const candidate = path.join(root, `${attempt === 0 ? stem : `${stem}-${attempt + 1}`}.md`)
+ const resolved = path.resolve(candidate)
+ // Containment is lexical: path.resolve does not resolve symlinks, so a
+ // symlink planted in an ancestor of reportsDir could still redirect the
+ // write. Planting one requires write access to the workspace, which
+ // already grants full control of the reports directory, so the symlink
+ // adds no capability. That trust assumption is why no realpath
+ // round-trip is done here.
+ if (resolved !== root && !resolved.startsWith(root + path.sep)) {
+ throw new Error(`subtask report path escapes the reports directory: ${resolved}`)
+ }
+ try {
+ await fs.access(resolved)
+ } catch {
+ return resolved
+ }
+ }
+ throw new Error(`subtask report filename collision limit reached after ${MAX_COLLISION_ATTEMPTS} attempts: ${stem}`)
+}
diff --git a/src/core/subtask-reports/writeReport.ts b/src/core/subtask-reports/writeReport.ts
new file mode 100644
index 0000000000..20178c53b3
--- /dev/null
+++ b/src/core/subtask-reports/writeReport.ts
@@ -0,0 +1,199 @@
+/**
+ * Atomic markdown report writer for the sub-subtasks feature (design D6).
+ *
+ * Invariant: the host owns report persistence; children only return markdown
+ * through attempt_completion and never touch the filesystem themselves. The
+ * write below is atomic: content lands in a temp file in the same directory
+ * and is committed with a single rename, so a reader never sees a partial
+ * report and an interrupted write leaves the previous file intact. The temp
+ * file is created exclusively (O_EXCL-style "wx"), so a pre-planted file at
+ * the temp path fails the write instead of being overwritten or hijacked, and
+ * the failure cleanup removes only a temp file this writer acquired.
+ *
+ * Containment is canonical, not lexical: `.zoocode` or any ancestor may be a
+ * symlink (a junction on Windows), so the report directory is validated via
+ * realpath before the mkdir and again after it, and a directory that resolves
+ * outside `cwd` fails closed instead of publishing the report outside the
+ * workspace.
+ */
+import * as fs from "fs/promises"
+import * as path from "path"
+
+import { resolveReportPath } from "./naming"
+
+export interface WriteSubtaskReportParams {
+ cwd: string
+ parentTaskId: string
+ childTaskId: string
+ label: string
+ markdown: string
+}
+
+/** One written report; `path` is absolute. */
+export interface SubtaskReport {
+ path: string
+ label: string
+ taskId: string
+ parentTaskId: string
+}
+
+/** Directory holding one parent's child reports. */
+export function getSubtaskReportsDir(cwd: string, parentTaskId: string): string {
+ return path.join(cwd, ".zoocode", "subtask-reports", parentTaskId)
+}
+
+/**
+ * Temp path in the destination directory. The basename is deliberately short
+ * and does not embed the destination name: a report name can approach the
+ * 255-byte per-component limit on ext4 (60 UTF-8-heavy label characters plus a
+ * 36-character child id), and a temp name built from it would exceed that
+ * limit and fail the write. `pid` and the base-36 timestamp plus random suffix
+ * keep concurrent writers in one directory apart.
+ */
+function createTempPath(targetPath: string): string {
+ const unique = `${process.pid}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`
+ return path.join(path.dirname(targetPath), `.tmp-${unique}`)
+}
+
+/**
+ * Realpath of the deepest existing ancestor of `target` (the path itself when
+ * it exists), walking up on ENOENT. A dangling symlink fails closed: creation
+ * flows (mkdir -p) would follow it and could escape the workspace. Returns
+ * null on unexpected fs errors so the containment check fails closed. Mirrors
+ * realPathOfExistingAncestor in src/utils/pathUtils.ts; it is duplicated here
+ * because that helper is not exported and its module imports vscode, which
+ * this vscode-free writer must not require.
+ */
+async function realPathOfExistingAncestor(target: string): Promise {
+ let current = target
+ for (;;) {
+ try {
+ return await fs.realpath(current)
+ } catch (error) {
+ const code = (error as NodeJS.ErrnoException).code
+ if (code !== "ENOENT") {
+ return null
+ }
+ // ENOENT from realpath is ambiguous: the entry may not exist yet, or
+ // it may be a dangling symlink whose target is missing. lstat does
+ // not follow the final entry, so it distinguishes the two.
+ try {
+ const stat = await fs.lstat(current)
+ if (stat.isSymbolicLink()) {
+ return null
+ }
+ } catch (lstatError) {
+ const lstatCode = (lstatError as NodeJS.ErrnoException).code
+ if (lstatCode !== "ENOENT") {
+ return null
+ }
+ }
+ const parent = path.dirname(current)
+ if (parent === current) {
+ return null
+ }
+ current = parent
+ }
+ }
+}
+
+/**
+ * Throws when `canonicalCandidate` is neither `canonicalRoot` nor one of its
+ * descendants. `reportsDir` is the lexical path used for the error message.
+ */
+function assertContainedInWorkspace(canonicalRoot: string, canonicalCandidate: string, reportsDir: string): void {
+ if (canonicalCandidate !== canonicalRoot && !canonicalCandidate.startsWith(canonicalRoot + path.sep)) {
+ throw new Error(`subtask report directory escapes the workspace: ${reportsDir}`)
+ }
+}
+
+/**
+ * Atomically writes one child's markdown report to
+ * `/.zoocode/subtask-reports//-.md`.
+ * Collision-free by construction (the child task id is globally unique) with a
+ * numeric suffix if a sanitized collision still occurs; the resolved path is
+ * guarded against escaping the reports directory, and the report directory
+ * itself is guarded against escaping the workspace once symlinks are
+ * resolved. Throws on any failure so the caller can mark the child failed
+ * instead of silently losing the report.
+ */
+export async function writeSubtaskReport(params: WriteSubtaskReportParams): Promise {
+ const reportsDir = getSubtaskReportsDir(params.cwd, params.parentTaskId)
+
+ // Fail closed before creating anything: if an existing ancestor of the
+ // report directory (e.g. a symlinked .zoocode) resolves outside the
+ // workspace, the mkdir below would publish the report outside the
+ // workspace. realpath on the full path can fail because the leaf
+ // directories do not exist yet, so the deepest existing ancestor is
+ // checked instead.
+ const canonicalCwd = await fs.realpath(params.cwd)
+ const existingAncestor = await realPathOfExistingAncestor(reportsDir)
+ if (!existingAncestor) {
+ throw new Error(`subtask report directory escapes the workspace: ${reportsDir}`)
+ }
+ assertContainedInWorkspace(canonicalCwd, existingAncestor, reportsDir)
+
+ await fs.mkdir(reportsDir, { recursive: true })
+
+ // Re-validate through realpath after the mkdir: it catches a symlink
+ // swapped in between the check above and the directory creation, and it
+ // confirms the directory the temp file and rename will actually touch is
+ // the canonical one inside the workspace. The lexical reportsDir still
+ // drives naming and the returned path, so the public path shape is stable.
+ const canonicalReportsDir = await fs.realpath(reportsDir)
+ assertContainedInWorkspace(canonicalCwd, canonicalReportsDir, reportsDir)
+
+ const targetPath = await resolveReportPath(reportsDir, params.label, params.childTaskId)
+ const tempPath = createTempPath(targetPath)
+
+ let tempAcquired = false
+ try {
+ // Exclusive create ("wx"): a pre-planted file (or symlink) at the temp
+ // path makes the create fail instead of being hijacked, and the rename
+ // below then never runs against attacker content. tempAcquired is set
+ // as soon as the create succeeds, before the write: a write failure
+ // after the create (a full disk, for example) leaves a temp fragment
+ // this writer owns, and the failure cleanup below must remove it.
+ const handle = await fs.open(tempPath, "wx")
+ tempAcquired = true
+ // Some filesystems (NFS in particular) report a quota or space failure
+ // at close() rather than at write() time. A rejected close after a
+ // resolved writeFile therefore still means the report may not be
+ // durable; swallowing it would let the rename below publish a report
+ // the filesystem already flagged. When the write itself also failed,
+ // the original write error is preserved.
+ let writeError: unknown
+ try {
+ await fs.writeFile(handle, params.markdown, { encoding: "utf8" })
+ } catch (error) {
+ writeError = error
+ }
+ try {
+ await handle.close()
+ } catch (closeError) {
+ if (writeError === undefined) {
+ writeError = closeError
+ }
+ }
+ if (writeError !== undefined) {
+ throw writeError
+ }
+ await fs.rename(tempPath, targetPath)
+ } catch (error) {
+ // Remove only the temp file this writer acquired. A pre-planted file
+ // that made the exclusive create fail belongs to someone else; deleting
+ // it would erase content the writer never owned. The target keeps its
+ // previous content either way.
+ if (tempAcquired) {
+ await fs.rm(tempPath, { force: true }).catch(() => {})
+ }
+ throw error instanceof Error ? error : new Error(String(error))
+ }
+
+ return {
+ path: targetPath,
+ label: params.label,
+ taskId: params.childTaskId,
+ parentTaskId: params.parentTaskId,
+ }
+}
diff --git a/src/core/task-persistence/TaskHistoryStore.ts b/src/core/task-persistence/TaskHistoryStore.ts
index e0bb54998c..dacbd1fcf8 100644
--- a/src/core/task-persistence/TaskHistoryStore.ts
+++ b/src/core/task-persistence/TaskHistoryStore.ts
@@ -26,6 +26,24 @@ function mergeWithDisk(delta: Partial): (existing: unknown, incomin
return (existing, incoming) => mergeHistoryDelta(existing, incoming as HistoryItem, delta)
}
+/**
+ * Raised from a guarded repair write when the locked disk record shows the
+ * repair target no longer matches the snapshot the repair was computed from:
+ * the record was deleted, or its status / background parent changed. Callers
+ * skip the repair (and drop any deferral) instead of retrying against a stale
+ * snapshot. `diskItem` is the authoritative replacement for the cache, or
+ * null when the record is gone.
+ */
+class RepairTargetChangedError extends Error {
+ constructor(
+ public readonly taskId: string,
+ public readonly diskItem: HistoryItem | null,
+ ) {
+ super(`[TaskHistoryStore] repair target ${taskId} changed on disk`)
+ this.name = "RepairTargetChangedError"
+ }
+}
+
/**
* Durable intent for the one repair that spans an active delegated child and
* its parent. Task files remain authoritative; this file only records the
@@ -80,16 +98,28 @@ export interface TaskHistoryStoreOptions {
* globalState during the transition period.
*/
onWrite?: (items: HistoryItem[]) => Promise
+
+ /**
+ * Optional hook consulted by the startup background-child pass (D11):
+ * returns true when `taskId` belongs to a live in-memory background child
+ * of the running extension host. A live child is never marked interrupted
+ * by that pass. Defaults to "not live", which is correct for startup
+ * cleanup because a live child is registered in host memory, not only on
+ * disk.
+ */
+ isLiveBackgroundChild?: (taskId: string) => boolean
}
export class TaskHistoryStore {
private readonly globalStoragePath: string
private readonly onWrite?: (items: HistoryItem[]) => Promise
+ private readonly isLiveBackgroundChild?: (taskId: string) => boolean
private cache: Map = new Map()
private taskFileMtimes: Map = new Map()
private writeLock: Promise = Promise.resolve()
private fsWatcher: fsSync.FSWatcher | null = null
private reconcileTimer: ReturnType | null = null
+ private deferredBackgroundChildRepairs: Set = new Set()
private disposed = false
/**
@@ -105,6 +135,7 @@ export class TaskHistoryStore {
constructor(globalStoragePath: string, options?: TaskHistoryStoreOptions) {
this.globalStoragePath = globalStoragePath
this.onWrite = options?.onWrite
+ this.isLiveBackgroundChild = options?.isLiveBackgroundChild
this.initialized = new Promise((resolve) => {
this.resolveInitialized = resolve
})
@@ -137,10 +168,18 @@ export class TaskHistoryStore {
// 3. Repair delegation inconsistencies left by a previous crash
await this.reconcileDelegationState(persistedActiveIds)
- // 4. Start fs.watch for cross-instance reactivity
+ // 4. Clean up background children orphaned by a previous session (D11): a
+ // persisted child stamped `backgroundParentTaskId` whose parent is no
+ // longer active was left running when the extension went away, so mark it
+ // interrupted. Like `reconcileDelegationState`, the wrapper acquires
+ // `withLock` and the core writes through `upsertCore` directly so the
+ // non-reentrant lock is never re-entered.
+ await this.reconcileBackgroundChildren(persistedActiveIds)
+
+ // 5. Start fs.watch for cross-instance reactivity
this.startWatcher()
- // 5. Start periodic reconciliation as a defensive fallback
+ // 6. Start periodic reconciliation as a defensive fallback
this.startPeriodicReconciliation()
} finally {
// Mark initialization as complete so callers awaiting `initialized` can proceed
@@ -209,7 +248,7 @@ export class TaskHistoryStore {
*/
private async upsertCore(
item: HistoryItem,
- options: { skipTransitionCheck?: boolean } = {},
+ options: { skipTransitionCheck?: boolean; repairGuard?: (existing: unknown) => void } = {},
): Promise {
const existing = this.cache.get(item.id)
@@ -241,7 +280,7 @@ export class TaskHistoryStore {
const delta = existing ? this.buildDelta(item.id, existing, item) : { ...item }
let written: HistoryItem
try {
- written = await this.writeTaskFile(merged, delta)
+ written = await this.writeTaskFile(merged, delta, options.repairGuard)
} catch (error) {
if (error instanceof DeltaRejectedError) {
const diskItem = await this.readTaskFile(item.id)
@@ -336,6 +375,9 @@ export class TaskHistoryStore {
*
* - Tasks on disk but missing from cache: read and add
* - Tasks in cache but missing from disk: remove
+ * - Orphan-repair deferrals from `reconcileBackgroundChildren` are retried
+ * at the end of the pass, so the watcher- and timer-driven reconciliations
+ * re-evaluate a child once its parent's record becomes readable again
*/
async reconcile(options: { forceRefresh?: boolean } = {}): Promise {
// Run through the write lock to prevent interleaving with upsert/delete
@@ -410,6 +452,11 @@ export class TaskHistoryStore {
this.taskFileMtimes.delete(taskId)
}
}
+
+ // Retry orphan repairs deferred while a parent record was
+ // unreadable. The set is empty on almost every pass, so this is a
+ // no-op unless startup (or an earlier pass) registered a deferral.
+ await this.retryDeferredBackgroundChildRepairsCore()
})
}
@@ -531,6 +578,270 @@ export class TaskHistoryStore {
} while (repairsInThisPass > 0)
}
+ /**
+ * Clean up background children orphaned by a previous session (D11).
+ *
+ * Called once from `initialize()` after `reconcileDelegationState()`.
+ *
+ * Must NOT be called from within `withLock` — `withLock` is non-reentrant
+ * (promise chain); calling `upsert` (which acquires the lock) from inside
+ * would deadlock. `upsertCore` is called directly here instead, bypassing
+ * transition validation via `skipTransitionCheck: true` because these
+ * writes are administrative repairs, not runtime state-machine transitions.
+ *
+ * Cases repaired per child (children the startup pass never touches are
+ * left exactly as-is):
+ * - Child without `backgroundParentTaskId` → not a background child, skip
+ * - Child status not `active` (explicit or implicit) → already terminal, skip
+ * - Child live in host memory per the `isLiveBackgroundChild` hook → skip;
+ * a startup pass must not kill a child the running host still owns
+ * - Parent record missing from the cache: read the parent file
+ * authoritatively — an unreadable record defers the repair to a later
+ * pass; a confirmed-missing or terminal parent means child to `interrupted`
+ * - Parent status not `active`/`delegated` → child → `interrupted`
+ * - Parent `active`/`delegated` → the parent may still be resumed and its
+ * fan-out retried, so the child is left for normal lifecycle handling
+ *
+ * The interrupted write is guarded: inside the child file's advisory lock,
+ * the repair is skipped when the record no longer exists, is no longer
+ * active, or carries a different `backgroundParentTaskId` — a child deleted
+ * or changed by another host after the scan must not be recreated from the
+ * startup snapshot.
+ *
+ * A deferred child is registered in `deferredBackgroundChildRepairs`;
+ * every later `reconcile()` pass (watcher- or timer-driven) retries it via
+ * `retryDeferredBackgroundChildRepairsCore` once the parent's record
+ * becomes readable.
+ *
+ * The pass never rethrows: each child's repair is caught and logged so one
+ * bad record cannot stop the remaining repairs or block startup.
+ */
+ private async reconcileBackgroundChildren(persistedActiveIds: ReadonlySet): Promise {
+ return this.withLock(() => this.reconcileBackgroundChildrenCore(persistedActiveIds))
+ }
+
+ /**
+ * Reconcile orphaned background children while the store lock is held.
+ *
+ * Callers that do not hold the lock must use `reconcileBackgroundChildren()`.
+ */
+ private async reconcileBackgroundChildrenCore(persistedActiveIds: ReadonlySet): Promise {
+ const byId = new Map(Array.from(this.cache.values()).map((i) => [i.id, i]))
+
+ for (const [, item] of byId) {
+ try {
+ const parentTaskId = item.backgroundParentTaskId
+ if (parentTaskId === undefined) {
+ continue
+ }
+
+ // Mirror reconcileDelegationStateCore: only statuses loaded from
+ // persistence represent sessions that could have been orphaned by a
+ // crash. No earlier startup pass re-activates a background child, so
+ // the snapshot guard is documentation as much as enforcement.
+ const childStatus: HistoryItemStatus = item.status ?? "active"
+ if (childStatus !== "active" || !persistedActiveIds.has(item.id)) {
+ continue
+ }
+
+ if (this.isLiveBackgroundChild?.(item.id)) {
+ continue
+ }
+
+ const parent = byId.get(parentTaskId)
+ if (parent) {
+ const parentStatus: HistoryItemStatus = parent.status ?? "active"
+ if (parentStatus === "active" || parentStatus === "delegated") {
+ continue
+ }
+ // Terminal parent confirmed by the startup scan: repair below.
+ } else {
+ // A cache miss is not proof the parent is gone. A transient read
+ // failure during the startup scan keeps a live parent's record out
+ // of the cache while its child's record loads normally, and this
+ // pass must not write `interrupted` to the child on that guess.
+ // Read the parent file authoritatively: defer on a read error and
+ // keep the repair only for a confirmed missing or terminal parent.
+ const diskParent = await this.readTaskFileDiscriminated(parentTaskId)
+ if (diskParent.kind === "unreadable") {
+ this.deferredBackgroundChildRepairs.add(item.id)
+ console.warn(
+ `[TaskHistoryStore] Deferred orphaned-background-child repair for task ${item.id}: parent ${parentTaskId} record unreadable`,
+ diskParent.reason,
+ )
+ continue
+ }
+ if (diskParent.kind === "found") {
+ this.cache.set(parentTaskId, diskParent.item)
+ const diskParentStatus: HistoryItemStatus = diskParent.item.status ?? "active"
+ if (diskParentStatus === "active" || diskParentStatus === "delegated") {
+ continue
+ }
+ }
+ // kind === "missing": the parent file is confirmed gone.
+ }
+
+ await this.upsertCore(
+ { ...item, status: "interrupted" },
+ {
+ skipTransitionCheck: true,
+ repairGuard: this.backgroundChildRepairGuard(item.id, parentTaskId),
+ },
+ )
+ console.warn(
+ `[TaskHistoryStore] Reconciled orphaned background child: task ${item.id} → interrupted (parent ${parentTaskId} ${
+ parent ? `status ${parent.status}` : "not found"
+ })`,
+ )
+ } catch (error) {
+ if (error instanceof RepairTargetChangedError) {
+ // Another host deleted or changed the child after the scan.
+ // Skip the repair; the authoritative disk record (or its
+ // absence) wins over the startup snapshot.
+ this.settleSkippedBackgroundChildRepair(error)
+ continue
+ }
+ // One child's repair failure (e.g. a locked or unwritable file)
+ // must not end the pass: the remaining orphaned children are
+ // still repaired. The failed child's cache entry is untouched —
+ // upsertCore throws before updating it.
+ console.error(`[TaskHistoryStore] Failed to reconcile background child ${item.id}:`, error)
+ }
+ }
+ }
+
+ /**
+ * Retry orphan repairs deferred because a parent record was unreadable,
+ * while the store lock is already held. `reconcile()` invokes this at
+ * the end of its locked pass, so both the fs.watch debounce and the
+ * periodic timer retry a deferred child once the parent's record
+ * becomes readable again.
+ *
+ * Every deferred child is re-evaluated before any write, against the
+ * just-refreshed cache: a child that is no longer active, has no
+ * `backgroundParentTaskId`, or is now owned by the live host drops its
+ * deferral untouched; a parent that is readable and `active`/`delegated`
+ * means normal lifecycle handling owns the child, so the deferral is
+ * dropped too; a parent that is still unreadable keeps the deferral for
+ * a later pass; only a parent confirmed missing or terminal reaches the
+ * same `interrupted` write as the startup pass, guarded inside the child
+ * file's advisory lock the same way: a child deleted or changed after the
+ * cache refresh drops its deferral instead of being recreated. A failed
+ * write keeps the deferral instead of cancelling the retry.
+ */
+ private async retryDeferredBackgroundChildRepairsCore(): Promise {
+ for (const taskId of Array.from(this.deferredBackgroundChildRepairs)) {
+ try {
+ const item = this.cache.get(taskId)
+ const parentTaskId = item?.backgroundParentTaskId
+ if (!item || parentTaskId === undefined) {
+ this.deferredBackgroundChildRepairs.delete(taskId)
+ continue
+ }
+
+ const childStatus: HistoryItemStatus = item.status ?? "active"
+ if (childStatus !== "active" || this.isLiveBackgroundChild?.(taskId)) {
+ this.deferredBackgroundChildRepairs.delete(taskId)
+ continue
+ }
+
+ const parent = this.cache.get(parentTaskId)
+ if (parent) {
+ const parentStatus: HistoryItemStatus = parent.status ?? "active"
+ if (parentStatus === "active" || parentStatus === "delegated") {
+ this.deferredBackgroundChildRepairs.delete(taskId)
+ continue
+ }
+ // Terminal parent visible to the refreshed cache: repair below.
+ } else {
+ const diskParent = await this.readTaskFileDiscriminated(parentTaskId)
+ if (diskParent.kind === "unreadable") {
+ // Still unreadable: keep the deferral for a later pass.
+ continue
+ }
+ if (diskParent.kind === "found") {
+ this.cache.set(parentTaskId, diskParent.item)
+ const diskParentStatus: HistoryItemStatus = diskParent.item.status ?? "active"
+ if (diskParentStatus === "active" || diskParentStatus === "delegated") {
+ this.deferredBackgroundChildRepairs.delete(taskId)
+ continue
+ }
+ }
+ // kind === "missing": the parent file is confirmed gone.
+ }
+
+ await this.upsertCore(
+ { ...item, status: "interrupted" },
+ {
+ skipTransitionCheck: true,
+ repairGuard: this.backgroundChildRepairGuard(taskId, parentTaskId),
+ },
+ )
+ this.deferredBackgroundChildRepairs.delete(taskId)
+ console.warn(
+ `[TaskHistoryStore] Reconciled deferred orphaned background child: task ${taskId} → interrupted (parent ${parentTaskId})`,
+ )
+ } catch (error) {
+ if (error instanceof RepairTargetChangedError) {
+ // The child was deleted or changed while deferred: nothing
+ // left to repair, so drop the deferral instead of retrying
+ // against a stale snapshot.
+ this.settleSkippedBackgroundChildRepair(error)
+ this.deferredBackgroundChildRepairs.delete(taskId)
+ continue
+ }
+ // Keep the deferral: a transient failure must not cancel the retry.
+ console.error(
+ `[TaskHistoryStore] Failed to retry deferred background child repair for ${taskId}:`,
+ error,
+ )
+ }
+ }
+ }
+
+ /**
+ * Build the under-lock guard for an orphaned-background-child repair write.
+ * The check runs inside `safeWriteJson`'s per-file advisory-lock merge,
+ * against the record the lock hands us — not this store's cache, which the
+ * scan (or a concurrent reconcile) may have raced. A child deleted by
+ * another host after the scan must not be recreated as `interrupted`: a
+ * missing disk record would otherwise flow through `mergeHistoryDelta` as
+ * a fresh insert. A child whose status or background parent changed must
+ * not be overwritten from the stale snapshot either.
+ */
+ private backgroundChildRepairGuard(
+ taskId: string,
+ expectedBackgroundParentTaskId: string,
+ ): (existing: unknown) => void {
+ return (existing: unknown) => {
+ const disk =
+ existing && typeof existing === "object" && "id" in existing ? (existing as HistoryItem) : undefined
+ if (!disk || disk.id !== taskId) {
+ throw new RepairTargetChangedError(taskId, null)
+ }
+ if (
+ (disk.status ?? "active") !== "active" ||
+ disk.backgroundParentTaskId !== expectedBackgroundParentTaskId
+ ) {
+ throw new RepairTargetChangedError(taskId, disk)
+ }
+ }
+ }
+
+ /**
+ * Keep the cache consistent with the authoritative disk record after a
+ * guarded repair was skipped: a changed record replaces the stale cache
+ * entry, a deleted record evicts it.
+ */
+ private settleSkippedBackgroundChildRepair(error: RepairTargetChangedError): void {
+ if (error.diskItem) {
+ this.cache.set(error.taskId, error.diskItem)
+ } else {
+ this.cache.delete(error.taskId)
+ this.taskFileMtimes.delete(error.taskId)
+ }
+ }
+
private getPersistedActiveIds(): ReadonlySet {
return new Set(
Array.from(this.cache.values())
@@ -889,14 +1200,22 @@ export class TaskHistoryStore {
* delta to the current disk state, so fields written by another
* process are preserved. Without a delta the full item is written
* as-is (used by administrative repair paths that are authoritative).
+ * `repairGuard` runs first, inside the advisory lock, and may throw
+ * `RepairTargetChangedError` to abort a repair whose disk record no
+ * longer matches (see `backgroundChildRepairGuard`).
*/
- private async writeTaskFile(item: HistoryItem, delta?: Partial): Promise {
+ private async writeTaskFile(
+ item: HistoryItem,
+ delta?: Partial,
+ repairGuard?: (existing: unknown) => void,
+ ): Promise {
const filePath = await this.getTaskFilePath(item.id)
if (delta) {
let written: HistoryItem = item
const mergeFn = mergeWithDisk(delta)
await safeWriteJson(filePath, item, {
merge: (existing, incoming) => {
+ repairGuard?.(existing)
const result = mergeFn(existing, incoming)
written = result as HistoryItem
return result
@@ -1105,6 +1424,24 @@ export class TaskHistoryStore {
}
private async readTaskFileForAutoTitle(taskId: string): Promise {
+ const disk = await this.readTaskFileDiscriminated(taskId)
+ if (disk.kind === "unreadable") {
+ // The caller only sees `applied: false`, so the reason is logged here.
+ console.warn(`[TaskHistoryStore] Failed to read task ${taskId} for auto title:`, disk.reason)
+ return { kind: "unreadable" }
+ }
+ return disk
+ }
+
+ /**
+ * Read a HistoryItem from disk, distinguishing a missing file from an
+ * unreadable one (I/O or parse failure, or a mismatched record id). Callers
+ * that would repair or evict other state based on this result must defer on
+ * `unreadable`: a read error is not evidence of absence.
+ */
+ private async readTaskFileDiscriminated(
+ taskId: string,
+ ): Promise<{ kind: "found"; item: HistoryItem } | { kind: "missing" } | { kind: "unreadable"; reason: unknown }> {
let raw: string
try {
raw = await readFileWithMissingRetry(await this.getTaskFilePath(taskId))
@@ -1112,26 +1449,20 @@ export class TaskHistoryStore {
if (getErrorCode(error) === "ENOENT") {
return { kind: "missing" }
}
- return this.unreadableForAutoTitle(taskId, error)
+ return { kind: "unreadable", reason: error }
}
try {
const item: unknown = JSON.parse(raw)
const id = typeof item === "object" && item !== null ? (item as { id?: unknown }).id : undefined
if (id !== taskId) {
- return this.unreadableForAutoTitle(taskId, `task file has id ${JSON.stringify(id)}`)
+ return { kind: "unreadable", reason: `task file has id ${JSON.stringify(id)}` }
}
return { kind: "found", item: item as HistoryItem }
} catch (error) {
- return this.unreadableForAutoTitle(taskId, error)
+ return { kind: "unreadable", reason: error }
}
}
- /** The caller only sees `applied: false`, so the reason is logged here. */
- private unreadableForAutoTitle(taskId: string, reason: unknown): AutoTitleDiskRead {
- console.warn(`[TaskHistoryStore] Failed to read task ${taskId} for auto title:`, reason)
- return { kind: "unreadable" }
- }
-
/**
* Update two related HistoryItems within a single in-process lock acquisition.
* Both updaters run synchronously (no I/O, no lock re-entry). Both writes
diff --git a/src/core/task-persistence/__tests__/TaskHistoryStore.backgroundChildren.spec.ts b/src/core/task-persistence/__tests__/TaskHistoryStore.backgroundChildren.spec.ts
new file mode 100644
index 0000000000..6d71863c2d
--- /dev/null
+++ b/src/core/task-persistence/__tests__/TaskHistoryStore.backgroundChildren.spec.ts
@@ -0,0 +1,727 @@
+// pnpm --filter zoo-code test core/task-persistence/__tests__/TaskHistoryStore.backgroundChildren.spec.ts
+
+import * as fs from "fs/promises"
+import * as path from "path"
+import * as os from "os"
+
+import type { HistoryItem } from "@roo-code/types"
+
+import { GlobalFileNames } from "../../../shared/globalFileNames"
+import { TaskHistoryStore } from "../TaskHistoryStore"
+
+vi.mock("../../../utils/storage", () => ({
+ getStorageBasePath: vi.fn().mockImplementation((defaultPath: string) => defaultPath),
+}))
+
+const writeJson = async (filePath: string, data: unknown): Promise => {
+ await fs.mkdir(path.dirname(filePath), { recursive: true })
+ await fs.writeFile(filePath, JSON.stringify(data, null, "\t"), "utf8")
+}
+
+const safeWriteJsonMock = vi.hoisted(() => vi.fn())
+
+vi.mock("../../../utils/safeWriteJson", () => ({ safeWriteJson: safeWriteJsonMock }))
+
+safeWriteJsonMock.mockImplementation(writeJson)
+
+const readFileMocks = vi.hoisted(() => ({
+ readFileWithMissingRetry: vi.fn(),
+ realReadFileWithMissingRetry: null as null | ((filePath: string) => Promise),
+}))
+
+vi.mock("../readFileWithMissingRetry", async (importOriginal) => {
+ const actual = await importOriginal()
+ readFileMocks.realReadFileWithMissingRetry = actual.readFileWithMissingRetry
+ readFileMocks.readFileWithMissingRetry.mockImplementation(actual.readFileWithMissingRetry)
+ return { ...actual, readFileWithMissingRetry: readFileMocks.readFileWithMissingRetry }
+})
+
+function makeItem(overrides: Partial = {}): HistoryItem {
+ return {
+ id: `task-${Date.now()}-${Math.random().toString(36).substring(2, 8)}`,
+ number: 1,
+ ts: Date.now(),
+ task: "Test task",
+ tokensIn: 0,
+ tokensOut: 0,
+ totalCost: 0,
+ ...overrides,
+ }
+}
+
+async function readPersistedItem(tasksDir: string, taskId: string): Promise {
+ return JSON.parse(
+ await fs.readFile(path.join(tasksDir, taskId, GlobalFileNames.historyItem), "utf8"),
+ ) as HistoryItem
+}
+
+type SafeWriteOptions = { merge?: (existing: unknown, incoming: unknown) => unknown }
+
+/**
+ * A safeWriteJson stand-in that honors the merge contract the store relies
+ * on: read the current file (null when missing), hand it to options.merge,
+ * and write whatever merge returns. The default suite mock writes data
+ * verbatim, so a guard living inside a merge callback would never run there.
+ */
+const mergeHonoringWriteJson = async (filePath: string, data: unknown, options?: SafeWriteOptions): Promise => {
+ let existing: unknown = null
+ try {
+ existing = JSON.parse(await fs.readFile(filePath, "utf8"))
+ } catch {
+ existing = null
+ }
+ const result = options?.merge ? options.merge(existing, data) : data
+ await writeJson(filePath, result)
+}
+
+/**
+ * Wrap mergeHonoringWriteJson with a hook that runs before each merge, used to
+ * simulate another host mutating or deleting a record between the scan and
+ * the repair write.
+ */
+const withConcurrentMutation =
+ (mutate: (filePath: string) => Promise) =>
+ async (filePath: string, data: unknown, options?: SafeWriteOptions): Promise => {
+ await mutate(filePath)
+ await mergeHonoringWriteJson(filePath, data, options)
+ }
+
+// ─────────────────────────────────────────────────────────────────────────────
+// reconcileBackgroundChildren — startup orphan cleanup (D11) via initialize()
+// ─────────────────────────────────────────────────────────────────────────────
+
+describe("TaskHistoryStore reconcileBackgroundChildren", () => {
+ let tmpDir: string
+ let store: TaskHistoryStore
+ const disposables = new Set()
+
+ function registerStore(nextStore: TaskHistoryStore): TaskHistoryStore {
+ disposables.add(nextStore)
+ return nextStore
+ }
+
+ async function seedItems(items: HistoryItem[]): Promise {
+ const tasksDir = path.join(tmpDir, "tasks")
+ await fs.mkdir(tasksDir, { recursive: true })
+ for (const item of items) {
+ const taskDir = path.join(tasksDir, item.id)
+ await fs.mkdir(taskDir, { recursive: true })
+ await fs.writeFile(path.join(taskDir, "history_item.json"), JSON.stringify(item))
+ }
+ }
+
+ beforeEach(async () => {
+ tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), "bg-children-test-"))
+ store = registerStore(new TaskHistoryStore(tmpDir))
+ })
+
+ afterEach(async () => {
+ vi.restoreAllMocks()
+ safeWriteJsonMock.mockImplementation(writeJson)
+ if (readFileMocks.realReadFileWithMissingRetry) {
+ readFileMocks.readFileWithMissingRetry.mockImplementation(readFileMocks.realReadFileWithMissingRetry)
+ }
+ for (const disposable of disposables) disposable.dispose()
+ disposables.clear()
+ await fs.rm(tmpDir, { recursive: true, force: true }).catch(() => {})
+ })
+
+ it("marks a persisted background child interrupted when its parent record is missing", async () => {
+ const child = makeItem({ id: "child-orphan", status: "active", backgroundParentTaskId: "missing-parent" })
+ await seedItems([child])
+
+ await store.initialize()
+
+ const repaired = store.get("child-orphan")
+ expect(repaired).toMatchObject({
+ id: "child-orphan",
+ status: "interrupted",
+ backgroundParentTaskId: "missing-parent",
+ })
+ const persisted = await readPersistedItem(path.join(tmpDir, "tasks"), "child-orphan")
+ expect(persisted.status).toBe("interrupted")
+ })
+
+ it.each(["completed", "interrupted"] as const)(
+ "marks a persisted background child interrupted when its parent is %s",
+ async (parentStatus) => {
+ const parent = makeItem({ id: "parent-terminal", status: parentStatus })
+ const child = makeItem({ id: "child-terminal-parent", status: "active", backgroundParentTaskId: parent.id })
+ await seedItems([parent, child])
+
+ await store.initialize()
+
+ expect(store.get(child.id)?.status).toBe("interrupted")
+ expect(store.get(parent.id)?.status).toBe(parentStatus)
+ const persisted = await readPersistedItem(path.join(tmpDir, "tasks"), child.id)
+ expect(persisted.status).toBe("interrupted")
+ },
+ )
+
+ it.each(["active", "delegated"] as const)(
+ "leaves a background child untouched when its parent is %s",
+ async (parentStatus) => {
+ const parent = makeItem({
+ id: "parent-live",
+ status: parentStatus,
+ ...(parentStatus === "delegated" ? { awaitingChildId: "some-child", delegatedToId: "some-child" } : {}),
+ })
+ const items = [parent]
+ if (parentStatus === "delegated") {
+ // Seed the awaited child as interrupted: that is the branch that
+ // keeps a delegated parent delegated at startup. Without this
+ // record the delegation repair fires first (awaited child not
+ // found), so the delegated branch would never be exercised.
+ items.push(makeItem({ id: "some-child", status: "interrupted", parentTaskId: parent.id }))
+ }
+ const child = makeItem({ id: "child-live-parent", status: "active", backgroundParentTaskId: parent.id })
+ items.push(child)
+ await seedItems(items)
+
+ await store.initialize()
+
+ expect(store.get(child.id)).toMatchObject({
+ id: child.id,
+ status: "active",
+ backgroundParentTaskId: parent.id,
+ })
+ // The delegated case must survive startup with the parent still
+ // delegated and the delegation link intact.
+ if (parentStatus === "delegated") {
+ expect(store.get(parent.id)).toMatchObject({
+ status: "delegated",
+ awaitingChildId: "some-child",
+ delegatedToId: "some-child",
+ })
+ }
+ },
+ )
+
+ it("defers the repair when the parent's record is unreadable at startup instead of assuming the parent is gone", async () => {
+ const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {})
+ const parent = makeItem({ id: "parent-transient", status: "active" })
+ const child = makeItem({ id: "child-transient-parent", status: "active", backgroundParentTaskId: parent.id })
+ await seedItems([parent, child])
+ const realReadFileWithMissingRetry = readFileMocks.realReadFileWithMissingRetry
+ if (!realReadFileWithMissingRetry) {
+ throw new Error("readFileWithMissingRetry mock not initialized")
+ }
+ readFileMocks.readFileWithMissingRetry.mockImplementation(async (filePath: string) => {
+ if (filePath.includes(parent.id) && filePath.endsWith(GlobalFileNames.historyItem)) {
+ // A transient read error keeps the live parent out of the startup
+ // cache while the child's record loads normally.
+ const error = new Error("device busy") as NodeJS.ErrnoException
+ error.code = "EBUSY"
+ throw error
+ }
+ return realReadFileWithMissingRetry(filePath)
+ })
+
+ await store.initialize()
+
+ // The read error must not be mistaken for a missing parent: the child
+ // stays active in the cache and on disk.
+ expect(store.get(child.id)?.status).toBe("active")
+ const persisted = await readPersistedItem(path.join(tmpDir, "tasks"), child.id)
+ expect(persisted.status).toBe("active")
+ expect(warnSpy).toHaveBeenCalledWith(
+ expect.stringContaining("Deferred orphaned-background-child repair"),
+ expect.anything(),
+ )
+ warnSpy.mockRestore()
+ })
+
+ it.each(["interrupted", "completed"] as const)(
+ "leaves a background child whose own status is already %s untouched",
+ async (childStatus) => {
+ const child = makeItem({
+ id: "child-terminal",
+ status: childStatus,
+ backgroundParentTaskId: "missing-parent",
+ })
+ await seedItems([child])
+
+ await store.initialize()
+
+ expect(store.get(child.id)?.status).toBe(childStatus)
+ },
+ )
+
+ it("leaves a non-background active child untouched even without a parent record", async () => {
+ const plain = makeItem({ id: "plain-active", status: "active" })
+ await seedItems([plain])
+
+ await store.initialize()
+
+ expect(store.get("plain-active")?.status).toBe("active")
+ })
+
+ it("repairs an implicit-active background child with no status field", async () => {
+ const { status: _status, ...legacyChild } = makeItem({
+ id: "child-legacy",
+ status: "active",
+ backgroundParentTaskId: "missing-parent",
+ })
+ await seedItems([legacyChild as HistoryItem])
+
+ await store.initialize()
+
+ expect(store.get("child-legacy")?.status).toBe("interrupted")
+ })
+
+ it("keeps the parent's record unchanged while repairing the child", async () => {
+ const parent = makeItem({ id: "parent-unchanged", status: "completed", childIds: ["child-repair"] })
+ const child = makeItem({ id: "child-repair", status: "active", backgroundParentTaskId: parent.id })
+ await seedItems([parent, child])
+
+ await store.initialize()
+
+ expect(store.get(parent.id)).toMatchObject({ id: parent.id, status: "completed", childIds: ["child-repair"] })
+ expect(store.get(child.id)?.status).toBe("interrupted")
+ })
+
+ it("repairs several orphaned background children in a single initialize()", async () => {
+ const parent = makeItem({ id: "parent-multi", status: "completed" })
+ const childA = makeItem({ id: "child-multi-a", status: "active", backgroundParentTaskId: parent.id })
+ const childB = makeItem({ id: "child-multi-b", status: "active", backgroundParentTaskId: parent.id })
+ const childC = makeItem({ id: "child-multi-c", status: "active", backgroundParentTaskId: "missing-parent" })
+ await seedItems([parent, childA, childB, childC])
+
+ await store.initialize()
+
+ expect(store.get("child-multi-a")?.status).toBe("interrupted")
+ expect(store.get("child-multi-b")?.status).toBe("interrupted")
+ expect(store.get("child-multi-c")?.status).toBe("interrupted")
+ })
+
+ it("continues repairing the remaining children when one repair write fails", async () => {
+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {})
+ const childA = makeItem({ id: "child-pf-a", status: "active", backgroundParentTaskId: "missing-parent" })
+ const childB = makeItem({ id: "child-pf-b", status: "active", backgroundParentTaskId: "missing-parent" })
+ const childC = makeItem({ id: "child-pf-c", status: "active", backgroundParentTaskId: "missing-parent" })
+ await seedItems([childA, childB, childC])
+ // Fail the second repair attempt wherever it lands: the store iterates
+ // task directories in filesystem order, which this test does not
+ // control. Recording the attempt order both pins the injected failure
+ // to a middle attempt and lets the test prove a later attempt succeeded.
+ const repairOrder: string[] = []
+ safeWriteJsonMock.mockImplementation(async (filePath: string, data: unknown) => {
+ if (filePath.endsWith(GlobalFileNames.historyItem)) {
+ repairOrder.push(path.basename(path.dirname(filePath)))
+ if (repairOrder.length === 2) {
+ throw new Error("disk full")
+ }
+ }
+ await writeJson(filePath, data)
+ })
+
+ await store.initialize()
+
+ const [firstId, failedId, laterId] = repairOrder
+ // All three repairs were attempted: the pass did not stop at the first
+ // failed write.
+ expect(repairOrder).toHaveLength(3)
+ // The failed child's repair did not stick anywhere.
+ expect(store.get(failedId)?.status).toBe("active")
+ const persistedFailed = await readPersistedItem(path.join(tmpDir, "tasks"), failedId)
+ expect(persistedFailed.status).toBe("active")
+ // The repairs attempted before and after the failure both persisted.
+ for (const repairedId of [firstId, laterId]) {
+ expect(store.get(repairedId)?.status).toBe("interrupted")
+ const persisted = await readPersistedItem(path.join(tmpDir, "tasks"), repairedId)
+ expect(persisted.status).toBe("interrupted")
+ }
+ errorSpy.mockRestore()
+ })
+
+ describe("isLiveBackgroundChild seam", () => {
+ it("never marks a child the hook reports as live", async () => {
+ store.dispose()
+ store = registerStore(
+ new TaskHistoryStore(tmpDir, { isLiveBackgroundChild: (taskId: string) => taskId === "child-live" }),
+ )
+ const child = makeItem({ id: "child-live", status: "active", backgroundParentTaskId: "missing-parent" })
+ await seedItems([child])
+
+ await store.initialize()
+
+ expect(store.get("child-live")?.status).toBe("active")
+ })
+
+ it("still repairs other children when the hook reports only one as live", async () => {
+ store.dispose()
+ store = registerStore(
+ new TaskHistoryStore(tmpDir, { isLiveBackgroundChild: (taskId: string) => taskId === "child-live" }),
+ )
+ const live = makeItem({ id: "child-live", status: "active", backgroundParentTaskId: "missing-parent" })
+ const orphan = makeItem({
+ id: "child-orphan-seam",
+ status: "active",
+ backgroundParentTaskId: "missing-parent",
+ })
+ await seedItems([live, orphan])
+
+ await store.initialize()
+
+ expect(store.get("child-live")?.status).toBe("active")
+ expect(store.get("child-orphan-seam")?.status).toBe("interrupted")
+ })
+ })
+
+ it("does not block startup when the repair write fails", async () => {
+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {})
+ const child = makeItem({ id: "child-write-fails", status: "active", backgroundParentTaskId: "missing-parent" })
+ await seedItems([child])
+ safeWriteJsonMock.mockImplementation(async (filePath: string, data: unknown) => {
+ if (filePath.includes(child.id) && filePath.endsWith(GlobalFileNames.historyItem)) {
+ throw new Error("disk full")
+ }
+ await writeJson(filePath, data)
+ })
+
+ await expect(store.initialize()).resolves.toBeUndefined()
+
+ expect(errorSpy).toHaveBeenCalledWith(
+ `[TaskHistoryStore] Failed to reconcile background child ${child.id}:`,
+ expect.any(Error),
+ )
+ // The failed repair must not leave a half-updated cache entry behind.
+ expect(store.get(child.id)?.status).toBe("active")
+ errorSpy.mockRestore()
+ })
+
+ it("logs each repaired child to console.warn", async () => {
+ const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {})
+ const child = makeItem({ id: "child-logged", status: "active", backgroundParentTaskId: "missing-parent" })
+ await seedItems([child])
+
+ await store.initialize()
+
+ expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining("Reconciled orphaned background child"))
+ expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining("child-logged"))
+
+ warnSpy.mockRestore()
+ })
+
+ it("invokes onWrite after an orphan repair", async () => {
+ const onWrite = vi.fn().mockResolvedValue(undefined)
+ store.dispose()
+ store = registerStore(new TaskHistoryStore(tmpDir, { onWrite }))
+ const child = makeItem({ id: "child-onwrite", status: "active", backgroundParentTaskId: "missing-parent" })
+ await seedItems([child])
+
+ await store.initialize()
+
+ expect(onWrite).toHaveBeenCalled()
+ const lastCall = onWrite.mock.calls[onWrite.mock.calls.length - 1][0] as HistoryItem[]
+ expect(lastCall.find((i) => i.id === "child-onwrite")?.status).toBe("interrupted")
+ })
+
+ describe("concurrent changes by another host", () => {
+ it("does not recreate a background child deleted between the scan and the repair write", async () => {
+ const parent = makeItem({ id: "parent-concurrent-delete", status: "completed" })
+ const child = makeItem({
+ id: "child-concurrent-delete",
+ status: "active",
+ backgroundParentTaskId: parent.id,
+ })
+ await seedItems([parent, child])
+ const childFile = path.join(tmpDir, "tasks", child.id, GlobalFileNames.historyItem)
+ safeWriteJsonMock.mockImplementation(
+ withConcurrentMutation(async (filePath) => {
+ if (filePath === childFile) {
+ // Another host deletes the child after the startup scan
+ // cached it; the merge then sees no disk record.
+ await fs.rm(childFile, { force: true })
+ }
+ }),
+ )
+
+ await store.initialize()
+
+ // The repair must not recreate the deleted record, and the stale
+ // cache entry must not linger as an active task.
+ await expect(fs.access(childFile)).rejects.toThrow()
+ expect(store.get(child.id)).toBeUndefined()
+ })
+
+ it("does not overwrite a background child reassigned to a different parent before the repair write", async () => {
+ const parent = makeItem({ id: "parent-reassign", status: "completed" })
+ const child = makeItem({ id: "child-reassigned", status: "active", backgroundParentTaskId: parent.id })
+ await seedItems([parent, child])
+ const childFile = path.join(tmpDir, "tasks", child.id, GlobalFileNames.historyItem)
+ safeWriteJsonMock.mockImplementation(
+ withConcurrentMutation(async (filePath) => {
+ if (filePath === childFile) {
+ // Another host moved the child under a new parent; the
+ // stale snapshot's repair must not stamp it interrupted.
+ await writeJson(childFile, { ...child, backgroundParentTaskId: "parent-new-owner" })
+ }
+ }),
+ )
+
+ await store.initialize()
+
+ const persisted = await readPersistedItem(path.join(tmpDir, "tasks"), child.id)
+ expect(persisted).toMatchObject({ status: "active", backgroundParentTaskId: "parent-new-owner" })
+ expect(store.get(child.id)).toMatchObject({ status: "active", backgroundParentTaskId: "parent-new-owner" })
+ })
+
+ it("skips the repair cleanly when another host completes the child before the repair write", async () => {
+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {})
+ const parent = makeItem({ id: "parent-concurrent-complete", status: "completed" })
+ const child = makeItem({
+ id: "child-concurrent-complete",
+ status: "active",
+ backgroundParentTaskId: parent.id,
+ })
+ await seedItems([parent, child])
+ const childFile = path.join(tmpDir, "tasks", child.id, GlobalFileNames.historyItem)
+ safeWriteJsonMock.mockImplementation(
+ withConcurrentMutation(async (filePath) => {
+ if (filePath === childFile) {
+ await writeJson(childFile, { ...child, status: "completed" })
+ }
+ }),
+ )
+
+ await store.initialize()
+
+ const persisted = await readPersistedItem(path.join(tmpDir, "tasks"), child.id)
+ expect(persisted.status).toBe("completed")
+ expect(store.get(child.id)?.status).toBe("completed")
+ // The guard turns a changed child into a clean skip, not a failed
+ // repair write.
+ expect(errorSpy).not.toHaveBeenCalled()
+ errorSpy.mockRestore()
+ })
+ })
+
+ describe("deferred orphan-repair retry", () => {
+ const makeParentUnreadable = (parentId: string) => {
+ const realRead = readFileMocks.realReadFileWithMissingRetry
+ if (!realRead) {
+ throw new Error("readFileWithMissingRetry mock not initialized")
+ }
+ readFileMocks.readFileWithMissingRetry.mockImplementation(async (filePath: string) => {
+ if (filePath.includes(parentId) && filePath.endsWith(GlobalFileNames.historyItem)) {
+ const error = new Error("device busy") as NodeJS.ErrnoException
+ error.code = "EBUSY"
+ throw error
+ }
+ return realRead(filePath)
+ })
+ }
+
+ const restoreRealReads = () => {
+ const realRead = readFileMocks.realReadFileWithMissingRetry
+ if (!realRead) {
+ throw new Error("readFileWithMissingRetry mock not initialized")
+ }
+ readFileMocks.readFileWithMissingRetry.mockImplementation(realRead)
+ }
+
+ it("retries a deferred repair on the next reconciliation once the parent becomes readable", async () => {
+ const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {})
+ const parent = makeItem({ id: "parent-deferred-repair", status: "completed" })
+ const child = makeItem({ id: "child-deferred-repair", status: "active", backgroundParentTaskId: parent.id })
+ await seedItems([parent, child])
+ makeParentUnreadable(parent.id)
+
+ await store.initialize()
+
+ // Startup defers: the parent record is unreadable, so the child
+ // stays active in the cache and on disk.
+ expect(store.get(child.id)?.status).toBe("active")
+ const persistedBefore = await readPersistedItem(path.join(tmpDir, "tasks"), child.id)
+ expect(persistedBefore.status).toBe("active")
+ expect(warnSpy).toHaveBeenCalledWith(
+ expect.stringContaining("Deferred orphaned-background-child repair"),
+ expect.anything(),
+ )
+
+ // The parent record becomes readable again (a transient lock or
+ // device error cleared). Reconciliation is the path watcher and
+ // periodic timers take, so it must retry the deferred repair and
+ // now confirm the terminal parent.
+ restoreRealReads()
+ await store.reconcile()
+
+ expect(store.get(child.id)?.status).toBe("interrupted")
+ const persisted = await readPersistedItem(path.join(tmpDir, "tasks"), child.id)
+ expect(persisted.status).toBe("interrupted")
+ expect(warnSpy).toHaveBeenCalledWith(
+ expect.stringContaining("Reconciled deferred orphaned background child"),
+ )
+ warnSpy.mockRestore()
+ })
+
+ it("keeps the child unchanged while the parent is still unreadable at the retry", async () => {
+ const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {})
+ const parent = makeItem({ id: "parent-still-unreadable", status: "completed" })
+ const child = makeItem({
+ id: "child-still-unreadable",
+ status: "active",
+ backgroundParentTaskId: parent.id,
+ })
+ await seedItems([parent, child])
+ makeParentUnreadable(parent.id)
+
+ await store.initialize()
+ await store.reconcile()
+ await store.reconcile()
+
+ expect(store.get(child.id)?.status).toBe("active")
+ const persisted = await readPersistedItem(path.join(tmpDir, "tasks"), child.id)
+ expect(persisted.status).toBe("active")
+ warnSpy.mockRestore()
+ })
+
+ it("drops the deferral without writing when the parent is readable and active at the retry", async () => {
+ const parent = makeItem({ id: "parent-active-later", status: "active" })
+ const child = makeItem({ id: "child-parent-active", status: "active", backgroundParentTaskId: parent.id })
+ await seedItems([parent, child])
+ makeParentUnreadable(parent.id)
+
+ await store.initialize()
+ expect(store.get(child.id)?.status).toBe("active")
+
+ restoreRealReads()
+ await store.reconcile()
+
+ expect(store.get(child.id)?.status).toBe("active")
+ const persisted = await readPersistedItem(path.join(tmpDir, "tasks"), child.id)
+ expect(persisted.status).toBe("active")
+
+ // The deferral was consumed: even if the parent later turns
+ // terminal, the child was left for normal lifecycle handling and a
+ // later pass must not resurrect the repair.
+ await fs.writeFile(
+ path.join(tmpDir, "tasks", parent.id, GlobalFileNames.historyItem),
+ JSON.stringify({ ...parent, status: "completed" }),
+ )
+ await store.reconcile()
+
+ expect(store.get(child.id)?.status).toBe("active")
+ })
+
+ it("drops the deferral without writing when the child is owned by the live host at the retry", async () => {
+ let live = false
+ store.dispose()
+ store = registerStore(new TaskHistoryStore(tmpDir, { isLiveBackgroundChild: () => live }))
+ const parent = makeItem({ id: "parent-live-later", status: "completed" })
+ const child = makeItem({ id: "child-live-later", status: "active", backgroundParentTaskId: parent.id })
+ await seedItems([parent, child])
+ makeParentUnreadable(parent.id)
+
+ await store.initialize()
+ expect(store.get(child.id)?.status).toBe("active")
+
+ live = true
+ restoreRealReads()
+ await store.reconcile()
+
+ expect(store.get(child.id)?.status).toBe("active")
+ const persisted = await readPersistedItem(path.join(tmpDir, "tasks"), child.id)
+ expect(persisted.status).toBe("active")
+ })
+
+ it("drops the deferral without writing when the child reached a terminal state before the retry", async () => {
+ const parent = makeItem({ id: "parent-child-terminal", status: "completed" })
+ const child = makeItem({ id: "child-terminal-later", status: "active", backgroundParentTaskId: parent.id })
+ await seedItems([parent, child])
+ makeParentUnreadable(parent.id)
+
+ await store.initialize()
+
+ // Another host completes the child while the parent stays unreadable.
+ await fs.writeFile(
+ path.join(tmpDir, "tasks", child.id, GlobalFileNames.historyItem),
+ JSON.stringify({ ...child, status: "completed" }),
+ )
+
+ await store.reconcile()
+
+ expect(store.get(child.id)?.status).toBe("completed")
+ const persisted = await readPersistedItem(path.join(tmpDir, "tasks"), child.id)
+ expect(persisted.status).toBe("completed")
+ })
+
+ it("does not recreate a deferred child deleted between the reconcile scan and the retry write", async () => {
+ const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {})
+ const parent = makeItem({ id: "parent-deferred-delete", status: "completed" })
+ const child = makeItem({
+ id: "child-deferred-delete",
+ status: "active",
+ backgroundParentTaskId: parent.id,
+ })
+ await seedItems([parent, child])
+ makeParentUnreadable(parent.id)
+
+ await store.initialize()
+
+ // Startup defers on the unreadable parent; the child stays active.
+ expect(store.get(child.id)?.status).toBe("active")
+
+ restoreRealReads()
+ const childFile = path.join(tmpDir, "tasks", child.id, GlobalFileNames.historyItem)
+ let repairAttempted = false
+ safeWriteJsonMock.mockImplementation(
+ withConcurrentMutation(async (filePath) => {
+ if (filePath === childFile) {
+ repairAttempted = true
+ // Another host deletes the child after the reconcile
+ // scan refreshed the cache but before the retry write.
+ await fs.rm(childFile, { force: true })
+ }
+ }),
+ )
+
+ await store.reconcile()
+
+ // The deferred repair ran against the deleted record and must not
+ // have recreated it.
+ expect(repairAttempted).toBe(true)
+ await expect(fs.access(childFile)).rejects.toThrow()
+ expect(store.get(child.id)).toBeUndefined()
+ // The deferral was dropped, not retried: a later pass must not
+ // attempt the repair again.
+ await store.reconcile()
+ await expect(fs.access(childFile)).rejects.toThrow()
+ expect(warnSpy).not.toHaveBeenCalledWith(
+ expect.stringContaining("Reconciled deferred orphaned background child"),
+ )
+ warnSpy.mockRestore()
+ })
+
+ it("does not overwrite a deferred child reassigned to a different parent before the retry write", async () => {
+ const parent = makeItem({ id: "parent-deferred-reassign", status: "completed" })
+ const child = makeItem({
+ id: "child-deferred-reassign",
+ status: "active",
+ backgroundParentTaskId: parent.id,
+ })
+ await seedItems([parent, child])
+ makeParentUnreadable(parent.id)
+
+ await store.initialize()
+ expect(store.get(child.id)?.status).toBe("active")
+
+ restoreRealReads()
+ const childFile = path.join(tmpDir, "tasks", child.id, GlobalFileNames.historyItem)
+ safeWriteJsonMock.mockImplementation(
+ withConcurrentMutation(async (filePath) => {
+ if (filePath === childFile) {
+ await writeJson(childFile, { ...child, backgroundParentTaskId: "parent-new-owner" })
+ }
+ }),
+ )
+
+ await store.reconcile()
+
+ const persisted = await readPersistedItem(path.join(tmpDir, "tasks"), child.id)
+ expect(persisted).toMatchObject({ status: "active", backgroundParentTaskId: "parent-new-owner" })
+ expect(store.get(child.id)).toMatchObject({ status: "active", backgroundParentTaskId: "parent-new-owner" })
+ })
+ })
+})
diff --git a/src/core/task-persistence/__tests__/taskLifecycle.backgroundChild.spec.ts b/src/core/task-persistence/__tests__/taskLifecycle.backgroundChild.spec.ts
new file mode 100644
index 0000000000..d0aa12b0f3
--- /dev/null
+++ b/src/core/task-persistence/__tests__/taskLifecycle.backgroundChild.spec.ts
@@ -0,0 +1,91 @@
+import type { HistoryItem } from "@roo-code/types"
+
+import { addBackgroundChild } from "../taskLifecycle"
+
+function item(id: string, overrides: Partial = {}): HistoryItem {
+ return {
+ id,
+ number: 1,
+ ts: 1,
+ task: id,
+ tokensIn: 0,
+ tokensOut: 0,
+ totalCost: 0,
+ status: "active",
+ ...overrides,
+ }
+}
+
+describe("addBackgroundChild", () => {
+ it("registers a child on a parent without childIds", () => {
+ const parent = item("parent")
+
+ expect(addBackgroundChild(parent, "child")).toMatchObject({
+ id: "parent",
+ childIds: ["child"],
+ })
+ })
+
+ it("appends a child while preserving existing entries", () => {
+ const parent = item("parent", { childIds: ["older"] })
+
+ expect(addBackgroundChild(parent, "child")).toMatchObject({
+ childIds: ["older", "child"],
+ })
+ })
+
+ it("is idempotent and returns the same reference when the child is already registered", () => {
+ const parent = item("parent", { childIds: ["child"] })
+
+ expect(addBackgroundChild(parent, "child")).toBe(parent)
+ })
+
+ it("does not mutate the input parent", () => {
+ const parent = item("parent", { childIds: ["older"] })
+ const snapshot = structuredClone(parent)
+
+ addBackgroundChild(parent, "child")
+
+ expect(parent).toEqual(snapshot)
+ })
+
+ it("never touches the delegation fields or the parent status", () => {
+ const parent = item("parent", { status: "delegated", awaitingChildId: "awaited", delegatedToId: "awaited" })
+
+ const registered = addBackgroundChild(parent, "background-child")
+
+ expect(registered.status).toBe("delegated")
+ expect(registered.awaitingChildId).toBe("awaited")
+ expect(registered.delegatedToId).toBe("awaited")
+ expect(registered.childIds).toEqual(["background-child"])
+ })
+
+ it("keeps the singular awaitingChildId invariant after registering many background children", () => {
+ let parent = item("parent", { status: "active" })
+
+ for (const childId of ["child-1", "child-2", "child-3", "child-4"]) {
+ parent = addBackgroundChild(parent, childId)
+ }
+
+ expect(parent.childIds).toEqual(["child-1", "child-2", "child-3", "child-4"])
+ expect(parent.awaitingChildId).toBeUndefined()
+ expect(parent.delegatedToId).toBeUndefined()
+ expect(parent.status).toBe("active")
+ })
+
+ it("registers a background child alongside an awaited delegated child without merging the two", () => {
+ const parent = item("parent", {
+ status: "delegated",
+ awaitingChildId: "delegated-child",
+ delegatedToId: "delegated-child",
+ childIds: ["delegated-child"],
+ })
+
+ const registered = addBackgroundChild(parent, "background-child")
+
+ expect(registered.childIds).toEqual(["delegated-child", "background-child"])
+ expect(registered.awaitingChildId).toBe("delegated-child")
+ expect(registered.delegatedToId).toBe("delegated-child")
+ expect(registered.status).toBe("delegated")
+ })
+})
diff --git a/src/core/task-persistence/taskLifecycle.ts b/src/core/task-persistence/taskLifecycle.ts
index b8a5e571f0..b2aab27d4c 100644
--- a/src/core/task-persistence/taskLifecycle.ts
+++ b/src/core/task-persistence/taskLifecycle.ts
@@ -130,3 +130,24 @@ export function abandonDelegatedChild(
},
}
}
+
+/**
+ * Registers a read-only background child in its parent's `childIds` (D10).
+ *
+ * A background child runs outside the delegation state machine: the parent's
+ * status and its singular `awaitingChildId` are deliberately left untouched,
+ * so the closed-world lifecycle model and every existing delegation test keep
+ * their meaning. Registration exists so the delete cascade, cost aggregation,
+ * and diagnostics see the child exactly as they see a delegated one.
+ *
+ * Idempotent: re-registering the same child is a no-op.
+ */
+export function addBackgroundChild(parent: HistoryItem, childId: string): HistoryItem {
+ if (parent.childIds?.includes(childId)) {
+ return parent
+ }
+ return {
+ ...parent,
+ childIds: Array.from(new Set([...(parent.childIds ?? []), childId])),
+ }
+}
diff --git a/src/core/task/Task.ts b/src/core/task/Task.ts
index 98b1e17737..5232611c31 100644
--- a/src/core/task/Task.ts
+++ b/src/core/task/Task.ts
@@ -29,6 +29,7 @@ import {
type ClineMessage,
type ClineSay,
type ClineAsk,
+ type ClineSayTool,
type ExtensionState,
type ToolProgressStatus,
type HistoryItem,
@@ -94,6 +95,7 @@ import { OutputInterceptor } from "../../integrations/terminal/OutputInterceptor
// utils
import { calculateApiCostAnthropic, calculateApiCostOpenAI } from "../../shared/cost"
import { getWorkspacePath } from "../../utils/path"
+import { isRealPathOutsideWorkspace } from "../../utils/pathUtils"
import { sanitizeToolUseId } from "../../utils/tool-id"
import { getTaskDirectoryPath } from "../../utils/storage"
@@ -141,6 +143,7 @@ import { expandUserMentions, wrapUserMessage } from "../mentions/processUserCont
import { getMessagesSinceLastSummary, summarizeConversation, getEffectiveApiHistory } from "../condense"
import { MessageQueueService } from "../message-queue/MessageQueueService"
import { type AutoDenyDetail, AutoApprovalHandler, checkAutoApproval } from "../auto-approval"
+import { isReadOnlyToolAction } from "../auto-approval/tools"
import { MessageManager } from "../message-manager"
import { validateAndFixToolResultIds } from "./validateToolResultIds"
import { mergeConsecutiveApiMessages } from "./mergeConsecutiveApiMessages"
@@ -155,6 +158,7 @@ import {
isDivergenceCheckEnabled,
reportDivergence,
} from "./run-state/runStateDivergence"
+import { mergeBackgroundToolPolicy } from "../background-subtasks/policy"
const MAX_EXPONENTIAL_BACKOFF_SECONDS = 600 // 10 minutes
const DEFAULT_USAGE_COLLECTION_TIMEOUT_MS = 5000 // 5 seconds
@@ -218,6 +222,60 @@ export function isBlanketDenyEngaged(
)
}
+/**
+ * D4 read carve-out: parse a background child's tool ask text and, only when it
+ * names a read-only tool, return the parsed ask so the caller can apply the
+ * outside-workspace gate (M-1). The ask text for a tool is the say-tool JSON
+ * (e.g. {"tool":"readFile","path":"..."}); anything unparseable, non-object,
+ * lacking a string `tool` field, or naming a non-read-only tool returns
+ * undefined (fail closed) so the caller keeps the auto-deny.
+ *
+ * A batch read ask names no top-level `path`: every target lives in
+ * `batchFiles` (ReadFileTool's batch approval shape). Each batch entry must
+ * carry a non-empty string `path`, and the returned `paths` list holds every
+ * target so the caller gates each one. A batch whose entries are not all
+ * verifiable (a non-array `batchFiles`, or any entry lacking a non-empty
+ * string `path`) returns undefined (fail closed): an unverifiable target must
+ * not be silently skipped, or it would ride an approved batch past the gate.
+ * A read-only ask with neither `path` nor `batchFiles` returns an empty
+ * `paths` list and stays approved.
+ */
+function parseReadOnlyBackgroundChildToolAsk(text?: string): { tool: string; paths: string[] } | undefined {
+ if (!text) {
+ return undefined
+ }
+ try {
+ const parsed = JSON.parse(text) as { tool?: unknown; path?: unknown; batchFiles?: unknown }
+ if (typeof parsed?.tool !== "string") {
+ return undefined
+ }
+ // Single construction-site cast: the ask text is untrusted JSON, so the
+ // tool field is only known to be a string here; isReadOnlyToolAction
+ // membership-tests it against the read-only set.
+ if (!isReadOnlyToolAction({ tool: parsed.tool } as ClineSayTool)) {
+ return undefined
+ }
+ if (parsed.batchFiles !== undefined) {
+ if (!Array.isArray(parsed.batchFiles)) {
+ return undefined
+ }
+ const paths: string[] = []
+ for (const entry of parsed.batchFiles) {
+ const candidate = (entry as { path?: unknown } | null)?.path
+ if (typeof candidate !== "string" || candidate.length === 0) {
+ return undefined
+ }
+ paths.push(candidate)
+ }
+ return { tool: parsed.tool, paths }
+ }
+ const path = parsed.path
+ return { tool: parsed.tool, paths: typeof path === "string" && path.length > 0 ? [path] : [] }
+ } catch {
+ return undefined
+ }
+}
+
function queuedResponseForAsk(type: ClineAsk, text?: string): QueuedAskResolution | undefined {
if (type === "command_output") {
return undefined
@@ -244,6 +302,15 @@ function queuedResponseForAsk(type: ClineAsk, text?: string): QueuedAskResolutio
const FORCED_CONTEXT_REDUCTION_PERCENT = 75 // Keep 75% of context (remove 25%) on context window errors
const MAX_CONTEXT_WINDOW_RETRIES = 3 // Maximum retries for context window errors
+/**
+ * P1-1: maximum automatic retries for a LIVE background child across the three
+ * retry paths that never increment `consecutiveMistakeCount` (empty assistant
+ * response, mid-stream failure, first-chunk failure). Without a bound a
+ * persistently failing model loops forever, hangs the parent's join, and holds
+ * the scheduler permit. Normal tasks are unaffected: the counter only advances
+ * for `isBackgroundSubtaskChild`, so they keep their existing unbounded retries.
+ */
+const MAX_BACKGROUND_CHILD_RETRY_ATTEMPTS = 3
export interface ToolExecutionContext {
toolCallId: string
@@ -264,6 +331,16 @@ export interface TaskOptions extends CreateTaskOptions {
experiments?: Record
startTask?: boolean
rootTask?: Task
+ /**
+ * Authoritative root task id for a new task whose root TASK OBJECT is not
+ * live (e.g. a history-restored task whose root survives only as a stored
+ * id): stamping it here keeps a child spawned by such a task under the
+ * original root instead of inheriting the spawner's id. When provided it
+ * wins over the id derived from `rootTask`; when absent the `rootTask`
+ * derivation is kept. Ignored for a history-restored task, which keeps its
+ * stored rootTaskId.
+ */
+ rootTaskId?: string
parentTask?: Task
taskNumber?: number
onCreated?: (task: Task) => void
@@ -275,6 +352,22 @@ export interface TaskOptions extends CreateTaskOptions {
diffFuzzyThreshold?: number
/** Explicit task-local execution context for a delegated child. */
handoffExecutionContext?: TaskExecutionContext
+ /**
+ * Task-local tool policy for a background (read-only) child task. It is never
+ * set for a normal or serially-delegated task. Presence keeps the task
+ * read-only at the tool and prompt layers, including for a history-restored
+ * child (F-05), but on its own does NOT make the task a non-interactive
+ * background child — that is `backgroundChildHosted`.
+ */
+ backgroundToolPolicy?: { disabledTools?: readonly string[]; experiments?: Record }
+ /**
+ * Set only by the spawn path (`ClineProvider.spawnBackgroundChildren`) to mark
+ * a LIVE background child hosted off the task stack. `isBackgroundSubtaskChild`
+ * derives from this flag, NOT from `backgroundToolPolicy` presence, so a
+ * history-restored child keeps its read-only policy yet stays interactive
+ * (P1-2). A normal or serially-delegated task never sets it.
+ */
+ backgroundChildHosted?: boolean
}
type AssistantMessagePersistenceResult = boolean
@@ -312,6 +405,20 @@ export class Task extends EventEmitter implements TaskLike {
readonly taskNumber: number
readonly workspacePath: string
+ /**
+ * True when this task is a LIVE background child hosted off the stack (see
+ * TaskOptions.backgroundChildHosted): it runs beside the current task, so it
+ * must stay non-interactive and keep its chat activity off the webview. Webview
+ * state posts always carry the CURRENT task's messages, never this child's, so
+ * posting here would render the child's stream in the current task's view (the
+ * parent renders one parallelSubtasks panel row instead). The child's messages
+ * still persist to its own task directory, which is what the panel's debug-log
+ * button opens. A history-restored child is NOT flagged (it is the current task
+ * and stays interactive) even though it keeps its read-only
+ * `backgroundToolPolicy` (P1-2).
+ */
+ readonly isBackgroundSubtaskChild: boolean
+
/**
* The mode associated with this task. Persisted across sessions
* to maintain user context when reopening tasks from history.
@@ -493,6 +600,14 @@ export class Task extends EventEmitter implements TaskLike {
consecutiveMistakeCountForEditFile: Map = new Map()
consecutiveNoToolUseCount: number = 0
consecutiveNoAssistantMessagesCount: number = 0
+ /**
+ * P1-1: automatic retries a LIVE background child has taken across the three
+ * retry paths that bypass `consecutiveMistakeCount` (empty assistant response,
+ * mid-stream failure, first-chunk failure). Advances only for
+ * `isBackgroundSubtaskChild`; a normal task never touches it, so its retries
+ * stay unbounded. On exceed the child terminates like the mistake-limit path.
+ */
+ backgroundChildRetryCount: number = 0
toolUsage: ToolUsage = {}
// Conversation message counts, summarized once per Task Completed
@@ -567,6 +682,13 @@ export class Task extends EventEmitter implements TaskLike {
*/
private requestPolicySnapshot?: RequestPolicySnapshot
+ /**
+ * Task-local tool policy for a background child (design D3). Folded into the
+ * per-request policy snapshot at capture time; never written to provider or
+ * global state, so concurrent tasks cannot observe or leak it.
+ */
+ private readonly backgroundToolPolicy?: { disabledTools?: readonly string[]; experiments?: Record }
+
/**
* Fire-and-forget wrapper around `presentAssistantMessage` that swallows the
* expected cancellation rejection (the presenter throws when `this.abort` is set)
@@ -725,6 +847,7 @@ export class Task extends EventEmitter implements TaskLike {
experiments: _experimentsConfig,
startTask = true,
rootTask,
+ rootTaskId,
parentTask,
taskNumber = -1,
onCreated,
@@ -734,6 +857,8 @@ export class Task extends EventEmitter implements TaskLike {
rateLimitClock,
diffFuzzyThreshold,
handoffExecutionContext,
+ backgroundToolPolicy,
+ backgroundChildHosted,
}: TaskOptions) {
super()
this.segments = segments
@@ -759,7 +884,7 @@ export class Task extends EventEmitter implements TaskLike {
}
this.taskId = historyItem ? historyItem.id : (taskId ?? uuidv7())
- this.rootTaskId = historyItem ? historyItem.rootTaskId : rootTask?.taskId
+ this.rootTaskId = historyItem ? historyItem.rootTaskId : (rootTaskId ?? rootTask?.taskId)
this.parentTaskId = historyItem ? historyItem.parentTaskId : parentTask?.taskId
this.childTaskId = undefined
@@ -806,6 +931,11 @@ export class Task extends EventEmitter implements TaskLike {
this.taskNumber = taskNumber
this.initialStatus = initialStatus ?? historyItem?.status
this.pendingAction = historyItem?.pendingAction
+ this.backgroundToolPolicy = backgroundToolPolicy
+ // P1-2: the non-interactive background-child mode is carried by the hosted
+ // flag (spawn path only), NOT by policy presence, so a history-restored
+ // child keeps its read-only policy but stays interactive.
+ this.isBackgroundSubtaskChild = backgroundChildHosted === true
// Store the task's mode and API config name when it's created.
// For history items, use the stored values; for new tasks, we'll set them
@@ -838,12 +968,19 @@ export class Task extends EventEmitter implements TaskLike {
this.messageQueueStateChangedHandler = () => {
this.emit(RooCodeEventName.TaskUserMessage, this.taskId)
this.emit(RooCodeEventName.QueuedMessagesUpdated, this.taskId, this.messageQueueService.messages)
- void this.providerRef
- .deref()
- ?.postStateToWebviewThrottled()
- .catch((error) => {
- console.error("[Task#messageQueueStateChangedHandler] postStateToWebviewThrottled failed:", error)
- })
+ // A background child's queue activity must stay off the webview (same
+ // clobbering hazard as addToClineMessages); the events above still fire.
+ if (!this.isBackgroundSubtaskChild) {
+ void this.providerRef
+ .deref()
+ ?.postStateToWebviewThrottled()
+ .catch((error) => {
+ console.error(
+ "[Task#messageQueueStateChangedHandler] postStateToWebviewThrottled failed:",
+ error,
+ )
+ })
+ }
}
this.messageQueueService.on("stateChanged", this.messageQueueStateChangedHandler)
@@ -1714,16 +1851,22 @@ export class Task extends EventEmitter implements TaskLike {
// Partial *asks* still flush, via the clause below — `Task#ask` adds them without
// `isAnswered`, so they keep the ordering guarantee that unanswered asks depend on.
const requiresImmediateState = message.type === "ask" && message.isAnswered !== true
- try {
- await provider?.postStateToWebviewThrottled()
- } catch (error) {
- console.error("[Task#addToClineMessages] postStateToWebviewThrottled failed:", error)
- }
- if (requiresImmediateState) {
+ // A background child's chat must stay off the webview: its state post would
+ // carry the child's clineMessages into the webview, which renders the CURRENT
+ // task, clobbering the parent's chat. Persistence and the Message emit below
+ // still run, so the child's log stays complete in its own task directory.
+ if (!this.isBackgroundSubtaskChild) {
try {
- await provider?.flushPostStateToWebviewThrottled()
+ await provider?.postStateToWebviewThrottled()
} catch (error) {
- console.error("[Task#addToClineMessages] flushPostStateToWebviewThrottled failed:", error)
+ console.error("[Task#addToClineMessages] postStateToWebviewThrottled failed:", error)
+ }
+ if (requiresImmediateState) {
+ try {
+ await provider?.flushPostStateToWebviewThrottled()
+ } catch (error) {
+ console.error("[Task#addToClineMessages] flushPostStateToWebviewThrottled failed:", error)
+ }
}
}
this.emit(RooCodeEventName.Message, { action: "created", message })
@@ -1837,7 +1980,12 @@ export class Task extends EventEmitter implements TaskLike {
private async updateClineMessage(message: ClineMessage) {
const provider = this.providerRef.deref()
- await provider?.postMessageToWebview({ type: "messageUpdated", clineMessage: message })
+ // A background child's messageUpdated must stay off the webview: the webview
+ // renders the CURRENT task's messages, so a child ts would corrupt the
+ // parent's chat. The Message emit below still runs.
+ if (!this.isBackgroundSubtaskChild) {
+ await provider?.postMessageToWebview({ type: "messageUpdated", clineMessage: message })
+ }
this.emit(RooCodeEventName.Message, { action: "updated", message })
// Check if we should sync to cloud and haven't already synced this message
@@ -1907,7 +2055,19 @@ export class Task extends EventEmitter implements TaskLike {
const provider = this.providerRef.deref()
const existingStatus = provider?.taskHistoryStore.get(this.taskId)?.status
- await provider?.updateTaskHistory(existingStatus ? { ...historyItem, status: existingStatus } : historyItem)
+ // M-2: re-assert the background-parent stamp on the child's own
+ // history write. The spawn-time upsert (registerBackgroundChild) is
+ // best-effort, so a transient store failure could otherwise leave the
+ // child unstamped and a later restore would treat it as a normal task
+ // (fully privileged). The child already holds the parent id in memory,
+ // so every save makes the stamp durable.
+ const persistedItem =
+ this.isBackgroundSubtaskChild && this.parentTaskId
+ ? { ...historyItem, backgroundParentTaskId: this.parentTaskId }
+ : historyItem
+ await provider?.updateTaskHistory(
+ existingStatus ? { ...persistedItem, status: existingStatus } : persistedItem,
+ )
} catch (error) {
// The message array was persisted above; a metadata or task-history failure must
// not mask that write (see the method docs). The next saveClineMessages() call
@@ -1928,6 +2088,124 @@ export class Task extends EventEmitter implements TaskLike {
return undefined
}
+ /**
+ * Folds a background child's task-local policy into the ambient provider
+ * state. A task with no `backgroundToolPolicy` (a normal task and a
+ * serially-delegated task) gets the state values back untouched (same
+ * references, `undefined` preserved) so this seam is a no-op for it; any task
+ * carrying the policy — a LIVE background child or a history-restored one
+ * (P1-2) — gets a fresh union that is at least as restrictive as the user's
+ * global policy and is never aliased to provider state.
+ */
+ private effectiveToolPolicy(state?: { disabledTools?: string[]; experiments?: Record }): {
+ disabledTools: string[] | undefined
+ experiments: Record | undefined
+ } {
+ if (!this.backgroundToolPolicy) {
+ return { disabledTools: state?.disabledTools, experiments: state?.experiments }
+ }
+ const merged = mergeBackgroundToolPolicy(this.backgroundToolPolicy, state)
+ return { disabledTools: merged.disabledTools, experiments: merged.experiments }
+ }
+
+ /**
+ * P1-1: record one automatic retry for a LIVE background child and terminate
+ * the run once the retry bound is exceeded. The three retry paths that call
+ * this (empty assistant response, mid-stream failure, first-chunk failure)
+ * never increment `consecutiveMistakeCount`, so a persistently failing model
+ * would otherwise retry forever: the run never settles, the parent's
+ * `Promise.all(handles.map(h => h.done))` join hangs, and the scheduler
+ * permit is held while every retry issues a fresh API request. No-op for a
+ * normal task. On exceed this mirrors the mistake-limit terminal
+ * (`requestAbort(true)` + throw): the throw propagates out of the request
+ * loop and is swallowed by startTask's abandoned/abort catch, so `run()`
+ * settles and the host's run-settled catch-all settles the child handle as
+ * failed and releases the permit.
+ */
+ private noteBackgroundChildRetry(): void {
+ if (!this.isBackgroundSubtaskChild) {
+ return
+ }
+ this.backgroundChildRetryCount++
+ if (this.backgroundChildRetryCount > MAX_BACKGROUND_CHILD_RETRY_ATTEMPTS) {
+ this.requestAbort(true)
+ throw new Error(
+ `[RooCode#Task] background child task ${this.taskId}.${this.instanceId} exceeded the automatic retry limit (${MAX_BACKGROUND_CHILD_RETRY_ATTEMPTS})`,
+ )
+ }
+ }
+
+ /**
+ * D4 policy for background children: when the auto-approval decision is
+ * `ask`, a background child must never post a chat row and wait for a user
+ * click. Resolve the ask deterministically by type instead: read-only tool
+ * asks approve (design D4 scopes the auto-deny to "tool(읽기 외 전부)" —
+ * the user already approved the parallel_subtasks call that spawned this
+ * child, design §11, and the child's structural tool policy already blocks
+ * every dangerous tool), every other tool ask and every non-tool ask type
+ * fails closed. A read carve-out is only granted when every read target
+ * stays inside the workspace (M-1), checked canonically: each ask path —
+ * the single `path` value or every `batchFiles[].path` entry of a batch
+ * read — is resolved against the task cwd and the realpath of the target
+ * must sit under the realpath of a workspace root, so a workspace symlink
+ * cannot smuggle an outside file past a lexical containment check. A batch
+ * is denied when ANY of its targets escapes. Returns undefined for
+ * non-background tasks and for auto-answered asks, so the normal
+ * interactive flow is untouched.
+ */
+ private async resolveBackgroundChildAsk(
+ type: ClineAsk,
+ approval: { decision: "ask" },
+ text?: string,
+ ): Promise<{ response: ClineAskResponse; text?: string; autoDenyDetail?: AutoDenyDetail } | undefined> {
+ if (!this.isBackgroundSubtaskChild || approval.decision !== "ask") {
+ return undefined
+ }
+ if (type === "tool") {
+ const readOnlyAsk = parseReadOnlyBackgroundChildToolAsk(text)
+ // M-1: the read carve-out must still respect the outside-workspace
+ // gate, otherwise a prompt-injected child could read e.g.
+ // ~/.ssh/id_rsa under default settings and land it in a workspace
+ // report. A batch read ask carries its targets in `batchFiles` and
+ // no top-level `path`, so the gate must run on EVERY batch entry:
+ // one outside target denies the whole ask, and the parse step
+ // already failed closed on any entry whose path is not verifiable.
+ // Each target is resolved against the task cwd and compared
+ // canonically (realpath of the target vs realpath of each workspace
+ // root): a workspace symlink such as `private-link` would pass a
+ // lexical check while ReadFileTool reads its outside-workspace
+ // target. Fail closed (keep the auto-deny) when any target escapes
+ // the workspace or cannot be resolved. Read-only asks with no path
+ // and no batchFiles stay approved.
+ let pathOutsideWorkspace = false
+ if (readOnlyAsk) {
+ for (const candidate of readOnlyAsk.paths) {
+ if (await isRealPathOutsideWorkspace(path.resolve(this.cwd, candidate))) {
+ pathOutsideWorkspace = true
+ }
+ }
+ }
+ if (readOnlyAsk && !pathOutsideWorkspace) {
+ return { response: "yesButtonClicked" }
+ }
+ const autoDenyDetail: AutoDenyDetail = { kind: "background_policy" }
+ // Route the presenter through the structured auto-deny path (mirroring
+ // the deny branch of ask): the tool result must read as a policy
+ // denial scoped to this tool call, not as a user rejection.
+ this.pendingAutoDenyDetail = autoDenyDetail
+ return { response: "noButtonClicked", autoDenyDetail }
+ }
+ // followup, api_req_failed, mistake_limit_reached, and every other ask
+ // type resolve to noButtonClicked. That answer feeds each type's
+ // existing non-approval handling: for a background child the
+ // mistake_limit_reached path is terminal (recursivelyMakeClineRequests
+ // ends the run loop), and completion_result is intercepted earlier by
+ // AttemptCompletionTool (Phase 2) — denying it here is the correct
+ // fail-closed default should it ever reach this seam. The host settles
+ // the child handle when the run settles without a terminal entry.
+ return { response: "noButtonClicked" }
+ }
+
// Note that `partial` has three valid states true (partial message),
// false (completion of partial message), undefined (individual complete
// message).
@@ -2027,6 +2305,34 @@ export class Task extends EventEmitter implements TaskLike {
throw new Error(`[RooCode#ask] task ${this.taskId}.${this.instanceId} aborted`)
}
+ // D4: a background child never blocks on a user. Resolve an unresolved
+ // policy decision deterministically before any chat row is posted, and
+ // release a claimed queued message so the early return cannot strand it.
+ const backgroundAskResolution = await this.resolveBackgroundChildAsk(
+ type,
+ approval as { decision: "ask" },
+ text,
+ )
+ if (backgroundAskResolution) {
+ // Recheck cancellation after the resolution's awaits: the M-1 gate
+ // lookups (`isRealPathOutsideWorkspace`) can outlive the pre-await
+ // check above, and an abort landing while one is pending must not
+ // still return an approval (or a denial) for a cancelled task. The
+ // interactive path rechecks after its wait the same way (Task.ts
+ // pWaitFor settle). Release the queued message and fail closed like
+ // the other abort paths.
+ if (this.abort) {
+ if (queuedMessage) {
+ this.messageQueueService.releaseMessage(queuedMessage.id)
+ }
+ throw new Error(`[RooCode#ask] task ${this.taskId}.${this.instanceId} aborted`)
+ }
+ if (queuedMessage) {
+ this.messageQueueService.releaseMessage(queuedMessage.id)
+ }
+ return backgroundAskResolution
+ }
+
if (partial !== undefined) {
const lastMessage = this.clineMessages.at(-1)
@@ -2754,14 +3060,15 @@ export class Task extends EventEmitter implements TaskLike {
const provider = this.providerRef.deref()
let allTools: import("openai").default.Chat.ChatCompletionTool[] = []
if (provider) {
+ const effectivePolicy = this.effectiveToolPolicy(state)
const toolsResult = await buildNativeToolsArrayWithRestrictions({
provider,
cwd: this.cwd,
mode,
customModes: state?.customModes,
- experiments: state?.experiments,
+ experiments: effectivePolicy.experiments,
apiConfiguration,
- disabledTools: state?.disabledTools,
+ disabledTools: effectivePolicy.disabledTools,
modelInfo: requestModelInfo,
includeAllToolsWithRestrictions: false,
})
@@ -2857,6 +3164,12 @@ export class Task extends EventEmitter implements TaskLike {
this.processQueuedMessages()
}
+ /**
+ * Posts a say row. Returns the exact `ClineMessage` that was appended or
+ * updated so callers can keep updating it by identity: the row is pushed
+ * before persistence awaits complete, so `clineMessages.at(-1)` is not a
+ * safe way to recover it (another say can append its own row meanwhile).
+ */
async say(
type: ClineSay,
text?: string,
@@ -2869,7 +3182,7 @@ export class Task extends EventEmitter implements TaskLike {
} = {},
contextCondense?: ContextCondense,
contextTruncation?: ContextTruncation,
- ): Promise {
+ ): Promise {
if (this.abort) {
throw new Error(`[RooCode#say] task ${this.taskId}.${this.instanceId} aborted`)
}
@@ -2888,6 +3201,7 @@ export class Task extends EventEmitter implements TaskLike {
lastMessage.partial = partial
lastMessage.progressStatus = progressStatus
this.postPartialMessageUpdate(lastMessage, "say")
+ return lastMessage
} else {
// This is a new partial message, so add it with partial state.
const sayTs = Date.now()
@@ -2896,7 +3210,7 @@ export class Task extends EventEmitter implements TaskLike {
this.lastMessageTs = sayTs
}
- await this.addToClineMessages({
+ const message: ClineMessage = {
ts: sayTs,
type: "say",
say: type,
@@ -2905,7 +3219,9 @@ export class Task extends EventEmitter implements TaskLike {
partial,
contextCondense,
contextTruncation,
- })
+ }
+ await this.addToClineMessages(message)
+ return message
}
} else {
// New now have a complete version of a previously partial message.
@@ -2932,6 +3248,7 @@ export class Task extends EventEmitter implements TaskLike {
this.updateClineMessage(lastMessage).catch((error) => {
console.error("[Task#say] updateClineMessage failed:", error)
})
+ return lastMessage
} else {
// This is a new and complete message, so add it like normal.
const sayTs = Date.now()
@@ -2940,7 +3257,7 @@ export class Task extends EventEmitter implements TaskLike {
this.lastMessageTs = sayTs
}
- await this.addToClineMessages({
+ const message: ClineMessage = {
ts: sayTs,
type: "say",
say: type,
@@ -2948,7 +3265,9 @@ export class Task extends EventEmitter implements TaskLike {
images,
contextCondense,
contextTruncation,
- })
+ }
+ await this.addToClineMessages(message)
+ return message
}
}
} else {
@@ -2963,7 +3282,7 @@ export class Task extends EventEmitter implements TaskLike {
this.lastMessageTs = sayTs
}
- await this.addToClineMessages({
+ const message: ClineMessage = {
ts: sayTs,
type: "say",
say: type,
@@ -2972,7 +3291,9 @@ export class Task extends EventEmitter implements TaskLike {
checkpoint,
contextCondense,
contextTruncation,
- })
+ }
+ await this.addToClineMessages(message)
+ return message
}
}
@@ -3138,7 +3459,11 @@ export class Task extends EventEmitter implements TaskLike {
// The todo list is already set in the constructor if initialTodos were provided
// No need to add any messages - the todoList property is already set
- await this.providerRef.deref()?.postStateToWebviewWithoutTaskHistory()
+ // A background child posts nothing to the webview (design letter): the
+ // state it would post is the current task's, never the child's.
+ if (!this.isBackgroundSubtaskChild) {
+ await this.providerRef.deref()?.postStateToWebviewWithoutTaskHistory()
+ }
await this.say("text", task, images)
@@ -3695,13 +4020,16 @@ export class Task extends EventEmitter implements TaskLike {
// Force final token usage update before abort event
this.emitFinalTokenUsageUpdate()
- try {
- await this.providerRef.deref()?.flushPostStateToWebviewThrottled()
- } catch (error) {
- console.error(
- `[Task#abortTask] flushPostStateToWebviewThrottled failed for ${this.taskId}.${this.instanceId}:`,
- error,
- )
+ // A background child posts nothing to the webview (design letter).
+ if (!this.isBackgroundSubtaskChild) {
+ try {
+ await this.providerRef.deref()?.flushPostStateToWebviewThrottled()
+ } catch (error) {
+ console.error(
+ `[Task#abortTask] flushPostStateToWebviewThrottled failed for ${this.taskId}.${this.instanceId}:`,
+ error,
+ )
+ }
}
this.emit(RooCodeEventName.TaskAborted)
@@ -4066,6 +4394,24 @@ export class Task extends EventEmitter implements TaskLike {
t("common:errors.mistake_limit_guidance"),
)
+ if (this.isBackgroundSubtaskChild) {
+ // D4/§8: the ask above resolved by policy (a background child
+ // never waits for a user), and retrying the same content would
+ // hit the same validation/execution failures, so the
+ // consecutive mistake limit is terminal for a background
+ // child. requestAbort(true) sets the abandoned/abort latches
+ // (mirroring the D5 path in AttemptCompletionTool), so this
+ // throw — like the loop's own abort-guard throw — is swallowed
+ // by startTask's catch and run() settles; the host's
+ // run-settled catch-all then settles the child handle as
+ // failed. abortTask() is not used: its TaskAborted emit would
+ // overwrite that terminal status.
+ this.requestAbort(true)
+ throw new Error(
+ `[RooCode#recursivelyMakeRooRequests] background child task ${this.taskId}.${this.instanceId} reached the consecutive mistake limit`,
+ )
+ }
+
if (response === "messageResponse") {
currentUserContent.push(
...[
@@ -4161,7 +4507,11 @@ export class Task extends EventEmitter implements TaskLike {
} satisfies ClineApiReqInfo)
await this.saveClineMessages()
- await this.providerRef.deref()?.postStateToWebviewWithoutTaskHistory()
+ // A background child posts nothing to the webview (design letter); its
+ // messages persist to its own task directory regardless.
+ if (!this.isBackgroundSubtaskChild) {
+ await this.providerRef.deref()?.postStateToWebviewWithoutTaskHistory()
+ }
try {
let cacheWriteTokens = 0
@@ -4869,6 +5219,11 @@ export class Task extends EventEmitter implements TaskLike {
}
}
+ // P1-1: this unconditional re-push is an unbounded retry path
+ // (reached with and without auto-approval), so bound it for a
+ // background child. No-op for a normal task.
+ this.noteBackgroundChildRetry()
+
// Push the same content back onto the stack to retry, incrementing the retry attempt counter
stack.push({
userContent: currentUserContent,
@@ -5028,7 +5383,10 @@ export class Task extends EventEmitter implements TaskLike {
}
await this.saveClineMessages()
- await this.providerRef.deref()?.postStateToWebviewWithoutTaskHistory()
+ // A background child posts nothing to the webview (design letter).
+ if (!this.isBackgroundSubtaskChild) {
+ await this.providerRef.deref()?.postStateToWebviewWithoutTaskHistory()
+ }
// No legacy text-stream tool parser state to reset.
@@ -5272,6 +5630,12 @@ export class Task extends EventEmitter implements TaskLike {
// Increment consecutive no-assistant-messages counter
this.consecutiveNoAssistantMessagesCount++
+ // P1-1: an empty assistant response always leads to another attempt
+ // (auto-approval re-pushes here; a background child's denied ask
+ // falls through to the outer noToolsUsed nudge), so it is one of the
+ // unbounded retry paths this bound exists for. No-op for normal tasks.
+ this.noteBackgroundChildRetry()
+
// Only show error and count toward mistake limit after 2 consecutive failures
// This provides a "grace retry" - first failure retries silently
if (this.consecutiveNoAssistantMessagesCount >= 2) {
@@ -5437,8 +5801,14 @@ export class Task extends EventEmitter implements TaskLike {
const rooIgnoreInstructions = this.rooIgnoreController?.getInstructions()
- const { customModes, customModePrompts, customInstructions, experiments, language, enableSubfolderRules } =
+ const { customModes, customModePrompts, customInstructions, language, enableSubfolderRules } =
requestState ?? {}
+ // Fold the background child's task-local policy into the same snapshot
+ // the request's tool arrays were built from (the tool-array sites all call
+ // effectiveToolPolicy(state)), so the child's prompt never advertises a
+ // tool the runtime blocks and never hides a callable one. No-op for a
+ // non-background task.
+ const effectivePolicy = this.effectiveToolPolicy(requestState)
// Use task-local values, not provider state, to prevent cross-task configuration leaks.
const mode = await this.getTaskMode()
const apiConfiguration = this.apiConfiguration
@@ -5465,7 +5835,7 @@ export class Task extends EventEmitter implements TaskLike {
customModePrompts,
customModes,
customInstructions,
- experiments,
+ effectivePolicy.experiments,
language,
rooIgnoreInstructions,
{
@@ -5481,7 +5851,7 @@ export class Task extends EventEmitter implements TaskLike {
undefined, // todoList
this.api.getModel().id,
provider.getSkillsManager(),
- requestState?.disabledTools,
+ effectivePolicy.disabledTools,
modelInfo,
)
})()
@@ -5642,20 +6012,26 @@ export class Task extends EventEmitter implements TaskLike {
`Forcing truncation to ${FORCED_CONTEXT_REDUCTION_PERCENT}% of current context.`,
)
// Send condenseTaskContextStarted to show in-progress indicator
- await this.providerRef.deref()?.postMessageToWebview({ type: "condenseTaskContextStarted", text: this.taskId })
+ // A background child's condense spinner must not appear in the parent's chat.
+ if (!this.isBackgroundSubtaskChild) {
+ await this.providerRef
+ .deref()
+ ?.postMessageToWebview({ type: "condenseTaskContextStarted", text: this.taskId })
+ }
// Build tools for condensing metadata (same tools used for normal API calls)
const provider = this.providerRef.deref()
let allTools: import("openai").default.Chat.ChatCompletionTool[] = []
if (provider) {
+ const effectivePolicy = this.effectiveToolPolicy(state)
const toolsResult = await buildNativeToolsArrayWithRestrictions({
provider,
cwd: this.cwd,
mode,
customModes: state?.customModes,
- experiments: state?.experiments,
+ experiments: effectivePolicy.experiments,
apiConfiguration,
- disabledTools: state?.disabledTools,
+ disabledTools: effectivePolicy.disabledTools,
modelInfo,
includeAllToolsWithRestrictions: false,
})
@@ -5715,9 +6091,12 @@ export class Task extends EventEmitter implements TaskLike {
} finally {
// Notify webview that context management is complete (removes in-progress spinner)
// IMPORTANT: Must always be sent to dismiss the spinner, even on error
- await this.providerRef
- .deref()
- ?.postMessageToWebview({ type: "condenseTaskContextResponse", text: this.taskId })
+ // A background child has no spinner in the parent's chat, so nothing to dismiss.
+ if (!this.isBackgroundSubtaskChild) {
+ await this.providerRef
+ .deref()
+ ?.postMessageToWebview({ type: "condenseTaskContextResponse", text: this.taskId })
+ }
}
}
@@ -5821,10 +6200,13 @@ export class Task extends EventEmitter implements TaskLike {
// awaits above, so the streaming presenter of this request validates
// against exactly the policy its prompt advertised. The generator body
// re-executes per retry, so each attempt re-captures before its stream
- // can present anything.
+ // can present anything. A background child folds its task-local policy
+ // into the same snapshot the prompt was built from, so the prompt layer
+ // and the streaming validator cannot disagree about the child's tools.
+ const effectivePolicy = this.effectiveToolPolicy(state)
this.requestPolicySnapshot = {
- disabledTools: state?.disabledTools,
- experiments: state?.experiments,
+ disabledTools: effectivePolicy.disabledTools,
+ experiments: effectivePolicy.experiments,
customModes: state?.customModes,
modelInfo: requestModelInfo,
}
@@ -5886,7 +6268,8 @@ export class Task extends EventEmitter implements TaskLike {
// Send condenseTaskContextStarted BEFORE manageContext to show in-progress indicator
// This notification must be sent here (not earlier) because the early check uses stale token count
// (before user message is added to history), which could incorrectly skip showing the indicator
- if (contextManagementWillRun && autoCondenseContext) {
+ // A background child's condense spinner must not appear in the parent's chat.
+ if (contextManagementWillRun && autoCondenseContext && !this.isBackgroundSubtaskChild) {
await this.providerRef
.deref()
?.postMessageToWebview({ type: "condenseTaskContextStarted", text: this.taskId })
@@ -5898,14 +6281,15 @@ export class Task extends EventEmitter implements TaskLike {
{
const provider = this.providerRef.deref()
if (provider) {
+ const effectivePolicy = this.effectiveToolPolicy(state)
const toolsResult = await buildNativeToolsArrayWithRestrictions({
provider,
cwd: this.cwd,
mode,
customModes: state?.customModes,
- experiments: state?.experiments,
+ experiments: effectivePolicy.experiments,
apiConfiguration,
- disabledTools: state?.disabledTools,
+ disabledTools: effectivePolicy.disabledTools,
modelInfo: requestModelInfo,
includeAllToolsWithRestrictions: false,
})
@@ -5973,7 +6357,8 @@ export class Task extends EventEmitter implements TaskLike {
// Notify webview that context management is complete (sets isCondensing = false)
// This removes the in-progress spinner and allows the completed result to show
// IMPORTANT: Must always be sent to dismiss the spinner, even on error
- if (contextManagementWillRun && autoCondenseContext) {
+ // A background child has no spinner in the parent's chat, so nothing to dismiss.
+ if (contextManagementWillRun && autoCondenseContext && !this.isBackgroundSubtaskChild) {
await this.providerRef
.deref()
?.postMessageToWebview({ type: "condenseTaskContextResponse", text: this.taskId })
@@ -6031,14 +6416,15 @@ export class Task extends EventEmitter implements TaskLike {
throw new Error("Provider reference lost during tool building")
}
+ const effectivePolicy = this.effectiveToolPolicy(state)
const toolsResult = await buildNativeToolsArrayWithRestrictions({
provider,
cwd: this.cwd,
mode,
customModes: state?.customModes,
- experiments: state?.experiments,
+ experiments: effectivePolicy.experiments,
apiConfiguration,
- disabledTools: state?.disabledTools,
+ disabledTools: effectivePolicy.disabledTools,
modelInfo,
includeAllToolsWithRestrictions: supportsAllowedFunctionNames,
})
@@ -6148,6 +6534,11 @@ export class Task extends EventEmitter implements TaskLike {
)
}
+ // P1-1: this recursive retry with auto-approval is an unbounded path
+ // (only context-window errors are otherwise capped), so bound it for a
+ // background child. No-op for a normal task.
+ this.noteBackgroundChildRetry()
+
// Delegate generator output from the recursive call with
// incremented retry count.
yield* this.attemptApiRequest(retryAttempt + 1, retryOptions)
diff --git a/src/core/task/__tests__/Task.ignored-disabled-tools-notice.spec.ts b/src/core/task/__tests__/Task.ignored-disabled-tools-notice.spec.ts
index 5e1e8ee0ee..55f5564fd6 100644
--- a/src/core/task/__tests__/Task.ignored-disabled-tools-notice.spec.ts
+++ b/src/core/task/__tests__/Task.ignored-disabled-tools-notice.spec.ts
@@ -156,7 +156,7 @@ async function startTaskWithDisabledTools(disabledTools: string[] | undefined, p
startTask: false,
})
- const saySpy = vi.spyOn(task, "say").mockResolvedValue(undefined)
+ const saySpy = vi.spyOn(task, "say").mockResolvedValue({ ts: 0, type: "say", say: "text", text: "" })
// The model-profile suppression route is fed through the model info, never
// the provider state, so the fixture can vary it independently of the list.
const modelInfo: ModelInfo = {
@@ -203,7 +203,7 @@ async function startTaskWithFailingStateRead() {
// Mention expansion also reads the state. This test covers the notice read only.
vi.spyOn(task, "userInputContent").mockResolvedValue([])
- const saySpy = vi.spyOn(task, "say").mockResolvedValue(undefined)
+ const saySpy = vi.spyOn(task, "say").mockResolvedValue({ ts: 0, type: "say", say: "text", text: "" })
const taskAccess = getStartTaskAccess(task)
vi.spyOn(taskAccess, "getEnabledMcpToolsCount").mockResolvedValue({
enabledToolCount: 0,
@@ -245,7 +245,7 @@ async function resumeTaskWithDisabledTools(disabledTools: string[] | undefined)
startTask: false,
})
- const saySpy = vi.spyOn(task, "say").mockResolvedValue(undefined)
+ const saySpy = vi.spyOn(task, "say").mockResolvedValue({ ts: 0, type: "say", say: "text", text: "" })
const askSpy = vi.spyOn(task, "ask").mockResolvedValue({ response: "yesButtonClicked" })
// Persisted-history reads are stubbed so the resume path drives entirely in
// memory; the saved API history ends on an assistant turn, the ordinary
diff --git a/src/core/task/__tests__/Task.persistence.spec.ts b/src/core/task/__tests__/Task.persistence.spec.ts
index 86df5615db..f4cec7d1f4 100644
--- a/src/core/task/__tests__/Task.persistence.spec.ts
+++ b/src/core/task/__tests__/Task.persistence.spec.ts
@@ -529,7 +529,7 @@ describe("Task persistence", () => {
let saving: Promise | undefined
try {
- vi.spyOn(task, "say").mockResolvedValue(undefined)
+ vi.spyOn(task, "say").mockResolvedValue({ ts: 0, type: "say", say: "text", text: "" })
vi.spyOn(task, "ask").mockResolvedValue({ response: "yesButtonClicked", text: "", images: [] })
vi.spyOn(task, "emitFinalTokenUsageUpdate").mockImplementation(() => undefined)
vi.spyOn(task, "flushTelemetryInstallment").mockImplementation(() => undefined)
@@ -624,7 +624,7 @@ describe("Task persistence", () => {
toolDescription: vi.fn(),
toolCallId: completionCallId,
}
- vi.spyOn(task, "say").mockResolvedValue(undefined)
+ vi.spyOn(task, "say").mockResolvedValue({ ts: 0, type: "say", say: "text", text: "" })
vi.spyOn(task, "ask").mockResolvedValue({ response: "yesButtonClicked", text: "", images: [] })
vi.spyOn(task, "emitFinalTokenUsageUpdate").mockImplementation(() => undefined)
vi.spyOn(task, "flushTelemetryInstallment").mockImplementation(() => undefined)
@@ -694,7 +694,7 @@ describe("Task persistence", () => {
toolDescription: vi.fn(),
toolCallId: completionCallId,
}
- vi.spyOn(task, "say").mockResolvedValue(undefined)
+ vi.spyOn(task, "say").mockResolvedValue({ ts: 0, type: "say", say: "text", text: "" })
vi.spyOn(task, "ask").mockResolvedValue({ response: "yesButtonClicked", text: "", images: [] })
vi.spyOn(task, "emitFinalTokenUsageUpdate").mockImplementation(() => undefined)
vi.spyOn(task, "flushTelemetryInstallment").mockImplementation(() => undefined)
diff --git a/src/core/task/__tests__/Task.spec.ts b/src/core/task/__tests__/Task.spec.ts
index 739b7418a2..e98cb55d8b 100644
--- a/src/core/task/__tests__/Task.spec.ts
+++ b/src/core/task/__tests__/Task.spec.ts
@@ -2565,7 +2565,7 @@ describe("Cline", () => {
vi.spyOn(getTaskTestAccess(task), "getSystemPrompt").mockResolvedValue("mock system prompt")
vi.spyOn(task, "overwriteApiConversationHistory").mockResolvedValue(undefined)
task.apiConversationHistory = [{ role: "user", content: [{ type: "text", text: "x" }], ts: Date.now() }]
- const say = vi.spyOn(task, "say").mockResolvedValue(undefined)
+ const say = vi.spyOn(task, "say").mockResolvedValue({ ts: 0, type: "say", say: "text", text: "" })
return { task, say }
}
@@ -2805,7 +2805,7 @@ describe("Cline", () => {
totalTokensOut: 0,
contextTokens: 0,
})
- vi.spyOn(task, "say").mockResolvedValue(undefined)
+ vi.spyOn(task, "say").mockResolvedValue({ ts: 0, type: "say", say: "text", text: "" })
}
afterEach(() => {
@@ -3032,7 +3032,9 @@ describe("Cline", () => {
startTask: false,
})
- const saySpy = vi.spyOn(cline, "say").mockResolvedValue(undefined)
+ const saySpy = vi
+ .spyOn(cline, "say")
+ .mockResolvedValue({ ts: 0, type: "say" as const, say: "text", text: "" })
// relPath provided -> the "...WithPath" message branch.
const withPath = await cline.sayAndCreateMissingParamError("read_file", "path", "src/foo.ts")
@@ -5848,7 +5850,7 @@ describe("Cline", () => {
totalTokensOut: 0,
contextTokens: 0,
})
- vi.spyOn(task, "say").mockResolvedValue(undefined)
+ vi.spyOn(task, "say").mockResolvedValue({ ts: 0, type: "say", say: "text", text: "" })
task.apiConversationHistory = [
{ role: "user", content: [{ type: "text", text: "test message" }], ts: Date.now() },
]
@@ -6474,7 +6476,7 @@ describe("Cline", () => {
// The early return this guards never reaches say; the spy only keeps
// the aborted task's post-overwrite say from throwing before the
// summarize/overwrite assertions can report a regression.
- vi.spyOn(task, "say").mockResolvedValue(undefined)
+ vi.spyOn(task, "say").mockResolvedValue({ ts: 0, type: "say", say: "text", text: "" })
const overwriteSpy = vi.spyOn(task, "overwriteApiConversationHistory").mockResolvedValue(undefined)
// The summarizeConversation module mock is never cleared, so pin the
// call count this condense starts from.
@@ -6526,7 +6528,7 @@ describe("Cline", () => {
// The early return this guards never reaches say; the spy only keeps
// the aborted task's post-overwrite say from throwing before the
// overwrite assertion can report the regression.
- const saySpy = vi.spyOn(task, "say").mockResolvedValue(undefined)
+ const saySpy = vi.spyOn(task, "say").mockResolvedValue({ ts: 0, type: "say", say: "text", text: "" })
const overwriteSpy = vi.spyOn(task, "overwriteApiConversationHistory").mockResolvedValue(undefined)
// The summarizeConversation module mock is never cleared, so pin the
// call count this condense starts from.
@@ -6576,7 +6578,7 @@ describe("Cline", () => {
{ role: "user", content: [{ type: "text", text: "test message" }], ts: Date.now() },
]
vi.spyOn(getTaskTestAccess(task), "getSystemPrompt").mockResolvedValue("mock system prompt")
- vi.spyOn(task, "say").mockResolvedValue(undefined)
+ vi.spyOn(task, "say").mockResolvedValue({ ts: 0, type: "say", say: "text", text: "" })
const overwriteSpy = vi.spyOn(task, "overwriteApiConversationHistory").mockResolvedValue(undefined)
// Suspend inside the collector so the abort lands while the
// summarization request cannot have started yet.
@@ -6623,7 +6625,7 @@ describe("Cline", () => {
{ role: "user", content: [{ type: "text", text: "test message" }], ts: Date.now() },
]
vi.spyOn(getTaskTestAccess(task), "getSystemPrompt").mockResolvedValue("mock system prompt")
- vi.spyOn(task, "say").mockResolvedValue(undefined)
+ vi.spyOn(task, "say").mockResolvedValue({ ts: 0, type: "say", say: "text", text: "" })
const overwriteSpy = vi.spyOn(task, "overwriteApiConversationHistory").mockResolvedValue(undefined)
let releaseFilesRead!: (value: string[] | undefined) => void
const filesReadGate = new Promise((resolve) => {
@@ -6806,7 +6808,7 @@ describe("Cline", () => {
startTask: false,
})
- const ensureModelFetched = vi.fn().mockResolvedValue(undefined)
+ const ensureModelFetched = vi.fn().mockResolvedValue({ ts: 0, type: "say", say: "text", text: "" })
Object.assign(task.api, { ensureModelFetched })
vi.spyOn(task.api, "getModel").mockReturnValue({
id: mockApiConfig.apiModelId!,
@@ -7334,7 +7336,7 @@ describe("Cline", () => {
expect(task.clineMessages).toEqual([])
await pendingPostState
})
- const saySpy = vi.spyOn(task, "say").mockResolvedValue(undefined)
+ const saySpy = vi.spyOn(task, "say").mockResolvedValue({ ts: 0, type: "say", say: "text", text: "" })
vi.spyOn(taskAccess, "getEnabledMcpToolsCount").mockResolvedValue({
enabledToolCount: 0,
enabledServerCount: 0,
diff --git a/src/core/task/__tests__/ask-auto-deny.spec.ts b/src/core/task/__tests__/ask-auto-deny.spec.ts
index 0dc5071082..c30e104bcd 100644
--- a/src/core/task/__tests__/ask-auto-deny.spec.ts
+++ b/src/core/task/__tests__/ask-auto-deny.spec.ts
@@ -82,7 +82,7 @@ function attachTurnHarness(task: Task) {
Object.defineProperty(task, "streamingToolCallIndices", { value: new Map() })
Object.defineProperty(task, "activeToolContexts", { value: new Map() })
task["saveApiConversationHistory"] = vi.fn(async () => true)
- task["say"] = vi.fn(async () => undefined)
+ task["say"] = vi.fn(async () => ({ ts: 0, type: "say" as const, say: "text", text: "" }))
// The loop rewrites the newest api_req_started row with cost data; the
// no-op `say` stub above never adds one itself.
task["clineMessages"].push({ type: "say", say: "api_req_started", text: "{}", ts: Date.now() })
diff --git a/src/core/task/__tests__/background-ask-policy.spec.ts b/src/core/task/__tests__/background-ask-policy.spec.ts
new file mode 100644
index 0000000000..2c4f62c201
--- /dev/null
+++ b/src/core/task/__tests__/background-ask-policy.spec.ts
@@ -0,0 +1,521 @@
+// npx vitest run core/task/__tests__/background-ask-policy.spec.ts
+
+import * as fs from "fs"
+import * as os from "os"
+import * as path from "path"
+
+import * as vscode from "vscode"
+import { type ExtensionState, RooCodeEventName } from "@roo-code/types"
+
+import { Task } from "../Task"
+import { setAbortLatch } from "../../../test-utils/run-state"
+import { isRealPathOutsideWorkspace } from "../../../utils/pathUtils"
+
+// The streaming-loop drive below never asserts on environment details; the
+// real collector reaches into the VS Code window API, which this file's
+// lightweight task stub does not model.
+vi.mock("../../environment/getEnvironmentDetails", () => ({
+ getEnvironmentDetails: vi.fn().mockResolvedValue(""),
+}))
+
+// M-1: the read carve-out consults the canonical outside-workspace gate
+// (isRealPathOutsideWorkspace), which reads vscode.workspace.workspaceFolders
+// and the real filesystem. Mock it so the seam tests can pin both the
+// in-workspace (approve) and outside-workspace (deny) decisions
+// deterministically; the real-filesystem regression block below reinstalls the
+// production implementation.
+vi.mock("../../../utils/pathUtils", async (importOriginal) => {
+ const actual = await importOriginal()
+ return {
+ ...actual,
+ isRealPathOutsideWorkspace: vi.fn(),
+ }
+})
+
+// D4 ask policy: a background (read-only) child task must never post a chat
+// row and wait for a user click. When the auto-approval decision is `ask`,
+// ask() resolves deterministically by ask type. Read-only tool asks resolve
+// approved (D4 scopes the auto-deny to non-read tools: the user already
+// approved the parallel_subtasks call, and the child's structural tool policy
+// blocks every dangerous tool); every other tool ask carries the structured
+// `background_policy` auto-deny detail; every non-tool ask type resolves to
+// `noButtonClicked` without any detail. An ask whose tool text is not
+// say-tool JSON fails closed to the auto-deny.
+
+/** The parts of the provider that `Task.ask` reaches for. */
+type ProviderStub = {
+ getState: () => Promise>
+ postMessageToWebview: ReturnType
+ postStateToWebviewWithoutTaskHistory: ReturnType
+ getSkillsManager: () => undefined
+ cwd: string
+}
+
+const TASK_CWD = "/path/to/task-workspace"
+
+function buildTask(provider: ProviderStub, taskCwd: string, isBackgroundChild: boolean) {
+ const task = Object.create(Task.prototype) as Task
+ setAbortLatch(task, false)
+ task["clineMessages"] = []
+ task["askResponse"] = undefined
+ task["askResponseText"] = undefined
+ task["askResponseImages"] = undefined
+ task["lastMessageTs"] = undefined
+ task["addToClineMessages"] = vi.fn(async () => {})
+ task["saveClineMessages"] = vi.fn(async () => true)
+ task["updateClineMessage"] = vi.fn(async () => {})
+ task["cancelAutoApprovalTimeout"] = vi.fn(() => {})
+ task["checkpointSave"] = vi.fn(async () => {})
+ task["emit"] = vi.fn()
+ // A double assertion is unavoidable here: `providerRef` is a `WeakRef`,
+ // and the stub is neither a `WeakRef` nor a whole `ClineProvider`. Constructing
+ // either would drag in the extension host, when `Task.ask` only ever calls
+ // `deref()`, `getState()` and `postMessageToWebview()` on it.
+ task["providerRef"] = { deref: () => provider } as unknown as Task["providerRef"]
+ Object.defineProperty(task, "workspacePath", { value: taskCwd })
+ Object.defineProperty(task, "isBackgroundSubtaskChild", { value: isBackgroundChild })
+ return task
+}
+
+async function attachQueue(task: Task) {
+ const { MessageQueueService } = await import("../../message-queue/MessageQueueService")
+ const queue = new MessageQueueService()
+ Object.defineProperty(task, "messageQueueService", { value: queue })
+ return queue
+}
+
+describe("Task.ask fail-closed policy for background children (D4)", () => {
+ let state: Partial
+ let provider: ProviderStub
+
+ beforeEach(() => {
+ // Auto-approval off: checkAutoApproval resolves every blocking ask type
+ // with the `ask` decision, which is exactly the seam D4 intercepts.
+ state = { autoApprovalEnabled: false }
+ provider = {
+ postMessageToWebview: vi.fn().mockResolvedValue(undefined),
+ postStateToWebviewWithoutTaskHistory: vi.fn().mockResolvedValue(undefined),
+ getSkillsManager: () => undefined,
+ cwd: TASK_CWD,
+ getState: async () => state,
+ }
+ // M-1 default: the read target resolves inside the workspace, so the
+ // carve-out approves it. Outside-workspace cases override per test.
+ vi.mocked(isRealPathOutsideWorkspace).mockReset()
+ vi.mocked(isRealPathOutsideWorkspace).mockResolvedValue(false)
+ })
+
+ it("resolves a non-read tool ask without a user click and carries the background_policy detail", async () => {
+ const task = buildTask(provider, TASK_CWD, true)
+ await attachQueue(task)
+
+ const result = await task.ask("tool", JSON.stringify({ tool: "write_to_file", path: "a.txt" }), false)
+
+ expect(result.response).toBe("noButtonClicked")
+ expect(result.autoDenyDetail?.kind).toBe("background_policy")
+ // The presenter's structured auto-deny path is armed, mirroring the deny
+ // branch of a policy denial.
+ expect(task["pendingAutoDenyDetail"]).toEqual({ kind: "background_policy" })
+ // Fail closed before any chat row exists: no approval prompt was posted.
+ expect(task["addToClineMessages"]).not.toHaveBeenCalled()
+ expect(task["emit"]).not.toHaveBeenCalledWith(RooCodeEventName.TaskInteractive, expect.anything())
+ })
+
+ it.each(["readFile", "listFiles", "listFilesTopLevel", "listFilesRecursive", "searchFiles", "codebaseSearch"])(
+ "approves a %s tool ask under default settings (no alwaysAllowReadOnly)",
+ async (tool) => {
+ // Default settings: autoApprovalEnabled false, no alwaysAllowReadOnly,
+ // no allowedReadFiles — checkAutoApproval returns `ask` for every
+ // read. The D4 read carve-out must still resolve the ask approved;
+ // this is the regression test for the blanket-deny P0. The gate is
+ // mocked to in-workspace (the default set in beforeEach).
+ const task = buildTask(provider, TASK_CWD, true)
+ await attachQueue(task)
+
+ const result = await task.ask("tool", JSON.stringify({ tool, path: "a.txt" }), false)
+
+ expect(result.response).toBe("yesButtonClicked")
+ expect(result.autoDenyDetail).toBeUndefined()
+ expect(task["pendingAutoDenyDetail"]).toBeUndefined()
+ // Approved without any chat row: the child never prompts.
+ expect(task["addToClineMessages"]).not.toHaveBeenCalled()
+ expect(task["emit"]).not.toHaveBeenCalledWith(RooCodeEventName.TaskInteractive, expect.anything())
+ },
+ )
+
+ it("M-1: approves an in-workspace read under default settings", async () => {
+ vi.mocked(isRealPathOutsideWorkspace).mockResolvedValue(false)
+ const task = buildTask(provider, TASK_CWD, true)
+ await attachQueue(task)
+
+ const result = await task.ask("tool", JSON.stringify({ tool: "readFile", path: "src/a.txt" }), false)
+
+ expect(result.response).toBe("yesButtonClicked")
+ expect(result.autoDenyDetail).toBeUndefined()
+ // The gate was consulted with the path resolved against the task cwd.
+ expect(isRealPathOutsideWorkspace).toHaveBeenCalledWith(expect.stringContaining("a.txt"))
+ })
+
+ it("M-1: denies an outside-workspace read under default settings (fail closed)", async () => {
+ // A prompt-injected child must not be able to read e.g. ~/.ssh/id_rsa
+ // through the read carve-out.
+ vi.mocked(isRealPathOutsideWorkspace).mockResolvedValue(true)
+ const task = buildTask(provider, TASK_CWD, true)
+ await attachQueue(task)
+
+ const result = await task.ask("tool", JSON.stringify({ tool: "readFile", path: "../../.ssh/id_rsa" }), false)
+
+ expect(result.response).toBe("noButtonClicked")
+ expect(result.autoDenyDetail?.kind).toBe("background_policy")
+ expect(task["pendingAutoDenyDetail"]).toEqual({ kind: "background_policy" })
+ expect(task["addToClineMessages"]).not.toHaveBeenCalled()
+ })
+
+ it("M-1: approves a batch read when every batch target is in the workspace", async () => {
+ // ReadFileTool's batch approval ask carries no top-level `path`: every
+ // target lives in `batchFiles`. Each one must go through the gate.
+ const task = buildTask(provider, TASK_CWD, true)
+ await attachQueue(task)
+
+ const result = await task.ask(
+ "tool",
+ JSON.stringify({
+ tool: "readFile",
+ batchFiles: [
+ { path: "src/a.txt", lineSnippet: "", key: "src/a.txt" },
+ { path: "src/b.ts", lineSnippet: "", key: "src/b.ts" },
+ ],
+ }),
+ false,
+ )
+
+ expect(result.response).toBe("yesButtonClicked")
+ expect(result.autoDenyDetail).toBeUndefined()
+ // The gate ran on EVERY batch target, resolved against the task cwd
+ // exactly like the single-path case.
+ expect(isRealPathOutsideWorkspace).toHaveBeenCalledTimes(2)
+ expect(isRealPathOutsideWorkspace).toHaveBeenCalledWith(path.resolve(TASK_CWD, "src/a.txt"))
+ expect(isRealPathOutsideWorkspace).toHaveBeenCalledWith(path.resolve(TASK_CWD, "src/b.ts"))
+ })
+
+ it("M-1: denies a batch read when any batch target is outside the workspace (fail closed)", async () => {
+ // One outside entry must deny the WHOLE batch: the outside file's
+ // contents would land in the workspace report either way.
+ vi.mocked(isRealPathOutsideWorkspace).mockImplementation(async (candidate) => candidate.includes("id_rsa"))
+ const task = buildTask(provider, TASK_CWD, true)
+ await attachQueue(task)
+
+ const result = await task.ask(
+ "tool",
+ JSON.stringify({
+ tool: "readFile",
+ batchFiles: [
+ { path: "src/a.txt", lineSnippet: "", key: "src/a.txt" },
+ { path: "../../.ssh/id_rsa", lineSnippet: "", key: "../../.ssh/id_rsa" },
+ ],
+ }),
+ false,
+ )
+
+ expect(result.response).toBe("noButtonClicked")
+ expect(result.autoDenyDetail?.kind).toBe("background_policy")
+ expect(task["pendingAutoDenyDetail"]).toEqual({ kind: "background_policy" })
+ // The gate still checked every entry, including the in-workspace one.
+ expect(isRealPathOutsideWorkspace).toHaveBeenCalledWith(path.resolve(TASK_CWD, "src/a.txt"))
+ expect(isRealPathOutsideWorkspace).toHaveBeenCalledWith(path.resolve(TASK_CWD, "../../.ssh/id_rsa"))
+ expect(task["addToClineMessages"]).not.toHaveBeenCalled()
+ })
+
+ it.each([
+ ["an entry with an empty path", [{ path: "src/a.txt", lineSnippet: "", key: "src/a.txt" }, { path: "" }]],
+ [
+ "an entry with a missing path",
+ [
+ { path: "src/a.txt", lineSnippet: "", key: "src/a.txt" },
+ { lineSnippet: "", key: "b" },
+ ],
+ ],
+ ["an entry with a non-string path", [{ path: "src/a.txt", lineSnippet: "", key: "src/a.txt" }, { path: 42 }]],
+ ["a null entry", [null]],
+ ["a non-array batchFiles", "not-an-array"],
+ ] as Array<[string, unknown]>)(
+ "M-1: fails closed on a batch read with %s — the unverifiable entry must not ride an approved batch",
+ async (_label, batchFiles) => {
+ vi.mocked(isRealPathOutsideWorkspace).mockClear()
+ const task = buildTask(provider, TASK_CWD, true)
+ await attachQueue(task)
+
+ const result = await task.ask("tool", JSON.stringify({ tool: "readFile", batchFiles }), false)
+
+ expect(result.response).toBe("noButtonClicked")
+ expect(result.autoDenyDetail?.kind).toBe("background_policy")
+ // Unverifiable entries are never silently skipped: the gate never
+ // saw the batch, so nothing in it can be approved.
+ expect(isRealPathOutsideWorkspace).not.toHaveBeenCalled()
+ },
+ )
+
+ it("M-1: a batch read with no entries stays approved without consulting the gate", async () => {
+ vi.mocked(isRealPathOutsideWorkspace).mockClear()
+ const task = buildTask(provider, TASK_CWD, true)
+ await attachQueue(task)
+
+ const result = await task.ask("tool", JSON.stringify({ tool: "readFile", batchFiles: [] }), false)
+
+ expect(result.response).toBe("yesButtonClicked")
+ expect(result.autoDenyDetail).toBeUndefined()
+ expect(isRealPathOutsideWorkspace).not.toHaveBeenCalled()
+ })
+
+ it("M-1: a read-only ask with no path field stays approved without consulting the gate", async () => {
+ vi.mocked(isRealPathOutsideWorkspace).mockClear()
+ const task = buildTask(provider, TASK_CWD, true)
+ await attachQueue(task)
+
+ const result = await task.ask("tool", JSON.stringify({ tool: "runSlashCommand" }), false)
+
+ expect(result.response).toBe("yesButtonClicked")
+ expect(result.autoDenyDetail).toBeUndefined()
+ expect(isRealPathOutsideWorkspace).not.toHaveBeenCalled()
+ })
+
+ it.each(["not json at all", "{}", JSON.stringify({ path: "a.txt" }), '{"tool": 42}'])(
+ "fails closed to the auto-deny when the tool ask text is %j",
+ async (text) => {
+ const task = buildTask(provider, TASK_CWD, true)
+ await attachQueue(task)
+
+ const result = await task.ask("tool", text, false)
+
+ expect(result.response).toBe("noButtonClicked")
+ expect(result.autoDenyDetail?.kind).toBe("background_policy")
+ },
+ )
+
+ it.each(["followup", "api_req_failed", "command", "completion_result"] as const)(
+ "resolves a %s ask without a user click and without a chat row",
+ async (type) => {
+ const task = buildTask(provider, TASK_CWD, true)
+ await attachQueue(task)
+
+ const result = await task.ask(type, "{}", false)
+
+ expect(result.response).toBe("noButtonClicked")
+ expect(result.autoDenyDetail).toBeUndefined()
+ expect(task["addToClineMessages"]).not.toHaveBeenCalled()
+ },
+ )
+
+ it("releases a claimed queued message instead of stranding it", async () => {
+ const task = buildTask(provider, TASK_CWD, true)
+ const queue = await attachQueue(task)
+ queue.addMessage("queued feedback arriving during a background child ask")
+
+ const result = await task.ask("tool", JSON.stringify({ tool: "write_to_file", path: "a.txt" }), false)
+
+ expect(result.response).toBe("noButtonClicked")
+ // The early return must not consume the message as fake approval nor
+ // leave it claimed: it survives, unclaimed, for a later consumer.
+ expect(result.queuedMessageId).toBeUndefined()
+ expect(queue.messages).toHaveLength(1)
+ expect(queue.hasUnclaimed()).toBe(true)
+ })
+
+ it("does not approve a read ask aborted while the M-1 gate lookup is pending", async () => {
+ // axGv: the gate lookup is async, so a cancellation can land while it is
+ // pending. The pre-resolution abort check runs before the lookup
+ // starts; without a recheck after it, a late in-workspace result would
+ // still return yesButtonClicked for an already-aborted task. The lookup
+ // resolves late here; the ask must fail closed with the standard abort
+ // error, and a queued message claimed for the ask must be released,
+ // not stranded.
+ let resolveGate!: (outside: boolean) => void
+ vi.mocked(isRealPathOutsideWorkspace).mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ resolveGate = resolve
+ }),
+ )
+ const task = buildTask(provider, TASK_CWD, true)
+ const queue = await attachQueue(task)
+ queue.addMessage("queued feedback arriving during the gate lookup")
+
+ const askPromise = task.ask("tool", JSON.stringify({ tool: "readFile", path: "a.txt" }), false)
+ // The abort must land after the pre-resolution check and while the
+ // lookup is suspended, so wait until the gate has been consulted.
+ await vi.waitFor(() => expect(isRealPathOutsideWorkspace).toHaveBeenCalled())
+ setAbortLatch(task, true)
+ // The in-workspace verdict arrives only after the abort.
+ resolveGate(false)
+
+ await expect(askPromise).rejects.toMatchObject({
+ name: "Error",
+ message: `[RooCode#ask] task ${task.taskId}.${task.instanceId} aborted`,
+ })
+ // Fail closed: no approval, no chat row, and the claimed queued
+ // message is released for a later consumer.
+ expect(task["addToClineMessages"]).not.toHaveBeenCalled()
+ expect(queue.messages).toHaveLength(1)
+ expect(queue.hasUnclaimed()).toBe(true)
+ })
+
+ it("leaves the interactive flow untouched for a non-background task", async () => {
+ const task = buildTask(provider, TASK_CWD, false)
+ await attachQueue(task)
+ const addToClineMessages = task["addToClineMessages"] as ReturnType
+
+ const askPromise = task.ask("tool", JSON.stringify({ tool: "write_to_file", path: "a.txt" }), false)
+ // The ask posts its chat row and blocks, exactly as before D4.
+ await vi.waitFor(() => expect(addToClineMessages).toHaveBeenCalledTimes(1))
+ expect(addToClineMessages.mock.calls[0][0].type).toBe("ask")
+ expect(addToClineMessages.mock.calls[0][0].ask).toBe("tool")
+
+ task.approveAsk()
+ const result = await askPromise
+ expect(result.response).toBe("yesButtonClicked")
+ expect(result.autoDenyDetail).toBeUndefined()
+ })
+
+ it("leaves an auto-approved ask untouched for a background child", async () => {
+ // With alwaysAllowReadOnly on, checkAutoApproval itself approves the read
+ // (decision "approve"), so the D4 seam never engages. This test pins the
+ // seam's no-op for auto-answered asks; the default-settings read path is
+ // covered by the carve-out tests above.
+ state = { autoApprovalEnabled: true, alwaysAllowReadOnly: true }
+ const task = buildTask(provider, TASK_CWD, true)
+ await attachQueue(task)
+
+ const result = await task.ask("tool", JSON.stringify({ tool: "readFile", path: "a.txt" }), false)
+
+ expect(result.response).toBe("yesButtonClicked")
+ expect(result.autoDenyDetail).toBeUndefined()
+ })
+})
+
+// CR-1 (CodeRabbit finding 1, Task.ts carve-out): the M-1 gate must compare
+// CANONICAL paths. These tests run the production isRealPathOutsideWorkspace
+// against a real temporary filesystem: a workspace symlink pointing outside
+// must be denied even though its lexical path sits inside the workspace, and a
+// real in-workspace file must stay approved under default settings.
+describe("M-1 canonical gate against a real filesystem (CR-1)", () => {
+ // Set up at collection time so it.runIf can branch on symlink support.
+ const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), "zoo-cr1-m1-"))
+ const workspaceDir = path.join(tempRoot, "workspace")
+ const outsideDir = path.join(tempRoot, "outside")
+ fs.mkdirSync(path.join(workspaceDir, "src"), { recursive: true })
+ fs.mkdirSync(outsideDir)
+ fs.writeFileSync(path.join(outsideDir, "secret.txt"), "outside secret")
+ fs.writeFileSync(path.join(workspaceDir, "src", "a.txt"), "in-workspace file")
+ // `private-link` is a workspace entry whose TARGET lives outside the
+ // workspace — the escape the lexical gate missed. A junction is a directory
+ // link creatable without elevation on Windows and a plain directory symlink
+ // elsewhere.
+ let symlinkCreated = false
+ try {
+ fs.symlinkSync(outsideDir, path.join(workspaceDir, "private-link"), "junction")
+ symlinkCreated = true
+ } catch {
+ symlinkCreated = false
+ }
+
+ afterAll(() => {
+ fs.rmSync(tempRoot, { recursive: true, force: true })
+ })
+
+ // The global vscode mock exposes workspaceFolders as a plain mutable
+ // property; the double assertion stands in for the mock's lack of typed
+ // mutability (the real API declares the property readonly).
+ const setWorkspaceFolders = (folders: { uri: { fsPath: string } }[]) => {
+ ;(vscode.workspace as unknown as { workspaceFolders: { uri: { fsPath: string } }[] }).workspaceFolders = folders
+ }
+
+ let provider: ProviderStub
+
+ beforeEach(async () => {
+ provider = {
+ postMessageToWebview: vi.fn().mockResolvedValue(undefined),
+ postStateToWebviewWithoutTaskHistory: vi.fn().mockResolvedValue(undefined),
+ getSkillsManager: () => undefined,
+ cwd: workspaceDir,
+ getState: async () => ({ autoApprovalEnabled: false }),
+ }
+ // Reinstall the production gate and point the mocked vscode at the real
+ // temp workspace.
+ const actual = await vi.importActual("../../../utils/pathUtils")
+ vi.mocked(isRealPathOutsideWorkspace).mockReset()
+ vi.mocked(isRealPathOutsideWorkspace).mockImplementation(actual.isRealPathOutsideWorkspace)
+ setWorkspaceFolders([{ uri: { fsPath: workspaceDir } }])
+ })
+
+ afterEach(() => {
+ setWorkspaceFolders([])
+ })
+
+ it.runIf(symlinkCreated)(
+ "M-1: denies a read whose workspace symlink target escapes the workspace (real symlink, fail closed)",
+ async () => {
+ const task = buildTask(provider, workspaceDir, true)
+ await attachQueue(task)
+
+ const result = await task.ask(
+ "tool",
+ JSON.stringify({ tool: "readFile", path: "private-link/secret.txt" }),
+ false,
+ )
+
+ expect(result.response).toBe("noButtonClicked")
+ expect(result.autoDenyDetail?.kind).toBe("background_policy")
+ expect(task["pendingAutoDenyDetail"]).toEqual({ kind: "background_policy" })
+ // Denied before any chat row exists: the child never prompts.
+ expect(task["addToClineMessages"]).not.toHaveBeenCalled()
+ },
+ )
+
+ it.runIf(symlinkCreated)(
+ "M-1: denies a batch read when any batch target escapes through a workspace symlink (real gate, fail closed)",
+ async () => {
+ // The batch ask shape carries no top-level `path`, so the canonical
+ // gate must run per `batchFiles` entry: the symlinked outside entry
+ // denies the whole batch even alongside a real in-workspace file.
+ const task = buildTask(provider, workspaceDir, true)
+ await attachQueue(task)
+
+ const result = await task.ask(
+ "tool",
+ JSON.stringify({
+ tool: "readFile",
+ batchFiles: [
+ { path: "src/a.txt", lineSnippet: "", key: "src/a.txt" },
+ { path: "private-link/secret.txt", lineSnippet: "", key: "private-link/secret.txt" },
+ ],
+ }),
+ false,
+ )
+
+ expect(result.response).toBe("noButtonClicked")
+ expect(result.autoDenyDetail?.kind).toBe("background_policy")
+ expect(task["pendingAutoDenyDetail"]).toEqual({ kind: "background_policy" })
+ },
+ )
+
+ it("M-1: approves a real in-workspace read under default settings", async () => {
+ const task = buildTask(provider, workspaceDir, true)
+ await attachQueue(task)
+
+ const result = await task.ask("tool", JSON.stringify({ tool: "readFile", path: "src/a.txt" }), false)
+
+ expect(result.response).toBe("yesButtonClicked")
+ expect(result.autoDenyDetail).toBeUndefined()
+ })
+
+ it("M-1: fails closed through the real gate when no workspace folder is configured", async () => {
+ setWorkspaceFolders([])
+ const task = buildTask(provider, workspaceDir, true)
+ await attachQueue(task)
+
+ const result = await task.ask("tool", JSON.stringify({ tool: "readFile", path: "src/a.txt" }), false)
+
+ expect(result.response).toBe("noButtonClicked")
+ expect(result.autoDenyDetail?.kind).toBe("background_policy")
+ })
+})
diff --git a/src/core/task/__tests__/background-mistake-limit.spec.ts b/src/core/task/__tests__/background-mistake-limit.spec.ts
new file mode 100644
index 0000000000..5e015c901b
--- /dev/null
+++ b/src/core/task/__tests__/background-mistake-limit.spec.ts
@@ -0,0 +1,155 @@
+// npx vitest run core/task/__tests__/background-mistake-limit.spec.ts
+
+import { type ExtensionState, providerIdentifiers } from "@roo-code/types"
+
+import { Task } from "../Task"
+import { setAbortLatch } from "../../../test-utils/run-state"
+
+// F-08 regression: a background (read-only) child that reaches the consecutive
+// mistake limit must end its run loop instead of auto-answering the
+// mistake_limit_reached ask, resetting the counter, and looping forever while
+// holding a scheduler permit. The ask resolves by policy (D4), then
+// requestAbort(true) + throw terminates the run. The throw lands OUTSIDE the
+// didEndLoop try, so it is swallowed by startTask's abandoned/abort catch (not
+// the didEndLoop catch), run() settles, and the host's run-settled catch-all
+// settles the child handle.
+
+vi.mock("@roo-code/telemetry", () => ({
+ TelemetryService: {
+ instance: {
+ captureConsecutiveMistakeError: vi.fn(),
+ },
+ },
+}))
+
+vi.mock("../../environment/getEnvironmentDetails", () => ({
+ getEnvironmentDetails: vi.fn().mockResolvedValue(""),
+}))
+
+/** The parts of the provider that `Task.ask` reaches for. */
+type ProviderStub = {
+ getState: () => Promise>
+ postMessageToWebview: ReturnType
+ postStateToWebviewWithoutTaskHistory: ReturnType
+ getSkillsManager: () => undefined
+ cwd: string
+}
+
+const TASK_CWD = "/path/to/task-workspace"
+
+function buildTask(provider: ProviderStub, isBackgroundChild: boolean) {
+ const task = Object.create(Task.prototype) as Task
+ setAbortLatch(task, false)
+ task["clineMessages"] = []
+ task["askResponse"] = undefined
+ task["askResponseText"] = undefined
+ task["askResponseImages"] = undefined
+ task["lastMessageTs"] = undefined
+ task["addToClineMessages"] = vi.fn(async () => {})
+ task["saveClineMessages"] = vi.fn(async () => true)
+ task["updateClineMessage"] = vi.fn(async () => {})
+ task["cancelAutoApprovalTimeout"] = vi.fn(() => {})
+ task["checkpointSave"] = vi.fn(async () => {})
+ task["emit"] = vi.fn()
+ // driveRunEvent's reducer inputs; divergence reporting stays disabled.
+ // (Both fields are readonly at compile time; defineProperty assigns them.)
+ Object.defineProperty(task, "runRejections", { value: new Set() })
+ Object.defineProperty(task, "reportedDivergences", { value: new Set() })
+ task["consecutiveMistakeLimit"] = 3
+ task["consecutiveMistakeCount"] = 3
+ // A double assertion is unavoidable here: `providerRef` is a `WeakRef`,
+ // and the stub is neither a `WeakRef` nor a whole `ClineProvider`. Constructing
+ // either would drag in the extension host, when these seams only ever call
+ // `deref()`, `getState()` and `postMessageToWebview()` on it.
+ task["providerRef"] = { deref: () => provider } as unknown as Task["providerRef"]
+ Object.defineProperty(task, "workspacePath", { value: TASK_CWD })
+ Object.defineProperty(task, "isBackgroundSubtaskChild", { value: isBackgroundChild })
+ return task
+}
+
+async function attachQueue(task: Task) {
+ const { MessageQueueService } = await import("../../message-queue/MessageQueueService")
+ const queue = new MessageQueueService()
+ Object.defineProperty(task, "messageQueueService", { value: queue })
+ return queue
+}
+
+describe("background child mistake limit is terminal (F-08)", () => {
+ let provider: ProviderStub
+
+ beforeEach(() => {
+ // Auto-approval off: the mistake_limit_reached ask resolves `ask`, which
+ // is exactly the decision the D4 seam intercepts for a background child.
+ provider = {
+ postMessageToWebview: vi.fn().mockResolvedValue(undefined),
+ postStateToWebviewWithoutTaskHistory: vi.fn().mockResolvedValue(undefined),
+ getSkillsManager: () => undefined,
+ cwd: TASK_CWD,
+ getState: async () => ({ autoApprovalEnabled: false }),
+ }
+ })
+
+ it("ends the run loop instead of resetting the counter and retrying", async () => {
+ const task = buildTask(provider, true)
+ await attachQueue(task)
+
+ // The throw rejects the run promise; startTask's catch swallows it
+ // because requestAbort(true) already set the abandoned/abort latches
+ // (the same idiom as the loop's own abort guard), so run() settles
+ // instead of looping. Pre-F-08 the iteration continued: the counter was
+ // reset and a fresh API request started, forever.
+ await expect(task.recursivelyMakeClineRequests([{ type: "text", text: "keep going" }])).rejects.toThrow(
+ "reached the consecutive mistake limit",
+ )
+ // The loop was terminated, not merely breakable: the abort latch is set
+ // (requestAbort(true)) so no further iteration can start.
+ expect(task.abandoned).toBe(true)
+ expect(task.abort).toBe(true)
+ // Terminal without any user-visible row: the ask resolved by policy.
+ expect(task["addToClineMessages"]).not.toHaveBeenCalled()
+ expect(provider.postMessageToWebview).not.toHaveBeenCalled()
+ // The counter reset below the limit check never ran.
+ expect(task["consecutiveMistakeCount"]).toBe(3)
+ })
+
+ it("never reaches the next API request seam", async () => {
+ const task = buildTask(provider, true)
+ await attachQueue(task)
+ task["maybeWaitForProviderRateLimit"] = vi.fn(async () => {})
+
+ await expect(task.recursivelyMakeClineRequests([{ type: "text", text: "keep going" }])).rejects.toThrow(
+ "reached the consecutive mistake limit",
+ )
+
+ expect(task["maybeWaitForProviderRateLimit"]).not.toHaveBeenCalled()
+ })
+
+ it("does not engage for a non-background task", async () => {
+ const task = buildTask(provider, false)
+ await attachQueue(task)
+ task["apiConfiguration"] = {
+ apiProvider: providerIdentifiers.anthropic,
+ apiModelId: "claude-3-5-sonnet-20241022",
+ } as Task["apiConfiguration"]
+ // A non-background task blocks on the real ask; stand in the user's
+ // decline so the flow reaches the counter reset, then blow up at the
+ // next seam to prove execution continued past the limit check.
+ task.ask = vi.fn(async () => ({ response: "noButtonClicked" as const }))
+ task["requestAbort"] = vi.fn()
+ const sentinel = new Error("sentinel: reached the post-limit request path")
+ task["maybeWaitForProviderRateLimit"] = vi.fn(async () => {
+ throw sentinel
+ })
+
+ // The sentinel propagates the same way the terminal throw does (both
+ // land outside the didEndLoop try) — but no abort was requested and the
+ // counter was reset, i.e. the non-background flow is untouched.
+ await expect(task.recursivelyMakeClineRequests([{ type: "text", text: "keep going" }])).rejects.toThrow(
+ "sentinel: reached the post-limit request path",
+ )
+ expect(task["requestAbort"]).not.toHaveBeenCalled()
+ expect(task.abandoned).not.toBe(true)
+ expect(task["consecutiveMistakeCount"]).toBe(0)
+ expect(task["maybeWaitForProviderRateLimit"]).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/src/core/task/__tests__/background-policy-snapshot.spec.ts b/src/core/task/__tests__/background-policy-snapshot.spec.ts
new file mode 100644
index 0000000000..2bd0332a10
--- /dev/null
+++ b/src/core/task/__tests__/background-policy-snapshot.spec.ts
@@ -0,0 +1,510 @@
+// npx vitest run core/task/__tests__/background-policy-snapshot.spec.ts
+
+import * as os from "os"
+import * as path from "path"
+
+import type { ExtensionContext } from "vscode"
+import { providerIdentifiers, type GlobalState, type ModelInfo, type ProviderSettings } from "@roo-code/types"
+import { TelemetryService } from "@roo-code/telemetry"
+
+import { Task } from "../Task"
+import { ClineProvider } from "../../webview/ClineProvider"
+import { ContextProxy } from "../../config/ContextProxy"
+import { WebviewFocusTracker } from "../../webview/WebviewFocusTracker"
+import type { RequestPolicySnapshot } from "../../prompts/tools/effective-tool-policy"
+import type { ApiStreamChunk } from "../../../api/transform/stream"
+import { asyncStreamFrom } from "../../../test-utils/stream"
+import { BACKGROUND_CHILD_DISABLED_TOOLS, BACKGROUND_CHILD_EXPERIMENTS } from "../../background-subtasks/policy"
+
+// Mock delay before any imports that might use it
+vi.mock("delay", () => ({
+ __esModule: true,
+ default: vi.fn().mockResolvedValue(undefined),
+}))
+
+vi.mock("uuid", async (importOriginal) => {
+ const actual = await importOriginal()
+ return {
+ ...actual,
+ v7: vi.fn(() => "00000000-0000-7000-8000-000000000000"),
+ }
+})
+
+vi.mock("execa", () => ({
+ execa: vi.fn(),
+}))
+
+const mockMessages = [
+ {
+ ts: Date.now(),
+ type: "say",
+ say: "text",
+ text: "historical task",
+ },
+]
+
+vi.mock("fs/promises", async (importOriginal) => {
+ const actual = await importOriginal()
+ const mockFunctions = {
+ mkdir: vi.fn().mockResolvedValue(undefined),
+ writeFile: vi.fn().mockResolvedValue(undefined),
+ readFile: vi.fn().mockImplementation((filePath) => {
+ if (filePath.includes("ui_messages.json")) {
+ return Promise.resolve(JSON.stringify(mockMessages))
+ }
+ if (filePath.includes("api_conversation_history.json")) {
+ return Promise.resolve("[]")
+ }
+ return Promise.resolve("[]")
+ }),
+ unlink: vi.fn().mockResolvedValue(undefined),
+ rmdir: vi.fn().mockResolvedValue(undefined),
+ stat: vi.fn().mockRejectedValue({ code: "ENOENT" }),
+ readdir: vi.fn().mockResolvedValue([]),
+ }
+
+ return {
+ ...actual,
+ ...mockFunctions,
+ default: mockFunctions,
+ }
+})
+
+vi.mock("p-wait-for", () => ({
+ default: vi.fn().mockImplementation(async () => Promise.resolve()),
+}))
+
+// Task tests do not exercise indexing; keep workspace resolution and its cache out of this suite.
+vi.mock("../../../services/code-index/code-index-manager-registry", () => ({
+ CodeIndexManagerRegistry: {
+ getOrCreate: vi.fn().mockReturnValue(undefined),
+ getAllInstances: vi.fn().mockReturnValue([]),
+ disposeAll: vi.fn(),
+ },
+}))
+
+vi.mock("vscode", () => {
+ const mockDisposable = { dispose: vi.fn() }
+ const mockEventEmitter = { event: vi.fn(), fire: vi.fn() }
+ const mockTextDocument = { uri: { fsPath: "/mock/workspace/path/file.ts" } }
+ const mockTextEditor = { document: mockTextDocument }
+ const mockTab = { input: { uri: { fsPath: "/mock/workspace/path/file.ts" } } }
+ const mockTabGroup = { tabs: [mockTab] }
+
+ return {
+ TabInputTextDiff: vi.fn(),
+ CodeActionKind: {
+ QuickFix: { value: "quickfix" },
+ RefactorRewrite: { value: "refactor.rewrite" },
+ },
+ window: {
+ createTextEditorDecorationType: vi.fn().mockReturnValue({
+ dispose: vi.fn(),
+ }),
+ visibleTextEditors: [mockTextEditor],
+ tabGroups: {
+ all: [mockTabGroup],
+ close: vi.fn(),
+ onDidChangeTabs: vi.fn(() => ({ dispose: vi.fn() })),
+ },
+ showErrorMessage: vi.fn(),
+ },
+ workspace: {
+ workspaceFolders: [
+ {
+ uri: { fsPath: "/mock/workspace/path" },
+ name: "mock-workspace",
+ index: 0,
+ },
+ ],
+ createFileSystemWatcher: vi.fn(() => ({
+ onDidCreate: vi.fn(() => mockDisposable),
+ onDidDelete: vi.fn(() => mockDisposable),
+ onDidChange: vi.fn(() => mockDisposable),
+ dispose: vi.fn(),
+ })),
+ fs: {
+ stat: vi.fn().mockResolvedValue({ type: 1 }), // FileType.File = 1
+ },
+ onDidSaveTextDocument: vi.fn(() => mockDisposable),
+ getConfiguration: vi.fn(() => ({ get: (_key: string, defaultValue: unknown) => defaultValue })),
+ },
+ env: {
+ uriScheme: "vscode",
+ language: "en",
+ },
+ EventEmitter: vi.fn().mockImplementation(function () {
+ return mockEventEmitter
+ }),
+ Disposable: {
+ from: vi.fn(),
+ },
+ TabInputText: vi.fn(),
+ }
+})
+
+vi.mock("../../mentions", () => ({
+ parseMentions: vi.fn().mockImplementation((text) => {
+ return Promise.resolve({ text: `processed: ${text}`, mode: undefined, contentBlocks: [] })
+ }),
+ openMention: vi.fn(),
+ getLatestTerminalOutput: vi.fn(),
+}))
+
+vi.mock("../../../integrations/misc/extract-text", () => ({
+ extractTextFromFile: vi.fn().mockResolvedValue("Mock file content"),
+}))
+
+vi.mock("../../environment/getEnvironmentDetails", () => ({
+ getEnvironmentDetails: vi.fn().mockResolvedValue(""),
+}))
+
+vi.mock("../../ignore/RooIgnoreController")
+
+vi.mock("../../../i18n", () => {
+ return {
+ t: (key: string, args?: Record) => {
+ if (key === "tools:missingToolParameterWithPath") {
+ return `${args?.toolName}|${args?.relPath}|${args?.paramName}`
+ }
+ if (key === "tools:missingToolParameter") {
+ return `${args?.toolName}|${args?.paramName}`
+ }
+ return key
+ },
+ }
+})
+
+// Mock storagePathManager to prevent dynamic import issues.
+vi.mock("../../../utils/storage", () => ({
+ getTaskDirectoryPath: vi
+ .fn()
+ .mockImplementation((globalStoragePath, taskId) => Promise.resolve(`${globalStoragePath}/tasks/${taskId}`)),
+ getSettingsDirectoryPath: vi
+ .fn()
+ .mockImplementation((globalStoragePath) => Promise.resolve(`${globalStoragePath}/settings`)),
+}))
+
+vi.mock("../../../utils/fs", () => ({
+ fileExistsAtPath: vi.fn().mockImplementation((filePath) => {
+ return filePath.includes("ui_messages.json") || filePath.includes("api_conversation_history.json")
+ }),
+}))
+
+// Model-info stand-in: the settled snapshot only needs a defined ModelInfo.
+const stubModelInfo: ModelInfo = {
+ contextWindow: 200_000,
+ maxTokens: 4096,
+ supportsPromptCache: true,
+}
+
+type TaskTestAccess = {
+ getSystemPrompt: (requestState: ProviderState | undefined, requestModelInfo?: ModelInfo) => Promise
+ safeEnsureModelFetched: () => Promise
+ requestPolicySnapshot?: RequestPolicySnapshot
+}
+
+type ProviderState = Awaited>
+
+function getTaskTestAccess(task: Task): TaskTestAccess {
+ return task as unknown as TaskTestAccess
+}
+
+function requireDefined(value: T | null | undefined): T {
+ if (value == null) {
+ throw new Error("Expected test value to be defined")
+ }
+ return value
+}
+
+describe("background child tool policy in the request snapshot (D3)", () => {
+ let mockProvider: ClineProvider
+ let mockContextProxy: ContextProxy
+ let mockApiConfig: ProviderSettings
+ let mockExtensionContext: ExtensionContext
+
+ // Builds provider-state doubles on top of the real getState() result, so
+ // required fields stay compile-checked while each test states only its own
+ // overrides. mcpEnabled defaults to false so doubles skip the MCP-hub path.
+ let baseProviderState: ProviderState
+ const providerStateWith = (overrides: Partial = {}): ProviderState => ({
+ ...baseProviderState,
+ mcpEnabled: false,
+ ...overrides,
+ })
+
+ beforeEach(async () => {
+ if (!TelemetryService.hasInstance()) {
+ TelemetryService.createInstance([])
+ }
+
+ const storageUri = {
+ fsPath: path.join(os.tmpdir(), "test-storage"),
+ }
+
+ mockExtensionContext = {
+ globalState: {
+ get: vi.fn().mockImplementation((_key: keyof GlobalState) => undefined),
+ update: vi.fn().mockImplementation((_key, _value) => Promise.resolve()),
+ keys: vi.fn().mockReturnValue([]),
+ },
+ globalStorageUri: storageUri,
+ workspaceState: {
+ get: vi.fn().mockImplementation((_key) => undefined),
+ update: vi.fn().mockImplementation((_key, _value) => Promise.resolve()),
+ keys: vi.fn().mockReturnValue([]),
+ },
+ secrets: {
+ get: vi.fn().mockImplementation((_key) => Promise.resolve(undefined)),
+ store: vi.fn().mockImplementation((_key, _value) => Promise.resolve()),
+ delete: vi.fn().mockImplementation((_key) => Promise.resolve()),
+ },
+ extensionUri: {
+ fsPath: "/mock/extension/path",
+ },
+ extension: {
+ packageJSON: {
+ version: "1.0.0",
+ },
+ },
+ } as unknown as ExtensionContext
+
+ const mockOutputChannel = {
+ name: "test-output",
+ appendLine: vi.fn(),
+ append: vi.fn(),
+ replace: vi.fn(),
+ clear: vi.fn(),
+ show: vi.fn(),
+ hide: vi.fn(),
+ dispose: vi.fn(),
+ }
+
+ mockContextProxy = new ContextProxy(mockExtensionContext)
+ mockProvider = new ClineProvider(
+ mockExtensionContext,
+ mockOutputChannel,
+ "sidebar",
+ mockContextProxy,
+ new WebviewFocusTracker(),
+ )
+
+ mockApiConfig = {
+ apiProvider: providerIdentifiers.anthropic,
+ apiModelId: "claude-3-5-sonnet-20241022",
+ apiKey: "test-api-key",
+ }
+
+ mockProvider.postMessageToWebview = vi.fn().mockResolvedValue(undefined)
+ mockProvider.postStateToWebview = vi.fn().mockResolvedValue(undefined)
+ mockProvider.postStateToWebviewWithoutTaskHistory = vi.fn().mockResolvedValue(undefined)
+ mockProvider.postStateToWebviewThrottled = vi.fn().mockResolvedValue(undefined)
+ mockProvider.flushPostStateToWebviewThrottled = vi.fn().mockResolvedValue(undefined)
+
+ baseProviderState = await mockProvider.getState()
+ })
+
+ afterEach(() => {
+ vi.restoreAllMocks()
+ })
+
+ // Common seams so attemptApiRequest runs its capture and streams a first
+ // chunk without touching prompt building, context management, or UX.
+ function armRequestSeams(task: Task) {
+ vi.spyOn(getTaskTestAccess(task), "getSystemPrompt").mockResolvedValue("mock system prompt")
+ vi.spyOn(task, "getTokenUsage").mockReturnValue({
+ totalCost: 0,
+ totalTokensIn: 0,
+ totalTokensOut: 0,
+ contextTokens: 0,
+ })
+ vi.spyOn(task, "say").mockResolvedValue({ ts: 0, type: "say", say: "text", text: "" })
+ }
+
+ async function captureRequest(
+ requestTimeState: ProviderState,
+ backgroundToolPolicy?: ConstructorParameters[0]["backgroundToolPolicy"],
+ ): Promise<{ task: Task; snapshot: RequestPolicySnapshot; toolNames: string[] }> {
+ // Install the state read before construction: the constructor's mode
+ // initialization consumes the same request-time state the request will.
+ vi.spyOn(mockProvider, "getState").mockResolvedValue(requestTimeState)
+ const task = new Task({
+ provider: mockProvider,
+ apiConfiguration: mockApiConfig,
+ task: "test task",
+ startTask: false,
+ backgroundToolPolicy,
+ // P1-2: a LIVE background child is marked by the hosted flag, not by
+ // policy presence. Passing a policy here always means "live child".
+ backgroundChildHosted: backgroundToolPolicy !== undefined,
+ })
+ await task.getTaskMode()
+ armRequestSeams(task)
+ vi.spyOn(getTaskTestAccess(task), "safeEnsureModelFetched").mockResolvedValue(stubModelInfo)
+ const createMessageSpy = vi
+ .spyOn(task.api, "createMessage")
+ .mockReturnValue(asyncStreamFrom([{ type: "text", text: "ok" }]))
+
+ await task.attemptApiRequest(0).next()
+
+ const [, , metadata] = requireDefined(createMessageSpy.mock.calls[0])
+ const toolNames = requireDefined(metadata?.tools).map((tool) => {
+ if (tool.type !== "function") {
+ throw new Error(`Unexpected tool type: ${tool.type}`)
+ }
+ return tool.function.name
+ })
+
+ return {
+ task,
+ snapshot: requireDefined(getTaskTestAccess(task).requestPolicySnapshot),
+ toolNames,
+ }
+ }
+
+ it("marks the task as a background child and folds the block list into the snapshot as a state-first union", async () => {
+ const requestTimeState = providerStateWith({
+ autoApprovalEnabled: false,
+ disabledTools: ["read_file", "execute_command"],
+ experiments: { customTools: true, imageGeneration: true },
+ })
+
+ const { task, snapshot } = await captureRequest(requestTimeState, {
+ disabledTools: BACKGROUND_CHILD_DISABLED_TOOLS,
+ experiments: BACKGROUND_CHILD_EXPERIMENTS,
+ })
+
+ expect(task.isBackgroundSubtaskChild).toBe(true)
+ // State entries first, then the background entries, de-duplicated: the
+ // ambient execute_command must not appear twice.
+ expect(snapshot.disabledTools).toEqual([
+ "read_file",
+ "execute_command",
+ ...BACKGROUND_CHILD_DISABLED_TOOLS.filter((tool) => tool !== "execute_command"),
+ ])
+ // The background experiments win on conflict while ambient entries survive.
+ expect(snapshot.experiments).toEqual({ customTools: false, imageGeneration: true })
+ })
+
+ it("captures the snapshot from a fresh array, never aliasing the provider-state array", async () => {
+ const stateDisabledTools: ProviderState["disabledTools"] = ["read_file", "execute_command"]
+ const stateExperiments = { customTools: true }
+ const requestTimeState = providerStateWith({
+ autoApprovalEnabled: false,
+ disabledTools: stateDisabledTools,
+ experiments: stateExperiments,
+ })
+
+ const { snapshot } = await captureRequest(requestTimeState, {
+ disabledTools: BACKGROUND_CHILD_DISABLED_TOOLS,
+ experiments: BACKGROUND_CHILD_EXPERIMENTS,
+ })
+
+ // A later mutation of the snapshot (or of the state) must not write
+ // through into the other: the union is a fresh array and object.
+ expect(snapshot.disabledTools).not.toBe(stateDisabledTools)
+ expect(snapshot.experiments).not.toBe(stateExperiments)
+ expect(stateDisabledTools).toEqual(["read_file", "execute_command"])
+ expect(stateExperiments).toEqual({ customTools: true })
+ })
+
+ it("falls back to exactly the ambient state when no background policy is present", async () => {
+ const requestTimeState = providerStateWith({
+ autoApprovalEnabled: false,
+ disabledTools: ["read_file"],
+ experiments: { customTools: true },
+ })
+
+ const { task, snapshot } = await captureRequest(requestTimeState)
+
+ expect(task.isBackgroundSubtaskChild).toBe(false)
+ expect(snapshot.disabledTools).toEqual(["read_file"])
+ expect(snapshot.experiments).toEqual({ customTools: true })
+ // Byte-identical to the pre-D3 capture: same references, not copies, so
+ // a normal task's snapshot cannot drift from what it published before.
+ expect(snapshot.disabledTools).toBe(requestTimeState.disabledTools)
+ expect(snapshot.experiments).toBe(requestTimeState.experiments)
+ // No background entry may leak into a normal task's snapshot.
+ expect(snapshot.disabledTools).not.toContain("write_to_file")
+ })
+
+ it("never writes the background policy into provider state during capture", async () => {
+ const requestTimeState = providerStateWith({
+ autoApprovalEnabled: false,
+ disabledTools: ["read_file"],
+ experiments: { customTools: true },
+ })
+ const setValueSpy = vi.spyOn(mockContextProxy, "setValue")
+ const setValuesSpy = vi.spyOn(mockContextProxy, "setValues")
+ const providerSetValueSpy = vi.spyOn(mockProvider, "setValue")
+ const providerSetValuesSpy = vi.spyOn(mockProvider, "setValues")
+ const globalUpdateSpy = mockExtensionContext.globalState.update as ReturnType
+
+ await captureRequest(requestTimeState, {
+ disabledTools: BACKGROUND_CHILD_DISABLED_TOOLS,
+ experiments: BACKGROUND_CHILD_EXPERIMENTS,
+ })
+
+ const touchesPolicyKey = ([key]: unknown[]) => key === "disabledTools" || key === "experiments"
+ const writesPolicyKey = (values: unknown) => {
+ if (typeof values !== "object" || values === null) {
+ return false
+ }
+ const record = values as Record
+ return "disabledTools" in record || "experiments" in record
+ }
+ // Every write sink between the task and global storage must stay
+ // untouched by the fold: the policy is task-local by construction.
+ expect(globalUpdateSpy.mock.calls.some(touchesPolicyKey)).toBe(false)
+ expect(setValueSpy.mock.calls.some(touchesPolicyKey)).toBe(false)
+ expect(setValuesSpy.mock.calls.some(([values]) => writesPolicyKey(values))).toBe(false)
+ expect(providerSetValueSpy.mock.calls.some(touchesPolicyKey)).toBe(false)
+ expect(providerSetValuesSpy.mock.calls.some(([values]) => writesPolicyKey(values))).toBe(false)
+ })
+
+ it("drops every block-listed tool from the model-facing array a background child sends", async () => {
+ const stateForRequest = () =>
+ providerStateWith({
+ mode: "code",
+ autoApprovalEnabled: false,
+ disabledTools: [],
+ experiments: { customTools: true },
+ })
+
+ const normal = await captureRequest(stateForRequest())
+ const child = await captureRequest(stateForRequest(), {
+ disabledTools: BACKGROUND_CHILD_DISABLED_TOOLS,
+ experiments: BACKGROUND_CHILD_EXPERIMENTS,
+ })
+
+ // Non-vacuous control: code mode offers the writable, command, delegation,
+ // and question surfaces today, so their removal below is the block list
+ // doing work, not a mode that never granted them.
+ const blockedForNormalTasks = BACKGROUND_CHILD_DISABLED_TOOLS.filter((tool) => normal.toolNames.includes(tool))
+ expect(blockedForNormalTasks).toEqual(
+ expect.arrayContaining([
+ "write_to_file",
+ "execute_command",
+ "new_task",
+ "switch_mode",
+ "ask_followup_question",
+ ]),
+ )
+
+ for (const tool of blockedForNormalTasks) {
+ expect(child.toolNames).not.toContain(tool)
+ }
+ // The read-only surface and the completion exit still reach the model.
+ expect(child.toolNames).toEqual(expect.arrayContaining(["read_file", "attempt_completion"]))
+ })
+
+ it("keeps the model-facing tool array unchanged for a normal task", async () => {
+ const requestTimeState = providerStateWith({ mode: "code", autoApprovalEnabled: false, disabledTools: [] })
+
+ const { task, toolNames } = await captureRequest(requestTimeState)
+
+ expect(task.isBackgroundSubtaskChild).toBe(false)
+ expect(task.taskMode).toBe("code")
+ expect(toolNames).toEqual(expect.arrayContaining(["read_file", "write_to_file", "execute_command"]))
+ })
+})
diff --git a/src/core/task/__tests__/background-prompt-policy.spec.ts b/src/core/task/__tests__/background-prompt-policy.spec.ts
new file mode 100644
index 0000000000..632c9281f8
--- /dev/null
+++ b/src/core/task/__tests__/background-prompt-policy.spec.ts
@@ -0,0 +1,128 @@
+// npx vitest run core/task/__tests__/background-prompt-policy.spec.ts
+
+// F-10: a background child's system prompt must be built from the child's
+// effective tool policy (effectiveToolPolicy), exactly like the request's tool
+// arrays, so the prompt never advertises a tool the runtime blocks. These
+// tests capture the arguments Task.getSystemPrompt passes to SYSTEM_PROMPT.
+
+import { BACKGROUND_CHILD_DISABLED_TOOLS, BACKGROUND_CHILD_EXPERIMENTS } from "../../background-subtasks/policy"
+import { Task } from "../Task"
+
+const systemPromptMock = vi.hoisted(() => ({
+ capture: vi.fn((_context: unknown, ..._rest: unknown[]) => Promise.resolve("mock system prompt")),
+}))
+
+vi.mock("../../prompts/system", async (importOriginal) => {
+ const actual = await importOriginal()
+ return { ...actual, SYSTEM_PROMPT: systemPromptMock.capture }
+})
+
+type CapturedSystemPromptArgs = {
+ experiments: Record | undefined
+ disabledTools: string[] | undefined
+}
+
+/** Positional args of SYSTEM_PROMPT after (context, cwd, ...). */
+function lastCallArgs(): CapturedSystemPromptArgs {
+ const calls = systemPromptMock.capture.mock.calls
+ expect(calls.length).toBeGreaterThan(0)
+ const args = calls[calls.length - 1]
+ // The capture mock sees the args as unknown[]; these single casts pin the
+ // two SYSTEM_PROMPT parameters this spec asserts on.
+ return {
+ experiments: args[9] as Record | undefined,
+ disabledTools: args[16] as string[] | undefined,
+ }
+}
+
+function buildPromptTask(isBackgroundChild: boolean) {
+ const task = Object.create(Task.prototype) as Task
+ task["rooIgnoreController"] = undefined
+ Object.defineProperty(task, "cwd", { value: "/path/to/task-workspace" })
+ task["diffStrategy"] = undefined
+ task["api"] = { getModel: () => ({ id: "test-model" }) } as unknown as Task["api"]
+ task["getTaskMode"] = vi.fn(async () => "code")
+ const provider = {
+ context: {},
+ getSkillsManager: () => undefined,
+ }
+ // A double assertion is unavoidable here: `providerRef` is a `WeakRef`;
+ // the stub provides only the members getSystemPrompt dereferences.
+ task["providerRef"] = { deref: () => provider } as unknown as Task["providerRef"]
+ if (isBackgroundChild) {
+ Object.defineProperty(task, "isBackgroundSubtaskChild", { value: true })
+ Object.defineProperty(task, "backgroundToolPolicy", {
+ value: {
+ disabledTools: BACKGROUND_CHILD_DISABLED_TOOLS,
+ experiments: BACKGROUND_CHILD_EXPERIMENTS,
+ },
+ })
+ } else {
+ Object.defineProperty(task, "isBackgroundSubtaskChild", { value: false })
+ }
+ return task
+}
+
+describe("getSystemPrompt folds the background child's tool policy (F-10)", () => {
+ beforeEach(() => {
+ systemPromptMock.capture.mockClear()
+ })
+
+ it("passes the child's block list and experiment overrides for a background child", async () => {
+ const task = buildPromptTask(true)
+ const state = { mcpEnabled: false } as Parameters[0]
+
+ await task["getSystemPrompt"](state, {
+ contextWindow: 200_000,
+ maxTokens: 4096,
+ supportsPromptCache: true,
+ })
+
+ const { experiments, disabledTools } = lastCallArgs()
+ // The prompt must not advertise tools the child can never call.
+ expect(disabledTools).toEqual(expect.arrayContaining([...BACKGROUND_CHILD_DISABLED_TOOLS]))
+ expect(experiments?.customTools).toBe(false)
+ })
+
+ it("unions the child's policy with the user's global disabledTools", async () => {
+ const task = buildPromptTask(true)
+ const state = {
+ mcpEnabled: false,
+ disabledTools: ["readFile"],
+ experiments: { customTools: true },
+ } as unknown as Parameters[0]
+
+ await task["getSystemPrompt"](state, {
+ contextWindow: 200_000,
+ maxTokens: 4096,
+ supportsPromptCache: true,
+ })
+
+ const { experiments, disabledTools } = lastCallArgs()
+ // At least as restrictive as the user's own policy, never less: both the
+ // state's entry and every policy entry are present, and the policy's
+ // experiment override wins on conflict.
+ expect(disabledTools).toEqual(expect.arrayContaining(["readFile", "write_to_file", "execute_command"]))
+ expect(disabledTools?.indexOf("readFile")).toBeLessThan(disabledTools?.indexOf("write_to_file") ?? -1)
+ expect(experiments?.customTools).toBe(false)
+ })
+
+ it("passes the state's own values through for a non-background task", async () => {
+ const task = buildPromptTask(false)
+ const state = {
+ mcpEnabled: false,
+ disabledTools: ["write_to_file"],
+ experiments: { customTools: true },
+ } as unknown as Parameters[0]
+
+ await task["getSystemPrompt"](state, {
+ contextWindow: 200_000,
+ maxTokens: 4096,
+ supportsPromptCache: true,
+ })
+
+ const { experiments, disabledTools } = lastCallArgs()
+ expect(disabledTools).toEqual(["write_to_file"])
+ expect(experiments).toEqual({ customTools: true })
+ })
+})
diff --git a/src/core/task/__tests__/background-restored-child.spec.ts b/src/core/task/__tests__/background-restored-child.spec.ts
new file mode 100644
index 0000000000..8e179f0ca8
--- /dev/null
+++ b/src/core/task/__tests__/background-restored-child.spec.ts
@@ -0,0 +1,488 @@
+// npx vitest run core/task/__tests__/background-restored-child.spec.ts
+
+import * as os from "os"
+import * as path from "path"
+
+import pWaitFor from "p-wait-for"
+import type { ExtensionContext } from "vscode"
+import { providerIdentifiers, type GlobalState, type ModelInfo, type ProviderSettings } from "@roo-code/types"
+import { TelemetryService } from "@roo-code/telemetry"
+
+import { Task } from "../Task"
+import { setAbortLatch } from "../../../test-utils/run-state"
+import { ClineProvider } from "../../webview/ClineProvider"
+import { ContextProxy } from "../../config/ContextProxy"
+import { WebviewFocusTracker } from "../../webview/WebviewFocusTracker"
+import type { ApiStreamChunk } from "../../../api/transform/stream"
+import { asyncStreamFrom } from "../../../test-utils/stream"
+import { BACKGROUND_CHILD_DISABLED_TOOLS, BACKGROUND_CHILD_EXPERIMENTS } from "../../background-subtasks/policy"
+
+// Mock delay before any imports that might use it
+vi.mock("delay", () => ({
+ __esModule: true,
+ default: vi.fn().mockResolvedValue(undefined),
+}))
+
+vi.mock("uuid", async (importOriginal) => {
+ const actual = await importOriginal()
+ return {
+ ...actual,
+ v7: vi.fn(() => "00000000-0000-7000-8000-000000000000"),
+ }
+})
+
+vi.mock("execa", () => ({
+ execa: vi.fn(),
+}))
+
+vi.mock("fs/promises", async (importOriginal) => {
+ const actual = await importOriginal()
+ const mockFunctions = {
+ mkdir: vi.fn().mockResolvedValue(undefined),
+ writeFile: vi.fn().mockResolvedValue(undefined),
+ readFile: vi.fn().mockResolvedValue("[]"),
+ unlink: vi.fn().mockResolvedValue(undefined),
+ rmdir: vi.fn().mockResolvedValue(undefined),
+ stat: vi.fn().mockRejectedValue({ code: "ENOENT" }),
+ readdir: vi.fn().mockResolvedValue([]),
+ }
+
+ return {
+ ...actual,
+ ...mockFunctions,
+ default: mockFunctions,
+ }
+})
+
+vi.mock("p-wait-for", () => ({
+ default: vi.fn().mockImplementation(async () => Promise.resolve()),
+}))
+
+vi.mock("../../../services/code-index/code-index-manager-registry", () => ({
+ CodeIndexManagerRegistry: {
+ getOrCreate: vi.fn().mockReturnValue(undefined),
+ getAllInstances: vi.fn().mockReturnValue([]),
+ disposeAll: vi.fn(),
+ },
+}))
+
+vi.mock("vscode", () => {
+ const mockDisposable = { dispose: vi.fn() }
+ const mockEventEmitter = { event: vi.fn(), fire: vi.fn() }
+
+ return {
+ TabInputTextDiff: vi.fn(),
+ CodeActionKind: {
+ QuickFix: { value: "quickfix" },
+ RefactorRewrite: { value: "refactor.rewrite" },
+ },
+ window: {
+ createTextEditorDecorationType: vi.fn().mockReturnValue({ dispose: vi.fn() }),
+ visibleTextEditors: [],
+ tabGroups: { all: [], close: vi.fn(), onDidChangeTabs: vi.fn(() => ({ dispose: vi.fn() })) },
+ showErrorMessage: vi.fn(),
+ },
+ workspace: {
+ workspaceFolders: [{ uri: { fsPath: "/mock/workspace/path" }, name: "mock-workspace", index: 0 }],
+ createFileSystemWatcher: vi.fn(() => ({
+ onDidCreate: vi.fn(() => mockDisposable),
+ onDidDelete: vi.fn(() => mockDisposable),
+ onDidChange: vi.fn(() => mockDisposable),
+ dispose: vi.fn(),
+ })),
+ fs: { stat: vi.fn().mockResolvedValue({ type: 1 }) },
+ onDidSaveTextDocument: vi.fn(() => mockDisposable),
+ getConfiguration: vi.fn(() => ({ get: (_key: string, defaultValue: unknown) => defaultValue })),
+ },
+ env: { uriScheme: "vscode", language: "en" },
+ EventEmitter: vi.fn().mockImplementation(function () {
+ return mockEventEmitter
+ }),
+ Disposable: { from: vi.fn() },
+ TabInputText: vi.fn(),
+ }
+})
+
+vi.mock("../../mentions", () => ({
+ parseMentions: vi.fn().mockImplementation((text) => {
+ return Promise.resolve({ text: `processed: ${text}`, mode: undefined, contentBlocks: [] })
+ }),
+ openMention: vi.fn(),
+ getLatestTerminalOutput: vi.fn(),
+}))
+
+vi.mock("../../../integrations/misc/extract-text", () => ({
+ extractTextFromFile: vi.fn().mockResolvedValue("Mock file content"),
+}))
+
+vi.mock("../../environment/getEnvironmentDetails", () => ({
+ getEnvironmentDetails: vi.fn().mockResolvedValue(""),
+}))
+
+vi.mock("../../ignore/RooIgnoreController")
+
+vi.mock("../../../i18n", () => {
+ return {
+ t: (key: string, args?: Record) => {
+ if (key === "tools:missingToolParameterWithPath") {
+ return `${args?.toolName}|${args?.relPath}|${args?.paramName}`
+ }
+ if (key === "tools:missingToolParameter") {
+ return `${args?.toolName}|${args?.paramName}`
+ }
+ return key
+ },
+ }
+})
+
+vi.mock("../../../utils/storage", () => ({
+ getTaskDirectoryPath: vi
+ .fn()
+ .mockImplementation((globalStoragePath, taskId) => Promise.resolve(`${globalStoragePath}/tasks/${taskId}`)),
+ getSettingsDirectoryPath: vi
+ .fn()
+ .mockImplementation((globalStoragePath) => Promise.resolve(`${globalStoragePath}/settings`)),
+}))
+
+vi.mock("../../../utils/fs", () => ({
+ fileExistsAtPath: vi.fn().mockReturnValue(false),
+}))
+
+const stubModelInfo: ModelInfo = {
+ contextWindow: 200_000,
+ maxTokens: 4096,
+ supportsPromptCache: true,
+}
+
+type TaskSeams = {
+ getSystemPrompt: (requestState: ProviderState | undefined, requestModelInfo?: ModelInfo) => Promise
+ safeEnsureModelFetched: () => Promise
+}
+
+type ProviderState = Awaited>
+
+function getTaskSeams(task: Task): TaskSeams {
+ return task as unknown as TaskSeams
+}
+
+const backgroundPolicy: ConstructorParameters[0]["backgroundToolPolicy"] = {
+ disabledTools: BACKGROUND_CHILD_DISABLED_TOOLS,
+ experiments: BACKGROUND_CHILD_EXPERIMENTS,
+}
+
+describe("restored background child stays interactive but read-only (P1-2)", () => {
+ let mockProvider: ClineProvider
+ let mockContextProxy: ContextProxy
+ let mockApiConfig: ProviderSettings
+ let baseProviderState!: ProviderState
+ // Every task built by buildRestoredTask/buildHostedChild, so afterEach can
+ // dispose them. The builders construct Task objects directly and never
+ // register them with the provider, so provider disposal alone cannot
+ // reach them.
+ let builtTasks: Task[] = []
+
+ const providerStateWith = (overrides: Partial = {}): ProviderState => ({
+ ...baseProviderState,
+ mcpEnabled: false,
+ ...overrides,
+ })
+
+ beforeEach(() => {
+ if (!TelemetryService.hasInstance()) {
+ TelemetryService.createInstance([])
+ }
+
+ const storageUri = { fsPath: path.join(os.tmpdir(), "test-storage") }
+
+ const mockExtensionContext = {
+ globalState: {
+ get: vi.fn().mockImplementation((_key: keyof GlobalState) => undefined),
+ update: vi.fn().mockImplementation((_key, _value) => Promise.resolve()),
+ keys: vi.fn().mockReturnValue([]),
+ },
+ globalStorageUri: storageUri,
+ workspaceState: {
+ get: vi.fn().mockImplementation((_key) => undefined),
+ update: vi.fn().mockImplementation((_key, _value) => Promise.resolve()),
+ keys: vi.fn().mockReturnValue([]),
+ },
+ secrets: {
+ get: vi.fn().mockImplementation((_key) => Promise.resolve(undefined)),
+ store: vi.fn().mockImplementation((_key, _value) => Promise.resolve()),
+ delete: vi.fn().mockImplementation((_key) => Promise.resolve()),
+ },
+ extensionUri: { fsPath: "/mock/extension/path" },
+ extension: { packageJSON: { version: "1.0.0" } },
+ } as unknown as ExtensionContext
+
+ const mockOutputChannel = {
+ name: "test-output",
+ appendLine: vi.fn(),
+ append: vi.fn(),
+ replace: vi.fn(),
+ clear: vi.fn(),
+ show: vi.fn(),
+ hide: vi.fn(),
+ dispose: vi.fn(),
+ }
+
+ mockContextProxy = new ContextProxy(mockExtensionContext)
+ mockProvider = new ClineProvider(
+ mockExtensionContext,
+ mockOutputChannel,
+ "sidebar",
+ mockContextProxy,
+ new WebviewFocusTracker(),
+ )
+
+ mockApiConfig = {
+ apiProvider: providerIdentifiers.anthropic,
+ apiModelId: "claude-3-5-sonnet-20241022",
+ apiKey: "test-api-key",
+ }
+
+ mockProvider.postMessageToWebview = vi.fn().mockResolvedValue(undefined)
+ mockProvider.postStateToWebview = vi.fn().mockResolvedValue(undefined)
+ mockProvider.postStateToWebviewWithoutTaskHistory = vi.fn().mockResolvedValue(undefined)
+ mockProvider.postStateToWebviewThrottled = vi.fn().mockResolvedValue(undefined)
+ mockProvider.flushPostStateToWebviewThrottled = vi.fn().mockResolvedValue(undefined)
+ })
+
+ afterEach(async () => {
+ // Dispose every task this suite built, including after a failed
+ // assertion: the builders never register their tasks with the provider,
+ // so provider disposal alone cannot release them. Disposal runs before
+ // restoreAllMocks so the module mocks (fs, storage paths) are still in
+ // place for it, and a rejecting dispose must not mask the assertion
+ // failure under test.
+ //
+ // `Task.dispose()` writes to the console, so teardown emits
+ // worker->parent console RPCs while the worker is closing. Vitest
+ // reports that as `EnvironmentTeardownError: Closing rpc while
+ // "onUserConsoleLog" was pending` and exits non-zero even though every
+ // test passed. The repo runs with `silent: true`, so silencing it here
+ // drops no diagnostic.
+ const consoleQuiet = ["log", "info", "warn", "error", "debug"].map((key) =>
+ vi.spyOn(console, key as "log").mockImplementation(() => {}),
+ )
+ try {
+ for (const task of builtTasks) {
+ await task.dispose().catch(() => {})
+ }
+ builtTasks = []
+ await mockProvider.dispose().catch(() => {})
+ } finally {
+ for (const spy of consoleQuiet) {
+ spy.mockRestore()
+ }
+ }
+ vi.restoreAllMocks()
+ })
+
+ // A restored background child: the restore path (ClineProvider
+ // createTaskWithHistoryItemUnlocked) passes the read-only policy but never
+ // the hosted flag. This builder mirrors that exact construction.
+ async function buildRestoredTask() {
+ vi.spyOn(mockProvider, "getState").mockResolvedValue(
+ providerStateWith({ mode: "code", autoApprovalEnabled: false }),
+ )
+ const task = new Task({
+ provider: mockProvider,
+ apiConfiguration: mockApiConfig,
+ task: "test task",
+ startTask: false,
+ backgroundToolPolicy: backgroundPolicy,
+ // No backgroundChildHosted: the restore path never sets it.
+ })
+ // Track before the first await so a throw in getTaskMode still leaves a
+ // reachable task for afterEach disposal.
+ builtTasks.push(task)
+ await task.getTaskMode()
+ return task
+ }
+
+ // A LIVE background child for contrast: same policy plus the hosted flag.
+ async function buildHostedChild() {
+ vi.spyOn(mockProvider, "getState").mockResolvedValue(
+ providerStateWith({ mode: "code", autoApprovalEnabled: false }),
+ )
+ const task = new Task({
+ provider: mockProvider,
+ apiConfiguration: mockApiConfig,
+ task: "test task",
+ startTask: false,
+ backgroundToolPolicy: backgroundPolicy,
+ backgroundChildHosted: true,
+ })
+ // Track before the first await so a throw in getTaskMode still leaves a
+ // reachable task for afterEach disposal.
+ builtTasks.push(task)
+ await task.getTaskMode()
+ return task
+ }
+
+ function armRequestSeams(task: Task) {
+ const seams = getTaskSeams(task)
+ vi.spyOn(seams, "getSystemPrompt").mockResolvedValue("mock system prompt")
+ vi.spyOn(seams, "safeEnsureModelFetched").mockResolvedValue(stubModelInfo)
+ const createMessageSpy = vi
+ .spyOn(task.api, "createMessage")
+ .mockReturnValue(asyncStreamFrom([{ type: "text", text: "ok" }]))
+ vi.spyOn(task, "getTokenUsage").mockReturnValue({
+ totalCost: 0,
+ totalTokensIn: 0,
+ totalTokensOut: 0,
+ contextTokens: 0,
+ })
+ task["diffViewProvider"] = { reset: vi.fn() } as unknown as Task["diffViewProvider"]
+ vi.mocked(mockProvider.postStateToWebviewWithoutTaskHistory).mockClear()
+ return createMessageSpy
+ }
+
+ it("is interactive: the policy alone does not flag it as a background child", async () => {
+ const restored = await buildRestoredTask()
+ const hosted = await buildHostedChild()
+
+ expect(restored.isBackgroundSubtaskChild).toBe(false)
+ expect(hosted.isBackgroundSubtaskChild).toBe(true)
+ // Both carry the policy; only the derivation differs.
+ expect(restored["backgroundToolPolicy"]).toEqual(backgroundPolicy)
+ })
+
+ it("keeps the read-only policy at the tool layer (write tools stay blocked)", async () => {
+ const restored = await buildRestoredTask()
+ const policy = restored["effectiveToolPolicy"]({ disabledTools: undefined, experiments: undefined })
+
+ expect(policy.disabledTools).toEqual(expect.arrayContaining([...BACKGROUND_CHILD_DISABLED_TOOLS]))
+ expect(policy.experiments).toEqual(BACKGROUND_CHILD_EXPERIMENTS)
+ expect(policy.disabledTools).toContain("write_to_file")
+ expect(policy.disabledTools).toContain("execute_command")
+ })
+
+ it("still withholds write tools from the model-facing tool array", async () => {
+ const restored = await buildRestoredTask()
+ const createMessageSpy = armRequestSeams(restored)
+
+ await restored.recursivelyMakeClineRequests([{ type: "text", text: "investigate" }])
+
+ const [, , metadata] = createMessageSpy.mock.calls[0] as [unknown, unknown, { tools?: unknown[] } | undefined]
+ const toolNames = (metadata?.tools ?? []).map((tool) => {
+ const functionTool = tool as { type: string; function: { name: string } }
+ return functionTool.function.name
+ })
+ expect(toolNames).not.toContain("write_to_file")
+ expect(toolNames).not.toContain("execute_command")
+ expect(toolNames).toEqual(expect.arrayContaining(["read_file", "attempt_completion"]))
+ })
+
+ it("posts state to the webview across a request iteration (nothing suppressed)", async () => {
+ const restored = await buildRestoredTask()
+ const createMessageSpy = armRequestSeams(restored)
+
+ await restored.recursivelyMakeClineRequests([{ type: "text", text: "investigate" }])
+
+ // A LIVE child would post nothing here (the F-11 guards); a restored
+ // child is the current interactive task, so its state must flow.
+ expect(createMessageSpy).toHaveBeenCalled()
+ expect(mockProvider.postStateToWebviewWithoutTaskHistory).toHaveBeenCalled()
+ })
+
+ it("its ask is not auto-resolved by the D4 seam (resolveBackgroundChildAsk is a no-op)", async () => {
+ const restored = await buildRestoredTask()
+ const hosted = await buildHostedChild()
+
+ // The D4 seam must leave the restored child's asks alone so they reach the
+ // interactive blocking path, while it still auto-resolves a hosted child's.
+ // (The seam is async since the M-1 canonical gate resolves realpaths.)
+ expect(
+ await restored["resolveBackgroundChildAsk"]("resume_task", { decision: "ask" }, undefined),
+ ).toBeUndefined()
+ expect(await restored["resolveBackgroundChildAsk"]("tool", { decision: "ask" }, "{}")).toBeUndefined()
+ expect(await hosted["resolveBackgroundChildAsk"]("resume_task", { decision: "ask" }, undefined)).toEqual({
+ response: "noButtonClicked",
+ })
+ })
+
+ it("its resume ask blocks for approval instead of auto-running", async () => {
+ // Drive the ask through the lightweight prototype seam (the same harness
+ // background-ask-policy uses): the restored child has
+ // isBackgroundSubtaskChild === false — proven from the real constructor in
+ // the test above — so the D4 seam is inert and the ask behaves like any
+ // interactive history task.
+ const provider = {
+ postMessageToWebview: vi.fn().mockResolvedValue(undefined),
+ postStateToWebviewWithoutTaskHistory: vi.fn().mockResolvedValue(undefined),
+ getSkillsManager: () => undefined,
+ cwd: "/mock/workspace/path",
+ getState: async () => ({ autoApprovalEnabled: false }),
+ }
+ const task = Object.create(Task.prototype) as Task
+ setAbortLatch(task, false)
+ task["clineMessages"] = []
+ task["askResponse"] = undefined
+ task["askResponseText"] = undefined
+ task["askResponseImages"] = undefined
+ task["lastMessageTs"] = undefined
+ task["addToClineMessages"] = vi.fn(async () => {})
+ task["saveClineMessages"] = vi.fn(async () => true)
+ task["updateClineMessage"] = vi.fn(async () => {})
+ task["cancelAutoApprovalTimeout"] = vi.fn(() => {})
+ task["checkpointSave"] = vi.fn(async () => {})
+ task["emit"] = vi.fn()
+ Object.defineProperty(task, "runRejections", { value: new Set() })
+ Object.defineProperty(task, "reportedDivergences", { value: new Set() })
+ task["providerRef"] = { deref: () => provider } as unknown as Task["providerRef"]
+ Object.defineProperty(task, "workspacePath", { value: "/mock/workspace/path" })
+ Object.defineProperty(task, "isBackgroundSubtaskChild", { value: false })
+ const { MessageQueueService } = await import("../../message-queue/MessageQueueService")
+ Object.defineProperty(task, "messageQueueService", { value: new MessageQueueService() })
+
+ // resume_task has no auto-approval mapping, so with the D4 seam inert the
+ // ask posts a chat row and blocks on the user, exactly like any interactive
+ // history task. A hosted child would instead resolve noButtonClicked
+ // instantly (before any chat row) and fall through to initiateTaskLoop —
+ // the P1-2 bug.
+ //
+ // This test must prove the blocking itself, so it engages the real
+ // p-wait-for waiter: the file-level mock resolves unconditionally, and
+ // approving from inside the row-post callback (as the previous revision
+ // did) would let the ask settle without ever waiting for approval.
+ const { default: realWaitFor } = await vi.importActual("p-wait-for")
+ vi.mocked(pWaitFor).mockImplementation(realWaitFor)
+
+ // The row post is the observable "the prompt is on screen" signal: wait
+ // for it, prove the ask promise is still pending, then answer.
+ let markRowPosted: () => void = () => {}
+ const rowPosted = new Promise((resolve) => {
+ markRowPosted = resolve
+ })
+ task["addToClineMessages"] = vi.fn(async () => {
+ markRowPosted()
+ })
+
+ const askPromise = task.ask("resume_task", "{}", false)
+ await Promise.race([rowPosted, askPromise])
+ expect(task["addToClineMessages"]).toHaveBeenCalledWith(
+ expect.objectContaining({ type: "ask", ask: "resume_task" }),
+ )
+ // The row posts exactly once: a second post would mean the ask resolved
+ // and re-asked, which is the auto-resolve bug this test guards.
+ expect(task["addToClineMessages"]).toHaveBeenCalledTimes(1)
+
+ // The only legitimate way this promise settles is the approval below:
+ // race it past one waiter poll interval and demand it is still pending.
+ const stillPending = Symbol("stillPending")
+ const outcome = await Promise.race([
+ askPromise.then(
+ () => "settled" as const,
+ () => "rejected" as const,
+ ),
+ new Promise((resolve) => setTimeout(() => resolve(stillPending), 250)),
+ ])
+ expect(outcome).toBe(stillPending)
+
+ task.approveAsk()
+ const result = await askPromise
+ expect(result.response).toBe("yesButtonClicked")
+ })
+})
diff --git a/src/core/task/__tests__/background-retry-bound.spec.ts b/src/core/task/__tests__/background-retry-bound.spec.ts
new file mode 100644
index 0000000000..01a9ea3a1e
--- /dev/null
+++ b/src/core/task/__tests__/background-retry-bound.spec.ts
@@ -0,0 +1,380 @@
+// npx vitest run core/task/__tests__/background-retry-bound.spec.ts
+
+import * as os from "os"
+import * as path from "path"
+
+import type { ExtensionContext } from "vscode"
+import { providerIdentifiers, type GlobalState, type ModelInfo, type ProviderSettings } from "@roo-code/types"
+import { TelemetryService } from "@roo-code/telemetry"
+
+import { Task } from "../Task"
+import { ClineProvider } from "../../webview/ClineProvider"
+import { ContextProxy } from "../../config/ContextProxy"
+import { WebviewFocusTracker } from "../../webview/WebviewFocusTracker"
+import type { ApiStreamChunk } from "../../../api/transform/stream"
+import { asyncStreamFrom } from "../../../test-utils/stream"
+import { BACKGROUND_CHILD_DISABLED_TOOLS, BACKGROUND_CHILD_EXPERIMENTS } from "../../background-subtasks/policy"
+
+// Mock delay before any imports that might use it (backoffAndAnnounce awaits it)
+vi.mock("delay", () => ({
+ __esModule: true,
+ default: vi.fn().mockResolvedValue(undefined),
+}))
+
+vi.mock("uuid", async (importOriginal) => {
+ const actual = await importOriginal()
+ return {
+ ...actual,
+ v7: vi.fn(() => "00000000-0000-7000-8000-000000000000"),
+ }
+})
+
+vi.mock("execa", () => ({
+ execa: vi.fn(),
+}))
+
+vi.mock("fs/promises", async (importOriginal) => {
+ const actual = await importOriginal()
+ const mockFunctions = {
+ mkdir: vi.fn().mockResolvedValue(undefined),
+ writeFile: vi.fn().mockResolvedValue(undefined),
+ readFile: vi.fn().mockResolvedValue("[]"),
+ unlink: vi.fn().mockResolvedValue(undefined),
+ rmdir: vi.fn().mockResolvedValue(undefined),
+ stat: vi.fn().mockRejectedValue({ code: "ENOENT" }),
+ readdir: vi.fn().mockResolvedValue([]),
+ }
+
+ return {
+ ...actual,
+ ...mockFunctions,
+ default: mockFunctions,
+ }
+})
+
+vi.mock("p-wait-for", () => ({
+ default: vi.fn().mockImplementation(async () => Promise.resolve()),
+}))
+
+vi.mock("../../../services/code-index/code-index-manager-registry", () => ({
+ CodeIndexManagerRegistry: {
+ getOrCreate: vi.fn().mockReturnValue(undefined),
+ getAllInstances: vi.fn().mockReturnValue([]),
+ disposeAll: vi.fn(),
+ },
+}))
+
+vi.mock("vscode", () => {
+ const mockDisposable = { dispose: vi.fn() }
+ const mockEventEmitter = { event: vi.fn(), fire: vi.fn() }
+
+ return {
+ TabInputTextDiff: vi.fn(),
+ CodeActionKind: {
+ QuickFix: { value: "quickfix" },
+ RefactorRewrite: { value: "refactor.rewrite" },
+ },
+ window: {
+ createTextEditorDecorationType: vi.fn().mockReturnValue({ dispose: vi.fn() }),
+ visibleTextEditors: [],
+ tabGroups: { all: [], close: vi.fn(), onDidChangeTabs: vi.fn(() => ({ dispose: vi.fn() })) },
+ showErrorMessage: vi.fn(),
+ },
+ workspace: {
+ workspaceFolders: [{ uri: { fsPath: "/mock/workspace/path" }, name: "mock-workspace", index: 0 }],
+ createFileSystemWatcher: vi.fn(() => ({
+ onDidCreate: vi.fn(() => mockDisposable),
+ onDidDelete: vi.fn(() => mockDisposable),
+ onDidChange: vi.fn(() => mockDisposable),
+ dispose: vi.fn(),
+ })),
+ fs: { stat: vi.fn().mockResolvedValue({ type: 1 }) },
+ onDidSaveTextDocument: vi.fn(() => mockDisposable),
+ getConfiguration: vi.fn(() => ({ get: (_key: string, defaultValue: unknown) => defaultValue })),
+ },
+ env: { uriScheme: "vscode", language: "en" },
+ EventEmitter: vi.fn().mockImplementation(function () {
+ return mockEventEmitter
+ }),
+ Disposable: { from: vi.fn() },
+ TabInputText: vi.fn(),
+ }
+})
+
+vi.mock("../../mentions", () => ({
+ parseMentions: vi.fn().mockImplementation((text) => {
+ return Promise.resolve({ text: `processed: ${text}`, mode: undefined, contentBlocks: [] })
+ }),
+ openMention: vi.fn(),
+ getLatestTerminalOutput: vi.fn(),
+}))
+
+vi.mock("../../../integrations/misc/extract-text", () => ({
+ extractTextFromFile: vi.fn().mockResolvedValue("Mock file content"),
+}))
+
+vi.mock("../../environment/getEnvironmentDetails", () => ({
+ getEnvironmentDetails: vi.fn().mockResolvedValue(""),
+}))
+
+vi.mock("../../ignore/RooIgnoreController")
+
+vi.mock("../../../i18n", () => {
+ return {
+ t: (key: string, args?: Record) => {
+ if (key === "tools:missingToolParameterWithPath") {
+ return `${args?.toolName}|${args?.relPath}|${args?.paramName}`
+ }
+ if (key === "tools:missingToolParameter") {
+ return `${args?.toolName}|${args?.paramName}`
+ }
+ return key
+ },
+ }
+})
+
+vi.mock("../../../utils/storage", () => ({
+ getTaskDirectoryPath: vi
+ .fn()
+ .mockImplementation((globalStoragePath, taskId) => Promise.resolve(`${globalStoragePath}/tasks/${taskId}`)),
+ getSettingsDirectoryPath: vi
+ .fn()
+ .mockImplementation((globalStoragePath) => Promise.resolve(`${globalStoragePath}/settings`)),
+}))
+
+vi.mock("../../../utils/fs", () => ({
+ fileExistsAtPath: vi.fn().mockReturnValue(false),
+}))
+
+const stubModelInfo: ModelInfo = {
+ contextWindow: 200_000,
+ maxTokens: 4096,
+ supportsPromptCache: true,
+}
+
+type TaskSeams = {
+ getSystemPrompt: (requestState: ProviderState | undefined, requestModelInfo?: ModelInfo) => Promise
+ safeEnsureModelFetched: () => Promise
+}
+
+type ProviderState = Awaited>
+
+function getTaskSeams(task: Task): TaskSeams {
+ return task as unknown as TaskSeams
+}
+
+const backgroundPolicy: ConstructorParameters[0]["backgroundToolPolicy"] = {
+ disabledTools: BACKGROUND_CHILD_DISABLED_TOOLS,
+ experiments: BACKGROUND_CHILD_EXPERIMENTS,
+}
+
+// The retry bound a background child is allowed before the terminal fires; the
+// run makes the initial request plus this many retries, so a persistently
+// failing path issues exactly MAX + 1 API calls (P1-1).
+const MAX_ATTEMPTS = 3
+
+function emptyStream(): AsyncGenerator {
+ return asyncStreamFrom([])
+}
+
+async function* midStreamFailure(chunksBeforeFailure: ApiStreamChunk[]): AsyncGenerator {
+ for (const chunk of chunksBeforeFailure) {
+ yield chunk
+ }
+ throw new Error("stream terminated mid-flight")
+}
+
+async function* firstChunkFailure(): AsyncGenerator {
+ throw new Error("first chunk failed")
+ yield { type: "text", text: "unreachable" }
+}
+
+describe("background child retry bound (P1-1)", () => {
+ let mockProvider: ClineProvider
+ let mockContextProxy: ContextProxy
+ let mockApiConfig: ProviderSettings
+ let baseProviderState!: ProviderState
+
+ const providerStateWith = (overrides: Partial = {}): ProviderState => ({
+ ...baseProviderState,
+ mcpEnabled: false,
+ ...overrides,
+ })
+
+ beforeEach(() => {
+ if (!TelemetryService.hasInstance()) {
+ TelemetryService.createInstance([])
+ }
+
+ const storageUri = { fsPath: path.join(os.tmpdir(), "test-storage") }
+
+ const mockExtensionContext = {
+ globalState: {
+ get: vi.fn().mockImplementation((_key: keyof GlobalState) => undefined),
+ update: vi.fn().mockImplementation((_key, _value) => Promise.resolve()),
+ keys: vi.fn().mockReturnValue([]),
+ },
+ globalStorageUri: storageUri,
+ workspaceState: {
+ get: vi.fn().mockImplementation((_key) => undefined),
+ update: vi.fn().mockImplementation((_key, _value) => Promise.resolve()),
+ keys: vi.fn().mockReturnValue([]),
+ },
+ secrets: {
+ get: vi.fn().mockImplementation((_key) => Promise.resolve(undefined)),
+ store: vi.fn().mockImplementation((_key, _value) => Promise.resolve()),
+ delete: vi.fn().mockImplementation((_key) => Promise.resolve()),
+ },
+ extensionUri: { fsPath: "/mock/extension/path" },
+ extension: { packageJSON: { version: "1.0.0" } },
+ } as unknown as ExtensionContext
+
+ const mockOutputChannel = {
+ name: "test-output",
+ appendLine: vi.fn(),
+ append: vi.fn(),
+ replace: vi.fn(),
+ clear: vi.fn(),
+ show: vi.fn(),
+ hide: vi.fn(),
+ dispose: vi.fn(),
+ }
+
+ mockContextProxy = new ContextProxy(mockExtensionContext)
+ mockProvider = new ClineProvider(
+ mockExtensionContext,
+ mockOutputChannel,
+ "sidebar",
+ mockContextProxy,
+ new WebviewFocusTracker(),
+ )
+
+ mockApiConfig = {
+ apiProvider: providerIdentifiers.anthropic,
+ apiModelId: "claude-3-5-sonnet-20241022",
+ apiKey: "test-api-key",
+ }
+
+ mockProvider.postMessageToWebview = vi.fn().mockResolvedValue(undefined)
+ mockProvider.postStateToWebview = vi.fn().mockResolvedValue(undefined)
+ mockProvider.postStateToWebviewWithoutTaskHistory = vi.fn().mockResolvedValue(undefined)
+ mockProvider.postStateToWebviewThrottled = vi.fn().mockResolvedValue(undefined)
+ mockProvider.flushPostStateToWebviewThrottled = vi.fn().mockResolvedValue(undefined)
+ })
+
+ afterEach(() => {
+ vi.restoreAllMocks()
+ })
+
+ async function buildTask(isBackgroundChild: boolean, autoApprovalEnabled: boolean) {
+ vi.spyOn(mockProvider, "getState").mockResolvedValue(providerStateWith({ mode: "code", autoApprovalEnabled }))
+ const task = new Task({
+ provider: mockProvider,
+ apiConfiguration: mockApiConfig,
+ task: "test task",
+ startTask: false,
+ backgroundToolPolicy: isBackgroundChild ? backgroundPolicy : undefined,
+ backgroundChildHosted: isBackgroundChild,
+ })
+ await task.getTaskMode()
+ return task
+ }
+
+ function armRequestSeams(task: Task, makeStream: () => AsyncGenerator) {
+ const seams = getTaskSeams(task)
+ vi.spyOn(seams, "getSystemPrompt").mockResolvedValue("mock system prompt")
+ vi.spyOn(seams, "safeEnsureModelFetched").mockResolvedValue(stubModelInfo)
+ const createMessageSpy = vi.spyOn(task.api, "createMessage").mockImplementation(() => makeStream())
+ vi.spyOn(task, "getTokenUsage").mockReturnValue({
+ totalCost: 0,
+ totalTokensIn: 0,
+ totalTokensOut: 0,
+ contextTokens: 0,
+ })
+ task["diffViewProvider"] = { reset: vi.fn() } as unknown as Task["diffViewProvider"]
+ return createMessageSpy
+ }
+
+ it("noteBackgroundChildRetry terminates a hosted child past the cap and is a no-op for a normal task", async () => {
+ const hosted = await buildTask(true, true)
+ const normal = await buildTask(false, true)
+
+ for (let i = 0; i < MAX_ATTEMPTS; i++) {
+ expect(() => hosted["noteBackgroundChildRetry"]()).not.toThrow()
+ }
+ expect(hosted.backgroundChildRetryCount).toBe(MAX_ATTEMPTS)
+ expect(hosted.abandoned).toBe(false)
+
+ // The next retry crosses the bound: requestAbort(true) + throw, exactly
+ // like the mistake-limit terminal.
+ expect(() => hosted["noteBackgroundChildRetry"]()).toThrow(/exceeded the automatic retry limit/)
+ expect(hosted.abandoned).toBe(true)
+ expect(hosted.backgroundChildRetryCount).toBe(MAX_ATTEMPTS + 1)
+
+ // A normal task never counts and never aborts, however many retries.
+ for (let i = 0; i < MAX_ATTEMPTS + 5; i++) {
+ expect(() => normal["noteBackgroundChildRetry"]()).not.toThrow()
+ }
+ expect(normal.backgroundChildRetryCount).toBe(0)
+ expect(normal.abandoned).toBe(false)
+ })
+
+ it("path (a): persistent empty assistant responses terminate the child after the cap", async () => {
+ const task = await buildTask(true, true) // auto-approval ON: the looping branch
+ const createMessageSpy = armRequestSeams(task, emptyStream)
+
+ await task.recursivelyMakeClineRequests([{ type: "text", text: "investigate" }])
+
+ // The run settles (the terminal throw is swallowed into didEndLoop), the
+ // child is aborted, and the API calls are bounded at MAX + 1, not infinite.
+ expect(task.abandoned).toBe(true)
+ expect(task.backgroundChildRetryCount).toBe(MAX_ATTEMPTS + 1)
+ expect(createMessageSpy).toHaveBeenCalledTimes(MAX_ATTEMPTS + 1)
+ })
+
+ it("path (b): persistent mid-stream failures terminate the child after the cap", async () => {
+ const task = await buildTask(true, true)
+ const createMessageSpy = armRequestSeams(task, () => midStreamFailure([{ type: "text", text: "partial" }]))
+
+ await task.recursivelyMakeClineRequests([{ type: "text", text: "investigate" }])
+
+ expect(task.abandoned).toBe(true)
+ expect(task.backgroundChildRetryCount).toBe(MAX_ATTEMPTS + 1)
+ expect(createMessageSpy).toHaveBeenCalledTimes(MAX_ATTEMPTS + 1)
+ })
+
+ it("path (c): persistent first-chunk failures terminate the child after the cap", async () => {
+ const task = await buildTask(true, true) // auto-approval ON: the looping branch
+ const createMessageSpy = armRequestSeams(task, firstChunkFailure)
+
+ await task.recursivelyMakeClineRequests([{ type: "text", text: "investigate" }])
+
+ expect(task.abandoned).toBe(true)
+ expect(task.backgroundChildRetryCount).toBe(MAX_ATTEMPTS + 1)
+ expect(createMessageSpy).toHaveBeenCalledTimes(MAX_ATTEMPTS + 1)
+ })
+
+ it("a normal task is unaffected: the retry bound never engages on the empty path", async () => {
+ // Auto-approval ON, empty stream. A normal task must NOT terminate at the
+ // cap. The drive is otherwise unbounded, so end it manually once it has
+ // already retried more times than a child is allowed.
+ const task = await buildTask(false, true)
+ let calls = 0
+ const createMessageSpy = armRequestSeams(task, () => {
+ calls += 1
+ if (calls === MAX_ATTEMPTS + 2) {
+ // The normal task is still healthy past the child's cap; stop the
+ // drive. This abort is the test's, not the retry bound's.
+ task.requestAbort(true)
+ }
+ return emptyStream()
+ })
+
+ await task.recursivelyMakeClineRequests([{ type: "text", text: "investigate" }])
+
+ // The retry bound never engaged: the counter stayed at 0 across more
+ // retries than the child cap, and every one of those retries issued.
+ expect(task.backgroundChildRetryCount).toBe(0)
+ expect(createMessageSpy).toHaveBeenCalledTimes(MAX_ATTEMPTS + 2)
+ })
+})
diff --git a/src/core/task/__tests__/background-stamp-reassert.spec.ts b/src/core/task/__tests__/background-stamp-reassert.spec.ts
new file mode 100644
index 0000000000..f5b540b154
--- /dev/null
+++ b/src/core/task/__tests__/background-stamp-reassert.spec.ts
@@ -0,0 +1,287 @@
+// npx vitest run core/task/__tests__/background-stamp-reassert.spec.ts
+
+import * as os from "os"
+import * as path from "path"
+
+import type { ExtensionContext } from "vscode"
+import { providerIdentifiers, type ClineMessage, type GlobalState, type ProviderSettings } from "@roo-code/types"
+import { TelemetryService } from "@roo-code/telemetry"
+
+import { Task } from "../Task"
+import { ClineProvider } from "../../webview/ClineProvider"
+import { ContextProxy } from "../../config/ContextProxy"
+import { WebviewFocusTracker } from "../../webview/WebviewFocusTracker"
+import { BACKGROUND_CHILD_DISABLED_TOOLS, BACKGROUND_CHILD_EXPERIMENTS } from "../../background-subtasks/policy"
+
+vi.mock("uuid", async (importOriginal) => {
+ const actual = await importOriginal()
+ return {
+ ...actual,
+ v7: vi.fn(() => "00000000-0000-7000-8000-000000000000"),
+ }
+})
+
+vi.mock("execa", () => ({
+ execa: vi.fn(),
+}))
+
+vi.mock("fs/promises", async (importOriginal) => {
+ const actual = await importOriginal()
+ const mockFunctions = {
+ mkdir: vi.fn().mockResolvedValue(undefined),
+ writeFile: vi.fn().mockResolvedValue(undefined),
+ readFile: vi.fn().mockResolvedValue("[]"),
+ unlink: vi.fn().mockResolvedValue(undefined),
+ rmdir: vi.fn().mockResolvedValue(undefined),
+ stat: vi.fn().mockRejectedValue({ code: "ENOENT" }),
+ readdir: vi.fn().mockResolvedValue([]),
+ }
+
+ return {
+ ...actual,
+ ...mockFunctions,
+ default: mockFunctions,
+ }
+})
+
+vi.mock("p-wait-for", () => ({
+ default: vi.fn().mockImplementation(async () => Promise.resolve()),
+}))
+
+vi.mock("../../../services/code-index/code-index-manager-registry", () => ({
+ CodeIndexManagerRegistry: {
+ getOrCreate: vi.fn().mockReturnValue(undefined),
+ getAllInstances: vi.fn().mockReturnValue([]),
+ disposeAll: vi.fn(),
+ },
+}))
+
+vi.mock("vscode", () => {
+ const mockDisposable = { dispose: vi.fn() }
+ const mockEventEmitter = { event: vi.fn(), fire: vi.fn() }
+
+ return {
+ TabInputTextDiff: vi.fn(),
+ CodeActionKind: {
+ QuickFix: { value: "quickfix" },
+ RefactorRewrite: { value: "refactor.rewrite" },
+ },
+ window: {
+ createTextEditorDecorationType: vi.fn().mockReturnValue({ dispose: vi.fn() }),
+ visibleTextEditors: [],
+ tabGroups: { all: [], close: vi.fn(), onDidChangeTabs: vi.fn(() => ({ dispose: vi.fn() })) },
+ showErrorMessage: vi.fn(),
+ },
+ workspace: {
+ workspaceFolders: [{ uri: { fsPath: "/mock/workspace/path" }, name: "mock-workspace", index: 0 }],
+ createFileSystemWatcher: vi.fn(() => ({
+ onDidCreate: vi.fn(() => mockDisposable),
+ onDidDelete: vi.fn(() => mockDisposable),
+ onDidChange: vi.fn(() => mockDisposable),
+ dispose: vi.fn(),
+ })),
+ fs: { stat: vi.fn().mockResolvedValue({ type: 1 }) },
+ onDidSaveTextDocument: vi.fn(() => mockDisposable),
+ getConfiguration: vi.fn(() => ({ get: (_key: string, defaultValue: unknown) => defaultValue })),
+ },
+ env: { uriScheme: "vscode", language: "en" },
+ EventEmitter: vi.fn().mockImplementation(function () {
+ return mockEventEmitter
+ }),
+ Disposable: { from: vi.fn() },
+ TabInputText: vi.fn(),
+ }
+})
+
+vi.mock("../../mentions", () => ({
+ parseMentions: vi.fn().mockImplementation((text) => {
+ return Promise.resolve({ text: `processed: ${text}`, mode: undefined, contentBlocks: [] })
+ }),
+ openMention: vi.fn(),
+ getLatestTerminalOutput: vi.fn(),
+}))
+
+vi.mock("../../../integrations/misc/extract-text", () => ({
+ extractTextFromFile: vi.fn().mockResolvedValue("Mock file content"),
+}))
+
+vi.mock("../../environment/getEnvironmentDetails", () => ({
+ getEnvironmentDetails: vi.fn().mockResolvedValue(""),
+}))
+
+vi.mock("../../ignore/RooIgnoreController")
+
+vi.mock("../../../i18n", () => {
+ return {
+ t: (key: string, args?: Record) => {
+ if (key === "tools:missingToolParameterWithPath") {
+ return `${args?.toolName}|${args?.relPath}|${args?.paramName}`
+ }
+ if (key === "tools:missingToolParameter") {
+ return `${args?.toolName}|${args?.paramName}`
+ }
+ return key
+ },
+ }
+})
+
+vi.mock("../../../utils/storage", () => ({
+ getTaskDirectoryPath: vi
+ .fn()
+ .mockImplementation((globalStoragePath, taskId) => Promise.resolve(`${globalStoragePath}/tasks/${taskId}`)),
+ getSettingsDirectoryPath: vi
+ .fn()
+ .mockImplementation((globalStoragePath) => Promise.resolve(`${globalStoragePath}/settings`)),
+}))
+
+vi.mock("../../../utils/fs", () => ({
+ fileExistsAtPath: vi.fn().mockReturnValue(false),
+}))
+
+// The re-assert under test lives in Task.saveClineMessages AFTER the message
+// write, so stub the fs-touching saveTaskMessages to keep the spec deterministic
+// (the real safeWriteJson atomic-rename races with the mocked fs); taskMetadata
+// stays real so the historyItem shape is the production one.
+vi.mock("../../task-persistence", async (importOriginal) => {
+ const actual = await importOriginal()
+ return {
+ ...actual,
+ saveTaskMessages: vi.fn().mockResolvedValue([]),
+ }
+})
+
+const PARENT_TASK_ID = "parent-1"
+
+const backgroundPolicy: ConstructorParameters[0]["backgroundToolPolicy"] = {
+ disabledTools: BACKGROUND_CHILD_DISABLED_TOOLS,
+ experiments: BACKGROUND_CHILD_EXPERIMENTS,
+}
+
+describe("background child stamp re-assert on its own history write (M-2)", () => {
+ let mockProvider: ClineProvider
+ let mockContextProxy: ContextProxy
+ let mockApiConfig: ProviderSettings
+
+ beforeEach(() => {
+ if (!TelemetryService.hasInstance()) {
+ TelemetryService.createInstance([])
+ }
+
+ const storageUri = { fsPath: path.join(os.tmpdir(), "test-storage") }
+
+ const mockExtensionContext = {
+ globalState: {
+ get: vi.fn().mockImplementation((_key: keyof GlobalState) => undefined),
+ update: vi.fn().mockImplementation((_key, _value) => Promise.resolve()),
+ keys: vi.fn().mockReturnValue([]),
+ },
+ globalStorageUri: storageUri,
+ workspaceState: {
+ get: vi.fn().mockImplementation((_key) => undefined),
+ update: vi.fn().mockImplementation((_key, _value) => Promise.resolve()),
+ keys: vi.fn().mockReturnValue([]),
+ },
+ secrets: {
+ get: vi.fn().mockImplementation((_key) => Promise.resolve(undefined)),
+ store: vi.fn().mockImplementation((_key, _value) => Promise.resolve()),
+ delete: vi.fn().mockImplementation((_key) => Promise.resolve()),
+ },
+ extensionUri: { fsPath: "/mock/extension/path" },
+ extension: { packageJSON: { version: "1.0.0" } },
+ } as unknown as ExtensionContext
+
+ const mockOutputChannel = {
+ name: "test-output",
+ appendLine: vi.fn(),
+ append: vi.fn(),
+ replace: vi.fn(),
+ clear: vi.fn(),
+ show: vi.fn(),
+ hide: vi.fn(),
+ dispose: vi.fn(),
+ }
+
+ mockContextProxy = new ContextProxy(mockExtensionContext)
+ mockProvider = new ClineProvider(
+ mockExtensionContext,
+ mockOutputChannel,
+ "sidebar",
+ mockContextProxy,
+ new WebviewFocusTracker(),
+ )
+
+ mockApiConfig = {
+ apiProvider: providerIdentifiers.anthropic,
+ apiModelId: "claude-3-5-sonnet-20241022",
+ apiKey: "test-api-key",
+ }
+
+ mockProvider.postMessageToWebview = vi.fn().mockResolvedValue(undefined)
+ mockProvider.postStateToWebview = vi.fn().mockResolvedValue(undefined)
+ mockProvider.postStateToWebviewWithoutTaskHistory = vi.fn().mockResolvedValue(undefined)
+ mockProvider.postStateToWebviewThrottled = vi.fn().mockResolvedValue(undefined)
+ mockProvider.flushPostStateToWebviewThrottled = vi.fn().mockResolvedValue(undefined)
+ })
+
+ afterEach(() => {
+ vi.restoreAllMocks()
+ })
+
+ // A LIVE background child carrying its parent (so the parent id is in memory)
+ // — exactly what spawnBackgroundChildren registers. The spawn-time stamp
+ // upsert is intentionally NOT performed here, modeling the transient store
+ // failure that left the child unstamped (the M-2 scenario).
+ async function buildUnstampedHostedChild() {
+ const parentTask = { taskId: PARENT_TASK_ID } as unknown as Task
+ vi.spyOn(mockProvider, "getState").mockResolvedValue({ mcpEnabled: false } as never)
+ const task = new Task({
+ provider: mockProvider,
+ apiConfiguration: mockApiConfig,
+ task: "child investigation",
+ startTask: false,
+ parentTask,
+ backgroundToolPolicy: backgroundPolicy,
+ backgroundChildHosted: true,
+ })
+ await task.getTaskMode()
+ return task
+ }
+
+ const taskSay: ClineMessage = { ts: 1, type: "say", say: "text", text: "child investigation", partial: false }
+
+ it("the child's own save persists the backgroundParentTaskId stamp even when the spawn-time stamp failed", async () => {
+ const child = await buildUnstampedHostedChild()
+ expect(child.isBackgroundSubtaskChild).toBe(true)
+ expect(child.parentTaskId).toBe(PARENT_TASK_ID)
+
+ const updateSpy = vi.spyOn(mockProvider, "updateTaskHistory").mockResolvedValue([])
+ child["clineMessages"] = [taskSay]
+
+ await child["saveClineMessages"]()
+
+ // The child's own history write re-asserted the stamp from the in-memory
+ // parent id, so a later restore sees it and re-applies the read-only policy.
+ expect(updateSpy).toHaveBeenCalledTimes(1)
+ const persisted = updateSpy.mock.calls[0][0] as { backgroundParentTaskId?: string }
+ expect(persisted.backgroundParentTaskId).toBe(PARENT_TASK_ID)
+ })
+
+ it("a normal task's own save does not stamp a backgroundParentTaskId", async () => {
+ vi.spyOn(mockProvider, "getState").mockResolvedValue({ mcpEnabled: false } as never)
+ const task = new Task({
+ provider: mockProvider,
+ apiConfiguration: mockApiConfig,
+ task: "plain task",
+ startTask: false,
+ })
+ await task.getTaskMode()
+
+ const updateSpy = vi.spyOn(mockProvider, "updateTaskHistory").mockResolvedValue([])
+ task["clineMessages"] = [taskSay]
+
+ await task["saveClineMessages"]()
+
+ const persisted = updateSpy.mock.calls[0][0] as { backgroundParentTaskId?: string }
+ expect(persisted.backgroundParentTaskId).toBeUndefined()
+ })
+})
diff --git a/src/core/task/__tests__/background-webview-guards.spec.ts b/src/core/task/__tests__/background-webview-guards.spec.ts
new file mode 100644
index 0000000000..043624ce3a
--- /dev/null
+++ b/src/core/task/__tests__/background-webview-guards.spec.ts
@@ -0,0 +1,694 @@
+// npx vitest run core/task/__tests__/background-webview-guards.spec.ts
+
+import * as os from "os"
+import * as path from "path"
+
+import type { ExtensionContext } from "vscode"
+import {
+ providerIdentifiers,
+ type ClineMessage,
+ type GlobalState,
+ type ModelInfo,
+ type ProviderSettings,
+ RooCodeEventName,
+} from "@roo-code/types"
+import { TelemetryService } from "@roo-code/telemetry"
+
+import { Task } from "../Task"
+import { ClineProvider } from "../../webview/ClineProvider"
+import { ContextProxy } from "../../config/ContextProxy"
+import { WebviewFocusTracker } from "../../webview/WebviewFocusTracker"
+import type { ContextManagementOptions, ContextManagementResult } from "../../context-management"
+import type { ApiStreamChunk } from "../../../api/transform/stream"
+import { asyncStreamFrom } from "../../../test-utils/stream"
+import { BACKGROUND_CHILD_DISABLED_TOOLS, BACKGROUND_CHILD_EXPERIMENTS } from "../../background-subtasks/policy"
+
+// Mock delay before any imports that might use it
+vi.mock("delay", () => ({
+ __esModule: true,
+ default: vi.fn().mockResolvedValue(undefined),
+}))
+
+vi.mock("uuid", async (importOriginal) => {
+ const actual = await importOriginal()
+ return {
+ ...actual,
+ v7: vi.fn(() => "00000000-0000-7000-8000-000000000000"),
+ }
+})
+
+vi.mock("execa", () => ({
+ execa: vi.fn(),
+}))
+
+const mockMessages = [
+ {
+ ts: Date.now(),
+ type: "say",
+ say: "text",
+ text: "historical task",
+ },
+]
+
+vi.mock("fs/promises", async (importOriginal) => {
+ const actual = await importOriginal()
+ const mockFunctions = {
+ mkdir: vi.fn().mockResolvedValue(undefined),
+ writeFile: vi.fn().mockResolvedValue(undefined),
+ readFile: vi.fn().mockImplementation((filePath) => {
+ if (filePath.includes("ui_messages.json")) {
+ return Promise.resolve(JSON.stringify(mockMessages))
+ }
+ if (filePath.includes("api_conversation_history.json")) {
+ return Promise.resolve("[]")
+ }
+ return Promise.resolve("[]")
+ }),
+ unlink: vi.fn().mockResolvedValue(undefined),
+ rmdir: vi.fn().mockResolvedValue(undefined),
+ stat: vi.fn().mockRejectedValue({ code: "ENOENT" }),
+ readdir: vi.fn().mockResolvedValue([]),
+ }
+
+ return {
+ ...actual,
+ ...mockFunctions,
+ default: mockFunctions,
+ }
+})
+
+vi.mock("p-wait-for", () => ({
+ default: vi.fn().mockImplementation(async () => Promise.resolve()),
+}))
+
+// Task tests do not exercise indexing; keep workspace resolution and its cache out of this suite.
+vi.mock("../../../services/code-index/code-index-manager-registry", () => ({
+ CodeIndexManagerRegistry: {
+ getOrCreate: vi.fn().mockReturnValue(undefined),
+ getAllInstances: vi.fn().mockReturnValue([]),
+ disposeAll: vi.fn(),
+ },
+}))
+
+vi.mock("vscode", () => {
+ const mockDisposable = { dispose: vi.fn() }
+ const mockEventEmitter = { event: vi.fn(), fire: vi.fn() }
+ const mockTextDocument = { uri: { fsPath: "/mock/workspace/path/file.ts" } }
+ const mockTextEditor = { document: mockTextDocument }
+ const mockTab = { input: { uri: { fsPath: "/mock/workspace/path/file.ts" } } }
+ const mockTabGroup = { tabs: [mockTab] }
+
+ return {
+ TabInputTextDiff: vi.fn(),
+ CodeActionKind: {
+ QuickFix: { value: "quickfix" },
+ RefactorRewrite: { value: "refactor.rewrite" },
+ },
+ window: {
+ createTextEditorDecorationType: vi.fn().mockReturnValue({
+ dispose: vi.fn(),
+ }),
+ visibleTextEditors: [mockTextEditor],
+ tabGroups: {
+ all: [mockTabGroup],
+ close: vi.fn(),
+ onDidChangeTabs: vi.fn(() => ({ dispose: vi.fn() })),
+ },
+ showErrorMessage: vi.fn(),
+ },
+ workspace: {
+ workspaceFolders: [
+ {
+ uri: { fsPath: "/mock/workspace/path" },
+ name: "mock-workspace",
+ index: 0,
+ },
+ ],
+ createFileSystemWatcher: vi.fn(() => ({
+ onDidCreate: vi.fn(() => mockDisposable),
+ onDidDelete: vi.fn(() => mockDisposable),
+ onDidChange: vi.fn(() => mockDisposable),
+ dispose: vi.fn(),
+ })),
+ fs: {
+ stat: vi.fn().mockResolvedValue({ type: 1 }), // FileType.File = 1
+ },
+ onDidSaveTextDocument: vi.fn(() => mockDisposable),
+ getConfiguration: vi.fn(() => ({ get: (_key: string, defaultValue: unknown) => defaultValue })),
+ },
+ env: {
+ uriScheme: "vscode",
+ language: "en",
+ },
+ EventEmitter: vi.fn().mockImplementation(function () {
+ return mockEventEmitter
+ }),
+ Disposable: {
+ from: vi.fn(),
+ },
+ TabInputText: vi.fn(),
+ }
+})
+
+vi.mock("../../mentions", () => ({
+ parseMentions: vi.fn().mockImplementation((text) => {
+ return Promise.resolve({ text: `processed: ${text}`, mode: undefined, contentBlocks: [] })
+ }),
+ openMention: vi.fn(),
+ getLatestTerminalOutput: vi.fn(),
+}))
+
+vi.mock("../../../integrations/misc/extract-text", () => ({
+ extractTextFromFile: vi.fn().mockResolvedValue("Mock file content"),
+}))
+
+vi.mock("../../environment/getEnvironmentDetails", () => ({
+ getEnvironmentDetails: vi.fn().mockResolvedValue(""),
+}))
+
+vi.mock("../../ignore/RooIgnoreController")
+
+vi.mock("../../../i18n", () => {
+ return {
+ t: (key: string, args?: Record) => {
+ if (key === "tools:missingToolParameterWithPath") {
+ return `${args?.toolName}|${args?.relPath}|${args?.paramName}`
+ }
+ if (key === "tools:missingToolParameter") {
+ return `${args?.toolName}|${args?.paramName}`
+ }
+ return key
+ },
+ }
+})
+
+// Mock storagePathManager to prevent dynamic import issues.
+vi.mock("../../../utils/storage", () => ({
+ getTaskDirectoryPath: vi
+ .fn()
+ .mockImplementation((globalStoragePath, taskId) => Promise.resolve(`${globalStoragePath}/tasks/${taskId}`)),
+ getSettingsDirectoryPath: vi
+ .fn()
+ .mockImplementation((globalStoragePath) => Promise.resolve(`${globalStoragePath}/settings`)),
+}))
+
+vi.mock("../../../utils/fs", () => ({
+ fileExistsAtPath: vi.fn().mockImplementation((filePath) => {
+ return filePath.includes("ui_messages.json") || filePath.includes("api_conversation_history.json")
+ }),
+}))
+
+// The condense guards are asserted around manageContext: the real summarizer
+// would call the API, so it stands in as a pass-through that reports "nothing
+// condensed" (no summary, no error, no truncation).
+const { manageContextMock } = vi.hoisted(() => ({
+ manageContextMock: vi.fn<(options: ContextManagementOptions) => Promise>(),
+}))
+
+vi.mock("../../context-management", async (importOriginal) => {
+ const actual = await importOriginal()
+ return {
+ ...actual,
+ manageContext: manageContextMock,
+ }
+})
+
+// Model-info stand-in: the settled snapshot only needs a defined ModelInfo.
+const stubModelInfo: ModelInfo = {
+ contextWindow: 200_000,
+ maxTokens: 4096,
+ supportsPromptCache: true,
+}
+
+type TaskSeams = {
+ getSystemPrompt: (requestState: ProviderState | undefined, requestModelInfo?: ModelInfo) => Promise
+ safeEnsureModelFetched: () => Promise
+}
+
+type ProviderState = Awaited>
+
+// A double assertion is unavoidable here: the seam helpers are private on Task,
+// and the test drives them through vi.spyOn on the real instance.
+function getTaskSeams(task: Task): TaskSeams {
+ return task as unknown as TaskSeams
+}
+
+describe("background child webview suppression (UI-leak guards)", () => {
+ let mockProvider: ClineProvider
+ let mockContextProxy: ContextProxy
+ let mockApiConfig: ProviderSettings
+ let mockExtensionContext: ExtensionContext
+ // Every task built by buildTask, so afterEach can dispose them. The tests
+ // never add them to the provider's registry, so provider.dispose() alone
+ // would not reach them.
+ let builtTasks: Task[] = []
+
+ // The mocked getState only carries the fields a test pins; Task reads the
+ // rest through its own defaults. The cast supplies the remaining required
+ // ExtensionState shape, which a Partial spread alone cannot prove.
+ const providerStateWith = (overrides: Partial = {}): ProviderState =>
+ ({
+ mcpEnabled: false,
+ ...overrides,
+ }) as ProviderState
+
+ const backgroundPolicy: ConstructorParameters[0]["backgroundToolPolicy"] = {
+ disabledTools: BACKGROUND_CHILD_DISABLED_TOOLS,
+ experiments: BACKGROUND_CHILD_EXPERIMENTS,
+ }
+
+ beforeEach(() => {
+ if (!TelemetryService.hasInstance()) {
+ TelemetryService.createInstance([])
+ }
+
+ const storageUri = {
+ fsPath: path.join(os.tmpdir(), "test-storage"),
+ }
+
+ mockExtensionContext = {
+ globalState: {
+ get: vi.fn().mockImplementation((_key: keyof GlobalState) => undefined),
+ update: vi.fn().mockImplementation((_key, _value) => Promise.resolve()),
+ keys: vi.fn().mockReturnValue([]),
+ },
+ globalStorageUri: storageUri,
+ workspaceState: {
+ get: vi.fn().mockImplementation((_key) => undefined),
+ update: vi.fn().mockImplementation((_key, _value) => Promise.resolve()),
+ keys: vi.fn().mockReturnValue([]),
+ },
+ secrets: {
+ get: vi.fn().mockImplementation((_key) => Promise.resolve(undefined)),
+ store: vi.fn().mockImplementation((_key, _value) => Promise.resolve()),
+ delete: vi.fn().mockImplementation((_key) => Promise.resolve()),
+ },
+ extensionUri: {
+ fsPath: "/mock/extension/path",
+ },
+ extension: {
+ packageJSON: {
+ version: "1.0.0",
+ },
+ },
+ } as unknown as ExtensionContext
+
+ const mockOutputChannel = {
+ name: "test-output",
+ appendLine: vi.fn(),
+ append: vi.fn(),
+ replace: vi.fn(),
+ clear: vi.fn(),
+ show: vi.fn(),
+ hide: vi.fn(),
+ dispose: vi.fn(),
+ }
+
+ mockContextProxy = new ContextProxy(mockExtensionContext)
+ mockProvider = new ClineProvider(
+ mockExtensionContext,
+ mockOutputChannel,
+ "sidebar",
+ mockContextProxy,
+ new WebviewFocusTracker(),
+ )
+
+ mockApiConfig = {
+ apiProvider: providerIdentifiers.anthropic,
+ apiModelId: "claude-3-5-sonnet-20241022",
+ apiKey: "test-api-key",
+ }
+
+ mockProvider.postMessageToWebview = vi.fn().mockResolvedValue(undefined)
+ mockProvider.postStateToWebview = vi.fn().mockResolvedValue(undefined)
+ mockProvider.postStateToWebviewWithoutTaskHistory = vi.fn().mockResolvedValue(undefined)
+ mockProvider.postStateToWebviewThrottled = vi.fn().mockResolvedValue(undefined)
+ mockProvider.flushPostStateToWebviewThrottled = vi.fn().mockResolvedValue(undefined)
+
+ manageContextMock.mockImplementation(async (options) => ({
+ messages: options.messages,
+ summary: "",
+ cost: 0,
+ prevContextTokens: 0,
+ }))
+ })
+
+ afterEach(async () => {
+ // Deterministic teardown: dispose every built task (closes request
+ // generators still suspended mid-stream via their finally, clears
+ // listeners/queues) and then the provider, so no async work outlives
+ // this file. Disposal runs before restoreAllMocks so the module mocks
+ // (fs, storage paths) are still in place for it.
+ //
+ // `Task.dispose()` and `ClineProvider.dispose()` write to the console on
+ // every call. With ~30 tasks per file that is a burst of worker->parent
+ // console RPCs landing exactly when the worker is closing, which Vitest
+ // reports as `EnvironmentTeardownError: Closing rpc while
+ // "onUserConsoleLog" was pending` and turns into a non-zero exit even
+ // though every test passed. The repo runs with `silent: true`, so these
+ // lines are dropped from the terminal anyway; silencing them here only
+ // removes the RPC traffic, never a diagnostic a developer would see.
+ const consoleQuiet = ["log", "info", "warn", "error", "debug"].map((key) =>
+ vi.spyOn(console, key as "log").mockImplementation(() => {}),
+ )
+ try {
+ // A rejecting dispose must not skip the remaining disposals or mask
+ // the assertion failure under test.
+ for (const task of builtTasks) {
+ await task.dispose().catch(() => {})
+ }
+ builtTasks = []
+ await mockProvider.dispose().catch(() => {})
+ } finally {
+ for (const spy of consoleQuiet) {
+ spy.mockRestore()
+ }
+ }
+ vi.restoreAllMocks()
+ })
+
+ async function buildTask(
+ backgroundToolPolicy?: ConstructorParameters[0]["backgroundToolPolicy"],
+ stateOverrides: Partial = {},
+ ) {
+ // Install the state read before construction: the constructor's mode
+ // initialization consumes the same request-time state the request will.
+ // stateOverrides lets a test pin request-time settings (e.g. the
+ // auto-condense fields) so they survive into the request instead of
+ // being replaced by this install.
+ vi.spyOn(mockProvider, "getState").mockResolvedValue(
+ providerStateWith({ mode: "code", autoApprovalEnabled: false, ...stateOverrides }),
+ )
+ const task = new Task({
+ provider: mockProvider,
+ apiConfiguration: mockApiConfig,
+ task: "test task",
+ startTask: false,
+ backgroundToolPolicy,
+ // P1-2: a LIVE background child is marked by the hosted flag, not by
+ // policy presence. These specs always mean "live child" when they pass
+ // a policy, so the two travel together here.
+ backgroundChildHosted: backgroundToolPolicy !== undefined,
+ })
+ // Track before the first await so a throw in getTaskMode still leaves a
+ // reachable task for afterEach disposal.
+ builtTasks.push(task)
+ await task.getTaskMode()
+ return task
+ }
+
+ function resetProviderWebviewMocks() {
+ vi.mocked(mockProvider.postMessageToWebview).mockClear()
+ vi.mocked(mockProvider.postStateToWebviewThrottled).mockClear()
+ vi.mocked(mockProvider.flushPostStateToWebviewThrottled).mockClear()
+ }
+
+ describe("addToClineMessages", () => {
+ // An unanswered ask exercises both the throttled post and the immediate
+ // flush that unanswered asks normally require.
+ const askMessage: ClineMessage = {
+ ts: 1,
+ type: "ask",
+ ask: "tool",
+ text: "approve write?",
+ isAnswered: false,
+ partial: false,
+ }
+
+ it("posts no webview state for a background child but still emits, persists, and appends", async () => {
+ const task = await buildTask(backgroundPolicy)
+ task["emit"] = vi.fn()
+ task["saveClineMessages"] = vi.fn(async () => true)
+ resetProviderWebviewMocks()
+
+ await task["addToClineMessages"]({ ...askMessage })
+
+ expect(task.isBackgroundSubtaskChild).toBe(true)
+ expect(mockProvider.postStateToWebviewThrottled).not.toHaveBeenCalled()
+ expect(mockProvider.flushPostStateToWebviewThrottled).not.toHaveBeenCalled()
+ expect(task["emit"]).toHaveBeenCalledWith(RooCodeEventName.Message, expect.anything())
+ expect(task["saveClineMessages"]).toHaveBeenCalled()
+ expect(task.clineMessages).toHaveLength(1)
+ })
+
+ it("posts throttled state and the immediate flush for a non-background task", async () => {
+ const task = await buildTask()
+ task["emit"] = vi.fn()
+ task["saveClineMessages"] = vi.fn(async () => true)
+ resetProviderWebviewMocks()
+
+ await task["addToClineMessages"]({ ...askMessage })
+
+ expect(task.isBackgroundSubtaskChild).toBe(false)
+ expect(mockProvider.postStateToWebviewThrottled).toHaveBeenCalledTimes(1)
+ expect(mockProvider.flushPostStateToWebviewThrottled).toHaveBeenCalledTimes(1)
+ expect(task["emit"]).toHaveBeenCalledWith(RooCodeEventName.Message, expect.anything())
+ expect(task["saveClineMessages"]).toHaveBeenCalled()
+ })
+ })
+
+ describe("messageQueueStateChangedHandler", () => {
+ it("emits the queue events without posting webview state for a background child", async () => {
+ const task = await buildTask(backgroundPolicy)
+ task["emit"] = vi.fn()
+ resetProviderWebviewMocks()
+
+ task["messageQueueService"].addMessage("queued feedback")
+
+ expect(task["emit"]).toHaveBeenCalledWith(RooCodeEventName.TaskUserMessage, task.taskId)
+ expect(task["emit"]).toHaveBeenCalledWith(
+ RooCodeEventName.QueuedMessagesUpdated,
+ task.taskId,
+ expect.anything(),
+ )
+ expect(mockProvider.postStateToWebviewThrottled).not.toHaveBeenCalled()
+ })
+
+ it("posts webview state and emits the queue events for a non-background task", async () => {
+ const task = await buildTask()
+ task["emit"] = vi.fn()
+ resetProviderWebviewMocks()
+
+ task["messageQueueService"].addMessage("queued feedback")
+
+ expect(mockProvider.postStateToWebviewThrottled).toHaveBeenCalledTimes(1)
+ expect(task["emit"]).toHaveBeenCalledWith(RooCodeEventName.TaskUserMessage, task.taskId)
+ expect(task["emit"]).toHaveBeenCalledWith(
+ RooCodeEventName.QueuedMessagesUpdated,
+ task.taskId,
+ expect.anything(),
+ )
+ })
+ })
+
+ describe("updateClineMessage", () => {
+ const partialMessage: ClineMessage = {
+ ts: 2,
+ type: "say",
+ say: "text",
+ text: "streaming partial",
+ partial: true,
+ }
+
+ it("posts no messageUpdated for a background child but still emits the update event", async () => {
+ const task = await buildTask(backgroundPolicy)
+ task["emit"] = vi.fn()
+ resetProviderWebviewMocks()
+
+ await task["updateClineMessage"]({ ...partialMessage })
+
+ expect(mockProvider.postMessageToWebview).not.toHaveBeenCalled()
+ expect(task["emit"]).toHaveBeenCalledWith(RooCodeEventName.Message, {
+ action: "updated",
+ message: partialMessage,
+ })
+ })
+
+ it("posts messageUpdated for a non-background task", async () => {
+ const task = await buildTask()
+ task["emit"] = vi.fn()
+ resetProviderWebviewMocks()
+
+ await task["updateClineMessage"]({ ...partialMessage })
+
+ expect(mockProvider.postMessageToWebview).toHaveBeenCalledWith({
+ type: "messageUpdated",
+ clineMessage: partialMessage,
+ })
+ expect(task["emit"]).toHaveBeenCalledWith(RooCodeEventName.Message, {
+ action: "updated",
+ message: partialMessage,
+ })
+ })
+ })
+
+ describe("condense indicator posts", () => {
+ function armContextWindowSeams(task: Task) {
+ vi.spyOn(task, "getTokenUsage").mockReturnValue({
+ totalCost: 0,
+ totalTokensIn: 0,
+ totalTokensOut: 0,
+ contextTokens: 200_000,
+ })
+ }
+
+ it("posts no condense spinner or dismissal for a background child recovering from overflow", async () => {
+ const task = await buildTask(backgroundPolicy)
+ armContextWindowSeams(task)
+ resetProviderWebviewMocks()
+
+ await task["handleContextWindowExceededError"](stubModelInfo)
+
+ // The condense actually ran (guard is not "skip condensing"), only the
+ // webview indicator stayed silent.
+ expect(manageContextMock).toHaveBeenCalled()
+ expect(mockProvider.postMessageToWebview).not.toHaveBeenCalled()
+ })
+
+ it("posts the condense spinner and its dismissal for a non-background task recovering from overflow", async () => {
+ const task = await buildTask()
+ armContextWindowSeams(task)
+ resetProviderWebviewMocks()
+
+ await task["handleContextWindowExceededError"](stubModelInfo)
+
+ const posts = vi.mocked(mockProvider.postMessageToWebview).mock.calls.map(([message]) => message)
+ expect(posts.filter((message) => message.type === "condenseTaskContextStarted")).toHaveLength(1)
+ expect(posts.filter((message) => message.type === "condenseTaskContextResponse")).toHaveLength(1)
+ })
+
+ async function driveAutoCondense(task: Task) {
+ const seams = getTaskSeams(task)
+ vi.spyOn(seams, "getSystemPrompt").mockResolvedValue("mock system prompt")
+ vi.spyOn(seams, "safeEnsureModelFetched").mockResolvedValue(stubModelInfo)
+ vi.spyOn(task.api, "createMessage").mockReturnValue(
+ asyncStreamFrom([{ type: "text", text: "ok" }]),
+ )
+ armContextWindowSeams(task)
+ resetProviderWebviewMocks()
+
+ // Retain the generator: one unconsumed next() would leave
+ // attemptApiRequest suspended mid-stream (its finally, endApiWork,
+ // never running). return() closes it deterministically.
+ const requestGenerator = task.attemptApiRequest(0, { skipProviderRateLimit: true })
+ try {
+ await requestGenerator.next()
+ } finally {
+ await requestGenerator.return(undefined)
+ }
+ }
+
+ it("posts no condense spinner or dismissal for a background child during an auto-condense request", async () => {
+ const task = await buildTask(backgroundPolicy, {
+ autoCondenseContext: true,
+ autoCondenseContextPercent: 100,
+ })
+
+ await driveAutoCondense(task)
+
+ // 100% of the context window is occupied, so the real threshold check
+ // fires and the pass-through manageContext proves the branch ran.
+ expect(manageContextMock).toHaveBeenCalled()
+ expect(mockProvider.postMessageToWebview).not.toHaveBeenCalled()
+ })
+
+ it("posts the condense spinner and its dismissal for a non-background task during an auto-condense request", async () => {
+ const task = await buildTask(undefined, { autoCondenseContext: true, autoCondenseContextPercent: 100 })
+
+ await driveAutoCondense(task)
+
+ const posts = vi.mocked(mockProvider.postMessageToWebview).mock.calls.map(([message]) => message)
+ expect(posts.filter((message) => message.type === "condenseTaskContextStarted")).toHaveLength(1)
+ expect(posts.filter((message) => message.type === "condenseTaskContextResponse")).toHaveLength(1)
+ })
+ })
+
+ describe("request-iteration state posts (F-11)", () => {
+ function armRequestSeams(task: Task) {
+ const seams = getTaskSeams(task)
+ vi.spyOn(seams, "getSystemPrompt").mockResolvedValue("mock system prompt")
+ vi.spyOn(seams, "safeEnsureModelFetched").mockResolvedValue(stubModelInfo)
+ vi.spyOn(task.api, "createMessage").mockReturnValue(
+ asyncStreamFrom([{ type: "text", text: "ok" }]),
+ )
+ vi.spyOn(task, "getTokenUsage").mockReturnValue({
+ totalCost: 0,
+ totalTokensIn: 0,
+ totalTokensOut: 0,
+ contextTokens: 0,
+ })
+ // The real DiffViewProvider touches the editor API surface this file
+ // does not model; the request iteration only needs it reset.
+ task["diffViewProvider"] = { reset: vi.fn() } as unknown as Task["diffViewProvider"]
+ resetProviderWebviewMocks()
+ vi.mocked(mockProvider.postStateToWebviewWithoutTaskHistory).mockClear()
+ }
+
+ async function driveFullRequestIteration(task: Task) {
+ // Drive the full request iteration: both state-post sites (before the
+ // request and after the stream completes) live in
+ // recursivelyMakeClineRequests, so the whole loop must run.
+ await task.recursivelyMakeClineRequests([{ type: "text", text: "investigate the codebase" }])
+ }
+
+ it("posts no state to the webview across a full request iteration for a background child", async () => {
+ const task = await buildTask(backgroundPolicy)
+ armRequestSeams(task)
+
+ await driveFullRequestIteration(task)
+
+ expect(task.isBackgroundSubtaskChild).toBe(true)
+ expect(mockProvider.postStateToWebviewWithoutTaskHistory).not.toHaveBeenCalled()
+ // The loop really ran (its no-tool continuation can issue more than
+ // one request); every one of those requests stayed off the webview.
+ expect(vi.mocked(task.api.createMessage)).toHaveBeenCalled()
+ })
+
+ it("posts state around every request of a full iteration for a non-background task", async () => {
+ const task = await buildTask()
+ armRequestSeams(task)
+
+ await driveFullRequestIteration(task)
+
+ expect(task.isBackgroundSubtaskChild).toBe(false)
+ // Each request posts state twice: once before the request (placeholder
+ // cost/protocol refresh) and once after the stream completes.
+ const requests = vi.mocked(task.api.createMessage).mock.calls.length
+ expect(requests).toBeGreaterThan(0)
+ expect(mockProvider.postStateToWebviewWithoutTaskHistory).toHaveBeenCalledTimes(requests * 2)
+ })
+ })
+
+ describe("abortTaskOnce webview flush (F-11)", () => {
+ async function driveAbort(task: Task) {
+ task["emit"] = vi.fn()
+ task["emitFinalTokenUsageUpdate"] = vi.fn()
+ task["saveClineMessages"] = vi.fn(async () => true)
+ resetProviderWebviewMocks()
+ vi.mocked(mockProvider.flushPostStateToWebviewThrottled).mockClear()
+
+ // Do NOT stub task.dispose here: abortTaskOnce() ends with
+ // `void this.dispose()`, and these tasks stay in builtTasks, so
+ // afterEach disposes them through the same (memoized) method. A
+ // no-op stub would leave both abort-test tasks undisposed. Disposal
+ // never touches the webview flush counters these tests assert on.
+ await task["abortTaskOnce"]()
+ }
+
+ it("flushes nothing to the webview for a background child", async () => {
+ const task = await buildTask(backgroundPolicy)
+
+ await driveAbort(task)
+
+ expect(mockProvider.flushPostStateToWebviewThrottled).not.toHaveBeenCalled()
+ })
+
+ it("flushes webview state for a non-background task", async () => {
+ const task = await buildTask()
+
+ await driveAbort(task)
+
+ expect(mockProvider.flushPostStateToWebviewThrottled).toHaveBeenCalledTimes(1)
+ })
+ })
+})
diff --git a/src/core/task/__tests__/grace-retry-errors.spec.ts b/src/core/task/__tests__/grace-retry-errors.spec.ts
index 633664c625..d892f7927c 100644
--- a/src/core/task/__tests__/grace-retry-errors.spec.ts
+++ b/src/core/task/__tests__/grace-retry-errors.spec.ts
@@ -291,7 +291,7 @@ describe("Grace Retry Error Handling", () => {
startTask: false,
})
- const saySpy = vi.spyOn(task, "say").mockResolvedValue(undefined)
+ const saySpy = vi.spyOn(task, "say").mockResolvedValue({ ts: 0, type: "say", say: "text", text: "" })
// Simulate first empty response - should NOT show error
task.consecutiveNoAssistantMessagesCount = 0
@@ -315,7 +315,7 @@ describe("Grace Retry Error Handling", () => {
startTask: false,
})
- const saySpy = vi.spyOn(task, "say").mockResolvedValue(undefined)
+ const saySpy = vi.spyOn(task, "say").mockResolvedValue({ ts: 0, type: "say", say: "text", text: "" })
// Simulate second consecutive empty response
task.consecutiveNoAssistantMessagesCount = 1
@@ -339,7 +339,7 @@ describe("Grace Retry Error Handling", () => {
startTask: false,
})
- const saySpy = vi.spyOn(task, "say").mockResolvedValue(undefined)
+ const saySpy = vi.spyOn(task, "say").mockResolvedValue({ ts: 0, type: "say", say: "text", text: "" })
// Simulate third consecutive empty response
task.consecutiveNoAssistantMessagesCount = 2
@@ -411,7 +411,7 @@ describe("Grace Retry Error Handling", () => {
startTask: false,
})
- const saySpy = vi.spyOn(task, "say").mockResolvedValue(undefined)
+ const saySpy = vi.spyOn(task, "say").mockResolvedValue({ ts: 0, type: "say", say: "text", text: "" })
// Simulate the error condition (2 consecutive failures)
task.consecutiveNoAssistantMessagesCount = 2
diff --git a/src/core/task/__tests__/native-tools-filtering.spec.ts b/src/core/task/__tests__/native-tools-filtering.spec.ts
index 1c393456ab..6c57f295d8 100644
--- a/src/core/task/__tests__/native-tools-filtering.spec.ts
+++ b/src/core/task/__tests__/native-tools-filtering.spec.ts
@@ -113,8 +113,13 @@ describe("Native Tools Filtering by Mode", () => {
const { isToolAllowedForMode } = await import("../../tools/validateToolUse")
const { ALWAYS_AVAILABLE_TOOLS } = await import("../../../shared/tools")
- // Always-available tools should work even with no groups
- ALWAYS_AVAILABLE_TOOLS.forEach((tool) => {
+ // Always-available tools should work even with no groups. The
+ // experiment-gated members of the class are excluded here and covered
+ // by their own gate tests: the always-available short-circuit sits
+ // above the generic EXPERIMENT_IDS check, so a gated tool needs its
+ // own flag check and is deliberately unavailable until it is on.
+ const ungatedAlwaysAvailable = ALWAYS_AVAILABLE_TOOLS.filter((tool) => tool !== "parallel_subtasks")
+ ungatedAlwaysAvailable.forEach((tool) => {
expect(isToolAllowedForMode(tool as any, "restrictive", [restrictiveMode])).toBe(true)
})
})
diff --git a/src/core/task/__tests__/task-root-task-id.spec.ts b/src/core/task/__tests__/task-root-task-id.spec.ts
new file mode 100644
index 0000000000..fc1afb26c8
--- /dev/null
+++ b/src/core/task/__tests__/task-root-task-id.spec.ts
@@ -0,0 +1,399 @@
+// npx vitest run core/task/__tests__/task-root-task-id.spec.ts
+
+import * as os from "os"
+import * as path from "path"
+
+import type { ExtensionContext } from "vscode"
+import {
+ providerIdentifiers,
+ type ClineMessage,
+ type GlobalState,
+ type HistoryItem,
+ type ProviderSettings,
+} from "@roo-code/types"
+import { TelemetryService } from "@roo-code/telemetry"
+
+import { Task } from "../Task"
+import { ClineProvider } from "../../webview/ClineProvider"
+import { ContextProxy } from "../../config/ContextProxy"
+import { WebviewFocusTracker } from "../../webview/WebviewFocusTracker"
+
+// CR-1 finding 2 (Task-side contract): an explicit `rootTaskId` option lets a
+// caller stamp the authoritative root id when no root TASK OBJECT is live — the
+// history-restore case where a task knows its root only as a stored id. The
+// option wins over the rootTask-object derivation when provided; when absent
+// the derivation is unchanged. A history-restored task always keeps its stored
+// rootTaskId.
+
+vi.mock("uuid", async (importOriginal) => {
+ const actual = await importOriginal()
+ return {
+ ...actual,
+ v7: vi.fn(() => "00000000-0000-7000-8000-000000000000"),
+ }
+})
+
+vi.mock("execa", () => ({
+ execa: vi.fn(),
+}))
+
+vi.mock("fs/promises", async (importOriginal) => {
+ const actual = await importOriginal()
+ const mockFunctions = {
+ mkdir: vi.fn().mockResolvedValue(undefined),
+ writeFile: vi.fn().mockResolvedValue(undefined),
+ readFile: vi.fn().mockResolvedValue("[]"),
+ unlink: vi.fn().mockResolvedValue(undefined),
+ rmdir: vi.fn().mockResolvedValue(undefined),
+ stat: vi.fn().mockRejectedValue({ code: "ENOENT" }),
+ readdir: vi.fn().mockResolvedValue([]),
+ }
+
+ return {
+ ...actual,
+ ...mockFunctions,
+ default: mockFunctions,
+ }
+})
+
+vi.mock("p-wait-for", () => ({
+ default: vi.fn().mockImplementation(async () => Promise.resolve()),
+}))
+
+vi.mock("../../../services/code-index/code-index-manager-registry", () => ({
+ CodeIndexManagerRegistry: {
+ getOrCreate: vi.fn().mockReturnValue(undefined),
+ getAllInstances: vi.fn().mockReturnValue([]),
+ disposeAll: vi.fn(),
+ },
+}))
+
+vi.mock("vscode", () => {
+ const mockDisposable = { dispose: vi.fn() }
+ const mockEventEmitter = { event: vi.fn(), fire: vi.fn() }
+
+ return {
+ TabInputTextDiff: vi.fn(),
+ CodeActionKind: {
+ QuickFix: { value: "quickfix" },
+ RefactorRewrite: { value: "refactor.rewrite" },
+ },
+ window: {
+ createTextEditorDecorationType: vi.fn().mockReturnValue({ dispose: vi.fn() }),
+ visibleTextEditors: [],
+ tabGroups: { all: [], close: vi.fn(), onDidChangeTabs: vi.fn(() => ({ dispose: vi.fn() })) },
+ showErrorMessage: vi.fn(),
+ },
+ workspace: {
+ workspaceFolders: [{ uri: { fsPath: "/mock/workspace/path" }, name: "mock-workspace", index: 0 }],
+ createFileSystemWatcher: vi.fn(() => ({
+ onDidCreate: vi.fn(() => mockDisposable),
+ onDidDelete: vi.fn(() => mockDisposable),
+ onDidChange: vi.fn(() => mockDisposable),
+ dispose: vi.fn(),
+ })),
+ fs: { stat: vi.fn().mockResolvedValue({ type: 1 }) },
+ onDidSaveTextDocument: vi.fn(() => mockDisposable),
+ getConfiguration: vi.fn(() => ({ get: (_key: string, defaultValue: unknown) => defaultValue })),
+ },
+ env: { uriScheme: "vscode", language: "en" },
+ EventEmitter: vi.fn().mockImplementation(function () {
+ return mockEventEmitter
+ }),
+ Disposable: { from: vi.fn() },
+ TabInputText: vi.fn(),
+ }
+})
+
+vi.mock("../../mentions", () => ({
+ parseMentions: vi.fn().mockImplementation((text) => {
+ return Promise.resolve({ text: `processed: ${text}`, mode: undefined, contentBlocks: [] })
+ }),
+ openMention: vi.fn(),
+ getLatestTerminalOutput: vi.fn(),
+}))
+
+vi.mock("../../../integrations/misc/extract-text", () => ({
+ extractTextFromFile: vi.fn().mockResolvedValue("Mock file content"),
+}))
+
+vi.mock("../../environment/getEnvironmentDetails", () => ({
+ getEnvironmentDetails: vi.fn().mockResolvedValue(""),
+}))
+
+vi.mock("../../ignore/RooIgnoreController")
+
+vi.mock("../../../i18n", () => {
+ return {
+ t: (key: string, args?: Record) => {
+ if (key === "tools:missingToolParameterWithPath") {
+ return `${args?.toolName}|${args?.relPath}|${args?.paramName}`
+ }
+ if (key === "tools:missingToolParameter") {
+ return `${args?.toolName}|${args?.paramName}`
+ }
+ return key
+ },
+ }
+})
+
+vi.mock("../../../utils/storage", () => ({
+ getTaskDirectoryPath: vi
+ .fn()
+ .mockImplementation((globalStoragePath, taskId) => Promise.resolve(`${globalStoragePath}/tasks/${taskId}`)),
+ getSettingsDirectoryPath: vi
+ .fn()
+ .mockImplementation((globalStoragePath) => Promise.resolve(`${globalStoragePath}/settings`)),
+}))
+
+vi.mock("../../../utils/fs", () => ({
+ fileExistsAtPath: vi.fn().mockReturnValue(false),
+}))
+
+// Keep taskMetadata real so the persisted historyItem shape is the production
+// one; only the fs-touching message write is stubbed (mirrors
+// background-stamp-reassert.spec.ts).
+vi.mock("../../task-persistence", async (importOriginal) => {
+ const actual = await importOriginal()
+ return {
+ ...actual,
+ saveTaskMessages: vi.fn().mockResolvedValue([]),
+ }
+})
+
+const ROOT_TASK_ID = "root-task-1"
+const OTHER_ROOT_TASK_ID = "root-task-2"
+const PARENT_TASK_ID = "parent-task-1"
+
+const taskSay: ClineMessage = { ts: 1, type: "say", say: "text", text: "child task", partial: false }
+
+describe("Task rootTaskId option (CR-1 finding 2)", () => {
+ let mockProvider: ClineProvider
+ let mockContextProxy: ContextProxy
+ let mockApiConfig: ProviderSettings
+ // Every task this suite constructs directly, so afterEach can dispose
+ // them. None of the tests register their tasks with the provider, so
+ // provider disposal alone cannot reach them.
+ let builtTasks: Task[] = []
+
+ beforeEach(() => {
+ if (!TelemetryService.hasInstance()) {
+ TelemetryService.createInstance([])
+ }
+
+ const storageUri = { fsPath: path.join(os.tmpdir(), "test-storage") }
+
+ const mockExtensionContext = {
+ globalState: {
+ get: vi.fn().mockImplementation((_key: keyof GlobalState) => undefined),
+ update: vi.fn().mockImplementation((_key, _value) => Promise.resolve()),
+ keys: vi.fn().mockReturnValue([]),
+ },
+ globalStorageUri: storageUri,
+ workspaceState: {
+ get: vi.fn().mockImplementation((_key) => undefined),
+ update: vi.fn().mockImplementation((_key, _value) => Promise.resolve()),
+ keys: vi.fn().mockReturnValue([]),
+ },
+ secrets: {
+ get: vi.fn().mockImplementation((_key) => Promise.resolve(undefined)),
+ store: vi.fn().mockImplementation((_key, _value) => Promise.resolve()),
+ delete: vi.fn().mockImplementation((_key) => Promise.resolve()),
+ },
+ extensionUri: { fsPath: "/mock/extension/path" },
+ extension: { packageJSON: { version: "1.0.0" } },
+ } as unknown as ExtensionContext
+
+ const mockOutputChannel = {
+ name: "test-output",
+ appendLine: vi.fn(),
+ append: vi.fn(),
+ replace: vi.fn(),
+ clear: vi.fn(),
+ show: vi.fn(),
+ hide: vi.fn(),
+ dispose: vi.fn(),
+ }
+
+ mockContextProxy = new ContextProxy(mockExtensionContext)
+ mockProvider = new ClineProvider(
+ mockExtensionContext,
+ mockOutputChannel,
+ "sidebar",
+ mockContextProxy,
+ new WebviewFocusTracker(),
+ )
+
+ mockApiConfig = {
+ apiProvider: providerIdentifiers.anthropic,
+ apiModelId: "claude-3-5-sonnet-20241022",
+ apiKey: "test-api-key",
+ }
+
+ mockProvider.postMessageToWebview = vi.fn().mockResolvedValue(undefined)
+ mockProvider.postStateToWebview = vi.fn().mockResolvedValue(undefined)
+ mockProvider.postStateToWebviewWithoutTaskHistory = vi.fn().mockResolvedValue(undefined)
+ mockProvider.postStateToWebviewThrottled = vi.fn().mockResolvedValue(undefined)
+ mockProvider.flushPostStateToWebviewThrottled = vi.fn().mockResolvedValue(undefined)
+ })
+
+ afterEach(async () => {
+ // Dispose every task this suite built, including after a failed
+ // assertion: the tests never register their tasks with the provider,
+ // so provider disposal alone cannot release them. Disposal runs before
+ // restoreAllMocks so the module mocks (fs, storage paths) are still in
+ // place for it, and a rejecting dispose must not mask the assertion
+ // failure under test.
+ //
+ // `Task.dispose()` writes to the console, so teardown emits
+ // worker->parent console RPCs while the worker is closing. Vitest
+ // reports that as `EnvironmentTeardownError: Closing rpc while
+ // "onUserConsoleLog" was pending` and exits non-zero even though every
+ // test passed. The repo runs with `silent: true`, so silencing it here
+ // drops no diagnostic.
+ const consoleQuiet = ["log", "info", "warn", "error", "debug"].map((key) =>
+ vi.spyOn(console, key as "log").mockImplementation(() => {}),
+ )
+ try {
+ for (const task of builtTasks) {
+ await task.dispose().catch(() => {})
+ }
+ builtTasks = []
+ await mockProvider.dispose().catch(() => {})
+ } finally {
+ for (const spy of consoleQuiet) {
+ spy.mockRestore()
+ }
+ }
+ vi.restoreAllMocks()
+ })
+
+ it("stamps the provided rootTaskId when no root task object is live", async () => {
+ // The CR-2 scenario: a task restored from History has rootTaskId: R with
+ // no live reference to R; when it spawns a child the caller stamps R
+ // explicitly instead of letting the child inherit the spawner's id.
+ vi.spyOn(mockProvider, "getState").mockResolvedValue({ mcpEnabled: false } as never)
+ const task = new Task({
+ provider: mockProvider,
+ apiConfiguration: mockApiConfig,
+ task: "child of a restored task",
+ startTask: false,
+ rootTaskId: ROOT_TASK_ID,
+ parentTask: { taskId: PARENT_TASK_ID } as unknown as Task,
+ })
+ // Track before the first await so a throw in getTaskMode still leaves a
+ // reachable task for afterEach disposal.
+ builtTasks.push(task)
+ await task.getTaskMode()
+
+ expect(task.rootTaskId).toBe(ROOT_TASK_ID)
+ expect(task.parentTaskId).toBe(PARENT_TASK_ID)
+ })
+
+ it("the explicit rootTaskId wins over the rootTask object derivation", async () => {
+ vi.spyOn(mockProvider, "getState").mockResolvedValue({ mcpEnabled: false } as never)
+ const rootTask = { taskId: OTHER_ROOT_TASK_ID } as unknown as Task
+ const task = new Task({
+ provider: mockProvider,
+ apiConfiguration: mockApiConfig,
+ task: "stamped child",
+ startTask: false,
+ rootTask,
+ rootTaskId: ROOT_TASK_ID,
+ })
+ // Track before the first await so a throw in getTaskMode still leaves a
+ // reachable task for afterEach disposal.
+ builtTasks.push(task)
+ await task.getTaskMode()
+
+ expect(task.rootTaskId).toBe(ROOT_TASK_ID)
+ })
+
+ it("absent option keeps the rootTask object derivation", async () => {
+ vi.spyOn(mockProvider, "getState").mockResolvedValue({ mcpEnabled: false } as never)
+ const rootTask = { taskId: ROOT_TASK_ID } as unknown as Task
+ const task = new Task({
+ provider: mockProvider,
+ apiConfiguration: mockApiConfig,
+ task: "derived child",
+ startTask: false,
+ rootTask,
+ })
+ // Track before the first await so a throw in getTaskMode still leaves a
+ // reachable task for afterEach disposal.
+ builtTasks.push(task)
+ await task.getTaskMode()
+
+ expect(task.rootTaskId).toBe(ROOT_TASK_ID)
+ })
+
+ it("a rootless new task keeps rootTaskId undefined", async () => {
+ vi.spyOn(mockProvider, "getState").mockResolvedValue({ mcpEnabled: false } as never)
+ const task = new Task({
+ provider: mockProvider,
+ apiConfiguration: mockApiConfig,
+ task: "plain task",
+ startTask: false,
+ })
+ // Track before the first await so a throw in getTaskMode still leaves a
+ // reachable task for afterEach disposal.
+ builtTasks.push(task)
+ await task.getTaskMode()
+
+ expect(task.rootTaskId).toBeUndefined()
+ })
+
+ it("a history-restored task keeps its stored rootTaskId even when the option is provided", async () => {
+ vi.spyOn(mockProvider, "getState").mockResolvedValue({ mcpEnabled: false } as never)
+ const historyItem: HistoryItem = {
+ id: "restored-1",
+ rootTaskId: OTHER_ROOT_TASK_ID,
+ parentTaskId: PARENT_TASK_ID,
+ number: 1,
+ ts: 1,
+ task: "restored task",
+ tokensIn: 0,
+ tokensOut: 0,
+ totalCost: 0,
+ }
+ const task = new Task({
+ provider: mockProvider,
+ apiConfiguration: mockApiConfig,
+ historyItem,
+ startTask: false,
+ rootTaskId: ROOT_TASK_ID,
+ })
+ // Track before the first await so a throw in getTaskMode still leaves a
+ // reachable task for afterEach disposal.
+ builtTasks.push(task)
+ await task.getTaskMode()
+
+ expect(task.rootTaskId).toBe(OTHER_ROOT_TASK_ID)
+ })
+
+ it("saveClineMessages persists the stamped rootTaskId via taskMetadata", async () => {
+ vi.spyOn(mockProvider, "getState").mockResolvedValue({ mcpEnabled: false } as never)
+ const task = new Task({
+ provider: mockProvider,
+ apiConfiguration: mockApiConfig,
+ task: "child of a restored task",
+ startTask: false,
+ rootTaskId: ROOT_TASK_ID,
+ parentTask: { taskId: PARENT_TASK_ID } as unknown as Task,
+ })
+ // Track before the first await so a throw in getTaskMode still leaves a
+ // reachable task for afterEach disposal.
+ builtTasks.push(task)
+ await task.getTaskMode()
+
+ const updateSpy = vi.spyOn(mockProvider, "updateTaskHistory").mockResolvedValue([])
+ task["clineMessages"] = [taskSay]
+
+ await task["saveClineMessages"]()
+
+ expect(updateSpy).toHaveBeenCalledTimes(1)
+ const persisted = updateSpy.mock.calls[0][0] as { rootTaskId?: string; parentTaskId?: string }
+ expect(persisted.rootTaskId).toBe(ROOT_TASK_ID)
+ expect(persisted.parentTaskId).toBe(PARENT_TASK_ID)
+ })
+})
diff --git a/src/core/tools/AttemptCompletionTool.ts b/src/core/tools/AttemptCompletionTool.ts
index 3114e753c5..ea47505e74 100644
--- a/src/core/tools/AttemptCompletionTool.ts
+++ b/src/core/tools/AttemptCompletionTool.ts
@@ -3,6 +3,7 @@ import * as vscode from "vscode"
import { RooCodeEventName, type HistoryItem, type PendingTaskAction } from "@roo-code/types"
import { Task } from "../task/Task"
+import type { BackgroundSubtaskHost } from "../background-subtasks/types"
import { formatResponse } from "../prompts/responses"
import { Package } from "../../shared/package"
import type { ToolUse } from "../../shared/tools"
@@ -102,6 +103,55 @@ export class AttemptCompletionTool extends BaseTool<"attempt_completion"> {
// "continue" instead of returning.
let hasFlushedTelemetry = false
+ // Background (read-only) child completion branch, design D5.
+ //
+ // A background child is non-interactive: it reports its findings through
+ // attempt_completion and the host collects them, so it must never fall through
+ // to the completion_result ask below (F8: a rejected completion injects user
+ // feedback and loops). The branch sits before the parentTaskId delegation
+ // check so a background child, which does carry parentTaskId for lineage,
+ // never enters the interactive delegation state machine either. The say and
+ // mistake reset above already ran for this call.
+ if (task.isBackgroundSubtaskChild) {
+ // The same installment the delegation branch flushes before it hands
+ // control back, so a background child is not invisible in usage.
+ task.emitFinalTokenUsageUpdate()
+ task.flushTelemetryInstallment("attempt_completion")
+
+ // ClineProvider does not statically declare BackgroundSubtaskHost in this
+ // unit (the provider wires it), so the deref needs an explicit widening;
+ // the method-existence check below keeps this safe at runtime.
+ const host = task.providerRef.deref() as unknown as BackgroundSubtaskHost | undefined
+ if (host?.resolveBackgroundChild) {
+ host.resolveBackgroundChild(task.taskId, result)
+ } else {
+ // The host is gone (provider disposed mid-fan-out), so no host
+ // record exists to settle. The abort below still ends this
+ // child's run loop, and the spawning host's run-settled catch-all
+ // then settles the handle as failed instead of leaving the
+ // parent's Promise.all join pending forever (F-02/F-03).
+ console.warn(
+ `[AttemptCompletionTool] Background child ${task.taskId} completed but no BackgroundSubtaskHost is registered; aborting the child so its handle settles as failed.`,
+ )
+ }
+
+ // End the child's own run loop now. The loop's abort/abandoned guard
+ // (Task.recursivelyMakeClineRequests) throws into the loop's
+ // didEndLoop catch and run() settles, so no runaway loop outlives the
+ // result -- and in the no-host branch that same run-settled path is
+ // what fails the handle. requestAbort(true) over requestAbandon():
+ // the run-state reducer rejects abandonRequested while the abort
+ // latch is unset, and this also advances the S4a
+ // cancellationGeneration. abortTask() is deliberately not used: its
+ // TaskAborted emit would settle the host handle as "aborted" and
+ // overwrite the terminal status the host just persisted.
+ task.requestAbort(true)
+
+ // Empty tool result: the child's loop ends here. No ask, no user feedback.
+ pushToolResult("")
+ return
+ }
+
// Check for subtask using parentTaskId (metadata-driven delegation)
if (task.parentTaskId) {
// Check if this subtask has already completed and returned to parent
diff --git a/src/core/tools/ParallelSubtasksTool.ts b/src/core/tools/ParallelSubtasksTool.ts
new file mode 100644
index 0000000000..12471b6248
--- /dev/null
+++ b/src/core/tools/ParallelSubtasksTool.ts
@@ -0,0 +1,409 @@
+import { RooCodeEventName } from "@roo-code/types"
+import type { ClineMessage, ParallelSubtaskInfo } from "@roo-code/types"
+
+import { Task } from "../task/Task"
+import type { ClineProvider } from "../webview/ClineProvider"
+import { formatResponse } from "../prompts/responses"
+import { MAX_REQUESTED_PARALLEL_SUBTASKS } from "../assistant-message/NativeToolCallParser"
+import { BaseTool, ToolCallbacks } from "./BaseTool"
+import type { PushToolResult, ToolResponse, ToolUse } from "../../shared/tools"
+import { writeSubtaskReport } from "../subtask-reports"
+import type { BackgroundChildEntry, BackgroundSubtaskSpec } from "../background-subtasks/types"
+
+interface ParallelSubtasksParams {
+ tasks: Array<{ label?: string; mode: string; message: string }>
+}
+
+/** One-line summary cap for the progress row and the parent-facing result. */
+const SUMMARY_MAX_LENGTH = 120
+
+/** Entries kept while coercing a streamed preview; one past the ceiling makes an over-limit call visible. */
+const MAX_COERCED_TASKS = MAX_REQUESTED_PARALLEL_SUBTASKS + 1
+
+/** Fan-out the tool contract documents; excess entries are reported as dropped. */
+const DOCUMENTED_FAN_OUT = 6
+
+/**
+ * Coerces the `tasks` argument from its wire forms (parsed array or JSON
+ * string, as partial streaming can deliver either) into complete entries
+ * only; entries missing a mode or message are dropped, mirroring
+ * `NativeToolCallParser.normalizeParallelSubtaskTasks`. Collection stops one
+ * past `MAX_REQUESTED_PARALLEL_SUBTASKS` so a streamed preview of an oversized
+ * call stays bounded.
+ */
+function coerceTasks(value: unknown): ParallelSubtasksParams["tasks"] {
+ let entries: unknown = value
+ if (typeof value === "string") {
+ try {
+ entries = JSON.parse(value)
+ } catch {
+ return []
+ }
+ }
+ if (!Array.isArray(entries)) {
+ return []
+ }
+ const tasks: ParallelSubtasksParams["tasks"] = []
+ for (const entry of entries) {
+ if (tasks.length >= MAX_COERCED_TASKS) {
+ break
+ }
+ if (typeof entry !== "object" || entry === null) {
+ continue
+ }
+ const record: Record = { ...entry }
+ if (typeof record.mode !== "string" || typeof record.message !== "string") {
+ continue
+ }
+ tasks.push({
+ ...(typeof record.label === "string" ? { label: record.label } : {}),
+ mode: record.mode,
+ message: record.message,
+ })
+ }
+ return tasks
+}
+
+/**
+ * Assigns every child a sibling-unique label: absent labels default to
+ * `child-N`, duplicates gain a numeric suffix, and the requested order is
+ * kept so reports and the progress panel read like the tool call. Each base
+ * remembers the next suffix to try, so the scan advances instead of
+ * restarting at `-2` for every duplicate (no quadratic loop over the list).
+ */
+function buildUniqueSpecs(requested: ParallelSubtasksParams["tasks"]): BackgroundSubtaskSpec[] {
+ const used = new Set()
+ const nextSuffix = new Map()
+ return requested.map((entry, index) => {
+ const base = entry.label && entry.label.trim() !== "" ? entry.label : `child-${index + 1}`
+ let label = base
+ let suffix = nextSuffix.get(base) ?? 2
+ while (used.has(label)) {
+ label = `${base}-${suffix}`
+ suffix++
+ }
+ used.add(label)
+ nextSuffix.set(base, suffix)
+ return { label, mode: entry.mode, message: entry.message }
+ })
+}
+
+function summarizeReport(markdown: string): string {
+ const firstLine = markdown.split("\n", 1)[0]?.trim() ?? ""
+ return firstLine.length > SUMMARY_MAX_LENGTH ? `${firstLine.slice(0, SUMMARY_MAX_LENGTH)}...` : firstLine
+}
+
+export class ParallelSubtasksTool extends BaseTool<"parallel_subtasks"> {
+ readonly name = "parallel_subtasks" as const
+
+ async execute(params: ParallelSubtasksParams, task: Task, callbacks: ToolCallbacks): Promise {
+ const { askApproval, handleError, pushToolResult } = callbacks
+ let provider: ClineProvider | undefined
+
+ try {
+ // Validate required parameters.
+ if (!params || !Array.isArray(params.tasks) || params.tasks.length === 0) {
+ task.consecutiveMistakeCount++
+ task.recordToolError("parallel_subtasks")
+ task.didToolFailInCurrentTurn = true
+ pushToolResult(await task.sayAndCreateMissingParamError("parallel_subtasks", "tasks"))
+ return
+ }
+
+ // The array is bound at parse time; this is the enforcement point for
+ // the hard ceiling. Rejecting before any spec work keeps the approval
+ // payload, the progress rows, and the label de-duplication bounded.
+ if (params.tasks.length > MAX_REQUESTED_PARALLEL_SUBTASKS) {
+ task.consecutiveMistakeCount++
+ task.recordToolError("parallel_subtasks")
+ task.didToolFailInCurrentTurn = true
+ pushToolResult(
+ formatResponse.toolError(
+ `parallel_subtasks accepts at most ${MAX_REQUESTED_PARALLEL_SUBTASKS} task entries per call; this call exceeded that limit. ` +
+ `Split the work into calls of at most ${DOCUMENTED_FAN_OUT} investigations.`,
+ ),
+ )
+ return
+ }
+
+ const specs = buildUniqueSpecs(params.tasks)
+ provider = task.providerRef.deref()
+
+ if (!provider) {
+ pushToolResult(formatResponse.toolError("Provider reference lost"))
+ return
+ }
+
+ task.consecutiveMistakeCount = 0
+
+ // Exactly one user approval point for the whole fan-out (design §11).
+ // Protected: a queued follow-up message must not stand in for the
+ // approval click (Task.ask exempts protected asks from queue draining),
+ // while checkAutoApproval still honors alwaysAllowSubtasks for tool asks.
+ const toolMessage = JSON.stringify({
+ tool: "parallelSubtasks",
+ tasks: specs.map((s) => ({ label: s.label, mode: s.mode, message: s.message })),
+ })
+ const didApprove = await askApproval("tool", toolMessage, undefined, true)
+
+ if (!didApprove) {
+ return
+ }
+
+ await this.runFanOut(task, provider, specs, pushToolResult)
+ } catch (error) {
+ // A tool failure must not leave live children behind (design D8):
+ // settle every still-pending child before the error is reported.
+ void provider?.abortBackgroundChildren(task.taskId).catch(() => {})
+ await handleError("running parallel subtasks", error)
+ }
+ }
+
+ private async runFanOut(
+ task: Task,
+ provider: ClineProvider,
+ specs: BackgroundSubtaskSpec[],
+ pushToolResult: PushToolResult,
+ ): Promise {
+ // Observe the parent's own abort so a cancel that bypasses the provider's
+ // cascade still settles every child this tool is awaiting (design D8).
+ const onAborted = () => {
+ void provider.abortBackgroundChildren(task.taskId).catch(() => {})
+ }
+ task.once(RooCodeEventName.TaskAborted, onAborted)
+
+ const rows = new Map()
+
+ // The panel is a single say row (partial:true) created by the first post
+ // and updated in place by message identity afterwards. Task.say() cannot
+ // carry the updates: it only replaces the LAST partial row of the same
+ // type, so any message of another type landing between updates (e.g. a
+ // reasoning chunk) would make the next panel post create a second row
+ // instead of updating the first, stranding a stale panel beside the real
+ // one. The identity update follows Task's own reasoning-row precedent:
+ // mutate the captured message, then updateClineMessage(), and persist
+ // with saveClineMessages() once the row finalizes. The first post must
+ // capture the row by reference from say()'s return value, not by tail
+ // position: say() pushes the row before its persistence awaits resolve,
+ // so a say of another type landing during that wait appends its own row
+ // at the tail and clineMessages.at(-1) would capture that row instead.
+ let rowChain: Promise = Promise.resolve()
+ let panelMessage: ClineMessage | undefined
+ const postRow = async (partial: boolean): Promise => {
+ if (task.abort) {
+ // Mirror Task.say, which refuses to post once the task is aborting:
+ // the chained updates above swallow the throw, while the awaited
+ // final post propagates it so no tool result is pushed for an
+ // aborted task.
+ throw new Error(`[RooCode#say] task ${task.taskId} aborted`)
+ }
+ const text = JSON.stringify({ tool: "parallelSubtasks", subtasks: Array.from(rows.values()) })
+ if (!panelMessage) {
+ // First post: say() appends the partial row (or adopts a stale
+ // partial tool row left by an earlier interrupted fan-out) and
+ // returns the exact row it touched; keep that reference.
+ panelMessage = await task.say("tool", text, undefined, true)
+ return
+ }
+ panelMessage.text = text
+ if (!partial) {
+ panelMessage.partial = false
+ }
+ await task["updateClineMessage"](panelMessage)
+ if (!partial) {
+ // The finalized row must survive a restart, not just this session.
+ const persisted = await task["saveClineMessages"]()
+ if (!persisted) {
+ // Retry once: a transient message-file failure should not
+ // ship a success payload whose panel the restored chat would
+ // render without report links. The retry rewrites messages
+ // only; children are not rerun and their reports on disk are
+ // left untouched.
+ const retried = await task["saveClineMessages"]()
+ if (!retried) {
+ throw new Error(
+ `parallel_subtasks: failed to persist the finalized progress panel for task ${task.taskId}`,
+ )
+ }
+ }
+ }
+ }
+ const enqueueRowUpdate = (): void => {
+ rowChain = rowChain.then(() => postRow(true)).catch(() => {})
+ }
+
+ // Host-reported "running" transitions (F-09) arrive from inside the
+ // scheduler permit, which can be before the rows exist, so they are
+ // buffered until the initial post is done.
+ const pendingStarts = new Map()
+ let rowsReady = false
+ const applyStart = (taskId: string, startedAt: number): void => {
+ const row = rows.get(taskId)
+ if (!row) {
+ return
+ }
+ row.status = "running"
+ row.startedAt = startedAt
+ }
+ const flushPendingStarts = (): boolean => {
+ if (pendingStarts.size === 0) {
+ return false
+ }
+ for (const [taskId, startedAt] of pendingStarts) {
+ applyStart(taskId, startedAt)
+ }
+ pendingStarts.clear()
+ return true
+ }
+
+ try {
+ const spawned = await provider.spawnBackgroundChildren(task, specs, {
+ onChildStarted: (entry) => {
+ if (!rowsReady) {
+ pendingStarts.set(entry.taskId, entry.startedAt)
+ return
+ }
+ applyStart(entry.taskId, entry.startedAt)
+ enqueueRowUpdate()
+ },
+ })
+ const handles = spawned.children
+ // Specs the host dropped (the per-call cap slices the batch) still get
+ // a terminal row and a result line so nothing vanishes silently.
+ const dropped = specs.slice(handles.length)
+
+ for (const handle of handles) {
+ rows.set(handle.taskId, {
+ taskId: handle.taskId,
+ label: handle.label,
+ mode: handle.mode,
+ status: "queued",
+ })
+ }
+ dropped.forEach((spec, index) => {
+ rows.set(`dropped-${index}`, {
+ taskId: `dropped-${index}`,
+ label: spec.label,
+ mode: spec.mode,
+ status: "failed",
+ // `handles.length` counts the specs the host considered under its
+ // cap, not children that actually started: a considered spec can
+ // already be a settled failure (unknown mode, cancelled parent).
+ error: `Dropped: the request exceeded the per-call limit (${handles.length} of ${specs.length} specs considered)`,
+ })
+ })
+
+ // A child that acquired its permit before the rows existed is shown
+ // as running in the first post instead of queued.
+ flushPendingStarts()
+ await postRow(true)
+ rowsReady = true
+ // A start that raced the initial post still needs its own update.
+ if (flushPendingStarts()) {
+ enqueueRowUpdate()
+ }
+
+ for (const handle of handles) {
+ void handle.done
+ .then((entry) => {
+ this.applyEntry(rows.get(handle.taskId), entry)
+ enqueueRowUpdate()
+ })
+ .catch(() => {})
+ }
+
+ // done never rejects, so the join always settles, including when the
+ // abort cascade above marks every child aborted.
+ const entries = await Promise.all(handles.map((handle) => handle.done))
+ await rowChain
+
+ for (const entry of entries) {
+ if (entry.status !== "completed" || entry.result === undefined) {
+ continue
+ }
+ const row = rows.get(entry.taskId)
+ if (!row) {
+ continue
+ }
+ try {
+ const report = await writeSubtaskReport({
+ cwd: task.cwd,
+ parentTaskId: task.taskId,
+ childTaskId: entry.taskId,
+ label: entry.label,
+ markdown: entry.result,
+ })
+ row.reportPath = report.path
+ row.summary = summarizeReport(entry.result)
+ } catch (error) {
+ // A failed save demotes only that child; the sibling reports
+ // are already committed and the rest of the join is unaffected.
+ row.status = "failed"
+ row.error = `Report write failed: ${error instanceof Error ? error.message : String(error)}`
+ row.reportPath = undefined
+ }
+ }
+
+ await postRow(false)
+ pushToolResult(this.buildResultPayload(specs.length, rows))
+ } finally {
+ task.off(RooCodeEventName.TaskAborted, onAborted)
+ }
+ }
+
+ private applyEntry(row: ParallelSubtaskInfo | undefined, entry: BackgroundChildEntry): void {
+ if (!row) {
+ return
+ }
+ row.status = entry.status
+ row.startedAt = entry.startedAt
+ row.finishedAt = entry.finishedAt
+ row.error = entry.error
+ }
+
+ private buildResultPayload(specCount: number, rows: Map): ToolResponse {
+ const lines: string[] = []
+ let completedCount = 0
+ for (const row of rows.values()) {
+ if (row.status === "completed" && row.reportPath) {
+ completedCount++
+ // The parent model reads the payload, not the progress rows, so
+ // carry the one-line summary alongside the path to the report.
+ lines.push(
+ row.summary
+ ? `- ${row.label}: completed. Report: ${row.reportPath}. Summary: ${row.summary}`
+ : `- ${row.label}: completed. Report: ${row.reportPath}`,
+ )
+ } else {
+ lines.push(`- ${row.label}: ${row.status}${row.error ? ` (${row.error})` : ""}`)
+ }
+ }
+ const text = [
+ `parallel_subtasks finished: ${completedCount}/${specCount} children completed.`,
+ ...lines,
+ "",
+ "Each report is a markdown file. Read the ones you need with read_file before acting on the findings.",
+ ].join("\n")
+ return formatResponse.toolResult(text)
+ }
+
+ override async handlePartial(task: Task, block: ToolUse<"parallel_subtasks">): Promise {
+ // Prefer the parser's already-bounded list: the raw `params.tasks` can be
+ // the full streamed array as one JSON string, and re-parsing that on every
+ // chunk would defeat the bound at parse time.
+ const raw: unknown = block.nativeArgs?.tasks ?? block.params.tasks
+ const tasks = coerceTasks(raw)
+ const partialMessage = JSON.stringify({
+ tool: "parallelSubtasks",
+ tasks: tasks.map((entry) => ({
+ label: entry.label ?? "",
+ mode: entry.mode ?? "",
+ message: entry.message ?? "",
+ })),
+ })
+
+ await task.ask("tool", partialMessage, block.partial).catch(() => {})
+ }
+}
+
+export const parallelSubtasksTool = new ParallelSubtasksTool()
diff --git a/src/core/tools/__tests__/CodebaseSearchTool.spec.ts b/src/core/tools/__tests__/CodebaseSearchTool.spec.ts
index eb0c27c1ae..5f13d88650 100644
--- a/src/core/tools/__tests__/CodebaseSearchTool.spec.ts
+++ b/src/core/tools/__tests__/CodebaseSearchTool.spec.ts
@@ -59,7 +59,7 @@ describe("CodebaseSearchTool", () => {
sayAndCreateMissingParamError: vi
.fn()
.mockResolvedValue("missing query"),
- say: vi.fn().mockResolvedValue(undefined),
+ say: vi.fn().mockResolvedValue({ ts: 0, type: "say", say: "text", text: "" }),
ask: vi.fn().mockResolvedValue({ response: "yesButtonClicked" }),
}
task = taskStub as Task
diff --git a/src/core/tools/__tests__/CodebaseSearchTool.workspace.spec.ts b/src/core/tools/__tests__/CodebaseSearchTool.workspace.spec.ts
index f6f6c0f5cb..9b1e759325 100644
--- a/src/core/tools/__tests__/CodebaseSearchTool.workspace.spec.ts
+++ b/src/core/tools/__tests__/CodebaseSearchTool.workspace.spec.ts
@@ -75,11 +75,12 @@ describe("CodebaseSearchTool workspace selection", () => {
vi.mocked(getWorkspacePath).mockReturnValue(first.uri.fsPath)
// Only the provider context and task members consumed by this tool are needed.
provider = { context: makeExtensionContext(), contextProxy: {} } as ClineProvider
+ // `say` returns the message it appended, so the stub resolves one.
const taskStub: Pick = {
cwd: second.uri.fsPath,
providerRef: new WeakRef(provider),
consecutiveMistakeCount: 0,
- say: vi.fn().mockResolvedValue(undefined),
+ say: vi.fn().mockResolvedValue({ ts: 0, type: "say", say: "text", text: "" }),
}
task = taskStub as Task
callbacks = {
diff --git a/src/core/tools/__tests__/attemptCompletionTool.background.spec.ts b/src/core/tools/__tests__/attemptCompletionTool.background.spec.ts
new file mode 100644
index 0000000000..be9c902a0a
--- /dev/null
+++ b/src/core/tools/__tests__/attemptCompletionTool.background.spec.ts
@@ -0,0 +1,337 @@
+import { RooCodeEventName } from "@roo-code/types"
+
+import { ToolUse } from "../../../shared/tools"
+
+// Mock the formatResponse module before importing the tool
+vi.mock("../../prompts/responses", () => ({
+ formatResponse: {
+ toolError: vi.fn((msg: string) => `Error: ${msg}`),
+ toolResult: vi.fn((msg: string) => `Result: ${msg}`),
+ toolDenied: vi.fn(() => "Denied"),
+ },
+}))
+
+// Mock vscode module (the tool reads the preventCompletionWithOpenTodos setting;
+// the default mock returns undefined for every key, which keeps the guard off)
+vi.mock("vscode", () => ({
+ workspace: {
+ getConfiguration: vi.fn(() => ({
+ get: vi.fn(),
+ })),
+ },
+}))
+
+// Mock Package module
+vi.mock("../../../shared/package", () => ({
+ Package: {
+ name: "zoo-code",
+ },
+}))
+
+import { attemptCompletionTool, AttemptCompletionCallbacks } from "../AttemptCompletionTool"
+import { Task } from "../../task/Task"
+import type { BackgroundSubtaskHost } from "../../background-subtasks/types"
+import { AskApproval, HandleError, PushToolResult } from "../../../shared/tools"
+
+// D5: a background (read-only) child reports its findings through
+// attempt_completion and the host collects them. The tool must settle the
+// parent's promise and return WITHOUT ever asking the user, and the branch
+// must run before the parentTaskId delegation state machine (a background
+// child carries parentTaskId for lineage but is not an interactive delegate).
+
+function makeBlock(result: string | undefined): ToolUse<"attempt_completion"> {
+ return {
+ type: "tool_use",
+ name: "attempt_completion",
+ params: { result: result ?? "" },
+ nativeArgs: { result: result ?? "" },
+ partial: false,
+ }
+}
+
+describe("attemptCompletionTool background child branch (D5)", () => {
+ let mockPushToolResult: ReturnType>
+ let mockAskApproval: ReturnType>
+ let mockHandleError: ReturnType>
+ let mockToolDescription: ReturnType string>>
+ let mockAskFinishSubTaskApproval: ReturnType Promise>>
+ let warnSpy: ReturnType
+
+ beforeEach(() => {
+ mockPushToolResult = vi.fn()
+ mockAskApproval = vi.fn()
+ mockHandleError = vi.fn()
+ mockToolDescription = vi.fn<() => string>()
+ mockAskFinishSubTaskApproval = vi.fn<() => Promise>()
+ warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {})
+ })
+
+ afterEach(() => {
+ warnSpy.mockRestore()
+ })
+
+ function makeCallbacks(): AttemptCompletionCallbacks {
+ return {
+ askApproval: mockAskApproval,
+ handleError: mockHandleError,
+ pushToolResult: mockPushToolResult,
+ toolCallId: "call-background-completion",
+ askFinishSubTaskApproval: mockAskFinishSubTaskApproval,
+ toolDescription: mockToolDescription,
+ }
+ }
+
+ function makeBackgroundTask(overrides: Partial = {}): Partial