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
feat(desktop): paste pictures and copied files into a New Harness
Dev jacob48c90bb99ba8
diff --git a/desktop/CLAUDE.md b/desktop/CLAUDE.mdindex 0696a842d..eeb01a0d0 100644--- a/desktop/CLAUDE.md+++ b/desktop/CLAUDE.md@@ -317,6 +317,24 @@ by its listed tests. Cmd-T/Cmd-O retarget the same draft/search; Store requestsproduct and machine. `test/benchmarks/swarm_benchmark.dart` measures large synthetic inventories;its headless debug timings do not establish native display or network latency.+A New Harness box takes files three ways, all into the same `HarnessAttachments`: 📎, a drop, and a+paste (`widgets/new_harness_paste.dart`). ⌘V/Ctrl-V in the task asks the clipboard three things, in+this order. Files copied in a file manager come first (`NativeClipboard.readFilePaths` — the runner's+`readFilePaths` on `harness/clipboard_image`, NSPasteboard file URLs on macOS and GTK's+`text/uri-list` on Linux — read off disk by `clipboard/copied_files.dart`, which names a file over+the limit without ever reading it): Finder leaves each file's NAME as text and its ICON as a picture+beside them, and neither is what was copied. Then text, which pastes into the task and wins whenever+it is there — except a lone web address, which is what Safari's Copy Image puts beside the picture+(`pastedTextWins`). Then a picture — a screenshot, Copy Image — attached as `pasted-image.png` through+the same `NativeClipboard` the terminal reads. In a browser the page's `paste` event carries the files+instead (`clipboard/pasted_files.dart`, a no-op natively), because Flutter leaves ⌘V to the browser+there and `PasteTextIntent` never fires. Pasted files are numbered, never swapped for one of the same name — every+clipboard picture is called alike. The field's own paste is the fallback and must be captured inside+`Action.invoke`: `callingAction` is gone by the time a clipboard read returns. A chip+(`widgets/new_harness_attachment_chip.dart`) shows a picture as itself and any other file by the mark+of its kind — `fileTypeIcon` in `shared/theme/file_type_icon.dart`, one table from extension to icon;+add a kind there, not at the call site.+### Terminals- `TerminalPane` (`lib/state/terminal_pane.dart`) separates **intent** (machine + agent id, stablediff --git a/desktop/lib/clipboard/copied_files.dart b/desktop/lib/clipboard/copied_files.dartnew file mode 100644index 000000000..199d59cae--- /dev/null+++ b/desktop/lib/clipboard/copied_files.dart@@ -0,0 +1,36 @@+import 'dart:io';++import 'package:path/path.dart' as p;++import 'pasted_files.dart';++/// Files copied in a file manager, read off this computer's disk: those that+/// fit, and the names of those that did not.+typedef CopiedFiles = ({List<PastedFile> files, List<String> tooLarge});++/// Reads the files at [paths], which a clipboard named+/// ([NativeClipboard.readFilePaths]). A folder is left out, as is a file that+/// is gone or cannot be read. One over [maxBytes] is named in `tooLarge` and+/// never read: a copied video is not pulled into memory to be refused.+Future<CopiedFiles> readCopiedFiles(+ Iterable<String> paths, {+ required int maxBytes,+}) async {+ final files = <PastedFile>[];+ final tooLarge = <String>[];+ for (final path in paths) {+ final name = p.basename(path);+ try {+ if (!await FileSystemEntity.isFile(path)) continue;+ final file = File(path);+ if (await file.length() > maxBytes) {+ tooLarge.add(name);+ continue;+ }+ files.add((name: name, bytes: await file.readAsBytes()));+ } on FileSystemException {+ continue;+ }+ }+ return (files: files, tooLarge: tooLarge);+}diff --git a/desktop/lib/clipboard/native_clipboard.dart b/desktop/lib/clipboard/native_clipboard.dartindex 5a7ad78d4..a6caca224 100644--- a/desktop/lib/clipboard/native_clipboard.dart+++ b/desktop/lib/clipboard/native_clipboard.dart@@ -41,6 +41,21 @@ class NativeClipboard {return bytes;}+ /// The files the clipboard holds, as paths in the order they were copied —+ /// what a file manager's Copy puts there (Finder, Nautilus, Dolphin).+ ///+ /// Empty when it holds none, and on a runner that does not answer: Windows,+ /// or an app built before `readFilePaths` existed.+ static Future<List<String>> readFilePaths() async {+ if (!RuntimePlatform.isMacOS && !RuntimePlatform.isLinux) return const [];+ try {+ return await _channel.invokeListMethod<String>('readFilePaths') ??+ const [];+ } catch (_) {+ return const [];+ }+ }+/// Under WSL, the WINDOWS clipboard's image as PNG, read through/// `powershell.exe` (WSL interop). WSLg mirrors a Windows screenshot into/// the Linux clipboard as BMP only, when it mirrors it at alldiff --git a/desktop/lib/clipboard/pasted_files.dart b/desktop/lib/clipboard/pasted_files.dartnew file mode 100644index 000000000..b5a4f1d6d--- /dev/null+++ b/desktop/lib/clipboard/pasted_files.dart@@ -0,0 +1,20 @@+import 'dart:typed_data';++import 'pasted_files_native.dart'+ if (dart.library.js_interop) 'pasted_files_web.dart'+ as impl;++/// One file a paste carried: a screenshot, a copied picture, a copied file.+typedef PastedFile = ({String name, Uint8List bytes});++/// Hears a browser's paste while [wanted] says so, and hands [onFiles] the+/// files it carried instead of letting the field have them. A paste whose+/// text wins ([pastedTextWins]) is left to the browser. Returns what stops+/// listening.+///+/// A native build hears nothing here: its clipboard is read when ⌘V is+/// pressed ([NativeClipboard]), not delivered by an event.+void Function() listenForPastedFiles({+ required bool Function() wanted,+ required void Function(List<PastedFile> files) onFiles,+}) => impl.listenForPastedFiles(wanted: wanted, onFiles: onFiles);diff --git a/desktop/lib/clipboard/pasted_files_native.dart b/desktop/lib/clipboard/pasted_files_native.dartnew file mode 100644index 000000000..279c6a546--- /dev/null+++ b/desktop/lib/clipboard/pasted_files_native.dart@@ -0,0 +1,6 @@+import 'dart:typed_data';++void Function() listenForPastedFiles({+ required bool Function() wanted,+ required void Function(List<({String name, Uint8List bytes})> files) onFiles,+}) => () {};diff --git a/desktop/lib/clipboard/pasted_files_web.dart b/desktop/lib/clipboard/pasted_files_web.dartnew file mode 100644index 000000000..97064c464--- /dev/null+++ b/desktop/lib/clipboard/pasted_files_web.dart@@ -0,0 +1,38 @@+import 'dart:async';+import 'dart:js_interop';+import 'dart:typed_data';++import 'package:web/web.dart' as web;++import 'pasted_text.dart';++void Function() listenForPastedFiles({+ required bool Function() wanted,+ required void Function(List<({String name, Uint8List bytes})> files) onFiles,+}) {+ final listener = ((web.ClipboardEvent event) {+ final data = event.clipboardData;+ if (data == null || !wanted()) return;+ // The clipboard closes when this handler returns: take the files now.+ final files = [+ for (var i = 0; i < data.files.length; i++) ?data.files.item(i),+ ];+ if (files.isEmpty || pastedTextWins(data.getData('text/plain'))) return;+ event.preventDefault();+ unawaited(_read(files).then(onFiles));+ }).toJS;+ // Captured at the window: the field Flutter types into lives in its own+ // host element, and this must hear the paste whatever handles it there.+ web.window.addEventListener('paste', listener, true.toJS);+ return () => web.window.removeEventListener('paste', listener, true.toJS);+}++Future<List<({String name, Uint8List bytes})>> _read(+ List<web.File> files,+) async => [+ for (final file in files)+ (+ name: file.name,+ bytes: (await file.arrayBuffer().toDart).toDart.asUint8List(),+ ),+];diff --git a/desktop/lib/clipboard/pasted_text.dart b/desktop/lib/clipboard/pasted_text.dartnew file mode 100644index 000000000..8f132ad3c--- /dev/null+++ b/desktop/lib/clipboard/pasted_text.dart@@ -0,0 +1,11 @@+/// Whether a paste that holds both [text] and a picture is a paste of the+/// text. It is — a document's copy carries a picture of itself beside its+/// words, a copied file its icon beside its name — unless the text is only a+/// web address: Safari's Copy Image puts the picture's own URL next to it, and+/// the picture is what was copied.+bool pastedTextWins(String? text) {+ final trimmed = text?.trim() ?? '';+ return trimmed.isNotEmpty && !_webAddress.hasMatch(trimmed);+}++final _webAddress = RegExp(r'^https?://\S+$');diff --git a/desktop/lib/shared/theme/app_icons.dart b/desktop/lib/shared/theme/app_icons.dartindex 409c07777..d411a2127 100644--- a/desktop/lib/shared/theme/app_icons.dart+++ b/desktop/lib/shared/theme/app_icons.dart@@ -71,8 +71,18 @@ abstract final class AppIcons {static const eye = LucideIcons.eye400;static const eyeOff = LucideIcons.eyeOff400;static const file = LucideIcons.file400;+ static const fileArchive = LucideIcons.fileArchive400;+ static const fileBraces = LucideIcons.fileBraces400;+ static const fileCode = LucideIcons.fileCode400;+ static const fileDiff = LucideIcons.fileDiff400;static const fileDown = LucideIcons.fileDown400;+ static const fileImage = LucideIcons.fileImage400;+ static const fileMusic = LucideIcons.fileMusic400;+ static const filePlay = LucideIcons.filePlay400;+ static const fileSpreadsheet = LucideIcons.fileSpreadsheet400;+ static const fileTerminal = LucideIcons.fileTerminal400;static const fileText = LucideIcons.fileText400;+ static const fileType = LucideIcons.fileType400;static const film = LucideIcons.film400;static const flaskConical = LucideIcons.flaskConical400;static const folder = LucideIcons.folder400;@@ -120,6 +130,7 @@ abstract final class AppIcons {static const plug = LucideIcons.plug400;static const plus = LucideIcons.plus400;static const power = LucideIcons.power400;+ static const presentation = LucideIcons.presentation400;static const radioTower = LucideIcons.radioTower400;static const refreshCw = LucideIcons.refreshCw400;static const rocket = LucideIcons.rocket400;diff --git a/desktop/lib/shared/theme/file_type_icon.dart b/desktop/lib/shared/theme/file_type_icon.dartnew file mode 100644index 000000000..3e995cb2d--- /dev/null+++ b/desktop/lib/shared/theme/file_type_icon.dart@@ -0,0 +1,64 @@+import 'package:flutter/widgets.dart';++import 'app_icons.dart';++/// The mark for a file of this [name], told by its extension — or, for the+/// few build files that have none, by the name itself. A kind this does not+/// know gets the plain file.+IconData fileTypeIcon(String name) {+ final lower = name.toLowerCase();+ final dot = lower.lastIndexOf('.');+ final key = dot < 0 ? lower : lower.substring(dot + 1);+ return _icons[key] ?? AppIcons.file;+}++/// Each kind's mark, and the extensions that are of that kind.+const _kinds = <(IconData, List<String>)>[+ (+ AppIcons.fileImage,+ [+ 'png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'tif', 'tiff', //+ 'heic', 'heif', 'avif', 'ico', 'svg', 'psd', 'fig', 'sketch',+ ],+ ),+ (AppIcons.filePlay, ['mp4', 'mov', 'm4v', 'webm', 'mkv', 'avi']),+ (AppIcons.fileMusic, ['mp3', 'wav', 'm4a', 'aac', 'flac', 'ogg', 'opus']),+ (+ AppIcons.fileArchive,+ [+ 'zip', 'tar', 'gz', 'tgz', 'bz2', 'xz', 'zst', '7z', 'rar', //+ 'dmg', 'iso', 'jar', 'apk', 'ipa',+ ],+ ),+ (AppIcons.fileText, ['pdf', 'doc', 'docx', 'rtf', 'odt', 'pages', 'epub']),+ (AppIcons.fileType, ['txt', 'md', 'markdown', 'mdx', 'rst', 'log']),+ (AppIcons.fileSpreadsheet, ['csv', 'tsv', 'xls', 'xlsx', 'numbers', 'ods']),+ (AppIcons.presentation, ['ppt', 'pptx', 'key', 'odp']),+ (+ AppIcons.fileCode,+ [+ 'dart', 'ts', 'tsx', 'js', 'jsx', 'mjs', 'cjs', 'py', 'go', 'rs', //+ 'java', 'kt', 'swift', 'c', 'cc', 'cpp', 'h', 'hpp', 'm', 'mm', //+ 'cs', 'rb', 'php', 'lua', 'r', 'html', 'css', 'scss', 'vue', //+ 'svelte', 'sql', 'ipynb', 'makefile', 'dockerfile',+ ],+ ),+ (+ AppIcons.fileBraces,+ [+ 'json', 'jsonl', 'yaml', 'yml', 'toml', 'xml', 'plist', 'ini', //+ 'env', 'lock', 'conf',+ ],+ ),+ (+ AppIcons.fileTerminal,+ ['sh', 'bash', 'zsh', 'fish', 'ps1', 'bat', 'command'],+ ),+ (AppIcons.fileDiff, ['diff', 'patch']),+ (AppIcons.database, ['db', 'sqlite', 'sqlite3']),+];++final _icons = <String, IconData>{+ for (final (icon, extensions) in _kinds)+ for (final extension in extensions) extension: icon,+};diff --git a/desktop/lib/state/harness_attachments.dart b/desktop/lib/state/harness_attachments.dartindex 6c3664458..15e221f12 100644--- a/desktop/lib/state/harness_attachments.dart+++ b/desktop/lib/state/harness_attachments.dart@@ -31,8 +31,13 @@ class HarnessAttachments extends ChangeNotifier {/// Adds the files that fit, replacing one of the same name. Returns what/// to tell the person about any left out, or null when all were taken.- String? add(Iterable<HarnessAttachment> files) {- final tooLarge = <String>[];+ /// [oversized] names files already known to be over [maxBytes], which were+ /// never read into memory to be refused here.+ String? add(+ Iterable<HarnessAttachment> files, {+ Iterable<String> oversized = const [],+ }) {+ final tooLarge = [...oversized];for (final file in files) {if (file.bytes.isEmpty) continue;if (file.bytes.length > maxBytes) {@@ -51,6 +56,32 @@ class HarnessAttachments extends ChangeNotifier {: '${tooLarge.length} files are over $limit.';}+ /// Adds what was pasted beside what is there. A clipboard names every+ /// picture alike, so one whose name is taken is numbered, not swapped in.+ String? addPasted(+ Iterable<HarnessAttachment> files, {+ Iterable<String> oversized = const [],+ }) {+ final taken = {for (final file in _files) file.name};+ return add([+ for (final file in files)+ HarnessAttachment(_freeName(file.name, taken), file.bytes),+ ], oversized: oversized);+ }++ /// [name], or `name-2.ext`, `name-3.ext`… — the first not in [taken], which+ /// then holds it.+ static String _freeName(String name, Set<String> taken) {+ final dot = name.lastIndexOf('.');+ final stem = dot > 0 ? name.substring(0, dot) : name;+ final extension = dot > 0 ? name.substring(dot) : '';+ var candidate = name;+ for (var count = 2; !taken.add(candidate); count++) {+ candidate = '$stem-$count$extension';+ }+ return candidate;+ }+void remove(HarnessAttachment file) {if (_files.remove(file)) notifyListeners();}diff --git a/desktop/lib/widgets/new_harness_attachment_chip.dart b/desktop/lib/widgets/new_harness_attachment_chip.dartnew file mode 100644index 000000000..36cb58225--- /dev/null+++ b/desktop/lib/widgets/new_harness_attachment_chip.dart@@ -0,0 +1,80 @@+import 'package:flutter/material.dart';++import '../clipboard/image_bytes.dart';+import '../shared/theme/app_icons.dart';+import '../shared/theme/file_type_icon.dart';+import '../shared/widgets/app_icon_button.dart';+import '../state/harness_attachments.dart';+import 'desktop_chrome.dart';++/// One attached file: its mark, its name, and the × that takes it back out.+class NewHarnessAttachmentChip extends StatelessWidget {+ const NewHarnessAttachmentChip({+ super.key,+ required this.file,+ required this.onRemove,+ });++ final HarnessAttachment file;+ final VoidCallback? onRemove;++ /// A picture shows itself; anything else, the mark of its kind.+ Widget _mark() {+ final icon = Icon(+ fileTypeIcon(file.name),+ key: ValueKey('new-harness-attachment-icon:${file.name}'),+ size: 13,+ color: DesktopChrome.muted,+ );+ if (!looksLikeImage(file.bytes)) return icon;+ return ClipRRect(+ borderRadius: BorderRadius.circular(3),+ child: Image.memory(+ file.bytes,+ key: ValueKey('new-harness-attachment-preview:${file.name}'),+ width: _previewSize,+ height: _previewSize,+ // Decoded at the size it is drawn, not the screenshot's own.+ cacheWidth: _previewSize.toInt() * 3,+ fit: BoxFit.cover,+ gaplessPlayback: true,+ errorBuilder: (_, _, _) => icon,+ ),+ );+ }++ static const _previewSize = 16.0;++ @override+ Widget build(BuildContext context) => Container(+ key: ValueKey('new-harness-attachment:${file.name}'),+ constraints: const BoxConstraints(maxWidth: 220),+ padding: const EdgeInsets.only(left: 10, right: 2),+ height: DesktopChrome.compactControlHeight,+ decoration: BoxDecoration(+ color: DesktopChrome.foreground.withValues(alpha: .055),+ borderRadius: BorderRadius.circular(20),+ ),+ child: Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ _mark(),+ const SizedBox(width: 6),+ Flexible(+ child: Text(+ file.name,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: DesktopChrome.control(),+ ),+ ),+ AppIconButton(+ icon: AppIcons.close,+ tooltip: 'Remove ${file.name}',+ size: AppIcons.closeSize,+ onPressed: onRemove,+ ),+ ],+ ),+ );+}diff --git a/desktop/lib/widgets/new_harness_attachments.dart b/desktop/lib/widgets/new_harness_attachments.dartindex 447ae35eb..0c483ba3c 100644--- a/desktop/lib/widgets/new_harness_attachments.dart+++ b/desktop/lib/widgets/new_harness_attachments.dart@@ -8,6 +8,7 @@ import '../shared/theme/app_icons.dart';import '../shared/widgets/app_icon_button.dart';import '../state/harness_attachments.dart';import 'desktop_chrome.dart';+import 'new_harness_attachment_chip.dart';/// Reads picked or dropped files into attachments, and says what was left out.Future<void> _attach(@@ -19,8 +20,12 @@ Future<void> _attach(for (final file in files)HarnessAttachment(file.name, await file.readAsBytes()),];- final problem = attachments.add(read);- if (problem == null || !context.mounted) return;+ if (context.mounted) reportAttachProblem(context, attachments.add(read));+}++/// Says what an attach left out, when it left anything.+void reportAttachProblem(BuildContext context, String? problem) {+ if (problem == null) return;ScaffoldMessenger.maybeOf(context)?.showSnackBar(SnackBar(content: Text(problem)));}@@ -71,7 +76,7 @@ class NewHarnessAttachmentChips extends StatelessWidget {runSpacing: 6,children: [for (final file in attachments.files)- _AttachmentChip(+ NewHarnessAttachmentChip(file: file,onRemove: enabled ? () => attachments.remove(file) : null,),@@ -80,46 +85,6 @@ class NewHarnessAttachmentChips extends StatelessWidget {);}-class _AttachmentChip extends StatelessWidget {- const _AttachmentChip({required this.file, required this.onRemove});-- final HarnessAttachment file;- final VoidCallback? onRemove;-- @override- Widget build(BuildContext context) => Container(- key: ValueKey('new-harness-attachment:${file.name}'),- constraints: const BoxConstraints(maxWidth: 220),- padding: const EdgeInsets.only(left: 10, right: 2),- height: DesktopChrome.compactControlHeight,- decoration: BoxDecoration(- color: DesktopChrome.foreground.withValues(alpha: .055),- borderRadius: BorderRadius.circular(20),- ),- child: Row(- mainAxisSize: MainAxisSize.min,- children: [- Icon(AppIcons.file, size: 13, color: DesktopChrome.muted),- const SizedBox(width: 6),- Flexible(- child: Text(- file.name,- maxLines: 1,- overflow: TextOverflow.ellipsis,- style: DesktopChrome.control(),- ),- ),- AppIconButton(- icon: AppIcons.close,- tooltip: 'Remove ${file.name}',- size: AppIcons.closeSize,- onPressed: onRemove,- ),- ],- ),- );-}-/// Files dropped anywhere on [child] are attached; while a drag is over it,/// it says so.class NewHarnessDropZone extends StatefulWidget {diff --git a/desktop/lib/widgets/new_harness_form.dart b/desktop/lib/widgets/new_harness_form.dartindex 9c761a117..2c7cb47cd 100644--- a/desktop/lib/widgets/new_harness_form.dart+++ b/desktop/lib/widgets/new_harness_form.dart@@ -21,6 +21,7 @@ import 'box_chrome.dart' show kTerminalCornerRadius, terminalPaneBorder;import 'dsh_install_panel.dart' show describeInstallFailure;import 'desktop_chrome.dart';import 'new_harness_attachments.dart';+import 'new_harness_paste.dart';import 'engine_identity.dart';/// Desktop composer and legacy terminal launch form sharing the same draft.@@ -1824,12 +1825,18 @@ class NewHarnessFormState extends State<NewHarnessForm> {visualDensity: VisualDensity.compact,);- /// The task box, taking dropped files when the host attaches them.+ /// The task box, taking dropped files and pasted pictures when the host+ /// attaches them.Widget _desktopTaskEditor() => switch (box.attachments) {final attachments? when box.takesTask => NewHarnessDropZone(attachments: attachments,enabled: !box.locked,- child: _desktopTaskBox(),+ child: NewHarnessPasteTarget(+ attachments: attachments,+ enabled: !box.locked,+ focusNode: _taskFocus,+ child: _desktopTaskBox(),+ ),),_ => _desktopTaskBox(),};diff --git a/desktop/lib/widgets/new_harness_paste.dart b/desktop/lib/widgets/new_harness_paste.dartnew file mode 100644index 000000000..2bfa947a6--- /dev/null+++ b/desktop/lib/widgets/new_harness_paste.dart@@ -0,0 +1,140 @@+import 'dart:async';++import 'package:flutter/material.dart';+import 'package:flutter/services.dart';++import '../clipboard/copied_files.dart';+import '../clipboard/native_clipboard.dart';+import '../clipboard/pasted_files.dart';+import '../clipboard/pasted_text.dart';+import '../state/harness_attachments.dart';+import 'new_harness_attachments.dart';++/// What a picture pasted off this computer's clipboard is called: a clipboard+/// holds pixels, not a file, so the picture has no name of its own.+const kPastedImageName = 'pasted-image.png';++/// The files a file manager's Copy left on this computer's clipboard.+Future<CopiedFiles> _clipboardFiles() async => readCopiedFiles(+ await NativeClipboard.readFilePaths(),+ maxBytes: HarnessAttachments.maxBytes,+);++/// Paste in [child]'s task field attaches what the clipboard holds besides+/// text. On this computer ⌘V adds to [attachments] the files copied in a file+/// manager, or the picture on the clipboard — a screenshot, Copy Image; in a+/// browser, the files a paste carries. Text still pastes into the field+/// ([pastedTextWins]).+class NewHarnessPasteTarget extends StatefulWidget {+ const NewHarnessPasteTarget({+ super.key,+ required this.attachments,+ required this.enabled,+ required this.focusNode,+ required this.child,+ this.readFiles = _clipboardFiles,+ this.readImage = NativeClipboard.readImagePng,+ });++ final HarnessAttachments attachments;+ final bool enabled;++ /// The task field's focus: a browser's paste is this box's only while the+ /// field holds it.+ final FocusNode focusNode;+ final Widget child;++ /// The clipboard's copied files; tests pass their own.+ final Future<CopiedFiles> Function() readFiles;++ /// The clipboard's picture as PNG, or null; tests pass their own.+ final Future<Uint8List?> Function() readImage;++ @override+ State<NewHarnessPasteTarget> createState() => _NewHarnessPasteTargetState();+}++class _NewHarnessPasteTargetState extends State<NewHarnessPasteTarget> {+ late final _actions = <Type, Action<Intent>>{+ PasteTextIntent: _PasteAction(_paste),+ };+ late final void Function() _stopListening;++ @override+ void initState() {+ super.initState();+ _stopListening = listenForPastedFiles(+ wanted: () => widget.enabled && widget.focusNode.hasFocus,+ onFiles: _attachFiles,+ );+ }++ @override+ void dispose() {+ _stopListening();+ super.dispose();+ }++ void _attach(+ Iterable<HarnessAttachment> files, {+ Iterable<String> oversized = const [],+ }) {+ // Reading a clipboard takes a moment the box may not have survived.+ if (!mounted || !widget.enabled) return;+ reportAttachProblem(+ context,+ widget.attachments.addPasted(files, oversized: oversized),+ );+ }++ void _attachFiles(+ List<PastedFile> files, {+ Iterable<String> oversized = const [],+ }) => _attach([+ for (final file in files) HarnessAttachment(file.name, file.bytes),+ ], oversized: oversized);++ /// ⌘V: what the clipboard holds as attachments, or [pasteText] — the+ /// field's own paste — when text is what was copied.+ ///+ /// Copied files come first. Beside them a file manager leaves each file's+ /// name as text and its icon as a picture, and neither is what was copied.+ Future<void> _paste(VoidCallback pasteText) async {+ if (!widget.enabled) return pasteText();+ final copied = await widget.readFiles();+ if (copied.files.isNotEmpty || copied.tooLarge.isNotEmpty) {+ return _attachFiles(copied.files, oversized: copied.tooLarge);+ }+ if (pastedTextWins(await _clipboardText())) return pasteText();+ final image = await widget.readImage();+ if (image == null || image.isEmpty) return pasteText();+ _attach([HarnessAttachment(kPastedImageName, image)]);+ }++ Future<String?> _clipboardText() async {+ try {+ return (await Clipboard.getData(Clipboard.kTextPlain))?.text;+ } on PlatformException {+ return null;+ }+ }++ @override+ Widget build(BuildContext context) =>+ Actions(actions: _actions, child: widget.child);+}++/// Stands in for the field's paste, which it is handed to fall back on.+class _PasteAction extends Action<PasteTextIntent> {+ _PasteAction(this.paste);++ final Future<void> Function(VoidCallback pasteText) paste;++ @override+ Object? invoke(PasteTextIntent intent) {+ // The field's own action, taken now: it is gone once this returns.+ final field = callingAction;+ unawaited(paste(() => field?.invoke(intent)));+ return null;+ }+}diff --git a/desktop/linux/runner/my_application.cc b/desktop/linux/runner/my_application.ccindex 51270632c..edd3602a0 100644--- a/desktop/linux/runner/my_application.cc+++ b/desktop/linux/runner/my_application.cc@@ -77,10 +77,30 @@ static FlMethodResponse* write_clipboard_image_png(FlValue* args) {return FL_METHOD_RESPONSE(fl_method_success_response_new(fl_value_new_bool(TRUE)));}+// The files the GTK clipboard holds, as paths in the order they were copied — what a file+// manager's Copy puts there (Nautilus, Dolphin, Thunar and the rest all offer `text/uri-list`).+// An empty list when the clipboard holds none. A URI that is not a local file — a remote mount+// with no path here — is left out.+static FlMethodResponse* read_clipboard_file_paths() {+ GtkClipboard* clipboard = gtk_clipboard_get(GDK_SELECTION_CLIPBOARD);+ g_autoptr(FlValue) paths = fl_value_new_list();+ g_auto(GStrv) uris = gtk_clipboard_wait_for_uris(clipboard);+ if (uris != nullptr) {+ for (gchar** uri = uris; *uri != nullptr; uri++) {+ g_autofree gchar* path = g_filename_from_uri(*uri, nullptr, nullptr);+ if (path != nullptr) {+ fl_value_append_take(paths, fl_value_new_string(path));+ }+ }+ }+ return FL_METHOD_RESPONSE(fl_method_success_response_new(paths));+}+// Dart calls into this channel to read/write a native image on the GTK clipboard. Flutter's own// `Clipboard` API only ever sees text/plain — see terminal_panel.dart's `_paste()` — so a real// image (a screenshot, "Copy Image" from a browser, ...) needs this native round trip instead.-// Mirrors macOS's `harness/clipboard_image` channel (MainFlutterWindow.swift).+// It also answers for the FILES a clipboard holds (`readFilePaths`), which that API cannot see+// either. Mirrors macOS's `harness/clipboard_image` channel (MainFlutterWindow.swift).static void clipboard_image_method_call_cb(FlMethodChannel* channel,FlMethodCall* method_call,gpointer user_data) {@@ -90,6 +110,8 @@ static void clipboard_image_method_call_cb(FlMethodChannel* channel,response = read_clipboard_image_png();} else if (g_strcmp0(method, "writeImagePng") == 0) {response = write_clipboard_image_png(fl_method_call_get_args(method_call));+ } else if (g_strcmp0(method, "readFilePaths") == 0) {+ response = read_clipboard_file_paths();} else {response = FL_METHOD_RESPONSE(fl_method_not_implemented_response_new());}diff --git a/desktop/macos/Runner/MainFlutterWindow.swift b/desktop/macos/Runner/MainFlutterWindow.swiftindex 392edea9b..2e260d592 100644--- a/desktop/macos/Runner/MainFlutterWindow.swift+++ b/desktop/macos/Runner/MainFlutterWindow.swift@@ -11,7 +11,8 @@ private let kMenuChannel = "harness/app_menu"/// Flutter's own `Clipboard` API only ever sees `text/plain` — see `terminal_panel.dart`'s/// `_paste()` — so a real image (a screenshot, "Copy Image" from a browser, ...) needs this native/// round trip instead. The other direction of `harness/clipboard_image` (Dart calling Swift) rather-/// than `harness/app_menu`'s (Swift calling Dart).+/// than `harness/app_menu`'s (Swift calling Dart). It also answers for the FILES a pasteboard+/// holds (`readFilePaths`), which Flutter's `Clipboard` cannot see either.private let kClipboardImageChannel = "harness/clipboard_image"class MainFlutterWindow: NSWindow {@@ -334,6 +335,8 @@ class MainFlutterWindow: NSWindow {return}result(MainFlutterWindow.writeClipboardImagePng(bytes))+ case "readFilePaths":+ result(MainFlutterWindow.readClipboardFilePaths())default:result(FlutterMethodNotImplemented)}@@ -370,6 +373,19 @@ class MainFlutterWindow: NSWindow {pasteboard.clearContents()return pasteboard.setData(data, forType: .png)}++ /// The files the general pasteboard holds, as paths in the order they were copied — what+ /// Finder's Copy puts there. Empty when the clipboard holds none. Beside them Finder also+ /// leaves each file's NAME as text and its ICON as an image, so a caller that wants the files+ /// has to ask for them first: the text and the picture are not what was copied.+ private static func readClipboardFilePaths() -> [String] {+ let urls =+ NSPasteboard.general.readObjects(+ forClasses: [NSURL.self],+ options: [.urlReadingFileURLsOnly: true]+ ) as? [URL] ?? []+ return urls.map { $0.path }+ }}/// The Harness menu, in the order people act on it: what they came to do first,diff --git a/desktop/test/copied_files_test.dart b/desktop/test/copied_files_test.dartnew file mode 100644index 000000000..f588cd1e4--- /dev/null+++ b/desktop/test/copied_files_test.dart@@ -0,0 +1,75 @@+// Files copied in a file manager: what the clipboard names, read off disk.+import 'dart:io';++import 'package:flutter/services.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/clipboard/copied_files.dart';+import 'package:harness/clipboard/native_clipboard.dart';++void main() {+ late Directory dir;++ setUp(() => dir = Directory.systemTemp.createTempSync('copied-files-'));+ tearDown(() => dir.deleteSync(recursive: true));++ String write(String name, List<int> bytes) {+ final file = File('${dir.path}/$name')..writeAsBytesSync(bytes);+ return file.path;+ }++ test('files are read under their own names, in the order copied', () async {+ final copied = await readCopiedFiles([+ write('b.txt', [2, 2]),+ write('a.png', [1]),+ ], maxBytes: 16);+ expect([for (final file in copied.files) file.name], ['b.txt', 'a.png']);+ expect(copied.files.first.bytes, [2, 2]);+ expect(copied.tooLarge, isEmpty);+ });++ test('one over the limit is named and never read; the rest are', () async {+ final copied = await readCopiedFiles([+ write('movie.mov', List.filled(17, 0)),+ write('at-the-limit.bin', List.filled(16, 0)),+ ], maxBytes: 16);+ expect(copied.tooLarge, ['movie.mov']);+ expect(copied.files.single.name, 'at-the-limit.bin');+ });++ test('a folder, and a file that is gone, are left out', () async {+ Directory('${dir.path}/folder').createSync();+ final copied = await readCopiedFiles([+ '${dir.path}/folder',+ '${dir.path}/deleted.txt',+ write('kept.txt', [1]),+ ], maxBytes: 16);+ expect(copied.files.single.name, 'kept.txt');+ expect(copied.tooLarge, isEmpty);+ });++ group('the clipboard\'s file paths', () {+ TestWidgetsFlutterBinding.ensureInitialized();+ const channel = MethodChannel('harness/clipboard_image');+ final messenger =+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;+ tearDown(() => messenger.setMockMethodCallHandler(channel, null));++ test('are what the runner answers', () async {+ messenger.setMockMethodCallHandler(+ channel,+ (call) async =>+ call.method == 'readFilePaths' ? ['/tmp/a.png', '/tmp/b'] : null,+ );+ expect(await NativeClipboard.readFilePaths(), ['/tmp/a.png', '/tmp/b']);+ });++ test('are none on a runner built before the method existed', () async {+ expect(await NativeClipboard.readFilePaths(), isEmpty);+ messenger.setMockMethodCallHandler(+ channel,+ (call) async => throw PlatformException(code: 'broken'),+ );+ expect(await NativeClipboard.readFilePaths(), isEmpty);+ });+ }, skip: !Platform.isMacOS && !Platform.isLinux);+}diff --git a/desktop/test/desktop_composer_layout_test.dart b/desktop/test/desktop_composer_layout_test.dartindex c4d6e63f5..4dc7f2be1 100644--- a/desktop/test/desktop_composer_layout_test.dart+++ b/desktop/test/desktop_composer_layout_test.dart@@ -3,6 +3,7 @@ import 'dart:io';import 'dart:ui' as ui;import 'package:harness/shared/theme/app_icons.dart';+import 'package:flutter/foundation.dart';import 'package:flutter/material.dart';import 'package:flutter/rendering.dart';import 'package:flutter/services.dart';@@ -16,12 +17,14 @@ import 'package:harness/shared/theme/app_theme.dart' as grid;import 'package:harness/shortcuts/app_keymap.dart';import 'package:harness/shortcuts/keymap_host.dart';import 'package:harness/state/app_state.dart';+import 'package:harness/state/harness_attachments.dart';import 'package:harness/state/harness_placement.dart';import 'package:harness/state/new_harness.dart';import 'package:harness/state/pane_arrangement.dart';import 'package:harness/widgets/desktop_chrome.dart';import 'package:harness/widgets/engine_identity.dart';import 'package:harness/widgets/new_harness_form.dart';+import 'package:harness/widgets/new_harness_paste.dart';import 'box_render_preview_test.dart' show loadPreviewFonts;import 'keymap_host_test.dart' show MemoryKeymap, key;@@ -208,6 +211,7 @@ Future<_ReviewFixture> _mount(double scale = 1,Brightness brightness = Brightness.dark,NewHarnessDraft? draft,+ HarnessAttachments? attachments,FutureOr<void> Function(_ReviewFixture)? onBrowse,}) async {final app = _ReviewApp(@@ -221,6 +225,7 @@ Future<_ReviewFixture> _mount(engine: engine,folder: folder,draft: draft,+ attachments: attachments,);final fixture = _ReviewFixture(app, box, MemoryKeymap());addTearDown(fixture.dispose);@@ -530,6 +535,48 @@ void main() {expect(fixture.app.launches, isEmpty);});+ testWidgets('⌘V in the task attaches the clipboard\'s picture', (+ tester,+ ) async {+ debugDefaultTargetPlatformOverride = TargetPlatform.macOS;+ final messenger =+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;+ const clipboardImage = MethodChannel('harness/clipboard_image');+ // A screenshot: pixels on the clipboard, and no text beside them.+ messenger.setMockMethodCallHandler(+ clipboardImage,+ (call) async => switch (call.method) {+ 'readFilePaths' => const <String>[],+ 'readImagePng' => Uint8List.fromList([0x89, 0x50, 0x4E, 0x47]),+ _ => null,+ },+ );+ messenger.setMockMethodCallHandler(+ SystemChannels.platform,+ (call) async => null,+ );+ addTearDown(() {+ messenger.setMockMethodCallHandler(clipboardImage, null);+ messenger.setMockMethodCallHandler(SystemChannels.platform, null);+ });+ // The box owns its files, and disposes them with itself.+ final files = HarnessAttachments();+ await _mount(tester, attachments: files);+ await tester.tap(_task);+ await tester.pump();+ await tester.sendKeyDownEvent(LogicalKeyboardKey.metaLeft);+ await tester.sendKeyEvent(LogicalKeyboardKey.keyV);+ await tester.sendKeyUpEvent(LogicalKeyboardKey.metaLeft);+ await tester.pumpAndSettle();+ expect(files.files.single.name, kPastedImageName);+ expect(+ find.byKey(const ValueKey('new-harness-attachment:$kPastedImageName')),+ findsOneWidget,+ );+ expect(tester.takeException(), isNull);+ debugDefaultTargetPlatformOverride = null;+ }, skip: !Platform.isMacOS && !Platform.isLinux);+testWidgets('the platform send action submits the exact prompt once', (tester,) async {diff --git a/desktop/test/file_type_icon_test.dart b/desktop/test/file_type_icon_test.dartnew file mode 100644index 000000000..15c897272--- /dev/null+++ b/desktop/test/file_type_icon_test.dart@@ -0,0 +1,76 @@+import 'dart:convert';+import 'dart:typed_data';++import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/shared/theme/app_icons.dart';+import 'package:harness/shared/theme/file_type_icon.dart';+import 'package:harness/state/harness_attachments.dart';+import 'package:harness/widgets/new_harness_attachments.dart';++void main() {+ test('a file is marked by its kind', () {+ const kinds = {+ 'photo.heic': AppIcons.fileImage,+ 'logo.svg': AppIcons.fileImage,+ 'demo.mov': AppIcons.filePlay,+ 'voice.m4a': AppIcons.fileMusic,+ 'build.tar.gz': AppIcons.fileArchive,+ 'spec.pdf': AppIcons.fileText,+ 'brief.docx': AppIcons.fileText,+ 'README.md': AppIcons.fileType,+ 'server.log': AppIcons.fileType,+ 'users.csv': AppIcons.fileSpreadsheet,+ 'q3.xlsx': AppIcons.fileSpreadsheet,+ 'pitch.pptx': AppIcons.presentation,+ 'main.dart': AppIcons.fileCode,+ 'App.tsx': AppIcons.fileCode,+ 'package.json': AppIcons.fileBraces,+ 'pubspec.yaml': AppIcons.fileBraces,+ '.env': AppIcons.fileBraces,+ 'deploy.sh': AppIcons.fileTerminal,+ 'fix.patch': AppIcons.fileDiff,+ 'app.sqlite': AppIcons.database,+ };+ for (final MapEntry(key: name, value: icon) in kinds.entries) {+ expect(fileTypeIcon(name), icon, reason: name);+ }+ });++ test('the extension is read whatever its case, and only the last one', () {+ expect(fileTypeIcon('REPORT.PDF'), AppIcons.fileText);+ expect(fileTypeIcon('notes.pdf.txt'), AppIcons.fileType);+ });++ test('build files with no extension are known by name', () {+ expect(fileTypeIcon('Makefile'), AppIcons.fileCode);+ expect(fileTypeIcon('Dockerfile'), AppIcons.fileCode);+ });++ test('a kind nobody listed is the plain file', () {+ for (final name in ['LICENSE', 'data.bin', 'archive.', '.gitignore', '']) {+ expect(fileTypeIcon(name), AppIcons.file, reason: name);+ }+ });++ testWidgets("an attached file's chip wears its kind's mark", (tester) async {+ final files = HarnessAttachments()+ ..add([+ HarnessAttachment('spec.pdf', Uint8List.fromList(utf8.encode('%PDF'))),+ HarnessAttachment('main.dart', Uint8List.fromList(utf8.encode('//'))),+ ]);+ addTearDown(files.dispose);+ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(+ body: NewHarnessAttachmentChips(attachments: files, enabled: true),+ ),+ ),+ );+ IconData? mark(String name) => tester+ .widget<Icon>(find.byKey(ValueKey('new-harness-attachment-icon:$name')))+ .icon;+ expect(mark('spec.pdf'), AppIcons.fileText);+ expect(mark('main.dart'), AppIcons.fileCode);+ });+}diff --git a/desktop/test/new_harness_paste_test.dart b/desktop/test/new_harness_paste_test.dartnew file mode 100644index 000000000..2d40b792d--- /dev/null+++ b/desktop/test/new_harness_paste_test.dart@@ -0,0 +1,254 @@+// Paste in the New Harness box: a picture on the clipboard becomes an+// attachment, and text still goes into the task.+import 'dart:convert';++import 'package:flutter/foundation.dart';+import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/clipboard/copied_files.dart';+import 'package:harness/clipboard/pasted_text.dart';+import 'package:harness/state/harness_attachments.dart';+import 'package:harness/widgets/new_harness_attachments.dart';+import 'package:harness/widgets/new_harness_paste.dart';++/// A real 1×1 PNG, so a chip has something to draw.+final _png = base64Decode(+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA'+ '60e6kgAAAABJRU5ErkJggg==',+);++void main() {+ /// What the system clipboard holds as text; null is none.+ String? clipboardText;++ setUp(() {+ clipboardText = null;+ debugDefaultTargetPlatformOverride = TargetPlatform.macOS;+ final messenger =+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;+ messenger.setMockMethodCallHandler(SystemChannels.platform, (call) async {+ return switch (call.method) {+ 'Clipboard.getData' =>+ clipboardText == null ? null : {'text': clipboardText},+ 'Clipboard.hasStrings' => {'value': clipboardText != null},+ _ => null,+ };+ });+ addTearDown(+ () => messenger.setMockMethodCallHandler(SystemChannels.platform, null),+ );+ });++ Future<({HarnessAttachments files, TextEditingController task})> mount(+ WidgetTester tester, {+ Uint8List? image,+ CopiedFiles copied = (files: const [], tooLarge: const []),+ bool enabled = true,+ }) async {+ final files = HarnessAttachments();+ final task = TextEditingController();+ final focus = FocusNode();+ addTearDown(files.dispose);+ addTearDown(task.dispose);+ addTearDown(focus.dispose);+ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(+ body: NewHarnessPasteTarget(+ attachments: files,+ enabled: enabled,+ focusNode: focus,+ readFiles: () async => copied,+ readImage: () async => image,+ child: TextField(controller: task, focusNode: focus),+ ),+ ),+ ),+ );+ focus.requestFocus();+ await tester.pump();+ return (files: files, task: task);+ }++ Future<void> paste(WidgetTester tester) async {+ await tester.sendKeyDownEvent(LogicalKeyboardKey.metaLeft);+ await tester.sendKeyEvent(LogicalKeyboardKey.keyV);+ await tester.sendKeyUpEvent(LogicalKeyboardKey.metaLeft);+ await tester.pumpAndSettle();+ }++ List<String> names(HarnessAttachments files) => [+ for (final file in files.files) file.name,+ ];++ testWidgets('a picture on the clipboard is attached, each paste its own', (+ tester,+ ) async {+ final box = await mount(tester, image: _png);+ await paste(tester);+ expect(names(box.files), [kPastedImageName]);+ expect(box.files.files.single.bytes, _png);+ expect(box.task.text, isEmpty);++ await paste(tester);+ expect(names(box.files), [kPastedImageName, 'pasted-image-2.png']);+ debugDefaultTargetPlatformOverride = null;+ });++ testWidgets('text pastes into the task, a picture beside it or not', (+ tester,+ ) async {+ clipboardText = 'fix the login screen';+ final box = await mount(tester, image: _png);+ await paste(tester);+ expect(box.task.text, 'fix the login screen');+ expect(box.files.isEmpty, isTrue);+ debugDefaultTargetPlatformOverride = null;+ });++ testWidgets("a copied image's own web address does not hide the image", (+ tester,+ ) async {+ clipboardText = 'https://example.com/cat.png';+ final box = await mount(tester, image: _png);+ await paste(tester);+ expect(names(box.files), [kPastedImageName]);+ expect(box.task.text, isEmpty);+ debugDefaultTargetPlatformOverride = null;+ });++ testWidgets('with no picture, paste is the field\'s own', (tester) async {+ clipboardText = 'https://example.com/docs';+ final box = await mount(tester);+ await paste(tester);+ expect(box.task.text, 'https://example.com/docs');+ expect(box.files.isEmpty, isTrue);+ debugDefaultTargetPlatformOverride = null;+ });++ testWidgets('copied files are attached under their own names, and come '+ 'before the name and icon a file manager leaves beside them', (+ tester,+ ) async {+ // What Finder's Copy leaves: the files, their names as text, an icon.+ clipboardText = 'report.pdf\nshot.png';+ final box = await mount(+ tester,+ image: _png,+ copied: (+ files: [+ (name: 'report.pdf', bytes: Uint8List.fromList([1, 2])),+ (name: 'shot.png', bytes: _png),+ ],+ tooLarge: const [],+ ),+ );+ await paste(tester);+ expect(names(box.files), ['report.pdf', 'shot.png']);+ expect(box.task.text, isEmpty);++ // The same copy pasted again stands beside the first, never over it.+ await paste(tester);+ expect(names(box.files), [+ 'report.pdf',+ 'shot.png',+ 'report-2.pdf',+ 'shot-2.png',+ ]);+ debugDefaultTargetPlatformOverride = null;+ });++ testWidgets('a copied file over the limit is named, the rest attached', (+ tester,+ ) async {+ final box = await mount(+ tester,+ copied: (+ files: [+ (name: 'notes.txt', bytes: Uint8List.fromList([1])),+ ],+ tooLarge: const ['movie.mov'],+ ),+ );+ await paste(tester);+ expect(names(box.files), ['notes.txt']);+ expect(find.textContaining('movie.mov is over'), findsOneWidget);+ debugDefaultTargetPlatformOverride = null;+ });++ testWidgets('a locked box attaches nothing', (tester) async {+ final box = await mount(tester, image: _png, enabled: false);+ await paste(tester);+ expect(box.files.isEmpty, isTrue);+ debugDefaultTargetPlatformOverride = null;+ });++ testWidgets('a picture over the limit is refused, and says so', (+ tester,+ ) async {+ final box = await mount(+ tester,+ image: Uint8List(HarnessAttachments.maxBytes + 1),+ );+ await paste(tester);+ expect(box.files.isEmpty, isTrue);+ expect(find.textContaining('$kPastedImageName is over'), findsOneWidget);+ debugDefaultTargetPlatformOverride = null;+ });++ testWidgets('a picture\'s chip shows the picture; a file\'s, the file mark', (+ tester,+ ) async {+ final files = HarnessAttachments()+ ..add([+ HarnessAttachment(kPastedImageName, _png),+ HarnessAttachment('notes.txt', Uint8List.fromList(utf8.encode('hi'))),+ ]);+ addTearDown(files.dispose);+ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(+ body: NewHarnessAttachmentChips(attachments: files, enabled: true),+ ),+ ),+ );+ expect(+ find.byKey(+ const ValueKey('new-harness-attachment-preview:$kPastedImageName'),+ ),+ findsOneWidget,+ );+ expect(+ find.byKey(const ValueKey('new-harness-attachment-preview:notes.txt')),+ findsNothing,+ );+ expect(tester.takeException(), isNull);+ debugDefaultTargetPlatformOverride = null;+ });++ test('pasted files are numbered, never swapped for one of their name', () {+ final files = HarnessAttachments()+ ..add([HarnessAttachment('image.png', _png)]);+ addTearDown(files.dispose);+ files.addPasted([+ HarnessAttachment('image.png', _png),+ HarnessAttachment('image.png', _png),+ HarnessAttachment('Makefile', _png),+ HarnessAttachment('Makefile', _png),+ ]);+ expect(+ [for (final file in files.files) file.name],+ ['image.png', 'image-2.png', 'image-3.png', 'Makefile', 'Makefile-2'],+ );+ });++ test('text wins a paste unless it is only a web address', () {+ expect(pastedTextWins(null), isFalse);+ expect(pastedTextWins(' \n'), isFalse);+ expect(pastedTextWins('https://example.com/cat.png'), isFalse);+ expect(pastedTextWins('see https://example.com/cat.png'), isTrue);+ expect(pastedTextWins('Screenshot 2026-10-02.png'), isTrue);+ expect(pastedTextWins('line one\nline two'), isTrue);+ });+}diff --git a/desktop/test/web/pasted_files_test.dart b/desktop/test/web/pasted_files_test.dartnew file mode 100644index 000000000..0d1810a49--- /dev/null+++ b/desktop/test/web/pasted_files_test.dart@@ -0,0 +1,133 @@+@TestOn('browser')+library;++import 'dart:js_interop';+import 'dart:typed_data';++import 'package:flutter_test/flutter_test.dart';+import 'package:harness/clipboard/pasted_files.dart';+import 'package:web/web.dart' as web;++/// A paste the way a browser delivers one: files and text on a clipboard.+web.ClipboardEvent _paste({List<web.File> files = const [], String? text}) {+ final clipboard = web.DataTransfer();+ for (final file in files) {+ clipboard.items.add(file);+ }+ if (text != null) clipboard.setData('text/plain', text);+ return web.ClipboardEvent(+ 'paste',+ web.ClipboardEventInit(+ clipboardData: clipboard,+ bubbles: true,+ cancelable: true,+ ),+ );+}++web.File _file(String name, List<int> bytes) => web.File(+ [Uint8List.fromList(bytes).toJS].toJS,+ name,+ web.FilePropertyBag(type: 'image/png'),+);++void main() {+ late List<List<PastedFile>> heard;+ late void Function() stop;+ var wanted = true;++ setUp(() {+ heard = [];+ wanted = true;+ stop = listenForPastedFiles(wanted: () => wanted, onFiles: heard.add);+ });+ tearDown(() => stop());++ Future<bool> dispatch(web.ClipboardEvent event) async {+ web.document.body!.dispatchEvent(event);+ await Future<void>.delayed(const Duration(milliseconds: 50));+ return event.defaultPrevented;+ }++ test('a pasted picture is handed over, with its bytes, not typed', () async {+ final taken = await dispatch(+ _paste(+ files: [+ _file('image.png', [1, 2, 3]),+ ],+ ),+ );+ expect(taken, isTrue);+ expect(heard.single.single.name, 'image.png');+ expect(heard.single.single.bytes, [1, 2, 3]);+ });++ test('every file of one paste arrives together', () async {+ await dispatch(+ _paste(+ files: [+ _file('a.png', [1]),+ _file('b.png', [2, 2]),+ ],+ ),+ );+ expect([for (final file in heard.single) file.name], ['a.png', 'b.png']);+ });++ test('text beside the files is left for the field', () async {+ final taken = await dispatch(+ _paste(+ files: [+ _file('image.png', [1]),+ ],+ text: 'the words copied',+ ),+ );+ expect(taken, isFalse);+ expect(heard, isEmpty);+ });++ test("a copied image's own address does not hide the image", () async {+ final taken = await dispatch(+ _paste(+ files: [+ _file('image.png', [1]),+ ],+ text: 'https://example.com/cat.png',+ ),+ );+ expect(taken, isTrue);+ expect(heard, hasLength(1));+ });++ test('a paste of text alone, or one nobody wants, is not touched', () async {+ expect(await dispatch(_paste(text: 'hello')), isFalse);+ wanted = false;+ expect(+ await dispatch(+ _paste(+ files: [+ _file('image.png', [1]),+ ],+ ),+ ),+ isFalse,+ );+ expect(heard, isEmpty);+ });++ test('after stopping, nothing is heard', () async {+ stop();+ expect(+ await dispatch(+ _paste(+ files: [+ _file('image.png', [1]),+ ],+ ),+ ),+ isFalse,+ );+ expect(heard, isEmpty);+ });+}