Skip to content

Commit 48acb46

Browse files
fix(provider): compensate every durable store when a profile or mode mutation fails
- deleteProviderProfile aborts before the destructive delete when the pre-delete settings read fails for anything other than the typed not-found: without the snapshot there is no way to compensate a later failure. - deleteProviderProfile snapshots the profile list, the shared selection, and this view's pin/overlay, and compensates each store that already landed, each awaited on its own. A rollback that itself fails surfaces a distinct inconsistent-state error instead of masquerading as the original failure. - rePinViewLocalStateForDeletedProfile restores an affected sibling view's own pin when its re-pin write fails. - handleModeSwitch awaits the shared-mode and view-pin restores independently and reports an inconsistent-state error when either one fails. - handleModeSwitch re-checks the cancellation signal once the durable write settles: a write that lands after the mutation timeout already aborted the run is now compensated instead of emitted. - tests: coverage for each path above with a negative control, plus the openClineInNewTab rejection-then-retry contract.
1 parent 6605257 commit 48acb46

4 files changed

Lines changed: 572 additions & 18 deletions

File tree

‎src/activate/__tests__/registerCommands.spec.ts‎

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1101,6 +1101,84 @@ describe("openClineInNewTab", () => {
11011101
expect(vscode.window.createWebviewPanel).toHaveBeenCalledTimes(2)
11021102
})
11031103

