Skip to content

Commit db6299d

Browse files
fix: roll back task-side mode writes when the view mode pin write fails,
rebuild re-pinned siblings' tasks Review-round fixes on the shared code this unit carries: (1) when the view's durable mode pin write rejected inside handleModeSwitchUnlocked, the task-history write and the in-memory task mode had already landed and the caller delivered the submitted message with the new task mode against the view's unchanged mode and mode-linked API configuration - the failure now restores the pre-switch task mode and history entry before rethrowing. (2) rePinViewLocalStateForDeletedProfile updated each sibling's buffer but not its running task: the posted state prefers the task's own apiConfiguration, so a conversation in a view pinned to the deleted profile kept sending the deleted profile's settings - the re-pin now rebuilds the sibling's API handler with the replacement's settings and re-points the task's sticky profile name. Proofs: ClineProvider.spec, sticky-mode (new pin-write-failure rollback test), and parallel-mode (sibling re-pin test asserts the task handler rebuild and sticky-name re-point) green; negative controls: dropping the rollback call reddens exactly the rollback test, dropping the rebuild reddens exactly the re-pin test, restores byte-exact (hash match); eslint --max-warnings=0 clean; prettier clean.
1 parent 4b28d3d commit db6299d

3 files changed

Lines changed: 123 additions & 2 deletions

File tree

‎src/core/webview/ClineProvider.ts‎

