diff --git a/app/lib/features/artifacts/domain/artifact_kind.dart b/app/lib/features/artifacts/domain/artifact_kind.dart index 4282b45e..248e260d 100644 --- a/app/lib/features/artifacts/domain/artifact_kind.dart +++ b/app/lib/features/artifacts/domain/artifact_kind.dart @@ -198,7 +198,16 @@ bool isMarkdownArtifact(String contentType, String name) { /// How the viewer presents an artifact in-app, or [none] when it only offers /// Open/Download. -enum ArtifactPreviewFormat { image, video, markdown, text, table, html, none } +enum ArtifactPreviewFormat { + image, + video, + audio, + markdown, + text, + table, + html, + none, +} /// The one rule for in-app previews, shared by the gallery's paging and the /// viewer's fetch plan. Images and videos come from the content type; markdown @@ -210,6 +219,7 @@ ArtifactPreviewFormat artifactPreviewFormat(String contentType, String name) { if (isVideoContentType(contentType)) return ArtifactPreviewFormat.video; final mime = contentType.split(';').first.trim().toLowerCase(); final ext = _extensionOf(name); + if (mime.startsWith('audio/')) return ArtifactPreviewFormat.audio; if (mime == 'text/markdown' || ext == 'md' || ext == 'markdown') { return ArtifactPreviewFormat.markdown; } diff --git a/app/lib/features/artifacts/domain/artifact_preview.dart b/app/lib/features/artifacts/domain/artifact_preview.dart index 19d804cf..9006361d 100644 --- a/app/lib/features/artifacts/domain/artifact_preview.dart +++ b/app/lib/features/artifacts/domain/artifact_preview.dart @@ -12,6 +12,9 @@ enum ArtifactPreviewKind { /// fetched as bytes, never autoplayed), as the web viewer does. video, + /// A same-origin audio file, played with the shared media controller. + audio, + /// A CSV/TSV drawn as a table from its fetched text. table, @@ -68,13 +71,16 @@ const String artifactPreviewExternalUrl = /// Classifies [artifact] against the configured server origin. /// -/// The format comes from [artifactPreviewFormat]: images are drawn from the +/// The format comes from [format] (the shared [artifactPreviewFormat] unless a +/// caller such as the chat Files panel has its own rule): images are drawn from the /// resolved bytes, a video plays from the resolved url, markdown goes to the /// injected builder and the text family is selectable monospace text. /// Everything else is explicitly unsupported rather than faked. ArtifactPreviewPlan planArtifactPreview({ required ArtifactRecord artifact, required String configuredEndpoint, + ArtifactPreviewFormat Function(String contentType, String name) format = + artifactPreviewFormat, }) { if (!artifact.hasUrl) { return const ArtifactPreviewPlan( @@ -98,12 +104,10 @@ ArtifactPreviewPlan planArtifactPreview({ message: artifactPreviewExternalUrl, ); } - final kind = switch (artifactPreviewFormat( - artifact.contentType, - artifact.name, - )) { + final kind = switch (format(artifact.contentType, artifact.name)) { ArtifactPreviewFormat.image => ArtifactPreviewKind.image, ArtifactPreviewFormat.video => ArtifactPreviewKind.video, + ArtifactPreviewFormat.audio => ArtifactPreviewKind.audio, ArtifactPreviewFormat.markdown => ArtifactPreviewKind.markdown, ArtifactPreviewFormat.text => ArtifactPreviewKind.text, ArtifactPreviewFormat.table => ArtifactPreviewKind.table, diff --git a/app/lib/features/artifacts/ui/artifact_tile.dart b/app/lib/features/artifacts/ui/artifact_tile.dart index 4e1f5ae5..20ff6dcd 100644 --- a/app/lib/features/artifacts/ui/artifact_tile.dart +++ b/app/lib/features/artifacts/ui/artifact_tile.dart @@ -224,6 +224,8 @@ IconData artifactKindIcon(ArtifactRecord artifact, {required bool cupertino}) { cupertino ? CupertinoIcons.photo : Icons.image_outlined, ArtifactPreviewFormat.video => cupertino ? CupertinoIcons.film : Icons.movie_outlined, + ArtifactPreviewFormat.audio => + cupertino ? CupertinoIcons.music_note : Icons.audio_file_outlined, ArtifactPreviewFormat.markdown => cupertino ? CupertinoIcons.doc_text : Icons.article_outlined, ArtifactPreviewFormat.text => diff --git a/app/lib/features/artifacts/ui/artifact_video_player.dart b/app/lib/features/artifacts/ui/artifact_video_player.dart index f7617dfa..526087c2 100644 --- a/app/lib/features/artifacts/ui/artifact_video_player.dart +++ b/app/lib/features/artifacts/ui/artifact_video_player.dart @@ -4,7 +4,7 @@ import 'package:video_player/video_player.dart'; import '../../../ui/adaptive/host.dart'; -/// Creates the player for one video url; tests inject a fake controller. +/// Creates the player for one media url; tests inject a fake controller. typedef ArtifactVideoControllerFactory = VideoPlayerController Function(Uri uri); @@ -13,6 +13,8 @@ VideoPlayerController defaultArtifactVideoController(Uri uri) => const String artifactVideoPlayLabel = 'Play video'; const String artifactVideoPauseLabel = 'Pause video'; +const String artifactAudioPlayLabel = 'Play audio'; +const String artifactAudioPauseLabel = 'Pause audio'; const String artifactVideoError = 'The video could not be played.'; /// Plays one recorded same-origin video in the viewer, as the web viewer's @@ -22,10 +24,12 @@ class ArtifactVideoPlayer extends StatefulWidget { super.key, required this.uri, this.controllerFactory = defaultArtifactVideoController, + this.audio = false, }); final Uri uri; final ArtifactVideoControllerFactory controllerFactory; + final bool audio; @override State createState() => _ArtifactVideoPlayerState(); @@ -95,23 +99,29 @@ class _ArtifactVideoPlayerState extends State { ); } final label = value.isPlaying - ? artifactVideoPauseLabel - : artifactVideoPlayLabel; + ? (widget.audio ? artifactAudioPauseLabel : artifactVideoPauseLabel) + : (widget.audio ? artifactAudioPlayLabel : artifactVideoPlayLabel); final icon = cupertino ? (value.isPlaying ? CupertinoIcons.pause_fill : CupertinoIcons.play_fill) : (value.isPlaying ? Icons.pause : Icons.play_arrow); return Column( - key: const Key('artifact-video'), + key: Key(widget.audio ? 'artifact-audio' : 'artifact-video'), mainAxisSize: MainAxisSize.min, children: [ - Flexible( - child: AspectRatio( - aspectRatio: value.aspectRatio, - child: VideoPlayer(_controller), + if (!widget.audio) + Flexible( + child: AspectRatio( + aspectRatio: value.aspectRatio, + child: VideoPlayer(_controller), + ), + ) + else + const Padding( + padding: EdgeInsets.all(24), + child: Icon(Icons.audio_file_outlined, size: 64), ), - ), Padding( padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), child: Row( diff --git a/app/lib/features/artifacts/ui/artifact_viewer_bar.dart b/app/lib/features/artifacts/ui/artifact_viewer_bar.dart index 57ffeefb..b82adb2e 100644 --- a/app/lib/features/artifacts/ui/artifact_viewer_bar.dart +++ b/app/lib/features/artifacts/ui/artifact_viewer_bar.dart @@ -30,6 +30,7 @@ class ArtifactViewerBar extends StatelessWidget { required this.count, required this.fetch, required this.fileBridge, + this.downloadResolved, required this.onOpen, required this.onCopy, required this.onPrevious, @@ -44,6 +45,7 @@ class ArtifactViewerBar extends StatelessWidget { final int count; final ArtifactFetch fetch; final ArtifactFileBridge fileBridge; + final ResolvedArtifactUrl? downloadResolved; final VoidCallback onOpen; final VoidCallback onCopy; final VoidCallback onPrevious; @@ -123,7 +125,7 @@ class ArtifactViewerBar extends StatelessWidget { '${page.group.visit}\u0000${page.artifact.url}', ), artifact: page.artifact, - resolved: resolved, + resolved: downloadResolved ?? resolved, fetch: fetch, bridge: fileBridge, compact: true, diff --git a/app/lib/features/artifacts/ui/artifact_viewer_body.dart b/app/lib/features/artifacts/ui/artifact_viewer_body.dart index 48f6b9da..c304ee4e 100644 --- a/app/lib/features/artifacts/ui/artifact_viewer_body.dart +++ b/app/lib/features/artifacts/ui/artifact_viewer_body.dart @@ -8,6 +8,7 @@ import '../../../ui/adaptive/floating_bar_layout.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_html_view.dart'; import 'artifact_viewer_bar.dart'; @@ -39,6 +40,7 @@ class ArtifactViewerBody extends StatelessWidget { required this.onCopy, this.fetch = fetchArtifact, this.fileBridge = const ArtifactFileBridge(), + this.downloadResolved, this.text, this.bytes, this.error, @@ -73,6 +75,7 @@ class ArtifactViewerBody extends StatelessWidget { final VoidCallback onCopy; final ArtifactFetch fetch; final ArtifactFileBridge fileBridge; + final ResolvedArtifactUrl? downloadResolved; final String? text; final Uint8List? bytes; final String? error; @@ -138,6 +141,7 @@ class ArtifactViewerBody extends StatelessWidget { count: count, fetch: fetch, fileBridge: fileBridge, + downloadResolved: downloadResolved, onOpen: onOpen, onCopy: onCopy, onPrevious: onPrevious, diff --git a/app/lib/features/artifacts/ui/artifact_viewer_content.dart b/app/lib/features/artifacts/ui/artifact_viewer_content.dart index af00d828..22f5e1e8 100644 --- a/app/lib/features/artifacts/ui/artifact_viewer_content.dart +++ b/app/lib/features/artifacts/ui/artifact_viewer_content.dart @@ -111,6 +111,14 @@ class ArtifactPreviewBody extends StatelessWidget { controllerFactory: videoControllerFactory, ), ); + case ArtifactPreviewKind.audio: + return Center( + child: ArtifactVideoPlayer( + uri: plan.resolved!.uri, + controllerFactory: videoControllerFactory, + audio: true, + ), + ); case ArtifactPreviewKind.unsupported: case ArtifactPreviewKind.unavailable: return const SizedBox.shrink(); diff --git a/app/lib/features/artifacts/ui/artifact_viewer_page.dart b/app/lib/features/artifacts/ui/artifact_viewer_page.dart index 519224ef..f5afe1e0 100644 --- a/app/lib/features/artifacts/ui/artifact_viewer_page.dart +++ b/app/lib/features/artifacts/ui/artifact_viewer_page.dart @@ -7,6 +7,7 @@ import '../../../ui/input/arrow_key_pager.dart'; import 'artifact_selection_facts.dart'; import '../actions/artifact_file_bridge.dart'; import '../domain/artifact_groups.dart'; +import '../domain/artifact_kind.dart'; import '../domain/artifact_preview.dart'; import '../domain/artifact_preview_failure.dart'; import '../domain/artifact_url.dart'; @@ -43,6 +44,8 @@ class ArtifactViewerPage extends StatefulWidget { required this.selectedIdentity, this.includeExternalDocuments = false, this.configuredEndpoint = '', + this.downloadUrl, + this.previewFormat = artifactPreviewFormat, this.fetch = fetchArtifact, this.markdownBuilder = defaultArtifactMarkdown, this.openExternal = openArtifactExternally, @@ -60,6 +63,11 @@ class ArtifactViewerPage extends StatefulWidget { final bool includeExternalDocuments; final String configuredEndpoint; + final String? downloadUrl; + + /// The preview rule; the Files panel passes its own (every HTML previews). + final ArtifactPreviewFormat Function(String contentType, String name) + previewFormat; final ArtifactFetch fetch; final ArtifactMarkdownBuilder markdownBuilder; final ArtifactExternalOpen openExternal; @@ -110,6 +118,7 @@ class _ArtifactViewerPageState extends State return planArtifactPreview( artifact: page.artifact, configuredEndpoint: widget.configuredEndpoint, + format: widget.previewFormat, ); } @@ -224,6 +233,9 @@ class _ArtifactViewerPageState extends State Widget buildFrame(BuildContext context, {required bool fullscreen}) { final page = _page; final plan = _plan; + final downloadResolved = widget.downloadUrl == null + ? null + : resolveArtifactUrl(widget.configuredEndpoint, widget.downloadUrl!); final title = page == null ? artifactViewerTitle : artifactDisplayName(page.artifact); @@ -266,6 +278,7 @@ class _ArtifactViewerPageState extends State status: _status, fetch: widget.fetch, fileBridge: widget.fileBridge, + downloadResolved: downloadResolved, onPrevious: () => _step(-1), onNext: () => _step(1), // A failure is never cached, so loading again fetches afresh. diff --git a/app/lib/features/chat/files/files_controller.dart b/app/lib/features/chat/files/files_controller.dart index c4bc614f..1791cc50 100644 --- a/app/lib/features/chat/files/files_controller.dart +++ b/app/lib/features/chat/files/files_controller.dart @@ -47,7 +47,7 @@ class FilesController extends ChangeNotifier { filter = ''; } catch (e) { if (_disposed || request != _request) return; - error = '$e'; + error = "Couldn't load this folder."; } finally { if (!_disposed && request == _request) { loading = false; diff --git a/app/lib/features/chat/files/files_details.dart b/app/lib/features/chat/files/files_details.dart new file mode 100644 index 00000000..e5068ad0 --- /dev/null +++ b/app/lib/features/chat/files/files_details.dart @@ -0,0 +1,98 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import '../../../ui/adaptive/host.dart'; +import '../../artifacts/actions/artifact_transfer.dart'; +import '../../artifacts/domain/artifact_kind.dart'; +import '../../artifacts/ui/artifact_external_open.dart'; +import '../data/directory_listing.dart'; +import 'files_download.dart'; +import 'files_models.dart'; +import 'files_preview.dart'; +import 'files_urls.dart'; + +/// Details and host-native actions for a file the embedded viewer cannot show. +void showFileDetails( + BuildContext context, { + required DirectoryEntry entry, + required FileUrls? urls, + required Future Function()? download, + required ArtifactExternalOpen openExternal, +}) { + final cupertino = usesCupertinoHost(context); + Widget content(BuildContext sheet) { + Future open() async { + var opened = false; + try { + opened = await openExternal(urls!.view); + } catch (_) { + /* keep the sheet and download action available */ + } + if (opened && sheet.mounted) Navigator.pop(sheet); + } + + final body = SafeArea( + child: Padding( + padding: const EdgeInsets.all(20), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + entry.name, + style: cupertino + ? CupertinoTheme.of(sheet).textTheme.navTitleTextStyle + : Theme.of(sheet).textTheme.titleLarge, + ), + const SizedBox(height: 12), + Text( + '${artifactKindLabel(artifactKind(fileContentType(entry.name), entry.name))} · ${fileSizeLabel(entry.size)}', + ), + Text('Modified: ${fileModifiedLabel(entry.modified)}'), + const SizedBox(height: 8), + Text( + urls == null + ? 'No server address is configured, so this file cannot be fetched.' + : 'This file type cannot be previewed here.', + ), + const SizedBox(height: 16), + if (download != null) FileDownloadButton(download: download), + if (urls != null) + cupertino + ? CupertinoButton( + onPressed: open, + child: const Text('Open externally'), + ) + : TextButton.icon( + onPressed: open, + icon: const Icon(Icons.open_in_new), + label: const Text('Open externally'), + ), + if (cupertino) + CupertinoButton( + onPressed: () => Navigator.pop(sheet), + child: const Text('Close'), + ), + ], + ), + ), + ); + return cupertino + ? CupertinoPopupSurface( + child: DefaultTextStyle( + style: CupertinoTheme.of(sheet).textTheme.textStyle, + child: body, + ), + ) + : body; + } + + if (cupertino) { + showCupertinoModalPopup(context: context, builder: content); + } else { + showModalBottomSheet( + context: context, + showDragHandle: true, + builder: content, + ); + } +} diff --git a/app/lib/features/chat/files/files_download.dart b/app/lib/features/chat/files/files_download.dart new file mode 100644 index 00000000..bdad75d3 --- /dev/null +++ b/app/lib/features/chat/files/files_download.dart @@ -0,0 +1,141 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/cupertino.dart'; +import '../../../ui/adaptive/host.dart'; +import 'package:flutter/material.dart'; +import 'package:url_launcher/url_launcher.dart'; + +import '../../artifacts/actions/artifact_file.dart'; +import '../../artifacts/actions/artifact_file_bridge.dart'; +import '../../artifacts/actions/artifact_transfer.dart'; +import '../../artifacts/ui/artifact_viewer_fetch.dart'; +import '../data/directory_listing.dart'; +import 'files_preview.dart'; +import 'files_urls.dart'; + +const String fileDownloadFailed = 'Could not download the file. Try again.'; + +/// Opens an attachment url in the browser (web only); tests inject a recorder. +typedef FileUrlLauncher = Future Function(Uri url); + +Future launchFileUrl(Uri url) => + launchUrl(url, mode: LaunchMode.externalApplication); + +/// Downloads one working-directory file. +/// +/// On the web the browser handles the `download=1` url itself: the attachment +/// disposition makes it save the file with its own name, so no bytes pass +/// through the app. Everywhere else the bytes are fetched from the inline url +/// and handed to the host through the artifact file bridge (system "Save as"), +/// exactly as an artifact download is. +Future downloadFile({ + required DirectoryEntry entry, + required FileUrls urls, + ArtifactFileBridge bridge = const ArtifactFileBridge(), + ArtifactFetch fetch = fetchArtifact, + FileUrlLauncher launch = launchFileUrl, +}) async { + try { + if (kIsWeb) { + final opened = await launch(urls.download); + return opened + ? ArtifactTransferResult( + ArtifactTransferState.saved, + 'Downloading ${entry.name}.', + ) + : const ArtifactTransferResult( + ArtifactTransferState.failed, + fileDownloadFailed, + ); + } + final ArtifactFetchResult result; + try { + result = await fetch(urls.view); + } on ArtifactFetchException { + return const ArtifactTransferResult( + ArtifactTransferState.failed, + fileDownloadFailed, + ); + } + if (!result.ok) { + return const ArtifactTransferResult( + ArtifactTransferState.failed, + fileDownloadFailed, + ); + } + return await bridge.saveFile( + ArtifactFile( + name: entry.name, + mimeType: fileContentType(entry.name), + bytes: result.bytes, + ), + ); + } catch (_) { + return const ArtifactTransferResult( + ArtifactTransferState.failed, + fileDownloadFailed, + ); + } +} + +/// The Download button of the unviewable-file sheet, with its outcome below. +class FileDownloadButton extends StatefulWidget { + const FileDownloadButton({super.key, required this.download}); + + /// Runs the transfer; the sheet's owner binds the entry, urls and bridge. + final Future Function() download; + + @override + State createState() => _FileDownloadButtonState(); +} + +class _FileDownloadButtonState extends State { + bool _busy = false; + String? _status; + + Future _download() async { + if (_busy) return; + setState(() { + _busy = true; + _status = null; + }); + String status; + try { + status = (await widget.download()).message; + } catch (_) { + status = fileDownloadFailed; + } + if (!mounted) return; + setState(() { + _busy = false; + _status = status.isEmpty ? null : status; + }); + } + + @override + Widget build(BuildContext context) => Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (usesCupertinoHost(context)) + CupertinoButton.filled( + onPressed: _busy ? null : _download, + child: _busy + ? const CupertinoActivityIndicator() + : const Text('Download'), + ) + else + FilledButton.icon( + onPressed: _busy ? null : _download, + icon: _busy + ? const SizedBox( + width: 18, + height: 18, + child: CircularProgressIndicator(strokeWidth: 2), + ) + : const Icon(Icons.download_outlined), + label: const Text('Download'), + ), + if (_status != null) + Padding(padding: const EdgeInsets.only(top: 8), child: Text(_status!)), + ], + ); +} diff --git a/app/lib/features/chat/files/files_header.dart b/app/lib/features/chat/files/files_header.dart new file mode 100644 index 00000000..122e710f --- /dev/null +++ b/app/lib/features/chat/files/files_header.dart @@ -0,0 +1,137 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import '../../../ui/layout/app_overflow_menu.dart'; +import '../data/directory_listing.dart'; +import '../ui/sessions/chat_adaptive.dart'; +import 'files_controller.dart'; +import 'files_models.dart'; + +class FilesHeader extends StatelessWidget { + const FilesHeader({ + super.key, + required this.controller, + required this.filter, + }); + final FilesController controller; + final TextEditingController filter; + @override + Widget build(BuildContext context) { + final listing = controller.listing; + return Padding( + padding: const EdgeInsets.fromLTRB(12, 8, 8, 4), + child: Column( + children: [ + Row( + children: [ + if (listing?.parent != null) + IconButton( + tooltip: 'Back', + onPressed: controller.loading + ? null + : () => controller.open(listing!.parent), + icon: const Icon(Icons.arrow_back), + ), + Expanded( + child: Text( + homeRelativeLabel( + listing?.home ?? '', + listing?.path ?? controller.initialPath, + ), + overflow: TextOverflow.ellipsis, + ), + ), + IconButton( + tooltip: 'Refresh', + onPressed: controller.loading ? null : controller.retry, + icon: const Icon(Icons.refresh), + ), + IconButton( + tooltip: controller.view == FilesViewMode.list + ? 'Grid view' + : 'List view', + onPressed: () => controller.setView( + controller.view == FilesViewMode.list + ? FilesViewMode.grid + : FilesViewMode.list, + ), + icon: Icon( + controller.view == FilesViewMode.list + ? Icons.grid_view + : Icons.view_list, + ), + ), + AppOverflowMenu( + label: 'Sort', + onSelected: (_, key) => + controller.setSort(controller.sort.reverseOr(key)), + actions: [ + for (final key in FilesSortKey.values) + AppMenuAction( + value: key, + label: + '${key.name}${controller.sort.key == key ? (controller.sort.ascending ? ' ↑' : ' ↓') : ''}', + ), + ], + ), + ], + ), + if (listing != null) + SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: Row( + children: [ + for (final crumb in folderCrumbs(listing.home, listing.path)) + chatControlsStyleOf(context) == ChatControlsStyle.cupertino + ? CupertinoButton( + padding: const EdgeInsets.symmetric(horizontal: 6), + onPressed: controller.loading + ? null + : () => controller.open(crumb.path), + child: Text(crumb.label), + ) + : TextButton( + onPressed: controller.loading + ? null + : () => controller.open(crumb.path), + child: Text(crumb.label), + ), + ], + ), + ), + Row( + children: [ + Expanded( + child: + chatControlsStyleOf(context) == ChatControlsStyle.cupertino + ? CupertinoSearchTextField( + controller: filter, + onChanged: controller.setFilter, + placeholder: 'Filter files', + ) + : TextField( + controller: filter, + onChanged: controller.setFilter, + decoration: const InputDecoration( + prefixIcon: Icon(Icons.search), + hintText: 'Filter files', + isDense: true, + ), + ), + ), + IconButton( + tooltip: 'Show hidden files', + onPressed: () => + controller.toggleHidden(!controller.showHidden), + icon: Icon( + controller.showHidden + ? Icons.visibility + : Icons.visibility_off, + ), + ), + ], + ), + ], + ), + ); + } +} diff --git a/app/lib/features/chat/files/files_icons.dart b/app/lib/features/chat/files/files_icons.dart index 8fb19f8b..318adc56 100644 --- a/app/lib/features/chat/files/files_icons.dart +++ b/app/lib/features/chat/files/files_icons.dart @@ -1,12 +1,13 @@ import 'package:flutter/material.dart'; import '../../artifacts/domain/artifact_kind.dart'; import '../data/directory_listing.dart'; +import 'files_preview.dart'; /// Chooses the same broad kind glyphs used by the artifact gallery. IconData fileIcon(DirectoryEntry entry) { if (entry.isDir) return Icons.folder_outlined; - switch (artifactKind('', entry.name)) { + switch (artifactKind(fileContentType(entry.name), entry.name)) { case ArtifactKind.image: return Icons.image_outlined; case ArtifactKind.video: diff --git a/app/lib/features/chat/files/files_models.dart b/app/lib/features/chat/files/files_models.dart index 8bbb1bf6..b6d146ec 100644 --- a/app/lib/features/chat/files/files_models.dart +++ b/app/lib/features/chat/files/files_models.dart @@ -1,4 +1,5 @@ import '../data/directory_listing.dart'; +import 'files_preview.dart'; import '../../artifacts/domain/artifact_kind.dart'; enum FilesViewMode { list, grid } @@ -39,14 +40,15 @@ List sortFileEntries( return result; } -String fileKind(DirectoryEntry entry) => - entry.isDir ? 'Folder' : artifactKind('', entry.name).name; +String fileKind(DirectoryEntry entry) => entry.isDir + ? 'Folder' + : artifactKind(fileContentType(entry.name), entry.name).name; String fileSizeLabel(int? size) { if (size == null) return '—'; if (size < 1024) return '$size B'; final units = ['KiB', 'MiB', 'GiB', 'TiB']; - var value = size.toDouble(); + var value = size / 1024; var unit = 0; while (value >= 1024 && unit < units.length - 1) { value /= 1024; @@ -54,3 +56,12 @@ String fileSizeLabel(int? size) { } return '${value.toStringAsFixed(value >= 10 ? 0 : 1)} ${units[unit]}'; } + +/// A compact local timestamp; keep missing or malformed values unobtrusive. +String fileModifiedLabel(String? value) { + final date = DateTime.tryParse(value ?? '')?.toLocal(); + if (date == null) return 'Unknown'; + String two(int n) => n.toString().padLeft(2, '0'); + return '${date.year}-${two(date.month)}-${two(date.day)} ' + '${two(date.hour)}:${two(date.minute)}'; +} diff --git a/app/lib/features/chat/files/files_panel.dart b/app/lib/features/chat/files/files_panel.dart index 9a1d8622..0a57236d 100644 --- a/app/lib/features/chat/files/files_panel.dart +++ b/app/lib/features/chat/files/files_panel.dart @@ -1,10 +1,14 @@ -import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; +import '../../../core/transport/pipelines_client.dart'; import '../data/directory_listing.dart'; import '../ui/sessions/chat_adaptive.dart'; import 'files_controller.dart'; import 'files_icons.dart'; import 'files_models.dart'; +import 'files_thumbnail.dart'; +import 'files_viewer.dart'; +import 'files_header.dart'; +import '../../../ui/layout/app_overflow_menu.dart'; const double filesPanelMinWidth = 280; const double filesPanelMaxWidth = 420; @@ -13,10 +17,21 @@ const double filesPanelFraction = .30; double filesPanelWidth(double available) => (available * filesPanelFraction) .clamp(filesPanelMinWidth, filesPanelMaxWidth); +/// The two explicit actions of a file's row or tile menu. +enum FileAction { open, download } + class FilesPanel extends StatefulWidget { - const FilesPanel({super.key, required this.controller, this.onOpen}); + const FilesPanel({ + super.key, + required this.controller, + this.onOpen, + this.viewer = const FilesViewer(), + }); final FilesController controller; final ValueChanged? onOpen; + + /// Opens and downloads files; tests inject one that never fetches. + final FilesViewer viewer; @override State createState() => _FilesPanelState(); } @@ -24,6 +39,7 @@ class FilesPanel extends StatefulWidget { class _FilesPanelState extends State { late final TextEditingController _filter = TextEditingController(); FilesController get controller => widget.controller; + String get _endpoint => configuredGatewayEndpoint(controller.gateway); @override void initState() { super.initState(); @@ -32,7 +48,10 @@ class _FilesPanelState extends State { } void _changed() { - if (mounted) setState(() {}); + if (mounted) { + if (_filter.text != controller.filter) _filter.text = controller.filter; + setState(() {}); + } } @override @@ -45,6 +64,7 @@ class _FilesPanelState extends State { @override Widget build(BuildContext context) { final listing = controller.listing; + final entries = controller.entries; if (controller.missingDirectory) { return const _FilesMessage('This chat has no working directory.'); } @@ -52,7 +72,7 @@ class _FilesPanelState extends State { color: Theme.of(context).colorScheme.surface, child: Column( children: [ - _header(context, listing), + FilesHeader(controller: controller, filter: _filter), if (controller.error != null) ChatErrorNotice( message: controller.error!, @@ -60,13 +80,19 @@ class _FilesPanelState extends State { ), if (controller.loading && listing == null) const Expanded(child: ChatLoadingIndicator()) - else if (listing != null && - controller.entries.isEmpty && - !controller.loading) - const Expanded(child: _FilesMessage('This folder is empty.')) + else if (listing != null && entries.isEmpty && !controller.loading) + Expanded( + child: _FilesMessage( + controller.filter.isEmpty + ? 'This folder is empty.' + : 'No files match your filter.', + ), + ) else Expanded( - child: controller.view == FilesViewMode.grid ? _grid() : _list(), + child: controller.view == FilesViewMode.grid + ? _grid(entries) + : _list(entries), ), if (listing?.truncated == true) const Padding( @@ -78,137 +104,55 @@ class _FilesPanelState extends State { ); } - Widget _header(BuildContext context, DirectoryListing? listing) => Padding( - padding: const EdgeInsets.fromLTRB(12, 8, 8, 4), - child: Column( - children: [ - Row( - children: [ - if (listing?.parent != null) - IconButton( - tooltip: 'Back', - onPressed: controller.loading - ? null - : () => controller.open(listing!.parent), - icon: const Icon(Icons.arrow_back), - ), - Expanded( - child: Text( - homeRelativeLabel( - listing?.home ?? '', - listing?.path ?? controller.initialPath, - ), - overflow: TextOverflow.ellipsis, - ), - ), - IconButton( - tooltip: 'Refresh', - onPressed: controller.loading ? null : controller.retry, - icon: const Icon(Icons.refresh), - ), - IconButton( - tooltip: controller.view == FilesViewMode.list - ? 'Grid view' - : 'List view', - onPressed: () => controller.setView( - controller.view == FilesViewMode.list - ? FilesViewMode.grid - : FilesViewMode.list, - ), - icon: Icon( - controller.view == FilesViewMode.list - ? Icons.grid_view - : Icons.view_list, - ), - ), - PopupMenuButton( - initialValue: controller.sort.key, - tooltip: 'Sort', - onSelected: (key) => - controller.setSort(controller.sort.reverseOr(key)), - itemBuilder: (_) => [ - for (final key in FilesSortKey.values) - PopupMenuItem(value: key, child: Text(key.name)), - ], - ), - ], - ), - Row( - children: [ - Expanded( - child: chatControlsStyleOf(context) == ChatControlsStyle.cupertino - ? CupertinoSearchTextField( - controller: _filter, - onChanged: controller.setFilter, - placeholder: 'Filter files', - ) - : TextField( - controller: _filter, - onChanged: controller.setFilter, - decoration: const InputDecoration( - prefixIcon: Icon(Icons.search), - hintText: 'Filter files', - isDense: true, - ), - ), - ), - IconButton( - tooltip: 'Show hidden files', - onPressed: () => controller.toggleHidden(!controller.showHidden), - icon: Icon( - controller.showHidden ? Icons.visibility : Icons.visibility_off, - ), - ), - ], - ), - ], - ), - ); - - Widget _list() => ListView.builder( - itemCount: controller.entries.length, + Widget _list(List entries) => ListView.builder( + itemCount: entries.length, itemBuilder: (_, index) { - final entry = controller.entries[index]; + final entry = entries[index]; return ListTile( - onTap: () => entry.isDir - ? controller.open(entry.path) - : widget.onOpen?.call(entry), - leading: Icon( - fileIcon(entry), - ), - title: Text(entry.name), + onTap: () => entry.isDir ? controller.open(entry.path) : _open(entry), + leading: Icon(fileIcon(entry)), + title: Text(entry.name, maxLines: 2, overflow: TextOverflow.ellipsis), subtitle: Text( entry.isDir ? 'Folder' - : '${entry.modified ?? 'Unknown'} · ${fileSizeLabel(entry.size)}', + : '${fileModifiedLabel(entry.modified)} · ${fileSizeLabel(entry.size)}', ), - trailing: entry.isDir ? null : Text(fileKind(entry)), + trailing: entry.isDir + ? null + : Row( + mainAxisSize: MainAxisSize.min, + children: [Text(fileKind(entry)), _menu(entry)], + ), ); }, ); - Widget _grid() => GridView.builder( + Widget _grid(List entries) => GridView.builder( padding: const EdgeInsets.all(12), gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent( maxCrossAxisExtent: 180, - childAspectRatio: 1.25, + childAspectRatio: .85, ), - itemCount: controller.entries.length, + itemCount: entries.length, itemBuilder: (_, index) { - final entry = controller.entries[index]; + final entry = entries[index]; return InkWell( - onTap: () => entry.isDir - ? controller.open(entry.path) - : widget.onOpen?.call(entry), + onTap: () => entry.isDir ? controller.open(entry.path) : _open(entry), child: Card( child: Padding( padding: const EdgeInsets.all(12), child: Column( - mainAxisAlignment: MainAxisAlignment.center, children: [ - Icon( - fileIcon(entry), - size: 32, + Align( + alignment: Alignment.centerRight, + child: entry.isDir + ? const SizedBox(height: 48) + : _menu(entry), + ), + Expanded( + child: Center( + child: FileThumbnail(entry: entry, endpoint: _endpoint), + ), ), const SizedBox(height: 8), Text( @@ -224,6 +168,32 @@ class _FilesPanelState extends State { ); }, ); + + /// Open and Download for one file; a folder has no menu (nothing to save). + Widget _menu(DirectoryEntry entry) => AppOverflowMenu( + label: 'File actions', + sheetTitle: entry.name, + onSelected: (_, action) => switch (action) { + FileAction.open => _open(entry), + FileAction.download => widget.viewer.download( + context, + endpoint: _endpoint, + entry: entry, + ), + }, + actions: const [ + AppMenuAction(value: FileAction.open, label: 'Open'), + AppMenuAction(value: FileAction.download, label: 'Download'), + ], + ); + + void _open(DirectoryEntry entry) { + if (widget.onOpen != null) { + widget.onOpen!(entry); + } else { + widget.viewer.open(context, endpoint: _endpoint, entry: entry); + } + } } class _FilesMessage extends StatelessWidget { diff --git a/app/lib/features/chat/files/files_preview.dart b/app/lib/features/chat/files/files_preview.dart new file mode 100644 index 00000000..ae243be1 --- /dev/null +++ b/app/lib/features/chat/files/files_preview.dart @@ -0,0 +1,72 @@ +import '../../artifacts/domain/artifact_kind.dart'; + +/// The media type the files endpoint serves for [name], from its extension. +/// +/// The server sets the real `Content-Type` on the wire; this is the client's +/// own classification for choosing a viewer, a thumbnail and a download type. +String fileContentType(String name) { + final dot = name.lastIndexOf('.'); + final ext = dot == -1 ? '' : name.substring(dot + 1).toLowerCase(); + return _types[ext] ?? 'application/octet-stream'; +} + +const Map _types = { + 'svg': 'image/svg+xml', + 'ico': 'image/x-icon', + 'bmp': 'image/bmp', + 'avif': 'image/avif', + 'dart': 'text/plain', + 'png': 'image/png', + 'jpg': 'image/jpeg', + 'jpeg': 'image/jpeg', + 'gif': 'image/gif', + 'webp': 'image/webp', + 'mp4': 'video/mp4', + 'webm': 'video/webm', + 'mov': 'video/quicktime', + 'mp3': 'audio/mpeg', + 'wav': 'audio/wav', + 'm4a': 'audio/mp4', + 'pdf': 'application/pdf', + 'json': 'application/json', + 'csv': 'text/csv', + 'tsv': 'text/tab-separated-values', + 'html': 'text/html', + 'htm': 'text/html', + 'md': 'text/markdown', + 'markdown': 'text/markdown', + 'txt': 'text/plain', + 'log': 'text/plain', + 'zip': 'application/zip', + 'gz': 'application/gzip', + 'tar': 'application/x-tar', +}; + +/// How the Files panel's viewer presents [name]. +/// +/// Unlike the artifact gallery, which keeps a turn's `session.html` export (and +/// its repairs) external-only, every HTML document in a working directory +/// previews inertly here: a file called `session.html` in a folder is just a +/// web page. Everything else follows the shared [artifactPreviewFormat] rule. +ArtifactPreviewFormat filePreviewFormat(String contentType, String name) { + final mime = contentType.split(';').first.trim().toLowerCase(); + final lower = name.toLowerCase(); + if (mime == 'image/svg+xml' || + mime == 'text/html' || + lower.endsWith('.html') || + lower.endsWith('.htm')) { + return ArtifactPreviewFormat.html; + } + return artifactPreviewFormat(contentType, name); +} + +/// Whether the Files panel opens [name] in the in-app viewer rather than the +/// unviewable sheet (PDFs open externally and are not previewable here). +bool isPreviewableFile(String name) => + filePreviewFormat(fileContentType(name), name) != + ArtifactPreviewFormat.none; + +/// Whether [name] is an image the grid draws as a thumbnail. +bool isThumbnailFile(String name) => + filePreviewFormat(fileContentType(name), name) == + ArtifactPreviewFormat.image; diff --git a/app/lib/features/chat/files/files_thumbnail.dart b/app/lib/features/chat/files/files_thumbnail.dart new file mode 100644 index 00000000..7d2ddd49 --- /dev/null +++ b/app/lib/features/chat/files/files_thumbnail.dart @@ -0,0 +1,95 @@ +import 'package:flutter/material.dart'; + +import '../data/directory_listing.dart'; +import 'files_icons.dart'; +import 'files_preview.dart'; +import 'files_urls.dart'; + +/// The logical size of a grid thumbnail. +const double filesThumbnailSize = 56; + +/// The largest decode scale a thumbnail is allowed, so a 4x display still +/// decodes a 56 dp tile to at most 224 px per side. +const double filesThumbnailMaxScale = 4; + +/// The pixel edge a thumbnail decodes to: the tile size at the display's pixel +/// ratio, bounded. The shared [PaintingBinding.imageCache] then holds a few +/// hundred KiB at most per image instead of a full-size decode. +int filesThumbnailDecodeSize(double devicePixelRatio) => + (filesThumbnailSize * devicePixelRatio.clamp(1, filesThumbnailMaxScale)) + .round(); + +/// A grid tile's picture: an image file's own bytes from the files endpoint, +/// decoded at tile size, with the kind glyph while loading and when the fetch +/// or decode fails. Non-image files show the kind glyph. +class FileThumbnail extends StatefulWidget { + const FileThumbnail({super.key, required this.entry, required this.endpoint}); + + final DirectoryEntry entry; + final String endpoint; + + @override + State createState() => _FileThumbnailState(); +} + +class _FileThumbnailState extends State { + ImageProvider? _provider; + String? _url; + int? _decode; + + // Keep the shared image cache unchanged. Scrolled-out thumbnails release + // their decoded cache entry, bounding retention to the lazily built tiles. + @override + void dispose() { + _provider?.evict(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final entry = widget.entry; + final endpoint = widget.endpoint; + final icon = Icon(fileIcon(entry), size: 32); + if (entry.isDir || !isThumbnailFile(entry.name)) return icon; + final urls = resolveFileUrls(endpoint, entry.path); + if (urls == null) return icon; + final decode = filesThumbnailDecodeSize( + MediaQuery.devicePixelRatioOf(context), + ); + if (_url != urls.view.toString() || _decode != decode) { + _provider?.evict(); + _url = urls.view.toString(); + _decode = decode; + _provider = ResizeImage.resizeIfNeeded( + decode, + decode, + NetworkImage(_url!), + ); + } + final scheme = Theme.of(context).colorScheme; + final placeholder = Container( + width: filesThumbnailSize, + height: filesThumbnailSize, + alignment: Alignment.center, + decoration: BoxDecoration( + color: scheme.surfaceContainerHighest, + borderRadius: BorderRadius.circular(6), + ), + child: icon, + ); + return ClipRRect( + borderRadius: BorderRadius.circular(6), + child: Image( + image: _provider!, + width: filesThumbnailSize, + height: filesThumbnailSize, + fit: BoxFit.cover, + + semanticLabel: entry.name, + loadingBuilder: (_, child, progress) => + progress == null ? child : placeholder, + errorBuilder: (_, _, _) => icon, + ), + ); + } +} diff --git a/app/lib/features/chat/files/files_urls.dart b/app/lib/features/chat/files/files_urls.dart new file mode 100644 index 00000000..0daf3544 --- /dev/null +++ b/app/lib/features/chat/files/files_urls.dart @@ -0,0 +1,48 @@ +import '../../../core/transport/server_url.dart'; + +class FileUrls { + const FileUrls({required this.view, required this.download}); + + /// `GET /files?path=...`: the file inline, with its content type and ranges. + final Uri view; + + /// The same file with `download=1`: an attachment disposition. + final Uri download; +} + +/// Resolves the files endpoint URLs for one working-directory path. +typedef FileUrlResolver = + FileUrls? Function(String configuredEndpoint, String path); + +/// The resolver the Files panel uses for thumbnails, viewing and downloads. +/// +/// Production keeps [fileUrls]. The full-app capture fixture +/// (`tool/search_selection_probe_entry.dart`, `?files=1`) swaps in a resolver +/// whose urls point to bundled capture files, because its static server has no `/files` +/// route; widget tests swap in one that ignores the fake gateway's missing +/// endpoint. Restore it after a test. +FileUrlResolver resolveFileUrls = fileUrls; + +/// Builds the two same-origin HTTP URLs used by the files endpoint. +FileUrls? fileUrls(String configuredEndpoint, String path) { + final value = path; + if (value.trim().isEmpty) return null; + try { + final endpoint = ServerUrl.validate(configuredEndpoint); + final base = Uri.parse( + endpoint.httpUrl, + ).replace(path: '/files', query: null, fragment: null); + Uri make({required bool download}) => base.replace( + queryParameters: { + 'path': value, + if (download) 'download': '1', + }, + ); + return FileUrls( + view: make(download: false), + download: make(download: true), + ); + } on FormatException { + return null; + } +} diff --git a/app/lib/features/chat/files/files_viewer.dart b/app/lib/features/chat/files/files_viewer.dart new file mode 100644 index 00000000..4f80e8f1 --- /dev/null +++ b/app/lib/features/chat/files/files_viewer.dart @@ -0,0 +1,158 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../ui/adaptive/host.dart'; +import '../../artifacts/actions/artifact_file_bridge.dart'; +import '../../artifacts/actions/artifact_transfer.dart'; +import '../../artifacts/domain/artifact_groups.dart'; +import '../../artifacts/domain/artifact_kind.dart'; +import '../../artifacts/domain/artifact_record.dart'; +import '../../artifacts/domain/gallery_navigation.dart'; +import '../../artifacts/ui/artifact_external_open.dart'; +import '../../artifacts/ui/artifact_viewer_fetch.dart'; +import '../../artifacts/ui/artifact_viewer_page.dart'; +import '../data/directory_listing.dart'; +import 'files_download.dart'; +import 'files_details.dart'; +import 'files_preview.dart'; +import 'files_urls.dart'; + +/// Opens and downloads one working-directory file from the Files panel. +/// +/// Previewable files (images, video, audio, markdown, text, tables, HTML) open +/// in the shared artifact viewer over the inline `/files` url; a PDF goes to +/// the host's external handler; anything else gets a sheet with Download and +/// Open externally. The host capabilities are injectable so tests never fetch. +class FilesViewer { + const FilesViewer({ + this.bridge = const ArtifactFileBridge(), + this.fetch = fetchArtifact, + this.openExternal = openArtifactExternally, + this.launch = launchFileUrl, + }); + + final ArtifactFileBridge bridge; + final ArtifactFetch fetch; + final ArtifactExternalOpen openExternal; + final FileUrlLauncher launch; + + Future open( + BuildContext context, { + required String endpoint, + required DirectoryEntry entry, + }) async { + final urls = resolveFileUrls(endpoint, entry.path); + if (urls == null) { + _showSheet(context, entry, null); + return; + } + final type = fileContentType(entry.name); + if (artifactKind(type, entry.name) == ArtifactKind.pdf) { + var opened = false; + try { + opened = await openExternal(urls.view); + } catch (_) { + /* show fallback actions below */ + } + if (!opened && context.mounted) _showSheet(context, entry, urls); + return; + } + if (!isPreviewableFile(entry.name)) { + _showSheet(context, entry, urls); + return; + } + final artifact = ArtifactRecord( + name: entry.name, + url: urls.view.toString(), + contentType: type, + sizeBytes: entry.size ?? 0, + raw: const {}, + ); + final group = ArtifactGroup( + stageKey: 'Files', + visit: 1, + artifacts: [artifact], + ); + final page = ArtifactViewerPage( + groups: [group], + selectedIdentity: artifactVisitIdentityOf(group, artifact), + configuredEndpoint: endpoint, + downloadUrl: urls.download.toString(), + previewFormat: filePreviewFormat, + fetch: fetch, + openExternal: openExternal, + fileBridge: bridge, + ); + if (!context.mounted) return; + Navigator.of(context).push( + usesCupertinoHost(context) + ? CupertinoPageRoute(builder: (_) => page) + : MaterialPageRoute(builder: (_) => page), + ); + } + + /// Downloads [entry] straight from a row or tile menu and reports the + /// outcome (a snack bar, or an alert for a failure on a host without one); + /// without urls the sheet explains instead. + Future download( + BuildContext context, { + required String endpoint, + required DirectoryEntry entry, + }) async { + final urls = resolveFileUrls(endpoint, entry.path); + if (urls == null) { + _showSheet(context, entry, null); + return; + } + final messenger = ScaffoldMessenger.maybeOf(context); + final result = await _download(entry, urls); + if (result.message.isEmpty) return; + if (messenger != null) { + messenger.showSnackBar(SnackBar(content: Text(result.message))); + return; + } + // A Cupertino host has no snack bar; a failure still has to be said. + if (result.state != ArtifactTransferState.failed || !context.mounted) { + return; + } + await showAdaptiveDialog( + context: context, + builder: (dialog) => AlertDialog.adaptive( + title: Text(entry.name), + content: Text(result.message), + actions: [ + if (usesCupertinoHost(dialog)) + CupertinoDialogAction( + onPressed: () => Navigator.pop(dialog), + child: const Text('OK'), + ) + else + TextButton( + onPressed: () => Navigator.pop(dialog), + child: const Text('OK'), + ), + ], + ), + ); + } + + Future _download( + DirectoryEntry entry, + FileUrls urls, + ) => downloadFile( + entry: entry, + urls: urls, + bridge: bridge, + fetch: fetch, + launch: launch, + ); + + void _showSheet(BuildContext context, DirectoryEntry entry, FileUrls? urls) => + showFileDetails( + context, + entry: entry, + urls: urls, + download: urls == null ? null : () => _download(entry, urls), + openExternal: openExternal, + ); +} diff --git a/app/test/features/artifacts/domain/artifact_kind_test.dart b/app/test/features/artifacts/domain/artifact_kind_test.dart index 9a6d66e7..f92ba9f7 100644 --- a/app/test/features/artifacts/domain/artifact_kind_test.dart +++ b/app/test/features/artifacts/domain/artifact_kind_test.dart @@ -113,6 +113,10 @@ void main() { artifactPreviewFormat('text/html', 'report.html'), ArtifactPreviewFormat.html, ); + expect( + artifactPreviewFormat('audio/mpeg', 'recording.mp3'), + ArtifactPreviewFormat.audio, + ); expect( artifactPreviewFormat('', 'session-repair-3-ab12.html'), ArtifactPreviewFormat.none, diff --git a/app/test/features/chat/files/files_panel_test.dart b/app/test/features/chat/files/files_panel_test.dart new file mode 100644 index 00000000..109ed4f1 --- /dev/null +++ b/app/test/features/chat/files/files_panel_test.dart @@ -0,0 +1,280 @@ +import 'dart:convert'; +import 'package:flutter/material.dart'; +import 'package:flutter/cupertino.dart'; +import 'package:pipelines_app/features/chat/files/files_preview.dart'; +import 'package:pipelines_app/features/artifacts/domain/artifact_kind.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/core/transport/pipelines_client.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/ui/artifact_viewer_fetch.dart'; +import 'package:pipelines_app/features/artifacts/ui/artifact_viewer_page.dart'; +import 'package:pipelines_app/features/chat/files/files_controller.dart'; +import 'package:pipelines_app/features/chat/files/files_models.dart'; +import 'package:pipelines_app/features/chat/files/files_panel.dart'; +import 'package:pipelines_app/features/chat/files/files_thumbnail.dart'; +import 'package:pipelines_app/features/chat/files/files_urls.dart'; +import 'package:pipelines_app/features/chat/files/files_viewer.dart'; + +class Gateway extends PipelinesClient { + @override + Uri get endpoint => Uri.parse('ws://example.test/connect'); + bool fail = false; + @override + Stream get frames => const Stream.empty(); + @override + Future call(String type, [JsonMap fields = const {}]) async { + if (fail) throw StateError('internal transport secret'); + return { + 'directory_listing': { + 'path': '/home/demo', + 'home': '/home', + 'entries': [ + for (final name in [ + 'notes.txt', + 'picture.png', + 'archive.zip', + 'report.pdf', + ]) + {'name': name, 'path': '/home/demo/$name', 'size': 1234}, + ], + }, + }; + } +} + +void main() { + late FileUrlResolver original; + setUp(() { + original = resolveFileUrls; + resolveFileUrls = (_, path) => fileUrls('ws://example.test/connect', path); + }); + tearDown(() => resolveFileUrls = original); + Future pump( + WidgetTester tester, { + Gateway? gateway, + FilesViewer? viewer, + }) async { + final controller = FilesController( + gateway: gateway ?? Gateway(), + initialPath: '/home/demo', + ); + addTearDown(controller.dispose); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: FilesPanel( + controller: controller, + viewer: viewer ?? const FilesViewer(), + ), + ), + ), + ); + await tester.pumpAndSettle(); + return controller; + } + + testWidgets('text tap opens shared viewer and fetches inline URL', ( + tester, + ) async { + Uri? fetched; + await pump( + tester, + viewer: FilesViewer( + fetch: (url) async { + fetched = url; + return ArtifactFetchResult( + status: 200, + bytes: utf8.encode('A text file preview'), + ); + }, + ), + ); + await tester.tap(find.text('notes.txt')); + await tester.pumpAndSettle(); + expect(find.byType(ArtifactViewerPage), findsOneWidget); + expect(find.text('A text file preview'), findsOneWidget); + expect(fetched?.queryParameters['path'], '/home/demo/notes.txt'); + expect(fetched?.queryParameters.containsKey('download'), isFalse); + }); + testWidgets('image tap opens shared image viewer', (tester) async { + await pump( + tester, + viewer: FilesViewer( + fetch: (_) async => ArtifactFetchResult( + status: 200, + bytes: base64Decode( + 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==', + ), + ), + ), + ); + await tester.tap(find.text('picture.png')); + await tester.pumpAndSettle(); + expect(find.byType(ArtifactViewerPage), findsOneWidget); + expect(find.byType(Image), findsWidgets); + }); + testWidgets('unknown file has metadata and a working download', ( + tester, + ) async { + String? saved; + await pump( + tester, + viewer: FilesViewer( + fetch: (_) async => + ArtifactFetchResult(status: 200, bytes: utf8.encode('bytes')), + bridge: ArtifactFileBridge( + download: (file) async { + saved = file.name; + return const ArtifactTransferResult( + ArtifactTransferState.saved, + 'Saved file.', + ); + }, + ), + ), + ); + await tester.tap(find.text('archive.zip')); + await tester.pumpAndSettle(); + expect( + find.text('This file type cannot be previewed here.'), + findsOneWidget, + ); + await tester.tap(find.text('Download')); + await tester.pumpAndSettle(); + expect(saved, 'archive.zip'); + expect(find.text('Saved file.'), findsOneWidget); + }); + for (final grid in [false, true]) { + testWidgets( + '${grid ? 'grid' : 'list'} PDF menu downloads without opening', + (tester) async { + String? saved; + var opened = false; + final controller = await pump( + tester, + viewer: FilesViewer( + fetch: (_) async => ArtifactFetchResult( + status: 200, + bytes: utf8.encode('pdf bytes'), + ), + openExternal: (_) async { + opened = true; + return true; + }, + bridge: ArtifactFileBridge( + download: (file) async { + saved = file.name; + return const ArtifactTransferResult( + ArtifactTransferState.saved, + 'Saved', + ); + }, + ), + ), + ); + if (grid) { + controller.setView(FilesViewMode.grid); + await tester.pumpAndSettle(); + } + await tester.tap(find.byTooltip('File actions').last); + await tester.pumpAndSettle(); + expect(find.text('Open'), findsOneWidget); + await tester.tap(find.text('Download')); + await tester.pumpAndSettle(); + expect(saved, 'report.pdf'); + expect(opened, isFalse); + expect(tester.takeException(), isNull); + }, + ); + } + testWidgets('thumbnail error falls back to icon and decode stays bounded', ( + tester, + ) async { + final controller = await pump(tester); + controller.setView(FilesViewMode.grid); + await tester.pumpAndSettle(); + expect(find.byType(FileThumbnail), findsNWidgets(4)); + expect(find.byIcon(Icons.image_outlined), findsOneWidget); + expect(filesThumbnailDecodeSize(10), 224); + expect(tester.takeException(), isNull); + }); + testWidgets('Cupertino unknown file and menu use native controls', ( + tester, + ) async { + final controller = FilesController( + gateway: Gateway(), + initialPath: '/home/demo', + ); + addTearDown(controller.dispose); + await tester.pumpWidget( + CupertinoApp( + home: CupertinoPageScaffold(child: FilesPanel(controller: controller)), + ), + ); + await tester.pumpAndSettle(); + await tester.tap(find.text('archive.zip')); + await tester.pumpAndSettle(); + expect(find.text('Download'), findsOneWidget); + expect(find.byType(CupertinoButton), findsWidgets); + expect(tester.takeException(), isNull); + }); + testWidgets('PDF external-open failures keep download available', ( + tester, + ) async { + await pump( + tester, + viewer: FilesViewer( + openExternal: (_) async => throw StateError('no handler'), + ), + ); + await tester.tap(find.text('report.pdf')); + await tester.pumpAndSettle(); + expect(find.text('Download'), findsOneWidget); + expect(tester.takeException(), isNull); + }); + testWidgets('download thrown host errors become feedback', (tester) async { + await pump( + tester, + viewer: FilesViewer( + fetch: (_) async => + ArtifactFetchResult(status: 200, bytes: utf8.encode('bytes')), + bridge: ArtifactFileBridge( + download: (_) async => throw StateError('host failure'), + ), + ), + ); + await tester.tap(find.byTooltip('File actions').last); + await tester.pumpAndSettle(); + await tester.tap(find.text('Download')); + await tester.pumpAndSettle(); + expect( + find.text('Could not download the file. Try again.'), + findsOneWidget, + ); + expect(tester.takeException(), isNull); + }); + test('file-specific HTML previews preserve artifact export exclusions', () { + expect( + filePreviewFormat('text/html', 'session.html'), + ArtifactPreviewFormat.html, + ); + expect( + artifactPreviewFormat('text/html', 'session.html'), + ArtifactPreviewFormat.none, + ); + expect( + filePreviewFormat('image/svg+xml', 'icon.svg'), + ArtifactPreviewFormat.html, + ); + expect(fileContentType('code.dart'), 'text/plain'); + expect(fileSizeLabel(1024), '1.0 KiB'); + expect(fileSizeLabel(1024 * 1024), '1.0 MiB'); + }); + testWidgets('folder errors hide technical detail', (tester) async { + await pump(tester, gateway: Gateway()..fail = true); + expect(find.text("Couldn't load this folder."), findsOneWidget); + expect(find.textContaining('internal transport'), findsNothing); + }); +} diff --git a/app/test/features/chat/files/files_urls_test.dart b/app/test/features/chat/files/files_urls_test.dart new file mode 100644 index 00000000..97ecc45b --- /dev/null +++ b/app/test/features/chat/files/files_urls_test.dart @@ -0,0 +1,27 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/chat/files/files_urls.dart'; + +void main() { + test('resolves view and attachment urls with encoded paths', () { + final urls = fileUrls( + 'ws://example.test:8081/connect?old=1', + '~/My folder/naïve file.txt', + ); + expect(urls, isNotNull); + expect(urls!.view.path, '/files'); + expect(urls.view.queryParameters['path'], '~/My folder/naïve file.txt'); + expect(urls.view.toString(), contains('My+folder')); + expect(urls.view.toString(), contains('na%C3%AFve+file.txt')); + expect(urls.download.queryParameters['download'], '1'); + }); + + test('preserves whitespace in actual filenames', () { + final urls = fileUrls('ws://example.test/connect', '/home/file.txt '); + expect(urls!.view.queryParameters['path'], '/home/file.txt '); + }); + + test('rejects a missing or invalid endpoint', () { + expect(fileUrls('', '/tmp/a.txt'), isNull); + expect(fileUrls('http://example.test/connect', '/tmp/a.txt'), isNull); + }); +} diff --git a/app/tool/capture/README.md b/app/tool/capture/README.md index cff65da4..258e6ceb 100644 --- a/app/tool/capture/README.md +++ b/app/tool/capture/README.md @@ -132,3 +132,20 @@ content kind and expects the offset to move: node tool/capture/capture.mjs --build build/probe-app --out /tmp/review/chat-wheel \ --script tool/capture/examples/chat-wheel-scroll.json ``` + +## Chat file explorer + +Use `--params 'chats=2&files=1' open=/chat/bench-0 click=Files` to open a +populated explorer (the fixture always answers `list_directory`). `files=1` +redirects view/download URLs to same-origin static fixture files; production +continues to use `/files`. After building the probe, copy the fixtures: + +```sh +mkdir -p build/probe-app/capture-files +cp tool/capture/fixtures/files/* build/probe-app/capture-files/ +``` + +The tree has an assets subfolder, a hidden folder, PNG/JPEG miniatures, text, +JSON, CSV, PDF, archive, log and video entries. Image/text/table/archive files +have bundled bytes; PDF and video entries demonstrate type labels and menus +only. Use the real server for their external handlers and playback acceptance. diff --git a/app/tool/capture/fixtures/files/archive.zip b/app/tool/capture/fixtures/files/archive.zip new file mode 100644 index 00000000..9fc2a958 Binary files /dev/null and b/app/tool/capture/fixtures/files/archive.zip differ diff --git a/app/tool/capture/fixtures/files/config.json b/app/tool/capture/fixtures/files/config.json new file mode 100644 index 00000000..32dfb7fc --- /dev/null +++ b/app/tool/capture/fixtures/files/config.json @@ -0,0 +1 @@ +{"release":"1.0","ready":true} diff --git a/app/tool/capture/fixtures/files/design.png b/app/tool/capture/fixtures/files/design.png new file mode 100644 index 00000000..a70af616 Binary files /dev/null and b/app/tool/capture/fixtures/files/design.png differ diff --git a/app/tool/capture/fixtures/files/icon.jpg b/app/tool/capture/fixtures/files/icon.jpg new file mode 100644 index 00000000..27612e04 Binary files /dev/null and b/app/tool/capture/fixtures/files/icon.jpg differ diff --git a/app/tool/capture/fixtures/files/metrics.csv b/app/tool/capture/fixtures/files/metrics.csv new file mode 100644 index 00000000..98e247ab --- /dev/null +++ b/app/tool/capture/fixtures/files/metrics.csv @@ -0,0 +1,3 @@ +section,files +Images,2 +Documents,4 diff --git a/app/tool/capture/fixtures/files/release.md b/app/tool/capture/fixtures/files/release.md new file mode 100644 index 00000000..77c16d08 --- /dev/null +++ b/app/tool/capture/fixtures/files/release.md @@ -0,0 +1,6 @@ +# Release notes + +The explorer now previews files and saves downloads. + +- Open a file to inspect it. +- Use the file menu to download it. diff --git a/app/tool/probe_files_fixture.dart b/app/tool/probe_files_fixture.dart new file mode 100644 index 00000000..212df60a --- /dev/null +++ b/app/tool/probe_files_fixture.dart @@ -0,0 +1,63 @@ +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/chat/files/files_urls.dart'; + +/// A static, two-level explorer fixture. Its files live in capture/fixtures/files. +JsonMap probeFilesReply(JsonMap request) { + final fields = request['list_directory'] as Map?; + final path = '${fields?['path'] ?? '/srv/probe/release'}'; + final nested = path.endsWith('/assets'); + final entries = nested + ? <(String, int)>[('design.png', 18432), ('icon.jpg', 23000)] + : <(String, int)>[ + ('design.png', 18432), + ('icon.jpg', 23000), + ('release.md', 640), + ('config.json', 220), + ('metrics.csv', 88), + ('report.pdf', 45000), + ('archive.zip', 85000), + ('server.log', 12582912), + ('demo.mp4', 8000000), + ]; + return { + 'id': request['id'], + 'type': 'directory_listing', + 'directory_listing': { + 'path': path, + 'home': '/workspace', + 'parent': nested + ? path.substring(0, path.lastIndexOf('/')) + : '/workspace', + 'entries': [ + if (!nested) ...[ + {'name': 'assets', 'path': '$path/assets', 'is_dir': true}, + { + 'name': '.config', + 'path': '$path/.config', + 'is_dir': true, + 'hidden': true, + }, + ], + for (final (name, size) in entries) + { + 'name': name, + 'path': '$path/$name', + 'is_dir': false, + 'size': size, + 'modified': '2026-11-07T00:00:00Z', + }, + ], + }, + }; +} + +void installFilesFixture() { + resolveFileUrls = (_, path) { + final name = Uri.encodeComponent(path.split('/').last); + final view = Uri.base.resolve('/capture-files/$name'); + return FileUrls( + view: view, + download: view.replace(queryParameters: {'download': '1'}), + ); + }; +} diff --git a/app/tool/search_selection_probe_entry.dart b/app/tool/search_selection_probe_entry.dart index 783d9101..6b2d8d6a 100644 --- a/app/tool/search_selection_probe_entry.dart +++ b/app/tool/search_selection_probe_entry.dart @@ -34,6 +34,7 @@ import 'perf/chat_question_fixture.dart'; import 'perf/chat_scroll_fixture.dart'; import 'perf/perf_fixture.dart'; import 'probe_folder_fixture.dart'; +import 'probe_files_fixture.dart'; import 'probe_usage_fixture.dart'; /// The run every run-scoped hit names. Its recorded sequences are deliberately @@ -469,6 +470,8 @@ JsonMap? probeReply(JsonMap request) { final perf = perfChatReply(request); if (perf != null) return perf; switch (type) { + case 'list_directory': + return probeFilesReply(request); case 'subscribe': case 'unsubscribe': return null; @@ -726,6 +729,7 @@ void main() { return; } configurePerfFixture(params); + if (params['files'] == '1') installFilesFixture(); // `?font=inter` chooses a font as Settings would; otherwise the stored one. final font = params['font']; unawaited( diff --git a/docs/notes/files-panel.md b/docs/notes/files-panel.md index f1b8adfc..a5ba5de2 100644 --- a/docs/notes/files-panel.md +++ b/docs/notes/files-panel.md @@ -13,3 +13,23 @@ Server side: absolute or `~`-prefixed and are resolved through the operator home directory; cleaned paths and symlinks must stay inside that home subtree. Directories, special files and escape paths are refused. Add `download=1` for attachment disposition. + +## Viewing and downloads + +Files now open in the shared artifact viewer (images, SVG icons in an inert +HTML frame, text/code, markdown, JSON, tables, HTML, audio and video). PDFs open +through the platform handler. Unknown files show metadata and host-native Open +externally/Download actions. Every file has separate Open and Download menu +items, including PDFs; folders have neither. Downloads reuse the artifact +save bridge on native platforms and attachment URLs on web. Viewer downloads +also use attachment URLs. + +Image tiles decode at 56 logical pixels (maximum scale 4), show a loading +placeholder and error glyph, and evict decoded cache entries when scrolled out. +Sorting runs once per panel rebuild. Breadcrumbs navigate to ancestors; filters +stay synchronized with folder navigation, and filtered empty states differ from +empty folders. Sizes use binary units and mtimes use compact local timestamps. + +The capture fixture uses `files=1`; see app/tool/capture/README.md for bundling +its static files. PDF/video fixture entries only show types/menus and do not +provide playable sample bytes.