Skip to content

Commit 7f07a1d

Browse files
fix(task): skip saveClineMessages when history task aborts before messages load (#1181)
* fix(task): skip saveClineMessages when history task aborts before messages load * test: strengthen resume-eviction-race assertions and type mock provider * test: add fallback mock for second getSavedClineMessages read in resume-eviction spec * fix(task): prevent saving unhydrated history messages during abort --------- Co-authored-by: Naved Merchant <naved.merchant@gmail.com>
1 parent 84e54cf commit 7f07a1d

5 files changed

Lines changed: 462 additions & 3 deletions

File tree

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
{
2+
"fixtures": [
3+
{
4+
"match": {
5+
"userMessage": "RESUME_EVICTION_RACE_SMOKE"
6+
},
7+
"response": {
8+
"toolCalls": [
9+
{
10+
"name": "attempt_completion",
11+
"arguments": "{\"result\":\"Resume eviction smoke completed.\"}",
12+
"id": "call_resume_eviction_001"
13+
}
14+
]
15+
}
16+
}
17+
]
18+
}
Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
import * as assert from "assert"
2+
3+
import { setDefaultSuiteTimeout } from "./test-utils"
4+
import { waitUntilCompleted, waitFor } from "./utils"
5+
6+
// Regression test for the "Work #1 (no message)" title-clobber bug reported
7+
// against Zoo Code v3.76.0 (Discord, 2026-08-06).
8+
//
9+
// Root cause: Task#resumeTaskFromHistory() is started fire-and-forget by
10+
// scheduleTask() after createTaskWithHistoryItem() adds the task to the
11+
// registry, so `clineMessages` is [] until the first disk read resolves.
12+
// ClineProvider#evictCurrentTask() (called by clearCurrentTask / the
13+
// Back-to-parent / Go-to-subtask buttons) calls abortTask(), which calls
14+
// saveClineMessages() → taskMetadata() while the array is still empty.
15+
// taskMetadata() then persists the "no_messages" placeholder title,
16+
// permanently clobbering the real title in the history store.
17+
//
18+
// The test exercises the race by:
19+
// 1. Running a task to completion so a real title is persisted.
20+
// 2. Starting resumeTask() (same path as showTaskWithId) without awaiting it.
21+
// 3. Polling until the task appears on the stack, then immediately evicting —
22+
// the task is on the stack but its message load is still in flight.
23+
// 4. Asserting the stored title still matches the original.
24+
//
25+
// NOTE: Because the extension host reads task messages from disk in the same
26+
// process as this test, the I/O window is very tight (< 1ms on local disk).
27+
// The race is not reliably triggerable from the e2e layer; the canonical
28+
// regression anchor is the unit test in
29+
// src/core/task/__tests__/Task.resume-eviction-race.spec.ts, which controls
30+
// the timing via a deferred promise. This e2e test serves as a smoke test that
31+
// the resume-then-evict flow does not blow up and that the stored title is
32+
// correct after a round-trip.
33+
suite("Resume eviction race (title clobber regression)", function () {
34+
setDefaultSuiteTimeout(this)
35+
36+
test("evicting a mid-resume task does not overwrite its stored title", async () => {
37+
const api = globalThis.api
38+
39+
const ORIGINAL_TITLE =
40+
"RESUME_EVICTION_RACE_SMOKE: complete immediately with 'Resume eviction smoke completed.'"
41+
42+
// Step 1 — run a task to completion so a real title is persisted.
43+
const taskId = await waitUntilCompleted({
44+
api,
45+
start: () =>
46+
api.startNewTask({
47+
configuration: {
48+
mode: "ask",
49+
autoApprovalEnabled: true,
50+
enableCheckpoints: false,
51+
},
52+
text: ORIGINAL_TITLE,
53+
}),
54+
})
55+
56+
const beforeResume = await api.getTaskHistoryItem(taskId)
57+
assert.ok(beforeResume, "Task should be in history after completion")
58+
assert.ok(
59+
beforeResume.task?.includes("RESUME_EVICTION_RACE_SMOKE"),
60+
`Persisted title before resume should contain the prompt marker (got "${beforeResume.task}")`,
61+
)
62+
63+
// Drain the stack so we start clean.
64+
while (api.getCurrentTaskStack().length > 0) {
65+
await api.clearCurrentTask()
66+
}
67+
68+
// Step 2 — fire resumeTask() without awaiting it. resumeTask() calls
69+
// createTaskWithHistoryItem() which adds the task to the registry and
70+
// calls scheduleTask() (fire-and-forget). The task's run() and
71+
// resumeTaskFromHistory() start in the background.
72+
const resumePromise = api.resumeTask(taskId)
73+
74+
// Step 3 — wait only until the task appears on the stack (i.e.
75+
// createTaskWithHistoryItem has returned and addClineToStack has run),
76+
// then immediately evict. This minimises the gap between the eviction
77+
// and the in-flight message load, giving the best chance of hitting the
78+
// race window before readTaskMessages() resolves.
79+
await waitFor(() => api.getCurrentTaskStack().includes(taskId))
80+
await api.clearCurrentTask()
81+
82+
// Let the resume settle.
83+
await resumePromise.catch(() => {})
84+
85+
// Step 4 — the stored title must still be the real one.
86+
const afterEviction = await api.getTaskHistoryItem(taskId)
87+
assert.ok(afterEviction, "Task should still be in history after eviction")
88+
89+
// Before the fix this would be "Task #N (No messages)" / "工作 #N (無訊息)".
90+
assert.strictEqual(
91+
afterEviction.task,
92+
beforeResume.task,
93+
`Title must not change during resume eviction. Got: "${afterEviction.task}"`,
94+
)
95+
})
96+
})

‎src/core/task/Task.ts‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2258,9 +2258,16 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
22582258
console.error(`Error during task ${this.taskId}.${this.instanceId} disposal:`, error)
22592259
// Don't rethrow - we want abort to always succeed
22602260
}
2261-
// Save the countdown message in the automatic retry or other content.
2261+
// Guard: a history task whose message load has not finished yet has
2262+
// clineMessages = []. Saving now would call taskMetadata() with an
2263+
// empty array, which writes the "no messages" placeholder as the
2264+
// title and permanently clobbers the real title in the history store
2265+
// (the "Work #1 (no message)" / "工作 #1 (無訊息)" bug, v3.76.0).
2266+
// The on-disk data is still correct at this point, so skip the save.
2267+
if (this._isHistoryTask && this.clineMessages.length === 0) {
2268+
return
2269+
}
22622270
try {
2263-
// Save the countdown message in the automatic retry or other content.
22642271
await this.saveClineMessages()
22652272
} catch (error) {
22662273
console.error(`Error saving messages during abort for task ${this.taskId}.${this.instanceId}:`, error)

‎src/core/task/__tests__/Task.persistence.spec.ts‎

Lines changed: 114 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,30 @@ import * as os from "os"
44
import * as path from "path"
55
import * as vscode from "vscode"
66

7-
import type { GlobalState, ProviderSettings } from "@roo-code/types"
7+
import type { ClineMessage, GlobalState, ProviderSettings } from "@roo-code/types"
88
import { TelemetryService } from "@roo-code/telemetry"
99

1010
import { Task } from "../Task"
1111
import { ClineProvider } from "../../webview/ClineProvider"
1212
import { ContextProxy } from "../../config/ContextProxy"
1313

14+
type TaskPersistenceAccess = {
15+
resumeTaskFromHistory: () => Promise<void>
16+
saveClineMessages: () => Promise<boolean>
17+
}
18+
19+
function getTaskPersistenceAccess(task: Task): TaskPersistenceAccess {
20+
return task as unknown as TaskPersistenceAccess
21+
}
22+
23+
function createDeferred<T>() {
24+
let resolve!: (value: T) => void
25+
const promise = new Promise<T>((resolvePromise) => {
26+
resolve = resolvePromise
27+
})
28+
return { promise, resolve }
29+
}
30+
1431
// ─── Hoisted mocks ───────────────────────────────────────────────────────────
1532

1633
const {
@@ -470,6 +487,102 @@ describe("Task persistence", () => {
470487
})
471488
})
472489

