diff --git a/app/lib/features/artifacts/actions/artifact_file.dart b/app/lib/features/artifacts/actions/artifact_file.dart new file mode 100644 index 00000000..ac634f32 --- /dev/null +++ b/app/lib/features/artifacts/actions/artifact_file.dart @@ -0,0 +1,99 @@ +import 'dart:typed_data'; + +import '../domain/artifact_record.dart'; + +/// A recorded artifact's exact bytes, named and typed as the host must save or +/// share them. +/// +/// The name is the recorded file name's basename, never a url or a directory +/// path. The MIME type is the recorded media type without parameters. Only when +/// the recorded value is missing or malformed does the fallback apply: the +/// server url's basename, then `artifact`, and `application/octet-stream`. +class ArtifactFile { + const ArtifactFile({ + required this.name, + required this.mimeType, + required this.bytes, + }); + + final String name; + final String mimeType; + final Uint8List bytes; + + int get byteLength => bytes.length; +} + +const String artifactFileFallbackName = 'artifact'; +const String artifactFileFallbackMimeType = 'application/octet-stream'; + +/// Names and types one recorded artifact's fetched bytes for a file transfer. +ArtifactFile artifactFileFor({ + required ArtifactRecord artifact, + required Uri url, + required Uint8List bytes, +}) => ArtifactFile( + name: artifactFileName(artifact, url), + mimeType: artifactFileMimeType(artifact), + bytes: bytes, +); + +/// The recorded name without any `public/` prefix or directory component, with +/// control characters replaced. An absent, dot-only or unusable name falls +/// back to the resolved url's last path segment and then to `artifact`. +String artifactFileName(ArtifactRecord artifact, Uri url) { + final recorded = _usableBasename(artifact.name); + if (recorded.isNotEmpty) return recorded; + final fromUrl = _usableBasename( + url.pathSegments.isEmpty ? '' : url.pathSegments.last, + ); + return fromUrl.isEmpty ? artifactFileFallbackName : fromUrl; +} + +/// The recorded MIME type without parameters, lowercased, or +/// `application/octet-stream` when nothing usable was recorded. +String artifactFileMimeType(ArtifactRecord artifact) { + final mediaType = artifact.contentType.split(';').first.trim().toLowerCase(); + return _mediaType.hasMatch(mediaType) + ? mediaType + : artifactFileFallbackMimeType; +} + +final RegExp _mediaType = RegExp( + r"^[a-z0-9!#$&'*+.^_`|~-]+/[a-z0-9!#$&'*+.^_`|~-]+$", +); + +/// Whether the record carries a usable file name of its own. +bool hasRecordedArtifactName(ArtifactRecord artifact) => + _usableBasename(artifact.name).isNotEmpty; + +/// Whether the record carries a usable MIME type of its own. +bool hasRecordedArtifactMimeType(ArtifactRecord artifact) { + final mediaType = artifact.contentType.split(';').first.trim().toLowerCase(); + return _mediaType.hasMatch(mediaType); +} + +/// An explicit note when the recorded name or MIME type cannot be used, so the +/// fallback file name/type is never silent. Null for a complete record. +String? artifactFileRecordingNotice(ArtifactRecord artifact, Uri url) { + final nameMissing = !hasRecordedArtifactName(artifact); + final typeMissing = !hasRecordedArtifactMimeType(artifact); + if (!nameMissing && !typeMissing) return null; + final name = artifactFileName(artifact, url); + if (nameMissing && typeMissing) { + return 'No usable recorded name or MIME type; the file is saved as ' + '$name ($artifactFileFallbackMimeType).'; + } + if (nameMissing) { + return 'No usable recorded name; the file is saved as $name.'; + } + return 'No usable recorded MIME type; the file is saved as ' + '$artifactFileFallbackMimeType.'; +} + +String _usableBasename(String value) { + final segments = value.trim().split(RegExp(r'[\\/]')); + final name = segments.isEmpty ? '' : segments.last; + final cleaned = name.replaceAll(RegExp(r'[\x00-\x1f\x7f]'), '_').trim(); + if (cleaned == '.' || cleaned == '..') return ''; + return cleaned; +} diff --git a/app/lib/features/artifacts/actions/artifact_file_actions.dart b/app/lib/features/artifacts/actions/artifact_file_actions.dart new file mode 100644 index 00000000..39fa72b7 --- /dev/null +++ b/app/lib/features/artifacts/actions/artifact_file_actions.dart @@ -0,0 +1,187 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../ui/adaptive/host.dart'; +import '../domain/artifact_record.dart'; +import '../domain/artifact_url.dart'; +import '../ui/artifact_viewer_fetch.dart'; +import 'artifact_file.dart'; +import 'artifact_file_bridge.dart'; +import 'artifact_file_controller.dart'; + +/// Download and Share for one selected artifact, backed by its exact bytes. +/// +/// The controls are standard native buttons. Download creates a named file; +/// Share passes a named file to the host share sheet and never falls back to +/// the artifact url. A host without a capability shows a disabled control and +/// the exact reason, while the other action keeps working. One tap starts at +/// most one transfer; a slow fetch shows progress and can be cancelled. +class ArtifactFileActions extends StatefulWidget { + const ArtifactFileActions({ + super.key, + required this.artifact, + required this.resolved, + this.fetch = fetchArtifact, + this.bridge = const ArtifactFileBridge(), + }); + + final ArtifactRecord artifact; + final ResolvedArtifactUrl resolved; + final ArtifactFetch fetch; + final ArtifactFileBridge bridge; + + @override + State createState() => _ArtifactFileActionsState(); +} + +class _ArtifactFileActionsState extends State { + late ArtifactFileActionsController _controller; + + @override + void initState() { + super.initState(); + _controller = _create(); + } + + @override + void didUpdateWidget(covariant ArtifactFileActions oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.resolved.url != widget.resolved.url || + oldWidget.artifact.url != widget.artifact.url || + oldWidget.artifact.name != widget.artifact.name || + oldWidget.artifact.contentType != widget.artifact.contentType || + oldWidget.fetch != widget.fetch || + oldWidget.bridge != widget.bridge) { + _controller.dispose(); + _controller = _create(); + } + } + + ArtifactFileActionsController _create() => ArtifactFileActionsController( + artifact: widget.artifact, + resolved: widget.resolved, + fetch: widget.fetch, + bridge: widget.bridge, + ); + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return ListenableBuilder( + listenable: _controller, + builder: (context, _) => _ActionBar( + controller: _controller, + cupertino: usesCupertinoHost(context), + ), + ); + } +} + +class _ActionBar extends StatelessWidget { + const _ActionBar({required this.controller, required this.cupertino}); + + final ArtifactFileActionsController controller; + final bool cupertino; + + @override + Widget build(BuildContext context) { + final status = controller.status; + final notice = artifactFileRecordingNotice( + controller.artifact, + controller.resolved.uri, + ); + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Wrap( + spacing: 8, + runSpacing: 4, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + _button( + label: 'Download', + icon: Icons.download_outlined, + onPressed: controller.canDownload && !controller.busy + ? controller.download + : null, + ), + _button( + label: 'Share', + icon: Icons.ios_share, + onPressed: controller.canShare && !controller.busy + ? controller.share + : null, + ), + if (controller.canCancel) + _button( + label: 'Cancel', + icon: Icons.close, + onPressed: controller.cancel, + ), + ], + ), + if (controller.busy && status != null) + Padding( + padding: const EdgeInsets.only(top: 6), + child: Semantics( + liveRegion: true, + container: true, + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + if (cupertino) + const CupertinoActivityIndicator(radius: 8) + else + const SizedBox( + width: 14, + height: 14, + child: CircularProgressIndicator(strokeWidth: 2), + ), + const SizedBox(width: 8), + Flexible(child: Text(status)), + ], + ), + ), + ) + else if (status != null) + Padding( + padding: const EdgeInsets.only(top: 6), + child: Semantics(liveRegion: true, child: Text(status)), + ), + if (!controller.canDownload) + Padding( + padding: const EdgeInsets.only(top: 6), + child: Text(controller.bridge.downloadUnavailableMessage), + ), + if (!controller.canShare) + Padding( + padding: const EdgeInsets.only(top: 6), + child: Text(controller.bridge.shareUnavailableMessage), + ), + if (notice != null) + Padding(padding: const EdgeInsets.only(top: 6), child: Text(notice)), + ], + ); + } + + Widget _button({ + required String label, + required IconData icon, + required VoidCallback? onPressed, + }) { + if (cupertino) { + return CupertinoButton(onPressed: onPressed, child: Text(label)); + } + return TextButton.icon( + onPressed: onPressed, + icon: Icon(icon, size: 18), + label: Text(label), + ); + } +} diff --git a/app/lib/features/artifacts/actions/artifact_file_bridge.dart b/app/lib/features/artifacts/actions/artifact_file_bridge.dart new file mode 100644 index 00000000..8370dd35 --- /dev/null +++ b/app/lib/features/artifacts/actions/artifact_file_bridge.dart @@ -0,0 +1,42 @@ +import 'artifact_file.dart'; +import 'artifact_transfer.dart'; + +/// The host file capabilities one action row uses. +/// +/// The defaults are the real conditional-import bridge: a web Blob/anchor +/// download plus `navigator.share`, and honest `unsupported` results on native +/// hosts until a platform launcher exists. Tests inject both functions and the +/// capability flags without touching a browser. +class ArtifactFileBridge { + const ArtifactFileBridge({ + this.download, + this.share, + this.downloadSupported, + this.shareSupported, + this.downloadUnsupportedMessage, + this.shareUnsupportedMessage, + }); + + final ArtifactSaveFile? download; + final ArtifactShareFile? share; + final bool? downloadSupported; + final bool? shareSupported; + final String? downloadUnsupportedMessage; + final String? shareUnsupportedMessage; + + bool get canDownload => downloadSupported ?? artifactDownloadSupported; + + bool get canShare => shareSupported ?? artifactShareSupported; + + String get downloadUnavailableMessage => + downloadUnsupportedMessage ?? artifactDownloadUnsupportedMessage; + + String get shareUnavailableMessage => + shareUnsupportedMessage ?? artifactShareUnsupportedMessage; + + Future saveFile(ArtifactFile file) => + (download ?? saveArtifactFile)(file); + + Future shareFile(ArtifactFile file) => + (share ?? shareArtifactFile)(file); +} diff --git a/app/lib/features/artifacts/actions/artifact_file_controller.dart b/app/lib/features/artifacts/actions/artifact_file_controller.dart new file mode 100644 index 00000000..eb707704 --- /dev/null +++ b/app/lib/features/artifacts/actions/artifact_file_controller.dart @@ -0,0 +1,196 @@ +import 'package:flutter/foundation.dart'; + +import '../domain/artifact_record.dart'; +import '../domain/artifact_url.dart'; +import '../ui/artifact_viewer_fetch.dart'; +import 'artifact_file.dart'; +import 'artifact_file_bridge.dart'; +import 'artifact_transfer.dart'; + +/// Which host file action is currently in flight. +enum ArtifactFileAction { download, share } + +/// The words shown while bytes are being fetched. +const String artifactPreparingFile = 'Preparing file…'; + +/// Saves or shares one selected artifact's fetched bytes. +/// +/// The controller owns exactly one transfer at a time: a tap while [busy] is +/// ignored, so a double tap cannot start two fetches or two share sheets. The +/// same fetch seam the viewer uses obtains the bytes, so the same-origin +/// credential policy and HTTP status handling apply. Fetched bytes are kept +/// after a ready/blocked/canceled share so the next tap can retry with a fresh +/// user activation without another transfer. +/// +/// Cancelling stops the action from continuing: a late fetch result is ignored +/// by generation, and the host transfer is never started. The underlying HTTP +/// request is not aborted because the shared fetch seam has no cancellation +/// token; the app never reports those bytes as a completed transfer. +class ArtifactFileActionsController extends ChangeNotifier { + ArtifactFileActionsController({ + required this.artifact, + required this.resolved, + required this.fetch, + this.bridge = const ArtifactFileBridge(), + }); + + final ArtifactRecord artifact; + final ResolvedArtifactUrl resolved; + final ArtifactFileBridge bridge; + + final ArtifactFetch fetch; + ArtifactFile? _prepared; + String? _preparedUrl; + ArtifactFileAction? _active; + bool _preparing = false; + int _generation = 0; + bool _disposed = false; + String? _status; + + String? get status => _status; + + bool get busy => _active != null; + + /// Cancel is offered only while the fetch is still running; once the host + /// share sheet is open the OS owns the transfer. + bool get canCancel => _active != null && _preparing; + + bool get canDownload => bridge.canDownload; + + bool get canShare => bridge.canShare; + + Future download() async { + if (busy) return; + if (!canDownload) { + _setStatus(bridge.downloadUnavailableMessage); + return; + } + final generation = _begin(ArtifactFileAction.download); + final file = await _prepare(generation); + if (file == null || generation != _generation) return; + _preparing = false; + _notify(); + ArtifactTransferResult result; + try { + result = await bridge.saveFile(file); + } catch (_) { + _fail(generation, 'Could not download the file. Try again.'); + return; + } + if (generation != _generation) return; + _active = null; + _status = result.state == ArtifactTransferState.saved + ? 'Downloaded ${file.name}.' + : result.message; + _notify(); + } + + Future share() async { + if (busy) return; + if (!canShare) { + _setStatus(bridge.shareUnavailableMessage); + return; + } + final generation = _begin(ArtifactFileAction.share); + final file = await _prepare(generation); + if (file == null || generation != _generation) return; + _preparing = false; + _notify(); + ArtifactTransferResult result; + try { + result = await bridge.shareFile(file); + } catch (_) { + _fail( + generation, + 'Could not share the file. Use Download to save it, or try Share again.', + ); + return; + } + if (generation != _generation) return; + _active = null; + _status = result.state == ArtifactTransferState.shared + ? 'File shared.' + : result.message; + _notify(); + } + + /// Stops waiting for the fetch. Nothing is handed to the host afterwards. + void cancel() { + if (!canCancel) return; + final action = _active; + _generation += 1; + _active = null; + _preparing = false; + _status = action == ArtifactFileAction.share + ? 'Sharing canceled.' + : 'Download canceled.'; + _notify(); + } + + int _begin(ArtifactFileAction action) { + final generation = ++_generation; + _active = action; + _preparing = true; + _status = artifactPreparingFile; + _notify(); + return generation; + } + + Future _prepare(int generation) async { + final cached = _prepared; + if (cached != null && _preparedUrl == resolved.url) { + _preparing = false; + _notify(); + return cached; + } + try { + final fetched = await fetch(resolved.uri); + if (generation != _generation) return null; + if (!fetched.ok) { + _fail( + generation, + 'Could not fetch the artifact (HTTP ${fetched.status}).', + ); + return null; + } + final file = artifactFileFor( + artifact: artifact, + url: resolved.uri, + bytes: fetched.bytes, + ); + _prepared = file; + _preparedUrl = resolved.url; + return file; + } on ArtifactFetchException catch (error) { + _fail(generation, 'Could not fetch the artifact: ${error.message}'); + return null; + } catch (error) { + _fail(generation, 'Could not fetch the artifact: $error'); + return null; + } + } + + void _fail(int generation, String message) { + if (generation != _generation) return; + _active = null; + _preparing = false; + _status = message; + _notify(); + } + + void _setStatus(String message) { + _status = message; + _notify(); + } + + void _notify() { + if (!_disposed) notifyListeners(); + } + + @override + void dispose() { + _disposed = true; + _generation += 1; + super.dispose(); + } +} diff --git a/app/lib/features/artifacts/actions/artifact_transfer.dart b/app/lib/features/artifacts/actions/artifact_transfer.dart new file mode 100644 index 00000000..bc99bbf3 --- /dev/null +++ b/app/lib/features/artifacts/actions/artifact_transfer.dart @@ -0,0 +1,61 @@ +import 'artifact_file.dart'; +import 'artifact_transfer_stub.dart' + if (dart.library.js_interop) 'artifact_transfer_web.dart' + as impl; + +/// The outcome of a host file transfer. +enum ArtifactTransferState { + /// The host accepted a browser download. + saved, + + /// The host share sheet accepted the file. + shared, + + /// The bytes are ready but the browser needed a fresh user activation. + ready, + + /// The operator or the host canceled the transfer. + canceled, + + /// The host cannot save/share this file. + unsupported, + + /// The host refused the share for a policy or activation reason. + blocked, + + /// The transfer failed for any other reason. + failed, +} + +/// A transfer result plus the exact words the action row reports. +class ArtifactTransferResult { + const ArtifactTransferResult(this.state, this.message); + + final ArtifactTransferState state; + final String message; +} + +typedef ArtifactSaveFile = + Future Function(ArtifactFile file); +typedef ArtifactShareFile = + Future Function(ArtifactFile file); + +/// Whether the host can save an artifact's bytes as a named file. +bool get artifactDownloadSupported => impl.artifactDownloadSupported; + +/// Whether the host can share a file (not merely a link). +bool get artifactShareSupported => impl.artifactShareSupported; + +String get artifactDownloadUnsupportedMessage => + impl.artifactDownloadUnsupportedMessage; + +String get artifactShareUnsupportedMessage => + impl.artifactShareUnsupportedMessage; + +/// Saves [file] through the host's download capability. +Future saveArtifactFile(ArtifactFile file) => + impl.saveArtifactFile(file); + +/// Shares [file] through the host's file-sharing capability. +Future shareArtifactFile(ArtifactFile file) => + impl.shareArtifactFile(file); diff --git a/app/lib/features/artifacts/actions/artifact_transfer_stub.dart b/app/lib/features/artifacts/actions/artifact_transfer_stub.dart new file mode 100644 index 00000000..13556290 --- /dev/null +++ b/app/lib/features/artifacts/actions/artifact_transfer_stub.dart @@ -0,0 +1,29 @@ +import 'artifact_file.dart'; +import 'artifact_transfer.dart'; + +/// Native fallback for artifact file actions. +/// +/// A save/share plugin is not a dependency of this slice, so a non-web host +/// reports `unsupported` instead of pretending to save a file. The action row +/// disables the control and shows this exact explanation. +bool get artifactDownloadSupported => false; + +bool get artifactShareSupported => false; + +String get artifactDownloadUnsupportedMessage => + 'Downloading files is not supported on this platform yet.'; + +String get artifactShareUnsupportedMessage => + 'File sharing is not supported on this platform yet.'; + +Future saveArtifactFile(ArtifactFile file) async => + ArtifactTransferResult( + ArtifactTransferState.unsupported, + artifactDownloadUnsupportedMessage, + ); + +Future shareArtifactFile(ArtifactFile file) async => + ArtifactTransferResult( + ArtifactTransferState.unsupported, + artifactShareUnsupportedMessage, + ); diff --git a/app/lib/features/artifacts/actions/artifact_transfer_web.dart b/app/lib/features/artifacts/actions/artifact_transfer_web.dart new file mode 100644 index 00000000..bcd07d84 --- /dev/null +++ b/app/lib/features/artifacts/actions/artifact_transfer_web.dart @@ -0,0 +1,206 @@ +import 'dart:async'; +import 'dart:js_interop'; +import 'dart:js_interop_unsafe'; + +import 'artifact_file.dart'; +import 'artifact_transfer.dart'; + +/// Web file actions: the artifact's bytes become a named `Blob`/`File`. +/// +/// Download creates an object url and clicks a native anchor with the recorded +/// name; share passes a real `File` to `navigator.share`. Neither path ever +/// substitutes the artifact url or opens a blob page. No package:web import is +/// used, so the same source compiles for JavaScript and WebAssembly. +@JS('document') +external _Document get _document; + +@JS('navigator') +external _Navigator get _navigator; + +@JS('URL.createObjectURL') +external JSString _createObjectUrl(JSObject blob); + +@JS('URL.revokeObjectURL') +external void _revokeObjectUrl(JSString url); + +extension type _Document._(JSObject _) implements JSObject { + external _Anchor createElement(JSString tag); + external _Element get body; +} + +extension type _Anchor._(JSObject _) implements JSObject { + external set href(JSString value); + external set download(JSString value); + external void click(); + external void remove(); +} + +extension type _Element._(JSObject _) implements JSObject { + external void appendChild(JSObject node); +} + +extension type _BlobOptions._(JSObject _) implements JSObject { + external factory _BlobOptions({JSString type}); +} + +@JS('Blob') +extension type _Blob._(JSObject _) implements JSObject { + external factory _Blob(JSArray parts, _BlobOptions options); +} + +extension type _FileOptions._(JSObject _) implements JSObject { + external factory _FileOptions({JSString type}); +} + +@JS('File') +extension type _File._(JSObject _) implements JSObject { + external factory _File( + JSArray parts, + JSString name, + _FileOptions options, + ); +} + +extension type _ShareData._(JSObject _) implements JSObject { + external factory _ShareData({JSArray files}); +} + +extension type _UserActivation._(JSObject _) implements JSObject { + external bool get isActive; +} + +extension type _Navigator._(JSObject _) implements JSObject { + external JSPromise share(_ShareData data); + external bool canShare(_ShareData data); + external _UserActivation? get userActivation; +} + +bool get artifactDownloadSupported => true; + +bool get artifactShareSupported => + _hasFunction('share') && _hasFunction('canShare'); + +String get artifactDownloadUnsupportedMessage => + 'Downloading files is not supported in this browser.'; + +String get artifactShareUnsupportedMessage => + 'File sharing is not supported in this browser. Use Download to save the file.'; + +const String _fileReadyMessage = + 'File ready. Tap Share again to choose where to send it.'; + +Future saveArtifactFile(ArtifactFile file) async { + try { + final blob = _blobFor(file); + final url = _createObjectUrl(blob); + final anchor = _document.createElement('a'.toJS) + ..href = url + ..download = file.name.toJS; + _document.body.appendChild(anchor); + try { + anchor.click(); + } finally { + anchor.remove(); + // Revoking immediately can cancel a download in some browsers. + unawaited( + Future.delayed( + const Duration(seconds: 1), + () => _revokeObjectUrl(url), + ), + ); + } + return ArtifactTransferResult( + ArtifactTransferState.saved, + 'Downloaded ${file.name}.', + ); + } catch (_) { + return const ArtifactTransferResult( + ArtifactTransferState.failed, + 'Could not download the file. Try again.', + ); + } +} + +Future shareArtifactFile(ArtifactFile file) async { + if (!artifactShareSupported) { + return ArtifactTransferResult( + ArtifactTransferState.unsupported, + artifactShareUnsupportedMessage, + ); + } + final data = _ShareData(files: [_fileFor(file)].toJS); + try { + if (!_navigator.canShare(data)) { + return ArtifactTransferResult( + ArtifactTransferState.unsupported, + 'This browser cannot share this file type. Use Download to save the file.', + ); + } + } catch (_) { + return ArtifactTransferResult( + ArtifactTransferState.unsupported, + artifactShareUnsupportedMessage, + ); + } + // Fetching may outlast the browser's transient activation. Do not attempt a + // doomed share or substitute a url: the prepared bytes stay cached in the + // controller and the next tap shares them. + final activation = _navigator.userActivation; + if (activation != null && !activation.isActive) { + return const ArtifactTransferResult( + ArtifactTransferState.ready, + _fileReadyMessage, + ); + } + try { + await _navigator.share(data).toDart; + return const ArtifactTransferResult( + ArtifactTransferState.shared, + 'File shared.', + ); + } catch (error) { + final name = _errorName(error); + if (name == 'AbortError') { + return const ArtifactTransferResult( + ArtifactTransferState.canceled, + 'Sharing canceled.', + ); + } + if (name == 'NotAllowedError') { + return const ArtifactTransferResult( + ArtifactTransferState.blocked, + 'Sharing was blocked. Tap Share again, or use Download to save the file.', + ); + } + return const ArtifactTransferResult( + ArtifactTransferState.failed, + 'Could not share the file. Use Download to save it, or try Share again.', + ); + } +} + +_Blob _blobFor(ArtifactFile file) => _Blob( + [file.bytes.toJS].toJS, + _BlobOptions(type: file.mimeType.toJS), +); + +_File _fileFor(ArtifactFile file) => _File( + [_blobFor(file)].toJS, + file.name.toJS, + _FileOptions(type: file.mimeType.toJS), +); + +bool _hasFunction(String name) { + final value = _navigator.getProperty(name.toJS); + return value != null && value.isA(); +} + +String? _errorName(Object error) { + // A rejected JS promise arrives as a Dart error whose text carries the DOM + // exception name; the web's AbortError/NotAllowedError branches use those. + final text = '$error'; + for (final candidate in const ['AbortError', 'NotAllowedError']) { + if (text.contains(candidate)) return candidate; + } + return null; +} diff --git a/app/lib/features/artifacts/ui/artifact_gallery_page.dart b/app/lib/features/artifacts/ui/artifact_gallery_page.dart index e984079f..5d79bd0f 100644 --- a/app/lib/features/artifacts/ui/artifact_gallery_page.dart +++ b/app/lib/features/artifacts/ui/artifact_gallery_page.dart @@ -5,6 +5,8 @@ import 'package:flutter/services.dart'; import '../../../core/api_gateway.dart'; import '../../../ui/adaptive/host.dart'; import '../../chat/ui/transcript/chat_markdown_view.dart'; +import '../actions/artifact_file_actions.dart'; +import '../actions/artifact_file_bridge.dart'; import '../domain/artifact_groups.dart'; import '../domain/artifact_kind.dart'; import '../domain/artifact_record.dart'; @@ -28,8 +30,9 @@ const String artifactGalleryTitle = 'Artifacts'; /// never fetched); any other selection opens a native dialog with the recorded /// name, MIME and size, the visit's capture facts and, only when the recorded /// url resolves through [resolveArtifactUrl], native `Open` and `Copy link` -/// actions. Markdown previews use the same chat markdown renderer by default. -/// It never downloads, shares or filters. +/// actions plus file `Download`/`Share` for a server-served url. Markdown +/// previews use the same chat markdown renderer by default. It never filters, +/// and an external url is never fetched for preview or file transfer. class ArtifactGalleryPage extends StatefulWidget { const ArtifactGalleryPage({ super.key, @@ -39,6 +42,7 @@ class ArtifactGalleryPage extends StatefulWidget { this.openExternal = openArtifactExternally, this.fetch = fetchArtifact, this.markdownBuilder = chatMarkdownText, + this.fileBridge = const ArtifactFileBridge(), }); final List steps; @@ -47,6 +51,7 @@ class ArtifactGalleryPage extends StatefulWidget { final ArtifactExternalOpen openExternal; final ArtifactFetch fetch; final ArtifactMarkdownBuilder markdownBuilder; + final ArtifactFileBridge fileBridge; @override State createState() => _ArtifactGalleryPageState(); @@ -89,6 +94,7 @@ class _ArtifactGalleryPageState extends State { openExternal: widget.openExternal, fetch: widget.fetch, markdownBuilder: widget.markdownBuilder, + fileBridge: widget.fileBridge, ), ) : MaterialPageRoute( @@ -99,6 +105,7 @@ class _ArtifactGalleryPageState extends State { openExternal: widget.openExternal, fetch: widget.fetch, markdownBuilder: widget.markdownBuilder, + fileBridge: widget.fileBridge, ), ), ); @@ -120,12 +127,31 @@ class _ArtifactGalleryPageState extends State { step: step, resolved: resolved, ); + final content = Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + facts, + if (resolved != null && !resolved.external) ...[ + const SizedBox(height: 12), + ArtifactFileActions( + key: ValueKey( + 'artifact-files-${artifactVisitIdentity(group, artifact)}', + ), + artifact: artifact, + resolved: resolved, + fetch: widget.fetch, + bridge: widget.fileBridge, + ), + ], + ], + ); if (usesCupertinoHost(context)) { return showCupertinoDialog( context: context, builder: (dialogContext) => CupertinoAlertDialog( title: Text(artifactDisplayName(artifact)), - content: facts, + content: content, actions: [ if (resolved != null) CupertinoDialogAction( @@ -150,7 +176,7 @@ class _ArtifactGalleryPageState extends State { context: context, builder: (dialogContext) => AlertDialog( title: Text(artifactDisplayName(artifact)), - content: SingleChildScrollView(child: facts), + content: SingleChildScrollView(child: content), actions: [ if (resolved != null) TextButton( diff --git a/app/lib/features/artifacts/ui/artifact_viewer_body.dart b/app/lib/features/artifacts/ui/artifact_viewer_body.dart index e5ffdf1d..f5ffdbfe 100644 --- a/app/lib/features/artifacts/ui/artifact_viewer_body.dart +++ b/app/lib/features/artifacts/ui/artifact_viewer_body.dart @@ -4,17 +4,21 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import '../../../ui/adaptive/host.dart'; +import '../actions/artifact_file_actions.dart'; +import '../actions/artifact_file_bridge.dart'; import '../domain/artifact_preview.dart'; import '../domain/artifact_url.dart'; import '../domain/gallery_navigation.dart'; import 'artifact_selection_facts.dart'; import 'artifact_viewer_content.dart'; +import 'artifact_viewer_fetch.dart'; /// One viewer page: the recorded facts, position, live status, preview surface, -/// external actions and paging controls. +/// file transfer actions, external actions and paging controls. /// /// It is stateless so the page owns loading, fetch generations and focus; this -/// surface only draws the current page and reports the operator's intent. +/// surface only draws the current page and reports the operator's intent. The +/// page content scrolls as one column at large text sizes; paging stays fixed. class ArtifactViewerBody extends StatelessWidget { const ArtifactViewerBody({ super.key, @@ -28,6 +32,8 @@ class ArtifactViewerBody extends StatelessWidget { required this.onNext, required this.onOpen, required this.onCopy, + this.fetch = fetchArtifact, + this.fileBridge = const ArtifactFileBridge(), this.text, this.bytes, this.error, @@ -44,6 +50,8 @@ class ArtifactViewerBody extends StatelessWidget { final VoidCallback onNext; final VoidCallback onOpen; final VoidCallback onCopy; + final ArtifactFetch fetch; + final ArtifactFileBridge fileBridge; final String? text; final Uint8List? bytes; final String? error; @@ -54,42 +62,67 @@ class ArtifactViewerBody extends StatelessWidget { return Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ - Padding( - padding: const EdgeInsetsDirectional.fromSTEB(16, 12, 16, 4), - child: ArtifactSelectionFacts( - group: page.group, - artifact: page.artifact, - step: null, - resolved: plan.resolved, - ), - ), - Padding( - padding: const EdgeInsetsDirectional.fromSTEB(16, 4, 16, 4), - child: Text( - artifactViewerPositionLabel( - index, - count, - page.artifact.contentType, + Expanded( + child: SingleChildScrollView( + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Padding( + padding: const EdgeInsetsDirectional.fromSTEB(16, 12, 16, 4), + child: ArtifactSelectionFacts( + group: page.group, + artifact: page.artifact, + step: null, + resolved: plan.resolved, + ), + ), + Padding( + padding: const EdgeInsetsDirectional.fromSTEB(16, 4, 16, 4), + child: Text( + artifactViewerPositionLabel( + index, + count, + page.artifact.contentType, + ), + ), + ), + if (status != null) + Padding( + padding: const EdgeInsetsDirectional.fromSTEB(16, 0, 16, 4), + child: Semantics(liveRegion: true, child: Text(status!)), + ), + ArtifactPreviewBody( + plan: plan, + loading: loading, + markdownBuilder: markdownBuilder, + text: text, + bytes: bytes, + error: error, + ), + if (plan.resolved != null && !plan.resolved!.external) + Padding( + padding: const EdgeInsetsDirectional.fromSTEB(16, 4, 16, 4), + child: ArtifactFileActions( + key: ValueKey( + 'viewer-files-${page.group.stageKey}\u0000' + '${page.group.visit}\u0000${page.artifact.url}', + ), + artifact: page.artifact, + resolved: plan.resolved!, + fetch: fetch, + bridge: fileBridge, + ), + ), + if (plan.resolved != null) + _Actions( + resolved: plan.resolved!, + onOpen: onOpen, + onCopy: onCopy, + ), + ], ), ), ), - if (status != null) - Padding( - padding: const EdgeInsetsDirectional.fromSTEB(16, 0, 16, 4), - child: Semantics(liveRegion: true, child: Text(status!)), - ), - Expanded( - child: ArtifactPreviewBody( - plan: plan, - loading: loading, - markdownBuilder: markdownBuilder, - text: text, - bytes: bytes, - error: error, - ), - ), - if (plan.resolved != null) - _Actions(resolved: plan.resolved!, onOpen: onOpen, onCopy: onCopy), _Pager( index: index, count: count, diff --git a/app/lib/features/artifacts/ui/artifact_viewer_content.dart b/app/lib/features/artifacts/ui/artifact_viewer_content.dart index 519d12d4..a433946b 100644 --- a/app/lib/features/artifacts/ui/artifact_viewer_content.dart +++ b/app/lib/features/artifacts/ui/artifact_viewer_content.dart @@ -62,9 +62,9 @@ class ArtifactPreviewBody extends StatelessWidget { ), ); case ArtifactPreviewKind.text: - return _ScrollingText(child: SelectableText(text ?? '')); + return _PreviewPadding(child: SelectableText(text ?? '')); case ArtifactPreviewKind.markdown: - return _ScrollingText(child: markdownBuilder(context, text ?? '')); + return _PreviewPadding(child: markdownBuilder(context, text ?? '')); case ArtifactPreviewKind.unsupported: case ArtifactPreviewKind.unavailable: return const SizedBox.shrink(); @@ -93,14 +93,16 @@ class _Loading extends StatelessWidget { } } -class _ScrollingText extends StatelessWidget { - const _ScrollingText({required this.child}); +/// Preview text at its natural height; the viewer body owns the page scroll so +/// a long document and its actions scroll together instead of nested scrolls. +class _PreviewPadding extends StatelessWidget { + const _PreviewPadding({required this.child}); final Widget child; @override Widget build(BuildContext context) { - return SingleChildScrollView( + return Padding( padding: const EdgeInsetsDirectional.fromSTEB(16, 8, 16, 16), child: child, ); diff --git a/app/lib/features/artifacts/ui/artifact_viewer_page.dart b/app/lib/features/artifacts/ui/artifact_viewer_page.dart index 5673986f..cbb9a189 100644 --- a/app/lib/features/artifacts/ui/artifact_viewer_page.dart +++ b/app/lib/features/artifacts/ui/artifact_viewer_page.dart @@ -5,6 +5,7 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import '../../../ui/adaptive/host.dart'; +import '../actions/artifact_file_bridge.dart'; import '../domain/artifact_groups.dart'; import '../domain/artifact_preview.dart'; import '../domain/artifact_url.dart'; @@ -24,8 +25,9 @@ const String artifactViewerTitle = 'Artifact viewer'; /// `text/plain` artifact is selectable text, and a `.md`/`.markdown` or /// `text/markdown` artifact is handed to [markdownBuilder]. The selected page /// keeps its recorded facts visible and offers the existing external Open and -/// Copy link actions. Previous/Next walk the same filtered list the gallery -/// draws and stop at both ends; closing returns to the gallery row. +/// Copy link actions plus Download/Share of the same-origin bytes as a named +/// file. Previous/Next walk the same filtered list the gallery draws and stop at +/// both ends; closing returns to the gallery row. /// /// Nothing is ever drawn for an external, unsafe or unsupported url: the viewer /// reports the exact state instead. External urls are never fetched. @@ -38,6 +40,7 @@ class ArtifactViewerPage extends StatefulWidget { this.fetch = fetchArtifact, this.markdownBuilder = defaultArtifactMarkdown, this.openExternal = openArtifactExternally, + this.fileBridge = const ArtifactFileBridge(), }); final List groups; @@ -49,6 +52,7 @@ class ArtifactViewerPage extends StatefulWidget { final ArtifactFetch fetch; final ArtifactMarkdownBuilder markdownBuilder; final ArtifactExternalOpen openExternal; + final ArtifactFileBridge fileBridge; @override State createState() => _ArtifactViewerPageState(); @@ -228,6 +232,8 @@ class _ArtifactViewerPageState extends State { bytes: _fetched?.bytes, error: _error, status: _status, + fetch: widget.fetch, + fileBridge: widget.fileBridge, onPrevious: () => _step(-1), onNext: () => _step(1), onOpen: plan.resolved == null ? () {} : () => _open(plan.resolved!), diff --git a/app/notes/A3-files.md b/app/notes/A3-files.md new file mode 100644 index 00000000..d14382fc --- /dev/null +++ b/app/notes/A3-files.md @@ -0,0 +1,54 @@ +# A3 — artifact files: download and share + +## Scope + +The selected artifact can be saved or shared as a real file. The external +`Open` and `Copy link` actions stay unchanged; neither is reused as a stand-in +for a file transfer. + +## Implementation + +- `artifact_transfer.dart` is the platform seam with a web implementation and a + stub. The web file uses `dart:js_interop`/`dart:js_interop_unsafe` only, so the + same source compiles to JavaScript and WebAssembly without `package:web`. +- `artifact_transfer_web.dart` builds a `Blob`/`File` from the fetched bytes with + the recorded name and MIME type, downloads through an anchor created for that + name, and shares through `navigator.share` only when the platform can share + files. It never puts the artifact url or a blob page into the user's hands. +- `artifact_file_controller.dart` fetches bytes through the same + `ArtifactFetch` seam the in-app viewer already uses, so the same-origin + credential policy and HTTP status handling apply. One in-flight transfer at a + time; a second activation is ignored. Cancel stops the action from continuing + and a late result is never reported as a completed transfer. +- The selection sheet exposes `Download` and `Share` beside the existing + actions, with honest states for unsupported sharing (download still works), + missing/malformed name or MIME, fetch failure with its HTTP status, and + cancel. Nothing is silently substituted. + +## Evidence + +- Focused suite: 123 artifact tests pass; `flutter analyze` clean. +- Browser probe (`tool/artifact_gallery_probe.mjs`, 32 captures, 27 checks) on + both hosts, dark at 2x and 320 logical px: + - Material and Cupertino `Download` hand the host `report.csv`, `text/csv`, + 23 exact bytes. + - Material and Cupertino `Share` hand the host a `report.csv`, `text/csv`, + 23-byte `File`. + - Existing gallery/viewer checks (recorded rows, duplicate filename, empty vs + unavailable, image in-app, HTTP failure, external artifact never fetched, + 320/2x paging) still pass. + +## Known limits + +- The shared fetch seam has no cancellation token, so Cancel abandons the action + without aborting the HTTP request. The UI never claims the transfer finished. +- OS share sheets and file downloads are web-verified only. Android/iOS + transfer behavior remains unverified until the final build. +- No authenticated production artifact was transferred; the probe uses an + isolated fixture with fixed bytes. + +## Manager note + +The run reached its Code deadline with this tree complete and verified by the +manager: tests, analysis, browser build and the 27-check probe above. Merged +directly rather than replayed. diff --git a/app/test/features/artifacts/actions/artifact_file_actions_test.dart b/app/test/features/artifacts/actions/artifact_file_actions_test.dart new file mode 100644 index 00000000..16a2994e --- /dev/null +++ b/app/test/features/artifacts/actions/artifact_file_actions_test.dart @@ -0,0 +1,403 @@ +import 'dart:typed_data'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/artifacts/actions/artifact_file.dart'; +import 'package:pipelines_app/features/artifacts/actions/artifact_file_actions.dart'; +import 'package:pipelines_app/features/artifacts/actions/artifact_file_bridge.dart'; +import 'package:pipelines_app/features/artifacts/actions/artifact_transfer.dart'; +import 'package:pipelines_app/features/artifacts/domain/artifact_groups.dart'; +import 'package:pipelines_app/features/artifacts/domain/artifact_record.dart'; +import 'package:pipelines_app/features/artifacts/domain/artifact_url.dart'; +import 'package:pipelines_app/features/artifacts/ui/artifact_gallery_page.dart'; +import 'package:pipelines_app/features/artifacts/ui/artifact_visit_list.dart'; +import 'package:pipelines_app/features/artifacts/ui/artifact_viewer_fetch.dart'; +import 'package:pipelines_app/features/artifacts/ui/artifact_viewer_page.dart'; + +import '../domain/artifact_fixtures.dart'; +import '../ui/artifact_visit_list_fixture.dart'; + +const _endpoint = 'ws://127.0.0.1:8081/connect'; +final Uint8List _bytes = Uint8List.fromList([7, 8, 9]); + +final ArtifactRecord _record = ArtifactRecord.fromJson({ + 'name': 'report.csv', + 'url': '/artifacts/1/1/report.csv', + 'content_type': 'text/csv', + 'size_bytes': 3, +}); + +ArtifactFileBridge _bridge({ + List? saved, + List? shared, + bool downloadSupported = true, + bool shareSupported = true, +}) => ArtifactFileBridge( + downloadSupported: downloadSupported, + shareSupported: shareSupported, + downloadUnsupportedMessage: 'No download on this host.', + shareUnsupportedMessage: 'No share on this host.', + download: (file) async { + saved?.add(file); + return ArtifactTransferResult( + ArtifactTransferState.saved, + 'Downloaded ${file.name}.', + ); + }, + share: (file) async { + shared?.add(file); + return const ArtifactTransferResult( + ArtifactTransferState.shared, + 'File shared.', + ); + }, +); + +Future _fetch(Uri uri) async => + ArtifactFetchResult(status: 200, bytes: _bytes); + +Widget _row({ + required bool cupertino, + ArtifactFileBridge? bridge, + ArtifactRecord? artifact, + ArtifactFetch? fetch, +}) { + final actions = ArtifactFileActions( + artifact: artifact ?? _record, + resolved: resolveArtifactUrl(_endpoint, _record.url)!, + fetch: fetch ?? _fetch, + bridge: bridge ?? _bridge(), + ); + return cupertino + ? CupertinoApp( + home: CupertinoPageScaffold( + child: SafeArea( + child: Padding(padding: const EdgeInsets.all(8), child: actions), + ), + ), + ) + : MaterialApp( + home: Scaffold( + body: Padding(padding: const EdgeInsets.all(8), child: actions), + ), + ); +} + +TextButton _materialButton(WidgetTester tester, String label) => + tester.widget( + find + .ancestor(of: find.text(label), matching: find.byType(TextButton)) + .first, + ); + +CupertinoButton _cupertinoButton(WidgetTester tester, String label) => + tester.widget( + find + .ancestor( + of: find.text(label), + matching: find.byType(CupertinoButton), + ) + .first, + ); + +void main() { + testWidgets('Download saves the exact named bytes and reports it', ( + tester, + ) async { + final saved = []; + await tester.pumpWidget( + _row(cupertino: false, bridge: _bridge(saved: saved)), + ); + + await tester.tap(find.text('Download')); + await tester.pumpAndSettle(); + + expect(saved, hasLength(1)); + expect(saved.single.name, 'report.csv'); + expect(saved.single.mimeType, 'text/csv'); + expect(saved.single.bytes, _bytes); + expect(find.text('Downloaded report.csv.'), findsOneWidget); + }); + + testWidgets('Share starts one file transfer, not a link', (tester) async { + final shared = []; + await tester.pumpWidget( + _row(cupertino: false, bridge: _bridge(shared: shared)), + ); + + await tester.tap(find.text('Share')); + await tester.pumpAndSettle(); + + expect(shared.single.name, 'report.csv'); + expect(shared.single.byteLength, 3); + expect(find.text('File shared.'), findsOneWidget); + }); + + testWidgets('unsupported share is explained but download stays enabled', ( + tester, + ) async { + final saved = []; + await tester.pumpWidget( + _row( + cupertino: false, + bridge: _bridge(saved: saved, shareSupported: false), + ), + ); + + expect(find.text('No share on this host.'), findsOneWidget); + expect(_materialButton(tester, 'Share').onPressed, isNull); + expect(_materialButton(tester, 'Download').onPressed, isNotNull); + + await tester.tap(find.text('Download')); + await tester.pumpAndSettle(); + expect(saved, hasLength(1)); + }); + + testWidgets('a slow fetch shows progress and cancel, then reports cancel', ( + tester, + ) async { + await tester.pumpWidget( + _row( + cupertino: false, + bridge: _bridge(), + fetch: (_) => Future.delayed( + const Duration(seconds: 30), + () => ArtifactFetchResult(status: 200, bytes: _bytes), + ), + ), + ); + + await tester.tap(find.text('Download')); + await tester.pump(); + expect(find.text('Preparing file…'), findsOneWidget); + expect(find.byType(CircularProgressIndicator), findsOneWidget); + expect(_materialButton(tester, 'Download').onPressed, isNull); + expect(find.text('Cancel'), findsOneWidget); + + await tester.tap(find.text('Cancel')); + await tester.pump(); + expect(find.text('Download canceled.'), findsOneWidget); + expect(find.text('Cancel'), findsNothing); + await tester.pump(const Duration(seconds: 31)); + }); + + testWidgets('both hosts keep the file actions whole at 320/2x dark', ( + tester, + ) async { + tester.view.physicalSize = const Size(640, 1200); + tester.view.devicePixelRatio = 2; + tester.platformDispatcher.textScaleFactorTestValue = 2; + tester.platformDispatcher.platformBrightnessTestValue = Brightness.dark; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue); + addTearDown(tester.platformDispatcher.clearPlatformBrightnessTestValue); + + for (final cupertino in [false, true]) { + await tester.pumpWidget(_row(cupertino: cupertino)); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + expect(find.text('Download'), findsOneWidget); + expect(find.text('Share'), findsOneWidget); + if (cupertino) { + expect(_cupertinoButton(tester, 'Download').onPressed, isNotNull); + expect(find.byType(TextButton), findsNothing); + } else { + expect(_materialButton(tester, 'Download').onPressed, isNotNull); + expect(find.byType(CupertinoButton), findsNothing); + } + } + }); + + testWidgets('the gallery selection offers both file actions in its dialog', ( + tester, + ) async { + final saved = []; + await tester.pumpWidget( + MaterialApp( + home: ArtifactGalleryPage( + steps: [ + step( + stage: 'review', + visit: 1, + artifacts: [ + artifact('report.csv', contentType: 'text/csv', sizeBytes: 3), + ], + ), + ], + configuredEndpoint: _endpoint, + fetch: _fetch, + fileBridge: _bridge(saved: saved), + ), + ), + ); + await tester.pumpAndSettle(); + + await tester.tap(find.text('report.csv')); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsOneWidget); + expect(find.text('Download'), findsOneWidget); + expect(find.text('Share'), findsOneWidget); + expect(find.text('Open'), findsOneWidget); + expect(find.text('Copy link'), findsOneWidget); + + await tester.tap(find.text('Download')); + await tester.pumpAndSettle(); + expect(saved.single.bytes, _bytes); + expect(find.text('Downloaded report.csv.'), findsOneWidget); + expect(find.byType(AlertDialog), findsOneWidget); + }); + + testWidgets('a host without file capabilities explains and disables both', ( + tester, + ) async { + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Padding( + padding: const EdgeInsets.all(8), + child: ArtifactFileActions( + artifact: _record, + resolved: resolveArtifactUrl(_endpoint, _record.url)!, + fetch: _fetch, + ), + ), + ), + ), + ); + + expect(find.text('Download'), findsOneWidget); + expect(find.text('Share'), findsOneWidget); + expect(_materialButton(tester, 'Download').onPressed, isNull); + expect(_materialButton(tester, 'Share').onPressed, isNull); + expect( + find.text('Downloading files is not supported on this platform yet.'), + findsOneWidget, + ); + expect( + find.text('File sharing is not supported on this platform yet.'), + findsOneWidget, + ); + }); + + testWidgets('gallery selection keeps both actions at 320/2x dark', ( + tester, + ) async { + tester.view.physicalSize = const Size(640, 1200); + tester.view.devicePixelRatio = 2; + tester.platformDispatcher.textScaleFactorTestValue = 2; + tester.platformDispatcher.platformBrightnessTestValue = Brightness.dark; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue); + addTearDown(tester.platformDispatcher.clearPlatformBrightnessTestValue); + + final steps = [ + step( + stage: 'review', + visit: 1, + artifacts: [ + artifact('report.csv', contentType: 'text/csv', sizeBytes: 3), + ], + ), + ]; + for (final cupertino in [false, true]) { + await tester.pumpWidget( + cupertino + ? CupertinoApp( + theme: const CupertinoThemeData(brightness: Brightness.dark), + home: ArtifactGalleryPage( + steps: steps, + configuredEndpoint: _endpoint, + fetch: _fetch, + fileBridge: _bridge(), + ), + ) + : MaterialApp( + theme: ThemeData(brightness: Brightness.dark), + home: ArtifactGalleryPage( + steps: steps, + configuredEndpoint: _endpoint, + fetch: _fetch, + fileBridge: _bridge(), + ), + ), + ); + await tester.pumpAndSettle(); + await tester.tap(find.text('report.csv')); + await tester.pumpAndSettle(); + + expect(tester.takeException(), isNull); + expect(find.text('Download'), findsOneWidget); + expect(find.text('Share'), findsOneWidget); + expect( + cupertino + ? find.byType(CupertinoAlertDialog) + : find.byType(AlertDialog), + findsOneWidget, + ); + await tester.tap(find.text('Close')); + await tester.pumpAndSettle(); + } + }); + + testWidgets( + 'the viewer offers file actions only for a same-origin artifact', + (tester) async { + final local = recordedArtifact( + 'clip.mp4', + url: '/artifacts/1/1/clip.mp4', + contentType: 'video/mp4', + ); + final external = recordedArtifact( + 'elsewhere.png', + url: 'https://elsewhere.test/elsewhere.png', + contentType: 'image/png', + ); + final localGroup = visitGroup(artifacts: [local]); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: ArtifactViewerPage( + key: const ValueKey('local'), + groups: [localGroup], + selectedIdentity: artifactVisitIdentity(localGroup, local), + configuredEndpoint: _endpoint, + fetch: _fetch, + fileBridge: _bridge(), + openExternal: (_) async => true, + ), + ), + ), + ); + await tester.pumpAndSettle(); + + expect(find.text('Download'), findsOneWidget); + expect(find.text('Share'), findsOneWidget); + + final externalGroup = visitGroup(artifacts: [external]); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: ArtifactViewerPage( + key: const ValueKey('external'), + groups: [externalGroup], + selectedIdentity: artifactVisitIdentity(externalGroup, external), + configuredEndpoint: _endpoint, + fetch: _fetch, + fileBridge: _bridge(), + openExternal: (_) async => true, + ), + ), + ), + ); + await tester.pumpAndSettle(); + + expect(find.text('Download'), findsNothing); + expect(find.text('Share'), findsNothing); + expect(find.text('Open'), findsOneWidget); + }, + ); +} diff --git a/app/test/features/artifacts/actions/artifact_file_controller_test.dart b/app/test/features/artifacts/actions/artifact_file_controller_test.dart new file mode 100644 index 00000000..db4b7d1e --- /dev/null +++ b/app/test/features/artifacts/actions/artifact_file_controller_test.dart @@ -0,0 +1,229 @@ +import 'dart:async'; +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/artifacts/actions/artifact_file.dart'; +import 'package:pipelines_app/features/artifacts/actions/artifact_file_bridge.dart'; +import 'package:pipelines_app/features/artifacts/actions/artifact_file_controller.dart'; +import 'package:pipelines_app/features/artifacts/actions/artifact_transfer.dart'; +import 'package:pipelines_app/features/artifacts/domain/artifact_record.dart'; +import 'package:pipelines_app/features/artifacts/domain/artifact_url.dart'; +import 'package:pipelines_app/features/artifacts/ui/artifact_viewer_fetch.dart'; + +const _url = 'http://127.0.0.1:8081/artifacts/1/1/report.csv'; +final Uint8List _bytes = Uint8List.fromList([10, 20, 30, 40]); + +final ArtifactRecord _record = ArtifactRecord.fromJson({ + 'name': 'public/reports/report.csv', + 'url': '/artifacts/1/1/report.csv', + 'content_type': 'text/csv; charset=utf-8', + 'size_bytes': 4, +}); + +ArtifactFileActionsController _controller({ + ArtifactFetch? fetch, + ArtifactFileBridge bridge = const ArtifactFileBridge(), +}) => ArtifactFileActionsController( + artifact: _record, + resolved: resolveArtifactUrl('ws://127.0.0.1:8081/connect', _record.url)!, + fetch: fetch ?? (_) async => ArtifactFetchResult(status: 200, bytes: _bytes), + bridge: bridge, +); + +ArtifactFileBridge _bridge({ + List? saved, + List? shared, + ArtifactTransferResult shareResult = const ArtifactTransferResult( + ArtifactTransferState.shared, + 'File shared.', + ), + bool downloadSupported = true, + bool shareSupported = true, +}) => ArtifactFileBridge( + downloadSupported: downloadSupported, + shareSupported: shareSupported, + downloadUnsupportedMessage: 'No download here.', + shareUnsupportedMessage: 'No share here.', + download: (file) async { + saved?.add(file); + return ArtifactTransferResult( + ArtifactTransferState.saved, + 'Downloaded ${file.name}.', + ); + }, + share: (file) async { + shared?.add(file); + return shareResult; + }, +); + +void main() { + test('download carries the exact named, typed bytes', () async { + final saved = []; + final controller = _controller(bridge: _bridge(saved: saved)); + + await controller.download(); + + expect(saved, hasLength(1)); + expect(saved.single.name, 'report.csv'); + expect(saved.single.mimeType, 'text/csv'); + expect(saved.single.bytes, _bytes); + expect(controller.status, 'Downloaded report.csv.'); + expect(controller.busy, isFalse); + }); + + test('share uses a file, not a link, and reports when shared', () async { + final shared = []; + final fetched = []; + final controller = _controller( + bridge: _bridge(shared: shared), + fetch: (uri) async { + fetched.add(uri); + return ArtifactFetchResult(status: 200, bytes: _bytes); + }, + ); + + await controller.share(); + + expect(fetched, [Uri.parse(_url)]); + expect(shared, hasLength(1)); + expect(shared.single.name, 'report.csv'); + expect(shared.single.mimeType, 'text/csv'); + expect(shared.single.bytes, _bytes); + expect(controller.canShare, isTrue); + expect(controller.status, 'File shared.'); + }); + + test('unsupported sharing leaves download working', () async { + final saved = []; + final shared = []; + var fetches = 0; + final controller = _controller( + fetch: (_) async { + fetches += 1; + return ArtifactFetchResult(status: 200, bytes: _bytes); + }, + bridge: _bridge(saved: saved, shared: shared, shareSupported: false), + ); + + await controller.share(); + expect(shared, isEmpty); + expect(fetches, 0); + expect(controller.status, 'No share here.'); + expect(controller.canDownload, isTrue); + + await controller.download(); + expect(saved, hasLength(1)); + expect(controller.status, 'Downloaded report.csv.'); + }); + + test( + 'an HTTP or network fetch failure is reported, never transferred', + () async { + final saved = []; + final bridge = _bridge(saved: saved); + final notFound = _controller( + fetch: (_) async => + ArtifactFetchResult(status: 404, bytes: Uint8List(0)), + bridge: bridge, + ); + + await notFound.download(); + expect(notFound.status, 'Could not fetch the artifact (HTTP 404).'); + expect(saved, isEmpty); + expect(notFound.busy, isFalse); + + final offline = _controller( + fetch: (_) async => throw const ArtifactFetchException('network down'), + bridge: bridge, + ); + await offline.download(); + expect(offline.status, contains('network down')); + expect(saved, isEmpty); + }, + ); + + test( + 'cancel during a slow fetch starts no transfer and ignores the result', + () async { + final pending = Completer(); + final saved = []; + final controller = _controller( + fetch: (_) => pending.future, + bridge: _bridge(saved: saved), + ); + + final action = controller.download(); + await Future.delayed(Duration.zero); + expect(controller.busy, isTrue); + expect(controller.canCancel, isTrue); + expect(controller.status, 'Preparing file…'); + + controller.cancel(); + expect(controller.busy, isFalse); + expect(controller.status, 'Download canceled.'); + + pending.complete(ArtifactFetchResult(status: 200, bytes: _bytes)); + await action; + expect(saved, isEmpty); + expect(controller.status, 'Download canceled.'); + }, + ); + + test('one tap starts one transfer even when called twice', () async { + var fetches = 0; + final pending = Completer(); + final saved = []; + final controller = _controller( + fetch: (_) { + fetches += 1; + return pending.future; + }, + bridge: _bridge(saved: saved), + ); + + final first = controller.download(); + final second = controller.download(); + await Future.delayed(Duration.zero); + expect(fetches, 1); + + pending.complete(ArtifactFetchResult(status: 200, bytes: _bytes)); + await first; + await second; + expect(saved, hasLength(1)); + }); + + test('a ready share reuses prepared bytes on the fresh tap', () async { + var fetches = 0; + var shares = 0; + final controller = _controller( + fetch: (_) async { + fetches += 1; + return ArtifactFetchResult(status: 200, bytes: _bytes); + }, + bridge: ArtifactFileBridge( + shareSupported: true, + share: (file) async { + shares += 1; + return shares == 1 + ? const ArtifactTransferResult( + ArtifactTransferState.ready, + 'File ready. Tap Share again to choose where to send it.', + ) + : const ArtifactTransferResult( + ArtifactTransferState.shared, + 'File shared.', + ); + }, + ), + ); + + await controller.share(); + expect(controller.status, contains('Tap Share again')); + await controller.share(); + + expect(fetches, 1); + expect(shares, 2); + expect(controller.status, 'File shared.'); + }); +} diff --git a/app/test/features/artifacts/actions/artifact_file_test.dart b/app/test/features/artifacts/actions/artifact_file_test.dart new file mode 100644 index 00000000..8e4c71d0 --- /dev/null +++ b/app/test/features/artifacts/actions/artifact_file_test.dart @@ -0,0 +1,99 @@ +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/artifacts/actions/artifact_file.dart'; +import 'package:pipelines_app/features/artifacts/domain/artifact_record.dart'; + +ArtifactRecord _record( + String name, { + String contentType = '', + String url = '/artifacts/1/1/report.csv', +}) => ArtifactRecord.fromJson({ + 'name': name, + 'url': url, + 'content_type': contentType, + 'size_bytes': 10, +}); + +void main() { + test('a recorded name keeps only its basename', () { + final file = artifactFileFor( + artifact: _record('public/reports/result.csv', contentType: 'text/csv'), + url: Uri.parse('http://127.0.0.1:8081/artifacts/1/1/result.csv'), + bytes: Uint8List.fromList([1, 2, 3]), + ); + + expect(file.name, 'result.csv'); + expect(file.mimeType, 'text/csv'); + expect(file.byteLength, 3); + expect(file.bytes, [1, 2, 3]); + }); + + test( + 'a recorded name with backslashes and control characters is repaired', + () { + final name = artifactFileName( + _record('C:\\tmp\\odd\u0001name.csv'), + Uri.parse('http://127.0.0.1/a.csv'), + ); + + expect(name, 'odd_name.csv'); + }, + ); + + test('a missing name falls back to the url basename then artifact', () { + expect( + artifactFileName( + _record(''), + Uri.parse('http://127.0.0.1:8081/artifacts/1/1/from-url.csv'), + ), + 'from-url.csv', + ); + expect( + artifactFileName(_record('public/'), Uri.parse('http://127.0.0.1/')), + 'artifact', + ); + expect( + artifactFileName(_record('..'), Uri.parse('http://127.0.0.1/')), + 'artifact', + ); + }); + + test('the recorded media type loses parameters and is validated', () { + expect( + artifactFileMimeType( + _record('a.txt', contentType: 'Text/Plain; charset=utf-8'), + ), + 'text/plain', + ); + expect( + artifactFileMimeType(_record('a.bin')), + artifactFileFallbackMimeType, + ); + expect( + artifactFileMimeType(_record('a.bin', contentType: 'not a mime')), + artifactFileFallbackMimeType, + ); + }); + + test('a missing name or MIME type gets an explicit fallback notice', () { + final url = Uri.parse('http://127.0.0.1/artifacts/1/1/kept.csv'); + + expect( + artifactFileRecordingNotice( + _record('kept.csv', contentType: 'text/csv'), + url, + ), + isNull, + ); + expect( + artifactFileRecordingNotice(_record('', contentType: 'text/csv'), url), + 'No usable recorded name; the file is saved as kept.csv.', + ); + expect( + artifactFileRecordingNotice(_record('kept.csv'), url), + 'No usable recorded MIME type; the file is saved as ' + 'application/octet-stream.', + ); + }); +} diff --git a/app/tool/artifact_gallery_probe.dart b/app/tool/artifact_gallery_probe.dart index 3190fa10..c16a24b9 100644 --- a/app/tool/artifact_gallery_probe.dart +++ b/app/tool/artifact_gallery_probe.dart @@ -121,6 +121,24 @@ List _steps(String origin, String state) { }, ]; } + if (state == 'files') { + return [ + { + 'stage': 'reviewer', + 'sequence': 1, + 'status': 'completed', + 'control': {'visit': 1}, + 'artifacts': [ + _file( + 'report.csv', + url: '$origin/fixture/report.csv', + contentType: 'text/csv', + sizeBytes: 23, + ), + ], + }, + ]; + } return [ { 'stage': 'implementer', diff --git a/app/tool/artifact_gallery_probe.mjs b/app/tool/artifact_gallery_probe.mjs index d0e42c4a..6903e981 100644 --- a/app/tool/artifact_gallery_probe.mjs +++ b/app/tool/artifact_gallery_probe.mjs @@ -91,6 +91,7 @@ const probePng = () => { ]); }; const png = probePng(); +const probeCsv = Buffer.from('id,name\n1,alpha\n2,beta\n'); const server = createServer(async (req, res) => { const pathname = decodeURIComponent(new URL(req.url, 'http://localhost').pathname); @@ -100,6 +101,14 @@ const server = createServer(async (req, res) => { res.end('missing artifact\n'); return; } + if (pathname.endsWith('/report.csv')) { + res.writeHead(200, { + 'content-type': 'text/csv', + 'content-length': probeCsv.length, + }); + res.end(probeCsv); + return; + } if (pathname.endsWith('.png')) { res.writeHead(200, { 'content-type': 'image/png' }); res.end(png); @@ -179,6 +188,49 @@ try { })).result.sessionId; await send('Page.enable', {}, session); await send('Runtime.enable', {}, session); + // Record the real bytes the app hands to the OS. The download anchor's + // click is swallowed so headless Chrome never writes into the profile; the + // share function replaces the browser sheet with a recorder. + await send('Page.addScriptToEvaluateOnNewDocument', { + source: `(() => { + const state = { objects: [], downloads: [], shares: [] }; + window.__artifactTransfer = state; + const realCreate = URL.createObjectURL.bind(URL); + URL.createObjectURL = (blob) => { + const url = realCreate(blob); + const entry = { url, type: blob.type, size: blob.size, name: null, bytes: null }; + state.objects.push(entry); + blob.arrayBuffer().then((buffer) => { + entry.bytes = Array.from(new Uint8Array(buffer)); + }); + return url; + }; + HTMLAnchorElement.prototype.click = function () { + state.downloads.push({ name: this.download, href: this.href }); + }; + const navProto = Object.getPrototypeOf(navigator); + Object.defineProperty(navProto, 'share', { + configurable: true, + value: async (data) => { + state.shares.push((data?.files || []).map((file) => { + const entry = { name: file.name, type: file.type, size: file.size, bytes: null }; + file.arrayBuffer().then((buffer) => { + entry.bytes = Array.from(new Uint8Array(buffer)); + }); + return entry; + })); + }, + }); + Object.defineProperty(navProto, 'canShare', { + configurable: true, + value: (data) => Array.isArray(data?.files) && data.files.length > 0, + }); + Object.defineProperty(navProto, 'userActivation', { + configurable: true, + get: () => ({ isActive: true, hasBeenActive: true }), + }); + })();`, + }, session); await send('Browser.grantPermissions', { origin, permissions: ['clipboardReadWrite', 'clipboardSanitizedWrite'], @@ -255,6 +307,23 @@ try { (await send('Target.getTargets')).result.targetInfos.filter( (target) => target.type === 'page', ).length; + const transferState = () => + evaluate(`(() => { + const state = window.__artifactTransfer; + return { + downloads: state.downloads, + objects: state.objects.map(({ url, type, size, name, bytes }) => ({ url, type, size, name, bytes })), + shares: state.shares, + }; + })()`); + const waitForBytes = async (read) => { + for (let i = 0; i < 40; i++) { + const value = await read(); + if (value?.byteLength) return value; + await delay(100); + } + throw new Error('Timed out waiting for transfer bytes'); + }; const capture = async (name, width = 390, height = 844, scale = 1) => { await send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: scale, mobile: width < 600, @@ -591,6 +660,110 @@ try { await openScaled('cupertino', 'a1w-cupertino-2x-320'); evidence.checks.push({ check: 'Cupertino 2x/320 keeps the recorded rows, facts and actions', value: true }); + // File actions: a real same-origin artifact is fetched, then handed to the + // host as a named file. Blob/anchor and navigator.share are intercepted above + // so the evidence is the exact bytes, MIME type and download name, not a + // screenshot of a promise. + const sameBytes = (actual, expected) => + Array.isArray(actual) && + actual.length === expected.length && + actual.every((value, index) => value === expected[index]); + const fileProbe = async (platform, prefix, extra = '') => { + await send('Emulation.setDeviceMetricsOverride', { + width: 390, height: 844, deviceScaleFactor: 1, mobile: true, + }, session); + const before = await targetCount(); + await navigate(galleryView(`&state=files${extra}`, platform), 'Artifacts'); + await clickExact('report.csv'); + await delay(500); + if (!(await hasLabel('Download')) || !(await hasLabel('Share'))) { + throw new Error(`${platform} selection lost its file actions: ${JSON.stringify(await labels())}`); + } + await capture(`${prefix}-files-selected`); + + await clickExact('Download'); + let downloaded; + try { + downloaded = await waitFor(async () => { + const state = await transferState(); + return state.objects[0]?.bytes ? state : null; + }, `${platform} download bytes`); + } catch (error) { + throw new Error( + `${error.message}\nstate=${JSON.stringify(await transferState())}\nbody=${JSON.stringify(await bodyText())}`, + ); + } + const download = downloaded.downloads[0]; + const object = downloaded.objects[0]; + if (downloaded.downloads.length !== 1) { + throw new Error(`${platform} did not request exactly one download: ${JSON.stringify(downloaded)}`); + } + if (download.name !== 'report.csv') { + throw new Error(`${platform} download name was ${JSON.stringify(download.name)}`); + } + if (!download.href.startsWith('blob:')) { + throw new Error(`${platform} download used a non-blob href: ${JSON.stringify(download.href)}`); + } + if (object.type !== 'text/csv' || object.size !== probeCsv.length) { + throw new Error(`${platform} blob was ${object.type}/${object.size}, expected text/csv/${probeCsv.length}`); + } + if (!sameBytes(object.bytes, Array.from(probeCsv))) { + throw new Error(`${platform} download bytes differed from the served artifact`); + } + if (!(await bodyText()).includes('Downloaded report.csv.')) { + throw new Error(`${platform} download did not report its file: ${JSON.stringify(await bodyText())}`); + } + evidence.checks.push({ + check: `${platform} Download hands the host report.csv, text/csv, ${probeCsv.length} exact bytes`, + value: true, + name: download.name, + mime: object.type, + size: object.size, + blob: download.href.startsWith('blob:'), + }); + await capture(`${prefix}-files-downloaded`); + + await clickExact('Share'); + let shared; + try { + shared = await waitFor(async () => { + const state = await transferState(); + return state.shares[0]?.[0]?.bytes ? state : null; + }, `${platform} share file`); + } catch (error) { + throw new Error( + `${error.message}\nstate=${JSON.stringify(await transferState())}\nbody=${JSON.stringify(await bodyText())}`, + ); + } + const file = shared.shares[0]?.[0]; + if (shared.shares.length !== 1 || shared.shares[0].length !== 1) { + throw new Error(`${platform} share received ${JSON.stringify(shared.shares)}`); + } + if (file.name !== 'report.csv' || file.type !== 'text/csv' || file.size !== probeCsv.length) { + throw new Error(`${platform} shared file was ${JSON.stringify(file)}`); + } + if (!sameBytes(file.bytes, Array.from(probeCsv))) { + throw new Error(`${platform} shared bytes differed from the served artifact`); + } + if (!(await bodyText()).includes('File shared.')) { + throw new Error(`${platform} share did not report success: ${JSON.stringify(await bodyText())}`); + } + if ((await targetCount()) !== before) { + throw new Error(`${platform} file actions opened a browser tab`); + } + evidence.checks.push({ + check: `${platform} Share hands the host a report.csv, text/csv, ${probeCsv.length} byte file`, + value: true, + name: file.name, + mime: file.type, + size: file.size, + }); + await capture(`${prefix}-files-shared`); + }; + await fileProbe('material', 'a3-material'); + await fileProbe('cupertino', 'a3-cupertino'); + await fileProbe('cupertino', 'a3-cupertino-dark', '&theme=dark'); + console.log(JSON.stringify(evidence, null, 2)); } finally { ws?.close();