diff --git a/app/lib/features/chat/conversation/chat_background_task_card.dart b/app/lib/features/chat/conversation/chat_background_task_card.dart new file mode 100644 index 00000000..098c18c5 --- /dev/null +++ b/app/lib/features/chat/conversation/chat_background_task_card.dart @@ -0,0 +1,226 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../core/api_gateway.dart'; +import '../domain/chat_shells.dart'; +import '../domain/chat_task_metadata.dart'; +import 'chat_task_metadata_view.dart'; +import 'chat_task_presentation.dart'; + +/// One scan-friendly task card; only the explicit Details control loads output. +class ChatBackgroundTaskCard extends StatelessWidget { + const ChatBackgroundTaskCard({ + super.key, + required this.shell, + required this.now, + required this.selected, + required this.onDetails, + this.detail, + }); + final JsonMap shell; + final DateTime now; + final bool selected; + final VoidCallback onDetails; + final Widget? detail; + + @override + Widget build(BuildContext context) { + final cupertino = taskCupertino(context); + final kind = taskKindLabel(shell); + final agent = '${shell['task_type'] ?? ''}'.contains('agent'); + final progress = distinctTaskProgress(shell); + final elapsed = taskElapsed(shell, now); + final accent = cupertino + ? CupertinoTheme.of(context).primaryColor + : Theme.of(context).colorScheme.primary; + final status = DecoratedBox( + decoration: BoxDecoration( + color: cupertino + ? CupertinoColors.tertiarySystemFill.resolveFrom(context) + : Theme.of(context).colorScheme.secondaryContainer, + borderRadius: BorderRadius.circular(8), + ), + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + cupertino ? CupertinoIcons.play_fill : Icons.play_arrow_rounded, + size: 14, + color: accent, + ), + const SizedBox(width: 4), + Flexible( + child: Text( + 'Running', + style: cupertino + ? CupertinoTheme.of(context).textTheme.tabLabelTextStyle + : Theme.of(context).textTheme.labelMedium, + ), + ), + ], + ), + ), + ); + final details = Row( + mainAxisSize: MainAxisSize.min, + children: [ + Flexible(child: Text(selected ? 'Hide details' : 'Details')), + const SizedBox(width: 4), + Icon( + cupertino + ? (selected + ? CupertinoIcons.chevron_up + : CupertinoIcons.chevron_down) + : (selected ? Icons.expand_less : Icons.expand_more), + size: 18, + ), + ], + ); + return ChatTaskSurface( + key: ValueKey('chat-bg-task-card-${shellIdOf(shell)}'), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + CircleAvatar( + backgroundColor: cupertino + ? CupertinoColors.tertiarySystemFill.resolveFrom(context) + : Theme.of(context).colorScheme.primaryContainer, + child: Icon( + agent + ? (cupertino + ? CupertinoIcons.person_2 + : Icons.smart_toy_outlined) + : (cupertino + ? CupertinoIcons.chevron_left_slash_chevron_right + : Icons.terminal), + color: accent, + ), + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (kind != null) + Text( + kind, + style: TextStyle( + color: taskSecondary(context), + fontSize: 12, + ), + ), + Text( + taskDisplayTitle(shell), + style: taskHeading(context), + maxLines: selected ? null : 2, + overflow: selected + ? TextOverflow.clip + : TextOverflow.ellipsis, + ), + ], + ), + ), + ], + ), + const SizedBox(height: 16), + Wrap( + alignment: WrapAlignment.spaceBetween, + crossAxisAlignment: WrapCrossAlignment.center, + spacing: 16, + runSpacing: 8, + children: [ + status, + if (elapsed != null) + Semantics( + label: 'Elapsed ${taskDuration(elapsed)}', + child: Text( + taskDuration(elapsed), + style: (cupertino + ? CupertinoTheme.of(context) + .textTheme + .navLargeTitleTextStyle + .copyWith(fontSize: 24) + : Theme.of(context).textTheme.headlineSmall), + ), + ), + ], + ), + const SizedBox(height: 20), + ChatTaskMetadataView(shell: shell, now: now), + if (progress != null) ...[ + const SizedBox(height: 16), + DecoratedBox( + decoration: BoxDecoration( + color: cupertino + ? CupertinoColors.tertiarySystemGroupedBackground + .resolveFrom(context) + : Theme.of(context).colorScheme.surfaceContainerLowest, + borderRadius: BorderRadius.circular(8), + ), + child: Padding( + padding: const EdgeInsets.all(12), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Icon( + cupertino + ? CupertinoIcons.text_bubble + : Icons.notes_rounded, + size: 18, + color: taskSecondary(context), + ), + const SizedBox(width: 8), + Expanded( + child: Text( + progress, + maxLines: selected ? null : 2, + overflow: selected + ? TextOverflow.clip + : TextOverflow.ellipsis, + ), + ), + ], + ), + ), + ), + ], + Align( + alignment: AlignmentDirectional.centerEnd, + child: Semantics( + expanded: selected, + child: cupertino + ? CupertinoButton( + key: ValueKey('chat-bg-task-${shellIdOf(shell)}'), + sizeStyle: CupertinoButtonSize.small, + onPressed: onDetails, + child: details, + ) + : TextButton( + key: ValueKey('chat-bg-task-${shellIdOf(shell)}'), + onPressed: onDetails, + child: details, + ), + ), + ), + if (detail != null) ...[ + if (cupertino) + Container( + height: 0.5, + color: CupertinoColors.separator.resolveFrom(context), + ) + else + const Divider(), + const SizedBox(height: 12), + detail!, + ], + ], + ), + ); + } +} 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 0e035ff6..4417cb74 100644 --- a/app/lib/features/chat/conversation/chat_background_task_detail.dart +++ b/app/lib/features/chat/conversation/chat_background_task_detail.dart @@ -1,32 +1,15 @@ -import '../../../ui/theme/app_theme.dart'; -import 'dart:math' as math; - import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import '../../../core/api_gateway.dart'; import '../domain/chat_shells.dart'; +import '../domain/chat_task_metadata.dart'; +import 'chat_background_task_output.dart'; import 'chat_task_metadata_view.dart'; -import '../ui/sessions/chat_adaptive.dart'; -import '../../../ui/text/monospace.dart'; +import 'chat_task_presentation.dart'; +export 'chat_background_task_output.dart' show ChatBackgroundTaskButton; -/// 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 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. -/// -/// 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. +/// Expanded facts add information instead of repeating the card's title/status. class ChatBackgroundTaskDetail extends StatelessWidget { const ChatBackgroundTaskDetail({ super.key, @@ -36,221 +19,51 @@ class ChatBackgroundTaskDetail extends StatelessWidget { required this.heightBudget, required this.onRefresh, }); - final JsonMap shell; final DateTime now; final ChatShellOutputSnapshot? output; - - /// The modal viewport's height budget, used to bound its selectable output. final double heightBudget; - 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: appMonospaceFamily), - ), - Text(shellStatusRunningLabel), - ChatTaskMetadataView(shell: shell, now: now, detail: true), - _outputArea(context, cupertino), - ], - ), - ); - if (cupertino) { - return CupertinoListSection.insetGrouped( - backgroundColor: AppColors.groupedBackground, - 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); - } - - /// 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: appMonospaceFamily, - 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 - /// own pattern). - Widget _selectableOutput( - BuildContext context, - bool cupertino, - String output, - TextStyle style, - int maxLines, - ) { - 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 - // 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( - locale: Localizations.maybeLocaleOf(context) ?? const Locale('en'), - delegates: const [ - DefaultWidgetsLocalizations.delegate, - DefaultMaterialLocalizations.delegate, - DefaultCupertinoLocalizations.delegate, + final cupertino = taskCupertino(context); + final command = taskText(shell, 'command'); + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + mainAxisSize: MainAxisSize.min, + children: [ + Wrap( + spacing: 24, + runSpacing: 16, + children: [ + ChatTaskFact( + icon: cupertino ? CupertinoIcons.number : Icons.tag, + label: shellOutputTaskIdentityLabel, + value: shellIdOf(shell), + monospace: true, + ), + if (command != null && + !sameTaskText(command, taskDisplayTitle(shell))) + ChatTaskFact( + icon: cupertino + ? CupertinoIcons.chevron_left_slash_chevron_right + : Icons.terminal, + label: shellOutputCommandLabel, + value: command, + monospace: true, + ), + ], + ), + const SizedBox(height: 16), + ChatTaskMetadataView(shell: shell, now: now, detail: true), + const SizedBox(height: 20), + ChatBackgroundTaskOutput( + output: output, + heightBudget: heightBudget, + onRefresh: onRefresh, + ), ], - 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!; - final style = _outputStyle(context, cupertino); - return Column( - crossAxisAlignment: CrossAxisAlignment.start, - spacing: 4, - children: [ - _label(context, cupertino, shellOutputLabel), - _selectableOutput( - context, - cupertino, - page.output, - style, - _outputVisibleLineCount(context, style), - ), - 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_task_output.dart b/app/lib/features/chat/conversation/chat_background_task_output.dart new file mode 100644 index 00000000..36d1ce7c --- /dev/null +++ b/app/lib/features/chat/conversation/chat_background_task_output.dart @@ -0,0 +1,227 @@ +import 'dart:math' as math; +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import '../../../ui/text/monospace.dart'; +import '../domain/chat_shells.dart'; +import 'chat_task_presentation.dart'; + +const _outputVisibleLines = 12; +const _outputLineHeight = 1.5; +const _outputMaxBudgetShare = 0.45; + +/// The selected task's existing lazy output page on a separate reading surface. +class ChatBackgroundTaskOutput extends StatelessWidget { + const ChatBackgroundTaskOutput({ + super.key, + required this.output, + required this.heightBudget, + required this.onRefresh, + }); + final ChatShellOutputSnapshot? output; + final double heightBudget; + final VoidCallback onRefresh; + + @override + Widget build(BuildContext context) { + final cupertino = taskCupertino(context); + final state = output?.state ?? ChatShellOutputState.none; + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Wrap( + alignment: WrapAlignment.spaceBetween, + crossAxisAlignment: WrapCrossAlignment.center, + spacing: 12, + runSpacing: 8, + children: [ + Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + cupertino + ? CupertinoIcons.chevron_left_slash_chevron_right + : Icons.terminal, + size: 18, + color: taskSecondary(context), + ), + const SizedBox(width: 8), + Flexible( + child: Text(shellOutputLabel, style: taskHeading(context)), + ), + ], + ), + if (state != ChatShellOutputState.loading && + state != ChatShellOutputState.error) + ChatBackgroundTaskButton( + label: shellOutputRefreshLabel, + onPressed: onRefresh, + ), + ], + ), + const SizedBox(height: 8), + DecoratedBox( + decoration: BoxDecoration( + color: cupertino + ? CupertinoColors.tertiarySystemGroupedBackground.resolveFrom( + context, + ) + : Theme.of(context).colorScheme.surfaceContainerLowest, + borderRadius: BorderRadius.circular(8), + ), + child: Padding( + padding: const EdgeInsets.all(12), + child: _outputArea(context, cupertino), + ), + ), + ], + ); + } + + /// 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: appMonospaceFamily, + 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(); + final lines = output?.page?.output.split('\n').length ?? 2; + return math.max(2, math.min(lines, 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 + /// own pattern). + Widget _selectableOutput( + BuildContext context, + bool cupertino, + String output, + TextStyle style, + int maxLines, + ) { + 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 + // 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( + 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!; + final style = _outputStyle(context, cupertino); + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + spacing: 4, + children: [ + _selectableOutput( + context, + cupertino, + page.output, + style, + _outputVisibleLineCount(context, style), + ), + if (page.truncated) Text(shellOutputBoundedNote, style: noteStyle), + ], + ); + } + } +} + +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 (taskCupertino(context)) { + 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 index b3f5fd28..28ac103c 100644 --- a/app/lib/features/chat/conversation/chat_background_tasks.dart +++ b/app/lib/features/chat/conversation/chat_background_tasks.dart @@ -2,10 +2,9 @@ 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'; import 'chat_background_tasks_controller.dart'; -import 'chat_background_tasks_panel.dart'; +import 'chat_background_tasks_dialog.dart'; /// Compact live task count: a quiet control inside the composer beside Send, /// shown only while tasks run. Details live only in its modal. @@ -58,35 +57,14 @@ class _ChatBackgroundTasksState extends State { 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')), - ], - ); - } + Widget dialog(BuildContext context) => ChatBackgroundTasksDialog( + key: const Key('chat-background-tasks-modal'), + controller: controller, + onClose: () => Navigator.of(context, rootNavigator: true).pop(), + ); final TransitionRoute route = cupertino - ? CupertinoDialogRoute( - context: context, + ? CupertinoModalPopupRoute( barrierDismissible: true, builder: dialog, ) diff --git a/app/lib/features/chat/conversation/chat_background_tasks_dialog.dart b/app/lib/features/chat/conversation/chat_background_tasks_dialog.dart new file mode 100644 index 00000000..3aeb0776 --- /dev/null +++ b/app/lib/features/chat/conversation/chat_background_tasks_dialog.dart @@ -0,0 +1,94 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../domain/chat_shells.dart'; +import 'chat_background_tasks_controller.dart'; +import 'chat_background_tasks_panel.dart'; +import 'chat_task_presentation.dart'; + +/// A task inspector needs a reading surface, rather than alert-sized content. +class ChatBackgroundTasksDialog extends StatelessWidget { + const ChatBackgroundTasksDialog({ + super.key, + required this.controller, + required this.onClose, + }); + final ChatBackgroundTasksController controller; + final VoidCallback onClose; + + @override + Widget build(BuildContext context) { + final cupertino = taskCupertino(context); + final panel = Padding( + padding: const EdgeInsets.all(20), + child: ChatBackgroundTasksPanel(controller: controller), + ); + if (cupertino) { + return Align( + alignment: Alignment.bottomCenter, + child: FractionallySizedBox( + heightFactor: 0.88, + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 840), + child: CupertinoPageScaffold( + backgroundColor: CupertinoColors.systemGroupedBackground + .resolveFrom(context), + navigationBar: CupertinoNavigationBar( + automaticallyImplyLeading: false, + leading: const Icon(CupertinoIcons.square_stack_3d_up), + middle: const Text(backgroundTasksTitle), + trailing: CupertinoButton( + padding: EdgeInsets.zero, + onPressed: onClose, + child: const Text('Done'), + ), + ), + child: SafeArea(child: SingleChildScrollView(child: panel)), + ), + ), + ), + ); + } + return Dialog( + constraints: const BoxConstraints(maxWidth: 840), + insetPadding: const EdgeInsets.symmetric(horizontal: 24, vertical: 24), + child: ConstrainedBox( + constraints: BoxConstraints( + maxHeight: MediaQuery.sizeOf(context).height * 0.88, + ), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Padding( + padding: const EdgeInsetsDirectional.fromSTEB(24, 20, 12, 0), + child: Wrap( + alignment: WrapAlignment.spaceBetween, + crossAxisAlignment: WrapCrossAlignment.center, + spacing: 12, + runSpacing: 8, + children: [ + Row( + mainAxisSize: MainAxisSize.min, + children: [ + const Icon(Icons.layers_outlined), + const SizedBox(width: 12), + Flexible( + child: Text( + backgroundTasksTitle, + style: Theme.of(context).textTheme.titleLarge, + ), + ), + ], + ), + TextButton(onPressed: onClose, child: const Text('Done')), + ], + ), + ), + Flexible(child: SingleChildScrollView(child: panel)), + ], + ), + ), + ); + } +} diff --git a/app/lib/features/chat/conversation/chat_background_tasks_panel.dart b/app/lib/features/chat/conversation/chat_background_tasks_panel.dart index d59d322a..bd468fb2 100644 --- a/app/lib/features/chat/conversation/chat_background_tasks_panel.dart +++ b/app/lib/features/chat/conversation/chat_background_tasks_panel.dart @@ -3,11 +3,10 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import '../domain/chat_shells.dart'; -import '../domain/chat_task_metadata.dart'; import '../ui/sessions/chat_adaptive.dart'; +import 'chat_background_task_card.dart'; import 'chat_background_task_detail.dart'; import 'chat_background_tasks_controller.dart'; -import 'chat_task_metadata_view.dart'; /// Scrollable modal content, backed by the same live controller as its badge. class ChatBackgroundTasksPanel extends StatefulWidget { @@ -76,56 +75,29 @@ class _ChatBackgroundTasksPanelState extends State { const Text('No background tasks running.'), if (running.isNotEmpty) Text(backgroundTasksRunningLabel(running.length)), - for (final task in running) ...[ - _taskRow(context, task, cupertino, at), - if (shell != null && shellIdOf(task) == controller.selectedId) - ChatBackgroundTaskDetail( - key: const Key('chat-bg-task-detail'), - shell: shell, + for (final task in running) + Padding( + padding: const EdgeInsets.only(top: 12), + child: ChatBackgroundTaskCard( + shell: task, now: at, - output: controller.output, - heightBudget: MediaQuery.sizeOf(context).height, - onRefresh: controller.readOutput, + selected: shellIdOf(task) == controller.selectedId, + onDetails: () => controller.select(shellIdOf(task)), + detail: + shell != null && shellIdOf(task) == controller.selectedId + ? ChatBackgroundTaskDetail( + key: const Key('chat-bg-task-detail'), + shell: shell, + now: at, + output: controller.output, + heightBudget: MediaQuery.sizeOf(context).height, + onRefresh: controller.readOutput, + ) + : null, ), - ], + ), ], ); }, ); - - Widget _taskRow( - BuildContext context, - Map shell, - bool cupertino, - DateTime at, - ) { - final id = shellIdOf(shell); - final selected = controller.selectedId == id; - final title = Text( - shellCommandSummary(taskText(shell, 'description') ?? shell['command']), - maxLines: 2, - overflow: TextOverflow.ellipsis, - ); - if (cupertino) { - return Semantics( - selected: selected, - child: CupertinoListTile( - key: ValueKey('chat-bg-task-$id'), - title: title, - subtitle: ChatTaskMetadataView(shell: shell, now: at), - backgroundColor: selected - ? CupertinoColors.tertiarySystemFill.resolveFrom(context) - : null, - onTap: () => controller.select(id), - ), - ); - } - return ListTile( - key: ValueKey('chat-bg-task-$id'), - title: title, - subtitle: ChatTaskMetadataView(shell: shell, now: at), - selected: selected, - onTap: () => controller.select(id), - ); - } } diff --git a/app/lib/features/chat/conversation/chat_task_metadata_view.dart b/app/lib/features/chat/conversation/chat_task_metadata_view.dart index ca6e4065..d3f48aa2 100644 --- a/app/lib/features/chat/conversation/chat_task_metadata_view.dart +++ b/app/lib/features/chat/conversation/chat_task_metadata_view.dart @@ -3,8 +3,9 @@ import 'package:flutter/material.dart'; import '../../../core/api_gateway.dart'; import '../domain/chat_task_metadata.dart'; +import 'chat_task_presentation.dart'; -/// Recorded task facts in the row, with unabridged progress in selected detail. +/// Icon-labelled facts, kept distinct from the task's headline and progress. class ChatTaskMetadataView extends StatelessWidget { const ChatTaskMetadataView({ super.key, @@ -12,85 +13,76 @@ class ChatTaskMetadataView extends StatelessWidget { required this.now, this.detail = false, }); - final JsonMap shell; final DateTime now; final bool detail; - String _date(BuildContext context, DateTime time) { - final material = Localizations.of( - context, - MaterialLocalizations, - ); - final date = material != null - ? '${time.day} ${material.formatMonthYear(time)}' - : '${time.day} ${CupertinoLocalizations.of(context).datePickerMonth(time.month)} ${time.year}'; - return '$date · ${time.hour.toString().padLeft(2, '0')}:${time.minute.toString().padLeft(2, '0')}'; - } - @override Widget build(BuildContext context) { final start = taskInstant(shell, 'started_at'); - final elapsed = taskElapsed(shell, now); final duration = taskNumber(shell, 'duration_ms'); final updated = taskInstant(shell, 'updated_at'); - final description = taskText(shell, 'description'); - final progress = taskText(shell, 'progress'); - final kind = taskText(shell, 'task_type'); final lastTool = taskText(shell, 'last_tool'); final tools = taskNumber(shell, 'tool_count'); final tokens = taskNumber(shell, 'token_count'); - final counters = [ - if (tools != null) '$tools tool calls', - if (tokens != null) '$tokens tokens', + final facts = [ + if (!detail) + ChatTaskFact( + icon: taskCupertino(context) ? CupertinoIcons.clock : Icons.schedule, + label: 'Started', + value: start == null + ? 'Start time unavailable' + : formatTaskDate(context, start), + ), + if (!detail && start != null && start.isAfter(now)) + ChatTaskFact( + icon: taskCupertino(context) + ? CupertinoIcons.exclamationmark_circle + : Icons.info_outline, + label: 'Device clock', + value: 'Start time is ahead of this device’s clock', + ), + if (!detail && start == null && duration != null) + ChatTaskFact( + icon: taskCupertino(context) + ? CupertinoIcons.timer + : Icons.timer_outlined, + label: 'Reported runtime', + value: taskDuration(Duration(milliseconds: duration)), + ), + if (!detail && tools != null) + ChatTaskFact( + icon: taskCupertino(context) + ? CupertinoIcons.wrench + : Icons.build_outlined, + label: 'Tool calls', + value: formatTaskCount(tools), + ), + if (!detail && tokens != null) + ChatTaskFact( + icon: taskCupertino(context) + ? CupertinoIcons.number + : Icons.token_outlined, + label: 'Tokens', + value: formatTaskCount(tokens), + ), + if (detail && lastTool != null) + ChatTaskFact( + icon: taskCupertino(context) + ? CupertinoIcons.wrench + : Icons.build_outlined, + label: 'Last tool', + value: lastTool, + ), + if (detail && updated != null) + ChatTaskFact( + icon: taskCupertino(context) + ? CupertinoIcons.arrow_clockwise + : Icons.update, + label: 'Last update', + value: formatTaskDate(context, updated), + ), ]; - final state = elapsed == null - ? 'Running' - : 'Running · ${taskDuration(elapsed)}'; - final kindLabel = kind == null - ? null - : '${kind[0].toUpperCase()}${kind.substring(1).replaceAll('_', ' ')}'; - final summary = - progress ?? - (description != null && - !'${shell['command'] ?? ''}'.endsWith(description) - ? description - : null); - final facts = [ - if (!detail) kindLabel == null ? state : '$kindLabel · $state', - if (detail && elapsed != null) 'Elapsed: ${taskDuration(elapsed)}', - start == null - ? 'Start time unavailable' - : 'Started ${_date(context, start)}', - if (start != null && elapsed == null) - 'Start time is ahead of this device’s clock', - if (elapsed == null && duration != null) - 'Reported runtime: ${taskDuration(Duration(milliseconds: duration))}', - if (detail) ...[?kindLabel, ?description, ?progress] else ...[?summary], - if (counters.isNotEmpty) counters.join(' · '), - if (detail && lastTool != null) 'Last tool: $lastTool', - if (detail && updated != null) 'Last update ${_date(context, updated)}', - ]; - // CupertinoListTile supplies a one-line default; explicitly allow metadata - // to wrap and grow with the available width and system text scaling. - return DefaultTextStyle( - style: DefaultTextStyle.of(context).style, - softWrap: true, - child: Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - for (final fact in facts) - Padding( - padding: const EdgeInsets.only(top: 2), - child: Text( - fact, - maxLines: detail ? null : 2, - overflow: detail ? TextOverflow.clip : TextOverflow.ellipsis, - ), - ), - ], - ), - ); + return Wrap(spacing: 24, runSpacing: 16, children: facts); } } diff --git a/app/lib/features/chat/conversation/chat_task_presentation.dart b/app/lib/features/chat/conversation/chat_task_presentation.dart new file mode 100644 index 00000000..309a0397 --- /dev/null +++ b/app/lib/features/chat/conversation/chat_task_presentation.dart @@ -0,0 +1,140 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../domain/chat_task_metadata.dart'; +import '../../../ui/text/monospace.dart'; +import '../ui/sessions/chat_adaptive.dart'; + +bool taskCupertino(BuildContext context) => + chatControlsStyleOf(context) == ChatControlsStyle.cupertino; + +Color taskSecondary(BuildContext context) => taskCupertino(context) + ? CupertinoColors.secondaryLabel.resolveFrom(context) + : Theme.of(context).colorScheme.onSurfaceVariant; + +TextStyle taskHeading(BuildContext context) => taskCupertino(context) + ? CupertinoTheme.of( + context, + ).textTheme.textStyle.copyWith(fontWeight: FontWeight.w600) + : Theme.of(context).textTheme.titleMedium ?? const TextStyle(); + +String taskDisplayTitle(Map shell) => + taskText(shell, 'description') ?? + taskText(shell, 'command') ?? + 'Background process'; + +String? taskKindLabel(Map shell) { + final value = taskText(shell, 'task_type'); + return value == null + ? null + : '${value[0].toUpperCase()}${value.substring(1).replaceAll('_', ' ')}'; +} + +String _comparable(String value) => value + .trim() + .toLowerCase() + .replaceFirst(RegExp(r'^(agent|shell):\s*'), '') + .replaceAll(RegExp(r'\s+'), ' '); + +bool sameTaskText(String a, String b) => _comparable(a) == _comparable(b); + +/// Progress is useful only when it contributes a fact beyond the title/command. +String? distinctTaskProgress(Map shell) { + final progress = taskText(shell, 'progress'); + if (progress == null) return null; + return [ + taskDisplayTitle(shell), + taskText(shell, 'description'), + taskText(shell, 'command'), + ].whereType().any((value) => sameTaskText(progress, value)) + ? null + : progress; +} + +String formatTaskCount(int count) { + final digits = '$count'; + return [ + for (var end = digits.length; end > 0; end -= 3) + digits.substring((end - 3).clamp(0, digits.length), end), + ].reversed.join(','); +} + +String formatTaskDate(BuildContext context, DateTime time) { + final material = Localizations.of( + context, + MaterialLocalizations, + ); + final monthYear = + material?.formatMonthYear(time) ?? + '${CupertinoLocalizations.of(context).datePickerMonth(time.month)} ${time.year}'; + return '${time.day} $monthYear · ${time.hour.toString().padLeft(2, '0')}:${time.minute.toString().padLeft(2, '0')}'; +} + +/// Native grouped surface; callers supply content that grows with text scaling. +class ChatTaskSurface extends StatelessWidget { + const ChatTaskSurface({ + super.key, + required this.child, + this.padding = const EdgeInsets.all(16), + }); + final Widget child; + final EdgeInsetsGeometry padding; + + @override + Widget build(BuildContext context) => taskCupertino(context) + ? CupertinoListSection.insetGrouped( + margin: EdgeInsets.zero, + backgroundColor: CupertinoColors.transparent, + children: [Padding(padding: padding, child: child)], + ) + : Card.filled( + margin: EdgeInsets.zero, + child: Padding(padding: padding, child: child), + ); +} + +class ChatTaskFact extends StatelessWidget { + const ChatTaskFact({ + super.key, + required this.icon, + required this.label, + required this.value, + this.monospace = false, + }); + final IconData icon; + final String label; + final String value; + final bool monospace; + + @override + Widget build(BuildContext context) => Row( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Padding( + padding: const EdgeInsets.only(top: 2), + child: Icon(icon, size: 18, color: taskSecondary(context)), + ), + const SizedBox(width: 8), + Flexible( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + label, + style: TextStyle(color: taskSecondary(context), fontSize: 12), + ), + const SizedBox(height: 2), + Text( + value, + style: taskHeading( + context, + ).copyWith(fontFamily: monospace ? appMonospaceFamily : null), + ), + ], + ), + ), + ], + ); +} diff --git a/app/test/features/chat/conversation/chat_background_task_metadata_test.dart b/app/test/features/chat/conversation/chat_background_task_metadata_test.dart index 5d61c957..3b874ddc 100644 --- a/app/test/features/chat/conversation/chat_background_task_metadata_test.dart +++ b/app/test/features/chat/conversation/chat_background_task_metadata_test.dart @@ -65,13 +65,14 @@ void main() { ), ); await tester.pumpAndSettle(); - expect(find.text('Running · 2m 0s'), findsOneWidget); - expect(find.text('18 tool calls · 12450 tokens'), findsOneWidget); - expect(find.textContaining('Started 6 November 2026'), findsOneWidget); + expect(find.text('2m 0s'), findsOneWidget); + expect(find.text('18'), findsOneWidget); + expect(find.text('12,450'), findsOneWidget); + expect(find.textContaining('6 November 2026'), findsOneWidget); final requests = gateway.calls.length; now = now.add(const Duration(seconds: 11)); await tester.pump(const Duration(seconds: 11)); - expect(find.text('Running · 2m 11s'), findsOneWidget); + expect(find.text('2m 11s'), findsOneWidget); expect(gateway.calls.length, requests); expect( gateway.calls.where((call) => call.type == 'chat_shell_output'), @@ -127,19 +128,16 @@ void main() { ); await tester.pumpAndSettle(); expect(find.text('Review integration'), findsOneWidget); - expect(find.text('Last tool: Read'), findsNothing); + expect(find.text('Read'), findsNothing); expect( gateway.calls.where((call) => call.type == 'chat_shell_output'), isEmpty, ); await tester.tap(find.byKey(const ValueKey('chat-bg-task-a'))); await tester.pumpAndSettle(); - expect(find.text('Agent: Review integration'), findsOneWidget); - expect(find.text('Last tool: Read'), findsOneWidget); - expect( - find.textContaining('Last update 6 November 2026'), - findsOneWidget, - ); + expect(find.text('Review integration'), findsOneWidget); + expect(find.text('Read'), findsOneWidget); + expect(find.textContaining('09:20'), findsOneWidget); expect( gateway.calls.where((call) => call.type == 'chat_shell_output'), hasLength(1), @@ -162,9 +160,11 @@ void main() { ), ); expect(find.text('Start time unavailable'), findsOneWidget); - expect(find.text('Reported runtime: 1m 14s'), findsOneWidget); - expect(find.text('Running'), findsOneWidget); - expect(find.text('0 tool calls'), findsOneWidget); + expect(find.text('Reported runtime'), findsOneWidget); + expect(find.text('1m 14s'), findsOneWidget); + expect(find.text('Running'), findsNothing); + expect(find.text('Tool calls'), findsOneWidget); + expect(find.text('0'), findsOneWidget); expect(find.textContaining('tokens'), findsNothing); }); } diff --git a/app/test/features/chat/conversation/chat_background_tasks_gui_test.dart b/app/test/features/chat/conversation/chat_background_tasks_gui_test.dart new file mode 100644 index 00000000..fda532f2 --- /dev/null +++ b/app/test/features/chat/conversation/chat_background_tasks_gui_test.dart @@ -0,0 +1,109 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_background_task_card.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_background_tasks_controller.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_background_tasks_panel.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_task_presentation.dart'; + +import 'chat_background_tasks_fixtures.dart'; + +const example = 'Reading screenshots/intake-ui-review-r2/23-more-menu.png'; + +void main() { + test( + 'progress comparison suppresses exact, prefixed and whitespace duplicates', + () { + for (final command in [ + example, + 'Agent: $example', + 'Agent: Reading\n screenshots/intake-ui-review-r2/23-more-menu.png', + ]) { + expect( + distinctTaskProgress({'command': command, 'progress': example}), + isNull, + ); + } + expect( + distinctTaskProgress({ + 'description': example, + 'progress': 'Checking test results', + }), + 'Checking test results', + ); + expect(formatTaskCount(120905), '120,905'); + expect(formatTaskCount(0), '0'); + }, + ); + + for (final cupertino in [false, true]) { + testWidgets( + 'one task has GUI hierarchy, no duplicate path, explicit lazy details ($cupertino)', + (tester) async { + tester.view.physicalSize = const Size(560, 1000); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + final now = DateTime.utc(2026, 11, 6, 23, 44, 40); + final gateway = TasksGateway() + ..shells = (_) async => { + 'chat_shells': [ + { + 'id': 'example', + 'status': 'running', + 'task_type': 'local_agent', + 'command': example, + 'description': example, + 'progress': example, + 'started_at': now + .subtract(const Duration(minutes: 4, seconds: 40)) + .millisecondsSinceEpoch, + 'tool_count': 37, + 'token_count': 120905, + }, + ], + }; + final controller = ChatBackgroundTasksController(gateway, 's'); + addTearDown(controller.dispose); + addTearDown(gateway.close); + final panel = SingleChildScrollView( + child: ChatBackgroundTasksPanel( + controller: controller, + clock: () => now, + ), + ); + await tester.pumpWidget( + cupertino + ? CupertinoApp(home: CupertinoPageScaffold(child: panel)) + : MaterialApp(home: Scaffold(body: panel)), + ); + await tester.pumpAndSettle(); + expect(find.byType(ChatBackgroundTaskCard), findsOneWidget); + expect(find.byType(ChatTaskSurface), findsOneWidget); + expect(find.text(example), findsOneWidget); + expect(find.text('4m 40s'), findsOneWidget); + expect(find.text('Running'), findsOneWidget); + expect(find.text('120,905'), findsOneWidget); + expect(find.text('Tokens'), findsOneWidget); + expect(find.text('37'), findsOneWidget); + expect(find.text('Tool calls'), findsOneWidget); + expect(find.text('Details'), findsOneWidget); + expect( + gateway.calls.where((call) => call.type == 'chat_shell_output'), + isEmpty, + ); + await tester.tap(find.byKey(const ValueKey('chat-bg-task-example'))); + await tester.pumpAndSettle(); + expect(find.text(example), findsOneWidget); + expect(find.text('Hide details'), findsOneWidget); + expect(find.text('Output'), findsOneWidget); + expect( + gateway.calls.where((call) => call.type == 'chat_shell_output'), + hasLength(1), + ); + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox.shrink()); + }, + ); + } +} 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 8ee259dc..1f1fe7ac 100644 --- a/app/test/features/chat/conversation/chat_background_tasks_test.dart +++ b/app/test/features/chat/conversation/chat_background_tasks_test.dart @@ -212,7 +212,7 @@ void main() { await _openTasks(tester); expect(find.text('4 running'), findsOneWidget); - expect(find.byType(AlertDialog), findsOneWidget); + expect(find.byType(Dialog), findsOneWidget); expect(find.byType(SingleChildScrollView), findsWidgets); for (var index = 0; index < 4; index++) { expect( @@ -253,10 +253,10 @@ void main() { }, ]); expect(find.byKey(const Key('chat-bg-task-detail')), findsOneWidget); - expect(find.text('Command'), findsOneWidget); + expect(find.text('Command'), findsNothing); expect(find.text('Task identity'), findsOneWidget); expect(find.text('sh1'), findsOneWidget); - expect(find.text('Status: running'), findsOneWidget); + expect(find.text('Running'), findsOneWidget); expect(find.text('Output'), findsOneWidget); expect( tester @@ -417,8 +417,8 @@ void main() { expect(find.text('1 running'), findsOneWidget); await _tapTask(tester, 'sh1'); - expect(find.text('Command'), findsOneWidget); - expect(find.text('Status: running'), findsOneWidget); + expect(find.text('Command'), findsNothing); + expect(find.text('Running'), findsOneWidget); expect( tester .widget(find.byKey(const Key('chat-bg-task-output'))) @@ -468,6 +468,8 @@ void main() { tester.widget(outputFinder).data, contains('line 199'), ); + await tester.ensureVisible(outputFinder); + await tester.pumpAndSettle(); final scrollable = tester.state( find.descendant(of: outputFinder, matching: find.byType(Scrollable)), );