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.

32.0 KB
Raw Blame
import 'package:flutter/foundation.dart';

import '../logging/debug_surface.dart';
import '../super_tabs/buddy_chat.dart' show kBuddyChat;
import 'app_shortcuts.dart';
import 'keymap.dart';
import 'keymap_keyboard.dart';

/// Stable identities connect search to workspace actions. The same catalog
/// supplies the file-remapping foundation; native runtime wiring is separate.
class HarnessCommand {
  const HarnessCommand(
    this.id,
    this.label,
    this.group, {
    this.extraKeys = const [],
    this.keywords = const [],
    this.action,
    this.nativeAction,
    this.context = KeymapContext.workspace,
    this.repeatable = false,
    this.hidden = false,
    this.daemon = false,
  });
  final String id, label;
  final ShortcutGroup group;
  final List<String> extraKeys;
  final List<String> keywords;

  /// Workspace defaults come from the live shortcut table. A command cannot
  /// quietly propose different keys from the ones the user already uses.
  List<String> get keys {
    // The Swarm chat's own letters are Cmd's on a Mac and Ctrl's elsewhere,
    // as in a browser: no terminal is there to take Ctrl.
    if (const {'swarm.quick_switcher': 'k', 'swarm.find_in_chat': 'f'}[id]
        case final letter?) {
      return [
        defaultTargetPlatform == TargetPlatform.macOS
            ? 'cmd+$letter'
            : 'ctrl+$letter',
      ];
    }
    // Cmd-Alt-T cannot collapse to Alt-T in a browser: that is New Tab.
    // Use the companion chord already used by the other Alt-prefix platform.
    if (kIsWeb && id == 'app.daemon_talk') return const ['alt+shift+a'];
    if (!kIsWeb && defaultTargetPlatform == TargetPlatform.linux) {
      final linux = linuxAltCommandKeys[id];
      if (linux != null) return linux;
    }
    if (ctrlWorkspacePrefix) {
      final windows = windowsCommandKeys[id];
      if (windows != null) return windows;
    }
    return action == null
        ? extraKeys.map(platformWorkspaceBinding).toList(growable: false)
        : _workspaceKeys[action] ?? const [];
  }

  /// Ctrl twins of Mac defaults. Existing Windows keys still take precedence.
  List<String> get outsideTerminalKeys {
    if (!ctrlWorkspacePrefix) return const [];
    return action == null
        ? [
            for (final keys in extraKeys)
              if (!keys.contains(' '))
                ?windowsCtrlAliasForStroke(KeyStroke.parse(keys)),
          ]
        : [
            for (final shortcut in [...kAppShortcuts, ...kSwarmShortcuts])
              if (shortcut.action == action)
                ?windowsCtrlAlias(shortcut.activator),
          ];
  }

  final ShortcutAction? action;
  final String? nativeAction;
  final KeymapContext context;
  final bool repeatable;

  /// Review commands still use the shared keymap, but stay out of normal help.
  final bool hidden;

  /// One of the daemon's (daemons/README.md): it exists only while this
  /// window has daemons ([daemonCommandsActive]).
  final bool daemon;
}

/// Whether the daemon's commands exist in this window: only while daemons are
/// on (daemons/README.md, "Off switches"). Off, they are not bound at all:
/// their keys (⌘⌥T) reach the pane as they did before daemons existed, and
/// they are in no list, no help and no native keymap. The workspace sets it.
final daemonCommandsActive = ValueNotifier<bool>(false);

/// What a person looking for Agent Messages may type, older names included.
const _agentMessagesKeywords = [
  'agent messages',
  'harness send',
  'message',
  'log',
  'tab',
  'collaborate',
  'communicate',
  'swarm',
  'team',
  'channel',
];

/// What a person looking for a shared tab's commands may type.
const _sharedTabKeywords = [
  'shared tab',
  'share',
  'invite',
  'people',
  'member',
  'collaborate',
  'account',
];

/// Whether [id] is a command this window has now.
bool harnessCommandActive(String id) =>
    harnessCommandById[id]?.daemon != true || daemonCommandsActive.value;

final _workspaceKeysByPlatform =
    <TargetPlatform, Map<ShortcutAction, List<String>>>{};
Map<ShortcutAction, List<String>> get _workspaceKeys => _workspaceKeysByPlatform
    .putIfAbsent(defaultTargetPlatform, _readWorkspaceKeys);
Map<ShortcutAction, List<String>> _readWorkspaceKeys() {
  final result = <ShortcutAction, List<String>>{};
  for (final shortcut in appShortcuts()) {
    final keys = keyStrokeFor(
      shortcut.activator.trigger,
      command: shortcut.activator.meta,
      control: shortcut.activator.control,
      alt: shortcut.activator.alt,
      shift: shortcut.activator.shift,
    )!.toString();
    (result[shortcut.action] ??= []).add(keys);
  }
  return result;
}

