diff --git a/app/lib/application/app.dart b/app/lib/application/app.dart index cf1abe66..b3f9f64e 100644 --- a/app/lib/application/app.dart +++ b/app/lib/application/app.dart @@ -4,6 +4,8 @@ import '../ui/theme/app_theme.dart'; import '../ui/scale/ui_scale.dart'; import 'package:flutter/material.dart'; +import 'clipboard_failures.dart'; + import '../shell/adaptive_shell.dart'; import '../shell/destination.dart'; @@ -54,6 +56,7 @@ class MyApp extends StatelessWidget { if (router != null) { return MaterialApp.router( title: 'Pipelines', + scaffoldMessengerKey: appScaffoldMessengerKey, builder: _scaled, theme: appLightTheme(fontFamily: fontFamily), darkTheme: appDarkTheme(fontFamily: fontFamily), @@ -63,6 +66,7 @@ class MyApp extends StatelessWidget { } return MaterialApp( title: 'Pipelines', + scaffoldMessengerKey: appScaffoldMessengerKey, builder: _scaled, theme: appLightTheme(fontFamily: fontFamily), darkTheme: appDarkTheme(fontFamily: fontFamily), diff --git a/app/lib/application/bootstrap.dart b/app/lib/application/bootstrap.dart index 24060c00..7e03bd51 100644 --- a/app/lib/application/bootstrap.dart +++ b/app/lib/application/bootstrap.dart @@ -5,6 +5,7 @@ import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; import 'app_url_strategy.dart'; +import 'pipelines_binding.dart'; import 'pipelines_root.dart'; import 'server_endpoint.dart'; import '../features/settings/settings_store.dart'; @@ -55,7 +56,7 @@ Future runPipelinesApp({ SettingsStore? settingsStore, }) async { useAppUrlStrategy(); - WidgetsFlutterBinding.ensureInitialized(); + PipelinesBinding.ensureInitialized(); registerAppFontLicenses(); // The device's chosen font loads beside the session; a slow download does // not hold the first frame, and applies when it lands. diff --git a/app/lib/application/clipboard_failures.dart b/app/lib/application/clipboard_failures.dart new file mode 100644 index 00000000..83d23ebb --- /dev/null +++ b/app/lib/application/clipboard_failures.dart @@ -0,0 +1,100 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +/// The app's root messenger, for messages no screen owns. +final GlobalKey appScaffoldMessengerKey = GlobalKey(); + +/// The message for a failed clipboard call [method] ([error]), or null for +/// a call whose failure is not the operator's to hear about. +/// +/// The web reports a refused clipboard write or read (no permission, an +/// insecure page, a browser without the clipboard API) as an error reply. +String? clipboardFailureMessage(String method, PlatformException error) { + // The web's own reason ("Clipboard is not available in the context." on a + // page that is not secure) helps; its generic "Clipboard.setData failed." + // does not. + final detail = error.message?.trim() ?? ''; + final why = detail.isEmpty || detail.startsWith('Clipboard.') + ? 'the browser refused access to the clipboard' + : detail; + return switch (method) { + 'Clipboard.setData' => 'Could not copy: $why', + 'Clipboard.getData' => 'Could not paste: $why', + _ => null, + }; +} + +/// Shows [message] in the app's root messenger; false when there is none. +bool showAppMessage(String message) { + final messenger = appScaffoldMessengerKey.currentState; + if (messenger == null) return false; + messenger + ..hideCurrentSnackBar() + ..showSnackBar(SnackBar(content: Text(message))); + return true; +} + +/// A [BinaryMessenger] that reports failed clipboard writes and reads. +/// +/// Every copy in the app (the selection's copy keys and menu, copy buttons, +/// the terminal) writes through [Clipboard] on the platform channel, and +/// most never look at the result: a refusal would otherwise only reach the +/// console. The reply still reaches the caller unchanged. +class ClipboardReportingMessenger implements BinaryMessenger { + ClipboardReportingMessenger(this._inner, {void Function(String)? report}) + : _report = report ?? _show; + + final BinaryMessenger _inner; + final void Function(String message) _report; + + static void _show(String message) => showAppMessage(message); + + static const _codec = JSONMethodCodec(); + + @override + Future? send(String channel, ByteData? message) { + final reply = _inner.send(channel, message); + if (reply == null || + channel != SystemChannels.platform.name || + message == null) { + return reply; + } + final String method; + try { + method = _codec.decodeMethodCall(message).method; + } on Object { + return reply; + } + if (!method.startsWith('Clipboard.')) return reply; + return reply.then((data) { + _check(method, data); + return data; + }); + } + + void _check(String method, ByteData? data) { + if (data == null) return; + try { + _codec.decodeEnvelope(data); + } on PlatformException catch (error) { + final message = clipboardFailureMessage(method, error); + if (message != null) _report(message); + } on Object { + // Not a reply this messenger understands; the caller decodes it. + } + } + + @override + // ignore: deprecated_member_use + Future handlePlatformMessage( + String channel, + ByteData? data, + PlatformMessageResponseCallback? callback, + ) => + // ignore: deprecated_member_use + _inner.handlePlatformMessage(channel, data, callback); + + @override + void setMessageHandler(String channel, MessageHandler? handler) => + _inner.setMessageHandler(channel, handler); +} diff --git a/app/lib/application/pipelines_binding.dart b/app/lib/application/pipelines_binding.dart new file mode 100644 index 00000000..ff67144f --- /dev/null +++ b/app/lib/application/pipelines_binding.dart @@ -0,0 +1,38 @@ +import 'package:flutter/services.dart'; +import 'package:flutter/widgets.dart'; + +import '../core/keyboard/key_modifier_sync.dart'; +import 'clipboard_failures.dart'; + +/// The app's binding: Flutter's, with clipboard failures reported +/// ([ClipboardReportingMessenger]) and, on the web, key events carrying the +/// modifiers their browser events hold ([KeyModifierSync]). +/// +/// An entry point calls [ensureInitialized] before anything else creates a +/// binding. +class PipelinesBinding extends WidgetsFlutterBinding { + PipelinesBinding._(); + + static bool _created = false; + + /// The binding, created on the first call. + static WidgetsBinding ensureInitialized() { + if (!_created) { + _created = true; + PipelinesBinding._(); + } + return WidgetsBinding.instance; + } + + @override + void initInstances() { + super.initInstances(); + // The services binding hands key data to the framework only once the + // keyboard state is synced; the modifier sync goes in front of it then. + keyboard.syncKeyboardState().then((_) => installKeyModifierSync()); + } + + @override + BinaryMessenger createBinaryMessenger() => + ClipboardReportingMessenger(super.createBinaryMessenger()); +} diff --git a/app/lib/core/keyboard/key_event_modifiers.dart b/app/lib/core/keyboard/key_event_modifiers.dart new file mode 100644 index 00000000..a55358ac --- /dev/null +++ b/app/lib/core/keyboard/key_event_modifiers.dart @@ -0,0 +1,28 @@ +import 'key_event_modifiers_stub.dart' + if (dart.library.js_interop) 'key_event_modifiers_web.dart' + as platform; + +/// The modifier flags a key event itself carries. +class KeyEventModifiers { + const KeyEventModifiers({ + this.control = false, + this.shift = false, + this.alt = false, + this.meta = false, + }); + + final bool control; + final bool shift; + final bool alt; + final bool meta; + + @override + String toString() => + 'KeyEventModifiers(control: $control, shift: $shift, alt: $alt, ' + 'meta: $meta)'; +} + +/// The flags of the browser key event being dispatched (null elsewhere, or +/// when no key event is). +KeyEventModifiers? currentKeyEventModifiers() => + platform.currentKeyEventModifiers(); diff --git a/app/lib/core/keyboard/key_event_modifiers_stub.dart b/app/lib/core/keyboard/key_event_modifiers_stub.dart new file mode 100644 index 00000000..081fdb7e --- /dev/null +++ b/app/lib/core/keyboard/key_event_modifiers_stub.dart @@ -0,0 +1,3 @@ +import 'key_event_modifiers.dart'; + +KeyEventModifiers? currentKeyEventModifiers() => null; diff --git a/app/lib/core/keyboard/key_event_modifiers_web.dart b/app/lib/core/keyboard/key_event_modifiers_web.dart new file mode 100644 index 00000000..9e30e1cf --- /dev/null +++ b/app/lib/core/keyboard/key_event_modifiers_web.dart @@ -0,0 +1,20 @@ +import 'dart:js_interop'; + +import 'package:web/web.dart' as web; + +import 'key_event_modifiers.dart'; + +/// The browser's current event (`window.event`), set while its listeners +/// run, so the engine's key listener (and the key data it sends the +/// framework synchronously) is inside it. +KeyEventModifiers? currentKeyEventModifiers() { + final event = web.window.event; + if (event == null || !event.isA()) return null; + final key = event as web.KeyboardEvent; + return KeyEventModifiers( + control: key.ctrlKey, + shift: key.shiftKey, + alt: key.altKey, + meta: key.metaKey, + ); +} diff --git a/app/lib/core/keyboard/key_modifier_sync.dart b/app/lib/core/keyboard/key_modifier_sync.dart new file mode 100644 index 00000000..60c5cf0e --- /dev/null +++ b/app/lib/core/keyboard/key_modifier_sync.dart @@ -0,0 +1,240 @@ +import 'dart:ui' as ui; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; + +import 'key_event_modifiers.dart'; + +/// Keeps the framework's modifier state ([HardwareKeyboard]) in step with the +/// modifier flags of the key event being handled. +/// +/// A browser reports Ctrl, Shift, Alt and Meta on every key event, but +/// Flutter's web engine only learns that a modifier is down from that +/// modifier's own key event; it releases modifiers the flags say are up, but +/// never presses one the flags say is down. A shortcut a desktop injects +/// (Omarchy's universal copy: Super+C sends Ctrl+C by setting the modifier +/// state, with no Ctrl key event, while Super is still held) therefore +/// reached the app as a plain "c": nothing was copied, and the terminal +/// typed the letter. This sync sits in front of the framework's key data +/// handler and, for each non-modifier key, presses (synthesized) the +/// modifiers the event's flags hold that the framework does not, then +/// releases them with that key. +/// +/// Outside Apple platforms Meta is never part of the clipboard keys, so a +/// Meta (Super) that is held, or merged into such a chord, does not stop +/// Ctrl+C, V, X, A or Insert from being the clipboard key: Meta is released +/// for the chord and pressed again after it. +class KeyModifierSync { + KeyModifierSync({ + required this.forward, + required this.modifiers, + HardwareKeyboard? keyboard, + TargetPlatform Function()? platform, + }) : _keyboard = keyboard ?? HardwareKeyboard.instance, + _platform = platform ?? (() => defaultTargetPlatform); + + /// The framework's key data handler, which this one is placed in front of. + final bool Function(ui.KeyData data) forward; + + /// The flags of the key event being handled, or null when unknown. + final KeyEventModifiers? Function() modifiers; + + final HardwareKeyboard _keyboard; + final TargetPlatform Function() _platform; + + /// The sync installed in front of the app's key events, if any. + static KeyModifierSync? instance; + + /// Modifiers pressed by this sync, not by a key. + final Set _added = {}; + + /// Held modifiers this sync released for a chord, to press again after it. + final Map _released = {}; + + /// The key whose release ends the current chord. + PhysicalKeyboardKey? _chordKey; + + /// Whether Ctrl is down only because the key event says so: no Ctrl key + /// was pressed, so the chord came from a shortcut the desktop injected + /// (the "copy button"), not from the keyboard's Ctrl key. + bool get controlFromFlags => _added.contains(PhysicalKeyboardKey.controlLeft); + + /// Whether Ctrl is down only because the key event says so, for the + /// installed sync (false when none is). + static bool get injectedControl => instance?.controlFromFlags ?? false; + + /// Handles one key data from the engine: the framework's handler sees it + /// with the modifiers its event's flags hold. + bool handle(ui.KeyData data) { + final physical = PhysicalKeyboardKey(data.physical); + if (data.physical == 0 && data.logical == 0) return forward(data); + if (_added.contains(physical)) { + // The real key of a modifier this sync pressed: its own events win. + _release(physical, data.timeStamp); + } + if (_released.containsKey(physical)) { + // A modifier released for a chord: the framework already has it up. + // Its repeats are dropped; once it is let go (or the engine notices + // it is up) it is not pressed again after the chord. + switch (data.type) { + case ui.KeyEventType.repeat: + return false; + case ui.KeyEventType.up: + _released.remove(physical); + return false; + case ui.KeyEventType.down: + _released.remove(physical); + } + } + if (data.synthesized || _modifierKeys.contains(physical)) { + return forward(data); + } + final flags = modifiers(); + if (flags != null) _reconcile(flags, data); + final handled = forward(data); + if (data.type == ui.KeyEventType.up && physical == _chordKey) { + _endChord(data.timeStamp); + } + return handled; + } + + void _reconcile(KeyEventModifiers flags, ui.KeyData data) { + final logical = LogicalKeyboardKey(data.logical); + final clipboard = + flags.control && + _clipboardKeys.contains(logical) && + _platform() != TargetPlatform.macOS && + _platform() != TargetPlatform.iOS; + var changed = false; + final press = <_Modifier>[]; + // Releases first, so no chord ever holds both the old and new keys. + for (final modifier in _modifiers) { + final want = modifier.flag(flags) && !(clipboard && modifier.meta); + final held = modifier.keys + .where(_keyboard.physicalKeysPressed.contains) + .toList(); + if (want && held.isEmpty) { + press.add(modifier); + } else if (!want) { + for (final key in held) { + if (_added.contains(key)) { + _release(key, data.timeStamp); + changed = true; + } else if (modifier.meta && clipboard) { + // A held Super (Meta) is not part of a clipboard chord here. + final logical = _keyboard.lookUpLayout(key)!; + _released[key] = logical; + _lift(key, logical, data.timeStamp); + changed = true; + } + } + } + } + for (final modifier in press) { + _press(modifier.keys.first, modifier.logical, data.timeStamp); + _added.add(modifier.keys.first); + changed = true; + } + if (changed && data.type == ui.KeyEventType.down) { + _chordKey = PhysicalKeyboardKey(data.physical); + } + } + + /// Releases what the chord pressed and presses again what it released. + void _endChord(Duration timeStamp) { + _chordKey = null; + for (final key in _added.toList()) { + _release(key, timeStamp); + } + final released = Map.of(_released); + _released.clear(); + released.forEach((key, logical) => _press(key, logical, timeStamp)); + } + + void _release(PhysicalKeyboardKey key, Duration timeStamp) { + _added.remove(key); + final logical = _keyboard.lookUpLayout(key); + if (logical != null) _lift(key, logical, timeStamp); + } + + void _press( + PhysicalKeyboardKey key, + LogicalKeyboardKey logical, + Duration timeStamp, + ) => forward(_synthesized(ui.KeyEventType.down, key, logical, timeStamp)); + + void _lift( + PhysicalKeyboardKey key, + LogicalKeyboardKey logical, + Duration timeStamp, + ) => forward(_synthesized(ui.KeyEventType.up, key, logical, timeStamp)); + + static ui.KeyData _synthesized( + ui.KeyEventType type, + PhysicalKeyboardKey key, + LogicalKeyboardKey logical, + Duration timeStamp, + ) => ui.KeyData( + timeStamp: timeStamp, + type: type, + physical: key.usbHidUsage, + logical: logical.keyId, + character: null, + synthesized: true, + ); + + static final Set _clipboardKeys = { + LogicalKeyboardKey.keyC, + LogicalKeyboardKey.keyV, + LogicalKeyboardKey.keyX, + LogicalKeyboardKey.keyA, + LogicalKeyboardKey.insert, + }; + + static final List<_Modifier> _modifiers = [ + _Modifier((f) => f.control, LogicalKeyboardKey.controlLeft, const [ + PhysicalKeyboardKey.controlLeft, + PhysicalKeyboardKey.controlRight, + ]), + _Modifier((f) => f.shift, LogicalKeyboardKey.shiftLeft, const [ + PhysicalKeyboardKey.shiftLeft, + PhysicalKeyboardKey.shiftRight, + ]), + _Modifier((f) => f.alt, LogicalKeyboardKey.altLeft, const [ + PhysicalKeyboardKey.altLeft, + PhysicalKeyboardKey.altRight, + ]), + _Modifier((f) => f.meta, LogicalKeyboardKey.metaLeft, const [ + PhysicalKeyboardKey.metaLeft, + PhysicalKeyboardKey.metaRight, + ], meta: true), + ]; + + static final Set _modifierKeys = { + for (final modifier in _modifiers) ...modifier.keys, + }; +} + +class _Modifier { + const _Modifier(this.flag, this.logical, this.keys, {this.meta = false}); + final bool Function(KeyEventModifiers flags) flag; + final LogicalKeyboardKey logical; + final List keys; + final bool meta; +} + +/// Places a [KeyModifierSync] in front of the app's key events on the web, +/// where the browser's event flags are the modifier truth. Native embedders +/// already derive modifier state from their events' flags. +void installKeyModifierSync() { + if (!kIsWeb || KeyModifierSync.instance != null) return; + final dispatcher = ui.PlatformDispatcher.instance; + final framework = dispatcher.onKeyData; + if (framework == null) return; + final sync = KeyModifierSync( + forward: framework, + modifiers: currentKeyEventModifiers, + ); + dispatcher.onKeyData = sync.handle; + KeyModifierSync.instance = sync; +} diff --git a/app/lib/features/chat/shell/chat_shell_terminal_shortcuts.dart b/app/lib/features/chat/shell/chat_shell_terminal_shortcuts.dart index d8e37498..d2216128 100644 --- a/app/lib/features/chat/shell/chat_shell_terminal_shortcuts.dart +++ b/app/lib/features/chat/shell/chat_shell_terminal_shortcuts.dart @@ -7,11 +7,11 @@ bool _apple() => defaultTargetPlatform == TargetPlatform.iOS; /// The terminal's own key shortcuts. Cmd-C, Cmd-V and Cmd-A on Apple -/// platforms; elsewhere Ctrl-V (and the terminal convention Ctrl-Shift-V) -/// paste and Ctrl-Shift-C or Ctrl-Insert copies, so every other Ctrl key, -/// Ctrl-A included, reaches the process. Ctrl-C copies too while text is -/// selected (see [chatShellCopyKey]); a browser keeps Ctrl-Shift-C for its -/// developer tools, so there it is the key that works. +/// platforms; elsewhere Ctrl-V (and the terminal conventions Ctrl-Shift-V +/// and Shift-Insert) paste and Ctrl-Shift-C or Ctrl-Insert copies, so every +/// other Ctrl key, Ctrl-A included, reaches the process. Ctrl-C copies too +/// while text is selected (see [chatShellCopyKey]); a browser keeps +/// Ctrl-Shift-C for its developer tools, so there it is the key that works. Map chatShellTerminalShortcuts() { const paste = PasteTextIntent(SelectionChangedCause.keyboard); if (_apple()) { @@ -31,6 +31,7 @@ Map chatShellTerminalShortcuts() { CopySelectionTextIntent.copy, SingleActivator(LogicalKeyboardKey.keyV, control: true): paste, SingleActivator(LogicalKeyboardKey.keyV, control: true, shift: true): paste, + SingleActivator(LogicalKeyboardKey.insert, shift: true): paste, }; } diff --git a/app/lib/features/chat/shell/chat_shell_terminal_view.dart b/app/lib/features/chat/shell/chat_shell_terminal_view.dart index 9e87ff3d..289100de 100644 --- a/app/lib/features/chat/shell/chat_shell_terminal_view.dart +++ b/app/lib/features/chat/shell/chat_shell_terminal_view.dart @@ -3,6 +3,7 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:xterm/xterm.dart'; +import '../../../core/keyboard/key_modifier_sync.dart'; import '../conversation/chat_composer_paste_focus.dart'; import '../ui/transcript/chat_link_launcher.dart'; import 'chat_shell_metrics.dart'; @@ -127,14 +128,18 @@ class _ChatShellTerminalViewState extends State super.dispose(); } - /// Ctrl-C with a selection copies; the view's own keys (find, zoom, - /// scrolling) are answered; the terminal's own shortcuts (copy, paste) - /// are left to it; any other key xterm encodes differently from - /// xterm.dart (Alt as Meta, Ctrl symbols, modified special keys) is sent - /// here with its real character. The rest is the emulator's. + /// Ctrl-C with a selection copies (and sends no ^C); a desktop's copy + /// shortcut (Ctrl+C injected with no Ctrl key held, see + /// [KeyModifierSync.injectedControl]) only ever copies; the view's own + /// keys (find, zoom, scrolling) are answered; the terminal's own + /// shortcuts (copy, paste) are left to it; any other key xterm encodes + /// differently from xterm.dart (Alt as Meta, Ctrl symbols, modified + /// special keys) is sent here with its real character. The rest is the + /// emulator's. KeyEventResult _key(FocusNode node, KeyEvent event) { final keyboard = HardwareKeyboard.instance; - if (chatShellCopyKey(event, keyboard) && actions.copySelection()) { + if (chatShellCopyKey(event, keyboard) && + (actions.copySelection() || KeyModifierSync.injectedControl)) { return KeyEventResult.handled; } if (localKey(event)) return KeyEventResult.handled; diff --git a/app/lib/features/settings/keyboard_shortcuts_registry.dart b/app/lib/features/settings/keyboard_shortcuts_registry.dart index 22fdcc3b..c9aca0a3 100644 --- a/app/lib/features/settings/keyboard_shortcuts_registry.dart +++ b/app/lib/features/settings/keyboard_shortcuts_registry.dart @@ -231,7 +231,7 @@ class KeyboardShortcutRegistry { KeyboardShortcutEntry( group: KeyboardShortcutGroup.terminal, action: 'Paste into the terminal', - keys: _apple ? 'Cmd+V' : 'Ctrl+V, Ctrl+Shift+V', + keys: _apple ? 'Cmd+V' : 'Ctrl+V, Ctrl+Shift+V, Shift+Insert', ), if (_apple) const KeyboardShortcutEntry( diff --git a/app/notes/clipboard-keys.md b/app/notes/clipboard-keys.md new file mode 100644 index 00000000..6f621924 --- /dev/null +++ b/app/notes/clipboard-keys.md @@ -0,0 +1,70 @@ +# Clipboard keys (copy/paste everywhere, Omarchy universal copy, terminal Ctrl+C) + +Operator report: copying out of the web app was unreliable; the desktop's +universal copy key (Omarchy SUPER+C) worked everywhere but Pipelines; Ctrl+C +should not end the terminal session. + +## Root causes + +- **Universal copy/paste (confirmed in Chromium over CDP).** Omarchy's + SUPER+C (`/usr/share/omarchy/default/hypr/bindings/clipboard.lua`) sends + Ctrl+C with Hyprland `send_key_state`: the key event carries `ctrlKey`, but + no Ctrl key event is ever sent, while Super is physically held. Flutter's + web engine learns a modifier is down only from that modifier's own key + event (it synthesizes *releases* from the flags, never presses), so the + framework saw a plain `c`: the chat selection was not copied and the + terminal typed the letter. If the browser also reports Meta for the chord, + Ctrl+Meta+C matched no copy shortcut either. Physical Ctrl+C / Ctrl+Insert + worked. Paste into text fields mostly worked because the browser's own + paste follows the event flags. +- **Ctrl+C ending a terminal (confirmed with util-linux su 2.42).** Before + the login completes the terminal is `su -l `: Ctrl+C at the + password prompt kills su with SIGINT and the terminal ends ("The login did + not complete"). After login, su 2.42 runs the shell in its own pty, so + Ctrl+C reaches the shell and the session survives (checked with real su in + a user namespace). No client path closes a tab on Ctrl+C. + +## Fixes + +- `lib/core/keyboard/key_modifier_sync.dart`: on the web, a sync in front of + the framework's key data handler reads the browser event's own modifier + flags (`window.event`) and presses (synthesized) the modifiers the flags + hold that the framework does not, releasing them with the chord's key. + Outside Apple platforms a held/merged Meta is released for Ctrl+C/V/X/A/ + Insert and pressed again afterwards. Installed by `PipelinesBinding` + (`lib/application/pipelines_binding.dart`) once the services binding has + set its key handler. +- Terminal (`chat_shell_terminal_view.dart`): Ctrl+C with a selection + copies and clears it, never ^C; without one it is ^C; an injected Ctrl+C + (no Ctrl key held: the desktop's copy key) only ever copies. Shift+Insert + pastes (`chat_shell_terminal_shortcuts.dart`). +- Copy never fails silently: `ClipboardReportingMessenger` + (`lib/application/clipboard_failures.dart`) reports a refused + `Clipboard.setData`/`getData` reply as a snackbar ("Could not copy: …"). +- Server (`internal/server/terminal_login.go`, `terminal_process.go`): + before the login completes Ctrl+C and Ctrl+\ are sent as Ctrl+U (erase the + typed password) and Ctrl+Z is dropped, so su is not killed or stopped. + +## Evidence + +Widget tests: `test/core/keyboard/`, `test/features/chat/ui/transcript/ +chat_injected_clipboard_keys_test.dart`, `test/features/chat/conversation/ +chat_composer_injected_paste_test.dart`, `test/features/chat/shell/ +chat_shell_terminal_clipboard_keys_test.dart`, `test/application/ +clipboard_failures_test.dart`; Go `TestTerminalCtrlCAtLoginPromptKeepsTheTerminal`. + +Browser (headless Chromium, `--semantics false`, clipboard read back with +`navigator.clipboard.readText()`), scripts in `tool/capture/examples/ +clipboard-*.json`: before the fix the Super+C sequences (Meta down, `c` with +Ctrl flags and no Ctrl key, both with and without Meta in the flags) left +the clipboard unchanged in the chat and the terminal; after it they copy +"Answer 19" / the terminal selection, Super+C with nothing selected sends no +^C, Super+V pastes once into the terminal and the composer, physical Ctrl+C +without a selection still sends ^C, and a rejected `writeText` shows "Could +not copy: the browser refused access to the clipboard". + +Not verified: the real Hyprland session (whether it reports Meta with the +chord is covered both ways); text fields when the browser reports Ctrl and +Meta together (the browser's native paste may not run then). With Flutter +semantics enabled, copying the transcript after typing in the composer did +not copy before or after this change (semantics off works); not addressed. diff --git a/app/notes/terminal-panel.md b/app/notes/terminal-panel.md index bc0c88cd..5edd25cf 100644 --- a/app/notes/terminal-panel.md +++ b/app/notes/terminal-panel.md @@ -102,7 +102,10 @@ tmux inside it for work that must survive that). byte held. A restarted server lists the terminals as ended, with why. - **Keyboard:** a focused terminal gets every key (Ctrl-C, Esc, Tab, arrows, Ctrl-letters, Ctrl+T, Alt+T) except Cmd+T, Ctrl+` and Ctrl+Tab while - shown; paste is Cmd-V (Apple) or Ctrl-V/Ctrl-Shift-V. Clicking elsewhere + shown; paste is Cmd-V (Apple) or Ctrl-V/Ctrl-Shift-V/Shift-Insert. Ctrl-C + with a selection copies it (no ^C); a desktop's injected copy key + (Omarchy Super+C) only ever copies (`clipboard-keys.md`). Ctrl-C at the + login prompt erases the typed password instead of ending su. Clicking elsewhere moves focus away normally. Keys are encoded as xterm does; see `chat-interactive-terminal.md` (Keys). **Option as Meta** (Settings → Appearance → Terminal, Macs only, saved with the layout, default on): a diff --git a/app/test/application/clipboard_failures_test.dart b/app/test/application/clipboard_failures_test.dart new file mode 100644 index 00000000..fb7ec87e --- /dev/null +++ b/app/test/application/clipboard_failures_test.dart @@ -0,0 +1,107 @@ +import 'dart:ui' as ui; + +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/application/clipboard_failures.dart'; + +/// A platform side that answers every platform-channel call with [reply]. +class _Platform implements BinaryMessenger { + _Platform(this.reply); + final ByteData? Function(MethodCall call) reply; + static const codec = JSONMethodCodec(); + + @override + Future? send(String channel, ByteData? message) async => + reply(codec.decodeMethodCall(message)); + + @override + Future handlePlatformMessage( + String channel, + ByteData? data, + ui.PlatformMessageResponseCallback? callback, + ) async {} + + @override + void setMessageHandler(String channel, MessageHandler? handler) {} +} + +void main() { + const codec = JSONMethodCodec(); + final refused = codec.encodeErrorEnvelope( + code: 'copy_fail', + message: 'Clipboard.setData failed.', + ); + + Future<(List, Object?)> call( + String method, + ByteData? Function(MethodCall) reply, + ) async { + final reports = []; + final messenger = ClipboardReportingMessenger( + _Platform(reply), + report: reports.add, + ); + final channel = MethodChannel( + SystemChannels.platform.name, + codec, + messenger, + ); + Object? error; + try { + await channel.invokeMethod(method, {'text': 'x'}); + } on PlatformException catch (e) { + error = e; + } + return (reports, error); + } + + test( + 'a refused clipboard write is reported and still reaches the caller', + () async { + final (reports, error) = await call('Clipboard.setData', (_) => refused); + expect(reports, [ + 'Could not copy: the browser refused access to the clipboard', + ]); + expect(error, isA()); + }, + ); + + test('an insecure page says why; a refused read is reported too', () async { + final (reports, _) = await call( + 'Clipboard.getData', + (_) => codec.encodeErrorEnvelope( + code: 'paste_fail', + message: 'Clipboard is not available in the context.', + ), + ); + expect(reports, [ + 'Could not paste: Clipboard is not available in the context.', + ]); + }); + + test('successes and passive checks are not reported', () async { + final (ok, _) = await call( + 'Clipboard.setData', + (_) => codec.encodeSuccessEnvelope(null), + ); + expect(ok, isEmpty); + final (checks, _) = await call( + 'Clipboard.hasStrings', + (_) => codec.encodeErrorEnvelope(code: 'has_strings_fail'), + ); + expect(checks, isEmpty); + }); + + testWidgets('the message shows in the app', (tester) async { + await tester.pumpWidget( + MaterialApp( + scaffoldMessengerKey: appScaffoldMessengerKey, + home: const Scaffold(), + ), + ); + expect(showAppMessage('Could not copy: denied'), isTrue); + await tester.pump(); + expect(find.text('Could not copy: denied'), findsOneWidget); + }); +} diff --git a/app/test/core/keyboard/browser_keys.dart b/app/test/core/keyboard/browser_keys.dart new file mode 100644 index 00000000..63137a90 --- /dev/null +++ b/app/test/core/keyboard/browser_keys.dart @@ -0,0 +1,204 @@ +// ignore_for_file: deprecated_member_use + +import 'dart:ui' as ui; + +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/keyboard/key_event_modifiers.dart'; +import 'package:pipelines_app/core/keyboard/key_modifier_sync.dart'; + +/// Key events as Flutter's web engine delivers browser key events, through +/// the app's [KeyModifierSync] into the widget tree under test. +/// +/// Like the engine, it knows a modifier is down only from that modifier's +/// own key event, and releases (synthesized) a modifier the next event's +/// flags say is up. So a desktop's injected shortcut, which sets the +/// modifier flags without any Ctrl key event, arrives exactly as in the +/// browser. +class BrowserKeys { + BrowserKeys(this.tester) { + sync = KeyModifierSync(forward: _forward, modifiers: () => _flags); + KeyModifierSync.instance = sync; + addTearDown(() => KeyModifierSync.instance = null); + } + + final WidgetTester tester; + late final KeyModifierSync sync; + KeyEventModifiers? _flags; + final _engineHeld = {}; + + static final _modifierFlags = { + PhysicalKeyboardKey.controlLeft: 'control', + PhysicalKeyboardKey.shiftLeft: 'shift', + PhysicalKeyboardKey.altLeft: 'alt', + PhysicalKeyboardKey.metaLeft: 'meta', + }; + + static bool _flag(KeyEventModifiers flags, String name) => switch (name) { + 'control' => flags.control, + 'shift' => flags.shift, + 'alt' => flags.alt, + _ => flags.meta, + }; + + /// One browser key event for [key] (down or up) whose flags are [flags]. + Future event( + LogicalKeyboardKey key, { + required bool down, + KeyEventModifiers flags = const KeyEventModifiers(), + String? character, + }) async { + _flags = flags; + final physical = _physical(key); + final stamp = Duration.zero; + for (final held in _engineHeld.toList()) { + if (held == physical || _flag(flags, _modifierFlags[held]!)) continue; + _engineHeld.remove(held); + sync.handle(_data(ui.KeyEventType.up, held, null, stamp, true)); + } + if (_modifierFlags.containsKey(physical)) { + if (down) { + _engineHeld.add(physical); + } else if (!_engineHeld.remove(physical)) { + // The engine drops the release of a key it does not hold. + return tester.pump(); + } + } + final repeat = + down && + HardwareKeyboard.instance.physicalKeysPressed.contains(physical); + sync.handle( + _data( + down + ? (repeat ? ui.KeyEventType.repeat : ui.KeyEventType.down) + : ui.KeyEventType.up, + physical, + key, + stamp, + false, + character: down ? character : null, + raw: (down, key, flags), + ), + ); + // The engine sends the raw message even for an event whose key data + // the sync dropped. + if (_pendingRaw.isNotEmpty) _sendRaw(); + await tester.pump(); + } + + /// A key pressed and released with [flags] on both events. + Future tap( + LogicalKeyboardKey key, { + KeyEventModifiers flags = const KeyEventModifiers(), + String? character, + }) async { + await event(key, down: true, flags: flags, character: character); + await event(key, down: false, flags: flags); + } + + /// Omarchy's universal clipboard key: Super held, then [key] with Ctrl in + /// its flags (and Meta too when [mergedMeta]), with no Ctrl key event; + /// Super is let go afterwards. + Future superChord( + LogicalKeyboardKey key, { + bool mergedMeta = false, + String? character, + }) async { + const meta = KeyEventModifiers(meta: true); + final chord = KeyEventModifiers(control: true, meta: mergedMeta); + await event(LogicalKeyboardKey.metaLeft, down: true, flags: meta); + await event(key, down: true, flags: chord, character: character); + await event(key, down: false, flags: chord); + await event(LogicalKeyboardKey.metaLeft, down: false); + } + + /// [key] with a real modifier key held: [modifier] pressed, [key] tapped, + /// [modifier] released. + Future chord( + LogicalKeyboardKey modifier, + LogicalKeyboardKey key, { + KeyEventModifiers flags = const KeyEventModifiers(control: true), + }) async { + await event(modifier, down: true, flags: flags); + await tap(key, flags: flags); + await event(modifier, down: false); + } + + final _pendingRaw = <(bool, LogicalKeyboardKey, KeyEventModifiers)>[]; + + ui.KeyData _data( + ui.KeyEventType type, + PhysicalKeyboardKey physical, + LogicalKeyboardKey? logical, + Duration stamp, + bool synthesized, { + String? character, + (bool, LogicalKeyboardKey, KeyEventModifiers)? raw, + }) { + if (raw != null) _pendingRaw.add(raw); + return ui.KeyData( + timeStamp: stamp, + type: type, + physical: physical.usbHidUsage, + logical: + (logical ?? + HardwareKeyboard.instance.lookUpLayout(physical) ?? + LogicalKeyboardKey.metaLeft) + .keyId, + character: character, + synthesized: synthesized, + ); + } + + /// The framework's handler, as the engine calls it: key data, then (for + /// the event's own key) the raw key message that completes it. + bool _forward(ui.KeyData data) { + final handled = tester.binding.keyEventManager.handleKeyData(data); + if (!data.synthesized && _pendingRaw.isNotEmpty) _sendRaw(); + return handled; + } + + void _sendRaw() { + final (down, key, flags) = _pendingRaw.removeLast(); + tester.binding.keyEventManager.handleRawKeyMessage( + _rawMessage(down, key, flags), + ); + } + + static Map _rawMessage( + bool down, + LogicalKeyboardKey key, + KeyEventModifiers flags, + ) => { + 'type': down ? 'keydown' : 'keyup', + 'keymap': 'web', + 'code': _physical(key).debugName?.replaceAll(' ', '') ?? '', + 'key': key.keyLabel, + 'location': 0, + 'metaState': + (flags.shift ? 0x01 : 0) | + (flags.alt ? 0x02 : 0) | + (flags.control ? 0x04 : 0) | + (flags.meta ? 0x08 : 0), + 'keyCode': 0, + }; + + static PhysicalKeyboardKey _physical(LogicalKeyboardKey key) => + _physicalKeys[key] ?? _letterPhysical(key); + + static final _physicalKeys = { + LogicalKeyboardKey.controlLeft: PhysicalKeyboardKey.controlLeft, + LogicalKeyboardKey.shiftLeft: PhysicalKeyboardKey.shiftLeft, + LogicalKeyboardKey.altLeft: PhysicalKeyboardKey.altLeft, + LogicalKeyboardKey.metaLeft: PhysicalKeyboardKey.metaLeft, + LogicalKeyboardKey.insert: PhysicalKeyboardKey.insert, + }; + + static PhysicalKeyboardKey _letterPhysical(LogicalKeyboardKey key) { + final id = key.keyId; + if (id >= 0x61 && id <= 0x7a) { + return PhysicalKeyboardKey(0x00070004 + id - 0x61); + } + throw ArgumentError('no physical key for $key'); + } +} diff --git a/app/test/core/keyboard/key_modifier_sync_test.dart b/app/test/core/keyboard/key_modifier_sync_test.dart new file mode 100644 index 00000000..62a54612 --- /dev/null +++ b/app/test/core/keyboard/key_modifier_sync_test.dart @@ -0,0 +1,220 @@ +import 'dart:ui' as ui; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/keyboard/key_event_modifiers.dart'; +import 'package:pipelines_app/core/keyboard/key_modifier_sync.dart'; + +/// A key data as the web engine sends it. +ui.KeyData keyData( + ui.KeyEventType type, + PhysicalKeyboardKey physical, + LogicalKeyboardKey logical, { + bool synthesized = false, + String? character, +}) => ui.KeyData( + timeStamp: Duration.zero, + type: type, + physical: physical.usbHidUsage, + logical: logical.keyId, + character: character, + synthesized: synthesized, +); + +const _down = ui.KeyEventType.down; +const _up = ui.KeyEventType.up; +const _repeat = ui.KeyEventType.repeat; + +/// What one key data looks like in a forwarded list: `+key`, `-key`, `=key` +/// (repeat), with `*` for synthesized. +String describe(ui.KeyData data) { + final type = switch (data.type) { + ui.KeyEventType.down => '+', + ui.KeyEventType.up => '-', + ui.KeyEventType.repeat => '=', + }; + final name = PhysicalKeyboardKey(data.physical).debugName ?? '?'; + return '$type${data.synthesized ? '*' : ''}$name'; +} + +/// A sync over a record of what it forwards, with a fake keyboard state +/// kept as the framework would keep it. +class SyncHarness { + SyncHarness({TargetPlatform platform = TargetPlatform.linux}) { + sync = KeyModifierSync( + forward: (data) { + if (data.physical != 0) { + forwarded.add(describe(data)); + final key = PhysicalKeyboardKey(data.physical); + if (data.type == _up) { + pressed.remove(key); + } else { + pressed[key] = LogicalKeyboardKey(data.logical); + } + } + return false; + }, + modifiers: () => flags, + keyboard: _FakeKeyboard(pressed), + platform: () => platform, + ); + } + + late final KeyModifierSync sync; + final forwarded = []; + final pressed = {}; + KeyEventModifiers? flags; + + void send(ui.KeyData data, [KeyEventModifiers? flags]) { + this.flags = flags; + sync.handle(data); + } +} + +class _FakeKeyboard extends HardwareKeyboard { + _FakeKeyboard(this._pressed); + final Map _pressed; + + @override + Set get physicalKeysPressed => _pressed.keys.toSet(); + + @override + LogicalKeyboardKey? lookUpLayout(PhysicalKeyboardKey physicalKey) => + _pressed[physicalKey]; +} + +const _ctrl = KeyEventModifiers(control: true); +const _ctrlMeta = KeyEventModifiers(control: true, meta: true); +const _meta = KeyEventModifiers(meta: true); + +final _c = (PhysicalKeyboardKey.keyC, LogicalKeyboardKey.keyC); +final _metaLeft = (PhysicalKeyboardKey.metaLeft, LogicalKeyboardKey.metaLeft); +final _ctrlLeft = ( + PhysicalKeyboardKey.controlLeft, + LogicalKeyboardKey.controlLeft, +); + +ui.KeyData _key( + ui.KeyEventType type, + (PhysicalKeyboardKey, LogicalKeyboardKey) key, { + bool synthesized = false, +}) => keyData(type, key.$1, key.$2, synthesized: synthesized); + +void main() { + test('a physical Ctrl+C passes through untouched', () { + final h = SyncHarness(); + h.send(_key(_down, _ctrlLeft), _ctrl); + h.send(_key(_down, _c), _ctrl); + h.send(_key(_up, _c), _ctrl); + h.send(_key(_up, _ctrlLeft)); + expect(h.forwarded, ['+Control Left', '+Key C', '-Key C', '-Control Left']); + expect(h.sync.controlFromFlags, isFalse); + }); + + test("Omarchy's Super+C (Ctrl in the flags, no Ctrl key) presses Ctrl for " + 'the chord and releases it with the key', () { + final h = SyncHarness(); + h.send(_key(_down, _metaLeft), _meta); + // The engine releases Meta itself: the flags say it is up. + h.send(_key(_up, _metaLeft, synthesized: true), _ctrl); + h.send(_key(_down, _c), _ctrl); + expect(h.sync.controlFromFlags, isTrue); + h.send(_key(_repeat, _c), _ctrl); + h.send(_key(_up, _c), _ctrl); + expect(h.forwarded, [ + '+Meta Left', + '-*Meta Left', + '+*Control Left', + '+Key C', + '=Key C', + '-Key C', + '-*Control Left', + ]); + expect(h.pressed, isEmpty); + expect(h.sync.controlFromFlags, isFalse); + }); + + test('outside Apple platforms a held Super merged into Ctrl+C is let go ' + 'for the chord and pressed again after it', () { + final h = SyncHarness(); + h.send(_key(_down, _metaLeft), _meta); + h.send(_key(_down, _c), _ctrlMeta); + expect(h.pressed.keys, { + PhysicalKeyboardKey.controlLeft, + PhysicalKeyboardKey.keyC, + }); + h.send(_key(_up, _c), _ctrlMeta); + expect(h.pressed.keys, {PhysicalKeyboardKey.metaLeft}); + h.send(_key(_up, _metaLeft)); + expect(h.forwarded, [ + '+Meta Left', + '-*Meta Left', + '+*Control Left', + '+Key C', + '-Key C', + '-*Control Left', + '+*Meta Left', + '-Meta Left', + ]); + expect(h.pressed, isEmpty); + }); + + test('Super let go during the chord is not pressed again', () { + final h = SyncHarness(platform: TargetPlatform.windows); + h.send(_key(_down, _metaLeft), _meta); + h.send(_key(_down, _c), _ctrlMeta); + h.send(_key(_up, _metaLeft), _ctrl); + h.send(_key(_up, _c), _ctrl); + expect(h.pressed, isEmpty); + expect(h.forwarded.where((e) => e.contains('Meta')), [ + '+Meta Left', + '-*Meta Left', + ]); + }); + + test('on macOS Cmd stays part of a Ctrl+Cmd chord', () { + final h = SyncHarness(platform: TargetPlatform.macOS); + h.send(_key(_down, _metaLeft), _meta); + h.send(_key(_down, _c), _ctrlMeta); + expect(h.pressed.keys, contains(PhysicalKeyboardKey.metaLeft)); + expect(h.pressed.keys, contains(PhysicalKeyboardKey.controlLeft)); + }); + + test("a real Ctrl key takes over from the flags' Ctrl", () { + final h = SyncHarness(); + h.send(_key(_down, _c), _ctrl); + h.send(_key(_down, _ctrlLeft), _ctrl); + expect(h.forwarded, [ + '+*Control Left', + '+Key C', + '-*Control Left', + '+Control Left', + ]); + expect(h.sync.controlFromFlags, isFalse); + h.send(_key(_up, _c), _ctrl); + expect(h.pressed.keys, {PhysicalKeyboardKey.controlLeft}); + }); + + test('a key with no Ctrl in its flags releases a stale injected Ctrl', () { + final h = SyncHarness(); + h.send(_key(_down, _c), _ctrl); + final v = (PhysicalKeyboardKey.keyV, LogicalKeyboardKey.keyV); + h.send(_key(_down, v), const KeyEventModifiers()); + expect(h.pressed.keys, { + PhysicalKeyboardKey.keyC, + PhysicalKeyboardKey.keyV, + }); + }); + + test('unknown flags leave the event alone', () { + final h = SyncHarness(); + h.send(_key(_down, _c)); + expect(h.forwarded, ['+Key C']); + }); + + test('installs only on the web', () { + installKeyModifierSync(); + expect(KeyModifierSync.instance, kIsWeb ? isNotNull : isNull); + }); +} diff --git a/app/test/features/chat/conversation/chat_composer_injected_paste_test.dart b/app/test/features/chat/conversation/chat_composer_injected_paste_test.dart new file mode 100644 index 00000000..7bdf1abd --- /dev/null +++ b/app/test/features/chat/conversation/chat_composer_injected_paste_test.dart @@ -0,0 +1,94 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_composer_bar.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_composer_controller.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_draft_store.dart'; + +import '../../../core/keyboard/browser_keys.dart'; +import 'chat_composer_bar_fixtures.dart'; + +/// The desktop's universal paste key (Omarchy's Super+V sends Ctrl+V while +/// Super is held) pastes into the composer like Ctrl+V. +void main() { + late ComposerBarGateway gateway; + late ChatComposerController composer; + late int reads; + + setUp(() { + gateway = ComposerBarGateway(); + composer = ChatComposerController( + gateway, + 's', + drafts: MemoryChatDraftStore(), + ); + reads = 0; + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(SystemChannels.platform, (call) async { + if (call.method == 'Clipboard.getData') { + reads++; + return {'text': 'copied text'}; + } + if (call.method == 'Clipboard.hasStrings') return {'value': true}; + return null; + }); + }); + + tearDown(() { + composer.dispose(); + gateway.close(); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(SystemChannels.platform, null); + }); + + for (final merged in [false, true]) { + testWidgets( + 'Super+V (Ctrl${merged ? ' and Meta' : ''} in the flags) pastes into ' + 'the composer', + (tester) async { + final keys = BrowserKeys(tester); + await tester.pumpWidget( + materialHost(ChatComposerBar(composer: composer, running: false)), + ); + await tester.pumpAndSettle(); + await tester.showKeyboard(find.byKey(const Key('chat-composer-field'))); + await keys.superChord(LogicalKeyboardKey.keyV, mergedMeta: merged); + await tester.pumpAndSettle(); + expect(reads, 1); + expect(composer.draft, 'copied text'); + await tester.pumpWidget(const SizedBox()); + }, + variant: TargetPlatformVariant({ + TargetPlatform.linux, + TargetPlatform.windows, + }), + ); + } + + testWidgets( + 'Super+V, Super+A and Super+X work in any text field (question answers, ' + 'find bars)', + (tester) async { + final keys = BrowserKeys(tester); + final controller = TextEditingController(text: 'answer: '); + addTearDown(controller.dispose); + await tester.pumpWidget( + materialHost(TextField(controller: controller, autofocus: true)), + ); + await tester.pumpAndSettle(); + controller.selection = const TextSelection.collapsed(offset: 8); + await keys.superChord(LogicalKeyboardKey.keyV, mergedMeta: true); + await tester.pumpAndSettle(); + expect(controller.text, 'answer: copied text'); + await keys.superChord(LogicalKeyboardKey.keyA); + expect(controller.selection.textInside(controller.text), controller.text); + await keys.superChord(LogicalKeyboardKey.keyX); + await tester.pumpAndSettle(); + expect(controller.text, isEmpty); + }, + variant: TargetPlatformVariant({ + TargetPlatform.linux, + TargetPlatform.windows, + }), + ); +} diff --git a/app/test/features/chat/shell/chat_shell_terminal_clipboard_keys_test.dart b/app/test/features/chat/shell/chat_shell_terminal_clipboard_keys_test.dart new file mode 100644 index 00000000..e19ac620 --- /dev/null +++ b/app/test/features/chat/shell/chat_shell_terminal_clipboard_keys_test.dart @@ -0,0 +1,159 @@ +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/keyboard/key_event_modifiers.dart'; +import 'package:xterm/xterm.dart'; + +import '../../../core/keyboard/browser_keys.dart'; +import 'chat_shell_fixtures.dart'; + +/// The terminal's clipboard keys as the web app receives them: Ctrl+C +/// copies a selection (and sends no ^C) and interrupts without one; the +/// desktop's universal copy (Omarchy's Super+C, an injected Ctrl+C while +/// Super is held) only ever copies; its paste (Super+V) and Shift+Insert +/// paste. +void main() { + late ShellGateway gateway; + late List copied; + + setUp(() => gateway = ShellGateway()); + tearDown(() => gateway.close()); + + String typed() => [ + for (final body in gateway.bodies('chat_shell_input')) body['data'], + ].join(); + + Future open(WidgetTester tester) async { + copied = []; + final messenger = tester.binding.defaultBinaryMessenger; + messenger.setMockMethodCallHandler(SystemChannels.platform, (call) async { + switch (call.method) { + case 'Clipboard.setData': + copied.add('${(call.arguments as Map)['text']}'); + case 'Clipboard.getData': + return {'text': 'tok'}; + } + return null; + }); + addTearDown( + () => messenger.setMockMethodCallHandler(SystemChannels.platform, null), + ); + gateway.runs = [ + shellRecord( + 'run_t', + command: 'gh auth login', + terminal: true, + output: 'Paste your token: ', + ), + ]; + final keys = BrowserKeys(tester); + await tester.pumpWidget(shellThread(gateway)); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 500)); + await tester.pump(); + await tester.tap(find.byType(TerminalView)); + await tester.pump(); + return keys; + } + + TerminalController controller(WidgetTester tester) => + tester.widget(find.byType(TerminalView)).controller!; + + void select(WidgetTester tester, int length) { + final view = tester.widget(find.byType(TerminalView)); + final buffer = view.terminal.buffer; + view.controller!.setSelection( + buffer.createAnchor(0, 0), + buffer.createAnchor(length, 0), + ); + } + + Future settle(WidgetTester tester) async { + for (var i = 0; i < 5; i++) { + await tester.pump(const Duration(milliseconds: 20)); + } + } + + for (final merged in [false, true]) { + testWidgets( + 'Super+C (Ctrl${merged ? ' and Meta' : ''} in the flags) copies the ' + 'selection and never interrupts', + (tester) async { + final keys = await open(tester); + select(tester, 5); + await keys.superChord(LogicalKeyboardKey.keyC, mergedMeta: merged); + expect(copied, ['Paste']); + expect(controller(tester).selection, isNull); + // Nothing selected: the copy key does nothing, it sends no ^C. + await keys.superChord(LogicalKeyboardKey.keyC, mergedMeta: merged); + expect(copied, ['Paste']); + expect(typed(), isEmpty); + // Super+V pastes into the process. + await keys.superChord(LogicalKeyboardKey.keyV, mergedMeta: merged); + await settle(tester); + expect(typed(), 'tok'); + expect(HardwareKeyboard.instance.logicalKeysPressed, isEmpty); + await tester.pump(const Duration(milliseconds: 400)); + }, + variant: TargetPlatformVariant({ + TargetPlatform.linux, + TargetPlatform.windows, + }), + ); + } + + testWidgets( + 'Ctrl+C copies a selection without ^C and interrupts without one; ' + 'Ctrl+Insert copies, Shift+Insert and Ctrl+V paste', + (tester) async { + final keys = await open(tester); + const ctrl = KeyEventModifiers(control: true); + select(tester, 5); + await keys.chord(LogicalKeyboardKey.controlLeft, LogicalKeyboardKey.keyC); + expect(copied, ['Paste']); + expect(typed(), isEmpty); + expect(controller(tester).selection, isNull); + await keys.chord(LogicalKeyboardKey.controlLeft, LogicalKeyboardKey.keyC); + expect(typed(), '\x03'); + select(tester, 10); + await keys.chord( + LogicalKeyboardKey.controlLeft, + LogicalKeyboardKey.insert, + flags: ctrl, + ); + expect(copied, ['Paste', 'Paste your']); + await keys.chord( + LogicalKeyboardKey.shiftLeft, + LogicalKeyboardKey.insert, + flags: const KeyEventModifiers(shift: true), + ); + await settle(tester); + await keys.chord(LogicalKeyboardKey.controlLeft, LogicalKeyboardKey.keyV); + await settle(tester); + expect(typed(), '\x03toktok'); + await tester.pump(const Duration(milliseconds: 400)); + }, + variant: TargetPlatformVariant({ + TargetPlatform.linux, + TargetPlatform.windows, + }), + ); + + testWidgets( + 'on macOS Cmd+C copies and Ctrl+C interrupts', + (tester) async { + final keys = await open(tester); + select(tester, 5); + await keys.chord( + LogicalKeyboardKey.metaLeft, + LogicalKeyboardKey.keyC, + flags: const KeyEventModifiers(meta: true), + ); + expect(copied, ['Paste']); + select(tester, 5); + await keys.chord(LogicalKeyboardKey.controlLeft, LogicalKeyboardKey.keyC); + expect(typed(), '\x03'); + await tester.pump(const Duration(milliseconds: 400)); + }, + variant: TargetPlatformVariant.only(TargetPlatform.macOS), + ); +} diff --git a/app/test/features/chat/ui/transcript/chat_injected_clipboard_keys_test.dart b/app/test/features/chat/ui/transcript/chat_injected_clipboard_keys_test.dart new file mode 100644 index 00000000..f3ab5c10 --- /dev/null +++ b/app/test/features/chat/ui/transcript/chat_injected_clipboard_keys_test.dart @@ -0,0 +1,93 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/keyboard/key_event_modifiers.dart'; +import 'package:pipelines_app/features/chat/ui/transcript/chat_link_text.dart'; +import 'package:pipelines_app/features/chat/ui/transcript/chat_markdown_view.dart'; +import 'package:pipelines_app/features/chat/ui/transcript/chat_transcript_selection.dart'; + +import '../../../../core/keyboard/browser_keys.dart'; +import 'chat_transcript_selection_support.dart'; + +/// The desktop's universal copy key (Omarchy's Super+C sends Ctrl+C while +/// Super is held) copies the chat's selection like Ctrl+C (Cmd+C on a Mac), +/// whether the browser reports Ctrl alone or Ctrl and Meta for it. +void main() { + late List copied; + setUp(() { + ChatTranscriptSelectionArea.debugEnabled = true; + copied = recordTranscriptClipboard(); + }); + tearDown(() => ChatTranscriptSelectionArea.debugEnabled = null); + + Future selectAnswer(WidgetTester tester) async { + await tester.pumpWidget( + const MaterialApp( + home: Scaffold( + body: ChatTranscriptSelectionArea( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + ChatLinkText('Question 18'), + ChatMarkdownView(text: 'Answer 19 with `code`.'), + ], + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + final answer = tester.getRect(find.textContaining('Answer 19')); + await dragTranscriptSelection( + tester, + answer.centerLeft + const Offset(1, 0), + answer.centerRight - const Offset(1, 0), + ); + } + + bool apple() => + defaultTargetPlatform == TargetPlatform.macOS || + defaultTargetPlatform == TargetPlatform.iOS; + + for (final merged in [false, true]) { + testWidgets( + 'Super+C (Ctrl${merged ? ' and Meta' : ''} in the flags) copies the ' + 'selection', + (tester) async { + final keys = BrowserKeys(tester); + await selectAnswer(tester); + await keys.superChord(LogicalKeyboardKey.keyC, mergedMeta: merged); + // On a Mac, Ctrl+C (with or without Cmd) is not the copy key. + expect(copied, apple() ? isEmpty : ['Answer 19 with code.']); + }, + variant: TargetPlatformVariant.desktop(), + ); + } + + testWidgets( + 'the keyboard copy keys copy through the browser key path', + (tester) async { + final keys = BrowserKeys(tester); + await selectAnswer(tester); + if (apple()) { + await keys.chord( + LogicalKeyboardKey.metaLeft, + LogicalKeyboardKey.keyC, + flags: const KeyEventModifiers(meta: true), + ); + expect(copied, ['Answer 19 with code.']); + return; + } + await keys.chord(LogicalKeyboardKey.controlLeft, LogicalKeyboardKey.keyC); + await keys.chord( + LogicalKeyboardKey.controlLeft, + LogicalKeyboardKey.insert, + ); + expect(copied, ['Answer 19 with code.', 'Answer 19 with code.']); + // A Ctrl the flags pressed is released with its chord. + expect(HardwareKeyboard.instance.isControlPressed, isFalse); + }, + variant: TargetPlatformVariant.desktop(), + ); +} diff --git a/app/tool/capture/README.md b/app/tool/capture/README.md index aa44c898..1b764ba1 100644 --- a/app/tool/capture/README.md +++ b/app/tool/capture/README.md @@ -72,6 +72,8 @@ In JSON, a step can also set `wait` (ms), `timeout`, `name`, `ms` and `frames`. | `labels=name` | write the visible semantics labels, keys and rects to JSON | | `film=` | screencast a click for `--film-ms` (900) and write the frames plus a contact sheet; `film=press:Alt+t` films a key chord (as `press=`) instead | | `wait=ms` | sleep | +| `keys=[...]` | raw key events (JSON `Input.dispatchKeyEvent` params, each with an optional `after` ms), e.g. modifier flags without their key events as a compositor's injected shortcut sends them (`examples/clipboard-*.json`) | +| `grant=clipboard` | let the page read and write the clipboard (`navigator.clipboard` in `eval`) | | `files=a.ttf[,b.ttf]` | answer the next file chooser the page opens with these files (paths relative to the working directory); put it before the click that opens the picker | | `swipe=>dx,dy` | one-finger touch swipe (needs `--touch true`, which emulates a touch screen once semantics is on) | | `pinch=>scale` | two-finger touch pinch, spreading (>1) or closing (<1) (needs `--touch true`) | diff --git a/app/tool/capture/browser.mjs b/app/tool/capture/browser.mjs index 90c5f106..66572e3d 100644 --- a/app/tool/capture/browser.mjs +++ b/app/tool/capture/browser.mjs @@ -93,6 +93,8 @@ export async function openBrowser({ cdp, gpu = false, chromePath = process.env.C } catch (error) { ws.close(); await cleanup(); throw error; } return { send: (method, params) => raw(method, params, sessionId), + /** A browser-level call (no page session), e.g. `Browser.grantPermissions`. */ + sendBrowser: (method, params) => raw(method, params), on: (method, fn) => { listeners.set(method, [...(listeners.get(method) ?? []), fn]); return () => listeners.set(method, listeners.get(method).filter((f) => f !== fn)); diff --git a/app/tool/capture/capture.mjs b/app/tool/capture/capture.mjs index 4f2451df..7597d534 100644 --- a/app/tool/capture/capture.mjs +++ b/app/tool/capture/capture.mjs @@ -27,6 +27,7 @@ steps: open=[@WxH] wait= shot= click= waitfor= press= scroll= size=WxH files=[,] (answers the next file chooser) film= labels= tabs= eval= expect= hover= + keys= grant=clipboard rightclick= (secondary button: context menus) drag=>, (JSON: drag, dx, dy, steps, gap, hold) swipe=>, pinch=> (with --touch true) @@ -127,6 +128,24 @@ try { case 'type': await page.type(String(value)); await delay(step.wait ?? settle); break; case 'compose': await page.compose(String(value)); await delay(step.wait ?? settle); break; case 'press': await page.press(String(value)); await delay(step.wait ?? settle); break; + case 'keys': { + // Raw key events (Input.dispatchKeyEvent params), each optionally + // `after` ms after the previous: modifier flags without their key + // events, as a compositor's injected shortcut sends them. + for (const { after = 0, ...event } of Array.isArray(value) ? value : JSON.parse(String(value))) { + if (after) await delay(after); + await browser.send('Input.dispatchKeyEvent', event); + } + await delay(step.wait ?? settle); + break; + } + case 'grant': { + // `grant=clipboard` lets the page read and write the clipboard. + const origin = new URL(await page.evaluate('location.href')).origin; + const permissions = value === 'clipboard' ? ['clipboardReadWrite', 'clipboardSanitizedWrite'] : String(value).split(','); + await browser.sendBrowser('Browser.grantPermissions', { origin, permissions }); + break; + } case 'scroll': { const at = await page.scroll(Number(value), step.at, { dx: Number(step.dx ?? 0), repeat: Number(step.repeat ?? 1), gap: Number(step.gap ?? 16) }); log(` wheel at ${Math.round(at.x)},${Math.round(at.y)}`); diff --git a/app/tool/capture/examples/clipboard-copy-refused.json b/app/tool/capture/examples/clipboard-copy-refused.json new file mode 100644 index 00000000..2099873b --- /dev/null +++ b/app/tool/capture/examples/clipboard-copy-refused.json @@ -0,0 +1,70 @@ +{ + "params": "chats=2", + "steps": [ + { + "open": "/chat/perf-chat-0@1000x800" + }, + { + "wait": 1500 + }, + { + "grant": "clipboard" + }, + { + "eval": "(window.__writes=[], navigator.clipboard.writeText = (t) => { window.__writes.push(t); return Promise.reject(new DOMException('Write permission denied.', 'NotAllowedError')); }, 'clipboard writes now rejected')" + }, + { + "drag": "484,267", + "dx": 110, + "dy": 0 + }, + { + "keys": [ + { + "type": "rawKeyDown", + "key": "Meta", + "code": "MetaLeft", + "modifiers": 4, + "windowsVirtualKeyCode": 91 + }, + { + "type": "rawKeyDown", + "key": "c", + "code": "KeyC", + "modifiers": 2, + "windowsVirtualKeyCode": 67, + "after": 30 + }, + { + "type": "keyUp", + "key": "c", + "code": "KeyC", + "modifiers": 2, + "windowsVirtualKeyCode": 67, + "after": 50 + }, + { + "type": "keyUp", + "key": "Meta", + "code": "MetaLeft", + "modifiers": 0, + "windowsVirtualKeyCode": 91, + "after": 100 + } + ], + "wait": 800 + }, + { + "shot": "c2-copy-refused-message" + }, + { + "eval": "JSON.stringify(window.__writes)" + }, + { + "wait": 1000 + }, + { + "shot": "c3-later" + } + ] +} \ No newline at end of file diff --git a/app/tool/capture/examples/clipboard-super-c-chat.json b/app/tool/capture/examples/clipboard-super-c-chat.json new file mode 100644 index 00000000..814c4928 --- /dev/null +++ b/app/tool/capture/examples/clipboard-super-c-chat.json @@ -0,0 +1,224 @@ +{ + "params": "chats=2", + "steps": [ + { + "open": "/chat/perf-chat-0@1000x800" + }, + { + "wait": 1500 + }, + { + "grant": "clipboard" + }, + { + "eval": "navigator.clipboard.writeText('SENTINEL').then(()=>'reset')" + }, + { + "drag": "484,267", + "dx": 110, + "dy": 0 + }, + { + "shot": "physical-ctrl-c-selected" + }, + { + "keys": [ + { + "type": "rawKeyDown", + "key": "Control", + "code": "ControlLeft", + "modifiers": 2, + "windowsVirtualKeyCode": 17 + }, + { + "type": "rawKeyDown", + "key": "c", + "code": "KeyC", + "modifiers": 2, + "windowsVirtualKeyCode": 67 + }, + { + "type": "keyUp", + "key": "c", + "code": "KeyC", + "modifiers": 2, + "windowsVirtualKeyCode": 67 + }, + { + "type": "keyUp", + "key": "Control", + "code": "ControlLeft", + "modifiers": 0, + "windowsVirtualKeyCode": 17 + } + ], + "wait": 600 + }, + { + "eval": "navigator.clipboard.readText().then(t=>'physical-ctrl-c: '+JSON.stringify(t))", + "name": "physical-ctrl-c" + }, + { + "click": "700,200" + }, + { + "eval": "navigator.clipboard.writeText('SENTINEL').then(()=>'reset')" + }, + { + "drag": "484,267", + "dx": 110, + "dy": 0 + }, + { + "shot": "omarchy-super-c-ctrl-only-selected" + }, + { + "keys": [ + { + "type": "rawKeyDown", + "key": "Meta", + "code": "MetaLeft", + "modifiers": 4, + "windowsVirtualKeyCode": 91 + }, + { + "type": "rawKeyDown", + "key": "c", + "code": "KeyC", + "modifiers": 2, + "windowsVirtualKeyCode": 67, + "after": 30 + }, + { + "type": "keyUp", + "key": "c", + "code": "KeyC", + "modifiers": 2, + "windowsVirtualKeyCode": 67, + "after": 50 + }, + { + "type": "keyUp", + "key": "Meta", + "code": "MetaLeft", + "modifiers": 0, + "windowsVirtualKeyCode": 91, + "after": 100 + } + ], + "wait": 600 + }, + { + "eval": "navigator.clipboard.readText().then(t=>'omarchy-super-c-ctrl-only: '+JSON.stringify(t))", + "name": "omarchy-super-c-ctrl-only" + }, + { + "click": "700,200" + }, + { + "eval": "navigator.clipboard.writeText('SENTINEL').then(()=>'reset')" + }, + { + "drag": "484,267", + "dx": 110, + "dy": 0 + }, + { + "shot": "omarchy-super-c-ctrl-meta-selected" + }, + { + "keys": [ + { + "type": "rawKeyDown", + "key": "Meta", + "code": "MetaLeft", + "modifiers": 4, + "windowsVirtualKeyCode": 91 + }, + { + "type": "rawKeyDown", + "key": "c", + "code": "KeyC", + "modifiers": 6, + "windowsVirtualKeyCode": 67, + "after": 30 + }, + { + "type": "keyUp", + "key": "c", + "code": "KeyC", + "modifiers": 6, + "windowsVirtualKeyCode": 67, + "after": 50 + }, + { + "type": "keyUp", + "key": "Meta", + "code": "MetaLeft", + "modifiers": 0, + "windowsVirtualKeyCode": 91, + "after": 100 + } + ], + "wait": 600 + }, + { + "eval": "navigator.clipboard.readText().then(t=>'omarchy-super-c-ctrl-meta: '+JSON.stringify(t))", + "name": "omarchy-super-c-ctrl-meta" + }, + { + "click": "700,200" + }, + { + "eval": "navigator.clipboard.writeText('SENTINEL').then(()=>'reset')" + }, + { + "drag": "484,267", + "dx": 110, + "dy": 0 + }, + { + "shot": "ctrl-insert-selected" + }, + { + "keys": [ + { + "type": "rawKeyDown", + "key": "Control", + "code": "ControlLeft", + "modifiers": 2, + "windowsVirtualKeyCode": 17 + }, + { + "type": "rawKeyDown", + "key": "Insert", + "code": "Insert", + "modifiers": 2, + "windowsVirtualKeyCode": 45 + }, + { + "type": "keyUp", + "key": "Insert", + "code": "Insert", + "modifiers": 2, + "windowsVirtualKeyCode": 45 + }, + { + "type": "keyUp", + "key": "Control", + "code": "ControlLeft", + "modifiers": 0, + "windowsVirtualKeyCode": 17 + } + ], + "wait": 600 + }, + { + "eval": "navigator.clipboard.readText().then(t=>'ctrl-insert: '+JSON.stringify(t))", + "name": "ctrl-insert" + }, + { + "click": "700,200" + } + ] +} \ No newline at end of file diff --git a/app/tool/capture/examples/clipboard-super-c-terminal.json b/app/tool/capture/examples/clipboard-super-c-terminal.json new file mode 100644 index 00000000..3f0e7564 --- /dev/null +++ b/app/tool/capture/examples/clipboard-super-c-terminal.json @@ -0,0 +1,234 @@ +{ + "params": "chats=2&terminals=1&terminal=panel", + "steps": [ + { + "open": "/chat/perf-chat-0@1000x800" + }, + { + "wait": 2000 + }, + { + "grant": "clipboard" + }, + { + "eval": "navigator.clipboard.writeText('SENTINEL').then(()=>'reset')" + }, + { + "click": "500,720" + }, + { + "drag": "96,570", + "dx": 200, + "dy": 0 + }, + { + "shot": "t1-selected" + }, + { + "keys": [ + { + "type": "rawKeyDown", + "key": "Meta", + "code": "MetaLeft", + "modifiers": 4, + "windowsVirtualKeyCode": 91 + }, + { + "type": "rawKeyDown", + "key": "c", + "code": "KeyC", + "modifiers": 2, + "windowsVirtualKeyCode": 67, + "after": 30 + }, + { + "type": "keyUp", + "key": "c", + "code": "KeyC", + "modifiers": 2, + "windowsVirtualKeyCode": 67, + "after": 50 + }, + { + "type": "keyUp", + "key": "Meta", + "code": "MetaLeft", + "modifiers": 0, + "windowsVirtualKeyCode": 91, + "after": 100 + } + ], + "wait": 600 + }, + { + "eval": "navigator.clipboard.readText().then(t=>'t-super-c-selection: '+JSON.stringify(t))" + }, + { + "shot": "t2-after-super-c" + }, + { + "keys": [ + { + "type": "rawKeyDown", + "key": "Meta", + "code": "MetaLeft", + "modifiers": 4, + "windowsVirtualKeyCode": 91 + }, + { + "type": "rawKeyDown", + "key": "c", + "code": "KeyC", + "modifiers": 2, + "windowsVirtualKeyCode": 67, + "after": 30 + }, + { + "type": "keyUp", + "key": "c", + "code": "KeyC", + "modifiers": 2, + "windowsVirtualKeyCode": 67, + "after": 50 + }, + { + "type": "keyUp", + "key": "Meta", + "code": "MetaLeft", + "modifiers": 0, + "windowsVirtualKeyCode": 91, + "after": 100 + } + ], + "wait": 600 + }, + { + "eval": "navigator.clipboard.readText().then(t=>'t-super-c-no-selection: '+JSON.stringify(t))" + }, + { + "shot": "t3-super-c-nothing-selected" + }, + { + "keys": [ + { + "type": "rawKeyDown", + "key": "Meta", + "code": "MetaLeft", + "modifiers": 4, + "windowsVirtualKeyCode": 91 + }, + { + "type": "rawKeyDown", + "key": "v", + "code": "KeyV", + "modifiers": 2, + "windowsVirtualKeyCode": 86, + "after": 30 + }, + { + "type": "keyUp", + "key": "v", + "code": "KeyV", + "modifiers": 2, + "windowsVirtualKeyCode": 86, + "after": 50 + }, + { + "type": "keyUp", + "key": "Meta", + "code": "MetaLeft", + "modifiers": 0, + "windowsVirtualKeyCode": 91, + "after": 100 + } + ], + "wait": 800 + }, + { + "shot": "t4-super-v-pasted" + }, + { + "drag": "96,585", + "dx": 200, + "dy": 0 + }, + { + "keys": [ + { + "type": "rawKeyDown", + "key": "Meta", + "code": "MetaLeft", + "modifiers": 4, + "windowsVirtualKeyCode": 91 + }, + { + "type": "rawKeyDown", + "key": "c", + "code": "KeyC", + "modifiers": 6, + "windowsVirtualKeyCode": 67, + "after": 30 + }, + { + "type": "keyUp", + "key": "c", + "code": "KeyC", + "modifiers": 6, + "windowsVirtualKeyCode": 67, + "after": 50 + }, + { + "type": "keyUp", + "key": "Meta", + "code": "MetaLeft", + "modifiers": 0, + "windowsVirtualKeyCode": 91, + "after": 100 + } + ], + "wait": 600 + }, + { + "eval": "navigator.clipboard.readText().then(t=>'t-super-c-merged-meta: '+JSON.stringify(t))" + }, + { + "shot": "t5-after-merged" + }, + { + "keys": [ + { + "type": "rawKeyDown", + "key": "Control", + "code": "ControlLeft", + "modifiers": 2, + "windowsVirtualKeyCode": 17 + }, + { + "type": "rawKeyDown", + "key": "c", + "code": "KeyC", + "modifiers": 2, + "windowsVirtualKeyCode": 67 + }, + { + "type": "keyUp", + "key": "c", + "code": "KeyC", + "modifiers": 2, + "windowsVirtualKeyCode": 67 + }, + { + "type": "keyUp", + "key": "Control", + "code": "ControlLeft", + "modifiers": 0, + "windowsVirtualKeyCode": 17 + } + ], + "wait": 600 + }, + { + "shot": "t6-ctrl-c-no-selection-interrupts" + } + ] +} \ No newline at end of file diff --git a/app/tool/capture/examples/clipboard-super-v-composer.json b/app/tool/capture/examples/clipboard-super-v-composer.json new file mode 100644 index 00000000..78c9ea10 --- /dev/null +++ b/app/tool/capture/examples/clipboard-super-v-composer.json @@ -0,0 +1,59 @@ +{ + "params": "chats=2", + "steps": [ + { + "open": "/chat/perf-chat-0@1000x800" + }, + { + "wait": 1500 + }, + { + "grant": "clipboard" + }, + { + "eval": "navigator.clipboard.writeText('pasted via Super+V').then(()=>'set')" + }, + { + "click": "700,747" + }, + { + "keys": [ + { + "type": "rawKeyDown", + "key": "Meta", + "code": "MetaLeft", + "modifiers": 4, + "windowsVirtualKeyCode": 91 + }, + { + "type": "rawKeyDown", + "key": "v", + "code": "KeyV", + "modifiers": 2, + "windowsVirtualKeyCode": 86, + "after": 30 + }, + { + "type": "keyUp", + "key": "v", + "code": "KeyV", + "modifiers": 2, + "windowsVirtualKeyCode": 86, + "after": 50 + }, + { + "type": "keyUp", + "key": "Meta", + "code": "MetaLeft", + "modifiers": 0, + "windowsVirtualKeyCode": 91, + "after": 100 + } + ], + "wait": 800 + }, + { + "shot": "c1-composer-super-v" + } + ] +} \ No newline at end of file diff --git a/app/tool/perf/terminal_fixture.dart b/app/tool/perf/terminal_fixture.dart index 590050d1..ed9dbf5d 100644 --- a/app/tool/perf/terminal_fixture.dart +++ b/app/tool/perf/terminal_fixture.dart @@ -232,7 +232,11 @@ List terminalFixtureFollowUps(JsonMap request) { if (!_terminals.containsKey(terminal)) return const []; final data = '${body['data'] ?? ''}'; final folder = terminal == 'term_build' ? '~/src/pipelines' : '~'; - final echo = data.replaceAll('\r', '\r\n${_promptAt(folder)}'); + // Ctrl-C echoes as a terminal with echoctl shows it, so an interrupt + // is visible in captures. + final echo = data + .replaceAll('\r', '\r\n${_promptAt(folder)}') + .replaceAll('\x03', '^C\r\n${_promptAt(folder)}'); final offset = utf8.encode(_output[terminal]!).length; _output[terminal] = _output[terminal]! + echo; return [ diff --git a/app/tool/search_selection_probe_entry.dart b/app/tool/search_selection_probe_entry.dart index 2e2f9707..b87096ac 100644 --- a/app/tool/search_selection_probe_entry.dart +++ b/app/tool/search_selection_probe_entry.dart @@ -1,3 +1,4 @@ +import 'package:pipelines_app/application/pipelines_binding.dart'; import 'package:pipelines_app/core/servers/chat/chat_server_pool.dart'; import 'package:pipelines_app/core/servers/machine_access.dart'; import 'package:pipelines_app/core/servers/server_catalog.dart'; @@ -197,6 +198,7 @@ void _installUiReviewChats() { 'closed_at': null, }; } + const List _turnFileNames = [ 'input.md', 'memory.md', @@ -901,7 +903,7 @@ class _FixtureSink implements WebSocketSink { /// /// app/tool/capture/ drives this entry generically; see its README. Future main() async { - WidgetsFlutterBinding.ensureInitialized(); + PipelinesBinding.ensureInitialized(); await Future.wait([ QuickSwitchAnimationController.instance.restore(), AnimationSpeedController.instance.restore(), diff --git a/internal/server/terminal_login.go b/internal/server/terminal_login.go index 07d5b4a4..0ee140eb 100644 --- a/internal/server/terminal_login.go +++ b/internal/server/terminal_login.go @@ -117,6 +117,28 @@ func terminalLoginCommand(dir string) (*exec.Cmd, error) { return cmd, nil } +// terminalLoginInput is input typed before the login completes. At su's +// password prompt the terminal's signal keys would end su, and the terminal +// with it (Ctrl-C there is a habit, not a request to close the tab): Ctrl-C +// and Ctrl-\ erase the line typed so far instead (Ctrl-U, the kill +// character), and Ctrl-Z, which would stop su, is dropped. +func terminalLoginInput(data []byte) []byte { + if bytes.IndexAny(data, "\x03\x1c\x1a") < 0 { + return data + } + out := make([]byte, 0, len(data)) + for _, b := range data { + switch b { + case 0x03, 0x1c: + out = append(out, 0x15) + case 0x1a: + default: + out = append(out, b) + } + } + return out +} + // terminalLoginWatch follows a terminal's output until its login completes. type terminalLoginWatch struct { seen []byte diff --git a/internal/server/terminal_login_test.go b/internal/server/terminal_login_test.go index 878fdf5a..322adaa7 100644 --- a/internal/server/terminal_login_test.go +++ b/internal/server/terminal_login_test.go @@ -234,3 +234,45 @@ func TestTerminalRefusesUnpromptedLogin(t *testing.T) { t.Fatalf("%d refused terminals still running", running) } } + +// Ctrl-C (or Ctrl-\, Ctrl-Z) at the password prompt does not end su and +// the terminal with it: it erases what was typed, so the password typed +// after it logs in. +func TestTerminalCtrlCAtLoginPromptKeepsTheTerminal(t *testing.T) { + terminalHome(t) + m, _ := newTestTerminals(t, newOperatorStore(t)) + record, err := m.Open(context.Background(), "", "", 0, 0, false) + if err != nil { + t.Fatal(err) + } + if err := m.Input(record.ID, "typo\x03"); err != nil { + t.Fatal(err) + } + if err := m.Input(record.ID, "more\x1c\x1a"); err != nil { + t.Fatal(err) + } + time.Sleep(200 * time.Millisecond) + if p := m.process(record.ID); p == nil || !p.running() { + t.Fatal("Ctrl-C at the login prompt ended the terminal") + } + if err := m.Input(record.ID, fakeSuPassword+"\r"); err != nil { + t.Fatal(err) + } + if err := m.Input(record.ID, "echo in-$((6*7))\r"); err != nil { + t.Fatal(err) + } + waitTerminalOutput(t, m, record.ID, "in-42") +} + +func TestTerminalLoginInput(t *testing.T) { + for in, want := range map[string]string{ + "secret\r": "secret\r", + "ab\x03cd": "ab\x15cd", + "\x1c\x1aok": "\x15ok", + "": "", + } { + if got := string(terminalLoginInput([]byte(in))); got != want { + t.Errorf("terminalLoginInput(%q) = %q, want %q", in, got, want) + } + } +} diff --git a/internal/server/terminal_process.go b/internal/server/terminal_process.go index f524e125..8983912d 100644 --- a/internal/server/terminal_process.go +++ b/internal/server/terminal_process.go @@ -193,8 +193,11 @@ func (p *terminalProcess) pumpInput() { case data := <-p.input: p.mu.Lock() terminal := p.pty + if !p.login.loggedIn { + data = terminalLoginInput(data) + } p.mu.Unlock() - if terminal != nil { + if terminal != nil && len(data) > 0 { _, _ = terminal.Write(data) } }