Matthias Nott
9 days ago 6cbbea9b96db551e5c0ac26f0ace3d4c3d82a276
lib/providers/providers.dart
....@@ -100,28 +100,38 @@
100100
101101 /// Switch to a new session and load its messages.
102102 Future<void> switchSession(String sessionId) async {
103
- // Log caller for debugging
104103 final trace = StackTrace.current.toString().split('\n').take(4).join(' | ');
105104 TraceService.instance.addTrace(
106105 'switchSession',
107106 'from=${_currentSessionId?.substring(0, 8) ?? "null"}(${state.length}) → ${sessionId.substring(0, 8)} | $trace',
108107 );
109
- // Write current session DIRECTLY to disk (no debounce — prevents data loss)
108
+ // Write current session to disk
110109 if (_currentSessionId != null && state.isNotEmpty) {
111110 await MessageStore.writeDirect(_currentSessionId!, state);
112111 }
113112
113
+ // Skip reload if staying on the same session — messages are already in memory
114
+ if (_currentSessionId == sessionId) {
115
+ TraceService.instance.addTrace('switchSession SKIP', 'already on ${sessionId.substring(0, 8)}');
116
+ return;
117
+ }
118
+
114119 _currentSessionId = sessionId;
115120 final messages = await MessageStore.loadAll(sessionId);
116
- state = messages;
121
+ // Merge: if addMessage ran during loadAll and added messages for THIS session,
122
+ // they'll be in state but not in the loaded messages. Keep the longer list.
123
+ if (state.length > messages.length && _currentSessionId == sessionId) {
124
+ TraceService.instance.addTrace('switchSession MERGE', 'kept ${state.length} (loaded ${messages.length})');
125
+ } else {
126
+ state = messages;
127
+ }
117128 }
118129
119130 /// Add a message to the current session.
120131 void addMessage(Message message) {
121132 state = [...state, message];
122133 if (_currentSessionId != null) {
123
- // Write immediately (not debounced) to prevent race with switchSession's loadAll
124
- MessageStore.writeDirect(_currentSessionId!, state);
134
+ MessageStore.save(_currentSessionId!, state);
125135 }
126136 }
127137