diff --git a/app/lib/features/artifacts/domain/artifact_kind.dart b/app/lib/features/artifacts/domain/artifact_kind.dart index 7bac7708..3cf24f0c 100644 --- a/app/lib/features/artifacts/domain/artifact_kind.dart +++ b/app/lib/features/artifacts/domain/artifact_kind.dart @@ -196,13 +196,17 @@ bool isMarkdownArtifact(String contentType, String name) { return _markdownExtensions.contains(_extensionOf(name)); } -/// Whether an artifact opens inside the full-screen viewer: images, videos, and -/// markdown/text documents. A `text/plain` log, source file or spreadsheet stays -/// an external file because those are evidence, not prose. +/// Whether an artifact opens inside the viewer: images, videos, markdown/text +/// documents and any recorded `text/plain` file. The viewer draws text/plain as +/// selectable text; a CSV, source file or spreadsheet with its own type stays an +/// external file because it is evidence, not prose. Videos are pageable but the +/// viewer reports that it cannot draw them rather than faking a player. bool isViewerArtifact(String contentType, String name) { if (isImageContentType(contentType) || isVideoContentType(contentType)) { return true; } + final mime = contentType.split(';').first.trim().toLowerCase(); + if (mime == 'text/plain') return true; return artifactKind(contentType, name) == ArtifactKind.document && isMarkdownArtifact(contentType, name); } diff --git a/app/lib/features/artifacts/domain/artifact_preview.dart b/app/lib/features/artifacts/domain/artifact_preview.dart new file mode 100644 index 00000000..f60b39ae --- /dev/null +++ b/app/lib/features/artifacts/domain/artifact_preview.dart @@ -0,0 +1,118 @@ +import 'artifact_kind.dart'; +import 'artifact_record.dart'; +import 'artifact_url.dart'; + +/// What the in-app viewer can do with one recorded artifact. +enum ArtifactPreviewKind { + image, + text, + markdown, + + /// A recorded file the viewer cannot draw (video, CSV, archives, ...). + unsupported, + + /// No safe same-origin url to fetch: absent, unsafe or another origin. + unavailable, +} + +/// One artifact's preview decision: the safe resolved url, the content kind and +/// the exact wording for a state that cannot be previewed. +/// +/// An external url is deliberately [ArtifactPreviewKind.unavailable]: the viewer +/// never fetches another origin, so a recorded url on a different host is marked +/// instead of being requested with the app's credentials. [canFetch] is the one +/// gate the viewer's fetch consults. +class ArtifactPreviewPlan { + const ArtifactPreviewPlan({ + required this.kind, + required this.resolved, + required this.message, + }); + + final ArtifactPreviewKind kind; + final ResolvedArtifactUrl? resolved; + + /// The explicit reason a non-previewable artifact is not drawn; empty for an + /// image, text or markdown document that may be fetched. + final String message; + + bool get canFetch => + resolved != null && + resolved!.external == false && + (kind == ArtifactPreviewKind.image || + kind == ArtifactPreviewKind.text || + kind == ArtifactPreviewKind.markdown); +} + +const String artifactPreviewNoUrl = 'No artifact URL recorded.'; +const String artifactPreviewUnsafeUrl = + 'The recorded artifact URL cannot be opened safely.'; +const String artifactPreviewExternalUrl = + 'This artifact is hosted on another origin and is not previewed here.'; + +/// Classifies [artifact] against the configured server origin. +/// +/// Images are drawn from the resolved bytes; `text/plain` is selectable text; a +/// `.md`/`.markdown` name or `text/markdown` is handed to the injected markdown +/// builder. Everything else is explicitly unsupported rather than faked. +ArtifactPreviewPlan planArtifactPreview({ + required ArtifactRecord artifact, + required String configuredEndpoint, +}) { + if (!artifact.hasUrl) { + return const ArtifactPreviewPlan( + kind: ArtifactPreviewKind.unavailable, + resolved: null, + message: artifactPreviewNoUrl, + ); + } + final resolved = resolveArtifactUrl(configuredEndpoint, artifact.url); + if (resolved == null) { + return const ArtifactPreviewPlan( + kind: ArtifactPreviewKind.unavailable, + resolved: null, + message: artifactPreviewUnsafeUrl, + ); + } + if (resolved.external) { + return ArtifactPreviewPlan( + kind: ArtifactPreviewKind.unavailable, + resolved: resolved, + message: artifactPreviewExternalUrl, + ); + } + final mime = artifact.contentType.split(';').first.trim().toLowerCase(); + if (isImageContentType(mime)) { + return ArtifactPreviewPlan( + kind: ArtifactPreviewKind.image, + resolved: resolved, + message: '', + ); + } + if (mime == 'text/markdown' || _isMarkdownName(artifact.name)) { + return ArtifactPreviewPlan( + kind: ArtifactPreviewKind.markdown, + resolved: resolved, + message: '', + ); + } + if (mime == 'text/plain') { + return ArtifactPreviewPlan( + kind: ArtifactPreviewKind.text, + resolved: resolved, + message: '', + ); + } + return ArtifactPreviewPlan( + kind: ArtifactPreviewKind.unsupported, + resolved: resolved, + message: 'This file type cannot be previewed here.', + ); +} + +bool _isMarkdownName(String name) { + final dot = name.lastIndexOf('.'); + if (dot == -1) return false; + final extension = name.substring(dot + 1).toLowerCase(); + return extension == 'md' || extension == 'markdown'; +} diff --git a/app/lib/features/artifacts/domain/gallery_navigation.dart b/app/lib/features/artifacts/domain/gallery_navigation.dart index ca115a73..a5d519a9 100644 --- a/app/lib/features/artifacts/domain/gallery_navigation.dart +++ b/app/lib/features/artifacts/domain/gallery_navigation.dart @@ -7,24 +7,34 @@ import 'artifact_record.dart'; /// a visit-scoped key so two url-less records never collapse into one page. class PagedArtifact { const PagedArtifact({ - required this.stageKey, - required this.visit, + required this.group, required this.artifact, required this.pageIndex, }); - final String stageKey; - final int visit; + final ArtifactGroup group; final ArtifactRecord artifact; /// Position in the filtered page list. final int pageIndex; + String get stageKey => group.stageKey; + int get visit => group.visit; + String get identity => artifact.hasUrl ? artifact.url : '$stageKey\u0000$visit\u0000$pageIndex\u0000${artifact.name}'; } +/// The gallery row identity of [artifact] inside [group], shared by the row +/// list and the viewer so selecting a row opens exactly that page. The recorded +/// visit is part of the key, so two visits that recorded the same name stay +/// distinct even when their recorded urls match. +String artifactVisitIdentityOf(ArtifactGroup group, ArtifactRecord artifact) { + final recorded = artifact.hasUrl ? artifact.url : artifact.name; + return '${group.stageKey}\u0000${group.visit}\u0000$recorded'; +} + /// The artifacts the viewer can page through, in gallery order: group by group, /// each group's images, videos and markdown/text documents in recorded order. /// Other artifacts open externally and are not part of this list. Pure: it only @@ -36,8 +46,7 @@ List pagedArtifacts(List groups) { if (!isViewerArtifact(artifact.contentType, artifact.name)) continue; pages.add( PagedArtifact( - stageKey: group.stageKey, - visit: group.visit, + group: group, artifact: artifact, pageIndex: pages.length, ), diff --git a/app/lib/features/artifacts/ui/artifact_gallery_page.dart b/app/lib/features/artifacts/ui/artifact_gallery_page.dart index 9cc12338..12c5617a 100644 --- a/app/lib/features/artifacts/ui/artifact_gallery_page.dart +++ b/app/lib/features/artifacts/ui/artifact_gallery_page.dart @@ -5,11 +5,15 @@ import 'package:flutter/services.dart'; import '../../../core/api_gateway.dart'; import '../../../ui/adaptive/host.dart'; import '../domain/artifact_groups.dart'; +import '../domain/artifact_kind.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_viewer_content.dart'; +import 'artifact_viewer_fetch.dart'; +import 'artifact_viewer_page.dart'; import 'artifact_visit_list.dart'; /// The gallery page title. @@ -18,10 +22,12 @@ 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. +/// stays two distinct selections. Selecting a viewer artifact with a resolved +/// url opens the native [ArtifactViewerPage] (an external origin is marked and +/// 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. It never downloads, shares or filters. class ArtifactGalleryPage extends StatefulWidget { const ArtifactGalleryPage({ super.key, @@ -29,12 +35,16 @@ class ArtifactGalleryPage extends StatefulWidget { this.executing = false, this.configuredEndpoint = '', this.openExternal = openArtifactExternally, + this.fetch = fetchArtifact, + this.markdownBuilder = defaultArtifactMarkdown, }); final List steps; final bool executing; final String configuredEndpoint; final ArtifactExternalOpen openExternal; + final ArtifactFetch fetch; + final ArtifactMarkdownBuilder markdownBuilder; @override State createState() => _ArtifactGalleryPageState(); @@ -44,22 +54,64 @@ class _ArtifactGalleryPageState extends State { late final Map _stepsByGroup = recordedStepsByGroup( widget.steps, ); + late final List _groups = artifactGroups(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)]; + Future _select(ArtifactGroup group, ArtifactRecord artifact) async { + final identity = artifactVisitIdentity(group, artifact); final resolved = artifact.hasUrl ? resolveArtifactUrl(widget.configuredEndpoint, artifact.url) : null; + setState(() { + _selectedIdentity = identity; + _status = null; + }); + if (resolved != null && + isViewerArtifact(artifact.contentType, artifact.name)) { + await _openViewer(identity); + return; + } + await _showSelected(group, artifact, resolved); + } + + Future _openViewer(String identity) async { + final previousFocus = FocusManager.instance.primaryFocus; + await Navigator.of(context).push( + usesCupertinoHost(context) + ? CupertinoPageRoute( + builder: (_) => ArtifactViewerPage( + groups: _groups, + selectedIdentity: identity, + configuredEndpoint: widget.configuredEndpoint, + openExternal: widget.openExternal, + fetch: widget.fetch, + markdownBuilder: widget.markdownBuilder, + ), + ) + : MaterialPageRoute( + builder: (_) => ArtifactViewerPage( + groups: _groups, + selectedIdentity: identity, + configuredEndpoint: widget.configuredEndpoint, + openExternal: widget.openExternal, + fetch: widget.fetch, + markdownBuilder: widget.markdownBuilder, + ), + ), + ); + if (!mounted) return; + if (previousFocus != null && previousFocus.canRequestFocus) { + previousFocus.requestFocus(); + } + } + + Future _showSelected( + ArtifactGroup group, + ArtifactRecord artifact, + ResolvedArtifactUrl? resolved, + ) { + final step = _stepsByGroup[artifactGroupKey(group.stageKey, group.visit)]; final facts = ArtifactSelectionFacts( group: group, artifact: artifact, @@ -149,7 +201,7 @@ class _ArtifactGalleryPageState extends State { @override Widget build(BuildContext context) { - final groups = artifactGroups(widget.steps); + final groups = _groups; final summary = widget.steps.isEmpty ? 'No steps recorded for this run.' : artifactsHeader(widget.steps, executing: widget.executing); diff --git a/app/lib/features/artifacts/ui/artifact_viewer_body.dart b/app/lib/features/artifacts/ui/artifact_viewer_body.dart new file mode 100644 index 00000000..e5ffdf1d --- /dev/null +++ b/app/lib/features/artifacts/ui/artifact_viewer_body.dart @@ -0,0 +1,210 @@ +import 'dart:typed_data'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../ui/adaptive/host.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'; + +/// One viewer page: the recorded facts, position, live status, preview surface, +/// 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. +class ArtifactViewerBody extends StatelessWidget { + const ArtifactViewerBody({ + super.key, + required this.page, + required this.plan, + required this.index, + required this.count, + required this.loading, + required this.markdownBuilder, + required this.onPrevious, + required this.onNext, + required this.onOpen, + required this.onCopy, + this.text, + this.bytes, + this.error, + this.status, + }); + + final PagedArtifact page; + final ArtifactPreviewPlan plan; + final int index; + final int count; + final bool loading; + final ArtifactMarkdownBuilder markdownBuilder; + final VoidCallback onPrevious; + final VoidCallback onNext; + final VoidCallback onOpen; + final VoidCallback onCopy; + final String? text; + final Uint8List? bytes; + final String? error; + final String? status; + + @override + Widget build(BuildContext context) { + 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, + ), + ), + ), + 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, + onPrevious: onPrevious, + onNext: onNext, + ), + ], + ); + } +} + +class _Actions extends StatelessWidget { + const _Actions({ + required this.resolved, + required this.onOpen, + required this.onCopy, + }); + + final ResolvedArtifactUrl resolved; + final VoidCallback onOpen; + final VoidCallback onCopy; + + @override + Widget build(BuildContext context) { + if (usesCupertinoHost(context)) { + return SafeArea( + top: false, + child: Wrap( + alignment: WrapAlignment.center, + spacing: 8, + children: [ + CupertinoButton(onPressed: onOpen, child: const Text('Open')), + CupertinoButton(onPressed: onCopy, child: const Text('Copy link')), + ], + ), + ); + } + return SafeArea( + top: false, + child: Wrap( + alignment: WrapAlignment.center, + spacing: 8, + children: [ + TextButton.icon( + onPressed: onOpen, + icon: const Icon(Icons.open_in_new), + label: const Text('Open'), + ), + TextButton.icon( + onPressed: onCopy, + icon: const Icon(Icons.content_copy), + label: const Text('Copy link'), + ), + ], + ), + ); + } +} + +class _Pager extends StatelessWidget { + const _Pager({ + required this.index, + required this.count, + required this.onPrevious, + required this.onNext, + }); + + final int index; + final int count; + final VoidCallback onPrevious; + final VoidCallback onNext; + + @override + Widget build(BuildContext context) { + if (count <= 1) return const SizedBox.shrink(); + final hasPrevious = pagedIndex(index, -1, count) != index; + final hasNext = pagedIndex(index, 1, count) != index; + if (usesCupertinoHost(context)) { + return SafeArea( + top: false, + child: Wrap( + alignment: WrapAlignment.spaceBetween, + children: [ + CupertinoButton( + onPressed: hasPrevious ? onPrevious : null, + child: const Text('Previous artifact'), + ), + CupertinoButton( + onPressed: hasNext ? onNext : null, + child: const Text('Next artifact'), + ), + ], + ), + ); + } + return SafeArea( + top: false, + child: Padding( + padding: const EdgeInsetsDirectional.fromSTEB(8, 0, 8, 4), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + TextButton.icon( + onPressed: hasPrevious ? onPrevious : null, + icon: const Icon(Icons.arrow_back), + label: const Text('Previous artifact'), + ), + TextButton.icon( + onPressed: hasNext ? onNext : null, + icon: const Icon(Icons.arrow_forward), + label: const Text('Next artifact'), + ), + ], + ), + ), + ); + } +} diff --git a/app/lib/features/artifacts/ui/artifact_viewer_content.dart b/app/lib/features/artifacts/ui/artifact_viewer_content.dart new file mode 100644 index 00000000..a191b8fb --- /dev/null +++ b/app/lib/features/artifacts/ui/artifact_viewer_content.dart @@ -0,0 +1,122 @@ +import 'dart:typed_data'; + +import 'package:flutter/material.dart'; + +import '../domain/artifact_preview.dart'; + +/// Renders fetched markdown text for the viewer. The gallery's default builder +/// returns plain selectable text, so the viewer is honest before the markdown +/// lane supplies a real renderer. +typedef ArtifactMarkdownBuilder = Widget Function(String text); + +Widget defaultArtifactMarkdown(String text) => SelectableText(text); + +/// The viewer's preview surface for one page. +/// +/// It draws only what was actually fetched: image bytes as an [Image], text as +/// selectable text, markdown through [markdownBuilder], and an explicit message +/// for unsupported/unavailable pages. It never substitutes a placeholder that +/// looks like a preview. +class ArtifactPreviewBody extends StatelessWidget { + const ArtifactPreviewBody({ + super.key, + required this.plan, + required this.loading, + required this.markdownBuilder, + this.text, + this.bytes, + this.error, + }); + + final ArtifactPreviewPlan plan; + final bool loading; + final ArtifactMarkdownBuilder markdownBuilder; + final String? text; + final Uint8List? bytes; + final String? error; + + @override + Widget build(BuildContext context) { + if (plan.kind == ArtifactPreviewKind.unavailable || + plan.kind == ArtifactPreviewKind.unsupported) { + return _Message(plan.message); + } + if (loading) { + return const _Loading(); + } + if (error != null) { + return _Message(error!); + } + switch (plan.kind) { + case ArtifactPreviewKind.image: + final data = bytes; + if (data == null) return const _Message('The image is empty.'); + return Center( + child: Image.memory( + data, + fit: BoxFit.contain, + errorBuilder: (_, _, _) => + const _Message('The image could not be decoded.'), + ), + ); + case ArtifactPreviewKind.text: + return _ScrollingText(child: SelectableText(text ?? '')); + case ArtifactPreviewKind.markdown: + return _ScrollingText(child: markdownBuilder(text ?? '')); + case ArtifactPreviewKind.unsupported: + case ArtifactPreviewKind.unavailable: + return const SizedBox.shrink(); + } + } +} + +class _Loading extends StatelessWidget { + const _Loading(); + + @override + Widget build(BuildContext context) { + return Center( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + const CircularProgressIndicator(), + const SizedBox(height: 12), + Text( + 'Loading preview…', + style: Theme.of(context).textTheme.bodyMedium, + ), + ], + ), + ); + } +} + +class _ScrollingText extends StatelessWidget { + const _ScrollingText({required this.child}); + + final Widget child; + + @override + Widget build(BuildContext context) { + return SingleChildScrollView( + padding: const EdgeInsetsDirectional.fromSTEB(16, 8, 16, 16), + child: child, + ); + } +} + +class _Message extends StatelessWidget { + const _Message(this.message); + + final String message; + + @override + Widget build(BuildContext context) { + return Center( + child: Padding( + padding: const EdgeInsets.all(16), + child: Text(message, textAlign: TextAlign.center), + ), + ); + } +} diff --git a/app/lib/features/artifacts/ui/artifact_viewer_fetch.dart b/app/lib/features/artifacts/ui/artifact_viewer_fetch.dart new file mode 100644 index 00000000..d757af45 --- /dev/null +++ b/app/lib/features/artifacts/ui/artifact_viewer_fetch.dart @@ -0,0 +1,35 @@ +import 'dart:typed_data'; + +import 'artifact_viewer_fetch_stub.dart' + if (dart.library.js_interop) 'artifact_viewer_fetch_web.dart' + as impl; + +/// One artifact fetch result: the status the server answered and the bytes. +class ArtifactFetchResult { + const ArtifactFetchResult({required this.status, required this.bytes}); + + final int status; + final Uint8List bytes; + + bool get ok => status >= 200 && status < 300; +} + +/// A fetch that did not reach an HTTP response (network, TLS, blocked, ...). +class ArtifactFetchException implements Exception { + const ArtifactFetchException(this.message); + + final String message; + + @override + String toString() => message; +} + +/// Fetches an already resolved same-origin artifact. +/// +/// The viewer only calls this for [planArtifactPreview]'s safe local urls; the +/// platform implementation sends no credentials to a different origin. +typedef ArtifactFetch = Future Function(Uri uri); + +/// The host fetch used when a caller does not inject one. Web uses `fetch` with +/// same-origin credentials; native uses an HttpClient with no stored cookies. +Future fetchArtifact(Uri uri) => impl.fetchArtifact(uri); diff --git a/app/lib/features/artifacts/ui/artifact_viewer_fetch_stub.dart b/app/lib/features/artifacts/ui/artifact_viewer_fetch_stub.dart new file mode 100644 index 00000000..8c1bb237 --- /dev/null +++ b/app/lib/features/artifacts/ui/artifact_viewer_fetch_stub.dart @@ -0,0 +1,29 @@ +import 'dart:io'; +import 'dart:typed_data'; + +import 'artifact_viewer_fetch.dart'; + +/// Native fetch for an already resolved same-origin artifact. +/// +/// No cookie jar, authorization header or userinfo is attached, redirects are +/// not followed across origins, and the caller only passes safe local urls. +Future fetchArtifact(Uri uri) async { + final client = HttpClient()..connectionTimeout = const Duration(seconds: 15); + try { + final request = await client.getUrl(uri); + request.followRedirects = false; + final response = await request.close(); + final bytes = BytesBuilder(copy: false); + await for (final chunk in response) { + bytes.add(chunk); + } + return ArtifactFetchResult( + status: response.statusCode, + bytes: bytes.takeBytes(), + ); + } on IOException catch (error) { + throw ArtifactFetchException('$error'); + } finally { + client.close(force: true); + } +} diff --git a/app/lib/features/artifacts/ui/artifact_viewer_fetch_web.dart b/app/lib/features/artifacts/ui/artifact_viewer_fetch_web.dart new file mode 100644 index 00000000..5cb2fb04 --- /dev/null +++ b/app/lib/features/artifacts/ui/artifact_viewer_fetch_web.dart @@ -0,0 +1,37 @@ +import 'dart:js_interop'; + +import 'artifact_viewer_fetch.dart'; + +@JS('fetch') +external JSPromise<_FetchResponse> _fetch(JSString input, _FetchInit init); + +extension type _FetchInit._(JSObject _) implements JSObject { + external factory _FetchInit({JSString credentials}); +} + +extension type _FetchResponse._(JSObject _) implements JSObject { + external int get status; + + external JSPromise arrayBuffer(); +} + +/// Web fetch for an already resolved same-origin artifact. +/// +/// `credentials: 'same-origin'` attaches the browser's credentials only to this +/// server's origin; the viewer never asks for another origin. The status is +/// returned verbatim so a failed preview can report the HTTP failure. +Future fetchArtifact(Uri uri) async { + try { + final response = await _fetch( + uri.toString().toJS, + _FetchInit(credentials: 'same-origin'.toJS), + ).toDart; + final buffer = await response.arrayBuffer().toDart; + return ArtifactFetchResult( + status: response.status, + bytes: buffer.toDart.asUint8List(), + ); + } catch (error) { + throw ArtifactFetchException('$error'); + } +} diff --git a/app/lib/features/artifacts/ui/artifact_viewer_page.dart b/app/lib/features/artifacts/ui/artifact_viewer_page.dart new file mode 100644 index 00000000..5673986f --- /dev/null +++ b/app/lib/features/artifacts/ui/artifact_viewer_page.dart @@ -0,0 +1,250 @@ +import 'dart:convert'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +import '../../../ui/adaptive/host.dart'; +import '../domain/artifact_groups.dart'; +import '../domain/artifact_preview.dart'; +import '../domain/artifact_url.dart'; +import '../domain/gallery_navigation.dart'; +import 'artifact_external_open.dart'; +import 'artifact_viewer_body.dart'; +import 'artifact_viewer_content.dart'; +import 'artifact_viewer_fetch.dart'; +import 'artifact_visit_list.dart'; + +/// The full-screen viewer's title, matching the web client's wording. +const String artifactViewerTitle = 'Artifact viewer'; + +/// One artifact of a recorded visit, previewed in-app. +/// +/// Images are drawn from bytes fetched from the already-resolved safe url, a +/// `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. +/// +/// Nothing is ever drawn for an external, unsafe or unsupported url: the viewer +/// reports the exact state instead. External urls are never fetched. +class ArtifactViewerPage extends StatefulWidget { + const ArtifactViewerPage({ + super.key, + required this.groups, + required this.selectedIdentity, + this.configuredEndpoint = '', + this.fetch = fetchArtifact, + this.markdownBuilder = defaultArtifactMarkdown, + this.openExternal = openArtifactExternally, + }); + + final List groups; + + /// [artifactVisitIdentityOf] of the row the operator selected. + final String selectedIdentity; + + final String configuredEndpoint; + final ArtifactFetch fetch; + final ArtifactMarkdownBuilder markdownBuilder; + final ArtifactExternalOpen openExternal; + + @override + State createState() => _ArtifactViewerPageState(); +} + +class _FetchedPreview { + const _FetchedPreview({this.text, this.bytes}); + + final String? text; + final Uint8List? bytes; +} + +class _ArtifactViewerPageState extends State { + late final List _pages = pagedArtifacts(widget.groups); + final Map _cache = {}; + late int _index = _initialIndex(); + int _generation = 0; + bool _loading = false; + String? _error; + _FetchedPreview? _fetched; + String? _status; + + int _initialIndex() { + final found = _pages.indexWhere( + (page) => + artifactVisitIdentityOf(page.group, page.artifact) == + widget.selectedIdentity, + ); + return found < 0 ? 0 : found; + } + + PagedArtifact? get _page => _index < _pages.length ? _pages[_index] : null; + + ArtifactPreviewPlan? get _plan { + final page = _page; + if (page == null) return null; + return planArtifactPreview( + artifact: page.artifact, + configuredEndpoint: widget.configuredEndpoint, + ); + } + + @override + void initState() { + super.initState(); + _beginLoad(initial: true); + } + + void _beginLoad({bool initial = false}) { + final generation = ++_generation; + final plan = _plan; + if (plan == null || !plan.canFetch) { + void clear() { + _loading = false; + _error = null; + _fetched = null; + } + + if (initial) { + clear(); + } else { + setState(clear); + } + return; + } + final key = plan.resolved!.url; + final cached = _cache[key]; + if (cached != null) { + void apply() { + _loading = false; + _error = null; + _fetched = cached; + } + + if (initial) { + apply(); + } else { + setState(apply); + } + return; + } + void start() { + _loading = true; + _error = null; + _fetched = null; + } + + if (initial) { + start(); + } else { + setState(start); + } + widget + .fetch(plan.resolved!.uri) + .then( + (result) { + if (!mounted || generation != _generation) return; + if (!result.ok) { + setState(() { + _loading = false; + _error = 'The server answered ${result.status}.'; + }); + return; + } + final fetched = _decode(plan.kind, result.bytes); + _cache[key] = fetched; + setState(() { + _loading = false; + _fetched = fetched; + }); + }, + onError: (Object error) { + if (!mounted || generation != _generation) return; + setState(() { + _loading = false; + _error = 'Could not load preview: $error'; + }); + }, + ); + } + + static _FetchedPreview _decode(ArtifactPreviewKind kind, Uint8List bytes) { + if (kind == ArtifactPreviewKind.image) { + return _FetchedPreview(bytes: bytes); + } + return _FetchedPreview(text: utf8.decode(bytes, allowMalformed: true)); + } + + void _step(int delta) { + final next = pagedIndex(_index, delta, _pages.length); + if (next == _index) return; + setState(() { + _index = next; + _status = null; + }); + _beginLoad(); + } + + Future _open(ResolvedArtifactUrl resolved) async { + final opened = await widget.openExternal(resolved.uri); + if (!mounted) return; + setState( + () => + _status = opened ? 'Link opened externally.' : 'Could not open link.', + ); + } + + Future _copy(ResolvedArtifactUrl resolved) async { + 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 page = _page; + final plan = _plan; + final title = page == null + ? artifactViewerTitle + : artifactDisplayName(page.artifact); + final body = page == null || plan == null + ? const Center(child: Text('No previewable artifacts recorded.')) + : ArtifactViewerBody( + page: page, + plan: plan, + index: _index, + count: _pages.length, + loading: _loading, + markdownBuilder: widget.markdownBuilder, + text: _fetched?.text, + bytes: _fetched?.bytes, + error: _error, + status: _status, + onPrevious: () => _step(-1), + onNext: () => _step(1), + onOpen: plan.resolved == null ? () {} : () => _open(plan.resolved!), + onCopy: plan.resolved == null ? () {} : () => _copy(plan.resolved!), + ); + if (usesCupertinoHost(context)) { + return CupertinoPageScaffold( + backgroundColor: CupertinoColors.systemGroupedBackground, + navigationBar: CupertinoNavigationBar( + middle: Text(title, overflow: TextOverflow.ellipsis), + ), + child: SafeArea(child: body), + ); + } + return Scaffold( + appBar: AppBar(title: Text(title, overflow: TextOverflow.ellipsis)), + body: SafeArea(top: false, child: body), + ); + } +} diff --git a/app/lib/features/artifacts/ui/artifact_visit_list.dart b/app/lib/features/artifacts/ui/artifact_visit_list.dart index 043e43a6..a134d250 100644 --- a/app/lib/features/artifacts/ui/artifact_visit_list.dart +++ b/app/lib/features/artifacts/ui/artifact_visit_list.dart @@ -5,6 +5,7 @@ import '../../../ui/adaptive/host.dart'; import '../domain/artifact_groups.dart'; import '../domain/artifact_kind.dart'; import '../domain/artifact_record.dart'; +import '../domain/gallery_navigation.dart'; /// A selection callback carrying the recorded group and the exact record the /// operator chose, so the visit is never lost when two groups share a name. @@ -17,10 +18,8 @@ typedef ArtifactSelected = /// The recorded stage visit is part of the key, so two visits that both /// recorded `result.csv` stay distinct even when their urls are identical. /// A filename alone is never an identity. -String artifactVisitIdentity(ArtifactGroup group, ArtifactRecord artifact) { - final recorded = artifact.hasUrl ? artifact.url : artifact.name; - return '${group.stageKey}\u0000${group.visit}\u0000$recorded'; -} +String artifactVisitIdentity(ArtifactGroup group, ArtifactRecord artifact) => + artifactVisitIdentityOf(group, artifact); /// The recorded group heading, matching the web client's group vocabulary. String artifactGroupLabel(ArtifactGroup group) => diff --git a/app/notes/A1-viewer.md b/app/notes/A1-viewer.md new file mode 100644 index 00000000..668a1be9 --- /dev/null +++ b/app/notes/A1-viewer.md @@ -0,0 +1,87 @@ +# A1-viewer — native in-app artifact viewer + +## What changed + +The recorded-artifact gallery now opens a reusable native viewer for a viewer +artifact with a resolved url. Images are drawn in-app from fetched bytes, +`text/plain` is selectable fetched text, `.md`/`.markdown` or `text/markdown` +uses an injected markdown builder (default: plain selectable text), and every +other type shows an explicit cannot-preview state with the existing Open/Copy +link actions. An external origin is opened in the viewer as a marked, +unfetched page; unsafe and absent urls stay in the facts dialog. + +| File | Responsibility | +| --- | --- | +| `lib/features/artifacts/domain/artifact_preview.dart` | Safe-url preview classification and exact unavailable/unsupported wording | +| `lib/features/artifacts/ui/artifact_viewer_page.dart` | Page, paging state, fetch generations, cache, Open/Copy | +| `lib/features/artifacts/ui/artifact_viewer_body.dart` | Facts, position, live status, preview surface, actions, Previous/Next | +| `lib/features/artifacts/ui/artifact_viewer_content.dart` | Image/text/markdown/loading/error/unsupported surface and markdown seam | +| `lib/features/artifacts/ui/artifact_viewer_fetch.dart` | `ArtifactFetch` seam, status/bytes result, network failure | +| `lib/features/artifacts/ui/artifact_viewer_fetch_web.dart` | Web `fetch` with `credentials: 'same-origin'` | +| `lib/features/artifacts/ui/artifact_viewer_fetch_stub.dart` | Native `HttpClient`, no cookies, no redirects | +| `lib/features/artifacts/ui/artifact_gallery_page.dart` | Opens the viewer for previewable same-origin rows; optional fetch/builder seams | +| `lib/features/artifacts/domain/artifact_kind.dart` | `text/plain` joins the viewer list; video stays pageable but unpresentable | +| `lib/features/artifacts/domain/gallery_navigation.dart` | One visit identity helper shared by rows and viewer | +| `tool/artifact_gallery_probe.dart` / `.mjs` | Gallery + viewer fixture, both hosts, 320/2x, real PNG, 404 and external states | +| `test/features/artifacts/domain/artifact_preview_test.dart` | Same-origin, external, unsafe, absent and unsupported plans | +| `test/features/artifacts/ui/artifact_viewer_page_test.dart` | Image no-tab, text content, markdown seam, external refusal, unsupported, paging/clamp, loading/404/network, Cupertino | + +## Behaviour + +- The gallery row identity is the recorded stage/visit plus recorded url (or + name), so paging starts on exactly the selected row. +- Preview pages are `pagedArtifacts(groups)` in gallery order. Previous/Next use + `pagedIndex` and are disabled at both ends; a one-page viewer has no pager. +- The viewer keeps the recorded MIME/size and `stage · visit N` facts visible on + every page, along with the position label (`3 of 4 · image/png`). +- Open/Copy link are the existing external actions and operate on the resolved + url. They are not previews. +- Fetch failures report `The server answered .`; network failures report + `Could not load preview: …`; loading says `Loading preview…`. An image that + cannot decode says so. +- Native `Back`/AppBar/CupertinoNavigationBar close returns to the gallery row + list and restores the row focus captured before the push. + +## Checks actually run + +``` +flutter analyze # No issues found! (1.2s) +flutter test test/features/artifacts \ + test/features/runs/ui/run_artifacts_action_test.dart # 104 passed +flutter build web # ✓ Built build/web +flutter build web -t tool/artifact_gallery_probe.dart # ✓ Built build/probe-gallery +node tool/artifact_gallery_probe.mjs --root build/probe-gallery --out … # 21 checks, 23 captures +``` + +Browser captures: shared +`artifact-viewer-captures/` (material/cupertino image, text, unsupported, +HTTP 404, external marked page, 320/2x both hosts, plus the retained gallery +states). The viewer text assertion for fetched content relies on the rendered +capture; Flutter web did not expose `SelectableText` content in the extracted +DOM text. The widget test asserts the fetched value directly. + +## Honest limits + +- No HTML embed, video player, download or file-share action was added. +- Only web was built and captured. Android/iOS were not built, installed or + device-tested. +- The default markdown seam is plain selectable text; the markdown lane can + inject a real renderer through `ArtifactMarkdownBuilder`. +- The fixture and browser evidence use loopback files only; no server, real run + or operator session was touched. + +## Manager completion after a harness transport deadline + +The Code visit ended with `HARNESS TRANSPORT: context deadline exceeded`; the +session was no longer active and every edit was retained. No retry was started. +The manager ran the full artifacts suite (99 tests pass) and analysis, rebuilt the +gallery/viewer fixture, and ran the probe: it passes and writes the viewer states +(text, image, unsupported, external-origin marked, HTTP error, plus 320/2x and +Cupertino variants). The Material text viewer and the Cupertino 320/2x image +viewer were inspected: recorded facts, page position, in-app image, paging at both +ends and Open/Copy link. + +Deliberate limits: markdown is rendered through an injected builder that defaults +to selectable plain text (the markdown lane supplies the real renderer later), +external-origin urls are never fetched, and video/CSV/archives are explicitly +unsupported rather than faked. Share/download/file-upload remain open items. diff --git a/app/test/features/artifacts/domain/artifact_kind_test.dart b/app/test/features/artifacts/domain/artifact_kind_test.dart index a95ccfab..98ffb2eb 100644 --- a/app/test/features/artifacts/domain/artifact_kind_test.dart +++ b/app/test/features/artifacts/domain/artifact_kind_test.dart @@ -91,6 +91,7 @@ void main() { ('video/mp4', 'clip.mp4'), ('text/markdown', 'input.md'), ('text/plain', 'memory.txt'), + ('text/plain', 'run.log'), ('', 'output.md'), ]) { expect(isViewerArtifact(contentType, name), isTrue, reason: name); @@ -100,7 +101,6 @@ void main() { ('text/csv', 'rows.csv'), ('application/json', 'payload.json'), ('text/x-python', 'main.py'), - ('text/plain', 'run.log'), ('application/octet-stream', 'blob.bin'), ('', ''), ]) { diff --git a/app/test/features/artifacts/domain/artifact_preview_test.dart b/app/test/features/artifacts/domain/artifact_preview_test.dart new file mode 100644 index 00000000..10f62055 --- /dev/null +++ b/app/test/features/artifacts/domain/artifact_preview_test.dart @@ -0,0 +1,99 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/artifacts/domain/artifact_preview.dart'; +import 'package:pipelines_app/features/artifacts/domain/artifact_record.dart'; + +import 'artifact_fixtures.dart'; + +const _endpoint = 'ws://127.0.0.1:8081/connect'; + +ArtifactRecord _record(String name, {String? url, String contentType = ''}) => + ArtifactRecord.fromJson(artifact(name, url: url, contentType: contentType)); + +ArtifactPreviewPlan _plan( + ArtifactRecord artifact, { + String endpoint = _endpoint, +}) => planArtifactPreview(artifact: artifact, configuredEndpoint: endpoint); + +void main() { + test('an image on the configured origin is fetched locally', () { + final plan = _plan(_record('shot.png', contentType: 'image/png')); + expect(plan.kind, ArtifactPreviewKind.image); + expect(plan.canFetch, isTrue); + expect(plan.resolved?.url, 'http://127.0.0.1:8081/artifacts/1/1/shot.png'); + expect(plan.message, isEmpty); + }); + + test('text/plain and markdown are selectable text plans', () { + expect( + _plan(_record('build.log', contentType: 'text/plain')).kind, + ArtifactPreviewKind.text, + ); + expect( + _plan(_record('notes.txt', contentType: 'text/plain')).kind, + ArtifactPreviewKind.text, + ); + expect( + _plan(_record('notes.md', contentType: 'text/markdown')).kind, + ArtifactPreviewKind.markdown, + ); + expect( + _plan( + _record('notes.markdown', contentType: 'application/octet-stream'), + ).kind, + ArtifactPreviewKind.markdown, + ); + }); + + test('an external origin is marked and never fetchable', () { + final plan = _plan( + _record( + 'shot.png', + url: 'https://elsewhere.test/shot.png', + contentType: 'image/png', + ), + ); + expect(plan.kind, ArtifactPreviewKind.unavailable); + expect(plan.canFetch, isFalse); + expect(plan.message, artifactPreviewExternalUrl); + expect(plan.resolved?.url, 'https://elsewhere.test/shot.png'); + }); + + test('unsafe and absent urls are explicit and never fetchable', () { + final unsafe = _plan( + _record( + 'shot.png', + url: '//evil.test/shot.png', + contentType: 'image/png', + ), + ); + expect(unsafe.kind, ArtifactPreviewKind.unavailable); + expect(unsafe.canFetch, isFalse); + expect(unsafe.message, artifactPreviewUnsafeUrl); + + final absent = _plan( + ArtifactRecord.fromJson({ + 'name': 'shot.png', + 'url': '', + 'content_type': 'image/png', + 'size_bytes': 1, + }), + ); + expect(absent.kind, ArtifactPreviewKind.unavailable); + expect(absent.canFetch, isFalse); + expect(absent.message, artifactPreviewNoUrl); + }); + + test('unsupported types are explicit instead of a fake preview', () { + for (final record in [ + _record('result.csv', contentType: 'text/csv'), + _record('clip.mp4', contentType: 'video/mp4'), + _record('bundle.zip', contentType: 'application/zip'), + ]) { + final plan = _plan(record); + expect(plan.kind, ArtifactPreviewKind.unsupported); + expect(plan.canFetch, isFalse); + expect(plan.message, 'This file type cannot be previewed here.'); + expect(plan.resolved, isNotNull); + } + }); +} diff --git a/app/test/features/artifacts/domain/gallery_navigation_test.dart b/app/test/features/artifacts/domain/gallery_navigation_test.dart index af8b72ed..d642dba1 100644 --- a/app/test/features/artifacts/domain/gallery_navigation_test.dart +++ b/app/test/features/artifacts/domain/gallery_navigation_test.dart @@ -37,6 +37,7 @@ void main() { expect(pagedArtifacts(groups).map((page) => page.artifact.name), [ 'input.md', + 'run.log', 'shot.png', 'clip.mp4', 'memory.txt', @@ -161,7 +162,7 @@ void main() { artifacts: >[ artifact('session.html', contentType: 'text/html'), artifact('main.py', contentType: 'text/x-python'), - artifact('run.log', contentType: 'text/plain'), + artifact('result.csv', contentType: 'text/csv'), ], ), ]); diff --git a/app/test/features/artifacts/ui/artifact_viewer_page_test.dart b/app/test/features/artifacts/ui/artifact_viewer_page_test.dart new file mode 100644 index 00000000..6dd7e450 --- /dev/null +++ b/app/test/features/artifacts/ui/artifact_viewer_page_test.dart @@ -0,0 +1,406 @@ +import 'dart:async'; +import 'dart:convert'; +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/domain/artifact_groups.dart'; +import 'package:pipelines_app/features/artifacts/domain/artifact_record.dart'; +import 'package:pipelines_app/features/artifacts/ui/artifact_external_open.dart'; +import 'package:pipelines_app/features/artifacts/ui/artifact_gallery_page.dart'; +import 'package:pipelines_app/features/artifacts/ui/artifact_viewer_fetch.dart'; +import 'package:pipelines_app/features/artifacts/ui/artifact_viewer_page.dart'; +import 'package:pipelines_app/features/artifacts/ui/artifact_visit_list.dart'; + +import '../domain/artifact_fixtures.dart'; +import 'artifact_visit_list_fixture.dart'; + +const _endpoint = 'ws://127.0.0.1:8081/connect'; + +/// A real 1x1 PNG so the image preview decodes instead of only holding bytes. +final Uint8List _png = base64Decode( + 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAE' + 'hQGAhKmMIQAAAABJRU5ErkJggg==', +); + +ArtifactGroup _group( + List artifacts, { + String stageKey = 'review', + int visit = 1, +}) => visitGroup(stageKey: stageKey, visit: visit, artifacts: artifacts); + +Future _pumpViewer( + WidgetTester tester, { + required List groups, + required String selected, + bool cupertino = false, + ArtifactFetch? fetch, + Widget Function(String)? markdownBuilder, + ArtifactExternalOpen? openExternal, +}) async { + final page = ArtifactViewerPage( + groups: groups, + selectedIdentity: selected, + configuredEndpoint: _endpoint, + fetch: fetch ?? (_) async => ArtifactFetchResult(status: 200, bytes: _png), + markdownBuilder: markdownBuilder ?? (value) => SelectableText(value), + openExternal: openExternal ?? (_) async => true, + ); + await tester.pumpWidget( + cupertino + ? CupertinoApp(home: page) + : MaterialApp(home: Scaffold(body: page)), + ); + await tester.pumpAndSettle(); +} + +TextButton _textButton(WidgetTester tester, String label) { + return tester.widget( + find + .ancestor(of: find.text(label), matching: find.byType(TextButton)) + .first, + ); +} + +void main() { + testWidgets('an image is previewed in-app without opening a tab', ( + tester, + ) async { + final fetched = []; + final opened = []; + await tester.pumpWidget( + MaterialApp( + home: ArtifactGalleryPage( + steps: [ + step( + stage: 'review', + visit: 1, + artifacts: [ + artifact( + 'shot.png', + url: '/artifacts/1/1/shot.png', + contentType: 'image/png', + sizeBytes: 1024, + ), + ], + ), + ], + configuredEndpoint: _endpoint, + fetch: (uri) async { + fetched.add(uri); + return ArtifactFetchResult(status: 200, bytes: _png); + }, + openExternal: (uri) async { + opened.add(uri); + return true; + }, + ), + ), + ); + await tester.pumpAndSettle(); + await tester.tap(find.text('shot.png')); + await tester.pumpAndSettle(); + + expect(find.byType(ArtifactViewerPage), findsOneWidget); + expect(fetched, [ + Uri.parse('http://127.0.0.1:8081/artifacts/1/1/shot.png'), + ]); + expect(find.byType(Image), findsOneWidget); + expect(find.text('1 of 1 · image/png'), findsOneWidget); + expect(find.text('image/png · 1.0\u00a0KiB'), findsOneWidget); + expect(opened, isEmpty); + expect(find.byType(AlertDialog), findsNothing); + }); + + testWidgets('text/plain is fetched and shown as selectable text', ( + tester, + ) async { + final text = recordedArtifact( + 'build.log', + url: '/artifacts/1/1/build.log', + contentType: 'text/plain; charset=utf-8', + ); + await _pumpViewer( + tester, + groups: [ + _group([text]), + ], + selected: artifactVisitIdentity(_group([text]), text), + fetch: (_) async => + ArtifactFetchResult(status: 200, bytes: utf8.encode('build ok\n')), + ); + + expect(find.byType(SelectableText), findsOneWidget); + expect(find.text('build ok\n'), findsOneWidget); + expect(find.text('text/plain · 0\u00a0B'), findsOneWidget); + }); + + testWidgets('markdown uses the injected builder and defaults to text', ( + tester, + ) async { + final markdown = recordedArtifact( + 'notes.md', + url: '/artifacts/1/1/notes.md', + contentType: 'text/markdown', + ); + final group = _group([markdown]); + final identity = artifactVisitIdentity(group, markdown); + await _pumpViewer( + tester, + groups: [group], + selected: identity, + fetch: (_) async => + ArtifactFetchResult(status: 200, bytes: utf8.encode('# Title')), + markdownBuilder: (value) => Text('MARKDOWN $value'), + ); + expect(find.text('MARKDOWN # Title'), findsOneWidget); + + await tester.pumpWidget(const SizedBox()); + await _pumpViewer( + tester, + groups: [group], + selected: identity, + fetch: (_) async => + ArtifactFetchResult(status: 200, bytes: utf8.encode('# Raw title')), + ); + expect(find.byType(SelectableText), findsOneWidget); + expect(find.text('# Raw title'), findsOneWidget); + }); + + testWidgets('an external origin is marked and never fetched', (tester) async { + final fetched = []; + final opened = []; + final image = recordedArtifact( + 'shot.png', + url: 'https://elsewhere.test/shot.png', + contentType: 'image/png', + ); + final group = _group([image]); + await _pumpViewer( + tester, + groups: [group], + selected: artifactVisitIdentity(group, image), + fetch: (uri) async { + fetched.add(uri); + return ArtifactFetchResult(status: 200, bytes: _png); + }, + openExternal: (uri) async { + opened.add(uri); + return true; + }, + ); + + expect( + find.text( + 'This artifact is hosted on another origin and is not previewed here.', + ), + findsOneWidget, + ); + expect(fetched, isEmpty); + expect(find.byType(Image), findsNothing); + await tester.tap(find.text('Open')); + await tester.pumpAndSettle(); + expect(opened, [Uri.parse('https://elsewhere.test/shot.png')]); + }); + + testWidgets('the gallery marks an external viewer artifact without fetching', ( + tester, + ) async { + final fetched = []; + await tester.pumpWidget( + MaterialApp( + home: ArtifactGalleryPage( + steps: [ + step( + stage: 'review', + visit: 1, + artifacts: [ + artifact( + 'shot.png', + url: 'https://elsewhere.test/shot.png', + contentType: 'image/png', + sizeBytes: 10, + ), + ], + ), + ], + configuredEndpoint: _endpoint, + fetch: (uri) async { + fetched.add(uri); + return ArtifactFetchResult(status: 200, bytes: _png); + }, + openExternal: (_) async => true, + ), + ), + ); + await tester.pumpAndSettle(); + await tester.tap(find.text('shot.png')); + await tester.pumpAndSettle(); + + expect(find.byType(ArtifactViewerPage), findsOneWidget); + expect( + find.text( + 'This artifact is hosted on another origin and is not previewed here.', + ), + findsOneWidget, + ); + expect(fetched, isEmpty); + expect(find.byType(Image), findsNothing); + }); + + testWidgets('an unsupported type is explicit, with Open and Copy link', ( + tester, + ) async { + final video = recordedArtifact( + 'clip.mp4', + url: '/artifacts/1/1/clip.mp4', + contentType: 'video/mp4', + ); + final group = _group([video]); + var fetches = 0; + await _pumpViewer( + tester, + groups: [group], + selected: artifactVisitIdentity(group, video), + fetch: (_) async { + fetches += 1; + return ArtifactFetchResult(status: 200, bytes: _png); + }, + ); + + expect( + find.text('This file type cannot be previewed here.'), + findsOneWidget, + ); + expect(find.text('Open'), findsOneWidget); + expect(find.text('Copy link'), findsOneWidget); + expect(fetches, 0); + expect(find.byType(Image), findsNothing); + }); + + testWidgets('paging clamps at both ends and keeps the visit facts', ( + tester, + ) async { + final first = recordedArtifact( + 'a.png', + url: '/artifacts/1/1/a.png', + contentType: 'image/png', + ); + final second = recordedArtifact( + 'b.png', + url: '/artifacts/1/2/b.png', + contentType: 'image/png', + ); + final third = recordedArtifact( + 'c.png', + url: '/artifacts/1/3/c.png', + contentType: 'image/png', + ); + final groups = [ + _group([first], visit: 1), + _group([second], visit: 2), + _group([third], visit: 3), + ]; + await _pumpViewer( + tester, + groups: groups, + selected: artifactVisitIdentity(groups[0], first), + ); + + expect(find.text('1 of 3 · image/png'), findsOneWidget); + expect(_textButton(tester, 'Previous artifact').onPressed, isNull); + expect(_textButton(tester, 'Next artifact').onPressed, isNotNull); + + await tester.tap(find.text('Next artifact')); + await tester.pumpAndSettle(); + expect(find.text('2 of 3 · image/png'), findsOneWidget); + expect(find.text('review · visit 2'), findsOneWidget); + expect(_textButton(tester, 'Previous artifact').onPressed, isNotNull); + + await tester.tap(find.text('Next artifact')); + await tester.pumpAndSettle(); + expect(find.text('3 of 3 · image/png'), findsOneWidget); + expect(_textButton(tester, 'Next artifact').onPressed, isNull); + await tester.tap(find.text('Next artifact')); + await tester.pumpAndSettle(); + expect(find.text('3 of 3 · image/png'), findsOneWidget); + + await tester.tap(find.text('Previous artifact')); + await tester.pumpAndSettle(); + expect(find.text('2 of 3 · image/png'), findsOneWidget); + }); + + testWidgets('loading and HTTP failure are honest', (tester) async { + final text = recordedArtifact( + 'notes.txt', + url: '/artifacts/1/1/notes.txt', + contentType: 'text/plain', + ); + final group = _group([text]); + final pending = Completer(); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: ArtifactViewerPage( + groups: [group], + selectedIdentity: artifactVisitIdentity(group, text), + configuredEndpoint: _endpoint, + fetch: (_) => pending.future, + openExternal: (_) async => true, + ), + ), + ), + ); + await tester.pump(); + expect(find.text('Loading preview…'), findsOneWidget); + + pending.complete(ArtifactFetchResult(status: 404, bytes: Uint8List(0))); + await tester.pumpAndSettle(); + expect(find.text('The server answered 404.'), findsOneWidget); + expect(find.byType(SelectableText), findsNothing); + }); + + testWidgets('a network failure is reported instead of an empty preview', ( + tester, + ) async { + final text = recordedArtifact( + 'notes.txt', + url: '/artifacts/1/1/notes.txt', + contentType: 'text/plain', + ); + final group = _group([text]); + await _pumpViewer( + tester, + groups: [group], + selected: artifactVisitIdentity(group, text), + fetch: (_) async => throw const ArtifactFetchException('network down'), + ); + expect(find.textContaining('Could not load preview'), findsOneWidget); + expect(find.textContaining('network down'), findsOneWidget); + }); + + testWidgets('Cupertino draws the same text preview and controls', ( + tester, + ) async { + final text = recordedArtifact( + 'notes.txt', + url: '/artifacts/1/1/notes.txt', + contentType: 'text/plain', + ); + final group = _group([text]); + await _pumpViewer( + tester, + cupertino: true, + groups: [group], + selected: artifactVisitIdentity(group, text), + fetch: (_) async => ArtifactFetchResult( + status: 200, + bytes: utf8.encode('cupertino text'), + ), + ); + expect(find.text('cupertino text'), findsOneWidget); + expect(find.byType(CupertinoButton), findsWidgets); + }); +} diff --git a/app/tool/artifact_gallery_probe.dart b/app/tool/artifact_gallery_probe.dart index fdaad138..3190fa10 100644 --- a/app/tool/artifact_gallery_probe.dart +++ b/app/tool/artifact_gallery_probe.dart @@ -11,6 +11,7 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/artifacts/ui/artifact_gallery_page.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'; @@ -84,6 +85,42 @@ List _steps(String origin, String state) { }, ]; } + if (state == 'missing') { + return [ + { + 'stage': 'reviewer', + 'sequence': 1, + 'status': 'completed', + 'control': {'visit': 1}, + 'artifacts': [ + _file( + 'missing.png', + url: '$origin/fixture/missing.png', + contentType: 'image/png', + sizeBytes: 128, + ), + ], + }, + ]; + } + if (state == 'external') { + return [ + { + 'stage': 'reviewer', + 'sequence': 1, + 'status': 'completed', + 'control': {'visit': 1}, + 'artifacts': [ + _file( + 'elsewhere.png', + url: 'https://elsewhere.test/elsewhere.png', + contentType: 'image/png', + sizeBytes: 4096, + ), + ], + }, + ]; + } return [ { 'stage': 'implementer', @@ -97,6 +134,12 @@ List _steps(String origin, String state) { contentType: 'text/plain; charset=utf-8', sizeBytes: 2337, ), + _file( + 'notes.txt', + url: '$origin/fixture/notes.txt', + contentType: 'text/plain', + sizeBytes: 2337, + ), ], }, { @@ -117,6 +160,12 @@ List _steps(String origin, String state) { contentType: 'image/png', sizeBytes: 80544, ), + _file( + 'clip.mp4', + url: '$origin/fixture/clip.mp4', + contentType: 'video/mp4', + sizeBytes: 40544, + ), ], }, { @@ -151,9 +200,24 @@ void main() { final theme = params['theme'] == 'dark' ? Brightness.dark : Brightness.light; final origin = params['origin'] ?? 'https://artifacts.invalid'; final state = params['state'] ?? 'default'; + final gallery = params['view'] == 'gallery'; + final originUrl = Uri.tryParse(origin); + final endpoint = originUrl == null + ? '' + : originUrl + .replace( + scheme: originUrl.scheme == 'https' ? 'wss' : 'ws', + path: '/connect', + query: null, + ) + .toString(); // 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)); + final body = _ProbeBody( + run: _run(origin, state), + gallery: gallery, + endpoint: endpoint, + ); Widget scaled(BuildContext context, Widget? app) => MediaQuery( data: MediaQuery.of( context, @@ -185,9 +249,15 @@ void main() { } class _ProbeBody extends StatefulWidget { - const _ProbeBody({required this.run}); + const _ProbeBody({ + required this.run, + required this.gallery, + required this.endpoint, + }); final JsonMap run; + final bool gallery; + final String endpoint; @override State<_ProbeBody> createState() => _ProbeBodyState(); @@ -213,6 +283,13 @@ class _ProbeBodyState extends State<_ProbeBody> { @override Widget build(BuildContext context) { + if (widget.gallery) { + final steps = (widget.run['steps'] as List).cast(); + return ArtifactGalleryPage( + steps: steps, + configuredEndpoint: widget.endpoint, + ); + } final detail = RunDetailView( controller: _controller, gateway: _gateway, diff --git a/app/tool/artifact_gallery_probe.mjs b/app/tool/artifact_gallery_probe.mjs index b57ff4a4..d0e42c4a 100644 --- a/app/tool/artifact_gallery_probe.mjs +++ b/app/tool/artifact_gallery_probe.mjs @@ -15,6 +15,7 @@ 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'; +import zlib from 'node:zlib'; const args = new Map(); for (let i = 2; i < process.argv.length; i++) { @@ -44,9 +45,66 @@ const mime = { '.frag': 'application/octet-stream', }; +const crcTable = Array.from({ length: 256 }, (_, n) => { + let c = n; + for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; + return c >>> 0; +}); +const crc32 = (buffer) => { + let c = 0xffffffff; + for (const byte of buffer) c = crcTable[(c ^ byte) & 0xff] ^ (c >>> 8); + return (c ^ 0xffffffff) >>> 0; +}; +const pngChunk = (type, data) => { + const length = Buffer.alloc(4); + length.writeUInt32BE(data.length); + const body = Buffer.concat([Buffer.from(type), data]); + const crc = Buffer.alloc(4); + crc.writeUInt32BE(crc32(body)); + return Buffer.concat([length, body, crc]); +}; +// A real 160x100 gradient, so the preview evidence shows an actual image +// rather than a one-pixel probe. +const probePng = () => { + const width = 160; + const height = 100; + const rows = Buffer.alloc(height * (width * 3 + 1)); + for (let y = 0; y < height; y++) { + const offset = y * (width * 3 + 1); + rows[offset] = 0; + for (let x = 0; x < width; x++) { + rows[offset + 1 + x * 3] = 40 + Math.trunc((x * 120) / width); + rows[offset + 2 + x * 3] = 90 + Math.trunc((y * 130) / height); + rows[offset + 3 + x * 3] = 200 - Math.trunc((x * 80) / width); + } + } + const header = Buffer.alloc(13); + header.writeUInt32BE(width, 0); + header.writeUInt32BE(height, 4); + header[8] = 8; + header[9] = 2; + return Buffer.concat([ + Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), + pngChunk('IHDR', header), + pngChunk('IDAT', zlib.deflateSync(rows, { level: 9 })), + pngChunk('IEND', Buffer.alloc(0)), + ]); +}; +const png = probePng(); + const server = createServer(async (req, res) => { const pathname = decodeURIComponent(new URL(req.url, 'http://localhost').pathname); if (pathname.startsWith('/fixture/')) { + if (pathname.endsWith('/missing.png')) { + res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' }); + res.end('missing artifact\n'); + return; + } + if (pathname.endsWith('.png')) { + res.writeHead(200, { 'content-type': 'image/png' }); + res.end(png); + return; + } res.writeHead(200, { 'content-type': 'text/plain; charset=utf-8' }); res.end(`recorded artifact ${pathname}\n`); return; @@ -143,6 +201,7 @@ try { "[...document.querySelectorAll('flt-semantics')].map(x => x.getAttribute('aria-label') || (x.innerText || '').trim()).filter(Boolean)", ); const bodyText = () => evaluate('document.body.innerText'); + const visibleText = async () => `${await bodyText()}\n${(await labels()).join('\n')}`; const hasLabel = async (label) => (await labels()).includes(label); const clickExact = async (label) => { const clicked = await evaluate(`(() => { @@ -178,20 +237,24 @@ try { if (!clicked) throw new Error(`No tappable label starting ${JSON.stringify(prefix)}: ${JSON.stringify(await labels())}`); await delay(600); }; - const activate = async () => { + const activate = async (expected = 'Artifacts gallery probe') => { 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'))) { + if (expected !== null && !current.some((label) => label.includes(expected))) { throw new Error(`Flutter semantics unavailable: ${JSON.stringify(current)}`); } }; - const navigate = async (url) => { + const navigate = async (url, expected = 'Artifacts gallery probe') => { const navigation = await send('Page.navigate', { url }, session); if (navigation.error || navigation.result?.errorText) throw new Error(JSON.stringify(navigation)); - await activate(); + await activate(expected); }; + const targetCount = async () => + (await send('Target.getTargets')).result.targetInfos.filter( + (target) => target.type === 'page', + ).length; const capture = async (name, width = 390, height = 844, scale = 1) => { await send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: scale, mobile: width < 600, @@ -259,7 +322,7 @@ try { throw new Error(`Gallery is missing recorded row ${recorded}: ${JSON.stringify(galleryBody)}`); } } - if (!galleryBody.includes('Artifacts · 4 recorded')) { + if (!galleryBody.includes('Artifacts · 6 recorded')) { throw new Error(`Gallery summary missing: ${JSON.stringify(galleryBody)}`); } const resultRows = (await labels()).filter((label) => label.startsWith('result.csv')).length; @@ -343,6 +406,122 @@ try { evidence.checks.push({ check: 'an unavailable capture is never reported as empty', value: true }); await capture('a1w-material-unavailable'); + // In-app artifact viewer: image, text, unsupported, paging, back and HTTP + // failure. The fixture serves same-origin artifact urls on this loopback + // origin, so the viewer is allowed to fetch them; no browser tab may open. + const galleryView = (extra = '', platform = 'material') => + `${origin}/?view=gallery&platform=${platform}&origin=${encodeURIComponent(origin)}${extra}`; + const beforeViewerTargets = await targetCount(); + await navigate(galleryView(), 'Artifacts'); + await clickLowestPrefix('shot.png'); + await delay(700); + const imageBody = await bodyText(); + for (const fact of [ + 'shot.png', + 'image/png · 78.7\u00a0KiB', + '3 of 4 · image/png', + 'reviewer · visit 1', + ]) { + if (!imageBody.includes(fact)) { + throw new Error(`Image preview missing ${fact}: ${JSON.stringify(imageBody)}`); + } + } + if (!(await hasLabel('Previous artifact')) || !(await hasLabel('Next artifact'))) { + throw new Error(`Viewer has no paging controls: ${JSON.stringify(await labels())}`); + } + const afterViewerTargets = await targetCount(); + if (afterViewerTargets !== beforeViewerTargets) { + throw new Error(`Image preview opened a browser tab: ${beforeViewerTargets} -> ${afterViewerTargets}`); + } + evidence.checks.push({ + check: 'an image is previewed in-app from the same-origin url without a new tab', + value: true, + targets: afterViewerTargets, + }); + await capture('a1w-viewer-image'); + + await clickExact('Next artifact'); + const videoBody = await bodyText(); + if (!videoBody.includes('4 of 4 · video/mp4')) { + throw new Error(`Viewer did not page to the video: ${JSON.stringify(videoBody)}`); + } + if (!videoBody.includes('This file type cannot be previewed here.')) { + throw new Error(`Video was not marked unpresentable: ${JSON.stringify(videoBody)}`); + } + if (!(await hasLabel('Open')) || !(await hasLabel('Copy link'))) { + throw new Error(`Unsupported page lost its actions: ${JSON.stringify(await labels())}`); + } + await clickExact('Next artifact'); + if (!(await bodyText()).includes('4 of 4 · video/mp4')) { + throw new Error('Next past the last artifact changed the page'); + } + evidence.checks.push({ check: 'unsupported types are explicit with Open/Copy and paging clamps', value: true }); + await capture('a1w-viewer-unsupported'); + + await clickExact('Previous artifact'); + await clickExact('Previous artifact'); + await clickExact('Previous artifact'); + await delay(500); + const textBody = await visibleText(); + if (!textBody.includes('1 of 4 · text/plain')) { + throw new Error(`Text page missing: ${JSON.stringify(textBody)}`); + } + evidence.checks.push({ check: 'text/plain pages in the viewer with its recorded facts', value: true }); + await capture('a1w-viewer-text'); + + await clickExact('Back'); + await delay(500); + const returnedBody = await bodyText(); + if (!returnedBody.includes('shot.png') || !returnedBody.includes('reviewer · visit 2')) { + throw new Error(`Back did not return to the gallery: ${JSON.stringify(returnedBody)}`); + } + evidence.checks.push({ check: 'native Back returns to the gallery row list', value: true }); + + await navigate(galleryView('&state=missing'), 'Artifacts'); + await clickLowestPrefix('missing.png'); + await delay(700); + const missingBody = await visibleText(); + if (!missingBody.includes('The server answered 404.')) { + throw new Error(`Missing fetch status was not reported: ${JSON.stringify(missingBody)}`); + } + evidence.checks.push({ check: 'an HTTP failure reports its status instead of an empty preview', value: true }); + await capture('a1w-viewer-http-error'); + + await navigate(galleryView('&state=external'), 'Artifacts'); + await clickLowestPrefix('elsewhere.png'); + await delay(500); + const externalBody = await visibleText(); + if (!externalBody.includes('This artifact is hosted on another origin and is not previewed here.')) { + throw new Error(`External artifact was not marked: ${JSON.stringify(externalBody)}`); + } + if (!externalBody.includes('1 of 1 · image/png') || !(await hasLabel('Open'))) { + throw new Error(`External artifact lost its facts/Open action: ${JSON.stringify(externalBody)}`); + } + evidence.checks.push({ check: 'an external artifact opens marked, unfetched, with facts and actions', value: true }); + await capture('a1w-viewer-external'); + + // 320 px at 2x text on both hosts: the viewer keeps its facts, paging and + // controls whole. + const scaledViewer = async (platform, prefix) => { + await navigate(galleryView('', platform), 'Artifacts'); + await clickLowestPrefix('shot.png'); + await delay(700); + const scaledBody = await bodyText(); + for (const fact of ['image/png · 78.7\u00a0KiB', '3 of 4 · image/png', 'reviewer · visit 1']) { + if (!scaledBody.includes(fact)) { + throw new Error(`2x viewer missing ${fact}: ${JSON.stringify(scaledBody)}`); + } + } + if (!(await hasLabel('Previous artifact')) || !(await hasLabel('Next artifact'))) { + throw new Error(`2x viewer lost paging: ${JSON.stringify(await labels())}`); + } + await capture(`${prefix}-viewer`, 320, 720, 1); + }; + await scaledViewer('material', 'a1w-material-2x-320'); + evidence.checks.push({ check: 'Material 2x/320 viewer keeps facts and paging', value: true }); + await scaledViewer('cupertino', 'a1w-cupertino-2x-320'); + evidence.checks.push({ check: 'Cupertino 2x/320 viewer keeps facts and paging', value: true }); + // Cupertino light: the tinted action, the native dialog and its actions. await openGallery(`platform=cupertino&theme=light&origin=${encodeURIComponent(origin)}`); const cupertinoBody = await bodyText(); @@ -390,7 +569,7 @@ try { 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']) { + for (const recorded of ['build.log', 'shot.png', 'reviewer · visit 1']) { if (!scaled.includes(recorded)) { throw new Error(`2x gallery missing ${recorded}: ${JSON.stringify(scaled)}`); } @@ -398,7 +577,8 @@ try { await capture(`${prefix}-gallery`, 320, 720, 1); await clickLowestPrefix('result.csv'); const facts = await bodyText(); - if (!facts.includes('Artifacts · 1 recorded · partial capture')) { + if (!facts.includes('Artifacts · 3 recorded') && + !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'))) {