Skip to content

Commit 6063622

Browse files
committed
fix(provider): fail closed on unverified profile saves and compensate failed deletions
- Re-read the stored record after saveConfig and fail the upsert when the read-back fails, compensating the landed save with the pre-save snapshot instead of letting an unvalidated caller payload drive activation writes. - Snapshot the manager record and every persistence surface before deleteProviderProfile commits its manager delete, and restore them (record, profile-list merge, selection, shared settings, affected view pins) when a later write in the deletion group fails. - Keep the mutation queue owned by a mode switch past its timeout via runToCompletion so the next queued mutation cannot overlap in-flight writes.
1 parent aa2da74 commit 6063622

2 files changed

Lines changed: 476 additions & 106 deletions

File tree

‎src/core/webview/ClineProvider.ts‎

Lines changed: 218 additions & 95 deletions
Original file line numberDiff line numberDiff line change
@@ -2266,8 +2266,12 @@ export class ClineProvider
22662266
return
22672267
}
22682268

2269-
return this.enqueueProviderProfileMutation((signal) =>
2270-
this.handleModeSwitchUnlocked(newMode, targetTask, signal),
2269+
return this.enqueueProviderProfileMutation(
2270+
(signal) => this.handleModeSwitchUnlocked(newMode, targetTask, signal),
2271+
// The switch and its nested activation must own the queue until every
2272+
// write - including compensation - settles: a timeout must not let the
2273+
// next queued mutation overlap writes that are still in flight.
2274+
{ runToCompletion: true },
22712275
)
22722276
}
22732277

@@ -2768,6 +2772,16 @@ export class ClineProvider
27682772
// we rely on the `ContextProxy`'s data store and in other cases
27692773
// we rely on the `ProviderSettingsManager`'s data store. It might
27702774
// be simpler to unify these two.
2775+
// Snapshot the prior manager record before the save so a failed post-save
2776+
// read-back can compensate the landed write instead of leaving the record
2777+
// changed while the shared store was not.
2778+
let previousRecord: Awaited<ReturnType<ProviderSettingsManager["getProfile"]>> | undefined
2779+
try {
2780+
previousRecord = await this.providerSettingsManager.getProfile({ name })
2781+
} catch {
2782+
// Absent record: compensation deletes the landed create instead.
2783+
}
2784+
27712785
const id = await this.providerSettingsManager.saveConfig(name, providerSettings)
27722786

27732787
if (signal.aborted) return id
@@ -2776,19 +2790,37 @@ export class ClineProvider
27762790
// read the stored copy back and use it for every activation write,
27772791
// sibling refresh, overlay, and task-handler update below, so raw
27782792
// webview fields the profile schema strips cannot enter the shared
2779-
// store, sibling view state, or task configuration. When the read-back
2780-
// fails the caller's settings are kept: the record landed, and the
2781-
// next load re-reads the stored copy.
2782-
let normalizedSettings = providerSettings
2793+
// store, sibling view state, or task configuration. Fail closed when
2794+
// the read-back fails: the raw caller payload must never stand in for
2795+
// the validated record, so the landed save is compensated and the
2796+
// mutation group fails instead of propagating unvalidated settings.
2797+
let normalizedSettings: ProviderSettings
27832798
try {
27842799
const {
27852800
name: _savedName,
27862801
id: _savedId,
27872802
...storedRecord
27882803
} = await this.providerSettingsManager.getProfile({ name })
27892804
normalizedSettings = storedRecord as ProviderSettings
2790-
} catch {
2791-
// Best-effort read-back; see the comment above.
2805+
} catch (error) {
2806+
// Fail closed: compensate the landed save (restore the prior record,
2807+
// or delete a landed create) and fail the group so the raw caller
2808+
// payload never stands in for the validated stored record.
2809+
try {
2810+
if (previousRecord) {
2811+
const { name: _previousName, id: _previousId, ...previousSettings } = previousRecord
2812+
await this.providerSettingsManager.saveConfig(name, previousSettings)
2813+
} else {
2814+
await this.providerSettingsManager.deleteConfig(name)
2815+
}
2816+
} catch (restoreError) {
2817+
this.log(
2818+
`[persistProviderProfile] failed to compensate the landed save of '${name}': ${restoreError instanceof Error ? restoreError.message : String(restoreError)}`,
2819+
)
2820+
}
2821+
throw new Error(
2822+
`Provider profile '${name}' could not be read back after save: ${error instanceof Error ? error.message : String(error)}`,
2823+
)
27922824
}
27932825

