feat: watch background commands, open their output and stop them

A command the agent detached keeps running after its tool call returns;
the chat now shows it above the composer: one row per command with its
clock and a stop, folded under "正在执行 N 条命令" when there are
several, with a subagent tag for a child session's command.

Tapping a row opens the live output in a sheet (a page a second from
shell.output, tail kept), following the tail with a way back to the
newest line. The tool row that started it carries a 后台 tag and shows
the same output when expanded, falling back to the completion note once
the shell is gone; a command stopped from the app says so instead of
showing the Shell.NotFoundError it leaves behind.

The list comes from opencode's own shell jobs (experimental/job,
descendants included), so a foreground command never appears, and an
older server falls back to the shell list narrowed by the detached
calls in the transcript. Stopping confirms, removes the shell, and
leaves the model a note that the stop was the user's, as the
first-party client does.

0.4.14 (414).
This commit is contained in:
blumia committed 2026-11-24 19:31:22 +08:00
1 parent 809e0a747a
commit c4de5e84d8
11 files changed
+1749 -7

No files matched your search

+78
View File
@@ -8,6 +8,7 @@ import 'dart:typed_data';
import '../version.dart';
import 'models.dart';
import 'shells.dart';
import 'terminal.dart';
import 'transport.dart';
@@ -292,6 +293,83 @@ class Client {
directory: directory);
}
/// The shells started in [directory], running ones and ones that just
/// exited (the list keeps an exited shell for a while). A background command
/// is one the transcript marks with `{status: running, shellID}`.
Future<List<ShellTask>> listShells({String? directory}) async {
final r = await _json('GET', '/api/shell', directory: directory);
return shellTasksFromList(r);
}
/// The running jobs of a session (and its children with [descendants]):
/// shell commands opencode detached, plus unrelated kinds the caller
/// filters out. Empty on an opencode without the experimental endpoint
/// (404).
Future<List<ShellTask>> listShellJobs(String sessionId,
{bool descendants = true}) async {
final r = await _json('GET', '/api/experimental/job', query: {
'sessionID': sessionId,
if (descendants) 'descendants': 'true',
'status': 'running',
});
return shellTasksFromJobs(r);
}
/// One page of a shell's output. Without [cursor] the server reads from the
/// start; [size] in the answer says how much there is, so the first call can
/// ask again from `size - tail` for a long command.
Future<ShellOutputPage> shellOutput(String shellId,
{int? cursor, int? limit, String? directory}) async {
final query = <String, String>{
if (cursor != null) 'cursor': '$cursor',
if (limit != null) 'limit': '$limit',
};
final r = await _json(
'GET', '/api/shell/${Uri.encodeComponent(shellId)}/output',
query: query.isEmpty ? null : query, directory: directory);
return ShellOutputPage.fromJson(r);
}
/// One shell by id; null when the server no longer knows it (removed).
Future<ShellTask?> shell(String shellId, {String? directory}) async {
try {
final r = await _json(
'GET', '/api/shell/${Uri.encodeComponent(shellId)}',
directory: directory);
return ShellTask.fromWire(r['data']);
} on ApiError catch (e) {
if (e.status == 404) return null;
rethrow;
}
}
/// Stops a background shell (SIGTERM through its pid). The command's
/// completion notice then reports a `Shell.NotFoundError`-like failure, so
/// [syntheticNote] tells the model that the user stopped it.
Future<void> stopShell(String shellId, {String? directory}) async {
await _json('DELETE', '/api/shell/${Uri.encodeComponent(shellId)}',
directory: directory);
}
/// Writes a note into the session without starting a turn: how the model
/// learns that a command was stopped by the user (or anything else the
/// client did), as the first-party client does.
Future<void> syntheticNote(String sessionId,
{required String text,
String? description,
Map<String, dynamic>? metadata,
String? directory}) async {
await _json('POST',
'/api/session/${Uri.encodeComponent(sessionId)}/synthetic',
directory: directory,
body: {
'text': text,
if (description != null) 'description': description,
if (metadata != null) 'metadata': metadata,
'resume': false,
});
}
/// Moves a waiting prompt between `steer` and `queue`.
Future<void> updateInbox(String sessionId, String inboxId, String delivery,
{String? directory}) async {
+6
View File
@@ -444,6 +444,10 @@ class Message {
final String reason;
/// Compaction messages: the summary the model wrote for the new history.
final String summary;
/// What the server attached to the message: a synthetic note carries why it
/// was written (a stopped shell, a job report), the chat UI reads that.
final Map<String, dynamic>? metadata;
Message({
required this.id,
required this.type,
@@ -461,6 +465,7 @@ class Message {
this.status = '',
this.reason = '',
this.summary = '',
this.metadata,
});
factory Message.fromJson(Map<String, dynamic> j) {
final t = j['time'] as Map<String, dynamic>? ?? {};
@@ -489,6 +494,7 @@ class Message {
status: j['status'] as String? ?? '',
reason: j['reason'] as String? ?? '',
summary: j['summary'] as String? ?? '',
metadata: j['metadata'] as Map<String, dynamic>?,
);
}
String get partText {
+251
View File
@@ -0,0 +1,251 @@
// 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 '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<ShellTask> shellTasksFromList(Map<String, dynamic> 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<ShellTask> shellTasksFromJobs(Map<String, dynamic> body) {
final data = body['data'];
if (data is! List) return const [];
final out = <ShellTask>[];
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<String, dynamic> 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 (`<background-result …>`), 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'<background-result\b([^>]*)>([\s\S]*?)</background-result>');
/// 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<Message> 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<Message> 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<ShellTask> backgroundShellsFromMessages(
Iterable<Message> messages, String sessionId) {
final out = <ShellTask>[];
final seen = <String>{};
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 <String, dynamic>{};
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 '$secs秒';
if (secs < 3600) {
final rest = secs % 60;
return '${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')}';
}