From c53dedc5441d86105322bff1106170b3458b52e4 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 22:49:26 +0100 Subject: [PATCH] feat(app): wire retry and restart into the native run detail Render Retry beside Rename on a stopped failed run under both native hosts, send only {run_id, request_key} for resume and add retry_mode=restart for a fresh start, and open the run the accepted reply names. Keep hidden actions out of the Wrap so native 8/4 dp spacing is not doubled, and use a literal 2^32 entropy bound because dart2js evaluates 1 << 32 as 0. Adds wiring, guard and layout tests, a browser-only key regression and the retry probe; notes/R2c-wire.md records the checks and limits. --- .../features/runs/actions/retry_action.dart | 14 +- .../features/runs/actions/retry_intent.dart | 8 +- app/lib/features/runs/screen.dart | 1 + .../features/runs/ui/run_detail_actions.dart | 42 +- app/lib/features/runs/ui/run_detail_view.dart | 6 + app/notes/R2c-wire.md | 158 ++++ .../runs/actions/retry_action_test.dart | 16 + .../runs/actions/retry_intent_web_test.dart | 25 + .../runs/ui/run_retry_guard_test.dart | 114 +++ .../runs/ui/run_retry_layout_test.dart | 151 ++++ .../runs/ui/run_retry_wiring_support.dart | 113 +++ .../runs/ui/run_retry_wiring_test.dart | 102 +++ app/tool/retry_wiring_probe.dart | 22 + app/tool/retry_wiring_probe.mjs | 772 ++++++++++++++++++ 14 files changed, 1532 insertions(+), 12 deletions(-) create mode 100644 app/notes/R2c-wire.md create mode 100644 app/test/features/runs/actions/retry_intent_web_test.dart create mode 100644 app/test/features/runs/ui/run_retry_guard_test.dart create mode 100644 app/test/features/runs/ui/run_retry_layout_test.dart create mode 100644 app/test/features/runs/ui/run_retry_wiring_support.dart create mode 100644 app/test/features/runs/ui/run_retry_wiring_test.dart create mode 100644 app/tool/retry_wiring_probe.dart create mode 100644 app/tool/retry_wiring_probe.mjs diff --git a/app/lib/features/runs/actions/retry_action.dart b/app/lib/features/runs/actions/retry_action.dart index 28cda388..b7f593a2 100644 --- a/app/lib/features/runs/actions/retry_action.dart +++ b/app/lib/features/runs/actions/retry_action.dart @@ -22,12 +22,20 @@ class RetryRunAction extends StatefulWidget { required this.run, required this.gateway, required this.onRunChanged, + this.onRunOpened, }); final JsonMap run; final ApiGateway gateway; final ValueChanged onRunChanged; + /// Receives the id the accepted server reply names for the new retry run. + /// + /// The reply is first delivered through [onRunChanged] like every other + /// accepted detail. This callback then opens that run; it is never called + /// with a guessed id, and a reply without a usable id changes no selection. + final ValueChanged? onRunOpened; + @override State createState() => _RetryRunActionState(); } @@ -70,7 +78,11 @@ class _RetryRunActionState extends State { mode: intent.mode.wireMode, ); if (!mounted) return null; - if (_owns(id)) widget.onRunChanged(run); + if (_owns(id)) { + widget.onRunChanged(run); + final opened = retryRunId(run); + if (opened != null && opened != id) widget.onRunOpened?.call(opened); + } return null; } catch (error) { return ActionRefusal( diff --git a/app/lib/features/runs/actions/retry_intent.dart b/app/lib/features/runs/actions/retry_intent.dart index 17140a70..4b97bb0e 100644 --- a/app/lib/features/runs/actions/retry_intent.dart +++ b/app/lib/features/runs/actions/retry_intent.dart @@ -20,10 +20,16 @@ class RetryIntent { final String requestKey; } +/// The entropy bound for a fresh key. +/// +/// Written as a literal: on the web a bitwise `1 << 32` wraps to 0, which makes +/// `Random.nextInt` reject every retry with a `RangeError`. +const _entropyBound = 0x100000000; + /// A fresh `request_key` for one retry intent. The server requires one and caps /// it at 128 characters; this stays well inside that bound and unique per call. String newRetryRequestKey(num runId, {DateTime? now, int? random}) { final stamp = (now ?? DateTime.now()).microsecondsSinceEpoch; - final entropy = random ?? Random().nextInt(1 << 32); + final entropy = random ?? Random().nextInt(_entropyBound); return 'app-retry-$runId-$stamp-${entropy.toRadixString(36)}'; } diff --git a/app/lib/features/runs/screen.dart b/app/lib/features/runs/screen.dart index fbc4e66d..42126b44 100644 --- a/app/lib/features/runs/screen.dart +++ b/app/lib/features/runs/screen.dart @@ -111,6 +111,7 @@ class _RunsScreenState extends State { controller: controller, gateway: widget.gateway, onBack: _back, + onRunOpened: _select, ), ], ); diff --git a/app/lib/features/runs/ui/run_detail_actions.dart b/app/lib/features/runs/ui/run_detail_actions.dart index 699f734c..0d4b211f 100644 --- a/app/lib/features/runs/ui/run_detail_actions.dart +++ b/app/lib/features/runs/ui/run_detail_actions.dart @@ -1,7 +1,10 @@ import 'package:flutter/widgets.dart'; import '../../../core/api_gateway.dart'; +import '../actions/cancel_eligibility.dart'; import '../actions/cancel_run_action.dart'; +import '../actions/retry_action.dart'; +import '../actions/retry_eligibility.dart'; import '../actions/title_action.dart'; import 'run_decision_notice.dart'; @@ -13,29 +16,48 @@ class RunDetailActions extends StatelessWidget { required this.run, required this.gateway, required this.onRunChanged, + this.onRunOpened, }); final JsonMap run; final ApiGateway gateway; final ValueChanged onRunChanged; + /// Opens the new run named by an accepted retry reply; see [RetryRunAction]. + final ValueChanged? onRunOpened; + @override Widget build(BuildContext context) => Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ + // Standard native spacing keeps adjacent outlines and fills distinct. + // Only actions that render are included: a hidden zero-size child still + // consumes Wrap spacing and would double the visible gap. Wrap( + spacing: 8, + runSpacing: 4, + crossAxisAlignment: WrapCrossAlignment.center, children: [ - RunTitleAction( - run: run, - gateway: gateway, - onRunChanged: onRunChanged, - ), - CancelRunAction( - run: run, - gateway: gateway, - onRunChanged: onRunChanged, - ), + if (runTitleId(run) != null) + RunTitleAction( + run: run, + gateway: gateway, + onRunChanged: onRunChanged, + ), + if (retryRunId(run) != null && canRetryRun(run)) + RetryRunAction( + run: run, + gateway: gateway, + onRunChanged: onRunChanged, + onRunOpened: onRunOpened, + ), + if (cancelRunId(run) != null && canCancelRun(run)) + CancelRunAction( + run: run, + gateway: gateway, + onRunChanged: onRunChanged, + ), ], ), RunDecisionNotice(run: run, gateway: gateway, onRunChanged: onRunChanged), diff --git a/app/lib/features/runs/ui/run_detail_view.dart b/app/lib/features/runs/ui/run_detail_view.dart index f6982913..3e510b62 100644 --- a/app/lib/features/runs/ui/run_detail_view.dart +++ b/app/lib/features/runs/ui/run_detail_view.dart @@ -16,6 +16,7 @@ class RunDetailView extends StatefulWidget { required this.controller, required this.gateway, required this.onBack, + this.onRunOpened, }); final RunsController controller; @@ -24,6 +25,10 @@ class RunDetailView extends StatefulWidget { final ApiGateway gateway; final VoidCallback onBack; + /// Opens the run named by an accepted retry reply, so the host route follows + /// the server-identified new run. Null keeps the detail on the retried run. + final ValueChanged? onRunOpened; + @override State createState() => _RunDetailViewState(); } @@ -44,6 +49,7 @@ class _RunDetailViewState extends State { run: run, gateway: widget.gateway, onRunChanged: widget.controller.acceptRunDetail, + onRunOpened: widget.onRunOpened, ); return cupertino ? buildCupertinoRunDetail( diff --git a/app/notes/R2c-wire.md b/app/notes/R2c-wire.md new file mode 100644 index 00000000..060ebd1c --- /dev/null +++ b/app/notes/R2c-wire.md @@ -0,0 +1,158 @@ +# R2c-wire — Retry/restart in the real run detail + +## Result + +The already-landed `RetryRunAction` now renders in the real run detail action +row under both native hosts, beside Rename and Cancel/decision wiring. Only a +loaded, stopped `failed` run offers it. Resume sends exactly `run_id` and +`request_key`; restart additionally sends `retry_mode: "restart"`. `Keep` sends +nothing. The accepted reply is delivered through +`RunsController.acceptRunDetail` like cancel/title, and the new run is opened +only when the reply itself carries a numeric, different run id. A reply without +an id, a reply naming the source run, a late reply, or a reply after leaving +never guesses a run or moves the route. + +The action row now uses the detail's native 8 dp / 4 dp `Wrap` spacing. It +previously used the default zero spacing, so the outlined Rename border met the +filled Retry button at 320 px (browser-measured gap 0.008 CSS px). Only actions +that render are included in the `Wrap`: a hidden action still consumed spacing +and would have doubled the visible gap. + +The browser probe found one real web-only defect in the landed key generator: +dart2js evaluates `1 << 32` as `0`, so `Random.nextInt` raised every retry +before the request left the app. The bound is now a literal `0x100000000`; a +browser-compiled test and the web probe both exercise the real generator. + +## Files + +| File | Change | +| --- | --- | +| `lib/features/runs/ui/run_detail_actions.dart` | Renders `RetryRunAction` in the action row, forwards the reply-id callback, uses 8/4 dp spacing, includes only eligible actions | +| `lib/features/runs/ui/run_detail_view.dart` | Passes an optional server-identified run opener through to the actions | +| `lib/features/runs/screen.dart` | Opens the reply-named run through the existing `_select` path (controller selection + route) | +| `lib/features/runs/actions/retry_action.dart` | After the accepted detail callback, opens only a different numeric reply id | +| `lib/features/runs/actions/retry_intent.dart` | Web-safe 2^32 entropy literal instead of `1 << 32` | +| `test/features/runs/ui/run_retry_wiring_support.dart` | New: fixture gateway and both-host detail mount | +| `test/features/runs/ui/run_retry_wiring_test.dart` | New: real screen wiring, exact resume/restart payloads, server-named navigation | +| `test/features/runs/ui/run_retry_guard_test.dart` | New: no-id/same-id/refusal/late reply and eligibility gates | +| `test/features/runs/ui/run_retry_layout_test.dart` | New: action-row spacing at 320 px and 2x, no doubled gap from a hidden action | +| `test/features/runs/actions/retry_action_test.dart` | Full-width entropy regression for the request key | +| `test/features/runs/actions/retry_intent_web_test.dart` | New browser-only (`@TestOn('browser')`) regression for the dart2js entropy defect | +| `tool/retry_wiring_probe.dart`, `tool/retry_wiring_probe.mjs` | Normal-app browser probe; `CHROME_PATH`/`TESSERACT`/`PROBE_THEME` envs; measures the 8 dp action gap | + +No dialog, repository protocol, server, web, shell, main, pubspec, Android or +iOS file changed. No new server command or API. + +## Behaviour + +- Action order in the detail `Wrap` is Rename, Retry, Cancel; Retry renders + nothing unless `canRetryRun(run)` holds (`!executing && status == "failed"`). + Both Material (`FilledButton`) and Cupertino (`CupertinoButton.filled`) use + their native controls and host typography. The row uses `spacing: 8` and + `runSpacing: 4`, matching the detail's other action rows. +- Opening the prompt and choosing `Keep` send nothing. Resume sends exactly + `{run_id, request_key}`; restart sends + `{run_id, request_key, retry_mode: "restart"}`. The key is + `app-retry--…`, bounded at 128 characters, fresh per deliberate + intent, and retained across an uncertain resend by the landed dialog. +- The accepted `run_detail` goes through `onRunChanged`, i.e. + `controller.acceptRunDetail`: it folds an existing list row and replaces the + open detail only when its id still matches. A refusal stays in the prompt + with the server words and a bounded `get_run` recheck, as landed. +- The new run is opened only when `retryRunId(reply)` is numeric and differs + from the source id. `RunsScreen._select` then uses the existing controller + `select` generation guard and reports the route change, so the URL becomes + `/runs/`. No id or same id, no navigation; a later reply after + leaving is ignored by the action's ownership check and never reaches the + controller. The accepted reply for the source run is still folded normally. +- The reply is not used to invent a title, status or id. The opened detail is + the server's `get_run` for the id the retry reply named. + +## Checks actually run + +``` +dart format lib/features/runs test/features/runs tool/retry_wiring_probe.dart + # Formatted 61 files (0 changed) +flutter analyze # No issues found! +flutter test test/features/runs/ui/run_retry_guard_test.dart \ + test/features/runs/ui/run_retry_layout_test.dart \ + test/features/runs/ui/run_retry_wiring_test.dart # 13 passed +flutter test test/features/runs test/application/runs_destination_test.dart + # 134 passed +flutter test # 708 passed +flutter test --platform chrome \ + test/features/runs/actions/retry_intent_web_test.dart + # 1 passed (dart2js) +flutter build web # Built build/web +flutter build web --target=tool/retry_wiring_probe.dart -o build/retry_probe_web_code + # Built +OPENCODE_ARTIFACT_DIR=.../public/r2c-retry-wire-code-fix \ + node tool/retry_wiring_probe.mjs build/retry_probe_web_code + # ok: true, 9 checks, 10 captures +OPENCODE_ARTIFACT_DIR=.../public/r2c-retry-wire-code-fix PROBE_THEME=light \ + node tool/retry_wiring_probe.mjs build/retry_probe_web_code + # ok: true, 9 checks, 10 captures +``` + +Regression guards were mutation-checked: with `spacing: 0` the 320 px spacing +test fails, and with `Random().nextInt(1 << 32)` the browser test fails with the +dart2js `RangeError`; both were restored. + +Real-browser probe (normal app composition, isolated loopback websocket, +320×480 CSS at DPR 2, both themes and hosts): + +- The action row measures **8.016 CSS px** (Cupertino) and **8.008 CSS px** + (Material) between Rename and Retry in both themes, versus 0.008–0.016 px + before the fix. Failed and running rows are visually separated in dark and + light. +- Cupertino: failed run shows Rename and Retry; `Keep` recorded zero retry + requests; restart sent + `{run_id: 7, request_key: "app-retry-7-…", retry_mode: "restart"}` and opened + only `/runs/8`, the reply's run. Resume from the still-failed source sent + only `{run_id: 7, request_key: "app-retry-7-…"}`, omitted `retry_mode`, and + opened only `/runs/9`. +- Material: the same failed run and action row; `Keep` sent nothing; resume + sent the same two-field payload and opened only `/runs/10`. +- All retry request keys started with `app-retry-7-`, fit 128 characters, and + no navigation occurred before a reply. Back listed the source and retried + runs. +- Twenty PNGs in + `/Users/alan/.local/share/pipelines/data/artifacts/80/public/r2c-retry-wire-code-fix/` + cover both themes and both hosts (failed, prompt, kept, restart prompt, + restart run, list, resume run; seven Cupertino and three Material each). + OCR asserted the source/new-run titles; the + failed captures were inspected for the restored native gap and readable + 320 px layout. + +Before the key fix, the same probe failed with +`ZONE ERROR: RangeError: max must be in range 0 < max ≤ 2^32, was 0` and +recorded zero retry requests. + +## Honest limits + +- **Mobile unverified.** No Android/iOS build, emulator, ADB or device was used; + sources stay portable Material/Cupertino. +- No production server, operator run or real retry was touched. The probe used + an isolated fixture with no credentials or shared data. +- Browser text scaling cannot be driven from CDP; 2x text at 320 px is covered + by the widget tests, while the browser probe covers 320 CSS px at DPR 2 in + dark and light. +- The browser entropy test is not part of the default `flutter test` VM run; it + needs `flutter test --platform chrome` and a Chrome install. No CI wiring + exists in this repository to add it to. +- The app opens the reply-named new run, while `web/src/views/dialogs.js` + silently re-selects the source run. The reply is genuinely the new run, so + this remains an intended improvement rather than pure parity; the product + decision is unchanged in this turn. +- The accepted reply's own detail is discarded when navigating and one + `get_run` follows, briefly showing the loading placeholder. Correct, one + extra round trip; not changed in this focused fix. +- `tool/retry_wiring_probe.mjs` remains long and requires Chrome; it now + honours `CHROME_PATH`, `TESSERACT` and `PROBE_THEME`, but is not otherwise + split. +- The post-Keep Cupertino capture is identical to the failed state; the + "sent nothing" claim rests on the probe's zero-request fixture state. +- A pre-existing Cupertino detail-header defect was observed at 320 px/2x: the + landed Changes button's internal `Row` overflows by 14 px. It reproduces with + Retry absent and belongs to the Changes lane, so it was not edited here. +- Nothing was committed, pushed, merged to main or deployed. diff --git a/app/test/features/runs/actions/retry_action_test.dart b/app/test/features/runs/actions/retry_action_test.dart index ca11fa8b..c8a2eed6 100644 --- a/app/test/features/runs/actions/retry_action_test.dart +++ b/app/test/features/runs/actions/retry_action_test.dart @@ -40,6 +40,22 @@ void main() { ); }); + test('the full entropy width still forms a bounded request key', () { + // The web build once rejected every retry because `1 << 32` is 0 there; + // the generator now uses a literal 2^32 bound. This pins the largest + // entropy value it may consume. + final key = newRetryRequestKey( + 7, + now: DateTime.utc(2026, 1, 1), + random: 0xFFFFFFFF, + ); + expect( + key, + 'app-retry-7-${DateTime.utc(2026, 1, 1).microsecondsSinceEpoch}-1z141z3', + ); + expect(key.length, lessThanOrEqualTo(128)); + }); + testWidgets( 'material retry asks first, Keep sends nothing, then omits retry_mode', (tester) async { diff --git a/app/test/features/runs/actions/retry_intent_web_test.dart b/app/test/features/runs/actions/retry_intent_web_test.dart new file mode 100644 index 00000000..e0e64c34 --- /dev/null +++ b/app/test/features/runs/actions/retry_intent_web_test.dart @@ -0,0 +1,25 @@ +@TestOn('browser') +library; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/runs/actions/retry_intent.dart'; + +void main() { + test('a fresh key uses the full entropy bound under dart2js', () { + // `1 << 32` compiles to 0 on the web, so Random.nextInt threw a RangeError + // and no retry request was ever sent. Generating without an injected + // random value exercises the real bound; a VM test cannot catch this + // class of bug, so this file runs only in a browser: + // + // flutter test --platform chrome \ + // test/features/runs/actions/retry_intent_web_test.dart + final keys = {}; + for (var index = 0; index < 32; index++) { + final key = newRetryRequestKey(7); + expect(key, startsWith('app-retry-7-')); + expect(key.length, lessThanOrEqualTo(128)); + keys.add(key); + } + expect(keys, hasLength(32)); + }); +} diff --git a/app/test/features/runs/ui/run_retry_guard_test.dart b/app/test/features/runs/ui/run_retry_guard_test.dart new file mode 100644 index 00000000..c0c0cc33 --- /dev/null +++ b/app/test/features/runs/ui/run_retry_guard_test.dart @@ -0,0 +1,114 @@ +import 'package:flutter/widgets.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/transport/connection_state.dart'; +import 'package:pipelines_app/features/runs/actions/retry_wording.dart'; +import 'package:pipelines_app/features/runs/actions/title_wording.dart'; + +import 'run_retry_wiring_support.dart'; + +void main() { + testWidgets('a reply without an id never opens a guessed run', ( + tester, + ) async { + final gateway = RetryWiringGateway(); + addTearDown(gateway.framesController.close); + final opened = []; + await mountRetryScreen( + tester, + gateway, + cupertino: false, + onRunSelected: opened.add, + ); + + await confirmRetry(tester); + gateway.retries.last.complete({ + 'run_detail': {'title': 'Unknown run', 'status': 'running'}, + }); + await tester.pumpAndSettle(); + + expect(opened, isEmpty); + expect(find.text(retryFailedTitle), findsOneWidget); + expect(find.text('Unknown run'), findsNothing); + expect(gateway.calls.where((call) => call.type == 'get_run'), hasLength(1)); + }); + + testWidgets('a refused retry stays on the failed run', (tester) async { + final gateway = RetryWiringGateway(); + addTearDown(gateway.framesController.close); + final opened = []; + await mountRetryScreen( + tester, + gateway, + cupertino: false, + onRunSelected: opened.add, + ); + + await confirmRetry(tester); + gateway.refuseRetry(const ProtocolError('the run is still executing')); + await tester.pumpAndSettle(); + + expect(find.text('the run is still executing'), findsOneWidget); + expect(opened, isEmpty); + expect(find.text(retryFailedTitle), findsOneWidget); + await tester.tap(find.byKey(retryKeepKey)); + await tester.pumpAndSettle(); + expect(find.byKey(retryActionKey), findsOneWidget); + }); + + testWidgets('a retry reply that lands after leaving is ignored', ( + tester, + ) async { + final gateway = RetryWiringGateway(); + addTearDown(gateway.framesController.close); + final opened = []; + await mountRetryScreen( + tester, + gateway, + cupertino: false, + onRunSelected: opened.add, + ); + + await confirmRetry(tester); + expect(gateway.retryCalls, hasLength(1)); + await tester.pumpWidget(const SizedBox.shrink()); + gateway.acceptRetry(retryCreatedDetail()); + await tester.pump(); + + expect(tester.takeException(), isNull); + expect(opened, isEmpty); + expect(gateway.calls.where((call) => call.type == 'get_run'), hasLength(1)); + }); + + testWidgets('a reply naming the source run opens nothing', (tester) async { + final gateway = RetryWiringGateway(); + addTearDown(gateway.framesController.close); + final opened = []; + await mountRetryScreen( + tester, + gateway, + cupertino: false, + onRunSelected: opened.add, + ); + + await confirmRetry(tester); + gateway.acceptRetry(retryCreatedDetail(id: 7)); + await tester.pumpAndSettle(); + + // The accepted detail still folds, but its id is the source run, so there + // is no new run to open and no second read. + expect(opened, isEmpty); + expect(find.text(retryCreatedTitle), findsOneWidget); + expect(gateway.calls.where((call) => call.type == 'get_run'), hasLength(1)); + }); + + testWidgets('a failed run that is still executing exposes no retry', ( + tester, + ) async { + final gateway = RetryWiringGateway(executing: true); + addTearDown(gateway.framesController.close); + await mountRetryScreen(tester, gateway, cupertino: false); + + expect(find.byKey(runTitleActionKey), findsOneWidget); + expect(find.byKey(retryActionKey), findsNothing); + }); +} diff --git a/app/test/features/runs/ui/run_retry_layout_test.dart b/app/test/features/runs/ui/run_retry_layout_test.dart new file mode 100644 index 00000000..d4ee08a2 --- /dev/null +++ b/app/test/features/runs/ui/run_retry_layout_test.dart @@ -0,0 +1,151 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/runs/actions/cancel_wording.dart'; +import 'package:pipelines_app/features/runs/actions/retry_wording.dart'; +import 'package:pipelines_app/features/runs/actions/title_wording.dart'; +import 'package:pipelines_app/features/runs/ui/run_detail_actions.dart'; + +import 'run_retry_wiring_support.dart'; + +void main() { + testWidgets('a hidden retry adds no extra gap for Rename and Cancel', ( + tester, + ) async { + final gateway = RetryWiringGateway(); + addTearDown(gateway.framesController.close); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Padding( + padding: const EdgeInsets.all(16), + child: RunDetailActions( + run: retryCreatedDetail(id: 7), + gateway: gateway, + onRunChanged: (_) {}, + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + + // Retry is not eligible on the running run and must not consume spacing. + expect(find.byKey(retryActionKey), findsNothing); + final rename = tester.getRect(find.byKey(runTitleActionKey)); + final cancel = tester.getRect(find.byKey(cancelActionKey)); + expect(cancel.left - rename.right, closeTo(8, 0.5)); + }); + + for (final cupertino in [false, true]) { + testWidgets('adjacent actions keep native spacing at 320 px ($cupertino)', ( + tester, + ) async { + tester.view.physicalSize = const Size(320, 480); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + + final gateway = RetryWiringGateway(); + addTearDown(gateway.framesController.close); + final row = Padding( + padding: const EdgeInsets.all(16), + child: RunDetailActions( + run: retryFailedDetail(), + gateway: gateway, + onRunChanged: (_) {}, + ), + ); + await tester.pumpWidget( + cupertino + ? CupertinoApp( + home: CupertinoPageScaffold(child: SafeArea(child: row)), + ) + : MaterialApp(home: Scaffold(body: row)), + ); + await tester.pumpAndSettle(); + + expectNativeActionSpacing(tester); + }); + } + + for (final cupertino in [false, true]) { + testWidgets('320 px at 2x keeps Rename and Retry reachable ($cupertino)', ( + tester, + ) async { + tester.view.physicalSize = const Size(320, 480); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + + final gateway = RetryWiringGateway(); + addTearDown(gateway.framesController.close); + Widget scale(BuildContext context, Widget? app) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: const TextScaler.linear(2)), + child: app!, + ); + // The action row itself, in the detail's 16 px inset, so the narrow + // accessibility state is measured without unrelated header controls. + final row = Padding( + padding: const EdgeInsets.all(16), + child: RunDetailActions( + run: retryFailedDetail(), + gateway: gateway, + onRunChanged: (_) {}, + ), + ); + await tester.pumpWidget( + cupertino + ? CupertinoApp( + builder: scale, + home: CupertinoPageScaffold(child: SafeArea(child: row)), + ) + : MaterialApp( + builder: scale, + home: Scaffold(body: row), + ), + ); + await tester.pumpAndSettle(); + + expect(find.byKey(runTitleActionKey).hitTestable(), findsOneWidget); + expect(find.byKey(retryActionKey).hitTestable(), findsOneWidget); + final rect = tester.getRect(find.byKey(retryActionKey)); + expect(rect.left, greaterThanOrEqualTo(0)); + expect(rect.right, lessThanOrEqualTo(320)); + expectNativeActionSpacing(tester); + + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + expect(find.text(retryDialogTitle(7)), findsOneWidget); + await tester.tap(find.byKey(retryKeepKey)); + await tester.pumpAndSettle(); + expect(gateway.retryCalls, isEmpty); + }); + } +} + +/// Asserts the action row uses the detail's native 8 dp / 4 dp spacing. +/// +/// The row previously had no `spacing`, leaving the outlined Rename border +/// touching the filled Retry button; browser measurement at 320 px reported a +/// 0.008 px gap. A hidden action must not consume spacing either. +void expectNativeActionSpacing(WidgetTester tester) { + final rename = tester.getRect(find.byKey(runTitleActionKey)); + final retry = tester.getRect(find.byKey(retryActionKey)); + final sameRow = retry.top < rename.bottom && rename.top < retry.bottom; + if (sameRow) { + expect( + retry.left - rename.right, + greaterThanOrEqualTo(8 - 0.01), + reason: 'side-by-side actions need the 8 dp Wrap spacing', + ); + } else { + expect( + retry.top - rename.bottom, + greaterThanOrEqualTo(4 - 0.01), + reason: 'wrapped actions need the 4 dp Wrap run spacing', + ); + } +} diff --git a/app/test/features/runs/ui/run_retry_wiring_support.dart b/app/test/features/runs/ui/run_retry_wiring_support.dart new file mode 100644 index 00000000..d590e617 --- /dev/null +++ b/app/test/features/runs/ui/run_retry_wiring_support.dart @@ -0,0 +1,113 @@ +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/retry_wording.dart'; +import 'package:pipelines_app/features/runs/screen.dart'; + +const retryFailedTitle = 'Fixture failed run'; +const retryCreatedTitle = 'Retry of fixture'; + +JsonMap retryFailedDetail({bool executing = false}) => { + 'id': 7, + 'title': retryFailedTitle, + 'name': 'fixture', + 'status': 'failed', + 'executing': executing, + 'input': {'prompt': 'the stored prompt'}, + 'steps': const [], +}; + +JsonMap retryCreatedDetail({num id = 8}) => { + 'id': id, + 'title': retryCreatedTitle, + 'name': 'fixture', + 'status': 'running', + 'executing': true, + 'retry_of': 7, + 'input': {'prompt': 'the stored prompt'}, + 'steps': const [], +}; + +JsonMap _summary(JsonMap run) => { + 'id': run['id'], + 'title': run['title'], + 'name': run['name'], + 'status': run['status'], + 'executing': run['executing'] ?? false, +}; + +/// Serves the same envelopes as the app server and holds each retry reply until +/// the test releases it, so nothing can be applied optimistically. +class RetryWiringGateway implements ApiGateway { + RetryWiringGateway({bool executing = false}) { + details[7] = retryFailedDetail(executing: executing); + } + + final framesController = StreamController.broadcast(); + final calls = <({String type, JsonMap fields})>[]; + final retries = >[]; + final details = {}; + + @override + Stream get frames => framesController.stream; + + @override + Future call(String type, [JsonMap fields = const {}]) { + calls.add((type: type, fields: Map.from(fields))); + switch (type) { + case 'list_runs': + return Future.value({ + 'runs': [for (final run in details.values) _summary(run)], + }); + case 'get_run': + final id = fields['run_id'] as num; + return Future.value({'run_detail': details[id] ?? retryFailedDetail()}); + case 'retry_run': + final reply = Completer(); + retries.add(reply); + return reply.future; + } + return Future.error(UnsupportedError(type)); + } + + Iterable<({String type, JsonMap fields})> get retryCalls => + calls.where((call) => call.type == 'retry_run'); + + void acceptRetry(JsonMap detail) { + details[detail['id'] as num] = detail; + retries.last.complete({'run_detail': detail}); + } + + void refuseRetry(Object error) => retries.last.completeError(error); +} + +Future mountRetryScreen( + WidgetTester tester, + RetryWiringGateway gateway, { + required bool cupertino, + ValueChanged? onRunSelected, +}) async { + final screen = RunsScreen( + gateway: gateway, + initialRunId: 7, + onRunSelected: onRunSelected, + ); + await tester.pumpWidget( + cupertino + ? CupertinoApp( + home: CupertinoPageScaffold(child: SafeArea(child: screen)), + ) + : MaterialApp(home: Scaffold(body: screen)), + ); + await tester.pumpAndSettle(); +} + +Future confirmRetry(WidgetTester tester) async { + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryConfirmKey)); + await tester.pump(); +} diff --git a/app/test/features/runs/ui/run_retry_wiring_test.dart b/app/test/features/runs/ui/run_retry_wiring_test.dart new file mode 100644 index 00000000..7a45fd1c --- /dev/null +++ b/app/test/features/runs/ui/run_retry_wiring_test.dart @@ -0,0 +1,102 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/runs/actions/cancel_wording.dart'; +import 'package:pipelines_app/features/runs/actions/retry_wording.dart'; +import 'package:pipelines_app/features/runs/actions/title_wording.dart'; + +import 'run_retry_wiring_support.dart'; + +void main() { + for (final cupertino in [false, true]) { + testWidgets( + 'accepted retry reply opens the server-identified run ($cupertino)', + (tester) async { + final gateway = RetryWiringGateway(); + addTearDown(gateway.framesController.close); + final opened = []; + await mountRetryScreen( + tester, + gateway, + cupertino: cupertino, + onRunSelected: opened.add, + ); + + expect(find.text(retryFailedTitle), findsOneWidget); + expect(find.byKey(runTitleActionKey), findsOneWidget); + expect(find.byKey(retryActionKey), findsOneWidget); + expect(find.byKey(cancelActionKey), findsNothing); + expect(gateway.retryCalls, isEmpty); + + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + expect(find.text(retryDialogTitle(7)), findsOneWidget); + expect(find.text(retryDialogMessage), findsOneWidget); + expect(gateway.retryCalls, isEmpty); + + await tester.tap(find.byKey(retryKeepKey)); + await tester.pumpAndSettle(); + expect(gateway.retryCalls, isEmpty); + expect(opened, isEmpty); + expect(find.byKey(retryActionKey), findsOneWidget); + + await confirmRetry(tester); + expect(gateway.retryCalls, hasLength(1)); + final fields = gateway.retryCalls.single.fields; + expect(fields.keys.toSet(), {'run_id', 'request_key'}); + expect(fields['run_id'], 7); + expect(fields['request_key'], startsWith('app-retry-7-')); + expect( + (fields['request_key'] as String).length, + lessThanOrEqualTo(128), + ); + // The prompt closes only from server truth; no navigation is guessed. + expect(opened, isEmpty); + expect(find.text(retryFailedTitle), findsOneWidget); + + gateway.acceptRetry(retryCreatedDetail()); + await tester.pumpAndSettle(); + + expect(opened, [8]); + expect(find.text(retryCreatedTitle), findsOneWidget); + expect(find.text(retryFailedTitle), findsNothing); + expect(find.byKey(retryActionKey), findsNothing); + expect( + gateway.calls.where((call) => call.type == 'get_run').last.fields, + {'run_id': 8}, + ); + }, + ); + } + + testWidgets('restart sends its explicit mode through the real detail row', ( + tester, + ) async { + final gateway = RetryWiringGateway(); + addTearDown(gateway.framesController.close); + final opened = []; + await mountRetryScreen( + tester, + gateway, + cupertino: false, + onRunSelected: opened.add, + ); + + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryRestartKey)); + await tester.pumpAndSettle(); + expect(find.text(restartDialogTitle(7)), findsOneWidget); + await tester.tap(find.byKey(retryConfirmKey)); + await tester.pump(); + + final fields = gateway.retryCalls.single.fields; + expect(fields.keys.toSet(), {'run_id', 'request_key', 'retry_mode'}); + expect(fields['run_id'], 7); + expect(fields['retry_mode'], 'restart'); + expect(fields['request_key'], startsWith('app-retry-7-')); + + gateway.acceptRetry(retryCreatedDetail()); + await tester.pumpAndSettle(); + expect(opened, [8]); + expect(find.text(retryCreatedTitle), findsOneWidget); + }); +} diff --git a/app/tool/retry_wiring_probe.dart b/app/tool/retry_wiring_probe.dart new file mode 100644 index 00000000..8ec171c2 --- /dev/null +++ b/app/tool/retry_wiring_probe.dart @@ -0,0 +1,22 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; +import 'package:pipelines_app/application/bootstrap.dart'; + +/// Browser acceptance entrypoint for the run-retry wiring probe. +/// +/// This is the normal app composition; the deterministic failed run, retry +/// replies and new-run details come from the isolated loopback fixture in +/// `tool/retry_wiring_probe.mjs`, never from app-side fake data. The zone and +/// `FlutterError` hooks only report probe failures to the driver; they do not +/// alter composition or behavior. +void main() { + FlutterError.onError = (details) { + debugPrint('FLUTTER ERROR: ${details.exceptionAsString()}'); + FlutterError.presentError(details); + }; + runZonedGuarded( + runPipelinesApp, + (error, stack) => debugPrint('ZONE ERROR: $error\n$stack'), + ); +} diff --git a/app/tool/retry_wiring_probe.mjs b/app/tool/retry_wiring_probe.mjs new file mode 100644 index 00000000..a29a76cb --- /dev/null +++ b/app/tool/retry_wiring_probe.mjs @@ -0,0 +1,772 @@ +import { spawn, execFile } from 'node:child_process'; +import { promisify } from 'node:util'; +import { mkdtemp, mkdir, rm, writeFile, readFile, realpath, stat } from 'node:fs/promises'; +import { once } from 'node:events'; +import { createServer } from 'node:http'; +import { createHash } from 'node:crypto'; +import { tmpdir } from 'node:os'; +import { extname, join, resolve, sep } from 'node:path'; +import { setTimeout as delay } from 'node:timers/promises'; + +// Real-browser acceptance for the run-retry wiring. +// +// Usage (from app/): +// flutter build web --target=tool/retry_wiring_probe.dart -o build/retry_probe_web +// OPENCODE_ARTIFACT_DIR= node tool/retry_wiring_probe.mjs build/retry_probe_web +// +// Environment: +// OPENCODE_ARTIFACT_DIR required; receives the PNG captures +// PROBE_THEME `dark` (default) or `light` +// CHROME_PATH Chrome binary; defaults to the macOS install +// TESSERACT OCR binary; defaults to `tesseract` on PATH +// +// The fixture serves the real bundle over loopback and answers the same +// websocket protocol as the app server: one stopped failed run, `get_run`, +// and `retry_run`. It records the exact retry payload, replies with the new +// run's `run_started` detail and pushes the matching compact run event, so the +// real app must open only the id the server names. Chrome is required; OCR +// checks cover the canvas-rendered titles. +const output = process.env.OPENCODE_ARTIFACT_DIR; +if (!output) throw new Error('Set OPENCODE_ARTIFACT_DIR for the probe captures'); +await mkdir(output, { recursive: true }); +const theme = process.env.PROBE_THEME === 'light' ? 'light' : 'dark'; +const chromePath = + process.env.CHROME_PATH ?? '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'; +const tesseract = process.env.TESSERACT ?? 'tesseract'; +const root = await realpath(process.argv[2] ?? 'build/retry_probe_web'); + +const SOURCE_ID = 7; +const RUN = { + id: SOURCE_ID, + pipeline_id: 3, + title: 'Fixture failed run', + name: 'fixture-retry', + version: 2, + status: 'failed', + executing: false, + created_at: '2026-10-21T12:00:00Z', + finished_at: '2026-10-21T12:04:00Z', +}; +const retries = []; +const counters = { listRuns: 0, getRun: 0 }; +let nextRunId = SOURCE_ID + 1; +const runs = new Map([[SOURCE_ID, { ...RUN }]]); + +function runRow(run) { + return { + id: run.id, + pipeline_id: run.pipeline_id, + title: run.title, + name: run.name, + version: run.version, + status: run.status, + executing: run.executing, + created_at: run.created_at, + finished_at: run.finished_at, + }; +} + +function runDetail(run) { + return { + ...runRow(run), + retry_of: run.retry_of, + input: { prompt: ' fixture prompt with spaces ' }, + steps: [ + { stage: 'build', sequence: 3, status: 'completed', outcome: 'success' }, + ], + }; +} + +function newRetry(mode) { + const id = nextRunId++; + const label = mode === 'restart' ? 'Restart' : 'Resume'; + const run = { + id, + pipeline_id: RUN.pipeline_id, + title: `${label} of ${SOURCE_ID}`, + name: RUN.name, + version: RUN.version, + status: 'running', + executing: true, + retry_of: SOURCE_ID, + created_at: '2026-10-21T12:05:00Z', + finished_at: '', + }; + runs.set(id, run); + return run; +} + +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', +}; + +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) { + this.socket = socket; + this.buffer = Buffer.alloc(0); + } + + push(chunk) { + if (chunk?.length) this.buffer = Buffer.concat([this.buffer, chunk]); + while (this.buffer.length >= 2) { + const first = this.buffer[0]; + const second = this.buffer[1]; + const opcode = first & 0x0f; + 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 masked = (second & 0x80) !== 0; + 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); + if (opcode === 0x8) return this.close(); + if (opcode === 0x9) { + this.socket.write(frame(0x0a, payload)); + continue; + } + if (opcode !== 0x1) continue; + let request; + try { + request = JSON.parse(payload.toString('utf8')); + } catch { + continue; + } + this.message(request); + } + } + + message(request) { + if (request.type === 'subscribe' || request.type === 'unsubscribe') return; + if (request.type === 'ping') { + this.send({ id: request.id, type: 'pong', build: { version: 'Retry fixture' } }); + return; + } + if (request.type === 'list_runs') { + counters.listRuns++; + this.send({ + id: request.id, + type: 'runs', + runs: [...runs.values()].map(runRow), + usage: null, + }); + return; + } + if (request.type === 'get_run') { + counters.getRun++; + const run = runs.get(request.run_id); + if (!run) { + this.send({ id: request.id, type: 'error', error: `no run ${request.run_id}` }); + return; + } + this.send({ id: request.id, type: 'run', run_detail: runDetail(run) }); + return; + } + if (request.type === 'retry_run') { + const record = { + run_id: request.run_id, + request_key: request.request_key, + keys: Object.keys(request).filter((key) => !['type', 'id'].includes(key)).sort(), + }; + if (request.retry_mode != null) record.retry_mode = request.retry_mode; + retries.push(record); + const source = runs.get(request.run_id); + if (!source || source.status !== 'failed' || source.executing) { + this.send({ id: request.id, type: 'error', error: 'only failed stopped runs can be retried' }); + return; + } + if (!request.request_key) { + this.send({ id: request.id, type: 'error', error: 'retry requires an idempotency request key' }); + return; + } + const created = newRetry(request.retry_mode === 'restart' ? 'restart' : 'resume'); + this.send({ id: request.id, type: 'run_started', run_detail: runDetail(created) }); + // The real server also pushes the new run to the compact watch; that row + // is what makes the retried run appear in the list after Back. + this.send({ + type: 'run_event', + run_id: created.id, + pipeline_id: created.pipeline_id, + name: created.name, + title: created.title, + version: created.version, + status: created.status, + created_at: created.created_at, + finished_at: '', + }); + return; + } + this.send({ + id: request.id, + type: 'error', + error: `Fixture does not implement ${request.type}`, + }); + } + + 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, 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(body); + } catch { + res.writeHead(404).end('not found'); + } +} + +const sockets = new Set(); +const server = createServer(async (req, res) => { + const pathname = new URL(req.url, 'http://fixture').pathname; + if (pathname === '/fixture/state') { + res + .writeHead(200, { 'content-type': 'application/json' }) + .end(JSON.stringify({ retries, runs: [...runs.values()], ...counters })); + return; + } + if (req.method !== 'GET' && req.method !== 'HEAD') { + res.writeHead(405).end(); + return; + } + await staticFile(root, pathname, res); +}); +server.on('upgrade', (req, socket, head) => { + 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); + socket.on('data', (chunk) => connection.push(chunk)); + socket.on('error', () => socket.destroy()); + sockets.add(socket); + socket.on('close', () => sockets.delete(socket)); + connection.push(head); +}); +server.listen(0, '127.0.0.1'); +await once(server, 'listening'); +const fixtureUrl = `http://127.0.0.1:${server.address().port}`; + +const profile = await mkdtemp(join(tmpdir(), 'r2-title-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; +}); + +async function waitFor(check, label, attempts = 160) { + for (let attempt = 0; attempt < attempts; attempt++) { + const value = await check(); + if (value) return value; + await delay(100); + } + throw new Error(`Timed out waiting for ${label}\n${stderr.slice(-1200)}`); +} + +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.method === 'Runtime.exceptionThrown') { + console.error('PAGE EXCEPTION', JSON.stringify(message.params?.exceptionDetails)); + } + if (message.method === 'Runtime.consoleAPICalled') { + const values = (message.params?.args ?? []).map((arg) => arg.value ?? arg.description); + if (values.some((value) => String(value).includes('ERROR'))) { + console.error('PAGE CONSOLE', values.join(' ')); + } + } + 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 target = (await send('Target.createTarget', { url: 'about:blank' })).result.targetId; + const session = (await send('Target.attachToTarget', { targetId: target, flatten: true })).result.sessionId; + await send('Page.enable', {}, session); + await send('Runtime.enable', {}, 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)}`); + if (response.result?.exceptionDetails) { + throw new Error(`Page exception: ${JSON.stringify(response.result.exceptionDetails)}`); + } + return response.result?.result?.value; + }; + + const enableSemantics = async () => { + await waitFor( + () => evaluate("Boolean(document.querySelector('flt-semantics-placeholder'))"), + 'Flutter semantics placeholder', + ); + await evaluate("document.querySelector('flt-semantics-placeholder')?.click()"); + await delay(700); + }; + + const semanticText = () => + evaluate(`(() => { + const chunks = []; + for (const el of document.querySelectorAll('flt-semantics')) { + const label = el.getAttribute('aria-label'); + if (label) chunks.push(label); + const value = el.getAttribute('aria-valuetext'); + if (value) chunks.push(value); + if (el.value) chunks.push(String(el.value)); + if (!el.children.length && el.innerText) chunks.push(el.innerText); + } + for (const el of document.querySelectorAll('input, textarea')) { + const label = el.getAttribute('aria-label'); + if (label) chunks.push(label); + if (el.value) chunks.push(String(el.value)); + } + if (document.body?.innerText) chunks.push(document.body.innerText); + return [...new Set(chunks)].join('\\n'); + })()`); + + const assertBody = async (text) => { + try { + await waitFor( + async () => (await semanticText()).includes(text), + `body to contain ${JSON.stringify(text)}`, + ); + } catch (error) { + throw new Error(`${error.message}\nBody now:\n${(await semanticText()).slice(0, 3000)}`); + } + }; + + // The action row once had no Wrap spacing, so the outlined Rename border met + // the filled Retry button at 320 px. Measure the real controls' bounds; a + // screenshot alone cannot prove the 8 dp convention was restored. + const actionGap = async (check) => { + const rects = await evaluate(`(() => { + const found = {}; + for (const el of document.querySelectorAll('flt-semantics')) { + const label = (el.getAttribute('aria-label') || el.innerText || '').trim(); + if (label !== 'Rename' && label !== 'Retry') continue; + const r = el.getBoundingClientRect(); + const area = r.width * r.height; + if (!found[label] || area > found[label].area) { + found[label] = { left: r.left, right: r.right, top: r.top, bottom: r.bottom, area }; + } + } + return found; + })()`); + if (!rects.Rename || !rects.Retry) { + throw new Error(`${check}: action bounds missing ${JSON.stringify(rects)}`); + } + const sameRow = + Math.min(rects.Rename.bottom, rects.Retry.bottom) > + Math.max(rects.Rename.top, rects.Retry.top); + const gap = sameRow + ? rects.Retry.left - rects.Rename.right + : rects.Retry.top - rects.Rename.bottom; + const minimum = sameRow ? 8 : 4; + if (gap < minimum - 0.5) { + throw new Error( + `${check}: Rename/Retry are ${gap.toFixed(3)} px apart, expected at least ${minimum} dp`, + ); + } + return { + check: `${check} actions stay ${minimum} dp apart`, + gap: Number(gap.toFixed(3)), + sameRow, + }; + }; + + const clickText = async (text, { last = false } = {}) => { + const clicked = await evaluate(`(() => { + const wanted = ${JSON.stringify(text)}; + const all = [...document.querySelectorAll('flt-semantics')].filter((el) => { + const label = (el.getAttribute('aria-label') || el.innerText || '').trim(); + return label === wanted; + }); + const candidates = all.filter((el) => + ['button', 'tab', 'link', 'checkbox', 'menuitem'].includes(el.getAttribute('role')), + ); + const pool = candidates.length ? candidates : all; + // A modal route is appended after the page: choosing the last match + // targets the dialog confirm instead of the page action underneath. + const target = ${last ? 'pool.at(-1)' : 'pool[0]'}; + if (!target) return false; + target.click(); + return true; + })()`); + if (!clicked) { + const labels = await evaluate(`[...document.querySelectorAll('flt-semantics')] + .map((el) => (el.getAttribute('aria-label') || el.innerText || '').trim()).filter(Boolean)`); + throw new Error(`Could not click ${JSON.stringify(text)}. Labels: ${JSON.stringify(labels)}`); + } + await delay(400); + }; + + const clickContains = async (text) => { + const clicked = await evaluate(`(() => { + const wanted = ${JSON.stringify(text)}; + const all = [...document.querySelectorAll('flt-semantics')].filter((el) => { + const label = (el.getAttribute('aria-label') || el.innerText || '').trim(); + return label.includes(wanted); + }); + const target = all.find((el) => + ['button', 'link', 'tab'].includes(el.getAttribute('role')), + ) ?? all.at(-1); + if (!target) return false; + target.click(); + return true; + })()`); + if (!clicked) throw new Error(`Could not click a row containing ${JSON.stringify(text)}`); + await delay(400); + }; + + const capture = async (name) => { + const data = (await send('Page.captureScreenshot', { format: 'png' }, session)).result.data; + const path = join(output, `${name}.png`); + await writeFile(path, Buffer.from(data, 'base64')); + return path; + }; + + const ocr = async (path) => + (await promisify(execFile)(tesseract, [path, 'stdout'])).stdout; + + const assertOcr = async (path, text) => { + const read = await ocr(path); + if (!read.toLowerCase().includes(text.toLowerCase())) { + throw new Error(`OCR of ${path} lacks ${JSON.stringify(text)}:\n${read.slice(0, 2000)}`); + } + }; + + const state = async () => (await (await fetch(`${fixtureUrl}/fixture/state`)).json()); + + const setView = async ({ width, height, deviceScaleFactor = 1 }) => { + await send( + 'Emulation.setDeviceMetricsOverride', + { width, height, deviceScaleFactor, mobile: width < 600 }, + session, + ); + await send( + 'Emulation.setEmulatedMedia', + { features: [{ name: 'prefers-color-scheme', value: theme }] }, + session, + ); + await delay(400); + }; + + const retryPromptOpen = async () => + (await semanticText()).includes(`Retry run ${SOURCE_ID}?`); + const restartPromptOpen = async () => + (await semanticText()).includes(`Restart run ${SOURCE_ID}?`); + + const assertPayload = (record, { restart, check }) => { + if (!record) throw new Error(`${check}: the server recorded no retry`); + const keys = restart + ? ['request_key', 'retry_mode', 'run_id'] + : ['request_key', 'run_id']; + if (JSON.stringify(record.keys) !== JSON.stringify(keys)) { + throw new Error(`${check}: unexpected request fields ${JSON.stringify(record)}`); + } + if (record.run_id !== SOURCE_ID) { + throw new Error(`${check}: wrong run id ${JSON.stringify(record)}`); + } + if (!String(record.request_key).startsWith(`app-retry-${SOURCE_ID}-`)) { + throw new Error(`${check}: wrong request key ${JSON.stringify(record)}`); + } + if (String(record.request_key).length > 128) { + throw new Error(`${check}: request key too long ${JSON.stringify(record)}`); + } + if (restart && record.retry_mode !== 'restart') { + throw new Error(`${check}: restart mode missing ${JSON.stringify(record)}`); + } + if (!restart && record.retry_mode != null) { + throw new Error(`${check}: resume must omit retry_mode ${JSON.stringify(record)}`); + } + return record; + }; + + const captures = []; + const checks = []; + + await setView({ width: 320, height: 480, deviceScaleFactor: 2 }); + if ( + !(await evaluate(`matchMedia('(prefers-color-scheme: ${theme})').matches`)) + ) { + throw new Error(`The fixture host is not in ${theme} mode`); + } + + const open = async (id, expectedTitle) => { + const navigation = await send( + 'Page.navigate', + { url: `${fixtureUrl}/runs/${id}` }, + session, + ); + if (navigation.error || navigation.result?.errorText) throw new Error(JSON.stringify(navigation)); + await enableSemantics(); + await assertBody(expectedTitle); + if ((await evaluate('location.pathname')) !== `/runs/${id}`) { + throw new Error(`Deep link moved to ${await evaluate('location.pathname')}`); + } + }; + + const waitNewRun = async (id, title) => { + await waitFor( + async () => (await evaluate('location.pathname')) === `/runs/${id}`, + `the route to open run ${id}`, + ); + await assertBody(title); + await assertBody('Original prompt'); + }; + + // Cupertino host (macOS browser), 320 CSS px at DPR 2 in dark mode. + await open(SOURCE_ID, 'Fixture failed run'); + await assertBody('Rename'); + await assertBody('Retry'); + captures.push(await capture(`r2c-retry-cupertino-${theme}-failed`)); + await assertOcr(captures.at(-1), 'Fixture failed run'); + checks.push(await actionGap('Cupertino')); + checks.push({ check: `Cupertino ${theme} 320px detail offers Retry`, path: await evaluate('location.pathname') }); + + await clickText('Retry'); + await waitFor(retryPromptOpen, 'the retry prompt'); + await assertBody('Only failed runs can be retried'); + captures.push(await capture(`r2c-retry-cupertino-${theme}-prompt`)); + await assertOcr(captures.at(-1), 'Retry run 7?'); + + await clickText('Keep'); + await waitFor(async () => !(await retryPromptOpen()), 'the closed retry prompt'); + if ((await state()).retries.length !== 0) { + throw new Error('Keep sent retry_run'); + } + checks.push({ check: 'Cupertino Keep sent nothing', sent: 0 }); + captures.push(await capture(`r2c-retry-cupertino-${theme}-kept`)); + + // Restart: the browser-only second confirmation, then the server-named run. + await clickText('Retry'); + await waitFor(retryPromptOpen, 'the retry prompt again'); + await clickText('Restart from start'); + await waitFor(restartPromptOpen, 'the restart prompt'); + await assertBody('replays the whole pipeline'); + captures.push(await capture(`r2c-retry-cupertino-${theme}-restart-prompt`)); + await clickText('Restart from start', { last: true }); + try { + await waitFor(async () => (await state()).retries.length === 1, 'the first retry request'); + } catch (error) { + console.error('STATE', JSON.stringify(await state())); + console.error('TEXT', (await semanticText()).slice(0, 2000)); + await capture('r2c-retry-debug'); + throw error; + } + const restart = assertPayload((await state()).retries[0], { + restart: true, + check: 'Cupertino restart', + }); + await waitNewRun(SOURCE_ID + 1, 'Restart of 7'); + captures.push(await capture(`r2c-retry-cupertino-${theme}-restart-run`)); + await assertOcr(captures.at(-1), 'Restart of 7'); + checks.push({ check: 'Cupertino restart opened only the server-named run', restart, path: await evaluate('location.pathname') }); + + await clickText('Back'); + await assertBody('Fixture failed run'); + await assertBody('Restart of 7'); + captures.push(await capture(`r2c-retry-cupertino-${theme}-list`)); + await assertOcr(captures.at(-1), 'Restart of 7'); + + // Resume after returning to the still-failed source run. + await clickContains('Fixture failed run'); + await waitFor( + async () => (await evaluate('location.pathname')) === `/runs/${SOURCE_ID}`, + 'the source run again', + ); + await assertBody('Retry'); + await clickText('Retry'); + await waitFor(retryPromptOpen, 'the resume prompt'); + await clickText('Retry', { last: true }); + await waitFor(async () => (await state()).retries.length === 2, 'the resume request'); + const resume = assertPayload((await state()).retries[1], { + restart: false, + check: 'Cupertino resume', + }); + await waitNewRun(SOURCE_ID + 2, 'Resume of 7'); + captures.push(await capture(`r2c-retry-cupertino-${theme}-resume-run`)); + await assertOcr(captures.at(-1), 'Resume of 7'); + checks.push({ check: 'Cupertino resume omitted retry_mode and opened the reply run', resume, path: await evaluate('location.pathname') }); + + // Material host: the same deep link, shared gateway and normal app build. + await 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', + }, + session, + ); + await open(SOURCE_ID, 'Fixture failed run'); + await assertBody('Rename'); + await assertBody('Retry'); + captures.push(await capture(`r2c-retry-material-${theme}-failed`)); + await assertOcr(captures.at(-1), 'Fixture failed run'); + checks.push(await actionGap('Material')); + checks.push({ check: `Material ${theme} 320px detail offers Retry`, path: await evaluate('location.pathname') }); + + await clickText('Retry'); + await waitFor(retryPromptOpen, 'the material retry prompt'); + captures.push(await capture(`r2c-retry-material-${theme}-prompt`)); + await clickText('Keep'); + await waitFor(async () => !(await retryPromptOpen()), 'the closed material prompt'); + if ((await state()).retries.length !== 2) { + throw new Error('Material Keep sent retry_run'); + } + checks.push({ check: 'Material Keep sent nothing', sent: 0 }); + + await clickText('Retry'); + await waitFor(retryPromptOpen, 'the material resume prompt'); + await clickText('Retry', { last: true }); + await waitFor(async () => (await state()).retries.length === 3, 'the material retry request'); + const material = assertPayload((await state()).retries[2], { + restart: false, + check: 'Material resume', + }); + await waitNewRun(SOURCE_ID + 3, 'Resume of 7'); + captures.push(await capture(`r2c-retry-material-${theme}-run`)); + await assertOcr(captures.at(-1), 'Resume of 7'); + checks.push({ check: 'Material resume sent the exact payload and opened the reply run', material, path: await evaluate('location.pathname') }); + + const finalState = await state(); + if (finalState.retries.length !== 3) { + throw new Error(`Expected three retry requests, saw ${JSON.stringify(finalState.retries)}`); + } + if (finalState.runs.filter((run) => run.id !== SOURCE_ID).length !== 3) { + throw new Error(`Expected three server-created runs, saw ${JSON.stringify(finalState.runs)}`); + } + console.log(JSON.stringify({ ok: true, fixture: fixtureUrl, checks, captures }, null, 2)); +} finally { + ws?.close(); + for (const socket of sockets) socket.destroy(); + await new Promise((resolveClose) => server.close(resolveClose)); + chrome.kill('SIGTERM'); + await Promise.race([once(chrome, 'exit'), delay(3000)]); + await rm(profile, { recursive: true, force: true }); +}