| .. | .. |
|---|
| 9 | 9 | import '../models/server_config.dart'; |
|---|
| 10 | 10 | import '../models/session.dart'; |
|---|
| 11 | 11 | import '../services/message_store.dart'; |
|---|
| 12 | +import '../services/trace_service.dart'; |
|---|
| 12 | 13 | import '../services/mqtt_service.dart' show ConnectionStatus; |
|---|
| 13 | 14 | import '../services/navigate_notifier.dart'; |
|---|
| 14 | 15 | |
|---|
| .. | .. |
|---|
| 99 | 100 | |
|---|
| 100 | 101 | /// Switch to a new session and load its messages. |
|---|
| 101 | 102 | Future<void> switchSession(String sessionId) async { |
|---|
| 103 | + // Log caller for debugging |
|---|
| 104 | + final trace = StackTrace.current.toString().split('\n').take(4).join(' | '); |
|---|
| 105 | + TraceService.instance.addTrace( |
|---|
| 106 | + 'switchSession', |
|---|
| 107 | + 'from=${_currentSessionId?.substring(0, 8) ?? "null"}(${state.length}) → ${sessionId.substring(0, 8)} | $trace', |
|---|
| 108 | + ); |
|---|
| 102 | 109 | // Write current session DIRECTLY to disk (no debounce — prevents data loss) |
|---|
| 103 | 110 | if (_currentSessionId != null && state.isNotEmpty) { |
|---|
| 104 | 111 | await MessageStore.writeDirect(_currentSessionId!, state); |
|---|
| .. | .. |
|---|
| 113 | 120 | void addMessage(Message message) { |
|---|
| 114 | 121 | state = [...state, message]; |
|---|
| 115 | 122 | if (_currentSessionId != null) { |
|---|
| 116 | | - MessageStore.save(_currentSessionId!, state); |
|---|
| 123 | + // Write immediately (not debounced) to prevent race with switchSession's loadAll |
|---|
| 124 | + MessageStore.writeDirect(_currentSessionId!, state); |
|---|
| 117 | 125 | } |
|---|
| 118 | 126 | } |
|---|
| 119 | 127 | |
|---|