Skip to content

Commit 03913bf

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 ed668c4 commit 03913bf

4 files changed

Lines changed: 217 additions & 57 deletions

File tree

‎src/core/webview/ClineProvider.ts‎

Lines changed: 57 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -2325,6 +2325,11 @@ export class ClineProvider
23252325
const historyItemBefore = taskHistoryItem
23262326
rollbackTaskWrites = async () => {
23272327
task["_taskMode"] = previousTaskMode
2328+
// Listeners were told about the new mode before the failure landed: re-emit
2329+
// with the restored mode so API/IPC consumers track the rollback.
2330+
if (previousTaskMode) {
2331+
task.emit(RooCodeEventName.TaskModeSwitched, task.taskId, previousTaskMode)
2332+
}
23282333
if (historyItemBefore) {
23292334
// Restore only the field this switch changed: re-read the item so
23302335
// fields the running task persisted during the write survive.
@@ -2428,71 +2433,67 @@ export class ClineProvider
24282433
// restored mode would otherwise shadow the fresh switch for consumers.
24292434
sharedAttempted = true
24302435
await this.setValue("mode", newMode)
2431-
2432-
this.emit(RooCodeEventName.ModeChanged, newMode)
24332436
}
24342437

2435-
// If workspace lock is on, keep the current API config — don't load mode-specific config
2438+
// If workspace lock is on, keep the current API config: the mode-linked
2439+
// activation below is skipped, and the committed switch falls through to the
2440+
// emit/post tail outside the reconciled region.
24362441
const lockApiConfigAcrossModes = this.context.workspaceState.get("lockApiConfigAcrossModes", false)
2437-
if (lockApiConfigAcrossModes) {
2438-
// Keep the original post semantics: an explicit null target (pending child)
2439-
// posts its own state.
2440-
if (targetTask !== null) {
2441-
await this.postStateToWebview()
2442+
if (!lockApiConfigAcrossModes) {
2443+
if (signal?.aborted) return
2444+
if (!viewScopedSwitch) {
2445+
return
24422446
}
2443-
return
2444-
}
24452447

2446-
if (signal?.aborted) return
2447-
if (!viewScopedSwitch) {
2448-
return
2449-
}
2448+
// Load the saved API config for the new mode if it exists.
2449+
const savedConfigId = await this.providerSettingsManager.getModeConfigId(newMode)
2450+
const listApiConfig = await this.providerSettingsManager.listConfig()
24502451

2451-
// Load the saved API config for the new mode if it exists.
2452-
const savedConfigId = await this.providerSettingsManager.getModeConfigId(newMode)
2453-
const listApiConfig = await this.providerSettingsManager.listConfig()
2452+
if (signal?.aborted) return
24542453

2455-
if (signal?.aborted) return
2454+
// Update listApiConfigMeta first to ensure UI has latest data.
2455+
await this.updateGlobalState("listApiConfigMeta", listApiConfig)
24562456

2457-
// Update listApiConfigMeta first to ensure UI has latest data.
2458-
await this.updateGlobalState("listApiConfigMeta", listApiConfig)
2457+
// If this mode has a saved config, use it.
2458+
if (savedConfigId) {
2459+
const profile = listApiConfig.find(({ id }) => id === savedConfigId)
24592460

2460-
// If this mode has a saved config, use it.
2461-
if (savedConfigId) {
2462-
const profile = listApiConfig.find(({ id }) => id === savedConfigId)
2463-
2464-
if (profile?.name) {
2465-
// Check if the profile has actual API configuration (not just an id).
2466-
// In CLI mode, the ProviderSettingsManager may return empty default profiles
2467-
// that only contain 'id' and 'name' fields. Activating such a profile would
2468-
// overwrite the CLI's working API configuration with empty settings.
2469-
// Skip activation if the profile has no apiProvider set - this indicates
2470-
// an unconfigured/empty profile.
2471-
const fullProfile = await this.providerSettingsManager.getProfile({ name: profile.name })
2472-
const hasActualSettings = !!fullProfile.apiProvider
2473-
2474-
if (hasActualSettings) {
2475-
activationStarted = true
2476-
await this.activateProviderProfileUnlocked(
2477-
{ name: profile.name },
2478-
targetTask === null ? { skipCurrentTaskRebuild: true } : undefined,
2479-
signal,
2480-
)
2461+
if (profile?.name) {
2462+
// Check if the profile has actual API configuration (not just an id).
2463+
// In CLI mode, the ProviderSettingsManager may return empty default profiles
2464+
// that only contain 'id' and 'name' fields. Activating such a profile would
2465+
// overwrite the CLI's working API configuration with empty settings.
2466+
// Skip activation if the profile has no apiProvider set - this indicates
2467+
// an unconfigured/empty profile.
2468+
const fullProfile = await this.providerSettingsManager.getProfile({ name: profile.name })
2469+
const hasActualSettings = !!fullProfile.apiProvider
2470+
2471+
if (hasActualSettings) {
2472+
activationStarted = true
2473+
await this.activateProviderProfileUnlocked(
2474+
{ name: profile.name },
2475+
targetTask === null ? { skipCurrentTaskRebuild: true } : undefined,
2476+
signal,
2477+
)
2478+
} else {
2479+
// The task will continue with the current/default configuration.
2480+
}
24812481
} else {
24822482
// The task will continue with the current/default configuration.
24832483
}
24842484
} else {
2485-
// The task will continue with the current/default configuration.
2486-
}
2487-
} else {
2488-
// If no saved config for this mode, save current config as default.
2489-
const currentApiConfigNameAfter = this.getGlobalState("currentApiConfigName")
2485+
// If no saved config for this mode, save current config as default.
2486+
// Use this view's effective profile: with per-view pins the shared slot can
2487+
// belong to a sibling view, and recording that profile as this mode's default
2488+
// would activate the wrong profile for every later switch to it.
2489+
const currentApiConfigNameAfter = this.getValues().currentApiConfigName
24902490

2491-
if (currentApiConfigNameAfter) {
2492-
const config = listApiConfig.find((c) => c.name === currentApiConfigNameAfter)
2491+
if (currentApiConfigNameAfter) {
2492+
const config = listApiConfig.find((c) => c.name === currentApiConfigNameAfter)
24932493

2494-
if (config?.id) {
2495-
await this.providerSettingsManager.setModeConfig(newMode, config.id)
2494+
if (config?.id) {
2495+
await this.providerSettingsManager.setModeConfig(newMode, config.id)
2496+
}
24962497
}
24972498
}
24982499
}
@@ -2513,6 +2514,12 @@ export class ClineProvider
25132514
throw error
25142515
}
25152516

2517+
// The switch has committed: notify listeners only now, so a reconciled failure
2518+
// never leaves listeners tracking a mode the stores rolled back from.
2519+
if (viewScopedSwitch) {
2520+
this.emit(RooCodeEventName.ModeChanged, newMode)
2521+
}
2522+
25162523
// The switch has committed: a UI-refresh failure must not roll it back, so the
25172524
// trailing post runs outside the reconciled region and its failure is only logged.
25182525
if (targetTask !== null) {

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

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5887,13 +5887,11 @@ describe("ClineProvider", () => {
58875887
setModeConfig: vi.fn(),
58885888
} as any
58895889

5890-
// Mock the ContextProxy's getValue method to return the current config name
5890+
// Seed the shared current config name: the mode-default recording reads the
5891+
// view's effective profile, which falls back to the shared slot when this
5892+
// view pins no profile of its own.
58915893
const contextProxy = (provider as any).contextProxy
5892-
const getValueSpy = vi.spyOn(contextProxy, "getValue")
5893-
getValueSpy.mockImplementation((key: any) => {
5894-
if (key === "currentApiConfigName") return "current-config"
5895-
return undefined
5896-
})
5894+
await contextProxy.setValue("currentApiConfigName", "current-config")
58975895

58985896
// Register a stable view id so the durable per-view write is persisted
58995897
await provider["setViewStateId"]("stable-test-view")

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

Lines changed: 155 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -869,6 +869,161 @@ describe("ClineProvider - Sticky Mode", () => {
869869
expect(updateTaskHistorySpy).not.toHaveBeenCalledWith(expect.objectContaining({ mode: "code" }))
870870
})
871871

872+
it("does not report ModeChanged for a mode switch that gets reconciled", async () => {
873+
// Same typed double as the activation-failure rollback test above.
874+
const mockTask = Object.assign(
875+
{} as Task,
876+
{
877+
taskId: "test-task-id",
878+
taskMode: "code",
879+
_taskMode: "code",
880+
emit: vi.fn(),
881+
saveClineMessages: vi.fn(),
882+
clineMessages: [],
883+
apiConversationHistory: [],
884+
updateApiConfiguration: vi.fn(),
885+
} as Partial<Task>,
886+
)
887+
const historyItem: HistoryItem = {
888+
id: "test-task-id",
889+
ts: Date.now(),
890+
task: "Test task",
891+
mode: "code",
892+
number: 1,
893+
tokensIn: 0,
894+
tokensOut: 0,
895+
cacheWrites: 0,
896+
cacheReads: 0,
897+
totalCost: 0,
898+
}
899+
vi.spyOn(provider.taskHistoryStore, "get").mockReturnValue(historyItem)
900+
const updateTaskHistorySpy = vi.spyOn(provider, "updateTaskHistory").mockResolvedValue([])
901+
await provider.saveViewState("mode", "code")
902+
await provider.contextProxy.setValue("mode", "code")
903+
const emitSpy = vi.spyOn(provider, "emit")
904+
905+
// The task, pin, and shared writes land and the activation read then rejects:
906+
// the reconcile rolls every store back, so listeners must not be left tracking
907+
// the rolled-back mode: ModeChanged must not have fired for it, and the task's
908+
// TaskModeSwitched must be re-emitted with the restored mode.
909+
vi.spyOn(provider.providerSettingsManager, "getModeConfigId").mockRejectedValue(
910+
new Error("activation read failed"),
911+
)
912+
await provider.addClineToStack(mockTask)
913+
914+
await expect(provider["handleModeSwitchUnlocked"]("architect", mockTask)).rejects.toThrow(
915+
"activation read failed",
916+
)
917+
918+
expect(emitSpy).not.toHaveBeenCalledWith("modeChanged", "architect")
919+
expect(mockTask.emit).toHaveBeenCalledWith("taskModeSwitched", "test-task-id", "architect")
920+
expect(mockTask.emit).toHaveBeenLastCalledWith("taskModeSwitched", "test-task-id", "code")
921+
})
922+
923+
it("keeps the committed switch when the lock-path state refresh fails", async () => {
924+
// Same typed double as the activation-failure rollback test above.
925+
const mockTask = Object.assign(
926+
{} as Task,
927+
{
928+
taskId: "test-task-id",
929+
taskMode: "code",
930+
_taskMode: "code",
931+
emit: vi.fn(),
932+
saveClineMessages: vi.fn(),
933+
clineMessages: [],
934+
apiConversationHistory: [],
935+
updateApiConfiguration: vi.fn(),
936+
} as Partial<Task>,
937+
)
938+
const historyItem: HistoryItem = {
939+
id: "test-task-id",
940+
ts: Date.now(),
941+
task: "Test task",
942+
mode: "code",
943+
number: 1,
944+
tokensIn: 0,
945+
tokensOut: 0,
946+
cacheWrites: 0,
947+
cacheReads: 0,
948+
totalCost: 0,
949+
}
950+
vi.spyOn(provider.taskHistoryStore, "get").mockReturnValue(historyItem)
951+
const updateTaskHistorySpy = vi.spyOn(provider, "updateTaskHistory").mockResolvedValue([])
952+
await provider.saveViewState("mode", "code")
953+
await provider.contextProxy.setValue("mode", "code")
954+
955+
// With the workspace profile lock on the switch commits without a mode-linked
956+
// activation; the trailing post now runs outside the reconciled region, so its
957+
// failure must leave the committed switch standing instead of rolling the mode
958+
// stores back.
959+
vi.spyOn(provider["context"].workspaceState, "get").mockImplementation((key: unknown, def?: unknown) =>
960+
key === "lockApiConfigAcrossModes" ? true : def,
961+
)
962+
vi.spyOn(provider, "postStateToWebview").mockRejectedValue(new Error("post failed"))
963+
await provider.addClineToStack(mockTask)
964+
965+
await provider["handleModeSwitchUnlocked"]("architect", mockTask)
966+
967+
expect(provider.getValue("mode")).toBe("architect")
968+
expect(provider["viewLocalState"].mode).toBe("architect")
969+
expect(mockTask["_taskMode"]).toBe("architect")
970+
expect(updateTaskHistorySpy).not.toHaveBeenCalledWith(expect.objectContaining({ mode: "code" }))
971+
})
972+
973+
it("records the mode default from the view's pinned profile, not the shared slot", async () => {
974+
// Same typed double as the activation-failure rollback test above.
975+
const mockTask = Object.assign(
976+
{} as Task,
977+
{
978+
taskId: "test-task-id",
979+
taskMode: "code",
980+
_taskMode: "code",
981+
emit: vi.fn(),
982+
saveClineMessages: vi.fn(),
983+
clineMessages: [],
984+
apiConversationHistory: [],
985+
updateApiConfiguration: vi.fn(),
986+
} as Partial<Task>,
987+
)
988+
const historyItem: HistoryItem = {
989+
id: "test-task-id",
990+
ts: Date.now(),
991+
task: "Test task",
992+
mode: "code",
993+
number: 1,
994+
tokensIn: 0,
995+
tokensOut: 0,
996+
cacheWrites: 0,
997+
cacheReads: 0,
998+
totalCost: 0,
999+
}
1000+
vi.spyOn(provider.taskHistoryStore, "get").mockReturnValue(historyItem)
1001+
const updateTaskHistorySpy = vi.spyOn(provider, "updateTaskHistory").mockResolvedValue([])
1002+
await provider.saveViewState("mode", "code")
1003+
await provider.contextProxy.setValue("mode", "code")
1004+
1005+
// The view pins profile-x while a sibling view's activation moved the shared
1006+
// slot to profile-y. Recording the mode default from the shared slot would make
1007+
// profile-y the default for the new mode in every view, though this view was
1008+
// running profile-x.
1009+
await provider.setValue("currentApiConfigName", "profile-x")
1010+
await provider.contextProxy.setValue("currentApiConfigName", "profile-y")
1011+
vi.spyOn(provider.providerSettingsManager, "getModeConfigId").mockResolvedValue(undefined)
1012+
vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([
1013+
{ id: "x-id", name: "profile-x", apiProvider: providerIdentifiers.openrouter },
1014+
{ id: "y-id", name: "profile-y", apiProvider: providerIdentifiers.anthropic },
1015+
])
1016+
const setModeConfig = vi
1017+
.spyOn(provider.providerSettingsManager, "setModeConfig")
1018+
.mockResolvedValue(undefined)
1019+
vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined)
1020+
await provider.addClineToStack(mockTask)
1021+
1022+
await provider["handleModeSwitchUnlocked"]("architect", mockTask)
1023+
1024+
expect(setModeConfig).toHaveBeenCalledWith("architect", "x-id")
1025+
})
1026+
8721027
it("keeps the cancellation result when the abort rollback write itself fails", async () => {
8731028
const mockTask = Object.assign(
8741029
{} as Task,

‎src/eslint-suppressions.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1021,7 +1021,7 @@
10211021
},
10221022
"core/webview/__tests__/ClineProvider.spec.ts": {
10231023
"@typescript-eslint/no-explicit-any": {
1024-
"count": 194
1024+
"count": 193
10251025
}
10261026
},
10271027
"core/webview/__tests__/ClineProvider.sticky-mode.spec.ts": {

0 commit comments

Comments
 (0)