From 178f22aec20868656d0fff35e8a69dd2ce36baf6 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 15:13:00 +0100 Subject: [PATCH 01/18] feat(app): add native retry and restart action --- .../features/runs/actions/retry_action.dart | 123 +++++++++ .../features/runs/actions/retry_dialog.dart | 207 +++++++++++++++ .../runs/actions/retry_eligibility.dart | 16 ++ .../features/runs/actions/retry_intent.dart | 29 +++ .../features/runs/actions/retry_wording.dart | 33 +++ app/notes/R2c.md | 114 ++++++++ .../runs/actions/retry_action_test.dart | 245 ++++++++++++++++++ .../runs/actions/retry_resilience_test.dart | 223 ++++++++++++++++ .../runs/actions/retry_safety_test.dart | 133 ++++++++++ .../runs/actions/retry_test_support.dart | 112 ++++++++ 10 files changed, 1235 insertions(+) create mode 100644 app/lib/features/runs/actions/retry_action.dart create mode 100644 app/lib/features/runs/actions/retry_dialog.dart create mode 100644 app/lib/features/runs/actions/retry_eligibility.dart create mode 100644 app/lib/features/runs/actions/retry_intent.dart create mode 100644 app/lib/features/runs/actions/retry_wording.dart create mode 100644 app/notes/R2c.md create mode 100644 app/test/features/runs/actions/retry_action_test.dart create mode 100644 app/test/features/runs/actions/retry_resilience_test.dart create mode 100644 app/test/features/runs/actions/retry_safety_test.dart create mode 100644 app/test/features/runs/actions/retry_test_support.dart diff --git a/app/lib/features/runs/actions/retry_action.dart b/app/lib/features/runs/actions/retry_action.dart new file mode 100644 index 00000000..28cda388 --- /dev/null +++ b/app/lib/features/runs/actions/retry_action.dart @@ -0,0 +1,123 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../core/api_gateway.dart'; +import '../data/runs_repository.dart'; +import 'action_refusal.dart'; +import 'retry_dialog.dart'; +import 'retry_eligibility.dart'; +import 'retry_intent.dart'; +import 'retry_wording.dart'; + +/// The run detail's deliberate retry entry point. +/// +/// Renders one native button only while [run] is a stopped `failed` run. Opening +/// the resume or restart confirmation sends nothing; only the confirm action +/// asks the server to retry. A refusal is returned to the kept-open prompt +/// immediately and the run is re-read separately, so [onRunChanged] still +/// receives server truth without locking the prompt while that read is pending. +class RetryRunAction extends StatefulWidget { + const RetryRunAction({ + super.key, + required this.run, + required this.gateway, + required this.onRunChanged, + }); + + final JsonMap run; + final ApiGateway gateway; + final ValueChanged onRunChanged; + + @override + State createState() => _RetryRunActionState(); +} + +class _RetryRunActionState extends State { + bool _dialogOpen = false; + Future? _resync; + + bool _usesCupertino(BuildContext context) { + final material = Localizations.of( + context, + MaterialLocalizations, + ); + return material == null; + } + + Future _open() async { + final id = retryRunId(widget.run); + if (id == null || !canRetryRun(widget.run) || _dialogOpen) return; + _dialogOpen = true; + try { + await showRetryRunPrompt( + context: context, + runId: id, + cupertino: _usesCupertino(context), + onSubmit: (intent) => _submit(id, intent), + ); + } finally { + _dialogOpen = false; + if (mounted) setState(() {}); + } + } + + Future _submit(num id, RetryIntent intent) async { + final repository = RunsRepository(widget.gateway); + try { + final run = await repository.retryRun( + id, + requestKey: intent.requestKey, + mode: intent.mode.wireMode, + ); + if (!mounted) return null; + if (_owns(id)) widget.onRunChanged(run); + return null; + } catch (error) { + return ActionRefusal( + describeRetryError(error), + stillPossible: _resyncRun(id), + ); + } + } + + bool _owns(num id) => mounted && retryRunId(widget.run) == id; + + /// One bounded re-read per refusal. A refusal that arrives while a read is + /// already in flight observes that same read instead of starting another. + Future _resyncRun(num id) { + return _resync ??= _readRun(id); + } + + Future _readRun(num id) async { + try { + final run = await RunsRepository(widget.gateway).getRun(id); + if (!_owns(id)) return null; + widget.onRunChanged(run); + return canRetryRun(run); + } catch (_) { + // Unknown server truth: keep the refusal and leave a deliberate retry. + return null; + } finally { + _resync = null; + } + } + + @override + Widget build(BuildContext context) { + if (retryRunId(widget.run) == null || !canRetryRun(widget.run)) { + return const SizedBox.shrink(); + } + if (_usesCupertino(context)) { + return CupertinoButton.filled( + key: retryActionKey, + onPressed: _open, + child: const Text(retryActionLabel), + ); + } + return FilledButton( + key: retryActionKey, + onPressed: _open, + child: const Text(retryActionLabel), + ); + } +} diff --git a/app/lib/features/runs/actions/retry_dialog.dart b/app/lib/features/runs/actions/retry_dialog.dart new file mode 100644 index 00000000..846133a1 --- /dev/null +++ b/app/lib/features/runs/actions/retry_dialog.dart @@ -0,0 +1,207 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import 'action_refusal.dart'; +import 'retry_intent.dart'; +import 'retry_wording.dart'; + +/// Sends the confirmed retry intent. Returns null once the server has accepted +/// it, or an [ActionRefusal] carrying the server's words verbatim; the prompt +/// then stays open with dismissal available immediately. +typedef RetrySubmit = Future Function(RetryIntent intent); + +/// Opens the native retry confirmation for [runId]. +/// +/// The first confirmation offers resume (the default) and a secondary +/// `Restart from start` confirmation, exactly like the browser's retry dialog. +/// Nothing is sent until the operator presses a confirm action; `Keep` only +/// closes the prompt. +Future showRetryRunPrompt({ + required BuildContext context, + required num runId, + required bool cupertino, + required RetrySubmit onSubmit, +}) { + final prompt = _RetryPrompt( + runId: runId, + cupertino: cupertino, + onSubmit: onSubmit, + ); + if (cupertino) { + return showCupertinoDialog( + context: context, + barrierDismissible: false, + builder: (_) => prompt, + ); + } + return showDialog( + context: context, + barrierDismissible: false, + builder: (_) => prompt, + ); +} + +class _RetryPrompt extends StatefulWidget { + const _RetryPrompt({ + required this.runId, + required this.cupertino, + required this.onSubmit, + }); + + final num runId; + final bool cupertino; + final RetrySubmit onSubmit; + + @override + State<_RetryPrompt> createState() => _RetryPromptState(); +} + +class _RetryPromptState extends State<_RetryPrompt> { + RetryMode _mode = RetryMode.resume; + String? _requestKey; + bool _sending = false; + bool _checking = false; + bool _blocked = false; + bool _attempted = false; + String? _error; + + void _keep() { + if (!_sending) Navigator.of(context).pop(); + } + + void _restart() { + if (_sending || _checking || _attempted) return; + setState(() { + _mode = RetryMode.restart; + _error = null; + }); + } + + Future _confirm() async { + if (_sending || _checking || _blocked) return; + setState(() { + _sending = true; + _attempted = true; + _error = null; + }); + final intent = RetryIntent( + mode: _mode, + requestKey: _requestKey ??= newRetryRequestKey(widget.runId), + ); + final refusal = await widget.onSubmit(intent); + if (!mounted) return; + if (refusal == null) { + Navigator.of(context).pop(); + return; + } + final check = refusal.stillPossible; + setState(() { + _sending = false; + _error = refusal.message; + _checking = check != null; + }); + if (check == null) return; + bool? stillPossible; + try { + stillPossible = await check; + } catch (_) { + // The action reports re-read failures as null; never fabricate one here. + } + if (!mounted) return; + setState(() { + _checking = false; + _blocked = stillPossible == false; + }); + } + + @override + Widget build(BuildContext context) { + final dialog = widget.cupertino ? _cupertino(context) : _material(context); + return PopScope(canPop: !_sending, child: dialog); + } + + bool get _confirmDisabled => _sending || _checking || _blocked; + bool get _showRestart => _mode == RetryMode.resume && !_attempted; + + Widget _material(BuildContext context) { + final theme = Theme.of(context); + return AlertDialog( + scrollable: true, + title: Text(_dialogTitle), + content: _body(errorStyle: TextStyle(color: theme.colorScheme.error)), + actions: [ + if (_showRestart) + TextButton( + key: retryRestartKey, + onPressed: _sending || _checking ? null : _restart, + child: const Text(restartConfirmLabel), + ), + TextButton( + key: retryKeepKey, + onPressed: _sending ? null : _keep, + child: const Text(retryKeepLabel), + ), + FilledButton( + key: retryConfirmKey, + onPressed: _confirmDisabled ? null : _confirm, + child: Text(_confirmLabel), + ), + ], + ); + } + + Widget _cupertino(BuildContext context) { + return CupertinoAlertDialog( + title: Text(_dialogTitle), + content: _body( + errorStyle: TextStyle( + color: CupertinoColors.systemRed.resolveFrom(context), + ), + ), + actions: [ + if (_showRestart) + CupertinoDialogAction( + key: retryRestartKey, + onPressed: _sending || _checking ? null : _restart, + child: const Text(restartConfirmLabel), + ), + CupertinoDialogAction( + key: retryKeepKey, + onPressed: _sending ? null : _keep, + child: const Text(retryKeepLabel), + ), + CupertinoDialogAction( + key: retryConfirmKey, + isDestructiveAction: _mode == RetryMode.restart, + onPressed: _confirmDisabled ? null : _confirm, + child: Text(_confirmLabel), + ), + ], + ); + } + + Widget _body({required TextStyle errorStyle}) { + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text(_dialogMessage), + if (_error case final error?) + Padding( + padding: const EdgeInsets.only(top: 8), + child: Text(error, key: retryErrorKey, style: errorStyle), + ), + ], + ); + } + + String get _dialogTitle => _mode == RetryMode.restart + ? restartDialogTitle(widget.runId) + : retryDialogTitle(widget.runId); + + String get _dialogMessage => + _mode == RetryMode.restart ? restartDialogMessage : retryDialogMessage; + + String get _confirmLabel => + _mode == RetryMode.restart ? restartConfirmLabel : retryConfirmLabel; +} diff --git a/app/lib/features/runs/actions/retry_eligibility.dart b/app/lib/features/runs/actions/retry_eligibility.dart new file mode 100644 index 00000000..13026230 --- /dev/null +++ b/app/lib/features/runs/actions/retry_eligibility.dart @@ -0,0 +1,16 @@ +import '../../../core/api_gateway.dart'; + +/// Whether the operator may retry [run], matching `canRetry` in +/// `web/src/actions.js` exactly: a loaded run that is not executing and whose +/// status is `failed`. A stale `failed` status while the run still executes is +/// not retryable. +bool canRetryRun(JsonMap? run) { + if (run == null) return false; + return run['executing'] != true && run['status'] == 'failed'; +} + +/// The run id used by the retry request, or null for a malformed run. +num? retryRunId(JsonMap run) { + final id = run['id']; + return id is num ? id : null; +} diff --git a/app/lib/features/runs/actions/retry_intent.dart b/app/lib/features/runs/actions/retry_intent.dart new file mode 100644 index 00000000..17140a70 --- /dev/null +++ b/app/lib/features/runs/actions/retry_intent.dart @@ -0,0 +1,29 @@ +import 'dart:math'; + +/// The two deliberate retry choices. `resume` is the server's default, so its +/// wire field is omitted; `restart` replays the whole pipeline. +enum RetryMode { + resume, + restart; + + /// The `retry_mode` value to send, or null to let the server resume. + String? get wireMode => this == RetryMode.restart ? 'restart' : null; +} + +/// One confirmed retry intent: the chosen mode plus the idempotency key that +/// belongs to it. Retrying the same uncertain intent reuses [requestKey] so the +/// server can dedupe it; a fresh deliberate intent uses a new key. +class RetryIntent { + const RetryIntent({required this.mode, required this.requestKey}); + + final RetryMode mode; + final String requestKey; +} + +/// 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); + return 'app-retry-$runId-$stamp-${entropy.toRadixString(36)}'; +} diff --git a/app/lib/features/runs/actions/retry_wording.dart b/app/lib/features/runs/actions/retry_wording.dart new file mode 100644 index 00000000..efec7d86 --- /dev/null +++ b/app/lib/features/runs/actions/retry_wording.dart @@ -0,0 +1,33 @@ +import 'package:flutter/widgets.dart'; + +/// The browser client's retry wording, kept verbatim. +const retryActionLabel = 'Retry'; +const retryDialogMessage = + 'Only failed runs can be retried. The server starts a new run from the ' + 'same input.'; +const retryConfirmLabel = 'Retry'; +const restartDialogMessage = + 'This replays the whole pipeline from the start instead of resuming the ' + 'failed stage.'; +const restartConfirmLabel = 'Restart from start'; +const retryKeepLabel = 'Keep'; + +/// Stable test/semantics keys shared by the action and its prompt. +const retryActionKey = ValueKey('retry-run-action'); +const retryKeepKey = ValueKey('retry-run-keep'); +const retryConfirmKey = ValueKey('retry-run-confirm'); +const retryRestartKey = ValueKey('retry-run-restart'); +const retryErrorKey = ValueKey('retry-run-error'); + +/// The retry dialog's title: `Retry run {id}?`. +String retryDialogTitle(num runId) => 'Retry run $runId?'; + +/// The restart dialog's title: `Restart run {id}?`. +String restartDialogTitle(num runId) => 'Restart run $runId?'; + +/// The server's refusal, verbatim. Only a blank error gets a generic sentence +/// so the prompt never claims a retry that did not happen. +String describeRetryError(Object error) { + final message = '$error'.trim(); + return message.isEmpty ? 'The server did not retry the run.' : message; +} diff --git a/app/notes/R2c.md b/app/notes/R2c.md new file mode 100644 index 00000000..f2240602 --- /dev/null +++ b/app/notes/R2c.md @@ -0,0 +1,114 @@ +# R2c — native retry / restart action + +Small app-only addition, new files only. `RetryRunAction(run, gateway, +onRunChanged)` is the deliberate retry entry point for a stopped failed run; it +does not add a screen or controller and is not wired into the shell. + +## What changed + +| File | Lines | Responsibility | +| --- | --- | --- | +| `lib/features/runs/actions/retry_action.dart` | 123 | `RetryRunAction`, gating, send/refusal/resync orchestration | +| `lib/features/runs/actions/retry_dialog.dart` | 207 | Native resume/restart confirmation, refusal display, key lifetime | +| `lib/features/runs/actions/retry_eligibility.dart` | 16 | `canRetryRun` mirroring the web `canRetry` | +| `lib/features/runs/actions/retry_intent.dart` | 29 | Mode, confirmed intent and idempotency-key generation | +| `lib/features/runs/actions/retry_wording.dart` | 33 | Web-verbatim words, titles, error wording and test keys | +| `test/.../retry_test_support.dart` | 112 | Fake gateway and Material/Cupertino hosts | +| `test/.../retry_action_test.dart` | 245 | Eligibility, both platforms, modes and key fields | +| `test/.../retry_resilience_test.dart` | 223 | Immediate refusals, recheck outcomes, key retention | +| `test/.../retry_safety_test.dart` | 133 | Double submit, late replies, narrow 2x layout | + +No repository, gateway, socket, controller, shell, main, pubspec, web, server or +device file was edited. + +## Behavior + +Eligibility is exactly the browser's rule: a loaded run that is not executing and +whose status is `failed` (`run != null && !run.executing && status == "failed"`). +A stale `failed` status while execution is still in flight, a running/waiting/ +succeeded/canceled run, and a malformed run render nothing. + +The button is a Material `FilledButton` or a Cupertino `CupertinoButton.filled`, +labelled `Retry`. Opening the prompt sends nothing, and `Keep` only closes it. + +The first confirmation is the browser's retry copy: title `Retry run {id}?`, +message `Only failed runs can be retried. The server starts a new run from the +same input.`, confirm `Retry`, dismiss `Keep`, plus the browser-only secondary +`Restart from start` that leads to a distinct confirmation. That second prompt +uses title `Restart run {id}?`, message `This replays the whole pipeline from the +start instead of resuming the failed stage.` and confirm `Restart from start`; +the resume actions are gone, so the more destructive choice cannot be mistaken +for resume. + +Resume calls `RunsRepository.retryRun` with only `run_id` and `request_key`, so +`retry_mode` is omitted and the server's `resume` default applies. Restart sends +`retry_mode: "restart"` with the same two required fields. + +A `request_key` is created on the first confirm of an open prompt, not on opening +or `Keep`. It survives a refusal, so pressing confirm again for the same +uncertain request reuses the key and the server can dedupe it. Closing the prompt +and opening it again is a fresh deliberate intent and gets a new key, so a resume +attempt followed by a restart attempt never shares a key. Switching to the +restart confirmation before any send simply confirms restart with that prompt's +first key. Keys are bounded and run-scoped (`app-retry-{runId}-…`, well under the +server's 128-character cap). + +A server refusal returns to the prompt immediately: the exact server words are +visible and `Keep`/back are available while the detached `get_run` recheck is +still pending. One bounded re-read is issued per refusal, single-flight through a +retained future, with no retry loop or polling. If server truth says the run is no +longer retryable, confirm is disabled and an attempted tap sends nothing; the +refusal stays visible until dismissal. If the recheck itself fails, truth is +unknown, so confirm is re-enabled and a deliberate retry uses the retained key. +Late retry replies and late rechecks after disposal or navigation are ignored. + +Construction, controls and error colour are standard Material/Cupertino defaults; +there is no custom palette, fixed control size or dependency. The narrow layout +relies on the native dialog's own scrolling/wrapping. + +## Acceptance checks + +Fake-gateway widget tests, both platforms, no socket or real server: + +- eligibility table for stopped failed vs executing failed, running, waiting, + succeeded and canceled runs, plus the same visibility table under both apps; +- `Retry` opens the native `AlertDialog`/`CupertinoAlertDialog`, `Keep` closes it + and the recorded gateway calls are still empty; +- resume sends exactly `{run_id, request_key}` and no `retry_mode`; restart sends + exactly `{run_id, request_key, retry_mode: "restart"}`; +- key format is deterministic under an injected clock/entropy, bounded, fresh per + call, retained across an uncertain retry (resume and restart), and different + after a deliberate reopen or mode change; +- refusal message appears while `get_run` is deliberately unresolved, with Keep + enabled, confirm disabled and no callback yet; Keep then closes and the late + recheck still delivers server truth safely; +- ineligible recheck (`succeeded`) blocks a repeat action; failed recheck leaves + the same key and a working deliberate retry; +- two confirm taps while in flight produce one `retry_run`; both the retry reply + and the recheck are safe after disposal; +- 320×480 at 2× text: both resume and restart confirmations render on both apps + with no exception, and Keep sends nothing. + +## Checks actually run + +``` +dart format lib/features/runs/actions test/features/runs/actions # clean +flutter analyze # No issues found! +flutter test test/features/runs/actions # 40 passed +flutter test # 69 passed +flutter build web # Built build/web (14.5s) +``` + +## Honest limits + +- **Not wired into a run-detail screen.** This branch has no runs screen or + controller; the manager owns that integration. There is no browser interaction + or rendered capture for this widget, and `flutter build web` proves compilation + only, not rendered behavior. +- Browser parity is by source/word/request-shape comparison with + `web/src/actions.js` and `web/src/repository.js`; the web client itself was not + changed and no live web retry was performed. +- **Mobile unverified.** No Android/iOS build, emulator, ADB or device was used. +- No real server or run was retried, canceled or otherwise mutated; all evidence + uses local fakes. +- The candidate is committed, not pushed or deployed. diff --git a/app/test/features/runs/actions/retry_action_test.dart b/app/test/features/runs/actions/retry_action_test.dart new file mode 100644 index 00000000..ca11fa8b --- /dev/null +++ b/app/test/features/runs/actions/retry_action_test.dart @@ -0,0 +1,245 @@ +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_eligibility.dart'; +import 'package:pipelines_app/features/runs/actions/retry_intent.dart'; +import 'package:pipelines_app/features/runs/actions/retry_wording.dart'; + +import 'retry_test_support.dart'; + +void main() { + test('retry eligibility matches the web canRetry exactly', () { + final cases = <(String, JsonMap, bool)>[ + ('failed and stopped', failedRun(), true), + ('failed but still executing', failedRun(executing: true), false), + ('running', failedRun(status: 'running'), false), + ('waiting', failedRun(status: 'waiting'), false), + ('succeeded', failedRun(status: 'succeeded'), false), + ('canceled', failedRun(status: 'canceled'), false), + ]; + for (final (label, run, expected) in cases) { + expect(canRetryRun(run), expected, reason: label); + } + expect(canRetryRun(null), isFalse); + expect(retryRunId(failedRun()), 7); + expect(retryRunId({'id': '7'}), isNull); + }); + + test('a generated retry key is bounded, run-scoped and fresh', () { + final first = newRetryRequestKey(7); + final second = newRetryRequestKey(7); + + expect(first, startsWith('app-retry-7-')); + expect(first.length, lessThanOrEqualTo(128)); + expect(second.length, lessThanOrEqualTo(128)); + expect(first, isNot(second)); + expect( + newRetryRequestKey(7, now: DateTime.utc(2026, 1, 1), random: 36), + 'app-retry-7-${DateTime.utc(2026, 1, 1).microsecondsSinceEpoch}-10', + ); + }); + + testWidgets( + 'material retry asks first, Keep sends nothing, then omits retry_mode', + (tester) async { + final accepted = retriedRun(); + final gateway = FakeRetryGateway( + (type, fields) async => {'run_detail': accepted}, + ); + final changed = []; + await pumpRetry(tester, gateway: gateway, changed: changed); + + expect(find.byKey(retryActionKey), findsOneWidget); + expect(find.byType(FilledButton), findsOneWidget); + expect(gateway.calls, isEmpty); + + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsOneWidget); + expect(find.text(retryDialogTitle(7)), findsOneWidget); + expect(find.text(retryDialogMessage), findsOneWidget); + expect( + find.descendant( + of: find.byType(AlertDialog), + matching: find.text(retryConfirmLabel), + ), + findsOneWidget, + ); + expect(find.text(restartConfirmLabel), findsOneWidget); + expect(gateway.calls, isEmpty); + + await tester.tap(find.byKey(retryKeepKey)); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsNothing); + expect(find.byKey(retryActionKey), findsOneWidget); + expect(gateway.calls, isEmpty); + + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryConfirmKey)); + await tester.pumpAndSettle(); + + expect(gateway.retries, hasLength(1)); + final fields = gateway.retries.single.fields; + expect(fields.keys, containsAll(['run_id', 'request_key'])); + expect(fields.containsKey('retry_mode'), isFalse); + expect(fields['run_id'], 7); + expect(fields['request_key'], startsWith('app-retry-7-')); + expect(fields['request_key'].length, lessThanOrEqualTo(128)); + expect(changed.single, equals(accepted)); + expect(find.byType(AlertDialog), findsNothing); + expect(find.byKey(retryActionKey), findsNothing); + }, + ); + + testWidgets( + 'material restart has its own confirmation and sends retry_mode', + (tester) async { + final accepted = retriedRun(); + final gateway = FakeRetryGateway( + (type, fields) async => {'run_detail': accepted}, + ); + final changed = []; + await pumpRetry(tester, gateway: gateway, changed: changed); + + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryRestartKey)); + await tester.pumpAndSettle(); + + expect(find.text(restartDialogTitle(7)), findsOneWidget); + expect(find.text(restartDialogMessage), findsOneWidget); + expect(find.text(retryDialogTitle(7)), findsNothing); + expect(find.text(retryDialogMessage), findsNothing); + expect(find.text(restartConfirmLabel), findsOneWidget); + expect(find.byKey(retryRestartKey), findsNothing); + expect(gateway.calls, isEmpty); + + await tester.tap(find.byKey(retryConfirmKey)); + await tester.pumpAndSettle(); + + expect(gateway.retries, hasLength(1)); + final fields = gateway.retries.single.fields; + expect(fields['run_id'], 7); + expect(fields['retry_mode'], 'restart'); + expect(fields['request_key'], startsWith('app-retry-7-')); + expect(changed.single, equals(accepted)); + expect(find.byType(AlertDialog), findsNothing); + }, + ); + + testWidgets( + 'cupertino retry uses a native prompt and sends only on confirm', + (tester) async { + final accepted = retriedRun(); + final gateway = FakeRetryGateway( + (type, fields) async => {'run_detail': accepted}, + ); + final changed = []; + await pumpRetry( + tester, + gateway: gateway, + changed: changed, + cupertino: true, + ); + + expect(find.byKey(retryActionKey), findsOneWidget); + expect(find.byType(CupertinoButton), findsOneWidget); + expect(find.byType(FilledButton), findsNothing); + + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + expect(find.byType(CupertinoAlertDialog), findsOneWidget); + expect(find.byType(AlertDialog), findsNothing); + expect(find.text(retryDialogTitle(7)), findsOneWidget); + expect(find.text(retryDialogMessage), findsOneWidget); + expect(gateway.calls, isEmpty); + + await tester.tap(find.byKey(retryKeepKey)); + await tester.pumpAndSettle(); + expect(gateway.calls, isEmpty); + expect(find.byType(CupertinoAlertDialog), findsNothing); + + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryConfirmKey)); + await tester.pumpAndSettle(); + + expect(gateway.retries, hasLength(1)); + final fields = gateway.retries.single.fields; + expect(fields['run_id'], 7); + expect(fields.containsKey('retry_mode'), isFalse); + expect(fields['request_key'], startsWith('app-retry-7-')); + expect(changed.single, equals(accepted)); + expect(find.byType(CupertinoAlertDialog), findsNothing); + }, + ); + + testWidgets('cupertino restart switches to the restart confirmation', ( + tester, + ) async { + final gateway = FakeRetryGateway( + (type, fields) async => {'run_detail': retriedRun()}, + ); + await pumpRetry( + tester, + gateway: gateway, + changed: [], + cupertino: true, + ); + + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryRestartKey)); + await tester.pumpAndSettle(); + + expect(find.byType(CupertinoAlertDialog), findsOneWidget); + expect(find.text(restartDialogTitle(7)), findsOneWidget); + expect(find.text(restartDialogMessage), findsOneWidget); + expect(gateway.calls, isEmpty); + + await tester.tap(find.byKey(retryConfirmKey)); + await tester.pumpAndSettle(); + expect(gateway.retries.single.fields['retry_mode'], 'restart'); + }); + + testWidgets('the action is absent for runs the web does not retry', ( + tester, + ) async { + final gateway = FakeRetryGateway( + (type, fields) async => {'run_detail': retriedRun()}, + ); + final changed = []; + final cases = <(String, JsonMap, bool)>[ + ('failed', failedRun(), true), + ('executing', failedRun(executing: true), false), + ('running', failedRun(status: 'running'), false), + ('waiting', failedRun(status: 'waiting'), false), + ('succeeded', failedRun(status: 'succeeded'), false), + ('canceled', failedRun(status: 'canceled'), false), + ]; + for (final cupertino in [false, true]) { + for (final (label, run, visible) in cases) { + await tester.pumpWidget( + retryApp( + RetryHost( + key: ValueKey('$label-$cupertino'), + gateway: gateway, + initial: run, + changed: changed, + ), + cupertino: cupertino, + ), + ); + expect( + find.byKey(retryActionKey), + visible ? findsOneWidget : findsNothing, + reason: '$label cupertino=$cupertino', + ); + } + } + expect(gateway.calls, isEmpty); + expect(changed, isEmpty); + }); +} diff --git a/app/test/features/runs/actions/retry_resilience_test.dart b/app/test/features/runs/actions/retry_resilience_test.dart new file mode 100644 index 00000000..26053426 --- /dev/null +++ b/app/test/features/runs/actions/retry_resilience_test.dart @@ -0,0 +1,223 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/core/transport/connection_state.dart'; +import 'package:pipelines_app/features/runs/actions/retry_eligibility.dart'; +import 'package:pipelines_app/features/runs/actions/retry_wording.dart'; + +import 'retry_test_support.dart'; + +Future _openAndConfirm(WidgetTester tester) async { + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryConfirmKey)); +} + +void main() { + testWidgets('a refusal is shown at once and Keep does not wait for resync', ( + tester, + ) async { + const refusal = 'run 7 is still executing; wait for it to stop completely'; + final resync = Completer(); + final gateway = FakeRetryGateway((type, fields) { + if (type == 'retry_run') throw const ProtocolError(refusal); + return resync.future; + }); + final changed = []; + await pumpRetry(tester, gateway: gateway, changed: changed); + + await _openAndConfirm(tester); + await tester.pump(); + + expect(gateway.calls.map((call) => call.type), ['retry_run', 'get_run']); + expect(find.text(refusal), findsOneWidget); + expect(find.byKey(retryErrorKey), findsOneWidget); + expect( + tester.widget(find.byKey(retryKeepKey)).onPressed, + isNotNull, + ); + expect( + tester.widget(find.byKey(retryConfirmKey)).onPressed, + isNull, + ); + expect(changed, isEmpty); + + await tester.tap(find.byKey(retryKeepKey)); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsNothing); + + resync.complete({'run_detail': failedRun(status: 'succeeded')}); + await tester.pump(); + await tester.pump(); + + expect(tester.takeException(), isNull); + expect(changed.single['status'], 'succeeded'); + expect(find.byKey(retryActionKey), findsNothing); + }); + + testWidgets('server truth that is ineligible blocks a repeat action', ( + tester, + ) async { + const refusal = 'only failed runs can be retried'; + final finished = failedRun(status: 'succeeded'); + final gateway = FakeRetryGateway((type, fields) async { + if (type == 'retry_run') throw const ProtocolError(refusal); + return {'run_detail': finished}; + }); + final changed = []; + await pumpRetry(tester, gateway: gateway, changed: changed); + + await _openAndConfirm(tester); + await tester.pumpAndSettle(); + + expect(gateway.calls.map((call) => call.type), ['retry_run', 'get_run']); + expect(find.text(refusal), findsOneWidget); + expect( + tester.widget(find.byKey(retryConfirmKey)).onPressed, + isNull, + ); + expect( + tester.widget(find.byKey(retryKeepKey)).onPressed, + isNotNull, + ); + + await tester.tap(find.byKey(retryConfirmKey)); + await tester.pump(); + expect(gateway.calls.map((call) => call.type), ['retry_run', 'get_run']); + + await tester.tap(find.byKey(retryKeepKey)); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsNothing); + expect(find.byKey(retryActionKey), findsNothing); + expect(changed.single, equals(finished)); + expect(canRetryRun(changed.single), isFalse); + }); + + testWidgets('a failed recheck keeps the same key for the uncertain request', ( + tester, + ) async { + const refusal = 'connection dropped while retrying'; + var attempts = 0; + final gateway = FakeRetryGateway((type, fields) async { + if (type == 'get_run') throw const NotConnectedError(); + attempts += 1; + if (attempts == 1) throw const ProtocolError(refusal); + return {'run_detail': retriedRun()}; + }); + final changed = []; + await pumpRetry(tester, gateway: gateway, changed: changed); + + await _openAndConfirm(tester); + await tester.pumpAndSettle(); + + expect(find.text(refusal), findsOneWidget); + expect( + tester.widget(find.byKey(retryConfirmKey)).onPressed, + isNotNull, + ); + expect(gateway.retries, hasLength(1)); + + await tester.tap(find.byKey(retryConfirmKey)); + await tester.pumpAndSettle(); + + expect(gateway.retries, hasLength(2)); + expect( + gateway.retries.last.fields['request_key'], + gateway.retries.first.fields['request_key'], + ); + expect( + gateway.retries.every((call) => !call.fields.containsKey('retry_mode')), + isTrue, + ); + expect(changed.single, equals(retriedRun())); + expect(find.byType(AlertDialog), findsNothing); + }); + + testWidgets('a restart retry keeps the mode and key across uncertainty', ( + tester, + ) async { + var attempts = 0; + final gateway = FakeRetryGateway((type, fields) async { + if (type == 'get_run') throw const NotConnectedError(); + attempts += 1; + if (attempts == 1) throw const ProtocolError('network lost'); + return {'run_detail': retriedRun()}; + }); + await pumpRetry(tester, gateway: gateway, changed: []); + + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryRestartKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryConfirmKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryConfirmKey)); + await tester.pumpAndSettle(); + + expect(gateway.retries, hasLength(2)); + expect(gateway.retries.first.fields['retry_mode'], 'restart'); + expect(gateway.retries.last.fields['retry_mode'], 'restart'); + expect( + gateway.retries.last.fields['request_key'], + gateway.retries.first.fields['request_key'], + ); + }); + + testWidgets('a deliberate reopen sends a fresh request key', (tester) async { + final gateway = FakeRetryGateway((type, fields) async { + if (type == 'get_run') throw const NotConnectedError(); + throw const ProtocolError('server did not answer'); + }); + await pumpRetry(tester, gateway: gateway, changed: []); + + await _openAndConfirm(tester); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryKeepKey)); + await tester.pumpAndSettle(); + + await _openAndConfirm(tester); + await tester.pumpAndSettle(); + + expect(gateway.retries, hasLength(2)); + expect( + gateway.retries.first.fields['request_key'], + isNot(gateway.retries.last.fields['request_key']), + ); + }); + + testWidgets('a restart after a dismissed resume uses a fresh key', ( + tester, + ) async { + var attempts = 0; + final gateway = FakeRetryGateway((type, fields) async { + if (type == 'get_run') throw const NotConnectedError(); + attempts += 1; + if (attempts == 1) throw const ProtocolError('resume refused'); + return {'run_detail': retriedRun()}; + }); + await pumpRetry(tester, gateway: gateway, changed: []); + + await _openAndConfirm(tester); + await tester.pumpAndSettle(); + // A refusal leaves the prompt open; keep the mode frozen and dismiss. + await tester.tap(find.byKey(retryKeepKey)); + await tester.pumpAndSettle(); + + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryRestartKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryConfirmKey)); + await tester.pumpAndSettle(); + + expect(gateway.retries, hasLength(2)); + expect(gateway.retries.first.fields.containsKey('retry_mode'), isFalse); + expect(gateway.retries.last.fields['retry_mode'], 'restart'); + expect( + gateway.retries.first.fields['request_key'], + isNot(gateway.retries.last.fields['request_key']), + ); + }); +} diff --git a/app/test/features/runs/actions/retry_safety_test.dart b/app/test/features/runs/actions/retry_safety_test.dart new file mode 100644 index 00000000..df9e7e88 --- /dev/null +++ b/app/test/features/runs/actions/retry_safety_test.dart @@ -0,0 +1,133 @@ +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/core/transport/connection_state.dart'; +import 'package:pipelines_app/features/runs/actions/retry_wording.dart'; + +import 'retry_test_support.dart'; + +void main() { + testWidgets('confirm cannot submit twice while the retry is in flight', ( + tester, + ) async { + final reply = Completer(); + final gateway = FakeRetryGateway((type, fields) => reply.future); + final changed = []; + await pumpRetry(tester, gateway: gateway, changed: changed); + + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + final confirm = find.byKey(retryConfirmKey); + await tester.tap(confirm); + await tester.tap(confirm); + await tester.pump(); + + expect(gateway.retries, hasLength(1)); + expect( + tester.widget(find.byKey(retryConfirmKey)).onPressed, + isNull, + ); + expect( + tester.widget(find.byKey(retryKeepKey)).onPressed, + isNull, + ); + expect(find.byType(AlertDialog), findsOneWidget); + + reply.complete({'run_detail': retriedRun()}); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsNothing); + expect(changed, hasLength(1)); + }); + + testWidgets('a late retry reply after disposal is ignored safely', ( + tester, + ) async { + final reply = Completer(); + final gateway = FakeRetryGateway((type, fields) => reply.future); + final changed = []; + await pumpRetry(tester, gateway: gateway, changed: changed); + + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryConfirmKey)); + await tester.pump(); + expect(gateway.retries, hasLength(1)); + + await tester.pumpWidget(const SizedBox()); + reply.complete({'run_detail': retriedRun()}); + await tester.pump(); + + expect(tester.takeException(), isNull); + expect(changed, isEmpty); + }); + + testWidgets('a late resync after disposal is ignored safely', (tester) async { + final resync = Completer(); + final gateway = FakeRetryGateway((type, fields) { + if (type == 'retry_run') throw const ProtocolError('refused'); + return resync.future; + }); + final changed = []; + await pumpRetry(tester, gateway: gateway, changed: changed); + + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryConfirmKey)); + await tester.pump(); + expect(gateway.calls.map((call) => call.type), ['retry_run', 'get_run']); + + await tester.pumpWidget(const SizedBox()); + resync.complete({'run_detail': retriedRun()}); + await tester.pump(); + + expect(tester.takeException(), isNull); + expect(changed, isEmpty); + }); + + testWidgets('both confirmations fit 2x text at a narrow width', ( + tester, + ) async { + tester.view.physicalSize = const Size(320, 480); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + + for (final cupertino in [false, true]) { + final gateway = FakeRetryGateway( + (type, fields) async => {'run_detail': retriedRun()}, + ); + await pumpRetry( + tester, + gateway: gateway, + changed: [], + cupertino: cupertino, + textScale: 2, + ); + + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull, reason: 'cupertino=$cupertino'); + expect(find.text(retryDialogTitle(7)), findsOneWidget); + expect(find.text(retryDialogMessage), findsOneWidget); + expect( + cupertino + ? find.byType(CupertinoAlertDialog) + : find.byType(AlertDialog), + findsOneWidget, + ); + + await tester.tap(find.byKey(retryRestartKey)); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull, reason: 'restart=$cupertino'); + expect(find.text(restartDialogTitle(7)), findsOneWidget); + expect(find.text(restartDialogMessage), findsOneWidget); + + await tester.tap(find.byKey(retryKeepKey)); + await tester.pumpAndSettle(); + expect(gateway.calls, isEmpty); + } + }); +} diff --git a/app/test/features/runs/actions/retry_test_support.dart b/app/test/features/runs/actions/retry_test_support.dart new file mode 100644 index 00000000..67556d05 --- /dev/null +++ b/app/test/features/runs/actions/retry_test_support.dart @@ -0,0 +1,112 @@ +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_action.dart'; + +typedef RetryHandler = Future Function(String type, JsonMap fields); + +/// A fake gateway that records every request and never owns a socket. +class FakeRetryGateway implements ApiGateway { + FakeRetryGateway(this.handler); + + final RetryHandler handler; + final List<({String type, JsonMap fields})> calls = []; + + @override + Future call(String type, [JsonMap fields = const {}]) { + final copy = Map.from(fields); + calls.add((type: type, fields: copy)); + return handler(type, copy); + } + + @override + Stream get frames => const Stream.empty(); + + Iterable<({String type, JsonMap fields})> get retries => + calls.where((call) => call.type == 'retry_run'); +} + +JsonMap failedRun({ + num id = 7, + bool executing = false, + String status = 'failed', + String title = 'Nightly build', +}) => {'id': id, 'title': title, 'status': status, 'executing': executing}; + +JsonMap retriedRun({num id = 8}) => + failedRun(id: id, status: 'running', executing: true, title: 'Retry of 7'); + +/// Owns the run like a run-detail screen would, so the callback's returned +/// server detail is what the action renders next. +class RetryHost extends StatefulWidget { + const RetryHost({ + super.key, + required this.gateway, + required this.initial, + required this.changed, + }); + + final FakeRetryGateway gateway; + final JsonMap initial; + final List changed; + + @override + State createState() => _RetryHostState(); +} + +class _RetryHostState extends State { + late JsonMap _run = widget.initial; + + @override + Widget build(BuildContext context) { + return RetryRunAction( + run: _run, + gateway: widget.gateway, + onRunChanged: (run) { + widget.changed.add(run); + setState(() => _run = run); + }, + ); + } +} + +Widget retryApp(Widget child, {required bool cupertino, double textScale = 1}) { + Widget media(BuildContext context, Widget? app) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(textScale)), + child: app!, + ); + if (cupertino) { + return CupertinoApp( + builder: media, + home: CupertinoPageScaffold(child: Center(child: child)), + ); + } + return MaterialApp( + builder: media, + home: Scaffold(body: Center(child: child)), + ); +} + +Future pumpRetry( + WidgetTester tester, { + required FakeRetryGateway gateway, + required List changed, + bool cupertino = false, + double textScale = 1, + JsonMap? run, +}) async { + await tester.pumpWidget( + retryApp( + RetryHost( + gateway: gateway, + initial: run ?? failedRun(), + changed: changed, + ), + cupertino: cupertino, + textScale: textScale, + ), + ); +} From 9eb01b8f6a8dcbe27a60b618d264ecdf149c5ba8 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 15:20:36 +0100 Subject: [PATCH 02/18] docs(app): record schedule and retry landings plus 98-test integration check --- app/WORK.md | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/app/WORK.md b/app/WORK.md index ebafbaac..9d4dff9a 100644 --- a/app/WORK.md +++ b/app/WORK.md @@ -22,10 +22,12 @@ All work under app/. Existing applications remain running and unchanged. | X1 | Native search and result targets | run49 / flutter/x1-search | Code computed success; WAITING truncated2MiB export | held, review not reached | pending | | I1 | App-owned socket/session + live Runs shell registration | run50 / flutter/r1-native | Code computed success; WAITING truncated2MiB export | held, review not reached | not deployed | | E1 | Narrow authorized server export-bound fix | run53 / fix/session-export-limit | API v8, Flash; bounded export/repair regressions | pending | no service restart authorized by pipeline | -| R2c | Native retry/restart confirmation | run54 / flutter/r2-retry | Task v6, Flash; small independent action | pending | pending | +| R2c | Native retry/restart confirmation | run54 / commit178f22a | manager reran17 focused tests + analyze, pass; exact modes/stable intent keys checked | main804e531, ancestry verified | reusable only; wiring/browser pending | | R2d | Native rename-run dialog | run55 / commitf2643a0 | manager reran11 focused tests + analyze, pass; clean scoped diff | main3dde288, ancestry verified | reusable only; screen/list update wiring pending | -| S1a | Saved schedules repository/revision safety | run56 / flutter/s1-data | Task v6, Flash; nonvisual independent slice | pending | — | +| S1a | Saved schedules repository/revision safety | run56 / commitb963965 | manager reran18 focused tests + analyze, pass; revision/unknown field preservation checked | maina290858, ancestry verified | — | | T1a | Templates/validate/create-only requests | run57 / flutter/t1-data | Task v6, Flash; nonvisual independent slice | pending | — | +| S1b | Native read-only schedule list | run58 / flutter/s1-list | Task v6, Flash; separate from editor | pending | pending | +| P2a | Graph identities/recorded-visit model | run59 / flutter/p2-model | Task v6, Flash; separate from layout/rendering | pending | — | ## Next ready work - P1 pipelines list/detail/source/version; P2 graph and stage/visit selection. @@ -58,6 +60,10 @@ 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 +At804e531 manager ran the integrated main Flutter suite: 98tests passed and +flutter analyze was clean. These cover landed source/components only, not the +six unreviewed export-blocked feature branches or visible screen delivery. + ### Current delivery blocker — session export cap User asked about failed runs; explicit status inspection found runs34/37/39/42/ 49/50 are waiting, not failed: each Code visit1 computed success and is quiescent, From 22801a9b06d9c465460e6b0230f34c91916f64e0 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 15:26:29 +0100 Subject: [PATCH 03/18] fix(stage): align session export render cap with artifact bound Six computed Flutter runs stopped at the export handoff gate because the rendered session.html cap was 2 MiB while their complete sessions (well inside the 8 MiB source read bound) rendered between 2.25 and 4.28 MiB once html escaping and the readable projection duplicated native text. Raise SessionExportFileLimit to 8 MiB, the server's existing per-artifact file bound, so a complete export is still listed and served. Normal export verification, versioned repair and the handoff gate keep using the single shared constant. The source read bound is unchanged, and an over-cap render is still visibly truncated and recorded partial. Add focused regressions for a complete export above the old cap, an over-new-cap file rejected as partial, repair above the old cap leaving original evidence untouched, the gate accepting the larger repair, and the constant staying inside the artifact file bound. Update the artifact, handoff-gate and operations docs and record the diagnosis in docs/notes/session-export-render-cap.md. --- docs/notes/session-export-handoff-gate.md | 2 +- docs/notes/session-export-render-cap.md | 44 +++++++++++++ docs/stage-artifacts.md | 11 ++-- .../author/skill/references/operations.md | 7 ++- internal/server/session_export_gate_test.go | 50 +++++++++++++++ internal/server/session_export_repair_test.go | 51 +++++++++++++++ internal/server/session_export_status_test.go | 63 ++++++++++++++++++- internal/stage/session_export.go | 13 +++- internal/stage/session_export_test.go | 32 ++++++++++ 9 files changed, 261 insertions(+), 12 deletions(-) create mode 100644 docs/notes/session-export-render-cap.md diff --git a/docs/notes/session-export-handoff-gate.md b/docs/notes/session-export-handoff-gate.md index 6f09e72c..086d550a 100644 --- a/docs/notes/session-export-handoff-gate.md +++ b/docs/notes/session-export-handoff-gate.md @@ -73,7 +73,7 @@ retry and refresh of an already-open Session tab. Large (>256 KiB) API fixtures, wrong identity, partial/empty exports, restart, cancellation, workspace reservation, and exactly-once successor admission have focused regressions. A full ordinary artifact inventory no longer blocks versioned audit repair. -Repairs have a separate bounded allowance (twenty attempts, each at most 2 MiB), +Repairs have a separate bounded allowance (twenty attempts, each at most 8 MiB), so neither the ordinary inventory's file count nor its byte budget consumes the mandatory audit-recovery capacity. The ordinary scan limits remain unchanged. diff --git a/docs/notes/session-export-render-cap.md b/docs/notes/session-export-render-cap.md new file mode 100644 index 00000000..3ffd0b34 --- /dev/null +++ b/docs/notes/session-export-render-cap.md @@ -0,0 +1,44 @@ +# Session export: rendered-file cap aligned with the artifact bound + +## Problem + +Six computed Flutter runs (34, 37, 39, 42, 49, 50) reached Code visit 1 with a +successful, quiescent agent session but stopped at the export handoff gate. Each +recorded `session_export.status: partial`, `html_bytes: 2097152`, +`truncated: true`; the manual versioned repair of run 34 hit the same exact size. +The sessions had completed their computation, so a stage rerun was not the right +recovery. + +A read-only inspection of the recorded session rows showed the original native +data for those six sessions was between 1,083,391 and 2,111,470 bytes (the +complete HTTP export envelope for one of them was 2,126,449 bytes). All were +well inside the existing 8 MiB source read cap. The binding limit was the 2 MiB +rendered-file cap: html escaping and the readable projection keep native text +more than once, so an ordinary session can render larger than its source. +Re-exporting the six exact sessions read-only into scratch directories with the +new cap produced complete, untruncated files of 2,252,874 to 4,276,358 bytes. + +## Change + +`internal/stage/session_export.go` raises `SessionExportFileLimit` from 2 MiB to +8 MiB. That value is the same as the server's ordinary per-artifact file bound +(`maxArtifactFileBytes` in `internal/server/artifacts.go`), so a complete export +remains listed and served instead of being cut below the bound that the artifact +inventory already enforces. + +The source read remains capped by `SessionExportSourceLimit` (the single +`opencode.MaxSessionExport` value, 8 MiB). Normal export verification, versioned +export repair and the handoff gate all use `SessionExportFileLimit`, so they now +share one larger bound. The export still refuses to overwrite an existing file, +still marks any cut with a visible leading and trailing banner, and still reports +`truncated: true` and `status: partial`; nothing treats a partial export as +complete. + +## Checks + +Focused stage and server regressions cover a complete export above the old 2 MiB +cap but inside the new cap, a file above the new cap rejected as partial with the +verification diagnostic, repair accepting the larger complete file while the +original evidence stays unchanged, and the constant staying within the ordinary +artifact file bound. Focused stage/server suites and `go build ./...` plus +`go vet ./...` are run before landing; see the delivery report for exact results. diff --git a/docs/stage-artifacts.md b/docs/stage-artifacts.md index b29260d0..b2da6462 100644 --- a/docs/stage-artifacts.md +++ b/docs/stage-artifacts.md @@ -97,10 +97,13 @@ no special casing. `opencode session export `. Both reuse the same invocation helper and session-ID/messages validation as the transcript readback. The file is the harness's real session, never a reconstruction. -- Bounds: the source read is capped at 8 MiB and the rendered file at 2 MiB. When - either is cut, the file carries a visible truncation banner near the start and - the end and the step records `truncated: true`; a truncated export is never - described as whole. +- Bounds: the source read is capped at 8 MiB and the rendered file at 8 MiB, + matching the ordinary per-artifact file bound. The rendered file can exceed + its source because html escaping and the readable projection keep native text + more than once, so the previous 2 MiB render cap cut complete sessions that + were well inside the source bound. When either bound is exceeded, the file + carries a visible truncation banner near the start and the end and the step + records `truncated: true`; a truncated export is never described as whole. - Evidence: the step records `session_export` (`session_id`, `backend`, `source`, `html`, `html_bytes`, `messages`, `truncated`, `diagnostic`), so `pipelines inspect RUN_ID --json` shows what was written without reading the diff --git a/internal/author/skill/references/operations.md b/internal/author/skill/references/operations.md index 06a6013a..c67de23b 100644 --- a/internal/author/skill/references/operations.md +++ b/internal/author/skill/references/operations.md @@ -249,9 +249,10 @@ landed. presented. A run recorded before the HTML-only change still lists `session.md` among its stored artifacts (dated evidence kept on disk, not deleted); every listing — app, TUI, web spike — hides it rather than showing it beside the html. -- The source read is capped at 8 MiB and the rendered file at 2 MiB; a cut source or - a cut rendered file carries a visible truncation banner at both ends and - `session_export.truncated: true`, and a truncated export is never called whole. +- The source read is capped at 8 MiB and the rendered file at 8 MiB, matching the + ordinary per-artifact file bound; a cut source or a cut rendered file carries a + visible truncation banner at both ends and `session_export.truncated: true`, and + a truncated export is never called whole. - The step records `session_export` (`session_id`, `backend`, `source`, the html file name, `html_bytes`, `messages`, `truncated`, `diagnostic`) in `inspect RUN_ID --json`. A record written before the change still carried diff --git a/internal/server/session_export_gate_test.go b/internal/server/session_export_gate_test.go index a32a0943..3c9519c4 100644 --- a/internal/server/session_export_gate_test.go +++ b/internal/server/session_export_gate_test.go @@ -136,6 +136,56 @@ func TestSessionExportGateRetryOnlyAndExactlyOnce(t *testing.T) { } } +// TestSessionExportGateAcceptsRepairAboveOldRenderCap keeps the handoff gate's +// versioned-repair verification on the same larger bound as normal export. +func TestSessionExportGateAcceptsRepairAboveOldRenderCap(t *testing.T) { + h, s, id, first, second := gateRunner(t, func(context.Context, stage.SessionExportRequest) (stage.SessionExportResult, error) { + return stage.SessionExportResult{}, errors.New("export offline") + }, false) + h.runner.wg.Wait() + ctx := context.Background() + if err := s.ConfirmRecoveredSession(ctx, pipeline.SessionOwner{RunID: id, ID: "ses_exact"}); err != nil { + t.Fatal(err) + } + size := int64(2<<20) + 4096 + h.runner.exportSession = func(_ context.Context, req stage.SessionExportRequest) (stage.SessionExportResult, error) { + if err := os.MkdirAll(req.ArtifactsDir, 0700); err != nil { + return stage.SessionExportResult{}, err + } + f, err := os.Create(filepath.Join(req.ArtifactsDir, req.FileName)) + if err != nil { + return stage.SessionExportResult{}, err + } + if err := f.Truncate(size); err != nil { + f.Close() + return stage.SessionExportResult{}, err + } + if err := f.Close(); err != nil { + return stage.SessionExportResult{}, err + } + return stage.SessionExportResult{Source: "native_export", HTML: req.FileName, HTMLBytes: size, Messages: 2}, nil + } + if _, err := h.runner.repairSessionExport(ctx, id, 1); err != nil { + t.Fatal(err) + } + // The worker promotes a persisted complete repair before claiming a lease. + job, err := s.ClaimSessionExportJob(ctx, time.Now().Add(time.Second), time.Minute) + if err != nil { + t.Fatal(err) + } + if job != nil { + t.Fatalf("complete repair still claimed as a recovery job: %+v", job) + } + if err := h.runner.resumeExportGates(ctx); err != nil { + t.Fatal(err) + } + h.runner.wg.Wait() + d, _ := s.GetRun(ctx, id) + if first.Load() != 1 || second.Load() != 1 || d.Status != "succeeded" || len(d.Steps) != 2 { + t.Fatalf("large repair did not advance the gate: %+v (%d/%d)", d, first.Load(), second.Load()) + } +} + func TestSessionExportGateCleanupUnconfirmedDoesNotExportOrAdvance(t *testing.T) { var exports atomic.Int32 h, s, id, _, second := gateRunner(t, func(ctx context.Context, req stage.SessionExportRequest) (stage.SessionExportResult, error) { diff --git a/internal/server/session_export_repair_test.go b/internal/server/session_export_repair_test.go index 4c0d8252..c2aabf3a 100644 --- a/internal/server/session_export_repair_test.go +++ b/internal/server/session_export_repair_test.go @@ -111,6 +111,57 @@ func TestRuntimeSessionExportRepairPreservesOriginalAndUsesRecordedOwner(t *test } } +// TestRuntimeSessionExportRepairAcceptsAboveTheOldRenderCap proves a versioned +// repair uses the same larger bound as a normal export while leaving the +// original recorded evidence untouched. +func TestRuntimeSessionExportRepairAcceptsAboveTheOldRenderCap(t *testing.T) { + h, s, id := sessionExportRunner(t, "v2", func(stage.SessionExportRequest) (stage.SessionExportResult, error) { + return stage.SessionExportResult{}, errors.New("initial export unavailable") + }) + if err := s.ConfirmRecoveredSession(context.Background(), pipeline.SessionOwner{RunID: id, ID: "ses_run"}); err != nil { + t.Fatal(err) + } + original, err := s.GetRun(context.Background(), id) + if err != nil { + t.Fatal(err) + } + before, _ := json.Marshal(original.Steps[0].SessionExport) + size := int64(2<<20) + 4096 + h.runner.exportSession = func(_ context.Context, req stage.SessionExportRequest) (stage.SessionExportResult, error) { + if err := os.MkdirAll(req.ArtifactsDir, 0700); err != nil { + return stage.SessionExportResult{}, err + } + f, err := os.Create(filepath.Join(req.ArtifactsDir, req.FileName)) + if err != nil { + return stage.SessionExportResult{}, err + } + if err := f.Truncate(size); err != nil { + f.Close() + return stage.SessionExportResult{}, err + } + if err := f.Close(); err != nil { + return stage.SessionExportResult{}, err + } + return stage.SessionExportResult{Source: "native_export", HTML: req.FileName, HTMLBytes: size, Messages: 2}, nil + } + repaired, err := h.runner.repairSessionExport(context.Background(), id, 1) + if err != nil { + t.Fatal(err) + } + latest := repaired.Steps[0].SessionExportRepairs[0] + if latest.Status != "complete" || latest.HTMLBytes != size || latest.HTML == "" { + t.Fatalf("repair above the old cap was not complete: %+v", latest) + } + after, _ := json.Marshal(repaired.Steps[0].SessionExport) + if string(before) != string(after) { + t.Fatal("repair above the old cap overwrote original evidence") + } + info, err := os.Stat(filepath.Join(h.runner.artifactsRoot, "1", "stages", "01-"+repaired.Steps[0].Stage, latest.HTML)) + if err != nil || info.Size() != size { + t.Fatalf("repair file missing or resized: %v %+v", err, info) + } +} + func TestRuntimeRepairRejectsUnrecordedAndActiveVisits(t *testing.T) { h, _, id := sessionExportRunner(t, "v2", func(stage.SessionExportRequest) (stage.SessionExportResult, error) { return stage.SessionExportResult{}, errors.New("unavailable") diff --git a/internal/server/session_export_status_test.go b/internal/server/session_export_status_test.go index a1bae02a..10daae33 100644 --- a/internal/server/session_export_status_test.go +++ b/internal/server/session_export_status_test.go @@ -1,10 +1,13 @@ package server import ( - "git.a-wan.net/alan/pipelines/internal/protocol" "os" "path/filepath" + "strings" "testing" + + "git.a-wan.net/alan/pipelines/internal/protocol" + "git.a-wan.net/alan/pipelines/internal/stage" ) func TestSessionExportCompleteness(t *testing.T) { @@ -56,3 +59,61 @@ func TestRuntimeSessionExportFileVerificationDoesNotClaimMissingEvidence(t *test }) } } + +func sizedSessionFile(t *testing.T, size int64) string { + t.Helper() + dir := t.TempDir() + path := filepath.Join(dir, "session.html") + f, err := os.Create(path) + if err != nil { + t.Fatal(err) + } + if err := f.Truncate(size); err != nil { + f.Close() + t.Fatal(err) + } + if err := f.Close(); err != nil { + t.Fatal(err) + } + return dir +} + +// TestRuntimeSessionExportVerificationAcceptsAboveTheOldRenderCap pins the +// ordinary-session case the previous 2 MiB rendered bound cut. The file is +// larger than that old cap and inside the artifact-aligned bound, so normal +// export verification must keep it and classify the evidence complete. +func TestRuntimeSessionExportVerificationAcceptsAboveTheOldRenderCap(t *testing.T) { + size := int64(2<<20) + 4096 + dir := sizedSessionFile(t, size) + evidence := &protocol.SessionExport{Source: "native_export", Messages: 2, HTML: "session.html", HTMLBytes: size} + verifySessionExportFile(evidence, dir) + classifySessionExport(evidence) + if evidence.Status != "complete" || evidence.HTML != "session.html" || evidence.HTMLBytes != size || evidence.Diagnostic != "" { + t.Fatalf("complete export above the old cap was rejected: %+v", evidence) + } +} + +// TestRuntimeSessionExportVerificationRejectsAboveTheNewCap confirms the larger +// bound is still a hard bound: an oversized file is not presented as evidence. +func TestRuntimeSessionExportVerificationRejectsAboveTheNewCap(t *testing.T) { + size := int64(stage.SessionExportFileLimit) + 1 + dir := sizedSessionFile(t, size) + evidence := &protocol.SessionExport{Source: "native_export", Messages: 2, HTML: "session.html", HTMLBytes: size} + verifySessionExportFile(evidence, dir) + classifySessionExport(evidence) + if evidence.Status != "partial" || evidence.HTML != "" || evidence.HTMLBytes != 0 || !strings.Contains(evidence.Diagnostic, "bounded verification") { + t.Fatalf("oversized export was not rejected as partial: %+v", evidence) + } +} + +// TestSessionExportFileLimitStaysInsideArtifactBounds keeps the render cap +// principled: larger than the cap that cut ordinary sessions, and no larger +// than the ordinary per-artifact file bound that serves the file. +func TestSessionExportFileLimitStaysInsideArtifactBounds(t *testing.T) { + if stage.SessionExportFileLimit <= 2<<20 { + t.Fatalf("render cap %d did not grow beyond the old 2 MiB cutoff", stage.SessionExportFileLimit) + } + if stage.SessionExportFileLimit > maxArtifactFileBytes { + t.Fatalf("render cap %d exceeds the artifact file bound %d", stage.SessionExportFileLimit, maxArtifactFileBytes) + } +} diff --git a/internal/stage/session_export.go b/internal/stage/session_export.go index 583602dd..2c752c5c 100644 --- a/internal/stage/session_export.go +++ b/internal/stage/session_export.go @@ -20,7 +20,7 @@ import ( // artifacts directory as one html file so the existing artifact listing and // serving paths find it with no special casing. The source read is capped at // SessionExportSourceLimit and the rendered file at SessionExportFileLimit, so -// the export adds at most ~2 MiB per step, inside the artifact scan limits. +// the export stays inside the server's per-artifact file bound. const ( // SessionHTMLFile is the one session export a stage writes. SessionHTMLFile = "session.html" @@ -32,8 +32,15 @@ const ( // SessionExportSourceLimit is the native session read cap; it is the one // opencode.MaxSessionExport value, not a second copy. SessionExportSourceLimit = opencode.MaxSessionExport - SessionExportFileLimit = 2 << 20 - SessionExportTimeout = 10 * time.Second + // SessionExportFileLimit is the rendered file cap. Ordinary native sessions + // commonly render a little larger than their raw source because html escaping + // and the readable projection duplicate native text; the previous 2 MiB cap + // cut complete sessions that were well inside the source bound. This cap + // matches the server's per-artifact file bound (maxArtifactFileBytes in + // internal/server/artifacts.go), so a complete export remains listed and + // served while a genuinely oversized one is still visibly truncated. + SessionExportFileLimit = 8 << 20 + SessionExportTimeout = 10 * time.Second ) // SessionExportRequest names the stage session to export and the evidence the diff --git a/internal/stage/session_export_test.go b/internal/stage/session_export_test.go index 5db417fd..8cf2efe2 100644 --- a/internal/stage/session_export_test.go +++ b/internal/stage/session_export_test.go @@ -222,6 +222,38 @@ func TestExportSessionLargeHTTPExportWritesBoundedRealHTML(t *testing.T) { } } +// TestExportSessionCompletesAboveTheOldRenderedCap covers the ordinary case the +// previous 2 MiB render cap cut: a complete native session inside the 8 MiB +// source bound whose escaped html is larger than 2 MiB. +func TestExportSessionCompletesAboveTheOldRenderedCap(t *testing.T) { + const oldRenderCap = 2 << 20 + dir := t.TempDir() + line := "complete ordinary session line " + text := strings.Repeat(line, oldRenderCap/len(line)+1000) + body := `{"info":{"id":"ses_ok"},"messages":[{"info":{"id":"m1","role":"user"},"text":"` + text + `"}]}` + sessionCLI(t, "ses_ok", body) + result, err := ExportSession(context.Background(), sessionRequest(dir)) + if err != nil { + t.Fatal(err) + } + data, err := os.ReadFile(filepath.Join(dir, result.HTML)) + if err != nil { + t.Fatal(err) + } + if result.Truncated || result.Messages != 1 || result.HTMLBytes != int64(len(data)) { + t.Fatalf("complete export above the old cap was not recorded: %+v", result) + } + if len(data) <= oldRenderCap || len(data) > SessionExportFileLimit { + t.Fatalf("rendered size %d is not above the old cap and inside the new one", len(data)) + } + if strings.Contains(string(data), "TRUNCATED") { + t.Fatal("a complete export carried a truncation banner") + } + if !strings.Contains(string(data), "complete ordinary session line") { + t.Fatal("complete export lost its session text") + } +} + func TestExportSessionSourceTruncationIsLabelledNotWhole(t *testing.T) { session := opencode.ExportedSession{ ID: "ses_ok", From cd9ec62d28ffa24754330f3d5de1db0689797466 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 15:31:10 +0100 Subject: [PATCH 04/18] feat(app): add template catalogue and create-only submit repository Add the nonvisual templates data/domain slice: TemplateRepository over the shared ApiGateway for list_templates, validate and create-only submit, and TemplateEntry preserving every server field in a deeply read-only raw map. Re-include test/**/data/ in app/.gitignore so the mirroring tests are not silently dropped from a fresh checkout. Tests cover exact request shapes, source preservation, blank-name refusal, malformed replies, server refusals and immutability. --- app/.gitignore | 6 +- .../templates/data/template_repository.dart | 84 +++++++++ .../templates/domain/template_entry.dart | 63 +++++++ app/notes/T1a.md | 140 +++++++++++++++ .../templates/data/template_create_test.dart | 147 ++++++++++++++++ .../templates/data/template_list_test.dart | 165 ++++++++++++++++++ .../templates/data/template_test_support.dart | 47 +++++ 7 files changed, 651 insertions(+), 1 deletion(-) create mode 100644 app/lib/features/templates/data/template_repository.dart create mode 100644 app/lib/features/templates/domain/template_entry.dart create mode 100644 app/notes/T1a.md create mode 100644 app/test/features/templates/data/template_create_test.dart create mode 100644 app/test/features/templates/data/template_list_test.dart create mode 100644 app/test/features/templates/data/template_test_support.dart diff --git a/app/.gitignore b/app/.gitignore index 9f91cbac..ffe0bc2c 100644 --- a/app/.gitignore +++ b/app/.gitignore @@ -45,6 +45,10 @@ app.*.map.json /android/app/release # The repository ignores runtime data/ directories. Feature repository source -# is code, not runtime data, and must be included in fresh checkouts. +# and its mirroring tests are code, not runtime data, and must be included in +# fresh checkouts. The test negation is required too: without it every +# `test/**/data/` directory is silently dropped from the candidate. !/lib/**/data/ !/lib/**/data/** +!/test/**/data/ +!/test/**/data/** diff --git a/app/lib/features/templates/data/template_repository.dart b/app/lib/features/templates/data/template_repository.dart new file mode 100644 index 00000000..da56f5ea --- /dev/null +++ b/app/lib/features/templates/data/template_repository.dart @@ -0,0 +1,84 @@ +import '../../../core/api_gateway.dart'; +import '../domain/template_entry.dart'; + +/// A templates protocol refusal kept separate from transport errors; server +/// error envelopes are propagated unchanged by [ApiGateway]. +class TemplateRepositoryException implements Exception { + const TemplateRepositoryException(this.message); + final String message; + @override + String toString() => message; +} + +/// Template catalogue, definition validation and create-only submission over +/// the application's shared gateway. +/// +/// These are reads plus one explicit submit. No method publishes, runs, +/// overwrites or schedules a pipeline, so merely loading or validating a +/// template can never start work. +class TemplateRepository { + TemplateRepository(this._gateway); + final ApiGateway _gateway; + + /// The server's template catalogue, exactly as `list_templates` returns it. + /// A reply without a `templates` field is the older server answering with no + /// catalogue, which is an empty list rather than an error. + Future> listTemplates() async { + final reply = await _gateway.call('list_templates'); + final templates = reply['templates']; + if (templates == null) return const []; + if (templates is! List) { + throw const TemplateRepositoryException( + 'The server returned no template catalogue.', + ); + } + return List.unmodifiable( + templates.map((entry) { + if (entry is! Map) { + throw const TemplateRepositoryException( + 'The server returned a template that is not an object.', + ); + } + return TemplateEntry.fromJson(Map.from(entry)); + }), + ); + } + + /// Parses one definition source on the server (`validate`) and returns the + /// graph it produced. The source is sent byte-for-byte: no trimming, casing or + /// whitespace changes. A malformed definition rejects with the server's own + /// error; a reply without a graph is refused rather than reported as valid. + Future validate(String source) async { + final reply = await _gateway.call('validate', {'source': source}); + final graph = reply['graph']; + if (graph is! Map) { + throw const TemplateRepositoryException('The server returned no graph.'); + } + return Map.from(graph); + } + + /// Creates a new draft pipeline from [source] (`submit`), create-only. + /// + /// A blank name is refused locally before anything is sent, matching the + /// browser and Android clients; the name that is sent is trimmed. The source + /// is not changed. `create_only` is always true, so an existing pipeline can + /// never be overwritten, and no run is started. + Future submit(String name, String source) async { + final trimmed = name.trim(); + if (trimmed.isEmpty) { + throw const TemplateRepositoryException('Enter a pipeline name.'); + } + final reply = await _gateway.call('submit', { + 'name': trimmed, + 'source': source, + 'create_only': true, + }); + final detail = reply['detail']; + if (detail is! Map) { + throw const TemplateRepositoryException( + 'The server returned no pipeline detail.', + ); + } + return Map.from(detail); + } +} diff --git a/app/lib/features/templates/domain/template_entry.dart b/app/lib/features/templates/domain/template_entry.dart new file mode 100644 index 00000000..6c86bcbf --- /dev/null +++ b/app/lib/features/templates/domain/template_entry.dart @@ -0,0 +1,63 @@ +import '../../../core/api_gateway.dart'; + +/// One template from the server catalogue. +/// +/// The server owns this record: [key], [name], [description], [source] and +/// [scheduled] are read from it verbatim and every other field is kept in +/// [raw], so a later view or round-trip never loses fields this client does not +/// understand yet. Loading a template is a read; it never publishes or runs it. +class TemplateEntry { + const TemplateEntry({ + required this.key, + required this.name, + required this.description, + required this.source, + required this.scheduled, + required this.raw, + }); + + factory TemplateEntry.fromJson(JsonMap json) { + final raw = _frozenMap(json); + return TemplateEntry( + key: _text(raw['key']), + name: _text(raw['name']), + description: _text(raw['description']), + source: _text(raw['source']), + scheduled: raw['scheduled'] == true, + raw: raw, + ); + } + + /// The stable catalogue key the gallery selects on. + final String key; + final String name; + final String description; + + /// The template's complete, untrimmed definition source. + final String source; + + /// Whether the source declares a schedule (the summary's "Includes a schedule"). + final bool scheduled; + + /// Every field the server sent, including fields this client does not model. + /// Deeply unmodifiable: nested maps and lists are copied into read-only + /// collections too, so a view cannot mutate the server reply through it. + final JsonMap raw; + + static String _text(dynamic value) => value == null ? '' : '$value'; + + static JsonMap _frozenMap(Map json) => + Map.unmodifiable( + json.map((key, value) => MapEntry(key, _frozen(value))), + ); + + static dynamic _frozen(dynamic value) { + if (value is Map) { + return _frozenMap(Map.from(value)); + } + if (value is List) { + return List.unmodifiable(value.map(_frozen)); + } + return value; + } +} diff --git a/app/notes/T1a.md b/app/notes/T1a.md new file mode 100644 index 00000000..e8a39fc4 --- /dev/null +++ b/app/notes/T1a.md @@ -0,0 +1,140 @@ +# T1a — template catalogue, validate and create-only submit + +## What changed + +New nonvisual `templates` data/domain slice. One shared file was edited: +`app/.gitignore` re-includes `test/**/data/`, because the repository's runtime +`data/` rule was silently excluding this slice's tests from the candidate. No +other lane's work, `lib/main.dart`, shell, pubspec, `web/`, server or Android +file was touched. + +| File | Lines | Responsibility | +| --- | --- | --- | +| `lib/features/templates/domain/template_entry.dart` | 63 | Immutable server template; models key/name/description/source/scheduled and keeps every unknown field in deeply read-only `raw` | +| `lib/features/templates/data/template_repository.dart` | 84 | `TemplateRepository(ApiGateway)`: list, validate, create-only submit | +| `test/features/templates/data/template_test_support.dart` | 47 | Recording/refusing fake gateways, server-refusal error, Unicode source fixture | +| `test/features/templates/data/template_list_test.dart` | 165 | Catalogue request shape, field preservation, deep immutability, missing/malformed catalogue | +| `test/features/templates/data/template_create_test.dart` | 147 | Validate/submit envelopes, blank-name gate, missing payloads, verbatim refusals | +| `app/.gitignore` | +4 | Re-includes `test/**/data/` so test files enter the candidate | + +Nothing under `lib/main.dart`, `lib/shell/`, another feature, `pubspec.*`, +`web/`, the Go server or `android/` was changed. No dependency was added. + +## Review findings addressed + +- **Tests could never land (blocking).** `test/features/templates/data/` was + excluded by the repository root rule `data/`; `app/.gitignore` only re-included + `lib/**/data/`. The same negation now covers `test/**/data/`, so these three + test files are untracked-but-visible to git and `git add -n` succeeds. Fixing + the rule (rather than `git add -f`) also protects later `test/**/data/` lanes + such as S1a. No test was moved, so `test/` still mirrors `lib/`. +- **`raw` was only shallowly immutable (advisory).** `TemplateEntry.fromJson` + now deep-copies nested maps/lists into read-only collections, and the listed + test proves nested mutation throws and that the copy does not alias the reply. +- **Malformed-catalogue branches were untested (advisory).** Added tests for a + non-list `templates` value and a non-object catalogue entry, both rejecting + with explicit messages. +- `_text` still stringifies a non-string protocol value with `'$value'`; the + protocol only sends strings, and this matches how the browser would render + such a value, so the behaviour was left unchanged and is documented here + rather than claimed as strict parity. + +## Wire behaviour (mirrors `web/src/repository.js`) + +- `listTemplates()` sends exactly `{"type":"list_templates"}` with no fields and + returns the `templates` catalogue. A reply with no `templates` field is the + older server's empty catalogue (`?? []` in the browser), not a fake template. + Each entry keeps `key`, `name`, `description`, `source`, `scheduled` and all + unknown fields in `TemplateEntry.raw`; the reply list/maps are never mutated. + `raw` is a deep unmodifiable copy: nested unknown maps and lists are copied + into read-only collections, so neither the view nor a later caller can mutate + the server reply through it. +- `listTemplates()` rejects a malformed envelope instead of fabricating + entries: a non-list `templates` throws + `"The server returned no template catalogue."` and a non-object entry throws + `"The server returned a template that is not an object."`. The real server + cannot produce either, but a protocol mistake must not look like an empty or + half-populated catalogue. +- `validate(source)` sends exactly `{"type":"validate","source":}` and + returns the reply's `graph`. A reply without a graph throws + `TemplateRepositoryException("The server returned no graph.")` — the browser's + exact words — rather than reporting a valid definition. +- `submit(name, source)` sends exactly + `{"type":"submit","name":,"source":,"create_only":true}`. + A blank/whitespace-only name is refused locally with + `TemplateRepositoryException("Enter a pipeline name.")` and no gateway call is + made; the accepted name is trimmed. A reply without `detail` throws + `TemplateRepositoryException("The server returned no pipeline detail.")`. +- The source string is never trimmed, normalised or re-encoded: Unicode, tabs, + newlines and significant leading/trailing whitespace arrive unchanged. +- A server refusal is never caught or reworded by the repository. It reaches the + caller as the same gateway error object, so the server's own text is shown. +- The repository exposes only these three operations. It has no publish, run, + schedule or overwrite path, so loading or validating a template cannot start + work or mutate a retained pipeline. + +## Checks actually run + +``` +flutter pub get # Got dependencies +dart format lib/features/templates test/features/templates # clean +flutter analyze # No issues found! (0.9s) +flutter test test/features/templates # 13 passed +flutter test # 76 passed +flutter build web # ✓ Built build/web (15.5s) +git diff --check # clean +git check-ignore / git add -n # tests are no longer ignored +``` + +Tests are part of the candidate, not merely present on disk: + +``` +$ git add -n app/test/features/templates/data/template_list_test.dart \ + app/test/features/templates/data/template_create_test.dart \ + app/test/features/templates/data/template_test_support.dart +add 'app/test/features/templates/data/template_create_test.dart' +add 'app/test/features/templates/data/template_list_test.dart' +add 'app/test/features/templates/data/template_test_support.dart' +exit=0 + +$ git status --porcelain=v1 -uall + M app/.gitignore +?? app/lib/features/templates/data/template_repository.dart +?? app/lib/features/templates/domain/template_entry.dart +?? app/notes/T1a.md +?? app/test/features/templates/data/template_create_test.dart +?? app/test/features/templates/data/template_list_test.dart +?? app/test/features/templates/data/template_test_support.dart +``` + +Focused acceptance coverage: + +- exact `list_templates` request (no fields, one call) and preservation of + modelled plus unknown fields, including nested unknown data; +- listing does not mutate the reply's template list or entry maps; `raw` and + every nested map/list are read-only, and the copy does not alias the reply; +- missing catalogue -> empty list; malformed catalogue -> explicit refusal; +- blank/whitespace name -> refusal with zero gateway calls; +- Unicode/emoji, tab/newline and leading/trailing source whitespace preserved in + both `validate` and `submit`; submit sends only name, source and + `create_only: true`, with the name trimmed; +- missing `graph` and missing `detail` rejected with the browser's exact + messages, with no fabricated graph/detail; +- validate and submit server refusals surface as the identical error object, + not a wrapper. + +## Honest limits + +- **Not wired into a screen.** This branch has no templates screen and the task + owns data/domain only; the manager owns integration. No browser capture was + made because there is no rendered change in this slice. +- **Mobile unverified.** No Android/iOS build, emulator, ADB or device was used. + The code is plain Dart with no platform-specific code. +- No live server, template catalogue, validate call or submit/creation was + performed. All tests use local fake gateways with no socket, so no real + pipeline was created or run. +- No export-gate workaround, server change or service operation was made; the + pending export-cap fix remains another lane's scope. +- **Not committed.** The stage instruction says not to commit, push or deploy, + so the candidate above is uncommitted in the working tree even though the run + prompt asks to commit a reviewed candidate. Nothing was pushed or deployed. diff --git a/app/test/features/templates/data/template_create_test.dart b/app/test/features/templates/data/template_create_test.dart new file mode 100644 index 00000000..68b82c4b --- /dev/null +++ b/app/test/features/templates/data/template_create_test.dart @@ -0,0 +1,147 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/templates/data/template_repository.dart'; + +import 'template_test_support.dart'; + +void main() { + test( + 'validate sends the exact source and returns the server graph', + () async { + final graph = { + 'stages': [ + {'key': 'build', 'type': 'model'}, + ], + 'unknown_graph_field': true, + }; + final gateway = RecordingGateway([ + {'type': 'validated', 'graph': graph}, + ]); + + final result = await TemplateRepository(gateway).validate(source); + + expect(gateway.calls.single.type, 'validate'); + expect(gateway.calls.single.fields, {'source': source}); + expect(gateway.calls.single.fields['source'], source); + expect(result, graph); + }, + ); + + test( + 'validate rejects a reply without a graph instead of faking success', + () async { + for (final reply in [ + {'type': 'validated'}, + {'type': 'validated', 'graph': null}, + ]) { + final gateway = RecordingGateway([reply]); + + await expectLater( + TemplateRepository(gateway).validate(source), + throwsA( + isA().having( + (error) => error.message, + 'message', + 'The server returned no graph.', + ), + ), + ); + } + }, + ); + + test('validate propagates a server refusal verbatim', () async { + const refusal = ServerRefusal('invalid stage "añadir": unknown key'); + final gateway = RefusingGateway(refusal); + + await expectLater( + TemplateRepository(gateway).validate(source), + throwsA(same(refusal)), + ); + expect(gateway.calls, ['validate']); + }); + + test('submit refuses a blank name without sending anything', () async { + for (final name in ['', ' ', '\t\n']) { + final gateway = RecordingGateway([ + { + 'detail': {'id': 1}, + }, + ]); + + await expectLater( + TemplateRepository(gateway).submit(name, source), + throwsA( + isA().having( + (error) => error.message, + 'message', + 'Enter a pipeline name.', + ), + ), + ); + expect(gateway.calls, isEmpty); + } + }); + + test( + 'submit trims the name, preserves the source and is always create-only', + () async { + final detail = { + 'id': 9, + 'name': 'Release 2', + 'version': 1, + }; + final gateway = RecordingGateway([ + {'type': 'submitted', 'detail': detail}, + ]); + + final result = await TemplateRepository( + gateway, + ).submit(' Release 2 ', source); + + expect(gateway.calls.single.type, 'submit'); + expect(gateway.calls.single.fields, { + 'name': 'Release 2', + 'source': source, + 'create_only': true, + }); + expect(gateway.calls.single.fields.keys, [ + 'name', + 'source', + 'create_only', + ]); + expect(result, detail); + }, + ); + + test( + 'submit rejects a reply without a detail instead of faking success', + () async { + final gateway = RecordingGateway([ + {'type': 'submitted'}, + ]); + + await expectLater( + TemplateRepository(gateway).submit('Release', source), + throwsA( + isA().having( + (error) => error.message, + 'message', + 'The server returned no pipeline detail.', + ), + ), + ); + }, + ); + + test('submit propagates a server refusal verbatim', () async { + const refusal = ServerRefusal('a pipeline named "Release" already exists'); + final gateway = RefusingGateway(refusal); + + await expectLater( + TemplateRepository(gateway).submit(' Release ', source), + throwsA(same(refusal)), + ); + expect(gateway.calls, ['submit']); + }); +} diff --git a/app/test/features/templates/data/template_list_test.dart b/app/test/features/templates/data/template_list_test.dart new file mode 100644 index 00000000..63cd2e93 --- /dev/null +++ b/app/test/features/templates/data/template_list_test.dart @@ -0,0 +1,165 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/templates/data/template_repository.dart'; + +import 'template_test_support.dart'; + +void main() { + test( + 'list_templates sends only the type and preserves every field', + () async { + final catalogue = [ + { + 'key': 'release', + 'name': 'Release', + 'description': 'Ship a version', + 'source': source, + 'scheduled': true, + 'future_field': { + 'nested': [1, 2, 3], + }, + }, + { + 'key': 'blank', + 'name': '', + 'description': '', + 'source': 'name: empty', + 'scheduled': false, + }, + ]; + final gateway = RecordingGateway([ + {'templates': catalogue}, + ]); + + final entries = await TemplateRepository(gateway).listTemplates(); + + expect(gateway.calls, hasLength(1)); + expect(gateway.calls.single.type, 'list_templates'); + expect(gateway.calls.single.fields, isEmpty); + expect(entries, hasLength(2)); + expect(entries.first.key, 'release'); + expect(entries.first.name, 'Release'); + expect(entries.first.description, 'Ship a version'); + expect(entries.first.source, source); + expect(entries.first.scheduled, isTrue); + expect(entries.first.raw['future_field'], { + 'nested': [1, 2, 3], + }); + expect(entries.last.key, 'blank'); + expect(entries.last.scheduled, isFalse); + expect(entries.last.raw, isNot(contains('missing'))); + }, + ); + + test('list_templates leaves the server reply untouched', () async { + final first = { + 'key': 'one', + 'name': 'One', + 'source': source, + 'scheduled': true, + 'unknown': ['keep', 'me'], + }; + final reply = { + 'templates': [first], + 'usage': {'templates': 1}, + }; + final gateway = RecordingGateway([reply]); + + final entries = await TemplateRepository(gateway).listTemplates(); + + expect(reply['templates'], hasLength(1)); + expect(first, { + 'key': 'one', + 'name': 'One', + 'source': source, + 'scheduled': true, + 'unknown': ['keep', 'me'], + }); + expect(entries.single.raw['unknown'], ['keep', 'me']); + expect( + () => entries.single.raw['name'] = 'changed', + throwsUnsupportedError, + ); + expect(first['name'], 'One'); + }); + + test('list_templates freezes nested unknown data in raw', () async { + final nested = { + 'nested': [1, 2, 3], + }; + final gateway = RecordingGateway([ + { + 'templates': [ + { + 'key': 'one', + 'name': 'One', + 'source': source, + 'scheduled': true, + 'future_field': nested, + }, + ], + }, + ]); + + final entries = await TemplateRepository(gateway).listTemplates(); + final raw = entries.single.raw; + final future = raw['future_field'] as Map; + + expect(() => future['added'] = true, throwsUnsupportedError); + expect(() => (future['nested'] as List).add(4), throwsUnsupportedError); + expect(future['nested'], [1, 2, 3]); + // The unmodifiable copies do not alias the server reply either. + nested['added'] = true; + expect(raw['future_field'], isNot(contains('added'))); + }); + + test('list_templates rejects a catalogue that is not a list', () async { + final gateway = RecordingGateway([ + { + 'templates': {'key': 'not-a-list'}, + }, + ]); + + await expectLater( + TemplateRepository(gateway).listTemplates(), + throwsA( + isA().having( + (error) => error.message, + 'message', + 'The server returned no template catalogue.', + ), + ), + ); + }); + + test( + 'list_templates rejects a catalogue entry that is not an object', + () async { + final gateway = RecordingGateway([ + { + 'templates': ['not-an-entry'], + }, + ]); + + await expectLater( + TemplateRepository(gateway).listTemplates(), + throwsA( + isA().having( + (error) => error.message, + 'message', + 'The server returned a template that is not an object.', + ), + ), + ); + }, + ); + + test('list_templates treats a reply with no catalogue as empty', () async { + final gateway = RecordingGateway([{}]); + + final entries = await TemplateRepository(gateway).listTemplates(); + + expect(entries, isEmpty); + expect(gateway.calls.single.type, 'list_templates'); + }); +} diff --git a/app/test/features/templates/data/template_test_support.dart b/app/test/features/templates/data/template_test_support.dart new file mode 100644 index 00000000..f4f36500 --- /dev/null +++ b/app/test/features/templates/data/template_test_support.dart @@ -0,0 +1,47 @@ +import 'package:pipelines_app/core/api_gateway.dart'; + +/// A recording gateway: it captures every request and answers from [replies]. +class RecordingGateway implements ApiGateway { + RecordingGateway([List replies = const []]) + : _replies = [...replies]; + + final List _replies; + final List<({String type, JsonMap fields})> calls = []; + + @override + Future call(String type, [JsonMap fields = const {}]) async { + calls.add((type: type, fields: Map.from(fields))); + return _replies.removeAt(0); + } + + @override + Stream get frames => const Stream.empty(); +} + +/// A gateway that refuses every request with the same server error object. +class RefusingGateway implements ApiGateway { + RefusingGateway(this.refusal); + + final Object refusal; + final List calls = []; + + @override + Future call(String type, [JsonMap fields = const {}]) async { + calls.add(type); + throw refusal; + } + + @override + Stream get frames => const Stream.empty(); +} + +class ServerRefusal implements Exception { + const ServerRefusal(this.message); + final String message; + @override + String toString() => message; +} + +/// A source with Unicode, tabs, newlines and significant leading/trailing +/// whitespace: every request must carry it unchanged. +const source = ' name: "café"\n\tstages:\n - key: "añadir" 😀 \n'; From 2c105074aac8aea01d21593258aded6c4525ac5d Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 15:31:43 +0100 Subject: [PATCH 05/18] feat(app): add graph domain model for runs and definitions Pure-Dart graph foundation mirroring the current web client: terminal targets and labels, definition edges and nodes with web outcome ordering, recorded run evidence (visited stages, taken routes, current stage and live start), and sequence-ordered stage visit selection with clamping. No layout, widgets, screens or coordinates; fixtures cover linear, diamond, self-loop, repeated visits, mixed outcomes, terminals and missing/malformed evidence. --- .../graph/domain/graph_definition.dart | 152 ++++++++++++ .../features/graph/domain/graph_protocol.dart | 43 ++++ .../graph/domain/run_graph_state.dart | 124 ++++++++++ .../features/graph/domain/stage_visits.dart | 107 ++++++++ app/notes/P2a.md | 112 +++++++++ .../graph/domain/graph_definition_test.dart | 229 ++++++++++++++++++ .../features/graph/domain/graph_fixtures.dart | 96 ++++++++ .../graph/domain/graph_protocol_test.dart | 56 +++++ .../domain/run_graph_state_live_test.dart | 91 +++++++ .../graph/domain/run_graph_state_test.dart | 170 +++++++++++++ .../graph/domain/stage_visits_test.dart | 150 ++++++++++++ 11 files changed, 1330 insertions(+) create mode 100644 app/lib/features/graph/domain/graph_definition.dart create mode 100644 app/lib/features/graph/domain/graph_protocol.dart create mode 100644 app/lib/features/graph/domain/run_graph_state.dart create mode 100644 app/lib/features/graph/domain/stage_visits.dart create mode 100644 app/notes/P2a.md create mode 100644 app/test/features/graph/domain/graph_definition_test.dart create mode 100644 app/test/features/graph/domain/graph_fixtures.dart create mode 100644 app/test/features/graph/domain/graph_protocol_test.dart create mode 100644 app/test/features/graph/domain/run_graph_state_live_test.dart create mode 100644 app/test/features/graph/domain/run_graph_state_test.dart create mode 100644 app/test/features/graph/domain/stage_visits_test.dart diff --git a/app/lib/features/graph/domain/graph_definition.dart b/app/lib/features/graph/domain/graph_definition.dart new file mode 100644 index 00000000..60735fa9 --- /dev/null +++ b/app/lib/features/graph/domain/graph_definition.dart @@ -0,0 +1,152 @@ +import 'graph_protocol.dart'; + +/// The graph definition: nodes and edges declared by a pipeline, never the +/// evidence that a run executed them. Run evidence lives in +/// `run_graph_state.dart`; keeping the two shapes separate means a definition +/// can be drawn without claiming a visit happened. +/// +/// Mirrors `stageOutcomes`, `edgeLabel`, `graphEdges` and `nodeDisplayLabel` +/// from `web/src/graph.js` (and `web/src/runDetail.js`). Pure data only. + +/// Ordering priority: success first, error last, every other outcome +/// alphabetical in between (the web client's `outcomePriority`). +int _outcomePriority(String outcome) { + if (outcome == 'success') return 0; + if (outcome == 'error') return 2; + return 1; +} + +/// A stage's edge outcomes in the app's one stable order. +List stageOutcomes(dynamic stage) { + final edges = stage is Map ? stage['edges'] : null; + if (edges is! Map) return const []; + final outcomes = edges.keys.map((key) => '$key').toList(); + outcomes.sort((a, b) { + final priority = _outcomePriority(a) - _outcomePriority(b); + return priority != 0 ? priority : a.compareTo(b); + }); + return outcomes; +} + +/// The outcome label on an edge: `error*` for an implicit fallback error route. +String edgeLabel(dynamic stage, String outcome) { + final implicitFallback = stage is Map && stage['fallback_error'] == true; + return outcome == 'error' && implicitFallback ? 'error*' : outcome; +} + +/// One declared edge, in stable definition order. +class GraphEdge { + const GraphEdge({ + required this.id, + required this.source, + required this.outcome, + required this.target, + required this.label, + required this.fallback, + required this.knownTarget, + }); + + /// The 1-based id assigned in stable definition order (`Graph.edges()`). + final int id; + final String source; + final String outcome; + + /// The resolved target: `#` has already become `#success`/`#failure`. + final String target; + final String label; + + /// True only for the parser's implicit `error -> #failure` route. + final bool fallback; + + /// True when [target] is a terminal or a stage declared in this graph. + /// + /// An empty or unknown target is kept exactly as recorded, with this flag + /// false, so callers can show it honestly instead of inventing a node. + final bool knownTarget; + + bool get isTerminal => isTerminalTarget(target); +} + +/// One graph definition node: a declared stage, or a terminal the definition +/// routes to. +class GraphNode { + const GraphNode({required this.key, required this.terminal, this.stageIndex}); + + final String key; + final bool terminal; + + /// The node's stage declaration index, or null for a terminal. + final int? stageIndex; + + String get label => nodeDisplayLabel(key); + String get shortLabel => nodeLabel(key); +} + +List> _stages(dynamic graph) { + if (graph is! Map) return const >[]; + final stages = graph['stages']; + if (stages is! List) return const >[]; + return stages.whereType().map(Map.from).toList(); +} + +String _stageKey(Map stage) => '${stage['key'] ?? ''}'; + +/// Every definition edge in stable id order. +/// +/// Stages keep declaration order and each stage's outcomes use +/// [stageOutcomes]; ids are contiguous in that order. An absent (null) edge +/// value declares no edge and is skipped, while an empty or unknown target is +/// preserved with [GraphEdge.knownTarget] false. +List graphEdges(dynamic graph) { + final stages = _stages(graph); + final stageKeys = { + for (final stage in stages) + if (_stageKey(stage).isNotEmpty) _stageKey(stage), + }; + final result = []; + for (final stage in stages) { + final edges = stage['edges']; + if (edges is! Map) continue; + final source = _stageKey(stage); + for (final outcome in stageOutcomes(stage)) { + final raw = edges[outcome]; + if (raw == null) continue; + final target = resolveTarget(outcome, '$raw') ?? ''; + result.add( + GraphEdge( + id: result.length + 1, + source: source, + outcome: outcome, + target: target, + label: edgeLabel(stage, outcome), + fallback: outcome == 'error' && stage['fallback_error'] == true, + knownTarget: isTerminalTarget(target) || stageKeys.contains(target), + ), + ); + } + } + return result; +} + +/// The definition's nodes in declaration order. +/// +/// A stage key identifies one node even when it is declared twice; self edges +/// and loops therefore never duplicate identity. Terminal nodes are appended +/// failure first, then success, once any declared edge resolves to a terminal +/// (the same `hasTerminal` rule the web layout uses). They are still +/// definition nodes, not evidence that a run reached them. +List graphNodes(dynamic graph) { + final stages = _stages(graph); + final seen = {}; + final nodes = []; + for (var index = 0; index < stages.length; index += 1) { + final key = _stageKey(stages[index]); + if (key.isEmpty || !seen.add(key)) continue; + nodes.add(GraphNode(key: key, terminal: false, stageIndex: index)); + } + if (graphEdges(graph).any((edge) => edge.isTerminal)) { + nodes.add(const GraphNode(key: failureEnd, terminal: true)); + nodes.add(const GraphNode(key: successEnd, terminal: true)); + } + return nodes; +} diff --git a/app/lib/features/graph/domain/graph_protocol.dart b/app/lib/features/graph/domain/graph_protocol.dart new file mode 100644 index 00000000..a033884c --- /dev/null +++ b/app/lib/features/graph/domain/graph_protocol.dart @@ -0,0 +1,43 @@ +/// Protocol terminal targets and the labels the graph uses for them. +/// +/// Mirrors `web/src/protocol.js` (`SUCCESS_END`, `FAILURE_END`, +/// `isTerminal`, `resolveTarget`) and the label helpers in `web/src/graph.js`. +/// Pure Dart: no Flutter imports and no layout or rendering decisions. +library; + +/// The explicit success terminal (`Protocol.SUCCESS_END`). +const String successEnd = '#success'; + +/// The explicit failure terminal (`Protocol.FAILURE_END`). +const String failureEnd = '#failure'; + +/// True only for the two explicit terminal targets. +/// +/// A bare `#` is not itself terminal; [resolveTarget] turns it into one using +/// the outcome, exactly as the server and the web client do. +bool isTerminalTarget(String? target) => + target == successEnd || target == failureEnd; + +/// Mirrors `Protocol.resolveTarget`: a bare `#` is the outcome's terminal. +/// +/// Every other value is preserved verbatim, including an empty or unknown +/// stage key. A missing target stays null rather than becoming a terminal, so +/// a blank edge cannot fabricate a visit or a terminal node. +String? resolveTarget(String? outcome, String? target) { + if (target != '#') return target; + return outcome == 'error' ? failureEnd : successEnd; +} + +/// A graph node title: a stage keeps its key, a terminal reads Success/Failure. +String nodeDisplayLabel(String? key) { + if (key == successEnd) return 'Success'; + if (key == failureEnd) return 'Failure'; + return key ?? ''; +} + +/// The TUI-mirroring label: terminal targets are all caps. +String nodeLabel(String? key) { + if (key == successEnd) return 'SUCCESS'; + if (key == failureEnd) return 'FAILURE'; + return key ?? ''; +} diff --git a/app/lib/features/graph/domain/run_graph_state.dart b/app/lib/features/graph/domain/run_graph_state.dart new file mode 100644 index 00000000..ef3fb8be --- /dev/null +++ b/app/lib/features/graph/domain/run_graph_state.dart @@ -0,0 +1,124 @@ +import 'graph_protocol.dart'; + +/// Which stages and routes a run actually recorded. +/// +/// This is executed-route evidence, deliberately distinct from the graph +/// definition's nodes and edges. It mirrors `runGraphState` from +/// `web/src/runDetail.js` (Android `RunGraphState.from`): every recorded step's +/// stage is visited once in first-appearance order, a step with a non-blank +/// outcome and target contributes one deduplicated `source\0outcome\0target` +/// route, and only a resolved terminal is added by its target. A non-terminal +/// target is not visited until a step lands on it. +/// +/// The run map is the same detail produced by the runs feature; this helper +/// reads recorded steps and never folds live events a second time. +class RunGraphState { + RunGraphState({ + required List visitedStages, + required List takenRoutes, + required this.currentStage, + required this.executing, + required this.currentStageStartedAt, + }) : visitedStages = List.unmodifiable(visitedStages), + takenRoutes = List.unmodifiable(takenRoutes); + + /// Visited stage keys in first-appearance order, without duplicates. + final List visitedStages; + + /// Taken routes as `source\0outcome\0resolvedTarget`, in recorded order. + final List takenRoutes; + + /// The run's current stage, else the last recorded visit's stage, else null. + final String? currentStage; + final bool executing; + + /// The running visit's start for [currentStage], only while executing. + final String? currentStageStartedAt; + + bool isStageVisited(String key) => visitedStages.contains(key); + + /// True when a recorded visit took this definition route. The target is + /// resolved with the same `#` rule the definition edges use. + bool isRouteTaken(String source, String outcome, String target) { + final resolved = resolveTarget(outcome, target); + if (resolved == null || resolved.isEmpty) return false; + return takenRoutes.contains('$source\u0000$outcome\u0000$resolved'); + } + + /// The active stage for a live run, else null. A finished run has none. + String? get activeStage { + if (!executing || currentStage == null || currentStage!.isEmpty) { + return null; + } + return currentStage; + } +} + +List> _steps(dynamic run) { + if (run is! Map) return const >[]; + final steps = run['steps']; + if (steps is! List) return const >[]; + return steps.whereType().map(Map.from).toList(); +} + +String _text(dynamic value) => '${value ?? ''}'; + +/// Derives [RunGraphState] from one run detail map. +/// +/// Missing or malformed steps yield no visits and no routes; nothing is +/// fabricated from a missing capture. Repeated visits stay one identity per +/// stage, and self edges or loops never recurse. +RunGraphState runGraphState(dynamic run) { + final steps = _steps(run); + final visitedStages = []; + final seenStages = {}; + final takenRoutes = []; + final seenRoutes = {}; + + void visit(String? key) { + if (key == null || key.isEmpty || !seenStages.add(key)) return; + visitedStages.add(key); + } + + for (final step in steps) { + final stage = _text(step['stage']); + if (stage.isNotEmpty) visit(stage); + + final outcome = _text(step['outcome']); + final target = _text(step['target']); + if (outcome.trim().isEmpty || target.trim().isEmpty) continue; + + final resolved = resolveTarget(outcome, target); + if (resolved == null || resolved.isEmpty) continue; + final route = '$stage\u0000$outcome\u0000$resolved'; + if (seenRoutes.add(route)) takenRoutes.add(route); + if (isTerminalTarget(resolved)) visit(resolved); + } + + final lastStage = steps.isEmpty ? '' : _text(steps.last['stage']); + final rawCurrent = _text(run is Map ? run['current_stage'] : null); + final currentStage = rawCurrent.trim().isNotEmpty + ? rawCurrent + : (lastStage.trim().isNotEmpty ? lastStage : null); + final executing = run is Map && run['executing'] == true; + + String? currentStageStartedAt; + if (executing && currentStage != null) { + for (var index = steps.length - 1; index >= 0; index -= 1) { + final step = steps[index]; + if (_text(step['stage']) != currentStage) continue; + if (_text(step['status']) != 'running') continue; + final started = _text(step['started_at']); + if (started.trim().isNotEmpty) currentStageStartedAt = started; + break; + } + } + + return RunGraphState( + visitedStages: visitedStages, + takenRoutes: takenRoutes, + currentStage: currentStage, + executing: executing, + currentStageStartedAt: currentStageStartedAt, + ); +} diff --git a/app/lib/features/graph/domain/stage_visits.dart b/app/lib/features/graph/domain/stage_visits.dart new file mode 100644 index 00000000..4a546cfa --- /dev/null +++ b/app/lib/features/graph/domain/stage_visits.dart @@ -0,0 +1,107 @@ +import '../../../core/api_gateway.dart'; + +/// Recorded stage-visit selection, matching the web client's timeline and +/// stage pane. Visits are ordered by their recorded sequence, never by the +/// order a caller happens to pass them in; repeated visits to one stage stay +/// separate entries. Pure data: no widgets, layout or coordinates. + +int _sequenceOf(JsonMap step) { + final sequence = step['sequence']; + return sequence is num ? sequence.toInt() : 0; +} + +int _positiveVisit(dynamic control) { + if (control is! Map) return 0; + final visit = control['visit']; + if (visit is num) return visit > 0 ? visit.toInt() : 0; + return int.tryParse('${visit ?? ''}') ?? 0; +} + +/// The visit number a timeline row shows: the recorded `control.visit` when it +/// is positive, else the position within the stage's ordered visits. +int displayVisit(JsonMap step, int index) { + final recorded = _positiveVisit(step['control']); + return recorded > 0 ? recorded : index + 1; +} + +/// Clamps a visit index into `[0, count)`; an empty list yields 0. +int clampVisitIndex(int index, int count) { + if (count <= 0) return 0; + if (index < 0) return 0; + return index >= count ? count - 1 : index; +} + +List _ordered(List visits) { + final indexed = <({int position, JsonMap step})>[ + for (var index = 0; index < visits.length; index += 1) + (position: index, step: visits[index]), + ]; + indexed.sort((a, b) { + final bySequence = _sequenceOf(a.step).compareTo(_sequenceOf(b.step)); + return bySequence != 0 ? bySequence : a.position.compareTo(b.position); + }); + return [for (final entry in indexed) entry.step]; +} + +/// Every stage's recorded visits, ordered by sequence. +/// +/// The map keeps stage first-appearance order. Equal sequences keep their +/// recorded order (the web client's stable sort), and a stage with no recorded +/// visit is simply absent rather than present with a synthetic visit. +Map> visitsByStage(List steps) { + final grouped = >{}; + for (final step in steps) { + final stage = '${step['stage'] ?? ''}'; + grouped.putIfAbsent(stage, () => []).add(step); + } + return >{ + for (final entry in grouped.entries) entry.key: _ordered(entry.value), + }; +} + +/// One selected stage visit. [step] is null when the stage has no recorded +/// visit, so callers cannot mistake an absent capture for an execution. +class StageVisitSelection { + const StageVisitSelection({ + required this.stageKey, + required this.visits, + required this.index, + }); + + final String stageKey; + + /// The stage's visits ordered by sequence. + final List visits; + + /// The clamped index into [visits]; 0 when there are none. + final int index; + + bool get hasVisit => visits.isNotEmpty; + JsonMap? get step => hasVisit ? visits[index] : null; + int get visitNumber => step == null ? 0 : displayVisit(step!, index); + + /// True when an explicit requested index was clamped, so a caller can + /// correct its route exactly as the web stage route does. + bool correctedRequest(int? requested) => + requested != null && requested != index; +} + +/// Selects a stage's visit exactly as the web stage pane does. +/// +/// A null [visitIndex] means the stage's most recent recorded visit; an +/// out-of-range index is clamped to the last visit (negative values to the +/// first). A stage with no recorded visits returns [StageVisitSelection.step] +/// null instead of a fabricated visit. +StageVisitSelection selectStageVisit( + List steps, + String stageKey, { + int? visitIndex, +}) { + final visits = visitsByStage(steps)[stageKey] ?? const []; + final wanted = visitIndex ?? (visits.isEmpty ? 0 : visits.length - 1); + return StageVisitSelection( + stageKey: stageKey, + visits: visits, + index: clampVisitIndex(wanted, visits.length), + ); +} diff --git a/app/notes/P2a.md b/app/notes/P2a.md new file mode 100644 index 00000000..2e7d1e48 --- /dev/null +++ b/app/notes/P2a.md @@ -0,0 +1,112 @@ +# P2a — graph domain: nodes, edges, terminals, run evidence and stage visits + +## What changed + +New, app-only, pure-Dart files. No server, web client, legacy client, shell, +`main.dart`, pubspec, other feature or platform source was edited. + +| File | Lines | Responsibility | +| --- | --- | --- | +| `lib/features/graph/domain/graph_protocol.dart` | 43 | terminal constants, `resolveTarget`, terminal labels | +| `lib/features/graph/domain/graph_definition.dart` | 152 | outcome/edge order, definition edges, definition nodes | +| `lib/features/graph/domain/run_graph_state.dart` | 124 | recorded visited stages/routes, current-stage fallback, live start | +| `lib/features/graph/domain/stage_visits.dart` | 107 | sequence-ordered visits, display visit, clamped visit selection | +| `test/features/graph/domain/graph_fixtures.dart` | 96 | linear/diamond/self-loop/incomplete definitions and step fixtures | +| `test/features/graph/domain/graph_protocol_test.dart` | 56 | shorthand and terminal-label regressions | +| `test/features/graph/domain/graph_definition_test.dart` | 229 | edge order/ids, loops, duplicate keys, missing/unknown targets | +| `test/features/graph/domain/run_graph_state_test.dart` | 170 | linear/diamond/self-loop/repeated visits/outcomes/terminals/no evidence | +| `test/features/graph/domain/run_graph_state_live_test.dart` | 91 | current/last-stage fallback, live start, finished run | +| `test/features/graph/domain/stage_visits_test.dart` | 150 | repeated visits by sequence, latest default, clamping, absent visit | + +No layout, coordinates, widgets, styles or rendering were added. + +## Behavior copied from the current web client + +- **Terminals and `#`** (`web/src/protocol.js`): `#success`, `#failure`, + `isTerminal` only for the explicit keys, and `resolveTarget`: a bare `#` + becomes `#failure` for the `error` outcome and `#success` for every other + outcome. All other values are preserved verbatim, including `""` and unknown + stage keys. A missing target stays `null`, never a fabricated terminal. +- **Labels** (`web/src/graph.js`): `nodeDisplayLabel` gives `Success` / + `Failure` for graph nodes; `nodeLabel` gives the TUI-mirroring `SUCCESS` / + `FAILURE`. Stage keys are unchanged. +- **Definition edges** (`web/src/graph.js`): outcomes are success first, other + outcomes alphabetical, `error` last; stages keep declaration order; ids are + contiguous in that order; the label carries `error*` only when + `fallback_error` is true. A `null` edge value declares no edge and is + skipped. Empty/unknown targets are kept, with `knownTarget == false`. +- **Definition nodes** (`web/src/graph.js` `layoutGraph`): stage nodes keep + declaration order and one identity per key; terminal nodes are appended + failure then success once any declared edge resolves to a terminal. These + are definition nodes only, never run evidence. +- **Run evidence** (`web/src/runDetail.js` `runGraphState`): visited stages in + first-appearance order without duplicates; routes keyed + `source\0outcome\0resolvedTarget` without duplicates; only a resolved + terminal is visited by its target; a non-terminal target is not visited until + a step lands there. Current stage is `current_stage` when non-blank, else the + last recorded step's stage, else `null`. A start timestamp is read only while + executing, for a `running` visit of the current stage. +- **Visits** (`web/src/runDetail.js` `runTimeline`, `clampVisitIndex`, + `displayVisit`, and `web/src/app.js` stage routing): visits are grouped by + stage and ordered by recorded sequence with stable ties; the display visit + is a positive `control.visit`, else position + 1; no requested visit selects + the stage's most recent visit; an explicit index clamps to `[0, count)`; a + stage with no recorded visit yields `step == null`. + +The run map is the same detail the runs feature already holds; this slice only +reads `steps`, so it adds no second event fold. Live-event merging remains in +`lib/features/runs/domain/run_step_evidence.dart` and `run_events.dart`. + +## Honest edge handling + +- A missing/`null` definition edge produces no edge and no node. +- An empty or unknown target is returned as recorded, flagged `knownTarget: + false`; it never becomes a stage node or terminal and never produces a + visited stage. +- A blank recorded stage key is not turned into an empty visited identity. A + step with a blank outcome or target records no route and no terminal visit. +- Self edges and loops record one route and one node identity; nothing recurses. +- A stage with no recorded visits cannot be presented as visited: selection + exposes a null step rather than synthesizing one. + +## Checks actually run + +``` +flutter pub get +dart format lib/features/graph test/features/graph # 10 files, 0 changed after formatting +flutter test test/features/graph/domain # 41 passed +flutter analyze # No issues found! (0.8s) +flutter test # 139 passed +``` + +Focused coverage is the requested matrix: + +- **Linear**: plan -> build -> ship, contiguous ids, implicit `error*` + fallback, terminals. +- **Diamond**: fan-out/fan-in edges stay distinct and ordered; converging + routes do not merge. +- **Self loop**: `a/retry -> a` is one edge and one node identity; one run + self-loop is one route and one visited stage. +- **Repeated stage**: repeated visits remain separate ordered entries; visited + stage identity is not duplicated; repeated identical routes collapse. +- **Different outcomes**: success/approved/rejected routes to the same target + remain distinct. +- **Terminals**: bare `#` resolves by outcome, explicit terminals normalize, + labels are `SUCCESS`/`FAILURE`, mid-run targets do not fabricate visits. +- **Missing evidence**: null/absent/malformed steps and graphs yield empty + evidence, no terminals and no fabricated visits. + +## Honest limits + +- **No UI, layout or wiring.** This is deliberately the nonvisual foundation + slice; the native graph screen, layout, highlighting and interaction are + later work and are not claimed here. +- **No browser evidence.** A nonvisual pure-Dart change has no rendered + behavior to capture; no browser or screenshot check applies. +- **No live server or device used.** All tests use local fixtures. No run, + pipeline, schedule, workflow or service was created, changed or restarted. +- **Mobile unverified.** Only web-targeted Flutter tests and analysis ran; no + Android/iOS build, emulator, ADB or device. +- **Not committed, pushed or deployed.** The stage instruction for this visit + forbids commit/push/deploy, so the candidate remains as new untracked files + in the `flutter/p2-model` worktree for the manager to inspect and land. diff --git a/app/test/features/graph/domain/graph_definition_test.dart b/app/test/features/graph/domain/graph_definition_test.dart new file mode 100644 index 00000000..deb13d62 --- /dev/null +++ b/app/test/features/graph/domain/graph_definition_test.dart @@ -0,0 +1,229 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/graph/domain/graph_definition.dart'; +import 'package:pipelines_app/features/graph/domain/graph_protocol.dart'; + +import 'graph_fixtures.dart'; + +void main() { + group('outcome and edge order', () { + test('success first, other outcomes alphabetical, error last', () { + expect( + stageOutcomes( + stage( + 'a', + edges: { + 'error': '#', + 'rejected': 'a', + 'success': 'b', + 'approved': 'b', + 'retry': 'a', + }, + ), + ), + ['success', 'approved', 'rejected', 'retry', 'error'], + ); + expect(stageOutcomes({}), isEmpty); + expect(stageOutcomes(null), isEmpty); + }); + + test('edgeLabel marks only an implicit fallback error route', () { + expect( + edgeLabel({'fallback_error': true}, 'error'), + 'error*', + ); + expect( + edgeLabel({'fallback_error': false}, 'error'), + 'error', + ); + expect( + edgeLabel({'fallback_error': true}, 'success'), + 'success', + ); + expect(edgeLabel({}, 'rejected'), 'rejected'); + }); + }); + + group('linear definition', () { + test('edges keep stage and outcome order with contiguous ids', () { + final edges = graphEdges(linearGraph()); + expect(edges.map((edge) => edge.id), [1, 2, 3, 4, 5]); + expect(edges.map((edge) => edge.source), [ + 'plan', + 'plan', + 'build', + 'ship', + 'ship', + ]); + expect(edges.map((edge) => edge.outcome), [ + 'success', + 'error', + 'success', + 'success', + 'error', + ]); + expect(edges.map((edge) => edge.target), [ + 'build', + '#failure', + 'ship', + '#success', + '#failure', + ]); + expect(edges.map((edge) => edge.label), [ + 'success', + 'error*', + 'success', + 'success', + 'error', + ]); + expect(edges.where((edge) => edge.fallback).map((edge) => edge.id), [ + 2, + ]); + expect(edges.every((edge) => edge.knownTarget), isTrue); + }); + + test('nodes are declaration order plus failure then success terminals', () { + final nodes = graphNodes(linearGraph()); + expect(nodes.map((node) => node.key), [ + 'plan', + 'build', + 'ship', + failureEnd, + successEnd, + ]); + expect(nodes.map((node) => node.stageIndex), [0, 1, 2, null, null]); + expect(nodes.map((node) => node.terminal), [ + false, + false, + false, + true, + true, + ]); + expect(nodes[3].label, 'Failure'); + expect(nodes[3].shortLabel, 'FAILURE'); + expect(nodes[4].label, 'Success'); + expect(nodes[4].shortLabel, 'SUCCESS'); + }); + }); + + group('diamond definition', () { + test('keeps every converging edge distinct in stable order', () { + final edges = graphEdges(diamondGraph()); + expect( + edges.map((edge) => '${edge.source}/${edge.outcome}->${edge.target}'), + [ + 'a/success->b', + 'a/approved->c', + 'a/error->#failure', + 'b/success->d', + 'c/success->d', + 'd/success->#success', + ], + ); + expect(edges.every((edge) => edge.knownTarget), isTrue); + }); + }); + + group('self loops', () { + test('a self edge is one edge and never duplicates node identity', () { + final graph = selfLoopGraph(); + final edges = graphEdges(graph); + expect( + edges.map((edge) => '${edge.source}/${edge.outcome}->${edge.target}'), + [ + 'a/success->b', + 'a/retry->a', + 'b/success->#success', + 'b/error->#failure', + ], + ); + expect(edges[1].source, edges[1].target); + expect(edges[1].knownTarget, isTrue); + + final nodes = graphNodes(graph); + expect(nodes.map((node) => node.key), [ + 'a', + 'b', + failureEnd, + successEnd, + ]); + expect(nodes.where((node) => node.key == 'a'), hasLength(1)); + }); + + test( + 'a stage declared twice keeps one node and one set of edges per key', + () { + final graph = { + 'stages': [ + stage('a', edges: {'retry': 'a'}), + stage('a', edges: {'success': '#success'}), + ], + }; + expect(graphNodes(graph).map((node) => node.key), [ + 'a', + failureEnd, + successEnd, + ]); + // Both declarations are still definition data, with unique edge ids. + expect(graphEdges(graph).map((edge) => edge.id), [1, 2]); + }, + ); + }); + + group('missing and unknown targets', () { + test( + 'an absent edge declares nothing; empty and unknown targets stay honest', + () { + final edges = graphEdges(incompleteGraph()); + expect(edges.map((edge) => edge.id), [1, 2, 3, 4]); + expect(edges.map((edge) => edge.outcome), [ + 'blocked', + 'retry', + 'error', + 'success', + ]); + expect(edges[0].target, ''); + expect(edges[0].knownTarget, isFalse); + expect(edges[1].target, 'ghost'); + expect(edges[1].knownTarget, isFalse); + expect(edges[2].target, failureEnd); + expect(edges[2].fallback, isTrue); + expect(edges[3].target, successEnd); + }, + ); + + test('an unknown target does not become a node or a terminal', () { + final graph = { + 'stages': [ + stage('a', edges: {'retry': 'ghost'}), + ], + }; + expect(graphNodes(graph).map((node) => node.key), ['a']); + expect(graphEdges(graph).single.knownTarget, isFalse); + }); + + test('a graph with no stages has no nodes or edges', () { + expect(graphNodes({}), isEmpty); + expect(graphEdges({'stages': null}), isEmpty); + expect(graphNodes(null), isEmpty); + }); + }); + + test( + 'definition nodes ignore run evidence even when the graph map carries it', + () { + final graph = { + 'stages': [ + stage('a', edges: {'success': 'b'}), + stage('b'), + ], + 'steps': [ + step(sequence: 1, stage: 'a', outcome: 'success', target: 'b'), + ], + 'visited_stages': ['a', 'b'], + }; + final nodes = graphNodes(graph); + expect(nodes.map((node) => node.key), ['a', 'b']); + expect(nodes.every((node) => !node.terminal), isTrue); + }, + ); +} diff --git a/app/test/features/graph/domain/graph_fixtures.dart b/app/test/features/graph/domain/graph_fixtures.dart new file mode 100644 index 00000000..3a074221 --- /dev/null +++ b/app/test/features/graph/domain/graph_fixtures.dart @@ -0,0 +1,96 @@ +import 'package:pipelines_app/core/api_gateway.dart'; + +/// Small, server-shaped fixtures shared by the graph domain tests. + +JsonMap step({ + int sequence = 0, + String stage = '', + String status = 'completed', + String outcome = '', + String target = '', + String startedAt = '', + Map? control, +}) { + return { + 'sequence': sequence, + 'stage': stage, + 'status': status, + 'outcome': outcome, + 'target': target, + if (startedAt.isNotEmpty) 'started_at': startedAt, + 'control': ?control, + }; +} + +JsonMap stage( + String key, { + Map edges = const {}, + bool fallbackError = false, + String type = 'model', +}) { + return { + 'key': key, + 'type': type, + 'edges': edges, + if (fallbackError) 'fallback_error': true, + }; +} + +/// plan -> build -> ship, with an implicit failure fallback on plan and an +/// explicit terminal pair on ship. +JsonMap linearGraph() => { + 'stages': [ + stage( + 'plan', + edges: {'success': 'build', 'error': '#'}, + fallbackError: true, + ), + stage('build', edges: {'success': 'ship'}), + stage( + 'ship', + edges: {'success': '#success', 'error': '#failure'}, + ), + ], +}; + +/// a fans out to b/c and both converge on d. +JsonMap diamondGraph() => { + 'stages': [ + stage( + 'a', + edges: {'success': 'b', 'approved': 'c', 'error': '#'}, + fallbackError: true, + ), + stage('b', edges: {'success': 'd'}), + stage('c', edges: {'success': 'd'}), + stage('d', edges: {'success': '#success'}), + ], +}; + +/// a retries itself and can still succeed into b; terminal pair on b. +JsonMap selfLoopGraph() => { + 'stages': [ + stage('a', edges: {'success': 'b', 'retry': 'a'}), + stage( + 'b', + edges: {'success': '#success', 'error': '#failure'}, + ), + ], +}; + +/// A definition with an absent edge, an empty target and an unknown target. +JsonMap incompleteGraph() => { + 'stages': [ + stage( + 'a', + edges: { + 'success': null, + 'blocked': '', + 'retry': 'ghost', + 'error': '#', + }, + fallbackError: true, + ), + stage('b', edges: {'success': '#success'}), + ], +}; diff --git a/app/test/features/graph/domain/graph_protocol_test.dart b/app/test/features/graph/domain/graph_protocol_test.dart new file mode 100644 index 00000000..972fc77e --- /dev/null +++ b/app/test/features/graph/domain/graph_protocol_test.dart @@ -0,0 +1,56 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/graph/domain/graph_protocol.dart'; + +void main() { + group('terminal target normalization', () { + test('a bare # resolves by outcome exactly like the web protocol', () { + expect(resolveTarget('error', '#'), failureEnd); + expect(resolveTarget('success', '#'), successEnd); + expect(resolveTarget('approved', '#'), successEnd); + expect(resolveTarget('', '#'), successEnd); + }); + + test('explicit, empty and unknown targets are preserved verbatim', () { + expect(resolveTarget('success', successEnd), successEnd); + expect(resolveTarget('error', failureEnd), failureEnd); + expect(resolveTarget('success', 'review'), 'review'); + expect(resolveTarget('blocked', ''), ''); + expect(resolveTarget('retry', 'ghost'), 'ghost'); + expect(resolveTarget('success', ' #success'), ' #success'); + }); + + test( + 'a missing target stays missing instead of fabricating a terminal', + () { + expect(resolveTarget('success', null), isNull); + expect(resolveTarget(null, null), isNull); + }, + ); + + test('only the explicit terminal keys are terminals', () { + expect(isTerminalTarget(successEnd), isTrue); + expect(isTerminalTarget(failureEnd), isTrue); + expect(isTerminalTarget('#'), isFalse); + expect(isTerminalTarget('review'), isFalse); + expect(isTerminalTarget(''), isFalse); + expect(isTerminalTarget(null), isFalse); + }); + }); + + group('terminal labels', () { + test('TUI labels are SUCCESS and FAILURE', () { + expect(nodeLabel(successEnd), 'SUCCESS'); + expect(nodeLabel(failureEnd), 'FAILURE'); + expect(nodeLabel('implementer'), 'implementer'); + expect(nodeLabel(''), ''); + expect(nodeLabel(null), ''); + }); + + test('display labels title-case the terminals and keep stage keys', () { + expect(nodeDisplayLabel(successEnd), 'Success'); + expect(nodeDisplayLabel(failureEnd), 'Failure'); + expect(nodeDisplayLabel('implementer'), 'implementer'); + expect(nodeDisplayLabel(null), ''); + }); + }); +} diff --git a/app/test/features/graph/domain/run_graph_state_live_test.dart b/app/test/features/graph/domain/run_graph_state_live_test.dart new file mode 100644 index 00000000..18244107 --- /dev/null +++ b/app/test/features/graph/domain/run_graph_state_live_test.dart @@ -0,0 +1,91 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/graph/domain/run_graph_state.dart'; + +import 'graph_fixtures.dart'; + +void main() { + group('current stage fallback', () { + test('the run current stage wins over the last recorded visit', () { + final state = runGraphState({ + 'current_stage': 'committer', + 'steps': [step(sequence: 1, stage: 'review')], + }); + expect(state.currentStage, 'committer'); + }); + + test('a blank current stage falls back to the last visit, else null', () { + final fallback = runGraphState({ + 'current_stage': ' ', + 'steps': [ + step(sequence: 1, stage: 'a'), + step(sequence: 2, stage: 'b'), + ], + }); + expect(fallback.currentStage, 'b'); + + final blankLast = runGraphState({ + 'steps': [step(sequence: 1)], + }); + expect(blankLast.currentStage, isNull); + }); + }); + + group('active stage and start', () { + test('a live run exposes its running visit start', () { + final state = runGraphState({ + 'executing': true, + 'current_stage': 'review', + 'steps': [ + step( + sequence: 1, + stage: 'review', + status: 'running', + startedAt: '2026-01-01T00:00:00Z', + ), + ], + }); + expect(state.executing, isTrue); + expect(state.activeStage, 'review'); + expect(state.currentStageStartedAt, '2026-01-01T00:00:00Z'); + }); + + test('a finished run has no active stage or start', () { + final state = runGraphState({ + 'executing': false, + 'current_stage': 'review', + 'steps': [ + step( + sequence: 1, + stage: 'review', + status: 'running', + startedAt: '2026-01-01T00:00:00Z', + ), + ], + }); + expect(state.activeStage, isNull); + expect(state.currentStageStartedAt, isNull); + }); + + test('only an exact running status with a non-blank start is used', () { + final state = runGraphState({ + 'executing': true, + 'current_stage': 'review', + 'steps': [ + step( + sequence: 1, + stage: 'review', + status: 'Running', + startedAt: '2026-01-01T00:00:00Z', + ), + step( + sequence: 2, + stage: 'review', + status: 'running', + startedAt: ' ', + ), + ], + }); + expect(state.currentStageStartedAt, isNull); + }); + }); +} diff --git a/app/test/features/graph/domain/run_graph_state_test.dart b/app/test/features/graph/domain/run_graph_state_test.dart new file mode 100644 index 00000000..3af43777 --- /dev/null +++ b/app/test/features/graph/domain/run_graph_state_test.dart @@ -0,0 +1,170 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/graph/domain/graph_protocol.dart'; +import 'package:pipelines_app/features/graph/domain/run_graph_state.dart'; + +import 'graph_fixtures.dart'; + +void main() { + group('linear run evidence', () { + test('visits and routes follow the recorded visits', () { + final state = runGraphState({ + 'executing': false, + 'steps': [ + step(sequence: 1, stage: 'plan', outcome: 'success', target: 'build'), + step(sequence: 2, stage: 'build', outcome: 'success', target: 'ship'), + step( + sequence: 3, + stage: 'ship', + outcome: 'success', + target: '#success', + ), + ], + }); + expect(state.visitedStages, [ + 'plan', + 'build', + 'ship', + successEnd, + ]); + expect(state.takenRoutes, [ + 'plan\u0000success\u0000build', + 'build\u0000success\u0000ship', + 'ship\u0000success\u0000#success', + ]); + expect(state.currentStage, 'ship'); + expect(state.executing, isFalse); + expect(state.currentStageStartedAt, isNull); + expect(state.activeStage, isNull); + }); + }); + + group('diamond run evidence', () { + test('repeated visits keep one identity and loop routes stay distinct', () { + final state = runGraphState({ + 'executing': false, + 'steps': [ + step(sequence: 1, stage: 'a', outcome: 'success', target: 'b'), + step(sequence: 2, stage: 'b', outcome: 'success', target: 'd'), + step(sequence: 3, stage: 'd', outcome: 'rejected', target: 'b'), + step(sequence: 4, stage: 'b', outcome: 'success', target: 'd'), + step(sequence: 5, stage: 'd', outcome: 'success', target: '#success'), + ], + }); + expect(state.visitedStages, ['a', 'b', 'd', successEnd]); + expect(state.visitedStages.where((key) => key == 'b'), hasLength(1)); + expect(state.takenRoutes, [ + 'a\u0000success\u0000b', + 'b\u0000success\u0000d', + 'd\u0000rejected\u0000b', + 'd\u0000success\u0000#success', + ]); + }); + + test('different outcomes to the same target stay separate routes', () { + final state = runGraphState({ + 'executing': false, + 'steps': [ + step(sequence: 1, stage: 'a', outcome: 'success', target: 'b'), + step(sequence: 2, stage: 'a', outcome: 'approved', target: 'b'), + step(sequence: 3, stage: 'a', outcome: 'success', target: 'b'), + ], + }); + expect(state.visitedStages, ['a']); + expect(state.takenRoutes, [ + 'a\u0000success\u0000b', + 'a\u0000approved\u0000b', + ]); + }); + }); + + group('self edges', () { + test('a self edge is evidence, not a second visit or recursion', () { + final state = runGraphState({ + 'executing': false, + 'steps': [ + step(sequence: 1, stage: 'a', outcome: 'retry', target: 'a'), + step(sequence: 2, stage: 'a', outcome: 'success', target: 'b'), + ], + }); + expect(state.visitedStages, ['a']); + expect(state.takenRoutes, [ + 'a\u0000retry\u0000a', + 'a\u0000success\u0000b', + ]); + }); + }); + + group('terminals', () { + test('a bare # resolves to failure on error and success otherwise', () { + final failed = runGraphState({ + 'steps': [ + step(sequence: 1, stage: 'impl', outcome: 'error', target: '#'), + ], + }); + expect(failed.visitedStages, ['impl', failureEnd]); + expect(failed.visitedStages, isNot(contains(successEnd))); + expect(failed.isRouteTaken('impl', 'error', '#'), isTrue); + + final succeeded = runGraphState({ + 'steps': [ + step(sequence: 1, stage: 'impl', outcome: 'done', target: '#'), + ], + }); + expect(succeeded.visitedStages, ['impl', successEnd]); + expect(succeeded.visitedStages, isNot(contains(failureEnd))); + }); + + test('a non-terminal target is not visited until a step lands on it', () { + final state = runGraphState({ + 'steps': [ + step( + sequence: 1, + stage: 'impl', + outcome: 'success', + target: 'review', + ), + ], + }); + expect(state.visitedStages, ['impl']); + expect(state.isStageVisited('review'), isFalse); + expect(state.isRouteTaken('impl', 'success', 'review'), isTrue); + }); + + test('blank outcome or target records no route and no terminal visit', () { + final state = runGraphState({ + 'steps': [ + step(sequence: 1, stage: 'impl', outcome: 'success', target: ''), + step(sequence: 2, stage: 'impl', outcome: '', target: '#success'), + ], + }); + expect(state.visitedStages, ['impl']); + expect(state.takenRoutes, isEmpty); + }); + }); + + group('missing evidence', () { + test('absent run or steps fabricates no visits', () { + for (final run in [ + null, + {}, + {'steps': null}, + {'steps': []}, + ]) { + final state = runGraphState(run); + expect(state.visitedStages, isEmpty); + expect(state.takenRoutes, isEmpty); + expect(state.currentStage, isNull); + expect(state.executing, isFalse); + expect(state.currentStageStartedAt, isNull); + } + }); + + test('malformed step entries are ignored, not invented', () { + final state = runGraphState({ + 'steps': ['nope', 42, null], + }); + expect(state.visitedStages, isEmpty); + expect(state.takenRoutes, isEmpty); + }); + }); +} diff --git a/app/test/features/graph/domain/stage_visits_test.dart b/app/test/features/graph/domain/stage_visits_test.dart new file mode 100644 index 00000000..dcf77840 --- /dev/null +++ b/app/test/features/graph/domain/stage_visits_test.dart @@ -0,0 +1,150 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/graph/domain/stage_visits.dart'; + +import 'graph_fixtures.dart'; + +void main() { + group('ordered stage visits', () { + test('repeated visits are ordered by sequence, not input order', () { + final steps = [ + step( + sequence: 5, + stage: 'review', + outcome: 'rejected', + target: 'implementer', + control: {'visit': 2}, + ), + step(sequence: 3, stage: 'implementer'), + step( + sequence: 2, + stage: 'review', + outcome: 'success', + target: 'done', + control: {'visit': 1}, + ), + ].cast>(); + + final byStage = visitsByStage(steps); + expect(byStage.keys, ['review', 'implementer']); + expect(byStage['review']!.map((visit) => visit['sequence']), [2, 5]); + expect(byStage['review']!.map((visit) => visit['outcome']), [ + 'success', + 'rejected', + ]); + expect(displayVisit(byStage['review']![0], 0), 1); + expect(displayVisit(byStage['review']![1], 1), 2); + }); + + test('equal sequences keep their recorded order', () { + final steps = [ + step(sequence: 1, stage: 'a', outcome: 'first'), + step(sequence: 1, stage: 'a', outcome: 'second'), + ].cast>(); + expect( + visitsByStage(steps)['a']!.map((visit) => visit['outcome']), + ['first', 'second'], + ); + }); + + test('a missing control visit falls back to the position', () { + final steps = [ + step(sequence: 1, stage: 'a'), + step(sequence: 2, stage: 'a'), + ].cast>(); + final visits = visitsByStage(steps)['a']!; + expect(displayVisit(visits[0], 0), 1); + expect(displayVisit(visits[1], 1), 2); + }); + + test( + 'a non-positive or malformed control visit falls back to position', + () { + expect( + displayVisit(step(control: {'visit': 0}), 2), + 3, + ); + expect( + displayVisit(step(control: {'visit': -1}), 2), + 3, + ); + expect( + displayVisit(step(control: {'visit': '3'}), 0), + 3, + ); + expect(displayVisit(step(), 4), 5); + }, + ); + }); + + group('clamping', () { + test('keeps a valid index and handles an empty list', () { + expect(clampVisitIndex(0, 3), 0); + expect(clampVisitIndex(2, 3), 2); + expect(clampVisitIndex(99, 3), 2); + expect(clampVisitIndex(-4, 3), 0); + expect(clampVisitIndex(5, 0), 0); + }); + }); + + group('selection', () { + List> repeatedVisits() => [ + step(sequence: 5, stage: 'review', outcome: 'rejected'), + step(sequence: 2, stage: 'review', outcome: 'success'), + ].cast>(); + + test('no requested visit selects the stage most recent recorded visit', () { + final selection = selectStageVisit(repeatedVisits(), 'review'); + expect(selection.hasVisit, isTrue); + expect(selection.index, 1); + expect(selection.step!['sequence'], 5); + expect(selection.visitNumber, 2); + }); + + test('an explicit visit selects that recorded visit', () { + final selection = selectStageVisit( + repeatedVisits(), + 'review', + visitIndex: 0, + ); + expect(selection.step!['sequence'], 2); + expect(selection.visitNumber, 1); + }); + + test('out-of-range indexes clamp to the nearest recorded visit', () { + final late = selectStageVisit(repeatedVisits(), 'review', visitIndex: 99); + expect(late.index, 1); + expect(late.step!['sequence'], 5); + expect(late.correctedRequest(99), isTrue); + + final early = selectStageVisit( + repeatedVisits(), + 'review', + visitIndex: -4, + ); + expect(early.index, 0); + expect(early.step!['sequence'], 2); + expect(early.correctedRequest(-4), isTrue); + expect(early.correctedRequest(null), isFalse); + }); + + test('a stage with no recorded visit returns no fabricated step', () { + final selection = selectStageVisit(repeatedVisits(), 'never-ran'); + expect(selection.hasVisit, isFalse); + expect(selection.step, isNull); + expect(selection.index, 0); + expect(selection.visitNumber, 0); + + final empty = selectStageVisit(const >[], 'review'); + expect(empty.hasVisit, isFalse); + expect(empty.step, isNull); + }); + + test('an absent capture for one stage does not hide another stage', () { + final steps = [ + step(sequence: 1, stage: 'a', outcome: 'success', target: 'b'), + ].cast>(); + expect(selectStageVisit(steps, 'a').hasVisit, isTrue); + expect(selectStageVisit(steps, 'b').hasVisit, isFalse); + }); + }); +} From e8bde4f5787f8780d9ea6cf8770556721f35e5f8 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 15:32:21 +0100 Subject: [PATCH 06/18] docs(app): record verified export-fix landing and safe installation gate --- app/WORK.md | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/app/WORK.md b/app/WORK.md index 9d4dff9a..ce3293fe 100644 --- a/app/WORK.md +++ b/app/WORK.md @@ -21,7 +21,7 @@ All work under app/. Existing applications remain running and unchanged. | 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 | | X1 | Native search and result targets | run49 / flutter/x1-search | Code computed success; WAITING truncated2MiB export | held, review not reached | pending | | I1 | App-owned socket/session + live Runs shell registration | run50 / flutter/r1-native | Code computed success; WAITING truncated2MiB export | held, review not reached | not deployed | -| E1 | Narrow authorized server export-bound fix | run53 / fix/session-export-limit | API v8, Flash; bounded export/repair regressions | pending | no service restart authorized by pipeline | +| E1 | Narrow authorized server export-bound fix | run53 / commit22801a9 | manager reproduced landing-test env failure on unchanged main; full Go suite/build/vet pass with only test-process URL env unset | merged main, ancestry verified | NOT installed; operator restart approval/window pending | | R2c | Native retry/restart confirmation | run54 / commit178f22a | manager reran17 focused tests + analyze, pass; exact modes/stable intent keys checked | main804e531, ancestry verified | reusable only; wiring/browser pending | | R2d | Native rename-run dialog | run55 / commitf2643a0 | manager reran11 focused tests + analyze, pass; clean scoped diff | main3dde288, ancestry verified | reusable only; screen/list update wiring pending | | S1a | Saved schedules repository/revision safety | run56 / commitb963965 | manager reran18 focused tests + analyze, pass; revision/unknown field preservation checked | maina290858, ancestry verified | — | @@ -65,6 +65,22 @@ flutter analyze was clean. These cover landed source/components only, not the six unreviewed export-blocked feature branches or visible screen delivery. ### Current delivery blocker — session export cap +The fix is now merged: rendered file cap8MiB, source cap8MiB unchanged, within +ordinary artifact allowance. Pipeline read-only scratch exports of all six exact +sessions were complete at2.25–4.28MiB, establishing the fix is sufficient. +Run53 automatic delivery failed in pre-existing TestHumanRunAttentionNotification +because the test inherited the running service's PIPELINES_WEB_PUBLIC_URL. Manager +reproduced that same failure on unchanged main with a harmless example URL; no +notification source/test was edited. All packages pass on candidate with only that +test-process env var unset; build/vet/diff pass. Manager landed checked source +directly (no coding-stage replay), and refreshed installed managed Pipelines skill +from current source via go run ./cmd/pipelines skill install. +Installed server is unchanged. Deployment safety inspection found57/58/59 active; +no restart or binary replacement performed. Need explicit operator approval for +installation/restart after active work settles before exact export-only repairs. +Old CLI service status cannot resolve its expected launchd label; do not guess a +service or restart unrelated processes. Inspect authoritative supervisor first. + User asked about failed runs; explicit status inspection found runs34/37/39/42/ 49/50 are waiting, not failed: each Code visit1 computed success and is quiescent, but export is partial/truncated at exactly2097152 bytes. Exact recorded native From 4548d66235ee68660fbe0976c560e4764ccc5051 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 15:32:31 +0100 Subject: [PATCH 07/18] docs(app): record committed P2a candidate and merged main --- app/notes/P2a.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/app/notes/P2a.md b/app/notes/P2a.md index 2e7d1e48..9e15821f 100644 --- a/app/notes/P2a.md +++ b/app/notes/P2a.md @@ -107,6 +107,7 @@ Focused coverage is the requested matrix: pipeline, schedule, workflow or service was created, changed or restarted. - **Mobile unverified.** Only web-targeted Flutter tests and analysis ran; no Android/iOS build, emulator, ADB or device. -- **Not committed, pushed or deployed.** The stage instruction for this visit - forbids commit/push/deploy, so the candidate remains as new untracked files - in the `flutter/p2-model` worktree for the manager to inspect and land. +- **Committed, not deployed.** The reviewed slice is commit `2c10507` on + `flutter/p2-model`; the branch was then merged with current `main` (merge + `da48208`). No push, install, preview server or canonical-URL change was made + by this landing stage; server-side checks and the actual land follow. From 8ea892959aefee9aa6de96ac2fefcd65f9e3cd16 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 15:33:22 +0100 Subject: [PATCH 08/18] docs(app): record final P2a merge and landing state --- app/notes/P2a.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/app/notes/P2a.md b/app/notes/P2a.md index 9e15821f..a77dc77d 100644 --- a/app/notes/P2a.md +++ b/app/notes/P2a.md @@ -108,6 +108,7 @@ Focused coverage is the requested matrix: - **Mobile unverified.** Only web-targeted Flutter tests and analysis ran; no Android/iOS build, emulator, ADB or device. - **Committed, not deployed.** The reviewed slice is commit `2c10507` on - `flutter/p2-model`; the branch was then merged with current `main` (merge - `da48208`). No push, install, preview server or canonical-URL change was made - by this landing stage; server-side checks and the actual land follow. + `flutter/p2-model`; current `main` was merged in after review (final merge + `f07ada0`, which includes `main` `e8bde4f`). No push, install, preview server + or canonical-URL change was made by this landing stage; server-side checks and + the actual land follow. From 0bfbe706f42f43201b2c0978ca31b5239531fe75 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 15:35:43 +0100 Subject: [PATCH 09/18] docs(app): accept graph and template checks while preserving install window --- app/WORK.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/app/WORK.md b/app/WORK.md index ce3293fe..85aeab3b 100644 --- a/app/WORK.md +++ b/app/WORK.md @@ -25,9 +25,9 @@ All work under app/. Existing applications remain running and unchanged. | R2c | Native retry/restart confirmation | run54 / commit178f22a | manager reran17 focused tests + analyze, pass; exact modes/stable intent keys checked | main804e531, ancestry verified | reusable only; wiring/browser pending | | R2d | Native rename-run dialog | run55 / commitf2643a0 | manager reran11 focused tests + analyze, pass; clean scoped diff | main3dde288, ancestry verified | reusable only; screen/list update wiring pending | | S1a | Saved schedules repository/revision safety | run56 / commitb963965 | manager reran18 focused tests + analyze, pass; revision/unknown field preservation checked | maina290858, ancestry verified | — | -| T1a | Templates/validate/create-only requests | run57 / flutter/t1-data | Task v6, Flash; nonvisual independent slice | pending | — | +| T1a | Templates/validate/create-only requests | run57 / flutter/t1-data | manager reran13 focused tests + analyze, pass; exact create-only/source preservation checked | accepted for main | — | | S1b | Native read-only schedule list | run58 / flutter/s1-list | Task v6, Flash; separate from editor | pending | pending | -| P2a | Graph identities/recorded-visit model | run59 / flutter/p2-model | Task v6, Flash; separate from layout/rendering | pending | — | +| P2a | Graph identities/recorded-visit model | run59 / commit2c10507 | manager reran41 focused tests + analyze, pass; scoped 4 pure domain files | merged main, ancestry verified | no renderer/layout yet | ## Next ready work - P1 pipelines list/detail/source/version; P2 graph and stage/visit selection. @@ -80,6 +80,10 @@ no restart or binary replacement performed. Need explicit operator approval for installation/restart after active work settles before exact export-only repairs. Old CLI service status cannot resolve its expected launchd label; do not guess a service or restart unrelated processes. Inspect authoritative supervisor first. +Graph lane59 is finished/landed. New launches are temporarily held to allow a +quiescent installation window once operator restart approval arrives; native +schedule list58 continues, template data57 is finished/accepted. This is a +deployment dependency, not a reason to replay or discard completed feature work. User asked about failed runs; explicit status inspection found runs34/37/39/42/ 49/50 are waiting, not failed: each Code visit1 computed success and is quiescent, From edfd5ecb057ecf559965244098b94a4fb262e1ce Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 15:36:02 +0100 Subject: [PATCH 10/18] docs(app): confirm template request layer landed --- app/WORK.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/WORK.md b/app/WORK.md index 85aeab3b..835dd6fc 100644 --- a/app/WORK.md +++ b/app/WORK.md @@ -25,7 +25,7 @@ All work under app/. Existing applications remain running and unchanged. | R2c | Native retry/restart confirmation | run54 / commit178f22a | manager reran17 focused tests + analyze, pass; exact modes/stable intent keys checked | main804e531, ancestry verified | reusable only; wiring/browser pending | | R2d | Native rename-run dialog | run55 / commitf2643a0 | manager reran11 focused tests + analyze, pass; clean scoped diff | main3dde288, ancestry verified | reusable only; screen/list update wiring pending | | S1a | Saved schedules repository/revision safety | run56 / commitb963965 | manager reran18 focused tests + analyze, pass; revision/unknown field preservation checked | maina290858, ancestry verified | — | -| T1a | Templates/validate/create-only requests | run57 / flutter/t1-data | manager reran13 focused tests + analyze, pass; exact create-only/source preservation checked | accepted for main | — | +| T1a | Templates/validate/create-only requests | run57 / candidateef2f463 | manager reran13 focused tests + analyze, pass; exact create-only/source preservation checked | merged main, ancestry verified | — | | S1b | Native read-only schedule list | run58 / flutter/s1-list | Task v6, Flash; separate from editor | pending | pending | | P2a | Graph identities/recorded-visit model | run59 / commit2c10507 | manager reran41 focused tests + analyze, pass; scoped 4 pure domain files | merged main, ancestry verified | no renderer/layout yet | From 2f4d934458b66d6097cd51f35ee7d1fa48129be3 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 15:59:15 +0100 Subject: [PATCH 11/18] docs(app): prepare minimal export-only deployment and verified rollback --- app/WORK.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/app/WORK.md b/app/WORK.md index 835dd6fc..820b7bb3 100644 --- a/app/WORK.md +++ b/app/WORK.md @@ -80,6 +80,16 @@ no restart or binary replacement performed. Need explicit operator approval for installation/restart after active work settles before exact export-only repairs. Old CLI service status cannot resolve its expected launchd label; do not guess a service or restart unrelated processes. Inspect authoritative supervisor first. +Preparation completed after user asked what manager was doing: authoritative +launchd label is net.awan.pipelines.server (not old CLI's net.a-wan.pipelines), +running installed binary under ~/.local/share/pipelines/bin with original DB +and OpenCode endpoint retained. Built a deployment candidate from the exact +running9ee2e00 revision plus ONLY export fix22801a9: branch +deploy/export-limit-only, commitb4627e2. All six new export regressions pass on +that exact candidate. Staged binary in approved OpenCode temp directory is +pipelines-server-exportfix-b4627e2; rollback copy is +pipelines-server-before-exportfix-66779. Installed binary/launchd registration +remain untouched. This avoids deploying unrelated newer main changes. Graph lane59 is finished/landed. New launches are temporarily held to allow a quiescent installation window once operator restart approval arrives; native schedule list58 continues, template data57 is finished/accepted. This is a From 2227faad40c74e994d337d32511cd71dac5d1afb Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 16:08:22 +0100 Subject: [PATCH 12/18] docs(app): resolve export blocker and resume seven preserved feature reviews --- app/AGENTS.md | 1 + app/WORK.md | 40 +++++++++++++++++++++++++++++++--------- 2 files changed, 32 insertions(+), 9 deletions(-) diff --git a/app/AGENTS.md b/app/AGENTS.md index 7752342a..bee8f407 100644 --- a/app/AGENTS.md +++ b/app/AGENTS.md @@ -7,6 +7,7 @@ - Develop and test ONLY web now. No ADB, emulators, device changes, Android/iOS builds or installs. Keep source portable to all three targets. Explicitly report mobile as unverified. - Small cohesive files (aim below 250 lines; split by responsibility, not arbitrary fragments). Each task owns a directory and its tests. Do not edit another lane or root pubspec/main unless assigned. - Code quality is a delivery requirement. No minified implementations, silent capability fallbacks, fake data masking missing features, or workarounds that bypass the real defect. A pipeline success does not waive missing behavior, native controls, regression coverage or rendered evidence. Label incomplete work honestly and complete it before claiming parity. +- The manager drives authorized routine integration and recovery without repeatedly stopping for permission. Feature implementation stays in pipelines where appropriate; infrastructure blockers can be resolved directly within the user's authorized scope. Verify quiescence, preserve data and rollback, act, and report actual results. Ask only for genuinely new scope or unresolved destructive choices. ## Shared contract - `lib/core/api_gateway.dart`: `JsonMap` alias; `ApiGateway.call(type, [fields])` yields the entire decoded reply envelope; `frames` yields unsolicited server envelopes. Gateway owns request IDs. Do not put domain interpretation in transport. diff --git a/app/WORK.md b/app/WORK.md index 820b7bb3..9a843b90 100644 --- a/app/WORK.md +++ b/app/WORK.md @@ -12,21 +12,21 @@ All work under app/. Existing applications remain running and unchanged. | F3 | Run models, live event fold, actions | run 32 + 1515ebe | 11 regressions/analyze pass; 5 source files 105–226 lines | main 37d0823, ancestry verified | — | | F4 | Chat models, history/live fold, request facade | run 33 / flutter/f4-chat | pipeline passed; wire omissions carried into C1 | pending C1 adapter fixes | — | | F5 | Isolated authenticated web preview tooling | run 30 + ae352bb | 6 proxy fixtures incl auth/bytes/origin/idle sockets pass | main 160ab45, ancestry verified | http://127.0.0.1:8096/ | -| P1 | Pipeline list/detail/source/version browser | run34 / flutter/p1-pipelines | Code computed success; WAITING truncated2MiB export | held, review not reached | pending | -| C1 | Chat session browser and management | 35 →36 →42 / flutter/f4-chat | Code42 computed success; WAITING truncated2MiB export | held, final review not reached | pending | -| N1 | Connection settings/preferences | run37 / flutter/n1-settings | Code computed success; WAITING truncated2MiB export | held, review not reached | pending | +| P1 | Pipeline list/detail/source/version browser | run34 / flutter/p1-pipelines | original export repaired; Review resumed | pending review/landing | pending | +| C1 | Chat session browser and management | 35 →36 →42 / flutter/f4-chat | original export42 repaired; Review resumed | pending review/landing | pending | +| N1 | Connection settings/preferences | run37 / flutter/n1-settings | original export repaired; Review resumed | pending review/landing | pending | | R1 | Run list/detail/live timeline | controller43 + list48 + detail46 accepted | manager merged all three on flutter/r1-native; reran 25 combined tests + analyze, pass | candidate integrated, held for I1 | I1 run50 wiring + browser verification | -| D1 | Recorded changes/diff viewer | run39 / flutter/d1-diff-viewer | Code computed success; WAITING truncated2MiB export | held, review not reached | pending | +| D1 | Recorded changes/diff viewer | run39 / flutter/d1-diff-viewer | original export repaired; Review resumed | pending review/landing | 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 | -| X1 | Native search and result targets | run49 / flutter/x1-search | Code computed success; WAITING truncated2MiB export | held, review not reached | pending | -| I1 | App-owned socket/session + live Runs shell registration | run50 / flutter/r1-native | Code computed success; WAITING truncated2MiB export | held, review not reached | not deployed | -| E1 | Narrow authorized server export-bound fix | run53 / commit22801a9 | manager reproduced landing-test env failure on unchanged main; full Go suite/build/vet pass with only test-process URL env unset | merged main, ancestry verified | NOT installed; operator restart approval/window pending | +| X1 | Native search and result targets | run49 / flutter/x1-search | original export repaired; Review resumed | pending review/landing | pending | +| I1 | App-owned socket/session + live Runs shell registration | run50 / flutter/r1-native | original export repaired; Review resumed | pending review/landing | not deployed | +| 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 | | R2c | Native retry/restart confirmation | run54 / commit178f22a | manager reran17 focused tests + analyze, pass; exact modes/stable intent keys checked | main804e531, ancestry verified | reusable only; wiring/browser pending | | R2d | Native rename-run dialog | run55 / commitf2643a0 | manager reran11 focused tests + analyze, pass; clean scoped diff | main3dde288, ancestry verified | reusable only; screen/list update wiring pending | | S1a | Saved schedules repository/revision safety | run56 / commitb963965 | manager reran18 focused tests + analyze, pass; revision/unknown field preservation checked | maina290858, ancestry verified | — | | T1a | Templates/validate/create-only requests | run57 / candidateef2f463 | manager reran13 focused tests + analyze, pass; exact create-only/source preservation checked | merged main, ancestry verified | — | -| S1b | Native read-only schedule list | run58 / flutter/s1-list | Task v6, Flash; separate from editor | pending | pending | +| S1b | Native read-only schedule list | run58 / flutter/s1-list | original export repaired; Review resumed | pending review/landing | pending | | P2a | Graph identities/recorded-visit model | run59 / commit2c10507 | manager reran41 focused tests + analyze, pass; scoped 4 pure domain files | merged main, ancestry verified | no renderer/layout yet | ## Next ready work @@ -64,7 +64,29 @@ At804e531 manager ran the integrated main Flutter suite: 98tests passed and flutter analyze was clean. These cover landed source/components only, not the six unreviewed export-blocked feature branches or visible screen delivery. -### Current delivery blocker — session export cap +### Export blocker RESOLVED — direct manager recovery +User explicitly directed manager to perform routine unblock/install without +waiting for further decisions. Confirmed ZERO active runs and quiescent original +Code sessions, backed up SQLite via backup API plus installed binary/plist under +~/.local/share/pipelines/backups/exportfix-b4627e2 (private directory), atomically +replaced only the server binary and restarted exact launchd job +gui/501/net.awan.pipelines.server. No web/ntfy/OpenCode service was restarted. +Installed ping commit is b4627e29755c3496f5caee5a9c316d8bf24f0713; SHA256 +f70b4e17324262cf5275927c40f617838fefc0d9217946eeaf6d3a320c786fac. +Rollback binary remains saved, DB/session/workspaces untouched. + +Export-only repair of34/37/39/42/49/50/58 visit1 ALL returned complete, +untruncated, 2.25–4.28MiB. Original Code session IDs and output hashes match the +pre-install checkpoint, with one Code visit each; all seven moved to Review, +export_pending_sequence0. Evidence in approved OpenCode temp: +export-recovery-before.json, export-recovery-repair-results.json and +export-recovery-after.json. EOF/reset errors on old background waits were the +expected restart disconnect, NOT run failures. Reattached seven waits using a +private CLI built from the sameb4627e2 source; installed global CLI left alone. +No coding-stage replay, evidence overwrite or gate bypass. Network preview still +responds302 to protected login at http://10.0.0.249:8096/. Implementation/reviews +now proceed in parallel; the prior install-approval notes below are historical. + The fix is now merged: rendered file cap8MiB, source cap8MiB unchanged, within ordinary artifact allowance. Pipeline read-only scratch exports of all six exact sessions were complete at2.25–4.28MiB, establishing the fix is sufficient. From e219a4cfcd5d2ecf586f4d5c2a17d0fdebb3c901 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 16:13:33 +0100 Subject: [PATCH 13/18] docs(app): continue independent graph-layout and artifact-model lanes --- app/WORK.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/app/WORK.md b/app/WORK.md index 9a843b90..8b01ab70 100644 --- a/app/WORK.md +++ b/app/WORK.md @@ -28,6 +28,8 @@ All work under app/. Existing applications remain running and unchanged. | T1a | Templates/validate/create-only requests | run57 / candidateef2f463 | manager reran13 focused tests + analyze, pass; exact create-only/source preservation checked | merged main, ancestry verified | — | | S1b | Native read-only schedule list | run58 / flutter/s1-list | original export repaired; Review resumed | pending review/landing | pending | | P2a | Graph identities/recorded-visit model | run59 / commit2c10507 | manager reran41 focused tests + analyze, pass; scoped 4 pure domain files | merged main, ancestry verified | no renderer/layout yet | +| P2b | Content-sized graph node layout | run60 / flutter/p2-layout | Task v6, Flash; explicit measured extents, no fixed CSS dimensions | running | — | +| A1a | Artifact records/grouping/safe URL navigation | run61 / flutter/a1-data | Task v6, Flash; pure data/security fixtures | running | — | ## Next ready work - P1 pipelines list/detail/source/version; P2 graph and stage/visit selection. From c1f140bc78ae2aa6f5801afac16c1b76c89a5464 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 16:25:17 +0100 Subject: [PATCH 14/18] feat(app): add deterministic content-sized graph node layout Pure-Dart SCC ranking and column placement over the landed graph identities. Every extent and gap is caller supplied; missing measurements are rejected rather than defaulted. Focused tests cover linear, diamond, cycle, self-loop, disconnected, terminal, expanded-text and invalid-input cases. --- .../graph/layout/graph_node_layout.dart | 142 +++++++++++ .../features/graph/layout/graph_ranks.dart | 191 +++++++++++++++ .../features/graph/layout/layout_models.dart | 129 ++++++++++ app/notes/P2b.md | 100 ++++++++ .../layout/graph_layout_validation_test.dart | 96 ++++++++ .../graph/layout/graph_node_layout_test.dart | 228 ++++++++++++++++++ .../graph/layout/graph_ranks_test.dart | 116 +++++++++ .../graph/layout/layout_fixtures.dart | 102 ++++++++ 8 files changed, 1104 insertions(+) create mode 100644 app/lib/features/graph/layout/graph_node_layout.dart create mode 100644 app/lib/features/graph/layout/graph_ranks.dart create mode 100644 app/lib/features/graph/layout/layout_models.dart create mode 100644 app/notes/P2b.md create mode 100644 app/test/features/graph/layout/graph_layout_validation_test.dart create mode 100644 app/test/features/graph/layout/graph_node_layout_test.dart create mode 100644 app/test/features/graph/layout/graph_ranks_test.dart create mode 100644 app/test/features/graph/layout/layout_fixtures.dart diff --git a/app/lib/features/graph/layout/graph_node_layout.dart b/app/lib/features/graph/layout/graph_node_layout.dart new file mode 100644 index 00000000..767426ea --- /dev/null +++ b/app/lib/features/graph/layout/graph_node_layout.dart @@ -0,0 +1,142 @@ +import 'dart:math' as math; + +import '../domain/graph_definition.dart'; +import 'graph_ranks.dart'; +import 'layout_models.dart'; + +/// Places definition nodes in topological columns. +/// +/// Nodes keep definition order inside a rank, each column is as wide as its +/// widest measured node, and columns are top-aligned. A node is centred in its +/// column, so heterogeneous widths and text-expanded heights stay separated by +/// [GraphLayoutConfig.rowGap] inside a rank and [GraphLayoutConfig.columnGap] +/// between ranks. Nothing is clipped to a fixed box: the supplied measured +/// width and height are used verbatim and the returned bounds include them. +/// +/// [nodes] and [edges] normally come from `graphNodes`/`graphEdges`. Edges whose +/// source or target is not one of [nodes] are ignored, so an unknown target can +/// never invent a node. A measurement is required for every node; a missing one +/// is an error rather than a made-up size. Extra measurement entries are +/// ignored because they cannot become nodes. +GraphLayout layoutGraphNodes({ + required List nodes, + required List edges, + required Map extents, + required GraphLayoutConfig config, +}) { + _validateNodeKeys(nodes); + final ranks = assignGraphRanks(nodes, edges); + final measured = {}; + final missing = []; + for (final node in nodes) { + final extent = extents[node.key]; + if (extent == null) { + missing.add(node.key); + } else { + measured[node.key] = extent; + } + } + if (missing.isNotEmpty) { + throw ArgumentError.value( + missing, + 'extents', + 'missing measured extents for graph nodes', + ); + } + + final columns = List>.generate( + ranks.rankCount, + (_) => [], + ); + for (final node in nodes) { + columns[ranks.rankOf[node.key]!].add(node); + } + + final columnWidths = [ + for (final column in columns) + column.fold( + 0, + (width, node) => math.max(width, measured[node.key]!.width), + ), + ]; + final columnHeights = [ + for (final column in columns) + _columnHeight(column, measured, config.rowGap), + ]; + final columnX = []; + var nextX = config.padding; + for (var rank = 0; rank < columns.length; rank += 1) { + columnX.add(nextX); + nextX += columnWidths[rank]; + if (rank + 1 < columns.length) nextX += config.columnGap; + } + + final boxes = []; + for (var rank = 0; rank < columns.length; rank += 1) { + var nextY = config.padding; + for (final node in columns[rank]) { + final extent = measured[node.key]!; + boxes.add( + GraphNodeBox( + key: node.key, + terminal: node.terminal, + stageIndex: node.stageIndex, + rank: rank, + x: columnX[rank] + (columnWidths[rank] - extent.width) / 2, + y: nextY, + width: extent.width, + height: extent.height, + ), + ); + nextY += extent.height + config.rowGap; + } + } + + final width = + config.padding * 2 + + columnWidths.fold(0, (sum, column) => sum + column) + + config.columnGap * math.max(0, columns.length - 1); + final height = + config.padding * 2 + + columnHeights.fold( + 0, + (tallest, column) => math.max(tallest, column), + ); + + return GraphLayout( + nodes: boxes, + width: width, + height: height, + rankCount: ranks.rankCount, + ranks: ranks.rankOf, + ); +} + +void _validateNodeKeys(List nodes) { + final seen = {}; + for (final node in nodes) { + if (node.key.isEmpty) { + throw ArgumentError.value( + node.key, + 'nodes', + 'node key must not be empty', + ); + } + if (!seen.add(node.key)) { + throw ArgumentError.value(node.key, 'nodes', 'duplicate graph node key'); + } + } +} + +double _columnHeight( + List column, + Map measured, + double rowGap, +) { + if (column.isEmpty) return 0; + var height = 0.0; + for (final node in column) { + height += measured[node.key]!.height; + } + return height + rowGap * (column.length - 1); +} diff --git a/app/lib/features/graph/layout/graph_ranks.dart b/app/lib/features/graph/layout/graph_ranks.dart new file mode 100644 index 00000000..f7558db2 --- /dev/null +++ b/app/lib/features/graph/layout/graph_ranks.dart @@ -0,0 +1,191 @@ +import 'dart:collection'; +import 'dart:math' as math; + +import '../domain/graph_definition.dart'; + +/// Deterministic 0-based ranks for a graph definition's nodes. +/// +/// Ranks come from the condensation DAG: every strongly connected component +/// shares one rank, and a component sits one past its deepest predecessor +/// (longest path). Self loops and cycles therefore stay finite, a cycle's +/// members do not drift apart, and disconnected nodes stay at rank 0. Edges +/// whose endpoints are not definition nodes are ignored: an unknown target +/// never invents a node. +class GraphRanks { + GraphRanks({ + required Map rankOf, + required this.rankCount, + required List> components, + }) : rankOf = Map.unmodifiable(rankOf), + components = List.unmodifiable(>[ + for (final component in components) List.unmodifiable(component), + ]); + + /// Every definition key's rank, in definition order. + final Map rankOf; + + /// Number of distinct ranks, 0 for an empty node set. + final int rankCount; + + /// Strongly connected components as keys, each sorted by definition order and + /// the list sorted by its first member. + final List> components; +} + +/// One DFS frame for the iterative Tarjan walk. +class _Frame { + _Frame(this.node); + + final int node; + int nextChild = 0; +} + +/// Assigns ranks to exactly the supplied [nodes]. +/// +/// [edges] is read for ordering only; it never adds nodes. Duplicate edges are +/// harmless. The walk is iterative, so a deep chain cannot overflow the call +/// stack, and the work is linear in nodes plus edges. +GraphRanks assignGraphRanks(List nodes, List edges) { + final indexOf = {}; + for (var index = 0; index < nodes.length; index += 1) { + indexOf[nodes[index].key] = index; + } + + final adjacency = List>.generate(nodes.length, (_) => []); + final seenPairs = {}; + for (final edge in edges) { + final source = indexOf[edge.source]; + final target = indexOf[edge.target]; + if (source == null || target == null) continue; + if (!seenPairs.add(source * nodes.length + target)) continue; + adjacency[source].add(target); + } + + final components = _components(adjacency); + final componentOf = List.filled(nodes.length, -1); + for (var component = 0; component < components.length; component += 1) { + for (final node in components[component]) { + componentOf[node] = component; + } + } + + // Condensation edges and their indegrees. + final successors = List>.generate(components.length, (_) => {}); + final indegree = List.filled(components.length, 0); + for (var source = 0; source < adjacency.length; source += 1) { + final from = componentOf[source]; + for (final target in adjacency[source]) { + final to = componentOf[target]; + if (from == to) continue; + if (successors[from].add(to)) indegree[to] += 1; + } + } + + // Longest-path ranks over the condensation. Queue order only has to be a + // topological order; the resulting rank per component is unique. + final ranks = List.filled(components.length, 0); + final ready = ListQueue(); + for (var component = 0; component < components.length; component += 1) { + if (indegree[component] == 0) ready.add(component); + } + var settled = 0; + while (ready.isNotEmpty) { + final component = ready.removeFirst(); + settled += 1; + for (final next in successors[component]) { + ranks[next] = math.max(ranks[next], ranks[component] + 1); + indegree[next] -= 1; + if (indegree[next] == 0) ready.add(next); + } + } + if (settled != components.length) { + // The condensation cannot contain a cycle by construction; stop rather than + // return a silently truncated layout. + throw StateError('graph condensation was not acyclic'); + } + + final componentKeys = >[ + for (final component in components) + [for (final node in component) nodes[node].key], + ]; + final componentOrder = [ + for (var component = 0; component < components.length; component += 1) + component, + ]..sort((a, b) => components[a].first.compareTo(components[b].first)); + + final rankOf = {}; + var rankCount = 0; + for (var index = 0; index < nodes.length; index += 1) { + final rank = ranks[componentOf[index]]; + rankOf[nodes[index].key] = rank; + if (rank + 1 > rankCount) rankCount = rank + 1; + } + + return GraphRanks( + rankOf: rankOf, + rankCount: rankCount, + components: >[ + for (final component in componentOrder) componentKeys[component], + ], + ); +} + +/// Tarjan's strongly connected components, emitted sinks first. +/// +/// Iterative rather than recursive so a long chain cannot exhaust the stack. +/// Members are sorted by definition index, which keeps every output stable. +List> _components(List> adjacency) { + final discovery = List.filled(adjacency.length, -1); + final low = List.filled(adjacency.length, 0); + final onStack = List.filled(adjacency.length, false); + final stack = []; + final components = >[]; + var nextDiscovery = 0; + + for (var root = 0; root < adjacency.length; root += 1) { + if (discovery[root] != -1) continue; + discovery[root] = low[root] = nextDiscovery; + nextDiscovery += 1; + stack.add(root); + onStack[root] = true; + final callStack = <_Frame>[_Frame(root)]; + + while (callStack.isNotEmpty) { + final frame = callStack.last; + final node = frame.node; + if (frame.nextChild < adjacency[node].length) { + final child = adjacency[node][frame.nextChild]; + frame.nextChild += 1; + if (discovery[child] == -1) { + discovery[child] = low[child] = nextDiscovery; + nextDiscovery += 1; + stack.add(child); + onStack[child] = true; + callStack.add(_Frame(child)); + } else if (onStack[child]) { + low[node] = math.min(low[node], discovery[child]); + } + continue; + } + + callStack.removeLast(); + if (callStack.isNotEmpty) { + final parent = callStack.last.node; + low[parent] = math.min(low[parent], low[node]); + } + if (low[node] == discovery[node]) { + final component = []; + while (stack.isNotEmpty) { + final member = stack.removeLast(); + onStack[member] = false; + component.add(member); + if (member == node) break; + } + component.sort(); + components.add(component); + } + } + } + + return components; +} diff --git a/app/lib/features/graph/layout/layout_models.dart b/app/lib/features/graph/layout/layout_models.dart new file mode 100644 index 00000000..4a8dac4e --- /dev/null +++ b/app/lib/features/graph/layout/layout_models.dart @@ -0,0 +1,129 @@ +/// Pure geometry for a workflow graph's node layout. +/// +/// Every size and gap is supplied by the caller. The native renderer measures +/// each node after text layout (including the platform's text scaling), so this +/// library never assumes a node width, font, palette or device class. +/// +/// No Flutter imports: rectangles are plain numbers so the same result can be +/// built into widgets, a canvas or a test fixture. +library; + +void _requireFiniteNonNegative(String name, double value) { + if (!value.isFinite || value < 0) { + throw ArgumentError.value(value, name, 'must be finite and non-negative'); + } +} + +/// One caller-measured node extent, in logical pixels. +/// +/// A width or height may be zero for an empty label; the layout still keeps the +/// node separate from its neighbours through the configured gaps. +class NodeExtent { + NodeExtent({required this.width, required this.height}) { + _requireFiniteNonNegative('width', width); + _requireFiniteNonNegative('height', height); + } + + final double width; + final double height; +} + +/// The gaps a caller reserves around measured nodes. +/// +/// [columnGap] separates adjacent ranks, [rowGap] separates nodes sharing a +/// rank, and [padding] is the outer margin included in [GraphLayout] bounds. +class GraphLayoutConfig { + GraphLayoutConfig({ + required this.columnGap, + required this.rowGap, + this.padding = 0, + }) { + _requireFiniteNonNegative('columnGap', columnGap); + _requireFiniteNonNegative('rowGap', rowGap); + _requireFiniteNonNegative('padding', padding); + } + + final double columnGap; + final double rowGap; + final double padding; +} + +/// One placed node. +/// +/// [key], [terminal] and [stageIndex] are the definition node's own identity, +/// copied unchanged. [x]/[y] are the measured rectangle's top-left corner in +/// graph space and [rank] is its 0-based topological column. +class GraphNodeBox { + const GraphNodeBox({ + required this.key, + required this.terminal, + required this.stageIndex, + required this.rank, + required this.x, + required this.y, + required this.width, + required this.height, + }); + + final String key; + final bool terminal; + final int? stageIndex; + final int rank; + final double x; + final double y; + final double width; + final double height; + + double get right => x + width; + double get bottom => y + height; + + @override + bool operator ==(Object other) => + other is GraphNodeBox && + other.key == key && + other.terminal == terminal && + other.stageIndex == stageIndex && + other.rank == rank && + other.x == x && + other.y == y && + other.width == width && + other.height == height; + + @override + int get hashCode => + Object.hash(key, terminal, stageIndex, rank, x, y, width, height); +} + +/// An immutable node layout: every placed box plus the total graph bounds. +/// +/// [nodes] is ordered by rank first and definition order inside a rank; use +/// [ranks] or [nodeFor] for keyed lookup. [width] and [height] include the +/// caller's padding; every box's [right] and [bottom] stay inside them. +/// [ranks] exposes each definition key's 0-based rank; [rankCount] is the +/// number of columns (0 for an empty node set). +class GraphLayout { + GraphLayout({ + required List nodes, + required this.width, + required this.height, + required this.rankCount, + required Map ranks, + }) : nodes = List.unmodifiable(nodes), + ranks = Map.unmodifiable(ranks); + + final List nodes; + final Map ranks; + final double width; + final double height; + final int rankCount; + + bool get isEmpty => nodes.isEmpty; + + /// The placed box for [key], or null when the definition has no such node. + GraphNodeBox? nodeFor(String key) { + for (final node in nodes) { + if (node.key == key) return node; + } + return null; + } +} diff --git a/app/notes/P2b.md b/app/notes/P2b.md new file mode 100644 index 00000000..91d5e07a --- /dev/null +++ b/app/notes/P2b.md @@ -0,0 +1,100 @@ +# P2b — deterministic pure node layout + +## What changed + +New app-only, pure-Dart files. No existing file, server, web client, legacy +client, shell, `main.dart`, pubspec, other feature or platform source was edited. + +| File | Lines | Responsibility | +| --- | --- | --- | +| `lib/features/graph/layout/layout_models.dart` | 127 | measured extents, gap config, immutable node box, layout + ranks | +| `lib/features/graph/layout/graph_ranks.dart` | 191 | deterministic SCC ranks over the landed definition nodes/edges | +| `lib/features/graph/layout/graph_node_layout.dart` | 142 | column/row placement, bounds, validation | +| `test/features/graph/layout/layout_fixtures.dart` | 102 | shared definitions and measured extents | +| `test/features/graph/layout/graph_ranks_test.dart` | 116 | linear/diamond/cycle/self-loop/disconnected/unknown/long-chain ranks | +| `test/features/graph/layout/graph_node_layout_test.dart` | 224 | ordering, terminals, heterogeneous and expanded extents, bounds, determinism | +| `test/features/graph/layout/graph_layout_validation_test.dart` | 96 | empty input, missing/extra measurements, duplicate keys, invalid sizes | + +No layout widgets, painters, edge routing, styling or shell wiring were added. + +## Public API + +```dart +GraphRanks assignGraphRanks(List nodes, List edges); + +GraphLayout layoutGraphNodes({ + required List nodes, + required List edges, + required Map extents, + required GraphLayoutConfig config, +}); +``` + +`NodeExtent` is the caller's measured width/height after text layout. +`GraphLayoutConfig` takes `columnGap`, `rowGap` and an optional outer `padding`. +No node size, font, colour or device value is assumed in the library. + +`GraphLayout` returns an unmodifiable `nodes` list of `GraphNodeBox` +(`key`, `terminal`, `stageIndex`, `rank`, `x`, `y`, `width`, `height`), an +unmodifiable `ranks` map, `rankCount`, and total `width`/`height` including +padding. Node keys, terminal flags and stage indices are copied from the +landed `graphNodes` identities unchanged. + +## Ranking behavior + +Ranks are read from the definition supplied by the caller; the existing +`graphNodes`/`graphEdges` helpers remain the source of identities. + +- Iterative Tarjan strongly connected components (no recursion; a 2000-stage + chain is covered), then longest-path ranks over the condensation DAG. +- Every member of a cycle shares one rank, so cyclic routes cannot recurse or + push members apart. Self loops are internal supervision and add no rank. +- Disconnected stages and disconnected terminals stay at rank 0. +- Edges whose source or target is not a node are ignored. An unknown or empty + target never creates a node or a rank. +- Ranking is linear in nodes plus edges and stable for repeated input. + +## Placement behavior + +- One column per rank; nodes keep definition order inside a rank. +- A column is as wide as its widest measured node; columns are separated by + `columnGap` and top-aligned. +- Nodes are centred in their column and stacked with exactly `rowGap` between + measured boxes (centres are compared in the heterogeneous test). +- Supplied widths/heights are placed verbatim, so expanded text is never + clipped to a fixed box; growing the extents grows the total bounds. +- Bounds include every box: tests assert `right <= width` and + `bottom <= height` for every fixture. +- The result is immutable and identical for identical input. + +Measurements are required for every node; a missing key throws +`ArgumentError` rather than inventing a default size. Extra measurements are +ignored because they cannot become nodes. Duplicate/empty node keys, negative +or non-finite gaps and extents are rejected. + +## Checks actually run + +``` +flutter pub get +dart format lib/features/graph/layout test/features/graph/layout +flutter test test/features/graph/layout # 21 passed +flutter analyze # No issues found! +flutter test # 173 passed +git diff --check # clean +``` + +Tests cover linear, diamond, cycle, self-loop, disconnected, terminals, +unknown/empty targets, heterogeneous extents, 2.6x expanded text, determinism, +bounds and invalid input. + +## Honest limits + +- **Nodes only.** Edge routing, ports, labels, lanes, hit testing, selection + highlighting, painting and native controls are separate later items. +- **Not rendered.** A pure nonvisual slice has no browser behavior to capture; + no screenshot or browser check applies. +- **No server or device.** Tests use local fixtures only; no run, pipeline, + schedule, service, emulator, ADB, Android/iOS build or live chat was touched. +- **Mobile unverified.** Only web-targeted Flutter test/analyze ran. +- **Uncommitted candidate.** Per this stage's instruction the slice is left in + the worktree; no commit, push or deployment was made. diff --git a/app/test/features/graph/layout/graph_layout_validation_test.dart b/app/test/features/graph/layout/graph_layout_validation_test.dart new file mode 100644 index 00000000..dd70f7ee --- /dev/null +++ b/app/test/features/graph/layout/graph_layout_validation_test.dart @@ -0,0 +1,96 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/graph/domain/graph_definition.dart'; +import 'package:pipelines_app/features/graph/layout/graph_node_layout.dart'; +import 'package:pipelines_app/features/graph/layout/layout_models.dart'; + +import 'layout_fixtures.dart'; + +/// Invalid and boundary input for the pure layout engine. +void main() { + test('an empty definition yields empty padded bounds', () { + final layout = layoutGraphNodes( + nodes: const [], + edges: const [], + extents: const {}, + config: layoutConfig(columnGap: 30, rowGap: 10, padding: 6), + ); + + expect(layout.isEmpty, isTrue); + expect(layout.rankCount, 0); + expect(layout.width, 12); + expect(layout.height, 12); + expect(layout.ranks, isEmpty); + }); + + test('missing measurements are reported rather than invented', () { + final graph = linearGraphFixture(); + final nodes = graphNodes(graph); + final extents = uniformExtents(nodes)..remove('build'); + + expect( + () => layoutGraphNodes( + nodes: nodes, + edges: graphEdges(graph), + extents: extents, + config: layoutConfig(), + ), + throwsArgumentError, + ); + }); + + test('extra measurements are ignored because they cannot become nodes', () { + final graph = linearGraphFixture(); + final nodes = graphNodes(graph); + final extents = uniformExtents(nodes) + ..['ghost'] = NodeExtent(width: 20, height: 20); + + final layout = layoutGraphNodes( + nodes: nodes, + edges: graphEdges(graph), + extents: extents, + config: layoutConfig(), + ); + + expect(layout.nodeFor('ghost'), isNull); + expect(layout.nodes.length, nodes.length); + }); + + test('duplicate or empty node keys are rejected', () { + const stageNode = GraphNode(key: 'a', terminal: false, stageIndex: 0); + expect( + () => layoutGraphNodes( + nodes: const [stageNode, stageNode], + edges: const [], + extents: {'a': NodeExtent(width: 10, height: 10)}, + config: layoutConfig(), + ), + throwsArgumentError, + ); + expect( + () => layoutGraphNodes( + nodes: const [ + GraphNode(key: '', terminal: false, stageIndex: 0), + ], + edges: const [], + extents: const {}, + config: layoutConfig(), + ), + throwsArgumentError, + ); + }); + + test('invalid gaps and extents are rejected', () { + expect( + () => GraphLayoutConfig(columnGap: -1, rowGap: 8), + throwsArgumentError, + ); + expect( + () => GraphLayoutConfig(columnGap: 8, rowGap: double.nan), + throwsArgumentError, + ); + expect( + () => NodeExtent(width: double.infinity, height: 10), + throwsArgumentError, + ); + }); +} diff --git a/app/test/features/graph/layout/graph_node_layout_test.dart b/app/test/features/graph/layout/graph_node_layout_test.dart new file mode 100644 index 00000000..bbaf2408 --- /dev/null +++ b/app/test/features/graph/layout/graph_node_layout_test.dart @@ -0,0 +1,228 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/graph/domain/graph_definition.dart'; +import 'package:pipelines_app/features/graph/domain/graph_protocol.dart'; +import 'package:pipelines_app/features/graph/layout/graph_node_layout.dart'; +import 'package:pipelines_app/features/graph/layout/layout_models.dart'; + +import 'layout_fixtures.dart'; + +GraphLayout _layout( + Map graph, { + Map? extents, + GraphLayoutConfig? config, +}) { + final nodes = graphNodes(graph); + return layoutGraphNodes( + nodes: nodes, + edges: graphEdges(graph), + extents: extents ?? uniformExtents(nodes), + config: config ?? layoutConfig(), + ); +} + +void _expectWithinBounds(GraphLayout layout) { + for (final box in layout.nodes) { + expect(box.x, greaterThanOrEqualTo(0), reason: '${box.key} left'); + expect(box.y, greaterThanOrEqualTo(0), reason: '${box.key} top'); + expect( + box.right, + lessThanOrEqualTo(layout.width), + reason: '${box.key} right inside width', + ); + expect( + box.bottom, + lessThanOrEqualTo(layout.height), + reason: '${box.key} bottom inside height', + ); + } +} + +void _expectSeparated(GraphLayout layout) { + for (var first = 0; first < layout.nodes.length; first += 1) { + for (var second = first + 1; second < layout.nodes.length; second += 1) { + final a = layout.nodes[first]; + final b = layout.nodes[second]; + final separated = + a.right <= b.x || + b.right <= a.x || + a.bottom <= b.y || + b.bottom <= a.y; + expect(separated, isTrue, reason: '${a.key} overlaps ${b.key}'); + } + } +} + +void main() { + test('linear nodes keep declaration order and terminal identity', () { + final layout = _layout(linearGraphFixture()); + + expect(layout.rankCount, 4); + expect(layout.nodes.map((box) => box.key), [ + 'plan', + 'build', + 'ship', + failureEnd, + successEnd, + ]); + expect(layout.ranks, { + 'plan': 0, + 'build': 1, + 'ship': 2, + failureEnd: 3, + successEnd: 3, + }); + expect(layout.nodeFor('plan')!.stageIndex, 0); + expect(layout.nodeFor('build')!.stageIndex, 1); + expect(layout.nodeFor('ship')!.stageIndex, 2); + expect(layout.nodeFor(failureEnd)!.terminal, isTrue); + expect(layout.nodeFor(failureEnd)!.stageIndex, isNull); + expect(layout.nodeFor(successEnd)!.terminal, isTrue); + expect( + layout.nodeFor(successEnd)!.y - layout.nodeFor(failureEnd)!.bottom, + layoutConfig().rowGap, + ); + expect(layout.nodeFor(failureEnd)!.x, layout.nodeFor(successEnd)!.x); + expect(layout.nodeFor('plan')!.x, layoutConfig().padding); + expect(layout.nodeFor('plan')!.y, layoutConfig().padding); + expect( + layout.nodeFor('build')!.x - layout.nodeFor('plan')!.right, + layoutConfig().columnGap, + ); + expect(layout.width, 560); + expect(layout.height, 140); + _expectWithinBounds(layout); + _expectSeparated(layout); + }); + + test('diamond ranks place siblings in one column', () { + final layout = _layout(diamondGraphFixture()); + + final b = layout.nodeFor('b')!; + final c = layout.nodeFor('c')!; + expect(b.rank, 1); + expect(c.rank, 1); + expect(b.x, c.x); + expect(c.y - b.bottom, layoutConfig().rowGap); + expect(layout.nodeFor('d')!.rank, 2); + expect(layout.nodeFor('d')!.x, greaterThan(b.right)); + _expectWithinBounds(layout); + _expectSeparated(layout); + }); + + test('cycles share a column and terminals still follow them', () { + final layout = _layout(cycleGraph()); + + final a = layout.nodeFor('a')!; + final b = layout.nodeFor('b')!; + expect(a.rank, 0); + expect(b.rank, 0); + expect(b.y - a.bottom, layoutConfig().rowGap); + expect(layout.nodeFor(failureEnd)!.rank, 1); + expect(layout.nodeFor(successEnd)!.rank, 1); + _expectWithinBounds(layout); + _expectSeparated(layout); + }); + + test('self loops and disconnected stages stay finite and separate', () { + final selfLoop = _layout(selfLoopGraphFixture()); + expect(selfLoop.nodeFor('a')!.rank, 0); + expect(selfLoop.nodeFor('b')!.rank, 1); + + final disconnected = _layout(disconnectedGraph()); + expect(disconnected.nodeFor('a')!.rank, 0); + expect(disconnected.nodeFor('b')!.rank, 0); + expect(disconnected.nodeFor('c')!.rank, 0); + expect( + disconnected.nodeFor('b')!.y, + greaterThan(disconnected.nodeFor('a')!.bottom), + ); + _expectWithinBounds(selfLoop); + _expectSeparated(selfLoop); + _expectWithinBounds(disconnected); + _expectSeparated(disconnected); + }); + + test('unknown edge targets add no node and no column', () { + final graph = incompleteGraphFixture(); + final layout = _layout(graph); + + expect( + layout.nodes.map((box) => box.key), + graphNodes(graph).map((node) => node.key), + ); + expect(layout.nodeFor('ghost'), isNull); + expect(layout.ranks.containsKey('ghost'), isFalse); + _expectWithinBounds(layout); + _expectSeparated(layout); + }); + + test('heterogeneous measured widths stay inside their columns', () { + final layout = _layout( + diamondGraphFixture(), + extents: heterogeneousExtents(), + ); + + for (final entry in heterogeneousExtents().entries) { + final box = layout.nodeFor(entry.key)!; + expect(box.width, entry.value.width, reason: '${entry.key} width'); + expect(box.height, entry.value.height, reason: '${entry.key} height'); + } + final b = layout.nodeFor('b')!; + final c = layout.nodeFor('c')!; + expect(b.rank, c.rank); + expect(b.x + b.width / 2, c.x + c.width / 2); + expect(c.y - b.bottom, layoutConfig().rowGap); + expect(layout.width, greaterThan(0)); + expect(layout.width, 770); + expect(layout.height, 236); + _expectWithinBounds(layout); + _expectSeparated(layout); + }); + + test('expanded text extents grow the canvas without overlap or clipping', () { + final base = _layout( + diamondGraphFixture(), + extents: heterogeneousExtents(), + ); + final expandedExtents = scaledExtents(heterogeneousExtents(), 2.6); + final expanded = _layout(diamondGraphFixture(), extents: expandedExtents); + + expect(expanded.width, greaterThan(base.width)); + expect(expanded.height, greaterThan(base.height)); + for (final entry in expandedExtents.entries) { + final box = expanded.nodeFor(entry.key)!; + expect(box.width, entry.value.width, reason: '${entry.key} width'); + expect(box.height, entry.value.height, reason: '${entry.key} height'); + } + _expectWithinBounds(expanded); + _expectSeparated(expanded); + }); + + test('the same input produces the same immutable layout', () { + final graph = diamondGraphFixture(); + final nodes = graphNodes(graph); + final edges = graphEdges(graph); + final extents = uniformExtents(nodes, width: 133, height: 77); + + final first = layoutGraphNodes( + nodes: nodes, + edges: edges, + extents: extents, + config: layoutConfig(), + ); + final second = layoutGraphNodes( + nodes: nodes, + edges: edges, + extents: extents, + config: layoutConfig(), + ); + + expect(second.nodes, first.nodes); + expect(second.ranks, first.ranks); + expect(second.width, first.width); + expect(second.height, first.height); + expect(second.rankCount, first.rankCount); + expect(() => second.nodes.add(first.nodes.first), throwsUnsupportedError); + expect(() => second.ranks['a'] = 99, throwsUnsupportedError); + }); +} diff --git a/app/test/features/graph/layout/graph_ranks_test.dart b/app/test/features/graph/layout/graph_ranks_test.dart new file mode 100644 index 00000000..320ba287 --- /dev/null +++ b/app/test/features/graph/layout/graph_ranks_test.dart @@ -0,0 +1,116 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/graph/domain/graph_definition.dart'; +import 'package:pipelines_app/features/graph/domain/graph_protocol.dart'; +import 'package:pipelines_app/features/graph/layout/graph_ranks.dart'; + +import 'layout_fixtures.dart'; + +GraphRanks _ranksFor(Map graph) { + return assignGraphRanks(graphNodes(graph), graphEdges(graph)); +} + +void main() { + test('linear definitions rank one stage per column', () { + final ranks = _ranksFor(linearGraphFixture()); + + expect(ranks.rankOf, { + 'plan': 0, + 'build': 1, + 'ship': 2, + failureEnd: 3, + successEnd: 3, + }); + expect(ranks.rankCount, 4); + expect(ranks.components, >[ + ['plan'], + ['build'], + ['ship'], + [failureEnd], + [successEnd], + ]); + }); + + test('diamond fan-out shares a rank and converges after it', () { + final ranks = _ranksFor(diamondGraphFixture()); + + expect(ranks.rankOf['a'], 0); + expect(ranks.rankOf['b'], ranks.rankOf['c']); + expect(ranks.rankOf['b'], 1); + expect(ranks.rankOf['d'], 2); + expect(ranks.rankOf[failureEnd], 1); + expect(ranks.rankOf[successEnd], 3); + expect(ranks.rankCount, 4); + }); + + test('a cycle collapses to one shared rank instead of recursing', () { + final ranks = _ranksFor(cycleGraph()); + + expect(ranks.rankOf['a'], 0); + expect(ranks.rankOf['b'], 0); + expect(ranks.rankOf[failureEnd], 1); + expect(ranks.rankOf[successEnd], 1); + expect(ranks.rankCount, 2); + expect(ranks.components, contains(equals(['a', 'b']))); + }); + + test('a self edge stays inside its own component and adds no rank', () { + final ranks = _ranksFor(selfLoopGraphFixture()); + + expect(ranks.rankOf, { + 'a': 0, + 'b': 1, + failureEnd: 2, + successEnd: 2, + }); + expect(ranks.components, contains(equals(['a']))); + expect(ranks.components, contains(equals(['b']))); + }); + + test('disconnected stages stay at rank zero', () { + final ranks = _ranksFor(disconnectedGraph()); + + expect(ranks.rankOf['a'], 0); + expect(ranks.rankOf['b'], 0); + expect(ranks.rankOf['c'], 0); + expect(ranks.rankOf[failureEnd], 1); + expect(ranks.rankOf[successEnd], 1); + expect(ranks.rankCount, 2); + }); + + test('unknown and empty edge targets never become ranks or nodes', () { + final graph = incompleteGraphFixture(); + final nodes = graphNodes(graph); + final ranks = assignGraphRanks(nodes, graphEdges(graph)); + + expect(nodes.map((node) => node.key), isNot(contains('ghost'))); + expect(ranks.rankOf.containsKey('ghost'), isFalse); + expect(ranks.rankOf.containsKey(''), isFalse); + expect(ranks.rankOf['a'], 0); + expect(ranks.rankOf['b'], 0); + expect(ranks.rankOf[failureEnd], 1); + expect(ranks.rankOf[successEnd], 1); + }); + + test('ranks are stable across repeated assignments', () { + final graph = diamondGraphFixture(); + final nodes = graphNodes(graph); + final edges = graphEdges(graph); + + final first = assignGraphRanks(nodes, edges); + final second = assignGraphRanks(nodes, edges); + + expect(second.rankOf, first.rankOf); + expect(second.rankCount, first.rankCount); + expect(second.components, first.components); + }); + + test('a long chain is walked iteratively without overflow', () { + const length = 2000; + final ranks = _ranksFor(chainGraph(length)); + + expect(ranks.rankCount, length + 1); + expect(ranks.rankOf['s0'], 0); + expect(ranks.rankOf['s${length - 1}'], length - 1); + expect(ranks.rankOf[successEnd], length); + }); +} diff --git a/app/test/features/graph/layout/layout_fixtures.dart b/app/test/features/graph/layout/layout_fixtures.dart new file mode 100644 index 00000000..e67a6051 --- /dev/null +++ b/app/test/features/graph/layout/layout_fixtures.dart @@ -0,0 +1,102 @@ +import 'package:pipelines_app/features/graph/domain/graph_definition.dart'; +import 'package:pipelines_app/features/graph/domain/graph_protocol.dart'; +import 'package:pipelines_app/features/graph/layout/layout_models.dart'; + +import '../domain/graph_fixtures.dart' as domain; + +/// Small definitions and measured extents shared by the layout tests. + +GraphLayoutConfig layoutConfig({ + double columnGap = 24, + double rowGap = 12, + double padding = 4, +}) { + return GraphLayoutConfig( + columnGap: columnGap, + rowGap: rowGap, + padding: padding, + ); +} + +/// One measured size for every node, optionally scaled to simulate text growth. +Map uniformExtents( + Iterable nodes, { + double width = 120, + double height = 60, + double scale = 1, +}) { + return { + for (final node in nodes) + node.key: NodeExtent(width: width * scale, height: height * scale), + }; +} + +Map scaledExtents( + Map base, + double scale, +) { + return { + for (final entry in base.entries) + entry.key: NodeExtent( + width: entry.value.width * scale, + height: entry.value.height * scale, + ), + }; +} + +/// Deliberately uneven measured boxes for the diamond definition. +Map heterogeneousExtents() { + return { + 'a': NodeExtent(width: 210, height: 84), + 'b': NodeExtent(width: 92, height: 44), + 'c': NodeExtent(width: 148, height: 126), + 'd': NodeExtent(width: 104, height: 58), + failureEnd: NodeExtent(width: 72, height: 34), + successEnd: NodeExtent(width: 228, height: 96), + }; +} + +/// Two stages in a cycle; both terminals are reached from inside the cycle. +Map cycleGraph() => { + 'stages': [ + domain.stage( + 'a', + edges: {'success': 'b', 'error': '#'}, + fallbackError: true, + ), + domain.stage( + 'b', + edges: {'success': 'a', 'error': '#success'}, + ), + ], +}; + +/// Two independent routes and a stage with no edges at all. +Map disconnectedGraph() => { + 'stages': [ + domain.stage('a', edges: {'success': '#success'}), + domain.stage('b', edges: {'success': '#failure'}), + domain.stage('c'), + ], +}; + +Map linearGraphFixture() => domain.linearGraph(); + +Map diamondGraphFixture() => domain.diamondGraph(); + +Map selfLoopGraphFixture() => domain.selfLoopGraph(); + +Map incompleteGraphFixture() => domain.incompleteGraph(); + +/// A long chain, used to prove the iterative rank walk cannot overflow. +Map chainGraph(int length) => { + 'stages': [ + for (var index = 0; index < length; index += 1) + domain.stage( + 's$index', + edges: { + 'success': index + 1 < length ? 's${index + 1}' : '#success', + }, + ), + ], +}; From 0344ef10d1622d2cccedcb0ff8d812984d42352f Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 16:26:27 +0100 Subject: [PATCH 15/18] docs(app): record verified tailnet HTTPS preview access --- app/WORK.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/app/WORK.md b/app/WORK.md index 8b01ab70..bf36d6a8 100644 --- a/app/WORK.md +++ b/app/WORK.md @@ -152,6 +152,15 @@ HTML login redirect 302 and unauthenticated JS 401 via the LAN address. Existing proxy/API services remain unchanged. Bind command uses --host 0.0.0.0 explicitly; the source default remains loopback for safety. +HTTPS access fixed for the user's Tailscale URL: +https://alans-macbook-pro.tail6bf4dc.ts.net:8096/. Port8096 originally spoke only +plain HTTP; added tailnet-only Tailscale Serve HTTPS8096 → http://127.0.0.1:8096. +Existing Serve443→8787 and8443→8095 routes preserved. Verified trusted certificate +(curl ssl_verify_result0), protected root302 to login, login200, unauthenticated +JS401; LAN HTTP still302. No Funnel/public-Internet exposure or auth disabling. +Prior Serve config saved in approved temp tailscale-serve-before-preview8096.json; +remove ONLY this route with tailscale serve --https=8096 off if rollback needed. + ### Manager integration findings - F3 candidate omitted `lib/features/runs/data/runs_repository.dart`: root runtime-data ignore matched source. Main 718442d adds an app-only exception; From a9237ee0231ad5c4306e03f4d08ebba100ebc54d Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 16:35:20 +0100 Subject: [PATCH 16/18] docs(app): record measured graph layout landing and next routing slice --- app/WORK.md | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/app/WORK.md b/app/WORK.md index bf36d6a8..2b5cc144 100644 --- a/app/WORK.md +++ b/app/WORK.md @@ -28,8 +28,9 @@ All work under app/. Existing applications remain running and unchanged. | T1a | Templates/validate/create-only requests | run57 / candidateef2f463 | manager reran13 focused tests + analyze, pass; exact create-only/source preservation checked | merged main, ancestry verified | — | | S1b | Native read-only schedule list | run58 / flutter/s1-list | original export repaired; Review resumed | pending review/landing | pending | | P2a | Graph identities/recorded-visit model | run59 / commit2c10507 | manager reran41 focused tests + analyze, pass; scoped 4 pure domain files | merged main, ancestry verified | no renderer/layout yet | -| P2b | Content-sized graph node layout | run60 / flutter/p2-layout | Task v6, Flash; explicit measured extents, no fixed CSS dimensions | running | — | +| P2b | Content-sized graph node layout | run60 / commitc1f140b | manager checked caller-supplied extents + reran21 tests/analyze, pass | mainec9e889, ancestry verified | geometry only, no renderer | | A1a | Artifact records/grouping/safe URL navigation | run61 / flutter/a1-data | Task v6, Flash; pure data/security fixtures | running | — | +| P2c | Edge routes and measured label geometry | run62 / flutter/p2-routes | Task v6, Flash; separate from painter/widgets | running | — | ## Next ready work - P1 pipelines list/detail/source/version; P2 graph and stage/visit selection. @@ -114,10 +115,10 @@ that exact candidate. Staged binary in approved OpenCode temp directory is pipelines-server-exportfix-b4627e2; rollback copy is pipelines-server-before-exportfix-66779. Installed binary/launchd registration remain untouched. This avoids deploying unrelated newer main changes. -Graph lane59 is finished/landed. New launches are temporarily held to allow a -quiescent installation window once operator restart approval arrives; native -schedule list58 continues, template data57 is finished/accepted. This is a -deployment dependency, not a reason to replay or discard completed feature work. +The temporary launch pause ended after the direct, safe server installation. +Graph/model/layout lanes have progressed, and independent small tasks continue +alongside the seven restored feature reviews. No repeat approval gate remains +for routine authorized recovery/integration. User asked about failed runs; explicit status inspection found runs34/37/39/42/ 49/50 are waiting, not failed: each Code visit1 computed success and is quiescent, From 51140cd3b7a7ec80fb4b03230473fc7b28755349 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 16:41:30 +0100 Subject: [PATCH 17/18] feat(app): add native omni-search screen over the search gateway Pure request/parse/row logic in lib/features/search/domain, a gateway-backed repository, and Material plus Cupertino bodies. The header and rows share one scroll view, and the server's truncation, scan and cap facts stay visible even when a bounded scan returns no matches. Tests cover the exact search envelope, token parsing, stale replies, retry, truncation bounds and platform layouts. A Web-only fixture and CDP probe support rendered verification; the screen is not yet registered in the shell. --- .../search/data/search_repository.dart | 28 ++ .../search/domain/search_controller.dart | 236 +++++++++++++++++ .../features/search/domain/search_format.dart | 43 +++ .../features/search/domain/search_models.dart | 87 +++++++ .../features/search/domain/search_query.dart | 82 ++++++ .../features/search/domain/search_row.dart | 226 ++++++++++++++++ app/lib/features/search/search_screen.dart | 228 ++++++++++++++++ .../search/ui/cupertino_search_body.dart | 174 +++++++++++++ .../search/ui/material_search_body.dart | 166 ++++++++++++ .../search/ui/search_result_view.dart | 59 +++++ app/notes/X1.md | 121 +++++++++ .../search_controller_failure_test.dart | 90 +++++++ .../search/search_controller_test.dart | 240 +++++++++++++++++ .../features/search/search_query_test.dart | 118 +++++++++ .../search/search_repository_test.dart | 106 ++++++++ app/test/features/search/search_row_test.dart | 161 ++++++++++++ .../search/search_screen_states_test.dart | 146 +++++++++++ .../features/search/search_screen_test.dart | 223 ++++++++++++++++ .../features/search/search_test_support.dart | 50 ++++ app/tool/search_fixture/main.dart | 190 ++++++++++++++ app/tool/search_probe.mjs | 246 ++++++++++++++++++ 21 files changed, 3020 insertions(+) create mode 100644 app/lib/features/search/data/search_repository.dart create mode 100644 app/lib/features/search/domain/search_controller.dart create mode 100644 app/lib/features/search/domain/search_format.dart create mode 100644 app/lib/features/search/domain/search_models.dart create mode 100644 app/lib/features/search/domain/search_query.dart create mode 100644 app/lib/features/search/domain/search_row.dart create mode 100644 app/lib/features/search/search_screen.dart create mode 100644 app/lib/features/search/ui/cupertino_search_body.dart create mode 100644 app/lib/features/search/ui/material_search_body.dart create mode 100644 app/lib/features/search/ui/search_result_view.dart create mode 100644 app/notes/X1.md create mode 100644 app/test/features/search/search_controller_failure_test.dart create mode 100644 app/test/features/search/search_controller_test.dart create mode 100644 app/test/features/search/search_query_test.dart create mode 100644 app/test/features/search/search_repository_test.dart create mode 100644 app/test/features/search/search_row_test.dart create mode 100644 app/test/features/search/search_screen_states_test.dart create mode 100644 app/test/features/search/search_screen_test.dart create mode 100644 app/test/features/search/search_test_support.dart create mode 100644 app/tool/search_fixture/main.dart create mode 100644 app/tool/search_probe.mjs diff --git a/app/lib/features/search/data/search_repository.dart b/app/lib/features/search/data/search_repository.dart new file mode 100644 index 00000000..391aac13 --- /dev/null +++ b/app/lib/features/search/data/search_repository.dart @@ -0,0 +1,28 @@ +import '../../../core/api_gateway.dart'; +import '../domain/search_models.dart'; + +/// Search protocol requests over the application's shared gateway. +/// +/// The request body is exactly `SearchRequest{query, kind, limit}` with +/// `limit: 0`, so the server applies its own default cap (`SearchDefaultLimit`, +/// 50) instead of the client choosing a larger one. +class SearchRepository { + SearchRepository(this._gateway); + + final ApiGateway _gateway; + + /// Returns the bounded `search_results` body, or null when an older server + /// answered without it (its default `pong`) so the caller can report the + /// "cannot search" sentence rather than showing a false empty success. + Future search({ + required String query, + required SearchKind kind, + }) async { + final reply = await _gateway.call('search', { + 'search': {'query': query, 'kind': kind.wire, 'limit': 0}, + }); + final results = reply['search_results']; + if (results is! Map) return null; + return SearchResponse.fromJson(Map.from(results)); + } +} diff --git a/app/lib/features/search/domain/search_controller.dart b/app/lib/features/search/domain/search_controller.dart new file mode 100644 index 00000000..b9a3f8f8 --- /dev/null +++ b/app/lib/features/search/domain/search_controller.dart @@ -0,0 +1,236 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; + +import '../../../core/api_gateway.dart'; +import '../data/search_repository.dart'; +import 'search_models.dart'; +import 'search_query.dart'; +import 'search_row.dart'; + +/// The body the results area shows, in the browser's precedence order: an error +/// takes precedence over retained results, a refresh keeps results on screen, +/// and a first load shows the searching row. +enum SearchBodyKind { idle, searching, results, empty, error } + +/// Debounced, stale-safe omni-search state. It owns no widgets and no socket: +/// the screen listens to it and the repository talks to the shared gateway. +class OmniSearchController extends ChangeNotifier { + OmniSearchController({ + required this.repository, + this.debounce = const Duration(milliseconds: 250), + }); + + final SearchRepository repository; + final Duration debounce; + final SearchSequencer _sequencer = SearchSequencer(); + + Timer? _timer; + bool _disposed = false; + + String _query = ''; + SearchKind _selectedKind = SearchKind.all; + List _results = const []; + bool _loading = false; + bool _loaded = false; + bool _truncated = false; + int _scannedSteps = 0; + int _scannedBytes = 0; + int _cap = 0; + int _scanBoundBytes = 0; + String? _error; + + String get query => _query; + SearchKind get selectedKind => _selectedKind; + ParsedSearchQuery get parsed => parseSearchQuery(_query, _selectedKind); + List get results => _results; + bool get loading => _loading; + bool get loaded => _loaded; + bool get truncated => _truncated; + int get scannedSteps => _scannedSteps; + int get scannedBytes => _scannedBytes; + int get cap => _cap; + int get scanBoundBytes => _scanBoundBytes; + String? get error => _error; + + /// The results already in hand, re-narrowed to the effective kind so the list + /// always matches the control while a narrowed request loads. + List get shownResults { + final kind = parsed.kind; + if (kind == SearchKind.all) return _results; + return _results + .where((hit) => hit['kind'] == kind.wire) + .toList(growable: false); + } + + SearchBodyKind get bodyKind { + if (_error != null) return SearchBodyKind.error; + if (shownResults.isNotEmpty) return SearchBodyKind.results; + if (_loading && _results.isEmpty) return SearchBodyKind.searching; + if (emptyMessage != null) return SearchBodyKind.empty; + return SearchBodyKind.idle; + } + + /// A thin progress report above retained results while a newer query loads. + bool get showProgress => _loading && _results.isNotEmpty; + + String? get emptyMessage { + if (_error != null || _loading || shownResults.isNotEmpty) return null; + final effective = parsed; + if (effective.query.trim().isEmpty) { + if (!_loaded || effective.kind == SearchKind.all) return null; + final label = effective.kind.label.toLowerCase(); + return _truncated + ? "No $label found within the server's scan limit." + : 'No $label yet.'; + } + final bounded = _truncated ? " within the server's scan limit" : ''; + if (effective.kind == SearchKind.all) { + return 'No matches for "${effective.query}"$bounded.'; + } + return 'No ${effective.kind.label.toLowerCase()} match ' + '"${effective.query}"$bounded.'; + } + + /// The server's own result/scan bounds, so a capped answer is not presented as + /// a complete one. A truncated reply keeps its warning even with no rows; + /// before any loaded reply there is nothing to report. + String? get boundsText { + if (!_loaded) return null; + // A new first load has no current result set yet, so do not carry the + // previous reply's warning while the searching state is on screen. + if (_loading && _results.isEmpty) return null; + if (_results.isEmpty && !_truncated) return null; + final count = _results.length; + final parts = []; + if (_truncated) { + parts.add("Results truncated by the server's result or scan limit."); + } + parts.add('$count ${count == 1 ? 'result' : 'results'}'); + if (_cap > 0) parts.add('cap $_cap'); + parts.add('scanned $_scannedSteps steps'); + parts.add('${humanBytes(_scannedBytes)} scanned'); + if (_scanBoundBytes > 0) { + parts.add('scan limit ${humanBytes(_scanBoundBytes)}'); + } + return parts.join(' · '); + } + + /// Record a keystroke. Blank text with no kind clears locally and sends + /// nothing; valid kind-only browsing is sendable like the browser's search. + void updateQuery(String value) { + _query = value; + _error = null; + _cancelTimer(); + final effective = parsed; + if (!searchQuerySendable(effective.query, effective.kind)) { + _sequencer.edit(''); + _clearResults(); + _notify(); + return; + } + _loading = true; + final edit = _sequencer.edit(value); + _notify(); + _timer = Timer(debounce, () { + _timer = null; + final sent = _sequencer.begin(edit); + if (sent != null) unawaited(_send(sent)); + }); + } + + /// A kind change removes recognised type tokens from the visible text and + /// sends at once, matching the browser's selector behaviour. + void selectKind(SearchKind kind) { + _query = parseSearchQuery(_query, _selectedKind).query; + _selectedKind = kind; + _error = null; + _notify(); + unawaited(sendNow()); + } + + /// Enter: send the current query immediately, skipping the debounce. + Future submit() => sendNow(); + + /// Retry the current query after a failure. + Future retry() => sendNow(); + + Future sendNow() async { + _cancelTimer(); + final effective = parseSearchQuery(_query, _selectedKind); + if (!searchQuerySendable(effective.query, effective.kind)) { + _sequencer.edit(''); + _clearResults(); + _notify(); + return; + } + final sent = _sequencer.begin(_sequencer.edit(_query)); + if (sent == null) return; + await _send(sent); + } + + Future _send(SearchEdit sent) async { + final effective = parseSearchQuery(sent.query, _selectedKind); + _loading = true; + _error = null; + _notify(); + try { + final response = await repository.search( + query: effective.query.trim(), + kind: effective.kind, + ); + if (!_sequencer.accepts(sent.token) || _disposed) return; + if (response == null) { + _loading = false; + _loaded = true; + _error = unsupportedSearchCopy; + _notify(); + return; + } + _results = response.results; + _truncated = response.truncated; + _scannedSteps = response.scannedSteps; + _scannedBytes = response.scannedBytes; + _cap = response.cap; + _scanBoundBytes = response.scanBoundBytes; + _loading = false; + _loaded = true; + _error = null; + _notify(); + } catch (error) { + if (!_sequencer.accepts(sent.token) || _disposed) return; + _loading = false; + _loaded = true; + _error = searchFailureText(error); + _notify(); + } + } + + void _clearResults() { + _results = const []; + _truncated = false; + _scannedSteps = 0; + _scannedBytes = 0; + _cap = 0; + _scanBoundBytes = 0; + _loading = false; + _loaded = false; + _error = null; + } + + void _cancelTimer() { + _timer?.cancel(); + _timer = null; + } + + void _notify() { + if (!_disposed) notifyListeners(); + } + + @override + void dispose() { + _disposed = true; + _cancelTimer(); + super.dispose(); + } +} diff --git a/app/lib/features/search/domain/search_format.dart b/app/lib/features/search/domain/search_format.dart new file mode 100644 index 00000000..8e2f480a --- /dev/null +++ b/app/lib/features/search/domain/search_format.dart @@ -0,0 +1,43 @@ +/// Human bytes with the shared binary units (`2.0 KiB`), matching the browser. +String humanBytes(int size) { + const unit = 1024; + if (size < unit) return '$size B'; + var divisor = unit; + var exponent = 0; + var scaled = size ~/ unit; + while (scaled >= unit && exponent < 5) { + divisor *= unit; + exponent++; + scaled ~/= unit; + } + return '${(size / divisor).toStringAsFixed(1)} ${'KMGTPE'[exponent]}iB'; +} + +const _months = [ + 'Jan', + 'Feb', + 'Mar', + 'Apr', + 'May', + 'Jun', + 'Jul', + 'Aug', + 'Sep', + 'Oct', + 'Nov', + 'Dec', +]; + +/// An RFC3339 timestamp as the app's one human local rendering (`20 Oct 12:00`), +/// or null when blank/unparseable so the caller omits the value rather than +/// printing a blank. +String? formatSearchTimestamp(String value) { + final text = value.trim(); + if (text.isEmpty) return null; + final instant = DateTime.tryParse(text); + if (instant == null) return null; + final local = instant.toLocal(); + final hour = local.hour.toString().padLeft(2, '0'); + final minute = local.minute.toString().padLeft(2, '0'); + return '${local.day} ${_months[local.month - 1]} $hour:$minute'; +} diff --git a/app/lib/features/search/domain/search_models.dart b/app/lib/features/search/domain/search_models.dart new file mode 100644 index 00000000..671e38d9 --- /dev/null +++ b/app/lib/features/search/domain/search_models.dart @@ -0,0 +1,87 @@ +import '../../../core/api_gateway.dart'; + +/// The server's search narrowing vocabulary (`internal/protocol/search.go`), +/// in the control's display order. The empty [wire] value means every kind. +enum SearchKind { + all('', 'All kinds'), + pipeline('pipeline', 'Pipelines'), + run('run', 'Runs'), + step('step', 'Steps'), + field('field', 'Fields'), + artifact('artifact', 'Artifacts'), + version('version', 'Versions'); + + const SearchKind(this.wire, this.label); + + final String wire; + final String label; + + /// A stale or unknown value falls back to [SearchKind.all] rather than + /// inventing an option the server does not accept. + static SearchKind fromWire(String? wire) { + for (final kind in values) { + if (kind.wire == wire) return kind; + } + return SearchKind.all; + } +} + +/// A query after `t:`/`type:` tokens have been recognised. [query] is the text +/// the server should match; [kind] is the effective narrowing. +class ParsedSearchQuery { + const ParsedSearchQuery(this.query, this.kind, this.hasType); + + final String query; + final SearchKind kind; + final bool hasType; +} + +/// The bounded `search_results` body from the server. Every bound the server +/// reports is kept, so the screen can show a truncation/scan indicator instead +/// of pretending a capped reply was complete. +class SearchResponse { + const SearchResponse({ + this.query = '', + this.kind = SearchKind.all, + this.results = const [], + this.truncated = false, + this.scannedSteps = 0, + this.scannedBytes = 0, + this.cap = 0, + this.scanBoundBytes = 0, + }); + + factory SearchResponse.fromJson(JsonMap json) { + final rows = json['results']; + return SearchResponse( + query: '${json['query'] ?? ''}', + kind: SearchKind.fromWire('${json['kind'] ?? ''}'), + results: rows is List + ? rows + .whereType() + .map((row) => Map.from(row)) + .toList(growable: false) + : const [], + truncated: json['truncated'] == true, + scannedSteps: _integer(json['scanned_steps']), + scannedBytes: _integer(json['scanned_bytes']), + cap: _integer(json['cap']), + scanBoundBytes: _integer(json['scan_bound_bytes']), + ); + } + + final String query; + final SearchKind kind; + final List results; + final bool truncated; + final int scannedSteps; + final int scannedBytes; + final int cap; + final int scanBoundBytes; +} + +int _integer(Object? value) { + if (value is int) return value; + if (value is num) return value.toInt(); + return int.tryParse('$value') ?? 0; +} diff --git a/app/lib/features/search/domain/search_query.dart b/app/lib/features/search/domain/search_query.dart new file mode 100644 index 00000000..a7971540 --- /dev/null +++ b/app/lib/features/search/domain/search_query.dart @@ -0,0 +1,82 @@ +import 'search_models.dart'; + +/// Wording for a server that cannot answer `search`: an explicit rejection +/// naming an unknown/unsupported command, or a reply without +/// `search_results`. Kept verbatim from the web client's AppViewModel copy. +const unsupportedSearchCopy = + 'This server does not support search. Update the Pipelines server, then try again.'; + +/// Unquoted, whitespace-delimited `t:`/`type:` tokens; the last supported token +/// wins. Unknown tokens and quoted text stay literal, including their whitespace. +/// The selector is a fallback; explicitly changing it removes tokens in the view. +/// +/// This is the same token grammar as `web/src/search.js`, so `"t:run"`, +/// `t:unknown`, `prefix"t:run"` and `\t:run` all remain searchable text. +ParsedSearchQuery parseSearchQuery( + String value, [ + SearchKind selectedKind = SearchKind.all, +]) { + var kind = selectedKind; + var hasType = false; + final query = value.replaceAllMapped(_tokenPattern, (match) { + final token = match[0] ?? ''; + final type = _typePattern.firstMatch(token); + if (type == null) return token; + final candidate = SearchKind.fromWire(type.group(1)!.toLowerCase()); + if (candidate == SearchKind.all) return token; + kind = candidate; + hasType = true; + return ''; + }); + return ParsedSearchQuery(query, kind, hasType); +} + +final _tokenPattern = RegExp( + r'''(?:[^\s"'\\]|\\[\s\S]|"(?:[^"\\]|\\[\s\S])*(?:"|$)|'(?:[^'\\]|\\[\s\S])*(?:'|$))+''', +); +final _typePattern = RegExp(r'^(?:t|type):([a-z]+)$', caseSensitive: false); + +/// Text searches and valid kind-only browsing are sendable. Empty text with no +/// supported kind clears locally, without an all-kind scan. +bool searchQuerySendable(String query, SearchKind kind) => + query.trim().isNotEmpty || kind != SearchKind.all; + +/// The message for a failed search: the unsupported sentence for a missing +/// payload or an unknown-command rejection, otherwise the server's own text. +String searchFailureText(Object? error) { + if (error == null) return unsupportedSearchCopy; + final message = error.toString().trim(); + if (message.isEmpty) return unsupportedSearchCopy; + if (_unsupportedCommand.hasMatch(message)) return unsupportedSearchCopy; + return message; +} + +final _unsupportedCommand = RegExp( + r'\b(unknown|unsupported|unrecognised|unrecognized)\b[\s\S]*\bcommand\b', + caseSensitive: false, +); + +/// One recorded edit being debounced. +class SearchEdit { + const SearchEdit(this.token, this.query); + + final int token; + final String query; +} + +/// Query sequencing: a burst of keystrokes collapses into one request, and a +/// reply is accepted only for the newest recorded edit, so a stale reply can +/// never overwrite a newer one. Recording an edit (a keystroke, or an empty +/// edit when the field clears) is enough to invalidate an in-flight reply. +class SearchSequencer { + int _newest = 0; + + SearchEdit edit(String query) => SearchEdit(++_newest, query); + + SearchEdit? begin(SearchEdit? edit) { + if (edit == null || edit.token != _newest) return null; + return edit; + } + + bool accepts(int token) => token == _newest; +} diff --git a/app/lib/features/search/domain/search_row.dart b/app/lib/features/search/domain/search_row.dart new file mode 100644 index 00000000..283feca7 --- /dev/null +++ b/app/lib/features/search/domain/search_row.dart @@ -0,0 +1,226 @@ +import '../../../core/api_gateway.dart'; +import 'search_format.dart'; + +export 'search_format.dart' show humanBytes, formatSearchTimestamp; + +/// One run of a field snippet, split so the first case-insensitive occurrence of +/// the query can be emphasised without colour or markup. +class SearchSnippetSpan { + const SearchSnippetSpan(this.text, {required this.matched}); + + final String text; + final bool matched; +} + +/// A render-ready search row. [target] is the server's own stable target token; +/// it is null for an unknown/absent payload or a reply without a target, and +/// such a row is read-only — the client never guesses a route. +class SearchRowView { + const SearchRowView({ + required this.title, + required this.secondary, + required this.kindLabel, + required this.snippetSpans, + required this.target, + this.snippet, + this.recency, + }); + + final String title; + final String secondary; + final String kindLabel; + final String? snippet; + final List snippetSpans; + final String? recency; + final String? target; + + bool get openable => target != null; +} + +/// One rendered search row, mirroring the browser's per-kind row text. Every +/// server-provided string is only ever compared or rendered as text. +SearchRowView searchRowView(JsonMap hit, String query) { + final pipeline = _map(hit['pipeline']); + final version = _map(hit['version']); + final run = _map(hit['run']); + final step = _map(hit['step']); + final field = _map(hit['field']); + final artifact = _map(hit['artifact']); + + final recency = formatSearchTimestamp('${hit['recency'] ?? ''}'); + final target = _serverTarget(hit); + + if (pipeline != null) { + return SearchRowView( + title: _nonBlank(pipeline['name']) ?? 'pipeline ${_num(pipeline['id'])}', + secondary: + 'pipeline ${_num(pipeline['id'])} · v${_num(pipeline['version'])}' + ' · ${_stageCount(pipeline['stages'])}', + kindLabel: 'Pipeline', + snippetSpans: const [], + recency: recency, + target: target, + ); + } + if (version != null) { + final hash = _nonBlank(version['content_hash']); + return SearchRowView( + title: + 'pipeline ${_num(version['pipeline_id'])}' + ' · v${_num(version['version'])}', + secondary: _join([ + hash == null ? null : 'content $hash', + formatSearchTimestamp('${version['created_at'] ?? ''}'), + ]), + kindLabel: 'Pipeline version', + snippetSpans: const [], + recency: recency, + target: target, + ); + } + if (run != null) { + final name = _nonBlank(run['pipeline_name']); + return SearchRowView( + title: 'run #${_num(run['id'])}${name == null ? '' : ' · $name'}', + secondary: _join([ + _nonBlank(run['status']), + _nonBlank(run['workspace']), + formatSearchTimestamp('${run['created_at'] ?? ''}'), + ]), + kindLabel: 'Run', + snippetSpans: const [], + recency: recency, + target: target, + ); + } + if (step != null) { + final stage = _nonBlank(step['stage']) ?? 'step'; + return SearchRowView( + title: + 'run #${_num(step['run_id'])} · $stage' + ' visit ${_num(step['visit'])}', + secondary: _stepSecondary(step), + kindLabel: 'Step', + snippetSpans: const [], + recency: recency, + target: target, + ); + } + if (field != null) { + final snippet = '${field['snippet'] ?? ''}'; + return SearchRowView( + title: + 'run #${_num(field['run_id'])} · step ${_num(field['sequence'])}' + ' · ${_nonBlank(field['field']) ?? 'field'}', + secondary: snippet, + kindLabel: 'Field', + snippet: snippet, + snippetSpans: snippetSpans(snippet, query), + recency: recency, + target: target, + ); + } + if (artifact != null) { + return SearchRowView( + title: _nonBlank(artifact['name']) ?? 'artifact', + secondary: _join([ + 'run #${_num(artifact['run_id'])}', + 'step ${_num(artifact['sequence'])}', + _nonBlank(artifact['content_type']), + humanBytes(_num(artifact['size_bytes'])), + ]), + kindLabel: 'Artifact', + snippetSpans: const [], + recency: recency, + target: target, + ); + } + final kind = _nonBlank(hit['kind']); + return SearchRowView( + title: _nonBlank(hit['target']) ?? 'Unrecognised result', + secondary: kind == null ? 'read-only' : 'kind "$kind" · read-only', + kindLabel: 'Unrecognised result', + snippetSpans: const [], + recency: recency, + target: target, + ); +} + +/// Splits [snippet] so the first case-insensitive occurrence of [query] is a +/// distinct matched span. A blank query or absent match leaves the whole +/// snippet unmatched, so no text is ever dropped. +List snippetSpans(String snippet, String query) { + if (snippet.isEmpty) return const []; + final needle = query.trim(); + if (needle.isEmpty) { + return [SearchSnippetSpan(snippet, matched: false)]; + } + final index = snippet.toLowerCase().indexOf(needle.toLowerCase()); + if (index < 0) return [SearchSnippetSpan(snippet, matched: false)]; + final end = index + needle.length; + return [ + if (index > 0) + SearchSnippetSpan(snippet.substring(0, index), matched: false), + SearchSnippetSpan(snippet.substring(index, end), matched: true), + if (end < snippet.length) + SearchSnippetSpan(snippet.substring(end), matched: false), + ]; +} + +String _stepSecondary(JsonMap step) { + final diagnostic = '${step['diagnostic'] ?? ''}'; + String? line; + for (final candidate in diagnostic.split(RegExp(r'\r?\n'))) { + if (candidate.trim().isNotEmpty) { + line = candidate; + break; + } + } + final target = _nonBlank(step['target']); + final joined = _join([ + _nonBlank(step['outcome']), + target == null ? null : '→ $target', + line?.trim(), + ]); + return joined.isEmpty ? 'step ${_num(step['sequence'])}' : joined; +} + +/// The server's own target token, never a target the client invents. A known +/// payload is not enough: an absent token makes the row read-only. +String? _serverTarget(JsonMap hit) { + final target = _nonBlank(hit['target']); + if (target == null) return null; + final known = [ + 'pipeline', + 'version', + 'run', + 'step', + 'field', + 'artifact', + ].any((key) => _map(hit[key]) != null); + return known ? target : null; +} + +String _stageCount(Object? count) { + final n = _num(count); + return '$n ${n == 1 ? 'stage' : 'stages'}'; +} + +Map? _map(Object? value) { + if (value is! Map) return null; + return Map.from(value); +} + +String? _nonBlank(Object? value) { + final text = '${value ?? ''}'; + return text.trim().isEmpty ? null : text; +} + +int _num(Object? value) { + if (value is int) return value; + if (value is num) return value.toInt(); + return int.tryParse('${value ?? ''}') ?? 0; +} + +String _join(List parts) => + parts.whereType().where((part) => part.isNotEmpty).join(' · '); diff --git a/app/lib/features/search/search_screen.dart b/app/lib/features/search/search_screen.dart new file mode 100644 index 00000000..3c2e80ce --- /dev/null +++ b/app/lib/features/search/search_screen.dart @@ -0,0 +1,228 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../core/api_gateway.dart'; +import 'data/search_repository.dart'; +import 'domain/search_controller.dart'; +import 'domain/search_models.dart'; +import 'ui/cupertino_search_body.dart'; +import 'ui/material_search_body.dart'; + +/// Native omni-search over the Pipelines server: a standard search field, an +/// explicit kind selector, and a flat result list whose rows open the server's +/// own target through [onOpen]. The screen never mutates server state and never +/// guesses a route for an unknown or targetless hit. +class SearchScreen extends StatefulWidget { + const SearchScreen({ + super.key, + required this.gateway, + required this.onOpen, + this.cupertino, + }); + + final ApiGateway gateway; + final ValueChanged onOpen; + + /// Lets the shell state the surface it composed. When omitted, iOS/macOS use + /// Cupertino controls and every other platform uses Material. + final bool? cupertino; + + @override + State createState() => _SearchScreenState(); +} + +class _SearchScreenState extends State { + late final OmniSearchController _controller; + late final TextEditingController _text; + + @override + void initState() { + super.initState(); + _controller = OmniSearchController( + repository: SearchRepository(widget.gateway), + ); + _text = TextEditingController(); + _controller.addListener(_onState); + } + + void _onState() { + final query = _controller.query; + if (_text.text != query) { + _text.value = TextEditingValue( + text: query, + selection: TextSelection.collapsed(offset: query.length), + ); + } + if (mounted) setState(() {}); + } + + void _clear() { + _text.clear(); + _controller.updateQuery(''); + } + + void _selectKind(SearchKind kind) => _controller.selectKind(kind); + + bool get _showHint { + final body = _controller.bodyKind; + return body == SearchBodyKind.idle || body == SearchBodyKind.empty; + } + + Future _pickKind(BuildContext context) async { + final selected = await showCupertinoModalPopup( + context: context, + builder: (context) => CupertinoActionSheet( + title: const Text('Kind'), + actions: [ + for (final kind in SearchKind.values) + CupertinoActionSheetAction( + onPressed: () => Navigator.pop(context, kind), + isDefaultAction: kind == _controller.parsed.kind, + child: Text(kind.label), + ), + ], + cancelButton: CupertinoActionSheetAction( + onPressed: () => Navigator.pop(context), + child: const Text('Cancel'), + ), + ), + ); + if (selected != null) _selectKind(selected); + } + + @override + void dispose() { + _controller.removeListener(_onState); + _controller.dispose(); + _text.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final cupertino = + widget.cupertino ?? + switch (Theme.of(context).platform) { + TargetPlatform.iOS || TargetPlatform.macOS => true, + _ => false, + }; + return cupertino ? _cupertinoScreen() : _materialScreen(); + } + + Widget _materialScreen() => Scaffold( + appBar: AppBar(title: const Text('Search')), + body: SafeArea( + child: MaterialSearchBody( + controller: _controller, + query: _controller.parsed.query, + onOpen: widget.onOpen, + header: _materialHeader(), + ), + ), + ); + + Widget _materialHeader() => Padding( + padding: const EdgeInsets.fromLTRB(16, 12, 16, 8), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + spacing: 8, + children: [ + SearchBar( + key: const ValueKey('search.field'), + controller: _text, + autoFocus: true, + hintText: 'Search pipelines, runs and artifacts', + leading: const Icon(Icons.search), + trailing: [ + if (_text.text.isNotEmpty) + IconButton( + key: const ValueKey('search.clear'), + onPressed: _clear, + tooltip: 'Clear search', + icon: const Icon(Icons.close), + ), + ], + textInputAction: TextInputAction.search, + onChanged: _controller.updateQuery, + onSubmitted: (_) => _controller.submit(), + ), + InputDecorator( + decoration: const InputDecoration( + labelText: 'Kind', + border: OutlineInputBorder(), + ), + child: DropdownButtonHideUnderline( + child: DropdownButton( + key: const ValueKey('search.kind'), + value: _controller.parsed.kind, + isExpanded: true, + onChanged: (kind) { + if (kind != null) _selectKind(kind); + }, + items: [ + for (final kind in SearchKind.values) + DropdownMenuItem(value: kind, child: Text(kind.label)), + ], + ), + ), + ), + if (_showHint) const Text(_tokenHint), + if (_controller.boundsText case final bounds?) Text(bounds), + ], + ), + ); + + Widget _cupertinoScreen() => CupertinoPageScaffold( + navigationBar: const CupertinoNavigationBar(middle: Text('Search')), + child: SafeArea( + child: CupertinoSearchBody( + controller: _controller, + query: _controller.parsed.query, + onOpen: widget.onOpen, + header: _cupertinoHeader(context), + ), + ), + ); + + Widget _cupertinoHeader(BuildContext context) => Padding( + padding: const EdgeInsets.fromLTRB(16, 12, 16, 8), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + spacing: 8, + children: [ + CupertinoSearchTextField( + key: const ValueKey('search.field'), + controller: _text, + autofocus: true, + placeholder: 'Search pipelines, runs and artifacts', + onChanged: _controller.updateQuery, + onSubmitted: (_) => _controller.submit(), + onSuffixTap: _clear, + ), + Align( + alignment: AlignmentDirectional.centerStart, + child: CupertinoButton( + key: const ValueKey('search.kind'), + padding: EdgeInsets.zero, + onPressed: () => _pickKind(context), + child: Row( + mainAxisSize: MainAxisSize.max, + spacing: 6, + children: [ + Expanded(child: Text('Kind: ${_controller.parsed.kind.label}')), + const Icon(CupertinoIcons.chevron_down), + ], + ), + ), + ), + if (_showHint) const Text(_tokenHint), + if (_controller.boundsText case final bounds?) Text(bounds), + ], + ), + ); +} + +const _tokenHint = + 'Filter with t:pipeline or type:artifact (pipeline, run, step, field, ' + 'artifact, version). Last type wins; choosing Kind replaces it. Quote ' + 'tokens to search literally.'; diff --git a/app/lib/features/search/ui/cupertino_search_body.dart b/app/lib/features/search/ui/cupertino_search_body.dart new file mode 100644 index 00000000..2f29d3b0 --- /dev/null +++ b/app/lib/features/search/ui/cupertino_search_body.dart @@ -0,0 +1,174 @@ +import 'package:flutter/cupertino.dart'; + +import '../../../core/api_gateway.dart'; +import '../domain/search_controller.dart'; +import '../domain/search_row.dart'; +import 'search_result_view.dart'; + +/// The Cupertino search view: native search/kind controls and grouped list rows +/// in one scroll view, with standard activity and retry controls. +class CupertinoSearchBody extends StatelessWidget { + const CupertinoSearchBody({ + super.key, + required this.controller, + required this.query, + required this.onOpen, + required this.header, + }); + + final OmniSearchController controller; + final String query; + final ValueChanged onOpen; + final Widget header; + + @override + Widget build(BuildContext context) { + return CustomScrollView( + slivers: [ + SliverToBoxAdapter(child: header), + if (controller.showProgress) + const SliverToBoxAdapter( + child: Padding( + padding: EdgeInsets.symmetric(vertical: 8), + child: CupertinoActivityIndicator(), + ), + ), + ..._content(context), + ], + ); + } + + List _content(BuildContext context) { + switch (controller.bodyKind) { + case SearchBodyKind.error: + return [ + SliverFillRemaining( + hasScrollBody: false, + child: _CupertinoError( + message: controller.error!, + onRetry: controller.retry, + ), + ), + ]; + case SearchBodyKind.searching: + return const [ + SliverFillRemaining( + hasScrollBody: false, + child: _CupertinoSearching(), + ), + ]; + case SearchBodyKind.results: + return [ + SliverToBoxAdapter( + child: CupertinoListSection.insetGrouped( + children: [ + for (final hit in controller.shownResults) + _CupertinoResult(hit: hit, query: query, onOpen: onOpen), + ], + ), + ), + ]; + case SearchBodyKind.empty: + return [ + SliverFillRemaining( + hasScrollBody: false, + child: _CupertinoMessage(message: controller.emptyMessage!), + ), + ]; + case SearchBodyKind.idle: + return const [ + SliverFillRemaining( + hasScrollBody: false, + child: _CupertinoMessage( + message: 'Search pipelines, runs and artifacts.', + ), + ), + ]; + } + } +} + +class _CupertinoResult extends StatelessWidget { + const _CupertinoResult({ + required this.hit, + required this.query, + required this.onOpen, + }); + + final JsonMap hit; + final String query; + final ValueChanged onOpen; + + @override + Widget build(BuildContext context) { + final row = searchRowView(hit, query); + return CupertinoListTile( + key: ValueKey('search.result.${hit['target']}'), + leading: Icon(searchCupertinoIcon('${hit['kind'] ?? ''}')), + title: Text(row.title), + subtitle: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + spacing: 2, + children: [searchRowMeta(row), searchRowSnippet(context, row)], + ), + onTap: row.openable ? () => onOpen(hit) : null, + ); + } +} + +class _CupertinoSearching extends StatelessWidget { + const _CupertinoSearching(); + + @override + Widget build(BuildContext context) => const Center( + child: Padding( + padding: EdgeInsets.all(24), + child: Column( + mainAxisSize: MainAxisSize.min, + spacing: 12, + children: [CupertinoActivityIndicator(), Text('Searching…')], + ), + ), + ); +} + +class _CupertinoMessage extends StatelessWidget { + const _CupertinoMessage({required this.message}); + + final String message; + + @override + Widget build(BuildContext context) => Center( + child: Padding( + padding: const EdgeInsets.all(24), + child: Text(message, textAlign: TextAlign.center), + ), + ); +} + +class _CupertinoError extends StatelessWidget { + const _CupertinoError({required this.message, required this.onRetry}); + + final String message; + final Future Function() onRetry; + + @override + Widget build(BuildContext context) => Center( + child: Padding( + padding: const EdgeInsets.all(24), + child: Column( + mainAxisSize: MainAxisSize.min, + spacing: 12, + children: [ + Text(message, textAlign: TextAlign.center), + CupertinoButton.filled( + key: const ValueKey('search.retry'), + onPressed: onRetry, + child: const Text('Retry'), + ), + ], + ), + ), + ); +} diff --git a/app/lib/features/search/ui/material_search_body.dart b/app/lib/features/search/ui/material_search_body.dart new file mode 100644 index 00000000..462f75ee --- /dev/null +++ b/app/lib/features/search/ui/material_search_body.dart @@ -0,0 +1,166 @@ +import 'package:flutter/material.dart'; + +import '../../../core/api_gateway.dart'; +import '../domain/search_controller.dart'; +import '../domain/search_row.dart'; +import 'search_result_view.dart'; + +/// The Material search view: the controls header and a flat native result list +/// in one scroll view, so text scaling can never clip the controls or a row. +class MaterialSearchBody extends StatelessWidget { + const MaterialSearchBody({ + super.key, + required this.controller, + required this.query, + required this.onOpen, + required this.header, + }); + + final OmniSearchController controller; + final String query; + final ValueChanged onOpen; + final Widget header; + + @override + Widget build(BuildContext context) { + return CustomScrollView( + slivers: [ + SliverToBoxAdapter(child: header), + if (controller.showProgress) + const SliverToBoxAdapter(child: LinearProgressIndicator()), + ..._content(context), + ], + ); + } + + List _content(BuildContext context) { + switch (controller.bodyKind) { + case SearchBodyKind.error: + return [ + SliverFillRemaining( + hasScrollBody: false, + child: _SearchError( + message: controller.error!, + onRetry: controller.retry, + ), + ), + ]; + case SearchBodyKind.searching: + return const [ + SliverFillRemaining(hasScrollBody: false, child: _Searching()), + ]; + case SearchBodyKind.results: + return [ + SliverList.builder( + itemCount: controller.shownResults.length, + itemBuilder: (context, index) { + final hit = controller.shownResults[index]; + return _MaterialResult(hit: hit, query: query, onOpen: onOpen); + }, + ), + ]; + case SearchBodyKind.empty: + return [ + SliverFillRemaining( + hasScrollBody: false, + child: _SearchMessage(message: controller.emptyMessage!), + ), + ]; + case SearchBodyKind.idle: + return const [ + SliverFillRemaining( + hasScrollBody: false, + child: _SearchMessage( + message: 'Search pipelines, runs and artifacts.', + ), + ), + ]; + } + } +} + +class _MaterialResult extends StatelessWidget { + const _MaterialResult({ + required this.hit, + required this.query, + required this.onOpen, + }); + + final JsonMap hit; + final String query; + final ValueChanged onOpen; + + @override + Widget build(BuildContext context) { + final row = searchRowView(hit, query); + return ListTile( + key: ValueKey('search.result.${hit['target']}'), + leading: Icon(searchMaterialIcon('${hit['kind'] ?? ''}')), + title: Text(row.title), + subtitle: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + spacing: 2, + children: [searchRowMeta(row), searchRowSnippet(context, row)], + ), + onTap: row.openable ? () => onOpen(hit) : null, + ); + } +} + +class _Searching extends StatelessWidget { + const _Searching(); + + @override + Widget build(BuildContext context) => const Center( + child: Padding( + padding: EdgeInsets.all(24), + child: Column( + mainAxisSize: MainAxisSize.min, + spacing: 12, + children: [CircularProgressIndicator(), Text('Searching…')], + ), + ), + ); +} + +class _SearchMessage extends StatelessWidget { + const _SearchMessage({required this.message}); + + final String message; + + @override + Widget build(BuildContext context) => Center( + child: Padding( + padding: const EdgeInsets.all(24), + child: Text(message, textAlign: TextAlign.center), + ), + ); +} + +class _SearchError extends StatelessWidget { + const _SearchError({required this.message, required this.onRetry}); + + final String message; + final Future Function() onRetry; + + @override + Widget build(BuildContext context) => Center( + child: Padding( + padding: const EdgeInsets.all(24), + child: Column( + mainAxisSize: MainAxisSize.min, + spacing: 12, + children: [ + Text(message, textAlign: TextAlign.center), + FilledButton.tonalIcon( + key: const ValueKey('search.retry'), + onPressed: onRetry, + icon: const Icon(Icons.refresh), + label: const Text('Retry'), + ), + ], + ), + ), + ); +} diff --git a/app/lib/features/search/ui/search_result_view.dart b/app/lib/features/search/ui/search_result_view.dart new file mode 100644 index 00000000..fef687f3 --- /dev/null +++ b/app/lib/features/search/ui/search_result_view.dart @@ -0,0 +1,59 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../domain/search_row.dart'; + +/// Kind, recency and read-only affordance for one row. Deliberately unstyled +/// beyond weight so Material and Cupertino inherit their own system typography +/// and colours, including dark mode and text scaling. +Widget searchRowMeta(SearchRowView row) { + final parts = [row.kindLabel, if (row.recency != null) row.recency!]; + return Text( + parts.join(' · '), + style: const TextStyle(fontWeight: FontWeight.w600), + ); +} + +/// The snippet with the first query occurrence emphasised by weight, never by +/// parsing server text as markup or by a bespoke colour. +Widget searchRowSnippet(BuildContext context, SearchRowView row) { + final snippet = row.snippet; + if (snippet == null) { + return row.secondary.isEmpty + ? const SizedBox.shrink() + : Text(row.secondary); + } + return Text.rich( + TextSpan( + children: [ + for (final span in row.snippetSpans) + TextSpan( + text: span.text, + style: span.matched + ? const TextStyle(fontWeight: FontWeight.bold) + : null, + ), + ], + ), + ); +} + +IconData searchMaterialIcon(String kind) => switch (kind) { + 'pipeline' => Icons.account_tree_outlined, + 'version' => Icons.layers_outlined, + 'run' => Icons.play_circle_outline, + 'step' => Icons.arrow_forward, + 'field' => Icons.notes, + 'artifact' => Icons.attach_file, + _ => Icons.help_outline, +}; + +IconData searchCupertinoIcon(String kind) => switch (kind) { + 'pipeline' => CupertinoIcons.arrow_branch, + 'version' => CupertinoIcons.square_stack_3d_up, + 'run' => CupertinoIcons.play_circle, + 'step' => CupertinoIcons.arrow_right, + 'field' => CupertinoIcons.doc_text, + 'artifact' => CupertinoIcons.paperclip, + _ => CupertinoIcons.question_circle, +}; diff --git a/app/notes/X1.md b/app/notes/X1.md new file mode 100644 index 00000000..72e19645 --- /dev/null +++ b/app/notes/X1.md @@ -0,0 +1,121 @@ +# X1 — Omni-search + +## Scope and API + +Implemented the `search` feature under `lib/features/search/` with no +`main.dart`, shell, pubspec, server, web or Android edits. + +Entry point: + +```dart +SearchScreen( + gateway: apiGateway, // required ApiGateway + onOpen: (hit) { ... }, // required ValueChanged + cupertino: null, // optional; omitted = iOS/macOS Cupertino, else Material +) +``` + +`onOpen` always receives the server's original result map unchanged, including +its `target`. Unknown/absent payloads and results without a target are +read-only and never call `onOpen`; the client never invents a route or mutates +server state. + +Request shape is exact and shared-gateway only: + +```json +{"type":"search","search":{"query":"plan","kind":"","limit":0}} +``` + +`limit` is always `0` (server default cap), never a client-chosen larger value. + +## Behaviour + +- `t:`/`type:` tokens: unquoted, whitespace-delimited, case-insensitive, last + supported token wins; quoted, escaped, unknown and trailing-punctuation + tokens stay literal. The parser mirrors `web/src/search.js`. +- Kind selector: All kinds / Pipelines / Runs / Steps / Fields / Artifacts / + Versions. Changing it removes recognised type tokens from the field and sends + at once, like the browser's selector. +- Empty text with All kinds clears locally and sends nothing. Blank text with a + valid kind is a kind-only browse, matching the server/browser contract. +- 250 ms debounce; Enter sends at once. Every request carries a monotonically + increasing token, and replies for superseded edits are dropped. +- Loading, searching, retained-results refresh progress, empty (query-specific + and kind-only wording) and error are distinct. A truncated reply with no rows + says the server's scan limit was reached and keeps its truncation/scan bounds + on screen instead of claiming a complete empty; a complete empty has no bounds + line. A reply without `search_results` and an unknown-command rejection use + the server-upgrade sentence; any other failure shows the server's own text. + Error state offers Retry. +- Rows show the kind derived from the server payload (`Unrecognised result` for + an unknown payload), title, snippet (first case-insensitive query occurrence in + bold), and recency. Bounds show result count, cap, scanned steps/bytes, scan + limit and a truncation sentence when the server reports it, including for a + truncated reply with zero rows. +- In-hand results are re-narrowed by the effective kind while a narrowed request + loads, so the list always agrees with the control. +- Standard platform controls only: Material `SearchBar`, dropdown, + `LinearProgressIndicator`, `CircularProgressIndicator`, `ListTile`, + `FilledButton.tonalIcon`; Cupertino `CupertinoSearchTextField`, action-sheet + kind picker, `CupertinoListSection`/`CupertinoListTile`, + `CupertinoActivityIndicator`, `CupertinoButton.filled`. No CSS port, custom + palette, fixed row/bubble dimensions or bespoke buttons. Typography and + colours come from the ambient Material/Cupertino theme; rows and the header + scroll in one `CustomScrollView` so 2× text never clips. + +## Automated checks + +Run from `app/` with `/Users/alan/development/flutter/bin/flutter`: + +- `flutter test test/features/search` — **36 passed** (controller, repository, + query/token parser, row/snippet/routing, Material + Cupertino widget tests). +- `flutter test` — **65 passed** (whole app suite, including existing transport, + runs and shell tests). +- `flutter analyze` — **No issues found**. +- `flutter build web` (default `lib/main.dart`) — **succeeded**. +- `flutter build web -t tool/search_fixture/main.dart` — **succeeded** for the + rendered probe. +- `node --check tool/search_probe.mjs` — passed. +- `git diff --no-index --check /dev/null ` on every touched file — no + whitespace errors (all task files are untracked, so plain `git diff --check` + would not see them). + +Tests were written before the implementation (initial run failed on missing +symbols). Coverage includes the exact envelope, token parsing, selector token +clearing, no-request empty state, stale success and failure replies, +error/retry, truncation/bounds (including a truncated reply with zero rows), +per-kind row text, snippet spans, read-only hits, `onOpen` targets, and +MaterialApp/CupertinoApp at 390/1000 wide with 2× text. + +## Rendered browser evidence + +Built the Web-only fixture (`tool/search_fixture/main.dart`) and drove real +headless Chrome through CDP with `tool/search_probe.mjs` on an OS-assigned +loopback port. The probe typed `plan` into the real field, asserted five rows, +the server snippet, recency and truncation/scanned bounds, then clicked the +pipeline row and asserted that the fixture receiver got `pipeline:24`. It also +typed `needle` with no matching fixtures and asserted the Material and Cupertino +truncated-empty copy plus the retained `Results truncated … 0 results … scanned +2000 steps … scan limit 1.0 MiB` line, capturing both. + +Captures are in the run's shared artifacts: + +- `/Users/alan/.local/share/pipelines/data/artifacts/49/public/x1-search/x1-search-material-phone.png` — 390×844, Material controls, five mixed-kind results with recency/snippet/bounds. +- `/Users/alan/.local/share/pipelines/data/artifacts/49/public/x1-search/x1-search-material-desktop.png` — 1280×800, same results. +- `/Users/alan/.local/share/pipelines/data/artifacts/49/public/x1-search/x1-search-cupertino-phone.png` — 390×844, Cupertino search field/kind picker/grouped rows, dark system theme. +- `/Users/alan/.local/share/pipelines/data/artifacts/49/public/x1-search/x1-search-open-target.png` — the row click landing on `Opened pipeline target: pipeline:24`. +- `/Users/alan/.local/share/pipelines/data/artifacts/49/public/x1-search/x1-search-truncated-empty.png` — 390×844 Material, zero rows with the server's scan-limit sentence and truncation/scan bounds. +- `/Users/alan/.local/share/pipelines/data/artifacts/49/public/x1-search/x1-search-truncated-empty-cupertino.png` — 390×844 Cupertino dark, the same bounded empty state. + +The fixture and probe are development-only entry points; they are not imported +by `lib/main.dart` and are not part of the production routing. The browser run +used a static fake gateway, not a live Pipelines server or operator data. + +## Not verified / open items + +- No shell registration or navigation wiring was added (manager owns + `main.dart`/`shell/`); the screen is exported for that integration. +- No real server, operator chat/run, or production URL was used. +- Mobile targets (Android/iOS) were **not** built, installed or exercised; + only Web was rendered and tested. Source is kept portable. +- No commit, push, deployment or canonical URL change was made. diff --git a/app/test/features/search/search_controller_failure_test.dart b/app/test/features/search/search_controller_failure_test.dart new file mode 100644 index 00000000..43f217c1 --- /dev/null +++ b/app/test/features/search/search_controller_failure_test.dart @@ -0,0 +1,90 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/search/domain/search_controller.dart'; +import 'package:pipelines_app/features/search/domain/search_query.dart'; +import 'search_test_support.dart'; + +void main() { + test('a server error is shown, and retry issues a fresh request', () async { + final gateway = QueuedGateway(); + final controller = controllerFor(gateway); + addTearDown(controller.dispose); + + controller.updateQuery('plan'); + await pumpEventQueue(); + gateway.fail(0, StateError('server is down')); + await pumpEventQueue(); + + expect(controller.bodyKind, SearchBodyKind.error); + expect(controller.error, contains('server is down')); + + final retry = controller.retry(); + await pumpEventQueue(); + expect(gateway.calls, hasLength(2)); + expect(gateway.lastSearch, {'query': 'plan', 'kind': '', 'limit': 0}); + + gateway.succeed( + 1, + envelope([ + { + 'kind': 'pipeline', + 'target': 'pipeline:7', + 'pipeline': {'id': 7}, + }, + ]), + ); + await retry; + expect(controller.error, isNull); + expect(controller.results, hasLength(1)); + expect(controller.bodyKind, SearchBodyKind.results); + }); + + test('a stale failure never replaces the newest query state', () async { + final gateway = QueuedGateway(); + final controller = controllerFor(gateway); + addTearDown(controller.dispose); + + controller.updateQuery('first'); + await pumpEventQueue(); + controller.updateQuery('second'); + await pumpEventQueue(); + + gateway.fail(0, StateError('stale failure')); + await pumpEventQueue(); + + expect(controller.error, isNull); + expect(controller.loading, isTrue); + expect(controller.bodyKind, SearchBodyKind.searching); + + gateway.succeed( + 1, + envelope([ + { + 'kind': 'pipeline', + 'target': 'pipeline:9', + 'pipeline': {'id': 9}, + }, + ]), + ); + await pumpEventQueue(); + expect(controller.error, isNull); + expect(controller.results.single['target'], 'pipeline:9'); + expect(controller.bodyKind, SearchBodyKind.results); + }); + + test( + 'a missing search_results payload reports the unsupported copy', + () async { + final gateway = QueuedGateway(); + final controller = controllerFor(gateway); + addTearDown(controller.dispose); + + controller.updateQuery('plan'); + await pumpEventQueue(); + gateway.succeed(0, {'type': 'pong'}); + await pumpEventQueue(); + + expect(controller.bodyKind, SearchBodyKind.error); + expect(controller.error, unsupportedSearchCopy); + }, + ); +} diff --git a/app/test/features/search/search_controller_test.dart b/app/test/features/search/search_controller_test.dart new file mode 100644 index 00000000..f9d90fe3 --- /dev/null +++ b/app/test/features/search/search_controller_test.dart @@ -0,0 +1,240 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/search/domain/search_controller.dart'; +import 'package:pipelines_app/features/search/domain/search_models.dart'; +import 'search_test_support.dart'; + +void main() { + test('empty query with no kind is idle and sends no request', () async { + final gateway = QueuedGateway(); + final controller = controllerFor(gateway); + addTearDown(controller.dispose); + + controller.updateQuery(' '); + await pumpEventQueue(); + + expect(gateway.calls, isEmpty); + expect(controller.bodyKind, SearchBodyKind.idle); + expect(controller.results, isEmpty); + expect(controller.loaded, isFalse); + expect(controller.loading, isFalse); + }); + + test('the request carries the parsed query, kind and limit 0', () async { + final gateway = QueuedGateway(); + final controller = controllerFor(gateway); + addTearDown(controller.dispose); + + controller.updateQuery('t:run Plan TYPE:artifact'); + await pumpEventQueue(); + + expect(gateway.calls, hasLength(1)); + expect(gateway.lastSearch, { + 'query': 'Plan', + 'kind': 'artifact', + 'limit': 0, + }); + }); + + test( + 'a kind selector change removes type tokens and sends at once', + () async { + final gateway = QueuedGateway(); + final controller = controllerFor(gateway); + addTearDown(controller.dispose); + + controller.updateQuery('plan t:run'); + await pumpEventQueue(); + expect(gateway.lastSearch['kind'], 'run'); + + controller.selectKind(SearchKind.pipeline); + await pumpEventQueue(); + + expect(controller.query.trim(), 'plan'); + expect(controller.query, isNot(contains('t:run'))); + expect(controller.selectedKind, SearchKind.pipeline); + expect(gateway.calls, hasLength(2)); + expect(gateway.lastSearch, { + 'query': 'plan', + 'kind': 'pipeline', + 'limit': 0, + }); + }, + ); + + test( + 'kind-only browsing sends a blank query and reports the empty copy', + () async { + final gateway = QueuedGateway(); + final controller = controllerFor(gateway); + addTearDown(controller.dispose); + + controller.selectKind(SearchKind.pipeline); + await pumpEventQueue(); + expect(gateway.lastSearch, {'query': '', 'kind': 'pipeline', 'limit': 0}); + expect(controller.bodyKind, SearchBodyKind.searching); + + gateway.succeed(0, envelope(const [])); + await pumpEventQueue(); + expect(controller.bodyKind, SearchBodyKind.empty); + expect(controller.emptyMessage, 'No pipelines yet.'); + }, + ); + + test('the latest query wins and a stale reply is dropped', () async { + final gateway = QueuedGateway(); + final controller = controllerFor(gateway); + addTearDown(controller.dispose); + + controller.updateQuery('first'); + await pumpEventQueue(); + controller.updateQuery('second'); + await pumpEventQueue(); + expect(gateway.calls, hasLength(2)); + + gateway.succeed( + 0, + envelope([ + { + 'kind': 'run', + 'target': 'run:1', + 'run': {'id': 1}, + }, + ]), + ); + await pumpEventQueue(); + expect(controller.results, isEmpty); + expect(controller.loading, isTrue); + expect(controller.bodyKind, SearchBodyKind.searching); + + gateway.succeed( + 1, + envelope([ + { + 'kind': 'run', + 'target': 'run:2', + 'run': {'id': 2}, + }, + ]), + ); + await pumpEventQueue(); + expect(controller.results.single['target'], 'run:2'); + expect(controller.loading, isFalse); + expect(controller.bodyKind, SearchBodyKind.results); + }); + + test('truncation and scan bounds come from the server envelope', () async { + final gateway = QueuedGateway(); + final controller = controllerFor(gateway); + addTearDown(controller.dispose); + + controller.updateQuery('plan'); + await pumpEventQueue(); + gateway.succeed( + 0, + envelope( + [ + { + 'kind': 'field', + 'target': 'run:11:4:output', + 'field': {'run_id': 11}, + }, + ], + truncated: true, + scannedSteps: 2000, + scannedBytes: 1048576, + cap: 50, + ), + ); + await pumpEventQueue(); + + expect(controller.truncated, isTrue); + expect(controller.scannedSteps, 2000); + expect(controller.scannedBytes, 1048576); + expect(controller.cap, 50); + expect(controller.boundsText, contains('truncated')); + expect(controller.boundsText, contains('cap 50')); + expect(controller.boundsText, contains('2000 steps')); + }); + + test( + 'a truncated empty reply reports the scan bound instead of a complete empty', + () async { + final gateway = QueuedGateway(); + final controller = controllerFor(gateway); + addTearDown(controller.dispose); + + controller.updateQuery('needle'); + await pumpEventQueue(); + gateway.succeed( + 0, + envelope( + const [], + truncated: true, + scannedSteps: 2000, + scannedBytes: 1048576, + cap: 50, + ), + ); + await pumpEventQueue(); + + expect(controller.bodyKind, SearchBodyKind.empty); + expect( + controller.emptyMessage, + 'No matches for "needle" within the server\'s scan limit.', + ); + expect(controller.boundsText, contains('Results truncated')); + expect(controller.boundsText, contains('0 results')); + expect(controller.boundsText, contains('2000 steps')); + expect(controller.boundsText, contains('scan limit 1.0 MiB')); + }, + ); + + test( + 'a complete empty reply stays a plain empty with no bounds line', + () async { + final gateway = QueuedGateway(); + final controller = controllerFor(gateway); + addTearDown(controller.dispose); + + controller.updateQuery('needle'); + await pumpEventQueue(); + gateway.succeed(0, envelope(const [])); + await pumpEventQueue(); + + expect(controller.bodyKind, SearchBodyKind.empty); + expect(controller.emptyMessage, 'No matches for "needle".'); + expect(controller.boundsText, isNull); + }, + ); + + test('in-hand kind narrowing keeps the list honest while loading', () async { + final gateway = QueuedGateway(); + final controller = controllerFor(gateway); + addTearDown(controller.dispose); + + controller.updateQuery('plan'); + await pumpEventQueue(); + gateway.succeed( + 0, + envelope([ + { + 'kind': 'run', + 'target': 'run:1', + 'run': {'id': 1}, + }, + { + 'kind': 'pipeline', + 'target': 'pipeline:7', + 'pipeline': {'id': 7}, + }, + ]), + ); + await pumpEventQueue(); + expect(controller.shownResults, hasLength(2)); + + controller.selectKind(SearchKind.run); + await pumpEventQueue(); + expect(controller.shownResults, hasLength(1)); + expect(controller.shownResults.single['target'], 'run:1'); + }); +} diff --git a/app/test/features/search/search_query_test.dart b/app/test/features/search/search_query_test.dart new file mode 100644 index 00000000..942a9b73 --- /dev/null +++ b/app/test/features/search/search_query_test.dart @@ -0,0 +1,118 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/search/domain/search_models.dart'; +import 'package:pipelines_app/features/search/domain/search_query.dart'; + +const unsupported = + 'This server does not support search. Update the Pipelines server, then try again.'; + +void main() { + test('kind vocabulary is exactly the server vocabulary, All kinds first', () { + expect(SearchKind.values.map((kind) => kind.wire), [ + '', + 'pipeline', + 'run', + 'step', + 'field', + 'artifact', + 'version', + ]); + expect(SearchKind.values.map((kind) => kind.label), [ + 'All kinds', + 'Pipelines', + 'Runs', + 'Steps', + 'Fields', + 'Artifacts', + 'Versions', + ]); + expect(SearchKind.fromWire('run'), SearchKind.run); + expect(SearchKind.fromWire(''), SearchKind.all); + expect(SearchKind.fromWire('prompts'), SearchKind.all); + expect(SearchKind.fromWire(null), SearchKind.all); + }); + + test('both type aliases and kinds are case insensitive', () { + for (final kind in SearchKind.values.where( + (kind) => kind != SearchKind.all, + )) { + for (final prefix in ['t', 'type', 'T', 'TyPe']) { + final parsed = parseSearchQuery( + '$prefix:${kind.wire.toUpperCase()} plan', + ); + expect(parsed.query, ' plan'); + expect(parsed.kind, kind); + expect(parsed.hasType, isTrue); + } + } + }); + + test('normal, quoted and unsupported text is preserved byte for byte', () { + const preserved = [ + ' ordinary text\twith\nspacing ', + '"t:pipeline" "hello world"', + "'type:artifact'", + '"escaped \\" t:run"', + '"unclosed t:run', + 't:prompt type:unknown t: t:PIPELINES', + 'not:t:run t:run,', + 'prefix"t:run"', + '\\t:run', + ]; + for (final query in preserved) { + final parsed = parseSearchQuery(query, SearchKind.field); + expect(parsed.query, query); + expect(parsed.kind, SearchKind.field); + expect(parsed.hasType, isFalse); + } + expect( + parseSearchQuery('t:artifact "t:pipeline" report').query, + ' "t:pipeline" report', + ); + }); + + test('last supported token wins over the selector; unknown tokens stay', () { + final parsed = parseSearchQuery( + 't:run plan TYPE:artifact t:unknown', + SearchKind.pipeline, + ); + expect(parsed.query, ' plan t:unknown'); + expect(parsed.kind, SearchKind.artifact); + expect(parsed.hasType, isTrue); + expect(parseSearchQuery('plan', SearchKind.step).kind, SearchKind.step); + }); + + test('type-only query is distinguishable from literal and blank input', () { + final typed = parseSearchQuery('t:pipeline'); + expect(typed.query, ''); + expect(typed.kind, SearchKind.pipeline); + expect(typed.hasType, isTrue); + final blank = parseSearchQuery(''); + expect(blank.query, ''); + expect(blank.kind, SearchKind.all); + expect(blank.hasType, isFalse); + }); + + test('blank text is sendable only with a supported nonempty kind', () { + for (final kind in SearchKind.values) { + expect(searchQuerySendable(' \n\t ', kind), kind != SearchKind.all); + } + expect(searchQuerySendable('', SearchKind.all), isFalse); + expect(searchQuerySendable('plan', SearchKind.all), isTrue); + expect(searchQuerySendable(' plan ', SearchKind.all), isTrue); + }); + + test( + 'failure copy distinguishes an unsupported server from a plain error', + () { + expect(searchFailureText(null), unsupported); + expect(searchFailureText(' '), unsupported); + expect(searchFailureText('unknown command: search'), unsupported); + expect(searchFailureText('unsupported command'), unsupported); + expect(searchFailureText('boom'), 'boom'); + expect( + searchFailureText('request timed out after 30000ms'), + 'request timed out after 30000ms', + ); + }, + ); +} diff --git a/app/test/features/search/search_repository_test.dart b/app/test/features/search/search_repository_test.dart new file mode 100644 index 00000000..1760b363 --- /dev/null +++ b/app/test/features/search/search_repository_test.dart @@ -0,0 +1,106 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/search/data/search_repository.dart'; +import 'package:pipelines_app/features/search/domain/search_models.dart'; + +class RecordingGateway implements ApiGateway { + String? type; + JsonMap fields = {}; + JsonMap reply = {}; + Object? failure; + + @override + Future call(String type, [JsonMap fields = const {}]) async { + this.type = type; + this.fields = Map.of(fields); + if (failure case final error?) throw error; + return reply; + } + + @override + Stream get frames => const Stream.empty(); +} + +void main() { + test( + 'search sends exactly search/query/kind/limit and parses bounds', + () async { + final gateway = RecordingGateway() + ..reply = { + 'search_results': { + 'query': 'plan', + 'kind': 'run', + 'results': [ + { + 'kind': 'run', + 'target': 'run:11', + 'run': {'id': 11}, + }, + ], + 'truncated': true, + 'scanned_steps': 27, + 'scanned_bytes': 4096, + 'cap': 50, + 'scan_bound_bytes': 1048576, + }, + }; + final repository = SearchRepository(gateway); + + final response = await repository.search( + query: 'plan', + kind: SearchKind.run, + ); + + expect(gateway.type, 'search'); + expect(gateway.fields, { + 'search': {'query': 'plan', 'kind': 'run', 'limit': 0}, + }); + expect(response, isNotNull); + expect(response!.query, 'plan'); + expect(response.kind, SearchKind.run); + expect(response.results.single['target'], 'run:11'); + expect(response.truncated, isTrue); + expect(response.scannedSteps, 27); + expect(response.scannedBytes, 4096); + expect(response.cap, 50); + expect(response.scanBoundBytes, 1048576); + }, + ); + + test('all-kinds search still sends the empty kind field', () async { + final gateway = RecordingGateway() + ..reply = { + 'search_results': {'results': []}, + }; + await SearchRepository(gateway).search(query: 'plan', kind: SearchKind.all); + expect(gateway.fields, { + 'search': {'query': 'plan', 'kind': '', 'limit': 0}, + }); + }); + + test( + 'a reply without search_results is null, not an empty success', + () async { + final gateway = RecordingGateway()..reply = {'type': 'pong'}; + final response = await SearchRepository( + gateway, + ).search(query: 'plan', kind: SearchKind.all); + expect(response, isNull); + }, + ); + + test('server refusals propagate to the caller unchanged', () async { + final gateway = RecordingGateway() + ..failure = StateError('permission denied'); + await expectLater( + SearchRepository(gateway).search(query: 'plan', kind: SearchKind.all), + throwsA( + isA().having( + (error) => error.message, + 'message', + 'permission denied', + ), + ), + ); + }); +} diff --git a/app/test/features/search/search_row_test.dart b/app/test/features/search/search_row_test.dart new file mode 100644 index 00000000..086f2246 --- /dev/null +++ b/app/test/features/search/search_row_test.dart @@ -0,0 +1,161 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/search/domain/search_row.dart'; + +JsonMap pipelineHit([JsonMap overrides = const {}]) => { + 'kind': 'pipeline', + 'target': 'pipeline:7', + 'pipeline': { + 'id': 7, + 'name': 'release', + 'version': 3, + 'stages': 4, + ...overrides, + }, +}; + +JsonMap versionHit() => { + 'kind': 'version', + 'target': 'pipeline:9:v2', + 'recency': '2026-01-01T00:00:00Z', + 'version': { + 'pipeline_id': 9, + 'version': 2, + 'content_hash': 'abc', + 'created_at': '2026-01-01T00:00:00Z', + }, +}; + +JsonMap runHit([JsonMap overrides = const {}]) => { + 'kind': 'run', + 'target': 'run:11', + 'run': { + 'id': 11, + 'pipeline_name': 'release', + 'status': 'succeeded', + 'created_at': '2026-01-01T00:00:00Z', + ...overrides, + }, +}; + +JsonMap stepHit([JsonMap overrides = const {}]) => { + 'kind': 'step', + 'target': 'run:11:4', + 'step': { + 'run_id': 11, + 'sequence': 4, + 'stage': 'builder', + 'visit': 2, + 'outcome': 'success', + ...overrides, + }, +}; + +JsonMap fieldHit([JsonMap overrides = const {}]) => { + 'kind': 'field', + 'target': 'run:11:4:output', + 'matched_field': 'output', + 'field': { + 'run_id': 11, + 'sequence': 4, + 'field': 'output', + 'snippet': 'the release is ready', + ...overrides, + }, +}; + +JsonMap artifactHit([JsonMap overrides = const {}]) => { + 'kind': 'artifact', + 'target': '/artifacts/11/4/notes.md', + 'artifact': { + 'run_id': 11, + 'sequence': 4, + 'name': 'notes.md', + 'content_type': 'text/markdown', + 'size_bytes': 2048, + ...overrides, + }, +}; + +void main() { + test('per-kind rows mirror the browser titles and secondary lines', () { + final pipeline = searchRowView(pipelineHit(), 'release'); + expect(pipeline.title, 'release'); + expect(pipeline.secondary, 'pipeline 7 · v3 · 4 stages'); + expect(pipeline.kindLabel, 'Pipeline'); + expect(pipeline.target, 'pipeline:7'); + + final blankName = searchRowView(pipelineHit({'name': ' '}), 'x'); + expect(blankName.title, 'pipeline 7'); + + final version = searchRowView(versionHit(), 'release'); + expect(version.title, 'pipeline 9 · v2'); + expect(version.secondary, startsWith('content abc · ')); + expect(version.recency, isNotNull); + + final run = searchRowView(runHit(), 'release'); + expect(run.title, 'run #11 · release'); + expect(run.secondary, startsWith('succeeded · ')); + expect(run.secondary.split(' · '), hasLength(2)); + + final unnamed = searchRowView(runHit({'pipeline_name': ''}), ''); + expect(unnamed.title, 'run #11'); + + final step = searchRowView(stepHit({'target': '#success'}), ''); + expect(step.title, 'run #11 · builder visit 2'); + expect(step.secondary, 'success · → #success'); + + final artifact = searchRowView(artifactHit(), 'notes'); + expect(artifact.title, 'notes.md'); + expect(artifact.secondary, 'run #11 · step 4 · text/markdown · 2.0 KiB'); + }); + + test('a field snippet marks the first case-insensitive query occurrence', () { + final row = searchRowView(fieldHit(), 'RELEASE'); + expect(row.snippet, 'the release is ready'); + expect(row.snippetSpans.map((span) => (span.text, span.matched)), [ + ('the ', false), + ('release', true), + (' is ready', false), + ]); + expect(row.snippetSpans.where((span) => span.matched), hasLength(1)); + + final absent = searchRowView(fieldHit({'snippet': 'no match'}), 'absent'); + expect(absent.snippetSpans.single.matched, isFalse); + expect(absent.snippetSpans.single.text, 'no match'); + + final blank = searchRowView(fieldHit({'snippet': ''}), 'release'); + expect(blank.snippetSpans, isEmpty); + }); + + test('unknown or targetless hits are read-only and never open a guess', () { + final unknown = searchRowView({ + 'kind': 'future_kind', + 'target': 'widget:7', + }, 'x'); + expect(unknown.title, 'widget:7'); + expect(unknown.secondary, 'kind "future_kind" · read-only'); + expect(unknown.openable, isFalse); + expect(unknown.target, isNull); + expect(unknown.kindLabel, 'Unrecognised result'); + + final targetless = searchRowView({ + 'kind': 'run', + 'run': {'id': 11}, + }, 'x'); + expect(targetless.openable, isFalse); + expect(targetless.target, isNull); + + expect(searchRowView(pipelineHit(), '').openable, isTrue); + expect(searchRowView(versionHit(), '').openable, isTrue); + expect(searchRowView(artifactHit(), '').openable, isTrue); + }); + + test('byte sizes use the shared binary rendering', () { + expect(humanBytes(0), '0 B'); + expect(humanBytes(1023), '1023 B'); + expect(humanBytes(1024), '1.0 KiB'); + expect(humanBytes(2048), '2.0 KiB'); + expect(humanBytes(1048576), '1.0 MiB'); + }); +} diff --git a/app/test/features/search/search_screen_states_test.dart b/app/test/features/search/search_screen_states_test.dart new file mode 100644 index 00000000..71292861 --- /dev/null +++ b/app/test/features/search/search_screen_states_test.dart @@ -0,0 +1,146 @@ +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/search/search_screen.dart'; + +class RecordingGateway implements ApiGateway { + RecordingGateway(this.reply); + + final JsonMap Function(String query, String kind) reply; + final calls = []; + + @override + Future call(String type, [JsonMap fields = const {}]) async { + calls.add(Map.of(fields)); + final search = Map.from(fields['search'] as Map); + return reply(search['query'] as String, search['kind'] as String); + } + + @override + Stream get frames => const Stream.empty(); +} + +JsonMap response( + List results, { + bool truncated = false, + int scannedSteps = 2, + int scannedBytes = 128, +}) => { + 'search_results': { + 'results': results, + 'truncated': truncated, + 'scanned_steps': scannedSteps, + 'scanned_bytes': scannedBytes, + 'cap': 50, + 'scan_bound_bytes': 1 << 20, + }, +}; + +final pipeline = { + 'kind': 'pipeline', + 'target': 'pipeline:7', + 'pipeline': {'id': 7, 'name': 'Release planner', 'version': 3, 'stages': 4}, +}; + +Widget material(Widget child) => MaterialApp(home: child); + +void main() { + testWidgets( + 'a fresh screen sends no request and idle is not an empty result', + (tester) async { + final gateway = RecordingGateway((_, _) => response([pipeline])); + await tester.pumpWidget( + material(SearchScreen(gateway: gateway, onOpen: (_) {})), + ); + + expect(gateway.calls, isEmpty); + expect( + find.text('Search pipelines, runs and artifacts.'), + findsOneWidget, + ); + expect(find.textContaining('No matches'), findsNothing); + }, + ); + + testWidgets('an empty server result shows the query-specific empty copy', ( + tester, + ) async { + final gateway = RecordingGateway((_, _) => response(const [])); + await tester.pumpWidget( + material(SearchScreen(gateway: gateway, onOpen: (_) {})), + ); + + await tester.enterText(find.byKey(const ValueKey('search.field')), 'zzz'); + await tester.pump(const Duration(milliseconds: 300)); + await tester.pumpAndSettle(); + + expect(gateway.calls, hasLength(1)); + expect(find.text('No matches for "zzz".'), findsOneWidget); + expect(find.text('Searching…'), findsNothing); + }); + + testWidgets( + 'a truncated empty reply keeps the server scan warning on screen', + (tester) async { + final gateway = RecordingGateway( + (_, _) => response( + const [], + truncated: true, + scannedSteps: 2000, + scannedBytes: 1048576, + ), + ); + await tester.pumpWidget( + material(SearchScreen(gateway: gateway, onOpen: (_) {})), + ); + + await tester.enterText( + find.byKey(const ValueKey('search.field')), + 'needle', + ); + await tester.pump(const Duration(milliseconds: 300)); + await tester.pumpAndSettle(); + + expect( + find.text('No matches for "needle" within the server\'s scan limit.'), + findsOneWidget, + ); + expect(find.textContaining('Results truncated'), findsOneWidget); + expect(find.textContaining('scanned 2000 steps'), findsOneWidget); + expect(find.textContaining('scan limit 1.0 MiB'), findsOneWidget); + }, + ); + + testWidgets('changing Kind clears a typed token and requests the new kind', ( + tester, + ) async { + tester.view.physicalSize = const Size(390, 844); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + final gateway = RecordingGateway((_, _) => response([pipeline])); + await tester.pumpWidget( + material(SearchScreen(gateway: gateway, onOpen: (_) {})), + ); + + await tester.enterText( + find.byKey(const ValueKey('search.field')), + 'plan t:run', + ); + await tester.pump(const Duration(milliseconds: 300)); + await tester.pumpAndSettle(); + expect((gateway.calls.single['search'] as Map)['kind'], 'run'); + + await tester.tap(find.byKey(const ValueKey('search.kind'))); + await tester.pumpAndSettle(); + await tester.tap(find.text('Pipelines').last); + await tester.pumpAndSettle(); + + final field = tester.widget( + find.byKey(const ValueKey('search.field')), + ); + expect(field.controller!.text.trim(), 'plan'); + expect(field.controller!.text, isNot(contains('t:run'))); + expect((gateway.calls.last['search'] as Map)['kind'], 'pipeline'); + }); +} diff --git a/app/test/features/search/search_screen_test.dart b/app/test/features/search/search_screen_test.dart new file mode 100644 index 00000000..7c1b7eeb --- /dev/null +++ b/app/test/features/search/search_screen_test.dart @@ -0,0 +1,223 @@ +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/search/domain/search_models.dart'; +import 'package:pipelines_app/features/search/search_screen.dart'; + +class ImmediateGateway implements ApiGateway { + ImmediateGateway(this.reply); + + final JsonMap Function(String query, String kind) reply; + final calls = []; + + @override + Future call(String type, [JsonMap fields = const {}]) async { + calls.add(Map.of(fields)); + final search = Map.from(fields['search'] as Map); + return reply(search['query'] as String, search['kind'] as String); + } + + @override + Stream get frames => const Stream.empty(); +} + +class FailingThenSucceedingGateway implements ApiGateway { + FailingThenSucceedingGateway(this.success); + + final JsonMap success; + var calls = 0; + + @override + Future call(String type, [JsonMap fields = const {}]) async { + calls++; + if (calls == 1) throw StateError('unknown command: search'); + return success; + } + + @override + Stream get frames => const Stream.empty(); +} + +JsonMap hit({ + required String kind, + required String target, + required Map payload, +}) => {'kind': kind, 'target': target, ...payload}; + +JsonMap response(List results) => { + 'search_results': { + 'results': results, + 'truncated': false, + 'scanned_steps': 4, + 'scanned_bytes': 512, + 'cap': 50, + 'scan_bound_bytes': 1 << 20, + }, +}; + +final pipeline = hit( + kind: 'pipeline', + target: 'pipeline:7', + payload: { + 'pipeline': {'id': 7, 'name': 'Release planner', 'version': 3, 'stages': 4}, + }, +); +final field = hit( + kind: 'field', + target: 'run:11:4:output', + payload: { + 'matched_field': 'output', + 'field': { + 'run_id': 11, + 'sequence': 4, + 'field': 'output', + 'snippet': 'the release is ready', + }, + }, +); + +void useNarrowSurface(WidgetTester tester) { + tester.view.physicalSize = const Size(390, 844); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); +} + +Widget largeText(Widget child) => MediaQuery( + data: const MediaQueryData(textScaler: TextScaler.linear(2)), + child: child, +); + +Future search(WidgetTester tester, String query) async { + await tester.enterText(find.byKey(const ValueKey('search.field')), query); + await tester.pump(const Duration(milliseconds: 300)); + await tester.pumpAndSettle(); +} + +void main() { + for (final width in [390.0, 1000.0]) { + testWidgets( + 'Material search is native and usable at width $width and 2x text', + (tester) async { + useNarrowSurface(tester); + tester.view.physicalSize = Size(width, 844); + final gateway = ImmediateGateway((_, _) => response([pipeline, field])); + JsonMap? opened; + await tester.pumpWidget( + MaterialApp( + home: largeText( + SearchScreen( + gateway: gateway, + onOpen: (value) => opened = value, + cupertino: false, + ), + ), + ), + ); + + expect(find.byType(SearchBar), findsOneWidget); + expect(find.byType(DropdownButton), findsOneWidget); + expect(find.text('All kinds'), findsOneWidget); + expect(gateway.calls, isEmpty); + + await search(tester, 'release'); + + expect(gateway.calls.single, { + 'search': {'query': 'release', 'kind': '', 'limit': 0}, + }); + expect(find.text('Release planner'), findsOneWidget); + expect(find.textContaining('the release is ready'), findsOneWidget); + expect(find.textContaining('4 results'), findsNothing); + expect(tester.takeException(), isNull); + + await tester.tap( + find.byKey(const ValueKey('search.result.pipeline:7')), + ); + expect(opened?['target'], 'pipeline:7'); + expect(opened?['kind'], 'pipeline'); + }, + ); + } + + testWidgets( + 'Cupertino search uses native controls and opens the real target', + (tester) async { + useNarrowSurface(tester); + final gateway = ImmediateGateway((_, _) => response([pipeline])); + JsonMap? opened; + await tester.pumpWidget( + CupertinoApp( + home: largeText( + SearchScreen( + gateway: gateway, + onOpen: (value) => opened = value, + cupertino: true, + ), + ), + ), + ); + + expect(find.byType(CupertinoSearchTextField), findsOneWidget); + await search(tester, 'release'); + + expect(find.text('Release planner'), findsOneWidget); + expect(tester.takeException(), isNull); + await tester.tap(find.byKey(const ValueKey('search.result.pipeline:7'))); + expect(opened?['target'], 'pipeline:7'); + }, + ); + + testWidgets('a read-only hit cannot be opened', (tester) async { + useNarrowSurface(tester); + final unknown = hit( + kind: 'future_kind', + target: 'widget:7', + payload: const {}, + ); + final gateway = ImmediateGateway((_, _) => response([unknown])); + JsonMap? opened; + await tester.pumpWidget( + MaterialApp( + home: SearchScreen( + gateway: gateway, + onOpen: (value) => opened = value, + cupertino: false, + ), + ), + ); + await search(tester, 'widget'); + + expect(find.textContaining('read-only'), findsOneWidget); + await tester.tap(find.byKey(const ValueKey('search.result.widget:7'))); + expect(opened, isNull); + }); + + testWidgets('an unsupported server shows its sentence and retry recovers', ( + tester, + ) async { + useNarrowSurface(tester); + final gateway = FailingThenSucceedingGateway(response([pipeline])); + await tester.pumpWidget( + MaterialApp( + home: SearchScreen(gateway: gateway, onOpen: (_) {}, cupertino: false), + ), + ); + await search(tester, 'release'); + + expect( + find.text( + 'This server does not support search. Update the Pipelines server, then try again.', + ), + findsOneWidget, + ); + expect(find.byKey(const ValueKey('search.retry')), findsOneWidget); + + await tester.tap(find.byKey(const ValueKey('search.retry'))); + await tester.pumpAndSettle(); + + expect(gateway.calls, 2); + expect(find.text('Release planner'), findsOneWidget); + expect(find.byKey(const ValueKey('search.retry')), findsNothing); + }); +} diff --git a/app/test/features/search/search_test_support.dart b/app/test/features/search/search_test_support.dart new file mode 100644 index 00000000..fdad7425 --- /dev/null +++ b/app/test/features/search/search_test_support.dart @@ -0,0 +1,50 @@ +import 'dart:async'; + +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/search/data/search_repository.dart'; +import 'package:pipelines_app/features/search/domain/search_controller.dart'; + +class QueuedGateway implements ApiGateway { + final calls = []; + final pending = >[]; + + @override + Future call(String type, [JsonMap fields = const {}]) { + calls.add(Map.of(fields)); + final completer = Completer(); + pending.add(completer); + return completer.future; + } + + @override + Stream get frames => const Stream.empty(); + + void succeed(int index, JsonMap reply) => pending[index].complete(reply); + void fail(int index, Object error) => pending[index].completeError(error); + + JsonMap get lastSearch => + Map.from((calls.last['search'] as Map)); +} + +JsonMap envelope( + List results, { + bool truncated = false, + int scannedSteps = 0, + int scannedBytes = 0, + int cap = 50, + int scanBoundBytes = 1 << 20, +}) => { + 'search_results': { + 'results': results, + 'truncated': truncated, + 'scanned_steps': scannedSteps, + 'scanned_bytes': scannedBytes, + 'cap': cap, + 'scan_bound_bytes': scanBoundBytes, + }, +}; + +OmniSearchController controllerFor(ApiGateway gateway) => OmniSearchController( + repository: SearchRepository(gateway), + debounce: Duration.zero, +); diff --git a/app/tool/search_fixture/main.dart b/app/tool/search_fixture/main.dart new file mode 100644 index 00000000..1328cd07 --- /dev/null +++ b/app/tool/search_fixture/main.dart @@ -0,0 +1,190 @@ +// Web-only fixture entrypoint for rendered search evidence. It is not part of +// the application's `main.dart`; build it explicitly with: +// flutter build web -t tool/search_fixture/main.dart +// `?cupertino=1` renders the same screen inside a CupertinoApp. +import 'dart:convert'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/search/search_screen.dart'; + +void main() { + final cupertino = Uri.base.queryParameters['cupertino'] == '1'; + runApp( + cupertino + ? const CupertinoApp( + title: 'Search fixture', + home: _FixtureHost(cupertino: true), + ) + : const MaterialApp( + title: 'Search fixture', + home: _FixtureHost(cupertino: false), + ), + ); +} + +class _FixtureHost extends StatelessWidget { + const _FixtureHost({required this.cupertino}); + + final bool cupertino; + + @override + Widget build(BuildContext context) => SearchScreen( + gateway: const _FixtureGateway(), + cupertino: cupertino, + onOpen: (hit) { + final route = cupertino + ? CupertinoPageRoute( + builder: (_) => _Opened(hit: hit, cupertino: true), + ) + : MaterialPageRoute( + builder: (_) => _Opened(hit: hit, cupertino: false), + ); + Navigator.of(context).push(route); + }, + ); +} + +class _Opened extends StatelessWidget { + const _Opened({required this.hit, required this.cupertino}); + + final JsonMap hit; + final bool cupertino; + + @override + Widget build(BuildContext context) { + final body = Center( + child: Padding( + padding: const EdgeInsets.all(24), + child: Text( + 'Opened ${hit['kind']} target: ${hit['target']}', + textAlign: TextAlign.center, + ), + ), + ); + if (cupertino) { + return CupertinoPageScaffold( + navigationBar: const CupertinoNavigationBar(middle: Text('Opened')), + child: body, + ); + } + return Scaffold( + appBar: AppBar(title: const Text('Opened')), + body: body, + ); + } +} + +class _FixtureGateway implements ApiGateway { + const _FixtureGateway(); + + @override + Future call(String type, [JsonMap fields = const {}]) async { + if (type != 'search') throw StateError('unexpected request: $type'); + final request = Map.from(fields['search'] as Map); + final query = '${request['query'] ?? ''}'.trim().toLowerCase(); + final kind = '${request['kind'] ?? ''}'; + await Future.delayed(const Duration(milliseconds: 180)); + var hits = _fixtureHits + .where((hit) { + if (kind.isNotEmpty && hit['kind'] != kind) return false; + if (query.isEmpty) return true; + return jsonEncode(hit).toLowerCase().contains(query); + }) + .toList(growable: false); + return { + 'search_results': { + 'query': request['query'], + 'kind': kind, + 'results': hits, + 'truncated': true, + 'scanned_steps': 2000, + 'scanned_bytes': 1048576, + 'cap': 50, + 'scan_bound_bytes': 1048576, + }, + }; + } + + @override + Stream get frames => const Stream.empty(); +} + +const _fixtureHits = [ + { + 'kind': 'pipeline', + 'target': 'pipeline:24', + 'score': 3, + 'recency': '2026-10-20T09:18:00Z', + 'pipeline': {'id': 24, 'name': 'Plan and land', 'version': 5, 'stages': 4}, + }, + { + 'kind': 'run', + 'target': 'run:457', + 'score': 2, + 'recency': '2026-10-20T08:42:00Z', + 'run': { + 'id': 457, + 'pipeline_name': 'Plan and land', + 'status': 'succeeded', + 'workspace': '/Users/alan/repos/pipelines', + 'created_at': '2026-10-20T08:12:00Z', + 'finished_at': '2026-10-20T08:42:00Z', + }, + }, + { + 'kind': 'field', + 'target': 'run:457:3:input', + 'score': 1, + 'matched_field': 'input', + 'recency': '2026-10-20T08:20:00Z', + 'field': { + 'run_id': 457, + 'sequence': 3, + 'field': 'input', + 'snippet': 'Plan the change before implementing it', + }, + }, + { + 'kind': 'artifact', + 'target': '/artifacts/457/2/plan.md', + 'score': 1, + 'recency': '2026-10-20T08:24:00Z', + 'artifact': { + 'run_id': 457, + 'sequence': 2, + 'name': 'plan.md', + 'content_type': 'text/markdown', + 'size_bytes': 2048, + 'url': '/artifacts/457/2/plan.md', + }, + }, + { + 'kind': 'version', + 'target': 'pipeline:22:v6', + 'score': 2, + 'recency': '2026-10-18T16:05:00Z', + 'version': { + 'pipeline_id': 22, + 'version': 6, + 'content_hash': '9f2c1ad', + 'created_at': '2026-10-18T16:05:00Z', + }, + }, + { + 'kind': 'step', + 'target': 'run:457:1', + 'score': 1, + 'recency': '2026-10-20T08:14:00Z', + 'step': { + 'run_id': 457, + 'sequence': 1, + 'stage': 'planner', + 'visit': 1, + 'outcome': 'success', + 'target': '#success', + 'diagnostic': 'plan accepted', + }, + }, +]; diff --git a/app/tool/search_probe.mjs b/app/tool/search_probe.mjs new file mode 100644 index 00000000..172efb1f --- /dev/null +++ b/app/tool/search_probe.mjs @@ -0,0 +1,246 @@ +// Real Chrome evidence for the Flutter search screen. Serves the fixture build +// from build/web on an OS-assigned loopback port and drives the page through +// Chrome DevTools Protocol, like tool/shell_probe.mjs. Usage: +// flutter build web -t tool/search_fixture/main.dart +// OPENCODE_ARTIFACT_DIR= node tool/search_probe.mjs +import { createServer } from 'node:http'; +import { readFile, mkdtemp, 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 { join, extname, resolve, sep } from 'node:path'; +import { tmpdir } from 'node:os'; + +const root = join(process.cwd(), 'build/web'); +const artifactDir = process.env.OPENCODE_ARTIFACT_DIR; +if (!artifactDir) throw new Error('OPENCODE_ARTIFACT_DIR is required for captures'); +const mime = { + '.html': 'text/html', + '.js': 'text/javascript', + '.json': 'application/json', + '.wasm': 'application/wasm', + '.png': 'image/png', + '.ico': 'image/x-icon', + '.ttf': 'font/ttf', + '.otf': 'font/otf', +}; +const server = createServer(async (req, res) => { + try { + const path = resolve( + root, + '.' + decodeURIComponent(new URL(req.url, 'http://localhost').pathname), + ); + if (path !== root && !path.startsWith(root + sep)) { + return res.writeHead(403).end(); + } + const filePath = + path === root || path.endsWith('/') ? join(path, 'index.html') : path; + 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 port = server.address().port; +const profile = await mkdtemp(join(tmpdir(), 'x1-search-chrome-')); +const chrome = spawn( + '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', + [ + '--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) => { + for (let i = 0; i < 100; i++) { + const value = await fn(); + if (value) return value; + await delay(100); + } + throw new Error('Timed out waiting for Chrome DevTools'); +}; +const result = { captures: [], evidence: {} }; +let ws; +try { + const endpoint = await waitFor(() => + stderr.match(/DevTools listening on (ws:\/\/[^\s]+)/)?.[1], + ); + ws = new WebSocket(endpoint); + await once(ws, 'open'); + let id = 0; + const pending = new Map(); + ws.addEventListener('message', (event) => { + const msg = JSON.parse(event.data); + if (msg.id && pending.has(msg.id)) { + pending.get(msg.id)(msg); + pending.delete(msg.id); + } + }); + const send = (method, params = {}, sessionId) => + new Promise((resolve) => { + const callId = ++id; + pending.set(callId, resolve); + 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 target = created.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)}`); + } + return response.result?.result?.value; + }; + const clickMatching = (needle) => + evaluate(`(() => { + const needle = ${JSON.stringify(needle)}; + const nodes = [...document.querySelectorAll('flt-semantics')]; + const e = nodes.find(x => x.hasAttribute('flt-tappable') && + (x.getAttribute('aria-label') || x.innerText || '').includes(needle)); + if (!e) return false; + e.click(); + return true; + })()`); + const capture = async (name, width, height) => { + await send( + 'Emulation.setDeviceMetricsOverride', + { width, height, deviceScaleFactor: 1, mobile: width < 600 }, + session, + ); + await delay(350); + const data = ( + await send( + 'Page.captureScreenshot', + { format: 'png', captureBeyondViewport: false }, + session, + ) + ).result.data; + const path = join(artifactDir, `${name}.png`); + await writeFile(path, Buffer.from(data, 'base64')); + result.captures.push(path); + }; + const load = async (url, width, height) => { + await send( + 'Emulation.setDeviceMetricsOverride', + { width, height, deviceScaleFactor: 1, mobile: width < 600 }, + session, + ); + const navigation = await send('Page.navigate', { url }, session); + if (navigation.error || navigation.result?.errorText) throw new Error(JSON.stringify(navigation)); + await delay(3500); + await evaluate("document.querySelector('flt-semantics-placeholder')?.click()"); + await delay(900); + }; + const typeText = async (query) => { + const focused = await evaluate(`(() => { + const input = document.querySelector('input[type="search"]') || document.querySelector('input.flt-text-editing'); + if (!input) return false; input.focus(); return true; })()`); + if (!focused) throw new Error('Search input not found'); + await delay(400); + const inserted = await send('Input.insertText', { text: query }, session); + if (inserted.error) throw new Error(JSON.stringify(inserted)); + await delay(1400); + return (await evaluate('document.body.innerText')).trim(); + }; + const typeQuery = async (query) => { + const trimmed = await typeText(query); + if (!trimmed.includes('Plan and land')) { + throw new Error(`Results missing after typing: ${JSON.stringify(trimmed)}`); + } + return { + typed: query, + resultTitles: ['Plan and land', 'run #457 · Plan and land', 'run #457 · step 3 · input', + 'plan.md', 'run #457 · planner visit 1'].filter((title) => trimmed.includes(title)), + showsServerSnippet: trimmed.includes('Plan the change before implementing it'), + showsRecency: /\d{1,2} [A-Z][a-z]{2} \d{2}:\d{2}/.test(trimmed), + showsBounds: + trimmed.includes('Results truncated') && + trimmed.includes('cap 50') && + trimmed.includes('scanned 2000 steps'), + }; + }; + const typeTruncatedEmpty = async (query) => { + const text = await typeText(query); + const emptyCopy = `No matches for "${query}" within the server's scan limit.`; + const missing = [ + emptyCopy, 'Results truncated', '0 results', + 'scanned 2000 steps', 'scan limit 1.0 MiB', + ].filter((needle) => !text.includes(needle)); + if (missing.length) throw new Error(`Truncated empty missing ${JSON.stringify(missing)}`); + return { typed: query, emptyCopy, showsTruncationWarning: true, showsBounds: true }; + }; + + const base = `http://127.0.0.1:${port}/`; + await load(base, 390, 844); + result.evidence.materialPhone = await typeQuery('plan'); + await capture('x1-search-material-phone', 390, 844); + if (!(await clickMatching('Plan and land'))) { + throw new Error('Could not open the pipeline row'); + } + await delay(700); + const opened = await evaluate('document.body.innerText'); + if (!opened.includes('pipeline:24')) { + throw new Error(`Opened target missing: ${JSON.stringify(opened)}`); + } + result.evidence.opened = 'pipeline:24'; + await capture('x1-search-open-target', 390, 844); + + await load(base, 1280, 800); + result.evidence.materialDesktop = await typeQuery('plan'); + await capture('x1-search-material-desktop', 1280, 800); + + await load(`${base}?cupertino=1`, 390, 844); + result.evidence.cupertinoPhone = await typeQuery('plan'); + await capture('x1-search-cupertino-phone', 390, 844); + + await load(base, 390, 844); + result.evidence.materialTruncatedEmpty = await typeTruncatedEmpty('needle'); + await capture('x1-search-truncated-empty', 390, 844); + + await load(`${base}?cupertino=1`, 390, 844); + result.evidence.cupertinoTruncatedEmpty = + await typeTruncatedEmpty('needle'); + await capture('x1-search-truncated-empty-cupertino', 390, 844); + + console.log(JSON.stringify(result, 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 }); +} From ceffd5d0d1e150548abd4f8c01cb1da5f3adfee5 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 16:59:07 +0100 Subject: [PATCH 18/18] fix(stage): retain inline audit payloads once without losing native evidence --- .../session-export-inline-attachments.md | 26 +++++++ internal/stage/session_export.go | 21 +++++- internal/stage/session_export_inline_test.go | 68 +++++++++++++++++++ 3 files changed, 113 insertions(+), 2 deletions(-) create mode 100644 docs/notes/session-export-inline-attachments.md create mode 100644 internal/stage/session_export_inline_test.go diff --git a/docs/notes/session-export-inline-attachments.md b/docs/notes/session-export-inline-attachments.md new file mode 100644 index 00000000..4c03d10e --- /dev/null +++ b/docs/notes/session-export-inline-attachments.md @@ -0,0 +1,26 @@ +# Complete visual audit exports without duplicate inline payloads + +Run34 visit3 retained a complete, untruncated native session (71 messages, +4,196,297 decoded native bytes), but the HTML audit exceeded the8MiB render cap. +The readable tool projection printed47 inline `data:` attachment URIs as text, +duplicating3,752,634 bytes already stored in complete native message records. + +The renderer now summarizes an inline attachment in the readable projection +ONLY when its exact URI bytes also occur in that message's retained native +record. The complete native JSON remains unchanged and HTML-escaped. If the +native record is absent or does not contain the payload, the original full +projection is kept; there is no evidence loss or fabricated completeness. + +No source/render/artifact bound is raised. All remain at their existing limits, +and genuinely oversized exports still report partial/truncated. No HTML is +executed from the attachment; MIME labels and native data stay escaped. + +Read-only scratch export of the exact original visual-review session now +produces4,676,544 bytes,71 messages, `truncated:false`. Production originals and +checkpoints were not overwritten by this proof. + +Regressions cover a4MiB inline payload retained exactly once, fallback when no +native copy exists, and escaped/unescaped hostile native JSON/MIME values. The +full Go suite passes with the unrelated notification-test URL env isolated. +Installation remains deferred until a quiescent service window; no active run +may be interrupted just to activate this correction. diff --git a/internal/stage/session_export.go b/internal/stage/session_export.go index 2c752c5c..f7562b2d 100644 --- a/internal/stage/session_export.go +++ b/internal/stage/session_export.go @@ -262,7 +262,11 @@ func renderHTMLMessage(out *bytes.Buffer, index int, message opencode.ExportedMe fmt.Fprintf(out, "

