Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

8.2 KB
Raw Blame
import 'package:xterm/xterm.dart';

import 'key_chord.dart';

/// A key Codex's own chrome offers — `ctrl+] skip`, `⌥+↓ main prompt` — that a
/// phone has no way to press.
///
/// ⚠️ **Why read them off the screen at all.** A phone keyboard has no Shift,
/// Ctrl, Alt or function keys to hold, and the key strip carries only the
/// handful of keys every pane needs. What Codex binds to those modifiers
/// changes between versions and is the person's to remap (`tui.keymap`) — so
/// the key it prints next to what it does is the one reliable source for the
/// key. WHICH hints become buttons is not read off the screen, though: see
/// [_offered]. Measured on Codex 0.156.1, where the chords that stranded a
/// phone were `shift+←` (a queued question) and `ctrl+]` and `⌥+↓` (leaving
/// one).
class KeyHint {
  const KeyHint({
    required this.chord,
    required this.keyText,
    required this.action,
  });

  final KeyChord chord;

  /// The key as the chrome printed it — `ctrl+]`, `⌥+↓`, `⇧←`, `shift + ←` —
  /// for the button to repeat word for word, so it reads as the hint beside it
  /// rather than as a translation of it.
  final String keyText;

  /// What the hint says the key does, as the CLI worded it — `cycle`,
  /// `main prompt`.
  final String action;

  /// Whether the key strip draws this one AFTER its own keys rather than
  /// before them — see `TerminalKeyBar.hints`.
  ///
  /// ⚠️ **Only Claude Code's `shift+tab to cycle`.** It is on every prompt, so
  /// at the head of the strip it would push the arrows off the edge for good;
  /// at the end it is a swipe away and the strip opens as it always did. Every
  /// other hint is a key a screen is asking for right now — a queued question's
  /// `shift+← to answer` — and leads the strip.
  bool get trails => _trailing.hasMatch(action);

  @override
  bool operator ==(Object other) =>
      other is KeyHint &&
      other.chord == chord &&
      other.keyText == keyText &&
      other.action == action;

  @override
  int get hashCode => Object.hash(chord, keyText, action);

  @override
  String toString() => '$keyText $action';
}

/// How many of the pane's last non-blank lines count as its live chrome.
///
/// ⚠️ **Only the bottom, never the transcript.** Codex draws its live chrome —
/// the status line, a dialog's footer, the queue's `shift+← to answer` —
/// under everything else; what is above is conversation, where a model
/// explaining a shortcut would otherwise grow a button. Five reaches the
/// queue's hint over the composer and a status line wrapped onto two lines on
/// a phone-width pane.
const int _chromeLines = 5;

/// How far up from the bottom the walk may go looking for those lines.
///
/// ⚠️ A whole phone pane and more, not a handful: a short conversation leaves
/// every row under its prompt blank, and on a 50-row pane that is most of the
/// screen. Skipping a blank row costs nothing.
const int _chromeScan = 60;

/// The most hints offered at once. More would be a second key strip, and the
/// point is the one or two a screen is actually asking for.
const int _maxHints = 4;

/// A key as the chrome writes one: modifiers joined to a key by `+`, or a bare
/// function key. Modifiers are required for everything else — a plain `esc`
/// or `tab` is a key the phone already has.
///
/// ⚠️ **Both spellings, old and new.** Codex 0.156.1 writes a modifier joined
/// by `+` (`shift+←`, `⌥+↓`); 0.161.0 writes the macOS glyph straight onto
/// the key (`⇧← to answer`), and its glyph keys too (`⇥`, `⏎`). A pattern that
/// knew only the first read the queued question's key as no key at all: the
/// queue was seen, and the strip offered nothing to open it with. The bare
/// glyph and the glyph keys are added alongside, never in place of, the `+`
/// form — either CLI may be on the far side.
final RegExp _chord = RegExp(
  r'(?<![\w+])'
  r'((?:(?:shift|ctrl|control|alt|option|opt|meta|[⇧⌃⌥])\s*\+\s*|[⇧⌃⌥])+'
  r"(?:tab|enter|return|esc|escape|space|backspace|delete|del|up|down|left|right|home|end|pageup|pagedown|pgup|pgdn|f(?:1[0-2]|[1-9])|[←→↑↓]|[⇥⏎↵⌫]|[a-z0-9]|[\]\[\\/.,;'`=\-])"
  r'|f(?:1[0-2]|[1-9]))'
  r'(?![\w])',
  caseSensitive: false,
);

