Skip to content

Commit 94c5c76

Browse files
committed
fix(webview): commit the mode-switch guard at the activation write
1 parent 3f1b91c commit 94c5c76

2 files changed

Lines changed: 255 additions & 37 deletions

File tree

‎src/core/webview/ClineProvider.ts‎

Lines changed: 77 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -2438,7 +2438,8 @@ export class ClineProvider
24382438
// emit/post tail outside the reconciled region.
24392439
const lockApiConfigAcrossModes = this.context.workspaceState.get("lockApiConfigAcrossModes", false)
24402440
if (!lockApiConfigAcrossModes) {
2441-
if (signal?.aborted) return
2441+
// A background-task switch applies to the task only: no view pin, no
2442+
// ModeChanged, and no mode-linked activation on its behalf.
24422443
if (!viewScopedSwitch) {
24432444
return
24442445
}
@@ -2447,50 +2448,59 @@ export class ClineProvider
24472448
const savedConfigId = await this.providerSettingsManager.getModeConfigId(newMode)
24482449
const listApiConfig = await this.providerSettingsManager.listConfig()
24492450

2450-
if (signal?.aborted) return
2451+
// The pin and shared mode writes above have committed the mode: an abort
2452+
// here skips the remaining activation work but falls through to the
2453+
// emit/post tail so listeners and the webview learn the committed mode.
2454+
if (!signal?.aborted) {
2455+
await this.updateGlobalState("listApiConfigMeta", listApiConfig)
24512456

2452-
// Update listApiConfigMeta first to ensure UI has latest data.
2453-
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)
24542460

2455-
// If this mode has a saved config, use it.
2456-
if (savedConfigId) {
2457-
const profile = listApiConfig.find(({ id }) => id === savedConfigId)
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
24582470

2459-
if (profile?.name) {
2460-
// Check if the profile has actual API configuration (not just an id).
2461-
// In CLI mode, the ProviderSettingsManager may return empty default profiles
2462-
// that only contain 'id' and 'name' fields. Activating such a profile would
2463-
// overwrite the CLI's working API configuration with empty settings.
2464-
// Skip activation if the profile has no apiProvider set - this indicates
2465-
// an unconfigured/empty profile.
2466-
const fullProfile = await this.providerSettingsManager.getProfile({ name: profile.name })
2467-
const hasActualSettings = !!fullProfile.apiProvider
2468-
2469-
if (hasActualSettings) {
2470-
activationStarted = true
2471-
await this.activateProviderProfileUnlocked(
2472-
{ name: profile.name },
2473-
targetTask === null ? { skipCurrentTaskRebuild: true } : undefined,
2474-
signal,
2475-
)
2471+
if (hasActualSettings) {
2472+
// The committed-switch guard flips only when the activation has
2473+
// actually written the activated profile: a lookup failure (e.g. a
2474+
// deleted profile) throws before any write and must still reconcile.
2475+
await this.activateProviderProfileUnlocked(
2476+
{ name: profile.name },
2477+
{
2478+
...(targetTask === null ? { skipCurrentTaskRebuild: true } : {}),
2479+
onSharedWriteStart: () => {
2480+
activationStarted = true
2481+
},
2482+
},
2483+
signal,
2484+
)
2485+
} else {
2486+
// The task will continue with the current/default configuration.
2487+
}
24762488
} else {
24772489
// The task will continue with the current/default configuration.
24782490
}
24792491
} else {
2480-
// The task will continue with the current/default configuration.
2481-
}
2482-
} else {
2483-
// If no saved config for this mode, save current config as default.
2484-
// Use this view's effective profile: with per-view pins the shared slot can
2485-
// belong to a sibling view, and recording that profile as this mode's default
2486-
// would activate the wrong profile for every later switch to it.
2487-
const currentApiConfigNameAfter = this.getValues().currentApiConfigName
2492+
// If no saved config for this mode, save current config as default.
2493+
// Use this view's effective profile: with per-view pins the shared slot can
2494+
// belong to a sibling view, and recording that profile as this mode's default
2495+
// would activate the wrong profile for every later switch to it.
2496+
const currentApiConfigNameAfter = this.getValues().currentApiConfigName
24882497

2489-
if (currentApiConfigNameAfter) {
2490-
const config = listApiConfig.find((c) => c.name === currentApiConfigNameAfter)
2498+
if (currentApiConfigNameAfter) {
2499+
const config = listApiConfig.find((c) => c.name === currentApiConfigNameAfter)
24912500

2492-
if (config?.id) {
2493-
await this.providerSettingsManager.setModeConfig(newMode, config.id)
2501+
if (config?.id) {
2502+
await this.providerSettingsManager.setModeConfig(newMode, config.id)
2503+
}
24942504
}
24952505
}
24962506
}
@@ -2504,7 +2514,30 @@ export class ClineProvider
25042514
if (!activationStarted && !signal?.aborted) {
25052515
await reconcileSwitchWrites()
25062516
} else if (signal?.aborted) {
2517+
// After an abort the mutation queue has advanced: a newer mutation may
2518+
// already own the mode fields, so emitting here could announce a mode the
2519+
// newer mutation replaced - listeners are intentionally not notified on
2520+
// this path.
25072521
this.log(`[handleModeSwitch] Skipping rollback for aborted switch to "${newMode}"`)
2522+
} else {
2523+
// The activation had already written the activated profile: the switch is
2524+
// kept. Listeners must still learn the committed mode before the rethrow,
2525+
// and the webview must refresh in case the activation failed before its
2526+
// own state post.
2527+
if (viewScopedSwitch) {
2528+
this.emit(RooCodeEventName.ModeChanged, newMode)
2529+
}
2530+
if (targetTask !== null) {
2531+
try {
2532+
await this.postStateToWebview()
2533+
} catch (postError: unknown) {
2534+
this.log(
2535+
`[handleModeSwitch] Mode switch to "${newMode}" kept but the state post failed: ${
2536+
postError instanceof Error ? postError.message : String(postError)
2537+
}`,
2538+
)
2539+
}
2540+
}
25082541
}
25092542
this.log(
25102543
`[handleModeSwitch] Failed to persist mode "${newMode}": ${error instanceof Error ? error.message : String(error)}`,
@@ -2930,11 +2963,19 @@ export class ClineProvider
29302963
persistModeConfig?: boolean
29312964
persistTaskHistory?: boolean
29322965
skipCurrentTaskRebuild?: boolean
2966+
// Fires once the activation has written the activated profile to shared
2967+
// state, so callers can mark the switch committed at the true point of no
2968+
// return (a profile lookup failure must stay reconcilable).
2969+
onSharedWriteStart?: () => void
29332970
},
29342971
signal?: AbortSignal,
29352972
): Promise<void> {
29362973
const { name, id, ...providerSettings } = await this.providerSettingsManager.activateProfile(args)
29372974

2975+
// The manager has now written the activated profile: from here on a failure
2976+
// must keep the switch rather than roll the mode back onto the old profile.
2977+
options?.onSharedWriteStart?.()
2978+
29382979
if (signal?.aborted) return
29392980

29402981
const persistModeConfig = options?.persistModeConfig ?? true

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

Lines changed: 178 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -848,7 +848,10 @@ describe("ClineProvider - Sticky Mode", () => {
848848
id: "architect-profile-id",
849849
apiProvider: providerIdentifiers.openrouter,
850850
})
851-
provider["activateProviderProfileUnlocked"] = vi.fn().mockImplementation(async () => {
851+
provider["activateProviderProfileUnlocked"] = vi.fn().mockImplementation(async (_args, options) => {
852+
// The real activation flips the committed-switch guard when it writes
853+
// the activated profile; mirror that here.
854+
options?.onSharedWriteStart?.()
852855
await provider.contextProxy.setValue("currentApiConfigName", "architect-profile")
853856
throw new Error("activation step failed")
854857
})
@@ -1073,6 +1076,180 @@ describe("ClineProvider - Sticky Mode", () => {
10731076
expect(setModeConfig).toHaveBeenCalledWith("architect", "x-id")
10741077
})
10751078

1079+
it("reconciles the switch when the mode-linked profile lookup fails", async () => {
1080+
// Same typed double as the activation-failure rollback test above.
1081+
const mockTask = Object.assign(
1082+
{} as Task,
1083+
{
1084+
taskId: "test-task-id",
1085+
taskMode: "code",
1086+
_taskMode: "code",
1087+
emit: vi.fn(),
1088+
saveClineMessages: vi.fn(),
1089+
clineMessages: [],
1090+
apiConversationHistory: [],
1091+
updateApiConfiguration: vi.fn(),
1092+
} as Partial<Task>,
1093+
)
1094+
const historyItem: HistoryItem = {
1095+
id: "test-task-id",
1096+
ts: Date.now(),
1097+
task: "Test task",
1098+
mode: "code",
1099+
number: 1,
1100+
tokensIn: 0,
1101+
tokensOut: 0,
1102+
cacheWrites: 0,
1103+
cacheReads: 0,
1104+
totalCost: 0,
1105+
}
1106+
vi.spyOn(provider.taskHistoryStore, "get").mockReturnValue(historyItem)
1107+
const updateTaskHistorySpy = vi.spyOn(provider, "updateTaskHistory").mockResolvedValue([])
1108+
await provider.saveViewState("mode", "code")
1109+
await provider.contextProxy.setValue("mode", "code")
1110+
1111+
// The mode's saved profile was deleted: the lookup inside the activation
1112+
// throws before any shared write lands. The committed-switch guard must still
1113+
// be off, so the reconcile restores every mode write.
1114+
vi.spyOn(provider.providerSettingsManager, "getModeConfigId").mockResolvedValue("architect-profile-id")
1115+
vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([
1116+
{ id: "architect-profile-id", name: "architect-profile", apiProvider: providerIdentifiers.openrouter },
1117+
])
1118+
vi.spyOn(provider.providerSettingsManager, "getProfile").mockResolvedValue({
1119+
name: "architect-profile",
1120+
id: "architect-profile-id",
1121+
apiProvider: providerIdentifiers.openrouter,
1122+
})
1123+
// The activation's own profile lookup throws before any shared write lands
1124+
// (e.g. the profile was deleted): the committed-switch guard must still be
1125+
// off, so the reconcile restores every mode write.
1126+
provider["activateProviderProfileUnlocked"] = vi.fn().mockRejectedValue(new Error("profile not found"))
1127+
await provider.addClineToStack(mockTask)
1128+
1129+
await expect(provider["handleModeSwitchUnlocked"]("architect", mockTask)).rejects.toThrow(
1130+
"profile not found",
1131+
)
1132+
1133+
expect(provider.getValue("mode")).toBe("code")
1134+
expect(provider["viewLocalState"].mode).toBe("code")
1135+
expect(mockTask["_taskMode"]).toBe("code")
1136+
expect(updateTaskHistorySpy).toHaveBeenCalledWith(expect.objectContaining({ mode: "code" }))
1137+
})
1138+
1139+
it("reports ModeChanged for a switch the catch keeps after activation wrote", async () => {
1140+
// Same typed double as the activation-failure rollback test above.
1141+
const mockTask = Object.assign(
1142+
{} as Task,
1143+
{
1144+
taskId: "test-task-id",
1145+
taskMode: "code",
1146+
_taskMode: "code",
1147+
emit: vi.fn(),
1148+
saveClineMessages: vi.fn(),
1149+
clineMessages: [],
1150+
apiConversationHistory: [],
1151+
updateApiConfiguration: vi.fn(),
1152+
} as Partial<Task>,
1153+
)
1154+
const historyItem: HistoryItem = {
1155+
id: "test-task-id",
1156+
ts: Date.now(),
1157+
task: "Test task",
1158+
mode: "code",
1159+
number: 1,
1160+
tokensIn: 0,
1161+
tokensOut: 0,
1162+
cacheWrites: 0,
1163+
cacheReads: 0,
1164+
totalCost: 0,
1165+
}
1166+
vi.spyOn(provider.taskHistoryStore, "get").mockReturnValue(historyItem)
1167+
const updateTaskHistorySpy = vi.spyOn(provider, "updateTaskHistory").mockResolvedValue([])
1168+
await provider.saveViewState("mode", "code")
1169+
await provider.contextProxy.setValue("mode", "code")
1170+
1171+
// The activation writes the activated profile and only then rejects: the catch
1172+
// keeps the switch, and listeners plus the webview must still learn the
1173+
// committed mode before the error surfaces.
1174+
vi.spyOn(provider.providerSettingsManager, "getModeConfigId").mockResolvedValue("architect-profile-id")
1175+
vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([
1176+
{ id: "architect-profile-id", name: "architect-profile", apiProvider: providerIdentifiers.openrouter },
1177+
])
1178+
vi.spyOn(provider.providerSettingsManager, "getProfile").mockResolvedValue({
1179+
name: "architect-profile",
1180+
id: "architect-profile-id",
1181+
apiProvider: providerIdentifiers.openrouter,
1182+
})
1183+
const emitSpy = vi.spyOn(provider, "emit")
1184+
const postSpy = vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined)
1185+
provider["activateProviderProfileUnlocked"] = vi.fn().mockImplementation(async (_args, options) => {
1186+
options?.onSharedWriteStart?.()
1187+
await provider.contextProxy.setValue("currentApiConfigName", "architect-profile")
1188+
throw new Error("activation step failed")
1189+
})
1190+
await provider.addClineToStack(mockTask)
1191+
1192+
await expect(provider["handleModeSwitchUnlocked"]("architect", mockTask)).rejects.toThrow(
1193+
"activation step failed",
1194+
)
1195+
1196+
expect(emitSpy).toHaveBeenCalledWith("modeChanged", "architect")
1197+
expect(postSpy).toHaveBeenCalled()
1198+
expect(provider.getValue("mode")).toBe("architect")
1199+
})
1200+
1201+
it("reports the committed mode when the signal aborts after the mode writes", async () => {
1202+
// Same typed double as the activation-failure rollback test above.
1203+
const mockTask = Object.assign(
1204+
{} as Task,
1205+
{
1206+
taskId: "test-task-id",
1207+
taskMode: "code",
1208+
_taskMode: "code",
1209+
emit: vi.fn(),
1210+
saveClineMessages: vi.fn(),
1211+
clineMessages: [],
1212+
apiConversationHistory: [],
1213+
updateApiConfiguration: vi.fn(),
1214+
} as Partial<Task>,
1215+
)
1216+
const historyItem: HistoryItem = {
1217+
id: "test-task-id",
1218+
ts: Date.now(),
1219+
task: "Test task",
1220+
mode: "code",
1221+
number: 1,
1222+
tokensIn: 0,
1223+
tokensOut: 0,
1224+
cacheWrites: 0,
1225+
cacheReads: 0,
1226+
totalCost: 0,
1227+
}
1228+
vi.spyOn(provider.taskHistoryStore, "get").mockReturnValue(historyItem)
1229+
const updateTaskHistorySpy = vi.spyOn(provider, "updateTaskHistory").mockResolvedValue([])
1230+
await provider.saveViewState("mode", "code")
1231+
await provider.contextProxy.setValue("mode", "code")
1232+
1233+
// The pin and shared mode writes land, then the mutation signal aborts during
1234+
// the activation reads. The activation is skipped, but the committed mode
1235+
// must still reach listeners and the webview through the emit/post tail.
1236+
const emitSpy = vi.spyOn(provider, "emit")
1237+
const postSpy = vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined)
1238+
const controller = new AbortController()
1239+
vi.spyOn(provider.providerSettingsManager, "getModeConfigId").mockImplementation(async () => {
1240+
controller.abort()
1241+
return undefined
1242+
})
1243+
vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([])
1244+
await provider.addClineToStack(mockTask)
1245+
1246+
await provider["handleModeSwitchUnlocked"]("architect", mockTask, controller.signal)
1247+
1248+
expect(provider.getValue("mode")).toBe("architect")
1249+
expect(emitSpy).toHaveBeenCalledWith("modeChanged", "architect")
1250+
expect(postSpy).toHaveBeenCalled()
1251+
})
1252+
10761253
it("keeps the cancellation result when the abort rollback write itself fails", async () => {
10771254
const mockTask = Object.assign(
10781255
{} as Task,

0 commit comments

Comments
 (0)