id: %s | model: %s | agent: %s | created_at: %d

\n", html.EscapeString(message.ID), html.EscapeString(message.Model), html.EscapeString(message.Agent), message.CreatedAt) for _, part := range message.Parts { - renderHTMLPart(out, part) + if part.Type == protocol.ChatPartTool { + renderHTMLToolWithNativeRecord(out, part, message.Raw) + } else { + renderHTMLPart(out, part) + } } // The readable projection is not the complete native record: tools can // carry inline images and provider-specific metadata absent from ChatPart. @@ -297,6 +301,10 @@ func renderHTMLPart(out *bytes.Buffer, part opencode.ExportedPart) { // renderHTMLTool renders a tool call with its name, status, input, result and // error, escaping every value. func renderHTMLTool(out *bytes.Buffer, part opencode.ExportedPart) { + renderHTMLToolWithNativeRecord(out, part, nil) +} + +func renderHTMLToolWithNativeRecord(out *bytes.Buffer, part opencode.ExportedPart, native []byte) { name := part.Name if name == "" { name = part.ID @@ -316,7 +324,16 @@ func renderHTMLTool(out *bytes.Buffer, part opencode.ExportedPart) { if content.Text != "" { fmt.Fprintf(out, "
%s
\n", html.EscapeString(content.Text)) } else if content.URI != "" { - fmt.Fprintf(out, "

