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

+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.