Files
openchamber-android-native/lib/widgets/shell_jobs.dart
T

727 lines
22 KiB
Dart
Raw Normal View History

// 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;
}
}