From 2332143e5bc2880b4528bdb5263ae1bcccab1ab7 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Mon, 9 Nov 2026 20:51:59 +0000 Subject: [PATCH] Fit chat terminals to their output, keep pastes and keys in the terminal Finished terminals are sized synchronously from their rows at the view's width (the post-frame fit made the transcript re-anchor forever); blank rows xterm.dart keeps when rewrapping are dropped; desktop typing uses key events; the composer leaves Cmd/Ctrl-V to a focused terminal; Ctrl-A reaches the process. The probe fixture gains coloured terminal runs and an interactive login. Notes record behaviour, protocol, security and verification. --- .../chat_composer_paste_focus.dart | 8 + .../chat/shell/chat_shell_terminal_keys.dart | 8 +- .../shell/chat_shell_terminal_session.dart | 39 ++++ .../chat/shell/chat_shell_terminal_theme.dart | 25 +-- .../chat/shell/chat_shell_terminal_view.dart | 82 ++++++--- app/notes/chat-interactive-terminal.md | 170 ++++++++++++++++++ .../chat_shell_terminal_session_test.dart | 27 +++ .../chat/shell/chat_shell_terminal_test.dart | 26 ++- app/tool/perf/chat_shell_fixture.dart | 85 +++++++-- internal/server/chat_shell_runner_test.go | 11 +- 10 files changed, 429 insertions(+), 52 deletions(-) create mode 100644 app/notes/chat-interactive-terminal.md diff --git a/app/lib/features/chat/conversation/chat_composer_paste_focus.dart b/app/lib/features/chat/conversation/chat_composer_paste_focus.dart index e9b9e168..b28cb991 100644 --- a/app/lib/features/chat/conversation/chat_composer_paste_focus.dart +++ b/app/lib/features/chat/conversation/chat_composer_paste_focus.dart @@ -5,14 +5,22 @@ import 'package:flutter/widgets.dart'; abstract final class ChatComposerPasteFocus { static final Set _composers = {}; + static final Set _inputs = {}; + static void register(FocusNode focus) => _composers.add(focus); static void unregister(FocusNode focus) => _composers.remove(focus); + /// An input that is not an [EditableText] (a shell command's terminal) + /// registers its focus here: a paste while it has focus is its own. + static void registerInput(FocusNode focus) => _inputs.add(focus); + static void unregisterInput(FocusNode focus) => _inputs.remove(focus); + static bool get anotherEditableHasFocus { final primary = FocusManager.instance.primaryFocus; if (primary == null || _composers.any((focus) => focus.hasFocus)) { return false; } + if (_inputs.any((focus) => focus.hasFocus)) return true; final context = primary.context; if (context == null) return false; var editable = context.widget is EditableText; diff --git a/app/lib/features/chat/shell/chat_shell_terminal_keys.dart b/app/lib/features/chat/shell/chat_shell_terminal_keys.dart index 077a7470..00e48cf9 100644 --- a/app/lib/features/chat/shell/chat_shell_terminal_keys.dart +++ b/app/lib/features/chat/shell/chat_shell_terminal_keys.dart @@ -217,10 +217,16 @@ class _ChatShellTerminalKeysState extends State { ); } if (material == null) { - return OutlinedButton(key: key, onPressed: onPressed, child: Text(label)); + return OutlinedButton( + key: key, + style: OutlinedButton.styleFrom(visualDensity: VisualDensity.compact), + onPressed: onPressed, + child: Text(label), + ); } return IconButton.outlined( key: key, + visualDensity: VisualDensity.compact, tooltip: label, onPressed: onPressed, icon: Icon(material), diff --git a/app/lib/features/chat/shell/chat_shell_terminal_session.dart b/app/lib/features/chat/shell/chat_shell_terminal_session.dart index aacec792..01b5103e 100644 --- a/app/lib/features/chat/shell/chat_shell_terminal_session.dart +++ b/app/lib/features/chat/shell/chat_shell_terminal_session.dart @@ -89,6 +89,29 @@ class ChatShellTerminalSession { terminal.setCursorVisibleMode(false); } + /// The rows the drawn output takes, through the cursor's line, when the + /// terminal is [cols] wide: a finished run's box is sized by it before the + /// view lays the terminal out, so a card never changes height after it. + int rowsAt(int cols) { + final buffer = terminal.buffer; + final last = buffer.absoluteCursorY.clamp(0, buffer.height - 1); + var rows = 0; + var length = 0; + void close() => rows += length <= 0 ? 1 : (length + cols - 1) ~/ cols; + for (var y = 0; y <= last; y++) { + final line = buffer.lines[y]; + if (y > 0 && !line.isWrapped) { + close(); + length = 0; + } + // A row the next one continues is full to the terminal's width. + final continued = y + 1 < buffer.height && buffer.lines[y + 1].isWrapped; + length += continued ? line.length : line.getTrimmedLength(); + } + close(); + return rows; + } + void _output(String data) { if (_live && !_replaying) onInput(data); } @@ -109,4 +132,20 @@ class _ChatShellTerminal extends Terminal { void sendCursorPosition() { onOutput?.call('\x1b[${buffer.cursorY + 1};${buffer.cursorX + 1}R'); } + + /// Narrowing rewraps long lines, and xterm.dart 4.0.0 keeps every blank + /// row below the cursor while doing so: the extra rows push the top of + /// the output into scrollback. Blank rows below the cursor are dropped + /// instead, keeping the cursor on its line. + @override + void resize(int width, int height, [int? pixelWidth, int? pixelHeight]) { + super.resize(width, height, pixelWidth, pixelHeight); + final lines = buffer.lines; + while (buffer.height > viewHeight && + buffer.height - 1 > buffer.absoluteCursorY && + lines[buffer.height - 1].getText().trim().isEmpty) { + lines.pop(); + buffer.setCursor(buffer.cursorX, buffer.cursorY + 1); + } + } } diff --git a/app/lib/features/chat/shell/chat_shell_terminal_theme.dart b/app/lib/features/chat/shell/chat_shell_terminal_theme.dart index 88809c31..e025f1c6 100644 --- a/app/lib/features/chat/shell/chat_shell_terminal_theme.dart +++ b/app/lib/features/chat/shell/chat_shell_terminal_theme.dart @@ -1,3 +1,5 @@ +import 'dart:ui' as ui; + import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:xterm/xterm.dart'; @@ -71,15 +73,16 @@ TerminalStyle chatShellTerminalStyle(BuildContext context, bool cupertino) { ); } -/// The height of one terminal row in [style] at the context's text scale, -/// measured the way the emulator measures its cells. -double chatShellTerminalLineHeight(BuildContext context, TerminalStyle style) { - final painter = TextPainter( - text: TextSpan(text: 'mmmmmmmmmm', style: style.toTextStyle()), - textDirection: TextDirection.ltr, - textScaler: MediaQuery.textScalerOf(context), - )..layout(); - final height = painter.height; - painter.dispose(); - return height; +/// The size of one terminal cell in [style] at the context's text scale, +/// measured exactly as the emulator measures it. +Size chatShellTerminalCellSize(BuildContext context, TerminalStyle style) { + final text = style.toTextStyle(); + final builder = ui.ParagraphBuilder(text.getParagraphStyle()) + ..pushStyle(text.getTextStyle(textScaler: MediaQuery.textScalerOf(context))) + ..addText('mmmmmmmmmm'); + final paragraph = builder.build() + ..layout(const ui.ParagraphConstraints(width: double.infinity)); + final size = Size(paragraph.maxIntrinsicWidth / 10, paragraph.height); + paragraph.dispose(); + return size; } 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 a99c2177..d4e66117 100644 --- a/app/lib/features/chat/shell/chat_shell_terminal_view.dart +++ b/app/lib/features/chat/shell/chat_shell_terminal_view.dart @@ -1,19 +1,48 @@ import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; import 'package:xterm/xterm.dart'; +import '../conversation/chat_composer_paste_focus.dart'; import '../ui/transcript/chat_link_launcher.dart'; import 'chat_shell_metrics.dart'; import 'chat_shell_terminal_links.dart'; import 'chat_shell_terminal_session.dart'; import 'chat_shell_terminal_theme.dart'; -/// Whether the soft keyboard is the main way to type here, so the terminal -/// takes typing from the key toolbar's field rather than its own hidden one. +/// Whether the soft keyboard is the main way to type here, so the key +/// toolbar offers a text field: the terminal itself takes hardware keys only. bool chatShellTouchFirst() => defaultTargetPlatform == TargetPlatform.android || 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 copies, so every other Ctrl key, Ctrl-A and Ctrl-C +/// included, reaches the process. +Map chatShellTerminalShortcuts() { + const paste = PasteTextIntent(SelectionChangedCause.keyboard); + final apple = + defaultTargetPlatform == TargetPlatform.macOS || + defaultTargetPlatform == TargetPlatform.iOS; + if (apple) { + return const { + SingleActivator(LogicalKeyboardKey.keyC, meta: true): + CopySelectionTextIntent.copy, + SingleActivator(LogicalKeyboardKey.keyV, meta: true): paste, + SingleActivator(LogicalKeyboardKey.keyA, meta: true): SelectAllTextIntent( + SelectionChangedCause.keyboard, + ), + }; + } + return const { + SingleActivator(LogicalKeyboardKey.keyC, control: true, shift: true): + CopySelectionTextIntent.copy, + SingleActivator(LogicalKeyboardKey.keyV, control: true): paste, + SingleActivator(LogicalKeyboardKey.keyV, control: true, shift: true): paste, + }; +} + /// One run's terminal emulator view. In a card it is bounded to /// [kChatShellOutputCollapsedLines] rows (a finished run shrinks to its /// output); with [fill] it takes the space its parent gives (full screen). @@ -44,10 +73,18 @@ class ChatShellTerminalView extends StatefulWidget { class _ChatShellTerminalViewState extends State { final TerminalController _controller = TerminalController(); final FocusNode _focus = FocusNode(debugLabel: 'chat-shell-terminal'); - int? _fitRows; + + @override + void initState() { + super.initState(); + // A paste while the terminal has focus goes to the process, not to the + // chat composer. + ChatComposerPasteFocus.registerInput(_focus); + } @override void dispose() { + ChatComposerPasteFocus.unregisterInput(_focus); _controller.dispose(); _focus.dispose(); super.dispose(); @@ -58,14 +95,6 @@ class _ChatShellTerminalViewState extends State { if (uri != null) openChatLink(context, uri); } - /// A finished run's box shrinks to the rows its output uses. - void _fit() { - if (!mounted || widget.fill || widget.session.live) return; - final used = widget.session.terminal.buffer.absoluteCursorY + 1; - final rows = used.clamp(1, kChatShellOutputCollapsedLines); - if (rows != _fitRows) setState(() => _fitRows = rows); - } - @override Widget build(BuildContext context) { final session = widget.session; @@ -85,8 +114,11 @@ class _ChatShellTerminalViewState extends State { textStyle: style, padding: padding, readOnly: !live, - hardwareKeyboardOnly: !live || chatShellTouchFirst(), - keyboardType: TextInputType.visiblePassword, + // Keys go straight to the process as key events (a focused text + // input would stay closed on the web); touch typing goes through the + // key toolbar's field instead. + hardwareKeyboardOnly: true, + shortcuts: chatShellTerminalShortcuts(), cursorType: TerminalCursorType.block, onTapUp: _tapped, ), @@ -102,12 +134,22 @@ class _ChatShellTerminalViewState extends State { ); view = ClipRRect(borderRadius: BorderRadius.circular(8), child: view); if (widget.fill) return view; - if (!live) WidgetsBinding.instance.addPostFrameCallback((_) => _fit()); - final rows = live - ? kChatShellOutputCollapsedLines - : (_fitRows ?? kChatShellOutputCollapsedLines); - final line = chatShellTerminalLineHeight(context, style); - // A pixel of slack keeps rounding from losing the last row. - return SizedBox(height: rows * line + padding.vertical + 1, child: view); + final cell = chatShellTerminalCellSize(context, style); + return LayoutBuilder( + builder: (context, constraints) { + // A finished run's box fits the rows its output takes at this width. + final cols = ((constraints.maxWidth - padding.horizontal) / cell.width) + .floor() + .clamp(1, 1000); + final rows = live + ? kChatShellOutputCollapsedLines + : session.rowsAt(cols).clamp(1, kChatShellOutputCollapsedLines); + // A pixel of slack keeps rounding from losing the last row. + return SizedBox( + height: rows * cell.height + padding.vertical + 1, + child: view, + ); + }, + ); } } diff --git a/app/notes/chat-interactive-terminal.md b/app/notes/chat-interactive-terminal.md new file mode 100644 index 00000000..fbb5a417 --- /dev/null +++ b/app/notes/chat-interactive-terminal.md @@ -0,0 +1,170 @@ +# Interactive chat shell commands (terminal) + +Operator shell commands (`!cmd`, Run command…; see `chat-shell-commands.md`) +now run in a real pseudo-terminal and the card draws them with a terminal +emulator. Auth flows that print a link, wait for a pasted token and continue +(`gh auth login`, `claude login`, `npm login`, ssh prompts) work in the chat. + +## Behaviour + +- **Server (macOS, Linux):** every `chat_shell_run` starts `$SHELL -lc ` + inside a PTY (`github.com/creack/pty` v1.1.24) as the leader of a new + session with the PTY as controlling terminal (`Setsid`, `Setctty`), so the + session id is the process group Stop signals (SIGINT, then SIGKILL after the + grace period). `TERM=xterm-256color`; cwd and the rest of the environment are + unchanged. Size comes from the request (`cols`, `rows`), clamped to + 20–500 x 4–200, default 100x30. The PTY controller is closed when the command + ends. Other platforms keep the previous pipe mode; input and resize answer + "interactive terminals are not supported on this server". +- **Card:** the output area is an `xterm` 4.0.0 (xterm.dart) `TerminalView` + fed the raw stream in order. One emulator per run lives in the controller + (`ChatShellTerminals`), so scrolling a card away or opening Full screen keeps + the same state. + - Running: 12 rows in the reading column; click/tap to focus and type + (hardware keys, Ctrl-C, arrows, Tab, Esc go to the process). Paste: + Cmd-V on Apple platforms, Ctrl-V or Ctrl-Shift-V elsewhere, plus the + toolbar's Paste button. Ctrl-A and other Ctrl keys reach the process. A key + toolbar under the terminal: Paste, Enter, Ctrl-C, Tab, Esc, arrows. On + Android/iOS the toolbar also has a text field ("Type input, then Enter") + for the soft keyboard, with a Hide typing toggle; it is emptied when sent. + - The terminal is resized to its layout (debounced 150 ms); the process gets + SIGWINCH. New runs start at the last laid-out size. + - Printed `http(s)` links open in the browser on tap (wrapped links are + joined). Other schemes are ignored. + - Finished runs are drawn read-only, shrunk to the rows their output takes + (at most 12), cursor hidden. Full screen opens the same terminal in a page. + - Colours: background/foreground/cursor/selection from the host theme; the + 16 ANSI colours are xterm.dart's palette, darkened on light surfaces. + - Copy output copies the server's plain-text rendering; Send to agent shares + a bounded plain-text tail (no escape codes). +- Pipe-mode and older runs (no `terminal`) are drawn in the same emulator with + `\n` drawn as a new line, read-only. + +## Protocol + +- `chat_shell_run` request adds optional `cols`, `rows`; records add + `terminal`, `cols`, `rows` (current size) and, only in + `chat_shell_run_output`, `text` (plain-text rendering). +- `chat_shell_input {session_id, run_id, data}`: `data` is UTF-8 text written + byte-for-byte (its UTF-8 encoding). Control characters are JSON escapes: + Ctrl-C `\u0003`, Enter `\r`, arrows `\u001b[A`… Paste is text (bracketed when + the program asked). At most 16 KiB per request (clients split longer pastes + at 4096 UTF-16 units); invalid UTF-8 is refused. Requests from one + connection are applied in order through a 64-entry queue; a full queue is + refused ("the command is not reading its input"). Reply has no body. +- `chat_shell_resize {session_id, run_id, cols, rows}`: reply echoes the run. + The last resize from any client wins. +- Output frames are unchanged: raw terminal bytes (UTF-8, partial characters + held back) with absolute byte offsets `[offset, end)`, which are the stream + sequence numbers. `chat_shell_run_output` takes `after`: the reply's + `output_start` is `max(after, retained start)`, so a reconnecting client + fetches only what it missed and sees a gap if it fell out of the 1 MiB tail. + The app does this on reconnect for runs it holds. +- Persistence: `chat_shell_runs` gains `terminal`, `cols`, `rows`, + `output_text` (additive columns). `output` is the raw stream tail (1 MiB), + `output_text` its rendering (bounded to 1 MiB). Rows recorded before this + change get a rendering computed on read. + +## Security + +- Any authenticated client watching the chat may type into or resize a + running command, not only the one that started it (the same authority that + can already start and stop commands in that chat). Input is checked against + the chat's operator session like every other shell request. +- Input is never persisted or logged: the server does not log + `chat_shell_input`/`chat_shell_resize` request lines at all (keystrokes + would otherwise be one log line each), and only what the terminal echoes + becomes output. Password prompts disable echo, so hidden input never + appears in output, frames, `output` or `output_text`. +- The client keeps no copy of typed input: keys go from the emulator straight + into a send queue that is cleared as each request is sent (and discarded on + a refusal); the mobile field is cleared on send and can hide its text. +- When the terminal has focus, the chat composer leaves Cmd/Ctrl-V alone + (`ChatComposerPasteFocus.registerInput`), so a pasted token goes only to the + process. + +## Limits and known gaps + +- Plain-text rendering is not an emulator: it strips CSI/OSC/DCS sequences, + applies `\r`, backspace and line erase; full-screen programs render as their + last lines. The card's emulator draws them properly. +- Every watching client's emulator answers terminal queries (e.g. cursor + position) for a live run, so two open clients send two answers. + xterm.dart 4.0.0 answers DSR 6 zero-based; the app overrides it to the + correct one-based answer. +- xterm.dart 4.0.0 keeps blank rows when it rewraps; the app drops blank rows + below the cursor after a resize so the top of the output stays in view. +- Desktop typing uses key events (no IME composition for CJK input). Touch + platforms use the field. +- A descendant that keeps the PTY open after the command exits is read for + 1 s; on macOS the PTY has no read deadline, so its reader goroutine ends + only when that descendant closes it (the run itself is finished and the + group killed). +- Mobile behaviour (soft keyboard field) is verified by widget tests only; no + device test ran. Android/Linux builds were not run (web and macOS were). + +## Files + +- Server: `internal/protocol/chat_shell_terminal.go`, `chat_shell_run.go`; + `internal/server/chat_shell_terminal{,_unix,_other}.go`, + `chat_shell_plain.go`, `chat_shell_runner.go`, `chat_shell_supervise.go`, + `chat_shell_run_handlers.go`, `chat_shell_share.go`, `chat.go`, + `websocket.go`; `internal/pipeline/chat_shell_runs.go`; `go.mod`, `go.sum`. +- App: `lib/features/chat/shell/chat_shell_terminal_{session,view,keys,theme,links,page}.dart`, + `chat_shell_terminals.dart`, `chat_shell_output_view.dart`, + `chat_shell_run{,_card}.dart`, `chat_shell_card_actions.dart`, + `chat_shell_runs_{controller,repository}.dart`, `chat_shell_metrics.dart`; + `lib/features/chat/conversation/chat_composer_paste_focus.dart`; + `pubspec.yaml`/`pubspec.lock` (`xterm: ^4.0.0`, pure Dart; pub.dev lists + Android, iOS, Linux, macOS, web, Windows); probe fixture + `tool/perf/chat_shell_fixture.dart` (`?shell=1`: coloured runs and an + interactive `gh auth login` that hides the token and finishes on Enter). + +## Verification + +Flutter 3.44.6 / Dart 3.12.2; macOS host. + +- `go test ./internal/protocol ./internal/pipeline ./internal/server -count=1`: + `ok …/protocol 0.205s`, `ok …/pipeline 15.838s`, `ok …/server 140.086s`. + Real-PTY tests (`chat_shell_terminal_test.go`, `_ws_test.go`): a typed line + reaches `read`; `stty -echo` input is in no frame, output or text; `\x03` + interrupts; `stty size` sees the start size and a resize; resume by offset + over the websocket from a second client; raw + plain text persisted; + input bounds (16 KiB, empty, invalid UTF-8, full queue); size clamping. + `go test -run ChatShell -count=5`: ok. `GOOS=freebsd go build + ./internal/server` (pipe fallback) and `GOOS=linux GOARCH=amd64 go test -c` + compile. (`-race` shows an existing data race in + `internal/opencode` `nativeRequest`, unrelated to this change.) +- `tool/memwatch/full.sh test/features/chat`: `PASS: 1124 passed, 0 failed`. + New: `test/features/chat/shell/chat_shell_terminal_test.dart` (desktop keys, + Cmd-V paste not taken by the composer, Paste button, touch toolbar and + hidden field cleared on send, resize sent, finished run read-only, colours, + reconnect resume), `chat_shell_terminal_session_test.dart` (links incl. + wrapped and non-http, query answers not resent on replay, one-based DSR, + gap redraw, rewrap keeps first line, row fitting). +- `tool/analyze.sh`: clean. `flutter build web`: built. + `FLUTTER_XCODE_ARCHS=arm64 flutter build macos`: built (34.9MB). +- Real Chrome (`tool/capture`, probe `?chats=2&shell=1`, 880x1000, Material and + Cupertino, light and dark): `/tmp/chat-interactive-terminal/-/` + `01-login-prompt.png` (coloured output, underlined link, prompt and cursor), + `02-login-focused.png` (focused cursor), `03-login-done.png` (5 typed keys + and Enter reached the fixture: "received a 5-character token", nothing + echoed; the card shrank to its output, read-only), `04-full-screen.png`. +- Scratch server end to end (`go build ./cmd/pipelines-server`, `env -i` + with HOME/XDG_DATA_HOME/DB under `/tmp/pty-e2e`, OS-chosen loopback port, + operator session inserted with sqlite3, Node websocket driver + `/tmp/pty-e2e/drive.mjs`; server stopped afterwards, no processes left): + + ``` + started run_45be206dedb0454409c537b6 terminal=true size=90x20 + resize reply: chat_shell_resize 120x40 + input reply: chat_shell_input + final: status=exited exit=0 bytes=145 + "tty: xterm-256color\r\n20 90\r\n\u001b[1;32mOpen https://example.com/login\u001b[0m\r\nPaste token: \r\n40 120\r\ngot 13 characters\r\nName: operator\r\nhello operator\r\n" + secret in stream: false + resume after 119: output_start=119 output="operator\r\nhello operator\r\n" + secret in text: false + late input: error this command is not running + run_…|exited|0|1|120|40|145|125|0 (sqlite: terminal, cols, rows, raw, text, SECRET offset) + ``` + The server log has no `chat_shell_input` or `chat_shell_resize` lines. diff --git a/app/test/features/chat/shell/chat_shell_terminal_session_test.dart b/app/test/features/chat/shell/chat_shell_terminal_session_test.dart index f28b80c9..7394fed9 100644 --- a/app/test/features/chat/shell/chat_shell_terminal_session_test.dart +++ b/app/test/features/chat/shell/chat_shell_terminal_session_test.dart @@ -84,4 +84,31 @@ void main() { contains('earlier output was dropped'), ); }); + + test('narrowing rewraps without pushing the first line out of view', () { + final session = ChatShellTerminalSession( + _run('first\r\n${'u' * 30}\r\nprompt: '), + onInput: (_) {}, + onResize: (_, _) {}, + ); + session.terminal.resize(20, 6); + final buffer = session.terminal.buffer; + expect(buffer.height, 6); + expect(buffer.lines[0].getText().trim(), 'first'); + expect(buffer.lines[3].getText().trim(), 'prompt:'); + expect(buffer.absoluteCursorY, 3); + expect(buffer.cursorX, 8); + }); + + test('a finished run counts the rows its output takes at a width', () { + final session = ChatShellTerminalSession( + _run('a\r\n${'x' * 50}\r\nend\r\n', status: 'exited'), + onInput: (_) {}, + onResize: (_, _) {}, + ); + // The 50-character line wraps at the terminal's 40 columns. + expect(session.rowsAt(40), 4); + expect(session.rowsAt(20), 5); + expect(session.rowsAt(100), 3); + }); } diff --git a/app/test/features/chat/shell/chat_shell_terminal_test.dart b/app/test/features/chat/shell/chat_shell_terminal_test.dart index 14fd50ab..49df9977 100644 --- a/app/test/features/chat/shell/chat_shell_terminal_test.dart +++ b/app/test/features/chat/shell/chat_shell_terminal_test.dart @@ -39,12 +39,36 @@ void main() { expect(find.byKey(const Key('chat-shell-terminal-field')), findsNothing); await tester.tap(find.byType(TerminalView)); await tester.pump(); + await tester.sendKeyEvent(LogicalKeyboardKey.keyG); + await tester.sendKeyEvent(LogicalKeyboardKey.digit7); await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft); await tester.sendKeyEvent(LogicalKeyboardKey.keyC); await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); await tester.pump(); - expect(typed(), '\x1b[A\x03'); + expect(typed(), 'g7\x1b[A\x03'); + // Cmd-V pastes the clipboard into the process. + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + (call) async => + call.method == 'Clipboard.getData' ? {'text': 'tok'} : null, + ); + addTearDown( + () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + null, + ), + ); + await tester.sendKeyDownEvent(LogicalKeyboardKey.metaLeft); + await tester.sendKeyEvent(LogicalKeyboardKey.keyV); + await tester.sendKeyUpEvent(LogicalKeyboardKey.metaLeft); + for (var i = 0; i < 5; i++) { + await tester.pump(const Duration(milliseconds: 20)); + } + expect(typed(), 'g7\x1b[A\x03tok'); + // The chat composer leaves a paste into the terminal alone. + expect(find.text('tok'), findsNothing); + expect(find.byType(EditableText), findsWidgets); await tester.pump(const Duration(milliseconds: 400)); expect(gateway.bodies('chat_shell_input').first['run_id'], 'run_t'); }, diff --git a/app/tool/perf/chat_shell_fixture.dart b/app/tool/perf/chat_shell_fixture.dart index f2a87c5a..e066045b 100644 --- a/app/tool/perf/chat_shell_fixture.dart +++ b/app/tool/perf/chat_shell_fixture.dart @@ -1,17 +1,30 @@ // Operator shell commands for the full-app probe (`?shell=1`, with -// `?chats=N`): every fixture chat lists four recorded runs (succeeded, failed, -// stopped and one still running), and chat_shell_run/stop/share answer as the -// server does, with the frames that follow. +// `?chats=N`): every fixture chat lists four recorded terminal runs +// (succeeded, failed, stopped and an interactive login still waiting for a +// token), and chat_shell_run/stop/share/input answer as the server does, with +// the frames that follow. The login prompt hides what is typed, as a real +// terminal's password prompt does, and finishes on Enter. +import 'dart:convert'; + import 'package:pipelines_app/core/api_gateway.dart'; bool _enabled = false; DateTime _base = DateTime.now(); +int _loginEnd = utf8.encode(_loginPrompt).length; +int _tokenLength = 0; void configureChatShellFixture(Map params) { _enabled = params['shell'] == '1'; _base = DateTime.now().subtract(const Duration(minutes: 3)); + _loginEnd = utf8.encode(_loginPrompt).length; } +const String _loginPrompt = + '\x1b[1m!\x1b[0m First copy your one-time code: \x1b[1;33mA1B2-C3D4\x1b[0m\r\n' + 'Open this URL to continue in your web browser: ' + '\x1b[4mhttps://github.com/login/device\x1b[0m\r\n' + '\x1b[32m?\x1b[0m \x1b[1mPaste an authentication token\x1b[0m: '; + int _at(int seconds) => _base.add(Duration(seconds: seconds)).millisecondsSinceEpoch; @@ -30,6 +43,9 @@ JsonMap _run( int duration = 0, String output = '', }) => { + 'terminal': true, + 'cols': 100, + 'rows': 30, 'id': id, 'session_id': session, 'command': command, @@ -40,7 +56,7 @@ JsonMap _run( if (status != 'running') 'ended_at': _at(started) + duration, 'duration_ms': duration, 'output': output, - 'output_bytes': output.length, + 'output_bytes': utf8.encode(output).length, }; List _runs(String session) => [ @@ -52,8 +68,8 @@ List _runs(String session) => [ exitCode: 0, duration: 84, output: - ' M app/lib/features/chat/shell/chat_shell_run_card.dart\n' - '?? app/notes/chat-shell-commands.md\n', + ' \x1b[31mM\x1b[0m app/lib/features/chat/shell/chat_shell_run_card.dart\r\n' + '\x1b[31m??\x1b[0m app/notes/chat-shell-commands.md\r\n', ), _run( session, @@ -63,12 +79,12 @@ List _runs(String session) => [ exitCode: 1, duration: 4210, output: - '${[for (final name in _tests) '=== RUN TestChatShell$name\n--- PASS: TestChatShell$name (0.0${name.length % 9}s)\n'].join()}' - '--- FAIL: TestChatShellStopInterruptsTheGroup (0.21s)\n' - ' chat_shell_run_test.go:112: stopped record = {Status:exited}\n' - 'FAIL\n' - 'FAIL\tgit.a-wan.net/alan/pipelines/internal/server\t0.611s\n' - 'FAIL\n', + '${[for (final name in _tests) '=== RUN TestChatShell$name\r\n\x1b[32m--- PASS\x1b[0m: TestChatShell$name (0.0${name.length % 9}s)\r\n'].join()}' + '\x1b[1;31m--- FAIL\x1b[0m: TestChatShellStopInterruptsTheGroup (0.21s)\r\n' + ' chat_shell_run_test.go:112: stopped record = {Status:exited}\r\n' + '\x1b[31mFAIL\x1b[0m\r\n' + '\x1b[31mFAIL\x1b[0m\tgit.a-wan.net/alan/pipelines/internal/server\t0.611s\r\n' + '\x1b[31mFAIL\x1b[0m\r\n', ), _run( session, @@ -77,17 +93,15 @@ List _runs(String session) => [ 40, status: 'stopped', duration: 15200, - output: 'Nov 9 15:58:01 host kernel[0]: wake reason: EC.LidOpen\n', + output: 'Nov 9 15:58:01 host kernel[0]: wake reason: EC.LidOpen\r\n^C', ), _run( session, - 'run_build', - 'flutter build web --target tool/search_selection_probe_entry.dart', + 'run_login', + 'gh auth login --hostname github.com', 60, status: 'running', - output: - 'Compiling lib/main.dart for the Web...\n' - 'Font asset "CupertinoIcons.ttf" was tree-shaken.\n', + output: _loginPrompt, ), ]; @@ -129,6 +143,10 @@ JsonMap? chatShellReply(JsonMap request) { }; case 'chat_shell_share': return {'id': id, 'type': 'chat_prompt'}; + case 'chat_shell_input': + return {'id': id, 'type': 'chat_shell_input'}; + case 'chat_shell_resize': + return {'id': id, 'type': 'chat_shell_resize'}; } return null; } @@ -171,6 +189,37 @@ List chatShellFollowUps(JsonMap request) { return [ frame({'run_id': run['id'], 'run': run}), ]; + case 'chat_shell_input': + // The token prompt does not echo; Enter completes the login. + final body = request['chat_shell_run_request']; + final data = body is Map ? '${body['data'] ?? ''}' : ''; + _tokenLength += data.replaceAll('\r', '').length; + if (!data.contains('\r')) return const []; + final done = + '\r\n\x1b[2m(received a $_tokenLength-character token)\x1b[0m\r\n' + '\x1b[32m\u2713\x1b[0m Configured git protocol\r\n' + '\x1b[32m\u2713\x1b[0m Logged in as \x1b[1moperator\x1b[0m\r\n'; + final start = _loginEnd; + _loginEnd += utf8.encode(done).length; + return [ + frame({ + 'run_id': 'run_login', + 'output': done, + 'offset': start, + 'end': _loginEnd, + }), + frame({ + 'run_id': 'run_login', + 'run': _run( + session, + 'run_login', + 'gh auth login --hostname github.com', + 60, + exitCode: 0, + duration: 48200, + )..['output_bytes'] = _loginEnd, + }), + ]; } return const []; } diff --git a/internal/server/chat_shell_runner_test.go b/internal/server/chat_shell_runner_test.go index 31a75f0c..b84a3604 100644 --- a/internal/server/chat_shell_runner_test.go +++ b/internal/server/chat_shell_runner_test.go @@ -48,7 +48,16 @@ func TestChatShellStopKillsAfterGrace(t *testing.T) { if err != nil { t.Fatal(err) } - time.Sleep(150 * time.Millisecond) + // The trap must be in place before the stop: wait for the command's + // output rather than a fixed delay (a login shell can be slow to start). + for deadline := time.Now().Add(10 * time.Second); ; time.Sleep(10 * time.Millisecond) { + if record, err := runner.Read(context.Background(), "ses_1", run.ID); err == nil && strings.Contains(record.Output, "ready") { + break + } + if time.Now().After(deadline) { + t.Fatal("the command never printed ready") + } + } if _, err := runner.Stop("ses_2", run.ID); err == nil { t.Fatal("another session stopped this run") }