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 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; 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; setState(() => _output = const ChatShellOutputSnapshot(loading: true)); try { final reply = await _repository.shellOutput( widget.sessionId, shellId, cursor: 0, limit: chatShellOutputLimit, ); if (!mounted || _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 || _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); return Padding( key: const Key('chat-background-tasks'), 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, 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( children: [ Expanded( child: Semantics( header: true, child: Text(backgroundTasksTitle, style: titleStyle), ), ), if (countKnown) Text(backgroundTasksRunningLabel(count), 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( 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, button: true, child: CupertinoButton( key: key, padding: EdgeInsets.zero, onPressed: () => _select(id), child: Row( spacing: 8, children: [ Icon(CupertinoIcons.play_fill, color: primary), Text(shellRowLabel, style: style.copyWith(color: primary)), Expanded( child: Text( command, maxLines: 1, overflow: TextOverflow.ellipsis, style: style.copyWith(color: muted), ), ), if (selected) Text( shellDetailsLabel, style: CupertinoTheme.of( context, ).textTheme.tabLabelTextStyle.copyWith(color: muted), ), ], ), ), ); } final theme = Theme.of(context); return Semantics( selected: selected, child: ListTile( key: key, dense: true, contentPadding: EdgeInsets.zero, leading: Icon(Icons.play_arrow, color: theme.colorScheme.tertiary), title: Row( spacing: 8, children: [ Text( shellRowLabel, style: theme.textTheme.labelMedium?.copyWith( color: theme.colorScheme.tertiary, ), ), Expanded( child: Text( command, maxLines: 1, overflow: TextOverflow.ellipsis, style: theme.textTheme.labelMedium?.copyWith( color: theme.colorScheme.onSurfaceVariant, ), ), ), ], ), trailing: selected ? Text(shellDetailsLabel, style: theme.textTheme.labelSmall) : null, onTap: () => _select(id), ), ); } }