import 'dart:async'; import 'package:flutter/foundation.dart'; import '../../../core/api_gateway.dart'; import '../../../core/error_reason.dart'; import '../data/chat_repository.dart'; import '../domain/chat_automations.dart'; import '../domain/chat_shells.dart'; /// One session's live background tasks and lazy, bounded output selection. class ChatBackgroundTasksController extends ChangeNotifier { ChatBackgroundTasksController(this.gateway, this.sessionId) { _listen(); unawaited(refresh()); unawaited(refreshAutomations()); } ApiGateway gateway; String sessionId; late ChatRepository _repository = ChatRepository(gateway); StreamSubscription? _frames; List _shells = const []; Map? _loadFrames; String? selectedId; ChatShellOutputSnapshot? output; String? error; bool loading = true; bool _disposed = false; int _generation = 0; int _outputGeneration = 0; Timer? _automationDebounce; Future? _automationRequest; bool _automationRefreshPending = false; ChatAutomationStatus _automations = const ChatAutomationStatus(); int _automationGeneration = 0; List get running => runningShells(_shells); JsonMap? get selectedShell => running.where((shell) => shellIdOf(shell) == selectedId).firstOrNull; ChatAutomationStatus get automationStatus => _automations; void replace( ApiGateway nextGateway, String nextSessionId, { bool notify = true, }) { if (_disposed) return; unawaited(_frames?.cancel()); _automationRequest = null; _automationRefreshPending = false; gateway = nextGateway; sessionId = nextSessionId; _repository = ChatRepository(gateway); _listen(); reconnect(notify: notify); } void reconnect({bool notify = true}) { if (_disposed) return; _shells = const []; selectedId = null; output = null; error = null; _outputGeneration++; _automationGeneration++; _automationRequest = null; _automationRefreshPending = false; _automationDebounce?.cancel(); _automationDebounce = null; _automations = const ChatAutomationStatus(); unawaited(refresh(notify: notify)); unawaited(refreshAutomations(notify: notify)); } void _listen() => _frames = gateway.frames.listen((envelope) { if (_disposed || envelope['type'] != 'chat_event') return; final frame = envelope['chat_event']; _scheduleAutomationRefresh(frame); if (frame is! Map || frame['session_id'] != sessionId || frame['kind'] != 'shell' || frame['shell'] is! Map) { return; } _shells = mergeShellFrame( _shells, Map.from(frame['shell'] as Map), ); final id = shellIdOf(Map.from(frame['shell'] as Map)); if (_loadFrames != null && !blankShellValue(id)) { _loadFrames![id] = _shells.firstWhere((shell) => shellIdOf(shell) == id); if (_loadFrames!.length > observedShellLimit) { _loadFrames!.remove(_loadFrames!.keys.first); } } _dropStaleSelection(); notifyListeners(); }, onError: (_) {}); void _scheduleAutomationRefresh(Object frame) { if (frame is! Map) return; if (frame['session_id'] != sessionId) return; final kind = '${frame['kind'] ?? ''}'.toLowerCase(); final step = frame['step']; final part = frame['part']; final stepEnded = kind == 'step' && step is Map && '${step['status'] ?? ''}'.toLowerCase() == 'ended'; final toolCompleted = kind == 'tool' && part is Map && (part['state'] is Map) && { 'completed', 'error', }.contains('${(part['state'] as Map)['status'] ?? ''}'.toLowerCase()); if (!stepEnded && !toolCompleted) { return; } if (_automationRequest != null) _automationRefreshPending = true; _automationDebounce?.cancel(); _automationDebounce = Timer(const Duration(milliseconds: 250), () { _automationDebounce = null; unawaited(refreshAutomations()); }); } Future refresh({bool notify = true}) async { if (_disposed) return; final token = ++_generation; final observed = {}; _loadFrames = observed; loading = true; if (notify) notifyListeners(); try { final shells = await _repository.shells(sessionId); if (_disposed || token != _generation) return; _shells = shellsLoaded(_shells, shells); // Live frames are newer than a snapshot requested before they arrived. for (final frame in observed.values) { _shells = mergeShellFrame(_shells, frame); } error = null; _dropStaleSelection(); } catch (failure) { if (_disposed || token != _generation) return; error = describeErrorReason( failure, fallback: 'The server did not answer.', ); } loading = false; _loadFrames = null; notifyListeners(); } Future refreshAutomations({bool notify = true}) async { if (_disposed) return; if (_automationRequest != null) { _automationRefreshPending = true; return; } final token = ++_automationGeneration; final request = _readAutomations(token, notify: notify); _automationRequest = request; try { await request; } finally { if (identical(_automationRequest, request)) { _automationRequest = null; if (_automationRefreshPending && !_disposed) { _automationRefreshPending = false; _automationDebounce?.cancel(); _automationDebounce = Timer(const Duration(milliseconds: 250), () { _automationDebounce = null; unawaited(refreshAutomations()); }); } } } } Future _readAutomations(int token, {required bool notify}) async { final repository = _repository; final id = sessionId; // A legacy gateway can throw before returning a Future. Always cross an // async boundary before notifying listeners, including didUpdateWidget. await Future.value(); if (_disposed || token != _automationGeneration) return; final previous = _automations; try { final reply = await repository.automations(id); if (_disposed || token != _automationGeneration) return; _automations = ChatAutomationStatus.fromReply( reply, expectedSessionId: id, ); } catch (_) { // Older servers do not know this optional command. Keep shell state // usable and present capability absence in the inspector instead. if (_disposed || token != _automationGeneration) return; _automations = const ChatAutomationStatus(); } // Unsupported/unknown is intentionally quiet in the composer; supported // reports need to reveal their positive count. final changed = previous.supported != _automations.supported || previous.count != _automations.count || previous.reason != _automations.reason || previous.observedAt != _automations.observedAt; if (changed || (notify && _automations.supported)) { notifyListeners(); } } void _dropStaleSelection() { if (selectedId == null || selectedShell != null) return; selectedId = null; output = null; _outputGeneration++; } void select(String id) { if (_disposed) return; if (selectedId == id) { selectedId = null; output = null; _outputGeneration++; notifyListeners(); return; } if (!running.any((shell) => shellIdOf(shell) == id)) return; selectedId = id; unawaited(readOutput()); } Future readOutput() async { final id = selectedId; if (_disposed || id == null) return; final token = ++_outputGeneration; output = const ChatShellOutputSnapshot(loading: true); notifyListeners(); try { final reply = await _repository.shellOutput( sessionId, id, cursor: 0, limit: chatShellOutputLimit, ); if (_disposed || token != _outputGeneration || selectedId != id) return; final page = ChatShellOutputPage.fromReply(reply); if (page.shell case final shell? when !blankShellValue(shell['id'])) { _shells = mergeShellFrame(_shells, shell); } output = ChatShellOutputSnapshot(page: page); _dropStaleSelection(); } catch (failure) { if (_disposed || token != _outputGeneration || selectedId != id) return; output = ChatShellOutputSnapshot( error: describeErrorReason( failure, fallback: 'The server did not answer.', ), ); } notifyListeners(); } @override void dispose() { _disposed = true; _generation++; _outputGeneration++; _automationGeneration++; _automationDebounce?.cancel(); _automationDebounce = null; _automationRequest = null; _automationRefreshPending = false; unawaited(_frames?.cancel()); super.dispose(); } }