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'; import 'chat_shell_terminals.dart'; part 'chat_shell_runs_dismissal.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) { terminals = ChatShellTerminals( _repository, sessionId, onError: (id, error) { if (_disposed) return; _errors[id] = _reason(error); _changed(); }, ); _frames = gateway.frames.listen(_onFrame, onError: (_) {}); unawaited(refresh()); } /// The runs' terminal emulators and their input and size delivery. late final ChatShellTerminals terminals; 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 = {}; /// Runs dismissed here or by another client: a readback racing the /// dismissal does not bring their cards back. final Set _gone = {}; /// The dismissed runs this copy holds, shown collapsed in the transcript's /// command history rather than as cards. final Map _dismissed = {}; 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 finished runs, oldest first: what Dismiss all finished removes. List get finishedIds => [ for (final run in _runs.values) if (!run.running) run.id, ]; /// 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 (:runs, :dismissed, :dismissedRuns) = await _repository.runs( sessionId, ); if (_disposed || token != _generation) return; dismissed.forEach(_remove); _holdDismissed(dismissedRuns); for (final run in runs) { if (_gone.contains(run.id)) continue; // Restored by another client while this copy missed the frame. _dismissed.remove(run.id); final held = _runs[run.id]; if (held != null && held.running && held.outputEnd > 0 && run.outputBytes > held.outputEnd) { // A reconnect: fetch only what this copy missed. unawaited(_resume(held)); continue; } final keep = held != null && held.outputEnd >= run.outputEnd; _runs[run.id] = keep ? held.withLifecycle(run) : run; if (!keep) terminals.replaced(run); if (held != null && held.running && !run.running) { terminals.finished(_runs[run.id]!); } } _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 size = terminals.lastSize; final run = await _repository.run( sessionId, command, cols: size?.$1, rows: size?.$2, ); 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(); } /// The plain-text rendering of everything the server kept for [id]: what /// Copy output copies. Null when it cannot be read (the error is recorded). Future plainText(String id) async { try { final full = await _repository.output(sessionId, id); // A server without terminals records plain output and no rendering. return full.terminal || full.text.isNotEmpty ? full.text : full.output; } catch (error) { if (_disposed) return null; _errors[id] = _reason(error); _changed(); return null; } } /// Reads what a running run printed while this copy was disconnected, /// from the byte it holds up to; a gap redraws from what the server kept. Future _resume(ChatShellRun held) async { try { final tail = await _repository.output( sessionId, held.id, after: held.outputEnd, ); if (_disposed) return; final latest = _runs[held.id] ?? held; final next = latest .withChunk(tail.output, tail.outputStart, tail.outputBytes) .withLifecycle(latest.running ? tail : latest); _runs[held.id] = next; if (tail.outputStart == latest.outputEnd) { terminals.appended( next, tail.output, tail.outputStart, tail.outputBytes, ); } else { terminals.replaced(next); } if (!next.running) terminals.finished(next); _changed(); } catch (_) { // The next frame or refresh repairs the copy. } } 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'] ?? ''}'; if (frame['dismissed'] == true) { final known = _runs.containsKey(id) || _dismissed.containsKey(id); _remove(id); // Another client dismissed a run this copy never held: read it. if (!known) unawaited(refresh()); _changed(membership: true); return; } final record = ChatShellRun.fromJson(frame['run']); if (record != null) { // A restored run (another client's Undo) comes back without output. if (_gone.remove(record.id) && !record.running) unawaited(refresh()); _dismissed.remove(record.id); final held = _runs[record.id]; final next = held == null ? record : held.withLifecycle(record); _runs[record.id] = next; if (!record.running) { _stopping.remove(record.id); if (held != null && held.running) terminals.finished(next); } // Membership also tracks finishing: Dismiss all finished depends on it. _changed(membership: held == null || held.running != next.running); return; } if (_gone.contains(id)) return; final held = _runs[id]; if (held == null) { // Output for a run this copy has not seen yet: read the record. unawaited(refresh()); return; } final text = '${frame['output'] ?? ''}'; final offset = (frame['offset'] as num?)?.toInt() ?? 0; final end = (frame['end'] as num?)?.toInt() ?? 0; final next = held.withChunk(text, offset, end); _runs[id] = next; terminals.appended(next, text, offset, end); _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++; terminals.dispose(); unawaited(_frames?.cancel()); _membership.dispose(); super.dispose(); } }