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.

37.0 KB
Raw Blame
import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:harness/shared/theme/app_icons.dart';

import '../core/models.dart';
import '../shared/theme/app_theme.dart' as grid;
import 'desktop_chrome.dart';
import '../state/app_state.dart';
import '../state/task_route.dart';
import 'engine_identity.dart';

/// ⌘B — describe the work, and let the daemon say whose it is.
///
/// A TASK BOX, not a command palette. There is no list of actions to fuzzy-match and no agent search:
/// the whole interface is one field, and the answer to "which agent" is the router's job, not the
/// typist's. That is the point of the feature — the moment it also does lookup, the field has to guess
/// whether a word is a task or a name, and it will guess wrong on the short ones.
///
/// It is the same router the dial has always used (`routeVoiceTask`), which has never cared that its
/// input arrived as speech. What is new is that the answer comes back to a surface that can SHOW it: the
/// dial had to act on a pick it could not explain, a window can hold it up and ask.
///
/// CONFIDENT WORK IS SILENT, UNSURE WORK ASKS. Above the threshold the palette closes and the pane
/// simply becomes that agent — the text arriving in the terminal is the receipt, and a toast on top of it
/// would be a second one. Below it, nothing is sent and the runners-up are offered instead.
/// Words spoken into the dial, on their way into this palette instead of a person's typing.
///
/// The daemon asked THIS window to route them — see cable/windowRoute.ts — so the palette owes it an
/// answer either way: [taken] the moment it is on screen, then exactly one of [sent] or [cancelled].
/// Without the last one the dial holds its sending overlay until a watchdog it owns gives up, which is
/// a minute of a screen saying work is in flight when a person has already closed the question.
class SpokenTask {
  SpokenTask({
    required this.voiceId,
    required this.text,
    required this.cmd,
    required this.report,
  });

  final String voiceId;

  /// The transcript, verbatim. It lands in the field exactly as a person would have typed it.
  final String text;

  /// 'goal', 'loop', or empty — which of the dial's three buttons was held. The overview has all three,
  /// so a spoken task can be a goal without naming an agent.
  final String cmd;

  final void Function(String voiceId, String state, String agentId) report;

  bool _settled = false;

  void taken() => report(voiceId, 'taken', '');

  void sent(String agentId) {
    if (_settled) return;
    _settled = true;
    report(voiceId, 'sent', agentId);
  }

  /// Idempotent, and called on EVERY way out of the palette — Esc, the barrier, a dead end, or a commit
  /// that already answered (where it does nothing). One exit, one answer.
  void cancelled() {
    if (_settled) return;
    _settled = true;
    report(voiceId, 'cancelled', '');
  }
}

/// A task the router decided is new work, and the setup it chose: [machineId] and [folder] when a model
/// was sure of the project, [engine] when one was sure of the agent. The caller makes the harness once
/// the card is gone, filling what is missing from the pane the person is in.
class NewHarnessFromTask {
  const NewHarnessFromTask({
    required this.task,
    this.command = '',
    this.machineId,
    this.folder,
    this.engine,
  });
  final String task;

  /// The dial's Goal or Loop button, when the task was spoken with one held (see [SpokenTask.cmd]).
  final String command;
  final String? machineId, folder, engine;

  /// What the new harness is first told: the words, as the slash command the person pressed.
  String get prompt => command.isEmpty ? task : '/$command $task';
}

/// Resolves to the new harness to make when the task was decided to be new work; null on every other
/// way out — sent to a session, cancelled, or asked and answered by the person. A spoken task that
/// became new work is still owed its answer: the caller gives it once the harness is made.
Future<NewHarnessFromTask?> showTaskPalette(
  BuildContext context,
  AppNotifier notifier, {
  SpokenTask? spoken,
}) {
  // A keyboard palette opens fully drawn on its first frame.
  return showGeneralDialog<NewHarnessFromTask>(
    context: context,
    barrierDismissible: true,
    barrierLabel: 'Dismiss',
    barrierColor: Colors.transparent,
    transitionDuration: Duration.zero,
    pageBuilder: (context, _, _) =>
        _TaskPalette(notifier: notifier, spoken: spoken),
    transitionBuilder: (context, anim, _, child) => child,
    // Every exit lands here — Esc, a tap on the veil, and the self-close after a send. A commit has
    // already answered by then and this does nothing; anything else is a person walking away, which the
    // dial has to hear about or it keeps showing work that is not happening.
  ).then((plan) {
    if (plan == null) spoken?.cancelled();
    return plan;
  });
}

