// 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'; import '../l10n.dart'; /// One line of "正在执行 N 条命令", folding when there are many. class ShellTaskBar extends StatefulWidget { final List 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 createState() => _ShellTaskBarState(); } class _ShellTaskBarState extends State { /// 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( trArgs('Running {0} commands', [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), AppText('Subagent', 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 createState() => _ShellElapsedState(); } class _ShellElapsedState extends State { 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 showShellOutput( BuildContext context, { required Client client, required ShellTask task, required String directory, required Future Function() onStop, String? finalOutput, bool done = false, }) { return showModalBottomSheet( 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 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 createState() => _ShellOutputSheetState(); } class _ShellOutputSheetState extends State { 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 _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), AppText('Ended', 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: AppText(_stopping ? 'Stopping…' : 'Stop'), 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 AppText('Copy'), 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), ], AppText( _feed.error ?? (!_feed.loaded ? 'Reading output…' : running ? 'Waiting for output…' : 'No output'), 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 AppText('Jump to latest'), style: FilledButton.styleFrom( visualDensity: VisualDensity.compact, ), ), ), ], ), ), ], ), ); } Future _copy() async { await Clipboard.setData(ClipboardData(text: _text)); if (mounted) { ScaffoldMessenger.of(context) .showSnackBar(const SnackBar(content: AppText('Output copied'))); } } } /// 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 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 createState() => _ShellOutputInlineState(); } class _ShellOutputInlineState extends State { 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), AppText('Background output', style: TextStyle(fontSize: 12, color: theme.hintColor)), const SizedBox(width: 8), if (!ended) AppText('Running', style: TextStyle( fontSize: 12, color: theme.colorScheme.primary)), if (ended && text.isEmpty) AppText('Ended', 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 AppText('Stop'), ), 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 AppText('View all'), ), ], ), if (tail.isEmpty) Padding( padding: const EdgeInsets.only(bottom: 6), child: AppText( _feed.error ?? (ended ? 'No output' : 'Waiting for output…'), 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 _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 confirmStopShell(BuildContext context, String command) { return showDialog( context: context, builder: (dialog) => AlertDialog( title: const AppText('Stop this task?'), content: Text( command, maxLines: 4, overflow: TextOverflow.ellipsis, style: const TextStyle(fontSize: 13, fontFamily: 'monospace'), ), actions: [ TextButton( onPressed: () => Navigator.pop(dialog, false), child: const AppText('Cancel')), FilledButton( style: FilledButton.styleFrom( backgroundColor: Theme.of(dialog).colorScheme.error, foregroundColor: Theme.of(dialog).colorScheme.onError, ), onPressed: () => Navigator.pop(dialog, true), child: const AppText('Stop'), ), ], ), ); } /// 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 _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 = trArgs('Could not read output: {0}', [e.message]); } _onUpdate?.call(); } catch (e) { error = trArgs('Could not read output: {0}', ['$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; } }