import 'dart:async'; import 'package:flutter/foundation.dart'; import '../../../core/api_gateway.dart'; import '../../../core/error_reason.dart'; import 'chat_shell_run.dart'; import 'chat_shell_runs_repository.dart'; /// Where one run's "Send to agent" stands. enum ChatShellShareState { idle, sending, sent } /// One chat's operator shell commands: the recorded runs, their live output /// from `chat_shell_run_event` frames, and the card actions. /// /// It notifies on every change (cards listen to it); [membership] notifies /// only when the set of runs changes, so the transcript is not rebuilt for /// every output chunk. class ChatShellRunsController extends ChangeNotifier { ChatShellRunsController(this.gateway, this.sessionId) : _repository = ChatShellRunsRepository(gateway) { _frames = gateway.frames.listen(_onFrame, onError: (_) {}); unawaited(refresh()); } final ApiGateway gateway; final String sessionId; final ChatShellRunsRepository _repository; StreamSubscription? _frames; final Map _runs = {}; final ValueNotifier _membership = ValueNotifier(0); final Set _stopping = {}; final Map _shares = {}; final Map _errors = {}; bool _disposed = false; int _generation = 0; Listenable get membership => _membership; List get runs => List.unmodifiable(_runs.values); ChatShellRun? run(String id) => _runs[id]; bool stopping(String id) => _stopping.contains(id); ChatShellShareState shareState(String id) => _shares[id] ?? ChatShellShareState.idle; /// The last refused card action of [id], in the server's words. String? errorFor(String id) => _errors[id]; /// Reads the recorded runs again (open, reconnect). Runs this copy holds /// with newer output than the readback keep their own copy. Future refresh() async { final token = ++_generation; try { final listed = await _repository.runs(sessionId); if (_disposed || token != _generation) return; for (final run in listed) { final held = _runs[run.id]; _runs[run.id] = held != null && held.outputEnd > run.outputEnd ? held.withLifecycle(run) : run; } _changed(membership: true); } catch (_) { // An older server has no shell commands; the transcript is unchanged. } } /// Starts [command] in the chat's directory. Returns the refusal, or null. Future start(String command) async { try { final run = await _repository.run(sessionId, command); if (_disposed) return null; _runs.putIfAbsent(run.id, () => run); _changed(membership: true); return null; } catch (error) { return _reason(error); } } Future stop(String id) async { if (_stopping.contains(id)) return; _stopping.add(id); _errors.remove(id); _changed(); try { await _repository.stop(sessionId, id); } catch (error) { _stopping.remove(id); _errors[id] = _reason(error); _changed(); } } /// Queues the run's command and output tail as an ordinary prompt. Future share(String id) async { if (shareState(id) == ChatShellShareState.sending) return; _shares[id] = ChatShellShareState.sending; _errors.remove(id); _changed(); try { await _repository.share(sessionId, id); _shares[id] = ChatShellShareState.sent; } catch (error) { _shares.remove(id); _errors[id] = _reason(error); } _changed(); } /// Every byte the server retained for [id]: what Copy output copies and /// Show all draws. Null when it cannot be read (the error is recorded). Future loadAll(String id) async { final held = _runs[id]; if (held == null) return null; if (!held.truncated && !held.running) return held; try { final full = await _repository.output(sessionId, id); if (_disposed) return null; final latest = _runs[id] ?? held; // A frame newer than the read keeps the card's own lifecycle facts. final merged = full.withLifecycle(latest.running ? full : latest); _runs[id] = merged; _changed(); return merged; } catch (error) { _errors[id] = _reason(error); _changed(); return null; } } void _onFrame(JsonMap envelope) { if (_disposed || envelope['type'] != 'chat_shell_run_event') return; final frame = envelope['chat_shell_run_event']; if (frame is! Map || frame['session_id'] != sessionId) return; final id = '${frame['run_id'] ?? ''}'; final record = ChatShellRun.fromJson(frame['run']); if (record != null) { final held = _runs[record.id]; _runs[record.id] = held == null ? record : held.withLifecycle(record); if (!record.running) _stopping.remove(record.id); _changed(membership: held == null); return; } final held = _runs[id]; if (held == null) { // Output for a run this copy has not seen yet: read the record. unawaited(refresh()); return; } _runs[id] = held.withChunk( '${frame['output'] ?? ''}', (frame['offset'] as num?)?.toInt() ?? 0, (frame['end'] as num?)?.toInt() ?? 0, ); _changed(); } void _changed({bool membership = false}) { if (_disposed) return; if (membership) _membership.value++; notifyListeners(); } String _reason(Object error) => describeErrorReason(error, fallback: 'The server did not answer.'); @override void dispose() { _disposed = true; _generation++; unawaited(_frames?.cancel()); _membership.dispose(); super.dispose(); } }