@@ -132,10 +132,20 @@ export function createSessionStore(options: {
132132 mark ( "calling session.messages" ) ;
133133 const msgs = unwrap ( await withTimeout ( c . session . messages ( { sessionID } ) , 12_000 , "session.messages" ) ) ;
134134 mark ( "session.messages done" ) ;
135+ // If the selected session changed while we were waiting, abort to avoid
136+ // overwriting a newer selection's state.
137+ if ( options . selectedSessionId ( ) !== sessionID ) {
138+ mark ( "aborting: selection changed before messages applied" ) ;
139+ return ;
140+ }
135141 setMessages ( msgs ) ;
136142
137143 const model = options . lastUserModelFromMessages ( msgs ) ;
138144 if ( model ) {
145+ if ( options . selectedSessionId ( ) !== sessionID ) {
146+ mark ( "aborting: selection changed before model applied" ) ;
147+ return ;
148+ }
139149 options . setSessionModelState ( ( current ) => ( {
140150 overrides : current . overrides ,
141151 resolved : { ...current . resolved , [ sessionID ] : model } ,
@@ -151,8 +161,13 @@ export function createSessionStore(options: {
151161
152162 try {
153163 mark ( "calling session.todo" ) ;
154- setTodos ( unwrap ( await withTimeout ( c . session . todo ( { sessionID } ) , 8_000 , "session.todo" ) ) ) ;
164+ const todoList = unwrap ( await withTimeout ( c . session . todo ( { sessionID } ) , 8_000 , "session.todo" ) ) ;
155165 mark ( "session.todo done" ) ;
166+ if ( options . selectedSessionId ( ) !== sessionID ) {
167+ mark ( "aborting: selection changed before todos applied" ) ;
168+ return ;
169+ }
170+ setTodos ( todoList ) ;
156171 } catch {
157172 mark ( "session.todo failed/timeout" ) ;
158173 setTodos ( [ ] ) ;
@@ -162,6 +177,10 @@ export function createSessionStore(options: {
162177 mark ( "calling permission.list" ) ;
163178 await withTimeout ( refreshPendingPermissions ( ) , 6_000 , "permission.list" ) ;
164179 mark ( "permission.list done" ) ;
180+ if ( options . selectedSessionId ( ) !== sessionID ) {
181+ mark ( "aborting: selection changed before permissions applied" ) ;
182+ return ;
183+ }
165184 } catch {
166185 mark ( "permission.list failed/timeout" ) ;
167186 }
0 commit comments