@@ -2268,6 +2268,10 @@ export class ClineProvider
22682268 ) : Promise < void > {
22692269 const task = targetTask
22702270
2271+ // Captured for the reconcile below: the mode this task held before
2272+ // the switch (bracket access: _taskMode is private to Task).
2273+ const previousTaskMode = task ? task [ "_taskMode" ] : undefined
2274+ let rollbackTaskWrites : ( ( ) => Promise < void > ) | undefined
22712275 // A cancelled or timed-out switch must not be partially applied: bail out
22722276 // before the task history / _taskMode writes as well as the durable mode
22732277 // write below. Aborts that land while the history write is in flight are
@@ -2313,6 +2317,21 @@ export class ClineProvider
23132317
23142318 // Only update the task's mode after successful persistence.
23152319 ; ( task as any ) . _taskMode = newMode
2320+
2321+ // If a later write fails after these task-side writes landed, restore
2322+ // them: the caller delivers the message on the caught error, and the
2323+ // new task mode must not run against the view's unchanged mode and
2324+ // mode-linked API configuration.
2325+ const historyItemBefore = taskHistoryItem
2326+ rollbackTaskWrites = async ( ) => {
2327+ task [ "_taskMode" ] = previousTaskMode
2328+ if ( historyItemBefore ) {
2329+ // Restore only the field this switch changed: re-read the item so
2330+ // fields the running task persisted during the write survive.
2331+ const latest = this . getTaskHistoryItem ( task . taskId ) ?? historyItemBefore
2332+ await this . updateTaskHistory ( { ...latest , mode : historyItemBefore . mode } )
2333+ }
2334+ }
23162335 } catch ( error ) {
23172336 // If persistence fails, log the error but don't update the in-memory state.
23182337 this . log (
@@ -2336,21 +2355,26 @@ export class ClineProvider
23362355 // mode, broadcasting ModeChanged, or activating a profile on behalf of a
23372356 // background task would clobber the focused task's selection.
23382357 const viewScopedSwitch = task === undefined || task === null || this . getCurrentTask ( ) === task
2339- if ( viewScopedSwitch ) {
2340- // Pin the view's durable per-view mode first: the pin is this view's own
2341- // selection and must not be undone if the shared write later fails.
2342- await this . saveViewState ( "mode" , newMode )
2343-
2344- // setValue (not the deprecated updateGlobalState) so the in-memory viewLocalState
2345- // buffer stays in sync with the durable global write: getValues() merges
2346- // viewLocalState on top of the ContextProxy values, so an unsynced stale
2347- // restored mode would otherwise shadow the fresh switch for consumers.
2348- // If the durable write fails, roll the shared write back so getValues()
2349- // cannot mix a fresh shared mode with the stale pre-switch buffer.
2350- const previousMode = this . getValue ( "mode" )
2351- try {
2352- await this . setValue ( "mode" , newMode )
2353- } catch ( error ) {
2358+ // Captured for the reconcile below: the view's pre-switch durable mode pin
2359+ // (undefined means the view never pinned a mode) and the pre-switch shared
2360+ // mode. The pin write only touches the view buffer and the per-view store, so
2361+ // reading the shared value here is unaffected by it.
2362+ const previousViewMode = this . viewLocalState . mode
2363+ const previousMode = this . getValue ( "mode" )
2364+ let pinLanded = false
2365+ let sharedAttempted = false
2366+
2367+ // Explicit partial-failure behavior: every failure after the task-mode write
2368+ // rolls back all writes this switch owns - shared mode, view pin, task mode,
2369+ // and the task-history entry - so the caller (Task#submitUserMessage) delivers
2370+ // the submitted message on the pre-switch mode and profile instead of a
2371+ // half-applied switch that runs the new mode against the unchanged profile.
2372+ // Each restore is awaited on its own and logged on failure, never swallowed.
2373+ const reconcileSwitchWrites = async ( ) => {
2374+ if ( sharedAttempted ) {
2375+ // The shared write may have landed before its promise rejected: restore
2376+ // it unconditionally so getValues() cannot mix a fresh shared mode with
2377+ // the rolled-back view state.
23542378 try {
23552379 await this . contextProxy . setValue ( "mode" , previousMode )
23562380 } catch ( rollbackError ) {
@@ -2360,81 +2384,123 @@ export class ClineProvider
23602384 } `,
23612385 )
23622386 }
2363- this . log (
2364- `[handleModeSwitch] Failed to persist mode "${ newMode } ": ${ error instanceof Error ? error . message : String ( error ) } ` ,
2365- )
2366- throw error
23672387 }
2368-
2369- this . emit ( RooCodeEventName . ModeChanged , newMode )
2388+ if ( pinLanded ) {
2389+ try {
2390+ await this . saveViewState ( "mode" , previousViewMode )
2391+ } catch ( rollbackError ) {
2392+ this . log (
2393+ `[handleModeSwitch] Failed to roll back the view mode pin after persistence failure: ${
2394+ rollbackError instanceof Error ? rollbackError . message : String ( rollbackError )
2395+ } `,
2396+ )
2397+ }
2398+ }
2399+ if ( rollbackTaskWrites ) {
2400+ try {
2401+ await rollbackTaskWrites ( )
2402+ } catch ( rollbackError ) {
2403+ this . log (
2404+ `[handleModeSwitch] Failed to roll back task mode writes after the view mode pin write failed: ${
2405+ rollbackError instanceof Error ? rollbackError . message : String ( rollbackError )
2406+ } `,
2407+ )
2408+ }
2409+ }
23702410 }
23712411
2372- // If workspace lock is on, keep the current API config — don't load mode-specific config
2373- const lockApiConfigAcrossModes = this . context . workspaceState . get ( "lockApiConfigAcrossModes" , false )
2374- if ( lockApiConfigAcrossModes ) {
2375- // Keep the original post semantics: an explicit null target (pending child)
2376- // posts its own state.
2377- if ( targetTask !== null ) {
2378- await this . postStateToWebview ( )
2412+ try {
2413+ if ( viewScopedSwitch ) {
2414+ // Pin the view's durable per-view mode first: the pin is this view's own
2415+ // selection. If any write below fails, the reconcile above restores every
2416+ // write that landed, including this pin, so a delivered message never runs
2417+ // the new task mode against an unchanged view mode or mode-linked profile.
2418+ await this . saveViewState ( "mode" , newMode )
2419+ pinLanded = true
2420+
2421+ // setValue (not the deprecated updateGlobalState) so the in-memory viewLocalState
2422+ // buffer stays in sync with the durable global write: getValues() merges
2423+ // viewLocalState on top of the ContextProxy values, so an unsynced stale
2424+ // restored mode would otherwise shadow the fresh switch for consumers.
2425+ sharedAttempted = true
2426+ await this . setValue ( "mode" , newMode )
2427+
2428+ this . emit ( RooCodeEventName . ModeChanged , newMode )
23792429 }
2380- return
2381- }
23822430
2383- if ( signal ?. aborted ) return
2384- if ( ! viewScopedSwitch ) {
2385- return
2386- }
2431+ // If workspace lock is on, keep the current API config — don't load mode-specific config
2432+ const lockApiConfigAcrossModes = this . context . workspaceState . get ( "lockApiConfigAcrossModes" , false )
2433+ if ( lockApiConfigAcrossModes ) {
2434+ // Keep the original post semantics: an explicit null target (pending child)
2435+ // posts its own state.
2436+ if ( targetTask !== null ) {
2437+ await this . postStateToWebview ( )
2438+ }
2439+ return
2440+ }
23872441
2388- // Load the saved API config for the new mode if it exists.
2389- const savedConfigId = await this . providerSettingsManager . getModeConfigId ( newMode )
2390- const listApiConfig = await this . providerSettingsManager . listConfig ( )
2442+ if ( signal ?. aborted ) return
2443+ if ( ! viewScopedSwitch ) {
2444+ return
2445+ }
23912446
2392- if ( signal ?. aborted ) return
2447+ // Load the saved API config for the new mode if it exists.
2448+ const savedConfigId = await this . providerSettingsManager . getModeConfigId ( newMode )
2449+ const listApiConfig = await this . providerSettingsManager . listConfig ( )
23932450
2394- // Update listApiConfigMeta first to ensure UI has latest data.
2395- await this . updateGlobalState ( "listApiConfigMeta" , listApiConfig )
2451+ if ( signal ?. aborted ) return
23962452
2397- // If this mode has a saved config, use it.
2398- if ( savedConfigId ) {
2399- const profile = listApiConfig . find ( ( { id } ) => id === savedConfigId )
2453+ // Update listApiConfigMeta first to ensure UI has latest data.
2454+ await this . updateGlobalState ( "listApiConfigMeta" , listApiConfig )
24002455
2401- if ( profile ?. name ) {
2402- // Check if the profile has actual API configuration (not just an id).
2403- // In CLI mode, the ProviderSettingsManager may return empty default profiles
2404- // that only contain 'id' and 'name' fields. Activating such a profile would
2405- // overwrite the CLI's working API configuration with empty settings.
2406- // Skip activation if the profile has no apiProvider set - this indicates
2407- // an unconfigured/empty profile.
2408- const fullProfile = await this . providerSettingsManager . getProfile ( { name : profile . name } )
2409- const hasActualSettings = ! ! fullProfile . apiProvider
2410-
2411- if ( hasActualSettings ) {
2412- await this . activateProviderProfileUnlocked (
2413- { name : profile . name } ,
2414- targetTask === null ? { skipCurrentTaskRebuild : true } : undefined ,
2415- signal ,
2416- )
2456+ // If this mode has a saved config, use it.
2457+ if ( savedConfigId ) {
2458+ const profile = listApiConfig . find ( ( { id } ) => id === savedConfigId )
2459+
2460+ if ( profile ?. name ) {
2461+ // Check if the profile has actual API configuration (not just an id).
2462+ // In CLI mode, the ProviderSettingsManager may return empty default profiles
2463+ // that only contain 'id' and 'name' fields. Activating such a profile would
2464+ // overwrite the CLI's working API configuration with empty settings.
2465+ // Skip activation if the profile has no apiProvider set - this indicates
2466+ // an unconfigured/empty profile.
2467+ const fullProfile = await this . providerSettingsManager . getProfile ( { name : profile . name } )
2468+ const hasActualSettings = ! ! fullProfile . apiProvider
2469+
2470+ if ( hasActualSettings ) {
2471+ await this . activateProviderProfileUnlocked (
2472+ { name : profile . name } ,
2473+ targetTask === null ? { skipCurrentTaskRebuild : true } : undefined ,
2474+ signal ,
2475+ )
2476+ } else {
2477+ // The task will continue with the current/default configuration.
2478+ }
24172479 } else {
24182480 // The task will continue with the current/default configuration.
24192481 }
24202482 } else {
2421- // The task will continue with the current/default configuration.
2422- }
2423- } else {
2424- // If no saved config for this mode, save current config as default.
2425- const currentApiConfigNameAfter = this . getGlobalState ( "currentApiConfigName" )
2483+ // If no saved config for this mode, save current config as default.
2484+ const currentApiConfigNameAfter = this . getGlobalState ( "currentApiConfigName" )
24262485
2427- if ( currentApiConfigNameAfter ) {
2428- const config = listApiConfig . find ( ( c ) => c . name === currentApiConfigNameAfter )
2486+ if ( currentApiConfigNameAfter ) {
2487+ const config = listApiConfig . find ( ( c ) => c . name === currentApiConfigNameAfter )
24292488
2430- if ( config ?. id ) {
2431- await this . providerSettingsManager . setModeConfig ( newMode , config . id )
2489+ if ( config ?. id ) {
2490+ await this . providerSettingsManager . setModeConfig ( newMode , config . id )
2491+ }
24322492 }
24332493 }
2434- }
24352494
2436- if ( targetTask !== null ) {
2437- await this . postStateToWebview ( )
2495+ if ( targetTask !== null ) {
2496+ await this . postStateToWebview ( )
2497+ }
2498+ } catch ( error ) {
2499+ await reconcileSwitchWrites ( )
2500+ this . log (
2501+ `[handleModeSwitch] Failed to persist mode "${ newMode } ": ${ error instanceof Error ? error . message : String ( error ) } ` ,
2502+ )
2503+ throw error
24382504 }
24392505 }
24402506
@@ -2567,7 +2633,13 @@ export class ClineProvider
25672633 // serving the settings captured before the save under the same name.
25682634 if ( this . pinnedProfileName === name ) {
25692635 await this . _saveViewLocalStateFromMutation ( { apiConfiguration : providerSettings } )
2570- this . updateTaskApiHandlerIfNeeded ( providerSettings , { forceRebuild : true } )
2636+ // Only rebuild when the task actually runs under the saved profile: a
2637+ // view pinned to this profile can hold a task that follows a different
2638+ // sticky profile, and the forced rebuild would silently switch that
2639+ // conversation to the saved profile's settings.
2640+ if ( this . getCurrentTask ( ) ?. taskApiConfigName === name ) {
2641+ this . updateTaskApiHandlerIfNeeded ( providerSettings , { forceRebuild : true } )
2642+ }
25712643 }
25722644 await this . refreshViewLocalStateForUpdatedProfile ( name , providerSettings )
25732645 }
@@ -2921,9 +2993,13 @@ export class ClineProvider
29212993 // The active task of a pinned view holds its own API handler built from
29222994 // the profile's settings: rebuild it with the saved settings or the
29232995 // running conversation keeps sending the old token even though the
2924- // view's buffer has caught up. Direct private access across sibling
2925- // instances of the same class is compile-time safe.
2926- instance . updateTaskApiHandlerIfNeeded ( providerSettings , { forceRebuild : true } )
2996+ // view's buffer has caught up. Only rebuild when the task actually runs
2997+ // under the saved profile: a task that follows a different sticky
2998+ // profile must keep its own settings. Direct private access across
2999+ // sibling instances of the same class is compile-time safe.
3000+ if ( instance . getCurrentTask ( ) ?. taskApiConfigName === name ) {
3001+ instance . updateTaskApiHandlerIfNeeded ( providerSettings , { forceRebuild : true } )
3002+ }
29273003 await instance . postStateToWebview ( )
29283004 } ) ,
29293005 )
0 commit comments