/// Below this the palette stops guessing and asks.
///
/// It is not a tuned number, it is the router's own top band: the classifier is told to answer **0.85+
/// when the name and/or recent activity CLEARLY match**, ~0.6 for "reasonable but not certain", and ~0.3
/// when nothing fits and it is naming the closest agent anyway. Sitting the line exactly on 0.85 means
/// this window sends in silence only when the router used the word "clearly" — every softer answer,
/// including the ones it called reasonable, becomes a question.
///
/// It was 0.5, and 0.5 was measured to be inside the model's own noise. The same task — "so sanh iphone
/// vs samsung" — routed twice seven minutes apart came back 0.35 and 0.80: once a question, once a silent
/// send, to two DIFFERENT agents. A threshold a small classifier can cross by chance is not a threshold,
/// and the wrong side of it is a task delivered to the wrong agent with nothing on screen to say so.
///
/// The cost is deliberate and worth naming: more asking. A "reasonable" 0.6 pick now stops for a keypress
/// it used to skip. That trade is the right way round — a question costs one Enter, a silent wrong route
/// costs a turn on the wrong agent and the time to notice.
///
/// The heuristic fallback is unaffected and stays what it was: capped at 0.4, so a router that could not
/// run has never been able to reach this line and still cannot. "The router broke" and "the router is
/// unsure" arrive at the same place — a question, never a silent wrong guess.
const double _confidentEnough = 0.85;

class _TaskPalette extends StatefulWidget {
  const _TaskPalette({required this.notifier, this.spoken});

  final AppNotifier notifier;

  /// Set when the words arrived from the dial rather than the keyboard.
  final SpokenTask? spoken;

  @override
  State<_TaskPalette> createState() => _TaskPaletteState();
}

enum _Stage { typing, routing, choosing, empty }

class _TaskPaletteState extends State<_TaskPalette> {
  final TextEditingController _text = TextEditingController();

  /// THE KEYS ARE HANDLED ON THIS NODE, not on a Focus above the field, and not through onSubmitted.
  ///
  /// A multi-line TextField consumes Enter itself — it inserts a newline and never calls onSubmitted —
  /// and key events travel from the focused node UPWARDS, so an ancestor Focus is asked only about the
  /// keys the field did not want. Enter was never one of them. A FocusNode's own onKeyEvent runs while
  /// the event is dispatched TO the node, ahead of the editing shortcuts that would type the newline, so
  /// this is the one place that can take Enter back.
  late final FocusNode _fieldFocus = FocusNode(onKeyEvent: _onFieldKey);

  _Stage _stage = _Stage.typing;
  String _note = '';

  /// The answer itself, kept because the picker explains ITSELF with it: how many agents were weighed,
  /// across how many computers, and whether a classifier or the name matcher produced this.
  RouteAnswer? _answer;

  /// Seconds on the clock while the router thinks.
  ///
  /// The wait can run to twenty seconds, and a spinner that says nothing for that long reads as a hang.
  /// A number that moves is the difference between "it is working" and "it has stopped".
  Timer? _ticker;
  int _elapsed = 0;

  List<RouteCandidate> _choices = const [];
  int _cursor = 0;

  /// The picker scrolls now that it offers every agent that was weighed, so the arrow keys need
  /// somewhere to scroll and each row needs to be findable to be scrolled TO.
  final ScrollController _listScroll = ScrollController();
  List<GlobalKey> _rowKeys = const [];

  /// How tall the list is allowed to get before it scrolls.
  ///
  /// Fifteen rows is roughly eight hundred pixels — taller than the palette, taller than some screens,
  /// and it would push the field it belongs to off the top. Six-ish rows keeps the whole sheet a sheet,
  /// and the rest is one flick or one arrow key away.
  static const double _listMaxHeight = 316;

  /// What the sessions are about, being read since the box opened (`warmTaskRoute`).
  late final Future<void> _context;