%s (%s)

\n", html.EscapeString(content.URI), html.EscapeString(content.Mime)) + // Inline screenshot/file data is already retained verbatim in the + // complete native record. Printing megabytes of base64 again as a + // paragraph adds no readable evidence and can truncate the whole + // audit. Summarize only when that exact payload is demonstrably in + // this message's native bytes; otherwise preserve the old full output. + if len(content.URI) >= 5 && strings.EqualFold(content.URI[:5], "data:") && bytes.Contains(native, []byte(content.URI)) { + fmt.Fprintf(out, "

Inline attachment (%s): complete payload retained in the native message below.

\n", html.EscapeString(content.Mime)) + } else { + fmt.Fprintf(out, "

%s (%s)

\n", html.EscapeString(content.URI), html.EscapeString(content.Mime)) + } } } if part.State.Error != nil { diff --git a/internal/stage/session_export_inline_test.go b/internal/stage/session_export_inline_test.go new file mode 100644 index 00000000..87249d51 --- /dev/null +++ b/internal/stage/session_export_inline_test.go @@ -0,0 +1,68 @@ +package stage + +import ( + "encoding/json" + "html" + "strconv" + "strings" + "testing" + + "git.a-wan.net/alan/pipelines/internal/opencode" + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +func inlineSession(uri string, native json.RawMessage) opencode.ExportedSession { + return opencode.ExportedSession{ID: "ses_inline", Backend: "v2", Messages: []opencode.ExportedMessage{{ + ID: "message_inline", Role: "assistant", Raw: native, + Parts: []opencode.ExportedPart{{Type: protocol.ChatPartTool, Name: "screenshot", State: &protocol.ChatToolState{ + Content: []protocol.ChatToolContent{{URI: uri, Mime: "image/png"}}, + }}}, + }}} +} + +func TestSessionExportRetainsLargeInlinePayloadOnceWithoutRaisingBounds(t *testing.T) { + uri := "data:image/png;base64," + strings.Repeat("A", 4<<20) + native, err := json.Marshal(map[string]any{"id": "message_inline", "image": uri, "future_field": "retained"}) + if err != nil { + t.Fatal(err) + } + doc, truncated := renderSessionHTML(inlineSession(uri, native), SessionExportRequest{}) + if truncated || len(doc) > SessionExportFileLimit { + t.Fatalf("complete native screenshot was truncated by duplicate projection: bytes=%d", len(doc)) + } + if strings.Count(doc, uri) != 1 || !strings.Contains(html.UnescapeString(doc), string(native)) { + t.Fatal("exact native payload was lost or duplicated") + } + if !strings.Contains(doc, "complete payload retained in the native message below") || strings.Contains(doc, "TRUNCATED") { + t.Fatal("inline projection did not accurately describe retained complete evidence") + } +} + +func TestSessionExportNeverSummarizesInlinePayloadAbsentFromNativeRecord(t *testing.T) { + uri := "data:image/png;base64,AAAA" + for _, native := range []json.RawMessage{nil, json.RawMessage(`{"unrelated":"record"}`)} { + doc, truncated := renderSessionHTML(inlineSession(uri, native), SessionExportRequest{}) + if truncated || !strings.Contains(doc, uri) || strings.Contains(doc, "class=\"inline-attachment\"") { + t.Fatal("inline payload without a complete native copy was omitted") + } + } +} + +func TestSessionExportInlineProjectionDoesNotCreateExecutableMarkup(t *testing.T) { + uri := `data:text/html,` + native, err := json.Marshal(map[string]string{"attachment": uri}) + if err != nil { + t.Fatal(err) + } + // Cover both escaped and unescaped native JSON encodings: only the latter + // contains the literal URI and therefore takes the new summary path. + plain := json.RawMessage(`{"attachment":` + strconv.Quote(uri) + `}`) + for _, raw := range []json.RawMessage{native, plain} { + session := inlineSession(uri, raw) + session.Messages[0].Parts[0].State.Content[0].Mime = `image/png">` + doc, _ := renderSessionHTML(session, SessionExportRequest{}) + if strings.Contains(doc, "