The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
feat(mobile): draw key bar keys as native-style caps
tonyc13a3a90c53e
diff --git a/mobile/lib/phone/terminal_key_bar.dart b/mobile/lib/phone/terminal_key_bar.dartindex 9d30d2db1..f7848777b 100644--- a/mobile/lib/phone/terminal_key_bar.dart+++ b/mobile/lib/phone/terminal_key_bar.dart@@ -334,7 +334,7 @@ class _TerminalKeyBarState extends State<TerminalKeyBar>_key(label: 'clear',semanticLabel: 'Clear prompt',- wide: true,+ parts: _wideParts,onTap: () {_disarm();clear();@@ -347,7 +347,7 @@ class _TerminalKeyBarState extends State<TerminalKeyBar>_key(label: 'paste',semanticLabel: 'Paste',- wide: true,+ parts: _wideParts,onTap: () {_disarm();paste();@@ -438,8 +438,10 @@ class _TerminalKeyBarState extends State<TerminalKeyBar>label: '▾',semanticLabel: 'Hide keyboard',// ⚠️ `▾` is a SMALL triangle: at the row's size it read as a speck in- // the corner, on the key reached for most after typing.- scale: 1.6,+ // the corner, on the key reached for most after typing — which is+ // also why its cap is wider than the rest. See [_hideParts].+ scale: 1.8,+ parts: _hideParts,alwaysEnabled: true,onTap: widget.onDismissKeyboard,),@@ -456,13 +458,14 @@ class _TerminalKeyBarState extends State<TerminalKeyBar>border: Border(top: BorderSide(color: Tty.of(context).dim)),),child: Padding(- padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 2),+ padding: const EdgeInsets.symmetric(horizontal: _gap, vertical: 2),// Held out of the app-wide text scale like the composer's own type:// at a large scale the keys stop fitting the row.child: MediaQuery.withNoTextScaling(// Every key the same width, the two apart ones included — they are// separated by the rule, not by being a different size. Only the- // two five-letter words are wider: see [_wideParts].+ // two five-letter words are wider, and `▾`: see [_wideParts] and+ // [_hideParts].child: widget.hints.isEmpty? Row(children: [..._row(keys), ..._rule(), ..._row(apart)]): LayoutBuilder(@@ -476,7 +479,7 @@ class _TerminalKeyBarState extends State<TerminalKeyBar>}/// How many parts of the row a key takes: [_keyParts] for most,- /// [_wideParts] for `clear` and `paste`.+ /// [_wideParts] for `clear` and `paste`, [_hideParts] for `▾`.////// ⚠️ **A word as long as `clear` in a cell sized for `esc` is shrunk to half/// the size of the rest of the row.** The label scales down to fit rather@@ -486,13 +489,22 @@ class _TerminalKeyBarState extends State<TerminalKeyBar>static const _keyParts = 3;static const _wideParts = 5;+ /// `▾` takes a third more than a key: it is the one reached for most after+ /// typing, at the row's far end, and a cap the size of an arrow's was a+ /// small target for it.+ static const _hideParts = 4;++ /// Between two caps, and from the end caps to the strip's left and right+ /// edges. Top and bottom are the cap's own inset — see `_KeyCap`.+ static const _gap = 4.0;+/// A run of keys for the strip's one [Row], each `Expanded` with its/// [_Slot.parts] as the flex — so every key on the strip, on either side of/// the rule, gets the same width but the wide two, and the row fills the/// phone rather than ending in a gap.List<Widget> _row(List<_Slot> keys) => [for (var index = 0; index < keys.length; index++) ...[- if (index > 0) const SizedBox(width: 4),+ if (index > 0) const SizedBox(width: _gap),Expanded(flex: keys[index].parts, child: keys[index].key),],];@@ -506,14 +518,14 @@ class _TerminalKeyBarState extends State<TerminalKeyBar>/// longer made.List<Widget> _rule() => _canSendImage? [- const SizedBox(width: 8),+ const SizedBox(width: 6),Container(width: 1, height: 22, color: AppGlass.hair),- const SizedBox(width: 8),+ const SizedBox(width: 6),]- : [const SizedBox(width: 4)];+ : [const SizedBox(width: _gap)];- /// How wide [_rule] is — `8 + 1 + 8`, or the single gap in its place.- double get _ruleWidth => _canSendImage ? 17 : 4;+ /// How wide [_rule] is — `6 + 1 + 6`, or the single gap in its place.+ double get _ruleWidth => _canSendImage ? 13 : _gap;/// The row while the pane offers its own keys: [TerminalKeyBar.hints] at its/// head, the fixed keys, then the [KeyHint.trails] ones, scrolling sideways@@ -525,9 +537,8 @@ class _TerminalKeyBarState extends State<TerminalKeyBar>/// at the head push them along, and the ones at the tail start where the/// visible part of the row ends. [_revealHints] scrolls to whichever arrived.Widget _rowWithHints(List<_Slot> keys, List<_Slot> apart, double width) {- const gap = 4.0;final gaps =- gap * (keys.length - 1) + _ruleWidth + gap * (apart.length - 1);+ _gap * (keys.length - 1) + _ruleWidth + _gap * (apart.length - 1);final parts = [...keys,...apart,@@ -576,7 +587,7 @@ class _TerminalKeyBarState extends State<TerminalKeyBar>/// A run of the pane's keys, each as wide as its words.List<Widget> _hintRun(List<KeyHint> hints) => [for (var i = 0; i < hints.length; i++) ...[- if (i > 0) const SizedBox(width: 4),+ if (i > 0) const SizedBox(width: _gap),_hint(hints[i]),],];@@ -594,7 +605,7 @@ class _TerminalKeyBarState extends State<TerminalKeyBar>/// `Expanded`.List<Widget> _cells(List<_Slot> keys, double part) => [for (var index = 0; index < keys.length; index++) ...[- if (index > 0) const SizedBox(width: 4),+ if (index > 0) const SizedBox(width: _gap),SizedBox(width: part * keys[index].parts, child: keys[index].key),],];@@ -683,7 +694,7 @@ class _TerminalKeyBarState extends State<TerminalKeyBar>String? semanticLabel,bool alwaysEnabled = false,bool armed = false,- bool wide = false,+ int parts = _keyParts,double scale = 1,required VoidCallback onTap,}) {@@ -704,7 +715,7 @@ class _TerminalKeyBarState extends State<TerminalKeyBar>onTap: alwaysEnabled ? onTap : () => _send(onTap),),),- parts: wide ? _wideParts : _keyParts,+ parts: parts,);}}@@ -774,14 +785,38 @@ class _KeyCapState extends State<_KeyCap> {setState(() => _down = down);}+ /// The key's touch target: the strip's 36pt, less its 2pt above and below.+ static const _cellHeight = 32.0;++ /// How far the cap sits inside its cell, top and bottom: a 26pt cap, 5pt+ /// from the strip's edges with the strip's own 2pt. The whole cell takes the+ /// tap, not only the cap drawn in it.+ static const _capInset = 3.0;++ static const _capRadius = 5.0;++ /// The cap's fill: a step up from the ground, as a system keyboard's keys+ /// stand off its own — less of one while the key takes no input.+ static Color _capFill(Tty tty, {required bool live, required bool pressed}) {+ final (dead, rest, down) = tty.isLight+ ? (0.04, 0.08, 0.18)+ : (0.08, 0.16, 0.30);+ final alpha = !live ? dead : (pressed ? down : rest);+ return Color.alphaBlend(tty.text.withValues(alpha: alpha), tty.ground);+ }+@overrideWidget build(BuildContext context) {AppTheme.watch(context);final tty = Tty.of(context);final hint = widget.hint;- // A terminal's keys: plain words and the font's own arrows, no caps. Armed (ctrl, shift) is- // reverse video, as a terminal marks a mode; pressed is fzf's selection ground, on the way- // down — no fade.+ // ⚠️ **Caps, the one place the chrome draws them.** The strip sits on the+ // system keyboard and is pressed like it, so its keys are drawn as that+ // keyboard draws its own: a rounded cap a step up from the ground, with a+ // 1pt edge under it. Bare words over the ground read as a line of text,+ // not as keys. Armed (ctrl, shift) is still reverse video, as a terminal+ // marks a mode; pressed lightens the cap on the way down — no fade. Both+ // drop the edge: the key is down.final armed = widget.armed && widget.live;final pressed = _down && widget.live;final foreground = armed@@ -799,34 +834,57 @@ class _KeyCapState extends State<_KeyCap> {onTapCancel: () => _set(false),onTap: widget.onTap,child: Container(- height: 40,- alignment: Alignment.center,- color: armed- ? tty.text- : pressed- ? tty.selected- : Colors.transparent,- child: hint != null- ? _hintFace(hint, foreground: foreground, lit: armed || pressed)- // Shrinks rather than clips: ten keys share a phone's width.- : Padding(- padding: const EdgeInsets.symmetric(horizontal: 2),- child: FittedBox(- fit: BoxFit.scaleDown,- child: Text(- widget.label ?? '',- maxLines: 1,- style: tty.style(- color: foreground,- size: tty.fontSize * widget.scale,+ height: _cellHeight,+ padding: const EdgeInsets.symmetric(vertical: _capInset),+ child: DecoratedBox(+ decoration: BoxDecoration(+ color: armed+ ? tty.text+ : _capFill(tty, live: widget.live, pressed: pressed),+ borderRadius: BorderRadius.circular(_capRadius),+ boxShadow: widget.live && !armed && !pressed+ ? [+ BoxShadow(+ color: Colors.black.withValues(+ alpha: tty.isLight ? 0.22 : 0.45,+ ),+ offset: const Offset(0, 1),),- ),- ),- ),+ ]+ : null,+ ),+ child: Align(child: _face(tty, hint, foreground, armed, pressed)),+ ),),);}+ Widget _face(+ Tty tty,+ KeyHint? hint,+ Color foreground,+ bool armed,+ bool pressed,+ ) => hint != null+ ? _hintFace(hint, foreground: foreground, lit: armed || pressed)+ // Shrinks rather than clips: ten keys share a phone's width.+ : Padding(+ padding: const EdgeInsets.symmetric(horizontal: 2),+ child: FittedBox(+ fit: BoxFit.scaleDown,+ child: Text(+ widget.label ?? '',+ maxLines: 1,+ style: tty+ .style(color: foreground, size: tty.fontSize * widget.scale)+ // A scaled glyph drops the line's leading: at 1.2 it was+ // the empty line around it, not the glyph, that met the+ // cap's height and shrank it to fit.+ .copyWith(height: widget.scale == 1 ? null : 1),+ ),+ ),+ );+/// A [_KeyCap.hint]'s face: the key as the pane printed it, then the CLI's/// word for what it does, quieter — both in the terminal's own face,/// followed live, since Settings ▸ Terminal can change it while the row isdiff --git a/mobile/test/key_hints_codex_test.dart b/mobile/test/key_hints_codex_test.dartnew file mode 100644index 000000000..61a1c44a6--- /dev/null+++ b/mobile/test/key_hints_codex_test.dart@@ -0,0 +1,204 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/terminal/key_hints.dart';+import 'package:xterm/xterm.dart';++/// The keys Codex's chrome offers and a phone cannot press — as Codex 0.156.1+/// writes them (`shift+←`), as 0.161.0 does (`⇧←`), and the screens that must+/// never grow a button.+void main() {+ /// What pressing [hint] sends to the pane.+ String bytesOf(KeyHint hint) {+ final terminal = Terminal(maxLines: 100)..resize(80, 10);+ final out = <String>[];+ terminal.onOutput = out.add;+ expect(hint.chord.send(terminal), isTrue, reason: '$hint sends nothing');+ return out.join();+ }++ group('the keys a phone is stranded without', () {+ // As the pane prints the hint → the button's key, its words, its bytes.+ const offered = <(String, String, String, String)>[+ (' shift+← to answer', 'shift+←', 'answer', '\x1b[1;2D'),+ (' ctrl+] skip', 'ctrl+]', 'skip', '\x1d'),+ (' ⌥+↓ main prompt', '⌥+↓', 'main prompt', '\x1b[1;3B'),+ (' ⌥+↑ prev question', '⌥+↑', 'prev question', '\x1b[1;3A'),+ (' ⌥+↑ previous question', '⌥+↑', 'previous question', '\x1b[1;3A'),+ (' shift+→ next question', 'shift+→', 'next question', '\x1b[1;2C'),+ (+ ' shift+← edit last queued message',+ 'shift+←',+ 'edit last queued',+ '\x1b[1;2D',+ ),+ (' ctrl+o copy', 'ctrl+o', 'copy', '\x0f'),+ (' ctrl+t to view transcript', 'ctrl+t', 'view transcript', '\x14'),+ ];++ for (final (line, keyText, action, bytes) in offered) {+ test('"${line.trim()}" is a key that leads the strip', () {+ final hints = parseKeyHints([line]);+ expect(hints, hasLength(1));+ final hint = hints.single;+ expect(hint.keyText, keyText);+ expect(hint.action, action);+ expect(hint.trails, isFalse, reason: 'only cycle trails the strip');+ expect(bytesOf(hint), bytes);+ });+ }++ test('Claude Code\'s cycle is the one that trails', () {+ final hint = parseKeyHints([' ⏵⏵ auto mode on (shift+tab to cycle)'])+ .single;+ expect(hint.trails, isTrue);+ expect(bytesOf(hint), '\x1b[Z');+ });+ });++ group('Codex 0.161.0 writes the glyph straight onto the key', () {+ test('⇧← to answer is the same key as shift+← to answer', () {+ final glyph = parseKeyHints([' ? 1 question', ' ⇧← to answer']);+ final spelled = parseKeyHints([+ ' ? 1 question',+ ' shift+← to answer',+ ]);+ expect(glyph.single.keyText, '⇧←', reason: 'drawn as the pane drew it');+ expect(glyph.single.action, 'answer');+ expect(glyph.single.chord, spelled.single.chord);+ expect(bytesOf(glyph.single), '\x1b[1;2D');+ });++ test('and on its glyph keys: ⇧⇥ cycles, ⌥↓ leaves for the main prompt', () {+ expect(bytesOf(parseKeyHints([' ⇧⇥ to cycle']).single), '\x1b[Z');+ expect(parseKeyHints([' ⌥↓ main prompt']).single.keyText, '⌥↓');+ expect(bytesOf(parseKeyHints([' ⌥↓ main prompt']).single), '\x1b[1;3B');+ });+ });++ group('a footer of several hints', () {+ test('offers its keys in reading order and leaves the rest as text', () {+ final hints = parseKeyHints([+ ' ctrl+] skip · ⌥+↓ main prompt · enter to submit · esc to cancel',+ ]);+ expect([for (final h in hints) h.action], ['skip', 'main prompt']);+ });++ test('offers no more than four at once', () {+ final hints = parseKeyHints([+ ' ctrl+] skip · ⌥+↓ main prompt · ⌥+↑ prev question',+ ' shift+→ next question · ctrl+o copy · ctrl+t view transcript',+ ]);+ expect(+ [for (final h in hints) h.action],+ ['skip', 'main prompt', 'prev question', 'next question'],+ );+ });++ test('offers one button for one key, the first the pane names', () {+ final hints = parseKeyHints([+ ' shift+← to answer',+ ' shift+← edit last queued message',+ ]);+ expect(hints.single.action, 'answer');+ });+ });++ group('never a button', () {+ test('a hint in the conversation, above the live chrome', () {+ // The model explaining a shortcut, then five lines of chrome under it.+ expect(+ parseKeyHints([+ 'Press shift+← to answer the queued question.',+ '╭──────╮',+ '│ > │',+ '╰──────╯',+ ' gpt-5 · 12% context left',+ ' ? for shortcuts',+ ]),+ isEmpty,+ );+ // The same hint, low enough to be chrome.+ expect(+ parseKeyHints([+ 'Press shift+← to answer the queued question.',+ '╭──────╮',+ '│ > │',+ '╰──────╯',+ ' shift+← to answer',+ ]),+ hasLength(1),+ );+ });++ test('blank rows under the chrome are skipped, a whole pane of them', () {+ final blanks = List.filled(40, '');+ expect(parseKeyHints([' shift+← to answer', ...blanks]), hasLength(1));+ // Further up than a pane and more: not looked for.+ expect(+ parseKeyHints([' shift+← to answer', ...List.filled(60, '')]),+ isEmpty,+ );+ });++ test('a tip or shortcut no phone is stranded without', () {+ for (final line in [+ ' f3 search this conversation',+ ' ctrl+r to search history',+ ' shift+tab to toggle',+ ' ctrl+g to edit in your editor',+ ]) {+ expect(parseKeyHints([line]), isEmpty, reason: line);+ }+ });++ test('the keys that quit, drop or suspend the agent — whatever words '+ 'are beside them', () {+ for (final key in ['ctrl+c', 'ctrl+d', 'ctrl+z', r'ctrl+\', '⌃c']) {+ expect(parseKeyHints([' $key skip']), isEmpty, reason: key);+ }+ });++ test('a key the phone already has', () {+ for (final line in [+ ' esc to interrupt',+ ' tab to cycle',+ ' enter skip',+ ' ↑ prev question',+ ]) {+ expect(parseKeyHints([line]), isEmpty, reason: line);+ }+ });++ test('a key with nothing said about it', () {+ expect(parseKeyHints([' shift+←']), isEmpty);+ expect(parseKeyHints([' shift+← · ctrl+]']), isEmpty);+ });++ test('a key no terminal can send', () {+ expect(parseKeyHints([' ctrl+ä skip']), isEmpty);+ expect(parseKeyHints([' cmd+k skip']), isEmpty);+ expect(parseKeyHints([' ⌘k skip']), isEmpty);+ });+ });++ group('as the pane printed it', () {+ test('spacing collapsed, nothing else touched', () {+ final hint = parseKeyHints([' shift + ← to answer']).single;+ expect(hint.keyText, 'shift + ←');+ expect(bytesOf(hint), '\x1b[1;2D');+ });++ test('in any case, read as its words', () {+ final hint = parseKeyHints([' Shift+← to Answer']).single;+ expect(hint.action, 'answer');+ expect(hint.keyText, 'Shift+←');+ });++ test('a remapped key is pressed as the pane names it', () {+ // `tui.keymap` moved skip to ctrl+g: the button presses ctrl+g, not the+ // default ctrl+].+ final hint = parseKeyHints([' ctrl+g skip']).single;+ expect(hint.action, 'skip');+ expect(bytesOf(hint), '\x07');+ });+ });+}diff --git a/mobile/test/phone_edge/focus_behavior_test.dart b/mobile/test/phone_edge/focus_behavior_test.dartindex 9fa6c3877..c37aec41b 100644--- a/mobile/test/phone_edge/focus_behavior_test.dart+++ b/mobile/test/phone_edge/focus_behavior_test.dart@@ -1441,6 +1441,120 @@ void main() {await focus.close();});});++ // The keys a pane's chrome offers and a phone cannot press, read off this+ // page's own buffer and drawn on its key strip — and taken off it again the+ // moment the pane cannot type.+ group('the pane\'s own keys on the strip', () {+ const queued = '\r\n ? 1 question\r\n shift+← to answer';+ const cycle = '\r\n ⏵⏵ auto mode on (shift+tab to cycle)';+ final esc = find.byKey(const ValueKey('terminal-key-esc'));++ Future<_Focus> offered(+ WidgetTester tester, {+ String engine = 'codex',+ String screen = queued,+ }) async {+ final focus = await _Focus.open(+ tester,+ agents: [edgeAgent('a', engine: engine)],+ );+ raiseKeyboard(tester);+ await frames(tester);+ focus.session.terminal.write(screen);+ await frames(tester);+ return focus;+ }++ testWidgets('a Codex agent\'s queued question: its key on the strip, and '+ 'the key answers it', (tester) async {+ final focus = await offered(tester);+ expect(esc, findsOneWidget);+ expect(find.text('answer'), findsOneWidget);+ expect(+ tester.getTopRight(find.text('answer')).dx,+ lessThan(tester.getTopLeft(esc).dx),+ reason: 'it leads the strip',+ );++ await tester.tap(find.text('answer'));+ await frames(tester);+ expect(focus.typed, contains('\x1b[1;2D'));+ await focus.close();+ });++ testWidgets('Claude Code\'s cycle: on the strip, past its own keys', (+ tester,+ ) async {+ final focus = await offered(tester, engine: 'claude', screen: cycle);+ expect(find.text('cycle'), findsOneWidget);+ expect(+ tester.getTopLeft(find.text('cycle')).dx,+ greaterThan(tester.getTopRight(esc).dx),+ );+ await focus.close();+ });++ testWidgets('taken by the computer: the pane\'s keys leave the strip', (+ tester,+ ) async {+ final focus = await offered(tester);+ expect(find.text('answer'), findsOneWidget);++ await focus.takenByComputer();+ await frames(tester);+ expect(focus.session.acceptsInput, isFalse);+ expect(find.text('answer'), findsNothing);+ await focus.close();+ });++ testWidgets('a stream that died: the pane\'s keys leave the strip', (+ tester,+ ) async {+ final focus = await offered(tester);+ expect(find.text('answer'), findsOneWidget);++ await focus.session.handleFrame('terminal_closed', {+ 'streamId': focus.session.streamId,+ 'code': 'TERMINAL_CLOSED',+ 'reason': 'the daemon restarted',+ });+ await frames(tester);+ expect(focus.session.status, TerminalSessionStatus.closed);+ expect(find.text('answer'), findsNothing);+ await focus.close();+ });++ testWidgets('the agent is gone: no key of its pane is left', (+ tester,+ ) async {+ final focus = await offered(tester);+ expect(find.text('answer'), findsOneWidget);++ focus.app.stateOf('m')!+ ..agentsFromCache = false+ ..agents = [edgeAgent('other')];+ await focus.app.syncAgentsForTest('m');+ await frames(tester);+ expect(find.text('a is gone'), findsOneWidget);+ expect(find.text('answer'), findsNothing);+ await focus.close();+ });++ testWidgets('the hint goes once the pane stops offering it', (+ tester,+ ) async {+ final focus = await offered(tester);+ expect(find.text('answer'), findsOneWidget);++ // Answered: Codex redraws its bottom pane without the queue.+ focus.session.terminal.write('\x1b[2J\x1b[H› ');+ await frames(tester, count: 8);+ expect(find.text('answer'), findsNothing);+ expect(esc, findsOneWidget, reason: 'the strip itself stays');+ await focus.close();+ });+ });}/// The clipboard's contents as `Clipboard.getData` reports them.diff --git a/mobile/test/terminal_key_bar_test.dart b/mobile/test/terminal_key_bar_test.dartindex ceb7261da..0467e930a 100644--- a/mobile/test/terminal_key_bar_test.dart+++ b/mobile/test/terminal_key_bar_test.dart@@ -1,7 +1,11 @@import 'package:flutter/material.dart';+import 'package:flutter/services.dart';import 'package:flutter_test/flutter_test.dart';import 'package:harness_mobile/phone/terminal_input_dock.dart';import 'package:harness_mobile/phone/terminal_key_bar.dart';+import 'package:harness_mobile/phone/tty.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart';+import 'package:harness_mobile/shared/theme/color_palette.dart';import 'package:harness_mobile/terminal/key_hints.dart';import 'package:harness_mobile/terminal/terminal_input.dart';import 'package:harness_mobile/terminal/terminal_session.dart';@@ -456,4 +460,618 @@ void main() {expect(find.text('cycle').hitTestable(), findsOneWidget);},);++ group('keys are drawn as caps, as the system keyboard draws its own', () {+ Future<void> pumpCaps(WidgetTester tester, {bool enabled = true}) async {+ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(+ body: Align(+ alignment: Alignment.bottomCenter,+ child: SizedBox(+ width: 375,+ child: TerminalKeyBar(+ terminal: terminal,+ enabled: enabled,+ enginePrompt: true,+ onDismissKeyboard: () => dismissals++,+ onClearPrompt: () {},+ onPickImage: () {},+ ),+ ),+ ),+ ),+ ),+ );+ }++ Finder keyNamed(String name) => find.byKey(ValueKey('terminal-key-$name'));++ Finder capOf(Finder key) =>+ find.descendant(of: key, matching: find.byType(DecoratedBox));++ BoxDecoration capDecoration(WidgetTester tester, Finder key) =>+ tester.widget<DecoratedBox>(capOf(key)).decoration as BoxDecoration;++ Tty ttyOf(WidgetTester tester) =>+ Tty.of(tester.element(find.byType(TerminalKeyBar)));++ const names = [+ 'esc',+ 'Control C',+ 'tab',+ 'Clear prompt',+ 'shift',+ 'ctrl',+ 'Left',+ 'Up',+ 'Down',+ 'Right',+ 'Newline',+ 'Send image',+ 'Hide keyboard',+ ];++ testWidgets('every key sits in a rounded cap inside its cell, raised off '+ 'the ground, on a 36pt strip', (tester) async {+ await pumpCaps(tester);+ final tty = ttyOf(tester);++ final bar = tester.getRect(find.byType(TerminalKeyBar));+ expect(bar.height, 36);+ for (final name in names) {+ final key = keyNamed(name);+ expect(capOf(key), findsOneWidget, reason: name);+ final cap = capDecoration(tester, key);+ expect(cap.borderRadius, isNotNull, reason: name);+ expect(cap.color, isNot(tty.ground), reason: '$name stands off it');+ expect(cap.boxShadow, isNotEmpty, reason: '$name has an edge');++ final cell = tester.getRect(key), drawn = tester.getRect(capOf(key));+ expect(drawn.height, lessThan(cell.height), reason: name);+ expect(drawn.top, greaterThan(cell.top), reason: name);+ expect(drawn.bottom, lessThan(cell.bottom), reason: name);+ expect(drawn.width, cell.width, reason: name);+ // A 26pt cap, 5pt from the strip's top and bottom; the tap still+ // lands anywhere in the taller cell.+ expect(drawn.height, closeTo(26, 0.01), reason: name);+ expect(cell.height, closeTo(32, 0.01), reason: name);+ expect(drawn.top - bar.top, closeTo(5, 0.01), reason: name);+ expect(bar.bottom - drawn.bottom, closeTo(5, 0.01), reason: name);+ }+ });++ testWidgets('caps are 4pt apart and from the strip\'s edges, and share the '+ 'row by their parts', (tester) async {+ await pumpCaps(tester);+ final bar = tester.getRect(find.byType(TerminalKeyBar));+ final caps = [+ for (final name in names) tester.getRect(capOf(keyNamed(name))),+ ];++ expect(caps.first.left - bar.left, closeTo(4, 0.01));+ expect(bar.right - caps.last.right, closeTo(4, 0.01));+ for (var i = 1; i < caps.length; i++) {+ final gap = caps[i].left - caps[i - 1].right;+ // The rule's 6 + 1 + 6 sits before `Send image`.+ final expected = names[i] == 'Send image' ? 13.0 : 4.0;+ expect(gap, closeTo(expected, 0.01), reason: names[i]);+ }+ // 375pt less the edges, ten gaps, the rule and the gap past it, over+ // 9 keys × 3 parts, `clear` × 5, `img` × 3 and `▾` × 4.+ const part = (375 - 4 * 2 - 4 * 10 - 13 - 4) / 42;+ expect(caps.first.width, closeTo(part * 3, 0.01));+ expect(+ tester.getSize(capOf(keyNamed('Clear prompt'))).width,+ closeTo(part * 5, 0.01),+ );+ expect(+ tester.getSize(capOf(keyNamed('Hide keyboard'))).width,+ closeTo(part * 4, 0.01),+ );+ });++ testWidgets('▾ is a wider cap than the rest, and its glyph is drawn at its '+ 'own scale rather than shrunk to fit the cap', (tester) async {+ await pumpCaps(tester);+ final tty = ttyOf(tester);+ final hide = keyNamed('Hide keyboard');+ final glyph = find.descendant(of: hide, matching: find.text('▾'));++ expect(+ tester.getSize(capOf(hide)).width,+ greaterThan(tester.getSize(capOf(keyNamed('Send image'))).width),+ );+ // How large the glyph is drawn: its type size, times whatever the+ // FittedBox shrank it by to fit the cap.+ final size = tester.widget<Text>(glyph).style!.fontSize!;+ final shrunk =+ tester.getRect(glyph).height / tester.getSize(glyph).height;+ expect(shrunk, closeTo(1, 0.01), reason: 'fits the cap as it is');+ expect(size * shrunk, closeTo(tty.fontSize * 1.8, 0.01));+ expect(+ tester.getRect(glyph).height,+ lessThanOrEqualTo(tester.getSize(capOf(hide)).height),+ );+ });++ testWidgets('a held key lightens on the way down and lets go on the way '+ 'up; a finger that slides off sends nothing', (tester) async {+ await pumpCaps(tester);+ final esc = keyNamed('esc');+ final idle = capDecoration(tester, esc);++ final gesture = await tester.startGesture(tester.getCenter(esc));+ await tester.pump();+ final held = capDecoration(tester, esc);+ expect(held.color, isNot(idle.color));+ expect(held.boxShadow, isNull, reason: 'the key is down');++ await gesture.moveBy(const Offset(0, -200));+ await gesture.up();+ await tester.pump();+ expect(capDecoration(tester, esc).color, idle.color);+ expect(capDecoration(tester, esc).boxShadow, isNotEmpty);+ expect(outbound, isEmpty);++ await tapKey(tester, 'esc');+ expect(capDecoration(tester, esc).color, idle.color);+ expect(outbound, ['\x1b']);+ });++ testWidgets('an armed modifier is a reverse-video cap until it is spent', (+ tester,+ ) async {+ await pumpCaps(tester);+ final tty = ttyOf(tester);+ final ctrl = keyNamed('ctrl');+ final idle = capDecoration(tester, ctrl);++ await tapKey(tester, 'ctrl');+ final armed = capDecoration(tester, ctrl);+ expect(armed.color, tty.text);+ expect(armed.borderRadius, idle.borderRadius);+ expect(armed.boxShadow, isNull, reason: 'held down');+ expect(+ tester+ .widget<Text>(+ find.descendant(of: ctrl, matching: find.text('ctrl')),+ )+ .style+ ?.color,+ tty.ground,+ );++ await tapKey(tester, 'Up');+ expect(capDecoration(tester, ctrl).color, idle.color);+ expect(capDecoration(tester, ctrl).boxShadow, isNotEmpty);+ });++ testWidgets('while input is not taken the caps lie flat and fainter — but '+ 'the key that hides the keyboard', (tester) async {+ await pumpCaps(tester);+ final live = capDecoration(tester, keyNamed('esc'));++ await pumpCaps(tester, enabled: false);+ final dead = capDecoration(tester, keyNamed('esc'));+ expect(dead.color, isNot(live.color));+ expect(dead.boxShadow, isNull);+ expect(dead.borderRadius, live.borderRadius, reason: 'still a key');+ final hide = capDecoration(tester, keyNamed('Hide keyboard'));+ expect(hide.color, live.color);+ expect(hide.boxShadow, isNotEmpty);+ });++ // Every palette, light ones included: the chrome takes the app's+ // brightness, so a light ground is a light palette.+ test('a light palette is among them', () {+ expect(HarnessPalette.values.where((p) => !p.isDark), isNotEmpty);+ });+ for (final palette in HarnessPalette.values) {+ testWidgets('the caps stand off ${palette.name}\'s ground', (+ tester,+ ) async {+ final (paletteBefore, brightnessBefore) = (+ AppTheme.palette.value,+ AppTheme.brightness.value,+ );+ addTearDown(() {+ AppTheme.palette.value = paletteBefore;+ AppTheme.brightness.value = brightnessBefore;+ });+ AppTheme.palette.value = palette;+ AppTheme.brightness.value = palette.brightness;+ await pumpCaps(tester);+ final tty = ttyOf(tester);+ expect(tty.isLight, !palette.isDark);++ final idle = capDecoration(tester, keyNamed('esc')).color!;+ expect(idle, isNot(tty.ground));+ final gesture = await tester.startGesture(+ tester.getCenter(keyNamed('esc')),+ );+ await tester.pump();+ final held = capDecoration(tester, keyNamed('esc')).color!;+ await gesture.up();+ await tester.pump();+ // Each state a further step from the ground than the one before.+ double distance(Color color) =>+ (color.computeLuminance() - tty.ground.computeLuminance()).abs();+ expect(distance(held), greaterThan(distance(idle)));+ });+ }++ testWidgets('the pane\'s own keys are caps too, as wide as their words', (+ tester,+ ) async {+ await tester.pumpWidget(hintedBar(cycle));+ await tester.pumpAndSettle();++ final cap = find+ .ancestor(of: find.text('cycle'), matching: find.byType(DecoratedBox))+ .first;+ final decoration =+ tester.widget<DecoratedBox>(cap).decoration as BoxDecoration;+ expect(decoration.borderRadius, isNotNull);+ expect(decoration.boxShadow, isNotEmpty);+ expect(+ tester.getRect(cap).contains(tester.getCenter(find.text('cycle'))),+ isTrue,+ );+ expect(+ tester.getSize(cap).width,+ isNot(tester.getSize(capOf(esc)).width),+ );+ });++ // What Codex offers, as 0.156.1 and 0.161.0 print it.+ const codex = <String, (List<String>, List<String>)>{+ 'a queued question': (+ [' ? 1 question', ' shift+← to answer'],+ ['answer'],+ ),+ 'a queued question, 0.161.0': (+ [' ? 1 question', ' ⇧← to answer'],+ ['answer'],+ ),+ 'an open question\'s footer': (+ [' ctrl+] skip · ⌥+↓ main prompt · enter to submit'],+ ['skip', 'main prompt'],+ ),+ };++ for (final MapEntry(key: screen, value: (lines, words)) in codex.entries) {+ testWidgets('Codex\'s keys for $screen are caps on the strip, ahead of '+ 'its own keys, which keep their width', (tester) async {+ await pumpCaps(tester);+ final width = tester.getSize(keyNamed('esc')).width;++ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(+ body: Align(+ alignment: Alignment.bottomCenter,+ child: SizedBox(+ width: 375,+ child: TerminalKeyBar(+ terminal: terminal,+ enabled: true,+ enginePrompt: true,+ hints: parseKeyHints(lines),+ onDismissKeyboard: () {},+ onClearPrompt: () {},+ onPickImage: () {},+ ),+ ),+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();++ final bar = tester.getRect(find.byType(TerminalKeyBar));+ expect(bar.height, 36);+ for (final word in words) {+ final cap = find+ .ancestor(+ of: find.text(word),+ matching: find.byType(DecoratedBox),+ )+ .first;+ final decoration =+ tester.widget<DecoratedBox>(cap).decoration as BoxDecoration;+ expect(decoration.borderRadius, isNotNull, reason: word);+ expect(decoration.boxShadow, isNotEmpty, reason: word);+ final drawn = tester.getRect(cap);+ expect(drawn.height, closeTo(26, 0.01), reason: word);+ expect(drawn.top - bar.top, closeTo(5, 0.01), reason: word);+ expect(drawn.right, lessThan(tester.getRect(keyNamed('esc')).left));+ }+ expect(tester.getSize(keyNamed('esc')).width, width);+ expect(tester.takeException(), isNull);+ });+ }++ testWidgets(+ 'a hint dims with the strip: flat, fainter, and sends nothing',+ (tester) async {+ Future<BoxDecoration> answerCap({required bool enabled}) async {+ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(+ body: TerminalKeyBar(+ terminal: terminal,+ enabled: enabled,+ hints: queued,+ onDismissKeyboard: () {},+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ final cap = find+ .ancestor(+ of: find.text('answer'),+ matching: find.byType(DecoratedBox),+ )+ .first;+ return tester.widget<DecoratedBox>(cap).decoration as BoxDecoration;+ }++ final live = await answerCap(enabled: true);+ final dead = await answerCap(enabled: false);+ expect(dead.boxShadow, isNull);+ expect(dead.color, isNot(live.color));+ await tester.tap(find.text('answer'));+ await tester.pump();+ expect(outbound, isEmpty);+ },+ );+ });++ group('the pane\'s own keys, pressed', () {+ Widget bar({bool? ctrl, ValueChanged<bool>? armCtrl}) => MaterialApp(+ home: Scaffold(+ body: TerminalKeyBar(+ terminal: terminal,+ enabled: true,+ hints: queued,+ onDismissKeyboard: () {},+ onPromptEdited: () => edits++,+ ctrlArmed: ctrl,+ onArmCtrl: armCtrl,+ ),+ ),+ );++ testWidgets('a hint is the whole chord: armed modifiers are put down, '+ 'never added', (tester) async {+ await tester.pumpWidget(bar());+ await tester.pumpAndSettle();+ await tapKey(tester, 'ctrl');+ await tapKey(tester, 'shift');++ await tester.tap(find.text('answer'));+ await tester.pump();+ expect(outbound, ['\x1b[1;2D'], reason: 'shift+←, not ctrl+shift+←');++ // Spent: the key after it is plain — tab, not shift+tab (`\x1b[Z`).+ // Not an arrow: the hint at the head has pushed those out of view.+ await tapKey(tester, 'tab');+ expect(outbound, ['\x1b[1;2D', '\t']);+ });++ testWidgets('the session\'s ctrl is put down too', (tester) async {+ final armed = <bool>[];+ await tester.pumpWidget(bar(ctrl: true, armCtrl: armed.add));+ await tester.pumpAndSettle();++ await tester.tap(find.text('answer'));+ await tester.pump();+ expect(armed, [false]);+ expect(outbound, ['\x1b[1;2D']);+ });++ testWidgets('a hint lets go of the keyboard\'s buffer, as tab does', (+ tester,+ ) async {+ await tester.pumpWidget(bar());+ await tester.pumpAndSettle();++ await tester.tap(find.text('answer'));+ await tester.pump();+ expect(edits, 1);+ });+ });++ group('img', () {+ Widget bar({VoidCallback? pick, VoidCallback? photo}) => MaterialApp(+ home: Scaffold(+ body: Align(+ alignment: Alignment.bottomCenter,+ child: SizedBox(+ width: 375,+ child: TerminalKeyBar(+ terminal: terminal,+ enabled: true,+ enginePrompt: true,+ onDismissKeyboard: () {},+ onPickImage: pick,+ onTakePhoto: photo,+ ),+ ),+ ),+ ),+ );+ final image = find.byKey(const ValueKey('terminal-key-Send image'));+ final newline = find.byKey(const ValueKey('terminal-key-Newline'));+ final hide = find.byKey(const ValueKey('terminal-key-Hide keyboard'));++ testWidgets('is not drawn for a CLI that cannot take a picture, and the '+ 'rule goes with it', (tester) async {+ await tester.pumpWidget(bar());+ expect(image, findsNothing);+ expect(hide, findsOneWidget);+ // One gap where the rule stood: nothing left to set apart.+ expect(+ tester.getTopLeft(hide).dx - tester.getTopRight(newline).dx,+ closeTo(4, 0.01),+ );+ expect(+ find.byWidgetPredicate(+ (w) => w is Container && w.constraints?.maxWidth == 1,+ ),+ findsNothing,+ );+ });++ testWidgets('with both ways to send one, a sheet asks which', (+ tester,+ ) async {+ var picks = 0, photos = 0;+ await tester.pumpWidget(bar(pick: () => picks++, photo: () => photos++));+ await tester.tap(image);+ await tester.pumpAndSettle();+ expect(find.text('Choose from library'), findsOneWidget);+ expect(find.text('Take a photo'), findsOneWidget);++ await tester.tap(find.text('Take a photo'));+ await tester.pumpAndSettle();+ expect((picks, photos), (0, 1));+ expect(outbound, isEmpty, reason: 'nothing typed at the agent');+ });+ });++ group('paste comes and goes with the clipboard', () {+ // What `Clipboard.hasStrings` answers: null throws, as a platform that+ // cannot say.+ late bool? holdsText;+ late List<String> asked;++ setUp(() {+ holdsText = false;+ asked = [];+ final messenger =+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;+ messenger.setMockMethodCallHandler(SystemChannels.platform, (call) async {+ asked.add(call.method);+ if (call.method != 'Clipboard.hasStrings') return null;+ final holds = holdsText;+ if (holds == null) throw PlatformException(code: 'unavailable');+ return {'value': holds};+ });+ addTearDown(+ () => messenger.setMockMethodCallHandler(SystemChannels.platform, null),+ );+ });++ final paste = find.byKey(const ValueKey('terminal-key-Paste'));+ final clear = find.byKey(const ValueKey('terminal-key-Clear prompt'));+ late int pastes;++ Future<void> pumpPaste(WidgetTester tester) async {+ pastes = 0;+ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(+ body: Align(+ alignment: Alignment.bottomCenter,+ child: SizedBox(+ width: 375,+ child: TerminalKeyBar(+ terminal: terminal,+ enabled: true,+ onDismissKeyboard: () {},+ onPromptEdited: () => edits++,+ onClearPrompt: () {},+ onPaste: () => pastes++,+ ),+ ),+ ),+ ),+ ),+ );+ await tester.pump();+ }++ /// One turn of the strip's clipboard poll.+ Future<void> nextPoll(WidgetTester tester) async {+ await tester.pump(const Duration(seconds: 1));+ await tester.pump();+ }++ /// Takes the strip down, and its poll with it.+ Future<void> done(WidgetTester tester) =>+ tester.pumpWidget(const SizedBox());++ testWidgets('drawn only while the clipboard holds something, beside '+ 'clear, and pressed it pastes', (tester) async {+ await pumpPaste(tester);+ expect(paste, findsNothing);++ holdsText = true;+ await nextPoll(tester);+ expect(paste, findsOneWidget);+ expect(+ tester.getTopLeft(paste).dx - tester.getTopRight(clear).dx,+ closeTo(4, 0.01),+ );+ expect(tester.getSize(paste).width, tester.getSize(clear).width);++ await tester.tap(paste);+ await tester.pump();+ expect(pastes, 1);+ expect(edits, 1, reason: 'the keyboard lets go of what it held');++ holdsText = false;+ await nextPoll(tester);+ expect(paste, findsNothing);+ // ⚠️ Asked, never read: a read would bring up iOS's "Allow Paste".+ expect(asked, isNot(contains('Clipboard.getData')));+ await done(tester);+ });++ testWidgets('a clipboard that cannot answer leaves the key as it was', (+ tester,+ ) async {+ holdsText = true;+ await pumpPaste(tester);+ expect(paste, findsOneWidget);++ holdsText = null;+ await nextPoll(tester);+ expect(paste, findsOneWidget, reason: 'no flicker on an error');+ expect(tester.takeException(), isNull);+ await done(tester);+ });++ testWidgets('not asked in the background; asked at once on the way back', (+ tester,+ ) async {+ addTearDown(+ () => tester.binding.handleAppLifecycleStateChanged(+ AppLifecycleState.resumed,+ ),+ );+ await pumpPaste(tester);+ expect(paste, findsNothing);++ tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive);+ tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.hidden);+ tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.paused);+ asked.clear();+ holdsText = true;+ await nextPoll(tester);+ expect(asked, isEmpty, reason: 'Android hands a background app nothing');+ expect(paste, findsNothing);++ tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.hidden);+ tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive);+ tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);+ await tester.pump();+ await tester.pump();+ expect(paste, findsOneWidget, reason: 'without waiting for the poll');+ await done(tester);+ });+ });}