// Who is running in the background. opencode records detached commands as // "shell" jobs (`GET /api/experimental/job`), session-scoped and covering // subagents, so the list is right without reading the transcript. An older // server without that endpoint falls back to the shell list, where only the // transcript can say which commands were detached. import 'dart:async'; import 'package:flutter/foundation.dart'; import 'api/client.dart'; import 'api/shells.dart'; /// The background commands of the open session, refreshed while the chat is /// on screen. class ShellTasks extends ChangeNotifier { ShellTasks(this.client, {required this.sessionId}); final Client client; final String sessionId; List _tasks = const []; List get tasks => _tasks; /// The shell list stopped answering (an opencode without the shell API): /// polling stops so a chat does not keep asking. bool available = true; /// The job endpoint answered 404 once: this server only has `GET /api/shell`. bool _jobs = true; /// Fallback only: the detached calls the transcript knows about, with the /// start time of the message that ran them. final Map _seeded = {}; /// Every task ever seen, for a tool row that wants its output after the /// command has left the strip. final Map _known = {}; String _directory = ''; List _sessionIds = const []; Timer? _poll; bool _busy = false; bool _disposed = false; /// The transcript's detached calls (fallback path). Called on every chat /// change; cheap. void seed(Iterable tasks) { var changed = false; final ids = {}; for (final task in tasks) { if (!ids.add(task.id)) continue; final old = _seeded[task.id]; if (old == null || old.command != task.command || old.startedAt != task.startedAt) { _seeded[task.id] = task; changed = true; } _known[task.id] ??= task; } for (final id in _seeded.keys.toList()) { if (!ids.contains(id)) { _seeded.remove(id); changed = true; } } if (changed) { _prune(); if (_poll != null) unawaited(refresh()); } } /// Starts (or re-arms) the refresh for [directory]. The job list does not /// need it; the fallback shell list does. void watch({required String directory, required Set sessionIds}) { final ids = sessionIds.toList()..sort(); if (_poll != null && directory == _directory && _same(ids, _sessionIds)) { return; } _directory = directory; _sessionIds = ids; _poll?.cancel(); _poll = Timer.periodic(const Duration(seconds: 3), (_) => refresh()); refresh(); } /// Re-reads what is running now (after a stop, or when a tool transition /// arrives). Future refresh() async { if (_disposed || _busy) return; _busy = true; try { if (available && _jobs) { try { final jobs = await client.listShellJobs(sessionId); if (_disposed) return; _set(jobs); return; } on ApiError catch (e) { if (e.status != 404) rethrow; _jobs = false; } } if (available) await _refreshShellList(); } on ApiError catch (e) { if (e.status == 404) { available = false; _poll?.cancel(); _poll = null; } // A network hiccup keeps the last known tasks on screen. } catch (_) { // Same: the next tick tries again. } finally { _busy = false; } } /// The fallback: all running shells of the directory, narrowed to the /// commands the transcript detached. Future _refreshShellList() async { if (_seeded.isEmpty) { _set(const []); return; } final listed = await client.listShells(directory: _directory); if (_disposed) return; final byId = {for (final shell in listed) shell.id: shell}; final next = []; for (final task in _seeded.values) { final live = byId[task.id]; if (live == null || !live.running) continue; next.add(task.copyWith( command: live.command.isEmpty ? null : live.command, startedAt: live.startedAt > 0 ? live.startedAt : null, sessionId: live.sessionId.isEmpty ? null : live.sessionId, )); } _set(next); } /// Stops [task], then tells the model why its completion notice will look /// like a failure, as the first-party client does. Future stop(ShellTask task, String directory) async { await client.stopShell(task.id, directory: directory); _seeded.remove(task.id); _known.remove(task.id); _set(_tasks.where((t) => t.id != task.id).toList()); // The notice goes to the session that started the command. try { await client.syntheticNote( task.sessionId.isEmpty ? sessionId : task.sessionId, text: stopNote(task.command), description: 'Background command stopped by the user', metadata: { 'openchamber': { 'shellStop': { 'shellIDs': [task.id], }, }, }, directory: directory, ); } catch (_) { // The command is stopped either way; the notice is a courtesy. } unawaited(refresh()); } /// The task with this shell id, for a tool row opening its output. ShellTask? task(String id) => _known[id]; void _prune() { _set([ for (final task in _tasks) if (_seeded.containsKey(task.id)) task, ]); } void _set(List next) { _tasks = List.unmodifiable(next); for (final task in next) { _known[task.id] = task; } if (!_disposed) notifyListeners(); } static bool _same(List a, List b) { if (a.length != b.length) return false; for (var i = 0; i < a.length; i++) { if (a[i] != b[i]) return false; } return true; } @override void dispose() { _disposed = true; _poll?.cancel(); super.dispose(); } } /// What the model is told when a command is stopped from the app. Without it /// the completion notice reads as a failure and the model may run it again. String stopNote(String command) { final shown = command.replaceAll(RegExp(r'\s+'), ' ').trim(); return 'The user stopped the background command `$shown`. ' 'The completion notice that follows reports an error such as ' 'Shell.NotFoundError or says that nothing ran; that is the stop, not a ' 'failure of the command. Do not start it again just because of that ' 'notice.'; }