Lines changed: 49 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2198,6 +2198,10 @@ export class ClineProvider
21982198
): Promise<void> {
21992199
const task = targetTask
22002200

2201+
// Captured for the pin-write rollback below: the mode this task held before
2202+
// the switch (bracket access: _taskMode is private to Task).
2203+
const previousTaskMode = task ? task["_taskMode"] : undefined
2204+
let rollbackTaskWrites: (() => Promise<void>) | undefined
22012205
// A cancelled or timed-out switch must not be partially applied: bail out
22022206
// before the task history / _taskMode writes as well as the durable mode
22032207
// write below. Aborts that land while the history write is in flight are
@@ -2243,6 +2247,21 @@ export class ClineProvider
22432247

22442248
// Only update the task's mode after successful persistence.
22452249
;(task as any)._taskMode = newMode
2250+
2251+
// If the view's durable mode pin below fails after these task-side writes
2252+
// landed, restore them: the caller delivers the message on the caught
2253+
// error, and the new task mode must not run against the view's unchanged
2254+
// mode and mode-linked API configuration.
2255+
const historyItemBefore = taskHistoryItem
2256+
rollbackTaskWrites = async () => {
2257+
task["_taskMode"] = previousTaskMode
2258+
if (historyItemBefore) {
2259+
// Restore only the field this switch changed: re-read the item so
2260+
// fields the running task persisted during the write survive.
2261+
const latest = this.getTaskHistoryItem(task.taskId) ?? historyItemBefore
2262+
await this.updateTaskHistory({ ...latest, mode: historyItemBefore.mode })
2263+
}
2264+
}
22462265
} catch (error) {
22472266
// If persistence fails, log the error but don't update the in-memory state.
22482267
this.log(
@@ -2269,7 +2288,26 @@ export class ClineProvider
22692288
if (viewScopedSwitch) {
22702289
// Pin the view's durable per-view mode first: the pin is this view's own
22712290
// selection and must not be undone if the shared write later fails.
2272-
await this.saveViewState("mode", newMode)
2291+
// If the pin write itself fails, the task-side writes above are already
2292+
// applied: roll them back before rethrowing so the caller cannot deliver
2293+
// the message with the new task mode while the view's mode and mode-linked
2294+
// API configuration stayed old.
2295+
try {
2296+
await this.saveViewState("mode", newMode)
2297+
} catch (error) {
2298+
if (rollbackTaskWrites) {
2299+
try {
2300+
await rollbackTaskWrites()
2301+
} catch (rollbackError) {
2302+
this.log(
2303+
`[handleModeSwitch] Failed to roll back task mode writes after the view mode pin write failed: ${
2304+
rollbackError instanceof Error ? rollbackError.message : String(rollbackError)
2305+
}`,
2306+
)
2307+
}
2308+
}
2309+
throw error
2310+
}
22732311

22742312
// setValue (not the deprecated updateGlobalState) so the in-memory viewLocalState
22752313
// buffer stays in sync with the durable global write: getValues() merges
@@ -2884,6 +2922,16 @@ export class ClineProvider
28842922

28852923
// Direct private access: compile-time safe across sibling instances.
28862924
await instance._saveViewLocalStateFromMutation(values)
2925+
// The active task of a view pinned to the deleted profile holds its own API
2926+
// handler and sticky profile name built from the deleted profile: rebuild
2927+
// the handler with the replacement's settings and re-point the sticky name,
2928+
// or the running conversation keeps sending the deleted profile's
2929+
// configuration even though the view's buffer was re-pointed (the posted
2930+
// state prefers the task's own apiConfiguration).
2931+
if (replacementSettings) {
2932+
instance.updateTaskApiHandlerIfNeeded(replacementSettings, { forceRebuild: true })
2933+
}
2934+
await instance.persistStickyProviderProfileToCurrentTask(replacementName)
28872935
await instance.postStateToWebview()
28882936
}),
28892937
)

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

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1317,7 +1317,19 @@ describe("ClineProvider - Parallel Mode Support", () => {
13171317
vi.spyOn(providerA.providerSettingsManager, "listConfig").mockResolvedValue([
13181318
{ id: "replacement-id", name: "replacement-profile", apiProvider: providerIdentifiers.openrouter },
13191319
])
1320-
// The pre-return re-pin resolves the replacement's settings through the manager.
1320+
// B has an active task built from the doomed profile's settings: the posted
1321+
// state prefers the task's own apiConfiguration, so the re-pin must rebuild
1322+
// the task's handler and re-point its sticky profile name too.
1323+
const siblingTask = {
1324+
apiConfiguration: { apiProvider: providerIdentifiers.anthropic, apiKey: "doomed-key" },
1325+
updateApiConfiguration: vi.fn(),
1326+
setTaskApiConfigName: vi.fn(),
1327+
}
1328+
vi.spyOn(providerB, "getCurrentTask").mockReturnValue(
1329+
siblingTask as unknown as ReturnType<typeof providerB.getCurrentTask>,
1330+
)
1331+
1332+
// The pre-return re-pin // The pre-return re-pin resolves the replacement's settings through the manager.
13211333
vi.spyOn(providerA.providerSettingsManager, "getProfile").mockImplementation(
13221334
async (_args: { name?: string; id?: string }) =>
13231335
({
@@ -1342,6 +1354,18 @@ describe("ClineProvider - Parallel Mode Support", () => {
13421354
openRouterBaseUrl: "repl-url",
13431355
})
13441356
expect((await providerB.getState()).currentApiConfigName).toBe("replacement-profile")
1357+
// The active task's handler is rebuilt with the replacement's settings and
1358+
// its sticky profile name re-points to the replacement: without this the
1359+
// running conversation keeps sending the deleted profile's configuration.
1360+
// objectContaining: the replacement's settings carry the profile id alongside
1361+
// the provider fields (the name is stripped, the id is not).
1362+
expect(siblingTask.updateApiConfiguration).toHaveBeenCalledWith(
1363+
expect.objectContaining({
1364+
apiProvider: providerIdentifiers.openrouter,
1365+
openRouterBaseUrl: "repl-url",
1366+
}),
1367+
)
1368+
expect(siblingTask.setTaskApiConfigName).toHaveBeenCalledWith("replacement-profile")
13451369

13461370
await providerA.dispose()
13471371
await providerB.dispose()

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

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -627,6 +627,55 @@ describe("ClineProvider - Sticky Mode", () => {
627627
expect(mockContext.globalState.update).not.toHaveBeenCalledWith("mode", "architect")
628628
})
629629

630+
it("rolls back the task mode and history when the view mode pin write fails", async () => {
631+
// Same typed double as the abort rollback test: the private members stay
632+
// out of the Object.assign intersection type.
633+
const mockTask = Object.assign(
634+
{} as Task,
635+
{
636+
taskId: "test-task-id",
637+
taskMode: "code",
638+
_taskMode: "code",
639+
emit: vi.fn(),
640+
saveClineMessages: vi.fn(),
641+
clineMessages: [],
642+
apiConversationHistory: [],
643+
updateApiConfiguration: vi.fn(),
644+
} as Partial<Task>,
645+
)
646+
647+
const historyItem: HistoryItem = {
648+
id: "test-task-id",
649+
ts: Date.now(),
650+
task: "Test task",
651+
mode: "code",
652+
number: 1,
653+
tokensIn: 0,
654+
tokensOut: 0,
655+
cacheWrites: 0,
656+
cacheReads: 0,
657+
totalCost: 0,
658+
}
659+
vi.spyOn(provider.taskHistoryStore, "get").mockReturnValue(historyItem)
660+
661+
// The task-history write lands; the view's durable mode pin write then
662+
// rejects. The caller (submitUserMessage) logs the failure and delivers the
663+
// message, so the task-side writes must not stand.
664+
const updateTaskHistorySpy = vi.spyOn(provider, "updateTaskHistory").mockResolvedValue([])
665+
vi.spyOn(provider, "saveViewState").mockRejectedValueOnce(new Error("pin write failed"))
666+
await provider.addClineToStack(mockTask)
667+
668+
await expect(provider["handleModeSwitchUnlocked"]("architect", mockTask)).rejects.toThrow(
669+
"pin write failed",
670+
)
671+
672+
// No partial application: the task keeps its previous mode and the history
673+
// entry is restored, so the delivered message cannot run the new task mode
674+
// against the view's unchanged mode and mode-linked API configuration.
675+
expect(mockTask["_taskMode"]).toBe("code")
676+
expect(updateTaskHistorySpy).toHaveBeenLastCalledWith(historyItem)
677+
})
678+
630679
it("keeps the cancellation result when the abort rollback write itself fails", async () => {
631680
const mockTask = Object.assign(
632681
{} as Task,

0 commit comments

Comments
 (0)