  /// How long Return waits for it: the reads take a few hundred milliseconds, another machine's more.
  static const _contextWait = Duration(milliseconds: 1500);

  /// Which question is still ours. A second Enter — or an Esc and a re-open — must not let a slow first
  /// answer arrive and act: it belongs to a palette state nobody is looking at any more.
  int _generation = 0;

  @override
  void initState() {
    super.initState();
    _context = warmTaskRoute(widget.notifier);
    // The recent prompts are read from the state file the first time; the box draws them once they are.
    unawaited(
      widget.notifier.taskHistory.load().then((_) {
        if (mounted) setState(() {});
      }),
    );
    final spoken = widget.spoken;
    // The transcript goes in the field rather than into a variable the person cannot see: this is the
    // same palette, and what it is about to route has to be readable — and editable, if the STT heard
    // "web hook" and meant "webhook".
    if (spoken != null) {
      _text.text = spoken.text;
      _text.selection = TextSelection.collapsed(offset: _text.text.length);
    }
    // Typing narrows the recent prompts, and lets go of one picked with the arrows. Listened to only
    // now: a transcript set above, before the first frame, has nothing to redraw.
    _text.addListener(_typed);
    if (spoken == null) return;
    // Acked BEFORE the first frame, not after the route: the daemon is deciding, on a two-second clock,
    // whether any window is listening at all, and it must not fall back to routing on its own while this
    // one is up. See cable/windowRoute.ts.
    spoken.taken();
    // Then run exactly what Enter runs. Posted after the frame so the palette is on screen while it
    // works — routing takes up to twenty seconds, and a dialog that appears already-spinning reads as
    // a hang rather than as an answer being worked out.
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (mounted) unawaited(_decide());
    });
  }

  @override
  void dispose() {
    _text.removeListener(_typed);
    _generation++; // anything still in flight now answers to nobody
    _ticker?.cancel();
    _text.dispose();
    _fieldFocus.dispose();
    _listScroll.dispose();
    super.dispose();
  }

  /// SAY IT AND IT IS DONE (docs/design/2026-10-09-auto-router.md). Return asks the daemon to decide,
  /// and the card acts on the answer without asking: Jev's pick, or a new
  /// harness. A session gets the task at once — the owner chose no undo window — and new work closes
  /// the card with the setup the models chose, for the screen to make.
  ///
  /// A daemon that cannot decide (older, or signed out) leaves the card as it always was: the full
  /// router, and a question when it is unsure.
  Future<void> _decide() async {
    final task = _text.text.trim();
    // Not while one is in flight: Return held down would send the same task twice.
    if (task.isEmpty || _stage == _Stage.routing) return;
    // Remembered as it is said, sent or not: one that could not be sent is there to say again.
    unawaited(
      widget.notifier.taskHistory.add(
        task,
        account: widget.notifier.currentUser?.id,
      ),
    );
    final mine = ++_generation;
    setState(() {
      _stage = _Stage.routing;
      _note = '';
      _answer = null;
    });
    _startClock();
    // What each session is about, read as the box opened: a fast Return waits for it, briefly.
    await _context.timeout(_contextWait, onTimeout: () {});
    if (!mounted || mine != _generation) return;
    final choices = taskRouteChoices(widget.notifier);
    final decision = await widget.notifier.routeDecide(task, choices);
    if (!mounted || mine != _generation) return;
    if (decision == null) {
      _stopClock();
      setState(() => _stage = _Stage.typing);
      return _route();
    }
    if (decision.unavailableBecause case final because?) {
      _stopClock();
      setState(() {
        _stage = _Stage.empty;
        _note =
            'Jev could not decide${because.isEmpty ? '' : ' ($because)'}. Nothing was sent.';
      });
      return;
    }
    // The dial's Goal or Loop button, applied where the words are sent, as [_commit] does.
    final cmd = widget.spoken?.cmd ?? '';
    final session = decision.session;
    if (session == null) {
      _stopClock();
      // A follow-up belongs to the new harness now, not to wherever the last task went: the screen points
      // the hint at it once it is made.
      widget.notifier.lastRoutedTask = null;
      final project = decision.project;
      Navigator.of(context).pop(
        NewHarnessFromTask(
          task: task,
          command: cmd,
          machineId: project?.machineId,
          folder: project?.folder,
          engine: decision.engine,
        ),
      );
      return;
    }
    final failure = await widget.notifier.sendTaskToSession(
      session.machineId,
      session.agentId,
      cmd.isEmpty ? task : '/$cmd $task',
      stillWanted: () => mounted && mine == _generation,
    );
    if (!mounted || mine != _generation) return;
    _stopClock();
    if (failure != null) {
      setState(() {
        _stage = _Stage.empty;
        _note = failure;
      });
      return;
    }
    widget.notifier.lastRoutedTask = (
      id: decision.sessionId!,
      at: DateTime.now(),
    );
    _landed(session.machineId, session.agentId);
  }

  /// The words are in. The box goes at once and the pane they landed in lights (`markLanding`): the
  /// receipt is where the work went, not a line about it in a box that is in the way of seeing it.
  void _landed(String machineId, String agentId) {
    widget.spoken?.sent(agentId);
    widget.notifier.markLanding(machineId, agentId);
    Navigator.of(context).pop();
  }

  Future<void> _route() async {
    final task = _text.text.trim();
    if (task.isEmpty || _stage == _Stage.routing) return;
    final mine = ++_generation;
    setState(() {
      _stage = _Stage.routing;
      _note = '';
      _answer = null;
    });
    _startClock();

    final answer = await widget.notifier.routeTask(task);
    if (!mounted || mine != _generation) return;
    _stopClock();

    // Nobody to ask, or nobody to pick from. Say which — "no agents here" and "the daemon is not up" are
    // different problems and lead to different next moves.
    if (answer == null) {
      setState(() {
        _stage = _Stage.empty;
        _note = widget.notifier.ownedActionMachine == null
            ? (widget.notifier.viewer == null
                  ? 'No local machine is connected yet.'
                  : 'Connect a machine first.')
            : (widget.notifier.viewer == null
                  ? 'Could not reach the router on this computer.'
                  : 'Could not reach the router on the connected machine.');
      });
      return;
    }
    if (answer.isEmpty) {
      setState(() {
        _stage = _Stage.empty;
        _note = widget.notifier.viewer == null
            ? 'There is no harness on this computer to send that to.'
            : 'There is no harness on the connected machine to send that to.';
      });
      return;
    }

    if (answer.confidence >= _confidentEnough) {
      _answer = answer;
      await _commit(answer.agentId, answer.machineId, task);
      return;
    }
    setState(() {
      _stage = _Stage.choosing;
      _answer = answer;
      _choices = answer.candidates;
      _rowKeys = List.generate(answer.candidates.length, (_) => GlobalKey());
      _cursor = 0;
    });
  }

  /// Move the highlight, and keep it on screen.
  ///
  /// Without the second half the arrow keys walk the selection straight out of the visible window: the
  /// highlight is on row nine, the list is still showing rows one to six, and Enter sends to an agent
  /// nobody can see. `ensureVisible` is posted after the frame because the row it scrolls to may not
  /// have been laid out yet when the cursor moved onto it.
  void _moveCursor(int delta) {
    if (_choices.isEmpty) return;
    setState(() => _cursor = (_cursor + delta).clamp(0, _choices.length - 1));
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (!mounted || _cursor >= _rowKeys.length) return;
      final target = _rowKeys[_cursor].currentContext;
      if (target == null) return;
      unawaited(
        Scrollable.ensureVisible(
          target,
          alignment: 0.5,
          duration: Duration.zero,
          curve: Curves.easeOut,
        ),
      );
    });
  }

  /// One second at a time, and only while something is actually in flight.
  void _startClock() {
    _ticker?.cancel();
    _elapsed = 0;
    _ticker = Timer.periodic(const Duration(seconds: 1), (_) {
      if (!mounted) return;
      setState(() => _elapsed++);
    });
  }

  void _stopClock() {
    _ticker?.cancel();
    _ticker = null;
  }

  Future<void> _commit(String agentId, String machineId, String task) async {
    // NOT closed before the send any more.
    //
    // It used to close first, so a fast route never showed a modal over the pane it was about to fill.
    // But the delivery can fail — a machine that stopped answering takes the turn and nothing comes back
    // — and closing first meant that failure had nowhere to appear: the palette was gone, the pane never
    // changed, and the person was left with a task that had simply evaporated. Measured on the desk with
    // a remote machine whose link was timing out.
    //
    // So it waits for the answer. A successful send is still quiet — the window closes and the pane
    // becomes the agent's — it just closes a moment later than it did.
    final mine = ++_generation;
    setState(() {
      _stage = _Stage.routing;
      _note = '';
    });
    _startClock();
    // The dial's Goal and Loop buttons live on the overview too, so a spoken task can carry a command
    // word without naming an agent. It is applied HERE, at the one place that sends: routing reads the
    // words a person actually said, and the agent receives the slash command they actually pressed.
    final cmd = widget.spoken?.cmd ?? '';
    final failure = await widget.notifier.sendRoutedTask(
      agentId,
      machineId,
      cmd.isEmpty ? task : '/$cmd $task',
    );
    if (!mounted || mine != _generation) return;
    _stopClock();
    if (failure != null) {
      setState(() {
        _stage = _Stage.empty;
        _note = failure;
      });
      return;
    }
    widget.notifier.lastRoutedTask = (
      id: taskRouteSessionId(machineId, agentId),
      at: DateTime.now(),
    );
    // The old router may name no machine: the pane then opens where the send went (`sendRoutedTask`).
    final target = machineId.isNotEmpty
        ? machineId
        : (widget.notifier.viewer == null
                  ? widget.notifier.localMachineState
                  : widget.notifier.ownedActionMachine)
              ?.machine
              .machineId;
    _landed(target ?? machineId, agentId);
  }

  /// How many recent prompts the box offers: as many as a search box shows, and the same six the
  /// welcome page's recent harnesses stop at.
  static const _recentShown = 6;

  /// The recent prompt picked with the arrows, if one is: Return says it instead of what is typed.
  int? _recentCursor;

  /// The recent prompts that fit what is typed, newest first: all of them in an empty box, then those
  /// that contain the words so far. None while it decides, and none for a prompt of several lines.
  List<String> get _suggestions {
    if (_stage != _Stage.typing) return const [];
    // A prompt of several lines keeps its arrows for its own lines: checked before trimming, which would
    // drop the newline just typed.
    if (_text.text.contains('\n')) return const [];
    final typed = _text.text.trim().toLowerCase();
    return widget.notifier.taskHistory
        .recentFor(widget.notifier.currentUser?.id)
        .where((said) {
          final lower = said.toLowerCase();
          return typed.isEmpty || (lower.contains(typed) && lower != typed);
        })
        .take(_recentShown)
        .toList();
  }

  String? get _picked {
    final at = _recentCursor;
    final suggestions = _suggestions;
    return at == null || at >= suggestions.length ? null : suggestions[at];
  }

  void _typed() {
    if (!mounted) return;
    setState(() => _recentCursor = null);
  }

  /// A recent prompt picked: said again, as a search box runs a recent search — decided on the desk as it
  /// is now, so it may go somewhere other than it went before.
  KeyEventResult _sayAgain(String prompt) {
    _text.removeListener(_typed);
    _text.value = TextEditingValue(
      text: prompt,
      selection: TextSelection.collapsed(offset: prompt.length),
    );
    _text.addListener(_typed);
    _recentCursor = null;
    unawaited(_decide());
    return KeyEventResult.handled;
  }

  /// A recent prompt's row: the clock of a past search, and the words.
  Widget _recentRow(String prompt, {required bool active}) {
    final ink = active ? grid.AppDesktop.onSelection : DesktopChrome.foreground;
    return Semantics(
      selected: active,
      button: true,
      label: 'Say again: $prompt',
      child: InkWell(
        mouseCursor: SystemMouseCursors.click,
        onTap: () => _sayAgain(prompt),
        borderRadius: BorderRadius.circular(grid.AppDesktop.rowRadius),
        child: Container(
          padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
          decoration: BoxDecoration(
            color: active ? grid.AppDesktop.selection : null,
            borderRadius: BorderRadius.circular(grid.AppDesktop.rowRadius),
          ),
          child: Row(
            children: [
              ExcludeSemantics(
                child: Icon(
                  AppIcons.history,
                  size: 16,
                  color: active
                      ? grid.AppDesktop.selectionDetail
                      : DesktopChrome.muted,
                ),
              ),
              const SizedBox(width: 12),
              Expanded(
                child: ExcludeSemantics(
                  child: Text(
                    prompt.replaceAll(RegExp(r'\s+'), ' '),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: DesktopChrome.control(color: ink),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  KeyEventResult _onFieldKey(FocusNode node, KeyEvent event) {
    if (event is! KeyDownEvent && event is! KeyRepeatEvent) {
      return KeyEventResult.ignored;
    }
    final isEnter =
        event.logicalKey == LogicalKeyboardKey.enter ||
        event.logicalKey == LogicalKeyboardKey.numpadEnter;
    final isEscape = event.logicalKey == LogicalKeyboardKey.escape;
    final composing = _text.value.composing;
    if (composing.isValid && !composing.isCollapsed) {
      return isEnter || isEscape
          ? KeyEventResult.skipRemainingHandlers
          : KeyEventResult.ignored;
    }
    if (isEscape) {
      Navigator.of(context).pop();
      return KeyEventResult.handled;
    }
    // ⇧Enter is the newline — ignored here so the field does what it always does with it.
    final shift = HardwareKeyboard.instance.isShiftPressed;
    if (isEnter && !shift && _stage != _Stage.choosing) {
      final picked = _picked;
      if (picked != null) return _sayAgain(picked);
      unawaited(_decide());
      return KeyEventResult.handled; // …and NOT a newline
    }
    final suggestions = _suggestions;
    final down = event.logicalKey == LogicalKeyboardKey.arrowDown;
    if (_stage != _Stage.choosing &&
        suggestions.isNotEmpty &&
        (down || event.logicalKey == LogicalKeyboardKey.arrowUp)) {
      // Down from the field onto the first, up past the first back to the field.
      final at = _recentCursor;
      setState(
        () => _recentCursor = down
            ? (at == null ? 0 : (at + 1).clamp(0, suggestions.length - 1))
            : (at == null || at == 0 ? null : at - 1),
      );
      return KeyEventResult.handled;
    }
    if (_stage != _Stage.choosing) return KeyEventResult.ignored;

    if (event.logicalKey == LogicalKeyboardKey.arrowDown) {
      _moveCursor(1);
      return KeyEventResult.handled;
    }
    if (event.logicalKey == LogicalKeyboardKey.arrowUp) {
      _moveCursor(-1);
      return KeyEventResult.handled;
    }
    if (isEnter && !shift) {
      final pick = _choices[_cursor.clamp(0, _choices.length - 1)];
      unawaited(_commit(pick.agentId, pick.machineId, _text.text.trim()));
      return KeyEventResult.handled;
    }
    return KeyEventResult.ignored;
  }

  @override
  Widget build(BuildContext context) {
    grid.AppTheme.watch(context);
    return Stack(
      children: [
        Positioned.fill(
          child: DesktopDialogBackdrop(
            onDismiss: () => Navigator.of(context).maybePop(),
          ),
        ),
        SafeArea(
          child: Padding(
            padding: const EdgeInsets.all(24),
            child: Align(
              alignment: const Alignment(0, -.18),
              child: ConstrainedBox(
                constraints: const BoxConstraints(maxWidth: 680),
                child: SingleChildScrollView(child: _sheet()),
              ),
            ),
          ),
        ),
      ],
    );
  }

  Widget _sheet() => DesktopDialogSurface(
    child: Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [_field(), _results()],
    ),
  );

  /// The field, with Material's own skin switched OFF.
  ///
  /// ⚠️ `filled: false`, `isCollapsed: true` and the four explicit `InputBorder.none`s are load-bearing,
  /// not tidying — the same trap `ShareTextField` documents. The app's global [InputDecorationTheme] sets
  /// `filled: true`, a `minHeight` sized for a 32px control, and a focus ring on all three border slots.
  /// `border: InputBorder.none` alone does NOT win: `enabledBorder` and `focusedBorder` are consulted
  /// first, so the field drew a rounded pill in the app's grey INSIDE this sheet — two nested boxes
  /// around one line of text, which is what made the first cut of this palette look cheap.
  Widget _field() {
    final working = _stage == _Stage.routing;
    // 56 of right padding is the design's, and it is what the spinner stands in. The clock needs its own
    // room, so the gap widens only while it is showing rather than leaving a permanent hole.
    final rightPad = working && _elapsed >= 5 ? 84.0 : 56.0;
    return Stack(
      children: [
        Padding(
          padding: EdgeInsets.fromLTRB(24, 19, rightPad, 19),
          child: TextField(
            controller: _text,
            focusNode: _fieldFocus,
            autofocus: true,
            maxLines: 4,
            minLines: 1,
            // Enter routes; a newline needs the modifier. The field is for a sentence, not a document,
            // and the common case must not cost a reach for the mouse.
            // Read-only rather than disabled while the router thinks: a disabled field drops the focus,
            // and the focus is what Esc is listening on.
            readOnly: working,
            style: DesktopChrome.text(size: 17, height: 1.35),
            cursorColor: DesktopChrome.accent,
            cursorWidth: 2,
            cursorRadius: Radius.zero,
            decoration: InputDecoration(
              filled: false,
              isDense: true,
              isCollapsed: true,
              contentPadding: EdgeInsets.zero,
              constraints: BoxConstraints(),
              border: InputBorder.none,
              enabledBorder: InputBorder.none,
              focusedBorder: InputBorder.none,
              disabledBorder: InputBorder.none,
              hintText: "What's up?",
              hintStyle: DesktopChrome.text(
                size: 17,
                color: DesktopChrome.hint,
                height: 1.35,
              ),
            ),
          ),
        ),
        // The whole of the waiting state, in the field's own right margin: a 16px ring at right:24.
        if (working) ...[
          Positioned(
            right: 24,
            top: 0,
            bottom: 0,
            child: Center(
              child: SizedBox(
                width: 16,
                height: 16,
                child: CircularProgressIndicator(
                  strokeWidth: 1.8,
                  color: DesktopChrome.muted,
                ),
              ),
            ),
          ),
          // Past five seconds, and only then. The route can run to twenty; under five a clock is noise,
          // over it, it is the difference between working and stopped. The design has no slot for this,
          // so it borrows the spinner's margin rather than adding a row.
          if (_elapsed >= 5)
            Positioned(
              right: 46,
              top: 0,
              bottom: 0,
              child: Center(
                child: Text(
                  '${_elapsed}s',
                  style: grid.AppType.caption(color: DesktopChrome.muted),
                ),
              ),
            ),
        ],
      ],
    );
  }

  /// Everything below the hairline: the question, the rows, or nothing at all.
  Widget _results() {
    switch (_stage) {
      case _Stage.typing:
        final suggestions = _suggestions;
        if (suggestions.isEmpty) return const SizedBox.shrink();
        return _panel([
          for (var i = 0; i < suggestions.length; i++)
            _recentRow(suggestions[i], active: i == _recentCursor),
        ]);

      case _Stage.routing:
        return const SizedBox.shrink();

      case _Stage.empty:
        return _panel([
          Padding(
            padding: const EdgeInsets.fromLTRB(16, 6, 16, 8),
            child: Text(
              _note,
              style: grid.AppType.body(
                fontWeight: FontWeight.w400,
                color: DesktopChrome.muted,
                height: 1.45,
              ),
            ),
          ),
        ]);

      case _Stage.choosing:
        return _panel([
          _question(),
          // Every agent that was weighed, scrolling past the sixth. The question above stays put: it is
          // the explanation for the list, not a row in it.
          ConstrainedBox(
            constraints: const BoxConstraints(maxHeight: _listMaxHeight),
            child: Scrollbar(
              controller: _listScroll,
              child: SingleChildScrollView(
                controller: _listScroll,
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: [
                    for (var i = 0; i < _choices.length; i++)
                      KeyedSubtree(
                        key: i < _rowKeys.length ? _rowKeys[i] : null,
                        child: _row(_choices[i], active: i == _cursor),
                      ),
                  ],
                ),
              ),
            ),
          ),
        ]);
    }
  }

  Widget _panel(List<Widget> children) => Container(
    padding: const EdgeInsets.fromLTRB(8, 6, 8, 8),
    decoration: BoxDecoration(
      border: Border(top: BorderSide(color: DesktopChrome.rim)),
    ),
    child: Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: children,
    ),
  );

  /// Why it stopped, and what it looked at before it did.
  ///
  /// The counts are marked, not buried: the design gives the numbers inside this line their own colour,
  /// and they are the ones that answer the question a person actually has here — was the agent I mean
  /// even in the running? The list the daemon weighs is capped, so without this nothing on screen says.
  Widget _question() {
    final answer = _answer;
    final heuristic = answer?.via == 'heuristic';
    final reason = (answer?.reason ?? '').trim();
    final weighed = answer?.weighed ?? 0;
    final machines = answer?.machines ?? 0;
    final base = grid.AppType.body(
      fontWeight: FontWeight.w400,
      color: DesktopChrome.muted,
      height: 1.45,
    );
    final mark = grid.AppType.body(color: DesktopChrome.foreground);
    return Padding(
      padding: const EdgeInsets.fromLTRB(16, 6, 16, 4),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text.rich(
            TextSpan(
              style: base,
              children: [
                if (weighed > 0) ...[
                  const TextSpan(text: 'Weighed '),
                  TextSpan(
                    text: '$weighed ${weighed == 1 ? 'harness' : 'harnesses'}',
                    style: mark,
                  ),
                  if (machines > 1) ...[
                    const TextSpan(text: ' on '),
                    TextSpan(text: '$machines computers', style: mark),
                  ],
                  const TextSpan(text: ' — '),
                ],
                TextSpan(
                  text: heuristic
                      ? 'the router could not run, so these are name matches'
                      : 'not sure enough to send it',
                ),
              ],
            ),
          ),
          // The router's own words. It has always sent them and the window has always dropped them,
          // which left the person guessing at a judgement the machine had already explained. The design
          // has no slot for it, so it goes here, quieter than the line above it.
          if (!heuristic && reason.isNotEmpty)
            Padding(
              padding: const EdgeInsets.only(top: 3),
              child: Text(
                '“$reason”',
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: grid.AppType.caption(
                  color: DesktopChrome.muted,
                  fontStyle: FontStyle.italic,
                ),
              ),
            ),
        ],
      ),
    );
  }

  /// Shared picker anatomy keeps machine context legible in narrow windows.
  Widget _row(RouteCandidate candidate, {required bool active}) {
    final fit = candidate.confidence;
    final selected = active;
    final ink = selected
        ? grid.AppDesktop.onSelection
        : DesktopChrome.foreground;
    final detail = selected
        ? grid.AppDesktop.selectionDetail
        : DesktopChrome.muted;
    final description = [
      if (candidate.machine.isNotEmpty) candidate.machine,
      if (candidate.recent.isNotEmpty) candidate.recent,
    ].join(' · ');
    return Semantics(
      selected: active,
      child: InkWell(
        mouseCursor: SystemMouseCursors.click,
        onTap: () => unawaited(
          _commit(candidate.agentId, candidate.machineId, _text.text.trim()),
        ),
        borderRadius: BorderRadius.circular(grid.AppDesktop.rowRadius),
        child: Container(
          padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
          decoration: BoxDecoration(
            color: selected ? grid.AppDesktop.selection : null,
            borderRadius: BorderRadius.circular(grid.AppDesktop.rowRadius),
          ),
          child: Row(
            children: [
              EngineMark(
                engine: candidate.engine,
                size: grid.AppDesktop.identitySize,
              ),
              const SizedBox(width: 12),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      candidate.name,
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: DesktopChrome.control(color: ink, medium: true),
                    ),
                    if (description.isNotEmpty) ...[
                      const SizedBox(height: 2),
                      Text(
                        description,
                        maxLines: 2,
                        overflow: TextOverflow.ellipsis,
                        style: DesktopChrome.metadata(color: detail),
                      ),
                    ],
                  ],
                ),
              ),
              if (fit > 0) ...[
                const SizedBox(width: 12),
                Text(
                  fit.toStringAsFixed(2),
                  style: DesktopChrome.metadata(color: detail),
                ),
              ],
            ],
          ),
        ),
      ),
    );
  }
}