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 f36fa9fc..e4b5b397 100644 --- a/app/lib/features/chat/conversation/chat_background_task_detail.dart +++ b/app/lib/features/chat/conversation/chat_background_task_detail.dart @@ -16,9 +16,8 @@ import '../../../ui/text/monospace.dart'; 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. +/// Even at a large text scale the selected output stays bounded within the +/// modal's viewport budget; the native dialog scrolls the surrounding details. const _outputMaxBudgetShare = 0.45; /// The selected background task's read-only detail and bounded output page. @@ -39,9 +38,7 @@ class ChatBackgroundTaskDetail extends StatelessWidget { 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. + /// The modal viewport's height budget, used to bound its selectable output. final double heightBudget; final VoidCallback onRefresh; @@ -135,6 +132,7 @@ class ChatBackgroundTaskDetail extends StatelessWidget { ) { final text = SelectableText( output, + semanticsLabel: output, key: const Key('chat-bg-task-output'), style: style, // A multiline selectable body scrolls itself: the host's text control diff --git a/app/lib/features/chat/conversation/chat_background_tasks.dart b/app/lib/features/chat/conversation/chat_background_tasks.dart index 69e6254c..30c0c384 100644 --- a/app/lib/features/chat/conversation/chat_background_tasks.dart +++ b/app/lib/features/chat/conversation/chat_background_tasks.dart @@ -1,34 +1,13 @@ -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'; +import 'chat_background_tasks_controller.dart'; +import 'chat_background_tasks_panel.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. +/// Compact live task count, mounted above Send. Details live only in its modal. class ChatBackgroundTasks extends StatefulWidget { const ChatBackgroundTasks({ super.key, @@ -39,9 +18,6 @@ class ChatBackgroundTasks extends StatefulWidget { 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 @@ -49,432 +25,128 @@ class ChatBackgroundTasks extends StatefulWidget { } 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()); - } + late final controller = ChatBackgroundTasksController( + widget.gateway, + widget.sessionId, + ); + TransitionRoute? _modal; @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()); + _closeModal(); + controller.replace(widget.gateway, widget.sessionId, notify: false); + } else if (oldWidget.syncToken != widget.syncToken) { + controller.reconnect(notify: false); } } - 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(); + void _closeModal() { + final route = _modal; + _modal = null; + if (route == null || !route.isActive) return; + WidgetsBinding.instance.addPostFrameCallback((_) { + if (route.isActive) route.navigator?.removeRoute(route); }); } - 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.', - ), - ); + void _open() { + if (_modal != null) return; + FocusManager.instance.primaryFocus?.unfocus(); + final cupertino = + chatControlsStyleOf(context) == ChatControlsStyle.cupertino; + Widget dialog(BuildContext context) { + final content = ChatBackgroundTasksPanel(controller: controller); + void close() => Navigator.of(context).pop(); + return cupertino + ? CupertinoAlertDialog( + key: const Key('chat-background-tasks-modal'), + title: const Text(backgroundTasksTitle), + content: content, + actions: [ + CupertinoDialogAction( + onPressed: close, + child: const Text('Done'), + ), + ], + ) + : AlertDialog( + key: const Key('chat-background-tasks-modal'), + title: const Text(backgroundTasksTitle), + scrollable: true, + content: content, + actions: [ + TextButton(onPressed: close, child: const Text('Done')), + ], + ); } - } - /// 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; + final TransitionRoute route = cupertino + ? CupertinoDialogRoute( + context: context, + barrierDismissible: true, + builder: dialog, + ) + : DialogRoute(context: context, builder: dialog); + _modal = route; + Navigator.of(context, rootNavigator: true).push(route); + route.completed.then((_) { + if (_modal == route) _modal = 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()); + _closeModal(); + controller.dispose(); 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))), + Widget build(BuildContext context) => ListenableBuilder( + listenable: controller, + builder: (context, _) { + final count = controller.running.length; + final label = controller.error != null + ? 'Tasks' + : controller.loading && count == 0 + ? 'Tasks…' + : '$count ${count == 1 ? 'task' : 'tasks'}'; + final cupertino = + chatControlsStyleOf(context) == ChatControlsStyle.cupertino; + final button = cupertino + ? CupertinoButton( + key: const Key('chat-background-tasks-button'), + sizeStyle: CupertinoButtonSize.small, + padding: EdgeInsets.zero, + onPressed: _open, + child: Text( + label, + style: CupertinoTheme.of(context).textTheme.tabLabelTextStyle + .copyWith(color: CupertinoTheme.of(context).primaryColor), + ), + ) + : TextButton( + key: const Key('chat-background-tasks-button'), + onPressed: _open, + child: Text( + label, + style: Theme.of(context).textTheme.labelSmall?.copyWith( + color: Theme.of(context).colorScheme.primary, ), - ], - ), - ), - ), - ); - } - - /// 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), - ), - ), - ], - ), - ), + button: true, + excludeSemantics: true, + onTap: _open, + label: controller.error != null + ? 'Background tasks unavailable' + : 'Background tasks, $label', + child: button, ); - } - 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), - ), - ), - ); - } + }, + ); } diff --git a/app/lib/features/chat/conversation/chat_background_tasks_controller.dart b/app/lib/features/chat/conversation/chat_background_tasks_controller.dart new file mode 100644 index 00000000..0c0e7c27 --- /dev/null +++ b/app/lib/features/chat/conversation/chat_background_tasks_controller.dart @@ -0,0 +1,173 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; + +import '../../../core/api_gateway.dart'; +import '../../../core/error_reason.dart'; +import '../data/chat_repository.dart'; +import '../domain/chat_shells.dart'; + +/// One session's live background tasks and lazy, bounded output selection. +class ChatBackgroundTasksController extends ChangeNotifier { + ChatBackgroundTasksController(this.gateway, this.sessionId) { + _listen(); + unawaited(refresh()); + } + + ApiGateway gateway; + String sessionId; + late ChatRepository _repository = ChatRepository(gateway); + StreamSubscription? _frames; + List _shells = const []; + Map? _loadFrames; + String? selectedId; + ChatShellOutputSnapshot? output; + String? error; + bool loading = true; + bool _disposed = false; + int _generation = 0; + int _outputGeneration = 0; + + List get running => runningShells(_shells); + JsonMap? get selectedShell => + running.where((shell) => shellIdOf(shell) == selectedId).firstOrNull; + + void replace( + ApiGateway nextGateway, + String nextSessionId, { + bool notify = true, + }) { + if (_disposed) return; + unawaited(_frames?.cancel()); + gateway = nextGateway; + sessionId = nextSessionId; + _repository = ChatRepository(gateway); + _listen(); + reconnect(notify: notify); + } + + void reconnect({bool notify = true}) { + if (_disposed) return; + _shells = const []; + selectedId = null; + output = null; + error = null; + _outputGeneration++; + unawaited(refresh(notify: notify)); + } + + void _listen() => _frames = gateway.frames.listen((envelope) { + if (_disposed || envelope['type'] != 'chat_event') return; + final frame = envelope['chat_event']; + if (frame is! Map || + frame['session_id'] != sessionId || + frame['kind'] != 'shell' || + frame['shell'] is! Map) { + return; + } + _shells = mergeShellFrame( + _shells, + Map.from(frame['shell'] as Map), + ); + final id = shellIdOf(Map.from(frame['shell'] as Map)); + if (_loadFrames != null && !blankShellValue(id)) { + _loadFrames![id] = _shells.firstWhere((shell) => shellIdOf(shell) == id); + if (_loadFrames!.length > observedShellLimit) { + _loadFrames!.remove(_loadFrames!.keys.first); + } + } + _dropStaleSelection(); + notifyListeners(); + }, onError: (_) {}); + + Future refresh({bool notify = true}) async { + if (_disposed) return; + final token = ++_generation; + final observed = {}; + _loadFrames = observed; + loading = true; + if (notify) notifyListeners(); + try { + final shells = await _repository.shells(sessionId); + if (_disposed || token != _generation) return; + _shells = shellsLoaded(_shells, shells); + // Live frames are newer than a snapshot requested before they arrived. + for (final frame in observed.values) { + _shells = mergeShellFrame(_shells, frame); + } + error = null; + _dropStaleSelection(); + } catch (failure) { + if (_disposed || token != _generation) return; + error = describeErrorReason( + failure, + fallback: 'The server did not answer.', + ); + } + loading = false; + _loadFrames = null; + notifyListeners(); + } + + void _dropStaleSelection() { + if (selectedId == null || selectedShell != null) return; + selectedId = null; + output = null; + _outputGeneration++; + } + + void select(String id) { + if (_disposed) return; + if (selectedId == id) { + selectedId = null; + output = null; + _outputGeneration++; + notifyListeners(); + return; + } + if (!running.any((shell) => shellIdOf(shell) == id)) return; + selectedId = id; + unawaited(readOutput()); + } + + Future readOutput() async { + final id = selectedId; + if (_disposed || id == null) return; + final token = ++_outputGeneration; + output = const ChatShellOutputSnapshot(loading: true); + notifyListeners(); + try { + final reply = await _repository.shellOutput( + sessionId, + id, + cursor: 0, + limit: chatShellOutputLimit, + ); + if (_disposed || token != _outputGeneration || selectedId != id) return; + final page = ChatShellOutputPage.fromReply(reply); + if (page.shell case final shell? when !blankShellValue(shell['id'])) { + _shells = mergeShellFrame(_shells, shell); + } + output = ChatShellOutputSnapshot(page: page); + _dropStaleSelection(); + } catch (failure) { + if (_disposed || token != _outputGeneration || selectedId != id) return; + output = ChatShellOutputSnapshot( + error: describeErrorReason( + failure, + fallback: 'The server did not answer.', + ), + ); + } + notifyListeners(); + } + + @override + void dispose() { + _disposed = true; + _generation++; + _outputGeneration++; + unawaited(_frames?.cancel()); + super.dispose(); + } +} diff --git a/app/lib/features/chat/conversation/chat_background_tasks_panel.dart b/app/lib/features/chat/conversation/chat_background_tasks_panel.dart new file mode 100644 index 00000000..9f8cb087 --- /dev/null +++ b/app/lib/features/chat/conversation/chat_background_tasks_panel.dart @@ -0,0 +1,96 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../domain/chat_shells.dart'; +import '../ui/sessions/chat_adaptive.dart'; +import 'chat_background_task_detail.dart'; +import 'chat_background_tasks_controller.dart'; + +/// Scrollable modal content, backed by the same live controller as its badge. +class ChatBackgroundTasksPanel extends StatelessWidget { + const ChatBackgroundTasksPanel({super.key, required this.controller}); + + final ChatBackgroundTasksController controller; + + @override + Widget build(BuildContext context) => ListenableBuilder( + listenable: controller, + builder: (context, _) { + final cupertino = + chatControlsStyleOf(context) == ChatControlsStyle.cupertino; + final running = controller.running; + final shell = controller.selectedShell; + final error = controller.error; + return Column( + key: const Key('chat-background-tasks'), + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + if (controller.loading) + cupertino + ? const CupertinoActivityIndicator() + : const LinearProgressIndicator(), + if (error != null) ...[ + Text( + 'Background tasks unavailable. $error', + key: const Key('chat-background-tasks-error'), + ), + ChatBackgroundTaskButton( + label: 'Retry', + onPressed: controller.refresh, + ), + ] else if (!controller.loading && running.isEmpty) + const Text('No background tasks running.'), + if (running.isNotEmpty) + Text(backgroundTasksRunningLabel(running.length)), + for (final task in running) ...[ + _taskRow(context, task, cupertino), + if (shell != null && shellIdOf(task) == controller.selectedId) + ChatBackgroundTaskDetail( + key: const Key('chat-bg-task-detail'), + shell: shell, + output: controller.output, + heightBudget: MediaQuery.sizeOf(context).height, + onRefresh: controller.readOutput, + ), + ], + ], + ); + }, + ); + + Widget _taskRow( + BuildContext context, + Map shell, + bool cupertino, + ) { + final id = shellIdOf(shell); + final selected = controller.selectedId == id; + final title = Text( + shellCommandSummary(shell['command']), + maxLines: 2, + overflow: TextOverflow.ellipsis, + ); + if (cupertino) { + return Semantics( + selected: selected, + child: CupertinoListTile( + key: ValueKey('chat-bg-task-$id'), + title: title, + subtitle: const Text(shellRowLabel), + backgroundColor: selected + ? CupertinoColors.tertiarySystemFill.resolveFrom(context) + : null, + onTap: () => controller.select(id), + ), + ); + } + return ListTile( + key: ValueKey('chat-bg-task-$id'), + title: title, + subtitle: const Text(shellRowLabel), + selected: selected, + onTap: () => controller.select(id), + ); + } +} diff --git a/app/lib/features/chat/conversation/chat_composer_bar.dart b/app/lib/features/chat/conversation/chat_composer_bar.dart index ef9fd958..41a6264d 100644 --- a/app/lib/features/chat/conversation/chat_composer_bar.dart +++ b/app/lib/features/chat/conversation/chat_composer_bar.dart @@ -72,6 +72,7 @@ class ChatComposerBar extends StatefulWidget { this.picker, this.commands, this.paste, + this.backgroundTasks, }); final ChatComposerController composer; @@ -88,6 +89,7 @@ class ChatComposerBar extends StatefulWidget { /// The host clipboard-file seam; production uses [hostChatClipboardPaste]. final ChatClipboardPaste? paste; + final Widget? backgroundTasks; @override State createState() => _ChatComposerBarState(); @@ -627,11 +629,24 @@ class _ChatComposerBarState extends State { ), ), const SizedBox(width: 8), - if (widget.running) ...[ - _primary(context, cupertino, stop: true), - const SizedBox(width: 4), - ], - _primary(context, cupertino), + Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + if (widget.backgroundTasks != null) + widget.backgroundTasks!, + Row( + mainAxisSize: MainAxisSize.min, + children: [ + if (widget.running) ...[ + _primary(context, cupertino, stop: true), + const SizedBox(width: 4), + ], + _primary(context, cupertino), + ], + ), + ], + ), ], ), ], diff --git a/app/lib/features/chat/conversation/chat_thread_view.dart b/app/lib/features/chat/conversation/chat_thread_view.dart index a76cc5d2..ab71567d 100644 --- a/app/lib/features/chat/conversation/chat_thread_view.dart +++ b/app/lib/features/chat/conversation/chat_thread_view.dart @@ -782,15 +782,6 @@ class _ChatThreadViewState extends State { }, ), ), - // 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: NotificationListener( onNotification: _onScrollMetrics, @@ -910,6 +901,12 @@ class _ChatThreadViewState extends State { running: _controller.running, commands: _commandActions(), picker: widget.attachmentPicker, + backgroundTasks: ChatBackgroundTasks( + key: ValueKey('chat-background-tasks-${widget.sessionId}'), + gateway: widget.gateway, + sessionId: widget.sessionId, + syncToken: widget.syncToken, + ), ), ], ); diff --git a/app/lib/features/chat/domain/chat_shells.dart b/app/lib/features/chat/domain/chat_shells.dart index f0693ec4..4f84b6ab 100644 --- a/app/lib/features/chat/domain/chat_shells.dart +++ b/app/lib/features/chat/domain/chat_shells.dart @@ -13,10 +13,6 @@ const chatShellExited = 'exited'; /// 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; diff --git a/app/notes/chat-background-task-modal.md b/app/notes/chat-background-task-modal.md new file mode 100644 index 00000000..70b709e0 --- /dev/null +++ b/app/notes/chat-background-task-modal.md @@ -0,0 +1,29 @@ +# Background tasks badge and modal + +- Removed the pinned task list from above the transcript. A compact native + `N tasks` button now sits above Send (singular for one task). It remains + discoverable at zero; loading/failed reads never invent a known count. +- Opening it shows a native Material/Cupertino modal with the same live running + task facts and lazy session-scoped, 64 KiB output reads. Selected output appears + under its task. Exits update the count and remove stale selected output. +- The badge and modal share one controller/subscription. A slow snapshot cannot + resurrect an exit or discard a newer live task. Session replacement/disposal + invalidates pending reads and removes only the owned modal, not another route. +- Done, barrier and system Back use normal modal dismissal. Task updates do not + rebuild the transcript; small caption roles preserve composer space at 2x text. +- Refused/unavailable/empty output remains distinguished. Output is selectable, + bounded and explicitly exposed to accessibility. + +## Verification + +- Full `flutter test`: **1,936 passed**; conversation subset: 304 passed; + focused background controller/modal suite: 25 passed. Clean analysis. +- Real browser probes: Material 1280 and Cupertino 390, using loopback fixtures. + Checked button geometry above Send, absence of inline task content, native + modal, no eager output read, exact bounded query, live exits and empty state. + Captures inspected in `build/background-task-modal-{material,cupertino}/`. +- Existing output and narrow/2x text tests now exercise the modal. New tests + cover live count, Done/Back, session switches, stale reads, owner disposal and + preservation of an unrelated top route. +- This item is implemented separately from the newer prompt/row/stage/sizing + follow-ups. No public deployment or device installation of this item yet. diff --git a/app/notes/ui-followups-queue.md b/app/notes/ui-followups-queue.md new file mode 100644 index 00000000..ef1aee86 --- /dev/null +++ b/app/notes/ui-followups-queue.md @@ -0,0 +1,15 @@ +# UI follow-up queue + +| Item | Source | Verification | Landing | Deployment | +| --- | --- | --- | --- | --- | +| Tasks badge above Send + live modal | Manager implementation complete | 1,936 full tests; clean analysis; Material/Cupertino browser pass | Main, manager commit | Not published | +| Body-priority shared split (target ~60% window, minimum 50%) | Manager, next | Pending | Pending | Not published | +| Optional-by-default custom/preset create prompt | Run 187 partial; direct Luna completion in same worktree | Default-off candidate passes; actual chooser/race guard in progress | Candidate only | Not published | +| Structured multiline chat rows | Run 188 + direct Luna candidate | Further style/narrow fixes required; no browser capture | Candidate only | Not published | +| Prominent run-stage detail hierarchy | Run 189 no-op; direct Luna commit ca6a0516 | 13 focused tests; targeted analysis; browser probe needs repair | Candidate only | Not published | + +Prior Enter/shared equal-pane release is separately published as APK +0.1.29882706; see `shared-panes-enter-release.md`. It does not contain these new +follow-ups. Independent workers use separate worktrees; no pipeline definitions +were created or modified. Manager will inspect changes and actual landing, +resolve compatible overlaps, and run an integrated gate before claiming delivery. diff --git a/app/test/features/chat/conversation/chat_background_tasks_controller_test.dart b/app/test/features/chat/conversation/chat_background_tasks_controller_test.dart new file mode 100644 index 00000000..a29cb2ea --- /dev/null +++ b/app/test/features/chat/conversation/chat_background_tasks_controller_test.dart @@ -0,0 +1,100 @@ +import 'dart:async'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_background_tasks_controller.dart'; +import 'package:pipelines_app/features/chat/domain/chat_shells.dart'; + +import 'chat_background_tasks_fixtures.dart'; + +void main() { + test( + 'slow snapshot does not resurrect an exited task or drop a live arrival', + () async { + final gateway = TasksGateway(); + final reply = Completer(); + gateway.shells = (_) => reply.future; + final controller = ChatBackgroundTasksController(gateway, 's'); + addTearDown(controller.dispose); + addTearDown(gateway.close); + gateway.shell('gone', 'exited'); + gateway.shell('new', 'running'); + gateway.shell('unrelated', 'running', session: 'other'); + await pumpEventQueue(); + reply.complete({ + 'chat_shells': [task('gone')], + }); + await pumpEventQueue(); + expect(controller.running.map(shellIdOf), ['new']); + expect(controller.loading, isFalse); + }, + ); + + test('replacing sessions ignores a late previous snapshot', () async { + final gateway = TasksGateway(); + final old = Completer(); + gateway.shells = (fields) => fields['chat_query']['session_id'] == 's' + ? old.future + : Future.value({ + 'chat_shells': [task('current')], + }); + final controller = ChatBackgroundTasksController(gateway, 's'); + addTearDown(controller.dispose); + addTearDown(gateway.close); + controller.replace(gateway, 'new-session'); + await pumpEventQueue(); + old.complete({ + 'chat_shells': [task('old')], + }); + await pumpEventQueue(); + expect(controller.running.map(shellIdOf), ['current']); + }); + + test('an exit invalidates an in-flight output read for that task', () async { + final gateway = TasksGateway() + ..shells = (_) async => { + 'chat_shells': [task('a')], + }; + final page = Completer(); + gateway.output = (_) => page.future; + final controller = ChatBackgroundTasksController(gateway, 's'); + addTearDown(controller.dispose); + addTearDown(gateway.close); + await pumpEventQueue(); + controller.select('a'); + expect(controller.output?.state, ChatShellOutputState.loading); + gateway.shell('a', 'exited'); + await pumpEventQueue(); + page.complete({ + 'chat_shell_output': {'shell': task('a'), 'output': 'late'}, + }); + await pumpEventQueue(); + expect(controller.running, isEmpty); + expect(controller.output, isNull); + expect(controller.selectedShell, isNull); + }); + + test( + 'disposal ignores late reads and never attaches another subscription', + () async { + final gateway = TasksGateway(); + final reply = Completer(); + gateway.shells = (_) => reply.future; + final controller = ChatBackgroundTasksController(gateway, 's'); + var changes = 0; + controller.addListener(() => changes++); + controller.dispose(); + controller.replace(gateway, 'other'); + reply.complete({ + 'chat_shells': [task('late')], + }); + await pumpEventQueue(); + expect(changes, 0); + expect( + gateway.calls.where((call) => call.type == 'chat_shells'), + hasLength(1), + ); + gateway.close(); + }, + ); +} diff --git a/app/test/features/chat/conversation/chat_background_tasks_fixtures.dart b/app/test/features/chat/conversation/chat_background_tasks_fixtures.dart new file mode 100644 index 00000000..852b7745 --- /dev/null +++ b/app/test/features/chat/conversation/chat_background_tasks_fixtures.dart @@ -0,0 +1,36 @@ +import 'package:pipelines_app/core/api_gateway.dart'; + +import 'chat_thread_fixtures.dart'; + +class TasksGateway extends FakeChatGateway { + TasksGateway() { + history = (_) async => chatPage([]); + } + + Future Function(JsonMap)? shells; + Future Function(JsonMap)? output; + + @override + Future call(String type, [JsonMap fields = const {}]) { + if (type == 'chat_shells' || type == 'chat_shell_output') { + calls.add((type: type, fields: fields)); + if (type == 'chat_shells') { + return shells?.call(fields) ?? Future.value({'chat_shells': []}); + } + return output?.call(fields) ?? Future.value({'chat_shell_output': {}}); + } + return super.call(type, fields); + } + + void shell(String id, String status, {String session = 's'}) => emitEvent({ + 'session_id': session, + 'kind': 'shell', + 'shell': {'id': id, 'status': status, 'command': 'command $id'}, + }); +} + +Map task(String id) => { + 'id': id, + 'status': 'running', + 'command': 'command $id', +}; diff --git a/app/test/features/chat/conversation/chat_background_tasks_modal_test.dart b/app/test/features/chat/conversation/chat_background_tasks_modal_test.dart new file mode 100644 index 00000000..18846391 --- /dev/null +++ b/app/test/features/chat/conversation/chat_background_tasks_modal_test.dart @@ -0,0 +1,143 @@ +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/features/chat/conversation/chat_background_tasks.dart'; + +import 'chat_background_tasks_fixtures.dart'; + +Widget host( + TasksGateway gateway, { + bool cupertino = false, + String session = 's', +}) { + final button = ChatBackgroundTasks(gateway: gateway, sessionId: session); + return cupertino + ? CupertinoApp(home: CupertinoPageScaffold(child: button)) + : MaterialApp(home: Scaffold(body: button)); +} + +Future open(WidgetTester tester) async { + await tester.tap(find.byKey(const Key('chat-background-tasks-button'))); + await tester.pumpAndSettle(); +} + +void main() { + for (final cupertino in [false, true]) { + testWidgets( + 'count updates live, no eager output, Back/Done only close modal ($cupertino)', + (tester) async { + final gateway = TasksGateway() + ..shells = (_) async => { + 'chat_shells': [task('a')], + }; + addTearDown(gateway.close); + await tester.pumpWidget(host(gateway, cupertino: cupertino)); + await tester.pumpAndSettle(); + expect(find.text('1 task'), findsOneWidget); + expect(find.text('command a'), findsNothing); + expect( + gateway.calls.where((call) => call.type == 'chat_shell_output'), + isEmpty, + ); + await open(tester); + expect(find.text('command a'), findsOneWidget); + gateway.shell('b', 'running'); + await tester.pumpAndSettle(); + expect(find.text('2 running'), findsOneWidget); + expect(find.text('command b'), findsOneWidget); + await tester.binding.handlePopRoute(); + await tester.pumpAndSettle(); + expect( + find.byKey(const Key('chat-background-tasks-modal')), + findsNothing, + ); + expect(find.text('2 tasks'), findsOneWidget); + await open(tester); + await tester.tap(find.text('Done')); + await tester.pumpAndSettle(); + expect(find.text('2 tasks'), findsOneWidget); + expect( + gateway.calls.where((call) => call.type == 'chat_shells'), + hasLength(1), + ); + }, + ); + + testWidgets( + 'session switch closes its own modal and drops late output ($cupertino)', + (tester) async { + final gateway = TasksGateway() + ..shells = (_) async => { + 'chat_shells': [task('a')], + }; + final page = Completer(); + gateway.output = (_) => page.future; + addTearDown(gateway.close); + await tester.pumpWidget(host(gateway, cupertino: cupertino)); + await tester.pumpAndSettle(); + await open(tester); + await tester.tap(find.byKey(const ValueKey('chat-bg-task-a'))); + await tester.pump(); + gateway.shells = (_) async => {'chat_shells': []}; + await tester.pumpWidget( + host(gateway, cupertino: cupertino, session: 'other'), + ); + await tester.pumpAndSettle(); + page.complete({ + 'chat_shell_output': {'output': 'old session output'}, + }); + await tester.pumpAndSettle(); + expect( + find.byKey(const Key('chat-background-tasks-modal')), + findsNothing, + ); + expect(find.text('0 tasks'), findsOneWidget); + expect(find.text('old session output'), findsNothing); + expect(tester.takeException(), isNull); + }, + ); + } + + testWidgets( + 'owner disposal removes only its modal, not an unrelated top route', + (tester) async { + final gateway = TasksGateway(); + addTearDown(gateway.close); + var visible = true; + late StateSetter rebuild; + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: StatefulBuilder( + builder: (context, setState) { + rebuild = setState; + return visible + ? ChatBackgroundTasks(gateway: gateway, sessionId: 's') + : const SizedBox.shrink(); + }, + ), + ), + ), + ); + await tester.pumpAndSettle(); + await open(tester); + final navigator = tester.state(find.byType(Navigator)); + showDialog( + context: navigator.overlay!.context, + builder: (_) => const AlertDialog(title: Text('Unrelated dialog')), + ); + await tester.pumpAndSettle(); + rebuild(() => visible = false); + await tester.pumpAndSettle(); + expect(find.text('Unrelated dialog'), findsOneWidget); + expect( + find.byKey(const Key('chat-background-tasks-modal')), + findsNothing, + ); + expect(tester.takeException(), isNull); + }, + ); +} 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 b0df80ff..1675e90f 100644 --- a/app/test/features/chat/conversation/chat_background_tasks_test.dart +++ b/app/test/features/chat/conversation/chat_background_tasks_test.dart @@ -110,7 +110,18 @@ Widget _thread(_TasksGateway gateway) => MaterialApp( ); Future _tapTask(WidgetTester tester, String id) async { - await tester.tap(find.byKey(ValueKey('chat-bg-task-$id'))); + if (find.byKey(const Key('chat-background-tasks-modal')).evaluate().isEmpty) { + await _openTasks(tester); + } + final row = find.byKey(ValueKey('chat-bg-task-$id')); + await tester.ensureVisible(row); + await tester.pumpAndSettle(); + await tester.tap(row); + await tester.pumpAndSettle(); +} + +Future _openTasks(WidgetTester tester) async { + await tester.tap(find.byKey(const Key('chat-background-tasks-button'))); await tester.pumpAndSettle(); } @@ -129,6 +140,9 @@ void main() { await tester.pumpWidget(_host(gateway)); await tester.pumpAndSettle(); + expect(find.text('1 task'), findsOneWidget); + expect(find.text('go test ./...'), findsNothing); + await _openTasks(tester); expect(find.text('Background tasks'), findsOneWidget); expect(find.text('1 running'), findsOneWidget); expect(find.text('Running'), findsOneWidget); @@ -142,16 +156,20 @@ void main() { ]); }); - testWidgets('an honest empty snapshot draws no task surface', (tester) async { + testWidgets('an empty snapshot shows zero tasks and an honest empty modal', ( + 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('0 tasks'), findsOneWidget); expect(find.text('Background tasks'), findsNothing); expect(gateway.fieldsFor('chat_shells'), hasLength(1)); + await _openTasks(tester); + expect(find.text('No background tasks running.'), findsOneWidget); }); testWidgets('pushed shell frames add and remove this session tasks', ( @@ -166,20 +184,22 @@ void main() { gateway.emitShell('sh1', 'running', command: 'tail -f server.log'); await tester.pumpAndSettle(); + expect(find.text('1 task'), findsOneWidget); + await _openTasks(tester); 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); + expect(find.text('No background tasks running.'), findsOneWidget); gateway.emitShell('other', 'running', session: 'other-session'); await tester.pumpAndSettle(); - expect(find.text('Background tasks'), findsNothing); + expect(find.text('No background tasks running.'), findsOneWidget); }); - testWidgets('more than three running tasks scroll inside the bar', ( + testWidgets('more than three tasks are contained in a scrollable modal', ( tester, ) async { final gateway = _TasksGateway() @@ -190,13 +210,11 @@ void main() { await tester.pumpWidget(_host(gateway)); await tester.pumpAndSettle(); + await _openTasks(tester); expect(find.text('4 running'), findsOneWidget); - expect(find.byKey(const Key('chat-bg-task-list')), findsOneWidget); - expect( - tester.getRect(find.byKey(const Key('chat-bg-task-list'))).height, - lessThanOrEqualTo(kMinInteractiveDimension * backgroundTaskVisibleRows), - ); + expect(find.byType(AlertDialog), findsOneWidget); + expect(find.byType(SingleChildScrollView), findsWidgets); for (var index = 0; index < 4; index++) { expect( find.byKey(ValueKey('chat-bg-task-sh$index')), @@ -315,6 +333,8 @@ void main() { await tester.pumpWidget(_host(gateway)); await tester.pumpAndSettle(); + expect(find.text('0 tasks'), findsNothing); + await _openTasks(tester); expect( find.textContaining('Background tasks unavailable. server down'), @@ -332,7 +352,9 @@ void main() { expect(gateway.fieldsFor('chat_shells'), hasLength(2)); }); - testWidgets('an exit closes the selected pane and the bar', (tester) async { + testWidgets('an exit clears selected output while the modal stays open', ( + tester, + ) async { final gateway = _TasksGateway(); gateway.shells = () async => _snapshot([_running('sh1')]); gateway.output = (_) async => { @@ -352,7 +374,7 @@ void main() { await tester.pumpAndSettle(); expect(find.byKey(const Key('chat-bg-task-detail')), findsNothing); - expect(find.text('Background tasks'), findsNothing); + expect(find.text('No background tasks running.'), findsOneWidget); }); testWidgets('a replaced socket drops held tasks and re-learns the snapshot', ( @@ -364,13 +386,14 @@ void main() { await tester.pumpWidget(_host(gateway)); await tester.pumpAndSettle(); + await _openTasks(tester); 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(find.text('No background tasks running.'), findsOneWidget); expect(gateway.fieldsFor('chat_shells'), hasLength(2)); }); @@ -389,6 +412,7 @@ void main() { await tester.pumpWidget(_host(gateway, cupertino: true)); await tester.pumpAndSettle(); + await _openTasks(tester); expect(find.byType(CupertinoButton), findsWidgets); expect(find.text('1 running'), findsOneWidget); @@ -425,20 +449,20 @@ void main() { await tester.pumpWidget(_thread(gateway)); await tester.pumpAndSettle(); + final before = tester.getRect( + find.byKey(const ValueKey('chat-composer-s')), + ); 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. + // Output stays bounded and scrollable inside the modal. 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')), + final modal = tester.getRect( + find.byKey(const Key('chat-background-tasks-modal')), ); - expect(detail.bottom, lessThanOrEqualTo(composer.top)); - expect(composer.bottom, lessThanOrEqualTo(700)); + expect(output.height, lessThanOrEqualTo(modal.height)); + expect(modal.bottom, lessThanOrEqualTo(700)); // The page scrolls through the host's own text control to its last line. expect( @@ -452,6 +476,12 @@ void main() { await tester.drag(outputFinder, const Offset(0, -300)); await tester.pumpAndSettle(); expect(scrollable.position.pixels, greaterThan(0)); + await tester.tap(find.text('Done')); + await tester.pumpAndSettle(); + expect( + tester.getRect(find.byKey(const ValueKey('chat-composer-s'))), + before, + ); }); testWidgets('three tasks and an open page fit a 320px phone', (tester) async { @@ -473,28 +503,23 @@ void main() { await tester.pumpWidget(_thread(gateway)); await tester.pumpAndSettle(); + final before = tester.getRect( + find.byKey(const ValueKey('chat-composer-s')), + ); 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. + // Native dialog scrolling contains the task list and its selected output. 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')), + final modal = tester.getRect( + find.byKey(const Key('chat-background-tasks-modal')), ); + expect(modal.height, lessThanOrEqualTo(568)); + expect(modal.width, lessThanOrEqualTo(320)); + await tester.tap(find.text('Done')); + await tester.pumpAndSettle(); 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, + tester.getRect(find.byKey(const ValueKey('chat-composer-s'))), + before, ); }); @@ -523,14 +548,17 @@ void main() { 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. + // Task details stay in the modal at large text scale, not in the chat body. expect(tester.takeException(), isNull); - final bar = tester.getRect(find.byKey(const Key('chat-background-tasks'))); + final modal = tester.getRect( + find.byKey(const Key('chat-background-tasks-modal')), + ); + expect(modal.bottom, lessThanOrEqualTo(568)); + await tester.tap(find.text('Done')); + await tester.pumpAndSettle(); final composer = tester.getRect( find.byKey(const ValueKey('chat-composer-s')), ); - expect(bar.bottom, lessThanOrEqualTo(composer.top)); expect(composer.bottom, lessThanOrEqualTo(568)); }); @@ -562,10 +590,10 @@ void main() { await _tapTask(tester, 'sh1'); expect(tester.takeException(), isNull); - expect(find.text('Details'), findsOneWidget); + expect(find.text('Task identity'), findsOneWidget); }); - testWidgets('the conversation mounts the session task surface', ( + testWidgets('the conversation mounts only the live task badge', ( tester, ) async { final gateway = _TasksGateway() @@ -575,12 +603,18 @@ void main() { 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); + expect( + find.byKey(const Key('chat-background-tasks-button')), + findsOneWidget, + ); + expect(find.text('1 task'), findsOneWidget); + expect(find.byKey(const Key('chat-background-tasks')), findsNothing); + expect(find.text('go test ./...'), findsNothing); }); - testWidgets('the conversation bar leads, above the task bar', (tester) async { + testWidgets('the task badge sits above Send, outside the transcript', ( + tester, + ) async { final gateway = _TasksGateway(); gateway.shells = () async => _snapshot([_running('sh1')]); addTearDown(gateway.close); @@ -588,16 +622,19 @@ void main() { await tester.pumpWidget(_thread(gateway)); await tester.pumpAndSettle(); - final header = tester.getRect(find.byKey(const Key('chat-thread-header'))); final tasks = tester.getRect( - find.byKey(const Key('chat-background-tasks')), + find.byKey(const Key('chat-background-tasks-button')), ); final list = tester.getRect( find.byKey(const ValueKey('chat-thread-s')), ); - expect(header.top, 0); - expect(tasks.top, greaterThanOrEqualTo(header.bottom)); - // The bar sits outside the transcript's scroller, as the web's chat-bar. - expect(list.top, greaterThanOrEqualTo(tasks.bottom)); + final send = tester.getRect(find.byKey(const Key('chat-composer-primary'))); + final composer = tester.getRect( + find.byKey(const ValueKey('chat-composer-s')), + ); + expect(tasks.bottom, lessThanOrEqualTo(send.top)); + expect(send.center.dx, inInclusiveRange(tasks.left, tasks.right)); + expect(tasks.top, greaterThanOrEqualTo(composer.top)); + expect(list.bottom, lessThanOrEqualTo(composer.top)); }); } diff --git a/app/tool/chat_background_tasks_modal_probe.mjs b/app/tool/chat_background_tasks_modal_probe.mjs new file mode 100644 index 00000000..a29c6e9d --- /dev/null +++ b/app/tool/chat_background_tasks_modal_probe.mjs @@ -0,0 +1,77 @@ +// Real composer badge/modal interaction, using recorded loopback task fixtures. +import assert from 'node:assert/strict'; +import { mkdir, mkdtemp, writeFile } from 'node:fs/promises'; +import { once } from 'node:events'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; +import { startFixture } from './runs_probe_server.mjs'; +import { launchChrome, waitForPort, waitForPage, connect, sleep } from './pipelines_probe_cdp_lib.mjs'; +import { axNodes, enableSemantics, waitFor, capture, click } from './pipelines_probe_cdp_input.mjs'; + +const platform = process.env.PROBE_PLATFORM ?? 'material'; +const width = Number(process.env.PROBE_WIDTH ?? 1280); +const output = resolve(process.argv[3] ?? `build/background-task-modal-${platform}`); +await mkdir(output, { recursive: true }); +const fixture = await startFixture({ root:resolve(process.argv[2]), chatMessages: [], chatShells: [ + { id:'a', status:'running', command:'tail -f fixture.log' }, + { id:'b', status:'running', command:'fixture build' }, + { id:'finished', status:'exited', command:'old finished command' }, +], chatShellOutput: Array.from({length:200},(_,i)=>`Recorded output line ${i}`).join('\n') }); +const profile = await mkdtemp(join(tmpdir(),'background-task-modal-')); +const chrome = launchChrome('/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',profile,'about:blank'); +const log = {platform,width,checks:[],captures:[]}; +let c; +const names = async () => (await axNodes(c)).flatMap(n=>[n.name?.value??'',n.value?.value??'']); +const node = async name => (await axNodes(c)).find(n=>n.name?.value===name&&n.backendDOMNodeId); +const emit = body => fetch(fixture.url+'/fixture/chat-event',{method:'POST',body:JSON.stringify(body)}); +try { + c = await connect((await waitForPage(await waitForPort(join(profile,'DevToolsActivePort')))).webSocketDebuggerUrl); + await c.send('Page.enable'); + if(platform==='material') await c.send('Emulation.setUserAgentOverride',{ + userAgent:'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/155.0.0.0 Safari/537.36',platform:'Win32', + }); + await c.send('Emulation.setDeviceMetricsOverride',{width,height:844,deviceScaleFactor:1,mobile:false}); + await c.send('Page.navigate',{url:fixture.url+'/chat/ses_probechat'}); + assert.ok(await waitFor(()=>c.evaluate("Boolean(document.querySelector('flt-semantics-placeholder'))"),30000)); + await enableSemantics(c); + const badge=await waitFor(()=>node('Background tasks, 2 tasks'),15000); + assert.ok(badge,'live count badge'); + const send=await node('Send');assert.ok(send,'Send control'); + const {model:b}=await c.send('DOM.getBoxModel',{backendNodeId:badge.backendDOMNodeId}); + const {model:s}=await c.send('DOM.getBoxModel',{backendNodeId:send.backendDOMNodeId}); + assert.ok(b.content[5]<=s.content[1]+1,'task badge above Send'); + assert.ok(!(await names()).some(name=>name.includes('tail -f fixture.log')),'no tasks in the transcript'); + await capture(c,output,log,'01-badge-above-send'); + log.checks.push('running count above Send; task list absent from chat body'); + await click(c,'Background tasks, 2 tasks'); + assert.ok(await waitFor(async()=>(await names()).some(name=>name.includes('tail -f fixture.log')),10000)); + assert.ok(!(await names()).some(name=>name.includes('old finished command'))); + let state=await (await fetch(fixture.url+'/fixture/state')).json(); + assert.equal(state.shellOutputRequests.length,0,'no eager output read'); + await click(c,'tail -f fixture.log'); + assert.ok(await waitFor(async()=>(await names()).some(name=>name.includes('Recorded output line 0')),10000)); + state=await (await fetch(fixture.url+'/fixture/state')).json(); + assert.deepEqual(state.shellOutputRequests[0],{session_id:'ses_probechat',shell_id:'a',cursor:0,limit:65536}); + await capture(c,output,log,'02-task-output-in-modal'); + log.checks.push('native modal exposes tasks and lazy bounded output'); + await emit({kind:'shell',shell:{id:'a',status:'exited'}}); + assert.ok(await waitFor(async()=>(await names()).includes('1 running'),10000)); + assert.ok(!(await names()).some(name=>name.includes('Recorded output line 0')),'exited task output removed'); + await capture(c,output,log,'03-live-task-exit'); + await click(c,'Done'); + assert.ok(await waitFor(()=>node('Background tasks, 1 task'),10000)); + await emit({kind:'shell',shell:{id:'b',status:'exited'}}); + assert.ok(await waitFor(()=>node('Background tasks, 0 tasks'),10000)); + await click(c,'Background tasks, 0 tasks'); + assert.ok(await waitFor(async()=>(await names()).includes('No background tasks running.'),10000)); + await capture(c,output,log,'04-empty-modal'); + await click(c,'Done'); + log.checks.push('modal updates live on exits; dismissal restores chat; zero count opens honest empty state'); + console.log(JSON.stringify(log,null,2)); +} catch(error) { + if(c) {await capture(c,output,log,'failure');await writeFile(join(output,'failure-ax.json'),JSON.stringify(await axNodes(c),null,2));} + throw error; +} finally { + await writeFile(join(output,'result.json'),JSON.stringify(log,null,2)); + c?.close();const exited=once(chrome,'exit');chrome.kill();await exited;await fixture.close(); +} diff --git a/app/tool/runs_probe_server.mjs b/app/tool/runs_probe_server.mjs index f1c47b3c..bfba89c0 100644 --- a/app/tool/runs_probe_server.mjs +++ b/app/tool/runs_probe_server.mjs @@ -310,7 +310,7 @@ async function staticFile(base, pathname, req, res) { * It serves the built probe bundle and upgrades /connect on the same origin, so * the normal web composition infers this server from Uri.base. */ -export async function startFixture({ root, runs = RUNS, runDetail, files = {}, chatMessages, chatSessions, chatHistoryDelayMs = 0, onChatHistory }) { +export async function startFixture({ root, runs = RUNS, runDetail, files = {}, chatMessages, chatSessions, chatShells = [], chatShellOutput = '', chatHistoryDelayMs = 0, onChatHistory }) { const base = await realpath(root); const connections = new Set(); const sockets = new Set(); @@ -327,6 +327,7 @@ export async function startFixture({ root, runs = RUNS, runDetail, files = {}, c let chatSubscribed = 0; let chatHistory = 0; const chatPrompts = []; + const shellOutputRequests = []; const fileReads = []; let chatRunning = false; let chatInterrupts = 0; @@ -367,6 +368,9 @@ export async function startFixture({ root, runs = RUNS, runDetail, files = {}, c for await (const chunk of req) chunks.push(chunk); const event = JSON.parse(Buffer.concat(chunks).toString('utf8')); if (event.kind === 'step') chatRunning = event.step?.status !== 'ended'; + if (event.kind === 'shell' && event.shell?.id) { + chatShells = [...chatShells.filter(shell => shell.id !== event.shell.id), event.shell]; + } broadcast({ type: 'chat_event', chat_event: { session_id: CHAT_SESSION.id, ...event, } }); @@ -417,6 +421,7 @@ export async function startFixture({ root, runs = RUNS, runDetail, files = {}, c chatSubscribed, chatHistory, chatPrompts, + shellOutputRequests, chatRunning, chatInterrupts, fileReads, @@ -580,7 +585,15 @@ export async function startFixture({ root, runs = RUNS, runDetail, files = {}, c return; } if (request.type === 'chat_shells') { - client.send({ id: request.id, type: 'chat_shells', chat_shells: [] }); + client.send({ id: request.id, type: 'chat_shells', chat_shells: chatShells }); + return; + } + if (request.type === 'chat_shell_output') { + const query = request.chat_shell_output_query ?? {}; + shellOutputRequests.push(query); + const shell = chatShells.find(shell => shell.id === query.shell_id); + client.send({ id: request.id, type: 'chat_shell_output', chat_shell_output: + shell ? { shell, output: chatShellOutput } : { unavailable: true } }); return; } if (request.type === 'chat_interrupt') {