/// What follows a key: `to cycle`, `skip`, `main prompt` — words joined by
/// single spaces, ended by the separators the chrome puts between hints
/// (`·`, `|`, a bracket, a comma, a run of spaces) or by the line's end.
final RegExp _action = RegExp(
  r"^\s*(?:to\s+)?([a-z][a-z']*(?: [a-z][a-z']*){0,2})",
  caseSensitive: false,
);

/// Chords never offered as a button, however the chrome describes them: the
/// process-control keys. One tap from a glance must not be the key that quits
/// the agent, drops its session or suspends it.
bool _isProcessControl(KeyChord chord) =>
    chord.ctrl &&
    !chord.alt &&
    !chord.shift &&
    chord.key == null &&
    const {'c', 'd', 'z', '\\'}.contains(chord.char);

/// The hints offered as buttons, by what Codex says each one does — every
/// other hint on the pane is left as text.
///
/// ⚠️ **A list, not a rule.** Reading every `key + words` pair off the chrome
/// turned tips and one-off shortcuts into buttons (`f3 search this
/// conversation`, `shift+tab to cycle`) that crowded the key strip for keys
/// nobody needed from a phone. These are the ones a phone is stranded
/// without, from Codex 0.156.1 and 0.157.0:
///
/// - `shift+← to answer` — open a queued async question;
/// - `ctrl+] skip`, `⌥+↓ main prompt` / `prev question`, `shift+← next
///   question` — move through an open one, or leave it;
/// - `shift+← edit last queued message` — take back a queued message;
/// - `ctrl+o copy` — the warnings view;
/// - `ctrl+t to view transcript`;
/// - `shift+tab to cycle` — Claude Code's modes (plan, accept edits), one tap instead of two.
///
/// Matched on the WORDS, never the key: the key is the person's to remap, and
/// the one printed beside the words is the one pressed.
final RegExp _offered = RegExp(
  r'^(answer|skip|main prompt|next question|prev(ious)? question|edit last queued|copy|view transcript|cycle)\b',
  caseSensitive: false,
);

/// The [_offered] hints drawn after the key strip's own keys — see
/// [KeyHint.trails].
final RegExp _trailing = RegExp(r'^cycle\b', caseSensitive: false);

/// Whether a phone can already press [chord] — the software keyboard or the
/// key strip has it — so a hint for it would only repeat a key on screen.
bool _phoneHas(KeyChord chord) {
  if (chord.modified) return false;
  final key = chord.key;
  if (key == null) return true;
  return const {
    TerminalKey.escape,
    TerminalKey.tab,
    TerminalKey.enter,
    TerminalKey.space,
    TerminalKey.backspace,
    TerminalKey.arrowLeft,
    TerminalKey.arrowRight,
    TerminalKey.arrowUp,
    TerminalKey.arrowDown,
  }.contains(key);
}

/// The hints in the pane's live chrome that a phone cannot press itself, in
/// reading order, one per key.
List<KeyHint> parseKeyHints(List<String> lines) {
  final chrome = <String>[];
  for (
    var i = lines.length - 1;
    i >= 0 && lines.length - i <= _chromeScan && chrome.length < _chromeLines;
    i--
  ) {
    if (lines[i].trim().isNotEmpty) chrome.insert(0, lines[i]);
  }
  final hints = <KeyHint>[];
  for (final line in chrome) {
    for (final match in _chord.allMatches(line)) {
      final chord = KeyChord.parse(match.group(1)!);
      if (chord == null ||
          !chord.sendable ||
          _phoneHas(chord) ||
          _isProcessControl(chord)) {
        continue;
      }
      final words = _action.firstMatch(line.substring(match.end));
      // A key with nothing said about it is a name in a sentence, not a hint.
      if (words == null) continue;
      final action = words.group(1)!.toLowerCase();
      if (!_offered.hasMatch(action)) continue;
      if (hints.any((hint) => hint.chord == chord)) continue;
      hints.add(
        KeyHint(
          chord: chord,
          // Spacing collapsed, nothing else touched: `shift + ←` stays as the
          // pane drew it.
          keyText: match.group(1)!.trim().replaceAll(RegExp(r'\s+'), ' '),
          action: action,
        ),
      );
      if (hints.length == _maxHints) return hints;
    }
  }
  return hints;
}