@@ -290,6 +290,14 @@ export class ClineProvider
290290 private static readonly MAX_PERSISTED_VIEW_STATES = 50
291291 private static readonly MAX_VIEW_STATE_ID_LENGTH = 64
292292 private static persistedViewStateWriteQueue : Promise < void > = Promise . resolve ( )
293+
294+ /**
295+ * View ids whose durable entry a queued write intentionally removed
296+ * (unpin, clear, or re-key move). Activation rollback treats these as
297+ * tombstones and never resurrects a tracked eviction the clear has
298+ * since deleted; a write that lands an entry lifts its tombstone.
299+ */
300+ private static clearedViewStateIds = new Set < string > ( )
293301 private disposables : vscode . Disposable [ ] = [ ]
294302 private webviewDisposables : vscode . Disposable [ ] = [ ]
295303 private pendingThemeFixtureProbes = new Map <
@@ -710,9 +718,11 @@ export class ClineProvider
710718 let wroteEntry = false
711719 if ( ! next . mode && ! next . currentApiConfigName ) {
712720 delete states [ viewStateId ]
721+ ClineProvider . clearedViewStateIds . add ( viewStateId )
713722 } else {
714723 next . updatedAt = values . updatedAt ?? Date . now ( )
715724 states [ viewStateId ] = next
725+ ClineProvider . clearedViewStateIds . delete ( viewStateId )
716726 wroteEntry = true
717727 }
718728
@@ -759,6 +769,7 @@ export class ClineProvider
759769 const write = ClineProvider . persistedViewStateWriteQueue . then ( async ( ) => {
760770 const states = this . getPersistedViewStates ( { fresh : true } )
761771 delete states [ viewStateId ]
772+ ClineProvider . clearedViewStateIds . add ( viewStateId )
762773 try {
763774 await this . contextProxy . setValue ( "viewStates" , states )
764775 } catch ( error ) {
@@ -880,9 +891,11 @@ export class ClineProvider
880891 }
881892
882893 delete states [ previousViewStateId ]
894+ ClineProvider . clearedViewStateIds . add ( previousViewStateId )
883895
884896 if ( ! states [ nextViewStateId ] ) {
885897 states [ nextViewStateId ] = previous
898+ ClineProvider . clearedViewStateIds . delete ( nextViewStateId )
886899 }
887900
888901 const pruned = this . prunePersistedViewStates ( states )
@@ -2340,8 +2353,12 @@ export class ClineProvider
23402353 * current task. Pass null to apply only global mode/profile effects for a pending child.
23412354 */
23422355 public async handleModeSwitch ( newMode : Mode , targetTask : Task | null | undefined = this . getCurrentTask ( ) ) {
2343- return this . enqueueProviderProfileMutation ( ( signal ) =>
2344- this . handleModeSwitchUnlocked ( newMode , targetTask , signal ) ,
2356+ return this . enqueueProviderProfileMutation (
2357+ ( signal ) => this . handleModeSwitchUnlocked ( newMode , targetTask , signal ) ,
2358+ // The switch and its nested activation must own the queue until every
2359+ // write - including compensation - settles: a timeout must not let the
2360+ // next queued mutation overlap writes that are still in flight.
2361+ { runToCompletion : true } ,
23452362 )
23462363 }
23472364
@@ -2647,7 +2664,7 @@ export class ClineProvider
26472664 const merged = { ...current }
26482665 for ( const viewId of this . prunedViewIdsDuringActivation ) {
26492666 const entry = snapshot . viewStates [ viewId ]
2650- if ( entry && ! Object . hasOwn ( merged , viewId ) ) {
2667+ if ( entry && ! Object . hasOwn ( merged , viewId ) && ! ClineProvider . clearedViewStateIds . has ( viewId ) ) {
26512668 merged [ viewId ] = entry
26522669 }
26532670 }
@@ -2926,19 +2943,26 @@ export class ClineProvider
29262943 // read the stored copy back and use it for every activation write,
29272944 // sibling refresh, overlay, and task-handler update below, so raw
29282945 // webview fields the profile schema strips cannot enter the shared
2929- // store, sibling view state, or task configuration. When the read-back
2930- // fails the caller's settings are kept: the record landed, and the
2931- // next load re-reads the stored copy.
2932- let normalizedSettings = providerSettings
2946+ // store, sibling view state, or task configuration. Fail closed when
2947+ // the read-back fails: the raw caller payload must never stand in for
2948+ // the validated record, so the landed save is compensated and the
2949+ // mutation group fails instead of propagating unvalidated settings.
2950+ let normalizedSettings : ProviderSettings
29332951 try {
29342952 const {
29352953 name : _savedName ,
29362954 id : _savedId ,
29372955 ...storedRecord
29382956 } = await this . providerSettingsManager . getProfile ( { name } )
29392957 normalizedSettings = storedRecord as ProviderSettings
2940- } catch {
2941- // Best-effort read-back; see the comment above.
2958+ } catch ( error ) {
2959+ // Fail closed: compensate the landed manager record and fail the
2960+ // group so raw webview data cannot reach shared writes, sibling
2961+ // overlays, or task configuration.
2962+ await this . _restoreProviderManagerRecord ( name , managerSnapshot )
2963+ throw new Error (
2964+ `Provider profile '${ name } ' could not be read back after save: ${ error instanceof Error ? error . message : String ( error ) } ` ,
2965+ )
29422966 }
29432967
29442968 let activationMode : Mode | undefined
@@ -3062,6 +3086,23 @@ export class ClineProvider
30623086 throw new Error ( "You cannot delete the last profile" )
30633087 }
30643088
3089+ // Snapshot the manager record and every persistence surface this
3090+ // deletion rewrites BEFORE the manager delete commits, so a failure
3091+ // inside the write group below can be compensated instead of leaving
3092+ // the secrets-backed record gone while metadata and view pins still
3093+ // reference it.
3094+ let previousRecord : Awaited < ReturnType < ProviderSettingsManager [ "getProfile" ] > > | undefined
3095+ try {
3096+ previousRecord = await this . providerSettingsManager . getProfile ( { name : profileToDelete . name } )
3097+ } catch {
3098+ // Absent record: the idempotent not-found path below still prunes the
3099+ // stale list entry, and compensation skips the record restore.
3100+ }
3101+ const previousEntries = this . getProviderProfileEntries ( )
3102+ const previousSelection = globalSettings . currentApiConfigName
3103+ const previousSharedSettings = this . contextProxy . getProviderSettings ( )
3104+ const previousViewStates = this . getPersistedViewStates ( { fresh : true } )
3105+
30653106 // Remove the profile from the settings store (context.secrets) so it cannot be
30663107 // resurrected by a later listApiConfigMeta sync. A not-found rejection means
30673108 // the secret was already gone (e.g. pruned by an earlier run): branch on the
@@ -3081,76 +3122,150 @@ export class ClineProvider
30813122 )
30823123 }
30833124
3084- const entries = this . getProviderProfileEntries ( ) . filter ( ( { name } ) => name !== profileToDelete . name )
3085-
3086- // Write only the profile list back: replaying the full settings snapshot
3087- // captured above would also rewrite unrelated keys (including viewStates,
3088- // which ClineProvider mutates directly in storage for concurrent views)
3089- // with this view's stale cached copy.
3090- await this . contextProxy . setValue ( "listApiConfigMeta" , entries )
3091-
3092- // Resolve the surviving profile's settings so this view and any other
3093- // live view still pinned to the deleted profile can be re-pinned with
3094- // a matching configuration.
3095- let survivingSettings : ProviderSettings | undefined
30963125 try {
3097- const { name : _survivingName , ...settings } = await this . providerSettingsManager . getProfile ( {
3098- name : profileToActivate ,
3099- } )
3100- survivingSettings = settings as ProviderSettings
3101- } catch ( error ) {
3102- this . log (
3103- `[deleteProviderProfile] Unable to resolve API profile '${ profileToActivate } ': ${
3104- error instanceof Error ? error . message : String ( error )
3105- } `,
3106- )
3107- }
3108-
3109- // Capture this view's pin before any rewrite: a view pinned to the
3110- // deleted profile while the global selection points elsewhere must still be
3111- // reconfigured, or getState() would keep the deleted profile's settings under
3112- // the surviving profile's name.
3113- const viewWasPinnedToDeleted = this . viewLocalState . currentApiConfigName === profileToDelete . name
3114- const deletedWasGlobal = profileToDelete . name === globalSettings . currentApiConfigName
3115-
3116- if ( viewWasPinnedToDeleted ) {
3117- // This view's pin now dangles: re-point it. setValue also persists the
3118- // survivor to the shared store, which covers the deleted-was-global case
3119- // for every other view as well as this one.
3120- await this . setValue ( "currentApiConfigName" , profileToActivate )
3121- } else if ( deletedWasGlobal ) {
3122- // The shared selection changed, but this view's own pin still names a
3123- // surviving profile: update the shared store only, leaving the
3124- // view-local pin untouched.
3125- await this . contextProxy . setValue ( "currentApiConfigName" , profileToActivate )
3126- }
3126+ const entries = this . getProviderProfileEntries ( ) . filter ( ( { name } ) => name !== profileToDelete . name )
3127+
3128+ // Write only the profile list back: replaying the full settings snapshot
3129+ // captured above would also rewrite unrelated keys (including viewStates,
3130+ // which ClineProvider mutates directly in storage for concurrent views)
3131+ // with this view's stale cached copy.
3132+ await this . contextProxy . setValue ( "listApiConfigMeta" , entries )
3133+
3134+ // Resolve the surviving profile's settings so this view and any other
3135+ // live view still pinned to the deleted profile can be re-pinned with
3136+ // a matching configuration.
3137+ let survivingSettings : ProviderSettings | undefined
3138+ try {
3139+ const { name : _survivingName , ...settings } = await this . providerSettingsManager . getProfile ( {
3140+ name : profileToActivate ,
3141+ } )
3142+ survivingSettings = settings as ProviderSettings
3143+ } catch ( error ) {
3144+ this . log (
3145+ `[deleteProviderProfile] Unable to resolve API profile '${ profileToActivate } ': ${
3146+ error instanceof Error ? error . message : String ( error )
3147+ } `,
3148+ )
3149+ }
31273150
3128- if ( ( deletedWasGlobal || viewWasPinnedToDeleted ) && survivingSettings ) {
3129- // The deleted profile was the active one (globally, or for this view), so
3130- // the shared provider keys still carry its settings; replace them so
3131- // getState() reports the surviving profile's configuration.
3132- await this . contextProxy . setProviderSettings ( survivingSettings )
3151+ // Capture this view's pin before any rewrite: a view pinned to the
3152+ // deleted profile while the global selection points elsewhere must still be
3153+ // reconfigured, or getState() would keep the deleted profile's settings under
3154+ // the surviving profile's name.
3155+ const viewWasPinnedToDeleted = this . viewLocalState . currentApiConfigName === profileToDelete . name
3156+ const deletedWasGlobal = profileToDelete . name === globalSettings . currentApiConfigName
31333157
31343158 if ( viewWasPinnedToDeleted ) {
3135- // This view's nested overlay (viewLocalState.apiConfiguration, seeded
3136- // by loadViewState) still serves the deleted profile's configuration:
3137- // replace it with the survivor's so the re-pointed pin serves matching
3138- // settings. A view pinned to another profile keeps its own overlay.
3139- await this . _saveViewLocalStateFromMutation ( { apiConfiguration : survivingSettings } )
3159+ // This view's pin now dangles: re-point it. setValue also persists the
3160+ // survivor to the shared store, which covers the deleted-was-global case
3161+ // for every other view as well as this one.
3162+ await this . setValue ( "currentApiConfigName" , profileToActivate )
3163+ } else if ( deletedWasGlobal ) {
3164+ // The shared selection changed, but this view's own pin still names a
3165+ // surviving profile: update the shared store only, leaving the
3166+ // view-local pin untouched.
3167+ await this . contextProxy . setValue ( "currentApiConfigName" , profileToActivate )
31403168 }
3141- }
31423169
3143- // Re-pin other live views still buffered on the deleted profile: their
3144- // buffer and durable viewStates entry would otherwise keep serving the
3145- // deleted profile's name and configuration.
3146- await this . rePinViewLocalStateForDeletedProfile ( profileToDelete . name , profileToActivate , survivingSettings )
3170+ if ( ( deletedWasGlobal || viewWasPinnedToDeleted ) && survivingSettings ) {
3171+ // The deleted profile was the active one (globally, or for this view), so
3172+ // the shared provider keys still carry its settings; replace them so
3173+ // getState() reports the surviving profile's configuration.
3174+ await this . contextProxy . setProviderSettings ( survivingSettings )
3175+
3176+ if ( viewWasPinnedToDeleted ) {
3177+ // This view's nested overlay (viewLocalState.apiConfiguration, seeded
3178+ // by loadViewState) still serves the deleted profile's configuration:
3179+ // replace it with the survivor's so the re-pointed pin serves matching
3180+ // settings. A view pinned to another profile keeps its own overlay.
3181+ await this . _saveViewLocalStateFromMutation ( { apiConfiguration : survivingSettings } )
3182+ }
3183+ }
31473184
3148- // Closed views keep their durable viewStates entry after disposal: a pin
3149- // naming the deleted profile would rehydrate a missing profile name on
3150- // the next load. Re-point those persisted pins to the survivor too .
3151- await this . repointPersistedViewStates ( profileToDelete . name , profileToActivate )
3185+ // Re-pin other live views still buffered on the deleted profile: their
3186+ // buffer and durable viewStates entry would otherwise keep serving the
3187+ // deleted profile's name and configuration .
3188+ await this . rePinViewLocalStateForDeletedProfile ( profileToDelete . name , profileToActivate , survivingSettings )
31523189
3153- await this . postStateToWebview ( )
3190+ // Closed views keep their durable viewStates entry after disposal: a pin
3191+ // naming the deleted profile would rehydrate a missing profile name on
3192+ // the next load. Re-point those persisted pins to the survivor too.
3193+ await this . repointPersistedViewStates ( profileToDelete . name , profileToActivate )
3194+
3195+ await this . postStateToWebview ( )
3196+ } catch ( error ) {
3197+ // The manager delete committed but a later write failed: restore the
3198+ // deleted record first, then the shared metadata, selection, and shared
3199+ // settings the deletion had rewritten, and finally merge the affected
3200+ // persisted pins back. The merge re-reads the durable map and rewrites
3201+ // only entries that named the deleted profile in the pre-delete
3202+ // snapshot, so concurrent viewStates updates from sibling views
3203+ // survive. Each restore is independent and logged; the original
3204+ // failure is what the caller sees.
3205+ if ( previousRecord ) {
3206+ try {
3207+ const { name : _previousName , id : _previousId , ...previousSettings } = previousRecord
3208+ await this . providerSettingsManager . saveConfig ( profileToDelete . name , previousSettings )
3209+ } catch ( restoreError ) {
3210+ this . log (
3211+ `[deleteProviderProfile] failed to restore the manager record '${ profileToDelete . name } ': ${
3212+ restoreError instanceof Error ? restoreError . message : String ( restoreError )
3213+ } `,
3214+ )
3215+ }
3216+ }
3217+ try {
3218+ // Merge rather than clobber: another instance may have added
3219+ // profiles between the snapshot and the compensation.
3220+ const currentEntries = this . getProviderProfileEntries ( )
3221+ const deletedEntry = previousEntries . find ( ( entry ) => entry . name === profileToDelete . name )
3222+ if ( deletedEntry && ! currentEntries . some ( ( entry ) => entry . name === profileToDelete . name ) ) {
3223+ await this . contextProxy . setValue ( "listApiConfigMeta" , [ ...currentEntries , deletedEntry ] )
3224+ }
3225+ } catch ( restoreError ) {
3226+ this . log (
3227+ `[deleteProviderProfile] failed to restore the profile list: ${ restoreError instanceof Error ? restoreError . message : String ( restoreError ) } ` ,
3228+ )
3229+ }
3230+ try {
3231+ await this . contextProxy . setValue ( "currentApiConfigName" , previousSelection )
3232+ } catch ( restoreError ) {
3233+ this . log (
3234+ `[deleteProviderProfile] failed to restore the shared selection: ${ restoreError instanceof Error ? restoreError . message : String ( restoreError ) } ` ,
3235+ )
3236+ }
3237+ try {
3238+ await this . contextProxy . setProviderSettings ( previousSharedSettings )
3239+ } catch ( restoreError ) {
3240+ this . log (
3241+ `[deleteProviderProfile] failed to restore the shared provider settings: ${ restoreError instanceof Error ? restoreError . message : String ( restoreError ) } ` ,
3242+ )
3243+ }
3244+ try {
3245+ const restore = ClineProvider . persistedViewStateWriteQueue . then ( async ( ) => {
3246+ const current = this . getPersistedViewStates ( { fresh : true } )
3247+ const merged = { ...current }
3248+ let changed = false
3249+ for ( const [ viewId , entry ] of Object . entries ( previousViewStates ) ) {
3250+ if ( entry ?. currentApiConfigName !== profileToDelete . name ) {
3251+ continue
3252+ }
3253+ merged [ viewId ] = entry
3254+ changed = true
3255+ }
3256+ if ( changed ) {
3257+ await this . contextProxy . setValue ( "viewStates" , merged )
3258+ }
3259+ } )
3260+ ClineProvider . persistedViewStateWriteQueue = restore . catch ( ( ) => { } )
3261+ await restore
3262+ } catch ( restoreError ) {
3263+ this . log (
3264+ `[deleteProviderProfile] failed to restore the persisted view pins: ${ restoreError instanceof Error ? restoreError . message : String ( restoreError ) } ` ,
3265+ )
3266+ }
3267+ throw error
3268+ }
31543269 }
31553270
31563271 private async persistStickyProviderProfileToCurrentTask (
0 commit comments