// Background commands of a session (opencode's shells), as the first-party // client shows them above the composer: the command, how long it has been // running, and a way to stop it. import '../l10n.dart'; import 'models.dart'; /// One running (or just ended) shell. `id` is the shell id opencode created /// (`shellID` on a job); the tool call that detached it carries the same id. class ShellTask { final String id; /// The session that started it (a subagent has its own). final String sessionId; final String command; /// Epoch milliseconds. final int startedAt; final bool running; const ShellTask({ required this.id, required this.sessionId, required this.command, required this.startedAt, this.running = true, }); ShellTask copyWith({ String? command, int? startedAt, bool? running, String? sessionId, }) => ShellTask( id: id, sessionId: sessionId ?? this.sessionId, command: command ?? this.command, startedAt: startedAt ?? this.startedAt, running: running ?? this.running, ); static ShellTask? fromWire(Object? raw) { if (raw is! Map) return null; final id = raw['id']; if (id is! String || id.isEmpty) return null; final metadata = raw['metadata']; final owner = metadata is Map ? metadata['sessionID'] : null; final time = raw['time']; final started = time is Map ? time['started'] : null; return ShellTask( id: id, sessionId: owner is String ? owner : '', command: (raw['command'] as String?) ?? '', startedAt: (started as num?)?.toInt() ?? 0, running: (raw['status'] as String?) == 'running', ); } /// One entry of `GET /api/experimental/job` when it is a shell job: its /// `shellID` is the id the output and stop calls take. static ShellTask? fromJob(Object? raw) { if (raw is! Map || raw['kind'] != 'shell') return null; final shellId = raw['shellID']; if (shellId is! String || shellId.isEmpty) return null; final time = raw['time']; final started = time is Map ? time['started'] : null; return ShellTask( id: shellId, sessionId: (raw['sessionID'] as String?) ?? '', command: (raw['command'] as String?) ?? '', startedAt: (started as num?)?.toInt() ?? 0, running: (raw['status'] as String?) == 'running', ); } } /// The session's shells from `GET /api/shell`, running ones first as the /// wire lists them. Shells that already exited stay in the answer (status /// `exited`), so callers filter on [ShellTask.running]. List shellTasksFromList(Map body) { final data = body['data']; if (data is! List) return const []; return [ for (final raw in data) ?ShellTask.fromWire(raw), ]; } /// The running shell jobs of `GET /api/experimental/job`: opencode's own /// record of what it detached (a `bash` call that returned while the command /// kept going). Unlike the transcript this also covers subagent sessions, and /// it never contains a foreground command. List shellTasksFromJobs(Map body) { final data = body['data']; if (data is! List) return const []; final out = []; for (final raw in data) { final task = ShellTask.fromJob(raw); if (task != null && task.running) out.add(task); } return out; } /// One page of a shell's output (`GET /api/shell/:id/output`): the text read /// from [cursor], the cursor after it, and the total size so a first read can /// start near the tail instead of the beginning. class ShellOutputPage { final String output; final int cursor; final int size; /// The server cut this page (the requested span was larger than it serves /// at once); the next read continues from [cursor]. final bool truncated; const ShellOutputPage({ this.output = '', this.cursor = 0, this.size = 0, this.truncated = false, }); static ShellOutputPage fromJson(Map body) { final data = body['data']; if (data is! Map) return const ShellOutputPage(); return ShellOutputPage( output: (data['output'] as String?) ?? '', cursor: (data['cursor'] as num?)?.toInt() ?? 0, size: (data['size'] as num?)?.toInt() ?? 0, truncated: data['truncated'] == true, ); } } /// A finished background command's report: the synthetic message opencode /// writes into the session when the job ends (``), which /// also holds the output after the shell itself is gone. class ShellCompletionNote { final String shellId; final String state; final String output; const ShellCompletionNote({ required this.shellId, required this.state, required this.output, }); bool get failed => state == 'error' || state == 'cancelled'; } final _backgroundResult = RegExp( r']*)>([\s\S]*?)'); /// The completion a synthetic message carries, or null for other notes. ShellCompletionNote? shellCompletionNote(Message message) { if (message.type != 'synthetic') return null; final match = _backgroundResult.firstMatch(message.text); if (match == null) return null; final attrs = match.group(1) ?? ''; if (!attrs.contains('kind="shell"')) return null; final id = RegExp(r'id="([^"]+)"').firstMatch(attrs)?.group(1); if (id == null || id.isEmpty) return null; final state = RegExp(r'state="([^"]+)"').firstMatch(attrs)?.group(1) ?? ''; var output = match.group(2) ?? ''; if (output.startsWith('\n')) output = output.substring(1); return ShellCompletionNote( shellId: id, state: state, output: output.trimRight()); } /// The newest completion note for [shellId], if the command has finished. ShellCompletionNote? shellCompletionFor( Iterable messages, String shellId) { ShellCompletionNote? found; for (final message in messages) { final note = shellCompletionNote(message); if (note != null && note.shellId == shellId) found = note; } return found; } /// Whether the app itself stopped [shellId]: the note it writes into the /// session carries `metadata.openchamber.shellStop.shellIDs`. bool shellWasStopped(Iterable messages, String shellId) { for (final message in messages) { if (message.type != 'synthetic') continue; final openchamber = message.metadata?['openchamber']; if (openchamber is! Map) continue; final stop = openchamber['shellStop']; if (stop is! Map) continue; final ids = stop['shellIDs']; if (ids is List && ids.contains(shellId)) return true; } return false; } /// The shell id a *background* tool call detached, if this part is one. A /// foreground command keeps `status: running` on the tool part itself; the /// detached one is completed and its metadata says the shell still runs: /// `{status: 'running', shellID: 'sh_…'}`, as the first-party client reads it. String? backgroundShellId(ContentPart part) { if (part.type != 'tool') return null; const shells = {'bash', 'shell', 'pwsh', 'execute'}; if (!shells.contains(part.name ?? '')) return null; final state = part.state; if (state == null || state.status != 'completed') return null; final metadata = state.metadata; if (metadata == null || metadata['status'] != 'running') return null; final id = metadata['shellID']; return id is String && id.isNotEmpty ? id : null; } /// A running background command is completed in the transcript (the call /// returned at once) but still going; that is what the strip lists. List backgroundShellsFromMessages( Iterable messages, String sessionId) { final out = []; final seen = {}; for (final message in messages) { for (final part in message.content) { final id = backgroundShellId(part); if (id == null || !seen.add(id)) continue; final input = part.state?.input ?? const {}; out.add(ShellTask( id: id, sessionId: sessionId, command: '${input['command'] ?? ''}'.trim(), startedAt: message.created, )); } } return out; } /// Keep a shell under the report size: the first read asks for everything /// and the UI shows only this much of the tail. const shellOutputTailBytes = 256 * 1024; /// `12秒`, `3分05秒`, `1:02:03`: the running clock a task row shows. String formatElapsed(int milliseconds) { final secs = milliseconds <= 0 ? 0 : milliseconds ~/ 1000; if (secs < 60) return trArgs('{0}s', [secs]); if (secs < 3600) { final rest = secs % 60; return trArgs( '{0}m{1}s', [secs ~/ 60, rest.toString().padLeft(2, '0')]); } final hours = secs ~/ 3600; final mins = (secs % 3600) ~/ 60; final rest = secs % 60; return '$hours:${mins.toString().padLeft(2, '0')}:' '${rest.toString().padLeft(2, '0')}'; }