The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
fix(mobile): open terminal media previews in the app
tony7e965438ff5c
diff --git a/mobile/ios/Runner/Info.plist b/mobile/ios/Runner/Info.plistindex 01f93bad8..b6a985b4c 100644--- a/mobile/ios/Runner/Info.plist+++ b/mobile/ios/Runner/Info.plist@@ -57,6 +57,12 @@OS, so there is no Speech Recognition permission to ask for. --><key>NSMicrophoneUsageDescription</key><string>Talk to an agent in a terminal instead of typing.</string>+ <!-- Save Image and Save Video in the share sheet of a terminal's media+ preview (`phone/media_preview_page.dart`). Adding to the library is all+ it does, and iOS ends the app at that button when this string is+ missing. Reading the library still needs none — see the camera's note. -->+ <key>NSPhotoLibraryAddUsageDescription</key>+ <string>Save pictures and videos from an agent to your photo library.</string><key>UIApplicationSceneManifest</key><dict><key>UIApplicationSupportsMultipleScenes</key>diff --git a/mobile/lib/phone/media_preview_page.dart b/mobile/lib/phone/media_preview_page.dartnew file mode 100644index 000000000..be4b754a4--- /dev/null+++ b/mobile/lib/phone/media_preview_page.dart@@ -0,0 +1,286 @@+import 'dart:async';+import 'dart:io';++import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:lucide_icons_flutter/lucide_icons.dart';+import 'package:path/path.dart' as p;+import 'package:share_plus/share_plus.dart';+import 'package:video_player/video_player.dart';++import 'package:harness_mobile/shared/theme/app_theme.dart';+import 'package:harness_mobile/terminal/terminal_links.dart';++import 'phone_navigation.dart';+import 'tty.dart';+import 'tty_controls.dart';++/// Opens [path] — a picture or video an agent printed, already downloaded to this phone — full+/// screen over the page [context] is on. Back, or Android's back button, returns to it.+///+/// A picture's page cannot be dragged away from the left edge: the horizontal drag belongs to the+/// zoomed picture's pan, the reason the agent pager gives up the gesture too (see `phoneRoute`).+/// A video has nothing competing for it, so it keeps the edge swipe every other page has.+Future<void> openMediaPreview(BuildContext context, String path) =>+ Navigator.of(context).push(+ phoneRoute(+ (_) => MediaPreviewPage(path: path),+ swipeToGoBack: isVideoPath(path),+ ),+ );++/// The most a picture is decoded to along either side, in pixels. A preview can be up to 512 MB+/// (`remoteMediaMaxBytes`), and a picture that large decoded at full size is gigabytes of pixels —+/// enough for the OS to end the app. 4096 still leaves a phone screen room to zoom in a few times+/// before the picture softens.+const _maxDecodedSide = 4096;++/// What a program printed and the phone downloaded, shown in the app: a picture to pinch and pan,+/// or a video that a tap plays and pauses. Back and Share above it, and nothing else.+///+/// ⚠️ **In the app, never handed to another one.** `url_launcher` opens `file:` URLs on desktop+/// platforms only: iOS refuses them, and Android has no FileProvider here to pass one through, so+/// the terminal's media links used to end in "Could not open this preview" every time. Share is+/// how the file leaves — Save Image, Save to Files and AirDrop on iOS, the chooser on Android.+class MediaPreviewPage extends StatefulWidget {+ const MediaPreviewPage({+ super.key,+ required this.path,+ this.share,+ this.controller,+ });++ /// The downloaded copy on this phone, not the path on the agent's machine.+ final String path;++ /// Stands in for the share sheet in tests. Null opens the platform's.+ final Future<void> Function(ShareParams params)? share;++ /// Stands in for the video player in tests. Null plays [path]. Unused for a picture.+ final VideoPlayerController? controller;++ @override+ State<MediaPreviewPage> createState() => _MediaPreviewPageState();+}++class _MediaPreviewPageState extends State<MediaPreviewPage> {+ late final bool _isVideo = isVideoPath(widget.path);++ /// Bounded by [_maxDecodedSide] on the way in, keeping its shape, and never enlarged.+ late final ImageProvider _image = ResizeImage(+ FileImage(File(widget.path)),+ width: _maxDecodedSide,+ height: _maxDecodedSide,+ policy: ResizeImagePolicy.fit,+ allowUpscaling: false,+ );++ VideoPlayerController? _video;+ bool _videoReady = false;+ bool _videoFailed = false;++ /// Whether a share sheet asked for is still up. A second tap while it opens would ask for a+ /// second sheet: iOS refuses to present one over the other, and Android stacks two choosers.+ bool _sharing = false;++ @override+ void initState() {+ super.initState();+ if (_isVideo) {+ final video =+ widget.controller ?? VideoPlayerController.file(File(widget.path));+ _video = video..addListener(_onVideo);+ unawaited(_start(video));+ }+ }++ Future<void> _start(VideoPlayerController video) async {+ try {+ await video.initialize();+ if (!mounted) return;+ setState(() => _videoReady = true);+ await video.play();+ } catch (_) {+ // A format this phone cannot play (mkv and avi on iOS, say), or a file that is not a video+ // at all: said on the page, with Share still there to send the file somewhere that can.+ if (mounted) setState(() => _videoFailed = true);+ }+ }++ /// A player can also fail AFTER it has started — a file that turns out to be cut short — and+ /// says so only in its value.+ void _onVideo() {+ if (_videoFailed || !mounted || _video?.value.hasError != true) return;+ setState(() => _videoFailed = true);+ }++ @override+ void dispose() {+ _video?.removeListener(_onVideo);+ if (widget.controller == null) unawaited(_video?.dispose());+ // Out of the app's shared image cache as the page goes: every download has a path of its own+ // (`RemoteMediaDownloader`), so nothing will ask for these pixels again, and up to 64 MB of+ // them would otherwise sit there until the cache filled up.+ if (!_isVideo) unawaited(_image.evict());+ super.dispose();+ }++ /// A tap pauses, plays, or — at the end — plays it again.+ void _toggle() {+ final video = _video;+ if (video == null || !_videoReady || _videoFailed) return;+ final value = video.value;+ if (value.isPlaying) {+ unawaited(video.pause());+ } else {+ if (value.position >= value.duration) {+ unawaited(video.seekTo(Duration.zero));+ }+ unawaited(video.play());+ }+ }++ /// The share sheet with the file, anchored to [origin] — the Share button — for an iPad, where+ /// it is a popover.+ Future<void> _share(Rect? origin) async {+ if (_sharing) return;+ _sharing = true;+ try {+ await (widget.share ?? _platformShare)(+ ShareParams(files: [XFile(widget.path)], sharePositionOrigin: origin),+ );+ } catch (_) {+ // No share sheet came up: the preview is still here, and Share can be pressed again.+ } finally {+ _sharing = false;+ }+ }++ static Future<void> _platformShare(ShareParams params) async {+ await SharePlus.instance.share(params);+ }++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ final tty = Tty.of(context);+ return Scaffold(+ backgroundColor: tty.ground,+ // Nothing here is typed into. The terminal's keyboard can still be on its way down as this+ // page slides in, and keeping clear of it would make the picture jump as it falls.+ resizeToAvoidBottomInset: false,+ body: SafeArea(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Row(+ children: [+ TtyBackButton(+ onPressed: () => Navigator.of(context).maybePop(),+ ),+ const Spacer(),+ _ShareButton(onShare: (origin) => unawaited(_share(origin))),+ ],+ ),+ Expanded(child: _isVideo ? _videoView(tty) : _imageView(tty)),+ ],+ ),+ ),+ );+ }++ /// The picture, fitted to the screen, pinched and panned from there.+ ///+ /// The zoom wraps the decoded picture only — [Image.frameBuilder] is not called for the error —+ /// so a picture that cannot be decoded is a still sentence, not one that can be pinched.+ Widget _imageView(Tty tty) => Image(+ image: _image,+ fit: BoxFit.contain,+ semanticLabel: p.basename(widget.path),+ frameBuilder: (context, child, frame, synchronous) => InteractiveViewer(+ // Never smaller than fitted: there is nothing to see in a picture shrunk below the screen.+ minScale: 1,+ // Far enough to read a screenshot's small print.+ maxScale: 6,+ child: child,+ ),+ errorBuilder: (context, error, stack) => _failure(tty),+ );++ Widget _videoView(Tty tty) {+ final video = _video!;+ if (_videoFailed) return _failure(tty);+ // Opening it is a moment on a file already on the phone: nothing is drawn meanwhile.+ if (!_videoReady) return const SizedBox.shrink();+ return Semantics(+ label: p.basename(widget.path),+ child: GestureDetector(+ key: const ValueKey('media-preview-video'),+ // The whole page under the bar takes the tap, not only the video's own box: a landscape+ // video on a phone held upright leaves most of the screen above and below it.+ behavior: HitTestBehavior.opaque,+ onTap: _toggle,+ child: Center(+ child: AspectRatio(+ aspectRatio: video.value.aspectRatio,+ child: VideoPlayer(video),+ ),+ ),+ ),+ );+ }++ /// The opener's own words for a preview that will not open.+ Widget _failure(Tty tty) => Center(+ child: Padding(+ padding: const EdgeInsets.symmetric(horizontal: Tty.origin),+ child: Text(+ 'Could not open this preview.',+ textAlign: TextAlign.center,+ style: tty.style(color: tty.faint, size: TtySize.row),+ ),+ ),+ );+}++/// Share, the back chevron's box mirrored: the same touch target, the glyph on the right gutter.+class _ShareButton extends StatelessWidget {+ const _ShareButton({required this.onShare});++ /// Called with the button's own rectangle on screen, the share sheet's anchor on an iPad.+ final void Function(Rect? origin) onShare;++ @override+ Widget build(BuildContext context) {+ final tty = Tty.of(context);+ return Semantics(+ button: true,+ label: 'Share',+ excludeSemantics: true,+ child: GestureDetector(+ key: const ValueKey('media-preview-share'),+ behavior: HitTestBehavior.opaque,+ onTap: () {+ HapticFeedback.selectionClick();+ final box = context.findRenderObject() as RenderBox?;+ onShare(+ box == null || !box.attached+ ? null+ : box.localToGlobal(Offset.zero) & box.size,+ );+ },+ child: SizedBox(+ width: 52,+ height: 44,+ child: Padding(+ padding: const EdgeInsets.only(right: Tty.origin - 2),+ child: Align(+ alignment: Alignment.centerRight,+ child: Icon(LucideIcons.share300, size: 21, color: tty.text),+ ),+ ),+ ),+ ),+ );+ }+}diff --git a/mobile/lib/terminal/terminal_link_opener.dart b/mobile/lib/terminal/terminal_link_opener.dartindex 64dfdee3a..560a1a6ff 100644--- a/mobile/lib/terminal/terminal_link_opener.dart+++ b/mobile/lib/terminal/terminal_link_opener.dart@@ -5,28 +5,34 @@ import 'package:url_launcher/url_launcher.dart';import 'terminal_links.dart';import 'remote_media_download.dart';-/// Uses the existing OS launcher, never a shell command built from agent text.+/// Opens what a program printed: a web link in the OS launcher, and an image or video from the+/// agent's machine in the app's own preview, once its download is complete — never a shell+/// command built from agent text.class TerminalLinkOpener {TerminalLinkOpener({Future<bool> Function(Uri)? launch,Future<bool> Function(String)? fileExists,- bool? windows,}) : _launch = launch ?? _launchExternal,- _fileExists = fileExists ?? _exists,- _windows = windows ?? Platform.isWindows;+ _fileExists = fileExists ?? _exists;final Future<bool> Function(Uri) _launch;final Future<bool> Function(String) _fileExists;- final bool _windows;static Future<bool> _launchExternal(Uri uri) =>launchUrl(uri, mode: LaunchMode.externalApplication);static Future<bool> _exists(String path) => File(path).exists();- /// Null means the OS accepted the request; otherwise a user-facing failure.+ /// Null means the OS accepted the request, or [showLocal] was handed the downloaded copy;+ /// otherwise a user-facing failure.+ ///+ /// [showLocal] shows a downloaded file in the app — the caller's, because only the caller has a+ /// page to show it over. It is never the OS launcher: `url_launcher` opens `file:` URLs on+ /// desktop platforms only. iOS refuses them, and Android has no FileProvider here to hand one to+ /// another app, so a launch of the local copy failed on every phone, every time.Future<String?> open(String target, {Future<String> Function(String target)? downloadRemote,+ void Function(String localPath)? showLocal,bool Function()? isCancelled,}) async {if (RegExp(r'[\x00-\x1f\x7f]').hasMatch(target)) {@@ -56,13 +62,18 @@ class TerminalLinkOpener {if (downloadRemote == null) {return 'This file is on another machine. Update Harness to download a preview.';}+ // Asked before the download, not after it: a copy with nowhere to be shown would be up to+ // 512 MB fetched over the relay for nothing.+ if (showLocal == null) return 'Could not open this preview.';// Resolve paths on the owning machine; open only the completed local copy.final localPath = await downloadRemote(target);if (isCancelled?.call() == true) return null;if (!await _fileExists(localPath)) {return 'The downloaded preview is no longer available. Try again.';}- uri = Uri.file(localPath, windows: _windows);+ if (isCancelled?.call() == true) return null;+ showLocal(localPath);+ return null;}if (isCancelled?.call() == true) return null;if (!await _launch(uri)) {diff --git a/mobile/lib/terminal/terminal_links.dart b/mobile/lib/terminal/terminal_links.dartindex be6594d34..3335ab3a1 100644--- a/mobile/lib/terminal/terminal_links.dart+++ b/mobile/lib/terminal/terminal_links.dart@@ -1,9 +1,10 @@import 'package:xterm/xterm.dart';-const _mediaExtensions =- r'png|jpe?g|gif|webp|avif|heic|heif|bmp|tiff?|svg|ico|'- r'mp4|m4v|mov|webm|mkv|avi|mpe?g|ogv|3gp';+const _imageExtensions = r'png|jpe?g|gif|webp|avif|heic|heif|bmp|tiff?|svg|ico';+const _videoExtensions = r'mp4|m4v|mov|webm|mkv|avi|mpe?g|ogv|3gp';+const _mediaExtensions = '$_imageExtensions|$_videoExtensions';final _mediaSuffix = RegExp('\\.(?:$_mediaExtensions)\$', caseSensitive: false);+final _videoSuffix = RegExp('\\.(?:$_videoExtensions)\$', caseSensitive: false);final _markdownLink = RegExp(r'!?\[[^\]\r\n]*\]\((<[^>\r\n]+>|(?:[^()\r\n]|\([^()\r\n]*\))+)\)',);@@ -26,6 +27,11 @@ final _relativeMedia = RegExp(bool isMediaPath(String path) => _mediaSuffix.hasMatch(path);+/// Whether a media path is a video rather than a picture — which of the two players the in-app+/// preview (`phone/media_preview_page.dart`) opens it in. Read from the same list the links are+/// found with, so a new extension is underlined and opened in the right player in one edit.+bool isVideoPath(String path) => _videoSuffix.hasMatch(path);+bool _isTarget(String target) {final uri = Uri.tryParse(target);if (uri == null) return false;diff --git a/mobile/lib/widgets/terminal_panel.dart b/mobile/lib/widgets/terminal_panel.dartindex ae74a492b..65edecc31 100644--- a/mobile/lib/widgets/terminal_panel.dart+++ b/mobile/lib/widgets/terminal_panel.dart@@ -22,6 +22,7 @@ import '../terminal/remote_scroll_physics.dart';import '../terminal/terminal_links.dart';import '../terminal/output_blocks.dart';import '../terminal/terminal_prompt_zone.dart';+import '../phone/media_preview_page.dart';import '../phone/tty.dart';import '../terminal/terminal_session.dart';import '../terminal/terminal_theme.dart';@@ -1585,6 +1586,10 @@ class _TerminalPanelState extends State<TerminalPanel>},);},+ // Over this pane's own page, on its navigator, so Back lands on the terminal again. The+ // opener has already checked [isCancelled], so the pane is still mounted and on this agent.+ showLocal: (localPath) =>+ unawaited(openMediaPreview(context, localPath)),);if (!mounted || !identical(session, widget.session) || message == null) {return;diff --git a/mobile/pubspec.yaml b/mobile/pubspec.yamlindex 17d0b97ae..9ad3f89de 100644--- a/mobile/pubspec.yaml+++ b/mobile/pubspec.yaml@@ -80,10 +80,13 @@ dependencies:mobile_scanner: ^7.4.2# "On your computer, go to": the address is the button, and the system share sheet — AirDrop,# Messages or email — carries the download link to the computer (`phone/welcome/your_computer.dart`).+ # It is also how a picture or video a terminal printed leaves the app: Share on its preview+ # (`phone/media_preview_page.dart`).share_plus: ^13.3.0# "See how it works": the 30-second recording of the app the set-up page plays# (`phone/welcome/how_it_works_video.dart`, `assets/video/how_it_works.mp4`) — in place of an- # interactive demo.+ # interactive demo. It also plays a video a terminal printed, downloaded from the agent's machine+ # (`phone/media_preview_page.dart`).video_player: ^2.14.0dev_dependencies:diff --git a/mobile/test/media_preview_page_test.dart b/mobile/test/media_preview_page_test.dartnew file mode 100644index 000000000..b252e9b31--- /dev/null+++ b/mobile/test/media_preview_page_test.dart@@ -0,0 +1,452 @@+import 'dart:async';+import 'dart:convert';+import 'dart:io';++import 'package:flutter/cupertino.dart';+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/phone/media_preview_page.dart';+import 'package:share_plus/share_plus.dart';+import 'package:video_player/video_player.dart';++import 'phone_edge/edge_fixture.dart';++/// A picture or video an agent printed, downloaded and shown in the app — the page a tap on a+/// terminal's media link opens. Real files in a temporary folder, a share sheet and a player that+/// answer here rather than the platform's.++/// A 1×1 PNG.+final _png = base64Decode(+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==',+);++const _failed = 'Could not open this preview.';++final _share = find.byKey(const ValueKey('media-preview-share'));+final _back = find.byKey(const ValueKey('tty-back'));++void main() {+ late Directory folder;+ setUp(() {+ folder = Directory.systemTemp.createTempSync('media-preview-test-');+ imageCache.clear();+ });+ tearDown(() => folder.deleteSync(recursive: true));++ File file(String name, List<int> bytes) =>+ File('${folder.path}/$name')..writeAsBytesSync(bytes);++ /// Lets the real file read and the image codec finish: neither runs on the test's fake clock.+ Future<void> decode(WidgetTester tester) async {+ for (var i = 0; i < 100; i++) {+ await tester.runAsync(+ () => Future<void>.delayed(const Duration(milliseconds: 10)),+ );+ await tester.pump();+ if (find.text(_failed).evaluate().isNotEmpty) return;+ final raw = find.byType(RawImage);+ if (raw.evaluate().isNotEmpty &&+ tester.widget<RawImage>(raw).image != null) {+ return;+ }+ }+ }++ RawImage picture(WidgetTester tester) =>+ tester.widget<RawImage>(find.byType(RawImage));++ testWidgets('a picture is shown fitted to the screen, zoomable, with only '+ 'Back and Share above it', (tester) async {+ setPhone(tester, largePhone);+ final shot = file('shot.png', _png);+ await tester.pumpWidget(phoneApp(MediaPreviewPage(path: shot.path)));+ await decode(tester);++ expect(picture(tester).image, isNotNull);+ expect(picture(tester).fit, BoxFit.contain);+ expect(find.byType(InteractiveViewer), findsOneWidget);+ expect(find.text(_failed), findsNothing);+ expect(_back, findsOneWidget);+ expect(_share, findsOneWidget);+ expect(find.bySemanticsLabel('Share'), findsOneWidget);+ expect(find.bySemanticsLabel('shot.png'), findsOneWidget);+ // Nothing else: no title, no caption, no other control.+ expect(find.byType(Text), findsNothing);+ // The picture has the whole page under the bar to fit into.+ final area = tester.getSize(find.byType(InteractiveViewer));+ expect(area.width, largePhone.size.width);+ expect(+ area.height,+ largePhone.size.height - largePhone.top - largePhone.bottom - 44,+ );+ expect(tester.takeException(), isNull);+ });++ testWidgets('Share hands the file itself to the share sheet, anchored to '+ 'the button', (tester) async {+ setPhone(tester, largePhone);+ final shot = file('shot.png', _png);+ final shared = <ShareParams>[];+ await tester.pumpWidget(+ phoneApp(+ MediaPreviewPage(+ path: shot.path,+ share: (params) async => shared.add(params),+ ),+ ),+ );+ await decode(tester);++ await tester.tap(_share);+ await tester.pump();++ final params = shared.single;+ expect(params.files!.single.path, shot.path);+ expect(params.uri, isNull);+ expect(params.text, isNull);+ // An iPad shows the sheet as a popover, and needs to know what it points at.+ expect(params.sharePositionOrigin, tester.getRect(_share));+ });++ testWidgets('a second tap while the sheet is opening asks for no second '+ 'sheet; once it is gone, Share works again', (tester) async {+ setPhone(tester, largePhone);+ final shot = file('shot.png', _png);+ var asked = 0;+ var sheet = Completer<void>();+ await tester.pumpWidget(+ phoneApp(+ MediaPreviewPage(+ path: shot.path,+ share: (_) {+ asked++;+ return sheet.future;+ },+ ),+ ),+ );+ await decode(tester);++ await tester.tap(_share);+ await tester.pump();+ await tester.tap(_share);+ await tester.pump();+ expect(asked, 1);++ sheet.complete();+ await tester.pump();+ sheet = Completer<void>();+ await tester.tap(_share);+ await tester.pump();+ expect(asked, 2);+ sheet.complete();+ });++ testWidgets('a share sheet that will not come up leaves the page as it was', (+ tester,+ ) async {+ setPhone(tester, largePhone);+ final shot = file('shot.png', _png);+ var asked = 0;+ await tester.pumpWidget(+ phoneApp(+ MediaPreviewPage(+ path: shot.path,+ share: (_) async {+ asked++;+ throw StateError('no share sheet here');+ },+ ),+ ),+ );+ await decode(tester);++ await tester.tap(_share);+ await tester.pump();+ await tester.tap(_share);+ await tester.pump();++ expect(asked, 2);+ expect(tester.takeException(), isNull);+ expect(picture(tester).image, isNotNull);+ });++ for (final (name, bytes) in [+ ('corrupt.png', utf8.encode('not a picture at all')),+ ('empty.jpg', <int>[]),+ // A format the phone cannot draw — still a file worth sending somewhere that can.+ ('diagram.svg', utf8.encode('<svg xmlns="http://www.w3.org/2000/svg"/>')),+ ]) {+ testWidgets('$name cannot be decoded: the page says so, and Share still '+ 'sends it', (tester) async {+ setPhone(tester, largePhone);+ final broken = file(name, bytes);+ final shared = <ShareParams>[];+ await tester.pumpWidget(+ phoneApp(+ MediaPreviewPage(+ path: broken.path,+ share: (params) async => shared.add(params),+ ),+ ),+ );+ await decode(tester);++ expect(find.text(_failed), findsOneWidget);+ // A still sentence: the zoom is the decoded picture's alone.+ expect(find.byType(InteractiveViewer), findsNothing);+ expect(tester.takeException(), isNull);++ await tester.tap(_share);+ await tester.pump();+ expect(shared.single.files!.single.path, broken.path);+ });+ }++ testWidgets('a copy gone from the disk says so rather than staying blank', (+ tester,+ ) async {+ setPhone(tester, largePhone);+ await tester.pumpWidget(+ phoneApp(MediaPreviewPage(path: '${folder.path}/pruned.png')),+ );+ await decode(tester);+ expect(find.text(_failed), findsOneWidget);+ expect(_share, findsOneWidget);+ expect(tester.takeException(), isNull);+ });++ testWidgets('the picture leaves the image cache with the page', (+ tester,+ ) async {+ setPhone(tester, largePhone);+ final shot = file('shot.png', _png);+ await tester.pumpWidget(phoneApp(MediaPreviewPage(path: shot.path)));+ await decode(tester);+ expect(imageCache.currentSize, 1);++ await tester.pumpWidget(const SizedBox());+ expect(imageCache.currentSize, 0);+ });++ testWidgets('a keyboard still up as the page opens does not squeeze the '+ 'picture', (tester) async {+ setPhone(tester, largePhone);+ final shot = file('shot.png', _png);+ await tester.pumpWidget(phoneApp(MediaPreviewPage(path: shot.path)));+ await decode(tester);+ final before = tester.getSize(find.byType(InteractiveViewer));++ raiseKeyboard(tester);+ await tester.pump();+ expect(tester.getSize(find.byType(InteractiveViewer)), before);+ });++ group('opened over a page', () {+ Widget host(String path) => phoneApp(+ Builder(+ builder: (context) => Scaffold(+ body: Center(+ child: TextButton(+ onPressed: () => openMediaPreview(context, path),+ child: const Text('terminal'),+ ),+ ),+ ),+ ),+ );++ Future<void> open(WidgetTester tester) async {+ await tester.tap(find.text('terminal'));+ await tester.pump();+ await tester.pump(const Duration(seconds: 1));+ }++ testWidgets('Back returns to the page it was opened from', (tester) async {+ setPhone(tester, largePhone);+ final shot = file('shot.png', _png);+ await tester.pumpWidget(host(shot.path));+ await open(tester);+ expect(find.byType(MediaPreviewPage), findsOneWidget);+ expect(find.text('terminal'), findsNothing);++ await tester.tap(_back);+ await tester.pump();+ await tester.pump(const Duration(seconds: 1));+ expect(find.byType(MediaPreviewPage), findsNothing);+ expect(find.text('terminal'), findsOneWidget);+ });++ testWidgets("Android's back button returns too", (tester) async {+ setPhone(tester, largePhone);+ final shot = file('shot.png', _png);+ await tester.pumpWidget(host(shot.path));+ await open(tester);++ await tester.binding.handlePopRoute();+ await tester.pump();+ await tester.pump(const Duration(seconds: 1));+ expect(find.byType(MediaPreviewPage), findsNothing);+ expect(find.text('terminal'), findsOneWidget);+ });++ testWidgets('a picture gives the edge swipe to its pan; a video keeps it', (+ tester,+ ) async {+ setPhone(tester, largePhone);+ final shot = file('shot.png', _png);+ await tester.pumpWidget(host(shot.path));+ await open(tester);+ final pictureRoute =+ ModalRoute.of(tester.element(find.byType(MediaPreviewPage)))!+ as CupertinoPageRoute<void>;+ expect(pictureRoute.popGestureEnabled, isFalse);++ await tester.pumpWidget(host('${folder.path}/clip.mp4'));+ await tester.tap(_back);+ await tester.pump();+ await tester.pump(const Duration(seconds: 1));+ await open(tester);+ final videoRoute =+ ModalRoute.of(tester.element(find.byType(MediaPreviewPage)))!+ as CupertinoPageRoute<void>;+ expect(videoRoute.popGestureEnabled, isTrue);+ });+ });++ group('a video', () {+ testWidgets('plays once ready; a tap anywhere under the bar pauses, '+ 'plays, and at the end plays again', (tester) async {+ setPhone(tester, largePhone);+ final video = _Video();+ await tester.pumpWidget(+ phoneApp(+ MediaPreviewPage(path: '${folder.path}/clip.mp4', controller: video),+ ),+ );+ await tester.pump();+ expect(video.calls, ['initialize', 'play']);+ expect(find.byType(VideoPlayer), findsOneWidget);+ expect(find.byType(InteractiveViewer), findsNothing);+ expect(_share, findsOneWidget);+ expect(find.bySemanticsLabel('clip.mp4'), findsOneWidget);++ final screen = find.byKey(const ValueKey('media-preview-video'));+ // Above a landscape video on a phone held upright, not on it.+ await tester.tapAt(tester.getTopLeft(screen) + const Offset(8, 8));+ expect(video.calls.last, 'pause');+ await tester.tap(screen);+ expect(video.calls.last, 'play');++ video.finish();+ await tester.tap(screen);+ expect(video.calls.sublist(video.calls.length - 2), ['seekTo', 'play']);++ await tester.pumpWidget(const SizedBox());+ // The page plays what it was handed, and leaves disposing it to its owner.+ expect(video.disposed, isFalse);+ await video.dispose();+ });++ testWidgets('one that will not play says so, and Share still sends it', (+ tester,+ ) async {+ setPhone(tester, largePhone);+ final video = _Video(fails: true);+ final shared = <ShareParams>[];+ final path = '${folder.path}/clip.mkv';+ await tester.pumpWidget(+ phoneApp(+ MediaPreviewPage(+ path: path,+ controller: video,+ share: (params) async => shared.add(params),+ ),+ ),+ );+ await tester.pump();++ expect(video.calls, ['initialize']);+ expect(find.byType(VideoPlayer), findsNothing);+ expect(find.text(_failed), findsOneWidget);+ expect(tester.takeException(), isNull);++ await tester.tap(_share);+ await tester.pump();+ expect(shared.single.files!.single.path, path);++ await tester.pumpWidget(const SizedBox());+ await video.dispose();+ });++ testWidgets('one that fails after it started says so too', (tester) async {+ setPhone(tester, largePhone);+ final video = _Video();+ await tester.pumpWidget(+ phoneApp(+ MediaPreviewPage(path: '${folder.path}/clip.mov', controller: video),+ ),+ );+ await tester.pump();+ expect(find.byType(VideoPlayer), findsOneWidget);++ video.value = video.value.copyWith(errorDescription: 'decoder died');+ await tester.pump();+ expect(find.byType(VideoPlayer), findsNothing);+ expect(find.text(_failed), findsOneWidget);+ expect(find.byKey(const ValueKey('media-preview-video')), findsNothing);++ await tester.pumpWidget(const SizedBox());+ await video.dispose();+ });+ });+}++/// A player that plays nothing, and says what it was asked.+class _Video extends VideoPlayerController {+ _Video({this.fails = false}) : super.file(File('/sample-cache/clip.mp4'));++ final bool fails;+ final List<String> calls = [];+ bool disposed = false;++ @override+ Future<void> initialize() async {+ calls.add('initialize');+ if (fails) throw Exception('no decoder for this format');+ value = value.copyWith(+ isInitialized: true,+ duration: const Duration(seconds: 30),+ size: const Size(1920, 1080),+ );+ }++ @override+ Future<void> play() async {+ calls.add('play');+ value = value.copyWith(isPlaying: true);+ }++ @override+ Future<void> pause() async {+ calls.add('pause');+ value = value.copyWith(isPlaying: false);+ }++ @override+ Future<void> seekTo(Duration position) async {+ calls.add('seekTo');+ value = value.copyWith(position: position);+ }++ @override+ Future<void> dispose() async {+ disposed = true;+ await super.dispose();+ }++ void finish() => value = value.copyWith(+ isPlaying: false,+ position: const Duration(seconds: 30),+ );+}diff --git a/mobile/test/terminal_link_opener_test.dart b/mobile/test/terminal_link_opener_test.dartindex e135fa810..b25d92668 100644--- a/mobile/test/terminal_link_opener_test.dart+++ b/mobile/test/terminal_link_opener_test.dart@@ -11,38 +11,67 @@ void main() {return true;},);- expect(await opener.open('https://example.invalid/report?q=one'), isNull);+ expect(+ await opener.open(+ 'https://example.invalid/report?q=one',+ downloadRemote: (_) async => fail('web link downloaded'),+ showLocal: (_) => fail('web link shown in the app'),+ ),+ isNull,+ );expect(launched.single, Uri.parse('https://example.invalid/report?q=one'));});test(- 'a terminal file is downloaded from its computer before opening',+ 'a terminal file is downloaded from its computer, then shown in the app',() async {final launched = <Uri>[];final requested = <String>[];+ final shown = <String>[];final opener = TerminalLinkOpener(launch: (uri) async {launched.add(uri);return true;},fileExists: (_) async => true,- windows: false,- );- expect(- await opener.open(- '~/project/preview.png',- downloadRemote: (target) async {- requested.add(target);- return '/sample-cache/preview.png';- },- ),- isNull,);- expect(requested, ['~/project/preview.png']);- expect(launched.single, Uri.file('/sample-cache/preview.png'));+ for (final (target, local) in [+ ('~/project/preview.png', '/sample-cache/preview.png'),+ ('file:///project/clip.mov', '/sample-cache/clip.mov'),+ ]) {+ expect(+ await opener.open(+ target,+ downloadRemote: (target) async {+ requested.add(target);+ return local;+ },+ showLocal: shown.add,+ ),+ isNull,+ );+ }+ expect(requested, ['~/project/preview.png', 'file:///project/clip.mov']);+ expect(shown, ['/sample-cache/preview.png', '/sample-cache/clip.mov']);+ // `url_launcher` opens `file:` URLs on desktop platforms only: on a phone+ // handing the copy to it always failed.+ expect(launched, isEmpty);},);+ test('a file with nowhere to be shown is not downloaded', () async {+ final opener = TerminalLinkOpener(+ launch: (_) async => fail('local file launched'),+ );+ expect(+ await opener.open(+ '/project/image.png',+ downloadRemote: (_) async => fail('file downloaded for nothing'),+ ),+ 'Could not open this preview.',+ );+ });+test('unsupported targets never launch or request a download', () async {final opener = TerminalLinkOpener(launch: (_) async => fail('unsupported link launched'),@@ -58,6 +87,7 @@ void main() {await opener.open(target,downloadRemote: (_) async => fail('unsupported file downloaded'),+ showLocal: (_) => fail('unsupported file shown'),),isNotNull,);@@ -79,16 +109,18 @@ void main() {await opener.open('/project/image.png',downloadRemote: (_) async => '/sample-cache/gone.png',+ showLocal: (_) => fail('missing file shown'),),contains('no longer available'),);},);- test('a cancelled download stays silent and never launches', () async {+ test('a cancelled download stays silent and is never shown', () async {var cancelled = false;final opener = TerminalLinkOpener(launch: (_) async => fail('cancelled preview launched'),+ fileExists: (_) async => true,);expect(await opener.open(@@ -98,6 +130,7 @@ void main() {cancelled = true;return '/sample-cache/image.png';},+ showLocal: (_) => fail('cancelled preview shown'),),isNull,);@@ -105,11 +138,37 @@ void main() {await opener.open('/project/image.png',downloadRemote: (_) async => throw const RemoteMediaCancelled(),+ showLocal: (_) => fail('cancelled preview shown'),),isNull,);});+ test(+ 'a pane that moves on while the copy is checked does not show it',+ () async {+ // Cancelled between the download finishing and the copy being found on+ // disk: the pane went to another agent, or the bar's Cancel was pressed.+ var cancelled = false;+ final opener = TerminalLinkOpener(+ launch: (_) async => fail('cancelled preview launched'),+ fileExists: (_) async {+ cancelled = true;+ return true;+ },+ );+ expect(+ await opener.open(+ '/project/image.png',+ isCancelled: () => cancelled,+ downloadRemote: (_) async => '/sample-cache/image.png',+ showLocal: (_) => fail('cancelled preview shown'),+ ),+ isNull,+ );+ },+ );+test('download and launcher failures become readable messages', () async {final opener = TerminalLinkOpener(launch: (_) async => false);expect(@@ -121,6 +180,7 @@ void main() {'/project/image.png',downloadRemote: (_) async =>throw const RemoteMediaException('Preview too large.'),+ showLocal: (_) => fail('failed download shown'),),'Preview too large.',);diff --git a/mobile/test/terminal_links_test.dart b/mobile/test/terminal_links_test.dartnew file mode 100644index 000000000..2c575fcf4--- /dev/null+++ b/mobile/test/terminal_links_test.dart@@ -0,0 +1,44 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/terminal/terminal_links.dart';++void main() {+ test('a video is told from a picture by the list links are found with', () {+ for (final video in [+ 'clip.mp4',+ 'clip.m4v',+ '/work/Screen Recording.MOV',+ '~/out/demo.webm',+ 'take.mkv',+ 'take.avi',+ 'take.mpg',+ 'take.mpeg',+ 'take.ogv',+ 'take.3gp',+ ]) {+ expect(isVideoPath(video), isTrue, reason: video);+ expect(isMediaPath(video), isTrue, reason: video);+ }+ for (final picture in [+ 'shot.png',+ 'shot.JPG',+ 'shot.jpeg',+ 'loop.gif',+ 'shot.webp',+ 'shot.avif',+ 'IMG_0001.HEIC',+ 'shot.heif',+ 'shot.bmp',+ 'scan.tif',+ 'scan.tiff',+ 'diagram.svg',+ 'favicon.ico',+ ]) {+ expect(isVideoPath(picture), isFalse, reason: picture);+ expect(isMediaPath(picture), isTrue, reason: picture);+ }+ for (final other in ['notes.txt', 'mp4', 'clip.mp4.txt', 'movie']) {+ expect(isVideoPath(other), isFalse, reason: other);+ expect(isMediaPath(other), isFalse, reason: other);+ }+ });+}diff --git a/mobile/test/terminal_panel_phone_test.dart b/mobile/test/terminal_panel_phone_test.dartindex 20d1ba904..82c8e44b0 100644--- a/mobile/test/terminal_panel_phone_test.dart+++ b/mobile/test/terminal_panel_phone_test.dart@@ -6,6 +6,7 @@ import 'package:flutter/material.dart';import 'package:flutter/services.dart';import 'package:flutter_test/flutter_test.dart';import 'package:harness_mobile/core/models.dart';+import 'package:harness_mobile/phone/media_preview_page.dart';import 'package:harness_mobile/state/app_state.dart';import 'package:harness_mobile/terminal/remote_media_download.dart';import 'package:harness_mobile/terminal/terminal_binary.dart';@@ -766,7 +767,8 @@ void main() {}, variant: TargetPlatformVariant.only(TargetPlatform.iOS));testWidgets(- 'a picture on the far machine is fetched with a bar, then opened',+ 'a picture on the far machine is fetched with a bar, then shown in the '+ 'app',(tester) async {final launched = <Uri>[];final downloader = _Downloader();@@ -801,8 +803,77 @@ void main() {await tester.pump();await tester.pump();- expect(launched, [Uri.file('/tmp/preview/shot.png')]);+ // On its own page in the app, never handed to the launcher: a phone's+ // `url_launcher` cannot open a `file:` URL, so that always failed.+ expect(launched, isEmpty);expect(find.textContaining('Downloading'), findsNothing);+ expect(find.textContaining('Could not open'), findsNothing);+ await tester.pump(const Duration(seconds: 1));+ final page = find.byType(MediaPreviewPage);+ expect(page, findsOneWidget);+ expect(+ tester.widget<MediaPreviewPage>(page).path,+ '/tmp/preview/shot.png',+ );++ // Back is the terminal again, as it was.+ await tester.tap(find.byKey(const ValueKey('tty-back')));+ await tester.pump();+ await tester.pump(const Duration(seconds: 1));+ expect(page, findsNothing);+ expect(find.byType(TerminalView), findsOneWidget);+ expect(launched, isEmpty);+ },+ variant: TargetPlatformVariant.only(TargetPlatform.iOS),+ );++ testWidgets(+ 'a video on the far machine is shown in the app, the same way',+ (tester) async {+ final launched = <Uri>[];+ final downloader = _Downloader();+ final pane = session();+ pane.terminal.write('${_blank}recorded /work/demo.mp4');+ await pumpPanel(+ tester,+ pane,+ mediaDownloader: downloader,+ linkOpener: TerminalLinkOpener(+ launch: (uri) async {+ launched.add(uri);+ return true;+ },+ fileExists: (_) async => true,+ ),+ );++ await tester.tapAt(cellOf(tester, pane, '/work/demo.mp4', offset: 3));+ await tester.pump(kDoubleTapTimeout);+ await tester.pump();+ downloader.result.complete('/tmp/preview/demo.mp4');+ await tester.pump();+ await tester.pump(const Duration(seconds: 1));++ expect(launched, isEmpty);+ final page = find.byType(MediaPreviewPage);+ expect(+ tester.widget<MediaPreviewPage>(page).path,+ '/tmp/preview/demo.mp4',+ );+ // No player answers in a test: the page says so rather than breaking.+ await tester.pump();+ expect(find.text('Could not open this preview.'), findsOneWidget);+ expect(+ find.byKey(const ValueKey('media-preview-share')),+ findsOneWidget,+ );+ expect(tester.takeException(), isNull);++ await tester.tap(find.byKey(const ValueKey('tty-back')));+ await tester.pump();+ await tester.pump(const Duration(seconds: 1));+ expect(page, findsNothing);+ expect(find.byType(TerminalView), findsOneWidget);},variant: TargetPlatformVariant.only(TargetPlatform.iOS),);@@ -836,6 +907,8 @@ void main() {expect(launched, isEmpty);expect(find.textContaining('preview'), findsNothing);+ await tester.pump(const Duration(seconds: 1));+ expect(find.byType(MediaPreviewPage), findsNothing);}, variant: TargetPlatformVariant.only(TargetPlatform.iOS));});