Skip to content

Commit 0855f89

Browse files
committed
fix(webview): make mode-switch failures atomic and scope profile-save task rebuilds
Port of the sibling-unit fixes: handleModeSwitchUnlocked reconciles every write it owns (shared mode, view mode pin, task mode, task history) when a failure lands after the task-mode write, including the mode-linked profile activation, so submitUserMessage delivers on the pre-switch mode and profile. Non-activating profile saves only force-rebuild a view's task handler when the task actually runs under the saved profile. Regression tests for the activation-failure rollback and both rebuild guards. Test hygiene: prune assertions compare full kept entries; re-key storage tests seed through the durable write path so assertions can fail; sticky-mode afterEach disposes the per-test provider before resetting the instance registry; webview state-payload test renamed.
1 parent 8fb1532 commit 0855f89

4 files changed

Lines changed: 306 additions & 108 deletions

File tree

‎src/core/webview/ClineProvider.ts‎

Lines changed: 132 additions & 94 deletions
Original file line numberDiff line numberDiff line change
@@ -2353,40 +2353,26 @@ export class ClineProvider
23532353
// mode, broadcasting ModeChanged, or activating a profile on behalf of a
23542354
// background task would clobber the focused task's selection.
23552355
const viewScopedSwitch = task === undefined || task === null || this.getCurrentTask() === task
2356-
if (viewScopedSwitch) {
2357-
// Pin the view's durable per-view mode first: the pin is this view's own
2358-
// selection and must not be undone if the shared write later fails.
2359-
// If the pin write itself fails, the task-side writes above are already
2360-
// applied: roll them back before rethrowing so the caller cannot deliver
2361-
// the message with the new task mode while the view's mode and mode-linked
2362-
// API configuration stayed old.
2363-
try {
2364-
await this.saveViewState("mode", newMode)
2365-
} catch (error) {
2366-
if (rollbackTaskWrites) {
2367-
try {
2368-
await rollbackTaskWrites()
2369-
} catch (rollbackError) {
2370-
this.log(
2371-
`[handleModeSwitch] Failed to roll back task mode writes after the view mode pin write failed: ${
2372-
rollbackError instanceof Error ? rollbackError.message : String(rollbackError)
2373-
}`,
2374-
)
2375-
}
2376-
}
2377-
throw error
2378-
}
2379-
2380-
// setValue (not the deprecated updateGlobalState) so the in-memory viewLocalState
2381-
// buffer stays in sync with the durable global write: getValues() merges
2382-
// viewLocalState on top of the ContextProxy values, so an unsynced stale
2383-
// restored mode would otherwise shadow the fresh switch for consumers.
2384-
// If the durable write fails, roll the shared write back so getValues()
2385-
// cannot mix a fresh shared mode with the stale pre-switch buffer.
2386-
const previousMode = this.getValue("mode")
2387-
try {
2388-
await this.setValue("mode", newMode)
2389-
} catch (error) {
2356+
// Captured for the reconcile below: the view's pre-switch durable mode pin
2357+
// (undefined means the view never pinned a mode) and the pre-switch shared
2358+
// mode. The pin write only touches the view buffer and the per-view store, so
2359+
// reading the shared value here is unaffected by it.
2360+
const previousViewMode = this.viewLocalState.mode
2361+
const previousMode = this.getValue("mode")
2362+
let pinLanded = false
2363+
let sharedAttempted = false
2364+
2365+
// Explicit partial-failure behavior: every failure after the task-mode write
2366+
// rolls back all writes this switch owns - shared mode, view pin, task mode,
2367+
// and the task-history entry - so the caller (Task#submitUserMessage) delivers
2368+
// the submitted message on the pre-switch mode and profile instead of a
2369+
// half-applied switch that runs the new mode against the unchanged profile.
2370+
// Each restore is awaited on its own and logged on failure, never swallowed.
2371+
const reconcileSwitchWrites = async () => {
2372+
if (sharedAttempted) {
2373+
// The shared write may have landed before its promise rejected: restore
2374+
// it unconditionally so getValues() cannot mix a fresh shared mode with
2375+
// the rolled-back view state.
23902376
try {
23912377
await this.contextProxy.setValue("mode", previousMode)
23922378
} catch (rollbackError) {
@@ -2396,81 +2382,123 @@ export class ClineProvider
23962382
}`,
23972383
)
23982384
}
2399-
this.log(
2400-
`[handleModeSwitch] Failed to persist mode "${newMode}": ${error instanceof Error ? error.message : String(error)}`,
2401-
)
2402-
throw error
24032385
}
2404-
2405-
this.emit(RooCodeEventName.ModeChanged, newMode)
2386+
if (pinLanded) {
2387+
try {
2388+
await this.saveViewState("mode", previousViewMode)
2389+
} catch (rollbackError) {
2390+
this.log(
2391+
`[handleModeSwitch] Failed to roll back the view mode pin after persistence failure: ${
2392+
rollbackError instanceof Error ? rollbackError.message : String(rollbackError)
2393+
}`,
2394+
)
2395+
}
2396+
}
2397+
if (rollbackTaskWrites) {
2398+
try {
2399+
await rollbackTaskWrites()
2400+
} catch (rollbackError) {
2401+
this.log(
2402+
`[handleModeSwitch] Failed to roll back task mode writes after the view mode pin write failed: ${
2403+
rollbackError instanceof Error ? rollbackError.message : String(rollbackError)
2404+
}`,
2405+
)
2406+
}
2407+
}
24062408
}
24072409

2408-
// If workspace lock is on, keep the current API config — don't load mode-specific config
2409-
const lockApiConfigAcrossModes = this.context.workspaceState.get("lockApiConfigAcrossModes", false)
2410-
if (lockApiConfigAcrossModes) {
2411-
// Keep the original post semantics: an explicit null target (pending child)
2412-
// posts its own state.
2413-
if (targetTask !== null) {
2414-
await this.postStateToWebview()
2410+
try {
2411+
if (viewScopedSwitch) {
2412+
// Pin the view's durable per-view mode first: the pin is this view's own
2413+
// selection. If any write below fails, the reconcile above restores every
2414+
// write that landed, including this pin, so a delivered message never runs
2415+
// the new task mode against an unchanged view mode or mode-linked profile.
2416+
await this.saveViewState("mode", newMode)
2417+
pinLanded = true
2418+
2419+
// setValue (not the deprecated updateGlobalState) so the in-memory viewLocalState
2420+
// buffer stays in sync with the durable global write: getValues() merges
2421+
// viewLocalState on top of the ContextProxy values, so an unsynced stale
2422+
// restored mode would otherwise shadow the fresh switch for consumers.
2423+
sharedAttempted = true
2424+
await this.setValue("mode", newMode)
2425+
2426+
this.emit(RooCodeEventName.ModeChanged, newMode)
24152427
}
2416-
return
2417-
}
24182428

2419-
if (signal?.aborted) return
2420-
if (!viewScopedSwitch) {
2421-
return
2422-
}
2429+
// If workspace lock is on, keep the current API config — don't load mode-specific config
2430+
const lockApiConfigAcrossModes = this.context.workspaceState.get("lockApiConfigAcrossModes", false)
2431+
if (lockApiConfigAcrossModes) {
2432+
// Keep the original post semantics: an explicit null target (pending child)
2433+
// posts its own state.
2434+
if (targetTask !== null) {
2435+
await this.postStateToWebview()
2436+
}
2437+
return
2438+
}
24232439

2424-
// Load the saved API config for the new mode if it exists.
2425-
const savedConfigId = await this.providerSettingsManager.getModeConfigId(newMode)
2426-
const listApiConfig = await this.providerSettingsManager.listConfig()
2440+
if (signal?.aborted) return
2441+
if (!viewScopedSwitch) {
2442+
return
2443+
}
24272444

2428-
if (signal?.aborted) return
2445+
// Load the saved API config for the new mode if it exists.
2446+
const savedConfigId = await this.providerSettingsManager.getModeConfigId(newMode)
2447+
const listApiConfig = await this.providerSettingsManager.listConfig()
24292448

2430-
// Update listApiConfigMeta first to ensure UI has latest data.
2431-
await this.updateGlobalState("listApiConfigMeta", listApiConfig)
2449+
if (signal?.aborted) return
24322450

2433-
// If this mode has a saved config, use it.
2434-
if (savedConfigId) {
2435-
const profile = listApiConfig.find(({ id }) => id === savedConfigId)
2451+
// Update listApiConfigMeta first to ensure UI has latest data.
2452+
await this.updateGlobalState("listApiConfigMeta", listApiConfig)
24362453

2437-
if (profile?.name) {
2438-
// Check if the profile has actual API configuration (not just an id).
2439-
// In CLI mode, the ProviderSettingsManager may return empty default profiles
2440-
// that only contain 'id' and 'name' fields. Activating such a profile would
2441-
// overwrite the CLI's working API configuration with empty settings.
2442-
// Skip activation if the profile has no apiProvider set - this indicates
2443-
// an unconfigured/empty profile.
2444-
const fullProfile = await this.providerSettingsManager.getProfile({ name: profile.name })
2445-
const hasActualSettings = !!fullProfile.apiProvider
2446-
2447-
if (hasActualSettings) {
2448-
await this.activateProviderProfileUnlocked(
2449-
{ name: profile.name },
2450-
targetTask === null ? { skipCurrentTaskRebuild: true } : undefined,
2451-
signal,
2452-
)
2454+
// If this mode has a saved config, use it.
2455+
if (savedConfigId) {
2456+
const profile = listApiConfig.find(({ id }) => id === savedConfigId)
2457+
2458+
if (profile?.name) {
2459+
// Check if the profile has actual API configuration (not just an id).
2460+
// In CLI mode, the ProviderSettingsManager may return empty default profiles
2461+
// that only contain 'id' and 'name' fields. Activating such a profile would
2462+
// overwrite the CLI's working API configuration with empty settings.
2463+
// Skip activation if the profile has no apiProvider set - this indicates
2464+
// an unconfigured/empty profile.
2465+
const fullProfile = await this.providerSettingsManager.getProfile({ name: profile.name })
2466+
const hasActualSettings = !!fullProfile.apiProvider
2467+
2468+
if (hasActualSettings) {
2469+
await this.activateProviderProfileUnlocked(
2470+
{ name: profile.name },
2471+
targetTask === null ? { skipCurrentTaskRebuild: true } : undefined,
2472+
signal,
2473+
)
2474+
} else {
2475+
// The task will continue with the current/default configuration.
2476+
}
24532477
} else {
24542478
// The task will continue with the current/default configuration.
24552479
}
24562480
} else {
2457-
// The task will continue with the current/default configuration.
2458-
}
2459-
} else {
2460-
// If no saved config for this mode, save current config as default.
2461-
const currentApiConfigNameAfter = this.getGlobalState("currentApiConfigName")
2481+
// If no saved config for this mode, save current config as default.
2482+
const currentApiConfigNameAfter = this.getGlobalState("currentApiConfigName")
24622483

2463-
if (currentApiConfigNameAfter) {
2464-
const config = listApiConfig.find((c) => c.name === currentApiConfigNameAfter)
2484+
if (currentApiConfigNameAfter) {
2485+
const config = listApiConfig.find((c) => c.name === currentApiConfigNameAfter)
24652486

2466-
if (config?.id) {
2467-
await this.providerSettingsManager.setModeConfig(newMode, config.id)
2487+
if (config?.id) {
2488+
await this.providerSettingsManager.setModeConfig(newMode, config.id)
2489+
}
24682490
}
24692491
}
2470-
}
24712492

2472-
if (targetTask !== null) {
2473-
await this.postStateToWebview()
2493+
if (targetTask !== null) {
2494+
await this.postStateToWebview()
2495+
}
2496+
} catch (error) {
2497+
await reconcileSwitchWrites()
2498+
this.log(
2499+
`[handleModeSwitch] Failed to persist mode "${newMode}": ${error instanceof Error ? error.message : String(error)}`,
2500+
)
2501+
throw error
24742502
}
24752503
}
24762504

@@ -2603,7 +2631,13 @@ export class ClineProvider
26032631
// serving the settings captured before the save under the same name.
26042632
if (this.pinnedProfileName === name) {
26052633
await this._saveViewLocalStateFromMutation({ apiConfiguration: providerSettings })
2606-
this.updateTaskApiHandlerIfNeeded(providerSettings, { forceRebuild: true })
2634+
// Only rebuild when the task actually runs under the saved profile: a
2635+
// view pinned to this profile can hold a task that follows a different
2636+
// sticky profile, and the forced rebuild would silently switch that
2637+
// conversation to the saved profile's settings.
2638+
if (this.getCurrentTask()?.taskApiConfigName === name) {
2639+
this.updateTaskApiHandlerIfNeeded(providerSettings, { forceRebuild: true })
2640+
}
26072641
}
26082642
await this.refreshViewLocalStateForUpdatedProfile(name, providerSettings)
26092643
}
@@ -2957,9 +2991,13 @@ export class ClineProvider
29572991
// The active task of a pinned view holds its own API handler built from
29582992
// the profile's settings: rebuild it with the saved settings or the
29592993
// running conversation keeps sending the old token even though the
2960-
// view's buffer has caught up. Direct private access across sibling
2961-
// instances of the same class is compile-time safe.
2962-
instance.updateTaskApiHandlerIfNeeded(providerSettings, { forceRebuild: true })
2994+
// view's buffer has caught up. Only rebuild when the task actually runs
2995+
// under the saved profile: a task that follows a different sticky
2996+
// profile must keep its own settings. Direct private access across
2997+
// sibling instances of the same class is compile-time safe.
2998+
if (instance.getCurrentTask()?.taskApiConfigName === name) {
2999+
instance.updateTaskApiHandlerIfNeeded(providerSettings, { forceRebuild: true })
3000+
}
29633001
await instance.postStateToWebview()
29643002
}),
29653003
)

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

Lines changed: 98 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1928,8 +1928,8 @@ describe("ClineProvider", () => {
19281928
const pruned = provider["prunePersistedViewStates"](states)
19291929

19301930
expect(Object.keys(pruned)).toHaveLength(50)
1931-
expect(pruned["view-54"]).toBeDefined()
1932-
expect(pruned["view-5"]).toBeDefined()
1931+
expect(pruned["view-54"]).toEqual({ mode: "mode-54", updatedAt: 54 })
1932+
expect(pruned["view-5"]).toEqual({ mode: "mode-5", updatedAt: 5 })
19331933
expect(pruned["view-4"]).toBeUndefined()
19341934

19351935
await provider.dispose()
@@ -8734,6 +8734,7 @@ describe("ClineProvider - Comprehensive Edit/Delete Edge Cases", () => {
87348734
// minimal double without the full provider/services graph.
87358735
const siblingTask = {
87368736
apiConfiguration: { apiProvider: providerIdentifiers.anthropic, apiKey: "old-key" },
8737+
taskApiConfigName: "saved-profile",
87378738
updateApiConfiguration: vi.fn(),
87388739
}
87398740
vi.spyOn(sibling, "getCurrentTask").mockReturnValue(
@@ -8774,6 +8775,101 @@ describe("ClineProvider - Comprehensive Edit/Delete Edge Cases", () => {
87748775
}
87758776
})
87768777

8778+
it("does not rebuild a pinned sibling's task that runs under another profile", async () => {
8779+
// Defensive: the doubles in this suite can leave console writes pending
8780+
// at worker teardown.
8781+
vi.spyOn(console, "log").mockImplementation(() => {})
8782+
vi.spyOn(console, "warn").mockImplementation(() => {})
8783+
vi.spyOn(console, "error").mockImplementation(() => {})
8784+
const sibling = new ClineProvider(
8785+
mockContext,
8786+
mockOutputChannel,
8787+
"editor",
8788+
new ContextProxy(mockContext),
8789+
new WebviewFocusTracker(),
8790+
)
8791+
try {
8792+
// The sibling pins the saved profile, but its active task follows a
8793+
// different sticky profile: the save must refresh the view overlay
8794+
// without switching that conversation to the saved profile's settings.
8795+
sibling["viewLocalState"].currentApiConfigName = "saved-profile"
8796+
sibling["viewLocalState"].apiConfiguration = {
8797+
apiProvider: providerIdentifiers.anthropic,
8798+
apiKey: "old-key",
8799+
}
8800+
vi.spyOn(sibling, "postStateToWebview").mockResolvedValue(undefined)
8801+
8802+
const siblingTask = {
8803+
apiConfiguration: { apiProvider: providerIdentifiers.anthropic, apiKey: "other-key" },
8804+
taskApiConfigName: "other-profile",
8805+
updateApiConfiguration: vi.fn(),
8806+
}
8807+
vi.spyOn(sibling, "getCurrentTask").mockReturnValue(
8808+
siblingTask as unknown as ReturnType<typeof sibling.getCurrentTask>,
8809+
)
8810+
vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined)
8811+
// @ts-ignore - Replace providerSettingsManager with a test double.
8812+
provider.providerSettingsManager = {
8813+
saveConfig: vi.fn().mockResolvedValue("saved-id"),
8814+
listConfig: vi.fn().mockResolvedValue([]),
8815+
setModeConfig: vi.fn(),
8816+
}
8817+
8818+
await provider.upsertProviderProfile(
8819+
"saved-profile",
8820+
{ apiProvider: providerIdentifiers.anthropic, apiKey: "new-key" },
8821+
false,
8822+
)
8823+
8824+
// The pinned view's overlay still catches up with the saved settings...
8825+
expect(sibling["viewLocalState"].apiConfiguration).toEqual({
8826+
apiProvider: providerIdentifiers.anthropic,
8827+
apiKey: "new-key",
8828+
})
8829+
// ...but the task runs under another profile: its handler must not be
8830+
// switched to the saved profile's settings.
8831+
expect(siblingTask.updateApiConfiguration).not.toHaveBeenCalled()
8832+
// Let queued view-local persistence settle while the console spies are
8833+
// still installed, so teardown has no pending writes.
8834+
await new Promise((resolve) => setTimeout(resolve, 50))
8835+
} finally {
8836+
await sibling.dispose()
8837+
}
8838+
})
8839+
8840+
it("does not rebuild the acting view's task when it runs under another profile", async () => {
8841+
// The acting view pins the saved profile while its own task follows a
8842+
// different sticky profile: the non-activating save refreshes the view
8843+
// overlay but must leave the task's handler alone.
8844+
const task = {
8845+
apiConfiguration: { apiProvider: providerIdentifiers.anthropic, apiKey: "other-key" },
8846+
taskApiConfigName: "other-profile",
8847+
updateApiConfiguration: vi.fn(),
8848+
}
8849+
vi.spyOn(provider, "getCurrentTask").mockReturnValue(
8850+
task as unknown as ReturnType<typeof provider.getCurrentTask>,
8851+
)
8852+
vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined)
8853+
provider["viewLocalState"].currentApiConfigName = "saved-profile"
8854+
// @ts-ignore - Replace providerSettingsManager with a test double.
8855+
provider.providerSettingsManager = {
8856+
saveConfig: vi.fn().mockResolvedValue("saved-id"),
8857+
listConfig: vi.fn().mockResolvedValue([]),
8858+
setModeConfig: vi.fn(),
8859+
}
8860+
8861+
await provider.upsertProviderProfile(
8862+
"saved-profile",
8863+
{ apiProvider: providerIdentifiers.anthropic, apiKey: "new-key" },
8864+
false,
8865+
)
8866+
8867+
expect(provider["viewLocalState"].apiConfiguration).toEqual({
8868+
apiProvider: providerIdentifiers.anthropic,
8869+
apiKey: "new-key",
8870+
})
8871+
expect(task.updateApiConfiguration).not.toHaveBeenCalled()
8872+
})
87778873
it("does not leak shared provider keys into a pinned view's api configuration", async () => {
87788874
vi.spyOn(console, "log").mockImplementation(() => {})
87798875
vi.spyOn(console, "warn").mockImplementation(() => {})

0 commit comments

Comments
 (0)