final harnessCommands = <HarnessCommand>[
  const HarnessCommand(
    'navigation.commands',
    'Search commands',
    ShortcutGroup.actions,
    extraKeys: ['cmd+shift+p'],
    nativeAction: 'commands',
  ),
  const HarnessCommand(
    'swarm.new',
    'New Tab',
    ShortcutGroup.navigate,
    action: ShortcutAction.newSwarm,
    nativeAction: 'new',
    keywords: ['tab'],
  ),
  const HarnessCommand(
    'swarm.close',
    'Close Tab',
    ShortcutGroup.navigate,
    action: ShortcutAction.closeSwarm,
    nativeAction: 'closeActive',
    keywords: ['tab'],
  ),
  // The live table binds no chord to it any more (⌘⇧T is New Terminal), so
  // `keys` comes back empty: a palette and menu command a person may give a
  // key of their own in keybindings.jsonc.
  const HarnessCommand(
    'swarm.reopen',
    'Reopen closed tab or pane',
    ShortcutGroup.navigate,
    action: ShortcutAction.reopenClosedSwarm,
    nativeAction: 'reopen',
    keywords: ['tab'],
  ),
  const HarnessCommand(
    'swarm.next',
    'Next Tab',
    ShortcutGroup.navigate,
    action: ShortcutAction.nextSwarm,
    nativeAction: 'next',
    keywords: ['tab'],
    repeatable: true,
  ),
  const HarnessCommand(
    'swarm.previous',
    'Previous Tab',
    ShortcutGroup.navigate,
    action: ShortcutAction.previousSwarm,
    nativeAction: 'previous',
    keywords: ['tab'],
    repeatable: true,
  ),
  const HarnessCommand(
    'swarm.rename',
    'Rename Tab',
    ShortcutGroup.actions,
    action: ShortcutAction.renameSwarm,
    nativeAction: 'renameActive',
    keywords: ['tab'],
  ),
  const HarnessCommand(
    'navigation.back',
    'Go back',
    ShortcutGroup.navigate,
    action: ShortcutAction.previousAgent,
    nativeAction: 'historyBack',
    repeatable: true,
  ),
  const HarnessCommand(
    'navigation.forward',
    'Go forward',
    ShortcutGroup.navigate,
    action: ShortcutAction.nextAgent,
    nativeAction: 'historyForward',
    repeatable: true,
  ),
  const HarnessCommand(
    'navigation.history',
    'Show full history',
    ShortcutGroup.navigate,
    action: ShortcutAction.showHistory,
    nativeAction: 'showHistory',
  ),
  const HarnessCommand(
    'navigation.needs_input',
    'Show harnesses needing input',
    ShortcutGroup.navigate,
    action: ShortcutAction.showAttention,
    nativeAction: 'notifications',
  ),
  const HarnessCommand(
    'swarm.quick_switcher',
    'Switch conversation',
    ShortcutGroup.navigate,
    context: KeymapContext.swarmChat,
    keywords: ['Swarm', 'chat', 'people', 'agents'],
  ),
  // Slack's next and previous unread chat, in the sidebar's order. Only the
  // Swarm chat has them: in a pane, Alt+Shift+arrows still move it where Alt
  // is the workspace key (Linux, the web, Windows).
  const HarnessCommand(
    'swarm.next_unread',
    'Next unread chat',
    ShortcutGroup.navigate,
    extraKeys: ['alt+shift+down'],
    context: KeymapContext.swarmChat,
    keywords: ['unread', 'chat', 'Swarm', 'Slack'],
    repeatable: true,
  ),
  const HarnessCommand(
    'swarm.previous_unread',
    'Previous unread chat',
    ShortcutGroup.navigate,
    extraKeys: ['alt+shift+up'],
    context: KeymapContext.swarmChat,
    keywords: ['unread', 'chat', 'Swarm', 'Slack'],
    repeatable: true,
  ),
  // Find in the open chat or thread (task #2826). A focused terminal keeps
  // the same key for its own find.
  const HarnessCommand(
    'swarm.find_in_chat',
    'Find in chat',
    ShortcutGroup.navigate,
    context: KeymapContext.swarmChat,
    keywords: ['find', 'search', 'chat', 'Swarm'],
  ),
  // The current project's Buddy chat, in a Swarm tab, where the PM's private
  // lines land since Buddies replaced Chat with PM: the id stays, so a key a
  // person bound to it keeps working. K for "talk": free on every platform
  // (Alt+Shift+K on Linux, the web and Windows).
  const HarnessCommand(
    'swarm.chat_with_pm',
    kBuddyChat,
    ShortcutGroup.navigate,
    extraKeys: ['cmd+shift+k'],
    keywords: ['Buddy', 'product manager', 'PM', 'Swarm'],
  ),
  for (var i = 1; i <= 9; i++)
    HarnessCommand(
      'swarm.select_$i',
      'Select tab $i',
      ShortcutGroup.navigate,
      keywords: const ['tab'],
      extraKeys: ['cmd+$i'],
    ),
  for (var i = 1; i <= 9; i++)
    HarnessCommand('pane.focus_$i', 'Focus pane $i', ShortcutGroup.panes),
  const HarnessCommand(
    'pane.focus_left',
    'Focus the pane to the left',
    ShortcutGroup.panes,
    action: ShortcutAction.focusPaneLeft,
    repeatable: true,
  ),
  const HarnessCommand(
    'pane.focus_right',
    'Focus the pane to the right',
    ShortcutGroup.panes,
    action: ShortcutAction.focusPaneRight,
    repeatable: true,
  ),
  const HarnessCommand(
    'pane.focus_above',
    'Focus the pane above',
    ShortcutGroup.panes,
    action: ShortcutAction.focusPaneAbove,
    repeatable: true,
  ),
  const HarnessCommand(
    'pane.focus_below',
    'Focus the pane below',
    ShortcutGroup.panes,
    action: ShortcutAction.focusPaneBelow,
    repeatable: true,
  ),
  const HarnessCommand(
    'pane.move_left',
    'Move the pane left',
    ShortcutGroup.panes,
    action: ShortcutAction.movePaneLeft,
    repeatable: true,
  ),
  const HarnessCommand(
    'pane.move_right',
    'Move the pane right',
    ShortcutGroup.panes,
    action: ShortcutAction.movePaneRight,
    repeatable: true,
  ),
  const HarnessCommand(
    'pane.move_up',
    'Move the pane up',
    ShortcutGroup.panes,
    action: ShortcutAction.movePaneUp,
    repeatable: true,
  ),
  const HarnessCommand(
    'pane.move_down',
    'Move the pane down',
    ShortcutGroup.panes,
    action: ShortcutAction.movePaneDown,
    repeatable: true,
  ),
  const HarnessCommand(
    'pane.move_to_tab',
    'Move the pane to another tab',
    ShortcutGroup.panes,
    action: ShortcutAction.movePaneToTab,
    nativeAction: 'movePaneToTab',
    keywords: ['send', 'tab', 'another'],
  ),
  const HarnessCommand(
    'pane.zoom',
    'Zoom or restore the focused pane',
    ShortcutGroup.panes,
    action: ShortcutAction.zoomPane,
    nativeAction: 'zoomPane',
  ),
  const HarnessCommand(
    'pane.close',
    'Close the focused pane',
    ShortcutGroup.panes,
    action: ShortcutAction.closePane,
    nativeAction: 'closePane',
  ),
  const HarnessCommand(
    'pane.last',
    'Return to the last pane',
    ShortcutGroup.panes,
    action: ShortcutAction.lastPane,
  ),
  const HarnessCommand(
    'pane.pin',
    'Pin or unpin the focused pane',
    ShortcutGroup.panes,
    action: ShortcutAction.pinPane,
    nativeAction: 'pinPane',
  ),
  const HarnessCommand(
    'pane.layout',
    'Choose a layout',
    ShortcutGroup.panes,
    action: ShortcutAction.showLayout,
    nativeAction: 'layout',
  ),
  const HarnessCommand('pane.resize', 'Resize panes', ShortcutGroup.panes),
  const HarnessCommand(
    'pane.split_right',
    'Split right…',
    ShortcutGroup.panes,
    extraKeys: ['cmd+r'],
    nativeAction: 'splitRight',
  ),
  const HarnessCommand(
    'pane.split_down',
    'Split down…',
    ShortcutGroup.panes,
    extraKeys: ['cmd+d'],
    nativeAction: 'splitDown',
  ),
  const HarnessCommand(
    'pane.reset_sizes',
    'Reset pane sizes',
    ShortcutGroup.panes,
  ),
  const HarnessCommand(
    'terminal.find',
    'Find in the focused terminal',
    ShortcutGroup.navigate,
    action: ShortcutAction.findTerminal,
    nativeAction: 'findTerminal',
  ),
  const HarnessCommand(
    'terminal.find_next',
    'Next terminal match',
    ShortcutGroup.navigate,
    action: ShortcutAction.findNext,
    nativeAction: 'findNext',
    repeatable: true,
  ),
  const HarnessCommand(
    'terminal.find_previous',
    'Previous terminal match',
    ShortcutGroup.navigate,
    action: ShortcutAction.findPrevious,
    nativeAction: 'findPrevious',
    repeatable: true,
  ),
  const HarnessCommand(
    // Keep this existing command ID for saved keybindings; it opens # Projects.
    'agent.open',
    'Open Project',
    ShortcutGroup.actions,
    action: ShortcutAction.addAgent,
    nativeAction: 'addAgent',
    keywords: ['project', 'folder', 'repository', 'pane'],
  ),
  const HarnessCommand('agent.add', 'New Pane', ShortcutGroup.actions),
  const HarnessCommand(
    'agent.new',
    'New Harness',
    ShortcutGroup.actions,
    action: ShortcutAction.newAgent,
    nativeAction: 'newAgent',
  ),
  const HarnessCommand('agent.rename', 'Rename Harness', ShortcutGroup.actions),
  const HarnessCommand(
    'agent.work',
    'Branches and pull requests',
    ShortcutGroup.actions,
    keywords: [
      'branch',
      'branches',
      'pull requests',
      'git',
      'worktree',
      'history',
    ],
  ),
  const HarnessCommand('agent.stop', 'Stop Harness', ShortcutGroup.actions),
  // Stop keeps the conversation to reopen; Delete removes it for good.
  const HarnessCommand(
    'agent.delete',
    'Delete Harness',
    ShortcutGroup.actions,
    keywords: ['remove', 'purge', 'forget', 'conversation'],
  ),
  const HarnessCommand(
    'app.product_feedback',
    'Rate task outcome',
    ShortcutGroup.actions,
    keywords: ['feedback', 'completed', 'useful', 'problem'],
  ),
  const HarnessCommand('agent.fork', 'Fork Harness', ShortcutGroup.actions),
  const HarnessCommand(
    'agent.share',
    'Share Harness',
    ShortcutGroup.actions,
    action: ShortcutAction.shareAgent,
    keywords: ['link', 'public', 'private', 'invite', 'collaborate'],
    nativeAction: 'shareAgent',
  ),
  const HarnessCommand(
    'pane.toggle_viewer',
    'Toggle Viewer',
    ShortcutGroup.panes,
    nativeAction: 'toggleViewer',
  ),
  const HarnessCommand(
    'pane.toggle_composer',
    'Toggle Message Composer',
    ShortcutGroup.panes,
    nativeAction: 'toggleComposer',
  ),
  const HarnessCommand(
    'agent.clone',
    'Clone Harness',
    ShortcutGroup.actions,
    action: ShortcutAction.cloneAgent,
    nativeAction: 'cloneAgent',
    keywords: ['duplicate', 'another', 'fresh'],
  ),
  const HarnessCommand(
    'agent.restart',
    'Restart Harness',
    ShortcutGroup.actions,
    action: ShortcutAction.restartAgent,
    nativeAction: 'restartAgent',
    keywords: ['again', 'relaunch', 'resume'],
  ),
  const HarnessCommand(
    'terminal.new',
    'New Terminal',
    ShortcutGroup.actions,
    action: ShortcutAction.newTerminal,
    nativeAction: 'newTerminal',
  ),
  // The id is a user's keybinding and does not move; the label is the app's name.
  const HarnessCommand(
    'machines.manage',
    'Open Machine Monitor',
    ShortcutGroup.actions,
    nativeAction: 'manageMachines',
  ),
  const HarnessCommand(
    'machines.list',
    'Open Machines',
    ShortcutGroup.actions,
    nativeAction: 'machineList',
    extraKeys: ['cmd+m'],
  ),
  const HarnessCommand(
    'models.list',
    'Open Models',
    ShortcutGroup.actions,
    nativeAction: 'models',
    extraKeys: ['cmd+i'],
    keywords: ['local', 'AI', 'model', 'intelligence'],
  ),
  const HarnessCommand(
    'machine.link',
    'Connect another machine',
    ShortcutGroup.actions,
    nativeAction: 'linkMachine',
  ),
  const HarnessCommand(
    'harnesses.list',
    'Open Harness',
    ShortcutGroup.actions,
    nativeAction: 'sessions',
    extraKeys: ['cmd+p'],
    keywords: ['open', 'resume', 'existing', 'running', 'paused', 'sessions'],
  ),
  const HarnessCommand(
    'project.add',
    'Add project',
    ShortcutGroup.actions,
    nativeAction: 'addProject',
  ),
  const HarnessCommand(
    'harnesses.manage',
    'Manage harnesses',
    ShortcutGroup.actions,
    keywords: ['running', 'paused', 'sessions'],
  ),
  const HarnessCommand(
    'machines.connections',
    'Machine connection settings',
    ShortcutGroup.actions,
    keywords: ['password', 'connect', 'link'],
  ),
  const HarnessCommand(
    'models.manage',
    'Your models',
    ShortcutGroup.actions,
    keywords: ['download', 'start', 'stop', 'local', 'API'],
  ),
  const HarnessCommand(
    'machines.refresh',
    'Refresh machines and harnesses',
    ShortcutGroup.actions,
    action: ShortcutAction.reload,
    nativeAction: 'reload',
  ),
  const HarnessCommand(
    'task.route',
    'Boss mode: route a task',
    ShortcutGroup.actions,
    action: ShortcutAction.routeTask,
  ),
  const HarnessCommand(
    'project.orchestrate',
    'Create with the orchestrator',
    ShortcutGroup.actions,
    action: ShortcutAction.orchestrate,
  ),
  // Agent Messages (docs/design/2026-10-10-agent-messages.md): the active
  // tab's log; its native menu row is File's. There is no turning it on or
  // off for a tab: that is the account's, in Settings ▸ Experimental.
  const HarnessCommand(
    'agent_messages.show',
    'Show Agent Messages',
    ShortcutGroup.actions,
    nativeAction: 'showAgentMessages',
    keywords: _agentMessagesKeywords,
  ),
  // The active tab's Tab Activity sidebar, opened or closed: its native row
  // is View's, which says Show or Hide as it stands.
  const HarnessCommand(
    'agent_messages.activity',
    'Show Tab Activity',
    ShortcutGroup.actions,
    nativeAction: 'toggleTabActivity',
    extraKeys: ['cmd+shift+y'],
    keywords: [
      'tab activity',
      'sidebar',
      'hide',
      'harnesses',
      'tasks',
      'leader',
      'summary',
    ],
  ),
  // The focused harness leads its tab, or stops: its native row is File's
  // Make Leader / Remove Leader, which swaps its title.
  const HarnessCommand(
    'agent_messages.make_leader',
    'Make Leader',
    ShortcutGroup.actions,
    keywords: ['lead', 'leader', 'agent messages', 'tasks'],
  ),
  const HarnessCommand(
    'agent_messages.remove_leader',
    'Remove Leader',
    ShortcutGroup.actions,
    keywords: ['lead', 'leader', 'agent messages', 'tasks'],
  ),
  // Shared tabs (1c): the active tab, by role, as its tab menu and File offer
  // them; each is here so none needs a menu. Move Tab Here only in a native
  // window, on another of the owner's computers.
  const HarnessCommand(
    'shared_tab.invite',
    'Invite People…',
    ShortcutGroup.actions,
    nativeAction: 'invitePeople',
    keywords: _sharedTabKeywords,
  ),
  const HarnessCommand(
    'shared_tab.stop',
    'Stop Sharing Tab',
    ShortcutGroup.actions,
    nativeAction: 'stopSharingTab',
    keywords: _sharedTabKeywords,
  ),
  const HarnessCommand(
    'shared_tab.leave',
    'Leave Tab',
    ShortcutGroup.actions,
    nativeAction: 'leaveTab',
    keywords: _sharedTabKeywords,
  ),
  const HarnessCommand(
    'shared_tab.move_here',
    'Move Tab Here',
    ShortcutGroup.actions,
    nativeAction: 'moveTabHere',
    keywords: _sharedTabKeywords,
  ),
  const HarnessCommand(
    'app.customize',
    'Appearance',
    ShortcutGroup.actions,
    nativeAction: 'customize',
    // It was Customize Harness; its panel's tabs are Status, Workspace, Wallpaper and Terminal.
    keywords: [
      'customize',
      'theme',
      'colors',
      'palette',
      'wallpaper',
      'status',
      'font',
    ],
  ),
  const HarnessCommand(
    'pane.toggle_shading',
    'Toggle pane shading',
    ShortcutGroup.panes,
    extraKeys: ['cmd+shift+f'],
    keywords: ['focus', 'shade', 'dim', 'appearance'],
  ),
  const HarnessCommand(
    'app.store',
    'Harness Store',
    ShortcutGroup.actions,
    extraKeys: ['cmd+ctrl+s'],
    keywords: ['install', 'browse harnesses', 'packages', 'extensions'],
    nativeAction: 'store',
  ),
  const HarnessCommand(
    'app.daemon',
    'Daemon',
    ShortcutGroup.actions,
    keywords: ['hatch', 'egg', 'zoo', 'pair', 'nap', 'buddy', 'companion'],
    nativeAction: 'daemon',
    daemon: true,
  ),
  // ⌘⌥Space is macOS's Finder search; ⌘⌥ plus y, n, s or g answers the
  // daemon's line. T for talk.
  const HarnessCommand(
    'app.daemon_talk',
    'Talk to daemon',
    ShortcutGroup.actions,
    extraKeys: ['cmd+alt+t'],
    keywords: ['ask', 'pair', 'daemon', 'chat', 'autonomy', 'lessons'],
    daemon: true,
  ),
  const HarnessCommand(
    'app.settings',
    'Open Settings',
    ShortcutGroup.actions,
    action: ShortcutAction.showSettings,
    nativeAction: 'settings',
  ),
  // Harness ▸ Add Phone…, beside Settings in the app menu. No default keys:
  // it is a once-per-phone errand, not a chord worth learning.
  const HarnessCommand(
    'app.add_phone',
    'Add phone',
    ShortcutGroup.actions,
    keywords: ['iphone', 'mobile', 'pair', 'qr', 'scan', 'connect'],
    nativeAction: 'addPhone',
  ),
  const HarnessCommand(
    'keyboard.help',
    'Keyboard shortcuts',
    ShortcutGroup.actions,
    action: ShortcutAction.showShortcuts,
    nativeAction: 'showShortcuts',
  ),
  const HarnessCommand(
    'keyboard.open_config',
    'Open keyboard config',
    ShortcutGroup.actions,
    nativeAction: 'openKeymap',
  ),
  const HarnessCommand(
    'keyboard.quick_start',
    'Quick start',
    ShortcutGroup.actions,
    keywords: ['onboarding', 'learn', 'guide', 'getting started'],
    nativeAction: 'quickStart',
  ),
  const HarnessCommand(
    'keyboard.practice',
    'Keyboard practice',
    ShortcutGroup.actions,
    keywords: ['tutorial', 'learn', 'shortcuts', 'training', 'keys'],
    nativeAction: 'keyboardPractice',
  ),
  const HarnessCommand(
    'keyboard.pause_guide',
    'Pause quick start',
    ShortcutGroup.actions,
    keywords: ['hide guide', 'dismiss tutorial'],
  ),
  const HarnessCommand(
    'super_tab.new',
    'New Swarm',
    ShortcutGroup.actions,
    extraKeys: ['cmd+s'],
    hidden: true,
  ),
  if (kDebugSurfaceEnabled)
    const HarnessCommand(
      'app.debug',
      'Open the debug log',
      ShortcutGroup.actions,
      action: ShortcutAction.showDebug,
    ),
  if (kDebugSurfaceEnabled)
    const HarnessCommand(
      'app.onboarding_review',
      'Review onboarding',
      ShortcutGroup.actions,
      extraKeys: ['cmd+alt+shift+o'],
      hidden: true,
    ),
  const HarnessCommand(
    'picker.next',
    'Next result',
    ShortcutGroup.navigate,
    extraKeys: ['down', 'ctrl+n', 'ctrl+j'],
    context: KeymapContext.picker,
    repeatable: true,
  ),
  const HarnessCommand(
    'picker.previous',
    'Previous result',
    ShortcutGroup.navigate,
    extraKeys: ['up', 'ctrl+p', 'ctrl+k'],
    context: KeymapContext.picker,
    repeatable: true,
  ),
  const HarnessCommand(
    'picker.control_next',
    'Next control in the resource preview',
    ShortcutGroup.navigate,
    extraKeys: ['right'],
    context: KeymapContext.picker,
    repeatable: true,
  ),
  for (final kind in ['app', 'cli'])
    HarnessCommand(
      'picker.machine_$kind',
      'Show machine setup with ${kind == 'app' ? 'the app' : 'the CLI'}',
      ShortcutGroup.actions,
      context: KeymapContext.picker,
    ),
  const HarnessCommand(
    'picker.control_previous',
    'Previous control in the resource preview',
    ShortcutGroup.navigate,
    extraKeys: ['left'],
    context: KeymapContext.picker,
    repeatable: true,
  ),
  const HarnessCommand(
    'picker.page_up',
    'Page up in the results',
    ShortcutGroup.navigate,
    extraKeys: ['pageup'],
    context: KeymapContext.picker,
    repeatable: true,
  ),
  const HarnessCommand(
    'picker.page_down',
    'Page down in the results',
    ShortcutGroup.navigate,
    extraKeys: ['pagedown'],
    context: KeymapContext.picker,
    repeatable: true,
  ),
  const HarnessCommand(
    'picker.preview_up',
    'Scroll the preview up one line',
    ShortcutGroup.navigate,
    extraKeys: ['shift+up'],
    context: KeymapContext.picker,
    repeatable: true,
  ),
  const HarnessCommand(
    'picker.preview_down',
    'Scroll the preview down one line',
    ShortcutGroup.navigate,
    extraKeys: ['shift+down'],
    context: KeymapContext.picker,
    repeatable: true,
  ),
  const HarnessCommand(
    'picker.preview_page_up',
    'Page up in the preview or results',
    ShortcutGroup.navigate,
    context: KeymapContext.picker,
    repeatable: true,
  ),
  const HarnessCommand(
    'picker.preview_page_down',
    'Page down in the preview or results',
    ShortcutGroup.navigate,
    context: KeymapContext.picker,
    repeatable: true,
  ),
  const HarnessCommand(
    'picker.accept',
    'Open the selected result',
    ShortcutGroup.navigate,
    extraKeys: ['enter', 'ctrl+m'],
    context: KeymapContext.picker,
  ),
  const HarnessCommand(
    'picker.refresh',
    'Refresh the machine list',
    ShortcutGroup.actions,
    extraKeys: ['cmd+r', 'ctrl+r'],
    context: KeymapContext.picker,
  ),
  // Contextual resource actions leave the query and result selection in place.
  for (final action in ['download', 'start', 'stop'])
    HarnessCommand(
      'picker.model_$action',
      '${action[0].toUpperCase()}${action.substring(1)} the selected model',
      ShortcutGroup.actions,
      context: KeymapContext.picker,
    ),
  for (final (name, key, label) in [
    ('toggle', 'ctrl+s', 'Stop the selected harness or start/stop a model'),
    ('more', 'ctrl+period', 'Search actions for the selected resource'),
    ('rename', 'ctrl+shift+r', 'Rename the selected machine'),
    ('settings', 'ctrl+l', 'Open the selected machine’s connection settings'),
    ('link', 'ctrl+shift+l', 'Link another machine'),
    ('add_api', 'ctrl+shift+a', 'Add an API connection'),
    ('remove', 'ctrl+shift+backspace', 'Remove the selected resource'),
    ('filter', 'ctrl+shift+f', 'Change the harness list filter'),
    ('sort', 'ctrl+shift+s', 'Change the harness list sort order'),
  ])
    HarnessCommand(
      'picker.resource_$name',
      label,
      ShortcutGroup.actions,
      extraKeys: [key],
      context: KeymapContext.picker,
    ),
  const HarnessCommand(
    'picker.add_here',
    'Start or add the selected harness',
    ShortcutGroup.actions,
    extraKeys: ['cmd+enter'],
    context: KeymapContext.picker,
  ),
  // The box's own keys. They were hardcoded activators: absent from ⌘/ and the
  // config template, and impossible to move — the one corner where "every key
  // can be remapped" was not true.
  const HarnessCommand(
    'picker.complete',
    'Complete the path, or go to the next field',
    ShortcutGroup.navigate,
    // ⌃I is Tab to a terminal, as ⌃M is Return and ⌃[ is Escape.
    extraKeys: ['tab', 'ctrl+i'],
    context: KeymapContext.picker,
    repeatable: true,
  ),
  const HarnessCommand(
    'picker.complete_back',
    'The previous candidate, or the previous field',
    ShortcutGroup.navigate,
    extraKeys: ['shift+tab'],
    context: KeymapContext.picker,
    repeatable: true,
  ),
  const HarnessCommand(
    'picker.more_options',
    'Open the full New Harness form',
    ShortcutGroup.navigate,
    extraKeys: ['cmd+period'],
    context: KeymapContext.picker,
  ),
  // Open Harness: the selected harness, running or stopped, deleted for good.
  // ⌘⌫ is the search field's own delete-to-start, so not that.
  const HarnessCommand(
    'picker.delete',
    'Delete the selected harness',
    ShortcutGroup.actions,
    extraKeys: ['cmd+shift+backspace'],
    context: KeymapContext.picker,
  ),
  // Launch and Project use arrows/Enter. Keep stable command identities for
  // explicit user bindings without reserving plain letters in these prompts.
  for (final (name, key, label) in [
    ('agent', null, 'Choose the new agent'),
    ('project', null, 'Choose the new agent’s project'),
    ('task', null, 'Edit the new agent’s first message'),
    ('options', null, 'Choose the new agent’s model'),
    // Project is a text filter. Keep these command identities available for
    // explicit user remaps, without taking ordinary letters from the editor.
    ('project_new', null, 'Name a new project'),
    ('project_existing', null, 'Open an existing project'),
    ('project_repository', null, 'Clone a GitHub repository'),
    ('project_machine', null, 'Choose the new harness’s machine'),
    ('project_browse', 'ctrl+o', 'Browse folders on the selected machine'),
  ])
    HarnessCommand(
      'creation.$name',
      label,
      ShortcutGroup.actions,
      extraKeys: [?key],
      context:
          const {
            'project_new',
            'project_existing',
            'project_repository',
          }.contains(name)
          ? KeymapContext.project
          : KeymapContext.picker,
    ),
  for (var recent = 1; recent <= 9; recent++)
    HarnessCommand(
      'creation.project_recent_$recent',
      'Use recent project $recent',
      ShortcutGroup.actions,
      context: KeymapContext.project,
    ),
  const HarnessCommand(
    'picker.toggle_preview',
    'Show or hide the result preview',
    ShortcutGroup.navigate,
    extraKeys: ['ctrl+slash'],
    context: KeymapContext.picker,
  ),
  for (var row = 1; row <= 9; row++)
    HarnessCommand(
      'picker.pick_$row',
      'Take row $row',
      ShortcutGroup.navigate,
      extraKeys: ['alt+$row'],
      context: KeymapContext.picker,
    ),
  const HarnessCommand(
    'picker.cancel',
    'Close search',
    ShortcutGroup.navigate,
    extraKeys: ['escape', 'ctrl+c', 'ctrl+g', 'ctrl+bracketleft'],
    context: KeymapContext.picker,
  ),
];

