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

+17
View File
@@ -5,6 +5,23 @@
---
## 0.4.14 后台任务:状态条、实时输出与停止(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 状态条 | 输入框上方新增后台任务条(在运行状态胶囊之下):1 条时直接显示命令、计时、`停止`;多条折叠成「正在执行 N 条命令」,默认 N ≤ 3 展开;子代理会话的任务标「子代理」 |
| 输出 | 点状态条任意一行打开底部弹层:完整命令、运行状态与计时、实时输出(1 秒轮询 `GET /api/shell/:id/output`,cursor 续读、尾部 256KB 封顶)、自动跟随与「回到最新」、复制、停止 |
| 工具行 | 起后台命令的 `bash` 行带「后台」标签;展开后显示「后台输出」预览(最后 8 行,仅展开时轮询)+「查看全部」+「停止」 |
| 数据来源 | 首选 `GET /api/experimental/job?sessionID=…&descendants=true&status=running` 里的 `kind=shell`(opencode 自己的后台记录:`shellID`、`command`、`sessionID`、`time.started`,覆盖子会话,不会混入前台命令);老服务端 404 时退回 `GET /api/shell` + 转录里 `{status:running, shellID}` 的标记 |
| 停止 | 确认框「停止这个任务?」→ `DELETE /api/shell/:id` → 向启动它的会话写一条 synthetic 说明(“用户停止了这条后台命令,随后的 Shell.NotFoundError 不是失败,不要因此重跑”,与上游口径一致),然后刷新列表 |
| 结束后 | 命令结束后,工具行与弹层不再轮询,改用会话里 synthetic `<background-result kind="shell" …>` 的最终输出(shell 被删除后仍能看);如果是用户在 App 里停的,显示「用户停止了这条命令。」而不是 Shell.NotFoundError |
| 刷新 | 打开会话立即刷新,之后 3 秒一次;会话消息变化时也刷新(新任务立刻出现);服务端无该接口时停止轮询 |
| 测试 | 新增 `test/shell_jobs_test.dart`:后台标记识别(前台命令不算)、转录/任务/外壳列表解析、输出页、完成说明与停止标记、计时格式、停止说明,以及状态条 1 条/2 条/多条折叠的布局;80 项全过 |
| 验证 | 模拟器(真实任务):`sleep 900` 单条任务条 → 第二条命令变为「正在执行 2 条命令」+ 两条行;弹层实时输出(每秒 tick);弹层内「停止」→ 确认 → 任务与 shell 消失、模型收到 synthetic 停止说明;工具行「后台」标签 + 展开后的最终输出/「用户停止了这条命令。」 |
| 版本 | **0.4.14(code 414)** |
---
## 0.4.13 相对路径与生成图片的行内展示(分支 `flutter`)
| 项 | 结果 |
+4 -2
View File
@@ -5,7 +5,7 @@ Android first. This branch (`flutter`) is a framework evaluation: the same
feature set as the earlier Asuka/Go and MyGo attempts, reimplemented in
Flutter to compare mobile UI maturity.
Status: 0.4.13 — servers (passwordless / password login, HTTP/HTTPS and
Status: 0.4.14 — servers (passwordless / password login, HTTP/HTTPS and
SOCKS5/socks5h proxy, self-signed certificates and pinning, or a pairing link
over the OpenChamber private relay with end-to-end encryption; the pairing
link is pasted or scanned with the camera), session list with search and live
@@ -28,7 +28,9 @@ expanded) and open from the sidebar or the parent's Agent Task row; a subagent
chat is read-only unless the server allows prompting subagents; edit, write
and patch calls open as tinted line diffs with +N −M counts and show their
file path relative to the session directory; a finished image-generation call
shows the picture in the conversation instead of folding it away; the
shows the picture in the conversation instead of folding it away; commands
running in the background get a strip above the composer with their clock and
a stop, and their live output opens from there; the
server's managed chat folders are one 聊天 group, and a new session can target
聊天 instead of a project. Project rows use the icon and colour chosen in
OpenChamber (including an uploaded/auto icon image), and the chat group has a
+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')}';
}
+213
View File
@@ -0,0 +1,213 @@
// 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<ShellTask> _tasks = const [];
List<ShellTask> 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<String, ShellTask> _seeded = {};
/// Every task ever seen, for a tool row that wants its output after the
/// command has left the strip.
final Map<String, ShellTask> _known = {};
String _directory = '';
List<String> _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<ShellTask> tasks) {
var changed = false;
final ids = <String>{};
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<String> 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<void> 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<void> _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 = <ShellTask>[];
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<void> 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<ShellTask> next) {
_tasks = List.unmodifiable(next);
for (final task in next) {
_known[task.id] = task;
}
if (!_disposed) notifyListeners();
}
static bool _same(List<String> a, List<String> 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.';
}
+149 -3
View File
@@ -8,6 +8,8 @@ import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import '../api/client.dart';
import '../api/models.dart';
import '../api/shells.dart';
import '../background_jobs.dart';
import '../state.dart';
import '../widgets/composer_attachment.dart';
import '../widgets/markdown_view.dart';
@@ -15,6 +17,7 @@ import '../widgets/composer_box.dart';
import '../widgets/diff_view.dart';
import '../widgets/pet_sprite.dart';
import '../widgets/model_controls.dart';
import '../widgets/shell_jobs.dart';
import '../widgets/slash_palette.dart';
import '../widgets/usage_ring.dart';
import 'files_panel.dart';
@@ -73,6 +76,10 @@ class _ChatScreenState extends State<ChatScreen> {
/// Ticks the activity strip's clock while a turn runs.
Timer? _runClock;
/// Background commands of this session (and its known children): seeded
/// from the transcript, kept alive by the shell list.
ShellTasks? _shells;
@override
void initState() {
super.initState();
@@ -80,6 +87,12 @@ class _ChatScreenState extends State<ChatScreen> {
chat.addListener(_onChat);
_inputFocus.addListener(_onFocusChanged);
if (chat.running) _startClock();
final client = widget.app.client;
if (client != null) {
_shells = ShellTasks(client, sessionId: chat.session.id)
..addListener(_onShells);
_syncShells();
}
// The list is reversed: offset 0 is the newest message (the bottom), and
// older pages grow above without moving what is on screen.
_scroll.addListener(() {
@@ -98,6 +111,7 @@ class _ChatScreenState extends State<ChatScreen> {
void _onChat() {
if (mounted) setState(() {});
_syncShells();
if (chat.running) {
_startClock();
} else {
@@ -125,17 +139,97 @@ class _ChatScreenState extends State<ChatScreen> {
if (mounted) setState(() {});
}
void _onShells() {
if (mounted) setState(() {});
}
@override
void dispose() {
chat.removeListener(_onChat);
_inputFocus.removeListener(_onFocusChanged);
_stopClock();
_shells?.dispose();
_draftCtrl.dispose();
_inputFocus.dispose();
_scroll.dispose();
super.dispose();
}
/// The session plus every child the session list knows about, so a
/// subagent's background command is listed too.
Set<String> _sessionTree() {
final ids = <String>{chat.session.id};
var grew = true;
while (grew) {
grew = false;
for (final session in widget.app.sessions) {
final parent = session.parentID;
if (parent != null &&
parent.isNotEmpty &&
ids.contains(parent) &&
ids.add(session.id)) {
grew = true;
}
}
}
return ids;
}
/// What the transcript says is detached, handed to the watcher; the shell
/// list then decides which of them are still running.
void _syncShells() {
final shells = _shells;
if (shells == null) return;
shells.seed(backgroundShellsFromMessages(chat.msgs, chat.session.id));
shells.watch(directory: chat.dir, sessionIds: _sessionTree());
}
Future<void> _openShellSheet(ShellTask task,
{ShellCompletionNote? completion}) async {
final client = widget.app.client;
if (client == null) return;
await showShellOutput(
context,
client: client,
task: task,
directory: chat.dir,
onStop: () => _stopShell(task),
finalOutput: completion == null ? null : _completionText(task.id, completion),
done: completion != null,
);
}
/// What a finished command's output reads as: the report, or that the user
/// stopped it (the report itself is a `Shell.NotFoundError` then).
String _completionText(String shellId, ShellCompletionNote completion) =>
shellWasStopped(chat.msgs, shellId) ? '用户停止了这条命令。' : completion.output;
Future<void> _stopShell(ShellTask task) async {
final shells = _shells;
if (shells == null) return;
try {
await shells.stop(task, chat.dir);
} on ApiError catch (e) {
if (!mounted) return;
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text('停止失败:${e.message}')));
}
}
/// The task the transcript row is about: the strip's copy when it has one
/// (real start time), otherwise what the part itself says.
ShellTask _shellTaskFor(ContentPart part, String shellId, int startedAt) {
final known = _shells?.task(shellId);
if (known != null) return known;
final input = part.state?.input ?? const <String, dynamic>{};
return ShellTask(
id: shellId,
sessionId: chat.session.id,
command: '${input['command'] ?? ''}'.trim(),
startedAt: startedAt,
);
}
/// A subagent is view-only unless the server allows prompting subagents;
/// a lead's operator worker stays view-only until it is taken over.
bool get _promptReadOnly =>
@@ -255,6 +349,7 @@ class _ChatScreenState extends State<ChatScreen> {
_permissions(),
_forms(),
if (chat.running) _activityStrip(),
if (_shells != null && _shells!.tasks.isNotEmpty) _shellTasksBar(),
if (_promptReadOnly)
_readOnlyBanner(theme)
else
@@ -892,6 +987,7 @@ class _ChatScreenState extends State<ChatScreen> {
? const <_ImageRef>[]
: toolImages(p, chat.dir);
final subagentId = _subagentSessionId(p);
final shellId = reasoning ? null : backgroundShellId(p);
final diffFiles = reasoning ? const <DiffFile>[] : toolDiffFiles(p);
var diffAdded = 0;
var diffRemoved = 0;
@@ -974,6 +1070,23 @@ class _ChatScreenState extends State<ChatScreen> {
padding: const EdgeInsets.only(left: 6, right: 2),
child: DiffStats(added: diffAdded, removed: diffRemoved),
),
if (shellId != null)
Padding(
padding: const EdgeInsets.only(left: 6),
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: 6, vertical: 1),
decoration: BoxDecoration(
color: theme.colorScheme.primary
.withValues(alpha: 0.12),
borderRadius: BorderRadius.circular(6),
),
child: Text('后台',
style: TextStyle(
fontSize: 11,
color: theme.colorScheme.primary)),
),
),
if (subagentId != null)
Icon(Icons.chevron_right,
size: 18, color: theme.hintColor)
@@ -1011,7 +1124,7 @@ class _ChatScreenState extends State<ChatScreen> {
_Reveal(
open: open,
onGrow: _grow,
child: _stepDetails(p, reasoning, diffFiles),
child: _stepDetails(p, reasoning, diffFiles, shellId, m.created),
),
],
),
@@ -1110,9 +1223,27 @@ class _ChatScreenState extends State<ChatScreen> {
/// What the step actually did: the command or path, the rest of the input,
/// and the result — never the request JSON as a blob.
Widget _stepDetails(
ContentPart p, bool reasoning, List<DiffFile> diffFiles) {
Widget _stepDetails(ContentPart p, bool reasoning, List<DiffFile> diffFiles,
String? shellId, int startedAt) {
final theme = Theme.of(context);
if (shellId != null) {
final task = _shellTaskFor(p, shellId, startedAt);
final completion = shellCompletionFor(chat.msgs, shellId);
return Padding(
padding: const EdgeInsets.fromLTRB(10, 4, 10, 8),
child: ShellOutputInline(
client: widget.app.client!,
task: task,
directory: chat.dir,
finalOutput: completion == null
? null
: _completionText(shellId, completion),
done: completion != null,
onOpen: () => _openShellSheet(task, completion: completion),
onStop: () => _stopShell(task),
),
);
}
if (diffFiles.isNotEmpty) return _diffDetails(p, diffFiles);
if (reasoning) {
if (p.text.isEmpty) return const SizedBox.shrink();
@@ -1641,6 +1772,21 @@ class _ChatScreenState extends State<ChatScreen> {
return '${secs ~/ 60}:${(secs % 60).toString().padLeft(2, '0')}';
}
/// The background commands of this session, above the composer: what is
/// running, for how long, and the way into its output.
Widget _shellTasksBar() {
final tasks = _shells?.tasks ?? const <ShellTask>[];
return ShellTaskBar(
tasks: tasks,
sessionId: chat.session.id,
onOpen: _openShellSheet,
onStop: (task) async {
final ok = await confirmStopShell(context, task.command);
if (ok == true) await _stopShell(task);
},
);
}
/// dsh-Go's activity cap: a stadium above the input with the current step
/// on the left and its clock on the right. Its top edge is where the
/// input-box pet will later perch.
+1 -1
View File
@@ -1,2 +1,2 @@
/// The app version sent to the server in pairing and relay handshakes.
const appVersion = '0.4.13';
const appVersion = '0.4.14';
+727
View File
@@ -0,0 +1,727 @@
// The background-command surfaces: a strip above the composer that names what
// is running, a sheet with its live output, and the output preview inside the
// tool row that detached the command.
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../api/client.dart';
import '../api/shells.dart';
/// One line of "正在执行 N 条命令", folding when there are many.
class ShellTaskBar extends StatefulWidget {
final List<ShellTask> tasks;
/// The chat's own session: a task from a child session is marked.
final String sessionId;
final void Function(ShellTask task) onOpen;
final void Function(ShellTask task) onStop;
const ShellTaskBar({
super.key,
required this.tasks,
required this.sessionId,
required this.onOpen,
required this.onStop,
});
@override
State<ShellTaskBar> createState() => _ShellTaskBarState();
}
class _ShellTaskBarState extends State<ShellTaskBar> {
/// Null until the person folds or unfolds: by default a short list shows.
bool? _expanded;
bool get _open => _expanded ?? widget.tasks.length <= 3;
@override
Widget build(BuildContext context) {
final tasks = widget.tasks;
if (tasks.isEmpty) return const SizedBox.shrink();
final theme = Theme.of(context);
final single = tasks.length == 1;
return Padding(
padding: const EdgeInsets.fromLTRB(8, 2, 8, 6),
child: Material(
color: theme.colorScheme.surfaceContainerHighest.withValues(alpha: 0.7),
borderRadius: BorderRadius.circular(14),
clipBehavior: Clip.antiAlias,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (!single) _header(theme, tasks.length),
if (single || _open)
for (final task in tasks)
_ShellTaskRow(
key: ValueKey(task.id),
task: task,
subagent: task.sessionId.isNotEmpty &&
task.sessionId != widget.sessionId,
onTap: () => widget.onOpen(task),
onStop: () => widget.onStop(task),
),
],
),
),
);
}
Widget _header(ThemeData theme, int count) {
return InkWell(
onTap: () => setState(() => _expanded = !_open),
child: Padding(
padding: const EdgeInsets.fromLTRB(12, 8, 8, 8),
child: Row(
children: [
Icon(Icons.terminal, size: 15, color: theme.hintColor),
const SizedBox(width: 8),
Expanded(
child: Text(
'正在执行 $count 条命令',
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 13,
color: theme.colorScheme.onSurfaceVariant,
),
),
),
Icon(_open ? Icons.expand_less : Icons.expand_more,
size: 18, color: theme.hintColor),
],
),
),
);
}
}
class _ShellTaskRow extends StatelessWidget {
final ShellTask task;
final bool subagent;
final VoidCallback onTap;
final VoidCallback onStop;
const _ShellTaskRow({
super.key,
required this.task,
required this.subagent,
required this.onTap,
required this.onStop,
});
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return InkWell(
onTap: onTap,
child: Padding(
padding: const EdgeInsets.fromLTRB(12, 2, 4, 2),
child: Row(
children: [
Icon(Icons.terminal, size: 15, color: theme.hintColor),
const SizedBox(width: 8),
Expanded(
child: Text(
task.command.replaceAll(RegExp(r'\s+'), ' ').trim(),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontSize: 12, fontFamily: 'monospace', height: 1.35),
),
),
if (subagent) ...[
const SizedBox(width: 6),
Text('子代理',
style: TextStyle(fontSize: 11, color: theme.hintColor)),
],
const SizedBox(width: 8),
ShellElapsed(startedAt: task.startedAt),
TextButton(
onPressed: onStop,
style: TextButton.styleFrom(
minimumSize: const Size(0, 34),
padding: const EdgeInsets.symmetric(horizontal: 10),
foregroundColor: theme.colorScheme.error,
textStyle: const TextStyle(fontSize: 12.5),
),
child: const Text('停止'),
),
],
),
),
);
}
}
/// `3分05秒`, ticking while the command runs.
class ShellElapsed extends StatefulWidget {
final int startedAt;
final bool running;
const ShellElapsed(
{super.key, required this.startedAt, this.running = true});
@override
State<ShellElapsed> createState() => _ShellElapsedState();
}
class _ShellElapsedState extends State<ShellElapsed> {
Timer? _timer;
@override
void initState() {
super.initState();
if (widget.running) {
_timer = Timer.periodic(const Duration(seconds: 1), (_) {
if (mounted) setState(() {});
});
}
}
@override
void dispose() {
_timer?.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
if (widget.startedAt <= 0 || !widget.running) return const SizedBox.shrink();
final label =
formatElapsed(DateTime.now().millisecondsSinceEpoch - widget.startedAt);
return Text(
label,
style: TextStyle(
fontSize: 12,
color: Theme.of(context).hintColor,
fontFeatures: const [FontFeature.tabularFigures()],
),
);
}
}
/// Opens the live output of [task] in a sheet. A command that already ended
/// hands in its completion text instead, since the shell (and its output
/// file) may be gone.
Future<void> showShellOutput(
BuildContext context, {
required Client client,
required ShellTask task,
required String directory,
required Future<void> Function() onStop,
String? finalOutput,
bool done = false,
}) {
return showModalBottomSheet<void>(
context: context,
isScrollControlled: true,
useSafeArea: true,
showDragHandle: true,
builder: (_) => FractionallySizedBox(
heightFactor: 0.8,
child: ShellOutputSheet(
client: client,
task: task,
directory: directory,
onStop: onStop,
finalOutput: finalOutput,
done: done,
),
),
);
}
/// The command, its status, and the output so far, following the tail.
class ShellOutputSheet extends StatefulWidget {
final Client client;
final ShellTask task;
final String directory;
final Future<void> Function() onStop;
/// The completion text when the command has already ended; the sheet then
/// does not poll a shell that may no longer exist.
final String? finalOutput;
final bool done;
const ShellOutputSheet({
super.key,
required this.client,
required this.task,
required this.directory,
required this.onStop,
this.finalOutput,
this.done = false,
});
@override
State<ShellOutputSheet> createState() => _ShellOutputSheetState();
}
class _ShellOutputSheetState extends State<ShellOutputSheet> {
late final ShellOutputFeed _feed = ShellOutputFeed(
client: widget.client,
task: widget.task,
directory: widget.directory,
);
final ScrollController _scroll = ScrollController();
bool _stick = true;
bool _stopping = false;
String get _text => widget.done ? (widget.finalOutput ?? '') : _feed.text;
bool get _running => !widget.done && !_feed.ended;
@override
void initState() {
super.initState();
_scroll.addListener(() {
if (!_scroll.hasClients) return;
final atBottom =
_scroll.position.maxScrollExtent - _scroll.position.pixels <= 40;
if (atBottom != _stick) setState(() => _stick = atBottom);
});
if (!widget.done) _feed.start(_onFeed);
}
void _onFeed() {
if (!mounted) return;
setState(() {});
if (_stick) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (_scroll.hasClients) {
_scroll.jumpTo(_scroll.position.maxScrollExtent);
}
});
}
}
@override
void dispose() {
_feed.dispose();
_scroll.dispose();
super.dispose();
}
Future<void> _stop() async {
final ok = await confirmStopShell(context, widget.task.command);
if (ok != true || !mounted) return;
setState(() => _stopping = true);
try {
await widget.onStop();
} finally {
if (mounted) setState(() => _stopping = false);
}
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final running = _running;
return Padding(
padding: EdgeInsets.only(
bottom: MediaQuery.of(context).viewInsets.bottom),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Padding(
padding: const EdgeInsets.fromLTRB(20, 0, 8, 0),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Icon(Icons.terminal, size: 18, color: theme.hintColor),
const SizedBox(width: 10),
Expanded(
child: Text(
widget.task.command,
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontSize: 13, fontFamily: 'monospace', height: 1.4),
),
),
IconButton(
icon: const Icon(Icons.close, size: 20),
tooltip: '关闭',
onPressed: () => Navigator.pop(context),
),
],
),
),
Padding(
padding: const EdgeInsets.fromLTRB(20, 0, 20, 8),
child: Row(
children: [
Icon(
running ? Icons.sync : Icons.check_circle_outline,
size: 15,
color: running ? theme.colorScheme.primary : theme.hintColor,
),
const SizedBox(width: 6),
Text(
running ? '运行中' : '已结束',
style: TextStyle(
fontSize: 12,
color: running
? theme.colorScheme.primary
: theme.hintColor),
),
const SizedBox(width: 10),
ShellElapsed(
startedAt: widget.task.startedAt, running: running),
const Spacer(),
if (running)
TextButton(
onPressed: _stopping ? null : _stop,
style: TextButton.styleFrom(
foregroundColor: theme.colorScheme.error,
minimumSize: const Size(0, 32),
padding: const EdgeInsets.symmetric(horizontal: 10),
),
child: Text(_stopping ? '停止中…' : '停止'),
),
TextButton.icon(
onPressed: _text.isEmpty ? null : _copy,
icon: const Icon(Icons.copy, size: 15),
label: const Text('复制'),
style: TextButton.styleFrom(
minimumSize: const Size(0, 32),
padding: const EdgeInsets.symmetric(horizontal: 10),
),
),
],
),
),
const Divider(height: 1),
Expanded(
child: Stack(
children: [
Positioned.fill(
child: _text.isEmpty
? Center(
child: Text(
_feed.error ?? (running ? '等待输出…' : '没有输出'),
style: TextStyle(
fontSize: 13, color: theme.hintColor),
),
)
: Scrollbar(
controller: _scroll,
child: SingleChildScrollView(
controller: _scroll,
padding: const EdgeInsets.all(16),
child: SelectableText(
_text,
style: const TextStyle(
fontSize: 12,
fontFamily: 'monospace',
height: 1.45),
),
),
),
),
if (!_stick && _text.isNotEmpty)
Positioned(
right: 12,
bottom: 12,
child: FilledButton.tonalIcon(
onPressed: () {
setState(() => _stick = true);
_onFeed();
},
icon: const Icon(Icons.arrow_downward, size: 15),
label: const Text('回到最新'),
style: FilledButton.styleFrom(
visualDensity: VisualDensity.compact,
),
),
),
],
),
),
],
),
);
}
Future<void> _copy() async {
await Clipboard.setData(ClipboardData(text: _text));
if (mounted) {
ScaffoldMessenger.of(context)
.showSnackBar(const SnackBar(content: Text('已复制输出')));
}
}
}
/// The live output inside the tool row that detached the command: the last
/// lines, with the way to the full sheet.
class ShellOutputInline extends StatefulWidget {
final Client client;
final ShellTask task;
final String directory;
final VoidCallback onOpen;
final Future<void> Function() onStop;
/// The report of a command that already ended (the shell may be gone, so
/// there is nothing left to poll).
final String? finalOutput;
final bool done;
const ShellOutputInline({
super.key,
required this.client,
required this.task,
required this.directory,
required this.onOpen,
required this.onStop,
this.finalOutput,
this.done = false,
});
@override
State<ShellOutputInline> createState() => _ShellOutputInlineState();
}
class _ShellOutputInlineState extends State<ShellOutputInline> {
late final ShellOutputFeed _feed = ShellOutputFeed(
client: widget.client,
task: widget.task,
directory: widget.directory,
);
@override
void initState() {
super.initState();
if (!widget.done) {
_feed.start(() {
if (mounted) setState(() {});
});
}
}
@override
void dispose() {
_feed.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final ended = widget.done || _feed.ended;
final text = widget.done ? (widget.finalOutput ?? '') : _feed.text;
final tail = _tail(text, 8);
return Container(
width: double.infinity,
padding: const EdgeInsets.fromLTRB(10, 8, 10, 4),
decoration: BoxDecoration(
color: theme.colorScheme.surfaceContainerHighest,
borderRadius: BorderRadius.circular(8),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Icon(Icons.terminal, size: 15, color: theme.hintColor),
const SizedBox(width: 8),
Text('后台输出',
style: TextStyle(fontSize: 12, color: theme.hintColor)),
const SizedBox(width: 8),
if (!ended)
Text('运行中',
style: TextStyle(
fontSize: 12, color: theme.colorScheme.primary)),
if (ended && text.isEmpty)
Text('已结束',
style:
TextStyle(fontSize: 12, color: theme.hintColor)),
const Spacer(),
if (!ended)
TextButton(
onPressed: _stop,
style: TextButton.styleFrom(
foregroundColor: theme.colorScheme.error,
minimumSize: const Size(0, 32),
padding: const EdgeInsets.symmetric(horizontal: 8),
textStyle: const TextStyle(fontSize: 12.5),
),
child: const Text('停止'),
),
TextButton(
onPressed: widget.onOpen,
style: TextButton.styleFrom(
minimumSize: const Size(0, 32),
padding: const EdgeInsets.symmetric(horizontal: 8),
textStyle: const TextStyle(fontSize: 12.5),
),
child: const Text('查看全部'),
),
],
),
if (tail.isEmpty)
Padding(
padding: const EdgeInsets.only(bottom: 6),
child: Text(
_feed.error ?? (ended ? '没有输出' : '等待输出…'),
style: TextStyle(fontSize: 12, color: theme.hintColor)),
)
else
Padding(
padding: const EdgeInsets.only(top: 2, bottom: 6),
child: SelectableText(
tail,
style: const TextStyle(
fontSize: 12, fontFamily: 'monospace', height: 1.4),
),
),
],
),
);
}
Future<void> _stop() async {
final ok = await confirmStopShell(context, widget.task.command);
if (ok == true) await widget.onStop();
}
static String _tail(String text, int lines) {
if (text.isEmpty) return '';
final all = text.split('\n');
if (all.length <= lines) return text;
return '…\n${all.sublist(all.length - lines).join('\n')}';
}
}
/// "停止这个任务?" with the command, as the first-party client asks.
Future<bool?> confirmStopShell(BuildContext context, String command) {
return showDialog<bool>(
context: context,
builder: (dialog) => AlertDialog(
title: const Text('停止这个任务?'),
content: Text(
command,
maxLines: 4,
overflow: TextOverflow.ellipsis,
style: const TextStyle(fontSize: 13, fontFamily: 'monospace'),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(dialog, false),
child: const Text('取消')),
FilledButton(
style: FilledButton.styleFrom(
backgroundColor: Theme.of(dialog).colorScheme.error,
foregroundColor: Theme.of(dialog).colorScheme.onError,
),
onPressed: () => Navigator.pop(dialog, true),
child: const Text('停止'),
),
],
),
);
}
/// Reads a shell's output a page at a time (one poll a second) and says when
/// the command ended. Shared by the sheet and the tool row preview.
class ShellOutputFeed {
ShellOutputFeed({
required this.client,
required this.task,
required this.directory,
});
final Client client;
final ShellTask task;
final String directory;
String text = '';
bool ended = false;
String? error;
int _cursor = 0;
bool _first = true;
bool _busy = false;
int _ticks = 0;
Timer? _timer;
VoidCallback? _onUpdate;
void start(VoidCallback onUpdate) {
if (_timer != null) return;
_onUpdate = onUpdate;
unawaited(_poll());
_timer = Timer.periodic(const Duration(seconds: 1), (_) => _poll());
}
Future<void> _poll() async {
if (_busy) return;
_busy = true;
try {
if (_first) {
final page = await client.shellOutput(task.id, directory: directory);
_first = false;
if (page.size > shellOutputTailBytes) {
// Long command: start near the end instead of reading it all.
final tail = await client.shellOutput(
task.id,
cursor: page.size - shellOutputTailBytes,
limit: shellOutputTailBytes,
directory: directory,
);
text = tail.output;
_cursor = tail.cursor;
} else {
text = page.output;
_cursor = page.cursor;
}
error = null;
} else if (!ended) {
final page = await client.shellOutput(task.id,
cursor: _cursor, directory: directory);
if (page.output.isNotEmpty) text = _keepTail(text + page.output);
_cursor = page.cursor;
error = null;
}
if (!ended && ++_ticks % 3 == 0) {
final shell = await client.shell(task.id, directory: directory);
if (shell == null || !shell.running) {
if (!ended) {
final last = await client
.shellOutput(task.id, cursor: _cursor, directory: directory)
.catchError((_) => const ShellOutputPage());
if (last.output.isNotEmpty) text = _keepTail(text + last.output);
_cursor = last.cursor;
}
ended = true;
_timer?.cancel();
_timer = null;
}
}
_onUpdate?.call();
} on ApiError catch (e) {
if (e.status == 404) {
ended = true;
error = null;
_timer?.cancel();
_timer = null;
} else {
error = '读取输出失败:${e.message}';
}
_onUpdate?.call();
} catch (e) {
error = '读取输出失败:$e';
_onUpdate?.call();
} finally {
_busy = false;
}
}
static String _keepTail(String text) => text.length <= shellOutputTailBytes
? text
: text.substring(text.length - shellOutputTailBytes);
void dispose() {
_timer?.cancel();
_timer = null;
}
}
+1 -1
View File
@@ -2,7 +2,7 @@ name: openchamber
description: "A lightweight OpenChamber client for phones."
publish_to: 'none'
version: 0.4.13+413
version: 0.4.14+414
environment:
sdk: ^3.14.0
+302
View File
@@ -0,0 +1,302 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:openchamber/api/models.dart';
import 'package:openchamber/api/shells.dart';
import 'package:openchamber/background_jobs.dart';
import 'package:openchamber/widgets/shell_jobs.dart';
ContentPart shellCall({
String name = 'bash',
String status = 'completed',
String command = 'pnpm dev',
Map<String, dynamic>? metadata,
}) {
return ContentPart(
type: 'tool',
name: name,
state: ToolState(
status: status,
input: {'command': command},
metadata: metadata,
),
);
}
void main() {
group('backgroundShellId', () {
test('a detached command is completed with a running shell id', () {
expect(
backgroundShellId(shellCall(metadata: {
'status': 'running',
'shellID': 'sh_abc',
})),
'sh_abc',
);
});
test('a foreground command has the id but no detached marker', () {
expect(backgroundShellId(shellCall(metadata: {'shellID': 'sh_abc'})),
isNull);
expect(
backgroundShellId(shellCall(
status: 'running',
metadata: {'status': 'running', 'shellID': 'sh_abc'},
)),
isNull,
);
});
test('other tools and broken metadata say nothing', () {
expect(
backgroundShellId(
shellCall(name: 'read', metadata: {'status': 'running', 'shellID': 'sh_a'})),
isNull,
);
expect(backgroundShellId(shellCall(metadata: null)), isNull);
expect(
backgroundShellId(shellCall(metadata: {'status': 'running', 'shellID': ''})),
isNull,
);
});
});
test('the transcript gives command and start time for the strip', () {
final messages = [
Message(id: 'm1', type: 'assistant', created: 1000, content: [
shellCall(command: 'sleep 600', metadata: {
'status': 'running',
'shellID': 'sh_one',
}),
shellCall(metadata: {'shellID': 'sh_foreground'}),
]),
];
final tasks = backgroundShellsFromMessages(messages, 'ses_x');
expect(tasks, hasLength(1));
expect(tasks.single.id, 'sh_one');
expect(tasks.single.command, 'sleep 600');
expect(tasks.single.startedAt, 1000);
expect(tasks.single.sessionId, 'ses_x');
});
test('the job list gives shell jobs with their shell id and owner', () {
final tasks = shellTasksFromJobs({
'data': [
{
'id': 'job_a',
'kind': 'shell',
'status': 'running',
'sessionID': 'ses_a',
'shellID': 'sh_a',
'command': 'npm run dev',
'time': {'started': 1795000000000},
},
{
'id': 'job_b',
'kind': 'image',
'status': 'running',
'sessionID': 'ses_a',
'path': '/tmp/a.png',
'model': 'm',
'time': {'started': 1795000000000},
},
{
'id': 'job_c',
'kind': 'shell',
'status': 'completed',
'sessionID': 'ses_a',
'shellID': 'sh_c',
'command': 'npm test',
'time': {'started': 1794000000000},
},
],
});
expect(tasks, hasLength(1));
expect(tasks.single.id, 'sh_a');
expect(tasks.single.sessionId, 'ses_a');
expect(tasks.single.command, 'npm run dev');
expect(tasks.single.startedAt, 1795000000000);
});
test('a completion note gives the shell id, state and output', () {
final note = shellCompletionNote(Message(
id: 's',
type: 'synthetic',
text: '<background-result kind="shell" id="sh_a" state="completed" '
'command="echo hi">\nhi\nthere\n</background-result>',
));
expect(note, isNotNull);
expect(note!.shellId, 'sh_a');
expect(note.state, 'completed');
expect(note.output, 'hi\nthere');
expect(note.failed, isFalse);
final failed = shellCompletionNote(Message(
id: 's2',
type: 'synthetic',
text: '<background-result kind="shell" id="sh_b" state="error">\n'
'Shell.NotFoundError\n</background-result>',
));
expect(failed!.failed, isTrue);
expect(
shellCompletionNote(
Message(id: 's3', type: 'synthetic', text: 'plain note')),
isNull,
);
expect(
shellCompletionNote(Message(
id: 's4',
type: 'synthetic',
text: '<background-result kind="subagent" id="x" state="completed">'
'\ndone\n</background-result>',
)),
isNull,
);
});
test('the newest completion for a shell wins', () {
Message note(String id, String output) => Message(
id: id,
type: 'synthetic',
text: '<background-result kind="shell" id="sh_a" '
'state="completed">\n$output\n</background-result>',
);
final found = shellCompletionFor(
[note('n1', 'first'), note('n2', 'second')], 'sh_a');
expect(found!.output, 'second');
expect(shellCompletionFor([note('n1', 'x')], 'sh_other'), isNull);
});
test('a stop note marks its shells as stopped by the user', () {
final messages = [
Message(
id: 's',
type: 'synthetic',
text: 'The user stopped the background command `sleep 1`.',
metadata: {
'openchamber': {
'shellStop': {
'shellIDs': ['sh_a', 'sh_b'],
},
},
},
),
Message(id: 'a', type: 'assistant', text: 'ok'),
];
expect(shellWasStopped(messages, 'sh_a'), isTrue);
expect(shellWasStopped(messages, 'sh_b'), isTrue);
expect(shellWasStopped(messages, 'sh_c'), isFalse);
expect(shellWasStopped(const [], 'sh_a'), isFalse);
});
test('the shell list keeps owner, clock and running state', () {
final tasks = shellTasksFromList({
'location': {'directory': '/repo'},
'data': [
{
'id': 'sh_a',
'status': 'running',
'command': 'npm run dev',
'metadata': {'sessionID': 'ses_a'},
'time': {'started': 1795000000000},
},
{
'id': 'sh_b',
'status': 'exited',
'command': 'npm test',
'metadata': {},
'time': {'started': 1794000000000},
},
],
});
expect(tasks.map((t) => t.id), ['sh_a', 'sh_b']);
expect(tasks.first.running, isTrue);
expect(tasks.first.sessionId, 'ses_a');
expect(tasks.first.startedAt, 1795000000000);
expect(tasks.last.running, isFalse);
});
test('an output page reads text, cursor and size', () {
final page = ShellOutputPage.fromJson({
'data': {'output': 'one\ntwo\n', 'cursor': 8, 'size': 8, 'truncated': false},
});
expect(page.output, 'one\ntwo\n');
expect(page.cursor, 8);
expect(page.size, 8);
expect(page.truncated, isFalse);
expect(ShellOutputPage.fromJson({}).output, '');
});
test('elapsed reads in seconds, minutes and hours', () {
expect(formatElapsed(0), '0秒');
expect(formatElapsed(12 * 1000), '12秒');
expect(formatElapsed(185 * 1000), '3分05秒');
expect(formatElapsed(3723 * 1000), '1:02:03');
});
test('the stop note names the command and says it was the user', () {
final note = stopNote(' pnpm dev ');
expect(note, contains('pnpm dev'));
expect(note, contains('user stopped'));
expect(note, contains('Shell.NotFoundError'));
});
group('ShellTaskBar', () {
ShellTask task(String id, {String command = 'pnpm dev', String session = 'ses_a'}) =>
ShellTask(
id: id,
sessionId: session,
command: command,
startedAt: DateTime.now().millisecondsSinceEpoch - 65000,
);
Future<void> pump(WidgetTester tester, List<ShellTask> tasks) async {
await tester.pumpWidget(MaterialApp(
home: Scaffold(
body: Column(
children: [
ShellTaskBar(
tasks: tasks,
sessionId: 'ses_a',
onOpen: (_) {},
onStop: (_) {},
),
],
),
),
));
}
testWidgets('one command is its own row, with stop and clock',
(tester) async {
await pump(tester, [task('sh_1', command: 'pnpm dev')]);
expect(find.text('pnpm dev'), findsOneWidget);
expect(find.text('停止'), findsOneWidget);
expect(find.text('1分05秒'), findsOneWidget);
expect(find.textContaining('正在执行'), findsNothing);
});
testWidgets('two commands share a count header and both show',
(tester) async {
await pump(tester, [
task('sh_1', command: 'pnpm dev'),
task('sh_2', command: 'pnpm test', session: 'ses_child'),
]);
expect(find.text('正在执行 2 条命令'), findsOneWidget);
expect(find.text('pnpm dev'), findsOneWidget);
expect(find.text('pnpm test'), findsOneWidget);
expect(find.text('子代理'), findsOneWidget);
expect(find.text('停止'), findsNWidgets(2));
});
testWidgets('a long list folds until asked', (tester) async {
await pump(tester, [for (var i = 0; i < 4; i++) task('sh_$i', command: 'cmd $i')]);
expect(find.text('正在执行 4 条命令'), findsOneWidget);
expect(find.text('cmd 0'), findsNothing);
await tester.tap(find.text('正在执行 4 条命令'));
await tester.pump();
expect(find.text('cmd 0'), findsOneWidget);
expect(find.text('cmd 3'), findsOneWidget);
});
});
}