From e6df2109cb311cbfc7991bacaff0b6c7f4600b8c Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Tue, 10 Nov 2026 04:16:44 +0800 Subject: [PATCH 1/3] fix(task): guard saveClineMessages against abandoned tasks (fixes #1021) Squashed application of PR 1496's 13 own-content commits onto main as the measured two-file net content (11,935 B, 2 paths, 0 conflict markers under git apply --3way). Dropped from the original branch lineage: 7 merge commits whose second parents are already ancestors of the old base 05d01f33d03a, the empty re-trigger commit b67e573125ec, and the fork-side .coderabbit.yaml housekeeping that contributes nothing to the net diff. Squashed-from: 352df167431c ce34d4804c00 b67e573125ec 8cce67aea9c9 ea654697e0d1 a3db831f70cb a1c71012b1e8 10300ce76740 4671c9ac976e d5e5a54e003b 34dce6e8b76d 737fdd21c57c 757015b646ab Co-authored-by: edelauna Signed-off-by: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> --- src/core/task/Task.ts | 26 ++++ src/core/task/__tests__/Task.spec.ts | 221 +++++++++++++++++++++++++++ 2 files changed, 247 insertions(+) diff --git a/src/core/task/Task.ts b/src/core/task/Task.ts index e2e25ef93d..0cd855e204 100644 --- a/src/core/task/Task.ts +++ b/src/core/task/Task.ts @@ -1889,6 +1889,32 @@ export class Task extends EventEmitter implements TaskLike { this.debouncedEmitTokenUsage(tokenUsage, this.toolUsage) const provider = this.providerRef.deref() + + // Fire-and-forget saveClineMessages() calls can reach this point after + // abandonSubtask's atomicUpdatePair() cleared parentTaskId/rootTaskId. Writing + // this live Task's stale link values would silently reattach the severed + // parent-child link. Keep the upsert (so a plain cancel still records its + // metadata) but omit the link keys when the store already has this task's row: + // upsertCore merges over the existing record, so omitted keys keep the + // severed/null values while tokens, cost, ts and title are refreshed. + if (this.abandoned) { + const existing = provider?.taskHistoryStore.get(this.taskId) + if (!existing) { + // The message write succeeded, and the boolean reflects the message write + // only (see method docs): returning false here would make callers retry an + // already-persisted save (persistQueuedFeedbackAndAcknowledge) or skip a + // durable-state-gated update whose on-disk record is in fact current + // (finalizePartialToolAsk). No stored row means there is no link to + // reattach, and creating one here would write a task the store never had. + return true + } + const { parentTaskId: _parentTaskId, rootTaskId: _rootTaskId, ...detachedHistoryItem } = historyItem + await provider?.updateTaskHistory( + existing.status ? { ...detachedHistoryItem, status: existing.status } : detachedHistoryItem, + ) + return true + } + const existingStatus = provider?.taskHistoryStore.get(this.taskId)?.status await provider?.updateTaskHistory(existingStatus ? { ...historyItem, status: existingStatus } : historyItem) } catch (error) { diff --git a/src/core/task/__tests__/Task.spec.ts b/src/core/task/__tests__/Task.spec.ts index 5438453c2c..fcc0a503b2 100644 --- a/src/core/task/__tests__/Task.spec.ts +++ b/src/core/task/__tests__/Task.spec.ts @@ -10123,3 +10123,224 @@ describe("pushToolResultToUserContent", () => { expect(task.userMessageContent).toEqual([toolResult1, toolResult2, image, text1, text2]) }) }) + +describe("saveClineMessages abandoned guard (#1021)", () => { + beforeEach(() => { + if (!TelemetryService.hasInstance()) { + TelemetryService.createInstance([]) + } + }) + + // The history item carries the stale link: a fire-and-forget save that + // reaches updateTaskHistory() after abandonSubtask's atomicUpdatePair() + // cleared parentTaskId/rootTaskId would silently reattach the severed + // parent-child link. + const staleHistoryItem: HistoryItem = { + id: "orphan-subtask", + number: 7, + ts: Date.now(), + task: "orphan subtask", + tokensIn: 0, + tokensOut: 0, + totalCost: 0, + rootTaskId: "stale-root", + parentTaskId: "stale-parent", + } + + // Task receives a full ClineProvider at runtime; these focused unit tests only + // exercise these methods, so the partial double is cast. taskHistoryStore must + // be stubbed: without it provider?.taskHistoryStore.get() throws before the + // guard is evaluated and the catch would mask whether execution reached + // updateTaskHistory(). + // + // The double does not structurally overlap MockedClineProvider, so a direct + // literal `as` fails (TS2352). Object.assign over an empty-object single cast + // keeps one assertion: the target carries the declared type and the source's + // property types stay inferred. + function makeMockProvider() { + const mockProvider = Object.assign({} as MockedClineProvider, { + context: { + globalStorageUri: { fsPath: "/test/storage" }, + globalState: { + get: vi.fn().mockImplementation(() => undefined), + update: vi.fn().mockResolvedValue(undefined), + keys: vi.fn().mockReturnValue([]), + }, + }, + getState: vi.fn().mockResolvedValue({ + apiConfiguration: { apiProvider: providerIdentifiers.anthropic, apiKey: "test-key" }, + mcpEnabled: false, + }), + getMcpHub: vi.fn().mockReturnValue(undefined), + postMessageToWebview: vi.fn().mockResolvedValue(undefined), + updateTaskHistory: vi.fn().mockResolvedValue(undefined), + taskHistoryStore: { get: vi.fn(() => undefined) }, + }) + return mockProvider + } + + function createTask(provider: MockedClineProvider) { + return new Task({ + provider, + apiConfiguration: { apiProvider: providerIdentifiers.anthropic, apiKey: "test-key" }, + task: "orphan subtask", + startTask: false, + }) + } + + it("persists messages but does not update task history when the task was abandoned", async () => { + const saveSpy = vi.spyOn(taskMessagesModule, "saveTaskMessages").mockResolvedValue([]) + const metaSpy = vi + .spyOn(taskMetadataModule, "taskMetadata") + .mockResolvedValue({ historyItem: staleHistoryItem, tokenUsage: getApiMetrics([]) }) + + try { + const mockProvider = makeMockProvider() + const task = createTask(mockProvider) + + // Seed a message so the payload assertion is meaningful: clineMessages + // starts empty, and an empty-payload save would pass a call-count-only + // assertion even if the save dropped the messages field. + task.clineMessages = [{ ts: 1, type: "say", say: "text", text: "seeded message" }] + + // abandonSubtask severs the link, then aborts the subtask with + // isAbandoned=true; an in-flight fire-and-forget save lands here. + task.requestAbort(true) + + const saved = await getTaskTestAccess(task).saveClineMessages() + + // The boolean reflects the message write only: the write succeeded, so the + // save reports success even though the history update is skipped. + expect(saved).toBe(true) + expect(saveSpy).toHaveBeenCalledTimes(1) // messages are still persisted + expect(saveSpy).toHaveBeenCalledWith( + expect.objectContaining({ + taskId: task.taskId, + messages: expect.arrayContaining([expect.objectContaining({ text: "seeded message" })]), + }), + ) + expect(mockProvider.updateTaskHistory).not.toHaveBeenCalled() // history link is not reattached + } finally { + saveSpy.mockRestore() + metaSpy.mockRestore() + } + }) + + it("refreshes an existing history row without reattaching the severed link when abandoned", async () => { + const saveSpy = vi.spyOn(taskMessagesModule, "saveTaskMessages").mockResolvedValue([]) + const metaSpy = vi.spyOn(taskMetadataModule, "taskMetadata").mockResolvedValue({ + historyItem: { ...staleHistoryItem, tokensIn: 11, tokensOut: 7, totalCost: 0.02 }, + tokenUsage: getApiMetrics([]), + }) + + try { + const mockProvider = makeMockProvider() + // The row already exists with the severed link; a plain cancel's final save + // must refresh metadata but keep the link severed (upsertCore merges, so the + // link keys must be omitted from the update). + ;(mockProvider.taskHistoryStore.get as ReturnType).mockReturnValue({ + id: "orphan-subtask", + status: "completed", + }) + const task = createTask(mockProvider) + task.clineMessages = [{ ts: 1, type: "say", say: "text", text: "seeded message" }] + task.requestAbort(true) + + const saved = await getTaskTestAccess(task).saveClineMessages() + + expect(saved).toBe(true) + expect(mockProvider.updateTaskHistory).toHaveBeenCalledTimes(1) + const update = (mockProvider.updateTaskHistory as ReturnType).mock.calls[0][0] + // Metadata is refreshed... + expect(update).toEqual( + expect.objectContaining({ + id: "orphan-subtask", + tokensIn: 11, + tokensOut: 7, + totalCost: 0.02, + status: "completed", + }), + ) + // ...but the update carries no link keys: the merge must leave the stored + // severed link untouched. + expect(update).not.toHaveProperty("parentTaskId") + expect(update).not.toHaveProperty("rootTaskId") + } finally { + saveSpy.mockRestore() + metaSpy.mockRestore() + } + }) + + it("updates task history for a non-abandoned task (guard does not block the normal path)", async () => { + const saveSpy = vi.spyOn(taskMessagesModule, "saveTaskMessages").mockResolvedValue([]) + const metaSpy = vi + .spyOn(taskMetadataModule, "taskMetadata") + .mockResolvedValue({ historyItem: staleHistoryItem, tokenUsage: getApiMetrics([]) }) + + try { + const mockProvider = makeMockProvider() + const task = createTask(mockProvider) + + const saved = await getTaskTestAccess(task).saveClineMessages() + + expect(saved).toBe(true) + expect(saveSpy).toHaveBeenCalledTimes(1) + // Control case: the guard must not block the normal path, so execution + // genuinely reached updateTaskHistory(). No pre-existing store entry, + // so the item is written as-is. + expect(mockProvider.updateTaskHistory).toHaveBeenCalledTimes(1) + expect(mockProvider.updateTaskHistory).toHaveBeenCalledWith(staleHistoryItem) + } finally { + saveSpy.mockRestore() + metaSpy.mockRestore() + } + }) + + it("skips the history update when the task is abandoned while the save is in flight", async () => { + // Fire-and-forget race: the save starts while the task is still active, + // abandonSubtask severs the link mid-save, and the guard must catch it + // when the awaited saveTaskMessages() finally resolves. + let resolveSave!: (value: import("@roo-code/types").ClineMessage[]) => void + const saveSpy = vi + .spyOn(taskMessagesModule, "saveTaskMessages") + .mockImplementation( + () => new Promise((resolve) => (resolveSave = resolve)), + ) + const metaSpy = vi + .spyOn(taskMetadataModule, "taskMetadata") + .mockResolvedValue({ historyItem: staleHistoryItem, tokenUsage: getApiMetrics([]) }) + + try { + const mockProvider = makeMockProvider() + const task = createTask(mockProvider) + + // Seed a message so the payload assertion is meaningful: clineMessages + // starts empty, and an empty-payload save would pass a call-count-only + // assertion even if the save dropped the messages field. + task.clineMessages = [{ ts: 1, type: "say", say: "text", text: "seeded message" }] + + const savePromise = getTaskTestAccess(task).saveClineMessages() + + // The save is in flight (awaiting saveTaskMessages) when the task is + // abandoned; only after it resumes does the save hit the guard. + task.requestAbort(true) + resolveSave([]) + + const saved = await savePromise + + // Write-success contract: the guard skips the history update, not the save. + expect(saved).toBe(true) + expect(saveSpy).toHaveBeenCalledTimes(1) // messages are still persisted + expect(saveSpy).toHaveBeenCalledWith( + expect.objectContaining({ + messages: expect.arrayContaining([expect.objectContaining({ text: "seeded message" })]), + }), + ) + expect(mockProvider.updateTaskHistory).not.toHaveBeenCalled() // history link is not reattached + } finally { + resolveSave?.([]) // settle the deferred save if an assertion failed above + saveSpy.mockRestore() + metaSpy.mockRestore() + } + }) +}) From 089d242c95c4d2dcd9d71a0bef618e05ea4e69d5 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Wed, 11 Nov 2026 20:18:47 +0800 Subject: [PATCH 2/3] test(core): drive the status-less side of the abandoned-save guard saveClineMessages branches on the stored row's status at Task.ts:1909 and only the truthy side ever ran: the row at 8788 arms a stored row carrying status "completed". Arm { id: "orphan-subtask" } with no status and require the update to carry refreshed metadata, no link keys, and no status key at all - upsertCore merges over the stored record, so a status: undefined key would clear a status the store already holds. Control: forcing the ternary onto its status-stamping branch fails exactly this row - expected { id: 'orphan-subtask', ...(7) } to not have property "status" - with the other 214 passing. 215 passed with the production head untouched. --- src/core/task/__tests__/Task.spec.ts | 43 ++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/src/core/task/__tests__/Task.spec.ts b/src/core/task/__tests__/Task.spec.ts index fcc0a503b2..3e20cc1204 100644 --- a/src/core/task/__tests__/Task.spec.ts +++ b/src/core/task/__tests__/Task.spec.ts @@ -10271,6 +10271,49 @@ describe("saveClineMessages abandoned guard (#1021)", () => { } }) + it("omits the status key when the stored row has none so the merge keeps the stored status", async () => { + const saveSpy = vi.spyOn(taskMessagesModule, "saveTaskMessages").mockResolvedValue([]) + const metaSpy = vi.spyOn(taskMetadataModule, "taskMetadata").mockResolvedValue({ + historyItem: { ...staleHistoryItem, tokensIn: 11, tokensOut: 7, totalCost: 0.02 }, + tokenUsage: getApiMetrics([]), + }) + + try { + const mockProvider = makeMockProvider() + // Every other row here arms a stored row that carries a status, so the falsy side + // of Task.ts:1909 never ran under test. A stored row without a status must produce + // the bare detached item: upsertCore merges over the stored record, so a + // `status: undefined` key in the payload would clear the status the store holds. + ;(mockProvider.taskHistoryStore.get as ReturnType).mockReturnValue({ id: "orphan-subtask" }) + const task = createTask(mockProvider) + task.clineMessages = [{ ts: 1, type: "say", say: "text", text: "seeded message" }] + task.requestAbort(true) + + const saved = await getTaskTestAccess(task).saveClineMessages() + + expect(saved).toBe(true) + expect(mockProvider.updateTaskHistory).toHaveBeenCalledTimes(1) + const update = (mockProvider.updateTaskHistory as ReturnType).mock.calls[0][0] + // Refreshed metadata and no link keys, exactly as the status-bearing row above. + expect(update).toEqual( + expect.objectContaining({ + id: "orphan-subtask", + tokensIn: 11, + tokensOut: 7, + totalCost: 0.02, + }), + ) + expect(update).not.toHaveProperty("parentTaskId") + expect(update).not.toHaveProperty("rootTaskId") + // And no status key at all: the falsy branch hands over the detached item rather + // than stamping the stored row's absent status onto the update. + expect(update).not.toHaveProperty("status") + } finally { + saveSpy.mockRestore() + metaSpy.mockRestore() + } + }) + it("updates task history for a non-abandoned task (guard does not block the normal path)", async () => { const saveSpy = vi.spyOn(taskMessagesModule, "saveTaskMessages").mockResolvedValue([]) const metaSpy = vi From fb92f85b49a294e93799b7a344d7f83d9a9ea530 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Mon, 30 Nov 2026 01:35:56 +0800 Subject: [PATCH 3/3] test(task): declare the persistence seams the abandoned-save guard tests spy on The guard landed with its five tests, but the spec never declared the bindings those tests spy through: taskMessagesModule, taskMetadataModule and getApiMetrics were referenced and never imported. tsc reported them as TS2304 and the vitest transform aborted the whole file, so the compile job failed at its Check types step and the windows unit-test lane failed on the same file while the ubuntu leg was cancelled. Three imports supply them: the two persistence modules by namespace, which is how this package spies on a module-level seam, and the token usage helper that the mocked metadata payload is built from. No assertion, expectation or mock behaviour in the block changed. --- src/core/task/__tests__/Task.spec.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/core/task/__tests__/Task.spec.ts b/src/core/task/__tests__/Task.spec.ts index 3e20cc1204..4fae06e1b2 100644 --- a/src/core/task/__tests__/Task.spec.ts +++ b/src/core/task/__tests__/Task.spec.ts @@ -42,6 +42,9 @@ import { ContextProxy } from "../../config/ContextProxy" import { parseMentions } from "../../mentions" import { MultiSearchReplaceDiffStrategy } from "../../diff/strategies/multi-search-replace" import type { ApiMessage } from "../../task-persistence" +import * as taskMessagesModule from "../../task-persistence/taskMessages" +import * as taskMetadataModule from "../../task-persistence/taskMetadata" +import { getApiMetrics } from "../../../shared/getApiMetrics" import type { RequestPolicySnapshot } from "../../prompts/tools/effective-tool-policy" import type { InstructionFailureCollector } from "../../prompts/sections/custom-instructions" import { asyncStreamFrom } from "../../../test-utils/stream"