490+
// ── abortTask history hydration guard ─────────────────────────────────
491+
492+
describe("abortTask", () => {
493+
it("skips persistence when a history task aborts before messages load", async () => {
494+
const messagesDeferred = createDeferred<ClineMessage[]>()
495+
mockReadTaskMessages.mockReturnValueOnce(messagesDeferred.promise)
496+
497+
const task = new Task({
498+
provider: mockProvider,
499+
apiConfiguration: mockApiConfig,
500+
historyItem: {
501+
id: "history-task",
502+
number: 1,
503+
ts: Date.now(),
504+
task: "Original task title",
505+
tokensIn: 10,
506+
tokensOut: 5,
507+
totalCost: 0.001,
508+
},
509+
startTask: false,
510+
})
511+
512+
const resumePromise = task.run().catch(() => {})
513+
514+
await task.abortTask()
515+
516+
expect(mockSaveTaskMessages).not.toHaveBeenCalled()
517+
expect(mockProvider.updateTaskHistory).not.toHaveBeenCalled()
518+
519+
messagesDeferred.resolve([])
520+
await resumePromise
521+
})
522+
523+
it("persists a history task when messages load before abort", async () => {
524+
const messages = [
525+
{
526+
ts: Date.now(),
527+
type: "say" as const,
528+
say: "text" as const,
529+
text: "Loaded task message",
530+
},
531+
] satisfies ClineMessage[]
532+
const messagesDeferred = createDeferred<typeof messages>()
533+
mockReadTaskMessages.mockReturnValueOnce(messagesDeferred.promise).mockResolvedValue(messages)
534+
535+
const task = new Task({
536+
provider: mockProvider,
537+
apiConfiguration: mockApiConfig,
538+
historyItem: {
539+
id: "history-task",
540+
number: 1,
541+
ts: Date.now(),
542+
task: "Original task title",
543+
tokensIn: 10,
544+
tokensOut: 5,
545+
totalCost: 0.001,
546+
},
547+
startTask: false,
548+
})
549+
vi.spyOn(task, "ask").mockResolvedValue({ response: "noButtonClicked" })
550+
551+
mockReadApiMessages.mockResolvedValue([
552+
{
553+
role: "user",
554+
content: [{ type: "text", text: "Original task" }],
555+
},
556+
])
557+
558+
const resumePromise = getTaskPersistenceAccess(task).resumeTaskFromHistory()
559+
messagesDeferred.resolve(messages)
560+
await resumePromise
561+
562+
const saveCallsBeforeAbort = mockSaveTaskMessages.mock.calls.length
563+
expect(saveCallsBeforeAbort).toBeGreaterThan(0)
564+
expect(mockProvider.updateTaskHistory).toHaveBeenCalled()
565+
566+
await task.abortTask()
567+
expect(mockSaveTaskMessages.mock.calls.length).toBeGreaterThan(saveCallsBeforeAbort)
568+
})
569+
570+
it("persists an empty non-history task when aborted", async () => {
571+
const task = new Task({
572+
provider: mockProvider,
573+
apiConfiguration: mockApiConfig,
574+
task: "New task",
575+
startTask: false,
576+
})
577+
const saveClineMessagesSpy = vi.spyOn(getTaskPersistenceAccess(task), "saveClineMessages")
578+
579+
await task.abortTask()
580+
581+
expect(saveClineMessagesSpy).toHaveBeenCalledTimes(1)
582+
expect(mockSaveTaskMessages).toHaveBeenCalledTimes(1)
583+
})
584+
})
585+
473586
// ── flushPendingToolResultsToHistory — save failure/success ───────────
474587

475588
describe("flushPendingToolResultsToHistory persistence", () => {

0 commit comments

Comments
 (0)