Skip to content

Commit 08c6fcb

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 390c0d4 commit 08c6fcb

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
@@ -2340,40 +2340,26 @@ export class ClineProvider
23402340
// mode, broadcasting ModeChanged, or activating a profile on behalf of a
23412341
// background task would clobber the focused task's selection.
23422342
const viewScopedSwitch = task === undefined || task === null || this.getCurrentTask() === task
2343-
if (viewScopedSwitch) {
2344-
// Pin the view's durable per-view mode first: the pin is this view's own
2345-
// selection and must not be undone if the shared write later fails.
2346-
// If the pin write itself fails, the task-side writes above are already
2347-
// applied: roll them back before rethrowing so the caller cannot deliver
2348-
// the message with the new task mode while the view's mode and mode-linked
2349-
// API configuration stayed old.
2350-
try {
2351-
await this.saveViewState("mode", newMode)
2352-
} catch (error) {
2353-
if (rollbackTaskWrites) {
2354-
try {
2355-
await rollbackTaskWrites()
2356-
} catch (rollbackError) {
2357-
this.log(
2358-
`[handleModeSwitch] Failed to roll back task mode writes after the view mode pin write failed: ${
2359-
rollbackError instanceof Error ? rollbackError.message : String(rollbackError)
2360-
}`,
2361-
)
2362-
}
2363-
}
2364-
throw error
2365-
}
2366-
2367-
// setValue (not the deprecated updateGlobalState) so the in-memory viewLocalState
2368-
// buffer stays in sync with the durable global write: getValues() merges
2369-
// viewLocalState on top of the ContextProxy values, so an unsynced stale
2370-
// restored mode would otherwise shadow the fresh switch for consumers.
2371-
// If the durable write fails, roll the shared write back so getValues()
2372-
// cannot mix a fresh shared mode with the stale pre-switch buffer.
2373-
const previousMode = this.getValue("mode")
2374-
try {
2375-
await this.setValue("mode", newMode)
2376-
} catch (error) {
2343+
// Captured for the reconcile below: the view's pre-switch durable mode pin
2344+
// (undefined means the view never pinned a mode) and the pre-switch shared
2345+
// mode. The pin write only touches the view buffer and the per-view store, so
2346+
// reading the shared value here is unaffected by it.
2347+
const previousViewMode = this.viewLocalState.mode
2348+
const previousMode = this.getValue("mode")
2349+
let pinLanded = false
2350+
let sharedAttempted = false
2351+
2352+
// Explicit partial-failure behavior: every failure after the task-mode write
2353+
// rolls back all writes this switch owns - shared mode, view pin, task mode,
2354+
// and the task-history entry - so the caller (Task#submitUserMessage) delivers
2355+
// the submitted message on the pre-switch mode and profile instead of a
2356+
// half-applied switch that runs the new mode against the unchanged profile.
2357+
// Each restore is awaited on its own and logged on failure, never swallowed.
2358+
const reconcileSwitchWrites = async () => {
2359+
if (sharedAttempted) {
2360+
// The shared write may have landed before its promise rejected: restore
2361+
// it unconditionally so getValues() cannot mix a fresh shared mode with
2362+
// the rolled-back view state.
23772363
try {
23782364
await this.contextProxy.setValue("mode", previousMode)
23792365
} catch (rollbackError) {
@@ -2383,81 +2369,123 @@ export class ClineProvider
23832369
}`,
23842370
)
23852371
}
2386-
this.log(
2387-
`[handleModeSwitch] Failed to persist mode "${newMode}": ${error instanceof Error ? error.message : String(error)}`,
2388-
)
2389-
throw error
23902372
}
2391-
2392-
this.emit(RooCodeEventName.ModeChanged, newMode)
2373+
if (pinLanded) {
2374+
try {
2375+
await this.saveViewState("mode", previousViewMode)
2376+
} catch (rollbackError) {
2377+
this.log(
2378+
`[handleModeSwitch] Failed to roll back the view mode pin after persistence failure: ${
2379+
rollbackError instanceof Error ? rollbackError.message : String(rollbackError)
2380+
}`,
2381+
)
2382+
}
2383+
}
2384+
if (rollbackTaskWrites) {
2385+
try {
2386+
await rollbackTaskWrites()
2387+
} catch (rollbackError) {
2388+
this.log(
2389+
`[handleModeSwitch] Failed to roll back task mode writes after the view mode pin write failed: ${
2390+
rollbackError instanceof Error ? rollbackError.message : String(rollbackError)
2391+
}`,
2392+
)
2393+
}
2394+
}
23932395
}
23942396

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

2406-
if (signal?.aborted) return
2407-
if (!viewScopedSwitch) {
2408-
return
2409-
}
2416+
// If workspace lock is on, keep the current API config — don't load mode-specific config
2417+
const lockApiConfigAcrossModes = this.context.workspaceState.get("lockApiConfigAcrossModes", false)
2418+
if (lockApiConfigAcrossModes) {
2419+
// Keep the original post semantics: an explicit null target (pending child)
2420+
// posts its own state.
2421+
if (targetTask !== null) {
2422+
await this.postStateToWebview()
2423+
}
2424+
return
2425+
}
24102426

2411-
// Load the saved API config for the new mode if it exists.
2412-
const savedConfigId = await this.providerSettingsManager.getModeConfigId(newMode)
2413-
const listApiConfig = await this.providerSettingsManager.listConfig()
2427+
if (signal?.aborted) return
2428+
if (!viewScopedSwitch) {
2429+
return
2430+
}
24142431

2415-
if (signal?.aborted) return
2432+
// Load the saved API config for the new mode if it exists.
2433+
const savedConfigId = await this.providerSettingsManager.getModeConfigId(newMode)
2434+
const listApiConfig = await this.providerSettingsManager.listConfig()
24162435

2417-
// Update listApiConfigMeta first to ensure UI has latest data.
2418-
await this.updateGlobalState("listApiConfigMeta", listApiConfig)
2436+
if (signal?.aborted) return
24192437

2420-
// If this mode has a saved config, use it.
2421-
if (savedConfigId) {
2422-
const profile = listApiConfig.find(({ id }) => id === savedConfigId)
2438+
// Update listApiConfigMeta first to ensure UI has latest data.
2439+
await this.updateGlobalState("listApiConfigMeta", listApiConfig)
24232440

2424-
if (profile?.name) {
2425-
// Check if the profile has actual API configuration (not just an id).
2426-
// In CLI mode, the ProviderSettingsManager may return empty default profiles
2427-
// that only contain 'id' and 'name' fields. Activating such a profile would
2428-
// overwrite the CLI's working API configuration with empty settings.
2429-
// Skip activation if the profile has no apiProvider set - this indicates
2430-
// an unconfigured/empty profile.
2431-
const fullProfile = await this.providerSettingsManager.getProfile({ name: profile.name })
2432-
const hasActualSettings = !!fullProfile.apiProvider
2433-
2434-
if (hasActualSettings) {
2435-
await this.activateProviderProfileUnlocked(
2436-
{ name: profile.name },
2437-
targetTask === null ? { skipCurrentTaskRebuild: true } : undefined,
2438-
signal,
2439-
)
2441+
// If this mode has a saved config, use it.
2442+
if (savedConfigId) {
2443+
const profile = listApiConfig.find(({ id }) => id === savedConfigId)
2444+
2445+
if (profile?.name) {
2446+
// Check if the profile has actual API configuration (not just an id).
2447+
// In CLI mode, the ProviderSettingsManager may return empty default profiles
2448+
// that only contain 'id' and 'name' fields. Activating such a profile would
2449+
// overwrite the CLI's working API configuration with empty settings.
2450+
// Skip activation if the profile has no apiProvider set - this indicates
2451+
// an unconfigured/empty profile.
2452+
const fullProfile = await this.providerSettingsManager.getProfile({ name: profile.name })
2453+
const hasActualSettings = !!fullProfile.apiProvider
2454+
2455+
if (hasActualSettings) {
2456+
await this.activateProviderProfileUnlocked(
2457+
{ name: profile.name },
2458+
targetTask === null ? { skipCurrentTaskRebuild: true } : undefined,
2459+
signal,
2460+
)
2461+
} else {
2462+
// The task will continue with the current/default configuration.
2463+
}
24402464
} else {
24412465
// The task will continue with the current/default configuration.
24422466
}
24432467
} else {
2444-
// The task will continue with the current/default configuration.
2445-
}
2446-
} else {
2447-
// If no saved config for this mode, save current config as default.
2448-
const currentApiConfigNameAfter = this.getGlobalState("currentApiConfigName")
2468+
// If no saved config for this mode, save current config as default.
2469+
const currentApiConfigNameAfter = this.getGlobalState("currentApiConfigName")
24492470

2450-
if (currentApiConfigNameAfter) {
2451-
const config = listApiConfig.find((c) => c.name === currentApiConfigNameAfter)
2471+
if (currentApiConfigNameAfter) {
2472+
const config = listApiConfig.find((c) => c.name === currentApiConfigNameAfter)
24522473

2453-
if (config?.id) {
2454-
await this.providerSettingsManager.setModeConfig(newMode, config.id)
2474+
if (config?.id) {
2475+
await this.providerSettingsManager.setModeConfig(newMode, config.id)
2476+
}
24552477
}
24562478
}
2457-
}
24582479

2459-
if (targetTask !== null) {
2460-
await this.postStateToWebview()
2480+
if (targetTask !== null) {
2481+
await this.postStateToWebview()
2482+
}
2483+
} catch (error) {
2484+
await reconcileSwitchWrites()
2485+
this.log(
2486+
`[handleModeSwitch] Failed to persist mode "${newMode}": ${error instanceof Error ? error.message : String(error)}`,
2487+
)
2488+
throw error
24612489
}
24622490
}
24632491

@@ -2590,7 +2618,13 @@ export class ClineProvider
25902618
// serving the settings captured before the save under the same name.
25912619
if (this.pinnedProfileName === name) {
25922620
await this._saveViewLocalStateFromMutation({ apiConfiguration: providerSettings })
2593-
this.updateTaskApiHandlerIfNeeded(providerSettings, { forceRebuild: true })
2621+
// Only rebuild when the task actually runs under the saved profile: a
2622+
// view pinned to this profile can hold a task that follows a different
2623+
// sticky profile, and the forced rebuild would silently switch that
2624+
// conversation to the saved profile's settings.
2625+
if (this.getCurrentTask()?.taskApiConfigName === name) {
2626+
this.updateTaskApiHandlerIfNeeded(providerSettings, { forceRebuild: true })
2627+
}
25942628
}
25952629
await this.refreshViewLocalStateForUpdatedProfile(name, providerSettings)
25962630
}
@@ -2934,9 +2968,13 @@ export class ClineProvider
29342968
// The active task of a pinned view holds its own API handler built from
29352969
// the profile's settings: rebuild it with the saved settings or the
29362970
// running conversation keeps sending the old token even though the
2937-
// view's buffer has caught up. Direct private access across sibling
2938-
// instances of the same class is compile-time safe.
2939-
instance.updateTaskApiHandlerIfNeeded(providerSettings, { forceRebuild: true })
2971+
// view's buffer has caught up. Only rebuild when the task actually runs
2972+
// under the saved profile: a task that follows a different sticky
2973+
// profile must keep its own settings. Direct private access across
2974+
// sibling instances of the same class is compile-time safe.
2975+
if (instance.getCurrentTask()?.taskApiConfigName === name) {
2976+
instance.updateTaskApiHandlerIfNeeded(providerSettings, { forceRebuild: true })
2977+
}
29402978
await instance.postStateToWebview()
29412979
}),
29422980
)

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

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

20932093
expect(Object.keys(pruned)).toHaveLength(50)
2094-
expect(pruned["view-54"]).toBeDefined()
2095-
expect(pruned["view-5"]).toBeDefined()
2094+
expect(pruned["view-54"]).toEqual({ mode: "mode-54", updatedAt: 54 })
2095+
expect(pruned["view-5"]).toEqual({ mode: "mode-5", updatedAt: 5 })
20962096
expect(pruned["view-4"]).toBeUndefined()
20972097

20982098
await provider.dispose()
@@ -8725,6 +8725,7 @@ describe("ClineProvider - Comprehensive Edit/Delete Edge Cases", () => {
87258725
// minimal double without the full provider/services graph.
87268726
const siblingTask = {
87278727
apiConfiguration: { apiProvider: providerIdentifiers.anthropic, apiKey: "old-key" },
8728+
taskApiConfigName: "saved-profile",
87288729
updateApiConfiguration: vi.fn(),
87298730
}
87308731
vi.spyOn(sibling, "getCurrentTask").mockReturnValue(
@@ -8765,6 +8766,101 @@ describe("ClineProvider - Comprehensive Edit/Delete Edge Cases", () => {
87658766
}
87668767
})
87678768

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

0 commit comments

Comments
 (0)