From 2cb4a0c5550619087a136882555d75e73f12f169 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 22 Oct 2026 17:14:56 +0100 Subject: [PATCH 1/2] feat(app): show a session's running background tasks The conversation reads the session's recorded chat_shells snapshot and folds pushed shell frames, so only tasks the server still reports as running appear. The list is capped at three visible rows and scrolls beyond, and a task that exits leaves it. Selecting a task opens its recorded command, identity and running status plus one bounded chat_shell_output page (cursor 0, 64 KiB). Empty, unavailable and refused reads are reported with native Retry/Refresh controls, and a refused snapshot is shown with its reason instead of claiming there are no tasks. Both reads carry the session id, linking every task to its conversation. --- .../chat_background_task_detail.dart | 201 +++++++++ .../conversation/chat_background_tasks.dart | 405 +++++++++++++++++ .../chat/conversation/chat_thread_view.dart | 10 + app/lib/features/chat/domain/chat_shells.dart | 182 ++++++++ .../chat_background_tasks_test.dart | 412 ++++++++++++++++++ .../chat/domain/chat_shells_test.dart | 160 +++++++ 6 files changed, 1370 insertions(+) create mode 100644 app/lib/features/chat/conversation/chat_background_task_detail.dart create mode 100644 app/lib/features/chat/conversation/chat_background_tasks.dart create mode 100644 app/lib/features/chat/domain/chat_shells.dart create mode 100644 app/test/features/chat/conversation/chat_background_tasks_test.dart create mode 100644 app/test/features/chat/domain/chat_shells_test.dart diff --git a/app/lib/features/chat/conversation/chat_background_task_detail.dart b/app/lib/features/chat/conversation/chat_background_task_detail.dart new file mode 100644 index 00000000..23ed4972 --- /dev/null +++ b/app/lib/features/chat/conversation/chat_background_task_detail.dart @@ -0,0 +1,201 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../core/api_gateway.dart'; +import '../domain/chat_shells.dart'; +import '../ui/sessions/chat_adaptive.dart'; + +/// The selected background task's read-only detail and bounded output page. +/// +/// Every value is a recorded fact: the server's command, the shell identity, the +/// running status, and one lazy `chat_shell_output` page. The output area keeps +/// the five states apart, so an unavailable or empty page and a refused read are +/// never shown as output. Output is selectable and reads in a monospace body. +class ChatBackgroundTaskDetail extends StatelessWidget { + const ChatBackgroundTaskDetail({ + super.key, + required this.shell, + required this.output, + required this.onRefresh, + }); + + final JsonMap shell; + final ChatShellOutputSnapshot? output; + final VoidCallback onRefresh; + + @override + Widget build(BuildContext context) { + final cupertino = + chatControlsStyleOf(context) == ChatControlsStyle.cupertino; + final content = DefaultTextStyle.merge( + style: cupertino + ? CupertinoTheme.of(context).textTheme.textStyle + : DefaultTextStyle.of(context).style, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + spacing: 4, + children: [ + _label(context, cupertino, shellOutputCommandLabel), + Text( + blankShellValue(shell['command']) + ? shellOutputUnavailableLabel + : '${shell['command']}', + ), + _label(context, cupertino, shellOutputTaskIdentityLabel), + Text( + shellIdOf(shell), + style: const TextStyle(fontFamily: 'monospace'), + ), + Text(shellStatusRunningLabel), + _outputArea(context, cupertino), + ], + ), + ); + if (cupertino) { + return CupertinoListSection.insetGrouped( + children: [Padding(padding: const EdgeInsets.all(12), child: content)], + ); + } + return Card( + margin: EdgeInsets.zero, + child: Padding(padding: const EdgeInsets.all(12), child: content), + ); + } + + Widget _label(BuildContext context, bool cupertino, String text) { + final style = cupertino + ? CupertinoTheme.of(context).textTheme.tabLabelTextStyle.copyWith( + color: CupertinoColors.secondaryLabel.resolveFrom(context), + ) + : Theme.of(context).textTheme.labelSmall?.copyWith( + color: Theme.of(context).colorScheme.onSurfaceVariant, + ); + return Text(text, style: style); + } + + /// Selectable output in the host's own control. A Cupertino-only app has no + /// `MaterialLocalizations`, which `SelectableText` asserts on, so one English + /// default scope is supplied for its context menu (the chat markdown view's + /// own pattern). + Widget _selectableOutput( + BuildContext context, + bool cupertino, + String output, + ) { + final text = SelectableText( + output, + key: const Key('chat-bg-task-output'), + style: + (cupertino + ? CupertinoTheme.of(context).textTheme.textStyle + : Theme.of(context).textTheme.bodySmall) + ?.copyWith( + fontFamily: 'monospace', + // Cupertino's style is not inheriting; a selectable body needs a + // baseline from its own style. + textBaseline: TextBaseline.alphabetic, + ), + ); + if (!cupertino) return text; + return Localizations( + locale: Localizations.maybeLocaleOf(context) ?? const Locale('en'), + delegates: const [ + DefaultWidgetsLocalizations.delegate, + DefaultMaterialLocalizations.delegate, + DefaultCupertinoLocalizations.delegate, + ], + child: text, + ); + } + + Widget _outputArea(BuildContext context, bool cupertino) { + final state = output?.state ?? ChatShellOutputState.none; + final muted = cupertino + ? CupertinoColors.secondaryLabel.resolveFrom(context) + : Theme.of(context).colorScheme.onSurfaceVariant; + final noteStyle = + (cupertino + ? CupertinoTheme.of(context).textTheme.textStyle + : Theme.of(context).textTheme.bodySmall) + ?.copyWith(color: muted); + switch (state) { + case ChatShellOutputState.none: + return const SizedBox.shrink(); + case ChatShellOutputState.loading: + return Align( + alignment: AlignmentDirectional.centerStart, + child: cupertino + ? const CupertinoActivityIndicator() + : const CircularProgressIndicator(), + ); + case ChatShellOutputState.error: + return Row( + key: const Key('chat-bg-task-output-error'), + crossAxisAlignment: CrossAxisAlignment.start, + spacing: 8, + children: [ + Expanded( + child: Text( + '${output?.error ?? ''}', + style: noteStyle?.copyWith( + color: cupertino + ? CupertinoColors.systemRed.resolveFrom(context) + : Theme.of(context).colorScheme.error, + ), + ), + ), + ChatBackgroundTaskButton( + label: shellOutputRetryLabel, + onPressed: onRefresh, + ), + ], + ); + case ChatShellOutputState.unavailable: + return Text(shellOutputUnavailableNote, style: noteStyle); + case ChatShellOutputState.empty: + return Text(shellOutputEmptyNote, style: noteStyle); + case ChatShellOutputState.ready: + final page = output!.page!; + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + spacing: 4, + children: [ + _label(context, cupertino, shellOutputLabel), + _selectableOutput(context, cupertino, page.output), + if (page.truncated) Text(shellOutputBoundedNote, style: noteStyle), + Align( + alignment: AlignmentDirectional.centerStart, + child: ChatBackgroundTaskButton( + label: shellOutputRefreshLabel, + onPressed: onRefresh, + ), + ), + ], + ); + } + } +} + +/// The host's own text button for a task action (Retry/Refresh). +class ChatBackgroundTaskButton extends StatelessWidget { + const ChatBackgroundTaskButton({ + super.key, + required this.label, + required this.onPressed, + }); + + final String label; + final VoidCallback onPressed; + + @override + Widget build(BuildContext context) { + if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino) { + return CupertinoButton( + padding: EdgeInsets.zero, + onPressed: onPressed, + child: Text(label), + ); + } + return TextButton(onPressed: onPressed, child: Text(label)); + } +} diff --git a/app/lib/features/chat/conversation/chat_background_tasks.dart b/app/lib/features/chat/conversation/chat_background_tasks.dart new file mode 100644 index 00000000..7bab853d --- /dev/null +++ b/app/lib/features/chat/conversation/chat_background_tasks.dart @@ -0,0 +1,405 @@ +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), + ), + ); + } +} diff --git a/app/lib/features/chat/conversation/chat_thread_view.dart b/app/lib/features/chat/conversation/chat_thread_view.dart index ce85ad5b..54e1ec6c 100644 --- a/app/lib/features/chat/conversation/chat_thread_view.dart +++ b/app/lib/features/chat/conversation/chat_thread_view.dart @@ -10,6 +10,7 @@ import '../domain/chat_transcript.dart'; import '../ui/sessions/chat_adaptive.dart'; import '../ui/transcript/chat_markdown_view.dart'; import '../ui/transcript/chat_message_view.dart'; +import 'chat_background_tasks.dart'; import 'chat_composer_bar.dart'; import 'chat_composer_controller.dart'; import 'chat_draft_store.dart'; @@ -290,6 +291,15 @@ class _ChatThreadViewState extends State { final liveNotice = _noticeOf(notices, ChatNoticeKind.liveFailure); return Column( children: [ + // The session's still-running background tasks, above the transcript + // and outside its scroller (web C11). It removes itself when the last + // task exits and never draws a finished task. + ChatBackgroundTasks( + key: ValueKey('chat-background-tasks-${widget.sessionId}'), + gateway: widget.gateway, + sessionId: widget.sessionId, + syncToken: widget.syncToken, + ), Expanded( child: ListView( key: ValueKey('chat-thread-${widget.sessionId}'), diff --git a/app/lib/features/chat/domain/chat_shells.dart b/app/lib/features/chat/domain/chat_shells.dart new file mode 100644 index 00000000..b8422820 --- /dev/null +++ b/app/lib/features/chat/domain/chat_shells.dart @@ -0,0 +1,182 @@ +import '../../../core/api_gateway.dart'; + +/// The background shells a chat session owns (C11). +/// +/// These are recorded facts only: the status and command come from the server's +/// `chat_shells` snapshot or a pushed `shell` frame. Nothing here invents an +/// exit, an output or a command, and every read below is scoped to one session +/// so a task stays linked to the conversation that owns it. +const chatShellRunning = 'running'; +const chatShellExited = 'exited'; + +/// The retained shell tail a client keeps (mirrors ChatStore's observation +/// bound). This is not task history, only what this client itself observed. +const observedShellLimit = 16; + +/// How many running-task rows are drawn before the list scrolls instead of +/// growing, so a burst of tasks cannot push the composer off screen. +const backgroundTaskVisibleRows = 3; + +/// The server's absolute-byte bound for one lazy output page +/// (ChatShellOutputLimit). Reads always start at cursor 0. +const chatShellOutputLimit = 64 * 1024; + +const backgroundTasksTitle = 'Background tasks'; +const shellRowLabel = 'Running'; +const shellDetailsLabel = 'Details'; + +String backgroundTasksRunningLabel(int count) => '$count running'; + +const shellOutputCommandLabel = 'Command'; +const shellOutputUnavailableLabel = 'Unavailable'; +const shellOutputTaskIdentityLabel = 'Task identity'; +const shellStatusRunningLabel = 'Status: running'; +const shellOutputUnavailableNote = 'Output unavailable for this task.'; +const shellOutputEmptyNote = 'No output yet.'; +const shellOutputLabel = 'Output'; +const shellOutputBoundedNote = 'Output is bounded to 64 KiB.'; +const shellOutputRetryLabel = 'Retry'; +const shellOutputRefreshLabel = 'Refresh'; + +/// The generic name for a running shell that reported no command, rather than +/// an empty row. Mirrors the web and Android shellCommandSummary. +const shellCommandFallback = 'background process'; + +/// A one-line command is elided past this width like a tool call's detail. +const shellCommandSummaryLength = 72; + +bool blankShellValue(Object? value) => value == null || '$value'.trim().isEmpty; + +String shellIdOf(JsonMap shell) => '${shell['id'] ?? ''}'; + +/// Whether [shell] is a task that is still running: a non-blank id whose status +/// the server recorded as running. An exited shell is never a task. +bool isRunningShell(JsonMap shell) => + !blankShellValue(shell['id']) && + '${shell['status'] ?? ''}' == chatShellRunning; + +/// The running tasks in the order they started. The visible-row cap is a view +/// concern, so this never truncates the recorded list. +List runningShells(List shells) => [ + for (final shell in shells) + if (isRunningShell(shell)) shell, +]; + +/// Folds one shell frame (or a snapshot entry) into the retained shells, keyed +/// by id and kept in observation order. +/// +/// A blank incoming command keeps the command already learned, so a later frame +/// that omits it never blanks the row. The retained list is trimmed to the last +/// [observedShellLimit] entries. +List mergeShellFrame(List shells, JsonMap? shell) { + if (shell == null || blankShellValue(shell['id'])) return shells; + final id = shellIdOf(shell); + final next = List.of(shells); + final index = next.indexWhere((candidate) => shellIdOf(candidate) == id); + final prior = index >= 0 ? next[index] : null; + final merged = { + ...shell, + 'id': id, + 'command': blankShellValue(shell['command']) + ? (prior?['command'] ?? '') + : shell['command'], + }; + if (index >= 0) { + next[index] = merged; + } else { + next.add(merged); + } + return next.length <= observedShellLimit + ? next + : next.sublist(next.length - observedShellLimit); +} + +/// Folds a `chat_shells` snapshot into the retained shells: an exit this client +/// observed is kept, the server's current running list wins by id, and a shell +/// the server no longer lists (and whose exit this client never saw) drops out. +List shellsLoaded(List shells, List running) { + final byId = {}; + for (final shell in shells) { + if (!blankShellValue(shell['id']) && + '${shell['status'] ?? ''}' == chatShellExited) { + byId[shellIdOf(shell)] = shell; + } + } + for (final shell in running) { + if (blankShellValue(shell['id'])) continue; + byId[shellIdOf(shell)] = shell; + } + final values = byId.values.toList(); + return values.length <= observedShellLimit + ? values + : values.sublist(values.length - observedShellLimit); +} + +/// The one-line command a background process is running: whitespace collapsed, +/// elided past [shellCommandSummaryLength], and a generic word when the server +/// reported no command. +String shellCommandSummary(Object? command) { + final text = '${command ?? ''}'.trim().replaceAll(RegExp(r'\s+'), ' '); + if (text.isEmpty) return shellCommandFallback; + if (text.length <= shellCommandSummaryLength) return text; + return '${text.substring(0, shellCommandSummaryLength - 1).trimRight()}…'; +} + +/// One bounded, read-only output page from a verified shell. Unknown fields stay +/// empty/false instead of being guessed. +class ChatShellOutputPage { + const ChatShellOutputPage({ + this.output = '', + this.truncated = false, + this.unavailable = false, + this.shell, + }); + + factory ChatShellOutputPage.fromReply(JsonMap reply) { + final value = reply['chat_shell_output']; + final page = value is Map + ? Map.from(value) + : const {}; + final shell = page['shell']; + return ChatShellOutputPage( + output: '${page['output'] ?? ''}', + truncated: page['truncated'] == true, + unavailable: page['unavailable'] == true, + shell: shell is Map ? Map.from(shell) : null, + ); + } + + final String output; + final bool truncated; + final bool unavailable; + + /// The shell the page reports, so a settled task can be folded back into the + /// retained list without losing the command already learned. + final JsonMap? shell; +} + +/// The five shapes a selected task's output area can take. Unknown fields are +/// reported as unavailable or empty, never rendered as invented output. +enum ChatShellOutputState { none, loading, error, unavailable, empty, ready } + +class ChatShellOutputSnapshot { + const ChatShellOutputSnapshot({ + this.loading = false, + this.error = '', + this.page, + }); + + final bool loading; + final String error; + final ChatShellOutputPage? page; + + ChatShellOutputState get state { + if (loading) return ChatShellOutputState.loading; + if (error.trim().isNotEmpty) return ChatShellOutputState.error; + final current = page; + if (current == null) return ChatShellOutputState.none; + if (current.unavailable) return ChatShellOutputState.unavailable; + if (current.output.isEmpty) return ChatShellOutputState.empty; + return ChatShellOutputState.ready; + } +} diff --git a/app/test/features/chat/conversation/chat_background_tasks_test.dart b/app/test/features/chat/conversation/chat_background_tasks_test.dart new file mode 100644 index 00000000..770aec02 --- /dev/null +++ b/app/test/features/chat/conversation/chat_background_tasks_test.dart @@ -0,0 +1,412 @@ +import 'dart:async'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/core/transport/connection_state.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_background_tasks.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart'; +import 'package:pipelines_app/features/chat/domain/chat_shells.dart'; + +/// A gateway that scripts the session snapshot and bounded output reads and can +/// push a shell frame for the selected conversation. +class _TasksGateway implements ApiGateway { + final calls = <({String type, JsonMap fields})>[]; + final _frames = StreamController.broadcast(); + Future Function()? shells; + Future Function(JsonMap fields)? output; + + @override + Stream get frames => _frames.stream; + + @override + Future call(String type, [JsonMap fields = const {}]) async { + calls.add((type: type, fields: fields)); + switch (type) { + case 'chat_shells': + return shells == null + ? {'chat_shells': const []} + : shells!(); + case 'chat_shell_output': + return output == null + ? {'chat_shell_output': const {}} + : output!(fields); + case 'chat_subscribe': + return {}; + case 'chat_messages': + return { + 'chat_history': { + 'messages': const [], + 'next_cursor': '', + 'has_more': false, + }, + }; + } + return {}; + } + + List fieldsFor(String type) => [ + for (final call in calls) + if (call.type == type) call.fields, + ]; + + void emitShell( + String id, + String status, { + String command = '', + String session = 's', + }) => _frames.add({ + 'type': 'chat_event', + 'chat_event': { + 'session_id': session, + 'kind': 'shell', + 'shell': {'id': id, 'status': status, 'command': command}, + }, + }); + + void close() => _frames.close(); +} + +JsonMap _running(String id, {String command = 'go test ./...'}) => { + 'id': id, + 'status': 'running', + 'command': command, +}; + +JsonMap _snapshot(List shells) => {'chat_shells': shells}; + +Widget _host( + _TasksGateway gateway, { + bool cupertino = false, + int syncToken = 0, +}) { + final child = ChatBackgroundTasks( + gateway: gateway, + sessionId: 's', + syncToken: syncToken, + ); + if (cupertino) { + return CupertinoApp( + home: CupertinoPageScaffold(child: SingleChildScrollView(child: child)), + ); + } + return MaterialApp( + theme: ThemeData(platform: TargetPlatform.android), + home: Scaffold(body: SingleChildScrollView(child: child)), + ); +} + +Widget _thread(_TasksGateway gateway) => MaterialApp( + theme: ThemeData(platform: TargetPlatform.android), + home: Scaffold( + body: ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {}), + ), +); + +Future _tapTask(WidgetTester tester, String id) async { + await tester.tap(find.byKey(ValueKey('chat-bg-task-$id'))); + await tester.pumpAndSettle(); +} + +void main() { + testWidgets('shows only the session snapshot tasks that are still running', ( + tester, + ) async { + final gateway = _TasksGateway(); + gateway.shells = () async => _snapshot([ + _running('sh1'), + {'id': 'sh2', 'status': 'exited', 'command': 'pnpm build'}, + {'id': '', 'status': 'running', 'command': 'no identity'}, + ]); + addTearDown(gateway.close); + + await tester.pumpWidget(_host(gateway)); + await tester.pumpAndSettle(); + + expect(find.text('Background tasks'), findsOneWidget); + expect(find.text('1 running'), findsOneWidget); + expect(find.text('Running'), findsOneWidget); + expect(find.text('go test ./...'), findsOneWidget); + expect(find.text('pnpm build'), findsNothing); + expect(find.text('no identity'), findsNothing); + expect(gateway.fieldsFor('chat_shells'), [ + { + 'chat_query': {'session_id': 's'}, + }, + ]); + }); + + testWidgets('an honest empty snapshot draws no task surface', (tester) async { + final gateway = _TasksGateway(); + addTearDown(gateway.close); + + await tester.pumpWidget(_host(gateway)); + await tester.pumpAndSettle(); + + expect(find.byKey(const Key('chat-background-tasks')), findsNothing); + expect(find.text('Background tasks'), findsNothing); + expect(gateway.fieldsFor('chat_shells'), hasLength(1)); + }); + + testWidgets('pushed shell frames add and remove this session tasks', ( + tester, + ) async { + final gateway = _TasksGateway(); + addTearDown(gateway.close); + + await tester.pumpWidget(_host(gateway)); + await tester.pumpAndSettle(); + expect(find.text('Background tasks'), findsNothing); + + gateway.emitShell('sh1', 'running', command: 'tail -f server.log'); + await tester.pumpAndSettle(); + expect(find.text('Background tasks'), findsOneWidget); + expect(find.text('1 running'), findsOneWidget); + expect(find.text('tail -f server.log'), findsOneWidget); + + gateway.emitShell('sh1', 'exited'); + await tester.pumpAndSettle(); + expect(find.text('Background tasks'), findsNothing); + + gateway.emitShell('other', 'running', session: 'other-session'); + await tester.pumpAndSettle(); + expect(find.text('Background tasks'), findsNothing); + }); + + testWidgets('more than three running tasks scroll inside the bar', ( + tester, + ) async { + final gateway = _TasksGateway() + ..shells = () async => _snapshot([ + for (var index = 0; index < 4; index++) _running('sh$index'), + ]); + addTearDown(gateway.close); + + await tester.pumpWidget(_host(gateway)); + await tester.pumpAndSettle(); + + expect(find.text('4 running'), findsOneWidget); + expect( + find.descendant( + of: find.byType(ChatBackgroundTasks), + matching: find.byType(SingleChildScrollView), + ), + findsOneWidget, + ); + for (var index = 0; index < 4; index++) { + expect( + find.byKey(ValueKey('chat-bg-task-sh$index')), + findsOneWidget, + ); + } + }); + + testWidgets('selecting a task reads one bounded session-linked page', ( + tester, + ) async { + final gateway = _TasksGateway(); + gateway.shells = () async => _snapshot([_running('sh1')]); + gateway.output = (fields) async => { + 'chat_shell_output': { + 'shell': _running('sh1'), + 'output': 'ok example\n--- PASS: TestOne\n', + 'cursor': 0, + 'size': 8192, + 'truncated': true, + }, + }; + addTearDown(gateway.close); + + await tester.pumpWidget(_host(gateway)); + await tester.pumpAndSettle(); + await _tapTask(tester, 'sh1'); + + expect(gateway.fieldsFor('chat_shell_output'), [ + { + 'chat_shell_output_query': { + 'session_id': 's', + 'shell_id': 'sh1', + 'cursor': 0, + 'limit': 64 * 1024, + }, + }, + ]); + expect(find.byKey(const Key('chat-bg-task-detail')), findsOneWidget); + expect(find.text('Command'), findsOneWidget); + expect(find.text('Task identity'), findsOneWidget); + expect(find.text('sh1'), findsOneWidget); + expect(find.text('Status: running'), findsOneWidget); + expect(find.text('Output'), findsOneWidget); + expect( + tester + .widget(find.byKey(const Key('chat-bg-task-output'))) + .data, + 'ok example\n--- PASS: TestOne\n', + ); + expect(find.text('Output is bounded to 64 KiB.'), findsOneWidget); + expect(find.text('Refresh'), findsOneWidget); + + // Selecting the open task again closes its detail without another read. + await _tapTask(tester, 'sh1'); + expect(find.byKey(const Key('chat-bg-task-detail')), findsNothing); + expect(gateway.fieldsFor('chat_shell_output'), hasLength(1)); + }); + + testWidgets('the output pane reports empty, unavailable and a refusal', ( + tester, + ) async { + final gateway = _TasksGateway() + ..shells = () async => _snapshot([_running('sh1')]); + addTearDown(gateway.close); + + await tester.pumpWidget(_host(gateway)); + await tester.pumpAndSettle(); + + gateway.output = (_) async => { + 'chat_shell_output': {'shell': _running('sh1')}, + }; + await _tapTask(tester, 'sh1'); + expect(find.text('No output yet.'), findsOneWidget); + + gateway.output = (_) async => { + 'chat_shell_output': {'shell': _running('sh1'), 'unavailable': true}, + }; + await _tapTask(tester, 'sh1'); + await _tapTask(tester, 'sh1'); + expect(find.text('Output unavailable for this task.'), findsOneWidget); + + gateway.output = (_) async => throw ProtocolError('output refused'); + await _tapTask(tester, 'sh1'); + await _tapTask(tester, 'sh1'); + expect(find.byKey(const Key('chat-bg-task-output-error')), findsOneWidget); + expect(find.text('output refused'), findsOneWidget); + expect(find.text('Retry'), findsOneWidget); + + gateway.output = (_) async => { + 'chat_shell_output': {'shell': _running('sh1'), 'output': 'fresh output'}, + }; + await tester.tap(find.text('Retry')); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('chat-bg-task-output-error')), findsNothing); + expect( + tester + .widget(find.byKey(const Key('chat-bg-task-output'))) + .data, + 'fresh output', + ); + }); + + testWidgets('a refused snapshot is reported and Retry rereads it', ( + tester, + ) async { + final gateway = _TasksGateway() + ..shells = () async => throw ProtocolError('server down'); + addTearDown(gateway.close); + + await tester.pumpWidget(_host(gateway)); + await tester.pumpAndSettle(); + + expect( + find.textContaining('Background tasks unavailable. server down'), + findsOneWidget, + ); + expect(find.text('0 running'), findsNothing); + + gateway.shells = () async => _snapshot([_running('sh1')]); + await tester.tap(find.text('Retry')); + await tester.pumpAndSettle(); + + expect(find.byKey(const Key('chat-background-tasks-error')), findsNothing); + expect(find.text('Background tasks'), findsOneWidget); + expect(find.text('1 running'), findsOneWidget); + expect(gateway.fieldsFor('chat_shells'), hasLength(2)); + }); + + testWidgets('an exit closes the selected pane and the bar', (tester) async { + final gateway = _TasksGateway(); + gateway.shells = () async => _snapshot([_running('sh1')]); + gateway.output = (_) async => { + 'chat_shell_output': { + 'shell': _running('sh1'), + 'output': 'still running', + }, + }; + addTearDown(gateway.close); + + await tester.pumpWidget(_host(gateway)); + await tester.pumpAndSettle(); + await _tapTask(tester, 'sh1'); + expect(find.byKey(const Key('chat-bg-task-detail')), findsOneWidget); + + gateway.emitShell('sh1', 'exited'); + await tester.pumpAndSettle(); + + expect(find.byKey(const Key('chat-bg-task-detail')), findsNothing); + expect(find.text('Background tasks'), findsNothing); + }); + + testWidgets('a replaced socket drops held tasks and re-learns the snapshot', ( + tester, + ) async { + final gateway = _TasksGateway() + ..shells = () async => _snapshot([_running('sh1')]); + addTearDown(gateway.close); + + await tester.pumpWidget(_host(gateway)); + await tester.pumpAndSettle(); + expect(find.text('1 running'), findsOneWidget); + + gateway.shells = () async => _snapshot(const []); + await tester.pumpWidget(_host(gateway, syncToken: 1)); + await tester.pumpAndSettle(); + + expect(find.text('Background tasks'), findsNothing); + expect(gateway.fieldsFor('chat_shells'), hasLength(2)); + }); + + testWidgets('the Cupertino host keeps native buttons and the same facts', ( + tester, + ) async { + final gateway = _TasksGateway(); + gateway.shells = () async => _snapshot([_running('sh1')]); + gateway.output = (_) async => { + 'chat_shell_output': { + 'shell': _running('sh1'), + 'output': 'native output', + }, + }; + addTearDown(gateway.close); + + await tester.pumpWidget(_host(gateway, cupertino: true)); + await tester.pumpAndSettle(); + + expect(find.byType(CupertinoButton), findsWidgets); + expect(find.text('1 running'), findsOneWidget); + await _tapTask(tester, 'sh1'); + + expect(find.text('Command'), findsOneWidget); + expect(find.text('Status: running'), findsOneWidget); + expect( + tester + .widget(find.byKey(const Key('chat-bg-task-output'))) + .data, + 'native output', + ); + }); + + testWidgets('the conversation mounts the session task surface', ( + tester, + ) async { + final gateway = _TasksGateway() + ..shells = () async => _snapshot([_running('sh1')]); + addTearDown(gateway.close); + + await tester.pumpWidget(_thread(gateway)); + await tester.pumpAndSettle(); + + expect(find.byKey(const Key('chat-background-tasks')), findsOneWidget); + expect(find.text('Background tasks'), findsOneWidget); + expect(find.text('1 running'), findsOneWidget); + }); +} diff --git a/app/test/features/chat/domain/chat_shells_test.dart b/app/test/features/chat/domain/chat_shells_test.dart new file mode 100644 index 00000000..477896f0 --- /dev/null +++ b/app/test/features/chat/domain/chat_shells_test.dart @@ -0,0 +1,160 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/chat/domain/chat_shells.dart'; + +JsonMap _shell(String id, String status, {String command = ''}) => { + 'id': id, + 'status': status, + 'command': command, +}; + +void main() { + group('recorded running tasks', () { + test('only a non-blank id with status running is a task', () { + final shells = [ + _shell('sh1', 'running', command: 'go test ./...'), + _shell('sh2', 'exited', command: 'pnpm build'), + _shell('', 'running', command: 'no identity'), + {'status': 'running', 'command': 'no id'}, + _shell('sh3', 'pending', command: 'not started'), + ]; + + expect(runningShells(shells).map((shell) => shell['id']), ['sh1']); + }); + + test('a shell frame merges by id and keeps the command already known', () { + final first = mergeShellFrame( + const [], + _shell('sh1', 'running', command: 'go test ./...'), + ); + final exited = mergeShellFrame(first, _shell('sh1', 'exited')); + final other = mergeShellFrame( + exited, + _shell('sh2', 'running', command: 'sleep 1'), + ); + + expect(other, hasLength(2)); + expect(other.first['status'], 'exited'); + expect(other.first['command'], 'go test ./...'); + expect(runningShells(other).map((shell) => shell['id']), ['sh2']); + expect(mergeShellFrame(other, null), same(other)); + expect(mergeShellFrame(other, _shell('', 'running')), same(other)); + }); + + test('the retained observation tail is bounded', () { + var shells = const []; + for (var index = 0; index < observedShellLimit + 4; index++) { + shells = mergeShellFrame(shells, _shell('sh$index', 'running')); + } + + expect(shells, hasLength(observedShellLimit)); + expect(shells.first['id'], 'sh4'); + expect(shells.last['id'], 'sh${observedShellLimit + 3}'); + }); + + test('a snapshot keeps observed exits and drops shells never seen', () { + final observed = [ + _shell('exited', 'exited', command: 'pnpm build'), + _shell('running', 'running', command: 'go test ./...'), + _shell('gone', 'running', command: 'old fact'), + ]; + final loaded = shellsLoaded(observed, [ + _shell('running', 'running', command: 'go test ./...'), + _shell('new', 'running', command: 'tail -f log'), + ]); + + expect(loaded.map((shell) => '${shell['id']}:${shell['status']}'), [ + 'exited:exited', + 'running:running', + 'new:running', + ]); + expect(runningShells(loaded).map((shell) => shell['id']), [ + 'running', + 'new', + ]); + }); + }); + + group('shell wording', () { + test('the command collapses whitespace and names a blank one', () { + expect(shellCommandSummary(' go test\n ./... '), 'go test ./...'); + expect(shellCommandSummary(' '), 'background process'); + expect(shellCommandSummary(null), 'background process'); + }); + + test('a long command is elided to the tool-detail width', () { + final summary = shellCommandSummary('x' * 200); + + expect(summary.length, shellCommandSummaryLength); + expect(summary.endsWith('…'), isTrue); + expect(summary, '${'x' * (shellCommandSummaryLength - 1)}…'); + }); + + test('the heading keeps the recorded count', () { + expect(backgroundTasksTitle, 'Background tasks'); + expect(backgroundTasksRunningLabel(0), '0 running'); + expect(backgroundTasksRunningLabel(3), '3 running'); + }); + }); + + group('bounded output page', () { + test('a page carries its output, bound and reported shell', () { + final page = ChatShellOutputPage.fromReply({ + 'chat_shell_output': { + 'shell': {'id': 'sh1', 'status': 'running', 'command': 'go test'}, + 'output': 'ok example\n', + 'cursor': 0, + 'size': 11, + 'truncated': true, + }, + }); + + expect(page.output, 'ok example\n'); + expect(page.truncated, isTrue); + expect(page.unavailable, isFalse); + expect(page.shell?['command'], 'go test'); + expect(chatShellOutputLimit, 64 * 1024); + }); + + test('an unknown reply parses as no page, never invented output', () { + final page = ChatShellOutputPage.fromReply(const {}); + + expect(page.output, ''); + expect(page.shell, isNull); + expect( + const ChatShellOutputSnapshot(page: ChatShellOutputPage()).state, + ChatShellOutputState.empty, + ); + }); + + test( + 'the pane state follows loading, error, unavailable, empty, ready', + () { + expect( + const ChatShellOutputSnapshot().state, + ChatShellOutputState.none, + ); + expect( + const ChatShellOutputSnapshot(loading: true).state, + ChatShellOutputState.loading, + ); + expect( + const ChatShellOutputSnapshot(error: 'refused').state, + ChatShellOutputState.error, + ); + expect( + const ChatShellOutputSnapshot( + page: ChatShellOutputPage(unavailable: true), + ).state, + ChatShellOutputState.unavailable, + ); + expect( + const ChatShellOutputSnapshot( + page: ChatShellOutputPage(output: 'ready'), + ).state, + ChatShellOutputState.ready, + ); + }, + ); + }); +} From a26bfe2b0c66a028c6695bccf65d758c99407114 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 22 Oct 2026 17:53:48 +0100 Subject: [PATCH 2/2] fix(app): bound the background-task output pane and row labels Review 139 found the selected task's output page unbounded, overflowing a phone-height conversation. The bar now keeps half the viewport and scrolls its own body, the output pane is capped at twelve scaled lines, row labels elide instead of overflowing, and a reply without a page reads as unavailable rather than empty. --- .../chat_background_task_detail.dart | 74 +++++-- .../conversation/chat_background_tasks.dart | 185 ++++++++++++------ app/lib/features/chat/domain/chat_shells.dart | 9 +- .../chat_background_tasks_test.dart | 182 ++++++++++++++++- .../chat/domain/chat_shells_test.dart | 7 +- 5 files changed, 380 insertions(+), 77 deletions(-) diff --git a/app/lib/features/chat/conversation/chat_background_task_detail.dart b/app/lib/features/chat/conversation/chat_background_task_detail.dart index 23ed4972..df2f2552 100644 --- a/app/lib/features/chat/conversation/chat_background_task_detail.dart +++ b/app/lib/features/chat/conversation/chat_background_task_detail.dart @@ -1,3 +1,5 @@ +import 'dart:math' as math; + import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; @@ -5,6 +7,18 @@ import '../../../core/api_gateway.dart'; import '../domain/chat_shells.dart'; import '../ui/sessions/chat_adaptive.dart'; +/// One bounded output page: the web's 220 px pane is twelve 18 px monospace +/// lines (`web/chat.css`), so the bound is read from the host's own output type +/// and the user's text scale rather than a fixed pixel row. A longer page +/// scrolls inside this box and never moves the transcript or composer. +const _outputVisibleLines = 12; +const _outputLineHeight = 1.5; + +/// Even at a large text scale one pane keeps this share of the bar's own height +/// budget, so the bar's chrome and list keep room and the conversation below it +/// is never crowded out. +const _outputMaxBudgetShare = 0.45; + /// The selected background task's read-only detail and bounded output page. /// /// Every value is a recorded fact: the server's command, the shell identity, the @@ -16,11 +30,18 @@ class ChatBackgroundTaskDetail extends StatelessWidget { super.key, required this.shell, required this.output, + required this.heightBudget, required this.onRefresh, }); final JsonMap shell; final ChatShellOutputSnapshot? output; + + /// The space the enclosing task bar has for its whole body. The output pane is + /// measured against this, not the window, so a list of rows, a narrow phone or + /// a large text scale cannot make the detail outgrow its own bar. + final double heightBudget; + final VoidCallback onRefresh; @override @@ -73,6 +94,31 @@ class ChatBackgroundTaskDetail extends StatelessWidget { return Text(text, style: style); } + /// The host's own monospace body for one output page. `height` is set so the + /// visible-line bound below is measured on the same line box that is drawn. + TextStyle _outputStyle(BuildContext context, bool cupertino) => + (cupertino + ? CupertinoTheme.of(context).textTheme.textStyle + : Theme.of(context).textTheme.bodySmall ?? const TextStyle()) + .copyWith( + fontFamily: 'monospace', + height: _outputLineHeight, + // Cupertino's style is not inheriting; a selectable body needs a + // baseline from its own style. + textBaseline: TextBaseline.alphabetic, + ); + + /// The number of output lines the pane shows before it scrolls: up to twelve, + /// fewer when the user's text scale or the bar's remaining height would let + /// the pane crowd out the conversation. + int _outputVisibleLineCount(BuildContext context, TextStyle style) { + final scaledLine = + MediaQuery.textScalerOf(context).scale(style.fontSize ?? 12) * + _outputLineHeight; + final fit = (heightBudget * _outputMaxBudgetShare / scaledLine).floor(); + return math.max(2, math.min(_outputVisibleLines, fit)); + } + /// Selectable output in the host's own control. A Cupertino-only app has no /// `MaterialLocalizations`, which `SelectableText` asserts on, so one English /// default scope is supplied for its context menu (the chat markdown view's @@ -81,20 +127,17 @@ class ChatBackgroundTaskDetail extends StatelessWidget { BuildContext context, bool cupertino, String output, + TextStyle style, + int maxLines, ) { final text = SelectableText( output, key: const Key('chat-bg-task-output'), - style: - (cupertino - ? CupertinoTheme.of(context).textTheme.textStyle - : Theme.of(context).textTheme.bodySmall) - ?.copyWith( - fontFamily: 'monospace', - // Cupertino's style is not inheriting; a selectable body needs a - // baseline from its own style. - textBaseline: TextBaseline.alphabetic, - ), + style: style, + // A multiline selectable body scrolls itself: the host's text control + // keeps the page selectable and gives it its own scrollbar/drag, so no + // nested scroller can steal the conversation's gestures. + maxLines: maxLines, ); if (!cupertino) return text; return Localizations( @@ -136,7 +179,7 @@ class ChatBackgroundTaskDetail extends StatelessWidget { children: [ Expanded( child: Text( - '${output?.error ?? ''}', + output?.error ?? '', style: noteStyle?.copyWith( color: cupertino ? CupertinoColors.systemRed.resolveFrom(context) @@ -156,12 +199,19 @@ class ChatBackgroundTaskDetail extends StatelessWidget { return Text(shellOutputEmptyNote, style: noteStyle); case ChatShellOutputState.ready: final page = output!.page!; + final style = _outputStyle(context, cupertino); return Column( crossAxisAlignment: CrossAxisAlignment.start, spacing: 4, children: [ _label(context, cupertino, shellOutputLabel), - _selectableOutput(context, cupertino, page.output), + _selectableOutput( + context, + cupertino, + page.output, + style, + _outputVisibleLineCount(context, style), + ), if (page.truncated) Text(shellOutputBoundedNote, style: noteStyle), Align( alignment: AlignmentDirectional.centerStart, diff --git a/app/lib/features/chat/conversation/chat_background_tasks.dart b/app/lib/features/chat/conversation/chat_background_tasks.dart index 7bab853d..69e6254c 100644 --- a/app/lib/features/chat/conversation/chat_background_tasks.dart +++ b/app/lib/features/chat/conversation/chat_background_tasks.dart @@ -10,6 +10,12 @@ 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` @@ -50,6 +56,7 @@ class _ChatBackgroundTasksState extends State { ChatShellOutputSnapshot? _output; String? _listError; int _generation = 0; + int _outputGeneration = 0; bool _disposed = false; @override @@ -154,6 +161,7 @@ class _ChatBackgroundTasksState extends State { Future _readOutput(String shellId) async { if (_selectedId != shellId) return; + final token = ++_outputGeneration; setState(() => _output = const ChatShellOutputSnapshot(loading: true)); try { final reply = await _repository.shellOutput( @@ -162,7 +170,9 @@ class _ChatBackgroundTasksState extends State { cursor: 0, limit: chatShellOutputLimit, ); - if (!mounted || _selectedId != shellId) return; + if (!mounted || token != _outputGeneration || _selectedId != shellId) { + return; + } final page = ChatShellOutputPage.fromReply(reply); final reported = page.shell; setState(() { @@ -173,7 +183,9 @@ class _ChatBackgroundTasksState extends State { _dropStaleSelection(); }); } catch (error) { - if (!mounted || _selectedId != shellId) return; + if (!mounted || token != _outputGeneration || _selectedId != shellId) { + return; + } setState( () => _output = ChatShellOutputSnapshot( error: describeErrorReason( @@ -202,24 +214,40 @@ class _ChatBackgroundTasksState extends State { final cupertino = chatControlsStyleOf(context) == ChatControlsStyle.cupertino; final selectedShell = _selectedShell(running); - return Padding( + // 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'), - 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))), - ), - ], + 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))), + ), + ], + ), + ), ), ); } @@ -249,15 +277,31 @@ class _ChatBackgroundTasksState extends State { color: Theme.of(context).colorScheme.onSurfaceVariant, ); return Row( + spacing: 8, children: [ Expanded( + flex: 2, child: Semantics( header: true, - child: Text(backgroundTasksTitle, style: titleStyle), + 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) - Text(backgroundTasksRunningLabel(count), style: countStyle), + Flexible( + child: Text( + backgroundTasksRunningLabel(count), + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: countStyle, + ), + ), ], ); } @@ -314,6 +358,7 @@ class _ChatBackgroundTasksState extends State { // 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, ), @@ -336,7 +381,6 @@ class _ChatBackgroundTasksState extends State { final style = CupertinoTheme.of(context).textTheme.textStyle; return Semantics( selected: selected, - button: true, child: CupertinoButton( key: key, padding: EdgeInsets.zero, @@ -345,8 +389,16 @@ class _ChatBackgroundTasksState extends State { spacing: 8, children: [ Icon(CupertinoIcons.play_fill, color: primary), - Text(shellRowLabel, style: style.copyWith(color: primary)), + Flexible( + child: Text( + shellRowLabel, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: style.copyWith(color: primary), + ), + ), Expanded( + flex: 3, child: Text( command, maxLines: 1, @@ -355,11 +407,15 @@ class _ChatBackgroundTasksState extends State { ), ), if (selected) - Text( - shellDetailsLabel, - style: CupertinoTheme.of( - context, - ).textTheme.tabLabelTextStyle.copyWith(color: muted), + Flexible( + child: Text( + shellDetailsLabel, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: CupertinoTheme.of( + context, + ).textTheme.tabLabelTextStyle.copyWith(color: muted), + ), ), ], ), @@ -367,38 +423,57 @@ class _ChatBackgroundTasksState extends State { ); } final theme = Theme.of(context); + final fullCommand = '${shell['command'] ?? ''}'.trim(); + final rowStyle = theme.textTheme.labelMedium; 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, + 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), ), - trailing: selected - ? Text(shellDetailsLabel, style: theme.textTheme.labelSmall) - : null, - onTap: () => _select(id), ), ); } diff --git a/app/lib/features/chat/domain/chat_shells.dart b/app/lib/features/chat/domain/chat_shells.dart index b8422820..f0693ec4 100644 --- a/app/lib/features/chat/domain/chat_shells.dart +++ b/app/lib/features/chat/domain/chat_shells.dart @@ -134,9 +134,12 @@ class ChatShellOutputPage { factory ChatShellOutputPage.fromReply(JsonMap reply) { final value = reply['chat_shell_output']; - final page = value is Map - ? Map.from(value) - : const {}; + // A reply without the page is not evidence of an empty shell. Report it as + // unavailable (as the web refuses it) instead of inventing "No output yet.". + if (value is! Map) { + return const ChatShellOutputPage(unavailable: true); + } + final page = Map.from(value); final shell = page['shell']; return ChatShellOutputPage( output: '${page['output'] ?? ''}', diff --git a/app/test/features/chat/conversation/chat_background_tasks_test.dart b/app/test/features/chat/conversation/chat_background_tasks_test.dart index 770aec02..44884133 100644 --- a/app/test/features/chat/conversation/chat_background_tasks_test.dart +++ b/app/test/features/chat/conversation/chat_background_tasks_test.dart @@ -76,6 +76,11 @@ JsonMap _running(String id, {String command = 'go test ./...'}) => { JsonMap _snapshot(List shells) => {'chat_shells': shells}; +/// A realistically long recorded page (200 shell lines, more than one screen). +List _pageLines() => [ + for (var index = 0; index < 200; index++) 'line $index', +]; + Widget _host( _TasksGateway gateway, { bool cupertino = false, @@ -187,12 +192,10 @@ void main() { await tester.pumpAndSettle(); expect(find.text('4 running'), findsOneWidget); + expect(find.byKey(const Key('chat-bg-task-list')), findsOneWidget); expect( - find.descendant( - of: find.byType(ChatBackgroundTasks), - matching: find.byType(SingleChildScrollView), - ), - findsOneWidget, + tester.getRect(find.byKey(const Key('chat-bg-task-list'))).height, + lessThanOrEqualTo(kMinInteractiveDimension * backgroundTaskVisibleRows), ); for (var index = 0; index < 4; index++) { expect( @@ -228,7 +231,7 @@ void main() { 'session_id': 's', 'shell_id': 'sh1', 'cursor': 0, - 'limit': 64 * 1024, + 'limit': chatShellOutputLimit, }, }, ]); @@ -263,10 +266,16 @@ void main() { await tester.pumpWidget(_host(gateway)); await tester.pumpAndSettle(); + // A reply with no page at all is unavailable, not "No output yet.". + gateway.output = (_) async => const {}; + await _tapTask(tester, 'sh1'); + expect(find.text('Output unavailable for this task.'), findsOneWidget); + gateway.output = (_) async => { 'chat_shell_output': {'shell': _running('sh1')}, }; await _tapTask(tester, 'sh1'); + await _tapTask(tester, 'sh1'); expect(find.text('No output yet.'), findsOneWidget); gateway.output = (_) async => { @@ -395,6 +404,167 @@ void main() { ); }); + testWidgets('a long output page scrolls inside a bounded pane', ( + tester, + ) async { + tester.view.physicalSize = const Size(400, 700); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + + final lines = [for (var index = 0; index < 200; index++) 'line $index']; + final gateway = _TasksGateway(); + gateway.shells = () async => _snapshot([_running('sh1')]); + gateway.output = (_) async => { + 'chat_shell_output': { + 'shell': _running('sh1'), + 'output': '${lines.join('\n')}\n', + }, + }; + addTearDown(gateway.close); + + await tester.pumpWidget(_thread(gateway)); + await tester.pumpAndSettle(); + await _tapTask(tester, 'sh1'); + + // A real shell tail is bounded: the transcript and composer stay in the + // viewport instead of being pushed out by the whole page. + expect(tester.takeException(), isNull); + final outputFinder = find.byKey(const Key('chat-bg-task-output')); + final output = tester.getRect(outputFinder); + expect(output.height, lessThanOrEqualTo(210)); + final detail = tester.getRect(find.byKey(const Key('chat-bg-task-detail'))); + final composer = tester.getRect( + find.byKey(const ValueKey('chat-composer-s')), + ); + expect(detail.bottom, lessThanOrEqualTo(composer.top)); + expect(composer.bottom, lessThanOrEqualTo(700)); + + // The page scrolls through the host's own text control to its last line. + expect( + tester.widget(outputFinder).data, + contains('line 199'), + ); + final scrollable = tester.state( + find.descendant(of: outputFinder, matching: find.byType(Scrollable)), + ); + expect(scrollable.position.maxScrollExtent, greaterThan(0)); + await tester.drag(outputFinder, const Offset(0, -300)); + await tester.pumpAndSettle(); + expect(scrollable.position.pixels, greaterThan(0)); + }); + + testWidgets('three tasks and an open page fit a 320px phone', (tester) async { + tester.view.physicalSize = const Size(320, 568); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + + final gateway = _TasksGateway(); + gateway.shells = () async => + _snapshot([_running('sh1'), _running('sh2'), _running('sh3')]); + gateway.output = (_) async => { + 'chat_shell_output': { + 'shell': _running('sh1'), + 'output': '${_pageLines().join('\n')}\n', + }, + }; + addTearDown(gateway.close); + + await tester.pumpWidget(_thread(gateway)); + await tester.pumpAndSettle(); + await _tapTask(tester, 'sh1'); + + // Three rows plus the whole detail can no longer take the viewport: the bar + // keeps its share, scrolls its own body, and the composer stays reachable. + expect(tester.takeException(), isNull); + final bar = tester.getRect(find.byKey(const Key('chat-background-tasks'))); + final composer = tester.getRect( + find.byKey(const ValueKey('chat-composer-s')), + ); + final transcript = tester.getRect( + find.byKey(const ValueKey('chat-thread-s')), + ); + expect( + bar.height, + lessThanOrEqualTo(568 * backgroundTaskViewportShare + 0.5), + ); + expect(bar.bottom, lessThanOrEqualTo(composer.top)); + expect(composer.bottom, lessThanOrEqualTo(568)); + expect(transcript.height, greaterThan(0)); + expect( + find.byKey(const Key('chat-background-tasks-scroll')), + findsOneWidget, + ); + }); + + testWidgets('one open task at 2x text keeps the composer on screen', ( + tester, + ) async { + tester.view.physicalSize = const Size(320, 568); + tester.view.devicePixelRatio = 1; + tester.platformDispatcher.textScaleFactorTestValue = 2; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue); + + final gateway = _TasksGateway(); + gateway.shells = () async => _snapshot([_running('sh1')]); + gateway.output = (_) async => { + 'chat_shell_output': { + 'shell': _running('sh1'), + 'output': '${_pageLines().join('\n')}\n', + }, + }; + addTearDown(gateway.close); + + await tester.pumpWidget(_thread(gateway)); + await tester.pumpAndSettle(); + await _tapTask(tester, 'sh1'); + expect(find.byKey(const Key('chat-bg-task-detail')), findsOneWidget); + + // The row labels and the detail are laid out at twice the text size without + // overflowing, and the bar's bound still leaves the composer on screen. + expect(tester.takeException(), isNull); + final bar = tester.getRect(find.byKey(const Key('chat-background-tasks'))); + final composer = tester.getRect( + find.byKey(const ValueKey('chat-composer-s')), + ); + expect(bar.bottom, lessThanOrEqualTo(composer.top)); + expect(composer.bottom, lessThanOrEqualTo(568)); + }); + + testWidgets('the Cupertino row elides its labels instead of overflowing', ( + tester, + ) async { + tester.view.physicalSize = const Size(320, 568); + tester.view.devicePixelRatio = 1; + tester.platformDispatcher.textScaleFactorTestValue = 2; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue); + + final gateway = _TasksGateway(); + gateway.shells = () async => _snapshot([ + _running('sh1', command: 'go test ./... -run TestSomethingLongEnough'), + ]); + gateway.output = (_) async => { + 'chat_shell_output': { + 'shell': _running('sh1'), + 'output': 'native output', + }, + }; + addTearDown(gateway.close); + + await tester.pumpWidget(_host(gateway, cupertino: true)); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + + await _tapTask(tester, 'sh1'); + expect(tester.takeException(), isNull); + expect(find.text('Details'), findsOneWidget); + }); + testWidgets('the conversation mounts the session task surface', ( tester, ) async { diff --git a/app/test/features/chat/domain/chat_shells_test.dart b/app/test/features/chat/domain/chat_shells_test.dart index 477896f0..89106b05 100644 --- a/app/test/features/chat/domain/chat_shells_test.dart +++ b/app/test/features/chat/domain/chat_shells_test.dart @@ -116,11 +116,16 @@ void main() { expect(chatShellOutputLimit, 64 * 1024); }); - test('an unknown reply parses as no page, never invented output', () { + test('a reply without the page is unavailable, never invented output', () { final page = ChatShellOutputPage.fromReply(const {}); expect(page.output, ''); expect(page.shell, isNull); + expect(page.unavailable, isTrue); + expect( + ChatShellOutputSnapshot(page: page).state, + ChatShellOutputState.unavailable, + ); expect( const ChatShellOutputSnapshot(page: ChatShellOutputPage()).state, ChatShellOutputState.empty,