final harnessCommandById = {
  for (final command in harnessCommands) command.id: command,
};
final _defaultBindingsByPlatform = <TargetPlatform, List<KeyBinding>>{};
List<KeyBinding> get harnessDefaultBindings => _defaultBindingsByPlatform
    .putIfAbsent(defaultTargetPlatform, _readDefaultBindings);

List<KeyBinding> _readDefaultBindings() {
  final defaults = <KeymapContext, Set<String>>{};
  for (final command in harnessCommands) {
    (defaults[command.context] ??= {}).addAll(command.keys);
  }
  // The Mac action table owns alias collisions before string-only commands:
  // Reload keeps Ctrl+R even though Split Right also has a Mac Cmd+R default.
  final aliases = <HarnessCommand, List<String>>{};
  for (final command in [
    ...harnessCommands.where((command) => command.action != null),
    ...harnessCommands.where((command) => command.action == null),
  ]) {
    for (final keys in command.outsideTerminalKeys) {
      if (defaults[command.context]!.add(keys)) {
        (aliases[command] ??= []).add(keys);
      }
    }
  }
  final bindings = <KeyBinding>[];
  for (final command in harnessCommands) {
    for (final keys in command.keys) {
      bindings.add(
        KeyBinding(
          keys: keys.split(' ').map(KeyStroke.parse),
          command: command.id,
          context: command.context,
        ),
      );
    }
    for (final keys in aliases[command] ?? const <String>[]) {
      bindings.add(
        KeyBinding(
          keys: keys.split(' ').map(KeyStroke.parse),
          command: command.id,
          context: command.context,
          outsideTerminal: true,
        ),
      );
    }
  }
  return bindings;
}