1104+
1105+
it("clears the in-flight creation when it rejects so a later open retries", async () => {
1106+
// A creation that fails must not stay in the slot: every later "Open in editor"
1107+
// would receive the settled rejected promise and the tab could never be opened
1108+
// again without reloading the window.
1109+
const failure = new Error("context proxy unavailable")
1110+
;(ContextProxy.getInstance as Mock).mockRejectedValueOnce(failure)
1111+
1112+
await expect(
1113+
openClineInNewTab({
1114+
context: mockContext,
1115+
outputChannel: mockOutputChannel,
1116+
webviewFocusTracker: new WebviewFocusTracker(),
1117+
}),
1118+
).rejects.toThrow(failure)
1119+
1120+
// The retry starts a fresh creation instead of replaying the stored rejection.
1121+
const retried = await openClineInNewTab({
1122+
context: mockContext,
1123+
outputChannel: mockOutputChannel,
1124+
webviewFocusTracker: new WebviewFocusTracker(),
1125+
})
1126+
expect(retried).toBeDefined()
1127+
expect(ContextProxy.getInstance).toHaveBeenCalledTimes(2)
1128+
expect(vscode.window.createWebviewPanel).toHaveBeenCalledTimes(1)
1129+
})
1130+
1131+
it("shares a rejected creation with overlapping callers and still clears the slot", async () => {
1132+
// Both callers join the same in-flight creation, so both must observe its
1133+
// rejection: dropping it for the joined caller would leave that command
1134+
// handler hanging on a promise that never yields a usable result.
1135+
let rejectCreation!: (error: Error) => void
1136+
// Only the in-flight creation is deferred; the retry after it settles gets the
1137+
// normal (immediate) context proxy.
1138+
;(ContextProxy.getInstance as Mock).mockReturnValueOnce(
1139+
new Promise((_resolve, reject) => {
1140+
rejectCreation = reject
1141+
}),
1142+
)
1143+
1144+
const first = openClineInNewTab({
1145+
context: mockContext,
1146+
outputChannel: mockOutputChannel,
1147+
webviewFocusTracker: new WebviewFocusTracker(),
1148+
})
1149+
const second = openClineInNewTab({
1150+
context: mockContext,
1151+
outputChannel: mockOutputChannel,
1152+
webviewFocusTracker: new WebviewFocusTracker(),
1153+
})
1154+
1155+
// Attach the observers before the rejection is triggered.
1156+
const firstSettled = first.then(
1157+
() => "resolved",
1158+
(error: unknown) => error,
1159+
)
1160+
const secondSettled = second.then(
1161+
() => "resolved",
1162+
(error: unknown) => error,
1163+
)
1164+
1165+
const failure = new Error("panel creation failed")
1166+
rejectCreation(failure)
1167+
1168+
expect(await firstSettled).toBe(failure)
1169+
expect(await secondSettled).toBe(failure)
1170+
expect(ContextProxy.getInstance).toHaveBeenCalledTimes(1)
1171+
1172+
// The slot is cleared even on the shared-rejection path: the next open runs a
1173+
// fresh creation instead of replaying the stored rejection.
1174+
const third = await openClineInNewTab({
1175+
context: mockContext,
1176+
outputChannel: mockOutputChannel,
1177+
webviewFocusTracker: new WebviewFocusTracker(),
1178+
})
1179+
expect(third).toBeDefined()
1180+
expect(ContextProxy.getInstance).toHaveBeenCalledTimes(2)
1181+
})
11041182
it("keeps the replacement panel tracked when a stale panel's disposal fires late", async () => {
11051183
// Capture each created panel so the first panel's (stale) dispose
11061184
// handler can fire after the replacement is already tracked.

‎src/core/webview/ClineProvider.ts‎

Lines changed: 172 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -2200,6 +2200,46 @@ export class ClineProvider
22002200
throw error
22012201
}
22022202

2203+
// The durable write can settle AFTER the mutation timeout has already aborted this
2204+
// run and handed the caller a timeout rejection. Nothing below may then run:
2205+
// emitting TaskModeSwitched/ModeChanged or loading the mode profile would publish a
2206+
// switch the caller was told had been cancelled, and the next queued mutation could
2207+
// start against a half-applied mode. Undo everything that landed and keep the
2208+
// cancellation result; each restore is awaited on its own so one failing write
2209+
// cannot skip the next.
2210+
if (signal?.aborted) {
2211+
try {
2212+
await this.contextProxy.setValue("mode", previousSharedMode)
2213+
} catch (rollbackError) {
2214+
this.log(
2215+
`[handleModeSwitch] Failed to roll back shared mode after cancellation: ${
2216+
rollbackError instanceof Error ? rollbackError.message : String(rollbackError)
2217+
}`,
2218+
)
2219+
}
2220+
try {
2221+
await this._saveViewLocalStateFromMutation({ mode: previousViewMode })
2222+
} catch (rollbackError) {
2223+
this.log(
2224+
`[handleModeSwitch] Failed to roll back the view mode pin after cancellation: ${
2225+
rollbackError instanceof Error ? rollbackError.message : String(rollbackError)
2226+
}`,
2227+
)
2228+
}
2229+
if (undoHistoryWrite) {
2230+
try {
2231+
await undoHistoryWrite()
2232+
} catch (rollbackError) {
2233+
this.log(
2234+
`[handleModeSwitch] Failed to roll back task-history mode after cancellation: ${
2235+
rollbackError instanceof Error ? rollbackError.message : String(rollbackError)
2236+
}`,
2237+
)
2238+
}
2239+
}
2240+
return
2241+
}
2242+
22032243
// Both durable writes succeeded: this is the point of no return for the task
22042244
// side. Emitting and updating _taskMode here (rather than before the durable
22052245
// write) keeps listeners and in-memory task state from observing a switch that
@@ -2223,18 +2263,34 @@ export class ClineProvider
22232263
)
22242264
}
22252265
}
2266+
// Each restore is awaited on its own: a failed shared-mode write must not skip the
2267+
// pin restore (or the reverse), because one store left on the new mode while the
2268+
// other is back on the old one is exactly the split state this rollback exists to
2269+
// prevent. A rollback that itself failed is reported, not just logged.
2270+
const rollbackFailures: string[] = []
2271+
const describeModeRollbackFailure = (e: unknown) => (e instanceof Error ? e.message : String(e))
22262272
try {
2227-
// Restore the shared value through the proxy only, then restore the pin
2228-
// from its own pre-switch value. When the view had no pin, the forward
2229-
// setValue created one; clearing it (mode: undefined) is what returns this
2230-
// view to its pre-switch state instead of leaving the shared mode pinned.
2273+
// Restore the shared value through the proxy only.
22312274
await this.contextProxy.setValue("mode", previousSharedMode)
2275+
} catch (rollbackError) {
2276+
rollbackFailures.push(`shared mode: ${describeModeRollbackFailure(rollbackError)}`)
2277+
}
2278+
try {
2279+
// Then the pin from its own pre-switch value. When the view had no pin, the forward
2280+
// setValue created one; clearing it (mode: undefined) is what returns this view to
2281+
// its pre-switch state instead of leaving the shared mode pinned.
22322282
await this._saveViewLocalStateFromMutation({ mode: previousViewMode })
22332283
} catch (rollbackError) {
2284+
rollbackFailures.push(`view mode pin: ${describeModeRollbackFailure(rollbackError)}`)
2285+
}
2286+
if (rollbackFailures.length > 0) {
2287+
// Unrepaired partial state must not be reported as a clean rollback: the caller
2288+
// needs to know the durable mode may still name the mode this switch abandoned.
22342289
this.log(
2235-
`[handleModeSwitch] Failed to roll back shared mode after the emit failed: ${
2236-
rollbackError instanceof Error ? rollbackError.message : String(rollbackError)
2237-
}`,
2290+
`[handleModeSwitch] Mode rollback left persisted state inconsistent (${rollbackFailures.join(", ")}).`,
2291+
)
2292+
throw new Error(
2293+
`Mode switch left persisted mode state inconsistent: ${rollbackFailures.join(", ")}. Original failure: ${error instanceof Error ? error.message : String(error)}`,
22382294
)
22392295
}
22402296
throw error
@@ -2464,8 +2520,19 @@ export class ClineProvider
24642520
deletedProfile = profile as ProviderSettingsWithId
24652521
} catch (error: unknown) {
24662522
if (!(error instanceof ProviderSettingsNotFoundError)) {
2467-
this.log(`deleteProviderProfile: could not read the settings for '${profileToDelete.name}'; a later failure of the list update cannot be compensated. ${error instanceof Error ? error.message : String(error)}`)
2523+
// Abort BEFORE the destructive delete. Without the captured settings there is no
2524+
// way to put them back if a later durable write fails, so continuing here would
2525+
// turn a transient read error into permanent profile loss while the persisted list
2526+
// still named the profile.
2527+
this.log(
2528+
`deleteProviderProfile: could not read the settings for '${profileToDelete.name}'; aborting before the deletion because a later failure could not be compensated. ${
2529+
error instanceof Error ? error.message : String(error)
2530+
}`,
2531+
)
2532+
throw error
24682533
}
2534+
// A typed not-found is the idempotent case: the secret is already gone, so there is
2535+
// nothing to compensate and the stale list entry is still pruned below.
24692536
}
24702537

