Skip to content

Commit df5f562

Browse files
committed
fix(task): keep the first abort reason
1 parent eb83244 commit df5f562

4 files changed

Lines changed: 246 additions & 31 deletions

File tree

‎src/core/task/Task.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3715,8 +3715,9 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
37153715
await abortStream(cancelReason, streamingFailedMessage)
37163716

37173717
if (this.abort) {
3718-
// User cancelled - abort the entire task
3719-
this.abortReason = cancelReason
3718+
// User cancelled - abort the entire task.
3719+
// ??= keeps the first reason (R-4: cancel can land after cancelReason was computed as "streaming_failed").
3720+
this.abortReason ??= "user_cancelled"
37203721
await this.abortTask()
37213722
} else if (error instanceof OutputTokenLimitError) {
37223723
// Truncation repeats on an identical request, so never auto-retry it
Lines changed: 223 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,223 @@
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+
})

‎src/core/webview/ClineProvider.ts‎

Lines changed: 1 addition & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -406,35 +406,7 @@ export class ClineProvider
406406
}
407407
this.emit(RooCodeEventName.TaskCompleted, taskId, tokenUsage, toolUsage)
408408
}
409-
const onTaskAborted = async () => {
410-
this.emit(RooCodeEventName.TaskAborted, instance.taskId)
411-
412-
try {
413-
// Only rehydrate on genuine streaming failures.
414-
// User-initiated cancels are handled by cancelTask().
415-
if (instance.abortReason === "streaming_failed") {
416-
// Defensive safeguard: if another path already replaced this instance, skip
417-
const current = this.getCurrentTask()
418-
if (current && current.instanceId !== instance.instanceId) {
419-
this.log(
420-
`[onTaskAborted] Skipping rehydrate: current instance ${current.instanceId} != aborted ${instance.instanceId}`,
421-
)
422-
return
423-
}
424-
425-
const { historyItem } = await this.getTaskWithId(instance.taskId)
426-
const rootTask = instance.rootTask
427-
const parentTask = instance.parentTask
428-
await this.createTaskWithHistoryItem({ ...historyItem, rootTask, parentTask })
429-
}
430-
} catch (error) {
431-
this.log(
432-
`[onTaskAborted] Failed to rehydrate after streaming failure: ${
433-
error instanceof Error ? error.message : String(error)
434-
}`,
435-
)
436-
}
437-
}
409+
const onTaskAborted = () => this.emit(RooCodeEventName.TaskAborted, instance.taskId)
438410
const onTaskFocused = () => this.emit(RooCodeEventName.TaskFocused, instance.taskId)
439411
const onTaskUnfocused = () => this.emit(RooCodeEventName.TaskUnfocused, instance.taskId)
440412
const onTaskActive = (taskId: string) => this.emit(RooCodeEventName.TaskActive, taskId)

‎src/core/webview/__tests__/ClineProvider.taskHistory.spec.ts‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -961,6 +961,25 @@ describe("ClineProvider Task History Synchronization", () => {
961961
expect(logSpy).toHaveBeenCalledWith(expect.stringContaining("[onTaskCompleted] Failed to write"))
962962
})
963963

964+
it("onTaskAborted does not call createTaskWithHistoryItem (RSK-19 guard)", async () => {
965+
// The deleted rehydrate branch fired createTaskWithHistoryItem when
966+
// abortReason === "streaming_failed". Without a stored history item, getTaskWithId
967+
// throws and the old catch block silently swallows it, making the test pass even
968+
// with the buggy branch present. Store the item so that path would succeed.
969+
const existing = createHistoryItem({ id: "task-abort-1", task: "T" })
970+
await provider.updateTaskHistory(existing, { broadcast: false })
971+
972+
const createSpy = vi.spyOn(provider, "createTaskWithHistoryItem")
973+
974+
// Inject the value the race previously wrote (Task.ts ??= fix prevents this now).
975+
const fakeTask = { ...makeFakeTask("task-abort-1"), abortReason: "streaming_failed" }
976+
// Double cast: taskCreationCallback reads only on/taskId/abortReason from the fake.
977+
provider["taskCreationCallback"](fakeTask as unknown as Task)
978+
await fakeTask.emit(RooCodeEventName.TaskAborted)
979+
980+
expect(createSpy).not.toHaveBeenCalled()
981+
})
982+
964983
it("emits delegated completion through the provider after the child is disposed", () => {
965984
const listener = vi.fn()
966985
provider.on(RooCodeEventName.TaskCompleted, listener)

0 commit comments

Comments
 (0)