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.
This commit is contained in:
2026-11-09 20:51:59 +00:00
parent 89882d90f3
commit 2332143e5b
10 changed files with 429 additions and 52 deletions
@@ -217,10 +217,16 @@ class _ChatShellTerminalKeysState extends State<ChatShellTerminalKeys> {
);
}
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),
@@ -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);
}
}
}
@@ -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;
}
@@ -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<ShortcutActivator, Intent> 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<ChatShellTerminalView> {
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<ChatShellTerminalView> {
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<ChatShellTerminalView> {
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<ChatShellTerminalView> {
);
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,
);
},
);
}
}