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