|
| 1 | +// npx vitest run core/task/__tests__/Task.abort-reason-race.spec.ts |
| 2 | +// |
| 3 | +// Regression anchor for RSK-19 (GitHub #1802). |
| 4 | +// |
| 5 | +// Race R-4: the chunk-loop catch computes cancelReason as "streaming_failed" |
| 6 | +// while this.abort is false, then awaits abortStream cleanup. A cancel can |
| 7 | +// land during that await (cancelTask sets abortReason="user_cancelled" and |
| 8 | +// then abort=true). After the await, the if(this.abort) branch ran |
| 9 | +// |
| 10 | +// this.abortReason = cancelReason ← BUG: overwrites "user_cancelled" |
| 11 | +// |
| 12 | +// with the stale "streaming_failed". This caused onTaskAborted to see |
| 13 | +// abortReason==="streaming_failed" and rehydrate, while cancelTask also |
| 14 | +// rehydrated — double rehydration. |
| 15 | +// |
| 16 | +// Fix: Task.ts uses ??= so the first-set reason wins. The onTaskAborted |
| 17 | +// streaming_failed rehydrate branch (now dead) is removed. |
| 18 | + |
| 19 | +import * as os from "os" |
| 20 | +import * as path from "path" |
| 21 | + |
| 22 | +import type { GlobalState, ProviderSettings } from "@roo-code/types" |
| 23 | +import { providerIdentifiers } from "@roo-code/types/provider-identifiers" |
| 24 | +import { findLast } from "../../../shared/array" |
| 25 | +import { TelemetryService } from "@roo-code/telemetry" |
| 26 | + |
| 27 | +import { Task } from "../Task" |
| 28 | +import { ClineProvider } from "../../webview/ClineProvider" |
| 29 | + |
| 30 | +// ─── Hoisted mocks ─────────────────────────────────────────────────────────── |
| 31 | + |
| 32 | +const { mockSaveTaskMessages, mockSaveApiMessages } = vi.hoisted(() => ({ |
| 33 | + mockSaveTaskMessages: vi.fn().mockResolvedValue(undefined), |
| 34 | + mockSaveApiMessages: vi.fn().mockResolvedValue(undefined), |
| 35 | +})) |
| 36 | + |
| 37 | +// ─── Module mocks ──────────────────────────────────────────────────────────── |
| 38 | +// vscode is globally aliased to __mocks__/vscode.js by vitest.config.ts. |
| 39 | + |
| 40 | +vi.mock("delay", () => ({ __esModule: true, default: vi.fn().mockResolvedValue(undefined) })) |
| 41 | +vi.mock("execa", () => ({ execa: vi.fn() })) |
| 42 | +vi.mock("p-wait-for", () => ({ default: vi.fn().mockResolvedValue(undefined) })) |
| 43 | + |
| 44 | +vi.mock("../../task-persistence", async (importOriginal) => { |
| 45 | + const mod = await importOriginal<typeof import("../../task-persistence")>() |
| 46 | + return { |
| 47 | + ...mod, |
| 48 | + saveApiMessages: mockSaveApiMessages, |
| 49 | + saveTaskMessages: mockSaveTaskMessages, |
| 50 | + TaskHistoryStore: vi.fn().mockImplementation(function () { |
| 51 | + return { |
| 52 | + initialize: vi.fn().mockResolvedValue(undefined), |
| 53 | + dispose: vi.fn(), |
| 54 | + get: vi.fn(), |
| 55 | + getAll: vi.fn().mockReturnValue([]), |
| 56 | + upsert: vi.fn().mockResolvedValue([]), |
| 57 | + delete: vi.fn().mockResolvedValue(undefined), |
| 58 | + deleteMany: vi.fn().mockResolvedValue(undefined), |
| 59 | + reconcile: vi.fn().mockResolvedValue(undefined), |
| 60 | + initialized: Promise.resolve(), |
| 61 | + } |
| 62 | + }), |
| 63 | + } |
| 64 | +}) |
| 65 | + |
| 66 | +vi.mock("../../mentions", () => ({ |
| 67 | + parseMentions: vi |
| 68 | + .fn() |
| 69 | + .mockImplementation((text) => |
| 70 | + Promise.resolve({ text: `processed: ${text}`, mode: undefined, contentBlocks: [] }), |
| 71 | + ), |
| 72 | + openMention: vi.fn(), |
| 73 | + getLatestTerminalOutput: vi.fn(), |
| 74 | +})) |
| 75 | + |
| 76 | +vi.mock("../../mentions/processUserContentMentions", () => ({ |
| 77 | + processUserContentMentions: vi |
| 78 | + .fn() |
| 79 | + .mockImplementation(async ({ userContent }: { userContent: unknown[] }) => ({ |
| 80 | + content: userContent, |
| 81 | + mode: undefined, |
| 82 | + })), |
| 83 | +})) |
| 84 | + |
| 85 | +vi.mock("../../../integrations/misc/extract-text", () => ({ |
| 86 | + extractTextFromFile: vi.fn().mockResolvedValue(""), |
| 87 | +})) |
| 88 | + |
| 89 | +vi.mock("../../environment/getEnvironmentDetails", () => ({ |
| 90 | + getEnvironmentDetails: vi.fn().mockResolvedValue(""), |
| 91 | +})) |
| 92 | + |
| 93 | +vi.mock("../../ignore/RooIgnoreController") |
| 94 | + |
| 95 | +vi.mock("../../../utils/storage", () => ({ |
| 96 | + getTaskDirectoryPath: vi |
| 97 | + .fn() |
| 98 | + .mockImplementation((base: string, id: string) => Promise.resolve(`${base}/tasks/${id}`)), |
| 99 | + getSettingsDirectoryPath: vi |
| 100 | + .fn() |
| 101 | + .mockImplementation((base: string) => Promise.resolve(`${base}/settings`)), |
| 102 | +})) |
| 103 | + |
| 104 | +vi.mock("../../../utils/fs", () => ({ |
| 105 | + fileExistsAtPath: vi.fn().mockReturnValue(false), |
| 106 | +})) |
| 107 | + |
| 108 | +vi.mock("../../../i18n", () => ({ |
| 109 | + t: (key: string) => key, |
| 110 | +})) |
| 111 | + |
| 112 | +// ─── Helpers ───────────────────────────────────────────────────────────────── |
| 113 | + |
| 114 | +/** |
| 115 | + * Minimal provider object that satisfies what Task reads during construction |
| 116 | + * and what recursivelyMakeClineRequests calls on the provider. |
| 117 | + */ |
| 118 | +function makeMockProvider() { |
| 119 | + return { |
| 120 | + log: vi.fn(), |
| 121 | + taskHistoryStore: { get: () => undefined }, |
| 122 | + updateTaskHistory: vi.fn().mockResolvedValue([]), |
| 123 | + // Called directly (not via optional chain) inside recursivelyMakeClineRequests. |
| 124 | + getState: vi.fn().mockResolvedValue({}), |
| 125 | + getSkillsManager: vi.fn().mockReturnValue(undefined), |
| 126 | + // Called via optional chain. |
| 127 | + postStateToWebviewWithoutTaskHistory: vi.fn().mockResolvedValue(undefined), |
| 128 | + flushPostStateToWebviewThrottled: vi.fn().mockResolvedValue(undefined), |
| 129 | + postMessageToWebview: vi.fn().mockResolvedValue(undefined), |
| 130 | + postStateToWebview: vi.fn().mockResolvedValue(undefined), |
| 131 | + postStateToWebviewThrottled: vi.fn().mockResolvedValue(undefined), |
| 132 | + context: { |
| 133 | + globalStorageUri: { fsPath: path.join(os.tmpdir(), "test-storage-abort-race") }, |
| 134 | + globalState: { |
| 135 | + get: vi.fn().mockImplementation((_key: keyof GlobalState) => undefined), |
| 136 | + update: vi.fn().mockResolvedValue(undefined), |
| 137 | + keys: vi.fn().mockReturnValue([]), |
| 138 | + }, |
| 139 | + workspaceState: { |
| 140 | + get: vi.fn().mockImplementation(() => undefined), |
| 141 | + update: vi.fn().mockResolvedValue(undefined), |
| 142 | + keys: vi.fn().mockReturnValue([]), |
| 143 | + }, |
| 144 | + secrets: { |
| 145 | + get: vi.fn().mockResolvedValue(undefined), |
| 146 | + store: vi.fn().mockResolvedValue(undefined), |
| 147 | + delete: vi.fn().mockResolvedValue(undefined), |
| 148 | + }, |
| 149 | + extensionUri: { fsPath: "/mock/extension" }, |
| 150 | + extension: { packageJSON: { version: "1.0.0" } }, |
| 151 | + }, |
| 152 | + } |
| 153 | +} |
| 154 | + |
| 155 | +// ─── Tests ─────────────────────────────────────────────────────────────────── |
| 156 | + |
| 157 | +describe("Task abort-reason race (RSK-19 regression)", () => { |
| 158 | + let mockApiConfig: ProviderSettings |
| 159 | + |
| 160 | + beforeEach(() => { |
| 161 | + vi.clearAllMocks() |
| 162 | + mockSaveTaskMessages.mockResolvedValue(undefined) |
| 163 | + |
| 164 | + if (!TelemetryService.hasInstance()) { |
| 165 | + TelemetryService.createInstance([]) |
| 166 | + } |
| 167 | + |
| 168 | + mockApiConfig = { |
| 169 | + apiProvider: providerIdentifiers.anthropic, |
| 170 | + apiModelId: "claude-3-5-sonnet-20241022", |
| 171 | + apiKey: "test-api-key", |
| 172 | + } |
| 173 | + }) |
| 174 | + |
| 175 | + it("keeps user_cancelled when a cancel lands during abortStream cleanup", async () => { |
| 176 | + const mockProvider = makeMockProvider() |
| 177 | + |
| 178 | + // Double cast required: the test uses a plain object that satisfies only the |
| 179 | + // subset of ClineProvider methods called by this code path, not the full class. |
| 180 | + const task = new Task({ |
| 181 | + provider: mockProvider as unknown as ClineProvider, |
| 182 | + apiConfiguration: mockApiConfig, |
| 183 | + task: "test task", |
| 184 | + startTask: false, |
| 185 | + }) |
| 186 | + |
| 187 | + vi.spyOn(task.diffViewProvider, "reset").mockResolvedValue(undefined) |
| 188 | + vi.spyOn(task, "dispose").mockResolvedValue(undefined) |
| 189 | + |
| 190 | + // Return a stream that throws, simulating a mid-stream API failure while |
| 191 | + // this.abort is still false (no cancel yet). |
| 192 | + // eslint-disable-next-line require-yield -- intentional error-only async source |
| 193 | + task["attemptApiRequest"] = async function* () { |
| 194 | + throw new Error("mid-stream API failure") |
| 195 | + } |
| 196 | + |
| 197 | + // Inject the cancel at the abortStream cleanup save. abortStream calls |
| 198 | + // updateApiReqMsg("streaming_failed") synchronously first, then saves. |
| 199 | + // So when saveTaskMessages is called and the api_req_started row already |
| 200 | + // shows cancelReason="streaming_failed", we are inside abortStream. |
| 201 | + mockSaveTaskMessages.mockImplementation(async () => { |
| 202 | + const apiReqMsg = findLast(task.clineMessages, (m) => m.say === "api_req_started") |
| 203 | + const parsed = apiReqMsg?.text ? (JSON.parse(apiReqMsg.text) as { cancelReason?: string }) : {} |
| 204 | + const inAbortStreamSave = parsed.cancelReason === "streaming_failed" && !task.didFinishAbortingStream |
| 205 | + if (inAbortStreamSave) { |
| 206 | + // Simulate cancelTask landing during the abortStream await. |
| 207 | + // cancelTask sets abortReason first, THEN sets abort=true. |
| 208 | + task["abortReason"] = "user_cancelled" |
| 209 | + task["abort"] = true |
| 210 | + } |
| 211 | + }) |
| 212 | + |
| 213 | + // recursivelyMakeClineRequests returns true — the outer catch swallows the |
| 214 | + // abort-path throw and returns true so the parent loop can end the task. |
| 215 | + const result = await task.recursivelyMakeClineRequests([{ type: "text", text: "help me" }]) |
| 216 | + expect(result).toBe(true) |
| 217 | + |
| 218 | + // The first abort reason must win. "user_cancelled" (set by cancelTask during |
| 219 | + // abortStream) must not be overwritten by the stale "streaming_failed" |
| 220 | + // (computed before the cancel landed). |
| 221 | + expect(task.abortReason).toBe("user_cancelled") |
| 222 | + }) |
| 223 | +}) |
0 commit comments