| .. | .. |
|---|
| 100 | 100 | |
|---|
| 101 | 101 | /// Switch to a new session and load its messages. |
|---|
| 102 | 102 | Future<void> switchSession(String sessionId) async { |
|---|
| 103 | | - // Log caller for debugging |
|---|
| 104 | 103 | final trace = StackTrace.current.toString().split('\n').take(4).join(' | '); |
|---|
| 105 | 104 | TraceService.instance.addTrace( |
|---|
| 106 | 105 | 'switchSession', |
|---|
| 107 | 106 | 'from=${_currentSessionId?.substring(0, 8) ?? "null"}(${state.length}) → ${sessionId.substring(0, 8)} | $trace', |
|---|
| 108 | 107 | ); |
|---|
| 109 | | - // Write current session DIRECTLY to disk (no debounce — prevents data loss) |
|---|
| 108 | + // Write current session to disk |
|---|
| 110 | 109 | if (_currentSessionId != null && state.isNotEmpty) { |
|---|
| 111 | 110 | await MessageStore.writeDirect(_currentSessionId!, state); |
|---|
| 112 | 111 | } |
|---|
| 113 | 112 | |
|---|
| 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 | + |
|---|
| 114 | 119 | _currentSessionId = sessionId; |
|---|
| 115 | 120 | 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 | + } |
|---|
| 117 | 128 | } |
|---|
| 118 | 129 | |
|---|
| 119 | 130 | /// Add a message to the current session. |
|---|
| 120 | 131 | void addMessage(Message message) { |
|---|
| 121 | 132 | state = [...state, message]; |
|---|
| 122 | 133 | 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); |
|---|
| 125 | 135 | } |
|---|
| 126 | 136 | } |
|---|
| 127 | 137 | |
|---|