Skip to content

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.

feat(mobile): copy and paste in the terminal

tony174ed967ef83
diff --git a/mobile/android/app/src/main/kotlin/ai/autonomous/harness/android/MainActivity.kt b/mobile/android/app/src/main/kotlin/ai/autonomous/harness/android/MainActivity.kt
index e914c5456..ed52f6409 100644
--- a/mobile/android/app/src/main/kotlin/ai/autonomous/harness/android/MainActivity.kt
+++ b/mobile/android/app/src/main/kotlin/ai/autonomous/harness/android/MainActivity.kt
@@ -39,10 +39,18 @@ class MainActivity : FlutterActivity() {
// `harness/clipboard_image` — the image on the clipboard, as PNG bytes (Dart:
// `lib/clipboard/native_clipboard.dart`). Flutter's own clipboard reads text only, so a
- // screenshot copied from the share sheet was invisible to Paste. Only `readImagePng` is
- // implemented here, since nothing on the phone writes an image.
+ // screenshot copied from the share sheet was invisible to Paste. Only `readImagePng` and
+ // `hasImage` are implemented here, since nothing on the phone writes an image.
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "harness/clipboard_image")
.setMethodCallHandler { call, result ->
+ // Whether an image is there, for the key strip's `paste` (Dart:
+ // `phone/terminal_key_bar.dart`), which is asked about every second while the keyboard is
+ // up. Read off the clip's DESCRIPTION alone: opening the clip itself is what Android 12+
+ // tells the person about, with its "pasted from your clipboard" toast.
+ if (call.method == "hasImage") {
+ result.success(clipboardHasImage())
+ return@setMethodCallHandler
+ }
if (call.method != "readImagePng") { result.notImplemented(); return@setMethodCallHandler }
val uri = clipboardImageUri()
if (uri == null) { result.success(null); return@setMethodCallHandler }
@@ -92,6 +100,13 @@ class MainActivity : FlutterActivity() {
}
}
+ /** Whether the clipboard holds an image, from its description alone — the clip is never opened. */
+ private fun clipboardHasImage(): Boolean {
+ val clipboard = getSystemService(Context.CLIPBOARD_SERVICE) as? ClipboardManager ?: return false
+ val description = try { clipboard.primaryClipDescription } catch (e: Exception) { null }
+ return description?.hasMimeType("image/*") == true
+ }
+
/** The first image on the clipboard, or null. The description is checked before any item, so a
* text clip is never opened. */
private fun clipboardImageUri(): Uri? {
diff --git a/mobile/ios/Runner/AppDelegate.swift b/mobile/ios/Runner/AppDelegate.swift
index 1076f4b55..f93a2c51a 100644
--- a/mobile/ios/Runner/AppDelegate.swift
+++ b/mobile/ios/Runner/AppDelegate.swift
@@ -24,12 +24,20 @@ import UserNotifications
/// `harness/clipboard_image` — the image on the clipboard, as PNG bytes (Dart:
/// `lib/clipboard/native_clipboard.dart`). Flutter's own clipboard reads `text/plain` only, so a
/// screenshot or a "Copy" from Photos was invisible to Paste. The same channel the desktop runners
-/// answer; only `readImagePng` is implemented here, since nothing on the phone writes an image.
+/// answer; only `readImagePng` and `hasImage` are implemented here, since nothing on the phone
+/// writes an image.
enum ClipboardImageChannel {
static func register(with registry: FlutterPluginRegistry) {
guard let messenger = registry.registrar(forPlugin: "HarnessClipboardImage")?.messenger() else { return }
let channel = FlutterMethodChannel(name: "harness/clipboard_image", binaryMessenger: messenger)
channel.setMethodCallHandler { call, result in
+ // Whether an image is there, for the key strip's `paste` (Dart: `phone/terminal_key_bar.dart`),
+ // which is asked about every second while the keyboard is up. `hasImages` never brings up the
+ // system's paste prompt: only reading the image does.
+ if call.method == "hasImage" {
+ result(UIPasteboard.general.hasImages)
+ return
+ }
guard call.method == "readImagePng" else { result(FlutterMethodNotImplemented); return }
// `hasImages` answers without the system's paste prompt, so an empty clipboard never asks.
let pasteboard = UIPasteboard.general
diff --git a/mobile/lib/clipboard/native_clipboard.dart b/mobile/lib/clipboard/native_clipboard.dart
index dc38c2d12..a2a6a9b66 100644
--- a/mobile/lib/clipboard/native_clipboard.dart
+++ b/mobile/lib/clipboard/native_clipboard.dart
@@ -38,6 +38,23 @@ class NativeClipboard {
}
}
+ /// Whether the system clipboard holds an image, asked without reading it — so iOS shows no
+ /// "Allow Paste" prompt and Android no "pasted from your clipboard" toast, and it can be asked as
+ /// often as the key strip's `paste` needs to know whether to show (`phone/terminal_key_bar.dart`).
+ ///
+ /// False on any platform without a native handler for it (iOS and Android only), or when the
+ /// question cannot be answered.
+ static Future<bool> hasImage() async {
+ if (!Platform.isIOS && !Platform.isAndroid) return false;
+ try {
+ return await _channel.invokeMethod<bool>('hasImage') ?? false;
+ } on MissingPluginException {
+ return false;
+ } catch (_) {
+ return false;
+ }
+ }
+
/// Writes `pngBytes` onto the system clipboard, replacing whatever was there — the LOCAL half
/// of native image drag-drop (see `_dropImage` in `widgets/pane_grid.dart`): when the pane's
/// machine is this same computer, the app puts the bytes on ITS OWN clipboard directly instead
diff --git a/mobile/lib/phone/phone_shell.dart b/mobile/lib/phone/phone_shell.dart
index 385498a2c..2e39fdb59 100644
--- a/mobile/lib/phone/phone_shell.dart
+++ b/mobile/lib/phone/phone_shell.dart
@@ -285,23 +285,36 @@ class _PhoneShellState extends State<PhoneShell> with WidgetsBindingObserver {
Expanded(
// While a band shows it has taken the status-bar inset, so the pages under it must
// not take it again (a blank gap the height of the notch otherwise).
- child: MediaQuery.removePadding(
- context: context,
- removeTop: NewDeviceBanner.showing(widget.notifier),
- child: HeroControllerScope(
- controller: _heroController,
- child: Navigator(
- key: _navigator,
- // ⚠️ The controller goes in the SCOPE ONLY, never also in `observers`.
- // `NavigatorState._updateEffectiveObservers` appends the scope's controller to
- // `widget.observers` itself, so listing it here registers it twice and trips
- // "A HeroController can not be shared by multiple Navigators" — which reads
- // like a sharing bug and is really a double-subscription by one navigator.
- onGenerateRoute: (_) => MaterialPageRoute<void>(
- builder: (_) => AgentHome(
- notifier: widget.notifier,
- openMachineId: _linkedMachineId,
- openAgent: _openAgentRequest,
+ //
+ // ⚠️ **Read under the Scaffold, through this Builder — never through the shell's
+ // own context.** The Scaffold has resized its body for the keyboard, and hands the
+ // body a MediaQuery with the keyboard's inset taken out so nothing below takes it
+ // again. The shell's context sits ABOVE the Scaffold and still holds that inset:
+ // rebuilt from it, every page in this navigator read the keyboard afresh and its
+ // own Scaffold shrank for it a second time. The terminal page lost twice the
+ // keyboard's height, its key bar left floating halfway up the screen over an
+ // empty band. See `TerminalPage.didChangeMetrics`, which relies on the inset
+ // being gone here.
+ child: Builder(
+ builder: (context) => MediaQuery.removePadding(
+ context: context,
+ removeTop: NewDeviceBanner.showing(widget.notifier),
+ child: HeroControllerScope(
+ controller: _heroController,
+ child: Navigator(
+ key: _navigator,
+ // ⚠️ The controller goes in the SCOPE ONLY, never also in `observers`.
+ // `NavigatorState._updateEffectiveObservers` appends the scope's controller
+ // to `widget.observers` itself, so listing it here registers it twice and
+ // trips "A HeroController can not be shared by multiple Navigators" — which
+ // reads like a sharing bug and is really a double-subscription by one
+ // navigator.
+ onGenerateRoute: (_) => MaterialPageRoute<void>(
+ builder: (_) => AgentHome(
+ notifier: widget.notifier,
+ openMachineId: _linkedMachineId,
+ openAgent: _openAgentRequest,
+ ),
),
),
),
diff --git a/mobile/lib/phone/terminal_copy.dart b/mobile/lib/phone/terminal_copy.dart
new file mode 100644
index 000000000..14113e913
--- /dev/null
+++ b/mobile/lib/phone/terminal_copy.dart
@@ -0,0 +1,41 @@
+import 'package:flutter/services.dart';
+
+import 'package:harness_mobile/terminal/output_blocks.dart';
+import 'package:harness_mobile/terminal/terminal_session.dart';
+
+/// Whether [session]'s terminal holds a reply to copy — whether the actions sheet offers
+/// Copy last reply at all.
+bool hasLastReply(TerminalSession session) =>
+ lastReplyBlock(session.terminal.buffer) != null;
+
+/// Copies the agent's last reply in [session] to the phone's clipboard, as the agent wrote it —
+/// the Copy last reply row of the terminal's actions sheet (`phone/terminal_page.dart`).
+///
+/// Read from the terminal as it stands, not from the session's events: it is the reply the person
+/// is looking at, it needs no round trip to the machine, and it is there whether or not the turn
+/// was summarised. See [lastReplyBlock] for what counts as a reply, and [outputBlockText] for the
+/// text it copies as.
+///
+/// The terminal is read when the row is tapped, not when the sheet opened: a keyframe can have
+/// replaced it in between, and output can have added a newer reply. Every outcome goes to
+/// [report].
+Future<void> copyLastReply({
+ required TerminalSession session,
+ required void Function(String message) report,
+}) async {
+ final buffer = session.terminal.buffer;
+ final block = lastReplyBlock(buffer);
+ final text = block == null ? '' : outputBlockText(buffer, block);
+ if (text.isEmpty) {
+ report('There is no reply in this terminal to copy.');
+ return;
+ }
+ try {
+ await Clipboard.setData(ClipboardData(text: text));
+ } on PlatformException {
+ report('Could not copy to the clipboard.');
+ return;
+ }
+ HapticFeedback.lightImpact();
+ report('Copied the last reply.');
+}
diff --git a/mobile/lib/phone/terminal_input_dock.dart b/mobile/lib/phone/terminal_input_dock.dart
index 3d626e390..63fa5ef2b 100644
--- a/mobile/lib/phone/terminal_input_dock.dart
+++ b/mobile/lib/phone/terminal_input_dock.dart
@@ -32,6 +32,8 @@ class TerminalInputDock extends StatefulWidget {
required this.session,
required this.keyboardUp,
required this.onDismiss,
+ this.onClearPrompt,
+ this.onPaste,
this.onPickImage,
this.onTakePhoto,
this.questionOpen = false,
@@ -52,6 +54,11 @@ class TerminalInputDock extends StatefulWidget {
/// `⌄` on the key bar: puts the keyboard away.
final VoidCallback onDismiss;
+
+ /// `clear` and `paste` on the key bar — see [TerminalKeyBar.onClearPrompt]
+ /// and [TerminalKeyBar.onPaste].
+ final VoidCallback? onClearPrompt;
+ final VoidCallback? onPaste;
final VoidCallback? onPickImage;
final VoidCallback? onTakePhoto;
@@ -121,6 +128,8 @@ class _TerminalInputDockState extends State<TerminalInputDock>
enabled: widget.session.acceptsInput,
onPromptEdited: widget.session.resetInputBuffer,
onDismissKeyboard: widget.onDismiss,
+ onClearPrompt: widget.onClearPrompt,
+ onPaste: widget.onPaste,
onPickImage: widget.onPickImage,
onTakePhoto: widget.onTakePhoto,
questionOpen: widget.questionOpen,
diff --git a/mobile/lib/phone/terminal_key_bar.dart b/mobile/lib/phone/terminal_key_bar.dart
index b040e9844..af653b1b5 100644
--- a/mobile/lib/phone/terminal_key_bar.dart
+++ b/mobile/lib/phone/terminal_key_bar.dart
@@ -1,9 +1,12 @@
+import 'dart:async';
+
import 'package:flutter/foundation.dart' show listEquals;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:lucide_icons_flutter/lucide_icons.dart';
import 'package:xterm/xterm.dart';
+import 'package:harness_mobile/clipboard/native_clipboard.dart';
import 'package:harness_mobile/shared/theme/app_theme.dart';
import 'package:harness_mobile/terminal/key_hints.dart';
import 'package:harness_mobile/terminal/terminal_font_store.dart';
@@ -29,7 +32,7 @@ import 'tty.dart';
/// phone keyboard cannot produce, or buries, and a pane is driven by:
///
/// ```
-/// esc tab clear ← ↑ ↓ → / │ 🖼 ⌄
+/// esc ^C tab clear paste ⇧ ctrl ← ↑ ↓ → │ img ▾
/// ```
///
/// Every key stays in the same place every time; this strip is used while
@@ -57,6 +60,8 @@ class TerminalKeyBar extends StatefulWidget {
required this.enabled,
required this.onDismissKeyboard,
this.onPromptEdited,
+ this.onClearPrompt,
+ this.onPaste,
this.onPickImage,
this.onTakePhoto,
this.questionOpen = false,
@@ -88,6 +93,14 @@ class TerminalKeyBar extends StatefulWidget {
/// prompt no longer holds.
final VoidCallback? onPromptEdited;
+ /// `clear`: empties the prompt being typed into. Null leaves the key out.
+ final VoidCallback? onClearPrompt;
+
+ /// `paste`: the phone's clipboard into the prompt, its image as well as its
+ /// text. Null leaves the key out; so does a clipboard with nothing on it —
+ /// the one key on the strip that comes and goes.
+ final VoidCallback? onPaste;
+
/// False while the stream is not accepting input — the strip stays visible
/// (it moves with the keyboard, and a row that vanished would take the
/// keyboard's place with it) but dims and stops answering.
@@ -106,10 +119,76 @@ class TerminalKeyBar extends StatefulWidget {
State<TerminalKeyBar> createState() => _TerminalKeyBarState();
}
-class _TerminalKeyBarState extends State<TerminalKeyBar> {
+class _TerminalKeyBarState extends State<TerminalKeyBar>
+ with WidgetsBindingObserver {
bool get _canSendImage =>
widget.onPickImage != null || widget.onTakePhoto != null;
+ /// Whether the phone's clipboard holds anything `paste` would send: text,
+ /// or an image where this pane takes one. The key is drawn only then — a
+ /// `paste` that answers "nothing on the clipboard" is a key that did
+ /// nothing.
+ bool _clipboardFull = false;
+ bool _clipboardChecking = false;
+
+ /// Asks again every [_clipboardEvery] while the strip is up. Neither phone
+ /// says when its clipboard changes, and it does change under the strip: a
+ /// reply copied off the pane, text copied in another app over this one.
+ Timer? _clipboardPoll;
+ static const _clipboardEvery = Duration(seconds: 1);
+
+ @override
+ void initState() {
+ super.initState();
+ WidgetsBinding.instance.addObserver(this);
+ _watchClipboard();
+ }
+
+ @override
+ void didChangeAppLifecycleState(AppLifecycleState state) {
+ // Back from another app — where the copy usually happened.
+ if (state == AppLifecycleState.resumed) unawaited(_checkClipboard());
+ }
+
+ /// Starts asking about the clipboard while there is a `paste` to show, and
+ /// stops when there is not.
+ void _watchClipboard() {
+ if (widget.onPaste == null) {
+ _clipboardPoll?.cancel();
+ _clipboardPoll = null;
+ return;
+ }
+ _clipboardPoll ??= Timer.periodic(
+ _clipboardEvery,
+ (_) => unawaited(_checkClipboard()),
+ );
+ unawaited(_checkClipboard());
+ }
+
+ /// ⚠️ **Asked, never read.** [Clipboard.hasStrings] and
+ /// [NativeClipboard.hasImage] answer without iOS's "Allow Paste" prompt or
+ /// Android's "pasted from your clipboard" toast; reading the clipboard every
+ /// second would bring up one or the other each time.
+ Future<void> _checkClipboard() async {
+ if (_clipboardChecking || widget.onPaste == null) return;
+ // Only while the app is in front: Android hands an app in the background
+ // no clipboard at all, and the key would go away for nothing.
+ final lifecycle = WidgetsBinding.instance.lifecycleState;
+ if (lifecycle != null && lifecycle != AppLifecycleState.resumed) return;
+ _clipboardChecking = true;
+ try {
+ var full = await Clipboard.hasStrings();
+ if (!full && _canSendImage) full = await NativeClipboard.hasImage();
+ if (mounted && full != _clipboardFull) {
+ setState(() => _clipboardFull = full);
+ }
+ } on PlatformException {
+ // No answer: the key stays as it was rather than flickering.
+ } finally {
+ _clipboardChecking = false;
+ }
+ }
+
void _send(void Function() action) {
if (!widget.enabled) return;
HapticFeedback.selectionClick();
@@ -217,7 +296,7 @@ class _TerminalKeyBarState extends State<TerminalKeyBar> {
AppTheme.watch(context);
// What drives an engine and a phone keyboard lacks: leave a mode, walk
// history, move through a menu.
- final keys = <Widget>[
+ final keys = <_Slot>[
_key(label: 'esc', onTap: () => _sendKey(TerminalKey.escape)),
// The other key a terminal person reaches for without looking: stop, now.
_key(
@@ -230,6 +309,33 @@ class _TerminalKeyBarState extends State<TerminalKeyBar> {
),
// Completes a path or a command, and moves through Claude Code's menus.
_key(label: 'tab', onTap: () => _sendKey(TerminalKey.tab, edits: true)),
+ // Empties what is typed: Ctrl+K, then Ctrl+U — not Ctrl+C, which on an
+ // empty Claude Code prompt is the first half of quitting. See
+ // `TerminalSession.clearPrompt`.
+ if (widget.onClearPrompt case final clear?)
+ _key(
+ label: 'clear',
+ semanticLabel: 'Clear prompt',
+ wide: true,
+ onTap: () {
+ _disarm();
+ clear();
+ },
+ ),
+ // The phone's clipboard, text or image — iOS's keyboard has no paste
+ // key. Beside `clear`: the two edit what is typed as a whole. Only while
+ // the clipboard holds something to paste — see [_clipboardFull].
+ if (widget.onPaste case final paste? when _clipboardFull)
+ _key(
+ label: 'paste',
+ semanticLabel: 'Paste',
+ wide: true,
+ onTap: () {
+ _disarm();
+ paste();
+ widget.onPromptEdited?.call();
+ },
+ ),
// ⚠️ **The two modifiers stand together, before the keys they modify.**
// Apart — one here, one at the far end of the row — they read as two
// unrelated keys that happen to light up, and the pair a thumb reaches
@@ -282,7 +388,7 @@ class _TerminalKeyBarState extends State<TerminalKeyBar> {
// OS picker, the other drops the keyboard. Sharing a row taught the eye they
// were the same kind of thing, and an image button that looks like `esc`
// reads as something that will be typed at the agent.
- final apart = <Widget>[
+ final apart = <_Slot>[
if (_canSendImage)
_key(
label: 'img',
@@ -315,7 +421,8 @@ class _TerminalKeyBarState extends State<TerminalKeyBar> {
// at a large scale the keys stop fitting the row.
child: MediaQuery.withNoTextScaling(
// Every key the same width, the two apart ones included — they are
- // separated by the rule, not by being a different size.
+ // separated by the rule, not by being a different size. Only the
+ // two five-letter words are wider: see [_wideParts].
child: widget.hints.isEmpty
? Row(children: [..._row(keys), ..._rule(), ..._row(apart)])
: LayoutBuilder(
@@ -328,13 +435,25 @@ class _TerminalKeyBarState extends State<TerminalKeyBar> {
);
}
- /// A run of keys for the strip's one [Row], each `Expanded` with the same
- /// flex — so every key on the strip, on either side of the rule, gets the
- /// same width, and the row fills the phone rather than ending in a gap.
- List<Widget> _row(List<Widget> keys) => [
+ /// How many parts of the row a key takes: [_keyParts] for most,
+ /// [_wideParts] for `clear` and `paste`.
+ ///
+ /// ⚠️ **A word as long as `clear` in a cell sized for `esc` is shrunk to half
+ /// the size of the rest of the row.** The label scales down to fit rather
+ /// than clip, so the two words came out a size nobody could read. Five parts
+ /// to three gives them the room of the letters they have, and the row
+ /// reads at one size.
+ static const _keyParts = 3;
+ static const _wideParts = 5;
+
+ /// A run of keys for the strip's one [Row], each `Expanded` with its
+ /// [_Slot.parts] as the flex — so every key on the strip, on either side of
+ /// the rule, gets the same width but the wide two, and the row fills the
+ /// phone rather than ending in a gap.
+ List<Widget> _row(List<_Slot> keys) => [
for (var index = 0; index < keys.length; index++) ...[
if (index > 0) const SizedBox(width: 4),
- Expanded(child: keys[index]),
+ Expanded(flex: keys[index].parts, child: keys[index].key),
],
];
@@ -360,17 +479,21 @@ class _TerminalKeyBarState extends State<TerminalKeyBar> {
/// [TerminalKeyBar.hints], scrolling sideways together; the two apart keys
/// stay pinned past the rule.
///
- /// ⚠️ **Every fixed key keeps exactly the width [_row] gives it.** The cell
+ /// ⚠️ **Every fixed key keeps exactly the width [_row] gives it.** The part
/// is worked out the way the `Expanded` row divides [width] — the same keys,
/// gaps and rule — so the keys do not shrink or move when a hint arrives:
/// they fill the visible part of the row as they always do, and the hints
/// start where it ends. [_revealHints] then scrolls them into view.
- Widget _rowWithHints(List<Widget> keys, List<Widget> apart, double width) {
+ Widget _rowWithHints(List<_Slot> keys, List<_Slot> apart, double width) {
const gap = 4.0;
final gaps =
gap * (keys.length - 1) + _ruleWidth + gap * (apart.length - 1);
- final cell = (width - gaps) / (keys.length + apart.length);
- if (!cell.isFinite || cell <= 0) {
+ final parts = [
+ ...keys,
+ ...apart,
+ ].fold<int>(0, (sum, key) => sum + key.parts);
+ final part = (width - gaps) / parts;
+ if (!part.isFinite || part <= 0) {
return Row(children: [..._row(keys), ..._rule(), ..._row(apart)]);
}
final hints = widget.hints;
@@ -382,7 +505,7 @@ class _TerminalKeyBarState extends State<TerminalKeyBar> {
scrollDirection: Axis.horizontal,
child: Row(
children: [
- ..._cells(keys, cell),
+ ..._cells(keys, part),
// The pane's keys are not the strip's: a hairline says so,
// the way the rule sets the phone's own two apart.
const SizedBox(width: 6),
@@ -397,17 +520,18 @@ class _TerminalKeyBarState extends State<TerminalKeyBar> {
),
),
..._rule(),
- ..._cells(apart, cell),
+ ..._cells(apart, part),
],
);
}
- /// A run of keys at a fixed [width] each — [_row]'s layout, in a row that
- /// scrolls and so cannot divide itself with `Expanded`.
- List<Widget> _cells(List<Widget> keys, double width) => [
+ /// A run of keys at a fixed width each, [part] times its [_Slot.parts] —
+ /// [_row]'s layout, in a row that scrolls and so cannot divide itself with
+ /// `Expanded`.
+ List<Widget> _cells(List<_Slot> keys, double part) => [
for (var index = 0; index < keys.length; index++) ...[
if (index > 0) const SizedBox(width: 4),
- SizedBox(width: width, child: keys[index]),
+ SizedBox(width: part * keys[index].parts, child: keys[index].key),
],
];
@@ -426,10 +550,19 @@ class _TerminalKeyBarState extends State<TerminalKeyBar> {
if (widget.hints.isNotEmpty && !listEquals(widget.hints, oldWidget.hints)) {
_revealHints();
}
+ // `paste` came or went, or an image stopped (or started) counting.
+ final couldSendImage =
+ oldWidget.onPickImage != null || oldWidget.onTakePhoto != null;
+ if ((widget.onPaste == null) != (oldWidget.onPaste == null) ||
+ _canSendImage != couldSendImage) {
+ _watchClipboard();
+ }
}
@override
void dispose() {
+ WidgetsBinding.instance.removeObserver(this);
+ _clipboardPoll?.cancel();
_scroll.dispose();
super.dispose();
}
@@ -464,32 +597,40 @@ class _TerminalKeyBarState extends State<TerminalKeyBar> {
),
);
- Widget _key({
+ _Slot _key({
String? label,
IconData? icon,
String? semanticLabel,
bool alwaysEnabled = false,
bool armed = false,
+ bool wide = false,
required VoidCallback onTap,
}) {
assert((label == null) != (icon == null), 'a key carries one of the two');
final live = widget.enabled || alwaysEnabled;
- return Semantics(
- button: true,
- label: semanticLabel ?? label,
- // Named so a test can reach the icon keys, which carry no text.
- key: ValueKey('terminal-key-${semanticLabel ?? label}'),
- child: _KeyCap(
- label: label,
- icon: icon,
- live: live,
- armed: armed,
- onTap: alwaysEnabled ? onTap : () => _send(onTap),
+ return (
+ key: Semantics(
+ button: true,
+ label: semanticLabel ?? label,
+ // Named so a test can reach the icon keys, which carry no text.
+ key: ValueKey('terminal-key-${semanticLabel ?? label}'),
+ child: _KeyCap(
+ label: label,
+ icon: icon,
+ live: live,
+ armed: armed,
+ onTap: alwaysEnabled ? onTap : () => _send(onTap),
+ ),
),
+ parts: wide ? _wideParts : _keyParts,
);
}
}
+/// One key of the strip, and how many parts of the row it takes — see
+/// [_TerminalKeyBarState._wideParts].
+typedef _Slot = ({Widget key, int parts});
+
/// One key of the bar, lit while a thumb is on it.
///
/// ⚠️ **The lift is not decoration: this row had no press state at all.** Every
diff --git a/mobile/lib/phone/terminal_page.dart b/mobile/lib/phone/terminal_page.dart
index cc8b2c5c8..94da71f72 100644
--- a/mobile/lib/phone/terminal_page.dart
+++ b/mobile/lib/phone/terminal_page.dart
@@ -50,6 +50,7 @@ import 'terminal_action_column.dart';
import 'team_page.dart';
import 'terminal_chrome_scroll.dart';
import 'terminal_input_dock.dart';
+import 'terminal_copy.dart';
import 'terminal_paste.dart';
import 'terminal_search.dart';
import 'tty.dart';
@@ -2074,6 +2075,10 @@ class _TerminalPageState extends State<TerminalPage>
? _answerBands
: null,
onBandTap: _onAnswerBand,
+ // A long press on the prompt offers Paste, as
+ // a text field's does — see [_paste].
+ onPaste: () =>
+ _paste(session),
// Where the reader is in the history —
// what holds the view still under them.
scrollback: _scrollback,
@@ -2163,6 +2168,12 @@ class _TerminalPageState extends State<TerminalPage>
session: session,
keyboardUp: _keyBarUp,
onDismiss: _dismissInput,
+ // `clear` and `paste` on the key bar: the prompt
+ // emptied, and the phone's clipboard — text or
+ // image — through the same path as the sheet's
+ // Paste. See [_paste].
+ onClearPrompt: session.clearPrompt,
+ onPaste: () => _paste(session),
// A dialog the watcher can read is open: the
// strip offers Enter for it. See
// [TerminalKeyBar.questionOpen].
@@ -2439,6 +2450,10 @@ class _TerminalPageState extends State<TerminalPage>
// Hidden rather than dimmed while the stream is read-only: reclaiming is the header's
// job, and a paste that silently goes nowhere is worse than no row.
if (session != null && session.acceptsInput) _pasteAction(session),
+ // Beside Paste, its other half. Copying reads and sends nothing, so it is offered on a
+ // terminal only being watched too — but only while there is a reply on it to copy.
+ if (session != null && hasLastReply(session))
+ _copyReplyAction(session),
..._agentActions(agent),
],
),
@@ -2494,31 +2509,57 @@ class _TerminalPageState extends State<TerminalPage>
// was meant — and the phone's is the surprising answer, since the agent runs
// somewhere else. See [pasteClipboard], which says the same in its doc.
label: 'Paste from clipboard',
- onTap: () {
- final messenger = ScaffoldMessenger.maybeOf(context);
- unawaited(
- pasteClipboard(
- session: session,
- machine: widget.notifier.stateOf(widget.machineId),
- stillShowing: () =>
- mounted &&
- widget.isActive &&
- identical(
- widget.notifier
- .paneOfAgent(widget.machineId, widget.agentId)
- ?.session,
- session,
- ),
- report: (message) {
- if (mounted) {
- messenger?.showSnackBar(SnackBar(content: Text(message)));
- }
- },
- ),
- );
- },
+ 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
+ /// text, ask iOS once, and send only into the terminal still on screen.
+ void _paste(TerminalSession session) {
+ final messenger = ScaffoldMessenger.maybeOf(context);
+ unawaited(
+ pasteClipboard(
+ session: session,
+ machine: widget.notifier.stateOf(widget.machineId),
+ stillShowing: () =>
+ mounted &&
+ widget.isActive &&
+ identical(
+ widget.notifier
+ .paneOfAgent(widget.machineId, widget.agentId)
+ ?.session,
+ session,
+ ),
+ report: (message) {
+ if (mounted) {
+ messenger?.showSnackBar(SnackBar(content: Text(message)));
+ }
+ },
+ ),
+ );
+ }
+
+ /// Copy last reply: what the agent last said, onto the phone's clipboard, without selecting it
+ /// first. What it reads and copies lives in [copyLastReply].
+ PhoneSheetAction _copyReplyAction(TerminalSession session) =>
+ PhoneSheetAction(
+ icon: LucideIcons.copy300,
+ label: 'Copy last reply',
+ onTap: () {
+ final messenger = ScaffoldMessenger.maybeOf(context);
+ unawaited(
+ copyLastReply(
+ session: session,
+ report: (message) {
+ if (mounted) {
+ messenger?.showSnackBar(SnackBar(content: Text(message)));
+ }
+ },
+ ),
+ );
+ },
+ );
+
/// What acts on this agent and can be taken back — the first card of its sheet.
List<PhoneSheetAction> _agentActions(Agent agent) => [
PhoneSheetAction(
diff --git a/mobile/lib/terminal/output_blocks.dart b/mobile/lib/terminal/output_blocks.dart
new file mode 100644
index 000000000..b36fadaea
--- /dev/null
+++ b/mobile/lib/terminal/output_blocks.dart
@@ -0,0 +1,214 @@
+import 'dart:math';
+
+import 'package:xterm/xterm.dart';
+
+/// One message an agent's TUI drew — Claude Code's `⏺` block, Codex's `•` — as absolute buffer
+/// rows, [first] and [last] inclusive. [first] is the row with the mark; trailing blank rows are
+/// left out.
+typedef OutputBlock = ({int first, int last});
+
+/// What a message starts with, in column 0: Claude Code's `⏺` (`●` where it draws for Linux and
+/// Windows) and Codex's `•`. Everything else a message holds is indented under it — `⎿` and `└`
+/// results, wrapped lines, lists — so the next line with anything in column 0 (another mark, the
+/// person's `>`/`❯`/`›`, the input box's rule, a spinner) is where the message ends.
+const _marks = {0x23FA, 0x25CF, 0x2022};
+
+/// How far up a long press looks for the mark of the message it landed in.
+const _maxBlockRows = 2000;
+
+/// How close to the right edge a message has to reach before any of its line breaks is read as
+/// the TUI's own wrap rather than the agent's. A message that never comes near the edge was
+/// never wrapped, and its line breaks are all kept.
+const _nearEdge = 8;
+
+/// A line that never continues the one above it, however long that one is: a list item, a
+/// result, a table or box row.
+final _ownLine = RegExp(r'^(?:[-*•◦▪‣]\s|[☐☒□✔✓⎿└│├┌╭┃▎]|\d+[.)]\s)');
+
+/// A list item's marker, which its wrapped lines are indented past.
+final _listMarker = RegExp(r'^(?:[-*•◦▪‣☐☒□✔✓]|\d+[.)])\s+');
+
+/// A message's first line when it is a tool the agent ran rather than something it said:
+/// Claude Code's `Bash(npm test)`, an MCP tool's `(MCP)`, its todo list, a collapsed group's
+/// `(ctrl+o to expand)`; Codex's plan, its edits, its status line.
+final _toolHead = RegExp(
+ r'^(?:[A-Z][A-Za-z]*\(|Update Todos$|Updated Plan$|Explored$|Edited .*\(\+\d+ -\d+\)$|Working \()'
+ r'|\(MCP\)|ctrl\+[a-z] to (?:expand|interrupt)|esc to interrupt',
+);
+
+/// The message buffer row [row] is in, or null when it is in none — the person's prompt, the
+/// input box, a plain shell, the blank rows after a message.
+///
+/// A long press uses it to select a whole message rather than the word under the finger.
+OutputBlock? outputBlockAt(Buffer buffer, int row) {
+ final lines = buffer.lines;
+ if (row < 0 || row >= lines.length) return null;
+ var first = row;
+ while (true) {
+ final line = lines[first];
+ if (!line.isWrapped) {
+ final lead = _lead(line);
+ if (_marks.contains(lead)) break;
+ if (!_isBlank(lead)) return null;
+ }
+ if (first == 0 || row - first >= _maxBlockRows) return null;
+ first--;
+ }
+ final block = _blockFrom(buffer, first);
+ return row <= block.last ? block : null;
+}
+
+/// The last thing the agent SAID in [buffer]: the newest message that is not a tool it ran, or
+/// null when there is none — a fresh session, a shell, a reply already scrolled out of the
+/// history.
+OutputBlock? lastReplyBlock(Buffer buffer) {
+ final lines = buffer.lines;
+ for (var row = lines.length - 1; row >= 0; row--) {
+ final line = lines[row];
+ if (line.isWrapped || !_marks.contains(_lead(line))) continue;
+ final block = _blockFrom(buffer, row);
+ if (_isReply(buffer, block)) return block;
+ }
+ return null;
+}
+
+/// [block] as a selection: from its mark to the end of its last line's text.
+BufferRangeLine outputBlockRange(Buffer buffer, OutputBlock block) =>
+ BufferRangeLine(
+ CellOffset(0, block.first),
+ CellOffset(buffer.lines[block.last].getTrimmedLength(), block.last),
+ );
+
+/// [block]'s text as the agent wrote it, for the clipboard.
+///
+/// Without its mark, and without the two columns the TUI indents the rest of a message by. The
+/// lines the TUI broke only to fit the terminal are joined back up: a phone pane is about forty
+/// columns wide, so a reply copied as drawn would paste as a column of short lines anywhere else.
+///
+/// ⚠️ **Those breaks are hard newlines in the buffer, not soft wraps.** Both TUIs lay their text
+/// out themselves and write each row on its own, so xterm's `isWrapped` never marks them. A break
+/// is read as the TUI's when the line before it comes near the message's right edge and the next
+/// line's first word could not have fitted after it — the test a wrapping TUI applies. List
+/// items, results and box rows always keep their own line, as does anything indented
+/// differently from the paragraph above it.
+String outputBlockText(Buffer buffer, OutputBlock block) {
+ final rows = <_Row>[];
+ for (var i = block.first; i <= block.last; i++) {
+ final line = buffer.lines[i];
+ final text = line.getText();
+ final end = line.getTrimmedLength();
+ if (line.isWrapped && rows.isNotEmpty) {
+ final previous = rows.removeLast();
+ rows.add((
+ text: '${previous.text}$text',
+ indent: previous.indent,
+ end: end,
+ word: previous.word,
+ ));
+ continue;
+ }
+ final body = i == block.first ? _withoutMark(text) : _withoutHang(text);
+ rows.add((
+ text: body,
+ indent: body.length - body.trimLeft().length,
+ end: end,
+ word: _firstWordCells(line),
+ ));
+ }
+
+ final widest = rows.fold(0, (widest, row) => max(widest, row.end));
+ final limit = widest >= buffer.viewWidth - _nearEdge ? widest : 0;
+ final out = StringBuffer();
+ var paragraphIndent = 0;
+ for (var k = 0; k < rows.length; k++) {
+ final row = rows[k];
+ final text = row.text.trimRight();
+ final content = text.trimLeft();
+ if (k > 0 &&
+ limit > 0 &&
+ content.isNotEmpty &&
+ rows[k - 1].text.trim().isNotEmpty &&
+ row.indent == paragraphIndent &&
+ !_ownLine.hasMatch(content) &&
+ rows[k - 1].end + 1 + row.word > limit) {
+ out
+ ..write(' ')
+ ..write(content);
+ continue;
+ }
+ if (k > 0) out.write('\n');
+ out.write(text);
+ paragraphIndent =
+ row.indent + (_listMarker.firstMatch(content)?.group(0)?.length ?? 0);
+ }
+ return out.toString().trimRight();
+}
+
+/// One row of a message as [outputBlockText] reads it: its text without the mark or the hang,
+/// how far that text is indented, and, in cells as the buffer holds them, where the row ends and
+/// how long its first word is.
+typedef _Row = ({String text, int indent, int end, int word});
+
+/// What a row holds in column 0; 0 for a row with nothing in it.
+int _lead(BufferLine line) => line.length == 0 ? 0 : line.getCodePoint(0);
+
+/// An empty cell, or one a space was written into.
+bool _isBlank(int codePoint) => codePoint == 0 || codePoint == 0x20;
+
+/// The message whose mark is on row [first], to its last row with text before the next line
+/// with anything in column 0.
+OutputBlock _blockFrom(Buffer buffer, int first) {
+ final lines = buffer.lines;
+ var last = first;
+ for (var i = first + 1; i < lines.length; i++) {
+ final line = lines[i];
+ if (!line.isWrapped && !_isBlank(_lead(line))) break;
+ if (line.getTrimmedLength() > 0 && line.getText().trim().isNotEmpty) {
+ last = i;
+ }
+ }
+ return (first: first, last: last);
+}
+
+/// Whether [block] is something the agent said, rather than a tool it ran: a tool's head line
+/// names it, and a tool's result hangs under it on a `⎿` (Claude Code) or `└` (Codex).
+bool _isReply(Buffer buffer, OutputBlock block) {
+ final head = _withoutMark(buffer.lines[block.first].getText()).trim();
+ if (head.isEmpty || _toolHead.hasMatch(head)) return false;
+ for (var i = block.first + 1; i <= block.last; i++) {
+ final text = buffer.lines[i].getText().trimLeft();
+ if (text.startsWith('⎿') || text.startsWith('└')) return false;
+ }
+ return true;
+}
+
+/// A message's first row without its mark and the space after it. Every mark in [_marks] is one
+/// UTF-16 unit, and a wide one's second cell writes nothing into [BufferLine.getText].
+String _withoutMark(String text) {
+ if (text.isEmpty) return text;
+ final rest = text.substring(1);
+ return rest.startsWith(' ') ? rest.substring(1) : rest;
+}
+
+/// A message's later row without the two columns the TUI hangs it under the mark by.
+String _withoutHang(String text) {
+ var hang = 0;
+ while (hang < 2 && hang < text.length && text.codeUnitAt(hang) == 0x20) {
+ hang++;
+ }
+ return text.substring(hang);
+}
+
+/// How many cells the first word on [line] takes — wide characters as two.
+int _firstWordCells(BufferLine line) {
+ final length = line.getTrimmedLength();
+ var i = 0;
+ while (i < length && _isBlank(line.getCodePoint(i))) {
+ i++;
+ }
+ final start = i;
+ while (i < length && !_isBlank(line.getCodePoint(i))) {
+ i += max(1, line.getWidth(i));
+ }
+ return i - start;
+}
diff --git a/mobile/lib/terminal/terminal_prompt_zone.dart b/mobile/lib/terminal/terminal_prompt_zone.dart
index 92f25a077..1983dc1a4 100644
--- a/mobile/lib/terminal/terminal_prompt_zone.dart
+++ b/mobile/lib/terminal/terminal_prompt_zone.dart
@@ -56,3 +56,151 @@ bool _isTyped(BufferLine line) {
final text = line.getText().trim();
return text.isNotEmpty && !_rule.hasMatch(text);
}
+
+/// How many rows a prompt's typed text can run to — a long paste included.
+const _maxInputRows = 200;
+
+/// What an agent's prompt starts with, in column 0 or just inside a box's side: Claude Code's `❯`
+/// (`>` in older builds), its `!` shell mode and `#` memory mode, and Codex's `›`. A shell themed
+/// with a `❯` prompt reads the same way, and rightly: what follows it is what was typed.
+const _promptGlyphs = {0x276F, 0x3E, 0x21, 0x23, 0x203A};
+
+/// The side of the box older Claude Code draws its prompt inside: `│ > text │`.
+const _boxSide = 0x2502;
+
+/// An open question's answer, which the cursor sits on too: `❯ 1. Yes`. Not a prompt.
+final _answerRow = RegExp(r'^\d+[.)]\s');
+
+/// Where the text typed into the program's prompt is — from just past `❯ ` to its last character —
+/// or null when nothing is typed there: an empty prompt, one showing only its grey placeholder, an
+/// open question, or a prompt this cannot read (a plain shell's `%`, which cannot be told apart from
+/// what was typed after it).
+///
+/// Found from the cursor, as [isPromptTap] finds the prompt: walked up to the row with the prompt's
+/// glyph, then down through the rows the text wrapped onto, to the box's rule or a blank row.
+BufferRangeLine? promptInputRange(Buffer buffer) {
+ final lines = buffer.lines;
+ final cursorRow = buffer.absoluteCursorY;
+ if (cursorRow < 0 || cursorRow >= lines.length) return null;
+ int? top;
+ int? glyph;
+ for (
+ var row = cursorRow;
+ row >= 0 && cursorRow - row < _maxInputRows;
+ row--
+ ) {
+ final line = lines[row];
+ if (!_isTyped(line)) return null;
+ glyph = _promptGlyphColumn(line);
+ if (glyph != null) {
+ top = row;
+ break;
+ }
+ }
+ if (top == null || glyph == null) return null;
+ if (_answerRow.hasMatch(lines[top].getText(glyph + 1).trimLeft())) {
+ return null;
+ }
+ var last = top;
+ for (
+ var row = top + 1;
+ row < lines.length && row - top < _maxInputRows;
+ row++
+ ) {
+ final line = lines[row];
+ if (!_isTyped(line) || _promptGlyphColumn(line) != null) break;
+ last = row;
+ }
+ final start = CellOffset(glyph + 2, top);
+ final end = CellOffset(_textEnd(lines[last]), last);
+ if (!start.isBefore(end)) return null;
+ final range = BufferRangeLine(start, end);
+ return _isPlaceholder(buffer, range) ? null : range;
+}
+
+/// How many screen rows the prompt the cursor is in can take, at most: from its first row — the
+/// one with the prompt's glyph, or the one under the rule a TUI draws over its input — to the foot
+/// of the screen. The whole screen when neither is above the cursor.
+///
+/// ⚠️ **An overcount, by design.** It counts the footer under the prompt too, and a row the prompt
+/// is not on. Its one use is how many times to kill a line ([TerminalSession.clearPrompt]), and a
+/// kill too many does nothing, where one too few leaves text behind.
+int promptRowsBound(Buffer buffer) {
+ final lines = buffer.lines;
+ final screenTop = max(0, buffer.height - buffer.viewHeight);
+ var top = screenTop;
+ for (
+ var row = min(buffer.absoluteCursorY, buffer.height - 1);
+ row >= screenTop;
+ row--
+ ) {
+ final line = lines[row];
+ if (_promptGlyphColumn(line) != null) {
+ top = row;
+ break;
+ }
+ if (_isRuleRow(line)) {
+ top = row + 1;
+ break;
+ }
+ }
+ return max(1, buffer.height - top);
+}
+
+/// A rule a TUI draws across the screen, from column 0 — not a line of dashes typed into the
+/// prompt, which is indented under its glyph.
+bool _isRuleRow(BufferLine line) {
+ if (line.length == 0) return false;
+ final lead = line.getCodePoint(0);
+ if (lead == 0 || lead == 0x20) return false;
+ return _rule.hasMatch(line.getText().trim());
+}
+
+/// The column of [line]'s prompt glyph — 0, or 2 inside a box's side — or null when the line does
+/// not start a prompt. Always followed by a blank, which is what keeps a `#` or `>` the person
+/// typed at the start of a wrapped row from reading as a new prompt: those rows are indented.
+int? _promptGlyphColumn(BufferLine line) {
+ int at(int column) => column < line.length ? line.getCodePoint(column) : 0;
+ bool blank(int column) => at(column) == 0 || at(column) == 0x20;
+ if (_promptGlyphs.contains(at(0)) && blank(1)) return 0;
+ if (at(0) == _boxSide &&
+ blank(1) &&
+ _promptGlyphs.contains(at(2)) &&
+ blank(3)) {
+ return 2;
+ }
+ return null;
+}
+
+/// Where [line]'s text ends, short of a box's closing side and the padding before it.
+int _textEnd(BufferLine line) {
+ var end = line.getTrimmedLength();
+ if (end > 0 && line.getCodePoint(end - 1) == _boxSide) {
+ end--;
+ while (end > 0 &&
+ (line.getCodePoint(end - 1) == 0 ||
+ line.getCodePoint(end - 1) == 0x20)) {
+ end--;
+ }
+ }
+ return end;
+}
+
+/// Whether [range] holds the prompt's placeholder rather than anything typed: faint text, as both
+/// TUIs draw it (`Try "fix lint errors"`), all of it but the cell the TUI's own cursor is drawn on.
+bool _isPlaceholder(Buffer buffer, BufferRangeLine range) {
+ var cells = 0;
+ var faint = 0;
+ for (final segment in range.toSegments()) {
+ final line = buffer.lines[segment.line];
+ final from = segment.start ?? 0;
+ final to = (segment.end ?? line.length).clamp(0, line.length);
+ for (var x = from; x < to; x++) {
+ final codePoint = line.getCodePoint(x);
+ if (codePoint == 0 || codePoint == 0x20) continue;
+ cells++;
+ if (line.getAttributes(x) & CellFlags.faint != 0) faint++;
+ }
+ }
+ return faint > 0 && faint >= cells - 1;
+}
diff --git a/mobile/lib/terminal/terminal_session.dart b/mobile/lib/terminal/terminal_session.dart
index a863feed6..83250a5ec 100644
--- a/mobile/lib/terminal/terminal_session.dart
+++ b/mobile/lib/terminal/terminal_session.dart
@@ -11,6 +11,7 @@ import 'control_chord.dart';
import 'screen_snapshot.dart';
import 'terminal_binary.dart';
import 'terminal_input.dart';
+import 'terminal_prompt_zone.dart';
import 'terminal_viewport.dart';
import 'utf8_chunks.dart';
@@ -1060,17 +1061,30 @@ class TerminalSession extends ChangeNotifier {
if (identical(_viewport, viewport)) _viewport = null;
}
- /// Empties the prompt being typed into: Ctrl+E to its end, then Ctrl+U to
- /// delete back to its start — what a shell and Claude Code's prompt both
- /// read as "clear the line" — and the keyboard's own buffer with it (see
- /// [TerminalViewport.clearInputBuffer]).
+ /// Empties the prompt being typed into, all of it: Ctrl+K until nothing is
+ /// after the cursor, then Ctrl+U until nothing is before it — what a shell
+ /// and both agents' prompts read as "kill the line" — and the keyboard's own
+ /// buffer with it (see [TerminalViewport.clearInputBuffer]).
+ ///
+ /// ⚠️ **One kill is one ROW, not the prompt.** Claude Code's Ctrl+U deletes
+ /// back to the start of the row as WRAPPED, and at a row's start only the
+ /// newline before it; Ctrl+K likewise forwards. A phone's pane is about
+ /// forty columns wide, so two pastes already wrap, and a single Ctrl+E,
+ /// Ctrl+U left all but the last row behind. So each is sent twice per row
+ /// the prompt can take on screen ([promptRowsBound]): a kill past the
+ /// prompt's ends does nothing.
///
/// ⚠️ Not Ctrl+C: to Claude Code an empty prompt's Ctrl+C is the first half
/// of quitting.
void clearPrompt() {
if (!acceptsInput) return;
- terminal.keyInput(TerminalKey.keyE, ctrl: true);
- terminal.keyInput(TerminalKey.keyU, ctrl: true);
+ final kills = 2 * promptRowsBound(terminal.buffer);
+ for (var i = 0; i < kills; i++) {
+ terminal.keyInput(TerminalKey.keyK, ctrl: true);
+ }
+ for (var i = 0; i < kills; i++) {
+ terminal.keyInput(TerminalKey.keyU, ctrl: true);
+ }
resetInputBuffer();
}
diff --git a/mobile/lib/widgets/terminal_panel.dart b/mobile/lib/widgets/terminal_panel.dart
index 4ea7399f4..3ce8c3609 100644
--- a/mobile/lib/widgets/terminal_panel.dart
+++ b/mobile/lib/widgets/terminal_panel.dart
@@ -18,6 +18,7 @@ import '../terminal/terminal_font_store.dart';
import '../terminal/terminal_link_opener.dart';
import '../terminal/remote_media_download.dart';
import '../terminal/terminal_links.dart';
+import '../terminal/output_blocks.dart';
import '../terminal/terminal_prompt_zone.dart';
import '../phone/tty.dart';
import '../terminal/terminal_session.dart';
@@ -106,6 +107,10 @@ 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.
+ final VoidCallback? onPaste;
+
/// Test seam for OS actions; normal panes use the platform launcher.
final TerminalLinkOpener? linkOpener;
final RemoteMediaDownloader? mediaDownloader;
@@ -125,6 +130,7 @@ class TerminalPanel extends StatefulWidget {
this.onLineTap,
this.lineBands,
this.onBandTap,
+ this.onPaste,
this.linkOpener,
this.mediaDownloader,
});
@@ -187,6 +193,27 @@ class _TerminalPanelState extends State<TerminalPanel>
/// Whether [_releaseBandOnUp] is on the pointer router, waiting for the pressing finger to lift.
bool _bandReleaseRouted = false;
+ /// The selection handles' own box, which their positions are measured into — see
+ /// [_selectionEnds].
+ final GlobalKey _handlesKey = GlobalKey();
+
+ /// The end of the selection the finger on a handle is moving, or null while none is.
+ _SelectionEnd? _draggingEnd;
+
+ /// From the finger to the middle of the row its handle marks, held for the drag: the finger is
+ /// on the knob, not on the text, and the end must not jump to where the finger is.
+ Offset _handleGrab = Offset.zero;
+
+ /// The pane's menu while it is on screen — see [_syncMenu].
+ ContextMenuController? _menu;
+
+ /// Whether [_syncMenu] is already due after this frame.
+ bool _menuPending = false;
+
+ /// The cell a long press on the prompt opened its menu at, or null while that menu is closed —
+ /// see [_openPromptMenu].
+ CellOffset? _promptMenuCell;
+
/// Whether the tap in progress was claimed for [TerminalPanel.onInputTap].
bool _inputTapClaimed = false;
bool _openingLink = false;
@@ -203,6 +230,7 @@ class _TerminalPanelState extends State<TerminalPanel>
_viewTerminal = widget.session.terminal;
_viewTerminal.addListener(_scheduleLinkRefresh);
_scrollController.addListener(_onScrollChanged);
+ _controller.addListener(_scheduleMenu);
_terminalViewKey = GlobalKey<TerminalViewState>();
_linkOpener = widget.linkOpener ?? TerminalLinkOpener();
_mediaDownloader = widget.mediaDownloader ?? RemoteMediaDownloader();
@@ -223,6 +251,8 @@ class _TerminalPanelState extends State<TerminalPanel>
void didChangeDependencies() {
super.didChangeDependencies();
_updateTickerMode();
+ // A sheet pushed over the page, or taken off it — see [_syncMenu].
+ _scheduleMenu();
}
@override
@@ -276,6 +306,8 @@ class _TerminalPanelState extends State<TerminalPanel>
}
_cancelDialInertia();
_controller.clearSelection();
+ _draggingEnd = null;
+ _promptMenuCell = null;
_viewTerminal.removeListener(_scheduleLinkRefresh);
_viewTerminal = widget.session.terminal;
_viewTerminal.addListener(_scheduleLinkRefresh);
@@ -289,6 +321,7 @@ class _TerminalPanelState extends State<TerminalPanel>
_afterTerminalMounted();
}
if (oldWidget.visible && !widget.visible) {
+ _promptMenuCell = null;
_rememberFollowTail();
_focusNode.unfocus();
_cancelDialInertia();
@@ -313,6 +346,7 @@ class _TerminalPanelState extends State<TerminalPanel>
_claimFocusAfterFrame();
}
_syncCursorBlink();
+ if (oldWidget.visible != widget.visible) _scheduleMenu();
}
@override
@@ -332,6 +366,8 @@ class _TerminalPanelState extends State<TerminalPanel>
_cancelDialInertia();
_cursorBlinkTimer?.cancel();
_focusNode.removeListener(_handleFocusChange);
+ _hideMenu();
+ _controller.removeListener(_scheduleMenu);
_controller.dispose();
_scrollController.dispose();
_focusNode.dispose();
@@ -451,6 +487,8 @@ class _TerminalPanelState extends State<TerminalPanel>
// Selection anchors belong to a specific circular buffer. Detach them
// before the TerminalView starts laying out the replacement terminal.
_controller.clearSelection();
+ // The prompt's menu points at a cell of the screen just replaced.
+ _promptMenuCell = null;
_viewTerminal.removeListener(_scheduleLinkRefresh);
_viewTerminal = terminal;
_viewTerminal.addListener(_scheduleLinkRefresh);
@@ -763,17 +801,363 @@ class _TerminalPanelState extends State<TerminalPanel>
Future<void> _copySelection() async {
final selection = _controller.selection;
if (selection == null) return;
- final text = widget.session.terminal.buffer.getText(selection);
+ final text = _selectedText(widget.session.terminal.buffer, selection);
_controller.clearSelection();
await Clipboard.setData(ClipboardData(text: text));
HapticFeedback.lightImpact();
}
+ /// What [selection] copies as. A whole message, as a long press selected it, copies as the agent
+ /// wrote it ([outputBlockText]: no mark, no hang, the TUI's own wraps joined). Anything else — a
+ /// word, ends moved by a handle — copies exactly as marked.
+ String _selectedText(Buffer buffer, BufferRange selection) {
+ final range = selection.normalized;
+ final block = outputBlockAt(buffer, range.begin.y);
+ if (block != null && outputBlockRange(buffer, block) == range) {
+ return outputBlockText(buffer, block);
+ }
+ return buffer.getText(range);
+ }
+
+ /// A long press on an agent's message selects all of it — the `⏺` block, mark to last line —
+ /// rather than the word under the finger: the message is what anybody copies from a phone, and
+ /// a word at a time it took a dozen drags. The handles then move either end.
+ ///
+ /// A long press on the prompt opens its menu instead — Paste, Select — the menu a long press in
+ /// any text field opens: see [_openPromptMenu]. Anywhere else (a plain shell's output) xterm
+ /// selects the word, as it always did.
+ bool _onTerminalLongPressStart(
+ LongPressStartDetails details,
+ CellOffset cell,
+ ) {
+ _promptMenuCell = null;
+ final buffer = _viewTerminal.buffer;
+ final block = outputBlockAt(buffer, cell.y);
+ if (block != null) {
+ _select(outputBlockRange(buffer, block));
+ HapticFeedback.selectionClick();
+ return true;
+ }
+ if (isPromptTap(buffer, cell.y) && _openPromptMenu(cell)) {
+ HapticFeedback.selectionClick();
+ return true;
+ }
+ return false;
+ }
+
+ /// Opens the prompt's menu at [cell], when it would hold anything: Select while there is a word
+ /// under the finger, Select All and Remove while something is typed (see [promptInputRange]),
+ /// 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.
+ bool _openPromptMenu(CellOffset cell) {
+ final buffer = _viewTerminal.buffer;
+ if (!_canPasteHere &&
+ buffer.getWordBoundary(cell) == null &&
+ promptInputRange(buffer) == null) {
+ return false;
+ }
+ _controller.clearSelection();
+ _promptMenuCell = cell;
+ _scheduleMenu();
+ return true;
+ }
+
+ bool get _canPasteHere =>
+ widget.onPaste != null && widget.session.acceptsInput;
+
+ void _closePromptMenu() {
+ if (_promptMenuCell == null) return;
+ _promptMenuCell = null;
+ _scheduleMenu();
+ }
+
+ void _select(BufferRange range) {
+ final buffer = _viewTerminal.buffer;
+ _controller.setSelection(
+ buffer.createAnchorFromOffset(range.begin),
+ buffer.createAnchorFromOffset(range.end),
+ mode: SelectionMode.line,
+ );
+ }
+
+ /// What the selection menu's Select All selects: the next whole thing around the selection —
+ /// the text typed into the prompt when the selection is inside it, the message it lies in, then
+ /// everything the terminal holds. Null once the selection is already all there is.
+ BufferRange? _selectAllTarget() {
+ final selection = _controller.selection?.normalized;
+ if (selection == null) return null;
+ final buffer = _viewTerminal.buffer;
+ final input = promptInputRange(buffer);
+ if (input != null &&
+ input.contains(selection.begin) &&
+ input.contains(selection.end)) {
+ return input == selection ? null : input;
+ }
+ final message = _wholeMessage();
+ if (message != null) return message;
+ final all = _allText(buffer);
+ return all == null || all == selection ? null : all;
+ }
+
+ /// Everything the terminal holds, its history included: from its first row with text to the end
+ /// of its last. Null for a terminal with nothing on it.
+ BufferRangeLine? _allText(Buffer buffer) {
+ final lines = buffer.lines;
+ var first = 0;
+ while (first < lines.length && lines[first].getTrimmedLength() == 0) {
+ first++;
+ }
+ if (first >= lines.length) return null;
+ var last = lines.length - 1;
+ while (last > first && lines[last].getTrimmedLength() == 0) {
+ last--;
+ }
+ return BufferRangeLine(
+ CellOffset(0, first),
+ CellOffset(lines[last].getTrimmedLength(), last),
+ );
+ }
+
+ /// The message the selection lies in, while the selection is not already all of it. Null for a
+ /// selection outside any message, or across two.
+ BufferRange? _wholeMessage() {
+ final selection = _controller.selection?.normalized;
+ if (selection == null) return null;
+ final buffer = _viewTerminal.buffer;
+ final block = outputBlockAt(buffer, selection.begin.y);
+ if (block == null || outputBlockAt(buffer, selection.end.y) != block) {
+ return null;
+ }
+ final range = outputBlockRange(buffer, block);
+ return range == selection ? null : range;
+ }
+
+ /// Brings the pane's menu in line with it after this frame — once, however many selection
+ /// changes, scrolls and output chunks ask in it.
+ ///
+ /// After the frame because the menu reads where its rows were laid out, and because what asks
+ /// can be mid-build (a route's status) or mid-layout (a scroll the renderer corrected).
+ void _scheduleMenu() {
+ if (_menuPending) return;
+ if (_menu == null &&
+ _controller.selection == null &&
+ _promptMenuCell == null) {
+ return;
+ }
+ _menuPending = true;
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ _menuPending = false;
+ if (mounted) _syncMenu();
+ });
+ WidgetsBinding.instance.ensureVisualUpdate();
+ }
+
+ /// Shows the pane's menu — the selection's (Copy, Select All), or the prompt's (Paste, Select) —
+ /// at what it is about, or moves it along; hides it when there is neither.
+ ///
+ /// ⚠️ **Hidden while anything covers the page.** The menu lives in the app's root overlay, above
+ /// every route, so a sheet pushed over this page (its `…` actions) would open UNDER it. Hidden
+ /// too while a handle is being dragged, as the system's own is, and on a page swiped away.
+ void _syncMenu() {
+ final show =
+ widget.visible &&
+ _draggingEnd == null &&
+ (_controller.selection != null || _promptMenuCell != null) &&
+ (ModalRoute.of(context)?.isCurrent ?? true);
+ if (!show) {
+ _hideMenu();
+ return;
+ }
+ final menu = _menu;
+ if (menu != null && menu.isShown) {
+ menu.markNeedsBuild();
+ return;
+ }
+ _menu = ContextMenuController()
+ ..show(context: context, contextMenuBuilder: _buildMenu);
+ }
+
+ void _hideMenu() {
+ _menu?.remove();
+ _menu = null;
+ }
+
+ /// The system's own text toolbar ([AdaptiveTextSelectionToolbar]: iOS's dark bar on an
+ /// iPhone), pointed the way Flutter points it at text — above the first row, or under the last
+ /// when there is no room above. Nothing while those rows are scrolled out of the pane.
+ Widget _buildMenu(BuildContext context) {
+ final selection = _controller.selection?.normalized;
+ final prompt = _promptMenuCell;
+ final render = _laidOutTerminalView()?.renderTerminal;
+ if ((selection == null && prompt == null) ||
+ render == null ||
+ !render.attached ||
+ !render.hasSize) {
+ return const SizedBox.shrink();
+ }
+ final row = render.lineHeight;
+ final from = selection?.begin ?? prompt!;
+ final to = selection?.end ?? CellOffset(prompt!.x + 1, prompt.y);
+ final begin = render.getOffset(from);
+ final end = render.getOffset(to) + Offset(0, row);
+ if (end.dy <= 0 || begin.dy >= render.size.height) {
+ return const SizedBox.shrink();
+ }
+ final anchors = TextSelectionToolbarAnchors.fromSelection(
+ renderBox: render,
+ startGlyphHeight: row,
+ endGlyphHeight: row,
+ selectionEndpoints: [
+ TextSelectionPoint(begin + Offset(0, row), null),
+ TextSelectionPoint(end, null),
+ ],
+ );
+ if (selection != null) {
+ final all = _selectAllTarget();
+ return AdaptiveTextSelectionToolbar.buttonItems(
+ anchors: anchors,
+ buttonItems: [
+ ContextMenuButtonItem(
+ type: ContextMenuButtonType.copy,
+ onPressed: () => unawaited(_copySelection()),
+ ),
+ if (all != null)
+ ContextMenuButtonItem(
+ type: ContextMenuButtonType.selectAll,
+ onPressed: () => _select(all),
+ ),
+ ],
+ );
+ }
+ final buffer = _viewTerminal.buffer;
+ final word = buffer.getWordBoundary(prompt!);
+ final input = promptInputRange(buffer);
+ // Closed by a touch anywhere else, as a text field's is: nothing is selected to tap away.
+ return TapRegion(
+ onTapOutside: (_) => _closePromptMenu(),
+ child: AdaptiveTextSelectionToolbar.buttonItems(
+ anchors: anchors,
+ buttonItems: [
+ if (word != null)
+ ContextMenuButtonItem(
+ label: 'Select',
+ onPressed: () {
+ _closePromptMenu();
+ _select(word);
+ },
+ ),
+ if (input != null)
+ ContextMenuButtonItem(
+ type: ContextMenuButtonType.selectAll,
+ onPressed: () {
+ _closePromptMenu();
+ _select(input);
+ },
+ ),
+ if (_canPasteHere)
+ ContextMenuButtonItem(
+ type: ContextMenuButtonType.paste,
+ onPressed: () {
+ _closePromptMenu();
+ widget.onPaste?.call();
+ },
+ ),
+ // Empties what is typed: Ctrl+K, then Ctrl+U — see [TerminalSession.clearPrompt]. Only
+ // while something is typed and the prompt is this phone's to type into.
+ if (input != null && widget.session.acceptsInput)
+ ContextMenuButtonItem(
+ label: 'Remove',
+ onPressed: () {
+ _closePromptMenu();
+ widget.session.clearPrompt();
+ },
+ ),
+ ],
+ ),
+ );
+ }
+
+ /// Where the selection's ends are drawn, in the handles' own box: the top of the first selected
+ /// cell's left edge, and the top of the cell after the last one. Null with no selection, or
+ /// before layout.
+ ///
+ /// Measured through the terminal's render box, as [_bandRect] is, so the scroll offset and
+ /// xterm's padding are counted exactly as the selection's own paint counts them.
+ ({Offset begin, Offset end, double row})? _selectionEnds() {
+ final selection = _controller.selection?.normalized;
+ final render = _laidOutTerminalView()?.renderTerminal;
+ final box = _handlesKey.currentContext?.findRenderObject();
+ if (selection == null || render == null || !render.attached) return null;
+ if (box is! RenderBox || !box.attached || !box.hasSize) return null;
+ Offset at(CellOffset cell) =>
+ box.globalToLocal(render.localToGlobal(render.getOffset(cell)));
+ return (
+ begin: at(selection.begin),
+ end: at(selection.end),
+ row: render.lineHeight,
+ );
+ }
+
+ void _onHandleDragStart(DragStartDetails details) {
+ _draggingEnd = null;
+ final ends = _selectionEnds();
+ final box = _handlesKey.currentContext?.findRenderObject();
+ if (ends == null || box is! RenderBox) return;
+ final local = box.globalToLocal(details.globalPosition);
+ final end = _SelectionHandlesPainter.handleAt(local, ends);
+ if (end == null) return;
+ final marked = switch (end) {
+ _SelectionEnd.begin => ends.begin,
+ _SelectionEnd.end => ends.end,
+ };
+ _handleGrab = marked + Offset(0, ends.row / 2) - local;
+ _draggingEnd = end;
+ _scheduleMenu();
+ HapticFeedback.selectionClick();
+ }
+
+ /// Moves the dragged end to the cell boundary nearest the finger (less [_handleGrab]). The two
+ /// ends never cross: at least one cell stays selected, and a drag past the other end stops there.
+ void _onHandleDragUpdate(DragUpdateDetails details) {
+ final dragging = _draggingEnd;
+ if (dragging == null) return;
+ final selection = _controller.selection?.normalized;
+ final render = _laidOutTerminalView()?.renderTerminal;
+ if (selection == null || render == null || !render.attached) return;
+ final buffer = _viewTerminal.buffer;
+ final local = render.globalToLocal(details.globalPosition + _handleGrab);
+ final row = render.getCellOffset(local).y;
+ final rowLeft = render.getOffset(CellOffset(0, row)).dx;
+ final column = ((local.dx - rowLeft) / render.cellSize.width).round().clamp(
+ 0,
+ buffer.viewWidth,
+ );
+ final moved = CellOffset(column, row);
+ final begin = dragging == _SelectionEnd.begin ? moved : selection.begin;
+ final end = dragging == _SelectionEnd.end ? moved : selection.end;
+ if (!begin.isBefore(end)) return;
+ if (begin == selection.begin && end == selection.end) return;
+ _controller.setSelection(
+ buffer.createAnchorFromOffset(begin),
+ buffer.createAnchorFromOffset(end),
+ mode: SelectionMode.line,
+ );
+ }
+
+ void _onHandleDragEnd([DragEndDetails? _]) {
+ _draggingEnd = null;
+ _scheduleMenu();
+ }
+
Future<void> _copyOrPaste() async {
final terminal = widget.session.terminal;
final selection = _controller.selection;
if (selection != null) {
- final text = terminal.buffer.getText(selection);
+ final text = _selectedText(terminal.buffer, selection);
_controller.clearSelection();
await Clipboard.setData(ClipboardData(text: text));
return;
@@ -960,6 +1344,8 @@ class _TerminalPanelState extends State<TerminalPanel>
/// Output arrived. Below a reader scrolled up in the history the view holds still, and the
/// position counts the new lines — once per frame, after the layout that placed them.
void _onOutput() {
+ // Output can move a selection's lines, and the menu pointing at them.
+ if (_controller.selection != null) _scheduleMenu();
if (_followTail || !widget.visible || widget.scrollback == null) return;
if (_scrollbackPending) return;
_scrollbackPending = true;
@@ -990,6 +1376,7 @@ class _TerminalPanelState extends State<TerminalPanel>
}
void _onScrollChanged() {
+ _scheduleMenu();
_rememberFollowTail();
_scheduleLinkRefresh();
// A press that turned into a scroll is no longer a press.
@@ -1185,10 +1572,11 @@ class _TerminalPanelState extends State<TerminalPanel>
grid.AppTheme.watch(context);
final session = widget.session;
_syncTerminal(session.terminal);
- final foreground = terminalThemeFor(
+ final colors = terminalThemeFor(
grid.AppTheme.palette.value,
terminalThemeStore.value,
- ).foreground;
+ );
+ final foreground = colors.foreground;
return ColoredBox(
color: grid.AppPalette.windowBg,
child: Column(
@@ -1275,6 +1663,7 @@ class _TerminalPanelState extends State<TerminalPanel>
onKeyEvent: _onTerminalKey,
onTapDown: _onTerminalTapDown,
onTapUp: _onTerminalTapUp,
+ onLongPressStart: _onTerminalLongPressStart,
// Constant on purpose. The click cursor is applied by
// [_LinkTooltip]'s own MouseRegion, which repaints
// without rebuilding this view.
@@ -1311,6 +1700,45 @@ class _TerminalPanelState extends State<TerminalPanel>
),
),
),
+ // The selection's two ends, green, each with a knob to drag it by. Only the knobs and
+ // their rows take a touch ([_SelectionHandlesPainter.hitTest]); everywhere else the
+ // touch goes through to xterm, so a tap still clears the selection and a drag still
+ // scrolls.
+ //
+ // ⚠️ **The drag is claimed on touch-down** ([_EagerPanGestureRecognizer]). The page
+ // swipes between agents on a horizontal drag, and its recognizer would otherwise win
+ // every sideways move of a handle before the handle's own pan saw it.
+ Positioned.fill(
+ child: RawGestureDetector(
+ behavior: HitTestBehavior.deferToChild,
+ gestures: {
+ _EagerPanGestureRecognizer:
+ GestureRecognizerFactoryWithHandlers<
+ _EagerPanGestureRecognizer
+ >(_EagerPanGestureRecognizer.new, (recognizer) {
+ recognizer
+ ..dragStartBehavior = DragStartBehavior.down
+ ..onStart = _onHandleDragStart
+ ..onUpdate = _onHandleDragUpdate
+ ..onEnd = _onHandleDragEnd
+ ..onCancel = _onHandleDragEnd;
+ }),
+ },
+ child: CustomPaint(
+ key: _handlesKey,
+ painter: _SelectionHandlesPainter(
+ ends: _selectionEnds,
+ color: colors.green,
+ // The selection, a scroll and output are what move an end.
+ repaint: Listenable.merge([
+ _controller,
+ _scrollController,
+ session.outputTicks,
+ ]),
+ ),
+ ),
+ ),
+ ),
// Both bars tick once per transferred chunk. Listening here
// keeps that traffic off the pane's own element, so a paste
// or a preview download cannot stutter the live terminal.
@@ -1324,22 +1752,6 @@ class _TerminalPanelState extends State<TerminalPanel>
onCancelPreview: () => _previewCancellation?.cancel(),
),
),
- // A long press selects on a phone, and nothing else offered to copy what it
- // selected: `Copy` rides the selection, top right, until used or cleared.
- // Under the phone's title (three rows, laid over the pane's top), not behind it.
- Positioned(
- top: 60,
- right: 8,
- child: ListenableBuilder(
- listenable: _controller,
- builder: (context, _) => _controller.selection == null
- ? const SizedBox.shrink()
- : _SelectionActions(
- onCopy: () => unawaited(_copySelection()),
- onClear: _controller.clearSelection,
- ),
- ),
- ),
],
),
),
@@ -1349,6 +1761,97 @@ class _TerminalPanelState extends State<TerminalPanel>
}
}
+/// The two ends of a selection: where it starts, and where it stops.
+enum _SelectionEnd { begin, end }
+
+/// A pan that claims its pointer on touch-down — see the handles in [_TerminalPanelState.build].
+///
+/// Accepted while the arena is still open, which makes it the arena's eager winner: no drag
+/// recognizer above it (the page's swipe between agents) can take the pointer from it afterwards.
+class _EagerPanGestureRecognizer extends PanGestureRecognizer {
+ _EagerPanGestureRecognizer()
+ : super(supportedDevices: {PointerDeviceKind.touch});
+
+ @override
+ void addAllowedPointer(PointerDownEvent event) {
+ super.addAllowedPointer(event);
+ resolvePointer(event.pointer, GestureDisposition.accepted);
+ }
+}
+
+/// A selection's handles, drawn: a 2pt bar the height of a row at each end, with a knob above the
+/// first and below the last, as iOS draws its own.
+///
+/// Hit only on a knob or its bar, generously ([_reach]) — a row is ~16pt and a thumb is not.
+/// Everywhere else the touch belongs to xterm underneath.
+class _SelectionHandlesPainter extends CustomPainter {
+ _SelectionHandlesPainter({
+ required this.ends,
+ required this.color,
+ required Listenable repaint,
+ }) : super(repaint: repaint);
+
+ final ({Offset begin, Offset end, double row})? Function() ends;
+ final Color color;
+
+ static const _knob = 6.0;
+ static const _reach = 24.0;
+
+ /// The knob centres, and the bars the knobs hang from.
+ static ({Offset knob, Rect bar}) _begin(
+ ({Offset begin, Offset end, double row}) ends,
+ ) => (
+ knob: ends.begin - const Offset(0, _knob),
+ bar: Rect.fromLTWH(ends.begin.dx - 1, ends.begin.dy, 2, ends.row),
+ );
+
+ static ({Offset knob, Rect bar}) _end(
+ ({Offset begin, Offset end, double row}) ends,
+ ) => (
+ knob: ends.end + Offset(0, ends.row + _knob),
+ bar: Rect.fromLTWH(ends.end.dx - 1, ends.end.dy, 2, ends.row),
+ );
+
+ /// The handle under [position], if any. The end one first: on a one-row selection the two knobs
+ /// are a row apart, and the end is the one somebody most often moves.
+ static _SelectionEnd? handleAt(
+ Offset position,
+ ({Offset begin, Offset end, double row}) ends,
+ ) {
+ bool near(({Offset knob, Rect bar}) handle) =>
+ (position - handle.knob).distance <= _reach ||
+ handle.bar.inflate(_reach / 2).contains(position);
+ if (near(_end(ends))) return _SelectionEnd.end;
+ if (near(_begin(ends))) return _SelectionEnd.begin;
+ return null;
+ }
+
+ @override
+ void paint(Canvas canvas, Size size) {
+ final at = ends();
+ if (at == null) return;
+ canvas.save();
+ canvas.clipRect(Offset.zero & size);
+ final paint = Paint()..color = color;
+ for (final handle in [_begin(at), _end(at)]) {
+ canvas.drawRect(handle.bar, paint);
+ canvas.drawCircle(handle.knob, _knob, paint);
+ }
+ canvas.restore();
+ }
+
+ @override
+ bool? hitTest(Offset position) {
+ final at = ends();
+ return at != null && handleAt(position, at) != null;
+ }
+
+ /// Always: a rebuild is also a layout that can have moved the ends — the keyboard raised, the
+ /// font changed — without the selection, the scroll or the output saying so.
+ @override
+ bool shouldRepaint(_SelectionHandlesPainter old) => true;
+}
+
/// [TerminalPanel.lineBands], drawn: a faint wash across each band's rows, brighter while pressed.
///
/// ⚠️ **Over the text, not under it.** xterm owns its render box's whole background (see
@@ -1513,51 +2016,3 @@ class _TransferOverlay extends StatelessWidget {
);
}
}
-
-/// `Copy ×` over a selection — the phone has no right click and no ⌘C.
-class _SelectionActions extends StatelessWidget {
- const _SelectionActions({required this.onCopy, required this.onClear});
-
- final VoidCallback onCopy;
- final VoidCallback onClear;
-
- @override
- Widget build(BuildContext context) {
- final tty = Tty.of(context);
- Widget action(String label, VoidCallback onTap, {bool bold = false}) =>
- Semantics(
- button: true,
- label: label == '×' ? 'Clear selection' : label,
- excludeSemantics: true,
- child: GestureDetector(
- behavior: HitTestBehavior.opaque,
- onTap: onTap,
- child: ConstrainedBox(
- constraints: const BoxConstraints(minWidth: 44, minHeight: 40),
- child: Padding(
- padding: const EdgeInsets.symmetric(horizontal: 12),
- child: Center(
- widthFactor: 1,
- child: Text(
- label,
- style: tty.style(
- size: 15,
- weight: bold ? FontWeight.w700 : FontWeight.w400,
- ),
- ),
- ),
- ),
- ),
- ),
- );
- return Material(
- color: Color.alphaBlend(tty.text.withValues(alpha: 0.12), tty.ground),
- elevation: 2,
- borderRadius: BorderRadius.circular(6),
- child: Row(
- mainAxisSize: MainAxisSize.min,
- children: [action('Copy', onCopy, bold: true), action('×', onClear)],
- ),
- );
- }
-}
diff --git a/mobile/third_party/xterm/README.autonomous.md b/mobile/third_party/xterm/README.autonomous.md
index 0c3ed58b7..e01042ec7 100644
--- a/mobile/third_party/xterm/README.autonomous.md
+++ b/mobile/third_party/xterm/README.autonomous.md
@@ -36,6 +36,13 @@ fix and the regression in `test/terminal_session_test.dart` passes against it.
Ordinary clicks and drag selection keep their existing behavior. Regressions:
`test/terminal_link_gesture_test.dart`, `test/terminal_panel_links_test.dart`.
+- **Host-handled long presses** (`lib/src/terminal_view.dart`,
+ `lib/src/ui/gesture/gesture_handler.dart`). `TerminalView.onLongPressStart`
+ gets the touch long press first; returning true skips the word selection and
+ the drag-to-extend that follows it. The phone uses it to select a whole agent
+ message (`lib/terminal/output_blocks.dart`), and to open the prompt's Paste
+ menu. Without the callback, a long press selects the word as before.
+
Each of these has to survive an upstream bump — the tests named are what catch
it if one is dropped.
diff --git a/mobile/third_party/xterm/lib/src/terminal_view.dart b/mobile/third_party/xterm/lib/src/terminal_view.dart
index 20b7125c0..f9a1f0efc 100644
--- a/mobile/third_party/xterm/lib/src/terminal_view.dart
+++ b/mobile/third_party/xterm/lib/src/terminal_view.dart
@@ -40,6 +40,7 @@ class TerminalView extends StatefulWidget {
this.autofocus = false,
this.onTapDown,
this.onTapUp,
+ this.onLongPressStart,
this.onSecondaryTapDown,
this.onSecondaryTapUp,
this.mouseCursor = SystemMouseCursors.text,
@@ -111,6 +112,11 @@ class TerminalView extends StatefulWidget {
/// Callback for a primary click handled locally, including [onTapDown].
final void Function(TapUpDetails, CellOffset)? onTapUp;
+ /// Return true to take a touch long press in the host instead of selecting
+ /// the word under it. The drag that follows the press is then the host's
+ /// too: the terminal neither selects nor extends a selection for it.
+ final bool Function(LongPressStartDetails, CellOffset)? onLongPressStart;
+
/// Function called when the user taps on the terminal with a secondary
/// button.
final void Function(TapDownDetails, CellOffset)? onSecondaryTapDown;
@@ -366,6 +372,8 @@ class TerminalViewState extends State<TerminalView> {
terminalController: _controller,
onTapUp: _onTapUp,
onTapDown: _onTapDown,
+ onLongPressStart:
+ widget.onLongPressStart != null ? _onLongPressStart : null,
onSecondaryTapDown:
widget.onSecondaryTapDown != null ? _onSecondaryTapDown : null,
onSecondaryTapUp:
@@ -436,6 +444,13 @@ class TerminalViewState extends State<TerminalView> {
return false;
}
+ bool _onLongPressStart(LongPressStartDetails details) {
+ final offset = renderTerminal.getCellOffset(
+ renderTerminal.globalToLocal(details.globalPosition),
+ );
+ return widget.onLongPressStart?.call(details, offset) ?? false;
+ }
+
void _onSecondaryTapDown(TapDownDetails details) {
final offset = renderTerminal.getCellOffset(details.localPosition);
widget.onSecondaryTapDown?.call(details, offset);
diff --git a/mobile/third_party/xterm/lib/src/ui/gesture/gesture_handler.dart b/mobile/third_party/xterm/lib/src/ui/gesture/gesture_handler.dart
index 237b57ad7..6b6835575 100644
--- a/mobile/third_party/xterm/lib/src/ui/gesture/gesture_handler.dart
+++ b/mobile/third_party/xterm/lib/src/ui/gesture/gesture_handler.dart
@@ -17,6 +17,7 @@ class TerminalGestureHandler extends StatefulWidget {
this.onTapUp,
this.onSingleTapUp,
this.onTapDown,
+ this.onLongPressStart,
this.onSecondaryTapDown,
this.onSecondaryTapUp,
this.onTertiaryTapDown,
@@ -36,6 +37,10 @@ class TerminalGestureHandler extends StatefulWidget {
final bool Function(TapDownDetails)? onTapDown;
+ /// Return true to take the long press in the host — see
+ /// [TerminalView.onLongPressStart].
+ final bool Function(LongPressStartDetails)? onLongPressStart;
+
final GestureTapDownCallback? onSecondaryTapDown;
final GestureTapUpCallback? onSecondaryTapUp;
@@ -61,6 +66,8 @@ class _TerminalGestureHandlerState extends State<TerminalGestureHandler> {
bool _hostHandlesTap = false;
+ bool _hostHandlesLongPress = false;
+
@override
Widget build(BuildContext context) {
return TerminalGestureDetector(
@@ -174,11 +181,14 @@ class _TerminalGestureHandlerState extends State<TerminalGestureHandler> {
}
void onLongPressStart(LongPressStartDetails details) {
+ _hostHandlesLongPress = widget.onLongPressStart?.call(details) ?? false;
+ if (_hostHandlesLongPress) return;
_lastLongPressStartDetails = details;
renderTerminal.selectWord(details.localPosition);
}
void onLongPressMoveUpdate(LongPressMoveUpdateDetails details) {
+ if (_hostHandlesLongPress) return;
renderTerminal.selectWord(
_lastLongPressStartDetails!.localPosition,
details.localPosition,