24712538
try {
@@ -2479,14 +2546,27 @@ export class ClineProvider
24792546
)
24802547
}
24812548

2482-
const entries = this.getProviderProfileEntries().filter(({ name }) => name !== profileToDelete.name)
2549+
// Snapshot every durable store this method is about to change, so a failure after the
2550+
// settings commit can be rolled back store by store instead of only re-saving the
2551+
// settings: a later failed write would otherwise leave the persisted list, the shared
2552+
// selection, or this view's own pin pointing at a profile that no longer exists.
2553+
const previousEntries = this.getProviderProfileEntries()
2554+
const previousGlobalSelection = globalSettings.currentApiConfigName
2555+
const previousViewPin = this.viewLocalState.currentApiConfigName
2556+
const previousViewOverlay = this.viewLocalState.apiConfiguration
2557+
// Which writes have actually landed: only those need compensation.
2558+
let listWriteLanded = false
2559+
let selectionWriteLanded = false
2560+
let viewPinWriteLanded = false
2561+
const entries = previousEntries.filter(({ name }) => name !== profileToDelete.name)
24832562

24842563
// Write only the profile list back: replaying the full settings snapshot
24852564
// captured above would also rewrite unrelated keys (including viewStates,
24862565
// which ClineProvider mutates directly in storage for concurrent views)
24872566
// with this view's stale cached copy.
24882567
try {
24892568
await this.contextProxy.setValue("listApiConfigMeta", entries)
2569+
listWriteLanded = true
24902570

24912571
// Resolve the surviving profile's settings so this view and any other
24922572
// live view still pinned to the deleted profile can be re-pinned with
@@ -2517,11 +2597,14 @@ export class ClineProvider
25172597
// survivor to the shared store, which covers the deleted-was-global case
25182598
// for every other view as well as this one.
25192599
await this.setValue("currentApiConfigName", profileToActivate)
2600+
selectionWriteLanded = true
2601+
viewPinWriteLanded = true
25202602
} else if (deletedWasGlobal) {
25212603
// The shared selection changed, but this view's own pin still names a
25222604
// surviving profile: update the shared store only, leaving the
25232605
// view-local pin untouched.
25242606
await this.contextProxy.setValue("currentApiConfigName", profileToActivate)
2607+
selectionWriteLanded = true
25252608
}
25262609

25272610
if ((deletedWasGlobal || viewWasPinnedToDeleted) && survivingSettings) {
@@ -2536,6 +2619,7 @@ export class ClineProvider
25362619
// replace it with the survivor's so the re-pointed pin serves matching
25372620
// settings. A view pinned to another profile keeps its own overlay.
25382621
await this._saveViewLocalStateFromMutation({ apiConfiguration: survivingSettings })
2622+
viewPinWriteLanded = true
25392623
}
25402624
}
25412625

