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,