From d49ab0667ba938f7ea2270f3c4683ae7f2404a38 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Sat, 31 Oct 2026 05:20:00 +0000 Subject: [PATCH 01/14] Templates: shared list rows, named detail bar, compact create, 720 cap --- .../application/templates_destination.dart | 5 +- app/lib/features/templates/screen.dart | 3 + .../templates/ui/template_detail.dart | 118 ++++++++++----- .../templates/ui/template_gallery.dart | 143 +++++++++--------- .../templates/ui/templates_frame.dart | 16 +- .../templates_behind_bar_test.dart | 7 +- .../ui/template_gallery_screen_test.dart | 40 +++-- .../templates/ui/template_layout_test.dart | 73 +++++++++ 8 files changed, 275 insertions(+), 130 deletions(-) create mode 100644 app/test/features/templates/ui/template_layout_test.dart diff --git a/app/lib/application/templates_destination.dart b/app/lib/application/templates_destination.dart index e8569735..2c9188a6 100644 --- a/app/lib/application/templates_destination.dart +++ b/app/lib/application/templates_destination.dart @@ -83,10 +83,10 @@ class _TemplatesDestinationState extends State { // behind the bar and pad their own content by its height. final page = SafeArea(top: false, bottom: false, child: body); if (cupertino) { - // Inset-grouped rows on the grouped background, as in Settings; the + // Plain list rows on the page background, like the other lists; the // bar's scrim takes the same colour. return CupertinoPageScaffold( - backgroundColor: AppColors.groupedBackground, + backgroundColor: AppColors.background, navigationBar: _BarSlot(cupertino: true, child: bar), child: page, ); @@ -115,6 +115,7 @@ class _TemplatesDestinationState extends State { onPressed: widget.onBack, ), title: spec?.title ?? 'Templates', + subtitle: spec?.subtitle, actions: spec?.actions ?? const [], ); } diff --git a/app/lib/features/templates/screen.dart b/app/lib/features/templates/screen.dart index 19fba08e..e84b84ad 100644 --- a/app/lib/features/templates/screen.dart +++ b/app/lib/features/templates/screen.dart @@ -195,7 +195,10 @@ class _TemplatesScreenState extends State { onBack: _back, onCreate: () => _openCreate(selected), ); + final barTitle = selected == null ? null : templateBarTitle(selected); final framed = TemplatesFrame( + title: barTitle?.title ?? templatesTitle, + subtitle: barTitle?.subtitle, body: _withFailure(context, body), embedded: widget.embedded, canGoBack: selected != null, diff --git a/app/lib/features/templates/ui/template_detail.dart b/app/lib/features/templates/ui/template_detail.dart index 6aa24e41..1e887e48 100644 --- a/app/lib/features/templates/ui/template_detail.dart +++ b/app/lib/features/templates/ui/template_detail.dart @@ -5,6 +5,7 @@ import '../../../ui/adaptive/floating_bar_layout.dart'; import '../../../ui/adaptive/host.dart'; import '../../../ui/adaptive/segmented_bar.dart'; import '../domain/template_entry.dart'; +import 'template_gallery.dart' show templatesColumn; /// Browser wording for the gallery and the selected template, kept verbatim. const templateSourceLabel = 'Definition source'; @@ -15,6 +16,17 @@ const templateDetailKey = ValueKey('template-detail'); const templateSourceKey = ValueKey('template-source'); const templateCreateActionKey = ValueKey('template-create-action'); const templateDetailBackKey = ValueKey('template-detail-back'); +const templateKeyKey = ValueKey('template-key'); + +/// What the bar's title pill shows for an open template: its name, and its +/// description (when it has one) as the one-line subtitle. +({String title, String? subtitle}) templateBarTitle(TemplateEntry entry) { + final description = entry.description.trim(); + return ( + title: templateDetailName(entry), + subtitle: description.isEmpty ? null : description, + ); +} /// A gallery card's name: a blank name is the explicit unnamed placeholder. String templateGalleryName(TemplateEntry entry) { @@ -52,64 +64,92 @@ class TemplateDetail extends StatelessWidget { @override Widget build(BuildContext context) { final cupertino = usesCupertinoHost(context); + final muted = templateMutedStyle(context); + final description = entry.description.trim(); return ListView( key: templateDetailKey, padding: withBarClearance(context, const EdgeInsets.only(bottom: 24)), children: [ if (showBack) _backRow(context, cupertino), - Padding( - padding: const EdgeInsets.fromLTRB(16, 8, 16, 0), - child: Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - _createButton(context, cupertino), - const SizedBox(height: 12), - Text( - templateDetailName(entry), - style: templateTitleStyle(context), - ), - if (entry.description.trim().isNotEmpty) - Padding( - padding: const EdgeInsets.only(top: 8), - child: Text(entry.description), + templatesColumn( + Padding( + padding: const EdgeInsets.fromLTRB(16, 8, 16, 0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // With a bar above, its title pill carries the name and the + // description; only a bar-less page names the template here. + if (showBack) ...[ + Text( + templateDetailName(entry), + style: templateTitleStyle(context), + ), + if (description.isNotEmpty) + Padding( + padding: const EdgeInsets.only(top: 8), + child: Text(entry.description), + ), + const SizedBox(height: 12), + ], + _createButton(cupertino), + const SizedBox(height: 16), + // The key and the schedule on one quiet line, not a + // label/value document. + Wrap( + spacing: 8, + runSpacing: 4, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + SelectableText( + entry.key, + key: templateKeyKey, + semanticsLabel: 'Key ${entry.key}', + style: muted, + ), + if (entry.scheduled) ...[ + Text('·', style: muted), + Text(templateIncludesScheduleLabel, style: muted), + ], + ], ), - const SizedBox(height: 16), - Text('Key', style: templateMutedStyle(context)), - SelectableText(entry.key, style: templateBodyStyle(context)), - if (entry.scheduled) - Padding( - padding: const EdgeInsets.only(top: 8), - child: Text(templateIncludesScheduleLabel), + const SizedBox(height: 20), + Text(templateSourceLabel, style: templateSectionStyle(context)), + const SizedBox(height: 8), + // The server's source, byte-for-byte: no trim, re-indent or + // re-encoding, so selecting it copies exactly what was + // received. + SizedBox( + width: double.infinity, + child: SelectableText( + entry.source, + key: templateSourceKey, + style: templateBodyStyle(context), + ), ), - const SizedBox(height: 20), - Text(templateSourceLabel, style: templateSectionStyle(context)), - const SizedBox(height: 8), - // The server's source, byte-for-byte: no trim, re-indent or - // re-encoding, so selecting it copies exactly what was received. - SelectableText( - entry.source, - key: templateSourceKey, - style: templateBodyStyle(context), - ), - ], + ], + ), ), ), ], ); } - Widget _createButton(BuildContext context, bool cupertino) { + /// A compact button at its own width: the page's one action, never a bar + /// spanning a wide window. + Widget _createButton(bool cupertino) { if (cupertino) { return CupertinoButton.filled( key: templateCreateActionKey, + sizeStyle: CupertinoButtonSize.medium, onPressed: onCreate, child: const Text(templateCreateActionLabel), ); } - return FilledButton( + return FilledButton.icon( key: templateCreateActionKey, onPressed: onCreate, - child: const Text(templateCreateActionLabel), + icon: const Icon(Icons.add), + label: const Text(templateCreateActionLabel), ); } @@ -160,7 +200,11 @@ TextStyle? templateBodyStyle(BuildContext context) { TextStyle? templateMutedStyle(BuildContext context) { if (usesCupertinoHost(context)) { - return CupertinoTheme.of(context).textTheme.tabLabelTextStyle.copyWith( + // The list rows' secondary size, not the tab bar's 10pt caption. + // SelectableText needs an explicit baseline when it inherits no style. + return CupertinoTheme.of(context).textTheme.textStyle.copyWith( + inherit: true, + fontSize: 15, color: CupertinoColors.secondaryLabel.resolveFrom(context), ); } diff --git a/app/lib/features/templates/ui/template_gallery.dart b/app/lib/features/templates/ui/template_gallery.dart index 1bac4f26..39ba5c7d 100644 --- a/app/lib/features/templates/ui/template_gallery.dart +++ b/app/lib/features/templates/ui/template_gallery.dart @@ -1,8 +1,10 @@ -import '../../../ui/theme/app_theme.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; +import '../../../ui/adaptive/floating_bar_layout.dart'; import '../../../ui/adaptive/host.dart'; +import '../../../ui/layout/app_list_avatar.dart'; +import '../../../ui/layout/app_list_row.dart'; import '../domain/template_entry.dart'; import 'template_detail.dart'; import 'templates_failure.dart'; @@ -16,8 +18,23 @@ const _loadingMessage = 'Loading templates…'; const _emptyMessage = 'No templates are available on this server.'; Key templateRowKey(String key) => ValueKey('template-row-$key'); +Key templateAvatarKey(String key) => ValueKey('template-avatar-$key'); -/// The gallery's truthful states and native catalogue rows. +/// The widest the gallery and an open template grow on a wide window: the +/// Settings column's reading width, so the page opened from Settings lines up +/// with it. +const double templatesContentMaxWidth = 720; + +/// Caps [child] at [templatesContentMaxWidth], start-aligned under the bar. +Widget templatesColumn(Widget child) => Align( + alignment: AlignmentDirectional.topStart, + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: templatesContentMaxWidth), + child: child, + ), +); + +/// The gallery's truthful states and the app's shared list rows. /// /// It owns no requests: loading, failure and the actual rows all come from the /// screen, so opening a row only selects an already-read template. @@ -44,9 +61,7 @@ class TemplateGallery extends StatelessWidget { final ValueChanged onOpen; @override - Widget build(BuildContext context) => _body(context); - - Widget _body(BuildContext context) { + Widget build(BuildContext context) { if (!loaded) { if (error != null) { return TemplatesFailureState( @@ -58,9 +73,7 @@ class TemplateGallery extends StatelessWidget { return _loadingState(context); } if (templates.isEmpty) return _emptyState(context); - return usesCupertinoHost(context) - ? _cupertinoList(context) - : _materialList(context); + return _list(context); } Widget _loadingState(BuildContext context) { @@ -93,82 +106,62 @@ class TemplateGallery extends StatelessWidget { ); } - Widget _materialList(BuildContext context) { - return ListView.separated( + Widget _list(BuildContext context) { + final cupertino = usesCupertinoHost(context); + // The rows scroll behind the bar and the floating tab bar. + return ListView.builder( key: templatesGalleryKey, + padding: withBarClearance(context, const EdgeInsets.only(bottom: 8)), itemCount: templates.length, - separatorBuilder: (_, _) => const Divider(height: 1), itemBuilder: (context, index) { final entry = templates[index]; - return ListTile( - key: templateRowKey(entry.key), - title: Text(templateGalleryName(entry)), - subtitle: _materialSubtitle(entry), - trailing: const Icon(Icons.chevron_right), - onTap: () => onOpen(entry.key), + return templatesColumn( + AppListRow( + key: templateRowKey(entry.key), + cupertino: cupertino, + divider: index < templates.length - 1, + onTap: () => onOpen(entry.key), + leading: ExcludeSemantics( + child: AppListAvatar.initial( + templateDetailName(entry), + key: templateAvatarKey(entry.key), + color: _avatarColor(context, entry.key, cupertino), + ), + ), + title: Text(templateGalleryName(entry)), + subtitle: _subtitle(entry), + ), ); }, ); } - Widget _cupertinoList(BuildContext context) { - return ListView( - key: templatesGalleryKey, - children: [ - CupertinoListSection.insetGrouped( - backgroundColor: AppColors.groupedBackground, - children: [ - for (final entry in templates) - CupertinoListTile( - key: templateRowKey(entry.key), - title: _cupertinoText(templateGalleryName(entry)), - subtitle: _cupertinoSubtitle(entry), - trailing: const CupertinoListTileChevron(), - onTap: () => onOpen(entry.key), - ), - ], - ), - ], - ); - } - - /// The native tile is single-line by default. Let its content wrap at larger - /// text sizes instead of ellipsizing a template's own name; the row grows - /// with the content and nothing else about the tile is restyled. - Widget _cupertinoText(String text) => - DefaultTextStyle.merge(maxLines: 3, child: Text(text)); - - Widget _materialSubtitle(TemplateEntry entry) { - final description = entry.description.trim().isEmpty - ? null - : Text(entry.description); - final count = Text(_stageCountLabel(entry.key)); - if (description == null) return count; - return Column( - crossAxisAlignment: CrossAxisAlignment.start, - mainAxisSize: MainAxisSize.min, - children: [description, count], - ); - } - - Widget _cupertinoSubtitle(TemplateEntry entry) { - final description = entry.description.trim().isEmpty - ? null - : _cupertinoText(entry.description); - final count = _cupertinoText(_stageCountLabel(entry.key)); - if (description == null) return count; - return Column( - crossAxisAlignment: CrossAxisAlignment.start, - mainAxisSize: MainAxisSize.min, - children: [description, count], - ); - } - - String _stageCountLabel(String key) { - if (!stageCounts.containsKey(key) || stageCounts[key] == null) { - return 'stage count unavailable'; + /// One of the theme's accents, picked by the template key so a row keeps + /// its colour across reloads (the Pipelines list's palette). + Color _avatarColor(BuildContext context, String key, bool cupertino) { + final List colors; + if (cupertino) { + colors = [ + CupertinoTheme.of(context).primaryColor, + CupertinoColors.systemIndigo.resolveFrom(context), + CupertinoColors.systemTeal.resolveFrom(context), + ]; + } else { + final scheme = Theme.of(context).colorScheme; + colors = [scheme.primary, scheme.secondary, scheme.tertiary]; } - final count = stageCounts[key]!; - return '$count ${count == 1 ? 'stage' : 'stages'}'; + final hash = key.codeUnits.fold(0, (sum, unit) => sum + unit); + return colors[hash % colors.length]; + } + + /// The description, then the stage count when the server could parse the + /// source. An unknown count is left out rather than announced on every row. + Widget? _subtitle(TemplateEntry entry) { + final count = stageCounts[entry.key]; + final parts = [ + if (entry.description.trim().isNotEmpty) entry.description.trim(), + if (count != null) '$count ${count == 1 ? 'stage' : 'stages'}', + ]; + return parts.isEmpty ? null : Text(parts.join(' · ')); } } diff --git a/app/lib/features/templates/ui/templates_frame.dart b/app/lib/features/templates/ui/templates_frame.dart index 2894dd40..bec139de 100644 --- a/app/lib/features/templates/ui/templates_frame.dart +++ b/app/lib/features/templates/ui/templates_frame.dart @@ -9,6 +9,7 @@ import '../../../ui/theme/app_theme.dart'; const templatesRefreshKey = ValueKey('templates-refresh'); const templatesBackKey = ValueKey('templates-back'); +const templatesTitle = 'Templates'; /// The screen's native chrome. /// @@ -26,8 +27,14 @@ class TemplatesFrame extends StatelessWidget { required this.refreshing, required this.onBack, required this.onRefresh, + this.title = templatesTitle, + this.subtitle, }); + /// The bar's title pill: `Templates` on the gallery, the open template's + /// name (with its description as [subtitle]) on a detail. + final String title; + final String? subtitle; final Widget body; final bool embedded; final bool canGoBack; @@ -41,7 +48,8 @@ class TemplatesFrame extends StatelessWidget { if (embedded) { if (ShellBar.available(context)) { return ShellBar( - title: 'Templates', + title: title, + subtitle: subtitle, onBack: canGoBack ? onBack : null, actions: [_refreshButton()], child: body, @@ -70,14 +78,16 @@ class TemplatesFrame extends StatelessWidget { onPressed: onBack, ) : null, - title: 'Templates', + title: title, + subtitle: subtitle, actions: [_refreshButton()], ); // The body reaches the top edge and scrolls behind the bar. final page = SafeArea(top: false, bottom: false, child: body); if (cupertino) { return CupertinoPageScaffold( - backgroundColor: AppColors.groupedBackground, + // Plain list rows on the page background, like the other lists. + backgroundColor: AppColors.background, navigationBar: bar, child: page, ); diff --git a/app/test/application/templates_behind_bar_test.dart b/app/test/application/templates_behind_bar_test.dart index b4e17817..5e3d95a4 100644 --- a/app/test/application/templates_behind_bar_test.dart +++ b/app/test/application/templates_behind_bar_test.dart @@ -13,7 +13,7 @@ import 'templates_wiring_test.dart' show openSettings, openTemplates, pumpApp; /// The app-level Templates page: one bar (Back + Refresh), the gallery and an /// open template reach the top edge, start below the bar at rest and scroll -/// behind it. Cupertino draws inset-grouped rows on the grouped background. +/// behind it. Both hosts draw the shared list rows on the page background. void main() { for (final cupertino in [false, true]) { final host = cupertino ? 'Cupertino' : 'Material'; @@ -69,13 +69,14 @@ void main() { ) .first, ); - expect(scaffold.backgroundColor, AppColors.groupedBackground); + // Plain shared rows on the page background, like the other lists. + expect(scaffold.backgroundColor, AppColors.background); expect( find.descendant( of: gallery, matching: find.byType(CupertinoListSection), ), - findsOneWidget, + findsNothing, ); } diff --git a/app/test/features/templates/ui/template_gallery_screen_test.dart b/app/test/features/templates/ui/template_gallery_screen_test.dart index ec04ab7c..463f4285 100644 --- a/app/test/features/templates/ui/template_gallery_screen_test.dart +++ b/app/test/features/templates/ui/template_gallery_screen_test.dart @@ -6,6 +6,9 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:pipelines_app/core/api_gateway.dart'; import 'package:pipelines_app/features/templates/screen.dart'; import 'package:pipelines_app/features/templates/ui/template_detail.dart'; +import 'package:pipelines_app/features/templates/ui/template_gallery.dart' + show templateAvatarKey; +import 'package:pipelines_app/ui/layout/app_list_row.dart'; import '../data/template_test_support.dart' show source; import 'template_gallery_test_support.dart'; @@ -31,15 +34,19 @@ void main() { expect(find.byKey(templatesGalleryKey), findsOneWidget); expect(find.text('Release workflow'), findsOneWidget); - expect(find.text('Ship a version'), findsOneWidget); - expect(find.text('2 stages'), findsNWidgets(2)); + // One subtitle line: the description, then the parsed stage count. + expect(find.text('Ship a version · 2 stages'), findsOneWidget); + expect(find.text('No display name · 2 stages'), findsOneWidget); expect(find.text('(unnamed template)'), findsOneWidget); expect(find.byKey(templatesLoadingKey), findsNothing); + // The app's shared rows with an initial avatar; no chevrons or tiles. + expect(find.byType(AppListRow), findsNWidgets(2)); + expect(find.byKey(templateAvatarKey('release')), findsOneWidget); + expect(find.byType(ListTile), findsNothing); + expect(find.byIcon(Icons.chevron_right), findsNothing); }); - testWidgets('stage count is unavailable when server parsing refuses', ( - tester, - ) async { + testWidgets('an unknown stage count is left out of the row', (tester) async { final gateway = GalleryGateway((type, fields) async => templatesReply(galleryTemplates)) ..validationHandler = (type, fields) async { @@ -48,8 +55,9 @@ void main() { await pumpGallery(tester, gateway); - expect(find.text('stage count unavailable'), findsNWidgets(2)); - expect(find.text('0 stages'), findsNothing); + expect(find.textContaining('stage count'), findsNothing); + expect(find.textContaining('stages'), findsNothing); + expect(find.text('Ship a version'), findsOneWidget); expect(gateway.callsOf('validate'), hasLength(2)); expect( gateway.callsOf('validate').first.fields['source'], @@ -162,9 +170,20 @@ void main() { await tester.pumpAndSettle(); expect(find.byKey(templateDetailKey), findsOneWidget); + // The bar's title pill names the template; the body does not repeat it. + final bar = find.byType(SegmentedBar); + expect( + find.descendant(of: bar, matching: find.text('Release workflow')), + findsOneWidget, + ); + expect( + find.descendant(of: bar, matching: find.text('Ship a version')), + findsOneWidget, + ); expect(find.text('Release workflow'), findsOneWidget); expect(find.text('Ship a version'), findsOneWidget); - expect(find.text('Key'), findsOneWidget); + expect(find.text('Key'), findsNothing); + expect(find.byKey(templateKeyKey), findsOneWidget); expect(find.text('Includes a schedule'), findsOneWidget); expect(find.text(templateSourceLabel), findsOneWidget); expect(selectableSource(source), findsOneWidget); @@ -230,7 +249,8 @@ void main() { ); await pumpGallery(tester, gateway, cupertino: true); - expect(find.byType(CupertinoListTile), findsNWidgets(2)); + expect(find.byType(AppListRow), findsNWidgets(2)); + expect(find.byType(CupertinoListTile), findsNothing); expect(find.byType(Scaffold), findsNothing); await tester.tap(find.byKey(templateRowKey('release'))); await tester.pumpAndSettle(); @@ -247,7 +267,7 @@ void main() { await tester.tap(find.byKey(templatesBackKey)); await tester.pumpAndSettle(); - expect(find.byType(CupertinoListTile), findsNWidgets(2)); + expect(find.byType(AppListRow), findsNWidgets(2)); }); testWidgets( diff --git a/app/test/features/templates/ui/template_layout_test.dart b/app/test/features/templates/ui/template_layout_test.dart new file mode 100644 index 00000000..2104f768 --- /dev/null +++ b/app/test/features/templates/ui/template_layout_test.dart @@ -0,0 +1,73 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/templates/screen.dart'; +import 'package:pipelines_app/features/templates/ui/template_detail.dart'; +import 'package:pipelines_app/features/templates/ui/template_gallery.dart'; +import 'package:pipelines_app/ui/adaptive/segmented_bar.dart'; + +import '../data/template_test_support.dart' show source; +import 'template_gallery_test_support.dart'; + +/// The gallery and an open template on a wide window: the column stops at the +/// Settings reading width, start-aligned; the bar names the open template and +/// the Create action is a compact button, not a full-width bar. +void main() { + for (final cupertino in [false, true]) { + final host = cupertino ? 'Cupertino' : 'Material'; + + testWidgets('$host: rows and detail are capped at 720 on a wide window', ( + tester, + ) async { + final gateway = GalleryGateway( + (type, fields) async => templatesReply(galleryTemplates), + ); + await pumpGallery( + tester, + gateway, + cupertino: cupertino, + size: const Size(1200, 800), + ); + + final row = tester.getRect(find.byKey(templateRowKey('release'))); + expect(row.left, 0); + expect(row.width, templatesContentMaxWidth); + expect(find.text('Templates'), findsOneWidget); + + await tester.tap(find.byKey(templateRowKey('release'))); + await tester.pumpAndSettle(); + + final bar = find.byType(SegmentedBar); + expect( + find.descendant(of: bar, matching: find.text('Release workflow')), + findsOneWidget, + ); + expect(find.text('Templates'), findsNothing); + + final create = tester.getRect(find.byKey(templateCreateActionKey)); + expect(create.left, 16); + // Its own width, not stretched across the 688 content column. + expect(create.width, lessThan(templatesContentMaxWidth - 32)); + final body = tester.getRect(selectableSource(source)); + expect(body.right, lessThanOrEqualTo(templatesContentMaxWidth)); + expect(tester.takeException(), isNull); + }); + + testWidgets('$host: the detail fits 320 at 2x text', (tester) async { + final gateway = GalleryGateway( + (type, fields) async => templatesReply(galleryTemplates), + ); + await pumpGallery( + tester, + gateway, + cupertino: cupertino, + size: const Size(320, 800), + textScale: 2, + ); + expect(tester.takeException(), isNull); + await tester.tap(find.byKey(templateRowKey('release'))); + await tester.pumpAndSettle(); + expect(find.byKey(templateCreateActionKey), findsOneWidget); + expect(tester.takeException(), isNull); + }); + } +} From 06a52298b1dbb659d1a1867b6fab6eed924c54f1 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Sat, 31 Oct 2026 12:09:44 +0000 Subject: [PATCH 02/14] WIP: flat detail bodies, facts grid, wide run chrome, pipeline summary --- .../ui/artifact_document_section.dart | 23 ++- .../artifacts/ui/artifact_gallery_page.dart | 6 +- .../artifacts/ui/artifact_visit_list.dart | 10 +- .../widgets/pipeline_summary_view.dart | 142 ++++++++---------- .../features/runs/ui/run_decision_notice.dart | 15 +- .../runs/ui/run_detail_tab_bodies.dart | 112 +++----------- app/lib/features/runs/ui/run_detail_tabs.dart | 55 ++++--- .../features/runs/ui/run_detail_timeline.dart | 116 +++++--------- .../runs/ui/run_detail_visit_session.dart | 22 +-- .../runs/ui/run_detail_wide_chrome.dart | 86 +++++++++++ .../features/runs/ui/run_graph_preview.dart | 21 +++ .../pipeline/schedule_pipeline_list_body.dart | 75 +++++---- .../pipeline/schedule_pipeline_wording.dart | 2 - app/lib/ui/layout/facts_grid.dart | 123 +++++++++++++++ app/lib/ui/layout/section_heading.dart | 36 +++-- 15 files changed, 472 insertions(+), 372 deletions(-) create mode 100644 app/lib/features/runs/ui/run_detail_wide_chrome.dart create mode 100644 app/lib/ui/layout/facts_grid.dart diff --git a/app/lib/features/artifacts/ui/artifact_document_section.dart b/app/lib/features/artifacts/ui/artifact_document_section.dart index 5ee306cb..fb4df48f 100644 --- a/app/lib/features/artifacts/ui/artifact_document_section.dart +++ b/app/lib/features/artifacts/ui/artifact_document_section.dart @@ -1,4 +1,4 @@ -import '../../../ui/theme/app_theme.dart'; +import '../../../ui/layout/section_heading.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; @@ -41,18 +41,10 @@ class ArtifactDocumentSection extends StatelessWidget { children: rows, ); } - if (usesCupertinoHost(context)) { - return CupertinoListSection.insetGrouped( - backgroundColor: AppColors.groupedBackground, - header: Semantics( - container: true, - header: true, - child: const Text('Turn documents'), - ), - hasLeading: false, - children: rows, - ); - } + // Flat rows under a quiet label on both hosts: the section sits inside + // the visit's Session page, which is itself flat, so a Cupertino inset + // group here would be a group nested in a group. + final cupertino = usesCupertinoHost(context); return Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ @@ -61,7 +53,10 @@ class ArtifactDocumentSection extends StatelessWidget { child: Semantics( container: true, header: true, - child: const Text('Turn documents'), + child: Text( + 'Turn documents', + style: cupertino ? SectionHeadingStyle.of(context).title : null, + ), ), ), ...rows, diff --git a/app/lib/features/artifacts/ui/artifact_gallery_page.dart b/app/lib/features/artifacts/ui/artifact_gallery_page.dart index b3b06c1f..66f0d3a7 100644 --- a/app/lib/features/artifacts/ui/artifact_gallery_page.dart +++ b/app/lib/features/artifacts/ui/artifact_gallery_page.dart @@ -1,5 +1,4 @@ import '../../../ui/adaptive/segmented_bar.dart'; -import '../../../ui/theme/app_theme.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; @@ -395,10 +394,9 @@ class _ArtifactGalleryPageState extends State { ); if (widget.embedded) return body; if (usesCupertinoHost(context)) { + // Flat sections on the page colour, as in the run and stage details; + // their pinned headings take the same colour. return CupertinoPageScaffold( - // Sections paint the grouped background; the page must match it or a - // white seam shows below the last section in light mode. - backgroundColor: AppColors.groupedBackground, navigationBar: const SegmentedBar( cupertino: true, title: artifactGalleryTitle, diff --git a/app/lib/features/artifacts/ui/artifact_visit_list.dart b/app/lib/features/artifacts/ui/artifact_visit_list.dart index be9ed1ea..9051ed50 100644 --- a/app/lib/features/artifacts/ui/artifact_visit_list.dart +++ b/app/lib/features/artifacts/ui/artifact_visit_list.dart @@ -3,6 +3,7 @@ import 'package:flutter/material.dart'; import '../../../ui/adaptive/host.dart'; import '../domain/artifact_groups.dart'; +import '../../../ui/layout/section_heading.dart'; import '../../../ui/layout/sticky_section.dart'; import 'artifact_document_section.dart'; import 'artifact_record_row.dart'; @@ -106,7 +107,14 @@ class _ArtifactVisitListState extends State { final slivers = [ if (header != null) SliverToBoxAdapter(child: header), // The grid/list switch stays reachable while the gallery scrolls. - StickyBar(child: _modeSwitch(context)), + PinnedHeaderSliver( + // On the page colour (that of the pinned section headings), not a + // grouped band. + child: ColoredBox( + color: SectionHeadingStyle.of(context).background, + child: _modeSwitch(context), + ), + ), ]; for (final group in widget.groups) { final identity = '${group.stageKey}\u0000${group.visit}'; diff --git a/app/lib/features/pipelines/widgets/pipeline_summary_view.dart b/app/lib/features/pipelines/widgets/pipeline_summary_view.dart index 52fc0745..2fca4006 100644 --- a/app/lib/features/pipelines/widgets/pipeline_summary_view.dart +++ b/app/lib/features/pipelines/widgets/pipeline_summary_view.dart @@ -1,8 +1,10 @@ -import '../../../ui/theme/app_theme.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import '../../../core/api_gateway.dart'; +import '../../../ui/layout/app_list_row.dart'; +import '../../../ui/layout/facts_grid.dart'; +import '../../../ui/layout/section_heading.dart'; import '../../schedules/ui/pipeline/schedule_pipeline_section.dart'; import '../pipeline_format.dart'; import '../pipeline_models.dart'; @@ -11,9 +13,14 @@ import '../pipelines_controller.dart'; import 'pipeline_controls.dart'; import 'pipeline_detail_styles.dart'; -/// Summary tab: key/value facts, the pipeline's saved schedules and the version -/// history. Version rows are selectable; the latest version's row is marked and -/// a historical selection offers an explicit return to latest. +/// The Summary's facts grid. +const pipelineSummaryFactsKey = Key('pipeline-summary-facts'); + +/// Summary tab: the recorded facts as a compact grid, the pipeline's saved +/// schedules and the version history, flat on the page on both hosts (the +/// same structure as the run Summary). Version rows are the app's shared list +/// row; the shown version is the selected row, and a historical selection +/// offers an explicit return to latest. class PipelineSummaryView extends StatelessWidget { const PipelineSummaryView({ super.key, @@ -67,60 +74,62 @@ class PipelineSummaryView extends StatelessWidget { ); } + /// Only recorded values are facts: a blank one is omitted, not drawn empty. Widget _fields(BuildContext context) { - return Padding( - padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - for (final field in pipelineSummaryFields(detail)) - Padding( - padding: const EdgeInsets.only(bottom: 12), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text(field.key, style: pipelineMutedStyle(context)), - SelectableText( - field.value, - style: pipelineValueStyle( - context, - monospace: field.monospace, - ), - ), - ], - ), - ), - ], - ), + final fields = [ + for (final field in pipelineSummaryFields(detail)) + if (field.value.trim().isNotEmpty) field, + ]; + if (fields.isEmpty) return const SizedBox.shrink(); + return FactsGrid( + key: pipelineSummaryFactsKey, + cupertino: useCupertinoControls(context), + items: [ + for (final field in fields) + FactsGridItem( + key: ValueKey('pipeline-summary-${_slug(field.key)}'), + label: field.key, + value: field.value, + // A hash gets its own line; the host font is kept (the pipeline + // detail does not switch identifiers to monospace). + wide: field.monospace, + ), + ], ); } Widget _versions(BuildContext context) { + final cupertino = useCupertinoControls(context); final effective = detail.resolvedVersion; final showingLatest = effective == detail.latestVersion; + final versions = detail.versions; final rows = [ if (!showingLatest) - _versionTile( - context, + AppListRow( key: const Key('pipeline-latest-version'), - subtitle: 'Return to the latest version', - selected: false, - label: 'View latest v${detail.latestVersion}', + cupertino: cupertino, + title: Text('View latest v${detail.latestVersion}'), + subtitle: const Text('Return to the latest version'), + divider: versions.isNotEmpty, onTap: () => controller.selectVersion(0), ), - for (final version in detail.versions) - _versionTile( - context, - key: Key('pipeline-version-${version.version}'), - subtitle: [ - stageCountText(version.stages), - ?formatLocalTimestamp(version.createdAt), - ].join(' · '), - selected: version.version == effective, - label: 'v${version.version}', - onTap: () => controller.selectVersion(version.version), + for (var index = 0; index < versions.length; index += 1) + AppListRow( + key: Key('pipeline-version-${versions[index].version}'), + cupertino: cupertino, + selected: versions[index].version == effective, + title: Text('v${versions[index].version}'), + time: formatLocalTimestamp(versions[index].createdAt), + subtitle: Text( + [ + stageCountText(versions[index].stages), + if (versions[index].version == detail.latestVersion) 'latest', + ].join(' · '), + ), + divider: index < versions.length - 1, + onTap: () => controller.selectVersion(versions[index].version), ), - if (detail.versions.isEmpty) + if (versions.isEmpty) Padding( padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), child: Text( @@ -129,49 +138,18 @@ class PipelineSummaryView extends StatelessWidget { ), ), ]; - if (useCupertinoControls(context)) { - return CupertinoListSection.insetGrouped( - backgroundColor: AppColors.groupedBackground, - header: const Text('VERSIONS'), - children: rows, - ); - } return Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ - Padding( - padding: const EdgeInsets.fromLTRB(16, 12, 16, 4), - child: Text('Versions', style: pipelineSectionStyle(context)), + const SectionHeading( + title: 'Versions', + header: true, + padding: EdgeInsetsDirectional.only(start: 16, end: 8), ), ...rows, ], ); } - - Widget _versionTile( - BuildContext context, { - required Key key, - required String subtitle, - required bool selected, - required String label, - required VoidCallback onTap, - }) { - if (useCupertinoControls(context)) { - return CupertinoListTile( - key: key, - title: Text(label), - subtitle: Text(subtitle), - trailing: selected ? const Icon(CupertinoIcons.check_mark) : null, - onTap: onTap, - ); - } - return ListTile( - key: key, - selected: selected, - title: Text(label), - subtitle: Text(subtitle), - trailing: selected ? const Icon(Icons.check) : null, - onTap: onTap, - ); - } } + +String _slug(String label) => label.toLowerCase().replaceAll(' ', '-'); diff --git a/app/lib/features/runs/ui/run_decision_notice.dart b/app/lib/features/runs/ui/run_decision_notice.dart index 24cd7732..5a9a6f81 100644 --- a/app/lib/features/runs/ui/run_decision_notice.dart +++ b/app/lib/features/runs/ui/run_decision_notice.dart @@ -23,9 +23,10 @@ class RunDecisionNotice extends StatelessWidget { Widget build(BuildContext context) { final pending = pendingDecision(run); if (pending == null) return const SizedBox.shrink(); - // As the web's `.decision-card`: one full-width banner in the waiting - // colour, with the glyph, the title over its meta line, and the action on - // the trailing edge. The same banner on both hosts. + // One full-width line of the header strip: the glyph in the waiting + // colour, the title over its meta line, and the action on the trailing + // edge. The strip is already the frame, so the banner draws no card, + // border or tint of its own. The same banner on both hosts. final cupertino = usesCupertinoHost(context); final color = CupertinoColors.systemTeal.resolveFrom(context); final metaStyle = cupertino @@ -36,13 +37,7 @@ class RunDecisionNotice extends StatelessWidget { return Container( key: const Key('run-decision-banner'), width: double.infinity, - margin: const EdgeInsets.only(top: 8), - padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12), - decoration: BoxDecoration( - color: color.withValues(alpha: 0.12), - border: Border.all(color: color), - borderRadius: BorderRadius.circular(10), - ), + padding: const EdgeInsets.only(top: 8, bottom: 4), child: Row( children: [ Icon( diff --git a/app/lib/features/runs/ui/run_detail_tab_bodies.dart b/app/lib/features/runs/ui/run_detail_tab_bodies.dart index a6674623..fd5ae2c6 100644 --- a/app/lib/features/runs/ui/run_detail_tab_bodies.dart +++ b/app/lib/features/runs/ui/run_detail_tab_bodies.dart @@ -1,4 +1,3 @@ -import '../../../ui/theme/app_theme.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; @@ -8,11 +7,12 @@ import 'run_detail_summary_fields.dart'; import 'run_detail_visit_facts.dart'; import 'run_field_body.dart'; import '../../../ui/adaptive/host.dart'; +import '../../../ui/layout/facts_grid.dart'; import '../../../ui/layout/sticky_section.dart'; import '../../../ui/text/monospace.dart'; import '../../../ui/adaptive/floating_bar_layout.dart'; -/// The Summary tab: the run's identity, the recorded facts as key/value rows, +/// The Summary tab: the run's identity, the recorded facts as one grid, /// the stored original prompt with its copy control and the collapsible Input /// and Output sections. /// @@ -34,9 +34,12 @@ Widget runDetailSummaryTab({ final rows = detailSummaryRows(run); final identity = detailSummaryIdentity(run); // No separate "Original prompt": the run's Input carries it, as data. + // The top bar's subtitle already names the run's pipeline (and its title + // opens it), so a Pipeline fact would only repeat it. + final pipelineInBar = '${run['name'] ?? ''}'.trim().isNotEmpty; final facts = [ for (final row in rows) - if (!row.block) row, + if (!row.block && !(pipelineInBar && row.label == 'Pipeline')) row, ]; return CustomScrollView( key: const Key('run-detail-tab-body-summary'), @@ -58,14 +61,22 @@ Widget runDetailSummaryTab({ ), ), ), + // The facts sit on the page as one grid, the same on both hosts: no + // grouped card, so a single fact starts at the leading edge. if (facts.isNotEmpty) SliverToBoxAdapter( - child: cupertino - ? CupertinoListSection.insetGrouped( - backgroundColor: AppColors.groupedBackground, - children: [_summaryFacts(context, facts, cupertino: true)], - ) - : _summaryFacts(context, facts, cupertino: false), + child: FactsGrid( + key: const Key('run-detail-summary-facts'), + items: [ + for (final row in facts) + FactsGridItem( + key: ValueKey('run-detail-summary-${_slug(row.label)}'), + label: row.label, + value: row.value, + monospace: row.monospace, + ), + ], + ), ), // Long blocks (the Diagnostic), Input and Output are sticky // collapsibles: each title stays pinned while its content scrolls. @@ -200,18 +211,7 @@ Widget runDetailFieldTab({ cupertino: cupertino, textBuilder: cupertino ? _CupertinoSelectableText.new : null, ); - if (cupertino) { - return ListView( - key: Key('run-detail-tab-body-$tabKey'), - // Clear of a floating tab bar (the list pads its media insets itself). - children: [ - CupertinoListSection.insetGrouped( - backgroundColor: AppColors.groupedBackground, - children: [Padding(padding: const EdgeInsets.all(16), child: body)], - ), - ], - ); - } + // Flat on the page on both hosts, like the Summary. return Builder( builder: (context) => ListView( key: Key('run-detail-tab-body-$tabKey'), @@ -223,76 +223,6 @@ Widget runDetailFieldTab({ // --- Material -------------------------------------------------------------- -/// The recorded facts as a compact grid: two short facts per line on a phone, -/// three when wider; a long or monospace value (a path, a hash) takes a whole -/// line so it is never squeezed. -Widget _summaryFacts( - BuildContext context, - List rows, { - required bool cupertino, -}) { - final labelStyle = cupertino - ? CupertinoTheme.of(context).textTheme.tabLabelTextStyle.copyWith( - color: CupertinoColors.secondaryLabel.resolveFrom(context), - ) - : Theme.of(context).textTheme.bodySmall?.copyWith( - color: Theme.of(context).colorScheme.onSurfaceVariant, - ); - final TextStyle valueStyle = - (cupertino - ? CupertinoTheme.of(context).textTheme.textStyle - : Theme.of(context).textTheme.bodyMedium) ?? - const TextStyle(); - return Padding( - key: const Key('run-detail-summary-facts'), - padding: const EdgeInsets.fromLTRB(16, 12, 16, 12), - child: LayoutBuilder( - builder: (context, constraints) { - const gap = 16.0; - final columns = constraints.maxWidth >= 600 ? 3 : 2; - final cell = (constraints.maxWidth - gap * (columns - 1)) / columns; - return Wrap( - spacing: gap, - runSpacing: 12, - children: [ - for (final row in rows) - SizedBox( - key: ValueKey('run-detail-summary-${_slug(row.label)}'), - width: row.monospace || row.value.length > 28 - ? constraints.maxWidth - : cell, - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text(row.label, style: labelStyle), - const SizedBox(height: 2), - cupertino - ? Text( - row.value, - style: row.monospace - ? valueStyle.copyWith( - fontFamily: appMonospaceFamily, - ) - : valueStyle, - ) - : SelectableText( - row.value, - style: row.monospace - ? valueStyle.copyWith( - fontFamily: appMonospaceFamily, - ) - : valueStyle, - ), - ], - ), - ), - ], - ); - }, - ), - ); -} - /// A long recorded block (the Diagnostic) starts collapsed under its label. Widget _materialBlock(BuildContext context, DetailSummaryRow row) { final theme = Theme.of(context); diff --git a/app/lib/features/runs/ui/run_detail_tabs.dart b/app/lib/features/runs/ui/run_detail_tabs.dart index 1daffb40..2a93435e 100644 --- a/app/lib/features/runs/ui/run_detail_tabs.dart +++ b/app/lib/features/runs/ui/run_detail_tabs.dart @@ -19,6 +19,7 @@ import 'run_detail_tab_bodies.dart'; import 'run_detail_tab_strip.dart'; import 'run_detail_timeline.dart'; import 'run_detail_visit.dart'; +import 'run_detail_wide_chrome.dart'; import 'run_detail_visit_facts.dart'; import 'run_search_selection.dart'; @@ -360,6 +361,38 @@ class _RunDetailTabsState extends State { return LayoutBuilder( builder: (context, constraints) { final headerLimit = _headerLimit(constraints); + final header = ConstrainedBox( + constraints: BoxConstraints(maxHeight: headerLimit), + child: SingleChildScrollView( + key: ValueKey('run-detail-header-${widget.run['id']}'), + child: widget.header, + ), + ); + final tabStrip = RunDetailTabStrip( + tabs: tabs, + edge: edge, + selected: shown, + onSelected: (tab) => setState(() => _tab = tab), + ); + final body = KeyedSubtree( + key: ValueKey('run-detail-body-${widget.run['id']}'), + child: _body(shown), + ); + if (edge == FloatingBarEdge.top && + constraints.maxWidth >= kRunDetailWideChromeMinWidth) { + // Beside a list the tabs and the header share one row under the + // pane's bar, so only that row (not a header strip over a tabs + // strip) sits above the tab's content. + return FloatingBarOverlay( + edge: FloatingBarEdge.top, + bar: RunDetailWideChrome( + cupertino: widget.cupertino, + tabs: tabStrip, + header: header, + ), + child: body, + ); + } // The header (status, actions, notices) is a glass strip floating // just under the top bar, so every tab scrolls behind both and pads // its first item clear of them at rest. Below it, the tabs float over @@ -374,27 +407,9 @@ class _RunDetailTabsState extends State { key: const Key('run-detail-header'), cupertino: widget.cupertino, padding: const EdgeInsets.symmetric(vertical: 4), - child: ConstrainedBox( - constraints: BoxConstraints(maxHeight: headerLimit), - child: SingleChildScrollView( - key: ValueKey('run-detail-header-${widget.run['id']}'), - child: widget.header, - ), - ), - ), - child: KeyedSubtree( - key: ValueKey('run-detail-body-${widget.run['id']}'), - child: FloatingBarOverlay( - edge: edge, - bar: RunDetailTabStrip( - tabs: tabs, - edge: edge, - selected: shown, - onSelected: (tab) => setState(() => _tab = tab), - ), - child: _body(shown), - ), + child: header, ), + child: FloatingBarOverlay(edge: edge, bar: tabStrip, child: body), ); }, ); diff --git a/app/lib/features/runs/ui/run_detail_timeline.dart b/app/lib/features/runs/ui/run_detail_timeline.dart index 779bd72c..5af8867c 100644 --- a/app/lib/features/runs/ui/run_detail_timeline.dart +++ b/app/lib/features/runs/ui/run_detail_timeline.dart @@ -1,13 +1,16 @@ -import '../../../ui/theme/app_theme.dart'; -import 'package:flutter/cupertino.dart'; -import 'package:flutter/material.dart'; +import 'package:flutter/widgets.dart'; +import '../../../ui/adaptive/floating_bar_layout.dart'; +import '../../../ui/layout/app_list_avatar.dart'; +import '../../../ui/layout/app_list_row.dart'; import '../../../ui/status/run_status_icon.dart'; import '../domain/run_models.dart'; import 'run_detail_content.dart'; -import '../../../ui/adaptive/floating_bar_layout.dart'; -/// The Timeline tab's recorded visits, one native row per visit. +/// The Timeline tab's recorded visits, one shared list row per visit. +/// +/// The list is flat on the page on both hosts, like the runs list and the +/// Summary, with inset dividers between rows (no grouped card). /// /// [onSelected] receives the row's index in [visits], so the caller opens /// exactly the recorded step it was built from. [selectedSequence] highlights a @@ -38,37 +41,25 @@ class RunTimelineList extends StatelessWidget { children: const [Text('No visits recorded.')], ); } - final rows = [ - for (var index = 0; index < visits.length; index += 1) - RunTimelineRow( - key: ValueKey( - 'run-timeline-visit-${visits[index].sequence ?? index}', - ), - visit: visits[index], - selected: visits[index].sequence == selectedSequence, - cupertino: cupertino, - onTap: onSelected == null ? null : () => onSelected!(index), - ), - ]; - if (cupertino) { - return ListView( - key: const Key('run-detail-tab-body-timeline'), - children: [ - CupertinoListSection.insetGrouped( - backgroundColor: AppColors.groupedBackground, - header: const Text('Timeline'), - children: rows, - ), - ], - ); - } return ListView( key: const Key('run-detail-tab-body-timeline'), padding: withBarClearance( context, const EdgeInsets.symmetric(vertical: 8), ), - children: rows, + children: [ + for (var index = 0; index < visits.length; index += 1) + RunTimelineRow( + key: ValueKey( + 'run-timeline-visit-${visits[index].sequence ?? index}', + ), + visit: visits[index], + selected: visits[index].sequence == selectedSequence, + cupertino: cupertino, + divider: index < visits.length - 1, + onTap: onSelected == null ? null : () => onSelected!(index), + ), + ], ); } } @@ -82,12 +73,14 @@ class RunTimelineRow extends StatelessWidget { required this.visit, required this.selected, required this.cupertino, + this.divider = false, this.onTap, }); final DetailVisit visit; final bool selected; final bool cupertino; + final bool divider; final VoidCallback? onTap; /// The visit's state for its glyph: the outcome when it has one (a completed @@ -100,12 +93,6 @@ class RunTimelineRow extends StatelessWidget { return runStateOf(visit.status); } - /// One line under the title: where the visit went and how long it took. - String get _detail => [ - if (visit.target.isNotEmpty) '→ ${visit.target}', - ?visit.duration, - ].join(' · '); - Widget _outcome(BuildContext context) { final label = visit.outcome.isNotEmpty ? visit.outcome @@ -130,48 +117,25 @@ class RunTimelineRow extends StatelessWidget { @override Widget build(BuildContext context) { - final leading = RunStatusIcon( - state: _state, - label: visit.status.isEmpty ? 'Status unavailable' : visit.status, - size: 22, - ); - final title = Text( - visit.title, - maxLines: 1, - overflow: TextOverflow.ellipsis, - ); - final detail = _detail; - // The outcome chip leads the second line, so the title keeps the width. - final subtitle = Wrap( - spacing: 8, - runSpacing: 4, - crossAxisAlignment: WrapCrossAlignment.center, - children: [_outcome(context), if (detail.isNotEmpty) Text(detail)], - ); - if (cupertino) { - return Semantics( - selected: selected, - child: CupertinoListTile( - leading: leading, - title: title, - subtitle: subtitle, - trailing: const CupertinoListTileChevron(), - backgroundColor: selected - ? CupertinoDynamicColor.resolve( - CupertinoColors.secondarySystemFill, - context, - ) - : null, - onTap: onTap, - ), - ); - } - return ListTile( + final state = _state; + // The outcome chip leads the second line, then where the visit went; the + // duration is the row's time. + return AppListRow( + cupertino: cupertino, selected: selected, - leading: leading, - title: title, - subtitle: subtitle, + divider: divider, onTap: onTap, + leading: AppListAvatar( + foreground: runStatusColor(state).resolveFrom(context), + child: RunStatusIcon( + state: state, + label: visit.status.isEmpty ? 'Status unavailable' : visit.status, + ), + ), + title: Text(visit.title), + time: visit.duration, + subtitleLeading: _outcome(context), + subtitle: visit.target.isEmpty ? null : Text('→ ${visit.target}'), ); } } diff --git a/app/lib/features/runs/ui/run_detail_visit_session.dart b/app/lib/features/runs/ui/run_detail_visit_session.dart index 5a0d8a39..632666e1 100644 --- a/app/lib/features/runs/ui/run_detail_visit_session.dart +++ b/app/lib/features/runs/ui/run_detail_visit_session.dart @@ -1,4 +1,3 @@ -import '../../../ui/theme/app_theme.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; @@ -113,25 +112,8 @@ class _RunVisitSessionState extends State { configuredEndpoint: widget.configuredEndpoint, ), ]; - if (usesCupertinoHost(context)) { - return ListView( - key: const Key('run-visit-body-session'), - children: [ - CupertinoListSection.insetGrouped( - backgroundColor: AppColors.groupedBackground, - children: [ - Padding( - padding: const EdgeInsetsDirectional.fromSTEB(16, 12, 16, 16), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: _spaced(children), - ), - ), - ], - ), - ], - ); - } + // Flat on the page on both hosts; the turn documents below are a flat + // titled list too, so nothing is a group nested in a group. return ListView( key: const Key('run-visit-body-session'), padding: withBarClearance(context, const EdgeInsets.all(16)), diff --git a/app/lib/features/runs/ui/run_detail_wide_chrome.dart b/app/lib/features/runs/ui/run_detail_wide_chrome.dart new file mode 100644 index 00000000..abc1c5da --- /dev/null +++ b/app/lib/features/runs/ui/run_detail_wide_chrome.dart @@ -0,0 +1,86 @@ +import 'package:flutter/widgets.dart'; + +import '../../../ui/adaptive/floating_bar_layout.dart'; +import '../../../ui/adaptive/floating_destination_bar.dart'; +import '../../../ui/adaptive/glass_pill.dart'; +import '../../../ui/adaptive/top_glass_strip.dart'; + +/// The narrowest detail pane that puts its tabs and header in one row; +/// narrower panes stack the header strip over the tabs. +const double kRunDetailWideChromeMinWidth = kFloatingBarWideWidth; + +/// The most of the row the tabs take, leaving the rest to the header. +const double kRunDetailWideTabsShare = 0.6; + +/// The run detail's controls beside a list (a wide split): its tabs and its +/// header (status, run actions, notices) share one row under the pane's top +/// bar, instead of stacking the header strip above a second tabs strip. +/// +/// The tabs lead, in line with the bar's title; the header follows as a glass +/// piece as wide as its content, and wraps (or scrolls inside its height +/// limit) when the pane is narrow. Float the row with `FloatingBarOverlay` +/// at the top edge so the tab body pads past it at rest. The header keeps the +/// key `run-detail-header`. +class RunDetailWideChrome extends StatelessWidget { + const RunDetailWideChrome({ + super.key, + required this.cupertino, + required this.tabs, + required this.header, + }); + + final bool cupertino; + + /// The tab strip at [FloatingBarEdge.top]; it brings its own 12px margins. + final Widget tabs; + + /// The header's content, already bounded in height. + final Widget header; + + @override + Widget build(BuildContext context) { + final insets = MediaQuery.paddingOf(context); + return Padding( + padding: EdgeInsets.only(left: insets.left), + child: LayoutBuilder( + builder: (context, constraints) => Row( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + // The tabs keep at most 60% of the row, so the header always has + // room for its status and actions (scaled text included). + ConstrainedBox( + constraints: BoxConstraints( + maxWidth: constraints.maxWidth * kRunDetailWideTabsShare, + ), + child: tabs, + ), + Flexible( + child: Padding( + // The tabs' own trailing margin is the gap before the header. + padding: EdgeInsets.only( + right: FloatingDestinationBar.topMargin + insets.right, + bottom: 8, + ), + child: Align( + alignment: AlignmentDirectional.centerStart, + heightFactor: 1, + child: GlassPill( + key: const Key('run-detail-header'), + cupertino: cupertino, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(kTopGlassStripRadius), + ), + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 4), + child: header, + ), + ), + ), + ), + ), + ], + ), + ), + ); + } +} diff --git a/app/lib/features/runs/ui/run_graph_preview.dart b/app/lib/features/runs/ui/run_graph_preview.dart index f2e30e92..ac271f6d 100644 --- a/app/lib/features/runs/ui/run_graph_preview.dart +++ b/app/lib/features/runs/ui/run_graph_preview.dart @@ -5,10 +5,14 @@ import '../../../ui/adaptive/segmented_bar.dart'; import '../../../core/api_gateway.dart'; import '../../../ui/adaptive/host.dart'; import '../../../ui/adaptive/floating_bar_layout.dart'; +import '../../graph/domain/graph_definition.dart'; import '../../graph/widgets/run_graph_view.dart'; const runGraphPreviewKey = ValueKey('run-graph-preview'); +/// The muted line shown in place of the preview when the run has no graph. +const runGraphPreviewMissingKey = ValueKey('run-graph-preview-missing'); + /// The run graph as a still picture on top of Summary. Tapping it opens the /// interactive graph full screen; picking a stage there closes it and hands /// the stage to [onStageSelected]. @@ -31,6 +35,23 @@ class RunGraphPreview extends StatelessWidget { @override Widget build(BuildContext context) { final cupertino = usesCupertinoHost(context); + // No graph to draw: one muted line, with no frame and nothing to open. + if (graphNodes(graph).isEmpty) { + return Padding( + key: runGraphPreviewMissingKey, + padding: const EdgeInsets.fromLTRB(16, 12, 16, 0), + child: Text( + runGraphMissing, + style: cupertino + ? CupertinoTheme.of(context).textTheme.textStyle.copyWith( + color: CupertinoColors.secondaryLabel.resolveFrom(context), + ) + : Theme.of(context).textTheme.bodyMedium?.copyWith( + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + ), + ); + } final border = cupertino ? CupertinoColors.separator.resolveFrom(context) : Theme.of(context).colorScheme.outlineVariant; diff --git a/app/lib/features/schedules/ui/pipeline/schedule_pipeline_list_body.dart b/app/lib/features/schedules/ui/pipeline/schedule_pipeline_list_body.dart index 55310f2c..ceef4665 100644 --- a/app/lib/features/schedules/ui/pipeline/schedule_pipeline_list_body.dart +++ b/app/lib/features/schedules/ui/pipeline/schedule_pipeline_list_body.dart @@ -1,6 +1,8 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; +import '../../../../ui/adaptive/host.dart'; +import '../../../../ui/layout/section_heading.dart'; import '../../domain/saved_schedule.dart'; import '../list/schedule_list_controller.dart'; import 'schedule_pipeline_controller.dart'; @@ -40,17 +42,7 @@ class SchedulePipelineListBody extends StatelessWidget { child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ - Padding( - padding: const EdgeInsets.fromLTRB(16, 8, 16, 4), - child: _header(context), - ), - Padding( - padding: const EdgeInsets.symmetric(horizontal: 16), - child: Text( - scheduleSectionNote, - style: schedulePipelineMutedStyle(context), - ), - ), + _header(context), if (controller.isInitialLoading) Padding( padding: const EdgeInsets.fromLTRB(16, 8, 16, 8), @@ -68,8 +60,10 @@ class SchedulePipelineListBody extends StatelessWidget { else if (controller.hasLoaded && schedules.isEmpty) Padding( padding: const EdgeInsets.fromLTRB(16, 8, 16, 8), + // The empty state also says what a schedule is, so the section + // needs no standing paragraph. child: Text( - scheduleSectionEmpty, + '$scheduleSectionEmpty $scheduleSectionNote', style: schedulePipelineMutedStyle(context), ), ), @@ -84,35 +78,36 @@ class SchedulePipelineListBody extends StatelessWidget { ); } + /// The section's quiet heading (the same as Versions and the run Summary's + /// sections) with Add as its one trailing action. There is no Refresh: + /// the section reloads after every accepted change and offers Retry when a + /// load fails. Widget _header(BuildContext context) { - return Wrap( - spacing: 12, - runSpacing: 4, - crossAxisAlignment: WrapCrossAlignment.center, - children: [ - Semantics( - header: true, - container: true, - child: Text( - controller.hasLoaded && controller.failure == null - ? '$scheduleSectionTitle (${controller.schedules.length})' - : scheduleSectionTitle, - style: schedulePipelineHeadingStyle(context), - ), - ), - schedulePipelineTextButton( - context, - key: scheduleRefreshKey, - label: scheduleRefreshLabel, - onPressed: controller.isLoading ? null : controller.refresh, - ), - schedulePipelineTextButton( - context, - key: scheduleAddKey, - label: scheduleAddLabel, - onPressed: onAdd, - ), - ], + final cupertino = usesCupertinoHost(context); + final add = cupertino + ? CupertinoButton( + key: scheduleAddKey, + padding: EdgeInsets.zero, + minimumSize: const Size.square(44), + onPressed: onAdd, + child: const Icon( + CupertinoIcons.add, + semanticLabel: scheduleAddLabel, + ), + ) + : IconButton( + key: scheduleAddKey, + tooltip: scheduleAddLabel, + onPressed: onAdd, + icon: const Icon(Icons.add), + ); + return SectionHeading( + title: controller.hasLoaded && controller.failure == null + ? '$scheduleSectionTitle (${controller.schedules.length})' + : scheduleSectionTitle, + header: true, + padding: const EdgeInsetsDirectional.only(start: 16, end: 4), + trailing: [add], ); } diff --git a/app/lib/features/schedules/ui/pipeline/schedule_pipeline_wording.dart b/app/lib/features/schedules/ui/pipeline/schedule_pipeline_wording.dart index 1abcf429..11e92d8c 100644 --- a/app/lib/features/schedules/ui/pipeline/schedule_pipeline_wording.dart +++ b/app/lib/features/schedules/ui/pipeline/schedule_pipeline_wording.dart @@ -10,7 +10,6 @@ const scheduleSectionEmpty = 'No schedules yet. Add one for each topic or recurring task.'; const scheduleSectionLoading = 'Loading schedules…'; const scheduleAddLabel = 'Add schedule'; -const scheduleRefreshLabel = 'Refresh'; const scheduleEditLabel = 'Edit'; const schedulePauseLabel = 'Pause'; const scheduleEnableLabel = 'Enable'; @@ -25,7 +24,6 @@ String scheduleDeleteTitle(String name) => 'Delete $name?'; const scheduleSectionKey = ValueKey('schedule-pipeline-section'); const scheduleAddKey = ValueKey('schedule-pipeline-add'); -const scheduleRefreshKey = ValueKey('schedule-pipeline-refresh'); const scheduleDeleteKeepKey = ValueKey('schedule-delete-keep'); const scheduleDeleteConfirmKey = ValueKey('schedule-delete-confirm'); const scheduleDeleteErrorKey = ValueKey('schedule-delete-error'); diff --git a/app/lib/ui/layout/facts_grid.dart b/app/lib/ui/layout/facts_grid.dart new file mode 100644 index 00000000..cac2a05c --- /dev/null +++ b/app/lib/ui/layout/facts_grid.dart @@ -0,0 +1,123 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../adaptive/host.dart'; +import '../text/monospace.dart'; + +/// One recorded fact of a detail Summary: a small muted label over its value. +class FactsGridItem { + const FactsGridItem({ + required this.label, + required this.value, + this.key, + this.monospace = false, + this.wide = false, + }); + + final String label; + final String value; + final Key? key; + + /// Draws the value in the monospace family (and gives it a whole line). + final bool monospace; + + /// Gives the fact a whole line even when its value is short. + final bool wide; +} + +/// A value longer than this takes a whole line so it is never squeezed. +const int kFactsGridLongValue = 28; + +/// The pane width from which the grid shows three facts per line. +const double kFactsGridThreeColumnWidth = 600; + +/// A detail Summary's facts as one compact grid on the page, the same on +/// both hosts and in every detail (run, pipeline): two facts per line on a +/// phone, three from [kFactsGridThreeColumnWidth]; a long, wide or monospace +/// value (a path, a hash) takes a whole line. +/// +/// The grid always fills its width and starts at the leading edge, so a +/// single fact is a cell at the start of the line, never a shrunk block +/// centred on the page. It draws no card or group of its own. +class FactsGrid extends StatelessWidget { + const FactsGrid({ + super.key, + required this.items, + this.padding = const EdgeInsets.fromLTRB(16, 12, 16, 12), + this.selectable = true, + this.cupertino, + }); + + final List items; + final EdgeInsetsGeometry padding; + + /// Material values are selectable text; Cupertino values stay plain text. + final bool selectable; + + /// Overrides the host detection (a feature that picks its style per + /// platform). + final bool? cupertino; + + @override + Widget build(BuildContext context) { + final cupertino = this.cupertino ?? usesCupertinoHost(context); + final labelStyle = cupertino + ? CupertinoTheme.of(context).textTheme.tabLabelTextStyle.copyWith( + color: CupertinoColors.secondaryLabel.resolveFrom(context), + ) + : Theme.of(context).textTheme.bodySmall?.copyWith( + color: Theme.of(context).colorScheme.onSurfaceVariant, + ); + final TextStyle valueStyle = + (cupertino + ? CupertinoTheme.of(context).textTheme.textStyle + : Theme.of(context).textTheme.bodyMedium) ?? + const TextStyle(); + return Padding( + padding: padding, + child: LayoutBuilder( + builder: (context, constraints) { + const gap = 16.0; + final width = constraints.maxWidth; + final columns = width >= kFactsGridThreeColumnWidth ? 3 : 2; + final cell = (width - gap * (columns - 1)) / columns; + return SizedBox( + width: width, + child: Wrap( + spacing: gap, + runSpacing: 12, + children: [ + for (final item in items) + SizedBox( + key: item.key, + width: + item.wide || + item.monospace || + item.value.length > kFactsGridLongValue + ? width + : cell, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(item.label, style: labelStyle), + const SizedBox(height: 2), + _value(item, valueStyle, cupertino), + ], + ), + ), + ], + ), + ); + }, + ), + ); + } + + Widget _value(FactsGridItem item, TextStyle base, bool cupertino) { + final style = item.monospace + ? base.copyWith(fontFamily: appMonospaceFamily) + : base; + if (cupertino || !selectable) return Text(item.value, style: style); + return SelectableText(item.value, style: style); + } +} diff --git a/app/lib/ui/layout/section_heading.dart b/app/lib/ui/layout/section_heading.dart index 3c1e2dd1..9a99ab00 100644 --- a/app/lib/ui/layout/section_heading.dart +++ b/app/lib/ui/layout/section_heading.dart @@ -24,12 +24,15 @@ class SectionHeadingStyle { static SectionHeadingStyle of(BuildContext context) { if (usesCupertinoHost(context)) { - final base = CupertinoTheme.of(context).textTheme.textStyle; + final theme = CupertinoTheme.of(context); + final base = theme.textTheme.textStyle; + // The detail pages (run, stage, pipeline) are flat on the page colour, + // as on Material, so a pinned heading's scrim is the page itself rather + // than a grey grouped band (black in dark mode). + final page = theme.scaffoldBackgroundColor; return SectionHeadingStyle( - background: CupertinoColors.systemGroupedBackground.resolveFrom( - context, - ), - body: CupertinoColors.systemGroupedBackground.resolveFrom(context), + background: page, + body: page, accent: CupertinoTheme.of(context).primaryColor, title: base.copyWith( fontSize: 13, @@ -66,6 +69,7 @@ class SectionHeading extends StatelessWidget { this.titleColor, this.padding = const EdgeInsetsDirectional.only(start: 12, end: 8), this.minHeight = 40, + this.header = false, }); final String title; @@ -75,6 +79,10 @@ class SectionHeading extends StatelessWidget { final EdgeInsetsGeometry padding; final double minHeight; + /// Announces the title as a heading to assistive tech (the trailing + /// controls stay separate nodes). + final bool header; + @override Widget build(BuildContext context) { final style = SectionHeadingStyle.of(context); @@ -86,13 +94,17 @@ class SectionHeading extends StatelessWidget { children: [ if (leading != null) ...[leading!, const SizedBox(width: 8)], Expanded( - child: Text( - title, - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: titleColor == null - ? style.title - : style.title.copyWith(color: titleColor), + child: Semantics( + header: header, + container: header, + child: Text( + title, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: titleColor == null + ? style.title + : style.title.copyWith(color: titleColor), + ), ), ), ...trailing, From 2c4c4891eab55c55cea34b3c6bfb626d9d7aeda1 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Sat, 31 Oct 2026 12:09:47 +0000 Subject: [PATCH 03/14] Keep the shell tab bar over the list pane on wide splits; cap schedules and reading bodies; share the empty-pane placeholder --- app/lib/features/chat/screen.dart | 31 +--- .../widgets/pipeline_detail_panel.dart | 27 +++- app/lib/features/runs/screen.dart | 24 +-- app/lib/features/runs/ui/run_detail_tabs.dart | 11 +- .../features/runs/ui/run_detail_visit.dart | 34 ++-- .../ui/list/schedule_list_toolbar.dart | 115 +++++++------ .../schedules/ui/list/schedule_list_view.dart | 54 +++++-- app/lib/shell/adaptive_shell.dart | 39 +++-- app/lib/shell/empty_detail_pane.dart | 49 ++++++ app/lib/shell/list_detail.dart | 52 +++++- app/lib/ui/layout/reading_width.dart | 40 +++++ app/notes/wide-shell-fixes.md | 124 ++++++++++++++ .../features/chat/chat_list_detail_test.dart | 6 +- .../pipelines/pipeline_deep_link_test.dart | 4 +- .../pipelines_screen_filter_test.dart | 2 +- .../pipelines/pipelines_screen_test.dart | 9 +- .../runs/ui/run_detail_tabs_test.dart | 7 +- .../features/runs/ui/runs_screen_test.dart | 6 + .../ui/list/schedule_screen_harness.dart | 3 +- .../ui/list/schedules_layout_test.dart | 4 +- .../ui/list/schedules_wide_test.dart | 46 ++++++ app/test/shell/empty_detail_pane_test.dart | 52 ++++++ .../shell/split_destination_bar_test.dart | 151 ++++++++++++++++++ app/test/ui/layout/reading_width_test.dart | 115 +++++++++++++ 24 files changed, 851 insertions(+), 154 deletions(-) create mode 100644 app/lib/shell/empty_detail_pane.dart create mode 100644 app/lib/ui/layout/reading_width.dart create mode 100644 app/notes/wide-shell-fixes.md create mode 100644 app/test/features/schedules/ui/list/schedules_wide_test.dart create mode 100644 app/test/shell/empty_detail_pane_test.dart create mode 100644 app/test/shell/split_destination_bar_test.dart create mode 100644 app/test/ui/layout/reading_width_test.dart diff --git a/app/lib/features/chat/screen.dart b/app/lib/features/chat/screen.dart index b8aa6b5a..c8049662 100644 --- a/app/lib/features/chat/screen.dart +++ b/app/lib/features/chat/screen.dart @@ -1,7 +1,7 @@ import '../../shell/destination.dart'; import '../../shell/detail_page.dart'; +import '../../shell/empty_detail_pane.dart'; import '../../shell/list_detail.dart'; -import '../../ui/adaptive/host.dart'; import 'dart:async'; import 'package:flutter/cupertino.dart'; @@ -257,7 +257,10 @@ class _ChatScreenState extends State { return ListDetailPanes( list: list, detail: selected == null - ? const _NoChatSelected() + ? const EmptyDetailPane( + destination: AppDestination.chat, + message: 'Select a chat to open it here.', + ) : DetailPane( key: const ValueKey('chat-detail-pane'), destination: AppDestination.chat, @@ -267,27 +270,3 @@ class _ChatScreenState extends State { ); } } - -/// The open-chat pane before any chat is chosen. -class _NoChatSelected extends StatelessWidget { - const _NoChatSelected(); - - @override - Widget build(BuildContext context) { - final cupertino = usesCupertinoHost(context); - return Center( - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - Icon( - cupertino - ? CupertinoIcons.chat_bubble_2 - : Icons.chat_bubble_outline, - ), - const SizedBox(height: 12), - const Text('Select a chat to open it here.'), - ], - ), - ); - } -} diff --git a/app/lib/features/pipelines/widgets/pipeline_detail_panel.dart b/app/lib/features/pipelines/widgets/pipeline_detail_panel.dart index e493448d..0fa4d15e 100644 --- a/app/lib/features/pipelines/widgets/pipeline_detail_panel.dart +++ b/app/lib/features/pipelines/widgets/pipeline_detail_panel.dart @@ -4,8 +4,11 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import '../../../core/api_gateway.dart'; +import '../../../shell/destination.dart'; +import '../../../shell/empty_detail_pane.dart'; import '../../../shell/shell_bar.dart'; import '../../../ui/adaptive/floating_bar_layout.dart'; +import '../../../ui/layout/reading_width.dart'; import '../../graph/domain/graph_definition.dart'; import '../../graph/widgets/stage_definition_view.dart'; import '../pipeline_models.dart'; @@ -302,16 +305,26 @@ class _PipelineDetailPanelState extends State { ); } - Widget _scrolling(Widget child) => - ListView(children: [child, const SizedBox(height: 24)]); + /// A scrolling reading body: the whole pane scrolls, the content keeps + /// [kReadingMaxWidth] from the leading edge. + Widget _scrolling(Widget child) => ListView( + children: [ + Align( + alignment: AlignmentDirectional.topStart, + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: kReadingMaxWidth), + child: child, + ), + ), + const SizedBox(height: 24), + ], + ); Widget _withoutDetail(BuildContext context) { if (!_controller.hasSelection) { - return Center( - child: Padding( - padding: const EdgeInsets.all(24), - child: Text('Select a pipeline.', style: pipelineMutedStyle(context)), - ), + return const EmptyDetailPane( + destination: AppDestination.pipelines, + message: 'Select a pipeline to open it here.', ); } return ListView( diff --git a/app/lib/features/runs/screen.dart b/app/lib/features/runs/screen.dart index 36daae71..805044a3 100644 --- a/app/lib/features/runs/screen.dart +++ b/app/lib/features/runs/screen.dart @@ -5,6 +5,7 @@ import 'package:flutter/widgets.dart'; import '../../core/api_gateway.dart'; import '../../shell/destination.dart'; import '../../shell/detail_page.dart'; +import '../../shell/empty_detail_pane.dart'; import '../../shell/list_detail.dart'; import '../../ui/adaptive/host.dart'; import '../attention/notify/notification_controller.dart'; @@ -262,15 +263,15 @@ class _RunsScreenState extends State { animation: controller, builder: (context, _) => ContentWidth( child: RunsList( - active: narrow ? !selected : true, - controller: controller, - onSelected: _select, - syncToken: widget.syncToken, - attentionStore: widget.attentionStore, - attentionNow: widget.attentionNow, - notifications: widget.notifications, - attention: widget.attention, - ), + active: narrow ? !selected : true, + controller: controller, + onSelected: _select, + syncToken: widget.syncToken, + attentionStore: widget.attentionStore, + attentionNow: widget.attentionNow, + notifications: widget.notifications, + attention: widget.attention, + ), ), ); if (narrow) return list; @@ -283,7 +284,10 @@ class _RunsScreenState extends State { implyBack: false, builder: (_) => _detail(_back), ) - : const Center(child: Text('Select a run to open it here.')), + : const EmptyDetailPane( + destination: AppDestination.runs, + message: 'Select a run to open it here.', + ), ); } } diff --git a/app/lib/features/runs/ui/run_detail_tabs.dart b/app/lib/features/runs/ui/run_detail_tabs.dart index 1daffb40..974afb4a 100644 --- a/app/lib/features/runs/ui/run_detail_tabs.dart +++ b/app/lib/features/runs/ui/run_detail_tabs.dart @@ -1,6 +1,7 @@ import '../../../ui/adaptive/floating_bar_layout.dart'; import '../../../ui/adaptive/segmented_bar.dart'; import '../../../ui/adaptive/top_glass_strip.dart'; +import '../../../ui/layout/reading_width.dart'; import 'dart:math' as math; import 'package:flutter/cupertino.dart'; @@ -392,7 +393,15 @@ class _RunDetailTabsState extends State { selected: shown, onSelected: (tab) => setState(() => _tab = tab), ), - child: _body(shown), + // Reading tabs keep a readable width on a wide window; + // canvases, viewers and the gallery keep the whole pane. + child: switch (shown) { + RunDetailTab.summary || + RunDetailTab.input || + RunDetailTab.output || + RunDetailTab.timeline => ReadingWidth(child: _body(shown)), + _ => _body(shown), + }, ), ), ); diff --git a/app/lib/features/runs/ui/run_detail_visit.dart b/app/lib/features/runs/ui/run_detail_visit.dart index 49446124..c279adbb 100644 --- a/app/lib/features/runs/ui/run_detail_visit.dart +++ b/app/lib/features/runs/ui/run_detail_visit.dart @@ -2,6 +2,7 @@ import 'package:flutter/material.dart'; import '../../../core/api_gateway.dart'; import '../../../ui/adaptive/floating_bar_layout.dart'; +import '../../../ui/layout/reading_width.dart'; import 'run_detail_content.dart'; import 'run_detail_visit_facts_view.dart'; import 'run_detail_visit_sections.dart'; @@ -72,22 +73,31 @@ class _RunVisitPaneState extends State { selected: _section, onSelected: (section) => setState(() => _section = section), ), - child: runVisitSectionBody( - section: _section, - run: widget.run, - step: widget.step, - visitIndex: widget.visitIndex, - stageKey: widget.visit.stage, - runSteps: widget.runSteps, - gateway: widget.gateway, - onRunChanged: widget.onRunChanged, - configuredEndpoint: widget.configuredEndpoint, - cupertino: widget.cupertino, - facts: RunVisitFactsView(step: widget.step), + // Reading sections keep a readable width on a wide window; the + // gallery and the changes viewer keep the whole page. + child: _capped( + runVisitSectionBody( + section: _section, + run: widget.run, + step: widget.step, + visitIndex: widget.visitIndex, + stageKey: widget.visit.stage, + runSteps: widget.runSteps, + gateway: widget.gateway, + onRunChanged: widget.onRunChanged, + configuredEndpoint: widget.configuredEndpoint, + cupertino: widget.cupertino, + facts: RunVisitFactsView(step: widget.step), + ), ), ), ); } + + Widget _capped(Widget body) => switch (_section) { + RunVisitSection.artifacts || RunVisitSection.changes => body, + _ => ReadingWidth(child: body), + }; } /// The page bar's subtitle for a recorded visit: its sequence, then the run diff --git a/app/lib/features/schedules/ui/list/schedule_list_toolbar.dart b/app/lib/features/schedules/ui/list/schedule_list_toolbar.dart index 2a4e0d9b..78a52283 100644 --- a/app/lib/features/schedules/ui/list/schedule_list_toolbar.dart +++ b/app/lib/features/schedules/ui/list/schedule_list_toolbar.dart @@ -9,6 +9,10 @@ const scheduleSearchFieldKey = ValueKey('schedule-search-field'); const scheduleFilterKey = ValueKey('schedule-filter'); const scheduleRefreshKey = ValueKey('schedule-refresh'); +/// The strip width (inside its padding) from which the field, filter and +/// count share one row. +const double kScheduleToolbarRowWidth = 520; + /// Refresh for the list, as a bar action: the platform's activity indicator /// in the same touch target while a read is in flight. class ScheduleRefreshAction extends StatelessWidget { @@ -36,9 +40,12 @@ class ScheduleRefreshAction extends StatelessWidget { ); } -/// Search and the enabled filter, and the count; the refresh control too when -/// no bar above carries it ([onRefresh] null leaves it to the bar). The list -/// floats it as a glass strip under the page's bar. +/// Search and the enabled filter, with the count as a muted label; the +/// refresh control too when no bar above carries it ([onRefresh] null leaves +/// it to the bar). The list floats it as a glass strip under the page's bar. +/// +/// On a strip at least [kScheduleToolbarRowWidth] wide everything shares one +/// row; narrower, the field takes its own row above the filter and count. class ScheduleListToolbar extends StatelessWidget { const ScheduleListToolbar({ super.key, @@ -55,57 +62,60 @@ class ScheduleListToolbar extends StatelessWidget { @override Widget build(BuildContext context) { - return Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - Padding( - padding: const EdgeInsets.fromLTRB(12, 12, 12, 8), - child: _search(context), - ), - Padding( - padding: const EdgeInsets.symmetric(horizontal: 12), - child: Row( - children: [ - Expanded( - child: Align( - alignment: AlignmentDirectional.centerStart, - child: ConstrainedBox( - constraints: const BoxConstraints(maxWidth: 480), - child: _filter(context), - ), - ), - ), - if (onRefresh case final refresh?) ...[ - const SizedBox(width: 8), - ScheduleRefreshAction( - controller: controller, - cupertino: cupertino, - onRefresh: refresh, - ), - ], - ], - ), - ), - if (controller.hasLoaded) - Padding( - padding: const EdgeInsets.fromLTRB(12, 8, 12, 0), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text(controller.countLabel, style: _metaStyle(context)), - Text( - 'Saved run configurations, not pipeline definitions.', - style: _metaStyle(context), - ), - ], + return Padding( + padding: const EdgeInsets.all(12), + child: LayoutBuilder( + builder: (context, constraints) { + final refresh = switch (onRefresh) { + final refresh? => ScheduleRefreshAction( + controller: controller, + cupertino: cupertino, + onRefresh: refresh, ), - ), - const SizedBox(height: 12), - ], + null => null, + }; + if (constraints.maxWidth >= kScheduleToolbarRowWidth) { + return Row( + children: [ + Expanded(child: _search(context)), + const SizedBox(width: 12), + _filter(context), + const SizedBox(width: 12), + Flexible(child: _count(context)), + if (refresh != null) ...[const SizedBox(width: 8), refresh], + ], + ); + } + // Narrow: the count follows the filter, and wraps under it when + // large text leaves no room beside it. + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + _search(context), + const SizedBox(height: 8), + Wrap( + spacing: 12, + runSpacing: 8, + crossAxisAlignment: WrapCrossAlignment.center, + children: [_filter(context), _count(context), ?refresh], + ), + ], + ); + }, + ), ); } + /// The count, muted; empty space until the first read lands so the + /// strip keeps its size. + Widget _count(BuildContext context) => Text( + controller.hasLoaded ? controller.countLabel : '', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: _metaStyle(context), + ); + Widget _search(BuildContext context) => AppSearchField( fieldKey: scheduleSearchFieldKey, controller: searchController, @@ -150,10 +160,11 @@ class ScheduleListToolbar extends StatelessWidget { } TextStyle? _metaStyle(BuildContext context) => cupertino - ? CupertinoTheme.of(context).textTheme.tabLabelTextStyle.copyWith( + ? CupertinoTheme.of(context).textTheme.textStyle.copyWith( + fontSize: 15, color: CupertinoColors.secondaryLabel.resolveFrom(context), ) - : Theme.of(context).textTheme.bodySmall?.copyWith( + : Theme.of(context).textTheme.bodyMedium?.copyWith( color: Theme.of(context).colorScheme.onSurfaceVariant, ); } diff --git a/app/lib/features/schedules/ui/list/schedule_list_view.dart b/app/lib/features/schedules/ui/list/schedule_list_view.dart index 435fd12b..ff376840 100644 --- a/app/lib/features/schedules/ui/list/schedule_list_view.dart +++ b/app/lib/features/schedules/ui/list/schedule_list_view.dart @@ -13,9 +13,13 @@ const scheduleListKey = ValueKey('schedule-list'); const scheduleRetryKey = ValueKey('schedule-retry'); const scheduleToolbarKey = ValueKey('schedule-toolbar'); -/// The widest the search and filter strip grows on a wide window. +/// The widest the search and filter strip grows on a wide window. The rows +/// share its width, so a row's time ends under the strip's trailing edge. const double kScheduleToolbarMaxWidth = 720; +/// The widest a row grows: the strip plus its 12px leading inset. +const double kScheduleListMaxWidth = kScheduleToolbarMaxWidth + 12; + /// Platform-adaptive list body. It owns no navigation chrome; the shell frames /// it as the Schedules destination. /// @@ -74,7 +78,12 @@ class SchedulesListView extends StatelessWidget { return BelowTopBar(child: _loadingState(context)); } if (controller.schedules.isEmpty) { - return BelowTopBar(child: _emptyState('No schedules yet.')); + return BelowTopBar( + child: _emptyState( + 'No schedules yet.', + detail: 'Saved run configurations, not pipeline definitions.', + ), + ); } final content = controller.visibleSchedules.isEmpty ? BelowTopBar(child: _emptyState(controller.emptyMessage)) @@ -100,14 +109,20 @@ class SchedulesListView extends StatelessWidget { itemCount: schedules.length, itemBuilder: (context, index) { final schedule = schedules[index]; - return ScheduleListRow( - key: ValueKey( - 'schedule-row-$index-${schedule.id ?? 'unknown'}', + return Align( + alignment: AlignmentDirectional.centerStart, + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: kScheduleListMaxWidth), + child: ScheduleListRow( + key: ValueKey( + 'schedule-row-$index-${schedule.id ?? 'unknown'}', + ), + schedule: schedule, + cupertino: cupertino, + divider: index < schedules.length - 1, + onOpen: () => onOpen(schedule), + ), ), - schedule: schedule, - cupertino: cupertino, - divider: index < schedules.length - 1, - onOpen: () => onOpen(schedule), ); }, ); @@ -132,11 +147,28 @@ class SchedulesListView extends StatelessWidget { ); } - Widget _emptyState(String message) { + Widget _emptyState(String message, {String? detail}) { return Center( child: Padding( padding: const EdgeInsets.all(24), - child: Text(message, textAlign: TextAlign.center), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text(message, textAlign: TextAlign.center), + if (detail != null) + Builder( + builder: (context) => Text( + detail, + textAlign: TextAlign.center, + style: TextStyle( + color: cupertino + ? CupertinoColors.secondaryLabel.resolveFrom(context) + : Theme.of(context).colorScheme.onSurfaceVariant, + ), + ), + ), + ], + ), ), ); } diff --git a/app/lib/shell/adaptive_shell.dart b/app/lib/shell/adaptive_shell.dart index eb03c8a7..cecaebb9 100644 --- a/app/lib/shell/adaptive_shell.dart +++ b/app/lib/shell/adaptive_shell.dart @@ -143,17 +143,26 @@ class _AdaptiveShellState extends State { // it, learning the bar's height as its bottom media padding. Neither // scaffold's structure depends on the width, so resizing never // remounts a destination. - final bar = FloatingDestinationBar( - cupertino: widget.cupertino, - currentIndex: index, - onTap: (value) => _select(AppDestination.values[value]), - items: _destinationItems(), + // + // While the tab shows its list beside an open item, the bar floats + // over the list pane only (judging its placement on that width), so + // it never covers the item or stacks on the item's own composer. + final split = _bar.split(_selected); + final bar = ListPaneWidth( + split: split, + alignment: AlignmentDirectional.bottomStart, + child: FloatingDestinationBar( + cupertino: widget.cupertino, + currentIndex: index, + onTap: (value) => _select(AppDestination.values[value]), + items: _destinationItems(), + ), ); // Destinations reach the top edge and scroll behind the floating top // bar too: each learns the bar's height as its top media padding and // pads its own lists by it (see withTopBarClearance). final topBar = _ListPaneBar( - split: _bar.split(_selected), + split: split, bar: _segmentedBar(spec, details.label), ); if (widget.cupertino) { @@ -277,19 +286,9 @@ class _ListPaneBar extends StatelessWidget bar.shouldFullyObstruct(context); @override - Widget build(BuildContext context) => LayoutBuilder( - builder: (context, constraints) { - final width = split - ? listDetailListWidth( - MediaQuery.sizeOf(context).width, - constraints.maxWidth, - ) - : constraints.maxWidth; - return Align( - alignment: AlignmentDirectional.topStart, - heightFactor: 1, - child: SizedBox(width: width, child: bar), - ); - }, + Widget build(BuildContext context) => ListPaneWidth( + split: split, + alignment: AlignmentDirectional.topStart, + child: bar, ); } diff --git a/app/lib/shell/empty_detail_pane.dart b/app/lib/shell/empty_detail_pane.dart new file mode 100644 index 00000000..935718f3 --- /dev/null +++ b/app/lib/shell/empty_detail_pane.dart @@ -0,0 +1,49 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../ui/adaptive/host.dart'; +import 'destination.dart'; + +/// The detail pane beside a list before anything is chosen: the +/// destination's own icon above one short muted line, centred. One look for +/// Runs, Chat and Pipelines. +class EmptyDetailPane extends StatelessWidget { + const EmptyDetailPane({ + super.key, + required this.destination, + required this.message, + }); + + final AppDestination destination; + final String message; + + @override + Widget build(BuildContext context) { + final cupertino = usesCupertinoHost(context); + final details = destinationDetails(destination); + final color = cupertino + ? CupertinoColors.secondaryLabel.resolveFrom(context) + : Theme.of(context).colorScheme.onSurfaceVariant; + return Center( + child: Padding( + padding: const EdgeInsets.all(24), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + cupertino ? details.cupertinoIcon : details.icon, + size: 32, + color: color, + ), + const SizedBox(height: 12), + Text( + message, + textAlign: TextAlign.center, + style: TextStyle(color: color), + ), + ], + ), + ), + ); + } +} diff --git a/app/lib/shell/list_detail.dart b/app/lib/shell/list_detail.dart index 8873294c..0add8deb 100644 --- a/app/lib/shell/list_detail.dart +++ b/app/lib/shell/list_detail.dart @@ -36,14 +36,48 @@ double listDetailBodyWidth(double window, double available) { double listDetailListWidth(double window, double available) => math.max(0, available - 1 - listDetailBodyWidth(window, available)); +/// Narrows a shell bar to the list pane while [split] (the tab shows its list +/// beside an open item), placing it at the pane's [alignment]; otherwise the +/// bar keeps the whole width it is given. The bar keeps its place in the tree +/// either way, so a split never remounts it. +class ListPaneWidth extends StatelessWidget { + const ListPaneWidth({ + super.key, + required this.split, + required this.alignment, + required this.child, + }); + + final bool split; + final AlignmentGeometry alignment; + final Widget child; + + @override + Widget build(BuildContext context) => LayoutBuilder( + builder: (context, constraints) { + final width = split + ? listDetailListWidth( + MediaQuery.sizeOf(context).width, + constraints.maxWidth, + ) + : constraints.maxWidth; + return Align( + alignment: alignment, + heightFactor: 1, + child: SizedBox(width: width, child: child), + ); + }, + ); +} + /// One body-priority policy for all destinations, derived from the full window /// and actual available space after navigation. No fixed pixel pane widths. /// -/// Under the shell, the list keeps the shell's bar (narrowed to the list pane -/// through [ShellPaneSplit]) and the open item owns the rest of the top row: -/// the detail starts at the top edge with only the system inset as its top -/// padding, and its own tabs float at its top ([PageTabsEdge]) so they never -/// stack on the shell's tab bar at the bottom. +/// Under the shell, the list keeps the shell's bars (both narrowed to the list +/// pane through [ShellPaneSplit], see [ListPaneWidth]) and the open item owns +/// the rest of the window: the detail starts at the top edge and reaches the +/// bottom edge with only the system insets as its padding, and its own tabs +/// float at its top ([PageTabsEdge]). class ListDetailPanes extends StatelessWidget { const ListDetailPanes({super.key, required this.list, required this.detail}); @@ -71,9 +105,15 @@ class ListDetailPanes extends StatelessWidget { if (split) { // Beside the list the item is not under the shell's bar: it keeps // only the system's own inset and draws its bar at the top edge. + // The shell's destination bar stays over the list pane too, so the + // item keeps only the system's bottom inset: its own composer or + // controls own the pane's bottom edge. body = MediaQuery( data: media.copyWith( - padding: media.padding.copyWith(top: media.viewPadding.top), + padding: media.padding.copyWith( + top: media.viewPadding.top, + bottom: media.viewPadding.bottom, + ), ), child: PageTabsEdge(edge: FloatingBarEdge.top, child: body), ); diff --git a/app/lib/ui/layout/reading_width.dart b/app/lib/ui/layout/reading_width.dart new file mode 100644 index 00000000..86b50800 --- /dev/null +++ b/app/lib/ui/layout/reading_width.dart @@ -0,0 +1,40 @@ +import 'dart:math' as math; + +import 'package:flutter/widgets.dart'; + +/// The widest a detail's reading body (a run or pipeline Summary, a stage +/// page's sections) grows on a wide window, so its text, trailing copy +/// buttons and facts stay within reach of the title instead of stretching +/// to the window's far edge. +const double kReadingMaxWidth = 840; + +/// Caps [child] at [maxWidth] from the leading edge, where the detail's bar +/// pieces, header strip and tabs start. It passes the full height through +/// unchanged, so a scrollable child fills the height as before; only its +/// width is capped. +class ReadingWidth extends StatelessWidget { + const ReadingWidth({ + super.key, + required this.child, + this.maxWidth = kReadingMaxWidth, + }); + + final Widget child; + final double maxWidth; + + @override + Widget build(BuildContext context) => LayoutBuilder( + // One structure at every width, so resizing across the cap never + // remounts the body (its scroll offset and open sections stay). + builder: (context, constraints) { + return Align( + alignment: AlignmentDirectional.topStart, + child: SizedBox( + width: math.min(maxWidth, constraints.maxWidth), + height: constraints.hasBoundedHeight ? constraints.maxHeight : null, + child: child, + ), + ); + }, + ); +} diff --git a/app/notes/wide-shell-fixes.md b/app/notes/wide-shell-fixes.md new file mode 100644 index 00000000..d37bd758 --- /dev/null +++ b/app/notes/wide-shell-fixes.md @@ -0,0 +1,124 @@ +# Wide shell fixes (review round 2, batches A + K) + +From the second independent review (`/tmp/app-style-review-r2/report-summary.md`): +P1-1, P2-9, P3-6 and P3-14. Follows `notes/app-chrome-fixes.md` and +`notes/floating-tab-bars.md`. + +## P1-1: the destination bar stays over the list pane + +On a wide split window the shell's `FloatingDestinationBar` was laid out over +the whole window and right-aligned, so it sat over the detail pane. There it +stacked with the chat composer (two glass pills bottom-right) and covered the +run and pipeline detail content. + +- `ListPaneWidth` (`lib/shell/list_detail.dart`) narrows a shell bar to the + list pane (`listDetailListWidth`, the split math the panes use) while the + tab is split (`ShellPaneSplit`). It is placed at the pane's leading edge. + When nothing is split it passes the whole width through. The widget tree + is the same either way, so a split never remounts the bar. +- The shell (`lib/shell/adaptive_shell.dart`) wraps both bars in it: the top + bar (`_ListPaneBar`, which used to inline the same math) and the + destination bar (bottom-start). +- The destination bar still judges its own placement on the width it is + given. At 1200 the list pane is 479 wide, so the pill spans the pane minus + 16 per side. At 1600 the pane is 639 wide, so the pill is compact and + right-aligned within the pane. It never crosses into the detail. +- `ListDetailPanes` gives the detail pane only the system bottom inset + (`viewPadding.bottom`), in addition to the top inset it already had. The + composer, or any other bottom control, owns the pane's bottom edge. The + list keeps the bar's height as its bottom padding. +- Unchanged: on phones the bar spans the full width, and on wide windows with + no split (Settings, Search, Schedules, Templates) it is compact and + right-aligned. `floating_destination_bar.dart` needed no change. + +## P2-9: Schedules on a wide window + +- The strip (`schedule_list_toolbar.dart`) now holds the field and the filter, + with the count as a muted label (Material `bodyMedium` / + `onSurfaceVariant`, Cupertino 15pt `secondaryLabel`). The helper paragraph + "Saved run configurations, not pipeline definitions." has moved to the + empty state (`No schedules yet.` keeps its own text). +- If the strip is at least `kScheduleToolbarRowWidth` (520) wide, everything + sits on one row. On narrower strips the field takes the first row, and the + filter and count wrap below it (`Wrap`, so 2x text never overflows). +- Rows are capped at `kScheduleListMaxWidth` (the strip's 720 plus its 12 + inset) from the leading edge, so a row's trailing time ends under the + strip's trailing edge. The `ListView` still spans the pane, so the whole + area scrolls. + +## P3-6: one empty-pane placeholder + +`EmptyDetailPane` (`lib/shell/empty_detail_pane.dart`) shows the destination's +own icon (`destinationDetails`, per host) above one short muted line, centred. +Runs, Chat and Pipelines all use it: + +- "Select a run to open it here." +- "Select a chat to open it here." +- "Select a pipeline to open it here." This was "Select a pipeline.", and the + tests have been updated. + +The chat screen's private `_NoChatSelected` is gone. + +## P3-14: reading width on wide windows + +`ReadingWidth` / `kReadingMaxWidth` = 840 (`lib/ui/layout/reading_width.dart`) +caps a body from the leading edge and passes the full height through. Its +structure is the same at every width, so crossing the cap never remounts the +body or loses its scroll position. + +- Run detail (`run_detail_tabs.dart`): Summary, Input, Output and Timeline + are capped. Graph, Changes and Artifacts keep the whole pane. +- Stage page (`run_detail_visit.dart`): every section except Artifacts and + Changes is capped. +- Pipeline Summary (`pipeline_detail_panel.dart` `_scrolling`): the content + inside the `ListView` is capped, so the whole pane still scrolls. + +The cap is applied around the bodies, so `run_detail_tab_bodies.dart`, +`run_detail_visit_session.dart` and `pipeline_summary_view.dart` are untouched +(other workers own them). + +## Tests + +New: + +- `test/shell/split_destination_bar_test.dart` covers both hosts: + - At 1200 and 1600 split, the pill stays within the list pane and does not + overlap the detail. The detail composer reaches the bottom edge, and the + list still clears the bar. + - At 1200 unsplit, the pill is compact at the right edge. + - At 390, the pill spans the phone. + - At 600 and 840 split with 2x text, there is no overflow. +- `test/ui/layout/reading_width_test.dart`: + - The cap applies from the leading edge, and the body is not remounted + across the cap. + - Run Summary is capped at 1200 and full width at 390 (both hosts). + - The stage page Summary is capped and its copy button sits within the cap. + - Pipeline Summary is capped. +- `test/features/schedules/ui/list/schedules_wide_test.dart`: at 1200, rows + are 732 wide, the time ends inside the strip, and the field, filter and + count are on one row with no helper line (both hosts). +- `test/shell/empty_detail_pane_test.dart`: icon above a muted line, centred, + for each destination on both hosts. + +Updated: + +- `schedules_layout_test.dart` (the helper is no longer in the strip). +- `schedule_screen_harness.dart` (`size:`). +- The pipelines tests (placeholder wording). +- `chat_list_detail_test.dart`, `pipelines_screen_test.dart` and + `runs_screen_test.dart` now assert `EmptyDetailPane`. + +## Evidence + +Captures are in `/tmp/r3-a-evidence/`. They were taken with headless Chrome +using the reviewer's `/tmp/app-style-review-r2/shoot.mjs` over a web build of +`tool/app_host_probe_entry.dart` (`build/r3-app_host`): + +- Runs fixture: runs, run1, stage, chat, thread (`RICH=1`), schedules and + settings at 560, 1200 and 1600, Material and Cupertino, light, with dark at + 1200 and 1600 for run1, stage, thread and schedules. +- Pipelines fixture: plist and pdetail. + +The specs are in `/tmp/r3-a-evidence/scripts/`. + +Known gaps: there was no device run, so Android and iOS are unverified. diff --git a/app/test/features/chat/chat_list_detail_test.dart b/app/test/features/chat/chat_list_detail_test.dart index 523f2841..aab05934 100644 --- a/app/test/features/chat/chat_list_detail_test.dart +++ b/app/test/features/chat/chat_list_detail_test.dart @@ -1,5 +1,6 @@ import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/shell/empty_detail_pane.dart'; import 'package:pipelines_app/ui/layout/app_list_row.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:pipelines_app/ui/adaptive/floating_destination_bar.dart'; @@ -52,7 +53,10 @@ void main() { testWidgets('a wide window keeps the tab bar and list beside the open chat ' 'at $size', (tester) async { await _pumpShell(tester, size); - expect(find.text('Select a chat to open it here.'), findsOneWidget); + expect( + find.widgetWithText(EmptyDetailPane, 'Select a chat to open it here.'), + findsOneWidget, + ); expect( tester.widget(find.byKey(const Key('chat-row-a'))).selected, isFalse, diff --git a/app/test/features/pipelines/pipeline_deep_link_test.dart b/app/test/features/pipelines/pipeline_deep_link_test.dart index 5f3017bd..2fe1bcd7 100644 --- a/app/test/features/pipelines/pipeline_deep_link_test.dart +++ b/app/test/features/pipelines/pipeline_deep_link_test.dart @@ -112,9 +112,9 @@ void main() { await _pumpPipelines(tester, gateway: gateway, pipelineId: 1, version: 2); - // The detail is open (not the "Select a pipeline." placeholder), and the + // The detail is open (not the "Select a pipeline to open it here." placeholder), and the // detail request names the route's pinned version. - expect(find.text('Select a pipeline.'), findsNothing); + expect(find.text('Select a pipeline to open it here.'), findsNothing); expect(find.text('Alpha review'), findsWidgets); expect( gateway diff --git a/app/test/features/pipelines/pipelines_screen_filter_test.dart b/app/test/features/pipelines/pipelines_screen_filter_test.dart index e9dccc19..4233d6f8 100644 --- a/app/test/features/pipelines/pipelines_screen_filter_test.dart +++ b/app/test/features/pipelines/pipelines_screen_filter_test.dart @@ -116,7 +116,7 @@ void main() { expect(find.text('pipeline 2 was not found'), findsOneWidget); expect(find.text('Retry'), findsOneWidget); - expect(find.text('Select a pipeline.'), findsNothing); + expect(find.text('Select a pipeline to open it here.'), findsNothing); }); testWidgets('the list switches between all and scheduled pipelines', ( diff --git a/app/test/features/pipelines/pipelines_screen_test.dart b/app/test/features/pipelines/pipelines_screen_test.dart index cb8a146b..c5c92354 100644 --- a/app/test/features/pipelines/pipelines_screen_test.dart +++ b/app/test/features/pipelines/pipelines_screen_test.dart @@ -2,6 +2,7 @@ import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/shell/empty_detail_pane.dart'; import 'package:pipelines_app/ui/layout/app_list_row.dart'; import 'package:pipelines_app/features/pipelines/ui/run_pipeline_wording.dart'; import 'package:pipelines_app/core/api_gateway.dart'; @@ -25,7 +26,13 @@ void main() { expect(find.textContaining('run 42'), findsNothing); // A pipeline that never ran shows its summary alone, with no status dot. expect(find.text('no runs recorded'), findsNothing); - expect(find.text('Select a pipeline.'), findsOneWidget); + expect( + find.widgetWithText( + EmptyDetailPane, + 'Select a pipeline to open it here.', + ), + findsOneWidget, + ); await tester.tap(find.byKey(const Key('pipeline-row-1'))); await tester.pumpAndSettle(); diff --git a/app/test/features/runs/ui/run_detail_tabs_test.dart b/app/test/features/runs/ui/run_detail_tabs_test.dart index 454840e5..cfd0734e 100644 --- a/app/test/features/runs/ui/run_detail_tabs_test.dart +++ b/app/test/features/runs/ui/run_detail_tabs_test.dart @@ -1,5 +1,6 @@ import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/ui/layout/reading_width.dart'; import 'package:pipelines_app/features/runs/ui/run_graph_preview.dart'; import 'package:pipelines_app/features/runs/ui/run_more_menu.dart'; import 'package:pipelines_app/features/graph/widgets/run_graph_view.dart'; @@ -113,8 +114,10 @@ void main() { expect(widePill.right, 1000 - 16); expect(widePill.bottom, 844 - 16); expect(widePill.width, lessThan(1000 * 0.6)); - // Beside the bar the content takes taps: the body spans the width. - expect(tester.getRect(body).width, 1000); + // Beside the bar the content takes taps: the body spans the reading + // width from the leading edge (Summary is capped on a wide pane). + expect(tester.getRect(body).left, 0); + expect(tester.getRect(body).width, kReadingMaxWidth); }); testWidgets('${platform.name} missing graph states the exact wording', ( diff --git a/app/test/features/runs/ui/runs_screen_test.dart b/app/test/features/runs/ui/runs_screen_test.dart index 46873a54..9761a61f 100644 --- a/app/test/features/runs/ui/runs_screen_test.dart +++ b/app/test/features/runs/ui/runs_screen_test.dart @@ -8,6 +8,7 @@ import 'package:pipelines_app/core/api_gateway.dart'; import 'package:pipelines_app/features/runs/screen.dart'; import 'package:pipelines_app/features/runs/ui/run_detail_view.dart'; import 'run_detail_finders.dart'; +import 'package:pipelines_app/shell/empty_detail_pane.dart'; import 'package:pipelines_app/ui/adaptive/segmented_bar.dart'; class _Gateway implements ApiGateway { @@ -154,6 +155,11 @@ void main() { ) async { await tester.pumpWidget(_materialScreen(gateway)); await _mountList(tester, gateway); + // Beside the list, nothing open yet: the shared empty-pane placeholder. + expect( + find.widgetWithText(EmptyDetailPane, 'Select a run to open it here.'), + findsOneWidget, + ); await tester.tap(find.text('Beta run')); await tester.pump(); diff --git a/app/test/features/schedules/ui/list/schedule_screen_harness.dart b/app/test/features/schedules/ui/list/schedule_screen_harness.dart index 607e90bb..963078f3 100644 --- a/app/test/features/schedules/ui/list/schedule_screen_harness.dart +++ b/app/test/features/schedules/ui/list/schedule_screen_harness.dart @@ -13,8 +13,9 @@ Future pumpSchedules( ValueChanged? onOpen, double textScale = 1, bool settle = true, + Size size = const Size(390, 844), }) async { - tester.view.physicalSize = const Size(390, 844); + tester.view.physicalSize = size; tester.view.devicePixelRatio = 1; addTearDown(tester.view.resetPhysicalSize); addTearDown(tester.view.resetDevicePixelRatio); diff --git a/app/test/features/schedules/ui/list/schedules_layout_test.dart b/app/test/features/schedules/ui/list/schedules_layout_test.dart index ad53a690..878b6b79 100644 --- a/app/test/features/schedules/ui/list/schedules_layout_test.dart +++ b/app/test/features/schedules/ui/list/schedules_layout_test.dart @@ -29,7 +29,9 @@ void main() { ); expect(find.text('2 schedules'), findsOneWidget); - expect(find.textContaining('not pipeline definitions'), findsOneWidget); + // The strip carries the count only; the helper line lives in the + // empty state. + expect(find.textContaining('not pipeline definitions'), findsNothing); // Two lines per row: the name with its next run, then the timer // and pinned pipeline version. The editor holds the rest. expect(find.text('Research batteries'), findsOneWidget); diff --git a/app/test/features/schedules/ui/list/schedules_wide_test.dart b/app/test/features/schedules/ui/list/schedules_wide_test.dart new file mode 100644 index 00000000..e0dfcb2e --- /dev/null +++ b/app/test/features/schedules/ui/list/schedules_wide_test.dart @@ -0,0 +1,46 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/schedules/ui/list/schedule_list_toolbar.dart'; +import 'package:pipelines_app/features/schedules/ui/list/schedule_list_view.dart'; +import 'package:pipelines_app/ui/layout/app_list_row.dart'; + +import 'schedule_list_test_support.dart'; +import 'schedule_screen_harness.dart'; + +/// On a wide window the rows share the toolbar strip's width, and the strip +/// is one row: the field, the filter and the count as a muted label. +void main() { + for (final cupertino in [false, true]) { + final host = cupertino ? 'Cupertino' : 'Material'; + + testWidgets('$host 1200: rows end under the strip and the strip is one ' + 'row', (tester) async { + await pumpSchedules( + tester, + cupertino: cupertino, + size: const Size(1200, 800), + gateway: FakeSchedulesGateway( + (type, fields) async => schedulesReply([ + scheduleRecord(nextDue: '2026-10-22T09:00:00'), + pausedRecord(), + ]), + ), + ); + final strip = tester.getRect(find.byKey(scheduleToolbarKey)); + final row = tester.getRect(find.byKey(appListRowSurfaceKey).first); + expect(row.left, 0); + expect(row.width, kScheduleListMaxWidth); + // The row's trailing time ends inside the strip's trailing edge. + final time = tester.getRect(find.text('22 Oct 09:00')); + expect(time.right, lessThanOrEqualTo(strip.right - 12 + 0.5)); + + // Field, filter and count on one line. + final field = tester.getRect(find.byKey(scheduleSearchFieldKey)); + final filter = tester.getRect(find.byKey(scheduleFilterKey)); + final count = tester.getRect(find.text('2 schedules')); + expect((field.center.dy - filter.center.dy).abs(), lessThan(4)); + expect((count.center.dy - filter.center.dy).abs(), lessThan(4)); + expect(find.textContaining('not pipeline definitions'), findsNothing); + }); + } +} diff --git a/app/test/shell/empty_detail_pane_test.dart b/app/test/shell/empty_detail_pane_test.dart new file mode 100644 index 00000000..81f5eedc --- /dev/null +++ b/app/test/shell/empty_detail_pane_test.dart @@ -0,0 +1,52 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/shell/destination.dart'; +import 'package:pipelines_app/shell/empty_detail_pane.dart'; + +/// One placeholder for an empty detail pane: the destination's icon above a +/// short muted line, centred, on both hosts. +void main() { + for (final cupertino in [false, true]) { + final host = cupertino ? 'Cupertino' : 'Material'; + for (final destination in [ + AppDestination.runs, + AppDestination.chat, + AppDestination.pipelines, + ]) { + testWidgets('$host ${destination.name}: icon over a muted line', ( + tester, + ) async { + final content = EmptyDetailPane( + destination: destination, + message: 'Select one to open it here.', + ); + await tester.pumpWidget( + cupertino + ? CupertinoApp(home: CupertinoPageScaffold(child: content)) + : MaterialApp(home: Scaffold(body: content)), + ); + final details = destinationDetails(destination); + final icon = find.byIcon( + cupertino ? details.cupertinoIcon : details.icon, + ); + expect(icon, findsOneWidget); + final text = find.text('Select one to open it here.'); + expect( + tester.getTopLeft(text).dy, + greaterThan(tester.getRect(icon).bottom), + ); + // Centred in the pane. + final size = tester.view.physicalSize / tester.view.devicePixelRatio; + expect(tester.getCenter(text).dx, closeTo(size.width / 2, 1)); + // Muted: the same secondary colour on the icon and the line. + final context = tester.element(text); + final muted = cupertino + ? CupertinoColors.secondaryLabel.resolveFrom(context) + : Theme.of(context).colorScheme.onSurfaceVariant; + expect(tester.widget(icon).color, muted); + expect(tester.widget(text).style?.color, muted); + }); + } + } +} diff --git a/app/test/shell/split_destination_bar_test.dart b/app/test/shell/split_destination_bar_test.dart new file mode 100644 index 00000000..77efc529 --- /dev/null +++ b/app/test/shell/split_destination_bar_test.dart @@ -0,0 +1,151 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/shell/adaptive_shell.dart'; +import 'package:pipelines_app/shell/destination.dart'; +import 'package:pipelines_app/shell/list_detail.dart'; +import 'package:pipelines_app/ui/adaptive/floating_bar_layout.dart'; +import 'package:pipelines_app/ui/adaptive/glass_pill.dart'; + +/// While a tab shows its list beside an open item, the shell's destination +/// bar floats over the list pane only: it never covers the item, and the +/// item's own bottom control (a composer) owns the pane's bottom edge. +void main() { + Future setSize(WidgetTester tester, Size size) async { + tester.view.physicalSize = size; + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + } + + /// A detail whose composer sits at the bottom, padded by the media inset + /// the way the chat composer is. + Widget composerDetail() => Builder( + builder: (context) => Align( + alignment: Alignment.bottomCenter, + child: Padding( + padding: EdgeInsets.only(bottom: MediaQuery.paddingOf(context).bottom), + child: const SizedBox( + key: Key('composer'), + height: 56, + width: double.infinity, + ), + ), + ), + ); + + Widget listBody() => Builder( + builder: (context) => ListView( + key: const Key('list'), + children: [ + for (var index = 0; index < 40; index++) + SizedBox(height: 40, child: Text('row $index')), + ], + ), + ); + + Widget shell({ + required bool cupertino, + bool split = true, + double textScale = 1, + }) { + final app = AdaptiveShell( + cupertino: cupertino, + destination: AppDestination.chat, + destinationBodies: { + AppDestination.chat: (_) => split + ? ListDetailPanes(list: listBody(), detail: composerDetail()) + : listBody(), + }, + ); + return MediaQuery( + data: MediaQueryData.fromView( + WidgetsBinding.instance.platformDispatcher.views.first, + ).copyWith(textScaler: TextScaler.linear(textScale)), + child: cupertino ? CupertinoApp(home: app) : MaterialApp(home: app), + ); + } + + Rect destinationPill(WidgetTester tester) => tester.getRect( + find + .ancestor( + of: find.byKey(const ValueKey('shell.destination.chat')).first, + matching: find.byType(GlassPill), + ) + .first, + ); + + for (final cupertino in [false, true]) { + final host = cupertino ? 'Cupertino' : 'Material'; + + for (final width in [1200.0, 1600.0]) { + testWidgets('$host $width split: the destination bar stays over the ' + 'list pane and the composer owns the detail bottom', (tester) async { + await setSize(tester, Size(width, 800)); + await tester.pumpWidget(shell(cupertino: cupertino)); + await tester.pump(); + await tester.pump(); + + final list = tester.getRect( + find.byKey(const ValueKey('list-detail-list')), + ); + final body = tester.getRect( + find.byKey(const ValueKey('list-detail-body')), + ); + final pill = destinationPill(tester); + expect(pill.right, lessThanOrEqualTo(list.right)); + expect(pill.left, greaterThanOrEqualTo(list.left)); + expect(pill.overlaps(body), isFalse, reason: 'no overlap with detail'); + expect(pill.bottom, closeTo(800 - kFloatingBarMargin, 0.5)); + + // The detail keeps only the system inset (none here): its composer + // reaches the bottom edge, below the level of the shell's pill. + final composer = tester.getRect(find.byKey(const Key('composer'))); + expect(composer.bottom, 800); + expect(composer.left, body.left); + expect(composer.top, greaterThan(pill.top)); + + // The list still clears the bar. + final listContext = tester.element(find.byKey(const Key('list'))); + expect( + MediaQuery.paddingOf(listContext).bottom, + greaterThanOrEqualTo(pill.height), + ); + }); + } + + testWidgets('$host 1200 unsplit: the bar is compact at the right edge', ( + tester, + ) async { + await setSize(tester, const Size(1200, 800)); + await tester.pumpWidget(shell(cupertino: cupertino, split: false)); + await tester.pump(); + final pill = destinationPill(tester); + expect(pill.right, closeTo(1200 - kFloatingBarMargin, 0.5)); + expect(pill.width, lessThan(1200 * 0.6)); + }); + + testWidgets('$host 390: the bar spans the phone', (tester) async { + await setSize(tester, const Size(390, 844)); + await tester.pumpWidget(shell(cupertino: cupertino, split: false)); + await tester.pump(); + final pill = destinationPill(tester); + expect(pill.left, closeTo(kFloatingBarMargin, 0.5)); + expect(pill.right, closeTo(390 - kFloatingBarMargin, 0.5)); + }); + + for (final width in [600.0, 840.0]) { + testWidgets('$host $width split at 2x: the narrow list pane bar lays ' + 'out without overflow', (tester) async { + await setSize(tester, Size(width, 800)); + await tester.pumpWidget(shell(cupertino: cupertino, textScale: 2)); + await tester.pump(); + await tester.pump(); + expect(tester.takeException(), isNull); + final list = tester.getRect( + find.byKey(const ValueKey('list-detail-list')), + ); + expect(destinationPill(tester).right, lessThanOrEqualTo(list.right)); + }); + } + } +} diff --git a/app/test/ui/layout/reading_width_test.dart b/app/test/ui/layout/reading_width_test.dart new file mode 100644 index 00000000..7de8aa78 --- /dev/null +++ b/app/test/ui/layout/reading_width_test.dart @@ -0,0 +1,115 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/pipelines/pipeline_repository.dart'; +import 'package:pipelines_app/features/pipelines/pipelines_controller.dart'; +import 'package:pipelines_app/features/pipelines/widgets/pipeline_detail_panel.dart'; +import 'package:pipelines_app/features/pipelines/widgets/pipeline_summary_view.dart'; +import 'package:pipelines_app/ui/layout/reading_width.dart'; + +import '../../features/pipelines/fixtures.dart'; +import '../../features/pipelines/test_helpers.dart'; +import '../../features/runs/ui/run_detail_graph_support.dart'; +import '../../features/runs/ui/run_detail_visit_support.dart'; + +/// Reading bodies (run Summary, stage page sections, pipeline Summary) keep +/// [kReadingMaxWidth] from the leading edge on a wide window and the full +/// width on a phone. +void main() { + Future setSize(WidgetTester tester, Size size) async { + tester.view.physicalSize = size; + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + } + + testWidgets('ReadingWidth caps from the leading edge and keeps its child ' + 'across the cap', (tester) async { + await setSize(tester, const Size(1200, 600)); + final scroll = ScrollController(); + addTearDown(scroll.dispose); + await tester.pumpWidget( + MaterialApp( + home: ReadingWidth( + child: ListView( + key: const Key('body'), + controller: scroll, + children: [ + for (var index = 0; index < 50; index++) + SizedBox(height: 40, child: Text('row $index')), + ], + ), + ), + ), + ); + final wide = tester.getRect(find.byKey(const Key('body'))); + expect(wide.left, 0); + expect(wide.width, kReadingMaxWidth); + expect(wide.height, 600); + scroll.jumpTo(300); + await tester.pump(); + + await setSize(tester, const Size(500, 600)); + await tester.pump(); + expect(tester.getRect(find.byKey(const Key('body'))).width, 500); + expect(scroll.offset, 300, reason: 'the body was not remounted'); + }); + + for (final platform in RunDetailTestPlatform.values) { + testWidgets('${platform.name} 1200: run Summary is capped', (tester) async { + await pumpRunDetail(tester, platform, size: const Size(1200, 800)); + final body = tester.getRect( + find.byKey(const Key('run-detail-tab-body-summary')), + ); + expect(body.left, 0); + expect(body.width, kReadingMaxWidth); + }); + + testWidgets('${platform.name} 390: run Summary keeps the full width', ( + tester, + ) async { + await pumpRunDetail(tester, platform, size: const Size(390, 844)); + final body = tester.getRect( + find.byKey(const Key('run-detail-tab-body-summary')), + ); + expect(body.width, 390); + }); + + testWidgets('${platform.name} 1200: stage page Summary is capped', ( + tester, + ) async { + await openVisit(tester, platform, size: const Size(1200, 900)); + final body = tester.getRect( + find.byKey(const Key('run-visit-body-summary')), + ); + expect(body.left, 0); + expect(body.width, kReadingMaxWidth); + // The section's trailing copy button sits within the cap. + final copy = find.byKey(const ValueKey('run-visit-copy-Input')); + expect(tester.getRect(copy).right, lessThanOrEqualTo(kReadingMaxWidth)); + }); + } + + testWidgets('1200: pipeline Summary is capped, the pane still scrolls', ( + tester, + ) async { + await setSize(tester, const Size(1200, 800)); + final gateway = gatewayFor(PipelineFixture()); + final controller = PipelinesController(PipelinesRepository(gateway)); + addTearDown(controller.dispose); + await controller.openPipeline(1); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: PipelineDetailPanel( + controller: controller, + gateway: gateway, + showBack: false, + ), + ), + ), + ); + await tester.pumpAndSettle(); + final summary = tester.getRect(find.byType(PipelineSummaryView)); + expect(summary.left, 0); + expect(summary.width, kReadingMaxWidth); + }); +} From e43cc867f998ba85214f8a8dc03da0a98218c3b5 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Sat, 31 Oct 2026 12:13:34 +0000 Subject: [PATCH 04/14] Sheets, decision options, usage, settings and artifact errors: review r2 batches H and L Shared AppSheetHeader (title + Done) for the Runs filter/sort and Needs you sheets; Runs filter single-choice groups as check rows and statuses in sentence case; Cupertino decision options as a check list; run action sheet titled with the run; usage page without the duplicate title and with honest empty states; Settings Reconnect wording, compact notifications row and a tinted Cupertino Save workspace; friendly artifact preview failures with Retry. --- .../domain/artifact_preview_failure.dart | 22 ++ .../artifacts/ui/artifact_viewer_body.dart | 5 + .../artifacts/ui/artifact_viewer_content.dart | 38 ++- .../artifacts/ui/artifact_viewer_page.dart | 9 +- .../attention/notify/notification_models.dart | 41 +++ .../features/attention/ui/needs_you_copy.dart | 1 - .../features/attention/ui/needs_you_keys.dart | 3 + .../ui/needs_you_sheet_cupertino.dart | 26 +- .../ui/needs_you_sheet_material.dart | 33 +-- .../ui/notification_permission_tile.dart | 76 +++-- .../runs/actions/decision_dialog.dart | 48 +-- .../runs/actions/decision_option_row.dart | 109 +++++++ app/lib/features/runs/ui/run_more_menu.dart | 10 + .../features/runs/ui/runs_filter_options.dart | 61 ++++ .../features/runs/ui/runs_filter_sheet.dart | 215 ++++++++++++++ app/lib/features/runs/ui/runs_filters.dart | 275 +++--------------- app/lib/features/runs/ui/runs_stats_page.dart | 155 ++++++---- .../settings/settings_controller.dart | 5 +- .../features/settings/settings_sections.dart | 7 +- app/lib/ui/layout/app_sheet_header.dart | 106 +++++++ .../domain/artifact_preview_failure_test.dart | 27 ++ .../ui/artifact_viewer_page_test.dart | 46 ++- .../notification_manager_wiring_test.dart | 16 +- .../ui/notification_permission_tile_test.dart | 31 +- .../runs/actions/decision_action_test.dart | 25 ++ .../features/runs/ui/run_list_row_test.dart | 11 +- .../features/runs/ui/runs_sheets_test.dart | 188 ++++++++++++ .../features/runs/ui/runs_toolbar_test.dart | 32 +- .../settings/settings_screen_test.dart | 9 + 29 files changed, 1198 insertions(+), 432 deletions(-) create mode 100644 app/lib/features/artifacts/domain/artifact_preview_failure.dart create mode 100644 app/lib/features/runs/actions/decision_option_row.dart create mode 100644 app/lib/features/runs/ui/runs_filter_options.dart create mode 100644 app/lib/features/runs/ui/runs_filter_sheet.dart create mode 100644 app/lib/ui/layout/app_sheet_header.dart create mode 100644 app/test/features/artifacts/domain/artifact_preview_failure_test.dart create mode 100644 app/test/features/runs/ui/runs_sheets_test.dart diff --git a/app/lib/features/artifacts/domain/artifact_preview_failure.dart b/app/lib/features/artifacts/domain/artifact_preview_failure.dart new file mode 100644 index 00000000..ea8d44db --- /dev/null +++ b/app/lib/features/artifacts/domain/artifact_preview_failure.dart @@ -0,0 +1,22 @@ +/// The viewer's words for a preview that could not be fetched. +/// +/// The operator sees what happened in plain language and can retry; the raw +/// exception text (`TypeError: Failed to fetch`) and bare status lines +/// (`The server answered 404.`) never reach the screen. [status] is the HTTP +/// status the server answered, or null when no answer arrived at all. +String artifactPreviewFailureMessage({int? status}) { + if (status == null) { + return 'The preview could not be loaded. Check the connection and try ' + 'again.'; + } + if (status == 404 || status == 410) { + return 'This file is no longer on the server.'; + } + if (status == 401 || status == 403) { + return 'The server did not allow this file to be opened.'; + } + if (status >= 500) { + return 'The server could not send this file right now.'; + } + return 'The preview could not be loaded (status $status).'; +} diff --git a/app/lib/features/artifacts/ui/artifact_viewer_body.dart b/app/lib/features/artifacts/ui/artifact_viewer_body.dart index b6c5bbbf..2d962a15 100644 --- a/app/lib/features/artifacts/ui/artifact_viewer_body.dart +++ b/app/lib/features/artifacts/ui/artifact_viewer_body.dart @@ -41,8 +41,12 @@ class ArtifactViewerBody extends StatelessWidget { this.bytes, this.error, this.status, + this.onRetry, }); + /// Loads the current page's preview again after a failure. + final VoidCallback? onRetry; + final PagedArtifact page; final ArtifactPreviewPlan plan; final int index; @@ -76,6 +80,7 @@ class ArtifactViewerBody extends StatelessWidget { text: text, bytes: bytes, error: error, + onRetry: onRetry, ), ), ], diff --git a/app/lib/features/artifacts/ui/artifact_viewer_content.dart b/app/lib/features/artifacts/ui/artifact_viewer_content.dart index 3b0f28b1..af00d828 100644 --- a/app/lib/features/artifacts/ui/artifact_viewer_content.dart +++ b/app/lib/features/artifacts/ui/artifact_viewer_content.dart @@ -1,7 +1,10 @@ import 'dart:typed_data'; +import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; +import '../../../ui/adaptive/host.dart'; + import '../domain/artifact_preview.dart'; import 'artifact_html_view.dart'; import 'artifact_table_view.dart'; @@ -35,8 +38,12 @@ class ArtifactPreviewBody extends StatelessWidget { this.error, this.videoControllerFactory = defaultArtifactVideoController, this.htmlBuilder = defaultArtifactHtml, + this.onRetry, }); + /// Offered under a fetch failure; absent, the message stands alone. + final VoidCallback? onRetry; + final ArtifactPreviewPlan plan; final bool loading; final ArtifactMarkdownBuilder markdownBuilder; @@ -60,7 +67,7 @@ class ArtifactPreviewBody extends StatelessWidget { return const _Loading(); } if (error != null) { - return _Message(error!); + return _Message(error!, onRetry: onRetry); } switch (plan.kind) { case ArtifactPreviewKind.image: @@ -201,17 +208,42 @@ class _PreviewPadding extends StatelessWidget { } } +const artifactPreviewRetryKey = Key('artifact-preview-retry'); + class _Message extends StatelessWidget { - const _Message(this.message); + const _Message(this.message, {this.onRetry}); final String message; + final VoidCallback? onRetry; @override Widget build(BuildContext context) { + final retry = onRetry; + final cupertino = usesCupertinoHost(context); return Center( child: Padding( padding: const EdgeInsets.all(16), - child: Text(message, textAlign: TextAlign.center), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text(message, textAlign: TextAlign.center), + if (retry != null) ...[ + const SizedBox(height: 12), + cupertino + ? CupertinoButton.tinted( + key: artifactPreviewRetryKey, + sizeStyle: CupertinoButtonSize.small, + onPressed: retry, + child: const Text('Retry'), + ) + : FilledButton.tonal( + key: artifactPreviewRetryKey, + onPressed: retry, + child: const Text('Retry'), + ), + ], + ], + ), ), ); } diff --git a/app/lib/features/artifacts/ui/artifact_viewer_page.dart b/app/lib/features/artifacts/ui/artifact_viewer_page.dart index 1638b146..049b8a4a 100644 --- a/app/lib/features/artifacts/ui/artifact_viewer_page.dart +++ b/app/lib/features/artifacts/ui/artifact_viewer_page.dart @@ -12,6 +12,7 @@ import 'artifact_selection_facts.dart'; import '../actions/artifact_file_bridge.dart'; import '../domain/artifact_groups.dart'; import '../domain/artifact_preview.dart'; +import '../domain/artifact_preview_failure.dart'; import '../domain/artifact_url.dart'; import '../domain/gallery_navigation.dart'; import 'artifact_external_open.dart'; @@ -157,7 +158,7 @@ class _ArtifactViewerPageState extends State { if (!result.ok) { setState(() { _loading = false; - _error = 'The server answered ${result.status}.'; + _error = artifactPreviewFailureMessage(status: result.status); }); return; } @@ -168,11 +169,11 @@ class _ArtifactViewerPageState extends State { _fetched = fetched; }); }, - onError: (Object error) { + onError: (Object _) { if (!mounted || generation != _generation) return; setState(() { _loading = false; - _error = 'Could not load preview: $error'; + _error = artifactPreviewFailureMessage(); }); }, ); @@ -259,6 +260,8 @@ class _ArtifactViewerPageState extends State { fileBridge: widget.fileBridge, onPrevious: () => _step(-1), onNext: () => _step(1), + // A failure is never cached, so loading again fetches afresh. + onRetry: _beginLoad, onOpen: plan.resolved == null ? () {} : () => _open(plan.resolved!), onCopy: plan.resolved == null ? () {} : () => _copy(plan.resolved!), ); diff --git a/app/lib/features/attention/notify/notification_models.dart b/app/lib/features/attention/notify/notification_models.dart index a3d5af33..224ad0c0 100644 --- a/app/lib/features/attention/notify/notification_models.dart +++ b/app/lib/features/attention/notify/notification_models.dart @@ -67,6 +67,9 @@ const notificationRationale = const notificationSectionTitle = 'Notifications'; const notificationRequestLabel = 'Enable notifications'; +/// The compact row's visible action; [notificationRequestLabel] is its name. +const notificationEnableShortLabel = 'Enable'; + /// The honest wording for every state, verbatim from `web/src/notify.js`; each /// says plainly that the in-app `Needs you` surface is the only channel when the /// platform cannot notify. @@ -100,13 +103,21 @@ class NotificationPermissionView { const NotificationPermissionView({ required this.state, required this.body, + required this.headline, + required this.helper, required this.canRequest, required this.actionLabel, required this.asked, }); final NotificationPermissionState state; + + /// The browser's full sentence for the state (read out with the row). final String body; + + /// The compact Settings row: a short state line and one short helper. + final String headline; + final String helper; final bool canRequest; final String? actionLabel; final bool asked; @@ -126,9 +137,39 @@ NotificationPermissionView notificationPermissionView( NotificationPermissionState.notRequested => asked ? notificationDefaultAskedCopy : notificationDefaultCopy, }; + final (headline, helper) = switch (state) { + NotificationPermissionState.unsupported => ( + 'Not supported in this browser', + 'Runs that need you still appear in Needs you.', + ), + NotificationPermissionState.needsSecureContext => ( + 'Needs a secure page', + 'Open the app over https or localhost to turn them on.', + ), + NotificationPermissionState.granted => ( + 'Alerts are on', + 'Failed and waiting runs raise a notification.', + ), + NotificationPermissionState.denied => ( + 'Blocked by the browser', + 'Allow them in the site settings; Needs you still works.', + ), + NotificationPermissionState.notRequested => + asked + ? ( + 'Alerts are still off', + 'Permission was not granted. Ask again, or use Needs you.', + ) + : ( + 'Alerts are off', + 'Get told when a run fails or needs your decision.', + ), + }; return NotificationPermissionView( state: state, body: body, + headline: headline, + helper: helper, canRequest: canRequest, actionLabel: canRequest ? notificationRequestLabel : null, asked: asked, diff --git a/app/lib/features/attention/ui/needs_you_copy.dart b/app/lib/features/attention/ui/needs_you_copy.dart index a4121c97..4efe282b 100644 --- a/app/lib/features/attention/ui/needs_you_copy.dart +++ b/app/lib/features/attention/ui/needs_you_copy.dart @@ -4,7 +4,6 @@ import '../domain/attention_models.dart'; const attentionSheetTitle = 'Needs you'; const attentionEmptyCopy = 'Nothing needs you right now.'; const attentionClearAllCopy = 'Clear all'; -const attentionCloseCopy = 'Close'; /// One row's dismissal name. /// diff --git a/app/lib/features/attention/ui/needs_you_keys.dart b/app/lib/features/attention/ui/needs_you_keys.dart index bb7198b3..b9e42cc2 100644 --- a/app/lib/features/attention/ui/needs_you_keys.dart +++ b/app/lib/features/attention/ui/needs_you_keys.dart @@ -12,6 +12,9 @@ const attentionSheetKey = ValueKey('attention-sheet'); /// The honest empty line shown when the open snapshot has no entries. const attentionEmptyKey = ValueKey('attention-empty'); +/// The header's Done action, which closes the sheet on both hosts. +const attentionDoneKey = ValueKey('attention-done'); + /// The bulk dismissal action, present only while the snapshot has entries. const attentionClearAllKey = ValueKey('attention-clear-all'); diff --git a/app/lib/features/attention/ui/needs_you_sheet_cupertino.dart b/app/lib/features/attention/ui/needs_you_sheet_cupertino.dart index 2449e176..4c3456da 100644 --- a/app/lib/features/attention/ui/needs_you_sheet_cupertino.dart +++ b/app/lib/features/attention/ui/needs_you_sheet_cupertino.dart @@ -2,6 +2,7 @@ import '../../../ui/theme/app_theme.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/foundation.dart'; +import '../../../ui/layout/app_sheet_header.dart'; import 'attention_status_icon.dart'; import '../domain/attention_models.dart'; import 'needs_you_copy.dart'; @@ -65,25 +66,12 @@ class CupertinoNeedsYouSheet extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Padding( - padding: const EdgeInsetsDirectional.fromSTEB(20, 16, 8, 4), - child: Row( - children: [ - Expanded( - child: Semantics( - header: true, - namesRoute: true, - child: Text( - attentionSheetTitle, - style: theme.textTheme.navTitleTextStyle, - ), - ), - ), - CupertinoButton( - padding: EdgeInsets.zero, - onPressed: () => _close(context), - child: const Text(attentionCloseCopy), - ), - ], + padding: const EdgeInsets.only(top: 8), + child: AppSheetHeader( + title: attentionSheetTitle, + cupertino: true, + doneKey: attentionDoneKey, + onDone: () => _close(context), ), ), if (rows.isEmpty) diff --git a/app/lib/features/attention/ui/needs_you_sheet_material.dart b/app/lib/features/attention/ui/needs_you_sheet_material.dart index 2d9d6818..a4815c5c 100644 --- a/app/lib/features/attention/ui/needs_you_sheet_material.dart +++ b/app/lib/features/attention/ui/needs_you_sheet_material.dart @@ -1,6 +1,7 @@ import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; +import '../../../ui/layout/app_sheet_header.dart'; import 'attention_status_icon.dart'; import '../domain/attention_models.dart'; import 'needs_you_copy.dart'; @@ -57,28 +58,18 @@ class MaterialNeedsYouSheet extends StatelessWidget { mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ - Padding( - padding: const EdgeInsetsDirectional.fromSTEB(24, 0, 12, 4), - child: Row( - children: [ - Expanded( - child: Semantics( - header: true, - namesRoute: true, - child: Text( - attentionSheetTitle, - style: theme.textTheme.titleLarge, - ), - ), + AppSheetHeader( + title: attentionSheetTitle, + cupertino: false, + doneKey: attentionDoneKey, + actions: [ + if (rows.isNotEmpty) + TextButton( + key: attentionClearAllKey, + onPressed: () => onClearAll(snapshot), + child: const Text(attentionClearAllCopy), ), - if (rows.isNotEmpty) - TextButton( - key: attentionClearAllKey, - onPressed: () => onClearAll(snapshot), - child: const Text(attentionClearAllCopy), - ), - ], - ), + ], ), if (rows.isEmpty) Padding( diff --git a/app/lib/features/attention/ui/notification_permission_tile.dart b/app/lib/features/attention/ui/notification_permission_tile.dart index 6604bc5a..d88713f7 100644 --- a/app/lib/features/attention/ui/notification_permission_tile.dart +++ b/app/lib/features/attention/ui/notification_permission_tile.dart @@ -55,48 +55,68 @@ class NotificationPermissionTile extends StatelessWidget { final action = view.canRequest && onRequest != null ? _action(native, view.actionLabel!, onRequest!) : null; - final bodyStyle = native + final titleStyle = native + ? CupertinoTheme.of(context).textTheme.textStyle + : Theme.of(context).textTheme.bodyLarge; + final helperStyle = native ? CupertinoTheme.of(context).textTheme.textStyle.copyWith( + fontSize: 15, color: CupertinoColors.secondaryLabel.resolveFrom(context), ) : Theme.of(context).textTheme.bodyMedium?.copyWith( color: Theme.of(context).colorScheme.onSurfaceVariant, ); - // The Settings section supplies the `Notifications` heading and the page - // inset, as for every other section, so the body starts at that edge. - return Column( + // One compact row: the state, one short helper line and Enable at the + // end. The full sentence for the state is what a screen reader hears. + // The Settings section supplies the `Notifications` heading. + return Row( key: notificationTileKey, - crossAxisAlignment: CrossAxisAlignment.start, children: [ - Text(notificationRationale, style: bodyStyle), - const SizedBox(height: 8), - Semantics( - liveRegion: true, - child: Text(view.body, key: notificationStateKey, style: bodyStyle), + Expanded( + child: Semantics( + liveRegion: true, + label: view.body, + excludeSemantics: true, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + view.headline, + key: notificationStateKey, + style: titleStyle, + ), + const SizedBox(height: 2), + Text(view.helper, style: helperStyle), + ], + ), + ), ), - // The action sits on its own row, as the browser's settings section - // does: its label is too long to share a row at large text. - if (action != null) ...[ - const SizedBox(height: 8), - Align(alignment: AlignmentDirectional.centerStart, child: action), - ], + if (action != null) ...[const SizedBox(width: 12), action], ], ); } + /// A short `Enable`, named in full for assistive technology. Widget _action(bool native, String label, VoidCallback onRequest) { - if (native) { - return CupertinoButton( - key: notificationEnableKey, - padding: EdgeInsets.zero, - onPressed: onRequest, - child: Text(label), - ); - } - return TextButton( - key: notificationEnableKey, - onPressed: onRequest, - child: Text(label), + const text = Text(notificationEnableShortLabel); + final Widget button = native + ? CupertinoButton.tinted( + key: notificationEnableKey, + sizeStyle: CupertinoButtonSize.small, + onPressed: onRequest, + child: text, + ) + : FilledButton.tonal( + key: notificationEnableKey, + onPressed: onRequest, + child: text, + ); + return Semantics( + button: true, + label: label, + excludeSemantics: true, + onTap: onRequest, + child: button, ); } } diff --git a/app/lib/features/runs/actions/decision_dialog.dart b/app/lib/features/runs/actions/decision_dialog.dart index 81aa717c..c1ceea50 100644 --- a/app/lib/features/runs/actions/decision_dialog.dart +++ b/app/lib/features/runs/actions/decision_dialog.dart @@ -4,6 +4,7 @@ import 'package:flutter/material.dart'; import '../domain/run_decisions.dart'; import '../domain/run_models.dart'; import 'action_refusal.dart'; +import 'decision_option_row.dart'; import 'decision_wording.dart'; /// Sends the draft to the server. Returns null on success, or an @@ -172,39 +173,20 @@ class _DecisionPromptState extends State<_DecisionPrompt> { errorStyle: TextStyle( color: CupertinoColors.systemRed.resolveFrom(context), ), - options: RadioGroup( - groupValue: _draft.selected, - onChanged: (value) { - if (value != null) _select(value); - }, - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - for (final option in widget.decision.options) - CupertinoButton( - onPressed: _sending ? null : () => _select(option.key), - child: Row( - children: [ - CupertinoRadio( - value: option.key, - useCheckmarkStyle: true, - enabled: !_sending, - ), - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text(option.key), - if (_targetText(option) case final target?) - Text(target), - ], - ), - ), - ], - ), - ), - ], - ), + options: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + for (final (index, option) in widget.decision.options.indexed) + DecisionOptionRow( + key: decisionOptionKey(option.key), + label: option.key, + target: _targetText(option), + selected: _draft.selected == option.key, + divider: index > 0, + onTap: _sending ? null : () => _select(option.key), + ), + ], ), feedback: CupertinoTextField( key: decisionFeedbackKey, diff --git a/app/lib/features/runs/actions/decision_option_row.dart b/app/lib/features/runs/actions/decision_option_row.dart new file mode 100644 index 00000000..94e4e800 --- /dev/null +++ b/app/lib/features/runs/actions/decision_option_row.dart @@ -0,0 +1,109 @@ +import 'package:flutter/cupertino.dart'; + +/// One option row in the Cupertino decision prompt, keyed by the option. +ValueKey decisionOptionKey(String option) => + ValueKey('human-decision-option-$option'); + +/// One choice of the Cupertino decision prompt: a check-list row. +/// +/// The option reads as text in the label colour, not as a blue link, with its +/// target underneath in the secondary colour. An empty circle marks an +/// unpicked row and a filled check circle the picked one, so the choice is +/// visible before Confirm. The whole row is the tap target; semantics report +/// it as a selectable member of one exclusive group. A null [onTap] (while +/// sending) dims the row. +class DecisionOptionRow extends StatelessWidget { + const DecisionOptionRow({ + super.key, + required this.label, + required this.selected, + required this.onTap, + this.target, + this.divider = false, + }); + + final String label; + final String? target; + final bool selected; + final bool divider; + final VoidCallback? onTap; + + @override + Widget build(BuildContext context) { + final theme = CupertinoTheme.of(context); + final enabled = onTap != null; + final labelColor = enabled + ? CupertinoColors.label.resolveFrom(context) + : CupertinoColors.tertiaryLabel.resolveFrom(context); + final mark = selected + ? Icon( + CupertinoIcons.checkmark_circle_fill, + color: enabled + ? theme.primaryColor + : CupertinoColors.tertiaryLabel.resolveFrom(context), + ) + : Icon( + CupertinoIcons.circle, + color: CupertinoColors.tertiaryLabel.resolveFrom(context), + ); + final row = Padding( + padding: const EdgeInsets.symmetric(vertical: 10), + child: Row( + children: [ + mark, + const SizedBox(width: 10), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + label, + textAlign: TextAlign.start, + style: theme.textTheme.textStyle.copyWith( + color: labelColor, + fontWeight: selected ? FontWeight.w600 : null, + ), + ), + if (target case final target?) + Text( + target, + textAlign: TextAlign.start, + style: theme.textTheme.textStyle.copyWith( + fontSize: 13, + color: CupertinoColors.secondaryLabel.resolveFrom( + context, + ), + ), + ), + ], + ), + ), + ], + ), + ); + return Semantics( + inMutuallyExclusiveGroup: true, + selected: selected, + checked: selected, + button: true, + enabled: enabled, + child: DecoratedBox( + decoration: BoxDecoration( + border: divider + ? Border( + top: BorderSide( + color: CupertinoColors.separator.resolveFrom(context), + width: 0, + ), + ) + : null, + ), + child: GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: onTap, + child: row, + ), + ), + ); + } +} diff --git a/app/lib/features/runs/ui/run_more_menu.dart b/app/lib/features/runs/ui/run_more_menu.dart index 43c80012..6cabbca2 100644 --- a/app/lib/features/runs/ui/run_more_menu.dart +++ b/app/lib/features/runs/ui/run_more_menu.dart @@ -9,6 +9,7 @@ import '../actions/retry_eligibility.dart'; import '../actions/retry_wording.dart'; import '../actions/title_action.dart'; import '../actions/title_wording.dart'; +import '../domain/run_models.dart' show runIdentity; const runMoreMenuKey = ValueKey('run-more-menu'); @@ -16,6 +17,13 @@ const runMoreMenuKey = ValueKey('run-more-menu'); bool showRunMoreMenu(JsonMap run) => runTitleId(run) != null || canScheduleRun(run) || _canRetry(run); +/// The run's own name for its action sheet: its title or pipeline, else +/// `Run `, as its list row shows it. +String runMoreMenuTitle(JsonMap run) { + final label = runIdentity(run['title'], run['name']).label; + return label.isEmpty ? 'Run ${run['id']}' : label; +} + bool _canRetry(JsonMap run) => retryRunId(run) != null && canRetryRun(run); enum _RunMoreItem { retry, rename, schedule } @@ -97,6 +105,8 @@ class _RunMoreMenuState extends State { return AppOverflowMenu<_RunMoreItem>( key: widget.menuKey, cupertino: widget.cupertino, + // The Cupertino action sheet names the run it acts on. + sheetTitle: runMoreMenuTitle(run), actions: [ for (final (item, label) in _items) AppMenuAction(key: _keyOf(item), value: item, label: label), diff --git a/app/lib/features/runs/ui/runs_filter_options.dart b/app/lib/features/runs/ui/runs_filter_options.dart new file mode 100644 index 00000000..35bea7e0 --- /dev/null +++ b/app/lib/features/runs/ui/runs_filter_options.dart @@ -0,0 +1,61 @@ +import 'runs_controller.dart'; + +/// The Runs toolbar's choices and their labels, shared by the applied-filter +/// chips, the filter sheet and the sort sheet. No widgets here. + +const runSorts = [ + ('newest_first', 'Newest first'), + ('oldest_first', 'Oldest first'), + ('longest_duration', 'Longest duration'), + ('shortest_duration', 'Shortest duration'), + ('pipeline_name', 'Pipeline name'), + ('status', 'Status'), +]; +const runSchedules = [ + ('any', 'Any trigger'), + ('scheduled', 'Scheduled runs'), + ('unscheduled', 'Not scheduled'), +]; +const runTimeRanges = [ + ('any_time', 'Any time'), + ('today', 'Today'), + ('last_7_days', 'Last 7 days'), + ('last_30_days', 'Last 30 days'), +]; + +/// The pipelines the loaded runs belong to, by name then id. +List<({int id, String name})> runFilterPipelines(RunsController controller) { + final names = {}; + final ids = {}; + for (final run in controller.runs) { + final id = run['pipeline_id']; + if (id is! int) continue; + ids.add(id); + final name = '${run['name'] ?? ''}'.trim(); + if (name.isNotEmpty && !names.containsKey(id)) names[id] = name; + } + final options = ids + .map((id) => (id: id, name: names[id] ?? 'Pipeline $id')) + .toList(); + options.sort((a, b) { + final nameOrder = a.name.toLowerCase().compareTo(b.name.toLowerCase()); + return nameOrder != 0 ? nameOrder : a.id.compareTo(b.id); + }); + return options; +} + +/// Whether some loaded run carries no scheduling provenance at all. +bool runsHaveUnclassified(RunsController controller) => + controller.runs.any((run) { + final id = run['schedule_id']; + return run['scheduled'] is! bool && !(id is num && id > 0); + }); + +String runTimeRangeLabel(String value) => runTimeRanges + .firstWhere((entry) => entry.$1 == value, orElse: () => runTimeRanges.first) + .$2; +String runSortLabel(String value) => + runSorts.firstWhere((e) => e.$1 == value, orElse: () => runSorts.first).$2; +String runScheduleLabel(String value) => runSchedules + .firstWhere((e) => e.$1 == value, orElse: () => runSchedules.first) + .$2; diff --git a/app/lib/features/runs/ui/runs_filter_sheet.dart b/app/lib/features/runs/ui/runs_filter_sheet.dart new file mode 100644 index 00000000..89cfb075 --- /dev/null +++ b/app/lib/features/runs/ui/runs_filter_sheet.dart @@ -0,0 +1,215 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../ui/adaptive/host.dart'; +import '../../../ui/input/app_search_field.dart'; +import '../../../ui/layout/app_sheet_header.dart'; +import '../../pipelines/pipeline_format.dart' show runStateLabel; +import '../domain/run_models.dart'; +import 'runs_controller.dart'; +import 'runs_filter_options.dart'; + +const runsFilterTitle = 'Filter runs'; +const runsFilterDoneKey = ValueKey('runs.filter.done'); +const runsFilterClearKey = ValueKey('runs.filter.clear'); + +/// The filter sheet: a header (title, Clear, Done), the text filter, then +/// status (several may be picked), pipeline, time range and trigger (one +/// each), every choice applied as it is picked. +Future showRunsFilterSheet( + BuildContext context, + RunsController controller, +) { + final cupertino = usesCupertinoHost(context); + final sheet = _RunsFilterSheet(controller: controller, cupertino: cupertino); + if (cupertino) { + return showCupertinoModalPopup( + context: context, + builder: (_) => CupertinoPopupSurface(child: SafeArea(child: sheet)), + ); + } + return showModalBottomSheet( + context: context, + isScrollControlled: true, + showDragHandle: true, + useSafeArea: true, + builder: (_) => sheet, + ); +} + +class _RunsFilterSheet extends StatefulWidget { + const _RunsFilterSheet({required this.controller, required this.cupertino}); + + final RunsController controller; + final bool cupertino; + + @override + State<_RunsFilterSheet> createState() => _RunsFilterSheetState(); +} + +class _RunsFilterSheetState extends State<_RunsFilterSheet> { + late final TextEditingController _text = TextEditingController( + text: widget.controller.query, + ); + + @override + void dispose() { + _text.dispose(); + super.dispose(); + } + + void _clear() { + _text.clear(); + widget.controller.setQuery(''); + widget.controller.clearFilters(); + } + + Widget _section(BuildContext context, String title) { + final style = widget.cupertino + ? CupertinoTheme.of( + context, + ).textTheme.textStyle.copyWith(fontWeight: FontWeight.w600) + : Theme.of(context).textTheme.titleSmall; + return Padding( + padding: const EdgeInsets.fromLTRB(16, 16, 16, 4), + child: Semantics(header: true, child: Text(title, style: style)), + ); + } + + /// One status: several may be on at once, so Material uses a checkbox. + Widget _multiChoice(String label, bool checked, VoidCallback onTap) { + if (widget.cupertino) return _checkRow(label, checked, onTap); + return CheckboxListTile( + dense: true, + title: Text(label), + value: checked, + onChanged: (_) => onTap(), + ); + } + + /// One choice of a single-choice group: a check mark on the picked row. + Widget _singleChoice(String label, bool checked, VoidCallback onTap) => + Semantics( + inMutuallyExclusiveGroup: true, + child: _checkRow(label, checked, onTap), + ); + + Widget _checkRow(String label, bool checked, VoidCallback onTap) { + if (widget.cupertino) { + return CupertinoListTile( + title: Text(label), + trailing: checked ? const Icon(CupertinoIcons.check_mark) : null, + onTap: onTap, + ); + } + return ListTile( + dense: true, + selected: checked, + title: Text(label), + trailing: checked ? const Icon(Icons.check) : null, + onTap: onTap, + ); + } + + @override + Widget build(BuildContext context) { + final controller = widget.controller; + final field = AppSearchField( + fieldKey: const ValueKey('runs.filter.query'), + controller: _text, + cupertino: widget.cupertino, + placeholder: 'Filter runs', + onChanged: controller.setQuery, + ); + return ListenableBuilder( + listenable: controller, + builder: (context, _) { + final active = + controller.activeFilterCount > 0 || controller.query.isNotEmpty; + return ConstrainedBox( + constraints: BoxConstraints( + maxHeight: MediaQuery.sizeOf(context).height * 0.85, + ), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + AppSheetHeader( + title: runsFilterTitle, + cupertino: widget.cupertino, + doneKey: runsFilterDoneKey, + actions: [if (active) _clearButton()], + ), + Flexible(child: _list(context, controller, field)), + ], + ), + ); + }, + ); + } + + Widget _clearButton() => widget.cupertino + ? CupertinoButton( + key: runsFilterClearKey, + padding: const EdgeInsets.symmetric(horizontal: 8), + onPressed: _clear, + child: const Text('Clear'), + ) + : TextButton( + key: runsFilterClearKey, + onPressed: _clear, + child: const Text('Clear'), + ); + + Widget _list(BuildContext context, RunsController controller, Widget field) { + return ListView( + key: const ValueKey('runs.filter.sheet'), + shrinkWrap: true, + padding: const EdgeInsets.only(bottom: 16), + children: [ + Padding(padding: const EdgeInsets.fromLTRB(16, 4, 16, 0), child: field), + _section(context, 'Status'), + for (final status in runStates) + _multiChoice( + runStateLabel(status), + controller.statuses.contains(status), + () => controller.setStatus(status), + ), + _section(context, 'Pipeline'), + _singleChoice( + 'Any pipeline', + controller.pipelineId == null, + () => controller.setPipeline(null), + ), + for (final pipeline in runFilterPipelines(controller)) + _singleChoice( + pipeline.name, + controller.pipelineId == pipeline.id, + () => controller.setPipeline(pipeline.id), + ), + _section(context, 'Time range'), + for (final range in runTimeRanges) + _singleChoice( + range.$2, + controller.timeRange == range.$1, + () => controller.setTimeRange(range.$1), + ), + _section(context, 'Trigger'), + for (final schedule in runSchedules) + _singleChoice( + schedule.$2, + controller.scheduled == schedule.$1, + () => controller.setScheduled(schedule.$1), + ), + if (runsHaveUnclassified(controller)) + const Padding( + padding: EdgeInsets.fromLTRB(16, 4, 16, 0), + child: Text( + 'Some records have no scheduling provenance; they stay ' + 'unclassified.', + ), + ), + ], + ); + } +} diff --git a/app/lib/features/runs/ui/runs_filters.dart b/app/lib/features/runs/ui/runs_filters.dart index a42607b9..32025b8e 100644 --- a/app/lib/features/runs/ui/runs_filters.dart +++ b/app/lib/features/runs/ui/runs_filters.dart @@ -1,10 +1,17 @@ -import '../../../ui/input/app_search_field.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import '../../../ui/adaptive/host.dart'; -import '../domain/run_models.dart'; +import '../../../ui/layout/app_sheet_header.dart'; +import '../../pipelines/pipeline_format.dart' show runStateLabel; import 'runs_controller.dart'; +import 'runs_filter_options.dart'; +import 'runs_filter_sheet.dart'; + +export 'runs_filter_sheet.dart' show showRunsFilterSheet; + +const runsSortTitle = 'Sort runs'; +const runsSortDoneKey = ValueKey('runs.sort.done'); /// The runs list's compact native filter/sort toolbar and applied-filter chips. /// @@ -62,17 +69,20 @@ class RunsFilters extends StatelessWidget { applied.add((label: pipeline, clear: () => controller.setPipeline(null))); } for (final status in controller.statuses) { - applied.add((label: status, clear: () => controller.setStatus(status))); + applied.add(( + label: runStateLabel(status), + clear: () => controller.setStatus(status), + )); } if (controller.timeRange != 'any_time') { applied.add(( - label: _timeRangeLabel(controller.timeRange), + label: runTimeRangeLabel(controller.timeRange), clear: () => controller.setTimeRange('any_time'), )); } if (controller.scheduled != 'any') { applied.add(( - label: _scheduleLabel(controller.scheduled), + label: runScheduleLabel(controller.scheduled), clear: () => controller.setScheduled('any'), )); } @@ -128,61 +138,6 @@ class RunsFilters extends StatelessWidget { } } -const _sorts = [ - ('newest_first', 'Newest first'), - ('oldest_first', 'Oldest first'), - ('longest_duration', 'Longest duration'), - ('shortest_duration', 'Shortest duration'), - ('pipeline_name', 'Pipeline name'), - ('status', 'Status'), -]; -const _schedules = [ - ('any', 'Any trigger'), - ('scheduled', 'Scheduled runs'), - ('unscheduled', 'Not scheduled'), -]; -const _timeRanges = [ - ('any_time', 'Any time'), - ('today', 'Today'), - ('last_7_days', 'Last 7 days'), - ('last_30_days', 'Last 30 days'), -]; - -List<({int id, String name})> _pipelines(RunsController controller) { - final names = {}; - final ids = {}; - for (final run in controller.runs) { - final id = run['pipeline_id']; - if (id is! int) continue; - ids.add(id); - final name = '${run['name'] ?? ''}'.trim(); - if (name.isNotEmpty && !names.containsKey(id)) names[id] = name; - } - final options = ids - .map((id) => (id: id, name: names[id] ?? 'Pipeline $id')) - .toList(); - options.sort((a, b) { - final nameOrder = a.name.toLowerCase().compareTo(b.name.toLowerCase()); - return nameOrder != 0 ? nameOrder : a.id.compareTo(b.id); - }); - return options; -} - -bool _hasUnclassifiedRuns(RunsController controller) => - controller.runs.any((run) { - final id = run['schedule_id']; - return run['scheduled'] is! bool && !(id is num && id > 0); - }); - -String _timeRangeLabel(String value) => _timeRanges - .firstWhere((entry) => entry.$1 == value, orElse: () => _timeRanges.first) - .$2; -String _sortLabel(String value) => - _sorts.firstWhere((e) => e.$1 == value, orElse: () => _sorts.first).$2; -String _scheduleLabel(String value) => _schedules - .firstWhere((e) => e.$1 == value, orElse: () => _schedules.first) - .$2; - /// The Runs list's app-bar actions: usage and charts, filter (with the search /// field inside) and sort, as icons. class RunsBarActions { @@ -252,7 +207,7 @@ class RunsBarActions { const ValueKey('runs.sort'), Icons.sort, CupertinoIcons.arrow_up_arrow_down, - 'Sort runs: ${_sortLabel(controller.sort)}', + 'Sort runs: ${runSortLabel(controller.sort)}', () => _chooseSort(context), ), ]; @@ -265,10 +220,12 @@ class RunsBarActions { value = await showCupertinoModalPopup( context: context, builder: (sheet) => CupertinoActionSheet( - title: const Text('Sort runs'), + title: const Text(runsSortTitle), actions: [ - for (final option in _sorts) + for (final option in runSorts) CupertinoActionSheetAction( + // The current order is the sheet's default (bold) action. + isDefaultAction: controller.sort == option.$1, onPressed: () => Navigator.pop(sheet, option.$1), child: Text( '${controller.sort == option.$1 ? '✓ ' : ''}${option.$2}', @@ -286,18 +243,31 @@ class RunsBarActions { context: context, showDragHandle: true, builder: (sheet) => SafeArea( - child: ListView( - shrinkWrap: true, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, children: [ - const ListTile(title: Text('Sort runs')), - for (final option in _sorts) - ListTile( - title: Text(option.$2), - trailing: controller.sort == option.$1 - ? const Icon(Icons.check) - : null, - onTap: () => Navigator.pop(sheet, option.$1), + const AppSheetHeader( + title: runsSortTitle, + cupertino: false, + doneKey: runsSortDoneKey, + ), + Flexible( + child: ListView( + shrinkWrap: true, + children: [ + for (final option in runSorts) + ListTile( + selected: controller.sort == option.$1, + title: Text(option.$2), + trailing: controller.sort == option.$1 + ? const Icon(Icons.check) + : null, + onTap: () => Navigator.pop(sheet, option.$1), + ), + ], ), + ), ], ), ), @@ -306,162 +276,3 @@ class RunsBarActions { if (value != null && value != controller.sort) controller.setSort(value); } } - -/// The filter sheet: the text filter first, then status, pipeline, time range -/// and trigger, each choice applied as it is picked. -Future showRunsFilterSheet( - BuildContext context, - RunsController controller, -) { - final cupertino = usesCupertinoHost(context); - final sheet = _RunsFilterSheet(controller: controller, cupertino: cupertino); - if (cupertino) { - return showCupertinoModalPopup( - context: context, - builder: (_) => CupertinoPopupSurface(child: SafeArea(child: sheet)), - ); - } - return showModalBottomSheet( - context: context, - isScrollControlled: true, - showDragHandle: true, - useSafeArea: true, - builder: (_) => sheet, - ); -} - -class _RunsFilterSheet extends StatefulWidget { - const _RunsFilterSheet({required this.controller, required this.cupertino}); - - final RunsController controller; - final bool cupertino; - - @override - State<_RunsFilterSheet> createState() => _RunsFilterSheetState(); -} - -class _RunsFilterSheetState extends State<_RunsFilterSheet> { - late final TextEditingController _text = TextEditingController( - text: widget.controller.query, - ); - - @override - void dispose() { - _text.dispose(); - super.dispose(); - } - - Widget _section(String title) => Padding( - padding: const EdgeInsets.fromLTRB(16, 16, 16, 4), - child: Text(title, style: const TextStyle(fontWeight: FontWeight.w600)), - ); - - Widget _choice(String label, bool checked, VoidCallback onTap) { - if (widget.cupertino) { - return CupertinoListTile( - title: Text(label), - trailing: checked ? const Icon(CupertinoIcons.check_mark) : null, - onTap: onTap, - ); - } - return CheckboxListTile( - dense: true, - title: Text(label), - value: checked, - onChanged: (_) => onTap(), - ); - } - - @override - Widget build(BuildContext context) { - final controller = widget.controller; - final field = AppSearchField( - fieldKey: const ValueKey('runs.filter.query'), - controller: _text, - cupertino: widget.cupertino, - placeholder: 'Filter runs', - onChanged: controller.setQuery, - ); - return ListenableBuilder( - listenable: controller, - builder: (context, _) => ConstrainedBox( - constraints: BoxConstraints( - maxHeight: MediaQuery.sizeOf(context).height * 0.85, - ), - child: ListView( - key: const ValueKey('runs.filter.sheet'), - shrinkWrap: true, - padding: const EdgeInsets.only(bottom: 16), - children: [ - Padding( - padding: const EdgeInsets.fromLTRB(16, 8, 16, 0), - child: field, - ), - _section('Status'), - for (final status in runStates) - _choice( - status, - controller.statuses.contains(status), - () => controller.setStatus(status), - ), - _section('Pipeline'), - _choice( - 'Any pipeline', - controller.pipelineId == null, - () => controller.setPipeline(null), - ), - for (final pipeline in _pipelines(controller)) - _choice( - pipeline.name, - controller.pipelineId == pipeline.id, - () => controller.setPipeline(pipeline.id), - ), - _section('Time range'), - for (final range in _timeRanges) - _choice( - range.$2, - controller.timeRange == range.$1, - () => controller.setTimeRange(range.$1), - ), - _section('Trigger'), - for (final schedule in _schedules) - _choice( - schedule.$2, - controller.scheduled == schedule.$1, - () => controller.setScheduled(schedule.$1), - ), - if (_hasUnclassifiedRuns(controller)) - const Padding( - padding: EdgeInsets.fromLTRB(16, 4, 16, 0), - child: Text( - 'Some records have no scheduling provenance; they stay ' - 'unclassified.', - ), - ), - if (controller.activeFilterCount > 0 || controller.query.isNotEmpty) - Padding( - padding: const EdgeInsets.fromLTRB(16, 12, 16, 0), - child: widget.cupertino - ? CupertinoButton( - onPressed: () { - _text.clear(); - controller.setQuery(''); - controller.clearFilters(); - }, - child: const Text('Clear filters'), - ) - : TextButton( - onPressed: () { - _text.clear(); - controller.setQuery(''); - controller.clearFilters(); - }, - child: const Text('Clear filters'), - ), - ), - ], - ), - ), - ); - } -} diff --git a/app/lib/features/runs/ui/runs_stats_page.dart b/app/lib/features/runs/ui/runs_stats_page.dart index 1f733370..495b14ed 100644 --- a/app/lib/features/runs/ui/runs_stats_page.dart +++ b/app/lib/features/runs/ui/runs_stats_page.dart @@ -9,7 +9,7 @@ import '../../../ui/adaptive/floating_bar_layout.dart'; import '../../../ui/adaptive/host.dart'; import '../../../ui/status/run_status_icon.dart'; import '../domain/run_models.dart'; -import '../../pipelines/pipeline_format.dart' show parseInstant; +import '../../pipelines/pipeline_format.dart' show parseInstant, runStateLabel; import 'run_detail_content.dart'; import 'runs_controller.dart'; @@ -72,10 +72,13 @@ class RunsStatsPage extends StatelessWidget { key: const ValueKey('runs.stats.page'), padding: withBarClearance(context, const EdgeInsets.all(16)), children: [ - Text('Usage', style: heading), - const SizedBox(height: 8), + // The bar already says Usage: the totals lead the page untitled. if (metrics.isEmpty) - Text('No usage reported.', style: TextStyle(color: secondary)) + Text( + 'No usage has been reported for these runs.', + key: const ValueKey('runs.stats.usage.empty'), + style: TextStyle(color: secondary), + ) else Wrap( spacing: 24, @@ -124,11 +127,11 @@ class RunsStatsPage extends StatelessWidget { children: [ RunStatusIcon( state: entry.key, - label: entry.key, + label: runStateLabel(entry.key), size: 16, ), const SizedBox(width: 8), - Expanded(child: Text(entry.key)), + Expanded(child: Text(runStateLabel(entry.key))), Text('${entry.value}'), ], ), @@ -141,49 +144,14 @@ class RunsStatsPage extends StatelessWidget { const SizedBox(height: 24), Text('Runs in the last 7 days', style: heading), const SizedBox(height: 12), - SizedBox( - height: 140, - child: Row( - key: const ValueKey('runs.stats.days'), - crossAxisAlignment: CrossAxisAlignment.end, - children: [ - for (final day in days) - Expanded( - child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 4), - child: Column( - mainAxisAlignment: MainAxisAlignment.end, - children: [ - Text( - '${day.count}', - style: TextStyle(color: secondary), - ), - const SizedBox(height: 2), - Flexible( - child: FractionallySizedBox( - heightFactor: day.count == 0 - ? 0.02 - : day.count / - days.map((d) => d.count).reduce(math.max), - child: DecoratedBox( - decoration: BoxDecoration( - color: cupertino - ? CupertinoTheme.of(context).primaryColor - : Theme.of(context).colorScheme.primary, - borderRadius: BorderRadius.circular(4), - ), - ), - ), - ), - const SizedBox(height: 4), - Text(day.label, style: TextStyle(color: secondary)), - ], - ), - ), - ), - ], - ), - ), + if (days.every((day) => day.count == 0)) + Text( + 'No runs started in the last 7 days.', + key: const ValueKey('runs.stats.days.empty'), + style: TextStyle(color: secondary), + ) + else + _DaysChart(days: days, cupertino: cupertino, secondary: secondary), ], ); } @@ -231,3 +199,92 @@ class _PiePainter extends CustomPainter { @override bool shouldRepaint(_PiePainter oldDelegate) => true; } + +/// Runs per day as bars over a baseline axis, each bar labelled with its +/// count and its weekday underneath. Only drawn when some day has a run. +class _DaysChart extends StatelessWidget { + const _DaysChart({ + required this.days, + required this.cupertino, + required this.secondary, + }); + + final List<({String label, int count})> days; + final bool cupertino; + final Color secondary; + + @override + Widget build(BuildContext context) { + final most = days.map((d) => d.count).reduce(math.max); + final bar = cupertino + ? CupertinoTheme.of(context).primaryColor + : Theme.of(context).colorScheme.primary; + final axis = cupertino + ? CupertinoColors.separator.resolveFrom(context) + : Theme.of(context).colorScheme.outlineVariant; + return Column( + key: const ValueKey('runs.stats.days'), + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + DecoratedBox( + decoration: BoxDecoration( + border: Border(bottom: BorderSide(color: axis)), + ), + child: SizedBox( + height: 140, + child: Row( + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + for (final day in days) + Expanded( + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 4), + child: Column( + mainAxisAlignment: MainAxisAlignment.end, + children: [ + if (day.count > 0) ...[ + Text( + '${day.count}', + style: TextStyle(color: secondary), + ), + const SizedBox(height: 2), + Flexible( + child: FractionallySizedBox( + heightFactor: day.count / most, + child: DecoratedBox( + decoration: BoxDecoration( + color: bar, + borderRadius: const BorderRadius.vertical( + top: Radius.circular(4), + ), + ), + child: const SizedBox.expand(), + ), + ), + ), + ], + ], + ), + ), + ), + ], + ), + ), + ), + const SizedBox(height: 4), + Row( + children: [ + for (final day in days) + Expanded( + child: Text( + day.label, + textAlign: TextAlign.center, + style: TextStyle(color: secondary), + ), + ), + ], + ), + ], + ); + } +} diff --git a/app/lib/features/settings/settings_controller.dart b/app/lib/features/settings/settings_controller.dart index bc834706..e1f9840b 100644 --- a/app/lib/features/settings/settings_controller.dart +++ b/app/lib/features/settings/settings_controller.dart @@ -106,7 +106,10 @@ class SettingsController extends ChangeNotifier { _connection.kind == transport.ConnectionKind.connecting; String get primaryActionLabel => connectionActive ? 'Disconnect' : 'Connect'; - String get secondaryActionLabel => connectionActive ? 'Connect' : 'Reconnect'; + + /// Connecting again to the URL in the field; while connected that is a + /// reconnect, so it never reads `Connect` beside `Disconnect`. + String get secondaryActionLabel => 'Reconnect'; List get connectionLines => connectionCardLines( _connection, diff --git a/app/lib/features/settings/settings_sections.dart b/app/lib/features/settings/settings_sections.dart index ccf038df..aeaceca3 100644 --- a/app/lib/features/settings/settings_sections.dart +++ b/app/lib/features/settings/settings_sections.dart @@ -151,9 +151,12 @@ class SettingsWorkspaceSection extends StatelessWidget { crossAxisAlignment: WrapCrossAlignment.center, children: [ if (usesCupertinoControls(context)) - CupertinoButton( + // A tinted button keeps its shape when disabled, so an + // unsaved-nothing state reads as a disabled button, + // not as stray grey text. + CupertinoButton.tinted( key: SettingsKeys.saveWorkspace, - padding: EdgeInsets.zero, + sizeStyle: CupertinoButtonSize.small, onPressed: save, child: const Text('Save workspace'), ) diff --git a/app/lib/ui/layout/app_sheet_header.dart b/app/lib/ui/layout/app_sheet_header.dart new file mode 100644 index 00000000..88310c4a --- /dev/null +++ b/app/lib/ui/layout/app_sheet_header.dart @@ -0,0 +1,106 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../adaptive/host.dart'; + +/// The label of every sheet's close action. +const appSheetDoneLabel = 'Done'; + +/// The app's one sheet header: the sheet's [title] at the start, then any +/// extra [actions] (Clear all), then Done, which closes the sheet. +/// +/// Material shows the title in `titleLarge` and a [TextButton]; Cupertino +/// shows the navigation title style and a bold [CupertinoButton], like a +/// modal's navigation bar. The title is a header that names the route, so a +/// screen reader announces the sheet by it. Nothing has a fixed height and the +/// title wraps at large text. Used by the Runs filter and sort sheets and the +/// Needs you sheet, so every sheet closes the same way, not only by its drag +/// handle. +class AppSheetHeader extends StatelessWidget { + const AppSheetHeader({ + super.key, + required this.title, + this.actions = const [], + this.onDone, + this.doneKey, + this.cupertino, + }); + + final String title; + + /// Controls before Done, in the host's style. + final List actions; + + /// Closes the sheet; the default pops the route the header is in. + final VoidCallback? onDone; + final Key? doneKey; + + /// Overrides the host detection. + final bool? cupertino; + + @override + Widget build(BuildContext context) { + final cupertino = this.cupertino ?? usesCupertinoHost(context); + final done = onDone ?? () => Navigator.of(context).maybePop(); + final titleStyle = cupertino + ? CupertinoTheme.of(context).textTheme.navTitleTextStyle + : Theme.of(context).textTheme.titleLarge; + final Widget doneButton = cupertino + ? CupertinoButton( + key: doneKey, + padding: const EdgeInsets.symmetric(horizontal: 8), + minimumSize: const Size.square(kMinInteractiveDimensionCupertino), + onPressed: done, + child: const Text( + appSheetDoneLabel, + style: TextStyle(fontWeight: FontWeight.w600), + ), + ) + : TextButton( + key: doneKey, + onPressed: done, + child: const Text(appSheetDoneLabel), + ); + return Padding( + padding: EdgeInsetsDirectional.fromSTEB( + cupertino ? 20 : 24, + cupertino ? 8 : 0, + 8, + 4, + ), + child: LayoutBuilder( + builder: (context, constraints) { + final heading = Expanded( + child: Semantics( + header: true, + namesRoute: true, + child: Text(title, style: titleStyle), + ), + ); + // A narrow sheet at large text moves the extra actions to a line + // of their own under the title, so nothing is squeezed off. + final narrow = + constraints.maxWidth < + MediaQuery.textScalerOf(context).scale(_wideHeaderWidth); + if (actions.isEmpty || !narrow) { + return Row(children: [heading, ...actions, doneButton]); + } + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Row(children: [heading, doneButton]), + Align( + alignment: AlignmentDirectional.centerStart, + child: Wrap(children: actions), + ), + ], + ); + }, + ), + ); + } +} + +/// Below this width (scaled with the text) the extra actions wrap under the +/// title. +const double _wideHeaderWidth = 360; diff --git a/app/test/features/artifacts/domain/artifact_preview_failure_test.dart b/app/test/features/artifacts/domain/artifact_preview_failure_test.dart new file mode 100644 index 00000000..3937a50d --- /dev/null +++ b/app/test/features/artifacts/domain/artifact_preview_failure_test.dart @@ -0,0 +1,27 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/artifacts/domain/artifact_preview_failure.dart'; + +void main() { + test('fetch failures read as plain language, never raw errors', () { + expect( + artifactPreviewFailureMessage(), + 'The preview could not be loaded. Check the connection and try again.', + ); + expect( + artifactPreviewFailureMessage(status: 404), + 'This file is no longer on the server.', + ); + expect( + artifactPreviewFailureMessage(status: 403), + 'The server did not allow this file to be opened.', + ); + expect( + artifactPreviewFailureMessage(status: 502), + 'The server could not send this file right now.', + ); + expect( + artifactPreviewFailureMessage(status: 418), + 'The preview could not be loaded (status 418).', + ); + }); +} diff --git a/app/test/features/artifacts/ui/artifact_viewer_page_test.dart b/app/test/features/artifacts/ui/artifact_viewer_page_test.dart index 3f620cbf..adc7c35d 100644 --- a/app/test/features/artifacts/ui/artifact_viewer_page_test.dart +++ b/app/test/features/artifacts/ui/artifact_viewer_page_test.dart @@ -12,6 +12,8 @@ import 'package:pipelines_app/features/artifacts/domain/artifact_groups.dart'; import 'package:pipelines_app/features/artifacts/domain/artifact_record.dart'; import 'package:pipelines_app/features/artifacts/ui/artifact_external_open.dart'; import 'package:pipelines_app/features/artifacts/ui/artifact_gallery_page.dart'; +import 'package:pipelines_app/features/artifacts/ui/artifact_viewer_content.dart' + show artifactPreviewRetryKey; import 'package:pipelines_app/features/artifacts/ui/artifact_viewer_fetch.dart'; import 'package:pipelines_app/features/artifacts/ui/artifact_viewer_page.dart'; import 'package:pipelines_app/features/artifacts/ui/artifact_visit_list.dart'; @@ -464,8 +466,39 @@ void main() { pending.complete(ArtifactFetchResult(status: 404, bytes: Uint8List(0))); await tester.pumpAndSettle(); - expect(find.text('The server answered 404.'), findsOneWidget); + expect(find.text('This file is no longer on the server.'), findsOneWidget); + expect(find.textContaining('answered'), findsNothing); expect(find.byType(SelectableText), findsNothing); + expect(find.byKey(artifactPreviewRetryKey), findsOneWidget); + }); + + testWidgets('Retry fetches a failed preview again', (tester) async { + final text = recordedArtifact( + 'notes.txt', + url: '/artifacts/1/1/notes.txt', + contentType: 'text/plain', + ); + final group = _group([text]); + var calls = 0; + await _pumpViewer( + tester, + groups: [group], + selected: artifactVisitIdentity(group, text), + fetch: (_) async { + calls++; + if (calls == 1) throw const ArtifactFetchException('network down'); + return ArtifactFetchResult( + status: 200, + bytes: Uint8List.fromList('hello'.codeUnits), + ); + }, + ); + expect(find.byKey(artifactPreviewRetryKey), findsOneWidget); + await tester.tap(find.byKey(artifactPreviewRetryKey)); + await tester.pumpAndSettle(); + expect(calls, 2); + expect(find.byKey(artifactPreviewRetryKey), findsNothing); + expect(find.text('hello'), findsOneWidget); }); testWidgets('a network failure is reported instead of an empty preview', ( @@ -483,8 +516,15 @@ void main() { selected: artifactVisitIdentity(group, text), fetch: (_) async => throw const ArtifactFetchException('network down'), ); - expect(find.textContaining('Could not load preview'), findsOneWidget); - expect(find.textContaining('network down'), findsOneWidget); + // A friendly line with Retry, never the raw exception text. + expect( + find.text( + 'The preview could not be loaded. Check the connection and try again.', + ), + findsOneWidget, + ); + expect(find.textContaining('network down'), findsNothing); + expect(find.byKey(artifactPreviewRetryKey), findsOneWidget); }); testWidgets('Cupertino draws the same text preview and controls', ( diff --git a/app/test/features/attention/notify/notification_manager_wiring_test.dart b/app/test/features/attention/notify/notification_manager_wiring_test.dart index 85a2ac6b..a308cad7 100644 --- a/app/test/features/attention/notify/notification_manager_wiring_test.dart +++ b/app/test/features/attention/notify/notification_manager_wiring_test.dart @@ -7,6 +7,7 @@ import 'package:pipelines_app/features/attention/notify/notification_controller. import 'package:pipelines_app/features/attention/notify/notification_models.dart'; import 'package:pipelines_app/features/attention/notify/notification_store.dart'; import 'package:pipelines_app/features/attention/ui/needs_you_runs_heading.dart'; +import 'package:pipelines_app/features/attention/ui/notification_permission_tile.dart'; import 'package:pipelines_app/features/settings/settings_notifications_section.dart'; import 'notification_test_support.dart'; @@ -70,13 +71,13 @@ void main() { await tester.pumpWidget( MaterialApp( - home: Scaffold( - body: SettingsNotificationsSection(controller: notify), - ), + home: Scaffold(body: SettingsNotificationsSection(controller: notify)), ), ); await tester.pump(); - expect(find.text(notificationRationale), findsOneWidget); + // One compact row: the short state, not the long rationale paragraph. + expect(find.byKey(notificationStateKey), findsOneWidget); + expect(find.text(notificationRationale), findsNothing); // A denied platform answer shows its own words and no Enable action. final denied = NotificationController( @@ -86,12 +87,11 @@ void main() { addTearDown(denied.dispose); await tester.pumpWidget( MaterialApp( - home: Scaffold( - body: SettingsNotificationsSection(controller: denied), - ), + home: Scaffold(body: SettingsNotificationsSection(controller: denied)), ), ); await tester.pump(); - expect(find.text(notificationRationale), findsOneWidget); + expect(find.byKey(notificationStateKey), findsOneWidget); + expect(find.text(notificationRationale), findsNothing); }); } diff --git a/app/test/features/attention/ui/notification_permission_tile_test.dart b/app/test/features/attention/ui/notification_permission_tile_test.dart index f5cd487a..d4f00510 100644 --- a/app/test/features/attention/ui/notification_permission_tile_test.dart +++ b/app/test/features/attention/ui/notification_permission_tile_test.dart @@ -33,7 +33,7 @@ void main() { for (final native in [false, true]) { final host = native ? 'Cupertino' : 'Material'; - testWidgets('$host shows the state\'s own honest copy', (tester) async { + testWidgets('$host shows a compact row for each state', (tester) async { final cases = { NotificationPermissionState.unsupported: notificationUnsupportedCopy, NotificationPermissionState.needsSecureContext: @@ -46,10 +46,15 @@ void main() { await tester.pumpWidget( _page(state: entry.key, cupertino: native, onRequest: _noop), ); - // The Settings section owns the heading; the tile is its body. + final view = notificationPermissionView(entry.key); + // The Settings section owns the heading; the tile is one short row. expect(find.text(notificationSectionTitle), findsNothing); - expect(find.text(notificationRationale), findsOneWidget); - expect(find.text(entry.value), findsOneWidget, reason: '${entry.key}'); + expect(find.text(notificationRationale), findsNothing); + expect(find.text(view.headline), findsOneWidget); + expect(find.text(view.helper), findsOneWidget); + // The full honest sentence is what assistive technology reads. + expect(view.body, entry.value); + expect(find.bySemanticsLabel(entry.value), findsOneWidget); expect( find.byKey(notificationEnableKey), entry.key == NotificationPermissionState.notRequested @@ -70,8 +75,9 @@ void main() { cupertino: native, ), ); - expect(find.text(notificationDefaultAskedCopy), findsOneWidget); - expect(find.text(notificationDefaultCopy), findsNothing); + expect(find.text('Alerts are still off'), findsOneWidget); + expect(find.bySemanticsLabel(notificationDefaultAskedCopy), findsOne); + expect(find.bySemanticsLabel(notificationDefaultCopy), findsNothing); }); testWidgets('$host Enable runs the explicit request', (tester) async { @@ -115,16 +121,19 @@ void main() { ); expect(tester.takeException(), isNull); - final rationale = tester.renderObject( - find.text(notificationRationale), + final view = notificationPermissionView( + NotificationPermissionState.notRequested, + ); + final helper = tester.renderObject( + find.text(view.helper), ); expect( - rationale.size.width, + helper.size.width, greaterThan(100), - reason: 'the action must not squeeze the section copy', + reason: 'the action must not squeeze the row copy', ); final body = tester.renderObject( - find.text(notificationDefaultCopy), + find.text(view.headline), ); expect(body.didExceedMaxLines, isFalse); expect(find.byKey(notificationEnableKey), findsOneWidget); diff --git a/app/test/features/runs/actions/decision_action_test.dart b/app/test/features/runs/actions/decision_action_test.dart index b756db79..9f4c4b45 100644 --- a/app/test/features/runs/actions/decision_action_test.dart +++ b/app/test/features/runs/actions/decision_action_test.dart @@ -3,6 +3,7 @@ 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/runs/actions/decision_action.dart'; +import 'package:pipelines_app/features/runs/actions/decision_option_row.dart'; import 'package:pipelines_app/features/runs/actions/decision_wording.dart'; typedef _Handler = Future Function(String type, JsonMap fields); @@ -194,9 +195,33 @@ void main() { decisionConfirmLabel, ); expect(tester.widget(confirm).onPressed, isNull); + // Options are check-list rows, not blue link buttons: an empty circle + // until one is picked, then a filled check on that row only. + final skip = find.byKey(decisionOptionKey('skip')); + expect(skip, findsOneWidget); + expect( + find.ancestor( + of: find.text('skip'), + matching: find.byType(CupertinoButton), + ), + findsNothing, + ); + expect(find.byIcon(CupertinoIcons.checkmark_circle_fill), findsNothing); + expect( + find.descendant(of: skip, matching: find.byIcon(CupertinoIcons.circle)), + findsOneWidget, + ); await tester.tap(find.text('skip')); await tester.pump(); expect(gateway.calls, isEmpty); + expect( + find.descendant( + of: skip, + matching: find.byIcon(CupertinoIcons.checkmark_circle_fill), + ), + findsOneWidget, + ); + expect(find.byIcon(CupertinoIcons.checkmark_circle_fill), findsOneWidget); await tester.tap(find.text(decisionConfirmLabel)); await tester.pumpAndSettle(); diff --git a/app/test/features/runs/ui/run_list_row_test.dart b/app/test/features/runs/ui/run_list_row_test.dart index 2aa05b33..c11c260d 100644 --- a/app/test/features/runs/ui/run_list_row_test.dart +++ b/app/test/features/runs/ui/run_list_row_test.dart @@ -81,10 +81,13 @@ void main() { ), ); - expect( - find.text('Pipeline unavailable · 2m 5s · 3 steps'), - findsOneWidget, - ); + expect(find.text('Pipeline unavailable · 2m 5s · 3 steps'), findsOneWidget); + }); + + test('the run action sheet is titled with the run', () { + expect(runMoreMenuTitle(_finished), 'Ship the release notes'); + expect(runMoreMenuTitle({'id': 5, 'name': 'nightly'}), 'nightly'); + expect(runMoreMenuTitle({'id': 5}), 'Run 5'); }); testWidgets('gives a list action menu a per-run key', (tester) async { diff --git a/app/test/features/runs/ui/runs_sheets_test.dart b/app/test/features/runs/ui/runs_sheets_test.dart new file mode 100644 index 00000000..d423b3b4 --- /dev/null +++ b/app/test/features/runs/ui/runs_sheets_test.dart @@ -0,0 +1,188 @@ +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/runs/data/runs_repository.dart'; +import 'package:pipelines_app/features/runs/ui/runs_controller.dart'; +import 'package:pipelines_app/features/runs/ui/runs_filter_sheet.dart'; +import 'package:pipelines_app/features/runs/ui/runs_filters.dart'; +import 'package:pipelines_app/features/runs/ui/runs_list.dart'; +import 'package:pipelines_app/features/runs/ui/runs_stats_page.dart'; +import 'package:pipelines_app/ui/layout/app_sheet_header.dart'; + +class _Gateway implements ApiGateway { + final framesController = StreamController.broadcast(); + JsonMap? reply; + + @override + Stream get frames => framesController.stream; + + @override + Future call(String type, [JsonMap fields = const {}]) async => + reply ?? {'runs': []}; +} + +/// The Runs sheets share one header (title and Done), single-choice groups +/// use check rows, statuses read in sentence case, and the usage page neither +/// repeats its title nor draws a chart of zeros. +void main() { + late _Gateway gateway; + late RunsController controller; + + setUp(() { + gateway = _Gateway(); + controller = RunsController(RunsRepository(gateway)); + }); + + tearDown(() async { + controller.dispose(); + await gateway.framesController.close(); + }); + + Future mount( + WidgetTester tester, { + required bool cupertino, + String? createdAt, + }) async { + tester.view.physicalSize = const Size(800, 1400); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + final at = createdAt ?? DateTime.now().toIso8601String(); + gateway.reply = { + 'runs': [ + { + 'id': 1, + 'pipeline_id': 9, + 'name': 'Alpha', + 'status': 'running', + 'created_at': at, + 'scheduled': true, + }, + ], + }; + await controller.load(); + final list = AnimatedBuilder( + animation: controller, + builder: (context, _) => + RunsList(controller: controller, onSelected: (_) {}), + ); + await tester.pumpWidget( + cupertino + ? CupertinoApp(home: CupertinoPageScaffold(child: list)) + : MaterialApp(home: Scaffold(body: list)), + ); + await tester.pumpAndSettle(); + } + + for (final cupertino in [false, true]) { + final host = cupertino ? 'Cupertino' : 'Material'; + + testWidgets('$host filter sheet has a header whose Done closes it', ( + tester, + ) async { + await mount(tester, cupertino: cupertino); + await tester.tap(find.byKey(const ValueKey('runs.filter'))); + await tester.pumpAndSettle(); + + expect(find.byType(AppSheetHeader), findsOneWidget); + expect( + find.descendant( + of: find.byType(AppSheetHeader), + matching: find.text(runsFilterTitle), + ), + findsOneWidget, + ); + expect(find.text('Queued'), findsOneWidget); + expect(find.text('queued'), findsNothing); + expect(find.byKey(runsFilterClearKey), findsNothing); + + await tester.tap(find.text('Last 7 days')); + await tester.pumpAndSettle(); + expect(controller.timeRange, 'last_7_days'); + // An active filter offers Clear in the header. + expect(find.byKey(runsFilterClearKey), findsOneWidget); + + await tester.tap(find.byKey(runsFilterDoneKey)); + await tester.pumpAndSettle(); + expect(find.byKey(const ValueKey('runs.filter.sheet')), findsNothing); + // The applied chip reads in sentence case too. + expect(find.textContaining('Last 7 days'), findsOneWidget); + }); + } + + testWidgets('Material single-choice groups are check rows, not checkboxes', ( + tester, + ) async { + await mount(tester, cupertino: false); + await tester.tap(find.byKey(const ValueKey('runs.filter'))); + await tester.pumpAndSettle(); + + // Seven statuses may be combined: those keep their checkboxes. + expect(find.byType(CheckboxListTile), findsNWidgets(7)); + final anyTime = find.widgetWithText(ListTile, 'Any time'); + expect(anyTime, findsOneWidget); + expect( + find.descendant(of: anyTime, matching: find.byIcon(Icons.check)), + findsOneWidget, + ); + expect( + find.descendant(of: anyTime, matching: find.byType(Checkbox)), + findsNothing, + ); + final today = find.widgetWithText(ListTile, 'Today'); + expect( + find.descendant(of: today, matching: find.byIcon(Icons.check)), + findsNothing, + ); + expect(tester.widget(anyTime).selected, isTrue); + }); + + testWidgets('Material sort sheet has the same header', (tester) async { + await mount(tester, cupertino: false); + await tester.tap(find.byKey(const ValueKey('runs.sort'))); + await tester.pumpAndSettle(); + expect(find.text(runsSortTitle), findsOneWidget); + await tester.tap(find.byKey(runsSortDoneKey)); + await tester.pumpAndSettle(); + expect(find.text(runsSortTitle), findsNothing); + expect(controller.sort, 'newest_first'); + }); + + testWidgets('the usage page is honest when nothing was reported', ( + tester, + ) async { + await mount( + tester, + cupertino: false, + createdAt: DateTime(2020, 1, 1).toIso8601String(), + ); + await tester.tap(find.byKey(const ValueKey('runs.stats'))); + await tester.pumpAndSettle(); + + // The bar says Usage; the body does not repeat it. + expect(find.text('Usage'), findsOneWidget); + expect(find.byKey(const ValueKey('runs.stats.usage.empty')), findsOne); + expect(find.byKey(const ValueKey('runs.stats.days')), findsNothing); + expect(find.byKey(const ValueKey('runs.stats.days.empty')), findsOne); + expect(find.text('Running'), findsOneWidget); + expect(find.text('0'), findsNothing); + }); + + testWidgets('the 7-day chart shows bars over an axis when runs started', ( + tester, + ) async { + await mount(tester, cupertino: true); + await tester.tap(find.byKey(const ValueKey('runs.stats'))); + await tester.pumpAndSettle(); + expect(find.byKey(const ValueKey('runs.stats.days')), findsOneWidget); + expect(find.byKey(const ValueKey('runs.stats.days.empty')), findsNothing); + // Only the day with a run is labelled with its count. + final days = find.byKey(const ValueKey('runs.stats.days')); + expect(find.descendant(of: days, matching: find.text('1')), findsOne); + expect(find.text('0'), findsNothing); + expect(tester.takeException(), isNull); + }); +} diff --git a/app/test/features/runs/ui/runs_toolbar_test.dart b/app/test/features/runs/ui/runs_toolbar_test.dart index f5a31d22..ad12bd07 100644 --- a/app/test/features/runs/ui/runs_toolbar_test.dart +++ b/app/test/features/runs/ui/runs_toolbar_test.dart @@ -70,18 +70,22 @@ void main() { await tester.pumpAndSettle(); } - Future reveal(WidgetTester tester, Finder target) => - tester.scrollUntilVisible( - target, - 80, - // The sheet's own list, not the search field's inner scrollable. - scrollable: find - .descendant( - of: find.byKey(const ValueKey('runs.filter.sheet')), - matching: find.byType(Scrollable), - ) - .first, - ); + Future reveal(WidgetTester tester, Finder target) async { + await tester.scrollUntilVisible( + target, + 80, + // The sheet's own list, not the search field's inner scrollable. + scrollable: find + .descendant( + of: find.byKey(const ValueKey('runs.filter.sheet')), + matching: find.byType(Scrollable), + ) + .first, + ); + // Built is not on screen: bring the row fully inside the sheet. + await tester.ensureVisible(target); + await tester.pumpAndSettle(); + } Future closeSheet(WidgetTester tester) async { await tester.tapAt(const Offset(4, 4)); @@ -148,7 +152,7 @@ void main() { await tester.tap(find.byKey(const ValueKey('runs.filter'))); await tester.pumpAndSettle(); expect(find.byType(CupertinoSearchTextField), findsOneWidget); - final failed = find.widgetWithText(CupertinoListTile, 'failed'); + final failed = find.widgetWithText(CupertinoListTile, 'Failed'); await reveal(tester, failed); await tester.pumpAndSettle(); await tester.tap(failed); @@ -156,7 +160,7 @@ void main() { expect(controller.statuses, {'failed'}); await closeSheet(tester); - final failedChip = find.widgetWithText(CupertinoButton, 'failed'); + final failedChip = find.widgetWithText(CupertinoButton, 'Failed'); expect(failedChip, findsOneWidget); expect(find.text('Alpha'), findsNothing); await tester.tap(failedChip); diff --git a/app/test/features/settings/settings_screen_test.dart b/app/test/features/settings/settings_screen_test.dart index 1eb8587e..a217a34f 100644 --- a/app/test/features/settings/settings_screen_test.dart +++ b/app/test/features/settings/settings_screen_test.dart @@ -154,6 +154,15 @@ void main() { expect(find.text('Server time 2026-10-21T12:00:00Z'), findsOneWidget); expect(find.byKey(SettingsKeys.disconnect), findsOneWidget); expect(find.byKey(SettingsKeys.connect), findsOneWidget); + // Beside Disconnect, the second action reconnects; it never says Connect. + expect( + find.descendant( + of: find.byKey(SettingsKeys.connect), + matching: find.text('Reconnect'), + ), + findsOneWidget, + ); + expect(find.text('Connect'), findsNothing); // The only other request is the ntfy settings load, queued behind ping. _answerNtfySettings(factory.last); await tester.pump(); From 05a06e8f08fa430e9e150114a98e8aacf4df473a Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Sat, 31 Oct 2026 12:19:03 +0000 Subject: [PATCH 05/14] Drop unused test imports --- app/test/features/runs/ui/runs_sheets_test.dart | 1 - app/test/features/templates/ui/template_layout_test.dart | 1 - 2 files changed, 2 deletions(-) diff --git a/app/test/features/runs/ui/runs_sheets_test.dart b/app/test/features/runs/ui/runs_sheets_test.dart index d423b3b4..34d79db5 100644 --- a/app/test/features/runs/ui/runs_sheets_test.dart +++ b/app/test/features/runs/ui/runs_sheets_test.dart @@ -9,7 +9,6 @@ import 'package:pipelines_app/features/runs/ui/runs_controller.dart'; import 'package:pipelines_app/features/runs/ui/runs_filter_sheet.dart'; import 'package:pipelines_app/features/runs/ui/runs_filters.dart'; import 'package:pipelines_app/features/runs/ui/runs_list.dart'; -import 'package:pipelines_app/features/runs/ui/runs_stats_page.dart'; import 'package:pipelines_app/ui/layout/app_sheet_header.dart'; class _Gateway implements ApiGateway { diff --git a/app/test/features/templates/ui/template_layout_test.dart b/app/test/features/templates/ui/template_layout_test.dart index 2104f768..85e447e6 100644 --- a/app/test/features/templates/ui/template_layout_test.dart +++ b/app/test/features/templates/ui/template_layout_test.dart @@ -1,7 +1,6 @@ import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:pipelines_app/features/templates/screen.dart'; -import 'package:pipelines_app/features/templates/ui/template_detail.dart'; import 'package:pipelines_app/features/templates/ui/template_gallery.dart'; import 'package:pipelines_app/ui/adaptive/segmented_bar.dart'; From 1423159839e40cb25503668b82d1082d00042f1d Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Sat, 31 Oct 2026 12:20:37 +0000 Subject: [PATCH 06/14] Note the run detail tabs test update --- app/notes/wide-shell-fixes.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/app/notes/wide-shell-fixes.md b/app/notes/wide-shell-fixes.md index d37bd758..ad8277c6 100644 --- a/app/notes/wide-shell-fixes.md +++ b/app/notes/wide-shell-fixes.md @@ -107,6 +107,8 @@ Updated: - The pipelines tests (placeholder wording). - `chat_list_detail_test.dart`, `pipelines_screen_test.dart` and `runs_screen_test.dart` now assert `EmptyDetailPane`. +- `run_detail_tabs_test.dart`: at 1000 the Summary body is now + `kReadingMaxWidth` wide from x=0 instead of spanning the window. ## Evidence From f4b3ef17cc3c223878c7310729bd6f6b4dd7cade Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Sat, 31 Oct 2026 12:23:51 +0000 Subject: [PATCH 07/14] Persist and broadcast shared attention acknowledgements --- internal/pipeline/attention_acks.go | 172 +++++++++++++++++++++++ internal/pipeline/attention_acks_test.go | 166 ++++++++++++++++++++++ internal/pipeline/store.go | 4 + internal/protocol/attention_acks.go | 89 ++++++++++++ internal/protocol/attention_acks_test.go | 37 +++++ internal/protocol/message.go | 4 + internal/server/attention_acks.go | 90 ++++++++++++ internal/server/attention_acks_test.go | 110 +++++++++++++++ internal/server/websocket.go | 12 ++ 9 files changed, 684 insertions(+) create mode 100644 internal/pipeline/attention_acks.go create mode 100644 internal/pipeline/attention_acks_test.go create mode 100644 internal/protocol/attention_acks.go create mode 100644 internal/protocol/attention_acks_test.go create mode 100644 internal/server/attention_acks.go create mode 100644 internal/server/attention_acks_test.go diff --git a/internal/pipeline/attention_acks.go b/internal/pipeline/attention_acks.go new file mode 100644 index 00000000..7012b94d --- /dev/null +++ b/internal/pipeline/attention_acks.go @@ -0,0 +1,172 @@ +package pipeline + +import ( + "context" + "database/sql" + "sort" + "strconv" + "strings" + "time" + + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +// AttentionAckRetention bounds how long an acknowledgement is kept. The +// Needs-you list shows only today's work and a chat watermark is refreshed +// whenever the chat is opened, so a month-old acknowledgement protects nothing. +const AttentionAckRetention = 30 * 24 * time.Hour + +// initAttentionAcks creates the two additive acknowledgement tables. They are +// tables of their own so no run or session schema changes; run_id is kept as a +// column so pruning against pipeline_runs uses an integer comparison. +func (s *Store) initAttentionAcks() error { + _, err := s.db.Exec(`CREATE TABLE IF NOT EXISTS attention_dismissals ( +key TEXT PRIMARY KEY, run_id INTEGER NOT NULL, dismissed_at INTEGER NOT NULL); +CREATE TABLE IF NOT EXISTS chat_seen_watermarks ( +session_id TEXT PRIMARY KEY, seen_at INTEGER NOT NULL, acked_at INTEGER NOT NULL);`) + return err +} + +type attentionQuerier interface { + QueryContext(context.Context, string, ...any) (*sql.Rows, error) +} + +func readAttentionAcks(ctx context.Context, q attentionQuerier) (protocol.AttentionAcks, error) { + acks := protocol.AttentionAcks{Dismissed: []string{}, ChatSeen: map[string]int64{}} + rows, err := q.QueryContext(ctx, `SELECT key FROM attention_dismissals ORDER BY key`) + if err != nil { + return acks, err + } + for rows.Next() { + var key string + if err := rows.Scan(&key); err != nil { + rows.Close() + return acks, err + } + acks.Dismissed = append(acks.Dismissed, key) + } + rows.Close() + if err := rows.Err(); err != nil { + return acks, err + } + rows, err = q.QueryContext(ctx, `SELECT session_id, seen_at FROM chat_seen_watermarks`) + if err != nil { + return acks, err + } + defer rows.Close() + for rows.Next() { + var id string + var at int64 + if err := rows.Scan(&id, &at); err != nil { + return acks, err + } + acks.ChatSeen[id] = at + } + return acks, rows.Err() +} + +// AttentionAcks returns every stored acknowledgement. +func (s *Store) AttentionAcks(ctx context.Context) (protocol.AttentionAcks, error) { + return readAttentionAcks(ctx, s.db) +} + +// AckAttention validates and records one acknowledgement, prunes stale rows, +// and returns the delta that actually changed the stored set together with the +// whole set afterwards. +// +// A dismissal of a run that does not exist is skipped, and so is a watermark +// for a session that is not in the operator registry, so a client cannot grow +// the tables with invented ids. A watermark only advances: the stored value is +// the maximum of the old value, the client's value and the session's own +// registry recency, so a device that opened the chat from a stale list row +// still acknowledges everything the server listed at that moment. +func (s *Store) AckAttention(ctx context.Context, ack *protocol.AttentionAcks, now time.Time) (delta, all protocol.AttentionAcks, err error) { + valid, err := protocol.ValidateAttentionAck(ack) + if err != nil { + return delta, all, err + } + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return delta, all, err + } + defer tx.Rollback() + nowMillis := now.UnixMilli() + delta = protocol.AttentionAcks{Dismissed: []string{}, ChatSeen: map[string]int64{}} + for _, key := range valid.Dismissed { + runID, _ := strconv.ParseInt(key[:strings.IndexByte(key, ':')], 10, 64) + result, err := tx.ExecContext(ctx, `INSERT INTO attention_dismissals(key, run_id, dismissed_at) +SELECT ?, id, ? FROM pipeline_runs WHERE id=? ON CONFLICT(key) DO NOTHING`, key, nowMillis, runID) + if err != nil { + return delta, all, err + } + if n, _ := result.RowsAffected(); n > 0 { + delta.Dismissed = append(delta.Dismissed, key) + } + } + ids := make([]string, 0, len(valid.ChatSeen)) + for id := range valid.ChatSeen { + ids = append(ids, id) + } + sort.Strings(ids) + for _, id := range ids { + var recency, stored int64 + var hasStored bool + err := tx.QueryRowContext(ctx, `SELECT last_used_at FROM operator_sessions WHERE session_id=?`, id).Scan(&recency) + if err == sql.ErrNoRows { + continue + } + if err != nil { + return delta, all, err + } + switch err := tx.QueryRowContext(ctx, `SELECT seen_at FROM chat_seen_watermarks WHERE session_id=?`, id).Scan(&stored); err { + case nil: + hasStored = true + case sql.ErrNoRows: + default: + return delta, all, err + } + next := max(valid.ChatSeen[id], recency, stored) + if _, err := tx.ExecContext(ctx, `INSERT INTO chat_seen_watermarks(session_id, seen_at, acked_at) VALUES(?,?,?) +ON CONFLICT(session_id) DO UPDATE SET seen_at=excluded.seen_at, acked_at=excluded.acked_at`, id, next, nowMillis); err != nil { + return delta, all, err + } + if !hasStored || next > stored { + delta.ChatSeen[id] = next + } + } + if err := pruneAttentionAcks(ctx, tx, now); err != nil { + return delta, all, err + } + all, err = readAttentionAcks(ctx, tx) + if err != nil { + return delta, all, err + } + return delta, all, tx.Commit() +} + +// PruneAttentionAcks drops acknowledgements for runs and sessions that no +// longer exist and any older than AttentionAckRetention. +func (s *Store) PruneAttentionAcks(ctx context.Context, now time.Time) error { + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + if err := pruneAttentionAcks(ctx, tx, now); err != nil { + return err + } + return tx.Commit() +} + +func pruneAttentionAcks(ctx context.Context, tx *sql.Tx, now time.Time) error { + cutoff := now.Add(-AttentionAckRetention).UnixMilli() + for _, statement := range []string{ + `DELETE FROM attention_dismissals WHERE dismissed_at < ? OR run_id NOT IN (SELECT id FROM pipeline_runs)`, + `DELETE FROM chat_seen_watermarks WHERE acked_at < ? OR session_id NOT IN (SELECT session_id FROM operator_sessions)`, + } { + if _, err := tx.ExecContext(ctx, statement, cutoff); err != nil { + return err + } + } + return nil +} diff --git a/internal/pipeline/attention_acks_test.go b/internal/pipeline/attention_acks_test.go new file mode 100644 index 00000000..0498227f --- /dev/null +++ b/internal/pipeline/attention_acks_test.go @@ -0,0 +1,166 @@ +package pipeline + +import ( + "context" + "fmt" + "path/filepath" + "reflect" + "testing" + "time" + + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +func attentionAckFixture(t *testing.T) (*Store, string, []int64) { + t.Helper() + ctx := context.Background() + path := filepath.Join(t.TempDir(), "acks.db") + s, err := Open(path) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { s.Close() }) + if _, err := s.Submit(ctx, "acks", Template([]string{"one"}, true)); err != nil { + t.Fatal(err) + } + items, err := s.List(ctx) + if err != nil { + t.Fatal(err) + } + definition, err := s.Get(ctx, items[0].ID, 1) + if err != nil { + t.Fatal(err) + } + var runs []int64 + for i := range 2 { + id, _, err := s.CreateRun(ctx, definition, fmt.Sprintf("ack-%d", i), "/work/acks", false, nil, map[string]any{"prompt": "task"}) + if err != nil { + t.Fatal(err) + } + runs = append(runs, id) + } + if err := s.RecordOperatorSession(ctx, "ses_seen", "/work/acks", "Seen", "operator"); err != nil { + t.Fatal(err) + } + return s, path, runs +} + +func TestAttentionAcksPersistAdvanceAndSkipUnknown(t *testing.T) { + ctx := context.Background() + s, path, runs := attentionAckFixture(t) + empty, err := s.AttentionAcks(ctx) + if err != nil || len(empty.Dismissed) != 0 || len(empty.ChatSeen) != 0 { + t.Fatalf("fresh acks = %+v, %v", empty, err) + } + session, _, err := s.OperatorSession(ctx, "ses_seen") + if err != nil { + t.Fatal(err) + } + failed := fmt.Sprintf("%d:Failed", runs[0]) + decision := fmt.Sprintf("%d:Decision", runs[1]) + now := time.Now() + delta, all, err := s.AckAttention(ctx, &protocol.AttentionAcks{ + Dismissed: []string{failed, failed, decision, "999999:Failed"}, + ChatSeen: map[string]int64{"ses_seen": session.UpdatedAt + 5, "ses_gone": 10}, + }, now) + if err != nil { + t.Fatal(err) + } + wantKeys := []string{decision, failed} + if decision > failed { + wantKeys = []string{failed, decision} + } + if !reflect.DeepEqual(delta.Dismissed, wantKeys) || !reflect.DeepEqual(all.Dismissed, wantKeys) { + t.Fatalf("dismissed delta=%v all=%v, want %v (unknown run skipped)", delta.Dismissed, all.Dismissed, wantKeys) + } + if len(delta.ChatSeen) != 1 || delta.ChatSeen["ses_seen"] != session.UpdatedAt+5 || len(all.ChatSeen) != 1 { + t.Fatalf("chat seen delta=%v all=%v", delta.ChatSeen, all.ChatSeen) + } + // A repeated dismissal and an older watermark change nothing: the stored + // value never moves backwards and the delta is empty. + delta, all, err = s.AckAttention(ctx, &protocol.AttentionAcks{Dismissed: []string{failed}, ChatSeen: map[string]int64{"ses_seen": 1}}, now) + if err != nil || !delta.Empty() || all.ChatSeen["ses_seen"] != session.UpdatedAt+5 { + t.Fatalf("repeat delta=%+v all=%+v err=%v", delta, all, err) + } + // A stale client value is lifted to the session's registry recency. + recency := session.UpdatedAt + 60_000 + if _, err := s.db.ExecContext(ctx, `UPDATE operator_sessions SET last_used_at=? WHERE session_id='ses_seen'`, recency); err != nil { + t.Fatal(err) + } + delta, _, err = s.AckAttention(ctx, &protocol.AttentionAcks{ChatSeen: map[string]int64{"ses_seen": 1}}, now) + if err != nil || delta.ChatSeen["ses_seen"] != recency { + t.Fatalf("lifted delta=%+v err=%v (recency %d)", delta, err, recency) + } + if err := s.Close(); err != nil { + t.Fatal(err) + } + reopened, err := Open(path) + if err != nil { + t.Fatal(err) + } + defer reopened.Close() + again, err := reopened.AttentionAcks(ctx) + if err != nil || !reflect.DeepEqual(again.Dismissed, wantKeys) || again.ChatSeen["ses_seen"] == 0 { + t.Fatalf("after reopen = %+v, %v", again, err) + } +} + +func TestAttentionAcksPruneDeletedAndExpired(t *testing.T) { + ctx := context.Background() + s, _, runs := attentionAckFixture(t) + now := time.Now() + old := now.Add(-AttentionAckRetention - time.Hour) + if _, _, err := s.AckAttention(ctx, &protocol.AttentionAcks{Dismissed: []string{fmt.Sprintf("%d:Failed", runs[0])}}, old); err != nil { + t.Fatal(err) + } + if _, _, err := s.AckAttention(ctx, &protocol.AttentionAcks{ + Dismissed: []string{fmt.Sprintf("%d:Failed", runs[1])}, + ChatSeen: map[string]int64{"ses_seen": 5}, + }, now); err != nil { + t.Fatal(err) + } + all, _ := s.AttentionAcks(ctx) + if len(all.Dismissed) != 1 || all.Dismissed[0] != fmt.Sprintf("%d:Failed", runs[1]) { + t.Fatalf("expired dismissal not pruned: %+v", all) + } + if _, err := s.db.ExecContext(ctx, `DELETE FROM pipeline_runs WHERE id=?`, runs[1]); err != nil { + t.Fatal(err) + } + if _, err := s.db.ExecContext(ctx, `DELETE FROM operator_sessions WHERE session_id='ses_seen'`); err != nil { + t.Fatal(err) + } + if err := s.PruneAttentionAcks(ctx, now); err != nil { + t.Fatal(err) + } + all, err := s.AttentionAcks(ctx) + if err != nil || len(all.Dismissed) != 0 || len(all.ChatSeen) != 0 { + t.Fatalf("acks for deleted run/session not pruned: %+v, %v", all, err) + } +} + +func TestAttentionAcksRejectMalformed(t *testing.T) { + ctx := context.Background() + s, _, runs := attentionAckFixture(t) + tooMany := make([]string, protocol.MaxAttentionAckItems+1) + for i := range tooMany { + tooMany[i] = fmt.Sprintf("%d:Failed", i+1) + } + for name, ack := range map[string]*protocol.AttentionAcks{ + "nil": nil, + "empty": {}, + "kind": {Dismissed: []string{fmt.Sprintf("%d:Running", runs[0])}}, + "zero run": {Dismissed: []string{"0:Failed"}}, + "bare": {Dismissed: []string{"Failed"}}, + "session id": {ChatSeen: map[string]int64{"../etc": 4}}, + "non-positive": {ChatSeen: map[string]int64{"ses_seen": 0}}, + "too many": {Dismissed: tooMany}, + } { + if _, _, err := s.AckAttention(ctx, ack, time.Now()); err == nil { + t.Errorf("%s: malformed ack accepted", name) + } + } + all, _ := s.AttentionAcks(ctx) + if !all.Empty() { + t.Fatalf("a refused ack wrote something: %+v", all) + } +} diff --git a/internal/pipeline/store.go b/internal/pipeline/store.go index fe412ae3..7f5a844d 100644 --- a/internal/pipeline/store.go +++ b/internal/pipeline/store.go @@ -77,6 +77,10 @@ CREATE TABLE IF NOT EXISTS submissions (id INTEGER PRIMARY KEY, name TEXT NOT NU db.Close() return nil, err } + if err := s.initAttentionAcks(); err != nil { + db.Close() + return nil, err + } return s, nil } diff --git a/internal/protocol/attention_acks.go b/internal/protocol/attention_acks.go new file mode 100644 index 00000000..15676f96 --- /dev/null +++ b/internal/protocol/attention_acks.go @@ -0,0 +1,89 @@ +package protocol + +import ( + "fmt" + "regexp" + "sort" +) + +// Attention acknowledgements are the operator's in-app "I have seen this" +// state, shared by every connected client so clearing on one device clears +// everywhere. A client reads the whole set with {"type":"attention_acks"} and +// adds to it with +// +// {"type":"ack_attention","attention_acks":{"dismissed":["42:Failed"],"chat_seen":{"ses_x":1730000000000}}} +// +// Both reply with type "attention_acks" carrying the whole stored set. After an +// accepted ack, every other connection receives an unsolicited +// {"type":"attention_acks_changed","attention_acks":{...}} frame holding only +// what that ack changed. The set only grows (dismissals are added, watermarks +// only advance), so applying frames in any order or twice is harmless. +// +// A dismissal identity is ":", the Needs-you entry +// identity. Clear all is a batch of the identities the client showed, so an +// entry that appears later is never hidden by an earlier clear. A chat_seen +// value is the chat session's updated_at (epoch milliseconds) the operator has +// read up to. +const ( + GetAttentionAcks = "attention_acks" + AckAttention = "ack_attention" + AttentionAcksReply = "attention_acks" + AttentionAcksChanged = "attention_acks_changed" +) + +// MaxAttentionAckItems bounds the dismissals plus watermarks one ack may carry. +const MaxAttentionAckItems = 500 + +// AttentionAcks is the wire form of the acknowledgement set (or a delta of it). +type AttentionAcks struct { + Dismissed []string `json:"dismissed"` + ChatSeen map[string]int64 `json:"chat_seen"` +} + +var attentionKeyPattern = regexp.MustCompile(`^[1-9][0-9]{0,18}:(Decision|Failed)$`) + +// chatSeenIDPattern mirrors the server's chat session id shapes (OpenCode +// ses_…, Codex/Claude UUIDs). +var chatSeenIDPattern = regexp.MustCompile(`^(?:ses_[A-Za-z0-9_]+|[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$`) + +// ValidAttentionKey reports whether key is a ":" identity. +func ValidAttentionKey(key string) bool { return attentionKeyPattern.MatchString(key) } + +// ValidateAttentionAck checks one ack request: at least one item, at most +// MaxAttentionAckItems, every dismissal a valid identity, and every watermark a +// valid chat session id with a positive millisecond value. It returns the +// dismissals deduplicated and sorted. +func ValidateAttentionAck(ack *AttentionAcks) (AttentionAcks, error) { + if ack == nil || len(ack.Dismissed)+len(ack.ChatSeen) == 0 { + return AttentionAcks{}, fmt.Errorf("attention_acks must name at least one dismissal or chat_seen watermark") + } + if len(ack.Dismissed)+len(ack.ChatSeen) > MaxAttentionAckItems { + return AttentionAcks{}, fmt.Errorf("attention_acks may carry at most %d items", MaxAttentionAckItems) + } + seen := make(map[string]struct{}, len(ack.Dismissed)) + result := AttentionAcks{Dismissed: []string{}, ChatSeen: map[string]int64{}} + for _, key := range ack.Dismissed { + if !ValidAttentionKey(key) { + return AttentionAcks{}, fmt.Errorf("invalid attention identity %q", key) + } + if _, dup := seen[key]; dup { + continue + } + seen[key] = struct{}{} + result.Dismissed = append(result.Dismissed, key) + } + sort.Strings(result.Dismissed) + for id, at := range ack.ChatSeen { + if !chatSeenIDPattern.MatchString(id) { + return AttentionAcks{}, fmt.Errorf("invalid chat session id %q", id) + } + if at <= 0 { + return AttentionAcks{}, fmt.Errorf("chat_seen %q must be a positive epoch-millisecond time", id) + } + result.ChatSeen[id] = at + } + return result, nil +} + +// Empty reports whether the set carries nothing. +func (a AttentionAcks) Empty() bool { return len(a.Dismissed) == 0 && len(a.ChatSeen) == 0 } diff --git a/internal/protocol/attention_acks_test.go b/internal/protocol/attention_acks_test.go new file mode 100644 index 00000000..5cc0970c --- /dev/null +++ b/internal/protocol/attention_acks_test.go @@ -0,0 +1,37 @@ +package protocol + +import ( + "encoding/json" + "reflect" + "testing" +) + +func TestValidateAttentionAckDedupesAndRefuses(t *testing.T) { + got, err := ValidateAttentionAck(&AttentionAcks{ + Dismissed: []string{"9:Failed", "12:Decision", "9:Failed"}, + ChatSeen: map[string]int64{"ses_a1": 7, "0123abcd-0123-4567-89ab-0123456789ab": 8}, + }) + if err != nil || !reflect.DeepEqual(got.Dismissed, []string{"12:Decision", "9:Failed"}) || len(got.ChatSeen) != 2 { + t.Fatalf("valid ack = %+v, %v", got, err) + } + for _, bad := range []*AttentionAcks{nil, {}, {Dismissed: []string{"-1:Failed"}}, {Dismissed: []string{"1:failed"}}, {ChatSeen: map[string]int64{"ses_x": -1}}, {ChatSeen: map[string]int64{"ses x": 1}}} { + if _, err := ValidateAttentionAck(bad); err == nil { + t.Errorf("accepted %+v", bad) + } + } +} + +func TestAttentionAcksWireShape(t *testing.T) { + raw := `{"type":"ack_attention","id":"1","attention_acks":{"dismissed":["3:Failed"],"chat_seen":{"ses_q":5}}}` + var message Message + if err := json.Unmarshal([]byte(raw), &message); err != nil { + t.Fatal(err) + } + if message.Type != AckAttention || message.AttentionAcks == nil || message.AttentionAcks.Dismissed[0] != "3:Failed" || message.AttentionAcks.ChatSeen["ses_q"] != 5 { + t.Fatalf("decoded = %+v", message) + } + out, _ := json.Marshal(Message{Type: AttentionAcksChanged, AttentionAcks: &AttentionAcks{Dismissed: []string{}, ChatSeen: map[string]int64{}}}) + if string(out) == "" || !json.Valid(out) { + t.Fatal("unencodable") + } +} diff --git a/internal/protocol/message.go b/internal/protocol/message.go index a87201da..57401d18 100644 --- a/internal/protocol/message.go +++ b/internal/protocol/message.go @@ -241,4 +241,8 @@ type Message struct { // NotificationSettings is the set_notification_settings partial update and // the notification_settings reply (every key). See notification_settings.go. NotificationSettings map[string]any `json:"notification_settings,omitempty"` + // AttentionAcks is the ack_attention body, the attention_acks reply (the + // whole set) and the attention_acks_changed push (the delta). See + // attention_acks.go. + AttentionAcks *AttentionAcks `json:"attention_acks,omitempty"` } diff --git a/internal/server/attention_acks.go b/internal/server/attention_acks.go new file mode 100644 index 00000000..280d5962 --- /dev/null +++ b/internal/server/attention_acks.go @@ -0,0 +1,90 @@ +package server + +import ( + "context" + "sync" + "time" + + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +// attentionAckStore persists the shared in-app acknowledgements. +// *pipeline.Store implements it. +type attentionAckStore interface { + AttentionAcks(context.Context) (protocol.AttentionAcks, error) + AckAttention(context.Context, *protocol.AttentionAcks, time.Time) (delta, all protocol.AttentionAcks, err error) +} + +// attentionAckHub fans an accepted acknowledgement out to every other open +// connection, so a dismissal on one device disappears on the others live. +// It holds each connection's serialized write function, never the socket. +type attentionAckHub struct { + mu sync.Mutex + clients map[string]func(protocol.Message) error +} + +func newAttentionAckHub() *attentionAckHub { + return &attentionAckHub{clients: map[string]func(protocol.Message) error{}} +} + +func (h *attentionAckHub) attach(clientID string, write func(protocol.Message) error) { + h.mu.Lock() + defer h.mu.Unlock() + h.clients[clientID] = write +} + +func (h *attentionAckHub) detach(clientID string) { + h.mu.Lock() + defer h.mu.Unlock() + delete(h.clients, clientID) +} + +// broadcast pushes delta to every connection except the sender. Each write +// runs on its own goroutine (bounded by the connection's own write timeout), so +// one slow client cannot delay the sender's reply or the other clients. +func (h *attentionAckHub) broadcast(sender string, delta protocol.AttentionAcks) { + h.mu.Lock() + targets := make([]func(protocol.Message) error, 0, len(h.clients)) + for id, write := range h.clients { + if id != sender { + targets = append(targets, write) + } + } + h.mu.Unlock() + for _, write := range targets { + frame := delta + go func() { + _ = write(protocol.Message{Type: protocol.AttentionAcksChanged, AttentionAcks: &frame}) + }() + } +} + +// handleAttentionAcks answers attention_acks and ack_attention. It reports +// whether request was one of them. An ack that changes nothing (already +// dismissed, or a watermark that does not advance) replies with the whole set +// but pushes nothing. +func handleAttentionAcks(ctx context.Context, request protocol.Message, store attentionAckStore, hub *attentionAckHub, clientID string, write func(protocol.Message) error) bool { + if request.Type != protocol.GetAttentionAcks && request.Type != protocol.AckAttention { + return false + } + if store == nil { + _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "attention acknowledgements are unavailable: no store"}) + return true + } + var all, delta protocol.AttentionAcks + var err error + if request.Type == protocol.GetAttentionAcks { + all, err = store.AttentionAcks(ctx) + } else { + delta, all, err = store.AckAttention(ctx, request.AttentionAcks, time.Now()) + } + if err != nil { + _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()}) + return true + } + _ = write(protocol.Message{Type: protocol.AttentionAcksReply, ID: request.ID, AttentionAcks: &all}) + if hub != nil && !delta.Empty() { + hub.broadcast(clientID, delta) + } + return true +} diff --git a/internal/server/attention_acks_test.go b/internal/server/attention_acks_test.go new file mode 100644 index 00000000..775cfcac --- /dev/null +++ b/internal/server/attention_acks_test.go @@ -0,0 +1,110 @@ +package server + +import ( + "context" + "fmt" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/coder/websocket" + "github.com/coder/websocket/wsjson" + + "git.a-wan.net/alan/pipelines/internal/pipeline" + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +func dialAckClient(t *testing.T, ctx context.Context, url string) *websocket.Conn { + t.Helper() + conn, _, err := websocket.Dial(ctx, "ws"+strings.TrimPrefix(url, "http")+"/connect", nil) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { conn.CloseNow() }) + var welcome protocol.Message + if err := wsjson.Read(ctx, conn, &welcome); err != nil { + t.Fatal(err) + } + return conn +} + +func ackExchange(t *testing.T, ctx context.Context, conn *websocket.Conn, request protocol.Message) protocol.Message { + t.Helper() + if err := wsjson.Write(ctx, conn, request); err != nil { + t.Fatal(err) + } + var reply protocol.Message + if err := wsjson.Read(ctx, conn, &reply); err != nil { + t.Fatal(err) + } + return reply +} + +func TestAttentionAcksSyncAcrossConnections(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + store := newOperatorStore(t) + if _, err := store.Submit(ctx, "acks", pipeline.Template([]string{"one"}, true)); err != nil { + t.Fatal(err) + } + items, err := store.List(ctx) + if err != nil { + t.Fatal(err) + } + definition, err := store.Get(ctx, items[0].ID, 1) + if err != nil { + t.Fatal(err) + } + run, _, err := store.CreateRun(ctx, definition, "ack-run", t.TempDir(), false, nil, map[string]any{"prompt": "task"}) + if err != nil { + t.Fatal(err) + } + if err := store.RecordOperatorSession(ctx, "ses_sync", "/work", "Sync", "operator"); err != nil { + t.Fatal(err) + } + handlerCtx, stop := context.WithCancel(ctx) + handler := Handler(handlerCtx, store) + defer func() { stop(); WaitRuns(handler) }() + srv := httptest.NewServer(handler) + defer srv.Close() + web := dialAckClient(t, ctx, srv.URL) + phone := dialAckClient(t, ctx, srv.URL) + + initial := ackExchange(t, ctx, phone, protocol.Message{Type: protocol.GetAttentionAcks, ID: "get"}) + if initial.Type != protocol.AttentionAcksReply || initial.ID != "get" || initial.AttentionAcks == nil || !initial.AttentionAcks.Empty() { + t.Fatalf("initial = %+v", initial) + } + key := fmt.Sprintf("%d:Failed", run) + reply := ackExchange(t, ctx, web, protocol.Message{Type: protocol.AckAttention, ID: "ack", AttentionAcks: &protocol.AttentionAcks{ + Dismissed: []string{key}, + ChatSeen: map[string]int64{"ses_sync": 1}, + }}) + if reply.Type != protocol.AttentionAcksReply || reply.ID != "ack" || len(reply.AttentionAcks.Dismissed) != 1 || reply.AttentionAcks.ChatSeen["ses_sync"] == 0 { + t.Fatalf("ack reply = %+v", reply) + } + var pushed protocol.Message + if err := wsjson.Read(ctx, phone, &pushed); err != nil { + t.Fatal(err) + } + if pushed.Type != protocol.AttentionAcksChanged || pushed.ID != "" || pushed.AttentionAcks == nil || + len(pushed.AttentionAcks.Dismissed) != 1 || pushed.AttentionAcks.Dismissed[0] != key || + pushed.AttentionAcks.ChatSeen["ses_sync"] != reply.AttentionAcks.ChatSeen["ses_sync"] { + t.Fatalf("pushed = %+v", pushed) + } + + // Malformed acks are refused and push nothing: the next frame the phone + // reads is the reply to its own request. + for _, bad := range []*protocol.AttentionAcks{nil, {Dismissed: []string{"1:Running"}}, {ChatSeen: map[string]int64{"bad id": 3}}} { + refused := ackExchange(t, ctx, web, protocol.Message{Type: protocol.AckAttention, ID: "bad", AttentionAcks: bad}) + if refused.Type != protocol.Error || refused.Error == "" || refused.AttentionAcks != nil { + t.Fatalf("malformed ack accepted: %+v", refused) + } + } + // A repeated ack changes nothing and pushes nothing. + ackExchange(t, ctx, web, protocol.Message{Type: protocol.AckAttention, ID: "again", AttentionAcks: &protocol.AttentionAcks{Dismissed: []string{key}}}) + after := ackExchange(t, ctx, phone, protocol.Message{Type: protocol.GetAttentionAcks, ID: "after"}) + if after.Type != protocol.AttentionAcksReply || after.ID != "after" || len(after.AttentionAcks.Dismissed) != 1 { + t.Fatalf("phone read after malformed/repeated acks = %+v", after) + } +} diff --git a/internal/server/websocket.go b/internal/server/websocket.go index a2cfc51c..c4cbd2eb 100644 --- a/internal/server/websocket.go +++ b/internal/server/websocket.go @@ -113,6 +113,11 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin settingsStore = stores[0] } hub.settings = settingsStore + acks := newAttentionAckHub() + var ackStore attentionAckStore + if len(stores) > 0 { + ackStore = stores[0] + } mux.HandleFunc("GET /artifacts/{run}/{step}/{name...}", func(w http.ResponseWriter, r *http.Request) { if runs == nil { http.NotFound(w, r) @@ -180,6 +185,10 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin return } } + // Shared attention acknowledgements reach every open connection, after + // the welcome frame so a push never precedes it. + acks.attach(clientID, write) + defer acks.detach(clientID) for { var request protocol.Message if err := wsjson.Read(connCtx, conn, &request); err != nil { @@ -196,6 +205,9 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin if handleNotificationSettings(ctx, request, settingsStore, write) { continue } + if handleAttentionAcks(ctx, request, ackStore, acks, clientID, write) { + continue + } if handleRunEvents(request, events, runs, clientID, write) { continue } From b4273a64920bb5d677ffd3dbac7ee7c428c74b35 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Sat, 31 Oct 2026 12:25:21 +0000 Subject: [PATCH 08/14] Flatten run, stage and pipeline detail bodies; facts grid, wide run chrome, pipeline Summary rows Detail bodies are flat on the page on both hosts (no Cupertino inset groups, pinned headings on the page colour). Run and pipeline Summary share a FactsGrid that fills its width (no centred single-fact card). Missing run graph is one muted line. Beside a list the run tabs and header share one row; the duplicate Pipeline fact and the decision card-in-card are gone. Pipeline Summary: facts grid, Schedules heading with Add (no inline Refresh or paragraph), versions as AppListRow. Timeline rows are AppListRow. --- app/notes/detail-bodies-fixes.md | 170 ++++++++++++++++++ .../pipelines/pipeline_summary_flat_test.dart | 75 ++++++++ .../pipelines/pipelines_adaptive_test.dart | 9 +- .../runs/ui/run_detail_flat_bodies_test.dart | 91 ++++++++++ .../ui/run_detail_summary_fields_test.dart | 29 ++- .../runs/ui/run_detail_tabs_test.dart | 15 +- .../runs/ui/run_timeline_row_test.dart | 8 +- .../schedule_pipeline_section_test.dart | 10 +- 8 files changed, 394 insertions(+), 13 deletions(-) create mode 100644 app/notes/detail-bodies-fixes.md create mode 100644 app/test/features/pipelines/pipeline_summary_flat_test.dart create mode 100644 app/test/features/runs/ui/run_detail_flat_bodies_test.dart diff --git a/app/notes/detail-bodies-fixes.md b/app/notes/detail-bodies-fixes.md new file mode 100644 index 00000000..aa12a6d5 --- /dev/null +++ b/app/notes/detail-bodies-fixes.md @@ -0,0 +1,170 @@ +# Run, stage and pipeline detail bodies (style review round 2: B, C, E) + +These are fixes from the second style review +(`/tmp/app-style-review-r2/report-summary.md`): + +- P1-2: Cupertino summary pages were a patchwork of grouped bands. +- P2-2: run detail chrome. +- P2-3: the pipeline Summary read as a document. + +The shell, the floating destination bar, templates, settings, chat, +`segmented_bar*.dart` and `sticky_section.dart` were out of scope and are +untouched. + +## One approach: flat on the page, both hosts + +The run detail, the stage (visit) page and the pipeline detail now use the +flat list style on both hosts, as Material already did. The Cupertino page +stays the theme's page colour (`AppColors.background`: white, or `#141416` in +dark mode). Content sits directly on it: + +- facts as a grid; +- sections under quiet headings; +- rows as `AppListRow` with inset dividers. + +There is no `CupertinoListSection.insetGrouped` left in these bodies, so no +group can be nested inside another. Settings and Templates keep their grouped +background. They are lists of settings and choices, not detail documents. + +- `SectionHeadingStyle` (`lib/ui/layout/section_heading.dart`): + - On Cupertino, the background and body are now the theme's + `scaffoldBackgroundColor`, not `systemGroupedBackground`. Pinned sticky + headings (Input/Output, the artifact groups) used to be grey bands, or + black bands in dark mode. They now blend into the page, as on Material. + `sticky_section.dart` itself is unchanged. + - New `header` flag: it marks the title (only) as a heading for semantics. +- `FactsGrid` (`lib/ui/layout/facts_grid.dart`, new) is shared by the run and + pipeline Summaries: + - two facts per line below 600 wide, three from 600; + - a long (over 28 characters), `wide` or monospace value takes a whole line; + - the `Wrap` is wrapped in a full-width `SizedBox`, so a single fact sits at + x=16 instead of a half-width card centred on the page; + - no card of its own; + - optional `cupertino` override. +- Run Summary (`run_detail_tab_bodies.dart`): + - the facts are a `FactsGrid`, keeping `run-detail-summary-facts` and the + `run-detail-summary-` cell keys; + - the Cupertino Input/Output field tabs no longer wrap the body in an inset + group; + - the old `_summaryFacts` was removed. +- Timeline (`run_detail_timeline.dart`): + - rows are `AppListRow` with the status avatar (as in the runs list); + - the title is the visit, the time is the duration, and the line is the + outcome chip then `→ target`; + - inset dividers between rows, on a flat list on both hosts; + - the "Timeline" group header and the `CupertinoListTile`/`ListTile` are + gone; + - the keys `run-timeline-visit-` and `run-detail-tab-body-timeline` + are kept. +- Stage Session (`run_detail_visit_session.dart`): the Cupertino inset group + is gone, and the body is the same padded flat list as on Material. +- `ArtifactDocumentSection`: the Cupertino "Turn documents" inset group (the + group nested in the Session group) is now the same flat titled rows as on + Material, with the heading in the quiet section style. +- `ArtifactVisitList`: the grid/list switch's pinned bar was `StickyBar`, a + grouped-background band. It is now a local `PinnedHeaderSliver` on the + heading/page colour. +- The standalone `ArtifactGalleryPage` no longer forces the grouped + background on Cupertino. + +## Run detail chrome (P2-2) + +- No graph: `RunGraphPreview` now shows `runGraphMissing` as one muted line + (key `run-graph-preview-missing`). There is no 200px outlined box, and + nothing to tap or open. +- Wide (pane tabs at the top, pane at least 600 wide): + - `RunDetailWideChrome` (new, `run_detail_wide_chrome.dart`) puts the tabs + and the header (status kicker, Cancel/Retry, notices, decision banner) in + one floating row under the bar; + - the tabs lead, in line with the title pill, and take at most 60% of the + row; the header follows as a glass piece (key `run-detail-header`); + - before, this was title pill, then the status strip, then the tabs strip: + about 200px before content; + - narrower panes and phone pages keep the header strip under the bar, with + the tabs at the bottom. +- The Pipeline fact is dropped from the Summary when the run has a pipeline + name. That name is already in the bar's subtitle, and the title opens the + pipeline. `detailSummaryRows` itself is unchanged. +- Decision banner: the tinted, bordered card inside the grey header strip is + now a flat line of the strip. It keeps the teal glyph, the title over the + meta line, and Decide. The key `run-decision-banner` is kept. + +## Pipeline Summary (P2-3) + +- Facts: the five label/value rows are now a `FactsGrid` (key + `pipeline-summary-facts`, cells `pipeline-summary-`). + - The content hash takes a whole line (`wide`). It keeps the host font, + because the pipeline detail's no-monospace choice is untouched (P2-6 is + still a pending decision). + - Blank values are omitted instead of drawn empty. +- Schedules (`schedule_pipeline_list_body.dart`): + - The heading is a quiet `SectionHeading` ("Schedules (n)"), with Add as its + only trailing action: an icon button whose tooltip/semantics is "Add + schedule" (key `schedule-pipeline-add` kept). + - The inline Refresh is removed, with `scheduleRefreshKey`/`Label`. The + section reloads after every accepted mutation and has Retry on failure. + Note that the pipeline bar has no Refresh. The review assumed it did. + - The standing paragraph is gone. Its sentence is appended to the empty + state. +- Versions: + - `AppListRow` rows under a quiet "Versions" heading. The title is `vN`, the + time is the created date, and the line is `N stages`, plus `latest` when + it is the latest version. + - The shown version is the selected row (fill and selected semantics). This + replaces the check icon. + - "View latest vN" is a row too. + - Keys `pipeline-version-` and `pipeline-latest-version` are kept. + +## Tests + +- New: + - `test/features/runs/ui/run_detail_flat_bodies_test.dart`, both hosts: + - no `CupertinoListSection` on Summary or Timeline; + - the stage Session has Turn documents but no group (no nested groups); + - beside a list (`PageTabsEdge.top`, 720 wide) the header sits to the + right of the tabs and overlaps them vertically (one row); + - Cupertino heading scrim equals the page colour in light and dark. + - `test/features/pipelines/pipeline_summary_flat_test.dart`, both hosts: + - facts grid with short facts side by side; + - no Refresh, Add is an icon in the heading; + - no grouped section or `ListTile`; + - the version row is a selected `AppListRow`. +- `run_detail_summary_fields_test`: + - new single-fact case: the grid spans 900, the fact is at x=16 and left of + centre, and there is no group (the centred-card regression); + - the recorded-rows case now expects no Pipeline fact (it is in the bar). +- `run_detail_tabs_test` "missing graph": now expects one line on Summary, + with no preview, `RunGraphView` or frame, and under 60px tall. +- Updated for intentional changes: + - `run_timeline_row_test`: target and duration split; `AppListRow`, no + section; + - `pipelines_adaptive_test`: Cupertino version rows instead of + `CupertinoListTile`; + - `schedule_pipeline_section_test`: the empty text gained the note. + +## Evidence + +Captures are in `/tmp/r3-b-evidence/`. They were taken with the reviewer's +driver (`/tmp/r3-b-scripts/shoot.mjs`, a copy of +`/tmp/app-style-review-r2/shoot.mjs` pointing at this worktree's +`pipelines_wiring_probe_server.mjs`). The spec is +`/tmp/r3-b-scripts/mkspec.py`. + +- Runs: a web build of `tool/app_host_probe_entry.dart` over the wave2-e runs + fixture. +- Pipelines: the same build over `pipelines_wiring_probe_server`. +- Names: + - `{m,c}-{run1,run5,stage,pdetail}-{560,1200}-{light,dark}`; + - `{m,c}-{run1-timeline,stage-session,stage-artifacts}-560-{light,dark}`. + +There was no device run: Android and iOS are unverified. + +## Not done / notes + +- In the stage Session, the turn documents start at x=32 to 36: the list's + 16 padding plus the section's own 16. Material already rendered it this way + before this change, and it was left alone. +- Summary bodies are still uncapped on wide windows. That is batch K, which + is not in this scope. +- The 1200 Timeline/Session interactions were not captured. Only the 560 + tab clicks were scripted. diff --git a/app/test/features/pipelines/pipeline_summary_flat_test.dart b/app/test/features/pipelines/pipeline_summary_flat_test.dart new file mode 100644 index 00000000..f58a8383 --- /dev/null +++ b/app/test/features/pipelines/pipeline_summary_flat_test.dart @@ -0,0 +1,75 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/pipelines/screen.dart'; +import 'package:pipelines_app/features/pipelines/widgets/pipeline_summary_view.dart'; +import 'package:pipelines_app/features/schedules/ui/pipeline/schedule_pipeline_wording.dart'; +import 'package:pipelines_app/ui/layout/app_list_row.dart'; + +import 'fixtures.dart'; + +/// The pipeline Summary is flat on both hosts: facts in the shared grid, +/// Schedules with Add as its heading's only action (no body Refresh), and +/// versions as the shared list row. +void main() { + for (final cupertino in [false, true]) { + testWidgets('pipeline Summary is a facts grid with flat sections ' + '(${cupertino ? 'cupertino' : 'material'})', (tester) async { + final gateway = FakeGateway((type, fields) { + return switch (type) { + 'list_pipelines' => pipelineListReply([ + pipelineSummary(id: 1, name: 'Alpha review', version: 3), + ]), + 'list_runs' => runListReply([]), + 'get_pipeline' => pipelineDetailReply( + pipelineDetail( + id: 1, + name: 'Alpha review', + version: 3, + latestVersion: 3, + versions: [versionSummary(2), versionSummary(3)], + ), + ), + 'list_schedules' => {'type': 'schedules', 'schedules': []}, + _ => errorReply('unexpected $type'), + }; + }); + tester.view.physicalSize = const Size(1100, 900); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + final screen = PipelinesScreen(gateway: gateway); + await tester.pumpWidget( + cupertino + ? CupertinoApp(home: CupertinoPageScaffold(child: screen)) + : MaterialApp(home: screen), + ); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('pipeline-row-1'))); + await tester.pumpAndSettle(); + + expect(find.byKey(pipelineSummaryFactsKey), findsOneWidget); + // Short facts share a line instead of one label/value row each. + final latest = tester.getRect( + find.byKey(const ValueKey('pipeline-summary-latest-version')), + ); + final versionCreated = tester.getRect( + find.byKey(const ValueKey('pipeline-summary-version-created')), + ); + expect(versionCreated.top, moreOrLessEquals(latest.top)); + expect(versionCreated.left, greaterThan(latest.right)); + + expect(find.text('Refresh'), findsNothing); + expect(find.text(scheduleAddLabel), findsNothing); + expect(find.byKey(scheduleAddKey), findsOneWidget); + expect(find.byType(CupertinoListSection), findsNothing); + expect(find.byType(ListTile), findsNothing); + final row = tester.widget( + find.byKey(const Key('pipeline-version-3')), + ); + expect(row.selected, isTrue); + expect(row.cupertino, cupertino); + expect(tester.takeException(), isNull); + }); + } +} diff --git a/app/test/features/pipelines/pipelines_adaptive_test.dart b/app/test/features/pipelines/pipelines_adaptive_test.dart index ddb8bfe6..8bf67e6d 100644 --- a/app/test/features/pipelines/pipelines_adaptive_test.dart +++ b/app/test/features/pipelines/pipelines_adaptive_test.dart @@ -141,7 +141,14 @@ void main() { ), findsOneWidget, ); - expect(find.byType(CupertinoListTile), findsWidgets); + // Versions are the shared row in its Cupertino form, flat on the page. + expect( + tester + .widget(find.byKey(const Key('pipeline-version-1'))) + .cupertino, + isTrue, + ); + expect(find.byType(CupertinoListSection), findsNothing); await tester.tap(find.byKey(const Key('pipeline-version-1'))); await tester.pumpAndSettle(); diff --git a/app/test/features/runs/ui/run_detail_flat_bodies_test.dart b/app/test/features/runs/ui/run_detail_flat_bodies_test.dart new file mode 100644 index 00000000..6bb26ec5 --- /dev/null +++ b/app/test/features/runs/ui/run_detail_flat_bodies_test.dart @@ -0,0 +1,91 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/runs/data/runs_repository.dart'; +import 'package:pipelines_app/features/runs/ui/run_detail_tab.dart'; +import 'package:pipelines_app/features/runs/ui/run_detail_view.dart'; +import 'package:pipelines_app/features/runs/ui/run_detail_visit_sections.dart'; +import 'package:pipelines_app/features/runs/ui/runs_controller.dart'; +import 'package:pipelines_app/ui/adaptive/floating_bar_layout.dart'; +import 'package:pipelines_app/ui/layout/section_heading.dart'; + +import 'run_detail_graph_support.dart'; +import 'run_detail_visit_support.dart'; + +/// The run and stage detail bodies are flat on the page on both hosts: no +/// Cupertino inset group (so none nested in another), pinned headings on the +/// page colour, and beside a list one row of tabs and header. +void main() { + for (final platform in RunDetailTestPlatform.values) { + testWidgets('${platform.name} Summary and Timeline draw no grouped ' + 'card', (tester) async { + await pumpRunDetail(tester, platform); + expect(find.byType(CupertinoListSection), findsNothing); + await openRunDetailTab(tester, RunDetailTab.timeline); + expect(find.byType(CupertinoListSection), findsNothing); + expect(tester.takeException(), isNull); + }); + + testWidgets('${platform.name} the stage Session nests no group in a ' + 'group', (tester) async { + await openVisit(tester, platform); + await openVisitTab(tester, RunVisitSection.session); + expect(find.text('Turn documents'), findsOneWidget); + expect(find.byType(CupertinoListSection), findsNothing); + }); + + testWidgets('${platform.name} beside a list the tabs and the header ' + 'share one row', (tester) async { + tester.view.physicalSize = const Size(720, 900); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + final gateway = RunDetailFakeGateway(graphRunFixture()); + final controller = RunsController(RunsRepository(gateway)); + addTearDown(controller.dispose); + await controller.select(51); + final view = PageTabsEdge( + edge: FloatingBarEdge.top, + child: RunDetailView( + controller: controller, + gateway: gateway, + onBack: () {}, + ), + ); + await tester.pumpWidget( + platform == RunDetailTestPlatform.material + ? MaterialApp(home: Scaffold(body: view)) + : CupertinoApp(home: CupertinoPageScaffold(child: view)), + ); + await tester.pumpAndSettle(); + + final tabs = tester.getRect(find.byKey(const Key('run-detail-tabs'))); + final header = tester.getRect(find.byKey(const Key('run-detail-header'))); + // Side by side, not stacked: the header starts after the tabs and + // overlaps them vertically. + expect(header.left, greaterThanOrEqualTo(tabs.right - 12)); + expect(header.top, lessThan(tabs.bottom)); + expect(header.bottom, greaterThan(tabs.top)); + expect(tester.takeException(), isNull); + }); + } + + testWidgets('Cupertino pinned headings take the page colour', (tester) async { + for (final brightness in Brightness.values) { + late SectionHeadingStyle style; + late Color page; + await tester.pumpWidget( + CupertinoApp( + theme: CupertinoThemeData(brightness: brightness), + home: Builder( + builder: (context) { + style = SectionHeadingStyle.of(context); + page = CupertinoTheme.of(context).scaffoldBackgroundColor; + return const SizedBox.shrink(); + }, + ), + ), + ); + expect(style.background, page, reason: '$brightness'); + } + }); +} diff --git a/app/test/features/runs/ui/run_detail_summary_fields_test.dart b/app/test/features/runs/ui/run_detail_summary_fields_test.dart index e4888493..b1c1dc5a 100644 --- a/app/test/features/runs/ui/run_detail_summary_fields_test.dart +++ b/app/test/features/runs/ui/run_detail_summary_fields_test.dart @@ -1,3 +1,4 @@ +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'; @@ -132,10 +133,12 @@ void main() { size: const Size(900, 1600), ); - for (final label in recordedLabels) { + // The bar's subtitle names the pipeline, so no Pipeline fact repeats it. + for (final label in recordedLabels.where((l) => l != 'Pipeline')) { expect(find.text(label), findsOneWidget, reason: label); } - expect(find.text('id 3 · v2'), findsOneWidget); + expect(find.text('Pipeline'), findsNothing); + expect(find.text('id 3 · v2'), findsNothing); expect(find.text('review'), findsOneWidget); expect(find.text('/srv/workspaces/run-51'), findsOneWidget); expect(find.text('abc123def456'), findsOneWidget); @@ -199,6 +202,28 @@ void main() { expect(hash.width, greaterThan(300)); }); + testWidgets('${platform.name} a single fact starts at the leading edge, ' + 'with no grouped card', (tester) async { + await pumpRunDetail( + tester, + platform, + run: absentRunFixture()..['current_stage'] = 'review', + size: const Size(900, 1600), + ); + final grid = tester.getRect( + find.byKey(const Key('run-detail-summary-facts')), + ); + final stage = tester.getRect( + find.byKey(const ValueKey('run-detail-summary-stage')), + ); + // The grid spans the Summary, and its one fact is at the start of the + // line rather than a half-width block centred on the page. + expect(grid.width, moreOrLessEquals(900)); + expect(stage.left, moreOrLessEquals(16)); + expect(stage.center.dx, lessThan(450)); + expect(find.byType(CupertinoListSection), findsNothing); + }); + testWidgets('${platform.name} summary sections state their exact empty ' 'wording', (tester) async { await pumpRunDetail( diff --git a/app/test/features/runs/ui/run_detail_tabs_test.dart b/app/test/features/runs/ui/run_detail_tabs_test.dart index 454840e5..ba1517a3 100644 --- a/app/test/features/runs/ui/run_detail_tabs_test.dart +++ b/app/test/features/runs/ui/run_detail_tabs_test.dart @@ -121,10 +121,23 @@ void main() { tester, ) async { await pumpRunDetail(tester, platform, run: graphRunFixture(graph: false)); - await openRunDetailTab(tester, RunDetailTab.graph); + await openRunDetailTab(tester, RunDetailTab.summary); + // One muted line on the Summary: no framed, tappable empty preview. expect(find.text(runGraphMissing), findsOneWidget); + expect(find.byKey(runGraphPreviewMissingKey), findsOneWidget); + expect(find.byKey(runGraphPreviewKey), findsNothing); + expect(find.byType(RunGraphView), findsNothing); expect(find.byType(InteractiveViewer), findsNothing); + final line = tester.getSize(find.byKey(runGraphPreviewMissingKey)); + expect(line.height, lessThan(60)); + expect( + find.descendant( + of: find.byKey(runGraphPreviewMissingKey), + matching: find.byType(DecoratedBox), + ), + findsNothing, + ); }); testWidgets('${platform.name} Graph stays bounded at 320 with 2x text', ( diff --git a/app/test/features/runs/ui/run_timeline_row_test.dart b/app/test/features/runs/ui/run_timeline_row_test.dart index d5bca773..3d3df9bf 100644 --- a/app/test/features/runs/ui/run_timeline_row_test.dart +++ b/app/test/features/runs/ui/run_timeline_row_test.dart @@ -3,6 +3,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:pipelines_app/features/runs/ui/run_detail_content.dart'; import 'package:pipelines_app/features/runs/ui/run_detail_timeline.dart'; +import 'package:pipelines_app/ui/layout/app_list_row.dart'; import 'package:pipelines_app/ui/status/run_status_icon.dart'; final _steps = [ @@ -52,8 +53,13 @@ void main() { expect(find.text('success'), findsOneWidget); expect(find.text('error'), findsOneWidget); - expect(find.text('→ build · 2m 5s'), findsOneWidget); + // The target is the line; the duration is the row's time. + expect(find.text('→ build'), findsOneWidget); + expect(find.text('2m 5s'), findsOneWidget); expect(find.text('→ #failure'), findsOneWidget); + // The shared flat row, with no grouped card on either host. + expect(find.byType(AppListRow), findsNWidgets(3)); + expect(find.byType(CupertinoListSection), findsNothing); }); } } diff --git a/app/test/features/schedules/ui/pipeline/schedule_pipeline_section_test.dart b/app/test/features/schedules/ui/pipeline/schedule_pipeline_section_test.dart index b6cad9b2..adb8fdf6 100644 --- a/app/test/features/schedules/ui/pipeline/schedule_pipeline_section_test.dart +++ b/app/test/features/schedules/ui/pipeline/schedule_pipeline_section_test.dart @@ -112,10 +112,7 @@ void main() { await pumpScheduleSection(tester, gateway: gateway, version: 3); expect(find.text('Schedules (0)'), findsOneWidget); - expect( - find.text('No schedules yet. Add one for each topic or recurring task.'), - findsOneWidget, - ); + expect(find.textContaining(scheduleSectionEmpty), findsOneWidget); await tester.tap(find.byKey(scheduleAddKey)); await tester.pumpAndSettle(); @@ -329,10 +326,7 @@ void main() { expect(gateway.callsOf('delete_schedule'), hasLength(1)); expect(find.text('Research batteries'), findsNothing); - expect( - find.text('No schedules yet. Add one for each topic or recurring task.'), - findsOneWidget, - ); + expect(find.textContaining(scheduleSectionEmpty), findsOneWidget); expect(gateway.calls.map((call) => call.type), [ 'list_schedules', 'delete_schedule', From 1bf2ae41c4cb99d5f5db87cab7b0a537c1d8d522 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Sat, 31 Oct 2026 12:28:54 +0000 Subject: [PATCH 09/14] fix(runs): colour timeline outcomes by name, not by status A completed step's outcome chip took the success colour, so 'rejected' read green beside 'success'. Outcome chips now get one colour per distinct outcome name in the run (assigned by first appearance, from a well-separated hue list that continues by the golden angle), so equal names match and different names never share a colour. No outcome word is wired to a colour; the status glyph still shows the step's state. --- .../features/runs/ui/run_detail_timeline.dart | 19 +++++- app/lib/ui/status/outcome_palette.dart | 68 +++++++++++++++++++ .../runs/ui/run_timeline_row_test.dart | 36 ++++++++++ app/test/ui/status/outcome_palette_test.dart | 31 +++++++++ 4 files changed, 153 insertions(+), 1 deletion(-) create mode 100644 app/lib/ui/status/outcome_palette.dart create mode 100644 app/test/ui/status/outcome_palette_test.dart diff --git a/app/lib/features/runs/ui/run_detail_timeline.dart b/app/lib/features/runs/ui/run_detail_timeline.dart index 779bd72c..e7ac986d 100644 --- a/app/lib/features/runs/ui/run_detail_timeline.dart +++ b/app/lib/features/runs/ui/run_detail_timeline.dart @@ -2,6 +2,7 @@ import '../../../ui/theme/app_theme.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; +import '../../../ui/status/outcome_palette.dart'; import '../../../ui/status/run_status_icon.dart'; import '../domain/run_models.dart'; import 'run_detail_content.dart'; @@ -38,6 +39,9 @@ class RunTimelineList extends StatelessWidget { children: const [Text('No visits recorded.')], ); } + // One colour per distinct outcome name across the whole run, so the same + // outcome reads the same on every row and different ones never match. + final palette = OutcomePalette(visits.map((visit) => visit.outcome)); final rows = [ for (var index = 0; index < visits.length; index += 1) RunTimelineRow( @@ -47,6 +51,7 @@ class RunTimelineList extends StatelessWidget { visit: visits[index], selected: visits[index].sequence == selectedSequence, cupertino: cupertino, + palette: palette, onTap: onSelected == null ? null : () => onSelected!(index), ), ]; @@ -83,6 +88,7 @@ class RunTimelineRow extends StatelessWidget { required this.selected, required this.cupertino, this.onTap, + this.palette, }); final DetailVisit visit; @@ -90,6 +96,10 @@ class RunTimelineRow extends StatelessWidget { final bool cupertino; final VoidCallback? onTap; + /// The run's outcome colours; without one the row colours its own outcome + /// as the first (and only) name. + final OutcomePalette? palette; + /// The visit's state for its glyph: the outcome when it has one (a completed /// step can still have failed), else the step status. String get _state { @@ -110,7 +120,14 @@ class RunTimelineRow extends StatelessWidget { final label = visit.outcome.isNotEmpty ? visit.outcome : (visit.status.isEmpty ? 'unknown' : visit.status); - final color = runStatusColor(_state).resolveFrom(context); + // An outcome is coloured by its name (no word is wired to a colour); a + // visit with no outcome yet keeps its status colour. + final color = visit.outcome.isNotEmpty + ? (palette ?? OutcomePalette([visit.outcome])).colorFor( + context, + visit.outcome, + ) + : runStatusColor(_state).resolveFrom(context); return Container( padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2), decoration: BoxDecoration( diff --git a/app/lib/ui/status/outcome_palette.dart b/app/lib/ui/status/outcome_palette.dart new file mode 100644 index 00000000..a199d516 --- /dev/null +++ b/app/lib/ui/status/outcome_palette.dart @@ -0,0 +1,68 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +/// Colours for recorded outcome names, assigned per run by first appearance. +/// +/// Outcome words are pipeline-defined ('approved', 'rejected', 'retry', …), so +/// no name is hard-wired to a colour: the same name always gets the same +/// colour within a run and two different names never share one. The first +/// [_hues] names use well-separated hues; later ones continue around the +/// colour wheel by the golden angle so they stay distinct. +class OutcomePalette { + OutcomePalette(Iterable outcomes) { + for (final outcome in outcomes) { + final key = _key(outcome); + if (key.isNotEmpty) _index.putIfAbsent(key, () => _index.length); + } + } + + final Map _index = {}; + + static String _key(String outcome) => outcome.trim().toLowerCase(); + + /// The position [outcome] was first seen at, or null for a blank or unseen + /// name. + int? indexOf(String outcome) => _index[_key(outcome)]; + + /// [outcome]'s colour for the host's brightness; an unseen or blank name + /// uses the host's secondary text colour. + Color colorFor(BuildContext context, String outcome) { + final cupertino = + context.findAncestorWidgetOfExactType() == null; + final brightness = cupertino + ? CupertinoTheme.brightnessOf(context) + : Theme.of(context).brightness; + final index = indexOf(outcome); + if (index == null) { + return cupertino + ? CupertinoColors.secondaryLabel.resolveFrom(context) + : Theme.of(context).colorScheme.onSurfaceVariant; + } + return outcomeColorAt(index, brightness); + } +} + +const List _hues = [ + Colors.blue, + Colors.green, + Colors.deepOrange, + Colors.purple, + Colors.teal, + Colors.pink, + Colors.amber, + Colors.indigo, + Colors.brown, + Colors.cyan, +]; + +/// The colour for the [index]th distinct outcome, readable on the page in +/// [brightness] (darker shades on light pages, lighter on dark). +Color outcomeColorAt(int index, Brightness brightness) { + final dark = brightness == Brightness.dark; + if (index < _hues.length) { + final hue = _hues[index]; + return dark ? hue.shade300 : hue.shade800; + } + final degrees = (index * 137.508) % 360; + return HSLColor.fromAHSL(1, degrees, 0.6, dark ? 0.7 : 0.35).toColor(); +} diff --git a/app/test/features/runs/ui/run_timeline_row_test.dart b/app/test/features/runs/ui/run_timeline_row_test.dart index d5bca773..3f949b28 100644 --- a/app/test/features/runs/ui/run_timeline_row_test.dart +++ b/app/test/features/runs/ui/run_timeline_row_test.dart @@ -56,4 +56,40 @@ void main() { expect(find.text('→ #failure'), findsOneWidget); }); } + + for (final cupertino in [false, true]) { + testWidgets('outcome chips are coloured by name, not by status ' + '(${cupertino ? 'cupertino' : 'material'})', (tester) async { + // Every step completed: before, all three chips were the success colour. + final steps = [ + for (final (i, outcome) in [ + 'success', + 'rejected', + 'success', + 'approved', + ].indexed) + { + 'stage': 'stage$i', + 'sequence': i + 1, + 'status': 'completed', + 'outcome': outcome, + }, + ]; + final list = RunTimelineList( + visits: detailTimeline(steps), + cupertino: cupertino, + ); + await tester.pumpWidget( + cupertino + ? CupertinoApp(home: CupertinoPageScaffold(child: list)) + : MaterialApp(home: Scaffold(body: list)), + ); + Color chip(String text, [int at = 0]) => + tester.widget(find.text(text).at(at)).style!.color!; + expect(chip('success'), chip('success', 1)); + expect(chip('rejected'), isNot(chip('success'))); + expect(chip('approved'), isNot(chip('success'))); + expect(chip('approved'), isNot(chip('rejected'))); + }); + } } diff --git a/app/test/ui/status/outcome_palette_test.dart b/app/test/ui/status/outcome_palette_test.dart new file mode 100644 index 00000000..20f349ee --- /dev/null +++ b/app/test/ui/status/outcome_palette_test.dart @@ -0,0 +1,31 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/ui/status/outcome_palette.dart'; + +void main() { + test('same outcome names share a colour; different names never do', () { + final palette = OutcomePalette([ + 'success', + 'rejected', + 'Success', + 'approved', + '', + 'rejected ', + ]); + expect(palette.indexOf('success'), 0); + expect(palette.indexOf('SUCCESS'), 0); + expect(palette.indexOf('rejected'), 1); + expect(palette.indexOf('approved'), 2); + expect(palette.indexOf(''), isNull); + expect(palette.indexOf('never seen'), isNull); + }); + + test('the first fifty outcome colours are all distinct in both themes', () { + for (final brightness in Brightness.values) { + final colours = { + for (var i = 0; i < 50; i++) outcomeColorAt(i, brightness).toARGB32(), + }; + expect(colours, hasLength(50), reason: '$brightness'); + } + }); +} From fe24f228fe9f867995f8b9d8c1348b3f9d94a5a2 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Sat, 31 Oct 2026 12:29:16 +0000 Subject: [PATCH 10/14] fix(app): one relative-time style, day-aware durations, consistent visit wording Review r2 findings P2-4, P2-5, P3-13: a shared relative-time helper for every list row's time, formatDuration switches to days past 24h ('9d 16h'), the stage page uses one visit numbering, drops a repeated stage heading and fixes '1 files', and search run hits read 'Run 1'. Implemented by pipeline run #205/#207 (Terra); its UIReview blocked on a fixture without timestamps, verified by the manager. --- .../changes/domain/change_wording.dart | 3 +- .../changes/widgets/capture_section.dart | 1 - .../chat/ui/sessions/session_row_style.dart | 39 +----- .../features/pipelines/pipeline_format.dart | 17 +-- .../features/pipelines/pipeline_query.dart | 5 +- .../features/runs/ui/run_detail_content.dart | 60 ++++++--- .../features/runs/ui/run_detail_visit.dart | 4 +- app/lib/features/runs/ui/runs_list.dart | 4 +- .../ui/list/schedule_list_format.dart | 26 +--- .../features/search/domain/search_row.dart | 22 ++-- app/lib/ui/text/relative_time.dart | 40 ++++++ app/test/application/pipelines_app_test.dart | 2 +- app/test/application/search_wiring_test.dart | 6 +- .../features/changes/changes_viewer_test.dart | 12 +- .../features/changes/run_changes_test.dart | 2 +- .../features/changes/visit_paging_test.dart | 20 +-- .../chat_session_row_layout_test.dart | 121 +++++++++--------- .../chat_session_row_material_test.dart | 13 +- .../pipelines/pipeline_format_test.dart | 9 +- .../runs/ui/run_detail_deep_link_test.dart | 10 +- .../features/runs/ui/run_detail_finders.dart | 6 +- .../runs/ui/run_detail_visit_test.dart | 2 +- .../runs/ui/run_detail_widget_test.dart | 8 +- .../features/runs/ui/run_list_row_test.dart | 7 +- .../runs/ui/run_search_selection_test.dart | 2 +- .../ui/run_visit_changes_action_test.dart | 4 +- .../ui/list/schedules_layout_test.dart | 2 +- app/test/features/search/search_row_test.dart | 13 +- app/test/ui/text/relative_time_test.dart | 36 ++++++ 29 files changed, 267 insertions(+), 229 deletions(-) create mode 100644 app/lib/ui/text/relative_time.dart create mode 100644 app/test/ui/text/relative_time_test.dart diff --git a/app/lib/features/changes/domain/change_wording.dart b/app/lib/features/changes/domain/change_wording.dart index 5d614070..cf81814d 100644 --- a/app/lib/features/changes/domain/change_wording.dart +++ b/app/lib/features/changes/domain/change_wording.dart @@ -152,7 +152,8 @@ String fileChangesSummary(ChangeCapture capture) { var text = capture.status; if (capture.files.isNotEmpty) { if (text.isNotEmpty) text += ' '; - text += '(${capture.files.length} files)'; + final count = capture.files.length; + text += '($count ${count == 1 ? 'file' : 'files'})'; } if (capture.skipped > 0) { if (text.isNotEmpty) text += ', '; diff --git a/app/lib/features/changes/widgets/capture_section.dart b/app/lib/features/changes/widgets/capture_section.dart index 7f6e3eb2..2c570b17 100644 --- a/app/lib/features/changes/widgets/capture_section.dart +++ b/app/lib/features/changes/widgets/capture_section.dart @@ -45,7 +45,6 @@ class StageCaptureSection extends StatelessWidget { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Text(stage.stage, style: Theme.of(context).textTheme.titleMedium), Text(meta, style: Theme.of(context).textTheme.bodySmall), if (capture != null) ...[ Text( diff --git a/app/lib/features/chat/ui/sessions/session_row_style.dart b/app/lib/features/chat/ui/sessions/session_row_style.dart index 2d0a1eca..86f5c989 100644 --- a/app/lib/features/chat/ui/sessions/session_row_style.dart +++ b/app/lib/features/chat/ui/sessions/session_row_style.dart @@ -1,4 +1,5 @@ import '../../../../core/api_gateway.dart'; +import '../../../../ui/text/relative_time.dart'; import '../../domain/chat_sessions.dart'; /// Titles shared by more than one visible session, so row action labels can @@ -20,24 +21,15 @@ String sessionActionsLabel(JsonMap session, Set duplicateTitles) { : 'Chat actions for $title'; } -/// The web row's relative recency: `just now`, `N min ago`, `N hr ago`, -/// `N days ago`, then a short date (`22 Oct`). A row without a usable -/// `updated_at` reports nothing rather than inventing a time. +/// The shared list-row recency, or nothing for an unusable `updated_at`. String relativeChatSessionTime(Object? updatedAt, {DateTime? now}) { final millis = chatSessionMillis(updatedAt); if (millis <= 0) return ''; - final then = DateTime.fromMillisecondsSinceEpoch(millis); - var elapsed = (now ?? DateTime.now()).difference(then); - if (elapsed.isNegative) elapsed = Duration.zero; - final seconds = elapsed.inSeconds; - if (seconds < 45) return 'just now'; - final minutes = seconds ~/ 60 < 1 ? 1 : seconds ~/ 60; - if (minutes < 60) return '$minutes min ago'; - final hours = minutes ~/ 60; - if (hours < 24) return '$hours hr ago'; - final days = hours ~/ 24; - if (days < 7) return days == 1 ? '1 day ago' : '$days days ago'; - return '${then.day} ${_shortMonths[then.month - 1]}'; + return formatRelativeTime( + DateTime.fromMillisecondsSinceEpoch(millis), + now: now, + ) ?? + ''; } /// The row's one muted line: the recorded model and the folder (home as `~`). @@ -60,20 +52,3 @@ String? chatSessionRowStatus(JsonMap session, {required bool unseen}) { } return unseen ? 'New' : null; } - -const _shortMonths = [ - 'Jan', - 'Feb', - 'Mar', - 'Apr', - 'May', - 'Jun', - 'Jul', - 'Aug', - // `Intl.DateTimeFormat('en-GB', { month: 'short' })`, which the web row - // uses, abbreviates September as `Sept`, not `Sep`. - 'Sept', - 'Oct', - 'Nov', - 'Dec', -]; diff --git a/app/lib/features/pipelines/pipeline_format.dart b/app/lib/features/pipelines/pipeline_format.dart index f70fe675..ea1a1721 100644 --- a/app/lib/features/pipelines/pipeline_format.dart +++ b/app/lib/features/pipelines/pipeline_format.dart @@ -38,12 +38,13 @@ String? formatLocalTimestamp(String? text) { return '${local.day} ${_monthNames[local.month - 1]} $hour:$minute'; } -/// `45s`, `2m 5s`, `1h 2m`. Negative values clamp to `0s`. +/// `45s`, `2m 5s`, `1h 2m`, `9d 16h`. Negative values clamp to `0s`. String formatDuration(int totalSeconds) { final seconds = totalSeconds < 0 ? 0 : totalSeconds; if (seconds < 60) return '${seconds}s'; if (seconds < 3600) return '${seconds ~/ 60}m ${seconds % 60}s'; - return '${seconds ~/ 3600}h ${(seconds % 3600) ~/ 60}m'; + if (seconds < 86400) return '${seconds ~/ 3600}h ${(seconds % 3600) ~/ 60}m'; + return '${seconds ~/ 86400}d ${(seconds % 86400) ~/ 3600}h'; } /// Whole non-negative seconds between two timestamps, or null when either is @@ -56,18 +57,6 @@ int? durationSeconds(String? start, String? end) { return seconds >= 0 ? seconds : null; } -/// `just now`, `Nm ago`, `Nh ago`, `Nd ago`; a future timestamp reads as -/// `just now`, never a negative age. -String? formatRanAgo(String? createdAt, DateTime now) { - final start = parseInstant(createdAt); - if (start == null) return null; - final seconds = now.difference(start).inSeconds; - if (seconds < 60) return 'just now'; - if (seconds < 3600) return '${seconds ~/ 60}m ago'; - if (seconds < 86400) return '${seconds ~/ 3600}h ago'; - return '${seconds ~/ 86400}d ago'; -} - /// `1 stage` / `n stages`. String stageCountText(int count) => '$count ${count == 1 ? 'stage' : 'stages'}'; diff --git a/app/lib/features/pipelines/pipeline_query.dart b/app/lib/features/pipelines/pipeline_query.dart index eeb5701d..56c0b1ee 100644 --- a/app/lib/features/pipelines/pipeline_query.dart +++ b/app/lib/features/pipelines/pipeline_query.dart @@ -1,4 +1,5 @@ import 'pipeline_format.dart'; +import '../../ui/text/relative_time.dart'; import 'pipeline_models.dart'; export 'pipeline_filter.dart'; @@ -27,7 +28,7 @@ class RunBadge { final String? ranAgo; final String? duration; - /// `2h ago · 1m 5s · run 42`; missing fragments are omitted. + /// `2h · 1m 5s · run 42`; missing fragments are omitted. String get metaLine => [ ranAgo, duration, @@ -42,7 +43,7 @@ RunBadge runBadge(PipelineRun run, DateTime now) { return RunBadge( runId: run.id, state: runStateOf(run.status), - ranAgo: formatRanAgo(run.createdAt, now), + ranAgo: formatRelativeTimestamp(run.createdAt, now: now), duration: duration, ); } diff --git a/app/lib/features/runs/ui/run_detail_content.dart b/app/lib/features/runs/ui/run_detail_content.dart index 4f7eef7f..1412fc13 100644 --- a/app/lib/features/runs/ui/run_detail_content.dart +++ b/app/lib/features/runs/ui/run_detail_content.dart @@ -16,6 +16,7 @@ typedef DetailMetric = ({String label, String value}); typedef DetailVisit = ({ String stage, int? sequence, + int visit, String title, String subtitle, String status, @@ -114,22 +115,42 @@ List detailUsageMetrics(dynamic raw) { /// Every recorded visit with its server sequence, in recorded order. List detailTimeline(dynamic steps) { if (steps is! List) return const []; + final records = steps.whereType().toList(growable: false); + final ordered = List.generate(records.length, (index) => index) + ..sort((a, b) { + final bySequence = (_int(records[a]['sequence']) ?? 0).compareTo( + _int(records[b]['sequence']) ?? 0, + ); + return bySequence != 0 ? bySequence : a.compareTo(b); + }); + final positions = {}; + final visits = {}; + for (final index in ordered) { + final stage = '${records[index]['stage'] ?? ''}'.trim(); + final position = (positions[stage] ?? 0) + 1; + positions[stage] = position; + visits[index] = _displayVisit(records[index], position); + } return [ - for (final step in steps.whereType()) - ( - stage: '${step['stage'] ?? ''}'.trim(), - sequence: step['sequence'] is num - ? (step['sequence'] as num).toInt() - : null, - title: - '${_text(step['stage'], 'Stage unavailable')} · visit ' - '${step['sequence'] is num ? (step['sequence'] as num).toInt() : 'unavailable'}', - subtitle: _visitSubtitle(step), - status: '${step['status'] ?? ''}'.trim(), - outcome: '${step['outcome'] ?? ''}'.trim(), - target: '${step['target'] ?? ''}'.trim(), - duration: _visitDuration(step), - ), + for (var index = 0; index < records.length; index += 1) + () { + final step = records[index]; + final stage = '${step['stage'] ?? ''}'.trim(); + final visit = visits[index]!; + return ( + stage: stage, + sequence: step['sequence'] is num + ? (step['sequence'] as num).toInt() + : null, + visit: visit, + title: '${_text(step['stage'], 'Stage unavailable')} · Visit $visit', + subtitle: _visitSubtitle(step), + status: '${step['status'] ?? ''}'.trim(), + outcome: '${step['outcome'] ?? ''}'.trim(), + target: '${step['target'] ?? ''}'.trim(), + duration: _visitDuration(step), + ); + }(), ]; } @@ -166,6 +187,15 @@ String _visitSubtitle(Map step) { ].join(' · '); } +/// The stage's own recorded visit number, falling back to its position among +/// visits to that stage rather than the run-wide step sequence. +int _displayVisit(Map step, int position) { + final control = step['control']; + final recorded = control is Map ? control['visit'] : null; + if (recorded is num && recorded > 0) return recorded.toInt(); + return position; +} + /// The web's `stepDuration`: finished minus started, when both are recorded. String? _visitDuration(Map step) { final started = DateTime.tryParse('${step['started_at'] ?? ''}'); diff --git a/app/lib/features/runs/ui/run_detail_visit.dart b/app/lib/features/runs/ui/run_detail_visit.dart index 49446124..b51bc533 100644 --- a/app/lib/features/runs/ui/run_detail_visit.dart +++ b/app/lib/features/runs/ui/run_detail_visit.dart @@ -90,13 +90,13 @@ class _RunVisitPaneState extends State { } } -/// The page bar's subtitle for a recorded visit: its sequence, then the run +/// The page bar's subtitle for a recorded visit: its per-stage visit, then the run /// it belongs to (`Visit 2 · Run 7 · Nightly report`). String runVisitSubtitle(JsonMap run, DetailVisit visit) { final runId = '${run['id'] ?? ''}'.trim(); final title = detailTitle(run); return [ - if (visit.sequence != null) 'Visit ${visit.sequence}', + 'Visit ${visit.visit}', if (runId.isNotEmpty) 'Run $runId', if (title.isNotEmpty && title != 'Run $runId') title, ].join(' · '); diff --git a/app/lib/features/runs/ui/runs_list.dart b/app/lib/features/runs/ui/runs_list.dart index b6c38534..d73d5789 100644 --- a/app/lib/features/runs/ui/runs_list.dart +++ b/app/lib/features/runs/ui/runs_list.dart @@ -13,7 +13,7 @@ import '../../attention/notify/notification_controller.dart'; import '../../attention/runtime/attention_controller.dart'; import '../../attention/runtime/attention_store.dart'; import '../../attention/ui/needs_you_runs_heading.dart'; -import '../../pipelines/pipeline_format.dart' show formatRanAgo; +import '../../../ui/text/relative_time.dart'; import '../domain/run_models.dart'; import '../../../shell/shell_bar.dart'; import 'run_more_menu.dart'; @@ -354,7 +354,7 @@ class RunListRow extends StatelessWidget { child: RunStatusIcon(state: state, label: runStatusLabel(run)), ), title: Text(title), - time: formatRanAgo('${run['created_at'] ?? ''}', now), + time: formatRelativeTimestamp('${run['created_at'] ?? ''}', now: now), subtitle: Text(subtitle), compactSubtitle: Text(compactSubtitle), // A narrow list pane beside the open run leaves the row no room for a diff --git a/app/lib/features/schedules/ui/list/schedule_list_format.dart b/app/lib/features/schedules/ui/list/schedule_list_format.dart index e1a6d1d8..efa10212 100644 --- a/app/lib/features/schedules/ui/list/schedule_list_format.dart +++ b/app/lib/features/schedules/ui/list/schedule_list_format.dart @@ -1,4 +1,5 @@ import '../../domain/saved_schedule.dart'; +import '../../../../ui/text/relative_time.dart'; /// User-facing values for one saved schedule row. /// @@ -91,31 +92,12 @@ String scheduleCountLabel(int visible, int total) { return total == 1 ? '1 schedule' : '$total schedules'; } -/// A row's short next-run word for its title line: `Paused`, `Not -/// scheduled`, `Next time unavailable`, or the local time as `22 Oct 09:00`. -String scheduleNextDueShort(SavedSchedule schedule) { +/// A row's compact next-run label, using the shared relative-time vocabulary. +String scheduleNextDueShort(SavedSchedule schedule, {DateTime? now}) { if (!schedule.enabled) return 'Paused'; final value = schedule.nextDue; if (value.isEmpty) return 'Not scheduled'; final date = DateTime.tryParse(value); if (date == null) return 'Next time unavailable'; - final local = date.toLocal(); - String two(int part) => part.toString().padLeft(2, '0'); - return '${local.day} ${_shortMonths[local.month - 1]} ' - '${two(local.hour)}:${two(local.minute)}'; + return formatRelativeTime(date, now: now) ?? 'Next time unavailable'; } - -const _shortMonths = [ - 'Jan', - 'Feb', - 'Mar', - 'Apr', - 'May', - 'Jun', - 'Jul', - 'Aug', - 'Sep', - 'Oct', - 'Nov', - 'Dec', -]; diff --git a/app/lib/features/search/domain/search_row.dart b/app/lib/features/search/domain/search_row.dart index 283feca7..a6d2ffc9 100644 --- a/app/lib/features/search/domain/search_row.dart +++ b/app/lib/features/search/domain/search_row.dart @@ -1,4 +1,5 @@ import '../../../core/api_gateway.dart'; +import '../../../ui/text/relative_time.dart'; import 'search_format.dart'; export 'search_format.dart' show humanBytes, formatSearchTimestamp; @@ -47,7 +48,7 @@ SearchRowView searchRowView(JsonMap hit, String query) { final field = _map(hit['field']); final artifact = _map(hit['artifact']); - final recency = formatSearchTimestamp('${hit['recency'] ?? ''}'); + final recency = formatRelativeTimestamp('${hit['recency'] ?? ''}'); final target = _serverTarget(hit); if (pipeline != null) { @@ -68,10 +69,7 @@ SearchRowView searchRowView(JsonMap hit, String query) { title: 'pipeline ${_num(version['pipeline_id'])}' ' · v${_num(version['version'])}', - secondary: _join([ - hash == null ? null : 'content $hash', - formatSearchTimestamp('${version['created_at'] ?? ''}'), - ]), + secondary: hash == null ? '' : 'content $hash', kindLabel: 'Pipeline version', snippetSpans: const [], recency: recency, @@ -81,12 +79,8 @@ SearchRowView searchRowView(JsonMap hit, String query) { if (run != null) { final name = _nonBlank(run['pipeline_name']); return SearchRowView( - title: 'run #${_num(run['id'])}${name == null ? '' : ' · $name'}', - secondary: _join([ - _nonBlank(run['status']), - _nonBlank(run['workspace']), - formatSearchTimestamp('${run['created_at'] ?? ''}'), - ]), + title: 'Run ${_num(run['id'])}${name == null ? '' : ' · $name'}', + secondary: _join([_nonBlank(run['status']), _nonBlank(run['workspace'])]), kindLabel: 'Run', snippetSpans: const [], recency: recency, @@ -97,7 +91,7 @@ SearchRowView searchRowView(JsonMap hit, String query) { final stage = _nonBlank(step['stage']) ?? 'step'; return SearchRowView( title: - 'run #${_num(step['run_id'])} · $stage' + 'Run ${_num(step['run_id'])} · $stage' ' visit ${_num(step['visit'])}', secondary: _stepSecondary(step), kindLabel: 'Step', @@ -110,7 +104,7 @@ SearchRowView searchRowView(JsonMap hit, String query) { final snippet = '${field['snippet'] ?? ''}'; return SearchRowView( title: - 'run #${_num(field['run_id'])} · step ${_num(field['sequence'])}' + 'Run ${_num(field['run_id'])} · step ${_num(field['sequence'])}' ' · ${_nonBlank(field['field']) ?? 'field'}', secondary: snippet, kindLabel: 'Field', @@ -124,7 +118,7 @@ SearchRowView searchRowView(JsonMap hit, String query) { return SearchRowView( title: _nonBlank(artifact['name']) ?? 'artifact', secondary: _join([ - 'run #${_num(artifact['run_id'])}', + 'Run ${_num(artifact['run_id'])}', 'step ${_num(artifact['sequence'])}', _nonBlank(artifact['content_type']), humanBytes(_num(artifact['size_bytes'])), diff --git a/app/lib/ui/text/relative_time.dart b/app/lib/ui/text/relative_time.dart new file mode 100644 index 00000000..5f396620 --- /dev/null +++ b/app/lib/ui/text/relative_time.dart @@ -0,0 +1,40 @@ +const _monthNames = [ + 'Jan', + 'Feb', + 'Mar', + 'Apr', + 'May', + 'Jun', + 'Jul', + 'Aug', + 'Sep', + 'Oct', + 'Nov', + 'Dec', +]; + +/// A compact local recency label for list rows. +/// +/// Past instants use `just now`, `Nm`, `Nh`, or `Nd` for their first week, +/// then a short local date. Future instants use the same compact units with an +/// `in` prefix, which keeps scheduled rows truthful. +String? formatRelativeTime(DateTime? instant, {DateTime? now}) { + if (instant == null) return null; + final current = now ?? DateTime.now(); + final seconds = instant.difference(current).inSeconds; + final future = seconds > 0; + final age = seconds.abs(); + if (age < 60) return 'just now'; + final prefix = future ? 'in ' : ''; + if (age < 3600) return '$prefix${age ~/ 60}m'; + if (age < 86400) return '$prefix${age ~/ 3600}h'; + if (age < 7 * 86400) return '$prefix${age ~/ 86400}d'; + final local = instant.toLocal(); + return '${local.day} ${_monthNames[local.month - 1]}'; +} + +/// Parses [text] as an RFC3339 timestamp before formatting it for a list row. +String? formatRelativeTimestamp(String? text, {DateTime? now}) { + final value = text?.trim() ?? ''; + return formatRelativeTime(DateTime.tryParse(value), now: now); +} diff --git a/app/test/application/pipelines_app_test.dart b/app/test/application/pipelines_app_test.dart index c1818907..0defd93a 100644 --- a/app/test/application/pipelines_app_test.dart +++ b/app/test/application/pipelines_app_test.dart @@ -351,7 +351,7 @@ void main() { await tester.pump(); await tester.pump(const Duration(milliseconds: 400)); await tester.pump(const Duration(milliseconds: 400)); - expectVisitHeading(tester, 'plan', 5); + expectVisitHeading(tester, 'plan', 2); expect(provider.value.uri.path, '/runs/77/stage/plan'); expect(provider.value.uri.query, 'visit=1'); }); diff --git a/app/test/application/search_wiring_test.dart b/app/test/application/search_wiring_test.dart index cc9b13a9..b4ca51df 100644 --- a/app/test/application/search_wiring_test.dart +++ b/app/test/application/search_wiring_test.dart @@ -401,7 +401,7 @@ void main() { await tester.pump(); await tester.pump(); - expect(find.text('run #7 · Preserved run'), findsOneWidget); + expect(find.text('Run 7 · Preserved run'), findsOneWidget); await tester.tap(find.byKey(const ValueKey('search.result.run:7'))); await tester.pump(); await tester.pump(const Duration(milliseconds: 400)); @@ -497,7 +497,7 @@ void main() { expect(provider.value.uri.path, '/runs/7'); expect(find.byType(SearchScreen), findsNothing); expect(find.byKey(const Key('run-visit-pane')), findsOneWidget); - expectVisitHeading(tester, 'build', 2); + expectVisitHeading(tester, 'build', 1); // Leave the visit page (it covers the shell), then a retired field hit // opens the plain Summary with no visit. @@ -608,7 +608,7 @@ void main() { await tester.pumpAndSettle(); expect(find.byKey(const Key('run-visit-pane')), findsOneWidget); - expectVisitHeading(tester, 'build', 2); + expectVisitHeading(tester, 'build', 1); await tester.pumpWidget(const SizedBox.shrink()); await tester.pump(); diff --git a/app/test/features/changes/changes_viewer_test.dart b/app/test/features/changes/changes_viewer_test.dart index 74e55fa4..afe87afe 100644 --- a/app/test/features/changes/changes_viewer_test.dart +++ b/app/test/features/changes/changes_viewer_test.dart @@ -125,11 +125,11 @@ void main() { ); // The run-wide aggregate still counts the file this visit recorded. expect(find.textContaining('1 file changed'), findsOneWidget); - expect(find.text('implementer'), findsOneWidget); + expect(find.text('implementer'), findsNothing); expect(find.text('Visit 1 · completed'), findsOneWidget); expect( find.text( - 'partial (1 files), 1 skipped, 2 omitted · Excluded protected files.', + 'partial (1 file), 1 skipped, 2 omitted · Excluded protected files.', ), findsOneWidget, ); @@ -152,7 +152,7 @@ void main() { await tester.pump(); expect(find.text('implementer'), findsNothing); - expect(find.text('reviewer'), findsOneWidget); + expect(find.text('reviewer'), findsNothing); // The reviewer's first visit is Visit 1, not the run-wide step ordinal 2. expect(find.text('Visit 1 · failed'), findsOneWidget); expect(find.text('Visit 2 · failed'), findsNothing); @@ -200,18 +200,18 @@ void main() { await tester.tap(find.byKey(ChangesVisitPager.nextKey)); await tester.pump(); // The reviewer's first recorded visit is Visit 1 too. - expect(find.text('reviewer'), findsOneWidget); + expect(find.text('reviewer'), findsNothing); expect(find.text('Visit 1 · completed'), findsOneWidget); await tester.tap(find.byKey(ChangesVisitPager.nextKey)); await tester.pump(); - expect(find.text('implementer'), findsOneWidget); + expect(find.text('implementer'), findsNothing); expect(find.text('Visit 2 · completed'), findsOneWidget); await tester.tap(find.byKey(ChangesVisitPager.nextKey)); await tester.pump(); // The resumed reviewer visit records control.visit 6. - expect(find.text('reviewer'), findsOneWidget); + expect(find.text('reviewer'), findsNothing); expect(find.text('Visit 6 · completed'), findsOneWidget); expect(find.text('Visit 3 · completed'), findsNothing); expect(find.text('Visit 4 · completed'), findsNothing); diff --git a/app/test/features/changes/run_changes_test.dart b/app/test/features/changes/run_changes_test.dart index 60353033..0b196d3f 100644 --- a/app/test/features/changes/run_changes_test.dart +++ b/app/test/features/changes/run_changes_test.dart @@ -411,7 +411,7 @@ void main() { expect(parsed.files.map((entry) => entry.path), ['x']); expect( fileChangesSummary(parsed), - 'partial (1 files), 2 skipped, 1 omitted · Excluded protected files.', + 'partial (1 file), 2 skipped, 1 omitted · Excluded protected files.', ); }); diff --git a/app/test/features/changes/visit_paging_test.dart b/app/test/features/changes/visit_paging_test.dart index c8b99427..bc0ae765 100644 --- a/app/test/features/changes/visit_paging_test.dart +++ b/app/test/features/changes/visit_paging_test.dart @@ -43,7 +43,7 @@ void main() { // change as the operator pages. expect(find.text('3 files changed'), findsOneWidget); expect(find.text('1 of 2'), findsOneWidget); - expect(find.text('implementer'), findsOneWidget); + expect(find.text('implementer'), findsNothing); expect(find.text('Visit 1 · completed'), findsOneWidget); expect(find.text('lib/a.dart'), findsOneWidget); expect(find.text('lib/c.dart'), findsNothing); @@ -52,7 +52,7 @@ void main() { await tester.pump(); // The shown page keeps its own visit identity in the heading. - expect(find.text('reviewer'), findsOneWidget); + expect(find.text('reviewer'), findsNothing); expect(find.text('Visit 1 · completed'), findsOneWidget); expect(find.text('lib/c.dart'), findsOneWidget); expect(find.text('lib/a.dart'), findsNothing); @@ -62,7 +62,7 @@ void main() { await tester.tap(find.byKey(ChangesVisitPager.previousKey)); await tester.pump(); - expect(find.text('implementer'), findsOneWidget); + expect(find.text('implementer'), findsNothing); expect(find.text('lib/a.dart'), findsOneWidget); expect(find.text('lib/c.dart'), findsNothing); expect(find.text('1 of 2'), findsOneWidget); @@ -104,11 +104,11 @@ void main() { // The disabled Next is inert; the page stays on the last visit. await tester.tap(find.byKey(ChangesVisitPager.nextKey)); await tester.pump(); - expect(find.text('reviewer'), findsOneWidget); + expect(find.text('reviewer'), findsNothing); await tester.tap(find.byKey(ChangesVisitPager.previousKey)); await tester.pump(); - expect(find.text('implementer'), findsOneWidget); + expect(find.text('implementer'), findsNothing); expect(previous().onPressed, isNull); }); @@ -133,7 +133,7 @@ void main() { findsNothing, ); // The single visit still keeps its identity heading. - expect(find.text('implementer'), findsOneWidget); + expect(find.text('implementer'), findsNothing); expect(find.text('Visit 1 · completed'), findsOneWidget); expect(find.text('lib/only.dart'), findsOneWidget); }); @@ -154,12 +154,12 @@ void main() { await tester.pumpWidget(materialHost(ChangesViewer(steps: first))); await tester.tap(find.byKey(ChangesVisitPager.nextKey)); await tester.pump(); - expect(find.text('reviewer'), findsOneWidget); + expect(find.text('reviewer'), findsNothing); await tester.pumpWidget(materialHost(ChangesViewer(steps: second))); await tester.pump(); expect(tester.takeException(), isNull); - expect(find.text('implementer'), findsOneWidget); + expect(find.text('implementer'), findsNothing); expect(find.text('Visit 1 · completed'), findsOneWidget); expect(find.byKey(ChangesVisitPager.previousKey), findsNothing); }); @@ -187,7 +187,7 @@ void main() { await tester.tap(find.byKey(ChangesVisitPager.nextKey)); await tester.pump(); expect(tester.takeException(), isNull); - expect(find.text('reviewer'), findsOneWidget); + expect(find.text('reviewer'), findsNothing); expect(find.text('Visit 1 · completed'), findsOneWidget); expect(find.text('lib/c.dart'), findsOneWidget); }); @@ -210,7 +210,7 @@ void main() { await tester.tap(find.byKey(ChangesVisitPager.nextKey)); await tester.pump(); - expect(find.text('reviewer'), findsOneWidget); + expect(find.text('reviewer'), findsNothing); expect( tester .widget(find.byKey(ChangesVisitPager.nextKey)) diff --git a/app/test/features/chat/ui/sessions/chat_session_row_layout_test.dart b/app/test/features/chat/ui/sessions/chat_session_row_layout_test.dart index 483ab04c..1b9eec76 100644 --- a/app/test/features/chat/ui/sessions/chat_session_row_layout_test.dart +++ b/app/test/features/chat/ui/sessions/chat_session_row_layout_test.dart @@ -54,61 +54,64 @@ TextStyle _styleOf(WidgetTester tester, String text) => tester.renderObject(find.textContaining(text)).text.style!; void main() { - test('relative recency uses the web wording and never invents a time', () { - final now = DateTime(2026, 10, 22, 12); - final from = now.subtract; + test( + 'relative recency uses shared compact wording and never invents a time', + () { + final now = DateTime(2026, 10, 22, 12); + final from = now.subtract; - expect(relativeChatSessionTime(null, now: now), ''); - expect(relativeChatSessionTime(0, now: now), ''); - expect( - relativeChatSessionTime(now.millisecondsSinceEpoch, now: now), - 'just now', - ); - expect( - relativeChatSessionTime( - from(const Duration(minutes: 5)).millisecondsSinceEpoch, - now: now, - ), - '5 min ago', - ); - expect( - relativeChatSessionTime( - from(const Duration(hours: 3)).millisecondsSinceEpoch, - now: now, - ), - '3 hr ago', - ); - expect( - relativeChatSessionTime( - from(const Duration(hours: 25)).millisecondsSinceEpoch, - now: now, - ), - '1 day ago', - ); - expect( - relativeChatSessionTime( - from(const Duration(days: 3)).millisecondsSinceEpoch, - now: now, - ), - '3 days ago', - ); - expect( - relativeChatSessionTime( - DateTime(2026, 10, 1, 9).millisecondsSinceEpoch, - now: now, - ), - '1 Oct', - ); - // The web formats with `Intl.DateTimeFormat('en-GB', …)`, whose short - // September is `Sept`; its own test asserts `12 Sept`. - expect( - relativeChatSessionTime( - DateTime(2026, 9, 12, 9).millisecondsSinceEpoch, - now: now, - ), - '12 Sept', - ); - }); + expect(relativeChatSessionTime(null, now: now), ''); + expect(relativeChatSessionTime(0, now: now), ''); + expect( + relativeChatSessionTime(now.millisecondsSinceEpoch, now: now), + 'just now', + ); + expect( + relativeChatSessionTime( + from(const Duration(minutes: 5)).millisecondsSinceEpoch, + now: now, + ), + '5m', + ); + expect( + relativeChatSessionTime( + from(const Duration(hours: 3)).millisecondsSinceEpoch, + now: now, + ), + '3h', + ); + expect( + relativeChatSessionTime( + from(const Duration(hours: 25)).millisecondsSinceEpoch, + now: now, + ), + '1d', + ); + expect( + relativeChatSessionTime( + from(const Duration(days: 3)).millisecondsSinceEpoch, + now: now, + ), + '3d', + ); + expect( + relativeChatSessionTime( + DateTime(2026, 10, 1, 9).millisecondsSinceEpoch, + now: now, + ), + '1 Oct', + ); + // The web formats with `Intl.DateTimeFormat('en-GB', …)`, whose short + // September is `Sept`; its own test asserts `12 Sept`. + expect( + relativeChatSessionTime( + DateTime(2026, 9, 12, 9).millisecondsSinceEpoch, + now: now, + ), + '12 Sep', + ); + }, + ); test('the subtitle and status come only from the row', () { expect( @@ -173,7 +176,7 @@ void main() { ); final title = tester.getRect(find.textContaining('Unread chat')); - final time = tester.getRect(find.text('5 min ago')); + final time = tester.getRect(find.text('5m')); final subtitle = tester.getRect(find.text('model-a · /work')); final avatar = tester.getRect( find.descendant( @@ -197,10 +200,10 @@ void main() { expect(_styleOf(tester, 'Read chat').fontWeight, FontWeight.w600); expect(find.byKey(const Key('chat-row-unread')), findsOneWidget); final accent = CupertinoTheme.of( - tester.element(find.text('5 min ago')), + tester.element(find.text('5m')), ).primaryColor; - expect(_styleOf(tester, '5 min ago').color, accent); - expect(_styleOf(tester, '2 hr ago').color, isNot(accent)); + expect(_styleOf(tester, '5m').color, accent); + expect(_styleOf(tester, '2h').color, isNot(accent)); // Starred shows a small star by the title; running a badge on the avatar. expect( @@ -265,7 +268,7 @@ void main() { expect(subtitle.didExceedMaxLines, isTrue); // The time and the Closed word stay inside their row. - for (final (row, word) in [('s1', '3 days ago'), ('c1', 'Closed')]) { + for (final (row, word) in [('s1', '3d'), ('c1', 'Closed')]) { expect( tester.getRect(find.textContaining(word)).right, lessThanOrEqualTo( diff --git a/app/test/features/chat/ui/sessions/chat_session_row_material_test.dart b/app/test/features/chat/ui/sessions/chat_session_row_material_test.dart index 03f05607..f2746b8c 100644 --- a/app/test/features/chat/ui/sessions/chat_session_row_material_test.dart +++ b/app/test/features/chat/ui/sessions/chat_session_row_material_test.dart @@ -76,7 +76,7 @@ void main() { ], isUnseen: (session) => session['id'] == 's1'); final title = tester.getRect(find.text('Unread chat')); - final time = tester.getRect(find.text('5 min ago')); + final time = tester.getRect(find.text('5m')); expect(time.left, greaterThan(title.right)); expect(time.center.dy, closeTo(title.center.dy, 2)); expect( @@ -90,13 +90,10 @@ void main() { ); // Unread: bold title, accent time and a dot; the read row stays muted. - final scheme = Theme.of(tester.element(find.text('5 min ago'))).colorScheme; + final scheme = Theme.of(tester.element(find.text('5m'))).colorScheme; + expect(tester.widget(find.text('5m')).style?.color, scheme.primary); expect( - tester.widget(find.text('5 min ago')).style?.color, - scheme.primary, - ); - expect( - tester.widget(find.text('2 hr ago')).style?.color, + tester.widget(find.text('2h')).style?.color, scheme.onSurfaceVariant, ); expect(find.byKey(const Key('chat-row-unread')), findsOneWidget); @@ -183,7 +180,7 @@ void main() { ); expect(subtitle.maxLines, 1); expect(subtitle.didExceedMaxLines, isTrue); - for (final (row, word) in [('s1', '3 days ago'), ('c1', 'Closed')]) { + for (final (row, word) in [('s1', '3d'), ('c1', 'Closed')]) { expect( tester.getRect(find.textContaining(word)).right, lessThanOrEqualTo( diff --git a/app/test/features/pipelines/pipeline_format_test.dart b/app/test/features/pipelines/pipeline_format_test.dart index 189b9af8..ad55f787 100644 --- a/app/test/features/pipelines/pipeline_format_test.dart +++ b/app/test/features/pipelines/pipeline_format_test.dart @@ -7,7 +7,7 @@ import 'fixtures.dart'; void main() { group('formatting', () { - test('renders local timestamps, durations and ages', () { + test('renders local timestamps and bounded durations', () { expect(formatLocalTimestamp('2026-10-17T21:26:00'), '17 Oct 21:26'); expect(formatLocalTimestamp(''), isNull); expect(formatLocalTimestamp('not a time'), isNull); @@ -15,15 +15,10 @@ void main() { expect(formatDuration(45), '45s'); expect(formatDuration(125), '2m 5s'); expect(formatDuration(3720), '1h 2m'); + expect(formatDuration(840000), '9d 17h'); expect(formatDuration(-4), '0s'); expect(stageCountText(1), '1 stage'); expect(stageCountText(2), '2 stages'); - final now = DateTime(2026, 10, 17, 21, 30); - expect(formatRanAgo('2026-10-17T21:29:40', now), 'just now'); - expect(formatRanAgo('2026-10-17T21:25:00', now), '5m ago'); - expect(formatRanAgo('2026-10-17T19:30:00', now), '2h ago'); - expect(formatRanAgo('2026-10-14T21:30:00', now), '3d ago'); - expect(formatRanAgo('2026-10-17T22:00:00', now), 'just now'); }); test('maps the server status vocabulary and unknown values', () { diff --git a/app/test/features/runs/ui/run_detail_deep_link_test.dart b/app/test/features/runs/ui/run_detail_deep_link_test.dart index 711639b2..6c07e320 100644 --- a/app/test/features/runs/ui/run_detail_deep_link_test.dart +++ b/app/test/features/runs/ui/run_detail_deep_link_test.dart @@ -181,7 +181,7 @@ void main() { await pumpDeepLink(tester, RunDetailTestPlatform.material, stage: 'plan'); expect(find.byKey(const Key('run-visit-pane')), findsOneWidget); - expectVisitHeading(tester, 'plan', 5); + expectVisitHeading(tester, 'plan', 2); }); testWidgets('a Graph click opens the same latest visit as the stage route', ( @@ -195,7 +195,7 @@ void main() { // The web client's graph click takes the last visit in sequence order, not // the last row in reply order, so both entry points agree. expect(find.byKey(const Key('run-visit-pane')), findsOneWidget); - expectVisitHeading(tester, 'plan', 5); + expectVisitHeading(tester, 'plan', 2); }); testWidgets('an out-of-range visit is clamped to the stage last visit', ( @@ -209,7 +209,7 @@ void main() { ); expect(find.byKey(const Key('run-visit-pane')), findsOneWidget); - expectVisitHeading(tester, 'plan', 5); + expectVisitHeading(tester, 'plan', 2); }); testWidgets('a declared but unvisited stage selects its graph node', ( @@ -259,7 +259,7 @@ void main() { await tester.pumpAndSettle(); expect(find.byKey(const Key('run-visit-pane')), findsOneWidget); - expectVisitHeading(tester, 'plan', 5); + expectVisitHeading(tester, 'plan', 2); }); testWidgets('a route change applies its visit and a plain route closes it', ( @@ -301,7 +301,7 @@ void main() { rebuild(() => visit = 1); await tester.pumpAndSettle(); - expectVisitHeading(tester, 'plan', 5); + expectVisitHeading(tester, 'plan', 2); rebuild(() => stage = null); await tester.pumpAndSettle(); diff --git a/app/test/features/runs/ui/run_detail_finders.dart b/app/test/features/runs/ui/run_detail_finders.dart index a41a6066..c2294aaa 100644 --- a/app/test/features/runs/ui/run_detail_finders.dart +++ b/app/test/features/runs/ui/run_detail_finders.dart @@ -14,8 +14,8 @@ Finder runDetailText(String text) => find.descendant( ); /// The stage page's bar names the stage over its visit (and run): the title -/// is keyed `run-visit-title` and the subtitle starts `Visit `. -void expectVisitHeading(WidgetTester tester, String stage, num sequence) { +/// is keyed `run-visit-title` and the subtitle starts `Visit `. +void expectVisitHeading(WidgetTester tester, String stage, num visit) { expect(find.byKey(const Key('run-visit-pane')), findsOneWidget); final heading = find.byKey(const Key('run-visit-title')); expect( @@ -25,7 +25,7 @@ void expectVisitHeading(WidgetTester tester, String stage, num sequence) { expect( find.descendant( of: heading, - matching: find.textContaining(RegExp('^Visit $sequence( ·|\$)')), + matching: find.textContaining(RegExp('^Visit $visit( ·|\$)')), ), findsOneWidget, ); diff --git a/app/test/features/runs/ui/run_detail_visit_test.dart b/app/test/features/runs/ui/run_detail_visit_test.dart index 5ba115e6..872ea86c 100644 --- a/app/test/features/runs/ui/run_detail_visit_test.dart +++ b/app/test/features/runs/ui/run_detail_visit_test.dart @@ -100,7 +100,7 @@ void main() { expect(find.byKey(const Key('run-visit-pane')), findsNothing); expect(find.byType(RunTimelineList), findsOneWidget); - expect(find.text('plan · visit 1'), findsOneWidget); + expect(find.text('plan · Visit 1'), findsOneWidget); }); testWidgets('${platform.name} visit pane at 320 with 2x dark text', ( diff --git a/app/test/features/runs/ui/run_detail_widget_test.dart b/app/test/features/runs/ui/run_detail_widget_test.dart index 993f44b8..8adfd687 100644 --- a/app/test/features/runs/ui/run_detail_widget_test.dart +++ b/app/test/features/runs/ui/run_detail_widget_test.dart @@ -201,17 +201,17 @@ void main() { matching: find.byType(Scrollable), ); await tester.scrollUntilVisible( - find.textContaining('build · visit 3'), + find.textContaining('build · Visit 1').last, 200, scrollable: timelineScroll, ); - expect(find.textContaining('build · visit 3'), findsOneWidget); + expect(find.textContaining('build · Visit 1').last, findsOneWidget); await tester.scrollUntilVisible( - find.textContaining('test · visit 4'), + find.textContaining('test · Visit 1').last, 200, scrollable: timelineScroll, ); - expect(find.textContaining('test · visit 4'), findsOneWidget); + expect(find.textContaining('test · Visit 1').last, findsOneWidget); final before = tester .state(timelineScroll) diff --git a/app/test/features/runs/ui/run_list_row_test.dart b/app/test/features/runs/ui/run_list_row_test.dart index 2aa05b33..4c07c903 100644 --- a/app/test/features/runs/ui/run_list_row_test.dart +++ b/app/test/features/runs/ui/run_list_row_test.dart @@ -58,7 +58,7 @@ void main() { ); Rect at(String text) => tester.getRect(find.text(text)); final title = at('Ship the release notes'); - final age = at('12h ago'); + final age = at('12h'); final subtitle = at('release · 2m 5s · 3 steps'); expect(age.center.dy, moreOrLessEquals(title.center.dy)); @@ -81,10 +81,7 @@ void main() { ), ); - expect( - find.text('Pipeline unavailable · 2m 5s · 3 steps'), - findsOneWidget, - ); + expect(find.text('Pipeline unavailable · 2m 5s · 3 steps'), findsOneWidget); }); testWidgets('gives a list action menu a per-run key', (tester) async { diff --git a/app/test/features/runs/ui/run_search_selection_test.dart b/app/test/features/runs/ui/run_search_selection_test.dart index 71940085..5fd77fc7 100644 --- a/app/test/features/runs/ui/run_search_selection_test.dart +++ b/app/test/features/runs/ui/run_search_selection_test.dart @@ -113,7 +113,7 @@ void main() { ); expect(find.byKey(const Key('run-visit-pane')), findsOneWidget); - expectVisitHeading(tester, 'build', 2); + expectVisitHeading(tester, 'build', 1); }); } diff --git a/app/test/features/runs/ui/run_visit_changes_action_test.dart b/app/test/features/runs/ui/run_visit_changes_action_test.dart index e4a96c72..f841ff21 100644 --- a/app/test/features/runs/ui/run_visit_changes_action_test.dart +++ b/app/test/features/runs/ui/run_visit_changes_action_test.dart @@ -65,13 +65,13 @@ void main() { await _openVisitChanges(tester); expect(find.byKey(const Key('run-visit-pane')), findsOneWidget); - // The body keeps the landed viewer's own identity for that visit. + // The stage is already named in the page bar, so Changes does not repeat it. expect( find.descendant( of: find.byType(ChangesViewer), matching: find.text('plan'), ), - findsOneWidget, + findsNothing, ); expect(find.text('Visit 1 · completed'), findsOneWidget); expect(find.text('lib/plan.dart'), findsOneWidget); diff --git a/app/test/features/schedules/ui/list/schedules_layout_test.dart b/app/test/features/schedules/ui/list/schedules_layout_test.dart index ad53a690..7ad2a8b9 100644 --- a/app/test/features/schedules/ui/list/schedules_layout_test.dart +++ b/app/test/features/schedules/ui/list/schedules_layout_test.dart @@ -33,7 +33,7 @@ void main() { // Two lines per row: the name with its next run, then the timer // and pinned pipeline version. The editor holds the rest. expect(find.text('Research batteries'), findsOneWidget); - expect(find.text('22 Oct 09:00'), findsOneWidget); + expect(find.text('22 Oct'), findsOneWidget); expect( find.text('Every 24h · mon, wed · Pipeline 4 · v2'), findsOneWidget, diff --git a/app/test/features/search/search_row_test.dart b/app/test/features/search/search_row_test.dart index 086f2246..588f5637 100644 --- a/app/test/features/search/search_row_test.dart +++ b/app/test/features/search/search_row_test.dart @@ -90,24 +90,23 @@ void main() { final version = searchRowView(versionHit(), 'release'); expect(version.title, 'pipeline 9 · v2'); - expect(version.secondary, startsWith('content abc · ')); + expect(version.secondary, 'content abc'); expect(version.recency, isNotNull); final run = searchRowView(runHit(), 'release'); - expect(run.title, 'run #11 · release'); - expect(run.secondary, startsWith('succeeded · ')); - expect(run.secondary.split(' · '), hasLength(2)); + expect(run.title, 'Run 11 · release'); + expect(run.secondary, 'succeeded'); final unnamed = searchRowView(runHit({'pipeline_name': ''}), ''); - expect(unnamed.title, 'run #11'); + expect(unnamed.title, 'Run 11'); final step = searchRowView(stepHit({'target': '#success'}), ''); - expect(step.title, 'run #11 · builder visit 2'); + expect(step.title, 'Run 11 · builder visit 2'); expect(step.secondary, 'success · → #success'); final artifact = searchRowView(artifactHit(), 'notes'); expect(artifact.title, 'notes.md'); - expect(artifact.secondary, 'run #11 · step 4 · text/markdown · 2.0 KiB'); + expect(artifact.secondary, 'Run 11 · step 4 · text/markdown · 2.0 KiB'); }); test('a field snippet marks the first case-insensitive query occurrence', () { diff --git a/app/test/ui/text/relative_time_test.dart b/app/test/ui/text/relative_time_test.dart new file mode 100644 index 00000000..0e3cd2e6 --- /dev/null +++ b/app/test/ui/text/relative_time_test.dart @@ -0,0 +1,36 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/ui/text/relative_time.dart'; + +void main() { + final now = DateTime(2026, 10, 22, 12); + + test('formats compact past and future list-row times', () { + expect(formatRelativeTime(now, now: now), 'just now'); + expect( + formatRelativeTime(now.subtract(const Duration(minutes: 5)), now: now), + '5m', + ); + expect( + formatRelativeTime(now.subtract(const Duration(hours: 3)), now: now), + '3h', + ); + expect( + formatRelativeTime(now.subtract(const Duration(days: 3)), now: now), + '3d', + ); + expect( + formatRelativeTime(now.subtract(const Duration(days: 8)), now: now), + '14 Oct', + ); + expect( + formatRelativeTime(now.add(const Duration(hours: 2)), now: now), + 'in 2h', + ); + }); + + test('parses timestamps and omits unusable values', () { + expect(formatRelativeTimestamp('2026-10-22T11:55:00', now: now), '5m'); + expect(formatRelativeTimestamp('', now: now), isNull); + expect(formatRelativeTimestamp('not a time', now: now), isNull); + }); +} From 7351952b98c900715312d62640567d9ad546b117 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Sat, 31 Oct 2026 12:34:05 +0000 Subject: [PATCH 11/14] Notes: templates, sheets, dialogs, settings and artifact error fixes --- app/notes/templates-sheets-fixes.md | 117 ++++++++++++++++++++++++++++ 1 file changed, 117 insertions(+) create mode 100644 app/notes/templates-sheets-fixes.md diff --git a/app/notes/templates-sheets-fixes.md b/app/notes/templates-sheets-fixes.md new file mode 100644 index 00000000..33d88fb4 --- /dev/null +++ b/app/notes/templates-sheets-fixes.md @@ -0,0 +1,117 @@ +# Templates, sheets, dialogs, Settings and artifact errors (review r2 D + H + L) + +Fixes from the second style review (`/tmp/app-style-review-r2/report-summary.md`): +P1-3, P2-1, P2-7, P2-10, P3-7, P3-8, P3-9, P3-10 and P3-12. + +## Templates (P1-3, P2-1) + +- Gallery (`features/templates/ui/template_gallery.dart`): the old + `ListTile`/`CupertinoListTile` list is gone. Rows are `AppListRow`s with an + `AppListAvatar.initial` (key `template-avatar-`, a theme accent picked + by the template key), the name as the bold title and one subtitle line: the + description, then `N stages` only when the server parsed the source. The + `stage count unavailable` line, chevrons and full-width dividers are gone. + Row keys `template-row-` are kept. +- Width: `templatesContentMaxWidth` = 720 (the Settings column), start-aligned + via `templatesColumn`, for the gallery and the detail. +- Background: both Templates scaffolds (`TemplatesFrame` standalone and + `application/templates_destination.dart`) use `AppColors.background` on + Cupertino; the inset-grouped band is gone. +- Detail: the bar's title pill shows the template name with its description + as the subtitle (`templateBarTitle`; `TemplatesFrame.title/subtitle`, which + publishes through `ShellBar`; the Templates destination passes the subtitle + to its `SegmentedBar`). The body no longer repeats the name as a headline + (only a bar-less embedded page still names it). Create is a compact button + at its own width (Material `FilledButton.icon`, Cupertino medium filled), + key `template-create-action` kept. The `Key / release` label/value pair is + one muted line: the key (`template-key`, selectable, read as "Key …") and + `· Includes a schedule`. The Cupertino muted style is now 15pt + `secondaryLabel` instead of the 10pt tab caption. + +## Sheets (P2-7, P3-9) + +- `lib/ui/layout/app_sheet_header.dart` `AppSheetHeader`: title (route-naming + header) + optional extra actions + Done (Material `TextButton`, Cupertino + bold `CupertinoButton`). On a narrow sheet at large text the extra actions + wrap under the title. +- Used by the Runs filter sheet (key `runs.filter.done`; Clear filters moved + to a header `Clear`, key `runs.filter.clear`, shown only when something is + active), the Material Runs sort sheet (`runs.sort.done`) and both Needs you + sheets (`attention-done`; Clear all stays as a Material header action and + the Cupertino Clear-all group). The Cupertino sort stays a native action + sheet with title and Cancel; the current order is its default action. +- Filter sheet split out to `runs/ui/runs_filter_sheet.dart`; shared choices + and labels in `runs_filter_options.dart`. Statuses read in sentence case + (`runStateLabel`), also on applied chips and the usage legend. Status keeps + checkboxes on Material (several may be picked); Pipeline, Time range and + Trigger are check rows (`ListTile` with a trailing check and `selected`, + in a mutually exclusive semantics group). +- Not done: the chat "Chat information" sheet still says `Close` + (`chat_thread_view.dart` belongs to the chat lane). It should adopt + `AppSheetHeader` (Done) for full consistency. + +## Dialogs and action sheets (P2-10, P3-12) + +- Cupertino decision prompt: options are `DecisionOptionRow`s + (`runs/actions/decision_option_row.dart`, key `human-decision-option-`): + label-coloured text, the target in secondary text, an empty circle until + picked and a filled check circle when picked, hairline separators, the whole + row tappable. Material keeps its radio list. +- `RunMoreMenu` passes `sheetTitle: runMoreMenuTitle(run)` (title or pipeline, + else `Run `), so the Cupertino run action sheet is titled like the chat + row sheet. + +## Usage page (P3-7) + +The body no longer starts with a `Usage` heading (the bar says it). No usage: +"No usage has been reported for these runs." No run in the last 7 days: +"No runs started in the last 7 days." instead of seven zero labels. Otherwise +the chart draws bars over a baseline axis, counts only above days with runs. + +## Settings (P3-8) + +- `secondaryActionLabel` is always `Reconnect` (never `Connect` beside + `Disconnect`); keys unchanged. +- Notifications: `NotificationPermissionTile` is one compact row: a short + state line (`Alerts are off` …), one short helper line and `Enable` + (Material `FilledButton.tonal`, Cupertino small tinted; named "Enable + notifications"). The browser's full sentence for the state is the row's + semantics label. `NotificationPermissionView` gained `headline`/`helper`. +- Cupertino `Save workspace` is a small tinted button, so disabled reads as a + disabled button. + +## Artifact viewer (P3-10) + +`artifactPreviewFailureMessage` (`artifacts/domain/artifact_preview_failure.dart`) +maps no-answer, 404/410, 401/403, 5xx and other statuses to plain sentences; +exception text is never shown. The failure message carries a Retry button +(`artifact-preview-retry`) that refetches (failures are not cached). + +## Tests + +New: `test/features/templates/ui/template_layout_test.dart` (720 cap, named +bar, compact Create, 320 @2x), `test/features/runs/ui/runs_sheets_test.dart` +(header/Done, Clear, check rows, sentence case, sort header, usage empty +states and chart), `test/features/artifacts/domain/artifact_preview_failure_test.dart`, +a Retry test in `artifact_viewer_page_test.dart`, decision option-row +assertions in `decision_action_test.dart`, `runMoreMenuTitle` in +`run_list_row_test.dart`, and the Reconnect assertion in +`settings_screen_test.dart`. Updated for intentional changes: the template +gallery screen and behind-bar tests, runs toolbar test (sentence case; +`reveal` also ensures visibility), notification tile and wiring tests. + +Full suite: 2144 passed. `flutter analyze` clean, `flutter build web` OK. + +## Evidence + +`/tmp/r3-c-evidence/`: web build of `tool/templates_wiring_probe_entry.dart` +over `/tmp/wave2-e-scripts/fixture_server.mjs`, driven by +`/tmp/wave2-e-scripts/shoot.mjs` (spec generator `/tmp/r3c-scripts/mkspec.py`). +`{m,c}-{templates,tdetail,filter,sort,needsyou,usage,decide,settings}-{560,1200}-{light,dark}` +(+ `-empty` decide before picking, `-top` Settings top), `c-runmenu-*`, +`{m,c}-artifact-560-{light,dark}` (404 → friendly message + Retry). The fixture +cannot validate sources, so stage counts are absent in the gallery captures. +No device run: Android and iOS are unverified. + +Known gap: the usage page body is not width-capped on wide windows (summary +caps belong to batch K). From dbfecaa201e6b6245340aa3cd8cd6bab22b7f950 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Sat, 31 Oct 2026 12:41:18 +0000 Subject: [PATCH 12/14] Float detail tabs at the bottom of the split detail pane and keep its bars below the status bar --- .../widgets/pipeline_detail_panel.dart | 4 +- .../pipelines/widgets/pipeline_tabs.dart | 5 +- .../runs/ui/run_detail_tab_strip.dart | 4 +- app/lib/features/runs/ui/run_detail_tabs.dart | 2 +- app/lib/shell/adaptive_shell.dart | 37 ++-- app/lib/shell/list_detail.dart | 48 ++++- app/lib/ui/adaptive/floating_bar_layout.dart | 12 +- app/notes/wide-shell-fixes.md | 50 +++++ app/test/shell/pane_bar_row_test.dart | 37 ++-- app/test/shell/split_status_bar_test.dart | 191 ++++++++++++++++++ 10 files changed, 341 insertions(+), 49 deletions(-) create mode 100644 app/test/shell/split_status_bar_test.dart diff --git a/app/lib/features/pipelines/widgets/pipeline_detail_panel.dart b/app/lib/features/pipelines/widgets/pipeline_detail_panel.dart index 0fa4d15e..4721ac5d 100644 --- a/app/lib/features/pipelines/widgets/pipeline_detail_panel.dart +++ b/app/lib/features/pipelines/widgets/pipeline_detail_panel.dart @@ -127,8 +127,8 @@ class _PipelineDetailPanelState extends State { final panel = LayoutBuilder( builder: (context, constraints) { final headerLimit = _headerLimit(constraints); - // The tabs float over the tab body: at the bottom on a phone page, - // under the pane's top bar beside a list (never on the shell's bar). + // The tabs float over the bottom of the tab body, on a phone page + // and beside a list alike (the shell's bar stays over the list). final edge = PageTabsEdge.of(context); final tabs = PipelineDetailTabs( selected: _tab, diff --git a/app/lib/features/pipelines/widgets/pipeline_tabs.dart b/app/lib/features/pipelines/widgets/pipeline_tabs.dart index f8783643..13ad4f5c 100644 --- a/app/lib/features/pipelines/widgets/pipeline_tabs.dart +++ b/app/lib/features/pipelines/widgets/pipeline_tabs.dart @@ -7,8 +7,9 @@ import 'pipeline_detail_tab.dart'; export 'pipeline_detail_tab.dart'; -/// The pipeline detail's tabs: the app's floating glass tab bar, full width on -/// a phone page; beside a list, sized to its tabs under the pane's top bar. +/// The pipeline detail's tabs: the app's floating glass tab bar at the bottom, +/// full width on a phone page; beside a list, sized to its tabs at the bottom +/// of the detail pane (the shell's tab bar stays over the list pane). /// /// Float it over the tab body with `FloatingBarOverlay`. The whole bar is /// keyed `pipeline-detail-tabs`, each tab `pipeline-detail-tab-`. diff --git a/app/lib/features/runs/ui/run_detail_tab_strip.dart b/app/lib/features/runs/ui/run_detail_tab_strip.dart index f70002d4..d3db9d27 100644 --- a/app/lib/features/runs/ui/run_detail_tab_strip.dart +++ b/app/lib/features/runs/ui/run_detail_tab_strip.dart @@ -18,8 +18,8 @@ const List renderedRunDetailTabs = [ ]; /// The run detail's tabs: the app's floating glass tab bar, full width at the -/// bottom of a phone page; beside a list, under the pane's top bar (sized to -/// its tabs) so it never stacks on the shell's own tab bar. +/// bottom of a phone page; beside a list, sized to its tabs at the bottom of +/// the detail pane (the shell's own tab bar stays over the list pane). /// /// Float it over the tab body with `FloatingBarOverlay` at the same [edge]; /// every tab is always visible, so a tab selected by the Graph is shown diff --git a/app/lib/features/runs/ui/run_detail_tabs.dart b/app/lib/features/runs/ui/run_detail_tabs.dart index 974afb4a..05836376 100644 --- a/app/lib/features/runs/ui/run_detail_tabs.dart +++ b/app/lib/features/runs/ui/run_detail_tabs.dart @@ -364,7 +364,7 @@ class _RunDetailTabsState extends State { // The header (status, actions, notices) is a glass strip floating // just under the top bar, so every tab scrolls behind both and pads // its first item clear of them at rest. Below it, the tabs float over - // the tab, at its bottom on a page or at its top beside a list, and + // the bottom of the tab (on a page and beside a list alike), and // the tab learns their height as its padding on that edge too. Every // tab gets the whole height: the scrolling tabs own their content and // the Graph tab fills the slot, so its canvas is never asked for an diff --git a/app/lib/shell/adaptive_shell.dart b/app/lib/shell/adaptive_shell.dart index cecaebb9..81ed392a 100644 --- a/app/lib/shell/adaptive_shell.dart +++ b/app/lib/shell/adaptive_shell.dart @@ -165,25 +165,34 @@ class _AdaptiveShellState extends State { split: split, bar: _segmentedBar(spec, details.label), ); + // The scaffolds below swap the system insets for their bars' + // heights; panes beside a list read the real ones from here. + final system = MediaQuery.paddingOf(context); if (widget.cupertino) { - return CupertinoPageScaffold( - navigationBar: topBar, - child: SafeArea( - top: false, - bottom: false, - child: FloatingBarOverlay( - bar: bar, - child: _destinationStack(contents, index), + return ShellSystemInsets( + padding: system, + child: CupertinoPageScaffold( + navigationBar: topBar, + child: SafeArea( + top: false, + bottom: false, + child: FloatingBarOverlay( + bar: bar, + child: _destinationStack(contents, index), + ), ), ), ); } - return Scaffold( - extendBodyBehindAppBar: true, - appBar: topBar, - body: _destinationStack(contents, index), - extendBody: true, - bottomNavigationBar: bar, + return ShellSystemInsets( + padding: system, + child: Scaffold( + extendBodyBehindAppBar: true, + appBar: topBar, + body: _destinationStack(contents, index), + extendBody: true, + bottomNavigationBar: bar, + ), ); }, ); diff --git a/app/lib/shell/list_detail.dart b/app/lib/shell/list_detail.dart index 0add8deb..c6f44de4 100644 --- a/app/lib/shell/list_detail.dart +++ b/app/lib/shell/list_detail.dart @@ -36,6 +36,33 @@ double listDetailBodyWidth(double window, double available) { double listDetailListWidth(double window, double available) => math.max(0, available - 1 - listDetailBodyWidth(window, available)); +/// The system's own insets (status bar, navigation bar) as the shell saw +/// them, before its scaffold replaced them with its bars' heights. +/// +/// A Material [Scaffold] with an app bar and a bottom bar removes the top and +/// bottom padding *and* view padding from its body, so a pane beside the list +/// cannot recover the status-bar inset from its own [MediaQuery]. The shell +/// publishes the insets here; outside a shell the view padding stands in. +class ShellSystemInsets extends InheritedWidget { + const ShellSystemInsets({ + super.key, + required this.padding, + required super.child, + }); + + final EdgeInsets padding; + + static EdgeInsets of(BuildContext context) => + context + .dependOnInheritedWidgetOfExactType() + ?.padding ?? + MediaQuery.viewPaddingOf(context); + + @override + bool updateShouldNotify(ShellSystemInsets oldWidget) => + padding != oldWidget.padding; +} + /// Narrows a shell bar to the list pane while [split] (the tab shows its list /// beside an open item), placing it at the pane's [alignment]; otherwise the /// bar keeps the whole width it is given. The bar keeps its place in the tree @@ -76,8 +103,8 @@ class ListPaneWidth extends StatelessWidget { /// Under the shell, the list keeps the shell's bars (both narrowed to the list /// pane through [ShellPaneSplit], see [ListPaneWidth]) and the open item owns /// the rest of the window: the detail starts at the top edge and reaches the -/// bottom edge with only the system insets as its padding, and its own tabs -/// float at its top ([PageTabsEdge]). +/// bottom edge with only the system insets ([ShellSystemInsets]) as its +/// padding, and its own tabs float at its bottom, as on a phone. class ListDetailPanes extends StatelessWidget { const ListDetailPanes({super.key, required this.list, required this.detail}); @@ -103,19 +130,20 @@ class ListDetailPanes extends StatelessWidget { ); Widget body = detail; if (split) { - // Beside the list the item is not under the shell's bar: it keeps - // only the system's own inset and draws its bar at the top edge. - // The shell's destination bar stays over the list pane too, so the - // item keeps only the system's bottom inset: its own composer or - // controls own the pane's bottom edge. + // Beside the list the item is under neither of the shell's bars + // (both stay over the list pane): it keeps only the system's own + // insets, so its bar sits just below the status bar at the top + // edge, and its tabs or composer own the pane's bottom edge, + // floating just above the system inset. + final system = ShellSystemInsets.of(context); body = MediaQuery( data: media.copyWith( padding: media.padding.copyWith( - top: media.viewPadding.top, - bottom: media.viewPadding.bottom, + top: system.top, + bottom: system.bottom, ), ), - child: PageTabsEdge(edge: FloatingBarEdge.top, child: body), + child: PageTabsEdge(edge: FloatingBarEdge.bottom, child: body), ); } return Row( diff --git a/app/lib/ui/adaptive/floating_bar_layout.dart b/app/lib/ui/adaptive/floating_bar_layout.dart index c6b44a35..ed08aef4 100644 --- a/app/lib/ui/adaptive/floating_bar_layout.dart +++ b/app/lib/ui/adaptive/floating_bar_layout.dart @@ -112,19 +112,19 @@ class SliverFloatingBarClearance extends StatelessWidget { /// The edge a page's own floating tab bar sits at. enum FloatingBarEdge { - /// Above the bottom safe area: a phone page, or a page covering the shell. + /// Above the bottom safe area: a phone page, a page covering the shell, + /// or a detail pane beside a list (the shell's tab bar stays over the + /// list pane). bottom, - /// Just below the page's top bar: a detail pane beside a list, where the - /// shell's own tab bar already floats at the bottom. + /// Just below the page's top bar, for a surface whose bottom is taken. top, } /// Where the pages' own tab bars float in this subtree ([FloatingBarEdge]). /// -/// A detail pane beside a list says [FloatingBarEdge.top], so an open item's -/// tabs never stack on the shell's tab bar; everywhere else they float at the -/// bottom. +/// Pages float their tabs at the bottom (the default), including a detail +/// pane beside a list, whose bottom the shell leaves free. class PageTabsEdge extends InheritedWidget { const PageTabsEdge({super.key, required this.edge, required super.child}); diff --git a/app/notes/wide-shell-fixes.md b/app/notes/wide-shell-fixes.md index ad8277c6..b7e8896b 100644 --- a/app/notes/wide-shell-fixes.md +++ b/app/notes/wide-shell-fixes.md @@ -31,6 +31,46 @@ run and pipeline detail content. no split (Settings, Search, Schedules, Templates) it is compact and right-aligned. `floating_destination_bar.dart` needed no change. +## Detail tabs at the bottom (operator request) + +Beside a list, run and pipeline detail used to float their tabs at the top +of the pane, under its bar (`PageTabsEdge(top)` from +`notes/app-chrome-fixes.md`). The shell's tab bar now stays over the list +pane, which leaves the detail pane's bottom free. So `ListDetailPanes` now +says `PageTabsEdge(edge: FloatingBarEdge.bottom)`, and the item's tabs float +at the bottom of the detail pane, the same as on a phone page: + +- At 1200 and 1600 they are sized to their tabs and sit at the pane's + trailing edge. +- They sit 16 above the system inset. +- The content pads its last item clear of them. + +The chat composer owns the chat pane's bottom in the same way. No pill sits +on top of another pill. The stage page is always a pushed page, so its tabs +were already at the bottom. `FloatingBarEdge.top` remains in the layout +primitives, but nothing in the app uses it now. + +## Status-bar inset in the detail pane (unfolded foldable) + +On the Pixel Fold, the right pane drew its bar (chat header, run detail bar) +under the status bar. The cause is that a Material `Scaffold` with an +`appBar` and a `bottomNavigationBar` removes the top and bottom padding +*and view padding* from its body. `ListDetailPanes` rebuilt the detail's +insets from `viewPadding`, and inside the Material shell that is zero. +Cupertino was unaffected. + +The fix is in two places: + +- The shell publishes the system insets it saw before its scaffold: + `ShellSystemInsets` in `list_detail.dart`, set in `adaptive_shell.dart` + from `MediaQuery.paddingOf`. +- `ListDetailPanes` gives the detail exactly those insets at the top and + bottom. Outside a shell, `viewPadding` stands in. + +The list side keeps the shell bar's height, so it was already correct. +Headless Chrome has no status bar, so this is covered by widget tests only. +It has not been verified on a device. + ## P2-9: Schedules on a wide window - The strip (`schedule_list_toolbar.dart`) now holds the field and the filter, @@ -88,6 +128,14 @@ New: - At 1200 unsplit, the pill is compact at the right edge. - At 390, the pill spans the phone. - At 600 and 840 split with 2x text, there is no overflow. +- `test/shell/split_status_bar_test.dart` covers both hosts at 1200 with a + 40px status bar (`tester.view.padding` and `viewPadding`): + - The list bar, the detail pane bar and a self-drawn header (like the + chat thread's `SegmentedBarOverlay`) all start at y ≥ 40. + - The list and the item content still start at y=0. + - The item tabs float at the pane's bottom, inside the detail pane, and do + not overlap the shell tabs; the list clears them. + - Before the fix, Material failed with the bar at y=8. - `test/ui/layout/reading_width_test.dart`: - The cap applies from the leading edge, and the body is not remounted across the cap. @@ -107,6 +155,8 @@ Updated: - The pipelines tests (placeholder wording). - `chat_list_detail_test.dart`, `pipelines_screen_test.dart` and `runs_screen_test.dart` now assert `EmptyDetailPane`. +- `pane_bar_row_test.dart`: the item tabs are now at the bottom of the pane + (they were under the pane bar). - `run_detail_tabs_test.dart`: at 1000 the Summary body is now `kReadingMaxWidth` wide from x=0 instead of spanning the window. diff --git a/app/test/shell/pane_bar_row_test.dart b/app/test/shell/pane_bar_row_test.dart index ca48d31b..2f24dfef 100644 --- a/app/test/shell/pane_bar_row_test.dart +++ b/app/test/shell/pane_bar_row_test.dart @@ -12,7 +12,8 @@ import 'package:pipelines_app/ui/adaptive/glass_pill.dart'; import 'package:pipelines_app/ui/adaptive/segmented_bar.dart'; /// Beside a list each pane owns its bar on one shared top row, and an open -/// item's tabs never stack on the shell's tab bar at the bottom. +/// item's tabs float at the bottom of its own pane, beside (never on) the +/// shell's tab bar over the list. void main() { Future setSize(WidgetTester tester, Size size) async { tester.view.physicalSize = size; @@ -149,18 +150,20 @@ void main() { expect(find.text('Its context'), findsOneWidget); }); - testWidgets('$host 1200: the item\'s tabs float under its bar, not on ' - 'the shell\'s tab bar', (tester) async { + testWidgets('$host 1200: the item\'s tabs float at the bottom of its ' + 'pane, beside the shell\'s tab bar', (tester) async { await setSize(tester, const Size(1200, 800)); await tester.pumpWidget(shell(cupertino: cupertino)); await tester.pump(); await tester.pump(); final shellTabs = tester.getRect( - find.descendant( - of: find.byKey(const ValueKey('shell.destination.runs')).first, - matching: find.byType(Icon), - ), + find + .ancestor( + of: find.byKey(const ValueKey('shell.destination.runs')).first, + matching: find.byType(GlassPill), + ) + .first, ); final itemTabs = tester.getRect( find.descendant( @@ -168,16 +171,26 @@ void main() { matching: find.byType(GlassPill), ), ); + final body = tester.getRect( + find.byKey(const ValueKey('list-detail-body')), + ); + // Near the bottom of the detail pane, never on the shell's tabs. + expect(itemTabs.bottom, closeTo(800 - kFloatingBarMargin, 0.5)); + expect(itemTabs.left, greaterThanOrEqualTo(body.left)); + expect(itemTabs.overlaps(shellTabs), isFalse); + // The item's list starts below its bar and clears its tabs at rest. final paneBarPill = tester.getRect( find.descendant(of: paneBar(), matching: find.byType(GlassPill)).first, ); - expect(itemTabs.top, greaterThanOrEqualTo(paneBarPill.bottom)); - expect(itemTabs.top, lessThan(200)); - expect(itemTabs.bottom, lessThan(shellTabs.top - 100)); - // The item's list starts below its tabs at rest. expect( tester.getTopLeft(find.text('item row 0')).dy, - greaterThanOrEqualTo(itemTabs.bottom), + greaterThanOrEqualTo(paneBarPill.bottom), + ); + expect( + MediaQuery.paddingOf( + tester.element(find.byKey(const Key('item-list'))), + ).bottom, + greaterThanOrEqualTo(800 - itemTabs.top), ); }); } diff --git a/app/test/shell/split_status_bar_test.dart b/app/test/shell/split_status_bar_test.dart new file mode 100644 index 00000000..299204b8 --- /dev/null +++ b/app/test/shell/split_status_bar_test.dart @@ -0,0 +1,191 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/shell/adaptive_shell.dart'; +import 'package:pipelines_app/shell/destination.dart'; +import 'package:pipelines_app/shell/detail_page.dart'; +import 'package:pipelines_app/shell/list_detail.dart'; +import 'package:pipelines_app/shell/shell_bar.dart'; +import 'package:pipelines_app/ui/adaptive/floating_bar_layout.dart'; +import 'package:pipelines_app/ui/adaptive/floating_destination_bar.dart'; +import 'package:pipelines_app/ui/adaptive/glass_pill.dart'; +import 'package:pipelines_app/ui/adaptive/segmented_bar.dart'; +import 'package:pipelines_app/ui/adaptive/segmented_bar_overlay.dart'; + +/// On a wide split window (an unfolded foldable) under a system status bar, +/// every pane's bar sits below the status-bar inset while content still +/// reaches the top edge; and the open item's tabs float at the bottom of the +/// detail pane, beside (never on) the shell's tab bar over the list. +void main() { + const statusBar = 40.0; + + Future setUp(WidgetTester tester, Size size) async { + tester.view.physicalSize = size; + tester.view.devicePixelRatio = 1; + tester.view.padding = const FakeViewPadding(top: statusBar); + tester.view.viewPadding = const FakeViewPadding(top: statusBar); + addTearDown(tester.view.reset); + } + + List rows(String label) => [ + for (var index = 0; index < 40; index++) + SizedBox(height: 40, child: Text('$label $index')), + ]; + + /// An item publishing its bar to the pane, with its own floating tabs + /// placed where the pane says (like run and pipeline detail). + Widget tabbedItem(bool cupertino) => ShellBar( + title: 'Open item', + child: Builder( + builder: (context) { + final edge = PageTabsEdge.of(context); + return FloatingBarOverlay( + edge: edge, + bar: KeyedSubtree( + key: const Key('item-tabs'), + child: FloatingDestinationBar( + cupertino: cupertino, + edge: edge, + currentIndex: 0, + onTap: (_) {}, + items: const [ + FloatingDestinationItem(icon: Icon(Icons.notes), label: 'One'), + FloatingDestinationItem(icon: Icon(Icons.share), label: 'Two'), + ], + ), + ), + child: Builder( + builder: (context) => ListView( + key: const Key('item-list'), + padding: withBarClearance(context, EdgeInsets.zero), + children: rows('item'), + ), + ), + ); + }, + ), + ); + + /// An item drawing its own header over itself (like the chat thread). + Widget overlayItem(bool cupertino) => ShellBar( + barless: true, + child: SegmentedBarOverlay( + bar: SegmentedBar( + key: const Key('own-header'), + cupertino: cupertino, + automaticallyImplyLeading: false, + title: 'Own header', + ), + child: ListView(key: const Key('item-list'), children: rows('item')), + ), + ); + + Widget shell(bool cupertino, Widget Function(bool) item) { + final app = AdaptiveShell( + cupertino: cupertino, + destination: AppDestination.runs, + destinationBodies: { + AppDestination.runs: (_) => ListDetailPanes( + list: ShellBar( + child: ListView(key: const Key('list'), children: rows('list')), + ), + detail: DetailPane( + destination: AppDestination.runs, + implyBack: false, + builder: (_) => item(cupertino), + ), + ), + }, + ); + return cupertino ? CupertinoApp(home: app) : MaterialApp(home: app); + } + + Iterable pillsOf(WidgetTester tester, Finder bar) => find + .descendant(of: bar, matching: find.byType(GlassPill)) + .evaluate() + .map((element) { + final box = element.renderObject! as RenderBox; + return box.localToGlobal(Offset.zero) & box.size; + }); + + for (final cupertino in [false, true]) { + final host = cupertino ? 'Cupertino' : 'Material'; + + testWidgets('$host split under a status bar: list and pane bars sit ' + 'below it, content reaches the top edge', (tester) async { + await setUp(tester, const Size(1200, 800)); + await tester.pumpWidget(shell(cupertino, tabbedItem)); + await tester.pump(); + await tester.pump(); + + final listBar = find.byWidgetPredicate( + (widget) => widget is SegmentedBar && widget.title == 'Runs', + ); + final paneBar = find.byWidgetPredicate( + (widget) => widget is SegmentedBar && widget.title == 'Open item', + ); + for (final bar in [listBar, paneBar]) { + final pills = pillsOf(tester, bar); + expect(pills, isNotEmpty); + for (final pill in pills) { + expect(pill.top, greaterThanOrEqualTo(statusBar)); + } + } + // Content may still extend under the bars and the status bar. + expect(tester.getTopLeft(find.byKey(const Key('list'))).dy, 0); + expect(tester.getTopLeft(find.byKey(const Key('item-list'))).dy, 0); + // At rest the first rows start below the bars. + final paneBottom = pillsOf(tester, paneBar).first.bottom; + expect( + tester.getTopLeft(find.text('item 0')).dy, + greaterThanOrEqualTo(paneBottom), + ); + }); + + testWidgets('$host split under a status bar: a self-drawn header (chat) ' + 'sits below it', (tester) async { + await setUp(tester, const Size(1200, 800)); + await tester.pumpWidget(shell(cupertino, overlayItem)); + await tester.pump(); + await tester.pump(); + final pills = pillsOf(tester, find.byKey(const Key('own-header'))); + expect(pills, isNotEmpty); + for (final pill in pills) { + expect(pill.top, greaterThanOrEqualTo(statusBar)); + } + expect(tester.getTopLeft(find.byKey(const Key('item-list'))).dy, 0); + }); + + testWidgets('$host split: the item tabs float at the bottom of the ' + 'detail pane, beside the shell tab bar over the list', (tester) async { + await setUp(tester, const Size(1200, 800)); + await tester.pumpWidget(shell(cupertino, tabbedItem)); + await tester.pump(); + await tester.pump(); + + final body = tester.getRect( + find.byKey(const ValueKey('list-detail-body')), + ); + final tabs = pillsOf(tester, find.byKey(const Key('item-tabs'))).single; + expect(tabs.bottom, closeTo(800 - kFloatingBarMargin, 0.5)); + expect(tabs.left, greaterThanOrEqualTo(body.left)); + expect(tabs.right, lessThanOrEqualTo(body.right)); + final shellTabs = tester.getRect( + find + .ancestor( + of: find.byKey(const ValueKey('shell.destination.runs')).first, + matching: find.byType(GlassPill), + ) + .first, + ); + expect(shellTabs.overlaps(tabs), isFalse); + expect(shellTabs.right, lessThanOrEqualTo(body.left)); + // The item's list clears its tabs at rest. + final list = tester.element(find.byKey(const Key('item-list'))); + expect( + MediaQuery.paddingOf(list).bottom, + greaterThanOrEqualTo(800 - tabs.top), + ); + }); + } +} From b4ab9d72da2033e98901b2de77387fce55a40c1f Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Sat, 31 Oct 2026 12:45:11 +0000 Subject: [PATCH 13/14] Notes: final test count --- app/notes/templates-sheets-fixes.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/notes/templates-sheets-fixes.md b/app/notes/templates-sheets-fixes.md index 33d88fb4..4fe69278 100644 --- a/app/notes/templates-sheets-fixes.md +++ b/app/notes/templates-sheets-fixes.md @@ -100,7 +100,7 @@ assertions in `decision_action_test.dart`, `runMoreMenuTitle` in gallery screen and behind-bar tests, runs toolbar test (sentence case; `reveal` also ensures visibility), notification tile and wiring tests. -Full suite: 2144 passed. `flutter analyze` clean, `flutter build web` OK. +Full suite (after merging main bd370c99): 2150 passed. `flutter analyze` clean, `flutter build web` OK. ## Evidence From d1aa36163a25bf0f48b860927a6eba2eb2e23f97 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Sat, 31 Oct 2026 12:47:25 +0000 Subject: [PATCH 14/14] Sync Needs-you dismissals and chat read state across devices --- app/lib/application/pipelines_app.dart | 21 ++ .../attention/domain/attention_acks.dart | 110 ++++++++ .../runtime/attention_ack_queue.dart | 66 +++++ .../attention/runtime/attention_ack_sync.dart | 239 ++++++++++++++++++ .../runtime/attention_controller.dart | 48 +++- .../ui/sessions/chat_sessions_controller.dart | 97 ++++++- app/notes/synced-attention.md | 97 +++++++ .../runtime/attention_ack_sync_test.dart | 198 +++++++++++++++ .../attention/runtime/fake_ack_server.dart | 113 +++++++++ .../chat/ui/sessions/chat_seen_sync_test.dart | 167 ++++++++++++ docs/cli.md | 6 +- docs/ntfy.md | 16 ++ 12 files changed, 1164 insertions(+), 14 deletions(-) create mode 100644 app/lib/features/attention/domain/attention_acks.dart create mode 100644 app/lib/features/attention/runtime/attention_ack_queue.dart create mode 100644 app/lib/features/attention/runtime/attention_ack_sync.dart create mode 100644 app/notes/synced-attention.md create mode 100644 app/test/features/attention/runtime/attention_ack_sync_test.dart create mode 100644 app/test/features/attention/runtime/fake_ack_server.dart create mode 100644 app/test/features/chat/ui/sessions/chat_seen_sync_test.dart diff --git a/app/lib/application/pipelines_app.dart b/app/lib/application/pipelines_app.dart index 374e7594..1d20559a 100644 --- a/app/lib/application/pipelines_app.dart +++ b/app/lib/application/pipelines_app.dart @@ -13,6 +13,8 @@ import '../shell/destination.dart'; import '../features/attention/notify/notification_controller.dart'; import '../features/attention/notify/chat_question_notices.dart'; import '../features/attention/notify/notification_store.dart'; +import '../features/attention/runtime/attention_ack_queue.dart'; +import '../features/attention/runtime/attention_ack_sync.dart'; import '../features/attention/runtime/attention_controller.dart'; import '../features/attention/runtime/attention_store.dart'; import '../features/runs/ui/run_search_selection.dart'; @@ -126,6 +128,18 @@ class _PipelinesAppState extends State store: SharedPreferencesAttentionStore( serverId: serverStorageScope(widget.serverId), ), + sync: _ackSync, + ); + + /// Shares Needs-you dismissals and chat read watermarks with every device + /// through the server. Bound to the gateway so the chat list (created by its + /// destination) uses the same channel; refreshed on every connection. + late final AttentionAckSync _ackSync = AttentionAckSync( + gateway: _session.gateway, + sendOnly: _session.client.sendOnly, + queue: SharedPreferencesAttentionAckQueue( + serverId: serverStorageScope(widget.serverId), + ), ); StreamSubscription? _attentionFrames; int _attentionEpoch = 0; @@ -169,6 +183,8 @@ class _PipelinesAppState extends State if (mounted) _delegate.goTo(AppRoute.run(id)); }; unawaited(_notifications.load()); + bindAttentionAckSync(_session.gateway, _ackSync); + unawaited(_ackSync.load()); unawaited(_attention.load()); _attentionFrames = _session.gateway.frames .where((frame) => frame['type'] == 'run_event') @@ -216,6 +232,8 @@ class _PipelinesAppState extends State unawaited(_attentionFrames?.cancel()); _attention.removeListener(_attentionChanged); _attention.dispose(); + bindAttentionAckSync(_session.gateway, null); + _ackSync.dispose(); _attentionCount.dispose(); _notifications.dispose(); _chatQuestionNotices?.dispose(); @@ -275,6 +293,9 @@ class _PipelinesAppState extends State if (epoch == _attentionEpoch) return; _attentionEpoch = epoch; _attention.resetForReconnect(); + // Every connected transition sends acknowledgements queued while offline + // and re-reads the shared set, so a gap cannot leave this device stale. + if (_session.connected) unawaited(_ackSync.connected()); } /// Mirrors the controller's entry count for the shell. The Runs list seeds diff --git a/app/lib/features/attention/domain/attention_acks.dart b/app/lib/features/attention/domain/attention_acks.dart new file mode 100644 index 00000000..e1d7f18c --- /dev/null +++ b/app/lib/features/attention/domain/attention_acks.dart @@ -0,0 +1,110 @@ +import 'dart:convert'; + +import '../../../core/api_gateway.dart'; + +/// The server-shared "I have seen this" state (`attention_acks` on the wire): +/// dismissed Needs-you identities (`{runId}:{kind}`) and per-chat-session +/// read watermarks in epoch milliseconds. +/// +/// The set only grows — dismissals are added and watermarks only advance — so +/// merging is a union/maximum and applying a frame twice or out of order is +/// harmless. The same shape is used for the whole set, a pushed delta and the +/// offline queue of acknowledgements not yet accepted by the server. +class AttentionAcks { + const AttentionAcks({this.dismissed = const {}, this.chatSeen = const {}}); + + final Set dismissed; + final Map chatSeen; + + bool get isEmpty => dismissed.isEmpty && chatSeen.isEmpty; + + int get length => dismissed.length + chatSeen.length; + + /// The union of both sets, keeping the larger watermark per session. + /// Returns this instance when [other] adds nothing. + AttentionAcks merge(AttentionAcks other) { + final addsDismissal = !dismissed.containsAll(other.dismissed); + final advances = other.chatSeen.entries.any( + (entry) => entry.value > (chatSeen[entry.key] ?? 0), + ); + if (!addsDismissal && !advances) return this; + final seen = {...chatSeen}; + other.chatSeen.forEach((id, at) { + if (at > (seen[id] ?? 0)) seen[id] = at; + }); + return AttentionAcks( + dismissed: {...dismissed, ...other.dismissed}, + chatSeen: seen, + ); + } + + /// What remains of this queue after [sent] was accepted: a dismissal is + /// gone once sent, a watermark only when no newer value was queued since. + AttentionAcks without(AttentionAcks sent) => AttentionAcks( + dismissed: dismissed.difference(sent.dismissed), + chatSeen: { + for (final entry in chatSeen.entries) + if (entry.value > (sent.chatSeen[entry.key] ?? 0)) + entry.key: entry.value, + }, + ); + + /// The wire body of `ack_attention` / the stored queue. + JsonMap toJson() { + final keys = dismissed.toList()..sort(); + return {'dismissed': keys, 'chat_seen': chatSeen}; + } + + String encode() => jsonEncode(toJson()); + + /// Total decode of a wire or stored value: unreadable members are skipped + /// and a malformed value is the empty set, never an exception. + static AttentionAcks fromJson(Object? value) { + if (value is! Map) return const AttentionAcks(); + final dismissed = value['dismissed']; + final chatSeen = value['chat_seen']; + return AttentionAcks( + dismissed: { + if (dismissed is List) + for (final key in dismissed) + if (key is String && key.isNotEmpty) key, + }, + chatSeen: { + if (chatSeen is Map) + for (final entry in chatSeen.entries) + if (entry.key is String && + entry.value is num && + (entry.value as num) > 0) + entry.key as String: (entry.value as num).toInt(), + }, + ); + } + + static AttentionAcks decode(String? stored) { + final text = (stored ?? '').trim(); + if (text.isEmpty) return const AttentionAcks(); + try { + return fromJson(jsonDecode(text)); + } catch (_) { + return const AttentionAcks(); + } + } +} + +/// The server's bound on one `ack_attention`; a larger queue is sent in parts. +const maxAttentionAckItems = 500; + +/// The first [limit] items of [acks], dismissals first, for one request. +AttentionAcks attentionAckBatch( + AttentionAcks acks, { + int limit = maxAttentionAckItems, +}) { + if (acks.length <= limit) return acks; + final keys = acks.dismissed.toList()..sort(); + final dismissed = keys.take(limit).toSet(); + final room = limit - dismissed.length; + return AttentionAcks( + dismissed: dismissed, + chatSeen: Map.fromEntries(acks.chatSeen.entries.take(room)), + ); +} diff --git a/app/lib/features/attention/runtime/attention_ack_queue.dart b/app/lib/features/attention/runtime/attention_ack_queue.dart new file mode 100644 index 00000000..3dd58e2a --- /dev/null +++ b/app/lib/features/attention/runtime/attention_ack_queue.dart @@ -0,0 +1,66 @@ +import 'package:shared_preferences/shared_preferences.dart'; + +import '../../../core/servers/server_scope.dart'; + +/// Persistence for acknowledgements made while the server could not take +/// them (offline, or a server without `ack_attention`). The value is the +/// opaque string from `AttentionAcks.encode`; both directions may fail, and a +/// failure only means the queue lives in memory for this session. +abstract interface class AttentionAckQueueStore { + Future read(); + + Future write(String value); +} + +/// `shared_preferences` storage scoped to the server, like the other device +/// caches. An unavailable plugin returns null/false instead of throwing. +class SharedPreferencesAttentionAckQueue implements AttentionAckQueueStore { + const SharedPreferencesAttentionAckQueue({this.serverId = ''}); + + static const key = 'pipelines.next.attention.pending_acks.v1'; + + final String serverId; + String get _key => scopedServerKey(key, serverId); + + Future _preferences() async { + try { + return await SharedPreferences.getInstance(); + } catch (_) { + return null; + } + } + + @override + Future read() async { + try { + return (await _preferences())?.getString(_key); + } catch (_) { + return null; + } + } + + @override + Future write(String value) async { + try { + return await (await _preferences())?.setString(_key, value) ?? false; + } catch (_) { + return false; + } + } +} + +/// An in-memory queue for tests and isolated fixtures. +class MemoryAttentionAckQueue implements AttentionAckQueueStore { + MemoryAttentionAckQueue({this.stored}); + + String? stored; + + @override + Future read() async => stored; + + @override + Future write(String value) async { + stored = value; + return true; + } +} diff --git a/app/lib/features/attention/runtime/attention_ack_sync.dart b/app/lib/features/attention/runtime/attention_ack_sync.dart new file mode 100644 index 00000000..6edabd0c --- /dev/null +++ b/app/lib/features/attention/runtime/attention_ack_sync.dart @@ -0,0 +1,239 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; + +import '../../../core/api_gateway.dart'; +import '../../../core/transport/connection_state.dart'; +import '../domain/attention_acks.dart'; +import 'attention_ack_queue.dart'; + +/// Keeps this device's attention acknowledgements in step with the server so +/// clearing on one device clears everywhere. +/// +/// [acks] is everything known to be acknowledged: the server's set, every +/// pushed `attention_acks_changed` delta and this device's own acknowledgements +/// (applied at once, before the server answers). Listeners — the Needs-you +/// controller and the chat list — fold it into their own state. +/// +/// An acknowledgement the server has not accepted yet stays in a persisted +/// queue and is re-sent on the next [connected]. A server refusal drops the +/// refused batch (it can never succeed); a server that does not know +/// `ack_attention` keeps the queue for a later upgrade and this device falls +/// back to its local state. +/// +/// With [sendOnly] (the app passes the socket's own send-only path, as the +/// run watch does) requests are not queued behind the transport's serialized +/// request/reply calls, so a connect-time read never delays the first screen's +/// list; the reply is matched by id from the pushed frames. +class AttentionAckSync extends ChangeNotifier { + AttentionAckSync({ + required this.gateway, + required this.queue, + this.sendOnly, + this.replyTimeout = const Duration(seconds: 30), + }) { + _frames = gateway.frames.listen(_onFrame); + } + + final ApiGateway gateway; + final AttentionAckQueueStore queue; + final String Function(String type, JsonMap fields)? sendOnly; + final Duration replyTimeout; + late final StreamSubscription _frames; + final Map> _replies = {}; + + AttentionAcks _acks = const AttentionAcks(); + AttentionAcks _pending = const AttentionAcks(); + Future? _loading; + Future? _flushing; + bool _supported = true; + bool _disposed = false; + + /// Everything acknowledged on any device, as far as this device knows. + AttentionAcks get acks => _acks; + + /// Acknowledgements made here that the server has not accepted yet. + AttentionAcks get pending => _pending; + + /// False after the server answered `attention_acks` with something else + /// (an older server); reset on the next [connected]. + bool get supported => _supported; + + /// Reads the persisted offline queue once. + Future load() => _loading ??= _load(); + + Future _load() async { + String? stored; + try { + stored = await queue.read(); + } catch (_) { + stored = null; + } + if (_disposed) return; + final queued = AttentionAcks.decode(stored); + _pending = queued.merge(_pending); + _apply(queued); + } + + /// Records an acknowledgement made on this device: it applies here at once + /// and is sent to the server (now, or on the next [connected]). + Future acknowledge({ + Iterable dismissed = const [], + Map chatSeen = const {}, + }) async { + final ack = AttentionAcks( + dismissed: { + for (final key in dismissed) + if (key.trim().isNotEmpty) key, + }, + chatSeen: { + for (final entry in chatSeen.entries) + if (entry.key.isNotEmpty && entry.value > 0) entry.key: entry.value, + }, + ); + if (_disposed || ack.isEmpty) return; + await load(); + if (_disposed) return; + _pending = _pending.merge(ack); + _apply(ack); + await _persist(); + await flush(); + } + + /// Called on every connected transition of the shared socket: send what was + /// queued while disconnected, then read the server's whole set. + Future connected() async { + if (_disposed) return; + _supported = true; + // Replies still awaited belong to the replaced socket and never arrive; + // fail them now so a stalled flush does not hold up this connection. + _failReplies(StateError('Connection replaced')); + await load(); + await flush(); + if (_disposed || !_supported) return; + try { + final reply = await _request('attention_acks'); + _accept(reply); + } catch (_) { + // Offline or refused: the local state still applies; the next + // connection reads again. + } + } + + /// Sends the queue in bounded batches, one request at a time. + Future flush() => _flushing ??= _flush().whenComplete(() { + _flushing = null; + }); + + Future _flush() async { + while (!_disposed && _supported && !_pending.isEmpty) { + final batch = attentionAckBatch(_pending); + try { + final reply = await _request('ack_attention', { + 'attention_acks': batch.toJson(), + }); + if (!_accept(reply)) return; + } on ProtocolError { + // The server refused this batch; it will never be accepted. + } catch (_) { + return; // Not connected or timed out: keep it for the next connection. + } + _pending = _pending.without(batch); + await _persist(); + } + } + + /// Folds an `attention_acks` reply; false when the server answered with + /// another type, i.e. it does not support shared acknowledgements. + bool _accept(JsonMap reply) { + if (reply['type'] != 'attention_acks') { + _supported = false; + return false; + } + _apply(AttentionAcks.fromJson(reply['attention_acks'])); + return true; + } + + void _onFrame(JsonMap frame) { + final id = frame['id']; + final reply = id is String ? _replies.remove(id) : null; + if (reply != null) { + if (frame['type'] == 'error') { + final reason = '${frame['error'] ?? ''}'.trim(); + reply.completeError( + ProtocolError(reason.isEmpty ? 'server error' : reason), + ); + } else { + reply.complete(frame); + } + return; + } + if (frame['type'] != 'attention_acks_changed') return; + _apply(AttentionAcks.fromJson(frame['attention_acks'])); + } + + /// One request: through [sendOnly] when available (reply matched by id), + /// else the gateway's ordinary request/reply call. + Future _request(String type, [JsonMap fields = const {}]) { + final send = sendOnly; + if (send == null) return gateway.call(type, fields); + final String id; + try { + id = send(type, fields); + } catch (error) { + return Future.error(error); + } + final reply = Completer(); + _replies[id] = reply; + return reply.future.timeout( + replyTimeout, + onTimeout: () { + _replies.remove(id); + throw TimeoutException('$type timed out', replyTimeout); + }, + ); + } + + void _apply(AttentionAcks incoming) { + if (_disposed) return; + final next = _acks.merge(incoming); + if (identical(next, _acks)) return; + _acks = next; + notifyListeners(); + } + + Future _persist() async { + try { + await queue.write(_pending.encode()); + } catch (_) { + // The queue still lives in memory for this session. + } + } + + @override + void dispose() { + _disposed = true; + unawaited(_frames.cancel()); + _failReplies(StateError('Attention sync disposed')); + super.dispose(); + } + + void _failReplies(Object error) { + final waiting = _replies.values.toList(); + _replies.clear(); + for (final reply in waiting) { + reply.completeError(error); + } + } +} + +final _syncs = Expando('attention acknowledgement sync'); + +/// Makes [sync] the acknowledgement channel of [gateway], so feature +/// controllers created later for the same socket (the chat list) share it. +void bindAttentionAckSync(ApiGateway gateway, AttentionAckSync? sync) { + _syncs[gateway] = sync; +} + +/// The acknowledgement channel bound to [gateway], if the app bound one. +AttentionAckSync? attentionAckSyncOf(ApiGateway gateway) => _syncs[gateway]; diff --git a/app/lib/features/attention/runtime/attention_controller.dart b/app/lib/features/attention/runtime/attention_controller.dart index d80e3fcc..697152ba 100644 --- a/app/lib/features/attention/runtime/attention_controller.dart +++ b/app/lib/features/attention/runtime/attention_controller.dart @@ -6,6 +6,7 @@ import '../../../core/api_gateway.dart'; import '../../runs/domain/run_events.dart'; import '../domain/attention_models.dart'; import '../domain/attention_transitions.dart'; +import 'attention_ack_sync.dart'; import 'attention_store.dart'; /// The live `Needs you` state behind the Runs-list bell. @@ -20,11 +21,22 @@ import 'attention_store.dart'; /// [AttentionStore] without blocking the caller. A failed read or write leaves /// the in-memory set in force for this session; neither direction can throw into /// the UI. +/// +/// With a [sync], dismissals are shared with every device: Dismiss and Clear +/// all are also acknowledged to the server, and identities dismissed elsewhere +/// (the server's set and pushed deltas) are folded in and cached locally, so +/// the local store doubles as the offline copy. class AttentionController extends ChangeNotifier { - AttentionController({required this.store, DateTime Function()? now}) - : _now = now ?? DateTime.now; + AttentionController({ + required this.store, + this.sync, + DateTime Function()? now, + }) : _now = now ?? DateTime.now { + sync?.addListener(_syncChanged); + } final AttentionStore store; + final AttentionAckSync? sync; final DateTime Function() _now; final AttentionTransitionDetector _detector = AttentionTransitionDetector(); final List _transitions = []; @@ -75,6 +87,16 @@ class AttentionController extends ChangeNotifier { // older stored value; the in-memory set is the operator's latest intent. if (!_dirty) _dismissed = stored; notifyListeners(); + _syncChanged(); + } + + /// Folds identities acknowledged on any device into this set. A change is + /// cached in the local store; nothing is sent back to the server. + void _syncChanged() { + final shared = sync?.acks.dismissed; + if (_disposed || !_loaded || shared == null) return; + if (_dismissed.containsAll(shared)) return; + unawaited(_commit({..._dismissed, ...shared})); } /// Replaces the drawn rows with an authoritative read. @@ -149,12 +171,25 @@ class AttentionController extends ChangeNotifier { /// The in-memory set and the bell update before the store is touched, so a /// slow or failed write never blocks the sheet. The returned future reports /// whether the write succeeded; callers that do not need it may ignore it. - Future dismiss(AttentionEntry entry) => - _commit(attentionDismiss(_dismissed, entry.key)); + Future dismiss(AttentionEntry entry) { + _share([entry.key]); + return _commit(attentionDismiss(_dismissed, entry.key)); + } /// Applies only the identities captured when the sheet opened. - Future clearAll(Iterable snapshot) => - _commit(attentionDismissAll(_dismissed, snapshot)); + Future clearAll(Iterable snapshot) { + final entries = snapshot.toList(); + _share([for (final entry in entries) entry.key]); + return _commit(attentionDismissAll(_dismissed, entries)); + } + + /// Acknowledges [keys] to every device. The sync queues them while offline, + /// and sending never blocks or fails the local dismissal. + void _share(List keys) { + final shared = sync; + if (_disposed || shared == null || keys.isEmpty) return; + unawaited(shared.acknowledge(dismissed: keys)); + } Future _commit(Set next) async { final unchanged = @@ -174,6 +209,7 @@ class AttentionController extends ChangeNotifier { @override void dispose() { _disposed = true; + sync?.removeListener(_syncChanged); super.dispose(); } } diff --git a/app/lib/features/chat/ui/sessions/chat_sessions_controller.dart b/app/lib/features/chat/ui/sessions/chat_sessions_controller.dart index 64b49a62..e11afd84 100644 --- a/app/lib/features/chat/ui/sessions/chat_sessions_controller.dart +++ b/app/lib/features/chat/ui/sessions/chat_sessions_controller.dart @@ -1,10 +1,12 @@ import 'dart:async'; +import 'dart:math'; import 'package:flutter/foundation.dart'; import '../../../../core/api_gateway.dart'; import '../../../../core/servers/server_scope.dart'; import '../../../../core/transport/connection_state.dart'; +import '../../../attention/runtime/attention_ack_sync.dart'; import '../../data/chat_repository.dart'; import '../../domain/chat_sessions.dart'; import 'chat_session_local.dart'; @@ -16,18 +18,40 @@ import 'session_attention.dart'; /// discarded, so a slow reply can never replace fresher state. Accepted /// mutations always re-read the server list; only this device's hidden ids and /// read watermark are local. +/// +/// With an [AttentionAckSync] (bound to the gateway by the app, or passed in), +/// reading is shared: opening a chat acknowledges a `chat_seen` watermark to +/// every device, and a watermark acknowledged elsewhere that is newer than this +/// device's own clears the chat's New badge here. The local store remains the +/// offline cache of both. class ChatSessionsController extends ChangeNotifier { - ChatSessionsController(this.repository, {ChatSessionLocalStore? localStore}) - : _localStore = - localStore ?? - SharedPreferencesChatSessionLocalStore( - serverId: serverStorageScope(serverIdentity(repository.gateway)), - ) { + ChatSessionsController( + this.repository, { + ChatSessionLocalStore? localStore, + AttentionAckSync? ackSync, + int Function()? nowMillis, + this.activeAckDelay = const Duration(milliseconds: 1500), + }) : _localStore = + localStore ?? + SharedPreferencesChatSessionLocalStore( + serverId: serverStorageScope(serverIdentity(repository.gateway)), + ), + _nowMillis = nowMillis ?? _wallClockMillis { _listenFrames(); + _bindAckSync(ackSync ?? attentionAckSyncOf(repository.gateway)); } + static int _wallClockMillis() => DateTime.now().millisecondsSinceEpoch; + + /// How long the open chat stays quiet before its new content is + /// acknowledged to the other devices; streaming text arrives in many frames. + final Duration activeAckDelay; + ChatRepository repository; final ChatSessionLocalStore _localStore; + final int Function() _nowMillis; + AttentionAckSync? _ackSync; + Timer? _activeAck; ChatSessionLocal _local = const ChatSessionLocal(); final Map _actionErrors = {}; List _sessions = const []; @@ -59,6 +83,59 @@ class ChatSessionsController extends ChangeNotifier { if (row['closed_at'] != null || row['closed'] == true) return; if (effect.running != null) _setRunning(id, effect.running!); if (effect.attention && id != activeSessionId) unawaited(_markUnseen(id)); + if (effect.attention && id == activeSessionId) _scheduleActiveAck(id); + } + + void _bindAckSync(AttentionAckSync? sync) { + if (identical(sync, _ackSync)) return; + _ackSync?.removeListener(_ackChanged); + _ackSync = sync; + sync?.addListener(_ackChanged); + _ackChanged(); + } + + /// Content arriving in the chat this device has open is read here, so it is + /// acknowledged to the other devices once the stream goes quiet. + void _scheduleActiveAck(String id) { + if (_ackSync == null) return; + _activeAck?.cancel(); + _activeAck = Timer(activeAckDelay, () { + if (_disposed || id != activeSessionId) return; + unawaited(_acknowledgeSeen(id, 0)); + }); + } + + /// Applies watermarks acknowledged on any device: one newer than this + /// device's own marks the chat read here (clearing its New badge) and raises + /// the local watermark, so a later badge is not cleared by the same ack. + void _ackChanged() { + final seen = _ackSync?.acks.chatSeen; + if (_disposed || !_localLoaded || seen == null) return; + var next = _local; + seen.forEach((id, at) { + if (at > next.watermark(id)) next = next.read(id, at); + }); + if (identical(next, _local)) return; + _local = next; + _notify(); + unawaited(_persist()); + } + + /// Marks [id] read up to now here and acknowledges it to every device. The + /// value is at least the row's own recency; the server lifts it further to + /// the session's registry recency. + Future _acknowledgeSeen(String id, int updatedAt) async { + await _ensureLocal(); + if (_disposed) return; + final at = max(updatedAt, _nowMillis()); + final next = _local.read(id, at); + if (!identical(next, _local)) { + _local = next; + _notify(); + await _persist(); + } + if (_disposed) return; + await _ackSync?.acknowledge(chatSeen: {id: at}); } void _setRunning(String id, bool running) { @@ -126,6 +203,7 @@ class ChatSessionsController extends ChangeNotifier { repository = next; _runningFrames.clear(); _listenFrames(); + _bindAckSync(attentionAckSyncOf(next.gateway) ?? _ackSync); refresh(); } @@ -242,7 +320,9 @@ class ChatSessionsController extends ChangeNotifier { activeSessionId = id; await _ensureLocal(); if (_disposed) return; - final next = _local.read(id, chatSessionMillis(session['updated_at'])); + final updatedAt = chatSessionMillis(session['updated_at']); + if (_ackSync != null) return _acknowledgeSeen(id, updatedAt); + final next = _local.read(id, updatedAt); if (identical(next, _local)) return; _local = next; _notify(); @@ -313,6 +393,7 @@ class ChatSessionsController extends ChangeNotifier { } _localLoaded = true; _seedLocal(); + _ackChanged(); _notify(); } @@ -351,6 +432,8 @@ class ChatSessionsController extends ChangeNotifier { _disposed = true; _generation++; unawaited(_frameSubscription?.cancel()); + _activeAck?.cancel(); + _ackSync?.removeListener(_ackChanged); super.dispose(); } } diff --git a/app/notes/synced-attention.md b/app/notes/synced-attention.md new file mode 100644 index 00000000..81d655d2 --- /dev/null +++ b/app/notes/synced-attention.md @@ -0,0 +1,97 @@ +# Synced attention: clearing on one device clears everywhere + +Operator request: "when I clear notifications, it should clear in all places, +not only on the web and then I have to clear again on mobile." + +## What is shared + +- **Needs-you dismissals.** Dismiss and Clear all in the Needs-you sheet. Each + entry's identity is `{runId}:{Decision|Failed}` (`attentionKey`). +- **Chat New badges.** Opening a chat, and content arriving in the chat this + device has open, records a per-session `chat_seen` watermark in epoch ms. + +ntfy notifications already shown on a phone cannot be retracted (see +`docs/ntfy.md`, "Clearing notifications across devices"). + +## Protocol (server, `internal/protocol/attention_acks.go`) + +| Direction | Envelope | +| --- | --- | +| read | `{"type":"attention_acks"}` → `{"type":"attention_acks","attention_acks":{"dismissed":[…],"chat_seen":{…}}}` (the whole set) | +| add | `{"type":"ack_attention","attention_acks":{"dismissed":["42:Failed"],"chat_seen":{"ses_x":1730000000000}}}` → same reply (the whole set) | +| push | `{"type":"attention_acks_changed","attention_acks":{…}}`: only what changed, sent to every *other* connection | + +The set only grows: dismissals are added and watermarks only advance. That makes +merging a union/max that is safe to apply in any order or twice. Invalid +identities, invalid session ids, non-positive times, empty acks and acks with +more than 500 items are refused with `error`, and nothing is written. Dismissals +of unknown runs and watermarks for sessions that are not operator sessions are +skipped silently. A stored watermark is +`max(old, client value, operator_sessions.last_used_at)`. + +Storage: two additive SQLite tables, `attention_dismissals(key, run_id, +dismissed_at)` and `chat_seen_watermarks(session_id, seen_at, acked_at)`, +created in `Store.Open`. Each ack prunes rows for deleted runs and sessions, and +rows older than 30 days (`AttentionAckRetention`). + +**Clear all** sends the identities the sheet showed (its snapshot), not a +"cleared up to time T" marker. A time marker would hide a run created before T +that starts waiting on a person after T. The snapshot keeps the existing +"entries that arrive later stay" rule, and the request is bounded to 500 +identities per batch. + +## App + +- `features/attention/domain/attention_acks.dart`: the value type (merge, + `without`, encode/decode, bounded batches). +- `features/attention/runtime/attention_ack_sync.dart` (`AttentionAckSync`): one + per app/gateway, bound with `bindAttentionAckSync`. It applies local + acknowledgements immediately and queues them persistently + (`attention_ack_queue.dart`, SharedPreferences, server-scoped). On every + connected transition it flushes the queue and reads the set. It also applies + pushed deltas. It sends through the socket's send-only path, so the + connect-time read never queues ahead of the first screen's request. A + refusal drops the batch. An older server that answers `pong` keeps the queue + and turns syncing off until the next connection, so the local state still + applies. +- `AttentionController(sync:)`: Dismiss and Clear all also acknowledge. Shared + identities are unioned into the local set and cached in the existing local + store, which acts as the offline copy. +- `ChatSessionsController`: looks up the bound sync. Opening a chat stores and + acknowledges `max(row updated_at, now)`. A shared watermark newer than this + device's own clears the badge and raises the local watermark, so the same + acknowledgement cannot later clear newer content. Content arriving in the open + chat is acknowledged after 1.5 s of quiet. +- `PipelinesApp` creates and binds the sync, loads the queue, and calls + `connected()` on each connection epoch. + +The Needs-you sheet layout was not touched. + +## Known limits + +- The chat watermark compares a device clock with server times, so large clock + skew can mis-order a badge. +- An acknowledgement queued offline for a long time can clear a badge for + content that arrived between the offline open and the reconnect. +- Local dismissals made before this change are not uploaded. Only new + dismissals are shared. + +## Tests + +- Go: `internal/pipeline/attention_acks_test.go` (persist/reopen, advance-only, + unknown skipped, registry lift, prune deleted/expired, malformed refused), + `internal/server/attention_acks_test.go` (two websocket clients: push to the + other, no push for malformed/no-op acks), and + `internal/protocol/attention_acks_test.go`. +- Flutter: `test/features/attention/runtime/attention_ack_sync_test.dart` (two + devices: dismiss, Clear all, late connect, offline queue, restart, refusal, + legacy server, send-only path) and + `test/features/chat/ui/sessions/chat_seen_sync_test.dart` (open clears + everywhere, an earlier ack never clears later content, open-chat content, and + offline open synced on reconnect). + +## Deployment + +The server needs a rebuild and restart to serve the new requests; the tables are +created on open. The rebuilt web app and APK also need publishing. Until the +server is upgraded, the app keeps working with its local state and its queue. diff --git a/app/test/features/attention/runtime/attention_ack_sync_test.dart b/app/test/features/attention/runtime/attention_ack_sync_test.dart new file mode 100644 index 00000000..7f67f4cf --- /dev/null +++ b/app/test/features/attention/runtime/attention_ack_sync_test.dart @@ -0,0 +1,198 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/attention/domain/attention_acks.dart'; +import 'package:pipelines_app/features/attention/runtime/attention_ack_queue.dart'; +import 'package:pipelines_app/features/attention/runtime/attention_ack_sync.dart'; +import 'package:pipelines_app/features/attention/runtime/attention_controller.dart'; +import 'package:pipelines_app/features/attention/runtime/attention_store.dart'; + +import 'fake_ack_server.dart'; + +final _now = DateTime(2026, 10, 22, 12); + +Map _failed(int id) => { + 'id': id, + 'name': 'release', + 'title': 'Run $id', + 'status': 'failed', + 'created_at': _now.subtract(const Duration(hours: 1)).toIso8601String(), + 'finished_at': _now.subtract(const Duration(minutes: 30)).toIso8601String(), +}; + +/// One device: its gateway, sync, local stores and Needs-you controller. +class _Device { + _Device(FakeAckServer server) + : client = server.connect(), + store = MemoryAttentionStore(), + queue = MemoryAttentionAckQueue() { + sync = AttentionAckSync(gateway: client, queue: queue); + attention = AttentionController(store: store, sync: sync, now: () => _now); + } + + final FakeAckClient client; + final MemoryAttentionStore store; + final MemoryAttentionAckQueue queue; + late final AttentionAckSync sync; + late final AttentionController attention; + + Future start(List> rows) async { + await sync.load(); + await attention.load(); + attention.seedRows(rows); + await sync.connected(); + } + + List get shown => [for (final e in attention.entries) e.runId]; + + void dispose() { + attention.dispose(); + sync.dispose(); + } +} + +void main() { + late FakeAckServer server; + late _Device web; + late _Device phone; + final rows = [_failed(1), _failed(2), _failed(3)]; + + setUp(() async { + server = FakeAckServer(); + web = _Device(server); + phone = _Device(server); + await web.start(rows); + await phone.start(rows); + }); + + tearDown(() { + web.dispose(); + phone.dispose(); + }); + + test( + 'a dismissal on one device disappears on the other via the push', + () async { + expect(phone.shown, [3, 2, 1]); + await web.attention.dismiss( + web.attention.entries.firstWhere((e) => e.runId == 2), + ); + await settle(); + + expect(web.shown, [3, 1]); + expect(phone.shown, [3, 1]); + expect(server.state.dismissed, {'2:Failed'}); + // The other device caches the shared identity locally for offline use. + expect(phone.store.stored, contains('2:Failed')); + // The receiving device did not send anything back. + expect(phone.client.count('ack_attention'), 0); + }, + ); + + test('Clear all on the web clears the phone too', () async { + final snapshot = web.attention.entries; + await web.attention.clearAll(snapshot); + await settle(); + + expect(web.shown, isEmpty); + expect(phone.shown, isEmpty); + expect(server.state.dismissed, {'1:Failed', '2:Failed', '3:Failed'}); + }); + + test('a device that connects later loads the shared set', () async { + await web.attention.dismiss(web.attention.entries.first); + await settle(); + final late = _Device(server); + addTearDown(late.dispose); + await late.start(rows); + await settle(); + expect(late.shown, [2, 1]); + }); + + test( + 'a dismissal made offline is queued, then synced on reconnect', + () async { + phone.client.online = false; + await phone.attention.dismiss(phone.attention.entries.first); + await settle(); + + expect(phone.shown, [2, 1]); + expect(web.shown, [3, 2, 1]); + expect(phone.sync.pending.dismissed, {'3:Failed'}); + expect(AttentionAcks.decode(phone.queue.stored).dismissed, {'3:Failed'}); + + // A restarted app reads the persisted queue. + final restarted = AttentionAckSync( + gateway: phone.client, + queue: phone.queue, + ); + addTearDown(restarted.dispose); + await restarted.load(); + expect(restarted.pending.dismissed, {'3:Failed'}); + + phone.client.online = true; + await phone.sync.connected(); + await settle(); + + expect(phone.sync.pending.isEmpty, isTrue); + expect(AttentionAcks.decode(phone.queue.stored).isEmpty, isTrue); + expect(web.shown, [2, 1]); + }, + ); + + test('a refused batch is dropped; a legacy server keeps the queue', () async { + server.refuse = 'invalid attention identity'; + await web.sync.acknowledge(dismissed: ['9:Failed']); + expect(web.sync.pending.isEmpty, isTrue); + + server + ..refuse = null + ..legacy = true; + await web.sync.connected(); + expect(web.sync.supported, isFalse); + await web.attention.dismiss(web.attention.entries.first); + await settle(); + expect(web.shown, [2, 1], reason: 'the local dismissal still applies'); + expect(web.sync.pending.dismissed, {'3:Failed'}); + + server.legacy = false; + await web.sync.connected(); + await settle(); + expect(web.sync.pending.isEmpty, isTrue); + expect(phone.shown, [2, 1]); + }); + + test('batches stay within the server bound', () { + final big = AttentionAcks( + dismissed: {for (var i = 1; i <= 600; i++) '$i:Failed'}, + chatSeen: const {'ses_a': 1}, + ); + final batch = attentionAckBatch(big); + expect(batch.length, maxAttentionAckItems); + final rest = big.without(batch); + expect(rest.length, big.length - maxAttentionAckItems); + }); + + test('the send-only path matches replies and refusals by id', () async { + final client = server.connect(); + final sync = AttentionAckSync( + gateway: client, + queue: MemoryAttentionAckQueue(), + sendOnly: client.sendOnly, + ); + addTearDown(sync.dispose); + await sync.acknowledge(dismissed: ['1:Failed']); + await settle(); + expect(sync.pending.isEmpty, isTrue); + expect(phone.shown, [3, 2]); + + server.refuse = 'invalid attention identity'; + await sync.acknowledge(dismissed: ['2:Failed']); + await settle(); + expect(sync.pending.isEmpty, isTrue, reason: 'a refusal is dropped'); + + server.refuse = null; + await web.attention.dismiss(web.attention.entries.first); + await settle(); + await sync.connected(); + expect(sync.acks.dismissed, containsAll(['1:Failed', '3:Failed'])); + }); +} diff --git a/app/test/features/attention/runtime/fake_ack_server.dart b/app/test/features/attention/runtime/fake_ack_server.dart new file mode 100644 index 00000000..78cf75fe --- /dev/null +++ b/app/test/features/attention/runtime/fake_ack_server.dart @@ -0,0 +1,113 @@ +import 'dart:async'; + +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/core/transport/connection_state.dart'; +import 'package:pipelines_app/features/attention/domain/attention_acks.dart'; + +/// An in-memory stand-in for the server's `attention_acks` / `ack_attention` +/// protocol with any number of connected clients. Like the Go handler, an ack +/// that changes the set is pushed to every *other* connected client as an +/// `attention_acks_changed` delta. +class FakeAckServer { + AttentionAcks state = const AttentionAcks(); + final clients = []; + + /// When set, every ack_attention is refused with this reason. + String? refuse; + + /// When true the server predates shared acks and answers `pong`. + bool legacy = false; + + /// The chat list this server reports, for chat-list controllers. + List chatSessions = const []; + + FakeAckClient connect() { + final client = FakeAckClient(this); + clients.add(client); + return client; + } + + JsonMap _reply() => { + 'type': 'attention_acks', + 'attention_acks': state.toJson(), + }; + + JsonMap _ack(FakeAckClient from, JsonMap fields) { + final incoming = AttentionAcks.fromJson(fields['attention_acks']); + final delta = AttentionAcks( + dismissed: incoming.dismissed.difference(state.dismissed), + chatSeen: { + for (final entry in incoming.chatSeen.entries) + if (entry.value > (state.chatSeen[entry.key] ?? 0)) + entry.key: entry.value, + }, + ); + state = state.merge(incoming); + if (!delta.isEmpty) { + for (final client in clients) { + if (identical(client, from) || !client.online) continue; + client.pushed.add({ + 'type': 'attention_acks_changed', + 'attention_acks': delta.toJson(), + }); + } + } + return _reply(); + } +} + +class FakeAckClient implements ApiGateway { + FakeAckClient(this.server); + + final FakeAckServer server; + final pushed = StreamController.broadcast(); + final calls = []; + bool online = true; + + @override + Stream get frames => pushed.stream; + + @override + Future call(String type, [JsonMap fields = const {}]) async { + calls.add(type); + if (!online) throw const NotConnectedError(); + switch (type) { + case 'attention_acks': + case 'ack_attention': + if (server.legacy) return {'type': 'pong'}; + if (type == 'attention_acks') return server._reply(); + final reason = server.refuse; + if (reason != null) throw ProtocolError(reason); + return server._ack(this, fields); + case 'chat_sessions': + return {'type': 'chat_sessions', 'chat_sessions': server.chatSessions}; + } + return {'type': 'pong'}; + } + + int count(String type) => calls.where((call) => call == type).length; + + var _sequence = 0; + + /// The socket's send-only path: the reply (or error) arrives later as a + /// frame carrying the request id, like the real transport. + String sendOnly(String type, JsonMap fields) { + if (!online) throw const NotConnectedError(); + final id = 'send-${++_sequence}'; + scheduleMicrotask(() async { + try { + pushed.add({...await call(type, fields), 'id': id}); + } on ProtocolError catch (error) { + pushed.add({'type': 'error', 'id': id, 'error': error.message}); + } + }); + return id; + } +} + +/// Lets queued microtasks and stream deliveries settle. +Future settle() async { + for (var i = 0; i < 10; i++) { + await Future.delayed(Duration.zero); + } +} diff --git a/app/test/features/chat/ui/sessions/chat_seen_sync_test.dart b/app/test/features/chat/ui/sessions/chat_seen_sync_test.dart new file mode 100644 index 00000000..51258f9d --- /dev/null +++ b/app/test/features/chat/ui/sessions/chat_seen_sync_test.dart @@ -0,0 +1,167 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/attention/runtime/attention_ack_queue.dart'; +import 'package:pipelines_app/features/attention/runtime/attention_ack_sync.dart'; +import 'package:pipelines_app/features/chat/data/chat_repository.dart'; +import 'package:pipelines_app/features/chat/ui/sessions/chat_session_local.dart'; +import 'package:pipelines_app/features/chat/ui/sessions/chat_sessions_controller.dart'; + +import '../../../attention/runtime/fake_ack_server.dart'; +import 'chat_test_harness.dart'; + +JsonMap _text(String id) => { + 'type': 'chat_event', + 'chat_event': {'session_id': id, 'kind': 'text', 'delta': 'hello'}, +}; + +/// One device's chat list sharing read state through [FakeAckServer]. +class _Device { + _Device(FakeAckServer server, {required this.clock}) + : client = server.connect(), + local = MemoryChatSessionLocalStore() { + sync = AttentionAckSync(gateway: client, queue: MemoryAttentionAckQueue()); + bindAttentionAckSync(client, sync); + list = ChatSessionsController( + ChatRepository(client), + localStore: local, + nowMillis: () => clock(), + activeAckDelay: const Duration(milliseconds: 20), + ); + } + + final FakeAckClient client; + final MemoryChatSessionLocalStore local; + final int Function() clock; + late final AttentionAckSync sync; + late final ChatSessionsController list; + + Future start() async { + await sync.connected(); + await list.refresh(); + await settle(); + } + + bool isNew(String id) => + list.isUnseen(list.sessions.firstWhere((row) => row['id'] == id)); + + JsonMap row(String id) => list.sessions.firstWhere((row) => row['id'] == id); + + void dispose() { + list.dispose(); + sync.dispose(); + } +} + +void main() { + late FakeAckServer server; + late _Device web; + late _Device phone; + var now = 5000; + + setUp(() async { + now = 5000; + server = FakeAckServer() + ..chatSessions = [ + {'id': 'ses_a', 'title': 'A', 'directory': '/w', 'updated_at': 1000}, + {'id': 'ses_b', 'title': 'B', 'directory': '/w', 'updated_at': 1000}, + ]; + web = _Device(server, clock: () => now); + phone = _Device(server, clock: () => now); + await web.start(); + await phone.start(); + }); + + tearDown(() { + web.dispose(); + phone.dispose(); + }); + + void pushToAll(JsonMap frame) { + for (final client in server.clients) { + client.pushed.add(frame); + } + } + + test( + 'opening a chat on one device clears its New badge everywhere', + () async { + pushToAll(_text('ses_a')); + await settle(); + expect(web.isNew('ses_a'), isTrue); + expect(phone.isNew('ses_a'), isTrue); + + now = 6000; + await web.list.markOpened(web.row('ses_a')); + await settle(); + + expect(server.state.chatSeen['ses_a'], 6000); + expect(phone.isNew('ses_a'), isFalse); + expect(phone.local.state?.watermark('ses_a'), 6000); + // Only the opened chat is affected. + pushToAll(_text('ses_b')); + await settle(); + expect(phone.isNew('ses_b'), isTrue); + }, + ); + + test('an earlier acknowledgement never clears later content', () async { + now = 6000; + await web.list.markOpened(web.row('ses_a')); + web.list.activeSessionId = null; + await settle(); + // New content after the open: the phone marks it New and a reload of the + // same shared watermark must not clear it. + pushToAll(_text('ses_a')); + await settle(); + expect(phone.isNew('ses_a'), isTrue); + await phone.sync.connected(); + await settle(); + expect(phone.isNew('ses_a'), isTrue); + }); + + test('content arriving in a chat open elsewhere is read there', () async { + now = 6000; + await web.list.markOpened(web.row('ses_a')); + await settle(); + now = 7000; + pushToAll(_text('ses_a')); + await settle(); + expect(phone.isNew('ses_a'), isTrue); + expect(web.isNew('ses_a'), isFalse); + + // The open chat acknowledges once its stream goes quiet (20 ms here). + for (var i = 0; i < 100 && server.state.chatSeen['ses_a'] != 7000; i++) { + await Future.delayed(const Duration(milliseconds: 20)); + } + await settle(); + expect(server.state.chatSeen['ses_a'], 7000); + expect(phone.isNew('ses_a'), isFalse); + }); + + test('a chat opened offline is synced and cleared on reconnect', () async { + pushToAll(_text('ses_a')); + await settle(); + web.client.online = false; + now = 6000; + await web.list.markOpened(web.row('ses_a')); + await settle(); + expect(phone.isNew('ses_a'), isTrue); + expect(web.sync.pending.chatSeen, {'ses_a': 6000}); + + web.client.online = true; + await web.sync.connected(); + await settle(); + expect(phone.isNew('ses_a'), isFalse); + + // A device that was not connected for the push applies the stored set + // on its next connection. + final late = _Device(server, clock: () => now); + addTearDown(late.dispose); + late.local.state = const ChatSessionLocal( + seenAt: {'ses_a': 1000}, + unseen: ['ses_a'], + ); + await late.start(); + expect(late.isNew('ses_a'), isFalse); + }); +} diff --git a/docs/cli.md b/docs/cli.md index e2c5978e..4d07158a 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -316,7 +316,11 @@ Existing protocol commands: `ping`, `list_pipelines`, `get_pipeline`, optional `kind` and `limit`) and returns a `search_results` response whose ranked `results` each carry a stable `target` the client can open plus the typed payload and matched field. `list_runs` also returns all-history `usage` -aggregates. See `internal/protocol/message.go` for JSON envelopes. Mutating RPCs +aggregates. `attention_acks` reads and `ack_attention` adds to the operator's +shared in-app acknowledgements (dismissed Needs-you entries and chat read +watermarks; see [ntfy.md](ntfy.md#clearing-notifications-across-devices)); other +connections receive an `attention_acks_changed` push. See +`internal/protocol/message.go` for JSON envelopes. Mutating RPCs have real effects; they are not previews. TUI-only animation, scrolling, and transient client logs are presentation, not separate server capabilities. diff --git a/docs/ntfy.md b/docs/ntfy.md index 26175f21..17eb2018 100644 --- a/docs/ntfy.md +++ b/docs/ntfy.md @@ -182,6 +182,22 @@ changes any subset; both reply with type `notification_settings` carrying all three keys. Unknown keys and non-boolean values are refused with an `error` reply and nothing is written. +## Clearing notifications across devices + +The app's in-app attention state is shared through the server: dismissing an +entry or using **Clear all** in the Needs-you sheet, and opening a chat (which +clears its **New** badge), clears it on every connected browser and phone at +once, and on a disconnected device when it next connects. The protocol is +`{"type":"attention_acks"}` (read the whole set) and +`{"type":"ack_attention","attention_acks":{"dismissed":["42:Failed"],"chat_seen":{"ses_x":1730000000000}}}` +(add to it). Both reply `attention_acks`, and every other connection receives an +`attention_acks_changed` frame with the change. Acknowledgements for deleted runs +or sessions, or older than 30 days, are pruned. + +This does **not** reach notifications the ntfy app has already shown on a phone: +once ntfy delivered a message, the server cannot retract it, so those must still +be swiped away in the ntfy app (or the Android notification shade). + ## Explicit delivery stage (optional) The preceding stage must output three nonempty UTF-8 strings: `title`, `summary`,