@@ -2544,21 +2628,67 @@ export class ClineProvider
25442628
// deleted profile's name and configuration.
25452629
await this.rePinViewLocalStateForDeletedProfile(profileToDelete.name, profileToActivate, survivingSettings)
25462630
} catch (error: unknown) {
2547-
// The profile's settings are already gone from the secret store while the list
2548-
// write (or a later selection update) failed. Put the settings back so the durable
2549-
// metadata and the store agree again - the deletion simply did not happen - and
2550-
// then surface the original failure rather than a compensation outcome.
2631+
// Compensate every store that already landed, each awaited on its own so one
2632+
// failing restore cannot skip the next one. The deletion simply did not happen:
2633+
// the settings, the profile list, the shared selection, and this view's pin must
2634+
// all agree again before the original failure is surfaced.
2635+
const compensationFailures: string[] = []
2636+
const describeFailure = (e: unknown) => (e instanceof Error ? e.message : String(e))
2637+
25512638
if (deletedProfile) {
25522639
try {
25532640
await this.providerSettingsManager.saveConfig(profileToDelete.name, deletedProfile)
2554-
this.log(`deleteProviderProfile: the profile-list update failed after the settings were removed; the settings for '${profileToDelete.name}' were restored, so the stored profile list still resolves and the profile was not deleted.`)
25552641
} catch (compensationError: unknown) {
2556-
this.log(`deleteProviderProfile: the profile-list update failed AND the settings for '${profileToDelete.name}' could not be restored; the stored list may name a profile with no settings. ${compensationError instanceof Error ? compensationError.message : String(compensationError)}`)
2642+
compensationFailures.push(`settings for the deleted profile: ${describeFailure(compensationError)}`)
2643+
}
2644+
}
2645+
2646+
if (listWriteLanded) {
2647+
try {
2648+
await this.contextProxy.setValue("listApiConfigMeta", previousEntries)
2649+
} catch (compensationError: unknown) {
2650+
compensationFailures.push(`profile list: ${describeFailure(compensationError)}`)
2651+
}
2652+
}
2653+
2654+
if (selectionWriteLanded) {
2655+
try {
2656+
await this.contextProxy.setValue("currentApiConfigName", previousGlobalSelection)
2657+
} catch (compensationError: unknown) {
2658+
compensationFailures.push(`shared selection: ${describeFailure(compensationError)}`)
2659+
}
2660+
}
2661+
2662+
if (viewPinWriteLanded) {
2663+
try {
2664+
// Restoring the pin and its nested overlay together returns this view to its
2665+
// exact pre-deletion state; a view with no pre-deletion pin gets the pin the
2666+
// deletion created cleared again instead of left holding the survivor.
2667+
await this._saveViewLocalStateFromMutation({
2668+
currentApiConfigName: previousViewPin,
2669+
apiConfiguration: previousViewOverlay,
2670+
})
2671+
} catch (compensationError: unknown) {
2672+
compensationFailures.push(`view pin: ${describeFailure(compensationError)}`)
25572673
}
25582674
}
2675+
2676+
if (compensationFailures.length > 0) {
2677+
// A partially repaired deletion is worse than a reported one: surface it as its
2678+
// own inconsistent-state error so the caller cannot read it as a clean rollback.
2679+
this.log(
2680+
`deleteProviderProfile: the deletion failed AND the rollback was incomplete (${compensationFailures.join("; ")}); the persisted profile state may be inconsistent.`,
2681+
)
2682+
throw new Error(
2683+
`Profile deletion left persisted state inconsistent: ${compensationFailures.join("; ")}. Original failure: ${describeFailure(error)}`,
2684+
)
2685+
}
2686+
2687+
this.log(
2688+
`deleteProviderProfile: the deletion failed after durable writes landed; the settings, profile list, shared selection, and view pin were all restored, so the profile was not deleted.`,
2689+
)
25592690
throw error
25602691
}
2561-
25622692
await this.postStateToWebview()
25632693
}
25642694

@@ -2727,8 +2857,32 @@ export class ClineProvider
27272857
values.apiConfiguration = replacementSettings
27282858
}
27292859

2730-
// Direct private access: compile-time safe across sibling instances.
2731-
await instance._saveViewLocalStateFromMutation(values)
2860+
// Snapshot the affected view's own pin and overlay first. If this re-pin write
2861+
// fails, the caller rolls the shared stores back and this view's buffer and
2862+
// durable entry must go back with them, instead of keeping a pin to a profile
2863+
// that was never deleted.
2864+
const previousPin = instance.viewLocalState.currentApiConfigName
2865+
const previousOverlay = instance.viewLocalState.apiConfiguration
2866+
2867+
try {
2868+
// Direct private access: compile-time safe across sibling instances.
2869+
await instance._saveViewLocalStateFromMutation(values)
2870+
} catch (error) {
2871+
try {
2872+
await instance._saveViewLocalStateFromMutation({
2873+
currentApiConfigName: previousPin,
2874+
apiConfiguration: previousOverlay,
2875+
})
2876+
} catch (rollbackError) {
2877+
instance.log(
2878+
`[rePinViewLocalStateForDeletedProfile] Could not restore the pin for view ${instance.viewId} after a failed re-pin: ${
2879+
rollbackError instanceof Error ? rollbackError.message : String(rollbackError)
2880+
}`,
2881+
)
2882+
}
2883+
throw error
2884+
}
2885+
27322886
await instance.postStateToWebview()
27332887
}),
27342888
)

0 commit comments

Comments
 (0)