Skip to content

Commit ed668c4

Browse files
committed
fix(webview): keep committed mode switches out of the reconcile rollback
The mode-switch reconcile rolled the mode back even when the mode-linked activation had already written shared state (profile, provider settings, mode mapping, sticky task profile): a later failure then paired the old mode with the new profile, the very mismatch the reconcile exists to prevent. The catch now keeps the switch once activation has started writing, and also when the mutation signal has aborted - the queue has advanced past the timed-out switch, so a newer mutation may own the mode stores. The trailing state post moved outside the reconciled region: a UI-refresh failure after a fully committed switch is logged, not rolled back. Three regression tests included.
1 parent e27816f commit ed668c4

2 files changed

Lines changed: 207 additions & 5 deletions

File tree

‎src/core/webview/ClineProvider.ts‎

Lines changed: 29 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2409,6 +2409,10 @@ export class ClineProvider
24092409
}
24102410
}
24112411

2412+
// Once the mode-linked activation below has started writing shared state, a
2413+
// mode-only rollback would pair the old mode with the new profile: the catch must
2414+
// then keep the switch instead of reconciling.
2415+
let activationStarted = false
24122416
try {
24132417
if (viewScopedSwitch) {
24142418
// Pin the view's durable per-view mode first: the pin is this view's own
@@ -2468,6 +2472,7 @@ export class ClineProvider
24682472
const hasActualSettings = !!fullProfile.apiProvider
24692473

24702474
if (hasActualSettings) {
2475+
activationStarted = true
24712476
await this.activateProviderProfileUnlocked(
24722477
{ name: profile.name },
24732478
targetTask === null ? { skipCurrentTaskRebuild: true } : undefined,
@@ -2491,17 +2496,36 @@ export class ClineProvider
24912496
}
24922497
}
24932498
}
2494-
2495-
if (targetTask !== null) {
2496-
await this.postStateToWebview()
2497-
}
24982499
} catch (error) {
2499-
await reconcileSwitchWrites()
2500+
// Two reasons to keep the switch instead of reconciling: once the mode-linked
2501+
// activation has started writing shared state, a mode-only rollback would pair
2502+
// the old mode with the new profile; and after a timeout abort the queue has
2503+
// advanced, so a newer mutation may own these fields and replaying the
2504+
// pre-switch values would clobber it.
2505+
if (!activationStarted && !signal?.aborted) {
2506+
await reconcileSwitchWrites()
2507+
} else if (signal?.aborted) {
2508+
this.log(`[handleModeSwitch] Skipping rollback for aborted switch to "${newMode}"`)
2509+
}
25002510
this.log(
25012511
`[handleModeSwitch] Failed to persist mode "${newMode}": ${error instanceof Error ? error.message : String(error)}`,
25022512
)
25032513
throw error
25042514
}
2515+
2516+
// The switch has committed: a UI-refresh failure must not roll it back, so the
2517+
// trailing post runs outside the reconciled region and its failure is only logged.
2518+
if (targetTask !== null) {
2519+
try {
2520+
await this.postStateToWebview()
2521+
} catch (postError: unknown) {
2522+
this.log(
2523+
`[handleModeSwitch] Mode switch to "${newMode}" committed but the state post failed: ${
2524+
postError instanceof Error ? postError.message : String(postError)
2525+
}`,
2526+
)
2527+
}
2528+
}
25052529
}
25062530

25072531
// Provider Profile Management

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

Lines changed: 178 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -691,6 +691,184 @@ describe("ClineProvider - Sticky Mode", () => {
691691
expect(provider.getValue("mode")).toBe("code")
692692
})
693693

