import 'dart:async'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import '../../../core/api_gateway.dart'; import '../../../core/error_reason.dart'; import '../data/chat_repository.dart'; import '../domain/chat_shells.dart'; import '../ui/sessions/chat_adaptive.dart'; import 'chat_background_task_detail.dart'; /// The bar is pinned above the transcript, so the whole surface keeps at most /// this share of the window and scrolls inside itself. The transcript and the /// composer therefore always keep most of the window, however many tasks are /// listed and however large the selected page is. const backgroundTaskViewportShare = 0.5; /// The running background tasks a chat session owns (C11). /// /// The list is read from recorded facts only: the session's `chat_shells` /// snapshot on open and every pushed `shell` frame for that session. Every task /// is linked to its conversation because both reads carry this session's id. /// A task that exits leaves the list, so the bar disappears with the last exit /// instead of keeping a history of finished processes. /// /// Selecting a task reveals its read-only detail and reads one bounded output /// page (`chat_shell_output`, cursor 0, the server's 64 KiB limit). The pane /// reports an unavailable or empty page and a refused read truthfully; it never /// invents output. A refused list read is reported with the server's reason and /// a native Retry rather than pretending there are no tasks. class ChatBackgroundTasks extends StatefulWidget { const ChatBackgroundTasks({ super.key, required this.gateway, required this.sessionId, this.syncToken = 0, }); final ApiGateway gateway; final String sessionId; /// Advances when the shared socket is replaced: a gap may have swallowed an /// exit, so the retained tasks are dropped and re-learned from the snapshot. final int syncToken; @override State createState() => _ChatBackgroundTasksState(); } class _ChatBackgroundTasksState extends State { late ChatRepository _repository = ChatRepository(widget.gateway); StreamSubscription? _frames; List _shells = const []; String? _selectedId; ChatShellOutputSnapshot? _output; String? _listError; int _generation = 0; int _outputGeneration = 0; bool _disposed = false; @override void initState() { super.initState(); _listen(); unawaited(_loadShells()); } @override void didUpdateWidget(covariant ChatBackgroundTasks oldWidget) { super.didUpdateWidget(oldWidget); if (oldWidget.gateway != widget.gateway || oldWidget.sessionId != widget.sessionId) { unawaited(_frames?.cancel()); _generation++; _repository = ChatRepository(widget.gateway); _shells = const []; _selectedId = null; _output = null; _listError = null; _listen(); unawaited(_loadShells()); return; } if (oldWidget.syncToken != widget.syncToken) { // The reconnect repair: an exit could have been lost in the gap. _shells = const []; _selectedId = null; _output = null; _listError = null; unawaited(_loadShells()); } } void _listen() => _frames = widget.gateway.frames.listen(_onFrame, onError: (_) {}); void _onFrame(JsonMap envelope) { if (_disposed || envelope['type'] != 'chat_event') return; final value = envelope['chat_event']; if (value is! Map) return; final frame = Map.from(value); if ('${frame['session_id'] ?? ''}' != widget.sessionId) return; if (frame['kind'] != 'shell') return; final valueShell = frame['shell']; if (valueShell is! Map) return; final next = mergeShellFrame( _shells, Map.from(valueShell), ); setState(() { _shells = next; _dropStaleSelection(); }); } Future _loadShells() async { final token = ++_generation; try { final running = await _repository.shells(widget.sessionId); if (!mounted || token != _generation) return; setState(() { _shells = shellsLoaded(_shells, running); _listError = null; _dropStaleSelection(); }); } catch (error) { if (!mounted || token != _generation) return; setState( () => _listError = describeErrorReason( error, fallback: 'The server did not answer.', ), ); } } /// An exit, or a fresh snapshot that no longer lists the selected task, /// closes its pane so a finished task never keeps showing output. void _dropStaleSelection() { final selected = _selectedId; if (selected == null) return; if (!runningShells(_shells).any((shell) => shellIdOf(shell) == selected)) { _selectedId = null; _output = null; } } void _select(String shellId) { final closing = _selectedId == shellId; if (!closing && !runningShells(_shells).any((shell) => shellIdOf(shell) == shellId)) { return; } setState(() { _selectedId = closing ? null : shellId; _output = null; }); if (!closing) unawaited(_readOutput(shellId)); } Future _readOutput(String shellId) async { if (_selectedId != shellId) return; final token = ++_outputGeneration; setState(() => _output = const ChatShellOutputSnapshot(loading: true)); try { final reply = await _repository.shellOutput( widget.sessionId, shellId, cursor: 0, limit: chatShellOutputLimit, ); if (!mounted || token != _outputGeneration || _selectedId != shellId) { return; } final page = ChatShellOutputPage.fromReply(reply); final reported = page.shell; setState(() { if (reported != null && !blankShellValue(reported['id'])) { _shells = mergeShellFrame(_shells, reported); } _output = ChatShellOutputSnapshot(page: page); _dropStaleSelection(); }); } catch (error) { if (!mounted || token != _outputGeneration || _selectedId != shellId) { return; } setState( () => _output = ChatShellOutputSnapshot( error: describeErrorReason( error, fallback: 'The server did not answer.', ), ), ); } } @override void dispose() { _disposed = true; _generation++; unawaited(_frames?.cancel()); super.dispose(); } @override Widget build(BuildContext context) { final running = runningShells(_shells); final error = _listError; // Recorded facts only, honestly: no tasks and no refusal draws nothing. if (running.isEmpty && error == null) return const SizedBox.shrink(); final cupertino = chatControlsStyleOf(context) == ChatControlsStyle.cupertino; final selectedShell = _selectedShell(running); // The bar is pinned above the transcript, so it keeps a bounded share of // the window and scrolls its own body. Even three rows plus an open detail // can then never push the transcript or the composer out of the viewport. return ConstrainedBox( key: const Key('chat-background-tasks'), constraints: BoxConstraints( maxHeight: MediaQuery.sizeOf(context).height * backgroundTaskViewportShare, ), child: LayoutBuilder( builder: (context, constraints) => SingleChildScrollView( key: const Key('chat-background-tasks-scroll'), padding: const EdgeInsetsDirectional.fromSTEB(16, 4, 16, 4), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, spacing: 4, children: [ _heading(context, cupertino, running.length, error == null), if (error != null) _listFailure(context, cupertino, error), if (running.isNotEmpty) _taskList(context, cupertino, running), if (selectedShell != null) ChatBackgroundTaskDetail( key: const Key('chat-bg-task-detail'), shell: selectedShell, output: _output, // The detail derives its output pane from the space this bar // actually has left instead of the whole window. heightBudget: constraints.maxHeight, onRefresh: () => unawaited(_readOutput(shellIdOf(selectedShell))), ), ], ), ), ), ); } /// The running task this visit has selected, or null after it exited. JsonMap? _selectedShell(List running) { for (final shell in running) { if (shellIdOf(shell) == _selectedId) return shell; } return null; } Widget _heading( BuildContext context, bool cupertino, int count, bool countKnown, ) { final titleStyle = cupertino ? CupertinoTheme.of(context).textTheme.textStyle : Theme.of(context).textTheme.labelLarge; final countStyle = cupertino ? CupertinoTheme.of(context).textTheme.tabLabelTextStyle.copyWith( color: CupertinoColors.secondaryLabel.resolveFrom(context), ) : Theme.of(context).textTheme.labelMedium?.copyWith( color: Theme.of(context).colorScheme.onSurfaceVariant, ); return Row( spacing: 8, children: [ Expanded( flex: 2, child: Semantics( header: true, child: Text( backgroundTasksTitle, // One compact line like the web's head: a large text scale elides // rather than wrapping the heading into a tall stack. maxLines: 1, overflow: TextOverflow.ellipsis, style: titleStyle, ), ), ), if (countKnown) Flexible( child: Text( backgroundTasksRunningLabel(count), maxLines: 1, overflow: TextOverflow.ellipsis, style: countStyle, ), ), ], ); } Widget _listFailure(BuildContext context, bool cupertino, String error) { final color = cupertino ? CupertinoColors.systemRed.resolveFrom(context) : Theme.of(context).colorScheme.error; final style = (cupertino ? CupertinoTheme.of(context).textTheme.textStyle : Theme.of(context).textTheme.bodySmall) ?.copyWith(color: color); return Row( key: const Key('chat-background-tasks-error'), crossAxisAlignment: CrossAxisAlignment.start, children: [ Icon( cupertino ? CupertinoIcons.exclamationmark_circle : Icons.error_outline, color: color, ), const SizedBox(width: 8), Expanded( child: Padding( padding: const EdgeInsets.symmetric(vertical: 8), child: Text('Background tasks unavailable. $error', style: style), ), ), ChatBackgroundTaskButton( label: shellOutputRetryLabel, onPressed: () => unawaited(_loadShells()), ), ], ); } Widget _taskList( BuildContext context, bool cupertino, List running, ) { final rows = [ for (final shell in running) _taskRow(context, cupertino, shell, shellIdOf(shell) == _selectedId), ]; final list = Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: rows, ); if (rows.length <= backgroundTaskVisibleRows) return list; // More than the recorded visible-row cap: the list scrolls instead of // pushing the composer down. The bound is the host's own touch target. return ConstrainedBox( key: const Key('chat-bg-task-list'), constraints: const BoxConstraints( maxHeight: kMinInteractiveDimension * backgroundTaskVisibleRows, ), child: SingleChildScrollView(child: list), ); } Widget _taskRow( BuildContext context, bool cupertino, JsonMap shell, bool selected, ) { final id = shellIdOf(shell); final key = ValueKey('chat-bg-task-$id'); final command = shellCommandSummary(shell['command']); if (cupertino) { final primary = CupertinoTheme.of(context).primaryColor; final muted = CupertinoColors.secondaryLabel.resolveFrom(context); final style = CupertinoTheme.of(context).textTheme.textStyle; return Semantics( selected: selected, child: CupertinoButton( key: key, padding: EdgeInsets.zero, onPressed: () => _select(id), child: Row( spacing: 8, children: [ Icon(CupertinoIcons.play_fill, color: primary), Flexible( child: Text( shellRowLabel, maxLines: 1, overflow: TextOverflow.ellipsis, style: style.copyWith(color: primary), ), ), Expanded( flex: 3, child: Text( command, maxLines: 1, overflow: TextOverflow.ellipsis, style: style.copyWith(color: muted), ), ), if (selected) Flexible( child: Text( shellDetailsLabel, maxLines: 1, overflow: TextOverflow.ellipsis, style: CupertinoTheme.of( context, ).textTheme.tabLabelTextStyle.copyWith(color: muted), ), ), ], ), ), ); } final theme = Theme.of(context); final fullCommand = '${shell['command'] ?? ''}'.trim(); final rowStyle = theme.textTheme.labelMedium; return Semantics( selected: selected, child: Tooltip( // The row elides its command; the full recorded one stays reachable, // as the web row's `title` attribute does. message: fullCommand.isEmpty ? command : fullCommand, excludeFromSemantics: true, child: ListTile( key: key, dense: true, contentPadding: EdgeInsets.zero, leading: Icon(Icons.play_arrow, color: theme.colorScheme.tertiary), title: Row( spacing: 8, children: [ // Every part of the row is flexible: at a large text scale or a // narrow phone the labels elide instead of overflowing the row. Flexible( child: Text( shellRowLabel, maxLines: 1, overflow: TextOverflow.ellipsis, style: rowStyle?.copyWith(color: theme.colorScheme.tertiary), ), ), Expanded( flex: 3, child: Text( command, maxLines: 1, overflow: TextOverflow.ellipsis, style: rowStyle?.copyWith( color: theme.colorScheme.onSurfaceVariant, ), ), ), if (selected) Flexible( child: Text( shellDetailsLabel, maxLines: 1, overflow: TextOverflow.ellipsis, style: theme.textTheme.labelSmall, ), ), ], ), onTap: () => _select(id), ), ), ); } }