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 { + return { + consecutiveMistakeCount: 0, + recordToolError: vi.fn(), + todoList: undefined, + say: vi.fn().mockResolvedValue(undefined), + ask: vi.fn().mockResolvedValue({ response: "yesButtonClicked", text: "", images: [] }), + emitFinalTokenUsageUpdate: vi.fn(), + requestAbort: vi.fn(), + emit: vi.fn(), + getTokenUsage: vi.fn().mockReturnValue({}), + toolUsage: {}, + messageCounts: { user: 0, assistant: 0 }, + taskId: "bg-child-1", + parentTaskId: "parent-1", + isBackgroundSubtaskChild: true, + flushTelemetryInstallment: vi.fn(), + setPendingTaskAction: vi.fn(), + sayAndCreateMissingParamError: vi.fn().mockResolvedValue("missing result param"), + persistQueuedFeedbackAndAcknowledge: vi.fn().mockResolvedValue(true), + waitForCurrentAssistantMessagePersistence: vi.fn().mockResolvedValue(true), + ...overrides, + } + } + + it("collects the result, settles the host promise, and never asks the user", async () => { + const host: BackgroundSubtaskHost = { + resolveBackgroundChild: vi.fn(), + failBackgroundChild: vi.fn(), + } + const task = makeBackgroundTask() + Object.assign(task, { providerRef: { deref: () => host } }) + + await attemptCompletionTool.handle(task as Task, makeBlock("findings report"), makeCallbacks()) + + expect(task.say).toHaveBeenCalledWith("completion_result", "findings report", undefined, false) + expect(host.resolveBackgroundChild).toHaveBeenCalledWith("bg-child-1", "findings report") + expect(host.failBackgroundChild).not.toHaveBeenCalled() + expect(mockPushToolResult).toHaveBeenCalledWith("") + expect(task.ask).not.toHaveBeenCalled() + expect(mockAskFinishSubTaskApproval).not.toHaveBeenCalled() + expect(mockHandleError).not.toHaveBeenCalled() + expect(warnSpy).not.toHaveBeenCalled() + }) + + it("ends the child's own run loop after the host collects the result", async () => { + // The scheduler permit is released only when run() settles, so the D5 + // branch must terminate the loop itself: the host settle alone leaves + // run() pending forever and starves every later background child once + // DEFAULT_MAX_PARALLEL_SUBTASKS children have completed in the session. + const resolveBackgroundChild = vi.fn() + const requestAbort = vi.fn() + const host: BackgroundSubtaskHost = { + resolveBackgroundChild, + failBackgroundChild: vi.fn(), + } + const task = makeBackgroundTask({ requestAbort }) + Object.assign(task, { providerRef: { deref: () => host } }) + + await attemptCompletionTool.handle(task as Task, makeBlock("findings report"), makeCallbacks()) + + // The run ends only after the result is collected, so the "completed" + // persist can never be overwritten by an abort-driven terminal write. + expect(requestAbort).toHaveBeenCalledTimes(1) + expect(requestAbort).toHaveBeenCalledWith(true) + expect(requestAbort.mock.invocationCallOrder[0]).toBeGreaterThan( + resolveBackgroundChild.mock.invocationCallOrder[0], + ) + // The tool result still feeds the loop's history before the run ends. + expect(mockPushToolResult).toHaveBeenCalledWith("") + expect(task.ask).not.toHaveBeenCalled() + }) + + it("flushes the attempt_completion telemetry installment exactly once", async () => { + const host: BackgroundSubtaskHost = { + resolveBackgroundChild: vi.fn(), + failBackgroundChild: vi.fn(), + } + const task = makeBackgroundTask() + Object.assign(task, { providerRef: { deref: () => host } }) + + await attemptCompletionTool.handle(task as Task, makeBlock("usage report"), makeCallbacks()) + + expect(task.emitFinalTokenUsageUpdate).toHaveBeenCalledTimes(1) + expect(task.flushTelemetryInstallment).toHaveBeenCalledTimes(1) + expect(task.flushTelemetryInstallment).toHaveBeenCalledWith("attempt_completion") + }) + + it("runs before the parentTaskId delegation branch even though the child carries parentTaskId", async () => { + // The provider offers BOTH the delegation surface and the background host; + // entering the delegation state machine would call getTaskWithId. + const provider = { + log: vi.fn(), + getTaskWithId: vi.fn(), + setPendingTaskAction: vi.fn(), + clearPendingTaskAction: vi.fn(), + emitDelegatedTaskCompleted: vi.fn(), + reopenParentFromDelegation: vi.fn(), + resolveBackgroundChild: vi.fn(), + failBackgroundChild: vi.fn(), + } + const task = makeBackgroundTask() + Object.assign(task, { providerRef: { deref: () => provider } }) + + await attemptCompletionTool.handle(task as Task, makeBlock("ordering report"), makeCallbacks()) + + expect(provider.resolveBackgroundChild).toHaveBeenCalledWith("bg-child-1", "ordering report") + expect(provider.getTaskWithId).not.toHaveBeenCalled() + expect(provider.setPendingTaskAction).not.toHaveBeenCalled() + expect(provider.reopenParentFromDelegation).not.toHaveBeenCalled() + expect(provider.emitDelegatedTaskCompleted).not.toHaveBeenCalled() + expect(mockAskFinishSubTaskApproval).not.toHaveBeenCalled() + expect(task.ask).not.toHaveBeenCalled() + expect(mockPushToolResult).toHaveBeenCalledWith("") + }) + + it("aborts the child when no BackgroundSubtaskHost is registered so its handle can settle", async () => { + const requestAbort = vi.fn() + const task = makeBackgroundTask({ requestAbort }) + // A live provider object that does not implement the host interface. + Object.assign(task, { providerRef: { deref: () => ({}) } }) + + await attemptCompletionTool.handle(task as Task, makeBlock("orphan report"), makeCallbacks()) + + expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining("no BackgroundSubtaskHost is registered")) + // F-03: no host can settle the handle, so the child ends its own run + // loop; the spawn-time run-settled catch-all then fails the handle. + expect(requestAbort).toHaveBeenCalledTimes(1) + expect(requestAbort).toHaveBeenCalledWith(true) + expect(mockPushToolResult).toHaveBeenCalledWith("") + expect(task.ask).not.toHaveBeenCalled() + expect(mockAskFinishSubTaskApproval).not.toHaveBeenCalled() + }) + + it("aborts the child when the provider is gone", async () => { + const requestAbort = vi.fn() + const task = makeBackgroundTask({ requestAbort }) + Object.assign(task, { providerRef: { deref: () => undefined } }) + + await attemptCompletionTool.handle(task as Task, makeBlock("disposed report"), makeCallbacks()) + + expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining("no BackgroundSubtaskHost is registered")) + expect(requestAbort).toHaveBeenCalledTimes(1) + expect(requestAbort).toHaveBeenCalledWith(true) + expect(mockPushToolResult).toHaveBeenCalledWith("") + expect(task.ask).not.toHaveBeenCalled() + }) + + it("still treats a missing result param as a mistake instead of a silent completion", async () => { + const host: BackgroundSubtaskHost = { + resolveBackgroundChild: vi.fn(), + failBackgroundChild: vi.fn(), + } + const task = makeBackgroundTask() + Object.assign(task, { providerRef: { deref: () => host } }) + + const block: ToolUse<"attempt_completion"> = { + type: "tool_use", + name: "attempt_completion", + params: { result: "" }, + nativeArgs: { result: "" }, + partial: false, + } + + await attemptCompletionTool.handle(task as Task, block, makeCallbacks()) + + expect(task.consecutiveMistakeCount).toBe(1) + expect(task.recordToolError).toHaveBeenCalledWith("attempt_completion") + expect(task.sayAndCreateMissingParamError).toHaveBeenCalledWith("attempt_completion", "result") + expect(mockPushToolResult).toHaveBeenCalledWith("missing result param") + // The D5 branch must not run for a malformed call: nothing was collected. + expect(host.resolveBackgroundChild).not.toHaveBeenCalled() + expect(task.say).not.toHaveBeenCalledWith( + "completion_result", + expect.anything(), + expect.anything(), + expect.anything(), + ) + expect(task.flushTelemetryInstallment).not.toHaveBeenCalled() + expect(task.ask).not.toHaveBeenCalled() + }) + + it("leaves the interactive delegation branch untouched for a non-background child", async () => { + const provider = { + log: vi.fn(), + getTaskWithId: vi.fn().mockImplementation((id: string) => { + if (id === "delegate-child-1") { + return Promise.resolve({ historyItem: { id, status: "active" } }) + } + if (id === "parent-1") { + return Promise.resolve({ + historyItem: { id, status: "delegated", awaitingChildId: "delegate-child-1" }, + }) + } + throw new Error(`unexpected task id ${id}`) + }), + setPendingTaskAction: vi.fn().mockResolvedValue(undefined), + clearPendingTaskAction: vi.fn().mockResolvedValue(true), + emitDelegatedTaskCompleted: vi.fn(), + reopenParentFromDelegation: vi.fn().mockResolvedValue(true), + // Host methods exist on the provider but must NOT be consulted for a + // serially delegated child. + resolveBackgroundChild: vi.fn(), + failBackgroundChild: vi.fn(), + } + const task = makeBackgroundTask({ + taskId: "delegate-child-1", + isBackgroundSubtaskChild: false, + }) + Object.assign(task, { providerRef: { deref: () => provider } }) + mockAskFinishSubTaskApproval.mockResolvedValue(true) + + await attemptCompletionTool.handle(task as Task, makeBlock("delegated report"), makeCallbacks()) + + expect(provider.getTaskWithId).toHaveBeenCalled() + expect(mockAskFinishSubTaskApproval).toHaveBeenCalled() + expect(provider.reopenParentFromDelegation).toHaveBeenCalledWith({ + parentTaskId: "parent-1", + childTaskId: "delegate-child-1", + completionResultSummary: "delegated report", + pendingActionId: "call-background-completion", + }) + expect(provider.resolveBackgroundChild).not.toHaveBeenCalled() + expect(task.ask).not.toHaveBeenCalled() + expect(mockPushToolResult).toHaveBeenCalledWith("") + // Only the D5 branch may end the run loop; the delegation state machine + // hands control back to the parent and must not touch the latches. + expect(task.requestAbort).not.toHaveBeenCalled() + }) + + it("leaves the top-level completion ask untouched for a non-background task", async () => { + const task = makeBackgroundTask({ + taskId: "top-level-1", + parentTaskId: undefined, + isBackgroundSubtaskChild: false, + }) + + await attemptCompletionTool.handle(task as Task, makeBlock("top-level report"), makeCallbacks()) + + expect(task.ask).toHaveBeenCalledWith("completion_result", "", false) + expect(mockPushToolResult).not.toHaveBeenCalledWith("") + // The pre-existing top-level path flushes once here and again inside + // emitPublicTaskCompleted when the user accepts; the invariant is that + // the installment itself reports exactly once. + expect(task.emitFinalTokenUsageUpdate).toHaveBeenCalled() + expect(task.flushTelemetryInstallment).toHaveBeenCalledTimes(1) + expect(task.emit).toHaveBeenCalledWith( + RooCodeEventName.TaskCompleted, + "top-level-1", + expect.anything(), + expect.anything(), + ) + }) +}) diff --git a/src/core/tools/__tests__/attemptCompletionTool.backgroundRunLoop.spec.ts b/src/core/tools/__tests__/attemptCompletionTool.backgroundRunLoop.spec.ts new file mode 100644 index 0000000000..94c4fdb5e5 --- /dev/null +++ b/src/core/tools/__tests__/attemptCompletionTool.backgroundRunLoop.spec.ts @@ -0,0 +1,367 @@ +// pnpm --dir src exec vitest run core/tools/__tests__/attemptCompletionTool.backgroundRunLoop.spec.ts +// +// D5 run-loop termination (P1 permit-leak fix). The e2e replay exposed the +// defect: the D5 branch settled the host handle but never ended the child's +// own run loop, so the run promise never settled, the background scheduler +// permit leaked, and after DEFAULT_MAX_PARALLEL_SUBTASKS completions every +// later background child starved. These tests drive the REAL Task loop (real +// presentAssistantMessage, real AttemptCompletionTool) with the API request +// seam stubbed: the child must settle its run after exactly one +// attempt_completion turn, without issuing a second API request, and the late +// history writes must not regress the "completed" status. + +import * as os from "os" +import * as path from "path" + +import * as vscode from "vscode" +import { providerIdentifiers, type HistoryItem, type ProviderSettings } from "@roo-code/types" +import { TelemetryService } from "@roo-code/telemetry" + +import { Task } from "../../task/Task" +import { ClineProvider } from "../../webview/ClineProvider" +import { WebviewFocusTracker } from "../../webview/WebviewFocusTracker" +import { ContextProxy } from "../../config/ContextProxy" +import type { ApiStreamChunk } from "../../../api/transform/stream" + +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()) as Record + 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), + rm: vi.fn().mockResolvedValue(undefined), + stat: vi.fn().mockRejectedValue({ code: "ENOENT" }), + readdir: vi.fn().mockResolvedValue([]), + access: vi.fn().mockResolvedValue(undefined), + } + + return { + ...actual, + ...mockFunctions, + default: mockFunctions, + } +}) + +// p-wait-for stays REAL here: the regression hinges on the loop's own +// post-turn guard observing the latch the D5 branch sets, so the wait must +// actually poll for userMessageContentReady / abort / abandoned. + +vi.mock("vscode", () => { + const mockDisposable = { dispose: vi.fn() } + + return { + workspace: { + workspaceFolders: [{ uri: { fsPath: "/mock/workspace/path" }, name: "mock-workspace", index: 0 }], + getConfiguration: vi.fn(() => ({ get: vi.fn() })), + onDidChangeConfiguration: vi.fn(() => mockDisposable), + createFileSystemWatcher: vi.fn(() => ({ + onDidCreate: vi.fn(() => mockDisposable), + onDidDelete: vi.fn(() => mockDisposable), + onDidChange: vi.fn(() => mockDisposable), + dispose: vi.fn(), + })), + onDidSaveTextDocument: vi.fn(() => mockDisposable), + fs: { stat: vi.fn().mockResolvedValue({ type: 1 }) }, + }, + window: { + createTextEditorDecorationType: vi.fn().mockReturnValue({ dispose: vi.fn() }), + visibleTextEditors: [], + tabGroups: { + all: [], + close: vi.fn(), + onDidChangeTabs: vi.fn(() => mockDisposable), + }, + onDidChangeActiveTextEditor: vi.fn(() => mockDisposable), + showErrorMessage: vi.fn(), + showInformationMessage: vi.fn(), + showWarningMessage: vi.fn(), + }, + env: { uriScheme: "vscode", language: "en" }, + EventEmitter: vi.fn().mockImplementation(function () { + return { event: vi.fn(), fire: vi.fn() } + }), + Disposable: { from: vi.fn() }, + Uri: { file: vi.fn().mockReturnValue({ toString: () => "file://test" }), joinPath: vi.fn() }, + commands: { executeCommand: vi.fn().mockResolvedValue(undefined) }, + ExtensionMode: { Production: 1, Development: 2, Test: 3 }, + version: "1.85.0", + } +}) + +vi.mock("../../environment/getEnvironmentDetails", () => ({ + getEnvironmentDetails: vi.fn().mockResolvedValue(""), +})) + +vi.mock("../../mentions/processUserContentMentions", async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + expandUserMentions: vi.fn().mockImplementation(actual.expandUserMentions), + } +}) + +vi.mock("../../../i18n", () => ({ + t: (key: string) => key, +})) + +vi.mock("../../../utils/storage", () => ({ + getTaskDirectoryPath: vi + .fn() + .mockImplementation((globalStoragePath: string, taskId: string) => + Promise.resolve(`${globalStoragePath}/tasks/${taskId}`), + ), + getSettingsDirectoryPath: vi + .fn() + .mockImplementation((globalStoragePath: string) => Promise.resolve(`${globalStoragePath}/settings`)), + getGlobalStoragePath: vi.fn().mockResolvedValue("/test/storage/path"), + getStorageBasePath: vi.fn().mockImplementation((defaultPath: string) => defaultPath), +})) + +vi.mock("../../ignore/RooIgnoreController") + +// The provider's TaskHistoryStore is real here so status semantics stay +// production-shaped, but its writes go through safeWriteJson: with the fs +// mock's mkdir creating no directory, the real write rejects (ENOENT on the +// advisory lock) and the terminal settlement hangs waiting on it. Stub the +// write boundary only; the in-memory cache and status transitions remain real. +vi.mock("../../../utils/safeWriteJson", () => ({ + safeWriteJson: vi.fn().mockResolvedValue(undefined), +})) + +const apiConfig: ProviderSettings = { + apiProvider: providerIdentifiers.anthropic, + apiModelId: "claude-3-5-sonnet-20241022", + apiKey: "test-api-key", +} + +// One complete native attempt_completion call, the shape a finished +// background investigation produces. +function attemptCompletionStream(result: string): AsyncGenerator { + return (async function* (): AsyncGenerator { + yield { + type: "tool_call", + id: "call_bg_complete_1", + name: "attempt_completion", + arguments: JSON.stringify({ result }), + } + })() +} + +// Fails the test fast instead of hanging when the run loop never settles. +function withSettleDeadline(run: Promise, ms = 5000): Promise { + return Promise.race([ + run, + new Promise((_resolve, reject) => + setTimeout(() => reject(new Error(`child run() did not settle within ${ms}ms`)), ms), + ), + ]) +} + +describe("AttemptCompletionTool D5 run-loop termination (background child permit leak)", () => { + let mockProvider: ClineProvider + let mockOutputChannel: vscode.OutputChannel + let mockExtensionContext: vscode.ExtensionContext + let warnSpy: ReturnType + // Children built directly below never enter the provider's background + // registry (finishBackgroundChild early-returns for unknown ids), so + // provider disposal alone never releases their resources. + const createdTasks: Task[] = [] + + function createBackgroundChild(prompt: string): Task { + const task = new Task({ + provider: mockProvider, + apiConfiguration: apiConfig, + task: prompt, + startTask: false, + backgroundToolPolicy: { disabledTools: ["write_to_file"], experiments: { customTools: false } }, + // P1-2: the non-interactive background-child mode derives from this + // hosted flag (spawn path only), not from policy presence. + backgroundChildHosted: true, + }) + createdTasks.push(task) + return task + } + + function stubRequestSeam(task: Task, onExtraRequest: () => never) { + let apiCalls = 0 + const attemptApiRequest = vi.spyOn(task, "attemptApiRequest").mockImplementation(() => { + apiCalls += 1 + if (apiCalls > 1) { + // A background child that already reported must never start a + // second turn; the e2e replay looped exactly here. + onExtraRequest() + } + // The real attemptApiRequestWithActiveApi captures this before + // streaming; presentAssistantMessage refuses to run without it. + task["requestPolicySnapshot"] = { + disabledTools: ["write_to_file"], + experiments: { customTools: false }, + } + return attemptCompletionStream("child findings") + }) + return { attemptApiRequest, callCount: () => apiCalls } + } + + beforeEach(async () => { + if (!TelemetryService.hasInstance()) { + TelemetryService.createInstance([]) + } + warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {}) + + mockExtensionContext = { + globalState: { + get: vi.fn().mockReturnValue(undefined), + update: vi.fn().mockResolvedValue(undefined), + keys: vi.fn().mockReturnValue([]), + }, + globalStorageUri: { fsPath: path.join(os.tmpdir(), "test-storage") }, + workspaceState: { + get: vi.fn().mockReturnValue(undefined), + update: vi.fn().mockResolvedValue(undefined), + keys: vi.fn().mockReturnValue([]), + }, + secrets: { + get: vi.fn().mockResolvedValue(undefined), + store: vi.fn().mockResolvedValue(undefined), + delete: vi.fn().mockResolvedValue(undefined), + }, + extensionUri: { fsPath: "/mock/extension/path" }, + extension: { packageJSON: { version: "1.0.0" } }, + subscriptions: [], + } as unknown as vscode.ExtensionContext + + 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(), + } as unknown as vscode.OutputChannel + + mockProvider = new ClineProvider( + mockExtensionContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockExtensionContext), + new WebviewFocusTracker(), + ) + + 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) + + const state = await mockProvider.getState() + vi.spyOn(mockProvider, "getState").mockResolvedValue({ ...state, mcpEnabled: false }) + }) + + afterEach(async () => { + // Release every child this suite constructed, including after a failed + // assertion or a settle-deadline rejection: disposal sets the abort + // latch, so it also unwinds a run that never reached D5. dispose() is + // memoized, so children already released by the host are untouched. + // Teardown failures must not mask the assertion failure under test. + // + // `Task.dispose()` writes to the console, so the 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 createdTasks.splice(0)) { + await task.dispose().catch(() => {}) + } + await mockProvider.dispose().catch(() => {}) + } finally { + for (const spy of consoleQuiet) { + spy.mockRestore() + } + } + warnSpy.mockRestore() + }) + + it("settles the child's run after one attempt_completion turn without a second API request", async () => { + const task = createBackgroundChild("investigate the api surface") + vi.spyOn(task.diffViewProvider, "reset").mockResolvedValue(undefined) + const resolveBackgroundChild = vi.spyOn(mockProvider, "resolveBackgroundChild") + const failBackgroundChild = vi.spyOn(mockProvider, "failBackgroundChild") + const askSpy = vi.spyOn(task, "ask") + const requestAbort = vi.spyOn(task, "requestAbort") + const seam = stubRequestSeam(task, () => { + throw new Error("background child issued a second API request after D5") + }) + + await withSettleDeadline(task.run()) + + expect(seam.callCount()).toBe(1) + expect(resolveBackgroundChild).toHaveBeenCalledTimes(1) + expect(resolveBackgroundChild).toHaveBeenCalledWith(task.taskId, "child findings") + expect(failBackgroundChild).not.toHaveBeenCalled() + // The D5 branch ends the loop itself; no user ask ever happens. + expect(askSpy).not.toHaveBeenCalled() + expect(requestAbort).toHaveBeenCalledTimes(1) + expect(requestAbort).toHaveBeenCalledWith(true) + expect(task.abandoned).toBe(true) + expect(task.abort).toBe(true) + // requestAbort over requestAbandon: a reducer rejection or an + // abandoned-field divergence would surface as this warning. + const divergenceWarnings = warnSpy.mock.calls.filter((call: unknown[]) => + String(call[0]).includes("[RunState] divergence"), + ) + expect(divergenceWarnings).toEqual([]) + }) + + it("keeps the terminal history status completed after the loop ends", async () => { + const task = createBackgroundChild("investigate the debug logs") + vi.spyOn(task.diffViewProvider, "reset").mockResolvedValue(undefined) + vi.spyOn(mockProvider, "resolveBackgroundChild") + const seam = stubRequestSeam(task, () => { + throw new Error("background child issued a second API request after D5") + }) + + // The host persists "completed" when it collects the result; every late + // saveClineMessages() during loop teardown must preserve it. + const historyItem: HistoryItem = { + id: task.taskId, + number: 1, + ts: Date.now(), + task: "investigate the debug logs", + tokensIn: 0, + tokensOut: 0, + totalCost: 0, + status: "completed", + } + await mockProvider.taskHistoryStore.upsert(historyItem) + + await withSettleDeadline(task.run()) + + expect(seam.callCount()).toBe(1) + expect(mockProvider.taskHistoryStore.get(task.taskId)?.status).toBe("completed") + }) +}) diff --git a/src/core/tools/__tests__/parallelSubtasksExperimentGate.spec.ts b/src/core/tools/__tests__/parallelSubtasksExperimentGate.spec.ts new file mode 100644 index 0000000000..b616cde820 --- /dev/null +++ b/src/core/tools/__tests__/parallelSubtasksExperimentGate.spec.ts @@ -0,0 +1,101 @@ +// npx vitest run src/core/tools/__tests__/parallelSubtasksExperimentGate.spec.ts + +import type { ModeConfig } from "@roo-code/types" + +import { BACKGROUND_CHILD_DISABLED_TOOLS } from "../../background-subtasks/policy" +import { buildToolRequirements } from "../../prompts/tools/effective-tool-policy" + +import { isToolAllowedForMode, validateToolUse } from "../validateToolUse" + +const restrictiveMode: ModeConfig = { + slug: "restrictive", + name: "Restrictive", + roleDefinition: "No groups at all", + groups: [], +} + +describe("parallel_subtasks experiment gate", () => { + describe("flag off", () => { + it.each<[string, Record | undefined]>([ + ["omitted", undefined], + ["empty", {}], + ["explicitly off", { parallelSubtasks: false }], + ])("rejects the tool when experiments are %s", (_label, experiments) => { + expect(isToolAllowedForMode("parallel_subtasks", "code", [], undefined, undefined, experiments)).toBe(false) + }) + + it("rejects the tool in every built-in mode", () => { + for (const mode of ["architect", "code", "ask", "debug", "orchestrator"]) { + expect(isToolAllowedForMode("parallel_subtasks", mode, [])).toBe(false) + } + }) + + it("makes the execution-time validator throw the standard denial", () => { + expect(() => validateToolUse("parallel_subtasks", "code", [])).toThrow( + 'Tool "parallel_subtasks" is not allowed in code mode.', + ) + }) + }) + + describe("flag on", () => { + const on = { parallelSubtasks: true } + + it.each(["code", "debug", "architect"])("allows %s mode", (mode) => { + expect(isToolAllowedForMode("parallel_subtasks", mode, [], undefined, undefined, on)).toBe(true) + }) + + it("allows a custom mode with no groups (always-available exposure)", () => { + expect( + isToolAllowedForMode( + "parallel_subtasks", + restrictiveMode.slug, + [restrictiveMode], + undefined, + undefined, + on, + ), + ).toBe(true) + }) + + it("does not throw in the execution-time validator", () => { + expect(() => validateToolUse("parallel_subtasks", "code", [], undefined, undefined, on)).not.toThrow() + }) + }) + + describe("disabledTools precedence", () => { + const on = { parallelSubtasks: true } + + it("rejects the tool when requirements name it, even with the flag on", () => { + expect( + isToolAllowedForMode("parallel_subtasks", "code", [], { parallel_subtasks: false }, undefined, on), + ).toBe(false) + }) + + it("does not let a true requirement grant the tool while the flag is off", () => { + expect( + isToolAllowedForMode("parallel_subtasks", "code", [], { parallel_subtasks: true }, undefined, {}), + ).toBe(false) + }) + + it("rejects the tool through the real background-child block list", () => { + const requirements = buildToolRequirements([...BACKGROUND_CHILD_DISABLED_TOOLS]) + expect(isToolAllowedForMode("parallel_subtasks", "code", [], requirements, undefined, on)).toBe(false) + }) + + it("leaves every other always-available tool ungated", () => { + expect( + isToolAllowedForMode("new_task", restrictiveMode.slug, [restrictiveMode], undefined, undefined, {}), + ).toBe(true) + expect( + isToolAllowedForMode( + "attempt_completion", + restrictiveMode.slug, + [restrictiveMode], + undefined, + undefined, + {}, + ), + ).toBe(true) + }) + }) +}) diff --git a/src/core/tools/__tests__/parallelSubtasksTool.spec.ts b/src/core/tools/__tests__/parallelSubtasksTool.spec.ts new file mode 100644 index 0000000000..e8ee82c17e --- /dev/null +++ b/src/core/tools/__tests__/parallelSubtasksTool.spec.ts @@ -0,0 +1,1089 @@ +// pnpm --dir src exec vitest run core/tools/__tests__/parallelSubtasksTool.spec.ts + +import { RooCodeEventName, type ClineMessage, type ExtensionState } from "@roo-code/types" + +import type { AskApproval, HandleError, PushToolResult, ToolUse } from "../../../shared/tools" +import { Task } from "../../task/Task" +import { MessageQueueService } from "../../message-queue/MessageQueueService" +import { setAbortLatch } from "../../../test-utils/run-state" +import type { ClineProvider } from "../../webview/ClineProvider" +import type { BackgroundChildEntry, BackgroundChildHandle } from "../../background-subtasks/types" + +// Keep formatResponse deterministic so the payload assertions read the exact +// text the tool built; toolResult passes through unchanged. +vi.mock("../../prompts/responses", () => ({ + formatResponse: { + toolError: vi.fn((msg: string) => `Error: ${msg}`), + toolResult: vi.fn((msg: string) => msg), + toolDenied: vi.fn(() => "Denied"), + }, +})) + +// The report store has its own filesystem suite; here it is a controllable +// stand-in so report-write failures can be injected per test. +vi.mock("../../subtask-reports", () => ({ + writeSubtaskReport: vi.fn( + async (params: { + cwd: string + parentTaskId: string + childTaskId: string + label: string + markdown: string + }) => ({ + path: `/reports/${params.parentTaskId}/${params.label}-${params.childTaskId}.md`, + label: params.label, + taskId: params.childTaskId, + parentTaskId: params.parentTaskId, + }), + ), +})) + +import { parallelSubtasksTool } from "../ParallelSubtasksTool" +import parallelSubtasksToolDefinition from "../../prompts/tools/native-tools/parallel_subtasks" +import { MAX_REQUESTED_PARALLEL_SUBTASKS } from "../../assistant-message/NativeToolCallParser" +import { writeSubtaskReport } from "../../subtask-reports" + +const writeSubtaskReportMock = vi.mocked(writeSubtaskReport) + +interface TaskDouble { + taskId: string + cwd: string + abort: boolean + consecutiveMistakeCount: number + didToolFailInCurrentTurn: boolean + recordToolError: ReturnType void>> + sayAndCreateMissingParamError: ReturnType Promise>> + say: ReturnType< + typeof vi.fn<(type: string, text?: string, images?: string[], partial?: boolean) => Promise> + > + ask: ReturnType Promise>> + once: ReturnType void) => void>> + off: ReturnType void) => void>> + providerRef: { deref: () => unknown } + /** The message list the say double maintains, mirroring Task.say semantics. */ + clineMessages: ClineMessage[] + /** Identity-update notify the panel posts after the first row (Task private). */ + updateClineMessage: ReturnType Promise>> + /** Persistence the panel triggers when the finalized row lands (Task private). */ + saveClineMessages: ReturnType Promise>> +} + +interface ProviderDouble { + spawnBackgroundChildren: ReturnType> + abortBackgroundChildren: ReturnType> +} + +interface SettleableHandle extends BackgroundChildHandle { + settle: (entry: Partial & { status: BackgroundChildEntry["status"] }) => void +} + +function makeHandle(taskId: string, label: string, mode = "code"): SettleableHandle { + let resolveDone!: (entry: BackgroundChildEntry) => void + const done = new Promise((resolve) => { + resolveDone = resolve + }) + return { + taskId, + label, + mode, + done, + settle: (entry) => resolveDone({ taskId, label, mode, startedAt: 1, finishedAt: 2, ...entry }), + } +} + +/** The sole provider member `Task.ask` reaches for on this path. */ +interface AskProviderStub { + getState: () => Promise> +} + +/** + * A Task instance for exercising the real ask path: only the members `Task.ask` + * touches are installed. Bracket assignment keeps the private members typed; + * the provider stand-in satisfies the single `getState()` read this path makes. + */ +function createAskTask(provider: AskProviderStub = { getState: async () => ({}) }): Task { + const task = Object.create(Task.prototype, { + taskId: { value: "task-parallel-approval", enumerable: true }, + instanceId: { value: "instance-parallel-approval", enumerable: true }, + }) 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, while `Task.ask` only calls `deref()` and `getState()`. + task["providerRef"] = { deref: () => provider } as unknown as Task["providerRef"] + Object.defineProperty(task, "workspacePath", { value: "/workspace" }) + Object.defineProperty(task, "messageQueueService", { value: new MessageQueueService() }) + return task +} + +/** + * A Task instance for exercising the real say path: `Task.prototype.say` stays + * intact and only the members say() and the tool touch are installed or + * doubled. `addToClineMessages` is left for each test to install: it is the + * persistence boundary say() awaits after pushing its row, so gating it can + * suspend a post mid-say (a say double that resolves synchronously cannot + * reproduce that interleaving). + */ +function createPanelIdentityTask(provider: unknown): Task { + const task = Object.create(Task.prototype, { + taskId: { value: "task-panel-identity", enumerable: true }, + instanceId: { value: "instance-panel-identity", enumerable: true }, + }) as Task + setAbortLatch(task, false) + // Annotated so the empty literal is `ClineMessage[]` and not the `[]` tuple, + // which would make `messages[0]` a type error. + const clineMessages: ClineMessage[] = [] + task["clineMessages"] = clineMessages + task["lastMessageTs"] = undefined + task["postPartialMessageUpdate"] = vi.fn() + task["cancelPendingPartialMessageUpdate"] = vi.fn() + task["recordToolError"] = vi.fn() + task["sayAndCreateMissingParamError"] = vi.fn( + async (_tool: string, param: string) => `Missing required parameter: ${param}`, + ) + // Same WeakRef stand-in as createAskTask: the tool and say() only deref it. + task["providerRef"] = { deref: () => provider } as unknown as Task["providerRef"] + Object.defineProperty(task, "workspacePath", { value: "/workspace" }) + return task +} + +const PENDING = "pending" as const + +/** Resolves "pending" if `promise` has not settled within `ms`. */ +function pendingAfter(promise: Promise, ms = 250): Promise<"settled" | typeof PENDING> { + return Promise.race([ + promise.then(() => "settled" as const), + new Promise((resolve) => setTimeout(() => resolve(PENDING), ms)), + ]) +} + +describe("parallelSubtasksTool", () => { + let taskDouble: TaskDouble + let task: Task + let providerDouble: ProviderDouble + let askApproval: ReturnType> + let handleError: ReturnType> + let pushToolResult: ReturnType> + + const sayCalls = () => taskDouble.say.mock.calls + + // The panel is one message identity updated in place: tests read its state + // from the double's message list, not from the say call log (say only + // creates the row; identity updates go through updateClineMessage). + const panelMessages = () => + taskDouble.clineMessages.filter((message) => message.type === "say" && message.say === "tool") + + function createTaskDouble(): TaskDouble { + const double: TaskDouble = { + taskId: "parent-1", + cwd: "/workspace", + abort: false, + consecutiveMistakeCount: 0, + didToolFailInCurrentTurn: false, + recordToolError: vi.fn<(toolName: string) => void>(), + sayAndCreateMissingParamError: vi.fn( + async (_tool: string, param: string) => `Missing required parameter: ${param}`, + ), + say: vi.fn(async (type: string, text?: string, images?: string[], partial?: boolean) => { + if (double.abort) { + throw new Error(`[RooCode#say] task ${double.taskId} aborted`) + } + // Mirror Task.say's partial semantics so tests can interleave + // other message types between panel updates: a defined partial + // flag only updates the LAST message when that message is a + // partial say row of the same type; every other case appends. + // Returns the row touched, matching Task.say's contract. + const last = double.clineMessages.at(-1) + const isUpdatingPreviousPartial = + last !== undefined && last.partial === true && last.type === "say" && last.say === type + if (partial !== undefined && isUpdatingPreviousPartial) { + last.text = text + last.images = images + last.partial = partial + return last + } + const message: ClineMessage = { + ts: double.clineMessages.length + 1, + type: "say", + say: type as ClineMessage["say"], + text, + images, + ...(partial !== undefined ? { partial } : {}), + } + double.clineMessages.push(message) + return message + }), + ask: vi.fn(async () => ({ response: "yesButtonClicked", text: "", images: [] })), + once: vi.fn(), + off: vi.fn(), + providerRef: { deref: () => providerDouble }, + clineMessages: [], + updateClineMessage: vi.fn(async () => {}), + saveClineMessages: vi.fn(async () => true), + } + return double + } + + function makeCallbacks() { + return { askApproval, handleError, pushToolResult, toolCallId: "call-1" } + } + + function makeBlock(tasks: unknown): ToolUse<"parallel_subtasks"> { + return { + type: "tool_use", + name: "parallel_subtasks", + params: {}, + nativeArgs: { tasks } as ToolUse<"parallel_subtasks">["nativeArgs"], + partial: false, + } + } + + function spawnedHandles(...handles: SettleableHandle[]) { + providerDouble.spawnBackgroundChildren.mockResolvedValue({ children: handles, started: handles.length > 0 }) + } + + beforeEach(() => { + providerDouble = { + spawnBackgroundChildren: vi.fn(async () => ({ + children: [], + started: false, + })), + abortBackgroundChildren: vi.fn(async () => undefined), + } + taskDouble = createTaskDouble() + // The double stands in for a Task on the paths under test only. + task = taskDouble as unknown as Task + askApproval = vi.fn(async () => true) + handleError = vi.fn(async () => undefined) + pushToolResult = vi.fn() + writeSubtaskReportMock.mockReset() + writeSubtaskReportMock.mockImplementation(async (params) => ({ + path: `/reports/${params.parentTaskId}/${params.label}-${params.childTaskId}.md`, + label: params.label, + taskId: params.childTaskId, + parentTaskId: params.parentTaskId, + })) + }) + + describe("validation", () => { + it.each([ + ["an empty tasks array", { tasks: [] }], + ["a missing tasks parameter", { tasks: undefined }], + ])("takes the mistake path for %s without spawning or asking", async (_case, nativeArgs) => { + const block = { + type: "tool_use", + name: "parallel_subtasks", + params: {}, + nativeArgs, + partial: false, + } as unknown as ToolUse<"parallel_subtasks"> + + await parallelSubtasksTool.handle(task, block, makeCallbacks()) + + expect(taskDouble.consecutiveMistakeCount).toBe(1) + expect(taskDouble.recordToolError).toHaveBeenCalledWith("parallel_subtasks") + expect(taskDouble.didToolFailInCurrentTurn).toBe(true) + expect(pushToolResult).toHaveBeenCalledWith("Missing required parameter: tasks") + expect(providerDouble.spawnBackgroundChildren).not.toHaveBeenCalled() + expect(askApproval).not.toHaveBeenCalled() + expect(taskDouble.say).not.toHaveBeenCalled() + }) + + it("rejects a list above the hard ceiling before asking, spawning, or posting rows", async () => { + const tasks = Array.from({ length: MAX_REQUESTED_PARALLEL_SUBTASKS + 1 }, (_value, index) => ({ + label: `investigation-${index}`, + mode: "code", + message: `Investigation ${index}.`, + })) + + await parallelSubtasksTool.handle(task, makeBlock(tasks), makeCallbacks()) + + expect(taskDouble.consecutiveMistakeCount).toBe(1) + expect(taskDouble.recordToolError).toHaveBeenCalledWith("parallel_subtasks") + expect(taskDouble.didToolFailInCurrentTurn).toBe(true) + expect(pushToolResult).toHaveBeenCalledTimes(1) + const text = pushToolResult.mock.calls[0][0] as string + expect(text).toContain(`at most ${MAX_REQUESTED_PARALLEL_SUBTASKS} task entries per call`) + expect(text).toContain("at most 6 investigations") + expect(providerDouble.spawnBackgroundChildren).not.toHaveBeenCalled() + expect(askApproval).not.toHaveBeenCalled() + expect(taskDouble.say).not.toHaveBeenCalled() + }) + }) + + describe("request ceiling", () => { + it("accepts a list at the ceiling and bounds label de-duplication to it", async () => { + const tasks = Array.from({ length: MAX_REQUESTED_PARALLEL_SUBTASKS }, () => ({ + label: "dup", + mode: "code", + message: "same", + })) + + await parallelSubtasksTool.handle(task, makeBlock(tasks), makeCallbacks()) + + expect(providerDouble.spawnBackgroundChildren).toHaveBeenCalledOnce() + const specs = providerDouble.spawnBackgroundChildren.mock.calls[0][1] + expect(specs).toHaveLength(MAX_REQUESTED_PARALLEL_SUBTASKS) + expect(specs[0].label).toBe("dup") + expect(specs[1].label).toBe("dup-2") + expect(specs.at(-1)?.label).toBe(`dup-${MAX_REQUESTED_PARALLEL_SUBTASKS}`) + }) + + it("keeps the shipped description consistent with the enforced ceiling", () => { + const description = parallelSubtasksToolDefinition.function.description ?? "" + + expect(description).toContain(`more than ${MAX_REQUESTED_PARALLEL_SUBTASKS} tasks is rejected`) + expect(description).toContain("At most 6 children per call") + }) + }) + + describe("spec building", () => { + it("defaults absent labels, de-duplicates collisions, and preserves order", async () => { + const handles = [ + makeHandle("c1", "child-1"), + makeHandle("c2", "child-2"), + makeHandle("c3", "dup"), + makeHandle("c4", "dup-2"), + ] + spawnedHandles(...handles) + handles.forEach((handle) => handle.settle({ status: "completed", result: "ok" })) + + const block = makeBlock([ + { mode: "code", message: "first" }, + { label: "", mode: "debug", message: "second" }, + { label: "dup", mode: "code", message: "third" }, + { label: "dup", mode: "code", message: "fourth" }, + ]) + await parallelSubtasksTool.handle(task, block, makeCallbacks()) + + expect(providerDouble.spawnBackgroundChildren).toHaveBeenCalledOnce() + const specs = providerDouble.spawnBackgroundChildren.mock.calls[0][1] + expect(specs.map((spec) => spec.label)).toEqual(["child-1", "child-2", "dup", "dup-2"]) + expect(specs.map((spec) => spec.mode)).toEqual(["code", "debug", "code", "code"]) + expect(specs.map((spec) => spec.message)).toEqual(["first", "second", "third", "fourth"]) + }) + }) + + describe("approval", () => { + it("asks exactly once, naming every spec", async () => { + const handles = [makeHandle("c1", "api"), makeHandle("c2", "tests")] + spawnedHandles(...handles) + handles.forEach((handle) => handle.settle({ status: "completed", result: "ok" })) + + const block = makeBlock([ + { label: "api", mode: "code", message: "Map the API" }, + { label: "tests", mode: "debug", message: "Check coverage" }, + ]) + await parallelSubtasksTool.handle(task, block, makeCallbacks()) + + expect(askApproval).toHaveBeenCalledTimes(1) + expect(askApproval.mock.calls[0][0]).toBe("tool") + // `forceApproval` marks the ask protected so a queued follow-up cannot + // stand in for the click; checkAutoApproval still handles tool asks. + expect(askApproval.mock.calls[0][2]).toBeUndefined() + expect(askApproval.mock.calls[0][3]).toBe(true) + const payload = JSON.parse(askApproval.mock.calls[0][1] ?? "{}") as { + tool: string + tasks: Array<{ label: string; mode: string; message: string }> + } + expect(payload.tool).toBe("parallelSubtasks") + expect(payload.tasks).toEqual([ + { label: "api", mode: "code", message: "Map the API" }, + { label: "tests", mode: "debug", message: "Check coverage" }, + ]) + }) + + it("keeps the ask blocked when a follow-up message is queued", async () => { + const askTask = createAskTask() + askTask.messageQueueService.addMessage("Double-check the API first") + askApproval.mockImplementation(async (type, text, _progress, isProtected) => { + const result = await askTask.ask(type, text, false, undefined, isProtected) + return result.response === "yesButtonClicked" + }) + + const toolRun = parallelSubtasksTool.handle( + task, + makeBlock([{ label: "api", mode: "code", message: "Map the API" }]), + makeCallbacks(), + ) + + // The queued message must not satisfy the protected fan-out approval. + expect(await pendingAfter(toolRun)).toBe(PENDING) + expect(providerDouble.spawnBackgroundChildren).not.toHaveBeenCalled() + expect(askTask.messageQueueService.isEmpty()).toBe(false) + + askTask.approveAsk() + await toolRun + + expect(providerDouble.spawnBackgroundChildren).toHaveBeenCalledOnce() + // The queued text was not consumed as approval feedback. + expect(askTask.messageQueueService.claimNextMessage()?.text).toBe("Double-check the API first") + }) + + it("starts the fan-out without a click when alwaysAllowSubtasks is on", async () => { + const askTask = createAskTask({ + getState: async () => ({ autoApprovalEnabled: true, alwaysAllowSubtasks: true }), + }) + askApproval.mockImplementation(async (type, text, _progress, isProtected) => { + const result = await askTask.ask(type, text, false, undefined, isProtected) + return result.response === "yesButtonClicked" + }) + + await parallelSubtasksTool.handle( + task, + makeBlock([{ label: "api", mode: "code", message: "Map the API" }]), + makeCallbacks(), + ) + + expect(askApproval).toHaveBeenCalledWith("tool", expect.any(String), undefined, true) + expect(providerDouble.spawnBackgroundChildren).toHaveBeenCalledOnce() + expect(askTask.messageQueueService.isEmpty()).toBe(true) + }) + + it("returns without spawning when the user rejects", async () => { + askApproval.mockResolvedValue(false) + + const block = makeBlock([{ label: "api", mode: "code", message: "Map the API" }]) + await parallelSubtasksTool.handle(task, block, makeCallbacks()) + + expect(providerDouble.spawnBackgroundChildren).not.toHaveBeenCalled() + expect(taskDouble.say).not.toHaveBeenCalled() + expect(pushToolResult).not.toHaveBeenCalled() + expect(handleError).not.toHaveBeenCalled() + }) + }) + + describe("running transitions (F-09)", () => { + const flushTool = async (ticks = 8): Promise => { + for (let index = 0; index < ticks; index++) { + await new Promise((resolve) => setTimeout(resolve, 0)) + } + } + + const parseLastRow = (): { subtasks: Array<{ label: string; status: string; startedAt?: number }> } => + JSON.parse(panelMessages().at(-1)?.text ?? "{}") as { + subtasks: Array<{ label: string; status: string; startedAt?: number }> + } + + it("applies a start that beats the first row and a start that arrives later", async () => { + const first = makeHandle("c1", "one") + const second = makeHandle("c2", "two") + let notify: ((entry: BackgroundChildEntry) => void) | undefined + providerDouble.spawnBackgroundChildren.mockImplementation(async (_parent, _specs, options) => { + notify = options?.onChildStarted + // A permit can be acquired while the host is still inside spawn. + notify?.({ taskId: "c1", label: "one", mode: "code", status: "running", startedAt: 11 }) + return { children: [first, second], started: true } + }) + + const executePromise = parallelSubtasksTool.handle( + task, + makeBlock([ + { label: "one", mode: "code", message: "m1" }, + { label: "two", mode: "code", message: "m2" }, + ]), + makeCallbacks(), + ) + await flushTool() + + // The buffered start is already running in the initial post. + expect(parseLastRow().subtasks).toMatchObject([ + { label: "one", status: "running", startedAt: 11 }, + { label: "two", status: "queued" }, + ]) + + // A start reported after the rows exist updates the row immediately. + notify?.({ taskId: "c2", label: "two", mode: "code", status: "running", startedAt: 22 }) + await flushTool() + expect(parseLastRow().subtasks[1]).toMatchObject({ status: "running", startedAt: 22 }) + + first.settle({ status: "completed", result: "# One" }) + second.settle({ status: "failed", error: "child exploded" }) + await executePromise + + const final = parseLastRow().subtasks + expect(final[0]).toMatchObject({ status: "completed" }) + expect(final[1]).toMatchObject({ status: "failed" }) + }) + }) + + describe("progress rows", () => { + /** Polls the panel message until `predicate` holds or the deadline expires. */ + async function waitForLastRow( + predicate: (row: { subtasks: Array<{ label: string; status: string }> }) => boolean, + ms = 1000, + ): Promise { + const deadline = Date.now() + ms + for (;;) { + const last = panelMessages().at(-1) + if (last) { + const row = JSON.parse(last.text ?? "{}") as { + subtasks: Array<{ label: string; status: string }> + } + if (predicate(row)) { + return + } + } + if (Date.now() >= deadline) { + throw new Error("timed out waiting for a progress row update") + } + await new Promise((resolve) => setTimeout(resolve, 5)) + } + } + + it("posts one initial partial row, one update per completion, and a final non-partial row", async () => { + const handles = [makeHandle("c1", "one"), makeHandle("c2", "two"), makeHandle("c3", "three")] + spawnedHandles(...handles) + + const executePromise = parallelSubtasksTool.handle( + task, + makeBlock([ + { label: "one", mode: "code", message: "m1" }, + { label: "two", mode: "code", message: "m2" }, + { label: "three", mode: "code", message: "m3" }, + ]), + makeCallbacks(), + ) + + // Settle two children out of order and leave "one" pending. Each + // completion must post its own partial row while the tool is still + // awaiting the pending child; a tool that batch-posted every update + // after the join would leave the last row untouched here. + handles[2].settle({ status: "completed", result: "# Three\nfindings" }) + handles[1].settle({ status: "failed", error: "child exploded" }) + await waitForLastRow((row) => { + const byLabel = new Map(row.subtasks.map((subtask) => [subtask.label, subtask.status])) + return ( + byLabel.get("three") === "completed" && + byLabel.get("two") === "failed" && + byLabel.get("one") === "queued" + ) + }) + + // The join must still be waiting on the pending child. + expect(await pendingAfter(executePromise)).toBe(PENDING) + + handles[0].settle({ status: "completed", result: "# One\nfindings" }) + await executePromise + + // The panel is created once through say(partial:true) and updated in + // place by message identity afterwards: one say call, one panel + // message, one identity update per completion plus the finalize, and + // one persistence write when the row finalizes. + expect(taskDouble.say).toHaveBeenCalledTimes(1) + expect(sayCalls()[0]?.[3]).toBe(true) + const panels = panelMessages() + expect(panels).toHaveLength(1) + expect(taskDouble.updateClineMessage).toHaveBeenCalledTimes(4) + expect( + taskDouble.updateClineMessage.mock.calls.every((call) => call[0] === panels[0]), + "every update must target the same panel message identity", + ).toBe(true) + expect(taskDouble.saveClineMessages).toHaveBeenCalledTimes(1) + expect(panels[0]?.partial).toBe(false) + + const initial = JSON.parse(sayCalls()[0]?.[1] ?? "{}") as { + tool: string + subtasks: Array<{ status: string }> + } + expect(initial.tool).toBe("parallelSubtasks") + expect(initial.subtasks).toHaveLength(3) + expect(initial.subtasks.every((subtask) => subtask.status === "queued")).toBe(true) + + const final = JSON.parse(panels[0]?.text ?? "{}") as { + subtasks: Array<{ + label: string + status: string + reportPath?: string + summary?: string + error?: string + }> + } + const byLabel = new Map(final.subtasks.map((subtask) => [subtask.label, subtask])) + expect(byLabel.get("one")).toMatchObject({ + status: "completed", + reportPath: "/reports/parent-1/one-c1.md", + summary: "# One", + }) + expect(byLabel.get("three")).toMatchObject({ + status: "completed", + reportPath: "/reports/parent-1/three-c3.md", + summary: "# Three", + }) + expect(byLabel.get("two")).toMatchObject({ status: "failed", error: "child exploded" }) + }) + + it("keeps one finalized panel when a reasoning chunk interleaves between child updates", async () => { + const handles = [makeHandle("c1", "one"), makeHandle("c2", "two")] + spawnedHandles(...handles) + + const executePromise = parallelSubtasksTool.handle( + task, + makeBlock([ + { label: "one", mode: "code", message: "m1" }, + { label: "two", mode: "code", message: "m2" }, + ]), + makeCallbacks(), + ) + + // The initial partial panel exists before any child settles. + await waitForLastRow((row) => row.subtasks.length === 2) + expect(panelMessages()).toHaveLength(1) + + // The first completion updates the panel in place. + handles[1].settle({ status: "completed", result: "# Two" }) + await waitForLastRow((row) => + row.subtasks.every((subtask) => subtask.label !== "two" || subtask.status === "completed"), + ) + + // A reasoning chunk lands between updates. Task.say appends it (the + // last message is a partial tool row of a different type); with + // say-based panel updates the next row post would create a SECOND + // panel row instead of updating the first, stranding a stale panel. + await taskDouble.say("reasoning", "interleaved reasoning", undefined, true) + expect(taskDouble.clineMessages.at(-1)?.say).toBe("reasoning") + + handles[0].settle({ status: "completed", result: "# One" }) + await executePromise + + // Exactly one panel message exists, it is the finalized one, and the + // interleaved reasoning row survived as its own message. + const panels = panelMessages() + expect(panels).toHaveLength(1) + expect(panels[0]?.partial).toBe(false) + const byLabel = new Map( + ( + JSON.parse(panels[0]?.text ?? "{}") as { subtasks: Array<{ label: string; status: string }> } + ).subtasks.map((subtask) => [subtask.label, subtask.status]), + ) + expect(byLabel.get("one")).toBe("completed") + expect(byLabel.get("two")).toBe("completed") + expect(taskDouble.clineMessages.filter((message) => message.say === "reasoning")).toHaveLength(1) + expect(taskDouble.saveClineMessages).toHaveBeenCalledTimes(1) + }) + }) + + describe("panel identity under the real Task.say (F-1 regression)", () => { + it("finalizes the original panel row when a reasoning row lands while the first post is pending", async () => { + const task = createPanelIdentityTask(providerDouble) + let openGate = () => {} + const gate = new Promise((resolve) => { + openGate = resolve + }) + // Gate the persistence boundary the real say() awaits after pushing + // its row: the panel row is in clineMessages while its say() is still + // suspended, exactly the window the tail-position capture got wrong. + task["addToClineMessages"] = vi.fn(async (message: ClineMessage) => { + task["clineMessages"].push(message) + await gate + }) + const saveClineMessages = vi.fn(async () => true) + task["saveClineMessages"] = saveClineMessages + const updateClineMessage = vi.fn(async (_message: ClineMessage) => {}) + task["updateClineMessage"] = updateClineMessage + + const handles = [makeHandle("c1", "one"), makeHandle("c2", "two")] + spawnedHandles(...handles) + + const executePromise = parallelSubtasksTool.handle( + task, + makeBlock([ + { label: "one", mode: "code", message: "m1" }, + { label: "two", mode: "code", message: "m2" }, + ]), + makeCallbacks(), + ) + + // Wait for the panel row to be pushed while its say() is still gated. + const deadline = Date.now() + 1000 + while (task["clineMessages"].length === 0) { + if (Date.now() > deadline) { + throw new Error("timed out waiting for the panel row push") + } + await new Promise((resolve) => setTimeout(resolve, 0)) + } + + // A reasoning chunk lands mid-post: say() appends its own row at the + // tail before the panel's say() has returned, so a tail-position + // capture would hand the panel updates to the reasoning row. + const reasoningSay = task.say("reasoning", "interleaved reasoning", undefined, true) + expect(task["clineMessages"].at(-1)?.say).toBe("reasoning") + + openGate() + await reasoningSay + handles[0].settle({ status: "completed", result: "# One" }) + handles[1].settle({ status: "completed", result: "# Two" }) + await executePromise + + // The original panel row is the one that finalizes... + const panels = task["clineMessages"].filter((message) => message.type === "say" && message.say === "tool") + expect(panels).toHaveLength(1) + expect(panels[0]?.partial).toBe(false) + const finalPanel = JSON.parse(panels[0]?.text ?? "{}") as { + subtasks: Array<{ label: string; status: string }> + } + expect(finalPanel.subtasks.map((row) => row.status)).toEqual(["completed", "completed"]) + // ...every identity update targeted that same row... + expect(updateClineMessage.mock.calls.length).toBeGreaterThan(0) + expect(updateClineMessage.mock.calls.every((call) => call[0] === panels[0])).toBe(true) + // ...the reasoning row kept its own text and partial state... + const reasoning = task["clineMessages"].filter((message) => message.say === "reasoning") + expect(reasoning).toHaveLength(1) + expect(reasoning[0]?.text).toBe("interleaved reasoning") + expect(reasoning[0]?.partial).toBe(true) + // ...and the finalized row was persisted exactly once. + expect(saveClineMessages).toHaveBeenCalledTimes(1) + }) + }) + + describe("panel persistence (F-2)", () => { + it("retries the final message save once and still reports success", async () => { + taskDouble.saveClineMessages.mockResolvedValueOnce(false).mockResolvedValue(true) + const handles = [makeHandle("c1", "one")] + spawnedHandles(...handles) + handles[0].settle({ status: "completed", result: "# One" }) + + await parallelSubtasksTool.handle( + task, + makeBlock([{ label: "one", mode: "code", message: "m1" }]), + makeCallbacks(), + ) + + expect(taskDouble.saveClineMessages).toHaveBeenCalledTimes(2) + expect(pushToolResult).toHaveBeenCalledTimes(1) + expect(handleError).not.toHaveBeenCalled() + expect(panelMessages()[0]?.partial).toBe(false) + }) + + it("surfaces a persistence error when the final save keeps failing", async () => { + taskDouble.saveClineMessages.mockResolvedValue(false) + const handles = [makeHandle("c1", "one")] + spawnedHandles(...handles) + handles[0].settle({ status: "completed", result: "# One" }) + + await parallelSubtasksTool.handle( + task, + makeBlock([{ label: "one", mode: "code", message: "m1" }]), + makeCallbacks(), + ) + + // One retry, then the persistence failure is surfaced instead of a + // success payload whose panel the restored chat would render without + // report links. + expect(taskDouble.saveClineMessages).toHaveBeenCalledTimes(2) + expect(pushToolResult).not.toHaveBeenCalled() + expect(handleError).toHaveBeenCalledTimes(1) + expect(handleError.mock.calls[0]?.[1]).toBeInstanceOf(Error) + }) + }) + + describe("join and result injection", () => { + it("pushes one payload naming every child, its status, and the report path", async () => { + const handles = [makeHandle("c1", "api"), makeHandle("c2", "tests"), makeHandle("c3", "docs")] + spawnedHandles(...handles) + handles[0].settle({ status: "completed", result: "# API\nfindings" }) + handles[1].settle({ status: "failed", error: "out of tokens" }) + handles[2].settle({ status: "aborted", error: "cancelled" }) + + await parallelSubtasksTool.handle( + task, + makeBlock([ + { label: "api", mode: "code", message: "m1" }, + { label: "tests", mode: "debug", message: "m2" }, + { label: "docs", mode: "code", message: "m3" }, + ]), + makeCallbacks(), + ) + + expect(pushToolResult).toHaveBeenCalledTimes(1) + const payload = pushToolResult.mock.calls[0][0] + expect(typeof payload).toBe("string") + const text = payload as string + expect(text).toContain("parallel_subtasks finished: 1/3 children completed.") + expect(text).toContain("- api: completed. Report: /reports/parent-1/api-c1.md") + expect(text).toContain("Summary: # API") + expect(text).toContain("- tests: failed (out of tokens)") + expect(text).toContain("- docs: aborted (cancelled)") + expect(text).toContain("read_file") + }) + + it("includes the one-line report summary in the payload for the parent model", async () => { + const handles = [makeHandle("c1", "api")] + spawnedHandles(...handles) + handles[0].settle({ status: "completed", result: "# Findings\n- first\n- second" }) + + await parallelSubtasksTool.handle( + task, + makeBlock([{ label: "api", mode: "code", message: "m1" }]), + makeCallbacks(), + ) + + const text = pushToolResult.mock.calls[0][0] as string + expect(text).toContain("- api: completed. Report: /reports/parent-1/api-c1.md. Summary: # Findings") + // Only the first line ships to the parent; the full report stays on disk. + expect(text).not.toContain("- first") + }) + + it("does not count a failed admitted spec as a start in the dropped row", async () => { + // Seven specs pass the tool ceiling; the host cap considers six. One + // of the six has an unknown mode, so the host returns a handle that + // is already settled as failed instead of a live child. + const handles = Array.from({ length: 6 }, (_value, index) => + makeHandle(`c${index}`, `investigation-${index}`), + ) + handles[1].settle({ status: "failed", error: "Unknown mode: bogus" }) + spawnedHandles(...handles) + handles.forEach((handle, index) => { + if (index !== 1) { + handle.settle({ status: "completed", result: `# ${handle.label}` }) + } + }) + + const tasks = Array.from({ length: 7 }, (_value, index) => ({ + label: `investigation-${index}`, + mode: "code", + message: `Investigation ${index}.`, + })) + await parallelSubtasksTool.handle(task, makeBlock(tasks), makeCallbacks()) + + const text = pushToolResult.mock.calls[0][0] as string + expect(text).toContain("Dropped: the request exceeded the per-call limit (6 of 7 specs considered)") + expect(text).not.toContain("6 of 7 started") + }) + + it("keeps the documented drop semantics for a batch above the fan-out but under the ceiling", async () => { + const handles = Array.from({ length: 6 }, (_value, index) => + makeHandle(`c${index}`, `investigation-${index}`), + ) + spawnedHandles(...handles) + handles.forEach((handle) => handle.settle({ status: "completed", result: `# ${handle.label}` })) + + const tasks = Array.from({ length: 7 }, (_value, index) => ({ + label: `investigation-${index}`, + mode: "code", + message: `Investigation ${index}.`, + })) + await parallelSubtasksTool.handle(task, makeBlock(tasks), makeCallbacks()) + + const specs = providerDouble.spawnBackgroundChildren.mock.calls[0][1] + expect(specs).toHaveLength(7) + + const final = JSON.parse(panelMessages().at(-1)?.text ?? "{}") as { + subtasks: Array<{ taskId: string; status: string; error?: string }> + } + expect(final.subtasks).toHaveLength(7) + expect(final.subtasks.at(-1)).toMatchObject({ + taskId: "dropped-0", + status: "failed", + error: "Dropped: the request exceeded the per-call limit (6 of 7 specs considered)", + }) + + const text = pushToolResult.mock.calls[0][0] as string + expect(text).toContain("parallel_subtasks finished: 6/7 children completed.") + expect(text).toContain("Dropped: the request exceeded the per-call limit (6 of 7 specs considered)") + }) + }) + + describe("report saving", () => { + it("writes one report per completed child with the host-side coordinates", async () => { + const handles = [makeHandle("c1", "api"), makeHandle("c2", "tests")] + spawnedHandles(...handles) + handles[0].settle({ status: "completed", result: "# API\nfindings" }) + handles[1].settle({ status: "failed", error: "nope" }) + + await parallelSubtasksTool.handle( + task, + makeBlock([ + { label: "api", mode: "code", message: "m1" }, + { label: "tests", mode: "debug", message: "m2" }, + ]), + makeCallbacks(), + ) + + expect(writeSubtaskReportMock).toHaveBeenCalledTimes(1) + expect(writeSubtaskReportMock).toHaveBeenCalledWith({ + cwd: "/workspace", + parentTaskId: "parent-1", + childTaskId: "c1", + label: "api", + markdown: "# API\nfindings", + }) + }) + + it("marks only the affected child failed when a report write fails", async () => { + writeSubtaskReportMock.mockRejectedValueOnce(new Error("disk full")) + const handles = [makeHandle("c1", "api"), makeHandle("c2", "tests")] + spawnedHandles(...handles) + handles[0].settle({ status: "completed", result: "# API" }) + handles[1].settle({ status: "completed", result: "# Tests" }) + + await parallelSubtasksTool.handle( + task, + makeBlock([ + { label: "api", mode: "code", message: "m1" }, + { label: "tests", mode: "code", message: "m2" }, + ]), + makeCallbacks(), + ) + + const final = JSON.parse(panelMessages().at(-1)?.text ?? "{}") as { + subtasks: Array<{ label: string; status: string; error?: string; reportPath?: string }> + } + const byLabel = new Map(final.subtasks.map((subtask) => [subtask.label, subtask])) + expect(byLabel.get("api")).toMatchObject({ status: "failed", error: "Report write failed: disk full" }) + expect(byLabel.get("tests")).toMatchObject({ + status: "completed", + reportPath: "/reports/parent-1/tests-c2.md", + }) + + expect(pushToolResult).toHaveBeenCalledTimes(1) + const text = pushToolResult.mock.calls[0][0] as string + expect(text).toContain("- api: failed (Report write failed: disk full)") + expect(text).toContain("- tests: completed. Report: /reports/parent-1/tests-c2.md") + }) + }) + + describe("abort cascade", () => { + it("aborts the children when the parent is aborted and never pushes a success result", async () => { + const handles = [makeHandle("c1", "one"), makeHandle("c2", "two")] + spawnedHandles(...handles) + + const executePromise = parallelSubtasksTool.handle( + task, + makeBlock([ + { label: "one", mode: "code", message: "m1" }, + { label: "two", mode: "code", message: "m2" }, + ]), + makeCallbacks(), + ) + + // Let the spawn and the initial row land, then cancel the parent. + await Promise.resolve() + await Promise.resolve() + const listener = taskDouble.once.mock.calls.find((call) => call[0] === RooCodeEventName.TaskAborted)?.[1] + expect(listener).toBeTypeOf("function") + taskDouble.abort = true + listener?.() + + expect(providerDouble.abortBackgroundChildren).toHaveBeenCalledWith("parent-1") + + // The cascade settles each handle; the join still resolves. + handles[0].settle({ status: "aborted", error: "Parent task was cancelled" }) + handles[1].settle({ status: "aborted", error: "Parent task was cancelled" }) + await executePromise + + expect(pushToolResult).not.toHaveBeenCalled() + expect(handleError).toHaveBeenCalledTimes(1) + expect(taskDouble.off).toHaveBeenCalledWith(RooCodeEventName.TaskAborted, listener) + }) + }) + + describe("tool failure", () => { + it("aborts still-pending children when the tool fails after spawn", async () => { + const handles = [makeHandle("c1", "one"), makeHandle("c2", "two")] + // Keep the parent alive through admission; the failure must come from + // the first row post after the host already admitted live children. + providerDouble.spawnBackgroundChildren.mockImplementation(async () => { + taskDouble.abort = true + return { children: handles, started: true } + }) + // The abort cascade is what settles the children the tool is awaiting. + providerDouble.abortBackgroundChildren.mockImplementation(async () => { + handles.forEach((handle) => handle.settle({ status: "aborted", error: "Parent task was cancelled" })) + }) + const terminal = handles.map((handle) => handle.done) + + await parallelSubtasksTool.handle( + task, + makeBlock([ + { label: "one", mode: "code", message: "m1" }, + { label: "two", mode: "code", message: "m2" }, + ]), + makeCallbacks(), + ) + + expect(providerDouble.abortBackgroundChildren).toHaveBeenCalledWith("parent-1") + expect(handleError).toHaveBeenCalledTimes(1) + expect(pushToolResult).not.toHaveBeenCalled() + await expect(Promise.all(terminal)).resolves.toEqual([ + expect.objectContaining({ taskId: "c1", status: "aborted", error: "Parent task was cancelled" }), + expect.objectContaining({ taskId: "c2", status: "aborted", error: "Parent task was cancelled" }), + ]) + }) + }) + + describe("handlePartial", () => { + it.each([ + ["a JSON string", JSON.stringify([{ label: "api", mode: "code", message: "Map it" }])], + ["an already-parsed array", [{ label: "api", mode: "code", message: "Map it" }]], + ])("posts a partial ask row for %s", async (_case, tasks) => { + const block = { + type: "tool_use", + name: "parallel_subtasks", + params: { tasks: typeof tasks === "string" ? tasks : undefined }, + nativeArgs: typeof tasks === "string" ? undefined : { tasks }, + partial: true, + } as unknown as ToolUse<"parallel_subtasks"> + + await parallelSubtasksTool.handle(task, block, makeCallbacks()) + + expect(taskDouble.ask).toHaveBeenCalledWith( + "tool", + JSON.stringify({ + tool: "parallelSubtasks", + tasks: [{ label: "api", mode: "code", message: "Map it" }], + }), + true, + ) + }) + + it("bounds the streamed preview to the ceiling plus one", async () => { + const tasks = Array.from({ length: MAX_REQUESTED_PARALLEL_SUBTASKS + 100 }, (_value, index) => ({ + label: `investigation-${index}`, + mode: "code", + message: `Investigation ${index}.`, + })) + const block = { + type: "tool_use", + name: "parallel_subtasks", + params: { tasks: JSON.stringify(tasks) }, + nativeArgs: undefined, + partial: true, + } as unknown as ToolUse<"parallel_subtasks"> + + await parallelSubtasksTool.handle(task, block, makeCallbacks()) + + const payload = JSON.parse(taskDouble.ask.mock.calls[0][1] ?? "{}") as { tasks: unknown[] } + expect(payload.tasks).toHaveLength(MAX_REQUESTED_PARALLEL_SUBTASKS + 1) + }) + + it("prefers the parser's bounded list over the raw streamed params", async () => { + const nativeTasks = [{ label: "bounded", mode: "code", message: "from nativeArgs" }] + const block = { + type: "tool_use", + name: "parallel_subtasks", + params: { tasks: JSON.stringify([{ label: "raw", mode: "code", message: "from params" }]) }, + nativeArgs: { tasks: nativeTasks }, + partial: true, + } as unknown as ToolUse<"parallel_subtasks"> + + await parallelSubtasksTool.handle(task, block, makeCallbacks()) + + expect(taskDouble.ask).toHaveBeenCalledWith( + "tool", + JSON.stringify({ tool: "parallelSubtasks", tasks: nativeTasks }), + true, + ) + }) + }) +}) diff --git a/src/core/tools/validateToolUse.ts b/src/core/tools/validateToolUse.ts index 243a170ed9..6fd15bc9c9 100644 --- a/src/core/tools/validateToolUse.ts +++ b/src/core/tools/validateToolUse.ts @@ -117,6 +117,17 @@ function doesFileMatchRegex(filePath: string, pattern: string): boolean { } } +/** + * Always-available tools that stay behind an experiment flag. + * + * The always-available class short-circuits above the generic EXPERIMENT_IDS + * gate further down, so a tool that must not ship until its flag is on needs + * its own check here. Keyed by canonical tool name so an alias resolves first. + */ +const EXPERIMENT_GATED_ALWAYS_AVAILABLE_TOOLS: Partial> = { + parallel_subtasks: "parallelSubtasks", +} + export function isToolAllowedForMode( tool: string, modeSlug: string, @@ -147,6 +158,13 @@ export function isToolAllowedForMode( // Always allow these tools (unless explicitly disabled above) if (ALWAYS_AVAILABLE_TOOLS.includes(tool as any)) { + // Experiment-gated always-available tools: the class above short-circuits + // before the generic EXPERIMENT_IDS gate below, so the flag is checked + // here. An absent flag reads as off, matching the registry default. + const requiredExperiment = EXPERIMENT_GATED_ALWAYS_AVAILABLE_TOOLS[resolvedTool as ToolName] + if (requiredExperiment !== undefined && !experiments?.[requiredExperiment]) { + return false + } return true } diff --git a/src/core/webview/ClineProvider.ts b/src/core/webview/ClineProvider.ts index f19b686b32..d967dff288 100644 --- a/src/core/webview/ClineProvider.ts +++ b/src/core/webview/ClineProvider.ts @@ -72,6 +72,7 @@ import { DEFAULT_MODES, DEFAULT_CHECKPOINT_TIMEOUT_SECONDS, getModelId, + historyItemSchema, isRetiredProvider, modelIdKeys, providerIdentifiers, @@ -82,8 +83,16 @@ import { TaskScheduler } from "../task/TaskScheduler" import { getEffectiveTaskApiConfiguration, selectHandoffExecutionContext, + type SavedModeProfile, type TaskExecutionContext, } from "../task/providerHandoff" +import { BACKGROUND_CHILD_DISABLED_TOOLS, BACKGROUND_CHILD_EXPERIMENTS } from "../background-subtasks/policy" +import type { + BackgroundChildEntry, + BackgroundChildHandle, + BackgroundSubtaskSpec, + SpawnBackgroundChildrenResult, +} from "../background-subtasks/types" import { aggregateTaskCostsRecursive, type AggregatedCosts } from "./aggregateTaskCosts" import { TelemetryService } from "@roo-code/telemetry" import { CloudService, getRooCodeApiUrl } from "@roo-code/cloud" @@ -136,7 +145,7 @@ import { ContextProxy } from "../config/ContextProxy" import { withoutInvalidDisplaySettings } from "../config/displaySettings" import { ProviderSettingsManager } from "../config/ProviderSettingsManager" import { CustomModesManager } from "../config/CustomModesManager" -import { PendingActionSettlementError, Task } from "../task/Task" +import { PendingActionSettlementError, Task, type TaskOptions } from "../task/Task" import { webviewMessageHandler } from "./webviewMessageHandler" import type { WebviewFocusTracker } from "./WebviewFocusTracker" @@ -154,6 +163,7 @@ import { LifecycleTransitionError, } from "../task-persistence" import { readTaskMessages } from "../task-persistence/taskMessages" +import { addBackgroundChild } from "../task-persistence/taskLifecycle" import { readFileWithMissingRetry } from "../task-persistence/readFileWithMissingRetry" import { TaskTitleService } from "../task-title/TaskTitleService" import { getNonce } from "./getNonce" @@ -170,6 +180,87 @@ import { PendingEditOperationStore, type PendingEditOperationInput } from "./Pen type DelegatedChildContext = TaskExecutionContext +/** + * Requested background children when a caller does not specify a size cap + * (design OD-3). Also the default scheduler concurrency for a fan-out. + */ +export const DEFAULT_MAX_PARALLEL_SUBTASKS = 4 + +/** Hard ceiling for one fan-out batch; excess specs are truncated (design OD-3). */ +export const MAX_PARALLEL_SUBTASKS_CAP = 6 + +/** + * Cumulative ceiling on live background children per parent, applied across + * repeated fan-outs (F-17). The per-call cap bounds one batch; this bounds a + * parent that calls `parallel_subtasks` on every turn. + */ +export const MAX_LIVE_BACKGROUND_CHILDREN_PER_PARENT = 8 + +/** + * Options `createTask` accepts on top of the public `CreateTaskOptions`. + * + * Background children need fields that are `TaskOptions`-only: `rootTask` and + * `rootTaskId` (their lineage is not carried by the delegation chain; the id + * covers a root that has no live object), `taskNumber` (their own numbering + * channel), and `backgroundToolPolicy` (their read-only policy). + * `backgroundChildHosted` additionally marks the spawn-time child as a LIVE + * off-stack background child; keeping these in a provider-local type leaves + * the public `CreateTaskOptions` contract untouched. + */ +type CreateTaskInternalOptions = CreateTaskOptions & { + handoffExecutionContext?: DelegatedChildContext + segments?: MentionSegment[] + rootTask?: Task + /** + * Authoritative lineage root id for a child whose root has no live `Task` + * object (a parent restored from History, or an ancestor that delegation + * popped off the stack). `rootTask` cannot carry it in that case because no + * object exists to reference; the id is passed through to `TaskOptions`. + */ + rootTaskId?: string + taskNumber?: number + backgroundToolPolicy?: TaskOptions["backgroundToolPolicy"] + /** Mark a spawn-time background child as a LIVE off-stack background child (P1-2). */ + backgroundChildHosted?: boolean + /** Skip the stack push for tasks that run beside the stack (background children). */ + skipStackPush?: boolean +} + +interface BackgroundChildRecord { + entry: BackgroundChildEntry + task: Task + parentTaskId: string + /** Resolves the handle's `done` promise exactly once. */ + settle: (entry: BackgroundChildEntry) => void + /** + * The disposal `finishBackgroundChild` started at settlement. Callers that + * must drain disposal (the abort cascade, deletion) await this promise so + * they never need a second `dispose()` call: `Task.dispose()` is memoized, + * but a second call still trips exactly-once accounting around the child. + */ + disposalPromise?: Promise +} + +/** + * Optional hooks for one `spawnBackgroundChildren` call. + * + * `onChildStarted` fires from inside the background scheduler permit, right + * before the child's run loop starts, with the entry already marked + * `running`; the caller uses it to update its progress panel (F-09). + */ +export interface SpawnBackgroundChildrenOptions { + onChildStarted?: (entry: BackgroundChildEntry) => void +} + +interface BackgroundAbortHook { + parent: Task + listener: () => void +} + +function isTerminalBackgroundStatus(status: BackgroundChildEntry["status"]): boolean { + return status === "completed" || status === "failed" || status === "aborted" +} + function runDelegationTransition( locks: Map>, parentTaskId: string, @@ -264,6 +355,61 @@ export class ClineProvider private view?: vscode.WebviewView | vscode.WebviewPanel private taskRegistry = new TaskRegistry() private taskScheduler = new TaskScheduler() + // Background children run beside the stack instead of on top of it, so a + // fan-out can never starve the serial delegation gate (design D7). + private backgroundTaskScheduler = new TaskScheduler( + Math.min(DEFAULT_MAX_PARALLEL_SUBTASKS, MAX_PARALLEL_SUBTASKS_CAP), + ) + private readonly backgroundTasks = new Map() + private readonly backgroundAbortHooks = new Map() + // Cancellation epoch per parent. `TaskAborted` bumps it, and an in-flight + // spawn captures it when the batch starts; the abort cascade cannot see a + // child that has no record yet, so the loop compares epochs after each await + // and declines to start a child created inside a cancelled batch. + private readonly backgroundSpawnEpochs = new WeakMap() + // Highest task number issued to each parent's background children, so + // sequential fan-outs keep counting up instead of restarting (F-19). + private readonly backgroundChildNumberHighWater = new Map() + // Background children whose abort/disposal drain outlives their record: + // `finishBackgroundChild` removes the live record synchronously, while + // `abortTask()`'s final message save and disposal finish later. Deletion + // awaits these promises so it cannot remove a task directory that an + // aborted child is still writing (the abort cascade can run ahead of a + // concurrent `deleteTaskWithId`). + private readonly pendingBackgroundChildCleanup = new Map>() + // Child → parent history links whose registration write kept failing. A + // child stamped with `backgroundParentTaskId` but missing from the parent's + // `childIds` survives its parent's deletion (permanent `active` row), so a + // failed link is retried at the next registration, child settlement, or + // task deletion until it lands. + private readonly pendingBackgroundParentLinks = new Map() + // Terminal history writes still in flight for children whose records + // already settled: settlement is synchronous while the bounded-retry write + // runs behind, so a caller that must not race the write (disposal above + // all) drains these promises instead of the live record map. + private readonly pendingBackgroundTerminalWrites = new Map>() + // Children whose terminal write exhausted its bounded retries, keyed by + // child task id with the terminal entry to write. Retried by + // `flushPendingBackgroundTerminalRepairs` at the next registration, child + // settlement, or task deletion — the same repair cadence as + // `pendingBackgroundParentLinks` — because startup reconciliation skips a + // child whose parent is still `active` or `delegated`, which is exactly + // what a cancelled parent leaves behind. + private readonly pendingBackgroundTerminalRepairs = new Map() + // Background-child registrations (parent `childIds` link + child row) in + // flight, keyed by parent task id. Deletion drains the entries for the + // selected task and its descendants before it reads their `childIds`, so a + // registration that lands mid-delete either joins the cascade or is + // declined by the closed admission gate below — never a live child of a + // deleted parent. Unrelated parents' registrations are never drained: none + // of their children can enter that deletion set, so waiting for them would + // only stall the delete. + private readonly pendingBackgroundRegistrations = new Map>>() + // Parents that must not admit new background children. Deletion closes + // admission for the task being deleted: a spawn loop that already passed + // its earlier checks must not publish a child for a deleted parent. Ids + // are never removed; a deleted task never spawns again. + private readonly backgroundAdmissionClosed = new Set() private static readonly delegationTransitionLocks = new Map>() private cancelledDelegationChildIds = new Set() private _workspaceTracker?: WorkspaceTracker // workSpaceTracker read-only for access outside this class @@ -461,7 +607,11 @@ export class ClineProvider void this.updateGlobalState("codebaseIndexModels", EMBEDDING_MODEL_PROFILES) // Initialize the authoritative per-task file-based history store. - this.taskHistoryStore = new TaskHistoryStore(this.contextProxy.globalStorageUri.fsPath) + this.taskHistoryStore = new TaskHistoryStore(this.contextProxy.globalStorageUri.fsPath, { + // A live background child is registered in host memory, never on disk + // alone, so the startup orphan pass must not mark it interrupted (D11). + isLiveBackgroundChild: (taskId) => this.backgroundTasks.has(taskId), + }) this.initializeTaskHistoryStore().catch((error) => { this.log(`Failed to initialize TaskHistoryStore: ${error}`) }) @@ -1019,6 +1169,54 @@ export class ClineProvider // Reject any tasks still waiting for a scheduler permit so they don't // hold the event loop after the provider is torn down. this.taskScheduler.cancelQueued() + this.backgroundTaskScheduler.cancelQueued() + + // Abort every background child before the stack drains, so no child + // outlives the provider (design D8). Any record still live afterwards + // (an abort that threw) is settled synchronously below. + try { + const backgroundParentTaskIds = new Set( + Array.from(this.backgroundTasks.values(), (record) => record.parentTaskId), + ) + for (const parentTaskId of backgroundParentTaskIds) { + await this.abortBackgroundChildren(parentTaskId) + } + } catch (error) { + this.log( + `[ClineProvider#dispose] Background child cleanup failed: ${ + error instanceof Error ? error.message : String(error) + }`, + ) + } + + for (const childTaskId of Array.from(this.backgroundTasks.keys())) { + void this.finishBackgroundChild(childTaskId, { status: "aborted", error: "Provider disposed" }) + } + + this.releaseAllBackgroundAbortHooks() + + // An abort cascade that started before disposal (the parent's + // TaskAborted hook) settles children out of `backgroundTasks` before + // `dispose()`'s own pass, then keeps saving the child's final messages + // and draining its disposal under `pendingBackgroundChildCleanup`. + // Draining those registrations before the history store is torn down + // keeps the teardown ordered after the child's last write, the same + // guard the deletion path applies (`stopBackgroundChildrenBeingDeleted`, + // CR finding axIE). Both reads use the undefined-tolerant shape because + // rollback tests drive dispose-adjacent methods with test doubles. + const pendingBackgroundChildCleanup: Map> | undefined = this.pendingBackgroundChildCleanup + if (pendingBackgroundChildCleanup && pendingBackgroundChildCleanup.size > 0) { + await Promise.all(Array.from(pendingBackgroundChildCleanup.values())) + } + + // Terminal history writes outlive their records by design (see + // `finishBackgroundChild`); drain them so the store is not disposed + // mid-write. + const pendingBackgroundTerminalWrites: Map> | undefined = + this.pendingBackgroundTerminalWrites + if (pendingBackgroundTerminalWrites && pendingBackgroundTerminalWrites.size > 0) { + await Promise.allSettled(Array.from(pendingBackgroundTerminalWrites.values())) + } // Clear all tasks from the stack. The first pop goes through evictCurrentTask() // so an active delegated child is marked interrupted before the extension shuts down, @@ -1660,6 +1858,17 @@ export class ClineProvider startTask: false, // Preserve the status from the history item to avoid overwriting it when the task saves messages initialStatus: historyItem.status, + // A background child restored from history must keep its read-only + // policy: the policy itself is not persisted, so keying on the + // `backgroundParentTaskId` stamp is the only thing that keeps a + // restored child from becoming fully privileged (F-05). It must NOT + // set `backgroundChildHosted`: a restored child installed as the + // current stack task stays interactive (state posts flow, the resume + // ask blocks for approval, no auto-run); only its tool layer stays + // read-only via the policy carried here (P1-2). + backgroundToolPolicy: historyItem.backgroundParentTaskId + ? { disabledTools: BACKGROUND_CHILD_DISABLED_TOOLS, experiments: BACKGROUND_CHILD_EXPERIMENTS } + : undefined, rateLimitClock: this.rateLimitClock, diffFuzzyThreshold, }) @@ -2936,6 +3145,33 @@ export class ClineProvider try { await this.getTaskWithId(id) + // Close admission of new background children for the task being + // deleted, then drain its in-progress registrations before + // `childIds` is read or the delete cascade is collected: a spawn + // that passed its earlier checks would otherwise publish a live + // child for a deleted parent, and an in-flight registration whose + // link write lands after the drain below would escape the cascade + // with a permanent `active` row. Both are scoped to the selected + // task; the cascade closes admission and drains each descendant as + // it reaches it (below), and unrelated parents keep spawning and + // are never drained here. The undefined-tolerant reads match the + // prototype-called guards below for test doubles. + const backgroundAdmissionClosed: Set | undefined = this.backgroundAdmissionClosed + if (backgroundAdmissionClosed) { + backgroundAdmissionClosed.add(id) + } + await ClineProvider.prototype.drainPendingBackgroundRegistrationsFor.call(this, [id]) + await ClineProvider.prototype.flushPendingBackgroundTerminalRepairs.call(this) + + // Complete any background parent link whose registration write kept + // failing BEFORE the cascade below collects `childIds` from the + // store: otherwise a repaired-orphan child escapes the delete + // cascade and keeps a permanent `active` row (CR finding axIR). + // Prototype call, same reason as stopBackgroundChildrenBeingDeleted: + // delegation rollback drives this method with a test double as + // `this`, and the double carries no private methods. + await ClineProvider.prototype.flushPendingBackgroundParentLinks.call(this) + // Collect all task IDs to delete (parent + all subtasks) const allIdsToDelete: string[] = [id] @@ -2943,6 +3179,20 @@ export class ClineProvider // Recursively collect all child IDs const collectChildIds = async (taskId: string): Promise => { try { + // Close admission and drain in-flight registrations for + // this node BEFORE its record is read: a live descendant + // (e.g. a running background child) can otherwise admit + // and register a new background child while the + // collector awaits `getTaskWithId`, and the late + // `childIds` link escapes the cascade snapshot — the + // child's history row and files then survive the + // deletion. Ids are never re-opened, so the root's + // second close below is a no-op. + if (backgroundAdmissionClosed) { + backgroundAdmissionClosed.add(taskId) + } + await ClineProvider.prototype.drainPendingBackgroundRegistrationsFor.call(this, [taskId]) + const { historyItem: item } = await this.getTaskWithId(taskId) if (item.childIds && item.childIds.length > 0) { for (const childId of item.childIds) { @@ -2968,6 +3218,15 @@ export class ClineProvider } } + // A background child runs beside the stack, so the check above never + // matches it: deleting a running child by its own id would otherwise + // remove its history and files while its run keeps writing (CR finding + // 4). Stop and drain every live child being deleted before either + // removal; siblings not selected here keep running. Reached through + // the prototype for the same reason as resolveLineageRoot: delegation + // rollback drives this method with a test double as `this`. + await ClineProvider.prototype.stopBackgroundChildrenBeingDeleted.call(this, allIdsToDelete) + for (const taskId of allIdsToDelete) { this.taskTitleService.cancel(taskId, "deleted") } @@ -4372,10 +4631,7 @@ export class ClineProvider text?: string, images?: string[], parentTask?: Task, - options: CreateTaskOptions & { - handoffExecutionContext?: DelegatedChildContext - segments?: MentionSegment[] - } = {}, + options: CreateTaskInternalOptions = {}, configuration: RooCodeSettings = {}, ): Promise { if (configuration) { @@ -4442,6 +4698,8 @@ export class ClineProvider throw new OrganizationAllowListViolationError(t("common:errors.violated_organization_allowlist")) } + const { skipStackPush, ...taskOptions } = options + const task = new Task({ provider: this, apiConfiguration, @@ -4461,11 +4719,15 @@ export class ClineProvider // its initial state update, so state.currentTaskId is available ASAP. startTask: false, diffFuzzyThreshold, - ...options, + ...taskOptions, rateLimitClock: this.rateLimitClock, }) - await this.addClineToStack(task) + // Background children are started under their own scheduler and must + // never become the current stack task. + if (!skipStackPush) { + await this.addClineToStack(task) + } if (options.startTask !== false) { scheduleTask(this.taskScheduler, task, "createTask") } @@ -4547,6 +4809,20 @@ export class ClineProvider // before we persist "interrupted", so our write is always the last one. await abortPromise.catch(() => {}) + // Background children belong to this parent and must not outlive its + // cancellation. Runs before the rehydrate race checks below so the + // cascade also happens on their early-return paths; a cancel must never + // be blocked by a failing child abort. + try { + await this.abortBackgroundChildren(task.taskId) + } catch (error) { + this.log( + `[cancelTask] Failed to abort background children of ${task.taskId}: ${ + error instanceof Error ? error.message : String(error) + }`, + ) + } + // Defensive safeguard: if current instance already changed, skip rehydrate const current = this.getCurrentTask() if (current && current.instanceId !== originalInstanceId) { @@ -4636,177 +4912,1352 @@ export class ClineProvider await this.createTaskWithHistoryItem({ ...historyItem, rootTask, parentTask }) } - // Clear the current task without treating it as a subtask. - // This is used when the user cancels a task that is not a subtask. - public async clearTask(): Promise { - const task = this.taskRegistry.current - if (task) { - console.log(`[clearTask] clearing task ${task.taskId}.${task.instanceId}`) - await this.removeClineFromStack() + // Background subtasks (design D2/D7/D8) + // + // A background child is a read-only task spawned beside the active task + // instead of on top of it: it is created with `startTask: false`, never + // enters `taskRegistry`, and runs under its own scheduler permit pool. The + // provider owns the map so cancel, dispose, and the completion route all + // settle the same records exactly once. + + /** + * Spawn read-only background children for `parallel_subtasks`. + * + * The parent remains the sole stack task: `createTask` is called with + * `startTask: false` and without `addClineToStack`, then each child is + * started under `backgroundTaskScheduler`. The parent's history record + * gains the child ids (`addBackgroundChild`), and each child is stamped + * with `backgroundParentTaskId` before it can write history itself. + * + * Rejected specs (unknown mode, failed construction) produce a terminal + * `failed` handle instead of a live task, so callers always receive a + * settleable handle and `done` never rejects. + */ + public async spawnBackgroundChildren( + parent: Task, + specs: BackgroundSubtaskSpec[], + options: SpawnBackgroundChildrenOptions = {}, + ): Promise { + const children: BackgroundChildHandle[] = [] + + if (specs.length === 0) { + return { children, started: false } } - } - public resumeTask(taskId: string): void { - // Use the existing showTaskWithId method which handles both current and - // historical tasks. - this.showTaskWithId(taskId).catch((error) => { - this.log(`Failed to resume task ${taskId}: ${error.message}`) - }) - } + let effectiveSpecs = specs - // Modes + if (specs.length > MAX_PARALLEL_SUBTASKS_CAP) { + effectiveSpecs = specs.slice(0, MAX_PARALLEL_SUBTASKS_CAP) + this.log( + `[spawnBackgroundChildren] Truncated ${specs.length} requested background children to the hard cap of ${MAX_PARALLEL_SUBTASKS_CAP}`, + ) + } - public async getModes(): Promise<{ slug: string; name: string }[]> { - try { - const customModes = await this.customModesManager.getCustomModes() - return [...DEFAULT_MODES, ...customModes].map(({ slug, name }) => ({ slug, name })) - } catch { - return DEFAULT_MODES.map(({ slug, name }) => ({ slug, name })) + const { customModes } = await this.getState() + const parentMode = await parent.getTaskMode() + const parentExecutionContext: DelegatedChildContext = { + mode: parentMode, + apiConfigName: await parent.getTaskApiConfigName(), + apiConfiguration: structuredClone(parent.apiConfiguration), } - } + const savedModeProfiles = new Map() - public async getMode(): Promise { - const { mode } = await this.getState() - return mode - } + // `createTask` would hand every child the same `taskRegistry.length + 1`, + // because none of them is pushed to the stack. Number the batch from a + // per-parent high-water mark instead, so sequential fan-outs keep + // counting up rather than repeating the previous batch (F-19). + const baseTaskNumber = this.nextBackgroundChildNumber(parent) + const lineageRoot = this.resolveLineageRoot(parent) + const spawnEpoch = this.backgroundSpawnEpoch(parent) + let started = false - public async setMode(mode: string): Promise { - await this.setValues({ mode }) - } + // Installed before the first child is scheduled so an abort during the + // batch is observed. The finally block releases it once the last child + // is gone, including when the loop throws before any child registered + // (F-21). + this.ensureBackgroundAbortHook(parent) - // Provider Profiles + try { + for (const [index, spec] of effectiveSpecs.entries()) { + // A parent cancelled (or a provider disposed) while an earlier + // spec awaited `createTask`/registration is re-checked only from + // the awaits that follow it. Without this gate every remaining + // spec would still pay a full `createTask` construction that the + // post-await check then settles and disposes for nothing (CR + // finding 1: check the parent and provider before admitting + // work). The handle still settles so callers keep one handle + // per spec (ParallelSubtasksTool counts on that). + if (!this.isBackgroundSpawnParentActive(parent, spawnEpoch)) { + children.push(this.cancelledBackgroundHandle(spec)) + continue + } - public async getProviderProfiles(): Promise<{ name: string; provider?: string }[]> { - const { listApiConfigMeta = [] } = await this.getState() - return listApiConfigMeta.map((profile) => ({ name: profile.name, provider: profile.apiProvider })) - } + // The per-call cap bounds one batch; this bounds the parent's + // cumulative fan-out across turns (F-17). + if (this.countLiveBackgroundChildren(parent.taskId) >= MAX_LIVE_BACKGROUND_CHILDREN_PER_PARENT) { + children.push( + this.failedBackgroundHandle( + spec, + `Live background child limit reached (${MAX_LIVE_BACKGROUND_CHILDREN_PER_PARENT} per parent)`, + ), + ) + continue + } - public async getProviderProfile(): Promise { - const { currentApiConfigName = "default" } = await this.getState() - return currentApiConfigName - } + if (!getModeBySlug(spec.mode, customModes)) { + children.push(this.failedBackgroundHandle(spec, `Unknown mode: ${spec.mode}`)) + continue + } - public async setProviderProfile(name: string): Promise { - await this.activateProviderProfile({ name }) - } + const lockApiConfigAcrossModes = + spec.mode !== parentMode && this.context.workspaceState.get("lockApiConfigAcrossModes", false) + let savedModeProfile: SavedModeProfile | undefined - // Telemetry + if (spec.mode !== parentMode && !lockApiConfigAcrossModes) { + savedModeProfile = await this.loadSavedModeProfile(spec.mode, savedModeProfiles) + } - private _appProperties?: StaticAppProperties - private _gitProperties?: GitProperties + const handoffExecutionContext = selectHandoffExecutionContext( + parentExecutionContext, + spec.mode, + parentMode, + lockApiConfigAcrossModes, + savedModeProfile, + ) - private getAppProperties(): StaticAppProperties { - if (!this._appProperties) { - const packageJSON = this.context.extension?.packageJSON + let child: Task - this._appProperties = { - appName: packageJSON?.name ?? Package.name, - appVersion: packageJSON?.version ?? Package.version, - releaseChannel: Package.releaseChannel, - vscodeVersion: vscode.version, - platform: process.platform, - editorName: vscode.env.appName, - } - } + try { + child = await this.createTask(spec.message, undefined, parent, { + initialStatus: "active", + startTask: false, + skipStackPush: true, + taskNumber: baseTaskNumber + index, + // A background child has neither a `historyItem` nor a stack + // entry, so the lineage root has to be passed explicitly: the + // live object when one is reachable, or the authoritative root + // id on its own so the child still persists the true root + // instead of inheriting the parent's id (CR finding 5). + rootTask: lineageRoot.rootTask, + ...(lineageRoot.rootTask ? {} : { rootTaskId: lineageRoot.rootTaskId }), + handoffExecutionContext, + backgroundToolPolicy: { + disabledTools: BACKGROUND_CHILD_DISABLED_TOOLS, + experiments: BACKGROUND_CHILD_EXPERIMENTS, + }, + // LIVE off-stack background child (P1-2): `isBackgroundSubtaskChild` + // derives from this flag, not from the policy, so the child runs + // non-interactively beside the parent. A history-restore must NOT + // set it. + backgroundChildHosted: true, + }) + } catch (error) { + const message = error instanceof Error ? error.message : String(error) + // `label` is model-controlled, so JSON-encode it: a newline in + // the label must not be able to forge a second log line + // (CWE-117, F-22). + this.log( + `[spawnBackgroundChildren] Failed to create child ${JSON.stringify(spec.label)}: ${message}`, + ) + children.push(this.failedBackgroundHandle(spec, message)) + continue + } - return this._appProperties - } + // The parent may have been cancelled, evicted, or the provider + // disposed while `createTask` was awaiting (CR finding 1). The + // abort cascade settled only the records that existed then, so + // this child has no record and would otherwise be published and + // scheduled after cancellation. Never run it. + if (!this.isBackgroundSpawnParentActive(parent, spawnEpoch)) { + children.push(this.settleBackgroundChildWithoutScheduling(spec, child)) + continue + } - public get appProperties(): StaticAppProperties { - return this._appProperties ?? this.getAppProperties() - } + // The child's own history write only starts with its task loop, so + // both sides of the registration are written before it can race them. + await this.registerBackgroundChild(parent, child, handoffExecutionContext) - private getCloudProperties(): CloudAppProperties { - let cloudIsAuthenticated: boolean | undefined + // Registration awaits history-store writes; re-check the same window + // before the record is published and the run is scheduled. + if (!this.isBackgroundSpawnParentActive(parent, spawnEpoch)) { + children.push(this.settleBackgroundChildWithoutScheduling(spec, child)) + continue + } - try { - if (CloudService.hasInstance()) { - cloudIsAuthenticated = CloudService.instance.isAuthenticated() + const entry: BackgroundChildEntry = { + taskId: child.taskId, + label: spec.label, + mode: spec.mode, + status: "queued", + startedAt: Date.now(), + } + let settle!: (settled: BackgroundChildEntry) => void + const done = new Promise((resolve) => { + let settled = false + settle = (settledEntry) => { + if (settled) { + return + } + settled = true + resolve(settledEntry) + } + }) + + this.backgroundTasks.set(child.taskId, { + entry, + task: child, + parentTaskId: parent.taskId, + settle, + }) + + // A child that aborts itself (API failure, disposal) must still + // settle its handle even when nothing calls the host methods. + child.once(RooCodeEventName.TaskAborted, () => { + void this.finishBackgroundChild(child.taskId, { + status: "aborted", + error: "Background child was aborted", + }) + }) + + children.push({ taskId: child.taskId, label: spec.label, mode: spec.mode, done }) + started = true + + // Re-assert the hook: a sibling that failed during an earlier await + // could have released it when its record was the last live one. + this.ensureBackgroundAbortHook(parent) + + scheduleTask( + this.backgroundTaskScheduler, + child, + "spawnBackgroundChildren", + () => { + // The run wrapper is invoked after the permit is acquired, + // so this is the first moment the child is running (F-09). + this.markBackgroundChildRunning(child.taskId, options.onChildStarted) + + // Race the run against the handle: the host settles `done` + // exactly when a terminal state is recorded (D5 resolve, the + // TaskAborted hook, or the failure callback below), so the + // scheduler permit is released at that point even if a future + // change lets the run promise itself dangle. A background + // child has no user who could cancel it, so a terminal child + // must never keep holding a permit. + return Promise.race([child.run(), done]).then(() => { + // Catch-all (F-02): `run()` settled without any terminal + // record (D5 resolve, the TaskAborted hook, or the + // scheduler onError). Every such exit ends through an + // abort-style throw, not a recorded terminal state: the + // mistake-limit terminal (F-08), the bounded background + // retries exceeding MAX_BACKGROUND_CHILD_RETRY_ATTEMPTS + // (P1-1: empty assistant response, mid-stream failure, + // first-chunk failure), an output-token-limit denial, or a + // first-chunk API failure with auto-approval off. Fail the + // handle so the caller's join always settles. A recorded + // terminal state already removed the record, so this is a + // no-op for every normal path. + this.failBackgroundChild( + child.taskId, + "Background child run ended without a terminal state", + ) + }) + }, + (error) => { + void this.finishBackgroundChild(child.taskId, { + status: "failed", + error: error instanceof Error ? error.message : String(error), + }) + }, + ) } - } catch (error) { - // Silently handle errors to avoid breaking telemetry collection. - this.log(`[getTelemetryProperties] Failed to get cloud auth state: ${error}`) + } finally { + this.releaseBackgroundAbortHookIfIdle(parent.taskId) } - return { - cloudIsAuthenticated, - } - } + this.backgroundChildNumberHighWater.set(parent.taskId, baseTaskNumber + effectiveSpecs.length - 1) - private async getTaskProperties(): Promise { - const { language = "en", mode, apiConfiguration } = await this.getState() + return { children, started } + } - const task = this.getCurrentTask() - const todoList = task?.todoList - let todos: { total: number; completed: number; inProgress: number; pending: number } | undefined + /** + * First task number for `parent`'s next background batch. `createTask` + * numbers by stack length, which repeats for every batch because background + * children never join the stack; the per-parent high-water mark keeps + * numbers monotonic across sequential fan-outs (F-19), and existing history + * numbers seed it so a restart cannot reuse one. + */ + private nextBackgroundChildNumber(parent: Task): number { + let historyFloor = 0 - if (todoList && todoList.length > 0) { - todos = { - total: todoList.length, - completed: todoList.filter((todo) => todo.status === "completed").length, - inProgress: todoList.filter((todo) => todo.status === "in_progress").length, - pending: todoList.filter((todo) => todo.status === "pending").length, + for (const item of this.taskHistoryStore.getAll()) { + if (item.backgroundParentTaskId === parent.taskId && typeof item.number === "number") { + historyFloor = Math.max(historyFloor, item.number) } } - const apiProvider = apiConfiguration?.apiProvider + const previousBatchFloor = this.backgroundChildNumberHighWater.get(parent.taskId) ?? 0 + const liveFloor = this.taskRegistry.length + this.backgroundTasks.size - return { - language, - mode, - taskId: task?.taskId, - parentTaskId: task?.parentTaskId, - apiProvider: apiProvider && !isRetiredProvider(apiProvider) ? apiProvider : undefined, - modelId: task?.api?.getModel().id, - diffStrategy: task?.diffStrategy?.getName(), - isSubtask: task ? !!task.parentTaskId : undefined, - ...(todos && { todos }), - } + return Math.max(historyFloor, previousBatchFloor, liveFloor) + 1 } - private async getGitProperties(): Promise { - if (!this._gitProperties) { - this._gitProperties = await getWorkspaceGitInfo() + private countLiveBackgroundChildren(parentTaskId: string): number { + let count = 0 + + for (const record of this.backgroundTasks.values()) { + if (record.parentTaskId === parentTaskId) { + count++ + } } - return this._gitProperties + return count } - public get gitProperties(): GitProperties | undefined { - return this._gitProperties - } + /** + * Mark a queued child as running and publish the transition to the + * fan-out owner. Called from inside the scheduler permit, so it runs once + * per child and never for an already-terminal one. + */ + private markBackgroundChildRunning( + childTaskId: string, + onChildStarted?: (entry: BackgroundChildEntry) => void, + ): void { + const record = this.backgroundTasks.get(childTaskId) - public async getTelemetryProperties(): Promise { - return { - ...this.getAppProperties(), - ...this.getCloudProperties(), - ...(await this.getTaskProperties()), - ...(await this.getGitProperties()), + if (!record || record.entry.status !== "queued") { + return + } + + const entry: BackgroundChildEntry = { ...record.entry, status: "running", startedAt: Date.now() } + record.entry = entry + + try { + onChildStarted?.(entry) + } catch (error) { + this.log( + `[spawnBackgroundChildren] Background child start listener failed for ${childTaskId}: ${ + error instanceof Error ? error.message : String(error) + }`, + ) } } - /** Workspace explicitly associated with this provider, without an active-editor fallback. */ - public get workspacePath(): string | undefined { - return this.currentWorkspacePath + /** + * Resolve a background child that reported its result through + * `attempt_completion`. Idempotent: a terminal child is never re-settled. + */ + public resolveBackgroundChild(childTaskId: string, result: string): void { + void this.finishBackgroundChild(childTaskId, { status: "completed", result }) } - public get cwd() { - return this.currentWorkspacePath || getWorkspacePath() + /** + * Record a failed background child (API error, rejected completion, + * fail-closed ask) and settle its handle. Idempotent like the resolve path. + */ + public failBackgroundChild(childTaskId: string, error: string): void { + void this.finishBackgroundChild(childTaskId, { status: "failed", error }) } /** - * Delegate parent task and open child task. - * - * - Enforce single-open invariant - * - Persist parent delegation metadata - * - Emit TaskDelegated (task-level; API forwards to provider/bridge) - * - Create child as sole active and switch mode to child's mode + * Abort every live background child of `parentTaskId` and settle each + * handle as `aborted`. Used by the `TaskAborted` hook, `cancelTaskInternal` + * and `dispose`; a per-child abort failure never prevents the rest from + * settling (design D8). */ - public async delegateParentAndOpenChild(params: { - parentTaskId: string - message: string - initialTodos: TodoItem[] - mode: string + public async abortBackgroundChildren(parentTaskId: string): Promise { + const records = Array.from(this.backgroundTasks.values()).filter( + (record) => record.parentTaskId === parentTaskId, + ) + + if (records.length === 0) { + return + } + + this.log(`[abortBackgroundChildren] Aborting ${records.length} background child(ren) of ${parentTaskId}`) + + await Promise.all( + records.map(async (record) => { + const childTaskId = record.entry.taskId + + // Register the pending cleanup BEFORE settling: settlement + // removes the record from `backgroundTasks` synchronously, and a + // concurrent `deleteTaskWithId` that reaches the lookup after + // this point must still be able to await the abort/disposal + // drain that is about to start. + let runCleanup!: (cleanup: Promise) => void + const cleanupPending = new Promise((resolve) => { + runCleanup = resolve + }) + this.pendingBackgroundChildCleanup.set(childTaskId, cleanupPending) + + try { + // Settle before aborting: `abortTask()` emits TaskAborted, and the + // child's own listener would otherwise win the terminal-state race + // with a generic "child was aborted" reason. The terminal write + // promise stays fire-and-forget here; it is tracked in + // `pendingBackgroundTerminalWrites` for disposal to drain. + void this.finishBackgroundChild(childTaskId, { + status: "aborted", + error: "Parent task was cancelled", + }) + + runCleanup( + (async () => { + try { + await record.task.abortTask() + } catch (error) { + this.log( + `[abortBackgroundChildren] abortTask failed for ${childTaskId}: ${ + error instanceof Error ? error.message : String(error) + }`, + ) + } + + // `abortTask()` starts disposal without awaiting it, and + // settlement above started `dispose()` for real: drain the + // recorded promise so a concurrent deletion never removes + // the task directory while the child's own cleanup is + // still running. A second `dispose()` call is avoided even + // though Task memoizes it, because exactly-once disposal + // accounting around the child must not see two calls. + if (record.disposalPromise) { + try { + await record.disposalPromise + } catch { + // Settlement already logged the disposal failure. + } + } + })(), + ) + + await cleanupPending + } finally { + if (this.pendingBackgroundChildCleanup.get(childTaskId) === cleanupPending) { + this.pendingBackgroundChildCleanup.delete(childTaskId) + } + } + }), + ) + + this.releaseBackgroundAbortHookIfIdle(parentTaskId) + } + + /** + * Stop and drain the background children among `taskIds` before their + * history and files are deleted (CR finding 4). + * + * `abortBackgroundChildren` is keyed by parent; deletion is keyed by the + * children themselves, and a background child never matches + * `getCurrentTask()`. Each child is settled before `abortTask()` so the + * TaskAborted listener cannot overwrite the aborted outcome, and disposal is + * awaited so no pending write from the deleted task survives the removal. + * + * A child the abort cascade already settled is gone from `backgroundTasks`, + * but its abort/disposal drain is still tracked in + * `pendingBackgroundChildCleanup`: deleting the parent mid-cascade would + * otherwise remove the directory while the aborted child's final save is + * still in flight. Only the selected ids are awaited, so a sibling that is + * not being deleted never stalls the deletion. + */ + private async stopBackgroundChildrenBeingDeleted(taskIds: readonly string[]): Promise { + // Prototype-call doubles (delegation rollback tests) drive this method + // with a plain object that carries no background map; nothing can be live + // there, so there is nothing to stop. + const backgroundTasks: Map | undefined = this.backgroundTasks + const pendingBackgroundChildCleanup: Map> | undefined = this.pendingBackgroundChildCleanup + + if (!backgroundTasks || !pendingBackgroundChildCleanup) { + return + } + + const uniqueIds = Array.from(new Set(taskIds)) + const records = uniqueIds + .map((taskId) => backgroundTasks.get(taskId)) + .filter((record): record is BackgroundChildRecord => record !== undefined) + const pendingCleanups = uniqueIds + .map((taskId) => pendingBackgroundChildCleanup.get(taskId)) + .filter((cleanup): cleanup is Promise => cleanup !== undefined) + + if (records.length === 0 && pendingCleanups.length === 0) { + return + } + + await Promise.all([ + ...records.map(async (record) => { + // Settle first (the handle resolves synchronously), then let the + // terminal history write land before this row can be removed: + // `deleteMany` runs as soon as this drain resolves. + await this.finishBackgroundChild(record.entry.taskId, { + status: "aborted", + error: "Task was deleted", + }) + + try { + await record.task.abortTask() + } catch (error) { + this.log( + `[deleteTaskWithId] abortTask failed for background child ${record.entry.taskId}: ${ + error instanceof Error ? error.message : String(error) + }`, + ) + } + + try { + // `abortTask()` starts disposal without awaiting it; drain that + // promise so the caller removes the directory only after the + // task's own cleanup (reversion, artifacts) has finished. + await record.task.dispose() + } catch (error) { + this.log( + `[deleteTaskWithId] dispose failed for background child ${record.entry.taskId}: ${ + error instanceof Error ? error.message : String(error) + }`, + ) + } + }), + // Already-settled children: the cascade logged its own failures, and + // the tracked cleanup promise never rejects, so it is awaited as-is. + ...pendingCleanups, + ]) + } + + /** + * Settle one live record. The terminal check and the map removal run in the + * same synchronous turn, so concurrent resolve/abort/failure paths can never + * double-settle or overwrite a terminal outcome. + * + * The synchronous part settles the handle exactly as before; the returned + * promise is the child's terminal history write so a caller that must not + * race it (deletion before `deleteMany`, disposal before the store is torn + * down) can await the write after settlement. The write is also tracked in + * `pendingBackgroundTerminalWrites`, which outlives the record. + */ + private finishBackgroundChild( + childTaskId: string, + update: { status: BackgroundChildEntry["status"] } & Partial>, + ): Promise { + const record = this.backgroundTasks.get(childTaskId) + + if (!record || isTerminalBackgroundStatus(record.entry.status)) { + return Promise.resolve() + } + + const entry: BackgroundChildEntry = { ...record.entry, ...update, finishedAt: Date.now() } + record.entry = entry + record.settle(entry) + this.backgroundTasks.delete(childTaskId) + this.releaseBackgroundAbortHookIfIdle(record.parentTaskId) + + // A background child never enters the task stack, so stack eviction never + // releases the resources its dispose() owns (fileContextTracker, + // rooIgnoreController, messageQueueService). Terminal settlement is the + // only release point for a child that completes normally or dies through + // the retry/mistake limit. `dispose()` is memoized by `disposalPromise` + // (abortTaskOnce may call it too) and it never emits TaskAborted, so the + // recorded terminal status above cannot change. The started promise is + // kept on the record so the abort cascade and deletion can drain this + // same disposal instead of calling `dispose()` again. + const disposalPromise = record.task.dispose() + record.disposalPromise = disposalPromise + void disposalPromise.catch((error) => { + this.log( + `[spawnBackgroundChildren] Failed to release resources of settled child ${childTaskId}: ${ + error instanceof Error ? error.message : String(error) + }`, + ) + }) + + // The terminal write gets a bounded retry: a single rejected write + // would otherwise leave the row `active` with no later repair while + // the parent stays active/delegated. The promise is returned and + // tracked in `pendingBackgroundTerminalWrites` so disposal can drain + // it before the history store is torn down; settlement above already + // happened, so the settle-first order is unchanged. + const terminalWrite = this.persistBackgroundChildTerminalWithRetry(entry) + this.trackBackgroundTerminalWrite(childTaskId, terminalWrite) + void terminalWrite.catch((error) => { + this.log( + `[spawnBackgroundChildren] Unexpected error persisting terminal state for ${childTaskId}: ${ + error instanceof Error ? error.message : String(error) + }`, + ) + }) + + // The child has stopped touching its own record, so settlement is a + // natural repair point for any parent `childIds` link whose registration + // write kept failing (CR finding axIR), and for any sibling child whose + // terminal write exhausted its bounded retries. + void ClineProvider.prototype.flushPendingBackgroundParentLinks.call(this).catch((error) => { + this.log( + `[spawnBackgroundChildren] Unexpected error repairing pending parent links: ${ + error instanceof Error ? error.message : String(error) + }`, + ) + }) + void ClineProvider.prototype.flushPendingBackgroundTerminalRepairs.call(this).catch((error) => { + this.log( + `[spawnBackgroundChildren] Unexpected error repairing pending terminal writes: ${ + error instanceof Error ? error.message : String(error) + }`, + ) + }) + + return terminalWrite + } + + /** + * Write the child's terminal history status. A child that aborted or failed + * has no terminal history status of its own, so it is persisted as + * `interrupted`; `completed` is written as-is. + */ + private async persistBackgroundChildTerminal(entry: BackgroundChildEntry): Promise { + if (!this.taskHistoryStore.get(entry.taskId)) { + // The row can be missing when the child-side registration upsert + // kept failing or the row was already removed; the write would be + // dropped silently otherwise, which made those states + // indistinguishable from a landed write in the logs. + this.log( + `[spawnBackgroundChildren] Not persisting terminal state for ${entry.taskId}: no history record exists`, + ) + return + } + + const status = entry.status === "completed" ? "completed" : "interrupted" + + await this.taskHistoryStore.atomicReadAndUpdate(entry.taskId, (item) => + item.status === "completed" ? item : { ...item, status }, + ) + this.recentTasksCache = undefined + + if (this.isViewLaunched) { + const updated = this.taskHistoryStore.get(entry.taskId) + if (updated) { + await this.postMessageToWebview({ type: "taskHistoryItemUpdated", taskHistoryItem: updated }) + } + } + } + + /** + * Bounded-retry wrapper around the child's terminal history write. A + * single fire-and-forget write that rejects leaves the child's history row + * `active` with no later repair: startup reconciliation + * (`TaskHistoryStore.reconcileBackgroundChildren`) skips a child whose + * parent is still active or delegated, which is exactly the state a + * cancelled parent leaves behind. The realistic failure mode is a + * transient filesystem error (e.g. a Windows/OneDrive file lock on the + * history file), so the write is retried a small number of times, with a + * short backoff. A write that still fails is recorded in + * `pendingBackgroundTerminalRepairs` and retried by + * `flushPendingBackgroundTerminalRepairs` at the next registration, child + * settlement, or task deletion, so the row is never left `active` with no + * further action. The recorded terminal status semantics are unchanged: + * the retry writes exactly what a first-attempt success would have. + * + * Returns `true` when the write landed (or the row is gone, which needs + * no repair) and `false` when every attempt failed and the repair was + * recorded. + */ + private async persistBackgroundChildTerminalWithRetry(entry: BackgroundChildEntry): Promise { + const pendingBackgroundTerminalRepairs: Map | undefined = + this.pendingBackgroundTerminalRepairs + const maxAttempts = 3 + + for (let attempt = 1; attempt <= maxAttempts; attempt++) { + try { + await this.persistBackgroundChildTerminal(entry) + pendingBackgroundTerminalRepairs?.delete(entry.taskId) + return true + } catch (error) { + this.log( + `[spawnBackgroundChildren] Persisting terminal state for ${entry.taskId} failed (attempt ${attempt}/${maxAttempts}): ${ + error instanceof Error ? error.message : String(error) + }`, + ) + if (attempt < maxAttempts) { + await delay(50) + } + } + } + + pendingBackgroundTerminalRepairs?.set(entry.taskId, entry) + this.log( + `[spawnBackgroundChildren] Giving up persisting terminal state for ${entry.taskId} after ${maxAttempts} failed attempts; recorded for repair at the next registration, child settlement, or task deletion`, + ) + return false + } + + /** + * Track a child's in-flight terminal write so `dispose()` can drain it + * before the history store is torn down. The record itself is already + * gone at settlement, so the map — not `backgroundTasks` — is the + * reachability anchor for the write. + */ + private trackBackgroundTerminalWrite(childTaskId: string, terminalWrite: Promise): void { + const pendingBackgroundTerminalWrites: Map> | undefined = + this.pendingBackgroundTerminalWrites + + if (!pendingBackgroundTerminalWrites) { + return + } + + pendingBackgroundTerminalWrites.set(childTaskId, terminalWrite) + void terminalWrite + .finally(() => { + if (pendingBackgroundTerminalWrites.get(childTaskId) === terminalWrite) { + pendingBackgroundTerminalWrites.delete(childTaskId) + } + }) + .catch(() => { + // The write logs its own failures; the drain must never reject. + }) + } + + /** + * Retry every child whose terminal history write exhausted its bounded + * retries. Entries whose write lands are removed; the rest stay queued for + * the next pass. Mirrors `flushPendingBackgroundParentLinks`, including + * the undefined-tolerant map read: prototype-call doubles (delegation + * rollback tests) drive callers of this method with a plain object that + * carries no pending-repair map. + */ + private async flushPendingBackgroundTerminalRepairs(): Promise { + const pending: Map | undefined = this.pendingBackgroundTerminalRepairs + + if (!pending || pending.size === 0) { + return + } + + for (const [childTaskId, entry] of Array.from(pending)) { + if (await this.persistBackgroundChildTerminalWithRetry(entry)) { + pending.delete(childTaskId) + } + } + } + + /** + * Whether a spawn loop may still publish and schedule a child for `parent`. + * + * The loop awaits `createTask` and the history-store registration, and the + * parent can be cancelled (or the provider disposed) while those are + * pending. `abortBackgroundChildren` settles only children that already have + * a record, so a child created inside that window would otherwise be + * published and scheduled after the abort cascade drained the map. + */ + private isBackgroundSpawnParentActive(parent: Task, spawnEpoch: number): boolean { + if (this._disposed) { + return false + } + + // Deletion closes admission permanently for the task being deleted: a + // spawn loop that passed its earlier checks must not publish a child + // for a deleted parent. The undefined-tolerant read matches the other + // background guards for prototype-call test doubles. + const backgroundAdmissionClosed: Set | undefined = this.backgroundAdmissionClosed + if (backgroundAdmissionClosed?.has(parent.taskId)) { + return false + } + + // A batch that started before the parent aborted must not publish any + // more children; a batch started afterwards is a different decision. + if (this.backgroundSpawnEpoch(parent) !== spawnEpoch) { + return false + } + + // `abortTask()` flips this synchronously, so it also covers a + // cancellation whose TaskAborted event this provider did not observe. + return !parent.abort + } + + private backgroundSpawnEpoch(parent: Task): number { + return this.backgroundSpawnEpochs.get(parent) ?? 0 + } + + /** + * Settle a child that was constructed while its parent was being cancelled + * (or the provider disposed) without ever publishing it to + * `backgroundTasks` or scheduling it. + * + * The normal record path would emit TaskAborted and could overwrite the + * terminal outcome, so the handle is resolved directly. Disposal releases + * the resources the never-started task already allocated (CR finding 1). + * The terminal history write still has to land: it goes through the + * bounded retry so a transient store error cannot strand the row on + * `active` (startup reconciliation skips a child whose parent is still + * active or delegated). + */ + private settleBackgroundChildWithoutScheduling(spec: BackgroundSubtaskSpec, child: Task): BackgroundChildHandle { + const finishedAt = Date.now() + const entry: BackgroundChildEntry = { + taskId: child.taskId, + label: spec.label, + mode: spec.mode, + status: "aborted", + error: this._disposed ? "Provider disposed" : "Parent task was cancelled", + startedAt: finishedAt, + finishedAt, + } + + this.log( + `[spawnBackgroundChildren] Child ${child.taskId} finished construction after its parent was cancelled or the provider was disposed; not scheduling it`, + ) + + void child.dispose().catch((error) => { + this.log( + `[spawnBackgroundChildren] Failed to dispose unscheduled child ${child.taskId}: ${ + error instanceof Error ? error.message : String(error) + }`, + ) + }) + + // The terminal history write still has to land: it goes through the + // bounded retry so a transient store error cannot strand the row on + // `active` (startup reconciliation skips a child whose parent is still + // active or delegated). The promise is tracked like the scheduled + // path's write so disposal can drain it. + const terminalWrite = this.persistBackgroundChildTerminalWithRetry(entry) + this.trackBackgroundTerminalWrite(entry.taskId, terminalWrite) + void terminalWrite.catch((error) => { + this.log( + `[spawnBackgroundChildren] Unexpected error persisting terminal state for unscheduled child ${child.taskId}: ${ + error instanceof Error ? error.message : String(error) + }`, + ) + }) + + return { taskId: entry.taskId, label: spec.label, mode: spec.mode, done: Promise.resolve(entry) } + } + + private failedBackgroundHandle(spec: BackgroundSubtaskSpec, error: string): BackgroundChildHandle { + const finishedAt = Date.now() + // No task exists for a rejected spec, so the handle carries a synthetic id. + const entry: BackgroundChildEntry = { + taskId: crypto.randomUUID(), + label: spec.label, + mode: spec.mode, + status: "failed", + error, + startedAt: finishedAt, + finishedAt, + } + + return { taskId: entry.taskId, label: spec.label, mode: spec.mode, done: Promise.resolve(entry) } + } + + /** + * Settled `aborted` handle for a spec that was never constructed because + * its parent was cancelled or the provider disposed before the spec was + * admitted to the batch. Mirrors the outcome of + * `settleBackgroundChildWithoutScheduling` minus the task: with no task + * constructed there is nothing to dispose and no history record to + * reconcile, so this writes nothing. + */ + private cancelledBackgroundHandle(spec: BackgroundSubtaskSpec): BackgroundChildHandle { + const finishedAt = Date.now() + // `label` is model-controlled, so JSON-encode it: a newline in the label + // must not be able to forge a second log line (CWE-117, F-22). + this.log( + `[spawnBackgroundChildren] Parent was cancelled or the provider disposed before spec ${JSON.stringify(spec.label)} was admitted; not constructing a child`, + ) + const entry: BackgroundChildEntry = { + taskId: crypto.randomUUID(), + label: spec.label, + mode: spec.mode, + status: "aborted", + error: this._disposed ? "Provider disposed" : "Parent task was cancelled", + startedAt: finishedAt, + finishedAt, + } + + return { taskId: entry.taskId, label: spec.label, mode: spec.mode, done: Promise.resolve(entry) } + } + + private async loadSavedModeProfile( + mode: string, + cache: Map, + ): Promise { + if (cache.has(mode)) { + return cache.get(mode) + } + + let profile: SavedModeProfile | undefined + + // `getModeConfigId` lists the saved profiles and can reject. It shares the + // fallback below with the profile read: a rejection here used to escape the + // spawn loop, aborting children that were already running and denying the + // later spec its parent-configuration fallback (CR finding 3). + try { + const savedConfigId = await this.getModeConfigId(mode as Mode) + + if (savedConfigId) { + const { + name, + id: _id, + ...savedConfiguration + } = await this.providerSettingsManager.getProfile({ + id: savedConfigId, + }) + profile = { name, apiConfiguration: savedConfiguration } + } + } catch (error) { + this.log( + `[spawnBackgroundChildren] Saved profile lookup for mode '${mode}' failed: ${ + error instanceof Error ? error.message : String(error) + }. Using the parent task configuration.`, + ) + } + + cache.set(mode, profile) + return profile + } + + /** + * The lineage root for `parent`'s children: a live root object when one is + * reachable, plus the authoritative root id. + * + * The registry is consulted first, but it cannot be the only source: + * delegation pops every ancestor off the stack, so a delegated parent's + * root is usually absent from it (D-01). `Task` retains its `parentTask` + * reference after those pops (Task.ts constructor), so the chain walk is + * the production-reachable fallback. + * + * A task restored from History can carry `rootTaskId: R` with no live + * reference to `R` at all. Falling back to the parent object would make + * every descendant persist the parent as its root, so the stored id is + * returned on its own and carried through the explicit `rootTaskId` Task + * option (CR finding 5). + */ + private resolveLineageRoot(parent: Task): { rootTask?: Task; rootTaskId: string } { + const rootTaskId = parent.rootTaskId ?? parent.taskId + const registryRoot = this.taskRegistry.getById(rootTaskId) + + if (registryRoot) { + return { rootTask: registryRoot, rootTaskId } + } + + for (let ancestor: Task | undefined = parent; ancestor; ancestor = ancestor.parentTask) { + if (ancestor.taskId === rootTaskId) { + return { rootTask: ancestor, rootTaskId } + } + } + + if (rootTaskId !== parent.taskId) { + this.log( + `[resolveLineageRoot] Root task ${rootTaskId} is reachable from neither the registry nor the parent chain; carrying the stored root id into the child`, + ) + return { rootTaskId } + } + + return { rootTask: parent, rootTaskId } + } + + /** + * Persist both sides of the background-child registration: the parent's + * `childIds` (delete cascade, cost aggregation, diagnostics) and the + * child's `backgroundParentTaskId` stamp (startup orphan cleanup, D10/D11). + * + * The parent link must be durable before the child counts as registered: + * parent deletion follows `childIds`, so a stamped child missing from it + * keeps a permanent `active` row that no later child-side save repairs + * (CR finding axIR). The link therefore gets the same bounded retry as the + * terminal write; a link that still fails is recorded in + * `pendingBackgroundParentLinks` and retried at the next registration, + * child settlement, or task deletion. The child's own stamp stays + * best-effort, never fatal: an unregistered child can still run and + * report, and aborting the spawn would orphan running tasks. + */ + private async registerBackgroundChild( + parent: Task, + child: Task, + handoffExecutionContext: DelegatedChildContext, + ): Promise { + // Tracked per parent so deletion can drain only the registrations that + // can change its deletion set: a registration writes its own parent's + // `childIds`, so an unrelated parent's registration never affects it + // and must not stall it. Within a parent, a registration that lands + // mid-delete must either join the cascade or be declined by the closed + // admission gate, never orphan a live child of a deleted parent. + const registration = this.performBackgroundChildRegistration(parent, child, handoffExecutionContext) + let registrations = this.pendingBackgroundRegistrations.get(parent.taskId) + + if (!registrations) { + registrations = new Set() + this.pendingBackgroundRegistrations.set(parent.taskId, registrations) + } + + registrations.add(registration) + + try { + await registration + } finally { + registrations.delete(registration) + + if (registrations.size === 0) { + this.pendingBackgroundRegistrations.delete(parent.taskId) + } + } + } + + private async performBackgroundChildRegistration( + parent: Task, + child: Task, + handoffExecutionContext: DelegatedChildContext, + ): Promise { + await this.flushPendingBackgroundParentLinks() + await this.flushPendingBackgroundTerminalRepairs() + + const parentLinked = await this.addBackgroundChildToParentWithRetry(parent.taskId, child.taskId) + + if (!parentLinked) { + this.pendingBackgroundParentLinks.set(child.taskId, parent.taskId) + this.log( + `[spawnBackgroundChildren] Parent link for ${child.taskId} → ${parent.taskId} is pending repair; the child may outlive its parent's deletion until it lands`, + ) + } + + try { + await this.taskHistoryStore.upsert( + historyItemSchema.parse({ + id: child.taskId, + rootTaskId: child.rootTaskId, + parentTaskId: parent.taskId, + backgroundParentTaskId: parent.taskId, + number: child.taskNumber, + ts: Date.now(), + task: child.metadata.task ?? "", + tokensIn: 0, + tokensOut: 0, + totalCost: 0, + workspace: child.cwd, + mode: handoffExecutionContext.mode, + ...(handoffExecutionContext.apiConfigName + ? { apiConfigName: handoffExecutionContext.apiConfigName } + : {}), + status: "active", + }), + ) + } catch (error) { + this.log( + `[spawnBackgroundChildren] Failed to stamp ${child.taskId} with backgroundParentTaskId ${parent.taskId}: ${ + error instanceof Error ? error.message : String(error) + }`, + ) + } + } + + private async addBackgroundChildToParent(parentTaskId: string, childTaskId: string): Promise { + await this.taskHistoryStore.atomicReadAndUpdate(parentTaskId, (item) => addBackgroundChild(item, childTaskId)) + } + + /** + * Bounded-retry wrapper around the parent's `childIds` write, same idiom as + * `persistBackgroundChildTerminalWithRetry`: the realistic failure is a + * transient filesystem error (e.g. a Windows/OneDrive file lock on the + * history file), and a single rejected write would otherwise leave the + * child missing from the parent's `childIds` for the whole run. Returns + * `false` when every attempt failed; the caller records the link for a + * later repair pass. + */ + private async addBackgroundChildToParentWithRetry(parentTaskId: string, childTaskId: string): Promise { + const maxAttempts = 3 + + for (let attempt = 1; attempt <= maxAttempts; attempt++) { + try { + await this.addBackgroundChildToParent(parentTaskId, childTaskId) + return true + } catch (error) { + this.log( + `[spawnBackgroundChildren] Registering ${childTaskId} in parent ${parentTaskId} failed (attempt ${attempt}/${maxAttempts}): ${ + error instanceof Error ? error.message : String(error) + }`, + ) + + if (attempt < maxAttempts) { + await delay(50) + } + } + } + + return false + } + + /** + * Retry every background parent link whose registration write kept failing. + * Links that land are removed; the rest stay queued for the next pass. + * Deletion calls this before collecting `childIds` so a repaired link + * brings the child into the delete cascade. + */ + private async flushPendingBackgroundParentLinks(): Promise { + // Prototype-call doubles (delegation rollback tests) drive this method + // with a plain object that carries no pending-link map; nothing can be + // pending there, so there is nothing to flush. Same guard shape as + // stopBackgroundChildrenBeingDeleted. + const pending: Map | undefined = this.pendingBackgroundParentLinks + + if (!pending || pending.size === 0) { + return + } + + for (const [childTaskId, parentTaskId] of Array.from(pending)) { + if (await this.addBackgroundChildToParentWithRetry(parentTaskId, childTaskId)) { + pending.delete(childTaskId) + } + } + } + + /** + * Drain the in-flight background-child registrations of `parentIds` (parent + * `childIds` link + child row). Deletion calls this after closing admission + * for an id and before reading that id's `childIds`, so a registration that + * is mid-write either lands in time to join the cascade or was already + * declined by the admission gate. Registrations belonging to parents + * outside `parentIds` are not awaited: none of their children can enter + * this deletion set, so waiting for them would only stall the delete. + * Prototype-call doubles carry no registration map, so the read is + * undefined-tolerant like the other background guards. + */ + private async drainPendingBackgroundRegistrationsFor(parentIds: readonly string[]): Promise { + const pending: Map>> | undefined = this.pendingBackgroundRegistrations + + if (!pending || pending.size === 0) { + return + } + + const drained: Promise[] = [] + + for (const parentId of parentIds) { + const registrations = pending.get(parentId) + + if (registrations) { + drained.push(...registrations) + } + } + + if (drained.length === 0) { + return + } + + await Promise.allSettled(drained) + } + + /** Observe the parent's own abort so a cancel that bypasses `cancelTask` still cascades. */ + private ensureBackgroundAbortHook(parent: Task): void { + if (this.backgroundAbortHooks.has(parent.taskId)) { + return + } + + const listener = () => { + // A spawn loop awaiting `createTask`/registration reads this epoch + // after the await: its child has no record yet, so the cascade below + // cannot settle it (CR finding 1). + this.backgroundSpawnEpochs.set(parent, this.backgroundSpawnEpoch(parent) + 1) + void this.abortBackgroundChildren(parent.taskId).catch((error) => { + this.log( + `[spawnBackgroundChildren] Abort cascade for ${parent.taskId} failed: ${ + error instanceof Error ? error.message : String(error) + }`, + ) + }) + } + + parent.once(RooCodeEventName.TaskAborted, listener) + this.backgroundAbortHooks.set(parent.taskId, { parent, listener }) + } + + private releaseBackgroundAbortHookIfIdle(parentTaskId: string): void { + const hook = this.backgroundAbortHooks.get(parentTaskId) + + if (!hook) { + return + } + + for (const record of this.backgroundTasks.values()) { + if (record.parentTaskId === parentTaskId) { + return + } + } + + this.backgroundAbortHooks.delete(parentTaskId) + hook.parent.off(RooCodeEventName.TaskAborted, hook.listener) + } + + private releaseAllBackgroundAbortHooks(): void { + for (const hook of this.backgroundAbortHooks.values()) { + hook.parent.off(RooCodeEventName.TaskAborted, hook.listener) + } + + this.backgroundAbortHooks.clear() + } + + // Clear the current task without treating it as a subtask. + // This is used when the user cancels a task that is not a subtask. + public async clearTask(): Promise { + const task = this.taskRegistry.current + if (task) { + console.log(`[clearTask] clearing task ${task.taskId}.${task.instanceId}`) + await this.removeClineFromStack() + } + } + + public resumeTask(taskId: string): void { + // Use the existing showTaskWithId method which handles both current and + // historical tasks. + this.showTaskWithId(taskId).catch((error) => { + this.log(`Failed to resume task ${taskId}: ${error.message}`) + }) + } + + // Modes + + public async getModes(): Promise<{ slug: string; name: string }[]> { + try { + const customModes = await this.customModesManager.getCustomModes() + return [...DEFAULT_MODES, ...customModes].map(({ slug, name }) => ({ slug, name })) + } catch { + return DEFAULT_MODES.map(({ slug, name }) => ({ slug, name })) + } + } + + public async getMode(): Promise { + const { mode } = await this.getState() + return mode + } + + public async setMode(mode: string): Promise { + await this.setValues({ mode }) + } + + // Provider Profiles + + public async getProviderProfiles(): Promise<{ name: string; provider?: string }[]> { + const { listApiConfigMeta = [] } = await this.getState() + return listApiConfigMeta.map((profile) => ({ name: profile.name, provider: profile.apiProvider })) + } + + public async getProviderProfile(): Promise { + const { currentApiConfigName = "default" } = await this.getState() + return currentApiConfigName + } + + public async setProviderProfile(name: string): Promise { + await this.activateProviderProfile({ name }) + } + + // Telemetry + + private _appProperties?: StaticAppProperties + private _gitProperties?: GitProperties + + private getAppProperties(): StaticAppProperties { + if (!this._appProperties) { + const packageJSON = this.context.extension?.packageJSON + + this._appProperties = { + appName: packageJSON?.name ?? Package.name, + appVersion: packageJSON?.version ?? Package.version, + releaseChannel: Package.releaseChannel, + vscodeVersion: vscode.version, + platform: process.platform, + editorName: vscode.env.appName, + } + } + + return this._appProperties + } + + public get appProperties(): StaticAppProperties { + return this._appProperties ?? this.getAppProperties() + } + + private getCloudProperties(): CloudAppProperties { + let cloudIsAuthenticated: boolean | undefined + + try { + if (CloudService.hasInstance()) { + cloudIsAuthenticated = CloudService.instance.isAuthenticated() + } + } catch (error) { + // Silently handle errors to avoid breaking telemetry collection. + this.log(`[getTelemetryProperties] Failed to get cloud auth state: ${error}`) + } + + return { + cloudIsAuthenticated, + } + } + + private async getTaskProperties(): Promise { + const { language = "en", mode, apiConfiguration } = await this.getState() + + const task = this.getCurrentTask() + const todoList = task?.todoList + let todos: { total: number; completed: number; inProgress: number; pending: number } | undefined + + if (todoList && todoList.length > 0) { + todos = { + total: todoList.length, + completed: todoList.filter((todo) => todo.status === "completed").length, + inProgress: todoList.filter((todo) => todo.status === "in_progress").length, + pending: todoList.filter((todo) => todo.status === "pending").length, + } + } + + const apiProvider = apiConfiguration?.apiProvider + + return { + language, + mode, + taskId: task?.taskId, + parentTaskId: task?.parentTaskId, + apiProvider: apiProvider && !isRetiredProvider(apiProvider) ? apiProvider : undefined, + modelId: task?.api?.getModel().id, + diffStrategy: task?.diffStrategy?.getName(), + isSubtask: task ? !!task.parentTaskId : undefined, + ...(todos && { todos }), + } + } + + private async getGitProperties(): Promise { + if (!this._gitProperties) { + this._gitProperties = await getWorkspaceGitInfo() + } + + return this._gitProperties + } + + public get gitProperties(): GitProperties | undefined { + return this._gitProperties + } + + public async getTelemetryProperties(): Promise { + return { + ...this.getAppProperties(), + ...this.getCloudProperties(), + ...(await this.getTaskProperties()), + ...(await this.getGitProperties()), + } + } + + /** Workspace explicitly associated with this provider, without an active-editor fallback. */ + public get workspacePath(): string | undefined { + return this.currentWorkspacePath + } + + public get cwd() { + return this.currentWorkspacePath || getWorkspacePath() + } + + /** + * Delegate parent task and open child task. + * + * - Enforce single-open invariant + * - Persist parent delegation metadata + * - Emit TaskDelegated (task-level; API forwards to provider/bridge) + * - Create child as sole active and switch mode to child's mode + */ + public async delegateParentAndOpenChild(params: { + parentTaskId: string + message: string + initialTodos: TodoItem[] + mode: string pendingActionId?: string }): Promise { return runDelegationTransition(ClineProvider.delegationTransitionLocks, params.parentTaskId, () => @@ -4867,9 +6318,14 @@ export class ClineProvider mode !== parentMode && this.context.workspaceState.get("lockApiConfigAcrossModes", false) let savedModeProfile: { name?: string; apiConfiguration: ProviderSettings } | undefined if (mode !== parentMode && !lockApiConfigAcrossModes) { - const savedConfigId = await this.getModeConfigId(mode as Mode) - if (savedConfigId) { - try { + // The mode-config id lookup lists the saved profiles and can reject; + // it shares this fallback with the profile read so a failing lookup + // degrades to the parent configuration instead of failing the + // delegation (same contract as loadSavedModeProfile). + let savedConfigId: string | undefined + try { + savedConfigId = await this.getModeConfigId(mode as Mode) + if (savedConfigId) { const { name, id: _id, @@ -4878,11 +6334,12 @@ export class ClineProvider id: savedConfigId, }) savedModeProfile = { name, apiConfiguration: savedConfiguration } - } catch (error) { - this.log( - `[delegateParentAndOpenChild] Saved profile ${savedConfigId} for mode '${mode}' could not be loaded for parent ${parentTaskId}: ${error instanceof Error ? error.message : String(error)}. Using the parent task configuration.`, - ) } + } catch (error) { + const profileLabel = savedConfigId ? `Saved profile ${savedConfigId}` : "Saved profile lookup" + this.log( + `[delegateParentAndOpenChild] ${profileLabel} for mode '${mode}' could not be loaded for parent ${parentTaskId}: ${error instanceof Error ? error.message : String(error)}. Using the parent task configuration.`, + ) } } const handoffExecutionContext = selectHandoffExecutionContext( @@ -4926,6 +6383,22 @@ export class ClineProvider ) } + // Capture the lineage root before the parent leaves the stack: `createTask` + // otherwise derives `rootTask` from `taskRegistry.getAll()[0]`, which is + // empty by the time the child is constructed, so a delegated child would + // persist `rootTaskId: undefined` and sever the lineage root of every + // background child it later parents (D-01). + // Prototype-call idiom (same as createTaskWithHistoryItemUnlocked at the + // enqueueHistoryTaskTransition call sites): delegation is driven through + // `ClineProvider.prototype.delegateParentAndOpenChild*.call(this, ...)` + // with test doubles as `this`, so a sibling method must be reached through + // the prototype rather than through the double, which does not carry it. + const lineageRoot = ClineProvider.prototype.resolveLineageRoot.call< + ClineProvider, + [Task], + { rootTask?: Task; rootTaskId: string } + >(this, parent) + // 3) Enforce single-open invariant by closing/disposing the parent first // This ensures we never have >1 tasks open at any time during delegation. // Await abort completion to ensure clean disposal and prevent unhandled rejections. @@ -4958,6 +6431,10 @@ export class ClineProvider initialStatus: "active", startTask: false, handoffExecutionContext, + rootTask: lineageRoot.rootTask, + // Only an id without a live root object needs the explicit option; a + // live root keeps the original derivation (CR finding 5). + ...(lineageRoot.rootTask ? {} : { rootTaskId: lineageRoot.rootTaskId }), }) // 5) Persist parent delegation metadata BEFORE the child starts writing. diff --git a/src/core/webview/__tests__/ClineProvider.backgroundSpawnCancellation.spec.ts b/src/core/webview/__tests__/ClineProvider.backgroundSpawnCancellation.spec.ts new file mode 100644 index 0000000000..06abc2e418 --- /dev/null +++ b/src/core/webview/__tests__/ClineProvider.backgroundSpawnCancellation.spec.ts @@ -0,0 +1,1463 @@ +// pnpm --dir src exec vitest run core/webview/__tests__/ClineProvider.backgroundSpawnCancellation.spec.ts + +import EventEmitter from "events" + +import { WebviewFocusTracker } from "../WebviewFocusTracker" +import * as vscode from "vscode" +import type { HistoryItem, ProviderSettings } from "@roo-code/types" +import { ORGANIZATION_ALLOW_ALL, providerIdentifiers, RooCodeEventName } from "@roo-code/types" + +import { ContextProxy } from "../../config/ContextProxy" +import { TaskRegistry } from "../../task/TaskRegistry" +import { Task } from "../../task/Task" +import { ProfileValidator } from "../../../shared/ProfileValidator" +import type { BackgroundChildHandle, BackgroundSubtaskSpec } from "../../background-subtasks/types" +import { ClineProvider } from "../ClineProvider" + +const apiConfig: ProviderSettings = { + apiProvider: providerIdentifiers.anthropic, + apiKey: "test-key", +} + +/** + * Shared state for the mocked `Task` constructor: every created child is + * pushed here so a test can assert on the options the provider passed. + */ +const taskState = vi.hoisted(() => ({ created: [] as unknown[] })) + +interface MockTaskConstructorOptions { + taskId?: string + task?: string + parentTask?: { taskId: string } + rootTask?: { taskId: string } + /** Explicit authoritative root id for a child whose root object is gone. */ + rootTaskId?: string + taskNumber?: number + apiConfiguration?: unknown + handoffExecutionContext?: { + mode: string + apiConfigName?: string + apiConfiguration: ProviderSettings + } + backgroundToolPolicy?: { disabledTools?: readonly string[]; experiments?: Record } + backgroundChildHosted?: boolean + historyItem?: { id: string; rootTaskId?: string; parentTaskId?: string; number?: number } +} + +/** + * Tracks child task loop concurrency. `block()` makes every `run()` wait on a + * shared gate so the scheduler cap can be observed; `releaseAll()` frees them. + */ +const runTracker = vi.hoisted(() => { + const state = { active: 0, maxActive: 0, started: 0 } + let gate: Promise = Promise.resolve() + let release: (() => void) | undefined + let rejection: Error | undefined + + return { + state, + reset() { + state.active = 0 + state.maxActive = 0 + state.started = 0 + gate = Promise.resolve() + release = undefined + rejection = undefined + }, + block() { + gate = new Promise((resolve) => { + release = resolve + }) + }, + releaseAll() { + release?.() + release = undefined + }, + /** Makes the next `run()` reject the way a failed child loop does. */ + failNext(message: string) { + rejection = new Error(message) + }, + async run() { + state.started += 1 + state.active += 1 + state.maxActive = Math.max(state.maxActive, state.active) + await gate + state.active -= 1 + if (rejection) { + const error = rejection + rejection = undefined + throw error + } + }, + } +}) + +/** + * In-memory stand-in for `TaskHistoryStore` so the provider's registration + * writes are observable. + */ +const storeState = vi.hoisted(() => ({ + items: new Map(), +})) + +vi.mock("vscode", () => { + const mockDisposable = { dispose: vi.fn() } + return { + workspace: { + getConfiguration: vi.fn(() => ({ + get: vi.fn().mockReturnValue([]), + update: vi.fn().mockResolvedValue(undefined), + })), + workspaceFolders: [], + onDidChangeConfiguration: vi.fn(() => mockDisposable), + }, + env: { + uriScheme: "vscode", + language: "en", + }, + EventEmitter: vi.fn().mockImplementation(function () { + return { + event: vi.fn(), + fire: vi.fn(), + } + }), + Disposable: { + from: vi.fn(), + }, + window: { + showErrorMessage: vi.fn(), + showInformationMessage: vi.fn(), + showWarningMessage: vi.fn(), + createTextEditorDecorationType: vi.fn().mockReturnValue({ dispose: vi.fn() }), + onDidChangeActiveTextEditor: vi.fn(() => mockDisposable), + }, + Uri: { + file: vi.fn().mockReturnValue({ toString: () => "file://test" }), + joinPath: vi.fn(), + }, + commands: { + executeCommand: vi.fn().mockResolvedValue(undefined), + }, + ExtensionMode: { + Production: 1, + Development: 2, + Test: 3, + }, + version: "1.85.0", + } +}) + +// The fake child mirrors the constructor derivations the provider relies on: +// parentTaskId from `parentTask`, rootTaskId from an explicit `rootTaskId`, a +// `historyItem`, or `rootTask` (in that order). It deliberately does not call +// `onCreated`; no assertion depends on provider listeners being wired for a +// child in these tests. +vi.mock("../../task/Task", () => { + class MockTask { + taskId: string + instanceId = "mock-instance" + rootTaskId?: string + parentTaskId?: string + taskNumber: number + metadata: { task?: string } + cwd = "/test/workspace" + workspacePath = "/test/workspace" + apiConfiguration: unknown + handoffExecutionContext?: MockTaskConstructorOptions["handoffExecutionContext"] + backgroundToolPolicy?: { disabledTools?: readonly string[]; experiments?: Record } + isBackgroundSubtaskChild: boolean + abort = false + abandoned = false + // EventEmitter gives once() real Node semantics — the listener is + // removed before it runs — matching Task's production emitter. + private readonly emitter = new EventEmitter() + emit = vi.fn((event: string, ...args: unknown[]) => { + this.emitter.emit(event, ...args) + }) + on = vi.fn((event: string, listener: (...args: unknown[]) => void) => { + this.emitter.on(event, listener) + }) + once = vi.fn((event: string, listener: (...args: unknown[]) => void) => { + this.emitter.once(event, listener) + }) + off = vi.fn((event: string, listener: (...args: unknown[]) => void) => { + this.emitter.off(event, listener) + }) + dispose = vi.fn().mockResolvedValue(undefined) + abortTask = vi.fn(async () => { + this.emit(RooCodeEventName.TaskAborted) + }) + run = vi.fn(() => runTracker.run()) + getTaskMode = vi.fn(async () => "code") + getTaskApiConfigName = vi.fn(async () => undefined) + + constructor(options: MockTaskConstructorOptions) { + this.taskId = options.historyItem?.id ?? options.taskId ?? `mock-task-${taskState.created.length + 1}` + this.rootTaskId = + options.rootTaskId ?? (options.historyItem ? options.historyItem.rootTaskId : options.rootTask?.taskId) + this.parentTaskId = options.historyItem ? options.historyItem.parentTaskId : options.parentTask?.taskId + this.taskNumber = options.taskNumber ?? options.historyItem?.number ?? -1 + this.metadata = { task: options.task } + this.apiConfiguration = options.apiConfiguration + this.handoffExecutionContext = options.handoffExecutionContext + this.backgroundToolPolicy = options.backgroundToolPolicy + this.isBackgroundSubtaskChild = options.backgroundChildHosted === true + taskState.created.push(this) + } + } + + return { + Task: MockTask, + PendingActionSettlementError: class PendingActionSettlementError extends Error {}, + } +}) + +vi.mock("../../../services/mcp/McpServerManager", () => ({ + McpServerManager: { + getInstance: vi.fn().mockResolvedValue({ + registerClient: vi.fn(), + unregisterClient: vi.fn(), + }), + unregisterProvider: vi.fn(), + }, +})) + +vi.mock("../../../integrations/workspace/WorkspaceTracker", () => ({ + default: vi.fn().mockImplementation(function () { + return { + initializeFilePaths: vi.fn(), + dispose: vi.fn(), + } + }), +})) + +vi.mock("../../../utils/path", async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + getWorkspacePath: vi.fn().mockReturnValue("/test/workspace"), + } +}) + +vi.mock("@roo-code/telemetry", () => ({ + TelemetryService: { + instance: { + setProvider: vi.fn(), + captureTaskCreated: vi.fn(), + captureTaskRestarted: vi.fn(), + captureTaskCompleted: vi.fn(), + }, + }, +})) + +vi.mock("@roo-code/cloud", () => ({ + CloudService: { + hasInstance: vi.fn().mockReturnValue(false), + instance: { + isAuthenticated: vi.fn().mockReturnValue(false), + }, + }, + getRooCodeApiUrl: vi.fn().mockReturnValue("https://api.roo-code.com"), +})) + +vi.mock("../../../shared/embeddingModels", () => ({ + EMBEDDING_MODEL_PROFILES: [], +})) + +// Keep the real mode table so an unknown slug really is unknown. +vi.mock("../../../shared/modes", async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + getModeBySlug: vi.fn(actual.getModeBySlug), + } +}) + +vi.mock("p-wait-for", () => ({ + __esModule: true, + default: vi.fn().mockResolvedValue(undefined), +})) + +vi.mock("fs/promises", () => ({ + mkdir: vi.fn().mockResolvedValue(undefined), + writeFile: vi.fn().mockResolvedValue(undefined), + readFile: vi.fn().mockResolvedValue(""), + readdir: vi.fn().mockResolvedValue([]), + unlink: vi.fn().mockResolvedValue(undefined), + rmdir: vi.fn().mockResolvedValue(undefined), + access: vi.fn().mockResolvedValue(undefined), + rm: vi.fn().mockResolvedValue(undefined), +})) + +vi.mock("axios", () => ({ + default: { get: vi.fn().mockResolvedValue({ data: { data: [] } }), post: vi.fn() }, + get: vi.fn().mockResolvedValue({ data: { data: [] } }), + post: vi.fn(), +})) + +vi.mock("delay", () => { + const delayFn = (_ms: number) => Promise.resolve() + delayFn.createDelay = () => delayFn + delayFn.reject = () => Promise.reject(new Error("Delay rejected")) + delayFn.range = () => Promise.resolve() + return { default: delayFn } +}) + +vi.mock("../../../utils/storage", () => ({ + getSettingsDirectoryPath: vi.fn().mockResolvedValue("/test/settings/path"), + getTaskDirectoryPath: vi.fn().mockResolvedValue("/test/task/path"), + getGlobalStoragePath: vi.fn().mockResolvedValue("/test/storage/path"), + getStorageBasePath: vi.fn().mockImplementation((defaultPath: string) => defaultPath), +})) + +vi.mock("../../../utils/safeWriteJson", () => ({ + safeWriteJson: vi.fn().mockResolvedValue(undefined), +})) + +vi.mock("../../../utils/tts", () => ({ + setTtsEnabled: vi.fn(), + setTtsSpeed: vi.fn(), +})) + +vi.mock("../../../api", () => ({ + buildApiHandler: vi.fn().mockReturnValue({ + getModel: vi.fn().mockReturnValue({ id: "claude-3-sonnet" }), + }), +})) + +vi.mock("../../prompts/system", () => ({ + SYSTEM_PROMPT: vi.fn().mockImplementation(async () => "mocked system prompt"), + codeMode: "code", +})) + +vi.mock("../../prompts/sections/custom-instructions") + +vi.mock("../../../api/providers/fetchers/modelCache", () => ({ + getModels: vi.fn().mockResolvedValue({}), + flushModels: vi.fn(), + getModelsFromCache: vi.fn().mockReturnValue(undefined), +})) + +vi.mock("../../../integrations/misc/extract-text", () => ({ + extractTextFromFile: vi.fn().mockResolvedValue("file content"), +})) + +vi.mock("../diff/strategies/multi-search-replace", () => ({ + MultiSearchReplaceDiffStrategy: vi.fn().mockImplementation(function () { + return { getName: () => "test-strategy", applyDiff: vi.fn() } + }), +})) + +vi.mock("@modelcontextprotocol/sdk/types.js", () => ({ + CallToolResultSchema: {}, + ListResourcesResultSchema: {}, + ListResourceTemplatesResultSchema: {}, + ListToolsResultSchema: {}, + ReadResourceResultSchema: {}, + ErrorCode: { InvalidRequest: "InvalidRequest", MethodNotFound: "MethodNotFound", InternalError: "InternalError" }, + McpError: class McpError extends Error { + code: string + constructor(code: string, message: string) { + super(message) + this.code = code + this.name = "McpError" + } + }, +})) + +vi.mock("@modelcontextprotocol/sdk/client/index.js", () => ({ + Client: vi.fn().mockImplementation(function () { + return { + connect: vi.fn().mockResolvedValue(undefined), + close: vi.fn().mockResolvedValue(undefined), + listTools: vi.fn().mockResolvedValue({ tools: [] }), + callTool: vi.fn().mockResolvedValue({ content: [] }), + } + }), +})) + +vi.mock("@modelcontextprotocol/sdk/client/stdio.js", () => ({ + StdioClientTransport: vi.fn().mockImplementation(function () { + return { connect: vi.fn().mockResolvedValue(undefined), close: vi.fn().mockResolvedValue(undefined) } + }), +})) + +vi.mock("../../../services/skills/SkillsManager", () => ({ + SkillsManager: vi.fn().mockImplementation(function () { + return { + initialize: vi.fn().mockResolvedValue(undefined), + dispose: vi.fn(), + } + }), +})) + +// Keep the real lifecycle reducers (`addBackgroundChild`) and replace only the +// store, so the provider's registration writes land in the in-memory map. +vi.mock("../../task-persistence", async (importOriginal) => { + const actual = await importOriginal() + + const makeStore = () => ({ + initialize: vi.fn().mockResolvedValue(undefined), + initialized: Promise.resolve(), + dispose: vi.fn(), + get: vi.fn((taskId: string) => storeState.items.get(taskId)), + getAll: vi.fn(() => Array.from(storeState.items.values())), + upsert: vi.fn(async (item: HistoryItem) => { + const existing = storeState.items.get(item.id) + storeState.items.set(item.id, existing ? { ...existing, ...item } : item) + return Array.from(storeState.items.values()) + }), + atomicReadAndUpdate: vi.fn(async (taskId: string, update: (item: HistoryItem) => HistoryItem) => { + const current = storeState.items.get(taskId) + if (!current) { + throw new Error(`[mock TaskHistoryStore] task ${taskId} not found`) + } + const updated = update(current) + storeState.items.set(taskId, updated) + return Array.from(storeState.items.values()) + }), + delete: vi.fn().mockResolvedValue(undefined), + deleteMany: vi.fn().mockResolvedValue(undefined), + migrateFromGlobalState: vi.fn().mockResolvedValue(undefined), + invalidate: vi.fn().mockResolvedValue(undefined), + invalidateAll: vi.fn(), + setAutoTitleIfAbsent: vi.fn().mockResolvedValue({ applied: false }), + }) + + return { + ...actual, + TaskHistoryStore: vi.fn().mockImplementation(function (_path: string, _options?: unknown) { + return makeStore() + }), + saveTaskMessages: vi.fn().mockResolvedValue(undefined), + readApiMessages: vi.fn().mockResolvedValue([]), + saveApiMessages: vi.fn().mockResolvedValue(undefined), + } +}) + +interface MockTaskInstance { + taskId: string + rootTaskId?: string + parentTaskId?: string + taskNumber: number + isBackgroundSubtaskChild: boolean + handoffExecutionContext?: MockTaskConstructorOptions["handoffExecutionContext"] + backgroundToolPolicy?: { disabledTools?: readonly string[]; experiments?: Record } + run: ReturnType + abortTask: ReturnType + dispose: ReturnType + emit: ReturnType + once: ReturnType + off: ReturnType +} + +function createdTasks(): MockTaskInstance[] { + return taskState.created as MockTaskInstance[] +} + +/** + * Minimal stand-in for the members `spawnBackgroundChildren` reads from a parent + * task: identity, lineage, mode/profile accessors, the synchronous `abort` + * flag (`abortTask()` flips it synchronously on the real Task), and the + * TaskAborted emitter. + */ +class FakeParentTask { + // EventEmitter gives once() real Node semantics — the listener is removed + // before it runs — so abort-hook tests can tell when the provider retains + // a hook record after the once has already been consumed. + private readonly emitter = new EventEmitter() + readonly instanceId = "parent-instance" + readonly apiConfiguration: ProviderSettings = apiConfig + // Mirrors Task's synchronous abort flag (ClineProvider reads it in + // `isBackgroundSpawnParentActive`), so a pre-cancelled parent can be + // simulated without emitting the event. + abort = false + dispose = vi.fn().mockResolvedValue(undefined) + abortTask = vi.fn(async () => { + this.abort = true + this.emit(RooCodeEventName.TaskAborted) + }) + flushPendingToolResultsToHistory = vi.fn().mockResolvedValue(true) + + constructor( + readonly taskId: string, + readonly rootTaskId?: string, + // `Task` retains this reference after the stack pops that delegation + // performs; every production lineage walk relies on it. + readonly parentTask?: FakeParentTask, + ) {} + + async getTaskMode(): Promise { + return "code" + } + + async getTaskApiConfigName(): Promise { + return "default-profile" + } + + once(event: string, listener: (...args: unknown[]) => void): void { + this.emitter.once(event, listener) + } + + on(event: string, listener: (...args: unknown[]) => void): void { + this.emitter.on(event, listener) + } + + off(event: string, listener: (...args: unknown[]) => void): void { + this.emitter.off(event, listener) + } + + emit(event: string): void { + this.emitter.emit(event) + } + + listenerCount(event: string): number { + return this.emitter.listenerCount(event) + } +} + +// The double implements TaskIdentity/lineage/mode accessors and an event emitter; +// no other Task surface is reachable from spawnBackgroundChildren. +function asTask(parent: FakeParentTask): Task { + return parent as unknown as Task +} + +function seedRegistry(provider: ClineProvider, ...tasks: FakeParentTask[]): void { + const registry = new TaskRegistry() + for (const task of tasks) { + registry.push(asTask(task)) + } + provider["taskRegistry"] = registry +} + +function seedParentRecord(taskId: string, overrides: Partial = {}): HistoryItem { + const item: HistoryItem = { + id: taskId, + number: 1, + ts: 1, + task: "Parent task", + tokensIn: 0, + tokensOut: 0, + totalCost: 0, + status: "active", + childIds: [], + ...overrides, + } + storeState.items.set(taskId, item) + return item +} + +const flush = async (ticks = 6): Promise => { + for (let index = 0; index < ticks; index++) { + await new Promise((resolve) => setTimeout(resolve, 0)) + } +} + +function makeSpec(label: string, mode = "code"): BackgroundSubtaskSpec { + return { label, mode, message: `Investigate ${label}` } +} + +async function spawn( + provider: ClineProvider, + parent: FakeParentTask, + specs: BackgroundSubtaskSpec[], +): Promise<{ children: BackgroundChildHandle[]; started: boolean }> { + return provider.spawnBackgroundChildren(asTask(parent), specs) +} + +describe("ClineProvider background spawn admission gate (CR finding 1 residual)", () => { + let provider: ClineProvider + let mockContext: vscode.ExtensionContext + let mockOutputChannel: vscode.OutputChannel + + beforeEach(() => { + vi.clearAllMocks() + taskState.created.length = 0 + runTracker.reset() + storeState.items.clear() + + vi.spyOn(ProfileValidator, "isProfileAllowed").mockReturnValue(true) + + mockContext = { + globalState: { + get: vi.fn().mockReturnValue(undefined), + update: vi.fn().mockResolvedValue(undefined), + keys: vi.fn().mockReturnValue([]), + }, + globalStorageUri: { fsPath: "/test/storage" }, + secrets: { + get: vi.fn().mockResolvedValue(undefined), + store: vi.fn().mockResolvedValue(undefined), + delete: vi.fn().mockResolvedValue(undefined), + }, + workspaceState: { + get: vi.fn().mockReturnValue(undefined), + update: vi.fn().mockResolvedValue(undefined), + keys: vi.fn().mockReturnValue([]), + }, + extensionUri: { fsPath: "/test/extension" }, + extension: { packageJSON: { version: "1.0.0" } }, + subscriptions: [], + } as unknown as vscode.ExtensionContext + + mockOutputChannel = { + appendLine: vi.fn(), + dispose: vi.fn(), + } as unknown as vscode.OutputChannel + + const mockContextProxy = { + getValues: vi.fn().mockReturnValue({}), + getValue: vi.fn().mockReturnValue(undefined), + setValue: vi.fn().mockResolvedValue(undefined), + setValues: vi.fn().mockResolvedValue(undefined), + getProviderSettings: vi.fn().mockReturnValue(apiConfig), + extensionUri: mockContext.extensionUri, + globalStorageUri: mockContext.globalStorageUri, + } + + provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + mockContextProxy as unknown as ContextProxy, + new WebviewFocusTracker(), + ) + + provider.getState = vi.fn().mockResolvedValue({ + apiConfiguration: apiConfig, + customModes: [], + organizationAllowList: ORGANIZATION_ALLOW_ALL, + // `addClineToStack` refuses to finish without a mode. + mode: "code", + }) + provider["getModeConfigId"] = vi.fn().mockResolvedValue(undefined) + }) + + afterEach(async () => { + runTracker.releaseAll() + await provider.dispose() + vi.restoreAllMocks() + }) + + it("admits no construction work when the parent is already cancelled", async () => { + const parent = new FakeParentTask("parent-1") + seedRegistry(provider, parent) + seedParentRecord("parent-1") + // `abortTask()` flips this synchronously on the real Task, so a spawn + // that starts after the cancellation observes it before any work. + parent.abort = true + + const result = await spawn(provider, parent, [makeSpec("a"), makeSpec("b"), makeSpec("c")]) + + // The pre-admission gate must stop every spec from being constructed: + // no task, no run, no published record. + expect(createdTasks()).toHaveLength(0) + expect(runTracker.state.started).toBe(0) + expect(provider["backgroundTasks"].size).toBe(0) + expect(result.started).toBe(false) + + // Callers receive exactly one settleable handle per requested spec. + expect(result.children).toHaveLength(3) + const entries = await Promise.all(result.children.map((child) => child.done)) + expect(entries.map((entry) => entry.status)).toEqual(["aborted", "aborted", "aborted"]) + expect(entries.every((entry) => entry.error === "Parent task was cancelled")).toBe(true) + + // The synthetic ids never reach persistence: `cancelledBackgroundHandle` + // writes no history row, and the store still holds only the seeded + // parent record. Locks the "writes nothing" contract. + expect(storeState.items.size).toBe(1) + for (const entry of entries) { + expect(storeState.items.get(entry.taskId)).toBeUndefined() + } + }) + + it("admits no construction work after the provider was disposed", async () => { + const parent = new FakeParentTask("parent-1") + seedRegistry(provider, parent) + seedParentRecord("parent-1") + + await provider.dispose() + + const result = await spawn(provider, parent, [makeSpec("a"), makeSpec("b")]) + + expect(createdTasks()).toHaveLength(0) + expect(runTracker.state.started).toBe(0) + expect(provider["backgroundTasks"].size).toBe(0) + expect(result.started).toBe(false) + + expect(result.children).toHaveLength(2) + const entries = await Promise.all(result.children.map((child) => child.done)) + expect(entries.map((entry) => entry.status)).toEqual(["aborted", "aborted"]) + expect(entries.every((entry) => entry.error === "Provider disposed")).toBe(true) + }) + + it("does not construct the specs queued behind a parent cancelled mid-batch", async () => { + const parent = new FakeParentTask("parent-1") + seedRegistry(provider, parent) + seedParentRecord("parent-1") + + // Park the FIRST spec's `createTask`; cancel the parent while it is + // in flight, then release it. + const originalCreateTask = provider.createTask.bind(provider) + let releaseCreate!: () => void + const createGate = new Promise((resolve) => { + releaseCreate = resolve + }) + let enteredCreate!: () => void + const createEntered = new Promise((resolve) => { + enteredCreate = resolve + }) + + provider.createTask = vi.fn(async (...args: Parameters) => { + enteredCreate() + await createGate + return originalCreateTask(...args) + }) + + const spawnPromise = spawn(provider, parent, [makeSpec("a"), makeSpec("b"), makeSpec("c")]) + await createEntered + parent.emit(RooCodeEventName.TaskAborted) + releaseCreate() + const result = await spawnPromise + + // Spec "a" was in flight when the cancellation landed: it was + // constructed, then settled and disposed without scheduling. + expect(createdTasks()).toHaveLength(1) + expect(createdTasks()[0].dispose).toHaveBeenCalled() + + // Specs "b" and "c" were never admitted: no construction at all, so + // there was also nothing to dispose for them. + expect(runTracker.state.started).toBe(0) + expect(provider["backgroundTasks"].size).toBe(0) + expect(result.started).toBe(false) + + // One handle per spec, all settled aborted. + expect(result.children).toHaveLength(3) + const entries = await Promise.all(result.children.map((child) => child.done)) + expect(entries.map((entry) => entry.status)).toEqual(["aborted", "aborted", "aborted"]) + expect(entries.every((entry) => entry.error === "Parent task was cancelled")).toBe(true) + // The unadmitted handles carry synthetic ids, not constructed task ids. + expect(entries.slice(1).map((entry) => entry.taskId)).not.toContain(createdTasks()[0].taskId) + }) + + it("retries the terminal write when cancelling during registration makes it fail (CR round 3)", async () => { + const parent = new FakeParentTask("parent-1") + seedRegistry(provider, parent) + seedParentRecord("parent-1") + + // Park the registration's parent write so the parent is cancelled while + // the child's history row is being registered: the post-registration + // parent check then settles the child without scheduling it. The first + // terminal write for the child then fails transiently — without the + // bounded retry the row would stay `active` forever, and startup + // reconciliation skips a child whose parent is still active/delegated. + const store = provider.taskHistoryStore + const originalReadAndUpdate = store.atomicReadAndUpdate.bind(store) + let releaseRegistration!: () => void + const registrationGate = new Promise((resolve) => { + releaseRegistration = resolve + }) + let enteredRegistration!: () => void + const registrationEntered = new Promise((resolve) => { + enteredRegistration = resolve + }) + let failFirstTerminalWrite = true + store.atomicReadAndUpdate = vi.fn(async (taskId: string, update: (item: HistoryItem) => HistoryItem) => { + if (taskId === "parent-1") { + enteredRegistration() + await registrationGate + } else if (failFirstTerminalWrite) { + failFirstTerminalWrite = false + throw new Error("transient store failure") + } + return originalReadAndUpdate(taskId, update) + }) + + const spawnPromise = spawn(provider, parent, [makeSpec("a")]) + await registrationEntered + await parent.abortTask() + releaseRegistration() + const result = await spawnPromise + + // The child was settled unscheduled, exactly like the mid-batch case. + expect(result.children).toHaveLength(1) + const [entry] = await Promise.all(result.children.map((child) => child.done)) + expect(entry.status).toBe("aborted") + expect(entry.error).toBe("Parent task was cancelled") + expect(runTracker.state.started).toBe(0) + expect(provider["backgroundTasks"].size).toBe(0) + const childId = createdTasks()[0].taskId + + // The transient failure must not strand the child on `active`: the + // bounded retry lands the terminal `interrupted` write. + await vi.waitFor( + () => { + expect(storeState.items.get(childId)?.status).toBe("interrupted") + }, + { timeout: 2000, interval: 10 }, + ) + const childWriteCalls = vi.mocked(store.atomicReadAndUpdate).mock.calls.filter(([id]) => id === childId) + expect(childWriteCalls.length).toBeGreaterThanOrEqual(2) + }) + + it("keeps the abort hook released when nothing was ever scheduled", async () => { + const parent = new FakeParentTask("parent-1") + seedRegistry(provider, parent) + seedParentRecord("parent-1") + parent.abort = true + + await spawn(provider, parent, [makeSpec("a")]) + + // The finally block must not leave a listener behind on the parent. + expect(parent.listenerCount(RooCodeEventName.TaskAborted)).toBe(0) + expect(provider["backgroundAbortHooks"].size).toBe(0) + }) +}) + +describe("ClineProvider mode-config id lookup fallback (CR finding 3)", () => { + let provider: ClineProvider + let mockContext: vscode.ExtensionContext + let mockOutputChannel: vscode.OutputChannel + + beforeEach(() => { + vi.clearAllMocks() + taskState.created.length = 0 + runTracker.reset() + storeState.items.clear() + + vi.spyOn(ProfileValidator, "isProfileAllowed").mockReturnValue(true) + + mockContext = { + globalState: { + get: vi.fn().mockReturnValue(undefined), + update: vi.fn().mockResolvedValue(undefined), + keys: vi.fn().mockReturnValue([]), + }, + globalStorageUri: { fsPath: "/test/storage" }, + secrets: { + get: vi.fn().mockResolvedValue(undefined), + store: vi.fn().mockResolvedValue(undefined), + delete: vi.fn().mockResolvedValue(undefined), + }, + workspaceState: { + get: vi.fn().mockReturnValue(undefined), + update: vi.fn().mockResolvedValue(undefined), + keys: vi.fn().mockReturnValue([]), + }, + extensionUri: { fsPath: "/test/extension" }, + extension: { packageJSON: { version: "1.0.0" } }, + subscriptions: [], + } as unknown as vscode.ExtensionContext + + mockOutputChannel = { + appendLine: vi.fn(), + dispose: vi.fn(), + } as unknown as vscode.OutputChannel + + const mockContextProxy = { + getValues: vi.fn().mockReturnValue({}), + getValue: vi.fn().mockReturnValue(undefined), + setValue: vi.fn().mockResolvedValue(undefined), + setValues: vi.fn().mockResolvedValue(undefined), + getProviderSettings: vi.fn().mockReturnValue(apiConfig), + extensionUri: mockContext.extensionUri, + globalStorageUri: mockContext.globalStorageUri, + } + + provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + mockContextProxy as unknown as ContextProxy, + new WebviewFocusTracker(), + ) + + provider.getState = vi.fn().mockResolvedValue({ + apiConfiguration: apiConfig, + customModes: [], + organizationAllowList: ORGANIZATION_ALLOW_ALL, + mode: "code", + }) + }) + + afterEach(async () => { + runTracker.releaseAll() + await provider.dispose() + vi.restoreAllMocks() + }) + + it("a rejecting mode-config lookup degrades to the parent configuration without exiting the batch", async () => { + const parent = new FakeParentTask("parent-1") + seedRegistry(provider, parent) + seedParentRecord("parent-1") + provider["getModeConfigId"] = vi.fn(async (mode: string) => { + if (mode === "architect") { + throw new Error("settings store unavailable") + } + return undefined + }) + + // `a` shares the parent's mode (no lookup); `b`/`c` use a mode whose + // saved-profile lookup rejects while `a` is already constructed. + const result = await spawn(provider, parent, [ + makeSpec("a", "code"), + makeSpec("b", "architect"), + makeSpec("c", "architect"), + ]) + + // The rejection must not escape the spawn loop: every spec is admitted, + // constructed, and scheduled. + expect(result.children).toHaveLength(3) + expect(createdTasks()).toHaveLength(3) + expect(result.started).toBe(true) + await flush() + expect(runTracker.state.started).toBe(3) + + // The failing lookup falls back to the parent task configuration. + for (const child of createdTasks().slice(1)) { + expect(child.handoffExecutionContext?.mode).toBe("architect") + expect(child.handoffExecutionContext?.apiConfigName).toBe("default-profile") + expect(child.handoffExecutionContext?.apiConfiguration).toEqual(apiConfig) + } + + const entries = await Promise.all(result.children.map((child) => child.done)) + expect(entries).toHaveLength(3) + expect(provider["backgroundTasks"].size).toBe(0) + }) +}) + +describe("ClineProvider background child deletion and parent-link durability (CR findings axIE/axIR/axHd)", () => { + let provider: ClineProvider + let mockContext: vscode.ExtensionContext + let mockOutputChannel: vscode.OutputChannel + + beforeEach(() => { + vi.clearAllMocks() + taskState.created.length = 0 + runTracker.reset() + storeState.items.clear() + + vi.spyOn(ProfileValidator, "isProfileAllowed").mockReturnValue(true) + + mockContext = { + globalState: { + get: vi.fn().mockReturnValue(undefined), + update: vi.fn().mockResolvedValue(undefined), + keys: vi.fn().mockReturnValue([]), + }, + globalStorageUri: { fsPath: "/test/storage" }, + secrets: { + get: vi.fn().mockResolvedValue(undefined), + store: vi.fn().mockResolvedValue(undefined), + delete: vi.fn().mockResolvedValue(undefined), + }, + workspaceState: { + get: vi.fn().mockReturnValue(undefined), + update: vi.fn().mockResolvedValue(undefined), + keys: vi.fn().mockReturnValue([]), + }, + extensionUri: { fsPath: "/test/extension" }, + extension: { packageJSON: { version: "1.0.0" } }, + subscriptions: [], + } as unknown as vscode.ExtensionContext + + mockOutputChannel = { + appendLine: vi.fn(), + dispose: vi.fn(), + } as unknown as vscode.OutputChannel + + const mockContextProxy = { + getValues: vi.fn().mockReturnValue({}), + getValue: vi.fn().mockReturnValue(undefined), + setValue: vi.fn().mockResolvedValue(undefined), + setValues: vi.fn().mockResolvedValue(undefined), + getProviderSettings: vi.fn().mockReturnValue(apiConfig), + extensionUri: mockContext.extensionUri, + globalStorageUri: mockContext.globalStorageUri, + } + + provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + mockContextProxy as unknown as ContextProxy, + new WebviewFocusTracker(), + ) + + provider.getState = vi.fn().mockResolvedValue({ + apiConfiguration: apiConfig, + customModes: [], + organizationAllowList: ORGANIZATION_ALLOW_ALL, + mode: "code", + }) + provider["getModeConfigId"] = vi.fn().mockResolvedValue(undefined) + }) + + afterEach(async () => { + runTracker.releaseAll() + await provider.dispose() + vi.restoreAllMocks() + }) + + it("has deletion await a child whose abort cascade cleanup is still pending (CR axIE)", async () => { + const parent = new FakeParentTask("parent-1") + seedRegistry(provider, parent) + seedParentRecord("parent-1") + + runTracker.block() + const result = await spawn(provider, parent, [makeSpec("a")]) + expect(result.started).toBe(true) + const childId = result.children[0].taskId + + // Park the child's abort and disposal the way a final message save and + // resource teardown do in production. + const child = createdTasks()[0] + let releaseAbort!: () => void + const abortGate = new Promise((resolve) => { + releaseAbort = resolve + }) + let abortEntered!: () => void + const abortEnteredPromise = new Promise((resolve) => { + abortEntered = resolve + }) + child.abortTask.mockImplementation(async () => { + abortEntered() + await abortGate + }) + let releaseDispose!: () => void + const disposeGate = new Promise((resolve) => { + releaseDispose = resolve + }) + child.dispose.mockImplementation(async () => { + await disposeGate + }) + + // The parent's abort cascade settles the record (removing it from + // `backgroundTasks`) and then parks inside `abortTask()`. + try { + const cascade = provider.abortBackgroundChildren("parent-1") + await abortEnteredPromise + expect(provider["backgroundTasks"].size).toBe(0) + + // Deletion reaches the lookup after the cascade removed the record: it + // must still wait for the pending abort AND disposal drain. + let deletionSettled = false + const deletion = provider["stopBackgroundChildrenBeingDeleted"]([childId]).then(() => { + deletionSettled = true + }) + await flush() + expect(deletionSettled).toBe(false) + + releaseAbort() + await flush() + expect(deletionSettled).toBe(false) + + releaseDispose() + await deletion + expect(deletionSettled).toBe(true) + await cascade + } finally { + // A failed assertion above must not leave these gates closed: afterEach + // awaits provider.dispose(), which waits on the same parked child + // cleanup. Promise resolves are idempotent, so the staged releases on + // the success path stay as-is. + releaseAbort() + releaseDispose() + } + }) + + it("does not let deletion wait for a selected child's unselected sibling (CR axIE)", async () => { + const parent = new FakeParentTask("parent-1") + seedRegistry(provider, parent) + seedParentRecord("parent-1") + + runTracker.block() + const result = await spawn(provider, parent, [makeSpec("a"), makeSpec("b")]) + expect(result.started).toBe(true) + const [selectedId, siblingId] = result.children.map((child) => child.taskId) + + const gates = new Map void; entered: Promise }>() + for (const task of createdTasks()) { + let release!: () => void + const gate = new Promise((resolve) => { + release = resolve + }) + let entered!: () => void + const enteredPromise = new Promise((resolve) => { + entered = resolve + }) + gates.set(task.taskId, { release, entered: enteredPromise }) + task.abortTask.mockImplementation(async () => { + entered() + await gate + }) + } + + try { + const cascade = provider.abortBackgroundChildren("parent-1") + await Promise.all([gates.get(selectedId)!.entered, gates.get(siblingId)!.entered]) + + let deletionSettled = false + const deletion = provider["stopBackgroundChildrenBeingDeleted"]([selectedId]).then(() => { + deletionSettled = true + }) + await flush() + expect(deletionSettled).toBe(false) + + // Releasing only the selected child's cleanup must settle the deletion; + // the unselected sibling stays parked and must not stall it. + gates.get(selectedId)!.release() + await deletion + expect(deletionSettled).toBe(true) + + gates.get(siblingId)!.release() + await cascade + } finally { + // Keep every gate openable on the failure path too: afterEach disposes + // the provider, which drains the parked child cleanup behind these + // gates. Resolving twice is a no-op. + for (const gate of gates.values()) { + gate.release() + } + } + }) + + it("retries the parent childIds write when registration hits a transient store failure (CR axIR)", async () => { + const parent = new FakeParentTask("parent-1") + seedRegistry(provider, parent) + seedParentRecord("parent-1") + + const store = provider.taskHistoryStore + const originalReadAndUpdate = store.atomicReadAndUpdate.bind(store) + let parentWriteFailures = 0 + store.atomicReadAndUpdate = vi.fn(async (taskId: string, update: (item: HistoryItem) => HistoryItem) => { + if (taskId === "parent-1" && parentWriteFailures < 2) { + parentWriteFailures++ + throw new Error("transient store failure") + } + return originalReadAndUpdate(taskId, update) + }) + + const result = await spawn(provider, parent, [makeSpec("a")]) + expect(result.started).toBe(true) + const childId = result.children[0].taskId + + // The parent link must be durable once the child counts as registered: + // the bounded retry lands it instead of leaving the stamped child out + // of the parent's `childIds`. + expect(storeState.items.get("parent-1")?.childIds).toContain(childId) + expect(storeState.items.get(childId)?.backgroundParentTaskId).toBe("parent-1") + expect(provider["pendingBackgroundParentLinks"].size).toBe(0) + }) + + it("records a pending parent link that keeps failing and repairs it on the next pass (CR axIR)", async () => { + const parent = new FakeParentTask("parent-1") + seedRegistry(provider, parent) + seedParentRecord("parent-1") + + const store = provider.taskHistoryStore + const originalReadAndUpdate = store.atomicReadAndUpdate.bind(store) + let parentWritesFail = true + store.atomicReadAndUpdate = vi.fn(async (taskId: string, update: (item: HistoryItem) => HistoryItem) => { + if (taskId === "parent-1" && parentWritesFail) { + throw new Error("persistent store failure") + } + return originalReadAndUpdate(taskId, update) + }) + + runTracker.block() + const result = await spawn(provider, parent, [makeSpec("a")]) + expect(result.started).toBe(true) + const childId = result.children[0].taskId + + // The link did not land, but it is recorded for repair; the child is + // still stamped so startup orphan cleanup keeps working. + expect(storeState.items.get("parent-1")?.childIds).not.toContain(childId) + expect(provider["pendingBackgroundParentLinks"].get(childId)).toBe("parent-1") + expect(storeState.items.get(childId)?.backgroundParentTaskId).toBe("parent-1") + + // The store recovers; the next repair pass completes the link. + parentWritesFail = false + await provider["flushPendingBackgroundParentLinks"]() + expect(storeState.items.get("parent-1")?.childIds).toContain(childId) + expect(provider["pendingBackgroundParentLinks"].size).toBe(0) + }) + + it("repairs a pending parent link before the delete cascade collects childIds (CR axIR)", async () => { + const parent = new FakeParentTask("parent-1") + seedRegistry(provider, parent) + seedParentRecord("parent-1") + + const store = provider.taskHistoryStore + const originalReadAndUpdate = store.atomicReadAndUpdate.bind(store) + let parentWritesFail = true + store.atomicReadAndUpdate = vi.fn(async (taskId: string, update: (item: HistoryItem) => HistoryItem) => { + if (taskId === "parent-1" && parentWritesFail) { + throw new Error("persistent store failure") + } + return originalReadAndUpdate(taskId, update) + }) + store.deleteMany = vi.fn(async (ids: string[]) => { + for (const id of ids) { + storeState.items.delete(id) + } + }) + + runTracker.block() + const result = await spawn(provider, parent, [makeSpec("a")]) + const childId = result.children[0].taskId + expect(provider["pendingBackgroundParentLinks"].get(childId)).toBe("parent-1") + + // The store recovers before the user deletes the parent: the deletion's + // repair pass must bring the child into the cascade, so its history row + // and directory are removed with the parent's. + parentWritesFail = false + provider.postStateToWebview = vi.fn().mockResolvedValue(undefined) + await provider.deleteTaskWithId("parent-1") + + expect(store.deleteMany).toHaveBeenCalledWith(expect.arrayContaining(["parent-1", childId])) + expect(storeState.items.get("parent-1")).toBeUndefined() + expect(storeState.items.get(childId)).toBeUndefined() + }) + + it("closes admission and drains in-flight registrations before the delete cascade collects childIds (CR round 5)", async () => { + const parent = new FakeParentTask("parent-1") + seedRegistry(provider, parent) + seedParentRecord("parent-1") + + const store = provider.taskHistoryStore + const originalReadAndUpdate = store.atomicReadAndUpdate.bind(store) + let blockParentLinkWrites = false + let linkEntered!: () => void + let releaseLink!: () => void + const linkEnteredPromise = new Promise((resolve) => { + linkEntered = resolve + }) + const linkGate = new Promise((resolve) => { + releaseLink = resolve + }) + store.atomicReadAndUpdate = vi.fn(async (taskId: string, update: (item: HistoryItem) => HistoryItem) => { + if (taskId === "parent-1" && blockParentLinkWrites) { + linkEntered() + await linkGate + } + return originalReadAndUpdate(taskId, update) + }) + store.deleteMany = vi.fn(async (ids: string[]) => { + for (const id of ids) { + storeState.items.delete(id) + } + }) + + // First child registers normally. + runTracker.block() + const first = await spawn(provider, parent, [makeSpec("a")]) + const childA = first.children[0].taskId + + // Second spawn parks inside its parent-link write: its registration is + // in progress when deletion starts. + try { + blockParentLinkWrites = true + const second = spawn(provider, parent, [makeSpec("b")]) + await linkEnteredPromise + const childB = createdTasks()[1].taskId + + provider.postStateToWebview = vi.fn().mockResolvedValue(undefined) + + const deletion = provider.deleteTaskWithId("parent-1") + await flush() + + // The registration drain holds deletion before any history removal. + expect(store.deleteMany).not.toHaveBeenCalled() + + // A spawn admitted after deletion started is refused outright. + const late = await spawn(provider, parent, [makeSpec("c")]) + expect(late.started).toBe(false) + expect((await late.children[0].done).status).toBe("aborted") + expect(provider["backgroundTasks"].size).toBe(1) + + // Registration lands mid-delete; the cascade below must now see the + // link and take the second child with the parent. + releaseLink() + await second + await deletion + + expect(store.deleteMany).toHaveBeenCalledWith(expect.arrayContaining(["parent-1", childA, childB])) + expect(storeState.items.size).toBe(0) + expect(provider["backgroundTasks"].size).toBe(0) + } finally { + // A failed assertion must not leave the in-flight registration parked: + // the suite teardown only releases the run tracker, not this gate. + releaseLink() + } + }) + + it("closes admission and drains registrations for each descendant before reading its childIds (CR F-1)", async () => { + const parent = new FakeParentTask("parent-1") + const descendant = new FakeParentTask("desc-1") + seedRegistry(provider, parent, descendant) + seedParentRecord("parent-1", { childIds: ["desc-1"] }) + seedParentRecord("desc-1") + + const store = provider.taskHistoryStore + const originalReadAndUpdate = store.atomicReadAndUpdate.bind(store) + let blockDescendantLinkWrites = false + let releaseLink!: () => void + const linkGate = new Promise((resolve) => { + releaseLink = resolve + }) + store.atomicReadAndUpdate = vi.fn(async (taskId: string, update: (item: HistoryItem) => HistoryItem) => { + if (taskId === "desc-1" && blockDescendantLinkWrites) { + await linkGate + } + return originalReadAndUpdate(taskId, update) + }) + store.deleteMany = vi.fn(async (ids: string[]) => { + for (const id of ids) { + storeState.items.delete(id) + } + }) + + // Mirror the file-backed store: a read snapshots the record when it + // runs, so a link write that lands after the read began is not part of + // the returned item. Signal the moment the collector reads `desc-1`. + const originalGet = store.get.bind(store) + let readEntered!: () => void + const readEnteredPromise = new Promise((resolve) => { + readEntered = resolve + }) + store.get = vi.fn((taskId: string) => { + const item = originalGet(taskId) + if (taskId !== "desc-1" || !item) { + return item + } + readEntered() + return { ...item, childIds: item.childIds ? [...item.childIds] : item.childIds } + }) + + provider.postStateToWebview = vi.fn().mockResolvedValue(undefined) + + try { + runTracker.block() + blockDescendantLinkWrites = true + const deletion = provider.deleteTaskWithId("parent-1") + await readEnteredPromise + + // The descendant's record has been read (a snapshot without any new + // link); its admission gate must already be closed, so a spawn that + // starts now is refused outright instead of registering a + // grandchild whose link would escape the collector's snapshot. + const midDeletionSpawn = spawn(provider, descendant, [makeSpec("g")]) + await flush(10) + expect(provider["backgroundAdmissionClosed"].has("desc-1")).toBe(true) + + releaseLink() + const midResult = await midDeletionSpawn + await deletion + + expect(midResult.started).toBe(false) + expect((await midResult.children[0].done).status).toBe("aborted") + expect(store.deleteMany).toHaveBeenCalledWith(["parent-1", "desc-1"]) + expect(storeState.items.size).toBe(0) + expect(provider["backgroundTasks"].size).toBe(0) + } finally { + // A failed assertion must not leave a parked registration behind: + // the suite teardown only releases the run tracker, not this gate. + releaseLink() + } + }) + + it("does not drain an unrelated parent's in-flight registration when deleting a task (CR F-2)", async () => { + const parentA = new FakeParentTask("parent-a") + seedRegistry(provider, parentA) + seedParentRecord("parent-a") + seedParentRecord("parent-b") + + const store = provider.taskHistoryStore + const originalReadAndUpdate = store.atomicReadAndUpdate.bind(store) + let blockParentALinkWrites = false + let linkEntered!: () => void + let releaseLink!: () => void + const linkEnteredPromise = new Promise((resolve) => { + linkEntered = resolve + }) + const linkGate = new Promise((resolve) => { + releaseLink = resolve + }) + store.atomicReadAndUpdate = vi.fn(async (taskId: string, update: (item: HistoryItem) => HistoryItem) => { + if (taskId === "parent-a" && blockParentALinkWrites) { + linkEntered() + await linkGate + } + return originalReadAndUpdate(taskId, update) + }) + store.deleteMany = vi.fn(async (ids: string[]) => { + for (const id of ids) { + storeState.items.delete(id) + } + }) + + runTracker.block() + blockParentALinkWrites = true + const spawnA = spawn(provider, parentA, [makeSpec("a")]) + await linkEnteredPromise + + provider.postStateToWebview = vi.fn().mockResolvedValue(undefined) + const deletion = provider.deleteTaskWithId("parent-b", false) + + try { + // The unrelated registration is still parked inside its parent-link + // write, yet the deletion of parent-b must reach deleteMany without + // waiting for it, and no link may have been written for parent-a. + await flush(10) + expect(store.deleteMany).toHaveBeenCalledWith(["parent-b"]) + expect(storeState.items.get("parent-a")?.childIds ?? []).toHaveLength(0) + } finally { + releaseLink() + } + + await spawnA + await deletion + expect(storeState.items.get("parent-b")).toBeUndefined() + }) + + it("removes exactly the abort-hook listener and keeps unrelated listeners (CR axHd)", async () => { + const parent = new FakeParentTask("parent-1") + seedRegistry(provider, parent) + seedParentRecord("parent-1") + + const onceSpy = vi.spyOn(parent, "once") + const offSpy = vi.spyOn(parent, "off") + const unrelated = vi.fn() + parent.on(RooCodeEventName.TaskAborted, unrelated) + + runTracker.block() + const result = await spawn(provider, parent, [makeSpec("a")]) + parent.emit(RooCodeEventName.TaskAborted) + await Promise.all(result.children.map((child) => child.done)) + + await vi.waitFor( + () => { + expect(offSpy).toHaveBeenCalled() + }, + { timeout: 2000, interval: 10 }, + ) + + // The same function reference that `once` received must be the one + // passed to `off`: an implementation that drops every TaskAborted + // listener (e.g. `off(event)` without the listener) would pass an + // expect.any(Function) assertion but must fail here. + const onceCalls = onceSpy.mock.calls.filter(([event]) => event === RooCodeEventName.TaskAborted) + expect(onceCalls).toHaveLength(1) + const [registeredEvent, registeredListener] = onceCalls[0] + expect(offSpy).toHaveBeenCalledWith(registeredEvent, registeredListener) + + // The unrelated listener survives the hook release and still fires on + // the next abort (it also observed the first one, before the release). + expect(parent.listenerCount(RooCodeEventName.TaskAborted)).toBe(1) + const callsBefore = unrelated.mock.calls.length + parent.emit(RooCodeEventName.TaskAborted) + expect(unrelated.mock.calls.length).toBe(callsBefore + 1) + expect(provider["backgroundAbortHooks"].size).toBe(0) + }) +}) diff --git a/src/core/webview/__tests__/ClineProvider.backgroundSubtasks.spec.ts b/src/core/webview/__tests__/ClineProvider.backgroundSubtasks.spec.ts new file mode 100644 index 0000000000..c25dae3718 --- /dev/null +++ b/src/core/webview/__tests__/ClineProvider.backgroundSubtasks.spec.ts @@ -0,0 +1,1878 @@ +// pnpm --dir src exec vitest run core/webview/__tests__/ClineProvider.backgroundSubtasks.spec.ts + +import EventEmitter from "events" + +import { WebviewFocusTracker } from "../WebviewFocusTracker" +import * as vscode from "vscode" +import type { HistoryItem, ProviderSettings } from "@roo-code/types" +import { ORGANIZATION_ALLOW_ALL, providerIdentifiers, RooCodeEventName } from "@roo-code/types" + +import { ContextProxy } from "../../config/ContextProxy" +import { TaskRegistry } from "../../task/TaskRegistry" +import { Task } from "../../task/Task" +import { ShadowCheckpointService } from "../../../services/checkpoints/ShadowCheckpointService" +import { ProfileValidator } from "../../../shared/ProfileValidator" +import { BACKGROUND_CHILD_DISABLED_TOOLS, BACKGROUND_CHILD_EXPERIMENTS } from "../../background-subtasks/policy" +import type { + BackgroundChildEntry, + BackgroundChildHandle, + BackgroundSubtaskSpec, +} from "../../background-subtasks/types" +import { + ClineProvider, + DEFAULT_MAX_PARALLEL_SUBTASKS, + MAX_LIVE_BACKGROUND_CHILDREN_PER_PARENT, + MAX_PARALLEL_SUBTASKS_CAP, +} from "../ClineProvider" + +const apiConfig: ProviderSettings = { + apiProvider: providerIdentifiers.anthropic, + apiKey: "test-key", +} + +/** + * Shared state for the mocked `Task` constructor: every created child is + * pushed here so a test can assert on the options the provider passed. + */ +const taskState = vi.hoisted(() => ({ created: [] as unknown[] })) + +interface MockTaskConstructorOptions { + taskId?: string + task?: string + parentTask?: { taskId: string } + rootTask?: { taskId: string } + /** Explicit authoritative root id for a child whose root object is gone. */ + rootTaskId?: string + taskNumber?: number + apiConfiguration?: unknown + handoffExecutionContext?: { + mode: string + apiConfigName?: string + apiConfiguration: ProviderSettings + } + backgroundToolPolicy?: { disabledTools?: readonly string[]; experiments?: Record } + backgroundChildHosted?: boolean + historyItem?: { id: string; rootTaskId?: string; parentTaskId?: string; number?: number } +} + +/** + * Tracks child task loop concurrency. `block()` makes every `run()` wait on a + * shared gate so the scheduler cap can be observed; `releaseAll()` frees them. + */ +const runTracker = vi.hoisted(() => { + const state = { active: 0, maxActive: 0, started: 0 } + let gate: Promise = Promise.resolve() + let release: (() => void) | undefined + let rejection: Error | undefined + + return { + state, + reset() { + state.active = 0 + state.maxActive = 0 + state.started = 0 + gate = Promise.resolve() + release = undefined + rejection = undefined + }, + block() { + gate = new Promise((resolve) => { + release = resolve + }) + }, + releaseAll() { + release?.() + release = undefined + }, + /** Makes the next `run()` reject the way a failed child loop does. */ + failNext(message: string) { + rejection = new Error(message) + }, + async run() { + state.started += 1 + state.active += 1 + state.maxActive = Math.max(state.maxActive, state.active) + await gate + state.active -= 1 + if (rejection) { + const error = rejection + rejection = undefined + throw error + } + }, + } +}) + +/** + * In-memory stand-in for `TaskHistoryStore` so the provider's registration + * writes are observable, plus the constructor options for the option-wiring test. + */ +const storeState = vi.hoisted(() => ({ + items: new Map(), + constructorOptions: [] as unknown[], +})) + +vi.mock("vscode", () => { + const mockDisposable = { dispose: vi.fn() } + return { + workspace: { + getConfiguration: vi.fn(() => ({ + get: vi.fn().mockReturnValue([]), + update: vi.fn().mockResolvedValue(undefined), + })), + workspaceFolders: [], + onDidChangeConfiguration: vi.fn(() => mockDisposable), + }, + env: { + uriScheme: "vscode", + language: "en", + }, + EventEmitter: vi.fn().mockImplementation(function () { + return { + event: vi.fn(), + fire: vi.fn(), + } + }), + Disposable: { + from: vi.fn(), + }, + window: { + showErrorMessage: vi.fn(), + showInformationMessage: vi.fn(), + showWarningMessage: vi.fn(), + createTextEditorDecorationType: vi.fn().mockReturnValue({ dispose: vi.fn() }), + onDidChangeActiveTextEditor: vi.fn(() => mockDisposable), + }, + Uri: { + file: vi.fn().mockReturnValue({ toString: () => "file://test" }), + joinPath: vi.fn(), + }, + commands: { + executeCommand: vi.fn().mockResolvedValue(undefined), + }, + ExtensionMode: { + Production: 1, + Development: 2, + Test: 3, + }, + version: "1.85.0", + } +}) + +// The fake child mirrors the constructor derivations the provider relies on: +// parentTaskId from `parentTask`, rootTaskId from an explicit `rootTaskId`, a +// `historyItem`, or `rootTask` (in that order, matching CR-1's Task option). +// It deliberately does not call `onCreated`; no assertion depends on provider +// listeners being wired for a child in these tests. The raw constructor +// options are retained on each instance so provider tests assert the wiring +// the provider actually performed instead of this double's derivation of it. +vi.mock("../../task/Task", () => { + class MockTask { + taskId: string + instanceId = "mock-instance" + /** Raw options verbatim as passed by the provider under test. */ + readonly rawOptions: MockTaskConstructorOptions + rootTaskId?: string + parentTaskId?: string + taskNumber: number + metadata: { task?: string } + cwd = "/test/workspace" + workspacePath = "/test/workspace" + apiConfiguration: unknown + handoffExecutionContext?: MockTaskConstructorOptions["handoffExecutionContext"] + backgroundToolPolicy?: { disabledTools?: readonly string[]; experiments?: Record } + /** Raw hosted flag as passed by the provider; no derivation is mirrored. */ + backgroundChildHosted?: boolean + abort = false + abandoned = false + // EventEmitter gives once() real Node semantics — the listener is + // removed before it runs — matching Task's production emitter so + // abort-hook tests can detect a hook record retained after the once + // was consumed. + private readonly emitter = new EventEmitter() + emit = vi.fn((event: string, ...args: unknown[]) => { + this.emitter.emit(event, ...args) + }) + on = vi.fn((event: string, listener: (...args: unknown[]) => void) => { + this.emitter.on(event, listener) + }) + once = vi.fn((event: string, listener: (...args: unknown[]) => void) => { + this.emitter.once(event, listener) + }) + off = vi.fn((event: string, listener: (...args: unknown[]) => void) => { + this.emitter.off(event, listener) + }) + dispose = vi.fn().mockResolvedValue(undefined) + abortTask = vi.fn(async () => { + this.emit(RooCodeEventName.TaskAborted) + }) + run = vi.fn(() => runTracker.run()) + getTaskMode = vi.fn(async () => "code") + getTaskApiConfigName = vi.fn(async () => undefined) + + constructor(options: MockTaskConstructorOptions) { + this.rawOptions = options + this.taskId = options.historyItem?.id ?? options.taskId ?? `mock-task-${taskState.created.length + 1}` + this.rootTaskId = + options.rootTaskId ?? (options.historyItem ? options.historyItem.rootTaskId : options.rootTask?.taskId) + this.parentTaskId = options.historyItem ? options.historyItem.parentTaskId : options.parentTask?.taskId + this.taskNumber = options.taskNumber ?? options.historyItem?.number ?? -1 + this.metadata = { task: options.task } + this.apiConfiguration = options.apiConfiguration + this.handoffExecutionContext = options.handoffExecutionContext + this.backgroundToolPolicy = options.backgroundToolPolicy + // Record the hosted flag verbatim so tests assert the provider's + // wiring (spawn sets it, restore omits it) rather than a property + // this mock would have to derive. The `isBackgroundSubtaskChild` + // derivation is asserted against the real `Task` in + // src/core/task/__tests__/background-restored-child.spec.ts (P1-2). + this.backgroundChildHosted = options.backgroundChildHosted + taskState.created.push(this) + } + } + + return { + Task: MockTask, + PendingActionSettlementError: class PendingActionSettlementError extends Error {}, + } +}) + +vi.mock("../../../services/mcp/McpServerManager", () => ({ + McpServerManager: { + getInstance: vi.fn().mockResolvedValue({ + registerClient: vi.fn(), + unregisterClient: vi.fn(), + }), + unregisterProvider: vi.fn(), + }, +})) + +vi.mock("../../../integrations/workspace/WorkspaceTracker", () => ({ + default: vi.fn().mockImplementation(function () { + return { + initializeFilePaths: vi.fn(), + dispose: vi.fn(), + } + }), +})) + +vi.mock("../../../utils/path", async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + getWorkspacePath: vi.fn().mockReturnValue("/test/workspace"), + } +}) + +vi.mock("@roo-code/telemetry", () => ({ + TelemetryService: { + instance: { + setProvider: vi.fn(), + captureTaskCreated: vi.fn(), + captureTaskRestarted: vi.fn(), + captureTaskCompleted: vi.fn(), + }, + }, +})) + +vi.mock("@roo-code/cloud", () => ({ + CloudService: { + hasInstance: vi.fn().mockReturnValue(false), + instance: { + isAuthenticated: vi.fn().mockReturnValue(false), + }, + }, + getRooCodeApiUrl: vi.fn().mockReturnValue("https://api.roo-code.com"), +})) + +vi.mock("../../../shared/embeddingModels", () => ({ + EMBEDDING_MODEL_PROFILES: [], +})) + +// Keep the real mode table so an unknown slug really is unknown. +vi.mock("../../../shared/modes", async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + getModeBySlug: vi.fn(actual.getModeBySlug), + } +}) + +vi.mock("p-wait-for", () => ({ + __esModule: true, + default: vi.fn().mockResolvedValue(undefined), +})) + +vi.mock("fs/promises", () => ({ + mkdir: vi.fn().mockResolvedValue(undefined), + writeFile: vi.fn().mockResolvedValue(undefined), + readFile: vi.fn().mockResolvedValue(""), + readdir: vi.fn().mockResolvedValue([]), + unlink: vi.fn().mockResolvedValue(undefined), + rmdir: vi.fn().mockResolvedValue(undefined), + access: vi.fn().mockResolvedValue(undefined), + rm: vi.fn().mockResolvedValue(undefined), +})) + +vi.mock("axios", () => ({ + default: { get: vi.fn().mockResolvedValue({ data: { data: [] } }), post: vi.fn() }, + get: vi.fn().mockResolvedValue({ data: { data: [] } }), + post: vi.fn(), +})) + +vi.mock("delay", () => { + const delayFn = (_ms: number) => Promise.resolve() + delayFn.createDelay = () => delayFn + delayFn.reject = () => Promise.reject(new Error("Delay rejected")) + delayFn.range = () => Promise.resolve() + return { default: delayFn } +}) + +vi.mock("../../../utils/storage", () => ({ + getSettingsDirectoryPath: vi.fn().mockResolvedValue("/test/settings/path"), + getTaskDirectoryPath: vi.fn().mockResolvedValue("/test/task/path"), + getGlobalStoragePath: vi.fn().mockResolvedValue("/test/storage/path"), + getStorageBasePath: vi.fn().mockImplementation((defaultPath: string) => defaultPath), +})) + +vi.mock("../../../utils/safeWriteJson", () => ({ + safeWriteJson: vi.fn().mockResolvedValue(undefined), +})) + +vi.mock("../../../utils/tts", () => ({ + setTtsEnabled: vi.fn(), + setTtsSpeed: vi.fn(), +})) + +vi.mock("../../../api", () => ({ + buildApiHandler: vi.fn().mockReturnValue({ + getModel: vi.fn().mockReturnValue({ id: "claude-3-sonnet" }), + }), +})) + +vi.mock("../../prompts/system", () => ({ + SYSTEM_PROMPT: vi.fn().mockImplementation(async () => "mocked system prompt"), + codeMode: "code", +})) + +vi.mock("../../prompts/sections/custom-instructions") + +vi.mock("../../../api/providers/fetchers/modelCache", () => ({ + getModels: vi.fn().mockResolvedValue({}), + flushModels: vi.fn(), + getModelsFromCache: vi.fn().mockReturnValue(undefined), +})) + +vi.mock("../../../integrations/misc/extract-text", () => ({ + extractTextFromFile: vi.fn().mockResolvedValue("file content"), +})) + +vi.mock("../diff/strategies/multi-search-replace", () => ({ + MultiSearchReplaceDiffStrategy: vi.fn().mockImplementation(function () { + return { getName: () => "test-strategy", applyDiff: vi.fn() } + }), +})) + +vi.mock("@modelcontextprotocol/sdk/types.js", () => ({ + CallToolResultSchema: {}, + ListResourcesResultSchema: {}, + ListResourceTemplatesResultSchema: {}, + ListToolsResultSchema: {}, + ReadResourceResultSchema: {}, + ErrorCode: { InvalidRequest: "InvalidRequest", MethodNotFound: "MethodNotFound", InternalError: "InternalError" }, + McpError: class McpError extends Error { + code: string + constructor(code: string, message: string) { + super(message) + this.code = code + this.name = "McpError" + } + }, +})) + +vi.mock("@modelcontextprotocol/sdk/client/index.js", () => ({ + Client: vi.fn().mockImplementation(function () { + return { + connect: vi.fn().mockResolvedValue(undefined), + close: vi.fn().mockResolvedValue(undefined), + listTools: vi.fn().mockResolvedValue({ tools: [] }), + callTool: vi.fn().mockResolvedValue({ content: [] }), + } + }), +})) + +vi.mock("@modelcontextprotocol/sdk/client/stdio.js", () => ({ + StdioClientTransport: vi.fn().mockImplementation(function () { + return { connect: vi.fn().mockResolvedValue(undefined), close: vi.fn().mockResolvedValue(undefined) } + }), +})) + +vi.mock("../../../services/skills/SkillsManager", () => ({ + SkillsManager: vi.fn().mockImplementation(function () { + return { + initialize: vi.fn().mockResolvedValue(undefined), + dispose: vi.fn().mockResolvedValue(undefined), + } + }), +})) + +// Keep the real lifecycle reducers (`addBackgroundChild`) and replace only the +// store, so the provider's registration writes land in the in-memory map. +vi.mock("../../task-persistence", async (importOriginal) => { + const actual = await importOriginal() + + const makeStore = () => ({ + initialize: vi.fn().mockResolvedValue(undefined), + initialized: Promise.resolve(), + dispose: vi.fn(), + get: vi.fn((taskId: string) => storeState.items.get(taskId)), + getAll: vi.fn(() => Array.from(storeState.items.values())), + upsert: vi.fn(async (item: HistoryItem) => { + const existing = storeState.items.get(item.id) + storeState.items.set(item.id, existing ? { ...existing, ...item } : item) + return Array.from(storeState.items.values()) + }), + atomicReadAndUpdate: vi.fn(async (taskId: string, update: (item: HistoryItem) => HistoryItem) => { + const current = storeState.items.get(taskId) + if (!current) { + throw new Error(`[mock TaskHistoryStore] task ${taskId} not found`) + } + const updated = update(current) + storeState.items.set(taskId, updated) + return Array.from(storeState.items.values()) + }), + delete: vi.fn().mockResolvedValue(undefined), + deleteMany: vi.fn().mockResolvedValue(undefined), + migrateFromGlobalState: vi.fn().mockResolvedValue(undefined), + invalidate: vi.fn().mockResolvedValue(undefined), + invalidateAll: vi.fn(), + setAutoTitleIfAbsent: vi.fn().mockResolvedValue({ applied: false }), + }) + + return { + ...actual, + TaskHistoryStore: vi.fn().mockImplementation(function (_path: string, options?: unknown) { + storeState.constructorOptions.push(options) + return makeStore() + }), + saveTaskMessages: vi.fn().mockResolvedValue(undefined), + readApiMessages: vi.fn().mockResolvedValue([]), + saveApiMessages: vi.fn().mockResolvedValue(undefined), + } +}) + +interface MockTaskInstance { + taskId: string + rootTaskId?: string + parentTaskId?: string + rawOptions: MockTaskConstructorOptions + taskNumber: number + backgroundChildHosted?: boolean + handoffExecutionContext?: MockTaskConstructorOptions["handoffExecutionContext"] + backgroundToolPolicy?: { disabledTools?: readonly string[]; experiments?: Record } + run: ReturnType + abortTask: ReturnType + dispose: ReturnType + emit: ReturnType void>> + once: ReturnType + off: ReturnType +} + +function createdTasks(): MockTaskInstance[] { + return taskState.created as MockTaskInstance[] +} + +/** + * Minimal stand-in for the members `spawnBackgroundChildren` reads from a parent + * task: identity, lineage, mode/profile accessors, and the TaskAborted emitter. + */ +class FakeParentTask { + // EventEmitter gives once() real Node semantics — the listener is removed + // before it runs — so abort-hook tests can tell when the provider retains + // a hook record after the once has already been consumed. + private readonly emitter = new EventEmitter() + readonly instanceId = "parent-instance" + readonly apiConfiguration: ProviderSettings = apiConfig + dispose = vi.fn().mockResolvedValue(undefined) + abortTask = vi.fn().mockResolvedValue(undefined) + flushPendingToolResultsToHistory = vi.fn().mockResolvedValue(true) + + constructor( + readonly taskId: string, + readonly rootTaskId?: string, + // `Task` retains this reference after the stack pops that delegation + // performs; every production lineage walk relies on it (D-01). + readonly parentTask?: FakeParentTask, + ) {} + + async getTaskMode(): Promise { + return "code" + } + + async getTaskApiConfigName(): Promise { + return "default-profile" + } + + once(event: string, listener: (...args: unknown[]) => void): void { + this.emitter.once(event, listener) + } + + off(event: string, listener: (...args: unknown[]) => void): void { + this.emitter.off(event, listener) + } + + emit(event: string): void { + this.emitter.emit(event) + } + + listenerCount(event: string): number { + return this.emitter.listenerCount(event) + } +} + +// The double implements TaskIdentity/lineage/mode accessors and an event emitter; +// no other Task surface is reachable from spawnBackgroundChildren. +function asTask(parent: FakeParentTask): Task { + return parent as unknown as Task +} + +function seedRegistry(provider: ClineProvider, ...tasks: FakeParentTask[]): void { + const registry = new TaskRegistry() + for (const task of tasks) { + registry.push(asTask(task)) + } + provider["taskRegistry"] = registry +} + +function seedParentRecord(taskId: string, overrides: Partial = {}): HistoryItem { + const item: HistoryItem = { + id: taskId, + number: 1, + ts: 1, + task: "Parent task", + tokensIn: 0, + tokensOut: 0, + totalCost: 0, + status: "active", + childIds: [], + ...overrides, + } + storeState.items.set(taskId, item) + return item +} + +const flush = async (ticks = 6): Promise => { + for (let index = 0; index < ticks; index++) { + await new Promise((resolve) => setTimeout(resolve, 0)) + } +} + +function makeSpec(label: string, mode = "code"): BackgroundSubtaskSpec { + return { label, mode, message: `Investigate ${label}` } +} + +async function spawn( + provider: ClineProvider, + parent: FakeParentTask, + specs: BackgroundSubtaskSpec[], +): Promise<{ children: BackgroundChildHandle[]; started: boolean }> { + return provider.spawnBackgroundChildren(asTask(parent), specs) +} + +describe("ClineProvider background subtasks (D2/D7/D8)", () => { + let provider: ClineProvider + let mockContext: vscode.ExtensionContext + let mockOutputChannel: vscode.OutputChannel + + beforeEach(() => { + vi.clearAllMocks() + taskState.created.length = 0 + runTracker.reset() + storeState.items.clear() + storeState.constructorOptions.length = 0 + + vi.spyOn(ProfileValidator, "isProfileAllowed").mockReturnValue(true) + + mockContext = { + globalState: { + get: vi.fn().mockReturnValue(undefined), + update: vi.fn().mockResolvedValue(undefined), + keys: vi.fn().mockReturnValue([]), + }, + globalStorageUri: { fsPath: "/test/storage" }, + secrets: { + get: vi.fn().mockResolvedValue(undefined), + store: vi.fn().mockResolvedValue(undefined), + delete: vi.fn().mockResolvedValue(undefined), + }, + workspaceState: { + get: vi.fn().mockReturnValue(undefined), + update: vi.fn().mockResolvedValue(undefined), + keys: vi.fn().mockReturnValue([]), + }, + extensionUri: { fsPath: "/test/extension" }, + extension: { packageJSON: { version: "1.0.0" } }, + subscriptions: [], + } as unknown as vscode.ExtensionContext + + mockOutputChannel = { + appendLine: vi.fn(), + dispose: vi.fn(), + } as unknown as vscode.OutputChannel + + const mockContextProxy = { + getValues: vi.fn().mockReturnValue({}), + getValue: vi.fn().mockReturnValue(undefined), + setValue: vi.fn().mockResolvedValue(undefined), + setValues: vi.fn().mockResolvedValue(undefined), + getProviderSettings: vi.fn().mockReturnValue(apiConfig), + extensionUri: mockContext.extensionUri, + globalStorageUri: mockContext.globalStorageUri, + } + + provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + mockContextProxy as unknown as ContextProxy, + new WebviewFocusTracker(), + ) + + provider.getState = vi.fn().mockResolvedValue({ + apiConfiguration: apiConfig, + customModes: [], + organizationAllowList: ORGANIZATION_ALLOW_ALL, + // `addClineToStack` refuses to finish without a mode. + mode: "code", + }) + provider["getModeConfigId"] = vi.fn().mockResolvedValue(undefined) + }) + + afterEach(async () => { + runTracker.releaseAll() + await provider.dispose() + vi.restoreAllMocks() + }) + + describe("spawnBackgroundChildren", () => { + it("returns no children for an empty spec list", async () => { + const parent = new FakeParentTask("parent-1") + seedRegistry(provider, parent) + + const result = await spawn(provider, parent, []) + + expect(result).toEqual({ children: [], started: false }) + expect(createdTasks()).toHaveLength(0) + }) + + it("caps a batch at MAX_PARALLEL_SUBTASKS_CAP and logs the truncation", async () => { + const parent = new FakeParentTask("parent-1") + seedRegistry(provider, parent) + seedParentRecord("parent-1") + provider.log = vi.fn() + + const specs = Array.from({ length: MAX_PARALLEL_SUBTASKS_CAP + 2 }, (_value, index) => + makeSpec(`child-${index}`), + ) + const result = await spawn(provider, parent, specs) + + expect(result.children).toHaveLength(MAX_PARALLEL_SUBTASKS_CAP) + expect(createdTasks()).toHaveLength(MAX_PARALLEL_SUBTASKS_CAP) + expect(provider.log).toHaveBeenCalledWith( + expect.stringContaining(`Truncated ${specs.length} requested background children`), + ) + }) + + it("does not push children onto the task stack", async () => { + const parent = new FakeParentTask("parent-1") + seedRegistry(provider, parent) + seedParentRecord("parent-1") + const lengthBefore = provider["taskRegistry"].length + + await spawn(provider, parent, [makeSpec("a"), makeSpec("b")]) + + expect(provider["taskRegistry"].length).toBe(lengthBefore) + expect(provider.getCurrentTask()?.taskId).toBe("parent-1") + }) + + it("inherits parentTaskId and rootTaskId from the parent lineage", async () => { + const parent = new FakeParentTask("parent-1") + seedRegistry(provider, parent) + seedParentRecord("parent-1") + + await spawn(provider, parent, [makeSpec("a")]) + + // Assert the raw options the provider passed; the double's derivation + // of rootTaskId/parentTaskId is covered against a real `Task` in the + // task-layer suite and must not be what keeps this test green. + const [child] = createdTasks() + expect(child.rawOptions.parentTask?.taskId).toBe("parent-1") + expect(child.rawOptions.rootTask?.taskId).toBe("parent-1") + expect(child.rawOptions.rootTaskId).toBeUndefined() + }) + + it("inherits the true root when the delegated parent's root is absent from the registry", async () => { + // Production-reachable state (D-01): delegation pops every ancestor + // off the stack, so the registry holds only the delegated parent and + // the root survives only as the parent's in-memory `parentTask`. + const root = new FakeParentTask("root-1") + const parent = new FakeParentTask("parent-1", "root-1", root) + seedRegistry(provider, parent) + seedParentRecord("parent-1", { rootTaskId: "root-1" }) + + expect(provider["taskRegistry"].getById("root-1")).toBeUndefined() + + await spawn(provider, parent, [makeSpec("a")]) + + const [child] = createdTasks() + expect(child.rawOptions.parentTask?.taskId).toBe("parent-1") + expect(child.rawOptions.rootTask?.taskId).toBe("root-1") + expect(child.rawOptions.rootTaskId).toBeUndefined() + }) + + it("walks a nested delegation chain to the root", async () => { + const root = new FakeParentTask("root-1") + const middle = new FakeParentTask("middle-1", "root-1", root) + const parent = new FakeParentTask("parent-1", "root-1", middle) + seedRegistry(provider, parent) + seedParentRecord("parent-1", { rootTaskId: "root-1" }) + + await spawn(provider, parent, [makeSpec("a")]) + + expect(createdTasks()[0].rawOptions.rootTask?.taskId).toBe("root-1") + expect(createdTasks()[0].rawOptions.rootTaskId).toBeUndefined() + }) + + it("numbers the batch on its own channel without colliding with delegation", async () => { + const root = new FakeParentTask("root-1") + const parent = new FakeParentTask("parent-1", "root-1") + seedRegistry(provider, root, parent) + seedParentRecord("parent-1", { rootTaskId: "root-1" }) + + await spawn(provider, parent, [makeSpec("a"), makeSpec("b")]) + await spawn(provider, parent, [makeSpec("c"), makeSpec("d")]) + + const numbers = createdTasks().map((task) => task.taskNumber) + expect(numbers).toEqual([3, 4, 5, 6]) + expect(new Set(numbers).size).toBe(numbers.length) + + // A delegated child is numbered after the parent leaves the stack + // (length 1 -> 2), which is the channel the batch must not reuse. + const delegatedNumberAfterParentLeaves = provider["taskRegistry"].length - 1 + 1 + expect(numbers).not.toContain(delegatedNumberAfterParentLeaves) + }) + + it("turns an unknown mode into a failed handle without spawning a task", async () => { + const parent = new FakeParentTask("parent-1") + seedRegistry(provider, parent) + seedParentRecord("parent-1") + + const result = await spawn(provider, parent, [makeSpec("ok", "code"), makeSpec("bad", "missing-mode")]) + + expect(result.children).toHaveLength(2) + expect(createdTasks()).toHaveLength(1) + + const failedEntry = (await result.children[1].done) as BackgroundChildEntry + expect(failedEntry.status).toBe("failed") + expect(failedEntry.error).toBe("Unknown mode: missing-mode") + expect(failedEntry.label).toBe("bad") + expect(result.children[0].taskId).toBe(createdTasks()[0].taskId) + }) + + it("keeps other specs alive when construction fails", async () => { + const parent = new FakeParentTask("parent-1") + seedRegistry(provider, parent) + seedParentRecord("parent-1") + + const originalCreateTask = provider.createTask.bind(provider) + let call = 0 + provider.createTask = vi.fn(async (...args: Parameters) => { + call += 1 + if (call === 1) { + throw new Error("provider rejected the profile") + } + return originalCreateTask(...args) + }) + + const result = await spawn(provider, parent, [makeSpec("a"), makeSpec("b")]) + + expect(createdTasks()).toHaveLength(1) + const firstEntry = (await result.children[0].done) as BackgroundChildEntry + expect(firstEntry.status).toBe("failed") + expect(firstEntry.error).toBe("provider rejected the profile") + expect(result.children[1].taskId).toBe(createdTasks()[0].taskId) + }) + + it("injects the read-only background tool policy into every child", async () => { + const parent = new FakeParentTask("parent-1") + seedRegistry(provider, parent) + seedParentRecord("parent-1") + + await spawn(provider, parent, [makeSpec("a"), makeSpec("b", "architect")]) + + const children = createdTasks() + expect(children).toHaveLength(2) + + for (const child of children) { + expect(child.backgroundChildHosted).toBe(true) + const disabledTools = child.backgroundToolPolicy?.disabledTools ?? [] + expect(disabledTools).toEqual(BACKGROUND_CHILD_DISABLED_TOOLS) + expect(disabledTools).toContain("write_to_file") + expect(disabledTools).toContain("execute_command") + expect(disabledTools).toContain("new_task") + expect(child.backgroundToolPolicy?.experiments).toEqual(BACKGROUND_CHILD_EXPERIMENTS) + expect(child.backgroundToolPolicy?.experiments?.customTools).toBe(false) + } + }) + + it("registers every child id on the parent without touching awaitingChildId", async () => { + const parent = new FakeParentTask("parent-1") + seedRegistry(provider, parent) + seedParentRecord("parent-1") + + const result = await spawn(provider, parent, [makeSpec("a"), makeSpec("b")]) + + const parentRecord = storeState.items.get("parent-1") + expect(parentRecord?.childIds).toEqual(result.children.map((child) => child.taskId)) + expect(parentRecord?.awaitingChildId).toBeUndefined() + expect(parentRecord?.status).toBe("active") + }) + + it("stamps each child history record with backgroundParentTaskId", async () => { + const parent = new FakeParentTask("parent-1") + seedRegistry(provider, parent) + seedParentRecord("parent-1") + // Park the runs so the records stay live while registration is read. + runTracker.block() + + const result = await spawn(provider, parent, [makeSpec("a", "code"), makeSpec("b", "architect")]) + + for (const [index, child] of createdTasks().entries()) { + const record = storeState.items.get(child.taskId) + expect(record).toBeDefined() + expect(record?.backgroundParentTaskId).toBe("parent-1") + expect(record?.parentTaskId).toBe("parent-1") + expect(record?.status).toBe("active") + expect(record?.number).toBe(child.taskNumber) + expect(record?.mode).toBe(result.children[index].mode) + } + }) + }) + + describe("spawn cancellation window (CR finding 1)", () => { + /** + * Start a spawn whose `createTask` is parked, run `duringCreate` once the + * construction is in flight, then release it and return the spawn result. + */ + async function spawnWithParkedCreate( + parent: FakeParentTask, + specs: BackgroundSubtaskSpec[], + duringCreate: () => Promise | void, + ): Promise<{ children: BackgroundChildHandle[]; started: boolean }> { + const originalCreateTask = provider.createTask.bind(provider) + let releaseCreate!: () => void + const createGate = new Promise((resolve) => { + releaseCreate = resolve + }) + let enteredCreate!: () => void + const createEntered = new Promise((resolve) => { + enteredCreate = resolve + }) + + provider.createTask = vi.fn(async (...args: Parameters) => { + enteredCreate() + await createGate + return originalCreateTask(...args) + }) + + const spawnPromise = spawn(provider, parent, specs) + await createEntered + await duringCreate() + releaseCreate() + return spawnPromise + } + + it("does not schedule or publish a child created after the parent was cancelled", async () => { + const parent = new FakeParentTask("parent-1") + seedRegistry(provider, parent) + seedParentRecord("parent-1") + + const result = await spawnWithParkedCreate(parent, [makeSpec("late")], () => { + parent.emit(RooCodeEventName.TaskAborted) + }) + + expect(createdTasks()).toHaveLength(1) + expect(provider["backgroundTasks"].size).toBe(0) + expect(runTracker.state.started).toBe(0) + + const entry = await result.children[0].done + expect(entry.status).toBe("aborted") + expect(entry.error).toBe("Parent task was cancelled") + expect(createdTasks()[0].dispose).toHaveBeenCalled() + }) + + it("does not schedule or publish a child whose construction outlived the provider", async () => { + const parent = new FakeParentTask("parent-1") + seedRegistry(provider, parent) + seedParentRecord("parent-1") + + const result = await spawnWithParkedCreate(parent, [makeSpec("late")], async () => { + await provider.dispose() + }) + + expect(runTracker.state.started).toBe(0) + expect(provider["backgroundTasks"].size).toBe(0) + + const entry = await result.children[0].done + expect(entry.status).toBe("aborted") + expect(entry.error).toBe("Provider disposed") + }) + }) + + describe("mode profile fallback (CR finding 3)", () => { + it("spawns with the parent configuration when the mode config id lookup rejects", async () => { + const parent = new FakeParentTask("parent-1") + seedRegistry(provider, parent) + seedParentRecord("parent-1") + provider["getModeConfigId"] = vi.fn().mockRejectedValue(new Error("settings store unavailable")) + + const result = await spawn(provider, parent, [makeSpec("a", "architect"), makeSpec("b", "architect")]) + + expect(result.children).toHaveLength(2) + expect(createdTasks()).toHaveLength(2) + for (const child of createdTasks()) { + expect(child.handoffExecutionContext?.mode).toBe("architect") + expect(child.handoffExecutionContext?.apiConfigName).toBe("default-profile") + expect(child.handoffExecutionContext?.apiConfiguration).toEqual(apiConfig) + } + }) + }) + + describe("authoritative lineage root without a live root object (CR finding 5)", () => { + it("carries the parent's stored rootTaskId when neither the registry nor the chain has the root", async () => { + const parent = new FakeParentTask("parent-1", "root-1") + seedRegistry(provider, parent) + seedParentRecord("parent-1", { rootTaskId: "root-1" }) + + expect(provider["taskRegistry"].getById("root-1")).toBeUndefined() + + await spawn(provider, parent, [makeSpec("a")]) + + // No live root object exists, so the provider must pass the + // authoritative id explicitly (CR finding 5) rather than a root object. + const [child] = createdTasks() + expect(child.rawOptions.rootTask).toBeUndefined() + expect(child.rawOptions.rootTaskId).toBe("root-1") + expect(child.rawOptions.parentTask?.taskId).toBe("parent-1") + }) + + it("carries the stored rootTaskId into a delegated child", async () => { + const parent = new FakeParentTask("parent-1", "root-1") + seedRegistry(provider, parent) + seedParentRecord("parent-1", { rootTaskId: "root-1" }) + + await provider.delegateParentAndOpenChild({ + parentTaskId: "parent-1", + message: "do the thing", + initialTodos: [], + mode: "code", + }) + + const [child] = createdTasks() + expect(child.rawOptions.rootTask).toBeUndefined() + expect(child.rawOptions.rootTaskId).toBe("root-1") + expect(child.rawOptions.parentTask?.taskId).toBe("parent-1") + }) + }) + + describe("run ended without a terminal state (F-02)", () => { + it("settles the handle as failed when the run ends without attempt_completion", async () => { + const parent = new FakeParentTask("parent-1") + seedRegistry(provider, parent) + seedParentRecord("parent-1") + + // An unblocked run resolves immediately and never resolves the host + // handle: the mistake-limit / token-limit / first-chunk-failure shape. + const { children } = await spawn(provider, parent, [makeSpec("mistake-limit")]) + const entry = await children[0].done + + expect(entry.status).toBe("failed") + expect(entry.error).toBe("Background child run ended without a terminal state") + expect(entry.finishedAt).toBeTypeOf("number") + expect(provider["backgroundTasks"].size).toBe(0) + + // The parent's join is exactly this Promise.all; it must resolve. + await expect(Promise.all(children.map((child) => child.done))).resolves.toHaveLength(1) + }) + + it("frees the scheduler permits when runs end without a terminal state", async () => { + const parent = new FakeParentTask("parent-1") + seedRegistry(provider, parent) + seedParentRecord("parent-1") + + runTracker.block() + const first = await spawn( + provider, + parent, + Array.from({ length: DEFAULT_MAX_PARALLEL_SUBTASKS }, (_value, index) => makeSpec(`child-${index}`)), + ) + await flush() + expect(runTracker.state.active).toBe(DEFAULT_MAX_PARALLEL_SUBTASKS) + + runTracker.releaseAll() + const entries = await Promise.all(first.children.map((child) => child.done)) + expect(entries.map((entry) => entry.status)).toEqual( + Array.from({ length: DEFAULT_MAX_PARALLEL_SUBTASKS }, () => "failed"), + ) + + // A fresh child starts immediately, proving the pool is free. + const second = await spawn(provider, parent, [makeSpec("next")]) + await flush(10) + expect(second.children).toHaveLength(1) + expect(runTracker.state.started).toBe(DEFAULT_MAX_PARALLEL_SUBTASKS + 1) + }) + + it("does not overwrite the error of a run that rejected", async () => { + const parent = new FakeParentTask("parent-1") + seedRegistry(provider, parent) + seedParentRecord("parent-1") + + runTracker.failNext("api exploded") + const { children } = await spawn(provider, parent, [makeSpec("explodes")]) + const entry = await children[0].done + + expect(entry.status).toBe("failed") + expect(entry.error).toBe("api exploded") + }) + }) + + describe("running transition (F-09)", () => { + it("reports a child as running once the scheduler permit is acquired", async () => { + const parent = new FakeParentTask("parent-1") + seedRegistry(provider, parent) + seedParentRecord("parent-1") + + runTracker.block() + const started: BackgroundChildEntry[] = [] + const { children } = await provider.spawnBackgroundChildren( + asTask(parent), + [makeSpec("a"), makeSpec("b")], + { onChildStarted: (entry) => started.push(entry) }, + ) + await flush() + + expect(started).toHaveLength(2) + expect(started.every((entry) => entry.status === "running")).toBe(true) + expect(started.every((entry) => typeof entry.startedAt === "number")).toBe(true) + + provider.resolveBackgroundChild(children[0].taskId, "report") + provider.resolveBackgroundChild(children[1].taskId, "report") + const entries = await Promise.all(children.map((child) => child.done)) + + expect(entries.map((entry) => entry.status)).toEqual(["completed", "completed"]) + // Only the queued -> running transition is reported. + expect(started).toHaveLength(2) + }) + + it("does not report a queued child before a permit frees", async () => { + const parent = new FakeParentTask("parent-1") + seedRegistry(provider, parent) + seedParentRecord("parent-1") + + runTracker.block() + const started: string[] = [] + await provider.spawnBackgroundChildren( + asTask(parent), + Array.from({ length: DEFAULT_MAX_PARALLEL_SUBTASKS + 1 }, (_value, index) => + makeSpec(`child-${index}`), + ), + { onChildStarted: (entry) => started.push(entry.taskId) }, + ) + await flush() + expect(started).toHaveLength(DEFAULT_MAX_PARALLEL_SUBTASKS) + + runTracker.releaseAll() + await flush(10) + expect(started).toHaveLength(DEFAULT_MAX_PARALLEL_SUBTASKS + 1) + }) + }) + + describe("cumulative live-children cap (F-17)", () => { + it("rejects specs beyond the per-parent cap across repeated fan-outs", async () => { + const parent = new FakeParentTask("parent-1") + seedRegistry(provider, parent) + seedParentRecord("parent-1") + runTracker.block() + + const first = await spawn( + provider, + parent, + Array.from({ length: MAX_PARALLEL_SUBTASKS_CAP }, (_value, index) => makeSpec(`child-${index}`)), + ) + const second = await spawn(provider, parent, [makeSpec("g"), makeSpec("h")]) + expect(first.children).toHaveLength(MAX_PARALLEL_SUBTASKS_CAP) + expect(second.children).toHaveLength(2) + expect(provider["backgroundTasks"].size).toBe(MAX_LIVE_BACKGROUND_CHILDREN_PER_PARENT) + expect(createdTasks()).toHaveLength(MAX_LIVE_BACKGROUND_CHILDREN_PER_PARENT) + + const third = await spawn(provider, parent, [makeSpec("overflow")]) + + expect(third.children).toHaveLength(1) + expect(createdTasks()).toHaveLength(MAX_LIVE_BACKGROUND_CHILDREN_PER_PARENT) + const entry = await third.children[0].done + expect(entry.status).toBe("failed") + expect(entry.error).toBe( + `Live background child limit reached (${MAX_LIVE_BACKGROUND_CHILDREN_PER_PARENT} per parent)`, + ) + }) + }) + + describe("task numbering across batches (F-19)", () => { + it("never repeats a task number across sequential fan-out batches", async () => { + const parent = new FakeParentTask("parent-1") + seedRegistry(provider, parent) + seedParentRecord("parent-1") + + const first = await spawn(provider, parent, [makeSpec("a"), makeSpec("b")]) + provider.resolveBackgroundChild(first.children[0].taskId, "report") + provider.resolveBackgroundChild(first.children[1].taskId, "report") + await flush() + + const second = await spawn(provider, parent, [makeSpec("c"), makeSpec("d")]) + provider.resolveBackgroundChild(second.children[0].taskId, "report") + provider.resolveBackgroundChild(second.children[1].taskId, "report") + await flush() + + const numbers = createdTasks().map((task) => task.taskNumber) + expect(numbers).toHaveLength(4) + expect(new Set(numbers).size).toBe(numbers.length) + expect(numbers).toEqual([...numbers].sort((left, right) => left - right)) + }) + }) + + describe("abort-hook release (F-21)", () => { + it("releases the idle hook when the spawn throws before any child registers", async () => { + const parent = new FakeParentTask("parent-1") + seedRegistry(provider, parent) + seedParentRecord("parent-1") + // A cross-mode spec loads a saved profile; a throwing profile read + // aborts the batch before the first child exists. (The mode-config id + // lookup itself is covered by its own fallback since CR finding 3.) + provider["loadSavedModeProfile"] = vi.fn().mockRejectedValue(new Error("settings store unavailable")) + + await expect(spawn(provider, parent, [makeSpec("a", "architect")])).rejects.toThrow( + "settings store unavailable", + ) + + expect(parent.listenerCount(RooCodeEventName.TaskAborted)).toBe(0) + expect(provider["backgroundAbortHooks"].size).toBe(0) + }) + }) + + describe("log-injection hardening (F-22)", () => { + it("JSON-encodes a model-controlled label in spawn failure logs", async () => { + const parent = new FakeParentTask("parent-1") + seedRegistry(provider, parent) + seedParentRecord("parent-1") + provider.log = vi.fn() + provider.createTask = vi.fn(async (..._args: Parameters) => { + throw new Error("rejected by the profile check") + }) + + const label = "evil\n[spawnBackgroundChildren] forged line" + const result = await spawn(provider, parent, [makeSpec(label)]) + const entry = await result.children[0].done + + expect(entry.status).toBe("failed") + const logs = (provider.log as ReturnType).mock.calls.map((call) => call[0] as string) + const failureLog = logs.find((line) => line.includes("Failed to create child")) + expect(failureLog).toBeDefined() + expect(failureLog).toContain(JSON.stringify(label)) + expect(failureLog).not.toContain("\n") + }) + }) + + describe("delegation lineage (D-01)", () => { + it("stamps a top-level delegation child with the parent as its root", async () => { + const parent = new FakeParentTask("parent-1") + seedRegistry(provider, parent) + seedParentRecord("parent-1") + + await provider.delegateParentAndOpenChild({ + parentTaskId: "parent-1", + message: "do the thing", + initialTodos: [], + mode: "code", + }) + + const [child] = createdTasks() + expect(child.rawOptions.rootTask?.taskId).toBe("parent-1") + expect(child.rawOptions.rootTaskId).toBeUndefined() + expect(child.rawOptions.parentTask?.taskId).toBe("parent-1") + }) + + it("carries the true root instead of reading the registry after the parent was popped", async () => { + const root = new FakeParentTask("root-1") + const parent = new FakeParentTask("parent-1", "root-1", root) + seedRegistry(provider, parent) + seedParentRecord("parent-1", { rootTaskId: "root-1" }) + + await provider.delegateParentAndOpenChild({ + parentTaskId: "parent-1", + message: "do the thing", + initialTodos: [], + mode: "code", + }) + + // The registry is empty when the child is constructed; the lineage + // root comes from the reference captured before removeClineFromStack. + expect(provider["taskRegistry"].getById("parent-1")).toBeUndefined() + expect(provider["taskRegistry"].getById("root-1")).toBeUndefined() + const [child] = createdTasks() + expect(child.rawOptions.rootTask?.taskId).toBe("root-1") + expect(child.rawOptions.rootTaskId).toBeUndefined() + }) + }) + + describe("restored background child policy (F-05)", () => { + it("re-applies the read-only policy to a history item stamped with backgroundParentTaskId", async () => { + await provider.createTaskWithHistoryItem( + { + ...seedParentRecord("child-1"), + parentTaskId: "parent-1", + backgroundParentTaskId: "parent-1", + }, + { startTask: false }, + ) + + const [restored] = createdTasks() + expect(restored.taskId).toBe("child-1") + // P1-2: the restore path must OMIT the hosted flag so the restored + // child installed as the current stack task stays interactive (state + // posts flow, the resume ask blocks for approval). Only the spawn + // path passes it; the interactivity derivation from the flag is + // covered against the real `Task` in the task-layer suite. + expect(restored.backgroundChildHosted).toBeUndefined() + // F-05: but its read-only policy is preserved on restore. + expect(restored.backgroundToolPolicy?.disabledTools).toEqual(BACKGROUND_CHILD_DISABLED_TOOLS) + expect(restored.backgroundToolPolicy?.experiments).toEqual(BACKGROUND_CHILD_EXPERIMENTS) + }) + + it("leaves a normal history item without the background policy", async () => { + await provider.createTaskWithHistoryItem(seedParentRecord("normal-1"), { startTask: false }) + + const [restored] = createdTasks() + expect(restored.backgroundChildHosted).toBeUndefined() + expect(restored.backgroundToolPolicy).toBeUndefined() + }) + }) + + describe("background scheduler (D7)", () => { + it("runs at most DEFAULT_MAX_PARALLEL_SUBTASKS children concurrently and queues the rest", async () => { + const parent = new FakeParentTask("parent-1") + seedRegistry(provider, parent) + seedParentRecord("parent-1") + + expect(DEFAULT_MAX_PARALLEL_SUBTASKS).toBe(4) + expect(MAX_PARALLEL_SUBTASKS_CAP).toBe(6) + + runTracker.block() + const result = await spawn( + provider, + parent, + Array.from({ length: MAX_PARALLEL_SUBTASKS_CAP }, (_value, index) => makeSpec(`child-${index}`)), + ) + + await flush() + expect(result.children).toHaveLength(MAX_PARALLEL_SUBTASKS_CAP) + expect(runTracker.state.started).toBe(DEFAULT_MAX_PARALLEL_SUBTASKS) + expect(runTracker.state.active).toBe(DEFAULT_MAX_PARALLEL_SUBTASKS) + expect(runTracker.state.maxActive).toBeLessThanOrEqual(MAX_PARALLEL_SUBTASKS_CAP) + + runTracker.releaseAll() + await flush(10) + + expect(runTracker.state.started).toBe(MAX_PARALLEL_SUBTASKS_CAP) + expect(runTracker.state.active).toBe(0) + expect(runTracker.state.maxActive).toBe(DEFAULT_MAX_PARALLEL_SUBTASKS) + }) + }) + + describe("background scheduler permit release (D5 regression)", () => { + // The defect: a background child whose run completes through the D5 path + // never released its scheduler permit, because only the host handle + // settled while the run promise kept looping. After + // DEFAULT_MAX_PARALLEL_SUBTASKS such children, every later background + // child starved. These tests park the mock runs on the tracker gate, so + // the permit can only come back through the terminal-settle path. + it("returns the pool to full availability after DEFAULT_MAX_PARALLEL_SUBTASKS children complete", async () => { + const parent = new FakeParentTask("parent-1") + seedRegistry(provider, parent) + seedParentRecord("parent-1") + + runTracker.block() + const batch = await spawn( + provider, + parent, + Array.from({ length: DEFAULT_MAX_PARALLEL_SUBTASKS }, (_value, index) => makeSpec(`child-${index}`)), + ) + await flush() + expect(runTracker.state.started).toBe(DEFAULT_MAX_PARALLEL_SUBTASKS) + + // D5: every child reported its result while its run is still parked. + for (const child of batch.children) { + provider.resolveBackgroundChild(child.taskId, "report") + } + + const extra = await spawn(provider, parent, [makeSpec("overflow")]) + await flush(10) + + expect(extra.children).toHaveLength(1) + expect(runTracker.state.started).toBe(DEFAULT_MAX_PARALLEL_SUBTASKS + 1) + const entries = await Promise.all(batch.children.map((child) => child.done)) + expect(entries.map((entry) => entry.status)).toEqual(["completed", "completed", "completed", "completed"]) + }) + + it("releases the permits for children aborted mid-run and settles their handles as aborted", async () => { + const parent = new FakeParentTask("parent-1") + seedRegistry(provider, parent) + seedParentRecord("parent-1") + + // Fill the whole pool with parked runs so a permit comes back only + // through the terminal settle, never through run() settling. + runTracker.block() + const first = await spawn( + provider, + parent, + Array.from({ length: DEFAULT_MAX_PARALLEL_SUBTASKS }, (_value, index) => makeSpec(`child-${index}`)), + ) + await flush() + expect(runTracker.state.started).toBe(DEFAULT_MAX_PARALLEL_SUBTASKS) + + parent.emit(RooCodeEventName.TaskAborted) + await flush() + + const entries = await Promise.all(first.children.map((child) => child.done)) + expect(entries.map((entry) => entry.status)).toEqual(["aborted", "aborted", "aborted", "aborted"]) + + // The parked runs have not settled, so the next child starts only + // because each abort released its permit at the terminal settle. A + // live parent is what production hands the freed pool to: the + // aborted parent itself is unspawnable again (abort flag set, spawn + // epoch bumped), and the fake emits the event without recording + // either, so the second spawn goes through a fresh parent on the + // same provider. + const secondParent = new FakeParentTask("parent-2") + seedRegistry(provider, secondParent) + seedParentRecord("parent-2") + const second = await spawn(provider, secondParent, [makeSpec("e")]) + await flush(10) + expect(second.children).toHaveLength(1) + expect(runTracker.state.started).toBe(DEFAULT_MAX_PARALLEL_SUBTASKS + 1) + }) + + it("keeps the completed outcome when the parked run settles late", async () => { + const parent = new FakeParentTask("parent-1") + seedRegistry(provider, parent) + seedParentRecord("parent-1") + + runTracker.block() + const first = await spawn(provider, parent, [makeSpec("a")]) + provider.resolveBackgroundChild(first.children[0].taskId, "report") + const entry = await first.children[0].done + expect(entry.status).toBe("completed") + + // The run settles after the terminal record; nothing may re-settle or + // overwrite the outcome the parent already collected. + runTracker.releaseAll() + await flush(10) + const settled = await first.children[0].done + expect(settled.status).toBe("completed") + expect(settled.result).toBe("report") + }) + }) + + describe("BackgroundSubtaskHost", () => { + it("settles a completed child exactly once with its result", async () => { + const parent = new FakeParentTask("parent-1") + seedRegistry(provider, parent) + seedParentRecord("parent-1") + + const { children } = await spawn(provider, parent, [makeSpec("a")]) + const childId = children[0].taskId + seedChildRecord(childId) + + provider.resolveBackgroundChild(childId, "report body") + provider.resolveBackgroundChild(childId, "second body") + + const entry = await children[0].done + expect(entry.status).toBe("completed") + expect(entry.result).toBe("report body") + expect(entry.finishedAt).toBeTypeOf("number") + expect(provider["backgroundTasks"].has(childId)).toBe(false) + }) + + it("keeps the first outcome when resolve is followed by fail", async () => { + const parent = new FakeParentTask("parent-1") + seedRegistry(provider, parent) + seedParentRecord("parent-1") + + const { children } = await spawn(provider, parent, [makeSpec("a")]) + const childId = children[0].taskId + seedChildRecord(childId) + + provider.resolveBackgroundChild(childId, "report body") + provider.failBackgroundChild(childId, "late failure") + + const entry = await children[0].done + expect(entry.status).toBe("completed") + expect(entry.result).toBe("report body") + expect(entry.error).toBeUndefined() + }) + + it("ignores a failure for a child that was never registered", async () => { + const parent = new FakeParentTask("parent-1") + seedRegistry(provider, parent) + seedParentRecord("parent-1") + + expect(() => provider.failBackgroundChild("unknown-child", "boom")).not.toThrow() + expect(provider["backgroundTasks"].size).toBe(0) + }) + }) + + describe("terminal resource release (CR finding 2)", () => { + it("disposes the child exactly once after a normal completion and keeps its status", async () => { + const parent = new FakeParentTask("parent-1") + seedRegistry(provider, parent) + seedParentRecord("parent-1") + runTracker.block() + + const { children } = await spawn(provider, parent, [makeSpec("a")]) + const childId = children[0].taskId + expect(storeState.items.get(childId)?.status).toBe("active") + + provider.resolveBackgroundChild(childId, "report") + const entry = await children[0].done + await flush(10) + + const child = createdTasks()[0] + expect(entry.status).toBe("completed") + expect(child.dispose).toHaveBeenCalledTimes(1) + // Dispose must not go through the aborted path: that would have + // emitted TaskAborted and let the hook overwrite the status. + expect(child.emit).not.toHaveBeenCalledWith(RooCodeEventName.TaskAborted) + expect(storeState.items.get(childId)?.status).toBe("completed") + }) + + it("disposes the child exactly once after a terminal failure and keeps its status", async () => { + const parent = new FakeParentTask("parent-1") + seedRegistry(provider, parent) + seedParentRecord("parent-1") + + runTracker.failNext("api exploded") + const { children } = await spawn(provider, parent, [makeSpec("explodes")]) + const entry = await children[0].done + await flush(10) + + const child = createdTasks()[0] + expect(entry.status).toBe("failed") + expect(entry.error).toBe("api exploded") + expect(child.dispose).toHaveBeenCalledTimes(1) + expect(child.emit).not.toHaveBeenCalledWith(RooCodeEventName.TaskAborted) + // A failed child has no terminal history status of its own. + expect(storeState.items.get(child.taskId)?.status).toBe("interrupted") + }) + + it("does not release twice when the child's own abort settles it first", async () => { + const parent = new FakeParentTask("parent-1") + seedRegistry(provider, parent) + seedParentRecord("parent-1") + runTracker.block() + + const { children } = await spawn(provider, parent, [makeSpec("a")]) + const childTask = createdTasks()[0] + expect(childTask).toBeDefined() + + // The child aborts itself (API failure, disposal) while the parent + // stays active: the handle must settle through the child's own + // TaskAborted hook, not the parent cascade. + childTask.emit(RooCodeEventName.TaskAborted) + await flush() + + const entry = await children[0].done + expect(entry.status).toBe("aborted") + expect(entry.error).toBe("Background child was aborted") + expect(childTask.dispose).toHaveBeenCalledTimes(1) + // The parent cascade never ran: the parent is untouched and no + // "Parent task was cancelled" settlement overwrote the child reason. + expect(parent.abortTask).not.toHaveBeenCalled() + + // The parked run releasing later must not settle or dispose again. + runTracker.releaseAll() + await flush() + + expect(childTask.dispose).toHaveBeenCalledTimes(1) + expect(provider["backgroundTasks"].size).toBe(0) + }) + }) + + describe("deleting a live background child (CR finding 4)", () => { + it("stops and drains the deleted child before removing history, leaving its sibling running", async () => { + const parent = new FakeParentTask("parent-1") + seedRegistry(provider, parent) + seedParentRecord("parent-1") + runTracker.block() + + const { children } = await spawn(provider, parent, [makeSpec("a"), makeSpec("b")]) + const [target, sibling] = children + const targetTask = createdTasks().find((task) => task.taskId === target.taskId)! + const siblingTask = createdTasks().find((task) => task.taskId === sibling.taskId)! + + let releaseAbort!: () => void + const abortGate = new Promise((resolve) => { + releaseAbort = resolve + }) + targetTask.abortTask.mockImplementation(async () => { + await abortGate + }) + + // Gate disposal separately: `finishBackgroundChild` already calls + // `dispose()`, so an immediately-resolving mock would let the final + // assertions pass even if the deletion path stopped awaiting the + // drain. Deletion must stay blocked until BOTH gates open. + let releaseDispose!: () => void + const disposeGate = new Promise((resolve) => { + releaseDispose = resolve + }) + targetTask.dispose.mockImplementation(async () => { + await disposeGate + }) + + const deleteMany = vi.spyOn(provider.taskHistoryStore, "deleteMany") + vi.spyOn(ShadowCheckpointService, "deleteTask").mockResolvedValue(undefined) + vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) + + const deletion = provider.deleteTaskWithId(target.taskId, false) + try { + await flush() + + // The child is off-stack, so its run must be stopped by the deletion + // path itself; history removal waits for that drain. + expect(targetTask.abortTask).toHaveBeenCalledTimes(1) + expect(deleteMany).not.toHaveBeenCalled() + + releaseAbort() + await flush() + + // The abort has settled, but the drain still awaits the child's + // disposal: history removal must remain blocked. + expect(deleteMany).not.toHaveBeenCalled() + + releaseDispose() + await deletion + + expect(deleteMany).toHaveBeenCalledWith([target.taskId]) + expect(targetTask.dispose).toHaveBeenCalled() + expect(siblingTask.abortTask).not.toHaveBeenCalled() + expect(provider["backgroundTasks"].has(sibling.taskId)).toBe(true) + expect(provider["backgroundTasks"].has(target.taskId)).toBe(false) + } finally { + // A failed assertion must not leave the deletion parked: the suite + // teardown only releases the run tracker, and afterEach's + // provider.dispose() would wait on these same gates forever. + // Promise resolves are idempotent, so the staged releases above + // stay as-is on the success path. + releaseAbort() + releaseDispose() + await deletion + } + }) + }) + + describe("cancel cascade and dispose (D8)", () => { + it("aborts and settles every child when the parent emits TaskAborted", async () => { + const parent = new FakeParentTask("parent-1") + seedRegistry(provider, parent) + seedParentRecord("parent-1") + // Park the runs: the abort must settle live children, not children + // the run-ended catch-all already failed. + runTracker.block() + + const { children } = await spawn(provider, parent, [makeSpec("a"), makeSpec("b")]) + expect(parent.listenerCount(RooCodeEventName.TaskAborted)).toBe(1) + + parent.emit(RooCodeEventName.TaskAborted) + await flush() + + for (const child of createdTasks()) { + expect(child.abortTask).toHaveBeenCalled() + } + + const entries = await Promise.all(children.map((child) => child.done)) + expect(entries.map((entry) => entry.status)).toEqual(["aborted", "aborted"]) + expect(entries.every((entry) => entry.error === "Parent task was cancelled")).toBe(true) + expect(provider["backgroundTasks"].size).toBe(0) + expect(parent.listenerCount(RooCodeEventName.TaskAborted)).toBe(0) + }) + + it("aborts and settles every child on dispose and drains the map", async () => { + const parent = new FakeParentTask("parent-1") + seedRegistry(provider, parent) + seedParentRecord("parent-1") + // Park the runs so dispose, not the run-ended catch-all, settles them. + runTracker.block() + + const { children } = await spawn(provider, parent, [makeSpec("a"), makeSpec("b")]) + provider["taskRegistry"] = new TaskRegistry() + + await provider.dispose() + + expect(provider["backgroundTasks"].size).toBe(0) + for (const child of createdTasks()) { + expect(child.abortTask).toHaveBeenCalled() + } + + const entries = await Promise.all(children.map((child) => child.done)) + expect(entries.map((entry) => entry.status)).toEqual(["aborted", "aborted"]) + }) + + it("does not double-settle a child that resolves before the parent aborts", async () => { + const parent = new FakeParentTask("parent-1") + seedRegistry(provider, parent) + seedParentRecord("parent-1") + // Park the run so only the explicit resolve can settle the handle. + runTracker.block() + + const { children } = await spawn(provider, parent, [makeSpec("a")]) + const childId = children[0].taskId + seedChildRecord(childId) + + provider.resolveBackgroundChild(childId, "done early") + parent.emit(RooCodeEventName.TaskAborted) + await flush() + + const entry = await children[0].done + expect(entry.status).toBe("completed") + expect(entry.result).toBe("done early") + }) + }) + + describe("terminal persistence drains and repair (CR round 5)", () => { + it("dispose waits for a child's abort cascade already in progress before tearing down the history store", async () => { + const parent = new FakeParentTask("parent-1") + seedRegistry(provider, parent) + seedParentRecord("parent-1") + runTracker.block() + + const { children } = await spawn(provider, parent, [makeSpec("a")]) + const child = createdTasks()[0] + + // Hold the child's final save: the cascade below parks inside + // `abortTask`, so disposal can only observe the child through + // `pendingBackgroundChildCleanup`. + let releaseSave!: () => void + let saveEntered!: () => void + const saveGate = new Promise((resolve) => { + releaseSave = resolve + }) + const saveEnteredPromise = new Promise((resolve) => { + saveEntered = resolve + }) + child.abortTask.mockImplementation(async () => { + saveEntered() + await saveGate + }) + + const cascade = provider.abortBackgroundChildren("parent-1") + await saveEnteredPromise + + // dispose()'s own abort pass finds no records — the cascade already + // settled them — so only the drain of `pendingBackgroundChildCleanup` + // keeps the teardown ordered after the held final save. + provider["taskRegistry"] = new TaskRegistry() + const storeDispose = vi.spyOn(provider.taskHistoryStore, "dispose") + let disposalSettled = false + const disposal = provider.dispose().then(() => { + disposalSettled = true + }) + await flush() + + expect(disposalSettled).toBe(false) + expect(storeDispose).not.toHaveBeenCalled() + + releaseSave() + await cascade + await disposal + + expect(storeDispose).toHaveBeenCalledTimes(1) + const entry = await children[0].done + expect(entry.status).toBe("aborted") + }) + + it("dispose waits for a child's in-flight terminal write before tearing down the history store", async () => { + const parent = new FakeParentTask("parent-1") + seedRegistry(provider, parent) + seedParentRecord("parent-1") + runTracker.block() + + const { children } = await spawn(provider, parent, [makeSpec("a")]) + const childId = children[0].taskId + + // Park the terminal write itself: settlement is synchronous, so the + // record is gone while its history write is still in flight. + const store = provider.taskHistoryStore + const originalReadAndUpdate = store.atomicReadAndUpdate.bind(store) + let releaseWrite!: () => void + const writeGate = new Promise((resolve) => { + releaseWrite = resolve + }) + store.atomicReadAndUpdate = vi.fn(async (taskId: string, update: (item: HistoryItem) => HistoryItem) => { + if (taskId === childId) { + await writeGate + } + return originalReadAndUpdate(taskId, update) + }) + + provider.resolveBackgroundChild(childId, "done") + await flush() + + provider["taskRegistry"] = new TaskRegistry() + const storeDispose = vi.spyOn(provider.taskHistoryStore, "dispose") + let disposalSettled = false + const disposal = provider.dispose().then(() => { + disposalSettled = true + }) + await flush() + + expect(disposalSettled).toBe(false) + expect(storeDispose).not.toHaveBeenCalled() + + releaseWrite() + await disposal + + expect(storeDispose).toHaveBeenCalledTimes(1) + expect(provider["pendingBackgroundTerminalWrites"].size).toBe(0) + expect(storeState.items.get(childId)?.status).toBe("completed") + }) + + it("records an exhausted terminal write for repair, retries it on the next pass, and logs every failure", async () => { + const parent = new FakeParentTask("parent-1") + seedRegistry(provider, parent) + seedParentRecord("parent-1") + runTracker.block() + + const { children } = await spawn(provider, parent, [makeSpec("a")]) + const childId = children[0].taskId + + const store = provider.taskHistoryStore + const originalReadAndUpdate = store.atomicReadAndUpdate.bind(store) + let childWritesFail = true + store.atomicReadAndUpdate = vi.fn(async (taskId: string, update: (item: HistoryItem) => HistoryItem) => { + if (taskId === childId && childWritesFail) { + throw new Error("persistent store failure") + } + return originalReadAndUpdate(taskId, update) + }) + + provider.resolveBackgroundChild(childId, "done") + // The bounded retry runs behind settlement (`delay` is mocked to an + // immediate resolve), so a flush is enough for all three attempts to + // fail and the repair to be recorded. + await flush() + + // The write never landed: the row is still `active`, and the + // exhausted write is recorded for the next repair pass instead of + // being abandoned. + expect(storeState.items.get(childId)?.status).toBe("active") + expect(provider["pendingBackgroundTerminalRepairs"].get(childId)).toMatchObject({ + taskId: childId, + status: "completed", + }) + + // Every attempt failed and the give-up is logged, never silent. + const logs = vi.mocked(mockOutputChannel.appendLine).mock.calls.map((call) => String(call[0])) + expect( + logs.some((line) => line.includes(`Persisting terminal state for ${childId} failed (attempt 1/3)`)), + ).toBe(true) + expect( + logs.some((line) => line.includes(`Persisting terminal state for ${childId} failed (attempt 3/3)`)), + ).toBe(true) + expect(logs.some((line) => line.includes(`Giving up persisting terminal state for ${childId}`))).toBe(true) + + // The store recovers; the next repair pass lands exactly the write + // a first-attempt success would have made. + childWritesFail = false + await provider["flushPendingBackgroundTerminalRepairs"]() + expect(storeState.items.get(childId)?.status).toBe("completed") + expect(provider["pendingBackgroundTerminalRepairs"].size).toBe(0) + }) + + it("logs when the terminal write finds no history record", async () => { + const parent = new FakeParentTask("parent-1") + seedRegistry(provider, parent) + seedParentRecord("parent-1") + runTracker.block() + + const { children } = await spawn(provider, parent, [makeSpec("a")]) + const childId = children[0].taskId + + // The row disappears between registration and settlement (e.g. its + // registration upsert kept failing); the skipped write must say so + // instead of returning silently. + storeState.items.delete(childId) + + provider.resolveBackgroundChild(childId, "done") + await flush() + + const logs = vi.mocked(mockOutputChannel.appendLine).mock.calls.map((call) => String(call[0])) + expect( + logs.some((line) => + line.includes(`Not persisting terminal state for ${childId}: no history record exists`), + ), + ).toBe(true) + }) + }) + + describe("depth-1 guarantee and store wiring", () => { + it("blocks parallel_subtasks for every child (structural depth-1)", async () => { + const parent = new FakeParentTask("parent-1") + seedRegistry(provider, parent) + seedParentRecord("parent-1") + + await spawn(provider, parent, [makeSpec("a")]) + + expect(BACKGROUND_CHILD_DISABLED_TOOLS).toContain("parallel_subtasks") + const [child] = createdTasks() + expect(child.backgroundToolPolicy?.disabledTools).toContain("parallel_subtasks") + }) + + it("exposes the live background map through isLiveBackgroundChild", async () => { + const options = storeState.constructorOptions[0] as + { isLiveBackgroundChild?: (taskId: string) => boolean } | undefined + expect(options?.isLiveBackgroundChild).toBeTypeOf("function") + + const parent = new FakeParentTask("parent-1") + seedRegistry(provider, parent) + seedParentRecord("parent-1") + + const { children } = await spawn(provider, parent, [makeSpec("a")]) + + expect(options?.isLiveBackgroundChild?.(children[0].taskId)).toBe(true) + expect(options?.isLiveBackgroundChild?.("some-other-task")).toBe(false) + }) + }) +}) + +function seedChildRecord(childTaskId: string): void { + storeState.items.set(childTaskId, { + id: childTaskId, + number: 2, + ts: 2, + task: "Child task", + tokensIn: 0, + tokensOut: 0, + totalCost: 0, + status: "active", + backgroundParentTaskId: "parent-1", + }) +} diff --git a/src/core/webview/__tests__/webviewMessageHandler.openDebugHistory.spec.ts b/src/core/webview/__tests__/webviewMessageHandler.openDebugHistory.spec.ts new file mode 100644 index 0000000000..b3398fbc7c --- /dev/null +++ b/src/core/webview/__tests__/webviewMessageHandler.openDebugHistory.spec.ts @@ -0,0 +1,214 @@ +// npx vitest core/webview/__tests__/webviewMessageHandler.openDebugHistory.spec.ts + +import { describe, it, expect, vi, beforeEach } from "vitest" +import * as nodePath from "path" +import * as os from "os" +import * as vscode from "vscode" + +import { webviewMessageHandler } from "../webviewMessageHandler" +import { getTaskDirectoryPath } from "../../../utils/storage" +import { fileExistsAtPath } from "../../../utils/fs" +import type { ClineProvider } from "../ClineProvider" +import type { Task } from "../../task/Task" + +vi.mock("../../../api/providers/fetchers/modelCache") + +vi.mock("vscode", () => ({ + window: { + showInformationMessage: vi.fn(), + showErrorMessage: vi.fn(), + showTextDocument: vi.fn(), + }, + workspace: { + openTextDocument: vi.fn().mockResolvedValue({}), + }, + commands: { + executeCommand: vi.fn(), + }, +})) + +vi.mock("../../../i18n", () => ({ + t: vi.fn((key: string, params?: Record) => (params ? `${key}:${JSON.stringify(params)}` : key)), +})) + +vi.mock("fs/promises", async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + readFile: vi.fn().mockResolvedValue(JSON.stringify({ hello: "world" })), + writeFile: vi.fn().mockResolvedValue(undefined), + } +}) + +// The handler only needs fileExistsAtPath from this module; keep every other +// export real so the rest of the module graph loads unchanged. +vi.mock("../../../utils/fs", async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + fileExistsAtPath: vi.fn().mockResolvedValue(true), + } +}) + +// Resolve child task directories deterministically and record the taskId the +// handler asked for; this is the assertion target of the taskId routing. +vi.mock("../../../utils/storage", async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + getTaskDirectoryPath: vi.fn( + async (_globalStoragePath: string, taskId: string) => `/mock/global/storage/tasks/${taskId}`, + ), + } +}) + +const CURRENT_TASK_ID = "current-task-id-0000" +const CHILD_TASK_ID = "child-1234567890" + +const mockProvider = { + getState: vi.fn(), + postMessageToWebview: vi.fn(), + contextProxy: { + globalStorageUri: { fsPath: "/mock/global/storage" }, + setValue: vi.fn(), + getValue: vi.fn(), + }, + log: vi.fn(), + postStateToWebview: vi.fn(), + getCurrentTask: vi.fn(), +} as unknown as ClineProvider + +describe("webviewMessageHandler - openDebugApiHistory/openDebugUiHistory taskId routing", () => { + beforeEach(() => { + vi.clearAllMocks() + vi.mocked(fileExistsAtPath).mockResolvedValue(true) + }) + + it("opens the requested child's ui log even when no current task exists", async () => { + vi.mocked(mockProvider.getCurrentTask).mockReturnValue(undefined) + + await webviewMessageHandler(mockProvider, { + type: "openDebugUiHistory", + taskId: CHILD_TASK_ID, + }) + + expect(getTaskDirectoryPath).toHaveBeenCalledWith("/mock/global/storage", CHILD_TASK_ID) + const fsPromises = await import("fs/promises") + expect(fsPromises.readFile).toHaveBeenCalledWith( + nodePath.join(`/mock/global/storage/tasks/${CHILD_TASK_ID}`, "ui_messages.json"), + "utf8", + ) + expect(fsPromises.writeFile).toHaveBeenCalledWith( + expect.stringMatching(/roo-debug-ui-child-12-\d+\.json$/), + JSON.stringify({ hello: "world" }, null, 2), + "utf8", + ) + const writtenPath = String(vi.mocked(fsPromises.writeFile).mock.calls[0][0]) + expect(writtenPath.startsWith(os.tmpdir())).toBe(true) + expect(vscode.workspace.openTextDocument).toHaveBeenCalled() + expect(vscode.window.showTextDocument).toHaveBeenCalledWith({}, { preview: true }) + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled() + }) + + it("falls back to the current task's id when the message omits taskId", async () => { + vi.mocked(mockProvider.getCurrentTask).mockReturnValue({ taskId: CURRENT_TASK_ID } as Task) + + await webviewMessageHandler(mockProvider, { type: "openDebugUiHistory" }) + + expect(getTaskDirectoryPath).toHaveBeenCalledWith("/mock/global/storage", CURRENT_TASK_ID) + const fsPromises = await import("fs/promises") + expect(fsPromises.readFile).toHaveBeenCalledWith( + nodePath.join(`/mock/global/storage/tasks/${CURRENT_TASK_ID}`, "ui_messages.json"), + "utf8", + ) + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled() + }) + + it("prefers the explicit taskId over the current task", async () => { + vi.mocked(mockProvider.getCurrentTask).mockReturnValue({ taskId: CURRENT_TASK_ID } as Task) + + await webviewMessageHandler(mockProvider, { + type: "openDebugApiHistory", + taskId: CHILD_TASK_ID, + }) + + expect(getTaskDirectoryPath).toHaveBeenCalledWith("/mock/global/storage", CHILD_TASK_ID) + const fsPromises = await import("fs/promises") + expect(fsPromises.readFile).toHaveBeenCalledWith( + nodePath.join(`/mock/global/storage/tasks/${CHILD_TASK_ID}`, "api_conversation_history.json"), + "utf8", + ) + expect(fsPromises.writeFile).toHaveBeenCalledWith( + expect.stringMatching(/roo-debug-api-child-12-\d+\.json$/), + expect.any(String), + "utf8", + ) + }) + + it("keeps the no-active-task error when neither taskId nor current task exists", async () => { + vi.mocked(mockProvider.getCurrentTask).mockReturnValue(undefined) + + await webviewMessageHandler(mockProvider, { type: "openDebugApiHistory" }) + + expect(getTaskDirectoryPath).not.toHaveBeenCalled() + const fsPromises = await import("fs/promises") + expect(fsPromises.readFile).not.toHaveBeenCalled() + expect(vscode.window.showErrorMessage).toHaveBeenCalledWith("No active task to view history for") + }) + + it.each(["openDebugApiHistory", "openDebugUiHistory"] as const)( + "rejects a traversal taskId for %s with no filesystem access and no fallback to the current task", + async (type) => { + // A current task exists: the guard must not fall back to it either. + vi.mocked(mockProvider.getCurrentTask).mockReturnValue({ taskId: CURRENT_TASK_ID } as Task) + + await webviewMessageHandler(mockProvider, { + type, + taskId: "../../other-uuid-1234", + }) + + expect(vscode.window.showErrorMessage).toHaveBeenCalledWith("Invalid task id for debug history") + expect(getTaskDirectoryPath).not.toHaveBeenCalled() + const fsPromises = await import("fs/promises") + expect(fsPromises.readFile).not.toHaveBeenCalled() + expect(fsPromises.writeFile).not.toHaveBeenCalled() + expect(vscode.workspace.openTextDocument).not.toHaveBeenCalled() + expect(mockProvider.log).toHaveBeenCalledWith( + expect.stringContaining("Rejected debug history request with unsafe taskId"), + ) + }, + ) + + it("rejects a taskId over 128 characters", async () => { + vi.mocked(mockProvider.getCurrentTask).mockReturnValue(undefined) + + await webviewMessageHandler(mockProvider, { + type: "openDebugUiHistory", + taskId: "a".repeat(129), + }) + + expect(vscode.window.showErrorMessage).toHaveBeenCalledWith("Invalid task id for debug history") + expect(getTaskDirectoryPath).not.toHaveBeenCalled() + }) + + it("accepts a max-length taskId using the full allowed alphabet", async () => { + const validId = "Aa0_-".repeat(25) + "ABC" // 128 chars of [A-Za-z0-9_-] + expect(validId).toHaveLength(128) + vi.mocked(mockProvider.getCurrentTask).mockReturnValue(undefined) + + await webviewMessageHandler(mockProvider, { + type: "openDebugApiHistory", + taskId: validId, + }) + + expect(getTaskDirectoryPath).toHaveBeenCalledWith("/mock/global/storage", validId) + const fsPromises = await import("fs/promises") + expect(fsPromises.readFile).toHaveBeenCalled() + expect(fsPromises.writeFile).toHaveBeenCalledWith( + expect.stringMatching(new RegExp(`roo-debug-api-${validId.slice(0, 8)}-\\d+\\.json$`)), + expect.any(String), + "utf8", + ) + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled() + }) +}) diff --git a/src/core/webview/webviewMessageHandler.ts b/src/core/webview/webviewMessageHandler.ts index d20efcb9db..5396f04694 100644 --- a/src/core/webview/webviewMessageHandler.ts +++ b/src/core/webview/webviewMessageHandler.ts @@ -47,6 +47,7 @@ import { findOriginalContent } from "./stripOriginalContent" import { handleCheckpointRestoreOperation } from "./checkpointRestoreHandler" import { assertRecordedCheckpoint } from "../checkpoints/recordedCheckpoint" import { generateErrorDiagnostics } from "./diagnosticsHandler" +import { isSafeTaskId } from "../../services/diagnostics/persistence" import { handleRequestSkills, handleCreateSkill, @@ -4179,15 +4180,31 @@ export const webviewMessageHandler = async ( case "openDebugApiHistory": case "openDebugUiHistory": { const currentTask = provider.getCurrentTask() - if (!currentTask) { + // A child task's debug log can be requested long after the child + // stopped being the active task, so an explicit taskId wins over + // the current task; only fall back when the caller omits it. + const targetTaskId = message.taskId ?? currentTask?.taskId + if (!targetTaskId) { vscode.window.showErrorMessage("No active task to view history for") break } + // The task id is webview-supplied and flows into path.join plus an + // fs.mkdir under global storage, so anything outside the + // host-generated id shape is rejected outright. There is no + // fallback to the current task: a traversal payload must not be + // routed to the filesystem, and silently substituting another id + // would hide the attack. + if (!isSafeTaskId(targetTaskId)) { + provider.log(`Rejected debug history request with unsafe taskId ${JSON.stringify(targetTaskId)}`) + vscode.window.showErrorMessage("Invalid task id for debug history") + break + } + try { const { getTaskDirectoryPath } = await import("../../utils/storage") const globalStoragePath = provider.contextProxy.globalStorageUri.fsPath - const taskDirPath = await getTaskDirectoryPath(globalStoragePath, currentTask.taskId) + const taskDirPath = await getTaskDirectoryPath(globalStoragePath, targetTaskId) const fileName = message.type === "openDebugApiHistory" ? "api_conversation_history.json" : "ui_messages.json" @@ -4216,7 +4233,7 @@ export const webviewMessageHandler = async ( // Create a temporary file const tmpDir = os.tmpdir() const timestamp = Date.now() - const tempFileName = `roo-debug-${message.type === "openDebugApiHistory" ? "api" : "ui"}-${currentTask.taskId.slice(0, 8)}-${timestamp}.json` + const tempFileName = `roo-debug-${message.type === "openDebugApiHistory" ? "api" : "ui"}-${targetTaskId.slice(0, 8)}-${timestamp}.json` const tempFilePath = path.join(tmpDir, tempFileName) await fs.writeFile(tempFilePath, prettifiedContent, "utf8") diff --git a/src/services/diagnostics/__tests__/persistence.spec.ts b/src/services/diagnostics/__tests__/persistence.spec.ts index e96858cb4e..568de0c9a5 100644 --- a/src/services/diagnostics/__tests__/persistence.spec.ts +++ b/src/services/diagnostics/__tests__/persistence.spec.ts @@ -4,7 +4,7 @@ import * as path from "path" import type { HistoryItem } from "@roo-code/types" -import { collectPersistenceDiagnostics } from "../persistence" +import { collectPersistenceDiagnostics, isSafeTaskId } from "../persistence" vi.mock("fs/promises", { spy: true }) @@ -232,3 +232,29 @@ describe("collectPersistenceDiagnostics", () => { expect(result.tasks.every((task) => task.integrityFindings.includes("parentCycle"))).toBe(true) }) }) + +describe("isSafeTaskId", () => { + it.each([ + ["a plain task id", "task-1_abc-DEF", true], + ["a 128-char id", "a".repeat(128), true], + ["an empty string", "", false], + ["a 129-char id", "a".repeat(129), false], + ["a traversal attempt", "../outside", false], + ["an absolute path", "/absolute", false], + ["a dotted name", "has.dot", false], + ["a name with a space", "has space", false], + ])("classifies %s", (_label, value, expected) => { + expect(isSafeTaskId(value)).toBe(expected) + }) + + it("rejects non-string inputs instead of coercing them through the regex", () => { + // RegExp.test stringifies its input, so these values would otherwise match: + // "12345", "true", "abc-DEF" (array join), and the object's toString. + expect(isSafeTaskId(12345)).toBe(false) + expect(isSafeTaskId(true)).toBe(false) + expect(isSafeTaskId(["abc-DEF"])).toBe(false) + expect(isSafeTaskId({ toString: () => "abc-DEF" })).toBe(false) + expect(isSafeTaskId(null)).toBe(false) + expect(isSafeTaskId(undefined)).toBe(false) + }) +}) diff --git a/src/services/diagnostics/persistence.ts b/src/services/diagnostics/persistence.ts index cb07e01abb..d9da761864 100644 --- a/src/services/diagnostics/persistence.ts +++ b/src/services/diagnostics/persistence.ts @@ -64,8 +64,8 @@ function isHistoryItem(value: unknown): value is HistoryItem { return value !== null && typeof value === "object" && "id" in value && typeof value.id === "string" } -function isSafeTaskId(value: string): boolean { - return /^[A-Za-z0-9_-]{1,128}$/.test(value) +export function isSafeTaskId(value: unknown): value is string { + return typeof value === "string" && /^[A-Za-z0-9_-]{1,128}$/.test(value) } function hasParentCycle(item: HistoryItem, byId: Map): boolean { diff --git a/src/shared/__tests__/experiments.spec.ts b/src/shared/__tests__/experiments.spec.ts index b6e8993df4..b2efba7387 100644 --- a/src/shared/__tests__/experiments.spec.ts +++ b/src/shared/__tests__/experiments.spec.ts @@ -22,6 +22,7 @@ describe("experiments", () => { runSlashCommand: false, customTools: false, parallelToolExecution: false, + parallelSubtasks: false, dynamicThinkingEffort: false, } expect(Experiments.isEnabled(experiments, EXPERIMENT_IDS.PREVENT_FOCUS_DISRUPTION)).toBe(false) @@ -34,6 +35,7 @@ describe("experiments", () => { runSlashCommand: false, customTools: false, parallelToolExecution: false, + parallelSubtasks: false, dynamicThinkingEffort: false, } expect(Experiments.isEnabled(experiments, EXPERIMENT_IDS.PREVENT_FOCUS_DISRUPTION)).toBe(true) @@ -46,6 +48,7 @@ describe("experiments", () => { runSlashCommand: false, customTools: false, parallelToolExecution: false, + parallelSubtasks: false, dynamicThinkingEffort: false, } expect(Experiments.isEnabled(experiments, EXPERIMENT_IDS.PREVENT_FOCUS_DISRUPTION)).toBe(false) diff --git a/src/shared/__tests__/parallelSubtasksExperiment.spec.ts b/src/shared/__tests__/parallelSubtasksExperiment.spec.ts new file mode 100644 index 0000000000..5884a1fa06 --- /dev/null +++ b/src/shared/__tests__/parallelSubtasksExperiment.spec.ts @@ -0,0 +1,65 @@ +// npx vitest run src/shared/__tests__/parallelSubtasksExperiment.spec.ts + +import { experimentIds, experimentIdsSchema, experimentsSchema } from "@roo-code/types" + +import { EXPERIMENT_IDS, experimentConfigsMap, experimentDefault, experiments } from "../experiments" + +describe("PARALLEL_SUBTASKS experiment", () => { + it("registers the id and the config entry", () => { + expect(EXPERIMENT_IDS.PARALLEL_SUBTASKS).toBe("parallelSubtasks") + expect(experimentConfigsMap.PARALLEL_SUBTASKS).toMatchObject({ enabled: false, showInSettings: true }) + }) + + it("is off by default and follows the explicit value when present", () => { + expect(experimentDefault.parallelSubtasks).toBe(false) + expect(experiments.isEnabled({}, "parallelSubtasks")).toBe(false) + expect(experiments.isEnabled({ parallelSubtasks: false }, "parallelSubtasks")).toBe(false) + expect(experiments.isEnabled({ parallelSubtasks: true }, "parallelSubtasks")).toBe(true) + }) + + it("stays independent of parallelToolExecution", () => { + expect(experiments.isEnabled({ parallelToolExecution: true }, "parallelSubtasks")).toBe(false) + expect(experiments.isEnabled({ parallelSubtasks: true }, "parallelToolExecution")).toBe(false) + }) + + it("leaves every other experiment default unchanged", () => { + expect(experimentDefault).toEqual({ + preventFocusDisruption: false, + imageGeneration: false, + runSlashCommand: false, + customTools: false, + parallelToolExecution: false, + parallelSubtasks: false, + dynamicThinkingEffort: false, + }) + }) +}) + +describe("experimentsSchema parallelSubtasks round trip", () => { + it("admits the id through the enum", () => { + expect(experimentIds).toContain("parallelSubtasks") + expect(experimentIdsSchema.parse("parallelSubtasks")).toBe("parallelSubtasks") + }) + + it("parses the enabled, disabled and absent states", () => { + expect(experimentsSchema.parse({ parallelSubtasks: true })).toEqual({ parallelSubtasks: true }) + expect(experimentsSchema.parse({ parallelSubtasks: false })).toEqual({ parallelSubtasks: false }) + expect(experimentsSchema.parse({})).toEqual({}) + }) + + it("strips an unknown key rather than rejecting it", () => { + expect(experimentsSchema.parse({ parallelSubtasks: true, notAnExperiment: true })).toEqual({ + parallelSubtasks: true, + }) + }) + + it("rejects a non-boolean value", () => { + expect(experimentsSchema.safeParse({ parallelSubtasks: "yes" }).success).toBe(false) + }) + + it("accepts every registered experiment id", () => { + for (const id of experimentIds) { + expect(experimentsSchema.safeParse({ [id]: true }).success).toBe(true) + } + }) +}) diff --git a/src/shared/experiments.ts b/src/shared/experiments.ts index c0d461a454..d2b89a4344 100644 --- a/src/shared/experiments.ts +++ b/src/shared/experiments.ts @@ -6,6 +6,7 @@ export const EXPERIMENT_IDS = { RUN_SLASH_COMMAND: "runSlashCommand", CUSTOM_TOOLS: "customTools", PARALLEL_TOOL_EXECUTION: "parallelToolExecution", + PARALLEL_SUBTASKS: "parallelSubtasks", DYNAMIC_THINKING_EFFORT: "dynamicThinkingEffort", } as const satisfies Record @@ -26,6 +27,11 @@ export const experimentConfigsMap: Record = { CUSTOM_TOOLS: { enabled: false }, // TODO: add i18n keys (settings:experimental.PARALLEL_TOOL_EXECUTION.name/.description) in the same PR that sets showInSettings: true PARALLEL_TOOL_EXECUTION: { enabled: false, showInSettings: false }, + // Rollout gate for the parallel_subtasks tool (design §14). The Settings + // label/description keys (settings:experimental.PARALLEL_SUBTASKS.*) live in + // the webview locale bundles and ship with the feature, so the Settings + // panel can render this entry. + PARALLEL_SUBTASKS: { enabled: false, showInSettings: true }, DYNAMIC_THINKING_EFFORT: { enabled: false }, } diff --git a/src/shared/tools.ts b/src/shared/tools.ts index 6d2e9422ee..828810cba3 100644 --- a/src/shared/tools.ts +++ b/src/shared/tools.ts @@ -97,6 +97,9 @@ export const toolParamNames = [ // read_file legacy format parameter (backward compatibility) "files", "line_ranges", + // parallel_subtasks parameters + "tasks", + "label", ] as const export type ToolParamName = (typeof toolParamNames)[number] @@ -119,6 +122,7 @@ export type NativeToolArgs = { apply_patch: { patch: string } list_files: { path: string; recursive?: boolean } new_task: { mode: string; message: string; todos?: string } + parallel_subtasks: { tasks: Array<{ label?: string; mode: string; message: string }> } ask_followup_question: { question: string follow_up: Array<{ text: string; mode?: string }> @@ -216,6 +220,9 @@ export const ALWAYS_AVAILABLE_TOOLS: ToolName[] = [ "attempt_completion", "switch_mode", "new_task", + // Advertised in every mode; the tool-policy layer must drop it while the + // experiment flag is off so the flag actually un-advertises it. + "parallel_subtasks", "update_todo_list", "run_slash_command", "skill", diff --git a/webview-ui/playwright/gallery/stories.tsx b/webview-ui/playwright/gallery/stories.tsx index effe2c43e2..9deead0f10 100644 --- a/webview-ui/playwright/gallery/stories.tsx +++ b/webview-ui/playwright/gallery/stories.tsx @@ -343,6 +343,117 @@ export const stories: Record = { await import("@/components/settings/__tests__/OpencodeGoTemperature.visual.fixture") return }, + "parallel-subtasks-approval": async () => { + const [{ AppProviders }, { ChatRowContent }] = await Promise.all([ + import("../AppProviders"), + import("@/components/chat/ChatRow"), + ]) + // The host serializes the single approval ask as `{ tool, tasks }` before any + // child exists, so ChatRow renders ParallelSubtasksPreview from this payload. + const message: import("@roo-code/types").ClineMessage = { + type: "ask", + ask: "tool", + ts: 0, + text: JSON.stringify({ + tool: "parallelSubtasks", + tasks: [ + { + label: "Trace the parser", + mode: "code", + message: "Find where the lexer drops template literals and list the call sites.", + }, + { + label: "Audit locale coverage", + mode: "code", + message: "Confirm every locale file ships the parallelSubtasks keys.", + }, + { + label: "Check the MCP index", + mode: "debug", + message: "Reproduce the stale tool lookup after the server reconnects.", + }, + ], + }), + } + return ( + +
+ undefined} + onSuggestionClick={() => undefined} + onBatchFileResponse={() => undefined} + onFollowUpUnmount={() => undefined} + isFollowUpAnswered={false} + /> +
+
+ ) + }, + "parallel-subtasks-progress": async () => { + const [{ AppProviders }, { ChatRowContent }] = await Promise.all([ + import("../AppProviders"), + import("@/components/chat/ChatRow"), + ]) + // The visual test freezes the clock at this time so the running row's + // elapsed badge (startedAt below) stays stable across runs. + const now = new Date("2026-06-01T12:00:45Z").getTime() + const subtasks: import("@roo-code/types").ParallelSubtaskInfo[] = [ + { + taskId: "child-parser", + label: "Trace the parser", + mode: "code", + status: "running", + startedAt: now - 45_000, + }, + { + taskId: "child-locales", + label: "Audit locale coverage", + mode: "code", + status: "completed", + reportPath: "/workspace/demo/.zoocode/subtask-reports/task-1/audit-locale-coverage-child-locales.md", + summary: "All 16 locales ship the parallelSubtasks keys.", + }, + { + taskId: "child-mcp", + label: "Check the MCP index", + mode: "debug", + status: "failed", + error: 'Mode "debug" is not allowed for parallel subtasks.', + }, + ] + const message: import("@roo-code/types").ClineMessage = { + type: "say", + say: "tool", + ts: 0, + text: JSON.stringify({ tool: "parallelSubtasks", subtasks }), + partial: true, + } + return ( + +
+ undefined} + onSuggestionClick={() => undefined} + onBatchFileResponse={() => undefined} + onFollowUpUnmount={() => undefined} + isFollowUpAnswered={false} + /> +
+
+ ) + }, "rendered-content-contrast": async () => { const [{ AppProviders }, { RenderedContentContrastFixture }] = await Promise.all([ import("../AppProviders"), diff --git a/webview-ui/src/components/chat/ChatRow.tsx b/webview-ui/src/components/chat/ChatRow.tsx index f427ede478..23be03ec1f 100644 --- a/webview-ui/src/components/chat/ChatRow.tsx +++ b/webview-ui/src/components/chat/ChatRow.tsx @@ -27,6 +27,7 @@ import { formatPathTooltip } from "@src/utils/formatPathTooltip" import { ToolUseBlock, ToolUseBlockHeader } from "../common/ToolUseBlock" import UpdateTodoListToolBlock from "./UpdateTodoListToolBlock" +import ParallelSubtasksBlock, { ParallelSubtasksPreview, type ParallelSubtaskRequest } from "./ParallelSubtasksBlock" import { TodoChangeDisplay } from "./TodoChangeDisplay" import CodeAccordion from "../common/CodeAccordion" import MarkdownBlock from "../common/MarkdownBlock" @@ -118,6 +119,27 @@ function isNewTaskMessage(message: ClineMessage): boolean { return message.ask === "tool" && safeJsonParse(message.text)?.tool === "newTask" } +/** + * Ids of background children, read from the parent's `parallelSubtasks` panel + * rows. Background children are registered in the parent's `childIds` but never + * produce a `newTask` ask or a `subtask_result` row, so they must not shift the + * positional fallback below (F-07). + */ +function getBackgroundChildIds(messages: ClineMessage[]): Set { + const ids = new Set() + for (const message of messages) { + if (message.type !== "say" || message.say !== "tool") continue + // Cheap pre-filter only; the parsed tool field below is the identity test. + if (!message.text?.includes('"parallelSubtasks"')) continue + const tool = safeJsonParse(message.text) + if (tool?.tool !== "parallelSubtasks") continue + for (const subtask of tool.subtasks ?? []) { + ids.add(subtask.taskId) + } + } + return ids +} + function getLinkedChildTaskId( message: ClineMessage, messages: ClineMessage[], @@ -141,7 +163,11 @@ function getLinkedChildTaskId( return completedByChildId } - const childTaskId = childIds[precedingNewTasks.length - 1] + // Background children sit in `childIds` without a delegation row of their own, + // so remove them before indexing by serial delegation count (F-07). + const backgroundChildIds = getBackgroundChildIds(messages) + const serialChildIds = childIds.filter((candidate) => !backgroundChildIds.has(candidate)) + const childTaskId = serialChildIds[precedingNewTasks.length - 1] // Rejected asks must not borrow a child explicitly assigned to another approval. const isAssignedToAnotherAsk = messages.some( (candidate) => isNewTaskMessage(candidate) && candidate.childTaskId === childTaskId, @@ -933,6 +959,14 @@ export const ChatRowContent = ({ ) + case "parallelSubtasks": { + // Design §11's single approval point: no child exists before the + // ask is approved, so the payload carries the requested tasks + // rather than the say-side `subtasks` rows (F-06). + const request = safeJsonParse<{ tasks?: ParallelSubtaskRequest[] }>(message.text) + const tasks = Array.isArray(request?.tasks) ? request.tasks : [] + return + } case "finishTask": return ( <> @@ -1604,6 +1638,17 @@ export const ChatRowContent = ({ ) } + case "parallelSubtasks": { + // Registered case shipped with the panel component so the + // say-tool row never falls into the default (F10). + return ( + + ) + } default: return null } diff --git a/webview-ui/src/components/chat/ParallelSubtasksBlock.tsx b/webview-ui/src/components/chat/ParallelSubtasksBlock.tsx new file mode 100644 index 0000000000..6eba09c80b --- /dev/null +++ b/webview-ui/src/components/chat/ParallelSubtasksBlock.tsx @@ -0,0 +1,378 @@ +import React, { useEffect, useState } from "react" +import type { ParallelSubtaskInfo } from "@roo-code/types" + +import { useAppTranslation } from "@src/i18n/TranslationContext" +import { vscode } from "@src/utils/vscode" + +import { Button, StandardTooltip } from "@/components/ui" + +interface ParallelSubtasksBlockProps { + subtasks: ParallelSubtaskInfo[] + partial: boolean + /** + * Ids of every child this parent registered in task history. Rows whose id + * is absent have no task behind them: `dropped-N` rows and the random ids + * `failedBackgroundHandle` mints for rejected specs never reach the history + * store, so their navigation/debug buttons would open (and, for the debug + * view, create) a task directory that does not exist. Undefined means the + * caller does not know the parent's children yet and the buttons keep their + * previous behavior. + */ + childTaskIds?: readonly string[] +} + +interface StatusVisual { + icon: string + color: string + spin: boolean +} + +// Status visuals follow the terminal-dot convention of sibling tool blocks: +// green for success, red for failure, yellow/blue for in-flight work, and the +// description foreground for inactive states. +const STATUS_VISUALS: Record = { + queued: { icon: "codicon-circle-large-outline", color: "var(--vscode-descriptionForeground)", spin: false }, + running: { icon: "codicon-loading", color: "var(--vscode-charts-blue)", spin: true }, + completed: { icon: "codicon-check", color: "var(--vscode-charts-green)", spin: false }, + failed: { icon: "codicon-x", color: "var(--vscode-charts-red)", spin: false }, + aborted: { icon: "codicon-circle-slash", color: "var(--vscode-descriptionForeground)", spin: false }, +} + +const isTerminal = (status: ParallelSubtaskInfo["status"]) => + status === "completed" || status === "failed" || status === "aborted" + +/** Human-readable duration for the elapsed-time badge, e.g. "45s" or "3m 12s". */ +export const formatElapsed = (ms: number): string => { + const totalSeconds = Math.max(0, Math.floor(ms / 1000)) + const hours = Math.floor(totalSeconds / 3600) + const minutes = Math.floor((totalSeconds % 3600) / 60) + const seconds = totalSeconds % 60 + if (hours > 0) { + return `${hours}h ${minutes}m` + } + if (minutes > 0) { + return `${minutes}m ${seconds}s` + } + return `${seconds}s` +} + +const headerStyle: React.CSSProperties = { + display: "flex", + alignItems: "center", + gap: "8px", + cursor: "default", + marginBottom: "6px", + wordBreak: "break-word", +} + +const rowStyle: React.CSSProperties = { + display: "flex", + flexDirection: "column", + gap: "4px", + padding: "6px 0", + borderTop: "1px solid var(--vscode-editorGroup-border)", +} + +const rowMainStyle: React.CSSProperties = { + display: "flex", + alignItems: "center", + gap: "8px", + minWidth: 0, +} + +const labelStyle: React.CSSProperties = { + flex: 1, + minWidth: 0, + overflow: "hidden", + textOverflow: "ellipsis", + whiteSpace: "nowrap", + fontWeight: 500, + color: "var(--vscode-foreground)", +} + +const modeBadgeStyle: React.CSSProperties = { + flexShrink: 0, + padding: "0 6px", + borderRadius: "4px", + fontSize: "calc(var(--vscode-font-size) - 2px)", + lineHeight: "16px", + background: "var(--vscode-badge-background)", + color: "var(--vscode-badge-foreground)", +} + +const elapsedStyle: React.CSSProperties = { + flexShrink: 0, + fontFamily: "var(--vscode-editor-font-family, monospace)", + fontSize: "calc(var(--vscode-font-size) - 1px)", + color: "var(--vscode-descriptionForeground)", +} + +const terminalLineStyle: React.CSSProperties = { + margin: 0, + paddingLeft: "22px", + fontSize: "calc(var(--vscode-font-size) - 1px)", + color: "var(--vscode-descriptionForeground)", + overflow: "hidden", + textOverflow: "ellipsis", + whiteSpace: "nowrap", +} + +const actionsStyle: React.CSSProperties = { + display: "flex", + alignItems: "center", + gap: "2px", + flexShrink: 0, +} + +const requestMessageStyle: React.CSSProperties = { + margin: 0, + paddingLeft: "22px", + fontSize: "calc(var(--vscode-font-size) - 1px)", + color: "var(--vscode-descriptionForeground)", + overflow: "hidden", + wordBreak: "break-word", +} + +const requestPreviewStyle: React.CSSProperties = { + ...requestMessageStyle, + display: "-webkit-box", + WebkitLineClamp: 2, + WebkitBoxOrient: "vertical", +} + +/** `dropped-N` rows are minted by the tool when the per-call cap slices a batch. */ +const isDroppedRowId = (taskId: string): boolean => /^dropped-\d+$/.test(taskId) + +/** + * A row has a real task behind it unless the host synthesized the id. Dropped + * rows never exist, and a rejected spec's handle id is never registered in the + * parent's `childIds`, so only positively known child ids qualify when the + * caller supplies the list. + */ +const hasRealTask = (taskId: string, childTaskIds?: readonly string[]): boolean => { + if (isDroppedRowId(taskId)) { + return false + } + return childTaskIds === undefined || childTaskIds.includes(taskId) +} + +/** One requested child in the ask payload (`parallel_subtasks.tasks[]`). */ +export interface ParallelSubtaskRequest { + label: string + mode: string + message: string +} + +/** + * One requested task at the single approval point. The message keeps the + * compact two-line preview, with an explicit disclosure control (and the full + * text as the paragraph's title) so the complete instructions are reachable + * before approval. + */ +const ParallelSubtaskRequestRow: React.FC<{ task: ParallelSubtaskRequest; index: number }> = ({ task, index }) => { + const { t } = useAppTranslation() + const [expanded, setExpanded] = useState(false) + const toggleLabel = expanded ? t("chat:task.collapse") : t("chat:task.expand") + + return ( +
+
+ + + {task.label} + + + {task.mode} + + {task.message ? ( + + + + ) : null} +
+ {task.message ? ( +

+ {task.message} +

+ ) : null} +
+ ) +} + +/** + * Approval-time rendering of one `parallel_subtasks` call (design §11). + * + * The ask text carries the requested tasks (`{ label, mode, message }`) because + * no child exists before the single approval point; the say-side panel renders + * live `subtasks` rows instead. Header and row chrome mirror that panel so the + * approval and the progress report read as one surface. + */ +export const ParallelSubtasksPreview: React.FC<{ tasks: ParallelSubtaskRequest[] }> = ({ tasks }) => { + const { t } = useAppTranslation() + + return ( +
+
+ + {t("chat:parallelSubtasks.title")} +
+
+ {tasks.map((task, index) => ( + + ))} +
+
+ ) +} + +/** + * N-row progress/completion panel for one parallel_subtasks call (design D9). + * Rendered from the say channel, so it must never carry approval state; the + * buttons only read host-side state (report files, debug logs, task history). + */ +const ParallelSubtasksBlock: React.FC = ({ subtasks, partial, childTaskIds }) => { + const { t } = useAppTranslation() + const [now, setNow] = useState(() => Date.now()) + + const anyRunning = subtasks.some((subtask) => subtask.status === "running") + useEffect(() => { + if (!anyRunning) { + return + } + const interval = setInterval(() => setNow(Date.now()), 1000) + return () => clearInterval(interval) + }, [anyRunning]) + + const completedCount = subtasks.filter((subtask) => subtask.status === "completed").length + + return ( +
+
+ + {t("chat:parallelSubtasks.title")} + + {t("chat:parallelSubtasks.progress", { completed: completedCount, total: subtasks.length })} + +
+
+ {subtasks.map((subtask) => { + const visual = STATUS_VISUALS[subtask.status] + const hasTask = hasRealTask(subtask.taskId, childTaskIds) + const elapsed = + subtask.status === "running" && subtask.startedAt !== undefined + ? formatElapsed(now - subtask.startedAt) + : undefined + const terminalLine = !isTerminal(subtask.status) + ? undefined + : subtask.status === "completed" + ? subtask.summary + : subtask.error + return ( +
+
+ + + {subtask.label} + + + {subtask.mode} + + {elapsed !== undefined && ( + + {elapsed} + + )} +
+ + + + {hasTask && ( + <> + + + + + + + + )} +
+
+ {terminalLine && ( +

+ {terminalLine} +

+ )} +
+ ) + })} +
+
+ ) +} + +export default ParallelSubtasksBlock diff --git a/webview-ui/src/components/chat/__tests__/ChatRow.parallel-subtasks.spec.tsx b/webview-ui/src/components/chat/__tests__/ChatRow.parallel-subtasks.spec.tsx new file mode 100644 index 0000000000..6d8e07bd3c --- /dev/null +++ b/webview-ui/src/components/chat/__tests__/ChatRow.parallel-subtasks.spec.tsx @@ -0,0 +1,227 @@ +import React from "react" +import { render, screen, fireEvent } from "@/utils/test-utils" +import { ChatRowContent } from "../ChatRow" +import type { ClineMessage, HistoryItem, ParallelSubtaskInfo } from "@roo-code/types" + +const mockPostMessage = vi.fn() +vi.mock("@src/utils/vscode", () => ({ + vscode: { + postMessage: (msg: unknown) => mockPostMessage(msg), + }, +})) + +vi.mock("@src/i18n/TranslationContext", () => ({ + useAppTranslation: () => ({ + t: (key: string, params?: Record) => { + const map: Record = { + "chat:parallelSubtasks.title": "Parallel investigations", + "chat:parallelSubtasks.progress": "{{completed}} of {{total}} complete", + "chat:parallelSubtasks.status.queued": "Queued", + "chat:parallelSubtasks.status.running": "Running", + "chat:parallelSubtasks.status.completed": "Completed", + "chat:parallelSubtasks.status.failed": "Failed", + "chat:parallelSubtasks.status.aborted": "Aborted", + "chat:parallelSubtasks.openReport": "Report", + "chat:parallelSubtasks.openDebugLog": "JSON log", + "chat:parallelSubtasks.goToTask": "Go to task", + "chat:parallelSubtasks.noReport": "No report available yet", + "chat:task.expand": "Expand task", + "chat:task.collapse": "Collapse task", + } + let value = map[key] ?? key + if (params) { + for (const [k, v] of Object.entries(params)) { + value = value.replaceAll(`{{${k}}}`, String(v)) + } + } + return value + }, + }), +})) + +vi.mock("react-i18next", () => ({ + Trans: ({ children }: { children?: React.ReactNode }) => <>{children}, +})) + +let mockCurrentTaskItem: Partial | undefined = undefined + +vi.mock("@src/context/ExtensionStateContext", () => ({ + useExtensionState: () => ({ + mcpServers: [], + alwaysAllowMcp: false, + currentCheckpoint: null, + mode: "code", + apiConfiguration: {}, + clineMessages: [], + currentTaskItem: mockCurrentTaskItem, + }), +})) + +vi.mock("@src/components/ui/hooks/useSelectedModel", () => ({ + useSelectedModel: () => ({ info: { supportsImages: true } }), +})) + +const subtasks: ParallelSubtaskInfo[] = [ + { + taskId: "child-1", + label: "Investigate parser", + mode: "code", + status: "completed", + reportPath: "/ws/.zoocode/subtask-reports/parent/investigate-parser-child-1.md", + summary: "3 call sites found", + }, + { + taskId: "child-2", + label: "Check tests", + mode: "debug", + status: "running", + startedAt: Date.now(), + }, +] + +function sayMessage(rows: ParallelSubtaskInfo[], partial: boolean): ClineMessage { + return { + ts: 1000, + type: "say", + say: "tool", + text: JSON.stringify({ tool: "parallelSubtasks", subtasks: rows }), + partial, + } +} + +function parallelSubtasksMessage(partial: boolean): ClineMessage { + return sayMessage(subtasks, partial) +} + +function askMessage(text: string): ClineMessage { + return { ts: 1000, type: "ask", ask: "tool", text } +} + +const requestedTasks = [ + { label: "Investigate parser", mode: "code", message: "Trace how the parser handles braces." }, + { label: "Check tests", mode: "debug", message: "Find the missing assertion." }, +] + +function renderChatRow(message: ClineMessage, currentTaskItem?: Partial) { + mockCurrentTaskItem = currentTaskItem + + return render( + {}} + onSuggestionClick={() => {}} + onBatchFileResponse={() => {}} + onFollowUpUnmount={() => {}} + isFollowUpAnswered={false} + />, + ) +} + +describe("ChatRow - parallelSubtasks say tool", () => { + beforeEach(() => { + mockPostMessage.mockClear() + }) + + it("renders the panel instead of falling into the transparent-row default (F10)", () => { + const { container } = renderChatRow(parallelSubtasksMessage(true)) + + expect(screen.getByText("Parallel investigations")).toBeInTheDocument() + expect(screen.getByText("1 of 2 complete")).toBeInTheDocument() + expect(screen.getByText("Investigate parser")).toBeInTheDocument() + expect(screen.getByText("Check tests")).toBeInTheDocument() + expect(container.querySelectorAll("[data-testid^='parallel-subtask-row-']")).toHaveLength(2) + }) + + it("renders the final count when partial is false", () => { + renderChatRow(parallelSubtasksMessage(false)) + expect(screen.getByText("1 of 2 complete")).toBeInTheDocument() + }) + + it("routes the panel buttons through the existing message handlers", () => { + renderChatRow(parallelSubtasksMessage(false)) + + fireEvent.click(screen.getAllByRole("button", { name: "Report" })[0]) + expect(mockPostMessage).toHaveBeenCalledWith({ + type: "openFile", + text: "/ws/.zoocode/subtask-reports/parent/investigate-parser-child-1.md", + }) + + fireEvent.click(screen.getAllByRole("button", { name: "JSON log" })[0]) + expect(mockPostMessage).toHaveBeenCalledWith({ type: "openDebugUiHistory", taskId: "child-1" }) + + fireEvent.click(screen.getAllByRole("button", { name: "Go to task" })[1]) + expect(mockPostMessage).toHaveBeenCalledWith({ type: "showTaskWithId", text: "child-2" }) + }) +}) + +describe("ChatRow - parallelSubtasks ask approval point (F-06)", () => { + beforeEach(() => { + mockPostMessage.mockClear() + }) + + it("renders the requested task list with label, mode and message preview", () => { + renderChatRow(askMessage(JSON.stringify({ tool: "parallelSubtasks", tasks: requestedTasks }))) + + expect(screen.getByText("Parallel investigations")).toBeInTheDocument() + expect(screen.getByText("Investigate parser")).toBeInTheDocument() + expect(screen.getByText("Check tests")).toBeInTheDocument() + expect(screen.getByTestId("parallel-subtask-request-mode-0")).toHaveTextContent("code") + expect(screen.getByTestId("parallel-subtask-request-mode-1")).toHaveTextContent("debug") + expect(screen.getByTestId("parallel-subtask-request-message-0")).toHaveTextContent( + "Trace how the parser handles braces.", + ) + expect(screen.queryAllByTestId(/^parallel-subtask-row-/)).toHaveLength(0) + }) + + it.each([ + ["a payload without tasks", JSON.stringify({ tool: "parallelSubtasks" })], + ["a payload with non-array tasks", JSON.stringify({ tool: "parallelSubtasks", tasks: "nope" })], + ])("keeps the approval row visible for %s", (_case, text) => { + renderChatRow(askMessage(text)) + expect(screen.getByText("Parallel investigations")).toBeInTheDocument() + expect(screen.queryAllByTestId(/^parallel-subtask-request-/)).toHaveLength(0) + }) +}) + +describe("ChatRow - parallelSubtasks synthetic rows (F-20)", () => { + beforeEach(() => { + mockPostMessage.mockClear() + }) + + it("hides the debug and navigation buttons for rows without a registered child", () => { + renderChatRow( + sayMessage( + [ + { + taskId: "child-1", + label: "Investigate parser", + mode: "code", + status: "completed", + summary: "done", + }, + { + taskId: "dropped-0", + label: "Check tests", + mode: "debug", + status: "failed", + error: "Dropped: the request exceeded the per-call limit (1 of 2 started)", + }, + { taskId: "synthetic-uuid", label: "Ghost", mode: "code", status: "failed", error: "Unknown mode" }, + ], + false, + ), + { childIds: ["child-1"] }, + ) + + expect(screen.getByTestId("parallel-subtask-row-dropped-0")).toBeInTheDocument() + expect(screen.getByTestId("parallel-subtask-row-synthetic-uuid")).toBeInTheDocument() + expect(screen.getAllByRole("button", { name: "JSON log" })).toHaveLength(1) + expect(screen.getAllByRole("button", { name: "Go to task" })).toHaveLength(1) + + fireEvent.click(screen.getByRole("button", { name: "Go to task" })) + expect(mockPostMessage).toHaveBeenCalledWith({ type: "showTaskWithId", text: "child-1" }) + }) +}) diff --git a/webview-ui/src/components/chat/__tests__/ChatRow.subtask-links.spec.tsx b/webview-ui/src/components/chat/__tests__/ChatRow.subtask-links.spec.tsx index 49a7d7f2bc..8b691f22db 100644 --- a/webview-ui/src/components/chat/__tests__/ChatRow.subtask-links.spec.tsx +++ b/webview-ui/src/components/chat/__tests__/ChatRow.subtask-links.spec.tsx @@ -79,6 +79,18 @@ function subtaskResult(ts: number, childTaskId?: string): ClineMessage { return { ts, type: "say", say: "subtask_result", text: "Subtask completed", childTaskId } } +function parallelSubtasksSay(ts: number, childTaskIds: string[]): ClineMessage { + return { + ts, + type: "say", + say: "tool", + text: JSON.stringify({ + tool: "parallelSubtasks", + subtasks: childTaskIds.map((taskId) => ({ taskId, label: taskId, mode: "code", status: "completed" })), + }), + } +} + function expectSubtaskLink(childTaskId: string) { fireEvent.click(screen.getByRole("button", { name: "Go to subtask" })) expect(mockPostMessage).toHaveBeenCalledWith({ type: "showTaskWithId", text: childTaskId }) @@ -261,4 +273,41 @@ describe("ChatRow - subtask links", () => { expect(screen.queryByRole("button", { name: "Go to subtask" })).not.toBeInTheDocument() }) }) + + describe("background children in the positional fallback (F-07)", () => { + it("skips background children when resolving a legacy result position", () => { + const result = subtaskResult(2000) + renderChatRow(result, { childIds: ["bg-1", "bg-2", "serial-1"] }, [ + parallelSubtasksSay(900, ["bg-1", "bg-2"]), + newTask(1000), + result, + ]) + expectSubtaskLink("serial-1") + }) + + it("skips background children when resolving a pending legacy ask", () => { + const pending = newTask(3000) + renderChatRow(pending, { childIds: ["bg-1", "bg-2", "serial-1", "serial-2"] }, [ + parallelSubtasksSay(500, ["bg-1", "bg-2"]), + newTask(1000), + pending, + ]) + expectSubtaskLink("serial-2") + }) + + it("ignores other tool rows that carry a subtasks array", () => { + const lookalike: ClineMessage = { + ts: 900, + type: "say", + say: "tool", + text: JSON.stringify({ + tool: "runSlashCommand", + subtasks: [{ taskId: "serial-1", label: "serial-1", mode: "code", status: "completed" }], + }), + } + const result = subtaskResult(2000) + renderChatRow(result, { childIds: ["serial-1"] }, [lookalike, newTask(1000), result]) + expectSubtaskLink("serial-1") + }) + }) }) diff --git a/webview-ui/src/components/chat/__tests__/ParallelSubtasks.visual.tsx b/webview-ui/src/components/chat/__tests__/ParallelSubtasks.visual.tsx new file mode 100644 index 0000000000..af1a7d181e --- /dev/null +++ b/webview-ui/src/components/chat/__tests__/ParallelSubtasks.visual.tsx @@ -0,0 +1,25 @@ +import { expect, test } from "../../../../playwright/coverage-fixture" +import { mountedStory } from "../../../../playwright/mounted-story" +import { applyVisualTheme, visualThemes } from "../../../../playwright/themes" + +for (const theme of visualThemes) { + test(`renders the parallel-subtasks approval preview in the VS Code ${theme.name} theme`, async ({ + mount, + page, + }) => { + const component = mountedStory(await mount("parallel-subtasks-approval")) + await applyVisualTheme(page, theme) + + await expect(component).toHaveScreenshot(`parallel-subtasks-approval-${theme.name}.png`) + }) + + test(`renders the parallel-subtasks progress panel in the VS Code ${theme.name} theme`, async ({ mount, page }) => { + // Matches the "parallel-subtasks-progress" story's reference time so the + // running row's elapsed badge stays stable. + await page.clock.setFixedTime(new Date("2026-06-01T12:00:45Z")) + const component = mountedStory(await mount("parallel-subtasks-progress")) + await applyVisualTheme(page, theme) + + await expect(component).toHaveScreenshot(`parallel-subtasks-progress-${theme.name}.png`) + }) +} diff --git a/webview-ui/src/components/chat/__tests__/ParallelSubtasksBlock.spec.tsx b/webview-ui/src/components/chat/__tests__/ParallelSubtasksBlock.spec.tsx new file mode 100644 index 0000000000..3191a4d66d --- /dev/null +++ b/webview-ui/src/components/chat/__tests__/ParallelSubtasksBlock.spec.tsx @@ -0,0 +1,360 @@ +import React from "react" +import { render, screen, fireEvent, act } from "@/utils/test-utils" +import type { ParallelSubtaskInfo } from "@roo-code/types" + +import ParallelSubtasksBlock, { ParallelSubtasksPreview, formatElapsed } from "../ParallelSubtasksBlock" + +const mockPostMessage = vi.fn() +vi.mock("@src/utils/vscode", () => ({ + vscode: { + postMessage: (msg: unknown) => mockPostMessage(msg), + }, +})) + +vi.mock("@src/i18n/TranslationContext", () => ({ + useAppTranslation: () => ({ + t: (key: string, params?: Record) => { + const map: Record = { + "chat:parallelSubtasks.title": "Parallel investigations", + "chat:parallelSubtasks.progress": "{{completed}} of {{total}} complete", + "chat:parallelSubtasks.status.queued": "Queued", + "chat:parallelSubtasks.status.running": "Running", + "chat:parallelSubtasks.status.completed": "Completed", + "chat:parallelSubtasks.status.failed": "Failed", + "chat:parallelSubtasks.status.aborted": "Aborted", + "chat:parallelSubtasks.openReport": "Report", + "chat:parallelSubtasks.openDebugLog": "JSON log", + "chat:parallelSubtasks.goToTask": "Go to task", + "chat:parallelSubtasks.noReport": "No report available yet", + "chat:task.expand": "Expand task", + "chat:task.collapse": "Collapse task", + } + let value = map[key] ?? key + if (params) { + for (const [k, v] of Object.entries(params)) { + value = value.replaceAll(`{{${k}}}`, String(v)) + } + } + return value + }, + }), +})) + +const BASE_TIME = new Date("2026-11-19T00:00:00Z").getTime() + +const subtask = (overrides: Partial & { taskId: string }): ParallelSubtaskInfo => ({ + label: overrides.taskId, + mode: "code", + status: "queued", + ...overrides, +}) + +describe("ParallelSubtasksBlock", () => { + beforeEach(() => { + mockPostMessage.mockClear() + }) + + afterEach(() => { + vi.useRealTimers() + }) + + describe("rendering", () => { + it("renders one row per subtask in request order", () => { + const subtasks: ParallelSubtaskInfo[] = [ + subtask({ taskId: "child-3", label: "Third", mode: "debug", status: "failed" }), + subtask({ taskId: "child-1", label: "First", mode: "code", status: "completed" }), + subtask({ taskId: "child-2", label: "Second", mode: "architect", status: "queued" }), + ] + const { container } = render() + + const rows = container.querySelectorAll("[data-testid^='parallel-subtask-row-']") + expect(rows).toHaveLength(3) + expect(rows[0].getAttribute("data-testid")).toBe("parallel-subtask-row-child-3") + expect(rows[1].getAttribute("data-testid")).toBe("parallel-subtask-row-child-1") + expect(rows[2].getAttribute("data-testid")).toBe("parallel-subtask-row-child-2") + + expect(screen.getByText("Third")).toBeInTheDocument() + expect(screen.getByTestId("parallel-subtask-mode-child-1")).toHaveTextContent("code") + expect(screen.getByTestId("parallel-subtask-mode-child-2")).toHaveTextContent("architect") + }) + + it.each([ + ["queued", "Queued"], + ["running", "Running"], + ["completed", "Completed"], + ["failed", "Failed"], + ["aborted", "Aborted"], + ] as const)("renders the %s status icon with its label", (status, label) => { + render() + expect(screen.getByLabelText(label)).toBeInTheDocument() + }) + + it("shows the summary once completed and the error once failed", () => { + render( + , + ) + expect(screen.getByTestId("parallel-subtask-line-ok")).toHaveTextContent("Found 3 call sites") + expect(screen.getByTestId("parallel-subtask-line-bad")).toHaveTextContent("Output token limit") + }) + }) + + describe("progress header", () => { + it("shows the live count while partial and the final count when done", () => { + const subtasks: ParallelSubtaskInfo[] = [ + subtask({ taskId: "child-1", status: "completed" }), + subtask({ taskId: "child-2", status: "running", startedAt: BASE_TIME }), + subtask({ taskId: "child-3", status: "queued" }), + ] + const { rerender } = render() + expect(screen.getByText("1 of 3 complete")).toBeInTheDocument() + + rerender( + ({ ...s, status: "completed" as const }))} + partial={false} + />, + ) + expect(screen.getByText("3 of 3 complete")).toBeInTheDocument() + }) + }) + + describe("elapsed time", () => { + it("ticks the elapsed badge while a child is running", () => { + vi.useFakeTimers() + vi.setSystemTime(BASE_TIME + 10_000) + render( + , + ) + expect(screen.getByTestId("parallel-subtask-elapsed-child-1")).toHaveTextContent("10s") + + act(() => { + vi.advanceTimersByTime(5_000) + }) + expect(screen.getByTestId("parallel-subtask-elapsed-child-1")).toHaveTextContent("15s") + }) + + it("hides the elapsed badge for non-running rows", () => { + vi.useFakeTimers() + vi.setSystemTime(BASE_TIME + 10_000) + render( + , + ) + expect(screen.queryByTestId("parallel-subtask-elapsed-child-1")).not.toBeInTheDocument() + expect(screen.queryByTestId("parallel-subtask-elapsed-child-2")).not.toBeInTheDocument() + }) + }) + + describe("buttons", () => { + it("posts openFile with the report path when Report is clicked", () => { + render( + , + ) + fireEvent.click(screen.getByRole("button", { name: "Report" })) + expect(mockPostMessage).toHaveBeenCalledWith({ + type: "openFile", + text: "/ws/.zoocode/subtask-reports/p/a.md", + }) + }) + + it("disables Report when no report path exists", () => { + render( + , + ) + const reportButton = screen.getByRole("button", { name: "Report" }) + expect(reportButton).toBeDisabled() + fireEvent.click(reportButton) + expect(mockPostMessage).not.toHaveBeenCalled() + }) + + it("posts openDebugUiHistory with the child taskId when JSON log is clicked", () => { + render( + , + ) + fireEvent.click(screen.getByRole("button", { name: "JSON log" })) + expect(mockPostMessage).toHaveBeenCalledWith({ type: "openDebugUiHistory", taskId: "child-42" }) + }) + + it("posts showTaskWithId with the child taskId when Go to task is clicked", () => { + render( + , + ) + fireEvent.click(screen.getByRole("button", { name: "Go to task" })) + expect(mockPostMessage).toHaveBeenCalledWith({ type: "showTaskWithId", text: "child-42" }) + }) + }) + + describe("synthetic rows (F-20)", () => { + it("hides navigation and debug buttons for a dropped row", () => { + render( + , + ) + expect(screen.queryByRole("button", { name: "JSON log" })).not.toBeInTheDocument() + expect(screen.queryByRole("button", { name: "Go to task" })).not.toBeInTheDocument() + expect(screen.getByRole("button", { name: "Report" })).toBeDisabled() + expect(screen.getByTestId("parallel-subtask-line-dropped-0")).toHaveTextContent("Dropped") + }) + + it("hides navigation and debug buttons for an unregistered failed-handle id", () => { + render( + , + ) + expect(screen.getByTestId("parallel-subtask-row-synthetic-uuid")).toBeInTheDocument() + expect(screen.getAllByRole("button", { name: "JSON log" })).toHaveLength(1) + expect(screen.getAllByRole("button", { name: "Go to task" })).toHaveLength(1) + fireEvent.click(screen.getByRole("button", { name: "Go to task" })) + expect(mockPostMessage).toHaveBeenCalledWith({ type: "showTaskWithId", text: "child-1" }) + }) + + it("keeps navigation and debug buttons for every registered child", () => { + render( + , + ) + expect(screen.getAllByRole("button", { name: "JSON log" })).toHaveLength(2) + expect(screen.getAllByRole("button", { name: "Go to task" })).toHaveLength(2) + }) + }) + + describe("ParallelSubtasksPreview", () => { + it("renders one row per requested task with its label, mode and message preview", () => { + render( + , + ) + + expect(screen.getByText("Parallel investigations")).toBeInTheDocument() + expect(screen.getByText("Investigate parser")).toBeInTheDocument() + expect(screen.getByText("Check tests")).toBeInTheDocument() + expect(screen.getByTestId("parallel-subtask-request-mode-0")).toHaveTextContent("code") + expect(screen.getByTestId("parallel-subtask-request-mode-1")).toHaveTextContent("debug") + expect(screen.getByTestId("parallel-subtask-request-message-0")).toHaveTextContent( + "Trace how the parser handles braces.", + ) + expect(screen.getByTestId("parallel-subtask-request-message-1")).toHaveTextContent( + "Find the missing assertion.", + ) + expect(screen.getAllByLabelText("Queued")).toHaveLength(2) + }) + + it("keeps the header when no task parsed so the approval row is never invisible", () => { + render() + expect(screen.getByText("Parallel investigations")).toBeInTheDocument() + expect(screen.queryByTestId("parallel-subtask-request-0")).not.toBeInTheDocument() + }) + + it("reveals the full message through an accessible expand control", () => { + const message = + "First line of the request.\nSecond line.\nThird line carries the detail that the two-line preview hides." + render() + + const preview = screen.getByTestId("parallel-subtask-request-message-0") + // The compact preview keeps the full text in the DOM and as its title, + // but the visible clamp hides everything past two lines. + expect(preview.textContent).toBe(message) + expect(preview).toHaveAttribute("title", message) + expect(preview.style.display).toBe("-webkit-box") + + const expand = screen.getByRole("button", { name: "Expand task" }) + expect(expand).toHaveAttribute("aria-expanded", "false") + fireEvent.click(expand) + + const collapse = screen.getByRole("button", { name: "Collapse task" }) + expect(collapse).toHaveAttribute("aria-expanded", "true") + expect(preview.style.display).toBe("") + expect(preview.style.getPropertyValue("-webkit-line-clamp")).toBe("") + + fireEvent.click(collapse) + expect(screen.getByRole("button", { name: "Expand task" })).toHaveAttribute("aria-expanded", "false") + expect(preview.style.display).toBe("-webkit-box") + }) + + it("expands only the row whose control was clicked", () => { + render( + , + ) + + fireEvent.click(screen.getAllByRole("button", { name: "Expand task" })[0]) + + expect(screen.getByTestId("parallel-subtask-request-message-0").style.display).toBe("") + expect(screen.getByTestId("parallel-subtask-request-message-1").style.display).toBe("-webkit-box") + expect(screen.getAllByRole("button", { name: "Collapse task" })).toHaveLength(1) + }) + }) + + describe("formatElapsed", () => { + it.each([ + [0, "0s"], + [4_999, "4s"], + [65_000, "1m 5s"], + [3_600_000, "1h 0m"], + ] as const)("formats %d ms as %s", (ms, expected) => { + expect(formatElapsed(ms)).toBe(expected) + }) + }) +}) diff --git a/webview-ui/src/components/chat/__tests__/__screenshots__/parallel-subtasks-approval-dark.png b/webview-ui/src/components/chat/__tests__/__screenshots__/parallel-subtasks-approval-dark.png new file mode 100644 index 0000000000..1e5d2044bd Binary files /dev/null and b/webview-ui/src/components/chat/__tests__/__screenshots__/parallel-subtasks-approval-dark.png differ diff --git a/webview-ui/src/components/chat/__tests__/__screenshots__/parallel-subtasks-approval-high-contrast-light.png b/webview-ui/src/components/chat/__tests__/__screenshots__/parallel-subtasks-approval-high-contrast-light.png new file mode 100644 index 0000000000..0229ad9274 Binary files /dev/null and b/webview-ui/src/components/chat/__tests__/__screenshots__/parallel-subtasks-approval-high-contrast-light.png differ diff --git a/webview-ui/src/components/chat/__tests__/__screenshots__/parallel-subtasks-approval-high-contrast.png b/webview-ui/src/components/chat/__tests__/__screenshots__/parallel-subtasks-approval-high-contrast.png new file mode 100644 index 0000000000..fb99c41285 Binary files /dev/null and b/webview-ui/src/components/chat/__tests__/__screenshots__/parallel-subtasks-approval-high-contrast.png differ diff --git a/webview-ui/src/components/chat/__tests__/__screenshots__/parallel-subtasks-approval-light.png b/webview-ui/src/components/chat/__tests__/__screenshots__/parallel-subtasks-approval-light.png new file mode 100644 index 0000000000..daecb41d35 Binary files /dev/null and b/webview-ui/src/components/chat/__tests__/__screenshots__/parallel-subtasks-approval-light.png differ diff --git a/webview-ui/src/components/chat/__tests__/__screenshots__/parallel-subtasks-progress-dark.png b/webview-ui/src/components/chat/__tests__/__screenshots__/parallel-subtasks-progress-dark.png new file mode 100644 index 0000000000..02de7837cc Binary files /dev/null and b/webview-ui/src/components/chat/__tests__/__screenshots__/parallel-subtasks-progress-dark.png differ diff --git a/webview-ui/src/components/chat/__tests__/__screenshots__/parallel-subtasks-progress-high-contrast-light.png b/webview-ui/src/components/chat/__tests__/__screenshots__/parallel-subtasks-progress-high-contrast-light.png new file mode 100644 index 0000000000..82f563c488 Binary files /dev/null and b/webview-ui/src/components/chat/__tests__/__screenshots__/parallel-subtasks-progress-high-contrast-light.png differ diff --git a/webview-ui/src/components/chat/__tests__/__screenshots__/parallel-subtasks-progress-high-contrast.png b/webview-ui/src/components/chat/__tests__/__screenshots__/parallel-subtasks-progress-high-contrast.png new file mode 100644 index 0000000000..e2841ab45a Binary files /dev/null and b/webview-ui/src/components/chat/__tests__/__screenshots__/parallel-subtasks-progress-high-contrast.png differ diff --git a/webview-ui/src/components/chat/__tests__/__screenshots__/parallel-subtasks-progress-light.png b/webview-ui/src/components/chat/__tests__/__screenshots__/parallel-subtasks-progress-light.png new file mode 100644 index 0000000000..7cf9e3204e Binary files /dev/null and b/webview-ui/src/components/chat/__tests__/__screenshots__/parallel-subtasks-progress-light.png differ diff --git a/webview-ui/src/components/settings/__tests__/__screenshots__/experimental-settings-dark.png b/webview-ui/src/components/settings/__tests__/__screenshots__/experimental-settings-dark.png index 1bfbbcf884..d4a36e070c 100644 Binary files a/webview-ui/src/components/settings/__tests__/__screenshots__/experimental-settings-dark.png and b/webview-ui/src/components/settings/__tests__/__screenshots__/experimental-settings-dark.png differ diff --git a/webview-ui/src/components/settings/__tests__/__screenshots__/experimental-settings-high-contrast-light.png b/webview-ui/src/components/settings/__tests__/__screenshots__/experimental-settings-high-contrast-light.png index e4d9385b5e..e9df5b75af 100644 Binary files a/webview-ui/src/components/settings/__tests__/__screenshots__/experimental-settings-high-contrast-light.png and b/webview-ui/src/components/settings/__tests__/__screenshots__/experimental-settings-high-contrast-light.png differ diff --git a/webview-ui/src/components/settings/__tests__/__screenshots__/experimental-settings-high-contrast.png b/webview-ui/src/components/settings/__tests__/__screenshots__/experimental-settings-high-contrast.png index c83298d0ea..fb9b38aa62 100644 Binary files a/webview-ui/src/components/settings/__tests__/__screenshots__/experimental-settings-high-contrast.png and b/webview-ui/src/components/settings/__tests__/__screenshots__/experimental-settings-high-contrast.png differ diff --git a/webview-ui/src/components/settings/__tests__/__screenshots__/experimental-settings-light.png b/webview-ui/src/components/settings/__tests__/__screenshots__/experimental-settings-light.png index 55216d50cc..fed6506cab 100644 Binary files a/webview-ui/src/components/settings/__tests__/__screenshots__/experimental-settings-light.png and b/webview-ui/src/components/settings/__tests__/__screenshots__/experimental-settings-light.png differ diff --git a/webview-ui/src/i18n/__tests__/parallelSubtasks.locales.spec.ts b/webview-ui/src/i18n/__tests__/parallelSubtasks.locales.spec.ts new file mode 100644 index 0000000000..e337001922 --- /dev/null +++ b/webview-ui/src/i18n/__tests__/parallelSubtasks.locales.spec.ts @@ -0,0 +1,70 @@ +import { readdirSync, readFileSync } from "fs" +import { fileURLToPath } from "url" +import path from "path" + +// Phase 3 Unit C i18n contract: every locale ships the parallelSubtasks chat +// strings and the experimental.PARALLEL_SUBTASKS settings strings. Untranslated +// locales intentionally fall back to English text (design §13), so the values +// are not asserted, only presence and key shape. +const LOCALES_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../locales") + +const LOCALES = [ + "ca", + "de", + "en", + "es", + "fr", + "hi", + "id", + "it", + "ja", + "ko", + "nl", + "pl", + "pt-BR", + "ru", + "tr", + "vi", + "zh-CN", + "zh-TW", +] + +const CHAT_KEYS = ["title", "progress", "status", "openReport", "openDebugLog", "goToTask", "noReport"] +const STATUSES = ["queued", "running", "completed", "failed", "aborted"] + +describe("parallelSubtasks locale coverage", () => { + it.each(LOCALES)("%s/chat.json parses and carries the full key set", (locale) => { + const raw = readFileSync(path.join(LOCALES_DIR, locale, "chat.json"), "utf8") + const chat = JSON.parse(raw) + + for (const key of CHAT_KEYS) { + expect(chat.parallelSubtasks).toHaveProperty(key) + } + for (const status of STATUSES) { + expect(chat.parallelSubtasks.status).toHaveProperty(status) + } + expect(chat.parallelSubtasks.progress).toContain("{{completed}}") + expect(chat.parallelSubtasks.progress).toContain("{{total}}") + }) + + it.each(LOCALES)("%s/settings.json parses and carries experimental.PARALLEL_SUBTASKS", (locale) => { + const raw = readFileSync(path.join(LOCALES_DIR, locale, "settings.json"), "utf8") + const settings = JSON.parse(raw) + + expect(settings.experimental).toBeDefined() + expect(settings.experimental.PARALLEL_SUBTASKS).toBeDefined() + expect(typeof settings.experimental.PARALLEL_SUBTASKS.name).toBe("string") + expect(typeof settings.experimental.PARALLEL_SUBTASKS.description).toBe("string") + // The key must live inside `experimental`, not as a stray top-level key. + expect(settings.PARALLEL_SUBTASKS).toBeUndefined() + }) + + it("keeps exactly the 18 shipped locales", () => { + expect( + readdirSync(LOCALES_DIR, { withFileTypes: true }) + .filter((e) => e.isDirectory()) + .map((e) => e.name) + .sort(), + ).toEqual([...LOCALES].sort()) + }) +}) diff --git a/webview-ui/src/i18n/locales/ca/chat.json b/webview-ui/src/i18n/locales/ca/chat.json index d4a7cfe89b..0855cfb150 100644 --- a/webview-ui/src/i18n/locales/ca/chat.json +++ b/webview-ui/src/i18n/locales/ca/chat.json @@ -351,6 +351,21 @@ "copy_code": "Copiar codi" } }, + "parallelSubtasks": { + "title": "Investigacions paral·leles", + "progress": "{{completed}} de {{total}} completades", + "status": { + "queued": "En cua", + "running": "En execució", + "completed": "Completada", + "failed": "Ha fallat", + "aborted": "Avortada" + }, + "openReport": "Informe", + "openDebugLog": "Registre JSON", + "goToTask": "Anar a la tasca", + "noReport": "Encara no hi ha cap informe disponible" + }, "profileViolationWarning": "El perfil actual no és compatible amb la configuració de la teva organització", "shellIntegration": { "title": "Advertència d'execució d'ordres", diff --git a/webview-ui/src/i18n/locales/ca/settings.json b/webview-ui/src/i18n/locales/ca/settings.json index a86b313539..72955316c0 100644 --- a/webview-ui/src/i18n/locales/ca/settings.json +++ b/webview-ui/src/i18n/locales/ca/settings.json @@ -937,6 +937,10 @@ "DYNAMIC_THINKING_EFFORT": { "name": "Esforç de pensament dinàmic", "description": "Prepara l'eina set_thinking_effort per a un suport posterior: aquest paràmetre només desa la preferència i el comportament per sol·licitud arribarà en una feina posterior. (experimental)" + }, + "PARALLEL_SUBTASKS": { + "name": "Habilita subtasques paral·leles", + "description": "Quan està habilitat, Zoo pot crear diverses tasques d'investigació de només lectura en segon pla en diferents modes i models, i després recopilar els seus informes. Les tasques fill tenen bloquejada estructuralment l'escriptura de fitxers, l'execució de comandes o la delegació de més subtasques." } }, "temperature": { diff --git a/webview-ui/src/i18n/locales/de/chat.json b/webview-ui/src/i18n/locales/de/chat.json index 71d145f3b7..d385c507c5 100644 --- a/webview-ui/src/i18n/locales/de/chat.json +++ b/webview-ui/src/i18n/locales/de/chat.json @@ -348,6 +348,21 @@ "copy_code": "Code kopieren" } }, + "parallelSubtasks": { + "title": "Parallele Untersuchungen", + "progress": "{{completed}} von {{total}} abgeschlossen", + "status": { + "queued": "In Warteschlange", + "running": "Wird ausgeführt", + "completed": "Abgeschlossen", + "failed": "Fehlgeschlagen", + "aborted": "Abgebrochen" + }, + "openReport": "Bericht", + "openDebugLog": "JSON-Protokoll", + "goToTask": "Zur Aufgabe", + "noReport": "Noch kein Bericht verfügbar" + }, "profileViolationWarning": "Das aktuelle Profil ist nicht kompatibel mit den Einstellungen deiner Organisation", "shellIntegration": { "title": "Befehlsausführungswarnung", diff --git a/webview-ui/src/i18n/locales/de/settings.json b/webview-ui/src/i18n/locales/de/settings.json index f29ac76cb8..522cc5baca 100644 --- a/webview-ui/src/i18n/locales/de/settings.json +++ b/webview-ui/src/i18n/locales/de/settings.json @@ -936,6 +936,10 @@ "DYNAMIC_THINKING_EFFORT": { "name": "Dynamische Denkintensität", "description": "Bereitet das set_thinking_effort-Tool für spätere Unterstützung vor: Diese Einstellung speichert nur die Präferenz, das Verhalten pro Anfrage folgt in späterer Arbeit. (experimentell)" + }, + "PARALLEL_SUBTASKS": { + "name": "Parallele Teilaufgaben aktivieren", + "description": "Wenn aktiviert, kann Zoo mehrere schreibgeschützte Untersuchungsaufgaben im Hintergrund in verschiedenen Modi und Modellen starten und deren Berichte sammeln. Kindaufgaben sind strukturell daran gehindert, Dateien zu schreiben, Befehle auszuführen oder weitere Teilaufgaben zu delegieren." } }, "temperature": { diff --git a/webview-ui/src/i18n/locales/en/chat.json b/webview-ui/src/i18n/locales/en/chat.json index 08dde55a89..d59b6a194b 100644 --- a/webview-ui/src/i18n/locales/en/chat.json +++ b/webview-ui/src/i18n/locales/en/chat.json @@ -376,6 +376,21 @@ "copy_code": "Copy code" } }, + "parallelSubtasks": { + "title": "Parallel investigations", + "progress": "{{completed}} of {{total}} complete", + "status": { + "queued": "Queued", + "running": "Running", + "completed": "Completed", + "failed": "Failed", + "aborted": "Aborted" + }, + "openReport": "Report", + "openDebugLog": "JSON log", + "goToTask": "Go to task", + "noReport": "No report available yet" + }, "profileViolationWarning": "The current profile isn't compatible with your organization's settings", "shellIntegration": { "title": "Command Execution Warning", diff --git a/webview-ui/src/i18n/locales/en/settings.json b/webview-ui/src/i18n/locales/en/settings.json index d2fb634f82..ae250384e6 100644 --- a/webview-ui/src/i18n/locales/en/settings.json +++ b/webview-ui/src/i18n/locales/en/settings.json @@ -1009,6 +1009,10 @@ "DYNAMIC_THINKING_EFFORT": { "name": "Dynamic thinking effort", "description": "Prepares the set_thinking_effort tool for later support: this setting stores the preference only, and the tool's per-request behavior arrives in follow-up work. (experimental)" + }, + "PARALLEL_SUBTASKS": { + "name": "Enable parallel subtasks", + "description": "When enabled, Zoo can spawn multiple read-only background investigation tasks in different modes and models, then collect their reports. Child tasks are structurally blocked from writing files, running commands, or delegating further subtasks." } }, "temperature": { diff --git a/webview-ui/src/i18n/locales/es/chat.json b/webview-ui/src/i18n/locales/es/chat.json index cd3d926371..0f5cadd651 100644 --- a/webview-ui/src/i18n/locales/es/chat.json +++ b/webview-ui/src/i18n/locales/es/chat.json @@ -351,6 +351,21 @@ "copy_code": "Copiar código" } }, + "parallelSubtasks": { + "title": "Investigaciones en paralelo", + "progress": "{{completed}} de {{total}} completadas", + "status": { + "queued": "En cola", + "running": "Ejecutando", + "completed": "Completada", + "failed": "Fallida", + "aborted": "Abortada" + }, + "openReport": "Informe", + "openDebugLog": "Registro JSON", + "goToTask": "Ir a la tarea", + "noReport": "Aún no hay ningún informe disponible" + }, "profileViolationWarning": "El perfil actual no es compatible con la configuración de tu organización", "shellIntegration": { "title": "Advertencia de ejecución de comandos", diff --git a/webview-ui/src/i18n/locales/es/settings.json b/webview-ui/src/i18n/locales/es/settings.json index f40454ad65..730084e81e 100644 --- a/webview-ui/src/i18n/locales/es/settings.json +++ b/webview-ui/src/i18n/locales/es/settings.json @@ -937,6 +937,10 @@ "DYNAMIC_THINKING_EFFORT": { "name": "Esfuerzo de pensamiento dinámico", "description": "Prepara la herramienta set_thinking_effort para un soporte posterior: esta opción solo guarda la preferencia y el comportamiento por solicitud llegará en trabajo posterior. (experimental)" + }, + "PARALLEL_SUBTASKS": { + "name": "Habilitar subtareas en paralelo", + "description": "Cuando está habilitado, Zoo puede crear múltiples tareas de investigación de solo lectura en segundo plano en diferentes modos y modelos, y luego recopilar sus informes. Las tareas hijas tienen bloqueadas estructuralmente la escritura de archivos, la ejecución de comandos y la delegación de más subtareas." } }, "temperature": { diff --git a/webview-ui/src/i18n/locales/fr/chat.json b/webview-ui/src/i18n/locales/fr/chat.json index 4e134b01d3..e922238990 100644 --- a/webview-ui/src/i18n/locales/fr/chat.json +++ b/webview-ui/src/i18n/locales/fr/chat.json @@ -351,6 +351,21 @@ "copy_code": "Copier le code" } }, + "parallelSubtasks": { + "title": "Investigations parallèles", + "progress": "{{completed}} sur {{total}} terminées", + "status": { + "queued": "En file d'attente", + "running": "En cours d'exécution", + "completed": "Terminée", + "failed": "Échouée", + "aborted": "Abandonnée" + }, + "openReport": "Rapport", + "openDebugLog": "Journal JSON", + "goToTask": "Aller à la tâche", + "noReport": "Aucun rapport disponible pour le moment" + }, "profileViolationWarning": "Le profil actuel n'est pas compatible avec les paramètres de votre organisation", "shellIntegration": { "title": "Avertissement d'exécution de commande", diff --git a/webview-ui/src/i18n/locales/fr/settings.json b/webview-ui/src/i18n/locales/fr/settings.json index e38e4f65f6..3b33ddc8f2 100644 --- a/webview-ui/src/i18n/locales/fr/settings.json +++ b/webview-ui/src/i18n/locales/fr/settings.json @@ -937,6 +937,10 @@ "DYNAMIC_THINKING_EFFORT": { "name": "Effort de réflexion dynamique", "description": "Prépare l'outil set_thinking_effort pour une prise en charge ultérieure : ce réglage ne stocke que la préférence, le comportement par requête arrivera dans un travail ultérieur. (expérimental)" + }, + "PARALLEL_SUBTASKS": { + "name": "Activer les sous-tâches parallèles", + "description": "Lorsqu'elle est activée, Zoo peut lancer plusieurs tâches d'investigation en arrière-plan en lecture seule dans différents modes et modèles, puis collecter leurs rapports. Les tâches enfant sont structurellement bloquées : elles ne peuvent pas écrire de fichiers, exécuter de commandes ni déléguer de nouvelles sous-tâches." } }, "temperature": { diff --git a/webview-ui/src/i18n/locales/hi/chat.json b/webview-ui/src/i18n/locales/hi/chat.json index ece7f713c7..8a4a88015d 100644 --- a/webview-ui/src/i18n/locales/hi/chat.json +++ b/webview-ui/src/i18n/locales/hi/chat.json @@ -348,6 +348,21 @@ "copy_code": "कोड कॉपी करें" } }, + "parallelSubtasks": { + "title": "समांतर जांच", + "progress": "{{total}} में से {{completed}} पूर्ण", + "status": { + "queued": "कतारबद्ध", + "running": "चल रहा है", + "completed": "पूर्ण", + "failed": "विफल", + "aborted": "रद्द" + }, + "openReport": "रिपोर्ट", + "openDebugLog": "JSON लॉग", + "goToTask": "कार्य पर जाएं", + "noReport": "अभी कोई रिपोर्ट उपलब्ध नहीं है" + }, "profileViolationWarning": "वर्तमान प्रोफ़ाइल आपके संगठन की सेटिंग्स के साथ संगत नहीं है", "shellIntegration": { "title": "कमांड निष्पादन चेतावनी", diff --git a/webview-ui/src/i18n/locales/hi/settings.json b/webview-ui/src/i18n/locales/hi/settings.json index 8a599d8828..3a24bd5b79 100644 --- a/webview-ui/src/i18n/locales/hi/settings.json +++ b/webview-ui/src/i18n/locales/hi/settings.json @@ -936,6 +936,10 @@ "DYNAMIC_THINKING_EFFORT": { "name": "डायनामिक चिंतन प्रयास", "description": "set_thinking_effort टूल को बाद के समर्थन के लिए तैयार करता है: यह सेटिंग केवल प्राथमिकता सहेजती है, प्रति-अनुरोध व्यवहार आगे के काम में आएगा। (प्रयोगात्मक)" + }, + "PARALLEL_SUBTASKS": { + "name": "समांतर उपकार्य सक्षम करें", + "description": "सक्षम होने पर, Zoo विभिन्न मोड और मॉडल में कई केवल-पढ़ने योग्य बैकग्राउंड जांच कार्य शुरू कर सकता है, और फिर उनकी रिपोर्ट एकत्र कर सकता है। चाइल्ड कार्यों की फ़ाइलें लिखने, कमांड चलाने या आगे उपकार्य सौंपने की संरचनात्मक रूप से अनुमति नहीं है।" } }, "temperature": { diff --git a/webview-ui/src/i18n/locales/id/chat.json b/webview-ui/src/i18n/locales/id/chat.json index aae3b84e36..dc035293e9 100644 --- a/webview-ui/src/i18n/locales/id/chat.json +++ b/webview-ui/src/i18n/locales/id/chat.json @@ -382,6 +382,21 @@ "copy_code": "Salin kode" } }, + "parallelSubtasks": { + "title": "Investigasi paralel", + "progress": "{{completed}} dari {{total}} selesai", + "status": { + "queued": "Antrian", + "running": "Berjalan", + "completed": "Selesai", + "failed": "Gagal", + "aborted": "Dibatalkan" + }, + "openReport": "Laporan", + "openDebugLog": "Log JSON", + "goToTask": "Ke tugas", + "noReport": "Belum ada laporan yang tersedia" + }, "profileViolationWarning": "Profil saat ini tidak kompatibel dengan pengaturan organisasi kamu", "shellIntegration": { "title": "Peringatan Eksekusi Perintah", diff --git a/webview-ui/src/i18n/locales/id/settings.json b/webview-ui/src/i18n/locales/id/settings.json index 1ca6586866..913d8a0285 100644 --- a/webview-ui/src/i18n/locales/id/settings.json +++ b/webview-ui/src/i18n/locales/id/settings.json @@ -935,6 +935,10 @@ "DYNAMIC_THINKING_EFFORT": { "name": "Usaha berpikir dinamis", "description": "Menyiapkan alat set_thinking_effort untuk dukungan berikutnya: pengaturan ini hanya menyimpan preferensi, perilaku per permintaan akan datang pada pekerjaan lanjutan. (eksperimental)" + }, + "PARALLEL_SUBTASKS": { + "name": "Aktifkan subtugas paralel", + "description": "Saat diaktifkan, Zoo dapat memunculkan beberapa tugas investigasi latar belakang baca-saja dalam mode dan model berbeda, lalu mengumpulkan laporannya. Tugas anak secara struktural diblokir untuk menulis file, menjalankan perintah, atau mendelegasikan subtugas lebih lanjut." } }, "temperature": { diff --git a/webview-ui/src/i18n/locales/it/chat.json b/webview-ui/src/i18n/locales/it/chat.json index eaeb775b76..99a3755c7c 100644 --- a/webview-ui/src/i18n/locales/it/chat.json +++ b/webview-ui/src/i18n/locales/it/chat.json @@ -351,6 +351,21 @@ "copy_code": "Copia codice" } }, + "parallelSubtasks": { + "title": "Indagini parallele", + "progress": "{{completed}} di {{total}} completate", + "status": { + "queued": "In coda", + "running": "In esecuzione", + "completed": "Completata", + "failed": "Non riuscita", + "aborted": "Interrotta" + }, + "openReport": "Report", + "openDebugLog": "Log JSON", + "goToTask": "Vai all'attività", + "noReport": "Nessun report disponibile al momento" + }, "profileViolationWarning": "Il profilo corrente non è compatibile con le impostazioni della tua organizzazione", "shellIntegration": { "title": "Avviso di esecuzione comando", diff --git a/webview-ui/src/i18n/locales/it/settings.json b/webview-ui/src/i18n/locales/it/settings.json index 6f63827204..640c4516d9 100644 --- a/webview-ui/src/i18n/locales/it/settings.json +++ b/webview-ui/src/i18n/locales/it/settings.json @@ -937,6 +937,10 @@ "DYNAMIC_THINKING_EFFORT": { "name": "Sforzo di pensiero dinamico", "description": "Prepara lo strumento set_thinking_effort per un supporto successivo: questa impostazione salva solo la preferenza, il comportamento per richiesta arriverà in un lavoro successivo. (sperimentale)" + }, + "PARALLEL_SUBTASKS": { + "name": "Abilita sottoattività parallele", + "description": "Quando abilitato, Zoo può avviare più attività di indagine in background in sola lettura in modalità e modelli diversi, quindi raccoglierne i report. Le attività figlie sono bloccate a livello strutturale dalla scrittura di file, dall'esecuzione di comandi e dalla delega di ulteriori sottoattività." } }, "temperature": { diff --git a/webview-ui/src/i18n/locales/ja/chat.json b/webview-ui/src/i18n/locales/ja/chat.json index e9277e7ff0..e5f1f08cfe 100644 --- a/webview-ui/src/i18n/locales/ja/chat.json +++ b/webview-ui/src/i18n/locales/ja/chat.json @@ -345,6 +345,21 @@ "copy_code": "コードをコピー" } }, + "parallelSubtasks": { + "title": "並列調査", + "progress": "{{total}}件中{{completed}}件完了", + "status": { + "queued": "キュー待ち", + "running": "実行中", + "completed": "完了", + "failed": "失敗", + "aborted": "中止" + }, + "openReport": "レポート", + "openDebugLog": "JSONログ", + "goToTask": "タスクへ移動", + "noReport": "まだレポートがありません" + }, "profileViolationWarning": "現在のプロファイルは組織の設定と互換性がありません", "shellIntegration": { "title": "コマンド実行警告", diff --git a/webview-ui/src/i18n/locales/ja/settings.json b/webview-ui/src/i18n/locales/ja/settings.json index a6ec96a5d1..009fa6ca37 100644 --- a/webview-ui/src/i18n/locales/ja/settings.json +++ b/webview-ui/src/i18n/locales/ja/settings.json @@ -935,6 +935,10 @@ "DYNAMIC_THINKING_EFFORT": { "name": "ダイナミック思考強度", "description": "set_thinking_effort ツールを将来のサポートに備えて準備します。この設定は選好を保存するだけで、リクエストごとの動作は後続の作業で提供されます。(実験的機能)" + }, + "PARALLEL_SUBTASKS": { + "name": "並列サブタスクを有効化", + "description": "有効にすると、Zooは異なるモードとモデルで複数の読み取り専用のバックグラウンド調査タスクを起動し、そのレポートを収集できます。子タスクは、ファイルの書き込み、コマンドの実行、さらなるサブタスクの委任が構造的にブロックされています。" } }, "temperature": { diff --git a/webview-ui/src/i18n/locales/ko/chat.json b/webview-ui/src/i18n/locales/ko/chat.json index 28113bfd46..a87d676777 100644 --- a/webview-ui/src/i18n/locales/ko/chat.json +++ b/webview-ui/src/i18n/locales/ko/chat.json @@ -345,6 +345,21 @@ "copy_code": "코드 복사" } }, + "parallelSubtasks": { + "title": "병렬 조사", + "progress": "{{total}}개 중 {{completed}}개 완료", + "status": { + "queued": "대기 중", + "running": "실행 중", + "completed": "완료됨", + "failed": "실패함", + "aborted": "중단됨" + }, + "openReport": "보고서", + "openDebugLog": "JSON 로그", + "goToTask": "작업으로 이동", + "noReport": "아직 보고서가 없습니다" + }, "profileViolationWarning": "현재 프로필이 조직 설정과 호환되지 않습니다", "shellIntegration": { "title": "명령 실행 경고", diff --git a/webview-ui/src/i18n/locales/ko/settings.json b/webview-ui/src/i18n/locales/ko/settings.json index f966df4cc2..d06a44969c 100644 --- a/webview-ui/src/i18n/locales/ko/settings.json +++ b/webview-ui/src/i18n/locales/ko/settings.json @@ -935,6 +935,10 @@ "DYNAMIC_THINKING_EFFORT": { "name": "동적 사고 노력", "description": "set_thinking_effort 도구를 이후 지원을 위해 준비합니다. 이 설정은 선호도만 저장하며, 요청별 동작은 후속 작업에서 제공됩니다. (실험적 기능)" + }, + "PARALLEL_SUBTASKS": { + "name": "병렬 하위 작업 활성화", + "description": "활성화하면 Zoo가 서로 다른 모드와 모델의 읽기 전용 백그라운드 조사 작업을 여러 개 동시에 실행하고 결과 보고서를 취합합니다. 자식 작업은 파일 쓰기, 명령 실행, 추가 위임이 구조적으로 차단됩니다." } }, "temperature": { diff --git a/webview-ui/src/i18n/locales/nl/chat.json b/webview-ui/src/i18n/locales/nl/chat.json index 0523738314..ed7c89af99 100644 --- a/webview-ui/src/i18n/locales/nl/chat.json +++ b/webview-ui/src/i18n/locales/nl/chat.json @@ -348,6 +348,21 @@ "copy_code": "Code kopiëren" } }, + "parallelSubtasks": { + "title": "Parallelle onderzoeken", + "progress": "{{completed}} van {{total}} voltooid", + "status": { + "queued": "In wachtrij", + "running": "Bezig", + "completed": "Voltooid", + "failed": "Mislukt", + "aborted": "Afgebroken" + }, + "openReport": "Rapport", + "openDebugLog": "JSON-log", + "goToTask": "Naar taak", + "noReport": "Nog geen rapport beschikbaar" + }, "profileViolationWarning": "Het huidige profiel is niet compatibel met de instellingen van uw organisatie", "shellIntegration": { "title": "Waarschuwing commando-uitvoering", diff --git a/webview-ui/src/i18n/locales/nl/settings.json b/webview-ui/src/i18n/locales/nl/settings.json index 2823b557da..301e8f6303 100644 --- a/webview-ui/src/i18n/locales/nl/settings.json +++ b/webview-ui/src/i18n/locales/nl/settings.json @@ -936,6 +936,10 @@ "DYNAMIC_THINKING_EFFORT": { "name": "Dynamisch denkwerk", "description": "Bereidt het set_thinking_effort-gereedschap voor op latere ondersteuning: deze instelling slaat alleen de voorkeur op, het gedrag per verzoek volgt in later werk. (experimenteel)" + }, + "PARALLEL_SUBTASKS": { + "name": "Parallelle subtaken inschakelen", + "description": "Wanneer ingeschakeld, kan Zoo meerdere alleen-lezen achtergrondonderzoekstaken in verschillende modi en modellen starten en hun rapporten verzamelen. Onderliggende taken zijn structureel geblokkeerd voor het schrijven van bestanden, het uitvoeren van opdrachten of het delegeren van verdere subtaken." } }, "temperature": { diff --git a/webview-ui/src/i18n/locales/pl/chat.json b/webview-ui/src/i18n/locales/pl/chat.json index 30997cccfc..3e51ae287c 100644 --- a/webview-ui/src/i18n/locales/pl/chat.json +++ b/webview-ui/src/i18n/locales/pl/chat.json @@ -354,6 +354,21 @@ "copy_code": "Kopiuj kod" } }, + "parallelSubtasks": { + "title": "Równoległe śledztwa", + "progress": "Ukończono {{completed}} z {{total}}", + "status": { + "queued": "W kolejce", + "running": "Wykonywanie", + "completed": "Ukończone", + "failed": "Niepowodzenie", + "aborted": "Przerwane" + }, + "openReport": "Raport", + "openDebugLog": "Dziennik JSON", + "goToTask": "Przejdź do zadania", + "noReport": "Raport nie jest jeszcze dostępny" + }, "profileViolationWarning": "Bieżący profil nie jest kompatybilny z ustawieniami Twojej organizacji", "shellIntegration": { "title": "Ostrzeżenie wykonania polecenia", diff --git a/webview-ui/src/i18n/locales/pl/settings.json b/webview-ui/src/i18n/locales/pl/settings.json index bc52a5c297..4396664328 100644 --- a/webview-ui/src/i18n/locales/pl/settings.json +++ b/webview-ui/src/i18n/locales/pl/settings.json @@ -938,6 +938,10 @@ "DYNAMIC_THINKING_EFFORT": { "name": "Dynamiczny wysiłek myślowy", "description": "Przygotowuje narzędzie set_thinking_effort do późniejszego wsparcia: to ustawienie zapisuje tylko preferencję, zachowanie na żądanie pojawi się w kolejnych pracach. (eksperymentalne)" + }, + "PARALLEL_SUBTASKS": { + "name": "Włącz równoległe podzadania", + "description": "Po włączeniu Zoo może uruchomić wiele zadań śledztwa w tle, z dostępem tylko do odczytu, w różnych trybach i modelach, a następnie zebrać ich raporty. Zadania podrzędne są strukturalnie zablokowane przed zapisywaniem plików, uruchamianiem poleceń i delegowaniem kolejnych podzadań." } }, "temperature": { diff --git a/webview-ui/src/i18n/locales/pt-BR/chat.json b/webview-ui/src/i18n/locales/pt-BR/chat.json index a865671b83..0ba7a38610 100644 --- a/webview-ui/src/i18n/locales/pt-BR/chat.json +++ b/webview-ui/src/i18n/locales/pt-BR/chat.json @@ -351,6 +351,21 @@ "copy_code": "Copiar código" } }, + "parallelSubtasks": { + "title": "Investigações paralelas", + "progress": "{{completed}} de {{total}} concluídas", + "status": { + "queued": "Na fila", + "running": "Executando", + "completed": "Concluída", + "failed": "Falhou", + "aborted": "Interrompida" + }, + "openReport": "Relatório", + "openDebugLog": "Log JSON", + "goToTask": "Ir para a tarefa", + "noReport": "Nenhum relatório disponível ainda" + }, "profileViolationWarning": "O perfil atual não é compatível com as configurações da sua organização", "shellIntegration": { "title": "Aviso de execução de comando", diff --git a/webview-ui/src/i18n/locales/pt-BR/settings.json b/webview-ui/src/i18n/locales/pt-BR/settings.json index f07b036233..b28ae03a04 100644 --- a/webview-ui/src/i18n/locales/pt-BR/settings.json +++ b/webview-ui/src/i18n/locales/pt-BR/settings.json @@ -937,6 +937,10 @@ "DYNAMIC_THINKING_EFFORT": { "name": "Esforço de pensamento dinâmico", "description": "Prepara a ferramenta set_thinking_effort para suporte posterior: esta configuração apenas salva a preferência, o comportamento por solicitação chegará em trabalho futuro. (experimental)" + }, + "PARALLEL_SUBTASKS": { + "name": "Habilitar subtarefas paralelas", + "description": "Quando habilitado, Zoo pode iniciar várias tarefas de investigação em segundo plano somente leitura em diferentes modos e modelos e depois coletar seus relatórios. As tarefas filhas são estruturalmente impedidas de escrever arquivos, executar comandos ou delegar mais subtarefas." } }, "temperature": { diff --git a/webview-ui/src/i18n/locales/ru/chat.json b/webview-ui/src/i18n/locales/ru/chat.json index 1da6f0846c..45d144208c 100644 --- a/webview-ui/src/i18n/locales/ru/chat.json +++ b/webview-ui/src/i18n/locales/ru/chat.json @@ -355,6 +355,21 @@ "copy_code": "Копировать код" } }, + "parallelSubtasks": { + "title": "Параллельные расследования", + "progress": "Выполнено {{completed}} из {{total}}", + "status": { + "queued": "В очереди", + "running": "Выполняется", + "completed": "Завершена", + "failed": "Не удалось", + "aborted": "Прервана" + }, + "openReport": "Отчёт", + "openDebugLog": "Журнал JSON", + "goToTask": "Перейти к задаче", + "noReport": "Отчёт пока недоступен" + }, "profileViolationWarning": "Текущий профиль несовместим с настройками вашей организации", "shellIntegration": { "title": "Предупреждение о выполнении команды", diff --git a/webview-ui/src/i18n/locales/ru/settings.json b/webview-ui/src/i18n/locales/ru/settings.json index 826bbb8451..0cc1708bb5 100644 --- a/webview-ui/src/i18n/locales/ru/settings.json +++ b/webview-ui/src/i18n/locales/ru/settings.json @@ -938,6 +938,10 @@ "DYNAMIC_THINKING_EFFORT": { "name": "Динамическое усилие размышления", "description": "Подготавливает инструмент set_thinking_effort к последующей поддержке: этот параметр сохраняет только предпочтение, поведение для каждого запроса появится в дальнейшей работе. (экспериментально)" + }, + "PARALLEL_SUBTASKS": { + "name": "Включить параллельные подзадачи", + "description": "Когда включено, Zoo может запускать несколько фоновых задач расследования с доступом только для чтения в разных режимах и моделях, а затем собирать их отчёты. Дочерние задачи структурно заблокированы от записи файлов, выполнения команд и делегирования новых подзадач." } }, "temperature": { diff --git a/webview-ui/src/i18n/locales/tr/chat.json b/webview-ui/src/i18n/locales/tr/chat.json index 30902a0dd0..65cd250e82 100644 --- a/webview-ui/src/i18n/locales/tr/chat.json +++ b/webview-ui/src/i18n/locales/tr/chat.json @@ -349,6 +349,21 @@ "copy_code": "Kodu kopyala" } }, + "parallelSubtasks": { + "title": "Paralel araştırmalar", + "progress": "{{total}} görevin {{completed}} tanesi tamamlandı", + "status": { + "queued": "Kuyrukta", + "running": "Çalışıyor", + "completed": "Tamamlandı", + "failed": "Başarısız", + "aborted": "İptal edildi" + }, + "openReport": "Rapor", + "openDebugLog": "JSON günlüğü", + "goToTask": "Göreve git", + "noReport": "Henüz rapor yok" + }, "profileViolationWarning": "Geçerli profil kuruluşunuzun ayarlarıyla uyumlu değil", "shellIntegration": { "title": "Komut Çalıştırma Uyarısı", diff --git a/webview-ui/src/i18n/locales/tr/settings.json b/webview-ui/src/i18n/locales/tr/settings.json index f37e886c2e..60ada2ad66 100644 --- a/webview-ui/src/i18n/locales/tr/settings.json +++ b/webview-ui/src/i18n/locales/tr/settings.json @@ -936,6 +936,10 @@ "DYNAMIC_THINKING_EFFORT": { "name": "Dinamik düşünme çabası", "description": "set_thinking_effort aracını sonraki destek için hazırlar: bu ayar yalnızca tercihi saklar, istek başına davranış sonraki çalışmada gelir. (deneysel)" + }, + "PARALLEL_SUBTASKS": { + "name": "Paralel alt görevleri etkinleştir", + "description": "Etkinleştirildiğinde, Zoo farklı modlarda ve modellerde birden fazla salt-okunur arka plan araştırma görevi başlatabilir ve ardından raporlarını toplayabilir. Alt görevler dosya yazma, komut çalıştırma veya başka alt görevlere delege etme konusunda yapısal olarak engellenir." } }, "temperature": { diff --git a/webview-ui/src/i18n/locales/vi/chat.json b/webview-ui/src/i18n/locales/vi/chat.json index b6468c44f7..e688b386ba 100644 --- a/webview-ui/src/i18n/locales/vi/chat.json +++ b/webview-ui/src/i18n/locales/vi/chat.json @@ -346,6 +346,21 @@ "copy_code": "Sao chép mã" } }, + "parallelSubtasks": { + "title": "Điều tra song song", + "progress": "Hoàn thành {{completed}} trong tổng số {{total}}", + "status": { + "queued": "Đang chờ", + "running": "Đang chạy", + "completed": "Hoàn thành", + "failed": "Thất bại", + "aborted": "Đã hủy" + }, + "openReport": "Báo cáo", + "openDebugLog": "Nhật ký JSON", + "goToTask": "Đến nhiệm vụ", + "noReport": "Chưa có báo cáo nào" + }, "profileViolationWarning": "Hồ sơ hiện tại không tương thích với cài đặt của tổ chức của bạn", "shellIntegration": { "title": "Cảnh báo thực thi lệnh", diff --git a/webview-ui/src/i18n/locales/vi/settings.json b/webview-ui/src/i18n/locales/vi/settings.json index b17f4994cf..7703969431 100644 --- a/webview-ui/src/i18n/locales/vi/settings.json +++ b/webview-ui/src/i18n/locales/vi/settings.json @@ -935,6 +935,10 @@ "DYNAMIC_THINKING_EFFORT": { "name": "Nỗ lực suy nghĩ động", "description": "Chuẩn bị công cụ set_thinking_effort cho hỗ trợ sau này: cài đặt này chỉ lưu tùy chọn, hành vi theo từng yêu cầu sẽ đến trong công việc tiếp theo. (thử nghiệm)" + }, + "PARALLEL_SUBTASKS": { + "name": "Bật nhiệm vụ phụ song song", + "description": "Khi bật, Zoo có thể khởi tạo nhiều nhiệm vụ điều tra nền chỉ-đọc ở các chế độ và mô hình khác nhau, rồi thu thập báo cáo của chúng. Các nhiệm vụ con bị chặn về mặt cấu trúc khỏi việc ghi tệp, chạy lệnh hoặc ủy quyền thêm nhiệm vụ phụ." } }, "temperature": { diff --git a/webview-ui/src/i18n/locales/zh-CN/chat.json b/webview-ui/src/i18n/locales/zh-CN/chat.json index ab3bc22c67..1539fd0564 100644 --- a/webview-ui/src/i18n/locales/zh-CN/chat.json +++ b/webview-ui/src/i18n/locales/zh-CN/chat.json @@ -346,6 +346,21 @@ "copy_code": "复制代码" } }, + "parallelSubtasks": { + "title": "并行调查", + "progress": "已完成 {{completed}} / {{total}}", + "status": { + "queued": "排队中", + "running": "运行中", + "completed": "已完成", + "failed": "失败", + "aborted": "已中止" + }, + "openReport": "报告", + "openDebugLog": "JSON 日志", + "goToTask": "转到任务", + "noReport": "暂无可用报告" + }, "profileViolationWarning": "当前配置文件与您的组织设置不兼容", "shellIntegration": { "title": "命令执行警告", diff --git a/webview-ui/src/i18n/locales/zh-CN/settings.json b/webview-ui/src/i18n/locales/zh-CN/settings.json index bf35d38801..039aefc432 100644 --- a/webview-ui/src/i18n/locales/zh-CN/settings.json +++ b/webview-ui/src/i18n/locales/zh-CN/settings.json @@ -935,6 +935,10 @@ "DYNAMIC_THINKING_EFFORT": { "name": "动态思考强度", "description": "为后续支持准备 set_thinking_effort 工具:此设置仅保存偏好,按请求的工具行为将在后续工作中提供。(实验性功能)" + }, + "PARALLEL_SUBTASKS": { + "name": "启用并行子任务", + "description": "启用后,Zoo 可以在不同模式和模型中生成多个只读后台调查任务,然后收集它们的报告。子任务在结构上被阻止写入文件、运行命令或委派更多子任务。" } }, "temperature": { diff --git a/webview-ui/src/i18n/locales/zh-TW/chat.json b/webview-ui/src/i18n/locales/zh-TW/chat.json index 8143b8434b..95862c1058 100644 --- a/webview-ui/src/i18n/locales/zh-TW/chat.json +++ b/webview-ui/src/i18n/locales/zh-TW/chat.json @@ -375,6 +375,21 @@ "copy_code": "複製程式碼" } }, + "parallelSubtasks": { + "title": "平行調查", + "progress": "已完成 {{completed}}/{{total}}", + "status": { + "queued": "佇列中", + "running": "執行中", + "completed": "已完成", + "failed": "失敗", + "aborted": "已中止" + }, + "openReport": "報告", + "openDebugLog": "JSON 記錄", + "goToTask": "前往工作", + "noReport": "尚無可用報告" + }, "profileViolationWarning": "目前設定檔與您的組織設定不相容", "shellIntegration": { "title": "命令執行警告", diff --git a/webview-ui/src/i18n/locales/zh-TW/settings.json b/webview-ui/src/i18n/locales/zh-TW/settings.json index 6478135187..8726a8930d 100644 --- a/webview-ui/src/i18n/locales/zh-TW/settings.json +++ b/webview-ui/src/i18n/locales/zh-TW/settings.json @@ -962,6 +962,10 @@ "DYNAMIC_THINKING_EFFORT": { "name": "動態思考強度", "description": "為後續支援準備 set_thinking_effort 工具:此設定僅儲存偏好,逐次請求的工具行為會在後續工作中提供。(實驗性)" + }, + "PARALLEL_SUBTASKS": { + "name": "啟用平行子任務", + "description": "啟用後,Zoo 可以在不同模式和模型中產生多個唯讀背景調查工作,然後收集它們的報告。子工作在結構上被封鎖,無法寫入檔案、執行命令或委派更多子任務。" } }, "temperature": { diff --git a/webview-ui/src/utils/__tests__/chatBatchingPredicates.spec.ts b/webview-ui/src/utils/__tests__/chatBatchingPredicates.spec.ts new file mode 100644 index 0000000000..bfd5e89de4 --- /dev/null +++ b/webview-ui/src/utils/__tests__/chatBatchingPredicates.spec.ts @@ -0,0 +1,110 @@ +import { isBoundary, isIgnorableBetweenTargets } from "../chatBatchingPredicates" +import { batchNearby } from "../batchNearby" + +interface TestItem { + ts: number + type: string + text: string + say?: string +} + +const sayToolRow = (text: string): TestItem => ({ + ts: Date.now(), + type: "say", + say: "tool", + text, +}) + +describe("chatBatchingPredicates - parallelSubtasks", () => { + it("treats the parallelSubtasks panel row as a boundary", () => { + expect(isBoundary({ type: "say", say: "tool", text: '{"tool":"parallelSubtasks","subtasks":[]}' })).toBe(true) + }) + + it("does not treat other say tool rows as boundaries", () => { + expect(isBoundary({ type: "say", say: "tool", text: '{"tool":"runSlashCommand","command":"test"}' })).toBe( + false, + ) + }) + + it("does not treat a row that merely contains the literal as a boundary (F-12)", () => { + expect( + isBoundary({ + type: "say", + say: "tool", + text: '{"tool":"runSlashCommand","command":"grep parallelSubtasks src"}', + }), + ).toBe(false) + }) + + it("does not treat a malformed row that contains the literal as a boundary", () => { + expect(isBoundary({ type: "say", say: "tool", text: '{"tool":"parallelSubtasks",' })).toBe(false) + }) + + it("keeps rows of other say types non-boundary even when they contain the literal (F-12)", () => { + expect(isBoundary({ type: "say", say: "command_output", text: "log: parallelSubtasks launched" })).toBe(false) + expect(isBoundary({ type: "ask", text: '{"tool":"parallelSubtasks"}' })).toBe(false) + }) + + it("does not treat a parallelSubtasks say row as ignorable between targets", () => { + const batchContext: TestItem = { ts: 1, type: "say", say: "tool", text: "{}" } + expect( + isIgnorableBetweenTargets({ type: "say", say: "tool", text: '{"tool":"parallelSubtasks"}' }, batchContext), + ).toBe(false) + }) + + it("keeps non-say messages non-boundary", () => { + expect(isBoundary({ type: "ask", say: "parallelSubtasks" })).toBe(false) + }) + + it("preserves boundary behavior for every pre-existing say type", () => { + expect(isBoundary({ type: "say", say: "user_feedback" })).toBe(true) + expect(isBoundary({ type: "say", say: "user_feedback_diff" })).toBe(true) + expect(isBoundary({ type: "say", say: "text", text: "visible" })).toBe(true) + expect(isBoundary({ type: "say", say: "completion_result" })).toBe(true) + expect(isBoundary({ type: "say", say: "checkpoint_saved" })).toBe(true) + expect(isBoundary({ type: "say", say: "error" })).toBe(true) + expect(isBoundary({ type: "say", say: "condense_context" })).toBe(true) + expect(isBoundary({ type: "say", say: "codebase_search_result" })).toBe(true) + }) + + it("preserves non-boundary behavior for pre-existing say types", () => { + expect(isBoundary({ type: "say", say: "text", text: "" })).toBe(false) + expect(isBoundary({ type: "say", say: "api_req_started" })).toBe(false) + expect(isBoundary({ type: "say", say: "reasoning" })).toBe(false) + expect(isBoundary({ type: "say", say: "command_output" })).toBe(false) + }) + + it("preserves ignorable behavior for pre-existing say types", () => { + expect(isIgnorableBetweenTargets({ type: "say", say: "api_req_started" })).toBe(true) + expect(isIgnorableBetweenTargets({ type: "say", say: "reasoning" })).toBe(true) + expect(isIgnorableBetweenTargets({ type: "say", say: "text", text: "" })).toBe(true) + expect(isIgnorableBetweenTargets({ type: "say", say: "error" })).toBe(false) + }) +}) + +describe("batchNearby - parallelSubtasks panel row", () => { + // Mirrors ChatView's isReadFileAsk: targets are tool *asks* only, so the + // panel row (a say message) is never a batch target itself. + const isToolAsk = (m: TestItem) => m.type === "ask" && !!m.text?.startsWith("{") + const synthesizeBatch = (batch: TestItem[]): TestItem => ({ + ...batch[0], + text: `BATCH:${batch.map((m) => m.text).join(",")}`, + }) + const options = { + isTarget: isToolAsk, + isIgnorableBetweenTargets, + isBoundary, + synthesize: synthesizeBatch, + } + + it("splits adjacent tool asks around the panel row instead of merging them", () => { + const panelRow = sayToolRow(JSON.stringify({ tool: "parallelSubtasks", subtasks: [] })) + const messages: TestItem[] = [ + { ts: 1, type: "ask", text: '{"tool":"readFile"}' }, + panelRow, + { ts: 3, type: "ask", text: '{"tool":"editFile"}' }, + ] + const result = batchNearby(messages, options) + expect(result).toEqual(messages) + }) +}) diff --git a/webview-ui/src/utils/chatBatchingPredicates.ts b/webview-ui/src/utils/chatBatchingPredicates.ts index b011605642..3226229ecb 100644 --- a/webview-ui/src/utils/chatBatchingPredicates.ts +++ b/webview-ui/src/utils/chatBatchingPredicates.ts @@ -4,6 +4,25 @@ interface BatchableMessage { text?: string } +const isToolRecord = (value: unknown): value is { tool: string } => + typeof value === "object" && value !== null && typeof (value as { tool?: unknown }).tool === "string" + +/** + * Tool name carried by a say-tool row's JSON text. Partial or non-JSON payloads + * carry no tool field, so they never match. + */ +const parseToolName = (text?: string): string | undefined => { + if (!text) { + return undefined + } + try { + const parsed: unknown = JSON.parse(text) + return isToolRecord(parsed) ? parsed.tool : undefined + } catch { + return undefined + } +} + /** * Messages that can be safely skipped over when batching tool asks. * These are low-information or invisible messages that don't affect semantics. @@ -36,6 +55,13 @@ export const isBoundary = (msg: BatchableMessage): boolean => { msg.say === "checkpoint_saved" || msg.say === "error" || msg.say === "condense_context" || - msg.say === "codebase_search_result" + msg.say === "codebase_search_result" || + // The parallel-subtasks panel (design D9) is a say "tool" row whose + // JSON text carries { tool: "parallelSubtasks" }. It renders live child + // state, so merging it into an adjacent tool-ask batch would freeze the + // panel; treat it as a semantic boundary. The parsed tool field is the + // identity test, so unrelated rows that merely contain the literal do not + // match (F-12). + (msg.say === "tool" && parseToolName(msg.text) === "parallelSubtasks") ) }