From 73a11e1fc45738e911132f8b7dcad2561df65057 Mon Sep 17 00:00:00 2001 From: Phil Date: Sat, 5 Dec 2026 01:01:52 +0100 Subject: [PATCH 1/2] fix(task): return a skipped subtask handoff to the orchestrator (issue 2677) Failure: after one transient handoff skip, the user accepts the completion ask; the provider recorded the child completed while its parent still awaited it, and every later attempt_completion then stopped as a stale replay, so the result never reached the orchestrator. - AttemptCompletionTool: while the parent still awaits the child, a yes on the completion ask re-attempts the delegation instead of acknowledging the child in place. - ClineProvider onTaskCompleted: a still-awaited child is no longer recorded completed outside completeDelegatedChild (the only writer that frees the parent in the same atomic step). - task-persistence: parentStillAwaitsChild predicate shared by both. Spec: docs/architecture/tla/SubtaskReturn.tla (new). TLC: SubtaskReturn.cfg pass (3 states); SubtaskReturn.Poison.cfg fails NoPoisonedCompletion (4 states) - the reproduction on the pre-fix behavior. Tests red-verified on the unfixed code (9 failing) and sabotage-verified after the fix; test:core 5328 green; test:api 6417 green (node 22.23.4); tsc, eslint, prettier clean. --- .../architecture/tla/SubtaskReturn.Poison.cfg | 5 + docs/architecture/tla/SubtaskReturn.cfg | 5 + docs/architecture/tla/SubtaskReturn.tla | 88 ++++ .../__tests__/taskLifecycle.spec.ts | 43 ++ src/core/task-persistence/index.ts | 1 + src/core/task-persistence/taskLifecycle.ts | 22 + src/core/tools/AttemptCompletionTool.ts | 51 ++ .../__tests__/attemptCompletionTool.spec.ts | 133 ++++++ src/core/webview/ClineProvider.ts | 10 +- ...lineProvider.task-completed-status.spec.ts | 441 ++++++++++++++++++ 10 files changed, 798 insertions(+), 1 deletion(-) create mode 100644 docs/architecture/tla/SubtaskReturn.Poison.cfg create mode 100644 docs/architecture/tla/SubtaskReturn.cfg create mode 100644 docs/architecture/tla/SubtaskReturn.tla create mode 100644 src/core/webview/__tests__/ClineProvider.task-completed-status.spec.ts diff --git a/docs/architecture/tla/SubtaskReturn.Poison.cfg b/docs/architecture/tla/SubtaskReturn.Poison.cfg new file mode 100644 index 00000000000..d2a5706cb71 --- /dev/null +++ b/docs/architecture/tla/SubtaskReturn.Poison.cfg @@ -0,0 +1,5 @@ +SPECIFICATION Spec +CONSTANTS + Mode = "Poison" +INVARIANTS TypeOK NoPoisonedCompletion +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/SubtaskReturn.cfg b/docs/architecture/tla/SubtaskReturn.cfg new file mode 100644 index 00000000000..28d14e056cc --- /dev/null +++ b/docs/architecture/tla/SubtaskReturn.cfg @@ -0,0 +1,5 @@ +SPECIFICATION Spec +CONSTANTS + Mode = "Guarded" +INVARIANTS TypeOK NoPoisonedCompletion +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/SubtaskReturn.tla b/docs/architecture/tla/SubtaskReturn.tla new file mode 100644 index 00000000000..5ab06dbb19d --- /dev/null +++ b/docs/architecture/tla/SubtaskReturn.tla @@ -0,0 +1,88 @@ +---- MODULE SubtaskReturn ---- +\* Models the orchestrator subtask handoff: AttemptCompletionTool.execute with a +\* set parentTaskId, reopenParentFromDelegation, and the provider onTaskCompleted +\* listener (src/core/webview/ClineProvider.ts). +\* Source: the child records its final response and asks to return to the parent. +\* Sink: the parent record leaves delegated/awaiting, or a "completed" write lands +\* on a child its parent still awaits. +\* Failure: after one transient handoff skip, the user accepts the completion ask; +\* the listener records the child "completed" while the parent still awaits it, +\* and every later attempt_completion then reads "completed", stops as a stale +\* replay, and the result never reaches the orchestrator (issue 2677). +\* Invariant NoPoisonedCompletion: no reachable state records the child +\* "completed" while the parent record still awaits that child. +\* Modes: "Guarded" (fix - the accept re-runs the handoff while the parent +\* awaits, and the listener write defers to completeDelegatedChild) and +\* "Poison" (pre-fix - the accept writes "completed" in place). +\* Result: "Poison" fails NoPoisonedCompletion (reproduction). "Guarded" holds. +\* Model-checked 2026-12-05, tla2tools 1.7.4. +\* Review: 0 covered, 0 added, 0 gap (first version). +\* Not modeled: approval denial, persistence retries, cancellation, grandchild +\* delegation, and the message content itself (oracle: taskLifecycle.ts). + +EXTENDS Naturals + +CONSTANTS Mode + +VARIABLES parentAwaiting, childStatus, phase +vars == <> + +Init == /\ parentAwaiting = "child" + /\ childStatus = "active" + /\ phase = "running" + +\* The child streams its final response. The handoff either completes (the +\* reopen succeeds: the pair update frees the parent and completes the child) +\* or is skipped once (transient gate miss or reopen failure) and the tool +\* falls through to the plain completion ask. +AttemptReturn == + /\ phase = "running" + /\ IF parentAwaiting = "child" + THEN \/ /\ phase' = "handedOff" + /\ parentAwaiting' = "none" + /\ childStatus' = "completed" + \/ /\ phase' = "askUser" + /\ UNCHANGED <> + ELSE /\ phase' = "askUser" + /\ UNCHANGED <> + +\* The user answers the completion ask. "Poison" records the child completed +\* in place; the parent record keeps awaiting. "Guarded" re-runs the handoff +\* while the parent still awaits this child; only a free child completes in +\* place. A poisoned child can never re-run the handoff: the stale-replay +\* gate reads "completed" and skips delegation forever. +AcceptCompletion == + /\ phase = "askUser" + /\ IF Mode = "Guarded" + THEN IF parentAwaiting = "child" + THEN /\ phase' = "handedOff" + /\ parentAwaiting' = "none" + /\ childStatus' = "completed" + ELSE /\ childStatus' = "completed" + /\ phase' = "closed" + /\ UNCHANGED parentAwaiting + ELSE /\ childStatus' = "completed" + /\ phase' = "closed" + /\ UNCHANGED parentAwaiting + +\* The user re-prompts the model. A live child retries the handoff; a child +\* already recorded "completed" is treated as a stale replay and stays stuck. +PromptAgain == + /\ phase \in {"running", "closed"} + /\ IF childStatus = "active" /\ parentAwaiting = "child" + THEN phase' = "running" + ELSE phase' = phase + /\ UNCHANGED <> + +Next == AttemptReturn \/ AcceptCompletion \/ PromptAgain + +Spec == Init /\ [][Next]_vars + +TypeOK == /\ parentAwaiting \in {"child", "none"} + /\ childStatus \in {"active", "completed"} + /\ phase \in {"running", "askUser", "handedOff", "closed"} + +NoPoisonedCompletion == ~(childStatus = "completed" + /\ parentAwaiting = "child") + +==== diff --git a/src/core/task-persistence/__tests__/taskLifecycle.spec.ts b/src/core/task-persistence/__tests__/taskLifecycle.spec.ts index 5d3129e0237..dff754c67e0 100644 --- a/src/core/task-persistence/__tests__/taskLifecycle.spec.ts +++ b/src/core/task-persistence/__tests__/taskLifecycle.spec.ts @@ -6,6 +6,7 @@ import { delegateTaskToChild, interruptDelegatedChild, LifecycleTransitionError, + parentStillAwaitsChild, settleRejectedCreateSubtaskAction, } from "../taskLifecycle" @@ -185,3 +186,45 @@ describe("settleRejectedCreateSubtaskAction", () => { ) }) }) + +describe("parentStillAwaitsChild", () => { + it("sees a delegated parent awaiting the child", () => { + const parent = item("parent", { status: "delegated", awaitingChildId: "child" }) + const child = item("child", { parentTaskId: "parent" }) + + expect(parentStillAwaitsChild(child, (id) => (id === "parent" ? parent : undefined))).toBe(true) + }) + + it("sees a reopened parent that still awaits the child", () => { + const parent = item("parent", { status: "active", awaitingChildId: "child" }) + const child = item("child", { parentTaskId: "parent" }) + + expect(parentStillAwaitsChild(child, (id) => (id === "parent" ? parent : undefined))).toBe(true) + }) + + it("does not see a parent awaiting a different child", () => { + const parent = item("parent", { status: "delegated", awaitingChildId: "other-child" }) + const child = item("child", { parentTaskId: "parent" }) + + expect(parentStillAwaitsChild(child, (id) => (id === "parent" ? parent : undefined))).toBe(false) + }) + + it("does not see a parent whose awaiting id is unset", () => { + const parent = item("parent", { status: "delegated", awaitingChildId: undefined }) + const child = item("child", { parentTaskId: "parent" }) + + expect(parentStillAwaitsChild(child, (id) => (id === "parent" ? parent : undefined))).toBe(false) + }) + + it("does not see a parent for a top-level task", () => { + const child = item("child") + + expect(parentStillAwaitsChild(child, () => undefined)).toBe(false) + }) + + it("does not see a missing parent record", () => { + const child = item("child", { parentTaskId: "parent" }) + + expect(parentStillAwaitsChild(child, () => undefined)).toBe(false) + }) +}) diff --git a/src/core/task-persistence/index.ts b/src/core/task-persistence/index.ts index 0baf9ce57e6..32c4f34847e 100644 --- a/src/core/task-persistence/index.ts +++ b/src/core/task-persistence/index.ts @@ -21,6 +21,7 @@ export { delegateTaskToChild, interruptDelegatedChild, LifecycleTransitionError, + parentStillAwaitsChild, settleRejectedCreateSubtaskAction, type HistoryItemStatus, VALID_TASK_STATUS_TRANSITIONS, diff --git a/src/core/task-persistence/taskLifecycle.ts b/src/core/task-persistence/taskLifecycle.ts index b8a5e571f03..020ee4a8a25 100644 --- a/src/core/task-persistence/taskLifecycle.ts +++ b/src/core/task-persistence/taskLifecycle.ts @@ -130,3 +130,25 @@ export function abandonDelegatedChild( }, } } + +/** + * True when a parent record still delegates to and awaits this child. Only + * completeDelegatedChild may record a still-awaited child "completed", and it + * frees the parent in the same atomic step (#2677). Any other "completed" + * write over such a child poisons the return gate: every later + * attempt_completion reads "completed", skips the handoff as a stale replay, + * and the result never reaches the orchestrator. + */ +export function parentStillAwaitsChild( + child: HistoryItem, + getParent: (parentTaskId: string) => HistoryItem | undefined, +): boolean { + if (!child.parentTaskId) { + return false + } + const parent = getParent(child.parentTaskId) + if (!parent) { + return false + } + return (parent.status === "delegated" || parent.status === "active") && parent.awaitingChildId === child.id +} diff --git a/src/core/tools/AttemptCompletionTool.ts b/src/core/tools/AttemptCompletionTool.ts index 3114e753c5e..1e3ea929f81 100644 --- a/src/core/tools/AttemptCompletionTool.ts +++ b/src/core/tools/AttemptCompletionTool.ts @@ -221,6 +221,37 @@ export class AttemptCompletionTool extends BaseTool<"attempt_completion"> { const { response, text, images, queuedMessageId, segments } = await task.ask("completion_result", "", false) if (response === "yesButtonClicked") { + // A skipped handoff (a transient gate miss or a failed reopen) used to + // land here: the user accepted the completion ask, the provider recorded + // the child "completed", and every later attempt_completion then stopped + // as a stale replay - the result never reached the orchestrator (#2677). + // While the parent still awaits this child, the yes button re-attempts + // the handoff instead of acknowledging the child in place. + if (!isStaleHistoryReplay && task.parentTaskId) { + const provider = task.providerRef.deref() as DelegationProvider | undefined + + if (provider && (await this.parentStillAwaitingChild(task, provider))) { + const delegation = await this.delegateToParent( + task, + result, + provider, + undefined, + askFinishSubTaskApproval, + pushToolResult, + ) + + if (delegation === "delegated") { + task.emitFinalTokenUsageUpdate() + provider.emitDelegatedTaskCompleted(task.taskId, task.getTokenUsage(), task.toolUsage) + } + + if (delegation !== "continue") { + return + } + // "continue": the reopen found the parent detached after all. + // Fall through to the plain acknowledgment below. + } + } // A stale history replay reruns this handler on a fresh Task instance for a // subtask that already completed (and already emitted TaskCompleted) the first // time through -- re-acknowledging it from history must not emit it again. @@ -297,6 +328,26 @@ export class AttemptCompletionTool extends BaseTool<"attempt_completion"> { return "delegated" } + /** + * Re-reads the delegation gate before a retried handoff: the parent record + * must still await this child. A read failure counts as "not awaiting", so + * the caller keeps the plain acknowledgment path (#2677). + */ + private async parentStillAwaitingChild(task: Task, provider: DelegationProvider): Promise { + if (!task.parentTaskId) { + return false + } + try { + const { historyItem: parentHistory } = await provider.getTaskWithId(task.parentTaskId) + return ( + (parentHistory?.status === "delegated" || parentHistory?.status === "active") && + parentHistory?.awaitingChildId === task.taskId + ) + } catch { + return false + } + } + override async handlePartial(task: Task, block: ToolUse<"attempt_completion">): Promise { const result: string | undefined = block.params.result const command: string | undefined = block.params.command diff --git a/src/core/tools/__tests__/attemptCompletionTool.spec.ts b/src/core/tools/__tests__/attemptCompletionTool.spec.ts index 691a0c6c835..a1babb67529 100644 --- a/src/core/tools/__tests__/attemptCompletionTool.spec.ts +++ b/src/core/tools/__tests__/attemptCompletionTool.spec.ts @@ -1245,6 +1245,139 @@ describe("attemptCompletionTool", () => { expect(mockProvider.clearPendingTaskAction).not.toHaveBeenCalled() expect(mockTask.ask).toHaveBeenCalledWith("completion_result", "", false) }) + + it("returns the ball to a still-awaiting parent when the user accepts the completion ask after a failed handoff", async () => { + const block: ToolUse<"attempt_completion"> = { + type: "tool_use", + name: "attempt_completion", + params: { result: "9" }, + nativeArgs: { result: "9" }, + partial: false, + } + const mockProvider = { + log: vi.fn(), + getTaskWithId: vi.fn().mockImplementation((id: string) => { + if (id === "child-1") { + return Promise.resolve({ historyItem: { id, status: "active" } }) + } + if (id === "parent-1") { + return Promise.resolve({ + historyItem: { id, status: "delegated", awaitingChildId: "child-1" }, + }) + } + throw new Error(`unexpected task id ${id}`) + }), + setPendingTaskAction: vi.fn().mockResolvedValue(undefined), + clearPendingTaskAction: vi.fn().mockResolvedValue(true), + reopenParentFromDelegation: vi.fn().mockResolvedValueOnce(false).mockResolvedValueOnce(true), + emitDelegatedTaskCompleted: vi.fn(), + } + + Object.assign(mockTask, { + taskId: "child-1", + parentTaskId: "parent-1", + providerRef: { deref: () => mockProvider }, + }) + mockTask.ask = vi.fn().mockResolvedValue({ response: "yesButtonClicked", text: "", images: [] }) + mockAskFinishSubTaskApproval.mockResolvedValue(true) + + const callbacks: AttemptCompletionCallbacks = { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + askFinishSubTaskApproval: mockAskFinishSubTaskApproval, + toolDescription: mockToolDescription, + toolCallId: "call-retry", + } + + await attemptCompletionTool.handle(mockTask as Task, block, callbacks) + + // The first handoff fails once (transient), the tool falls through to the + // completion ask, and the user's yes must re-attempt the delegation instead + // of acknowledging a subtask its parent still awaits (issue #2677). + expect(mockProvider.reopenParentFromDelegation).toHaveBeenCalledTimes(2) + expect(mockProvider.reopenParentFromDelegation).toHaveBeenNthCalledWith(1, { + parentTaskId: "parent-1", + childTaskId: "child-1", + completionResultSummary: "9", + pendingActionId: "call-retry", + }) + expect(mockProvider.reopenParentFromDelegation).toHaveBeenNthCalledWith(2, { + parentTaskId: "parent-1", + childTaskId: "child-1", + completionResultSummary: "9", + }) + expect(mockProvider.clearPendingTaskAction).toHaveBeenCalledWith("child-1", "call-retry") + expect(mockProvider.emitDelegatedTaskCompleted).toHaveBeenCalledTimes(1) + expect(mockPushToolResult).toHaveBeenCalledWith("") + expect(mockTask.emit).not.toHaveBeenCalledWith( + RooCodeEventName.TaskCompleted, + expect.anything(), + expect.anything(), + expect.anything(), + ) + }) + + it("falls back to a standalone acknowledgment when the user denies the retried finish ask", async () => { + const block: ToolUse<"attempt_completion"> = { + type: "tool_use", + name: "attempt_completion", + params: { result: "9" }, + nativeArgs: { result: "9" }, + partial: false, + } + const mockProvider = { + log: vi.fn(), + getTaskWithId: vi.fn().mockImplementation((id: string) => { + if (id === "child-1") { + return Promise.resolve({ historyItem: { id, status: "active" } }) + } + if (id === "parent-1") { + return Promise.resolve({ + historyItem: { id, status: "delegated", awaitingChildId: "child-1" }, + }) + } + throw new Error(`unexpected task id ${id}`) + }), + setPendingTaskAction: vi.fn().mockResolvedValue(undefined), + clearPendingTaskAction: vi.fn().mockResolvedValue(true), + reopenParentFromDelegation: vi.fn().mockResolvedValue(false), + emitDelegatedTaskCompleted: vi.fn(), + } + + Object.assign(mockTask, { + taskId: "child-1", + parentTaskId: "parent-1", + providerRef: { deref: () => mockProvider }, + }) + mockTask.ask = vi.fn().mockResolvedValue({ response: "yesButtonClicked", text: "", images: [] }) + mockAskFinishSubTaskApproval.mockResolvedValueOnce(true).mockResolvedValueOnce(false) + + const callbacks: AttemptCompletionCallbacks = { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + askFinishSubTaskApproval: mockAskFinishSubTaskApproval, + toolDescription: mockToolDescription, + toolCallId: "call-retry-deny", + } + + await attemptCompletionTool.handle(mockTask as Task, block, callbacks) + + expect(mockAskFinishSubTaskApproval).toHaveBeenCalledTimes(2) + expect(mockProvider.reopenParentFromDelegation).toHaveBeenCalledTimes(1) + expect(mockProvider.clearPendingTaskAction).toHaveBeenCalledWith("child-1", "call-retry-deny") + expect(mockProvider.emitDelegatedTaskCompleted).not.toHaveBeenCalled() + // The user chose to keep the subtask open: the retried finish ask resolves + // like the first one, with a tool denial the model can act on. + expect(mockPushToolResult).toHaveBeenCalledWith("Denied") + expect(mockTask.emit).not.toHaveBeenCalledWith( + RooCodeEventName.TaskCompleted, + expect.anything(), + expect.anything(), + expect.anything(), + ) + }) }) }) }) diff --git a/src/core/webview/ClineProvider.ts b/src/core/webview/ClineProvider.ts index 32714067fa2..5fbf23dfa40 100644 --- a/src/core/webview/ClineProvider.ts +++ b/src/core/webview/ClineProvider.ts @@ -152,6 +152,7 @@ import { delegateTaskToChild, interruptDelegatedChild, LifecycleTransitionError, + parentStillAwaitsChild, } from "../task-persistence" import { readTaskMessages } from "../task-persistence/taskMessages" import { readFileWithMissingRetry } from "../task-persistence/readFileWithMissingRetry" @@ -546,9 +547,16 @@ export class ClineProvider // saveClineMessages() omits the status field for top-level tasks, which causes // the store's merge to preserve a stale "interrupted" status after completion. // interrupted → completed is a valid VALID_TRANSITIONS path. + // A child whose parent still awaits it is exempt (#2677): recording it + // "completed" outside completeDelegatedChild makes every later + // attempt_completion skip the handoff as a stale replay. try { const existing = this.taskHistoryStore.get(taskId) - if (existing && existing.status !== "completed") { + if ( + existing && + existing.status !== "completed" && + !parentStillAwaitsChild(existing, (parentId) => this.taskHistoryStore.get(parentId)) + ) { await this.updateTaskHistory({ ...existing, status: "completed" }) } } catch (err) { diff --git a/src/core/webview/__tests__/ClineProvider.task-completed-status.spec.ts b/src/core/webview/__tests__/ClineProvider.task-completed-status.spec.ts new file mode 100644 index 00000000000..a01cf45b3ba --- /dev/null +++ b/src/core/webview/__tests__/ClineProvider.task-completed-status.spec.ts @@ -0,0 +1,441 @@ +import { RooCodeEventName } from "@roo-code/types" +import { WebviewFocusTracker } from "../WebviewFocusTracker" +import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest" +import * as vscode from "vscode" + +import { ClineProvider } from "../ClineProvider" +import { Task } from "../../task/Task" +import { ContextProxy } from "../../config/ContextProxy" +import type { ProviderSettings, HistoryItem } from "@roo-code/types" +import { providerIdentifiers } from "@roo-code/types/provider-identifiers" + +// Mock dependencies +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(), + createTextEditorDecorationType: vi.fn().mockReturnValue({ + dispose: vi.fn(), + }), + onDidChangeActiveTextEditor: vi.fn(() => mockDisposable), + }, + Uri: { + file: vi.fn().mockReturnValue({ toString: () => "file://test" }), + }, + } +}) + +vi.mock("../../task/Task", () => ({ + Task: vi.fn().mockImplementation(function () { + return { + taskId: "mock-task-id", + instanceId: "mock-instance-id", + abortTask: vi.fn().mockResolvedValue(undefined), + emit: vi.fn(), + on: vi.fn(), + off: vi.fn(), + } + }), +})) +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", () => ({ + getWorkspacePath: vi.fn().mockReturnValue("/test/workspace"), +})) + +// Mock TelemetryService +vi.mock("@roo-code/telemetry", async (importOriginal) => { + const actual = await importOriginal() + return { + // Keep the real hashDistinctId: getStateToPostToWebview hashes the machine ID + // before posting it to the webview (issue #830). + ...actual, + TelemetryService: { + instance: { + setProvider: vi.fn(), + captureTaskCreated: vi.fn(), + }, + }, + } +}) + +// Mock CloudService +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: [], +})) + +vi.mock("../../../shared/modes", () => ({ + modes: [{ slug: "code", name: "Code Mode", roleDefinition: "You are a code assistant", groups: ["read", "edit"] }], + getModeBySlug: vi.fn().mockReturnValue({ + slug: "code", + name: "Code Mode", + roleDefinition: "You are a code assistant", + groups: ["read", "edit"], + }), + getGroupName: vi.fn().mockReturnValue("General Tools"), + defaultModeSlug: "code", +})) + +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), + } + }), +})) + +vi.mock("../../task-persistence", async (importOriginal) => { + const mod = await importOriginal() + return { + ...mod, + TaskHistoryStore: vi.fn().mockImplementation(function () { + return { + initialize: vi.fn().mockResolvedValue(undefined), + dispose: vi.fn(), + initialized: Promise.resolve(), + get: vi.fn().mockReturnValue(undefined), + getAll: vi.fn().mockReturnValue([]), + upsert: vi.fn().mockResolvedValue([]), + delete: vi.fn().mockResolvedValue(undefined), + deleteMany: vi.fn().mockResolvedValue(undefined), + migrateFromGlobalState: vi.fn().mockResolvedValue(undefined), + } + }), + readApiMessages: vi.fn().mockResolvedValue([]), + saveApiMessages: vi.fn().mockResolvedValue(undefined), + saveTaskMessages: vi.fn().mockResolvedValue(undefined), + } +}) + +function makeHistoryItem(id: string, overrides: Partial = {}): HistoryItem { + return { + id, + number: 1, + ts: 1, + task: id, + tokensIn: 0, + tokensOut: 0, + totalCost: 0, + status: "active", + ...overrides, + } +} + +type CapturedHandlers = Map unknown> + +function makeFakeTask(): { + task: { taskId: string; instanceId: string; on: ReturnType } + handlers: CapturedHandlers +} { + const handlers: CapturedHandlers = new Map() + const task = { + taskId: "child-1", + instanceId: "instance-1", + on: vi.fn((event: string, handler: (...args: unknown[]) => unknown) => { + handlers.set(event, handler) + }), + } + return { task, handlers } +} + +// Drive the constructor-installed taskCreationCallback so the real TaskCompleted +// listener under test gets registered against the fake task. +function captureTaskCompletedHandler( + provider: ClineProvider, + fakeTask: { taskId: string; on: ReturnType }, +) { + provider["taskCreationCallback"](fakeTask as unknown as Task) + const call = fakeTask.on.mock.calls.find(([event]) => event === RooCodeEventName.TaskCompleted) + if (!call) { + throw new Error("TaskCompleted listener was not registered") + } + return call[1] as (...args: unknown[]) => unknown +} + +describe("ClineProvider TaskCompleted status write", () => { + let provider: ClineProvider + let mockContext: vscode.ExtensionContext + let mockOutputChannel: vscode.OutputChannel + let updateTaskHistory: ReturnType + let historyGet: ReturnType + let consoleLogSpy: ReturnType + let consoleErrorSpy: ReturnType + + beforeAll(() => { + consoleLogSpy = vi.spyOn(console, "log").mockImplementation(() => {}) + consoleErrorSpy = vi.spyOn(console, "error").mockImplementation(() => {}) + }) + + afterAll(() => { + consoleLogSpy.mockRestore() + consoleErrorSpy.mockRestore() + }) + + beforeEach(() => { + vi.clearAllMocks() + + 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" }, + } 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), + getProviderSettings: vi + .fn() + .mockReturnValue({ apiProvider: providerIdentifiers.anthropic, apiKey: "test" } as ProviderSettings), + extensionUri: mockContext.extensionUri, + globalStorageUri: mockContext.globalStorageUri, + } + + provider = new ClineProvider( + mockContext, + mockOutputChannel, + "sidebar", + mockContextProxy as unknown as ContextProxy, + new WebviewFocusTracker(), + ) + + // The status write under test goes through this private method; swap it so the + // assertions observe the decision without touching the real store writer. + updateTaskHistory = vi.fn().mockResolvedValue([]) + provider["updateTaskHistory"] = updateTaskHistory as unknown as (typeof provider)["updateTaskHistory"] + + historyGet = vi.fn() + ;(provider["taskHistoryStore"] as unknown as { get: ReturnType }).get = historyGet + }) + + it("does not record a still-awaited child completed when its completion is accepted", async () => { + const child = makeHistoryItem("child-1", { parentTaskId: "parent-1" }) + const parent = makeHistoryItem("parent-1", { status: "delegated", awaitingChildId: "child-1" }) + historyGet.mockImplementation((id: string) => (id === "parent-1" ? parent : child)) + + const { task, handlers } = makeFakeTask() + const handler = captureTaskCompletedHandler(provider, task) + + await handler("child-1", {}, {}) + + // completeDelegatedChild is the only writer that may complete a still-awaited + // child, and it reopens the parent in the same step (issue #2677). + expect(updateTaskHistory).not.toHaveBeenCalled() + expect(handlers.get(RooCodeEventName.TaskCompleted)).toBeDefined() + }) + + it("still records a child completed once its parent no longer awaits it", async () => { + const child = makeHistoryItem("child-1", { parentTaskId: "parent-1" }) + const parent = makeHistoryItem("parent-1", { status: "active", awaitingChildId: undefined }) + historyGet.mockImplementation((id: string) => (id === "parent-1" ? parent : child)) + + const { task } = makeFakeTask() + const handler = captureTaskCompletedHandler(provider, task) + + await handler("child-1", {}, {}) + + expect(updateTaskHistory).toHaveBeenCalledTimes(1) + expect(updateTaskHistory.mock.calls[0][0]).toMatchObject({ id: "child-1", status: "completed" }) + }) + + it("still records a child completed when its parent record is gone", async () => { + const child = makeHistoryItem("child-1", { parentTaskId: "parent-1" }) + historyGet.mockImplementation((id: string) => (id === "child-1" ? child : undefined)) + + const { task } = makeFakeTask() + const handler = captureTaskCompletedHandler(provider, task) + + await handler("child-1", {}, {}) + + expect(updateTaskHistory).toHaveBeenCalledTimes(1) + }) + + it("still records a top-level task completed", async () => { + const taskItem = makeHistoryItem("task-1") + historyGet.mockImplementation((id: string) => (id === "task-1" ? taskItem : undefined)) + + const { task } = makeFakeTask() + const handler = captureTaskCompletedHandler(provider, task) + + await handler("task-1", {}, {}) + + expect(updateTaskHistory).toHaveBeenCalledTimes(1) + expect(updateTaskHistory.mock.calls[0][0]).toMatchObject({ id: "task-1", status: "completed" }) + }) +}) From 161ca35f96bef343c94cb459b69de6a7a678373d Mon Sep 17 00:00:00 2001 From: Phil Date: Sat, 5 Dec 2026 04:57:40 +0100 Subject: [PATCH 2/2] docs(tla): model the provider listener as a separate action (PR 2856 r1) CR round-1 findings on #2856 (issue 2677): - SubtaskReturn.tla: ListenerObserve models the provider onTaskCompleted listener as its own action (running/askUser phases); the guarded form defers a still-awaited child to completeDelegatedChild, an already-completed child is a no-op, and Init also admits the free-parent start so the guarded write branch is live. New sabotage SubtaskReturn.PoisonListener.cfg: accept keeps the fix, listener guard removed - TLC fails NoPoisonedCompletion at depth 1 through ListenerObserve alone. - ClineProvider.task-completed-status.spec.ts: async afterEach awaits provider.dispose() so the suite stops leaking instances into the static activeInstances set (sibling-spec pattern). TLC (tla2tools 1.7.4): SubtaskReturn.cfg pass (6 states), PoisonListener fail (5), Poison fail (5). afterEach sabotage-verified (store dispose throws -> 4/4 fail). Gates: test:core 5328, test:api 6417, tsc, eslint, prettier, scoped spec green (node 22.23.4). Review ratchet: 1 added, 1 gap (dispose finding is test hygiene). --- .../tla/SubtaskReturn.PoisonListener.cfg | 5 ++ docs/architecture/tla/SubtaskReturn.tla | 70 ++++++++++++++----- ...lineProvider.task-completed-status.spec.ts | 9 ++- 3 files changed, 64 insertions(+), 20 deletions(-) create mode 100644 docs/architecture/tla/SubtaskReturn.PoisonListener.cfg diff --git a/docs/architecture/tla/SubtaskReturn.PoisonListener.cfg b/docs/architecture/tla/SubtaskReturn.PoisonListener.cfg new file mode 100644 index 00000000000..1bb71bc5add --- /dev/null +++ b/docs/architecture/tla/SubtaskReturn.PoisonListener.cfg @@ -0,0 +1,5 @@ +SPECIFICATION Spec +CONSTANTS + Mode = "PoisonListener" +INVARIANTS TypeOK NoPoisonedCompletion +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/SubtaskReturn.tla b/docs/architecture/tla/SubtaskReturn.tla index 5ab06dbb19d..bdce67db217 100644 --- a/docs/architecture/tla/SubtaskReturn.tla +++ b/docs/architecture/tla/SubtaskReturn.tla @@ -2,21 +2,32 @@ \* Models the orchestrator subtask handoff: AttemptCompletionTool.execute with a \* set parentTaskId, reopenParentFromDelegation, and the provider onTaskCompleted \* listener (src/core/webview/ClineProvider.ts). -\* Source: the child records its final response and asks to return to the parent. +\* Source: the child records its final response and asks to return to the parent, +\* or the TaskCompleted event reaches the provider listener. \* Sink: the parent record leaves delegated/awaiting, or a "completed" write lands \* on a child its parent still awaits. -\* Failure: after one transient handoff skip, the user accepts the completion ask; -\* the listener records the child "completed" while the parent still awaits it, -\* and every later attempt_completion then reads "completed", stops as a stale -\* replay, and the result never reaches the orchestrator (issue 2677). +\* Failure: after one transient handoff skip, the user accepts the completion ask +\* or the listener fires; an unguarded writer records the child "completed" while +\* the parent still awaits it, and every later attempt_completion then reads +\* "completed", stops as a stale replay, and the result never reaches the +\* orchestrator (issue 2677). \* Invariant NoPoisonedCompletion: no reachable state records the child \* "completed" while the parent record still awaits that child. \* Modes: "Guarded" (fix - the accept re-runs the handoff while the parent -\* awaits, and the listener write defers to completeDelegatedChild) and -\* "Poison" (pre-fix - the accept writes "completed" in place). -\* Result: "Poison" fails NoPoisonedCompletion (reproduction). "Guarded" holds. -\* Model-checked 2026-12-05, tla2tools 1.7.4. -\* Review: 0 covered, 0 added, 0 gap (first version). +\* awaits, and the listener write defers to completeDelegatedChild), "Poison" +\* (pre-fix - accept and listener write "completed" in place), and +\* "PoisonListener" (only the listener guard removed; the accept keeps the fix). +\* Result: "Poison" fails NoPoisonedCompletion (reproduction). "PoisonListener" +\* fails it through ListenerObserve alone: its guarded accept cannot reach the +\* poisoned state. "Guarded" holds, and the listener can write there (free +\* parent) - the hold comes from the guard, not from a dead action. +\* Model-checked 2026-12-05, tla2tools 1.7.4: SubtaskReturn.cfg pass +\* (6 states), SubtaskReturn.PoisonListener.cfg fail (5 states), +\* SubtaskReturn.Poison.cfg fail (5 states). Counts vary run to run. +\* Review: 0 covered, 1 added (PR 2856 round 1, thread SubtaskReturn.tla:60 - +\* ListenerObserve action + PoisonListener sabotage), 1 gap (the +\* provider-dispose test-hygiene finding is not a modeled-system behavior; +\* fixed in the TS spec file). \* Not modeled: approval denial, persistence retries, cancellation, grandchild \* delegation, and the message content itself (oracle: taskLifecycle.ts). @@ -27,9 +38,15 @@ CONSTANTS Mode VARIABLES parentAwaiting, childStatus, phase vars == <> -Init == /\ parentAwaiting = "child" - /\ childStatus = "active" - /\ phase = "running" +\* Two starts a real system can be in when the child finishes: the parent +\* record still awaits this child, or the parent record is free (gone, or no +\* longer awaiting) while the child task is still active. +Init == \/ /\ parentAwaiting = "child" + /\ childStatus = "active" + /\ phase = "running" + \/ /\ parentAwaiting = "none" + /\ childStatus = "active" + /\ phase = "running" \* The child streams its final response. The handoff either completes (the \* reopen succeeds: the pair update frees the parent and completes the child) @@ -46,14 +63,29 @@ AttemptReturn == ELSE /\ phase' = "askUser" /\ UNCHANGED <> +\* The provider onTaskCompleted listener fires for the finished child. The +\* guarded form writes "completed" only when the parent record is free; a +\* still-awaited child defers the write to completeDelegatedChild. The +\* unguarded form (Poison, PoisonListener) writes "completed" regardless. +\* An already completed child makes the write a no-op. +ListenerObserve == + /\ phase \in {"running", "askUser"} + /\ IF childStatus = "completed" + THEN UNCHANGED vars + ELSE IF Mode = "Guarded" /\ parentAwaiting = "child" + THEN UNCHANGED vars + ELSE /\ childStatus' = "completed" + /\ phase' = "closed" + /\ UNCHANGED parentAwaiting + \* The user answers the completion ask. "Poison" records the child completed -\* in place; the parent record keeps awaiting. "Guarded" re-runs the handoff -\* while the parent still awaits this child; only a free child completes in -\* place. A poisoned child can never re-run the handoff: the stale-replay -\* gate reads "completed" and skips delegation forever. +\* in place; the parent record keeps awaiting. The other modes re-run the +\* handoff while the parent still awaits this child; only a free child +\* completes in place. A poisoned child can never re-run the handoff: the +\* stale-replay gate reads "completed" and skips delegation forever. AcceptCompletion == /\ phase = "askUser" - /\ IF Mode = "Guarded" + /\ IF Mode # "Poison" THEN IF parentAwaiting = "child" THEN /\ phase' = "handedOff" /\ parentAwaiting' = "none" @@ -74,7 +106,7 @@ PromptAgain == ELSE phase' = phase /\ UNCHANGED <> -Next == AttemptReturn \/ AcceptCompletion \/ PromptAgain +Next == AttemptReturn \/ AcceptCompletion \/ ListenerObserve \/ PromptAgain Spec == Init /\ [][Next]_vars diff --git a/src/core/webview/__tests__/ClineProvider.task-completed-status.spec.ts b/src/core/webview/__tests__/ClineProvider.task-completed-status.spec.ts index a01cf45b3ba..ba605334d6b 100644 --- a/src/core/webview/__tests__/ClineProvider.task-completed-status.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.task-completed-status.spec.ts @@ -1,6 +1,6 @@ import { RooCodeEventName } from "@roo-code/types" import { WebviewFocusTracker } from "../WebviewFocusTracker" -import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest" +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest" import * as vscode from "vscode" import { ClineProvider } from "../ClineProvider" @@ -384,6 +384,13 @@ describe("ClineProvider TaskCompleted status write", () => { ;(provider["taskHistoryStore"] as unknown as { get: ReturnType }).get = historyGet }) + // The constructor registers the instance in ClineProvider.activeInstances and + // only dispose() removes it; leaking it would hand a stale provider to a later + // test via getVisibleInstance(). + afterEach(async () => { + await provider.dispose() + }) + it("does not record a still-awaited child completed when its completion is accepted", async () => { const child = makeHistoryItem("child-1", { parentTaskId: "parent-1" }) const parent = makeHistoryItem("parent-1", { status: "delegated", awaitingChildId: "child-1" })