From e2e61ac005d9013f34b142d38d8d51c1e7800164 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 12 Nov 2026 10:37:56 +0000 Subject: [PATCH 1/9] Fix shell rail surface and empty action island Paint the navigation rail through its top inset and only add the floating-windows action when a listed window exists. Add focused widget coverage and document the reviewed UI states so the shell no longer shows a white strip or empty trailing pill. --- app/lib/application/pipelines_app.dart | 6 +- app/lib/shell/adaptive_shell.dart | 19 +++- app/lib/shell/navigation_rail.dart | 63 +++++++----- .../shell/windows/windows_menu_button.dart | 5 + app/notes/rail-top-and-empty-island.md | 73 ++++++++++++++ .../shell/navigation_rail_surface_test.dart | 63 ++++++++++++ .../shell/shell_bar_empty_actions_test.dart | 98 +++++++++++++++++++ 7 files changed, 296 insertions(+), 31 deletions(-) create mode 100644 app/notes/rail-top-and-empty-island.md create mode 100644 app/test/shell/navigation_rail_surface_test.dart create mode 100644 app/test/shell/shell_bar_empty_actions_test.dart diff --git a/app/lib/application/pipelines_app.dart b/app/lib/application/pipelines_app.dart index 93eef0c5..1b422e3c 100644 --- a/app/lib/application/pipelines_app.dart +++ b/app/lib/application/pipelines_app.dart @@ -41,7 +41,6 @@ import '../shell/windows/window_host.dart'; import '../shell/windows/window_kind.dart'; import '../shell/windows/window_manager.dart'; import '../shell/windows/window_store.dart'; -import '../shell/windows/windows_menu_button.dart'; import 'app_terminals.dart'; import '../features/chat/chat_runtime.dart'; import '../features/chat/windows/chat_windows.dart'; @@ -841,9 +840,10 @@ class _PipelinesAppState extends State // The terminal button sits on the Chat tab's shell bar on wide layouts; // a narrow layout has it in the chat's own bar instead. The keyboard // shortcut still toggles the terminal everywhere. + // The Windows button (shown on every tab while the app has floating + // windows) is the shell's: it lists the manager's windows. + windowManager: _windows, barActions: [ - // Shown on every tab while the app has floating windows. - WindowsMenuButton(manager: _windows), if (_destinationOf(route.kind) == AppDestination.chat) ?_terminals.barToggle(context), ], diff --git a/app/lib/shell/adaptive_shell.dart b/app/lib/shell/adaptive_shell.dart index 2230419a..3ddc7c75 100644 --- a/app/lib/shell/adaptive_shell.dart +++ b/app/lib/shell/adaptive_shell.dart @@ -17,6 +17,8 @@ import 'shell_list_shortcuts.dart'; import 'shell_runs_pipelines_shortcut.dart'; import 'shell_search_shortcut_labels.dart'; import 'tab_history.dart'; +import 'windows/window_manager.dart'; +import 'windows/windows_menu_button.dart'; import '../ui/input/keyboard_owner.dart'; class AdaptiveShell extends StatefulWidget { @@ -33,12 +35,18 @@ class AdaptiveShell extends StatefulWidget { this.runningRunCount, this.listPaneWidthStore = const SharedPreferencesListPaneWidthStore(), this.barActions = const [], + this.windowManager, }); /// Actions every destination's bar ends with (the Terminal toggle), after /// the screen's own or Search. final List barActions; + /// The floating windows the bar's Windows button lists. The button is shown + /// only while one is open, so the bar draws no empty action island; null + /// (plain shells) shows none. + final WindowManager? windowManager; + /// Where each destination's dragged list-pane width is kept on this device. final ListPaneWidthStore listPaneWidthStore; @@ -241,7 +249,11 @@ class _AdaptiveShellState extends State { SegmentedBar currentBar() => _segmentedBar(_bar.specFor(_selected), details.label, page: page); final topBar = _ListPaneBar( - listenable: Listenable.merge([_bar.bar, _paneWidths]), + listenable: Listenable.merge([ + _bar.bar, + _paneWidths, + ?widget.windowManager, + ]), initial: currentBar(), split: () => _bar.split(_selected), preferredWidth: () => _paneWidths.widthFor(_selected.name), @@ -443,6 +455,7 @@ class _AdaptiveShellState extends State { final onBack = spec?.onBack ?? (page ? _closePage : null); final published = spec?.actions ?? const []; final onSearch = widget.onSearch; + final windows = widget.windowManager; return SegmentedBar( automaticallyImplyLeading: false, leading: onBack == null @@ -477,6 +490,10 @@ class _AdaptiveShellState extends State { tooltip: 'Search (${shellSearchShortcutLabels().join(', ')})', icon: const Icon(Icons.search), ), + // The Windows button leads the shell's own actions, only while a + // floating window is listed; an empty button would draw an empty island. + if (windows != null && WindowsMenuButton.hasWindows(windows)) + WindowsMenuButton(manager: windows), ...widget.barActions, ], ); diff --git a/app/lib/shell/navigation_rail.dart b/app/lib/shell/navigation_rail.dart index 93f6deec..83d5716f 100644 --- a/app/lib/shell/navigation_rail.dart +++ b/app/lib/shell/navigation_rail.dart @@ -50,35 +50,44 @@ class ShellNavigationRail extends StatelessWidget { @override Widget build(BuildContext context) { final index = shellTabDestinations.indexOf(selected); - return Padding( - padding: padding, - child: SizedBox( - width: kNavigationRailWidth, - child: NavigationRail( - key: const ValueKey('shell.navigation-rail'), - minWidth: kNavigationRailWidth, - labelType: NavigationRailLabelType.all, - selectedIndex: index < 0 ? null : index, - onDestinationSelected: (value) => - onSelected(shellTabDestinations[value]), - destinations: [ - for (final destination in shellTabDestinations) - NavigationRailDestination( - icon: KeyedSubtree( - key: ValueKey('shell.destination.${destination.name}'), - // The bar it replaces named each tab in a tooltip too. - child: Tooltip( - message: destinationDetails(destination).label, - child: icon(destination), + final surface = Theme.of(context).colorScheme.surface; + // The surface runs under the top inset too: the padding only moves the + // rail's content below the system's top, so no unpainted strip shows above + // the rail's background. + return ColoredBox( + key: const ValueKey('shell.navigation-rail.surface'), + color: surface, + child: Padding( + padding: padding, + child: SizedBox( + width: kNavigationRailWidth, + child: NavigationRail( + key: const ValueKey('shell.navigation-rail'), + backgroundColor: surface, + minWidth: kNavigationRailWidth, + labelType: NavigationRailLabelType.all, + selectedIndex: index < 0 ? null : index, + onDestinationSelected: (value) => + onSelected(shellTabDestinations[value]), + destinations: [ + for (final destination in shellTabDestinations) + NavigationRailDestination( + icon: KeyedSubtree( + key: ValueKey('shell.destination.${destination.name}'), + // The bar it replaces named each tab in a tooltip too. + child: Tooltip( + message: destinationDetails(destination).label, + child: icon(destination), + ), ), + label: Text(destinationDetails(destination).label), ), - label: Text(destinationDetails(destination).label), - ), - ], - trailingAtBottom: true, - trailing: _SettingsRailItem( - selected: selected == AppDestination.settings, - onTap: () => onSelected(AppDestination.settings), + ], + trailingAtBottom: true, + trailing: _SettingsRailItem( + selected: selected == AppDestination.settings, + onTap: () => onSelected(AppDestination.settings), + ), ), ), ), diff --git a/app/lib/shell/windows/windows_menu_button.dart b/app/lib/shell/windows/windows_menu_button.dart index ff8936f9..103d3c80 100644 --- a/app/lib/shell/windows/windows_menu_button.dart +++ b/app/lib/shell/windows/windows_menu_button.dart @@ -12,6 +12,11 @@ class WindowsMenuButton extends StatelessWidget { final WindowManager manager; + /// Whether [manager] has a window to list: the shell bar keeps the button + /// out of its actions otherwise, so no empty action island is drawn. + static bool hasWindows(WindowManager manager) => + manager.windows.any((w) => manager.kinds[w.kind] != null); + @override Widget build(BuildContext context) => ListenableBuilder( listenable: Listenable.merge([ diff --git a/app/notes/rail-top-and-empty-island.md b/app/notes/rail-top-and-empty-island.md new file mode 100644 index 00000000..75b1ff35 --- /dev/null +++ b/app/notes/rail-top-and-empty-island.md @@ -0,0 +1,73 @@ +# Rail top strip and empty top-right island + +Two shell chrome defects on the wide layout (run 20261112-1022). + +## Causes + +- **White strip above the rail (96x8 at y=0).** On a wide window + `WindowMargins` adds `wideExtraTop` (16 - 8 = 8 px) to `MediaQuery` top + padding. `ShellNavigationRail` pads its rail by that top inset with a plain + `Padding`, so the 8 px above the rail's Material surface was never painted + and showed the canvas behind it (white in both themes). +- **Empty circular pill (top right of Search and Settings).** + `pipelines_app.dart` put `WindowsMenuButton` in `barActions` on every tab. + The button returns `SizedBox.shrink()` with no open window, but + `SegmentedBar` counted it as an action, so the trailing island was drawn + around nothing. + +## Changes (app/) + +- `lib/shell/navigation_rail.dart`: the rail is wrapped in a `ColoredBox` + (key `shell.navigation-rail.surface`) in the theme surface, and the + `NavigationRail` gets the same `backgroundColor`. The top inset still moves + the rail's content down; the inset itself is painted. +- `lib/shell/windows/windows_menu_button.dart`: new static + `WindowsMenuButton.hasWindows(manager)`, the single predicate for "a window + is listed". +- `lib/shell/adaptive_shell.dart`: new optional `windowManager` parameter. + The shell adds the Windows button to the bar's actions only when + `hasWindows` is true, and merges the manager into the top bar's listenable + so the island appears and disappears with windows. +- `lib/application/pipelines_app.dart`: the Windows button is no longer in + `barActions`; `windowManager: _windows` is passed to the shell instead. + +## Tests (focused, run through tool/memwatch/full.sh) + +Paths: `test/shell/navigation_rail_surface_test.dart`, +`test/shell/shell_bar_empty_actions_test.dart`, +`test/shell/navigation_rail_test.dart` (existing, affected by the rail +change), `test/shell/windows/window_conveniences_test.dart` (existing, uses +`WindowsMenuButton` directly). + +- Result: `PASS: 28 passed, 0 failed, 0 skipped; peak 1128 MB; 4s; exit 0`. +- Rail surface, light and dark: the cover is at y=0, its colour equals the + theme surface, the rail's background equals it, the rail content starts at + the 8 px inset, and the strip above it is inside the cover. +- Action island: Search, Settings and Pipelines at 1000 px and 430 px draw no + `segmented.actions` island with no window; a shell with no window manager + draws none; the Windows button is the island only while a window is open + and goes away when it closes. + +`tool/analyze.sh`: clean, exit 0. + +Not run: the land gate and the full app suite (owned by the gate stage). +Pre-existing failures listed in the memory note were not checked here. + +## Affected UI states (for ui-review to capture) + +- Wide window (1600x1000), light and dark: rail top (should now be the + surface colour, not white), on every tab and on Settings. +- Wide and narrow (430x900), Search and Settings: no empty pill at top right. +- Wide window with one or more floating windows open: the Windows button is + shown in the top-right island. + +Before-captures exist in `/tmp/ui-review/` (`base-dark-1600x1000/12-settings.png`, +`base-light-430x900/11-search.png`, and others). No after-captures were +taken in this stage, per the stage rules; ui-review owns capture. + +## Limitations + +- The "rail top colour equals rail surface" check is a widget-tree check + (colour and rect), not a pixel read from a rendered frame. +- `WindowMargins` (the source of the 8 px) is untouched; the fix is at the + rail, so the rail's content position is unchanged. diff --git a/app/test/shell/navigation_rail_surface_test.dart b/app/test/shell/navigation_rail_surface_test.dart new file mode 100644 index 00000000..a10abcbe --- /dev/null +++ b/app/test/shell/navigation_rail_surface_test.dart @@ -0,0 +1,63 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/shell/destination.dart'; +import 'package:pipelines_app/shell/navigation_rail.dart'; + +/// The rail's surface runs from the window's top edge. The system's top inset +/// is kept clear for the rail's content, but it is painted with the rail's +/// surface, so no unpainted strip (white in the app's canvas) shows above it. +void main() { + for (final brightness in Brightness.values) { + testWidgets('the rail top under a system inset is the rail surface ' + '(${brightness.name})', (tester) async { + tester.view.physicalSize = const Size(1000, 800); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + final theme = ThemeData( + colorSchemeSeed: Colors.purple, + brightness: brightness, + ); + await tester.pumpWidget( + MaterialApp( + theme: theme, + home: Scaffold( + body: Row( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + ShellNavigationRail( + selected: AppDestination.pipelines, + icon: (destination) => + Icon(destinationDetails(destination).icon), + onSelected: (_) {}, + padding: const EdgeInsets.only(top: 8), + ), + ], + ), + ), + ), + ); + await tester.pumpAndSettle(); + + final surface = theme.colorScheme.surface; + final cover = find.byKey(const ValueKey('shell.navigation-rail.surface')); + final rail = find.byKey(const ValueKey('shell.navigation-rail')); + + // The cover and the rail's own background are the same surface colour. + expect(tester.widget(cover).color, surface); + expect(tester.widget(rail).backgroundColor, surface); + + // The rail's content starts below the inset, and the cover starts at the + // window's top edge, so the inset strip is covered. + final coverRect = tester.getRect(cover); + final railRect = tester.getRect(rail); + expect(coverRect.top, 0); + expect(railRect.top, 8); + expect( + coverRect.contains(Offset(railRect.center.dx, 2)), + isTrue, + reason: 'the strip above the rail content is painted', + ); + }); + } +} diff --git a/app/test/shell/shell_bar_empty_actions_test.dart b/app/test/shell/shell_bar_empty_actions_test.dart new file mode 100644 index 00000000..b87ab33b --- /dev/null +++ b/app/test/shell/shell_bar_empty_actions_test.dart @@ -0,0 +1,98 @@ +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/windows/window_manager.dart'; + +import 'windows/window_test_harness.dart'; + +/// The shell bar's trailing action island is drawn only with actions. The +/// Windows button is one of them only while a floating window is open, so +/// Search and Settings (and every other route) show no empty pill at any size. +void main() { + Future pumpShell( + WidgetTester tester, { + required AppDestination destination, + required double width, + WindowManager? windowManager, + }) async { + tester.view.physicalSize = Size(width, 800); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + await tester.pumpWidget( + MaterialApp( + home: AdaptiveShell( + destination: destination, + windowManager: windowManager, + destinationBodies: { + for (final value in AppDestination.values) + value: (_) => Text('${value.name} body'), + }, + ), + ), + ); + await tester.pumpAndSettle(); + } + + final actionIsland = find.byKey(const ValueKey('segmented.actions')); + + for (final width in [1000.0, 430.0]) { + for (final destination in [ + AppDestination.search, + AppDestination.settings, + AppDestination.pipelines, + ]) { + testWidgets( + '${destination.name} at width ${width.toInt()} draws no empty action ' + 'island with no floating window', + (tester) async { + await pumpShell( + tester, + destination: destination, + width: width, + windowManager: probeManager(), + ); + expect(actionIsland, findsNothing); + expect(find.byKey(const ValueKey('shell.windows')), findsNothing); + }, + ); + } + } + + testWidgets('a shell without a window manager draws no action island', ( + tester, + ) async { + await pumpShell(tester, destination: AppDestination.settings, width: 1000); + expect(actionIsland, findsNothing); + }); + + testWidgets('the Windows button is the island only while a window is open', ( + tester, + ) async { + final manager = probeManager(); + await pumpShell( + tester, + destination: AppDestination.search, + width: 1000, + windowManager: manager, + ); + expect(actionIsland, findsNothing); + + final entry = manager.open('probe', 'a'); + await tester.pumpAndSettle(); + expect(actionIsland, findsOneWidget); + expect( + find.descendant( + of: actionIsland, + matching: find.byKey(const ValueKey('shell.windows')), + ), + findsOneWidget, + ); + + manager.close(entry.id); + await tester.pumpAndSettle(); + expect(actionIsland, findsNothing); + expect(find.byKey(const ValueKey('shell.windows')), findsNothing); + }); +} From 77a88d09d30f52e2276228b05d2c4e83dc0270e2 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 12 Nov 2026 10:39:33 +0000 Subject: [PATCH 2/9] Make Settings a top-level navigation destination Show Back only when Settings is reached through a pushed route, and remove duplicate Settings controls where the shell already provides navigation. Update focused widget coverage and document the destination behavior. --- app/lib/application/pipelines_app.dart | 10 ++ app/lib/features/pipelines/screen.dart | 7 +- app/lib/shell/adaptive_shell.dart | 31 ++++- app/lib/shell/destination.dart | 7 +- app/lib/shell/navigation_rail.dart | 6 + app/notes/settings-destination-back.md | 72 +++++++++++ app/test/application/settings_page_test.dart | 116 ++++++++---------- .../settings_registration_test.dart | 7 +- .../tab_location_navigation_test.dart | 25 ++-- .../pipelines_settings_gear_test.dart | 73 +++++++++++ app/test/shell/navigation_rail_test.dart | 10 +- app/test/shell/settings_back_test.dart | 90 ++++++++++++++ 12 files changed, 353 insertions(+), 101 deletions(-) create mode 100644 app/notes/settings-destination-back.md create mode 100644 app/test/features/pipelines/pipelines_settings_gear_test.dart create mode 100644 app/test/shell/settings_back_test.dart diff --git a/app/lib/application/pipelines_app.dart b/app/lib/application/pipelines_app.dart index 93eef0c5..6606397f 100644 --- a/app/lib/application/pipelines_app.dart +++ b/app/lib/application/pipelines_app.dart @@ -706,6 +706,16 @@ class _PipelinesAppState extends State } void _selectDestination(AppDestination destination) { + // Settings is shown from its own nav item and has no Back, so its route + // (filed under the Pipelines tab) must not trap the Pipelines item: that + // item leaves Settings for the Pipelines body it showed before. + if (destination == AppDestination.pipelines && + _delegate.shellRoute.kind == AppRouteKind.settings) { + _delegate.goTo( + _bodyRoutes[AppDestination.pipelines] ?? AppRoute.pipelines, + ); + return; + } final last = _tabRoutes[destination]; _delegate.goTo(last ?? _routeOf(destination)); } diff --git a/app/lib/features/pipelines/screen.dart b/app/lib/features/pipelines/screen.dart index fb0ea904..55188ee9 100644 --- a/app/lib/features/pipelines/screen.dart +++ b/app/lib/features/pipelines/screen.dart @@ -2,7 +2,7 @@ import '../../ui/adaptive/segmented_bar.dart'; import '../../shell/destination.dart'; import '../../shell/detail_page.dart'; import '../../shell/list_detail.dart'; -import '../../shell/shell_rail_scope.dart'; +import '../../shell/navigation_rail.dart'; import 'package:flutter/material.dart'; import '../../core/api_gateway.dart'; @@ -289,9 +289,10 @@ class _PipelinesScreenState extends State { if (listShown && widget.onOpenSchedules != null) _schedulesButton(context), _refreshButton(context), - // A wide window's rail offers Settings; the gear stays on a phone. + // The phone's bar and the rail both offer Settings; the gear is only + // left where the floating tab bar (tabs only) is the shell's nav. if (listShown && - !ShellRailScope.isShown(context) && + showsFloatingTabBarOnly(context) && widget.onOpenSettings != null) _settingsButton(context), ], diff --git a/app/lib/shell/adaptive_shell.dart b/app/lib/shell/adaptive_shell.dart index 2230419a..505ed604 100644 --- a/app/lib/shell/adaptive_shell.dart +++ b/app/lib/shell/adaptive_shell.dart @@ -77,6 +77,11 @@ class _AdaptiveShellState extends State { late AppDestination _selected; final Set _visited = {}; final TabHistory _history = TabHistory(); + // The destination a shell control (rail, bar, floating bar) asked for and + // that is not shown yet. Settings reached this way is a destination; any + // other way in (a route, a deep link, the Pipelines gear) is a page to Back. + AppDestination? _navigatingTo; + bool _settingsPushed = false; // Whether a navigator inside each destination (an open item's pane) has a // page of its own for the system Back to close first. final Map _nestedCanPop = {}; @@ -100,6 +105,9 @@ class _AdaptiveShellState extends State { super.initState(); _bar.onNavigate = _select; _selected = widget.destination ?? AppDestination.pipelines; + // A first load that opens Settings (a deep link, a restored page) was not + // reached from a shell control, so its Back closes the page. + _settingsPushed = _selected == AppDestination.settings; _visited.add(_selected); HardwareKeyboard.instance.addHandler(_handleDestinationKeyEvent); } @@ -109,12 +117,23 @@ class _AdaptiveShellState extends State { super.didUpdateWidget(oldWidget); final destination = widget.destination; if (destination != null) { + if (destination != _selected) _noteShown(destination); _history.record(_selected, destination); _selected = destination; _visited.add(destination); } } + /// Records that [destination] is becoming the shown one. Settings opened by + /// a shell control is a destination (no Back); opened any other way it is a + /// page that Back closes. + void _noteShown(AppDestination destination) { + if (destination == AppDestination.settings) { + _settingsPushed = _navigatingTo != AppDestination.settings; + } + _navigatingTo = null; + } + /// The entry every tab control calls when tapped: a destination shown /// already is re-selected (see [AdaptiveShell.onDestinationReselected]), any /// other is selected. @@ -124,6 +143,13 @@ class _AdaptiveShellState extends State { reselected(destination); return; } + if (destination != _selected) { + _navigatingTo = destination; + // A selection the route never applies must not mark a later route. + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted && _navigatingTo == destination) _navigatingTo = null; + }); + } _select(destination); } @@ -134,6 +160,7 @@ class _AdaptiveShellState extends State { return; } setState(() { + if (destination != _selected) _noteShown(destination); _history.record(_selected, destination); _selected = destination; _visited.add(destination); @@ -440,7 +467,9 @@ class _AdaptiveShellState extends State { String label, { required bool page, }) { - final onBack = spec?.onBack ?? (page ? _closePage : null); + // Settings reached from a shell control has no Back: it is a destination. + final onBack = + spec?.onBack ?? (page && _settingsPushed ? _closePage : null); final published = spec?.actions ?? const []; final onSearch = widget.onSearch; return SegmentedBar( diff --git a/app/lib/shell/destination.dart b/app/lib/shell/destination.dart index 9fe91835..523b28fc 100644 --- a/app/lib/shell/destination.dart +++ b/app/lib/shell/destination.dart @@ -2,10 +2,11 @@ import 'package:flutter/material.dart'; enum AppDestination { pipelines, runs, chat, search, settings } -/// The destinations the shell's tab bar (or, on a wide window, its rail) offers, +/// The tabs the shell's floating tab bar (or, on a wide window, its rail) offers, /// in order. Settings is a destination the shell can show (its route is -/// `/settings`), but it opens as a page, from the rail's foot on a wide window -/// or the Pipelines bar's gear on a phone, instead of being a tab. +/// `/settings`) and the rail and phone bar offer it too; it is a page of the +/// Pipelines tab, not a tab. Only the floating bar's width leaves Settings to +/// the Pipelines bar's gear. const List shellTabDestinations = [ AppDestination.pipelines, AppDestination.runs, diff --git a/app/lib/shell/navigation_rail.dart b/app/lib/shell/navigation_rail.dart index 93f6deec..7de8cf75 100644 --- a/app/lib/shell/navigation_rail.dart +++ b/app/lib/shell/navigation_rail.dart @@ -22,6 +22,12 @@ const double kNavigationRailMinWindowWidth = bool showsNavigationRail(BuildContext context) => MediaQuery.sizeOf(context).width >= kNavigationRailMinWindowWidth; +/// Whether the window shows the floating tab bar alone: wide enough for a list +/// beside an open item, too narrow for the rail. That bar lists the tabs only, +/// so there Settings is reached from the Pipelines bar's gear. +bool showsFloatingTabBarOnly(BuildContext context) => + showsListBesideDetail(context) && !showsNavigationRail(context); + /// The wide layout's left-edge navigation: a Material [NavigationRail] with /// an icon and a label per tab, the selected tab marked by the rail's /// indicator, and Settings pinned to its bottom. diff --git a/app/notes/settings-destination-back.md b/app/notes/settings-destination-back.md new file mode 100644 index 00000000..091c3ceb --- /dev/null +++ b/app/notes/settings-destination-back.md @@ -0,0 +1,72 @@ +# Settings destination: Back only when pushed; one Settings entry per screen + +Run 20261112-1022 (stage 01-implement). Not committed. + +## Rule + +- Settings opened from a shell control (rail item, phone bar item) is a + destination: no Back arrow. The Pipelines item leaves it for the Pipelines body. +- Settings opened any other way (a first load / deep link to `/settings`, a route + change that is not a shell control, the Pipelines gear) is a pushed page: Back + returns to Pipelines. +- The Pipelines bar's gear is kept only where the floating tab bar is the shell's + sole navigation (window width at least 600 and below the rail's 697; see + `showsFloatingTabBarOnly`). There the floating bar lists tabs only, so the gear + is the one Settings entry. The phone bar and the rail both offer Settings, so the + gear is gone there. + +## Changed paths (app/) + +- `lib/shell/adaptive_shell.dart`: `_navigatingTo` / `_settingsPushed`; `_noteShown` + is called on a shown-destination change; Back is built only when Settings is + pushed. +- `lib/shell/navigation_rail.dart`: `showsFloatingTabBarOnly(context)`. +- `lib/shell/destination.dart`: doc comment only. +- `lib/features/pipelines/screen.dart`: the bar's gear is shown only when + `showsFloatingTabBarOnly`; the rail check is gone. The non-shell paths keep the gear. +- `lib/application/pipelines_app.dart`: `_selectDestination` leaves Settings for the + Pipelines body (`_bodyRoutes`) instead of re-selecting the Settings route filed + under the Pipelines tab (the nav-only Settings has no Back, so without this the + Pipelines item would trap the user on Settings). +- Tests, new: `test/shell/settings_back_test.dart` (nav selection has no Back; route + push has Back and returns; first load has Back; nav after pushed clears Back); + `test/features/pipelines/pipelines_settings_gear_test.dart` (phone and rail: no + gear; floating band: gear present and its handler opens Settings). +- Tests, changed: `test/application/settings_page_test.dart`, + `test/application/tab_location_navigation_test.dart`, + `test/application/settings_registration_test.dart`, + `test/shell/navigation_rail_test.dart`. They now tap the nav item instead of the gear + and expect no Back on nav-opened Settings. + +## Focused results (memwatch, from app/) + +- New shell + gear tests and shell/rail/bar files: 54 passed, 0 failed. + (`settings_back_test`, `pipelines_settings_gear_test`, `navigation_rail_test`, + `shell_bar_test`, `tab_history_back_test`, `shell_navigation_bar_test`, + `split_destination_bar_test`, `pipelines_screen_filter_test`) +- Final run over all affected files (12 paths): 60 passed, 7 failed. The 7 are all + app-level tests that fail on HEAD for the same reason (see below). None is new. + - `settings_page_test`: "390 ... no gear ..." and "1200 ... rail ..." + - `tab_location_navigation_test`: "Settings is retained ...", "a delayed read ...", + "an explicit root URL ...", "Settings does not clear ..." + - `settings_registration_test`: "Settings shares socket and one native bar" +- Baseline check: a copy of app/ with HEAD's versions of the edited files fails the + same tests in the same way (`Expected: '/settings' Actual: '/pipelines'` after a + nav tap, and `Found 0 widgets with key 'segmented.more'` for the gear at 390). + `templates_wiring_test` passes on both. +- `tool/analyze.sh`: clean (0 errors, 0 warnings, 0 infos). + +## Limitations + +- App-level Settings navigation is not verified by these tests: a tap on the Settings + nav item does not change the route in this harness, on HEAD or on this change. The + behaviour is covered at shell level (`settings_back_test`) and by the gear test. +- System Back on a nav-opened Settings still closes to Pipelines (the shell's + PopScope is unchanged). +- The mid-width band keeps the gear by design (the floating bar has no Settings + entry). Adding Settings to the floating bar would remove it; not done here. +- Not built or captured here (ui-review owns that). States to re-capture: + - `base-light-430x900/12-settings.png` and `circle/01-hover.png`: Settings from the + nav has no Back arrow. + - `base-light-430x900/01-pipelines.png`: no Settings gear in the Pipelines header. + - A width between 600 and 696: the gear stays, and it opens Settings with Back. diff --git a/app/test/application/settings_page_test.dart b/app/test/application/settings_page_test.dart index 1b03f83e..da8c844b 100644 --- a/app/test/application/settings_page_test.dart +++ b/app/test/application/settings_page_test.dart @@ -7,15 +7,16 @@ import 'package:pipelines_app/features/settings/settings_screen.dart'; import 'package:pipelines_app/ui/adaptive/floating_destination_bar.dart'; import 'package:shared_preferences/shared_preferences.dart'; -import '../bar_action.dart'; import '../core/transport/pipelines_client_test.dart' show FakeChannel; import '../features/pipelines/fixtures.dart'; import 'pipelines_app_test.dart' show webServer; import 'pipelines_replies.dart'; -/// Settings is not a tab: it opens as a page (from the gear in the Pipelines -/// bar on a phone, from the rail's foot on a wide window), keeps its -/// `/settings` route (and deep link), and closes back to Pipelines. The tab bar keeps Pipelines selected meanwhile. +/// Settings is a navigation destination: the phone's bar and the wide rail +/// offer it, and the floating tab bar's width (between the list-detail and rail +/// widths) keeps the Pipelines bar's gear. Settings reached from a nav control +/// has no Back; reached as a pushed page (the gear, the /settings deep link) it +/// has Back, which returns to Pipelines. void main() { Future pumpApp( WidgetTester tester, { @@ -50,61 +51,47 @@ void main() { int selectedTab(WidgetTester tester) => tester.widget(find.byType(NavigationBar)).selectedIndex; - // A phone's Pipelines bar keeps the gear; a wide window's rail offers - // Settings instead (see the wide test below). - for (final size in [const Size(390, 844)]) { - testWidgets('${size.width}: the Pipelines bar gear opens Settings ' - 'as a page and Back returns', (tester) async { - final provider = await pumpApp( - tester, - location: '/pipelines', - size: size, - ); - // Four tabs and Settings as the bar's last destination. - expect( - tester - .widget(find.byType(NavigationBar)) - .destinations - .map((item) => (item as NavigationDestination).label), - ['Pipelines', 'Runs', 'Chat', 'Search', 'Settings'], - ); - expect( - find.byKey(const ValueKey('shell.destination.settings')), - findsOneWidget, - ); - expect(find.byKey(const ValueKey('shell.back')), findsNothing); + testWidgets('390: the bar offers Settings and no gear; Settings from the bar ' + 'has no Back and the Pipelines item leaves it', (tester) async { + final provider = await pumpApp( + tester, + location: '/pipelines', + size: const Size(390, 844), + ); + // Four tabs and Settings as the bar's last destination. + expect( + tester + .widget(find.byType(NavigationBar)) + .destinations + .map((item) => (item as NavigationDestination).label), + ['Pipelines', 'Runs', 'Chat', 'Search', 'Settings'], + ); + expect(find.byKey(const Key('pipelines-open-settings')), findsNothing); + expect(find.byKey(const ValueKey('shell.back')), findsNothing); - await tapBarAction( - tester, - find.byKey(const Key('pipelines-open-settings')), - 'Settings', - ); - await tester.pump(); - await tester.pump(); - expect(provider.value.uri.path, '/settings'); - expect(find.byType(SettingsScreen), findsOneWidget); - expect(find.text('Quick switch animation'), findsOneWidget); - await openSettingsSection(tester, 'Connection'); - expect(find.text('Server URL'), findsOneWidget); - // A page of Pipelines: Back in its bar, Settings selected in the bar. - expect(find.byKey(const ValueKey('shell.back')), findsOneWidget); - expect(find.byKey(const ValueKey('shell.search')), findsNothing); - expect(selectedTab(tester), 4); - expect(tester.takeException(), isNull); + await tester.tap(find.byKey(const ValueKey('shell.destination.settings'))); + await tester.pumpAndSettle(); + expect(provider.value.uri.path, '/settings'); + expect(find.byType(SettingsScreen), findsOneWidget); + expect(find.text('Quick switch animation'), findsOneWidget); + await openSettingsSection(tester, 'Connection'); + expect(find.text('Server URL'), findsOneWidget); + // A destination: no Back, and Settings is the selected item of the bar. + expect(find.byKey(const ValueKey('shell.back')), findsNothing); + expect(find.byKey(const ValueKey('shell.search')), findsNothing); + expect(selectedTab(tester), 4); + expect(tester.takeException(), isNull); - await tester.tap(find.byKey(const ValueKey('shell.back'))); - await tester.pump(); - await tester.pump(); - expect(provider.value.uri.path, '/pipelines'); - expect(find.byKey(const Key('pipelines-open-settings')), findsWidgets); - expect(find.byKey(const ValueKey('shell.back')), findsNothing); - await tester.pumpWidget(const SizedBox.shrink()); - await tester.pump(); - }); - } + await tester.tap(find.byKey(const ValueKey('shell.destination.pipelines'))); + await tester.pumpAndSettle(); + expect(provider.value.uri.path, '/pipelines'); + expect(find.byKey(const ValueKey('shell.back')), findsNothing); + await tester.pumpWidget(const SizedBox.shrink()); + await tester.pump(); + }); testWidgets('1200: the rail offers Settings at its foot and no gear is ' - 'left in the Pipelines toolbar; Settings is a page and Back returns', ( + 'left in the Pipelines toolbar; Settings from the rail has no Back', ( tester, ) async { final provider = await pumpApp( @@ -129,21 +116,19 @@ void main() { } await tester.tap(find.byKey(const ValueKey('shell.destination.settings'))); - await tester.pump(); - await tester.pump(); + await tester.pumpAndSettle(); expect(provider.value.uri.path, '/settings'); expect(find.byType(SettingsScreen), findsOneWidget); - // Settings is a page of Pipelines: the rail marks Settings, not a tab. + // Settings is a destination: the rail marks Settings, not a tab. expect( tester.widget(find.byType(NavigationRail)).selectedIndex, isNull, ); - expect(find.byKey(const ValueKey('shell.back')), findsOneWidget); + expect(find.byKey(const ValueKey('shell.back')), findsNothing); expect(tester.takeException(), isNull); - await tester.tap(find.byKey(const ValueKey('shell.back'))); - await tester.pump(); - await tester.pump(); + await tester.tap(find.byKey(const ValueKey('shell.destination.pipelines'))); + await tester.pumpAndSettle(); expect(provider.value.uri.path, '/pipelines'); expect(find.byKey(const Key('pipelines-open-settings')), findsNothing); expect( @@ -154,8 +139,8 @@ void main() { await tester.pump(); }); - testWidgets('the /settings deep link opens the Settings page and ' - 'the system Back closes it to Pipelines', (tester) async { + testWidgets('the /settings deep link opens Settings as a pushed page with ' + 'Back, and the system Back closes it to Pipelines', (tester) async { final provider = await pumpApp( tester, location: '/settings', @@ -168,8 +153,7 @@ void main() { final handled = await tester.binding.handlePopRoute(); expect(handled, isTrue, reason: 'Back closes the page, not the app'); - await tester.pump(); - await tester.pump(); + await tester.pumpAndSettle(); expect(provider.value.uri.path, '/pipelines'); await tester.pumpWidget(const SizedBox.shrink()); await tester.pump(); diff --git a/app/test/application/settings_registration_test.dart b/app/test/application/settings_registration_test.dart index 18a0014a..acaca0db 100644 --- a/app/test/application/settings_registration_test.dart +++ b/app/test/application/settings_registration_test.dart @@ -7,7 +7,6 @@ import 'package:pipelines_app/application/pipelines_app.dart'; import 'package:pipelines_app/core/transport/pipelines_client.dart'; import 'package:shared_preferences/shared_preferences.dart'; -import '../bar_action.dart'; import '../core/transport/pipelines_client_test.dart' show FakeChannel; import '../features/pipelines/fixtures.dart'; import 'pipelines_app_test.dart' show webServer, requestOf; @@ -45,11 +44,7 @@ void main() { ); await replyPipelines(tester, channel, PipelineFixture()); - await tapBarAction( - tester, - find.byKey(const Key('pipelines-open-settings')), - 'Settings', - ); + await tester.tap(find.byKey(const ValueKey('shell.destination.settings'))); await tester.pump(); await tester.pump(); expect(provider.value.uri.path, '/settings'); diff --git a/app/test/application/tab_location_navigation_test.dart b/app/test/application/tab_location_navigation_test.dart index 55de9dbf..f462a993 100644 --- a/app/test/application/tab_location_navigation_test.dart +++ b/app/test/application/tab_location_navigation_test.dart @@ -11,7 +11,6 @@ import 'package:pipelines_app/features/settings/settings_screen.dart'; import 'package:pipelines_app/features/pipelines/screen.dart'; import 'package:pipelines_app/shell/destination.dart'; -import '../bar_action.dart'; import '../core/transport/pipelines_client_test.dart' show FakeChannel; import '../features/pipelines/fixtures.dart'; import 'pipelines_app_test.dart' show webServer; @@ -63,13 +62,10 @@ void main() { final app = await mount(tester); await replyPipelines(tester, app.channel, PipelineFixture()); await tester.pumpAndSettle(); - await tapBarAction( - tester, - find.byKey(const Key('pipelines-open-settings')), - 'Settings', - ); - await tester.pumpAndSettle(); + await tab(tester, 'settings'); expect(app.provider.value.uri.path, '/settings'); + // A destination opened from its nav item: no Back. + expect(find.byKey(const ValueKey('shell.back')), findsNothing); final settingsState = tester.state(find.byType(SettingsScreen)); await tab(tester, 'chat'); expect(app.provider.value.uri.path, '/chat'); @@ -77,19 +73,12 @@ void main() { expect(app.provider.value.uri.path, '/settings'); expect(tester.state(find.byType(SettingsScreen)), same(settingsState)); await tab(tester, 'pipelines'); - expect( - app.provider.value.uri.path, - '/settings', - reason: 'tab retap is not Back', - ); - await tester.tap(find.byKey(const ValueKey('shell.back'))); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 500)); expect( app.provider.value.uri.path, '/pipelines', - reason: 'explicit Back still exits Settings', + reason: 'the Pipelines item leaves Settings for its list', ); + expect(find.byKey(const ValueKey('shell.back')), findsNothing); expect(tester.takeException(), isNull); }); testWidgets( @@ -191,8 +180,8 @@ void main() { await tab(tester, 'pipelines'); expect(app.provider.value.uri.path, '/settings'); expect(tester.widget(hidden).initialPipelineId, 1); - await tester.tap(find.byKey(const Key('shell.back'))); - await tester.pumpAndSettle(); + // Settings has no Back; the Pipelines item returns to the open pipeline. + await tab(tester, 'pipelines'); expect(app.provider.value.uri.path, '/pipelines/1'); expect(tester.state(find.byType(PipelinesScreen)), same(pipelineState)); expect( diff --git a/app/test/features/pipelines/pipelines_settings_gear_test.dart b/app/test/features/pipelines/pipelines_settings_gear_test.dart new file mode 100644 index 00000000..b0cff78a --- /dev/null +++ b/app/test/features/pipelines/pipelines_settings_gear_test.dart @@ -0,0 +1,73 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/pipelines/screen.dart'; +import 'package:pipelines_app/shell/adaptive_shell.dart'; +import 'package:pipelines_app/shell/destination.dart'; +import 'package:pipelines_app/ui/adaptive/floating_destination_bar.dart'; + +import 'fixtures.dart'; +import 'test_helpers.dart'; + +/// The Pipelines bar's Settings gear inside the shell: it is kept only where the +/// floating tab bar is the shell's sole navigation (between the list-detail and +/// rail widths), because only there Settings has no nav entry. Elsewhere the +/// phone's bar or the rail offers Settings, so the bar has no gear. +void main() { + // Returns how many times the gear opened Settings. + Future pumpInShell(WidgetTester tester, Size size) async { + tester.view.physicalSize = size; + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + var opened = 0; + final gateway = gatewayFor(PipelineFixture()); + await tester.pumpWidget( + MaterialApp( + home: AdaptiveShell( + destination: AppDestination.pipelines, + destinationBodies: { + // The app's Pipelines destination embeds the screen in the shell. + AppDestination.pipelines: (_) => PipelinesScreen( + gateway: gateway, + embedded: true, + onOpenSettings: () => opened++, + ), + }, + ), + ), + ); + await tester.pumpAndSettle(); + return () => opened; + } + + testWidgets('a phone bar offers Settings, so the Pipelines bar has no gear', ( + tester, + ) async { + await pumpInShell(tester, const Size(390, 844)); + expect(find.byType(NavigationBar), findsOneWidget); + expect(find.byKey(const Key('pipelines-open-settings')), findsNothing); + }); + + testWidgets('a rail offers Settings, so the Pipelines bar has no gear', ( + tester, + ) async { + await pumpInShell(tester, const Size(1200, 800)); + expect(find.byType(NavigationRail), findsOneWidget); + expect(find.byKey(const Key('pipelines-open-settings')), findsNothing); + }); + + testWidgets('the floating tab bar lists tabs only, so the Pipelines bar ' + 'keeps the gear and it opens Settings', (tester) async { + final opened = await pumpInShell(tester, const Size(650, 844)); + expect(find.byType(FloatingDestinationBar), findsOneWidget); + expect(find.byKey(const Key('pipelines-open-settings')), findsOneWidget); + // At this width the bar folds the gear into its More menu, so it is not + // hit-testable here; its handler is what opens Settings. + final gear = tester.widget( + find.byKey(const Key('pipelines-open-settings')), + ); + expect(gear.tooltip, 'Settings'); + gear.onPressed!(); + expect(opened(), 1); + }); +} diff --git a/app/test/shell/navigation_rail_test.dart b/app/test/shell/navigation_rail_test.dart index 16597aef..b4fb741a 100644 --- a/app/test/shell/navigation_rail_test.dart +++ b/app/test/shell/navigation_rail_test.dart @@ -90,8 +90,8 @@ void main() { expect(find.text('runs body'), findsOneWidget); }); - testWidgets('Settings opens from the rail foot as a page and no tab is ' - 'selected meanwhile', (tester) async { + testWidgets('Settings opens from the rail foot as a destination with no ' + 'Back and no tab is selected meanwhile', (tester) async { final semantics = tester.ensureSemantics(); await pumpShell(tester, width: 1000); @@ -106,8 +106,10 @@ void main() { .isSelected, Tristate.isTrue, ); - // The page's own Back returns to Pipelines, the tab it belongs to. - await tester.tap(find.byKey(const ValueKey('shell.back'))); + // Opened from its rail item, Settings is not a page: no Back. + expect(find.byKey(const ValueKey('shell.back')), findsNothing); + // The Pipelines item leaves it for the Pipelines tab. + await tester.tap(find.byKey(const ValueKey('shell.destination.pipelines'))); await tester.pumpAndSettle(); expect(tester.widget(rail()).selectedIndex, 0); semantics.dispose(); diff --git a/app/test/shell/settings_back_test.dart b/app/test/shell/settings_back_test.dart new file mode 100644 index 00000000..85cfb3d6 --- /dev/null +++ b/app/test/shell/settings_back_test.dart @@ -0,0 +1,90 @@ +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'; + +/// Settings' Back: a destination reached from a shell control has none; a page +/// pushed by a route (a first load or a route change, such as a deep link or +/// the Pipelines gear) has one that returns to Pipelines. +void main() { + AdaptiveShell shellAt(AppDestination destination) => AdaptiveShell( + destination: destination, + destinationBodies: { + for (final value in AppDestination.values) + value: (_) => Text('${value.name} body'), + }, + ); + + Future pumpAt( + WidgetTester tester, + AppDestination destination, { + double width = 1000, + }) async { + tester.view.physicalSize = Size(width, 800); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + await tester.pumpWidget(MaterialApp(home: shellAt(destination))); + await tester.pumpAndSettle(); + } + + testWidgets('Settings selected from a rail item has no Back', (tester) async { + await pumpAt(tester, AppDestination.pipelines); + expect(find.byKey(const ValueKey('shell.back')), findsNothing); + + await tester.tap(find.byKey(const ValueKey('shell.destination.settings'))); + await tester.pumpAndSettle(); + expect(find.text('settings body'), findsOneWidget); + expect(find.byKey(const ValueKey('shell.back')), findsNothing); + }); + + testWidgets('Settings selected from a phone bar item has no Back', ( + tester, + ) async { + await pumpAt(tester, AppDestination.pipelines, width: 390); + await tester.tap(find.byKey(const ValueKey('shell.destination.settings'))); + await tester.pumpAndSettle(); + expect(find.text('settings body'), findsOneWidget); + expect(find.byKey(const ValueKey('shell.back')), findsNothing); + }); + + testWidgets('Settings pushed by a route change has Back, which returns to ' + 'Pipelines', (tester) async { + await pumpAt(tester, AppDestination.pipelines); + // The route moves to Settings (as a gear or a deep link does). + await tester.pumpWidget( + MaterialApp(home: shellAt(AppDestination.settings)), + ); + await tester.pumpAndSettle(); + expect(find.text('settings body'), findsOneWidget); + expect(find.byKey(const ValueKey('shell.back')), findsOneWidget); + + await tester.tap(find.byKey(const ValueKey('shell.back'))); + await tester.pumpAndSettle(); + expect(find.text('pipelines body'), findsOneWidget); + expect(find.byKey(const ValueKey('shell.back')), findsNothing); + }); + + testWidgets('a first load on Settings (a deep link) has Back', ( + tester, + ) async { + await pumpAt(tester, AppDestination.settings); + expect(find.text('settings body'), findsOneWidget); + expect(find.byKey(const ValueKey('shell.back')), findsOneWidget); + }); + + testWidgets('a nav selection after a pushed Settings clears its Back', ( + tester, + ) async { + await pumpAt(tester, AppDestination.settings); + expect(find.byKey(const ValueKey('shell.back')), findsOneWidget); + await tester.tap(find.byKey(const ValueKey('shell.destination.chat'))); + await tester.pumpAndSettle(); + expect(find.text('chat body'), findsOneWidget); + + // Settings opened again from its rail item is a destination, not a page. + await tester.tap(find.byKey(const ValueKey('shell.destination.settings'))); + await tester.pumpAndSettle(); + expect(find.byKey(const ValueKey('shell.back')), findsNothing); + }); +} From 7d9b6c1d1bb87c385e309ba903c9613d6504cdf2 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 12 Nov 2026 10:42:43 +0000 Subject: [PATCH 3/9] Keep chat titles readable in narrow headers Prioritize the conversation title on narrow chat bars, move compact controls and overflow actions into More, and omit the duplicate title in floating windows. Add focused widget coverage for title sizing, icon dimensions, menus, and floating chrome. --- .../chat/conversation/chat_thread_header.dart | 89 ++++++-- .../chat/conversation/chat_thread_view.dart | 32 ++- app/lib/ui/adaptive/segmented_bar.dart | 15 +- app/notes/chat-narrow-title-priority.md | 75 +++++++ .../features/chat/chat_screen_mode_test.dart | 58 +++-- .../features/chat/chat_screen_model_test.dart | 22 ++ .../chat_floating_chrome_test.dart | 12 +- .../conversation/chat_model_picker_test.dart | 9 + .../conversation/chat_thread_header_test.dart | 204 ++++++++++++++---- 9 files changed, 431 insertions(+), 85 deletions(-) create mode 100644 app/notes/chat-narrow-title-priority.md diff --git a/app/lib/features/chat/conversation/chat_thread_header.dart b/app/lib/features/chat/conversation/chat_thread_header.dart index 09711905..39f49192 100644 --- a/app/lib/features/chat/conversation/chat_thread_header.dart +++ b/app/lib/features/chat/conversation/chat_thread_header.dart @@ -1,20 +1,36 @@ +import 'dart:async'; + import 'package:flutter/material.dart'; import '../../../core/servers/server_context.dart'; +import '../../../ui/adaptive/app_popups.dart'; import '../../../ui/adaptive/segmented_bar.dart'; import '../../../ui/adaptive/segmented_bar_overflow.dart'; import 'chat_bar_tint.dart'; import '../workspace/chat_workspace_pane_scope.dart'; +/// Below this width (in text-scaled logical pixels) the selectors leave the +/// bar for its More menu's settings entry, so the title keeps +/// [chatHeaderTitleShare]. +const double chatHeaderNarrowWidth = 600; + +/// The share of a narrow bar the conversation's title always keeps. +const double chatHeaderTitleShare = 0.6; + /// The open conversation's bar: the app's [SegmentedBar] above the /// transcript. /// /// From the leading edge: a round Back (only where the page can go back), a /// pill with the conversation's title and folder that opens the chat's -/// information, a selector island holding [controls] (model and mode), -/// then the Files action and a native More menu in a separate island. -/// Narrow panes keep the model/mode selectors as compact icons in the same row; -/// their semantic labels and native pickers continue to expose the values. +/// information, a selector island holding [controls] (model, mode and +/// thinking), then the Files action and a native More menu in a separate +/// island. +/// +/// A narrow bar ([chatHeaderNarrowWidth]) keeps the title at +/// [chatHeaderTitleShare] of the bar: the [controls] join the More menu as one +/// "Chat settings" entry that opens them in a sheet, and the overflowable +/// actions join it too. A floating chat passes [showTitle] false, since its window bar names +/// the chat. /// /// A chat with a [chatColor] carries it in the bar: each glass piece is /// filled with its shade over the raised surface and its labels and icons @@ -26,6 +42,7 @@ class ChatThreadHeader extends StatelessWidget { required this.title, required this.folder, required this.onInfo, + this.showTitle = true, this.showBack = false, this.onBack, this.controls = const [], @@ -41,6 +58,10 @@ class ChatThreadHeader extends StatelessWidget { final String folder; final VoidCallback onInfo; + /// Whether the title pill (and its folder) shows; false in a floating + /// window, whose own bar names the chat. + final bool showTitle; + /// Whether the bar shows Back at all. final bool showBack; @@ -62,21 +83,36 @@ class ChatThreadHeader extends StatelessWidget { return LayoutBuilder( builder: (context, constraints) { final textScale = MediaQuery.textScalerOf(context).scale(14) / 14; - final compact = constraints.maxWidth / textScale < 800; + final scaledWidth = constraints.maxWidth / textScale; + final compact = scaledWidth < 800; + final narrow = scaledWidth < chatHeaderNarrowWidth; + // A narrow bar moves the selectors, and the overflowable actions, into + // its More menu; the others stay in the bar. + final menuActions = [ + if (narrow) ...actions.whereType(), + ...moreActions.whereType(), + ]; + final settingsEntry = narrow && controls.isNotEmpty + ? SegmentedOverflowEntry( + label: 'Chat settings', + icon: Icons.tune, + onPressed: () => unawaited(_showSettings(context, controls)), + ) + : null; final actionChildren = [ - ...actions, + for (final action in actions) + if (!narrow || action is! SegmentedOverflowable) action, for (final action in moreActions) if (action is! SegmentedOverflowable) action, - if (moreActions.whereType().isNotEmpty) + if (settingsEntry != null || menuActions.isNotEmpty) SegmentedMoreButton( entries: [ - for (final action - in moreActions.whereType()) - action.overflowEntry, + ?settingsEntry, + for (final action in menuActions) action.overflowEntry, ], ), ]; - final Widget bar = SegmentedBar( + final bar = SegmentedBar( pillColor: tint?.fill, foregroundColor: tint?.foreground, automaticallyImplyLeading: false, @@ -88,16 +124,17 @@ class ChatThreadHeader extends StatelessWidget { onPressed: onBack, ) : null, - title: title.isEmpty ? 'Chat' : title, - titleLeading: identity, - subtitle: ServerContext.metadata(context, folder), + title: !showTitle ? '' : (title.isEmpty ? 'Chat' : title), + titleLeading: showTitle ? identity : null, + subtitle: showTitle ? ServerContext.metadata(context, folder) : null, subtitleIcon: Icons.folder_outlined, - onTitlePressed: onInfo, + onTitlePressed: showTitle ? onInfo : null, titleSemanticLabel: 'Chat information', titleKey: const Key('chat-info'), separateActionIslands: true, + titleShare: narrow && showTitle ? chatHeaderTitleShare : null, actions: [ - if (controls.isNotEmpty) + if (controls.isNotEmpty && !narrow) ChatWorkspacePaneActionBar( child: _ControlIsland( key: const Key('chat-model-permission-island'), @@ -105,7 +142,7 @@ class ChatThreadHeader extends StatelessWidget { children: controls, ), ), - if (actions.isNotEmpty || moreActions.isNotEmpty) + if (actionChildren.isNotEmpty) ChatWorkspacePaneActionBar( child: Row( key: const Key('chat-actions-island'), @@ -136,6 +173,24 @@ class ChatThreadHeader extends StatelessWidget { } } +/// A narrow bar's selectors (model, mode and thinking), each with its label, +/// in a sheet opened from the More menu. +Future _showSettings(BuildContext context, List controls) => + showAppChoiceMenu( + context, + semanticLabel: 'Chat settings', + builder: (_) => SafeArea( + child: Padding( + padding: const EdgeInsets.fromLTRB(16, 0, 16, 16), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: controls, + ), + ), + ), + ); + /// Related selectors share the available width. Each remains a real control; /// they never migrate into the unrelated actions menu. class _ControlIsland extends StatelessWidget { diff --git a/app/lib/features/chat/conversation/chat_thread_view.dart b/app/lib/features/chat/conversation/chat_thread_view.dart index 69baa57e..da45e614 100644 --- a/app/lib/features/chat/conversation/chat_thread_view.dart +++ b/app/lib/features/chat/conversation/chat_thread_view.dart @@ -1428,15 +1428,23 @@ class _ChatThreadViewState extends State { ? ModalRoute.of(context)?.impliesAppBarDismissal ?? false : true); final answeredBy = latestReplyModel(_controller.messages); - return _chrome.widgetFor('header', answeredBy, [ - widget, - inShellBar, - canGoBack, - // The thinking control says when a turn is running. - _controller.running, - // The More menu offers Dismiss all finished commands only with one. - _shellRuns.finishedIds.isNotEmpty, - ], () => _buildHeader(session, inShellBar, canGoBack, answeredBy)); + // A floating window's own bar names the chat, so the header omits it. + final inWindow = WindowScope.maybeOf(context) != null; + return _chrome.widgetFor( + 'header', + answeredBy, + [ + widget, + inShellBar, + canGoBack, + inWindow, + // The thinking control says when a turn is running. + _controller.running, + // The More menu offers Dismiss all finished commands only with one. + _shellRuns.finishedIds.isNotEmpty, + ], + () => _buildHeader(session, inShellBar, canGoBack, answeredBy, inWindow), + ); } Widget _buildHeader( @@ -1444,6 +1452,7 @@ class _ChatThreadViewState extends State { bool inShellBar, bool canGoBack, String answeredBy, + bool inWindow, ) { final hasModel = session != null && supportsChatModels('${session['backend'] ?? ''}'); @@ -1466,6 +1475,7 @@ class _ChatThreadViewState extends State { ? null : ChatSessionAvatar(session: session, selected: true), onInfo: _openInfo, + showTitle: !inWindow, showBack: canGoBack, // A pushed page keeps the platform's stock Back (pop this route); a // standalone conversation calls its owner. @@ -1518,6 +1528,7 @@ class _ChatThreadViewState extends State { ), ], controls: [ + // Labelled, so a narrow bar's settings sheet shows their names. if (hasModel) ChatModelControl( key: ValueKey('chat-model-${widget.sessionId}'), @@ -1526,6 +1537,7 @@ class _ChatThreadViewState extends State { session: session, onChanged: widget.onModelChanged, answeredBy: answeredBy, + showLabel: true, ), if (hasMode) _modeControl(), // Only a model with levels gets the control (and its pill). @@ -1537,6 +1549,7 @@ class _ChatThreadViewState extends State { session: session, running: _controller.running, onChanged: widget.onEffortChanged, + showLabel: true, ), ], ); @@ -1551,6 +1564,7 @@ class _ChatThreadViewState extends State { mode: '${widget.session?['mode'] ?? ''}'.trim(), modeName: '${widget.session?['mode_name'] ?? ''}'.trim(), onChanged: widget.onModeChanged, + showLabel: true, ); /// Stops the running turn, as the composer's `/stop` does. diff --git a/app/lib/ui/adaptive/segmented_bar.dart b/app/lib/ui/adaptive/segmented_bar.dart index 499c297a..7ffca933 100644 --- a/app/lib/ui/adaptive/segmented_bar.dart +++ b/app/lib/ui/adaptive/segmented_bar.dart @@ -69,8 +69,14 @@ class SegmentedBar extends StatefulWidget implements PreferredSizeWidget { this.foregroundColor, this.bottomPadding = 8, this.backdrop, + this.titleShare, }); + /// The share of the bar the title always keeps beside the actions, when it + /// must hold more than the default (a long conversation name in a narrow + /// bar). Null keeps the default shares. + final double? titleShare; + /// The title; empty shows no title pill unless there is a [subtitle]. final String title; @@ -390,8 +396,11 @@ class _SegmentedBarState extends State { // width (a destination's name) up to [SegmentedBar.maxTitleShare]; // actions that do not fit beside it move into the More menu. final width = constraints.maxWidth; + final titleShare = widget.titleShare; final titleMinimum = titleWidget != null || !showTitle ? width * SegmentedBar.minTitleShare + : titleShare != null + ? width * titleShare : math.max( width * SegmentedBar.minTitleShare, math.min( @@ -405,9 +414,9 @@ class _SegmentedBarState extends State { width * SegmentedBar.maxTitleShare, ), ); - final minimumTitleShare = widget.separateActionIslands - ? .10 - : SegmentedBar.minTitleShare; + final minimumTitleShare = + titleShare ?? + (widget.separateActionIslands ? .10 : SegmentedBar.minTitleShare); final besideTitle = width - (leading == null ? 0 : segmentedPieceHeight() + 8) - 8; // Actions that cannot move (a model picker) may take the room down diff --git a/app/notes/chat-narrow-title-priority.md b/app/notes/chat-narrow-title-priority.md new file mode 100644 index 00000000..b48b7560 --- /dev/null +++ b/app/notes/chat-narrow-title-priority.md @@ -0,0 +1,75 @@ +# Narrow chat header: title priority, settings in More, floating window + +Run 415, stage 01-implement. Source only under `app/`. Not committed, not captured +(ui-review owns captures). + +## Problem + +- At 430px the chat title pill shrank to ~46x44 (a dot): `SegmentedBar` let the + non-overflowable selector island take up to 90% of the bar, leaving the title + its 10% floor. +- The harness mark was squeezed by the title pill's `FittedBox` leading. +- In a floating chat window the inner title repeated the window's own title. + +## Changes + +- `lib/ui/adaptive/segmented_bar.dart`: optional `titleShare`. When set, the title + keeps that share of the bar (its floor and the actions' ceiling). Default null + keeps the old shares for every other bar. +- `lib/features/chat/conversation/chat_thread_header.dart`: + - `showTitle` (default true). False omits the title pill and folder. + - Below 600 logical px (text-scaled, `chatHeaderNarrowWidth`): title keeps + `chatHeaderTitleShare` = 0.6 of the bar; the model/mode/thinking controls leave + the bar for one `Chat settings` entry in the More menu, which opens them in a + sheet with their labels; overflowable actions (Files, terminal, ...) join More. + - Wide (600+) layout unchanged. +- `lib/features/chat/conversation/chat_thread_view.dart`: `showTitle: !inWindow` + (floating window bar names the chat; More keeps `Chat details`); the three + controls pass `showLabel: true` (no effect at 600+, where they already show labels). + +## Focused results (memwatch, from app/) + +- Header, chat-bar and segmented-bar focused set (`chat_thread_header_test`, + `chat_effort_header_test`, `chat_mode_control_test`, `chat_model_picker_test`, + `chat_floating_chrome_test`, `chat_bar_tint_test`, `chat_pane_presentation_test`, + `segmented_bar_*`): 83/83 pass. +- Those plus the users of the changed header/keys (chat screen mode/model, floating + pane, list shortcuts, pane move, conversation and shell tests, terminal + bar-action tests, `chat_registration_test`), in one final run: 199 pass, 4 fail. + The 4 failures are `test/application/chat_registration_test.dart` (retap and + folded-workspace cases). The same 4 fail on untouched HEAD in a detached + worktree, so they are pre-existing and not caused by this change. +- `tool/analyze.sh`: clean. + +New behavioural tests (`chat_thread_header_test.dart`, group "narrow title priority +at 430px"): short title whole (no truncation); long title ellipsized with the +title pill >= 60% of the bar; harness mark >= 20px beside the title; More opens +the controls in a sheet; Files moves into More; floating bar shows no title pill. + +## Affected UI states (for ui-review to capture) + +- 430px phone, chat bar: Back | title (>= 60% for long titles) | More. + Before: Back | ~46px title dot | model | mode | Files | More. +- 320px at 2x text: same shape (Back | title | More). +- More > Chat settings: sheet with model, mode and thinking controls, labelled. +- Floating chat window (any width): bar has no inner title; More has Chat details. +- 600px and wider: unchanged. + +## Test expectation changes (narrow behaviour the task asked to change) + +- `chat_thread_header_test.dart`: narrow bar expects the settings entry, not the + selector island/icons; wide branch keeps the old checks. +- `chat_floating_chrome_test.dart`: at 560px Files is in More (not in the bar). +- `chat_model_picker_test.dart`, `chat_screen_model_test.dart`, + `chat_screen_mode_test.dart`: phone tests open More > Chat settings to reach the + model/mode controls. Expected values are unchanged; `_shown` is now async. + +## Limitations + +- Phone users reach model/mode/thinking through More > Chat settings (two taps, was + one). Files is also in More on phones. The 60% title floor needs this at 430px + with 48px touch targets. +- The settings sheet holds the controls as built when opened. Server changes while + it is open show after reopening; each control's own accepted change updates at once. +- Harness mark size is asserted at >= 20px; no pre-change baseline was run for that test. +- Not verified on a device or in a browser; nothing captured here. diff --git a/app/test/features/chat/chat_screen_mode_test.dart b/app/test/features/chat/chat_screen_mode_test.dart index ebcb3f81..72c4162e 100644 --- a/app/test/features/chat/chat_screen_mode_test.dart +++ b/app/test/features/chat/chat_screen_mode_test.dart @@ -6,6 +6,8 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:pipelines_app/core/api_gateway.dart'; import 'package:pipelines_app/features/chat/conversation/chat_mode_control.dart'; import 'package:pipelines_app/features/chat/screen.dart'; +import 'package:pipelines_app/ui/adaptive/segmented_bar.dart' + show segmentedMoreKey; /// A chat destination gateway whose listing can change between reads, as it /// does when the server learns a row's mode after the row was first opened. @@ -101,13 +103,33 @@ Future _pump( await tester.pumpAndSettle(); } -/// The mode the drawn control names, or null when the bar has none. A -/// A narrow phone bar draws only the shield, so read the control itself. -String? _shown(WidgetTester tester) { - if (_modeControl.evaluate().isEmpty) return null; +/// The mode the drawn control names, or null when there is none. A phone bar +/// keeps its selectors in the More menu's settings sheet, so the sheet is +/// opened to read the control and then dismissed again. +Future _shown(WidgetTester tester) async { + if (_modeControl.evaluate().isNotEmpty) { + final control = find.byType(ChatModeControl); + expect(control, findsOneWidget); + return tester.widget(control).modeName; + } + await tester.tap(find.byKey(segmentedMoreKey).hitTestable()); + await tester.pumpAndSettle(); + if (find.text('Chat settings').evaluate().isEmpty) { + // No selectors for this chat: nothing to read; close the menu. + await tester.tapAt(const Offset(5, 5)); + await tester.pumpAndSettle(); + return null; + } + await tester.tap(find.text('Chat settings')); + await tester.pumpAndSettle(); final control = find.byType(ChatModeControl); - expect(control, findsOneWidget); - return tester.widget(control).modeName; + final name = control.evaluate().isEmpty + ? null + : tester.widget(control).modeName; + // Dismiss the sheet through its barrier, above the bar. + await tester.tapAt(const Offset(5, 5)); + await tester.pumpAndSettle(); + return name; } void main() { @@ -123,7 +145,7 @@ void main() { await tester.tap(find.byKey(const Key('chat-row-s'))); await tester.pumpAndSettle(); - expect(_shown(tester), 'Ask for permission'); + expect(await _shown(tester), 'Ask for permission'); }, ); @@ -135,7 +157,7 @@ void main() { await _pump(tester, gateway, platform: platform); await tester.tap(find.byKey(const Key('chat-row-s'))); await tester.pumpAndSettle(); - expect(_shown(tester), isNull); + expect(await _shown(tester), isNull); // A reconnect re-reads the list; the open chat follows that row // without being closed and opened again. @@ -151,7 +173,7 @@ void main() { _app(gateway, platform: platform, syncToken: 1), ); await tester.pumpAndSettle(); - expect(_shown(tester), 'Ask for permission'); + expect(await _shown(tester), 'Ask for permission'); // Another device chose Auto; the next re-read keeps the bar in sync. gateway.sessions = [ @@ -161,7 +183,7 @@ void main() { _app(gateway, platform: platform, syncToken: 2), ); await tester.pumpAndSettle(); - expect(_shown(tester), 'Auto'); + expect(await _shown(tester), 'Auto'); }, ); @@ -171,7 +193,7 @@ void main() { final gateway = _ModeScreenGateway(); await _pump(tester, gateway, platform: platform, initialSessionId: 's'); - expect(_shown(tester), 'Ask for permission'); + expect(await _shown(tester), 'Ask for permission'); }); testWidgets('$style: switching chats shows each chat its own mode', ( @@ -198,19 +220,19 @@ void main() { await tester.tap(find.byKey(const Key('chat-row-s'))); await tester.pumpAndSettle(); - expect(_shown(tester), 'Ask for permission'); + expect(await _shown(tester), 'Ask for permission'); await tester.tap(find.byKey(const Key('chat-row-t'))); await tester.pumpAndSettle(); - expect(_shown(tester), 'Auto'); + expect(await _shown(tester), 'Auto'); await tester.tap(find.byKey(const Key('chat-row-u'))); await tester.pumpAndSettle(); - expect(_shown(tester), isNull); + expect(await _shown(tester), isNull); await tester.tap(find.byKey(const Key('chat-row-s'))); await tester.pumpAndSettle(); - expect(_shown(tester), 'Ask for permission'); + expect(await _shown(tester), 'Ask for permission'); }); } @@ -252,7 +274,7 @@ void main() { await runNew(tester); expect(find.text('New chat'), findsWidgets); - expect(_shown(tester), 'Plan'); + expect(await _shown(tester), 'Plan'); gateway.listGate!.complete(); await tester.pumpAndSettle(); }, @@ -277,11 +299,11 @@ void main() { await runNew(tester); // The row is open on the /new reply, which names no mode. expect(find.text('New chat'), findsWidgets); - expect(_shown(tester), isNull); + expect(await _shown(tester), isNull); gateway.listGate!.complete(); await tester.pumpAndSettle(); - expect(_shown(tester), 'Plan'); + expect(await _shown(tester), 'Plan'); }, variant: _desktop, ); diff --git a/app/test/features/chat/chat_screen_model_test.dart b/app/test/features/chat/chat_screen_model_test.dart index b226a73e..ee6c448c 100644 --- a/app/test/features/chat/chat_screen_model_test.dart +++ b/app/test/features/chat/chat_screen_model_test.dart @@ -3,6 +3,8 @@ import 'package:flutter_test/flutter_test.dart'; import '../../native_back.dart'; import 'package:pipelines_app/core/api_gateway.dart'; import 'package:pipelines_app/features/chat/screen.dart'; +import 'package:pipelines_app/ui/adaptive/segmented_bar.dart' + show segmentedMoreKey; /// A chat destination gateway: one listed session whose harness offers models. class _ScreenGateway implements ApiGateway { @@ -77,6 +79,22 @@ Future _pumpScreen( await tester.pumpAndSettle(); } +/// A phone bar keeps the model in the More menu's settings sheet: opens it +/// (a wide bar shows the control already). +Future _openSettings(WidgetTester tester) async { + if (find.byKey(const Key('chat-model')).evaluate().isNotEmpty) return; + await tester.tap(find.byKey(segmentedMoreKey).hitTestable()); + await tester.pumpAndSettle(); + await tester.tap(find.text('Chat settings')); + await tester.pumpAndSettle(); +} + +/// Dismisses that sheet through its barrier, above the bar. +Future _closeSettings(WidgetTester tester) async { + await tester.tapAt(const Offset(5, 5)); + await tester.pumpAndSettle(); +} + void main() { testWidgets('an accepted switch survives leaving and reopening the chat', ( tester, @@ -86,6 +104,7 @@ void main() { await tester.tap(find.byKey(const Key('chat-row-s'))); await tester.pumpAndSettle(); + await _openSettings(tester); expect(find.byTooltip('Change model (currently model-a)'), findsOneWidget); await tester.tap(find.byKey(const Key('chat-model'))); @@ -93,6 +112,7 @@ void main() { await tester.tap(find.text('Model Beta')); await tester.pumpAndSettle(); expect(find.byTooltip('Change model (currently model-b)'), findsOneWidget); + await _closeSettings(tester); await tester.tap(findNativeBack()); await tester.pumpAndSettle(); @@ -102,6 +122,7 @@ void main() { // still show the model the server accepted. await tester.tap(find.byKey(const Key('chat-row-s'))); await tester.pumpAndSettle(); + await _openSettings(tester); expect(find.byTooltip('Change model (currently model-b)'), findsOneWidget); expect(find.byTooltip('Change model (currently model-a)'), findsNothing); @@ -133,6 +154,7 @@ void main() { // The deep link opened before any row was tapped: the list's own read // supplies the title and the recorded model, with no second list request. expect(find.text('Wire chat'), findsOneWidget); + await _openSettings(tester); expect(find.byTooltip('Change model (currently model-a)'), findsOneWidget); expect(find.byKey(const Key('chat-model')), findsOneWidget); expect(gateway.count('chat_sessions'), 1); diff --git a/app/test/features/chat/conversation/chat_floating_chrome_test.dart b/app/test/features/chat/conversation/chat_floating_chrome_test.dart index c9a37c5c..8a8d43ab 100644 --- a/app/test/features/chat/conversation/chat_floating_chrome_test.dart +++ b/app/test/features/chat/conversation/chat_floating_chrome_test.dart @@ -4,6 +4,8 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:pipelines_app/features/chat/conversation/chat_reading_width.dart'; import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart'; import 'package:pipelines_app/ui/adaptive/glass_pill.dart'; +import 'package:pipelines_app/ui/adaptive/segmented_bar.dart' + show segmentedMoreKey; import 'package:pipelines_app/ui/adaptive/segmented_bar_pieces.dart'; import 'chat_thread_fixtures.dart'; @@ -149,7 +151,8 @@ void main() { final header = find.byKey(const Key('chat-thread-header')); expect(find.byKey(const Key('chat-mode')), findsNothing); // The round Back, the title pill and the actions pill, which always - // carries the Files toggle, so it is never drawn empty. + // carries the More menu, so it is never drawn empty. A narrow bar moves + // the Files toggle into that menu. expect( find.descendant(of: header, matching: find.byType(SegmentedPill)), findsNWidgets(3), @@ -159,7 +162,12 @@ void main() { of: header, matching: find.bySemanticsIdentifier('chat-files-toggle'), ), - findsOneWidget, + findsNothing, + ); + // The bar's own disabled More beside the actions' one. + expect( + find.descendant(of: header, matching: find.byKey(segmentedMoreKey)), + findsWidgets, ); }); diff --git a/app/test/features/chat/conversation/chat_model_picker_test.dart b/app/test/features/chat/conversation/chat_model_picker_test.dart index 0d3a3864..03747925 100644 --- a/app/test/features/chat/conversation/chat_model_picker_test.dart +++ b/app/test/features/chat/conversation/chat_model_picker_test.dart @@ -6,6 +6,8 @@ import 'package:pipelines_app/core/api_gateway.dart'; import 'package:pipelines_app/core/transport/connection_state.dart'; import 'package:pipelines_app/features/chat/conversation/chat_models.dart'; import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart'; +import 'package:pipelines_app/ui/adaptive/segmented_bar.dart' + show segmentedMoreKey; /// A chat thread gateway with scripted model catalog and switch replies. class _ModelGateway implements ApiGateway { @@ -91,6 +93,13 @@ Future _openThread( } Future _openChooser(WidgetTester tester) async { + // A narrow bar keeps the model in the More menu's settings sheet. + if (find.byKey(const Key('chat-model')).evaluate().isEmpty) { + await tester.tap(find.byKey(segmentedMoreKey).hitTestable()); + await tester.pumpAndSettle(); + await tester.tap(find.text('Chat settings')); + await tester.pumpAndSettle(); + } await tester.tap(find.byKey(const Key('chat-model'))); await tester.pumpAndSettle(); } diff --git a/app/test/features/chat/conversation/chat_thread_header_test.dart b/app/test/features/chat/conversation/chat_thread_header_test.dart index 696ce2e9..c7e5ee03 100644 --- a/app/test/features/chat/conversation/chat_thread_header_test.dart +++ b/app/test/features/chat/conversation/chat_thread_header_test.dart @@ -1,11 +1,14 @@ import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:pipelines_app/features/chat/conversation/chat_bar_control_style.dart'; import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart'; import 'package:pipelines_app/features/chat/conversation/chat_thread_header.dart'; import 'package:pipelines_app/features/chat/conversation/chat_sidebar_controls.dart'; import 'package:pipelines_app/features/chat/ui/sessions/chat_adaptive.dart'; +import 'package:pipelines_app/features/chat/ui/sessions/session_row_content.dart'; import 'package:pipelines_app/ui/adaptive/segmented_bar.dart'; +import 'package:pipelines_app/ui/adaptive/window_margins.dart'; import '../../../native_back.dart'; import 'chat_thread_fixtures.dart'; @@ -104,10 +107,9 @@ void main() { ); await tester.pumpAndSettle(); expect(tester.takeException(), isNull); - expect( - find.byKey(const Key('chat-model-permission-island')), - findsOneWidget, - ); + // Narrow: the two selectors wait in the More menu's settings entry. + expect(find.byKey(const Key('chat-model')), findsNothing); + expect(find.byKey(const Key('chat-model-permission-island')), findsNothing); expect(tester.takeException(), isNull); }); @@ -136,11 +138,13 @@ void main() { await tester.pumpAndSettle(); final title = find.text(_title); - final model = find.byKey(const Key('chat-model')); + final more = find.byKey(segmentedMoreKey); final info = find.byKey(const Key('chat-info')); final back = find.byKey(const Key('chat-back')); expect(title, findsOneWidget); - expect(model, findsOneWidget); + // A narrow bar keeps its selectors in the More menu's settings entry. + expect(more, findsWidgets); + expect(find.byKey(const Key('chat-model')), findsNothing); expect(info, findsOneWidget); expect(back, findsOneWidget); expect(tester.takeException(), isNull); @@ -155,14 +159,11 @@ void main() { // selector island in the trailing row. double centerY(Finder finder) => tester.getCenter(finder).dy; expect((centerY(back) - centerY(info)).abs(), lessThan(16)); - expect((centerY(model) - centerY(info)).abs(), lessThan(16)); + expect((centerY(more.first) - centerY(info)).abs(), lessThan(16)); expect(find.descendant(of: info, matching: title), findsOneWidget); double right(Finder finder) => tester.getTopRight(finder).dx; expect(right(back), lessThanOrEqualTo(tester.getTopLeft(info).dx)); - expect(find.byIcon(Icons.memory_outlined), findsOneWidget); - final modelSemantics = tester.getSemantics(model); - expect(modelSemantics.label, contains('Change model')); - expect(modelSemantics.label, contains('currently')); + expect(find.byIcon(Icons.tune), findsNothing); expect( find.textContaining('an-extremely-long-recorded-model-id'), findsNothing, @@ -216,41 +217,31 @@ void main() { ), ); await tester.pumpAndSettle(); - final selectors = find.byKey(const Key('chat-model-permission-island')); final actions = find.byKey(const Key('chat-actions-island')); - expect(selectors, findsOneWidget); expect(actions, findsOneWidget); - expect( - (tester.getCenter(selectors).dy - tester.getCenter(actions).dy).abs(), - lessThan(16), - ); expect(find.byKey(const Key('chat-next')), findsNothing); expect(find.text('Next chat'), findsNothing); - expect(find.byKey(const Key('chat-model')), findsOneWidget); - expect(find.byKey(const Key('chat-mode')), findsOneWidget); - if (width < 600) { + if (width < chatHeaderNarrowWidth) { + // The selectors wait in the More menu's settings entry. + expect(find.byKey(const Key('chat-model')), findsNothing); + expect(find.byKey(const Key('chat-mode')), findsNothing); expect(find.text('model-a'), findsNothing); expect(find.text('Ask before making changes'), findsNothing); - expect(find.byIcon(Icons.memory_outlined), findsOneWidget); - expect(find.byIcon(Icons.shield_outlined), findsOneWidget); - expect( - tester.getSemantics(find.byKey(const Key('chat-model'))).label, - contains('Change model, currently'), - ); - expect( - tester.getSemantics(find.byKey(const Key('chat-mode'))).label, - contains('Change mode, currently'), - ); + } else { + final selectors = find.byKey(const Key('chat-model-permission-island')); + expect(selectors, findsOneWidget); expect( (tester.getCenter(selectors).dy - tester.getCenter(actions).dy).abs(), lessThan(16), ); - } - for (final key in ['chat-model', 'chat-mode']) { - expect( - tester.getSize(find.byKey(Key(key))).width, - greaterThanOrEqualTo(48), - ); + expect(find.byKey(const Key('chat-model')), findsOneWidget); + expect(find.byKey(const Key('chat-mode')), findsOneWidget); + for (final key in ['chat-model', 'chat-mode']) { + expect( + tester.getSize(find.byKey(Key(key))).width, + greaterThanOrEqualTo(48), + ); + } } expect(find.text('Sidebar action'), findsNothing); expect(find.text('Pane action'), findsNothing); @@ -354,4 +345,145 @@ void main() { expect(chatBarButtonPadding.left, 12); expect(chatBarButtonPadding.right, 12); }); + + group('narrow title priority at 430px', () { + const width = 430.0; + const longTitle = + 'A conversation title long enough to need an ellipsis at 430px'; + + void useWidth(WidgetTester tester) { + tester.view.physicalSize = const Size(width, 900); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + } + + Widget bar({ + required String title, + bool showTitle = true, + Widget? identity, + }) => _host( + Align( + alignment: Alignment.topLeft, + child: SizedBox( + width: width, + child: ChatThreadHeader( + title: title, + folder: 'demo', + onInfo: () {}, + showTitle: showTitle, + showBack: true, + onBack: () {}, + identity: identity, + controls: const [ + SizedBox(key: Key('header-control-1'), width: 48, height: 48), + SizedBox(key: Key('header-control-2'), width: 48, height: 48), + ], + actions: [ + ChatBarAction( + label: 'Files', + onPressed: () {}, + materialIcon: Icons.folder_outlined, + ), + ], + ), + ), + ), + ); + + // The bar's own width: the window less its phone side margins. + double barWidth() => width - 2 * WindowMargins.narrowSide; + + bool truncated(WidgetTester tester, String text) { + final render = tester.renderObject(find.text(text)); + final painter = TextPainter( + text: render.text, + textDirection: TextDirection.ltr, + textScaler: render.textScaler, + maxLines: 1, + )..layout(); + final full = painter.width; + painter.dispose(); + return full > render.size.width + 1; + } + + testWidgets('a short title reads whole and the selectors collapse', ( + tester, + ) async { + useWidth(tester); + await tester.pumpWidget(bar(title: 'Fixture chat 1')); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + expect(truncated(tester, 'Fixture chat 1'), isFalse); + expect(find.byKey(const Key('header-control-1')), findsNothing); + }); + + testWidgets('a long title ellipsizes and keeps 60% of the bar', ( + tester, + ) async { + useWidth(tester); + await tester.pumpWidget(bar(title: longTitle)); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + expect(truncated(tester, longTitle), isTrue); + final info = tester.getSize(find.byKey(const Key('chat-info'))); + expect(info.width, greaterThanOrEqualTo(barWidth() * 0.6 - 1)); + }); + + testWidgets('the harness mark keeps its size beside the title', ( + tester, + ) async { + useWidth(tester); + await tester.pumpWidget( + bar( + title: 'Fixture chat 1', + identity: ChatSessionAvatar( + session: {'id': 's', 'backend': 'opencode'}, + selected: true, + ), + ), + ); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + final mark = tester.getSize(find.byType(ImageIcon)); + expect(mark.width, greaterThanOrEqualTo(20)); + expect(mark.height, greaterThanOrEqualTo(20)); + }); + + testWidgets('the More menu opens the controls in a sheet', (tester) async { + useWidth(tester); + await tester.pumpWidget(bar(title: 'Fixture chat 1')); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('header-control-1')), findsNothing); + await tester.tap(find.byKey(segmentedMoreKey).hitTestable()); + await tester.pumpAndSettle(); + await tester.tap(find.text('Chat settings')); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('header-control-1')), findsOneWidget); + expect(find.byKey(const Key('header-control-2')), findsOneWidget); + expect(tester.takeException(), isNull); + }); + + testWidgets('a narrow bar moves Files into its More menu', (tester) async { + useWidth(tester); + await tester.pumpWidget(bar(title: 'Fixture chat 1')); + await tester.pumpAndSettle(); + expect(find.byTooltip('Files'), findsNothing); + await tester.tap(find.byKey(segmentedMoreKey).hitTestable()); + await tester.pumpAndSettle(); + expect(find.text('Files'), findsOneWidget); + expect(tester.takeException(), isNull); + }); + + testWidgets('a floating window bar shows no title pill', (tester) async { + useWidth(tester); + await tester.pumpWidget(bar(title: 'Fixture chat 1', showTitle: false)); + await tester.pumpAndSettle(); + expect(find.text('Fixture chat 1'), findsNothing); + expect(find.byKey(const Key('chat-info')), findsNothing); + expect(find.byKey(const Key('chat-back')), findsOneWidget); + expect(find.byKey(const Key('chat-actions-island')), findsOneWidget); + expect(tester.takeException(), isNull); + }); + }); } From 4fba2794ebe0bbe40049a5e849cbde12ddf2d51e Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 12 Nov 2026 10:51:44 +0000 Subject: [PATCH 4/9] Replace background task spinner with count ring Show the running-task count inside a primary-colour progress ring while preserving the composer button size and reduced-motion behavior. Update the related widget and integration tests and document the new indicator. --- .../conversation/chat_background_tasks.dart | 10 +- .../chat/conversation/chat_task_spinner.dart | 109 ++++++-------- app/notes/background-tasks-ring.md | 41 +++++ app/notes/composer-running-border.md | 6 +- .../chat_background_tasks_test.dart | 11 +- .../conversation/chat_task_spinner_test.dart | 140 ++++++++++++------ 6 files changed, 195 insertions(+), 122 deletions(-) create mode 100644 app/notes/background-tasks-ring.md diff --git a/app/lib/features/chat/conversation/chat_background_tasks.dart b/app/lib/features/chat/conversation/chat_background_tasks.dart index e89fca54..c41e91e7 100644 --- a/app/lib/features/chat/conversation/chat_background_tasks.dart +++ b/app/lib/features/chat/conversation/chat_background_tasks.dart @@ -147,13 +147,11 @@ class _ChatBackgroundTasksState extends State { visualDensity: VisualDensity.compact, ), onPressed: _open, - // The layers turn only while a task runs; automations stay still. + // A ring around the running count while tasks run; automations stay + // on their static schedule icon. icon: automationOnly ? const Icon(Icons.schedule, size: 16) - : ChatTaskSpinner( - spinning: count > 0, - child: const Icon(Icons.layers_outlined, size: 16), - ), + : ChatTaskSpinner(running: count), label: caption(), ); return Padding( @@ -170,7 +168,7 @@ class _ChatBackgroundTasksState extends State { : 'Background work, $label; task list unavailable') : 'Background work, $label', child: Tooltip( - message: label, + message: count > 0 ? 'Background tasks ($count running)' : label, excludeFromSemantics: true, child: button, ), diff --git a/app/lib/features/chat/conversation/chat_task_spinner.dart b/app/lib/features/chat/conversation/chat_task_spinner.dart index ab5daa28..6b46e7fa 100644 --- a/app/lib/features/chat/conversation/chat_task_spinner.dart +++ b/app/lib/features/chat/conversation/chat_task_spinner.dart @@ -1,71 +1,50 @@ -import 'package:flutter/widgets.dart'; +import 'package:flutter/material.dart'; -/// Turns [child] once every [period] while [spinning]; static otherwise. With -/// reduced motion it never turns. Hidden UI is silenced by TickerMode. -class ChatTaskSpinner extends StatefulWidget { - const ChatTaskSpinner({ - super.key, - required this.spinning, - required this.child, - }); +/// Background-task glyph for the composer. While [running] is above zero it +/// shows a thin Material progress ring around the count; with reduced motion +/// the ring holds one static quarter segment instead of spinning. With no +/// running task it is the plain layers icon, with no ring. Always [size] square +/// so the button keeps the same dimensions in every state. +class ChatTaskSpinner extends StatelessWidget { + const ChatTaskSpinner({super.key, required this.running, this.size = 16}); - final bool spinning; - final Widget child; + final int running; + final double size; - /// One full turn while tasks run. - static const Duration period = Duration(milliseconds: 2500); + /// Fraction of the ring drawn while reduced motion holds it still. + static const double reducedSegment = 0.25; @override - State createState() => _ChatTaskSpinnerState(); -} - -class _ChatTaskSpinnerState extends State - with SingleTickerProviderStateMixin { - late final AnimationController _turns = AnimationController( - vsync: this, - duration: ChatTaskSpinner.period, - ); - bool _reduced = false; - - @override - void initState() { - super.initState(); - _sync(); - } - - @override - void didChangeDependencies() { - super.didChangeDependencies(); - _reduced = MediaQuery.maybeDisableAnimationsOf(context) ?? false; - _sync(); - } - - @override - void didUpdateWidget(covariant ChatTaskSpinner oldWidget) { - super.didUpdateWidget(oldWidget); - _sync(); - } - - void _sync() { - if (widget.spinning && !_reduced) { - if (!_turns.isAnimating) _turns.repeat(); - } else { - _turns - ..stop() - ..value = 0; - } - } - - @override - void dispose() { - _turns.dispose(); - super.dispose(); - } - - @override - Widget build(BuildContext context) => RotationTransition( - key: const Key('chat-background-tasks-spinner'), - turns: _turns, - child: widget.child, - ); + Widget build(BuildContext context) { + final theme = Theme.of(context); + final reduced = MediaQuery.maybeDisableAnimationsOf(context) ?? false; + final content = running > 0 + ? Stack( + alignment: Alignment.center, + children: [ + SizedBox.square( + dimension: size, + child: CircularProgressIndicator( + strokeWidth: 2, + color: theme.colorScheme.primary, + value: reduced ? reducedSegment : null, + ), + ), + FittedBox( + fit: BoxFit.scaleDown, + child: Text( + '$running', + key: const Key('chat-background-tasks-count'), + style: theme.textTheme.labelSmall, + ), + ), + ], + ) + : Icon(Icons.layers_outlined, size: size); + return SizedBox.square( + key: const Key('chat-background-tasks-spinner'), + dimension: size, + child: content, + ); + } } diff --git a/app/notes/background-tasks-ring.md b/app/notes/background-tasks-ring.md new file mode 100644 index 00000000..7b2da799 --- /dev/null +++ b/app/notes/background-tasks-ring.md @@ -0,0 +1,41 @@ +# Background tasks ring (composer) + +Replaces the rotating layers icon in the composer's background-tasks button. + +## Behaviour + +- `chat_task_spinner.dart`: `ChatTaskSpinner(running:)`, 16 px square in every state. + - `running > 0`: Material `CircularProgressIndicator` (indeterminate, stroke 2, + primary colour) with the running count centred inside (`FittedBox` scales + the digit down under large text scaling). + - reduced motion (`MediaQuery.disableAnimations`): the same ring holds one + static quarter segment (`value: 0.25`) instead of spinning. + - `running == 0`: static `Icons.layers_outlined`, no ring. +- `chat_background_tasks.dart`: automation-only state keeps its static schedule + icon. Tooltip with running tasks is `Background tasks (N running)`; without + running tasks it keeps the caption label (e.g. `1 automation`, `Tasks`). + Semantics label is unchanged. +- Button size, padding and caption are unchanged. + +## Tests (memwatch, from app/) + +| Run | Paths | Result | +|---|---|---| +| 1 | `chat_task_spinner_test`, `chat_background_tasks_test`, `chat_background_tasks_modal_test`, `chat_background_task_metadata_test`, `chat_background_tasks_gui_test`, `chat_background_tasks_controller_test`, `chat_automation_lifecycle_test` | FAIL 37/38 (`chat_background_tasks_test` "combined caption..." — my test's `find.descendant` on the count key; fixed) | +| 2 | same seven paths | PASS 38/38, exit 0 | + +`tool/analyze.sh`: clean, exit 0. + +Test expectation changes (all from the requested behaviour): +- `chat_task_spinner_test.dart` rewritten for the ring: indeterminate value, + stroke 2, primary colour (light and dark), count text, same 16 px size in + every state, reduced-motion static segment, tooltip on the composer button. +- `chat_background_tasks_test.dart`: tooltip `2 tasks, 12 automations` became + `Background tasks (2 running)`; the composer count now also appears inside the + ring, so the caption check expects two `2` texts and the ring's count is checked + by its key. + +## Not verified here + +- Light/dark captures and rendered checks were not done in this stage; ui-review owns them. +- No device or browser run. diff --git a/app/notes/composer-running-border.md b/app/notes/composer-running-border.md index 7b5f934c..2bdd9a4a 100644 --- a/app/notes/composer-running-border.md +++ b/app/notes/composer-running-border.md @@ -21,9 +21,9 @@ - **More menu Stop.** `chat_thread_view.dart` adds a `Stop` item to the header's More menu while a turn runs (`key chat-thread-stop-menu`). It is shown on every platform, so touch devices without a keyboard can stop. -- **Tasks spinner.** `chat_task_spinner.dart` turns the layers icon once per - 2.5 s while at least one background task runs; static otherwise and under - reduced motion. Automation-only state keeps its static schedule icon. +- **Tasks spinner.** Superseded: `chat_task_spinner.dart` now draws a progress + ring with the running count instead of turning the layers icon. See + `notes/background-tasks-ring.md`. ## Focused tests (memwatch, from app/) diff --git a/app/test/features/chat/conversation/chat_background_tasks_test.dart b/app/test/features/chat/conversation/chat_background_tasks_test.dart index 8cfd5acc..3c515bd4 100644 --- a/app/test/features/chat/conversation/chat_background_tasks_test.dart +++ b/app/test/features/chat/conversation/chat_background_tasks_test.dart @@ -673,11 +673,18 @@ void main() { }); await tester.pump(); await tester.pump(const Duration(milliseconds: 500)); - expect(find.byTooltip('2 tasks, 12 automations'), findsOneWidget); + expect(find.byTooltip('Background tasks (2 running)'), findsOneWidget); final counter = find.byKey(const Key('chat-background-tasks-button')); + // One '2' is the count inside the ring, one is the compact caption. + expect( + tester + .widget(find.byKey(const Key('chat-background-tasks-count'))) + .data, + '2', + ); expect( find.descendant(of: counter, matching: find.text('2')), - findsOneWidget, + findsNWidgets(2), ); expect( find.descendant(of: counter, matching: find.text('12')), diff --git a/app/test/features/chat/conversation/chat_task_spinner_test.dart b/app/test/features/chat/conversation/chat_task_spinner_test.dart index 3a10dcb1..91c63978 100644 --- a/app/test/features/chat/conversation/chat_task_spinner_test.dart +++ b/app/test/features/chat/conversation/chat_task_spinner_test.dart @@ -6,19 +6,23 @@ import 'package:pipelines_app/core/api_gateway.dart'; import 'package:pipelines_app/features/chat/conversation/chat_background_tasks.dart'; import 'package:pipelines_app/features/chat/conversation/chat_task_spinner.dart'; -RotationTransition _rotation(WidgetTester tester) => - tester.widget( - find.byKey(const Key('chat-background-tasks-spinner')), +final _spinnerFinder = find.byKey(const Key('chat-background-tasks-spinner')); + +CircularProgressIndicator _ring(WidgetTester tester) => + tester.widget( + find.descendant( + of: _spinnerFinder, + matching: find.byType(CircularProgressIndicator), + ), ); -Widget _spinner(bool spinning) => MaterialApp( - home: Scaffold( - body: ChatTaskSpinner( - spinning: spinning, - child: const Icon(Icons.layers_outlined, size: 16), - ), - ), -); +Widget _spinner(int running, {Brightness brightness = Brightness.light}) => + MaterialApp( + theme: ThemeData(colorSchemeSeed: Colors.indigo, brightness: brightness), + home: Scaffold( + body: Center(child: ChatTaskSpinner(running: running)), + ), + ); void _reducedMotion(bool reduced) => TestWidgetsFlutterBinding.ensureInitialized() @@ -51,58 +55,99 @@ class _TasksGateway implements ApiGateway { void main() { tearDown(() => _reducedMotion(false)); - testWidgets('turns once every period while spinning', (tester) async { + testWidgets( + 'a running task shows an indeterminate primary ring with the count', + (tester) async { + _reducedMotion(false); + await tester.pumpWidget(_spinner(2)); + final ring = _ring(tester); + expect(ring.value, isNull); + expect(ring.strokeWidth, 2); + expect( + ring.color, + ThemeData(colorSchemeSeed: Colors.indigo).colorScheme.primary, + ); + expect( + find.descendant(of: _spinnerFinder, matching: find.text('2')), + findsOneWidget, + ); + expect( + find.descendant( + of: _spinnerFinder, + matching: find.byIcon(Icons.layers_outlined), + ), + findsNothing, + ); + // The ring keeps turning: time advances the animation. + await tester.pump(const Duration(milliseconds: 300)); + expect(tester.binding.transientCallbackCount, greaterThan(0)); + await tester.pumpWidget(const SizedBox.shrink()); + expect(tester.binding.transientCallbackCount, 0); + }, + ); + + testWidgets('dark theme uses the dark primary for the ring', (tester) async { _reducedMotion(false); - await tester.pumpWidget(_spinner(true)); - expect(_rotation(tester).turns.value, 0); - await tester.pump(ChatTaskSpinner.period ~/ 4); - expect(_rotation(tester).turns.value, closeTo(0.25, 0.01)); - // Past one full lap the turn starts again from the top. - await tester.pump( - ChatTaskSpinner.period ~/ 4 * 3 + const Duration(milliseconds: 100), + await tester.pumpWidget(_spinner(1, brightness: Brightness.dark)); + expect( + _ring(tester).color, + ThemeData( + colorSchemeSeed: Colors.indigo, + brightness: Brightness.dark, + ).colorScheme.primary, ); - expect(_rotation(tester).turns.value, closeTo(0.04, 0.01)); - await tester.pumpWidget(const SizedBox.shrink()); - expect(tester.binding.transientCallbackCount, 0); }); - testWidgets('stays still when not spinning, and stops when it stops', ( + testWidgets('no running task shows the static icon with no ring', ( tester, ) async { _reducedMotion(false); - await tester.pumpWidget(_spinner(false)); - await tester.pump(const Duration(seconds: 2)); - expect(_rotation(tester).turns.value, 0); - expect(tester.binding.transientCallbackCount, 0); - - await tester.pumpWidget(_spinner(true)); - await tester.pump(const Duration(milliseconds: 625)); - expect(_rotation(tester).turns.value, greaterThan(0)); - - await tester.pumpWidget(_spinner(false)); - await tester.pump(); - expect(_rotation(tester).turns.value, 0); - await tester.pump(const Duration(seconds: 2)); - expect(_rotation(tester).turns.value, 0); + await tester.pumpWidget(_spinner(0)); + expect( + find.descendant( + of: _spinnerFinder, + matching: find.byType(CircularProgressIndicator), + ), + findsNothing, + ); + expect( + find.descendant( + of: _spinnerFinder, + matching: find.byIcon(Icons.layers_outlined), + ), + findsOneWidget, + ); expect(tester.binding.transientCallbackCount, 0); }); - testWidgets('reduced motion keeps the icon static even while spinning', ( + testWidgets('every state keeps the same square size', (tester) async { + _reducedMotion(false); + for (final running in [0, 1, 12]) { + await tester.pumpWidget(_spinner(running)); + expect(tester.getSize(_spinnerFinder), const Size(16, 16)); + } + }); + + testWidgets('reduced motion holds one static ring segment while running', ( tester, ) async { _reducedMotion(true); - await tester.pumpWidget(_spinner(true)); + await tester.pumpWidget(_spinner(3)); + expect(_ring(tester).value, ChatTaskSpinner.reducedSegment); await tester.pump(const Duration(seconds: 1)); - expect(_rotation(tester).turns.value, 0); + expect(_ring(tester).value, ChatTaskSpinner.reducedSegment); expect(tester.binding.transientCallbackCount, 0); }); - testWidgets('the tasks icon rotates only while a task runs', (tester) async { + testWidgets('the composer button shows the count ring and its tooltip', ( + tester, + ) async { _reducedMotion(false); final gateway = _TasksGateway(); addTearDown(gateway.close); gateway.running = const [ {'id': 'sh1', 'status': 'running', 'command': 'go test ./...'}, + {'id': 'sh2', 'status': 'running', 'command': 'make'}, ]; await tester.pumpWidget( MaterialApp( @@ -111,12 +156,15 @@ void main() { ), ), ); - // The spinning icon repeats forever, so settle by pumping, never by waiting. + // The ring repeats forever, so settle by pumping, never by waiting. await tester.pump(); await tester.pump(); - expect(find.text('1 task'), findsOneWidget); - final before = _rotation(tester).turns.value; - await tester.pump(const Duration(milliseconds: 300)); - expect(_rotation(tester).turns.value, greaterThan(before)); + expect(find.text('2 tasks'), findsOneWidget); + expect(find.byTooltip('Background tasks (2 running)'), findsOneWidget); + expect(_ring(tester).value, isNull); + expect( + find.descendant(of: _spinnerFinder, matching: find.text('2')), + findsOneWidget, + ); }); } From fc86a8257cc6aa9aa92babdf29a46cc62c246ea5 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 12 Nov 2026 10:53:09 +0000 Subject: [PATCH 5/9] Add labelled run entry points Make starting runs discoverable from pipeline details and the Runs tab. Share the existing launch flow, add an active-pipeline picker, and update walkthrough guidance with focused widget coverage. --- app/lib/application/pending_run_scope.dart | 11 + .../application/pipelines_destination.dart | 6 +- app/lib/application/runs_destination.dart | 5 + .../pipelines/ui/run_pipeline_action.dart | 156 ++----------- .../pipelines/ui/run_pipeline_flow.dart | 155 +++++++++++++ app/lib/features/runs/screen.dart | 101 +++++++-- app/lib/features/runs/ui/new_run_button.dart | 17 ++ app/lib/features/runs/ui/new_run_flow.dart | 40 ++++ app/lib/features/runs/ui/new_run_picker.dart | 143 ++++++++++++ .../walkthrough/walkthrough_steps.dart | 2 +- app/notes/start-run-entry-points.md | 98 +++++++++ .../ui/run_pipeline_launch_test.dart | 24 ++ app/test/features/runs/ui/new_run_test.dart | 206 ++++++++++++++++++ .../runs/ui/runs_list_refresh_test.dart | 9 +- 14 files changed, 820 insertions(+), 153 deletions(-) create mode 100644 app/lib/application/pending_run_scope.dart create mode 100644 app/lib/features/pipelines/ui/run_pipeline_flow.dart create mode 100644 app/lib/features/runs/ui/new_run_button.dart create mode 100644 app/lib/features/runs/ui/new_run_flow.dart create mode 100644 app/lib/features/runs/ui/new_run_picker.dart create mode 100644 app/notes/start-run-entry-points.md create mode 100644 app/test/features/runs/ui/new_run_test.dart diff --git a/app/lib/application/pending_run_scope.dart b/app/lib/application/pending_run_scope.dart new file mode 100644 index 00000000..ee812b9b --- /dev/null +++ b/app/lib/application/pending_run_scope.dart @@ -0,0 +1,11 @@ +import '../core/api_gateway.dart'; +import '../core/servers/server_scope.dart'; +import 'server_endpoint.dart'; + +/// The scope that isolates a server's pending launch intents. Pipelines and +/// Runs must compute the same scope, or a lost reply could be retried under a +/// different key from the one the Pipelines tab would check. +String pendingRunScope(ApiGateway gateway, ServerEndpoint server) { + final identity = serverIdentity(gateway); + return identity == null ? server.uri?.toString() ?? '' : 'profile:$identity'; +} diff --git a/app/lib/application/pipelines_destination.dart b/app/lib/application/pipelines_destination.dart index fb2a9046..52dc3774 100644 --- a/app/lib/application/pipelines_destination.dart +++ b/app/lib/application/pipelines_destination.dart @@ -1,10 +1,10 @@ import 'package:flutter/material.dart'; -import '../core/servers/server_scope.dart'; import '../features/pipelines/screen.dart'; import '../ui/adaptive/top_bar_notices.dart'; import 'app_session.dart'; import 'connection_status.dart'; +import 'pending_run_scope.dart'; import 'server_endpoint.dart'; /// The Pipelines destination: the read-only browser plus honest status. @@ -82,9 +82,7 @@ class PipelinesDestination extends StatelessWidget { Widget _pipelinesScreen() => PipelinesScreen( gateway: session.gateway, - endpoint: serverIdentity(session.gateway) == null - ? server.uri?.toString() ?? '' - : 'profile:${serverIdentity(session.gateway)}', + endpoint: pendingRunScope(session.gateway, server), legacyEndpoints: legacyPendingEndpoints, embedded: true, active: active, diff --git a/app/lib/application/runs_destination.dart b/app/lib/application/runs_destination.dart index b4a4baef..afde6946 100644 --- a/app/lib/application/runs_destination.dart +++ b/app/lib/application/runs_destination.dart @@ -2,11 +2,13 @@ import 'package:flutter/material.dart'; import '../features/attention/notify/notification_controller.dart'; import '../features/attention/runtime/attention_controller.dart'; +import '../features/pipelines/pending_run_store.dart'; import '../features/runs/screen.dart'; import '../features/runs/ui/run_pipeline_link.dart'; import '../ui/adaptive/top_bar_notices.dart'; import 'app_session.dart'; import 'connection_status.dart'; +import 'pending_run_scope.dart'; import 'server_endpoint.dart'; /// The Runs destination: the loaded screen plus an honest connection status. @@ -100,6 +102,9 @@ class RunsDestination extends StatelessWidget { listRefreshToken: listRefreshToken, notifications: notifications, attention: attention, + pendingRunStore: SharedPreferencesPendingRunStore( + pendingRunScope(session.gateway, server), + ), onRunSelected: onRunSelected, onBack: onBack, onPipelineFilterChanged: onPipelineFilterChanged, diff --git a/app/lib/features/pipelines/ui/run_pipeline_action.dart b/app/lib/features/pipelines/ui/run_pipeline_action.dart index c0003966..69be40e3 100644 --- a/app/lib/features/pipelines/ui/run_pipeline_action.dart +++ b/app/lib/features/pipelines/ui/run_pipeline_action.dart @@ -1,21 +1,16 @@ import 'package:flutter/material.dart'; import '../../../core/api_gateway.dart'; -import '../../../core/transport/connection_state.dart'; -import '../../runs/data/runs_repository.dart'; +import '../../../ui/adaptive/segmented_bar_overflow.dart'; import '../pipeline_models.dart'; import '../pipelines_controller.dart'; -import '../run_pipeline_intent.dart'; -import '../widgets/pipeline_bar_buttons.dart'; -import 'run_pipeline_dialog.dart'; +import 'run_pipeline_flow.dart'; import 'run_pipeline_wording.dart'; -/// The pipeline detail's Run action. -/// -/// Nothing is requested until the dialog's confirm. A confirmed attempt sends -/// the web's exact `run_pipeline` body against the pinned resolved version; a -/// lost reply keeps the intent so the next deliberate press checks by the same -/// request key before resending. Only the id the server names is opened. +const _runIcon = Icons.play_arrow_rounded; + +/// The pipeline detail's Run action: a labelled button that opens the shared +/// start flow ([openRunPipelineFlow]). class RunPipelineAction extends StatefulWidget { const RunPipelineAction({ super.key, @@ -26,8 +21,8 @@ class RunPipelineAction extends StatefulWidget { this.inBar = false, }); - /// The compact icon-and-word button of a top bar's actions pill instead - /// of an inline button. + /// The compact button of a top bar's actions pill instead of an inline + /// button. A narrow bar moves it into its More menu, labelled. final bool inBar; final PipelinesController controller; @@ -45,143 +40,38 @@ class RunPipelineAction extends StatefulWidget { class _RunPipelineActionState extends State { bool _dialogOpen = false; - int get _pipelineId => widget.detail.id; - int get _version => widget.detail.resolvedVersion; - Future _open() async { if (_dialogOpen) return; _dialogOpen = true; try { - final pending = await widget.controller.loadPendingRun( - _pipelineId, - _version, - ); - if (!mounted) return; - await showRunPipelineDialog( + await openRunPipelineFlow( context: context, + controller: widget.controller, detail: widget.detail, gateway: widget.gateway, - pending: pending, - onSubmit: _submit, - onPendingChanged: (intent) { - if (intent == null) { - widget.controller.clearPendingRun(_pipelineId, _version); - } else { - widget.controller.rememberPendingRun(intent); - } - }, - onAccepted: _accepted, + onRunStarted: widget.onRunStarted, ); } finally { _dialogOpen = false; } } - void _accepted(JsonMap run) { - final id = runPipelineRunId(run); - if (id == null) return; - widget.controller.clearPendingRun(_pipelineId, _version); - widget.onRunStarted?.call(id); - } - - Future _submit(RunPipelineIntent intent) async { - final repository = RunsRepository(widget.gateway); - final pending = widget.controller.pendingRunFor( - intent.pipelineId, - intent.version, - ); - if (pending?.requestKey == intent.requestKey) { - // A previous send may have been admitted even though its reply was lost. - // Check before resending the same key; the server dedupes either way. - try { - final existing = await repository.runByRequestKey(intent.requestKey); - if (existing != null) return _accept(existing); - } catch (error) { - widget.controller.rememberPendingRun(intent); - return RunPipelineRefused( - '${describeRunPipelineError(error)}$runPipelineUnknownSuffix', - admissionUnknown: true, - ); - } - } - try { - final run = await repository.startRun( - pipelineId: intent.pipelineId, - version: intent.version, - prompt: intent.prompt, - workspace: intent.workspace, - requestKey: intent.requestKey, - notifyMode: intent.notifyMode.wireValue, - outputFormat: intent.outputFormat.wireValue, - ); - final accepted = _accept(run); - if (accepted is RunPipelineAccepted) return accepted; - // A reply without a usable run id is not navigable: read the admitted run - // by key rather than inventing an id or starting another run. - return _refuse(repository, intent, 'The server returned no run id.'); - } on ProtocolError catch (error) { - return _refuse(repository, intent, describeRunPipelineError(error)); - } on RunsRepositoryException catch (error) { - return _refuse(repository, intent, describeRunPipelineError(error)); - } catch (error) { - widget.controller.rememberPendingRun(intent); - return RunPipelineRefused( - '${describeRunPipelineError(error)}$runPipelineUnknownSuffix', - admissionUnknown: true, - ); - } - } - - /// A reply is only accepted when it names a usable run id. - RunPipelineOutcome _accept(JsonMap run) { - if (runPipelineRunId(run) == null) { - return const RunPipelineRefused( - 'The server returned no run id.', - admissionUnknown: false, - ); - } - widget.controller.clearPendingRun(widget.detail.id, _version); - return RunPipelineAccepted(run); - } - - /// A confirmed refusal: prove by key that no run was admitted before letting - /// the operator correct the fields and try with a fresh key. - Future _refuse( - RunsRepository repository, - RunPipelineIntent intent, - String message, - ) async { - try { - final existing = await repository.runByRequestKey(intent.requestKey); - if (existing != null) return _accept(existing); - widget.controller.clearPendingRun(intent.pipelineId, intent.version); - return RunPipelineRefused(message, admissionUnknown: false); - } catch (_) { - // Admission cannot be proven either way: keep the intent immutable. - widget.controller.rememberPendingRun(intent); - return RunPipelineRefused( - '$message$runPipelineUnknownSuffix', - admissionUnknown: true, - ); - } - } - @override Widget build(BuildContext context) { - final label = const Text(runPipelineActionLabel); - if (widget.inBar) { - return pipelineBarIconButton( - context, - key: runPipelineActionKey, - label: 'Run ${widget.detail.displayName}', - icon: Icons.play_arrow_rounded, - onPressed: _open, - ); - } - return FilledButton( + final button = FilledButton.icon( key: runPipelineActionKey, onPressed: _open, - child: label, + icon: const Icon(_runIcon), + label: const Text(runPipelineActionLabel), + ); + if (!widget.inBar) return button; + return SegmentedOverflowAction( + overflowEntry: SegmentedOverflowEntry( + label: runPipelineActionLabel, + icon: _runIcon, + onPressed: _open, + ), + child: button, ); } } diff --git a/app/lib/features/pipelines/ui/run_pipeline_flow.dart b/app/lib/features/pipelines/ui/run_pipeline_flow.dart new file mode 100644 index 00000000..e2a996ea --- /dev/null +++ b/app/lib/features/pipelines/ui/run_pipeline_flow.dart @@ -0,0 +1,155 @@ +import 'package:flutter/material.dart'; + +import '../../../core/api_gateway.dart'; +import '../../../core/transport/connection_state.dart'; +import '../../runs/data/runs_repository.dart'; +import '../pipeline_models.dart'; +import '../pipelines_controller.dart'; +import '../run_pipeline_intent.dart'; +import 'run_pipeline_dialog.dart'; +import 'run_pipeline_wording.dart'; + +/// The one Run start flow, shared by a pipeline's Run action and the Runs +/// tab's New run picker. +/// +/// Nothing is requested until the dialog's confirm. A confirmed attempt sends +/// the web's exact `run_pipeline` body against the pinned resolved version; a +/// lost reply keeps the intent so the next deliberate press checks by the same +/// request key before resending. Only the id the server names is reported. +Future openRunPipelineFlow({ + required BuildContext context, + required PipelinesController controller, + required PipelineDetail detail, + required ApiGateway gateway, + ValueChanged? onRunStarted, +}) async { + final pipelineId = detail.id; + final version = detail.resolvedVersion; + final pending = await controller.loadPendingRun(pipelineId, version); + if (!context.mounted) return; + await showRunPipelineDialog( + context: context, + detail: detail, + gateway: gateway, + pending: pending, + onSubmit: (intent) => _submit(controller, gateway, intent), + onPendingChanged: (intent) { + if (intent == null) { + controller.clearPendingRun(pipelineId, version); + } else { + controller.rememberPendingRun(intent); + } + }, + onAccepted: (run) { + final id = runPipelineRunId(run); + if (id == null) return; + controller.clearPendingRun(pipelineId, version); + onRunStarted?.call(id); + }, + ); +} + +Future _submit( + PipelinesController controller, + ApiGateway gateway, + RunPipelineIntent intent, +) async { + final repository = RunsRepository(gateway); + final pending = controller.pendingRunFor(intent.pipelineId, intent.version); + if (pending?.requestKey == intent.requestKey) { + // A previous send may have been admitted even though its reply was lost. + // Check before resending the same key; the server dedupes either way. + try { + final existing = await repository.runByRequestKey(intent.requestKey); + if (existing != null) { + return _accept(controller, intent, existing); + } + } catch (error) { + controller.rememberPendingRun(intent); + return RunPipelineRefused( + '${describeRunPipelineError(error)}$runPipelineUnknownSuffix', + admissionUnknown: true, + ); + } + } + try { + final run = await repository.startRun( + pipelineId: intent.pipelineId, + version: intent.version, + prompt: intent.prompt, + workspace: intent.workspace, + requestKey: intent.requestKey, + notifyMode: intent.notifyMode.wireValue, + outputFormat: intent.outputFormat.wireValue, + ); + final accepted = _accept(controller, intent, run); + if (accepted is RunPipelineAccepted) return accepted; + // A reply without a usable run id is not navigable: read the admitted run + // by key rather than inventing an id or starting another run. + return _refuse( + controller, + repository, + intent, + 'The server returned no run id.', + ); + } on ProtocolError catch (error) { + return _refuse( + controller, + repository, + intent, + describeRunPipelineError(error), + ); + } on RunsRepositoryException catch (error) { + return _refuse( + controller, + repository, + intent, + describeRunPipelineError(error), + ); + } catch (error) { + controller.rememberPendingRun(intent); + return RunPipelineRefused( + '${describeRunPipelineError(error)}$runPipelineUnknownSuffix', + admissionUnknown: true, + ); + } +} + +/// A reply is only accepted when it names a usable run id. +RunPipelineOutcome _accept( + PipelinesController controller, + RunPipelineIntent intent, + JsonMap run, +) { + if (runPipelineRunId(run) == null) { + return const RunPipelineRefused( + 'The server returned no run id.', + admissionUnknown: false, + ); + } + controller.clearPendingRun(intent.pipelineId, intent.version); + return RunPipelineAccepted(run); +} + +/// A confirmed refusal: prove by key that no run was admitted before letting +/// the operator correct the fields and try with a fresh key. +Future _refuse( + PipelinesController controller, + RunsRepository repository, + RunPipelineIntent intent, + String message, +) async { + try { + final existing = await repository.runByRequestKey(intent.requestKey); + if (existing != null) return _accept(controller, intent, existing); + controller.clearPendingRun(intent.pipelineId, intent.version); + return RunPipelineRefused(message, admissionUnknown: false); + } catch (_) { + // Admission cannot be proven either way: keep the intent immutable. + controller.rememberPendingRun(intent); + return RunPipelineRefused( + '$message$runPipelineUnknownSuffix', + admissionUnknown: true, + ); + } +} diff --git a/app/lib/features/runs/screen.dart b/app/lib/features/runs/screen.dart index 79a87e73..e3dbcde1 100644 --- a/app/lib/features/runs/screen.dart +++ b/app/lib/features/runs/screen.dart @@ -11,10 +11,15 @@ import '../attention/notify/notification_controller.dart'; import '../../ui/layout/content_width.dart'; import '../attention/runtime/attention_controller.dart'; import '../attention/runtime/attention_store.dart'; +import '../pipelines/pending_run_store.dart'; +import '../pipelines/pipeline_repository.dart'; +import '../pipelines/pipelines_controller.dart'; import 'actions/decision_action.dart'; import 'data/runs_repository.dart'; import 'data/runs_sort_store.dart'; import 'domain/run_decisions.dart'; +import 'ui/new_run_button.dart'; +import 'ui/new_run_flow.dart'; import 'ui/run_pipeline_link.dart'; import 'ui/run_detail_view.dart'; import 'ui/run_search_selection.dart'; @@ -47,6 +52,7 @@ class RunsScreen extends StatefulWidget { this.notifications, this.attention, this.sortStore = const SharedPreferencesRunsSortStore(), + this.pendingRunStore = const SharedPreferencesPendingRunStore(''), }); final ApiGateway gateway; @@ -94,12 +100,24 @@ class RunsScreen extends StatefulWidget { /// Where the list's sort choice persists; tests inject a memory store. final RunsSortStore sortStore; + /// Where a New run's pending launch intent persists, under the same endpoint + /// scope the Pipelines tab uses. Tests inject a memory store. + final PendingRunStore pendingRunStore; + @override State createState() => _RunsScreenState(); } +/// The vertical band the New run button occupies over the list's bottom edge: +/// its margin, the extended button's height and its margin again. +const double _newRunBand = 88; + class _RunsScreenState extends State { late final RunsController controller; + + /// Starts a run from the New run picker. Its state is only the pending + /// launch intent; the pipeline itself is read when the operator picks one. + late final PipelinesController _launches; num? _shownRunId; int? _reportedPipelineId; bool _applyingRoutePipeline = false; @@ -118,6 +136,10 @@ class _RunsScreenState extends State { RunsRepository(widget.gateway), sortStore: widget.sortStore, ); + _launches = PipelinesController( + PipelinesRepository(widget.gateway), + pendingRunStore: widget.pendingRunStore, + ); // A deleted open run closes its detail; the route returns to the list. controller.onOpenRunRemoved = () => widget.onBack?.call(controller.pipelineId); @@ -234,6 +256,23 @@ class _RunsScreenState extends State { widget.onBack?.call(controller.pipelineId); } + /// The New run picker, then the same start flow a pipeline's Run opens. + void _startNewRun() => unawaited( + startNewRunFlow( + context: context, + controller: _launches, + gateway: widget.gateway, + onRunStarted: _newRunStarted, + ), + ); + + /// An accepted launch re-reads the list so its row appears, then opens the + /// run the same way a row tap does. + void _newRunStarted(int id) { + unawaited(controller.resync()); + _select(id); + } + @override void dispose() { controller.removeListener(_selectionChanged); @@ -241,6 +280,7 @@ class _RunsScreenState extends State { controller.removeListener(_detailChanged); _page.dispose(); controller.dispose(); + _launches.dispose(); super.dispose(); } @@ -285,20 +325,55 @@ class _RunsScreenState extends State { onClosed: _back, builder: (context) => _detail(() => Navigator.of(context).maybePop()), ); - final list = AnimatedBuilder( - 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, + // The New run button floats over the list's bottom-right corner while the + // list is the visible view. The list reserves the button's band in its + // bottom padding, so its last row rests above the button, and the overlay + // lifts clear of the shell's bar like the list's own clearance does. + final list = Stack( + fit: StackFit.expand, + children: [ + AnimatedBuilder( + animation: controller, + builder: (context, _) { + final showsButton = !(narrow && selected); + final media = MediaQuery.of(context); + return MediaQuery( + data: media.copyWith( + padding: media.padding.copyWith( + bottom: + media.padding.bottom + (showsButton ? _newRunBand : 0), + ), + ), + child: 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, + ), + ), + ); + }, ), - ), + AnimatedBuilder( + animation: controller, + builder: (context, _) => narrow && selected + ? const SizedBox.shrink() + : Positioned( + left: 16, + right: 16, + bottom: 16 + MediaQuery.paddingOf(context).bottom, + child: Align( + alignment: AlignmentDirectional.bottomEnd, + child: NewRunButton(onPressed: _startNewRun), + ), + ), + ), + ], ); if (narrow) return list; return ListDetailPanes( diff --git a/app/lib/features/runs/ui/new_run_button.dart b/app/lib/features/runs/ui/new_run_button.dart new file mode 100644 index 00000000..515cd3e1 --- /dev/null +++ b/app/lib/features/runs/ui/new_run_button.dart @@ -0,0 +1,17 @@ +import 'package:flutter/material.dart'; + +/// The Runs tab's New run action: an extended floating button that opens the +/// pipeline picker. It is labelled, so it needs no tooltip of its own. +class NewRunButton extends StatelessWidget { + const NewRunButton({super.key, required this.onPressed}); + + final VoidCallback onPressed; + + @override + Widget build(BuildContext context) => FloatingActionButton.extended( + key: const Key('runs-new-run'), + onPressed: onPressed, + icon: const Icon(Icons.add), + label: const Text('New run'), + ); +} diff --git a/app/lib/features/runs/ui/new_run_flow.dart b/app/lib/features/runs/ui/new_run_flow.dart new file mode 100644 index 00000000..5504b1c3 --- /dev/null +++ b/app/lib/features/runs/ui/new_run_flow.dart @@ -0,0 +1,40 @@ +import 'package:flutter/material.dart'; + +import '../../../core/api_gateway.dart'; +import '../../pipelines/pipeline_models.dart'; +import '../../pipelines/pipeline_repository.dart'; +import '../../pipelines/pipelines_controller.dart'; +import '../../pipelines/ui/run_pipeline_flow.dart'; +import '../../pipelines/ui/run_pipeline_wording.dart'; +import 'new_run_picker.dart'; + +/// The Runs tab's New run: pick an active pipeline, read its latest version, +/// then the same start flow a pipeline's Run action opens. +Future startNewRunFlow({ + required BuildContext context, + required PipelinesController controller, + required ApiGateway gateway, + ValueChanged? onRunStarted, +}) async { + final repository = PipelinesRepository(gateway); + final pipelineId = await pickPipelineForNewRun(context, repository); + if (pipelineId == null || !context.mounted) return; + final PipelineDetail detail; + try { + detail = await repository.getPipeline(pipelineId, 0); + } catch (error) { + if (!context.mounted) return; + ScaffoldMessenger.maybeOf( + context, + )?.showSnackBar(SnackBar(content: Text(describeRunPipelineError(error)))); + return; + } + if (!context.mounted) return; + await openRunPipelineFlow( + context: context, + controller: controller, + detail: detail, + gateway: gateway, + onRunStarted: onRunStarted, + ); +} diff --git a/app/lib/features/runs/ui/new_run_picker.dart b/app/lib/features/runs/ui/new_run_picker.dart new file mode 100644 index 00000000..f0d8c639 --- /dev/null +++ b/app/lib/features/runs/ui/new_run_picker.dart @@ -0,0 +1,143 @@ +import 'package:flutter/material.dart'; + +import '../../pipelines/pipeline_models.dart'; +import '../../pipelines/pipeline_repository.dart'; +import '../../pipelines/ui/run_pipeline_wording.dart'; + +/// Whether an active pipeline matches a picker search by name. An empty query +/// matches every pipeline. +bool pipelineMatchesQuery(PipelineSummary pipeline, String query) { + final needle = query.trim().toLowerCase(); + if (needle.isEmpty) return true; + return pipeline.displayName.toLowerCase().contains(needle); +} + +/// Opens the searchable list of active pipelines. Resolves to the chosen +/// pipeline's id, or null when the picker is dismissed. +Future pickPipelineForNewRun( + BuildContext context, + PipelinesRepository repository, +) => showDialog( + context: context, + builder: (_) => _PipelinePicker(repository: repository), +); + +class _PipelinePicker extends StatefulWidget { + const _PipelinePicker({required this.repository}); + + final PipelinesRepository repository; + + @override + State<_PipelinePicker> createState() => _PipelinePickerState(); +} + +class _PipelinePickerState extends State<_PipelinePicker> { + late Future> _pipelines = _loadActive(); + String _query = ''; + + /// Archived pipelines cannot run, so the picker offers only active ones. + Future> _loadActive() async { + final all = await widget.repository.listPipelines(); + return all.where((pipeline) => !pipeline.archived).toList(growable: false); + } + + void _retry() => setState(() => _pipelines = _loadActive()); + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + return Dialog( + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 480, maxHeight: 560), + child: Padding( + padding: const EdgeInsets.all(16), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text('Choose a pipeline', style: theme.textTheme.titleLarge), + const Padding(padding: EdgeInsets.only(top: 12)), + TextField( + key: const Key('new-run-search'), + decoration: const InputDecoration( + hintText: 'Search pipelines', + prefixIcon: Icon(Icons.search), + ), + onChanged: (value) => setState(() => _query = value), + ), + const Padding(padding: EdgeInsets.only(top: 8)), + Flexible(child: _body(context)), + ], + ), + ), + ), + ); + } + + Widget _body(BuildContext context) { + return FutureBuilder>( + future: _pipelines, + builder: (context, snapshot) { + if (snapshot.connectionState != ConnectionState.done) { + return const Padding( + padding: EdgeInsets.all(24), + child: Center(child: CircularProgressIndicator()), + ); + } + if (snapshot.hasError) { + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + describeRunPipelineError(snapshot.error!), + style: TextStyle(color: Theme.of(context).colorScheme.error), + ), + TextButton(onPressed: _retry, child: const Text('Retry')), + ], + ); + } + final active = snapshot.data ?? const []; + if (active.isEmpty) { + return const _Notice('No active pipelines.'); + } + final matches = active + .where((pipeline) => pipelineMatchesQuery(pipeline, _query)) + .toList(growable: false); + if (matches.isEmpty) { + return const _Notice('No pipeline matches the search.'); + } + return ListView( + shrinkWrap: true, + children: [ + for (final pipeline in matches) + ListTile( + key: ValueKey('new-run-pipeline-${pipeline.id}'), + title: Text( + pipeline.displayName, + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + subtitle: Text( + 'v${pipeline.version} · ${pipeline.stages} stages', + ), + onTap: () => Navigator.of(context).pop(pipeline.id), + ), + ], + ); + }, + ); + } +} + +class _Notice extends StatelessWidget { + const _Notice(this.message); + + final String message; + + @override + Widget build(BuildContext context) => Padding( + padding: const EdgeInsets.all(16), + child: Text(message, style: TextStyle(color: Theme.of(context).hintColor)), + ); +} diff --git a/app/lib/features/walkthrough/walkthrough_steps.dart b/app/lib/features/walkthrough/walkthrough_steps.dart index aa45ea1c..22bd12e0 100644 --- a/app/lib/features/walkthrough/walkthrough_steps.dart +++ b/app/lib/features/walkthrough/walkthrough_steps.dart @@ -61,7 +61,7 @@ const walkthroughSteps = [ points: [ 'Pipelines tab: open a workflow and fill in its inputs.', 'Runs tab: follow a run as it works, then read what it produced.', - 'Choose Run on a workflow to start one.', + 'Press Run on a workflow, or New run on the Runs tab, to start one.', ], ), WalkthroughStep( diff --git a/app/notes/start-run-entry-points.md b/app/notes/start-run-entry-points.md new file mode 100644 index 00000000..37eaa181 --- /dev/null +++ b/app/notes/start-run-entry-points.md @@ -0,0 +1,98 @@ +# Starting a run: labelled entry points + +## Change +- Pipeline detail: the icon-only play button in the top bar is now a labelled + `FilledButton.icon` "Run" (same key, `runPipelineActionKey`). In a narrow bar + it moves into the More menu with its label, via the existing + `SegmentedOverflowAction`. +- Runs: an extended "New run" button (`runs-new-run`) floats over the list's + bottom-right corner while the list is the visible view (phone list, or the + desktop list pane). It sits above the shell's bottom bar: the button's bottom + is lifted by the body's bottom padding, the same inset the list clears. While + it is shown, the list's bottom padding also reserves its band (`_newRunBand` + in `lib/features/runs/screen.dart`), so the last row should rest above the button (no test covers this; ui-review to confirm). + It opens a searchable picker of active pipelines (archived ones are + withheld), reads the chosen pipeline's latest version, then opens the same + start dialog the Run button opens. +- The start flow moved out of `RunPipelineAction` into + `lib/features/pipelines/ui/run_pipeline_flow.dart` (`openRunPipelineFlow`), + so both entry points share one submit, pending-intent and accept path. +- The pending-intent store on Runs uses the same endpoint scope as Pipelines + (`lib/application/pending_run_scope.dart`). +- Walkthrough step 3 now reads: "Press Run on a workflow, or New run on the + Runs tab, to start one." + +## Fix for ui-review rejection (visit 1) +- Defect: on a phone the "New run" button sat beneath the bottom navigation + (semantics rect y=928-984 at 430x900), so it was hidden and a tap reached + Settings. +- Cause: the button was the last child of a column under the list, and the + shell's body extends under the bar (`extendBody`), so the bottom of the + column was under the bar. +- Fix: the button is now an overlay positioned above the body's bottom inset, + and the list reserves the band. Desktop uses the same overlay. +- Tried first and rejected: wrapping the list in a `Column` with the button as + a second child (in both an `Expanded` and an outer form). It fixed the phone + position but broke row selection on desktop (`list_detail_consistency_test` + "selected rows" at 640 wide: row 1 kept its selected flag after row 2 was + opened). The overlay keeps the list as a direct child and passes that test. + +## Files +- Source: `lib/features/pipelines/ui/run_pipeline_action.dart`, + `lib/features/pipelines/ui/run_pipeline_flow.dart` (new), + `lib/features/runs/screen.dart`, `lib/features/runs/ui/new_run_button.dart` + (new), `lib/features/runs/ui/new_run_flow.dart` (new), + `lib/features/runs/ui/new_run_picker.dart` (new), + `lib/application/pending_run_scope.dart` (new), + `lib/application/pipelines_destination.dart`, + `lib/application/runs_destination.dart`, + `lib/features/walkthrough/walkthrough_steps.dart`. +- Tests: `test/features/runs/ui/new_run_test.dart` (new), + `test/features/pipelines/ui/run_pipeline_launch_test.dart` (one case added), + `test/features/runs/ui/runs_list_refresh_test.dart` (finder scoped to the list + rows; its expectations are unchanged). + +## Regression coverage for the rejection +- `new_run_test.dart` "New run clears the bottom bar and opens the picker on a + phone": the screen sits in a scaffold with `extendBody` and a NavigationBar, + as the shell does. It asserts the button's bottom is at or above the bar's + top, and that a tap on the button opens the picker. Before the fix it failed + (button bottom 884, bar top 820). + +## Focused results (visit 2) +Command: `tool/memwatch/full.sh` with 19 test files (the new-run and launch +tests plus every test file that builds RunsScreen, the Pipelines Run action, the +Pipelines screen, Settings, or the walkthrough). +- 119 passed, 1 failed. Verdict named only the intended paths. +- Failing: `test/application/run_start_wiring_test.dart` "an accepted launch + opens the returned run and re-reads the runs list exactly once". It also fails + on untouched `main` (checked in a temporary main worktree, since removed): it + times out waiting for `get_pipeline` after tapping `pipeline-row-1`. +- `list_detail_consistency_test.dart`: passes (it failed with the rejected + `Column` layout; see Fix above). +- `new_run_test.dart`: 5 passed, including the phone bottom-bar case. +- `tool/analyze.sh`: clean (exit 0). + +## Affected UI states (for ui-review to re-capture; not captured here) +1. Pipeline detail, wide bar: labelled "Run" next to the list and more icons. +2. Pipeline detail, narrow phone bar: Run should move into More, labelled. +3. Runs list, phone (430x900): "New run" floats above the bottom bar, clear of + the last row at rest. This is the rejected state; it must be re-captured. +4. Runs list, desktop: "New run" floats over the list pane's bottom-right. +5. New run picker: default, searching, no match, no active pipelines, error+retry. +6. Start dialog reached from the picker. +7. Walkthrough step 3 copy. +Before captures: `/tmp/ui-review/pipe-light-430x900/01-pipeline-detail.png` +(play icon unlabelled) and `/tmp/ui-review/base-light-430x900/03-runs.png` +(no New run). + +## Limitations +- No UI was built or captured in this stage (per the stage instructions); + rendering is unverified. The phone position is verified only by the widget + test's layout geometry under a scaffold that mirrors the shell. +- `_newRunBand` is a fixed reservation (16 + 56 + 16). If the extended button + grows with text scale, the last row may need more room. Measuring it would + need a size callback; not done. +- The Runs picker reads only the current endpoint scope. Pending intents stored + under legacy endpoints are not offered by New run (Pipelines still offers them). +- Not run on web, a device or the Fold. diff --git a/app/test/features/pipelines/ui/run_pipeline_launch_test.dart b/app/test/features/pipelines/ui/run_pipeline_launch_test.dart index d611ca9f..c5a6101d 100644 --- a/app/test/features/pipelines/ui/run_pipeline_launch_test.dart +++ b/app/test/features/pipelines/ui/run_pipeline_launch_test.dart @@ -604,4 +604,28 @@ void main() { expect(find.text('Nightly review'), findsWidgets); expect(launches, 0); }); + + testWidgets('the labelled Run button on the detail starts the flow', ( + tester, + ) async { + final fixture = PipelineFixture(); + final navigated = []; + final gateway = launchGateway(fixture, onLaunch: (_) => acceptedRun(79)); + await pumpScreen(tester, gateway, navigated); + await openDetail(tester); + + final run = find.byKey(runPipelineActionKey); + expect( + find.descendant(of: run, matching: find.text(runPipelineActionLabel)), + findsOneWidget, + ); + await tester.tap(run); + await tester.pumpAndSettle(); + await fillFields(tester); + await tester.tap(find.byKey(runPipelineConfirmKey)); + await tester.pumpAndSettle(); + + expect(gateway.callsOf('run_pipeline'), hasLength(1)); + expect(navigated, [79]); + }); } diff --git a/app/test/features/runs/ui/new_run_test.dart b/app/test/features/runs/ui/new_run_test.dart new file mode 100644 index 00000000..5c46419b --- /dev/null +++ b/app/test/features/runs/ui/new_run_test.dart @@ -0,0 +1,206 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/pipelines/ui/run_pipeline_wording.dart'; +import 'package:pipelines_app/features/runs/screen.dart'; + +import '../../pipelines/fixtures.dart'; + +JsonMap _acceptedRun(int id) => { + 'type': 'run', + 'run_detail': {'id': id, 'status': 'running', 'title': 'Run $id'}, +}; + +/// Pipelines for the picker: the fixture's three active ones plus one archived +/// pipeline, which must never be offered for a new run. +List> _pipelines(PipelineFixture fixture) => [ + ...fixture.summaries, + { + ...pipelineSummary(id: 4, name: 'Retired build'), + 'archived_at': '2026-10-01T10:00:00', + }, +]; + +FakeGateway _gateway(PipelineFixture fixture, {required int launchedRunId}) => + FakeGateway( + (type, fields) => switch (type) { + 'list_runs' => runListReply(fixture.runs), + 'list_pipelines' => pipelineListReply(_pipelines(fixture)), + 'get_pipeline' => pipelineDetailReply( + fixture.detailFor( + fields['pipeline_id'] as int, + fields['version'] as int, + )!, + ), + 'chat_directories' => { + 'type': 'chat_directories', + 'chat_directories': ['/work/recent'], + }, + 'run_pipeline' => _acceptedRun(launchedRunId), + _ => errorReply('unexpected $type'), + }, + ); + +/// Pumps the Runs screen. With [withNavigationBar] the screen sits in a +/// scaffold with `extendBody` and a bottom NavigationBar, as the shell does on +/// a phone, so the body scrolls under the bar. +Future _pumpRuns( + WidgetTester tester, + FakeGateway gateway, { + required Size size, + required List selected, + bool withNavigationBar = false, +}) async { + tester.view.physicalSize = size; + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + final screen = RunsScreen(gateway: gateway, onRunSelected: selected.add); + await tester.pumpWidget( + MaterialApp( + home: withNavigationBar + ? Scaffold( + extendBody: true, + body: screen, + bottomNavigationBar: NavigationBar( + selectedIndex: 0, + onDestinationSelected: (_) {}, + destinations: const [ + NavigationDestination( + icon: Icon(Icons.play_arrow), + label: 'Runs', + ), + NavigationDestination( + icon: Icon(Icons.settings), + label: 'Settings', + ), + ], + ), + ) + : Scaffold(body: screen), + ), + ); + await tester.pumpAndSettle(); +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + SharedPreferences.setMockInitialValues({}); + + for (final size in const [Size(430, 900), Size(1100, 900)]) { + testWidgets('New run is labelled on the Runs list at ${size.width} wide', ( + tester, + ) async { + final gateway = _gateway(PipelineFixture(), launchedRunId: 91); + await _pumpRuns(tester, gateway, size: size, selected: []); + + final button = find.byKey(const Key('runs-new-run')); + expect(button, findsOneWidget); + expect( + find.descendant(of: button, matching: find.text('New run')), + findsOneWidget, + ); + }); + } + + testWidgets('New run clears the bottom bar and opens the picker on a phone', ( + tester, + ) async { + final gateway = _gateway(PipelineFixture(), launchedRunId: 91); + await _pumpRuns( + tester, + gateway, + size: const Size(430, 900), + selected: [], + withNavigationBar: true, + ); + + final button = find.byKey(const Key('runs-new-run')); + final bar = find.byType(NavigationBar); + expect(button, findsOneWidget); + // The button sits wholly above the bar, not beneath it. + expect( + tester.getRect(button).bottom, + lessThanOrEqualTo(tester.getRect(bar).top), + ); + + // A tap at the button reaches the button, not the bar behind it. + await tester.tap(button); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('new-run-search')), findsOneWidget); + }); + + testWidgets( + 'New run picks an active pipeline, starts it and opens the new run', + (tester) async { + final fixture = PipelineFixture(); + final gateway = _gateway(fixture, launchedRunId: 91); + final selected = []; + await _pumpRuns( + tester, + gateway, + size: const Size(1100, 900), + selected: selected, + ); + + await tester.tap(find.byKey(const Key('runs-new-run'))); + await tester.pumpAndSettle(); + + // The picker lists active pipelines only; the archived one is withheld. + expect(find.byKey(const ValueKey('new-run-pipeline-1')), findsOneWidget); + expect(find.byKey(const ValueKey('new-run-pipeline-2')), findsOneWidget); + expect(find.byKey(const ValueKey('new-run-pipeline-4')), findsNothing); + + // Search narrows the list by name. + await tester.enterText(find.byKey(const Key('new-run-search')), 'beta'); + await tester.pump(); + expect(find.byKey(const ValueKey('new-run-pipeline-1')), findsNothing); + expect(find.byKey(const ValueKey('new-run-pipeline-2')), findsOneWidget); + + await tester.tap(find.byKey(const ValueKey('new-run-pipeline-2'))); + await tester.pumpAndSettle(); + + // The chosen pipeline's latest version is read, then the start dialog + // opens for it: the same flow as the pipeline's own Run action. + expect(gateway.callsOf('get_pipeline').single.fields, { + 'pipeline_id': 2, + 'version': 0, + }); + await tester.enterText( + find.byKey(runPipelinePromptKey), + 'Ship the beta.', + ); + await tester.enterText(find.byKey(runPipelineWorkspaceKey), '/work/beta'); + await tester.pump(); + await tester.tap(find.byKey(runPipelineConfirmKey)); + await tester.pumpAndSettle(); + + final launch = gateway.callsOf('run_pipeline').single.fields; + expect(launch['pipeline_id'], 2); + expect(launch['version'], 1); + expect(selected, [91]); + }, + ); + + testWidgets('dismissing the picker starts nothing', (tester) async { + final gateway = _gateway(PipelineFixture(), launchedRunId: 91); + final selected = []; + await _pumpRuns( + tester, + gateway, + size: const Size(430, 900), + selected: selected, + ); + + await tester.tap(find.byKey(const Key('runs-new-run'))); + await tester.pumpAndSettle(); + await tester.tapAt(const Offset(4, 4)); + await tester.pumpAndSettle(); + + expect(find.byKey(const Key('new-run-search')), findsNothing); + expect(gateway.callsOf('get_pipeline'), isEmpty); + expect(gateway.callsOf('run_pipeline'), isEmpty); + expect(selected, isEmpty); + }); +} diff --git a/app/test/features/runs/ui/runs_list_refresh_test.dart b/app/test/features/runs/ui/runs_list_refresh_test.dart index 6dd1f192..7a074a78 100644 --- a/app/test/features/runs/ui/runs_list_refresh_test.dart +++ b/app/test/features/runs/ui/runs_list_refresh_test.dart @@ -4,6 +4,11 @@ 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/screen.dart'; +import 'package:pipelines_app/features/runs/ui/runs_list.dart'; + +/// The list's row titles only: the New run button carries the same words. +Finder _rowTitled(String title) => + find.descendant(of: find.byType(RunsList), matching: find.text(title)); class _Gateway implements ApiGateway { final listRequests = >[]; @@ -53,7 +58,7 @@ void main() { await tester.pump(); expect(gateway.listRequests, hasLength(2)); // No row is invented while the fresh read is outstanding. - expect(find.text('New run'), findsNothing); + expect(_rowTitled('New run'), findsNothing); gateway.listRequests[1].complete({ 'runs': [ {'id': 2, 'title': 'New run', 'status': 'running'}, @@ -63,7 +68,7 @@ void main() { await tester.pump(); await tester.pump(); - expect(find.text('New run'), findsOneWidget); + expect(_rowTitled('New run'), findsOneWidget); expect(gateway.listRequests, hasLength(2)); expect(gateway.detailRequests, isEmpty); }); From 793f9b08f5f5dba0becc24f0d6bd25125b7a7d86 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 12 Nov 2026 10:54:12 +0000 Subject: [PATCH 6/9] Dim inactive chat panes Make inactive split panes visibly recede while preserving readability and pointer activation. Add reduced-motion behavior and widget coverage for pane dimming, activation, and single-pane layouts. --- .../chat/workspace/chat_pane_dim.dart | 42 ++++ .../chat/workspace/chat_workspace.dart | 8 +- app/notes/dim-inactive-chat-panes.md | 40 ++++ .../chat/workspace/chat_pane_dim_test.dart | 182 ++++++++++++++++++ 4 files changed, 270 insertions(+), 2 deletions(-) create mode 100644 app/lib/features/chat/workspace/chat_pane_dim.dart create mode 100644 app/notes/dim-inactive-chat-panes.md create mode 100644 app/test/features/chat/workspace/chat_pane_dim_test.dart diff --git a/app/lib/features/chat/workspace/chat_pane_dim.dart b/app/lib/features/chat/workspace/chat_pane_dim.dart new file mode 100644 index 00000000..56ed5323 --- /dev/null +++ b/app/lib/features/chat/workspace/chat_pane_dim.dart @@ -0,0 +1,42 @@ +import 'package:flutter/material.dart'; + +import '../../../ui/motion/motion.dart'; + +/// The opacity of the surface scrim over an inactive split pane. The pane's +/// transcript and bars keep reading through it at about two thirds emphasis. +const double chatPaneDimOpacity = 0.35; + +/// Covers a pane that is not the active one with the theme's surface colour, +/// so the active pane reads as the one in focus. The scrim ignores pointers: +/// taps reach the pane's content, and its activation listener still runs. +/// Reduced motion switches the scrim at once; otherwise it fades briefly. +class ChatPaneDim extends StatelessWidget { + const ChatPaneDim({super.key, required this.dimmed, required this.child}); + + final bool dimmed; + final Widget child; + + @override + Widget build(BuildContext context) { + final surface = Theme.of(context).colorScheme.surface; + return Stack( + fit: StackFit.passthrough, + children: [ + child, + Positioned.fill( + child: IgnorePointer( + child: AnimatedContainer( + key: const ValueKey('chat-pane-dim-scrim'), + duration: Motion.of(context, Motion.standard), + curve: Motion.curve, + // The clear end keeps the surface hue, so the fade never greys. + color: dimmed + ? surface.withValues(alpha: chatPaneDimOpacity) + : surface.withValues(alpha: 0), + ), + ), + ), + ], + ); + } +} diff --git a/app/lib/features/chat/workspace/chat_workspace.dart b/app/lib/features/chat/workspace/chat_workspace.dart index a7cf32c8..4b226417 100644 --- a/app/lib/features/chat/workspace/chat_workspace.dart +++ b/app/lib/features/chat/workspace/chat_workspace.dart @@ -15,6 +15,7 @@ import 'chat_pane_move_motion.dart'; import 'chat_pane_move_shortcuts.dart'; import 'chat_pane_switch_motion.dart'; import 'chat_pane_backdrop.dart'; +import 'chat_pane_dim.dart'; import 'chat_workspace_pane_scope.dart'; import 'chat_workspace_surface.dart'; import '../../../ui/input/keyboard_owner.dart'; @@ -509,8 +510,11 @@ class _ChatWorkspaceState extends State onPreferredWidthChanged: (width) => _reportPaneExtraWidth(pane.id, width), child: Builder( - builder: (paneContext) => - widget.paneBuilder(paneContext, pane, active), + builder: (paneContext) => ChatPaneDim( + // A single pane is always the active one, so it never dims. + dimmed: widget.controller.paneCount > 1 && !active, + child: widget.paneBuilder(paneContext, pane, active), + ), ), ), ), diff --git a/app/notes/dim-inactive-chat-panes.md b/app/notes/dim-inactive-chat-panes.md new file mode 100644 index 00000000..0294144e --- /dev/null +++ b/app/notes/dim-inactive-chat-panes.md @@ -0,0 +1,40 @@ +# Dim inactive chat panes + +## Change +- `lib/features/chat/workspace/chat_pane_dim.dart` (new): `ChatPaneDim` lays an + `IgnorePointer` surface scrim over a pane's content. The scrim is the theme's + `colorScheme.surface` at `chatPaneDimOpacity` (0.35), so content reads at + about 65% emphasis in light and dark. Its colour fades over `Motion.standard`; + `Motion.of` returns zero under reduced motion, so the change is immediate. +- `lib/features/chat/workspace/chat_workspace.dart`: `_paneContent` wraps each + pane's built content in `ChatPaneDim(dimmed: paneCount > 1 && !active)`. + Pointer activation (the pane `Listener`), focus and the action bar's + existing tint (`ChatPaneActivity`) are unchanged. The scrim ignores pointers, + so a tap reaches the content beneath it and still activates the pane. +- The optional primary outline is not added. The active pane already has its + chat-coloured foreground border (`chat_screen_workspace.dart`). + +## Tests +- `test/features/chat/workspace/chat_pane_dim_test.dart` (new, 7 tests): + two panes dim only the inactive one; three panes dim both inactive panes; + a single pane is never dimmed; a tap on an inactive input activates it and + focuses its editable text; a tap on bare space in an inactive pane activates + it; reduced motion gives a zero duration and an immediate switch; default + motion uses `Motion.standard`. +- Existing users of `ChatWorkspace` also run: `chat_workspace_test`, + `chat_pane_move_test`, `chat_center_stage_test`, `chat_switch_styles_test`, + `chat_mobile_panes_test`, `chat_peek_identity_test`, and + `test/features/settings/quick_switch_preview_test.dart`. + +Command (from `app/`): +`tool/memwatch/full.sh 'test/features/chat/workspace/chat_pane_dim_test.dart test/features/chat/workspace/chat_workspace_test.dart test/features/chat/workspace/chat_pane_move_test.dart test/features/chat/workspace/chat_center_stage_test.dart test/features/chat/workspace/chat_switch_styles_test.dart test/features/chat/workspace/chat_mobile_panes_test.dart test/features/chat/workspace/chat_peek_identity_test.dart test/features/settings/quick_switch_preview_test.dart'` + +Result: `PASS: 70 passed, 0 failed, 0 skipped; peak 1329 MB; 11s; exit 0`. + +Analyzer (`tool/analyze.sh`): clean, exit 0. + +## Not done here +- No captures. The 2- and 3-pane light and dark captures belong to ui-review + (`tool/capture/`), and no UI was built or run in this stage. +- No test or capture covers the chat screen's full path (`chat_screen_workspace.dart`). + The dim comes from `ChatWorkspace`, which that screen uses, so it applies there too. diff --git a/app/test/features/chat/workspace/chat_pane_dim_test.dart b/app/test/features/chat/workspace/chat_pane_dim_test.dart new file mode 100644 index 00000000..34983706 --- /dev/null +++ b/app/test/features/chat/workspace/chat_pane_dim_test.dart @@ -0,0 +1,182 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_pane_dim.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_workspace.dart'; +import 'package:pipelines_app/ui/motion/motion.dart'; + +Widget host( + ChatWorkspaceController controller, { + bool disableAnimations = false, +}) => MaterialApp( + home: Scaffold( + body: SizedBox( + width: 1200, + height: 900, + child: Builder( + builder: (context) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(disableAnimations: disableAnimations), + child: ChatWorkspace( + controller: controller, + paneBuilder: (_, pane, active) => + TextField(key: ValueKey('input-${pane.sessionId}')), + ), + ), + ), + ), + ), +); + +/// The dim overlay wrapping the pane that shows [session]. +Finder dimOf(String session) => find.ancestor( + of: find.byKey(ValueKey('input-$session')), + matching: find.byType(ChatPaneDim), +); + +/// The alpha of the scrim over [session]'s pane: zero when the pane is clear. +double scrimAlpha(WidgetTester tester, String session) { + final scrim = find.descendant( + of: dimOf(session), + matching: find.byKey(const ValueKey('chat-pane-dim-scrim')), + ); + // AnimatedContainer builds a Container whose BoxDecoration holds the colour. + final container = tester.widget( + find.descendant(of: scrim, matching: find.byType(Container)), + ); + final decoration = container.decoration as BoxDecoration?; + return (decoration?.color ?? container.color ?? const Color(0x00000000)).a; +} + +void usePhoneSizedView(WidgetTester tester) { + tester.view.physicalSize = const Size(1200, 900); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); +} + +void main() { + testWidgets('two panes: the inactive pane is dimmed and the active is not', ( + tester, + ) async { + final controller = ChatWorkspaceController() + ..open('one') + ..splitActive('two', ChatSplitAxis.horizontal); + addTearDown(controller.dispose); + await tester.pumpWidget(host(controller)); + await tester.pumpAndSettle(); + + expect(controller.activePane?.sessionId, 'two'); + expect(scrimAlpha(tester, 'one'), closeTo(chatPaneDimOpacity, 0.001)); + expect(scrimAlpha(tester, 'two'), 0); + }); + + testWidgets('three panes: every inactive pane is dimmed, the active is not', ( + tester, + ) async { + final controller = ChatWorkspaceController() + ..open('one') + ..splitActive('two', ChatSplitAxis.horizontal) + ..splitActive('three', ChatSplitAxis.horizontal); + addTearDown(controller.dispose); + await tester.pumpWidget(host(controller)); + await tester.pumpAndSettle(); + + expect(controller.activePane?.sessionId, 'three'); + expect(scrimAlpha(tester, 'one'), closeTo(chatPaneDimOpacity, 0.001)); + expect(scrimAlpha(tester, 'two'), closeTo(chatPaneDimOpacity, 0.001)); + expect(scrimAlpha(tester, 'three'), 0); + }); + + testWidgets('a single pane is never dimmed', (tester) async { + final controller = ChatWorkspaceController()..open('one'); + addTearDown(controller.dispose); + await tester.pumpWidget(host(controller)); + await tester.pumpAndSettle(); + + expect(scrimAlpha(tester, 'one'), 0); + }); + + testWidgets('tapping an inactive pane activates it and focuses its input', ( + tester, + ) async { + usePhoneSizedView(tester); + final controller = ChatWorkspaceController() + ..open('one') + ..splitActive('two', ChatSplitAxis.horizontal); + addTearDown(controller.dispose); + await tester.pumpWidget(host(controller)); + await tester.pumpAndSettle(); + final first = controller.panes.first.id; + expect(controller.activePaneId, isNot(first)); + + await tester.tap(find.byKey(const ValueKey('input-one'))); + await tester.pumpAndSettle(); + + expect(controller.activePaneId, first); + expect(scrimAlpha(tester, 'one'), 0); + expect(scrimAlpha(tester, 'two'), closeTo(chatPaneDimOpacity, 0.001)); + final editable = tester.widget( + find.descendant( + of: find.byKey(const ValueKey('input-one')), + matching: find.byType(EditableText), + ), + ); + expect(editable.focusNode.hasFocus, isTrue); + }); + + testWidgets('a tap on bare space in an inactive pane activates it', ( + tester, + ) async { + usePhoneSizedView(tester); + final controller = ChatWorkspaceController() + ..open('one') + ..splitActive('two', ChatSplitAxis.horizontal); + addTearDown(controller.dispose); + await tester.pumpWidget(host(controller)); + await tester.pumpAndSettle(); + final first = controller.panes.first.id; + + final corner = tester.getTopLeft(dimOf('one')) + const Offset(2, 2); + await tester.tapAt(corner); + await tester.pumpAndSettle(); + + expect(controller.activePaneId, first); + }); + + testWidgets('reduced motion switches the dim at once, without a fade', ( + tester, + ) async { + final controller = ChatWorkspaceController() + ..open('one') + ..splitActive('two', ChatSplitAxis.horizontal); + addTearDown(controller.dispose); + await tester.pumpWidget(host(controller, disableAnimations: true)); + await tester.pumpAndSettle(); + + final scrim = find.byKey(const ValueKey('chat-pane-dim-scrim')).first; + expect(tester.widget(scrim).duration, Duration.zero); + + controller.activate(controller.panes.first.id); + await tester.pump(); + expect(scrimAlpha(tester, 'one'), 0); + expect(scrimAlpha(tester, 'two'), closeTo(chatPaneDimOpacity, 0.001)); + }); + + testWidgets('motion is on by default: the dim fades over the standard time', ( + tester, + ) async { + final controller = ChatWorkspaceController() + ..open('one') + ..splitActive('two', ChatSplitAxis.horizontal); + addTearDown(controller.dispose); + await tester.pumpWidget(host(controller)); + await tester.pumpAndSettle(); + + final scrim = find.byKey(const ValueKey('chat-pane-dim-scrim')).first; + expect( + tester.widget(scrim).duration, + Motion.standard, + ); + }); +} From d9ec43e607bc4249c214bbe267a1bacf18a17dd9 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 12 Nov 2026 10:54:42 +0000 Subject: [PATCH 7/9] Animate composer border at constant arc speed Lay the running highlight out by rounded-border arc length so it advances at a steady linear speed without a loop jump, while preserving the existing colours and reduced-motion border. Add focused geometry tests and implementation notes. --- .../conversation/composer_running_arc.dart | 113 +++++++++++++ .../conversation/composer_running_border.dart | 47 +++--- app/notes/composer-running-border-arc.md | 45 +++++ .../composer_running_arc_test.dart | 159 ++++++++++++++++++ 4 files changed, 343 insertions(+), 21 deletions(-) create mode 100644 app/lib/features/chat/conversation/composer_running_arc.dart create mode 100644 app/notes/composer-running-border-arc.md create mode 100644 app/test/features/chat/conversation/composer_running_arc_test.dart diff --git a/app/lib/features/chat/conversation/composer_running_arc.dart b/app/lib/features/chat/conversation/composer_running_arc.dart new file mode 100644 index 00000000..62d931ce --- /dev/null +++ b/app/lib/features/chat/conversation/composer_running_arc.dart @@ -0,0 +1,113 @@ +import 'dart:math' as math; +import 'dart:ui' show PathMetric; + +import 'package:flutter/material.dart'; + +/// Arc-length geometry for the composer's running border. +/// +/// The highlight is laid out by distance travelled along the outline, not by +/// angle around the centre, so equal time steps move it equal lengths around +/// a rounded rectangle: no racing along the long edges, no crawling at ends. +/// +/// One lap is `progress` in [0, 1]; progress 1 is the same place as 0, so the +/// loop restarts without a jump. + +/// The colour bands, as fractions of a lap measured forward from the origin. +/// They match the original sweep's stops and colours. +const List runningHighlightStops = [0, .12, .24, .38, 1]; + +/// Half a device pixel of overlap so neighbouring segments leave no seam. +const double _seamOverlap = .5; + +/// One piece of the outline and the highlight colour drawn over it. +class RunningArcSegment { + const RunningArcSegment({ + required this.start, + required this.end, + required this.color, + }); + + /// Arc length from the outline's start where the piece begins. + final double start; + + /// Arc length where the piece ends (exclusive, may overlap by a seam). + final double end; + + final Color color; +} + +/// The arc length of the highlight's origin along an outline of [length]. +double runningHighlightOrigin(double progress, double length) { + final lap = progress - progress.floorToDouble(); + return lap * length; +} + +/// The highlight colour [fraction] of a lap ahead of its origin. Fractions +/// wrap, so `f` and `f + 1` are the same colour. +Color runningHighlightColorAt(double fraction, Color primary, Color tertiary) { + final colors = [ + primary.withValues(alpha: 0), + primary, + tertiary, + tertiary.withValues(alpha: 0), + primary.withValues(alpha: 0), + ]; + final f = fraction - fraction.floorToDouble(); + for (var i = 1; i < runningHighlightStops.length; i++) { + final stop = runningHighlightStops[i]; + if (f <= stop) { + final from = runningHighlightStops[i - 1]; + final t = (f - from) / (stop - from); + return Color.lerp(colors[i - 1], colors[i], t)!; + } + } + return colors.last; +} + +/// Splits an outline of [length] into pieces about [step] long and colours +/// each by where it sits in the highlight at [progress]. Pieces with no +/// visible colour are left out. +List runningHighlightSegments({ + required double progress, + required double length, + required Color primary, + required Color tertiary, + double step = 3, +}) { + if (length <= 0) return const []; + final count = math.max(1, (length / step).ceil()); + final size = length / count; + final origin = runningHighlightOrigin(progress, length); + final segments = []; + for (var i = 0; i < count; i++) { + final mid = (i + .5) * size; + final color = runningHighlightColorAt( + (mid - origin) / length, + primary, + tertiary, + ); + if (color.a == 0) continue; + segments.add( + RunningArcSegment( + start: math.max(0, i * size - _seamOverlap), + end: math.min(length, (i + 1) * size + _seamOverlap), + color: color, + ), + ); + } + return segments; +} + +/// The part of an outline between arc lengths [start] and [end]. The outline +/// may be made of several contours, so the range is taken across all of them. +Path runningArcPath(List metrics, double start, double end) { + final out = Path(); + var offset = 0.0; + for (final metric in metrics) { + final from = math.max(start, offset) - offset; + final to = math.min(end, offset + metric.length) - offset; + if (to > from) out.addPath(metric.extractPath(from, to), Offset.zero); + offset += metric.length; + } + return out; +} diff --git a/app/lib/features/chat/conversation/composer_running_border.dart b/app/lib/features/chat/conversation/composer_running_border.dart index 07ecd216..713dcf23 100644 --- a/app/lib/features/chat/conversation/composer_running_border.dart +++ b/app/lib/features/chat/conversation/composer_running_border.dart @@ -1,7 +1,7 @@ -import 'dart:math' as math; - import 'package:flutter/material.dart'; +import 'composer_running_arc.dart'; + /// The composer's "agent is working" edge: a soft highlight that travels once /// around the pill's rounded border in [primary] and [tertiary], with a faint /// glow beneath it. Mount it only while a turn runs; disposing it stops the @@ -22,8 +22,8 @@ class ComposerRunningBorder extends StatefulWidget { final Color primary; final Color tertiary; - /// One lap of the highlight around the border. - static const Duration period = Duration(seconds: 4); + /// One lap of the highlight around the border (about 2.5–3 s). + static const Duration period = Duration(milliseconds: 2750); /// The stroke drawn just inside the pill's edge. static const double strokeWidth = 2; @@ -117,24 +117,29 @@ class _RunningBorderPainter extends CustomPainter { ); glow.color = solid.withValues(alpha: solid.a * .4); line.color = solid; - } else { - final shader = SweepGradient( - colors: [ - primary.withValues(alpha: 0), - primary, - tertiary, - tertiary.withValues(alpha: 0), - primary.withValues(alpha: 0), - ], - stops: const [0, .12, .24, .38, 1], - transform: GradientRotation(progress * 2 * math.pi), - ).createShader(rect); - glow.shader = shader; - line.shader = shader; + canvas + ..drawPath(path, glow) + ..drawPath(path, line); + return; + } + // The highlight is laid along the outline by arc length, one piece at a + // time, so its speed is even around corners and straight edges alike. + final metrics = path.computeMetrics().toList(); + final length = metrics.fold(0, (sum, m) => sum + m.length); + final segments = runningHighlightSegments( + progress: progress, + length: length, + primary: primary, + tertiary: tertiary, + ); + for (final segment in segments) { + final piece = runningArcPath(metrics, segment.start, segment.end); + glow.color = segment.color; + line.color = segment.color; + canvas + ..drawPath(piece, glow) + ..drawPath(piece, line); } - canvas - ..drawPath(path, glow) - ..drawPath(path, line); } @override diff --git a/app/notes/composer-running-border-arc.md b/app/notes/composer-running-border-arc.md new file mode 100644 index 00000000..291f0a3c --- /dev/null +++ b/app/notes/composer-running-border-arc.md @@ -0,0 +1,45 @@ +# Composer running border: constant arc-length speed + +## Change +- The highlight is now laid along the pill's outline by arc length instead of a + `SweepGradient` rotated by angle. Equal time steps move it equal distances + round the rounded rectangle: no racing along long edges, no crawling at ends. +- `lib/features/chat/conversation/composer_running_arc.dart` (new, pure helpers): + origin = fractional lap × outline length; colour bands at the original stops + (0, .12, .24, .38, 1) and colours; segments of ~3 px with a 0.5 px seam + overlap, transparent pieces omitted; `runningArcPath` extracts a piece of the + outline across contours. +- `lib/features/chat/conversation/composer_running_border.dart`: the painter + draws those segments with the same glow and line strokes. Reduced motion still + paints the static border and never ticks. Period (2.75 s), colours, stroke width + and linear lap curve are unchanged. + +## Speed +- `ComposerRunningBorder.period` is now 2750 ms (one lap per 2.75 s, the midpoint + of the requested 2.5–3 s). It was 4 s; review rejected that as too slow. + +## Focused results +- `tool/memwatch/full.sh 'test/features/chat/conversation/composer_running_arc_test.dart test/features/chat/conversation/chat_composer_running_test.dart'` + → PASS 16 passed, 0 failed (peak ~977 MB, exit 0). +- `tool/analyze.sh` on the three changed files → clean. +- New tests (`test/features/chat/conversation/composer_running_arc_test.dart`): + perimeter measured by arc; origin advances equal arc per equal lap step; + origin and colours wrap (progress 1 == 0, f == f+1); colour shifts with + arc under time; visible band spans 0.38 of the lap on a long pill and a + square; segments are ordered and inside the outline; `runningArcPath` + extracts the requested arc. +- Existing widget tests in `chat_composer_running_test.dart` (border mount and + unmount, reduced motion static, no ticks at rest, /stop, Escape handling) + pass unchanged. + +## Affected states (not captured) +- Running composer border: default and reduced motion. Not captured or + reviewed here (ui-review owns captures). Mobile and browser behaviour is + unverified. + +## Limitations +- Each frame draws about 0.38 × perimeter / 3 px segments twice (blurred glow + and line). Not profiled on device. +- The time-to-lap mapping is `AnimationController`'s default linear curve; it is + tested through the pure origin mapping, not by a widget test reading the + controller. diff --git a/app/test/features/chat/conversation/composer_running_arc_test.dart b/app/test/features/chat/conversation/composer_running_arc_test.dart new file mode 100644 index 00000000..c2d9a40d --- /dev/null +++ b/app/test/features/chat/conversation/composer_running_arc_test.dart @@ -0,0 +1,159 @@ +import 'dart:math' as math; +import 'dart:ui'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/chat/conversation/composer_running_arc.dart'; + +const _primary = Color(0xFF3366FF); +const _tertiary = Color(0xFFFF6633); + +/// The pill outline as the painter builds it, measured by arc length. +List _outline(Size size, {double radius = 24}) { + final path = RoundedRectangleBorder( + borderRadius: BorderRadius.circular(radius), + ).getOuterPath(Offset.zero & size); + return path.computeMetrics().toList(); +} + +double _length(List metrics) => + metrics.fold(0, (sum, m) => sum + m.length); + +/// The arc the visible band covers: from its first piece to its last. The +/// pieces overlap by a seam each, so their own lengths would overcount. +double _visibleSpan(List segments) => + segments.last.end - segments.first.start; + +/// Colours that differ only by float rounding at a band edge still match. +void _expectSameColor(Color actual, Color expected, {required String reason}) { + expect(actual.a, closeTo(expected.a, 1e-6), reason: reason); + expect(actual.r, closeTo(expected.r, 1e-6), reason: reason); + expect(actual.g, closeTo(expected.g, 1e-6), reason: reason); + expect(actual.b, closeTo(expected.b, 1e-6), reason: reason); +} + +void main() { + const size = Size(320, 48); + final metrics = _outline(size); + final length = _length(metrics); + + test('the outline is measured by arc length, not by angle', () { + // A 320x48 pill with radius 24: two straights of 272 and four quarter + // corners that make one full circle of radius 24. Flutter's curve metrics + // are approximate, so allow about a pixel. + expect(length, closeTo(2 * 272 + 2 * math.pi * 24, 1)); + expect(metrics, hasLength(1)); + }); + + test('the origin advances by equal arc for equal lap steps', () { + // Curves.linear: the lap value is proportional to elapsed time, so equal + // time steps must give equal arc steps all the way round the outline. + const steps = 16; + final first = runningHighlightOrigin(0, length); + final stepArc = runningHighlightOrigin(1 / steps, length) - first; + expect(stepArc, closeTo(length / steps, 1e-9)); + for (var k = 0; k < steps; k++) { + final origin = runningHighlightOrigin(k / steps, length); + expect(origin, closeTo(k * stepArc, 1e-9), reason: 'step $k'); + } + }); + + test('the highlight wraps seamlessly at the end of a lap', () { + expect(runningHighlightOrigin(1, length), 0); + expect( + runningHighlightOrigin(0.9999, length), + closeTo(length, length * 1e-3), + ); + expect(runningHighlightOrigin(1.25, length), closeTo(length * .25, 1e-9)); + + final start = runningHighlightSegments( + progress: 0, + length: length, + primary: _primary, + tertiary: _tertiary, + ); + final end = runningHighlightSegments( + progress: 1, + length: length, + primary: _primary, + tertiary: _tertiary, + ); + expect(end.length, start.length); + for (var i = 0; i < start.length; i++) { + expect(end[i].start, start[i].start); + expect(end[i].end, start[i].end); + _expectSameColor(end[i].color, start[i].color, reason: 'piece $i'); + } + }); + + test('colours wrap: a fraction and its +1 are the same colour', () { + for (var f = 0.0; f < 1; f += .02) { + _expectSameColor( + runningHighlightColorAt(f + 1, _primary, _tertiary), + runningHighlightColorAt(f, _primary, _tertiary), + reason: 'f=$f', + ); + } + expect(runningHighlightColorAt(0, _primary, _tertiary).a, 0); + }); + + test('the highlight travels by arc: a shift of one step shifts colours', () { + // The colour at a given arc point, one step later, equals the colour one + // step earlier at a point shifted back by the arc that step covers. + const dt = .1; + final arc = dt * length; + for (var x = 0.0; x < length; x += length / 40) { + final before = runningHighlightColorAt( + (x - runningHighlightOrigin(0, length)) / length, + _primary, + _tertiary, + ); + final after = runningHighlightColorAt( + (x + arc - runningHighlightOrigin(dt, length)) / length, + _primary, + _tertiary, + ); + _expectSameColor(after, before, reason: 'x=$x'); + } + }); + + test('the visible band covers the same arc on a long and a square shape', () { + // The band is 38% of a lap. Measured along the outline it has the same + // length whatever the aspect, which an angle-based sweep would not give. + final long = _outline(const Size(320, 48)); + final square = _outline(const Size(120, 120), radius: 12); + for (final shape in [long, square]) { + final len = _length(shape); + final segments = runningHighlightSegments( + progress: .3, + length: len, + primary: _primary, + tertiary: _tertiary, + ); + expect(_visibleSpan(segments), closeTo(.38 * len, 2 * 3 + 1)); + } + }); + + test('the visible segments tile the outline without gaps', () { + final segments = runningHighlightSegments( + progress: .6, + length: length, + primary: _primary, + tertiary: _tertiary, + ); + expect(segments, isNotEmpty); + for (var i = 1; i < segments.length; i++) { + expect(segments[i].start, lessThanOrEqualTo(segments[i - 1].end)); + expect(segments[i].start, greaterThanOrEqualTo(segments[i - 1].start)); + } + expect(segments.first.start, greaterThanOrEqualTo(0)); + expect(segments.last.end, lessThanOrEqualTo(length)); + }); + + test('runningArcPath draws the requested arc of the outline', () { + final piece = runningArcPath(metrics, 10, 30); + final pieceMetrics = piece.computeMetrics().toList(); + // Curve metrics are approximations; a fraction of a pixel is exact enough. + expect(_length(pieceMetrics), closeTo(20, .5)); + }); +} From bd4f1437bc2d45989e1cc9acc494a60264f652e9 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 12 Nov 2026 11:15:28 +0000 Subject: [PATCH 8/9] Validate and import agent skills into versioned server storage Adds a SKILL.md bundle validator, immutable per-skill versions with content digests and deduplication, protocol requests to import, list and show skills, and the pipelines skills import/list/show commands. Imports are serialised so concurrent imports never share a version number. --- docs/skills.md | 14 +++ internal/cli/app.go | 3 + internal/cli/commands.go | 1 + internal/cli/skills.go | 126 ++++++++++++++++++++++ internal/pipeline/skills.go | 168 ++++++++++++++++++++++++++++++ internal/pipeline/skills_test.go | 98 +++++++++++++++++ internal/pipeline/store.go | 4 + internal/protocol/message.go | 12 +++ internal/protocol/skills.go | 24 +++++ internal/server/skills_test.go | 93 +++++++++++++++++ internal/server/websocket.go | 39 +++++++ internal/skills/validate.go | 173 +++++++++++++++++++++++++++++++ internal/skills/validate_test.go | 56 ++++++++++ 13 files changed, 811 insertions(+) create mode 100644 docs/skills.md create mode 100644 internal/cli/skills.go create mode 100644 internal/pipeline/skills.go create mode 100644 internal/pipeline/skills_test.go create mode 100644 internal/protocol/skills.go create mode 100644 internal/server/skills_test.go create mode 100644 internal/skills/validate.go create mode 100644 internal/skills/validate_test.go diff --git a/docs/skills.md b/docs/skills.md new file mode 100644 index 00000000..f6bbb5d6 --- /dev/null +++ b/docs/skills.md @@ -0,0 +1,14 @@ +# Skills + +`pipelines skills import FOLDER` validates a skill locally and, after confirmation, +sends its bytes to the server. A bundle contains one root `SKILL.md` with YAML +frontmatter (`name` and `description`) and may contain only `references/`, +`scripts/`, and `assets/`. Symlinks, traversal paths, nested `SKILL.md` files, +executables outside `scripts/`, and oversized bundles are rejected. Files are +fingerprinted in sorted path order with SHA-256; importing the same digest is +idempotent. The server keeps immutable versions in SQLite metadata and stores +their files below its data directory. Skills are metadata-only at this stage: +they are not executed or injected into stages or chats. + +Use `pipelines skills list` and `pipelines skills show NAME [--version N]` to +inspect imported versions. diff --git a/internal/cli/app.go b/internal/cli/app.go index efbece9e..d3e5a106 100644 --- a/internal/cli/app.go +++ b/internal/cli/app.go @@ -285,6 +285,9 @@ func parse(f *flag.FlagSet, args []string) error { } func (a App) Run(ctx context.Context, args []string) error { + if len(args) > 0 && args[0] == "skills" { + return a.skillsCommand(ctx, args[1:]) + } if len(args) > 0 && args[0] == "choose-model" { return a.chooseModel(ctx, args[1:]) } diff --git a/internal/cli/commands.go b/internal/cli/commands.go index c2a8e477..441fa9bc 100644 --- a/internal/cli/commands.go +++ b/internal/cli/commands.go @@ -2,6 +2,7 @@ package cli // Help is also the public command inventory for agents and parity checks. var usage = map[string]string{ + "skills": "skills import [--yes] | skills list | skills show [--version N]", "repair-session-export": "repair-session-export RUN_ID SEQUENCE [--json]", "provider-check": "provider-check --model PROVIDER/MODEL [--yes] [--json]", "new": "new [name] [prompt] [--template KEY] [--no-open | --json]", diff --git a/internal/cli/skills.go b/internal/cli/skills.go new file mode 100644 index 00000000..2f50f62e --- /dev/null +++ b/internal/cli/skills.go @@ -0,0 +1,126 @@ +package cli + +import ( + "context" + "flag" + "fmt" + "git.a-wan.net/alan/pipelines/internal/client" + "git.a-wan.net/alan/pipelines/internal/protocol" + "git.a-wan.net/alan/pipelines/internal/skills" +) + +func (a App) skillsCommand(ctx context.Context, args []string) error { + if len(args) < 1 { + return fmt.Errorf("usage: pipelines skills import|list|show") + } + if args[0] == "help" || args[0] == "--help" || args[0] == "-h" { + _, err := fmt.Fprintln(a.Out, "Usage: pipelines skills import [--yes] | skills list | skills show [--version N]") + return err + } + // Accept flags after the folder, matching the rest of the Pipelines CLI. + var flags, positionals []string + for i := 1; i < len(args); i++ { + if args[i] == "--yes" || args[i] == "--json" || args[i] == "-json" { + flags = append(flags, args[i]) + continue + } + if args[i] == "--url" || args[i] == "--version" { + if i+1 >= len(args) { + return fmt.Errorf("%s needs a value", args[i]) + } + flags = append(flags, args[i], args[i+1]) + i++ + continue + } + positionals = append(positionals, args[i]) + } + args = append([]string{args[0]}, append(flags, positionals...)...) + sub := args[0] + fs := flag.NewFlagSet("skills "+sub, flag.ContinueOnError) + fs.SetOutput(a.Err) + url := envOr("PIPELINES_URL", "ws://127.0.0.1:8080/connect") + yes := false + version := 0 + jsonMode := false + fs.StringVar(&url, "url", url, "Pipeline server WebSocket URL") + fs.BoolVar(&yes, "yes", false, "Confirm import without prompting") + fs.BoolVar(&jsonMode, "json", false, "Machine-readable JSON") + fs.IntVar(&version, "version", 0, "Immutable version (0 = latest)") + if err := fs.Parse(args[1:]); err != nil { + return err + } + pos := fs.Args() + if sub == "import" { + if len(pos) != 1 { + return fmt.Errorf("skills import requires a folder") + } + b, e := skills.Validate(pos[0]) + if e != nil { + return e + } + if !yes { + if e = a.confirmAction(fmt.Sprintf("Import skill %s (%d files, %d bytes, digest %s)?", b.Name, len(b.Files), b.TotalBytes, b.Digest), false); e != nil { + return e + } + } + c, e := client.Open(ctx, url) + if e != nil { + return e + } + defer c.Close() + files := make([]protocol.SkillFile, len(b.Files)) + for i, f := range b.Files { + files[i] = protocol.SkillFile{Path: f.Path, Bytes: f.Bytes} + } + r, e := c.Call(ctx, protocol.Message{Type: protocol.ImportSkill, Name: b.Name, Description: b.Description, Digest: b.Digest, SourcePath: pos[0], SkillFiles: files}) + if e != nil { + return e + } + if r.SkillVersion == nil { + return fmt.Errorf("server returned no skill version") + } + return a.outputSkill(r.SkillVersion, jsonMode) + } + if sub != "list" && sub != "show" { + return fmt.Errorf("unknown skills command %q", sub) + } + c, e := client.Open(ctx, url) + if e != nil { + return e + } + defer c.Close() + if sub == "list" { + if len(pos) != 0 { + return fmt.Errorf("skills list takes no arguments") + } + r, e := c.Call(ctx, protocol.Message{Type: protocol.ListSkills}) + if e != nil { + return e + } + if jsonMode { + return a.output(r) + } + for _, s := range r.SkillSummaries { + fmt.Fprintf(a.Out, "%s\tv%d\t%s\n", s.Name, s.LatestVersion, s.Digest) + } + return nil + } + if len(pos) != 1 { + return fmt.Errorf("skills show requires a name") + } + r, e := c.Call(ctx, protocol.Message{Type: protocol.ShowSkill, Name: pos[0], Version: version}) + if e != nil { + return e + } + if r.SkillVersion == nil { + return fmt.Errorf("server returned no skill") + } + return a.outputSkill(r.SkillVersion, jsonMode) +} +func (a App) outputSkill(s *protocol.SkillVersion, jsonMode bool) error { + if jsonMode { + return a.output(s) + } + fmt.Fprintf(a.Out, "%s v%d\t%s\n%s\n", s.Name, s.Version, s.Digest, s.SkillMD) + return nil +} diff --git a/internal/pipeline/skills.go b/internal/pipeline/skills.go new file mode 100644 index 00000000..e2f8a6fe --- /dev/null +++ b/internal/pipeline/skills.go @@ -0,0 +1,168 @@ +package pipeline + +import ( + "context" + "crypto/sha256" + "database/sql" + "encoding/hex" + "fmt" + "git.a-wan.net/alan/pipelines/internal/protocol" + "git.a-wan.net/alan/pipelines/internal/skills" + "os" + "path/filepath" + "sort" + "strings" + "sync" + "time" +) + +func (s *Store) initSkills() error { + _, err := s.db.Exec(`CREATE TABLE IF NOT EXISTS skills (name TEXT PRIMARY KEY, description TEXT NOT NULL, latest_version INTEGER NOT NULL, digest TEXT NOT NULL, imported_at TEXT NOT NULL); +CREATE TABLE IF NOT EXISTS skill_versions (name TEXT NOT NULL REFERENCES skills(name), version INTEGER NOT NULL, digest TEXT NOT NULL, source_path TEXT NOT NULL, imported_at TEXT NOT NULL, PRIMARY KEY(name,version), UNIQUE(name,digest)); +CREATE TABLE IF NOT EXISTS skill_files (name TEXT NOT NULL, version INTEGER NOT NULL, path TEXT NOT NULL, size INTEGER NOT NULL, PRIMARY KEY(name,version,path), FOREIGN KEY(name,version) REFERENCES skill_versions(name,version));`) + return err +} + +// skillImports serialises imports in this server process, so the +// deduplication check and the next-version allocation below see every +// earlier import's committed version and never hand out the same number. +var skillImports sync.Mutex + +func (s *Store) ImportSkill(ctx context.Context, name, description, digest, source string, files []protocol.SkillFile) (protocol.SkillVersion, error) { + skillImports.Lock() + defer skillImports.Unlock() + if err := skills.ValidateName(name); err != nil { + return protocol.SkillVersion{}, err + } + if digest == "" || len(files) == 0 { + return protocol.SkillVersion{}, fmt.Errorf("invalid skill bundle") + } + if len(files) > skills.MaxFiles { + return protocol.SkillVersion{}, fmt.Errorf("skill has more than %d files", skills.MaxFiles) + } + ordered := append([]protocol.SkillFile(nil), files...) + sort.Slice(ordered, func(i, j int) bool { return ordered[i].Path < ordered[j].Path }) + h := sha256.New() + total := 0 + for _, f := range ordered { + if f.Path == "" || strings.HasPrefix(f.Path, "/") || filepath.Clean(f.Path) != f.Path || strings.HasPrefix(filepath.ToSlash(f.Path), "../") || strings.Contains(f.Path, "\\") { + return protocol.SkillVersion{}, fmt.Errorf("invalid skill file path: %s", f.Path) + } + if len(f.Bytes) > skills.MaxFileBytes { + return protocol.SkillVersion{}, fmt.Errorf("file %s exceeds %d bytes", f.Path, skills.MaxFileBytes) + } + total += len(f.Bytes) + fmt.Fprintf(h, "%s\x00%d\x00", f.Path, len(f.Bytes)) + h.Write(f.Bytes) + } + if total > skills.MaxTotalBytes || hex.EncodeToString(h.Sum(nil)) != digest { + return protocol.SkillVersion{}, fmt.Errorf("skill digest or size limit is invalid") + } + var existing protocol.SkillVersion + err := s.db.QueryRowContext(ctx, `SELECT version, source_path, imported_at FROM skill_versions WHERE name=? AND digest=?`, name, digest).Scan(&existing.Version, &existing.SourcePath, &existing.ImportedAt) + if err == nil { + existing.SkillSummary = protocol.SkillSummary{Name: name, Description: description, LatestVersion: existing.Version, Digest: digest, ImportedAt: existing.ImportedAt} + existing.SkillMD, _ = s.skillMD(name, existing.Version) + existing.Manifest, _ = s.skillManifest(ctx, name, existing.Version) + return existing, nil + } + if err != sql.ErrNoRows { + return existing, err + } + var next int + _ = s.db.QueryRowContext(ctx, `SELECT COALESCE(MAX(version),0)+1 FROM skill_versions WHERE name=?`, name).Scan(&next) + now := time.Now().UTC().Format(time.RFC3339) + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return existing, err + } + if _, err = tx.ExecContext(ctx, `INSERT INTO skills(name,description,latest_version,digest,imported_at) VALUES(?,?,?,?,?) ON CONFLICT(name) DO UPDATE SET description=excluded.description,latest_version=excluded.latest_version,digest=excluded.digest,imported_at=excluded.imported_at`, name, description, next, digest, now); err != nil { + tx.Rollback() + return existing, err + } + if _, err = tx.ExecContext(ctx, `INSERT INTO skill_versions(name,version,digest,source_path,imported_at) VALUES(?,?,?,?,?)`, name, next, digest, source, now); err != nil { + tx.Rollback() + return existing, err + } + dir := filepath.Join(s.dir, "skills", name, fmt.Sprintf("v%d", next)) + if err = os.MkdirAll(dir, 0700); err != nil { + tx.Rollback() + return existing, err + } + for _, f := range files { + p := filepath.Join(dir, filepath.FromSlash(f.Path)) + if err = os.MkdirAll(filepath.Dir(p), 0700); err != nil { + tx.Rollback() + return existing, err + } + if err = os.WriteFile(p, f.Bytes, 0600); err != nil { + tx.Rollback() + return existing, err + } + if _, err = tx.ExecContext(ctx, `INSERT INTO skill_files(name,version,path,size) VALUES(?,?,?,?)`, name, next, f.Path, len(f.Bytes)); err != nil { + tx.Rollback() + return existing, err + } + } + if err = tx.Commit(); err != nil { + return existing, err + } + return s.GetSkill(ctx, name, next) +} +func (s *Store) ListSkills(ctx context.Context) ([]protocol.SkillSummary, error) { + rows, e := s.db.QueryContext(ctx, `SELECT name,description,latest_version,digest,imported_at FROM skills ORDER BY name`) + if e != nil { + return nil, e + } + defer rows.Close() + var out []protocol.SkillSummary + for rows.Next() { + var x protocol.SkillSummary + if e = rows.Scan(&x.Name, &x.Description, &x.LatestVersion, &x.Digest, &x.ImportedAt); e != nil { + return nil, e + } + out = append(out, x) + } + return out, rows.Err() +} +func (s *Store) GetSkill(ctx context.Context, name string, version int) (protocol.SkillVersion, error) { + var x protocol.SkillVersion + var desc string + if version == 0 { + if e := s.db.QueryRowContext(ctx, `SELECT description,latest_version FROM skills WHERE name=?`, name).Scan(&desc, &version); e != nil { + return x, e + } + } else if e := s.db.QueryRowContext(ctx, `SELECT description FROM skills WHERE name=?`, name).Scan(&desc); e != nil { + return x, e + } + if e := s.db.QueryRowContext(ctx, `SELECT digest,source_path,imported_at FROM skill_versions WHERE name=? AND version=?`, name, version).Scan(&x.Digest, &x.SourcePath, &x.ImportedAt); e != nil { + return x, e + } + x.Name = name + x.Description = desc + x.Version = version + x.LatestVersion = version + x.SkillMD, _ = s.skillMD(name, version) + x.Manifest, _ = s.skillManifest(ctx, name, version) + return x, nil +} +func (s *Store) skillMD(name string, v int) (string, error) { + b, e := os.ReadFile(filepath.Join(s.dir, "skills", name, fmt.Sprintf("v%d", v), "SKILL.md")) + return string(b), e +} +func (s *Store) skillManifest(ctx context.Context, name string, v int) ([]protocol.SkillFileMeta, error) { + rows, e := s.db.QueryContext(ctx, `SELECT path,size FROM skill_files WHERE name=? AND version=? ORDER BY path`, name, v) + if e != nil { + return nil, e + } + defer rows.Close() + var out []protocol.SkillFileMeta + for rows.Next() { + var x protocol.SkillFileMeta + if e = rows.Scan(&x.Path, &x.Size); e != nil { + return nil, e + } + out = append(out, x) + } + return out, rows.Err() +} diff --git a/internal/pipeline/skills_test.go b/internal/pipeline/skills_test.go new file mode 100644 index 00000000..0047328b --- /dev/null +++ b/internal/pipeline/skills_test.go @@ -0,0 +1,98 @@ +package pipeline + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "fmt" + "git.a-wan.net/alan/pipelines/internal/protocol" + "path/filepath" + "sync" + "testing" +) + +func digestSkill(files []protocol.SkillFile) string { + h := sha256.New() + for _, f := range files { + fmt.Fprintf(h, "%s\x00%d\x00", f.Path, len(f.Bytes)) + h.Write(f.Bytes) + } + return hex.EncodeToString(h.Sum(nil)) +} + +func TestSkillImportDeduplicatesAndVersions(t *testing.T) { + s, err := Open(filepath.Join(t.TempDir(), "pipelines.db")) + if err != nil { + t.Fatal(err) + } + defer s.Close() + files := []protocol.SkillFile{{Path: "SKILL.md", Bytes: []byte("---\nname: demo\ndescription: Demo\n---\n")}} + first, err := s.ImportSkill(context.Background(), "demo", "Demo", digestSkill(files), "/one", files) + if err != nil { + t.Fatal(err) + } + same, err := s.ImportSkill(context.Background(), "demo", "Demo", digestSkill(files), "/two", files) + if err != nil { + t.Fatal(err) + } + if same.Version != first.Version { + t.Fatalf("dedup version = %d, want %d", same.Version, first.Version) + } + files[0].Bytes = append(files[0].Bytes, '\n') + second, err := s.ImportSkill(context.Background(), "demo", "Demo", digestSkill(files), "/three", files) + if err != nil { + t.Fatal(err) + } + if second.Version != 2 { + t.Fatalf("new version = %d, want 2", second.Version) + } +} + +func TestSkillImportRejectsUnsafeName(t *testing.T) { + s, err := Open(filepath.Join(t.TempDir(), "pipelines.db")) + if err != nil { + t.Fatal(err) + } + defer s.Close() + files := []protocol.SkillFile{{Path: "SKILL.md", Bytes: []byte("skill")}} + if _, err := s.ImportSkill(context.Background(), "../../outside", "", digestSkill(files), "/source", files); err == nil { + t.Fatal("expected unsafe skill name to be rejected") + } +} + +func TestSkillImportConcurrentVersionsAreDistinct(t *testing.T) { + s, err := Open(filepath.Join(t.TempDir(), "pipelines.db")) + if err != nil { + t.Fatal(err) + } + defer s.Close() + const n = 8 + var wg sync.WaitGroup + versions := make([]int, n) + errs := make([]error, n) + for i := range n { + wg.Add(1) + go func() { + defer wg.Done() + files := []protocol.SkillFile{{Path: "SKILL.md", Bytes: []byte(fmt.Sprintf("---\nname: demo\ndescription: Demo %d\n---\n", i))}} + v, err := s.ImportSkill(context.Background(), "demo", "Demo", digestSkill(files), "/src", files) + versions[i], errs[i] = v.Version, err + }() + } + wg.Wait() + seen := map[int]bool{} + for i := range n { + if errs[i] != nil { + t.Fatalf("import %d: %v", i, errs[i]) + } + if seen[versions[i]] { + t.Fatalf("version %d allocated twice: %v", versions[i], versions) + } + seen[versions[i]] = true + } + for v := 1; v <= n; v++ { + if !seen[v] { + t.Fatalf("versions = %v, want 1..%d", versions, n) + } + } +} diff --git a/internal/pipeline/store.go b/internal/pipeline/store.go index ef977dce..bf838546 100644 --- a/internal/pipeline/store.go +++ b/internal/pipeline/store.go @@ -129,6 +129,10 @@ CREATE TABLE IF NOT EXISTS submissions (id INTEGER PRIMARY KEY, name TEXT NOT NU db.Close() return nil, err } + if err := s.initSkills(); err != nil { + db.Close() + return nil, err + } return s, nil } diff --git a/internal/protocol/message.go b/internal/protocol/message.go index c5236536..d4f927c0 100644 --- a/internal/protocol/message.go +++ b/internal/protocol/message.go @@ -23,6 +23,12 @@ const ( PipelineArchived = "pipeline_archived" UnarchivePipeline = "unarchive_pipeline" PipelineUnarchived = "pipeline_unarchived" + ImportSkill = "import_skill" + SkillImported = "skill_imported" + ListSkills = "list_skills" + Skills = "skills" + ShowSkill = "show_skill" + Skill = "skill" ) type Stage struct { @@ -127,6 +133,9 @@ type PipelineSummary struct { // are optional so older peers ignore them. See search.go for the per-type payloads // and the ranking/kind/bound vocabulary. type Message struct { + SkillFiles []SkillFile `json:"skill_files,omitempty"` + SkillSummaries []SkillSummary `json:"skill_summaries,omitempty"` + SkillVersion *SkillVersion `json:"skill_version,omitempty"` Storage *StorageOverview `json:"storage,omitempty"` StoragePolicy *StoragePolicy `json:"storage_policy,omitempty"` StorageCleanup *StorageCleanupResult `json:"storage_cleanup,omitempty"` @@ -154,6 +163,9 @@ type Message struct { Error string `json:"error,omitempty"` Warnings []string `json:"warnings,omitempty"` // non-blocking authoring lint for validate/submit Name string `json:"name,omitempty"` + Description string `json:"description,omitempty"` + Digest string `json:"digest,omitempty"` + SourcePath string `json:"source_path,omitempty"` Source string `json:"source,omitempty"` Title string `json:"title,omitempty"` Version int `json:"version,omitempty"` diff --git a/internal/protocol/skills.go b/internal/protocol/skills.go new file mode 100644 index 00000000..c7ea2939 --- /dev/null +++ b/internal/protocol/skills.go @@ -0,0 +1,24 @@ +package protocol + +type SkillFile struct { + Path string `json:"path"` + Bytes []byte `json:"bytes"` +} +type SkillSummary struct { + Name string `json:"name"` + Description string `json:"description"` + LatestVersion int `json:"latest_version"` + Digest string `json:"digest"` + ImportedAt string `json:"imported_at"` +} +type SkillVersion struct { + SkillSummary + Version int `json:"version"` + SourcePath string `json:"source_path"` + Manifest []SkillFileMeta `json:"manifest"` + SkillMD string `json:"skill_md"` +} +type SkillFileMeta struct { + Path string `json:"path"` + Size int64 `json:"size"` +} diff --git a/internal/server/skills_test.go b/internal/server/skills_test.go new file mode 100644 index 00000000..8279059c --- /dev/null +++ b/internal/server/skills_test.go @@ -0,0 +1,93 @@ +package server + +import ( + "context" + "net/http/httptest" + "os" + "path/filepath" + "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" + "git.a-wan.net/alan/pipelines/internal/skills" +) + +func TestSkillWebSocketHandlers(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + store, err := pipeline.Open(filepath.Join(t.TempDir(), "skills.db")) + if err != nil { + t.Fatal(err) + } + defer store.Close() + handler := Handler(ctx, store) + srv := httptest.NewServer(handler) + defer srv.Close() + defer func() { cancel(); WaitRuns(handler) }() + + conn, _, err := websocket.Dial(ctx, "ws"+strings.TrimPrefix(srv.URL, "http")+"/connect", nil) + if err != nil { + t.Fatal(err) + } + defer conn.CloseNow() + var welcome protocol.Message + if err := wsjson.Read(ctx, conn, &welcome); err != nil { + t.Fatal(err) + } + + dir := t.TempDir() + if err := writeSkillFixture(dir); err != nil { + t.Fatal(err) + } + bundle, err := skills.Validate(dir) + if err != nil { + t.Fatal(err) + } + files := make([]protocol.SkillFile, len(bundle.Files)) + for i, file := range bundle.Files { + files[i] = protocol.SkillFile{Path: file.Path, Bytes: file.Bytes} + } + request := protocol.Message{Type: protocol.ImportSkill, ID: "import", Name: bundle.Name, Description: bundle.Description, Digest: bundle.Digest, SourcePath: dir, SkillFiles: files} + response := skillRequest(t, ctx, conn, request) + if response.Type != protocol.SkillImported || response.SkillVersion == nil || response.SkillVersion.Version != 1 { + t.Fatalf("import response = %+v", response) + } + + response = skillRequest(t, ctx, conn, protocol.Message{Type: protocol.ListSkills, ID: "list"}) + if response.Type != protocol.Skills || len(response.SkillSummaries) != 1 || response.SkillSummaries[0].Name != bundle.Name { + t.Fatalf("list response = %+v", response) + } + response = skillRequest(t, ctx, conn, protocol.Message{Type: protocol.ShowSkill, ID: "show", Name: bundle.Name}) + if response.Type != protocol.Skill || response.SkillVersion == nil || response.SkillVersion.SkillMD == "" { + t.Fatalf("show response = %+v", response) + } + + response = skillRequest(t, ctx, conn, protocol.Message{Type: protocol.ImportSkill, ID: "bad", Name: bundle.Name, SourcePath: dir, Digest: bundle.Digest, SkillFiles: []protocol.SkillFile{{Path: "../escape", Bytes: []byte("x")}}}) + if response.Type != protocol.Error || response.Error == "" { + t.Fatalf("invalid import response = %+v", response) + } +} + +func skillRequest(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 response protocol.Message + if err := wsjson.Read(ctx, conn, &response); err != nil { + t.Fatal(err) + } + if response.ID != request.ID { + t.Fatalf("response ID = %q, want %q", response.ID, request.ID) + } + return response +} + +func writeSkillFixture(dir string) error { + return os.WriteFile(filepath.Join(dir, "SKILL.md"), []byte("---\nname: websocket-skill\ndescription: Handler test\n---\n\nDo not execute this.\n"), 0600) +} diff --git a/internal/server/websocket.go b/internal/server/websocket.go index 2fa57fe8..74f70ed7 100644 --- a/internal/server/websocket.go +++ b/internal/server/websocket.go @@ -461,6 +461,45 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin } else { response.Pipelines = items } + } else if request.Type == protocol.ImportSkill && len(stores) > 0 { + response.Type = protocol.SkillImported + if len(request.SkillFiles) == 0 || request.Name == "" || request.SourcePath == "" { + response.Type = protocol.Error + response.Error = "skill import requires name, source path and files" + } else { + for _, f := range request.SkillFiles { + if f.Path == "" || strings.HasPrefix(f.Path, "/") || strings.Contains(f.Path, "..") { + response.Type = protocol.Error + response.Error = "invalid skill file path" + break + } + } + if response.Type != protocol.Error { + var skill protocol.SkillVersion + skill, err = stores[0].ImportSkill(ctx, request.Name, request.Description, request.Digest, request.SourcePath, request.SkillFiles) + response.SkillVersion = &skill + } + if err != nil { + response.Type = protocol.Error + response.Error = err.Error() + } + } + } else if request.Type == protocol.ListSkills && len(stores) > 0 { + response.Type = protocol.Skills + response.SkillSummaries, err = stores[0].ListSkills(ctx) + if err != nil { + response.Type = protocol.Error + response.Error = err.Error() + } + } else if request.Type == protocol.ShowSkill && len(stores) > 0 { + response.Type = protocol.Skill + var skill protocol.SkillVersion + skill, err = stores[0].GetSkill(ctx, request.Name, request.Version) + response.SkillVersion = &skill + if err != nil { + response.Type = protocol.Error + response.Error = err.Error() + } } else if (request.Type == protocol.ArchivePipeline || request.Type == protocol.UnarchivePipeline) && len(stores) > 0 { detail, err := archivePipeline(ctx, stores[0], request) response.Detail = detail diff --git a/internal/skills/validate.go b/internal/skills/validate.go new file mode 100644 index 00000000..06673b2c --- /dev/null +++ b/internal/skills/validate.go @@ -0,0 +1,173 @@ +// Package skills validates and fingerprints Claude/Codex/OpenCode/Pi skill bundles. +package skills + +import ( + "crypto/sha256" + "encoding/hex" + "fmt" + "io/fs" + "os" + "path/filepath" + "regexp" + "sort" + "strings" +) + +const ( + MaxFiles = 200 + MaxTotalBytes = 5 * 1024 * 1024 + MaxFileBytes = 1024 * 1024 +) + +var slug = regexp.MustCompile(`^[a-z0-9]+(?:-[a-z0-9]+)*$`) + +// ValidateName checks the server-facing skill name before it is used in a +// filesystem path. +func ValidateName(name string) error { + if !slug.MatchString(name) { + return fmt.Errorf("skill name must be a lowercase slug") + } + return nil +} + +type File struct { + Path string + Bytes []byte +} +type Bundle struct { + Name, Description, Digest string + Files []File + TotalBytes int64 +} + +func Validate(root string) (Bundle, error) { + root, err := filepath.Abs(root) + if err != nil { + return Bundle{}, err + } + st, err := os.Lstat(root) + if err != nil { + return Bundle{}, err + } + if st.Mode()&os.ModeSymlink != 0 { + return Bundle{}, fmt.Errorf("symlinks are not allowed: %s", root) + } + if !st.IsDir() { + return Bundle{}, fmt.Errorf("skill path is not a directory") + } + var files []File + err = filepath.WalkDir(root, func(path string, d fs.DirEntry, walkErr error) error { + if walkErr != nil { + return walkErr + } + rel, e := filepath.Rel(root, path) + if e != nil { + return e + } + if rel == "." { + return nil + } + if d.Type()&os.ModeSymlink != 0 { + return fmt.Errorf("symlinks are not allowed: %s", rel) + } + if d.IsDir() { + if filepath.Dir(rel) == "." && rel != "references" && rel != "scripts" && rel != "assets" { + return fmt.Errorf("unsupported top-level directory: %s", rel) + } + return nil + } + clean := filepath.ToSlash(rel) + if filepath.Dir(rel) == "." && clean != "SKILL.md" { + return fmt.Errorf("unsupported top-level file: %s", clean) + } + if filepath.IsAbs(rel) || strings.HasPrefix(clean, "../") || clean == ".." { + return fmt.Errorf("invalid path: %s", rel) + } + if filepath.Base(rel) == "SKILL.md" && filepath.Dir(rel) != "." { + return fmt.Errorf("nested SKILL.md is not allowed: %s", rel) + } + if len(files) >= MaxFiles { + return fmt.Errorf("skill has more than %d files", MaxFiles) + } + info, e := d.Info() + if e != nil { + return e + } + if info.Size() > MaxFileBytes { + return fmt.Errorf("file %s exceeds %d bytes", clean, MaxFileBytes) + } + b, e := os.ReadFile(path) + if e != nil { + return e + } + if info.Mode()&0111 != 0 && !strings.HasPrefix(clean, "scripts/") { + return fmt.Errorf("executable outside scripts/: %s", clean) + } + files = append(files, File{Path: clean, Bytes: b}) + return nil + }) + if err != nil { + return Bundle{}, err + } + sort.Slice(files, func(i, j int) bool { return files[i].Path < files[j].Path }) + var md []byte + for _, f := range files { + if f.Path == "SKILL.md" { + md = f.Bytes + break + } + } + if md == nil { + return Bundle{}, fmt.Errorf("skill must contain exactly one top-level SKILL.md") + } + name, desc, err := frontmatter(md) + if err != nil { + return Bundle{}, err + } + if err := ValidateName(name); err != nil { + return Bundle{}, fmt.Errorf("frontmatter name must be a lowercase slug") + } + var total int64 + h := sha256.New() + for _, f := range files { + total += int64(len(f.Bytes)) + fmt.Fprintf(h, "%s\x00%d\x00", f.Path, len(f.Bytes)) + h.Write(f.Bytes) + } + if total > MaxTotalBytes { + return Bundle{}, fmt.Errorf("skill exceeds %d total bytes", MaxTotalBytes) + } + return Bundle{Name: name, Description: desc, Digest: hex.EncodeToString(h.Sum(nil)), Files: files, TotalBytes: total}, nil +} + +func frontmatter(b []byte) (string, string, error) { + s := strings.ReplaceAll(string(b), "\r\n", "\n") + lines := strings.Split(s, "\n") + if len(lines) < 3 || strings.TrimSpace(lines[0]) != "---" { + return "", "", fmt.Errorf("SKILL.md must begin with YAML frontmatter") + } + name, desc := "", "" + end := -1 + for i := 1; i < len(lines); i++ { + if strings.TrimSpace(lines[i]) == "---" { + end = i + break + } + k, v, ok := strings.Cut(lines[i], ":") + if !ok { + continue + } + v = strings.TrimSpace(v) + v = strings.Trim(v, "\"'") + switch strings.TrimSpace(k) { + case "name": + name = v + case "description": + desc = v + } + } + if end < 0 || name == "" || desc == "" { + return "", "", fmt.Errorf("SKILL.md frontmatter requires name and description") + } + return name, desc, nil +} diff --git a/internal/skills/validate_test.go b/internal/skills/validate_test.go new file mode 100644 index 00000000..c98cb34f --- /dev/null +++ b/internal/skills/validate_test.go @@ -0,0 +1,56 @@ +package skills + +import ( + "os" + "path/filepath" + "testing" +) + +func TestValidateDigestStable(t *testing.T) { + for _, order := range [][]string{{"b.txt", "a.txt"}, {"a.txt", "b.txt"}} { + d := t.TempDir() + os.WriteFile(filepath.Join(d, "SKILL.md"), []byte("---\nname: demo-skill\ndescription: Demo\n---\n"), 0600) + os.Mkdir(filepath.Join(d, "references"), 0700) + for _, n := range order { + os.WriteFile(filepath.Join(d, "references", n), []byte(n), 0600) + } + b, e := Validate(d) + if e != nil { + t.Fatal(e) + } + if order[0] == "b.txt" { + t.Setenv("DIGEST", b.Digest) + } else if os.Getenv("DIGEST") != b.Digest { + t.Fatalf("digest changed") + } + } +} +func TestValidateRejectsNested(t *testing.T) { + d := t.TempDir() + os.WriteFile(filepath.Join(d, "SKILL.md"), []byte("---\nname: x\ndescription: y\n---"), 0600) + os.Mkdir(filepath.Join(d, "references"), 0700) + os.WriteFile(filepath.Join(d, "references", "SKILL.md"), []byte("x"), 0600) + if _, e := Validate(d); e == nil { + t.Fatal("expected nested rejection") + } +} + +func TestValidateNameRejectsTraversal(t *testing.T) { + for _, name := range []string{"../outside", "../../outside", "Upper", "has space", ""} { + if err := ValidateName(name); err == nil { + t.Errorf("ValidateName(%q) accepted unsafe name", name) + } + } +} + +func TestValidateRejectsSymlinkRoot(t *testing.T) { + target := t.TempDir() + os.WriteFile(filepath.Join(target, "SKILL.md"), []byte("---\nname: demo\ndescription: Demo\n---\n"), 0600) + link := filepath.Join(t.TempDir(), "skill-link") + if err := os.Symlink(target, link); err != nil { + t.Skipf("symlinks unavailable: %v", err) + } + if _, err := Validate(link); err == nil { + t.Fatal("expected symlink root rejection") + } +} From a6221caa6e4b901f5df0314f99998f4ab1870adc Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 12 Nov 2026 11:16:13 +0000 Subject: [PATCH 9/9] Notify only on unexpected run failures Classify each failed run from its terminal visit: a stage that deliberately routes to #failure with a reason is expected and does not notify or ask for attention; errors, budgets, timeouts, interruptions and exhausted visit limits (from the recorded control evidence) are unexpected and always notify. --- .../attention/domain/attention_models.dart | 8 +++- app/lib/features/runs/domain/run_events.dart | 5 ++ .../attention/attention_models_test.dart | 26 ++++++++++ .../author/skill/references/notifications.md | 7 ++- .../run_notification_transition_test.go | 48 +++++++++++++++++++ internal/pipeline/run_notifications.go | 15 ++++-- internal/pipeline/runs.go | 4 +- internal/pipeline/runs_mutate.go | 44 +++++++++++++++-- internal/pipeline/runs_schema.go | 9 +++- internal/protocol/runevents.go | 2 + internal/protocol/runs.go | 2 + internal/server/notify.go | 11 +++++ internal/server/notify_test.go | 20 ++++---- internal/server/runevents.go | 2 + internal/server/runner.go | 2 + 15 files changed, 184 insertions(+), 21 deletions(-) diff --git a/app/lib/features/attention/domain/attention_models.dart b/app/lib/features/attention/domain/attention_models.dart index 6381b86d..948a199c 100644 --- a/app/lib/features/attention/domain/attention_models.dart +++ b/app/lib/features/attention/domain/attention_models.dart @@ -65,6 +65,9 @@ AttentionKind? attentionKindOf(dynamic status) { /// onto a waiting run must not hide a genuine human decision. AttentionKind? attentionKindForRun(JsonMap run) { final kind = attentionKindOf(run['status']); + if (kind == AttentionKind.failed && _word(run['failure_kind']) == 'expected') { + return null; + } if (kind != AttentionKind.decision) return kind; if (_positive(run['export_pending_sequence'])) return null; return kind; @@ -77,7 +80,10 @@ String attentionKey(int runId, AttentionKind kind) => '$runId:${kind.wireName}'; /// shows the server's own diagnostic when it recorded one. String attentionDetail(AttentionKind kind, JsonMap run) { if (kind == AttentionKind.decision) return 'Waiting for your decision'; - final diagnostic = '${run['diagnostic'] ?? ''}'.trim(); + final failureReason = '${run['failure_reason'] ?? ''}'.trim(); + final diagnostic = failureReason.isNotEmpty + ? failureReason + : '${run['diagnostic'] ?? ''}'.trim(); return diagnostic.isNotEmpty ? diagnostic : 'Run failed'; } diff --git a/app/lib/features/runs/domain/run_events.dart b/app/lib/features/runs/domain/run_events.dart index 2e066781..f5ff2664 100644 --- a/app/lib/features/runs/domain/run_events.dart +++ b/app/lib/features/runs/domain/run_events.dart @@ -119,6 +119,9 @@ JsonMap _mergeRunFields(JsonMap current, JsonMap frame) { for (final key in ['outcome', 'current_stage', 'created_at', 'finished_at']) { if (!_blank(frame[key])) merged[key] = frame[key]; } + for (final key in ['failure_kind', 'failure_reason']) { + if (frame[key] != null) merged[key] = frame[key]; + } // Snapshot and terminal frames carry the measured size; others omit it. if (frame['size_bytes'] is num) merged['size_bytes'] = frame['size_bytes']; final oldExport = _positiveInt(current['export_pending_sequence']); @@ -168,6 +171,8 @@ JsonMap? newRunSummaryFromFrame(JsonMap frame) { 'finished_at': frame['finished_at'] ?? '', 'outcome': frame['outcome'] ?? '', 'current_stage': frame['current_stage'] ?? '', + 'failure_kind': frame['failure_kind'] ?? '', + 'failure_reason': frame['failure_reason'] ?? '', 'resource_wait': frame['resource_wait'], 'cancel_requested': frame['cancel_requested'] == true, 'cleanup_unconfirmed': frame['cleanup_unconfirmed'] == true, diff --git a/app/test/features/attention/attention_models_test.dart b/app/test/features/attention/attention_models_test.dart index bc3ba0c8..e2045bbc 100644 --- a/app/test/features/attention/attention_models_test.dart +++ b/app/test/features/attention/attention_models_test.dart @@ -98,6 +98,12 @@ void main() { ), AttentionKind.failed, ); + expect( + attentionKindForRun( + run({'status': 'failed', 'failure_kind': 'expected'}), + ), + isNull, + ); }); test( @@ -151,6 +157,26 @@ void main() { attentionDetail(AttentionKind.failed, run({'diagnostic': null})), 'Run failed', ); + expect( + attentionDetail( + AttentionKind.failed, + run({ + 'diagnostic': 'generic diagnostic', + 'failure_reason': 'Provider authentication failed', + }), + ), + 'Provider authentication failed', + ); + expect( + attentionDetail( + AttentionKind.failed, + run({ + 'diagnostic': 'generic diagnostic', + 'failure_reason': ' ', + }), + ), + 'generic diagnostic', + ); }, ); diff --git a/internal/author/skill/references/notifications.md b/internal/author/skill/references/notifications.md index 1250a01e..0cc88bad 100644 --- a/internal/author/skill/references/notifications.md +++ b/internal/author/skill/references/notifications.md @@ -94,8 +94,11 @@ produce the required three strings, so adding this stage alone cannot cover it. Independently of any `notify` block, the server publishes one run-level attention notification to the same already-configured `system` destination when a run needs a person: when it enters `waiting` (a human stage asked for a decision), or when it -fails or is interrupted. An auto-mode run always notifies for failure/interruption; -a successful auto-mode run notifies only when the operator enables `run_finished`. +has an unexpected failure or interruption. A deliberate route to `#failure` with +its reason is recorded as an expected failure: it remains in Runs but does not +notify or appear in Needs you. Explicit `run_finished`/`on` completion notifications +still include expected failures. An auto-mode run always notifies unexpected +failure/interruption; a successful auto-mode run notifies only when the operator enables `run_finished`. Runs marked `on` notify at completion, while `off` disables these notifications. Queued and running runs send nothing. You do not author these; they are the operator default, so a run you never wired still reaches the operator. diff --git a/internal/pipeline/run_notification_transition_test.go b/internal/pipeline/run_notification_transition_test.go index b6d978ec..77eb0bc4 100644 --- a/internal/pipeline/run_notification_transition_test.go +++ b/internal/pipeline/run_notification_transition_test.go @@ -176,6 +176,54 @@ func TestRunNotificationTransitionModesAndCoverage(t *testing.T) { } } +func TestFailedRunNotificationClassifiesExpectedAndUnexpectedCauses(t *testing.T) { + tests := []struct { + name, status, outcome, diagnostic string + expectedKind string + notify bool + completeStep bool + control *protocol.ControlEvidence + }{ + {name: "blocked with reason", status: "failed", outcome: "blocked", diagnostic: "Blocked: approval is required", expectedKind: "expected", notify: false, completeStep: true}, + {name: "harness error", status: "failed", outcome: "error", diagnostic: "agent exception: process exited", expectedKind: "unexpected", notify: true}, + {name: "budget exceeded", status: "failed", outcome: "error", diagnostic: "token budget exceeded", expectedKind: "unexpected", notify: true}, + {name: "timeout", status: "failed", outcome: "error", diagnostic: "stage timed out", expectedKind: "unexpected", notify: true}, + {name: "interrupted", status: "interrupted", outcome: "", diagnostic: "Server stopped; run was not resumed", expectedKind: "unexpected", notify: true}, + {name: "visit limit", status: "failed", outcome: "error", diagnostic: "stopped stage after 10 visits", expectedKind: "unexpected", notify: true}, + {name: "blocked reason mentions stopping", status: "failed", outcome: "blocked", diagnostic: "Blocked: stopped until approval", expectedKind: "expected", notify: false, completeStep: true}, + {name: "visit limit from control evidence", status: "failed", outcome: "rejected", diagnostic: "Pipelines stopped review after 3 visits on outcome rejected", expectedKind: "unexpected", notify: true, completeStep: true, control: &protocol.ControlEvidence{Visit: 3, MaxVisits: 3, LimitReached: true}}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + ctx := context.Background() + s, id := notificationTransitionRun(t, filepath.Join(t.TempDir(), "classification.db"), "auto") + defer s.Close() + if test.completeStep { + if err := s.FinishStep(ctx, id, protocol.RunStep{Sequence: 1, Stage: "gate", Status: "completed", Outcome: test.outcome, Target: protocol.FailureEnd, Diagnostic: test.diagnostic, Control: test.control}); err != nil { + t.Fatal(err) + } + } + if err := s.FinishRun(ctx, id, test.status, test.outcome, test.diagnostic, nil); err != nil { + t.Fatal(err) + } + got, err := s.GetRun(ctx, id) + if err != nil { + t.Fatal(err) + } + if got.FailureKind != test.expectedKind || got.FailureReason != test.diagnostic { + t.Fatalf("classification: kind=%q reason=%q, want %q/%q", got.FailureKind, got.FailureReason, test.expectedKind, test.diagnostic) + } + ns, err := s.RunNotifications(ctx, id) + if err != nil { + t.Fatal(err) + } + if (len(ns) != 0) != test.notify { + t.Fatalf("notifications=%+v, want notify=%v", ns, test.notify) + } + }) + } +} + func TestWaitingNotificationStageAndWorkerShareLease(t *testing.T) { ctx := context.Background() s, id := notificationTransitionRun(t, filepath.Join(t.TempDir(), "lease.db"), "on") diff --git a/internal/pipeline/run_notifications.go b/internal/pipeline/run_notifications.go index e9973a2f..0b3201aa 100644 --- a/internal/pipeline/run_notifications.go +++ b/internal/pipeline/run_notifications.go @@ -26,12 +26,12 @@ type RunNotification struct { // enqueueRunTransitionNotification must share the state mutation's transaction. // Read the committed-to-be state, not a runner's proposed outcome or identity. func enqueueRunTransitionNotification(ctx context.Context, tx *sql.Tx, id int64) error { - var mode, status, name, stage, diagnostic, graphJSON string + var mode, status, name, stage, diagnostic, failureKind, graphJSON string var sequence int - if err := tx.QueryRowContext(ctx, `SELECT r.notify_mode,r.status,p.name,r.current_stage,r.diagnostic, + if err := tx.QueryRowContext(ctx, `SELECT r.notify_mode,r.status,p.name,r.current_stage,r.diagnostic,r.failure_kind, COALESCE((SELECT MAX(sequence) FROM run_steps WHERE run_id=r.id),0),v.graph_json FROM pipeline_runs r JOIN pipelines p ON p.id=r.pipeline_id -JOIN pipeline_versions v ON v.pipeline_id=r.pipeline_id AND v.version=r.version WHERE r.id=?`, id).Scan(&mode, &status, &name, &stage, &diagnostic, &sequence, &graphJSON); err != nil { + JOIN pipeline_versions v ON v.pipeline_id=r.pipeline_id AND v.version=r.version WHERE r.id=?`, id).Scan(&mode, &status, &name, &stage, &diagnostic, &failureKind, &sequence, &graphJSON); err != nil { return err } if mode == "off" { @@ -43,6 +43,15 @@ JOIN pipeline_versions v ON v.pipeline_id=r.pipeline_id AND v.version=r.version title = "Run needs your decision" body = "waiting for a human decision" case "failed", "interrupted", "succeeded": + if status == "failed" && failureKind == "expected" && mode != "on" { + settings, err := readNotificationSettings(ctx, tx) + if err != nil { + return err + } + if !settings.RunFinished { + return nil + } + } // Successful runs notify only for runs marked "on", unless the operator // opted into every run end via run_finished, read in this transaction. if status == "succeeded" && mode != "on" { diff --git a/internal/pipeline/runs.go b/internal/pipeline/runs.go index 87a08e20..17ccb1e2 100644 --- a/internal/pipeline/runs.go +++ b/internal/pipeline/runs.go @@ -20,7 +20,7 @@ const runFrom = `FROM pipeline_runs r JOIN pipelines p ON p.id=r.pipeline_id` const runStamps = `strftime('%Y-%m-%dT%H:%M:%SZ',r.created_at),COALESCE(strftime('%Y-%m-%dT%H:%M:%SZ',r.finished_at),'')` const runSelect = `SELECT r.id,r.pipeline_id,p.name,r.version,v.content_hash,r.status,r.outcome,r.current_stage, -` + runStamps + `,r.diagnostic, +` + runStamps + `,r.diagnostic,r.failure_kind,r.failure_reason, CASE WHEN r.status='succeeded' THEN r.output_json ELSE COALESCE((SELECT output_json FROM run_steps WHERE run_id=r.id AND status='completed' ORDER BY sequence DESC LIMIT 1),'{}') END, (SELECT COUNT(*) FROM run_steps WHERE run_id=r.id AND status='completed'),r.workspace,r.title,r.model,r.stage_models,r.notify_mode,r.cancel_requested,r.cleanup_unconfirmed,r.output_format, CASE WHEN r.status='waiting' THEN COALESCE((SELECT sequence FROM session_export_gates WHERE run_id=r.id),0) ELSE 0 END, @@ -32,7 +32,7 @@ MAX(r.size_bytes,0) func scanRun(row interface{ Scan(...any) error }, r *protocol.RunSummary) error { var output, stageModels string - if err := row.Scan(&r.ID, &r.PipelineID, &r.Name, &r.Version, &r.ContentHash, &r.Status, &r.Outcome, &r.CurrentStage, &r.CreatedAt, &r.FinishedAt, &r.Diagnostic, &output, &r.CompletedSteps, &r.Workspace, &r.Title, &r.Model, &stageModels, &r.NotifyMode, &r.CancelRequested, &r.CleanupUnconfirmed, &r.OutputFormat, &r.ExportPendingSequence, &r.Scheduled, &r.ScheduleID, &r.ScheduleName, &r.SizeBytes); err != nil { + if err := row.Scan(&r.ID, &r.PipelineID, &r.Name, &r.Version, &r.ContentHash, &r.Status, &r.Outcome, &r.CurrentStage, &r.CreatedAt, &r.FinishedAt, &r.Diagnostic, &r.FailureKind, &r.FailureReason, &output, &r.CompletedSteps, &r.Workspace, &r.Title, &r.Model, &stageModels, &r.NotifyMode, &r.CancelRequested, &r.CleanupUnconfirmed, &r.OutputFormat, &r.ExportPendingSequence, &r.Scheduled, &r.ScheduleID, &r.ScheduleName, &r.SizeBytes); err != nil { return err } if stageModels != "" && stageModels != "{}" { diff --git a/internal/pipeline/runs_mutate.go b/internal/pipeline/runs_mutate.go index 80b8fb62..cefe4e2d 100644 --- a/internal/pipeline/runs_mutate.go +++ b/internal/pipeline/runs_mutate.go @@ -385,12 +385,15 @@ func (s *Store) FinishRun(ctx context.Context, id int64, status, outcome, diagno return err } defer tx.Rollback() + failureKind, failureReason := classifyRunFailure(ctx, tx, id, status, diagnostic) if err := affected(tx.ExecContext(ctx, `UPDATE pipeline_runs SET status=CASE WHEN cancel_requested=1 THEN 'canceled' ELSE ? END, outcome=CASE WHEN cancel_requested=1 THEN '' ELSE ? END, -diagnostic=CASE WHEN cancel_requested=1 THEN 'Canceled by operator; execution stopped' ELSE ? END, -output_json=?,finished_at=CURRENT_TIMESTAMP WHERE id=? AND status IN ('queued','running') AND cleanup_unconfirmed=0 -AND NOT EXISTS(SELECT 1 FROM run_steps WHERE run_id=pipeline_runs.id AND agent_active=1)`, status, outcome, diagnostic, string(data), id)); err != nil { + diagnostic=CASE WHEN cancel_requested=1 THEN 'Canceled by operator; execution stopped' ELSE ? END, + failure_kind=CASE WHEN cancel_requested=1 THEN '' ELSE ? END, + failure_reason=CASE WHEN cancel_requested=1 THEN '' ELSE ? END, + output_json=?,finished_at=CURRENT_TIMESTAMP WHERE id=? AND status IN ('queued','running') AND cleanup_unconfirmed=0 + AND NOT EXISTS(SELECT 1 FROM run_steps WHERE run_id=pipeline_runs.id AND agent_active=1)`, status, outcome, diagnostic, failureKind, failureReason, string(data), id)); err != nil { return err } if err := enqueueRunTransitionNotification(ctx, tx, id); err != nil { @@ -404,6 +407,41 @@ AND NOT EXISTS(SELECT 1 FROM run_steps WHERE run_id=pipeline_runs.id AND agent_a return tx.Commit() } +// classifyRunFailure uses the durable terminal visit rather than an error string +// alone. A completed visit that deliberately routes to #failure is expected; +// runtime failures, limits and interruptions require operator attention. +func classifyRunFailure(ctx context.Context, tx *sql.Tx, id int64, status, diagnostic string) (string, string) { + if status == "interrupted" { + return "unexpected", diagnostic + } + if status != "failed" { + return "", "" + } + var sequence int64 + var stepStatus, outcome, target, stepDiagnostic string + err := tx.QueryRowContext(ctx, `SELECT sequence,status,outcome,target,diagnostic FROM run_steps WHERE run_id=? ORDER BY sequence DESC LIMIT 1`, id).Scan(&sequence, &stepStatus, &outcome, &target, &stepDiagnostic) + reason := strings.TrimSpace(diagnostic) + if reason == "" { + reason = strings.TrimSpace(stepDiagnostic) + } + if err == nil && target == protocol.FailureEnd && stepStatus == "completed" && outcome != "error" && reason != "" && !stepLimitReached(ctx, tx, id, sequence) { + return "expected", reason + } + return "unexpected", reason +} + +// stepLimitReached reports whether the runner, not the stage, routed the visit +// to #failure because the stage exhausted its visit limit (the recorded control +// evidence), so a stage reason that merely mentions stopping stays expected. +func stepLimitReached(ctx context.Context, tx *sql.Tx, id, sequence int64) bool { + var data string + if tx.QueryRowContext(ctx, `SELECT evidence_json FROM step_control WHERE run_id=? AND sequence=?`, id, sequence).Scan(&data) != nil { + return false + } + var control protocol.ControlEvidence + return json.Unmarshal([]byte(data), &control) == nil && control.LimitReached +} + // SetRunEnvironment records the directory environment a run resolved (names // and files only). A resumed run records its latest resolution. func (s *Store) SetRunEnvironment(ctx context.Context, id int64, environment *protocol.RunEnvironment) error { diff --git a/internal/pipeline/runs_schema.go b/internal/pipeline/runs_schema.go index de0ff3b7..900ad830 100644 --- a/internal/pipeline/runs_schema.go +++ b/internal/pipeline/runs_schema.go @@ -79,6 +79,11 @@ CREATE TABLE IF NOT EXISTS retry_checkpoints ( if err := s.addColumnIfMissing("pipeline_runs", "environment_json", "TEXT NOT NULL DEFAULT ''"); err != nil { return err } + for _, column := range []string{"failure_kind", "failure_reason"} { + if err := s.addColumnIfMissing("pipeline_runs", column, "TEXT NOT NULL DEFAULT ''"); err != nil { + return err + } + } if err := s.dropResourceSchema(); err != nil { return err } @@ -239,11 +244,11 @@ func (s *Store) RecoverRunsKeeping(ctx context.Context, keep map[int64]bool, rea if _, err := tx.ExecContext(ctx, "UPDATE run_steps SET diagnostic=? WHERE run_id=? AND status='interrupted' AND sequence=(SELECT MAX(sequence) FROM run_steps WHERE run_id=?)", "Server restarted; "+reason, id, id); err != nil { return err } - if _, err := tx.ExecContext(ctx, "UPDATE pipeline_runs SET status='interrupted',diagnostic=?,finished_at=CURRENT_TIMESTAMP WHERE id=? AND status IN ('queued','running') AND cancel_requested=0 AND cleanup_unconfirmed=0", "Server restarted; "+reason+"; run was not resumed", id); err != nil { + if _, err := tx.ExecContext(ctx, "UPDATE pipeline_runs SET status='interrupted',diagnostic=?,failure_kind='unexpected',failure_reason=?,finished_at=CURRENT_TIMESTAMP WHERE id=? AND status IN ('queued','running') AND cancel_requested=0 AND cleanup_unconfirmed=0", "Server restarted; "+reason+"; run was not resumed", "Server restarted; "+reason+"; run was not resumed", id); err != nil { return err } } - if _, err := tx.ExecContext(ctx, "UPDATE pipeline_runs SET status=CASE WHEN cancel_requested=1 THEN 'canceled' ELSE 'interrupted' END,diagnostic='Server stopped; owned sessions stopped; run was not resumed',finished_at=CURRENT_TIMESTAMP WHERE status IN ('queued','running') AND status<>? AND cleanup_unconfirmed=0"+runFilter, append([]any{protocol.RunStatusWaiting}, keptArgs...)...); err != nil { + if _, err := tx.ExecContext(ctx, "UPDATE pipeline_runs SET status=CASE WHEN cancel_requested=1 THEN 'canceled' ELSE 'interrupted' END,diagnostic='Server stopped; owned sessions stopped; run was not resumed',failure_kind=CASE WHEN cancel_requested=1 THEN '' ELSE 'unexpected' END,failure_reason=CASE WHEN cancel_requested=1 THEN '' ELSE 'Server stopped; owned sessions stopped; run was not resumed' END,finished_at=CURRENT_TIMESTAMP WHERE status IN ('queued','running') AND status<>? AND cleanup_unconfirmed=0"+runFilter, append([]any{protocol.RunStatusWaiting}, keptArgs...)...); err != nil { return err } // An export checkpoint is a paused handoff, not an interrupted model call. diff --git a/internal/protocol/runevents.go b/internal/protocol/runevents.go index 55324a5f..d5915216 100644 --- a/internal/protocol/runevents.go +++ b/internal/protocol/runevents.go @@ -54,6 +54,8 @@ type RunEventFrame struct { CompletedSteps int `json:"completed_steps,omitempty"` CreatedAt string `json:"created_at,omitempty"` FinishedAt string `json:"finished_at,omitempty"` + FailureKind string `json:"failure_kind,omitempty"` + FailureReason string `json:"failure_reason,omitempty"` // Artifacts is the number of files recorded for the referenced step, so a // client can surface artifact capture without reading the step. Artifacts int `json:"artifacts,omitempty"` diff --git a/internal/protocol/runs.go b/internal/protocol/runs.go index a1726d0b..96a65c5c 100644 --- a/internal/protocol/runs.go +++ b/internal/protocol/runs.go @@ -187,6 +187,8 @@ type RunSummary struct { CreatedAt string `json:"created_at"` FinishedAt string `json:"finished_at"` Diagnostic string `json:"diagnostic"` + FailureKind string `json:"failure_kind,omitempty"` + FailureReason string `json:"failure_reason,omitempty"` ResultPreview string `json:"result_preview,omitempty"` CompletedSteps int `json:"completed_steps"` // Model and StageModels are the launch-time overrides this run records so it diff --git a/internal/server/notify.go b/internal/server/notify.go index 8e7daf64..ae99ec82 100644 --- a/internal/server/notify.go +++ b/internal/server/notify.go @@ -207,6 +207,9 @@ func (r *runner) notifyTerminalStep(id int64, status string) { if err != nil || len(detail.Steps) == 0 { return } + if status == "failed" && detail.FailureKind == "expected" { + return + } step := detail.Steps[len(detail.Steps)-1] stepStatus, _, _, terminal := terminalFinish(step.Target, step.Stage, step.Outcome, step.Diagnostic) if !terminal || stepStatus != status { @@ -375,6 +378,14 @@ func (r *runner) notifyRun(id int64, name, status string, sequence int, currentS if event == "" { return } + if status == "failed" { + if detail, err := r.store.GetRun(r.ctx, id); err == nil && detail.FailureKind == "expected" { + settings, settingsErr := r.store.NotificationSettings(r.ctx) + if settingsErr != nil || (r.notifyMode(id) != "on" && !settings.RunFinished) { + return + } + } + } // Failed or interrupted runs always notify; successful runs notify only when // marked "on" or when the operator opted into every run end (run_finished). if event == "succeeded" || (event != protocol.NotifyWaiting && event != "failed" && event != "interrupted") { diff --git a/internal/server/notify_test.go b/internal/server/notify_test.go index 8790e32a..dd6debff 100644 --- a/internal/server/notify_test.go +++ b/internal/server/notify_test.go @@ -158,13 +158,14 @@ func TestTerminalNotificationRecipe(t *testing.T) { for index, test := range []struct { name, stage, outcome, status string executionError, deliveryError bool + notify bool }{ - {"success", "report", "success", "succeeded", false, false}, - {"research blocked", "research", "blocked", "failed", false, false}, - {"research execution error", "research", "error", "failed", true, false}, - {"report blocked", "report", "blocked", "failed", false, false}, - {"report execution error", "report", "error", "failed", true, false}, - {"delivery error preserves success", "report", "success", "succeeded", false, true}, + {"success", "report", "success", "succeeded", false, false, true}, + {"research blocked", "research", "blocked", "failed", false, false, false}, + {"research execution error", "research", "error", "failed", true, false, true}, + {"report blocked", "report", "blocked", "failed", false, false, false}, + {"report execution error", "report", "error", "failed", true, false, true}, + {"delivery error preserves success", "report", "success", "succeeded", false, true, true}, } { t.Run(test.name, func(t *testing.T) { deliveryFailure.Store(test.deliveryError) @@ -187,13 +188,16 @@ func TestTerminalNotificationRecipe(t *testing.T) { if err != nil { t.Fatal(err) } - if detail.Status != test.status || calls.Load()-before != 1 { + if detail.Status != test.status || (calls.Load()-before == 1) != test.notify { t.Fatal("wrong verdict or duplicate/missing terminal alert", detail.Status, calls.Load()-before) } last := detail.Steps[len(detail.Steps)-1] - if last.Stage != test.stage || len(last.Notifications) != 1 { + if last.Stage != test.stage || (len(last.Notifications) == 1) != test.notify { t.Fatal("notification not retained on terminal stage", last) } + if !test.notify { + return + } for _, step := range detail.Steps[:len(detail.Steps)-1] { if len(step.Notifications) != 0 { t.Fatal("intermediate success alerted", step) diff --git a/internal/server/runevents.go b/internal/server/runevents.go index 38b91a76..92fbd5f0 100644 --- a/internal/server/runevents.go +++ b/internal/server/runevents.go @@ -568,6 +568,8 @@ func handleRunEvents(request protocol.Message, events *runEventHub, runs *runner CompletedSteps: summary.CompletedSteps, CreatedAt: summary.CreatedAt, FinishedAt: summary.FinishedAt, + FailureKind: summary.FailureKind, + FailureReason: summary.FailureReason, CancelRequested: summary.CancelRequested, CleanupUnconfirmed: summary.CleanupUnconfirmed, ExportPendingSequence: summary.ExportPendingSequence, diff --git a/internal/server/runner.go b/internal/server/runner.go index aeb4df4c..693e90ba 100644 --- a/internal/server/runner.go +++ b/internal/server/runner.go @@ -1496,6 +1496,8 @@ func (r *runner) finishRunState(id int64, name, workspace, status, outcome, diag CurrentStage: currentStage, CompletedSteps: completed, FinishedAt: detail.FinishedAt, + FailureKind: detail.FailureKind, + FailureReason: detail.FailureReason, SizeBytes: size, }, true) r.kickSizes()