Skip to content

Commit bff2a5c

Browse files
committed
2 parents 267bf35 + 3a24b1b commit bff2a5c

2 files changed

Lines changed: 144 additions & 2 deletions

File tree

‎src/core/webview/ClineProvider.ts‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2093,9 +2093,19 @@ export class ClineProvider
20932093
// An abort that lands while the history write is in flight has
20942094
// already persisted the new mode: restore the pre-switch item and
20952095
// bail before the in-memory task write and the emit, so task
2096-
// history, task state, and provider mode cannot diverge.
2096+
// history, task state, and provider mode cannot diverge. A failed
2097+
// rollback must not surface as the persistence error of the
2098+
// cancelled switch: log it and keep the cancellation result.
20972099
if (signal?.aborted) {
2098-
await this.updateTaskHistory(taskHistoryItem)
2100+
try {
2101+
// Restore only the field this switch changed: re-read the item so
2102+
// fields the running task persisted during the pending window
2103+
// (tokens, cost, status, apiConfigName) survive the rollback.
2104+
const latest = this.getTaskHistoryItem(task.taskId) ?? taskHistoryItem
2105+
await this.updateTaskHistory({ ...latest, mode: taskHistoryItem.mode })
2106+
} catch (rollbackError) {
2107+
this.log(`Failed to roll back mode switch ${task.taskId}: ${String(rollbackError)}`)
2108+
}
20992109
return
21002110
}
21012111
} else if (signal?.aborted) {

‎src/core/webview/__tests__/ClineProvider.sticky-mode.spec.ts‎

Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -589,6 +589,138 @@ describe("ClineProvider - Sticky Mode", () => {
589589
expect(mockContext.globalState.update).not.toHaveBeenCalledWith("mode", "architect")
590590
})
591591

592+
it("keeps the cancellation result when the abort rollback write itself fails", async () => {
593+
const mockTask = Object.assign(
594+
{} as Task,
595+
{
596+
taskId: "test-task-id",
597+
taskMode: "code",
598+
_taskMode: "code",
599+
emit: vi.fn(),
600+
saveClineMessages: vi.fn(),
601+
clineMessages: [],
602+
apiConversationHistory: [],
603+
updateApiConfiguration: vi.fn(),
604+
} as Partial<Task>,
605+
)
606+
607+
const historyItem: HistoryItem = {
608+
id: "test-task-id",
609+
ts: Date.now(),
610+
task: "Test task",
611+
mode: "code",
612+
number: 1,
613+
tokensIn: 0,
614+
tokensOut: 0,
615+
cacheWrites: 0,
616+
cacheReads: 0,
617+
totalCost: 0,
618+
}
619+
vi.spyOn(provider.taskHistoryStore, "get").mockReturnValue(historyItem)
620+
621+
// The first write settles after the abort lands; the rollback write rejects:
622+
// the failure is logged with its own message and the cancelled switch still
623+
// resolves (it must not surface as the switch's persistence error).
624+
let releaseUpdate!: (value: HistoryItem[]) => void
625+
const updateTaskHistorySpy = vi
626+
.spyOn(provider, "updateTaskHistory")
627+
.mockImplementationOnce(
628+
() =>
629+
new Promise<HistoryItem[]>((resolve) => {
630+
releaseUpdate = resolve
631+
}),
632+
)
633+
.mockRejectedValueOnce(new Error("rollback write failed"))
634+
await provider.addClineToStack(mockTask)
635+
636+
const controller = new AbortController()
637+
const switchPromise = provider["handleModeSwitchUnlocked"]("architect", mockTask, controller.signal)
638+
639+
await vi.waitFor(() => {
640+
expect(updateTaskHistorySpy).toHaveBeenCalledTimes(1)
641+
})
642+
controller.abort()
643+
releaseUpdate([])
644+
await expect(switchPromise).resolves.toBeUndefined()
645+
646+
expect(updateTaskHistorySpy).toHaveBeenCalledTimes(2)
647+
expect(mockOutputChannel.appendLine).toHaveBeenCalledWith(
648+
expect.stringContaining("Failed to roll back mode switch"),
649+
)
650+
})
651+
652+
it("preserves fields persisted during the pending window when rolling back the mode", async () => {
653+
const mockTask = Object.assign(
654+
{} as Task,
655+
{
656+
taskId: "test-task-id",
657+
taskMode: "code",
658+
_taskMode: "code",
659+
emit: vi.fn(),
660+
saveClineMessages: vi.fn(),
661+
clineMessages: [],
662+
apiConversationHistory: [],
663+
updateApiConfiguration: vi.fn(),
664+
} as Partial<Task>,
665+
)
666+
667+
const preSwitchItem: HistoryItem = {
668+
id: "test-task-id",
669+
ts: Date.now(),
670+
task: "Test task",
671+
mode: "code",
672+
number: 1,
673+
tokensIn: 0,
674+
tokensOut: 0,
675+
cacheWrites: 0,
676+
cacheReads: 0,
677+
totalCost: 0,
678+
}
679+
// While the history write is in flight the running task persists other fields
680+
// of the same item; the store now returns that updated item.
681+
const updatedItem: HistoryItem = {
682+
...preSwitchItem,
683+
mode: "architect",
684+
tokensIn: 42,
685+
totalCost: 0.5,
686+
}
687+
const storeGet = vi
688+
.spyOn(provider.taskHistoryStore, "get")
689+
.mockReturnValueOnce(preSwitchItem)
690+
.mockReturnValue(updatedItem)
691+
692+
let releaseUpdate!: (value: HistoryItem[]) => void
693+
const updateTaskHistorySpy = vi
694+
.spyOn(provider, "updateTaskHistory")
695+
.mockImplementationOnce(
696+
() =>
697+
new Promise<HistoryItem[]>((resolve) => {
698+
releaseUpdate = resolve
699+
}),
700+
)
701+
.mockResolvedValueOnce([])
702+
await provider.addClineToStack(mockTask)
703+
704+
const controller = new AbortController()
705+
const switchPromise = provider["handleModeSwitchUnlocked"]("architect", mockTask, controller.signal)
706+
707+
await vi.waitFor(() => {
708+
expect(updateTaskHistorySpy).toHaveBeenCalledTimes(1)
709+
})
710+
controller.abort()
711+
releaseUpdate([])
712+
await expect(switchPromise).resolves.toBeUndefined()
713+
714+
// The rollback restores only the mode: the fields persisted during the
715+
// pending window (tokensIn, totalCost) survive the rollback write.
716+
expect(updateTaskHistorySpy).toHaveBeenCalledTimes(2)
717+
expect(storeGet).toHaveBeenCalledTimes(2)
718+
expect(updateTaskHistorySpy).toHaveBeenNthCalledWith(
719+
2,
720+
expect.objectContaining({ id: "test-task-id", mode: "code", tokensIn: 42, totalCost: 0.5 }),
721+
)
722+
})
723+
592724
it("proceeds normally when no mutation signal is provided", async () => {
593725
// A minimal typed double keeps the test focused on the mode-switch contract.
594726
// The literal is asserted as Partial<Task> so its private members (_taskMode,

0 commit comments

Comments
 (0)