27942826
if (activate) {
@@ -2881,6 +2913,23 @@ export class ClineProvider
28812913
throw new Error("You cannot delete the last profile")
28822914
}
28832915

2916+
// Snapshot the manager record and every persistence surface this
2917+
// deletion rewrites BEFORE the manager delete commits, so a failure
2918+
// inside the write group below can be compensated instead of leaving
2919+
// the secrets-backed record gone while metadata and view pins still
2920+
// reference it.
2921+
let previousRecord: Awaited<ReturnType<ProviderSettingsManager["getProfile"]>> | undefined
2922+
try {
2923+
previousRecord = await this.providerSettingsManager.getProfile({ name: profileToDelete.name })
2924+
} catch {
2925+
// Absent record: the idempotent not-found path below still prunes the
2926+
// stale list entry, and compensation skips the record restore.
2927+
}
2928+
const previousEntries = this.getProviderProfileEntries()
2929+
const previousSelection = globalSettings.currentApiConfigName
2930+
const previousSharedSettings = this.contextProxy.getProviderSettings()
2931+
const previousViewStates = this.getPersistedViewStates({ fresh: true })
2932+
28842933
// Remove the profile from the settings store (context.secrets) so it cannot be
28852934
// resurrected by a later listApiConfigMeta sync. A not-found rejection means
28862935
// the secret was already gone (e.g. pruned by an earlier run): branch on the
@@ -2900,108 +2949,182 @@ export class ClineProvider
29002949
)
29012950
}
29022951

