import 'dart:async'; import 'package:flutter/foundation.dart'; import '../../../core/api_gateway.dart'; import '../domain/chat_claude_accounts.dart'; import 'chat_thread_controller.dart'; /// One Claude chat's saved accounts: loads `claude_accounts` once on demand, /// switches with `claude_account_use` and saves with `claude_account_save`. /// A switch hands the new account's quota to [thread], so its usage-limit /// banner reflects the new account at once (the server also pushes it to /// every open chat on the same Claude home). class ChatClaudeAccountsController extends ChangeNotifier { ChatClaudeAccountsController({ required this.gateway, required this.sessionId, this.thread, }); final ApiGateway gateway; final String sessionId; final ChatThreadController? thread; ChatClaudeAccounts? _accounts; String? _error; Future? _loading; bool _busy = false; bool _disposed = false; /// The last reply, or null before one arrived. ChatClaudeAccounts? get accounts => _accounts; /// The last refusal (for example a chat directory with no Claude home). String? get error => _error; /// A switch or save is in flight. bool get busy => _busy; /// Loads the accounts once; later calls reuse the first load. Future ensureLoaded() => _loading ??= refresh(); Future refresh() async { try { await _run('claude_accounts', null); } catch (_) { // Recorded in [error]. } } /// Switches to the saved account [name] and returns the new active account. Future use(String name) async { final accounts = await _run('claude_account_use', name); final usage = accounts?.usage; if (usage != null) thread?.accountSwitched(usage); return accounts?.active; } /// Saves the active login as [name] ('' uses its email). Future save(String name) => _run('claude_account_save', name); Future _run(String type, String? name) async { _busy = type != 'claude_accounts'; _notify(); try { final reply = await gateway.call(type, { 'claude_account': {'session_id': sessionId, 'name': ?name}, }); final accounts = ChatClaudeAccounts.fromJson(reply['claude_accounts']); if (accounts == null) { throw StateError('The server sent no Claude accounts.'); } _accounts = accounts; _error = null; return accounts; } catch (error) { if (type == 'claude_accounts') _error = '$error'; rethrow; } finally { _busy = false; _notify(); } } void _notify() { if (!_disposed) notifyListeners(); } @override void dispose() { _disposed = true; super.dispose(); } }