Skip to content

Commit 1971923

Browse files
fix(webview): keep the view overlay consistent with the pin on a failed activation write
activateProviderProfileUnlocked clears this view's apiConfiguration overlay in the same Promise.all as the shared settings write, so a partial failure left the view holding the activated profile's pin with no overlay at all: getState() then paired the new name with whatever the shared store held, out of step with the handler the failure path had just force-rebuilt. The legs are not atomic with each other, so the failure path now decides after every leg has settled - allSettled rather than all, matching upsertProviderProfile - and puts the overlay in the state that agrees with the pin this view actually holds: the activated settings when the pin write took the new name, which is the invariant refreshViewLocalStateForUpdatedProfile enforces on the success path and the configuration the rebuild handed the task, and otherwise the overlay captured before the switch. Covered on both rejecting legs: the provider-settings leg, where both existing cases now assert the reported name against the reported settings, and the pin leg, added as its own case. Without the restore the three assertions fail (38/41); with it 41/41, and the ClineProvider, sticky-profile, sticky-mode, parallelMode, webviewMessageHandler, api-configuration, ContextProxy and registerCommands suites pass unchanged.
1 parent cf80e4b commit 1971923

2 files changed

Lines changed: 119 additions & 16 deletions

File tree

‎src/core/webview/ClineProvider.ts‎

Lines changed: 38 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -3779,21 +3779,31 @@ export class ClineProvider
37793779
// settings into their overlays first.
37803780
await this.snapshotSiblingOverlaysBeforeSharedSettingsWrite(name)
37813781

3782-
try {
3783-
await Promise.all([
3784-
this.contextProxy.setValue("listApiConfigMeta", listApiConfigMeta),
3785-
// Route through setValue so the in-memory viewLocalState buffer tracks the
3786-
// activated profile: a plain ContextProxy write would leave a stale loaded
3787-
// currentApiConfigName shadowing the new value in getValues().
3788-
this.setValue("currentApiConfigName", name),
3789-
this.contextProxy.setProviderSettings(providerSettings),
3790-
// setProviderSettings writes the shared store directly, bypassing the
3791-
// view-local mutation path: clear this view's buffered apiConfiguration
3792-
// overlay (if any) so a stale loaded profile cannot keep shadowing the
3793-
// new settings in getState().
3794-
this._saveViewLocalStateFromMutation({ apiConfiguration: undefined }),
3795-
])
3796-
} catch (error) {
3782+
// The overlay this view holds before the shared write below. The failure path restores it when
3783+
// the pin never took the activated name; the success path overwrites it either way.
3784+
const previousViewApiConfiguration = this.viewLocalState.apiConfiguration
3785+
3786+
// `allSettled` rather than `all` so the failure path below cannot observe the pin mid-race:
3787+
// a rejection must not return while another leg is still in flight, because the decision about
3788+
// this view's overlay depends on whether the pin write landed.
3789+
const sharedWriteResults = await Promise.allSettled([
3790+
this.contextProxy.setValue("listApiConfigMeta", listApiConfigMeta),
3791+
// Route through setValue so the in-memory viewLocalState buffer tracks the
3792+
// activated profile: a plain ContextProxy write would leave a stale loaded
3793+
// currentApiConfigName shadowing the new value in getValues().
3794+
this.setValue("currentApiConfigName", name),
3795+
this.contextProxy.setProviderSettings(providerSettings),
3796+
// setProviderSettings writes the shared store directly, bypassing the
3797+
// view-local mutation path: clear this view's buffered apiConfiguration
3798+
// overlay (if any) so a stale loaded profile cannot keep shadowing the
3799+
// new settings in getState().
3800+
this._saveViewLocalStateFromMutation({ apiConfiguration: undefined }),
3801+
])
3802+
const failedSharedWrite = sharedWriteResults.find(
3803+
(result): result is PromiseRejectedResult => result.status === "rejected",
3804+
)
3805+
3806+
if (failedSharedWrite) {
37973807
// The manager has already written the activated profile, so the caller keeps the
37983808
// switch and delivers its pending message now. The task must run the activated
37993809
// profile's settings: without this rebuild the handler still belongs to the profile
@@ -3802,7 +3812,19 @@ export class ClineProvider
38023812
forceRebuild: true,
38033813
expectedCurrentTaskId: options?.expectedCurrentTaskId,
38043814
})
3805-
throw error
3815+
3816+
// The legs above are not atomic with each other, so which half of the shared write landed
3817+
// is not knowable here. Put the overlay in the state that agrees with the pin this view
3818+
// actually holds now that every leg has settled: the activated settings when the pin took
3819+
// the new name (the same invariant refreshViewLocalStateForUpdatedProfile enforces on the
3820+
// success path, and the configuration the rebuild above handed the task), and otherwise the
3821+
// overlay this view held before the switch - pinning the activated settings under a name
3822+
// write that never landed would create the same mismatch in the other direction.
3823+
await this._saveViewLocalStateFromMutation({
3824+
apiConfiguration: this.pinnedProfileName === name ? providerSettings : previousViewApiConfiguration,
3825+
})
3826+
3827+
throw failedSharedWrite.reason
38063828
}
38073829

