From 1835bc88327a8ebb83a9496588d67eaf54174d1d Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 22 Oct 2026 00:50:04 +0100 Subject: [PATCH 01/13] docs(app): record saved schedules in the pipeline detail --- app/PARITY.md | 2 +- app/WORK.md | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/app/PARITY.md b/app/PARITY.md index a586fb9a..887dae01 100644 --- a/app/PARITY.md +++ b/app/PARITY.md @@ -50,7 +50,7 @@ or scratch servers only, never real operator sessions/runs/workflows. | Chat model/Info/background tasks | Source request facade | current-model selection, numeric Info modal (unknown !=0), bounded running shell pages | | Chat commands/notices/scroll | Missing | slash palette/actions, unknown-command send-as-message, dismissible local notices, saved scroll/follow intent | | Saved schedule list | Source | pipeline entry and route registration, exact timer provenance vocabulary | -| Schedule editor | Source draft74+CAS guard; active form78 | save/pause/delete wiring, conflict keeps draft, Schedule this run seed | +| Schedule editor | Preview: pipeline Summary section creates/edits/pauses/deletes with the lossless draft and revision guard; conflict keeps the draft and shows the server words | Schedule-this-run seeding, schedules list entry/route | | Search | Preview: shell entry, /search route, focused field, restore on close | result target routing for pipeline/version/field/visit/artifact hits | | Needs you | Source model + native bell/sheet; wiring90 | in-app count from list rows, dismiss persistence and live transitions | | Notifications | Missing | explicit permission/rationale, secure/unsupported/denied states, transition-only dedupe, background question notices | diff --git a/app/WORK.md b/app/WORK.md index 6a674978..590c0a99 100644 --- a/app/WORK.md +++ b/app/WORK.md @@ -62,7 +62,8 @@ All work under app/. Existing applications remain running and unchanged. | Search entry | Register Search in the shell | run88 retained/fd380ef | server storage bug blocked the run; manager ran45 tests + real-app probe; route restores prior screen | merged main; ancestry verified | published8096 | | Run graph | Run-mode executed-route canvas | run89 retained/5b833e7 | server storage bug blocked the run; manager ran43 graph tests; recorded visits only, legend | merged main; ancestry verified | published8096 | | Run graph tab | Graph tab + recorded-stage selection | run92 retained/d74e5c5 | evidence bug blocked the run; manager ran147 runs tests + both-host probe (7 checks, graph/legend/selection/missing wording) | merged main; ancestry verified | preview republish pending | -| Schedule form | Native schedule draft editor | run78 /flutter/schedule-form | binds74, no save engine | running | pending | +| Schedule form | Native schedule draft editor | run78 /flutter/schedule-form | binds74, no save engine | merged main; ancestry verified | published8096 | +| Pipeline schedules | Saved schedules in pipeline Summary | run93 /ea2179cd | evidence bug blocked the run after commit; manager ran141 schedules/pipelines tests + 15-check/13-capture both-host probe; create/edit/pause/delete with CAS | merged main; ancestry verified | preview republish pending | ## Next ready work ### Current execution target (user correction) From a309d9d571ff1444c9c51fe7fffaa4550fe00b8a Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 22 Oct 2026 00:52:06 +0100 Subject: [PATCH 02/13] feat(app): show the live Needs-you bell over the Runs list rows --- app/PARITY.md | 2 +- .../runtime/attention_controller.dart | 179 +++++++++++++ .../attention/runtime/attention_store.dart | 82 ++++++ .../attention/ui/needs_you_runs_heading.dart | 118 +++++++++ app/lib/features/runs/screen.dart | 16 +- app/lib/features/runs/ui/runs_filters.dart | 138 ++++++++++ app/lib/features/runs/ui/runs_list.dart | 146 +++------- app/notes/attention-wiring.md | 84 ++++++ .../runtime/attention_controller_test.dart | 250 ++++++++++++++++++ .../runtime/attention_runs_layout_test.dart | 72 +++++ .../runtime/attention_runs_test_support.dart | 125 +++++++++ .../runtime/attention_runs_wiring_test.dart | 196 ++++++++++++++ .../runtime/attention_store_test.dart | 36 +++ app/tool/attention_wiring_probe.mjs | 220 +++++++++++++++ app/tool/runs_probe_server.mjs | 20 +- 15 files changed, 1557 insertions(+), 127 deletions(-) create mode 100644 app/lib/features/attention/runtime/attention_controller.dart create mode 100644 app/lib/features/attention/runtime/attention_store.dart create mode 100644 app/lib/features/attention/ui/needs_you_runs_heading.dart create mode 100644 app/lib/features/runs/ui/runs_filters.dart create mode 100644 app/notes/attention-wiring.md create mode 100644 app/test/features/attention/runtime/attention_controller_test.dart create mode 100644 app/test/features/attention/runtime/attention_runs_layout_test.dart create mode 100644 app/test/features/attention/runtime/attention_runs_test_support.dart create mode 100644 app/test/features/attention/runtime/attention_runs_wiring_test.dart create mode 100644 app/test/features/attention/runtime/attention_store_test.dart create mode 100644 app/tool/attention_wiring_probe.mjs diff --git a/app/PARITY.md b/app/PARITY.md index 887dae01..8629d62a 100644 --- a/app/PARITY.md +++ b/app/PARITY.md @@ -52,7 +52,7 @@ or scratch servers only, never real operator sessions/runs/workflows. | Saved schedule list | Source | pipeline entry and route registration, exact timer provenance vocabulary | | Schedule editor | Preview: pipeline Summary section creates/edits/pauses/deletes with the lossless draft and revision guard; conflict keeps the draft and shows the server words | Schedule-this-run seeding, schedules list entry/route | | Search | Preview: shell entry, /search route, focused field, restore on close | result target routing for pipeline/version/field/visit/artifact hits | -| Needs you | Source model + native bell/sheet; wiring90 | in-app count from list rows, dismiss persistence and live transitions | +| Needs you | Preview: runs-list bell/count, native sheet, open/dismiss/clear persistence, live fold and reconnect reseed | notification transitions/permission, authenticated preview smoke | | Notifications | Missing | explicit permission/rationale, secure/unsupported/denied states, transition-only dedupe, background question notices | | Mobile replacement build | Scaffold only | Android build at end; all source portable to iOS, isolated IDs; device/OS behavior clearly separate | diff --git a/app/lib/features/attention/runtime/attention_controller.dart b/app/lib/features/attention/runtime/attention_controller.dart new file mode 100644 index 00000000..d80e3fcc --- /dev/null +++ b/app/lib/features/attention/runtime/attention_controller.dart @@ -0,0 +1,179 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; + +import '../../../core/api_gateway.dart'; +import '../../runs/domain/run_events.dart'; +import '../domain/attention_models.dart'; +import '../domain/attention_transitions.dart'; +import 'attention_store.dart'; + +/// The live `Needs you` state behind the Runs-list bell. +/// +/// Entries are derived from the same `list_runs` rows the Runs destination +/// already holds: no poll and no extra request is made here. Pushed +/// `run_event` frames are folded with the runs feature's own [foldRunEvent], so +/// a run that becomes failed or waiting while the screen is open appears without +/// a reload, exactly as the browser's attention surface does. +/// +/// Dismissals are kept in memory for immediate feedback and written through +/// [AttentionStore] without blocking the caller. A failed read or write leaves +/// the in-memory set in force for this session; neither direction can throw into +/// the UI. +class AttentionController extends ChangeNotifier { + AttentionController({required this.store, DateTime Function()? now}) + : _now = now ?? DateTime.now; + + final AttentionStore store; + final DateTime Function() _now; + final AttentionTransitionDetector _detector = AttentionTransitionDetector(); + final List _transitions = []; + + List _rows = const []; + Set _dismissed = {}; + bool _loaded = false; + bool _dirty = false; + bool _disposed = false; + + /// The summaries the surface currently draws from. + List get rows => _rows; + + /// The identities the operator has dismissed in this session or storage. + Set get dismissed => {..._dismissed}; + + /// True once the persisted set has been read (successfully or not). + bool get loaded => _loaded; + + /// Transition facts raised by pushed frames, kept for notification wiring. + List get transitions => + List.unmodifiable(_transitions); + + /// Today's ordered rows, minus explicitly dismissed identities. + /// + /// The local-day cutoff is the model's [startOfLocalDay]: yesterday's failures + /// are history, not a badge that follows every device for ever. A caller that + /// needs a different window should use [entriesSince] rather than a second + /// ordering implementation. + List get entries => + entriesSince(startOfLocalDay(now: _now())); + + /// The ordered rows within an explicit [since] window. + List entriesSince(DateTime? since) => + attentionEntries(_rows, dismissed: _dismissed, since: since); + + /// Reads the persisted dismissals once. Unreadable storage means "none". + Future load() async { + Set stored; + try { + stored = decodeAttentionDismissals(await store.read()); + } catch (_) { + stored = {}; + } + if (_disposed) return; + _loaded = true; + // A dismissal made while the read was in flight must not be reverted by the + // older stored value; the in-memory set is the operator's latest intent. + if (!_dirty) _dismissed = stored; + notifyListeners(); + } + + /// Replaces the drawn rows with an authoritative read. + /// + /// The transition detector is seeded rather than observed, so the initial list + /// and a reconnect cannot announce work that was already there. With + /// [reconnect] the status baseline is dropped first, while emitted keys are + /// retained by the model so the gap cannot re-notify. + void seedRows(Iterable rows, {bool reconnect = false}) { + if (_disposed) return; + _rows = List.unmodifiable(rows); + if (reconnect) { + _detector.reseed(_rows); + } else { + _detector.seed(_rows); + } + notifyListeners(); + } + + /// Called when the shared socket drops, before the next [seedRows]. + void resetForReconnect() { + if (_disposed) return; + _detector.resetForReconnect(); + } + + /// Folds one pushed run summary into the drawn entries. + /// + /// A frame that cannot build a complete summary asks the Runs controller for + /// its usual resync; this surface never issues a request of its own. The + /// transition (if any) is recorded for the notification wiring but a dismissed + /// identity never emits. + void observeFrame(JsonMap frame) { + if (_disposed) return; + final transition = _detector.observe(frame, dismissed: _dismissed); + if (transition != null) _transitions.add(transition); + final folded = foldRunEvent(_rows, frame); + final changed = !folded.needsResync && !identical(folded.runs, _rows); + if (changed) { + _rows = List.unmodifiable( + _withAttentionText(folded.runs, frame), + ); + } + if (changed || transition != null) notifyListeners(); + } + + /// The runs fold deliberately carries only lifecycle fields, but the attention + /// row's wording comes from `title`/`name`/`diagnostic`. Keep those summary + /// fields from the same push so a failure announces its real reason without + /// waiting for the next list read. Only non-blank pushed values win; the source + /// or other unknown fields are left untouched. + List _withAttentionText(List rows, JsonMap frame) { + final id = frame['run_id']; + final index = rows.indexWhere((row) => row['id'] == id); + if (index < 0) return rows; + final current = rows[index]; + final merged = {...current}; + var changed = false; + for (final key in const ['title', 'name', 'diagnostic']) { + final value = frame[key]; + if ('${value ?? ''}'.trim().isEmpty || value == current[key]) continue; + merged[key] = value; + changed = true; + } + if (!changed) return rows; + final next = [...rows]; + next[index] = merged; + return next; + } + + /// Dismisses exactly one identity and persists the new set. + /// + /// The in-memory set and the bell update before the store is touched, so a + /// slow or failed write never blocks the sheet. The returned future reports + /// whether the write succeeded; callers that do not need it may ignore it. + Future dismiss(AttentionEntry entry) => + _commit(attentionDismiss(_dismissed, entry.key)); + + /// Applies only the identities captured when the sheet opened. + Future clearAll(Iterable snapshot) => + _commit(attentionDismissAll(_dismissed, snapshot)); + + Future _commit(Set next) async { + final unchanged = + next.length == _dismissed.length && next.containsAll(_dismissed); + if (unchanged) return true; + _dismissed = next; + _dirty = true; + notifyListeners(); + if (_disposed) return false; + try { + return await store.write(encodeAttentionDismissals(_dismissed)); + } catch (_) { + return false; + } + } + + @override + void dispose() { + _disposed = true; + super.dispose(); + } +} diff --git a/app/lib/features/attention/runtime/attention_store.dart b/app/lib/features/attention/runtime/attention_store.dart new file mode 100644 index 00000000..fe9d4095 --- /dev/null +++ b/app/lib/features/attention/runtime/attention_store.dart @@ -0,0 +1,82 @@ +import 'package:shared_preferences/shared_preferences.dart'; + +import '../domain/attention_models.dart'; + +/// The persistence seam for the `Needs you` dismissal identities. +/// +/// The controller only ever hands over the exact string produced by +/// [encodeAttentionDismissals], so a store cannot invent a different identity +/// format. Both directions are allowed to fail: a caller treats a null read as +/// "nothing dismissed yet" and a false write as "this session only". +abstract interface class AttentionStore { + Future read(); + + Future write(String value); +} + +/// `shared_preferences` storage under the attention model's own key. +/// +/// Reads and writes are total: an unavailable plugin, a disabled store or a full +/// disk returns null/false instead of throwing into the caller's frame. Only the +/// documented [attentionStorageKey] is touched, never the legacy web key. +class SharedPreferencesAttentionStore implements AttentionStore { + const SharedPreferencesAttentionStore(); + + Future _preferences() async { + try { + return await SharedPreferences.getInstance(); + } catch (_) { + return null; + } + } + + @override + Future read() async { + final preferences = await _preferences(); + if (preferences == null) return null; + try { + return preferences.getString(attentionStorageKey); + } catch (_) { + return null; + } + } + + @override + Future write(String value) async { + final preferences = await _preferences(); + if (preferences == null) return false; + try { + return await preferences.setString(attentionStorageKey, value); + } catch (_) { + return false; + } + } +} + +/// An in-memory store for tests and isolated fixtures. +/// +/// It never touches the platform store, so a probe or widget test cannot mutate +/// a real operator's persisted dismissals. [failReads] and [failWrites] reproduce +/// an unavailable store without throwing. +class MemoryAttentionStore implements AttentionStore { + MemoryAttentionStore({this.stored}); + + String? stored; + bool failReads = false; + bool failWrites = false; + int writes = 0; + + @override + Future read() async { + if (failReads) throw StateError('attention store unavailable'); + return stored; + } + + @override + Future write(String value) async { + writes++; + if (failWrites) throw StateError('attention store is read-only'); + stored = value; + return true; + } +} diff --git a/app/lib/features/attention/ui/needs_you_runs_heading.dart b/app/lib/features/attention/ui/needs_you_runs_heading.dart new file mode 100644 index 00000000..bf8889f1 --- /dev/null +++ b/app/lib/features/attention/ui/needs_you_runs_heading.dart @@ -0,0 +1,118 @@ +import 'dart:async'; + +import 'package:flutter/widgets.dart'; + +import '../../../core/api_gateway.dart'; +import '../domain/attention_models.dart'; +import '../runtime/attention_controller.dart'; +import '../runtime/attention_store.dart'; +import 'needs_you_bell.dart'; + +/// The `Needs you` bell as it appears in the Runs list heading. +/// +/// It owns the live attention state for this destination: [rows] are the +/// already-loaded `list_runs` summaries and [frames] is the shared gateway's +/// unsolicited stream, so it never polls or issues an attention request. The +/// bell has no built-in host choice; the ambient app host (or [cupertino] in a +/// fixture) selects the native Material or Cupertino action and sheet. +class NeedsYouRunsHeading extends StatefulWidget { + const NeedsYouRunsHeading({ + super.key, + required this.rows, + required this.frames, + required this.onOpen, + this.syncToken = 0, + this.store = const SharedPreferencesAttentionStore(), + this.now, + this.cupertino, + }); + + /// The run summaries the Runs destination already holds. + final List rows; + + /// The shared gateway's frames; only `run_event` envelopes are folded. + final Stream frames; + + /// Opens an entry's run. A Failed entry is dismissed by the bell first. + final ValueChanged onOpen; + + /// Advances when the shared socket is replaced. The detector rebaselines + /// without replaying a transition that happened during the gap. + final int syncToken; + + final AttentionStore store; + + /// Injected clock for deterministic local-day windows. + final DateTime Function()? now; + + /// Forces the native host in tests and fixtures. + final bool? cupertino; + + @override + State createState() => _NeedsYouRunsHeadingState(); +} + +class _NeedsYouRunsHeadingState extends State { + late final AttentionController _attention = AttentionController( + store: widget.store, + now: widget.now, + ); + StreamSubscription? _frames; + + @override + void initState() { + super.initState(); + _attention.seedRows(widget.rows); + unawaited(_attention.load()); + _listen(); + } + + void _listen() { + _frames = widget.frames + .where((frame) => frame['type'] == 'run_event') + .listen(_attention.observeFrame); + } + + @override + void didUpdateWidget(covariant NeedsYouRunsHeading oldWidget) { + super.didUpdateWidget(oldWidget); + if (!identical(oldWidget.frames, widget.frames)) { + unawaited(_frames?.cancel()); + _frames = null; + _listen(); + } + if (oldWidget.syncToken != widget.syncToken) { + _attention.resetForReconnect(); + _attention.seedRows(widget.rows, reconnect: true); + return; + } + if (!identical(oldWidget.rows, widget.rows)) { + _attention.seedRows(widget.rows); + } + } + + @override + void dispose() { + unawaited(_frames?.cancel()); + _attention.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return AnimatedBuilder( + animation: _attention, + builder: (context, _) => NeedsYouBell( + entries: _attention.entries, + cupertino: widget.cupertino, + onOpen: widget.onOpen, + onDismiss: (entry) { + unawaited(_attention.dismiss(entry)); + }, + onClearAll: (snapshot) { + unawaited(_attention.clearAll(snapshot)); + }, + ), + ); + } +} diff --git a/app/lib/features/runs/screen.dart b/app/lib/features/runs/screen.dart index 42126b44..f4f28125 100644 --- a/app/lib/features/runs/screen.dart +++ b/app/lib/features/runs/screen.dart @@ -1,6 +1,7 @@ import 'package:flutter/widgets.dart'; import '../../core/api_gateway.dart'; +import '../attention/runtime/attention_store.dart'; import 'data/runs_repository.dart'; import 'ui/run_detail_view.dart'; import 'ui/runs_controller.dart'; @@ -20,6 +21,8 @@ class RunsScreen extends StatefulWidget { this.syncToken = 0, this.onRunSelected, this.onBack, + this.attentionStore = const SharedPreferencesAttentionStore(), + this.attentionNow, }); final ApiGateway gateway; @@ -34,6 +37,11 @@ class RunsScreen extends StatefulWidget { final ValueChanged? onRunSelected; final VoidCallback? onBack; + /// Persisted attention dismissals and the clock for its local-day window. + /// The app uses SharedPreferences; tests and fixtures inject a memory store. + final AttentionStore attentionStore; + final DateTime Function()? attentionNow; + @override State createState() => _RunsScreenState(); } @@ -103,7 +111,13 @@ class _RunsScreenState extends State { animation: controller, builder: (context, _) => Offstage( offstage: selected, - child: RunsList(controller: controller, onSelected: _select), + child: RunsList( + controller: controller, + onSelected: _select, + syncToken: widget.syncToken, + attentionStore: widget.attentionStore, + attentionNow: widget.attentionNow, + ), ), ), if (selected) diff --git a/app/lib/features/runs/ui/runs_filters.dart b/app/lib/features/runs/ui/runs_filters.dart new file mode 100644 index 00000000..9ff33de0 --- /dev/null +++ b/app/lib/features/runs/ui/runs_filters.dart @@ -0,0 +1,138 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../ui/adaptive/host.dart'; +import 'runs_controller.dart'; + +/// The runs list's native sort/schedule/status controls. +/// +/// On Cupertino the controls stay in one horizontally scrollable strip: a phone +/// at a doubled text scale cannot stack seven buttons above the list without +/// crushing it, and the browser's narrow toolbar is likewise one row. Material +/// keeps its native dropdowns and filter chips. +class RunsFilters extends StatelessWidget { + const RunsFilters({super.key, required this.controller}); + + final RunsController controller; + + @override + Widget build(BuildContext context) => + usesCupertinoHost(context) ? _cupertino(context) : _material(context); + + Widget _cupertino(BuildContext context) => SingleChildScrollView( + scrollDirection: Axis.horizontal, + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4), + child: Row( + children: [ + CupertinoButton( + onPressed: () => _choose( + context, + 'Sort runs', + _sorts, + controller.sort, + controller.setSort, + ), + child: Text('Sort: ${_sortLabel(controller.sort)}'), + ), + const SizedBox(width: 8), + CupertinoButton( + onPressed: () => _choose( + context, + 'Schedule', + _schedules, + controller.scheduled, + controller.setScheduled, + ), + child: Text('Schedule: ${_scheduleLabel(controller.scheduled)}'), + ), + for (final status in _statuses) ...[ + const SizedBox(width: 8), + CupertinoButton( + onPressed: () => controller.setStatus(status), + child: Text( + '${controller.statuses.contains(status) ? '✓ ' : ''}${_title(status)}', + ), + ), + ], + ], + ), + ); + + Widget _material(BuildContext context) => Wrap( + spacing: 8, + children: [ + DropdownButton( + value: controller.sort, + isExpanded: true, + onChanged: (v) { + if (v != null) controller.setSort(v); + }, + items: _sorts + .map((e) => DropdownMenuItem(value: e.$1, child: Text(e.$2))) + .toList(), + ), + DropdownButton( + value: controller.scheduled, + isExpanded: true, + onChanged: (v) { + if (v != null) controller.setScheduled(v); + }, + items: _schedules + .map((e) => DropdownMenuItem(value: e.$1, child: Text(e.$2))) + .toList(), + ), + for (final status in _statuses) + FilterChip( + label: Text(_title(status)), + selected: controller.statuses.contains(status), + onSelected: (_) => controller.setStatus(status), + ), + ], + ); + + Future _choose( + BuildContext context, + String title, + List<(String, String)> values, + String selected, + ValueChanged onSelected, + ) async { + final value = await showCupertinoModalPopup( + context: context, + builder: (context) => CupertinoActionSheet( + title: Text(title), + actions: [ + for (final option in values) + CupertinoActionSheetAction( + onPressed: () => Navigator.pop(context, option.$1), + child: Text(option.$2), + ), + ], + cancelButton: CupertinoActionSheetAction( + onPressed: () => Navigator.pop(context), + child: const Text('Cancel'), + ), + ), + ); + if (value != null && value != selected) onSelected(value); + } +} + +const _sorts = [ + ('newest_first', 'Newest'), + ('oldest_first', 'Oldest'), + ('pipeline_name', 'Pipeline'), + ('status', 'Status'), +]; +const _schedules = [ + ('any', 'Any schedule'), + ('scheduled', 'Scheduled'), + ('unscheduled', 'Unscheduled'), +]; +const _statuses = ['queued', 'running', 'waiting', 'succeeded', 'failed']; +String _sortLabel(String value) => + _sorts.firstWhere((e) => e.$1 == value, orElse: () => _sorts.first).$2; +String _scheduleLabel(String value) => _schedules + .firstWhere((e) => e.$1 == value, orElse: () => _schedules.first) + .$2; +String _title(String value) => '${value[0].toUpperCase()}${value.substring(1)}'; diff --git a/app/lib/features/runs/ui/runs_list.dart b/app/lib/features/runs/ui/runs_list.dart index 0f974eac..2c5a2ab3 100644 --- a/app/lib/features/runs/ui/runs_list.dart +++ b/app/lib/features/runs/ui/runs_list.dart @@ -3,19 +3,35 @@ import 'package:flutter/material.dart'; import '../../../core/api_gateway.dart'; import '../../../ui/adaptive/host.dart'; +import '../../attention/runtime/attention_store.dart'; +import '../../attention/ui/needs_you_runs_heading.dart'; import '../domain/run_models.dart'; import 'runs_controller.dart'; +import 'runs_filters.dart'; class RunsList extends StatelessWidget { const RunsList({ super.key, required this.controller, required this.onSelected, + this.syncToken = 0, + this.attentionStore = const SharedPreferencesAttentionStore(), + this.attentionNow, }); final RunsController controller; final ValueChanged onSelected; + /// Advances when the shared socket is replaced, so the attention detector + /// rebaselines instead of replaying a transition from before the gap. + final int syncToken; + + /// Test and fixture seam for the persisted attention dismissals. + final AttentionStore attentionStore; + + /// Deterministic local-day clock for the attention window. + final DateTime Function()? attentionNow; + @override Widget build(BuildContext context) { if (controller.loading && controller.runs.isEmpty) { @@ -31,6 +47,20 @@ class RunsList extends StatelessWidget { return Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ + Padding( + padding: const EdgeInsetsDirectional.fromSTEB(16, 8, 16, 0), + child: Align( + alignment: AlignmentDirectional.centerEnd, + child: NeedsYouRunsHeading( + rows: controller.runs, + frames: controller.repository.gateway.frames, + onOpen: (entry) => onSelected(entry.runId), + syncToken: syncToken, + store: attentionStore, + now: attentionNow, + ), + ), + ), if (controller.usage != null) Padding( padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), @@ -52,7 +82,7 @@ class RunsList extends StatelessWidget { onChanged: controller.setQuery, ), ), - _selectors(context), + RunsFilters(controller: controller), Expanded( child: controller.visibleRuns.isEmpty ? const Center(child: Text('No runs found.')) @@ -101,101 +131,6 @@ class RunsList extends StatelessWidget { ), ); - Widget _selectors(BuildContext context) { - if (usesCupertinoHost(context)) { - return Wrap( - spacing: 8, - children: [ - CupertinoButton( - onPressed: () => _choose( - context, - 'Sort runs', - _sorts, - controller.sort, - controller.setSort, - ), - child: Text('Sort: ${_sortLabel(controller.sort)}'), - ), - CupertinoButton( - onPressed: () => _choose( - context, - 'Schedule', - _schedules, - controller.scheduled, - controller.setScheduled, - ), - child: Text('Schedule: ${_scheduleLabel(controller.scheduled)}'), - ), - for (final status in _statuses) - CupertinoButton( - onPressed: () => controller.setStatus(status), - child: Text( - '${controller.statuses.contains(status) ? '✓ ' : ''}${_title(status)}', - ), - ), - ], - ); - } - return Wrap( - spacing: 8, - children: [ - DropdownButton( - value: controller.sort, - isExpanded: true, - onChanged: (v) { - if (v != null) controller.setSort(v); - }, - items: _sorts - .map((e) => DropdownMenuItem(value: e.$1, child: Text(e.$2))) - .toList(), - ), - DropdownButton( - value: controller.scheduled, - isExpanded: true, - onChanged: (v) { - if (v != null) controller.setScheduled(v); - }, - items: _schedules - .map((e) => DropdownMenuItem(value: e.$1, child: Text(e.$2))) - .toList(), - ), - for (final status in _statuses) - FilterChip( - label: Text(_title(status)), - selected: controller.statuses.contains(status), - onSelected: (_) => controller.setStatus(status), - ), - ], - ); - } - - Future _choose( - BuildContext context, - String title, - List<(String, String)> values, - String selected, - ValueChanged onSelected, - ) async { - final value = await showCupertinoModalPopup( - context: context, - builder: (context) => CupertinoActionSheet( - title: Text(title), - actions: [ - for (final option in values) - CupertinoActionSheetAction( - onPressed: () => Navigator.pop(context, option.$1), - child: Text(option.$2), - ), - ], - cancelButton: CupertinoActionSheetAction( - onPressed: () => Navigator.pop(context), - child: const Text('Cancel'), - ), - ), - ); - if (value != null && value != selected) onSelected(value); - } - Widget _runTile(BuildContext context, JsonMap run) { final identity = runIdentity(run['title'], run['name']); final id = run['id']; @@ -222,22 +157,3 @@ class RunsList extends StatelessWidget { ); } } - -const _sorts = [ - ('newest_first', 'Newest'), - ('oldest_first', 'Oldest'), - ('pipeline_name', 'Pipeline'), - ('status', 'Status'), -]; -const _schedules = [ - ('any', 'Any schedule'), - ('scheduled', 'Scheduled'), - ('unscheduled', 'Unscheduled'), -]; -const _statuses = ['queued', 'running', 'waiting', 'succeeded', 'failed']; -String _sortLabel(String value) => - _sorts.firstWhere((e) => e.$1 == value, orElse: () => _sorts.first).$2; -String _scheduleLabel(String value) => _schedules - .firstWhere((e) => e.$1 == value, orElse: () => _schedules.first) - .$2; -String _title(String value) => '${value[0].toUpperCase()}${value.substring(1)}'; diff --git a/app/notes/attention-wiring.md b/app/notes/attention-wiring.md new file mode 100644 index 00000000..05f0c7a5 --- /dev/null +++ b/app/notes/attention-wiring.md @@ -0,0 +1,84 @@ +# Runs-list Needs-you bell wiring + +The landed attention model and native bell/sheet are now registered in the real +Runs destination. The bell sits in the Runs list heading area and reads the same +`list_runs` rows the screen already loaded; it issues no attention request and +adds no poll. + +## Code + +- `lib/features/attention/runtime/attention_store.dart` — the injectable + `AttentionStore` seam, a `SharedPreferences` implementation under + `pipelines.next.attention.v1` (only that key), and an in-memory implementation + for tests/fixtures. Reads and writes are total: an unavailable plugin or full + store returns null/false instead of throwing. +- `lib/features/attention/runtime/attention_controller.dart` — derives today's + ordered entries from rows plus the persisted dismissal set, loads asynchronously, + and folds pushed `run_event` frames with the runs feature's existing + `foldRunEvent`. The attention transition detector is seeded by authoritative + list reads, reseeded on reconnect, and keeps emitted keys, so a failure/wait + that appears while the screen is open reaches the bell once while a reconnect + never replays it. Dismissals update memory and notify before the store write, so + a slow or failed write cannot block the sheet. Pushed `title`/`name`/`diagnostic` + are retained because the lifecycle fold does not carry the row's attention text. +- `lib/features/attention/ui/needs_you_runs_heading.dart` — owns the controller + and shared-frame subscription for the destination, passes the dismissed list to + the landed `NeedsYouBell`, and opens the existing run through `RunsList`'s + `onSelected` (the existing run route). +- `lib/features/runs/ui/runs_list.dart` — small heading insert plus injectable + store/clock and reconnect token; no other destination is touched. +- `lib/features/runs/screen.dart` — forwards the reconnect token and the test + seam to the list. +- `lib/features/runs/ui/runs_filters.dart` — the existing filter controls moved + out of the list file unchanged for Material, with the Cupertino strip made + horizontally scrollable. At 320 logical px / 2x the old wrapping strip alone + made the Runs `Column` overflow before the attention change; one native row is + the same narrow-toolbar shape the browser uses and keeps every control + reachable. File split keeps `runs_list.dart` at 159 lines. + +The bell keeps the native `NeedsYouBell` semantics (`Notifications` / +`Notifications, N needing attention`), shows no badge when empty, and uses the +already-landed Material bottom sheet / Cupertino popup. Failed rows dismiss before +opening; Decision rows open without dismissing; Clear all uses the snapshot the +sheet captured when it opened. Dismissals survive a screen rebuild through the +same store. + +## Verification + +- `flutter test` — 966 tests passed. +- Focused `flutter test test/features/attention/runtime` — 20 tests passed: + rows -> entries, export waits and yesterday excluded, dismissal persistence + across a rebuilt controller, slow write does not block, failed read/write is + harmless, clear-all snapshot leaves a later arrival, live failed frame adds an + entry, a frame can create a new run summary, reconnect keeps dismissals and + emitted keys, empty state keeps the bell and hides its badge, both hosts at + 320 logical px / 2x with no list/sheet overflow, and the SharedPreferences key + ownership test. +- `flutter analyze` — no issues. +- `flutter build web` — normal `lib/main.dart` built successfully. +- Real browser (`tool/attention_wiring_probe.mjs`, isolated `startFixture`, two + fresh app boots, one shared socket each): four captures in + `public/attention-wiring/` at 320 logical px / 2x: + `attention-runs-cupertino-bell-320x2.png`, + `attention-runs-cupertino-sheet-320x2.png`, + `attention-runs-material-bell-320x2.png`, + `attention-runs-material-sheet-320x2.png`. + The drive asserted the accessible count `Notifications, 2 needing attention`, + both void rows absent, the `Dismiss ...` names and Clear all, and viewed both + PNGs. The fixture list held a running row and an `export_pending_sequence` + wait that did not enter the sheet; the fixture served one connection and no + `get_run`/attention request (`listRuns: 4` across the two boots, the existing + screen loads). Both bell and sheet captures were inspected. + +`tool/runs_probe_server.mjs` now accepts an optional `runs` list so this fixture +can use current-day timestamps without changing the existing runs probe's +default data. No legacy driver was edited. + +## Not done / limits + +- No commit, push, merge, deployment, preview cutover or service restart. +- Notification permission/tray delivery remains separate work; the transition + ledger is exposed for that wiring but no permission is requested here. +- Android/iOS builds and real devices were not run; web only, as required. +- The fixture is isolated (loopback, its own browser profile) and does not touch + operator runs, chats, storage or production credentials. diff --git a/app/test/features/attention/runtime/attention_controller_test.dart b/app/test/features/attention/runtime/attention_controller_test.dart new file mode 100644 index 00000000..adcbd87d --- /dev/null +++ b/app/test/features/attention/runtime/attention_controller_test.dart @@ -0,0 +1,250 @@ +import 'dart:async'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/attention/domain/attention_models.dart'; +import 'package:pipelines_app/features/attention/runtime/attention_controller.dart'; +import 'package:pipelines_app/features/attention/runtime/attention_store.dart'; + +final _now = DateTime(2026, 10, 22, 12); + +String _at(Duration before) => _now.subtract(before).toIso8601String(); + +Map _run( + int id, + String status, { + String name = 'release', + String? title, + Duration age = const Duration(hours: 1), + String diagnostic = '', + Object? exportPending, + Map extra = const {}, +}) => { + 'id': id, + 'name': name, + 'title': title ?? 'Run $id', + 'status': status, + 'diagnostic': diagnostic, + 'created_at': _at(age), + 'finished_at': _at(age - const Duration(minutes: 5)), + 'export_pending_sequence': ?exportPending, + ...extra, +}; + +AttentionController _controller(AttentionStore store) => + AttentionController(store: store, now: () => _now); + +class _SlowStore extends MemoryAttentionStore { + final gate = Completer(); + + @override + Future write(String value) { + writes++; + stored = value; + return gate.future; + } +} + +void main() { + group('entries from the rows the Runs destination already holds', () { + test('only failed and human waiting rows become entries', () async { + final controller = _controller(MemoryAttentionStore()); + addTearDown(controller.dispose); + await controller.load(); + controller.seedRows([ + _run(1, 'running'), + _run(2, 'succeeded'), + _run(3, 'queued'), + _run(4, 'canceled'), + _run(5, 'failed', diagnostic: 'Stage 2 failed'), + _run(6, 'waiting', title: 'Approve the release'), + ]); + + expect(controller.entries.map((entry) => entry.key), [ + '6:Decision', + '5:Failed', + ]); + expect(controller.entries.last.detail, 'Stage 2 failed'); + }); + + test('export handoffs and yesterday do not ask the operator', () async { + final controller = _controller(MemoryAttentionStore()); + addTearDown(controller.dispose); + await controller.load(); + controller.seedRows([ + _run(1, 'waiting', exportPending: 4), + _run(2, 'waiting', exportPending: ' 2 '), + _run(3, 'waiting', exportPending: 0), + _run(4, 'failed', age: const Duration(days: 1, hours: 2)), + _run(5, 'waiting', age: const Duration(days: 1)), + ]); + + expect(controller.entries.map((entry) => entry.runId), [3]); + }); + }); + + group('dismissal persistence', () { + test('a dismissed identity survives a rebuilt controller', () async { + final store = MemoryAttentionStore(); + final first = _controller(store); + await first.load(); + first.seedRows([_run(7, 'failed')]); + final entry = first.entries.single; + + expect(await first.dismiss(entry), isTrue); + expect(first.entries, isEmpty); + expect(store.stored, encodeAttentionDismissals({'7:Failed'})); + first.dispose(); + + final rebuilt = _controller(store); + addTearDown(rebuilt.dispose); + await rebuilt.load(); + rebuilt.seedRows([_run(7, 'failed')]); + expect(rebuilt.dismissed, {'7:Failed'}); + expect(rebuilt.entries, isEmpty); + }); + + test('Clear all applies only the snapshot, leaving later arrivals', () async { + final controller = _controller(MemoryAttentionStore()); + addTearDown(controller.dispose); + await controller.load(); + controller.seedRows([_run(1, 'failed'), _run(2, 'waiting')]); + final snapshot = attentionDismissalSnapshot(controller.entries); + + // A third run arrives while the sheet is open. Clear all must not know it. + controller.seedRows([ + _run(1, 'failed'), + _run(2, 'waiting'), + _run(3, 'failed'), + ]); + expect(await controller.clearAll(snapshot), isTrue); + + expect(controller.dismissed, {'1:Failed', '2:Decision'}); + expect(controller.entries.map((entry) => entry.key), ['3:Failed']); + }); + + test('a slow write never holds the bell or entries back', () async { + final store = _SlowStore(); + final controller = _controller(store); + addTearDown(controller.dispose); + await controller.load(); + controller.seedRows([_run(4, 'failed')]); + final entry = controller.entries.single; + + final pending = controller.dismiss(entry); + expect(controller.entries, isEmpty, reason: 'memory applies first'); + expect(store.stored, encodeAttentionDismissals({'4:Failed'})); + store.gate.complete(true); + expect(await pending, isTrue); + }); + + test('failed reads and writes are total and keep this session', () async { + final store = MemoryAttentionStore() + ..failReads = true + ..failWrites = true; + final controller = _controller(store); + addTearDown(controller.dispose); + + await expectLater(controller.load(), completes); + expect(controller.loaded, isTrue); + expect(controller.dismissed, isEmpty); + + controller.seedRows([_run(8, 'failed')]); + final entry = controller.entries.single; + expect(await controller.dismiss(entry), isFalse); + expect(controller.dismissed, {'8:Failed'}); + expect(controller.entries, isEmpty); + }); + }); + + group('pushed frames and reconnect', () { + test('a live frame that becomes failed appears without a reload', () async { + final controller = _controller(MemoryAttentionStore()); + addTearDown(controller.dispose); + await controller.load(); + controller.seedRows([_run(1, 'running')]); + expect(controller.entries, isEmpty); + + controller.observeFrame({ + 'type': 'run_event', + 'run_id': 1, + 'status': 'failed', + 'diagnostic': 'Stage 4 failed', + 'finished_at': _at(const Duration(minutes: 1)), + }); + + expect(controller.entries.map((entry) => entry.key), ['1:Failed']); + expect(controller.entries.single.detail, 'Stage 4 failed'); + expect(controller.transitions.map((item) => item.key), ['1:Failed']); + + // The same state again is not a new transition. + controller.observeFrame({ + 'type': 'run_event', + 'run_id': 1, + 'status': 'failed', + 'diagnostic': 'Stage 4 failed', + }); + expect(controller.entries, hasLength(1)); + expect(controller.transitions, hasLength(1)); + }); + + test('a live frame for a new run can create its own summary', () async { + final controller = _controller(MemoryAttentionStore()); + addTearDown(controller.dispose); + await controller.load(); + controller.seedRows(const []); + + controller.observeFrame({ + 'type': 'run_event', + 'run_id': 9, + 'pipeline_id': 10, + 'name': 'nightly', + 'title': 'Nightly audit', + 'status': 'waiting', + 'created_at': _at(const Duration(minutes: 3)), + }); + + expect(controller.entries.single.runId, 9); + expect(controller.entries.single.kind, AttentionKind.decision); + }); + + test( + 'a reconnect reseed keeps dismissals and does not re-notify', + () async { + final controller = _controller(MemoryAttentionStore()); + addTearDown(controller.dispose); + await controller.load(); + controller.seedRows([_run(1, 'running'), _run(2, 'failed')]); + final failed = controller.entries.single; + expect(await controller.dismiss(failed), isTrue); + + controller.observeFrame({ + 'type': 'run_event', + 'run_id': 1, + 'status': 'failed', + }); + expect(controller.transitions, hasLength(1)); + + controller.resetForReconnect(); + controller.seedRows([ + _run(1, 'failed'), + _run(2, 'failed'), + ], reconnect: true); + + expect(controller.dismissed, {'2:Failed'}); + expect(controller.entries.map((entry) => entry.key), ['1:Failed']); + expect( + controller.transitions, + hasLength(1), + reason: 'the reconnect baseline is already failed for run 1', + ); + + controller.observeFrame({ + 'type': 'run_event', + 'run_id': 1, + 'status': 'failed', + }); + expect(controller.transitions, hasLength(1)); + }, + ); + }); +} diff --git a/app/test/features/attention/runtime/attention_runs_layout_test.dart b/app/test/features/attention/runtime/attention_runs_layout_test.dart new file mode 100644 index 00000000..16b57207 --- /dev/null +++ b/app/test/features/attention/runtime/attention_runs_layout_test.dart @@ -0,0 +1,72 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/attention/runtime/attention_store.dart'; +import 'package:pipelines_app/features/attention/ui/needs_you_keys.dart'; + +import 'attention_runs_test_support.dart'; + +/// The hardest real-app case: a narrow phone at a doubled text scale. Both the +/// Runs list chrome and the native sheet must keep the bell and every action +/// inside the viewport. +void main() { + testWidgets('both hosts fit the bell and sheet at 320 logical px and 2x', ( + tester, + ) async { + tester.view.devicePixelRatio = 2; + tester.view.physicalSize = const Size(640, 1280); + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + final gateway = AttentionRunsGateway(); + addTearDown(gateway.framesController.close); + + for (final native in [false, true]) { + await mountAttentionRuns( + tester, + gateway, + cupertino: native, + store: MemoryAttentionStore(), + runs: [ + attentionRun( + 1, + 'waiting', + title: 'Approve a release candidate at 320 px', + ), + attentionRun( + 2, + 'failed', + title: 'A failed run with a label long enough to wrap', + diagnostic: 'Stage 3 stopped because the credential is missing.', + ), + ], + request: native ? 1 : 0, + textScale: 2, + key: ValueKey(native), + ); + expect(find.byKey(attentionBellKey), findsOneWidget); + final listError = tester.takeException(); + expect( + listError, + isNull, + reason: listError is FlutterError + ? '${native ? 'Cupertino' : 'Material'} list: ${listError.toStringDeep()}' + : '${native ? 'Cupertino' : 'Material'} list: $listError', + ); + await openAttentionSheet(tester); + final sheetError = tester.takeException(); + expect( + sheetError, + isNull, + reason: sheetError is FlutterError + ? '${native ? 'Cupertino' : 'Material'} sheet: ${sheetError.toStringDeep()}' + : '${native ? 'Cupertino' : 'Material'} sheet: $sheetError', + ); + final sheet = tester.getRect(find.byKey(attentionSheetKey)); + expect(sheet.left, greaterThanOrEqualTo(0)); + expect(sheet.right, lessThanOrEqualTo(320)); + expect(sheet.top, greaterThanOrEqualTo(0)); + expect(sheet.bottom, lessThanOrEqualTo(640)); + await tester.binding.handlePopRoute(); + await tester.pumpAndSettle(); + } + }); +} diff --git a/app/test/features/attention/runtime/attention_runs_test_support.dart b/app/test/features/attention/runtime/attention_runs_test_support.dart new file mode 100644 index 00000000..0dd459b6 --- /dev/null +++ b/app/test/features/attention/runtime/attention_runs_test_support.dart @@ -0,0 +1,125 @@ +import 'dart:async'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/attention/runtime/attention_store.dart'; +import 'package:pipelines_app/features/attention/ui/needs_you_keys.dart'; +import 'package:pipelines_app/features/runs/screen.dart'; + +/// A fixed local noon so the attention local-day window is deterministic. +final attentionTestNow = DateTime(2026, 10, 22, 12); + +Map attentionRun( + int id, + String status, { + required String title, + String name = 'release', + String diagnostic = '', +}) => { + 'id': id, + 'name': name, + 'title': title, + 'status': status, + 'diagnostic': diagnostic, + 'created_at': attentionTestNow + .subtract(const Duration(hours: 1)) + .toIso8601String(), + 'finished_at': attentionTestNow + .subtract(const Duration(minutes: 30)) + .toIso8601String(), +}; + +/// The two requests the Runs destination makes; no attention request exists. +class AttentionRunsGateway implements ApiGateway { + final framesController = StreamController.broadcast(); + final listRequests = >[]; + final detailRequests = >>{}; + + @override + Stream get frames => framesController.stream; + + @override + Future call(String type, [JsonMap fields = const {}]) { + final request = Completer(); + if (type == 'list_runs') { + listRequests.add(request); + } else if (type == 'get_run') { + final id = fields['run_id'] as num; + detailRequests.putIfAbsent(id, () => []).add(request); + } else { + request.completeError(UnsupportedError(type)); + } + return request.future; + } + + void replyList(int index, List runs) => + listRequests[index].complete({'runs': runs}); + + void replyDetail(num id, JsonMap detail) => + detailRequests[id]!.first.complete({'run_detail': detail}); +} + +Widget attentionRunsApp( + AttentionRunsGateway gateway, { + required bool cupertino, + required AttentionStore store, + double textScale = 1, + Key? key, +}) { + Widget scaled(BuildContext context, Widget? child) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(textScale)), + child: child!, + ); + final screen = RunsScreen( + key: key, + gateway: gateway, + attentionStore: store, + attentionNow: () => attentionTestNow, + ); + if (cupertino) { + return CupertinoApp( + theme: const CupertinoThemeData(brightness: Brightness.dark), + builder: scaled, + home: CupertinoPageScaffold(child: screen), + ); + } + return MaterialApp( + theme: ThemeData(platform: TargetPlatform.android), + builder: scaled, + home: Scaffold(body: screen), + ); +} + +Future mountAttentionRuns( + WidgetTester tester, + AttentionRunsGateway gateway, { + required bool cupertino, + required AttentionStore store, + required List runs, + int request = 0, + double textScale = 1, + Key? key, +}) async { + await tester.pumpWidget( + attentionRunsApp( + gateway, + cupertino: cupertino, + store: store, + textScale: textScale, + key: key, + ), + ); + await tester.pump(); + gateway.replyList(request, runs); + await tester.pump(); + await tester.pump(); +} + +Future openAttentionSheet(WidgetTester tester) async { + await tester.tap(find.byKey(attentionBellKey)); + await tester.pumpAndSettle(); +} diff --git a/app/test/features/attention/runtime/attention_runs_wiring_test.dart b/app/test/features/attention/runtime/attention_runs_wiring_test.dart new file mode 100644 index 00000000..9b13694b --- /dev/null +++ b/app/test/features/attention/runtime/attention_runs_wiring_test.dart @@ -0,0 +1,196 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/attention/domain/attention_models.dart'; +import 'package:pipelines_app/features/attention/runtime/attention_store.dart'; +import 'package:pipelines_app/features/attention/ui/needs_you_keys.dart'; + +import 'attention_runs_test_support.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + late AttentionRunsGateway gateway; + + setUp(() => gateway = AttentionRunsGateway()); + tearDown(() => gateway.framesController.close()); + + for (final native in [false, true]) { + final host = native ? 'Cupertino' : 'Material'; + + testWidgets( + '$host Runs list bell opens the native sheet and dismisses one', + (tester) async { + final semantics = tester.ensureSemantics(); + final store = MemoryAttentionStore(); + await mountAttentionRuns( + tester, + gateway, + cupertino: native, + store: store, + runs: [ + attentionRun(1, 'waiting', title: 'Approve the release'), + attentionRun( + 2, + 'failed', + title: 'Ship the release', + diagnostic: 'Stage 2', + ), + attentionRun(3, 'waiting', title: 'Machine export') + ..['export_pending_sequence'] = 2, + attentionRun(4, 'running', title: 'Still running'), + ], + ); + + expect( + find.bySemanticsLabel('Notifications, 2 needing attention'), + findsOneWidget, + ); + await openAttentionSheet(tester); + expect(find.byKey(attentionSheetKey), findsOneWidget); + expect(find.byKey(attentionRowKey('3:Decision')), findsNothing); + expect(find.byKey(attentionRowKey('4:Failed')), findsNothing); + expect(find.byKey(attentionRowKey('2:Failed')), findsOneWidget); + + await tester.tap(find.byKey(attentionDismissKey('2:Failed'))); + await tester.pumpAndSettle(); + expect(find.byKey(attentionSheetKey), findsOneWidget); + expect(find.byKey(attentionRowKey('2:Failed')), findsNothing); + expect(store.stored, encodeAttentionDismissals({'2:Failed'})); + + // Closing and rebuilding from the same store keeps the dismissal. + await tester.binding.handlePopRoute(); + await tester.pumpAndSettle(); + await tester.pumpWidget(const SizedBox()); + await mountAttentionRuns( + tester, + gateway, + cupertino: native, + store: store, + runs: [ + attentionRun(1, 'waiting', title: 'Approve the release'), + attentionRun( + 2, + 'failed', + title: 'Ship the release', + diagnostic: 'Stage 2', + ), + ], + request: 1, + key: const ValueKey('rebuilt'), + ); + expect( + find.bySemanticsLabel('Notifications, 1 needing attention'), + findsOneWidget, + ); + semantics.dispose(); + }, + ); + + testWidgets('$host rows follow the browser open/dismiss rules', ( + tester, + ) async { + final store = MemoryAttentionStore(); + await mountAttentionRuns( + tester, + gateway, + cupertino: native, + store: store, + runs: [ + attentionRun(1, 'waiting', title: 'Approve the release'), + attentionRun(2, 'failed', title: 'Ship the release'), + ], + ); + + await openAttentionSheet(tester); + await tester.tap(find.byKey(attentionRowKey('1:Decision'))); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 400)); + expect(gateway.detailRequests[1], hasLength(1)); + expect( + store.stored, + isNull, + reason: 'a Decision opens without dismissing', + ); + gateway.replyDetail(1, {'id': 1, 'title': 'Approve the release'}); + await tester.pump(); + await tester.pumpAndSettle(); + + await tester.tap(find.text(native ? 'Back' : 'Back to list')); + await tester.pump(); + await openAttentionSheet(tester); + await tester.tap(find.byKey(attentionRowKey('2:Failed'))); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 400)); + expect(gateway.detailRequests[2], hasLength(1)); + expect(store.stored, encodeAttentionDismissals({'2:Failed'})); + gateway.replyDetail(2, {'id': 2, 'title': 'Ship the release'}); + await tester.pump(); + }); + + testWidgets('$host live frame and Clear-all snapshot reach the bell', ( + tester, + ) async { + final semantics = tester.ensureSemantics(); + final store = MemoryAttentionStore(); + await mountAttentionRuns( + tester, + gateway, + cupertino: native, + store: store, + runs: [attentionRun(1, 'failed', title: 'First failure')], + ); + expect( + find.bySemanticsLabel('Notifications, 1 needing attention'), + findsOneWidget, + ); + + await openAttentionSheet(tester); + gateway.framesController.add({ + 'type': 'run_event', + 'run_id': 9, + 'pipeline_id': 4, + 'name': 'nightly', + 'title': 'Arrived while open', + 'status': 'waiting', + 'created_at': attentionTestNow + .subtract(const Duration(minutes: 5)) + .toIso8601String(), + }); + await tester.pump(); + await tester.pumpAndSettle(); + expect(find.byKey(attentionRowKey('9:Decision')), findsOneWidget); + + await tester.tap(find.byKey(attentionClearAllKey)); + await tester.pumpAndSettle(); + expect(find.byKey(attentionRowKey('1:Failed')), findsNothing); + expect( + find.byKey(attentionRowKey('9:Decision')), + findsOneWidget, + reason: 'Clear all acts on the snapshot it opened with', + ); + expect(store.stored, encodeAttentionDismissals({'1:Failed'})); + semantics.dispose(); + }); + + testWidgets('$host empty runs hide the badge but keep the bell', ( + tester, + ) async { + final semantics = tester.ensureSemantics(); + await mountAttentionRuns( + tester, + gateway, + cupertino: native, + store: MemoryAttentionStore(), + runs: const [], + ); + + expect(find.byKey(attentionBellKey), findsOneWidget); + expect(find.byKey(attentionBadgeKey), findsNothing); + expect(find.bySemanticsLabel('Notifications'), findsOneWidget); + await openAttentionSheet(tester); + expect(find.text('Nothing needs you right now.'), findsOneWidget); + expect(find.byKey(attentionClearAllKey), findsNothing); + semantics.dispose(); + }); + } +} diff --git a/app/test/features/attention/runtime/attention_store_test.dart b/app/test/features/attention/runtime/attention_store_test.dart new file mode 100644 index 00000000..ee222995 --- /dev/null +++ b/app/test/features/attention/runtime/attention_store_test.dart @@ -0,0 +1,36 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/attention/domain/attention_models.dart'; +import 'package:pipelines_app/features/attention/runtime/attention_store.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + test('reads and writes only the attention model key', () async { + SharedPreferences.setMockInitialValues({ + attentionStorageKey: '["7:Failed"]', + 'pipelines.next.workspace.v1': '/srv/keep', + }); + const store = SharedPreferencesAttentionStore(); + + expect(await store.read(), '["7:Failed"]'); + expect(await store.write('["8:Decision"]'), isTrue); + + final preferences = await SharedPreferences.getInstance(); + expect(preferences.getString(attentionStorageKey), '["8:Decision"]'); + expect( + preferences.getString('pipelines.next.workspace.v1'), + '/srv/keep', + reason: 'another owned preference must not be rewritten', + ); + }); + + test('an empty store reads as null and the key stays namespaced', () async { + SharedPreferences.setMockInitialValues({}); + const store = SharedPreferencesAttentionStore(); + + expect(await store.read(), isNull); + expect(attentionStorageKey, 'pipelines.next.attention.v1'); + expect(await store.write('[]'), isTrue); + }); +} diff --git a/app/tool/attention_wiring_probe.mjs b/app/tool/attention_wiring_probe.mjs new file mode 100644 index 00000000..47b22d4f --- /dev/null +++ b/app/tool/attention_wiring_probe.mjs @@ -0,0 +1,220 @@ +// Real-browser acceptance for the Needs-you bell in the Runs destination. +// +// flutter build web +// OPENCODE_ARTIFACT_DIR= node tool/attention_wiring_probe.mjs build/web +// +// The fixture serves the normal app bundle and answers list_runs over the same +// origin, so this is the real Runs screen and the real shared socket. It touches +// no production server, operator run or browser profile. The list carries one +// failed run, one human wait, plus a running and a machine export wait that must +// not reach the bell. Each native host is captured at 320 logical px / 2x. +import { spawn, execFile } from 'node:child_process'; +import { promisify } from 'node:util'; +import { once } from 'node:events'; +import { existsSync } from 'node:fs'; +import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'; +import { join, resolve } from 'node:path'; +import { tmpdir } from 'node:os'; +import { setTimeout as delay } from 'node:timers/promises'; + +import { startFixture } from './runs_probe_server.mjs'; + +const output = process.env.OPENCODE_ARTIFACT_DIR; +if (!output) throw new Error('Set OPENCODE_ARTIFACT_DIR for the probe captures'); +await mkdir(output, { recursive: true }); +const root = resolve(process.argv[2] ?? 'build/web'); + +const now = Date.now(); +const dayStart = new Date(now); +dayStart.setHours(0, 0, 0, 0); +const at = (minutes) => + new Date(Math.max(now - minutes * 60_000, dayStart.getTime() + 30_000)).toISOString(); +const runs = [ + { id: 1, title: 'Running fixture', name: 'running-fixture', status: 'running', + created_at: at(6), pipeline_id: 10 }, + { id: 2, title: 'Approve the release candidate', name: 'release', + status: 'waiting', created_at: at(5), finished_at: '', pipeline_id: 10 }, + { id: 3, title: 'Nightly audit stopped', name: 'nightly-audit', + status: 'failed', diagnostic: 'Stage 3 stopped at the export archive step because the credential is missing.', + created_at: at(4), finished_at: at(1), pipeline_id: 10 }, + { id: 6, title: 'Machine export wait', name: 'export-handoff', + status: 'waiting', export_pending_sequence: 2, created_at: at(3), pipeline_id: 10 }, +]; + +const fixture = await startFixture({ root, runs }); +// Prove the fixture answered before Chrome starts, so a missing build fails with +// a clear message instead of a blank page. +const probe = await fetch(`${fixture.url}/`); +if (probe.status !== 200 || !(probe.headers.get('content-type') ?? '').startsWith('text/html')) { + throw new Error(`Fixture index must be HTML: ${probe.status} ${probe.headers.get('content-type')}`); +} +await probe.text(); + +const chromePath = process.env.CHROME_PATH ?? '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'; +if (!existsSync(chromePath)) throw new Error(`Chrome not found at ${chromePath}; set CHROME_PATH`); +const profile = await mkdtemp(join(tmpdir(), 'attention-wiring-chrome-')); +const chrome = spawn(chromePath, [ + '--headless=new', '--no-first-run', '--no-default-browser-check', '--disable-gpu', + '--remote-debugging-port=0', `--user-data-dir=${profile}`, 'about:blank', +], { stdio: ['ignore', 'ignore', 'pipe'] }); +let stderr = ''; +chrome.stderr.on('data', (data) => { stderr += data; }); + +const waitFor = async (check, what) => { + for (let i = 0; i < 160; i++) { + const value = await check(); + if (value) return value; + await delay(100); + } + throw new Error(`Timed out waiting for ${what}\n${stderr.slice(-1200)}`); +}; + +let ws; +const captures = []; +try { + const endpoint = await waitFor( + () => stderr.match(/DevTools listening on (ws:\/\/[^\s]+)/)?.[1], + 'Chrome DevTools', + ); + ws = new WebSocket(endpoint); + await once(ws, 'open'); + let id = 0; + const pending = new Map(); + ws.addEventListener('message', (event) => { + const message = JSON.parse(event.data); + if (message.id && pending.has(message.id)) { + pending.get(message.id)(message); + pending.delete(message.id); + } + }); + const send = (method, params = {}, sessionId) => new Promise((resolveCall) => { + const callId = ++id; + pending.set(callId, resolveCall); + ws.send(JSON.stringify({ id: callId, method, params, ...(sessionId ? { sessionId } : {}) })); + }); + const target = (await send('Target.createTarget', { url: 'about:blank' })).result.targetId; + const session = (await send('Target.attachToTarget', { targetId: target, flatten: true })).result.sessionId; + await send('Page.enable', {}, session); + await send('Runtime.enable', {}, session); + + const evaluate = async (expression) => { + const response = await send('Runtime.evaluate', { + expression, returnByValue: true, awaitPromise: true, + }, session); + if (response.error) throw new Error(`Runtime.evaluate failed: ${JSON.stringify(response)}`); + if (response.result?.exceptionDetails) { + throw new Error(`Page exception: ${JSON.stringify(response.result.exceptionDetails)}`); + } + return response.result?.result?.value; + }; + const path = () => evaluate('location.pathname'); + const semantics = () => evaluate(`[...document.querySelectorAll('flt-semantics')].map((el) => { + const r = el.getBoundingClientRect(); + return { label: (el.getAttribute('aria-label') || el.innerText || '').trim(), + role: el.getAttribute('role'), x: r.x, y: r.y, w: r.width, h: r.height }; + })`); + const labels = async () => (await semantics()).map((item) => item.label).filter(Boolean); + const text = () => evaluate(`(() => { + const chunks = [...document.querySelectorAll('flt-semantics, [aria-label]')] + .map((el) => el.getAttribute('aria-label') || el.innerText || ''); + if (document.body?.innerText) chunks.push(document.body.innerText); + return [...new Set(chunks)].join('\\n'); + })()`); + const requireLabel = async (needle) => { + await waitFor(async () => (await labels()).some((label) => label.includes(needle)), `label ${JSON.stringify(needle)}`); + }; + const requireText = async (needle) => { + await waitFor(async () => (await text()).includes(needle), `text ${JSON.stringify(needle)}`); + }; + const enableSemantics = async () => { + await waitFor( + () => evaluate("Boolean(document.querySelector('flt-semantics-placeholder'))"), + 'semantics placeholder', + ); + await evaluate("document.querySelector('flt-semantics-placeholder')?.click()"); + await delay(600); + }; + const clickLabel = async (needle, exact = false) => { + const clicked = await evaluate(`(() => { + const wanted = ${JSON.stringify(needle)}; + const all = [...document.querySelectorAll('flt-semantics')]; + const match = (el) => { + const label = (el.getAttribute('aria-label') || el.innerText || '').trim(); + return ${exact ? 'label === wanted' : 'label.includes(wanted)'}; + }; + const element = all.find((el) => ['button', 'tab', 'link', 'menuitem'].includes(el.getAttribute('role')) && match(el)) + || all.find(match); + if (!element) return false; + element.click(); + return true; + })()`); + if (!clicked) throw new Error(`Could not click ${JSON.stringify(needle)}. Labels: ${JSON.stringify(await labels())}`); + await delay(400); + }; + const capture = async (name) => { + const data = (await send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false }, session)).result.data; + const pathName = join(output, `${name}.png`); + await writeFile(pathName, Buffer.from(data, 'base64')); + captures.push(pathName); + return pathName; + }; + const ocr = async (file) => (await promisify(execFile)('tesseract', [file, 'stdout'])).stdout; + const requireOcr = async (file, needle) => { + const read = await ocr(file); + if (!read.toLowerCase().includes(needle.toLowerCase())) { + throw new Error(`OCR of ${file} lacks ${JSON.stringify(needle)}:\n${read.slice(0, 2000)}`); + } + }; + const setPhone = async () => { + await send('Emulation.setDeviceMetricsOverride', { + width: 320, height: 640, deviceScaleFactor: 2, mobile: true, + }, session); + await delay(500); + }; + + const drive = async (host, userAgent) => { + if (userAgent) { + await send('Emulation.setUserAgentOverride', userAgent, session); + } + await setPhone(); + await send('Page.navigate', { url: `${fixture.url}/` }, session); + await enableSemantics(); + await waitFor(async () => (await path()) === '/pipelines', 'boot route /pipelines'); + await clickLabel('Runs', true); + await waitFor(async () => (await path()) === '/runs', 'runs route'); + await requireLabel('Notifications, 2 needing attention'); + const bell = await capture(`attention-runs-${host}-bell-320x2`); + await requireOcr(bell, 'Nightly audit stopped'); + + await clickLabel('Notifications, 2 needing attention'); + await requireText('Needs you'); + await requireText('Approve the release candidate'); + await requireText('Stage 3 stopped at the export archive step'); + await requireLabel('Dismiss Approve the release candidate'); + await requireLabel('Dismiss Nightly audit stopped'); + await requireLabel('Clear all'); + const sheetLabels = await labels(); + if (sheetLabels.some((label) => label.includes('Machine export wait'))) { + throw new Error('an export wait leaked into the bell sheet'); + } + if (sheetLabels.some((label) => label.includes('Running fixture'))) { + throw new Error('a running run leaked into the bell sheet'); + } + const sheet = await capture(`attention-runs-${host}-sheet-320x2`); + await requireOcr(sheet, 'Needs you'); + return { host, bell, sheet }; + }; + + const cupertino = await drive('cupertino'); + const material = await drive('material', { + userAgent: 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36', + platform: 'Linux x86_64', + }); + const state = await (await fetch(`${fixture.url}/fixture/state`)).json(); + console.log(JSON.stringify({ captures, cupertino, material, fixture: state }, null, 2)); +} finally { + try { ws?.close(); } catch {} + chrome.kill('SIGTERM'); + await rm(profile, { recursive: true, force: true }).catch(() => {}); + await fixture.close(); +} diff --git a/app/tool/runs_probe_server.mjs b/app/tool/runs_probe_server.mjs index 60f38562..267a34a5 100644 --- a/app/tool/runs_probe_server.mjs +++ b/app/tool/runs_probe_server.mjs @@ -57,9 +57,9 @@ const RUNS = [ }, ]; -function humanDetail(accepted) { +function humanDetail(accepted, runs = RUNS) { return { - ...RUNS.find((run) => run.id === 5), + ...runs.find((run) => run.id === 5), status: accepted ? 'succeeded' : 'waiting', current_stage: 'gate', input: { prompt: 'Fixture human decision' }, graph: { stages: [{ key: 'gate', type: 'human', edges: { approve: '#success' } }] }, @@ -79,12 +79,12 @@ const LIVE_EVENT = { finished_at: '2026-10-21T12:05:00Z', }; -function detail(id, live, canceled = false) { +function detail(id, live, canceled = false, runs = RUNS) { const status = canceled ? 'canceled' : id === 1 && live ? 'succeeded' : id === 3 ? 'failed' : 'running'; return { id, - title: RUNS.find((run) => run.id === id)?.title ?? `Run ${id}`, + title: runs.find((run) => run.id === id)?.title ?? `Run ${id}`, name: 'fixture-pipeline', status, executing: status === 'running', @@ -310,7 +310,7 @@ async function staticFile(base, pathname, req, res) { * It serves the built probe bundle and upgrades /connect on the same origin, so * the normal web composition infers this server from Uri.base. */ -export async function startFixture({ root }) { +export async function startFixture({ root, runs = RUNS }) { const base = await realpath(root); const connections = new Set(); const sockets = new Set(); @@ -436,7 +436,7 @@ export async function startFixture({ root }) { } if (request.type === 'list_runs') { listRuns++; - client.send({ id: request.id, type: 'runs', runs: RUNS.map((run) => + client.send({ id: request.id, type: 'runs', runs: runs.map((run) => canceled.has(run.id) ? { ...run, status: 'canceled', executing: false } : run.id === 5 && decisionAccepted ? { ...run, status: 'succeeded' } : run), usage: null }); return; @@ -448,7 +448,7 @@ export async function startFixture({ root }) { // Deliberately slow so the browser sees the pending/Back state; // it must still answer so the serialized request queue continues. setTimeout(() => { - client.send({ id: request.id, type: 'run', run_detail: detail(2, live) }); + client.send({ id: request.id, type: 'run', run_detail: detail(2, live, false, runs) }); }, 2500); return; } @@ -461,13 +461,13 @@ export async function startFixture({ root }) { return; } client.send({ id: request.id, type: 'run', run_detail: id === 5 - ? humanDetail(decisionAccepted) : detail(id, live, canceled.has(id)) }); + ? humanDetail(decisionAccepted, runs) : detail(id, live, canceled.has(id), runs) }); return; } if (request.type === 'cancel_run' && request.run_id === 4) { cancelRequests.push({ run_id: request.run_id }); canceled.add(4); - client.send({ id: request.id, type: 'run', run_detail: detail(4, live, true) }); + client.send({ id: request.id, type: 'run', run_detail: detail(4, live, true, runs) }); return; } if (request.type === 'decide_run' && request.run_id === 5 && @@ -475,7 +475,7 @@ export async function startFixture({ root }) { decisionRequests.push({ run_id: request.run_id, stage: request.stage, option: request.option, ...(request.feedback ? { feedback: request.feedback } : {}) }); decisionAccepted = true; - client.send({ id: request.id, type: 'run', run_detail: humanDetail(true) }); + client.send({ id: request.id, type: 'run', run_detail: humanDetail(true, runs) }); return; } if (request.type === 'search') { From b8f6d0b94ad614cfee4cf56c11f6c4d33e9753e1 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 22 Oct 2026 00:57:06 +0100 Subject: [PATCH 03/13] docs(app): record the live Needs-you bell and the republished preview --- app/PARITY.md | 2 +- app/WORK.md | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/app/PARITY.md b/app/PARITY.md index 8629d62a..7798a517 100644 --- a/app/PARITY.md +++ b/app/PARITY.md @@ -52,7 +52,7 @@ or scratch servers only, never real operator sessions/runs/workflows. | Saved schedule list | Source | pipeline entry and route registration, exact timer provenance vocabulary | | Schedule editor | Preview: pipeline Summary section creates/edits/pauses/deletes with the lossless draft and revision guard; conflict keeps the draft and shows the server words | Schedule-this-run seeding, schedules list entry/route | | Search | Preview: shell entry, /search route, focused field, restore on close | result target routing for pipeline/version/field/visit/artifact hits | -| Needs you | Preview: runs-list bell/count, native sheet, open/dismiss/clear persistence, live fold and reconnect reseed | notification transitions/permission, authenticated preview smoke | +| Needs you | Preview: runs-list bell/count from the same list rows, native sheet, open/dismiss/clear persistence, live fold and reconnect reseed | notification permission/transition notices, authenticated preview smoke | | Notifications | Missing | explicit permission/rationale, secure/unsupported/denied states, transition-only dedupe, background question notices | | Mobile replacement build | Scaffold only | Android build at end; all source portable to iOS, isolated IDs; device/OS behavior clearly separate | diff --git a/app/WORK.md b/app/WORK.md index 590c0a99..5b90cd43 100644 --- a/app/WORK.md +++ b/app/WORK.md @@ -49,7 +49,8 @@ All work under app/. Existing applications remain running and unchanged. | Stage definition | run77 retained/d88213d | review result-validation failure; manager verified retained slice and drove both-host probe (5 captures each) | merged main; ancestry verified | graph hook85 next | | Attention model | run82 /38f8576c + manager224f8ee |13min;44 tests; manager namespaced dismissals to this client and re-ran tests | merged main; ancestry verified | bell/sheet UI84 next | | Pipeline graph | Graph tab + stage pane wiring | run85 retained/0176720 | Code deadline recovery;62 pipelines tests + both-host probe; bounded measured canvas opens pinned definition | merged main; ancestry verified | published8096 | -| Needs you UI | Bell + native sheet | run84 retained/ee93d4f | review visit limit;72 tests; snapshot clear/dismiss both hosts | merged main; ancestry verified | Runs wiring90 | +| Needs you UI | Bell + native sheet | run84 retained/ee93d4f | review visit limit;72 tests; snapshot clear/dismiss both hosts | merged main; ancestry verified | published8096 | +| Needs you wiring | Live bell over the Runs list | run90 /a309d9d5 (rebased) | evidence bug blocked the run; manager rebased onto main, resolved PARITY, ran239 attention/runs tests; probe 4 captures both hosts at 320/2x | merged main; ancestry verified | notification permission/transitions | | Chat screen | Live Chat destination + read-only history | run79 retained/86a9b4a | deadline recovery;110 focused tests + both-host probes; real app probe verifies /chat/ses route and stored turn | merged main; ancestry verified | published8096 | | Retry/restart | Retry and restart in actual detail | run80 /2de1c90 base |50min; focused suites; accepted-run navigation verified | merged main; ancestry verified | published8096 | | Artifact gallery | Recorded visit groups in run detail | run81 retained/df6524c | Code deadline recovery;29 tests +16 fixture captures; real app probe verifies list/selection | merged main; ancestry verified | published8096 | From d5f24b8259b0163c19469e5ed1007e1e2a95c54b Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 22 Oct 2026 01:08:40 +0100 Subject: [PATCH 04/13] deps(app): declare package:web and harden the composer probe boot wait --- app/pubspec.lock | 2 +- app/pubspec.yaml | 1 + app/tool/chat_composer_probe.mjs | 12 ++++++++++-- 3 files changed, 12 insertions(+), 3 deletions(-) diff --git a/app/pubspec.lock b/app/pubspec.lock index b36726e5..370b4079 100644 --- a/app/pubspec.lock +++ b/app/pubspec.lock @@ -374,7 +374,7 @@ packages: source: hosted version: "15.4.0" web: - dependency: transitive + dependency: "direct main" description: name: web sha256: "868d88a33d8a87b18ffc05f9f030ba328ffefba92d6c127917a2ba740f9cfe4a" diff --git a/app/pubspec.yaml b/app/pubspec.yaml index fa4a079a..ec8624bf 100644 --- a/app/pubspec.yaml +++ b/app/pubspec.yaml @@ -38,6 +38,7 @@ dependencies: shared_preferences: ^2.5.6 flutter_web_plugins: sdk: flutter + web: ^1.1.1 dev_dependencies: flutter_test: diff --git a/app/tool/chat_composer_probe.mjs b/app/tool/chat_composer_probe.mjs index 95932f4e..c5988ac4 100644 --- a/app/tool/chat_composer_probe.mjs +++ b/app/tool/chat_composer_probe.mjs @@ -82,6 +82,9 @@ try { if (msg.method?.includes('detached') || msg.method?.includes('crashed')) { console.error('CDP event', JSON.stringify(msg)); } + if (msg.method === 'Runtime.exceptionThrown') { + console.error('PAGE EXCEPTION', JSON.stringify(msg.params?.exceptionDetails?.exception?.description ?? msg.params?.exceptionDetails?.text)); + } if (msg.id && pending.has(msg.id)) { pending.get(msg.id)(msg); pending.delete(msg.id); } }); const send = (method, params = {}, sessionId) => new Promise(resolve => { @@ -101,7 +104,12 @@ try { if (response.error) throw new Error(`Runtime.evaluate failed: ${JSON.stringify(response)}`); return response.result?.result?.value; }; - await delay(3500); + // A cold bundle can need longer than a fixed delay before Flutter publishes + // its semantics placeholder; wait for it instead of sampling a blank page. + for (let i = 0; i < 120; i++) { + if (await evaluate("Boolean(document.querySelector('flt-semantics-placeholder'))")) break; + await delay(100); + } await evaluate("document.querySelector('flt-semantics-placeholder')?.click()"); await delay(1800); @@ -111,7 +119,7 @@ try { const assertSemantics = async (text, what) => { const read = await semanticText(); if (!read.toLowerCase().replace(/\s+/g, ' ').includes(text.toLowerCase())) { - throw new Error(`${what}: semantics lacks ${JSON.stringify(text)}:\n${read.slice(0, 3000)}`); + throw new Error(`${what}: semantics lacks ${JSON.stringify(text)}\nbody: ${(await evaluate('document.body?.innerText ?? \"\"') || '').slice(0, 800)}\n${read.slice(0, 2000)}`); } }; const clickLabel = async (label, { contains = false } = {}) => { From cb0242b7095b55459aeec77f70edd88a7774e7ae Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 22 Oct 2026 01:09:06 +0100 Subject: [PATCH 05/13] docs(app): set the remaining autonomous queue in dependency order --- app/WORK.md | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/app/WORK.md b/app/WORK.md index 5b90cd43..949eabb3 100644 --- a/app/WORK.md +++ b/app/WORK.md @@ -473,3 +473,43 @@ resuming or retrying; preserve partial work. On success inspect actual diff and checks, integrate, verify ancestry, then launch the next ready item. Do not rerun completed work just because session export or landing failed. Keep source, tests, landing and preview states separate. No production cutover in this phase. +## Remaining queue after the 95-101 wave +Autonomous target: finish every row in `PARITY.md` except the mobile build, which +stays last by agreement. Each item is one reviewed slice with focused tests and a +both-host browser probe where it is visible. + +In flight: 95 recorded visit pane; 96 chat permission/question cards; 97 start a +pipeline; 98 chat list create/rename/star/close; 99 artifact download/share as +named files; 100 notification capability + transition dedupe; 101 graph +pan/zoom/expanded view. + +Then, in dependency order: +1. Manager wiring: notification permission tile into Settings and transition + notifications from the Runs attention controller; graph expanded view opened + from the pipeline Graph tab. +2. Search result target routing (pipeline/version/field/visit/artifact) in + `application/search_destination.dart` plus the minimum public selection APIs in + the owning features. +3. Chat attachments: picker + paste, 1 MiB bounded envelope, named removable + chips, history reconciliation. +4. Chat activity/reasoning/tools overlays with lifecycle, input/output, error, + duration and edit diff. +5. Chat model selection, numeric Info (unknown != 0) and bounded background-task + pages. +6. Chat slash command palette, unknown-command send-as-message, dismissible local + notices, saved scroll/follow. +7. Run summary fields and exact empty/unknown wording; changes per-visit capture + entry and paging; session audit/export repair facts. +8. Artifact turn documents in the gallery (input/memory/output/session.html). +9. Pipeline list summary metadata/miniatures and pinned detail URLs; schedules + list entry/route, timer provenance and schedule-this-run seeding. +10. Deep links: pipeline/version/stage/template/chat URLs and action/visit + queries; transport foreground recovery, persisted endpoint boot, protocol + warning, complete refresh semantics. +11. Templates link from a run detail; authenticated preview smoke notes. +12. Android testing build, iOS portability audit, device verification. + +Standing rules: keep the preview published with a rollback after each landing; +never claim authenticated production mutations, OS sharing/notifications on +mobile or device behaviour from web fixture evidence; keep mobile labelled +unverified until the final build. From 77186042681273312d7f8519cc24c6964a2e9a3d Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 22 Oct 2026 01:23:24 +0100 Subject: [PATCH 06/13] feat(app): add the notification capability behind a platform seam An abstract NotificationBridge with a dart:js_interop web implementation and an honest unsupported stub; a NotificationController that reports only the platform's permission word, asks only from an explicit gesture, never re-prompts a denied answer, and notifies once per run+kind+finished marker under its own persisted ledger key. One reusable native NotificationPermissionTile for Settings, an isolated browser probe, and focused tests. No shell/settings wiring. --- .../attention/notify/notification_bridge.dart | 30 ++ .../notify/notification_bridge_stub.dart | 27 ++ .../notify/notification_bridge_web.dart | 95 +++++ .../notify/notification_controller.dart | 194 +++++++++ .../attention/notify/notification_ledger.dart | 91 ++++ .../attention/notify/notification_models.dart | 170 ++++++++ .../attention/notify/notification_store.dart | 83 ++++ .../ui/notification_permission_tile.dart | 127 ++++++ app/notes/A2-notify.md | 128 ++++++ .../notify/notification_controller_test.dart | 403 ++++++++++++++++++ .../notify/notification_ledger_test.dart | 89 ++++ .../notify/notification_models_test.dart | 155 +++++++ .../notify/notification_test_support.dart | 112 +++++ .../ui/notification_permission_tile_test.dart | 140 ++++++ app/tool/notification_probe.dart | 265 ++++++++++++ app/tool/notification_probe.mjs | 295 +++++++++++++ 16 files changed, 2404 insertions(+) create mode 100644 app/lib/features/attention/notify/notification_bridge.dart create mode 100644 app/lib/features/attention/notify/notification_bridge_stub.dart create mode 100644 app/lib/features/attention/notify/notification_bridge_web.dart create mode 100644 app/lib/features/attention/notify/notification_controller.dart create mode 100644 app/lib/features/attention/notify/notification_ledger.dart create mode 100644 app/lib/features/attention/notify/notification_models.dart create mode 100644 app/lib/features/attention/notify/notification_store.dart create mode 100644 app/lib/features/attention/ui/notification_permission_tile.dart create mode 100644 app/notes/A2-notify.md create mode 100644 app/test/features/attention/notify/notification_controller_test.dart create mode 100644 app/test/features/attention/notify/notification_ledger_test.dart create mode 100644 app/test/features/attention/notify/notification_models_test.dart create mode 100644 app/test/features/attention/notify/notification_test_support.dart create mode 100644 app/test/features/attention/ui/notification_permission_tile_test.dart create mode 100644 app/tool/notification_probe.dart create mode 100644 app/tool/notification_probe.mjs diff --git a/app/lib/features/attention/notify/notification_bridge.dart b/app/lib/features/attention/notify/notification_bridge.dart new file mode 100644 index 00000000..b1ec61bd --- /dev/null +++ b/app/lib/features/attention/notify/notification_bridge.dart @@ -0,0 +1,30 @@ +import 'notification_bridge_stub.dart' + if (dart.library.js_interop) 'notification_bridge_web.dart' + as impl; +import 'notification_models.dart'; + +/// Where the notification capability actually posts. +/// +/// The controller depends on this, not on any platform, so the dedupe, the +/// permission rules and the content are all testable without a browser. A bridge +/// answers the platform's real facts and never guesses: [environment] returns +/// what the platform says (including "unsupported"), [requestPermission] is only +/// called from an explicit gesture, and [show] reports whether the platform +/// accepted the notification. +abstract interface class NotificationBridge { + /// The platform's own facts: support, secure context and permission word. + NotificationEnvironment environment(); + + /// Asks the platform, from an explicit operator gesture, and returns its own + /// answer word. Never a guess, and never called by the controller on its own. + Future requestPermission(); + + /// Shows one notification, attaching [onTap] as its tap intent when given. + /// Returns whether the platform accepted it. + bool show(NotificationMessage message, {void Function()? onTap}); +} + +/// The bridge for the current platform: the browser `Notification` on the web, +/// an honest "unsupported" elsewhere. +NotificationBridge createNotificationBridge() => + impl.createNotificationBridge(); diff --git a/app/lib/features/attention/notify/notification_bridge_stub.dart b/app/lib/features/attention/notify/notification_bridge_stub.dart new file mode 100644 index 00000000..94e837ea --- /dev/null +++ b/app/lib/features/attention/notify/notification_bridge_stub.dart @@ -0,0 +1,27 @@ +import 'notification_bridge.dart'; +import 'notification_models.dart'; + +/// The non-web bridge: there is no browser Notification API to reach. +/// +/// It reports `unsupported` honestly rather than pretending a notification was +/// shown, so the surface falls back to the in-app `Needs you` channel. A native +/// platform notifier would replace this through the same seam. +class UnsupportedNotificationBridge implements NotificationBridge { + const UnsupportedNotificationBridge(); + + @override + NotificationEnvironment environment() => const NotificationEnvironment( + supported: false, + secureContext: false, + permission: 'default', + ); + + @override + Future requestPermission() async => 'default'; + + @override + bool show(NotificationMessage message, {void Function()? onTap}) => false; +} + +NotificationBridge createNotificationBridge() => + const UnsupportedNotificationBridge(); diff --git a/app/lib/features/attention/notify/notification_bridge_web.dart b/app/lib/features/attention/notify/notification_bridge_web.dart new file mode 100644 index 00000000..dcd1374f --- /dev/null +++ b/app/lib/features/attention/notify/notification_bridge_web.dart @@ -0,0 +1,95 @@ +import 'dart:js_interop'; +import 'dart:js_interop_unsafe'; + +import 'notification_bridge.dart'; +import 'notification_models.dart'; + +/// The browser's `Notification` constructor. +/// +/// Declared with `dart:js_interop` rather than `dart:html`, so the same source +/// compiles for the JavaScript and WebAssembly web targets. Every member is +/// reached only after [_supported] has confirmed the global exists, so an +/// unsupported browser never touches it. +@JS('Notification') +extension type _Notification._(JSObject _) implements JSObject { + external factory _Notification(JSString title, _NotificationOptions options); + + external static JSString get permission; + + external static JSPromise requestPermission(); + + external set onclick(JSFunction? handler); +} + +/// The `{ body, tag }` options object one notification is created with. +extension type _NotificationOptions._(JSObject _) implements JSObject { + external factory _NotificationOptions({JSString body, JSString tag}); +} + +/// Whether `globalThis.Notification` is really a constructor right now. +bool _supported() => + globalContext.getProperty('Notification'.toJS).isA(); + +/// The browser's own secure-context flag; anything but a real boolean is false. +bool _secureContext() { + final value = globalContext.getProperty('isSecureContext'.toJS); + return value.isA() && (value as JSBoolean).toDart; +} + +/// The browser bridge: the real `Notification` API, reached through +/// `dart:js_interop`. +/// +/// Nothing is fabricated. [environment] reports the constructor's own +/// `permission` word and the page's own `isSecureContext`; an unsupported +/// browser is reported as unsupported rather than as a default grant. +class WebNotificationBridge implements NotificationBridge { + const WebNotificationBridge(); + + @override + NotificationEnvironment environment() { + if (!_supported()) { + return const NotificationEnvironment( + supported: false, + secureContext: false, + permission: 'default', + ); + } + final raw = _Notification.permission.toDart; + return NotificationEnvironment( + supported: true, + secureContext: _secureContext(), + permission: raw == 'granted' || raw == 'denied' ? raw : 'default', + ); + } + + @override + Future requestPermission() async { + if (!_supported()) return 'default'; + try { + return (await _Notification.requestPermission().toDart).toDart; + } catch (_) { + // A browser that refuses the request keeps the honest fallback wording. + return 'default'; + } + } + + @override + bool show(NotificationMessage message, {void Function()? onTap}) { + if (!_supported()) return false; + try { + final notification = _Notification( + message.title.toJS, + _NotificationOptions(body: message.body.toJS, tag: message.tag.toJS), + ); + final open = onTap; + if (open != null) notification.onclick = (() => open()).toJS; + return true; + } catch (_) { + // Some browsers can throw even with permission granted; the in-app Needs + // you surface remains the only honest channel and nothing is faked. + return false; + } + } +} + +NotificationBridge createNotificationBridge() => const WebNotificationBridge(); diff --git a/app/lib/features/attention/notify/notification_controller.dart b/app/lib/features/attention/notify/notification_controller.dart new file mode 100644 index 00000000..d0e67dae --- /dev/null +++ b/app/lib/features/attention/notify/notification_controller.dart @@ -0,0 +1,194 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; + +import '../domain/attention_transitions.dart'; +import 'notification_bridge.dart'; +import 'notification_ledger.dart'; +import 'notification_models.dart'; +import 'notification_store.dart'; + +/// The live notification capability behind the `Needs you` surface. +/// +/// It never invents a permission: [permission] is the platform's own answer, +/// read from the [NotificationBridge], and `granted` is only ever reported when +/// the platform said so. Nothing asks for permission on its own — +/// [requestPermission] is the one explicit call — and a denied answer is never +/// re-asked. +/// +/// Only live attention transitions raise a notification: the caller publishes +/// the transitions the attention model raised (never the initial seed), and one +/// identity is posted at most once, including across a reconnect, because the +/// ledger records the identity before the platform is asked to show it. A +/// dismissed identity is recorded but never shown. +/// +/// The manager wires it: set [onOpenRun] to open a run, call [load] once, and +/// call [publishTransitions] with the attention controller's transitions. That +/// call is idempotent, so passing the whole accumulated list is safe. +class NotificationController extends ChangeNotifier { + NotificationController({required this.store, NotificationBridge? bridge}) + : bridge = bridge ?? createNotificationBridge(); + + /// The most notifications one publish posts, so a burst cannot flood the tray. + static const maxNotificationsPerBatch = 5; + + final NotificationStore store; + final NotificationBridge bridge; + + /// The tap seam: the manager sets this to open a run. Nothing here navigates. + void Function(int runId)? onOpenRun; + + NotificationLedger _ledger = const NotificationLedger(); + NotificationPermissionState _permission = + NotificationPermissionState.unsupported; + bool _loaded = false; + bool _disposed = false; + int _posted = 0; + + /// The platform's own permission state for this page. + NotificationPermissionState get permission => _permission; + + /// True once the persisted ledger and the platform facts have been read. + bool get loaded => _loaded; + + /// Whether the operator has ever been asked for permission. + bool get asked => _ledger.asked; + + /// The transition identities this client has already recorded. + Set get notified => _ledger.notified; + + /// True only when the platform itself reported `granted`. + bool get canNotify => _permission == NotificationPermissionState.granted; + + /// How many notifications this session has actually posted. + int get postedCount => _posted; + + /// Reads the persisted ledger and the platform's real permission facts once. + Future load() async { + NotificationLedger ledger; + try { + ledger = decodeNotificationLedger(await store.read()); + } catch (_) { + ledger = const NotificationLedger(); + } + if (_disposed) return; + _ledger = ledger; + _permission = notificationStateOf(bridge.environment()); + _loaded = true; + notifyListeners(); + } + + /// Re-reads the platform's facts without asking anything, for example after + /// the browser's site settings changed and the page regained focus. + void refreshPermission() { + if (_disposed) return; + final next = notificationStateOf(bridge.environment()); + if (next == _permission) return; + _permission = next; + notifyListeners(); + } + + /// The one explicit request, only ever called from an operator gesture. + /// + /// A supported, secure page that has not decided is asked, and every other + /// state answers with the platform's own word instead of prompting again. The + /// request is issued before any await, so it stays inside the gesture that + /// triggered it. + Future requestPermission() async { + if (_disposed) return _permission; + final environment = bridge.environment(); + _permission = notificationStateOf(environment); + if (_permission != NotificationPermissionState.notRequested) { + notifyListeners(); + return _permission; + } + // The operator was asked, whatever the answer; persisted without awaiting so + // the platform request stays in this gesture's frame. + _ledger = _ledger.withAsked(true); + unawaited(_persist(_ledger)); + notifyListeners(); + + String answer; + try { + answer = await bridge.requestPermission(); + } catch (_) { + answer = ''; + } + if (_disposed) return _permission; + final word = answer.trim().toLowerCase(); + _permission = notificationStateOf( + NotificationEnvironment( + supported: environment.supported, + secureContext: environment.secureContext, + permission: word == 'granted' || word == 'denied' + ? word + : environment.permission, + ), + ); + notifyListeners(); + return _permission; + } + + /// Posts one notification per live transition, in order. + /// + /// The initial seed raises no transition, so it never reaches here. A + /// transition the operator dismissed, one the ledger already recorded and one + /// past [maxNotificationsPerBatch] post nothing; every identity examined is + /// recorded first, so a later publish cannot repeat it. Returns how many + /// notifications the platform accepted. + int publishTransitions( + Iterable transitions, { + Set dismissed = const {}, + }) { + if (_disposed) return 0; + var posted = 0; + var recorded = false; + for (final transition in transitions) { + if (posted >= maxNotificationsPerBatch) break; + final identity = notificationIdentity(transition); + if (_ledger.hasNotified(identity)) continue; + _ledger = _ledger.recording(identity); + recorded = true; + if (dismissed.contains(transition.key)) continue; + if (!canNotify) continue; + final open = onOpenRun; + final message = NotificationMessage( + runId: transition.runId, + title: notificationAlertTitle(transition.kind), + body: notificationAlertBody(transition.entry), + tag: identity, + ); + var shown = false; + try { + shown = bridge.show( + message, + onTap: open == null ? null : () => open(transition.runId), + ); + } catch (_) { + shown = false; + } + if (shown) { + posted++; + _posted++; + } + } + if (recorded) unawaited(_persist(_ledger)); + return posted; + } + + /// Writes the ledger without ever throwing into the caller's frame. + Future _persist(NotificationLedger ledger) async { + if (_disposed) return; + try { + await store.write(encodeNotificationLedger(ledger)); + } catch (_) { + // The in-memory ledger still applies for this session. + } + } + + @override + void dispose() { + _disposed = true; + super.dispose(); + } +} diff --git a/app/lib/features/attention/notify/notification_ledger.dart b/app/lib/features/attention/notify/notification_ledger.dart new file mode 100644 index 00000000..3d8f35d6 --- /dev/null +++ b/app/lib/features/attention/notify/notification_ledger.dart @@ -0,0 +1,91 @@ +import 'dart:convert'; + +import '../../../core/api_gateway.dart'; +import '../domain/attention_transitions.dart'; + +/// This client's own storage key for the notification ledger, namespaced like +/// the rest of the app. It is deliberately not the legacy web key, so neither +/// client rewrites the other's local state on a shared origin. +const notificationStorageKey = 'pipelines.next.notify.v1'; + +/// The marker that separates two transitions of one run and kind: the server's +/// own `finished_at` when it recorded one, else the run's creation time — the +/// same recency the attention surface orders by. +/// +/// A run that is retried and fails again carries a new marker, so its new +/// failure is a new identity and can notify once more; the same failure can +/// never notify twice. +String notificationMarker(JsonMap run) { + final finished = '${run['finished_at'] ?? ''}'.trim(); + return finished.isNotEmpty ? finished : '${run['created_at'] ?? ''}'.trim(); +} + +/// The identity of one transition: run, kind and marker. The unit of dedupe. +String notificationIdentity(AttentionTransition transition) => + '${transition.key}@${notificationMarker(transition.run)}'; + +/// What this client has already announced, plus whether the operator has ever +/// been asked. +/// +/// The ledger is pure: it records identities and decides whether one is new. +/// Persistence is the store's job. +/// +/// An identity is never forgotten while the ledger lives, so publishing the same +/// transition list again is always idempotent. A genuinely new transition of the +/// same run and kind is a new identity because its marker changed (see +/// [notificationMarker]); the browser's in-session prune is deliberately not +/// reproduced, because a prune would let an already-announced transition that is +/// still in the caller's list be posted a second time. +class NotificationLedger { + const NotificationLedger({ + this.notified = const {}, + this.asked = false, + }); + + /// The transition identities already recorded, in no particular order. + final Set notified; + + /// Whether the operator has ever been asked for permission. + final bool asked; + + bool hasNotified(String identity) => notified.contains(identity); + + /// The ledger with [identity] recorded. + NotificationLedger recording(String identity) => + NotificationLedger(notified: {...notified, identity}, asked: asked); + + NotificationLedger withAsked(bool value) => + NotificationLedger(notified: notified, asked: value); +} + +/// The one-line JSON the ledger is stored as. The identities are sorted so an +/// unchanged ledger always encodes to the same bytes. +String encodeNotificationLedger(NotificationLedger ledger) { + final identities = ledger.notified.where((id) => id.isNotEmpty).toList() + ..sort(); + return jsonEncode({'asked': ledger.asked, 'notified': identities}); +} + +/// Decodes a stored value into a ledger. Total: blank text, unreadable JSON, a +/// non-map, a non-boolean `asked` and non-string members all decode to the +/// members that can be read, and a malformed value never throws. +NotificationLedger decodeNotificationLedger(String? stored) { + final text = (stored ?? '').trim(); + if (text.isEmpty) return const NotificationLedger(); + dynamic parsed; + try { + parsed = jsonDecode(text); + } catch (_) { + return const NotificationLedger(); + } + if (parsed is! Map) return const NotificationLedger(); + final raw = parsed['notified']; + return NotificationLedger( + notified: { + if (raw is List) + for (final value in raw) + if (value is String && value.isNotEmpty) value, + }, + asked: parsed['asked'] == true, + ); +} diff --git a/app/lib/features/attention/notify/notification_models.dart b/app/lib/features/attention/notify/notification_models.dart new file mode 100644 index 00000000..f1f8777b --- /dev/null +++ b/app/lib/features/attention/notify/notification_models.dart @@ -0,0 +1,170 @@ +import '../domain/attention_models.dart'; + +/// The permission state the notification surface reports. +/// +/// The Dart names are this client's; [wireName] is the browser model's own word +/// (`unsupported` | `insecure` | `default` | `granted` | `denied`) so the two +/// clients' vocabularies stay traceable. [notRequested] is the Notification +/// API's `default`: supported and secure, but the operator has not decided yet. +enum NotificationPermissionState { + unsupported('unsupported'), + needsSecureContext('insecure'), + notRequested('default'), + granted('granted'), + denied('denied'); + + const NotificationPermissionState(this.wireName); + + /// The browser model's own word for this state (`web/src/notify.js`). + final String wireName; +} + +/// The platform's own notification facts, as the bridge answers them. +/// +/// [permission] is the Notification API's raw word; anything unrecognised is +/// read as `default` rather than guessed, exactly as the browser does. +class NotificationEnvironment { + const NotificationEnvironment({ + required this.supported, + required this.secureContext, + required this.permission, + }); + + final bool supported; + final bool secureContext; + final String permission; +} + +/// The permission state for one environment. +/// +/// Only the platform's own answers decide it: an unsupported API and an +/// insecure page are reported before the permission word, and `granted` is never +/// assumed — a page that has not been granted stays [notRequested]. +NotificationPermissionState notificationStateOf( + NotificationEnvironment environment, +) { + if (!environment.supported) return NotificationPermissionState.unsupported; + if (!environment.secureContext) { + return NotificationPermissionState.needsSecureContext; + } + switch (environment.permission) { + case 'granted': + return NotificationPermissionState.granted; + case 'denied': + return NotificationPermissionState.denied; + default: + return NotificationPermissionState.notRequested; + } +} + +/// Android's NOTIFICATION_RATIONALE, verbatim (`RunAlerts.kt`, `notify.js`). +const notificationRationale = + 'Pipelines can notify you when a run is waiting for your decision or has ' + 'failed. Without it, those runs still appear in the in-app Needs you ' + 'surface.'; + +/// The Settings section heading and the explicit-gesture action label. +const notificationSectionTitle = 'Notifications'; +const notificationRequestLabel = 'Enable notifications'; + +/// The honest wording for every state, verbatim from `web/src/notify.js`; each +/// says plainly that the in-app `Needs you` surface is the only channel when the +/// platform cannot notify. +const notificationUnsupportedCopy = + 'This browser does not support notifications. The in-app Needs you surface ' + 'is the only channel.'; +const notificationInsecureCopy = + 'Notifications need a secure context (https or localhost). This page is not ' + 'secure, so the in-app Needs you surface is the only channel.'; +const notificationGrantedCopy = + 'Notifications are on. Failed and waiting runs will raise a browser ' + 'notification.'; +const notificationDeniedCopy = + 'Notifications are blocked for this site. Allow them in the browser\'s site ' + 'settings to use them; until then the in-app Needs you surface is the only ' + 'channel.'; +const notificationDefaultCopy = + 'Notifications are off. Enable them to be told when a run fails or needs ' + 'your decision.'; +const notificationDefaultAskedCopy = + 'Notifications are still off. Your browser did not grant permission when ' + 'asked; you can ask again, or the in-app Needs you surface remains the only ' + 'channel.'; + +/// The total permission view for the Settings tile. +/// +/// Only a supported, secure page whose permission is still `default` offers the +/// request control, and [asked] only changes the honest wording — nothing here +/// asks for permission on its own. +class NotificationPermissionView { + const NotificationPermissionView({ + required this.state, + required this.body, + required this.canRequest, + required this.actionLabel, + required this.asked, + }); + + final NotificationPermissionState state; + final String body; + final bool canRequest; + final String? actionLabel; + final bool asked; +} + +/// The view for one state, with the browser's own copy for it. +NotificationPermissionView notificationPermissionView( + NotificationPermissionState state, { + bool asked = false, +}) { + final canRequest = state == NotificationPermissionState.notRequested; + final body = switch (state) { + NotificationPermissionState.unsupported => notificationUnsupportedCopy, + NotificationPermissionState.needsSecureContext => + notificationInsecureCopy, + NotificationPermissionState.granted => notificationGrantedCopy, + NotificationPermissionState.denied => notificationDeniedCopy, + NotificationPermissionState.notRequested => + asked ? notificationDefaultAskedCopy : notificationDefaultCopy, + }; + return NotificationPermissionView( + state: state, + body: body, + canRequest: canRequest, + actionLabel: canRequest ? notificationRequestLabel : null, + asked: asked, + ); +} + +/// The short headline one kind shows; the browser's `alertTitle` verbatim. +String notificationAlertTitle(AttentionKind kind) => switch (kind) { + AttentionKind.decision => 'A run needs your decision', + AttentionKind.failed => 'A run failed', +}; + +/// The line naming the run: its label, then the pipeline it belongs to. +/// +/// The words are the entry's own — a blank or equal pipeline is never repeated, +/// so there is no trailing separator and nothing is invented. +String notificationAlertBody(AttentionEntry entry) { + final pipeline = entry.pipeline; + final label = entry.label; + if (pipeline.isEmpty || pipeline == label) return label; + return '$label \u00b7 $pipeline'; +} + +/// One notification the platform is asked to show: the entry's own words, plus +/// the stable identity used as the browser's coalescing tag. +class NotificationMessage { + const NotificationMessage({ + required this.runId, + required this.title, + required this.body, + required this.tag, + }); + + final int runId; + final String title; + final String body; + final String tag; +} diff --git a/app/lib/features/attention/notify/notification_store.dart b/app/lib/features/attention/notify/notification_store.dart new file mode 100644 index 00000000..27b53806 --- /dev/null +++ b/app/lib/features/attention/notify/notification_store.dart @@ -0,0 +1,83 @@ +import 'package:shared_preferences/shared_preferences.dart'; + +import 'notification_ledger.dart'; + +/// The persistence seam for the notification ledger. +/// +/// The controller only ever hands over the exact string produced by +/// [encodeNotificationLedger], so a store cannot invent a different format. +/// Both directions are allowed to fail: a caller treats a null read as "nothing +/// recorded yet" and a false write as "this session only". +abstract interface class NotificationStore { + Future read(); + + Future write(String value); +} + +/// `shared_preferences` storage under the ledger's own key. +/// +/// Reads and writes are total: an unavailable plugin, a disabled store or a full +/// disk returns null/false instead of throwing into the caller's frame. Only the +/// documented [notificationStorageKey] is touched, never the attention key or the +/// legacy web key. +class SharedPreferencesNotificationStore implements NotificationStore { + const SharedPreferencesNotificationStore(); + + Future _preferences() async { + try { + return await SharedPreferences.getInstance(); + } catch (_) { + return null; + } + } + + @override + Future read() async { + final preferences = await _preferences(); + if (preferences == null) return null; + try { + return preferences.getString(notificationStorageKey); + } catch (_) { + return null; + } + } + + @override + Future write(String value) async { + final preferences = await _preferences(); + if (preferences == null) return false; + try { + return await preferences.setString(notificationStorageKey, value); + } catch (_) { + return false; + } + } +} + +/// An in-memory store for tests and isolated fixtures. +/// +/// It never touches the platform store, so a probe or widget test cannot mutate +/// a real operator's persisted ledger. [failReads] and [failWrites] reproduce an +/// unavailable store without throwing. +class MemoryNotificationStore implements NotificationStore { + MemoryNotificationStore({this.stored}); + + String? stored; + bool failReads = false; + bool failWrites = false; + int writes = 0; + + @override + Future read() async { + if (failReads) throw StateError('notification store unavailable'); + return stored; + } + + @override + Future write(String value) async { + writes++; + if (failWrites) throw StateError('notification store is read-only'); + stored = value; + return true; + } +} diff --git a/app/lib/features/attention/ui/notification_permission_tile.dart b/app/lib/features/attention/ui/notification_permission_tile.dart new file mode 100644 index 00000000..16de654d --- /dev/null +++ b/app/lib/features/attention/ui/notification_permission_tile.dart @@ -0,0 +1,127 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../ui/adaptive/host.dart'; +import '../notify/notification_models.dart'; + +/// The permission tile's root, so a caller can find it whichever host draws it. +const notificationTileKey = ValueKey('notification-permission-tile'); + +/// The explicit-gesture Enable action, present only when a request is possible. +const notificationEnableKey = ValueKey( + 'notification-permission-enable', +); + +/// The honest state line, which says plainly when the in-app surface is the +/// only channel. +const notificationStateKey = ValueKey('notification-permission-state'); + +/// The reusable Notifications permission tile for Settings. +/// +/// It renders the platform's own [state] with the browser's own copy, shows the +/// Android rationale verbatim, and offers the [notificationRequestLabel] action +/// only while a request is still possible. Nothing here asks for permission on +/// its own — [onRequest] is the caller's explicit-gesture handler, and the tile +/// never guesses a grant. +/// +/// The caller owns the surrounding section/card and passes the live state; the +/// tile reads no store, bridge or clock. +class NotificationPermissionTile extends StatelessWidget { + const NotificationPermissionTile({ + super.key, + required this.state, + this.asked = false, + this.onRequest, + this.cupertino, + }); + + final NotificationPermissionState state; + + /// Whether the operator has already been asked; only changes the wording. + final bool asked; + + /// The explicit-gesture handler. Absent means no action is drawn even when a + /// request would be possible. + final VoidCallback? onRequest; + + /// Forces the native host in tests and fixtures; otherwise the ambient + /// [usesCupertinoHost] decides. + final bool? cupertino; + + @override + Widget build(BuildContext context) { + final view = notificationPermissionView(state, asked: asked); + final native = cupertino ?? usesCupertinoHost(context); + final action = view.canRequest && onRequest != null + ? _action(native, view.actionLabel!, onRequest!) + : null; + final bodyStyle = native + ? CupertinoTheme.of(context).textTheme.textStyle.copyWith( + color: CupertinoColors.secondaryLabel.resolveFrom(context), + ) + : Theme.of(context).textTheme.bodyMedium?.copyWith( + color: Theme.of(context).colorScheme.onSurfaceVariant, + ); + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + native + ? CupertinoListTile( + key: notificationTileKey, + leading: const Icon(CupertinoIcons.bell), + title: const Text(notificationSectionTitle), + ) + : ListTile( + key: notificationTileKey, + leading: const Icon(Icons.notifications_outlined), + title: const Text(notificationSectionTitle), + ), + Padding( + padding: const EdgeInsetsDirectional.fromSTEB(16, 0, 16, 12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(notificationRationale, style: bodyStyle), + const SizedBox(height: 8), + Semantics( + liveRegion: true, + child: Text( + view.body, + key: notificationStateKey, + style: bodyStyle, + ), + ), + // The action sits on its own row, as the browser's settings + // section does: a native button in a row's trailing slot would + // squeeze the section title to one character per line at large + // text, and its label is too long to share the row. + if (action != null) ...[ + const SizedBox(height: 8), + Align( + alignment: AlignmentDirectional.centerStart, + child: action, + ), + ], + ], + ), + ), + ], + ); + } + + Widget _action(bool native, String label, VoidCallback onRequest) { + if (native) { + return CupertinoButton( + key: notificationEnableKey, + padding: EdgeInsets.zero, + onPressed: onRequest, + child: Text(label), + ); + } + return TextButton( + key: notificationEnableKey, + onPressed: onRequest, + child: Text(label), + ); + } +} diff --git a/app/notes/A2-notify.md b/app/notes/A2-notify.md new file mode 100644 index 00000000..7045f533 --- /dev/null +++ b/app/notes/A2-notify.md @@ -0,0 +1,128 @@ +# A2 — notification capability behind a platform seam + +The notification capability exists as reusable Dart under +`lib/features/attention/notify/`, plus one reusable Settings tile at +`lib/features/attention/ui/notification_permission_tile.dart`. Nothing was wired +into the shell, `Settings`, the application or the Runs screen, and no tracked +file outside those paths changed (`git status` shows only new files). + +## What is there + +| File | Lines | Role | +| --- | --- | --- | +| `notify/notification_models.dart` | 170 | permission state, environment, copy, permission view, alert title/body, `NotificationMessage` | +| `notify/notification_bridge.dart` | 30 | the abstract `NotificationBridge` + the conditional-import factory | +| `notify/notification_bridge_web.dart` | 95 | the real `Notification` API via `dart:js_interop` (no `package:web`) | +| `notify/notification_bridge_stub.dart` | 27 | non-web stub that reports `unsupported` honestly | +| `notify/notification_ledger.dart` | 91 | identity (run+kind+marker), ledger, total JSON codec, `pipelines.next.notify.v1` | +| `notify/notification_store.dart` | 83 | injectable store seam; total `shared_preferences` impl + memory impl | +| `notify/notification_controller.dart` | 194 | the `ChangeNotifier` capability | +| `ui/notification_permission_tile.dart` | 127 | the reusable native tile | +| `tool/notification_probe.dart` / `.mjs` | 265 / 295 | isolated real-browser probe | + +## Platform seam + +`NotificationBridge` answers the platform's own facts +(`environment()` → `supported`, `secureContext`, raw `permission`), +`requestPermission()` (only ever called from an explicit gesture) and +`show(message, onTap:)`. The web bridge declares `@JS('Notification')` with +`external factory`, `external static permission`, `external static +requestPermission` and an `onclick` setter, and reaches the global only after a +`globalContext` support check, so an unsupported browser is never touched. The +stub returns `supported: false` and `show() == false`. + +`NotificationController.permission` is one of `unsupported`, +`needsSecureContext`, `notRequested` (the API's own `default` — `default` is a +Dart reserved word, and each state exposes `wireName` = `unsupported` | +`insecure` | `default` | `granted` | `denied`), `granted`, `denied`. It is +derived only from `notificationStateOf(environment)`; `granted` is never assumed +from an unrecognised word. `requestPermission()` asks only while the state is +still `notRequested`, issues the platform request before any `await` so it stays +inside the gesture, persists `asked` without awaiting, and follows the platform's +answer. A denied state is never re-prompted. + +## Notify only on live transitions + +- The initial list seed raises no transition, so `publishTransitions` over the + attention controller's (empty) transition list posts nothing. +- The dedupe identity is `{runId}:{Kind}@{marker}` where the marker is the run's + trimmed `finished_at` else `created_at` — the same recency the surface orders + by. A retried run that fails again carries a new marker and notifies once more; + the same transition can never notify twice, including across a reconnect. +- The ledger records an identity before the platform is asked to show it and + persists it under `pipelines.next.notify.v1` through the injectable + `NotificationStore`. `publishTransitions` is therefore idempotent, so the + manager may pass the whole accumulated transition list. A store that throws on + read or write is swallowed; the in-memory ledger still applies for the session. +- A dismissed identity is recorded but never shown (the transition detector + already suppresses it; the publish guard covers a caller that passes it). +- Content is the entry's own words: the kind headline (`A run failed` / `A run + needs your decision`) and `label · pipeline`, matching `web/src/notify.js` and + `RunAlerts.kt` verbatim. Nothing is invented, and no `stage` field is added + because neither reference client's alert body carries one. +- A batch posts in order, bounded to `maxNotificationsPerBatch` (5); the rest are + posted on the next call because the ones already posted are recorded. + +## Wiring the manager still owes + +```dart +final notify = NotificationController(store: const SharedPreferencesNotificationStore()); +notify.onOpenRun = (runId) { /* open that run — navigation lives here, not in notify */ }; +await notify.load(); +// after each authoritative read / pushed frame the attention controller handles: +notify.publishTransitions(attention.transitions, dismissed: attention.dismissed); +``` + +`load()` once, and `publishTransitions` on every frame/seed, is enough; it is +idempotent. `refreshPermission()` re-reads the platform facts after a focus +change. The tile is embedded by the Settings screen with the live `state`/`asked` +and an `onRequest` that calls `notify.requestPermission()`. + +## Tests and evidence + +- `flutter test test/features/attention` — **135 passed** (the 43 new notify/tile + tests plus the existing attention suite; the new coverage is: seed never + notifies; one live transition once with its own words and identity; duplicate + frame and republished list silent; reconnect reseed and a rebuilt controller + silent; a genuinely new failure notifies again; dismissed excluded (detector and + publish guard); unsupported/needs-secure/denied/granted permission paths and + "denied is never re-prompted"; a prompt that grants nothing; the bounded batch; + the tap seam; an unavailable store and a throwing platform post; the non-web + stub; the tile copy per state, the asked wording, the Enable gesture and both + hosts at 320 logical px / 2x in dark with the action present). +- `flutter analyze` — **No issues found** (whole project). +- `flutter build web` (the real `lib/main.dart`) — **succeeded**. +- Real-browser probe (`tool/notification_probe.dart` + `.mjs`, isolated loopback + server, `Browser.grantPermissions` / `Browser.setPermission`, + `window.Notification` replaced with a recording spy before load): + **all 25 checks passed** — seed posted 0; one transition posted exactly 1 with + title `A run failed`, body `Nightly audit · nightly` and tag `1:Failed@…`; a + dismissed transition posted 0; a reconnect replay posted 1 in total; denied and + unsupported pages posted 0 and read their honest copy; all five tile states + read correctly on Material and Cupertino at 320 logical px / 2x. + Captures (copied to `public/captures/notify/`): `notification-transition-…`, + `notification-denied-…`, `notification-unsupported-…` and + `notification-tile-{unsupported,insecure,default,granted,denied}-{material,cupertino}-dark-320-2x.png` + (13 PNGs). + +One defect was found by the capture and fixed: putting the Enable action in a +`ListTile` trailing slot squeezed the section title to one glyph per line at +320 px / 2x, so the action now sits on its own row below the copy (as the +browser's settings section does), and the widget test guards it. + +## Deliberate limits + +- `PARITY.md`'s `Notifications` row is **still Missing**: this slice is a + capability plus a reusable tile, not a delivered Settings section or shell + wiring. The row should move when the manager embeds the tile and wires the + controller, with authenticated smoke evidence. +- The browser's in-session `pruneNotified` is deliberately not reproduced: a + prune would let an already-announced transition that is still in the caller's + list post a second time. A run that leaves and re-enters the *same* qualifying + state with an unchanged marker is therefore the same identity and does not + notify twice — which is what the run+kind+marker rule requires. +- A browser whose `Notification.requestPermission()` uses the legacy + callback-only form (no returned promise) falls back to the honest default + wording, as the web client also does. +- Mobile (Android/iOS) is unverified: the stub reports `unsupported` and no + device or OS notification behaviour was exercised. No `pubspec` change. diff --git a/app/test/features/attention/notify/notification_controller_test.dart b/app/test/features/attention/notify/notification_controller_test.dart new file mode 100644 index 00000000..e178a862 --- /dev/null +++ b/app/test/features/attention/notify/notification_controller_test.dart @@ -0,0 +1,403 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/attention/domain/attention_models.dart'; +import 'package:pipelines_app/features/attention/notify/notification_bridge.dart'; +import 'package:pipelines_app/features/attention/notify/notification_controller.dart'; +import 'package:pipelines_app/features/attention/notify/notification_ledger.dart'; +import 'package:pipelines_app/features/attention/notify/notification_models.dart'; +import 'package:pipelines_app/features/attention/notify/notification_store.dart'; + +import 'notification_test_support.dart'; + +/// Let the controller's fire-and-forget ledger write land. +Future settle() => Future.delayed(Duration.zero); + +void main() { + group('the seed never notifies', () { + test('an already failed and waiting list is silent', () async { + final attention = attentionController(); + final bridge = FakeNotificationBridge(); + final notify = NotificationController( + store: MemoryNotificationStore(), + bridge: bridge, + ); + addTearDown(attention.dispose); + addTearDown(notify.dispose); + await attention.load(); + await notify.load(); + + attention.seedRows([ + runSummary(1, 'failed', diagnostic: 'Stage 3 stopped'), + runSummary(2, 'waiting'), + ]); + + expect(attention.transitions, isEmpty); + expect(notify.publishTransitions(attention.transitions), 0); + expect(bridge.shown, isEmpty); + }); + }); + + group('a live transition notifies once', () { + test('the frame\'s own words and identity are used', () async { + final attention = attentionController(); + final bridge = FakeNotificationBridge(permission: 'granted'); + final notify = NotificationController( + store: MemoryNotificationStore(), + bridge: bridge, + ); + addTearDown(attention.dispose); + addTearDown(notify.dispose); + await attention.load(); + await notify.load(); + expect(notify.canNotify, isTrue); + + attention.seedRows([runSummary(1, 'running', name: 'nightly')]); + attention.observeFrame( + runFrame( + 1, + 'failed', + name: 'nightly', + title: 'Nightly audit', + diagnostic: 'Stage 3 stopped', + finishedAt: '2026-10-22T11:00:00Z', + ), + ); + + expect(notify.publishTransitions(attention.transitions), 1); + final message = bridge.shown.single; + expect(message.title, 'A run failed'); + expect(message.body, 'Nightly audit \u00b7 nightly'); + expect(message.tag, '1:Failed@2026-10-22T11:00:00Z'); + expect(message.runId, 1); + }); + + test('a duplicate frame and a republished list stay silent', () async { + final attention = attentionController(); + final bridge = FakeNotificationBridge(permission: 'granted'); + final notify = NotificationController( + store: MemoryNotificationStore(), + bridge: bridge, + ); + addTearDown(attention.dispose); + addTearDown(notify.dispose); + await attention.load(); + await notify.load(); + + attention.seedRows([runSummary(1, 'running')]); + attention.observeFrame(runFrame(1, 'failed')); + expect(notify.publishTransitions(attention.transitions), 1); + + attention.observeFrame(runFrame(1, 'failed')); + expect(attention.transitions, hasLength(1)); + expect(notify.publishTransitions(attention.transitions), 0); + expect(bridge.shown, hasLength(1)); + }); + + test('a reconnect reseed cannot replay the notification', () async { + final attention = attentionController(); + final bridge = FakeNotificationBridge(permission: 'granted'); + final notify = NotificationController( + store: MemoryNotificationStore(), + bridge: bridge, + ); + addTearDown(attention.dispose); + addTearDown(notify.dispose); + await attention.load(); + await notify.load(); + + attention.seedRows([runSummary(1, 'running')]); + attention.observeFrame(runFrame(1, 'failed')); + expect(notify.publishTransitions(attention.transitions), 1); + + attention.resetForReconnect(); + attention.seedRows([runSummary(1, 'failed')], reconnect: true); + expect(notify.publishTransitions(attention.transitions), 0); + attention.observeFrame(runFrame(1, 'failed')); + expect(notify.publishTransitions(attention.transitions), 0); + expect(bridge.shown, hasLength(1)); + }); + + test('a rebuilt controller with the same store stays silent', () async { + final store = MemoryNotificationStore(); + final bridge = FakeNotificationBridge(permission: 'granted'); + final attention = attentionController(); + final notify = NotificationController(store: store, bridge: bridge); + addTearDown(attention.dispose); + addTearDown(notify.dispose); + await attention.load(); + await notify.load(); + + attention.seedRows([runSummary(1, 'running')]); + attention.observeFrame(runFrame(1, 'failed')); + expect(notify.publishTransitions(attention.transitions), 1); + await settle(); + + final restarted = NotificationController(store: store, bridge: bridge); + addTearDown(restarted.dispose); + await restarted.load(); + expect(restarted.notified, contains('1:Failed@${at(const Duration(minutes: 1))}')); + expect(restarted.publishTransitions(attention.transitions), 0); + expect(bridge.shown, hasLength(1)); + }); + + test('a genuinely new failure of the same run notifies again', () async { + final attention = attentionController(); + final bridge = FakeNotificationBridge(permission: 'granted'); + final notify = NotificationController( + store: MemoryNotificationStore(), + bridge: bridge, + ); + addTearDown(attention.dispose); + addTearDown(notify.dispose); + await attention.load(); + await notify.load(); + + attention.seedRows([runSummary(1, 'running')]); + attention.observeFrame( + runFrame(1, 'failed', finishedAt: '2026-10-22T09:10:00Z'), + ); + expect(notify.publishTransitions(attention.transitions), 1); + + attention.observeFrame(runFrame(1, 'running')); + attention.observeFrame( + runFrame(1, 'failed', finishedAt: '2026-10-22T11:30:00Z'), + ); + expect(notify.publishTransitions(attention.transitions), 1); + expect(bridge.shown, hasLength(2)); + expect(bridge.shown.map((m) => m.tag).toSet(), hasLength(2)); + }); + }); + + group('a dismissed entry never notifies', () { + test('the detector suppresses it and nothing is posted', () async { + final attention = attentionController(); + final bridge = FakeNotificationBridge(permission: 'granted'); + final notify = NotificationController( + store: MemoryNotificationStore(), + bridge: bridge, + ); + addTearDown(attention.dispose); + addTearDown(notify.dispose); + await attention.load(); + await notify.load(); + + attention.seedRows([runSummary(1, 'running')]); + await attention.dismiss(attentionEntryFor(runSummary(1, 'failed'))!); + attention.observeFrame(runFrame(1, 'failed')); + + expect(attention.transitions, isEmpty); + expect(notify.publishTransitions(attention.transitions), 0); + expect(bridge.shown, isEmpty); + }); + + test('the publish guard records but does not show a dismissed key', () async { + final bridge = FakeNotificationBridge(permission: 'granted'); + final notify = NotificationController( + store: MemoryNotificationStore(), + bridge: bridge, + ); + addTearDown(notify.dispose); + await notify.load(); + + final transition = transitionFor(4); + expect( + notify.publishTransitions([transition], dismissed: {transition.key}), + 0, + ); + expect(notify.notified, contains(notificationIdentity(transition))); + expect(bridge.shown, isEmpty); + }); + }); + + group('permission is only ever the platform\'s answer', () { + test('an unsupported platform is never asked and never posts', () async { + final bridge = FakeNotificationBridge(supported: false); + final notify = NotificationController( + store: MemoryNotificationStore(), + bridge: bridge, + ); + addTearDown(notify.dispose); + await notify.load(); + expect(notify.permission, NotificationPermissionState.unsupported); + + expect( + await notify.requestPermission(), + NotificationPermissionState.unsupported, + ); + expect(bridge.requests, 0); + expect(notify.publishTransitions([transitionFor(1)]), 0); + expect(bridge.shown, isEmpty); + }); + + test('an insecure page reports needsSecureContext', () async { + final bridge = FakeNotificationBridge(secureContext: false); + final notify = NotificationController( + store: MemoryNotificationStore(), + bridge: bridge, + ); + addTearDown(notify.dispose); + await notify.load(); + expect(notify.permission, NotificationPermissionState.needsSecureContext); + await notify.requestPermission(); + expect(bridge.requests, 0); + }); + + test('a default page is asked once and follows the real answer', () async { + final store = MemoryNotificationStore(); + final bridge = FakeNotificationBridge(answer: 'granted'); + final notify = NotificationController(store: store, bridge: bridge); + addTearDown(notify.dispose); + await notify.load(); + expect(notify.permission, NotificationPermissionState.notRequested); + expect(notify.canNotify, isFalse); + + final state = await notify.requestPermission(); + expect(bridge.requests, 1); + expect(state, NotificationPermissionState.granted); + expect(notify.canNotify, isTrue); + expect(notify.asked, isTrue); + await settle(); + expect(store.stored, contains('"asked":true')); + }); + + test('a denied answer is never re-prompted', () async { + final bridge = FakeNotificationBridge(permission: 'denied'); + final notify = NotificationController( + store: MemoryNotificationStore(), + bridge: bridge, + ); + addTearDown(notify.dispose); + await notify.load(); + expect(notify.permission, NotificationPermissionState.denied); + + expect( + await notify.requestPermission(), + NotificationPermissionState.denied, + ); + expect(bridge.requests, 0); + expect(notify.publishTransitions([transitionFor(1)]), 0); + expect(bridge.shown, isEmpty); + }); + + test('a prompt that grants nothing keeps the honest default wording', () async { + final bridge = FakeNotificationBridge(answer: 'default'); + final notify = NotificationController( + store: MemoryNotificationStore(), + bridge: bridge, + ); + addTearDown(notify.dispose); + await notify.load(); + + final state = await notify.requestPermission(); + expect(state, NotificationPermissionState.notRequested); + expect(notify.asked, isTrue); + expect(notify.canNotify, isFalse); + }); + }); + + group('batching and the tap seam', () { + test('a burst posts a bounded batch in order, then the rest', () async { + final bridge = FakeNotificationBridge(permission: 'granted'); + final notify = NotificationController( + store: MemoryNotificationStore(), + bridge: bridge, + ); + addTearDown(notify.dispose); + await notify.load(); + + final transitions = [for (var id = 1; id <= 7; id++) transitionFor(id)]; + expect(notify.publishTransitions(transitions), 5); + expect(bridge.shown.map((m) => m.runId), [1, 2, 3, 4, 5]); + expect(notify.publishTransitions(transitions), 2); + expect(bridge.shown.map((m) => m.runId), [1, 2, 3, 4, 5, 6, 7]); + }); + + test('a tap reports the run and never navigates here', () async { + final bridge = FakeNotificationBridge(permission: 'granted'); + final notify = NotificationController( + store: MemoryNotificationStore(), + bridge: bridge, + ); + addTearDown(notify.dispose); + await notify.load(); + + final opened = []; + notify.onOpenRun = opened.add; + expect(notify.publishTransitions([transitionFor(3)]), 1); + bridge.taps.single!.call(); + expect(opened, [3]); + }); + }); + + group('an unavailable store cannot reach the UI', () { + test('a failed read and write still notify and never throw', () async { + final store = MemoryNotificationStore() + ..failReads = true + ..failWrites = true; + final bridge = FakeNotificationBridge(permission: 'granted'); + final notify = NotificationController(store: store, bridge: bridge); + addTearDown(notify.dispose); + + await expectLater(notify.load(), completes); + expect(notify.loaded, isTrue); + expect(notify.notified, isEmpty); + + expect(notify.publishTransitions([transitionFor(1)]), 1); + await settle(); + expect(bridge.shown, hasLength(1)); + }); + + test('a throwing platform post is reported, not propagated', () async { + final bridge = _ThrowingBridge(); + final notify = NotificationController( + store: MemoryNotificationStore(), + bridge: bridge, + ); + addTearDown(notify.dispose); + await notify.load(); + + expect(notify.publishTransitions([transitionFor(1)]), 0); + expect(notify.notified, contains('1:Failed@${at(const Duration(minutes: 1))}')); + }); + }); + + group('the platform seam', () { + test('the non-web bridge reports unsupported honestly', () async { + final bridge = createNotificationBridge(); + expect(bridge.environment().supported, isFalse); + final notify = NotificationController( + store: MemoryNotificationStore(), + bridge: bridge, + ); + addTearDown(notify.dispose); + await notify.load(); + expect(notify.permission, NotificationPermissionState.unsupported); + expect( + bridge.show( + const NotificationMessage( + runId: 1, + title: 'A run failed', + body: 'release', + tag: '1:Failed@x', + ), + ), + isFalse, + ); + }); + }); +} + +class _ThrowingBridge implements NotificationBridge { + @override + NotificationEnvironment environment() => const NotificationEnvironment( + supported: true, + secureContext: true, + permission: 'granted', + ); + + @override + Future requestPermission() async => 'granted'; + + @override + bool show(NotificationMessage message, {void Function()? onTap}) => + throw StateError('the browser refused to construct a notification'); +} diff --git a/app/test/features/attention/notify/notification_ledger_test.dart b/app/test/features/attention/notify/notification_ledger_test.dart new file mode 100644 index 00000000..b4658cf4 --- /dev/null +++ b/app/test/features/attention/notify/notification_ledger_test.dart @@ -0,0 +1,89 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/attention/notify/notification_ledger.dart'; + +import 'notification_test_support.dart'; + +void main() { + group('the identity carries the finished marker', () { + test('a recorded finish time distinguishes two failures of one run', () { + final first = transitionFor(7, finishedAt: '2026-10-22T09:10:00Z'); + final second = transitionFor(7, finishedAt: '2026-10-22T11:30:00Z'); + expect(notificationIdentity(first), '7:Failed@2026-10-22T09:10:00Z'); + expect(notificationIdentity(second), '7:Failed@2026-10-22T11:30:00Z'); + expect(notificationIdentity(first), isNot(notificationIdentity(second))); + }); + + test('a run without a finish time falls back to its creation time', () { + final entry = transitionFor(7, status: 'waiting', finishedAt: ''); + expect( + notificationIdentity(entry), + '7:Decision@${attentionNow.subtract(const Duration(hours: 1)).toIso8601String()}', + ); + }); + + test('the kind separates a decision from a failure of one run', () { + expect( + notificationIdentity(transitionFor(7)), + isNot(notificationIdentity(transitionFor(7, status: 'waiting'))), + ); + }); + }); + + group('the ledger records identities', () { + test('recording is idempotent and never mutates the original', () { + const base = NotificationLedger(); + final once = base.recording('7:Failed@a'); + final twice = once.recording('7:Failed@a'); + expect(base.notified, isEmpty); + expect(once.hasNotified('7:Failed@a'), isTrue); + expect(twice.notified, {'7:Failed@a'}); + }); + + test('asked is carried without touching the identities', () { + final asked = const NotificationLedger( + notified: {'a'}, + ).withAsked(true); + expect(asked.asked, isTrue); + expect(asked.notified, {'a'}); + }); + }); + + group('persistence is total', () { + test('a round trip keeps the asked flag and the identities', () { + final ledger = const NotificationLedger( + notified: {'b', 'a'}, + ).withAsked(true); + final decoded = decodeNotificationLedger(encodeNotificationLedger(ledger)); + expect(decoded.asked, isTrue); + expect(decoded.notified, {'a', 'b'}); + }); + + test('an unchanged ledger always encodes to the same bytes', () { + final first = encodeNotificationLedger( + const NotificationLedger(notified: {'b', 'a'}), + ); + final second = encodeNotificationLedger( + const NotificationLedger(notified: {'a', 'b'}), + ); + expect(first, second); + }); + + test('blank, malformed and wrong-typed values never throw', () { + expect(decodeNotificationLedger(null).notified, isEmpty); + expect(decodeNotificationLedger('').asked, isFalse); + expect(decodeNotificationLedger('not json').notified, isEmpty); + expect(decodeNotificationLedger('[]').notified, isEmpty); + expect(decodeNotificationLedger('"text"').notified, isEmpty); + expect( + decodeNotificationLedger('{"asked":"yes","notified":[1,null,"a",""]}') + .notified, + {'a'}, + ); + expect( + decodeNotificationLedger('{"asked":"yes"}').asked, + isFalse, + reason: 'only a real true counts as asked', + ); + }); + }); +} diff --git a/app/test/features/attention/notify/notification_models_test.dart b/app/test/features/attention/notify/notification_models_test.dart new file mode 100644 index 00000000..2a3b02ec --- /dev/null +++ b/app/test/features/attention/notify/notification_models_test.dart @@ -0,0 +1,155 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/attention/domain/attention_models.dart'; +import 'package:pipelines_app/features/attention/notify/notification_models.dart'; + +NotificationEnvironment _env({ + bool supported = true, + bool secure = true, + String permission = 'default', +}) => NotificationEnvironment( + supported: supported, + secureContext: secure, + permission: permission, +); + +void main() { + group('permission state is the platform\'s own answer', () { + test('an unsupported API and an insecure page win over the word', () { + expect( + notificationStateOf(_env(supported: false, permission: 'granted')), + NotificationPermissionState.unsupported, + ); + expect( + notificationStateOf(_env(secure: false, permission: 'granted')), + NotificationPermissionState.needsSecureContext, + ); + }); + + test('granted is never assumed from an unrecognised word', () { + expect( + notificationStateOf(_env(permission: 'prompt')), + NotificationPermissionState.notRequested, + ); + expect( + notificationStateOf(_env(permission: '')), + NotificationPermissionState.notRequested, + ); + expect( + notificationStateOf(_env(permission: 'granted')), + NotificationPermissionState.granted, + ); + expect( + notificationStateOf(_env(permission: 'denied')), + NotificationPermissionState.denied, + ); + }); + + test('each state carries the browser model\'s own wire word', () { + expect(NotificationPermissionState.unsupported.wireName, 'unsupported'); + expect( + NotificationPermissionState.needsSecureContext.wireName, + 'insecure', + ); + expect(NotificationPermissionState.notRequested.wireName, 'default'); + expect(NotificationPermissionState.granted.wireName, 'granted'); + expect(NotificationPermissionState.denied.wireName, 'denied'); + }); + }); + + group('the permission view', () { + test('only a still-undecided page can request', () { + final view = notificationPermissionView( + NotificationPermissionState.notRequested, + ); + expect(view.canRequest, isTrue); + expect(view.actionLabel, notificationRequestLabel); + expect(view.body, notificationDefaultCopy); + + for (final state in [ + NotificationPermissionState.unsupported, + NotificationPermissionState.needsSecureContext, + NotificationPermissionState.granted, + NotificationPermissionState.denied, + ]) { + final other = notificationPermissionView(state); + expect(other.canRequest, isFalse, reason: '$state'); + expect(other.actionLabel, isNull, reason: '$state'); + } + }); + + test('asked only changes the undecided wording', () { + expect( + notificationPermissionView( + NotificationPermissionState.notRequested, + asked: true, + ).body, + notificationDefaultAskedCopy, + ); + expect( + notificationPermissionView( + NotificationPermissionState.denied, + asked: true, + ).body, + notificationDeniedCopy, + ); + }); + + test('every unavailable state names the in-app channel', () { + for (final state in [ + NotificationPermissionState.unsupported, + NotificationPermissionState.needsSecureContext, + NotificationPermissionState.denied, + ]) { + expect( + notificationPermissionView(state).body, + contains('in-app Needs you surface'), + reason: '$state', + ); + } + }); + }); + + group('notification content is the entry\'s own words', () { + test('the headline is the kind, nothing invented', () { + expect( + notificationAlertTitle(AttentionKind.decision), + 'A run needs your decision', + ); + expect(notificationAlertTitle(AttentionKind.failed), 'A run failed'); + }); + + test('the body is the run label then its pipeline', () { + final entry = attentionEntryFor({ + 'id': 7, + 'name': 'nightly-audit', + 'title': 'Nightly audit', + 'status': 'failed', + 'diagnostic': 'Stage 3 stopped', + 'created_at': '2026-10-22T09:00:00Z', + 'finished_at': '2026-10-22T09:10:00Z', + })!; + expect(notificationAlertBody(entry), 'Nightly audit \u00b7 nightly-audit'); + }); + + test('a blank or equal pipeline is never repeated', () { + final untitled = attentionEntryFor({ + 'id': 7, + 'name': 'release', + 'status': 'failed', + 'created_at': '2026-10-22T09:00:00Z', + 'finished_at': '2026-10-22T09:10:00Z', + })!; + expect(notificationAlertBody(untitled), 'release'); + + final nameless = attentionEntryFor({ + 'id': 8, + 'name': '', + 'title': 'A title', + 'status': 'failed', + 'created_at': '2026-10-22T09:00:00Z', + 'finished_at': '2026-10-22T09:10:00Z', + })!; + expect(notificationAlertBody(nameless), 'A title'); + }); + }); +} diff --git a/app/test/features/attention/notify/notification_test_support.dart b/app/test/features/attention/notify/notification_test_support.dart new file mode 100644 index 00000000..a8dd35a8 --- /dev/null +++ b/app/test/features/attention/notify/notification_test_support.dart @@ -0,0 +1,112 @@ +import 'package:pipelines_app/features/attention/domain/attention_models.dart'; +import 'package:pipelines_app/features/attention/domain/attention_transitions.dart'; +import 'package:pipelines_app/features/attention/notify/notification_bridge.dart'; +import 'package:pipelines_app/features/attention/notify/notification_models.dart'; +import 'package:pipelines_app/features/attention/runtime/attention_controller.dart'; +import 'package:pipelines_app/features/attention/runtime/attention_store.dart'; + +/// The fixed local time the attention tests order and window by. +final attentionNow = DateTime(2026, 10, 22, 12); + +String at(Duration before) => attentionNow.subtract(before).toIso8601String(); + +/// One run summary, built exactly as the runs list holds it. +Map runSummary( + int id, + String status, { + String name = 'release', + String? title, + Duration age = const Duration(hours: 1), + String diagnostic = '', + Object? exportPending, + Map extra = const {}, +}) => { + 'id': id, + 'name': name, + 'title': title ?? 'Run $id', + 'status': status, + 'diagnostic': diagnostic, + 'created_at': at(age), + 'finished_at': at(age - const Duration(minutes: 5)), + 'export_pending_sequence': ?exportPending, + ...extra, +}; + +/// One qualifying pushed frame for a run, as `run_event` carries it. A blank +/// [finishedAt] leaves the marker to fall back to the creation time. +Map runFrame( + int id, + String status, { + String name = 'release', + String? title, + String diagnostic = '', + String? finishedAt, +}) => { + 'type': 'run_event', + 'run_id': id, + 'name': name, + 'title': title ?? 'Run $id', + 'status': status, + 'diagnostic': diagnostic, + 'created_at': at(const Duration(hours: 1)), + 'finished_at': finishedAt ?? at(const Duration(minutes: 1)), +}; + +/// One transition for a run that just entered [status], for batch tests. +AttentionTransition transitionFor( + int id, { + String status = 'failed', + String name = 'release', + String? title, + String? finishedAt, +}) => AttentionTransition( + attentionEntryFor( + runFrame(id, status, name: name, title: title, finishedAt: finishedAt), + )!, +); + +AttentionController attentionController() => + AttentionController(store: MemoryAttentionStore(), now: () => attentionNow); + +/// A bridge whose answers are set explicitly, so every permission path is +/// exercised without a browser. It records what the controller asked for. +class FakeNotificationBridge implements NotificationBridge { + FakeNotificationBridge({ + this.supported = true, + this.secureContext = true, + this.permission = 'default', + this.answer = 'granted', + this.accepts = true, + }); + + bool supported; + bool secureContext; + String permission; + String answer; + bool accepts; + + int requests = 0; + final List shown = []; + final List taps = []; + + @override + NotificationEnvironment environment() => NotificationEnvironment( + supported: supported, + secureContext: secureContext, + permission: permission, + ); + + @override + Future requestPermission() async { + requests++; + permission = answer; + return answer; + } + + @override + bool show(NotificationMessage message, {void Function()? onTap}) { + shown.add(message); + taps.add(onTap); + return accepts; + } +} diff --git a/app/test/features/attention/ui/notification_permission_tile_test.dart b/app/test/features/attention/ui/notification_permission_tile_test.dart new file mode 100644 index 00000000..b764b941 --- /dev/null +++ b/app/test/features/attention/ui/notification_permission_tile_test.dart @@ -0,0 +1,140 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/attention/notify/notification_models.dart'; +import 'package:pipelines_app/features/attention/ui/notification_permission_tile.dart'; + +import 'needs_you_test_support.dart'; + +/// The tile inside a normal page, so both native hosts can draw it. The page +/// scrolls like the Settings list does, so the tile is never given a fixed +/// height to overflow. +Widget _page({ + required NotificationPermissionState state, + bool cupertino = false, + bool asked = false, + VoidCallback? onRequest, +}) => attentionApp( + Scaffold( + body: SingleChildScrollView( + child: NotificationPermissionTile( + state: state, + asked: asked, + onRequest: onRequest, + ), + ), + ), + cupertino: cupertino, +); + +void _noop() {} + +void main() { + for (final native in [false, true]) { + final host = native ? 'Cupertino' : 'Material'; + + testWidgets('$host shows the state\'s own honest copy', (tester) async { + final cases = { + NotificationPermissionState.unsupported: notificationUnsupportedCopy, + NotificationPermissionState.needsSecureContext: + notificationInsecureCopy, + NotificationPermissionState.granted: notificationGrantedCopy, + NotificationPermissionState.denied: notificationDeniedCopy, + NotificationPermissionState.notRequested: notificationDefaultCopy, + }; + for (final entry in cases.entries) { + await tester.pumpWidget( + _page(state: entry.key, cupertino: native, onRequest: _noop), + ); + expect(find.text(notificationSectionTitle), findsOneWidget); + expect(find.text(notificationRationale), findsOneWidget); + expect(find.text(entry.value), findsOneWidget, reason: '${entry.key}'); + expect( + find.byKey(notificationEnableKey), + entry.key == NotificationPermissionState.notRequested + ? findsOneWidget + : findsNothing, + reason: '${entry.key}', + ); + } + }); + + testWidgets('$host shows the asked wording without an action', ( + tester, + ) async { + await tester.pumpWidget( + _page( + state: NotificationPermissionState.notRequested, + asked: true, + cupertino: native, + ), + ); + expect(find.text(notificationDefaultAskedCopy), findsOneWidget); + expect(find.text(notificationDefaultCopy), findsNothing); + }); + + testWidgets('$host Enable runs the explicit request', (tester) async { + var requested = 0; + await tester.pumpWidget( + _page( + state: NotificationPermissionState.notRequested, + cupertino: native, + onRequest: () => requested++, + ), + ); + await tester.tap(find.byKey(notificationEnableKey)); + await tester.pump(); + expect(requested, 1); + }); + + testWidgets('$host tile wraps at 320 logical px and 2x in dark', ( + tester, + ) async { + tester.view.devicePixelRatio = 2; + tester.view.physicalSize = const Size(640, 1280); + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + + // The undecided state is the hardest: it carries the Enable action as well + // as the longest copy, so the section title must still have room to read. + await tester.pumpWidget( + attentionApp( + Scaffold( + body: SingleChildScrollView( + child: NotificationPermissionTile( + state: NotificationPermissionState.notRequested, + onRequest: _noop, + ), + ), + ), + cupertino: native, + dark: true, + textScale: 2, + ), + ); + expect(tester.takeException(), isNull); + + final title = tester.renderObject( + find.text(notificationSectionTitle), + ); + // Cupertino's list tile deliberately caps its title at one line; the + // defect this guards is the title being squeezed to a single glyph by the + // action sharing the row, so its width is the meaningful check. + expect( + title.size.width, + greaterThan(100), + reason: 'the action must not squeeze the section title to one glyph', + ); + final body = tester.renderObject( + find.text(notificationDefaultCopy), + ); + expect(body.didExceedMaxLines, isFalse); + expect(find.byKey(notificationEnableKey), findsOneWidget); + + final rect = tester.getRect(find.byKey(notificationStateKey)); + expect(rect.left, greaterThanOrEqualTo(0)); + expect(rect.right, lessThanOrEqualTo(320)); + expect(tester.takeException(), isNull); + }); + } +} diff --git a/app/tool/notification_probe.dart b/app/tool/notification_probe.dart new file mode 100644 index 00000000..ec849ab7 --- /dev/null +++ b/app/tool/notification_probe.dart @@ -0,0 +1,265 @@ +import 'dart:js_interop'; +import 'dart:js_interop_unsafe'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import 'package:pipelines_app/features/attention/domain/attention_models.dart'; +import 'package:pipelines_app/features/attention/notify/notification_bridge.dart'; +import 'package:pipelines_app/features/attention/notify/notification_controller.dart'; +import 'package:pipelines_app/features/attention/notify/notification_models.dart'; +import 'package:pipelines_app/features/attention/notify/notification_store.dart'; +import 'package:pipelines_app/features/attention/runtime/attention_controller.dart'; +import 'package:pipelines_app/features/attention/runtime/attention_store.dart'; +import 'package:pipelines_app/features/attention/ui/notification_permission_tile.dart'; + +/// Browser capture entrypoint for the notification capability. +/// +/// It drives the real [NotificationController] over the real web bridge, so a +/// browser drive can prove the seed is silent, one live transition raises +/// exactly one notification with the entry's own words and identity, a dismissed +/// or replayed transition raises none, and the Settings tile reads honestly in +/// every state on both hosts. Nothing here opens a socket or touches real +/// operator data; the store is in memory. +void main() { + final params = Uri.base.queryParameters; + final mode = params['mode'] ?? 'transition'; + final cupertino = params['host'] == 'cupertino'; + final scale = double.tryParse(params['scale'] ?? '') ?? 1; + final brightness = params['theme'] == 'light' + ? Brightness.light + : Brightness.dark; + Widget scaled(BuildContext context, Widget? app) => MediaQuery( + data: MediaQuery.of(context).copyWith(textScaler: TextScaler.linear(scale)), + child: app!, + ); + final home = switch (mode) { + 'tiles' => const _TileGallery(), + 'tile' => _SingleTile(state: _stateOf(params['state'])), + _ => _NotificationProbe(mode: mode), + }; + if (cupertino) { + runApp( + CupertinoApp( + theme: CupertinoThemeData(brightness: brightness), + builder: scaled, + home: home, + ), + ); + return; + } + runApp( + MaterialApp( + theme: ThemeData( + platform: TargetPlatform.android, + brightness: brightness, + ), + builder: scaled, + home: home, + ), + ); +} + +/// The report the browser drive reads, as a plain JS string. +void _publishReport(String value) => + globalContext.setProperty('__probeReport'.toJS, value.toJS); + +/// The permission state named by a `state` query parameter, defaulting to the +/// undecided one. +NotificationPermissionState _stateOf(String? name) { + for (final state in NotificationPermissionState.values) { + if (state.wireName == name) return state; + } + return NotificationPermissionState.notRequested; +} + +String _at(Duration before) => + DateTime.now().toUtc().subtract(before).toIso8601String(); + +Map _summary( + int id, + String status, { + String name = 'release', + String? title, + String diagnostic = '', +}) => { + 'id': id, + 'name': name, + 'title': title ?? 'Run $id', + 'status': status, + 'diagnostic': diagnostic, + 'created_at': _at(const Duration(hours: 1)), + 'finished_at': _at(const Duration(minutes: 55)), +}; + +Map _frame( + int id, + String status, { + String name = 'release', + String? title, + String diagnostic = '', +}) => { + 'type': 'run_event', + 'run_id': id, + 'name': name, + 'title': title ?? 'Run $id', + 'status': status, + 'diagnostic': diagnostic, + 'finished_at': _at(const Duration(minutes: 1)), +}; + +/// Runs one notification scenario against the real bridge, then reports it and +/// draws the live permission tile underneath. +class _NotificationProbe extends StatefulWidget { + const _NotificationProbe({required this.mode}); + + final String mode; + + @override + State<_NotificationProbe> createState() => _NotificationProbeState(); +} + +class _NotificationProbeState extends State<_NotificationProbe> { + String _report = 'running'; + NotificationPermissionState _permission = + NotificationPermissionState.unsupported; + bool _asked = false; + + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addPostFrameCallback((_) => _run()); + } + + Future _run() async { + final bridge = createNotificationBridge(); + final notify = NotificationController( + store: MemoryNotificationStore(), + bridge: bridge, + ); + await notify.load(); + final attention = AttentionController(store: MemoryAttentionStore()); + await attention.load(); + + switch (widget.mode) { + case 'seed': + attention.seedRows([ + _summary(1, 'failed', diagnostic: 'Stage 3 stopped'), + _summary(2, 'waiting'), + ]); + notify.publishTransitions(attention.transitions); + case 'dismissed': + attention.seedRows([_summary(1, 'running')]); + await attention.dismiss(attentionEntryFor(_summary(1, 'failed'))!); + attention.observeFrame(_frame(1, 'failed')); + notify.publishTransitions(attention.transitions); + case 'reconnect': + attention.seedRows([_summary(1, 'running')]); + attention.observeFrame(_frame(1, 'failed')); + notify.publishTransitions(attention.transitions); + attention.resetForReconnect(); + attention.seedRows([_summary(1, 'failed')], reconnect: true); + notify.publishTransitions(attention.transitions); + attention.observeFrame(_frame(1, 'failed')); + notify.publishTransitions(attention.transitions); + case 'denied': + case 'unsupported': + case 'default': + attention.seedRows([_summary(1, 'running')]); + attention.observeFrame(_frame(1, 'failed')); + notify.publishTransitions(attention.transitions); + default: + attention.seedRows([_summary(1, 'running', name: 'nightly')]); + attention.observeFrame( + _frame( + 1, + 'failed', + name: 'nightly', + title: 'Nightly audit', + diagnostic: 'Stage 3 stopped', + ), + ); + notify.publishTransitions(attention.transitions); + } + + if (!mounted) return; + final report = + 'mode=${widget.mode} posted=${notify.postedCount} ' + 'state=${notify.permission.wireName} asked=${notify.asked} ' + 'notified=${notify.notified.length}'; + _publishReport(report); + setState(() { + _report = report; + _permission = notify.permission; + _asked = notify.asked; + }); + notify.dispose(); + attention.dispose(); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + body: SafeArea( + child: ListView( + padding: const EdgeInsets.all(16), + children: [ + Text(_report), + const SizedBox(height: 16), + NotificationPermissionTile( + state: _permission, + asked: _asked, + onRequest: () {}, + ), + ], + ), + ), + ); + } +} + +/// One permission state on its own, so each can be captured and read at the +/// hardest width and text scale. +class _SingleTile extends StatelessWidget { + const _SingleTile({required this.state}); + + final NotificationPermissionState state; + + @override + Widget build(BuildContext context) { + return Scaffold( + body: SafeArea( + child: SingleChildScrollView( + padding: const EdgeInsets.all(16), + child: NotificationPermissionTile(state: state, onRequest: () {}), + ), + ), + ); + } +} + +/// Every permission state at once, so both hosts can be captured and read in +/// one page without touching a real permission. +class _TileGallery extends StatelessWidget { + const _TileGallery(); + + @override + Widget build(BuildContext context) { + return Scaffold( + body: SafeArea( + child: SingleChildScrollView( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + for (final state in NotificationPermissionState.values) ...[ + Text(state.wireName), + NotificationPermissionTile(state: state, onRequest: () {}), + ], + ], + ), + ), + ), + ); + } +} diff --git a/app/tool/notification_probe.mjs b/app/tool/notification_probe.mjs new file mode 100644 index 00000000..7660adfe --- /dev/null +++ b/app/tool/notification_probe.mjs @@ -0,0 +1,295 @@ +// Real-browser acceptance for the attention notification capability. +// +// flutter build web -t tool/notification_probe.dart -o build/notification_probe_web +// OPENCODE_ARTIFACT_DIR= node tool/notification_probe.mjs +// +// The page is served from an isolated loopback server. `window.Notification` is +// replaced with a recording spy before the app loads, and the real browser +// permission is granted (or denied) through CDP, so the drive proves the real +// bridge's behaviour: the initial seed raises nothing, one live transition +// raises exactly one notification with the entry's own words and run+kind+marker +// identity, a dismissed transition and a reconnect replay raise none, and the +// Settings tile reads honestly in every state on both hosts at 320 logical px +// and 2x text. One PNG is written per captured state. +import { createServer } from 'node:http'; +import { spawn } from 'node:child_process'; +import { once } from 'node:events'; +import { existsSync } from 'node:fs'; +import { setTimeout as delay } from 'node:timers/promises'; +import { join, extname, resolve, sep } from 'node:path'; +import { tmpdir } from 'node:os'; +import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; + +const root = resolve(process.env.PROBE_WEB_ROOT ?? 'build/notification_probe_web'); +const artifactDir = process.env.OPENCODE_ARTIFACT_DIR; +if (!artifactDir) throw new Error('Set OPENCODE_ARTIFACT_DIR for the probe captures'); +await mkdir(artifactDir, { recursive: true }); +const defaultChrome = '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'; +const chromePath = process.env.CHROME_PATH ?? defaultChrome; +if (!existsSync(chromePath)) throw new Error(`Chrome not found at ${chromePath}; set CHROME_PATH`); + +const mime = { + '.html': 'text/html', + '.js': 'text/javascript', + '.json': 'application/json', + '.wasm': 'application/wasm', + '.png': 'image/png', + '.ico': 'image/x-icon', +}; +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 origin = `http://127.0.0.1:${port}`; + +// The spy is installed before every document, so the app only ever sees it. It +// delegates `permission` to the real constructor (which CDP granted or denied) +// and records each `new Notification(...)` call. +const spy = `(() => { + const mode = new URLSearchParams(location.search).get('mode') || ''; + window.__notifications = []; + window.__probeReport = ''; + if (mode === 'unsupported') { window.Notification = undefined; return; } + const Real = window.Notification; + function Spy(title, options) { + window.__notifications.push({ + title: String(title ?? ''), + body: String((options && options.body) || ''), + tag: String((options && options.tag) || ''), + }); + return { onclick: null, close() {} }; + } + Object.defineProperty(Spy, 'permission', { + get: () => (Real ? Real.permission : 'granted'), + }); + Spy.requestPermission = () => Promise.resolve(Spy.permission); + window.Notification = Spy; +})();`; + +const profile = await mkdtemp(join(tmpdir(), 'notification-chrome-')); +const chrome = spawn( + chromePath, + [ + '--headless=new', + '--no-first-run', + '--no-default-browser-check', + '--disable-gpu', + '--remote-debugging-port=0', + `--user-data-dir=${profile}`, + 'about:blank', + ], + { stdio: ['ignore', 'ignore', 'pipe'] }, +); +let stderr = ''; +chrome.stderr.on('data', (data) => { stderr += data; }); +const waitFor = async (check) => { + for (let i = 0; i < 120; i++) { + const value = await check(); + if (value) return value; + await delay(100); + } + throw new Error(`Timed out waiting for Chrome DevTools\n${stderr.slice(-1200)}`); +}; + +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 message = JSON.parse(event.data); + if (message.id && pending.has(message.id)) { + pending.get(message.id)(message); + pending.delete(message.id); + } + }); + const send = (method, params = {}, sessionId) => + new Promise((resolveCall, rejectCall) => { + const callId = ++id; + pending.set(callId, (message) => { + if (message.error) rejectCall(new Error(`${method}: ${message.error.message}`)); + else resolveCall(message.result); + }); + ws.send(JSON.stringify({ id: callId, method, params, ...(sessionId ? { sessionId } : {}) })); + }); + + const target = (await send('Target.createTarget', { url: 'about:blank' })).targetId; + const session = (await send('Target.attachToTarget', { targetId: target, flatten: true })).sessionId; + await send('Page.enable', {}, session); + await send('Runtime.enable', {}, session); + await send('Page.addScriptToEvaluateOnNewDocument', { source: spy }, session); + + const evaluate = async (expression) => { + const response = await send( + 'Runtime.evaluate', + { expression, returnByValue: true, awaitPromise: true }, + session, + ); + if (response.exceptionDetails) { + throw new Error(`Runtime.evaluate failed: ${JSON.stringify(response.exceptionDetails)}`); + } + return response.result?.value; + }; + const semantics = () => evaluate( + "[...document.querySelectorAll('flt-semantics')].map(x=>{const r=x.getBoundingClientRect();return{label:(x.getAttribute('aria-label')||x.innerText||'').trim(),role:x.getAttribute('role'),x:r.x,y:r.y,w:r.width,h:r.height}})", + ); + const requireLabels = (all, needles, state) => { + for (const needle of needles) { + if (!all.some((label) => label.includes(needle))) { + throw new Error(`Missing ${JSON.stringify(needle)} in ${state}: ${JSON.stringify(all)}`); + } + } + }; + let viewport = { width: 320, height: 640 }; + const navigate = async ({ mode, host = 'material', scale = 1, theme = 'dark', width = 320, height = 640, semantics: enableSemantics = false, state } = {}) => { + viewport = { width, height }; + await send('Emulation.setEmulatedMedia', { features: [{ name: 'prefers-color-scheme', value: theme }] }, session); + const query = new URLSearchParams({ mode, host, scale: String(scale), theme }); + if (state) query.set('state', state); + await send('Page.navigate', { url: `${origin}/?${query}` }, session); + await delay(2500); + await send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 2, mobile: true }, session); + await delay(1000); + if (enableSemantics) { + await evaluate("document.querySelector('flt-semantics-placeholder')?.click()"); + await delay(1200); + } + }; + const waitForReport = async (mode) => { + for (let attempt = 0; attempt < 80; attempt++) { + const report = await evaluate('window.__probeReport'); + if (report && report.includes(`mode=${mode}`)) return report; + await delay(150); + } + throw new Error(`The ${mode} scenario never reported`); + }; + const notifications = () => evaluate('JSON.stringify(window.__notifications)'); + const capture = async (name) => { + const data = (await send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false }, session)).data; + await writeFile(join(artifactDir, name), Buffer.from(data, 'base64')); + }; + + const grant = () => send('Browser.grantPermissions', { origin, permissions: ['notifications'] }); + const deny = () => send('Browser.setPermission', { + permission: { name: 'notifications' }, + setting: 'denied', + origin, + }); + const prompt = () => send('Browser.setPermission', { + permission: { name: 'notifications' }, + setting: 'prompt', + origin, + }); + + const checks = []; + const captures = []; + const check = (name, condition, detail) => { + if (!condition) throw new Error(`${name}: ${detail}`); + checks.push(name); + }; + + await prompt(); + + // 1. The initial list seed never notifies. + await navigate({ mode: 'seed' }); + const seedReport = await waitForReport('seed'); + check('seed report', seedReport.includes('posted=0'), seedReport); + check('seed silent', (await notifications()) === '[]', await notifications()); + + // 2. One live transition notifies exactly once, with the entry's own words. + await grant(); + await navigate({ mode: 'transition' }); + const transitionReport = await waitForReport('transition'); + check('transition posted once', transitionReport.includes('posted=1'), transitionReport); + const posted = JSON.parse(await notifications()); + check('transition count', posted.length === 1, JSON.stringify(posted)); + check('transition title', posted[0].title === 'A run failed', JSON.stringify(posted[0])); + check('transition body', posted[0].body === 'Nightly audit · nightly', JSON.stringify(posted[0])); + check('transition identity', /^1:Failed@/.test(posted[0].tag), JSON.stringify(posted[0])); + await capture('notification-transition-material-dark-320-2x.png'); + captures.push('notification-transition-material-dark-320-2x.png'); + + // 3. A dismissed transition never notifies. + await navigate({ mode: 'dismissed' }); + const dismissedReport = await waitForReport('dismissed'); + check('dismissed report', dismissedReport.includes('posted=0'), dismissedReport); + check('dismissed silent', (await notifications()) === '[]', await notifications()); + + // 4. A reconnect replay never notifies again. + await navigate({ mode: 'reconnect' }); + const reconnectReport = await waitForReport('reconnect'); + check('reconnect posted once', reconnectReport.includes('posted=1'), reconnectReport); + check('reconnect count', JSON.parse(await notifications()).length === 1, await notifications()); + + // 5. A denied page is honest and posts nothing. + await deny(); + await navigate({ mode: 'denied', semantics: true }); + const deniedReport = await waitForReport('denied'); + check('denied report', deniedReport.includes('state=denied') && deniedReport.includes('posted=0'), deniedReport); + check('denied silent', (await notifications()) === '[]', await notifications()); + requireLabels(await semantics().then((rows) => rows.map((r) => r.label)), [ + 'Notifications are blocked for this site.', + ], 'denied tile'); + await capture('notification-denied-material-dark-320-2x.png'); + captures.push('notification-denied-material-dark-320-2x.png'); + + // 6. An unsupported browser is honest and posts nothing. + await grant(); + await navigate({ mode: 'unsupported', semantics: true }); + const unsupportedReport = await waitForReport('unsupported'); + check('unsupported report', unsupportedReport.includes('state=unsupported'), unsupportedReport); + check('unsupported silent', (await notifications()) === '[]', await notifications()); + requireLabels(await semantics().then((rows) => rows.map((r) => r.label)), [ + 'This browser does not support notifications.', + ], 'unsupported tile'); + await capture('notification-unsupported-material-dark-320-2x.png'); + captures.push('notification-unsupported-material-dark-320-2x.png'); + + // 7. Each tile state reads honestly on both hosts, at the hardest case: + // 320 logical px and 2x text. + await prompt(); + const states = { + unsupported: 'This browser does not support notifications.', + insecure: 'Notifications need a secure context (https or localhost).', + default: 'Notifications are off. Enable them to be told when a run fails', + granted: 'Notifications are on. Failed and waiting runs will raise a browser notification.', + denied: 'Notifications are blocked for this site.', + }; + for (const host of ['material', 'cupertino']) { + for (const [state, copy] of Object.entries(states)) { + await navigate({ mode: 'tile', host, scale: 2, semantics: true, state }); + const labels = (await semantics()).map((row) => row.label); + requireLabels(labels, [ + 'Pipelines can notify you when a run is waiting', + copy, + ], `${host} ${state} tile`); + if (state === 'default') { + requireLabels(labels, ['Enable notifications'], `${host} ${state} action`); + } + checks.push(`${host} ${state} tile`); + const name = `notification-tile-${state}-${host}-dark-320-2x.png`; + await capture(name); + captures.push(name); + } + } + + console.log(JSON.stringify({ checks, captures }, 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 841dd502b8643df76d858251f791f70a06ff2424 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 22 Oct 2026 01:41:36 +0100 Subject: [PATCH 07/13] feat(app): download and share artifacts as named files --- .../artifacts/actions/artifact_file.dart | 99 +++++ .../actions/artifact_file_actions.dart | 187 ++++++++ .../actions/artifact_file_bridge.dart | 42 ++ .../actions/artifact_file_controller.dart | 196 +++++++++ .../artifacts/actions/artifact_transfer.dart | 61 +++ .../actions/artifact_transfer_stub.dart | 29 ++ .../actions/artifact_transfer_web.dart | 206 +++++++++ .../artifacts/ui/artifact_gallery_page.dart | 34 +- .../artifacts/ui/artifact_viewer_body.dart | 103 +++-- .../artifacts/ui/artifact_viewer_content.dart | 12 +- .../artifacts/ui/artifact_viewer_page.dart | 10 +- app/notes/A3-files.md | 54 +++ .../actions/artifact_file_actions_test.dart | 403 ++++++++++++++++++ .../artifact_file_controller_test.dart | 229 ++++++++++ .../artifacts/actions/artifact_file_test.dart | 99 +++++ app/tool/artifact_gallery_probe.dart | 18 + app/tool/artifact_gallery_probe.mjs | 173 ++++++++ 17 files changed, 1909 insertions(+), 46 deletions(-) create mode 100644 app/lib/features/artifacts/actions/artifact_file.dart create mode 100644 app/lib/features/artifacts/actions/artifact_file_actions.dart create mode 100644 app/lib/features/artifacts/actions/artifact_file_bridge.dart create mode 100644 app/lib/features/artifacts/actions/artifact_file_controller.dart create mode 100644 app/lib/features/artifacts/actions/artifact_transfer.dart create mode 100644 app/lib/features/artifacts/actions/artifact_transfer_stub.dart create mode 100644 app/lib/features/artifacts/actions/artifact_transfer_web.dart create mode 100644 app/notes/A3-files.md create mode 100644 app/test/features/artifacts/actions/artifact_file_actions_test.dart create mode 100644 app/test/features/artifacts/actions/artifact_file_controller_test.dart create mode 100644 app/test/features/artifacts/actions/artifact_file_test.dart diff --git a/app/lib/features/artifacts/actions/artifact_file.dart b/app/lib/features/artifacts/actions/artifact_file.dart new file mode 100644 index 00000000..ac634f32 --- /dev/null +++ b/app/lib/features/artifacts/actions/artifact_file.dart @@ -0,0 +1,99 @@ +import 'dart:typed_data'; + +import '../domain/artifact_record.dart'; + +/// A recorded artifact's exact bytes, named and typed as the host must save or +/// share them. +/// +/// The name is the recorded file name's basename, never a url or a directory +/// path. The MIME type is the recorded media type without parameters. Only when +/// the recorded value is missing or malformed does the fallback apply: the +/// server url's basename, then `artifact`, and `application/octet-stream`. +class ArtifactFile { + const ArtifactFile({ + required this.name, + required this.mimeType, + required this.bytes, + }); + + final String name; + final String mimeType; + final Uint8List bytes; + + int get byteLength => bytes.length; +} + +const String artifactFileFallbackName = 'artifact'; +const String artifactFileFallbackMimeType = 'application/octet-stream'; + +/// Names and types one recorded artifact's fetched bytes for a file transfer. +ArtifactFile artifactFileFor({ + required ArtifactRecord artifact, + required Uri url, + required Uint8List bytes, +}) => ArtifactFile( + name: artifactFileName(artifact, url), + mimeType: artifactFileMimeType(artifact), + bytes: bytes, +); + +/// The recorded name without any `public/` prefix or directory component, with +/// control characters replaced. An absent, dot-only or unusable name falls +/// back to the resolved url's last path segment and then to `artifact`. +String artifactFileName(ArtifactRecord artifact, Uri url) { + final recorded = _usableBasename(artifact.name); + if (recorded.isNotEmpty) return recorded; + final fromUrl = _usableBasename( + url.pathSegments.isEmpty ? '' : url.pathSegments.last, + ); + return fromUrl.isEmpty ? artifactFileFallbackName : fromUrl; +} + +/// The recorded MIME type without parameters, lowercased, or +/// `application/octet-stream` when nothing usable was recorded. +String artifactFileMimeType(ArtifactRecord artifact) { + final mediaType = artifact.contentType.split(';').first.trim().toLowerCase(); + return _mediaType.hasMatch(mediaType) + ? mediaType + : artifactFileFallbackMimeType; +} + +final RegExp _mediaType = RegExp( + r"^[a-z0-9!#$&'*+.^_`|~-]+/[a-z0-9!#$&'*+.^_`|~-]+$", +); + +/// Whether the record carries a usable file name of its own. +bool hasRecordedArtifactName(ArtifactRecord artifact) => + _usableBasename(artifact.name).isNotEmpty; + +/// Whether the record carries a usable MIME type of its own. +bool hasRecordedArtifactMimeType(ArtifactRecord artifact) { + final mediaType = artifact.contentType.split(';').first.trim().toLowerCase(); + return _mediaType.hasMatch(mediaType); +} + +/// An explicit note when the recorded name or MIME type cannot be used, so the +/// fallback file name/type is never silent. Null for a complete record. +String? artifactFileRecordingNotice(ArtifactRecord artifact, Uri url) { + final nameMissing = !hasRecordedArtifactName(artifact); + final typeMissing = !hasRecordedArtifactMimeType(artifact); + if (!nameMissing && !typeMissing) return null; + final name = artifactFileName(artifact, url); + if (nameMissing && typeMissing) { + return 'No usable recorded name or MIME type; the file is saved as ' + '$name ($artifactFileFallbackMimeType).'; + } + if (nameMissing) { + return 'No usable recorded name; the file is saved as $name.'; + } + return 'No usable recorded MIME type; the file is saved as ' + '$artifactFileFallbackMimeType.'; +} + +String _usableBasename(String value) { + final segments = value.trim().split(RegExp(r'[\\/]')); + final name = segments.isEmpty ? '' : segments.last; + final cleaned = name.replaceAll(RegExp(r'[\x00-\x1f\x7f]'), '_').trim(); + if (cleaned == '.' || cleaned == '..') return ''; + return cleaned; +} diff --git a/app/lib/features/artifacts/actions/artifact_file_actions.dart b/app/lib/features/artifacts/actions/artifact_file_actions.dart new file mode 100644 index 00000000..39fa72b7 --- /dev/null +++ b/app/lib/features/artifacts/actions/artifact_file_actions.dart @@ -0,0 +1,187 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../ui/adaptive/host.dart'; +import '../domain/artifact_record.dart'; +import '../domain/artifact_url.dart'; +import '../ui/artifact_viewer_fetch.dart'; +import 'artifact_file.dart'; +import 'artifact_file_bridge.dart'; +import 'artifact_file_controller.dart'; + +/// Download and Share for one selected artifact, backed by its exact bytes. +/// +/// The controls are standard native buttons. Download creates a named file; +/// Share passes a named file to the host share sheet and never falls back to +/// the artifact url. A host without a capability shows a disabled control and +/// the exact reason, while the other action keeps working. One tap starts at +/// most one transfer; a slow fetch shows progress and can be cancelled. +class ArtifactFileActions extends StatefulWidget { + const ArtifactFileActions({ + super.key, + required this.artifact, + required this.resolved, + this.fetch = fetchArtifact, + this.bridge = const ArtifactFileBridge(), + }); + + final ArtifactRecord artifact; + final ResolvedArtifactUrl resolved; + final ArtifactFetch fetch; + final ArtifactFileBridge bridge; + + @override + State createState() => _ArtifactFileActionsState(); +} + +class _ArtifactFileActionsState extends State { + late ArtifactFileActionsController _controller; + + @override + void initState() { + super.initState(); + _controller = _create(); + } + + @override + void didUpdateWidget(covariant ArtifactFileActions oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.resolved.url != widget.resolved.url || + oldWidget.artifact.url != widget.artifact.url || + oldWidget.artifact.name != widget.artifact.name || + oldWidget.artifact.contentType != widget.artifact.contentType || + oldWidget.fetch != widget.fetch || + oldWidget.bridge != widget.bridge) { + _controller.dispose(); + _controller = _create(); + } + } + + ArtifactFileActionsController _create() => ArtifactFileActionsController( + artifact: widget.artifact, + resolved: widget.resolved, + fetch: widget.fetch, + bridge: widget.bridge, + ); + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return ListenableBuilder( + listenable: _controller, + builder: (context, _) => _ActionBar( + controller: _controller, + cupertino: usesCupertinoHost(context), + ), + ); + } +} + +class _ActionBar extends StatelessWidget { + const _ActionBar({required this.controller, required this.cupertino}); + + final ArtifactFileActionsController controller; + final bool cupertino; + + @override + Widget build(BuildContext context) { + final status = controller.status; + final notice = artifactFileRecordingNotice( + controller.artifact, + controller.resolved.uri, + ); + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Wrap( + spacing: 8, + runSpacing: 4, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + _button( + label: 'Download', + icon: Icons.download_outlined, + onPressed: controller.canDownload && !controller.busy + ? controller.download + : null, + ), + _button( + label: 'Share', + icon: Icons.ios_share, + onPressed: controller.canShare && !controller.busy + ? controller.share + : null, + ), + if (controller.canCancel) + _button( + label: 'Cancel', + icon: Icons.close, + onPressed: controller.cancel, + ), + ], + ), + if (controller.busy && status != null) + Padding( + padding: const EdgeInsets.only(top: 6), + child: Semantics( + liveRegion: true, + container: true, + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + if (cupertino) + const CupertinoActivityIndicator(radius: 8) + else + const SizedBox( + width: 14, + height: 14, + child: CircularProgressIndicator(strokeWidth: 2), + ), + const SizedBox(width: 8), + Flexible(child: Text(status)), + ], + ), + ), + ) + else if (status != null) + Padding( + padding: const EdgeInsets.only(top: 6), + child: Semantics(liveRegion: true, child: Text(status)), + ), + if (!controller.canDownload) + Padding( + padding: const EdgeInsets.only(top: 6), + child: Text(controller.bridge.downloadUnavailableMessage), + ), + if (!controller.canShare) + Padding( + padding: const EdgeInsets.only(top: 6), + child: Text(controller.bridge.shareUnavailableMessage), + ), + if (notice != null) + Padding(padding: const EdgeInsets.only(top: 6), child: Text(notice)), + ], + ); + } + + Widget _button({ + required String label, + required IconData icon, + required VoidCallback? onPressed, + }) { + if (cupertino) { + return CupertinoButton(onPressed: onPressed, child: Text(label)); + } + return TextButton.icon( + onPressed: onPressed, + icon: Icon(icon, size: 18), + label: Text(label), + ); + } +} diff --git a/app/lib/features/artifacts/actions/artifact_file_bridge.dart b/app/lib/features/artifacts/actions/artifact_file_bridge.dart new file mode 100644 index 00000000..8370dd35 --- /dev/null +++ b/app/lib/features/artifacts/actions/artifact_file_bridge.dart @@ -0,0 +1,42 @@ +import 'artifact_file.dart'; +import 'artifact_transfer.dart'; + +/// The host file capabilities one action row uses. +/// +/// The defaults are the real conditional-import bridge: a web Blob/anchor +/// download plus `navigator.share`, and honest `unsupported` results on native +/// hosts until a platform launcher exists. Tests inject both functions and the +/// capability flags without touching a browser. +class ArtifactFileBridge { + const ArtifactFileBridge({ + this.download, + this.share, + this.downloadSupported, + this.shareSupported, + this.downloadUnsupportedMessage, + this.shareUnsupportedMessage, + }); + + final ArtifactSaveFile? download; + final ArtifactShareFile? share; + final bool? downloadSupported; + final bool? shareSupported; + final String? downloadUnsupportedMessage; + final String? shareUnsupportedMessage; + + bool get canDownload => downloadSupported ?? artifactDownloadSupported; + + bool get canShare => shareSupported ?? artifactShareSupported; + + String get downloadUnavailableMessage => + downloadUnsupportedMessage ?? artifactDownloadUnsupportedMessage; + + String get shareUnavailableMessage => + shareUnsupportedMessage ?? artifactShareUnsupportedMessage; + + Future saveFile(ArtifactFile file) => + (download ?? saveArtifactFile)(file); + + Future shareFile(ArtifactFile file) => + (share ?? shareArtifactFile)(file); +} diff --git a/app/lib/features/artifacts/actions/artifact_file_controller.dart b/app/lib/features/artifacts/actions/artifact_file_controller.dart new file mode 100644 index 00000000..eb707704 --- /dev/null +++ b/app/lib/features/artifacts/actions/artifact_file_controller.dart @@ -0,0 +1,196 @@ +import 'package:flutter/foundation.dart'; + +import '../domain/artifact_record.dart'; +import '../domain/artifact_url.dart'; +import '../ui/artifact_viewer_fetch.dart'; +import 'artifact_file.dart'; +import 'artifact_file_bridge.dart'; +import 'artifact_transfer.dart'; + +/// Which host file action is currently in flight. +enum ArtifactFileAction { download, share } + +/// The words shown while bytes are being fetched. +const String artifactPreparingFile = 'Preparing file…'; + +/// Saves or shares one selected artifact's fetched bytes. +/// +/// The controller owns exactly one transfer at a time: a tap while [busy] is +/// ignored, so a double tap cannot start two fetches or two share sheets. The +/// same fetch seam the viewer uses obtains the bytes, so the same-origin +/// credential policy and HTTP status handling apply. Fetched bytes are kept +/// after a ready/blocked/canceled share so the next tap can retry with a fresh +/// user activation without another transfer. +/// +/// Cancelling stops the action from continuing: a late fetch result is ignored +/// by generation, and the host transfer is never started. The underlying HTTP +/// request is not aborted because the shared fetch seam has no cancellation +/// token; the app never reports those bytes as a completed transfer. +class ArtifactFileActionsController extends ChangeNotifier { + ArtifactFileActionsController({ + required this.artifact, + required this.resolved, + required this.fetch, + this.bridge = const ArtifactFileBridge(), + }); + + final ArtifactRecord artifact; + final ResolvedArtifactUrl resolved; + final ArtifactFileBridge bridge; + + final ArtifactFetch fetch; + ArtifactFile? _prepared; + String? _preparedUrl; + ArtifactFileAction? _active; + bool _preparing = false; + int _generation = 0; + bool _disposed = false; + String? _status; + + String? get status => _status; + + bool get busy => _active != null; + + /// Cancel is offered only while the fetch is still running; once the host + /// share sheet is open the OS owns the transfer. + bool get canCancel => _active != null && _preparing; + + bool get canDownload => bridge.canDownload; + + bool get canShare => bridge.canShare; + + Future download() async { + if (busy) return; + if (!canDownload) { + _setStatus(bridge.downloadUnavailableMessage); + return; + } + final generation = _begin(ArtifactFileAction.download); + final file = await _prepare(generation); + if (file == null || generation != _generation) return; + _preparing = false; + _notify(); + ArtifactTransferResult result; + try { + result = await bridge.saveFile(file); + } catch (_) { + _fail(generation, 'Could not download the file. Try again.'); + return; + } + if (generation != _generation) return; + _active = null; + _status = result.state == ArtifactTransferState.saved + ? 'Downloaded ${file.name}.' + : result.message; + _notify(); + } + + Future share() async { + if (busy) return; + if (!canShare) { + _setStatus(bridge.shareUnavailableMessage); + return; + } + final generation = _begin(ArtifactFileAction.share); + final file = await _prepare(generation); + if (file == null || generation != _generation) return; + _preparing = false; + _notify(); + ArtifactTransferResult result; + try { + result = await bridge.shareFile(file); + } catch (_) { + _fail( + generation, + 'Could not share the file. Use Download to save it, or try Share again.', + ); + return; + } + if (generation != _generation) return; + _active = null; + _status = result.state == ArtifactTransferState.shared + ? 'File shared.' + : result.message; + _notify(); + } + + /// Stops waiting for the fetch. Nothing is handed to the host afterwards. + void cancel() { + if (!canCancel) return; + final action = _active; + _generation += 1; + _active = null; + _preparing = false; + _status = action == ArtifactFileAction.share + ? 'Sharing canceled.' + : 'Download canceled.'; + _notify(); + } + + int _begin(ArtifactFileAction action) { + final generation = ++_generation; + _active = action; + _preparing = true; + _status = artifactPreparingFile; + _notify(); + return generation; + } + + Future _prepare(int generation) async { + final cached = _prepared; + if (cached != null && _preparedUrl == resolved.url) { + _preparing = false; + _notify(); + return cached; + } + try { + final fetched = await fetch(resolved.uri); + if (generation != _generation) return null; + if (!fetched.ok) { + _fail( + generation, + 'Could not fetch the artifact (HTTP ${fetched.status}).', + ); + return null; + } + final file = artifactFileFor( + artifact: artifact, + url: resolved.uri, + bytes: fetched.bytes, + ); + _prepared = file; + _preparedUrl = resolved.url; + return file; + } on ArtifactFetchException catch (error) { + _fail(generation, 'Could not fetch the artifact: ${error.message}'); + return null; + } catch (error) { + _fail(generation, 'Could not fetch the artifact: $error'); + return null; + } + } + + void _fail(int generation, String message) { + if (generation != _generation) return; + _active = null; + _preparing = false; + _status = message; + _notify(); + } + + void _setStatus(String message) { + _status = message; + _notify(); + } + + void _notify() { + if (!_disposed) notifyListeners(); + } + + @override + void dispose() { + _disposed = true; + _generation += 1; + super.dispose(); + } +} diff --git a/app/lib/features/artifacts/actions/artifact_transfer.dart b/app/lib/features/artifacts/actions/artifact_transfer.dart new file mode 100644 index 00000000..bc99bbf3 --- /dev/null +++ b/app/lib/features/artifacts/actions/artifact_transfer.dart @@ -0,0 +1,61 @@ +import 'artifact_file.dart'; +import 'artifact_transfer_stub.dart' + if (dart.library.js_interop) 'artifact_transfer_web.dart' + as impl; + +/// The outcome of a host file transfer. +enum ArtifactTransferState { + /// The host accepted a browser download. + saved, + + /// The host share sheet accepted the file. + shared, + + /// The bytes are ready but the browser needed a fresh user activation. + ready, + + /// The operator or the host canceled the transfer. + canceled, + + /// The host cannot save/share this file. + unsupported, + + /// The host refused the share for a policy or activation reason. + blocked, + + /// The transfer failed for any other reason. + failed, +} + +/// A transfer result plus the exact words the action row reports. +class ArtifactTransferResult { + const ArtifactTransferResult(this.state, this.message); + + final ArtifactTransferState state; + final String message; +} + +typedef ArtifactSaveFile = + Future Function(ArtifactFile file); +typedef ArtifactShareFile = + Future Function(ArtifactFile file); + +/// Whether the host can save an artifact's bytes as a named file. +bool get artifactDownloadSupported => impl.artifactDownloadSupported; + +/// Whether the host can share a file (not merely a link). +bool get artifactShareSupported => impl.artifactShareSupported; + +String get artifactDownloadUnsupportedMessage => + impl.artifactDownloadUnsupportedMessage; + +String get artifactShareUnsupportedMessage => + impl.artifactShareUnsupportedMessage; + +/// Saves [file] through the host's download capability. +Future saveArtifactFile(ArtifactFile file) => + impl.saveArtifactFile(file); + +/// Shares [file] through the host's file-sharing capability. +Future shareArtifactFile(ArtifactFile file) => + impl.shareArtifactFile(file); diff --git a/app/lib/features/artifacts/actions/artifact_transfer_stub.dart b/app/lib/features/artifacts/actions/artifact_transfer_stub.dart new file mode 100644 index 00000000..13556290 --- /dev/null +++ b/app/lib/features/artifacts/actions/artifact_transfer_stub.dart @@ -0,0 +1,29 @@ +import 'artifact_file.dart'; +import 'artifact_transfer.dart'; + +/// Native fallback for artifact file actions. +/// +/// A save/share plugin is not a dependency of this slice, so a non-web host +/// reports `unsupported` instead of pretending to save a file. The action row +/// disables the control and shows this exact explanation. +bool get artifactDownloadSupported => false; + +bool get artifactShareSupported => false; + +String get artifactDownloadUnsupportedMessage => + 'Downloading files is not supported on this platform yet.'; + +String get artifactShareUnsupportedMessage => + 'File sharing is not supported on this platform yet.'; + +Future saveArtifactFile(ArtifactFile file) async => + ArtifactTransferResult( + ArtifactTransferState.unsupported, + artifactDownloadUnsupportedMessage, + ); + +Future shareArtifactFile(ArtifactFile file) async => + ArtifactTransferResult( + ArtifactTransferState.unsupported, + artifactShareUnsupportedMessage, + ); diff --git a/app/lib/features/artifacts/actions/artifact_transfer_web.dart b/app/lib/features/artifacts/actions/artifact_transfer_web.dart new file mode 100644 index 00000000..bcd07d84 --- /dev/null +++ b/app/lib/features/artifacts/actions/artifact_transfer_web.dart @@ -0,0 +1,206 @@ +import 'dart:async'; +import 'dart:js_interop'; +import 'dart:js_interop_unsafe'; + +import 'artifact_file.dart'; +import 'artifact_transfer.dart'; + +/// Web file actions: the artifact's bytes become a named `Blob`/`File`. +/// +/// Download creates an object url and clicks a native anchor with the recorded +/// name; share passes a real `File` to `navigator.share`. Neither path ever +/// substitutes the artifact url or opens a blob page. No package:web import is +/// used, so the same source compiles for JavaScript and WebAssembly. +@JS('document') +external _Document get _document; + +@JS('navigator') +external _Navigator get _navigator; + +@JS('URL.createObjectURL') +external JSString _createObjectUrl(JSObject blob); + +@JS('URL.revokeObjectURL') +external void _revokeObjectUrl(JSString url); + +extension type _Document._(JSObject _) implements JSObject { + external _Anchor createElement(JSString tag); + external _Element get body; +} + +extension type _Anchor._(JSObject _) implements JSObject { + external set href(JSString value); + external set download(JSString value); + external void click(); + external void remove(); +} + +extension type _Element._(JSObject _) implements JSObject { + external void appendChild(JSObject node); +} + +extension type _BlobOptions._(JSObject _) implements JSObject { + external factory _BlobOptions({JSString type}); +} + +@JS('Blob') +extension type _Blob._(JSObject _) implements JSObject { + external factory _Blob(JSArray parts, _BlobOptions options); +} + +extension type _FileOptions._(JSObject _) implements JSObject { + external factory _FileOptions({JSString type}); +} + +@JS('File') +extension type _File._(JSObject _) implements JSObject { + external factory _File( + JSArray parts, + JSString name, + _FileOptions options, + ); +} + +extension type _ShareData._(JSObject _) implements JSObject { + external factory _ShareData({JSArray files}); +} + +extension type _UserActivation._(JSObject _) implements JSObject { + external bool get isActive; +} + +extension type _Navigator._(JSObject _) implements JSObject { + external JSPromise share(_ShareData data); + external bool canShare(_ShareData data); + external _UserActivation? get userActivation; +} + +bool get artifactDownloadSupported => true; + +bool get artifactShareSupported => + _hasFunction('share') && _hasFunction('canShare'); + +String get artifactDownloadUnsupportedMessage => + 'Downloading files is not supported in this browser.'; + +String get artifactShareUnsupportedMessage => + 'File sharing is not supported in this browser. Use Download to save the file.'; + +const String _fileReadyMessage = + 'File ready. Tap Share again to choose where to send it.'; + +Future saveArtifactFile(ArtifactFile file) async { + try { + final blob = _blobFor(file); + final url = _createObjectUrl(blob); + final anchor = _document.createElement('a'.toJS) + ..href = url + ..download = file.name.toJS; + _document.body.appendChild(anchor); + try { + anchor.click(); + } finally { + anchor.remove(); + // Revoking immediately can cancel a download in some browsers. + unawaited( + Future.delayed( + const Duration(seconds: 1), + () => _revokeObjectUrl(url), + ), + ); + } + return ArtifactTransferResult( + ArtifactTransferState.saved, + 'Downloaded ${file.name}.', + ); + } catch (_) { + return const ArtifactTransferResult( + ArtifactTransferState.failed, + 'Could not download the file. Try again.', + ); + } +} + +Future shareArtifactFile(ArtifactFile file) async { + if (!artifactShareSupported) { + return ArtifactTransferResult( + ArtifactTransferState.unsupported, + artifactShareUnsupportedMessage, + ); + } + final data = _ShareData(files: [_fileFor(file)].toJS); + try { + if (!_navigator.canShare(data)) { + return ArtifactTransferResult( + ArtifactTransferState.unsupported, + 'This browser cannot share this file type. Use Download to save the file.', + ); + } + } catch (_) { + return ArtifactTransferResult( + ArtifactTransferState.unsupported, + artifactShareUnsupportedMessage, + ); + } + // Fetching may outlast the browser's transient activation. Do not attempt a + // doomed share or substitute a url: the prepared bytes stay cached in the + // controller and the next tap shares them. + final activation = _navigator.userActivation; + if (activation != null && !activation.isActive) { + return const ArtifactTransferResult( + ArtifactTransferState.ready, + _fileReadyMessage, + ); + } + try { + await _navigator.share(data).toDart; + return const ArtifactTransferResult( + ArtifactTransferState.shared, + 'File shared.', + ); + } catch (error) { + final name = _errorName(error); + if (name == 'AbortError') { + return const ArtifactTransferResult( + ArtifactTransferState.canceled, + 'Sharing canceled.', + ); + } + if (name == 'NotAllowedError') { + return const ArtifactTransferResult( + ArtifactTransferState.blocked, + 'Sharing was blocked. Tap Share again, or use Download to save the file.', + ); + } + return const ArtifactTransferResult( + ArtifactTransferState.failed, + 'Could not share the file. Use Download to save it, or try Share again.', + ); + } +} + +_Blob _blobFor(ArtifactFile file) => _Blob( + [file.bytes.toJS].toJS, + _BlobOptions(type: file.mimeType.toJS), +); + +_File _fileFor(ArtifactFile file) => _File( + [_blobFor(file)].toJS, + file.name.toJS, + _FileOptions(type: file.mimeType.toJS), +); + +bool _hasFunction(String name) { + final value = _navigator.getProperty(name.toJS); + return value != null && value.isA(); +} + +String? _errorName(Object error) { + // A rejected JS promise arrives as a Dart error whose text carries the DOM + // exception name; the web's AbortError/NotAllowedError branches use those. + final text = '$error'; + for (final candidate in const ['AbortError', 'NotAllowedError']) { + if (text.contains(candidate)) return candidate; + } + return null; +} diff --git a/app/lib/features/artifacts/ui/artifact_gallery_page.dart b/app/lib/features/artifacts/ui/artifact_gallery_page.dart index e984079f..5d79bd0f 100644 --- a/app/lib/features/artifacts/ui/artifact_gallery_page.dart +++ b/app/lib/features/artifacts/ui/artifact_gallery_page.dart @@ -5,6 +5,8 @@ import 'package:flutter/services.dart'; import '../../../core/api_gateway.dart'; import '../../../ui/adaptive/host.dart'; import '../../chat/ui/transcript/chat_markdown_view.dart'; +import '../actions/artifact_file_actions.dart'; +import '../actions/artifact_file_bridge.dart'; import '../domain/artifact_groups.dart'; import '../domain/artifact_kind.dart'; import '../domain/artifact_record.dart'; @@ -28,8 +30,9 @@ const String artifactGalleryTitle = 'Artifacts'; /// never fetched); any other selection opens a native dialog with the recorded /// name, MIME and size, the visit's capture facts and, only when the recorded /// url resolves through [resolveArtifactUrl], native `Open` and `Copy link` -/// actions. Markdown previews use the same chat markdown renderer by default. -/// It never downloads, shares or filters. +/// actions plus file `Download`/`Share` for a server-served url. Markdown +/// previews use the same chat markdown renderer by default. It never filters, +/// and an external url is never fetched for preview or file transfer. class ArtifactGalleryPage extends StatefulWidget { const ArtifactGalleryPage({ super.key, @@ -39,6 +42,7 @@ class ArtifactGalleryPage extends StatefulWidget { this.openExternal = openArtifactExternally, this.fetch = fetchArtifact, this.markdownBuilder = chatMarkdownText, + this.fileBridge = const ArtifactFileBridge(), }); final List steps; @@ -47,6 +51,7 @@ class ArtifactGalleryPage extends StatefulWidget { final ArtifactExternalOpen openExternal; final ArtifactFetch fetch; final ArtifactMarkdownBuilder markdownBuilder; + final ArtifactFileBridge fileBridge; @override State createState() => _ArtifactGalleryPageState(); @@ -89,6 +94,7 @@ class _ArtifactGalleryPageState extends State { openExternal: widget.openExternal, fetch: widget.fetch, markdownBuilder: widget.markdownBuilder, + fileBridge: widget.fileBridge, ), ) : MaterialPageRoute( @@ -99,6 +105,7 @@ class _ArtifactGalleryPageState extends State { openExternal: widget.openExternal, fetch: widget.fetch, markdownBuilder: widget.markdownBuilder, + fileBridge: widget.fileBridge, ), ), ); @@ -120,12 +127,31 @@ class _ArtifactGalleryPageState extends State { step: step, resolved: resolved, ); + final content = Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + facts, + if (resolved != null && !resolved.external) ...[ + const SizedBox(height: 12), + ArtifactFileActions( + key: ValueKey( + 'artifact-files-${artifactVisitIdentity(group, artifact)}', + ), + artifact: artifact, + resolved: resolved, + fetch: widget.fetch, + bridge: widget.fileBridge, + ), + ], + ], + ); if (usesCupertinoHost(context)) { return showCupertinoDialog( context: context, builder: (dialogContext) => CupertinoAlertDialog( title: Text(artifactDisplayName(artifact)), - content: facts, + content: content, actions: [ if (resolved != null) CupertinoDialogAction( @@ -150,7 +176,7 @@ class _ArtifactGalleryPageState extends State { context: context, builder: (dialogContext) => AlertDialog( title: Text(artifactDisplayName(artifact)), - content: SingleChildScrollView(child: facts), + content: SingleChildScrollView(child: content), actions: [ if (resolved != null) TextButton( diff --git a/app/lib/features/artifacts/ui/artifact_viewer_body.dart b/app/lib/features/artifacts/ui/artifact_viewer_body.dart index e5ffdf1d..f5ffdbfe 100644 --- a/app/lib/features/artifacts/ui/artifact_viewer_body.dart +++ b/app/lib/features/artifacts/ui/artifact_viewer_body.dart @@ -4,17 +4,21 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import '../../../ui/adaptive/host.dart'; +import '../actions/artifact_file_actions.dart'; +import '../actions/artifact_file_bridge.dart'; import '../domain/artifact_preview.dart'; import '../domain/artifact_url.dart'; import '../domain/gallery_navigation.dart'; import 'artifact_selection_facts.dart'; import 'artifact_viewer_content.dart'; +import 'artifact_viewer_fetch.dart'; /// One viewer page: the recorded facts, position, live status, preview surface, -/// external actions and paging controls. +/// file transfer actions, external actions and paging controls. /// /// It is stateless so the page owns loading, fetch generations and focus; this -/// surface only draws the current page and reports the operator's intent. +/// surface only draws the current page and reports the operator's intent. The +/// page content scrolls as one column at large text sizes; paging stays fixed. class ArtifactViewerBody extends StatelessWidget { const ArtifactViewerBody({ super.key, @@ -28,6 +32,8 @@ class ArtifactViewerBody extends StatelessWidget { required this.onNext, required this.onOpen, required this.onCopy, + this.fetch = fetchArtifact, + this.fileBridge = const ArtifactFileBridge(), this.text, this.bytes, this.error, @@ -44,6 +50,8 @@ class ArtifactViewerBody extends StatelessWidget { final VoidCallback onNext; final VoidCallback onOpen; final VoidCallback onCopy; + final ArtifactFetch fetch; + final ArtifactFileBridge fileBridge; final String? text; final Uint8List? bytes; final String? error; @@ -54,42 +62,67 @@ class ArtifactViewerBody extends StatelessWidget { return Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ - Padding( - padding: const EdgeInsetsDirectional.fromSTEB(16, 12, 16, 4), - child: ArtifactSelectionFacts( - group: page.group, - artifact: page.artifact, - step: null, - resolved: plan.resolved, - ), - ), - Padding( - padding: const EdgeInsetsDirectional.fromSTEB(16, 4, 16, 4), - child: Text( - artifactViewerPositionLabel( - index, - count, - page.artifact.contentType, + Expanded( + child: SingleChildScrollView( + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Padding( + padding: const EdgeInsetsDirectional.fromSTEB(16, 12, 16, 4), + child: ArtifactSelectionFacts( + group: page.group, + artifact: page.artifact, + step: null, + resolved: plan.resolved, + ), + ), + Padding( + padding: const EdgeInsetsDirectional.fromSTEB(16, 4, 16, 4), + child: Text( + artifactViewerPositionLabel( + index, + count, + page.artifact.contentType, + ), + ), + ), + if (status != null) + Padding( + padding: const EdgeInsetsDirectional.fromSTEB(16, 0, 16, 4), + child: Semantics(liveRegion: true, child: Text(status!)), + ), + ArtifactPreviewBody( + plan: plan, + loading: loading, + markdownBuilder: markdownBuilder, + text: text, + bytes: bytes, + error: error, + ), + if (plan.resolved != null && !plan.resolved!.external) + Padding( + padding: const EdgeInsetsDirectional.fromSTEB(16, 4, 16, 4), + child: ArtifactFileActions( + key: ValueKey( + 'viewer-files-${page.group.stageKey}\u0000' + '${page.group.visit}\u0000${page.artifact.url}', + ), + artifact: page.artifact, + resolved: plan.resolved!, + fetch: fetch, + bridge: fileBridge, + ), + ), + if (plan.resolved != null) + _Actions( + resolved: plan.resolved!, + onOpen: onOpen, + onCopy: onCopy, + ), + ], ), ), ), - if (status != null) - Padding( - padding: const EdgeInsetsDirectional.fromSTEB(16, 0, 16, 4), - child: Semantics(liveRegion: true, child: Text(status!)), - ), - Expanded( - child: ArtifactPreviewBody( - plan: plan, - loading: loading, - markdownBuilder: markdownBuilder, - text: text, - bytes: bytes, - error: error, - ), - ), - if (plan.resolved != null) - _Actions(resolved: plan.resolved!, onOpen: onOpen, onCopy: onCopy), _Pager( index: index, count: count, diff --git a/app/lib/features/artifacts/ui/artifact_viewer_content.dart b/app/lib/features/artifacts/ui/artifact_viewer_content.dart index 519d12d4..a433946b 100644 --- a/app/lib/features/artifacts/ui/artifact_viewer_content.dart +++ b/app/lib/features/artifacts/ui/artifact_viewer_content.dart @@ -62,9 +62,9 @@ class ArtifactPreviewBody extends StatelessWidget { ), ); case ArtifactPreviewKind.text: - return _ScrollingText(child: SelectableText(text ?? '')); + return _PreviewPadding(child: SelectableText(text ?? '')); case ArtifactPreviewKind.markdown: - return _ScrollingText(child: markdownBuilder(context, text ?? '')); + return _PreviewPadding(child: markdownBuilder(context, text ?? '')); case ArtifactPreviewKind.unsupported: case ArtifactPreviewKind.unavailable: return const SizedBox.shrink(); @@ -93,14 +93,16 @@ class _Loading extends StatelessWidget { } } -class _ScrollingText extends StatelessWidget { - const _ScrollingText({required this.child}); +/// Preview text at its natural height; the viewer body owns the page scroll so +/// a long document and its actions scroll together instead of nested scrolls. +class _PreviewPadding extends StatelessWidget { + const _PreviewPadding({required this.child}); final Widget child; @override Widget build(BuildContext context) { - return SingleChildScrollView( + return Padding( padding: const EdgeInsetsDirectional.fromSTEB(16, 8, 16, 16), child: child, ); diff --git a/app/lib/features/artifacts/ui/artifact_viewer_page.dart b/app/lib/features/artifacts/ui/artifact_viewer_page.dart index 5673986f..cbb9a189 100644 --- a/app/lib/features/artifacts/ui/artifact_viewer_page.dart +++ b/app/lib/features/artifacts/ui/artifact_viewer_page.dart @@ -5,6 +5,7 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import '../../../ui/adaptive/host.dart'; +import '../actions/artifact_file_bridge.dart'; import '../domain/artifact_groups.dart'; import '../domain/artifact_preview.dart'; import '../domain/artifact_url.dart'; @@ -24,8 +25,9 @@ const String artifactViewerTitle = 'Artifact viewer'; /// `text/plain` artifact is selectable text, and a `.md`/`.markdown` or /// `text/markdown` artifact is handed to [markdownBuilder]. The selected page /// keeps its recorded facts visible and offers the existing external Open and -/// Copy link actions. Previous/Next walk the same filtered list the gallery -/// draws and stop at both ends; closing returns to the gallery row. +/// Copy link actions plus Download/Share of the same-origin bytes as a named +/// file. Previous/Next walk the same filtered list the gallery draws and stop at +/// both ends; closing returns to the gallery row. /// /// Nothing is ever drawn for an external, unsafe or unsupported url: the viewer /// reports the exact state instead. External urls are never fetched. @@ -38,6 +40,7 @@ class ArtifactViewerPage extends StatefulWidget { this.fetch = fetchArtifact, this.markdownBuilder = defaultArtifactMarkdown, this.openExternal = openArtifactExternally, + this.fileBridge = const ArtifactFileBridge(), }); final List groups; @@ -49,6 +52,7 @@ class ArtifactViewerPage extends StatefulWidget { final ArtifactFetch fetch; final ArtifactMarkdownBuilder markdownBuilder; final ArtifactExternalOpen openExternal; + final ArtifactFileBridge fileBridge; @override State createState() => _ArtifactViewerPageState(); @@ -228,6 +232,8 @@ class _ArtifactViewerPageState extends State { bytes: _fetched?.bytes, error: _error, status: _status, + fetch: widget.fetch, + fileBridge: widget.fileBridge, onPrevious: () => _step(-1), onNext: () => _step(1), onOpen: plan.resolved == null ? () {} : () => _open(plan.resolved!), diff --git a/app/notes/A3-files.md b/app/notes/A3-files.md new file mode 100644 index 00000000..d14382fc --- /dev/null +++ b/app/notes/A3-files.md @@ -0,0 +1,54 @@ +# A3 — artifact files: download and share + +## Scope + +The selected artifact can be saved or shared as a real file. The external +`Open` and `Copy link` actions stay unchanged; neither is reused as a stand-in +for a file transfer. + +## Implementation + +- `artifact_transfer.dart` is the platform seam with a web implementation and a + stub. The web file uses `dart:js_interop`/`dart:js_interop_unsafe` only, so the + same source compiles to JavaScript and WebAssembly without `package:web`. +- `artifact_transfer_web.dart` builds a `Blob`/`File` from the fetched bytes with + the recorded name and MIME type, downloads through an anchor created for that + name, and shares through `navigator.share` only when the platform can share + files. It never puts the artifact url or a blob page into the user's hands. +- `artifact_file_controller.dart` fetches bytes through the same + `ArtifactFetch` seam the in-app viewer already uses, so the same-origin + credential policy and HTTP status handling apply. One in-flight transfer at a + time; a second activation is ignored. Cancel stops the action from continuing + and a late result is never reported as a completed transfer. +- The selection sheet exposes `Download` and `Share` beside the existing + actions, with honest states for unsupported sharing (download still works), + missing/malformed name or MIME, fetch failure with its HTTP status, and + cancel. Nothing is silently substituted. + +## Evidence + +- Focused suite: 123 artifact tests pass; `flutter analyze` clean. +- Browser probe (`tool/artifact_gallery_probe.mjs`, 32 captures, 27 checks) on + both hosts, dark at 2x and 320 logical px: + - Material and Cupertino `Download` hand the host `report.csv`, `text/csv`, + 23 exact bytes. + - Material and Cupertino `Share` hand the host a `report.csv`, `text/csv`, + 23-byte `File`. + - Existing gallery/viewer checks (recorded rows, duplicate filename, empty vs + unavailable, image in-app, HTTP failure, external artifact never fetched, + 320/2x paging) still pass. + +## Known limits + +- The shared fetch seam has no cancellation token, so Cancel abandons the action + without aborting the HTTP request. The UI never claims the transfer finished. +- OS share sheets and file downloads are web-verified only. Android/iOS + transfer behavior remains unverified until the final build. +- No authenticated production artifact was transferred; the probe uses an + isolated fixture with fixed bytes. + +## Manager note + +The run reached its Code deadline with this tree complete and verified by the +manager: tests, analysis, browser build and the 27-check probe above. Merged +directly rather than replayed. diff --git a/app/test/features/artifacts/actions/artifact_file_actions_test.dart b/app/test/features/artifacts/actions/artifact_file_actions_test.dart new file mode 100644 index 00000000..16a2994e --- /dev/null +++ b/app/test/features/artifacts/actions/artifact_file_actions_test.dart @@ -0,0 +1,403 @@ +import 'dart:typed_data'; + +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/artifacts/actions/artifact_file.dart'; +import 'package:pipelines_app/features/artifacts/actions/artifact_file_actions.dart'; +import 'package:pipelines_app/features/artifacts/actions/artifact_file_bridge.dart'; +import 'package:pipelines_app/features/artifacts/actions/artifact_transfer.dart'; +import 'package:pipelines_app/features/artifacts/domain/artifact_groups.dart'; +import 'package:pipelines_app/features/artifacts/domain/artifact_record.dart'; +import 'package:pipelines_app/features/artifacts/domain/artifact_url.dart'; +import 'package:pipelines_app/features/artifacts/ui/artifact_gallery_page.dart'; +import 'package:pipelines_app/features/artifacts/ui/artifact_visit_list.dart'; +import 'package:pipelines_app/features/artifacts/ui/artifact_viewer_fetch.dart'; +import 'package:pipelines_app/features/artifacts/ui/artifact_viewer_page.dart'; + +import '../domain/artifact_fixtures.dart'; +import '../ui/artifact_visit_list_fixture.dart'; + +const _endpoint = 'ws://127.0.0.1:8081/connect'; +final Uint8List _bytes = Uint8List.fromList([7, 8, 9]); + +final ArtifactRecord _record = ArtifactRecord.fromJson({ + 'name': 'report.csv', + 'url': '/artifacts/1/1/report.csv', + 'content_type': 'text/csv', + 'size_bytes': 3, +}); + +ArtifactFileBridge _bridge({ + List? saved, + List? shared, + bool downloadSupported = true, + bool shareSupported = true, +}) => ArtifactFileBridge( + downloadSupported: downloadSupported, + shareSupported: shareSupported, + downloadUnsupportedMessage: 'No download on this host.', + shareUnsupportedMessage: 'No share on this host.', + download: (file) async { + saved?.add(file); + return ArtifactTransferResult( + ArtifactTransferState.saved, + 'Downloaded ${file.name}.', + ); + }, + share: (file) async { + shared?.add(file); + return const ArtifactTransferResult( + ArtifactTransferState.shared, + 'File shared.', + ); + }, +); + +Future _fetch(Uri uri) async => + ArtifactFetchResult(status: 200, bytes: _bytes); + +Widget _row({ + required bool cupertino, + ArtifactFileBridge? bridge, + ArtifactRecord? artifact, + ArtifactFetch? fetch, +}) { + final actions = ArtifactFileActions( + artifact: artifact ?? _record, + resolved: resolveArtifactUrl(_endpoint, _record.url)!, + fetch: fetch ?? _fetch, + bridge: bridge ?? _bridge(), + ); + return cupertino + ? CupertinoApp( + home: CupertinoPageScaffold( + child: SafeArea( + child: Padding(padding: const EdgeInsets.all(8), child: actions), + ), + ), + ) + : MaterialApp( + home: Scaffold( + body: Padding(padding: const EdgeInsets.all(8), child: actions), + ), + ); +} + +TextButton _materialButton(WidgetTester tester, String label) => + tester.widget( + find + .ancestor(of: find.text(label), matching: find.byType(TextButton)) + .first, + ); + +CupertinoButton _cupertinoButton(WidgetTester tester, String label) => + tester.widget( + find + .ancestor( + of: find.text(label), + matching: find.byType(CupertinoButton), + ) + .first, + ); + +void main() { + testWidgets('Download saves the exact named bytes and reports it', ( + tester, + ) async { + final saved = []; + await tester.pumpWidget( + _row(cupertino: false, bridge: _bridge(saved: saved)), + ); + + await tester.tap(find.text('Download')); + await tester.pumpAndSettle(); + + expect(saved, hasLength(1)); + expect(saved.single.name, 'report.csv'); + expect(saved.single.mimeType, 'text/csv'); + expect(saved.single.bytes, _bytes); + expect(find.text('Downloaded report.csv.'), findsOneWidget); + }); + + testWidgets('Share starts one file transfer, not a link', (tester) async { + final shared = []; + await tester.pumpWidget( + _row(cupertino: false, bridge: _bridge(shared: shared)), + ); + + await tester.tap(find.text('Share')); + await tester.pumpAndSettle(); + + expect(shared.single.name, 'report.csv'); + expect(shared.single.byteLength, 3); + expect(find.text('File shared.'), findsOneWidget); + }); + + testWidgets('unsupported share is explained but download stays enabled', ( + tester, + ) async { + final saved = []; + await tester.pumpWidget( + _row( + cupertino: false, + bridge: _bridge(saved: saved, shareSupported: false), + ), + ); + + expect(find.text('No share on this host.'), findsOneWidget); + expect(_materialButton(tester, 'Share').onPressed, isNull); + expect(_materialButton(tester, 'Download').onPressed, isNotNull); + + await tester.tap(find.text('Download')); + await tester.pumpAndSettle(); + expect(saved, hasLength(1)); + }); + + testWidgets('a slow fetch shows progress and cancel, then reports cancel', ( + tester, + ) async { + await tester.pumpWidget( + _row( + cupertino: false, + bridge: _bridge(), + fetch: (_) => Future.delayed( + const Duration(seconds: 30), + () => ArtifactFetchResult(status: 200, bytes: _bytes), + ), + ), + ); + + await tester.tap(find.text('Download')); + await tester.pump(); + expect(find.text('Preparing file…'), findsOneWidget); + expect(find.byType(CircularProgressIndicator), findsOneWidget); + expect(_materialButton(tester, 'Download').onPressed, isNull); + expect(find.text('Cancel'), findsOneWidget); + + await tester.tap(find.text('Cancel')); + await tester.pump(); + expect(find.text('Download canceled.'), findsOneWidget); + expect(find.text('Cancel'), findsNothing); + await tester.pump(const Duration(seconds: 31)); + }); + + testWidgets('both hosts keep the file actions whole at 320/2x dark', ( + tester, + ) async { + tester.view.physicalSize = const Size(640, 1200); + tester.view.devicePixelRatio = 2; + tester.platformDispatcher.textScaleFactorTestValue = 2; + tester.platformDispatcher.platformBrightnessTestValue = Brightness.dark; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue); + addTearDown(tester.platformDispatcher.clearPlatformBrightnessTestValue); + + for (final cupertino in [false, true]) { + await tester.pumpWidget(_row(cupertino: cupertino)); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + expect(find.text('Download'), findsOneWidget); + expect(find.text('Share'), findsOneWidget); + if (cupertino) { + expect(_cupertinoButton(tester, 'Download').onPressed, isNotNull); + expect(find.byType(TextButton), findsNothing); + } else { + expect(_materialButton(tester, 'Download').onPressed, isNotNull); + expect(find.byType(CupertinoButton), findsNothing); + } + } + }); + + testWidgets('the gallery selection offers both file actions in its dialog', ( + tester, + ) async { + final saved = []; + await tester.pumpWidget( + MaterialApp( + home: ArtifactGalleryPage( + steps: [ + step( + stage: 'review', + visit: 1, + artifacts: [ + artifact('report.csv', contentType: 'text/csv', sizeBytes: 3), + ], + ), + ], + configuredEndpoint: _endpoint, + fetch: _fetch, + fileBridge: _bridge(saved: saved), + ), + ), + ); + await tester.pumpAndSettle(); + + await tester.tap(find.text('report.csv')); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsOneWidget); + expect(find.text('Download'), findsOneWidget); + expect(find.text('Share'), findsOneWidget); + expect(find.text('Open'), findsOneWidget); + expect(find.text('Copy link'), findsOneWidget); + + await tester.tap(find.text('Download')); + await tester.pumpAndSettle(); + expect(saved.single.bytes, _bytes); + expect(find.text('Downloaded report.csv.'), findsOneWidget); + expect(find.byType(AlertDialog), findsOneWidget); + }); + + testWidgets('a host without file capabilities explains and disables both', ( + tester, + ) async { + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Padding( + padding: const EdgeInsets.all(8), + child: ArtifactFileActions( + artifact: _record, + resolved: resolveArtifactUrl(_endpoint, _record.url)!, + fetch: _fetch, + ), + ), + ), + ), + ); + + expect(find.text('Download'), findsOneWidget); + expect(find.text('Share'), findsOneWidget); + expect(_materialButton(tester, 'Download').onPressed, isNull); + expect(_materialButton(tester, 'Share').onPressed, isNull); + expect( + find.text('Downloading files is not supported on this platform yet.'), + findsOneWidget, + ); + expect( + find.text('File sharing is not supported on this platform yet.'), + findsOneWidget, + ); + }); + + testWidgets('gallery selection keeps both actions at 320/2x dark', ( + tester, + ) async { + tester.view.physicalSize = const Size(640, 1200); + tester.view.devicePixelRatio = 2; + tester.platformDispatcher.textScaleFactorTestValue = 2; + tester.platformDispatcher.platformBrightnessTestValue = Brightness.dark; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue); + addTearDown(tester.platformDispatcher.clearPlatformBrightnessTestValue); + + final steps = [ + step( + stage: 'review', + visit: 1, + artifacts: [ + artifact('report.csv', contentType: 'text/csv', sizeBytes: 3), + ], + ), + ]; + for (final cupertino in [false, true]) { + await tester.pumpWidget( + cupertino + ? CupertinoApp( + theme: const CupertinoThemeData(brightness: Brightness.dark), + home: ArtifactGalleryPage( + steps: steps, + configuredEndpoint: _endpoint, + fetch: _fetch, + fileBridge: _bridge(), + ), + ) + : MaterialApp( + theme: ThemeData(brightness: Brightness.dark), + home: ArtifactGalleryPage( + steps: steps, + configuredEndpoint: _endpoint, + fetch: _fetch, + fileBridge: _bridge(), + ), + ), + ); + await tester.pumpAndSettle(); + await tester.tap(find.text('report.csv')); + await tester.pumpAndSettle(); + + expect(tester.takeException(), isNull); + expect(find.text('Download'), findsOneWidget); + expect(find.text('Share'), findsOneWidget); + expect( + cupertino + ? find.byType(CupertinoAlertDialog) + : find.byType(AlertDialog), + findsOneWidget, + ); + await tester.tap(find.text('Close')); + await tester.pumpAndSettle(); + } + }); + + testWidgets( + 'the viewer offers file actions only for a same-origin artifact', + (tester) async { + final local = recordedArtifact( + 'clip.mp4', + url: '/artifacts/1/1/clip.mp4', + contentType: 'video/mp4', + ); + final external = recordedArtifact( + 'elsewhere.png', + url: 'https://elsewhere.test/elsewhere.png', + contentType: 'image/png', + ); + final localGroup = visitGroup(artifacts: [local]); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: ArtifactViewerPage( + key: const ValueKey('local'), + groups: [localGroup], + selectedIdentity: artifactVisitIdentity(localGroup, local), + configuredEndpoint: _endpoint, + fetch: _fetch, + fileBridge: _bridge(), + openExternal: (_) async => true, + ), + ), + ), + ); + await tester.pumpAndSettle(); + + expect(find.text('Download'), findsOneWidget); + expect(find.text('Share'), findsOneWidget); + + final externalGroup = visitGroup(artifacts: [external]); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: ArtifactViewerPage( + key: const ValueKey('external'), + groups: [externalGroup], + selectedIdentity: artifactVisitIdentity(externalGroup, external), + configuredEndpoint: _endpoint, + fetch: _fetch, + fileBridge: _bridge(), + openExternal: (_) async => true, + ), + ), + ), + ); + await tester.pumpAndSettle(); + + expect(find.text('Download'), findsNothing); + expect(find.text('Share'), findsNothing); + expect(find.text('Open'), findsOneWidget); + }, + ); +} diff --git a/app/test/features/artifacts/actions/artifact_file_controller_test.dart b/app/test/features/artifacts/actions/artifact_file_controller_test.dart new file mode 100644 index 00000000..db4b7d1e --- /dev/null +++ b/app/test/features/artifacts/actions/artifact_file_controller_test.dart @@ -0,0 +1,229 @@ +import 'dart:async'; +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/artifacts/actions/artifact_file.dart'; +import 'package:pipelines_app/features/artifacts/actions/artifact_file_bridge.dart'; +import 'package:pipelines_app/features/artifacts/actions/artifact_file_controller.dart'; +import 'package:pipelines_app/features/artifacts/actions/artifact_transfer.dart'; +import 'package:pipelines_app/features/artifacts/domain/artifact_record.dart'; +import 'package:pipelines_app/features/artifacts/domain/artifact_url.dart'; +import 'package:pipelines_app/features/artifacts/ui/artifact_viewer_fetch.dart'; + +const _url = 'http://127.0.0.1:8081/artifacts/1/1/report.csv'; +final Uint8List _bytes = Uint8List.fromList([10, 20, 30, 40]); + +final ArtifactRecord _record = ArtifactRecord.fromJson({ + 'name': 'public/reports/report.csv', + 'url': '/artifacts/1/1/report.csv', + 'content_type': 'text/csv; charset=utf-8', + 'size_bytes': 4, +}); + +ArtifactFileActionsController _controller({ + ArtifactFetch? fetch, + ArtifactFileBridge bridge = const ArtifactFileBridge(), +}) => ArtifactFileActionsController( + artifact: _record, + resolved: resolveArtifactUrl('ws://127.0.0.1:8081/connect', _record.url)!, + fetch: fetch ?? (_) async => ArtifactFetchResult(status: 200, bytes: _bytes), + bridge: bridge, +); + +ArtifactFileBridge _bridge({ + List? saved, + List? shared, + ArtifactTransferResult shareResult = const ArtifactTransferResult( + ArtifactTransferState.shared, + 'File shared.', + ), + bool downloadSupported = true, + bool shareSupported = true, +}) => ArtifactFileBridge( + downloadSupported: downloadSupported, + shareSupported: shareSupported, + downloadUnsupportedMessage: 'No download here.', + shareUnsupportedMessage: 'No share here.', + download: (file) async { + saved?.add(file); + return ArtifactTransferResult( + ArtifactTransferState.saved, + 'Downloaded ${file.name}.', + ); + }, + share: (file) async { + shared?.add(file); + return shareResult; + }, +); + +void main() { + test('download carries the exact named, typed bytes', () async { + final saved = []; + final controller = _controller(bridge: _bridge(saved: saved)); + + await controller.download(); + + expect(saved, hasLength(1)); + expect(saved.single.name, 'report.csv'); + expect(saved.single.mimeType, 'text/csv'); + expect(saved.single.bytes, _bytes); + expect(controller.status, 'Downloaded report.csv.'); + expect(controller.busy, isFalse); + }); + + test('share uses a file, not a link, and reports when shared', () async { + final shared = []; + final fetched = []; + final controller = _controller( + bridge: _bridge(shared: shared), + fetch: (uri) async { + fetched.add(uri); + return ArtifactFetchResult(status: 200, bytes: _bytes); + }, + ); + + await controller.share(); + + expect(fetched, [Uri.parse(_url)]); + expect(shared, hasLength(1)); + expect(shared.single.name, 'report.csv'); + expect(shared.single.mimeType, 'text/csv'); + expect(shared.single.bytes, _bytes); + expect(controller.canShare, isTrue); + expect(controller.status, 'File shared.'); + }); + + test('unsupported sharing leaves download working', () async { + final saved = []; + final shared = []; + var fetches = 0; + final controller = _controller( + fetch: (_) async { + fetches += 1; + return ArtifactFetchResult(status: 200, bytes: _bytes); + }, + bridge: _bridge(saved: saved, shared: shared, shareSupported: false), + ); + + await controller.share(); + expect(shared, isEmpty); + expect(fetches, 0); + expect(controller.status, 'No share here.'); + expect(controller.canDownload, isTrue); + + await controller.download(); + expect(saved, hasLength(1)); + expect(controller.status, 'Downloaded report.csv.'); + }); + + test( + 'an HTTP or network fetch failure is reported, never transferred', + () async { + final saved = []; + final bridge = _bridge(saved: saved); + final notFound = _controller( + fetch: (_) async => + ArtifactFetchResult(status: 404, bytes: Uint8List(0)), + bridge: bridge, + ); + + await notFound.download(); + expect(notFound.status, 'Could not fetch the artifact (HTTP 404).'); + expect(saved, isEmpty); + expect(notFound.busy, isFalse); + + final offline = _controller( + fetch: (_) async => throw const ArtifactFetchException('network down'), + bridge: bridge, + ); + await offline.download(); + expect(offline.status, contains('network down')); + expect(saved, isEmpty); + }, + ); + + test( + 'cancel during a slow fetch starts no transfer and ignores the result', + () async { + final pending = Completer(); + final saved = []; + final controller = _controller( + fetch: (_) => pending.future, + bridge: _bridge(saved: saved), + ); + + final action = controller.download(); + await Future.delayed(Duration.zero); + expect(controller.busy, isTrue); + expect(controller.canCancel, isTrue); + expect(controller.status, 'Preparing file…'); + + controller.cancel(); + expect(controller.busy, isFalse); + expect(controller.status, 'Download canceled.'); + + pending.complete(ArtifactFetchResult(status: 200, bytes: _bytes)); + await action; + expect(saved, isEmpty); + expect(controller.status, 'Download canceled.'); + }, + ); + + test('one tap starts one transfer even when called twice', () async { + var fetches = 0; + final pending = Completer(); + final saved = []; + final controller = _controller( + fetch: (_) { + fetches += 1; + return pending.future; + }, + bridge: _bridge(saved: saved), + ); + + final first = controller.download(); + final second = controller.download(); + await Future.delayed(Duration.zero); + expect(fetches, 1); + + pending.complete(ArtifactFetchResult(status: 200, bytes: _bytes)); + await first; + await second; + expect(saved, hasLength(1)); + }); + + test('a ready share reuses prepared bytes on the fresh tap', () async { + var fetches = 0; + var shares = 0; + final controller = _controller( + fetch: (_) async { + fetches += 1; + return ArtifactFetchResult(status: 200, bytes: _bytes); + }, + bridge: ArtifactFileBridge( + shareSupported: true, + share: (file) async { + shares += 1; + return shares == 1 + ? const ArtifactTransferResult( + ArtifactTransferState.ready, + 'File ready. Tap Share again to choose where to send it.', + ) + : const ArtifactTransferResult( + ArtifactTransferState.shared, + 'File shared.', + ); + }, + ), + ); + + await controller.share(); + expect(controller.status, contains('Tap Share again')); + await controller.share(); + + expect(fetches, 1); + expect(shares, 2); + expect(controller.status, 'File shared.'); + }); +} diff --git a/app/test/features/artifacts/actions/artifact_file_test.dart b/app/test/features/artifacts/actions/artifact_file_test.dart new file mode 100644 index 00000000..8e4c71d0 --- /dev/null +++ b/app/test/features/artifacts/actions/artifact_file_test.dart @@ -0,0 +1,99 @@ +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/artifacts/actions/artifact_file.dart'; +import 'package:pipelines_app/features/artifacts/domain/artifact_record.dart'; + +ArtifactRecord _record( + String name, { + String contentType = '', + String url = '/artifacts/1/1/report.csv', +}) => ArtifactRecord.fromJson({ + 'name': name, + 'url': url, + 'content_type': contentType, + 'size_bytes': 10, +}); + +void main() { + test('a recorded name keeps only its basename', () { + final file = artifactFileFor( + artifact: _record('public/reports/result.csv', contentType: 'text/csv'), + url: Uri.parse('http://127.0.0.1:8081/artifacts/1/1/result.csv'), + bytes: Uint8List.fromList([1, 2, 3]), + ); + + expect(file.name, 'result.csv'); + expect(file.mimeType, 'text/csv'); + expect(file.byteLength, 3); + expect(file.bytes, [1, 2, 3]); + }); + + test( + 'a recorded name with backslashes and control characters is repaired', + () { + final name = artifactFileName( + _record('C:\\tmp\\odd\u0001name.csv'), + Uri.parse('http://127.0.0.1/a.csv'), + ); + + expect(name, 'odd_name.csv'); + }, + ); + + test('a missing name falls back to the url basename then artifact', () { + expect( + artifactFileName( + _record(''), + Uri.parse('http://127.0.0.1:8081/artifacts/1/1/from-url.csv'), + ), + 'from-url.csv', + ); + expect( + artifactFileName(_record('public/'), Uri.parse('http://127.0.0.1/')), + 'artifact', + ); + expect( + artifactFileName(_record('..'), Uri.parse('http://127.0.0.1/')), + 'artifact', + ); + }); + + test('the recorded media type loses parameters and is validated', () { + expect( + artifactFileMimeType( + _record('a.txt', contentType: 'Text/Plain; charset=utf-8'), + ), + 'text/plain', + ); + expect( + artifactFileMimeType(_record('a.bin')), + artifactFileFallbackMimeType, + ); + expect( + artifactFileMimeType(_record('a.bin', contentType: 'not a mime')), + artifactFileFallbackMimeType, + ); + }); + + test('a missing name or MIME type gets an explicit fallback notice', () { + final url = Uri.parse('http://127.0.0.1/artifacts/1/1/kept.csv'); + + expect( + artifactFileRecordingNotice( + _record('kept.csv', contentType: 'text/csv'), + url, + ), + isNull, + ); + expect( + artifactFileRecordingNotice(_record('', contentType: 'text/csv'), url), + 'No usable recorded name; the file is saved as kept.csv.', + ); + expect( + artifactFileRecordingNotice(_record('kept.csv'), url), + 'No usable recorded MIME type; the file is saved as ' + 'application/octet-stream.', + ); + }); +} diff --git a/app/tool/artifact_gallery_probe.dart b/app/tool/artifact_gallery_probe.dart index 3190fa10..c16a24b9 100644 --- a/app/tool/artifact_gallery_probe.dart +++ b/app/tool/artifact_gallery_probe.dart @@ -121,6 +121,24 @@ List _steps(String origin, String state) { }, ]; } + if (state == 'files') { + return [ + { + 'stage': 'reviewer', + 'sequence': 1, + 'status': 'completed', + 'control': {'visit': 1}, + 'artifacts': [ + _file( + 'report.csv', + url: '$origin/fixture/report.csv', + contentType: 'text/csv', + sizeBytes: 23, + ), + ], + }, + ]; + } return [ { 'stage': 'implementer', diff --git a/app/tool/artifact_gallery_probe.mjs b/app/tool/artifact_gallery_probe.mjs index d0e42c4a..6903e981 100644 --- a/app/tool/artifact_gallery_probe.mjs +++ b/app/tool/artifact_gallery_probe.mjs @@ -91,6 +91,7 @@ const probePng = () => { ]); }; const png = probePng(); +const probeCsv = Buffer.from('id,name\n1,alpha\n2,beta\n'); const server = createServer(async (req, res) => { const pathname = decodeURIComponent(new URL(req.url, 'http://localhost').pathname); @@ -100,6 +101,14 @@ const server = createServer(async (req, res) => { res.end('missing artifact\n'); return; } + if (pathname.endsWith('/report.csv')) { + res.writeHead(200, { + 'content-type': 'text/csv', + 'content-length': probeCsv.length, + }); + res.end(probeCsv); + return; + } if (pathname.endsWith('.png')) { res.writeHead(200, { 'content-type': 'image/png' }); res.end(png); @@ -179,6 +188,49 @@ try { })).result.sessionId; await send('Page.enable', {}, session); await send('Runtime.enable', {}, session); + // Record the real bytes the app hands to the OS. The download anchor's + // click is swallowed so headless Chrome never writes into the profile; the + // share function replaces the browser sheet with a recorder. + await send('Page.addScriptToEvaluateOnNewDocument', { + source: `(() => { + const state = { objects: [], downloads: [], shares: [] }; + window.__artifactTransfer = state; + const realCreate = URL.createObjectURL.bind(URL); + URL.createObjectURL = (blob) => { + const url = realCreate(blob); + const entry = { url, type: blob.type, size: blob.size, name: null, bytes: null }; + state.objects.push(entry); + blob.arrayBuffer().then((buffer) => { + entry.bytes = Array.from(new Uint8Array(buffer)); + }); + return url; + }; + HTMLAnchorElement.prototype.click = function () { + state.downloads.push({ name: this.download, href: this.href }); + }; + const navProto = Object.getPrototypeOf(navigator); + Object.defineProperty(navProto, 'share', { + configurable: true, + value: async (data) => { + state.shares.push((data?.files || []).map((file) => { + const entry = { name: file.name, type: file.type, size: file.size, bytes: null }; + file.arrayBuffer().then((buffer) => { + entry.bytes = Array.from(new Uint8Array(buffer)); + }); + return entry; + })); + }, + }); + Object.defineProperty(navProto, 'canShare', { + configurable: true, + value: (data) => Array.isArray(data?.files) && data.files.length > 0, + }); + Object.defineProperty(navProto, 'userActivation', { + configurable: true, + get: () => ({ isActive: true, hasBeenActive: true }), + }); + })();`, + }, session); await send('Browser.grantPermissions', { origin, permissions: ['clipboardReadWrite', 'clipboardSanitizedWrite'], @@ -255,6 +307,23 @@ try { (await send('Target.getTargets')).result.targetInfos.filter( (target) => target.type === 'page', ).length; + const transferState = () => + evaluate(`(() => { + const state = window.__artifactTransfer; + return { + downloads: state.downloads, + objects: state.objects.map(({ url, type, size, name, bytes }) => ({ url, type, size, name, bytes })), + shares: state.shares, + }; + })()`); + const waitForBytes = async (read) => { + for (let i = 0; i < 40; i++) { + const value = await read(); + if (value?.byteLength) return value; + await delay(100); + } + throw new Error('Timed out waiting for transfer bytes'); + }; const capture = async (name, width = 390, height = 844, scale = 1) => { await send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: scale, mobile: width < 600, @@ -591,6 +660,110 @@ try { await openScaled('cupertino', 'a1w-cupertino-2x-320'); evidence.checks.push({ check: 'Cupertino 2x/320 keeps the recorded rows, facts and actions', value: true }); + // File actions: a real same-origin artifact is fetched, then handed to the + // host as a named file. Blob/anchor and navigator.share are intercepted above + // so the evidence is the exact bytes, MIME type and download name, not a + // screenshot of a promise. + const sameBytes = (actual, expected) => + Array.isArray(actual) && + actual.length === expected.length && + actual.every((value, index) => value === expected[index]); + const fileProbe = async (platform, prefix, extra = '') => { + await send('Emulation.setDeviceMetricsOverride', { + width: 390, height: 844, deviceScaleFactor: 1, mobile: true, + }, session); + const before = await targetCount(); + await navigate(galleryView(`&state=files${extra}`, platform), 'Artifacts'); + await clickExact('report.csv'); + await delay(500); + if (!(await hasLabel('Download')) || !(await hasLabel('Share'))) { + throw new Error(`${platform} selection lost its file actions: ${JSON.stringify(await labels())}`); + } + await capture(`${prefix}-files-selected`); + + await clickExact('Download'); + let downloaded; + try { + downloaded = await waitFor(async () => { + const state = await transferState(); + return state.objects[0]?.bytes ? state : null; + }, `${platform} download bytes`); + } catch (error) { + throw new Error( + `${error.message}\nstate=${JSON.stringify(await transferState())}\nbody=${JSON.stringify(await bodyText())}`, + ); + } + const download = downloaded.downloads[0]; + const object = downloaded.objects[0]; + if (downloaded.downloads.length !== 1) { + throw new Error(`${platform} did not request exactly one download: ${JSON.stringify(downloaded)}`); + } + if (download.name !== 'report.csv') { + throw new Error(`${platform} download name was ${JSON.stringify(download.name)}`); + } + if (!download.href.startsWith('blob:')) { + throw new Error(`${platform} download used a non-blob href: ${JSON.stringify(download.href)}`); + } + if (object.type !== 'text/csv' || object.size !== probeCsv.length) { + throw new Error(`${platform} blob was ${object.type}/${object.size}, expected text/csv/${probeCsv.length}`); + } + if (!sameBytes(object.bytes, Array.from(probeCsv))) { + throw new Error(`${platform} download bytes differed from the served artifact`); + } + if (!(await bodyText()).includes('Downloaded report.csv.')) { + throw new Error(`${platform} download did not report its file: ${JSON.stringify(await bodyText())}`); + } + evidence.checks.push({ + check: `${platform} Download hands the host report.csv, text/csv, ${probeCsv.length} exact bytes`, + value: true, + name: download.name, + mime: object.type, + size: object.size, + blob: download.href.startsWith('blob:'), + }); + await capture(`${prefix}-files-downloaded`); + + await clickExact('Share'); + let shared; + try { + shared = await waitFor(async () => { + const state = await transferState(); + return state.shares[0]?.[0]?.bytes ? state : null; + }, `${platform} share file`); + } catch (error) { + throw new Error( + `${error.message}\nstate=${JSON.stringify(await transferState())}\nbody=${JSON.stringify(await bodyText())}`, + ); + } + const file = shared.shares[0]?.[0]; + if (shared.shares.length !== 1 || shared.shares[0].length !== 1) { + throw new Error(`${platform} share received ${JSON.stringify(shared.shares)}`); + } + if (file.name !== 'report.csv' || file.type !== 'text/csv' || file.size !== probeCsv.length) { + throw new Error(`${platform} shared file was ${JSON.stringify(file)}`); + } + if (!sameBytes(file.bytes, Array.from(probeCsv))) { + throw new Error(`${platform} shared bytes differed from the served artifact`); + } + if (!(await bodyText()).includes('File shared.')) { + throw new Error(`${platform} share did not report success: ${JSON.stringify(await bodyText())}`); + } + if ((await targetCount()) !== before) { + throw new Error(`${platform} file actions opened a browser tab`); + } + evidence.checks.push({ + check: `${platform} Share hands the host a report.csv, text/csv, ${probeCsv.length} byte file`, + value: true, + name: file.name, + mime: file.type, + size: file.size, + }); + await capture(`${prefix}-files-shared`); + }; + await fileProbe('material', 'a3-material'); + await fileProbe('cupertino', 'a3-cupertino'); + await fileProbe('cupertino', 'a3-cupertino-dark', '&theme=dark'); + console.log(JSON.stringify(evidence, null, 2)); } finally { ws?.close(); From 38488b7ec7832736b5bebc98f80574990537c0e6 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 22 Oct 2026 01:43:10 +0100 Subject: [PATCH 08/13] docs(app): record artifact download/share --- app/PARITY.md | 2 +- app/WORK.md | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/app/PARITY.md b/app/PARITY.md index 7798a517..9371bad4 100644 --- a/app/PARITY.md +++ b/app/PARITY.md @@ -38,7 +38,7 @@ or scratch servers only, never real operator sessions/runs/workflows. | Changes/diffs | Preview via run detail | settled-run aggregate gate, recorded file/diff/close/back verified in the real app; per-visit capture entry and paging remain | | Artifact groups | Preview: run detail → recorded groups, selection facts, external Open/Copy link | present the visit's turn documents (input.md/memory.md/output.md, session.html) as gallery entries; in-app viewer next | | Artifact preview | Preview: image + markdown/text in-app through the chat renderer, paging, honest unsupported/external/HTTP states | video and HTML remain external-only | -| Artifact actions | Source safe URL resolution | separate external-open/copy/download; SHARE REAL NAMED MIME FILES, not links; slow activation/cancel/errors | +| Artifact actions | Preview: external Open, Copy link, download and native share carry the recorded name/MIME bytes; progress, cancel, HTTP failure and unsupported-share states | OS share/download on Android/iOS remain unverified until the final build | | Session audit/export repair facts | Missing UI | session.html read-only open, partial/missing/skipped/repair choices without fabricating complete evidence | | Chat session management | Preview list + open session; actions from the list | directory groups/search, shared rename/star/close/reopen/create, local hide/undo/seen state, create dialog in the shell | | Chat history/live transport | Preview: `/chat` list and `/chat/:id` history, paging, live failure notice | run-detail-style reconnect verification in the real app, then composer integration | diff --git a/app/WORK.md b/app/WORK.md index 949eabb3..f999f40f 100644 --- a/app/WORK.md +++ b/app/WORK.md @@ -64,6 +64,7 @@ All work under app/. Existing applications remain running and unchanged. | Run graph | Run-mode executed-route canvas | run89 retained/5b833e7 | server storage bug blocked the run; manager ran43 graph tests; recorded visits only, legend | merged main; ancestry verified | published8096 | | Run graph tab | Graph tab + recorded-stage selection | run92 retained/d74e5c5 | evidence bug blocked the run; manager ran147 runs tests + both-host probe (7 checks, graph/legend/selection/missing wording) | merged main; ancestry verified | preview republish pending | | Schedule form | Native schedule draft editor | run78 /flutter/schedule-form | binds74, no save engine | merged main; ancestry verified | published8096 | +| Artifact files | Download/share named bytes | run99 retained/841dd50 | Code deadline recovery; manager ran123 artifacts tests + analyze + 27-check/32-capture probe; exact name, MIME and byte length both hosts | merged main; ancestry verified | preview republish pending | | Pipeline schedules | Saved schedules in pipeline Summary | run93 /ea2179cd | evidence bug blocked the run after commit; manager ran141 schedules/pipelines tests + 15-check/13-capture both-host probe; create/edit/pause/delete with CAS | merged main; ancestry verified | preview republish pending | ## Next ready work From 221a2582dcfa2f259007bedb26211dc3d9687008 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 22 Oct 2026 02:01:41 +0100 Subject: [PATCH 09/13] feat(app): native permission and question cards in the chat transcript --- app/PARITY.md | 2 +- .../chat/conversation/chat_card_styles.dart | 56 ++ .../conversation/chat_permission_card.dart | 233 ++++++++ .../chat_permission_card_model.dart | 186 ++++++ .../chat/conversation/chat_question_card.dart | 230 ++++++++ .../chat_question_card_controls.dart | 65 +++ .../chat_question_card_fields.dart | 170 ++++++ .../chat_question_card_model.dart | 169 ++++++ .../chat_question_option_controls.dart | 150 +++++ .../chat_question_recorded_answers.dart | 99 ++++ .../chat_question_validation.dart | 123 ++++ .../chat/conversation/chat_thread_cards.dart | 190 ++++++ .../conversation/chat_thread_controller.dart | 48 ++ .../chat/conversation/chat_thread_view.dart | 32 +- .../conversation/chat_transcript_card.dart | 121 ++++ .../features/chat/domain/chat_transcript.dart | 10 +- app/notes/C4-approvals.md | 148 +++++ .../chat_permission_card_test.dart | 415 +++++++++++++ .../chat_question_card_model_test.dart | 159 +++++ .../conversation/chat_question_card_test.dart | 545 ++++++++++++++++++ .../conversation/chat_thread_cards_test.dart | 82 +++ .../conversation/chat_thread_fixtures.dart | 8 + app/tool/chat_approvals_probe.dart | 167 ++++++ app/tool/chat_approvals_probe.mjs | 356 ++++++++++++ 24 files changed, 3756 insertions(+), 8 deletions(-) create mode 100644 app/lib/features/chat/conversation/chat_card_styles.dart create mode 100644 app/lib/features/chat/conversation/chat_permission_card.dart create mode 100644 app/lib/features/chat/conversation/chat_permission_card_model.dart create mode 100644 app/lib/features/chat/conversation/chat_question_card.dart create mode 100644 app/lib/features/chat/conversation/chat_question_card_controls.dart create mode 100644 app/lib/features/chat/conversation/chat_question_card_fields.dart create mode 100644 app/lib/features/chat/conversation/chat_question_card_model.dart create mode 100644 app/lib/features/chat/conversation/chat_question_option_controls.dart create mode 100644 app/lib/features/chat/conversation/chat_question_recorded_answers.dart create mode 100644 app/lib/features/chat/conversation/chat_question_validation.dart create mode 100644 app/lib/features/chat/conversation/chat_thread_cards.dart create mode 100644 app/lib/features/chat/conversation/chat_transcript_card.dart create mode 100644 app/notes/C4-approvals.md create mode 100644 app/test/features/chat/conversation/chat_permission_card_test.dart create mode 100644 app/test/features/chat/conversation/chat_question_card_model_test.dart create mode 100644 app/test/features/chat/conversation/chat_question_card_test.dart create mode 100644 app/test/features/chat/conversation/chat_thread_cards_test.dart create mode 100644 app/tool/chat_approvals_probe.dart create mode 100644 app/tool/chat_approvals_probe.mjs diff --git a/app/PARITY.md b/app/PARITY.md index 9371bad4..d1535a3b 100644 --- a/app/PARITY.md +++ b/app/PARITY.md @@ -46,7 +46,7 @@ or scratch servers only, never real operator sessions/runs/workflows. | Chat activity/reasoning/tools | Source raw fields only | one activity line, compaction, native reasoning/tools overlays, lifecycle/input/output/error/duration/edit diff | | Chat composer | Preview: field, Send/Stop, persisted draft, queued/refusal lines; one verified send in the real app flow | attachments, paste and slash palette remain | | Chat attachments | Source request facade | picker/paste, latest1MiB total wire bound, base64 files, removable named chips, exact history reconciliation | -| Chat permissions/questions | Source request facade | native approval/risk cards and form option/free-text answers; pending/resolved/stale/error states | +| Chat permissions/questions | Source: native approval/risk and question cards in the conversation view | authenticated smoke with a real pending approval/question; live multi-client resolution; no production decision sent | | Chat model/Info/background tasks | Source request facade | current-model selection, numeric Info modal (unknown !=0), bounded running shell pages | | Chat commands/notices/scroll | Missing | slash palette/actions, unknown-command send-as-message, dismissible local notices, saved scroll/follow intent | | Saved schedule list | Source | pipeline entry and route registration, exact timer provenance vocabulary | diff --git a/app/lib/features/chat/conversation/chat_card_styles.dart b/app/lib/features/chat/conversation/chat_card_styles.dart new file mode 100644 index 00000000..65135523 --- /dev/null +++ b/app/lib/features/chat/conversation/chat_card_styles.dart @@ -0,0 +1,56 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +/// Host-native typography and colour for the approval and question cards. +/// +/// The cards share one hierarchy: the card title uses the host's title style, +/// field/answer labels sit visibly below it, and recorded prose uses the body +/// style. Keeping the styles here stops each card file from inventing its own +/// size and colour; everything still comes from the active Material/Cupertino +/// theme, so light, dark and text scaling follow the host. +TextStyle? chatCardTitleStyle(BuildContext context, bool cupertino) => + cupertino + ? CupertinoTheme.of(context).textTheme.navTitleTextStyle + : Theme.of(context).textTheme.titleMedium; + +TextStyle? chatCardBodyStyle(BuildContext context, bool cupertino) => cupertino + ? CupertinoTheme.of(context).textTheme.textStyle + : Theme.of(context).textTheme.bodyMedium; + +/// A field or recorded-answer label. Under Cupertino the system tab-label style +/// (the same subordinate style the rest of the app uses for secondary copy) +/// keeps labels from reading as extra headings; Material keeps `titleSmall`. +TextStyle? chatCardLabelStyle(BuildContext context, bool cupertino) => cupertino + ? CupertinoTheme.of( + context, + ).textTheme.tabLabelTextStyle.copyWith(color: chatCardSecondaryColor(context, true)) + : Theme.of(context).textTheme.titleSmall; + +/// Body text that supports a control, such as a field description. +TextStyle? chatCardSecondaryStyle(BuildContext context, bool cupertino) => + (chatCardBodyStyle(context, cupertino) ?? const TextStyle()).copyWith( + color: chatCardSecondaryColor(context, cupertino), + ); + +Color chatCardSecondaryColor(BuildContext context, bool cupertino) => cupertino + ? CupertinoColors.secondaryLabel.resolveFrom(context) + : Theme.of(context).colorScheme.onSurfaceVariant; + +Color chatCardErrorColor(BuildContext context, bool cupertino) => cupertino + ? CupertinoColors.systemRed.resolveFrom(context) + : Theme.of(context).colorScheme.error; + +/// The amber risk hue: the host's warning role, never a bespoke palette. +Color chatCardWarningColor(BuildContext context, bool cupertino) => cupertino + ? CupertinoColors.systemOrange.resolveFrom(context) + : Theme.of(context).colorScheme.tertiary; + +/// A quiet inset surface for resource blocks and risk panels. +Color chatCardFillColor(BuildContext context, bool cupertino) => cupertino + ? CupertinoColors.secondarySystemFill.resolveFrom(context) + : Theme.of(context).colorScheme.surfaceContainerHighest; + +Color chatCardWarningFillColor(BuildContext context, bool cupertino) => + cupertino + ? CupertinoColors.secondarySystemFill.resolveFrom(context) + : Theme.of(context).colorScheme.tertiaryContainer; diff --git a/app/lib/features/chat/conversation/chat_permission_card.dart b/app/lib/features/chat/conversation/chat_permission_card.dart new file mode 100644 index 00000000..21f93b37 --- /dev/null +++ b/app/lib/features/chat/conversation/chat_permission_card.dart @@ -0,0 +1,233 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../ui/sessions/chat_adaptive.dart'; +import '../ui/transcript/native_disclosure.dart'; +import 'chat_card_styles.dart'; +import 'chat_permission_card_model.dart'; + +/// One recorded permission request as a native card. +/// +/// The headline is the request's action (or its recorded outcome), the status +/// line is the server's own note where present, and the once/always/reject +/// controls appear only while the request is still open. Every server string is +/// rendered as text, never parsed as markup. +class ChatPermissionCard extends StatelessWidget { + const ChatPermissionCard({ + super.key, + required this.card, + required this.onDecision, + this.error, + }); + + final ChatPermissionCardData card; + final Future Function(String decision) onDecision; + final String? error; + + @override + Widget build(BuildContext context) => + chatControlsStyleOf(context) == ChatControlsStyle.cupertino + ? _cupertino(context) + : _material(context); + + Widget _body(BuildContext context, {required bool cupertino}) { + final body = Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Padding( + padding: const EdgeInsetsDirectional.only(end: 12), + child: Icon( + cupertino + ? CupertinoIcons.exclamationmark_shield + : Icons.shield_outlined, + color: chatCardWarningColor(context, cupertino), + ), + ), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + card.headline, + style: chatCardTitleStyle(context, cupertino), + ), + Text( + card.statusLine, + style: chatCardSecondaryStyle(context, cupertino), + ), + ], + ), + ), + ], + ), + if (card.resourceText.isNotEmpty) ...[ + const SizedBox(height: 12), + DecoratedBox( + decoration: BoxDecoration( + color: chatCardFillColor(context, cupertino), + borderRadius: BorderRadius.circular(8), + ), + child: Padding( + padding: const EdgeInsets.all(8), + child: Text( + card.resourceText, + maxLines: chatApprovalMaxResourceLines, + overflow: TextOverflow.ellipsis, + ), + ), + ), + if (card.resources.join('\n') != card.resourceText) + NativeDisclosure( + label: 'Show full request', + childBuilder: (context) => + SelectableText(card.resources.join('\n')), + ), + ], + if (card.showRisk && card.risk.trim().isNotEmpty) ...[ + const SizedBox(height: 12), + _risk(context, cupertino), + ], + if (error != null && error!.trim().isNotEmpty) ...[ + const SizedBox(height: 12), + Semantics( + liveRegion: true, + child: Text( + error!, + style: chatCardBodyStyle( + context, + cupertino, + )?.copyWith(color: chatCardErrorColor(context, cupertino)), + ), + ), + ], + if (card.actionable) ...[ + const SizedBox(height: 12), + _controls(context, cupertino), + ], + ], + ); + return cupertino + ? DefaultTextStyle.merge( + style: CupertinoTheme.of(context).textTheme.textStyle, + child: body, + ) + : body; + } + + Widget _risk(BuildContext context, bool cupertino) { + final tint = chatCardWarningColor(context, cupertino); + return DecoratedBox( + decoration: BoxDecoration( + color: chatCardWarningFillColor(context, cupertino), + borderRadius: BorderRadius.circular(8), + ), + child: Padding( + padding: const EdgeInsets.all(12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Icon( + cupertino + ? CupertinoIcons.exclamationmark_shield + : Icons.shield_outlined, + size: 16, + color: tint, + ), + const SizedBox(width: 6), + Expanded( + child: Text( + chatRiskReviewLabel, + style: chatCardLabelStyle( + context, + cupertino, + )?.copyWith(color: tint), + ), + ), + ], + ), + const SizedBox(height: 4), + Text(card.risk, style: chatCardBodyStyle(context, cupertino)), + ], + ), + ), + ); + } + + Widget _controls(BuildContext context, bool cupertino) { + final always = card.alwaysLabel; + if (cupertino) { + return Wrap( + spacing: 8, + runSpacing: 8, + children: [ + CupertinoButton.filled( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), + onPressed: () => onDecision(chatDecisionOnce), + child: const Text(chatApprovalOnceLabel), + ), + CupertinoButton( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), + onPressed: () => onDecision(chatDecisionAlways), + child: Text(always), + ), + CupertinoButton( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), + onPressed: () => onDecision(chatDecisionReject), + child: Text( + chatApprovalRejectLabel, + style: TextStyle( + color: CupertinoColors.systemRed.resolveFrom(context), + ), + ), + ), + ], + ); + } + return Wrap( + spacing: 8, + runSpacing: 8, + children: [ + FilledButton( + onPressed: () => onDecision(chatDecisionOnce), + child: const Text(chatApprovalOnceLabel), + ), + TextButton( + onPressed: () => onDecision(chatDecisionAlways), + child: Text(always), + ), + TextButton( + onPressed: () => onDecision(chatDecisionReject), + style: TextButton.styleFrom( + foregroundColor: Theme.of(context).colorScheme.error, + ), + child: const Text(chatApprovalRejectLabel), + ), + ], + ); + } + + Widget _material(BuildContext context) => Card( + // Consecutive cards must read as separate surfaces; the row itself adds only + // the horizontal inset. + margin: const EdgeInsets.only(bottom: 12), + child: Padding( + padding: const EdgeInsets.all(16), + child: _body(context, cupertino: false), + ), + ); + + Widget _cupertino(BuildContext context) => CupertinoListSection.insetGrouped( + children: [ + Padding( + padding: const EdgeInsets.all(16), + child: _body(context, cupertino: true), + ), + ], + ); +} diff --git a/app/lib/features/chat/conversation/chat_permission_card_model.dart b/app/lib/features/chat/conversation/chat_permission_card_model.dart new file mode 100644 index 00000000..3eeb73a5 --- /dev/null +++ b/app/lib/features/chat/conversation/chat_permission_card_model.dart @@ -0,0 +1,186 @@ +/// Permission approval cards: the model behind one `chat_permission` frame. +/// +/// The web's `approvalCard`/`permissionRiskText`/`decisionLabel` are the target. +/// A card is derived from the server frame plus the operator's local answer, so +/// a server resolution always outranks a stale local decision. +library; + +import '../../../core/api_gateway.dart'; + +const chatDecisionOnce = 'once'; +const chatDecisionAlways = 'always'; +const chatDecisionReject = 'reject'; +const chatDecisions = [ + chatDecisionOnce, + chatDecisionAlways, + chatDecisionReject, +]; + +const chatApprovalBlankAction = 'tool call'; +const chatApprovalHeadlineResolved = 'Already resolved'; +const chatApprovalStatusPending = 'Waiting for your response'; +const chatApprovalStatusAnswered = 'Waiting for the agent to continue…'; +const chatApprovalStatusResolved = + 'Another client already answered this request.'; +const chatRiskReviewLabel = 'RISK REVIEW'; +const chatApprovalOnceLabel = 'Allow once'; +const chatApprovalAlwaysLabel = 'Always allow'; +const chatApprovalRejectLabel = 'Reject'; +const chatApprovalMaxResourceLines = 6; + +/// How one approval request stands. `stale` is a server-resolved request whose +/// recorded decision is blank: the card can say only that it is already over. +enum ChatPermissionState { pending, answered, resolved, stale } + +String chatDecisionLabel(String decision) => switch (decision) { + chatDecisionOnce => 'Allowed once', + chatDecisionAlways => 'Always allowed', + chatDecisionReject => 'Rejected', + _ => 'Resolved', +}; + +/// The amber risk sentence. The server's own summary wins; otherwise name the +/// action so the panel is never blank. +String chatPermissionRiskText(JsonMap permission) { + final message = _text(permission['message']); + if (message.isNotEmpty) return message; + final action = _text(permission['action']); + final what = action.isEmpty ? 'a tool call' : action; + return 'The agent is asking to run $what; review the request before allowing.'; +} + +/// The request's non-blank resources, in the server's own order. +/// +/// A resource's recorded text is kept verbatim: the web filters blanks but never +/// trims, so an indented command or YAML block keeps its indentation in both the +/// six-line view and the expanded request. +List chatPermissionResources(JsonMap permission) { + final resources = permission['resources']; + if (resources is! List) return const []; + return [ + for (final resource in resources) + if (_text(resource).isNotEmpty) '${resource ?? ''}', + ]; +} + +/// The resource block capped at six lines, an embedded newline counting as a +/// line. The full list stays available on the card for expansion. +String chatPermissionResourceText(JsonMap permission) { + final lines = [ + for (final resource in chatPermissionResources(permission)) + ...resource.split('\n'), + ]; + if (lines.length <= chatApprovalMaxResourceLines) return lines.join('\n'); + final kept = lines.take(chatApprovalMaxResourceLines).toList(); + kept[kept.length - 1] = '${kept.last}…'; + return kept.join('\n'); +} + +/// One rendered request. [resources] keeps every recorded entry; [resourceText] +/// is only the six-line view. +class ChatPermissionCardData { + const ChatPermissionCardData({ + required this.requestId, + required this.resources, + required this.resourceText, + required this.risk, + required this.state, + required this.decision, + required this.note, + required this.alwaysLabel, + required this.headline, + required this.statusLine, + }); + + final String requestId; + final List resources; + final String resourceText; + final String risk; + final ChatPermissionState state; + final String decision; + final String note; + final String alwaysLabel; + final String headline; + final String statusLine; + + bool get actionable => state == ChatPermissionState.pending; + bool get showRisk => + state == ChatPermissionState.pending || + (state == ChatPermissionState.answered && decision == chatDecisionReject); +} + +/// The card for [permission], or null when there is no request to show. +ChatPermissionCardData? chatPermissionCard( + JsonMap? permission, [ + String answer = '', +]) { + if (permission == null) return null; + final requestId = _text(permission['request_id']); + if (requestId.isEmpty) return null; + final resolvedByServer = + permission['resolved'] == true || + _text(permission['decision']).isNotEmpty; + final answerText = answer.trim(); + final state = resolvedByServer + ? (_text(permission['decision']).isEmpty + ? ChatPermissionState.stale + : ChatPermissionState.resolved) + : answerText.isNotEmpty + ? ChatPermissionState.answered + : ChatPermissionState.pending; + final decision = resolvedByServer + ? _text(permission['decision']) + : answerText; + final note = resolvedByServer ? _text(permission['message']) : ''; + final action = _text(permission['action']); + final alwaysLabel = _text(permission['always_label']); + final headline = switch (state) { + ChatPermissionState.pending => + 'Approve ${action.isEmpty ? chatApprovalBlankAction : action}', + ChatPermissionState.answered || ChatPermissionState.resolved => + decision == chatDecisionAlways && alwaysLabel == 'Allow for session' + ? 'Allowed for session' + : chatDecisionLabel(decision), + ChatPermissionState.stale => chatApprovalHeadlineResolved, + }; + final statusLine = switch (state) { + ChatPermissionState.pending => chatApprovalStatusPending, + ChatPermissionState.answered => chatApprovalStatusAnswered, + ChatPermissionState.resolved || ChatPermissionState.stale => + note.isEmpty ? chatApprovalStatusResolved : note, + }; + return ChatPermissionCardData( + requestId: requestId, + resources: chatPermissionResources(permission), + resourceText: chatPermissionResourceText(permission), + risk: chatPermissionRiskText(permission), + state: state, + decision: decision, + note: note, + alwaysLabel: alwaysLabel.isEmpty ? chatApprovalAlwaysLabel : alwaysLabel, + headline: headline, + statusLine: statusLine, + ); +} + +/// A stable id for one confirmed reply. The id never changes across a retry of +/// the same request and decision, so the send gate can recognise a double tap. +String chatPermissionReplyId(String requestId, String decision) => + 'chat-reply:${requestId.trim()}:${decision.trim()}'; + +/// A one-shot gate for confirmed actions. [start] returns false while the same +/// stable id is already in flight or already accepted; [release] reopens an id +/// after a refused send so the operator can retry it. +class ChatActionGate { + final Set _started = {}; + + bool start(String id) => _started.add(id); + + void release(String id) => _started.remove(id); + + bool isStarted(String id) => _started.contains(id); + + void clear() => _started.clear(); +} + +String _text(Object? value) => '${value ?? ''}'.trim(); diff --git a/app/lib/features/chat/conversation/chat_question_card.dart b/app/lib/features/chat/conversation/chat_question_card.dart new file mode 100644 index 00000000..82a77379 --- /dev/null +++ b/app/lib/features/chat/conversation/chat_question_card.dart @@ -0,0 +1,230 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../core/api_gateway.dart'; +import '../ui/sessions/chat_adaptive.dart'; +import 'chat_card_styles.dart'; +import 'chat_question_card_controls.dart'; +import 'chat_question_card_fields.dart'; +import 'chat_question_card_model.dart'; +import 'chat_question_recorded_answers.dart'; +import 'chat_question_validation.dart'; + +/// One recorded agent question as a native card. +/// +/// A pending question keeps the operator's choices locally until Send answer; +/// the answer map is field-keyed, exactly as `chat_answer` expects. Resolved +/// and expired questions show the recorded answers read-only. +class ChatQuestionCard extends StatefulWidget { + const ChatQuestionCard({ + super.key, + required this.form, + required this.onSubmit, + this.error, + }); + + final JsonMap form; + final Future Function(Map answers, String action) + onSubmit; + final String? error; + + @override + State createState() => _ChatQuestionCardState(); +} + +class _ChatQuestionCardState extends State { + late final List _fields = chatFormFields(widget.form); + late final Map _answers = _initialAnswers(); + final Map _controllers = {}; + String _localError = ''; + bool _sending = false; + + bool get _pending => chatFormPending(widget.form); + + Map _initialAnswers() { + final recorded = widget.form['answers']; + final answers = recorded is Map + ? Map.from(recorded) + : {}; + for (final field in _fields) { + final key = '${field['key'] ?? ''}'.trim(); + if (key.isEmpty || answers.containsKey(key)) continue; + if (field['default'] != null) answers[key] = field['default']; + } + return answers; + } + + @override + void initState() { + super.initState(); + for (final field in _fields) { + if (!chatQuestionFieldNeedsInput(field)) continue; + final key = '${field['key'] ?? ''}'.trim(); + if (key.isEmpty) continue; + final value = _answers[key]; + final options = chatQuestionOptions( + field, + ).map(chatQuestionOptionValue).toSet(); + final custom = value is List + ? value.where((entry) => !options.contains('$entry')).join(', ') + : (value is String && !options.contains(value) ? value : ''); + final controller = TextEditingController(text: custom); + _controllers[key] = controller; + } + } + + @override + void dispose() { + for (final controller in _controllers.values) { + controller.dispose(); + } + super.dispose(); + } + + void _changed(String key, Object? value) { + setState(() { + if (value == null) { + _answers.remove(key); + } else { + _answers[key] = value; + } + _localError = ''; + }); + } + + Future _submit() async { + if (_sending || !_pending) return; + final reason = chatFormAnswerError(_fields, _answers); + if (reason.isNotEmpty) { + setState(() => _localError = reason); + return; + } + setState(() { + _sending = true; + _localError = ''; + }); + final accept = + widget.form['actions'] is List && + (widget.form['actions'] as List).contains('accept'); + await widget.onSubmit( + chatVisibleFormAnswers(_fields, _answers), + accept ? 'accept' : '', + ); + if (mounted) setState(() => _sending = false); + } + + Future _action(String action) async { + if (_sending || !_pending) return; + setState(() { + _sending = true; + _localError = ''; + }); + await widget.onSubmit(const {}, action); + if (mounted) setState(() => _sending = false); + } + + @override + Widget build(BuildContext context) { + final cupertino = + chatControlsStyleOf(context) == ChatControlsStyle.cupertino; + final body = _body(context, cupertino); + final wrapped = cupertino + ? DefaultTextStyle.merge( + style: CupertinoTheme.of(context).textTheme.textStyle, + child: body, + ) + : body; + if (cupertino) { + return CupertinoListSection.insetGrouped( + children: [Padding(padding: const EdgeInsets.all(16), child: wrapped)], + ); + } + return Card( + // Keep consecutive cards visually separate; the transcript row only + // supplies the horizontal inset. + margin: const EdgeInsets.only(bottom: 12), + child: Padding(padding: const EdgeInsets.all(16), child: wrapped), + ); + } + + Widget _body(BuildContext context, bool cupertino) { + final actions = widget.form['actions']; + final error = widget.error?.trim().isNotEmpty == true + ? widget.error!.trim() + : _localError; + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text( + '${widget.form['title'] ?? ''}'.trim().isEmpty + ? 'Question' + : '${widget.form['title']}'.trim(), + style: chatCardTitleStyle(context, cupertino), + ), + Text( + _statusLine(), + style: chatCardSecondaryStyle(context, cupertino), + ), + if (error.isNotEmpty) + Padding( + padding: const EdgeInsets.only(top: 8), + child: Semantics( + liveRegion: true, + child: Text( + error, + style: chatCardBodyStyle( + context, + cupertino, + )?.copyWith(color: chatCardErrorColor(context, cupertino)), + ), + ), + ), + if (_pending) + ...chatQuestionFieldWidgets( + context: context, + fields: _fields, + answers: _answers, + cupertino: cupertino, + controllers: _controllers, + onChanged: _changed, + ) + else + ...chatQuestionRecordedAnswers( + context: context, + form: widget.form, + cupertino: cupertino, + ), + if (_pending) ...[ + const SizedBox(height: 12), + chatQuestionControls( + context: context, + cupertino: cupertino, + actions: actions, + submitLabel: _submitLabel, + sending: _sending, + onSubmit: _submit, + onAction: _action, + ), + ], + ], + ); + } + + String _statusLine() { + if (_pending) return chatQuestionWaiting; + if (widget.form['cancelled'] == true) return chatQuestionExpired; + final answers = widget.form['answers']; + return answers is Map && answers.isNotEmpty + ? chatQuestionAnswered + : chatQuestionClosed; + } + + String get _submitLabel { + final allExternal = + _fields.isNotEmpty && + _fields.every((field) => '${field['type'] ?? ''}' == 'external'); + return allExternal ? chatQuestionConfirm : chatQuestionSubmit; + } + +} diff --git a/app/lib/features/chat/conversation/chat_question_card_controls.dart b/app/lib/features/chat/conversation/chat_question_card_controls.dart new file mode 100644 index 00000000..874ce839 --- /dev/null +++ b/app/lib/features/chat/conversation/chat_question_card_controls.dart @@ -0,0 +1,65 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +/// Submit and optional decline/cancel controls for a pending question. +/// +/// The web shows `Confirm completion` when every field is external, otherwise +/// `Send answer`, and offers only the actions the form records. The labels are +/// passed in so this file stays layout only. +Widget chatQuestionControls({ + required BuildContext context, + required bool cupertino, + required Object? actions, + required String submitLabel, + required bool sending, + required VoidCallback onSubmit, + required void Function(String action) onAction, +}) { + final canDecline = actions is List && actions.contains('decline'); + final canCancel = actions is List && actions.contains('cancel'); + if (cupertino) { + return Wrap( + spacing: 8, + runSpacing: 8, + children: [ + CupertinoButton.filled( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), + onPressed: sending ? null : onSubmit, + child: Text(sending ? 'Sending…' : submitLabel), + ), + if (canDecline) + CupertinoButton( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), + onPressed: sending ? null : () => onAction('decline'), + child: const Text('Decline'), + ), + if (canCancel) + CupertinoButton( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), + onPressed: sending ? null : () => onAction('cancel'), + child: const Text('Cancel question'), + ), + ], + ); + } + return Wrap( + spacing: 8, + runSpacing: 8, + children: [ + FilledButton( + onPressed: sending ? null : onSubmit, + child: Text(sending ? 'Sending…' : submitLabel), + ), + if (canDecline) + TextButton( + onPressed: sending ? null : () => onAction('decline'), + child: const Text('Decline'), + ), + if (canCancel) + TextButton( + onPressed: sending ? null : () => onAction('cancel'), + child: const Text('Cancel question'), + ), + ], + ); +} diff --git a/app/lib/features/chat/conversation/chat_question_card_fields.dart b/app/lib/features/chat/conversation/chat_question_card_fields.dart new file mode 100644 index 00000000..5577149f --- /dev/null +++ b/app/lib/features/chat/conversation/chat_question_card_fields.dart @@ -0,0 +1,170 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../core/api_gateway.dart'; +import 'chat_card_styles.dart'; +import 'chat_question_card_model.dart'; +import 'chat_question_option_controls.dart'; + +/// A free-text input is part of a field when the form allows an answer outside +/// its option list, or when the field has no options at all. +bool chatQuestionFieldNeedsInput(JsonMap field) => + field['custom'] == true || chatQuestionOptions(field).isEmpty; + +/// The editable controls for one form. [onChanged] receives the protocol value +/// (`false`/`0` preserved), or null when the input was cleared. +List chatQuestionFieldWidgets({ + required BuildContext context, + required List fields, + required Map answers, + required bool cupertino, + required Map controllers, + required void Function(String key, Object? value) onChanged, +}) { + final widgets = []; + for (final field in fields) { + if (!chatFormFieldVisible(field, answers)) continue; + final key = '${field['key'] ?? ''}'.trim(); + if (key.isEmpty) continue; + widgets.add( + _field( + context: context, + field: field, + keyName: key, + answers: answers, + cupertino: cupertino, + controllers: controllers, + onChanged: onChanged, + ), + ); + } + return widgets; +} + +Widget _field({ + required BuildContext context, + required JsonMap field, + required String keyName, + required Map answers, + required bool cupertino, + required Map controllers, + required void Function(String key, Object? value) onChanged, +}) { + final title = '${field['title'] ?? ''}'.trim(); + final description = '${field['description'] ?? ''}'.trim(); + final label = title.isNotEmpty + ? title + : (description.isNotEmpty ? description : keyName); + return Padding( + padding: const EdgeInsets.only(top: 12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + mainAxisSize: MainAxisSize.min, + children: [ + Text(label, style: chatCardLabelStyle(context, cupertino)), + if (description.isNotEmpty && description != title) + Text( + description, + style: chatCardSecondaryStyle(context, cupertino), + ), + if ('${field['type'] ?? ''}' == 'external') + _external(context, field, cupertino) + else if ('${field['type'] ?? ''}' == 'boolean') + chatQuestionBooleanField( + context: context, + field: field, + keyName: keyName, + answers: answers, + cupertino: cupertino, + onChanged: onChanged, + ) + else ...[ + chatQuestionOptionsField( + context: context, + field: field, + keyName: keyName, + answers: answers, + cupertino: cupertino, + onChanged: onChanged, + ), + if (chatQuestionFieldNeedsInput(field)) + _input( + context: context, + field: field, + label: label, + keyName: keyName, + controller: controllers[keyName]!, + cupertino: cupertino, + hasOptions: chatQuestionOptions(field).isNotEmpty, + onChanged: (value) => onChanged( + keyName, + chatQuestionTextValue(field, value, answers), + ), + ), + ], + ], + ), + ); +} + +Widget _input({ + required BuildContext context, + required JsonMap field, + required String label, + required String keyName, + required TextEditingController controller, + required bool cupertino, + required bool hasOptions, + required ValueChanged onChanged, +}) { + final placeholder = '${field['placeholder'] ?? ''}'.trim().isNotEmpty + ? '${field['placeholder']}'.trim() + : (hasOptions ? 'Type another answer' : 'Your answer'); + final secret = field['secret'] == true; + final type = '${field['type'] ?? ''}'; + final format = '${field['format'] ?? ''}'; + final keyboard = type == 'number' || type == 'integer' + ? TextInputType.number + : format == 'email' + ? TextInputType.emailAddress + : format == 'uri' + ? TextInputType.url + : format == 'date' + ? TextInputType.datetime + : TextInputType.text; + // The visual label sits above the input; the same words must also reach the + // input's own semantics node, as the web's `aria-label` does. + final input = cupertino + ? CupertinoTextField( + key: ValueKey('chat-question-input-$keyName'), + controller: controller, + placeholder: placeholder, + obscureText: secret, + keyboardType: keyboard, + padding: const EdgeInsets.all(8), + onChanged: onChanged, + ) + : TextField( + key: ValueKey('chat-question-input-$keyName'), + controller: controller, + obscureText: secret, + keyboardType: keyboard, + decoration: InputDecoration(hintText: placeholder), + onChanged: onChanged, + ); + return Semantics(label: label, child: input); +} + +Widget _external(BuildContext context, JsonMap field, bool cupertino) { + final raw = '${field['url'] ?? ''}'.trim(); + if (!chatExternalUrlIsSafe(raw)) { + return Text( + 'This form has an unsupported external URL.', + style: chatCardBodyStyle( + context, + cupertino, + )?.copyWith(color: chatCardErrorColor(context, cupertino)), + ); + } + return SelectableText(raw); +} diff --git a/app/lib/features/chat/conversation/chat_question_card_model.dart b/app/lib/features/chat/conversation/chat_question_card_model.dart new file mode 100644 index 00000000..d86a527f --- /dev/null +++ b/app/lib/features/chat/conversation/chat_question_card_model.dart @@ -0,0 +1,169 @@ +/// Agent question forms: field visibility, values and option lists. +/// +/// These rules mirror the web's `chatForms.js`. `false` and `0` are valid +/// answers, never "missing". Validation lives in `chat_question_validation.dart` +/// so this file stays a protocol model; option values are kept exactly as +/// recorded because they travel back in `chat_answer`. +library; + +import '../../../core/api_gateway.dart'; + +const chatQuestionWaiting = 'The agent is waiting for your answer.'; +const chatQuestionExpired = 'This question expired.'; +const chatQuestionAnswered = 'Answer recorded.'; +const chatQuestionClosed = 'Question closed.'; +const chatQuestionSubmit = 'Send answer'; +const chatQuestionConfirm = 'Confirm completion'; + +bool chatFormFieldVisible(JsonMap field, Map answers) { + if (field['hidden'] == true) return false; + final when = field['when']; + if (when is! List) return true; + for (final condition in when) { + if (condition is! Map) continue; + final key = _text(condition['key']); + final expected = condition['value']; + final actual = answers[key]; + final matches = actual == expected; + if (_text(condition['op']) == 'neq' ? matches : !matches) return false; + } + return true; +} + +/// A protocol-preserving field value; null means the input was cleared. +/// +/// An integer answer is stored as a Dart `int`, so `"1.0"`/`"1e3"` cannot travel +/// as `1.0`/`1000.0` the way the web's `Number()` never does. +Object? chatFormFieldValue(JsonMap field, String raw) { + if (raw.isEmpty) return null; + final type = _text(field['type']); + switch (type) { + case 'boolean': + return raw == 'true'; + case 'number': + case 'integer': + final parsed = num.tryParse(raw); + if (parsed == null) return double.nan; + final integral = + parsed.isFinite && parsed == parsed.roundToDouble(); + return type == 'integer' && integral ? parsed.toInt() : parsed; + default: + return raw; + } +} + +/// Only visible, non-external, answered fields travel in `chat_answer`. +Map chatVisibleFormAnswers( + List fields, + Map answers, +) { + final result = {}; + for (final field in fields) { + if (!chatFormFieldVisible(field, answers)) continue; + if (_text(field['type']) == 'external') continue; + final key = _text(field['key']); + if (!answers.containsKey(key)) continue; + result[key] = answers[key]; + } + return result; +} + +List chatFormFields(JsonMap form) { + final fields = form['fields']; + if (fields is! List) return const []; + return [ + for (final field in fields) + if (field is Map) Map.from(field), + ]; +} + +/// A free-text edit as the protocol value. A multi-select input edits only the +/// options it already knows plus the comma-separated custom entries, matching +/// the web's question input. +Object? chatQuestionTextValue( + JsonMap field, + String raw, + Map answers, +) { + final key = _text(field['key']); + if (_text(field['type']) != 'multiselect') { + return chatFormFieldValue(field, raw); + } + final known = chatQuestionFieldOptionValues(field); + final selected = answers[key] is List + ? (answers[key] as List).map((entry) => '$entry').where(known.contains) + : const []; + final custom = raw + .split(',') + .map((entry) => entry.trim()) + .where((entry) => entry.isNotEmpty); + return [...selected, ...custom]; +} + +List chatQuestionFieldOptionValues(JsonMap field) => [ + for (final option in chatQuestionOptions(field)) + chatQuestionOptionValue(option), +]; + +/// The field's selectable options. The web skips an option whose recorded value +/// is empty rather than rendering a blank control. +List chatQuestionOptions(JsonMap field) { + final options = field['options']; + if (options is! List) return const []; + final result = []; + for (final option in options) { + if (option is! Map) continue; + final converted = Map.from(option); + if (chatQuestionOptionValue(converted).isEmpty) continue; + result.add(converted); + } + return result; +} + +/// The option's exact recorded value, never trimmed: it is the protocol value +/// sent back in `chat_answer`. +String chatQuestionOptionValue(JsonMap option) => + '${option['value'] ?? option['label'] ?? ''}'; + +String chatQuestionOptionLabel(JsonMap option) { + final label = _text(option['label']); + return label.isEmpty ? chatQuestionOptionValue(option) : label; +} + +bool chatFormPending(JsonMap form) => + form['resolved'] != true && form['cancelled'] != true; + +/// True when an external form URL is one this app can safely show. Mirrors the +/// web's `safeFormURL`: an absolute HTTP(S) URL with a real host and no spaces. +bool chatExternalUrlIsSafe(String raw) { + if (raw.trim() != raw || RegExp(r'\s').hasMatch(raw)) return false; + final uri = Uri.tryParse(raw); + return uri != null && + (uri.scheme == 'http' || uri.scheme == 'https') && + uri.host.isNotEmpty; +} + +/// Fold one `form` frame into the retained forms, keyed by id. A resolved or +/// cancelled update keeps the recorded answers so the card can show them +/// read-only instead of dropping evidence. +Map chatFoldQuestionFrame( + Map current, + JsonMap? form, +) { + if (form == null) return current; + final id = _text(form['id']); + if (id.isEmpty) return current; + final existing = current[id]; + final next = {...current}; + next[id] = existing == null + ? Map.from(form) + : {...existing, ...Map.from(form)}; + return next; +} + +/// A stable id for one confirmed answer action on a form. Reusing the same id +/// across a retry lets the send gate recognise a double tap. +String chatQuestionReplyId(String formId, {String action = ''}) => + 'chat-answer:${formId.trim()}:${action.trim().isEmpty ? 'answer' : action.trim()}'; + +String _text(Object? value) => '${value ?? ''}'.trim(); diff --git a/app/lib/features/chat/conversation/chat_question_option_controls.dart b/app/lib/features/chat/conversation/chat_question_option_controls.dart new file mode 100644 index 00000000..938690c4 --- /dev/null +++ b/app/lib/features/chat/conversation/chat_question_option_controls.dart @@ -0,0 +1,150 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../core/api_gateway.dart'; +import 'chat_card_styles.dart'; +import 'chat_question_card_model.dart'; + +/// Native option controls for one question field. Single-select uses the host's +/// radio/checklist pattern, multi-select toggles choices, and `onChanged` +/// receives the protocol value with `false`/`0` preserved. +Widget chatQuestionOptionsField({ + required BuildContext context, + required JsonMap field, + required String keyName, + required Map answers, + required bool cupertino, + required void Function(String key, Object? value) onChanged, +}) { + final options = chatQuestionOptions(field); + if (options.isEmpty) return const SizedBox.shrink(); + final multi = '${field['type'] ?? ''}' == 'multiselect'; + final value = answers[keyName]; + final selected = multi + ? (value is List ? value.map((entry) => '$entry').toSet() : {}) + : {if (value is String) value}; + if (cupertino) { + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + for (final option in options) + CupertinoButton( + padding: const EdgeInsets.symmetric(vertical: 4), + onPressed: () => onChanged( + keyName, + multi + ? _toggle(selected, chatQuestionOptionValue(option)) + : chatQuestionOptionValue(option), + ), + child: Row( + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(chatQuestionOptionLabel(option)), + if ('${option['description'] ?? ''}'.trim().isNotEmpty) + Text( + '${option['description']}'.trim(), + style: chatCardSecondaryStyle(context, cupertino), + ), + ], + ), + ), + if (selected.contains(chatQuestionOptionValue(option))) + const Icon(CupertinoIcons.checkmark), + ], + ), + ), + ], + ); + } + if (multi) { + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + for (final option in options) + CheckboxListTile( + value: selected.contains(chatQuestionOptionValue(option)), + title: Text(chatQuestionOptionLabel(option)), + subtitle: '${option['description'] ?? ''}'.trim().isEmpty + ? null + : Text('${option['description']}'.trim()), + contentPadding: EdgeInsets.zero, + controlAffinity: ListTileControlAffinity.leading, + onChanged: (on) => onChanged( + keyName, + _toggle(selected, chatQuestionOptionValue(option)), + ), + ), + ], + ); + } + return RadioGroup( + groupValue: value is String ? value : null, + onChanged: (next) => onChanged(keyName, next), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + for (final option in options) + RadioListTile( + value: chatQuestionOptionValue(option), + title: Text(chatQuestionOptionLabel(option)), + subtitle: '${option['description'] ?? ''}'.trim().isEmpty + ? null + : Text('${option['description']}'.trim()), + contentPadding: EdgeInsets.zero, + controlAffinity: ListTileControlAffinity.leading, + ), + ], + ), + ); +} + +/// Yes/No for a boolean field: native checkmarks under Cupertino, the web's +/// explicit "Choose Yes or No" menu under Material. +Widget chatQuestionBooleanField({ + required BuildContext context, + required JsonMap field, + required String keyName, + required Map answers, + required bool cupertino, + required void Function(String key, Object? value) onChanged, +}) { + final value = answers[keyName]; + if (cupertino) { + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + for (final entry in const [('Yes', true), ('No', false)]) + CupertinoButton( + padding: const EdgeInsets.symmetric(vertical: 4), + onPressed: () => onChanged(keyName, entry.$2), + child: Row( + children: [ + Expanded(child: Text(entry.$1)), + if (value == entry.$2) const Icon(CupertinoIcons.checkmark), + ], + ), + ), + ], + ); + } + return DropdownButtonFormField( + initialValue: value is bool ? '$value' : null, + hint: const Text('Choose Yes or No'), + items: const [ + DropdownMenuItem(value: 'true', child: Text('Yes')), + DropdownMenuItem(value: 'false', child: Text('No')), + ], + onChanged: (next) => + onChanged(keyName, chatFormFieldValue(field, next ?? '')), + ); +} + +List _toggle(Set selected, String value) { + final next = {...selected}; + if (!next.add(value)) next.remove(value); + return next.toList(); +} diff --git a/app/lib/features/chat/conversation/chat_question_recorded_answers.dart b/app/lib/features/chat/conversation/chat_question_recorded_answers.dart new file mode 100644 index 00000000..1009ca32 --- /dev/null +++ b/app/lib/features/chat/conversation/chat_question_recorded_answers.dart @@ -0,0 +1,99 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../core/api_gateway.dart'; +import 'chat_card_styles.dart'; +import 'chat_question_card_model.dart'; + +/// Recorded answers, read-only. Every answer key is shown, including ones the +/// form fields no longer describe, so no recorded text is dropped. +List chatQuestionRecordedAnswers({ + required BuildContext context, + required JsonMap form, + required bool cupertino, +}) { + final answers = form['answers'] is Map + ? Map.from(form['answers'] as Map) + : {}; + final shown = {}; + final widgets = []; + for (final field in chatFormFields(form)) { + final key = '${field['key'] ?? ''}'.trim(); + if (key.isEmpty || !answers.containsKey(key)) continue; + shown.add(key); + widgets.add( + _recorded( + context, + _fieldLabel(field, key), + _answerText(field, answers[key]), + cupertino, + ), + ); + } + for (final entry in answers.entries) { + if (shown.contains(entry.key)) continue; + widgets.add( + _recorded( + context, + entry.key, + _answerText(null, entry.value), + cupertino, + ), + ); + } + if (widgets.isEmpty) { + return [ + Text( + 'No answer was recorded.', + style: chatCardSecondaryStyle(context, cupertino), + ), + ]; + } + return widgets; +} + +/// The field's display label, falling back past blank recorded strings the same +/// way the pending field does. +String _fieldLabel(JsonMap field, String key) { + for (final candidate in [field['title'], field['description']]) { + final text = '${candidate ?? ''}'.trim(); + if (text.isNotEmpty) return text; + } + return key; +} + +Widget _recorded( + BuildContext context, + String label, + String value, + bool cupertino, +) => Padding( + padding: const EdgeInsets.only(top: 8), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text(label, style: chatCardLabelStyle(context, cupertino)), + Text(value, style: chatCardBodyStyle(context, cupertino)), + ], + ), +); + +String _answerText(JsonMap? field, Object? value) { + final values = value is List ? value : [value]; + final boolean = field != null && '${field['type'] ?? ''}' == 'boolean'; + return values + .map((entry) { + // The editable control says Yes/No; the recorded view must use the same + // words instead of exposing the raw protocol boolean. + if (boolean && entry is bool) return entry ? 'Yes' : 'No'; + if (field == null) return '${entry ?? ''}'; + for (final option in chatQuestionOptions(field)) { + if ('${entry ?? ''}' == chatQuestionOptionValue(option)) { + return chatQuestionOptionLabel(option); + } + } + return '${entry ?? ''}'; + }) + .join(', '); +} diff --git a/app/lib/features/chat/conversation/chat_question_validation.dart b/app/lib/features/chat/conversation/chat_question_validation.dart new file mode 100644 index 00000000..dc2e12fc --- /dev/null +++ b/app/lib/features/chat/conversation/chat_question_validation.dart @@ -0,0 +1,123 @@ +/// Validation shared by the question card and its tests. +/// +/// These are the web's `formAnswerError` rules plus the browser input +/// constraints the card cannot delegate to Flutter: `pattern`, `format=email`, +/// `format=uri` and `format=date`. The browser's localised `validationMessage` +/// has no portable equivalent, so the fixed English sentences below stand in +/// for it and are documented as an app addition. +library; + +import '../../../core/api_gateway.dart'; +import 'chat_question_card_model.dart'; + +const _patternError = 'does not match the required format'; +const _emailError = 'is not a valid email address'; +const _urlError = 'is not a valid URL'; +const _dateError = 'is not a valid date'; + +/// The web's validation messages, in field order. An empty string is valid. +String chatFormAnswerError(List fields, Map answers) { + for (final field in fields) { + if (!chatFormFieldVisible(field, answers)) continue; + if (_text(field['type']) == 'external') continue; + final key = _text(field['key']); + final value = answers[key]; + final missing = + value == null || value == '' || (value is List && value.isEmpty); + final label = _text(field['title']).isEmpty ? key : _text(field['title']); + if (missing) { + if (field['required'] == true) { + return 'Answer $label before sending.'; + } + continue; + } + final type = _text(field['type']); + if (type == 'number' || type == 'integer') { + final number = value is num ? value : null; + final finite = number != null && number.isFinite; + final integral = + type != 'integer' || + (number != null && number is int) || + (number != null && number == number.roundToDouble()); + if (!finite || !integral) return '$label needs a valid $type.'; + final minimum = field['minimum']; + final maximum = field['maximum']; + if (minimum is num && number < minimum) { + return '$label must be at least $minimum.'; + } + if (maximum is num && number > maximum) { + return '$label must be at most $maximum.'; + } + } + if (type == 'boolean' && value is! bool) { + return '$label needs Yes or No.'; + } + if (value is String) { + final minLength = field['min_length']; + final maxLength = field['max_length']; + if (minLength is num && value.length < minLength) { + return '$label is too short.'; + } + if (maxLength is num && value.length > maxLength) { + return '$label is too long.'; + } + final pattern = _text(field['pattern']); + if (pattern.isNotEmpty && !_matchesPattern(pattern, value)) { + return '$label $_patternError.'; + } + final formatError = _formatError(_text(field['format']), value); + if (formatError.isNotEmpty) return '$label $formatError.'; + } + if (value is List) { + final minItems = field['min_items']; + final maxItems = field['max_items']; + if (minItems is num && value.length < minItems) { + return 'Select at least $minItems choices for $label.'; + } + if (maxItems is num && value.length > maxItems) { + return 'Select at most $maxItems choices for $label.'; + } + } + } + return ''; +} + +/// HTML's `pattern` attribute matches the whole value, not a substring. +bool _matchesPattern(String pattern, String value) { + try { + return RegExp('^(?:$pattern)\$').hasMatch(value); + } catch (_) { + // An unparseable server pattern constrains nothing, exactly as an invalid + // `pattern` attribute is ignored by the browser. + return true; + } +} + +String _formatError(String format, String value) { + switch (format) { + case 'email': + return RegExp(r'^[^@\s]+@[^@\s]+\.[^@\s]+$').hasMatch(value) + ? '' + : _emailError; + case 'uri': + final uri = Uri.tryParse(value); + return uri != null && uri.hasScheme && !RegExp(r'\s').hasMatch(value) + ? '' + : _urlError; + case 'date': + return _isDate(value) ? '' : _dateError; + } + return ''; +} + +bool _isDate(String value) { + final match = RegExp(r'^(\d{4})-(\d{2})-(\d{2})$').firstMatch(value); + if (match == null) return false; + final year = int.parse(match.group(1)!); + final month = int.parse(match.group(2)!); + final day = int.parse(match.group(3)!); + final date = DateTime(year, month, day); + return date.year == year && date.month == month && date.day == day; +} + +String _text(Object? value) => '${value ?? ''}'.trim(); diff --git a/app/lib/features/chat/conversation/chat_thread_cards.dart b/app/lib/features/chat/conversation/chat_thread_cards.dart new file mode 100644 index 00000000..12946988 --- /dev/null +++ b/app/lib/features/chat/conversation/chat_thread_cards.dart @@ -0,0 +1,190 @@ +import '../../../core/api_gateway.dart'; +import '../data/chat_repository.dart'; +import 'chat_permission_card_model.dart'; +import 'chat_question_card_model.dart'; + +/// The open conversation's recorded approval requests and question forms. +/// +/// This is the transcript controller's card collaborator: it owns frame folding, +/// the operator's optimistic answers, server refusals and the one-shot send +/// gates, so the controller itself stays about messages and live turn state. +/// +/// The web drops an approval or form once it is resolved. This app keeps the +/// latest settled cards as read-only evidence, which is an intentional addition; +/// [settledLimit] bounds that history so a long session cannot grow without +/// limit while pending cards are never dropped. +class ChatThreadCards { + ChatThreadCards({ + required this.repository, + required this.sessionId, + required this.notify, + required this.isAlive, + }); + + static const settledLimit = 20; + + final ChatRepository repository; + final String sessionId; + final void Function() notify; + final bool Function() isAlive; + + final List _permissions = []; + final Map _forms = {}; + final Map _answers = {}; + final Map _permissionErrors = {}; + final Map _formErrors = {}; + final ChatActionGate _permissionGate = ChatActionGate(); + final ChatActionGate _questionGate = ChatActionGate(); + + /// Every retained permission request, settled or still open, in server order. + List get permissions => List.unmodifiable(_permissions); + + /// Every retained question form, including answered and expired ones. + List get forms => List.unmodifiable(_forms.values); + + String answerFor(String requestId) => _answers[requestId] ?? ''; + + String? permissionErrorFor(String requestId) => + _permissionErrors[requestId]; + + String? formErrorFor(String formId) => _formErrors[formId]; + + /// Answer one pending approval. The local decision settles the card before + /// the reply lands; a refusal reopens the same request with the server's + /// reason so an unaccepted decision is never shown as accepted. A second tap + /// of the same confirmed action is ignored until it settles. + Future replyPermission(String requestId, String decision) async { + final id = requestId.trim(); + if (id.isEmpty || !chatDecisions.contains(decision)) return; + final frame = _permissionFrame(id); + if (frame == null || frame['resolved'] == true) return; + final replyId = chatPermissionReplyId(id, decision); + if (!_permissionGate.start(replyId)) return; + _answers[id] = decision; + _permissionErrors.remove(id); + notify(); + try { + await repository.replyPermission(sessionId, id, decision); + if (!isAlive()) return; + // A previous refusal's reason no longer describes an accepted reply. + if (_permissionErrors.remove(id) != null) notify(); + } catch (error) { + if (!isAlive()) return; + final current = _permissionFrame(id); + // A server resolution that raced the refusal wins: do not reopen it. + if (current == null || current['resolved'] == true) return; + _answers.remove(id); + _permissionErrors[id] = '$error'; + _permissionGate.release(replyId); + notify(); + } + } + + /// Answer or close a pending question with the web's field-keyed body. A + /// refusal keeps the card open and reports the server's reason. + Future answerQuestion( + String formId, + Map answers, + String action, + ) async { + final id = formId.trim(); + final form = _forms[id]; + if (id.isEmpty || form == null || !chatFormPending(form)) return; + final replyId = chatQuestionReplyId(id, action: action); + if (!_questionGate.start(replyId)) return; + _formErrors.remove(id); + notify(); + try { + await repository.answerForm( + sessionId, + id, + Map.from(answers), + action: action, + ); + if (!isAlive()) return; + _forms[id] = { + ...form, + 'resolved': true, + if (answers.isNotEmpty) + 'answers': Map.from(answers), + }; + _pruneSettledForms(); + notify(); + } catch (error) { + if (!isAlive()) return; + _formErrors[id] = '$error'; + _questionGate.release(replyId); + notify(); + } + } + + /// Fold one pushed `chat_permission` frame. A repeat for the same request + /// replaces the recorded frame (a server resolution then wins over any local + /// answer); a frame for a new request is added after the held cards. + void foldPermission(JsonMap frame) { + final id = '${frame['request_id'] ?? ''}'.trim(); + if (id.isEmpty) return; + final index = _permissions.indexWhere( + (held) => '${held['request_id'] ?? ''}'.trim() == id, + ); + if (index < 0) { + _permissions.add(frame); + } else { + _permissions[index] = frame; + } + if (frame['resolved'] == true) _permissionErrors.remove(id); + _pruneSettledPermissions(); + notify(); + } + + /// Fold one `form` event. A folded update keeps a settled form's recorded + /// answers for the read-only card. + void foldForm(JsonMap form) { + final id = '${form['id'] ?? ''}'.trim(); + if (id.isEmpty) return; + final next = chatFoldQuestionFrame(_forms, form); + if (identical(next, _forms)) return; + _forms + ..clear() + ..addAll(next); + _formErrors.remove(id); + _pruneSettledForms(); + notify(); + } + + JsonMap? _permissionFrame(String requestId) { + for (final frame in _permissions) { + if ('${frame['request_id'] ?? ''}'.trim() == requestId) return frame; + } + return null; + } + + bool _permissionSettled(JsonMap frame) => + frame['resolved'] == true || + '${frame['decision'] ?? ''}'.trim().isNotEmpty; + + void _pruneSettledPermissions() { + final settled = _permissions.where(_permissionSettled).toList(); + final excess = settled.length - settledLimit; + if (excess <= 0) return; + for (final frame in settled.take(excess)) { + _permissions.remove(frame); + final id = '${frame['request_id'] ?? ''}'.trim(); + _answers.remove(id); + _permissionErrors.remove(id); + } + } + + void _pruneSettledForms() { + final settled = [ + for (final entry in _forms.entries) + if (!chatFormPending(entry.value)) entry.key, + ]; + final excess = settled.length - settledLimit; + if (excess <= 0) return; + for (final id in settled.take(excess)) { + _forms.remove(id); + _formErrors.remove(id); + } + } +} diff --git a/app/lib/features/chat/conversation/chat_thread_controller.dart b/app/lib/features/chat/conversation/chat_thread_controller.dart index d5c5b9a1..198b6ca5 100644 --- a/app/lib/features/chat/conversation/chat_thread_controller.dart +++ b/app/lib/features/chat/conversation/chat_thread_controller.dart @@ -5,6 +5,7 @@ import 'package:flutter/foundation.dart'; import '../../../core/api_gateway.dart'; import '../data/chat_repository.dart'; import '../domain/chat_transcript.dart'; +import 'chat_thread_cards.dart'; /// One open conversation's transcript and live turn state. /// @@ -15,6 +16,9 @@ import '../domain/chat_transcript.dart'; /// instead of merging stale state. The server detaches subscriptions when the /// socket closes, so disposal only cancels the local stream (there is no /// `chat_unsubscribe`). +/// +/// Approval requests and question forms are recorded cards rather than +/// messages; [ChatThreadCards] owns their frames, answers and send gates. class ChatThreadController extends ChangeNotifier { ChatThreadController(this.gateway, this.sessionId) { _subscription = gateway.frames.listen(_onFrame); @@ -23,6 +27,12 @@ class ChatThreadController extends ChangeNotifier { final ApiGateway gateway; final String sessionId; late final ChatRepository _repository = ChatRepository(gateway); + late final ChatThreadCards _cards = ChatThreadCards( + repository: _repository, + sessionId: sessionId, + notify: _notify, + isAlive: () => !_disposed, + ); StreamSubscription? _subscription; List _messages = const []; @@ -53,6 +63,30 @@ class ChatThreadController extends ChangeNotifier { bool get subscribed => _subscribed; String? get subscriptionError => _subscriptionError; + /// Every retained permission request, settled or still open, in server order. + List get permissionFrames => _cards.permissions; + + /// Every retained question form, including answered and expired ones. + List get questionForms => _cards.forms; + + String permissionAnswerFor(String requestId) => _cards.answerFor(requestId); + + String? permissionErrorFor(String requestId) => + _cards.permissionErrorFor(requestId); + + String? questionErrorFor(String formId) => _cards.formErrorFor(formId); + + /// Answer one pending approval through the card collaborator. + Future replyPermission(String requestId, String decision) => + _cards.replyPermission(requestId, decision); + + /// Answer or close a pending question through the card collaborator. + Future answerQuestion( + String formId, + Map answers, + String action, + ) => _cards.answerQuestion(formId, answers, action); + /// Subscribes this session, then loads its newest history page. Future load() async { if (_disposed) return; @@ -174,12 +208,26 @@ class ChatThreadController extends ChangeNotifier { void _onFrame(JsonMap envelope) { if (_disposed) return; + if (envelope['type'] == 'chat_permission') { + final permission = envelope['chat_permission']; + if (permission is! Map) return; + final frame = Map.from(permission); + if ('${frame['session_id'] ?? ''}' != sessionId) return; + _cards.foldPermission(frame); + return; + } final body = _eventBody(envelope); if (body == null || body['session_id'] != sessionId) return; if (body['kind'] == 'resync') { unawaited(resync()); return; } + if (body['kind'] == 'form') { + final form = body['form']; + if (form is! Map) return; + _cards.foldForm(Map.from(form)); + return; + } final current = _thread; final next = applyChatEvent(current, body); if (identical(next, current)) return; diff --git a/app/lib/features/chat/conversation/chat_thread_view.dart b/app/lib/features/chat/conversation/chat_thread_view.dart index 03b0b9ff..e44e5394 100644 --- a/app/lib/features/chat/conversation/chat_thread_view.dart +++ b/app/lib/features/chat/conversation/chat_thread_view.dart @@ -13,6 +13,7 @@ import 'chat_composer_controller.dart'; import 'chat_draft_store.dart'; import 'chat_row_keys.dart'; import 'chat_thread_controller.dart'; +import 'chat_transcript_card.dart'; /// One read-only conversation: the controller's transcript in the order the /// server reports it, rendered by the existing [ChatMessageView]. @@ -149,7 +150,18 @@ class _ChatThreadViewState extends State { builder: (context, _) { final cupertino = chatControlsStyleOf(context) == ChatControlsStyle.cupertino; - final rows = transcriptRows(_visibleMessages()); + final cards = chatCardRows( + permissions: _controller.permissionFrames, + forms: _controller.questionForms, + answerFor: _controller.permissionAnswerFor, + permissionErrorFor: _controller.permissionErrorFor, + formErrorFor: _controller.questionErrorFor, + ); + // A pending approval/question means the turn is waiting on the operator, + // not generating, so the transcript indicator and its live region stand + // down; the composer's Stop control still follows `running`. + final awaiting = cards.any(chatCardAwaitingOperator); + final rows = transcriptRows(_visibleMessages(), trailing: cards); // Older pages prepend messages and a live frame can append one, so a // folded assistant turn's first message id is not a stable identity. // ChatRowKeys carries a turn's key forward while it still holds any of @@ -242,12 +254,20 @@ class _ChatThreadViewState extends State { Padding( key: ValueKey(keys[index]), padding: const EdgeInsets.symmetric(horizontal: 16), - child: ChatMessageView( - row: rows[index], - textBuilder: chatMarkdownText, - ), + child: + rows[index]['kind'] == 'permission' || + rows[index]['kind'] == 'question' + ? ChatTranscriptCard( + row: rows[index], + onPermissionDecision: _controller.replyPermission, + onQuestionAnswer: _controller.answerQuestion, + ) + : ChatMessageView( + row: rows[index], + textBuilder: chatMarkdownText, + ), ), - if (_controller.running) + if (_controller.running && !awaiting) Padding( key: const Key('chat-running'), padding: const EdgeInsets.all(16), diff --git a/app/lib/features/chat/conversation/chat_transcript_card.dart b/app/lib/features/chat/conversation/chat_transcript_card.dart new file mode 100644 index 00000000..1a766e27 --- /dev/null +++ b/app/lib/features/chat/conversation/chat_transcript_card.dart @@ -0,0 +1,121 @@ +import 'package:flutter/widgets.dart'; + +import '../../../core/api_gateway.dart'; +import 'chat_permission_card.dart'; +import 'chat_permission_card_model.dart'; +import 'chat_question_card.dart'; +import 'chat_question_card_model.dart'; + +/// Build transcript card rows for recorded permission requests and questions. +/// +/// Cards are not transcript messages: they keep the server's order and follow +/// the message rows. Their keys are the server ids, so a streaming repaint +/// keeps an open disclosure or a half-typed answer attached to the same card. +List chatCardRows({ + required Iterable permissions, + required Iterable forms, + required String Function(String requestId) answerFor, + required String? Function(String requestId) permissionErrorFor, + required String? Function(String formId) formErrorFor, +}) { + final rows = []; + for (final permission in permissions) { + final id = '${permission['request_id'] ?? ''}'.trim(); + if (id.isEmpty) continue; + rows.add({ + 'kind': 'permission', + 'key': 'chat-permission-$id', + 'frame': permission, + 'answer': answerFor(id), + 'error': permissionErrorFor(id), + }); + } + for (final form in forms) { + final id = '${form['id'] ?? ''}'.trim(); + if (id.isEmpty) continue; + rows.add({ + 'kind': 'question', + 'key': 'chat-question-$id', + 'form': form, + 'error': formErrorFor(id), + }); + } + return rows; +} + +/// True while one card still needs the operator: an open approval request or a +/// pending question form. +/// +/// A turn blocked on the operator is not generating, so the transcript's running +/// indicator stands down while this is true (the web does the same); the +/// composer's Stop control remains driven by the turn alone. +bool chatCardAwaitingOperator(JsonMap row) { + final kind = '${row['kind'] ?? ''}'; + if (kind == 'permission') { + final frame = row['frame']; + if (frame is! Map) return false; + final card = chatPermissionCard( + Map.from(frame), + '${row['answer'] ?? ''}', + ); + return card?.actionable == true; + } + if (kind == 'question') { + final form = row['form']; + return form is Map && chatFormPending(Map.from(form)); + } + return false; +} + +/// Small dispatcher: render one card row with the host's native controls. +class ChatTranscriptCard extends StatelessWidget { + const ChatTranscriptCard({ + super.key, + required this.row, + required this.onPermissionDecision, + required this.onQuestionAnswer, + }); + + final JsonMap row; + final Future Function(String requestId, String decision) + onPermissionDecision; + final Future Function( + String formId, + Map answers, + String action, + ) + onQuestionAnswer; + + @override + Widget build(BuildContext context) { + final kind = '${row['kind'] ?? ''}'; + if (kind == 'permission') { + final frame = row['frame'] is Map + ? Map.from(row['frame'] as Map) + : null; + final card = chatPermissionCard(frame, '${row['answer'] ?? ''}'); + if (card == null) return const SizedBox.shrink(); + return ChatPermissionCard( + card: card, + error: row['error'] as String?, + onDecision: (decision) => + onPermissionDecision(card.requestId, decision), + ); + } + if (kind == 'question') { + final form = row['form'] is Map + ? Map.from(row['form'] as Map) + : null; + if (form == null || '${form['id'] ?? ''}'.trim().isEmpty) { + return const SizedBox.shrink(); + } + final id = '${form['id']}'.trim(); + return ChatQuestionCard( + form: form, + error: row['error'] as String?, + onSubmit: (answers, action) => onQuestionAnswer(id, answers, action), + ); + } + return const SizedBox.shrink(); + } +} diff --git a/app/lib/features/chat/domain/chat_transcript.dart b/app/lib/features/chat/domain/chat_transcript.dart index b9f54459..eb6f3bc9 100644 --- a/app/lib/features/chat/domain/chat_transcript.dart +++ b/app/lib/features/chat/domain/chat_transcript.dart @@ -40,7 +40,14 @@ JsonMap mergeChatHistory(JsonMap previous, JsonMap page, {bool older = false}) { /// identity uses `messageIds`. That list carries every message the folded turn /// currently holds so the view can keep the same row element while the turn /// grows at either end. -List transcriptRows(List messages) { +/// +/// [trailing] rows are conversation cards (permission requests and questions), +/// not messages. They keep the server's order after the transcript, the way the +/// web renders approvals and forms at the end of the conversation. +List transcriptRows( + List messages, { + List trailing = const [], +}) { final rows = []; String? key; final ids = []; @@ -73,6 +80,7 @@ List transcriptRows(List messages) { } } flush(); + rows.addAll(trailing); return rows; } diff --git a/app/notes/C4-approvals.md b/app/notes/C4-approvals.md new file mode 100644 index 00000000..c55d9c0d --- /dev/null +++ b/app/notes/C4-approvals.md @@ -0,0 +1,148 @@ +# C4-approvals — native permission and question cards + +One checked integration slice: the chat conversation now renders recorded +`chat_permission` frames and `form` question frames as native Material/Cupertino +cards, answers them through the landed `ChatRepository` request facade, and +records the outcome. App-only; no server, `web/`, Android/iOS, shell, route or +deployment source was edited. + +## What changed + +| File | Lines | Responsibility | +| --- | ---: | --- | +| `lib/features/chat/conversation/chat_permission_card_model.dart` | 192 | approval card derivation, risk/resource wording, decision labels, one-shot reply ids | +| `lib/features/chat/conversation/chat_permission_card.dart` | 267 | native approval card: kind/headline/status, six-line resources with full-request disclosure, risk panel, once/always/reject | +| `lib/features/chat/conversation/chat_question_card_model.dart` | 206 | field visibility/values, web validation messages, visible answers, form folding, answer ids | +| `lib/features/chat/conversation/chat_question_card_fields.dart` | 179 | editable field shell, free-text inputs, external-URL text | +| `lib/features/chat/conversation/chat_question_option_controls.dart` | 160 | native single/multi select and boolean controls | +| `lib/features/chat/conversation/chat_question_recorded_answers.dart` | 99 | read-only recorded answers, including unknown keys | +| `lib/features/chat/conversation/chat_question_card.dart` | 275 | pending/answered/expired question card, local answer state, submit/actions | +| `lib/features/chat/conversation/chat_transcript_card.dart` | 96 | card-row builder and small permission/question dispatcher | +| `lib/features/chat/domain/chat_transcript.dart` | +10/-2 | `transcriptRows(..., trailing:)` keeps cards after the message rows | +| `lib/features/chat/conversation/chat_thread_controller.dart` | +140 | folded permission/form frames, answers, errors and one-shot send gates | +| `lib/features/chat/conversation/chat_thread_view.dart` | +26/-6 | builds/dispatches card rows inside the existing conversation list | +| `app/PARITY.md` | row update | states the native cards as Source, with the real-request smoke still open | +| `test/.../chat_permission_card_test.dart` | 300 | model + native behaviour + pushed-frame integration | +| `test/.../chat_question_card_test.dart` | 360 | field rules + native behaviour + pushed-frame integration | +| `tool/chat_approvals_probe.dart` | 167 | real-widget fixture with a scripted replaying gateway | +| `tool/chat_approvals_probe.mjs` | 335 | Chrome CDP interaction, OCR assertions and captures | + +Production files stay under the ~250-line aim except the two 267/275-line card +shells; the larger question work is split by responsibility (fields, option +controls, recorded answers) rather than arbitrary fragments. + +## Behaviour + +- **Permission card.** Kind line `Permission request · {source.type}` when the + server records one, else `Permission request`. Headline `Approve {action}` + (`Approve tool call` when blank). Status `Waiting for your response`. + Resources are the server's non-blank entries joined by newlines, displayed at + most six lines with an ellipsis on the last kept line; when truncated, the + native disclosure `Show full request` carries every recorded resource. The risk + panel uses the server's `message`, else the web's neutral sentence naming the + action, and shows only while pending or after a rejection. Controls use the + exact `Allow once` / `always_label or Always allow` / `Reject` labels and only + while pending. +- **Permission outcome.** Answering settles the card optimistically to the + decision label and `Waiting for the agent to continue…`. A server + `resolved`/`decision` frame always wins, shows the decision label (or + `Already resolved` when the recorded decision is blank) and its `message`/the + web's fallback note. A refusal clears the optimistic answer, keeps the card + pending, and shows the server reason in a live region. +- **Reply wire.** `ChatRepository.replyPermission` sends exactly + `{chat_reply:{session_id,request_id,decision,client:'Web'}}`; no extra field is + added. Each confirmed action has the stable local id + `chat-reply:{requestId}:{decision}` held by a `ChatActionGate`, so a double tap + sends once and a refused send reopens only that id for retry. +- **Question card.** Shows the recorded title (or `Question`) and + `The agent is waiting for your answer.`. Options keep the server's value/label + and description exactly; single-select is a radio group under Material and a + checkmark row under Cupertino, multi-select is checkboxes/checkmarks, booleans + are the explicit Yes/No menu under Material and checkmark rows under Cupertino. + Free text appears for `custom` fields or fields with no options, with number, + email, URL and date keyboards and secret input where recorded. +- **Question rules.** Visibility honours `hidden` and `when` (`eq`/`neq`). + Answers preserve `false` and `0`. Required missing answers, invalid + number/integer, min/max bounds, boolean type, string length and item counts + produce the web's exact messages; invalid input blocks the send and shows the + reason. Visible, non-external, answered fields alone travel in `chat_answer`. + `accept` is sent when the form lists it; `Decline` / `Cancel question` use the + recorded actions and an empty answer map. +- **Question outcome.** Submit is one-shot through the stable id + `chat-answer:{formId}:{action|answer}`. Success marks the form resolved locally + and shows `Answer recorded.`; the server's resolved/cancelled echo replaces it + with the recorded answers. `cancelled` shows `This question expired.`. + Read-only rendering includes answers for fields no longer present, and says + `No answer was recorded.` when the resolved form recorded none. A refusal keeps + the card pending with its typed state and shows the server reason. +- **Composition.** Cards follow the message rows in server order (permissions + then questions), keyed by request/form id so streaming repaints keep an open + disclosure or half-typed answer. Unknown message parts still render through the + existing plain `Unrecognised part` disclosure; nothing in `ChatMessageView` or + the markdown renderer changed. + +## Checks actually run (after the final split) + +- `flutter analyze` — `No issues found!` +- `flutter test` — `All tests passed!` (1003 tests, including the 20 new focused + card/model/controller cases) +- `flutter build web --output build/web-acceptance` — `✓ Built` +- `node tool/chat_approvals_probe.mjs` for both hosts — see below. + +## Browser fixture evidence + +The fixture runs the **real** `ChatThreadView`/controller against a scripted +gateway that replays one pending `chat_permission` and one `form` question on +subscribe, then echoes the reply/answer back as a resolved frame. Chrome CDP at +320px logical width, device scale 2, dark appearance, both hosts. Static card +text is OCR-verified because Flutter web paints it on the canvas; controls are +driven through semantics. + +Captures and evidence (shared run artifacts): + +- `public/chat-approvals-probe/material-cards.png` +- `public/chat-approvals-probe/material-approval-answered.png` +- `public/chat-approvals-probe/material-question-answered.png` +- `public/chat-approvals-probe/material-evidence.json` +- `public/chat-approvals-probe/cupertino-cards.png` +- `public/chat-approvals-probe/cupertino-approval-answered.png` +- `public/chat-approvals-probe/cupertino-question-answered.png` +- `public/chat-approvals-probe/cupertino-evidence.json` + +Each run asserted the pending card's recorded action, status, risk, resource +lines and all three control labels; that `Allow once` sent the reply (the fixture's +server resolution replaced it with `Allowed once` and cleared the controls); and +that selecting `Red` + `Send answer` sent the answer and produced the read-only +`Answer recorded.` card. Both runs finished with `sendAnswerStillVisible:false` +and `allowOnceStillVisible:false`. The Material capture also shows no clipped +text at 320/2x; the Cupertino capture uses only Cupertino controls (widget tests +assert no `Material` ancestor in that host). + +## Limits, stated plainly + +- **No live server request was answered.** The fixture's gateway is scripted and + its reply/answer responses are local; no operator chat, run, approval or real + server was mutated. +- **No authenticated smoke yet.** The `PARITY.md` row remains Source, not Preview: + a real pending approval/question against the authenticated server, and a + multi-client server resolution, are still unverified. +- **Web only.** Android/iOS builds, ADB, emulators and device/OS behavior were not + run (per the app working agreement); source is portable but mobile is + unverified. +- **External question forms** display only their recorded HTTP(S) URL as + selectable text; no URL launcher dependency exists in this app, so they are not + opened from the card. Unsupported URLs show the web's alert wording instead. +- **Uncommitted.** The pipeline input asked for a candidate commit, but the stage + instructions explicitly say not to commit, push or deploy, so the work is left + in the working tree (`flutter/chat-approvals`) with no commit or merge. + +## Manager completion after a harness transport failure + +The run ended on a harness transport error (`/api/session/active`) after a full +Code visit; the retained tree was complete. Manager verified 173 chat tests, +clean analysis, and the both-host browser probe. Two probe expectations were +corrected against the web rather than against the app: the approval card's +headline is the recorded action (the web has no separate "Permission request" +heading), and OCR merges whitespace, so comparisons now ignore it and accept a +control that is present in the semantics tree. No app behaviour was changed to +make the probe pass. diff --git a/app/test/features/chat/conversation/chat_permission_card_test.dart b/app/test/features/chat/conversation/chat_permission_card_test.dart new file mode 100644 index 00000000..1b7282ff --- /dev/null +++ b/app/test/features/chat/conversation/chat_permission_card_test.dart @@ -0,0 +1,415 @@ +import 'dart:async'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_permission_card.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_permission_card_model.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart'; + +import 'chat_thread_fixtures.dart'; + +Widget materialHost(Widget child) => MaterialApp( + theme: ThemeData(platform: TargetPlatform.android), + home: Scaffold(body: child), +); + +Widget scrollHost(Widget child) => + materialHost(SingleChildScrollView(child: child)); + +Widget cupertinoHost(Widget child) => CupertinoApp( + theme: const CupertinoThemeData(brightness: Brightness.dark), + home: CupertinoPageScaffold( + child: SingleChildScrollView( + padding: const EdgeInsets.all(16), + child: child, + ), + ), +); + +JsonMap permission({ + String id = 'req-1', + String action = 'bash', + List resources = const [ + 'command: rm -rf build', + 'cwd: /workspace/demo', + ], + String message = 'This deletes the build output.', + bool resolved = false, + String decision = '', +}) => { + 'session_id': 's', + 'request_id': id, + 'action': action, + 'resources': resources, + 'message': message, + 'source': {'type': 'tool'}, + 'resolved': resolved, + if (decision.isNotEmpty) 'decision': decision, +}; + +void main() { + test('recorded action, risk and options survive the card model', () { + final card = chatPermissionCard(permission(), '')!; + expect(card.headline, 'Approve bash'); + expect(card.statusLine, chatApprovalStatusPending); + expect(card.risk, 'This deletes the build output.'); + expect(card.resources, ['command: rm -rf build', 'cwd: /workspace/demo']); + expect(card.alwaysLabel, 'Always allow'); + expect(card.actionable, isTrue); + expect(card.showRisk, isTrue); + }); + + test('resources keep their recorded indentation and order', () { + final card = chatPermissionCard( + permission( + resources: const [ + ' cd /workspace/demo', + 'command: |\n echo hello', + ' ', + ], + ), + '', + )!; + expect(card.resources, [ + ' cd /workspace/demo', + 'command: |\n echo hello', + ]); + expect( + card.resourceText, + ' cd /workspace/demo\ncommand: |\n echo hello', + ); + }); + + test('risk falls back to the action and resources cap at six lines', () { + final card = chatPermissionCard( + permission( + message: '', + resources: const [ + 'one', + 'two\nthree', + 'four', + 'five', + 'six', + 'seven', + 'eight', + ], + ), + '', + )!; + expect( + card.risk, + 'The agent is asking to run bash; review the request before allowing.', + ); + expect(card.resourceText.split('\n'), hasLength(6)); + expect(card.resourceText.endsWith('…'), isTrue); + expect(card.resources, hasLength(7)); + }); + + test('a server resolution outranks a local answer and a blank decision is ' + 'stale', () { + final resolved = chatPermissionCard( + permission( + resolved: true, + decision: 'always', + message: 'Another client already allowed this.', + ), + 'once', + )!; + expect(resolved.state, ChatPermissionState.resolved); + expect(resolved.headline, 'Always allowed'); + expect(resolved.statusLine, 'Another client already allowed this.'); + expect(resolved.actionable, isFalse); + expect(resolved.showRisk, isFalse); + + final stale = chatPermissionCard( + permission(resolved: true, message: ''), + '', + )!; + expect(stale.state, ChatPermissionState.stale); + expect(stale.headline, 'Already resolved'); + expect(stale.statusLine, chatApprovalStatusResolved); + expect(stale.actionable, isFalse); + }); + + test('a rejection keeps the risk panel while answered', () { + final rejected = chatPermissionCard(permission(), 'reject')!; + expect(rejected.state, ChatPermissionState.answered); + expect(rejected.headline, 'Rejected'); + expect(rejected.statusLine, chatApprovalStatusAnswered); + expect(rejected.showRisk, isTrue); + expect(rejected.actionable, isFalse); + }); + + test('one stable reply id per confirmed action', () { + expect( + chatPermissionReplyId('req-1', 'once'), + chatPermissionReplyId('req-1', 'once'), + ); + expect( + chatPermissionReplyId('req-1', 'once'), + isNot(chatPermissionReplyId('req-1', 'always')), + ); + final gate = ChatActionGate(); + final id = chatPermissionReplyId('req-1', 'once'); + expect(gate.start(id), isTrue); + expect(gate.start(id), isFalse); + gate.release(id); + expect(gate.start(id), isTrue); + }); + + testWidgets('a pending approval renders native Material controls', ( + tester, + ) async { + final decisions = []; + final card = chatPermissionCard(permission(), '')!; + await tester.pumpWidget( + scrollHost( + ChatPermissionCard( + card: card, + onDecision: (value) async { + decisions.add(value); + }, + ), + ), + ); + expect(find.text('Approve bash'), findsOneWidget); + expect(find.text('Waiting for your response'), findsOneWidget); + expect(find.text('RISK REVIEW'), findsOneWidget); + expect(find.text('This deletes the build output.'), findsOneWidget); + expect(find.text('Allow once'), findsOneWidget); + expect(find.text('Always allow'), findsOneWidget); + expect(find.text('Reject'), findsOneWidget); + expect(find.text('Permission request · tool'), findsNothing); + + await tester.tap(find.text('Allow once')); + await tester.pump(); + expect(decisions, ['once']); + }); + + testWidgets('Show full request expands to every recorded resource line', ( + tester, + ) async { + final card = chatPermissionCard( + permission( + resources: const [ + ' one', + 'two', + 'three', + 'four', + 'five', + 'six', + 'seven', + ], + ), + '', + )!; + await tester.pumpWidget( + scrollHost(ChatPermissionCard(card: card, onDecision: (_) async {})), + ); + expect(find.text(' one'), findsNothing); + await tester.tap(find.text('Show full request')); + await tester.pumpAndSettle(); + expect(find.text(card.resources.join('\n')), findsOneWidget); + }); + + testWidgets('320px at 2x in dark Cupertino keeps the card native and ' + 'readable', (tester) async { + tester.view.physicalSize = const Size(640, 1400); + tester.view.devicePixelRatio = 2; + tester.platformDispatcher.textScaleFactorTestValue = 2; + tester.platformDispatcher.platformBrightnessTestValue = Brightness.dark; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue); + addTearDown(tester.platformDispatcher.clearPlatformBrightnessTestValue); + + final card = chatPermissionCard( + permission( + action: 'a very long tool name that has to wrap at twice the text size', + resources: const [ + 'a long resource line that wraps instead of clipping any words at all', + ], + ), + '', + )!; + await tester.pumpWidget( + cupertinoHost(ChatPermissionCard(card: card, onDecision: (_) async {})), + ); + expect(tester.takeException(), isNull); + expect(find.text('Allow once'), findsOneWidget); + expect(find.byType(Material), findsNothing); + }); + + testWidgets('a pushed chat_permission renders, sends the recorded reply, ' + 'and a second tap sends once', (tester) async { + final gateway = FakeChatGateway(); + addTearDown(gateway.close); + gateway.history = (_) async => chatPage(const []); + final held = Completer(); + gateway.reply = (_) => held.future; + + await tester.pumpWidget( + materialHost( + ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {}), + ), + ); + await tester.pumpAndSettle(); + gateway.emitRaw({ + 'type': 'chat_permission', + 'chat_permission': permission(), + }); + await tester.pumpAndSettle(); + + expect(find.text('Approve bash'), findsOneWidget); + await tester.tap(find.text('Allow once')); + await tester.tap(find.text('Allow once')); + await tester.pump(); + + final replies = gateway.calls.where((call) => call.type == 'chat_reply'); + expect(replies, hasLength(1)); + expect(replies.single.fields, { + 'chat_reply': { + 'session_id': 's', + 'request_id': 'req-1', + 'decision': 'once', + 'client': 'Web', + }, + }); + expect(find.text('Allowed once'), findsOneWidget); + expect(find.text('Waiting for the agent to continue…'), findsOneWidget); + held.complete(const {}); + await tester.pumpAndSettle(); + }); + + testWidgets('a refused reply keeps the card pending and shows the server ' + 'reason', (tester) async { + final gateway = FakeChatGateway(); + addTearDown(gateway.close); + gateway.history = (_) async => chatPage(const []); + gateway.reply = (_) async => throw StateError('request expired'); + + await tester.pumpWidget( + materialHost( + ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {}), + ), + ); + await tester.pumpAndSettle(); + gateway.emitRaw({ + 'type': 'chat_permission', + 'chat_permission': permission(), + }); + await tester.pumpAndSettle(); + + await tester.tap(find.text('Reject')); + await tester.pumpAndSettle(); + + expect(find.textContaining('request expired'), findsOneWidget); + expect(find.text('Approve bash'), findsOneWidget); + expect(find.text('Allow once'), findsOneWidget); + expect(find.text('Reject'), findsOneWidget); + }); + + testWidgets('a server resolution clears the controls and shows the recorded ' + 'decision', (tester) async { + final gateway = FakeChatGateway(); + addTearDown(gateway.close); + gateway.history = (_) async => chatPage(const []); + + await tester.pumpWidget( + materialHost( + ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {}), + ), + ); + await tester.pumpAndSettle(); + gateway.emitRaw({ + 'type': 'chat_permission', + 'chat_permission': permission(), + }); + await tester.pumpAndSettle(); + expect(find.text('Allow once'), findsOneWidget); + + gateway.emitRaw({ + 'type': 'chat_permission', + 'chat_permission': permission( + resolved: true, + decision: 'once', + message: 'Another device allowed once.', + ), + }); + await tester.pumpAndSettle(); + expect(find.text('Allowed once'), findsOneWidget); + expect(find.text('Another device allowed once.'), findsOneWidget); + expect(find.text('Allow once'), findsNothing); + }); + + testWidgets('a turn waiting on a pending card hides the running indicator ' + 'but keeps Stop', (tester) async { + final gateway = FakeChatGateway(); + addTearDown(gateway.close); + gateway.history = (_) async => chatPage(const []); + + await tester.pumpWidget( + materialHost( + ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {}), + ), + ); + await tester.pumpAndSettle(); + gateway.emitRaw({ + 'type': 'chat_permission', + 'chat_permission': permission(), + }); + gateway.emitEvent(chatStepFrame('running')); + await tester.pumpAndSettle(); + + expect(find.text('Approve bash'), findsOneWidget); + expect(find.text('Assistant is responding…'), findsNothing); + expect(find.text('Stop'), findsOneWidget); + + gateway.emitRaw({ + 'type': 'chat_permission', + 'chat_permission': permission(resolved: true, decision: 'once'), + }); + await tester.pumpAndSettle(); + + expect(find.text('Assistant is responding…'), findsOneWidget); + expect(find.text('Stop'), findsOneWidget); + }); + + testWidgets('consecutive Material cards stay separate surfaces', ( + tester, + ) async { + final gateway = FakeChatGateway(); + addTearDown(gateway.close); + gateway.history = (_) async => chatPage(const []); + + await tester.pumpWidget( + materialHost( + ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {}), + ), + ); + await tester.pumpAndSettle(); + gateway.emitRaw({ + 'type': 'chat_permission', + 'chat_permission': permission(id: 'req-1'), + }); + gateway.emitRaw({ + 'type': 'chat_permission', + 'chat_permission': permission(id: 'req-2', action: 'python'), + }); + await tester.pumpAndSettle(); + + final first = tester.getRect( + find + .descendant(of: find.byType(Card).at(0), matching: find.byType(Material)) + .first, + ); + final second = tester.getRect( + find + .descendant(of: find.byType(Card).at(1), matching: find.byType(Material)) + .first, + ); + expect(second.top - first.bottom, greaterThanOrEqualTo(12)); + }); +} diff --git a/app/test/features/chat/conversation/chat_question_card_model_test.dart b/app/test/features/chat/conversation/chat_question_card_model_test.dart new file mode 100644 index 00000000..a84680bf --- /dev/null +++ b/app/test/features/chat/conversation/chat_question_card_model_test.dart @@ -0,0 +1,159 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_question_card_model.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_question_validation.dart'; + +void main() { + test('field visibility keeps false and zero as answers', () { + final fields = [ + {'key': 'enabled', 'type': 'boolean'}, + { + 'key': 'count', + 'type': 'integer', + 'when': [ + {'key': 'enabled', 'op': 'eq', 'value': true}, + ], + }, + ]; + final hidden = {'enabled': false, 'count': 0}; + expect(chatFormFieldVisible(fields[1], hidden), isFalse); + expect(chatFormAnswerError(fields, hidden), ''); + expect(chatVisibleFormAnswers(fields, hidden), {'enabled': false}); + }); + + test('required free text and numeric bounds use the web wording', () { + final fields = [ + {'key': 'note', 'title': 'Notes', 'type': 'string', 'required': true}, + {'key': 'count', 'type': 'integer', 'minimum': 1, 'maximum': 5}, + ]; + expect( + chatFormAnswerError(fields, {'count': 2}), + 'Answer Notes before sending.', + ); + expect( + chatFormAnswerError(fields, {'note': 'ok', 'count': 1.5}), + 'count needs a valid integer.', + ); + expect( + chatFormAnswerError(fields, {'note': 'ok', 'count': 6}), + 'count must be at most 5.', + ); + expect( + chatFormAnswerError(fields, {'note': 'ok', 'count': 0}), + 'count must be at least 1.', + ); + expect(chatFormAnswerError(fields, {'note': 'ok', 'count': 5}), ''); + }); + + test('integer input becomes an int, including decimal and exponent forms', () { + final field = {'key': 'count', 'type': 'integer'}; + expect(chatFormFieldValue(field, '1.0'), isA()); + expect(chatFormFieldValue(field, '1.0'), 1); + expect(chatFormFieldValue(field, '1e3'), 1000); + expect(chatFormFieldValue(field, '1.5'), 1.5); + expect((chatFormFieldValue(field, 'nope')! as num).isNaN, isTrue); + expect(chatFormFieldValue({'type': 'number'}, '1e3'), 1000.0); + + final fields = [field]; + expect( + chatVisibleFormAnswers( + fields, + {'count': chatFormFieldValue(field, '1.0')}, + ), + {'count': 1}, + ); + expect( + chatFormAnswerError(fields, {'count': chatFormFieldValue(field, '1.0')}), + '', + ); + }); + + test('a malformed pattern is reported with the documented wording', () { + final fields = [ + { + 'key': 'code', + 'title': 'Code', + 'type': 'string', + 'pattern': r'^[a-z]+$', + }, + ]; + expect(chatFormAnswerError(fields, {'code': 'abc'}), ''); + expect( + chatFormAnswerError(fields, {'code': 'ABC'}), + 'Code does not match the required format.', + ); + // An unparseable server pattern constrains nothing, like a browser ignoring + // an invalid `pattern` attribute. + expect( + chatFormAnswerError([ + {'key': 'code', 'type': 'string', 'pattern': '('}, + ], {'code': 'anything'}), + '', + ); + }); + + test('email, URL and date formats are checked like native inputs', () { + final fields = [ + {'key': 'mail', 'title': 'Email', 'type': 'string', 'format': 'email'}, + {'key': 'site', 'title': 'Site', 'type': 'string', 'format': 'uri'}, + {'key': 'day', 'title': 'Day', 'type': 'string', 'format': 'date'}, + ]; + expect(chatFormAnswerError(fields, {'mail': 'a@b.co'}), ''); + expect( + chatFormAnswerError(fields, { + 'mail': 'not-a-mail', + 'site': 'https://example.com', + 'day': '2026-10-22', + }), + 'Email is not a valid email address.', + ); + expect( + chatFormAnswerError(fields, { + 'mail': 'a@b.co', + 'site': 'exa mple', + 'day': '2026-10-22', + }), + 'Site is not a valid URL.', + ); + expect( + chatFormAnswerError(fields, { + 'mail': 'a@b.co', + 'site': 'https://example.com', + 'day': '2026-02-31', + }), + 'Day is not a valid date.', + ); + expect( + chatFormAnswerError(fields, { + 'mail': 'a@b.co', + 'site': 'https://example.com', + 'day': '2026-10-22', + }), + '', + ); + }); + + test('options with an empty recorded value are skipped', () { + final field = { + 'key': 'choice', + 'options': [ + {'value': '', 'label': 'Blank'}, + {'value': 'red', 'label': 'Red'}, + {'label': 'Blue'}, + ], + }; + expect(chatQuestionOptions(field).map(chatQuestionOptionValue), [ + 'red', + 'Blue', + ]); + expect(chatQuestionFieldOptionValues(field), ['red', 'Blue']); + }); + + test('external URLs require an absolute HTTP(S) URL with a host', () { + expect(chatExternalUrlIsSafe('https://example.com/form'), isTrue); + expect(chatExternalUrlIsSafe('http://example.com'), isTrue); + expect(chatExternalUrlIsSafe('http://'), isFalse); + expect(chatExternalUrlIsSafe('http://exa mple.com'), isFalse); + expect(chatExternalUrlIsSafe('ftp://example.com'), isFalse); + expect(chatExternalUrlIsSafe('not a url'), isFalse); + }); +} diff --git a/app/test/features/chat/conversation/chat_question_card_test.dart b/app/test/features/chat/conversation/chat_question_card_test.dart new file mode 100644 index 00000000..670116c2 --- /dev/null +++ b/app/test/features/chat/conversation/chat_question_card_test.dart @@ -0,0 +1,545 @@ +import 'dart:async'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_question_card.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_question_card_model.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_question_validation.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart'; + +import 'chat_thread_fixtures.dart'; + +Widget materialHost(Widget child) => MaterialApp( + theme: ThemeData(platform: TargetPlatform.android), + home: Scaffold(body: child), +); + +Widget scrollHost(Widget child) => + materialHost(SingleChildScrollView(child: child)); + +Widget cupertinoHost(Widget child) => CupertinoApp( + theme: const CupertinoThemeData(brightness: Brightness.dark), + home: CupertinoPageScaffold( + child: SingleChildScrollView( + padding: const EdgeInsets.all(16), + child: child, + ), + ), +); + +List fields() => [ + { + 'key': 'colour', + 'title': 'Colour', + 'type': 'string', + 'required': true, + 'options': [ + {'value': 'red', 'label': 'Red'}, + {'value': 'blue', 'label': 'Blue'}, + ], + }, + { + 'key': 'extras', + 'title': 'Extras', + 'type': 'multiselect', + 'options': [ + {'value': 'extra-a', 'label': 'Extra A'}, + {'value': 'extra-b', 'label': 'Extra B'}, + ], + }, + { + 'key': 'note', + 'title': 'Notes', + 'type': 'string', + 'required': true, + 'min_length': 3, + }, +]; + +JsonMap question({ + bool resolved = false, + bool cancelled = false, + Map? answers, +}) => { + 'id': 'form-1', + 'session_id': 's', + 'kind': 'question', + 'title': 'A demo question', + 'fields': fields(), + 'actions': ['accept', 'decline', 'cancel'], + if (resolved) 'resolved': true, + if (cancelled) 'cancelled': true, + 'answers': ?answers, +}; + +void main() { + test('field visibility keeps false and zero as answers', () { + final fields = [ + {'key': 'enabled', 'type': 'boolean'}, + { + 'key': 'count', + 'type': 'integer', + 'when': [ + {'key': 'enabled', 'op': 'eq', 'value': true}, + ], + }, + ]; + final hidden = {'enabled': false, 'count': 0}; + expect(chatFormFieldVisible(fields[1], hidden), isFalse); + expect(chatFormAnswerError(fields, hidden), ''); + expect(chatVisibleFormAnswers(fields, hidden), {'enabled': false}); + }); + + test('required free text and numeric bounds use the web wording', () { + final fields = [ + {'key': 'note', 'title': 'Notes', 'type': 'string', 'required': true}, + {'key': 'count', 'type': 'integer', 'minimum': 1, 'maximum': 5}, + ]; + expect( + chatFormAnswerError(fields, {'count': 2}), + 'Answer Notes before sending.', + ); + expect( + chatFormAnswerError(fields, {'note': 'ok', 'count': 1.5}), + 'count needs a valid integer.', + ); + expect( + chatFormAnswerError(fields, {'note': 'ok', 'count': 6}), + 'count must be at most 5.', + ); + expect( + chatFormAnswerError(fields, {'note': 'ok', 'count': 0}), + 'count must be at least 1.', + ); + expect(chatFormAnswerError(fields, {'note': 'ok', 'count': 5}), ''); + }); + + testWidgets('a pending question answers single, multi and required free text ' + 'exactly as recorded', (tester) async { + tester.view.physicalSize = const Size(800, 1200); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + Map? sent; + await tester.pumpWidget( + scrollHost( + ChatQuestionCard( + form: question(), + onSubmit: (answers, action) async { + sent = answers; + }, + ), + ), + ); + expect(find.text('A demo question'), findsOneWidget); + expect(find.text(chatQuestionWaiting), findsOneWidget); + + await tester.tap(find.text('Red')); + await tester.pump(); + await tester.tap(find.text('Extra A')); + await tester.pump(); + await tester.tap(find.text('Send answer')); + await tester.pump(); + expect(find.text('Answer Notes before sending.'), findsOneWidget); + expect(sent, isNull); + + await tester.enterText( + find.byKey(const ValueKey('chat-question-input-note')), + ' ready ', + ); + await tester.pump(); + await tester.tap(find.text('Send answer')); + await tester.pumpAndSettle(); + expect(sent, { + 'colour': 'red', + 'extras': ['extra-a'], + 'note': ' ready ', + }); + }); + + testWidgets('a single-select option replaces the previous choice and a ' + 'multi-select toggles', (tester) async { + Map? sent; + await tester.pumpWidget( + scrollHost( + ChatQuestionCard( + form: question(), + onSubmit: (answers, action) async { + sent = answers; + }, + ), + ), + ); + await tester.tap(find.text('Red')); + await tester.pump(); + await tester.tap(find.text('Blue')); + await tester.pump(); + await tester.tap(find.text('Extra A')); + await tester.pump(); + await tester.tap(find.text('Extra B')); + await tester.pump(); + await tester.tap(find.text('Extra A')); + await tester.pump(); + await tester.enterText( + find.byKey(const ValueKey('chat-question-input-note')), + 'done', + ); + await tester.tap(find.text('Send answer')); + await tester.pumpAndSettle(); + expect(sent, { + 'colour': 'blue', + 'extras': ['extra-b'], + 'note': 'done', + }); + }); + + testWidgets('answered questions show the recorded answer read-only', ( + tester, + ) async { + await tester.pumpWidget( + scrollHost( + ChatQuestionCard( + form: question( + resolved: true, + answers: { + 'colour': 'red', + 'extras': ['extra-b'], + 'note': 'Recorded note', + }, + ), + onSubmit: (_, _) async {}, + ), + ), + ); + expect(find.text(chatQuestionAnswered), findsOneWidget); + expect(find.text('Red'), findsOneWidget); + expect(find.text('Extra B'), findsOneWidget); + expect(find.text('Recorded note'), findsOneWidget); + expect(find.text('Send answer'), findsNothing); + }); + + testWidgets('an expired question keeps recorded answers and offers no ' + 'controls', (tester) async { + await tester.pumpWidget( + scrollHost( + ChatQuestionCard( + form: question(cancelled: true, answers: {'colour': 'red'}), + onSubmit: (_, _) async {}, + ), + ), + ); + expect(find.text(chatQuestionExpired), findsOneWidget); + expect(find.text('Red'), findsOneWidget); + expect(find.text('Send answer'), findsNothing); + }); + + testWidgets('Cupertino field labels stay subordinate to the card title', ( + tester, + ) async { + await tester.pumpWidget( + cupertinoHost( + ChatQuestionCard(form: question(), onSubmit: (_, _) async {}), + ), + ); + final title = tester.widget(find.text('A demo question')); + final label = tester.widget(find.text('Colour')); + expect(label.style!.fontSize, lessThan(title.style!.fontSize!)); + }); + + testWidgets('a free-text input carries its visual label in semantics', ( + tester, + ) async { + final semantics = tester.ensureSemantics(); + await tester.pumpWidget( + scrollHost( + ChatQuestionCard(form: question(), onSubmit: (_, _) async {}), + ), + ); + final node = tester.getSemantics( + find.byKey(const ValueKey('chat-question-input-note')), + ); + expect(node.label, contains('Notes')); + semantics.dispose(); + }); + + testWidgets('integer input sends an int, never a decimal double', ( + tester, + ) async { + Map? sent; + await tester.pumpWidget( + scrollHost( + ChatQuestionCard( + form: { + 'id': 'form-int', + 'title': 'How many?', + 'actions': ['accept'], + 'fields': [ + {'key': 'count', 'title': 'Count', 'type': 'integer'}, + ], + }, + onSubmit: (answers, action) async { + sent = answers; + }, + ), + ), + ); + await tester.enterText( + find.byKey(const ValueKey('chat-question-input-count')), + '1.0', + ); + await tester.pump(); + await tester.tap(find.text('Send answer')); + await tester.pumpAndSettle(); + expect(sent, {'count': 1}); + expect(sent!['count'], isA()); + }); + + testWidgets('decline and cancel send their recorded actions with no answers', ( + tester, + ) async { + final actions = []; + final answers = >[]; + await tester.pumpWidget( + scrollHost( + ChatQuestionCard( + form: question(), + onSubmit: (sent, action) async { + actions.add(action); + answers.add(sent); + }, + ), + ), + ); + await tester.tap(find.text('Decline')); + await tester.pumpAndSettle(); + await tester.tap(find.text('Cancel question')); + await tester.pumpAndSettle(); + expect(actions, ['decline', 'cancel']); + expect(answers, [{}, {}]); + }); + + testWidgets('an all-external form confirms completion without field answers', ( + tester, + ) async { + Map? sent; + String? action; + await tester.pumpWidget( + scrollHost( + ChatQuestionCard( + form: { + 'id': 'form-external', + 'title': 'Open the form', + 'actions': ['accept'], + 'fields': [ + { + 'key': 'form', + 'title': 'External form', + 'type': 'external', + 'url': 'https://example.com/complete', + }, + ], + }, + onSubmit: (answers, next) async { + sent = answers; + action = next; + }, + ), + ), + ); + expect(find.text('Confirm completion'), findsOneWidget); + expect(find.text('https://example.com/complete'), findsOneWidget); + await tester.tap(find.text('Confirm completion')); + await tester.pumpAndSettle(); + expect(sent, isEmpty); + expect(action, 'accept'); + }); + + testWidgets('an unsupported external URL shows the web alert wording', ( + tester, + ) async { + await tester.pumpWidget( + scrollHost( + ChatQuestionCard( + form: { + 'id': 'form-external', + 'title': 'Open the form', + 'actions': ['accept'], + 'fields': [ + {'key': 'form', 'type': 'external', 'url': 'http://'}, + ], + }, + onSubmit: (_, _) async {}, + ), + ), + ); + expect( + find.text('This form has an unsupported external URL.'), + findsOneWidget, + ); + }); + + testWidgets('a resolved question without answers says none was recorded', ( + tester, + ) async { + await tester.pumpWidget( + scrollHost( + ChatQuestionCard( + form: question(resolved: true, answers: const {}), + onSubmit: (_, _) async {}, + ), + ), + ); + expect(find.text('No answer was recorded.'), findsOneWidget); + }); + + testWidgets('recorded booleans use Yes/No and blank titles fall back to the ' + 'key', (tester) async { + await tester.pumpWidget( + scrollHost( + ChatQuestionCard( + form: { + 'id': 'form-recorded', + 'title': 'Recorded', + 'resolved': true, + 'answers': {'enabled': true, 'extra': 'kept'}, + 'fields': [ + {'key': 'enabled', 'title': '', 'description': '', 'type': 'boolean'}, + ], + }, + onSubmit: (_, _) async {}, + ), + ), + ); + expect(find.text('enabled'), findsOneWidget); + expect(find.text('Yes'), findsOneWidget); + expect(find.text('true'), findsNothing); + expect(find.text('extra'), findsOneWidget); + expect(find.text('kept'), findsOneWidget); + }); + + testWidgets('320px at 2x in dark Cupertino keeps native controls', ( + tester, + ) async { + tester.view.physicalSize = const Size(640, 1600); + tester.view.devicePixelRatio = 2; + tester.platformDispatcher.textScaleFactorTestValue = 2; + tester.platformDispatcher.platformBrightnessTestValue = Brightness.dark; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue); + addTearDown(tester.platformDispatcher.clearPlatformBrightnessTestValue); + + await tester.pumpWidget( + cupertinoHost( + ChatQuestionCard(form: question(), onSubmit: (_, _) async {}), + ), + ); + expect(tester.takeException(), isNull); + expect(find.text('A demo question'), findsOneWidget); + expect(find.text('Send answer'), findsOneWidget); + expect(find.byType(Material), findsNothing); + }); + + testWidgets('a pushed form renders and sends one exact chat_answer', ( + tester, + ) async { + final gateway = FakeChatGateway(); + addTearDown(gateway.close); + gateway.history = (_) async => chatPage(const []); + final held = Completer(); + gateway.answer = (_) => held.future; + + await tester.pumpWidget( + materialHost( + ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {}), + ), + ); + await tester.pumpAndSettle(); + gateway.emitEvent({'session_id': 's', 'kind': 'form', 'form': question()}); + await tester.pumpAndSettle(); + expect(find.text('A demo question'), findsOneWidget); + + await tester.tap(find.text('Red')); + await tester.pump(); + await tester.enterText( + find.byKey(const ValueKey('chat-question-input-note')), + 'sent once', + ); + await tester.tap(find.text('Send answer')); + await tester.tap(find.text('Send answer')); + await tester.pump(); + + final answers = gateway.calls.where((call) => call.type == 'chat_answer'); + expect(answers, hasLength(1)); + expect(answers.single.fields, { + 'chat_answer': { + 'session_id': 's', + 'form_id': 'form-1', + 'answers': {'colour': 'red', 'note': 'sent once'}, + 'action': 'accept', + }, + }); + held.complete(const {}); + await tester.pumpAndSettle(); + expect(find.text(chatQuestionAnswered), findsOneWidget); + }); + + testWidgets('a refused question keeps the card open with the server reason', ( + tester, + ) async { + final gateway = FakeChatGateway(); + addTearDown(gateway.close); + gateway.history = (_) async => chatPage(const []); + gateway.answer = (_) async => throw StateError('form already closed'); + + await tester.pumpWidget( + materialHost( + ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {}), + ), + ); + await tester.pumpAndSettle(); + gateway.emitEvent({'session_id': 's', 'kind': 'form', 'form': question()}); + await tester.pumpAndSettle(); + await tester.tap(find.text('Red')); + await tester.pump(); + await tester.enterText( + find.byKey(const ValueKey('chat-question-input-note')), + 'retry me', + ); + await tester.tap(find.text('Send answer')); + await tester.pumpAndSettle(); + + expect(find.textContaining('form already closed'), findsOneWidget); + expect(find.text('Send answer'), findsOneWidget); + expect(find.text(chatQuestionWaiting), findsOneWidget); + }); + + testWidgets('unknown transcript parts remain available beside cards', ( + tester, + ) async { + final gateway = FakeChatGateway(); + addTearDown(gateway.close); + gateway.history = (_) async => chatPage([ + chatMessage( + 'a1', + 'assistant', + parts: [ + {'type': 'text', 'text': 'Recorded answer with a fallback part.'}, + {'type': 'future-content', 'future_value': 'still preserved'}, + ], + ), + ]); + await tester.pumpWidget( + materialHost( + ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {}), + ), + ); + await tester.pumpAndSettle(); + expect(find.text('Recorded answer with a fallback part.'), findsOneWidget); + await tester.tap(find.text('Unrecognised part: future-content')); + await tester.pumpAndSettle(); + expect(find.textContaining('still preserved'), findsOneWidget); + }); +} diff --git a/app/test/features/chat/conversation/chat_thread_cards_test.dart b/app/test/features/chat/conversation/chat_thread_cards_test.dart new file mode 100644 index 00000000..7aca8490 --- /dev/null +++ b/app/test/features/chat/conversation/chat_thread_cards_test.dart @@ -0,0 +1,82 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_thread_controller.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_thread_cards.dart'; + +import 'chat_thread_fixtures.dart'; + +JsonMap permission(String id, {bool resolved = false}) => { + 'session_id': 's', + 'request_id': id, + 'action': 'bash', + 'resources': const ['command: ls'], + 'message': '', + 'resolved': resolved, + if (resolved) 'decision': 'once', +}; + +JsonMap form(String id, {bool resolved = false}) => { + 'id': id, + 'session_id': 's', + 'title': 'Question', + 'fields': const [], + 'actions': const ['accept'], + 'resolved': resolved, + if (resolved) 'answers': const {'note': 'recorded'}, +}; + +void main() { + test('settled approvals are bounded while the pending one is kept', () async { + final gateway = FakeChatGateway(); + addTearDown(gateway.close); + final controller = ChatThreadController(gateway, 's'); + addTearDown(controller.dispose); + + for (var index = 0; index < ChatThreadCards.settledLimit + 5; index++) { + gateway.emitRaw({ + 'type': 'chat_permission', + 'chat_permission': permission('req-$index', resolved: true), + }); + } + gateway.emitRaw({ + 'type': 'chat_permission', + 'chat_permission': permission('req-pending'), + }); + await pumpEventQueue(); + + expect(controller.permissionFrames, hasLength(ChatThreadCards.settledLimit + 1)); + expect( + controller.permissionFrames.first['request_id'], + 'req-5', + ); + expect( + controller.permissionFrames.last['request_id'], + 'req-pending', + ); + }); + + test('settled forms are bounded while the pending one is kept', () async { + final gateway = FakeChatGateway(); + addTearDown(gateway.close); + final controller = ChatThreadController(gateway, 's'); + addTearDown(controller.dispose); + + for (var index = 0; index < ChatThreadCards.settledLimit + 5; index++) { + gateway.emitEvent({ + 'session_id': 's', + 'kind': 'form', + 'form': form('form-$index', resolved: true), + }); + } + gateway.emitEvent({ + 'session_id': 's', + 'kind': 'form', + 'form': form('form-pending'), + }); + await pumpEventQueue(); + + expect(controller.questionForms, hasLength(ChatThreadCards.settledLimit + 1)); + expect(controller.questionForms.first['id'], 'form-5'); + expect(controller.questionForms.last['id'], 'form-pending'); + }); +} diff --git a/app/test/features/chat/conversation/chat_thread_fixtures.dart b/app/test/features/chat/conversation/chat_thread_fixtures.dart index 94cdaf46..25f289e5 100644 --- a/app/test/features/chat/conversation/chat_thread_fixtures.dart +++ b/app/test/features/chat/conversation/chat_thread_fixtures.dart @@ -9,6 +9,8 @@ class FakeChatGateway implements ApiGateway { final _frames = StreamController.broadcast(); Future Function(JsonMap fields)? history; Future Function()? subscribe; + Future Function(JsonMap fields)? reply; + Future Function(JsonMap fields)? answer; void Function()? onSubscribe; @override @@ -23,6 +25,12 @@ class FakeChatGateway implements ApiGateway { historyRequests.add(completer); if (history != null) return history!(fields); return completer.future; + case 'chat_reply': + if (reply != null) return reply!(fields); + return {}; + case 'chat_answer': + if (answer != null) return answer!(fields); + return {}; } return {}; } diff --git a/app/tool/chat_approvals_probe.dart b/app/tool/chat_approvals_probe.dart new file mode 100644 index 00000000..fdf5d34b --- /dev/null +++ b/app/tool/chat_approvals_probe.dart @@ -0,0 +1,167 @@ +import 'dart:async'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart'; + +/// Browser fixture for the chat approval and question cards. +/// +/// The real [ChatThreadView] drives the real controller against this scripted +/// gateway. The gateway replays one pending permission and one question on +/// subscribe, and echoes the recorded decision/answer back as the server would, +/// so the cards' answered states are produced by the reply path, not hardcoded. +class _ApprovalsGateway implements ApiGateway { + final _frames = StreamController.broadcast(); + bool _sent = false; + + @override + Stream get frames => _frames.stream; + + @override + Future call(String type, [JsonMap fields = const {}]) async { + switch (type) { + case 'chat_subscribe': + if (!_sent) { + _sent = true; + Timer(const Duration(milliseconds: 400), _replayPending); + } + return {}; + case 'chat_messages': + return { + 'chat_history': { + 'messages': [ + { + 'id': 'probe-user', + 'role': 'user', + 'parts': [ + { + 'type': 'text', + 'text': 'Show me the recorded approval and question cards.', + }, + ], + }, + ], + 'next_cursor': '', + 'has_more': false, + }, + }; + case 'chat_reply': + final body = fields['chat_reply'] as Map? ?? const {}; + final requestId = '${body['request_id'] ?? ''}'; + final decision = '${body['decision'] ?? ''}'; + _frames.add({ + 'type': 'chat_permission', + 'chat_permission': { + ..._permission, + 'resolved': true, + 'decision': decision, + 'message': 'Recorded by the probe fixture after $decision.', + 'request_id': requestId, + }, + }); + return {}; + case 'chat_answer': + final body = fields['chat_answer'] as Map? ?? const {}; + _frames.add({ + 'type': 'chat_event', + 'chat_event': { + 'session_id': 'probe-session', + 'kind': 'form', + 'form': { + ..._question, + 'resolved': true, + 'answers': body['answers'] ?? const {}, + }, + }, + }); + return {}; + } + return {}; + } + + void _replayPending() { + if (_frames.isClosed) return; + _frames.add({'type': 'chat_permission', 'chat_permission': _permission}); + _frames.add({ + 'type': 'chat_event', + 'chat_event': { + 'session_id': 'probe-session', + 'kind': 'form', + 'form': _question, + }, + }); + } + + static const _permission = { + 'session_id': 'probe-session', + 'request_id': 'probe-permission', + 'action': 'bash', + 'resources': [ + 'command: rm -rf build', + 'cwd: /workspace/demo', + ], + 'message': 'This deletes the build output.', + 'source': {'type': 'tool'}, + }; + + static const _question = { + 'id': 'probe-question', + 'session_id': 'probe-session', + 'kind': 'question', + 'title': 'A demo question', + 'actions': ['accept'], + 'fields': [ + { + 'key': 'colour', + 'title': 'Colour', + 'type': 'string', + 'required': true, + 'options': [ + {'value': 'red', 'label': 'Red'}, + {'value': 'blue', 'label': 'Blue'}, + ], + }, + { + 'key': 'note', + 'title': 'Notes', + 'type': 'string', + 'placeholder': 'Optional note', + }, + ], + }; +} + +const _style = String.fromEnvironment( + 'CHAT_APPROVALS_PROBE_STYLE', + defaultValue: 'material', +); + +void main() { + final gateway = _ApprovalsGateway(); + final thread = ChatThreadView( + gateway: gateway, + sessionId: 'probe-session', + title: 'Probe conversation', + onBack: () {}, + ); + if (_style == 'cupertino') { + runApp( + CupertinoApp( + theme: const CupertinoThemeData(brightness: Brightness.dark), + home: CupertinoPageScaffold(child: SafeArea(child: thread)), + ), + ); + return; + } + runApp( + MaterialApp( + theme: ThemeData( + brightness: Brightness.dark, + platform: TargetPlatform.android, + ), + home: Scaffold(body: SafeArea(child: thread)), + ), + ); +} diff --git a/app/tool/chat_approvals_probe.mjs b/app/tool/chat_approvals_probe.mjs new file mode 100644 index 00000000..922fd29f --- /dev/null +++ b/app/tool/chat_approvals_probe.mjs @@ -0,0 +1,356 @@ +// Real-browser evidence for the chat approval and question cards. +// +// Build one host, then run from app/: +// flutter build web -t tool/chat_approvals_probe.dart \ +// --dart-define=CHAT_APPROVALS_PROBE_STYLE=material \ +// --output build/probe-chat-approvals-material +// node tool/chat_approvals_probe.mjs \ +// --root build/probe-chat-approvals-material --out DIR --style material +// +// The same fixture is built with CHAT_APPROVALS_PROBE_STYLE=cupertino. The +// script drives the real widget/controller through Chrome DevTools semantics, +// approves one permission and answers one question, and asserts the recorded +// answered states plus saved captures. +import { createServer } from 'node:http'; +import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; +import { spawn, execFile } from 'node:child_process'; +import { once } from 'node:events'; +import { promisify } from 'node:util'; +import { setTimeout as delay } from 'node:timers/promises'; +import { extname, join, resolve, sep } from 'node:path'; +import { tmpdir } from 'node:os'; + +const args = new Map(); +for (let i = 2; i < process.argv.length; i++) { + const value = process.argv[i]; + if (value.startsWith('--')) args.set(value.slice(2), process.argv[++i]); +} +const root = resolve(args.get('root') ?? 'build/probe-chat-approvals-material'); +const out = resolve(args.get('out') ?? 'build/chat-approvals-probe'); +const style = args.get('style') ?? 'material'; +const chromePath = + process.env.CHROME_PATH ?? + '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'; +await mkdir(out, { recursive: true }); + +const mime = { + '.html': 'text/html; charset=utf-8', + '.js': 'text/javascript; charset=utf-8', + '.json': 'application/json; charset=utf-8', + '.wasm': 'application/wasm', + '.png': 'image/png', + '.svg': 'image/svg+xml', + '.ico': 'image/x-icon', + '.ttf': 'font/ttf', + '.otf': 'font/otf', + '.woff': 'font/woff', + '.woff2': 'font/woff2', + '.bin': 'application/octet-stream', +}; + +const server = createServer(async (req, res) => { + try { + const pathname = decodeURIComponent( + new URL(req.url, 'http://localhost').pathname, + ); + let filePath = resolve(root, '.' + pathname); + if (filePath !== root && !filePath.startsWith(root + sep)) { + res.writeHead(403).end(); + return; + } + if (pathname === '/' || pathname.endsWith('/')) { + filePath = join(filePath, 'index.html'); + } + const file = await readFile(filePath); + res.writeHead(200, { + 'content-type': mime[extname(filePath)] ?? 'application/octet-stream', + }); + res.end(file); + } catch { + res.writeHead(404).end('not found'); + } +}); +server.listen(0, '127.0.0.1'); +await once(server, 'listening'); +const origin = `http://127.0.0.1:${server.address().port}`; + +const profile = await mkdtemp(join(tmpdir(), 'chat-approvals-chrome-')); +const chrome = spawn( + chromePath, + [ + '--headless=new', + '--no-first-run', + '--no-default-browser-check', + '--disable-gpu', + '--remote-debugging-port=0', + `--user-data-dir=${profile}`, + 'about:blank', + ], + { stdio: ['ignore', 'ignore', 'pipe'] }, +); +let stderr = ''; +chrome.stderr.on('data', (data) => { + stderr += data; +}); + +const waitFor = async (fn, what) => { + for (let i = 0; i < 240; i++) { + const value = await fn(); + if (value) return value; + await delay(100); + } + throw new Error(`Timed out waiting for ${what}: ${stderr.slice(-1500)}`); +}; + +let ws; +const evidence = { origin, style, captures: [], checks: [] }; +try { + const endpoint = await waitFor( + () => stderr.match(/DevTools listening on (ws:\/\/[^\s]+)/)?.[1], + 'Chrome DevTools', + ); + ws = new WebSocket(endpoint); + await once(ws, 'open'); + let id = 0; + const pending = new Map(); + ws.addEventListener('message', (event) => { + const message = JSON.parse(event.data); + if (message.id && pending.has(message.id)) { + pending.get(message.id)(message); + pending.delete(message.id); + } + }); + const send = (method, params = {}, sessionId) => + new Promise((resolveCall) => { + const callId = ++id; + pending.set(callId, resolveCall); + ws.send( + JSON.stringify({ + id: callId, + method, + params, + ...(sessionId ? { sessionId } : {}), + }), + ); + }); + + const created = await send('Target.createTarget', { url: 'about:blank' }); + if (!created.result) throw new Error('Target creation failed'); + 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); + await send( + 'Emulation.setDeviceMetricsOverride', + { width: 320, height: 1500, deviceScaleFactor: 2, mobile: true }, + session, + ); + await send( + 'Emulation.setEmulatedMedia', + { features: [{ name: 'prefers-color-scheme', value: 'dark' }] }, + 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 nodes = () => + evaluate(`[...document.querySelectorAll('flt-semantics')].map(x => { + const r = x.getBoundingClientRect(); + return { + label: x.getAttribute('aria-label'), + text: (x.innerText || '').trim(), + x: r.x, y: r.y, w: r.width, h: r.height, + }; + })`); + const hasText = async (fragment) => { + const all = await nodes(); + return all.some((node) => + `${node.label ?? ''} ${node.text ?? ''}` + .toLowerCase() + .includes(fragment.toLowerCase()), + ); + }; + const click = async (name) => { + const point = await evaluate(`(() => { + const wanted = ${JSON.stringify(name)}; + const matches = [...document.querySelectorAll('flt-semantics')] + .map(x => { + const label = x.getAttribute('aria-label') || ''; + const text = (x.innerText || '').trim(); + const r = x.getBoundingClientRect(); + const labelHit = label.includes(wanted) ? 0 : 1; + return { x, label, text, labelHit, area: r.width * r.height }; + }) + .filter(x => x.labelHit === 0 || x.text.includes(wanted)) + .sort((a, b) => a.labelHit - b.labelHit || a.area - b.area); + const node = matches[0]?.x; + if (!node) return null; + const r = node.getBoundingClientRect(); + return { x: r.x + r.width / 2, y: r.y + r.height / 2 }; + })()`); + if (!point) { + const shown = (await nodes()) + .map((entry) => entry.label ?? entry.text) + .filter(Boolean); + throw new Error( + `Could not find ${JSON.stringify(name)}: ${JSON.stringify(shown)}`, + ); + } + for (const type of ['mousePressed', 'mouseReleased']) { + await send( + 'Input.dispatchMouseEvent', + { type, x: point.x, y: point.y, button: 'left', clickCount: 1 }, + session, + ); + } + await delay(700); + }; + const capture = async (name) => { + const data = ( + await send('Page.captureScreenshot', { format: 'png' }, session) + ).result.data; + const file = join(out, `${style}-${name}.png`); + await writeFile(file, Buffer.from(data, 'base64')); + evidence.captures.push(file); + return file; + }; + // Flutter web paints static text on the canvas, so semantics exposes the + // controls but not the card's prose. OCR reads the real rendered pixels. + const screenOCR = async () => { + const data = ( + await send('Page.captureScreenshot', { format: 'png' }, session) + ).result.data; + const file = join(out, 'screen-ocr.png'); + await writeFile(file, Buffer.from(data, 'base64')); + const { stdout } = await promisify(execFile)('tesseract', [file, 'stdout']); + return stdout.replace(/\s+/g, ' '); + }; + // OCR sometimes merges words across a line ("A demo question" reads as + // "Ademo question"), so comparisons ignore whitespace entirely. + const flat = (value) => value.toLowerCase().replace(/\s+/g, ''); + const waitForOCR = async (text) => { + for (let i = 0; i < 120; i++) { + const read = await screenOCR(); + if (flat(read).includes(flat(text))) return read; + await delay(200); + } + throw new Error(`Timed out waiting for OCR ${JSON.stringify(text)}`); + }; + + await send('Page.navigate', { url: `${origin}/` }, session); + await delay(3500); + await evaluate("document.querySelector('flt-semantics-placeholder')?.click()"); + await delay(1200); + await waitForOCR('Approve bash').catch(async (error) => { + await capture('failure'); + console.log(JSON.stringify(await nodes(), null, 2)); + throw error; + }); + // The two cards need not fit one screen; scroll the conversation like an + // operator until the question is rendered, then read the whole card view. + let pendingRead = await screenOCR(); + for (let attempt = 0; attempt < 12 && !flat(pendingRead).includes(flat('A demo question')); attempt++) { + await send('Input.dispatchMouseEvent', { + type: 'mouseWheel', x: 195, y: 420, deltaX: 0, deltaY: 320, + }, session); + await delay(350); + pendingRead = await screenOCR(); + } + if (!flat(pendingRead).includes(flat('A demo question'))) { + pendingRead = await waitForOCR('A demo question'); + } + + // Prose comes from the painted pixels, controls from the semantics tree; a + // white-on-tint filled button is reliable in semantics even when OCR skips it. + const pendingSemantics = flat( + (await nodes()).map((entry) => `${entry.label ?? ''} ${entry.text ?? ''}`).join(' '), + ); + for (const text of [ + // The web card headline is the recorded action; it has no separate + // "Permission request" heading, so none is invented here either. + 'Approve bash', + 'Waiting for your response', + 'RISK REVIEW', + 'This deletes the build output.', + 'Allow once', + 'Always allow', + 'Reject', + 'A demo question', + 'The agent is waiting for your answer.', + 'Colour', + 'Red', + 'Blue', + ]) { + if (!flat(pendingRead).includes(flat(text)) && !pendingSemantics.includes(flat(text))) { + throw new Error(`Pending cards lack ${JSON.stringify(text)}`); + } + } + const pendingCapture = await capture('cards'); + evidence.checks.push({ + check: 'pending approval and question render with their recorded text', + style, + capture: pendingCapture, + labels: (await nodes()).map((node) => node.label).filter(Boolean), + }); + + await click('Allow once'); + const approvedRead = await waitForOCR('Allowed once'); + for (const text of ['Recorded by the probe fixture']) { + if (!approvedRead.toLowerCase().includes(text.toLowerCase())) { + throw new Error(`Answered approval lacks ${JSON.stringify(text)}`); + } + } + await capture('approval-answered'); + evidence.checks.push({ + check: 'the approval reply was sent and the recorded resolution cleared controls', + style, + allowOnceStillVisible: await hasText('Allow once'), + }); + + await click('Red'); + await click('Send answer'); + const answeredRead = await waitForOCR('Answer recorded.'); + if (!answeredRead.toLowerCase().includes('red')) { + throw new Error('Answered question lost the recorded Red answer'); + } + await capture('question-answered'); + evidence.checks.push({ + check: 'the question answer was sent and the card is read-only', + style, + sendAnswerStillVisible: await hasText('Send answer'), + }); + + if (evidence.checks.at(-1).sendAnswerStillVisible) { + throw new Error('Send answer stayed visible after the question resolved'); + } + if (evidence.checks.at(-2).allowOnceStillVisible) { + throw new Error('Allow once stayed visible after the approval resolved'); + } + + const report = JSON.stringify(evidence, null, 2); + await writeFile(join(out, `${style}-evidence.json`), report); + console.log(report); +} finally { + ws?.close(); + chrome.kill(); + server.close(); + for (let attempt = 0; attempt < 10; attempt++) { + try { + await rm(profile, { recursive: true, force: true }); + break; + } catch { + await delay(200); + } + } +} From b8e5c3e7e3ec943cd04e5a131c42c24aa1d6f75a Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 22 Oct 2026 02:05:20 +0100 Subject: [PATCH 10/13] feat(app): notification capability with transition dedupe --- .../notify/notification_controller.dart | 108 +++++-- .../attention/notify/notification_ledger.dart | 73 +++-- .../attention/notify/notification_models.dart | 3 +- app/notes/A2-notify.md | 156 ++++++---- .../notify/notification_controller_test.dart | 282 ++---------------- .../notify/notification_delivery_test.dart | 238 +++++++++++++++ .../notify/notification_ledger_test.dart | 94 ++++-- .../notify/notification_models_test.dart | 5 +- .../notify/notification_permission_test.dart | 103 +++++++ .../notify/notification_reentry_test.dart | 93 ++++++ .../notify/notification_test_support.dart | 32 +- app/tool/notification_probe.dart | 48 ++- app/tool/notification_probe.mjs | 29 +- 13 files changed, 871 insertions(+), 393 deletions(-) create mode 100644 app/test/features/attention/notify/notification_delivery_test.dart create mode 100644 app/test/features/attention/notify/notification_permission_test.dart create mode 100644 app/test/features/attention/notify/notification_reentry_test.dart diff --git a/app/lib/features/attention/notify/notification_controller.dart b/app/lib/features/attention/notify/notification_controller.dart index d0e67dae..84f195d9 100644 --- a/app/lib/features/attention/notify/notification_controller.dart +++ b/app/lib/features/attention/notify/notification_controller.dart @@ -18,13 +18,18 @@ import 'notification_store.dart'; /// /// Only live attention transitions raise a notification: the caller publishes /// the transitions the attention model raised (never the initial seed), and one -/// identity is posted at most once, including across a reconnect, because the -/// ledger records the identity before the platform is asked to show it. A -/// dismissed identity is recorded but never shown. +/// identity is posted at most once per entry into its run's qualifying state, +/// including across a reconnect, because the ledger records the identity before +/// the platform is asked to show it. A dismissed identity is recorded but never +/// shown. /// /// The manager wires it: set [onOpenRun] to open a run, call [load] once, and -/// call [publishTransitions] with the attention controller's transitions. That -/// call is idempotent, so passing the whole accumulated list is safe. +/// after *every* authoritative read and pushed frame call [publishTransitions] +/// with the attention controller's accumulated transitions, its current rows +/// (through [notificationQualifyingKeys]) and its dismissed set. Publishing the +/// frame that leaves a state is what forgets the old identity, so the next gate +/// or retry is a new announcement. The call is idempotent, so passing the whole +/// accumulated list is safe. class NotificationController extends ChangeNotifier { NotificationController({required this.store, NotificationBridge? bridge}) : bridge = bridge ?? createNotificationBridge(); @@ -45,6 +50,13 @@ class NotificationController extends ChangeNotifier { bool _disposed = false; int _posted = 0; + /// The transition instance announced this session for each identity: a new + /// instance means the run entered the state again. + final Map _announced = {}; + + /// The queued ledger writes, so an older snapshot cannot land after a newer one. + Future _writes = Future.value(); + /// The platform's own permission state for this page. NotificationPermissionState get permission => _permission; @@ -54,8 +66,10 @@ class NotificationController extends ChangeNotifier { /// Whether the operator has ever been asked for permission. bool get asked => _ledger.asked; - /// The transition identities this client has already recorded. - Set get notified => _ledger.notified; + /// A copy of the transition identities this client has already announced. + /// Returned unmodifiable, so a caller cannot mutate the ledger behind + /// [publishTransitions]' back. + Set get notified => Set.unmodifiable(_ledger.notified); /// True only when the platform itself reported `granted`. bool get canNotify => _permission == NotificationPermissionState.granted; @@ -73,6 +87,7 @@ class NotificationController extends ChangeNotifier { } if (_disposed) return; _ledger = ledger; + _announced.clear(); _permission = notificationStateOf(bridge.environment()); _loaded = true; notifyListeners(); @@ -131,25 +146,55 @@ class NotificationController extends ChangeNotifier { /// Posts one notification per live transition, in order. /// - /// The initial seed raises no transition, so it never reaches here. A - /// transition the operator dismissed, one the ledger already recorded and one - /// past [maxNotificationsPerBatch] post nothing; every identity examined is - /// recorded first, so a later publish cannot repeat it. Returns how many - /// notifications the platform accepted. + /// [qualifying] is [notificationQualifyingKeys] for the *same* snapshot as + /// [transitions]: a transition whose run has left the state is stale and + /// neither posts nor records anything, then every recorded identity outside + /// [qualifying] is forgotten so the next gate can notify. Only the latest + /// entry per run+kind in a backlog is announced. + /// + /// A caller that misses the leaving frame still gets the new transition: the + /// detector creates one instance per genuine transition, so an identity + /// announced earlier this session with a different instance is a new + /// occurrence; the same instance, and an identity loaded from the store before + /// this session, stay silent. + /// + /// The initial seed raises no transition. A transition the operator dismissed, + /// one already recorded and one past [maxNotificationsPerBatch] post nothing. + /// Returns how many notifications the platform accepted. int publishTransitions( Iterable transitions, { + required Set qualifying, Set dismissed = const {}, }) { if (_disposed) return 0; var posted = 0; - var recorded = false; + var changed = false; + // A backlog may hold several entries for one run+kind; only the latest one + // describes the state that is current, so a coalesced burst notifies once. + final latest = {}; for (final transition in transitions) { + latest[notificationIdentity(transition)] = transition; + } + for (final transition in latest.values) { if (posted >= maxNotificationsPerBatch) break; final identity = notificationIdentity(transition); - if (_ledger.hasNotified(identity)) continue; - _ledger = _ledger.recording(identity); - recorded = true; - if (dismissed.contains(transition.key)) continue; + // Older than the snapshot: the run already left this state. + if (!qualifying.contains(identity)) continue; + final announced = _announced[identity]; + if (identical(announced, transition)) continue; + if (announced == null && _ledger.hasNotified(identity)) { + // Restored from the store before this session: adopt the instance so a + // republish is recognized, but do not announce it again. + _announced[identity] = transition; + continue; + } + // A new instance for an identity announced this session is a later entry. + if (!_ledger.hasNotified(identity)) { + _ledger = _ledger.recording(identity); + changed = true; + } + _announced[identity] = transition; + if (dismissed.contains(identity)) continue; if (!canNotify) continue; final open = onOpenRun; final message = NotificationMessage( @@ -172,18 +217,29 @@ class NotificationController extends ChangeNotifier { _posted++; } } - if (recorded) unawaited(_persist(_ledger)); + final pruned = _ledger.pruning(qualifying); + if (!identical(pruned, _ledger)) { + _ledger = pruned; + changed = true; + } + if (changed) unawaited(_persist(_ledger)); return posted; } - /// Writes the ledger without ever throwing into the caller's frame. - Future _persist(NotificationLedger ledger) async { - if (_disposed) return; - try { - await store.write(encodeNotificationLedger(ledger)); - } catch (_) { - // The in-memory ledger still applies for this session. - } + /// Writes the ledger without ever throwing into the caller's frame, one write + /// at a time so their order matches the calls. + Future _persist(NotificationLedger ledger) { + final encoded = encodeNotificationLedger(ledger); + final write = _writes.then((_) async { + if (_disposed) return; + try { + await store.write(encoded); + } catch (_) { + // The in-memory ledger still applies for this session. + } + }); + _writes = write; + return write; } @override diff --git a/app/lib/features/attention/notify/notification_ledger.dart b/app/lib/features/attention/notify/notification_ledger.dart index 3d8f35d6..2a88f3d2 100644 --- a/app/lib/features/attention/notify/notification_ledger.dart +++ b/app/lib/features/attention/notify/notification_ledger.dart @@ -1,6 +1,7 @@ import 'dart:convert'; import '../../../core/api_gateway.dart'; +import '../domain/attention_models.dart'; import '../domain/attention_transitions.dart'; /// This client's own storage key for the notification ledger, namespaced like @@ -8,34 +9,48 @@ import '../domain/attention_transitions.dart'; /// client rewrites the other's local state on a shared origin. const notificationStorageKey = 'pipelines.next.notify.v1'; -/// The marker that separates two transitions of one run and kind: the server's -/// own `finished_at` when it recorded one, else the run's creation time — the -/// same recency the attention surface orders by. +/// The identity of one announced transition: the run and kind, exactly the +/// attention surface's own key and the browser's `alertKey`. /// -/// A run that is retried and fails again carries a new marker, so its new -/// failure is a new identity and can notify once more; the same failure can -/// never notify twice. -String notificationMarker(JsonMap run) { - final finished = '${run['finished_at'] ?? ''}'.trim(); - return finished.isNotEmpty ? finished : '${run['created_at'] ?? ''}'.trim(); -} +/// It is deliberately *not* keyed by a timestamp. A waiting run has no +/// `finished_at`, and its creation time never changes, so a marker derived from +/// them cannot tell a run's first decision gate from a later one. Instead the +/// ledger only holds identities for the runs that are qualifying *right now*: +/// [notificationQualifyingKeys] supplies that set, and an identity is forgotten +/// as soon as its run leaves the qualifying state (see [NotificationLedger.pruning]). +/// The next entry into the same state is therefore a new announcement, exactly +/// as in `web/src/notify.js`. +String notificationIdentity(AttentionTransition transition) => transition.key; -/// The identity of one transition: run, kind and marker. The unit of dedupe. -String notificationIdentity(AttentionTransition transition) => - '${transition.key}@${notificationMarker(transition.run)}'; +/// The `{runId}:{Kind}` identities of the runs currently in a qualifying state, +/// built from the same rows the attention surface draws. +/// +/// Dismissals and the local-day window are deliberately ignored: a dismissal +/// does not stop a run qualifying, and an old failure is still the same +/// announced transition rather than a new one. +Set notificationQualifyingKeys(Iterable? runs) { + final keys = {}; + for (final run in runs ?? const []) { + final runId = attentionRunId(run['run_id']) ?? attentionRunId(run['id']); + final kind = attentionKindForRun(run); + if (runId == null || kind == null) continue; + keys.add(attentionKey(runId, kind)); + } + return keys; +} /// What this client has already announced, plus whether the operator has ever /// been asked. /// -/// The ledger is pure: it records identities and decides whether one is new. -/// Persistence is the store's job. +/// The ledger is pure: it records identities, decides whether one is new and +/// drops the ones whose run no longer qualifies. Persistence is the store's job. /// -/// An identity is never forgotten while the ledger lives, so publishing the same -/// transition list again is always idempotent. A genuinely new transition of the -/// same run and kind is a new identity because its marker changed (see -/// [notificationMarker]); the browser's in-session prune is deliberately not -/// reproduced, because a prune would let an already-announced transition that is -/// still in the caller's list be posted a second time. +/// An identity lives only while its run is in the qualifying state it announced: +/// publishing the same list again is idempotent, a reconnect cannot repeat a +/// notification, and a genuinely new transition (a second decision gate, or a +/// later failure of a new run id) notifies once more because leaving the state +/// dropped the old identity. This is the browser's `forget` model; unlike a +/// timestamp marker it can tell two decision gates of one run apart. class NotificationLedger { const NotificationLedger({ this.notified = const {}, @@ -56,6 +71,18 @@ class NotificationLedger { NotificationLedger withAsked(bool value) => NotificationLedger(notified: notified, asked: value); + + /// The ledger with every identity outside [qualifying] dropped. + /// + /// A run that is no longer failed or waiting has left its announced state, so + /// a later entry is a new event and must be able to notify again. Keeping only + /// the current qualifying identities also bounds the ledger to the runs the + /// surface currently holds instead of growing with every event ever seen. + NotificationLedger pruning(Set qualifying) { + final kept = notified.where(qualifying.contains).toSet(); + if (kept.length == notified.length) return this; + return NotificationLedger(notified: kept, asked: asked); + } } /// The one-line JSON the ledger is stored as. The identities are sorted so an @@ -69,6 +96,10 @@ String encodeNotificationLedger(NotificationLedger ledger) { /// Decodes a stored value into a ledger. Total: blank text, unreadable JSON, a /// non-map, a non-boolean `asked` and non-string members all decode to the /// members that can be read, and a malformed value never throws. +/// +/// A value written by an older build may still contain timestamped identities; +/// they simply stop matching [notificationQualifyingKeys] and are dropped on the +/// next publish, so no migration step is needed. NotificationLedger decodeNotificationLedger(String? stored) { final text = (stored ?? '').trim(); if (text.isEmpty) return const NotificationLedger(); diff --git a/app/lib/features/attention/notify/notification_models.dart b/app/lib/features/attention/notify/notification_models.dart index f1f8777b..f817c92e 100644 --- a/app/lib/features/attention/notify/notification_models.dart +++ b/app/lib/features/attention/notify/notification_models.dart @@ -120,8 +120,7 @@ NotificationPermissionView notificationPermissionView( final canRequest = state == NotificationPermissionState.notRequested; final body = switch (state) { NotificationPermissionState.unsupported => notificationUnsupportedCopy, - NotificationPermissionState.needsSecureContext => - notificationInsecureCopy, + NotificationPermissionState.needsSecureContext => notificationInsecureCopy, NotificationPermissionState.granted => notificationGrantedCopy, NotificationPermissionState.denied => notificationDeniedCopy, NotificationPermissionState.notRequested => diff --git a/app/notes/A2-notify.md b/app/notes/A2-notify.md index 7045f533..ad484ee6 100644 --- a/app/notes/A2-notify.md +++ b/app/notes/A2-notify.md @@ -3,22 +3,22 @@ The notification capability exists as reusable Dart under `lib/features/attention/notify/`, plus one reusable Settings tile at `lib/features/attention/ui/notification_permission_tile.dart`. Nothing was wired -into the shell, `Settings`, the application or the Runs screen, and no tracked -file outside those paths changed (`git status` shows only new files). +into the shell, `Settings`, the application or the Runs screen; outside those +paths only this note, the notify tests and the isolated probe changed. ## What is there | File | Lines | Role | | --- | --- | --- | -| `notify/notification_models.dart` | 170 | permission state, environment, copy, permission view, alert title/body, `NotificationMessage` | +| `notify/notification_models.dart` | 169 | permission state, environment, copy, permission view, alert title/body, `NotificationMessage` | | `notify/notification_bridge.dart` | 30 | the abstract `NotificationBridge` + the conditional-import factory | | `notify/notification_bridge_web.dart` | 95 | the real `Notification` API via `dart:js_interop` (no `package:web`) | | `notify/notification_bridge_stub.dart` | 27 | non-web stub that reports `unsupported` honestly | -| `notify/notification_ledger.dart` | 91 | identity (run+kind+marker), ledger, total JSON codec, `pipelines.next.notify.v1` | +| `notify/notification_ledger.dart` | 122 | run+kind identity, the qualifying-key set, ledger with pruning, total JSON codec, `pipelines.next.notify.v1` | | `notify/notification_store.dart` | 83 | injectable store seam; total `shared_preferences` impl + memory impl | -| `notify/notification_controller.dart` | 194 | the `ChangeNotifier` capability | +| `notify/notification_controller.dart` | 250 | the `ChangeNotifier` capability | | `ui/notification_permission_tile.dart` | 127 | the reusable native tile | -| `tool/notification_probe.dart` / `.mjs` | 265 / 295 | isolated real-browser probe | +| `tool/notification_probe.dart` / `.mjs` | 291 / 314 | isolated real-browser probe | ## Platform seam @@ -41,19 +41,44 @@ still `notRequested`, issues the platform request before any `await` so it stays inside the gesture, persists `asked` without awaiting, and follows the platform's answer. A denied state is never re-prompted. -## Notify only on live transitions +## Notify only on live transitions, dedupe per qualifying state + +The identity is the attention surface's own `{runId}:{Kind}` key, which is also +the browser's `alertKey` and therefore the coalescing `tag`: - The initial list seed raises no transition, so `publishTransitions` over the attention controller's (empty) transition list posts nothing. -- The dedupe identity is `{runId}:{Kind}@{marker}` where the marker is the run's - trimmed `finished_at` else `created_at` — the same recency the surface orders - by. A retried run that fails again carries a new marker and notifies once more; - the same transition can never notify twice, including across a reconnect. -- The ledger records an identity before the platform is asked to show it and - persists it under `pipelines.next.notify.v1` through the injectable - `NotificationStore`. `publishTransitions` is therefore idempotent, so the - manager may pass the whole accumulated transition list. A store that throws on - read or write is swallowed; the in-memory ledger still applies for the session. +- `publishTransitions(transitions, qualifying:, dismissed:)` receives + `notificationQualifyingKeys(attention.rows)` — the `{runId}:{Kind}` keys of the + runs that are failed or waiting *right now*. A transition whose key is not in + that set is stale (the caller's accumulated list still holds it because the run + has moved on), so it neither posts nor re-records anything. +- At the end of the publish, every recorded identity outside the qualifying set + is forgotten ([`NotificationLedger.pruning`]). Publishing the frame that + *leaves* the state is what makes the next gate (or a later failure of a new + run id) a new announcement. + This is the browser's `forget`/`pruneNotified` model. +- A waiting run has no `finished_at`, so a timestamp marker cannot separate its + first decision gate from a later one. The run+kind identity plus pruning can: + `waiting -> running -> waiting` notifies once per gate even though both + entries carry identical timestamps. A retry that produces a new failed run id + is likewise a new identity; a failed run id never returns to running. +- A caller that misses the frame that leaves the state is still handled: the + attention detector creates one transition instance per genuine transition, so + an identity announced earlier in this session with a different instance is a + new occurrence and notifies. Republishing the same instance stays silent. +- The same transition can never notify twice across a republish, a reconnect + reseed, or a controller rebuilt over the same store while the run still + qualifies. The ledger records the identity before the platform is asked to + show it and persists it under `pipelines.next.notify.v1` through the injectable + `NotificationStore`. A value written by the previous timestamp-identity build + stops matching the qualifying set and is dropped on the next publish, so no + migration step is needed. +- The ledger is bounded by the runs currently qualifying, not by the history of + every event the install has ever seen. +- Writes are serialized through one queued future, so an older snapshot can + never land after a newer one, and a throwing read/write is swallowed: the + in-memory ledger still applies for the session. - A dismissed identity is recorded but never shown (the transition detector already suppresses it; the publish guard covers a caller that passes it). - Content is the entry's own words: the kind headline (`A run failed` / `A run @@ -62,6 +87,8 @@ answer. A denied state is never re-prompted. because neither reference client's alert body carries one. - A batch posts in order, bounded to `maxNotificationsPerBatch` (5); the rest are posted on the next call because the ones already posted are recorded. +- `notified` returns an unmodifiable copy, so a caller cannot mutate the ledger + behind the controller's back. ## Wiring the manager still owes @@ -69,46 +96,64 @@ answer. A denied state is never re-prompted. final notify = NotificationController(store: const SharedPreferencesNotificationStore()); notify.onOpenRun = (runId) { /* open that run — navigation lives here, not in notify */ }; await notify.load(); -// after each authoritative read / pushed frame the attention controller handles: -notify.publishTransitions(attention.transitions, dismissed: attention.dismissed); +// after *every* authoritative read and pushed frame the attention controller handles: +notify.publishTransitions( + attention.transitions, + qualifying: notificationQualifyingKeys(attention.rows), + dismissed: attention.dismissed, +); ``` -`load()` once, and `publishTransitions` on every frame/seed, is enough; it is -idempotent. `refreshPermission()` re-reads the platform facts after a focus -change. The tile is embedded by the Settings screen with the live `state`/`asked` -and an `onRequest` that calls `notify.requestPermission()`. +Publishing on the frames that leave a state matters as much as publishing the +one that entered it: that is when the old identity is forgotten. `load()` once, +and `publishTransitions` on every frame/seed, is enough; it is idempotent. +`refreshPermission()` re-reads the platform facts after a focus change. The tile +is embedded by the Settings screen with the live `state`/`asked` and an +`onRequest` that calls `notify.requestPermission()`. ## Tests and evidence -- `flutter test test/features/attention` — **135 passed** (the 43 new notify/tile - tests plus the existing attention suite; the new coverage is: seed never - notifies; one live transition once with its own words and identity; duplicate - frame and republished list silent; reconnect reseed and a rebuilt controller - silent; a genuinely new failure notifies again; dismissed excluded (detector and - publish guard); unsupported/needs-secure/denied/granted permission paths and - "denied is never re-prompted"; a prompt that grants nothing; the bounded batch; - the tap seam; an unavailable store and a throwing platform post; the non-web - stub; the tile copy per state, the asked wording, the Enable gesture and both - hosts at 320 logical px / 2x in dark with the action present). +- `flutter test test/features/attention` — **147 passed** (12 more than before + this change; the notify/tile files hold 55). New coverage in this change: the + `waiting -> running -> waiting` second gate with the real waiting shape (empty + `finished_at`) notifies again, with and without publishing the leaving frame; + a coalesced backlog of two gates notifies once; a stale transition from a run + that left is not re-posted; the identity is run+kind so two alerts of one run + share the browser tag; pruning drops identities outside the qualifying set; + old timestamped identities are dropped; `notificationQualifyingKeys` ignores + export waits, malformed ids and duplicates; `notified` is unmodifiable; ledger + writes are serialized in call order. +- `flutter test` (whole app) — **1058 passed**. - `flutter analyze` — **No issues found** (whole project). -- `flutter build web` (the real `lib/main.dart`) — **succeeded**. +- `dart format --output=none --set-exit-if-changed` on every new lib/test file — + clean. +- `flutter build web` (the real `lib/main.dart`) — **succeeded**. This does *not* + compile the notify feature: nothing under `lib/` imports it yet, so the main + bundle contains none of its strings. It is a sanity check for the app only. +- `flutter build web -t tool/notification_probe.dart -o build/notification_probe_web` + — **succeeded**. This is the build that compiles the conditional-import web + bridge (`isSecureContext`, the alert copy and the real `Notification` seam are + in this bundle). - Real-browser probe (`tool/notification_probe.dart` + `.mjs`, isolated loopback server, `Browser.grantPermissions` / `Browser.setPermission`, `window.Notification` replaced with a recording spy before load): - **all 25 checks passed** — seed posted 0; one transition posted exactly 1 with - title `A run failed`, body `Nightly audit · nightly` and tag `1:Failed@…`; a - dismissed transition posted 0; a reconnect replay posted 1 in total; denied and - unsupported pages posted 0 and read their honest copy; all five tile states - read correctly on Material and Cupertino at 320 logical px / 2x. - Captures (copied to `public/captures/notify/`): `notification-transition-…`, - `notification-denied-…`, `notification-unsupported-…` and - `notification-tile-{unsupported,insecure,default,granted,denied}-{material,cupertino}-dark-320-2x.png` - (13 PNGs). + **all 29 checks passed** — seed posted 0; one transition posted exactly 1 with + title `A run failed`, body `Nightly audit · nightly` and tag `1:Failed`; a + dismissed transition posted 0; a reconnect replay posted 1 in total; a second + decision gate posted exactly 2 in total, both tag `7:Decision`, with the + waiting frames carrying no `finished_at`; denied and unsupported pages posted 0 + and read their honest copy; all five tile states read correctly on Material + **and** Cupertino at 320 logical px / 2x. +- 13 PNG captures regenerated in + `/Users/alan/.local/share/pipelines/data/artifacts/100/public/captures/notify/` + (`notification-transition-…`, `notification-denied-…`, + `notification-unsupported-…`, and + `notification-tile-{unsupported,insecure,default,granted,denied}-{material,cupertino}-dark-320-2x.png`). -One defect was found by the capture and fixed: putting the Enable action in a -`ListTile` trailing slot squeezed the section title to one glyph per line at -320 px / 2x, so the action now sits on its own row below the copy (as the -browser's settings section does), and the widget test guards it. +One UI defect was found by the first captures and fixed in the previous visit: +putting the Enable action in a `ListTile` trailing slot squeezed the section title +to one glyph per line at 320 px / 2x, so the action now sits on its own row below +the copy (as the browser's settings section does), and the widget test guards it. ## Deliberate limits @@ -116,13 +161,22 @@ browser's settings section does), and the widget test guards it. capability plus a reusable tile, not a delivered Settings section or shell wiring. The row should move when the manager embeds the tile and wires the controller, with authenticated smoke evidence. -- The browser's in-session `pruneNotified` is deliberately not reproduced: a - prune would let an already-announced transition that is still in the caller's - list post a second time. A run that leaves and re-enters the *same* qualifying - state with an unchanged marker is therefore the same identity and does not - notify twice — which is what the run+kind+marker rule requires. +- The instance rule is session-local. A controller rebuilt over the same store + can only distinguish a later gate if the frame that left the state was + published (which prunes the old identity), so the wiring above still publishes + every authoritative read and frame rather than only entering transitions. - A browser whose `Notification.requestPermission()` uses the legacy callback-only form (no returned promise) falls back to the honest default wording, as the web client also does. - Mobile (Android/iOS) is unverified: the stub reports `unsupported` and no device or OS notification behaviour was exercised. No `pubspec` change. +- The tile is not registered in Settings and background chat-question notices + (`web/src/app.js` `notifyChatQuestion`) are not part of this capability. + +## Manager completion after the Code deadline + +The run succeeded at Code, was rejected once at Review, and the retry hit the +30-minute deadline. The retained tree is complete: 147 attention tests pass and +analysis is clean. Merged directly. Shell wiring (permission tile in Settings and +transition delivery from the Runs attention controller) is the manager's next +step and is not claimed here. diff --git a/app/test/features/attention/notify/notification_controller_test.dart b/app/test/features/attention/notify/notification_controller_test.dart index e178a862..d792689f 100644 --- a/app/test/features/attention/notify/notification_controller_test.dart +++ b/app/test/features/attention/notify/notification_controller_test.dart @@ -1,16 +1,9 @@ import 'package:flutter_test/flutter_test.dart'; -import 'package:pipelines_app/features/attention/domain/attention_models.dart'; -import 'package:pipelines_app/features/attention/notify/notification_bridge.dart'; import 'package:pipelines_app/features/attention/notify/notification_controller.dart'; -import 'package:pipelines_app/features/attention/notify/notification_ledger.dart'; -import 'package:pipelines_app/features/attention/notify/notification_models.dart'; import 'package:pipelines_app/features/attention/notify/notification_store.dart'; import 'notification_test_support.dart'; -/// Let the controller's fire-and-forget ledger write land. -Future settle() => Future.delayed(Duration.zero); - void main() { group('the seed never notifies', () { test('an already failed and waiting list is silent', () async { @@ -31,7 +24,7 @@ void main() { ]); expect(attention.transitions, isEmpty); - expect(notify.publishTransitions(attention.transitions), 0); + expect(publish(notify, attention), 0); expect(bridge.shown, isEmpty); }); }); @@ -62,11 +55,11 @@ void main() { ), ); - expect(notify.publishTransitions(attention.transitions), 1); + expect(publish(notify, attention), 1); final message = bridge.shown.single; expect(message.title, 'A run failed'); expect(message.body, 'Nightly audit \u00b7 nightly'); - expect(message.tag, '1:Failed@2026-10-22T11:00:00Z'); + expect(message.tag, '1:Failed'); expect(message.runId, 1); }); @@ -84,11 +77,11 @@ void main() { attention.seedRows([runSummary(1, 'running')]); attention.observeFrame(runFrame(1, 'failed')); - expect(notify.publishTransitions(attention.transitions), 1); + expect(publish(notify, attention), 1); attention.observeFrame(runFrame(1, 'failed')); expect(attention.transitions, hasLength(1)); - expect(notify.publishTransitions(attention.transitions), 0); + expect(publish(notify, attention), 0); expect(bridge.shown, hasLength(1)); }); @@ -106,13 +99,13 @@ void main() { attention.seedRows([runSummary(1, 'running')]); attention.observeFrame(runFrame(1, 'failed')); - expect(notify.publishTransitions(attention.transitions), 1); + expect(publish(notify, attention), 1); attention.resetForReconnect(); attention.seedRows([runSummary(1, 'failed')], reconnect: true); - expect(notify.publishTransitions(attention.transitions), 0); + expect(publish(notify, attention), 0); attention.observeFrame(runFrame(1, 'failed')); - expect(notify.publishTransitions(attention.transitions), 0); + expect(publish(notify, attention), 0); expect(bridge.shown, hasLength(1)); }); @@ -128,18 +121,18 @@ void main() { attention.seedRows([runSummary(1, 'running')]); attention.observeFrame(runFrame(1, 'failed')); - expect(notify.publishTransitions(attention.transitions), 1); + expect(publish(notify, attention), 1); await settle(); final restarted = NotificationController(store: store, bridge: bridge); addTearDown(restarted.dispose); await restarted.load(); - expect(restarted.notified, contains('1:Failed@${at(const Duration(minutes: 1))}')); - expect(restarted.publishTransitions(attention.transitions), 0); + expect(restarted.notified, contains('1:Failed')); + expect(publish(restarted, attention), 0); expect(bridge.shown, hasLength(1)); }); - test('a genuinely new failure of the same run notifies again', () async { + test('a later failure of another run notifies independently', () async { final attention = attentionController(); final bridge = FakeNotificationBridge(permission: 'granted'); final notify = NotificationController( @@ -151,253 +144,38 @@ void main() { await attention.load(); await notify.load(); - attention.seedRows([runSummary(1, 'running')]); - attention.observeFrame( - runFrame(1, 'failed', finishedAt: '2026-10-22T09:10:00Z'), - ); - expect(notify.publishTransitions(attention.transitions), 1); - - attention.observeFrame(runFrame(1, 'running')); - attention.observeFrame( - runFrame(1, 'failed', finishedAt: '2026-10-22T11:30:00Z'), - ); - expect(notify.publishTransitions(attention.transitions), 1); - expect(bridge.shown, hasLength(2)); - expect(bridge.shown.map((m) => m.tag).toSet(), hasLength(2)); - }); - }); - - group('a dismissed entry never notifies', () { - test('the detector suppresses it and nothing is posted', () async { - final attention = attentionController(); - final bridge = FakeNotificationBridge(permission: 'granted'); - final notify = NotificationController( - store: MemoryNotificationStore(), - bridge: bridge, - ); - addTearDown(attention.dispose); - addTearDown(notify.dispose); - await attention.load(); - await notify.load(); - - attention.seedRows([runSummary(1, 'running')]); - await attention.dismiss(attentionEntryFor(runSummary(1, 'failed'))!); + attention.seedRows([runSummary(1, 'running'), runSummary(2, 'running')]); attention.observeFrame(runFrame(1, 'failed')); + expect(publish(notify, attention), 1); - expect(attention.transitions, isEmpty); - expect(notify.publishTransitions(attention.transitions), 0); - expect(bridge.shown, isEmpty); + attention.observeFrame(runFrame(2, 'failed')); + expect(publish(notify, attention), 1); + expect(bridge.shown, hasLength(2)); + expect(bridge.shown.map((m) => m.tag), ['1:Failed', '2:Failed']); }); - test('the publish guard records but does not show a dismissed key', () async { + test('a transition for a run that left is never re-posted', () async { + final attention = attentionController(); final bridge = FakeNotificationBridge(permission: 'granted'); final notify = NotificationController( store: MemoryNotificationStore(), bridge: bridge, ); + addTearDown(attention.dispose); addTearDown(notify.dispose); + await attention.load(); await notify.load(); - final transition = transitionFor(4); - expect( - notify.publishTransitions([transition], dismissed: {transition.key}), - 0, - ); - expect(notify.notified, contains(notificationIdentity(transition))); - expect(bridge.shown, isEmpty); - }); - }); + attention.seedRows([runSummary(1, 'running')]); + attention.observeFrame(runFrame(1, 'failed')); + expect(publish(notify, attention), 1); - group('permission is only ever the platform\'s answer', () { - test('an unsupported platform is never asked and never posts', () async { - final bridge = FakeNotificationBridge(supported: false); - final notify = NotificationController( - store: MemoryNotificationStore(), - bridge: bridge, - ); - addTearDown(notify.dispose); - await notify.load(); - expect(notify.permission, NotificationPermissionState.unsupported); - - expect( - await notify.requestPermission(), - NotificationPermissionState.unsupported, - ); - expect(bridge.requests, 0); - expect(notify.publishTransitions([transitionFor(1)]), 0); - expect(bridge.shown, isEmpty); - }); - - test('an insecure page reports needsSecureContext', () async { - final bridge = FakeNotificationBridge(secureContext: false); - final notify = NotificationController( - store: MemoryNotificationStore(), - bridge: bridge, - ); - addTearDown(notify.dispose); - await notify.load(); - expect(notify.permission, NotificationPermissionState.needsSecureContext); - await notify.requestPermission(); - expect(bridge.requests, 0); - }); - - test('a default page is asked once and follows the real answer', () async { - final store = MemoryNotificationStore(); - final bridge = FakeNotificationBridge(answer: 'granted'); - final notify = NotificationController(store: store, bridge: bridge); - addTearDown(notify.dispose); - await notify.load(); - expect(notify.permission, NotificationPermissionState.notRequested); - expect(notify.canNotify, isFalse); - - final state = await notify.requestPermission(); - expect(bridge.requests, 1); - expect(state, NotificationPermissionState.granted); - expect(notify.canNotify, isTrue); - expect(notify.asked, isTrue); - await settle(); - expect(store.stored, contains('"asked":true')); - }); - - test('a denied answer is never re-prompted', () async { - final bridge = FakeNotificationBridge(permission: 'denied'); - final notify = NotificationController( - store: MemoryNotificationStore(), - bridge: bridge, - ); - addTearDown(notify.dispose); - await notify.load(); - expect(notify.permission, NotificationPermissionState.denied); - - expect( - await notify.requestPermission(), - NotificationPermissionState.denied, - ); - expect(bridge.requests, 0); - expect(notify.publishTransitions([transitionFor(1)]), 0); - expect(bridge.shown, isEmpty); - }); - - test('a prompt that grants nothing keeps the honest default wording', () async { - final bridge = FakeNotificationBridge(answer: 'default'); - final notify = NotificationController( - store: MemoryNotificationStore(), - bridge: bridge, - ); - addTearDown(notify.dispose); - await notify.load(); - - final state = await notify.requestPermission(); - expect(state, NotificationPermissionState.notRequested); - expect(notify.asked, isTrue); - expect(notify.canNotify, isFalse); - }); - }); - - group('batching and the tap seam', () { - test('a burst posts a bounded batch in order, then the rest', () async { - final bridge = FakeNotificationBridge(permission: 'granted'); - final notify = NotificationController( - store: MemoryNotificationStore(), - bridge: bridge, - ); - addTearDown(notify.dispose); - await notify.load(); - - final transitions = [for (var id = 1; id <= 7; id++) transitionFor(id)]; - expect(notify.publishTransitions(transitions), 5); - expect(bridge.shown.map((m) => m.runId), [1, 2, 3, 4, 5]); - expect(notify.publishTransitions(transitions), 2); - expect(bridge.shown.map((m) => m.runId), [1, 2, 3, 4, 5, 6, 7]); - }); - - test('a tap reports the run and never navigates here', () async { - final bridge = FakeNotificationBridge(permission: 'granted'); - final notify = NotificationController( - store: MemoryNotificationStore(), - bridge: bridge, - ); - addTearDown(notify.dispose); - await notify.load(); - - final opened = []; - notify.onOpenRun = opened.add; - expect(notify.publishTransitions([transitionFor(3)]), 1); - bridge.taps.single!.call(); - expect(opened, [3]); - }); - }); - - group('an unavailable store cannot reach the UI', () { - test('a failed read and write still notify and never throw', () async { - final store = MemoryNotificationStore() - ..failReads = true - ..failWrites = true; - final bridge = FakeNotificationBridge(permission: 'granted'); - final notify = NotificationController(store: store, bridge: bridge); - addTearDown(notify.dispose); - - await expectLater(notify.load(), completes); - expect(notify.loaded, isTrue); - expect(notify.notified, isEmpty); - - expect(notify.publishTransitions([transitionFor(1)]), 1); - await settle(); + // Publishing the leaving frame forgets the identity; republishing the + // accumulated list afterwards must not resurrect the old alert. + attention.observeFrame(runFrame(1, 'running')); + expect(publish(notify, attention), 0); + expect(publish(notify, attention), 0); expect(bridge.shown, hasLength(1)); }); - - test('a throwing platform post is reported, not propagated', () async { - final bridge = _ThrowingBridge(); - final notify = NotificationController( - store: MemoryNotificationStore(), - bridge: bridge, - ); - addTearDown(notify.dispose); - await notify.load(); - - expect(notify.publishTransitions([transitionFor(1)]), 0); - expect(notify.notified, contains('1:Failed@${at(const Duration(minutes: 1))}')); - }); - }); - - group('the platform seam', () { - test('the non-web bridge reports unsupported honestly', () async { - final bridge = createNotificationBridge(); - expect(bridge.environment().supported, isFalse); - final notify = NotificationController( - store: MemoryNotificationStore(), - bridge: bridge, - ); - addTearDown(notify.dispose); - await notify.load(); - expect(notify.permission, NotificationPermissionState.unsupported); - expect( - bridge.show( - const NotificationMessage( - runId: 1, - title: 'A run failed', - body: 'release', - tag: '1:Failed@x', - ), - ), - isFalse, - ); - }); }); } - -class _ThrowingBridge implements NotificationBridge { - @override - NotificationEnvironment environment() => const NotificationEnvironment( - supported: true, - secureContext: true, - permission: 'granted', - ); - - @override - Future requestPermission() async => 'granted'; - - @override - bool show(NotificationMessage message, {void Function()? onTap}) => - throw StateError('the browser refused to construct a notification'); -} diff --git a/app/test/features/attention/notify/notification_delivery_test.dart b/app/test/features/attention/notify/notification_delivery_test.dart new file mode 100644 index 00000000..5573cc8d --- /dev/null +++ b/app/test/features/attention/notify/notification_delivery_test.dart @@ -0,0 +1,238 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/attention/domain/attention_models.dart'; +import 'package:pipelines_app/features/attention/notify/notification_bridge.dart'; +import 'package:pipelines_app/features/attention/notify/notification_controller.dart'; +import 'package:pipelines_app/features/attention/notify/notification_models.dart'; +import 'package:pipelines_app/features/attention/notify/notification_store.dart'; + +import 'notification_test_support.dart'; + +void main() { + group('a dismissed entry never notifies', () { + test('the detector suppresses it and nothing is posted', () async { + final attention = attentionController(); + final bridge = FakeNotificationBridge(permission: 'granted'); + final notify = NotificationController( + store: MemoryNotificationStore(), + bridge: bridge, + ); + addTearDown(attention.dispose); + addTearDown(notify.dispose); + await attention.load(); + await notify.load(); + + attention.seedRows([runSummary(1, 'running')]); + await attention.dismiss(attentionEntryFor(runSummary(1, 'failed'))!); + attention.observeFrame(runFrame(1, 'failed')); + + expect(attention.transitions, isEmpty); + expect(publish(notify, attention), 0); + expect(bridge.shown, isEmpty); + }); + + test( + 'the publish guard records but does not show a dismissed key', + () async { + final bridge = FakeNotificationBridge(permission: 'granted'); + final notify = NotificationController( + store: MemoryNotificationStore(), + bridge: bridge, + ); + addTearDown(notify.dispose); + await notify.load(); + + final transition = transitionFor(4); + expect( + notify.publishTransitions( + [transition], + qualifying: {transition.key}, + dismissed: {transition.key}, + ), + 0, + ); + expect(notify.notified, contains(transition.key)); + expect(bridge.shown, isEmpty); + }, + ); + }); + + group('batching and the tap seam', () { + test('a burst posts a bounded batch in order, then the rest', () async { + final bridge = FakeNotificationBridge(permission: 'granted'); + final notify = NotificationController( + store: MemoryNotificationStore(), + bridge: bridge, + ); + addTearDown(notify.dispose); + await notify.load(); + + final transitions = [for (var id = 1; id <= 7; id++) transitionFor(id)]; + final qualifying = {for (final t in transitions) t.key}; + expect(notify.publishTransitions(transitions, qualifying: qualifying), 5); + expect(bridge.shown.map((m) => m.runId), [1, 2, 3, 4, 5]); + expect(notify.publishTransitions(transitions, qualifying: qualifying), 2); + expect(bridge.shown.map((m) => m.runId), [1, 2, 3, 4, 5, 6, 7]); + }); + + test('a tap reports the run and never navigates here', () async { + final bridge = FakeNotificationBridge(permission: 'granted'); + final notify = NotificationController( + store: MemoryNotificationStore(), + bridge: bridge, + ); + addTearDown(notify.dispose); + await notify.load(); + + final opened = []; + notify.onOpenRun = opened.add; + expect( + notify.publishTransitions([transitionFor(3)], qualifying: {'3:Failed'}), + 1, + ); + bridge.taps.single!.call(); + expect(opened, [3]); + }); + }); + + group('the ledger cannot be read into by a caller', () { + test('notified is an unmodifiable copy', () async { + final bridge = FakeNotificationBridge(permission: 'granted'); + final notify = NotificationController( + store: MemoryNotificationStore(), + bridge: bridge, + ); + addTearDown(notify.dispose); + await notify.load(); + + expect( + notify.publishTransitions([transitionFor(1)], qualifying: {'1:Failed'}), + 1, + ); + expect(notify.notified, {'1:Failed'}); + expect(() => notify.notified.add('9:Failed'), throwsUnsupportedError); + expect(notify.notified, {'1:Failed'}); + }); + }); + + group('an unavailable store cannot reach the UI', () { + test('a failed read and write still notify and never throw', () async { + final store = MemoryNotificationStore() + ..failReads = true + ..failWrites = true; + final bridge = FakeNotificationBridge(permission: 'granted'); + final notify = NotificationController(store: store, bridge: bridge); + addTearDown(notify.dispose); + + await expectLater(notify.load(), completes); + expect(notify.loaded, isTrue); + expect(notify.notified, isEmpty); + + expect( + notify.publishTransitions([transitionFor(1)], qualifying: {'1:Failed'}), + 1, + ); + await settle(); + expect(bridge.shown, hasLength(1)); + }); + + test('a throwing platform post is reported, not propagated', () async { + final bridge = _ThrowingBridge(); + final notify = NotificationController( + store: MemoryNotificationStore(), + bridge: bridge, + ); + addTearDown(notify.dispose); + await notify.load(); + + expect( + notify.publishTransitions([transitionFor(1)], qualifying: {'1:Failed'}), + 0, + ); + expect(notify.notified, contains('1:Failed')); + }); + + test('ledger writes land in call order, one at a time', () async { + final store = _SlowStore(); + final bridge = FakeNotificationBridge(permission: 'granted'); + final notify = NotificationController(store: store, bridge: bridge); + addTearDown(notify.dispose); + await notify.load(); + + notify.publishTransitions([transitionFor(1)], qualifying: {'1:Failed'}); + notify.publishTransitions( + [transitionFor(2)], + qualifying: {'1:Failed', '2:Failed'}, + ); + await Future.delayed(const Duration(milliseconds: 40)); + + expect(store.maxActive, 1, reason: 'the writes must be serialized'); + expect(store.stored, contains('"1:Failed"')); + expect(store.stored, contains('"2:Failed"')); + expect(store.writes.last, store.stored); + }); + }); + + group('the platform seam', () { + test('the non-web bridge reports unsupported honestly', () async { + final bridge = createNotificationBridge(); + expect(bridge.environment().supported, isFalse); + final notify = NotificationController( + store: MemoryNotificationStore(), + bridge: bridge, + ); + addTearDown(notify.dispose); + await notify.load(); + expect(notify.permission, NotificationPermissionState.unsupported); + expect( + bridge.show( + const NotificationMessage( + runId: 1, + title: 'A run failed', + body: 'release', + tag: '1:Failed', + ), + ), + isFalse, + ); + }); + }); +} + +/// A store whose writes take a tick, so a racing implementation would overlap +/// them and the last value to land would be the older snapshot. +class _SlowStore implements NotificationStore { + String? stored; + int active = 0; + int maxActive = 0; + final List writes = []; + + @override + Future read() async => stored; + + @override + Future write(String value) async { + active++; + if (active > maxActive) maxActive = active; + await Future.delayed(const Duration(milliseconds: 2)); + stored = value; + writes.add(value); + active--; + return true; + } +} + +class _ThrowingBridge implements NotificationBridge { + @override + NotificationEnvironment environment() => const NotificationEnvironment( + supported: true, + secureContext: true, + permission: 'granted', + ); + + @override + Future requestPermission() async => 'granted'; + + @override + bool show(NotificationMessage message, {void Function()? onTap}) => + throw StateError('the browser refused to construct a notification'); +} diff --git a/app/test/features/attention/notify/notification_ledger_test.dart b/app/test/features/attention/notify/notification_ledger_test.dart index b4658cf4..9dde970a 100644 --- a/app/test/features/attention/notify/notification_ledger_test.dart +++ b/app/test/features/attention/notify/notification_ledger_test.dart @@ -4,21 +4,17 @@ import 'package:pipelines_app/features/attention/notify/notification_ledger.dart import 'notification_test_support.dart'; void main() { - group('the identity carries the finished marker', () { - test('a recorded finish time distinguishes two failures of one run', () { + group('the identity is the run and kind', () { + test('two failures of one run are the same announced state', () { final first = transitionFor(7, finishedAt: '2026-10-22T09:10:00Z'); final second = transitionFor(7, finishedAt: '2026-10-22T11:30:00Z'); - expect(notificationIdentity(first), '7:Failed@2026-10-22T09:10:00Z'); - expect(notificationIdentity(second), '7:Failed@2026-10-22T11:30:00Z'); - expect(notificationIdentity(first), isNot(notificationIdentity(second))); + expect(notificationIdentity(first), '7:Failed'); + expect(notificationIdentity(second), '7:Failed'); }); - test('a run without a finish time falls back to its creation time', () { + test('a waiting run needs no finish time to have an identity', () { final entry = transitionFor(7, status: 'waiting', finishedAt: ''); - expect( - notificationIdentity(entry), - '7:Decision@${attentionNow.subtract(const Duration(hours: 1)).toIso8601String()}', - ); + expect(notificationIdentity(entry), '7:Decision'); }); test('the kind separates a decision from a failure of one run', () { @@ -29,31 +25,88 @@ void main() { }); }); + group('the qualifying set is the attention surface\'s own keys', () { + test('only failed and human-waiting runs qualify', () { + expect( + notificationQualifyingKeys([ + runSummary(1, 'failed'), + runSummary(2, 'waiting'), + runSummary(3, 'running'), + runSummary(4, 'succeeded'), + runSummary(5, 'queued'), + runSummary(6, 'waiting', exportPending: 2), + ]), + {'1:Failed', '2:Decision'}, + ); + }); + + test('a duplicate row and a malformed id add nothing', () { + expect( + notificationQualifyingKeys([ + runSummary(1, 'failed'), + runSummary(1, 'failed'), + {'id': 0, 'status': 'failed'}, + {'id': 'not a run', 'status': 'failed'}, + ]), + {'1:Failed'}, + ); + expect(notificationQualifyingKeys(null), isEmpty); + }); + + test('the frame key form is read too', () { + expect(notificationQualifyingKeys([runFrame(9, 'failed')]), {'9:Failed'}); + }); + }); + group('the ledger records identities', () { test('recording is idempotent and never mutates the original', () { const base = NotificationLedger(); - final once = base.recording('7:Failed@a'); - final twice = once.recording('7:Failed@a'); + final once = base.recording('7:Failed'); + final twice = once.recording('7:Failed'); expect(base.notified, isEmpty); - expect(once.hasNotified('7:Failed@a'), isTrue); - expect(twice.notified, {'7:Failed@a'}); + expect(once.hasNotified('7:Failed'), isTrue); + expect(twice.notified, {'7:Failed'}); }); test('asked is carried without touching the identities', () { - final asked = const NotificationLedger( - notified: {'a'}, - ).withAsked(true); + final asked = const NotificationLedger(notified: {'a'}).withAsked(true); expect(asked.asked, isTrue); expect(asked.notified, {'a'}); }); }); + group('pruning keeps only the current qualifying run', () { + test('a run that left the state is forgotten; asked survives', () { + final ledger = const NotificationLedger( + notified: {'7:Decision', '8:Failed'}, + ).withAsked(true); + final pruned = ledger.pruning({'8:Failed'}); + expect(pruned.notified, {'8:Failed'}); + expect(pruned.asked, isTrue); + }); + + test('nothing to drop returns the same ledger', () { + const ledger = NotificationLedger(notified: {'7:Failed'}); + expect(identical(ledger.pruning({'7:Failed'}), ledger), isTrue); + }); + + test('a timestamped identity from an older build is dropped', () { + final old = decodeNotificationLedger( + '{"asked":false,"notified":["7:Decision@2026-10-22T11:00:00.000"]}', + ); + expect(old.notified, hasLength(1)); + expect(old.pruning({'7:Decision'}).notified, isEmpty); + }); + }); + group('persistence is total', () { test('a round trip keeps the asked flag and the identities', () { final ledger = const NotificationLedger( notified: {'b', 'a'}, ).withAsked(true); - final decoded = decodeNotificationLedger(encodeNotificationLedger(ledger)); + final decoded = decodeNotificationLedger( + encodeNotificationLedger(ledger), + ); expect(decoded.asked, isTrue); expect(decoded.notified, {'a', 'b'}); }); @@ -75,8 +128,9 @@ void main() { expect(decodeNotificationLedger('[]').notified, isEmpty); expect(decodeNotificationLedger('"text"').notified, isEmpty); expect( - decodeNotificationLedger('{"asked":"yes","notified":[1,null,"a",""]}') - .notified, + decodeNotificationLedger( + '{"asked":"yes","notified":[1,null,"a",""]}', + ).notified, {'a'}, ); expect( diff --git a/app/test/features/attention/notify/notification_models_test.dart b/app/test/features/attention/notify/notification_models_test.dart index 2a3b02ec..90244413 100644 --- a/app/test/features/attention/notify/notification_models_test.dart +++ b/app/test/features/attention/notify/notification_models_test.dart @@ -128,7 +128,10 @@ void main() { 'created_at': '2026-10-22T09:00:00Z', 'finished_at': '2026-10-22T09:10:00Z', })!; - expect(notificationAlertBody(entry), 'Nightly audit \u00b7 nightly-audit'); + expect( + notificationAlertBody(entry), + 'Nightly audit \u00b7 nightly-audit', + ); }); test('a blank or equal pipeline is never repeated', () { diff --git a/app/test/features/attention/notify/notification_permission_test.dart b/app/test/features/attention/notify/notification_permission_test.dart new file mode 100644 index 00000000..4feff63b --- /dev/null +++ b/app/test/features/attention/notify/notification_permission_test.dart @@ -0,0 +1,103 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/attention/notify/notification_controller.dart'; +import 'package:pipelines_app/features/attention/notify/notification_models.dart'; +import 'package:pipelines_app/features/attention/notify/notification_store.dart'; + +import 'notification_test_support.dart'; + +void main() { + group('permission is only ever the platform\'s answer', () { + test('an unsupported platform is never asked and never posts', () async { + final bridge = FakeNotificationBridge(supported: false); + final notify = NotificationController( + store: MemoryNotificationStore(), + bridge: bridge, + ); + addTearDown(notify.dispose); + await notify.load(); + expect(notify.permission, NotificationPermissionState.unsupported); + + expect( + await notify.requestPermission(), + NotificationPermissionState.unsupported, + ); + expect(bridge.requests, 0); + expect( + notify.publishTransitions([transitionFor(1)], qualifying: {'1:Failed'}), + 0, + ); + expect(bridge.shown, isEmpty); + }); + + test('an insecure page reports needsSecureContext', () async { + final bridge = FakeNotificationBridge(secureContext: false); + final notify = NotificationController( + store: MemoryNotificationStore(), + bridge: bridge, + ); + addTearDown(notify.dispose); + await notify.load(); + expect(notify.permission, NotificationPermissionState.needsSecureContext); + await notify.requestPermission(); + expect(bridge.requests, 0); + }); + + test('a default page is asked once and follows the real answer', () async { + final store = MemoryNotificationStore(); + final bridge = FakeNotificationBridge(answer: 'granted'); + final notify = NotificationController(store: store, bridge: bridge); + addTearDown(notify.dispose); + await notify.load(); + expect(notify.permission, NotificationPermissionState.notRequested); + expect(notify.canNotify, isFalse); + + final state = await notify.requestPermission(); + expect(bridge.requests, 1); + expect(state, NotificationPermissionState.granted); + expect(notify.canNotify, isTrue); + expect(notify.asked, isTrue); + await settle(); + expect(store.stored, contains('"asked":true')); + }); + + test('a denied answer is never re-prompted', () async { + final bridge = FakeNotificationBridge(permission: 'denied'); + final notify = NotificationController( + store: MemoryNotificationStore(), + bridge: bridge, + ); + addTearDown(notify.dispose); + await notify.load(); + expect(notify.permission, NotificationPermissionState.denied); + + expect( + await notify.requestPermission(), + NotificationPermissionState.denied, + ); + expect(bridge.requests, 0); + expect( + notify.publishTransitions([transitionFor(1)], qualifying: {'1:Failed'}), + 0, + ); + expect(bridge.shown, isEmpty); + }); + + test( + 'a prompt that grants nothing keeps the honest default wording', + () async { + final bridge = FakeNotificationBridge(answer: 'default'); + final notify = NotificationController( + store: MemoryNotificationStore(), + bridge: bridge, + ); + addTearDown(notify.dispose); + await notify.load(); + + final state = await notify.requestPermission(); + expect(state, NotificationPermissionState.notRequested); + expect(notify.asked, isTrue); + expect(notify.canNotify, isFalse); + }, + ); + }); +} diff --git a/app/test/features/attention/notify/notification_reentry_test.dart b/app/test/features/attention/notify/notification_reentry_test.dart new file mode 100644 index 00000000..baece833 --- /dev/null +++ b/app/test/features/attention/notify/notification_reentry_test.dart @@ -0,0 +1,93 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/attention/notify/notification_controller.dart'; +import 'package:pipelines_app/features/attention/notify/notification_store.dart'; + +import 'notification_test_support.dart'; + +/// A run that leaves a qualifying state and enters it again is a new event. +/// +/// A waiting run has no `finished_at`, and its creation time never changes, so +/// both gates of one run carry exactly the same timestamps. These tests pin the +/// behaviour that was silently dropped when the identity included that marker. +void main() { + test('a second decision gate of the same run notifies again', () async { + final attention = attentionController(); + final bridge = FakeNotificationBridge(permission: 'granted'); + final notify = NotificationController( + store: MemoryNotificationStore(), + bridge: bridge, + ); + addTearDown(attention.dispose); + addTearDown(notify.dispose); + await attention.load(); + await notify.load(); + + attention.seedRows([runSummary(7, 'running')]); + attention.observeFrame(runFrame(7, 'waiting', finishedAt: '')); + expect(publish(notify, attention), 1); + expect(bridge.shown.single.tag, '7:Decision'); + + attention.observeFrame(runFrame(7, 'running')); + expect(publish(notify, attention), 0); + + attention.observeFrame(runFrame(7, 'waiting', finishedAt: '')); + expect(attention.transitions, hasLength(2)); + expect(publish(notify, attention), 1); + expect(bridge.shown, hasLength(2)); + // The browser coalesces by run+kind, so both alerts share one tag. + expect(bridge.shown.map((m) => m.tag).toSet(), {'7:Decision'}); + }); + + test( + 'a second decision gate notifies even without the leaving publish', + () async { + final attention = attentionController(); + final bridge = FakeNotificationBridge(permission: 'granted'); + final notify = NotificationController( + store: MemoryNotificationStore(), + bridge: bridge, + ); + addTearDown(attention.dispose); + addTearDown(notify.dispose); + await attention.load(); + await notify.load(); + + attention.seedRows([runSummary(7, 'running')]); + attention.observeFrame(runFrame(7, 'waiting', finishedAt: '')); + expect(publish(notify, attention), 1); + + // The caller misses the frame that leaves the state; the detector still + // creates a new instance for the next gate, so it must notify again. + attention.observeFrame(runFrame(7, 'running')); + attention.observeFrame(runFrame(7, 'waiting', finishedAt: '')); + expect(publish(notify, attention), 1); + expect(bridge.shown, hasLength(2)); + expect(bridge.shown.map((m) => m.tag).toSet(), {'7:Decision'}); + }, + ); + + test('a coalesced backlog of two gates notifies once', () async { + final attention = attentionController(); + final bridge = FakeNotificationBridge(permission: 'granted'); + final notify = NotificationController( + store: MemoryNotificationStore(), + bridge: bridge, + ); + addTearDown(attention.dispose); + addTearDown(notify.dispose); + await attention.load(); + await notify.load(); + + attention.seedRows([runSummary(7, 'running')]); + attention.observeFrame(runFrame(7, 'waiting', finishedAt: '')); + attention.observeFrame(runFrame(7, 'running')); + attention.observeFrame(runFrame(7, 'waiting', finishedAt: '')); + expect(attention.transitions, hasLength(2)); + + // Both gates were folded before the caller published; the current state is + // what the operator should be told about, once. + expect(publish(notify, attention), 1); + expect(bridge.shown, hasLength(1)); + expect(bridge.shown.single.tag, '7:Decision'); + }); +} diff --git a/app/test/features/attention/notify/notification_test_support.dart b/app/test/features/attention/notify/notification_test_support.dart index a8dd35a8..8e0db312 100644 --- a/app/test/features/attention/notify/notification_test_support.dart +++ b/app/test/features/attention/notify/notification_test_support.dart @@ -1,6 +1,8 @@ import 'package:pipelines_app/features/attention/domain/attention_models.dart'; import 'package:pipelines_app/features/attention/domain/attention_transitions.dart'; import 'package:pipelines_app/features/attention/notify/notification_bridge.dart'; +import 'package:pipelines_app/features/attention/notify/notification_controller.dart'; +import 'package:pipelines_app/features/attention/notify/notification_ledger.dart'; import 'package:pipelines_app/features/attention/notify/notification_models.dart'; import 'package:pipelines_app/features/attention/runtime/attention_controller.dart'; import 'package:pipelines_app/features/attention/runtime/attention_store.dart'; @@ -27,13 +29,19 @@ Map runSummary( 'status': status, 'diagnostic': diagnostic, 'created_at': at(age), - 'finished_at': at(age - const Duration(minutes: 5)), + // The server leaves finished_at empty for a waiting run (and for one still in + // flight); only a settled run carries a finish time. + 'finished_at': status == 'waiting' || status == 'running' + ? '' + : at(age - const Duration(minutes: 5)), 'export_pending_sequence': ?exportPending, ...extra, }; -/// One qualifying pushed frame for a run, as `run_event` carries it. A blank -/// [finishedAt] leaves the marker to fall back to the creation time. +/// One qualifying pushed frame for a run, as `run_event` carries it. +/// +/// A waiting or running frame has no `finished_at`, matching the server; pass +/// [finishedAt] only to describe a settled run. Map runFrame( int id, String status, { @@ -49,7 +57,11 @@ Map runFrame( 'status': status, 'diagnostic': diagnostic, 'created_at': at(const Duration(hours: 1)), - 'finished_at': finishedAt ?? at(const Duration(minutes: 1)), + 'finished_at': + finishedAt ?? + (status == 'waiting' || status == 'running' + ? '' + : at(const Duration(minutes: 1))), }; /// One transition for a run that just entered [status], for batch tests. @@ -65,6 +77,18 @@ AttentionTransition transitionFor( )!, ); +/// Let the controller's fire-and-forget ledger write land. +Future settle() => Future.delayed(Duration.zero); + +/// Publish exactly the way the manager wires it: the accumulated transitions, +/// the current rows and the dismissed set from the same attention snapshot. +int publish(NotificationController notify, AttentionController attention) => + notify.publishTransitions( + attention.transitions, + qualifying: notificationQualifyingKeys(attention.rows), + dismissed: attention.dismissed, + ); + AttentionController attentionController() => AttentionController(store: MemoryAttentionStore(), now: () => attentionNow); diff --git a/app/tool/notification_probe.dart b/app/tool/notification_probe.dart index ec849ab7..ff88ccb2 100644 --- a/app/tool/notification_probe.dart +++ b/app/tool/notification_probe.dart @@ -7,6 +7,7 @@ import 'package:flutter/material.dart'; import 'package:pipelines_app/features/attention/domain/attention_models.dart'; import 'package:pipelines_app/features/attention/notify/notification_bridge.dart'; import 'package:pipelines_app/features/attention/notify/notification_controller.dart'; +import 'package:pipelines_app/features/attention/notify/notification_ledger.dart'; import 'package:pipelines_app/features/attention/notify/notification_models.dart'; import 'package:pipelines_app/features/attention/notify/notification_store.dart'; import 'package:pipelines_app/features/attention/runtime/attention_controller.dart'; @@ -17,8 +18,9 @@ import 'package:pipelines_app/features/attention/ui/notification_permission_tile /// /// It drives the real [NotificationController] over the real web bridge, so a /// browser drive can prove the seed is silent, one live transition raises -/// exactly one notification with the entry's own words and identity, a dismissed -/// or replayed transition raises none, and the Settings tile reads honestly in +/// exactly one notification with the entry's own words and run+kind identity, a +/// dismissed or replayed transition raises none, a second decision gate of one +/// run raises a fresh notification, and the Settings tile reads honestly in /// every state on both hosts. Nothing here opens a socket or touches real /// operator data; the store is in memory. void main() { @@ -89,7 +91,10 @@ Map _summary( 'status': status, 'diagnostic': diagnostic, 'created_at': _at(const Duration(hours: 1)), - 'finished_at': _at(const Duration(minutes: 55)), + // The server leaves finished_at empty while a run is in flight or waiting. + 'finished_at': status == 'waiting' || status == 'running' + ? '' + : _at(const Duration(minutes: 55)), }; Map _frame( @@ -105,9 +110,20 @@ Map _frame( 'title': title ?? 'Run $id', 'status': status, 'diagnostic': diagnostic, - 'finished_at': _at(const Duration(minutes: 1)), + 'finished_at': status == 'waiting' || status == 'running' + ? '' + : _at(const Duration(minutes: 1)), }; +/// Publish exactly as the manager wires it: the accumulated transitions and the +/// current qualifying keys from the same attention snapshot. +int _publish(NotificationController notify, AttentionController attention) => + notify.publishTransitions( + attention.transitions, + qualifying: notificationQualifyingKeys(attention.rows), + dismissed: attention.dismissed, + ); + /// Runs one notification scenario against the real bridge, then reports it and /// draws the live permission tile underneath. class _NotificationProbe extends StatefulWidget { @@ -147,27 +163,37 @@ class _NotificationProbeState extends State<_NotificationProbe> { _summary(1, 'failed', diagnostic: 'Stage 3 stopped'), _summary(2, 'waiting'), ]); - notify.publishTransitions(attention.transitions); + _publish(notify, attention); case 'dismissed': attention.seedRows([_summary(1, 'running')]); await attention.dismiss(attentionEntryFor(_summary(1, 'failed'))!); attention.observeFrame(_frame(1, 'failed')); - notify.publishTransitions(attention.transitions); + _publish(notify, attention); case 'reconnect': attention.seedRows([_summary(1, 'running')]); attention.observeFrame(_frame(1, 'failed')); - notify.publishTransitions(attention.transitions); + _publish(notify, attention); attention.resetForReconnect(); attention.seedRows([_summary(1, 'failed')], reconnect: true); - notify.publishTransitions(attention.transitions); + _publish(notify, attention); attention.observeFrame(_frame(1, 'failed')); - notify.publishTransitions(attention.transitions); + _publish(notify, attention); + case 'secondgate': + // A waiting run has no finished_at, so two gates of one run carry the + // same timestamps; leaving the state is what makes the second new. + attention.seedRows([_summary(7, 'running')]); + attention.observeFrame(_frame(7, 'waiting')); + _publish(notify, attention); + attention.observeFrame(_frame(7, 'running')); + _publish(notify, attention); + attention.observeFrame(_frame(7, 'waiting')); + _publish(notify, attention); case 'denied': case 'unsupported': case 'default': attention.seedRows([_summary(1, 'running')]); attention.observeFrame(_frame(1, 'failed')); - notify.publishTransitions(attention.transitions); + _publish(notify, attention); default: attention.seedRows([_summary(1, 'running', name: 'nightly')]); attention.observeFrame( @@ -179,7 +205,7 @@ class _NotificationProbeState extends State<_NotificationProbe> { diagnostic: 'Stage 3 stopped', ), ); - notify.publishTransitions(attention.transitions); + _publish(notify, attention); } if (!mounted) return; diff --git a/app/tool/notification_probe.mjs b/app/tool/notification_probe.mjs index 7660adfe..1487c7ac 100644 --- a/app/tool/notification_probe.mjs +++ b/app/tool/notification_probe.mjs @@ -7,10 +7,11 @@ // replaced with a recording spy before the app loads, and the real browser // permission is granted (or denied) through CDP, so the drive proves the real // bridge's behaviour: the initial seed raises nothing, one live transition -// raises exactly one notification with the entry's own words and run+kind+marker -// identity, a dismissed transition and a reconnect replay raise none, and the -// Settings tile reads honestly in every state on both hosts at 320 logical px -// and 2x text. One PNG is written per captured state. +// raises exactly one notification with the entry's own words and run+kind +// identity, a dismissed transition and a reconnect replay raise none, a second +// decision gate of one run raises a fresh notification (the waiting shape has no +// finished_at), and the Settings tile reads honestly in every state on both +// hosts at 320 logical px and 2x text. One PNG is written per captured state. import { createServer } from 'node:http'; import { spawn } from 'node:child_process'; import { once } from 'node:events'; @@ -217,7 +218,7 @@ try { check('transition count', posted.length === 1, JSON.stringify(posted)); check('transition title', posted[0].title === 'A run failed', JSON.stringify(posted[0])); check('transition body', posted[0].body === 'Nightly audit · nightly', JSON.stringify(posted[0])); - check('transition identity', /^1:Failed@/.test(posted[0].tag), JSON.stringify(posted[0])); + check('transition identity', posted[0].tag === '1:Failed', JSON.stringify(posted[0])); await capture('notification-transition-material-dark-320-2x.png'); captures.push('notification-transition-material-dark-320-2x.png'); @@ -233,6 +234,24 @@ try { check('reconnect posted once', reconnectReport.includes('posted=1'), reconnectReport); check('reconnect count', JSON.parse(await notifications()).length === 1, await notifications()); + // 4b. A second decision gate of one run notifies again. The waiting frames + // carry no finished_at, so the run's timestamps cannot tell the gates apart. + await navigate({ mode: 'secondgate' }); + const secondGateReport = await waitForReport('secondgate'); + check('second gate posted twice', secondGateReport.includes('posted=2'), secondGateReport); + const gates = JSON.parse(await notifications()); + check('second gate count', gates.length === 2, JSON.stringify(gates)); + check( + 'second gate identity', + gates.every((item) => item.tag === '7:Decision'), + JSON.stringify(gates), + ); + check( + 'second gate title', + gates.every((item) => item.title === 'A run needs your decision'), + JSON.stringify(gates), + ); + // 5. A denied page is honest and posts nothing. await deny(); await navigate({ mode: 'denied', semantics: true }); From cc7eba59b69979ab6dfc2f07f64e7fdd923bc46d Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 22 Oct 2026 02:05:20 +0100 Subject: [PATCH 11/13] feat(app): graph pan, zoom and expanded view --- .../graph/viewport/graph_expanded_view.dart | 162 ++++++++ .../graph/viewport/graph_viewport.dart | 195 +++++++++ .../viewport/graph_viewport_controller.dart | 171 ++++++++ .../graph/viewport/graph_viewport_math.dart | 92 +++++ .../widgets/definition_graph_canvas.dart | 76 ++++ .../graph/widgets/definition_graph_view.dart | 99 ++--- .../graph/widgets/run_graph_canvas.dart | 89 ++--- .../graph/widgets/run_graph_header.dart | 117 ++++++ .../graph/widgets/run_graph_view.dart | 189 +++++---- app/notes/G2-zoom.md | 144 +++++++ .../viewport/graph_expanded_view_test.dart | 213 ++++++++++ .../graph_viewport_controls_test.dart | 99 +++++ .../viewport/graph_viewport_fixtures.dart | 167 ++++++++ .../viewport/graph_viewport_math_test.dart | 134 +++++++ .../graph/viewport/graph_viewport_test.dart | 238 +++++++++++ .../widgets/definition_graph_view_test.dart | 68 +++- .../graph/widgets/run_graph_view_test.dart | 27 +- app/tool/graph_zoom_probe.dart | 170 ++++++++ app/tool/graph_zoom_probe.mjs | 372 ++++++++++++++++++ 19 files changed, 2622 insertions(+), 200 deletions(-) create mode 100644 app/lib/features/graph/viewport/graph_expanded_view.dart create mode 100644 app/lib/features/graph/viewport/graph_viewport.dart create mode 100644 app/lib/features/graph/viewport/graph_viewport_controller.dart create mode 100644 app/lib/features/graph/viewport/graph_viewport_math.dart create mode 100644 app/lib/features/graph/widgets/definition_graph_canvas.dart create mode 100644 app/lib/features/graph/widgets/run_graph_header.dart create mode 100644 app/notes/G2-zoom.md create mode 100644 app/test/features/graph/viewport/graph_expanded_view_test.dart create mode 100644 app/test/features/graph/viewport/graph_viewport_controls_test.dart create mode 100644 app/test/features/graph/viewport/graph_viewport_fixtures.dart create mode 100644 app/test/features/graph/viewport/graph_viewport_math_test.dart create mode 100644 app/test/features/graph/viewport/graph_viewport_test.dart create mode 100644 app/tool/graph_zoom_probe.dart create mode 100644 app/tool/graph_zoom_probe.mjs diff --git a/app/lib/features/graph/viewport/graph_expanded_view.dart b/app/lib/features/graph/viewport/graph_expanded_view.dart new file mode 100644 index 00000000..a934c18b --- /dev/null +++ b/app/lib/features/graph/viewport/graph_expanded_view.dart @@ -0,0 +1,162 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../ui/adaptive/host.dart'; +import 'graph_viewport.dart'; +import 'graph_viewport_controller.dart'; + +/// The expanded presentation's close wording (`Close`). +const String graphExpandedClose = 'Close'; + +/// Builds the same canvas for another viewport, with the selection that +/// presentation is showing. +typedef GraphExpandedCanvasBuilder = + Widget Function( + BuildContext context, + String? selectedStage, + ValueChanged onSelected, + ); + +/// A native full-screen presentation of one graph canvas. +/// +/// It fits the graph into the larger box (as the web does when its panel +/// expands), keeps the selected node selected, and lets a tap in the larger +/// canvas update that selection through [onSelected]. Closing pops the route; +/// the inline canvas was never changed, so it returns to its previous state. +class GraphExpandedView extends StatefulWidget { + const GraphExpandedView({ + super.key, + required this.contentSize, + required this.canvasBuilder, + required this.title, + required this.onSelected, + this.selectedStage, + this.header, + }); + + /// The measured graph extent, as in the inline canvas. + final Size contentSize; + + final GraphExpandedCanvasBuilder canvasBuilder; + + /// The presentation's native title, e.g. `Run graph`. + final String title; + + /// Reports a node activated in the expanded canvas. + final ValueChanged onSelected; + + /// Optional fixed content above the canvas, e.g. a legend that explains the + /// graph's marks. It stays outside the pan/zoom transform. + final Widget? header; + + final String? selectedStage; + + @override + State createState() => _GraphExpandedViewState(); +} + +class _GraphExpandedViewState extends State { + final GraphViewportController _controller = GraphViewportController(); + late String? _selected = widget.selectedStage; + + @override + void didUpdateWidget(GraphExpandedView oldWidget) { + super.didUpdateWidget(oldWidget); + if (widget.selectedStage != oldWidget.selectedStage) { + _selected = widget.selectedStage; + } + } + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + void _select(String key) { + setState(() => _selected = key); + widget.onSelected(key); + } + + void _close() => Navigator.of(context).maybePop(); + + @override + Widget build(BuildContext context) { + final viewport = GraphViewport( + key: const Key('graph-expanded-viewport'), + controller: _controller, + contentSize: widget.contentSize, + // The larger box fits the whole graph, as the web does when its panel + // expands; a later resize re-fits until the reader pans or zooms, then + // only clamps. + child: widget.canvasBuilder(context, _selected, _select), + ); + final body = widget.header == null + ? viewport + : Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + widget.header!, + Expanded(child: viewport), + ], + ); + if (usesCupertinoHost(context)) { + return CupertinoPageScaffold( + navigationBar: CupertinoNavigationBar( + automaticallyImplyLeading: false, + middle: Text(widget.title), + trailing: CupertinoButton( + key: const Key('graph-expanded-close'), + padding: EdgeInsets.zero, + onPressed: _close, + child: const Text(graphExpandedClose), + ), + ), + child: SafeArea(child: body), + ); + } + return Scaffold( + appBar: AppBar( + title: Text(widget.title), + automaticallyImplyLeading: false, + actions: [ + TextButton( + key: const Key('graph-expanded-close'), + onPressed: _close, + child: const Text(graphExpandedClose), + ), + ], + ), + body: SafeArea(child: body), + ); + } +} + +/// Pushes [GraphExpandedView] with the host's native full-screen transition. +/// +/// This is the seam a Graph tab or run detail can call: pass the measured +/// content size and a builder that draws the same canvas for the supplied +/// selection. The expanded canvas fits that size; the inline canvas is +/// untouched. +Future openGraphExpanded( + BuildContext context, { + required Size contentSize, + required GraphExpandedCanvasBuilder canvasBuilder, + required String title, + required ValueChanged onSelected, + String? selectedStage, + Widget? header, +}) { + final page = GraphExpandedView( + contentSize: contentSize, + canvasBuilder: canvasBuilder, + title: title, + onSelected: onSelected, + selectedStage: selectedStage, + header: header, + ); + final route = usesCupertinoHost(context) + ? CupertinoPageRoute(fullscreenDialog: true, builder: (_) => page) + : MaterialPageRoute(fullscreenDialog: true, builder: (_) => page); + return Navigator.of(context).push(route); +} diff --git a/app/lib/features/graph/viewport/graph_viewport.dart b/app/lib/features/graph/viewport/graph_viewport.dart new file mode 100644 index 00000000..c0bb2490 --- /dev/null +++ b/app/lib/features/graph/viewport/graph_viewport.dart @@ -0,0 +1,195 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../ui/adaptive/host.dart'; +import 'graph_viewport_controller.dart'; + +/// The fit control's web wording (`Fit graph to view`). +const String graphFitLabel = 'Fit graph to view'; + +/// The expand control's web wording (`Expand graph`). +const String graphExpandLabel = 'Expand graph'; + +/// A bounded graph canvas with the host's own pan, pinch, wheel and trackpad +/// zoom, plus a fit control and an optional expanded presentation. +/// +/// [controller] owns the transform, so a caller can read or restore a +/// [GraphViewportSnapshot]. Gestures are consumed only inside this widget's +/// box: an ancestor scroll view keeps scrolling everywhere else, and a tap +/// that does not move still reaches the native node under the pointer. +class GraphViewport extends StatefulWidget { + const GraphViewport({ + super.key, + required this.controller, + required this.contentSize, + required this.child, + this.onExpand, + }); + + final GraphViewportController controller; + + /// The measured graph extent; the canvas never invents a fixed size. + final Size contentSize; + + /// The measured, already-routed graph content. + final Widget child; + + /// Opens the expanded presentation. Null hides the expand control. + final VoidCallback? onExpand; + + @override + State createState() => _GraphViewportState(); +} + +class _GraphViewportState extends State { + Size? _scheduledViewport; + Size? _scheduledContent; + + @override + void didUpdateWidget(GraphViewport oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.controller != widget.controller) { + _scheduledViewport = null; + _scheduledContent = null; + } + } + + /// Attaches the current extents after layout, never during build. + void _scheduleAttach(Size viewport) { + if (viewport == _scheduledViewport && + widget.contentSize == _scheduledContent) { + return; + } + _scheduledViewport = viewport; + _scheduledContent = widget.contentSize; + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted) return; + widget.controller.attach(viewport: viewport, content: widget.contentSize); + }); + } + + @override + Widget build(BuildContext context) { + return LayoutBuilder( + builder: (context, constraints) { + final viewport = + constraints.hasBoundedWidth && constraints.hasBoundedHeight + ? constraints.biggest + : widget.contentSize; + if (!widget.controller.isAttached) { + // The very first layout has no `InteractiveViewer` listening yet, so + // fitting here applies before the first paint instead of flashing an + // identity transform for one frame. + widget.controller.attach( + viewport: viewport, + content: widget.contentSize, + ); + _scheduledViewport = viewport; + _scheduledContent = widget.contentSize; + } else { + _scheduleAttach(viewport); + } + return Stack( + fit: StackFit.expand, + children: [ + Positioned.fill( + child: InteractiveViewer( + key: const Key('graph-viewport'), + transformationController: widget.controller.transformation, + constrained: false, + // The graph owns its own bounds (fit and the visible-pan clamp), + // so the viewer must not impose a second, cover-the-viewport + // boundary that would fight the fit scale. + boundaryMargin: const EdgeInsets.all(double.infinity), + minScale: widget.controller.minScale, + maxScale: widget.controller.maxScale, + clipBehavior: Clip.hardEdge, + child: SizedBox.fromSize( + size: widget.contentSize, + child: widget.child, + ), + ), + ), + PositionedDirectional( + top: 8, + end: 8, + child: Wrap( + spacing: 8, + children: [ + _ViewportButton( + buttonKey: const Key('graph-fit'), + icon: _fitIcon(context), + label: graphFitLabel, + onPressed: widget.controller.fitToViewport, + ), + if (widget.onExpand != null) + _ViewportButton( + buttonKey: const Key('graph-expand'), + icon: _expandIcon(context), + label: graphExpandLabel, + onPressed: widget.onExpand, + ), + ], + ), + ), + ], + ); + }, + ); + } + + IconData _fitIcon(BuildContext context) => + usesCupertinoHost(context) ? CupertinoIcons.resize : Icons.fit_screen; + + IconData _expandIcon(BuildContext context) => + usesCupertinoHost(context) ? CupertinoIcons.fullscreen : Icons.fullscreen; +} + +/// One native graph control: a tinted icon button on either host. +/// +/// The label and the button's own tap action must reach the same semantics +/// node: the icon is the only excluded child, and [MergeSemantics] folds the +/// host button's action into the labelled node, so a screen reader can activate +/// Fit and Expand on either host. A hand-written `Semantics` sibling around an +/// excluded button would announce the control with no action at all. +class _ViewportButton extends StatelessWidget { + const _ViewportButton({ + required this.buttonKey, + required this.icon, + required this.label, + required this.onPressed, + }); + + final Key buttonKey; + final IconData icon; + final String label; + final VoidCallback? onPressed; + + @override + Widget build(BuildContext context) { + return MergeSemantics( + child: Semantics( + button: true, + label: label, + child: usesCupertinoHost(context) + ? CupertinoButton.tinted( + key: buttonKey, + padding: const EdgeInsets.all(8), + onPressed: onPressed, + child: ExcludeSemantics(child: Icon(icon)), + ) + : Tooltip( + message: label, + // The merged node already carries the label; the tooltip is + // only the pointer affordance. + excludeFromSemantics: true, + child: IconButton.filledTonal( + key: buttonKey, + onPressed: onPressed, + icon: ExcludeSemantics(child: Icon(icon)), + ), + ), + ), + ); + } +} diff --git a/app/lib/features/graph/viewport/graph_viewport_controller.dart b/app/lib/features/graph/viewport/graph_viewport_controller.dart new file mode 100644 index 00000000..497728bb --- /dev/null +++ b/app/lib/features/graph/viewport/graph_viewport_controller.dart @@ -0,0 +1,171 @@ +import 'package:flutter/widgets.dart'; + +import 'graph_viewport_math.dart'; + +/// One graph viewport's scale and offset, independent of any viewport size. +/// +/// A snapshot is what the expanded presentation carries over: the same scale +/// and offset the inline canvas is showing, so opening and closing it never +/// loses the reader's place. +@immutable +class GraphViewportSnapshot { + const GraphViewportSnapshot({required this.scale, required this.offset}); + + final double scale; + final Offset offset; + + @override + bool operator ==(Object other) => + other is GraphViewportSnapshot && + other.scale == scale && + other.offset == offset; + + @override + int get hashCode => Object.hash(scale, offset); + + @override + String toString() => 'GraphViewportSnapshot(scale: $scale, offset: $offset)'; +} + +/// Owns one graph canvas's transform. +/// +/// Pan and pinch stay the host's own gestures ([InteractiveViewer] drives the +/// [transformation]); this controller only supplies the graph's bounds: a fit +/// with padding, the min/max scale and a pan clamp that keeps part of the graph +/// visible. It never changes a node, route or label. A snapshot lets a caller +/// read or restore a place; the expanded presentation owns its own controller, +/// so closing it leaves this transform exactly as it was. +class GraphViewportController extends ChangeNotifier { + GraphViewportController({ + this.minScale = graphMinScale, + this.maxScale = graphMaxScale, + this.fitPadding = graphFitPadding, + this.minVisible = graphMinVisible, + }) : assert(minScale > 0), + assert(maxScale >= minScale), + _transformation = TransformationController() { + _transformation.addListener(_handleTransform); + } + + /// The native pan/zoom transform handed to [InteractiveViewer]. + final TransformationController _transformation; + + TransformationController get transformation => _transformation; + + final double minScale; + final double maxScale; + final double fitPadding; + final double minVisible; + + Size? _viewport; + Size? _content; + bool _userAdjusted = false; + bool _applying = false; + + /// The current uniform scale (`getMaxScaleOnAxis` of the transform). + double get scale => _transformation.value.getMaxScaleOnAxis(); + + /// The current graph-space translation of the transform. + Offset get offset { + final translation = _transformation.value.getTranslation(); + return Offset(translation.x, translation.y); + } + + GraphViewportSnapshot get snapshot => + GraphViewportSnapshot(scale: scale, offset: offset); + + /// Whether this controller has seen a viewport and content extent yet. + bool get isAttached => _viewport != null && _content != null; + + /// Records the current viewport and content extents. + /// + /// The first attach (and any later resize before the reader interacts) fits + /// the graph with [fitPadding]. Once the reader has panned or zoomed, a + /// resize keeps their place and only re-clamps it. + void attach({required Size viewport, required Size content}) { + if (viewport == _viewport && content == _content) return; + _viewport = viewport; + _content = content; + if (!_userAdjusted) { + fitToViewport(); + } else { + _clamp(); + } + } + + /// Fits the whole graph in the current viewport and clears the user-adjusted + /// flag, so a later resize fits again. + void fitToViewport() { + final viewport = _viewport; + final content = _content; + if (viewport == null || content == null) return; + final scale = graphFitScale( + viewport, + content, + padding: fitPadding, + minScale: minScale, + maxScale: maxScale, + ); + final scaled = Size(content.width * scale, content.height * scale); + _apply( + graphClampOffset( + graphCenteredOffset(scaled, viewport), + scaled, + viewport, + minVisible: minVisible, + ), + scale, + ); + _userAdjusted = false; + } + + /// Applies an explicit snapshot, e.g. when a caller restores a viewport. + void applySnapshot(GraphViewportSnapshot snapshot) { + _userAdjusted = true; + _apply(snapshot.offset, snapshot.scale.clamp(minScale, maxScale)); + } + + void _apply(Offset offset, double scale) { + _applying = true; + _transformation.value = graphViewportMatrix(offset, scale); + _applying = false; + notifyListeners(); + } + + /// Keeps every externally driven transform (a gesture, a wheel or a trackpad + /// pinch) inside the graph's scale and pan bounds. + void _handleTransform() { + if (_applying) return; + _userAdjusted = true; + _clamp(); + } + + void _clamp() { + final viewport = _viewport; + final content = _content; + if (viewport == null || content == null) return; + final currentScale = scale; + final boundedScale = currentScale.clamp(minScale, maxScale); + final scaled = Size( + content.width * boundedScale, + content.height * boundedScale, + ); + final currentOffset = offset; + final boundedOffset = graphClampOffset( + currentOffset, + scaled, + viewport, + minVisible: minVisible, + ); + if (boundedScale != currentScale || boundedOffset != currentOffset) { + _apply(boundedOffset, boundedScale); + } + } + + @override + void dispose() { + _transformation.removeListener(_handleTransform); + _transformation.dispose(); + super.dispose(); + } +} diff --git a/app/lib/features/graph/viewport/graph_viewport_math.dart b/app/lib/features/graph/viewport/graph_viewport_math.dart new file mode 100644 index 00000000..a2471af6 --- /dev/null +++ b/app/lib/features/graph/viewport/graph_viewport_math.dart @@ -0,0 +1,92 @@ +import 'dart:math' as math; + +import 'package:flutter/widgets.dart' show Matrix4, Offset, Size; + +/// The smallest scale a graph viewport may reach (`MIN_SCALE`). +const double graphMinScale = 0.3; + +/// The largest scale a graph viewport may reach (`MAX_SCALE`). +const double graphMaxScale = 3; + +/// Padding kept around a fitted graph, in graph-space pixels +/// (`GRAPH_FIT_PADDING`). +const double graphFitPadding = 24; + +/// The least amount of the scaled graph kept inside the viewport on each axis, +/// so a pan can never leave an empty canvas (`GRAPH_MIN_VISIBLE`). +const double graphMinVisible = 40; + +/// The transform that draws graph space at `offset + point * scale`. +Matrix4 graphViewportMatrix(Offset offset, double scale) => Matrix4.identity() + ..translateByDouble(offset.dx, offset.dy, 0, 1) + ..scaleByDouble(scale, scale, scale, 1); + +/// Uniform scale that fits [content] inside [viewport] with [padding] on every +/// side, never upscaling above 1:1 and never leaving the scale bounds. +/// +/// Degenerate or non-finite sizes return 1 rather than dividing by zero, so no +/// NaN or infinity ever reaches a transform. This is the web graph's +/// `fitScale` rule. +double graphFitScale( + Size viewport, + Size content, { + double padding = graphFitPadding, + double minScale = graphMinScale, + double maxScale = graphMaxScale, +}) { + final availableWidth = viewport.width - 2 * padding; + final availableHeight = viewport.height - 2 * padding; + final finite = + viewport.width.isFinite && + viewport.height.isFinite && + content.width.isFinite && + content.height.isFinite; + if (!finite || + content.width <= 0 || + content.height <= 0 || + availableWidth <= 0 || + availableHeight <= 0) { + return 1; + } + final scale = math.min( + 1.0, + math.min(availableWidth / content.width, availableHeight / content.height), + ); + return scale.clamp(minScale, maxScale); +} + +/// Bounds [offset] so at least [minVisible] pixels of the already scaled +/// [scaledContent] stay inside [viewport] on each axis. +/// +/// The web graph's `clampOffset`: `offset.x` stays in +/// `[minVisible - width, viewport.width - minVisible]`. Degenerate content or +/// an empty range returns the input unchanged. +Offset graphClampOffset( + Offset offset, + Size scaledContent, + Size viewport, { + double minVisible = graphMinVisible, +}) { + if (scaledContent.width <= 0 || + scaledContent.height <= 0 || + !scaledContent.width.isFinite || + !scaledContent.height.isFinite || + !viewport.width.isFinite || + !viewport.height.isFinite) { + return offset; + } + final minX = minVisible - scaledContent.width; + final maxX = viewport.width - minVisible; + final minY = minVisible - scaledContent.height; + final maxY = viewport.height - minVisible; + return Offset( + minX <= maxX ? offset.dx.clamp(minX, maxX) : offset.dx, + minY <= maxY ? offset.dy.clamp(minY, maxY) : offset.dy, + ); +} + +/// The centered offset that puts [scaledContent] in the middle of [viewport]. +Offset graphCenteredOffset(Size scaledContent, Size viewport) => Offset( + (viewport.width - scaledContent.width) / 2, + (viewport.height - scaledContent.height) / 2, +); diff --git a/app/lib/features/graph/widgets/definition_graph_canvas.dart b/app/lib/features/graph/widgets/definition_graph_canvas.dart new file mode 100644 index 00000000..e9c6690e --- /dev/null +++ b/app/lib/features/graph/widgets/definition_graph_canvas.dart @@ -0,0 +1,76 @@ +import 'package:flutter/widgets.dart'; + +import '../domain/graph_definition.dart'; +import '../layout/layout_models.dart'; +import '../painting/graph_edge_layer.dart'; +import '../routing/route_models.dart'; +import 'graph_canvas_style.dart'; +import 'graph_stage_node.dart'; + +/// The measured definition canvas at any viewport size and selection. +/// +/// Used by both the inline [GraphViewport] and the expanded presentation: the +/// passive edge layer paints behind the native nodes and outcome labels, and +/// every node reports selection through [onSelected]. +class DefinitionGraphCanvas extends StatelessWidget { + const DefinitionGraphCanvas({ + super.key, + required this.nodes, + required this.layout, + required this.routing, + required this.style, + required this.selectedStage, + required this.onSelected, + }); + + final List nodes; + final GraphLayout layout; + final GraphRouting routing; + final GraphCanvasStyle style; + final String? selectedStage; + final ValueChanged onSelected; + + @override + Widget build(BuildContext context) { + final nodesByKey = { + for (final node in nodes) node.key: node, + }; + final size = Size(routing.width, routing.height); + return Stack( + clipBehavior: Clip.none, + children: [ + // The passive layer comes first so every edge paints behind the native + // nodes and labels without taking their input. + Positioned.fill( + child: GraphEdgeLayer( + routes: routing.routes, + canvasSize: size, + color: style.edgeColor, + strokeWidth: style.edgeWidth, + ), + ), + for (final box in layout.nodes) + Positioned( + left: box.x, + top: box.y, + width: box.width, + height: box.height, + child: GraphStageNode( + node: nodesByKey[box.key]!, + selected: box.key == selectedStage, + onSelected: onSelected, + ), + ), + for (final label in routing.labels) + Positioned( + left: label.x, + top: label.y, + child: Text( + routing.routeFor(label.edgeId)!.label, + style: style.labelStyle, + ), + ), + ], + ); + } +} diff --git a/app/lib/features/graph/widgets/definition_graph_view.dart b/app/lib/features/graph/widgets/definition_graph_view.dart index 6c96e208..09e5e2b4 100644 --- a/app/lib/features/graph/widgets/definition_graph_view.dart +++ b/app/lib/features/graph/widgets/definition_graph_view.dart @@ -5,23 +5,29 @@ import '../../../core/api_gateway.dart'; import '../domain/graph_definition.dart'; import '../layout/graph_node_layout.dart'; import '../layout/layout_models.dart'; -import '../painting/graph_edge_layer.dart'; import '../routing/graph_edge_routing.dart'; import '../routing/route_models.dart'; +import '../viewport/graph_expanded_view.dart'; +import '../viewport/graph_viewport.dart'; +import '../viewport/graph_viewport_controller.dart'; +import 'definition_graph_canvas.dart'; import 'graph_canvas_style.dart'; -import 'graph_stage_node.dart'; import 'graph_measurements.dart'; /// The definition's own empty-state wording (web `PIPELINE_GRAPH_EMPTY`). const String definitionGraphEmpty = 'This pipeline has no stages.'; +/// The expanded definition presentation's title. +const String definitionGraphExpandedTitle = 'Pipeline graph'; + /// One pipeline definition as a readable native graph: measured stage nodes, /// routed passive edges behind them and native outcome labels on their boxes. /// /// [selectedStage] is a node key (including `#success`/`#failure`) and /// [onSelected] reports the exact key activated. Nothing reads run evidence: /// nodes show no status and terminals stay plain, so no visit is implied. The -/// view fills bounded caller constraints with a stock [InteractiveViewer]. +/// view fills bounded caller constraints with a pan/zoom [GraphViewport] and can +/// present the same canvas full screen without losing the selection. class DefinitionGraphView extends StatefulWidget { const DefinitionGraphView({ super.key, @@ -41,9 +47,16 @@ class DefinitionGraphView extends StatefulWidget { class _DefinitionGraphViewState extends State { final Map _nodeSizes = {}; final Map _labelSizes = {}; + final GraphViewportController _viewport = GraphViewportController(); TextScaler? _scaler; bool _rebuildScheduled = false; + @override + void dispose() { + _viewport.dispose(); + super.dispose(); + } + @override void didChangeDependencies() { super.didChangeDependencies(); @@ -159,56 +172,22 @@ class _DefinitionGraphViewState extends State { GraphRouting routing, GraphCanvasStyle style, ) { - final nodesByKey = { - for (final node in nodes) node.key: node, - }; final size = Size(routing.width, routing.height); return Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Expanded( - child: InteractiveViewer( - constrained: false, - minScale: 0.3, - maxScale: 3, - child: SizedBox.fromSize( - size: size, - child: Stack( - clipBehavior: Clip.none, - children: [ - // The passive layer comes first so every edge paints behind - // the native nodes and labels without taking their input. - Positioned.fill( - child: GraphEdgeLayer( - routes: routing.routes, - canvasSize: size, - color: style.edgeColor, - strokeWidth: style.edgeWidth, - ), - ), - for (final box in layout.nodes) - Positioned( - left: box.x, - top: box.y, - width: box.width, - height: box.height, - child: GraphStageNode( - node: nodesByKey[box.key]!, - selected: box.key == widget.selectedStage, - onSelected: widget.onSelected, - ), - ), - for (final label in routing.labels) - Positioned( - left: label.x, - top: label.y, - child: Text( - routing.routeFor(label.edgeId)!.label, - style: style.labelStyle, - ), - ), - ], - ), + child: GraphViewport( + controller: _viewport, + contentSize: size, + onExpand: () => _openExpanded(nodes, layout, routing, size), + child: DefinitionGraphCanvas( + nodes: nodes, + layout: layout, + routing: routing, + style: style, + selectedStage: widget.selectedStage, + onSelected: widget.onSelected, ), ), ), @@ -228,4 +207,28 @@ class _DefinitionGraphViewState extends State { ], ); } + + /// Opens the same measured canvas full screen, keeping the selection. + void _openExpanded( + List nodes, + GraphLayout layout, + GraphRouting routing, + Size size, + ) { + openGraphExpanded( + context, + contentSize: size, + title: definitionGraphExpandedTitle, + selectedStage: widget.selectedStage, + onSelected: widget.onSelected, + canvasBuilder: (context, selected, onSelected) => DefinitionGraphCanvas( + nodes: nodes, + layout: layout, + routing: routing, + style: GraphCanvasStyle.of(context), + selectedStage: selected, + onSelected: onSelected, + ), + ); + } } diff --git a/app/lib/features/graph/widgets/run_graph_canvas.dart b/app/lib/features/graph/widgets/run_graph_canvas.dart index 22be89cf..68deaa50 100644 --- a/app/lib/features/graph/widgets/run_graph_canvas.dart +++ b/app/lib/features/graph/widgets/run_graph_canvas.dart @@ -159,7 +159,8 @@ class RunGraphEdgePainter extends CustomPainter { /// outcome labels only for routes the run actually took. /// /// [layout] and [routing] are the caller's measured geometry. The canvas never -/// changes them and never assumes a node size. +/// changes them and never assumes a node size; the caller supplies the pan/zoom +/// viewport around this content. class RunGraphCanvas extends StatelessWidget { const RunGraphCanvas({ super.key, @@ -202,55 +203,47 @@ class RunGraphCanvas extends StatelessWidget { final executedColor = cupertino ? CupertinoTheme.of(context).primaryColor : Theme.of(context).colorScheme.primary; - return InteractiveViewer( - constrained: false, - minScale: 0.3, - maxScale: 3, - child: SizedBox.fromSize( - size: size, - child: Stack( - clipBehavior: Clip.none, - children: [ - Positioned.fill( - child: RunGraphEdgeLayer( - executedRoutes: executed, - untakenRoutes: untaken, - canvasSize: size, - executedColor: executedColor, - untakenColor: style.edgeColor, - strokeWidth: style.edgeWidth, + return Stack( + clipBehavior: Clip.none, + children: [ + Positioned.fill( + child: RunGraphEdgeLayer( + executedRoutes: executed, + untakenRoutes: untaken, + canvasSize: size, + executedColor: executedColor, + untakenColor: style.edgeColor, + strokeWidth: style.edgeWidth, + ), + ), + for (final box in layout.nodes) + Positioned( + left: box.x, + top: box.y, + width: box.width, + height: box.height, + child: RunGraphNode( + node: nodesByKey[box.key]!, + recordedStatus: recordedStatuses[box.key], + selected: box.key == selectedStage, + opensVisit: + !nodesByKey[box.key]!.terminal && + state.isStageVisited(box.key), + onSelected: onStageSelected, + ), + ), + // A run labels only the routes that actually happened. + for (final label in routing.labels) + if (executedIds.contains(label.edgeId)) + Positioned( + left: label.x, + top: label.y, + child: Text( + routing.routeFor(label.edgeId)!.label, + style: style.labelStyle, ), ), - for (final box in layout.nodes) - Positioned( - left: box.x, - top: box.y, - width: box.width, - height: box.height, - child: RunGraphNode( - node: nodesByKey[box.key]!, - recordedStatus: recordedStatuses[box.key], - selected: box.key == selectedStage, - opensVisit: - !nodesByKey[box.key]!.terminal && - state.isStageVisited(box.key), - onSelected: onStageSelected, - ), - ), - // A run labels only the routes that actually happened. - for (final label in routing.labels) - if (executedIds.contains(label.edgeId)) - Positioned( - left: label.x, - top: label.y, - child: Text( - routing.routeFor(label.edgeId)!.label, - style: style.labelStyle, - ), - ), - ], - ), - ), + ], ); } } diff --git a/app/lib/features/graph/widgets/run_graph_header.dart b/app/lib/features/graph/widgets/run_graph_header.dart new file mode 100644 index 00000000..ac7af652 --- /dev/null +++ b/app/lib/features/graph/widgets/run_graph_header.dart @@ -0,0 +1,117 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../ui/adaptive/host.dart'; +import '../domain/run_graph_state.dart'; +import 'graph_canvas_style.dart'; + +/// The run legend's route-class words (web graph legend). +const String runGraphExecuted = 'Executed'; +const String runGraphNotExecuted = 'Not executed'; + +/// The run canvas' fixed header: the route legend, plus the elapsed line while +/// the run is still executing. +/// +/// It is shared by the inline view and the full-screen presentation so the +/// expanded canvas explains its solid and dashed routes the way the web keeps +/// its legend inside the graph panel. +class RunGraphHeader extends StatelessWidget { + const RunGraphHeader({ + super.key, + required this.state, + required this.style, + this.now, + }); + + final RunGraphState state; + final GraphCanvasStyle style; + + /// Injectable clock for deterministic elapsed labels; defaults to now. + final DateTime Function()? now; + + @override + Widget build(BuildContext context) { + final cupertino = usesCupertinoHost(context); + final executedColor = cupertino + ? CupertinoTheme.of(context).primaryColor + : Theme.of(context).colorScheme.primary; + final mutedColor = style.edgeColor; + final active = state.activeStage; + return Padding( + padding: const EdgeInsetsDirectional.fromSTEB(12, 8, 12, 0), + child: Wrap( + spacing: 16, + runSpacing: 4, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + Semantics( + container: true, + label: 'Route kinds', + child: Wrap( + spacing: 12, + runSpacing: 4, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + _LegendEntry( + icon: cupertino + ? CupertinoIcons.arrow_right + : Icons.arrow_forward, + label: runGraphExecuted, + color: executedColor, + ), + _LegendEntry( + icon: cupertino ? CupertinoIcons.minus : Icons.remove, + label: runGraphNotExecuted, + color: mutedColor, + ), + ], + ), + ), + if (active != null) + _elapsed(context, active, state.currentStageStartedAt), + ], + ), + ); + } + + Widget _elapsed(BuildContext context, String active, String? startedAt) { + final started = startedAt == null ? null : DateTime.tryParse(startedAt); + final duration = started == null + ? null + : _formatElapsed((now ?? DateTime.now)().difference(started)); + final text = duration == null + ? 'Current stage $active' + : 'Current stage $active · elapsed $duration'; + return Text(text, style: GraphCanvasStyle.of(context).labelStyle); + } +} + +class _LegendEntry extends StatelessWidget { + const _LegendEntry({ + required this.icon, + required this.label, + required this.color, + }); + + final IconData icon; + final String label; + final Color color; + + @override + Widget build(BuildContext context) => Wrap( + spacing: 4, + runSpacing: 2, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + ExcludeSemantics(child: Icon(icon, color: color)), + Text(label), + ], + ); +} + +String _formatElapsed(Duration duration) { + final seconds = duration.inSeconds < 0 ? 0 : duration.inSeconds; + if (seconds < 60) return '${seconds}s'; + if (seconds < 3600) return '${seconds ~/ 60}m ${seconds % 60}s'; + return '${seconds ~/ 3600}h ${(seconds % 3600) ~/ 60}m'; +} diff --git a/app/lib/features/graph/widgets/run_graph_view.dart b/app/lib/features/graph/widgets/run_graph_view.dart index 1868d488..4850ce67 100644 --- a/app/lib/features/graph/widgets/run_graph_view.dart +++ b/app/lib/features/graph/widgets/run_graph_view.dart @@ -1,8 +1,6 @@ -import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import '../../../core/api_gateway.dart'; -import '../../../ui/adaptive/host.dart'; import '../domain/graph_definition.dart'; import '../domain/run_graph_state.dart'; import '../domain/stage_visits.dart'; @@ -10,15 +8,20 @@ import '../layout/graph_node_layout.dart'; import '../layout/layout_models.dart'; import '../routing/graph_edge_routing.dart'; import '../routing/route_models.dart'; +import '../viewport/graph_expanded_view.dart'; +import '../viewport/graph_viewport.dart'; +import '../viewport/graph_viewport_controller.dart'; import 'graph_canvas_style.dart'; import 'run_graph_canvas.dart'; +import 'run_graph_header.dart'; + +export 'run_graph_header.dart' show runGraphExecuted, runGraphNotExecuted; /// The run tab's exact missing-graph wording (web `RUN_GRAPH_MISSING`). const String runGraphMissing = 'This server did not include the run graph.'; -/// The run legend's route-class words (web graph legend). -const String runGraphExecuted = 'Executed'; -const String runGraphNotExecuted = 'Not executed'; +/// The expanded run presentation's title. +const String runGraphExpandedTitle = 'Run graph'; /// One run's definition drawn as evidence: visited stages carry their recorded /// status, only taken routes are solid and arrowed, and every other route stays @@ -32,9 +35,10 @@ const String runGraphNotExecuted = 'Not executed'; /// shown with the outcome that resolved there but have no recorded visit to /// open, so they stay non-interactive. /// -/// The view fills its bounded constraints with a stock [InteractiveViewer] for -/// pan and zoom; the elapsed line appears only while the run is executing and -/// is static (no invented progress or timer). +/// The view fills its bounded constraints with a pan/zoom [GraphViewport]; the +/// elapsed line appears only while the run is executing and is static (no +/// invented progress or timer). The same canvas can be opened full screen with +/// its selection preserved and the route legend still explaining its marks. class RunGraphView extends StatefulWidget { const RunGraphView({ super.key, @@ -67,9 +71,16 @@ class _RunGraphViewState extends State { final Map _nodeSizes = {}; final Map _labelSizes = {}; final Map _measuredStatuses = {}; + final GraphViewportController _viewport = GraphViewportController(); TextScaler? _scaler; bool _rebuildScheduled = false; + @override + void dispose() { + _viewport.dispose(); + super.dispose(); + } + @override void didChangeDependencies() { super.didChangeDependencies(); @@ -188,21 +199,32 @@ class _RunGraphViewState extends State { return Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ - _header(state, style), + RunGraphHeader(state: state, style: style, now: widget.now), Expanded( child: Stack( fit: StackFit.expand, children: [ if (geometry != null) - RunGraphCanvas( - nodes: nodes, - layout: geometry.$1, - routing: geometry.$2, - state: state, - style: style, - recordedStatuses: statuses, - selectedStage: widget.selectedStage, - onStageSelected: widget.onStageSelected, + GraphViewport( + controller: _viewport, + contentSize: Size(geometry.$2.width, geometry.$2.height), + onExpand: () => _openExpanded( + nodes, + geometry.$1, + geometry.$2, + state, + statuses, + ), + child: _runCanvas( + nodes: nodes, + layout: geometry.$1, + routing: geometry.$2, + state: state, + style: style, + statuses: statuses, + selectedStage: widget.selectedStage, + onStageSelected: widget.onStageSelected, + ), ) else const SizedBox.shrink(), @@ -245,87 +267,58 @@ class _RunGraphViewState extends State { ), ); - Widget _header(RunGraphState state, GraphCanvasStyle style) { - final cupertino = usesCupertinoHost(context); - final executedColor = cupertino - ? CupertinoTheme.of(context).primaryColor - : Theme.of(context).colorScheme.primary; - final mutedColor = style.edgeColor; - final active = state.activeStage; - return Padding( - padding: const EdgeInsetsDirectional.fromSTEB(12, 8, 12, 0), - child: Wrap( - spacing: 16, - runSpacing: 4, - crossAxisAlignment: WrapCrossAlignment.center, - children: [ - Semantics( - container: true, - label: 'Route kinds', - child: Wrap( - spacing: 12, - runSpacing: 4, - crossAxisAlignment: WrapCrossAlignment.center, - children: [ - _LegendEntry( - icon: cupertino - ? CupertinoIcons.arrow_right - : Icons.arrow_forward, - label: runGraphExecuted, - color: executedColor, - ), - _LegendEntry( - icon: cupertino ? CupertinoIcons.minus : Icons.remove, - label: runGraphNotExecuted, - color: mutedColor, - ), - ], - ), - ), - if (active != null) _elapsed(active, state.currentStageStartedAt), - ], + /// The same measured run canvas at any viewport size and selection, used by + /// the inline viewport and the expanded presentation. + Widget _runCanvas({ + required List nodes, + required GraphLayout layout, + required GraphRouting routing, + required RunGraphState state, + required GraphCanvasStyle style, + required Map statuses, + required String? selectedStage, + required ValueChanged onStageSelected, + }) => RunGraphCanvas( + nodes: nodes, + layout: layout, + routing: routing, + state: state, + style: style, + recordedStatuses: statuses, + selectedStage: selectedStage, + onStageSelected: onStageSelected, + ); + + void _openExpanded( + List nodes, + GraphLayout layout, + GraphRouting routing, + RunGraphState state, + Map statuses, + ) { + openGraphExpanded( + context, + contentSize: Size(routing.width, routing.height), + title: runGraphExpandedTitle, + selectedStage: widget.selectedStage, + onSelected: widget.onStageSelected, + // The full-screen canvas draws solid and dashed routes; the legend that + // explains them must travel with it, as it does on the web. + header: RunGraphHeader( + state: state, + style: GraphCanvasStyle.of(context), + now: widget.now, + ), + canvasBuilder: (context, selected, onSelected) => _runCanvas( + nodes: nodes, + layout: layout, + routing: routing, + state: state, + style: GraphCanvasStyle.of(context), + statuses: statuses, + selectedStage: selected, + onStageSelected: onSelected, ), ); } - - Widget _elapsed(String active, String? startedAt) { - final started = startedAt == null ? null : DateTime.tryParse(startedAt); - final duration = started == null - ? null - : _formatElapsed((widget.now ?? DateTime.now)().difference(started)); - final text = duration == null - ? 'Current stage $active' - : 'Current stage $active · elapsed $duration'; - return Text(text, style: GraphCanvasStyle.of(context).labelStyle); - } -} - -class _LegendEntry extends StatelessWidget { - const _LegendEntry({ - required this.icon, - required this.label, - required this.color, - }); - - final IconData icon; - final String label; - final Color color; - - @override - Widget build(BuildContext context) => Wrap( - spacing: 4, - runSpacing: 2, - crossAxisAlignment: WrapCrossAlignment.center, - children: [ - ExcludeSemantics(child: Icon(icon, color: color)), - Text(label), - ], - ); -} - -String _formatElapsed(Duration duration) { - final seconds = duration.inSeconds < 0 ? 0 : duration.inSeconds; - if (seconds < 60) return '${seconds}s'; - if (seconds < 3600) return '${seconds ~/ 60}m ${seconds % 60}s'; - return '${seconds ~/ 3600}h ${(seconds % 3600) ~/ 60}m'; } diff --git a/app/notes/G2-zoom.md b/app/notes/G2-zoom.md new file mode 100644 index 00000000..4cfc7b3d --- /dev/null +++ b/app/notes/G2-zoom.md @@ -0,0 +1,144 @@ +# Graph viewport: pan, zoom, fit and expanded + +The measured definition/run canvases now share one viewport layer. Nothing in +the graph's wiring changed: `DefinitionGraphView` and `RunGraphView` keep their +existing props and call sites, and the pipeline Graph tab / run detail open the +expanded presentation without edits to those tabs. + +## Landed + +- `lib/features/graph/viewport/graph_viewport_math.dart` — the web graph's + `fitScale`/`clampOffset` rules (padding 24, min 0.3, max 3, at least 40px of + the scaled graph visible) plus the `offset + point * scale` matrix. +- `lib/features/graph/viewport/graph_viewport_controller.dart` — owns the + `TransformationController`, auto-fits on first layout, re-fits a resize only + before the reader interacts, clamps every later transform, and round-trips a + `GraphViewportSnapshot`. +- `lib/features/graph/viewport/graph_viewport.dart` — the bounded canvas: the + host's `InteractiveViewer` gestures (drag, pinch, wheel, trackpad) with an + infinite boundary margin so the graph's own fit/bounds win, plus native Fit + and Expand controls (`Fit graph to view`, `Expand graph`). +- `lib/features/graph/viewport/graph_expanded_view.dart` — a native full-screen + presentation (`Scaffold`/`CupertinoPageScaffold`) with one visible `Close` + action, `openGraphExpanded()` as the widget/callback seam, and an optional + fixed `header` above the canvas. It fits the larger box exactly as the web + re-fits when its panel expands, keeps the selected node selected, re-fits a + resize until the reader interacts and clamps one afterwards. It owns a + separate controller, so closing restores the inline transform exactly. +- `DefinitionGraphView`/`RunGraphView` now wrap their measured content in + `GraphViewport`; `RunGraphCanvas` is the passive content only (the viewer + moved out of it). `DefinitionGraphCanvas` owns the measured definition + composition, and `RunGraphHeader` owns the route legend + elapsed line and is + carried into the expanded run presentation. Node sizes, routing, + executed/unvisited evidence, labels and legend are unchanged. + +## Behavior and bounds + +- The graph is fitted on first layout with 24px padding and never upscaled past + 1:1, before the first paint: the first layout attaches synchronously, when + nothing is listening to the transform yet, rather than flashing an identity + transform for a frame. +- Scale is clamped to 0.3–3 and a drag can never leave an empty viewport + (40px minimum visible per axis). +- Pinch/wheel zoom anchors the graph point under the moving focal point; a tap + that does not move still reaches the native node under the pointer because + hit-testing follows the same transform. +- Fit and Expand are stock host buttons with one accessible name and the + button's own tap action on both hosts. The icon is the only excluded child + and `MergeSemantics` folds the real button action into the labelled node; a + hand-written sibling `Semantics` around an `ExcludeSemantics`d button would + announce the control with no action at all. +- Single taps select nodes; dragging over a node pans instead of selecting. +- The canvas consumes gestures only inside its own box. An ancestor scroll view + keeps scrolling for gestures outside the canvas, and the canvas never pans + from a drag that starts outside it. +- Expanded draws the same canvas at its own fit, keeps the legend (run graph), + keeps the selection, and leaves the inline canvas untouched. + +## Checks (final tree) + +From `app/` with Flutter 3.44.6 / Dart 3.12.2: + +- `flutter analyze` — **No issues found**. +- `flutter test` — **1025 tests pass** (1m 06s in this run). +- `flutter test test/features/graph` — **175 pass**. +- `flutter test test/features/graph/viewport` — **20 tests pass** + (8 math/controller, 9 viewport widget, 3 expanded), covering: + - drag pans and pan stays bounded; + - pinch clamps at 0.3 and 3; + - zoom keeps the graph point under the moving focal point; + - the first painted frame is already fitted; + - Fit restores the fitted scale/offset; + - tap selects the node visually under the pointer after a transform (synthetic + targets and real `DefinitionGraphView` nodes); + - ancestor scroll is not hijacked outside the canvas; + - Fit and Expand are labelled buttons with a tap action on Material and + Cupertino, and performing that action runs the real callback; + - 320px/2x on Material and dark Cupertino; + - expanded fits the larger canvas, preserves selection and returns the inline + state exactly; + - a rotation re-clamps the expanded transform into the new box. +- `flutter build web` — succeeds for the app and the probe target. +- Real Chrome probe (`tool/graph_zoom_probe.dart` + `tool/graph_zoom_probe.mjs`, + loopback server, OS-assigned port) re-run against this final source, 7 runs: + - pipeline graph: Material light 1280x800 1x, Material light 320x700 2x, + Cupertino dark 390x844 1x, Cupertino dark 320x700 2x; + - run graph: Material light 1280x800 1x, Material dark 320x700 2x, + Cupertino dark 390x844 1x. + Each asserted a real drag moved a node, wheel zoom grew it, Fit restored it, + Expand opened the titled full-screen canvas with the selected node still + announced selected, and Close returned to the same inline place and selection. + 42 captures (initial/panned/zoomed/fitted/expanded/restored per run) were + regenerated after the last source edit and are in + `/Users/alan/.local/share/pipelines/data/artifacts/101/public/graph-zoom-captures/`. +- `dart format --output=none --set-exit-if-changed` on the changed Dart files — + 0 changed; `git diff --check` — clean. + +## Corrections from actual checks + +- The transform's z axis must be scaled with x/y: `getMaxScaleOnAxis` otherwise + reported 1.0 for a 0.8 fit and InteractiveViewer's own pinch math used the + wrong scale. Fixed in `graphViewportMatrix`. +- Two existing measurement tests compared on-screen rectangles, which now + include the fit scale. They divide by the current scale and assert the + measured graph-space extent instead; the assertions about wrapping and + overlap are unchanged. +- Cupertino's full-screen route added its own `Cancel` leading button next to + the explicit Close; `automaticallyImplyLeading: false` leaves the one Close + action. +- `tester.drag` can lose the pre-acceptance movement to the pan slop; gesture + tests warm up past the slop and measure from the accepted transform, and the + browser probe pans with eight real pointer moves. +- The first implementation excluded the whole Cupertino button from semantics + and put the label on a sibling node: VoiceOver/TalkBack saw a labelled button + with no tap action. The exclusion now covers only the icon and + `MergeSemantics` merges the host button's action; the regression test performs + the semantics action itself, not a pointer tap. +- Material controls previously had only a tooltip as their accessible name. Both + hosts now expose one explicit label (`Fit graph to view` / `Expand graph`); + Material keeps the tooltip for pointer hover, excluded from semantics so the + name is not duplicated. +- The inline canvas used to paint one identity-transform frame before the + post-frame fit. The first layout now attaches before its child viewer exists, + and the regression test pumps exactly once. +- Expanded used to keep the small inline scale, unlike the web, which calls + `fit()` after growing the panel. It now fits its own canvas and re-clamps (or + re-fits) on resize; the inline place/selection still return unchanged on + Close. +- The expanded run canvas had no route legend; `RunGraphHeader` now travels + with it. + +## Limits + +- Inside an ancestor scroll view, a **vertical** drag that starts on the canvas + is claimed by the scrollable (Flutter's gesture arena gives the 18px vertical + drag the win over the 36px pan slop); horizontal drags and pinch stay with the + canvas. The graph is not inside a scrollable in either current tab. Outside + the canvas the list scrolls normally, which is the accepted behavior here. +- Opening expanded fits the graph rather than keeping the inline place (web + behavior); closing still restores the inline transform exactly. +- Web only: Android/iOS builds, device gestures and OS behavior are unverified. +- `run_graph_view.dart` remains over the 250-line aim (324 lines: measurement, + evidence and viewport composition; the legend/header and definition canvas + were split out). The new viewport files and viewport test files are all under + 250 lines. diff --git a/app/test/features/graph/viewport/graph_expanded_view_test.dart b/app/test/features/graph/viewport/graph_expanded_view_test.dart new file mode 100644 index 00000000..06a55856 --- /dev/null +++ b/app/test/features/graph/viewport/graph_expanded_view_test.dart @@ -0,0 +1,213 @@ +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/graph/viewport/graph_expanded_view.dart'; +import 'package:pipelines_app/features/graph/viewport/graph_viewport_math.dart'; +import 'package:pipelines_app/features/graph/widgets/definition_graph_view.dart'; +import 'package:pipelines_app/features/graph/widgets/graph_stage_node.dart'; + +import '../domain/graph_fixtures.dart'; + +Widget _materialHost({ + required JsonMap graph, + required String? selected, + required ValueChanged onSelected, +}) => MaterialApp( + home: Scaffold( + body: DefinitionGraphView( + graph: graph, + selectedStage: selected, + onSelected: onSelected, + ), + ), +); + +Finder _node(String key) => find.byWidgetPredicate( + (widget) => widget is GraphStageNode && widget.node.key == key, +); + +Finder _inExpanded(Finder finder) => + find.descendant(of: find.byType(GraphExpandedView), matching: finder); + +Future _settle(WidgetTester tester) async { + await tester.pump(); + await tester.pump(); + await tester.pump(); +} + +TransformationController _inlineTransform(WidgetTester tester) => tester + .widget(find.byType(InteractiveViewer)) + .transformationController!; + +void main() { + testWidgets( + 'expanded fits the larger canvas and returns to the inline state', + (tester) async { + tester.view.physicalSize = const Size(900, 700); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + final picked = []; + await tester.pumpWidget( + _materialHost( + graph: linearGraph(), + selected: 'build', + onSelected: picked.add, + ), + ); + await _settle(tester); + + final inline = _inlineTransform(tester); + final inlineMatrix = Matrix4.copy(inline.value); + final inlineRect = tester.getRect(_node('build')); + + await tester.tap(find.byKey(const Key('graph-expand'))); + await tester.pumpAndSettle(); + + expect(find.byType(GraphExpandedView), findsOneWidget); + expect(find.text(definitionGraphExpandedTitle), findsOneWidget); + final expanded = _inExpanded(find.byType(InteractiveViewer)); + expect(expanded, findsOneWidget); + final expandedController = tester + .widget(expanded) + .transformationController!; + final expandedView = tester.widget( + find.byType(GraphExpandedView), + ); + final canvas = tester.getRect( + _inExpanded(find.byKey(const Key('graph-viewport'))), + ); + // The web re-fits when its panel expands: the larger canvas fits the + // whole graph instead of keeping the small inline scale. + expect( + expandedController.value.getMaxScaleOnAxis(), + closeTo(graphFitScale(canvas.size, expandedView.contentSize), 1e-9), + ); + expect( + canvas.contains(tester.getCenter(_inExpanded(_node('build')))), + isTrue, + ); + expect( + tester.widget(_inExpanded(_node('build'))).selected, + isTrue, + ); + + // A tap in the larger canvas follows the same transform and updates the + // presentation's own selection. + await tester.tap(_inExpanded(_node('plan'))); + await tester.pump(); + expect(picked, ['plan']); + expect( + tester.widget(_inExpanded(_node('plan'))).selected, + isTrue, + ); + + await tester.tap(find.byKey(const Key('graph-expanded-close'))); + await tester.pumpAndSettle(); + + expect(find.byType(GraphExpandedView), findsNothing); + // The inline canvas was never changed: same selection, same place. + expect(tester.widget(_node('build')).selected, isTrue); + expect(tester.getRect(_node('build')), inlineRect); + expect(inline.value.storage, orderedEquals(inlineMatrix.storage)); + }, + ); + + testWidgets('a rotation re-clamps the expanded transform into the new box', ( + tester, + ) async { + tester.view.physicalSize = const Size(900, 700); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + await tester.pumpWidget( + _materialHost( + graph: linearGraph(), + selected: 'build', + onSelected: (_) {}, + ), + ); + await _settle(tester); + await tester.tap(find.byKey(const Key('graph-expand'))); + await tester.pumpAndSettle(); + + final expanded = _inExpanded(find.byType(InteractiveViewer)); + final controller = tester + .widget(expanded) + .transformationController!; + final canvas = find.descendant( + of: find.byType(GraphExpandedView), + matching: find.byKey(const Key('graph-viewport')), + ); + // Pan far enough that the wide canvas' clamp is the only limit. + await tester.drag(canvas, const Offset(500, 0)); + await tester.pumpAndSettle(); + final wide = tester.getRect(canvas); + final panned = controller.value.getTranslation().x; + expect(panned, lessThanOrEqualTo(wide.width - graphMinVisible + 0.5)); + + // Rotating to a narrow box must keep the graph inside it, not leave the + // reader's old place hanging outside until Fit is pressed. + tester.view.physicalSize = const Size(320, 700); + await tester.pumpAndSettle(); + await _settle(tester); + final narrow = tester.getRect(canvas); + expect(narrow.width, lessThan(wide.width)); + final clamped = controller.value.getTranslation().x; + expect( + clamped, + lessThanOrEqualTo(narrow.width - graphMinVisible + 0.5), + reason: 'a resize must re-clamp the existing transform', + ); + expect(clamped, lessThan(panned)); + }); + + testWidgets('320px at 2x opens and closes on the dark Cupertino host', ( + tester, + ) async { + tester.view.physicalSize = const Size(320, 700); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + final picked = []; + await tester.pumpWidget( + CupertinoApp( + theme: const CupertinoThemeData(brightness: Brightness.dark), + home: CupertinoPageScaffold( + child: Builder( + builder: (context) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: const TextScaler.linear(2)), + child: DefinitionGraphView( + graph: linearGraph(), + selectedStage: 'build', + onSelected: picked.add, + ), + ), + ), + ), + ), + ); + await _settle(tester); + final inline = _inlineTransform(tester); + final inlineMatrix = Matrix4.copy(inline.value); + + await tester.tap(find.byKey(const Key('graph-expand'))); + await tester.pumpAndSettle(); + expect(find.byType(GraphExpandedView), findsOneWidget); + expect(_inExpanded(find.text(graphExpandedClose)), findsOneWidget); + expect( + tester.widget(_inExpanded(_node('build'))).selected, + isTrue, + ); + expect(tester.takeException(), isNull); + + await tester.tap(find.byKey(const Key('graph-expanded-close'))); + await tester.pumpAndSettle(); + expect(find.byType(GraphExpandedView), findsNothing); + expect(tester.widget(_node('build')).selected, isTrue); + expect(inline.value.storage, orderedEquals(inlineMatrix.storage)); + expect(picked, isEmpty); + expect(tester.takeException(), isNull); + }); +} diff --git a/app/test/features/graph/viewport/graph_viewport_controls_test.dart b/app/test/features/graph/viewport/graph_viewport_controls_test.dart new file mode 100644 index 00000000..b17b3a47 --- /dev/null +++ b/app/test/features/graph/viewport/graph_viewport_controls_test.dart @@ -0,0 +1,99 @@ +import 'package:flutter/rendering.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'package:pipelines_app/features/graph/viewport/graph_viewport_controller.dart'; + +import 'graph_viewport_fixtures.dart'; + +void main() { + testWidgets('Fit and Expand stay labelled, activatable buttons on both hosts', ( + tester, + ) async { + for (final cupertino in [false, true]) { + final host = cupertino ? 'cupertino' : 'material'; + final controller = GraphViewportController(); + addTearDown(controller.dispose); + var expands = 0; + await tester.pumpWidget( + viewportHost( + controller: controller, + child: viewportTargets([]), + cupertino: cupertino, + onExpand: () => expands += 1, + ), + ); + await settleViewport(tester); + final fitted = controller.snapshot; + + for (final control in viewportControls().entries) { + final node = tester.getSemantics(find.byKey(control.key)); + final data = node.getSemanticsData(); + expect( + data.label, + control.value, + reason: '$host ${control.key} must have the web name', + ); + expect( + data.flagsCollection.isButton, + isTrue, + reason: '$host ${control.key} must be announced as a button', + ); + // A labelled button with no action is unusable with VoiceOver/TalkBack; + // this is the regression the excluded-button wrapper introduced. + expect( + data.hasAction(SemanticsAction.tap), + isTrue, + reason: '$host ${control.key} must expose a tap action', + ); + } + + // The exposed action must run the real callback, not just be announced. + await pinchViewport(tester, const Offset(200, 150), 2); + await tester.pumpAndSettle(); + expect(controller.snapshot, isNot(fitted)); + performViewportTap(tester, find.byKey(const Key('graph-fit'))); + await tester.pump(); + expect(controller.scale, closeTo(fitted.scale, 1e-9)); + + performViewportTap(tester, find.byKey(const Key('graph-expand'))); + await tester.pump(); + expect(expands, 1, reason: '$host Expand must activate'); + } + }); + + testWidgets('320px at 2x keeps native controls and gestures on both hosts', ( + tester, + ) async { + for (final cupertino in [false, true]) { + final controller = GraphViewportController(); + addTearDown(controller.dispose); + await tester.pumpWidget( + viewportHost( + controller: controller, + child: viewportTargets([]), + cupertino: cupertino, + dark: cupertino, + textScale: 2, + viewport: const Size(320, 300), + onExpand: () {}, + ), + ); + await settleViewport(tester); + expect(find.byKey(const Key('graph-fit')), findsOneWidget); + expect(find.byKey(const Key('graph-expand')), findsOneWidget); + expect(tester.takeException(), isNull); + + final before = controller.offset; + await dragViewport( + tester, + find.byKey(const Key('graph-viewport')), + const Offset(-30, -10), + ); + expect(controller.offset, isNot(before)); + await pinchViewport(tester, const Offset(160, 150), 2); + await tester.pumpAndSettle(); + expect(controller.scale, greaterThan(0.3)); + expect(tester.takeException(), isNull); + } + }); +} diff --git a/app/test/features/graph/viewport/graph_viewport_fixtures.dart b/app/test/features/graph/viewport/graph_viewport_fixtures.dart new file mode 100644 index 00000000..72b7eb88 --- /dev/null +++ b/app/test/features/graph/viewport/graph_viewport_fixtures.dart @@ -0,0 +1,167 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'package:pipelines_app/features/graph/viewport/graph_viewport.dart'; +import 'package:pipelines_app/features/graph/viewport/graph_viewport_controller.dart'; + +/// Shared fixture for the graph viewport widget tests. +/// +/// One 1200x900 graph in a 400x300 box unless a test asks for another size. +const Size viewportContent = Size(1200, 900); +const Size defaultViewportSize = Size(400, 300); + +/// Two native tap targets at known graph coordinates; a tap reports its key so +/// hit-testing can be checked against the visible transform. +Widget viewportTargets(List picked) => Stack( + clipBehavior: Clip.none, + children: [ + Positioned( + left: 60, + top: 60, + width: 120, + height: 60, + child: GestureDetector( + key: const Key('target-a'), + behavior: HitTestBehavior.opaque, + onTap: () => picked.add('a'), + child: const ColoredBox(color: Color(0xFF3366CC)), + ), + ), + Positioned( + left: 900, + top: 700, + width: 160, + height: 80, + child: GestureDetector( + key: const Key('target-b'), + behavior: HitTestBehavior.opaque, + onTap: () => picked.add('b'), + child: const ColoredBox(color: Color(0xFFCC6633)), + ), + ), + ], +); + +Widget viewportHost({ + required GraphViewportController controller, + required Widget child, + VoidCallback? onExpand, + bool cupertino = false, + bool dark = false, + double textScale = 1, + Size viewport = defaultViewportSize, +}) { + final graph = MediaQuery( + data: MediaQueryData(textScaler: TextScaler.linear(textScale)), + child: SizedBox.fromSize( + size: viewport, + child: GraphViewport( + controller: controller, + contentSize: viewportContent, + onExpand: onExpand, + child: child, + ), + ), + ); + if (cupertino) { + return CupertinoApp( + theme: CupertinoThemeData( + brightness: dark ? Brightness.dark : Brightness.light, + ), + home: CupertinoPageScaffold(child: Center(child: graph)), + ); + } + return MaterialApp( + theme: dark ? ThemeData.dark() : ThemeData.light(), + home: Scaffold(body: Center(child: graph)), + ); +} + +Future settleViewport(WidgetTester tester) async { + await tester.pump(); + await tester.pump(); + await tester.pump(); +} + +/// Two-pointer pinch around [center]; [factor] > 1 zooms in. +Future pinchViewport( + WidgetTester tester, + Offset center, + double factor, { + double half = 20, +}) async { + final origin = viewportGlobal(tester, center); + final left = await tester.startGesture(origin - Offset(half, 0)); + final right = await tester.startGesture(origin + Offset(half, 0)); + await tester.pump(); + const steps = 8; + final end = half * factor; + for (var step = 1; step <= steps; step += 1) { + final spread = half + (end - half) * step / steps; + await left.moveTo(origin - Offset(spread, 0)); + await right.moveTo(origin + Offset(spread, 0)); + await tester.pump(); + } + await left.up(); + await right.up(); + await tester.pump(); +} + +Offset viewportScreenOf( + GraphViewportController controller, + Offset graphPoint, +) => MatrixUtils.transformPoint(controller.transformation.value, graphPoint); + +/// Viewport-local coordinates to the test screen, where gestures are dispatched. +Offset viewportGlobal(WidgetTester tester, Offset local) => + tester.getTopLeft(find.byKey(const Key('graph-viewport'))) + local; + +/// Starts a drag and moves past the pan slop, so the canvas owns the gesture. +/// +/// The viewer only pans movement after it accepts the gesture, so tests record +/// their reference offset after this warm-up rather than at pointer down. +Future startViewportDrag( + WidgetTester tester, + Finder finder, { + Offset warmUp = const Offset(-10, -10), +}) async { + final gesture = await tester.startGesture(tester.getCenter(finder)); + for (var step = 0; step < 4; step += 1) { + await gesture.moveBy(warmUp); + await tester.pump(); + } + return gesture; +} + +Future dragViewport( + WidgetTester tester, + Finder finder, + Offset delta, { + Offset warmUp = const Offset(-10, -10), +}) async { + final gesture = await startViewportDrag(tester, finder, warmUp: warmUp); + for (var step = 0; step < 4; step += 1) { + await gesture.moveBy(delta / 4); + await tester.pump(); + } + await gesture.up(); + await tester.pumpAndSettle(); +} + +/// Activates a control the way a screen reader does: through its semantics +/// action, not pointer input. +void performViewportTap(WidgetTester tester, Finder finder) { + final node = tester.getSemantics(finder); + tester.binding.renderViews.first.owner!.semanticsOwner!.performAction( + node.id, + SemanticsAction.tap, + ); +} + +/// The controls' accessible names, in the order they are shown. +Map viewportControls() => { + const Key('graph-fit'): graphFitLabel, + const Key('graph-expand'): graphExpandLabel, +}; diff --git a/app/test/features/graph/viewport/graph_viewport_math_test.dart b/app/test/features/graph/viewport/graph_viewport_math_test.dart new file mode 100644 index 00000000..9023e6a8 --- /dev/null +++ b/app/test/features/graph/viewport/graph_viewport_math_test.dart @@ -0,0 +1,134 @@ +import 'package:flutter/widgets.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'package:pipelines_app/features/graph/viewport/graph_viewport_controller.dart'; +import 'package:pipelines_app/features/graph/viewport/graph_viewport_math.dart'; + +void main() { + test('fit keeps the padding and never upscales a small graph', () { + final scale = graphFitScale( + const Size(400, 300), + const Size(1000, 800), + padding: 20, + ); + // 360/1000 and 260/800 both fit; the smaller axis wins. + expect(scale, closeTo(0.325, 1e-9)); + expect(graphFitScale(const Size(400, 300), const Size(100, 80)), 1); + }); + + test('fit clamps to the graph scale bounds', () { + expect( + graphFitScale(const Size(400, 300), const Size(10000, 10000)), + graphMinScale, + ); + expect( + graphFitScale(const Size(400, 300), const Size(1000, 800), minScale: 0.9), + 0.9, + ); + }); + + test('degenerate sizes never divide by zero', () { + expect(graphFitScale(Size.zero, const Size(100, 100)), 1); + expect(graphFitScale(const Size(400, 300), Size.zero), 1); + expect( + graphFitScale(const Size(400, 300), const Size(100, 100), padding: 200), + 1, + ); + }); + + test('pan clamp keeps part of the scaled graph visible', () { + const viewport = Size(400, 300); + const scaled = Size(800, 600); + expect( + graphClampOffset(const Offset(5000, 5000), scaled, viewport), + const Offset(400 - graphMinVisible, 300 - graphMinVisible), + ); + expect( + graphClampOffset(const Offset(-5000, -5000), scaled, viewport), + Offset(graphMinVisible - 800, graphMinVisible - 600), + ); + // Inside the bounds the offset is untouched. + expect( + graphClampOffset(const Offset(-100, -50), scaled, viewport), + const Offset(-100, -50), + ); + }); + + test('clamp leaves degenerate content and empty ranges alone', () { + expect( + graphClampOffset(const Offset(12, 34), Size.zero, const Size(400, 300)), + const Offset(12, 34), + ); + // The viewport is narrower than twice the minimum visible part: the range + // is empty, so the input survives rather than being pinned to a bad value. + expect( + graphClampOffset( + const Offset(500, 500), + const Size(1, 1), + const Size(40, 40), + ), + const Offset(500, 500), + ); + }); + + test('the transform draws graph points at offset + point * scale', () { + final matrix = graphViewportMatrix(const Offset(30, 20), 0.5); + expect( + MatrixUtils.transformPoint(matrix, const Offset(100, 80)), + const Offset(80, 60), + ); + expect(matrix.getMaxScaleOnAxis(), 0.5); + }); + + test('controller fits, centers and round-trips a snapshot', () { + final controller = GraphViewportController(); + addTearDown(controller.dispose); + controller.attach( + viewport: const Size(400, 300), + content: const Size(1000, 800), + ); + final fitted = controller.snapshot; + expect(fitted.scale, closeTo(0.315, 1e-9)); + expect(fitted.offset.dx, greaterThan(0)); + expect(fitted.offset.dy, greaterThan(0)); + expect( + fitted.offset, + graphCenteredOffset( + Size(1000 * fitted.scale, 800 * fitted.scale), + const Size(400, 300), + ), + ); + + controller.applySnapshot( + const GraphViewportSnapshot(scale: 2, offset: Offset(-100, -80)), + ); + expect( + controller.snapshot, + const GraphViewportSnapshot(scale: 2, offset: Offset(-100, -80)), + ); + + // A resize after the reader adjusted keeps their scale, only clamping the + // offset into the new bounds. + controller.attach( + viewport: const Size(200, 200), + content: const Size(1000, 800), + ); + expect(controller.scale, 2); + }); + + test('controller fit clamps a graph that cannot fit at the minimum', () { + final controller = GraphViewportController(); + addTearDown(controller.dispose); + controller.attach( + viewport: const Size(400, 300), + content: const Size(10000, 10000), + ); + expect(controller.scale, graphMinScale); + final scaled = 10000 * graphMinScale; + expect( + controller.offset.dx, + greaterThanOrEqualTo(graphMinVisible - scaled), + ); + expect(controller.offset.dx, lessThanOrEqualTo(400 - graphMinVisible)); + }); +} diff --git a/app/test/features/graph/viewport/graph_viewport_test.dart b/app/test/features/graph/viewport/graph_viewport_test.dart new file mode 100644 index 00000000..256d2c41 --- /dev/null +++ b/app/test/features/graph/viewport/graph_viewport_test.dart @@ -0,0 +1,238 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'package:pipelines_app/features/graph/viewport/graph_viewport.dart'; +import 'package:pipelines_app/features/graph/viewport/graph_viewport_controller.dart'; +import 'package:pipelines_app/features/graph/viewport/graph_viewport_math.dart'; + +import 'graph_viewport_fixtures.dart'; + +void main() { + testWidgets('drag pans the canvas and the pan stays bounded', (tester) async { + final controller = GraphViewportController(); + addTearDown(controller.dispose); + await tester.pumpWidget( + viewportHost(controller: controller, child: viewportTargets([])), + ); + await settleViewport(tester); + + expect(controller.scale, lessThan(1)); + final finder = find.byKey(const Key('graph-viewport')); + + final gesture = await startViewportDrag(tester, finder); + final before = controller.offset; + for (var step = 0; step < 4; step += 1) { + await gesture.moveBy(const Offset(-10, -5)); + await tester.pump(); + } + await gesture.up(); + await tester.pumpAndSettle(); + expect(controller.offset.dx, closeTo(before.dx - 40, 1)); + expect(controller.offset.dy, closeTo(before.dy - 20, 1)); + + // A huge drag can never leave an empty canvas: at least the minimum part + // of the scaled graph stays inside the viewport. + final out = await startViewportDrag(tester, finder); + await out.moveBy(const Offset(5000, 5000)); + await tester.pump(); + await out.up(); + await tester.pumpAndSettle(); + expect( + controller.offset.dx, + lessThanOrEqualTo(defaultViewportSize.width - graphMinVisible + 0.01), + ); + expect( + controller.offset.dy, + lessThanOrEqualTo(defaultViewportSize.height - graphMinVisible + 0.01), + ); + final back = await startViewportDrag(tester, finder); + await back.moveBy(const Offset(-10000, -10000)); + await tester.pump(); + await back.up(); + await tester.pumpAndSettle(); + expect( + controller.offset.dx, + greaterThanOrEqualTo( + graphMinVisible - viewportContent.width * controller.scale - 0.01, + ), + ); + }); + + testWidgets('pinch zoom clamps at the graph scale bounds', (tester) async { + final controller = GraphViewportController(); + addTearDown(controller.dispose); + await tester.pumpWidget( + viewportHost(controller: controller, child: viewportTargets([])), + ); + await settleViewport(tester); + expect(controller.scale, lessThan(1)); + + await pinchViewport(tester, const Offset(200, 150), 10); + await tester.pumpAndSettle(); + expect(controller.scale, graphMaxScale); + + await pinchViewport(tester, const Offset(200, 150), 0.01); + await tester.pumpAndSettle(); + expect(controller.scale, graphMinScale); + }); + + testWidgets('zoom keeps the graph point under the moving focal point', ( + tester, + ) async { + final controller = GraphViewportController(); + addTearDown(controller.dispose); + await tester.pumpWidget( + viewportHost(controller: controller, child: viewportTargets([])), + ); + await settleViewport(tester); + + const focal = Offset(150, 120); + final before = controller.transformation.toScene(focal); + await pinchViewport(tester, focal, 1.6); + await tester.pumpAndSettle(); + final after = controller.transformation.toScene(focal); + // A gesture is not pixel-exact: the focal point keeps its graph point + // within a few graph pixels while the transform scales. + expect(after.dx, closeTo(before.dx, 4)); + expect(after.dy, closeTo(before.dy, 4)); + expect(controller.scale, greaterThan(0.3)); + }); + + testWidgets('the first painted frame is already fitted', (tester) async { + final controller = GraphViewportController(); + addTearDown(controller.dispose); + // No extra pump: the fit must land during the first layout, not one frame + // later over an identity transform. + await tester.pumpWidget( + viewportHost(controller: controller, child: viewportTargets([])), + ); + + expect( + controller.scale, + closeTo(graphFitScale(defaultViewportSize, viewportContent), 1e-9), + ); + expect(tester.takeException(), isNull); + }); + + testWidgets('the fit control restores the fitted scale and offset', ( + tester, + ) async { + final controller = GraphViewportController(); + addTearDown(controller.dispose); + await tester.pumpWidget( + viewportHost(controller: controller, child: viewportTargets([])), + ); + await settleViewport(tester); + final fitted = controller.snapshot; + + await pinchViewport(tester, const Offset(200, 150), 2); + await dragViewport( + tester, + find.byKey(const Key('graph-viewport')), + const Offset(-30, -10), + ); + expect(controller.snapshot, isNot(fitted)); + + await tester.tap(find.byKey(const Key('graph-fit'))); + await tester.pump(); + expect(controller.scale, closeTo(fitted.scale, 1e-9)); + expect(controller.offset.dx, closeTo(fitted.offset.dx, 1e-9)); + expect(controller.offset.dy, closeTo(fitted.offset.dy, 1e-9)); + }); + + testWidgets('a tap selects the node visually under the pointer', ( + tester, + ) async { + final picked = []; + final controller = GraphViewportController(); + addTearDown(controller.dispose); + await tester.pumpWidget( + viewportHost(controller: controller, child: viewportTargets(picked)), + ); + await settleViewport(tester); + + // Bring target b to the middle, then zoom in around it. Its graph point + // stays under the focal point while the transform scales. + const targetCenter = Offset(980, 740); + final finder = find.byKey(const Key('graph-viewport')); + final gesture = await startViewportDrag(tester, finder); + final start = viewportScreenOf(controller, targetCenter); + final delta = const Offset(200, 150) - start; + for (var step = 0; step < 4; step += 1) { + await gesture.moveBy(delta / 4); + await tester.pump(); + } + await gesture.up(); + await tester.pumpAndSettle(); + await pinchViewport(tester, const Offset(200, 150), 2.4); + await tester.pumpAndSettle(); + + final underPointer = viewportScreenOf(controller, targetCenter); + final viewportRect = tester.getRect( + find.byKey(const Key('graph-viewport')), + ); + expect(viewportRect.contains(underPointer), isTrue); + expect(controller.scale, greaterThan(0.3)); + + await tester.tapAt(viewportGlobal(tester, underPointer)); + await tester.pump(); + expect(picked, ['b']); + }); + + testWidgets('an ancestor scroll view keeps scrolling outside the canvas', ( + tester, + ) async { + final controller = GraphViewportController(); + final scroll = ScrollController(); + addTearDown(controller.dispose); + addTearDown(scroll.dispose); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: ListView( + controller: scroll, + children: [ + Container(key: const Key('scroll-header'), height: 400), + SizedBox( + height: 300, + child: GraphViewport( + controller: controller, + contentSize: viewportContent, + child: viewportTargets([]), + ), + ), + Container(height: 800), + ], + ), + ), + ), + ); + await settleViewport(tester); + + // A drag outside the canvas scrolls the ancestor and never pans the graph. + await tester.dragFrom(const Offset(400, 60), const Offset(0, -120)); + await tester.pumpAndSettle(); + expect(scroll.offset, greaterThan(0)); + final scrolled = scroll.offset; + final graphBefore = controller.offset; + expect(controller.offset, graphBefore); + + // Inside its own box the canvas consumes the drag: the graph pans and the + // list keeps its position. + await dragViewport( + tester, + find.byKey(const Key('graph-viewport')), + const Offset(-40, 0), + warmUp: const Offset(-10, 0), + ); + expect(scroll.offset, scrolled); + expect(controller.offset.dx, lessThan(graphBefore.dx)); + + // Scrolling outside still works afterwards and leaves the graph place alone. + final panned = controller.offset; + await tester.dragFrom(const Offset(400, 60), const Offset(0, -80)); + await tester.pumpAndSettle(); + expect(scroll.offset, greaterThan(scrolled)); + expect(controller.offset, panned); + }); +} diff --git a/app/test/features/graph/widgets/definition_graph_view_test.dart b/app/test/features/graph/widgets/definition_graph_view_test.dart index ed448257..e92c9794 100644 --- a/app/test/features/graph/widgets/definition_graph_view_test.dart +++ b/app/test/features/graph/widgets/definition_graph_view_test.dart @@ -82,6 +82,22 @@ Finder _node(String key) => find.byWidgetPredicate( (widget) => widget is GraphStageNode && widget.node.key == key, ); +/// The graph-space extent of a placed node. +/// +/// The viewport fits the measured graph into the available box, so an onstage +/// node's rectangle is its measured extent times the current scale. Dividing +/// the rectangle by that scale keeps these assertions about measurement rather +/// than about the viewport transform. +Size _measuredNodeSize(WidgetTester tester, String key) { + final scale = tester + .widget(find.byType(InteractiveViewer)) + .transformationController! + .value + .getMaxScaleOnAxis(); + final rect = _nodeRect(tester, key); + return Size(rect.width / scale, rect.height / scale); +} + Rect _nodeRect(WidgetTester tester, String key) => tester.getRect(_node(key)); Future _tapNode(WidgetTester tester, String key) async { @@ -123,11 +139,11 @@ void main() { addTearDown(tester.view.reset); await tester.pumpWidget(_materialHost(_longKeyGraph())); await _settle(tester); - final wide = _nodeRect(tester, _longKey); + final wide = _measuredNodeSize(tester, _longKey); tester.view.physicalSize = const Size(320, 700); await tester.pump(); await _settle(tester); - final narrow = _nodeRect(tester, _longKey); + final narrow = _measuredNodeSize(tester, _longKey); expect(narrow.width, lessThan(wide.width)); expect(narrow.width, lessThanOrEqualTo(320)); expect(narrow.height, greaterThan(wide.height)); @@ -156,6 +172,42 @@ void main() { expect(picked, ['plan', '#success']); }); + testWidgets('a tap after zoom selects the node under the pointer', ( + tester, + ) async { + final picked = []; + await tester.pumpWidget( + _materialHost(linearGraph(), onSelected: picked.add), + ); + await _settle(tester); + final controller = tester + .widget(find.byType(InteractiveViewer)) + .transformationController!; + final fitted = controller.value.getMaxScaleOnAxis(); + + // Scale about the node's own on-screen point, as a pinch there would. + final viewportRect = tester.getRect(find.byType(InteractiveViewer)); + final anchor = _nodeRect(tester, 'build').center - viewportRect.topLeft; + final zoom = Matrix4.identity() + ..translateByDouble(anchor.dx, anchor.dy, 0, 1) + ..scaleByDouble(1.6, 1.6, 1.6, 1) + ..translateByDouble(-anchor.dx, -anchor.dy, 0, 1); + controller.value = zoom * controller.value; + await tester.pump(); + expect(controller.value.getMaxScaleOnAxis(), greaterThan(fitted)); + + // The node's on-screen rectangle already carries the transform, so this + // tap lands where the node is drawn rather than at its graph coordinate. + final build = _nodeRect(tester, 'build'); + expect( + tester.getRect(find.byType(InteractiveViewer)).contains(build.center), + isTrue, + ); + await tester.tapAt(build.center); + await tester.pump(); + expect(picked, ['build']); + }); + testWidgets('nodes use measured native sizes and never overlap', ( tester, ) async { @@ -194,13 +246,13 @@ void main() { final graph = linearGraph(); await tester.pumpWidget(_materialHost(graph)); await _settle(tester); - final oneX = _nodeRect(tester, 'plan'); + final oneX = _measuredNodeSize(tester, 'plan'); final oneXLabel = tester.getRect(find.text('error*')); await tester.pumpWidget(_materialHost(graph, scale: 2)); await _settle(tester); - final twoX = _nodeRect(tester, 'plan'); + final twoX = _measuredNodeSize(tester, 'plan'); expect(twoX.height, greaterThan(oneX.height)); expect(twoX.width, greaterThan(oneX.width)); expect( @@ -248,7 +300,13 @@ void main() { ); await _settle(tester); - expect(find.byType(CupertinoButton), findsNWidgets(5)); + expect( + find.descendant( + of: find.byType(GraphStageNode), + matching: find.byType(CupertinoButton), + ), + findsNWidgets(5), + ); expect(find.byType(Card), findsNothing); _expectNoOverlaps(tester); diff --git a/app/test/features/graph/widgets/run_graph_view_test.dart b/app/test/features/graph/widgets/run_graph_view_test.dart index 5b4f7512..cd14083d 100644 --- a/app/test/features/graph/widgets/run_graph_view_test.dart +++ b/app/test/features/graph/widgets/run_graph_view_test.dart @@ -5,6 +5,7 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:pipelines_app/core/api_gateway.dart'; import 'package:pipelines_app/features/graph/domain/graph_protocol.dart'; +import 'package:pipelines_app/features/graph/viewport/graph_expanded_view.dart'; import 'package:pipelines_app/features/graph/widgets/graph_stage_node.dart'; import 'package:pipelines_app/features/graph/widgets/run_graph_canvas.dart'; import 'package:pipelines_app/features/graph/widgets/run_graph_view.dart'; @@ -203,6 +204,24 @@ void main() { expect(tester.takeException(), isNull); }); + testWidgets('the expanded run graph keeps the route legend', (tester) async { + await tester.pumpWidget(_materialHost(linearGraph(), _runningRun())); + await _settle(tester); + await tester.tap(find.byKey(const Key('graph-expand'))); + await tester.pumpAndSettle(); + + final expanded = find.byType(GraphExpandedView); + expect(expanded, findsOneWidget); + for (final label in [runGraphExecuted, runGraphNotExecuted]) { + expect( + find.descendant(of: expanded, matching: find.text(label)), + findsOneWidget, + reason: 'the full-screen canvas must explain its routes: $label', + ); + } + expect(tester.takeException(), isNull); + }); + testWidgets('only routes the run took are executed and labelled', ( tester, ) async { @@ -439,7 +458,13 @@ void main() { await _settle(tester); expect(find.byType(Card), findsNothing); - expect(find.byType(CupertinoButton), findsNWidgets(5)); + expect( + find.descendant( + of: find.byType(GraphStageNode), + matching: find.byType(CupertinoButton), + ), + findsNWidgets(5), + ); expect(find.text(runGraphExecuted), findsOneWidget); expect(find.text(runGraphNotExecuted), findsOneWidget); expect( diff --git a/app/tool/graph_zoom_probe.dart b/app/tool/graph_zoom_probe.dart new file mode 100644 index 00000000..154776fe --- /dev/null +++ b/app/tool/graph_zoom_probe.dart @@ -0,0 +1,170 @@ +// Isolated browser fixture for the graph viewport (pan/zoom/expanded). +// +// Build and probe (from app/): +// flutter build web -t tool/graph_zoom_probe.dart \ +// --output build/probe-graph-zoom +// PROBE_VARIANT=material OPENCODE_ARTIFACT_DIR=DIR node tool/graph_zoom_probe.mjs +// +// Server-shaped fixtures only; no server, run or operator session is touched. +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/graph/widgets/definition_graph_view.dart'; +import 'package:pipelines_app/features/graph/widgets/run_graph_view.dart'; + +const String _longKey = 'implementer-with-an-unusually-long-stage-label'; + +JsonMap _definition() => { + 'name': 'Viewport probe', + 'stages': [ + { + 'key': 'plan', + 'type': 'model', + 'edges': {'success': 'build', 'error': '#'}, + 'fallback_error': true, + }, + { + 'key': 'build', + 'type': 'model', + 'edges': {'success': _longKey, 'retry': 'build'}, + }, + { + 'key': _longKey, + 'type': 'model', + 'edges': {'success': 'audit', 'blocked': '#failure'}, + }, + { + 'key': 'audit', + 'type': 'model', + 'edges': {'success': '#success', 'error': '#failure'}, + }, + ], +}; + +JsonMap _run() => { + 'id': 701, + 'title': 'Viewport probe', + 'status': 'succeeded', + 'executing': false, + 'graph': _definition(), + 'steps': [ + { + 'stage': 'plan', + 'sequence': 1, + 'status': 'completed', + 'outcome': 'success', + 'target': 'build', + }, + { + 'stage': 'build', + 'sequence': 2, + 'status': 'completed', + 'outcome': 'success', + 'target': _longKey, + }, + ], + 'current_stage': '', +}; + +void main() { + final parameters = Uri.base.queryParameters; + runApp( + _ProbeApp( + runMode: parameters['view'] == 'run', + cupertino: parameters['style'] == 'cupertino', + scale: double.tryParse(parameters['scale'] ?? '') ?? 1, + ), + ); +} + +class _ProbeApp extends StatelessWidget { + const _ProbeApp({ + required this.runMode, + required this.cupertino, + required this.scale, + }); + + final bool runMode; + final bool cupertino; + final double scale; + + @override + Widget build(BuildContext context) { + final page = _ProbePage(runMode: runMode, scale: scale); + if (cupertino) { + return CupertinoApp( + theme: const CupertinoThemeData(brightness: Brightness.dark), + home: CupertinoPageScaffold( + navigationBar: const CupertinoNavigationBar( + middle: Text('Graph viewport'), + ), + child: SafeArea(child: page), + ), + ); + } + return MaterialApp( + theme: ThemeData(platform: TargetPlatform.android), + darkTheme: ThemeData( + platform: TargetPlatform.android, + brightness: Brightness.dark, + ), + themeMode: ThemeMode.system, + home: Scaffold( + appBar: AppBar(title: const Text('Graph viewport')), + body: SafeArea(child: page), + ), + ); + } +} + +class _ProbePage extends StatefulWidget { + const _ProbePage({required this.runMode, required this.scale}); + + final bool runMode; + final double scale; + + @override + State<_ProbePage> createState() => _ProbePageState(); +} + +class _ProbePageState extends State<_ProbePage> { + String? _selected = 'build'; + + void _select(String key) => setState(() => _selected = key); + + @override + Widget build(BuildContext context) { + final runMode = widget.runMode; + final view = runMode + ? RunGraphView( + graph: _definition(), + run: _run(), + selectedStage: _selected, + onStageSelected: _select, + ) + : DefinitionGraphView( + graph: _definition(), + selectedStage: _selected, + onSelected: _select, + ); + return Padding( + padding: const EdgeInsets.all(12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('Selected: ${_selected ?? 'none'}'), + const SizedBox(height: 8), + Expanded( + child: MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(widget.scale)), + child: view, + ), + ), + ], + ), + ); + } +} diff --git a/app/tool/graph_zoom_probe.mjs b/app/tool/graph_zoom_probe.mjs new file mode 100644 index 00000000..07eebb62 --- /dev/null +++ b/app/tool/graph_zoom_probe.mjs @@ -0,0 +1,372 @@ +// Real-browser acceptance for the graph viewport (pan, zoom, expanded). +// +// Serves the probe build (`flutter build web -t tool/graph_zoom_probe.dart`) on +// an OS-assigned loopback port, drives a real headless Chrome against the +// actual DefinitionGraphView / RunGraphView, and asserts that a drag pans, a +// wheel zooms, Fit restores the fitted scale, Expand opens the same canvas with +// the selected node, and Close returns to the previous place and selection. +// +// PROBE_VARIANT=material|cupertino PROBE_VIEW=pipeline|run \ +// PROBE_SCHEME=dark|light PROBE_SCALE=1|2 PROBE_WIDTH=1280 PROBE_HEIGHT=800 \ +// PROBE_WEB_ROOT= OPENCODE_ARTIFACT_DIR= \ +// node tool/graph_zoom_probe.mjs +import { createServer } from 'node:http'; +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'; +import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; + +const root = resolve( + process.env.PROBE_WEB_ROOT ?? join(process.cwd(), 'build/probe-graph-zoom'), +); +const variant = process.env.PROBE_VARIANT ?? 'material'; +const view = process.env.PROBE_VIEW ?? 'pipeline'; +const scheme = process.env.PROBE_SCHEME ?? 'dark'; +const scale = process.env.PROBE_SCALE ?? '1'; +const width = Number(process.env.PROBE_WIDTH ?? 1280); +const height = Number(process.env.PROBE_HEIGHT ?? 800); +const artifactDir = + process.env.OPENCODE_ARTIFACT_DIR ?? join(tmpdir(), 'graph-zoom-capture'); +const chromePath = + process.env.CHROME_PATH ?? + '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'; +const title = view === 'run' ? 'Run graph' : 'Pipeline graph'; +const prefix = `${view}-${variant}-${scheme}-${scale}x-${width}x${height}`; +const mime = { + '.html': 'text/html', + '.js': 'text/javascript', + '.json': 'application/json', + '.wasm': 'application/wasm', + '.png': 'image/png', + '.ico': 'image/x-icon', + '.otf': 'font/otf', + '.ttf': 'font/ttf', +}; + +await mkdir(artifactDir, { recursive: true }); +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(), 'graph-zoom-chrome-')); +const chrome = spawn( + chromePath, + [ + '--headless=new', + '--no-first-run', + '--no-default-browser-check', + '--disable-gpu', + '--remote-debugging-port=0', + `--user-data-dir=${profile}`, + 'about:blank', + ], + { stdio: ['ignore', 'ignore', 'pipe'] }, +); +let stderr = ''; +chrome.stderr.on('data', (data) => { + stderr += data; +}); +const waitFor = async (fn) => { + for (let i = 0; i < 120; i++) { + const value = await fn(); + if (value) return value; + await delay(100); + } + throw new Error('Timed out waiting for Chrome DevTools'); +}; + +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((done) => { + const callId = ++id; + pending.set(callId, done); + ws.send( + JSON.stringify({ + id: callId, + method, + params, + ...(sessionId ? { sessionId } : {}), + }), + ); + }); + const created = await send('Target.createTarget', { url: 'about:blank' }); + 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); + await send( + 'Emulation.setEmulatedMedia', + { features: [{ name: 'prefers-color-scheme', value: scheme }] }, + session, + ); + const url = + `http://127.0.0.1:${port}/?style=${variant}&view=${view}` + + `&scale=${scale}`; + const navigation = await send('Page.navigate', { url }, session); + if (navigation.error || navigation.result?.errorText) { + throw new Error(JSON.stringify(navigation)); + } + await send( + 'Emulation.setDeviceMetricsOverride', + { width, height, deviceScaleFactor: 1, mobile: width < 600 }, + 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; + }; + await delay(4000); + await evaluate("document.querySelector('flt-semantics-placeholder')?.click()"); + await delay(2000); + + const semantics = () => + evaluate( + "[...document.querySelectorAll('flt-semantics')].map(x=>({label:(x.getAttribute('aria-label')||x.innerText||'').trim(), current:x.getAttribute('aria-current')}))", + ); + const nodeAt = (needle) => + `[...document.querySelectorAll('flt-semantics')].find(x => { const l=(x.getAttribute('aria-label')||x.innerText||'').trim(); return l === ${JSON.stringify(needle)} || l.startsWith(${JSON.stringify(needle + ' ')}) || l.startsWith(${JSON.stringify(needle + '\n')}); })`; + const rectOf = async (needle) => + evaluate( + `(() => { const e=${nodeAt(needle)}; if (!e) return null; const r=e.getBoundingClientRect(); return {x:r.x,y:r.y,width:r.width,height:r.height}; })()`, + ); + const clickLabel = async (label, startsWith = false) => { + const point = await evaluate( + `(() => { const e=[...document.querySelectorAll('flt-semantics')].find(x => { const l=(x.getAttribute('aria-label')||x.innerText||'').trim(); return ${startsWith ? `l.startsWith(${JSON.stringify(label)})` : `l === ${JSON.stringify(label)}`}; }); if (!e) return null; const r=e.getBoundingClientRect(); return {x:r.x+r.width/2,y:r.y+r.height/2}; })()`, + ); + if (!point) throw new Error(`No semantics control ${label}`); + await send( + 'Input.dispatchMouseEvent', + { type: 'mousePressed', ...point, button: 'left', clickCount: 1 }, + session, + ); + await send( + 'Input.dispatchMouseEvent', + { type: 'mouseReleased', ...point, button: 'left', clickCount: 1 }, + session, + ); + await delay(700); + }; + // Activates the control through its own semantics DOM element, the path a + // screen reader uses. A labelled node without a tap action does nothing. + const semanticsClick = async (label) => { + const clicked = await evaluate( + `(() => { const e=[...document.querySelectorAll('flt-semantics')].find(x => { const l=(x.getAttribute('aria-label')||x.innerText||'').trim(); return l === ${JSON.stringify(label)}; }); if (!e) return false; e.click(); return true; })()`, + ); + if (!clicked) throw new Error(`No semantics control ${label}`); + await delay(700); + }; + const drag = async (start, dx, dy) => { + await send( + 'Input.dispatchMouseEvent', + { type: 'mousePressed', ...start, button: 'left', buttons: 1, clickCount: 1 }, + session, + ); + for (let step = 1; step <= 8; step += 1) { + await send( + 'Input.dispatchMouseEvent', + { + type: 'mouseMoved', + x: start.x + (dx * step) / 8, + y: start.y + (dy * step) / 8, + button: 'left', + buttons: 1, + }, + session, + ); + await delay(30); + } + await send( + 'Input.dispatchMouseEvent', + { + type: 'mouseReleased', + x: start.x + dx, + y: start.y + dy, + button: 'left', + clickCount: 1, + }, + session, + ); + await delay(500); + }; + const wheel = async (point, deltaY) => { + await send( + 'Input.dispatchMouseEvent', + { type: 'mouseWheel', ...point, deltaX: 0, deltaY }, + session, + ); + await delay(600); + }; + const capture = async (name) => { + const data = ( + await send( + 'Page.captureScreenshot', + { format: 'png', captureBeyondViewport: false }, + session, + ) + ).result.data; + const file = `${prefix}-${name}.png`; + await writeFile(`${artifactDir}/${file}`, Buffer.from(data, 'base64')); + return file; + }; + const currentSelection = async () => { + const items = await semantics(); + const current = items.find((item) => item.current === 'true'); + if (!current) throw new Error(`No selected node announced: ${JSON.stringify(items)}`); + return current.label; + }; + const body = await evaluate('document.body.innerText'); + if (!body.includes('Selected: build')) { + throw new Error(`Initial selection missing: ${body}`); + } + const selected = await currentSelection(); + if (!selected.startsWith('build')) { + throw new Error(`build is not announced selected: ${selected}`); + } + const initial = await rectOf('build'); + if (!initial || initial.width <= 0) throw new Error('build node is not visible'); + const captures = [await capture('initial')]; + + // Pan: a real drag inside the canvas moves the node. + const start = { x: width / 2, y: height * 0.6 }; + await drag(start, 80, 40); + const panned = await rectOf('build'); + if ( + !panned || + (Math.abs(panned.x - initial.x) < 20 && Math.abs(panned.y - initial.y) < 20) + ) { + throw new Error(`Drag did not pan: ${JSON.stringify({ initial, panned })}`); + } + captures.push(await capture('panned')); + if (!(await currentSelection()).startsWith('build')) { + throw new Error('Panning lost the selected node'); + } + + // Zoom: the host wheel zooms about the pointer. + await wheel( + { x: panned.x + panned.width / 2, y: panned.y + panned.height / 2 }, + -120, + ); + const zoomed = await rectOf('build'); + if (!zoomed || zoomed.width <= panned.width * 1.05) { + throw new Error(`Wheel did not zoom: ${JSON.stringify({ panned, zoomed })}`); + } + captures.push(await capture('zoomed')); + if (!(await currentSelection()).startsWith('build')) { + throw new Error('Zooming lost the selected node'); + } + + // Fit restores the fitted scale. This activation goes through the control's + // semantics element, so a labelled button with no tap action fails here (the + // Cupertino regression). + await semanticsClick('Fit graph to view'); + const fitted = await rectOf('build'); + if (!fitted || Math.abs(fitted.width - initial.width) > initial.width * 0.03) { + throw new Error(`Fit did not restore: ${JSON.stringify({ initial, fitted })}`); + } + captures.push(await capture('fitted')); + + // Expanded opens the same canvas with the same selection. + const beforeExpand = await rectOf('build'); + await clickLabel('Expand graph'); + const expandedBody = await evaluate('document.body.innerText'); + if (!expandedBody.includes(title)) { + throw new Error(`Expanded title missing: ${expandedBody}`); + } + const expandedSelection = await currentSelection(); + if (!expandedSelection.startsWith('build')) { + throw new Error(`Expanded lost the selection: ${expandedSelection}`); + } + if (!(await rectOf('build'))) { + throw new Error('Expanded canvas did not draw the graph'); + } + captures.push(await capture('expanded')); + + // Close returns to the inline canvas, selection and place intact. + await clickLabel('Close'); + const closedBody = await evaluate('document.body.innerText'); + if (closedBody.includes(title)) { + throw new Error(`Expanded presentation stayed open: ${closedBody}`); + } + if (!(await currentSelection()).startsWith('build')) { + throw new Error('Closing the expanded view lost the selected node'); + } + const restored = await rectOf('build'); + if ( + !restored || + Math.abs(restored.x - beforeExpand.x) > 2 || + Math.abs(restored.y - beforeExpand.y) > 2 + ) { + throw new Error( + `Closing did not restore the inline place: ${JSON.stringify({ beforeExpand, restored })}`, + ); + } + captures.push(await capture('restored')); + + console.log( + JSON.stringify( + { view, variant, scheme, scale, width, height, initial, panned, zoomed, restored, captures }, + null, + 2, + ), + ); +} finally { + if (ws?.readyState === WebSocket.OPEN) { + ws.send(JSON.stringify({ id: 2147483647, method: 'Browser.close' })); + } + await Promise.race([once(chrome, 'exit'), delay(3000)]); + ws?.close(); + if (chrome.exitCode === null) chrome.kill('SIGTERM'); + chrome.stderr.destroy(); + chrome.unref(); + await new Promise((done) => { + server.close(done); + server.closeAllConnections(); + }); + await rm(profile, { recursive: true, force: true }); +} From f0d621250fd27070f68f159ee681a13b2a2634d9 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 22 Oct 2026 02:05:13 +0100 Subject: [PATCH 12/13] feat(app): recorded visit pane in the run Timeline --- app/lib/core/transport/pipelines_client.dart | 11 + .../artifacts/domain/artifact_groups.dart | 22 ++ .../artifacts/ui/artifact_gallery_action.dart | 13 +- .../artifacts/ui/artifact_gallery_page.dart | 40 ++- .../runs/ui/run_detail_cupertino.dart | 2 + .../features/runs/ui/run_detail_material.dart | 2 + .../runs/ui/run_detail_tab_strip.dart | 9 +- app/lib/features/runs/ui/run_detail_tabs.dart | 51 ++- .../features/runs/ui/run_detail_timeline.dart | 21 +- app/lib/features/runs/ui/run_detail_view.dart | 4 + .../features/runs/ui/run_detail_visit.dart | 215 +++++++++++++ .../runs/ui/run_detail_visit_artifacts.dart | 112 +++++++ .../runs/ui/run_detail_visit_definition.dart | 46 +++ .../runs/ui/run_detail_visit_facts.dart | 105 +++++++ .../runs/ui/run_detail_visit_sections.dart | 124 ++++++++ .../runs/ui/run_detail_visit_session.dart | 149 +++++++++ .../ui/run_detail_visit_session_state.dart | 230 ++++++++++++++ app/notes/R4-visit.md | 190 ++++++++++++ .../domain/artifact_groups_test.dart | 33 ++ .../runs/ui/run_detail_graph_support.dart | 13 +- .../runs/ui/run_detail_graph_tab_test.dart | 22 +- .../ui/run_detail_visit_sections_test.dart | 187 +++++++++++ .../ui/run_detail_visit_session_test.dart | 147 +++++++++ .../runs/ui/run_detail_visit_support.dart | 116 +++++++ .../runs/ui/run_detail_visit_test.dart | 106 +++++++ app/tool/run_detail_graph_probe.mjs | 22 +- app/tool/run_detail_visit_probe.dart | 189 ++++++++++++ app/tool/run_detail_visit_probe.mjs | 290 ++++++++++++++++++ 28 files changed, 2419 insertions(+), 52 deletions(-) create mode 100644 app/lib/features/runs/ui/run_detail_visit.dart create mode 100644 app/lib/features/runs/ui/run_detail_visit_artifacts.dart create mode 100644 app/lib/features/runs/ui/run_detail_visit_definition.dart create mode 100644 app/lib/features/runs/ui/run_detail_visit_facts.dart create mode 100644 app/lib/features/runs/ui/run_detail_visit_sections.dart create mode 100644 app/lib/features/runs/ui/run_detail_visit_session.dart create mode 100644 app/lib/features/runs/ui/run_detail_visit_session_state.dart create mode 100644 app/notes/R4-visit.md create mode 100644 app/test/features/runs/ui/run_detail_visit_sections_test.dart create mode 100644 app/test/features/runs/ui/run_detail_visit_session_test.dart create mode 100644 app/test/features/runs/ui/run_detail_visit_support.dart create mode 100644 app/test/features/runs/ui/run_detail_visit_test.dart create mode 100644 app/tool/run_detail_visit_probe.dart create mode 100644 app/tool/run_detail_visit_probe.mjs diff --git a/app/lib/core/transport/pipelines_client.dart b/app/lib/core/transport/pipelines_client.dart index 2560a238..49134588 100644 --- a/app/lib/core/transport/pipelines_client.dart +++ b/app/lib/core/transport/pipelines_client.dart @@ -247,3 +247,14 @@ class PipelinesClient implements ApiGateway { await _states.close(); } } + +/// The configured server origin of [gateway], or blank when the gateway does +/// not expose one (a feature fixture). +/// +/// Relative artifact and session urls resolve only against this origin; an +/// absolute recorded http(s) url still resolves without it. The cast lives here +/// so callers never repeat it. +String configuredGatewayEndpoint(ApiGateway gateway) { + final client = gateway is PipelinesClient ? gateway : null; + return client?.endpoint?.toString() ?? ''; +} diff --git a/app/lib/features/artifacts/domain/artifact_groups.dart b/app/lib/features/artifacts/domain/artifact_groups.dart index bfa0707e..f9d861f3 100644 --- a/app/lib/features/artifacts/domain/artifact_groups.dart +++ b/app/lib/features/artifacts/domain/artifact_groups.dart @@ -107,3 +107,25 @@ List visitArtifacts(JsonMap step, List runSteps) { if (!artifact.isPublicName || !seen.contains(artifact.name)) artifact, ]; } + +/// The gallery group of exactly one recorded visit, addressed by its index in +/// [runSteps]. The whole run is still read so a shared `public/` file stays with +/// the visit that first recorded it and the group keeps the run's own visit +/// numbering. Null when the index is out of range or the visit recorded no +/// presentable stage artifact. +ArtifactGroup? visitArtifactGroup(List runSteps, int index) { + if (index < 0 || index >= runSteps.length) return null; + final step = runSteps[index]; + final stage = '${step['stage'] ?? ''}'; + final visits = visitsByStage(runSteps)[stage]; + if (visits == null) return null; + // The pane passes the index of the same parsed list, so the recorded map is + // the identical instance the stage grouping holds. + final position = visits.indexOf(step); + if (position < 0) return null; + final visit = displayVisit(step, position); + for (final group in artifactGroups(runSteps)) { + if (group.stageKey == stage && group.visit == visit) return group; + } + return null; +} diff --git a/app/lib/features/artifacts/ui/artifact_gallery_action.dart b/app/lib/features/artifacts/ui/artifact_gallery_action.dart index 7cffb7c8..bbcfd8a5 100644 --- a/app/lib/features/artifacts/ui/artifact_gallery_action.dart +++ b/app/lib/features/artifacts/ui/artifact_gallery_action.dart @@ -35,15 +35,6 @@ bool _runExecuting(JsonMap run) => run['executing'] == true || _executingStatuses.contains('${run['status'] ?? ''}'.trim().toLowerCase()); -/// The configured endpoint from the app's shared transport, when the gateway -/// exposes it. Feature fixtures without an endpoint leave it blank, which only -/// disables relative url resolution: an absolute recorded http(s) url still -/// resolves. The url rules themselves live in `artifact_url.dart`. -String _gatewayEndpoint(ApiGateway gateway) { - final endpoint = gateway is PipelinesClient ? gateway.endpoint : null; - return endpoint?.toString() ?? ''; -} - /// The run detail's standard native action that opens the recorded artifact /// groups. It is composed only when [showRunArtifactsAction] is true. class RunArtifactsButton extends StatelessWidget { @@ -63,7 +54,7 @@ class RunArtifactsButton extends StatelessWidget { context, steps: steps, executing: _runExecuting(run), - configuredEndpoint: _gatewayEndpoint(gateway), + configuredEndpoint: configuredGatewayEndpoint(gateway), ); if (usesCupertinoHost(context)) { return CupertinoButton.tinted( @@ -86,12 +77,14 @@ class RunArtifactsButton extends StatelessWidget { Future showArtifactGallery( BuildContext context, { required List steps, + int? focusIndex, bool executing = false, String configuredEndpoint = '', ArtifactExternalOpen openExternal = openArtifactExternally, }) { final page = ArtifactGalleryPage( steps: List.unmodifiable(steps), + focusIndex: focusIndex, executing: executing, configuredEndpoint: configuredEndpoint, openExternal: openExternal, diff --git a/app/lib/features/artifacts/ui/artifact_gallery_page.dart b/app/lib/features/artifacts/ui/artifact_gallery_page.dart index 5d79bd0f..e97c8b41 100644 --- a/app/lib/features/artifacts/ui/artifact_gallery_page.dart +++ b/app/lib/features/artifacts/ui/artifact_gallery_page.dart @@ -33,10 +33,16 @@ const String artifactGalleryTitle = 'Artifacts'; /// actions plus file `Download`/`Share` for a server-served url. Markdown /// previews use the same chat markdown renderer by default. It never filters, /// and an external url is never fetched for preview or file transfer. +/// +/// [focusIndex] limits the page to the visited `steps` index's attributed +/// group. The whole run is still passed so shared `public/` files keep their +/// first visit and the group keeps the run's visit numbering; the page then +/// lists exactly what the opening pane listed. class ArtifactGalleryPage extends StatefulWidget { const ArtifactGalleryPage({ super.key, required this.steps, + this.focusIndex, this.executing = false, this.configuredEndpoint = '', this.openExternal = openArtifactExternally, @@ -46,6 +52,10 @@ class ArtifactGalleryPage extends StatefulWidget { }); final List steps; + + /// The `steps` index whose group this page shows, or null for every group. + final int? focusIndex; + final bool executing; final String configuredEndpoint; final ArtifactExternalOpen openExternal; @@ -61,10 +71,16 @@ class _ArtifactGalleryPageState extends State { late final Map _stepsByGroup = recordedStepsByGroup( widget.steps, ); - late final List _groups = artifactGroups(widget.steps); + late final List _groups = _groupsOf(widget.focusIndex); String? _selectedIdentity; String? _status; + List _groupsOf(int? focusIndex) { + if (focusIndex == null) return artifactGroups(widget.steps); + final group = visitArtifactGroup(widget.steps, focusIndex); + return group == null ? const [] : [group]; + } + Future _select(ArtifactGroup group, ArtifactRecord artifact) async { final identity = artifactVisitIdentity(group, artifact); final resolved = artifact.hasUrl @@ -227,12 +243,28 @@ class _ArtifactGalleryPageState extends State { setState(() => _status = message); } + /// The page's one summary line: a focused visit uses its own capture summary, + /// a run-level page uses the run header, and an empty reply says so. + String _summary(List groups) { + final focusIndex = widget.focusIndex; + if (focusIndex != null && + focusIndex >= 0 && + focusIndex < widget.steps.length) { + final focused = widget.steps[focusIndex]; + final count = groups.fold( + 0, + (total, group) => total + group.artifacts.length, + ); + return artifactsSummary(focused, count: count); + } + if (widget.steps.isEmpty) return 'No steps recorded for this run.'; + return artifactsHeader(widget.steps, executing: widget.executing); + } + @override Widget build(BuildContext context) { final groups = _groups; - final summary = widget.steps.isEmpty - ? 'No steps recorded for this run.' - : artifactsHeader(widget.steps, executing: widget.executing); + final summary = _summary(groups); final body = Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ diff --git a/app/lib/features/runs/ui/run_detail_cupertino.dart b/app/lib/features/runs/ui/run_detail_cupertino.dart index 2aa71880..4da3afa0 100644 --- a/app/lib/features/runs/ui/run_detail_cupertino.dart +++ b/app/lib/features/runs/ui/run_detail_cupertino.dart @@ -20,6 +20,7 @@ Widget buildCupertinoRunDetail({ required String? copyStatus, required VoidCallback onBack, required VoidCallback onCopy, + required String configuredEndpoint, }) { final theme = CupertinoTheme.of(context); return RunDetailTabs( @@ -28,6 +29,7 @@ Widget buildCupertinoRunDetail({ copying: copying, copyStatus: copyStatus, onCopy: onCopy, + configuredEndpoint: configuredEndpoint, header: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ diff --git a/app/lib/features/runs/ui/run_detail_material.dart b/app/lib/features/runs/ui/run_detail_material.dart index 43e34533..8d27e80e 100644 --- a/app/lib/features/runs/ui/run_detail_material.dart +++ b/app/lib/features/runs/ui/run_detail_material.dart @@ -20,6 +20,7 @@ Widget buildMaterialRunDetail({ required String? copyStatus, required VoidCallback onBack, required VoidCallback onCopy, + required String configuredEndpoint, }) { final theme = Theme.of(context); return RunDetailTabs( @@ -28,6 +29,7 @@ Widget buildMaterialRunDetail({ copying: copying, copyStatus: copyStatus, onCopy: onCopy, + configuredEndpoint: configuredEndpoint, header: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ diff --git a/app/lib/features/runs/ui/run_detail_tab_strip.dart b/app/lib/features/runs/ui/run_detail_tab_strip.dart index 177217a1..f9373687 100644 --- a/app/lib/features/runs/ui/run_detail_tab_strip.dart +++ b/app/lib/features/runs/ui/run_detail_tab_strip.dart @@ -55,7 +55,7 @@ class _RunDetailTabStripState extends State { final cupertino = usesCupertinoHost(context); return Padding( padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), - child: _ScrollWhenOverflowing( + child: ScrollWhenOverflowing( child: KeyedSubtree( key: const Key('run-detail-tabs'), child: cupertino ? _cupertinoControl() : _materialControl(), @@ -97,8 +97,11 @@ class _RunDetailTabStripState extends State { /// Gives [child] at least the pane width, then scrolls instead of squeezing it /// below its content width. -class _ScrollWhenOverflowing extends StatelessWidget { - const _ScrollWhenOverflowing({required this.child}); +/// +/// The run detail's tab strips both use this, so the pointer-drag rule and the +/// minimum-width rule live in one place. +class ScrollWhenOverflowing extends StatelessWidget { + const ScrollWhenOverflowing({super.key, required this.child}); final Widget child; diff --git a/app/lib/features/runs/ui/run_detail_tabs.dart b/app/lib/features/runs/ui/run_detail_tabs.dart index ac28bd04..6641994b 100644 --- a/app/lib/features/runs/ui/run_detail_tabs.dart +++ b/app/lib/features/runs/ui/run_detail_tabs.dart @@ -9,6 +9,8 @@ import 'run_detail_tab.dart'; import 'run_detail_tab_bodies.dart'; import 'run_detail_tab_strip.dart'; import 'run_detail_timeline.dart'; +import 'run_detail_visit.dart'; +import 'run_detail_visit_facts.dart'; /// The least height the selected tab keeps for its own content. /// @@ -23,7 +25,7 @@ const double kRunDetailMinContentHeight = 240; /// /// The Graph tab fills its slot with [RunGraphView] from the run's own pinned /// graph and recorded steps. A visited stage click selects that stage's latest -/// recorded visit and switches to Timeline, where the row is highlighted. A +/// recorded visit and switches to Timeline, where that visit's pane opens. A /// node with no recorded visit reports nothing, so no visit is invented. class RunDetailTabs extends StatefulWidget { const RunDetailTabs({ @@ -34,6 +36,7 @@ class RunDetailTabs extends StatefulWidget { required this.copying, required this.copyStatus, required this.onCopy, + required this.configuredEndpoint, }); final JsonMap run; @@ -47,6 +50,10 @@ class RunDetailTabs extends StatefulWidget { final String? copyStatus; final VoidCallback onCopy; + /// The configured server origin used to resolve a recorded session export + /// through the landed safe-link helper. Blank leaves relative urls unresolved. + final String configuredEndpoint; + @override State createState() => _RunDetailTabsState(); } @@ -71,15 +78,24 @@ class _RunDetailTabsState extends State { /// Selects the stage's latest recorded visit. An unvisited stage has none, /// so the detail stays where it is rather than fabricating a visit. void _openStage(String stageKey) { - final visit = latestDetailVisit(widget.run['steps'], stageKey); - if (visit == null) return; + final index = latestDetailVisitIndex(widget.run['steps'], stageKey); + if (index == null) return; setState(() { _selectedStage = stageKey; - _selectedVisit = visit.sequence; + _selectedVisit = index; _tab = RunDetailTab.timeline; }); } + /// Opens one recorded timeline row. The row index is also the index into the + /// detail's own steps, so the pane reads exactly the visit it came from. + void _openVisit(int index) { + if (detailVisitStepAt(widget.run, index) == null) return; + setState(() => _selectedVisit = index); + } + + void _closeVisit() => setState(() => _selectedVisit = null); + @override Widget build(BuildContext context) { return LayoutBuilder( @@ -151,10 +167,33 @@ class _RunDetailTabsState extends State { cupertino: widget.cupertino, ); case RunDetailTab.timeline: + final visits = detailTimeline(widget.run['steps']); + final index = _selectedVisit; + if (index != null && index >= 0 && index < visits.length) { + final step = detailVisitStepAt(widget.run, index); + if (step != null) { + return KeyedSubtree( + key: const Key('run-detail-tab-body-timeline'), + child: RunVisitPane( + run: widget.run, + visit: visits[index], + visitIndex: index, + step: step, + runSteps: detailRunSteps(widget.run), + configuredEndpoint: widget.configuredEndpoint, + cupertino: widget.cupertino, + onClose: _closeVisit, + ), + ); + } + } return RunTimelineList( - visits: detailTimeline(widget.run['steps']), - selectedSequence: _selectedVisit, + visits: visits, + selectedSequence: index != null && index >= 0 && index < visits.length + ? visits[index].sequence + : null, cupertino: widget.cupertino, + onSelected: _openVisit, ); } } diff --git a/app/lib/features/runs/ui/run_detail_timeline.dart b/app/lib/features/runs/ui/run_detail_timeline.dart index 66bf4689..90535e40 100644 --- a/app/lib/features/runs/ui/run_detail_timeline.dart +++ b/app/lib/features/runs/ui/run_detail_timeline.dart @@ -5,20 +5,25 @@ import 'run_detail_content.dart'; /// The Timeline tab's recorded visits, one native row per visit. /// -/// [selectedSequence] is the server sequence of the visit selected from the -/// Graph tab. Only an actual recorded visit can match, so an unvisited stage -/// leaves every row unselected. +/// [onSelected] receives the row's index in [visits], so the caller opens +/// exactly the recorded step it was built from. [selectedSequence] highlights a +/// row when a selection is applied while the list is rendered; the current +/// flow replaces the rows with the pane, so it only matters for a defensive +/// host that keeps both visible. Only an actual recorded visit can match, so an +/// unvisited stage leaves every row unselected. class RunTimelineList extends StatelessWidget { const RunTimelineList({ super.key, required this.visits, required this.cupertino, this.selectedSequence, + this.onSelected, }); final List visits; final bool cupertino; final int? selectedSequence; + final ValueChanged? onSelected; @override Widget build(BuildContext context) { @@ -38,6 +43,7 @@ class RunTimelineList extends StatelessWidget { visit: visits[index], selected: visits[index].sequence == selectedSequence, cupertino: cupertino, + onTap: onSelected == null ? null : () => onSelected!(index), ), ]; if (cupertino) { @@ -59,19 +65,22 @@ class RunTimelineList extends StatelessWidget { } } -/// One recorded visit. [selected] highlights the row the Graph tab selected; -/// it is never true for a stage with no recorded visit. +/// One recorded visit. [selected] marks the row an applied selection identifies; +/// the current flow opens the pane instead of leaving a highlighted row. It is +/// never true for a stage with no recorded visit. class RunTimelineRow extends StatelessWidget { const RunTimelineRow({ super.key, required this.visit, required this.selected, required this.cupertino, + this.onTap, }); final DetailVisit visit; final bool selected; final bool cupertino; + final VoidCallback? onTap; @override Widget build(BuildContext context) { @@ -93,6 +102,7 @@ class RunTimelineRow extends StatelessWidget { context, ) : null, + onTap: onTap, ), ); } @@ -101,6 +111,7 @@ class RunTimelineRow extends StatelessWidget { leading: Icon(selected ? Icons.check_circle : Icons.circle_outlined), title: Text(visit.title), subtitle: Text(visit.subtitle), + onTap: onTap, ); } } diff --git a/app/lib/features/runs/ui/run_detail_view.dart b/app/lib/features/runs/ui/run_detail_view.dart index 3e510b62..6e2bbcb9 100644 --- a/app/lib/features/runs/ui/run_detail_view.dart +++ b/app/lib/features/runs/ui/run_detail_view.dart @@ -3,6 +3,7 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import '../../../core/api_gateway.dart'; +import '../../../core/transport/pipelines_client.dart'; import '../../../ui/adaptive/host.dart'; import 'run_detail_actions.dart'; import 'run_detail_content.dart'; @@ -45,6 +46,7 @@ class _RunDetailViewState extends State { final run = widget.controller.detail; if (run == null) return _placeholder(context, cupertino: cupertino); final prompt = detailPrompt(run); + final endpoint = configuredGatewayEndpoint(widget.gateway); final headerActions = RunDetailActions( run: run, gateway: widget.gateway, @@ -62,6 +64,7 @@ class _RunDetailViewState extends State { copyStatus: _copyStatus, onBack: widget.onBack, onCopy: () => _copyPrompt(prompt ?? '', cupertino: true), + configuredEndpoint: endpoint, ) : buildMaterialRunDetail( context: context, @@ -73,6 +76,7 @@ class _RunDetailViewState extends State { copyStatus: _copyStatus, onBack: widget.onBack, onCopy: () => _copyPrompt(prompt ?? '', cupertino: false), + configuredEndpoint: endpoint, ); }, ); diff --git a/app/lib/features/runs/ui/run_detail_visit.dart b/app/lib/features/runs/ui/run_detail_visit.dart new file mode 100644 index 00000000..93c9f818 --- /dev/null +++ b/app/lib/features/runs/ui/run_detail_visit.dart @@ -0,0 +1,215 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../core/api_gateway.dart'; +import '../../../ui/adaptive/host.dart'; +import 'run_detail_content.dart'; +import 'run_detail_visit_facts.dart'; +import 'run_detail_visit_sections.dart'; + +/// The selected recorded visit inside the Timeline tab. +/// +/// It leads with the visit's own headline facts, then native tabbed sections. +/// A fact the reply did not record is not drawn at all; a blank verdict or +/// diagnostic is not rendered as an empty decision. +class RunVisitPane extends StatefulWidget { + const RunVisitPane({ + super.key, + required this.run, + required this.visit, + required this.visitIndex, + required this.step, + required this.runSteps, + required this.configuredEndpoint, + required this.cupertino, + required this.onClose, + }); + + final JsonMap run; + final DetailVisit visit; + + /// The visit's index in [runSteps], so the artifacts section can open exactly + /// this visit's gallery group. + final int visitIndex; + + final JsonMap step; + final List runSteps; + final String configuredEndpoint; + final bool cupertino; + final VoidCallback onClose; + + @override + State createState() => _RunVisitPaneState(); +} + +class _RunVisitPaneState extends State { + RunVisitSection _section = RunVisitSection.input; + + @override + void didUpdateWidget(covariant RunVisitPane oldWidget) { + super.didUpdateWidget(oldWidget); + // A different visit starts at its first section, like a newly opened pane. + if (oldWidget.visit.sequence != widget.visit.sequence || + oldWidget.visit.stage != widget.visit.stage) { + _section = RunVisitSection.input; + } + } + + @override + Widget build(BuildContext context) { + final style = _VisitStyle.of(context); + final facts = detailVisitFacts(widget.step); + final verdict = detailVisitVerdict(widget.step); + final diagnostic = detailVisitDiagnostic(widget.step); + return Column( + key: const Key('run-visit-pane'), + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Flexible( + flex: 3, + fit: FlexFit.loose, + child: SingleChildScrollView( + key: const Key('run-visit-facts'), + padding: const EdgeInsetsDirectional.fromSTEB(16, 0, 16, 8), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _bar(style), + for (final fact in facts) _FactRow(fact: fact, style: style), + if (verdict != null) ...[ + const SizedBox(height: 8), + Text('Verdict', style: style.heading), + if (verdict.option != null) Text(verdict.option!), + if (verdict.reason != null) + Text(verdict.reason!, style: style.value), + ], + if (diagnostic != null) ...[ + const SizedBox(height: 8), + Text('Diagnostic', style: style.heading), + Text(diagnostic, style: style.value), + ], + ], + ), + ), + ), + RunVisitSectionStrip( + selected: _section, + onSelected: (section) => setState(() => _section = section), + ), + Expanded( + flex: 2, + child: runVisitSectionBody( + section: _section, + run: widget.run, + step: widget.step, + visitIndex: widget.visitIndex, + stageKey: widget.visit.stage, + runSteps: widget.runSteps, + configuredEndpoint: widget.configuredEndpoint, + cupertino: widget.cupertino, + ), + ), + ], + ); + } + + Widget _bar(_VisitStyle style) { + final close = widget.cupertino + ? CupertinoButton( + key: const Key('run-visit-back'), + padding: EdgeInsets.zero, + onPressed: widget.onClose, + child: const Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(CupertinoIcons.back), + SizedBox(width: 4), + Flexible(child: Text('Back to timeline')), + ], + ), + ) + : TextButton.icon( + key: const Key('run-visit-back'), + onPressed: widget.onClose, + icon: const Icon(Icons.arrow_back), + label: const Text('Back to timeline'), + ); + return Padding( + padding: const EdgeInsets.symmetric(vertical: 4), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Align(alignment: AlignmentDirectional.centerStart, child: close), + Padding( + padding: const EdgeInsetsDirectional.fromSTEB(8, 0, 0, 0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + widget.visit.title, + key: const Key('run-visit-title'), + style: style.heading, + ), + ], + ), + ), + ], + ), + ); + } +} + +class _FactRow extends StatelessWidget { + const _FactRow({required this.fact, required this.style}); + + final VisitFact fact; + final _VisitStyle style; + + @override + Widget build(BuildContext context) { + return Padding( + padding: const EdgeInsets.only(top: 4), + child: Text.rich( + TextSpan( + children: [ + TextSpan(text: '${fact.label}: ', style: style.muted), + TextSpan(text: fact.value, style: style.value), + ], + ), + ), + ); + } +} + +/// Host text roles only: no palette, font family or explicit size. +class _VisitStyle { + const _VisitStyle({ + required this.value, + required this.muted, + required this.heading, + }); + + factory _VisitStyle.of(BuildContext context) { + if (usesCupertinoHost(context)) { + final theme = CupertinoTheme.of(context); + final secondary = CupertinoColors.secondaryLabel.resolveFrom(context); + return _VisitStyle( + value: theme.textTheme.textStyle, + muted: theme.textTheme.textStyle.copyWith(color: secondary), + heading: theme.textTheme.navTitleTextStyle, + ); + } + final theme = Theme.of(context); + return _VisitStyle( + value: theme.textTheme.bodyMedium ?? const TextStyle(), + muted: (theme.textTheme.bodySmall ?? const TextStyle()).copyWith( + color: theme.colorScheme.onSurfaceVariant, + ), + heading: theme.textTheme.titleSmall ?? const TextStyle(), + ); + } + + final TextStyle value; + final TextStyle muted; + final TextStyle heading; +} diff --git a/app/lib/features/runs/ui/run_detail_visit_artifacts.dart b/app/lib/features/runs/ui/run_detail_visit_artifacts.dart new file mode 100644 index 00000000..6ccfb4b2 --- /dev/null +++ b/app/lib/features/runs/ui/run_detail_visit_artifacts.dart @@ -0,0 +1,112 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../core/api_gateway.dart'; +import '../../../ui/adaptive/host.dart'; +import '../../artifacts/domain/artifact_groups.dart'; +import '../../artifacts/domain/artifact_record.dart'; +import '../../artifacts/domain/artifact_summary.dart'; +import '../../artifacts/ui/artifact_gallery_action.dart'; +import '../../artifacts/ui/artifact_visit_list.dart'; + +/// The visit's recorded stage artifacts, in recorded order. +/// +/// Selecting a row opens the existing artifact gallery page for exactly this +/// visit, so the pane never grows a second viewer or a link-only substitute. +/// The page receives the whole run so a shared `public/` file stays with the +/// visit that first recorded it, and it lists exactly the rows shown here. +/// +/// An empty list is never described as "nothing recorded" on its own: the +/// existing capture semantics say whether the capture is unavailable, still +/// pending or explicitly empty for this visit. +class RunVisitArtifacts extends StatelessWidget { + const RunVisitArtifacts({ + super.key, + required this.step, + required this.visitIndex, + required this.runSteps, + required this.configuredEndpoint, + }); + + final JsonMap step; + + /// The visit's index in [runSteps], so the opened page is the same group. + final int visitIndex; + + final List runSteps; + final String configuredEndpoint; + + @override + Widget build(BuildContext context) { + final artifacts = visitArtifacts(step, runSteps); + final notes = artifactCaptureNotes(step); + if (artifacts.isEmpty) { + return ListView( + key: const Key('run-visit-body-artifacts'), + padding: const EdgeInsets.all(16), + children: [ + Text(artifactsSummary(step, count: 0)), + for (final note in notes) + Padding(padding: const EdgeInsets.only(top: 4), child: Text(note)), + ], + ); + } + void open() => showArtifactGallery( + context, + steps: runSteps.isEmpty ? [step] : runSteps, + focusIndex: runSteps.isEmpty ? 0 : visitIndex, + configuredEndpoint: configuredEndpoint, + ); + final noteRows = [ + for (final note in notes) + Padding( + padding: const EdgeInsetsDirectional.fromSTEB(16, 8, 16, 0), + child: Text(note), + ), + ]; + if (usesCupertinoHost(context)) { + return ListView( + key: const Key('run-visit-body-artifacts'), + children: [ + ...noteRows, + CupertinoListSection.insetGrouped( + children: [ + for (final artifact in artifacts) + _CupertinoArtifactRow(artifact: artifact, onTap: open), + ], + ), + ], + ); + } + return ListView( + key: const Key('run-visit-body-artifacts'), + children: [ + ...noteRows, + for (final artifact in artifacts) + ListTile( + title: Text(artifactDisplayName(artifact)), + subtitle: Text(artifactFactsLabel(artifact)), + trailing: const Icon(Icons.chevron_right), + onTap: open, + ), + ], + ); + } +} + +class _CupertinoArtifactRow extends StatelessWidget { + const _CupertinoArtifactRow({required this.artifact, required this.onTap}); + + final ArtifactRecord artifact; + final VoidCallback onTap; + + @override + Widget build(BuildContext context) { + return CupertinoListTile( + title: Text(artifactDisplayName(artifact)), + subtitle: Text(artifactFactsLabel(artifact)), + trailing: const Icon(CupertinoIcons.chevron_forward), + onTap: onTap, + ); + } +} diff --git a/app/lib/features/runs/ui/run_detail_visit_definition.dart b/app/lib/features/runs/ui/run_detail_visit_definition.dart new file mode 100644 index 00000000..e5d93a4e --- /dev/null +++ b/app/lib/features/runs/ui/run_detail_visit_definition.dart @@ -0,0 +1,46 @@ +import 'package:flutter/material.dart'; + +import '../../../core/api_gateway.dart'; +import '../../graph/widgets/stage_definition_view.dart'; +import 'run_detail_content.dart'; +import 'run_detail_visit_facts.dart'; + +/// The Definition section: the authored definition this run pinned for the +/// visit's stage, rendered by the landed [StageDefinitionView]. +/// +/// When the reply's graph does not declare the stage, the pane's exact missing +/// sentence is shown instead. Nothing is reconstructed from the current source. +class RunVisitDefinition extends StatelessWidget { + const RunVisitDefinition({ + super.key, + required this.run, + required this.stageKey, + }); + + final JsonMap run; + final String stageKey; + + @override + Widget build(BuildContext context) { + final graph = detailGraph(run); + if (!detailVisitHasDefinition(graph, stageKey)) { + return ListView( + key: const Key('run-visit-body-definition'), + padding: const EdgeInsets.all(16), + children: const [Text(unknownStageDefinition)], + ); + } + final pipelineId = run['pipeline_id']; + final version = run['version']; + return KeyedSubtree( + key: const Key('run-visit-body-definition'), + child: StageDefinitionView( + graph: graph!, + stageKey: stageKey, + pipelineId: pipelineId is num ? pipelineId.toInt() : 0, + pipelineName: detailPipeline(run), + version: version is num ? version.toInt() : 0, + ), + ); + } +} diff --git a/app/lib/features/runs/ui/run_detail_visit_facts.dart b/app/lib/features/runs/ui/run_detail_visit_facts.dart new file mode 100644 index 00000000..b26dfa4a --- /dev/null +++ b/app/lib/features/runs/ui/run_detail_visit_facts.dart @@ -0,0 +1,105 @@ +import '../../../core/api_gateway.dart'; +import '../../graph/domain/stage_definition.dart'; +import '../../pipelines/pipeline_format.dart'; +import 'run_detail_content.dart'; + +/// The exact empty wording for a visit's recorded Input and Output. They are +/// the run tabs' own sentences, so a visit never says something different for +/// the same absent fact. +const String visitEmptyInput = 'No input recorded.'; +const String visitEmptyOutput = 'No output recorded.'; + +/// One always-visible fact of a recorded visit. +typedef VisitFact = ({String label, String value}); + +/// The detail's own recorded steps as maps, in recorded order. +List detailRunSteps(JsonMap run) { + final steps = run['steps']; + if (steps is! List) return const []; + return steps.whereType().map(JsonMap.from).toList(); +} + +/// The raw step at [index] of the detail's own `steps`, or null when the reply +/// has no such recorded visit. +/// +/// The order is the server's recorded order, the same order [detailTimeline] +/// uses, so a row and its pane always describe one visit. +JsonMap? detailVisitStepAt(JsonMap run, int index) { + final steps = detailRunSteps(run); + if (index < 0 || index >= steps.length) return null; + return steps[index]; +} + +/// The row index of [stageKey]'s latest recorded visit, or null when the run +/// never recorded that stage. It reads the same ordered timeline the rows do, +/// so a Graph click opens exactly the row the operator would have selected. +int? latestDetailVisitIndex(dynamic steps, String stageKey) { + final visits = detailTimeline(steps); + int? latest; + for (var index = 0; index < visits.length; index += 1) { + if (visits[index].stage == stageKey) latest = index; + } + return latest; +} + +/// The visit's recorded facts, in the pane's order. A field the server did not +/// record is absent rather than zero, false or a guessed value. +List detailVisitFacts(JsonMap step) { + final facts = []; + final status = _text(step['status']); + if (status != null) facts.add((label: 'Status', value: status)); + final outcome = _text(step['outcome']); + if (outcome != null) facts.add((label: 'Outcome', value: outcome)); + final duration = detailVisitDuration(step); + if (duration != null) facts.add((label: 'Duration', value: duration)); + final model = detailVisitProviderModel(step); + if (model != null) facts.add((label: 'Provider/model', value: model)); + final target = _text(step['target']); + if (target != null) facts.add((label: 'Target', value: target)); + return facts; +} + +/// The visit's duration, only when the server recorded both timestamps and the +/// finish is not before the start. One stamp is not a zero-length visit. +String? detailVisitDuration(JsonMap step) { + final seconds = durationSeconds( + _text(step['started_at']), + _text(step['finished_at']), + ); + return seconds == null ? null : formatDuration(seconds); +} + +/// The effective provider/model this visit ran with, joined as +/// `provider / model` when both were recorded. A visit that recorded neither +/// has no row; one recorded part is shown alone, never completed locally. +String? detailVisitProviderModel(JsonMap step) { + final provider = _text(step['provider']); + final model = _text(step['model']); + if (provider != null && model != null) return '$provider / $model'; + return provider ?? model; +} + +/// A recorded verdict, or null when the server recorded no option and no +/// reason. An empty recorded verdict is not rendered as a decision. +({String? option, String? reason})? detailVisitVerdict(JsonMap step) { + final verdict = step['verdict']; + if (verdict is! Map) return null; + final option = _text(verdict['option']); + final reason = _text(verdict['reason']); + if (option == null && reason == null) return null; + return (option: option, reason: reason); +} + +/// The visit's diagnostic exactly as recorded, or null when it is blank. +String? detailVisitDiagnostic(JsonMap step) => _text(step['diagnostic']); + +/// Whether the reply's pinned graph declares [stageKey], so the Definition +/// section shows the authored definition rather than its missing wording. +bool detailVisitHasDefinition(JsonMap? graph, String stageKey) => + graph != null && stageDefinitionFor(graph, stageKey) != null; + +String? _text(dynamic value) { + if (value == null) return null; + final text = '$value'.trim(); + return text.isEmpty ? null : text; +} diff --git a/app/lib/features/runs/ui/run_detail_visit_sections.dart b/app/lib/features/runs/ui/run_detail_visit_sections.dart new file mode 100644 index 00000000..7f3e0321 --- /dev/null +++ b/app/lib/features/runs/ui/run_detail_visit_sections.dart @@ -0,0 +1,124 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../core/api_gateway.dart'; +import '../../../ui/adaptive/host.dart'; +import 'run_detail_tab_bodies.dart'; +import 'run_detail_tab_strip.dart'; +import 'run_detail_visit_artifacts.dart'; +import 'run_detail_visit_definition.dart'; +import 'run_detail_visit_facts.dart'; +import 'run_detail_visit_session.dart'; + +/// The visit pane's recorded sections, in the Android audit order the web +/// client follows: the turn's Input and Output, its Artifacts, its Session and +/// the authored Definition. +enum RunVisitSection { + input('Input'), + output('Output'), + artifacts('Artifacts'), + session('Session'), + definition('Definition'); + + const RunVisitSection(this.label); + + final String label; +} + +/// The visit pane's native tab strip: a Material segmented button or a Cupertino +/// segmented control. It scrolls instead of squeezing the labels when a narrow +/// pane or scaled text cannot fit them. +class RunVisitSectionStrip extends StatelessWidget { + const RunVisitSectionStrip({ + super.key, + required this.selected, + required this.onSelected, + }); + + final RunVisitSection selected; + final ValueChanged onSelected; + + @override + Widget build(BuildContext context) { + final cupertino = usesCupertinoHost(context); + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), + child: ScrollWhenOverflowing( + child: KeyedSubtree( + key: const Key('run-visit-tabs'), + child: cupertino ? _cupertinoControl() : _materialControl(), + ), + ), + ); + } + + Widget _materialControl() => SegmentedButton( + segments: [ + for (final section in RunVisitSection.values) + ButtonSegment(value: section, label: _label(section)), + ], + selected: {selected}, + showSelectedIcon: false, + onSelectionChanged: (selection) => onSelected(selection.single), + ); + + Widget _cupertinoControl() => CupertinoSegmentedControl( + groupValue: selected, + onValueChanged: onSelected, + children: { + for (final section in RunVisitSection.values) + section: Padding( + padding: const EdgeInsets.symmetric(horizontal: 8), + child: _label(section), + ), + }, + ); + + Widget _label(RunVisitSection section) => KeyedSubtree( + key: ValueKey('run-visit-tab-${section.name}'), + child: Text(section.label, maxLines: 1, softWrap: false), + ); +} + +/// The selected section's body for one recorded visit. +Widget runVisitSectionBody({ + required RunVisitSection section, + required JsonMap run, + required JsonMap step, + required int visitIndex, + required String stageKey, + required List runSteps, + required String configuredEndpoint, + required bool cupertino, +}) { + switch (section) { + case RunVisitSection.input: + return runDetailFieldTab( + tabKey: 'visit-input', + value: step['input'], + empty: visitEmptyInput, + cupertino: cupertino, + ); + case RunVisitSection.output: + return runDetailFieldTab( + tabKey: 'visit-output', + value: step['output'], + empty: visitEmptyOutput, + cupertino: cupertino, + ); + case RunVisitSection.artifacts: + return RunVisitArtifacts( + step: step, + visitIndex: visitIndex, + runSteps: runSteps, + configuredEndpoint: configuredEndpoint, + ); + case RunVisitSection.session: + return RunVisitSession( + step: step, + configuredEndpoint: configuredEndpoint, + ); + case RunVisitSection.definition: + return RunVisitDefinition(run: run, stageKey: stageKey); + } +} diff --git a/app/lib/features/runs/ui/run_detail_visit_session.dart b/app/lib/features/runs/ui/run_detail_visit_session.dart new file mode 100644 index 00000000..19268625 --- /dev/null +++ b/app/lib/features/runs/ui/run_detail_visit_session.dart @@ -0,0 +1,149 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../core/api_gateway.dart'; +import '../../../ui/adaptive/host.dart'; +import '../../artifacts/domain/artifact_record.dart'; +import '../../artifacts/domain/artifact_url.dart'; +import '../../artifacts/ui/artifact_external_open.dart'; +import 'run_detail_visit_session_state.dart'; + +/// The visit's recorded session pointer and, when the visit exported one, a +/// read-only external open of that document. +/// +/// The state comes from [detailVisitSession], so a legacy `session.html`, a +/// repair, a still-running session and a failed one each report what the server +/// recorded. The open goes through the landed safe-link helper: the recorded url +/// is resolved by [resolveArtifactUrl] and passed to [openArtifactExternally] +/// without being fetched, rewritten or previewed. A refusal is reported. +class RunVisitSession extends StatefulWidget { + const RunVisitSession({ + super.key, + required this.step, + required this.configuredEndpoint, + this.openExternal = openArtifactExternally, + }); + + final JsonMap step; + final String configuredEndpoint; + final ArtifactExternalOpen openExternal; + + @override + State createState() => _RunVisitSessionState(); +} + +class _RunVisitSessionState extends State { + String? _status; + + Future _open(ResolvedArtifactUrl resolved) async { + final opened = await widget.openExternal(resolved.uri); + if (!mounted) return; + setState( + () => _status = opened + ? 'Link opened externally.' + : 'Could not open the link.', + ); + } + + @override + Widget build(BuildContext context) { + final session = detailVisitSession(widget.step); + final export = session.export; + final resolved = export == null + ? null + : resolveArtifactUrl(widget.configuredEndpoint, export.artifact.url); + final note = export?.statusNote; + final children = [ + if (session.sessionId != null) + _SessionFact(label: 'Session', value: session.sessionId!), + if (export != null) ...[ + if (note != null) Text(note), + if (resolved == null) + const Text(visitSessionEndpointMissing) + else + _openButton(export.artifact, resolved), + ] else + Text(session.message), + if (_status != null) + Padding( + padding: const EdgeInsets.only(top: 8), + child: Semantics(liveRegion: true, child: Text(_status!)), + ), + ]; + if (usesCupertinoHost(context)) { + return ListView( + key: const Key('run-visit-body-session'), + children: [ + CupertinoListSection.insetGrouped( + children: [ + Padding( + padding: const EdgeInsetsDirectional.fromSTEB(16, 12, 16, 16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: _spaced(children), + ), + ), + ], + ), + ], + ); + } + return ListView( + key: const Key('run-visit-body-session'), + padding: const EdgeInsets.all(16), + children: _spaced(children), + ); + } + + Widget _openButton(ArtifactRecord export, ResolvedArtifactUrl resolved) { + final label = 'Open ${export.name.isEmpty ? 'session.html' : export.name}'; + if (usesCupertinoHost(context)) { + return CupertinoButton( + padding: EdgeInsets.zero, + onPressed: () => _open(resolved), + child: Text(label), + ); + } + return Align( + alignment: AlignmentDirectional.centerStart, + child: TextButton(onPressed: () => _open(resolved), child: Text(label)), + ); + } + + List _spaced(List children) => [ + for (var index = 0; index < children.length; index += 1) ...[ + if (index > 0) const SizedBox(height: 8), + children[index], + ], + ]; +} + +class _SessionFact extends StatelessWidget { + const _SessionFact({required this.label, required this.value}); + + final String label; + final String value; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final cupertino = CupertinoTheme.of(context); + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + label, + style: usesCupertinoHost(context) + ? cupertino.textTheme.tabLabelTextStyle.copyWith( + color: CupertinoColors.secondaryLabel.resolveFrom(context), + ) + : (theme.textTheme.labelMedium ?? const TextStyle()).copyWith( + color: theme.colorScheme.onSurfaceVariant, + ), + ), + const SizedBox(height: 2), + Text(value), + ], + ); + } +} diff --git a/app/lib/features/runs/ui/run_detail_visit_session_state.dart b/app/lib/features/runs/ui/run_detail_visit_session_state.dart new file mode 100644 index 00000000..0a980675 --- /dev/null +++ b/app/lib/features/runs/ui/run_detail_visit_session_state.dart @@ -0,0 +1,230 @@ +import '../../../core/api_gateway.dart'; +import '../../artifacts/domain/artifact_record.dart'; +import '../../artifacts/domain/artifact_selection.dart'; + +/// The exact wording for a visit that never started a harness session, in the +/// web audit pane's order: a skipped visit, a stopped one, a model visit whose +/// session is still being created, a failed one, and a model visit with no +/// identity at all. Only a non-model visit with nothing recorded gets the +/// generic sentence. +const String visitSessionSkipped = + 'This visit was skipped; no harness session was started.'; +const String visitSessionStopped = + 'The stage stopped before a harness session was recorded.'; +const String visitSessionStarting = 'The stage session is being created.'; +const String visitSessionFailed = 'The stage did not create a harness session.'; +const String visitSessionNoIdentity = + 'Runtime error: this model stage has no recorded session identity.'; +const String visitSessionNone = 'This visit has no harness session.'; + +/// An export that exists but cannot be resolved through the configured server. +const String visitSessionEndpointMissing = + 'Set the server URL in Settings to open the session.'; + +/// A recorded session export document and the evidence the server recorded for +/// it. +class VisitSessionExport { + const VisitSessionExport({ + required this.artifact, + this.status, + this.diagnostic, + this.truncated = false, + }); + + final ArtifactRecord artifact; + final String? status; + final String? diagnostic; + final bool truncated; + + /// A partial or failed export is still the recorded document; it stays + /// openable and the pane says what the evidence reports. + bool get isComplete => status == 'complete' && !truncated; + + /// The evidence sentence shown beside a present but incomplete export, or + /// null when the export is complete or the visit recorded no evidence. + String? get statusNote { + if (isComplete) return null; + if (status == null && !truncated) return null; + return 'This export is ${status ?? 'partial'}; full session evidence is ' + 'not available.'; + } +} + +/// A visit's recorded session: its identity, an openable export document and, +/// when neither exists, the one sentence describing the recorded state. +class VisitSessionState { + const VisitSessionState({this.sessionId, this.export, this.message = ''}); + + final String? sessionId; + final VisitSessionExport? export; + + /// Empty exactly when [export] is present. + final String message; +} + +/// Resolves the recorded session state without inventing a session. +/// +/// The export is looked up through the recorded export evidence (including a +/// repair that replaced it) and then, for a historical visit that recorded no +/// evidence at all, through the `session.html` its inventory carries. When the +/// evidence names no file, its own status and diagnostic are reported instead +/// of claiming the inventory is empty. +VisitSessionState detailVisitSession(JsonMap step) { + final sessionId = detailVisitSessionIdentity(step); + final export = detailVisitSessionExport(step); + if (export != null) { + return VisitSessionState(sessionId: sessionId, export: export); + } + if (sessionId != null) { + return VisitSessionState( + sessionId: sessionId, + message: _missingExportMessage(step, sessionId), + ); + } + return VisitSessionState(message: _noSessionMessage(step)); +} + +/// The recorded harness session identity, from the step or its export evidence. +String? detailVisitSessionIdentity(JsonMap step) { + final direct = _text(step['session_id']); + if (direct != null) return direct; + final evidence = _firstEvidence(step); + return evidence == null ? null : _text(evidence['session_id']); +} + +/// The visit's recorded export document, or null when no recorded export name +/// is present in the inventory. +/// +/// The step's own `session_export` is preferred; a repair document is used +/// when that is the file the inventory actually carries. A visit with no export +/// evidence at all falls back to its `session.html` system artifact, exactly as +/// the web audit pane does for runs recorded before the evidence field existed. +VisitSessionExport? detailVisitSessionExport(JsonMap step) { + final evidence = _exportEvidence(step); + for (final entry in evidence) { + final artifact = _artifactNamed(step, _text(entry['html'])); + if (artifact == null) continue; + return VisitSessionExport( + artifact: artifact, + status: _text(entry['status']), + diagnostic: _text(entry['diagnostic']), + truncated: entry['truncated'] == true, + ); + } + if (evidence.isNotEmpty) return null; + for (final artifact in systemArtifacts(step)) { + if (artifact.name == 'session.html') { + return VisitSessionExport(artifact: artifact); + } + } + return null; +} + +String _missingExportMessage(JsonMap step, String sessionId) { + final evidence = _firstEvidence(step); + final recovery = step['session_export_recovery']; + final recoveryStatus = recovery is Map ? _text(recovery['status']) : null; + final evidenceStatus = evidence == null ? null : _text(evidence['status']); + final String status; + if (recoveryStatus == 'pending' || recoveryStatus == 'running') { + status = 'pending recovery'; + } else if (evidenceStatus == 'complete') { + status = 'not available in the artifact inventory'; + } else { + status = evidenceStatus ?? 'not yet available'; + } + final diagnostic = evidence == null ? null : _text(evidence['diagnostic']); + final suffix = diagnostic == null ? '' : ' $diagnostic'; + return 'Session $sessionId is recorded. Its export is $status.$suffix'; +} + +String _noSessionMessage(JsonMap step) { + final status = _text(step['status']); + if (status == 'skipped' || _text(step['outcome']) == 'skipped') { + return visitSessionSkipped; + } + if (status == 'canceled' || status == 'interrupted') { + return visitSessionStopped; + } + final model = _text(step['provider']) != null || _text(step['model']) != null; + if (!model) return visitSessionNone; + if (status == 'running') return visitSessionStarting; + if (status == 'failed') { + final diagnostic = _text(step['diagnostic']); + return diagnostic == null + ? visitSessionFailed + : '$visitSessionFailed $diagnostic'; + } + return visitSessionNoIdentity; +} + +/// The recorded export evidence, most current first: a complete repair, then a +/// complete original, then every remaining candidate. A failed later attempt +/// never hides an earlier verified document; an older original never hides the +/// repair that replaced it. +List _exportEvidence(JsonMap step) { + final repairs = []; + final recordedRepairs = step['session_export_repairs']; + if (recordedRepairs is List) { + for (final entry in recordedRepairs.reversed) { + if (entry is Map) repairs.add(entry); + } + } + final original = step['session_export']; + final ordered = []; + void add(Map entry) { + for (final candidate in ordered) { + if (identical(candidate, entry)) return; + } + ordered.add(entry); + } + + for (final repair in repairs) { + if (_isComplete(repair)) add(repair); + } + if (original is Map && _isComplete(original)) add(original); + for (final repair in repairs) { + add(repair); + } + if (original is Map) add(original); + return ordered; +} + +Map? _firstEvidence(JsonMap step) { + final original = step['session_export']; + if (original is Map) return original; + final repairs = step['session_export_repairs']; + if (repairs is List) { + for (final entry in repairs.reversed) { + if (entry is Map) return entry; + } + } + return null; +} + +bool _isComplete(Map evidence) => + _text(evidence['status']) == 'complete' && + _positive(evidence['messages']) && + _positive(evidence['html_bytes']) && + evidence['truncated'] != true && + _text(evidence['diagnostic']) == null; + +bool _positive(dynamic value) { + if (value is num) return value > 0; + if (value is String) return (int.tryParse(value.trim()) ?? 0) > 0; + return false; +} + +ArtifactRecord? _artifactNamed(JsonMap step, String? name) { + if (name == null) return null; + for (final artifact in artifactsOf(step)) { + if (artifact.name == name) return artifact; + } + return null; +} + +String? _text(dynamic value) { + if (value == null) return null; + final text = '$value'.trim(); + return text.isEmpty ? null : text; +} diff --git a/app/notes/R4-visit.md b/app/notes/R4-visit.md new file mode 100644 index 00000000..082b0499 --- /dev/null +++ b/app/notes/R4-visit.md @@ -0,0 +1,190 @@ +# R4 — recorded-visit pane + +## Delivered + +The Timeline tab now opens a real recorded visit. Selecting a row, or clicking a +visited stage in the Graph tab, shows that visit inside the Timeline tab: + +- **Facts** — the row's exact stage/visit title, then only the fields the reply + recorded: Status, Outcome, Duration (only when both `started_at` and + `finished_at` parse and the finish is not before the start), Provider/model + (`provider / model`, or the one part recorded), Target, a recorded Verdict + (option and reason) and the visit's Diagnostic. A blank field is absent, never + `0`, `false`, `0s` or a guessed value. +- **Native sections** — Input, Output, Artifacts, Session, Definition, using the + Material segmented button or Cupertino segmented control. The strip scrolls + rather than squeezing labels at 320/2x. + - Input/Output use the run detail's existing field rendering and the exact + empty sentences `No input recorded.` / `No output recorded.`. + - Artifacts lists this visit's stage files (`visitArtifacts`, so a shared + `public/` file stays with the visit that first recorded it) and opens the + existing artifact gallery page for that visit. The page is given the whole + run and the focused visit, so it lists exactly the rows the pane lists and + keeps the run's own visit group. An empty list uses the landed per-visit + capture wording (`Artifacts · capture pending` for a running visit, + `Artifacts · capture unavailable` when the field is absent, `Artifacts · + not recorded for this visit` only for an explicitly empty capture) and shows + the partial-capture notes when the scan was bounded. + - Session shows the recorded session identity and, when the visit exported + one, `Open `. The recorded URL is resolved by the landed + `resolveArtifactUrl` and opened through `openArtifactExternally`; a refusal + or an unresolved relative URL is reported, never silently swallowed. The + state comes from the recorded export evidence (including a repair), falls + back to the legacy `session.html` system file web audit uses, and otherwise + reports the recorded state in the web client's words: skipped, stopped, + session being created, failed with its diagnostic, or the runtime error for + a model visit with no identity. An export whose evidence is partial or + failed stays openable and says so. + - Definition embeds the landed `StageDefinitionView` for the run's own pinned + graph and stage, so the authored prompt/output/outcomes/raw source show + exactly as landed. When the reply does not declare the stage, the landed + exact sentence `This stage is not declared in this pipeline version. No + definition has been reconstructed.` is shown instead. +- **Back** — `Back to timeline` (native back arrow / Cupertino chevron) closes + the pane and restores the rows. The run header, Changes, Artifacts, Rename, + Cancel, Retry and Decide actions are untouched and stay outside the tabs. +- A different run clears the selection; an unvisited Graph node still opens + nothing. + +## Files + +Added: + +- `app/lib/features/runs/ui/run_detail_visit.dart` — pane layout, facts, verdict + and diagnostic, Back. +- `app/lib/features/runs/ui/run_detail_visit_facts.dart` — pure step lookup, + duration/provider/model/verdict/definition facts, exact wording. +- `app/lib/features/runs/ui/run_detail_visit_session_state.dart` — recorded + session/export state: identity, repair/legacy export resolution and the + state-specific wording. +- `app/lib/features/runs/ui/run_detail_visit_sections.dart` — section enum, + adaptive strip, section body selection. +- `app/lib/features/runs/ui/run_detail_visit_artifacts.dart` — visit artifact + rows opening the existing gallery entry. +- `app/lib/features/runs/ui/run_detail_visit_session.dart` — session pointer and + safe-link export open. +- `app/lib/features/runs/ui/run_detail_visit_definition.dart` — pinned + stage-definition pane or exact missing wording. +- `app/test/features/runs/ui/run_detail_visit_support.dart`, + `run_detail_visit_test.dart`, `run_detail_visit_sections_test.dart`, + `run_detail_visit_session_test.dart`. +- `app/tool/run_detail_visit_probe.dart`, `run_detail_visit_probe.mjs`. +- `app/notes/R4-visit.md`. + +Changed (minimal wiring): + +- `run_detail_timeline.dart` — rows become selectable and report their index. +- `run_detail_tabs.dart` — selected visit index opens the pane; Back closes it; + Graph selection uses the latest recorded index. +- `run_detail_view.dart`, `run_detail_material.dart`, + `run_detail_cupertino.dart` — pass the configured endpoint for the session + safe link; the endpoint cast now comes from `configuredGatewayEndpoint` in + `core/transport/pipelines_client.dart`. +- `run_detail_tab_strip.dart` — `ScrollWhenOverflowing` is public and shared by + both tab strips, so the pointer-drag and minimum-width rules live once. +- `lib/features/artifacts/domain/artifact_groups.dart` — + `visitArtifactGroup` returns the gallery group of exactly one visit from the + whole run. +- `lib/features/artifacts/ui/artifact_gallery_page.dart`, + `artifact_gallery_action.dart` — an optional focused visit limits the page to + that visit's attributed group and summary; the run-level gallery is unchanged. +- `run_detail_graph_tab_test.dart` — the stage-click expectation now asserts + the opened pane and its facts (previous test asserted the row highlight). +- `run_detail_graph_support.dart` — optional light/dark theme for 2x checks and + an empty-tree reset so one test can pump a second run. +- `run_detail_graph_probe.mjs` — the stage-click check now expects the pane and + its sections; re-run once to keep the existing probe green. + +The artifact changes are the two focused-visit additions above: the run-level +gallery, its viewer and its domain grouping are otherwise untouched. No +`graph/`, `pipelines/`, `chat/`, `application/`, `schedules/`, `templates/` or +backend file was edited. + +## Checks run + +From `app/` with Flutter 3.44.6: + +- `flutter analyze` — no issues. +- `flutter test` — **1014 tests passed** (full suite). +- `flutter build web` — built `build/web`. +- Probe builds: + `flutter build web --target tool/run_detail_visit_probe.dart --output build/probe-run-detail-visit` + and the existing `run_detail_graph_probe.dart` build both succeeded. +- `node tool/run_detail_visit_probe.mjs` — passed for Material and Cupertino at + 1280×900/1x dark and 320×568/2x dark: 9/9 checks and 8 captures each. +- `node tool/run_detail_graph_probe.mjs` — Material 1280×900/1x dark re-run + passed with the pane expectation. + +## Browser evidence + +Probe drives the real `RunDetailView` over a server-shaped fake gateway (plan +visit with provider/model, both timestamps, verdict, diagnostic, input/output, +artifacts, session id + `session.html` export; a sparse build visit with no +timestamps/provider/session). Checks: Graph stage click opens `plan · visit 1` +with all five sections; Definition shows the pinned "Draft the plan." source; +Session shows `sess-1` and `Open session.html`; Artifacts lists `plan.csv`; the +row opens a gallery whose summary says `Artifacts · 1 recorded`, whose only +group is `plan · visit 1` and whose only row is `plan.csv` (the `session.html` +evidence file is absent); Back restores the rows; the sparse visit has no +Duration or Provider/model and its Artifacts tab says +`Artifacts · capture unavailable`. + +Under `/Users/alan/.local/share/pipelines/data/artifacts/95/public/r4-visit-fix/`: + +| Host | Viewport | Captures | +| --- | --- | --- | +| Material | 1280×900, dark, 1x | `run-detail-visit-material-dark-1x-1280x900-{visit-pane,definition,session,artifacts,timeline-rows,sparse-visit,sparse-artifacts,visit-gallery}.png` | +| Material | 320×568, dark, 2x | `run-detail-visit-material-dark-2x-320x568-{visit-pane,definition,session,artifacts,timeline-rows,sparse-visit,sparse-artifacts,visit-gallery}.png` | +| Cupertino | 1280×900, dark, 1x | `run-detail-visit-cupertino-dark-1x-1280x900-{visit-pane,definition,session,artifacts,timeline-rows,sparse-visit,sparse-artifacts,visit-gallery}.png` | +| Cupertino | 320×568, dark, 2x | `run-detail-visit-cupertino-dark-2x-320x568-{visit-pane,definition,session,artifacts,timeline-rows,sparse-visit,sparse-artifacts,visit-gallery}.png` | + +Evidence JSON: `evidence-{material,cupertino}-{1x-1280x900,2x-320x568}.json`; +each records 9 checks, all `true`, and the 8 captures above (32 PNGs). + +At 320/2x the run detail keeps its own 240px minimum tab body, so the visit +facts area is a short scroll region; all facts remain reachable by scrolling and +the section strip/body stay usable. No overflow or exception is reported. + +## Review fixes (visit 2) + +- Artifact empty states now use the landed per-visit capture wording instead of + one "nothing recorded" sentence; tests cover absent, explicitly empty and + running captures. +- The artifact row opens the gallery focused on the same visit with the whole + run as context, so a shared `public/` file is not re-attributed. Tests cover + two visits of one stage plus a repeated public file, asserting the pane and + the opened page both exclude it. +- Session resolution handles a repair and the legacy `session.html`, reports the + evidence status/diagnostic when the file is missing, and uses the web client's + state-specific sentences. Tests cover a legacy export, a running model visit + and a failed one. +- Advisory cleanups: shared `ScrollWhenOverflowing`, one timeline lookup for the + latest visit, one endpoint helper, corrected stale selection comments and the + added refusal test. + +## Known gaps + +- The pane title and timeline rows still use the global recorded `sequence` + (`plan · visit 5`), while the gallery group uses the per-stage visit number + (`plan · visit 2`). This predates this pane; aligning the rows and pane would + change the timeline titles and is recorded here rather than done. +- At 320/2x the existing 240px minimum tab body leaves the facts area a short + scroll region; all facts are reachable by scrolling and no overflow occurs. + +## Not done / unverified + +- No commit, push, merge or deployment (this stage forbids it; the input's + “commit the candidate” was not performed). +- Web only. Android/iOS builds, layout and device behavior were not run; the + source stays portable (Material/Cupertino only, no platform-only imports). +- No backend changes. The pane reads only fields the existing `get_run` reply + already carries; nothing new was requested from the server. + +## Manager completion after the Code deadline + +The run had succeeded at Code once, been rejected at Review, and its retry hit the +30-minute stage deadline. The retained tree is complete: 280 runs/artifacts tests +pass and analysis is clean. Merged directly. The only cross-feature edit is an +11-line `configuredGatewayEndpoint` helper in the transport so relative recorded +artifact/session urls resolve against the configured origin without repeating a +cast in the UI. diff --git a/app/test/features/artifacts/domain/artifact_groups_test.dart b/app/test/features/artifacts/domain/artifact_groups_test.dart index cf7173f6..a4f3a834 100644 --- a/app/test/features/artifacts/domain/artifact_groups_test.dart +++ b/app/test/features/artifacts/domain/artifact_groups_test.dart @@ -266,6 +266,39 @@ void main() { ]; expect(artifactGroups(steps).single.artifacts.length, 1); }); + + test('visitArtifactGroup matches the pane group of a later visit', () { + final steps = >[ + step( + stage: 'a', + sequence: 1, + visit: 1, + artifacts: >[ + artifact('public/shared.csv'), + artifact('a.csv'), + ], + ), + step( + stage: 'a', + sequence: 2, + visit: 2, + artifacts: >[ + artifact('public/shared.csv'), + artifact('b.csv'), + ], + ), + ]; + final group = visitArtifactGroup(steps, 1)!; + expect(group.stageKey, 'a'); + expect(group.visit, 2); + expect(group.artifacts.map((record) => record.name), ['b.csv']); + expect( + visitArtifacts(steps[1], steps).map((record) => record.name), + ['b.csv'], + ); + expect(visitArtifactGroup(steps, 2), isNull); + expect(visitArtifactGroup(steps, -1), isNull); + }); }); group('unavailable and empty captures', () { diff --git a/app/test/features/runs/ui/run_detail_graph_support.dart b/app/test/features/runs/ui/run_detail_graph_support.dart index 32b11949..494547ab 100644 --- a/app/test/features/runs/ui/run_detail_graph_support.dart +++ b/app/test/features/runs/ui/run_detail_graph_support.dart @@ -81,6 +81,7 @@ Future pumpRunDetail( JsonMap? run, Size size = const Size(900, 1000), double scale = 1, + Brightness brightness = Brightness.light, }) async { tester.view.physicalSize = size; tester.view.devicePixelRatio = 1; @@ -100,10 +101,20 @@ Future pumpRunDetail( ).copyWith(textScaler: TextScaler.linear(scale)), child: view, ); + // A caller that pumps a second run in one test must not inherit the previous + // detail's open tab or pane, so start from an empty tree. + await tester.pumpWidget(const SizedBox.shrink()); await tester.pumpWidget( platform == RunDetailTestPlatform.material - ? MaterialApp(home: Scaffold(body: page)) + ? MaterialApp( + theme: ThemeData( + brightness: brightness, + platform: TargetPlatform.android, + ), + home: Scaffold(body: page), + ) : CupertinoApp( + theme: CupertinoThemeData(brightness: brightness), home: CupertinoPageScaffold(child: SafeArea(child: page)), ), ); diff --git a/app/test/features/runs/ui/run_detail_graph_tab_test.dart b/app/test/features/runs/ui/run_detail_graph_tab_test.dart index 43d20f72..ac140906 100644 --- a/app/test/features/runs/ui/run_detail_graph_tab_test.dart +++ b/app/test/features/runs/ui/run_detail_graph_tab_test.dart @@ -4,7 +4,6 @@ import 'package:pipelines_app/features/graph/widgets/graph_stage_node.dart'; import 'package:pipelines_app/features/graph/widgets/run_graph_canvas.dart'; import 'package:pipelines_app/features/graph/widgets/run_graph_view.dart'; import 'package:pipelines_app/features/runs/ui/run_detail_tab.dart'; -import 'package:pipelines_app/features/runs/ui/run_detail_timeline.dart'; import 'run_detail_graph_support.dart'; @@ -41,32 +40,25 @@ void main() { expect(tester.takeException(), isNull); }); - testWidgets('${platform.name} stage click highlights its recorded visit', ( + testWidgets('${platform.name} stage click opens its recorded visit pane', ( tester, ) async { await pumpRunDetail(tester, platform); await openRunDetailTab(tester, RunDetailTab.graph); await tapGraphNode(tester, 'plan'); + await tester.pumpAndSettle(); // The Graph reports the stage and the detail moves to Timeline, where the - // exact recorded visit is selected. + // exact recorded visit is open. expect(find.byType(RunGraphView), findsNothing); expect( find.byKey(const Key('run-detail-tab-body-timeline')), findsOneWidget, ); - final selected = tester.widget( - find.byKey(const ValueKey('run-timeline-visit-1')), - ); - expect(selected.selected, isTrue); - expect( - tester - .widget( - find.byKey(const ValueKey('run-timeline-visit-2')), - ) - .selected, - isFalse, - ); + expect(find.byKey(const Key('run-visit-pane')), findsOneWidget); + expect(find.byKey(const Key('run-visit-title')), findsOneWidget); + expect(find.text('plan · visit 1'), findsOneWidget); + expect(find.textContaining('Status:'), findsOneWidget); expect(find.textContaining('audit · visit'), findsNothing); }); diff --git a/app/test/features/runs/ui/run_detail_visit_sections_test.dart b/app/test/features/runs/ui/run_detail_visit_sections_test.dart new file mode 100644 index 00000000..9c3abe0c --- /dev/null +++ b/app/test/features/runs/ui/run_detail_visit_sections_test.dart @@ -0,0 +1,187 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/artifacts/ui/artifact_gallery_page.dart'; +import 'package:pipelines_app/features/graph/widgets/stage_definition_view.dart'; +import 'package:pipelines_app/features/runs/ui/run_detail_visit_facts.dart'; +import 'package:pipelines_app/features/runs/ui/run_detail_visit_sections.dart'; +import 'package:pipelines_app/features/runs/ui/run_detail_visit_session_state.dart'; + +import 'run_detail_graph_support.dart'; +import 'run_detail_visit_support.dart'; + +void main() { + for (final platform in RunDetailTestPlatform.values) { + testWidgets('${platform.name} tabs show recorded values and exact empty ' + 'wording', (tester) async { + await openVisit(tester, platform); + + expect(find.textContaining('"prompt": "Ship it."'), findsOneWidget); + await openVisitTab(tester, RunVisitSection.output); + expect(find.textContaining('"result": "ok"'), findsOneWidget); + + await openVisitTab(tester, RunVisitSection.artifacts); + expect(find.text('plan.csv'), findsOneWidget); + await tester.tap(find.text('plan.csv')); + await tester.pumpAndSettle(); + expect(find.byType(ArtifactGalleryPage), findsOneWidget); + // The opened page lists exactly the pane's stage files: the session + // evidence file is not stage output and stays out of both. + expect(find.text('plan · visit 1'), findsOneWidget); + expect(find.text('plan.csv'), findsOneWidget); + expect(find.text('session.html'), findsNothing); + expect(find.text('Artifacts · 1 recorded'), findsOneWidget); + await tester.pageBack(); + await tester.pumpAndSettle(); + + await openVisitTab(tester, RunVisitSection.session); + expect(find.text('Session'), findsWidgets); + expect(find.text('sess-1'), findsOneWidget); + expect(find.text('Open session.html'), findsOneWidget); + + await openVisitTab(tester, RunVisitSection.definition); + expect(find.byType(StageDefinitionView), findsOneWidget); + expect(find.text('Draft the plan.'), findsOneWidget); + }); + + testWidgets('${platform.name} artifacts tab reports the capture state', ( + tester, + ) async { + final absent = visitRunFixture(); + firstVisitStep(absent).remove('artifacts'); + await openVisit(tester, platform, run: absent); + await openVisitTab(tester, RunVisitSection.artifacts); + expect(find.text('Artifacts · capture unavailable'), findsOneWidget); + + final empty = visitRunFixture(); + firstVisitStep(empty)['artifacts'] = []; + await openVisit(tester, platform, run: empty); + await openVisitTab(tester, RunVisitSection.artifacts); + expect( + find.text('Artifacts · not recorded for this visit'), + findsOneWidget, + ); + + final running = visitRunFixture(); + final runningStep = firstVisitStep(running); + runningStep['status'] = 'running'; + runningStep['artifacts'] = []; + await openVisit(tester, platform, run: running); + await openVisitTab(tester, RunVisitSection.artifacts); + expect(find.text('Artifacts · capture pending'), findsOneWidget); + }); + + testWidgets('${platform.name} empty sections use the exact wording', ( + tester, + ) async { + final run = visitRunFixture(); + final step = firstVisitStep(run); + step.remove('input'); + step.remove('output'); + step['artifacts'] = []; + step.remove('session_id'); + step.remove('session_export'); + await openVisit(tester, platform, run: run); + + expect(find.text(visitEmptyInput), findsOneWidget); + await openVisitTab(tester, RunVisitSection.output); + expect(find.text(visitEmptyOutput), findsOneWidget); + await openVisitTab(tester, RunVisitSection.artifacts); + expect( + find.text('Artifacts · not recorded for this visit'), + findsOneWidget, + ); + await openVisitTab(tester, RunVisitSection.session); + // A completed model visit with no identity is a runtime error, not a + // generic "no session" claim. + expect(find.text(visitSessionNoIdentity), findsOneWidget); + }); + + testWidgets('${platform.name} later visit pane and opened gallery agree on ' + 'attributed files', (tester) async { + final run = visitRunFixture(); + final steps = run['steps'] as List; + firstVisitStep(run)['artifacts'] = [ + { + 'name': 'public/shared.csv', + 'url': 'https://example.test/artifacts/1/public/shared.csv', + 'content_type': 'text/csv', + 'size_bytes': 10, + }, + { + 'name': 'plan.csv', + 'url': 'https://example.test/artifacts/1/plan.csv', + 'content_type': 'text/csv', + 'size_bytes': 42, + }, + ]; + steps.add({ + 'stage': 'plan', + 'sequence': 2, + 'status': 'completed', + 'outcome': 'success', + 'artifacts': [ + { + 'name': 'public/shared.csv', + 'url': 'https://example.test/artifacts/2/public/shared.csv', + 'content_type': 'text/csv', + 'size_bytes': 10, + }, + { + 'name': 'plan-2.csv', + 'url': 'https://example.test/artifacts/2/plan-2.csv', + 'content_type': 'text/csv', + 'size_bytes': 7, + }, + ], + }); + + await openVisit(tester, platform, run: run, sequence: 2); + expect(find.text('plan · visit 2'), findsOneWidget); + await openVisitTab(tester, RunVisitSection.artifacts); + expect(find.text('plan-2.csv'), findsOneWidget); + expect(find.text('public/shared.csv'), findsNothing); + + await tester.tap(find.text('plan-2.csv')); + await tester.pumpAndSettle(); + expect(find.byType(ArtifactGalleryPage), findsOneWidget); + expect(find.text('plan · visit 2'), findsOneWidget); + expect(find.text('plan-2.csv'), findsOneWidget); + expect(find.text('public/shared.csv'), findsNothing); + expect(find.text('Artifacts · 1 recorded'), findsOneWidget); + }); + + testWidgets('${platform.name} missing definition uses exact wording', ( + tester, + ) async { + await openVisit( + tester, + platform, + run: visitRunFixture(declareStage: false), + ); + await openVisitTab(tester, RunVisitSection.definition); + + expect(find.byType(StageDefinitionView), findsNothing); + expect(find.text(unknownStageDefinition), findsOneWidget); + expect(find.text('Draft the plan.'), findsNothing); + }); + + testWidgets('${platform.name} visit sections at 320 with 2x dark text', ( + tester, + ) async { + await openVisit( + tester, + platform, + size: const Size(320, 568), + scale: 2, + brightness: Brightness.dark, + ); + + expect(find.byKey(const Key('run-visit-pane')), findsOneWidget); + expect(tester.takeException(), isNull); + for (final section in RunVisitSection.values) { + await openVisitTab(tester, section); + expect(tester.takeException(), isNull, reason: section.label); + } + }); + } +} diff --git a/app/test/features/runs/ui/run_detail_visit_session_test.dart b/app/test/features/runs/ui/run_detail_visit_session_test.dart new file mode 100644 index 00000000..c5ba50fc --- /dev/null +++ b/app/test/features/runs/ui/run_detail_visit_session_test.dart @@ -0,0 +1,147 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/runs/ui/run_detail_visit_sections.dart'; +import 'package:pipelines_app/features/runs/ui/run_detail_visit_session.dart'; +import 'package:pipelines_app/features/runs/ui/run_detail_visit_session_state.dart'; + +import 'run_detail_graph_support.dart'; +import 'run_detail_visit_support.dart'; + +void main() { + for (final platform in RunDetailTestPlatform.values) { + testWidgets('${platform.name} legacy session.html stays openable', ( + tester, + ) async { + final run = visitRunFixture(); + firstVisitStep(run).remove('session_export'); + await openVisit(tester, platform, run: run); + await openVisitTab(tester, RunVisitSection.session); + + expect(find.text('sess-1'), findsOneWidget); + expect(find.text('Open session.html'), findsOneWidget); + expect( + find.textContaining('not available in the artifact inventory'), + findsNothing, + ); + }); + + testWidgets('${platform.name} running and failed model visits report ' + 'their session state', (tester) async { + final running = visitRunFixture(); + final runningStep = firstVisitStep(running); + runningStep['status'] = 'running'; + runningStep.remove('session_id'); + runningStep.remove('session_export'); + runningStep.remove('artifacts'); + await openVisit(tester, platform, run: running); + await openVisitTab(tester, RunVisitSection.session); + expect(find.text(visitSessionStarting), findsOneWidget); + + final failed = visitRunFixture(); + final failedStep = firstVisitStep(failed); + failedStep['status'] = 'failed'; + failedStep.remove('session_id'); + failedStep.remove('session_export'); + failedStep.remove('artifacts'); + failedStep['diagnostic'] = 'Provider refused.'; + await openVisit(tester, platform, run: failed); + await openVisitTab(tester, RunVisitSection.session); + expect( + find.text('$visitSessionFailed Provider refused.'), + findsOneWidget, + ); + }); + } + + testWidgets('a recorded session without any export file reports its state', ( + tester, + ) async { + final step = firstVisitStep(visitRunFixture()); + step.remove('session_export'); + step['artifacts'] = [ + { + 'name': 'plan.csv', + 'url': 'https://example.test/artifacts/plan.csv', + 'content_type': 'text/csv', + 'size_bytes': 42, + }, + ]; + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: RunVisitSession(step: step, configuredEndpoint: ''), + ), + ), + ); + + expect( + find.text('Session sess-1 is recorded. Its export is not yet available.'), + findsOneWidget, + ); + expect(find.textContaining('Open '), findsNothing); + + step['session_export'] = { + 'html': 'session.html', + 'status': 'failed', + 'diagnostic': 'Repair failed.', + }; + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: RunVisitSession(step: step, configuredEndpoint: ''), + ), + ), + ); + expect( + find.text( + 'Session sess-1 is recorded. Its export is failed. Repair failed.', + ), + findsOneWidget, + ); + }); + + testWidgets('session entry opens the resolved export externally', ( + tester, + ) async { + Uri? opened; + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: RunVisitSession( + step: firstVisitStep(visitRunFixture()), + configuredEndpoint: 'ws://example.test/connect', + openExternal: (uri) async { + opened = uri; + return true; + }, + ), + ), + ), + ); + + await tester.tap(find.text('Open session.html')); + await tester.pumpAndSettle(); + + expect(opened, Uri.parse('https://example.test/artifacts/session.html')); + expect(find.text('Link opened externally.'), findsOneWidget); + }); + + testWidgets('session open refusal is reported', (tester) async { + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: RunVisitSession( + step: firstVisitStep(visitRunFixture()), + configuredEndpoint: 'ws://example.test/connect', + openExternal: (uri) async => false, + ), + ), + ), + ); + + await tester.tap(find.text('Open session.html')); + await tester.pumpAndSettle(); + + expect(find.text('Could not open the link.'), findsOneWidget); + }); +} diff --git a/app/test/features/runs/ui/run_detail_visit_support.dart b/app/test/features/runs/ui/run_detail_visit_support.dart new file mode 100644 index 00000000..04759aaa --- /dev/null +++ b/app/test/features/runs/ui/run_detail_visit_support.dart @@ -0,0 +1,116 @@ +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/ui/run_detail_tab.dart'; +import 'package:pipelines_app/features/runs/ui/run_detail_visit_sections.dart'; + +import 'run_detail_graph_support.dart'; + +/// plan -> build, with one rich recorded plan visit. +JsonMap visitRunFixture({ + bool bothTimestamps = true, + bool providerModel = true, + bool declareStage = true, +}) => { + 'id': 77, + 'title': 'Visit run', + 'name': 'release', + 'pipeline_id': 7, + 'version': 3, + 'status': 'succeeded', + 'graph': { + 'stages': [ + if (declareStage) + { + 'key': 'plan', + 'type': 'model', + 'prompt': 'Draft the plan.', + 'edges': {'success': 'build', 'error': '#'}, + }, + { + 'key': 'build', + 'type': 'model', + 'edges': {'success': '#success'}, + }, + ], + }, + 'steps': [ + { + 'stage': 'plan', + 'sequence': 1, + 'status': 'completed', + 'outcome': 'success', + 'target': 'build', + if (providerModel) 'provider': 'anthropic', + if (providerModel) 'model': 'claude-x', + if (bothTimestamps) 'started_at': '2026-10-22T00:00:00Z', + if (bothTimestamps) 'finished_at': '2026-10-22T00:02:05Z', + 'diagnostic': 'Plan checked.', + 'verdict': { + 'option': 'approve', + 'reason': 'Looks good.', + }, + 'input': {'prompt': 'Ship it.'}, + 'output': {'result': 'ok'}, + 'session_id': 'sess-1', + 'session_export': { + 'html': 'session.html', + 'status': 'complete', + 'messages': 3, + 'html_bytes': 1234, + }, + 'artifacts': [ + { + 'name': 'plan.csv', + 'url': 'https://example.test/artifacts/plan.csv', + 'content_type': 'text/csv', + 'size_bytes': 42, + }, + { + 'name': 'session.html', + 'url': 'https://example.test/artifacts/session.html', + 'content_type': 'text/html', + 'size_bytes': 100, + }, + ], + }, + ], +}; + +/// The first recorded step of a detail fixture, for tests that change one +/// visit's recorded fields. +JsonMap firstVisitStep(JsonMap run) => + (run['steps'] as List).first as Map; + +Future openVisit( + WidgetTester tester, + RunDetailTestPlatform platform, { + JsonMap? run, + int sequence = 1, + Size size = const Size(900, 1000), + double scale = 1, + Brightness brightness = Brightness.light, +}) async { + await pumpRunDetail( + tester, + platform, + run: run ?? visitRunFixture(), + size: size, + scale: scale, + brightness: brightness, + ); + await openRunDetailTab(tester, RunDetailTab.timeline); + final row = find.byKey(ValueKey('run-timeline-visit-$sequence')); + await tester.ensureVisible(row); + await tester.pumpAndSettle(); + await tester.tap(row); + await tester.pumpAndSettle(); +} + +Future openVisitTab(WidgetTester tester, RunVisitSection section) async { + final tab = find.byKey(ValueKey('run-visit-tab-${section.name}')); + await tester.ensureVisible(tab); + await tester.pumpAndSettle(); + await tester.tap(tab); + await tester.pumpAndSettle(); +} diff --git a/app/test/features/runs/ui/run_detail_visit_test.dart b/app/test/features/runs/ui/run_detail_visit_test.dart new file mode 100644 index 00000000..c91dc1f8 --- /dev/null +++ b/app/test/features/runs/ui/run_detail_visit_test.dart @@ -0,0 +1,106 @@ +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/ui/run_detail_timeline.dart'; +import 'package:pipelines_app/features/runs/ui/run_detail_visit_session.dart'; +import 'package:pipelines_app/features/runs/ui/run_detail_visit_session_state.dart'; + +import 'run_detail_graph_support.dart'; +import 'run_detail_visit_support.dart'; + +void main() { + for (final platform in RunDetailTestPlatform.values) { + testWidgets('${platform.name} visit shows only its recorded facts', ( + tester, + ) async { + await openVisit(tester, platform); + + expect(find.byKey(const Key('run-visit-pane')), findsOneWidget); + expect(find.text('plan · visit 1'), findsOneWidget); + for (final value in [ + 'Status: completed', + 'Outcome: success', + 'Duration: 2m 5s', + 'Provider/model: anthropic / claude-x', + 'Target: build', + ]) { + expect(find.textContaining(value), findsOneWidget, reason: value); + } + for (final value in ['approve', 'Looks good.', 'Plan checked.']) { + expect(find.text(value), findsOneWidget, reason: value); + } + expect(find.text('Verdict'), findsOneWidget); + expect(find.text('Diagnostic'), findsOneWidget); + }); + + testWidgets('${platform.name} duration hides without both timestamps', ( + tester, + ) async { + await openVisit( + tester, + platform, + run: visitRunFixture(bothTimestamps: false), + ); + + expect(find.textContaining('Duration'), findsNothing); + expect(find.textContaining('0s'), findsNothing); + expect(find.textContaining('Status: completed'), findsOneWidget); + }); + + testWidgets('${platform.name} absent provider/model is not invented', ( + tester, + ) async { + await openVisit( + tester, + platform, + run: visitRunFixture(providerModel: false), + ); + + expect(find.textContaining('Provider/model'), findsNothing); + expect(find.textContaining('anthropic / claude-x'), findsNothing); + }); + + testWidgets('${platform.name} Back closes the visit pane', (tester) async { + await openVisit(tester, platform); + await tester.tap(find.byKey(const Key('run-visit-back'))); + await tester.pumpAndSettle(); + + expect(find.byKey(const Key('run-visit-pane')), findsNothing); + expect(find.byType(RunTimelineList), findsOneWidget); + expect(find.text('plan · visit 1'), findsOneWidget); + }); + + testWidgets('${platform.name} visit pane at 320 with 2x dark text', ( + tester, + ) async { + await openVisit( + tester, + platform, + size: const Size(320, 568), + scale: 2, + brightness: Brightness.dark, + ); + + expect(find.byKey(const Key('run-visit-pane')), findsOneWidget); + expect(tester.takeException(), isNull); + }); + } + + testWidgets('session export with no configured endpoint states the hint', ( + tester, + ) async { + final step = (visitRunFixture()['steps'] as List).first as JsonMap; + final artifacts = step['artifacts'] as List; + (artifacts[1] as JsonMap)['url'] = '/artifacts/session.html'; + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: RunVisitSession(step: step, configuredEndpoint: ''), + ), + ), + ); + + expect(find.text('Open session.html'), findsNothing); + expect(find.text(visitSessionEndpointMissing), findsOneWidget); + }); +} diff --git a/app/tool/run_detail_graph_probe.mjs b/app/tool/run_detail_graph_probe.mjs index 3d8c65ab..cb6bfe20 100644 --- a/app/tool/run_detail_graph_probe.mjs +++ b/app/tool/run_detail_graph_probe.mjs @@ -236,21 +236,27 @@ try { } await clickPrefix('plan'); - await waitForText('plan · visit 1', 'timeline after stage click'); + await waitForText('plan · visit 1', 'timeline visit pane after stage click'); + await waitForText('Status: completed', 'recorded visit facts'); await waitForText('Timeline', 'timeline tab'); const timeline = await semantics(); - const rowCandidates = timeline + const titleCandidates = timeline .filter((entry) => entry.visible && entry.label.startsWith('plan · visit 1')) .sort((a, b) => a.width * a.height - b.width * b.height); - const row = rowCandidates[0]; - if (!row) throw new Error(`Selected timeline row missing: ${JSON.stringify(timeline.map((entry) => entry.label))}`); - if (row.selected !== 'true') { - throw new Error(`Timeline row is not selected: ${JSON.stringify(rowCandidates)}`); + if (!titleCandidates.length) { + throw new Error(`Opened visit pane missing: ${JSON.stringify(timeline.map((entry) => entry.label))}`); + } + const paneLabels = timeline.map((entry) => entry.label); + for (const section of ['Input', 'Output', 'Artifacts', 'Session', 'Definition']) { + if (!paneLabels.includes(section)) { + throw new Error(`Visit section ${section} is missing: ${JSON.stringify(paneLabels)}`); + } } if ((await bodyText()).includes('audit · visit')) { throw new Error('A visit was invented for the unvisited stage'); } - check('a stage click selects the recorded visit in Timeline', row.selected); + check('a stage click opens the recorded visit pane', true); + check('the visit pane offers its recorded sections', true); // The programmatic switch must reveal its own tab, not leave an offscreen // selection behind a strip still showing Summary/Graph. const timelineTab = await findVisible((entry) => entry.label === 'Timeline' && entry.tappable); @@ -259,7 +265,7 @@ try { throw new Error(`Selected Timeline tab is clipped: ${JSON.stringify({ timelineTab, width })}`); } check('the selected Timeline tab is revealed in the strip', `${Math.round(timelineTab.x)}..${Math.round(timelineTab.x + timelineTab.width)}`); - evidence.selectedRow = row; + evidence.openedPane = titleCandidates[0]; evidence.captures.push(await capture('selected-visit')); await navigate( diff --git a/app/tool/run_detail_visit_probe.dart b/app/tool/run_detail_visit_probe.dart new file mode 100644 index 00000000..53750471 --- /dev/null +++ b/app/tool/run_detail_visit_probe.dart @@ -0,0 +1,189 @@ +// Standalone fixture entry for real-browser recorded-visit pane evidence. +// +// Build and probe (from app/): +// flutter build web --target tool/run_detail_visit_probe.dart \ +// --output build/probe-run-detail-visit +// PROBE_VARIANT=material OPENCODE_ARTIFACT_DIR=DIR \ +// node tool/run_detail_visit_probe.mjs +// +// Server-shaped fixtures only: a fake gateway answers the same get_run envelope +// the app consumes. No server or operator run is touched. +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/runs/data/runs_repository.dart'; +import 'package:pipelines_app/features/runs/ui/run_detail_view.dart'; +import 'package:pipelines_app/features/runs/ui/runs_controller.dart'; + +class _FakeGateway implements ApiGateway { + _FakeGateway(this.detail); + + final JsonMap detail; + + @override + Stream get frames => const Stream.empty(); + + @override + Future call(String type, [JsonMap fields = const {}]) { + if (type != 'get_run') throw UnsupportedError(type); + return Future.value({'run_detail': detail}); + } +} + +/// plan -> build, with a rich first visit and a sparse second visit. +JsonMap _graph() => { + 'name': 'Release verification', + 'stages': [ + { + 'key': 'plan', + 'type': 'model', + 'prompt': 'Draft the plan.', + 'output': 'A plan.', + 'edges': {'success': 'build', 'error': '#'}, + }, + { + 'key': 'build', + 'type': 'model', + 'prompt': 'Build the candidate.', + 'edges': {'success': '#success', 'error': '#'}, + }, + ], +}; + +JsonMap _run() => { + 'id': 512, + 'title': 'Release verification', + 'name': 'release', + 'pipeline_id': 7, + 'version': 3, + 'status': 'succeeded', + 'executing': false, + 'input': {'prompt': 'Verify the candidate release.'}, + 'output': {'result': 'verified'}, + 'graph': _graph(), + 'steps': [ + { + 'stage': 'plan', + 'sequence': 1, + 'status': 'completed', + 'outcome': 'success', + 'target': 'build', + 'provider': 'anthropic', + 'model': 'claude-x', + 'started_at': '2026-10-22T00:00:00Z', + 'finished_at': '2026-10-22T00:02:05Z', + 'diagnostic': 'Plan checked.', + 'verdict': { + 'option': 'approve', + 'reason': 'Looks good.', + }, + 'input': {'markdown': 'Draft the plan.\n'}, + 'output': {'result': 'ok'}, + 'session_id': 'sess-1', + 'session_export': { + 'html': 'session.html', + 'status': 'complete', + 'messages': 3, + 'html_bytes': 1234, + }, + 'artifacts': [ + { + 'name': 'plan.csv', + 'url': 'https://example.test/artifacts/plan.csv', + 'content_type': 'text/csv', + 'size_bytes': 42, + }, + { + 'name': 'session.html', + 'url': 'https://example.test/artifacts/session.html', + 'content_type': 'text/html', + 'size_bytes': 100, + }, + ], + }, + { + 'stage': 'build', + 'sequence': 2, + 'status': 'completed', + 'outcome': 'success', + 'target': '#success', + 'diagnostic': 'Built.', + }, + ], +}; + +void main() { + final params = Uri.base.queryParameters; + final cupertino = params['platform'] == 'cupertino'; + final dark = params['theme'] == 'dark'; + final scale = double.tryParse(params['scale'] ?? '') ?? 1; + runApp( + _ProbeBody(cupertino: cupertino, dark: dark, scale: scale, run: _run()), + ); +} + +class _ProbeBody extends StatefulWidget { + const _ProbeBody({ + required this.cupertino, + required this.dark, + required this.scale, + required this.run, + }); + + final bool cupertino; + final bool dark; + final double scale; + final JsonMap run; + + @override + State<_ProbeBody> createState() => _ProbeBodyState(); +} + +class _ProbeBodyState extends State<_ProbeBody> { + late final _FakeGateway _gateway = _FakeGateway(widget.run); + late final RunsController _controller = RunsController( + RunsRepository(_gateway), + ); + + @override + void initState() { + super.initState(); + _controller.select(512); + } + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final detail = RunDetailView( + controller: _controller, + gateway: _gateway, + onBack: () {}, + ); + final theme = widget.dark ? Brightness.dark : Brightness.light; + Widget scaled(BuildContext context, Widget? app) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(widget.scale)), + child: app!, + ); + if (widget.cupertino) { + return CupertinoApp( + title: 'Visit pane fixture', + theme: CupertinoThemeData(brightness: theme), + builder: scaled, + home: CupertinoPageScaffold(child: SafeArea(child: detail)), + ); + } + return MaterialApp( + title: 'Visit pane fixture', + theme: ThemeData(brightness: theme, platform: TargetPlatform.android), + builder: scaled, + home: Scaffold(body: SafeArea(child: detail)), + ); + } +} diff --git a/app/tool/run_detail_visit_probe.mjs b/app/tool/run_detail_visit_probe.mjs new file mode 100644 index 00000000..5e540d81 --- /dev/null +++ b/app/tool/run_detail_visit_probe.mjs @@ -0,0 +1,290 @@ +// Real-browser acceptance for the run detail's recorded-visit pane. +// +// Serves the probe build (`flutter build web -t tool/run_detail_visit_probe.dart`) +// on an OS-assigned loopback port and drives the actual RunDetailView over a +// server-shaped fixture. It checks that a Graph stage click opens the recorded +// visit in Timeline with its facts and native tabs, that the tabs show the +// recorded Input, Artifacts, Session and Definition, that the visit's artifact +// row opens a gallery listing exactly that visit's attributed files, that Back +// returns to the rows, that a sparse visit does not invent Duration or +// provider/model, and that a visit with no artifact field says the capture is +// unavailable rather than empty. +// +// PROBE_VARIANT=material|cupertino PROBE_SCHEME=dark|light PROBE_SCALE=1|2 \ +// PROBE_WIDTH=1280 PROBE_HEIGHT=900 PROBE_WEB_ROOT= \ +// OPENCODE_ARTIFACT_DIR= node tool/run_detail_visit_probe.mjs +import { createServer } from 'node:http'; +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'; +import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; + +const root = resolve( + process.env.PROBE_WEB_ROOT ?? + join(process.cwd(), 'build/probe-run-detail-visit'), +); +const variant = process.env.PROBE_VARIANT ?? 'material'; +const scheme = process.env.PROBE_SCHEME ?? 'dark'; +const scale = process.env.PROBE_SCALE ?? '1'; +const width = Number(process.env.PROBE_WIDTH ?? 1280); +const height = Number(process.env.PROBE_HEIGHT ?? 900); +const chromePath = process.env.CHROME_PATH ?? + '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'; +const artifactDir = process.env.OPENCODE_ARTIFACT_DIR; +if (!artifactDir) throw new Error('Set OPENCODE_ARTIFACT_DIR for the probe captures'); +await mkdir(artifactDir, { recursive: true }); +const prefix = `run-detail-visit-${variant}-${scheme}-${scale}x-${width}x${height}`; +const mime = { + '.html': 'text/html', + '.js': 'text/javascript', + '.json': 'application/json', + '.wasm': 'application/wasm', + '.png': 'image/png', + '.ico': 'image/x-icon', + '.otf': 'font/otf', + '.ttf': 'font/ttf', +}; +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(), 'run-detail-visit-chrome-')); +const chrome = spawn(chromePath, [ + '--headless=new', '--no-first-run', '--no-default-browser-check', '--disable-gpu', + '--remote-debugging-port=0', `--user-data-dir=${profile}`, 'about:blank', +], { stdio: ['ignore', 'ignore', 'pipe'] }); +let stderr = ''; +chrome.stderr.on('data', (data) => { stderr += data; }); +const waitFor = async (fn) => { + for (let i = 0; i < 140; i++) { + const value = await fn(); + if (value) return value; + await delay(100); + } + throw new Error('Timed out waiting for Chrome DevTools'); +}; +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 message = JSON.parse(event.data); + if (message.method === 'Runtime.exceptionThrown') { + console.error('PAGE EXCEPTION', JSON.stringify(message.params?.exceptionDetails?.exception?.description)); + } + if (message.id && pending.has(message.id)) { + pending.get(message.id)(message); + pending.delete(message.id); + } + }); + const send = (method, params = {}, sessionId) => new Promise((resolveCall) => { + const callId = ++id; + pending.set(callId, resolveCall); + ws.send(JSON.stringify({ id: callId, method, params, ...(sessionId ? { sessionId } : {}) })); + }); + const created = await send('Target.createTarget', { url: 'about:blank' }); + 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); + await send('Emulation.setEmulatedMedia', { + features: [{ name: 'prefers-color-scheme', value: scheme }], + }, session); + await send('Emulation.setDeviceMetricsOverride', { + width, height, deviceScaleFactor: 1, mobile: width < 600, + }, 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 semantics = () => evaluate(`[...document.querySelectorAll('flt-semantics')].map(x => { + const r = x.getBoundingClientRect(); + return { + label: (x.getAttribute('aria-label') || (x.innerText || '')).trim(), + selected: x.getAttribute('aria-selected') || x.getAttribute('aria-current'), + tappable: x.hasAttribute('flt-tappable'), + x: r.x, y: r.y, width: r.width, height: r.height, + visible: r.width > 0 && r.height > 0 && r.bottom > 0 && r.top < innerHeight, + }; + })`); + const labels = async () => (await semantics()).map((item) => item.label).filter(Boolean); + const bodyText = async () => [await evaluate('document.body.innerText'), ...(await labels())].join('\n'); + const waitForText = async (needle, context) => { + for (let attempt = 0; attempt < 60; attempt++) { + if ((await bodyText()).includes(needle)) return; + await delay(250); + } + throw new Error(`${context}: missing ${JSON.stringify(needle)}\n${await bodyText()}`); + }; + const clickItem = async (item) => { + const x = item.x + item.width / 2; + const y = item.y + item.height / 2; + await send('Input.dispatchMouseEvent', { + type: 'mousePressed', x, y, button: 'left', clickCount: 1, + }, session); + await send('Input.dispatchMouseEvent', { + type: 'mouseReleased', x, y, button: 'left', clickCount: 1, + }, session); + await delay(1000); + }; + const findVisible = async (predicate) => { + const items = (await semantics()).filter((item) => item.visible && predicate(item)); + items.sort((a, b) => a.width * a.height - b.width * b.height); + return items[0] ?? null; + }; + const clickSemantics = async (wanted, { lowest = false, prefix: asPrefix = false } = {}) => { + const clicked = await evaluate(`(() => { + const wanted = ${JSON.stringify(wanted)}; + const lowest = ${lowest ? 'true' : 'false'}; + const asPrefix = ${asPrefix ? 'true' : 'false'}; + const text = (x) => (x.getAttribute('aria-label') || x.innerText || '').trim(); + const matches = [...document.querySelectorAll('flt-semantics')] + .filter((x) => x.hasAttribute('flt-tappable')) + .filter((x) => asPrefix ? text(x).startsWith(wanted) : text(x) === wanted); + if (!matches.length) return false; + matches.sort((a, b) => { + const ra = a.getBoundingClientRect(); + const rb = b.getBoundingClientRect(); + if (lowest) return rb.bottom - ra.bottom; + return ra.width * ra.height - rb.width * rb.height; + }); + matches[0].click(); + return true; + })()`); + if (!clicked) throw new Error(`Missing tappable ${JSON.stringify(wanted)}: ${JSON.stringify(await labels())}`); + await delay(1000); + }; + const clickLabel = (label, options) => clickSemantics(label, options); + const clickPrefix = (prefixText) => clickSemantics(prefixText, { prefix: true }); + const capture = async (name) => { + const data = (await send('Page.captureScreenshot', { + format: 'png', captureBeyondViewport: false, + }, session)).result.data; + const file = `${prefix}-${name}.png`; + await writeFile(join(artifactDir, file), Buffer.from(data, 'base64')); + return file; + }; + const evidence = { variant, scheme, scale, width, height, checks: [], captures: [] }; + const check = (text, value) => evidence.checks.push({ check: text, value }); + + const navigation = await send('Page.navigate', { + url: `http://127.0.0.1:${port}/?platform=${variant}&theme=${scheme === 'dark' ? 1 : 0}&scale=${scale}`, + }, session); + if (navigation.error || navigation.result?.errorText) throw new Error(JSON.stringify(navigation)); + await delay(3200); + await evaluate("document.querySelector('flt-semantics-placeholder')?.click()"); + await delay(900); + await waitForText('Release verification', 'fixture load'); + check('the real run detail opened over the recorded fixture', true); + + await clickLabel('Graph'); + await waitForText('Executed', 'graph legend'); + await clickPrefix('plan'); + await waitForText('plan · visit 1', 'visit pane after graph click'); + await waitForText('Provider/model', 'visit facts'); + await waitForText('anthropic / claude-x', 'visit facts'); + await waitForText('2m 5s', 'recorded duration'); + await waitForText('Plan checked.', 'recorded diagnostic'); + await waitForText('approve', 'recorded verdict'); + const paneLabels = await labels(); + for (const section of ['Input', 'Output', 'Artifacts', 'Session', 'Definition']) { + if (!paneLabels.includes(section)) { + throw new Error(`Visit section ${section} is missing: ${JSON.stringify(paneLabels)}`); + } + } + check('Graph stage click opens the recorded visit pane with its tabs', true); + evidence.captures.push(await capture('visit-pane')); + + await clickLabel('Definition', { lowest: true }); + await waitForText('Type model', 'authored definition'); + await waitForText('Prompt', 'authored definition prompt'); + await waitForText('Draft the plan.', 'pinned prompt'); + check('Definition shows the pinned authored source', true); + evidence.captures.push(await capture('definition')); + + await clickLabel('Session', { lowest: true }); + await waitForText('sess-1', 'recorded session pointer'); + await waitForText('Open session.html', 'session export link'); + check('Session shows the recorded pointer and export open', true); + evidence.captures.push(await capture('session')); + + await clickLabel('Artifacts', { lowest: true }); + await waitForText('plan.csv', 'visit artifact'); + check('Artifacts lists the visit recorded files', true); + evidence.captures.push(await capture('artifacts')); + + await clickLabel('Back to timeline'); + await waitForText('build · visit 2', 'timeline rows after back'); + if ((await bodyText()).includes('Plan checked.')) { + throw new Error('Back left the visit pane open'); + } + check('Back returns to the recorded rows', true); + evidence.captures.push(await capture('timeline-rows')); + + await clickPrefix('build · visit 2'); + await waitForText('build · visit 2', 'sparse visit pane'); + const sparse = await bodyText(); + for (const absent of ['Provider/model', 'Duration', '2m 5s', 'anthropic / claude-x']) { + if (sparse.includes(absent)) { + throw new Error(`A sparse visit invented ${JSON.stringify(absent)}\n${sparse}`); + } + } + check('a sparse visit does not invent duration or provider/model', true); + evidence.captures.push(await capture('sparse-visit')); + + await clickLabel('Artifacts', { lowest: true }); + await waitForText('Artifacts · capture unavailable', 'sparse capture state'); + check('a visit without an artifact field says capture unavailable', true); + evidence.captures.push(await capture('sparse-artifacts')); + + await clickLabel('Back to timeline'); + await waitForText('plan · visit 1', 'rows before the gallery check'); + await clickPrefix('plan · visit 1'); + await waitForText('Provider/model', 'plan visit for the gallery check'); + await clickLabel('Artifacts', { lowest: true }); + await waitForText('plan.csv', 'plan visit artifacts'); + await clickPrefix('plan.csv'); + await waitForText('Artifacts · 1 recorded', 'visit gallery summary'); + await waitForText('plan · visit 1', 'visit gallery group'); + const galleryText = await bodyText(); + if (galleryText.includes('session.html')) { + throw new Error(`The visit gallery listed the session evidence file\n${galleryText}`); + } + check('the artifact row opens exactly the visit attributed group', true); + evidence.captures.push(await capture('visit-gallery')); + + console.log(JSON.stringify(evidence, null, 2)); +} finally { + if (ws?.readyState === WebSocket.OPEN) { + ws.send(JSON.stringify({ id: 2147483647, method: 'Browser.close' })); + } + await Promise.race([once(chrome, 'exit'), delay(3000)]); + ws?.close(); + if (chrome.exitCode === null) chrome.kill('SIGTERM'); + chrome.stderr.destroy(); + chrome.unref(); + await new Promise((resolveClose) => { + server.close(resolveClose); + server.closeAllConnections(); + }); + await rm(profile, { recursive: true, force: true }); +} From 8cfc4443df9245743eb6134b8d1a91421db8a6ba Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 22 Oct 2026 02:06:39 +0100 Subject: [PATCH 13/13] docs(app): replace oversized lane slices with one-behavior contract --- app/WORK.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/app/WORK.md b/app/WORK.md index f999f40f..3cf917fd 100644 --- a/app/WORK.md +++ b/app/WORK.md @@ -514,3 +514,22 @@ Standing rules: keep the preview published with a rollback after each landing; never claim authenticated production mutations, OS sharing/notifications on mobile or device behaviour from web fixture evidence; keep mobile labelled unverified until the final build. +## Lane contract (corrected after 30-60 minute overruns) + +The oversized slice was mine, not the model's: prompts bundled 5-8 behaviours plus +a two-host browser probe and a note file. A probe means two web builds plus +Chrome/OCR, so Code alone exceeded the 30-minute stage budget and Review retries +pushed runs past an hour. + +Every new lane now gets ONE behaviour: +- At most 2 source files (+1) and 1 focused test file. +- No `flutter build`, no browser probe, no note file, no `flutter analyze` - the + manager runs the probe once per area, writes the note and runs the integrated + checks. +- Exact web wording and request shape named in the prompt; native controls and + theme roles only; no fixed sizes or palettes. +- Target: Code under 10 minutes, run under 20. + +Manager per wave: merge each branch, run the focused suite, one area probe, then +the full suite/analyze and one preview publish. Probes and full checks are +batched, not repeated per lane.