694+
it("keeps the committed mode switch when the post-activation state refresh fails", async () => {
695+
// Same typed double as the activation-failure rollback test above.
696+
const mockTask = Object.assign(
697+
{} as Task,
698+
{
699+
taskId: "test-task-id",
700+
taskMode: "code",
701+
_taskMode: "code",
702+
emit: vi.fn(),
703+
saveClineMessages: vi.fn(),
704+
clineMessages: [],
705+
apiConversationHistory: [],
706+
updateApiConfiguration: vi.fn(),
707+
} as Partial<Task>,
708+
)
709+
const historyItem: HistoryItem = {
710+
id: "test-task-id",
711+
ts: Date.now(),
712+
task: "Test task",
713+
mode: "code",
714+
number: 1,
715+
tokensIn: 0,
716+
tokensOut: 0,
717+
cacheWrites: 0,
718+
cacheReads: 0,
719+
totalCost: 0,
720+
}
721+
vi.spyOn(provider.taskHistoryStore, "get").mockReturnValue(historyItem)
722+
const updateTaskHistorySpy = vi.spyOn(provider, "updateTaskHistory").mockResolvedValue([])
723+
await provider.saveViewState("mode", "code")
724+
await provider.contextProxy.setValue("mode", "code")
725+
726+
// The mode-linked profile resolves and its activation lands (writing the
727+
// shared profile like the real activation does); only the trailing state
728+
// post rejects. By then the switch has fully committed - ModeChanged was
729+
// emitted and the activation persisted the new profile - so a UI refresh
730+
// failure must not roll the mode back: that would pair the old mode with
731+
// the new profile, the very mismatch the reconcile exists to prevent.
732+
vi.spyOn(provider.providerSettingsManager, "getModeConfigId").mockResolvedValue("architect-profile-id")
733+
vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([
734+
{ id: "architect-profile-id", name: "architect-profile", apiProvider: providerIdentifiers.openrouter },
735+
])
736+
vi.spyOn(provider.providerSettingsManager, "getProfile").mockResolvedValue({
737+
name: "architect-profile",
738+
id: "architect-profile-id",
739+
apiProvider: providerIdentifiers.openrouter,
740+
})
741+
provider["activateProviderProfileUnlocked"] = vi.fn().mockImplementation(async () => {
742+
await provider.contextProxy.setValue("currentApiConfigName", "architect-profile")
743+
})
744+
vi.spyOn(provider, "postStateToWebview").mockRejectedValue(new Error("post failed"))
745+
await provider.addClineToStack(mockTask)
746+
747+
await provider["handleModeSwitchUnlocked"]("architect", mockTask)
748+
749+
expect(provider.getValue("mode")).toBe("architect")
750+
expect(provider["viewLocalState"].mode).toBe("architect")
751+
expect(mockTask["_taskMode"]).toBe("architect")
752+
expect(provider.contextProxy.getValue("currentApiConfigName")).toBe("architect-profile")
753+
expect(updateTaskHistorySpy).not.toHaveBeenCalledWith(expect.objectContaining({ mode: "code" }))
754+
})
755+
756+
it("keeps the switched mode when the mode-linked activation fails after writing", async () => {
757+
// Same typed double as the activation-failure rollback test above.
758+
const mockTask = Object.assign(
759+
{} as Task,
760+
{
761+
taskId: "test-task-id",
762+
taskMode: "code",
763+
_taskMode: "code",
764+
emit: vi.fn(),
765+
saveClineMessages: vi.fn(),
766+
clineMessages: [],
767+
apiConversationHistory: [],
768+
updateApiConfiguration: vi.fn(),
769+
} as Partial<Task>,
770+
)
771+
const historyItem: HistoryItem = {
772+
id: "test-task-id",
773+
ts: Date.now(),
774+
task: "Test task",
775+
mode: "code",
776+
number: 1,
777+
tokensIn: 0,
778+
tokensOut: 0,
779+
cacheWrites: 0,
780+
cacheReads: 0,
781+
totalCost: 0,
782+
}
783+
vi.spyOn(provider.taskHistoryStore, "get").mockReturnValue(historyItem)
784+
const updateTaskHistorySpy = vi.spyOn(provider, "updateTaskHistory").mockResolvedValue([])
785+
await provider.saveViewState("mode", "code")
786+
await provider.contextProxy.setValue("mode", "code")
787+
788+
// The mode-linked activation lands its shared writes and only then rejects
789+
// (e.g. its own state post or setModeConfig step failing). A mode-only rollback
790+
// would pair the old mode with the profile the activation already switched to,
791+
// the mismatch the reconcile exists to prevent: the switch must stand and the
792+
// error must still surface.
793+
vi.spyOn(provider.providerSettingsManager, "getModeConfigId").mockResolvedValue("architect-profile-id")
794+
vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([
795+
{ id: "architect-profile-id", name: "architect-profile", apiProvider: providerIdentifiers.openrouter },
796+
])
797+
vi.spyOn(provider.providerSettingsManager, "getProfile").mockResolvedValue({
798+
name: "architect-profile",
799+
id: "architect-profile-id",
800+
apiProvider: providerIdentifiers.openrouter,
801+
})
802+
provider["activateProviderProfileUnlocked"] = vi.fn().mockImplementation(async () => {
803+
await provider.contextProxy.setValue("currentApiConfigName", "architect-profile")
804+
throw new Error("activation step failed")
805+
})
806+
await provider.addClineToStack(mockTask)
807+
808+
await expect(provider["handleModeSwitchUnlocked"]("architect", mockTask)).rejects.toThrow(
809+
"activation step failed",
810+
)
811+
812+
expect(provider.getValue("mode")).toBe("architect")
813+
expect(provider["viewLocalState"].mode).toBe("architect")
814+
expect(mockTask["_taskMode"]).toBe("architect")
815+
expect(provider.contextProxy.getValue("currentApiConfigName")).toBe("architect-profile")
816+
expect(updateTaskHistorySpy).not.toHaveBeenCalledWith(expect.objectContaining({ mode: "code" }))
817+
})
818+
819+
it("keeps the switched mode when the mutation signal aborted before the failure", async () => {
820+
// Same typed double as the activation-failure rollback test above.
821+
const mockTask = Object.assign(
822+
{} as Task,
823+
{
824+
taskId: "test-task-id",
825+
taskMode: "code",
826+
_taskMode: "code",
827+
emit: vi.fn(),
828+
saveClineMessages: vi.fn(),
829+
clineMessages: [],
830+
apiConversationHistory: [],
831+
updateApiConfiguration: vi.fn(),
832+
} as Partial<Task>,
833+
)
834+
const historyItem: HistoryItem = {
835+
id: "test-task-id",
836+
ts: Date.now(),
837+
task: "Test task",
838+
mode: "code",
839+
number: 1,
840+
tokensIn: 0,
841+
tokensOut: 0,
842+
cacheWrites: 0,
843+
cacheReads: 0,
844+
totalCost: 0,
845+
}
846+
vi.spyOn(provider.taskHistoryStore, "get").mockReturnValue(historyItem)
847+
const updateTaskHistorySpy = vi.spyOn(provider, "updateTaskHistory").mockResolvedValue([])
848+
await provider.saveViewState("mode", "code")
849+
await provider.contextProxy.setValue("mode", "code")
850+
851+
// The pin and shared writes land; then the mutation timeout aborts this
852+
// switch and a later step rejects. The queue has already advanced past the
853+
// timed-out switch, so a newer mutation may own the mode stores: the late
854+
// rollback must not replay the pre-switch values over them.
855+
const controller = new AbortController()
856+
vi.spyOn(provider.providerSettingsManager, "getModeConfigId").mockImplementation(async () => {
857+
controller.abort()
858+
throw new Error("late activation read failure")
859+
})
860+
await provider.addClineToStack(mockTask)
861+
862+
await expect(
863+
provider["handleModeSwitchUnlocked"]("architect", mockTask, controller.signal),
864+
).rejects.toThrow("late activation read failure")
865+
866+
expect(provider.getValue("mode")).toBe("architect")
867+
expect(provider["viewLocalState"].mode).toBe("architect")
868+
expect(mockTask["_taskMode"]).toBe("architect")
869+
expect(updateTaskHistorySpy).not.toHaveBeenCalledWith(expect.objectContaining({ mode: "code" }))
870+
})
871+
694872
it("keeps the cancellation result when the abort rollback write itself fails", async () => {
695873
const mockTask = Object.assign(
696874
{} as Task,

0 commit comments

Comments
 (0)