2903-
// Re-point any persisted view pin that referenced the deleted profile so views
2904-
// do not rehydrate a missing profile name after a reload.
2905-
await this.repointPersistedViewStates(profileToDelete.name, profileToActivate)
2906-
2907-
const viewPinsDeletedProfile =
2908-
this.viewLocalState.currentApiConfigName === profileToDelete.name ||
2909-
// No view-local pin: the view follows the shared selection, so it only needs the
2910-
// replacement activation when that shared selection referenced the deleted profile;
2911-
// an unrelated deletion must not rebuild this view's task handler.
2912-
(this.viewLocalState.currentApiConfigName === undefined &&
2913-
globalSettings.currentApiConfigName === profileToDelete.name)
2914-
2915-
if (viewPinsDeletedProfile) {
2916-
// Apply the replacement through the activation path so this view's
2917-
// viewLocalState.apiConfiguration and the current task's api handler are
2918-
// refreshed; a name-only update would leave the deleted profile's settings
2919-
// behind in both.
2920-
await this.activateProviderProfile({ name: profileToActivate })
2921-
2922-
// The return below would otherwise skip the sibling re-pin further down:
2923-
// the activation's pinned-name refresh only selects siblings pinned to
2924-
// the replacement, so live views still buffered on the deleted profile
2925-
// must be re-pointed here as well, with the replacement's settings when
2926-
// they can be resolved (a name-only re-pin is still better than leaving
2927-
// the deleted name behind).
2928-
let replacementSettings: ProviderSettings | undefined
2952+
try {
2953+
// Re-point any persisted view pin that referenced the deleted profile so views
2954+
// do not rehydrate a missing profile name after a reload.
2955+
await this.repointPersistedViewStates(profileToDelete.name, profileToActivate)
2956+
2957+
const viewPinsDeletedProfile =
2958+
this.viewLocalState.currentApiConfigName === profileToDelete.name ||
2959+
// No view-local pin: the view follows the shared selection, so it only needs the
2960+
// replacement activation when that shared selection referenced the deleted profile;
2961+
// an unrelated deletion must not rebuild this view's task handler.
2962+
(this.viewLocalState.currentApiConfigName === undefined &&
2963+
globalSettings.currentApiConfigName === profileToDelete.name)
2964+
2965+
if (viewPinsDeletedProfile) {
2966+
// Apply the replacement through the activation path so this view's
2967+
// viewLocalState.apiConfiguration and the current task's api handler are
2968+
// refreshed; a name-only update would leave the deleted profile's settings
2969+
// behind in both.
2970+
await this.activateProviderProfile({ name: profileToActivate })
2971+
2972+
// The return below would otherwise skip the sibling re-pin further down:
2973+
// the activation's pinned-name refresh only selects siblings pinned to
2974+
// the replacement, so live views still buffered on the deleted profile
2975+
// must be re-pointed here as well, with the replacement's settings when
2976+
// they can be resolved (a name-only re-pin is still better than leaving
2977+
// the deleted name behind).
2978+
let replacementSettings: ProviderSettings | undefined
2979+
try {
2980+
const { name: _replacementName, ...settings } = await this.providerSettingsManager.getProfile({
2981+
name: profileToActivate,
2982+
})
2983+
replacementSettings = settings as ProviderSettings
2984+
} catch (error) {
2985+
this.log(
2986+
`[deleteProviderProfile] Unable to resolve API profile '${profileToActivate}': ${
2987+
error instanceof Error ? error.message : String(error)
2988+
}`,
2989+
)
2990+
}
2991+
await this.rePinViewLocalStateForDeletedProfile(
2992+
profileToDelete.name,
2993+
profileToActivate,
2994+
replacementSettings,
2995+
)
2996+
return
2997+
}
2998+
2999+
// This view pins an unrelated profile, which must survive the deletion: sync the
3000+
// shared profile list and post the updated state only. The buffer already holds
3001+
// the surviving pin, so the current-profile slot is left untouched here: a
3002+
// setValue would only trigger a viewStates prune write and could clobber the pin
3003+
// with the shared slot's value.
3004+
const entries = this.getProviderProfileEntries().filter(({ name }) => name !== profileToDelete.name)
3005+
3006+
// Write only the profile list back: replaying the full settings snapshot
3007+
// captured above would also rewrite unrelated keys (including viewStates,
3008+
// which ClineProvider mutates directly in storage for concurrent views)
3009+
// with this view's stale cached copy.
3010+
await this.contextProxy.setValue("listApiConfigMeta", entries)
3011+
3012+
// Resolve the surviving profile's settings so the shared provider keys
3013+
// and any other live view still pinned to the deleted profile can be
3014+
// updated with a matching configuration.
3015+
let survivingSettings: ProviderSettings | undefined
29293016
try {
2930-
const { name: _replacementName, ...settings } = await this.providerSettingsManager.getProfile({
3017+
const { name: _survivingName, ...settings } = await this.providerSettingsManager.getProfile({
29313018
name: profileToActivate,
29323019
})
2933-
replacementSettings = settings as ProviderSettings
3020+
survivingSettings = settings as ProviderSettings
29343021
} catch (error) {
29353022
this.log(
29363023
`[deleteProviderProfile] Unable to resolve API profile '${profileToActivate}': ${
29373024
error instanceof Error ? error.message : String(error)
29383025
}`,
29393026
)
29403027
}
2941-
await this.rePinViewLocalStateForDeletedProfile(
2942-
profileToDelete.name,
2943-
profileToActivate,
2944-
replacementSettings,
2945-
)
2946-
return
2947-
}
2948-
2949-
// This view pins an unrelated profile, which must survive the deletion: sync the
2950-
// shared profile list and post the updated state only. The buffer already holds
2951-
// the surviving pin, so the current-profile slot is left untouched here: a
2952-
// setValue would only trigger a viewStates prune write and could clobber the pin
2953-
// with the shared slot's value.
2954-
const entries = this.getProviderProfileEntries().filter(({ name }) => name !== profileToDelete.name)
29553028

2956-
// Write only the profile list back: replaying the full settings snapshot
2957-
// captured above would also rewrite unrelated keys (including viewStates,
2958-
// which ClineProvider mutates directly in storage for concurrent views)
2959-
// with this view's stale cached copy.
2960-
await this.contextProxy.setValue("listApiConfigMeta", entries)
2961-
2962-
// Resolve the surviving profile's settings so the shared provider keys
2963-
// and any other live view still pinned to the deleted profile can be
2964-
// updated with a matching configuration.
2965-
let survivingSettings: ProviderSettings | undefined
2966-
try {
2967-
const { name: _survivingName, ...settings } = await this.providerSettingsManager.getProfile({
2968-
name: profileToActivate,
2969-
})
2970-
survivingSettings = settings as ProviderSettings
2971-
} catch (error) {
2972-
this.log(
2973-
`[deleteProviderProfile] Unable to resolve API profile '${profileToActivate}': ${
2974-
error instanceof Error ? error.message : String(error)
2975-
}`,
2976-
)
2977-
}
3029+
// This view does not pin the deleted profile here (that case returned
3030+
// above), so only the shared selection can dangle: when the deleted profile
3031+
// was the globally selected one, the shared slot and the shared provider
3032+
// settings still carry its configuration.
3033+
const deletedWasGlobal = profileToDelete.name === globalSettings.currentApiConfigName
3034+
3035+
if (deletedWasGlobal) {
3036+
// The shared selection changed, but this view's own pin (if any) still
3037+
// names a surviving profile: update the shared store only, leaving the
3038+
// view-local pin untouched.
3039+
await this.contextProxy.setValue("currentApiConfigName", profileToActivate)
3040+
}
29783041

2979-
// This view does not pin the deleted profile here (that case returned
2980-
// above), so only the shared selection can dangle: when the deleted profile
2981-
// was the globally selected one, the shared slot and the shared provider
2982-
// settings still carry its configuration.
2983-
const deletedWasGlobal = profileToDelete.name === globalSettings.currentApiConfigName
3042+
if (deletedWasGlobal && survivingSettings) {
3043+
// The deleted profile was the globally active one, so the shared
3044+
// provider keys still carry its settings; replace them so getState()
3045+
// reports the surviving profile's configuration.
3046+
await this.contextProxy.setProviderSettings(survivingSettings)
3047+
}
29843048

2985-
if (deletedWasGlobal) {
2986-
// The shared selection changed, but this view's own pin (if any) still
2987-
// names a surviving profile: update the shared store only, leaving the
2988-
// view-local pin untouched.
2989-
await this.contextProxy.setValue("currentApiConfigName", profileToActivate)
2990-
}
3049+
// Re-pin other live views still buffered on the deleted profile: their
3050+
// buffer and durable viewStates entry would otherwise keep serving the
3051+
// deleted profile's name and configuration.
3052+
await this.rePinViewLocalStateForDeletedProfile(profileToDelete.name, profileToActivate, survivingSettings)
29913053

2992-
if (deletedWasGlobal && survivingSettings) {
2993-
// The deleted profile was the globally active one, so the shared
2994-
// provider keys still carry its settings; replace them so getState()
2995-
// reports the surviving profile's configuration.
2996-
await this.contextProxy.setProviderSettings(survivingSettings)
3054+
await this.postStateToWebview()
3055+
} catch (error) {
3056+
// The manager delete committed but a later write failed: restore the
3057+
// deleted record first, then the shared metadata, selection, and shared
3058+
// settings the deletion had rewritten, and finally merge the affected
3059+
// persisted pins back. The merge re-reads the durable map and rewrites
3060+
// only entries that named the deleted profile in the pre-delete
3061+
// snapshot, so concurrent viewStates updates from sibling views
3062+
// survive. Each restore is independent and logged; the original
3063+
// failure is what the caller sees.
3064+
if (previousRecord) {
3065+
try {
3066+
const { name: _previousName, id: _previousId, ...previousSettings } = previousRecord
3067+
await this.providerSettingsManager.saveConfig(profileToDelete.name, previousSettings)
3068+
} catch (restoreError) {
3069+
this.log(
3070+
`[deleteProviderProfile] failed to restore the manager record '${profileToDelete.name}': ${
3071+
restoreError instanceof Error ? restoreError.message : String(restoreError)
3072+
}`,
3073+
)
3074+
}
3075+
}
3076+
try {
3077+
// Merge rather than clobber: another instance may have added
3078+
// profiles between the snapshot and the compensation.
3079+
const currentEntries = this.getProviderProfileEntries()
3080+
const deletedEntry = previousEntries.find((entry) => entry.name === profileToDelete.name)
3081+
if (deletedEntry && !currentEntries.some((entry) => entry.name === profileToDelete.name)) {
3082+
await this.contextProxy.setValue("listApiConfigMeta", [...currentEntries, deletedEntry])
3083+
}
3084+
} catch (restoreError) {
3085+
this.log(
3086+
`[deleteProviderProfile] failed to restore the profile list: ${restoreError instanceof Error ? restoreError.message : String(restoreError)}`,
3087+
)
3088+
}
3089+
try {
3090+
await this.contextProxy.setValue("currentApiConfigName", previousSelection)
3091+
} catch (restoreError) {
3092+
this.log(
3093+
`[deleteProviderProfile] failed to restore the shared selection: ${restoreError instanceof Error ? restoreError.message : String(restoreError)}`,
3094+
)
3095+
}
3096+
try {
3097+
await this.contextProxy.setProviderSettings(previousSharedSettings)
3098+
} catch (restoreError) {
3099+
this.log(
3100+
`[deleteProviderProfile] failed to restore the shared provider settings: ${restoreError instanceof Error ? restoreError.message : String(restoreError)}`,
3101+
)
3102+
}
3103+
try {
3104+
const restore = ClineProvider.persistedViewStateWriteQueue.then(async () => {
3105+
const current = this.getPersistedViewStates({ fresh: true })
3106+
const merged = { ...current }
3107+
let changed = false
3108+
for (const [viewId, entry] of Object.entries(previousViewStates)) {
3109+
if (entry?.currentApiConfigName !== profileToDelete.name) {
3110+
continue
3111+
}
3112+
merged[viewId] = entry
3113+
changed = true
3114+
}
3115+
if (changed) {
3116+
await this.contextProxy.setValue("viewStates", merged)
3117+
}
3118+
})
3119+
ClineProvider.persistedViewStateWriteQueue = restore.catch(() => {})
3120+
await restore
3121+
} catch (restoreError) {
3122+
this.log(
3123+
`[deleteProviderProfile] failed to restore the persisted view pins: ${restoreError instanceof Error ? restoreError.message : String(restoreError)}`,
3124+
)
3125+
}
3126+
throw error
29973127
}
2998-
2999-
// Re-pin other live views still buffered on the deleted profile: their
3000-
// buffer and durable viewStates entry would otherwise keep serving the
3001-
// deleted profile's name and configuration.
3002-
await this.rePinViewLocalStateForDeletedProfile(profileToDelete.name, profileToActivate, survivingSettings)
3003-
3004-
await this.postStateToWebview()
30053128
}
30063129

30073130
private async persistStickyProviderProfileToCurrentTask(

0 commit comments

Comments
 (0)