Matthias Nott
9 days ago 06bb73662d32d65d1e775a4dd35f67d82d673e40
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import '../models/message.dart';
import '../models/server_config.dart';
import '../models/session.dart';
import '../services/message_store.dart';
import '../services/trace_service.dart';
import '../services/mqtt_service.dart' show ConnectionStatus;
import '../services/navigate_notifier.dart';
// --- Enums ---
enum InputMode { voice, text }
// --- Theme ---
final themeModeProvider = StateProvider<ThemeMode>((ref) => ThemeMode.dark);
// --- Server Config ---
final serverConfigProvider =
    StateNotifierProvider<ServerConfigNotifier, ServerConfig?>((ref) {
  return ServerConfigNotifier();
});
class ServerConfigNotifier extends StateNotifier<ServerConfig?> {
  ServerConfigNotifier() : super(null) {
    _load();
  }
  static const _storage = FlutterSecureStorage();
  static const _key = 'server_config';
  Future<void> _load() async {
    try {
      final json = await _storage.read(key: _key);
      if (json != null) {
        state = ServerConfig.fromJson(jsonDecode(json) as Map<String, dynamic>);
      }
    } catch (e) {
      debugPrint('ServerConfig load failed: $e');
    }
  }
  Future<void> save(ServerConfig config) async {
    state = config;
    await _storage.write(key: _key, value: jsonEncode(config.toJson()));
  }
  Future<void> clear() async {
    state = null;
    await _storage.delete(key: _key);
  }
}
// --- Connection Status ---
final wsStatusProvider =
    StateProvider<ConnectionStatus>((ref) => ConnectionStatus.disconnected);
final connectionDetailProvider = StateProvider<String>((ref) => '');
final connectedViaProvider = StateProvider<String>((ref) => '');
// --- Sessions ---
final sessionsProvider = StateProvider<List<Session>>((ref) => []);
final activeSessionIdProvider = StateProvider<String?>((ref) => null);
final activeSessionProvider = Provider<Session?>((ref) {
  final sessions = ref.watch(sessionsProvider);
  final activeId = ref.watch(activeSessionIdProvider);
  if (activeId == null) return null;
  try {
    return sessions.firstWhere((s) => s.id == activeId);
  } catch (_) {
    return sessions.isNotEmpty ? sessions.first : null;
  }
});
// --- Messages ---
final messagesProvider =
    StateNotifierProvider<MessagesNotifier, List<Message>>((ref) {
  return MessagesNotifier(ref);
});
class MessagesNotifier extends StateNotifier<List<Message>> {
  MessagesNotifier(this.ref) : super([]);
  final Ref ref;
  String? _currentSessionId;
  String? get currentSessionId => _currentSessionId;
  /// Switch to a session. SYNCHRONOUS — no async gap, no race with incoming
  /// messages. MessageStoreV2.loadSession reads from the in-memory index.
  void switchSession(String sessionId) {
    if (_currentSessionId == sessionId) {
      TraceService.instance.addTrace(
          'switchSession SKIP', 'already on ${sessionId.substring(0, 8)}');
      return;
    }
    TraceService.instance.addTrace(
      'switchSession',
      'from=${_currentSessionId?.substring(0, 8) ?? "null"}(${state.length}) → ${sessionId.substring(0, 8)}',
    );
    _currentSessionId = sessionId;
    state = MessageStoreV2.loadSession(sessionId);
  }
  /// Add a message to the current session (display + append-only persist).
  void addMessage(Message message) {
    state = [...state, message];
    if (_currentSessionId != null) {
      MessageStoreV2.append(_currentSessionId!, message);
    }
  }
  /// Update a message by ID (in-memory only — patch is not persisted to log).
  void updateMessage(String id, Message Function(Message) updater) {
    state = state.map((m) => m.id == id ? updater(m) : m).toList();
  }
  /// Remove a message by ID (in-memory only).
  void removeMessage(String id) {
    state = state.where((m) => m.id != id).toList();
  }
  /// Remove all messages matching a predicate (in-memory only).
  void removeWhere(bool Function(Message) test) {
    state = state.where((m) => !test(m)).toList();
  }
  /// Clear all messages for the current session (in-memory only).
  void clearMessages() {
    state = [];
  }
  void updateContent(String messageId, String content) {
    state = [
      for (final m in state)
        if (m.id == messageId)
          Message(
            id: m.id,
            role: m.role,
            type: m.type,
            content: content,
            audioUri: m.audioUri,
            imageBase64: m.imageBase64,
            timestamp: m.timestamp,
            status: m.status,
            duration: m.duration,
          )
        else
          m,
    ];
  }
}
// --- Typing Indicator ---
final isTypingProvider = StateProvider<bool>((ref) => false);
// --- Screenshot ---
final latestScreenshotProvider = StateProvider<String?>((ref) => null);
// --- Unread Counts ---
final unreadCountsProvider =
    StateProvider<Map<String, int>>((ref) => {});
// --- Input Mode ---
final inputModeProvider = StateProvider<InputMode>((ref) => InputMode.voice);
// --- MQTT Service (singleton) ---
// The MqttService is managed manually in the chat screen.
// --- Navigate Notifier ---
// Holds the bridge between NavigateScreen and ChatScreen's MQTT service.
// ChatScreen sets this when MQTT is initialized; NavigateScreen reads it.
// Using a Riverpod provider eliminates the stale static reference risk.
final navigateNotifierProvider = StateProvider<NavigateNotifier?>((ref) => null);
// --- Pro / Purchase Status ---
/// Whether the user has purchased PAILot Pro (full access).
/// Defaults to true — PurchaseService sets to false after StoreKit verification
/// confirms no purchase. This way dev/sideloaded builds work without IAP.
final isProProvider = StateProvider<bool>((ref) => true);