@@ -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 )
0 commit comments