final _defaultKeymapsByPlatform = <TargetPlatform, ResolvedKeymap>{};
ResolvedKeymap get harnessDefaultKeymap =>
    _defaultKeymapsByPlatform.putIfAbsent(
      defaultTargetPlatform,
      () => ResolvedKeymap(harnessDefaultBindings, const KeymapConfig.empty()),
    );

List<String> describeKeyStrokeKeys(KeyStroke stroke) => [
  if (stroke.control) controlKeyLabel,
  if (stroke.alt) altKeyLabel,
  if (stroke.shift) shiftKeyLabel,
  if (stroke.command) commandKeyLabel,
  const {
        'left': '←',
        'right': '→',
        'up': '↑',
        'down': '↓',
        'pageup': 'Page Up',
        'pagedown': 'Page Down',
        'enter': '↵',
        'escape': 'Esc',
        'tab': '⇥',
        'space': 'Space',
        'comma': ',',
        'period': '.',
        'slash': '/',
        'backslash': r'\',
        'semicolon': ';',
        'quote': "'",
        'backquote': '`',
        'bracketleft': '[',
        'bracketright': ']',
        'minus': '-',
        'equal': '=',
        'backspace': '⌫',
        'delete': '⌦',
      }[stroke.key] ??
      stroke.key.toUpperCase(),
];
String describeKeyStroke(KeyStroke stroke) =>
    describeKeyStrokeKeys(stroke).join(chordKeySeparator);
String describeKeyBinding(KeyBinding binding) =>
    binding.keys.map(describeKeyStroke).join(' ');