Skip to content

Commit 3c454e5

Browse files
committed
fix(webview): commit the mode-switch guard at the activation write
1 parent 8fbce54 commit 3c454e5

2 files changed

Lines changed: 257 additions & 37 deletions

File tree

‎src/core/webview/ClineProvider.ts‎

Lines changed: 77 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -2370,7 +2370,8 @@ export class ClineProvider
23702370
// emit/post tail outside the reconciled region.
23712371
const lockApiConfigAcrossModes = this.context.workspaceState.get("lockApiConfigAcrossModes", false)
23722372
if (!lockApiConfigAcrossModes) {
2373-
if (signal?.aborted) return
2373+
// A background-task switch applies to the task only: no view pin, no
2374+
// ModeChanged, and no mode-linked activation on its behalf.
23742375
if (!viewScopedSwitch) {
23752376
return
23762377
}
@@ -2379,50 +2380,59 @@ export class ClineProvider
23792380
const savedConfigId = await this.providerSettingsManager.getModeConfigId(newMode)
23802381
const listApiConfig = await this.providerSettingsManager.listConfig()
23812382

2382-
if (signal?.aborted) return
2383+
// The pin and shared mode writes above have committed the mode: an abort
2384+
// here skips the remaining activation work but falls through to the
2385+
// emit/post tail so listeners and the webview learn the committed mode.
2386+
if (!signal?.aborted) {
2387+
await this.updateGlobalState("listApiConfigMeta", listApiConfig)
23832388

2384-
// Update listApiConfigMeta first to ensure UI has latest data.
2385-
await this.updateGlobalState("listApiConfigMeta", listApiConfig)
2389+
// If this mode has a saved config, use it.
2390+
if (savedConfigId) {
2391+
const profile = listApiConfig.find(({ id }) => id === savedConfigId)
23862392

2387-
// If this mode has a saved config, use it.
2388-
if (savedConfigId) {
2389-
const profile = listApiConfig.find(({ id }) => id === savedConfigId)
2393+
if (profile?.name) {
2394+
// Check if the profile has actual API configuration (not just an id).
2395+
// In CLI mode, the ProviderSettingsManager may return empty default profiles
2396+
// that only contain 'id' and 'name' fields. Activating such a profile would
2397+
// overwrite the CLI's working API configuration with empty settings.
2398+
// Skip activation if the profile has no apiProvider set - this indicates
2399+
// an unconfigured/empty profile.
2400+
const fullProfile = await this.providerSettingsManager.getProfile({ name: profile.name })
2401+
const hasActualSettings = !!fullProfile.apiProvider
23902402

2391-
if (profile?.name) {
2392-
// Check if the profile has actual API configuration (not just an id).
2393-
// In CLI mode, the ProviderSettingsManager may return empty default profiles
2394-
// that only contain 'id' and 'name' fields. Activating such a profile would
2395-
// overwrite the CLI's working API configuration with empty settings.
2396-
// Skip activation if the profile has no apiProvider set - this indicates
2397-
// an unconfigured/empty profile.
2398-
const fullProfile = await this.providerSettingsManager.getProfile({ name: profile.name })
2399-
const hasActualSettings = !!fullProfile.apiProvider
2400-
2401-
if (hasActualSettings) {
2402-
activationStarted = true
2403-
await this.activateProviderProfileUnlocked(
2404-
{ name: profile.name },
2405-
targetTask === null ? { skipCurrentTaskRebuild: true } : undefined,
2406-
signal,
2407-
)
2403+
if (hasActualSettings) {
2404+
// The committed-switch guard flips only when the activation has
2405+
// actually written the activated profile: a lookup failure (e.g. a
2406+
// deleted profile) throws before any write and must still reconcile.
2407+
await this.activateProviderProfileUnlocked(
2408+
{ name: profile.name },
2409+
{
2410+
...(targetTask === null ? { skipCurrentTaskRebuild: true } : {}),
2411+
onSharedWriteStart: () => {
2412+
activationStarted = true
2413+
},
2414+
},
2415+
signal,
2416+
)
2417+
} else {
2418+
// The task will continue with the current/default configuration.
2419+
}
24082420
} else {
24092421
// The task will continue with the current/default configuration.
24102422
}
24112423
} else {
2412-
// The task will continue with the current/default configuration.
2413-
}
2414-
} else {
2415-
// If no saved config for this mode, save current config as default.
2416-
// Use this view's effective profile: with per-view pins the shared slot can
2417-
// belong to a sibling view, and recording that profile as this mode's default
2418-
// would activate the wrong profile for every later switch to it.
2419-
const currentApiConfigNameAfter = this.getValues().currentApiConfigName
2424+
// If no saved config for this mode, save current config as default.
2425+
// Use this view's effective profile: with per-view pins the shared slot can
2426+
// belong to a sibling view, and recording that profile as this mode's default
2427+
// would activate the wrong profile for every later switch to it.
2428+
const currentApiConfigNameAfter = this.getValues().currentApiConfigName
24202429

2421-
if (currentApiConfigNameAfter) {
2422-
const config = listApiConfig.find((c) => c.name === currentApiConfigNameAfter)
2430+
if (currentApiConfigNameAfter) {
2431+
const config = listApiConfig.find((c) => c.name === currentApiConfigNameAfter)
24232432

2424-
if (config?.id) {
2425-
await this.providerSettingsManager.setModeConfig(newMode, config.id)
2433+
if (config?.id) {
2434+
await this.providerSettingsManager.setModeConfig(newMode, config.id)
2435+
}
24262436
}
24272437
}
24282438
}
@@ -2436,7 +2446,30 @@ export class ClineProvider
24362446
if (!activationStarted && !signal?.aborted) {
24372447
await reconcileSwitchWrites()
24382448
} else if (signal?.aborted) {
2449+
// After an abort the mutation queue has advanced: a newer mutation may
2450+
// already own the mode fields, so emitting here could announce a mode the
2451+
// newer mutation replaced - listeners are intentionally not notified on
2452+
// this path.
24392453
this.log(`[handleModeSwitch] Skipping rollback for aborted switch to "${newMode}"`)
2454+
} else {
2455+
// The activation had already written the activated profile: the switch is
2456+
// kept. Listeners must still learn the committed mode before the rethrow,
2457+
// and the webview must refresh in case the activation failed before its
2458+
// own state post.
2459+
if (viewScopedSwitch) {
2460+
this.emit(RooCodeEventName.ModeChanged, newMode)
2461+
}
2462+
if (targetTask !== null) {
2463+
try {
2464+
await this.postStateToWebview()
2465+
} catch (postError: unknown) {
2466+
this.log(
2467+
`[handleModeSwitch] Mode switch to "${newMode}" kept but the state post failed: ${
2468+
postError instanceof Error ? postError.message : String(postError)
2469+
}`,
2470+
)
2471+
}
2472+
}
24402473
}
24412474
this.log(
24422475
`[handleModeSwitch] Failed to persist mode "${newMode}": ${error instanceof Error ? error.message : String(error)}`,
@@ -2855,11 +2888,19 @@ export class ClineProvider
28552888
persistModeConfig?: boolean
28562889
persistTaskHistory?: boolean
28572890
skipCurrentTaskRebuild?: boolean
2891+
// Fires once the activation has written the activated profile to shared
2892+
// state, so callers can mark the switch committed at the true point of no
2893+
// return (a profile lookup failure must stay reconcilable).
2894+
onSharedWriteStart?: () => void
28582895
},
28592896
signal?: AbortSignal,
28602897
): Promise<void> {
28612898
const { name, id, ...providerSettings } = await this.providerSettingsManager.activateProfile(args)
28622899

2900+
// The manager has now written the activated profile: from here on a failure
2901+
// must keep the switch rather than roll the mode back onto the old profile.
2902+
options?.onSharedWriteStart?.()
2903+
28632904
if (signal?.aborted) return
28642905

28652906
const persistModeConfig = options?.persistModeConfig ?? true

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

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

0 commit comments

Comments
 (0)