diff --git a/app/lib/features/artifacts/ui/artifact_external_open.dart b/app/lib/features/artifacts/ui/artifact_external_open.dart new file mode 100644 index 00000000..15ae4180 --- /dev/null +++ b/app/lib/features/artifacts/ui/artifact_external_open.dart @@ -0,0 +1,14 @@ +import '../domain/artifact_url.dart'; +import 'artifact_external_open_stub.dart' + if (dart.library.js_interop) 'artifact_external_open_web.dart' + as impl; + +/// Opens an already validated artifact url with the host's external handler. +/// +/// The url must come from [resolveArtifactUrl]; this capability never resolves, +/// rewrites, fetches or previews it. Returns whether the host accepted the +/// request, so a refusal is reported instead of being silently swallowed. +typedef ArtifactExternalOpen = Future Function(Uri uri); + +Future openArtifactExternally(Uri uri) => + impl.openArtifactExternally(uri); diff --git a/app/lib/features/artifacts/ui/artifact_external_open_stub.dart b/app/lib/features/artifacts/ui/artifact_external_open_stub.dart new file mode 100644 index 00000000..95708cb5 --- /dev/null +++ b/app/lib/features/artifacts/ui/artifact_external_open_stub.dart @@ -0,0 +1,6 @@ +/// Non-web fallback for external artifact urls. +/// +/// A native launcher needs a platform plugin that this slice does not depend +/// on, so a non-web host reports the refusal instead of pretending to open the +/// link. The page surfaces that message to the operator. +Future openArtifactExternally(Uri uri) async => false; diff --git a/app/lib/features/artifacts/ui/artifact_external_open_web.dart b/app/lib/features/artifacts/ui/artifact_external_open_web.dart new file mode 100644 index 00000000..f57fc411 --- /dev/null +++ b/app/lib/features/artifacts/ui/artifact_external_open_web.dart @@ -0,0 +1,20 @@ +import 'dart:js_interop'; +import 'dart:js_interop_unsafe'; + +/// Web external open: a new browser tab. The url is already validated by +/// [resolveArtifactUrl]; it is passed through unchanged and never fetched. +/// +/// `window.open` is reached through `js_interop` rather than `dart:html`, so the +/// same source compiles for both the JavaScript and WebAssembly web targets. +Future openArtifactExternally(Uri uri) async { + try { + final opened = globalContext.callMethod( + 'open'.toJS, + uri.toString().toJS, + '_blank'.toJS, + ); + return opened.isDefinedAndNotNull; + } catch (_) { + return false; + } +} diff --git a/app/lib/features/artifacts/ui/artifact_gallery_action.dart b/app/lib/features/artifacts/ui/artifact_gallery_action.dart new file mode 100644 index 00000000..7cffb7c8 --- /dev/null +++ b/app/lib/features/artifacts/ui/artifact_gallery_action.dart @@ -0,0 +1,104 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../core/api_gateway.dart'; +import '../../../core/transport/pipelines_client.dart'; +import '../../../ui/adaptive/host.dart'; +import 'artifact_external_open.dart'; +import 'artifact_gallery_page.dart'; + +/// The run detail's action label key, so a host can find the one action. +const ValueKey runArtifactsButtonKey = ValueKey( + 'run-detail-artifacts', +); + +const Set _executingStatuses = {'queued', 'running', 'waiting'}; + +/// The detail's `steps` exactly as returned by the server. The pushed page +/// snapshots the returned list once, so it never re-derives on each rebuild. +List runDetailArtifactSteps(JsonMap run) { + final steps = run['steps']; + if (steps is List) return steps; + if (steps is List) return steps.cast(); + return const []; +} + +/// Whether the run detail offers the gallery action at all: only once the +/// loaded detail actually carries steps. A run with no steps has nothing to +/// list, so the action is absent rather than opening a page that says so. +bool showRunArtifactsAction(JsonMap run) => + runDetailArtifactSteps(run).isNotEmpty; + +/// Whether the run is still executing, so the page can say capture pending +/// instead of claiming nothing was recorded. +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 { + const RunArtifactsButton({ + super.key, + required this.run, + required this.gateway, + }); + + final JsonMap run; + final ApiGateway gateway; + + @override + Widget build(BuildContext context) { + final steps = runDetailArtifactSteps(run); + void open() => showArtifactGallery( + context, + steps: steps, + executing: _runExecuting(run), + configuredEndpoint: _gatewayEndpoint(gateway), + ); + if (usesCupertinoHost(context)) { + return CupertinoButton.tinted( + key: runArtifactsButtonKey, + onPressed: open, + child: const Text(artifactGalleryTitle), + ); + } + return FilledButton.tonalIcon( + key: runArtifactsButtonKey, + onPressed: open, + icon: const Icon(Icons.inventory_2_outlined), + label: const Text(artifactGalleryTitle), + ); + } +} + +/// Opens the recorded artifact groups on a native page. The steps are +/// snapshotted once; the page never re-fetches or re-derives them. +Future showArtifactGallery( + BuildContext context, { + required List steps, + bool executing = false, + String configuredEndpoint = '', + ArtifactExternalOpen openExternal = openArtifactExternally, +}) { + final page = ArtifactGalleryPage( + steps: List.unmodifiable(steps), + executing: executing, + configuredEndpoint: configuredEndpoint, + openExternal: openExternal, + ); + return Navigator.of(context).push( + usesCupertinoHost(context) + ? CupertinoPageRoute(builder: (_) => page) + : MaterialPageRoute(builder: (_) => page), + ); +} diff --git a/app/lib/features/artifacts/ui/artifact_gallery_page.dart b/app/lib/features/artifacts/ui/artifact_gallery_page.dart new file mode 100644 index 00000000..9cc12338 --- /dev/null +++ b/app/lib/features/artifacts/ui/artifact_gallery_page.dart @@ -0,0 +1,194 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +import '../../../core/api_gateway.dart'; +import '../../../ui/adaptive/host.dart'; +import '../domain/artifact_groups.dart'; +import '../domain/artifact_record.dart'; +import '../domain/artifact_summary.dart'; +import '../domain/artifact_url.dart'; +import 'artifact_external_open.dart'; +import 'artifact_selection_facts.dart'; +import 'artifact_visit_list.dart'; + +/// The gallery page title. +const String artifactGalleryTitle = 'Artifacts'; + +/// A read-only page of recorded stage/visit artifact groups. +/// +/// Selection uses [artifactVisitIdentity], so the same filename in two visits +/// stays two distinct selections. Selecting a row 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. It never previews, downloads, shares or filters. +class ArtifactGalleryPage extends StatefulWidget { + const ArtifactGalleryPage({ + super.key, + required this.steps, + this.executing = false, + this.configuredEndpoint = '', + this.openExternal = openArtifactExternally, + }); + + final List steps; + final bool executing; + final String configuredEndpoint; + final ArtifactExternalOpen openExternal; + + @override + State createState() => _ArtifactGalleryPageState(); +} + +class _ArtifactGalleryPageState extends State { + late final Map _stepsByGroup = recordedStepsByGroup( + widget.steps, + ); + String? _selectedIdentity; + String? _status; + + void _select(ArtifactGroup group, ArtifactRecord artifact) { + setState(() { + _selectedIdentity = artifactVisitIdentity(group, artifact); + _status = null; + }); + _showSelected(group, artifact); + } + + Future _showSelected(ArtifactGroup group, ArtifactRecord artifact) { + final step = _stepsByGroup[artifactGroupKey(group.stageKey, group.visit)]; + final resolved = artifact.hasUrl + ? resolveArtifactUrl(widget.configuredEndpoint, artifact.url) + : null; + final facts = ArtifactSelectionFacts( + group: group, + artifact: artifact, + step: step, + resolved: resolved, + ); + if (usesCupertinoHost(context)) { + return showCupertinoDialog( + context: context, + builder: (dialogContext) => CupertinoAlertDialog( + title: Text(artifactDisplayName(artifact)), + content: facts, + actions: [ + if (resolved != null) + CupertinoDialogAction( + isDefaultAction: true, + onPressed: () => _open(resolved, dialogContext), + child: const Text('Open'), + ), + if (resolved != null) + CupertinoDialogAction( + onPressed: () => _copyLink(resolved, dialogContext), + child: const Text('Copy link'), + ), + CupertinoDialogAction( + onPressed: () => Navigator.of(dialogContext).pop(), + child: const Text('Close'), + ), + ], + ), + ); + } + return showDialog( + context: context, + builder: (dialogContext) => AlertDialog( + title: Text(artifactDisplayName(artifact)), + content: SingleChildScrollView(child: facts), + actions: [ + if (resolved != null) + TextButton( + onPressed: () => _copyLink(resolved, dialogContext), + child: const Text('Copy link'), + ), + TextButton( + onPressed: () => Navigator.of(dialogContext).pop(), + child: const Text('Close'), + ), + if (resolved != null) + TextButton( + onPressed: () => _open(resolved, dialogContext), + child: const Text('Open'), + ), + ], + ), + ); + } + + Future _open( + ResolvedArtifactUrl resolved, + BuildContext dialogContext, + ) async { + Navigator.of(dialogContext).pop(); + final opened = await widget.openExternal(resolved.uri); + if (!mounted) return; + setState( + () => _status = opened + ? 'Link opened externally.' + : 'Could not open the link.', + ); + } + + Future _copyLink( + ResolvedArtifactUrl resolved, + BuildContext dialogContext, + ) async { + Navigator.of(dialogContext).pop(); + String message; + try { + await Clipboard.setData(ClipboardData(text: resolved.url)); + message = 'Link copied.'; + } catch (_) { + message = 'Could not copy link.'; + } + if (!mounted) return; + setState(() => _status = message); + } + + @override + Widget build(BuildContext context) { + final groups = artifactGroups(widget.steps); + final summary = widget.steps.isEmpty + ? 'No steps recorded for this run.' + : artifactsHeader(widget.steps, executing: widget.executing); + final body = Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Padding( + padding: const EdgeInsetsDirectional.fromSTEB(16, 12, 16, 4), + child: Text(summary), + ), + if (_status != null) + Padding( + padding: const EdgeInsetsDirectional.fromSTEB(16, 0, 16, 4), + child: Semantics(liveRegion: true, child: Text(_status!)), + ), + if (groups.isNotEmpty) + Expanded( + child: ArtifactVisitList( + groups: groups, + selectedIdentity: _selectedIdentity, + onSelected: _select, + ), + ), + ], + ); + if (usesCupertinoHost(context)) { + return CupertinoPageScaffold( + // Sections paint the grouped background; the page must match it or a + // white seam shows below the last section in light mode. + backgroundColor: CupertinoColors.systemGroupedBackground, + navigationBar: const CupertinoNavigationBar( + middle: Text(artifactGalleryTitle), + ), + child: SafeArea(child: body), + ); + } + return Scaffold( + appBar: AppBar(title: const Text(artifactGalleryTitle)), + body: SafeArea(top: false, child: body), + ); + } +} diff --git a/app/lib/features/artifacts/ui/artifact_selection_facts.dart b/app/lib/features/artifacts/ui/artifact_selection_facts.dart new file mode 100644 index 00000000..083a322e --- /dev/null +++ b/app/lib/features/artifacts/ui/artifact_selection_facts.dart @@ -0,0 +1,71 @@ +import 'package:flutter/widgets.dart'; + +import '../../../core/api_gateway.dart'; +import '../../graph/domain/stage_visits.dart'; +import '../domain/artifact_groups.dart'; +import '../domain/artifact_record.dart'; +import '../domain/artifact_summary.dart'; +import '../domain/artifact_url.dart'; +import 'artifact_visit_list.dart'; + +/// The key one recorded group maps to, used only to find its step. +String artifactGroupKey(String stageKey, int visit) => '$stageKey\u0000$visit'; + +/// Each recorded group's step, keyed by stage and display visit, so a selected +/// row can show its own visit's capture facts. Derives the same grouping the +/// gallery uses; an absent key yields null rather than a fabricated capture. +Map recordedStepsByGroup(List steps) { + final result = {}; + for (final entry in visitsByStage(steps).entries) { + for (var index = 0; index < entry.value.length; index += 1) { + final step = entry.value[index]; + result[artifactGroupKey(entry.key, displayVisit(step, index))] = step; + } + } + return result; +} + +/// The recorded facts of one selected artifact: name, MIME/size, its visit's +/// capture summary and notes, and the url state. Nothing is inferred. +class ArtifactSelectionFacts extends StatelessWidget { + const ArtifactSelectionFacts({ + super.key, + required this.group, + required this.artifact, + required this.step, + required this.resolved, + }); + + final ArtifactGroup group; + final ArtifactRecord artifact; + final JsonMap? step; + final ResolvedArtifactUrl? resolved; + + @override + Widget build(BuildContext context) { + final recordedStep = step; + final url = resolved; + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text(artifactFactsLabel(artifact)), + const SizedBox(height: 8), + Text(artifactGroupLabel(group)), + if (recordedStep != null) ...[ + const SizedBox(height: 8), + Text(artifactsSummary(recordedStep, count: group.artifacts.length)), + for (final note in artifactCaptureNotes(recordedStep)) + Padding(padding: const EdgeInsets.only(top: 4), child: Text(note)), + ], + if (!artifact.hasUrl) ...[ + const SizedBox(height: 8), + const Text('No artifact URL recorded.'), + ] else if (url == null) ...[ + const SizedBox(height: 8), + const Text('The recorded artifact URL cannot be opened safely.'), + ], + ], + ); + } +} diff --git a/app/lib/features/artifacts/ui/artifact_visit_list.dart b/app/lib/features/artifacts/ui/artifact_visit_list.dart index 82cf0aa8..043e43a6 100644 --- a/app/lib/features/artifacts/ui/artifact_visit_list.dart +++ b/app/lib/features/artifacts/ui/artifact_visit_list.dart @@ -22,6 +22,25 @@ String artifactVisitIdentity(ArtifactGroup group, ArtifactRecord artifact) { return '${group.stageKey}\u0000${group.visit}\u0000$recorded'; } +/// The recorded group heading, matching the web client's group vocabulary. +String artifactGroupLabel(ArtifactGroup group) => + '${group.stageKey} · visit ${group.visit}'; + +/// The displayed artifact name: a missing server name stays explicit. +String artifactDisplayName(ArtifactRecord artifact) => + artifact.name.isEmpty ? '(unnamed artifact)' : artifact.name; + +/// The recorded MIME and byte size, never inferred from the name. +/// +/// The value and its unit are joined by a non-breaking space so a narrow row +/// never wraps `120.6` away from `KiB`. +String artifactFactsLabel(ArtifactRecord artifact) { + final type = artifact.contentType.split(';').first.trim(); + final mime = type.isEmpty ? 'type not recorded' : type; + final size = humanBytes(artifact.sizeBytes).replaceFirst(' ', '\u00a0'); + return '$mime · $size'; +} + /// A read-only, selectable list of recorded artifact groups. /// /// Each group shows its recorded stage and visit, and each row its recorded @@ -60,7 +79,7 @@ class ArtifactVisitList extends StatelessWidget { header: Semantics( container: true, header: true, - child: Text(_groupLabel(group)), + child: Text(artifactGroupLabel(group)), ), hasLeading: false, children: [ @@ -85,7 +104,7 @@ class ArtifactVisitList extends StatelessWidget { child: Semantics( container: true, header: true, - child: Text(_groupLabel(group)), + child: Text(artifactGroupLabel(group)), ), ), for (var index = 0; index < group.artifacts.length; index += 1) @@ -108,25 +127,6 @@ class ArtifactVisitList extends StatelessWidget { ValueKey('${artifactVisitIdentity(group, artifact)}\u0000$index'); } -/// The recorded group heading, matching the web client's group vocabulary. -String _groupLabel(ArtifactGroup group) => - '${group.stageKey} · visit ${group.visit}'; - -/// The displayed artifact name: a missing server name stays explicit. -String _displayName(ArtifactRecord artifact) => - artifact.name.isEmpty ? '(unnamed artifact)' : artifact.name; - -/// The recorded MIME and byte size, never inferred from the name. -/// -/// The value and its unit are joined by a non-breaking space so a narrow row -/// never wraps `120.6` away from `KiB`. -String _facts(ArtifactRecord artifact) { - final type = artifact.contentType.split(';').first.trim(); - final mime = type.isEmpty ? 'type not recorded' : type; - final size = humanBytes(artifact.sizeBytes).replaceFirst(' ', '\u00a0'); - return '$mime · $size'; -} - class _MaterialRow extends StatelessWidget { const _MaterialRow({ super.key, @@ -145,8 +145,8 @@ class _MaterialRow extends StatelessWidget { Widget build(BuildContext context) { return ListTile( selected: selected, - title: Text(_displayName(artifact)), - subtitle: Text(_facts(artifact)), + title: Text(artifactDisplayName(artifact)), + subtitle: Text(artifactFactsLabel(artifact)), trailing: selected ? const Icon(Icons.check) : null, onTap: onSelected == null ? null : () => onSelected!(group, artifact), ); @@ -181,8 +181,8 @@ class _CupertinoRow extends StatelessWidget { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Text(_displayName(artifact)), - Text(_facts(artifact), style: factsStyle), + Text(artifactDisplayName(artifact)), + Text(artifactFactsLabel(artifact), style: factsStyle), ], ), ), diff --git a/app/lib/features/runs/ui/run_detail_actions.dart b/app/lib/features/runs/ui/run_detail_actions.dart index 699f734c..8639e899 100644 --- a/app/lib/features/runs/ui/run_detail_actions.dart +++ b/app/lib/features/runs/ui/run_detail_actions.dart @@ -1,6 +1,7 @@ import 'package:flutter/widgets.dart'; import '../../../core/api_gateway.dart'; +import '../../artifacts/ui/artifact_gallery_action.dart'; import '../actions/cancel_run_action.dart'; import '../actions/title_action.dart'; import 'run_decision_notice.dart'; @@ -36,6 +37,8 @@ class RunDetailActions extends StatelessWidget { gateway: gateway, onRunChanged: onRunChanged, ), + if (showRunArtifactsAction(run)) + RunArtifactsButton(run: run, gateway: gateway), ], ), RunDecisionNotice(run: run, gateway: gateway, onRunChanged: onRunChanged), diff --git a/app/notes/A1-wire.md b/app/notes/A1-wire.md new file mode 100644 index 00000000..94949244 --- /dev/null +++ b/app/notes/A1-wire.md @@ -0,0 +1,150 @@ +# A1-wire — native Artifacts action and recorded-group gallery + +## What changed + +The run detail now offers a standard native **Artifacts** action whenever the +loaded detail carries steps. It pushes a native page that lists the recorded +stage/visit groups from the landed `artifactGroups`/`ArtifactVisitList`. +Selecting a row opens the host's native dialog with the recorded name, MIME and +size, the visit's own capture facts, and — only when the recorded url resolves +through the existing `resolveArtifactUrl` rules — native **Open** and a separate +**Copy link**. + +| File | Lines | Responsibility | +| --- | --- | --- | +| `lib/features/artifacts/ui/artifact_gallery_action.dart` | 104 | Action gate, steps snapshot, native button, page push | +| `lib/features/artifacts/ui/artifact_gallery_page.dart` | 194 | The page: summary/empty state, list, selection, Open/Copy link | +| `lib/features/artifacts/ui/artifact_selection_facts.dart` | 71 | Group→step map and the recorded-facts widget | +| `lib/features/artifacts/ui/artifact_external_open.dart` | 14 | `ArtifactExternalOpen` capability + default | +| `lib/features/artifacts/ui/artifact_external_open_web.dart` | 20 | `window.open` through `js_interop` (JS and wasm) | +| `lib/features/artifacts/ui/artifact_external_open_stub.dart` | 6 | Non-web refusal (no launcher dependency in this slice) | +| `lib/features/artifacts/ui/artifact_visit_list.dart` | +28/-25 | Exposes the landed label helpers the page reuses | +| `lib/features/runs/ui/run_detail_actions.dart` | +3 | Composes the action beside Rename/Cancel | +| `test/features/artifacts/ui/artifact_gallery_page_test.dart` | 321 | Page, identity, capture facts, url rules, copy | +| `test/features/runs/ui/run_artifacts_action_test.dart` | 161 | Action gate and wiring on both hosts | +| `tool/artifact_gallery_probe.dart` | 232 | Isolated fixture entry (real `RunDetailView`) | +| `tool/artifact_gallery_probe.mjs` | 421 | Loopback server + headless Chrome driver | + +No shell/main, pubspec, `web/`, Go server, `android/` or other feature was +edited. No dependency was added. + +## Behaviour + +- **Gate.** `showRunArtifactsAction` is true exactly when the loaded detail has + at least one step. A detail with no steps shows no action; the page also has + an explicit `No steps recorded for this run.` state if ever reached. +- **Truthful empty/unavailable.** The page header is the landed + `artifactsHeader`: `Artifacts · N recorded` (`· partial capture` when a visit + excluded/omitted files), `Artifacts · capture pending` while executing, + `No artifacts recorded for this run.` only for a recorded empty capture, and + `Artifacts · capture unavailable` when the field was absent. An unavailable + capture never says nothing was recorded. +- **Selection identity.** `ArtifactVisitList` selection uses + `artifactVisitIdentity`; two visits that both recorded `result.csv` stay two + distinct rows and selections (unit + browser evidence). +- **Facts.** The dialog shows the recorded filename (or `(unnamed artifact)`), + the recorded MIME/size (`type not recorded` when empty), the group's + `stage · visit N`, the visit's `artifactsSummary` and its + `artifactCaptureNotes`. Nothing is inferred from a name. +- **Url rules.** Open/Copy link appear only when `resolveArtifactUrl` returns a + value: absolute http(s) or a server-relative path resolved against the + configured endpoint. Protocol-relative, credentialed, malformed and + non-http(s) urls are rejected and the dialog says + `The recorded artifact URL cannot be opened safely.` A record with no url says + `No artifact URL recorded.` and offers no action. The endpoint comes from the + app's shared `PipelinesClient` when the gateway exposes it; a fixture gateway + leaves it blank, which only disables relative resolution. +- **Open vs copy.** Open calls the injected `ArtifactExternalOpen` with the + resolved `Uri` (web: a new tab via `window.open` reached through + `js_interop`, so it compiles for JS and wasm). Copy link is a separate action + that writes the resolved url to the clipboard. Each reports + `Link opened externally.` / `Could not open the link.` and `Link copied.` / + `Could not copy link.` as an inline live region. +- **Controls.** Material uses `FilledButton.tonalIcon` + `AlertDialog`; Cupertino + uses `CupertinoButton.tinted` + `CupertinoAlertDialog` and the grouped page + background. No fixed row/button sizes, custom font or palette. The Cupertino + action is text-only: the icon variant overflowed by 11 px at 2x text on 390 px + (caught by the existing `run_detail_widget_test`), and dropping the icon keeps + the label whole without clipping. +- **Out of scope, labelled next:** in-app preview/viewer, download, share files, + gallery filters and any network artifact fetch were not written. + +## Checks actually run + +``` +flutter analyze # No issues found +dart format --output=none --set-exit-if-changed ... # 0 changed +flutter test test/features/artifacts test/features/runs # 203 passed +flutter test # 712 passed (whole app) +flutter build web # ✓ Built build/web +flutter build web -t tool/artifact_gallery_probe.dart # ✓ Built build/probe-gallery +node --check tool/artifact_gallery_probe.mjs # ok +node tool/artifact_gallery_probe.mjs ... # 13/13 checks, 16 captures +``` + +`git status --short --untracked-files=all` lists only the files above; +`pubspec.yaml`/`pubspec.lock` are unchanged. No commit, push or deploy. + +## Real browser evidence + +`tool/artifact_gallery_probe.dart` renders the real `RunDetailView` over a fake +`get_run` gateway; `tool/artifact_gallery_probe.mjs` serves the build on an +OS-assigned loopback port and drives headless Chrome. Recorded urls point at the +probe's own loopback origin (plus unsafe/no-url/empty/unavailable states). No +server or operator run was touched. + +13/13 checks passed; 16 captures in +`/Users/alan/.local/share/pipelines/data/artifacts/81/public/a1-wire/` +(`evidence.json` holds the machine-readable result): + +- The run detail offers the native Artifacts action; the page lists the actual + recorded rows (`build.log`, `shot.png`, two `result.csv` visits, group + headings, MIME/size), not nav labels. +- Selecting the lower duplicate `result.csv` selected `reviewer · visit 2` with + its own `Artifacts · 1 recorded · partial capture` and + `2 files excluded from artifact capture.` +- The safe selection offers native **Open** and a separate **Copy link**; a + protocol-relative url offers neither and shows the unsafe wording; a url-less + record shows `No artifact URL recorded.` and no action. +- A recorded empty capture says `No artifacts recorded for this run.`; an + unavailable capture says `Artifacts · capture unavailable` and never the empty + wording. +- Cupertino lists the same rows with its native dialog and actions; dark + Cupertino dialog text samples light (max luminance 1.0). +- Both hosts at 320 px / 2x text keep the recorded rows, facts and actions + whole. + +Captures: `a1w-material-{detail,gallery,selected,open,unsafe,nourl,empty, +unavailable}.png`, `a1w-cupertino-{gallery,selected,dark-gallery, +dark-selected}.png`, `a1w-{material,cupertino}-2x-320-{gallery,selected}.png`. + +## Not verified / limits + +- The actual new-tab open could not be driven in headless Chrome: a synthetic + semantics activation carries no user gesture, so the app reports its honest + `Could not open the link.` refusal path. The browser proves the action is + offered only for a safe resolved url; the widget test proves the exact + `http://127.0.0.1:8081/artifacts/1/1/result.csv` uri handed to the opener and + the clipboard write. A genuine user tap was not captured. +- Non-web external open returns false (no launcher dependency is in scope); the + page reports that refusal. Mobile targets were not built or run, so **mobile + remains unverified**. +- All data is fixture data; no live server or operator run was used. +- Page/viewer/share/download/filters are not part of this slice and are labelled + as next work. + +## Manager completion after the Code deadline + +The Code visit hit its 30-minute deadline while still active; its session settled +and all edits were retained. No retry was started. The manager confirmed the dirty +paths were exactly this slice, then ran the focused artifacts/UI tests (29 pass), +analysis, and the fixture probe. The probe covers both hosts plus 320px/2x and +produced 16 captures (detail, gallery, selected facts, Open, unsafe url, no url, +empty, unavailable capture). The Cupertino dark selected dialog and the Material +320px/2x selected dialog were inspected: recorded name/MIME/size, the visit's own +capture facts, excluded-file note, and distinct Open / Copy link / Close where a +safe url exists. + +Deliberate scope: this slice links to a validated url externally and copies that +link. It performs no in-app preview, download or file sharing, so the artifact +viewer/Share rows in app/PARITY.md remain open. diff --git a/app/test/features/artifacts/ui/artifact_gallery_page_test.dart b/app/test/features/artifacts/ui/artifact_gallery_page_test.dart new file mode 100644 index 00000000..c1a4fe72 --- /dev/null +++ b/app/test/features/artifacts/ui/artifact_gallery_page_test.dart @@ -0,0 +1,321 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/artifacts/domain/artifact_groups.dart'; +import 'package:pipelines_app/features/artifacts/ui/artifact_gallery_page.dart'; +import 'package:pipelines_app/features/artifacts/ui/artifact_visit_list.dart'; + +import '../domain/artifact_fixtures.dart'; + +enum _Platform { material, cupertino } + +JsonMap _recorded( + String name, { + String url = '', + String contentType = 'text/csv', + int sizeBytes = 2048, +}) => artifact( + name, + url: url.isEmpty ? null : url, + contentType: contentType, + sizeBytes: sizeBytes, +); + +/// Two visits of `review` record the same filename; the second visit also +/// records `notes.md`. `build` records one file. +List _steps() => [ + step( + stage: 'build', + sequence: 1, + visit: 1, + artifacts: [_recorded('build.log', contentType: 'text/plain')], + ), + step( + stage: 'review', + sequence: 2, + visit: 1, + artifacts: [ + _recorded('result.csv'), + _recorded('notes.md', contentType: 'text/markdown'), + ], + ), + step( + stage: 'review', + sequence: 3, + visit: 2, + artifacts: [_recorded('result.csv', url: '/artifacts/1/2/result.csv')], + ), +]; + +Future _pumpGallery( + WidgetTester tester, + _Platform platform, + List steps, { + String configuredEndpoint = '', + bool executing = false, + Future Function(Uri)? openExternal, +}) async { + final page = ArtifactGalleryPage( + steps: steps, + executing: executing, + configuredEndpoint: configuredEndpoint, + openExternal: openExternal ?? (_) async => true, + ); + await tester.pumpWidget( + platform == _Platform.material + ? MaterialApp(home: page) + : CupertinoApp(home: page), + ); + await tester.pumpAndSettle(); +} + +Finder _inDialog(_Platform platform, String text) => find.descendant( + of: find.byType( + platform == _Platform.material ? AlertDialog : CupertinoAlertDialog, + ), + matching: find.text(text), +); + +void main() { + for (final platform in _Platform.values) { + testWidgets('${platform.name}: lists recorded groups and rows', ( + tester, + ) async { + await _pumpGallery(tester, platform, _steps()); + expect(find.text('Artifacts · 4 recorded'), findsOneWidget); + expect(find.text('build · visit 1'), findsOneWidget); + expect(find.text('review · visit 1'), findsOneWidget); + expect(find.text('review · visit 2'), findsOneWidget); + expect(find.text('result.csv'), findsNWidgets(2)); + expect(find.text('notes.md'), findsOneWidget); + expect(find.text('text/markdown · 2.0\u00a0KiB'), findsOneWidget); + }); + + testWidgets('${platform.name}: duplicate filename stays visit distinct', ( + tester, + ) async { + final steps = _steps(); + await _pumpGallery(tester, platform, steps); + await tester.tap(find.text('result.csv').at(1)); + await tester.pumpAndSettle(); + + final groups = artifactGroups(steps); + final visitTwo = groups.firstWhere( + (group) => group.stageKey == 'review' && group.visit == 2, + ); + final list = tester.widget( + find.byType(ArtifactVisitList), + ); + expect( + list.selectedIdentity, + artifactVisitIdentity(visitTwo, visitTwo.artifacts.single), + ); + expect(_inDialog(platform, 'review · visit 2'), findsOneWidget); + expect(_inDialog(platform, 'review · visit 1'), findsNothing); + expect(_inDialog(platform, 'Artifacts · 1 recorded'), findsOneWidget); + }); + } + + testWidgets('capture notes and partial label come from the visit step', ( + tester, + ) async { + await _pumpGallery(tester, _Platform.material, [ + step( + stage: 'review', + visit: 1, + artifacts: [_recorded('result.csv'), _recorded('notes.md')], + skipped: 2, + truncated: 3, + ), + ]); + expect( + find.text('Artifacts · 2 recorded · partial capture'), + findsOneWidget, + ); + await tester.tap(find.text('result.csv')); + await tester.pumpAndSettle(); + expect( + _inDialog(_Platform.material, 'Artifacts · 2 recorded · partial capture'), + findsOneWidget, + ); + expect( + _inDialog(_Platform.material, '2 files excluded from artifact capture.'), + findsOneWidget, + ); + expect( + _inDialog( + _Platform.material, + '3 files omitted by artifact capture limits.', + ), + findsOneWidget, + ); + }); + + testWidgets('an unavailable capture never claims nothing was recorded', ( + tester, + ) async { + await _pumpGallery(tester, _Platform.material, [ + step(stage: 'review', visit: 1, includeArtifacts: false), + ]); + expect(find.text('Artifacts · capture unavailable'), findsOneWidget); + expect(find.text('No artifacts recorded for this run.'), findsNothing); + }); + + testWidgets('a recorded empty capture says nothing was recorded', ( + tester, + ) async { + await _pumpGallery(tester, _Platform.material, [ + step(stage: 'review', visit: 1, artifacts: const []), + ]); + expect(find.text('No artifacts recorded for this run.'), findsOneWidget); + expect(find.byType(ArtifactVisitList), findsNothing); + }); + + testWidgets('a page with no steps says so explicitly', (tester) async { + await _pumpGallery(tester, _Platform.material, const []); + expect(find.text('No steps recorded for this run.'), findsOneWidget); + }); + + testWidgets('Open uses the resolved recorded url only', (tester) async { + final opened = []; + await _pumpGallery( + tester, + _Platform.material, + [ + step( + stage: 'review', + visit: 1, + artifacts: [ + _recorded('result.csv', url: '/artifacts/1/1/result.csv'), + ], + ), + ], + configuredEndpoint: 'ws://127.0.0.1:8081/connect', + openExternal: (uri) async { + opened.add(uri); + return true; + }, + ); + await tester.tap(find.text('result.csv')); + await tester.pumpAndSettle(); + await tester.tap(_inDialog(_Platform.material, 'Open')); + await tester.pumpAndSettle(); + + expect(opened, [ + Uri.parse('http://127.0.0.1:8081/artifacts/1/1/result.csv'), + ]); + expect(find.text('Link opened externally.'), findsOneWidget); + expect(find.byType(AlertDialog), findsNothing); + }); + + testWidgets('an unsafe recorded url offers no open or copy action', ( + tester, + ) async { + await _pumpGallery(tester, _Platform.material, [ + step( + stage: 'review', + visit: 1, + artifacts: [_recorded('result.csv', url: '//evil.test/result.csv')], + ), + ], configuredEndpoint: 'ws://127.0.0.1:8081/connect'); + await tester.tap(find.text('result.csv')); + await tester.pumpAndSettle(); + expect( + _inDialog( + _Platform.material, + 'The recorded artifact URL cannot be opened safely.', + ), + findsOneWidget, + ); + expect(_inDialog(_Platform.material, 'Open'), findsNothing); + expect(_inDialog(_Platform.material, 'Copy link'), findsNothing); + }); + + testWidgets('a record with no url is explicit and offers no action', ( + tester, + ) async { + await _pumpGallery(tester, _Platform.material, [ + step( + stage: 'review', + visit: 1, + artifacts: [ + { + 'name': 'result.csv', + 'url': '', + 'content_type': 'text/csv', + 'size_bytes': 10, + }, + ], + ), + ]); + await tester.tap(find.text('result.csv')); + await tester.pumpAndSettle(); + expect( + _inDialog(_Platform.material, 'No artifact URL recorded.'), + findsOneWidget, + ); + expect(_inDialog(_Platform.material, 'Open'), findsNothing); + }); + + testWidgets('Copy link copies the resolved url, separate from Open', ( + tester, + ) async { + final copied = []; + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + (call) async { + if (call.method == 'Clipboard.setData') { + copied.add((call.arguments as Map)['text'] as String); + } + return null; + }, + ); + addTearDown( + () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + null, + ), + ); + final opened = []; + await _pumpGallery( + tester, + _Platform.material, + [ + step( + stage: 'review', + visit: 1, + artifacts: [ + _recorded('result.csv', url: '/artifacts/1/1/result.csv'), + ], + ), + ], + configuredEndpoint: 'ws://127.0.0.1:8081/connect', + openExternal: (uri) async { + opened.add(uri); + return true; + }, + ); + await tester.tap(find.text('result.csv')); + await tester.pumpAndSettle(); + await tester.tap(_inDialog(_Platform.material, 'Copy link')); + await tester.pumpAndSettle(); + + expect(copied, ['http://127.0.0.1:8081/artifacts/1/1/result.csv']); + expect(opened, isEmpty); + expect(find.text('Link copied.'), findsOneWidget); + }); + + testWidgets('an executing run says capture pending', (tester) async { + await _pumpGallery(tester, _Platform.material, [ + step( + stage: 'review', + visit: 1, + includeArtifacts: false, + status: 'running', + ), + ], executing: true); + expect(find.text('Artifacts · capture pending'), findsOneWidget); + }); +} diff --git a/app/test/features/runs/ui/run_artifacts_action_test.dart b/app/test/features/runs/ui/run_artifacts_action_test.dart new file mode 100644 index 00000000..1a654187 --- /dev/null +++ b/app/test/features/runs/ui/run_artifacts_action_test.dart @@ -0,0 +1,161 @@ +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/ui/artifact_gallery_action.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'; + +import '../../artifacts/domain/artifact_fixtures.dart'; + +enum _Platform { material, cupertino } + +class _FakeGateway implements ApiGateway { + _FakeGateway(this.detail); + final JsonMap detail; + + @override + Stream get frames => const Stream.empty(); + + @override + Future call(String type, [JsonMap fields = const {}]) { + if (type != 'get_run') throw UnsupportedError(type); + return Future.value({'run_detail': detail}); + } +} + +JsonMap _run({required List steps}) => { + 'id': 21, + 'title': 'Artifacts wiring run', + 'name': 'gallery', + 'status': 'succeeded', + 'steps': steps, +}; + +Future _pumpDetail( + WidgetTester tester, + _Platform platform, + RunsController controller, + ApiGateway gateway, +) async { + tester.view.physicalSize = const Size(500, 1200); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + final view = RunDetailView( + controller: controller, + gateway: gateway, + onBack: () {}, + ); + await tester.pumpWidget( + platform == _Platform.material + ? MaterialApp(home: Scaffold(body: view)) + : CupertinoApp( + builder: (context, app) => Theme( + data: ThemeData(platform: TargetPlatform.iOS), + child: app!, + ), + home: CupertinoPageScaffold(child: view), + ), + ); + await tester.pumpAndSettle(); +} + +Future _loaded(ApiGateway gateway) async { + final controller = RunsController(RunsRepository(gateway)); + await controller.select(21); + return controller; +} + +void main() { + for (final platform in _Platform.values) { + testWidgets('${platform.name}: the action opens the recorded groups', ( + tester, + ) async { + final gateway = _FakeGateway( + _run( + steps: [ + step( + stage: 'implementer', + sequence: 1, + artifacts: [ + artifact( + 'build.log', + contentType: 'text/plain', + sizeBytes: 2337, + ), + ], + ), + step( + stage: 'reviewer', + sequence: 2, + artifacts: [ + artifact( + 'shot.png', + contentType: 'image/png', + sizeBytes: 80544, + ), + ], + ), + ], + ), + ); + final controller = await _loaded(gateway); + addTearDown(controller.dispose); + await _pumpDetail(tester, platform, controller, gateway); + + expect(find.byKey(runArtifactsButtonKey), findsOneWidget); + await tester.tap(find.byKey(runArtifactsButtonKey)); + await tester.pumpAndSettle(); + + expect(find.text('Artifacts · 2 recorded'), findsOneWidget); + expect(find.text('build.log'), findsOneWidget); + expect(find.text('shot.png'), findsOneWidget); + expect(find.text('implementer · visit 1'), findsOneWidget); + expect(find.text('reviewer · visit 1'), findsOneWidget); + }); + } + + testWidgets('the action is offered only when the detail has steps', ( + tester, + ) async { + final gateway = _FakeGateway(_run(steps: const [])); + final controller = await _loaded(gateway); + addTearDown(controller.dispose); + await _pumpDetail(tester, _Platform.material, controller, gateway); + expect(find.byKey(runArtifactsButtonKey), findsNothing); + }); + + testWidgets('a recorded empty capture keeps its explicit wording', ( + tester, + ) async { + final gateway = _FakeGateway( + _run( + steps: [step(stage: 'reviewer', visit: 1, artifacts: const [])], + ), + ); + final controller = await _loaded(gateway); + addTearDown(controller.dispose); + await _pumpDetail(tester, _Platform.material, controller, gateway); + + await tester.tap(find.byKey(runArtifactsButtonKey)); + await tester.pumpAndSettle(); + expect(find.text('No artifacts recorded for this run.'), findsOneWidget); + }); + + testWidgets('an unavailable capture is never reported as empty', ( + tester, + ) async { + final gateway = _FakeGateway( + _run(steps: [step(stage: 'reviewer', visit: 1, includeArtifacts: false)]), + ); + final controller = await _loaded(gateway); + addTearDown(controller.dispose); + await _pumpDetail(tester, _Platform.material, controller, gateway); + + await tester.tap(find.byKey(runArtifactsButtonKey)); + await tester.pumpAndSettle(); + expect(find.text('Artifacts · capture unavailable'), findsOneWidget); + expect(find.text('No artifacts recorded for this run.'), findsNothing); + }); +} diff --git a/app/tool/artifact_gallery_probe.dart b/app/tool/artifact_gallery_probe.dart new file mode 100644 index 00000000..fdaad138 --- /dev/null +++ b/app/tool/artifact_gallery_probe.dart @@ -0,0 +1,232 @@ +// Standalone fixture entry for real-browser run-detail Artifacts evidence. +// +// Build and probe (from app/): +// flutter build web --target tool/artifact_gallery_probe.dart --output build/probe-gallery +// node tool/artifact_gallery_probe.mjs --root build/probe-gallery --out DIR +// +// Server-shaped fixtures only: a fake gateway answers the same get_run envelope +// the app consumes. The recorded urls point at the probe's own loopback origin, +// so the external Open action has a real target. 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}); + } +} + +JsonMap _file( + String name, { + required String url, + required String contentType, + required int sizeBytes, +}) => { + 'name': name, + 'url': url, + 'content_type': contentType, + 'size_bytes': sizeBytes, +}; + +/// The recorded steps for one probe state. `default` carries two visits that +/// both record `result.csv` plus a partial capture on the second visit. +List _steps(String origin, String state) { + if (state == 'unavailable') { + return [ + { + 'stage': 'implementer', + 'sequence': 1, + 'status': 'completed', + 'control': {'visit': 1}, + }, + ]; + } + if (state == 'empty') { + return [ + { + 'stage': 'implementer', + 'sequence': 1, + 'status': 'completed', + 'control': {'visit': 1}, + 'artifacts': const [], + }, + ]; + } + if (state == 'unsafe' || state == 'nourl') { + return [ + { + 'stage': 'reviewer', + 'sequence': 1, + 'status': 'completed', + 'control': {'visit': 1}, + 'artifacts': [ + _file( + 'result.csv', + url: state == 'unsafe' ? '//evil.test/result.csv' : '', + contentType: 'text/csv', + sizeBytes: 2048, + ), + ], + }, + ]; + } + return [ + { + 'stage': 'implementer', + 'sequence': 1, + 'status': 'completed', + 'control': {'visit': 1}, + 'artifacts': [ + _file( + 'build.log', + url: '$origin/fixture/build.log', + contentType: 'text/plain; charset=utf-8', + sizeBytes: 2337, + ), + ], + }, + { + 'stage': 'reviewer', + 'sequence': 2, + 'status': 'completed', + 'control': {'visit': 1}, + 'artifacts': [ + _file( + 'result.csv', + url: '$origin/fixture/result.csv', + contentType: 'text/csv', + sizeBytes: 2048, + ), + _file( + 'shot.png', + url: '$origin/fixture/shot.png', + contentType: 'image/png', + sizeBytes: 80544, + ), + ], + }, + { + 'stage': 'reviewer', + 'sequence': 3, + 'status': 'completed', + 'control': {'visit': 2}, + 'artifacts': [ + _file( + 'result.csv', + url: '$origin/fixture/result-2.csv', + contentType: 'text/csv', + sizeBytes: 4096, + ), + ], + 'artifacts_skipped': 2, + }, + ]; +} + +JsonMap _run(String origin, String state) => { + 'id': 31, + 'title': 'Artifacts gallery probe', + 'name': 'gallery', + 'status': 'succeeded', + 'steps': _steps(origin, state), +}; + +void main() { + final params = Uri.base.queryParameters; + final cupertino = params['platform'] == 'cupertino'; + final theme = params['theme'] == 'dark' ? Brightness.dark : Brightness.light; + final origin = params['origin'] ?? 'https://artifacts.invalid'; + final state = params['state'] ?? 'default'; + // Browser text scaling is a fixture input like platform and theme. + final textScale = double.tryParse(params['scale'] ?? '') ?? 1; + final body = _ProbeBody(run: _run(origin, state)); + Widget scaled(BuildContext context, Widget? app) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(textScale)), + child: app!, + ); + if (cupertino) { + runApp( + CupertinoApp( + title: 'Artifacts probe', + theme: CupertinoThemeData(brightness: theme), + builder: (context, app) => Theme( + data: ThemeData(platform: TargetPlatform.iOS), + child: scaled(context, app), + ), + home: body, + ), + ); + } else { + runApp( + MaterialApp( + title: 'Artifacts probe', + theme: ThemeData(brightness: theme, platform: TargetPlatform.android), + builder: scaled, + home: body, + ), + ); + } +} + +class _ProbeBody extends StatefulWidget { + const _ProbeBody({required this.run}); + + 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(31); + } + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final detail = RunDetailView( + controller: _controller, + gateway: _gateway, + onBack: () {}, + ); + if (Theme.of(context).platform == TargetPlatform.iOS) { + return CupertinoPageScaffold( + navigationBar: const CupertinoNavigationBar(middle: Text('Runs')), + child: SafeArea(child: detail), + ); + } + return Scaffold( + appBar: AppBar(title: const Text('Runs')), + body: detail, + ); + } +} diff --git a/app/tool/artifact_gallery_probe.mjs b/app/tool/artifact_gallery_probe.mjs new file mode 100644 index 00000000..b57ff4a4 --- /dev/null +++ b/app/tool/artifact_gallery_probe.mjs @@ -0,0 +1,421 @@ +// Real-browser evidence for the run-detail Artifacts action and gallery page. +// +// Usage (from app/): +// flutter build web --target tool/artifact_gallery_probe.dart --output build/probe-gallery +// node tool/artifact_gallery_probe.mjs --root build/probe-gallery --out DIR +// +// Serves the built fixture on an OS-assigned loopback port, drives headless +// Chrome, and records the actual recorded rows, the selection dialog, the safe +// external Open, the empty/unavailable states, both native hosts, dark +// Cupertino and the 320/2x states. No server or operator run is touched. +import { createServer } from 'node:http'; +import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; +import { spawn } from 'node:child_process'; +import { once } from 'node:events'; +import { setTimeout as delay } from 'node:timers/promises'; +import { extname, join, resolve, sep } from 'node:path'; +import { tmpdir } from 'node:os'; + +const args = new Map(); +for (let i = 2; i < process.argv.length; i++) { + const value = process.argv[i]; + if (value.startsWith('--')) args.set(value.slice(2), process.argv[++i]); +} +const root = resolve(args.get('root') ?? 'build/probe-gallery'); +const out = resolve(args.get('out') ?? 'build/artifact-gallery-probe'); +const chromePath = + process.env.CHROME_PATH ?? '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'; +await mkdir(out, { recursive: true }); + +const mime = { + '.html': 'text/html; charset=utf-8', + '.js': 'text/javascript; charset=utf-8', + '.mjs': 'text/javascript; charset=utf-8', + '.json': 'application/json; charset=utf-8', + '.wasm': 'application/wasm', + '.png': 'image/png', + '.svg': 'image/svg+xml', + '.ico': 'image/x-icon', + '.ttf': 'font/ttf', + '.otf': 'font/otf', + '.woff': 'font/woff', + '.woff2': 'font/woff2', + '.bin': 'application/octet-stream', + '.frag': 'application/octet-stream', +}; + +const server = createServer(async (req, res) => { + const pathname = decodeURIComponent(new URL(req.url, 'http://localhost').pathname); + if (pathname.startsWith('/fixture/')) { + res.writeHead(200, { 'content-type': 'text/plain; charset=utf-8' }); + res.end(`recorded artifact ${pathname}\n`); + return; + } + try { + let filePath = resolve(root, '.' + pathname); + if (filePath !== root && !filePath.startsWith(root + sep)) { + res.writeHead(403).end(); + return; + } + if (pathname === '/' || pathname.endsWith('/')) filePath = join(filePath, 'index.html'); + const file = await readFile(filePath); + res.writeHead(200, { 'content-type': mime[extname(filePath)] ?? 'application/octet-stream' }).end(file); + } catch { + res.writeHead(404).end('not found'); + } +}); +server.listen(0, '127.0.0.1'); +await once(server, 'listening'); +const origin = `http://127.0.0.1:${server.address().port}`; + +const profile = await mkdtemp(join(tmpdir(), 'a1w-chrome-')); +const chrome = spawn( + chromePath, + ['--headless=new', '--no-first-run', '--no-default-browser-check', '--disable-gpu', + '--disable-popup-blocking', '--remote-debugging-port=0', `--user-data-dir=${profile}`, 'about:blank'], + { stdio: ['ignore', 'ignore', 'pipe'] }, +); +let stderr = ''; +chrome.stderr.on('data', (data) => { + stderr += data; +}); + +const waitFor = async (fn, what) => { + for (let i = 0; i < 120; i++) { + const value = await fn(); + if (value) return value; + await delay(100); + } + throw new Error(`Timed out waiting for ${what}: ${stderr.slice(-1500)}`); +}; + +const evidence = { origin, captures: [], checks: [] }; +let ws; +try { + const endpoint = await waitFor( + () => stderr.match(/DevTools listening on (ws:\/\/[^\s]+)/)?.[1], + 'Chrome DevTools', + ); + ws = new WebSocket(endpoint); + await once(ws, 'open'); + let id = 0; + const pending = new Map(); + ws.addEventListener('message', (event) => { + const message = JSON.parse(event.data); + if (message.id && pending.has(message.id)) { + pending.get(message.id)(message); + pending.delete(message.id); + } + }); + const send = (method, params = {}, sessionId) => + new Promise((resolveCall) => { + const callId = ++id; + pending.set(callId, resolveCall); + ws.send(JSON.stringify({ id: callId, method, params, ...(sessionId ? { sessionId } : {}) })); + }); + + const created = await send('Target.createTarget', { url: 'about:blank' }); + const session = (await send('Target.attachToTarget', { + targetId: created.result.targetId, + flatten: true, + })).result.sessionId; + await send('Page.enable', {}, session); + await send('Runtime.enable', {}, session); + await send('Browser.grantPermissions', { + origin, + permissions: ['clipboardReadWrite', 'clipboardSanitizedWrite'], + }); + await send('Emulation.setDeviceMetricsOverride', { + width: 390, height: 844, deviceScaleFactor: 1, mobile: true, + }, session); + + const evaluate = async (expression) => { + const response = await send( + 'Runtime.evaluate', + { expression, returnByValue: true, awaitPromise: true }, + session, + ); + if (response.error) throw new Error(`Runtime.evaluate failed: ${JSON.stringify(response)}`); + return response.result?.result?.value; + }; + const labels = () => + evaluate( + "[...document.querySelectorAll('flt-semantics')].map(x => x.getAttribute('aria-label') || (x.innerText || '').trim()).filter(Boolean)", + ); + const bodyText = () => evaluate('document.body.innerText'); + const hasLabel = async (label) => (await labels()).includes(label); + const clickExact = async (label) => { + const clicked = await evaluate(`(() => { + const wanted = ${JSON.stringify(label)}; + const text = (x) => x.getAttribute('aria-label') || (x.innerText || '').trim(); + const nodes = [...document.querySelectorAll('flt-semantics')]; + const tappable = nodes.filter(x => x.hasAttribute('flt-tappable')); + // The tappable node is the one the engine listens to; a labelled wrapper + // above it would swallow a synthetic click. + const node = tappable.find(x => text(x) === wanted) + || tappable.find(x => text(x).startsWith(wanted)) + || nodes.find(x => text(x) === wanted); + if (!node) return false; + node.click(); + return true; + })()`); + if (!clicked) throw new Error(`No exact semantics label ${JSON.stringify(label)}: ${JSON.stringify(await labels())}`); + await delay(500); + }; + // The lowest matching row is the later visit's duplicate filename. + const clickLowestPrefix = async (prefix) => { + const clicked = await evaluate(`(() => { + const wanted = ${JSON.stringify(prefix)}; + const text = (x) => x.getAttribute('aria-label') || (x.innerText || '').trim(); + const candidates = [...document.querySelectorAll('flt-semantics')] + .filter(x => text(x).startsWith(wanted)) + .filter(x => x.hasAttribute('flt-tappable')); + if (!candidates.length) return false; + candidates.sort((a, b) => b.getBoundingClientRect().y - a.getBoundingClientRect().y); + candidates[0].click(); + return true; + })()`); + if (!clicked) throw new Error(`No tappable label starting ${JSON.stringify(prefix)}: ${JSON.stringify(await labels())}`); + await delay(600); + }; + const activate = async () => { + await delay(3200); + await evaluate("document.querySelector('flt-semantics-placeholder')?.click()"); + await delay(900); + const current = await labels(); + if (!current.some((label) => label.includes('Artifacts gallery probe'))) { + throw new Error(`Flutter semantics unavailable: ${JSON.stringify(current)}`); + } + }; + const navigate = async (url) => { + const navigation = await send('Page.navigate', { url }, session); + if (navigation.error || navigation.result?.errorText) throw new Error(JSON.stringify(navigation)); + await activate(); + }; + const capture = async (name, width = 390, height = 844, scale = 1) => { + await send('Emulation.setDeviceMetricsOverride', { + width, height, deviceScaleFactor: scale, mobile: width < 600, + }, session); + await delay(350); + const data = (await send('Page.captureScreenshot', { format: 'png' }, session)).result.data; + const path = join(out, `${name}.png`); + await writeFile(path, Buffer.from(data, 'base64')); + evidence.captures.push(path); + }; + const rectOfPrefix = (prefix) => + evaluate(`(() => { + const wanted = ${JSON.stringify(prefix)}; + const text = (x) => x.getAttribute('aria-label') || (x.innerText || '').trim(); + const node = [...document.querySelectorAll('flt-semantics')].find(x => text(x).startsWith(wanted)); + if (!node) return null; + const r = node.getBoundingClientRect(); + return { x: r.x, y: r.y, width: r.width, height: r.height }; + })()`); + const brightestPixel = async (rect) => { + const shot = await send('Page.captureScreenshot', { + format: 'png', + clip: { ...rect, scale: 2 }, + }, session); + return evaluate(`(async () => { + const img = new Image(); + img.src = 'data:image/png;base64,${shot.result.data}'; + await img.decode(); + const canvas = document.createElement('canvas'); + canvas.width = img.width; + canvas.height = img.height; + const ctx = canvas.getContext('2d'); + ctx.drawImage(img, 0, 0); + const data = ctx.getImageData(0, 0, img.width, img.height).data; + let max = 0; + for (let i = 0; i < data.length; i += 4) { + const lum = (0.2126 * data[i] + 0.7152 * data[i + 1] + 0.0722 * data[i + 2]) / 255; + if (lum > max) max = lum; + } + return { max, width: img.width, height: img.height }; + })()`); + }; + const openGallery = async (query) => { + await navigate(`${origin}/?${query}`); + if (!(await hasLabel('Artifacts'))) { + throw new Error(`Run detail has no Artifacts action: ${JSON.stringify(await labels())}`); + } + await clickExact('Artifacts'); + await delay(600); + }; + + // Material: recorded rows, duplicate filename, visit-2 capture facts and the + // safe external Open. + await navigate(`${origin}/?origin=${encodeURIComponent(origin)}`); + if (!(await hasLabel('Artifacts'))) { + throw new Error(`Material run detail has no Artifacts action: ${JSON.stringify(await labels())}`); + } + evidence.checks.push({ check: 'the run detail offers the native Artifacts action', value: true }); + await capture('a1w-material-detail'); + + await clickExact('Artifacts'); + const galleryBody = await bodyText(); + for (const recorded of ['build.log', 'shot.png', 'text/csv', 'implementer · visit 1', 'reviewer · visit 2']) { + if (!galleryBody.includes(recorded)) { + throw new Error(`Gallery is missing recorded row ${recorded}: ${JSON.stringify(galleryBody)}`); + } + } + if (!galleryBody.includes('Artifacts · 4 recorded')) { + throw new Error(`Gallery summary missing: ${JSON.stringify(galleryBody)}`); + } + const resultRows = (await labels()).filter((label) => label.startsWith('result.csv')).length; + if (resultRows < 2) { + throw new Error(`Duplicate result.csv rows missing: ${JSON.stringify(await labels())}`); + } + evidence.checks.push({ check: 'the gallery lists the actual recorded rows, not nav labels', value: true }); + await capture('a1w-material-gallery'); + + await clickLowestPrefix('result.csv'); + const selectedBody = await bodyText(); + for (const fact of ['reviewer · visit 2', 'text/csv · 4.0\u00a0KiB', 'Artifacts · 1 recorded · partial capture', '2 files excluded from artifact capture.']) { + if (!selectedBody.includes(fact)) { + throw new Error(`Selected visit-2 facts missing ${fact}: ${JSON.stringify(selectedBody)}`); + } + } + if (!(await hasLabel('Open')) || !(await hasLabel('Copy link'))) { + throw new Error(`Selection offers no Open/Copy link: ${JSON.stringify(await labels())}`); + } + evidence.checks.push({ check: 'the duplicate filename selected visit 2 with its own capture facts', value: true }); + await capture('a1w-material-selected'); + + // The selection offers the safe external Open and a separate Copy link. + // Headless Chrome cannot carry a user activation through a synthetic + // semantics click, so the tab itself is proven by the widget test that + // records the exact uri handed to the opener; the browser proves the actions + // appear only for a url that resolves through the safe rules. + if (!(await hasLabel('Open')) || !(await hasLabel('Copy link'))) { + throw new Error(`Selection offers no Open/Copy link: ${JSON.stringify(await labels())}`); + } + evidence.checks.push({ + check: 'the selection offers the native Open and separate Copy link for a safe recorded url', + value: true, + }); + await capture('a1w-material-open'); + + await navigate(`${origin}/?origin=${encodeURIComponent(origin)}&state=unsafe`); + await clickExact('Artifacts'); + await clickLowestPrefix('result.csv'); + const unsafeBody = await bodyText(); + if (!unsafeBody.includes('The recorded artifact URL cannot be opened safely.')) { + throw new Error(`Unsafe url wording missing: ${JSON.stringify(unsafeBody)}`); + } + if ((await hasLabel('Open')) || (await hasLabel('Copy link'))) { + throw new Error(`Unsafe url still offered an action: ${JSON.stringify(await labels())}`); + } + evidence.checks.push({ check: 'a protocol-relative url offers no open or copy action', value: true }); + await capture('a1w-material-unsafe'); + + await navigate(`${origin}/?origin=${encodeURIComponent(origin)}&state=nourl`); + await clickExact('Artifacts'); + await clickLowestPrefix('result.csv'); + const nourlBody = await bodyText(); + if (!nourlBody.includes('No artifact URL recorded.')) { + throw new Error(`No-url wording missing: ${JSON.stringify(nourlBody)}`); + } + if ((await hasLabel('Open')) || (await hasLabel('Copy link'))) { + throw new Error(`A url-less record still offered an action: ${JSON.stringify(await labels())}`); + } + evidence.checks.push({ check: 'a record with no url is explicit and offers no action', value: true }); + await capture('a1w-material-nourl'); + + await navigate(`${origin}/?origin=${encodeURIComponent(origin)}&state=empty`); + await clickExact('Artifacts'); + const emptyBody = await bodyText(); + if (!emptyBody.includes('No artifacts recorded for this run.')) { + throw new Error(`Recorded empty capture wording missing: ${JSON.stringify(emptyBody)}`); + } + evidence.checks.push({ check: 'a recorded empty capture says nothing was recorded', value: true }); + await capture('a1w-material-empty'); + + await navigate(`${origin}/?origin=${encodeURIComponent(origin)}&state=unavailable`); + await clickExact('Artifacts'); + const unavailableBody = await bodyText(); + if (!unavailableBody.includes('Artifacts · capture unavailable')) { + throw new Error(`Unavailable capture wording missing: ${JSON.stringify(unavailableBody)}`); + } + if (unavailableBody.includes('No artifacts recorded for this run.')) { + throw new Error('Unavailable capture claimed nothing was recorded'); + } + evidence.checks.push({ check: 'an unavailable capture is never reported as empty', value: true }); + await capture('a1w-material-unavailable'); + + // Cupertino light: the tinted action, the native dialog and its actions. + await openGallery(`platform=cupertino&theme=light&origin=${encodeURIComponent(origin)}`); + const cupertinoBody = await bodyText(); + if (!cupertinoBody.includes('shot.png') || !cupertinoBody.includes('reviewer · visit 2')) { + throw new Error(`Cupertino gallery missing recorded rows: ${JSON.stringify(cupertinoBody)}`); + } + evidence.checks.push({ check: 'Cupertino lists the same recorded rows', value: true }); + await capture('a1w-cupertino-gallery'); + await clickLowestPrefix('result.csv'); + if (!(await hasLabel('Open')) || !(await hasLabel('Copy link'))) { + throw new Error(`Cupertino selection offers no actions: ${JSON.stringify(await labels())}`); + } + const cupertinoSelected = await bodyText(); + if (!cupertinoSelected.includes('Artifacts · 1 recorded · partial capture')) { + throw new Error(`Cupertino selection lost its capture facts: ${JSON.stringify(cupertinoSelected)}`); + } + evidence.checks.push({ check: 'Cupertino selection shows the recorded facts and native actions', value: true }); + await capture('a1w-cupertino-selected'); + + // Cupertino dark: the gallery and its dialog on the dark host. + await openGallery(`platform=cupertino&theme=dark&origin=${encodeURIComponent(origin)}`); + await capture('a1w-cupertino-dark-gallery'); + await clickLowestPrefix('result.csv'); + const darkLabels = await labels(); + const darkTitle = darkLabels.find((label) => label.startsWith('result.csv')); + const titleRect = await rectOfPrefix('result.csv'); + const darkText = [await bodyText(), ...darkLabels].join('\n'); + if (!darkText.includes('Artifacts · 1 recorded · partial capture')) { + throw new Error(`Dark Cupertino dialog did not render: ${JSON.stringify(darkText)}`); + } + if (!titleRect) throw new Error(`Dark Cupertino dialog title missing: ${JSON.stringify(darkLabels)}`); + const luminance = await brightestPixel(titleRect); + if (luminance.max < 0.5) { + throw new Error(`Dark Cupertino dialog text is not light: ${JSON.stringify(luminance)}`); + } + evidence.checks.push({ + check: 'dark Cupertino dialog text is light on the popup surface', + value: true, + luminance: luminance.max, + title: darkTitle, + }); + await capture('a1w-cupertino-dark-selected'); + + // 320 px at 2x text on both hosts: the recorded rows and facts stay whole. + const openScaled = async (platform, prefix) => { + await openGallery(`platform=${platform}&theme=light&scale=2&origin=${encodeURIComponent(origin)}`); + const scaled = await bodyText(); + for (const recorded of ['build.log', 'shot.png', 'reviewer · visit 2']) { + if (!scaled.includes(recorded)) { + throw new Error(`2x gallery missing ${recorded}: ${JSON.stringify(scaled)}`); + } + } + await capture(`${prefix}-gallery`, 320, 720, 1); + await clickLowestPrefix('result.csv'); + const facts = await bodyText(); + if (!facts.includes('Artifacts · 1 recorded · partial capture')) { + throw new Error(`2x selection lost its facts: ${JSON.stringify(facts)}`); + } + if (!(await hasLabel('Open')) || !(await hasLabel('Copy link'))) { + throw new Error(`2x selection lost its actions: ${JSON.stringify(await labels())}`); + } + await capture(`${prefix}-selected`, 320, 720, 1); + }; + await openScaled('material', 'a1w-material-2x-320'); + evidence.checks.push({ check: 'Material 2x/320 keeps the recorded rows, facts and actions', value: true }); + await openScaled('cupertino', 'a1w-cupertino-2x-320'); + evidence.checks.push({ check: 'Cupertino 2x/320 keeps the recorded rows, facts and actions', value: true }); + + console.log(JSON.stringify(evidence, null, 2)); +} finally { + ws?.close(); + chrome.kill('SIGTERM'); + await Promise.race([once(chrome, 'exit'), delay(3000)]); + server.close(); + await rm(profile, { recursive: true, force: true }); +}