@@ -3298,10 +3298,13 @@ export default function ChatView(props: ChatViewProps) {
32983298 const pending = environmentChangeRef . current ;
32993299 return pending !== null && pending . scope === environmentChangeScopeRef . current ? pending : null ;
33003300 } ;
3301- const [ environmentChangingScope , setEnvironmentChangingScope ] = useState < string | null > ( null ) ;
3302- const isEnvironmentChanging = environmentChangingScope === environmentChangeScope ;
3303- const setIsEnvironmentChanging = ( changing : boolean ) =>
3304- setEnvironmentChangingScope ( changing ? environmentChangeScope : null ) ;
3301+ // The busy state belongs to the request that set it, so an older request settling late
3302+ // (abandoned, or superseded by a newer switch) can never clear a newer one's.
3303+ const [ busyEnvironmentChange , setBusyEnvironmentChange ] = useState < {
3304+ readonly environmentId : EnvironmentId ;
3305+ readonly scope : string ;
3306+ } | null > ( null ) ;
3307+ const isEnvironmentChanging = busyEnvironmentChange ?. scope === environmentChangeScope ;
33053308
33063309 const onEnvironmentChange = ( nextEnvironmentId : EnvironmentId ) => {
33073310 if ( envLocked || ! draftId || sendInFlightRef . current ) return ;
@@ -3313,7 +3316,7 @@ export default function ChatView(props: ChatViewProps) {
33133316 if ( ! target ) return ;
33143317 const request = { environmentId : target . environmentId , scope : environmentChangeScope } ;
33153318 environmentChangeRef . current = request ;
3316- setIsEnvironmentChanging ( false ) ;
3319+ setBusyEnvironmentChange ( null ) ;
33173320 const retarget = ( project : ( typeof allProjects ) [ number ] ) => {
33183321 const currentDraft = getDraftSession ( draftId ) ;
33193322 if (
@@ -3344,9 +3347,7 @@ export default function ChatView(props: ChatViewProps) {
33443347 } ;
33453348 const finish = ( ) => {
33463349 if ( environmentChangeRef . current === request ) environmentChangeRef . current = null ;
3347- // Clear the busy state even when the request was abandoned, or returning
3348- // to that draft would show it busy forever.
3349- setEnvironmentChangingScope ( ( scope ) => ( scope === request . scope ? null : scope ) ) ;
3350+ setBusyEnvironmentChange ( ( busy ) => ( busy === request ? null : busy ) ) ;
33503351 } ;
33513352 if ( target . projectId !== null ) {
33523353 const project = allProjects . find (
@@ -3357,7 +3358,7 @@ export default function ChatView(props: ChatViewProps) {
33573358 finish ( ) ;
33583359 return ;
33593360 }
3360- setIsEnvironmentChanging ( true ) ;
3361+ setBusyEnvironmentChange ( request ) ;
33613362 void openScratchProject ( target . environmentId , "Could not switch machine" )
33623363 . then ( ( project ) => {
33633364 if ( project ) retarget ( project ) ;
0 commit comments