Files
openchamber-android-native/lib/widgets/shell_jobs.dart
T
blumia 9564019a91 fix: match the background task bar to the activity strip
- draw the task bar in the activity strip's capsule (8px margins, 14px
  padding, 36px min height, stadium radius) so the two read as one stack
- drop the stop button from the bar: its padding pushed the clock off the
  right edge shared with the strip above; the row opens the sheet instead
- in the sheet, show only the clock while running, a stop button with a
  stop icon, and "已结束" once the command ends; no "运行中" label and no
  close x (the drag handle and the scrim already close it)
- say "读取输出…" while the first page loads instead of claiming the
  command has printed nothing
- rest the pet's feet on the status capsule's edge (4px top margin)
  instead of sinking 2px into it
2026-11-24 23:19:47 +08:00

750 lines
23 KiB
Dart

// 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;
/// Tapping a row opens its output; the stop lives in that sheet.
final void Function(ShellTask task) onOpen;
const ShellTaskBar({
super.key,
required this.tasks,
required this.sessionId,
required this.onOpen,
});
@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;
// The same capsule as the activity strip above it: one row of text in the
// same stadium, with the same margins, so the two read as one stack.
return Padding(
padding: const EdgeInsets.fromLTRB(8, 4, 8, 4),
child: Material(
color: theme.colorScheme.surfaceContainerHighest.withValues(alpha: 0.7),
shape: const StadiumBorder(),
clipBehavior: Clip.antiAlias,
child: ConstrainedBox(
constraints: const BoxConstraints(minHeight: 36),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 6),
child: Column(
mainAxisSize: MainAxisSize.min,
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),
),
],
),
),
),
),
);
}
Widget _header(ThemeData theme, int count) {
return InkWell(
onTap: () => setState(() => _expanded = !_open),
child: SizedBox(
height: 24,
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,
fontWeight: FontWeight.w600,
color: theme.colorScheme.onSurface,
),
),
),
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;
const _ShellTaskRow({
super.key,
required this.task,
required this.subagent,
required this.onTap,
});
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return InkWell(
onTap: onTap,
child: SizedBox(
height: 24,
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.5, fontFamily: 'monospace', height: 1.3),
),
),
if (subagent) ...[
const SizedBox(width: 6),
Text('子代理',
style: TextStyle(
fontSize: 12,
color: theme.colorScheme.onSurfaceVariant,
)),
],
const SizedBox(width: 8),
// The clock ends on the capsule's inner edge, the same line the
// activity strip's clock ends on above it; stopping is a tap away
// in the sheet, so no button here to break that line.
ShellElapsed(startedAt: task.startedAt),
],
),
),
);
}
}
/// `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: [
// The drag handle above and a tap on the scrim close the sheet;
// a close button would only repeat them.
Padding(
padding: const EdgeInsets.fromLTRB(20, 0, 20, 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),
),
),
],
),
),
Padding(
padding: const EdgeInsets.fromLTRB(20, 0, 20, 8),
child: Row(
children: [
// No "运行中" label: a live sheet is running by definition,
// and the clock says since when. Only the end is worth saying.
if (running)
ShellElapsed(
startedAt: widget.task.startedAt, running: true)
else ...[
Icon(Icons.check_circle_outline,
size: 15, color: theme.hintColor),
const SizedBox(width: 6),
Text('已结束',
style:
TextStyle(fontSize: 12, color: theme.hintColor)),
],
const Spacer(),
if (running)
TextButton.icon(
onPressed: _stopping ? null : _stop,
icon: const Icon(Icons.stop_rounded, size: 17),
label: Text(_stopping ? '停止中…' : '停止'),
style: TextButton.styleFrom(
foregroundColor: theme.colorScheme.error,
minimumSize: const Size(0, 32),
padding: const EdgeInsets.symmetric(horizontal: 10),
),
),
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: Column(
mainAxisSize: MainAxisSize.min,
children: [
if (_feed.error == null && !_feed.loaded) ...[
const SizedBox(
width: 16,
height: 16,
child:
CircularProgressIndicator(strokeWidth: 1.8),
),
const SizedBox(height: 10),
],
Text(
_feed.error ??
(!_feed.loaded
? '读取输出…'
: 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 = '';
/// The first page has been read: before that, an empty [text] means the
/// read is still under way, not that the command has printed nothing.
bool loaded = false;
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;
loaded = true;
} 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;
loaded = 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;
}
}