From 8476cfd7409395dfdb3fbf3d79e0075493f16baa Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 19:47:08 +0100 Subject: [PATCH 01/10] feat(app): wire the native pipelines browser on the shared session Register the landed PipelinesScreen at /pipelines through AppSession, with an honest first-connection gate, a native reconnect banner that retains the open list and detail, and an in-place refresh on reconnect. Move the shared connection chrome out of RunsDestination so both destinations use one implementation and one wording. Add destination, registration and reconnect coverage plus an isolated loopback Chrome probe that drives the real runPipelinesApp() composition. --- app/lib/application/connection_status.dart | 195 +++++++++ app/lib/application/pipelines_app.dart | 3 + .../application/pipelines_destination.dart | 61 +++ app/lib/application/runs_destination.dart | 188 +-------- app/lib/features/pipelines/screen.dart | 73 +++- app/notes/P1-wire.md | 157 +++++++ app/test/application/pipelines_app_test.dart | 31 +- .../pipelines_destination_test.dart | 237 +++++++++++ .../pipelines_registration_test.dart | 94 +++++ app/test/application/pipelines_replies.dart | 93 +++++ .../settings_registration_test.dart | 3 + .../pipelines/pipelines_screen_test.dart | 26 ++ app/tool/pipelines_wiring_probe.mjs | 236 +++++++++++ app/tool/pipelines_wiring_probe_entry.dart | 8 + app/tool/pipelines_wiring_probe_server.mjs | 394 ++++++++++++++++++ 15 files changed, 1594 insertions(+), 205 deletions(-) create mode 100644 app/lib/application/connection_status.dart create mode 100644 app/lib/application/pipelines_destination.dart create mode 100644 app/notes/P1-wire.md create mode 100644 app/test/application/pipelines_destination_test.dart create mode 100644 app/test/application/pipelines_registration_test.dart create mode 100644 app/test/application/pipelines_replies.dart create mode 100644 app/tool/pipelines_wiring_probe.mjs create mode 100644 app/tool/pipelines_wiring_probe_entry.dart create mode 100644 app/tool/pipelines_wiring_probe_server.mjs diff --git a/app/lib/application/connection_status.dart b/app/lib/application/connection_status.dart new file mode 100644 index 00000000..bbe57b46 --- /dev/null +++ b/app/lib/application/connection_status.dart @@ -0,0 +1,195 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../core/transport/connection_state.dart'; +import 'app_session.dart'; +import 'server_endpoint.dart'; + +/// The full connection screen shown before a destination has ever loaded. +/// +/// A missing native endpoint is a configuration state, not a server failure, +/// so it is explained without opening a socket. Otherwise the screen reports +/// connecting, then an honest unavailable state with a native Retry action. +class ConnectionGate extends StatelessWidget { + const ConnectionGate({ + super.key, + required this.session, + required this.server, + required this.cupertino, + }); + + final AppSession session; + final ServerEndpoint server; + final bool cupertino; + + @override + Widget build(BuildContext context) { + final state = session.connection; + if (server.requiresConfiguration) { + return _status( + context, + title: 'Server endpoint not configured', + detail: + 'Build the native app with an explicit Pipelines endpoint, for ' + 'example --dart-define=PIPELINES_SERVER_URL=ws://host:port/connect.', + ); + } + if (server.error != null) { + return _status(context, title: server.error!, detail: ''); + } + // Only the very first attempt is "connecting". A failed attempt keeps the + // same honest unavailable state while the client retries behind it, so the + // screen no longer flickers between unavailable and connecting. + if (state.kind == ConnectionKind.connecting && state.attempt <= 1) { + return _status( + context, + title: 'Connecting to Pipelines…', + detail: '', + progress: true, + ); + } + return _status( + context, + title: 'Pipelines server unavailable', + detail: state.retrying + ? 'Retrying automatically. Check that the Pipelines server is running.' + : 'Check that the Pipelines server is running, then try again.', + onRetry: session.retry, + ); + } + + Widget _status( + BuildContext context, { + required String title, + required String detail, + bool progress = false, + VoidCallback? onRetry, + }) { + final theme = Theme.of(context); + return Center( + child: SingleChildScrollView( + padding: const EdgeInsets.all(24), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + if (progress) + Padding( + padding: const EdgeInsets.only(bottom: 12), + child: cupertino + ? const CupertinoActivityIndicator() + : const CircularProgressIndicator(), + ), + Semantics( + liveRegion: true, + child: Text( + title, + textAlign: TextAlign.center, + style: cupertino + ? CupertinoTheme.of(context).textTheme.navTitleTextStyle + : theme.textTheme.titleMedium, + ), + ), + if (detail.isNotEmpty) ...[ + const SizedBox(height: 8), + Text( + detail, + textAlign: TextAlign.center, + style: cupertino ? null : theme.textTheme.bodyMedium, + ), + ], + if (onRetry != null) ...[ + const SizedBox(height: 16), + if (cupertino) + CupertinoButton(onPressed: onRetry, child: const Text('Retry')) + else + FilledButton(onPressed: onRetry, child: const Text('Retry')), + ], + ], + ), + ), + ); + } +} + +/// A compact status bar above retained content after the first connection. +class ConnectionBanner extends StatelessWidget { + const ConnectionBanner({ + super.key, + required this.session, + required this.cupertino, + }); + + final AppSession session; + final bool cupertino; + + @override + Widget build(BuildContext context) { + final state = session.connection; + final refused = session.subscription == RunSubscriptionState.refused; + final reconnecting = + !session.connected && + (state.kind == ConnectionKind.connecting || state.retrying); + final String title; + final String detail; + final VoidCallback onRetry; + if (session.connected && refused) { + title = 'Not live — run updates are unavailable.'; + detail = session.subscriptionError; + onRetry = session.resubscribe; + } else if (reconnecting) { + title = 'Reconnecting to Pipelines…'; + detail = ''; + onRetry = session.retry; + } else { + title = 'Not live — Pipelines server unavailable.'; + detail = 'Check that the Pipelines server is running.'; + onRetry = session.retry; + } + final textStyle = cupertino + ? CupertinoTheme.of(context).textTheme.textStyle + : Theme.of(context).textTheme.bodyMedium; + return ColoredBox( + color: cupertino + ? CupertinoDynamicColor.resolve(CupertinoColors.systemGrey5, context) + : Theme.of(context).colorScheme.surfaceContainerHighest, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), + child: Row( + children: [ + if (reconnecting) ...[ + cupertino + ? const CupertinoActivityIndicator(radius: 7) + : const SizedBox( + width: 14, + height: 14, + child: CircularProgressIndicator(strokeWidth: 2), + ), + const SizedBox(width: 10), + ], + Expanded( + child: Semantics( + liveRegion: true, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(title, style: textStyle), + if (detail.isNotEmpty) Text(detail, style: textStyle), + ], + ), + ), + ), + const SizedBox(width: 8), + if (cupertino) + CupertinoButton( + padding: EdgeInsets.zero, + onPressed: onRetry, + child: const Text('Retry'), + ) + else + TextButton(onPressed: onRetry, child: const Text('Retry')), + ], + ), + ), + ); + } +} diff --git a/app/lib/application/pipelines_app.dart b/app/lib/application/pipelines_app.dart index f9c02e35..e5de270d 100644 --- a/app/lib/application/pipelines_app.dart +++ b/app/lib/application/pipelines_app.dart @@ -11,6 +11,7 @@ import 'app.dart'; import 'app_route.dart'; import 'app_router.dart'; import 'app_session.dart'; +import 'pipelines_destination.dart'; import 'runs_destination.dart'; import 'server_endpoint.dart'; @@ -100,6 +101,8 @@ class _PipelinesAppState extends State { onDestinationSelected: (destination) => _delegate.goTo(_routeOf(destination)), destinationBodies: { + AppDestination.pipelines: (_) => + PipelinesDestination(session: _session, server: widget.server), AppDestination.runs: (_) => RunsDestination( session: _session, server: widget.server, diff --git a/app/lib/application/pipelines_destination.dart b/app/lib/application/pipelines_destination.dart new file mode 100644 index 00000000..d9b3c603 --- /dev/null +++ b/app/lib/application/pipelines_destination.dart @@ -0,0 +1,61 @@ +import 'package:flutter/material.dart'; + +import '../features/pipelines/screen.dart'; +import '../ui/adaptive/host.dart'; +import 'app_session.dart'; +import 'connection_status.dart'; +import 'server_endpoint.dart'; + +/// The Pipelines destination: the read-only browser plus honest status. +/// +/// Before the shared socket accepts its first connection nothing is requested, +/// so an offline launch cannot look like an empty pipeline list. After that the +/// browser stays mounted through drops; a reconnect advances [syncToken] so the +/// list and the open detail refresh in place instead of losing the selection. +class PipelinesDestination extends StatelessWidget { + const PipelinesDestination({ + super.key, + required this.session, + required this.server, + }); + + final AppSession session; + final ServerEndpoint server; + + @override + Widget build(BuildContext context) => AnimatedBuilder( + animation: session, + builder: (context, _) { + final cupertino = usesCupertinoHost(context); + if ((server.requiresConfiguration || server.error != null) && + session.endpoint == null) { + return ConnectionGate( + session: session, + server: server, + cupertino: cupertino, + ); + } + if (!session.everConnected) { + if (session.connected) return _pipelinesScreen(); + return ConnectionGate( + session: session, + server: server, + cupertino: cupertino, + ); + } + return Column( + children: [ + if (!session.connected) + ConnectionBanner(session: session, cupertino: cupertino), + Expanded(child: _pipelinesScreen()), + ], + ); + }, + ); + + Widget _pipelinesScreen() => PipelinesScreen( + gateway: session.gateway, + embedded: true, + syncToken: session.connectionEpoch, + ); +} diff --git a/app/lib/application/runs_destination.dart b/app/lib/application/runs_destination.dart index ca4e5481..67f01461 100644 --- a/app/lib/application/runs_destination.dart +++ b/app/lib/application/runs_destination.dart @@ -1,10 +1,9 @@ -import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; -import '../core/transport/connection_state.dart'; import '../features/runs/screen.dart'; import '../ui/adaptive/host.dart'; import 'app_session.dart'; +import 'connection_status.dart'; import 'server_endpoint.dart'; /// The Runs destination: the loaded screen plus an honest connection status. @@ -36,7 +35,7 @@ class RunsDestination extends StatelessWidget { final cupertino = usesCupertinoHost(context); if ((server.requiresConfiguration || server.error != null) && session.endpoint == null) { - return _ConnectionScreen( + return ConnectionGate( session: session, server: server, cupertino: cupertino, @@ -44,7 +43,7 @@ class RunsDestination extends StatelessWidget { } if (!session.everConnected) { if (session.connected) return _runsScreen(); - return _ConnectionScreen( + return ConnectionGate( session: session, server: server, cupertino: cupertino, @@ -54,7 +53,7 @@ class RunsDestination extends StatelessWidget { children: [ if (!session.connected || session.subscription == RunSubscriptionState.refused) - _ConnectionBanner(session: session, cupertino: cupertino), + ConnectionBanner(session: session, cupertino: cupertino), Expanded(child: _runsScreen()), ], ); @@ -69,182 +68,3 @@ class RunsDestination extends StatelessWidget { onBack: onBack, ); } - -class _ConnectionScreen extends StatelessWidget { - const _ConnectionScreen({ - required this.session, - required this.server, - required this.cupertino, - }); - - final AppSession session; - final ServerEndpoint server; - final bool cupertino; - - @override - Widget build(BuildContext context) { - final state = session.connection; - if (server.requiresConfiguration) { - return _status( - context, - title: 'Server endpoint not configured', - detail: - 'Build the native app with an explicit Pipelines endpoint, for ' - 'example --dart-define=PIPELINES_SERVER_URL=ws://host:port/connect.', - ); - } - if (server.error != null) { - return _status(context, title: server.error!, detail: ''); - } - // Only the very first attempt is "connecting". A failed attempt keeps the - // same honest unavailable state while the client retries behind it, so the - // screen no longer flickers between unavailable and connecting. - if (state.kind == ConnectionKind.connecting && state.attempt <= 1) { - return _status( - context, - title: 'Connecting to Pipelines…', - detail: '', - progress: true, - ); - } - return _status( - context, - title: 'Pipelines server unavailable', - detail: state.retrying - ? 'Retrying automatically. Check that the Pipelines server is running.' - : 'Check that the Pipelines server is running, then try again.', - onRetry: session.retry, - ); - } - - Widget _status( - BuildContext context, { - required String title, - required String detail, - bool progress = false, - VoidCallback? onRetry, - }) { - final theme = Theme.of(context); - return Center( - child: SingleChildScrollView( - padding: const EdgeInsets.all(24), - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - if (progress) - Padding( - padding: const EdgeInsets.only(bottom: 12), - child: cupertino - ? const CupertinoActivityIndicator() - : const CircularProgressIndicator(), - ), - Semantics( - liveRegion: true, - child: Text( - title, - textAlign: TextAlign.center, - style: cupertino - ? CupertinoTheme.of(context).textTheme.navTitleTextStyle - : theme.textTheme.titleMedium, - ), - ), - if (detail.isNotEmpty) ...[ - const SizedBox(height: 8), - Text( - detail, - textAlign: TextAlign.center, - style: cupertino ? null : theme.textTheme.bodyMedium, - ), - ], - if (onRetry != null) ...[ - const SizedBox(height: 16), - if (cupertino) - CupertinoButton(onPressed: onRetry, child: const Text('Retry')) - else - FilledButton(onPressed: onRetry, child: const Text('Retry')), - ], - ], - ), - ), - ); - } -} - -/// A compact status bar above the retained Runs screen. -class _ConnectionBanner extends StatelessWidget { - const _ConnectionBanner({required this.session, required this.cupertino}); - - final AppSession session; - final bool cupertino; - - @override - Widget build(BuildContext context) { - final state = session.connection; - final refused = session.subscription == RunSubscriptionState.refused; - final reconnecting = - !session.connected && - (state.kind == ConnectionKind.connecting || state.retrying); - final String title; - final String detail; - final VoidCallback onRetry; - if (session.connected && refused) { - title = 'Not live — run updates are unavailable.'; - detail = session.subscriptionError; - onRetry = session.resubscribe; - } else if (reconnecting) { - title = 'Reconnecting to Pipelines…'; - detail = ''; - onRetry = session.retry; - } else { - title = 'Not live — Pipelines server unavailable.'; - detail = 'Check that the Pipelines server is running.'; - onRetry = session.retry; - } - final textStyle = cupertino - ? CupertinoTheme.of(context).textTheme.textStyle - : Theme.of(context).textTheme.bodyMedium; - return ColoredBox( - color: cupertino - ? CupertinoDynamicColor.resolve(CupertinoColors.systemGrey5, context) - : Theme.of(context).colorScheme.surfaceContainerHighest, - child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), - child: Row( - children: [ - if (reconnecting) ...[ - cupertino - ? const CupertinoActivityIndicator(radius: 7) - : const SizedBox( - width: 14, - height: 14, - child: CircularProgressIndicator(strokeWidth: 2), - ), - const SizedBox(width: 10), - ], - Expanded( - child: Semantics( - liveRegion: true, - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text(title, style: textStyle), - if (detail.isNotEmpty) Text(detail, style: textStyle), - ], - ), - ), - ), - const SizedBox(width: 8), - if (cupertino) - CupertinoButton( - padding: EdgeInsets.zero, - onPressed: onRetry, - child: const Text('Retry'), - ) - else - TextButton(onPressed: onRetry, child: const Text('Retry')), - ], - ), - ), - ); - } -} diff --git a/app/lib/features/pipelines/screen.dart b/app/lib/features/pipelines/screen.dart index ae6dc3f5..94807ad8 100644 --- a/app/lib/features/pipelines/screen.dart +++ b/app/lib/features/pipelines/screen.dart @@ -21,18 +21,31 @@ const double kPipelinesWideBreakpoint = 720; /// /// [graphBuilder] is the optional integration hook for the later graph item. /// Without it the Graph tab states that graph rendering is pending. +/// +/// Standalone use keeps the screen's own native scaffolding. The application +/// shell sets [embedded] because it already owns the one navigation bar, and +/// supplies [syncToken] so a reconnect refreshes in place. class PipelinesScreen extends StatefulWidget { const PipelinesScreen({ super.key, required this.gateway, this.graphBuilder, this.onStageSelected, + this.embedded = false, + this.syncToken = 0, }); final ApiGateway gateway; final PipelineGraphBuilder? graphBuilder; final ValueChanged? onStageSelected; + /// True under the application shell, which owns the single navigation bar. + final bool embedded; + + /// Advances when the shared socket is replaced. The mounted controller + /// reloads the list and the selected detail without losing the selection. + final int syncToken; + @override State createState() => _PipelinesScreenState(); } @@ -54,6 +67,10 @@ class _PipelinesScreenState extends State { _controller.dispose(); _controller = PipelinesController(PipelinesRepository(widget.gateway)) ..load(); + } else if (oldWidget.syncToken != widget.syncToken) { + // The socket was replaced; re-read through the existing controller so the + // selected pipeline and requested version survive the reconnect. + _controller.load(); } } @@ -102,6 +119,7 @@ class _PipelinesScreenState extends State { ); }, ); + if (widget.embedded) return _embeddedBody(context, body); return useCupertinoControls(context) ? _cupertinoShell(context, body) : _materialShell(context, body); @@ -109,6 +127,43 @@ class _PipelinesScreenState extends State { ); } + /// The shell owns the navigation bar here, so the content keeps a native + /// Refresh action without adding a second bar. + Widget _embeddedBody(BuildContext context, Widget body) { + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Align( + alignment: AlignmentDirectional.centerEnd, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 8), + child: _refreshButton(context), + ), + ), + Expanded(child: body), + ], + ); + } + + Widget _refreshButton(BuildContext context) { + if (useCupertinoControls(context)) { + return Semantics( + button: true, + label: 'Refresh', + child: CupertinoButton( + padding: EdgeInsets.zero, + onPressed: _controller.load, + child: const Icon(CupertinoIcons.refresh), + ), + ); + } + return IconButton( + tooltip: 'Refresh', + onPressed: _controller.load, + icon: const Icon(Icons.refresh), + ); + } + Widget _divider(BuildContext context) { if (useCupertinoControls(context)) { return Container( @@ -123,13 +178,7 @@ class _PipelinesScreenState extends State { return Scaffold( appBar: AppBar( title: const Text('Pipelines'), - actions: [ - IconButton( - tooltip: 'Refresh', - onPressed: _controller.load, - icon: const Icon(Icons.refresh), - ), - ], + actions: [_refreshButton(context)], ), body: SafeArea(child: body), ); @@ -139,15 +188,7 @@ class _PipelinesScreenState extends State { return CupertinoPageScaffold( navigationBar: CupertinoNavigationBar( middle: const Text('Pipelines'), - trailing: Semantics( - button: true, - label: 'Refresh', - child: CupertinoButton( - padding: EdgeInsets.zero, - onPressed: _controller.load, - child: const Icon(CupertinoIcons.refresh), - ), - ), + trailing: _refreshButton(context), ), child: SafeArea(top: false, child: body), ); diff --git a/app/notes/P1-wire.md b/app/notes/P1-wire.md new file mode 100644 index 00000000..968b1576 --- /dev/null +++ b/app/notes/P1-wire.md @@ -0,0 +1,157 @@ +# P1 wire — Pipelines destination on the shared session + +## Implemented + +- `lib/application/pipelines_destination.dart` registers the landed + `PipelinesScreen` on the existing `/pipelines` route through `AppSession`. + It reuses the session's single socket and gateway; no second connection, + fake rows or hidden request path was added. +- Before the first accepted connection the destination mounts no screen and + sends no `list_pipelines`, `list_runs` or `get_pipeline`. The full gate says + `Connecting to Pipelines…` or `Pipelines server unavailable`, with an + explicit native `Retry` and the existing missing-endpoint explanation. +- After the first connection the screen stays mounted through drops. A + status banner reports `Reconnecting to Pipelines…`; a reconnect advances + `syncToken`, and `PipelinesScreen.didUpdateWidget` calls the existing + `controller.load()` so the list and the selected detail refresh in place. + Selection (pipeline id and requested version) is preserved; there is no + remount and no return to the empty list. +- `PipelinesScreen` gained `embedded` and `syncToken`. Embedded mode skips its + own Material `Scaffold`/`AppBar` or Cupertino `CupertinoPageScaffold`/ + `CupertinoNavigationBar`, because the shell already owns the single bar. + A native refresh action stays in the content (`IconButton`/`CupertinoButton` + with the same `Refresh` wording), using the real host selection. +- The connection gate and banner moved verbatim from `runs_destination.dart` + to `lib/application/connection_status.dart`, so Runs and Pipelines share one + implementation and one wording. Runs behavior is unchanged. +- Registration is a tiny entry in the existing `destinationBodies` map in + `lib/application/pipelines_app.dart`. +- No graph rendering, actions, templates, schedules, route expansion, native + control replacement, fixed component size/font/colour override, server, + web, legacy, Android or pubspec change was made. Graph still shows + `Graph rendering is pending (P2).` + +## Files + +Production: + +- `lib/application/connection_status.dart` (new, moved shared chrome) +- `lib/application/pipelines_destination.dart` (new) +- `lib/application/pipelines_app.dart` (registration and import) +- `lib/application/runs_destination.dart` (uses the shared chrome) +- `lib/features/pipelines/screen.dart` (embedded framing, content refresh, + reconnect sync token) + +Tests: + +- `test/application/pipelines_destination_test.dart` (new) +- `test/application/pipelines_registration_test.dart` (new) +- `test/application/pipelines_replies.dart` (new serialized reply helper) +- `test/application/pipelines_app_test.dart` (route now renders the real list) +- `test/application/settings_registration_test.dart` (answers the mounted + Pipelines reads before visiting Settings) +- `test/features/pipelines/pipelines_screen_test.dart` (embedded framing and + content refresh) + +Browser tooling (isolated, pure loopback fixtures): + +- `tool/pipelines_wiring_probe_entry.dart` — exact `runPipelinesApp()` + composition +- `tool/pipelines_wiring_probe_server.mjs` — static bundle plus loopback + websocket fixture with drop/refuse/accept/state endpoints +- `tool/pipelines_wiring_probe.mjs` — real Chrome DevTools probe + +## Checks actually run + +| Check | Result | +| --- | --- | +| `flutter analyze` | `No issues found!` | +| `flutter test` | **595 passed** | +| `flutter test test/application` | **33 passed** | +| `flutter test test/features/pipelines` | **49 passed** | +| `flutter test test/features/pipelines/pipelines_screen_test.dart` | **6 passed** | +| `dart format --output=none --set-exit-if-changed lib test tool/pipelines_wiring_probe_entry.dart` | 273 files, 0 changed | +| `node --check` on both probe scripts | passed | +| `flutter build web` (default `lib/main.dart`) | `✓ Built build/web` | +| `flutter build web -t tool/pipelines_wiring_probe_entry.dart` | `✓ Built` | +| `node tool/pipelines_wiring_probe.mjs ` | exit 0, 25 checks, 9 captures, `probe.json` has no error | + +Coverage added: + +- missing native endpoint never opens a socket; +- connecting gate sends no list request; the screen mounts only after the + shared socket accepts; +- refused first connection is friendly, names no transport exception and + offers Retry; +- a drop retains the loaded rows and detail, then reconnect re-reads list and + the open detail without losing the selected row; +- the registered `/pipelines` route renders real rows, detail content hash and + source with exactly one Material or Cupertino bar, one socket; +- Cupertino host builds no `Material` widget; +- embedded framing adds no second bar and keeps a working content Refresh. + +## Browser evidence (real Chrome, normal composition) + +Directory: `/Users/alan/.local/share/pipelines/data/artifacts/69/public/p1-wire-captures` + +- `01-gate-refused-material.png` — first connection refused: honest gate, + `Retry`, shell nav present, zero list requests recorded by the fixture. +- `02-list-material.png` — Material shell below its single bar with the real + `Release verification` / `Nightly documentation` rows. +- `03-detail-material.png` — selected pipeline Summary with + `sha256:fixture-3-v3`, versions and metadata. +- `04-source-material.png` — Source tab with the real fixture source text. +- `05-drop-detail-retained-material.png` — socket dropped: `Reconnecting to + Pipelines…` banner while the open detail stays visible at `/pipelines`. +- `06-reconnect-detail-refreshed-material.png` — after Retry: banner gone, + list and open detail re-read (fixture counters advanced for `list_pipelines` + and `get_pipeline`), same selection. +- `07-list-cupertino-dark.png` — macOS/dark host: Cupertino global bar and tab + bar, inset grouped rows, `Release verification` present. +- `08-detail-cupertino-dark.png` — Cupertino dark detail with content hash, + versions and native segmented tabs. +- `09-source-cupertino-dark.png` — Cupertino dark Source with source text. +- `probe.json` — fixture URL, 25 checks, captures and final counters. + +The probe starts the fixture with websocket upgrades refused, asserts the gate +and that `listPipelines`, `listRuns` and `getPipeline` are all 0, then accepts +and drives the normal app. Hosts are selected through the browser platform +user agent (Linux for Material, macOS for Cupertino), which is what the normal +composition reads. OCR asserts the real row, content hash and source; the +captures were inspected to confirm one bar and Cupertino dark styling. + +Reproduce: + +```sh +flutter build web -t tool/pipelines_wiring_probe_entry.dart -o +node tool/pipelines_wiring_probe.mjs +``` + +## Explicitly not done / unverified + +- Graph rendering and graph nodes/edges remain P2; the existing pending notice + is unchanged. +- No action, template, schedule, route expansion or navigation redesign. +- No production server, real operator chat/run or authenticated preview was + touched; all browser data comes from the isolated loopback fixture. +- Android and iOS were not built, installed or run; mobile remains unverified. +- No commit, push, deployment or preview-service change was made. +- No Material/Cupertino fixed sizes, palette or font overrides were added. + The only fixed breakpoint remains the existing `kPipelinesWideBreakpoint`. + +## Diff + +Tracked changes (`git diff --numstat`): + +``` +3 0 app/lib/application/pipelines_app.dart +4 184 app/lib/application/runs_destination.dart +57 16 app/lib/features/pipelines/screen.dart +26 5 app/test/application/pipelines_app_test.dart +3 0 app/test/application/settings_registration_test.dart +26 0 app/test/features/pipelines/pipelines_screen_test.dart +``` + +New files: `connection_status.dart` (195), `pipelines_destination.dart` (61), +three test files and three probe files. Net production change is ~120 added +lines after moving the shared chrome out of `runs_destination.dart`. diff --git a/app/test/application/pipelines_app_test.dart b/app/test/application/pipelines_app_test.dart index b92c3b41..81e526d8 100644 --- a/app/test/application/pipelines_app_test.dart +++ b/app/test/application/pipelines_app_test.dart @@ -5,8 +5,11 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:pipelines_app/application/pipelines_app.dart'; import 'package:pipelines_app/application/server_endpoint.dart'; import 'package:pipelines_app/core/transport/pipelines_client.dart'; +import 'package:pipelines_app/features/pipelines/screen.dart'; import '../core/transport/pipelines_client_test.dart' show FakeChannel; +import '../features/pipelines/fixtures.dart'; +import 'pipelines_replies.dart'; ServerEndpoint webServer() => ServerEndpoint.resolve( base: Uri.parse('http://127.0.0.1:8096/'), @@ -125,18 +128,32 @@ void main() { await pumpApp(tester, channel: channel, client: client, provider: provider); expect(provider.value.uri.path, '/pipelines'); + final fixture = PipelineFixture(); + await replyPipelines(tester, channel, fixture); + final pipelinesRunsId = + pipelineRequest(channel, 'list_runs')!['id'] as String; await tester.tap(find.text('Runs').last); await tester.pump(); expect(provider.value.uri.path, '/runs'); - await replyList( + final runsRequest = await waitForLaterRequest( tester, channel, - runs: [ - {'id': 2, 'name': 'Beta run', 'status': 'failed'}, - ], + 'list_runs', + pipelinesRunsId, ); + channel.incoming.add( + jsonEncode({ + 'id': runsRequest['id'], + 'type': 'runs', + 'runs': [ + {'id': 2, 'name': 'Beta run', 'status': 'failed'}, + ], + }), + ); + await tester.pump(); + await tester.pump(); await tester.tap(find.text('Beta run')); await tester.pump(); expect(provider.value.uri.path, '/runs/2'); @@ -172,6 +189,10 @@ void main() { await pumpApp(tester, channel: channel, client: client, provider: provider); expect(provider.value.uri.path, '/pipelines'); - expect(find.text('Pipelines — Not implemented'), findsOneWidget); + await replyPipelines(tester, channel, PipelineFixture()); + expect(find.byType(PipelinesScreen), findsOneWidget); + expect(find.text('Pipelines — Not implemented'), findsNothing); + await tester.pumpWidget(const SizedBox.shrink()); + await tester.pump(); }); } diff --git a/app/test/application/pipelines_destination_test.dart b/app/test/application/pipelines_destination_test.dart new file mode 100644 index 00000000..65010f09 --- /dev/null +++ b/app/test/application/pipelines_destination_test.dart @@ -0,0 +1,237 @@ +import 'dart:convert'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/application/app_session.dart'; +import 'package:pipelines_app/application/pipelines_destination.dart'; +import 'package:pipelines_app/application/server_endpoint.dart'; +import 'package:pipelines_app/core/transport/pipelines_client.dart'; +import 'package:pipelines_app/features/pipelines/screen.dart'; + +import '../core/transport/pipelines_client_test.dart' show FakeChannel; +import '../features/pipelines/fixtures.dart'; + +ServerEndpoint webServer() => ServerEndpoint.resolve( + base: Uri.parse('http://127.0.0.1:8096/'), + web: true, +); + +Map? requestOf(FakeChannel channel, String type) => channel + .outgoing + .map((frame) => jsonDecode(frame as String) as Map) + .where((frame) => frame['type'] == type) + .firstOrNull; + +Widget materialApp(AppSession session, ServerEndpoint server) => MaterialApp( + home: Scaffold( + body: PipelinesDestination(session: session, server: server), + ), +); + +Future waitFor( + WidgetTester tester, + bool Function() check, + String label, +) async { + for (var attempt = 0; attempt < 60 && !check(); attempt++) { + await tester.pump(const Duration(milliseconds: 10)); + } + expect(check(), isTrue, reason: 'Timed out waiting for $label'); +} + +Future replyList( + WidgetTester tester, + FakeChannel channel, + PipelineFixture fixture, +) async { + await waitFor( + tester, + () => requestOf(channel, 'list_pipelines') != null, + 'list_pipelines', + ); + final pipelines = requestOf(channel, 'list_pipelines')!; + channel.incoming.add( + jsonEncode({ + 'id': pipelines['id'], + 'type': 'pipelines', + 'pipelines': fixture.summaries, + }), + ); + await tester.pump(); + await waitFor( + tester, + () => requestOf(channel, 'list_runs') != null, + 'list_runs', + ); + final runs = requestOf(channel, 'list_runs')!; + channel.incoming.add( + jsonEncode({'id': runs['id'], 'type': 'runs', 'runs': fixture.runs}), + ); + await tester.pump(); +} + +Future replyDetail( + WidgetTester tester, + FakeChannel channel, + PipelineFixture fixture, + int id, +) async { + await waitFor( + tester, + () => requestOf(channel, 'get_pipeline') != null, + 'get_pipeline', + ); + final request = requestOf(channel, 'get_pipeline')!; + final detail = fixture.detailFor( + request['pipeline_id'] as int, + request['version'] as int, + )!; + channel.incoming.add( + jsonEncode({'id': request['id'], 'type': 'pipeline', 'detail': detail}), + ); + await tester.pump(); +} + +void main() { + testWidgets('missing native configuration never opens a socket', ( + tester, + ) async { + final channel = FakeChannel(); + final client = PipelinesClient(channelFactory: (_) => channel); + final server = ServerEndpoint.resolve( + base: Uri.parse('http://127.0.0.1:8096/'), + web: false, + ); + final session = AppSession(endpoint: server.uri, client: client); + addTearDown(session.dispose); + + await tester.pumpWidget(materialApp(session, server)); + expect(find.text('Server endpoint not configured'), findsOneWidget); + expect(find.textContaining('PIPELINES_SERVER_URL'), findsOneWidget); + expect(find.byType(PipelinesScreen), findsNothing); + expect(channel.outgoing, isEmpty); + }); + + testWidgets('the list is only requested after the first connection', ( + tester, + ) async { + final fixture = PipelineFixture(); + final channel = FakeChannel(); + final client = PipelinesClient(channelFactory: (_) => channel); + final server = webServer(); + final session = AppSession(endpoint: server.uri, client: client); + addTearDown(session.dispose); + + final starting = session.start(); + await tester.pumpWidget(materialApp(session, server)); + await tester.pump(); + expect(find.text('Connecting to Pipelines…'), findsOneWidget); + expect(find.byType(PipelinesScreen), findsNothing); + expect(requestOf(channel, 'list_pipelines'), isNull); + expect(channel.outgoing, isEmpty); + + channel.readyCompleter.complete(); + await starting; + await tester.pump(); + await replyList(tester, channel, fixture); + await tester.pump(); + + expect(find.byType(PipelinesScreen), findsOneWidget); + expect(find.text('Alpha review'), findsOneWidget); + expect(requestOf(channel, 'list_pipelines'), isNotNull); + }); + + testWidgets('an unavailable first connection is honest and retryable', ( + tester, + ) async { + final channel = FakeChannel(); + final client = PipelinesClient( + channelFactory: (_) => channel, + backoffBase: const Duration(hours: 1), + backoffMax: const Duration(hours: 1), + ); + final server = webServer(); + final session = AppSession(endpoint: server.uri, client: client); + addTearDown(session.dispose); + + final starting = session.start(); + channel.readyCompleter.completeError(StateError('Failed to connect')); + await starting; + await tester.pumpWidget(materialApp(session, server)); + await tester.pump(); + + expect(find.text('Pipelines server unavailable'), findsOneWidget); + expect(find.textContaining('Failed to connect'), findsNothing); + expect(find.widgetWithText(FilledButton, 'Retry'), findsOneWidget); + expect(find.byType(PipelinesScreen), findsNothing); + expect(channel.outgoing, isEmpty); + // The client keeps retrying by design; end its backoff timer explicitly. + session.dispose(); + }); + + testWidgets('reconnect refreshes the list and the open detail in place', ( + tester, + ) async { + tester.view.physicalSize = const Size(1100, 900); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + + final fixture = PipelineFixture(); + final first = FakeChannel()..readyCompleter.complete(); + final second = FakeChannel()..readyCompleter.complete(); + var sockets = 0; + final client = PipelinesClient( + channelFactory: (_) => sockets++ == 0 ? first : second, + backoffBase: const Duration(milliseconds: 10), + ); + final server = webServer(); + final session = AppSession(endpoint: server.uri, client: client); + addTearDown(session.dispose); + + await session.start(); + await tester.pumpWidget(materialApp(session, server)); + await tester.pump(); + await replyList(tester, first, fixture); + await tester.pump(); + expect(find.text('Alpha review'), findsOneWidget); + + await tester.tap(find.byKey(const Key('pipeline-row-1'))); + await tester.pump(); + await replyDetail(tester, first, fixture, 1); + await tester.pump(); + expect(find.text('hash-alpha'), findsOneWidget); + expect( + tester.widget(find.byKey(const Key('pipeline-row-1'))).selected, + isTrue, + ); + + first.incoming.addError(StateError('network drop')); + await tester.pump(); + expect(find.byType(PipelinesScreen), findsOneWidget); + expect(find.text('Reconnecting to Pipelines…'), findsOneWidget); + expect(find.text('hash-alpha'), findsOneWidget); + + await waitFor( + tester, + () => requestOf(second, 'list_pipelines') != null, + 'reconnected list request', + ); + await replyList(tester, second, fixture); + await waitFor( + tester, + () => requestOf(second, 'get_pipeline') != null, + 'reconnected detail request', + ); + await replyDetail(tester, second, fixture, 1); + await tester.pump(); + + expect(find.text('Reconnecting to Pipelines…'), findsNothing); + expect(find.text('hash-alpha'), findsOneWidget); + expect( + tester.widget(find.byKey(const Key('pipeline-row-1'))).selected, + isTrue, + reason: 'A reconnect must not remount the screen or drop the selection.', + ); + }); +} diff --git a/app/test/application/pipelines_registration_test.dart b/app/test/application/pipelines_registration_test.dart new file mode 100644 index 00000000..19a9d6e3 --- /dev/null +++ b/app/test/application/pipelines_registration_test.dart @@ -0,0 +1,94 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/application/pipelines_app.dart'; +import 'package:pipelines_app/core/transport/pipelines_client.dart'; + +import '../core/transport/pipelines_client_test.dart' show FakeChannel; +import '../features/pipelines/fixtures.dart'; +import '../features/pipelines/test_helpers.dart' show selectableText; +import 'pipelines_app_test.dart' show webServer; +import 'pipelines_replies.dart'; + +void main() { + for (final cupertino in [false, true]) { + testWidgets( + 'the /pipelines route renders real rows, detail and source ($cupertino)', + (tester) async { + tester.view.physicalSize = const Size(1100, 900); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + if (cupertino) { + tester.platformDispatcher.platformBrightnessTestValue = + Brightness.dark; + addTearDown( + tester.platformDispatcher.clearPlatformBrightnessTestValue, + ); + } + + final fixture = PipelineFixture(); + final channel = FakeChannel()..readyCompleter.complete(); + var sockets = 0; + final client = PipelinesClient( + channelFactory: (_) { + sockets++; + return channel; + }, + ); + final provider = PlatformRouteInformationProvider( + initialRouteInformation: RouteInformation( + uri: Uri.parse('/pipelines'), + ), + ); + addTearDown(provider.dispose); + + await tester.pumpWidget( + PipelinesApp( + server: webServer(), + client: client, + cupertino: cupertino, + routeInformationProvider: provider, + ), + ); + await tester.pump(); + await replyPipelines(tester, channel, fixture); + await tester.pump(); + + expect(find.text('Alpha review'), findsOneWidget); + expect(find.text('id 1 · v2 · 2 stages'), findsOneWidget); + expect(find.text('Pipelines — Not implemented'), findsNothing); + expect(sockets, 1); + + // The shell owns the only navigation bar; the embedded screen adds no + // second AppBar or CupertinoNavigationBar. + if (cupertino) { + expect(find.byType(CupertinoNavigationBar), findsOneWidget); + expect(find.byType(CupertinoPageScaffold), findsOneWidget); + expect(find.byType(Material), findsNothing); + } else { + expect(find.byType(AppBar), findsOneWidget); + expect(find.byType(Scaffold), findsOneWidget); + } + + await tester.tap(find.byKey(const Key('pipeline-row-1'))); + await tester.pump(); + await replyPipelineDetail(tester, channel, fixture); + await tester.pump(); + expect(find.text('hash-alpha'), findsOneWidget); + + await tester.tap(find.text('Source')); + await tester.pump(); + expect( + selectableText( + 'name: Alpha review\nstages:\n review:\n type: model', + ), + findsOneWidget, + ); + + await tester.pumpWidget(const SizedBox.shrink()); + await tester.pump(); + }, + ); + } +} diff --git a/app/test/application/pipelines_replies.dart b/app/test/application/pipelines_replies.dart new file mode 100644 index 00000000..9c5b2f5d --- /dev/null +++ b/app/test/application/pipelines_replies.dart @@ -0,0 +1,93 @@ +import 'dart:convert'; + +import 'package:flutter_test/flutter_test.dart'; + +import '../core/transport/pipelines_client_test.dart' show FakeChannel; +import '../features/pipelines/fixtures.dart'; + +Map? pipelineRequest(FakeChannel channel, String type) => + channel.outgoing + .map((frame) => jsonDecode(frame as String) as Map) + .where((frame) => frame['type'] == type) + .firstOrNull; + +Future waitForRequest( + WidgetTester tester, + FakeChannel channel, + String type, +) async { + for ( + var attempt = 0; + attempt < 60 && pipelineRequest(channel, type) == null; + attempt++ + ) { + await tester.pump(const Duration(milliseconds: 10)); + } + expect( + pipelineRequest(channel, type), + isNotNull, + reason: 'Timed out waiting for $type', + ); +} + +/// Waits for a later request of [type] than [afterId]. The transport serializes +/// requests, so a destination that mounts later issues its read only after the +/// previous reply arrives. +Future> waitForLaterRequest( + WidgetTester tester, + FakeChannel channel, + String type, + String afterId, +) async { + Map? later() => channel.outgoing + .map((frame) => jsonDecode(frame as String) as Map) + .where((frame) => frame['type'] == type && frame['id'] != afterId) + .firstOrNull; + for (var attempt = 0; attempt < 60 && later() == null; attempt++) { + await tester.pump(const Duration(milliseconds: 10)); + } + expect(later(), isNotNull, reason: 'Timed out waiting for later $type'); + return later()!; +} + +Future replyPipelines( + WidgetTester tester, + FakeChannel channel, + PipelineFixture fixture, +) async { + await waitForRequest(tester, channel, 'list_pipelines'); + final pipelines = pipelineRequest(channel, 'list_pipelines')!; + channel.incoming.add( + jsonEncode({ + 'id': pipelines['id'], + 'type': 'pipelines', + 'pipelines': fixture.summaries, + }), + ); + await tester.pump(); + await waitForRequest(tester, channel, 'list_runs'); + final runs = pipelineRequest(channel, 'list_runs')!; + channel.incoming.add( + jsonEncode({'id': runs['id'], 'type': 'runs', 'runs': fixture.runs}), + ); + await tester.pump(); + await tester.pump(); +} + +Future replyPipelineDetail( + WidgetTester tester, + FakeChannel channel, + PipelineFixture fixture, +) async { + await waitForRequest(tester, channel, 'get_pipeline'); + final request = pipelineRequest(channel, 'get_pipeline')!; + final detail = fixture.detailFor( + request['pipeline_id'] as int, + request['version'] as int, + )!; + channel.incoming.add( + jsonEncode({'id': request['id'], 'type': 'pipeline', 'detail': detail}), + ); + await tester.pump(); + await tester.pump(); +} diff --git a/app/test/application/settings_registration_test.dart b/app/test/application/settings_registration_test.dart index 238287ab..d54304be 100644 --- a/app/test/application/settings_registration_test.dart +++ b/app/test/application/settings_registration_test.dart @@ -8,7 +8,9 @@ import 'package:pipelines_app/core/transport/pipelines_client.dart'; import 'package:shared_preferences/shared_preferences.dart'; import '../core/transport/pipelines_client_test.dart' show FakeChannel; +import '../features/pipelines/fixtures.dart'; import 'pipelines_app_test.dart' show webServer, requestOf; +import 'pipelines_replies.dart'; void main() { for (final cupertino in [false, true]) { @@ -46,6 +48,7 @@ void main() { isNull, reason: 'Unvisited settings must not issue hidden requests', ); + await replyPipelines(tester, channel, PipelineFixture()); await tester.tap(find.text('Settings').last); await tester.pump(); diff --git a/app/test/features/pipelines/pipelines_screen_test.dart b/app/test/features/pipelines/pipelines_screen_test.dart index 957d4e16..b5db966e 100644 --- a/app/test/features/pipelines/pipelines_screen_test.dart +++ b/app/test/features/pipelines/pipelines_screen_test.dart @@ -128,6 +128,32 @@ void main() { expect(find.text('Alpha review'), findsOneWidget); }); + testWidgets('embedded framing adds no bar and keeps a content refresh', ( + tester, + ) async { + final fixture = PipelineFixture(); + final gateway = gatewayFor(fixture); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + appBar: AppBar(title: const Text('Host bar')), + body: PipelinesScreen(gateway: gateway, embedded: true), + ), + ), + ); + await tester.pumpAndSettle(); + + expect(find.byType(AppBar), findsOneWidget); + expect(find.text('Host bar'), findsOneWidget); + expect(find.text('Pipelines'), findsNothing); + expect(find.text('Alpha review'), findsOneWidget); + + final lists = gateway.callsOf('list_pipelines').length; + await tester.tap(find.byTooltip('Refresh')); + await tester.pumpAndSettle(); + expect(gateway.callsOf('list_pipelines').length, lists + 1); + }); + testWidgets('graph tab states it is pending without a hook', (tester) async { final fixture = PipelineFixture(); await pumpWide(tester, gatewayFor(fixture)); diff --git a/app/tool/pipelines_wiring_probe.mjs b/app/tool/pipelines_wiring_probe.mjs new file mode 100644 index 00000000..a87ee614 --- /dev/null +++ b/app/tool/pipelines_wiring_probe.mjs @@ -0,0 +1,236 @@ +// Real-Chrome acceptance for the Pipelines destination in the normal app. +// +// The bundle is `tool/pipelines_wiring_probe_entry.dart`, i.e. the same +// composition as main; the isolated loopback fixture answers the protocol. +// Both native hosts are exercised by changing the browser platform user agent. +// +// Usage: node tool/pipelines_wiring_probe.mjs +import { execFile } from 'node:child_process'; +import { mkdir, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; +import { promisify } from 'node:util'; + +import { + connect, + launchChrome, + sleep, + waitForPage, + waitForPort, +} from './pipelines_probe_cdp_lib.mjs'; +import { + assertName, + axNodes, + capture, + click, + enableSemantics, + waitFor, +} from './pipelines_probe_cdp_input.mjs'; +import { startWiringFixture } from './pipelines_wiring_probe_server.mjs'; + +const CHROME = + process.env.CHROME_PATH ?? + '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'; +const buildDir = resolve(process.argv[2] ?? 'build/wiring_web'); +const captureDir = resolve(process.argv[3] ?? 'p1-wire-captures'); +const fixture = await startWiringFixture({ root: buildDir, refuse: true }); +await mkdir(captureDir, { recursive: true }); +const profile = join(tmpdir(), `pipelines-wiring-chrome-${process.pid}`); +const chrome = launchChrome(CHROME, profile, 'about:blank'); +let connection; +const log = { url: fixture.url, captures: [], checks: [], states: [] }; + +const semanticText = () => + connection.evaluate(`(() => { + const chunks = []; + for (const el of document.querySelectorAll('flt-semantics')) { + const label = el.getAttribute('aria-label'); + if (label) chunks.push(label); + if (!el.children.length && el.innerText) chunks.push(el.innerText); + } + if (document.body?.innerText) chunks.push(document.body.innerText); + return [...new Set(chunks)].join('\\n'); + })()`); + +const assertBody = async (text) => { + const ok = await waitFor( + async () => (await semanticText()).includes(text), + 12000, + ); + if (!ok) { + throw new Error(`Missing text ${JSON.stringify(text)}:\n${(await semanticText()).slice(0, 3000)}`); + } + log.checks.push(`text: ${text}`); +}; + +const noBody = async (text) => { + if ((await semanticText()).includes(text)) { + throw new Error(`Unexpected text ${JSON.stringify(text)}`); + } + log.checks.push(`absent: ${text}`); +}; + +const state = async () => fixture.state(); + +const waitForState = async (check, label) => { + const value = await waitFor(async () => { + const current = await state(); + return check(current) ? current : false; + }, 12000); + if (!value) throw new Error(`Timed out waiting for ${label}: ${JSON.stringify(await state())}`); + log.states.push({ label, ...value }); + return value; +}; + +const ocr = async (path) => { + const { stdout } = await promisify(execFile)('tesseract', [path, 'stdout']); + return stdout; +}; + +const assertOcr = async (name, text) => { + const read = await ocr(join(captureDir, `${name}.png`)); + if (!read.toLowerCase().includes(text.toLowerCase())) { + throw new Error(`OCR of ${name} lacks ${JSON.stringify(text)}:\n${read.slice(0, 3000)}`); + } + log.checks.push(`ocr ${name}: ${text}`); +}; + +const navigate = async (url) => { + await connection.send('Page.navigate', { url }); + await waitFor( + () => connection.evaluate("document.querySelector('flutter-view') !== null"), + 20000, + ); + await sleep(1200); + await enableSemantics(connection); +}; + +try { + const devtoolsPort = await waitForPort(join(profile, 'DevToolsActivePort')); + const target = await waitForPage(devtoolsPort); + connection = await connect(target.webSocketDebuggerUrl); + await connection.send('Page.enable'); + await connection.send('Runtime.enable'); + await connection.send('DOM.enable'); + await connection.send('Accessibility.enable'); + await connection.send('Emulation.setDeviceMetricsOverride', { + width: 1200, + height: 900, + deviceScaleFactor: 1, + mobile: false, + }); + + // Material host: Linux platform, light mode. + await connection.send('Emulation.setUserAgentOverride', { + userAgent: + 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 ' + + '(KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36', + platform: 'Linux x86_64', + }); + await navigate(`${fixture.url}/pipelines`); + + // The first connection is refused: the honest gate must appear and nothing + // may be requested while there is no socket. + await assertBody('Pipelines server unavailable'); + const initial = await state(); + if (initial.listPipelines !== 0 || initial.listRuns !== 0 || initial.getPipeline !== 0) { + throw new Error(`Premature requests before connection: ${JSON.stringify(initial)}`); + } + log.checks.push('no requests before first connection'); + await capture(connection, captureDir, log, '01-gate-refused-material'); + await assertOcr('01-gate-refused-material', 'Pipelines server unavailable'); + + await fetch(`${fixture.url}/fixture/accept`, { method: 'POST' }); + await click(connection, 'Retry'); + await assertName(connection, 'Release verification', 'real pipeline row', log); + await assertName(connection, 'Nightly documentation', 'second real row', log); + await noBody('Pipelines — Not implemented'); + const loaded = await waitForState( + (value) => value.listPipelines >= 1 && value.listRuns >= 1, + 'pipeline list after retry', + ); + log.checks.push('shell lists real rows'); + await capture(connection, captureDir, log, '02-list-material'); + await assertOcr('02-list-material', 'Release verification'); + + await click(connection, 'Release verification'); + await assertName(connection, 'Content hash', 'real pipeline detail', log); + await capture(connection, captureDir, log, '03-detail-material'); + await assertOcr('03-detail-material', 'sha256:fixture-3-v3'); + + await click(connection, 'Source'); + await capture(connection, captureDir, log, '04-source-material'); + await assertOcr('04-source-material', 'name: Release verification'); + await assertOcr('04-source-material', 'type: model'); + await click(connection, 'Summary'); + await assertName(connection, 'Content hash', 'summary restored', log); + + // A drop keeps the open detail visible and, once the socket returns, the + // same list and detail are re-read without remounting or losing selection. + await fetch(`${fixture.url}/fixture/refuse`, { method: 'POST' }); + await assertBody('Reconnecting to Pipelines…'); + await assertName(connection, 'Content hash', 'detail retained after drop', log); + if ((await connection.evaluate('location.pathname')) !== '/pipelines') { + throw new Error(`Drop moved the route to ${await connection.evaluate('location.pathname')}`); + } + await capture(connection, captureDir, log, '05-drop-detail-retained-material'); + + await fetch(`${fixture.url}/fixture/accept`, { method: 'POST' }); + await click(connection, 'Retry'); + await waitForState( + (value) => + value.listPipelines > loaded.listPipelines && + value.getPipeline > loaded.getPipeline, + 'reconnect reload of list and open detail', + ); + await assertName(connection, 'Content hash', 'detail refreshed in place', log); + await noBody('Pipelines server unavailable'); + await capture(connection, captureDir, log, '06-reconnect-detail-refreshed-material'); + + // Cupertino host: macOS platform, dark appearance. + await connection.send('Emulation.setUserAgentOverride', { + userAgent: + 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 ' + + '(KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36', + platform: 'MacIntel', + }); + await connection.send('Emulation.setEmulatedMedia', { + features: [{ name: 'prefers-color-scheme', value: 'dark' }], + }); + await navigate(`${fixture.url}/pipelines`); + await assertName(connection, 'Release verification', 'cupertino dark row', log); + await noBody('Pipelines — Not implemented'); + await capture(connection, captureDir, log, '07-list-cupertino-dark'); + await assertOcr('07-list-cupertino-dark', 'Release verification'); + + await click(connection, 'Release verification'); + await assertName(connection, 'Content hash', 'cupertino dark detail', log); + await capture(connection, captureDir, log, '08-detail-cupertino-dark'); + await assertOcr('08-detail-cupertino-dark', 'Content hash'); + + await click(connection, 'Source'); + await capture(connection, captureDir, log, '09-source-cupertino-dark'); + await assertOcr('09-source-cupertino-dark', 'name: Release verification'); + await assertOcr('09-source-cupertino-dark', 'type: model'); + + const final = await state(); + if (final.connections < 1) throw new Error('No shared socket'); + log.checks.push('both native hosts rendered real rows, detail and source'); + log.final = final; +} catch (error) { + log.error = String(error?.stack ?? error); + try { + log.failureAx = (await axNodes(connection)) + .filter((node) => node.name?.value) + .map((node) => `${node.role?.value}: ${node.name.value}`) + .slice(0, 120); + } catch { + // The browser may already be gone; the error itself is still recorded. + } + process.exitCode = 1; +} finally { + await writeFile(join(captureDir, 'probe.json'), JSON.stringify(log, null, 2)); + connection?.close(); + chrome.kill('SIGTERM'); + await fixture.close(); +} diff --git a/app/tool/pipelines_wiring_probe_entry.dart b/app/tool/pipelines_wiring_probe_entry.dart new file mode 100644 index 00000000..b237c09a --- /dev/null +++ b/app/tool/pipelines_wiring_probe_entry.dart @@ -0,0 +1,8 @@ +import 'package:pipelines_app/application/bootstrap.dart'; + +/// Browser acceptance entrypoint for the Pipelines destination wiring. +/// +/// It is exactly the normal application composition; every reply comes from the +/// isolated loopback fixture in `tool/pipelines_wiring_probe_server.mjs`, not +/// from app-side fake data and not from a production server. +void main() => runPipelinesApp(); diff --git a/app/tool/pipelines_wiring_probe_server.mjs b/app/tool/pipelines_wiring_probe_server.mjs new file mode 100644 index 00000000..22f003b2 --- /dev/null +++ b/app/tool/pipelines_wiring_probe_server.mjs @@ -0,0 +1,394 @@ +import { createHash } from 'node:crypto'; +import { createServer } from 'node:http'; +import { readFile, realpath, stat } from 'node:fs/promises'; +import { extname, join, resolve, sep } from 'node:path'; +import { once } from 'node:events'; + +// Isolated loopback fixture for the Pipelines wiring probe. It serves the +// normal application composition and answers the read-only protocol with +// deterministic data. No production server, database or operator data. + +const MIME = { + '.html': 'text/html; charset=utf-8', + '.js': 'text/javascript; charset=utf-8', + '.mjs': 'text/javascript; charset=utf-8', + '.json': 'application/json; charset=utf-8', + '.wasm': 'application/wasm', + '.css': 'text/css; charset=utf-8', + '.png': 'image/png', + '.svg': 'image/svg+xml', + '.ico': 'image/x-icon', + '.ttf': 'font/ttf', + '.otf': 'font/otf', + '.woff': 'font/woff', + '.woff2': 'font/woff2', +}; + +const PIPELINES = [ + { + id: 3, + name: 'Release verification', + version: 3, + stages: 4, + created_at: '2026-09-28T10:12:00', + updated_at: '2026-10-21T09:40:00', + scheduled: true, + schedule_count: 2, + enabled_schedule_count: 1, + }, + { + id: 7, + name: 'Nightly documentation', + version: 1, + stages: 2, + created_at: '2026-10-02T18:20:00', + updated_at: '2026-10-20T22:05:00', + scheduled: true, + schedule_count: 1, + enabled_schedule_count: 1, + }, +]; + +const RUNS = [ + { + id: 488, + pipeline_id: 3, + status: 'succeeded', + created_at: '2026-10-21T09:30:00', + finished_at: '2026-10-21T09:34:12', + executing: false, + }, + { + id: 487, + pipeline_id: 7, + status: 'running', + created_at: '2026-10-21T09:20:00', + finished_at: '', + executing: true, + }, +]; + +const VERSIONS = [ + { version: 1, stages: 2, created_at: '2026-09-28T10:12:00' }, + { version: 2, stages: 3, created_at: '2026-10-08T15:44:00' }, + { version: 3, stages: 4, created_at: '2026-10-21T09:12:00' }, +]; + +const SOURCE = `name: Release verification +stages: + inspect: + type: model + output: report + verify: + type: model + output: verdict +`; + +const SOURCE_V2 = `${SOURCE} # selected version 2 +`; + +function detail(id, requestedVersion) { + const summary = PIPELINES.find((pipeline) => pipeline.id === id) ?? PIPELINES[0]; + const versions = id === 3 ? VERSIONS : VERSIONS.slice(0, 1); + const latest = versions[versions.length - 1].version; + const version = requestedVersion > 0 ? requestedVersion : latest; + return { + ...summary, + version, + stages: versions.find((row) => row.version === version)?.stages ?? summary.stages, + latest_version: id === 3 ? latest : 1, + version_created_at: + versions.find((row) => row.version === version)?.created_at ?? summary.created_at, + content_hash: `sha256:fixture-${id}-v${version}`, + source: id === 3 && version === 2 ? SOURCE_V2 : SOURCE, + versions, + }; +} + +function accept(key) { + return createHash('sha1') + .update(`${key}258EAFA5-E914-47DA-95CA-C5AB0DC85B11`) + .digest('base64'); +} + +function frame(opcode, payload) { + const length = payload.length; + let header; + if (length < 126) { + header = Buffer.from([0x80 | opcode, length]); + } else if (length < 65536) { + header = Buffer.alloc(4); + header[0] = 0x80 | opcode; + header[1] = 126; + header.writeUInt16BE(length, 2); + } else { + header = Buffer.alloc(10); + header[0] = 0x80 | opcode; + header[1] = 127; + header.writeBigUInt64BE(BigInt(length), 2); + } + return Buffer.concat([header, payload]); +} + +class Connection { + constructor(socket, owner) { + this.socket = socket; + this.owner = owner; + this.buffer = Buffer.alloc(0); + this.fragments = []; + this.fragmentOpcode = 0; + } + + push(chunk) { + if (chunk?.length) this.buffer = Buffer.concat([this.buffer, chunk]); + this.parse(); + } + + parse() { + while (this.buffer.length >= 2) { + const first = this.buffer[0]; + const second = this.buffer[1]; + const fin = (first & 0x80) !== 0; + const opcode = first & 0x0f; + const masked = (second & 0x80) !== 0; + let length = second & 0x7f; + let offset = 2; + if (length === 126) { + if (this.buffer.length < 4) return; + length = this.buffer.readUInt16BE(2); + offset = 4; + } else if (length === 127) { + if (this.buffer.length < 10) return; + length = Number(this.buffer.readBigUInt64BE(2)); + offset = 10; + } + const maskOffset = offset; + if (masked) { + if (this.buffer.length < offset + 4) return; + offset += 4; + } + if (this.buffer.length < offset + length) return; + let payload = Buffer.from(this.buffer.subarray(offset, offset + length)); + if (masked) { + const mask = this.buffer.subarray(maskOffset, maskOffset + 4); + for (let index = 0; index < payload.length; index++) { + payload[index] ^= mask[index % 4]; + } + } + this.buffer = this.buffer.subarray(offset + length); + this.handleFrame(fin, opcode, payload); + } + } + + handleFrame(fin, opcode, payload) { + if (opcode === 0x8) return this.close(); + if (opcode === 0x9) return void this.socket.write(frame(0x0a, payload)); + if (opcode === 0x0a) return; + if (opcode === 0x0) { + this.fragments.push(payload); + if (fin) { + const data = Buffer.concat(this.fragments); + this.fragments = []; + this.message(this.fragmentOpcode, data); + } + return; + } + if (opcode !== 0x1) return; + if (!fin) { + this.fragmentOpcode = opcode; + this.fragments = [payload]; + return; + } + this.message(opcode, payload); + } + + message(_opcode, payload) { + let request; + try { + request = JSON.parse(payload.toString('utf8')); + } catch { + return; + } + this.owner.onMessage(this, request); + } + + send(value) { + if (!this.socket.destroyed) { + this.socket.write(frame(0x1, Buffer.from(JSON.stringify(value)))); + } + } + + close() { + if (!this.socket.destroyed) this.socket.end(); + } +} + +async function staticFile(base, pathname, req, res) { + let file = resolve(base, `.${pathname}`); + if (file !== base && !file.startsWith(base + sep)) { + res.writeHead(403).end(); + return; + } + try { + if ((await stat(file)).isDirectory()) file = join(file, 'index.html'); + } catch { + if (extname(pathname)) { + res.writeHead(404).end('not found'); + return; + } + file = join(base, 'index.html'); + } + try { + const body = await readFile(file); + res + .writeHead(200, { + 'content-type': MIME[extname(file)] ?? 'application/octet-stream', + 'cache-control': 'no-store', + }) + .end(req.method === 'HEAD' ? undefined : body); + } catch { + res.writeHead(404).end('not found'); + } +} + +export async function startWiringFixture({ root, refuse = false }) { + const base = await realpath(root); + const connections = new Set(); + const sockets = new Set(); + const counts = { subscribed: 0, listPipelines: 0, listRuns: 0, getPipeline: 0, dropped: 0 }; + let refusing = refuse; + + const dropConnections = () => { + for (const connection of connections) connection.close(); + connections.clear(); + counts.dropped++; + }; + + const server = createServer(async (req, res) => { + const pathname = new URL(req.url, 'http://fixture').pathname; + if (pathname === '/fixture/drop' && req.method === 'POST') { + dropConnections(); + res.writeHead(200).end('{"ok":true}'); + return; + } + if (pathname === '/fixture/refuse' && req.method === 'POST') { + refusing = true; + dropConnections(); + res.writeHead(200).end('{"ok":true}'); + return; + } + if (pathname === '/fixture/accept' && req.method === 'POST') { + refusing = false; + res.writeHead(200).end('{"ok":true}'); + return; + } + if (pathname === '/fixture/state') { + res + .writeHead(200, { 'content-type': 'application/json' }) + .end(JSON.stringify({ ...counts, connections: connections.size, refusing })); + return; + } + if (req.method !== 'GET' && req.method !== 'HEAD') { + res.writeHead(405).end(); + return; + } + await staticFile(base, pathname, req, res); + }); + + server.on('upgrade', (req, socket, head) => { + if (refusing) { + socket.end('HTTP/1.1 503 Service Unavailable\r\nConnection: close\r\n\r\n'); + return; + } + const url = new URL(req.url, 'http://fixture'); + if ( + url.pathname !== '/connect' || + req.headers.upgrade?.toLowerCase() !== 'websocket' || + !req.headers['sec-websocket-key'] + ) { + socket.end('HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n'); + return; + } + socket.write( + 'HTTP/1.1 101 Switching Protocols\r\n' + + 'Upgrade: websocket\r\n' + + 'Connection: Upgrade\r\n' + + `Sec-WebSocket-Accept: ${accept(req.headers['sec-websocket-key'])}\r\n\r\n`, + ); + const connection = new Connection(socket, { + onMessage: (client, request) => { + switch (request.type) { + case 'subscribe': + counts.subscribed++; + return; + case 'unsubscribe': + return; + case 'list_pipelines': + counts.listPipelines++; + client.send({ id: request.id, type: 'pipelines', pipelines: PIPELINES }); + return; + case 'list_runs': + counts.listRuns++; + client.send({ id: request.id, type: 'runs', runs: RUNS }); + return; + case 'get_pipeline': { + counts.getPipeline++; + const id = request.pipeline_id; + if (!PIPELINES.some((pipeline) => pipeline.id === id)) { + client.send({ + id: request.id, + type: 'error', + error: `Fixture pipeline ${id} is unavailable`, + }); + return; + } + client.send({ + id: request.id, + type: 'pipeline', + detail: detail(id, request.version), + }); + return; + } + case 'ping': + client.send({ + id: request.id, + type: 'pong', + build: { version: 'Fixture wiring build' }, + time: '2026-10-21T12:00:00Z', + }); + return; + default: + client.send({ + id: request.id, + type: 'error', + error: `Fixture does not implement ${request.type}`, + }); + } + }, + }); + connections.add(connection); + socket.on('data', (chunk) => connection.push(chunk)); + socket.on('close', () => connections.delete(connection)); + socket.on('error', () => connections.delete(connection)); + connection.push(head); + }); + + server.listen(0, '127.0.0.1'); + await once(server, 'listening'); + server.on('connection', (socket) => { + sockets.add(socket); + socket.on('close', () => sockets.delete(socket)); + }); + + return { + server, + url: `http://127.0.0.1:${server.address().port}`, + state: async () => (await fetch(`http://127.0.0.1:${server.address().port}/fixture/state`)).json(), + close: () => + new Promise((resolveClose) => { + for (const connection of connections) connection.close(); + server.close(() => resolveClose()); + for (const socket of sockets) socket.destroy(); + }), + }; +} From b6ed1689d9df2e1c7c33959489015c2f9367b0b8 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 19:49:09 +0100 Subject: [PATCH 02/10] docs(app): record the landed pipelines candidate and merge verification --- app/notes/P1-wire.md | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/app/notes/P1-wire.md b/app/notes/P1-wire.md index 968b1576..1adaf349 100644 --- a/app/notes/P1-wire.md +++ b/app/notes/P1-wire.md @@ -135,7 +135,9 @@ node tool/pipelines_wiring_probe.mjs - No production server, real operator chat/run or authenticated preview was touched; all browser data comes from the isolated loopback fixture. - Android and iOS were not built, installed or run; mobile remains unverified. -- No commit, push, deployment or preview-service change was made. +- No push, deployment or preview-service change was made. The Land stage + committed the reviewed candidate on `flutter/p1-wire` and merged `main` + into it (see Landing below). - No Material/Cupertino fixed sizes, palette or font overrides were added. The only fixed breakpoint remains the existing `kPipelinesWideBreakpoint`. @@ -155,3 +157,18 @@ Tracked changes (`git diff --numstat`): New files: `connection_status.dart` (195), `pipelines_destination.dart` (61), three test files and three probe files. Net production change is ~120 added lines after moving the shared chrome out of `runs_destination.dart`. + +## Landing + +- Committed the reviewed work as `8476cfd7 feat(app): wire the native + pipelines browser on the shared session` (15 paths, no unrelated files). +- Merged local `main` (`7be4456f`) into `flutter/p1-wire` with no conflicts; + the merge brought in the native run rename work only (`app/WORK.md`, + `lib/features/runs/**`, `notes/R2-title-wire.md`, its tests and probe). +- Post-merge checks on the merged candidate: `flutter analyze` clean, + `flutter test` **599 passed**, `dart format` 274 files 0 changed, + `node --check` on both probe scripts, `flutter build web` built, and the + Chrome wiring probe again reported **25 checks, 9 captures**, no error, + final `{subscribed:3, listPipelines:3, listRuns:3, getPipeline:3, + dropped:1, connections:1}`. The 595 in the table above is the pre-merge + branch count; the extra 4 tests are the merged rename coverage. From 76437db01879d3812b556f5f19d08ed3d7df1099 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 20:04:38 +0100 Subject: [PATCH 03/10] feat(app): add chat thread controller for live conversations Owns one open chat session: subscribes with chat_subscribe, reads the newest history page, folds only this session's chat_event frames, pages older history with the opaque cursor, and replaces the held turn on resync. Failures keep the held transcript and surface an error; disposal only cancels the local stream. Co-authored-by: C2 pipeline --- .../conversation/chat_thread_controller.dart | 230 ++++++++++++++++++ app/notes/C2-thread.md | 38 +++ .../chat_thread_controller_test.dart | 154 ++++++++++++ .../conversation/chat_thread_fixtures.dart | 73 ++++++ .../conversation/chat_thread_live_test.dart | 188 ++++++++++++++ 5 files changed, 683 insertions(+) create mode 100644 app/lib/features/chat/conversation/chat_thread_controller.dart create mode 100644 app/notes/C2-thread.md create mode 100644 app/test/features/chat/conversation/chat_thread_controller_test.dart create mode 100644 app/test/features/chat/conversation/chat_thread_fixtures.dart create mode 100644 app/test/features/chat/conversation/chat_thread_live_test.dart diff --git a/app/lib/features/chat/conversation/chat_thread_controller.dart b/app/lib/features/chat/conversation/chat_thread_controller.dart new file mode 100644 index 00000000..0864c8c2 --- /dev/null +++ b/app/lib/features/chat/conversation/chat_thread_controller.dart @@ -0,0 +1,230 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; + +import '../../../core/api_gateway.dart'; +import '../data/chat_repository.dart'; +import '../domain/chat_transcript.dart'; + +/// One open conversation's transcript and live turn state. +/// +/// The controller attaches to exactly one session: it subscribes that session +/// with `chat_subscribe`, then reads the newest history page. Pushed frames for +/// any other session are ignored, a superseded or disposed read never lands, and +/// a reconnect/resync replaces the held turn with the newest authoritative page +/// instead of merging stale state. The server detaches subscriptions when the +/// socket closes, so disposal only cancels the local stream (there is no +/// `chat_unsubscribe`). +class ChatThreadController extends ChangeNotifier { + ChatThreadController(this.gateway, this.sessionId) { + _subscription = gateway.frames.listen(_onFrame); + } + + final ApiGateway gateway; + final String sessionId; + late final ChatRepository _repository = ChatRepository(gateway); + StreamSubscription? _subscription; + + List _messages = const []; + bool _running = false; + bool _loaded = false; + bool _loading = false; + bool _hasMore = false; + String _cursor = ''; + String _nativeTurnId = ''; + String? _error; + + bool _subscribed = false; + bool _disposed = false; + int _generation = 0; + bool _resyncing = false; + bool _resyncAgain = false; + + List get messages => _messages; + bool get running => _running; + bool get loaded => _loaded; + bool get loading => _loading; + bool get hasMore => _hasMore; + + /// The server's opaque older-page cursor. Never interpreted, only passed back. + String get cursor => _cursor; + String? get error => _error; + + /// Subscribes this session, then loads its newest history page. + Future load() async { + if (_disposed) return; + final token = ++_generation; + _loading = true; + _error = null; + _notify(); + await _attach(); + if (!_owned(token)) return; + await _readNewest(token, replaceHeldTurn: false); + } + + /// Reads the next older page. Only offered while the server says `has_more`; + /// the cursor is the server's own `next_cursor`, passed back verbatim. + Future loadOlder() async { + if (_disposed || _loading || !_hasMore) return; + final token = ++_generation; + _loading = true; + _error = null; + _notify(); + try { + final page = await _repository.history( + sessionId, + cursor: _cursor, + limit: 200, + ); + if (!_owned(token)) return; + final merged = mergeChatHistory( + {'messages': _messages}, + page, + older: true, + ); + _applyPage(merged); + } catch (error) { + if (!_owned(token)) return; + _loading = false; + _error = '$error'; + } + _notify(); + } + + /// The reconnect/resync repair: settle the held turn, re-attach the session, + /// then replace the conversation with the newest authoritative page. Activity + /// replayed while re-attaching (a running step, a form) is fresh native state + /// and survives the replacement. A resync frame also lands here. + Future resync() async { + if (_disposed) return; + if (_resyncing) { + _resyncAgain = true; + return; + } + _resyncing = true; + do { + _resyncAgain = false; + await _resyncOnce(); + } while (_resyncAgain && !_disposed); + _resyncing = false; + } + + Future _resyncOnce() async { + final token = ++_generation; + // A socket drop removed the frames feeding the turn, so no held turn may + // keep claiming to run until the re-subscribe proves otherwise. + _running = false; + _nativeTurnId = ''; + _notify(); + await _attach(force: true); + if (!_owned(token)) return; + await _readNewest(token, replaceHeldTurn: true); + } + + Future _readNewest(int token, {required bool replaceHeldTurn}) async { + try { + final page = await _repository.history(sessionId, limit: 200); + if (!_owned(token)) return; + if (replaceHeldTurn) { + _messages = (page['messages'] as List? ?? const []) + .whereType() + .map((message) => Map.from(message)) + .toList(); + _cursor = '${page['nextCursor'] ?? ''}'; + _hasMore = page['hasMore'] == true; + } else { + // A live frame may have arrived while the page was loading; merge it + // over the held transcript instead of replacing it. + _applyPage(mergeChatHistory({'messages': _messages}, page)); + } + _loaded = true; + _loading = false; + _error = null; + } catch (error) { + if (!_owned(token)) return; + // A refused read is not an empty successful history: the reason stays + // visible and the held transcript is kept. + _loaded = true; + _loading = false; + _error = '$error'; + } + _notify(); + } + + /// Attaches the session stream once per connection. A refusal leaves history + /// usable (the live stream is simply not attached) and is retried on resync. + Future _attach({bool force = false}) async { + if (_disposed || (_subscribed && !force)) return; + try { + await _repository.subscribe(sessionId); + if (_disposed) return; + _subscribed = true; + } catch (_) { + // The history path remains usable; resync re-attempts the subscribe. + if (_disposed) return; + _subscribed = false; + } + } + + void _onFrame(JsonMap envelope) { + if (_disposed) return; + final body = _eventBody(envelope); + if (body == null || body['session_id'] != sessionId) return; + if (body['kind'] == 'resync') { + unawaited(resync()); + return; + } + final current = _thread; + final next = applyChatEvent(current, body); + if (identical(next, current)) return; + _messages = (next['messages'] as List? ?? const []) + .whereType() + .map((message) => Map.from(message)) + .toList(); + _running = next['running'] == true; + _nativeTurnId = '${next['nativeTurnId'] ?? ''}'; + _notify(); + } + + /// The pushed envelope body, or null for another message type. The server + /// wraps `chat_event` in the typed envelope; domain code never sees the + /// transport fields. + JsonMap? _eventBody(JsonMap envelope) { + if (envelope['type'] != 'chat_event') return null; + final body = envelope['chat_event']; + if (body is! Map) return null; + return Map.from(body); + } + + JsonMap get _thread => { + 'sessionId': sessionId, + 'messages': _messages, + 'running': _running, + 'nativeTurnId': _nativeTurnId, + }; + + void _applyPage(JsonMap page) { + _messages = (page['messages'] as List? ?? const []) + .whereType() + .map((message) => Map.from(message)) + .toList(); + _cursor = '${page['nextCursor'] ?? ''}'; + _hasMore = page['hasMore'] == true; + _loaded = true; + _loading = false; + } + + bool _owned(int token) => !_disposed && token == _generation; + + void _notify() { + if (!_disposed) notifyListeners(); + } + + @override + void dispose() { + _disposed = true; + _generation++; + unawaited(_subscription?.cancel()); + super.dispose(); + } +} diff --git a/app/notes/C2-thread.md b/app/notes/C2-thread.md new file mode 100644 index 00000000..cd5f048a --- /dev/null +++ b/app/notes/C2-thread.md @@ -0,0 +1,38 @@ +# C2 — Chat thread controller + +`lib/features/chat/conversation/chat_thread_controller.dart` owns one open +conversation without any UI. It is constructed with the shared `ApiGateway` and +one `sessionId`, reuses `ChatRepository` for the wire and +`domain/chat_transcript.dart` for the fold, and exposes `messages`, `running`, +`loaded`, `loading`, `hasMore`, `cursor` and `error` through +`ChangeNotifier`. + +Behaviour: + +- `load()` calls `chat_subscribe` with the exact session body, then reads the + newest `chat_messages` page with `limit: 200` and an empty cursor. A refused + subscribe leaves history usable. +- `loadOlder()` is explicit only, requires `hasMore`, passes the server's opaque + `next_cursor` back verbatim, and prepends the older page by id. +- Only `chat_event` envelopes for this session are folded; replayed/live + text, reasoning, tool, step and user frames use the existing domain fold, so + unknown message and part fields survive. +- `resync()` settles the held turn, re-subscribes, then replaces the transcript, + cursor and `hasMore` with the newest authoritative page. Activity replayed + while re-attaching (for example a running step) survives the replacement. A + pushed `resync` event invokes the same path. +- History failures set `error` and keep the held transcript; they are never + reported as an empty success. Superseded reads and replies after disposal are + ignored. +- Disposal cancels only the local stream subscription. There is no + `chat_unsubscribe` request. + +Checks (run from `app/`): + +- `flutter test test/features/chat/conversation` — 10 tests passed. +- `flutter test test/features/chat` — 43 tests passed. +- `flutter analyze lib/features/chat test/features/chat` — no issues. + +Not done: the controller is not yet wired to a screen, so there is no rendered +or browser change to capture; mobile builds and device verification were not +performed. No shared domain, shell, main, pubspec or server files changed. diff --git a/app/test/features/chat/conversation/chat_thread_controller_test.dart b/app/test/features/chat/conversation/chat_thread_controller_test.dart new file mode 100644 index 00000000..d429a8ae --- /dev/null +++ b/app/test/features/chat/conversation/chat_thread_controller_test.dart @@ -0,0 +1,154 @@ +import 'dart:async'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_thread_controller.dart'; + +import 'chat_thread_fixtures.dart'; + +void main() { + late FakeChatGateway gateway; + late ChatThreadController controller; + + setUp(() { + gateway = FakeChatGateway(); + controller = ChatThreadController(gateway, 's'); + }); + + tearDown(() { + controller.dispose(); + gateway.close(); + }); + + test( + 'subscribes the exact session, then reads newest history with all data', + () async { + final unknown = chatMessage( + 'a', + 'assistant', + parts: [ + { + 'type': 'future_part', + 'id': 'p1', + 'payload': {'nested': true}, + 'unknown_field': 7, + }, + ], + )..['future_message_field'] = 'keep'; + gateway.history = (_) async => + chatPage([unknown], cursor: 'opaque/next?x=1', hasMore: true); + + await controller.load(); + + expect(gateway.calls.map((call) => call.type), [ + 'chat_subscribe', + 'chat_messages', + ]); + expect(gateway.calls.first.fields, { + 'chat_subscribe': {'session_id': 's'}, + }); + expect(gateway.calls.last.fields['chat_query'], { + 'session_id': 's', + 'limit': 200, + 'cursor': '', + }); + expect(controller.loaded, isTrue); + expect(controller.loading, isFalse); + expect(controller.error, isNull); + expect(controller.running, isFalse); + expect(controller.hasMore, isTrue); + expect(controller.cursor, 'opaque/next?x=1'); + expect(controller.messages.single, unknown); + expect(controller.messages.single['future_message_field'], 'keep'); + }, + ); + + test( + 'loadOlder passes the opaque cursor back and prepends the page', + () async { + gateway.history = (_) async => chatPage( + [chatMessage('b', 'user')], + cursor: 'older-1', + hasMore: true, + ); + await controller.load(); + + final olderReply = Completer(); + gateway.history = (_) => olderReply.future; + final loadingStates = []; + controller.addListener(() => loadingStates.add(controller.loading)); + final older = controller.loadOlder(); + + expect(gateway.calls.last.fields['chat_query'], { + 'session_id': 's', + 'limit': 200, + 'cursor': 'older-1', + }); + expect(controller.loading, isTrue); + expect(loadingStates, [true]); + olderReply.complete( + chatPage( + [chatMessage('a', 'assistant')], + cursor: 'last', + hasMore: false, + ), + ); + await older; + + expect(controller.messages.map((item) => item['id']), ['a', 'b']); + expect(controller.cursor, 'last'); + expect(controller.hasMore, isFalse); + expect(controller.loading, isFalse); + }, + ); + + test( + 'a superseded history reply never replaces the newer transcript', + () async { + final first = Completer(); + final second = Completer(); + var request = 0; + gateway.history = (_) => request++ == 0 ? first.future : second.future; + + final stale = controller.load(); + await pumpEventQueue(); + final current = controller.load(); + await pumpEventQueue(); + second.complete(chatPage([chatMessage('new', 'user')])); + await current; + expect(controller.messages.single['id'], 'new'); + + first.complete(chatPage([chatMessage('old', 'user')])); + await stale; + expect(controller.messages.single['id'], 'new'); + expect(controller.loaded, isTrue); + expect(controller.loading, isFalse); + }, + ); + + test( + 'a failed history read reports the error, never an empty success', + () async { + gateway.history = (_) => Future.error(StateError('history unavailable')); + + await controller.load(); + + expect(controller.error, contains('history unavailable')); + expect(controller.error, isNot('')); + expect(controller.messages, isEmpty); + expect(controller.loading, isFalse); + expect(controller.loaded, isTrue); + }, + ); + + test('a refused subscribe leaves history usable', () async { + gateway.subscribe = () => Future.error(StateError('not live')); + gateway.history = (_) async => chatPage([chatMessage('a', 'user')]); + + await controller.load(); + + expect(controller.messages.single['id'], 'a'); + expect(controller.error, isNull); + expect(controller.loaded, isTrue); + }); +} diff --git a/app/test/features/chat/conversation/chat_thread_fixtures.dart b/app/test/features/chat/conversation/chat_thread_fixtures.dart new file mode 100644 index 00000000..94cdaf46 --- /dev/null +++ b/app/test/features/chat/conversation/chat_thread_fixtures.dart @@ -0,0 +1,73 @@ +import 'dart:async'; + +import 'package:pipelines_app/core/api_gateway.dart'; + +/// A fake gateway whose subscribe/history replies the test controls. +class FakeChatGateway implements ApiGateway { + final calls = <({String type, JsonMap fields})>[]; + final historyRequests = >[]; + final _frames = StreamController.broadcast(); + Future Function(JsonMap fields)? history; + Future Function()? subscribe; + void Function()? onSubscribe; + + @override + Future call(String type, [JsonMap fields = const {}]) async { + calls.add((type: type, fields: fields)); + switch (type) { + case 'chat_subscribe': + onSubscribe?.call(); + return subscribe == null ? {} : subscribe!(); + case 'chat_messages': + final completer = Completer(); + historyRequests.add(completer); + if (history != null) return history!(fields); + return completer.future; + } + return {}; + } + + @override + Stream get frames => _frames.stream; + + void emitEvent(JsonMap body) { + _frames.add({'type': 'chat_event', 'chat_event': body}); + } + + void emitRaw(JsonMap envelope) => _frames.add(envelope); + + void close() => _frames.close(); +} + +JsonMap chatPage( + List messages, { + String cursor = '', + bool hasMore = false, +}) => { + 'chat_history': { + 'messages': messages, + 'next_cursor': cursor, + 'has_more': hasMore, + }, +}; + +JsonMap chatMessage(String id, String role, {List parts = const []}) => + {'id': id, 'role': role, 'parts': parts}; + +JsonMap chatTextFrame( + String text, { + String session = 's', + String messageId = 'a', +}) => { + 'session_id': session, + 'message_id': messageId, + 'kind': 'text', + 'part': {'id': 'p', 'type': 'text'}, + 'delta': text, +}; + +JsonMap chatStepFrame(String status, {String session = 's'}) => { + 'session_id': session, + 'kind': 'step', + 'step': {'status': status, 'turn_id': 'turn', 'intermediate': false}, +}; diff --git a/app/test/features/chat/conversation/chat_thread_live_test.dart b/app/test/features/chat/conversation/chat_thread_live_test.dart new file mode 100644 index 00000000..436260a6 --- /dev/null +++ b/app/test/features/chat/conversation/chat_thread_live_test.dart @@ -0,0 +1,188 @@ +import 'dart:async'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_thread_controller.dart'; + +import 'chat_thread_fixtures.dart'; + +void main() { + late FakeChatGateway gateway; + late ChatThreadController controller; + + setUp(() { + gateway = FakeChatGateway(); + controller = ChatThreadController(gateway, 's'); + }); + + tearDown(() { + controller.dispose(); + gateway.close(); + }); + + test('folds own session frames only and keeps live turn activity', () async { + gateway.history = (_) async => chatPage([ + chatMessage( + 'a', + 'assistant', + parts: [ + {'type': 'reasoning', 'id': 'r', 'text': 'held'}, + ], + ), + ]); + await controller.load(); + var notifications = 0; + controller.addListener(() => notifications++); + + gateway.emitEvent(chatTextFrame('foreign', session: 'other')); + gateway.emitEvent(chatTextFrame('nodata')..remove('session_id')); + gateway.emitRaw({'type': 'run_event', 'session_id': 's'}); + await pumpEventQueue(); + expect(notifications, 0); + expect(controller.messages.single['parts'], [ + {'type': 'reasoning', 'id': 'r', 'text': 'held'}, + ]); + expect(controller.running, isFalse); + + gateway.emitEvent(chatTextFrame('one')); + gateway.emitEvent(chatTextFrame(' two')); + await pumpEventQueue(); + expect(controller.running, isTrue); + expect(controller.messages.single['parts'], [ + {'type': 'reasoning', 'id': 'r', 'text': 'held'}, + {'type': 'text', 'id': 'p', 'text': 'one two'}, + ]); + + gateway.emitEvent(chatStepFrame('ended')); + await pumpEventQueue(); + expect(controller.running, isFalse); + expect(notifications, greaterThan(0)); + }); + + test( + 'resync re-subscribes, settles the held turn, and replaces it with the page', + () async { + gateway.history = (_) async => chatPage( + [ + chatMessage('stale-user', 'user'), + chatMessage('stale-assistant', 'assistant'), + ], + cursor: 'stale-cursor', + hasMore: true, + ); + await controller.load(); + gateway.emitEvent(chatTextFrame('still running')); + await pumpEventQueue(); + expect(controller.running, isTrue); + + gateway.onSubscribe = () { + // Settled before the re-attach, then replay proves the fresh turn. + expect(controller.running, isFalse); + gateway.emitEvent(chatStepFrame('started')); + }; + gateway.history = (_) async => chatPage( + [ + chatMessage('fresh-user', 'user'), + chatMessage('fresh-assistant', 'assistant'), + ], + cursor: 'fresh-cursor', + hasMore: false, + ); + + await controller.resync(); + await pumpEventQueue(); + + expect( + gateway.calls.where((call) => call.type == 'chat_subscribe').length, + 2, + ); + expect( + gateway.calls.where((call) => call.type == 'chat_messages').length, + 2, + ); + expect(gateway.calls.last.fields['chat_query'], { + 'session_id': 's', + 'limit': 200, + 'cursor': '', + }); + expect(controller.messages.map((item) => item['id']), [ + 'fresh-user', + 'fresh-assistant', + ]); + expect(controller.cursor, 'fresh-cursor'); + expect(controller.hasMore, isFalse); + expect(controller.running, isTrue); + expect(controller.error, isNull); + }, + ); + + test( + 'a failed resync keeps replayed activity and reports the error', + () async { + var attempt = 0; + gateway.history = (_) async { + attempt++; + if (attempt == 1) return chatPage([chatMessage('held', 'user')]); + throw StateError('resync unavailable'); + }; + await controller.load(); + gateway.onSubscribe = () { + gateway.emitEvent(chatStepFrame('started')); + }; + + await controller.resync(); + await pumpEventQueue(); + + expect(controller.messages.single['id'], 'held'); + expect(controller.running, isTrue); + expect(controller.error, contains('resync unavailable')); + expect(controller.loading, isFalse); + }, + ); + + test( + 'a resync frame reattaches and replaces the new authoritative page', + () async { + var attempt = 0; + gateway.history = (_) async => attempt++ == 0 + ? chatPage([chatMessage('held', 'user')], hasMore: true) + : chatPage([chatMessage('fresh', 'assistant')]); + await controller.load(); + + gateway.emitEvent({'session_id': 's', 'kind': 'resync'}); + await pumpEventQueue(); + + expect( + gateway.calls.where((call) => call.type == 'chat_subscribe').length, + 2, + ); + expect(controller.messages.single['id'], 'fresh'); + expect(controller.hasMore, isFalse); + }, + ); + + test( + 'disposal ignores a late reply and never invents an unsubscribe', + () async { + final pending = Completer(); + gateway.history = (_) => pending.future; + var notifications = 0; + controller.addListener(() => notifications++); + final load = controller.load(); + await pumpEventQueue(); + final before = notifications; + + controller.dispose(); + pending.complete(chatPage([chatMessage('late', 'user')])); + await load; + + expect(notifications, before); + expect( + gateway.calls.where((call) => call.type == 'chat_unsubscribe'), + isEmpty, + ); + // Keep tearDown's dispose idempotent. + controller = ChatThreadController(gateway, 's'); + }, + ); +} From e20ac9f5a1ffbcd49b13176aed06ebff0eba1aa5 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 20:04:38 +0100 Subject: [PATCH 04/10] feat(app): wire native cancel and track complete port acceptance --- app/PARITY.md | 75 +++++++++++++++ .../features/runs/ui/run_detail_actions.dart | 28 ++++++ .../runs/ui/run_detail_cupertino.dart | 4 +- .../features/runs/ui/run_detail_material.dart | 4 +- app/lib/features/runs/ui/run_detail_view.dart | 8 +- app/lib/features/runs/ui/runs_controller.dart | 22 ++++- app/notes/R2-cancel-wire.md | 23 +++++ .../runs/ui/run_cancel_wiring_test.dart | 93 +++++++++++++++++++ app/tool/runs_probe.mjs | 26 ++++++ app/tool/runs_probe_server.mjs | 25 ++++- 10 files changed, 295 insertions(+), 13 deletions(-) create mode 100644 app/PARITY.md create mode 100644 app/lib/features/runs/ui/run_detail_actions.dart create mode 100644 app/notes/R2-cancel-wire.md create mode 100644 app/test/features/runs/ui/run_cancel_wiring_test.dart diff --git a/app/PARITY.md b/app/PARITY.md new file mode 100644 index 00000000..f522df5a --- /dev/null +++ b/app/PARITY.md @@ -0,0 +1,75 @@ +# Flutter port acceptance + +Target: current `web/src/` behavior and latest entries in `web/PARITY.md`, NOT +web CSS. Native Material/Cupertino controls, typography, semantic colours and +content-driven sizing take precedence over visual-review styling suggestions. +`WORK.md` is the run/commit queue; this file tracks what remains for a full port. + +## Evidence vocabulary + +- **Preview**: registered in the normal app and published to8096, with fixture + browser interaction/captures. This does NOT imply live production mutations. +- **Source**: landed/tested reusable code, not a delivered screen. +- **Active**: assigned implementation, not accepted or deployed. +- **Missing**: still required; no implied fallback or scope waiver. + +Live authenticated data, OS sharing/notifications and Android/iOS device behavior +remain unverified unless explicitly recorded. Test mutations use isolated fakes +or scratch servers only, never real operator sessions/runs/workflows. + +## Functional inventory + +| Area | Current state | Remaining acceptance | +| --- | --- | --- | +| Shared transport/settings connection | Preview | foreground recovery, persisted endpoint boot, protocol warning, complete refresh semantics | +| Native shell/run URLs | Preview | pipeline/version/stage/template/chat URLs, action/visit queries and native deep-link handling | +| Pipeline list/filter/sort/detail/source/versions | Preview | latest summary metadata/miniatures, pinned detail URLs | +| Definition graph | Source nodes/layout/routes/edges; active canvas71 | compose measured native nodes+labels, graph tab, pan/zoom, expanded view, definition stage pane | +| Start a pipeline | Missing | native prompt/workspace/notify dialog, exact pinned run request, response-loss intent | +| Templates | Source repository; active create dialog73 | gallery/detail/source, Settings entry, validate/create-only dialog integration and refresh | +| Runs list/filter/sort/live fold | Preview | full time/status/provenance filters, recency/day groups, shell live/attention state | +| Run detail/input/output/copy/metrics | Preview | latest summary tabs/fields and exact empty/unknown states | +| Rename run | Preview | verified exact accepted title fold; no live production mutation tested | +| Cancel run | Preview | exact confirm/server-accepted detail+list fold; production cancellation not tested | +| Retry/restart | Source actions/dialogs | actual detail controls, accepted new-run navigation, stale/refusal handling | +| Human decisions | Source action/dialog | waiting card, exact recorded options/feedback, attention/action URL entry | +| Run graph | Source projection/visits | executed/unvisited routes, live activity, graph clicks open latest RECORDED visit, no definition by default | +| Timeline/recorded visit pane | Preview text rows only | visit selection, status/outcome/duration/model/target/verdict, artifacts/session/input/output/definition tabs | +| Changes/diffs | Source; active detail wiring67 | settled-run aggregate gate, per-visit capture, paging/raw/rendered/copy and keyboard/back routes | +| Artifact groups | Source model/list | actual visit/run gallery integration and truthful unavailable capture facts | +| Artifact preview | Missing | image-primary in-app viewer, video/doc/text/markdown, paging, focus/back, authenticated fetch errors | +| Artifact actions | Source safe URL resolution | separate external-open/copy/download; SHARE REAL NAMED MIME FILES, not links; slow activation/cancel/errors | +| Session audit/export repair facts | Missing UI | session.html read-only open, partial/missing/skipped/repair choices without fabricating complete evidence | +| Chat session management | Source | normal Chat destination, directory groups/history/search, shared rename/star/close/reopen/create, local hide/undo/seen state | +| Chat history/live transport | Source pure fold; active controller72 | authoritative reconnect, opaque older-page cursor, one-turn grouping and stable session navigation | +| Chat message surfaces | Active native body70 | integrate thread, markdown (safe links/headings/lists/tables/fences), exact attachments and unknown-part retention | +| Chat activity/reasoning/tools | Source raw fields only | one activity line, compaction, native reasoning/tools overlays, lifecycle/input/output/error/duration/edit diff | +| Chat composer | Missing | per-chat persisted drafts, Enter newline/Ctrl-Cmd+Enter send, Send beside Stop, optimistic identity, queued/refused restore | +| Chat attachments | Source request facade | picker/paste, latest1MiB total wire bound, base64 files, removable named chips, exact history reconciliation | +| Chat permissions/questions | Source request facade | native approval/risk cards and form option/free-text answers; pending/resolved/stale/error states | +| Chat model/Info/background tasks | Source request facade | current-model selection, numeric Info modal (unknown !=0), bounded running shell pages | +| Chat commands/notices/scroll | Missing | slash palette/actions, unknown-command send-as-message, dismissible local notices, saved scroll/follow intent | +| Saved schedule list | Source | pipeline entry and route registration, exact timer provenance vocabulary | +| Schedule editor | Active lossless draft74 | native fields, stable create key, revision-CAS edit/pause/delete, conflict keeps draft, Schedule this run seed | +| Search | Source screen | shell entry, close/focus/selection retention, exact pipeline/version/run/field/visit/artifact target routing | +| Needs you | Missing | derived failed/waiting counts, native list/sheet, open/dismiss/clear snapshot, persisted identities | +| Notifications | Missing | explicit permission/rationale, secure/unsupported/denied states, transition-only dedupe, background question notices | +| Mobile replacement build | Scaffold only | Android build at end; all source portable to iOS, isolated IDs; device/OS behavior clearly separate | + +## Current-reference corrections + +Latest behavior supersedes older parity rows: Enter inserts a newline and +Ctrl/Cmd+Enter sends; chat rename/star are server-shared; chat usage is behind +Info; graph clicks open recorded visits; image artifacts preview internally; +artifact Share carries bytes as a named file, never a URL; attachments use the +latest bounded attachment envelope. Native layout differences are intentional; +missing behavior is not a native-layout difference. + +## Completion gate + +Every row must have actual normal-app registration, request/state regression +coverage, and real-browser evidence for visible/interactive states. Recheck +integrated analysis/tests/build and publish the verified preview. Produce the +requested Android testing build only after development acceptance; do not use +the personal delivery device for tests. Distinguish code, landing, publication, +authenticated smoke, native build and device/OS verification in the final report. diff --git a/app/lib/features/runs/ui/run_detail_actions.dart b/app/lib/features/runs/ui/run_detail_actions.dart new file mode 100644 index 00000000..5b2e5fd2 --- /dev/null +++ b/app/lib/features/runs/ui/run_detail_actions.dart @@ -0,0 +1,28 @@ +import 'package:flutter/widgets.dart'; + +import '../../../core/api_gateway.dart'; +import '../actions/cancel_run_action.dart'; +import '../actions/title_action.dart'; + +/// Native actions on the loaded run, all using the app's one gateway and +/// applying only accepted server detail through the same controller callback. +class RunDetailActions extends StatelessWidget { + const RunDetailActions({ + super.key, + required this.run, + required this.gateway, + required this.onRunChanged, + }); + + final JsonMap run; + final ApiGateway gateway; + final ValueChanged onRunChanged; + + @override + Widget build(BuildContext context) => Wrap( + children: [ + RunTitleAction(run: run, gateway: gateway, onRunChanged: onRunChanged), + CancelRunAction(run: run, gateway: gateway, onRunChanged: onRunChanged), + ], + ); +} diff --git a/app/lib/features/runs/ui/run_detail_cupertino.dart b/app/lib/features/runs/ui/run_detail_cupertino.dart index cf8388fd..12a48c8a 100644 --- a/app/lib/features/runs/ui/run_detail_cupertino.dart +++ b/app/lib/features/runs/ui/run_detail_cupertino.dart @@ -10,7 +10,7 @@ import 'run_detail_content.dart'; Widget buildCupertinoRunDetail({ required BuildContext context, required JsonMap run, - required Widget titleAction, + required Widget headerActions, required bool detailLoading, required String? error, required bool copying, @@ -65,7 +65,7 @@ Widget buildCupertinoRunDetail({ padding: const EdgeInsetsDirectional.fromSTEB(16, 8, 16, 0), child: Align( alignment: AlignmentDirectional.centerStart, - child: titleAction, + child: headerActions, ), ), if (detailLoading) const _CupertinoNotice('Refreshing run details…'), diff --git a/app/lib/features/runs/ui/run_detail_material.dart b/app/lib/features/runs/ui/run_detail_material.dart index 6ced0428..654a1561 100644 --- a/app/lib/features/runs/ui/run_detail_material.dart +++ b/app/lib/features/runs/ui/run_detail_material.dart @@ -8,7 +8,7 @@ import 'run_detail_content.dart'; Widget buildMaterialRunDetail({ required BuildContext context, required JsonMap run, - required Widget titleAction, + required Widget headerActions, required bool detailLoading, required String? error, required bool copying, @@ -42,7 +42,7 @@ Widget buildMaterialRunDetail({ Chip(label: Text(runStatusLabel(run))), Text('Run ${run['id']}'), Text('Pipeline ${detailPipeline(run)}'), - titleAction, + headerActions, ], ), if (detailLoading) const _Notice('Refreshing run details…'), diff --git a/app/lib/features/runs/ui/run_detail_view.dart b/app/lib/features/runs/ui/run_detail_view.dart index da808dc2..f6982913 100644 --- a/app/lib/features/runs/ui/run_detail_view.dart +++ b/app/lib/features/runs/ui/run_detail_view.dart @@ -4,7 +4,7 @@ import 'package:flutter/services.dart'; import '../../../core/api_gateway.dart'; import '../../../ui/adaptive/host.dart'; -import '../actions/title_action.dart'; +import 'run_detail_actions.dart'; import 'run_detail_content.dart'; import 'run_detail_cupertino.dart'; import 'run_detail_material.dart'; @@ -40,7 +40,7 @@ class _RunDetailViewState extends State { final run = widget.controller.detail; if (run == null) return _placeholder(context, cupertino: cupertino); final prompt = detailPrompt(run); - final titleAction = RunTitleAction( + final headerActions = RunDetailActions( run: run, gateway: widget.gateway, onRunChanged: widget.controller.acceptRunDetail, @@ -49,7 +49,7 @@ class _RunDetailViewState extends State { ? buildCupertinoRunDetail( context: context, run: run, - titleAction: titleAction, + headerActions: headerActions, detailLoading: widget.controller.detailLoading, error: widget.controller.error, copying: _copying, @@ -60,7 +60,7 @@ class _RunDetailViewState extends State { : buildMaterialRunDetail( context: context, run: run, - titleAction: titleAction, + headerActions: headerActions, detailLoading: widget.controller.detailLoading, error: widget.controller.error, copying: _copying, diff --git a/app/lib/features/runs/ui/runs_controller.dart b/app/lib/features/runs/ui/runs_controller.dart index a01ecab5..72ed9b5d 100644 --- a/app/lib/features/runs/ui/runs_controller.dart +++ b/app/lib/features/runs/ui/runs_controller.dart @@ -114,12 +114,32 @@ class RunsController extends ChangeNotifier { if (id == null) return; var changed = false; if (detail?['id'] == id) { + ++_detailGeneration; + _cancelDetailRefresh(); detail = run; + detailLoading = false; + error = null; changed = true; } final index = runs.indexWhere((row) => row['id'] == id); if (index >= 0) { - runs = [...runs]..[index] = {...runs[index], 'title': run['title'] ?? ''}; + // A cancel/decision reply changes lifecycle fields as well as title. + // Keep sparse/unknown summary fields, without copying bulky detail-only + // payloads into the held list or inventing missing values. + const detailOnly = { + 'steps', + 'input', + 'output', + 'graph', + 'usage', + 'notifications', + }; + runs = [...runs] + ..[index] = { + ...runs[index], + for (final entry in run.entries) + if (!detailOnly.contains(entry.key)) entry.key: entry.value, + }; changed = true; } if (changed) notifyListeners(); diff --git a/app/notes/R2-cancel-wire.md b/app/notes/R2-cancel-wire.md new file mode 100644 index 00000000..6a1529b7 --- /dev/null +++ b/app/notes/R2-cancel-wire.md @@ -0,0 +1,23 @@ +# Cancel from the actual run detail + +The loaded detail's native action row reuses CancelRunAction alongside Rename. +No new confirmation or protocol implementation: Keep sends nothing, only Confirm +sends the exact run_id, and no canceled state appears before server acceptance. +The accepted run detail now folds lifecycle fields into the held list row as well +as the detail (the previous title-only update was insufficient for Cancel). +Detail-only payloads are not duplicated into the summary list; pending old detail +refreshes are invalidated after acceptance. Foreign run replies cannot replace +the open detail. Native controls still own sizing and appearance. + +## Actual checks + +- New normal-screen Material/Cupertino tests failed before registration, then + passed: Keep/no request, Confirm exact id, delayed accepted canceled state, + action disappears, Back shows canceled list row. +- 601 integrated tests pass; analyzer and normal web build pass. +- Normal-app real Chrome fixture probe passes23 captures, including Cupertino + confirm/Keep, Material confirm and accepted detail/list. The fixture records + exactly one cancel_run for its own synthetic run4. No real run was canceled. +- Fresh Cupertino-confirm and Material-accepted PNGs inspected in approved + temp/cancel-wired-browser. Existing history/reconnect/Settings checks pass too. +- Mobile and authenticated production mutations remain unverified. diff --git a/app/test/features/runs/ui/run_cancel_wiring_test.dart b/app/test/features/runs/ui/run_cancel_wiring_test.dart new file mode 100644 index 00000000..5677ab93 --- /dev/null +++ b/app/test/features/runs/ui/run_cancel_wiring_test.dart @@ -0,0 +1,93 @@ +import 'dart:async'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/runs/actions/cancel_wording.dart'; +import 'package:pipelines_app/features/runs/screen.dart'; + +class _Gateway implements ApiGateway { + final events = StreamController.broadcast(); + final requests = <({String type, JsonMap fields})>[]; + final canceled = Completer(); + final JsonMap run = { + 'id': 7, + 'title': 'Controlled run', + 'name': 'fixture', + 'status': 'running', + 'executing': true, + 'steps': [], + }; + + @override + Stream get frames => events.stream; + + @override + Future call(String type, [JsonMap fields = const {}]) { + requests.add((type: type, fields: fields)); + return switch (type) { + 'list_runs' => Future.value({ + 'runs': [Map.of(run)], + }), + 'get_run' => Future.value({'run_detail': Map.of(run)}), + 'cancel_run' => canceled.future, + _ => Future.error(UnsupportedError(type)), + }; + } +} + +void main() { + for (final cupertino in [false, true]) { + testWidgets( + 'actual detail confirms cancel and folds accepted state ($cupertino)', + (tester) async { + final gateway = _Gateway(); + addTearDown(gateway.events.close); + final screen = RunsScreen(gateway: gateway, initialRunId: 7); + await tester.pumpWidget( + cupertino + ? CupertinoApp(home: CupertinoPageScaffold(child: screen)) + : MaterialApp(home: Scaffold(body: screen)), + ); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(cancelActionKey)); + await tester.pumpAndSettle(); + expect(find.text('Cancel run 7?'), findsOneWidget); + expect(gateway.requests.where((r) => r.type == 'cancel_run'), isEmpty); + await tester.tap(find.byKey(cancelKeepKey)); + await tester.pumpAndSettle(); + expect(gateway.requests.where((r) => r.type == 'cancel_run'), isEmpty); + + await tester.tap(find.byKey(cancelActionKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(cancelConfirmKey)); + await tester.pump(); + expect( + gateway.requests.where((r) => r.type == 'cancel_run').single.fields, + {'run_id': 7}, + ); + expect(find.text('canceled'), findsNothing); + gateway.canceled.complete({ + 'run_detail': { + ...gateway.run, + 'status': 'canceled', + 'executing': false, + }, + }); + await tester.pumpAndSettle(); + expect(find.byKey(cancelActionKey), findsNothing); + expect(find.text('canceled'), findsOneWidget); + await tester.tap(find.text(cupertino ? 'Back' : 'Back to list')); + await tester.pumpAndSettle(); + expect( + find.textContaining('canceled'), + findsWidgets, + reason: + 'The accepted server state must also update the held list row', + ); + await tester.pumpWidget(const SizedBox.shrink()); + }, + ); + } +} diff --git a/app/tool/runs_probe.mjs b/app/tool/runs_probe.mjs index 4d816d2e..0075fc24 100644 --- a/app/tool/runs_probe.mjs +++ b/app/tool/runs_probe.mjs @@ -377,6 +377,16 @@ try { if ((await path()) !== '/settings') throw new Error('Settings did not update route'); captures.push(await capture('settings-cupertino-registered-phone')); + await clickText('Runs'); + await clickText('Fixture cancel run', { contains: true }); + await assertBody('Original prompt'); + await clickText('Cancel run'); + await assertBody('Cancel run 4?'); + captures.push(await capture('cancel-cupertino-confirm')); + await clickText('Keep'); + const kept = await (await fetch(`${fixture.url}/fixture/state`)).json(); + if (kept.cancelRequests.length) throw new Error('Keep sent a cancellation'); + // Material host: the same deep link and route must render standard Material // controls (the Cupertino host was selected by the macOS browser above). await send( @@ -408,7 +418,23 @@ try { } captures.push(await capture('settings-material-registered-phone')); + await clickText('Runs'); + await clickText('Fixture cancel run', { contains: true }); + await assertBody('Original prompt'); + await clickText('Cancel run'); + await assertBody('Cancel run 4?'); + captures.push(await capture('cancel-material-confirm')); + await clickText('Cancel run'); + await assertBody('canceled'); + captures.push(await capture('cancel-material-accepted')); + await clickText('Back to list'); + await assertBody('Fixture cancel run'); + await assertBody('canceled'); + const fixtureState = await (await fetch(`${fixture.url}/fixture/state`)).json(); + if (JSON.stringify(fixtureState.cancelRequests) !== JSON.stringify([{ run_id: 4 }])) { + throw new Error('Cancel sent the wrong payload or repeated the request'); + } if (fixtureState.subscribed < 2) throw new Error(`App never resubscribed: ${JSON.stringify(fixtureState)}`); if (fixtureState.listRuns < 2) throw new Error(`App never reloaded: ${JSON.stringify(fixtureState)}`); if (fixtureState.getRun < 2) throw new Error(`Detail was not rehydrated: ${JSON.stringify(fixtureState)}`); diff --git a/app/tool/runs_probe_server.mjs b/app/tool/runs_probe_server.mjs index 79160044..a0f77586 100644 --- a/app/tool/runs_probe_server.mjs +++ b/app/tool/runs_probe_server.mjs @@ -45,6 +45,11 @@ const RUNS = [ created_at: '2026-10-21T10:00:00Z', pipeline_id: 10, }, + { + id: 4, title: 'Fixture cancel run', name: 'fixture-cancel', + status: 'running', executing: true, + created_at: '2026-10-21T09:00:00Z', pipeline_id: 10, + }, ]; const LIVE_EVENT = { @@ -57,13 +62,15 @@ const LIVE_EVENT = { finished_at: '2026-10-21T12:05:00Z', }; -function detail(id, live) { - const status = id === 1 && live ? 'succeeded' : id === 3 ? 'failed' : 'running'; +function detail(id, live, canceled = false) { + const status = canceled ? 'canceled' + : id === 1 && live ? 'succeeded' : id === 3 ? 'failed' : 'running'; return { id, title: RUNS.find((run) => run.id === id)?.title ?? `Run ${id}`, name: 'fixture-pipeline', status, + executing: status === 'running', input: { prompt: ' fixture prompt with spaces ', note: 'input payload', @@ -260,6 +267,8 @@ export async function startFixture({ root }) { let dropped = 0; let listRuns = 0; let getRun = 0; + const canceled = new Set(); + const cancelRequests = []; const dropConnections = () => { for (const connection of connections) connection.close(); @@ -306,6 +315,7 @@ export async function startFixture({ root }) { dropped, listRuns, getRun, + cancelRequests, })); return; } @@ -355,7 +365,8 @@ export async function startFixture({ root }) { } if (request.type === 'list_runs') { listRuns++; - client.send({ id: request.id, type: 'runs', runs: RUNS, usage: null }); + client.send({ id: request.id, type: 'runs', runs: RUNS.map((run) => + canceled.has(run.id) ? { ...run, status: 'canceled', executing: false } : run), usage: null }); return; } if (request.type === 'get_run') { @@ -377,7 +388,13 @@ export async function startFixture({ root }) { }); return; } - client.send({ id: request.id, type: 'run', run_detail: detail(id, live) }); + client.send({ id: request.id, type: 'run', run_detail: detail(id, live, canceled.has(id)) }); + return; + } + if (request.type === 'cancel_run' && request.run_id === 4) { + cancelRequests.push({ run_id: request.run_id }); + canceled.add(4); + client.send({ id: request.id, type: 'run', run_detail: detail(4, live, true) }); return; } client.send({ From 18b55603b2e8278924aeb3c34c6d802af5fc4c86 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 20:06:24 +0100 Subject: [PATCH 05/10] docs(app): track full-port inventory and parallel feature slices --- app/WORK.md | 31 +++++++++++++++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/app/WORK.md b/app/WORK.md index daaff8af..f443d516 100644 --- a/app/WORK.md +++ b/app/WORK.md @@ -18,7 +18,7 @@ All work under app/. Existing applications remain running and unchanged. | R1 | Run list/detail/live timeline | controller43 + list48 + detail46 +35a8aab | manager checked retained candidate and real browser captures | merged main; ancestry verified | built into8096 preview | | D1 | Recorded changes/diff viewer | run39 /15cca17 + manager32e1cac | manager rejected bundled font/fixed palette; corrected to host typography/native semantic colors,47 tests + fresh18 browser captures pass | merged main; ancestry verified | run-detail wiring pending | | R2a | Human-decision native confirm | run47 / commit42b21b8 | manager inspected source + reran 7 exact-confirm/refusal/native tests + analyze, pass | main3e6f950, ancestry verified | reusable component only; wiring/browser pending | -| R2b | Native cancel-run confirmation | run51 →52 / correction5449370 | manager reran23 action tests + analyze, pass; known refusal now immediate and dismissible while resync pending | merged main; ancestry verified | reusable component only; wiring/browser pending | +| R2b | Native cancel-run confirmation | run51 →52 + managere20ac9f | actual detail wiring, accepted lifecycle/list fold;601 integrated tests +23 normal-app browser captures pass | merged main | published8096; no production cancellation tested | | X1 | Native search and result targets | run49 / commit51140cd | manager reran36 tests, checked native browser evidence + source; all pass | merged main, ancestry verified | standalone screen; shell wiring pending | | I1 | App-owned socket/session + live Runs shell registration | run50 timeout → manager finish /35a8aab |68 focused tests; integrated375 tests; clean analyze/build; normal-entry browser probe passed18 captures incl deep links/history/reconnect | merged main; ancestry verified |8096 bundle rebuilt, auth preserved; live authenticated smoke not verified | | E1 | Narrow authorized server export-bound fix | run53 / source22801a9 / deployb4627e2 | bounded regressions + full isolated Go suite pass; exact installed revision verified | source merged; deployed minimal patch on original server revision | installed; seven exact exports complete, Review resumed | @@ -36,7 +36,12 @@ All work under app/. Existing applications remain running and unchanged. | A1-list | One read-only artifact visit-group list | run65 /596365d9 | manager inspected231-line source + dark Cupertino PNG;11 focused tests pass;59min MISSED20min target | merged main; ancestry verified | run-detail wiring/preview pending | | D1-wire | Open existing ChangesViewer from run detail | run67 /flutter/d1-wire | Task v6 Flash; one native button/recorded-steps route, no viewer rewrite | running | pending | | R2-title-wire | Existing Rename action into detail/controller | run68 /3d3ee3a3 |19min total MET target; manager reviewed source/server-reply fold, focused tests + normal-app browser7 captures pass | merged main; ancestry verified | published8096 with Runs/Settings | -| P1-wire | Register pipeline browser in actual app shell | run69 /flutter/p1-wire | small shared-session/embedded/native-host/reconnect integration only, no graph renderer | running | pending | +| P1-wire | Register pipeline browser in actual app shell | run69 /8476cfd7 | manager reviewed, focused tests;599 integrated tests + actual app browser25 checks/9 PNGs pass;27min missed20min target | merged main; ancestry verified | published8096 | +| C2-message | Native chat message body | run70 /flutter/chat-messages | pure native text/unknown-part disclosure, no network; focused tests/captures required | running | component first | +| P2-canvas | Measured definition graph composition | run71 /flutter/graph-canvas | existing node/layout/routes/edge layer, actual measurements, no invented visits | running | graph hook next | +| C2-thread | Chat paging/live controller | run72 /flutter/chat-thread | existing repository/fold, opaque cursors and reconnect; no UI/network ownership changes | running | conversation integration next | +| T1-create | Native template create-only dialog | run73 /flutter/template-create | validate before submit, no production authoring; no gallery scope | running | gallery integration next | +| S1-draft | Lossless schedule editor draft | run74 /flutter/schedule-draft | pure validation/CAS-preserving copy; no CRUD/timer engine | running | editor next | ## Next ready work ### Current execution target (user correction) @@ -85,6 +90,28 @@ override, server edit or shell-write bypass was used by the manager. Allowed pipeline models: Luna or DeepSeek V4.1 Flash; current runs use Luna. ## Latest integration check +The user directs continued work until the whole client is ported, not just +components. app/PARITY.md now enumerates the entire remaining behavior inventory +against latest web behavior, distinguishing preview/source/active/missing. + +Pipeline browser69 landed and was tested against the normal app build in real +Chrome:25 checks/9 PNGs, actual dark Cupertino detail inspected; existing Runs/ +Settings regression20 captures pass. Published without service restart; previous +bundle kept at build/web-before-pipelines-1792609054. + +Then manager wired existing CancelRunAction alongside Rename. New native-screen +tests failed before wiring and pass after; accepted server state updates list +lifecycle too, not just title, invalidating stale detail requests. Full suite601 +tests pass; clean analysis/build. Extended normal-app CDP probe23 captures verifies +Cupertino confirm/Keep sends nothing, Material confirm sends exactly one run_id4 +to its isolated fixture, and accepted canceled detail/list. Both new native +captures inspected; no real run canceled. Preview includes this verified bundle +(e20ac9f), rollback build/web-before-cancel-1792609492, JS SHA256 +60391291f5086fbef409399ee0660801c887e5891d37b35f02519dc56af9205b; +authentication401 preserved. No shared service restarted. Five independent +micro-slices70–74 started in parallel with individual background waits;67 Changes +wiring continues independently. No workflow authored or modified. + Integrated main592 tests pass; analyze and normal web build clean. P1 candidate correction removed491 lines of custom measured control code/test expectations: all widths keep actual native segmented controls, scaled labels scroll whole and From 914866f640dfa86eb459471858cdc0457ac86f0a Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 20:08:02 +0100 Subject: [PATCH 06/10] feat(app): add pure schedule editor draft and validation Build a save_schedule record from server schedule records with the web editor's field messages. The draft preserves unknown record, input, rule and run-option fields, keeps the exact revision, writes the operator's workspace and sends no payload while any field is invalid. --- .../domain/editor/schedule_draft.dart | 210 ++++++++++++++++++ app/notes/S1-draft.md | 134 +++++++++++ .../domain/editor/draft_fixtures.dart | 42 ++++ .../domain/editor/schedule_draft_test.dart | 134 +++++++++++ .../schedule_draft_validation_test.dart | 130 +++++++++++ 5 files changed, 650 insertions(+) create mode 100644 app/lib/features/schedules/domain/editor/schedule_draft.dart create mode 100644 app/notes/S1-draft.md create mode 100644 app/test/features/schedules/domain/editor/draft_fixtures.dart create mode 100644 app/test/features/schedules/domain/editor/schedule_draft_test.dart create mode 100644 app/test/features/schedules/domain/editor/schedule_draft_validation_test.dart diff --git a/app/lib/features/schedules/domain/editor/schedule_draft.dart b/app/lib/features/schedules/domain/editor/schedule_draft.dart new file mode 100644 index 00000000..1beb75cc --- /dev/null +++ b/app/lib/features/schedules/domain/editor/schedule_draft.dart @@ -0,0 +1,210 @@ +import '../../../../core/api_gateway.dart'; +import '../saved_schedule.dart'; +import '../schedule_rule.dart'; + +/// Which half of the timer rule the editor is writing. +enum ScheduleTimerMode { interval, clock } + +/// Either a ready-to-send `save_schedule` record or field errors keyed by the +/// draft field the control binds to. [record] is null when any field fails, so +/// an invalid draft can never be mistaken for a save payload. +class ScheduleSaveResult { + ScheduleSaveResult(this.record, this.errors); + + final JsonMap? record; + final Map errors; + + bool get isValid => record != null; +} + +/// Core editor state for one saved schedule, mirroring the web editor draft. +/// +/// Pure draft only: no network, timer calculation or timezone conversion. +/// [build] mirrors `serializeSchedule` in `web/src/schedules.js` for name, +/// prompt, pinned version, server workspace, timer rule, weekdays and +/// timezone. It starts from a deep copy of the server record, so unknown +/// record/input/rule/run-option fields and the exact revision survive an edit. +class ScheduleDraft { + ScheduleDraft._(this.source, this.pipelineId); + + /// The record this draft edits; null for a create. + final SavedSchedule? source; + final int? pipelineId; + + String name = ''; + String prompt = ''; + String version = ''; + String workspace = ''; + bool enabled = true; + ScheduleTimerMode mode = ScheduleTimerMode.interval; + String every = '24h'; + String times = ''; + List days = []; + String timezone = ''; + String notifyMode = 'auto'; + + /// New schedule: the server's create sentinel is `id: 0` with no revision. + factory ScheduleDraft.create({ + required int pipelineId, + String version = '', + String workspace = '', + String timezone = '', + }) => ScheduleDraft._(null, pipelineId) + ..version = version + ..workspace = workspace + ..timezone = timezone; + + /// Existing record: every field starts from the server value, never from a + /// default that could overwrite it. + factory ScheduleDraft.fromSchedule(SavedSchedule s, {int? pipelineId}) { + final rule = s.rule; + return ScheduleDraft._(s, s.pipelineId ?? pipelineId) + ..name = s.name + ..prompt = s.prompt + ..version = s.version?.toString() ?? '' + ..workspace = s.workspace + ..enabled = s.raw['enabled'] is bool ? s.enabled : true + ..mode = rule.isClock + ? ScheduleTimerMode.clock + : ScheduleTimerMode.interval + ..every = rule.raw['every'] is String ? rule.every : '24h' + ..times = rule.times.join(', ') + ..days = [...rule.days] + ..timezone = rule.timezone + ..notifyMode = s.raw['notify_mode'] is String ? s.notifyMode : 'auto'; + } + + /// Validates every field and assembles the exact `save_schedule` record. + /// The draft and the source snapshot are never mutated. + ScheduleSaveResult build() { + final errors = {}; + void fail(String field, String message) => + errors.putIfAbsent(field, () => message); + + if (name.trim().isEmpty) fail('name', 'Enter a schedule name.'); + if (prompt.trim().isEmpty) fail('prompt', 'Enter a prompt.'); + final pinned = int.tryParse(version); + if (!_digits.hasMatch(version) || + pinned == null || + pinned < 1 || + pinned > _maxSafeInteger) { + fail('version', 'Choose a positive pinned version, not latest (0).'); + } + if (!workspace.startsWith('/') || _workspaceBreaks.hasMatch(workspace)) { + fail('workspace', 'Enter an absolute workspace path on the server.'); + } + if (!const {'auto', 'on', 'off'}.contains(notifyMode)) { + fail('notifyMode', 'Choose a notification mode.'); + } + if (days.any((day) => !scheduleDays.contains(day)) || + days.toSet().length != days.length) { + fail('days', 'Choose valid, distinct weekdays.'); + } + List? clock; + if (mode == ScheduleTimerMode.interval) { + if (!_validDuration(every)) { + fail( + 'every', + 'Interval must be at least 1m (for example 24h or 1h30m).', + ); + } + } else { + clock = [for (final time in times.split(',')) time.trim()]; + if (clock.any((time) => !_timeOfDay.hasMatch(time)) || + clock.toSet().length != clock.length) { + fail('times', 'Enter distinct 24-hour times, such as 09:00, 17:30.'); + } + } + if (!_validTimezone(timezone.trim())) { + fail('timezone', 'Enter a valid IANA timezone.'); + } + if (errors.isNotEmpty) return ScheduleSaveResult(null, errors); + + final record = source?.toJson() ?? {}; + if (source == null) record['id'] = 0; + record['name'] = name.trim(); + final pipeline = source?.pipelineId ?? pipelineId; + if (pipeline != null) record['pipeline_id'] = pipeline; + record['version'] = pinned; + record['enabled'] = enabled; + record['input'] = (source?.input ?? {}) + ..['prompt'] = prompt; + // Untrimmed like `workspace: draft.workspace`; validation also runs on the + // untrimmed value, so a valid workspace is sent exactly as the operator + // entered it. + record['workspace'] = workspace; + + final rule = source?.rule.toJson() ?? {}; + for (final key in const ['every', 'times', 'days', 'timezone']) { + rule.remove(key); + } + if (mode == ScheduleTimerMode.interval) { + rule['every'] = every.trim(); + } else { + rule['times'] = clock; + } + if (days.isNotEmpty) { + final prior = source?.rule.days ?? const []; + final unchanged = + prior.length == days.length && prior.every(days.contains); + rule['days'] = unchanged ? [...prior] : [...days]; + } + if (timezone.trim().isNotEmpty) rule['timezone'] = timezone.trim(); + record['rule'] = rule; + record['notify_mode'] = notifyMode; + return ScheduleSaveResult(record, const {}); + } +} + +const _maxSafeInteger = 9007199254740991; +final _digits = RegExp(r'^\d+$'); +final _timeOfDay = RegExp(r'^([01]\d|2[0-3]):[0-5]\d$'); +final _workspaceBreaks = RegExp(r'[\x00\r\n]'); +final _zonePart = RegExp(r'^[A-Za-z0-9_+\-]+$'); +const _durationPart = r'((?:\d+(?:\.\d*)?|\.\d+))(ms|us|µs|ns|h|m|s)'; +final _areas = + 'Africa America Antarctica Arctic Asia Atlantic Australia ' + 'Brazil Canada Chile Etc Europe Indian Mexico Pacific US' + .split(' '); +final _singleZones = + 'UTC GMT UCT Zulu Universal Greenwich CET EET EST HST ' + 'MST WET GB NZ PRC ROC ROK W-SU Egypt Eire Iceland Iran Israel Jamaica ' + 'Japan Kwajalein Libya Navajo Poland Portugal Singapore Turkey Cuba ' + 'Hongkong' + .split(' '); + +double? _unit(String unit) => switch (unit) { + 'h' => 3600000, + 'm' => 60000, + 's' => 1000, + 'ms' => 1, + 'us' || 'µs' => .001, + 'ns' => .000001, + _ => null, +}; + +/// Go-style compound duration, at least one minute, as the web client accepts. +bool _validDuration(String text) { + final every = text.trim(); + final parts = RegExp(_durationPart).allMatches(every).toList(); + final duration = parts.fold( + 0, + (sum, part) => sum + double.parse(part[1]!) * _unit(part[2]!)!, + ); + return parts.map((part) => part[0]!).join() == every && + duration.isFinite && + duration >= 60000; +} + +/// Structural IANA check. Dart carries no timezone database, so a known area +/// plus a well-formed location is the strongest pure check; the server stays +/// the final validator. +bool _validTimezone(String value) { + if (value.isEmpty || value == 'Local' || _singleZones.contains(value)) { + return true; + } + final parts = value.split('/'); + return parts.length > 1 && + _areas.contains(parts.first) && + parts.every(_zonePart.hasMatch); +} diff --git a/app/notes/S1-draft.md b/app/notes/S1-draft.md new file mode 100644 index 00000000..27ca42db --- /dev/null +++ b/app/notes/S1-draft.md @@ -0,0 +1,134 @@ +# S1-draft — pure saved-schedule editor draft and validation + +## What changed + +New files only; no existing feature, shell, transport, `main` or pubspec source +edited: + +| File | Lines | Responsibility | +| --- | --- | --- | +| `lib/features/schedules/domain/editor/schedule_draft.dart` | 210 | mutable editor draft over `SavedSchedule`/`ScheduleRule`, web-mirrored validation, `save_schedule` record assembly | +| `test/features/schedules/domain/editor/draft_fixtures.dart` | 42 | shared server-record fixture and deep-copy helper | +| `test/features/schedules/domain/editor/schedule_draft_test.dart` | 134 | create/edit record assembly, CAS, unknown fields, workspace, source immutability | +| `test/features/schedules/domain/editor/schedule_draft_validation_test.dart` | 130 | timer/day/timezone/core field validation and invalid-field behavior | + +The production file is one cohesive file (below the 220-line slice budget) and +keeps the existing domain pattern: `SavedSchedule` and `ScheduleRule` are +read-only views, `ScheduleDraft` is the separate editable state. Tests are split +by responsibility (record assembly vs. validation) so neither file exceeds the +working agreement's ~250-line aim. + +## Review fix — workspace is now written into the record + +Review visit 1 found that `build()` validated `workspace` but never wrote it, so +creates were refused by `save_schedule` and workspace edits were dropped. The +fix writes `record['workspace'] = workspace;` beside `name`/`version`/`enabled`, +untrimmed to match `workspace: draft.workspace` in `web/src/schedules.js` +(validation also runs on the untrimmed value). Direct probe against the real +classes: + +``` +create keys: enabled, id, input, name, notify_mode, pipeline_id, rule, version, workspace +create: {"id":0,...,"workspace":"/srv","rule":{"every":"24h","timezone":"UTC"},"notify_mode":"auto"} +edit workspace: /new (source /old) +edit revision: 13 +``` + +New assertions cover the create record, an unchanged edit, a changed edit and +the untrimmed value. + +## Behavior copied from `web/src/schedules.js` + +`ScheduleDraft.build()` returns `ScheduleSaveResult(null, errors)` while any +field is invalid, so an invalid draft cannot yield a save payload. Errors are a +field-name → message map using the web editor's exact words: + +- name `Enter a schedule name.` (stored trimmed, as the web record is) +- prompt `Enter a prompt.` (stored untrimmed) +- pinned version: digits only, safe integer, at least 1 — `Choose a positive + pinned version, not latest (0).` +- workspace must start with `/` and contain no NUL/CR/LF — `Enter an absolute + workspace path on the server.` +- interval is Go-style compound duration (`24h`, `1h30m`, `.5h`, `1.5m`) whose + matched text covers the whole value and totals at least one minute — + `Interval must be at least 1m (for example 24h or 1h30m).` +- clock times are comma-separated, trimmed, distinct `HH:mm` in 00:00–23:59 — + `Enter distinct 24-hour times, such as 09:00, 17:30.` +- weekday keys must be distinct values from `scheduleDays` — + `Choose valid, distinct weekdays.` +- notification mode is `auto`, `on` or `off` — `Choose a notification mode.` +- timezone is blank, `Local`, a known single-zone alias or a well-formed + `Area/Location` — `Enter a valid IANA timezone.` + +Rule assembly mirrors the web editor: the prior rule is copied, `every`, +`times`, `days` and `timezone` are removed, then only the selected timer shape +is written. Empty weekdays mean every day (the key stays absent). A weekday set +that is unchanged keeps the server's original order (the web editor does this +so editing only a prompt does not reorder days). A blank timezone is omitted. + +## Losslessness and CAS + +- Edits start from `SavedSchedule.toJson()` (a deep copy): unknown top-level, + `input`, `rule` and run-option fields (`model`, `stage_models`, `write_paths`, + `allow_tools`, `title`, `output_format`, `next_due`, timestamps, future + fields) survive untouched. +- `input` keeps every unknown key and replaces only `prompt`. +- **Every build starts from a fresh copy**, so the source snapshot and the + draft are not mutated or aliased by a returned payload. +- The edit record keeps the exact server `revision`; it is never incremented, + invented or defaulted. An edit never rewrites `id`. +- A create has no source: it emits the web sentinel `id: 0`, no `revision`, no + unknown/run-option leftovers, `pipeline_id` from the caller, `enabled`, + `input: {prompt}`, `rule`, and `notify_mode`. +- `notify_mode` and `enabled` default the same way as the web draft when absent + from a malformed older record, but an existing non-default string/boolean is + preserved and validated rather than silently replaced. + +## Checks actually run + +``` +flutter pub get +dart format lib/features/schedules/domain/editor test/features/schedules/domain/editor +flutter analyze # No issues found! (1.1s) +flutter test test/features/schedules/domain/editor # 9 passed +flutter test test/features/schedules # 56 passed +``` + +Focused coverage maps to the requested acceptance: + +- create: sentinel `id: 0`, no revision, pipeline/version/prompt/workspace/rule; +- lossless edit: id 9/revision 13, unknown record/input/rule/run options, + workspace from the source, original map and `SavedSchedule` snapshot + unchanged, returned payload not aliased; +- changed workspace is written untrimmed, matching the web serializer; +- prompt-only edit keeps the server weekday order and clock rule; +- clock ↔ interval switching removes the other timer key and keeps unknown + rule fields; +- invalid timers (`59s`, `NaN`, `-1h`, `1.1x`, `Infinityh`, mixed text) and + valid parity cases (`.5h`, `1h30m`, `24h`); +- invalid clock times, duplicate weekdays, bad notification mode, invalid + timezones, bad name/prompt/version/workspace; +- invalid draft mutates nothing and has no record. + +## Honest limits + +- **Scope is the core editor slice.** Name, prompt, pinned version, workspace, + timer mode/every/times, weekdays, timezone, enabled and notification mode are + editable. Advanced JSON run options (`otherInput`, `stage models`, write + paths, model, title, output format) and tools are **preserved exactly but not + editable in this slice**; no control or parser for them was invented here. +- **Timezone is structural.** Dart ships no IANA database, so the check accepts + blank/`Local`, known single-zone aliases and a known area plus a well-formed + location (e.g. `Europe/London`, `Etc/GMT+5`). It rejects clearly malformed + values such as `Nowhere/Invalid` and `Europe/`, but cannot prove that every + location in an accepted area exists. The server remains the final validator. + This is documented at the function. +- **No UI, network, CRUD, run dispatch, polling or scheduling engine.** The + draft only assembles a record; the existing repository owns `save_schedule`, + and no server was contacted. +- **No browser capture applies.** This is a nonvisual pure domain item; there + is no rendered change, so no fixture or screenshot was produced. +- **Mobile unverified.** Only web-targeted Flutter tests and analysis ran. No + Android/iOS build, emulator, ADB or device was used; the code is pure Dart. +- **Not committed.** This stage forbids commit, push and deploy, so the + candidate remains in the `flutter/schedule-draft` worktree for the manager. diff --git a/app/test/features/schedules/domain/editor/draft_fixtures.dart b/app/test/features/schedules/domain/editor/draft_fixtures.dart new file mode 100644 index 00000000..a5cb6406 --- /dev/null +++ b/app/test/features/schedules/domain/editor/draft_fixtures.dart @@ -0,0 +1,42 @@ +import 'dart:convert'; + +import 'package:pipelines_app/core/api_gateway.dart'; + +JsonMap deepCopy(JsonMap value) => jsonDecode(jsonEncode(value)) as JsonMap; + +/// A server record with every editable field plus unknown record, input, rule +/// and run-option keys this slice must preserve. +JsonMap completeRecord() => { + 'id': 9, + 'revision': 13, + 'name': 'Saved topic', + 'pipeline_id': 4, + 'version': 2, + 'enabled': true, + 'input': { + 'prompt': 'Topic', + 'count': 4, + 'flag': false, + 'nested': { + 'list': [null, 2], + }, + }, + 'workspace': '/srv/research', + 'rule': { + 'times': ['09:00', '17:30'], + 'days': ['fri', 'mon'], + 'timezone': '', + 'future': 'keep', + }, + 'model': 'provider/model', + 'stage_models': {'research': 'provider/other'}, + 'write_paths': ['src/file.go'], + 'allow_tools': true, + 'title': 'Saved title', + 'output_format': 'json', + 'notify_mode': 'off', + 'next_due': '2026-10-22T09:00:00Z', + 'server_extra': { + 'keep': [1, true], + }, +}; diff --git a/app/test/features/schedules/domain/editor/schedule_draft_test.dart b/app/test/features/schedules/domain/editor/schedule_draft_test.dart new file mode 100644 index 00000000..228e76f7 --- /dev/null +++ b/app/test/features/schedules/domain/editor/schedule_draft_test.dart @@ -0,0 +1,134 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/schedules/domain/editor/schedule_draft.dart'; +import 'package:pipelines_app/features/schedules/domain/saved_schedule.dart'; + +import 'draft_fixtures.dart'; + +void main() { + test('a new schedule snapshots prompt, pipeline, workspace and version', () { + final draft = + ScheduleDraft.create( + pipelineId: 42, + version: '7', + workspace: '/srv/research', + timezone: 'UTC', + ) + ..name = 'AI news' + ..prompt = 'Research AI news'; + final result = draft.build(); + + expect(result.isValid, isTrue); + expect(result.errors, isEmpty); + final record = result.record!; + expect(record['id'], 0); + expect(record.containsKey('revision'), isFalse); + expect(record['pipeline_id'], 42); + expect(record['version'], 7); + expect(record['enabled'], isTrue); + expect(record['name'], 'AI news'); + expect(record['workspace'], '/srv/research'); + expect(record['input'], {'prompt': 'Research AI news'}); + expect(record['rule'], {'every': '24h', 'timezone': 'UTC'}); + expect(record['notify_mode'], 'auto'); + }); + + test('an edit preserves CAS, unknown fields and untouched run options', () { + final original = completeRecord(); + final snapshot = deepCopy(original); + final schedule = SavedSchedule(original); + final draft = ScheduleDraft.fromSchedule(schedule)..prompt = 'Changed'; + final result = draft.build(); + + expect(result.isValid, isTrue); + final record = result.record!; + expect(record['id'], 9); + expect(record['revision'], 13); + expect(record['workspace'], '/srv/research'); + expect(record['server_extra'], snapshot['server_extra']); + expect(record['next_due'], snapshot['next_due']); + expect(record['model'], 'provider/model'); + expect(record['stage_models'], {'research': 'provider/other'}); + expect(record['write_paths'], ['src/file.go']); + expect(record['allow_tools'], isTrue); + expect(record['title'], 'Saved title'); + expect(record['output_format'], 'json'); + expect(record['notify_mode'], 'off'); + expect((record['input'] as JsonMap)['count'], 4); + expect((record['input'] as JsonMap)['nested'], { + 'list': [null, 2], + }); + expect((record['input'] as JsonMap)['prompt'], 'Changed'); + expect((record['rule'] as JsonMap)['future'], 'keep'); + expect((record['rule'] as JsonMap)['days'], ['fri', 'mon']); + + // Neither the server map nor the SavedSchedule snapshot was mutated. + expect(original, snapshot); + expect(schedule.toJson(), snapshot); + ((record['input'] as JsonMap)['nested'] as JsonMap)['extra'] = true; + expect(schedule.input['nested'], { + 'list': [null, 2], + }); + }); + + test( + 'an edit writes the changed workspace, untrimmed like the web client', + () { + final record = (ScheduleDraft.fromSchedule( + SavedSchedule(completeRecord()), + )..workspace = '/srv/other').build().record!; + expect(record['workspace'], '/srv/other'); + + final untrimmed = (ScheduleDraft.fromSchedule( + SavedSchedule(completeRecord()), + )..workspace = '/srv/dir ').build().record!; + expect(untrimmed['workspace'], '/srv/dir '); + }, + ); + + test('a prompt-only edit keeps the existing weekday order', () { + final original = completeRecord(); + final draft = ScheduleDraft.fromSchedule(SavedSchedule(original)) + ..prompt = 'New topic' + ..days = ['mon', 'fri']; + final record = draft.build().record!; + + expect((record['rule'] as JsonMap)['days'], ['fri', 'mon']); + expect((record['rule'] as JsonMap)['times'], ['09:00', '17:30']); + expect((record['rule'] as JsonMap)['timezone'], isNull); + }); + + test('switching modes removes the other timer shape and keeps unknowns', () { + final original = completeRecord(); + final clock = ScheduleDraft.fromSchedule(SavedSchedule(original)) + ..mode = ScheduleTimerMode.clock + ..times = '09:00, 23:59'; + final clockRule = clock.build().record!['rule'] as JsonMap; + expect(clockRule['times'], ['09:00', '23:59']); + expect(clockRule.containsKey('every'), isFalse); + expect(clockRule['future'], 'keep'); + + final interval = + ScheduleDraft.fromSchedule(SavedSchedule(clock.build().record!)) + ..mode = ScheduleTimerMode.interval + ..every = '1.5m'; + final intervalRule = interval.build().record!['rule'] as JsonMap; + expect(intervalRule['every'], '1.5m'); + expect(intervalRule.containsKey('times'), isFalse); + expect(intervalRule['future'], 'keep'); + }); + + test('the source record is never aliased by a built payload', () { + final original = completeRecord(); + final schedule = SavedSchedule(original); + final first = (ScheduleDraft.fromSchedule(schedule)).build(); + expect(first.record, isNotNull); + expect(schedule.toJson(), original); + + final second = (ScheduleDraft.fromSchedule( + schedule, + )..prompt = 'Other').build(); + expect((second.record!['input'] as JsonMap)['prompt'], 'Other'); + expect(schedule.input['prompt'], 'Topic'); + }); +} diff --git a/app/test/features/schedules/domain/editor/schedule_draft_validation_test.dart b/app/test/features/schedules/domain/editor/schedule_draft_validation_test.dart new file mode 100644 index 00000000..dd69b4a3 --- /dev/null +++ b/app/test/features/schedules/domain/editor/schedule_draft_validation_test.dart @@ -0,0 +1,130 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/schedules/domain/editor/schedule_draft.dart'; +import 'package:pipelines_app/features/schedules/domain/saved_schedule.dart'; + +import 'draft_fixtures.dart'; + +void main() { + test('invalid intervals are field errors and never a record', () { + for (final every in [ + '', + '59s', + 'NaN', + '-1h', + '1.1x', + 'Infinityh', + '1m2h x', + ]) { + final draft = + ScheduleDraft.create(pipelineId: 4, version: '2', workspace: '/srv') + ..name = 'Timer' + ..prompt = 'Prompt' + ..every = every; + final result = draft.build(); + expect(result.record, isNull, reason: every); + expect( + result.errors['every'], + 'Interval must be at least 1m (for example 24h or 1h30m).', + reason: every, + ); + } + for (final every in ['1m', '.5h', '1h30m', '24h']) { + final draft = + ScheduleDraft.create(pipelineId: 4, version: '2', workspace: '/srv') + ..name = 'Timer' + ..prompt = 'Prompt' + ..every = every; + final result = draft.build(); + expect(result.record, isNotNull, reason: every); + expect((result.record!['rule'] as JsonMap)['every'], every); + } + }); + + test('invalid clock times, weekdays and timezones are field errors', () { + final draft = + ScheduleDraft.create(pipelineId: 4, version: '2', workspace: '/srv') + ..name = 'Timer' + ..prompt = 'Prompt' + ..mode = ScheduleTimerMode.clock + ..times = '24:00' + ..days = ['mon', 'mon'] + ..timezone = 'Nowhere/Invalid' + ..notifyMode = 'sometimes'; + final result = draft.build(); + + expect(result.record, isNull); + expect( + result.errors['times'], + 'Enter distinct 24-hour times, such as 09:00, 17:30.', + ); + expect(result.errors['days'], 'Choose valid, distinct weekdays.'); + expect(result.errors['timezone'], 'Enter a valid IANA timezone.'); + expect(result.errors['notifyMode'], 'Choose a notification mode.'); + + for (final times in ['', '9:00', '09:60', '09:00,09:00']) { + final invalid = + ScheduleDraft.fromSchedule(SavedSchedule(completeRecord())) + ..mode = ScheduleTimerMode.clock + ..times = times; + expect(invalid.build().errors['times'], isNotNull, reason: times); + } + for (final timezone in ['Europe', 'Europe/', '/London']) { + final invalid = + ScheduleDraft.create(pipelineId: 4, version: '2', workspace: '/srv') + ..name = 'Timer' + ..prompt = 'Prompt' + ..timezone = timezone; + expect(invalid.build().errors['timezone'], isNotNull, reason: timezone); + } + for (final timezone in ['Local', 'UTC', 'Asia/Tokyo', 'Etc/GMT+5']) { + final valid = + ScheduleDraft.create(pipelineId: 4, version: '2', workspace: '/srv') + ..name = 'Timer' + ..prompt = 'Prompt' + ..timezone = timezone; + expect(valid.build().isValid, isTrue, reason: timezone); + } + }); + + test('invalid core fields report every error without mutating the draft', () { + final draft = ScheduleDraft.create(pipelineId: 4) + ..prompt = ' ' + ..version = '7junk' + ..workspace = '/srv\npath'; + final before = { + 'name': draft.name, + 'prompt': draft.prompt, + 'version': draft.version, + 'workspace': draft.workspace, + }; + final result = draft.build(); + + expect(result.record, isNull); + expect(result.errors, { + 'name': 'Enter a schedule name.', + 'prompt': 'Enter a prompt.', + 'version': 'Choose a positive pinned version, not latest (0).', + 'workspace': 'Enter an absolute workspace path on the server.', + }); + expect({ + 'name': draft.name, + 'prompt': draft.prompt, + 'version': draft.version, + 'workspace': draft.workspace, + }, before); + + for (final version in ['0', '-1', '1.2', 'Infinity']) { + final invalid = ScheduleDraft.fromSchedule( + SavedSchedule(completeRecord()), + )..version = version; + expect(invalid.build().errors['version'], isNotNull, reason: version); + } + for (final workspace in ['', 'relative', '~/repo']) { + final invalid = ScheduleDraft.fromSchedule( + SavedSchedule(completeRecord()), + )..workspace = workspace; + expect(invalid.build().errors['workspace'], isNotNull, reason: workspace); + } + }); +} From c970aa5d1614e40472768f609ec94e71c68ad1fd Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 20:09:36 +0100 Subject: [PATCH 07/10] fix(app): expose refused chat watches without losing readable history --- app/PARITY.md | 2 +- .../conversation/chat_thread_controller.dart | 12 ++++++--- app/notes/C2-thread.md | 6 +++++ .../chat_thread_subscription_test.dart | 27 +++++++++++++++++++ 4 files changed, 43 insertions(+), 4 deletions(-) create mode 100644 app/test/features/chat/conversation/chat_thread_subscription_test.dart diff --git a/app/PARITY.md b/app/PARITY.md index f522df5a..edcfc4f7 100644 --- a/app/PARITY.md +++ b/app/PARITY.md @@ -41,7 +41,7 @@ or scratch servers only, never real operator sessions/runs/workflows. | Artifact actions | Source safe URL resolution | separate external-open/copy/download; SHARE REAL NAMED MIME FILES, not links; slow activation/cancel/errors | | Session audit/export repair facts | Missing UI | session.html read-only open, partial/missing/skipped/repair choices without fabricating complete evidence | | Chat session management | Source | normal Chat destination, directory groups/history/search, shared rename/star/close/reopen/create, local hide/undo/seen state | -| Chat history/live transport | Source pure fold; active controller72 | authoritative reconnect, opaque older-page cursor, one-turn grouping and stable session navigation | +| Chat history/live transport | Source controller72 + pure fold | integrate authoritative reconnect/paging/live-failure status and stable session navigation | | Chat message surfaces | Active native body70 | integrate thread, markdown (safe links/headings/lists/tables/fences), exact attachments and unknown-part retention | | Chat activity/reasoning/tools | Source raw fields only | one activity line, compaction, native reasoning/tools overlays, lifecycle/input/output/error/duration/edit diff | | Chat composer | Missing | per-chat persisted drafts, Enter newline/Ctrl-Cmd+Enter send, Send beside Stop, optimistic identity, queued/refused restore | diff --git a/app/lib/features/chat/conversation/chat_thread_controller.dart b/app/lib/features/chat/conversation/chat_thread_controller.dart index 0864c8c2..d5c5b9a1 100644 --- a/app/lib/features/chat/conversation/chat_thread_controller.dart +++ b/app/lib/features/chat/conversation/chat_thread_controller.dart @@ -35,6 +35,7 @@ class ChatThreadController extends ChangeNotifier { String? _error; bool _subscribed = false; + String? _subscriptionError; bool _disposed = false; int _generation = 0; bool _resyncing = false; @@ -49,6 +50,8 @@ class ChatThreadController extends ChangeNotifier { /// The server's opaque older-page cursor. Never interpreted, only passed back. String get cursor => _cursor; String? get error => _error; + bool get subscribed => _subscribed; + String? get subscriptionError => _subscriptionError; /// Subscribes this session, then loads its newest history page. Future load() async { @@ -93,7 +96,7 @@ class ChatThreadController extends ChangeNotifier { /// The reconnect/resync repair: settle the held turn, re-attach the session, /// then replace the conversation with the newest authoritative page. Activity - /// replayed while re-attaching (a running step, a form) is fresh native state + /// replayed while re-attaching (a running step) is fresh native state /// and survives the replacement. A resync frame also lands here. Future resync() async { if (_disposed) return; @@ -111,6 +114,7 @@ class ChatThreadController extends ChangeNotifier { Future _resyncOnce() async { final token = ++_generation; + _loading = true; // A socket drop removed the frames feeding the turn, so no held turn may // keep claiming to run until the re-subscribe proves otherwise. _running = false; @@ -159,10 +163,12 @@ class ChatThreadController extends ChangeNotifier { await _repository.subscribe(sessionId); if (_disposed) return; _subscribed = true; - } catch (_) { - // The history path remains usable; resync re-attempts the subscribe. + _subscriptionError = null; + } catch (error) { + // History stays usable, but the UI must report that live updates failed. if (_disposed) return; _subscribed = false; + _subscriptionError = '$error'; } } diff --git a/app/notes/C2-thread.md b/app/notes/C2-thread.md index cd5f048a..a5a48aba 100644 --- a/app/notes/C2-thread.md +++ b/app/notes/C2-thread.md @@ -1,5 +1,11 @@ # C2 — Chat thread controller +Manager integration follow-up: exposes subscribed/subscriptionError separately +from history errors, so readable stored history cannot hide a refused live watch. +Resync marks history loading while retaining the current transcript. A focused +regression covers refused subscribe + successful history, then successful resync. +The controller does not claim to fold form events; those are a separate UI slice. + `lib/features/chat/conversation/chat_thread_controller.dart` owns one open conversation without any UI. It is constructed with the shared `ApiGateway` and one `sessionId`, reuses `ChatRepository` for the wire and diff --git a/app/test/features/chat/conversation/chat_thread_subscription_test.dart b/app/test/features/chat/conversation/chat_thread_subscription_test.dart new file mode 100644 index 00000000..d8bc18b3 --- /dev/null +++ b/app/test/features/chat/conversation/chat_thread_subscription_test.dart @@ -0,0 +1,27 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_thread_controller.dart'; + +import 'chat_thread_fixtures.dart'; + +void main() { + test('readable history never hides a refused live subscription', () async { + final gateway = FakeChatGateway(); + gateway.subscribe = () async { + throw StateError('live watch denied'); + }; + gateway.history = (_) async => + chatPage([chatMessage('stored', 'assistant')]); + addTearDown(gateway.close); + final controller = ChatThreadController(gateway, 's'); + addTearDown(controller.dispose); + await controller.load(); + expect(controller.messages.single['id'], 'stored'); + expect(controller.error, isNull); + expect(controller.subscribed, isFalse); + expect(controller.subscriptionError, contains('live watch denied')); + gateway.subscribe = () async => {}; + await controller.resync(); + expect(controller.subscribed, isTrue); + expect(controller.subscriptionError, isNull); + }); +} From 1400780ee2442625a9ad44c00327584ec987b228 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 20:18:55 +0100 Subject: [PATCH 08/10] feat(app): expose recorded human decisions in native run detail --- app/PARITY.md | 2 +- .../features/runs/ui/run_decision_notice.dart | 54 +++++++++ .../features/runs/ui/run_detail_actions.dart | 22 +++- app/notes/R2-decision-wire.md | 19 +++ .../runs/ui/run_decision_wiring_test.dart | 109 ++++++++++++++++++ app/tool/runs_probe.mjs | 36 +++++- app/tool/runs_probe_server.mjs | 34 +++++- 7 files changed, 268 insertions(+), 8 deletions(-) create mode 100644 app/lib/features/runs/ui/run_decision_notice.dart create mode 100644 app/notes/R2-decision-wire.md create mode 100644 app/test/features/runs/ui/run_decision_wiring_test.dart diff --git a/app/PARITY.md b/app/PARITY.md index edcfc4f7..c6da5edd 100644 --- a/app/PARITY.md +++ b/app/PARITY.md @@ -32,7 +32,7 @@ or scratch servers only, never real operator sessions/runs/workflows. | Rename run | Preview | verified exact accepted title fold; no live production mutation tested | | Cancel run | Preview | exact confirm/server-accepted detail+list fold; production cancellation not tested | | Retry/restart | Source actions/dialogs | actual detail controls, accepted new-run navigation, stale/refusal handling | -| Human decisions | Source action/dialog | waiting card, exact recorded options/feedback, attention/action URL entry | +| Human decisions | Preview waiting card/native prompt/exact accepted reply | attention/action URL entry; no production decision answered during tests | | Run graph | Source projection/visits | executed/unvisited routes, live activity, graph clicks open latest RECORDED visit, no definition by default | | Timeline/recorded visit pane | Preview text rows only | visit selection, status/outcome/duration/model/target/verdict, artifacts/session/input/output/definition tabs | | Changes/diffs | Source; active detail wiring67 | settled-run aggregate gate, per-visit capture, paging/raw/rendered/copy and keyboard/back routes | diff --git a/app/lib/features/runs/ui/run_decision_notice.dart b/app/lib/features/runs/ui/run_decision_notice.dart new file mode 100644 index 00000000..cbd474f2 --- /dev/null +++ b/app/lib/features/runs/ui/run_decision_notice.dart @@ -0,0 +1,54 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../core/api_gateway.dart'; +import '../../../ui/adaptive/host.dart'; +import '../actions/decision_action.dart'; +import '../actions/decision_wording.dart'; +import '../domain/run_decisions.dart'; + +/// A recorded human checkpoint, never an audit-export/resource wait. +class RunDecisionNotice extends StatelessWidget { + const RunDecisionNotice({ + super.key, + required this.run, + required this.gateway, + required this.onRunChanged, + }); + final JsonMap run; + final ApiGateway gateway; + final ValueChanged onRunChanged; + + @override + Widget build(BuildContext context) { + final pending = pendingDecision(run); + if (pending == null) return const SizedBox.shrink(); + final content = Padding( + padding: const EdgeInsets.all(16), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Semantics(header: true, child: const Text(decisionWaitingTitle)), + Text(decisionMeta(pending)), + HumanDecisionAction( + run: run, + gateway: gateway, + onRunChanged: onRunChanged, + ), + ], + ), + ); + if (usesCupertinoHost(context)) { + return CupertinoListSection.insetGrouped( + children: [ + DefaultTextStyle( + style: CupertinoTheme.of(context).textTheme.textStyle, + child: content, + ), + ], + ); + } + return Card(child: content); + } +} diff --git a/app/lib/features/runs/ui/run_detail_actions.dart b/app/lib/features/runs/ui/run_detail_actions.dart index 5b2e5fd2..699f734c 100644 --- a/app/lib/features/runs/ui/run_detail_actions.dart +++ b/app/lib/features/runs/ui/run_detail_actions.dart @@ -3,6 +3,7 @@ import 'package:flutter/widgets.dart'; import '../../../core/api_gateway.dart'; import '../actions/cancel_run_action.dart'; import '../actions/title_action.dart'; +import 'run_decision_notice.dart'; /// Native actions on the loaded run, all using the app's one gateway and /// applying only accepted server detail through the same controller callback. @@ -19,10 +20,25 @@ class RunDetailActions extends StatelessWidget { final ValueChanged onRunChanged; @override - Widget build(BuildContext context) => Wrap( + Widget build(BuildContext context) => Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, children: [ - RunTitleAction(run: run, gateway: gateway, onRunChanged: onRunChanged), - CancelRunAction(run: run, gateway: gateway, onRunChanged: onRunChanged), + Wrap( + children: [ + RunTitleAction( + run: run, + gateway: gateway, + onRunChanged: onRunChanged, + ), + CancelRunAction( + run: run, + gateway: gateway, + onRunChanged: onRunChanged, + ), + ], + ), + RunDecisionNotice(run: run, gateway: gateway, onRunChanged: onRunChanged), ], ); } diff --git a/app/notes/R2-decision-wire.md b/app/notes/R2-decision-wire.md new file mode 100644 index 00000000..56aed422 --- /dev/null +++ b/app/notes/R2-decision-wire.md @@ -0,0 +1,19 @@ +# Recorded human decisions in run detail + +RunDecisionNotice reuses pendingDecision and HumanDecisionAction. A standard +Material card or Cupertino section names the recorded checkpoint and offers +Decide. The existing native prompt owns option/feedback/confirmation/refusal +semantics; export/resource waits do not become invented human checkpoints. +Accepted server detail flows through the same lifecycle/list update as Cancel. + +New actual-screen tests failed before wiring and now pass on both hosts: recorded +instructions, selection sends nothing, exact run/stage/option and trimmed feedback +only on confirmation, accepted result removes the card. Integrated614 tests pass; +analysis and normal web build are clean. + +Real normal-app browser fixture passes28 captures, including actual Cupertino +waiting card and prompt, Material card/prompt/accepted result, Cancel/Keep and +the existing history/reconnect/Settings checks. The fixture records one exact +decide_run for its synthetic run5; opening/Cancel send nothing. Card and prompt +PNGs inspected in approved temp/decision-wired-browser. No production decision +was answered; mobile and live authenticated mutations remain unverified. diff --git a/app/test/features/runs/ui/run_decision_wiring_test.dart b/app/test/features/runs/ui/run_decision_wiring_test.dart new file mode 100644 index 00000000..9d29e537 --- /dev/null +++ b/app/test/features/runs/ui/run_decision_wiring_test.dart @@ -0,0 +1,109 @@ +import 'dart:async'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/runs/actions/decision_wording.dart'; +import 'package:pipelines_app/features/runs/screen.dart'; + +class _DecisionGateway implements ApiGateway { + final events = StreamController.broadcast(); + final decisions = []; + final reply = Completer(); + final JsonMap run = { + 'id': 9, + 'title': 'Human checkpoint', + 'name': 'fixture', + 'status': 'waiting', + 'executing': false, + 'current_stage': 'gate', + 'graph': { + 'stages': [ + { + 'key': 'gate', + 'type': 'human', + 'edges': {'approve': '#success'}, + }, + ], + }, + 'steps': [ + { + 'sequence': 1, + 'stage': 'gate', + 'status': 'waiting', + 'output': { + 'prompt': 'Please review this recorded checkpoint.', + 'options': ['approve'], + }, + }, + ], + }; + + @override + Stream get frames => events.stream; + @override + Future call(String type, [JsonMap fields = const {}]) => + switch (type) { + 'list_runs' => Future.value({ + 'runs': [run], + }), + 'get_run' => Future.value({'run_detail': run}), + 'decide_run' => _decide(fields), + _ => Future.error(UnsupportedError(type)), + }; + Future _decide(JsonMap fields) { + decisions.add(fields); + return reply.future; + } +} + +void main() { + for (final cupertino in [false, true]) { + testWidgets( + 'actual detail exposes and confirms recorded decision ($cupertino)', + (tester) async { + final gateway = _DecisionGateway(); + addTearDown(gateway.events.close); + final screen = RunsScreen(gateway: gateway, initialRunId: 9); + await tester.pumpWidget( + cupertino + ? CupertinoApp(home: CupertinoPageScaffold(child: screen)) + : MaterialApp(home: Scaffold(body: screen)), + ); + await tester.pumpAndSettle(); + expect(find.text(decisionWaitingTitle), findsOneWidget); + await tester.tap(find.byKey(decisionActionKey)); + await tester.pumpAndSettle(); + expect( + find.text('Please review this recorded checkpoint.'), + findsOneWidget, + ); + await tester.tap(find.text('approve')); + await tester.enterText(find.byKey(decisionFeedbackKey), ' checked '); + await tester.pump(); + expect(gateway.decisions, isEmpty); + await tester.tap(find.text(decisionConfirmLabel)); + await tester.pump(); + expect(gateway.decisions.single, { + 'run_id': 9, + 'stage': 'gate', + 'option': 'approve', + 'feedback': 'checked', + }); + gateway.reply.complete({ + 'run_detail': { + ...gateway.run, + 'status': 'succeeded', + 'executing': false, + }, + }); + await tester.pumpAndSettle(); + expect(find.byKey(decisionActionKey), findsNothing); + expect(find.text(decisionWaitingTitle), findsNothing); + expect(find.text('succeeded'), findsOneWidget); + await tester.pumpWidget(const SizedBox.shrink()); + }, + ); + } +} diff --git a/app/tool/runs_probe.mjs b/app/tool/runs_probe.mjs index 0075fc24..846cc110 100644 --- a/app/tool/runs_probe.mjs +++ b/app/tool/runs_probe.mjs @@ -110,7 +110,7 @@ try { const semanticText = () => evaluate(`(() => { const chunks = []; - for (const el of document.querySelectorAll('flt-semantics')) { + for (const el of document.querySelectorAll('flt-semantics, [aria-label], [aria-valuetext]')) { const label = el.getAttribute('aria-label'); if (label) chunks.push(label); const value = el.getAttribute('aria-valuetext'); @@ -153,7 +153,7 @@ try { return label === wanted || (${contains} && label.includes(wanted)); }); const interactive = candidates.find((el) => - ['button', 'tab', 'link', 'checkbox', 'menuitem'].includes(el.getAttribute('role')), + ['button', 'tab', 'link', 'checkbox', 'radio', 'menuitem'].includes(el.getAttribute('role')), ); const target = interactive ?? candidates[0]; if (!target) return false; @@ -384,8 +384,17 @@ try { await assertBody('Cancel run 4?'); captures.push(await capture('cancel-cupertino-confirm')); await clickText('Keep'); + await assertBody('Original prompt'); const kept = await (await fetch(`${fixture.url}/fixture/state`)).json(); if (kept.cancelRequests.length) throw new Error('Keep sent a cancellation'); + await clickText('Back', { contains: true }); + await clickText('Fixture human run', { contains: true }); + captures.push(await capture('decision-cupertino-card')); + await assertBody('Waiting for your decision'); + await clickText('Decide'); + await assertBody('Please review this recorded checkpoint.'); + captures.push(await capture('decision-cupertino-confirm')); + await clickText('Cancel'); // Material host: the same deep link and route must render standard Material // controls (the Cupertino host was selected by the macOS browser above). @@ -431,7 +440,30 @@ try { await assertBody('Fixture cancel run'); await assertBody('canceled'); + await clickText('Fixture human run', { contains: true }); + await assertBody('Waiting for your decision'); + captures.push(await capture('decision-material-card')); + await clickText('Decide'); + await assertBody('Please review this recorded checkpoint.'); + captures.push(await capture('decision-material-confirm')); + const pendingDecision = await (await fetch(`${fixture.url}/fixture/state`)).json(); + if (pendingDecision.decisionRequests.length) throw new Error('Opening decision sent a reply'); + await clickText('approve', { contains: true }); + await clickText('Confirm decision'); + await assertBody('succeeded'); + if ((await semanticText()).includes('Waiting for your decision')) { + throw new Error('Accepted human decision left the waiting card behind'); + } + captures.push(await capture('decision-material-accepted')); + await clickText('Back to list'); + await assertBody('Fixture cancel run'); + await assertBody('canceled'); + const fixtureState = await (await fetch(`${fixture.url}/fixture/state`)).json(); + if (JSON.stringify(fixtureState.decisionRequests) !== + JSON.stringify([{ run_id: 5, stage: 'gate', option: 'approve' }])) { + throw new Error('Decision sent the wrong payload or repeated the request'); + } if (JSON.stringify(fixtureState.cancelRequests) !== JSON.stringify([{ run_id: 4 }])) { throw new Error('Cancel sent the wrong payload or repeated the request'); } diff --git a/app/tool/runs_probe_server.mjs b/app/tool/runs_probe_server.mjs index a0f77586..b9ece509 100644 --- a/app/tool/runs_probe_server.mjs +++ b/app/tool/runs_probe_server.mjs @@ -50,8 +50,25 @@ const RUNS = [ status: 'running', executing: true, created_at: '2026-10-21T09:00:00Z', pipeline_id: 10, }, + { + id: 5, title: 'Fixture human run', name: 'fixture-human', + status: 'waiting', executing: false, + created_at: '2026-10-21T08:00:00Z', pipeline_id: 10, + }, ]; +function humanDetail(accepted) { + return { + ...RUNS.find((run) => run.id === 5), + status: accepted ? 'succeeded' : 'waiting', current_stage: 'gate', + input: { prompt: 'Fixture human decision' }, + graph: { stages: [{ key: 'gate', type: 'human', edges: { approve: '#success' } }] }, + steps: [{ sequence: 1, stage: 'gate', status: accepted ? 'completed' : 'waiting', + output: { prompt: 'Please review this recorded checkpoint.', options: ['approve'] }, + }], + }; +} + const LIVE_EVENT = { type: 'run_event', run_id: 1, @@ -269,6 +286,8 @@ export async function startFixture({ root }) { let getRun = 0; const canceled = new Set(); const cancelRequests = []; + let decisionAccepted = false; + const decisionRequests = []; const dropConnections = () => { for (const connection of connections) connection.close(); @@ -316,6 +335,7 @@ export async function startFixture({ root }) { listRuns, getRun, cancelRequests, + decisionRequests, })); return; } @@ -366,7 +386,8 @@ export async function startFixture({ root }) { if (request.type === 'list_runs') { listRuns++; client.send({ id: request.id, type: 'runs', runs: RUNS.map((run) => - canceled.has(run.id) ? { ...run, status: 'canceled', executing: false } : run), usage: null }); + canceled.has(run.id) ? { ...run, status: 'canceled', executing: false } + : run.id === 5 && decisionAccepted ? { ...run, status: 'succeeded' } : run), usage: null }); return; } if (request.type === 'get_run') { @@ -388,7 +409,8 @@ export async function startFixture({ root }) { }); return; } - client.send({ id: request.id, type: 'run', run_detail: detail(id, live, canceled.has(id)) }); + client.send({ id: request.id, type: 'run', run_detail: id === 5 + ? humanDetail(decisionAccepted) : detail(id, live, canceled.has(id)) }); return; } if (request.type === 'cancel_run' && request.run_id === 4) { @@ -397,6 +419,14 @@ export async function startFixture({ root }) { client.send({ id: request.id, type: 'run', run_detail: detail(4, live, true) }); return; } + if (request.type === 'decide_run' && request.run_id === 5 && + request.stage === 'gate' && request.option === 'approve') { + decisionRequests.push({ run_id: request.run_id, stage: request.stage, + option: request.option, ...(request.feedback ? { feedback: request.feedback } : {}) }); + decisionAccepted = true; + client.send({ id: request.id, type: 'run', run_detail: humanDetail(true) }); + return; + } client.send({ id: request.id, type: 'error', From 87220fe886b04d9eb0f67a47818b0ed186debb4c Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 20:21:48 +0100 Subject: [PATCH 09/10] fix(app): reject schedule edits without exact identity and revision --- app/PARITY.md | 2 +- .../domain/editor/schedule_draft.dart | 17 +++++++++-- app/notes/S1-draft.md | 6 ++++ .../editor/schedule_draft_identity_test.dart | 30 +++++++++++++++++++ 4 files changed, 52 insertions(+), 3 deletions(-) create mode 100644 app/test/features/schedules/domain/editor/schedule_draft_identity_test.dart diff --git a/app/PARITY.md b/app/PARITY.md index c6da5edd..a9e3a727 100644 --- a/app/PARITY.md +++ b/app/PARITY.md @@ -50,7 +50,7 @@ or scratch servers only, never real operator sessions/runs/workflows. | Chat model/Info/background tasks | Source request facade | current-model selection, numeric Info modal (unknown !=0), bounded running shell pages | | Chat commands/notices/scroll | Missing | slash palette/actions, unknown-command send-as-message, dismissible local notices, saved scroll/follow intent | | Saved schedule list | Source | pipeline entry and route registration, exact timer provenance vocabulary | -| Schedule editor | Active lossless draft74 | native fields, stable create key, revision-CAS edit/pause/delete, conflict keeps draft, Schedule this run seed | +| Schedule editor | Source lossless draft74 + identity/CAS guard | native fields, stable create key, edit/pause/delete, conflict keeps draft, Schedule this run seed | | Search | Source screen | shell entry, close/focus/selection retention, exact pipeline/version/run/field/visit/artifact target routing | | Needs you | Missing | derived failed/waiting counts, native list/sheet, open/dismiss/clear snapshot, persisted identities | | Notifications | Missing | explicit permission/rationale, secure/unsupported/denied states, transition-only dedupe, background question notices | diff --git a/app/lib/features/schedules/domain/editor/schedule_draft.dart b/app/lib/features/schedules/domain/editor/schedule_draft.dart index 1beb75cc..a07edc97 100644 --- a/app/lib/features/schedules/domain/editor/schedule_draft.dart +++ b/app/lib/features/schedules/domain/editor/schedule_draft.dart @@ -81,6 +81,18 @@ class ScheduleDraft { void fail(String field, String message) => errors.putIfAbsent(field, () => message); + final selectedPipeline = source?.pipelineId ?? pipelineId; + if (!_validIdentity(selectedPipeline)) { + fail('pipelineId', 'Choose a valid pipeline.'); + } + if (source != null && + (!_validIdentity(source!.id) || !_validIdentity(source!.revision))) { + fail( + 'record', + 'Schedule identity or revision is missing. Refresh before editing.', + ); + } + if (name.trim().isEmpty) fail('name', 'Enter a schedule name.'); if (prompt.trim().isEmpty) fail('prompt', 'Enter a prompt.'); final pinned = int.tryParse(version); @@ -123,8 +135,7 @@ class ScheduleDraft { final record = source?.toJson() ?? {}; if (source == null) record['id'] = 0; record['name'] = name.trim(); - final pipeline = source?.pipelineId ?? pipelineId; - if (pipeline != null) record['pipeline_id'] = pipeline; + record['pipeline_id'] = selectedPipeline; record['version'] = pinned; record['enabled'] = enabled; record['input'] = (source?.input ?? {}) @@ -157,6 +168,8 @@ class ScheduleDraft { } const _maxSafeInteger = 9007199254740991; +bool _validIdentity(int? value) => + value != null && value > 0 && value <= _maxSafeInteger; final _digits = RegExp(r'^\d+$'); final _timeOfDay = RegExp(r'^([01]\d|2[0-3]):[0-5]\d$'); final _workspaceBreaks = RegExp(r'[\x00\r\n]'); diff --git a/app/notes/S1-draft.md b/app/notes/S1-draft.md index 27ca42db..57fa7d2c 100644 --- a/app/notes/S1-draft.md +++ b/app/notes/S1-draft.md @@ -1,5 +1,11 @@ # S1-draft — pure saved-schedule editor draft and validation +Manager integration guard: invalid pipeline IDs and edited records without a +positive exact server identity/revision cannot build save payloads. This prevents +a malformed/historical edit from becoming a create or bypassing CAS. Three new +regressions failed against the original draft and pass after the fail-closed +guard. The original snapshot remains unchanged; no production save was tested. + ## What changed New files only; no existing feature, shell, transport, `main` or pubspec source diff --git a/app/test/features/schedules/domain/editor/schedule_draft_identity_test.dart b/app/test/features/schedules/domain/editor/schedule_draft_identity_test.dart new file mode 100644 index 00000000..d3512fd8 --- /dev/null +++ b/app/test/features/schedules/domain/editor/schedule_draft_identity_test.dart @@ -0,0 +1,30 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/schedules/domain/editor/schedule_draft.dart'; +import 'package:pipelines_app/features/schedules/domain/saved_schedule.dart'; + +import 'draft_fixtures.dart'; + +void main() { + test('an invalid pipeline identity cannot become a create payload', () { + final draft = + ScheduleDraft.create(pipelineId: 0, version: '1', workspace: '/srv') + ..name = 'Topic' + ..prompt = 'Research this'; + expect(draft.build().record, isNull); + expect(draft.build().errors, contains('pipelineId')); + }); + + for (final missing in ['id', 'revision']) { + test( + 'missing $missing never turns an edit into an unconditional create', + () { + final raw = completeRecord()..remove(missing); + final source = SavedSchedule(raw); + final draft = ScheduleDraft.fromSchedule(source); + expect(draft.build().record, isNull); + expect(draft.build().errors, contains('record')); + expect(source.raw.containsKey(missing), isFalse); + }, + ); + } +} From 77c71eb45e7fda817a1cfbcb2bdf1d4a0b5a537a Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 20:48:45 +0100 Subject: [PATCH 10/10] feat(app): finish native run Changes wiring and scaled form menus --- app/lib/features/changes/changes.dart | 2 +- .../features/changes/domain/run_changes.dart | 7 + .../changes/widgets/change_style.dart | 105 +--- .../changes/widgets/changes_viewer.dart | 73 +-- .../changes/widgets/diff_form_control.dart | 138 +++++ .../changes/widgets/file_diff_viewer.dart | 93 ++-- .../changes/widgets/raw_patch_view.dart | 75 +++ .../features/runs/ui/run_changes_action.dart | 126 +++++ .../runs/ui/run_detail_cupertino.dart | 9 +- .../features/runs/ui/run_detail_material.dart | 20 +- app/notes/D1-wire.md | 191 +++++++ .../features/changes/changes_viewer_test.dart | 4 +- .../changes/diff_presentation_test.dart | 196 +++++++ .../features/changes/run_changes_test.dart | 9 + .../runs/ui/run_changes_action_test.dart | 177 +++++++ .../runs/ui/run_changes_status_test.dart | 204 +++++++ app/tool/diff_wiring_probe.dart | 188 +++++++ app/tool/diff_wiring_probe.mjs | 498 ++++++++++++++++++ 18 files changed, 1956 insertions(+), 159 deletions(-) create mode 100644 app/lib/features/changes/widgets/diff_form_control.dart create mode 100644 app/lib/features/changes/widgets/raw_patch_view.dart create mode 100644 app/lib/features/runs/ui/run_changes_action.dart create mode 100644 app/notes/D1-wire.md create mode 100644 app/test/features/runs/ui/run_changes_action_test.dart create mode 100644 app/test/features/runs/ui/run_changes_status_test.dart create mode 100644 app/tool/diff_wiring_probe.dart create mode 100644 app/tool/diff_wiring_probe.mjs diff --git a/app/lib/features/changes/changes.dart b/app/lib/features/changes/changes.dart index ac7e0e4d..e9c43314 100644 --- a/app/lib/features/changes/changes.dart +++ b/app/lib/features/changes/changes.dart @@ -11,7 +11,7 @@ export 'domain/change_wording.dart'; export 'domain/file_change.dart'; export 'domain/run_changes.dart'; export 'domain/unified_patch.dart'; -export 'widgets/change_style.dart' show DiffForm, usesCupertino; +export 'widgets/change_style.dart' show DiffForm, hostTextTheme, usesCupertino; export 'widgets/changes_viewer.dart'; export 'widgets/file_diff_viewer.dart'; export 'widgets/patch_view.dart'; diff --git a/app/lib/features/changes/domain/run_changes.dart b/app/lib/features/changes/domain/run_changes.dart index b7708eeb..ab8cc648 100644 --- a/app/lib/features/changes/domain/run_changes.dart +++ b/app/lib/features/changes/domain/run_changes.dart @@ -44,6 +44,13 @@ class RunChanges { RunChanges runChanges(List steps) => runChangesFor(stageCaptures(steps)); +/// Whether the run-wide final-state aggregate may be presented. Ported from +/// `web/src/changes.js` `showRunChangesSummary`: only a settled succeeded run +/// has a final workspace state. A failed or running run keeps its evidence in +/// each visit's own captured section instead of claiming a settled summary. +bool showRunChangesSummary(Object? status) => + status != null && '$status'.trim().toLowerCase() == 'succeeded'; + /// The same aggregate over already-derived [stageCaptures], so a caller that /// shows both the summary and the sections parses each capture only once. RunChanges runChangesFor(List visits) { diff --git a/app/lib/features/changes/widgets/change_style.dart b/app/lib/features/changes/widgets/change_style.dart index a3f12ffd..2bb6cdab 100644 --- a/app/lib/features/changes/widgets/change_style.dart +++ b/app/lib/features/changes/widgets/change_style.dart @@ -2,104 +2,52 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import '../domain/unified_patch.dart'; +import 'diff_form_control.dart'; -/// Which form of a recorded patch the viewer is showing. -enum DiffForm { rendered, raw } +export 'diff_form_control.dart'; -/// The app's established platform switch: Material for Android/desktop/web, -/// Cupertino for iOS and macOS. Feature widgets stay portable across all three -/// targets instead of hard-coding one control set. -bool usesCupertino(BuildContext context) { - final platform = Theme.of(context).platform; - return platform == TargetPlatform.iOS || platform == TargetPlatform.macOS; -} - -/// Patch text inherits the host's typography, including its font and scaler. -/// A diff is not an exception to the native-defaults requirement. +/// Patch text inherits the host's typography without a diff-specific font. TextStyle nativeDiffText(TextStyle base) => base; -/// Native semantic colours, never a bespoke diff palette. The recorded +/- -/// markers carry meaning independently of colour. No background tint is added. +/// Keep Material-derived metadata roles readable inside a Cupertino host. +ThemeData hostTextTheme(BuildContext context) => ThemeData( + brightness: CupertinoTheme.brightnessOf(context), + platform: Theme.of(context).platform, +); + +/// Native semantic roles, never a bespoke palette or added row tint. The exact +/// recorded +/- markers also distinguish changes without relying on colour. ({Color text, Color? background}) diffLineColors( BuildContext context, ChangeLineKind kind, -) { - return switch (kind) { - ChangeLineKind.add => ( - text: usesCupertino(context) - ? CupertinoColors.systemGreen.resolveFrom(context) - : Theme.of(context).colorScheme.primary, - background: null, - ), - ChangeLineKind.remove => ( - text: usesCupertino(context) - ? CupertinoColors.destructiveRed.resolveFrom(context) - : Theme.of(context).colorScheme.error, - background: null, - ), - ChangeLineKind.context => (text: labelColor(context), background: null), - }; -} +) => switch (kind) { + ChangeLineKind.add => ( + text: usesCupertino(context) + ? CupertinoColors.systemGreen.resolveFrom(context) + : Theme.of(context).colorScheme.primary, + background: null, + ), + ChangeLineKind.remove => ( + text: usesCupertino(context) + ? CupertinoColors.destructiveRed.resolveFrom(context) + : Theme.of(context).colorScheme.error, + background: null, + ), + ChangeLineKind.context => (text: labelColor(context), background: null), +}; -/// The plain body/label colour for non-diff text inside the viewer. Color labelColor(BuildContext context) => usesCupertino(context) ? CupertinoColors.label.resolveFrom(context) : Theme.of(context).colorScheme.onSurface; -/// The muted colour for gutters, notes and secondary metadata. Color mutedColor(BuildContext context) => usesCupertino(context) ? CupertinoColors.secondaryLabel.resolveFrom(context) : Theme.of(context).colorScheme.onSurfaceVariant; -/// The hunk header's fill. Color hunkHeaderColor(BuildContext context) => usesCupertino(context) ? CupertinoColors.tertiarySystemFill.resolveFrom(context) : Theme.of(context).colorScheme.surfaceContainerHighest; -/// The viewer's shared Rendered/Raw control: a native segmented control on each -/// platform, with the same two words the browser uses. -Widget diffFormControl( - BuildContext context, { - required DiffForm form, - required ValueChanged onChanged, -}) { - if (usesCupertino(context)) { - return CupertinoSlidingSegmentedControl( - groupValue: form, - onValueChanged: (value) { - if (value != null) onChanged(value); - }, - children: const { - DiffForm.rendered: _SegmentLabel('Rendered'), - DiffForm.raw: _SegmentLabel('Raw patch'), - }, - ); - } - return SegmentedButton( - segments: const [ - ButtonSegment(value: DiffForm.rendered, label: Text('Rendered')), - ButtonSegment(value: DiffForm.raw, label: Text('Raw patch')), - ], - selected: {form}, - showSelectedIcon: false, - onSelectionChanged: (selection) { - if (selection.isNotEmpty) onChanged(selection.first); - }, - ); -} - -class _SegmentLabel extends StatelessWidget { - const _SegmentLabel(this.label); - - final String label; - - @override - Widget build(BuildContext context) => - Padding(padding: const EdgeInsets.all(6), child: Text(label)); -} - -/// Copy the server's raw patch exactly as recorded. Disabled when the entry has -/// no readable patch, so the action never copies a fabricated empty diff. Widget copyPatchControl( BuildContext context, { required bool enabled, @@ -128,7 +76,6 @@ Widget copyPatchControl( ); } -/// The standard close action, labelled exactly on both platforms. Widget closeDiffControl(BuildContext context, VoidCallback onClose) { if (usesCupertino(context)) { return Semantics( diff --git a/app/lib/features/changes/widgets/changes_viewer.dart b/app/lib/features/changes/widgets/changes_viewer.dart index a58d91b7..d8f85d02 100644 --- a/app/lib/features/changes/widgets/changes_viewer.dart +++ b/app/lib/features/changes/widgets/changes_viewer.dart @@ -17,7 +17,11 @@ import 'file_diff_viewer.dart'; /// Scaffold body, tab body or Expanded child). It never opens its own socket or /// requests data; the caller passes the run detail's `steps`. class ChangesViewer extends StatefulWidget { - const ChangesViewer({super.key, required this.steps}); + const ChangesViewer({ + super.key, + required this.steps, + this.showSummary = true, + }); /// The run detail's steps exactly as the server returned them. Each step's /// `file_changes` may be null (no capture), a complete/partial/unavailable @@ -27,6 +31,11 @@ class ChangesViewer extends StatefulWidget { /// captures and the summary are derived from it rather than on every rebuild. final List steps; + /// Whether the run-wide final-state header and filter are shown. The web + /// client gates its aggregate on [showRunChangesSummary]; the per-stage + /// sections stay the evidence for a run without a settled final state. + final bool showSummary; + @override State createState() => _ChangesViewerState(); } @@ -67,49 +76,51 @@ class _ChangesViewerState extends State { Widget build(BuildContext context) { final run = _run; final captures = _captures; + final showSummary = widget.showSummary; final hasFiles = captures.any( (visit) => visit.capture?.files.isNotEmpty ?? false, ); - final note = runChangesNote(run); + final note = showSummary ? runChangesNote(run) : ''; return Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ - Padding( - padding: const EdgeInsets.fromLTRB(16, 16, 16, 8), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - runChangesHeader(run), - style: Theme.of(context).textTheme.titleMedium, - ), - if (note.isNotEmpty) - Padding( - padding: const EdgeInsets.only(top: 4), - child: Text( - note, - style: Theme.of(context).textTheme.bodySmall, - ), + if (showSummary) + Padding( + padding: const EdgeInsets.fromLTRB(16, 16, 16, 8), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + runChangesHeader(run), + style: Theme.of(context).textTheme.titleMedium, ), - if (hasFiles) - Padding( - padding: const EdgeInsets.only(top: 8), - child: Text( - 'The summary counts each path once, as the last recorded ' - 'visit left it. Each stage/visit below lists what its own ' - 'capture recorded.', - style: Theme.of(context).textTheme.bodySmall, + if (note.isNotEmpty) + Padding( + padding: const EdgeInsets.only(top: 4), + child: Text( + note, + style: Theme.of(context).textTheme.bodySmall, + ), ), - ), - ], + if (hasFiles) + Padding( + padding: const EdgeInsets.only(top: 8), + child: Text( + 'The summary counts each path once, as the last recorded ' + 'visit left it. Each stage/visit below lists what its own ' + 'capture recorded.', + style: Theme.of(context).textTheme.bodySmall, + ), + ), + ], + ), ), - ), - if (hasFiles) + if (showSummary && hasFiles) Padding( padding: const EdgeInsets.fromLTRB(16, 0, 16, 8), child: _filterField(context, run), ), - const Divider(height: 1), + if (showSummary) const Divider(height: 1), Expanded( child: captures.isEmpty ? SingleChildScrollView( diff --git a/app/lib/features/changes/widgets/diff_form_control.dart b/app/lib/features/changes/widgets/diff_form_control.dart new file mode 100644 index 00000000..7385e777 --- /dev/null +++ b/app/lib/features/changes/widgets/diff_form_control.dart @@ -0,0 +1,138 @@ +import 'dart:math' as math; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../ui/adaptive/host.dart'; + +enum DiffForm { rendered, raw } + +bool usesCupertino(BuildContext context) => usesCupertinoHost(context); + +const diffFormLabels = { + DiffForm.rendered: 'Rendered', + DiffForm.raw: 'Raw patch', +}; + +/// Conservatively choose between two stock controls using the current native +/// label role and text scaler. This does not size or restyle either control. +bool diffFormSegmentsFit(BuildContext context, double maxWidth) { + final style = usesCupertino(context) + ? CupertinoTheme.of(context).textTheme.textStyle + : Theme.of(context).textTheme.labelLarge ?? + DefaultTextStyle.of(context).style; + var widest = 0.0; + for (final label in diffFormLabels.values) { + final painter = TextPainter( + text: TextSpan(text: label, style: style), + textDirection: Directionality.of(context), + textScaler: MediaQuery.textScalerOf(context), + maxLines: 1, + )..layout(); + widest = math.max(widest, painter.width); + painter.dispose(); + } + return (widest + 48) * 2 <= maxWidth; +} + +Widget diffFormControl( + BuildContext context, { + required DiffForm form, + required ValueChanged onChanged, +}) { + if (usesCupertino(context)) { + return CupertinoSlidingSegmentedControl( + groupValue: form, + onValueChanged: (value) { + if (value != null) onChanged(value); + }, + children: { + for (final entry in diffFormLabels.entries) + entry.key: Padding( + padding: const EdgeInsets.all(6), + child: Text(entry.value), + ), + }, + ); + } + return SegmentedButton( + segments: [ + for (final entry in diffFormLabels.entries) + ButtonSegment(value: entry.key, label: Text(entry.value)), + ], + selected: {form}, + showSelectedIcon: false, + onSelectionChanged: (selection) { + if (selection.isNotEmpty) onChanged(selection.first); + }, + ); +} + +/// Native action sheet/bottom sheet when fixed segment labels cannot fit. +Widget diffFormMenu( + BuildContext context, { + required DiffForm form, + required ValueChanged onChanged, +}) { + if (usesCupertino(context)) { + return Semantics( + label: 'Diff form', + button: true, + child: CupertinoButton( + padding: EdgeInsets.zero, + onPressed: () => showCupertinoModalPopup( + context: context, + builder: (sheetContext) => CupertinoActionSheet( + title: const Text('Diff form'), + actions: [ + for (final entry in diffFormLabels.entries) + CupertinoActionSheetAction( + isDefaultAction: entry.key == form, + onPressed: () { + Navigator.of(sheetContext).pop(); + onChanged(entry.key); + }, + child: Text(entry.value), + ), + ], + ), + ), + child: const Icon(CupertinoIcons.ellipsis), + ), + ); + } + return IconButton( + tooltip: 'Diff form', + icon: const Icon(Icons.more_vert), + onPressed: () => showModalBottomSheet( + context: context, + showDragHandle: true, + builder: (sheetContext) => SafeArea( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(16, 0, 16, 8), + child: Align( + alignment: AlignmentDirectional.centerStart, + child: Text( + 'Diff form', + style: Theme.of(sheetContext).textTheme.titleMedium, + ), + ), + ), + for (final entry in diffFormLabels.entries) + ListTile( + title: Text(entry.value), + selected: entry.key == form, + onTap: () { + Navigator.of(sheetContext).pop(); + onChanged(entry.key); + }, + ), + ], + ), + ), + ), + ); +} diff --git a/app/lib/features/changes/widgets/file_diff_viewer.dart b/app/lib/features/changes/widgets/file_diff_viewer.dart index 1e05c54e..2c1c186d 100644 --- a/app/lib/features/changes/widgets/file_diff_viewer.dart +++ b/app/lib/features/changes/widgets/file_diff_viewer.dart @@ -10,6 +10,7 @@ import '../domain/file_change.dart'; import '../domain/unified_patch.dart'; import 'change_style.dart'; import 'patch_view.dart'; +import 'raw_patch_view.dart'; /// The reusable viewer for one recorded file change: its kind, path, stat, /// tags, the rendered or raw unified patch, Copy patch (the server's exact @@ -38,6 +39,8 @@ class _FileDiffViewerState extends State { super.dispose(); } + void _selectForm(DiffForm value) => setState(() => _form = value); + void _close() { final close = widget.onClose; if (close != null) { @@ -147,16 +150,33 @@ class _FileDiffViewerState extends State { crossAxisAlignment: WrapCrossAlignment.center, children: [ if (file.hasPatch) - diffFormControl( - context, - form: _form, - onChanged: (value) => setState(() => _form = value), + LayoutBuilder( + builder: (context, constraints) { + // Two native segmented-control segments cannot show both + // fixed words at 2x text on a narrow host; their menu + // shows the same labels whole, one per row. + final control = + diffFormSegmentsFit(context, constraints.maxWidth) + ? diffFormControl( + context, + form: _form, + onChanged: _selectForm, + ) + : diffFormMenu( + context, + form: _form, + onChanged: _selectForm, + ); + return control; + }, + ), + _scrollsWhenTooWide( + copyPatchControl( + context, + enabled: file.hasPatch, + copied: _copied, + onPressed: _copy, ), - copyPatchControl( - context, - enabled: file.hasPatch, - copied: _copied, - onPressed: _copy, ), ], ), @@ -167,13 +187,13 @@ class _FileDiffViewerState extends State { ? CupertinoColors.separator.resolveFrom(context) : Theme.of(context).dividerColor, ), - Flexible(child: _body(context, cupertino, mono)), + Flexible(child: _body(context, mono)), ], ), ); } - Widget _body(BuildContext context, bool cupertino, TextStyle mono) { + Widget _body(BuildContext context, TextStyle mono) { final file = widget.file; if (file.binary) return _message(context, binaryDiffMessage); if (!file.hasPatch) { @@ -184,24 +204,7 @@ class _FileDiffViewerState extends State { container: true, label: 'Raw patch for ${file.path}', value: file.patch, - child: SingleChildScrollView( - padding: const EdgeInsets.fromLTRB(16, 0, 16, 16), - child: SingleChildScrollView( - // Raw patch bytes are one line each: scroll them sideways like the - // web view instead of wrapping a continuation under a new line. - scrollDirection: Axis.horizontal, - child: ExcludeSemantics( - child: SelectionArea( - child: Text( - file.patch!, - style: mono, - softWrap: false, - overflow: TextOverflow.visible, - ), - ), - ), - ), - ), + child: RawPatchView(patch: file.patch!, style: mono), ); } return SingleChildScrollView( @@ -218,6 +221,15 @@ class _FileDiffViewerState extends State { } } +/// Gives a native control its intrinsic width and lets it scroll sideways when +/// the dialog is narrower than the control, instead of letting the control clip +/// or break one of its fixed labels. +/// +/// The scroll view shrink-wraps when the control already fits, so the action +/// keeps its usual layout until scaled text or a narrow phone demands more room. +Widget _scrollsWhenTooWide(Widget control) => + SingleChildScrollView(scrollDirection: Axis.horizontal, child: control); + /// Open [file] in the platform's standard modal: a Material dialog on /// Android/desktop/web, a Cupertino dialog with a popup surface on iOS/macOS. Future showFileDiffViewer(BuildContext context, FileChange file) { @@ -231,15 +243,20 @@ Future showFileDiffViewer(BuildContext context, FileChange file) { // A popup surface spans the window unless it is inset; on a phone the // screen edge would clip its native rounded corners. final width = MediaQuery.sizeOf(dialogContext).width; - return Padding( - padding: EdgeInsets.symmetric( - horizontal: width < 600 ? 16 : 40, - vertical: 24, - ), - child: Center( - child: ConstrainedBox( - constraints: const BoxConstraints(maxWidth: 900), - child: CupertinoPopupSurface(child: SafeArea(child: viewer)), + return Theme( + // Dialogs open on the app Navigator, above the Changes page's own + // brightness-aware theme, so the popup needs its own. + data: hostTextTheme(dialogContext), + child: Padding( + padding: EdgeInsets.symmetric( + horizontal: width < 600 ? 16 : 40, + vertical: 24, + ), + child: Center( + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 900), + child: CupertinoPopupSurface(child: SafeArea(child: viewer)), + ), ), ), ); diff --git a/app/lib/features/changes/widgets/raw_patch_view.dart b/app/lib/features/changes/widgets/raw_patch_view.dart new file mode 100644 index 00000000..29966ef4 --- /dev/null +++ b/app/lib/features/changes/widgets/raw_patch_view.dart @@ -0,0 +1,75 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import 'change_style.dart'; + +/// The recorded raw patch bytes, one recorded line per line, in the host's own +/// selectable body. +/// +/// Material uses [SelectionArea]; a Cupertino host has no +/// [MaterialLocalizations], so it renders the same text in the read-only +/// [CupertinoTextField] the run detail already uses for plain selectable text. +/// Both forms keep their intrinsic line width, so long lines scroll sideways +/// instead of wrapping a continuation under a new line. +class RawPatchView extends StatefulWidget { + const RawPatchView({super.key, required this.patch, required this.style}); + + final String patch; + final TextStyle style; + + @override + State createState() => _RawPatchViewState(); +} + +class _RawPatchViewState extends State { + late final TextEditingController _text = TextEditingController( + text: widget.patch, + ); + + @override + void didUpdateWidget(RawPatchView oldWidget) { + super.didUpdateWidget(oldWidget); + if (widget.patch != _text.text) _text.text = widget.patch; + } + + @override + void dispose() { + _text.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final cupertino = usesCupertino(context); + return SingleChildScrollView( + padding: const EdgeInsets.fromLTRB(16, 0, 16, 16), + child: SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: cupertino + ? IntrinsicWidth( + child: ExcludeSemantics( + child: CupertinoTextField( + key: const ValueKey('raw-patch-field'), + controller: _text, + readOnly: true, + maxLines: null, + padding: EdgeInsets.zero, + decoration: const BoxDecoration(), + style: widget.style, + ), + ), + ) + : ExcludeSemantics( + child: SelectionArea( + child: Text( + widget.patch, + style: widget.style, + softWrap: false, + overflow: TextOverflow.visible, + ), + ), + ), + ), + ); + } +} diff --git a/app/lib/features/runs/ui/run_changes_action.dart b/app/lib/features/runs/ui/run_changes_action.dart new file mode 100644 index 00000000..d5cebe70 --- /dev/null +++ b/app/lib/features/runs/ui/run_changes_action.dart @@ -0,0 +1,126 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../core/api_gateway.dart'; +import '../../../ui/adaptive/host.dart'; +import '../../changes/changes.dart'; + +/// The run detail's action and page label. The viewer itself owns the +/// recorded summary and capture wording, so this bar stays neutral. +const runChangesLabel = 'Changes'; +const runChangesButtonKey = ValueKey('run-detail-changes'); + +/// The detail's `steps` exactly as returned by the server. The pushed page +/// snapshots the returned list once, so it never re-derives on each rebuild. +List runDetailChangeSteps(JsonMap run) { + final steps = run['steps']; + if (steps is List) return steps; + if (steps is List) return steps.cast(); + return const []; +} + +const _executingStatuses = {'queued', 'running', 'waiting'}; + +/// Whether the run detail offers the action at all. The opened page is a +/// snapshot of the recorded steps, so it is offered only once nothing is +/// executing: the server's own `executing` flag (which can stay true on a +/// failed run whose step is still active) or a queued/running/waiting status +/// would otherwise show a page that silently goes stale. +bool showRunChangesAction(JsonMap run) => + run['executing'] != true && + !_executingStatuses.contains('${run['status'] ?? ''}'.trim().toLowerCase()); + +/// A standard native button for the run detail body. It opens the recorded +/// changes in a platform page whose single navigation bar is the only chrome. +class RunChangesButton extends StatelessWidget { + const RunChangesButton({super.key, required this.run}); + + final JsonMap run; + + @override + Widget build(BuildContext context) { + final steps = runDetailChangeSteps(run); + // The web client shows the run-wide aggregate only for a succeeded run; a + // failed run still keeps each visit's own recorded capture. + final summary = showRunChangesSummary(run['status']); + void open() => showRunChanges(context, steps: steps, showSummary: summary); + if (usesCupertinoHost(context)) { + return CupertinoButton.tinted( + key: runChangesButtonKey, + onPressed: open, + child: const Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(CupertinoIcons.doc_text), + SizedBox(width: 6), + Text(runChangesLabel), + ], + ), + ); + } + return FilledButton.tonalIcon( + key: runChangesButtonKey, + onPressed: open, + icon: const Icon(Icons.difference_outlined), + label: const Text(runChangesLabel), + ); + } +} + +/// Opens the already-landed [ChangesViewer] for [steps] on a native page. +/// The bar is the one title bar; the viewer's own summary and capture facts +/// are passed through untouched, except for the caller's [showSummary] gate. +Future showRunChanges( + BuildContext context, { + required List steps, + required bool showSummary, +}) { + final cupertino = usesCupertinoHost(context); + return Navigator.of(context).push( + cupertino + ? CupertinoPageRoute( + builder: (_) => + _CupertinoChangesPage(steps: steps, showSummary: showSummary), + ) + : MaterialPageRoute( + builder: (_) => + _MaterialChangesPage(steps: steps, showSummary: showSummary), + ), + ); +} + +class _MaterialChangesPage extends StatelessWidget { + const _MaterialChangesPage({required this.steps, required this.showSummary}); + + final List steps; + final bool showSummary; + + @override + Widget build(BuildContext context) => Scaffold( + appBar: AppBar(title: const Text(runChangesLabel)), + body: SafeArea( + top: false, + child: ChangesViewer(steps: steps, showSummary: showSummary), + ), + ); +} + +class _CupertinoChangesPage extends StatelessWidget { + const _CupertinoChangesPage({required this.steps, required this.showSummary}); + + final List steps; + final bool showSummary; + + @override + Widget build(BuildContext context) => CupertinoPageScaffold( + navigationBar: const CupertinoNavigationBar(middle: Text(runChangesLabel)), + child: SafeArea( + // A CupertinoApp supplies no Material theme; follow the host brightness + // so the viewer's Material-derived section text stays readable. + child: Theme( + data: hostTextTheme(context), + child: ChangesViewer(steps: steps, showSummary: showSummary), + ), + ), + ); +} diff --git a/app/lib/features/runs/ui/run_detail_cupertino.dart b/app/lib/features/runs/ui/run_detail_cupertino.dart index 28fdddfe..c2f34487 100644 --- a/app/lib/features/runs/ui/run_detail_cupertino.dart +++ b/app/lib/features/runs/ui/run_detail_cupertino.dart @@ -2,6 +2,7 @@ import 'package:flutter/cupertino.dart'; import '../../../core/api_gateway.dart'; import '../domain/run_models.dart'; +import 'run_changes_action.dart'; import 'run_detail_content.dart'; /// The runs detail with standard Cupertino controls. It has no Material @@ -26,7 +27,11 @@ Widget buildCupertinoRunDetail({ children: [ Padding( padding: const EdgeInsetsDirectional.fromSTEB(16, 8, 16, 0), - child: Row( + child: Wrap( + alignment: WrapAlignment.spaceBetween, + crossAxisAlignment: WrapCrossAlignment.center, + spacing: 8, + runSpacing: 4, children: [ CupertinoButton( padding: EdgeInsets.zero, @@ -40,7 +45,7 @@ Widget buildCupertinoRunDetail({ ], ), ), - const Spacer(), + if (showRunChangesAction(run)) RunChangesButton(run: run), if (copying) const CupertinoActivityIndicator(), ], ), diff --git a/app/lib/features/runs/ui/run_detail_material.dart b/app/lib/features/runs/ui/run_detail_material.dart index 27d98316..13a1125f 100644 --- a/app/lib/features/runs/ui/run_detail_material.dart +++ b/app/lib/features/runs/ui/run_detail_material.dart @@ -2,6 +2,7 @@ import 'package:flutter/material.dart'; import '../../../core/api_gateway.dart'; import '../domain/run_models.dart'; +import 'run_changes_action.dart'; import 'run_detail_content.dart'; /// The runs detail with standard Material controls. @@ -23,13 +24,18 @@ Widget buildMaterialRunDetail({ key: ValueKey('run-detail-${run['id']}'), padding: const EdgeInsets.all(16), children: [ - Align( - alignment: AlignmentDirectional.centerStart, - child: TextButton.icon( - onPressed: onBack, - icon: const Icon(Icons.arrow_back), - label: const Text('Back to list'), - ), + Wrap( + spacing: 8, + runSpacing: 4, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + TextButton.icon( + onPressed: onBack, + icon: const Icon(Icons.arrow_back), + label: const Text('Back to list'), + ), + if (showRunChangesAction(run)) RunChangesButton(run: run), + ], ), Text(detailTitle(run), style: theme.textTheme.headlineSmall), const SizedBox(height: 8), diff --git a/app/notes/D1-wire.md b/app/notes/D1-wire.md new file mode 100644 index 00000000..2dc2c94f --- /dev/null +++ b/app/notes/D1-wire.md @@ -0,0 +1,191 @@ +# D1-wire — native Changes action in the run detail + +## Manager completion after retained stage limit + +The final Code visit completed its fixes, but the runner could not revisit Review +again (visit limit3). No implementation was rerun or discarded. Manager checked +the retained source, focused changes/wiring tests and analyzer, then rebuilt and +drove the real RunDetailView fixture:15 checks/20 captures pass, including both +320px/2x native menus and selected Raw patch. Narrow hosts use a standard native +sheet, never a custom segmented clone. Manager separated the cohesive form +controls into diff_form_control.dart and used the actual host/native label style +instead of a hard-coded font measurement. No font/size/palette override remains. +Evidence: approved temp/changes-wiring-manager-browser. Actual shell merges and +publication are tracked separately in WORK.md; earlier notes below are historical. + +Adds one standard native action to the existing run-detail bodies and reuses the +landed `ChangesViewer`. No API call, shell/main or pubspec edit; no commit, push +or deploy. + +## Behaviour + +- Material: `FilledButton.tonalIcon` labelled **Changes** beside **Back to + list**. It pushes a `MaterialPageRoute` whose only bar is an + `AppBar(title: Text('Changes'))` above the viewer. +- Cupertino: `CupertinoButton.tinted` labelled **Changes** in the detail's + header row. It pushes a `CupertinoPageRoute` whose only bar is a + `CupertinoNavigationBar`; native back is automatic. +- The action is offered once the run has stopped executing: the server's + `executing` flag must be false and the status must not be + `queued`/`running`/`waiting`. The opened page snapshots the recorded steps, so + an executing run is not given a page that could go stale or miss a later + settlement; its evidence belongs to the live visit pane when that slice + lands. `showRunChangesAction` holds that check. +- The run-wide aggregate is shown only for `succeeded`, matching + `web/src/changes.js` `showRunChangesSummary` and PARITY R4. A failed run keeps + each visit's own recorded capture (stage, visit number, status, capture + counters/scope/diagnostic and file rows) without claiming a settled final + state; `ChangesViewer` gained a `showSummary` input for that. +- `runDetailChangeSteps` passes the server's `steps` unchanged; the page + snapshots the list once. +- No capture, visit, partial/missing/unavailable wording or diff rendering is + reinterpreted by the wiring; the changes domain still owns all of it. + +## Review findings addressed + +1. **Failed/running runs no longer receive a settled Changes page.** The + aggregate and filter are hidden unless the status is `succeeded`; failed + runs still open the per-visit evidence. Executing runs get no action at all, + which also removes the stale-snapshot case. Covered by failed and running + regressions plus browser checks. +2. **Cupertino Raw patch no longer asserts.** The raw body moved to + `RawPatchView`: Material keeps `SelectionArea`; Cupertino renders the exact + recorded bytes in a read-only `CupertinoTextField` (the pattern the run + detail already uses), with its intrinsic line width and horizontal scrolling, + so no `MaterialLocalizations` are required. A Cupertino Raw regression taps + the control and checks the native field, and the browser probe opens it. +3. **Dark Cupertino Changes now follows the host.** Both the Cupertino page and + the file-diff popup it opens wrap the viewer in `hostTextTheme(context)` + (`change_style.dart`): a `Theme` with `CupertinoTheme.brightnessOf(context)` + and the host platform. The popup matters because dialogs open on the app + Navigator, above the page's own theme, so the first fix alone left the diff + header light-theme near-black on the dark popup. Widget regression opens the + file from the dark page and asserts the `Modified` header is light; the probe + measures the rendered header pixels (luminance 0.87; 0.15 without the fix), + and captures cover dark Changes and dark diff. +4. **The diff form labels stay whole at 320 px and 2x text.** A two-segment + control cannot keep `Rendered` and `Raw patch` on one line there: Material + broke `Rendered` mid-word and Cupertino clipped `Raw patch` to `Raw`, with no + way to see the rest. `diffFormSegmentsFit` measures the two fixed words at + the host's text scale and, when the native segmented control cannot fit both, + the viewer uses the host's standard menu instead (a Material bottom sheet or + a Cupertino action sheet) with the same two words, one per row. The current + mode is highlighted and the menu is titled `Diff form`. The `Copy patch` + action keeps its intrinsic width in a horizontal strip rather than breaking + its words. Widget regressions on both hosts assert that no label breaks + inside a word, is clipped vertically or is clipped horizontally, and that + choosing `Raw patch` from the menu shows the recorded raw body. Browser + captures cover the 320x2 menu and raw state on both hosts. + +The action gate now also honours the server's `executing` flag (web's +`isExecuting`), so a failed run whose step is still active is not offered the +snapshot page; the status list remains as the fallback for replies without the +flag. + +The earlier comment claiming `runDetailChangeSteps` returns the same list +instance was corrected. The browser/system Back advisory is unchanged and +unresolved: it needs `AppRouterDelegate.popRoute`/Router work in `lib/shell/`, +which this lane must not edit. The probe's Back checks exercise the page's own +back control only. + +## Files + +``` +lib/features/runs/ui/run_changes_action.dart new, 126 lines +lib/features/runs/ui/run_detail_material.dart +13/-7 +lib/features/runs/ui/run_detail_cupertino.dart +8/-2 +lib/features/changes/changes.dart export hostTextTheme +lib/features/changes/domain/run_changes.dart +7 +lib/features/changes/widgets/change_style.dart +hostTextTheme, fit check, native menu +lib/features/changes/widgets/changes_viewer.dart showSummary gate +lib/features/changes/widgets/file_diff_viewer.dart raw body, themed dialog, form menu +lib/features/changes/widgets/raw_patch_view.dart new, 75 lines +test/features/runs/ui/run_changes_action_test.dart new, 177 lines +test/features/runs/ui/run_changes_status_test.dart new, 204 lines +test/features/changes/diff_presentation_test.dart +2x label regressions +test/features/changes/changes_viewer_test.dart 2x control expectation +test/features/changes/run_changes_test.dart +9 (status gate) +tool/diff_wiring_probe.dart fixture entry, scale=2 +tool/diff_wiring_probe.mjs browser driver, pixel probe, 2x/320 +``` + +## Checks (actual results) + +- `flutter test test/features/changes test/features/runs` — **159 tests passed**. +- `flutter test test/features/runs/ui/run_changes_action_test.dart + test/features/runs/ui/run_changes_status_test.dart + test/features/runs/ui/run_detail_widget_test.dart test/features/changes` — + **67 tests passed**. +- `flutter analyze` — **No issues found**. +- `dart format --output=none --set-exit-if-changed` on every touched Dart file — + clean (0 changed). +- `node --check tool/diff_wiring_probe.mjs` — passed. +- `flutter build web --target tool/diff_wiring_probe.dart --output + build/probe-wire` — built. +- `flutter build web --output build/web-wire-check` — built. + +Widget regressions cover both hosts: the happy path (recorded filename, stat, +per-stage Visit 1, rendered diff, Close diff, Back), unavailable capture +wording, a failed run without the aggregate but with its visit capture, an +executing run with no action, the dark host text colour on both the Changes page +and the opened diff header, the Cupertino Raw native field, and the 320x720 2x +labels: no mid-word break, no vertical or horizontal clipping, the native menu +labels and choosing `Raw patch` in it, and the unchanged segmented control on a +wide host. + +## Real browser evidence + +`tool/diff_wiring_probe.dart` renders the real `RunDetailView` over a fake +`get_run` gateway; `tool/diff_wiring_probe.mjs` serves it on an OS-assigned +loopback port and drives headless Chrome. Query parameters select the fixture: +`?run=failed`, `?run=running`, `?capture=unavailable`, +`?platform=cupertino&theme=light|dark` and `?scale=2` for the 2x text states. +No server or operator run was touched. + +All **15/15 checks** passed (`d1-wire/d1-wire-probe.json`), 20 captures: + +- Material run detail shows the native Changes action; it opens the recorded + `lib/features/runs/ui/run_changes_action.dart` with `1 file changed · +2 -1` + and its implementer visit section. +- The recorded file opens its actual diff (`- const label = "Old";`, + `+ const recorded = true;`) with Rendered/Raw patch/Copy patch/Close diff; + Close diff and Back return. +- `?capture=unavailable` shows `Changes · capture unavailable` and the server + diagnostic, never "No changes observed". +- `?run=failed` keeps the visit capture and shows no run-wide `file changed` + summary. +- `?run=running` offers no Changes action. +- Cupertino shows the tinted Changes button, one bar, the recorded file and + diff; Raw patch renders in the native field with the other actions intact; + Close diff and Back return. +- Cupertino dark renders the summary and the recorded diff with light text; the + diff header is sampled from the rendered capture (max luminance 0.87, above + the 0.5 readable-text gate) instead of only checking that the words exist. +- `?scale=2` at 320x720 opens the same diff on both hosts, shows the `Diff form` + menu with `Rendered` and `Raw patch` whole, and renders the recorded raw body + after choosing `Raw patch`. + +Captures in the shared `d1-wire/` folder (390x844, plus the 320x720 2x states): + +``` +d1-wire-material-detail.png d1-wire-material-changes.png +d1-wire-material-diff.png d1-wire-material-back.png +d1-wire-material-unavailable.png d1-wire-material-failed.png +d1-wire-material-running.png d1-wire-cupertino-detail.png +d1-wire-cupertino-changes.png d1-wire-cupertino-diff.png +d1-wire-cupertino-raw.png d1-wire-cupertino-back.png +d1-wire-cupertino-dark-changes.png d1-wire-cupertino-dark-diff.png +d1-wire-material-2x-320-diff.png d1-wire-material-2x-320-menu.png +d1-wire-material-2x-320-raw.png d1-wire-cupertino-2x-320-diff.png +d1-wire-cupertino-2x-320-menu.png d1-wire-cupertino-2x-320-raw.png +``` + +## Not verified / remaining + +- Browser and Android system Back on the pushed page are unverified; the + advisory Router integration was not changed. +- Active-run per-visit changes are not shown anywhere yet; that belongs to the + live run visit pane, not this snapshot page. +- Mobile targets were not built, installed or run; Cupertino is verified through + widget tests and browser rendering only, so **mobile remains unverified**. +- All data is fixture data; no live server or operator run was used. diff --git a/app/test/features/changes/changes_viewer_test.dart b/app/test/features/changes/changes_viewer_test.dart index 5278e84b..6ec11041 100644 --- a/app/test/features/changes/changes_viewer_test.dart +++ b/app/test/features/changes/changes_viewer_test.dart @@ -466,7 +466,9 @@ void main() { ), ); expect(tester.takeException(), isNull); - expect(find.text('Rendered'), findsOneWidget); + // The host is too narrow for a two-segment control at 2x, so the same form + // selection is offered through the native menu instead. + expect(find.byTooltip('Diff form'), findsOneWidget); expect(find.text('Copy patch'), findsOneWidget); expect(find.byTooltip('Close diff'), findsOneWidget); }); diff --git a/app/test/features/changes/diff_presentation_test.dart b/app/test/features/changes/diff_presentation_test.dart index 77dad873..a522ec68 100644 --- a/app/test/features/changes/diff_presentation_test.dart +++ b/app/test/features/changes/diff_presentation_test.dart @@ -1,5 +1,6 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:pipelines_app/features/changes/changes.dart'; import 'package:pipelines_app/features/changes/widgets/change_style.dart'; @@ -16,6 +17,64 @@ const _raggedPatch = '-x\n' ' tail\n'; +/// Opens the real single-file diff modal from a host, so the test covers the +/// dialog's own width and insets rather than the viewer in isolation. +Widget _diffDialogOpener(FileChange file) => Builder( + builder: (context) => TextButton( + onPressed: () => showFileDiffViewer(context, file), + child: const Text('Open diff'), + ), +); + +/// Fails when a fixed control label is broken inside a word or clipped by its +/// control. A label may wrap only between whole words, which is how a native +/// menu keeps an accessibility-size label readable. +void _expectWholeLabel(WidgetTester tester, Finder finder, String label) { + final paragraph = tester.renderObject( + find.descendant(of: finder, matching: find.byType(RichText)), + ); + final span = paragraph.text as TextSpan; + expect(span.toPlainText(), label); + expect(paragraph.didExceedMaxLines, isFalse); + final boxes = paragraph + .getBoxesForSelection( + TextSelection(baseOffset: 0, extentOffset: label.length), + ) + .toList(); + expect(boxes, isNotEmpty); + // The laid-out paragraph must be tall enough to paint every line it broke. + expect( + boxes.last.bottom, + lessThanOrEqualTo(paragraph.size.height + 0.5), + reason: '"$label" must not be clipped vertically', + ); + final widestLine = boxes + .map((box) => box.right - box.left) + .reduce((a, b) => a > b ? a : b); + final style = span.style ?? const TextStyle(); + var widestWord = 0.0; + for (final word in label.split(' ')) { + final painter = TextPainter( + text: TextSpan(text: word, style: style), + textDirection: TextDirection.ltr, + textScaler: paragraph.textScaler, + )..layout(); + if (painter.width > widestWord) widestWord = painter.width; + } + // A line narrower than a whole word means the label broke mid-word. + expect( + widestLine, + greaterThanOrEqualTo(widestWord - 0.5), + reason: '"$label" must not break inside a word', + ); + // A clipped line would paint wider than the paragraph's laid-out box. + expect( + widestLine, + lessThanOrEqualTo(paragraph.size.width + 0.5), + reason: '"$label" must not be clipped horizontally', + ); +} + void main() { test( 'patch typography preserves the native host style without overrides', @@ -139,6 +198,49 @@ void main() { ); }); + testWidgets('the Cupertino raw patch is a native selectable field', ( + tester, + ) async { + await tester.pumpWidget( + cupertinoHost( + SizedBox( + height: 400, + child: FileDiffViewer( + file: FileChange( + path: 'lib/feature.dart', + kind: ChangeKind.modified, + patch: multiHunkPatch, + ), + ), + ), + ), + ); + await tester.tap(find.text('Raw patch')); + await tester.pumpAndSettle(); + + // A CupertinoApp has no MaterialLocalizations, so Raw must not use the + // Material SelectionArea; it renders the recorded bytes in a native field. + expect(tester.takeException(), isNull); + expect(find.byType(SelectionArea), findsNothing); + final field = tester.widget( + find.byKey(const ValueKey('raw-patch-field')), + ); + expect(field.readOnly, isTrue); + expect(field.maxLines, isNull); + expect(field.controller?.text, multiHunkPatch); + expect( + find.ancestor( + of: find.byKey(const ValueKey('raw-patch-field')), + matching: find.byWidgetPredicate( + (widget) => + widget is SingleChildScrollView && + widget.scrollDirection == Axis.horizontal, + ), + ), + findsOneWidget, + ); + }); + testWidgets('a Cupertino row wraps its recorded path instead of clipping it', ( tester, ) async { @@ -203,4 +305,98 @@ void main() { expect(rect.right, lessThan(382)); expect(tester.takeException(), isNull); }); + + final diffFile = FileChange( + path: 'lib/feature.dart', + kind: ChangeKind.modified, + patch: multiHunkPatch, + ); + + for (final cupertino in [false, true]) { + final host = cupertino ? 'Cupertino' : 'Material'; + + testWidgets('$host diff labels stay whole at 320x720 with 2x text', ( + tester, + ) async { + tester.view.physicalSize = const Size(320, 720); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + final opener = _diffDialogOpener(diffFile); + await tester.pumpWidget( + cupertino + ? cupertinoHost(opener, scaler: const TextScaler.linear(2)) + : materialHost(opener, scaler: const TextScaler.linear(2)), + ); + await tester.tap(find.text('Open diff')); + await tester.pumpAndSettle(); + + // A segmented control cannot keep both fixed words at this size, so the + // host's native menu carries them instead. "Rendered" used to break + // mid-word and "Raw patch" used to be clipped to "Raw". + expect(find.byType(SegmentedButton), findsNothing); + expect( + find.byType(CupertinoSlidingSegmentedControl), + findsNothing, + ); + + // Copy patch stays a standard action at intrinsic width; it must not + // break its two words either. + _expectWholeLabel(tester, find.text('Copy patch'), 'Copy patch'); + + await tester.tap( + cupertino + ? find.byIcon(CupertinoIcons.ellipsis) + : find.byTooltip('Diff form'), + ); + await tester.pumpAndSettle(); + + final items = cupertino + ? find.byType(CupertinoActionSheetAction) + : find.byType(ListTile); + expect(items, findsNWidgets(2)); + for (final label in ['Rendered', 'Raw patch']) { + _expectWholeLabel( + tester, + find.descendant(of: items, matching: find.text(label)), + label, + ); + } + + await tester.tap( + find.descendant(of: items, matching: find.text('Raw patch')), + ); + await tester.pumpAndSettle(); + if (cupertino) { + expect(find.byKey(const ValueKey('raw-patch-field')), findsOneWidget); + } else { + expect(find.text(multiHunkPatch), findsOneWidget); + } + expect(tester.takeException(), isNull); + }); + } + + for (final cupertino in [false, true]) { + testWidgets( + '${cupertino ? 'Cupertino' : 'Material'} wide host keeps the native ' + 'segmented control', + (tester) async { + await tester.pumpWidget( + cupertino + ? cupertinoHost(_diffDialogOpener(diffFile)) + : materialHost(_diffDialogOpener(diffFile)), + ); + await tester.tap(find.text('Open diff')); + await tester.pumpAndSettle(); + expect( + cupertino + ? find.byType(CupertinoSlidingSegmentedControl) + : find.byType(SegmentedButton), + findsOneWidget, + ); + expect(find.text('Rendered'), findsOneWidget); + expect(find.text('Raw patch'), findsOneWidget); + expect(tester.takeException(), isNull); + }, + ); + } } diff --git a/app/test/features/changes/run_changes_test.dart b/app/test/features/changes/run_changes_test.dart index 384c1170..60353033 100644 --- a/app/test/features/changes/run_changes_test.dart +++ b/app/test/features/changes/run_changes_test.dart @@ -415,6 +415,15 @@ void main() { ); }); + test('showRunChangesSummary is true only for a settled succeeded run', () { + expect(showRunChangesSummary('succeeded'), isTrue); + expect(showRunChangesSummary(' Succeeded '), isTrue); + for (final status in ['failed', 'running', 'waiting', 'canceled', '']) { + expect(showRunChangesSummary(status), isFalse, reason: status); + } + expect(showRunChangesSummary(null), isFalse); + }); + test('header covers every empty-capture variant', () { expect( runChangesHeader(_run(unavailable: true, files: const [])), diff --git a/app/test/features/runs/ui/run_changes_action_test.dart b/app/test/features/runs/ui/run_changes_action_test.dart new file mode 100644 index 00000000..62a6c0a7 --- /dev/null +++ b/app/test/features/runs/ui/run_changes_action_test.dart @@ -0,0 +1,177 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/changes/changes.dart'; +import 'package:pipelines_app/features/runs/data/runs_repository.dart'; +import 'package:pipelines_app/features/runs/ui/run_changes_action.dart'; +import 'package:pipelines_app/features/runs/ui/run_detail_view.dart'; +import 'package:pipelines_app/features/runs/ui/runs_controller.dart'; + +import '../../changes/fixtures.dart'; + +enum _Platform { material, cupertino } + +class _FakeGateway implements ApiGateway { + _FakeGateway(this.detail); + final JsonMap detail; + + @override + Stream get frames => const Stream.empty(); + + @override + Future call(String type, [JsonMap fields = const {}]) { + if (type != 'get_run') throw UnsupportedError(type); + return Future.value({'run_detail': detail}); + } +} + +JsonMap _run({ + JsonMap? fileChanges, + String status = 'succeeded', + String stepStatus = 'completed', +}) => { + 'id': 9, + 'title': 'Wiring run', + 'name': 'release', + 'status': status, + 'steps': [ + stepFixture( + stage: 'implementer', + sequence: 1, + status: stepStatus, + fileChanges: fileChanges, + ), + stepFixture( + stage: 'reviewer', + sequence: 2, + status: stepStatus, + fileChanges: null, + ), + ], +}; + +Future _pumpDetail( + WidgetTester tester, + _Platform platform, + RunsController controller, +) async { + tester.view.physicalSize = const Size(500, 1200); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + final view = RunDetailView(controller: controller, onBack: () {}); + await tester.pumpWidget( + platform == _Platform.material + ? MaterialApp(home: Scaffold(body: view)) + : CupertinoApp( + // The real host chooses Cupertino on iOS/macOS; state that platform + // without mutating the global debug override, as the Changes tests do. + builder: (context, app) => Theme( + data: ThemeData(platform: TargetPlatform.iOS), + child: app!, + ), + home: CupertinoPageScaffold(child: view), + ), + ); + await tester.pumpAndSettle(); +} + +void main() { + for (final platform in _Platform.values) { + testWidgets( + '${platform.name}: Changes opens the recorded files, diff and returns', + (tester) async { + final controller = RunsController( + RunsRepository( + _FakeGateway( + _run( + fileChanges: captureFixture( + files: [ + fileChangeFixture( + path: 'lib/feature.dart', + patch: multiHunkPatch, + ), + ], + ), + ), + ), + ), + ); + addTearDown(controller.dispose); + await controller.select(9); + await _pumpDetail(tester, platform, controller); + + await tester.tap(find.byKey(runChangesButtonKey)); + await tester.pumpAndSettle(); + + expect(find.text('Changes'), findsOneWidget); + expect(find.text('lib/feature.dart'), findsOneWidget); + expect( + find.text('1 file changed · +2 -2 · capture incomplete'), + findsOneWidget, + ); + // Visit numbers are per stage, so both stages' first visits say Visit 1. + expect(find.text('Visit 1 · completed'), findsNWidgets(2)); + + await tester.tap( + find.byKey(const ValueKey('change-1-lib/feature.dart')), + ); + await tester.pumpAndSettle(); + final rendered = tester + .widgetList(find.byType(RichText)) + .map((rich) => rich.text.toPlainText()) + .join('\n'); + expect(rendered, contains('+ added line')); + expect(rendered, contains('- removed line')); + + if (platform == _Platform.material) { + await tester.tap(find.byTooltip('Close diff')); + } else { + await tester.tap(find.byIcon(CupertinoIcons.xmark)); + } + await tester.pumpAndSettle(); + expect(find.text('lib/feature.dart'), findsOneWidget); + + if (platform == _Platform.material) { + await tester.tap(find.byTooltip('Back')); + } else { + await tester.tap(find.byType(CupertinoNavigationBarBackButton)); + } + await tester.pumpAndSettle(); + expect(find.text('Wiring run'), findsOneWidget); + expect(find.byKey(runChangesButtonKey), findsOneWidget); + expect(find.text('lib/feature.dart'), findsNothing); + }, + ); + + testWidgets( + '${platform.name}: an unavailable capture keeps its gap wording', + (tester) async { + final diagnostic = + 'Workspace snapshot unavailable; changes could not be compared.'; + final controller = RunsController( + RunsRepository( + _FakeGateway( + _run( + fileChanges: captureFixture( + status: 'unavailable', + diagnostic: diagnostic, + ), + ), + ), + ), + ); + addTearDown(controller.dispose); + await controller.select(9); + await _pumpDetail(tester, platform, controller); + + await tester.tap(find.byKey(runChangesButtonKey)); + await tester.pumpAndSettle(); + expect(find.text('Changes · capture unavailable'), findsOneWidget); + expect(find.text(diagnostic), findsWidgets); + expect(find.text(emptyCaptureDetail), findsNothing); + expect(find.text('No changes observed'), findsNothing); + }, + ); + } +} diff --git a/app/test/features/runs/ui/run_changes_status_test.dart b/app/test/features/runs/ui/run_changes_status_test.dart new file mode 100644 index 00000000..bdaf6c8d --- /dev/null +++ b/app/test/features/runs/ui/run_changes_status_test.dart @@ -0,0 +1,204 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/runs/data/runs_repository.dart'; +import 'package:pipelines_app/features/runs/ui/run_changes_action.dart'; +import 'package:pipelines_app/features/runs/ui/run_detail_view.dart'; +import 'package:pipelines_app/features/runs/ui/runs_controller.dart'; + +import '../../changes/fixtures.dart'; + +enum _Platform { material, cupertino } + +class _FakeGateway implements ApiGateway { + _FakeGateway(this.detail); + final JsonMap detail; + + @override + Stream get frames => const Stream.empty(); + + @override + Future call(String type, [JsonMap fields = const {}]) { + if (type != 'get_run') throw UnsupportedError(type); + return Future.value({'run_detail': detail}); + } +} + +JsonMap _run({ + required String status, + JsonMap? fileChanges, + String stepStatus = 'completed', +}) => { + 'id': 9, + 'title': 'Wiring run', + 'name': 'release', + 'status': status, + 'steps': [ + stepFixture( + stage: 'implementer', + sequence: 1, + status: stepStatus, + fileChanges: fileChanges, + ), + stepFixture( + stage: 'reviewer', + sequence: 2, + status: stepStatus, + fileChanges: null, + ), + ], +}; + +Future _pumpDetail( + WidgetTester tester, + _Platform platform, + JsonMap run, { + Brightness brightness = Brightness.light, +}) async { + tester.view.physicalSize = const Size(500, 1200); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + final controller = RunsController(RunsRepository(_FakeGateway(run))); + addTearDown(controller.dispose); + await controller.select(9); + final view = RunDetailView(controller: controller, onBack: () {}); + await tester.pumpWidget( + platform == _Platform.material + ? MaterialApp( + theme: ThemeData(brightness: brightness), + home: Scaffold(body: view), + ) + : CupertinoApp( + theme: CupertinoThemeData(brightness: brightness), + builder: (context, app) => Theme( + data: ThemeData(platform: TargetPlatform.iOS), + child: app!, + ), + home: CupertinoPageScaffold(child: view), + ), + ); + await tester.pumpAndSettle(); +} + +Future _openChanges( + WidgetTester tester, + _Platform platform, + JsonMap run, { + Brightness brightness = Brightness.light, +}) async { + await _pumpDetail(tester, platform, run, brightness: brightness); + await tester.tap(find.byKey(runChangesButtonKey)); + await tester.pumpAndSettle(); +} + +void main() { + test('the Changes action waits for the run to stop executing', () { + for (final status in ['queued', 'running', 'waiting', ' RUNNING ']) { + expect(showRunChangesAction({'status': status}), isFalse, reason: status); + } + for (final status in ['succeeded', 'failed', 'canceled', 'interrupted']) { + expect(showRunChangesAction({'status': status}), isTrue, reason: status); + } + // The server can keep a failed run flagged while one of its steps is still + // active; the snapshot page would go stale, so the flag wins. + expect( + showRunChangesAction({'status': 'failed', 'executing': true}), + isFalse, + ); + expect( + showRunChangesAction({'status': 'succeeded', 'executing': false}), + isTrue, + ); + }); + + for (final platform in _Platform.values) { + testWidgets( + '${platform.name}: a failed run keeps visit evidence, not a summary', + (tester) async { + await _openChanges( + tester, + platform, + _run( + status: 'failed', + fileChanges: captureFixture( + files: [fileChangeFixture(path: 'lib/feature.dart')], + ), + ), + ); + + // The web client shows the aggregate only for succeeded runs. + expect(find.textContaining('file changed ·'), findsNothing); + expect( + find.textContaining('The summary counts each path once'), + findsNothing, + ); + // The visit's own recorded capture stays reachable. + expect(find.text('lib/feature.dart'), findsOneWidget); + expect(find.text('Visit 1 · completed'), findsNWidgets(2)); + expect(tester.takeException(), isNull); + }, + ); + + testWidgets( + '${platform.name}: an active run offers no snapshot Changes page', + (tester) async { + await _pumpDetail( + tester, + platform, + _run(status: 'running', stepStatus: 'running'), + ); + + // The opened page would not follow live captures, so an executing run + // has no action until the live visit pane can show them. + expect(find.byKey(runChangesButtonKey), findsNothing); + expect(find.text('Changes'), findsNothing); + expect(tester.takeException(), isNull); + }, + ); + + testWidgets( + '${platform.name}: the Changes page follows a dark host theme', + (tester) async { + await _openChanges( + tester, + platform, + _run( + status: 'succeeded', + fileChanges: captureFixture( + files: [fileChangeFixture(path: 'lib/feature.dart')], + ), + ), + brightness: Brightness.dark, + ); + + final header = tester.widget( + find.textContaining('1 file changed'), + ); + final color = header.style?.color; + expect(color, isNotNull); + expect( + color!.computeLuminance(), + greaterThan(0.5), + reason: 'section text must be light on a dark host: $color', + ); + + // The diff opens on the app Navigator, above the page's theme, so its + // own header must follow the host brightness too. + await tester.tap( + find.byKey(const ValueKey('change-1-lib/feature.dart')), + ); + await tester.pumpAndSettle(); + final title = tester.widget(find.text('Modified')); + final titleColor = title.style?.color; + expect(titleColor, isNotNull); + expect( + titleColor!.computeLuminance(), + greaterThan(0.5), + reason: 'diff header must be light on a dark host: $titleColor', + ); + expect(tester.takeException(), isNull); + }, + ); + } +} diff --git a/app/tool/diff_wiring_probe.dart b/app/tool/diff_wiring_probe.dart new file mode 100644 index 00000000..40515069 --- /dev/null +++ b/app/tool/diff_wiring_probe.dart @@ -0,0 +1,188 @@ +// Standalone fixture entry for real-browser run-detail Changes wiring evidence. +// +// Build and probe (from app/): +// flutter build web --target tool/diff_wiring_probe.dart --output build/probe-wire +// node tool/diff_wiring_probe.mjs --root build/probe-wire --out DIR +// +// Server-shaped fixtures only: a fake gateway answers the same get_run envelope +// the app consumes. No server or operator run is touched. +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/runs/data/runs_repository.dart'; +import 'package:pipelines_app/features/runs/ui/run_detail_view.dart'; +import 'package:pipelines_app/features/runs/ui/runs_controller.dart'; + +const _patch = + '--- "a/lib/features/runs/ui/run_changes_action.dart"\n' + '+++ "b/lib/features/runs/ui/run_changes_action.dart"\n' + '@@ -1,3 +1,4 @@\n' + ' import package:flutter/material.dart;\n' + '-const label = "Old";\n' + '+const label = "Changes";\n' + '+const recorded = true;\n' + ' // end\n'; + +class _FakeGateway implements ApiGateway { + _FakeGateway(this.detail); + + final JsonMap detail; + + @override + Stream get frames => const Stream.empty(); + + @override + Future call(String type, [JsonMap fields = const {}]) { + if (type != 'get_run') throw UnsupportedError(type); + return Future.value({'run_detail': detail}); + } +} + +JsonMap _run({ + required bool unavailable, + String status = 'succeeded', + String stepStatus = 'completed', +}) => { + 'id': 12, + 'title': 'Changes wiring probe', + 'name': 'probe', + 'status': status, + 'steps': [ + { + 'stage': 'implementer', + 'sequence': 1, + 'status': stepStatus, + 'file_changes': unavailable + ? { + 'status': 'unavailable', + 'skipped': 0, + 'omitted': 0, + 'diagnostic': + 'Workspace snapshot unavailable; changes could not be ' + 'compared.', + 'files': [], + } + : status == 'running' + ? null + : { + 'status': 'complete', + 'scope': 'Git tracked and nonignored files in the run directory', + 'skipped': 0, + 'omitted': 0, + 'diagnostic': '', + 'files': [ + { + 'path': 'lib/features/runs/ui/run_changes_action.dart', + 'kind': 'modified', + 'patch': _patch, + }, + ], + }, + }, + ], +}; + +void main() { + final params = Uri.base.queryParameters; + final cupertino = params['platform'] == 'cupertino'; + final stepsUnavailable = params['capture'] == 'unavailable'; + final status = params['run'] == 'failed' + ? 'failed' + : params['run'] == 'running' + ? 'running' + : 'succeeded'; + final stepStatus = status == 'running' ? 'running' : 'completed'; + final theme = params['theme'] == 'light' ? Brightness.light : Brightness.dark; + // Browser text scaling is a fixture input like platform and theme: the + // accessibility states are otherwise unreachable from CDP metrics alone. + final textScale = double.tryParse(params['scale'] ?? '') ?? 1; + final body = _ProbeBody( + unavailable: stepsUnavailable, + status: status, + stepStatus: stepStatus, + ); + Widget scaled(BuildContext context, Widget? app) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(textScale)), + child: app!, + ); + if (cupertino) { + runApp( + CupertinoApp( + title: 'Run changes probe', + theme: CupertinoThemeData(brightness: theme), + builder: (context, app) => Theme( + data: ThemeData(platform: TargetPlatform.iOS), + child: scaled(context, app), + ), + home: body, + ), + ); + } else { + runApp( + MaterialApp( + title: 'Run changes probe', + theme: ThemeData(brightness: theme, platform: TargetPlatform.android), + builder: scaled, + home: body, + ), + ); + } +} + +class _ProbeBody extends StatefulWidget { + const _ProbeBody({ + required this.unavailable, + required this.status, + required this.stepStatus, + }); + + final bool unavailable; + final String status; + final String stepStatus; + + @override + State<_ProbeBody> createState() => _ProbeBodyState(); +} + +class _ProbeBodyState extends State<_ProbeBody> { + late final RunsController _controller = RunsController( + RunsRepository( + _FakeGateway( + _run( + unavailable: widget.unavailable, + status: widget.status, + stepStatus: widget.stepStatus, + ), + ), + ), + ); + + @override + void initState() { + super.initState(); + _controller.select(12); + } + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final detail = RunDetailView(controller: _controller, onBack: () {}); + if (Theme.of(context).platform == TargetPlatform.iOS) { + return CupertinoPageScaffold( + navigationBar: const CupertinoNavigationBar(middle: Text('Runs')), + child: SafeArea(child: detail), + ); + } + return Scaffold( + appBar: AppBar(title: const Text('Runs')), + body: detail, + ); + } +} diff --git a/app/tool/diff_wiring_probe.mjs b/app/tool/diff_wiring_probe.mjs new file mode 100644 index 00000000..d7764d0b --- /dev/null +++ b/app/tool/diff_wiring_probe.mjs @@ -0,0 +1,498 @@ +// Real-browser evidence for the run-detail Changes action wiring. +// +// Usage (from app/): +// flutter build web --target tool/diff_wiring_probe.dart --output build/probe-wire +// node tool/diff_wiring_probe.mjs --root build/probe-wire --out DIR +// +// The fixture serves the actual RunDetailView over a fake gateway, then drives +// headless Chrome over loopback: the native Changes button, the recorded file, +// its diff, Close diff, Back, the failed-run evidence without a run-wide +// summary, the absent action while executing, and the Cupertino raw/dark +// surfaces. No server or operator run is touched. +import { createServer } from 'node:http'; +import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; +import { spawn } from 'node:child_process'; +import { once } from 'node:events'; +import { setTimeout as delay } from 'node:timers/promises'; +import { extname, join, resolve, sep } from 'node:path'; +import { tmpdir } from 'node:os'; + +const args = new Map(); +for (let i = 2; i < process.argv.length; i++) { + const value = process.argv[i]; + if (value.startsWith('--')) args.set(value.slice(2), process.argv[++i]); +} +const root = resolve(args.get('root') ?? 'build/probe-wire'); +const out = resolve(args.get('out') ?? 'build/diff-wiring-probe'); +const chromePath = + process.env.CHROME_PATH ?? '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'; +await mkdir(out, { recursive: true }); + +const mime = { + '.html': 'text/html; charset=utf-8', + '.js': 'text/javascript; charset=utf-8', + '.mjs': 'text/javascript; charset=utf-8', + '.json': 'application/json; charset=utf-8', + '.wasm': 'application/wasm', + '.png': 'image/png', + '.svg': 'image/svg+xml', + '.ico': 'image/x-icon', + '.ttf': 'font/ttf', + '.otf': 'font/otf', + '.woff': 'font/woff', + '.woff2': 'font/woff2', + '.bin': 'application/octet-stream', + '.frag': 'application/octet-stream', +}; + +const server = createServer(async (req, res) => { + try { + const pathname = decodeURIComponent(new URL(req.url, 'http://localhost').pathname); + let filePath = resolve(root, '.' + pathname); + if (filePath !== root && !filePath.startsWith(root + sep)) { + res.writeHead(403).end(); + return; + } + if (pathname === '/' || pathname.endsWith('/')) filePath = join(filePath, 'index.html'); + const file = await readFile(filePath); + res.writeHead(200, { 'content-type': mime[extname(filePath)] ?? 'application/octet-stream' }).end(file); + } catch { + res.writeHead(404).end('not found'); + } +}); +server.listen(0, '127.0.0.1'); +await once(server, 'listening'); +const origin = `http://127.0.0.1:${server.address().port}`; + +const profile = await mkdtemp(join(tmpdir(), 'd1-wire-chrome-')); +const chrome = spawn( + chromePath, + ['--headless=new', '--no-first-run', '--no-default-browser-check', '--disable-gpu', + '--remote-debugging-port=0', `--user-data-dir=${profile}`, 'about:blank'], + { stdio: ['ignore', 'ignore', 'pipe'] }, +); +let stderr = ''; +chrome.stderr.on('data', (data) => { + stderr += data; +}); + +const waitFor = async (fn, what) => { + for (let i = 0; i < 120; i++) { + const value = await fn(); + if (value) return value; + await delay(100); + } + throw new Error(`Timed out waiting for ${what}: ${stderr.slice(-1500)}`); +}; + +const file = 'lib/features/runs/ui/run_changes_action.dart'; +const rowPrefix = `Open diff for ${file}`; +const evidence = { origin, captures: [], checks: [] }; +let ws; +try { + const endpoint = await waitFor( + () => stderr.match(/DevTools listening on (ws:\/\/[^\s]+)/)?.[1], + 'Chrome DevTools', + ); + ws = new WebSocket(endpoint); + await once(ws, 'open'); + let id = 0; + const pending = new Map(); + ws.addEventListener('message', (event) => { + const message = JSON.parse(event.data); + if (message.id && pending.has(message.id)) { + pending.get(message.id)(message); + pending.delete(message.id); + } + }); + const send = (method, params = {}, sessionId) => + new Promise((resolveCall) => { + const callId = ++id; + pending.set(callId, resolveCall); + ws.send(JSON.stringify({ id: callId, method, params, ...(sessionId ? { sessionId } : {}) })); + }); + + const created = await send('Target.createTarget', { url: 'about:blank' }); + if (!created.result) throw new Error(`Target creation failed: ${JSON.stringify(created)}`); + const session = (await send('Target.attachToTarget', { + targetId: created.result.targetId, + flatten: true, + })).result.sessionId; + await send('Page.enable', {}, session); + await send('Runtime.enable', {}, session); + await send('Emulation.setDeviceMetricsOverride', { + width: 390, height: 844, deviceScaleFactor: 1, mobile: true, + }, session); + + const evaluate = async (expression) => { + const response = await send( + 'Runtime.evaluate', + { expression, returnByValue: true, awaitPromise: true }, + session, + ); + if (response.error) throw new Error(`Runtime.evaluate failed: ${JSON.stringify(response)}`); + return response.result?.result?.value; + }; + const labels = () => + evaluate( + "[...document.querySelectorAll('flt-semantics')].map(x => x.getAttribute('aria-label') || (x.innerText || '').trim()).filter(Boolean)", + ); + const bodyText = () => evaluate('document.body.innerText'); + const hasLabel = async (label) => (await labels()).includes(label); + const hasPrefix = async (prefix) => + (await labels()).some((label) => label.startsWith(prefix)); + const clickExact = async (label) => { + const clicked = await evaluate(`(() => { + const wanted = ${JSON.stringify(label)}; + const nodes = [...document.querySelectorAll('flt-semantics')]; + const node = nodes.find(x => x.getAttribute('aria-label') === wanted) + || nodes.find(x => (x.innerText || '').trim() === wanted); + if (!node) return false; + node.click(); + return true; + })()`); + if (!clicked) throw new Error(`No exact semantics label ${JSON.stringify(label)}: ${JSON.stringify(await labels())}`); + await delay(500); + }; + const clickPrefix = async (prefix) => { + const clicked = await evaluate(`(() => { + const wanted = ${JSON.stringify(prefix)}; + const nodes = [...document.querySelectorAll('flt-semantics')]; + const candidates = nodes.filter((x) => + (x.getAttribute('aria-label') || '').startsWith(wanted) + || (x.innerText || '').trim().startsWith(wanted)); + if (candidates.length === 0) return false; + // Click the actionable row, not an ancestor semantics container whose + // innerText happens to start with the same text. + const actionable = candidates.filter((x) => x.hasAttribute('flt-tappable')); + const target = (actionable.length > 0 ? actionable : candidates) + .sort((a, b) => (a.innerText || '').length - (b.innerText || '').length)[0]; + target.click(); + return true; + })()`); + if (!clicked) throw new Error(`No semantics label starting ${JSON.stringify(prefix)}: ${JSON.stringify(await labels())}`); + await delay(500); + }; + const activate = async () => { + await delay(3200); + await evaluate("document.querySelector('flt-semantics-placeholder')?.click()"); + await delay(900); + const current = await labels(); + if (!current.some((label) => label.includes('Changes wiring probe'))) { + throw new Error(`Flutter semantics unavailable: ${JSON.stringify(current)}`); + } + }; + const navigate = async (url) => { + const navigation = await send('Page.navigate', { url }, session); + if (navigation.error || navigation.result?.errorText) throw new Error(JSON.stringify(navigation)); + await activate(); + }; + const capture = async (name, width = 390, height = 844, scale = 1) => { + await send('Emulation.setDeviceMetricsOverride', { + width, height, deviceScaleFactor: scale, mobile: width < 600, + }, session); + await delay(350); + const data = (await send('Page.captureScreenshot', { format: 'png' }, session)).result.data; + const path = join(out, `${name}.png`); + await writeFile(path, Buffer.from(data, 'base64')); + evidence.captures.push(path); + }; + + // Semantics expose a widget's box in CSS pixels; the pixel probe then reads + // the rendered screen so a text colour can be asserted, not just presence. + const rectOfLabel = (prefix) => + evaluate(`(() => { + const wanted = ${JSON.stringify(prefix)}; + const text = (x) => x.getAttribute('aria-label') || (x.innerText || '').trim(); + const node = [...document.querySelectorAll('flt-semantics')] + .find(x => text(x).startsWith(wanted)); + if (!node) return null; + const r = node.getBoundingClientRect(); + return { x: r.x, y: r.y, width: r.width, height: r.height }; + })()`); + const brightestPixel = async (rect) => { + const shot = await send('Page.captureScreenshot', { + format: 'png', + clip: { ...rect, scale: 2 }, + }, session); + if (!shot.result?.data) throw new Error(`Screenshot clip failed: ${JSON.stringify(shot)}`); + return evaluate(`(async () => { + const img = new Image(); + img.src = 'data:image/png;base64,${shot.result.data}'; + await img.decode(); + const canvas = document.createElement('canvas'); + canvas.width = img.width; + canvas.height = img.height; + const ctx = canvas.getContext('2d'); + ctx.drawImage(img, 0, 0); + const data = ctx.getImageData(0, 0, img.width, img.height).data; + let max = 0; + let bright = 0; + for (let i = 0; i < data.length; i += 4) { + const lum = (0.2126 * data[i] + 0.7152 * data[i + 1] + 0.0722 * data[i + 2]) / 255; + if (lum > max) max = lum; + if (lum > 0.5) bright++; + } + return { max, bright, pixels: data.length / 4, width: img.width, height: img.height }; + })()`); + }; + + await navigate(`${origin}/`); + const detailBody = await bodyText(); + if (!detailBody.includes('Changes wiring probe')) { + throw new Error(`Run detail did not render: ${JSON.stringify(detailBody)}`); + } + if (!(await hasLabel('Changes'))) { + throw new Error(`Run detail has no Changes action: ${JSON.stringify(await labels())}`); + } + evidence.checks.push({ check: 'run detail shows the native Changes action', value: true }); + await capture('d1-wire-material-detail'); + + await clickExact('Changes'); + const changesBody = await bodyText(); + if (changesBody === detailBody) throw new Error('Changes did not open a new page'); + if (!changesBody.includes(file)) throw new Error(`Recorded filename missing: ${JSON.stringify(changesBody)}`); + if (!changesBody.includes('1 file changed · +2 -1')) { + throw new Error(`Recorded stat missing: ${JSON.stringify(changesBody)}`); + } + evidence.checks.push({ check: 'Changes opened the recorded filename and stat', value: true }); + await capture('d1-wire-material-changes'); + await delay(1200); + await clickPrefix(rowPrefix); + const diffBody = await bodyText(); + if (!diffBody.includes('const recorded = true;') + || !diffBody.includes('const label = "Old";')) { + throw new Error(`Recorded diff lines missing: ${JSON.stringify(diffBody)}`); + } + for (const label of ['Rendered', 'Raw patch', 'Copy patch', 'Close diff']) { + if (!(await hasLabel(label))) throw new Error(`Diff is missing ${label}: ${JSON.stringify(await labels())}`); + } + evidence.checks.push({ check: 'the recorded file opened its actual diff', value: true }); + await capture('d1-wire-material-diff'); + + await clickExact('Close diff'); + if (!(await bodyText()).includes(file)) throw new Error('Close diff did not return to Changes'); + await clickExact('Back'); + const backBody = await bodyText(); + if (!backBody.includes('Changes wiring probe') || !(await hasLabel('Changes'))) { + throw new Error(`Back did not return to the run detail: ${JSON.stringify(backBody)}`); + } + evidence.checks.push({ check: 'Close diff and Back returned to the previous pages', value: true }); + await capture('d1-wire-material-back'); + + await navigate(`${origin}/?capture=unavailable`); + await clickExact('Changes'); + const unavailableBody = await bodyText(); + if (!unavailableBody.includes('Changes · capture unavailable')) { + throw new Error(`Unavailable capture wording missing: ${JSON.stringify(unavailableBody)}`); + } + if (!unavailableBody.includes('Workspace snapshot unavailable; changes could not be compared.')) { + throw new Error('Unavailable diagnostic missing'); + } + if (unavailableBody.includes('No changes observed')) { + throw new Error('Unavailable capture claimed no changes'); + } + evidence.checks.push({ check: 'unavailable capture keeps its gap wording', value: true }); + await capture('d1-wire-material-unavailable'); + + await navigate(`${origin}/?run=failed`); + await clickExact('Changes'); + await capture('d1-wire-material-failed'); + const failedBody = await bodyText(); + const failedText = [failedBody, ...(await labels())].join('\n'); + if (!failedText.includes(file)) { + throw new Error(`Failed run lost its visit capture: ${JSON.stringify(failedText)}`); + } + if (failedText.includes('file changed')) { + throw new Error(`Failed run showed a settled run-wide summary: ${JSON.stringify(failedText)}`); + } + if (!failedText.includes('Visit 1')) { + throw new Error(`Failed run visit section missing: ${JSON.stringify(failedText)}`); + } + evidence.checks.push({ check: 'a failed run keeps visit evidence without a summary', value: true }); + + await navigate(`${origin}/?run=running`); + if (await hasLabel('Changes')) { + throw new Error('An executing run offered the snapshot Changes page'); + } + const runningBody = await bodyText(); + if (!runningBody.includes('running')) { + throw new Error(`Running run detail did not render its status: ${JSON.stringify(runningBody)}`); + } + evidence.checks.push({ check: 'an executing run offers no snapshot Changes page', value: true }); + await capture('d1-wire-material-running'); + + await navigate(`${origin}/?platform=cupertino&theme=light`); + if (!(await hasLabel('Changes'))) { + throw new Error(`Cupertino run detail has no Changes action: ${JSON.stringify(await labels())}`); + } + await capture('d1-wire-cupertino-detail'); + await clickExact('Changes'); + const cupertinoChanges = await bodyText(); + if (!cupertinoChanges.includes(file)) { + throw new Error(`Cupertino Changes did not open the recorded file: ${JSON.stringify(cupertinoChanges)}`); + } + evidence.checks.push({ check: 'Cupertino Changes opened the recorded file', value: true }); + await capture('d1-wire-cupertino-changes'); + + await clickPrefix(rowPrefix); + if (!(await bodyText()).includes('const recorded = true;')) { + throw new Error('Cupertino recorded diff missing'); + } + await capture('d1-wire-cupertino-diff'); + await clickExact('Raw patch'); + const rawLabels = await labels(); + const rawBody = await bodyText(); + if (!rawLabels.some((label) => label.includes('Raw patch for')) + && !rawBody.includes('const recorded = true;')) { + throw new Error(`Cupertino raw patch did not render: ${JSON.stringify(rawLabels)}`); + } + if (!(await hasLabel('Copy patch'))) { + throw new Error(`Cupertino raw view lost its actions: ${JSON.stringify(await labels())}`); + } + evidence.checks.push({ check: 'Cupertino Raw patch uses a native selectable body', value: true }); + await capture('d1-wire-cupertino-raw'); + await clickExact('Close diff'); + await delay(600); + await clickExact('Back'); + await delay(800); + if (!(await bodyText()).includes('Changes wiring probe')) { + throw new Error('Cupertino Back did not return to the run detail'); + } + evidence.checks.push({ check: 'Cupertino diff and Back returned', value: true }); + await capture('d1-wire-cupertino-back'); + + await navigate(`${origin}/?platform=cupertino&theme=dark`); + await clickExact('Changes'); + const darkText = [await bodyText(), ...(await labels())].join('\n'); + if (!darkText.includes(file) || !darkText.includes('file changed')) { + throw new Error(`Cupertino dark Changes did not render: ${JSON.stringify(darkText)}`); + } + evidence.checks.push({ check: 'Cupertino dark Changes renders the recorded summary', value: true }); + await capture('d1-wire-cupertino-dark-changes'); + await clickPrefix(rowPrefix); + if (!(await bodyText()).includes('const recorded = true;')) { + throw new Error('Cupertino dark recorded diff missing'); + } + // The header is a merged semantics label, so anchor the pixel crop on the + // controls below it: the form control and the title share the 16 px inset, + // and the close control shares the header's top line. + const formRect = await rectOfLabel('Rendered'); + const closeRect = await rectOfLabel('Close diff'); + if (!formRect || !closeRect) { + throw new Error(`Dark diff controls are missing: ${JSON.stringify(await labels())}`); + } + const titleLuminance = await brightestPixel({ + x: formRect.x, + y: closeRect.y, + width: 60, + height: 22, + }); + if (titleLuminance.max < 0.5) { + throw new Error(`Dark Cupertino diff header is not light: ${JSON.stringify(titleLuminance)}`); + } + evidence.checks.push({ + check: 'Cupertino dark diff header text is light on the popup surface', + value: true, + luminance: titleLuminance.max, + }); + evidence.checks.push({ check: 'Cupertino dark diff renders its recorded lines', value: true }); + await capture('d1-wire-cupertino-dark-diff'); + + // A 320-px host at 2x text is the narrowest documented state. The native + // controls must keep the whole browser words; the strip scrolls and reveals + // the selected segment instead of clipping or breaking a label. + const scroll = async ({ x, y, deltaX = 0, deltaY = 0 }) => { + await send('Input.dispatchMouseEvent', { + type: 'mouseWheel', x, y, deltaX, deltaY, + }, session); + await delay(400); + }; + const openScaledDiff = async ({ platform, prefix }) => { + await send('Emulation.setDeviceMetricsOverride', { + width: 320, height: 720, deviceScaleFactor: 1, mobile: true, + }, session); + const query = platform === 'cupertino' + ? '?platform=cupertino&theme=light&scale=2' + : '?theme=light&scale=2'; + await navigate(`${origin}/${query}`); + await clickExact('Changes'); + // The 2x summary pushes the recorded file below the fold: scroll the + // Changes list until its row is built and offered. + for (let i = 0; i < 8 && !(await hasPrefix(rowPrefix)); i++) { + await scroll({ x: 160, y: 600, deltaY: 400 }); + } + if (!(await hasPrefix(rowPrefix))) { + throw new Error(`2x Changes did not offer the recorded file: ${JSON.stringify(await labels())}`); + } + await clickPrefix(rowPrefix); + await delay(800); + const body = await bodyText(); + if (!body.includes('const recorded = true;')) { + throw new Error(`2x diff did not render: ${JSON.stringify(body)}`); + } + for (const label of ['Copy patch', 'Close diff', 'Diff form']) { + if (!(await hasLabel(label))) { + throw new Error(`2x diff is missing ${label}: ${JSON.stringify(await labels())}`); + } + } + await capture(`${prefix}-diff`, 320, 720, 1); + + // The native menu carries both fixed words on a host too narrow for the + // segmented control; the sheet/list must show each of them whole. A real + // pointer tap is used because the Cupertino label sits on a semantic + // wrapper above the actual button. + const menuRect = await rectOfLabel('Diff form'); + if (!menuRect) { + throw new Error(`2x diff has no Diff form control: ${JSON.stringify(await labels())}`); + } + const tap = { + x: menuRect.x + menuRect.width / 2, + y: menuRect.y + menuRect.height / 2, + }; + await send('Input.dispatchMouseEvent', { + type: 'mousePressed', ...tap, button: 'left', clickCount: 1, + }, session); + await send('Input.dispatchMouseEvent', { + type: 'mouseReleased', ...tap, button: 'left', clickCount: 1, + }, session); + await delay(900); + for (const label of ['Rendered', 'Raw patch']) { + if (!(await hasLabel(label))) { + throw new Error(`2x diff menu is missing ${label}: ${JSON.stringify(await labels())}`); + } + } + await capture(`${prefix}-menu`, 320, 720, 1); + + await clickExact('Raw patch'); + await delay(900); + const raw = await bodyText(); + const rawLabels = await labels(); + if (!rawLabels.some((label) => label.includes('Raw patch for')) + && !raw.includes('const recorded = true;')) { + throw new Error(`2x Raw patch did not render: ${JSON.stringify(rawLabels)}`); + } + await capture(`${prefix}-raw`, 320, 720, 1); + await clickExact('Close diff'); + await delay(600); + }; + + await openScaledDiff({ platform: 'material', prefix: 'd1-wire-material-2x-320' }); + evidence.checks.push({ + check: 'Material 2x/320 diff keeps its controls and opens Raw patch', + value: true, + }); + await openScaledDiff({ platform: 'cupertino', prefix: 'd1-wire-cupertino-2x-320' }); + evidence.checks.push({ + check: 'Cupertino 2x/320 diff keeps its controls and opens Raw patch', + value: true, + }); + + console.log(JSON.stringify(evidence, null, 2)); +} finally { + ws?.close(); + chrome.kill('SIGTERM'); + await Promise.race([once(chrome, 'exit'), delay(3000)]); + server.close(); + await rm(profile, { recursive: true, force: true }); +}