38083830
// Other live views may have buffered this profile's settings earlier;

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

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1077,6 +1077,17 @@ describe("ClineProvider - API Handler Rebuild Guard", () => {
10771077
expect(saveViewStateSpy).not.toHaveBeenCalledWith("mode", modeBeforeSwitch)
10781078
// Listeners must learn the committed mode before the error is rethrown.
10791079
expect(emitSpy).toHaveBeenCalledWith(RooCodeEventName.ModeChanged, "ask")
1080+
1081+
// getState() must not pair the profile the activation committed with the settings the failed
1082+
// shared write left behind: the pin took the new name, so this view overlay has to carry the
1083+
// activated profile settings - the same invariant the success path enforces through
1084+
// refreshViewLocalStateForUpdatedProfile, and the configuration the rebuild above handed
1085+
// the task.
1086+
const stateAfterFailure = await provider.getState()
1087+
expect(stateAfterFailure.currentApiConfigName).toBe("ask-profile")
1088+
expect(stateAfterFailure.apiConfiguration).toMatchObject({
1089+
openRouterModelId: "openai/gpt-4.1-mini",
1090+
})
10801091
})
10811092

10821093
test("rebuilds the task handler on a failed shared write when provider and model are unchanged", async () => {
@@ -1126,6 +1137,76 @@ describe("ClineProvider - API Handler Rebuild Guard", () => {
11261137
expect((mockTask as { apiConfiguration?: ProviderSettings }).apiConfiguration?.openRouterApiKey).toBe(
11271138
"activated-key",
11281139
)
1140+
1141+
// Same rule for the credentials case: the handler runs the activated profile key, so the
1142+
// state the webview reads under the committed pin must report it too.
1143+
const stateAfterFailure = await provider.getState()
1144+
expect(stateAfterFailure.currentApiConfigName).toBe("ask-profile")
1145+
expect(stateAfterFailure.apiConfiguration).toMatchObject({
1146+
openRouterApiKey: "activated-key",
1147+
rateLimitSeconds: 7,
1148+
})
1149+
})
1150+
1151+
// Mirror case for the same failure path: the leg that rejects is the pin write itself, not
1152+
// the provider-settings write. The activation still stands for the task, but this view never
1153+
// took the new name, so its overlay must go back to what it held before the switch -
1154+
// pinning the activated settings under a name that never landed would create the same
1155+
// mismatch in the other direction.
1156+
test("restores the previous overlay when the pin write fails after activation", async () => {
1157+
const mockTask = new Task({
1158+
...defaultTaskOptions,
1159+
apiConfiguration: {
1160+
apiProvider: providerIdentifiers.openrouter,
1161+
openRouterModelId: "openai/gpt-4",
1162+
openRouterApiKey: "task-key",
1163+
},
1164+
})
1165+
await provider.addClineToStack(mockTask)
1166+
provider["providerSettingsManager"].getModeConfigId = vi.fn().mockResolvedValue("ask-id")
1167+
provider["providerSettingsManager"].listConfig = vi
1168+
.fn()
1169+
.mockResolvedValue([{ name: "ask-profile", id: "ask-id", apiProvider: providerIdentifiers.openrouter }])
1170+
const activatedProfile = {
1171+
name: "ask-profile",
1172+
id: "ask-id",
1173+
apiProvider: providerIdentifiers.openrouter,
1174+
openRouterModelId: "openai/gpt-4",
1175+
openRouterApiKey: "activated-key",
1176+
rateLimitSeconds: 7,
1177+
}
1178+
provider["providerSettingsManager"].getProfile = vi.fn().mockResolvedValue(activatedProfile)
1179+
provider["providerSettingsManager"].activateProfile = vi.fn().mockResolvedValue(activatedProfile)
1180+
// The pin and overlay this view held before the switch.
1181+
const profileNameBeforeSwitch = (await provider.getState()).currentApiConfigName
1182+
const pinBeforeSwitch = provider.pinnedProfileName
1183+
await provider.saveViewState("apiConfiguration", {
1184+
apiProvider: providerIdentifiers.openrouter,
1185+
openRouterModelId: "openai/gpt-4",
1186+
openRouterApiKey: "overlay-before",
1187+
})
1188+
const contextProxySetValue = provider.contextProxy.setValue.bind(provider.contextProxy)
1189+
vi.spyOn(provider.contextProxy, "setValue").mockImplementation((key, value) =>
1190+
key === "currentApiConfigName"
1191+
? Promise.reject(new Error("pin write failed"))
1192+
: contextProxySetValue(key, value),
1193+
)
1194+
vi.spyOn(provider.contextProxy, "setProviderSettings").mockResolvedValue(undefined)
1195+
1196+
await expect(provider.handleModeSwitch("ask" as Mode, undefined)).rejects.toThrow("pin write failed")
1197+
1198+
// The task still runs the activated profile: the keep-the-switch rebuild is not gated on the
1199+
// pin write.
1200+
expect(mockTask.updateApiConfiguration).toHaveBeenCalledWith(
1201+
expect.objectContaining({ openRouterApiKey: "activated-key" }),
1202+
)
1203+
// And this view still reports its own profile with its own settings: the overlay the failure
1204+
// path cleared is back, not the activated profile settings, and not the shared store copy
1205+
// that the successful provider-settings write left behind.
1206+
expect(provider.pinnedProfileName).toBe(pinBeforeSwitch)
1207+
const stateAfterFailure = await provider.getState()
1208+
expect(stateAfterFailure.currentApiConfigName).toBe(profileNameBeforeSwitch)
1209+
expect(stateAfterFailure.apiConfiguration).toMatchObject({ openRouterApiKey: "overlay-before" })
11291210
})
11301211

11311212
test("calls updateApiConfiguration when provider/model unchanged but settings differ (explicit profile switch)", async () => {

0 commit comments

Comments
 (0)