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): paste from a hardware keyboard as the screen does
tony5c5f0bac21ad
diff --git a/mobile/lib/clipboard/native_clipboard.dart b/mobile/lib/clipboard/native_clipboard.dartindex a2a6a9b66..2cbba5e8a 100644--- a/mobile/lib/clipboard/native_clipboard.dart+++ b/mobile/lib/clipboard/native_clipboard.dart@@ -3,7 +3,7 @@ import 'dart:io';import 'package:flutter/services.dart';/// Flutter's own `Clipboard` (package:flutter/services.dart) only ever exposes `text/plain` — see-/// `widgets/terminal_panel.dart`'s `_paste()`. Reading a real IMAGE off the clipboard (a+/// `phone/terminal_paste.dart`'s `pasteClipboard()`. Reading a real IMAGE off the clipboard (a/// screenshot, "Copy Image" from a browser, ...) needs a native round trip instead: NSPasteboard on/// macOS (`macos/Runner/MainFlutterWindow.swift`), the GTK clipboard on Linux/// (`linux/runner/my_application.cc`), UIPasteboard on iOS (`ios/Runner/AppDelegate.swift`, readdiff --git a/mobile/lib/phone/terminal_page.dart b/mobile/lib/phone/terminal_page.dartindex 8a5d2bba1..2f1b00e98 100644--- a/mobile/lib/phone/terminal_page.dart+++ b/mobile/lib/phone/terminal_page.dart@@ -2294,7 +2294,9 @@ class _TerminalPageState extends State<TerminalPage>: null,onBandTap: _onAnswerBand,// A long press on the prompt offers Paste, as- // a text field's does — see [_paste].+ // a text field's does; a hardware ⌘V (Ctrl+V+ // on Android) and a right- or middle-click+ // paste through it too — see [_paste].onPaste: () =>_paste(session),// Where the reader is in the history —@@ -2738,8 +2740,9 @@ class _TerminalPageState extends State<TerminalPage>onTap: () => _paste(session),);- /// The clipboard into [session] — the sheet's Paste row, and the Paste of a long press on the- /// prompt (`TerminalPanel.onPaste`). One path for both, so both read the image as well as the+ /// The clipboard into [session] — the sheet's Paste row, the key bar's paste, and the panel's+ /// own pastes (`TerminalPanel.onPaste`): a long press on the prompt, a hardware ⌘V (Ctrl+V on+ /// Android), a right- or middle-click. One path for all, so all read the image as well as the/// text, ask iOS once, and send only into the terminal still on screen.void _paste(TerminalSession session) {final messenger = ScaffoldMessenger.maybeOf(context);diff --git a/mobile/lib/phone/terminal_paste.dart b/mobile/lib/phone/terminal_paste.dartindex d2d135275..84a8b8aaf 100644--- a/mobile/lib/phone/terminal_paste.dart+++ b/mobile/lib/phone/terminal_paste.dart@@ -12,8 +12,11 @@ const pasteChangedMessage =/// Pastes the phone's clipboard into [session]: its text as one paste rather than as typing, or,/// when there is no text, its image, the same upload the key bar's image button makes.///-/// The Paste row of the terminal's actions sheet (`phone/terminal_page.dart`). iOS has no other way-/// in: long-press on the terminal is selection there, and the soft keyboard has no paste key.+/// The Paste row of the terminal's actions sheet (`phone/terminal_page.dart`), and every other paste+/// the page offers through it: the key bar's paste, the long-press Paste on the prompt, and a+/// hardware keyboard's ⌘V (Ctrl+V on Android) or a right- or middle-click on the terminal+/// (`TerminalPanel.onPaste`). iOS has no other way in: long-press on the output is selection there,+/// and the soft keyboard has no paste key.////// Text is asked about first with [Clipboard.hasStrings], which iOS answers without its "Allow/// Paste" prompt, so the person is asked once, for the one thing actually read. Unlike thediff --git a/mobile/lib/state/app_state.dart b/mobile/lib/state/app_state.dartindex f5baa07f4..d2492e291 100644--- a/mobile/lib/state/app_state.dart+++ b/mobile/lib/state/app_state.dart@@ -188,7 +188,8 @@ class MachineState {bool terminalPasteRawAvailable = false;// Whether this machine's CLI daemon understands TerminalBinaryKind.imagePaste (a native clipboard// IMAGE paste — see TerminalSession.pasteImage). False for any CLI published before this existed;- // the panel falls back to forwarding a bare Ctrl+V, today's only option for an image paste.+ // the phone then says the machine is too old to receive images (phone/terminal_paste.dart) and+ // never forwards a bare Ctrl+V, which would paste the far machine's clipboard, not the phone's.bool terminalImagePasteAvailable = false;// Whether this machine's CLI daemon understands TerminalBinaryKind.pasteFile (a dropped non-image// file, written to disk on that machine and pasted as a path — see TerminalSession.pasteFile).diff --git a/mobile/lib/widgets/terminal_panel.dart b/mobile/lib/widgets/terminal_panel.dartindex 65edecc31..2ea43fe43 100644--- a/mobile/lib/widgets/terminal_panel.dart+++ b/mobile/lib/widgets/terminal_panel.dart@@ -9,7 +9,6 @@ import 'package:flutter/semantics.dart';import 'package:flutter/services.dart';import 'package:xterm/xterm.dart';-import '../clipboard/native_clipboard.dart';import '../logging/typing_trace.dart';import '../state/app_state.dart';@@ -119,8 +118,13 @@ class TerminalPanel extends StatefulWidget {/// [onLineTap], and whether or not [onInputTap] is set: a band is drawn to be pressed.final void Function(TerminalLineBand band)? onBandTap;- /// Pastes the phone's clipboard into the session — the Paste of a long press on the prompt- /// (see `_TerminalPanelState._openPromptMenu`). Null offers no Paste there.+ /// Pastes the phone's clipboard into the session — every paste the pane itself is asked for: the+ /// Paste of a long press on the prompt (see `_TerminalPanelState._openPromptMenu`), a hardware+ /// keyboard's ⌘V (Ctrl+V on Android), and a right- or middle-click with nothing selected (see+ /// `_TerminalPanelState._paste`). Only called while the session takes input.+ ///+ /// Null offers no Paste on the prompt, and leaves the keys and clicks a paste of the clipboard's+ /// text alone — see `_TerminalPanelState._pasteTextOnly` for why only the text.final VoidCallback? onPaste;/// Test seam for OS actions; normal panes use the platform launcher.@@ -869,9 +873,9 @@ class _TerminalPanelState extends State<TerminalPanel>/// Paste while the session takes input.////// ⚠️ **Paste is the page's, not the panel's.** What it reads and how it sends lives in- /// `phone/terminal_paste.dart`, behind [TerminalPanel.onPaste]: the panel's own [_paste] is the- /// desktop's ⌘V, whose last resort is a Ctrl+V for the engine to read ITS clipboard — on a- /// phone that is the far machine's clipboard, not the one the person just copied to.+ /// `phone/terminal_paste.dart`, behind [TerminalPanel.onPaste] — the same path a hardware ⌘V and+ /// a right-click take (see [_paste]), so every way into a paste reads THIS phone's clipboard,+ /// never the far machine's, and tells the person when there was nothing to send.bool _openPromptMenu(CellOffset cell) {final buffer = _viewTerminal.buffer;if (!_canPasteHere &&@@ -1172,6 +1176,9 @@ class _TerminalPanelState extends State<TerminalPanel>_scheduleMenu();}+ /// A right-click — or a middle-click, which xterm's gesture handler routes to this same callback+ /// — on a mouse or trackpad: copies the selection when there is one, and otherwise pastes exactly+ /// as a hardware ⌘V does ([_paste]).Future<void> _copyOrPaste() async {final terminal = widget.session.terminal;final selection = _controller.selection;@@ -1184,28 +1191,13 @@ class _TerminalPanelState extends State<TerminalPanel>await _paste();}- /// Paste — including the kinds of clipboard this app cannot fully read.- ///- /// ⚠️ FLUTTER'S OWN `Clipboard` API ONLY SEES `text/plain`. A screenshot has no- /// text at all, so a naive body finds `null` and returns, silently: the single- /// most common thing anyone pastes into a coding agent did nothing, with no- /// error and nothing in a log. [NativeClipboard] closes that gap with a native- /// platform-channel read for an actual image (all but Windows; see its doc).- ///- /// The engines running in these panes read the system clipboard THEMSELVES —- /// Claude Code attaches an image on Ctrl+V — so on a LOCAL pane that is already- /// true with zero help from us: a bare Ctrl+V is all that ever ran here, before- /// native image paste existed, and it still works because the engine and this- /// app share the exact same OS clipboard. The wire-based `pasteImage` (chunked- /// upload, daemon writes the far side's OS clipboard, daemon replays Ctrl+V) is- /// reserved for a genuinely REMOTE pane, whose engine reads a DIFFERENT- /// clipboard than this one — which, on a phone, is every pane./// An image handed over by the software keyboard's own clipboard.////// Flutter's [Clipboard] reads `text/plain` and nothing else, and Gboard hands/// the bytes over directly, so there is no clipboard to read at all. (The- /// actions sheet's Paste reads the system clipboard's image instead, through- /// [NativeClipboard]: see `phone/terminal_paste.dart`.)+ /// actions sheet's Paste — and a hardware ⌘V, see [_paste] — reads the system+ /// clipboard's image instead, through `NativeClipboard`: see+ /// `phone/terminal_paste.dart`.)////// ⚠️ A pane on a phone is ALWAYS remote — the agent runs on another machine,/// whose engine reads a different OS clipboard — so unlike the desktop there is@@ -1220,39 +1212,86 @@ class _TerminalPanelState extends State<TerminalPanel>unawaited(widget.session.pasteImage(bytes));}+ /// The paste of a hardware keyboard's ⌘V (Ctrl+V on Android) and of a right- or middle-click:+ /// the host's [TerminalPanel.onPaste] — on the phone the page's paste, `phone/terminal_paste.dart`,+ /// the one the prompt's long-press Paste, the key bar's paste and the actions sheet's Paste run.+ /// So a key does exactly what the on-screen Paste does: the text pasted, an image scaled under+ /// the upload's ceiling and sent, and a word to the person when there was nothing to send.+ ///+ /// ⚠️ **Never a Ctrl+V for the engine to read its own clipboard.** That was this method's last+ /// resort while it was the desktop's ⌘V, where the engine and the app share one OS clipboard. A+ /// pane on a phone is ALWAYS remote, so the Ctrl+V reached the far machine and its engine pasted+ /// THAT machine's clipboard — something the person never copied on this phone, with nothing on+ /// screen to say why. The desktop's paste also sent the clipboard's image as it came, unscaled,+ /// and iOS hands it over at full size: a photo from the library easily went over the upload's+ /// ceiling and fell through to that same Ctrl+V.+ ///+ /// ⚠️ **Not asked while the pane cannot take input** — a watcher, a stream taken over or closed.+ /// The host's paste reads the clipboard first and checks only after, so asked here it would raise+ /// iOS's "Allow Paste" prompt for a paste that could only be refused, and then say the terminal+ /// changed when it did not. The prompt's Paste is held to the same rule by [_canPasteHere].Future<void> _paste() async {- if (!widget.session.acceptsInput) return;- final text = (await Clipboard.getData(Clipboard.kTextPlain))?.text;- if (text != null && text.isNotEmpty) {- // A binary TerminalBinaryKind.paste frame rides the same AEAD channel as every other terminal- // byte, so this works identically for a local or a relayed machine — see pasteText's doc. Only- // the CLI's own version gates it: an older daemon never advertises the capability.- final machine = widget.notifier.stateOf(widget.session.machineId);- if (machine != null && machine.terminalPasteRawAvailable) {- await widget.session.pasteText(text);- } else {- widget.session.terminal.paste(text);- }+ final session = widget.session;+ if (!session.acceptsInput) return;+ final paste = widget.onPaste;+ if (paste != null) {+ paste();return;}- final machine = widget.notifier.stateOf(widget.session.machineId);- if (machine != null && machine.terminalImagePasteAvailable) {- final imageBytes = await NativeClipboard.readImagePng();- if (imageBytes != null &&- imageBytes.isNotEmpty &&- imageBytes.length <= terminalLocalImagePasteMaxPayloadBytes) {- await widget.session.pasteImage(imageBytes);- return;- }+ await _pasteTextOnly(session);+ }++ /// The paste of a pane whose host gave it no [TerminalPanel.onPaste]: the clipboard's TEXT, as+ /// one paste, and nothing else. The phone's own page always gives one; this is for any other+ /// host of the panel — today, only tests.+ ///+ /// ⚠️ **Text only, and that is the safe half, not a shortcut.** An image needs what only a host+ /// has: the transcode that scales a photo under the upload's ceiling, a place to tell the person+ /// why nothing went, and its own word on whether it still shows this terminal. Without them a+ /// clipboard with no text on it pastes nothing — never the Ctrl+V that pasted the far machine's+ /// clipboard instead (see [_paste]).+ ///+ /// Text is asked about first with [Clipboard.hasStrings], which iOS answers without its "Allow+ /// Paste" prompt, so a clipboard holding only an image is never read at all. And the text lands+ /// only where the key was pressed: the read can wait on that prompt, and in that time the pane can+ /// have been handed another session, or its stream reconnected or taken over — the same rule+ /// `phone/terminal_paste.dart` holds the page's paste to.+ Future<void> _pasteTextOnly(TerminalSession session) async {+ final streamId = session.streamId;+ final String? text;+ try {+ if (!await Clipboard.hasStrings()) return;+ text = (await Clipboard.getData(Clipboard.kTextPlain))?.text;+ } on PlatformException {+ // Nothing was sent and there is nobody to tell: the same as an empty clipboard.+ return;+ }+ if (text == null || text.isEmpty) return;+ if (!mounted ||+ !identical(widget.session, session) ||+ !session.acceptsInput ||+ session.streamId != streamId) {+ return;+ }+ // A binary TerminalBinaryKind.paste frame rides the same AEAD channel as every other terminal+ // byte, so this works identically for a local or a relayed machine — see pasteText's doc. Only+ // the CLI's own version gates it: an older daemon never advertises the capability.+ final machine = widget.notifier.stateOf(session.machineId);+ if (machine != null && machine.terminalPasteRawAvailable) {+ await session.pasteText(text);+ } else {+ session.terminal.paste(text);}- widget.session.terminal.keyInput(TerminalKey.keyV, ctrl: true);}- /// ⌘V (Ctrl+V off Apple) — taken from xterm so the fallthrough above applies.+ /// ⌘V (Ctrl+V on Android) from a hardware keyboard — taken from xterm so it pastes what [_paste]+ /// pastes: the phone's clipboard, through the host's paste.///- /// xterm binds paste itself, but only ever to its text-only action. `onKeyEvent`- /// is the one hook that runs BEFORE its shortcut map (terminal_view.dart), so- /// this is where the binding has to be replaced rather than added.+ /// xterm binds paste itself, but only ever to its text-only action, which reads no image and says+ /// nothing when there is nothing to paste. `onKeyEvent` is the one hook that runs BEFORE its+ /// shortcut map (terminal_view.dart), so this is where the binding has to be replaced rather than+ /// added. Only this chord is taken: ⇧⌘V, iOS's ⌃V (a keystroke for the far program, like any+ /// other control key) and every other key go on to xterm as they always did.KeyEventResult _onTerminalKey(FocusNode node, KeyEvent event) {if (event is! KeyDownEvent) return KeyEventResult.ignored;if (event.logicalKey != LogicalKeyboardKey.keyV) {diff --git a/mobile/test/phone_edge/focus_behavior_test.dart b/mobile/test/phone_edge/focus_behavior_test.dartindex 2138c9e9f..364a4be8e 100644--- a/mobile/test/phone_edge/focus_behavior_test.dart+++ b/mobile/test/phone_edge/focus_behavior_test.dart@@ -1,6 +1,7 @@import 'dart:async';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';@@ -645,6 +646,61 @@ void main() {});});+ // ⌘V on an iPad's keyboard, Ctrl+V on an Android one: the menu's own Paste, not the desktop's —+ // which ended in a ⌃V that pasted the far machine's clipboard rather than this phone's.+ group('a hardware keyboard\'s paste', () {+ final phones = TargetPlatformVariant({+ TargetPlatform.iOS,+ TargetPlatform.android,+ });++ /// The page, typing into its terminal.+ Future<_Focus> typing(WidgetTester tester) async {+ final focus = await _Focus.open(tester);+ await focus.tapPrompt();+ await tester.pump();+ raiseKeyboard(tester);+ await frames(tester);+ return focus;+ }++ Future<void> pasteChord(WidgetTester tester) async {+ final ios = defaultTargetPlatform == TargetPlatform.iOS;+ final platform = ios ? 'ios' : 'android';+ final modifier = ios+ ? LogicalKeyboardKey.metaLeft+ : LogicalKeyboardKey.controlLeft;+ await tester.sendKeyDownEvent(modifier, platform: platform);+ await tester.sendKeyEvent(LogicalKeyboardKey.keyV, platform: platform);+ await tester.sendKeyUpEvent(modifier, platform: platform);+ await frames(tester);+ }++ testWidgets('pastes the clipboard\'s text as the menu\'s Paste does', (+ tester,+ ) async {+ final focus = await typing(tester);+ _clipboard = {'text': 'git status'};+ await pasteChord(tester);+ expect(focus.typed.join(), contains('git status'));+ await focus.close();+ }, variant: phones);++ testWidgets('with nothing on the clipboard says so, and sends no ⌃V', (+ tester,+ ) async {+ final focus = await typing(tester);+ _clipboard = null;+ await pasteChord(tester);+ expect(focus.typed.join(), isNot(contains('\x16')));+ expect(+ find.text('There is nothing on the clipboard to paste.'),+ findsOneWidget,+ );+ await focus.close();+ }, variant: phones);+ });+group('a question', () {Future<_Focus> asked(WidgetTester tester) async {final focus = await _Focus.open(tester);diff --git a/mobile/test/terminal_panel_fixture.dart b/mobile/test/terminal_panel_fixture.dartindex 5de53c208..687002d69 100644--- a/mobile/test/terminal_panel_fixture.dart+++ b/mobile/test/terminal_panel_fixture.dart@@ -11,16 +11,18 @@ AppNotifier panelNotifier() => AppNotifier();/// A session already controlling its stream, so the pane takes input. Every-/// frame is accepted unless the test listens for it.+/// frame is accepted unless the test listens for it. [engineId] is an agent's+/// unless the test asks for a plain shell (`terminal`).TerminalSession controllingSession({TerminalFrameSender? send,TerminalBinarySender? sendBinary,+ String engineId = 'claude',}) =>TerminalSession(machineId: 'm',agentId: 'a',agentName: 'Agent',- engineId: 'claude',+ engineId: engineId,send: send ?? (_, _) async => true,sendBinary: sendBinary ?? (_) async => true,)diff --git a/mobile/test/terminal_panel_paste_test.dart b/mobile/test/terminal_panel_paste_test.dartnew file mode 100644index 000000000..eaa4fb1be--- /dev/null+++ b/mobile/test/terminal_panel_paste_test.dart@@ -0,0 +1,629 @@+// NativeClipboard asks its channel only where a runner answers it, which a Windows host is not.+@TestOn('!windows')+library;++import 'dart:async';+import 'dart:convert';++import 'package:flutter/foundation.dart';+import 'package:flutter/gestures.dart';+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/terminal_paste.dart';+import 'package:harness_mobile/state/app_state.dart';+import 'package:harness_mobile/terminal/terminal_binary.dart';+import 'package:harness_mobile/terminal/terminal_session.dart';+import 'package:harness_mobile/widgets/terminal_panel.dart';+import 'package:xterm/xterm.dart';++import 'terminal_panel_fixture.dart';++/// A hardware keyboard's ⌘V (Ctrl+V on Android) and a right- or middle-click on the terminal, with+/// the pane's paste hooked up the way the phone's page hooks it: to `pasteClipboard`, the path the+/// on-screen Paste takes. They must do exactly what that Paste does — and never hand the far+/// machine a ⌃V, which pasted THAT machine's clipboard rather than this phone's.+///+/// Every other key stays the terminal's, as it was.+void main() {+ final phones = TargetPlatformVariant({+ TargetPlatform.iOS,+ TargetPlatform.android,+ });++ late AppNotifier notifier;+ late _Wire wire;+ late List<String> reports;+ late int hostPastes;++ setUp(() {+ notifier = panelNotifier();+ wire = _Wire();+ reports = [];+ hostPastes = 0;+ });++ tearDown(() => notifier.dispose());++ /// ⚠️ Built inside each test, never in `setUp`: the session's send queue is a Future, and one+ /// made outside the test's fake clock never drains in it.+ TerminalSession session({String engineId = 'claude'}) {+ final made = controllingSession(+ engineId: engineId,+ send: (type, payload) async {+ wire.frames.add((type: type, payload: payload));+ return true;+ },+ sendBinary: (frame) async {+ wire.binaries.add(frame);+ return true;+ },+ );+ addTearDown(made.dispose);+ return made;+ }++ /// The machine the pane's agent runs on, as the phone knows it.+ void machine({bool pasteRaw = false, bool imagePaste = false}) {+ notifier.machineStates['m'] =+ MachineState(+ const Machine(+ machineId: 'm',+ authMode: MachineAuthMode.remote,+ name: 'Studio',+ ),+ )+ ..terminalPasteRawAvailable = pasteRaw+ ..terminalImagePasteAvailable = imagePaste;+ }++ /// A focused pane. [hosted] gives it the paste `TerminalPage._paste` gives it: the phone's own+ /// path, told whether the page still shows this terminal and where to say what happened.+ Future<void> pumpPanel(+ WidgetTester tester,+ TerminalSession pane, {+ bool hosted = true,+ }) async {+ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(+ body: Align(+ alignment: Alignment.topLeft,+ child: SizedBox(+ width: 400,+ height: 320,+ child: TerminalPanel(+ notifier: notifier,+ session: pane,+ focused: true,+ onPaste: hosted+ ? () {+ hostPastes++;+ unawaited(+ pasteClipboard(+ session: pane,+ machine: notifier.stateOf(pane.machineId),+ stillShowing: () => true,+ report: reports.add,+ ),+ );+ }+ : null,+ ),+ ),+ ),+ ),+ ),+ );+ await tester.pump();+ await tester.pump();+ }++ /// [key] pressed with [modifiers] held, from a hardware keyboard on the phone the test runs as.+ Future<void> chord(+ WidgetTester tester,+ LogicalKeyboardKey key, [+ List<LogicalKeyboardKey> modifiers = const [],+ ]) async {+ final platform = defaultTargetPlatform == TargetPlatform.iOS+ ? 'ios'+ : 'android';+ for (final modifier in modifiers) {+ await tester.sendKeyDownEvent(modifier, platform: platform);+ }+ await tester.sendKeyEvent(key, platform: platform);+ for (final modifier in modifiers.reversed) {+ await tester.sendKeyUpEvent(modifier, platform: platform);+ }+ // Past the session's input coalescing, so every key is on the wire.+ await tester.pump(const Duration(milliseconds: 50));+ }++ /// The paste chord of the phone the test runs as: ⌘V on iOS, Ctrl+V on Android.+ Future<void> pasteChord(WidgetTester tester) =>+ chord(tester, LogicalKeyboardKey.keyV, [+ defaultTargetPlatform == TargetPlatform.iOS+ ? LogicalKeyboardKey.metaLeft+ : LogicalKeyboardKey.controlLeft,+ ]);++ /// A mouse or trackpad click on the terminal with [buttons], away from anything drawn over it.+ Future<void> click(WidgetTester tester, int buttons) async {+ final view = tester.getRect(find.byType(TerminalView));+ await tester.tapAt(+ view.topLeft + const Offset(40, 20),+ buttons: buttons,+ kind: PointerDeviceKind.mouse,+ );+ await tester.pump(const Duration(milliseconds: 50));+ }++ /// Lets the platform's image codec run until [done] holds. Decoding is real work on the engine's+ /// own threads, which the test's fake clock never waits for, so each turn steps out to the real+ /// clock and then pumps what came back.+ Future<void> decodeUntil(WidgetTester tester, bool Function() done) async {+ for (var turn = 0; turn < 200 && !done(); turn++) {+ await tester.runAsync(+ () => Future<void>.delayed(const Duration(milliseconds: 10)),+ );+ await tester.pump();+ }+ expect(done(), isTrue, reason: 'the clipboard image was decoded');+ }++ group('⌘V (Ctrl+V on Android) pastes as the on-screen Paste does', () {+ testWidgets(+ 'the text goes out as one paste, asked about before it is read',+ (tester) async {+ final clipboard = _Clipboard(tester)..text = 'git status';+ machine(pasteRaw: true);+ await pumpPanel(tester, session());++ await pasteChord(tester);++ expect(hostPastes, 1);+ expect(wire.pasted, ['git status']);+ expect(wire.input, isNot(contains('\x16')));+ expect(reports, isEmpty);+ // iOS answers `hasStrings` without its "Allow Paste" prompt, so the person is asked once,+ // for the one thing actually read.+ expect(clipboard.methods, [+ 'Clipboard.hasStrings',+ 'Clipboard.getData',+ ]);+ },+ variant: phones,+ );++ testWidgets('an image over the upload\'s ceiling is scaled down and sent', (+ tester,+ ) async {+ // What iOS hands over for a photo from the library: the image at its own size, past what+ // one upload takes. A real picture, padded past the ceiling with bytes a decoder skips.+ final clipboard = _Clipboard(tester)+ ..image = Uint8List.fromList([+ ..._onePixelPng,+ ...Uint8List(terminalLocalImagePasteMaxPayloadBytes + 1),+ ]);+ machine(imagePaste: true);+ await pumpPanel(tester, session());++ await pasteChord(tester);+ // Until the upload is asked for, or a key went out in its place.+ await decodeUntil(+ tester,+ () => wire.uploadBegin != null || wire.input.isNotEmpty,+ );++ expect(wire.input, isNot(contains('\x16')));+ expect(hostPastes, 1);+ expect(clipboard.imageReads, 1);+ expect(+ wire.uploadBegin!['totalBytes'],+ allOf(greaterThan(0), lessThan(clipboard.image!.length)),+ );+ expect(reports, isEmpty);+ // The upload's own wait for the machine to accept it runs out.+ await tester.pump(const Duration(seconds: 11));+ }, variant: phones);++ testWidgets(+ 'an empty clipboard is said, and no ⌃V goes to the far machine',+ (tester) async {+ final clipboard = _Clipboard(tester);+ machine(imagePaste: true);+ await pumpPanel(tester, session());++ await pasteChord(tester);++ expect(wire.input, isNot(contains('\x16')));+ expect(wire.binaries, isEmpty, reason: 'no ⌃V, no paste');+ expect(hostPastes, 1);+ expect(reports, ['There is nothing on the clipboard to paste.']);+ expect(wire.uploadBegin, isNull);+ // No text, so the text was never read — and iOS never asked about it.+ expect(clipboard.methods, isNot(contains('Clipboard.getData')));+ },+ variant: phones,+ );++ testWidgets(+ 'an image the phone cannot read is said, and no ⌃V goes instead',+ (tester) async {+ // What the native side answers for an image it found but could not re-encode.+ _Clipboard(tester).image = Uint8List(0);+ machine(imagePaste: true);+ await pumpPanel(tester, session());++ await pasteChord(tester);++ expect(wire.input, isNot(contains('\x16')));+ expect(wire.binaries, isEmpty);+ expect(reports, [+ "The clipboard's image isn't one this phone can read.",+ ]);+ expect(wire.uploadBegin, isNull);+ },+ variant: phones,+ );++ testWidgets(+ 'bytes that are not a picture are said to be unreadable, not sent as '+ 'they came',+ (tester) async {+ _Clipboard(tester).image = Uint8List.fromList([1, 2, 3, 4]);+ machine(imagePaste: true);+ await pumpPanel(tester, session());++ await pasteChord(tester);+ await decodeUntil(tester, () => reports.isNotEmpty);++ expect(reports, [+ "The clipboard's image isn't one this phone can read.",+ ]);+ expect(wire.uploadBegin, isNull);+ expect(wire.binaries, isEmpty);+ },+ variant: phones,+ );++ testWidgets('a plain shell is not offered the image, and no ⌃V either', (+ tester,+ ) async {+ final clipboard = _Clipboard(tester)..image = _onePixelPng;+ machine(imagePaste: true);+ await pumpPanel(tester, session(engineId: 'terminal'));++ await pasteChord(tester);++ // The CLI delivers an image by replaying ⌃V, which a shell reads as quoted-insert.+ expect(clipboard.imageReads, 0);+ expect(reports, ['There is no text on the clipboard.']);+ expect(wire.binaries, isEmpty);+ expect(wire.uploadBegin, isNull);+ }, variant: phones);++ testWidgets(+ 'a terminal that reconnected during the read is not pasted into',+ (tester) async {+ final pane = session();+ _Clipboard(tester)+ ..text = 'git status'+ // The read waits on iOS's prompt, and the stream came back as another one meanwhile.+ ..onRead = () => pane.streamId = 's2';+ machine(pasteRaw: true);+ await pumpPanel(tester, pane);++ await pasteChord(tester);++ expect(wire.pasted, isEmpty);+ expect(reports, [pasteChangedMessage]);+ },+ variant: phones,+ );++ testWidgets(+ 'a pane that cannot take input reads nothing and sends nothing',+ (tester) async {+ final clipboard = _Clipboard(tester)..text = 'git status';+ machine(pasteRaw: true);+ final pane = session();+ await pumpPanel(tester, pane);+ pane.status = TerminalSessionStatus.takenOver;++ await pasteChord(tester);++ // Not even read: asked, iOS would raise its "Allow Paste" prompt for a paste that could only+ // be refused. And the key is still taken, so xterm's own paste does not read it either.+ expect(hostPastes, 0);+ expect(clipboard.methods, isEmpty);+ expect(wire.binaries, isEmpty);+ expect(reports, isEmpty);+ },+ variant: phones,+ );+ });++ group('a right- or middle-click', () {+ testWidgets('with nothing selected pastes as ⌘V does', (tester) async {+ _Clipboard(tester).text = 'git status';+ machine(pasteRaw: true);+ await pumpPanel(tester, session());++ await click(tester, kSecondaryMouseButton);++ expect(hostPastes, 1);+ expect(wire.pasted, ['git status']);+ expect(reports, isEmpty);+ }, variant: phones);++ testWidgets('with an empty clipboard says so, and sends no ⌃V', (+ tester,+ ) async {+ _Clipboard(tester);+ machine(imagePaste: true);+ await pumpPanel(tester, session());++ await click(tester, kSecondaryMouseButton);++ expect(wire.input, isNot(contains('\x16')));+ expect(wire.binaries, isEmpty);+ expect(hostPastes, 1);+ expect(reports, ['There is nothing on the clipboard to paste.']);+ }, variant: phones);++ testWidgets('a middle-click pastes the same way', (tester) async {+ _Clipboard(tester).text = 'git status';+ machine(pasteRaw: true);+ await pumpPanel(tester, session());++ await click(tester, kMiddleMouseButton);++ expect(hostPastes, 1);+ expect(wire.pasted, ['git status']);+ }, variant: phones);++ testWidgets('with a selection copies it, and pastes nothing', (+ tester,+ ) async {+ final clipboard = _Clipboard(tester)..text = 'git status';+ machine(pasteRaw: true);+ final pane = session();+ pane.terminal.write('${'\r\n' * 30}npm test\r\nall 42 passed');+ await pumpPanel(tester, pane);+ final view = tester.widget<TerminalView>(find.byType(TerminalView));+ final buffer = pane.terminal.buffer;+ final row = buffer.lines.length - 1;+ view.controller!.setSelection(+ buffer.createAnchor(0, row),+ buffer.createAnchor(13, row),+ );+ await tester.pump();++ await click(tester, kSecondaryMouseButton);++ expect(clipboard.copied, 'all 42 passed');+ expect(view.controller!.selection, isNull);+ expect(hostPastes, 0);+ expect(wire.binaries, isEmpty);+ }, variant: phones);++ testWidgets(+ 'on a pane with no paste of its host\'s, pastes only text, and never a ⌃V',+ (tester) async {+ final clipboard = _Clipboard(tester)..image = _onePixelPng;+ machine(pasteRaw: true, imagePaste: true);+ await pumpPanel(tester, session(), hosted: false);++ await click(tester, kSecondaryMouseButton);++ // No text: nothing at all — the image is the host's to send, and a ⌃V would read the far+ // machine's clipboard.+ expect(clipboard.imageReads, 0);+ expect(clipboard.methods, isNot(contains('Clipboard.getData')));+ expect(wire.binaries, isEmpty);+ expect(wire.uploadBegin, isNull);++ clipboard.text = 'git status';+ await click(tester, kSecondaryMouseButton);++ expect(wire.pasted, ['git status']);+ },+ variant: phones,+ );+ });++ group('every other key is the terminal\'s, as it was', () {+ testWidgets('Ctrl+C interrupts', (tester) async {+ final clipboard = _Clipboard(tester)..text = 'git status';+ machine(pasteRaw: true);+ await pumpPanel(tester, session());++ await chord(tester, LogicalKeyboardKey.keyC, [+ LogicalKeyboardKey.controlLeft,+ ]);++ expect(wire.input, '\x03');+ expect(hostPastes, 0);+ expect(clipboard.methods, isEmpty);+ }, variant: phones);++ testWidgets('an arrow moves through the history', (tester) async {+ _Clipboard(tester).text = 'git status';+ machine(pasteRaw: true);+ await pumpPanel(tester, session());++ await chord(tester, LogicalKeyboardKey.arrowUp);++ expect(wire.input, '\x1b[A');+ expect(hostPastes, 0);+ }, variant: phones);++ testWidgets('a bare V is a letter, typed through the keyboard', (+ tester,+ ) async {+ final clipboard = _Clipboard(tester)..text = 'git status';+ machine(pasteRaw: true);+ await pumpPanel(tester, session());++ // A hardware letter is the keyboard's to type: the key goes by, and the text arrives through+ // the input connection.+ await chord(tester, LogicalKeyboardKey.keyV);+ final typed = '${tester.testTextInput.editingState!['text']}v';+ tester.testTextInput.updateEditingValue(+ TextEditingValue(+ text: typed,+ selection: TextSelection.collapsed(offset: typed.length),+ ),+ );+ await tester.pump(const Duration(milliseconds: 50));++ expect(wire.input, 'v');+ expect(wire.pasted, isEmpty);+ expect(hostPastes, 0);+ expect(clipboard.methods, isEmpty);+ }, variant: phones);++ testWidgets('⌘C (Ctrl+Shift+C on Android) copies the selection', (+ tester,+ ) async {+ final clipboard = _Clipboard(tester);+ machine(pasteRaw: true);+ final pane = session();+ pane.terminal.write('npm test');+ await pumpPanel(tester, pane);+ final buffer = pane.terminal.buffer;+ tester+ .widget<TerminalView>(find.byType(TerminalView))+ .controller!+ .setSelection(buffer.createAnchor(0, 0), buffer.createAnchor(8, 0));+ await tester.pump();++ await chord(+ tester,+ LogicalKeyboardKey.keyC,+ defaultTargetPlatform == TargetPlatform.iOS+ ? [LogicalKeyboardKey.metaLeft]+ : [LogicalKeyboardKey.controlLeft, LogicalKeyboardKey.shiftLeft],+ );++ expect(clipboard.copied, 'npm test');+ expect(wire.binaries, isEmpty);+ expect(hostPastes, 0);+ }, variant: phones);++ testWidgets('⇧ with the paste chord is not this paste', (tester) async {+ _Clipboard(tester).text = 'git status';+ machine(pasteRaw: true);+ await pumpPanel(tester, session());++ await chord(tester, LogicalKeyboardKey.keyV, [+ defaultTargetPlatform == TargetPlatform.iOS+ ? LogicalKeyboardKey.metaLeft+ : LogicalKeyboardKey.controlLeft,+ LogicalKeyboardKey.shiftLeft,+ ]);++ expect(hostPastes, 0);+ expect(wire.pasted, isEmpty);+ }, variant: phones);++ testWidgets("iOS's ⌃V is a keystroke for the far program, not a paste", (+ tester,+ ) async {+ final clipboard = _Clipboard(tester)..text = 'git status';+ machine(pasteRaw: true);+ await pumpPanel(tester, session());++ await chord(tester, LogicalKeyboardKey.keyV, [+ LogicalKeyboardKey.controlLeft,+ ]);++ // Typed on purpose — Claude Code reads it as its own image paste — so it goes as typed.+ expect(wire.input, '\x16');+ expect(hostPastes, 0);+ expect(clipboard.methods, isEmpty);+ }, variant: TargetPlatformVariant.only(TargetPlatform.iOS));+ });+}++/// A 1x1 PNG, for an image the transcode can actually read.+final _onePixelPng = base64Decode(+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==',+);++/// Everything the pane put on the wire.+class _Wire {+ final frames = <({String type, Map<String, dynamic> payload})>[];+ final binaries = <TerminalBinaryFrame>[];++ /// What was typed as input, as text.+ String get input => utf8.decode([+ for (final frame in binaries)+ if (frame.kind == TerminalBinaryKind.input) ...frame.bytes,+ ], allowMalformed: true);++ /// Each paste sent as one paste frame, as text.+ List<String> get pasted => [+ for (final frame in binaries)+ if (frame.kind == TerminalBinaryKind.paste) utf8.decode(frame.bytes),+ ];++ /// The announcement of an image upload, or null when none was asked for.+ Map<String, dynamic>? get uploadBegin {+ for (final frame in frames) {+ if (frame.type == 'terminal_chunked_upload_begin') return frame.payload;+ }+ return null;+ }+}++/// The phone's clipboard, both halves: the text Flutter's [Clipboard] reads, and the image the+/// native side reads (`harness/clipboard_image`). Records every clipboard call the pane makes.+class _Clipboard {+ _Clipboard(WidgetTester tester) {+ final messenger = tester.binding.defaultBinaryMessenger;+ messenger.setMockMethodCallHandler(SystemChannels.platform, (call) async {+ if (call.method.startsWith('Clipboard.')) methods.add(call.method);+ switch (call.method) {+ case 'Clipboard.setData':+ copied = (call.arguments as Map)['text'] as String?;+ // ⚠️ Typed `<String, dynamic>`: Flutter casts the reply to that, and a `Map<String, bool>`+ // fails the cast inside an unawaited paste — no paste, no message, no failure.+ case 'Clipboard.hasStrings':+ return <String, dynamic>{'value': text != null && text!.isNotEmpty};+ case 'Clipboard.getData':+ onRead?.call();+ return text == null ? null : {'text': text};+ }+ return null;+ });+ messenger.setMockMethodCallHandler(_imageChannel, (call) async {+ if (call.method != 'readImagePng') return null;+ imageReads++;+ return image;+ });+ addTearDown(() {+ messenger.setMockMethodCallHandler(SystemChannels.platform, null);+ messenger.setMockMethodCallHandler(_imageChannel, null);+ });+ }++ static const _imageChannel = MethodChannel('harness/clipboard_image');++ /// Null for a clipboard with no text.+ String? text;++ /// The image as the native side answers it: null for none, empty for one it could not read.+ Uint8List? image;++ /// Runs while the text is being read — the window in which iOS can be showing its prompt.+ void Function()? onRead;++ /// What was copied onto the clipboard, if anything.+ String? copied;++ final methods = <String>[];+ int imageReads = 0;+}diff --git a/mobile/test/terminal_panel_phone_test.dart b/mobile/test/terminal_panel_phone_test.dartindex 82c8e44b0..3933b0a2f 100644--- a/mobile/test/terminal_panel_phone_test.dart+++ b/mobile/test/terminal_panel_phone_test.dart@@ -73,7 +73,16 @@ class _Platform {switch (call.method) {case 'Clipboard.setData':copied = (call.arguments as Map)['text'] as String?;+ // ⚠️ Answered as well as `getData`: a paste asks it FIRST, which is how iOS is spared an+ // "Allow Paste" prompt for a clipboard with no text on it. Unanswered it reads as false,+ // and the paste never reads the text. Typed `<String, dynamic>`, the type Flutter casts+ // the reply to.+ case 'Clipboard.hasStrings':+ return <String, dynamic>{+ 'value': clipboard != null && clipboard!.isNotEmpty,+ };case 'Clipboard.getData':+ onRead?.call();return clipboard == null ? null : {'text': clipboard};}return null;@@ -90,6 +99,10 @@ class _Platform {final calls = <MethodCall>[];String? clipboard;String? copied;++ /// Runs while the clipboard's text is being read — the window in which iOS can be showing its+ /// paste prompt.+ void Function()? onRead;}/// A download that finishes when the test says so.@@ -489,6 +502,8 @@ void main() {});});+ // On a pane whose host gave it no paste of its own (`TerminalPanel.onPaste`): the clipboard's text+ // and nothing else. With the phone page's paste hooked up, ⌘V is `terminal_panel_paste_test.dart`.group('a hardware keyboard\'s ⌘V', () {Future<void> commandV(WidgetTester tester, {bool shift = false}) async {await tester.sendKeyDownEvent(LogicalKeyboardKey.metaLeft);@@ -535,17 +550,22 @@ void main() {expect(wire.input, contains('git status'));}, variant: TargetPlatformVariant.only(TargetPlatform.iOS));+ // ⚠️ It used to hand the agent a ⌃V here, for its engine to read a picture itself — off the FAR+ // machine's clipboard, not this phone's. An image is the host's paste to send, or nothing.testWidgets(- 'an empty clipboard hands the agent its own ⌃V, to read a picture itself',+ 'a clipboard with no text pastes nothing, and never a ⌃V for the far '+ 'machine',(tester) async {- _Platform(tester);- // What the image reader answers on a phone: nothing, at once. The- // test host is a Mac, where it would ask a channel nobody answers.+ final platform = _Platform(tester);+ // A picture on the clipboard, as the phone's native side would answer for one.const images = MethodChannel('harness/clipboard_image');- tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(- images,- (_) async => null,- );+ var imageReads = 0;+ tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(images, (+ _,+ ) async {+ imageReads++;+ return Uint8List.fromList([0x89, 0x50, 0x4e, 0x47]);+ });addTearDown(() => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(images,@@ -559,7 +579,35 @@ void main() {await commandV(tester);- expect(wire.input, '\x16');+ expect(wire.input, isNot(contains('\x16')));+ expect(wire.binaries, isEmpty);+ expect(wire.types, isNot(contains('terminal_chunked_upload_begin')));+ expect(imageReads, 0);+ // No text, so it was never read: iOS asks nobody about it.+ expect(+ platform.calls.map((c) => c.method),+ isNot(contains('Clipboard.getData')),+ );+ },+ variant: TargetPlatformVariant.only(TargetPlatform.iOS),+ );++ testWidgets(+ 'a terminal that reconnected during the read is not pasted into',+ (tester) async {+ final pane = session();+ _Platform(tester)+ ..clipboard = 'git status'+ // The read waits on iOS's prompt, and the stream came back as another one meanwhile.+ ..onRead = () => pane.streamId = 's2';+ _machine(notifier, pasteRaw: true);+ await pumpPanel(tester, pane, focused: true);+ await tester.pump();++ await commandV(tester);++ expect(wire.ofKind(TerminalBinaryKind.paste), isEmpty);+ expect(wire.input, isEmpty);},variant: TargetPlatformVariant.only(TargetPlatform.iOS),);