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.

89.5 KB
Raw Blame
import 'dart:async';

import 'package:flutter/foundation.dart' show ValueListenable;
import 'package:flutter/material.dart';

import 'package:harness_mobile/demo/sample_mode.dart';
import 'package:harness_mobile/logging/startup_trace.dart';
import 'package:harness_mobile/logging/typing_trace.dart';
import 'package:harness_mobile/measurement/onboarding_measurement.dart';
import 'package:harness_mobile/measurement/product_measurement.dart';
import 'package:harness_mobile/shared/theme/app_theme.dart';
import 'package:harness_mobile/core/models.dart';
import 'package:harness_mobile/state/app_state.dart';

import 'agent_index.dart';
import 'agent_swipe.dart';
import 'agent_swipe_list.dart';
import 'agents_page.dart' show openNewAgent;
import 'daemon_chip.dart';
import 'desk_groups.dart';
import 'link_page.dart';
import 'machines_tab.dart';
import 'out_of_sight.dart';
import 'phone_navigation.dart' show phoneRoute;
import 'settings_page.dart' show PhoneSettingsButton;
import 'tty_controls.dart';
import 'tty.dart';
import 'welcome/join_moment.dart';
import 'welcome/onboarding_copy.dart';
import 'welcome/onboarding_frame.dart';
import 'welcome/onboarding_picture.dart';
import 'welcome/pairing_with_code.dart';
import 'welcome/pick_up_page.dart';
import 'welcome/your_computer.dart';

import 'phone_header.dart';
import 'phone_status.dart';

/// The phone's home: one agent's terminal, at the ROOT of the stack rather than pushed over a list.
///
/// ⚠️ **The root is what removes the back button, and that is the whole point of this widget.**
/// [PhoneHeader] draws its chevron from `Navigator.canPop()`, and the terminal used to sit on top of
/// an agents list — so there was always somewhere to go back TO. Here there is not: the terminal is
/// the first page, `canPop()` answers false, and the header loses its chevron without being told
/// anything. Nothing about the terminal page itself changed.
///
/// Which agent it shows is [AppNotifier.lastOpenedAgent]'s record, and failing that the first agent
/// the account can reach — see [_target]. Moving between agents is the pager's horizontal swipe,
/// which is why the neighbours below are the whole visible list rather than one entry: with no list
/// screen left, a pager over a single agent would be a home screen with no way off it.
class AgentHome extends StatefulWidget {
  const AgentHome({
    super.key,
    required this.notifier,
    this.openMachineId,
    this.openAgent,
  });

  final AppNotifier notifier;

  /// An agent somebody picked elsewhere — search, the new-agent form — to put on this screen.
  ///
  /// Listened to for the same reason [openMachineId] is. Outranks everything, including a machine
  /// still being waited for: it is a choice made by hand a moment ago.
  final ValueListenable<({String machineId, String agentId})?>? openAgent;

  /// A machine whose password has just been accepted, whose first agent should take the screen once
  /// it answers. Holds null the rest of the time.
  ///
  /// ⚠️ **Without it, entering a password appears to do nothing.** The home screen holds the agent
  /// it is showing ([_AgentHomeState._showing]) and keeps it while it is still openable, which is
  /// exactly right for an agent list reshuffling underneath — and exactly wrong here: somebody who
  /// has just unlocked a machine is waiting for THAT machine's agents, and a perfectly healthy
  /// agent on another machine would hold the screen against them indefinitely.
  ///
  /// ⚠️ **Listened to rather than read as a plain field, and the difference is the whole feature.**
  /// This widget is a tab's root, built inside `onGenerateRoute` — which a nested [Navigator] runs
  /// once, when the route is created. A plain `String?` would therefore be read on the first launch
  /// frame, before any machine could have been linked, and never updated again however many times
  /// the shell rebuilt.
  ///
  /// Null where there is no shell to provide one, which is how a page pumped on its own still works.
  final ValueListenable<String?>? openMachineId;

  @override
  State<AgentHome> createState() => _AgentHomeState();
}

class _AgentHomeState extends State<AgentHome>
    with SingleTickerProviderStateMixin {
  /// The agent the pager is currently built around, or null while nothing can be opened.
  ///
  /// ⚠️ **Held as state rather than recomputed every build, and it is what keeps the screen still.**
  /// [visibleAgents] sorts partly on state that moves by itself — an agent that starts working sorts
  /// upward — so a home screen reading "the first agent" on every rebuild would swap the terminal
  /// under somebody mid-sentence, for a reason nothing on screen explains. Once an agent is chosen
  /// it is kept until it can no longer be opened.
  ({String machineId, String agentId})? _showing;

  /// Whether the record of the last agent has been read. Until it has, the screen must not fall back
  /// to "the first agent": the record usually names a different one, and the fallback would be
  /// replaced a frame later — a terminal flashing past on every launch.
  bool _readingLast = true;

  /// A machine to jump to as soon as it reports an agent — [AgentHome.openMachineId], held until it
  /// is satisfied.
  ///
  /// Cleared the moment an agent of that machine takes the screen, and not before: the machine is
  /// still connecting when this arrives, so the first few rebuilds have nothing of its to offer and
  /// must not be mistaken for the request having been met.
  ///
  /// ⚠️ Also cleared by a SWIPE, in [_onAgentChanged]. Somebody who has swiped away has chosen an
  /// agent by hand, and a pending jump firing over that choice a second later is the screen moving
  /// on its own after the person started using it.
  String? _awaitingMachine;

  /// The neighbour list handed to the pager currently on screen, frozen for as long as that pager
  /// lives.
  ///
  /// ⚠️ **Rebuilding this on every frame silently breaks the pager, which is why it is held.**
  /// [AgentSwipeHost] works out its page index once, in `initState`, and then reads `neighbours` by
  /// that index on every build — the list and the index have to stay in step. [visibleAgents] does
  /// not: it sorts partly on state that moves by itself, so an agent that starts working sorts
  /// upward and every index after it shifts. A fresh list each build would therefore leave the pager
  /// drawing a DIFFERENT agent at the page it thinks it is on, mid-session, with nothing on screen
  /// to explain it.
  ///
  /// So the snapshot is taken when a pager opens, and replaced only when a new one does — which is
  /// exactly the rule every pushed pager already followed by being built once from a list the person
  /// had just been looking at — or when the tab's SET of agents changes. The pager then lines the new
  /// list up with the page already on screen rather than reading it by the old index (see
  /// `AgentSwipeHost`'s `didUpdateWidget`), which is what keeps the two in step through a swap.
  AgentSwipeList? _neighbours;

  /// The agent [_neighbours] was taken for. A different one means a different pager, and therefore a
  /// fresh snapshot.
  ({String machineId, String agentId})? _neighboursFor;

  /// How long the loading screen may hold the app before it gives up and shows the empty state.
  ///
  /// ⚠️ **A guard against a spinner that never stops, which the states below can genuinely produce.**
  /// `agentLoadStatus` is not guaranteed to reach a terminal value: `_performMachineDataLoad` returns
  /// early — leaving it on `loading` — when the auth revision moves under it, and a machine linked
  /// but not yet dialled sits on `idle` until something asks it to load. Neither is common, and both
  /// would otherwise be permanent, on the one screen where "stuck" and "still working" look alike.
  ///
  /// The empty state it falls back to is honest about not knowing — it names what to do next, and
  /// `RefreshIndicator` is not reachable here, so the value is set long enough that a slow-but-fine
  /// launch is never cut short. Matches the 45s the shell's old landing rules allowed.
  static const _loadingTimeout = Duration(seconds: 45);

  /// Set once [_loadingTimeout] has passed. From then on [_loadingMessage] answers null and the
  /// screen stops waiting — an agent that arrives later is still picked up by the ordinary rebuild.
  bool _gaveUpWaiting = false;
  Timer? _loadingDeadline;

  /// How long the loading screen waits on its own before it says so and offers a way off it —
  /// Settings, and the computers list ([_loadingSlow]). Past a slow-but-fine launch, short of
  /// [_loadingTimeout].
  static const _slowAfter = Duration(seconds: 15);
  Timer? _slowTimer;

  /// The loading screen has been up for [_slowAfter] without a break.
  bool _loadingSlow = false;

  void _giveUpWaiting() {
    if (!mounted || _gaveUpWaiting) return;
    setState(() => _gaveUpWaiting = true);
  }

  /// The loading screen is what [build] draws: its [_loadingTimeout] and [_slowAfter] run, each
  /// from the moment this wait began.
  ///
  /// ⚠️ **Every wait, not the launch's alone.** The deadline used to be armed once, in
  /// [initState], and ended for good by the first screen that was not a loading one — which on a
  /// first sign-in is "Waiting for your computer…". The computer turning up then brought
  /// "Connecting to your computer…" back with no deadline at all, over a machine whose agent list
  /// can stall (see [_loadingTimeout]): a spinner with no end and nothing on screen to leave it by.
  ///
  /// Called from [build]: it starts timers and never sets state itself.
  void _holdLaunchWait() {
    if (!_gaveUpWaiting) {
      _loadingDeadline ??= Timer(_loadingTimeout, _giveUpWaiting);
    }
    if (!_loadingSlow) {
      _slowTimer ??= Timer(_slowAfter, () {
        if (!mounted) return;
        setState(() => _loadingSlow = true);
      });
    }
  }

  /// The wait is over — the screen has something other than a loading message to show — so
  /// [_loadingTimeout] has nothing left to guard, and must not fire into a screen that has stopped
  /// waiting: it would hold back every loading message after it. A later wait starts its own
  /// ([_holdLaunchWait]).
  ///
  /// Called from [build], on each way out of the loading screen.
  void _endLaunchWait() {
    _loadingDeadline?.cancel();
    _loadingDeadline = null;
    _slowTimer?.cancel();
    _slowTimer = null;
    _loadingSlow = false;
  }

  @override
  void initState() {
    super.initState();
    // Whatever it already holds counts: a relink that happened while this root was being rebuilt
    // would otherwise be missed between the write and the listen.
    _awaitingMachine = widget.openMachineId?.value;
    widget.openMachineId?.addListener(_onLinkedMachineChanged);
    _requestedAgent = widget.openAgent?.value;
    widget.openAgent?.addListener(_onAgentRequested);
    _loadingDeadline = Timer(_loadingTimeout, _giveUpWaiting);
    _readLast();
  }

  @override
  void dispose() {
    widget.openMachineId?.removeListener(_onLinkedMachineChanged);
    widget.openAgent?.removeListener(_onAgentRequested);
    _loadingDeadline?.cancel();
    _slowTimer?.cancel();
    _restoreDeadline?.cancel();
    _terminalWait?.cancel();
    _firstSessionWait?.cancel();
    _moment.dispose();
    super.dispose();
  }

  @override
  void didUpdateWidget(AgentHome old) {
    super.didUpdateWidget(old);
    // The shell hands over one notifier for its lifetime, so this is belt and braces — but a
    // listener left on a replaced notifier would keep this State alive against a dead object.
    if (!identical(old.openMachineId, widget.openMachineId)) {
      old.openMachineId?.removeListener(_onLinkedMachineChanged);
      widget.openMachineId?.addListener(_onLinkedMachineChanged);
      _onLinkedMachineChanged();
    }
    if (!identical(old.openAgent, widget.openAgent)) {
      old.openAgent?.removeListener(_onAgentRequested);
      widget.openAgent?.addListener(_onAgentRequested);
      _onAgentRequested();
    }
  }

  /// An agent picked elsewhere, waiting to take the screen — [AgentHome.openAgent], held until it
  /// appears in the list. A freshly created agent can reach the request a frame before it reaches
  /// the machine's agent list, and dropping the request then would leave the screen on the old one.
  ({String machineId, String agentId})? _requestedAgent;

  /// The welcome ([PickUpPage]) in place of a guessed session: set when this phone has nothing to
  /// remember, or a computer was just linked; spent the moment a session is picked.
  bool _welcome = false;

  /// The first session has been put on screen since this phone signed in: the onboarding is over,
  /// and a wait after it is an ordinary one again ([_onboarding]).
  bool _onboardingDone = false;

  /// This phone has nothing of its own to go back to — no session remembered, no tab — read by
  /// [_readLast]: it has never reached a session, whenever it signed in.
  bool _freshPhone = false;

  /// The onboarding is under way: this phone signed in on this run ([AppNotifier.signedInThisRun])
  /// or has never reached a session ([_freshPhone]), and has not reached one yet. Home's waits are
  /// then drawn on the onboarding's picture — eased from the welcome's, so signing in reads as one
  /// screen changing rather than a cut to a spinner — and the computer joining gets its moment
  /// ([_joinStage]) before its session opens by itself.
  ///
  /// ⚠️ **Never in the sample.** Its home is a fresh phone's too — nothing remembered — but it is
  /// not setting a computer up: it opens on its sessions to pick from, and its guide takes it on.
  bool get _onboarding =>
      (widget.notifier.signedInThisRun || _freshPhone) &&
      !_onboardingDone &&
      SampleMode.maybeOf(context) == null;

  /// The computer the onboarding is joining, by its name on the account — the last beat before its
  /// session opens ([_joinStage]). Set once, the first time there is one ([_noticeJoin]).
  ({String machineId, String name})? _joining;

  /// "On your computer, go to" has been on screen: the next computer on the account is the one the
  /// person just set up for this phone, not one the account already had.
  bool _awaitedComputer = false;

  /// The computer joining, before its session opens ([_joinStage]).
  late final JoinMoment _moment = JoinMoment(
    vsync: this,
    onDone: () {
      if (mounted) setState(() {});
    },
  );

  /// How long "… is ready." waits for the computer's first session before it gives way to the
  /// empty state — the desktop's own tour may still be fetching the agents it starts one with.
  static const _firstSessionPatience = Duration(seconds: 90);
  Timer? _firstSessionWait;
  bool _firstSessionGaveUp = false;

  void _onAgentRequested() {
    final requested = widget.openAgent?.value;
    // Null is the shell resetting before it writes, not a request.
    if (requested == null) return;
    if (kTypingTrace) {
      typingEvent('switch: agent ${_shortId(requested.agentId)} asked for');
    }
    setState(() {
      _welcome = false;
      _requestedAgent = requested;
      // A choice made by hand supersedes a jump still pending for a machine.
      _awaitingMachine = null;
    });
  }

  /// A machine's password was accepted somewhere in the app: its first agent now outranks whatever
  /// is on screen. See [AgentHome.openMachineId].
  void _onLinkedMachineChanged() {
    final requested = widget.openMachineId?.value;
    // Null is the notifier at rest, not a request to stop waiting for anything — a jump already
    // pending stands.
    if (requested == null || requested == _awaitingMachine) return;
    // A computer just linked: its sessions, and every other, to pick from — not one of them opened
    // for you.
    setState(() {
      _awaitingMachine = requested;
      _welcome = true;
    });
  }

  Future<void> _readLast() async {
    final record = widget.notifier.lastOpenedAgent;
    final lastTab = record.readTab();
    final last = await StartupTrace.time('home.readLastAgent', record.read);
    final tabId = await lastTab;
    if (!mounted) return;
    // The tab the phone was in last run, for [_firstOfLastTab] — unless one was already chosen on
    // this run while the record was being read.
    if (tabId != null && widget.notifier.activeDeskTabId == null) {
      widget.notifier.noteDeskTab(tabId);
    }
    // ⚠️ The deadline is NOT ended here. This read takes milliseconds, and ending it here left the
    // waits it exists for — an agent list that never arrives, after the machine is up — with no end
    // at all. It ends when the screen stops waiting ([_endLaunchWait]).
    setState(() {
      _readingLast = false;
      // ⚠️ Not applied if a pager is already up, which only happens when this read came back AFTER
      // the screen gave up waiting and opened an agent on its own. Taking the record then would move
      // somebody off a terminal they are already looking at, seconds after it opened.
      if (last != null && _neighboursFor == null) _showing = last;
      // Nothing remembered on this phone, not even a tab: open on the sessions to pick from, not a
      // guessed one. A phone that remembers its tab has been used here before, and gets that tab's
      // first agent as it always has ([_firstOfLastTab]).
      if (last == null &&
          tabId == null &&
          _neighboursFor == null &&
          _requestedAgent == null) {
        _welcome = true;
        _freshPhone = true;
      }
    });
    _restoreDeadline = Timer(_restoreTimeout, () {
      if (!mounted) return;
      setState(() => _restoreGaveUp = true);
    });
  }

  /// How long the remembered agent's machine — and the desk's tabs — get to come up before the
  /// screen settles for the first agent it can reach — see [_target].
  ///
  /// 30s: a relayed machine that drops its first dial and redials was measured taking well past 15s
  /// to hand over its agent list.
  static const _restoreTimeout = Duration(seconds: 30);
  Timer? _restoreDeadline;
  bool _restoreGaveUp = false;

  /// The account's machine list could not be read: not answered in this sign-in, not being asked
  /// for, and a failure on record ([AppNotifier.lastError], which every sign-in clears). Not an
  /// empty account — nothing says what the account has until a Try again answers.
  bool get _machinesUnreadable {
    final notifier = widget.notifier;
    return notifier.machines.isEmpty &&
        !notifier.machinesLoading &&
        !notifier.machinesAnswered &&
        notifier.lastError != null;
  }

  /// Whether [machineId] is on its way — connecting, or connected with its agent list still owed —
  /// rather than answered, offline, or wanting a password.
  ///
  /// ⚠️ **"Offline" and a failed agent list are NOT taken at their word here.** A socket that drops
  /// while it is still being dialled marks the node offline for a moment, and `agents_list` answers
  /// "WS closed" on the way — both seen on a real launch, both for a machine that came up seconds
  /// later. Believing either ended the wait and handed the screen to the faster machine's agent.
  /// So offline counts as coming while the account's own record (`/api/machines`) says the machine
  /// is up, and an errored list counts as coming too; the deadline is what ends a wait that is not
  /// going to be met. Only a password prompt, a machine the account says is down, or a list that
  /// LOADED without the agent end it early.
  bool _machineStillComing(String machineId) {
    final notifier = widget.notifier;
    final machine = notifier.stateOf(machineId);
    if (machine == null) {
      // Not on the list: coming only while the list itself is. ⚠️ An empty list that has ANSWERED
      // is the account's word that the machine is not on it — the record names a computer since
      // removed, or one of another account's (it is never cleared). Read as "not answered yet", it
      // held an account with no computer on "Connecting to your computer…" for the whole
      // [_restoreTimeout] before its set-up page came up.
      //
      // Nor while a list that FAILED waits on a Try again: nothing is on its way until then, and
      // the wait held "Connecting to your computer…" over the error for the whole timeout.
      return notifier.machinesLoading ||
          (notifier.machines.isEmpty &&
              !notifier.machinesAnswered &&
              !_machinesUnreadable);
    }
    return switch (phoneMachineStatusOf(machine)) {
      PhoneMachineStatus.needsPassword => false,
      PhoneMachineStatus.offline => phoneAccountSaysOnline(
        machine.machine.status,
      ),
      PhoneMachineStatus.connecting => true,
      PhoneMachineStatus.ready => switch (machine.agentLoadStatus) {
        AgentLoadStatus.loaded || AgentLoadStatus.needsLink => false,
        AgentLoadStatus.idle ||
        AgentLoadStatus.loading ||
        AgentLoadStatus.error => true,
      },
    };
  }

  /// How long the remembered agent gets to have its terminal verified, once its machine has listed
  /// it — see [_pendingEntryFor].
  ///
  /// 10s: the daemon's reconciler sweeps once as it starts and then every five seconds at its floor
  /// (`TMUX_REAP_INTERVAL_MS`), so a pane that is really there is reported inside two sweeps. Past
  /// that the agent genuinely has no terminal — a pane that was closed, a machine that reaped it —
  /// and the screen stops holding out for one.
  static const _terminalWaitTimeout = Duration(seconds: 10);
  Timer? _terminalWait;
  bool _terminalWaitGaveUp = false;

  /// Whether the remembered agent is listed with its terminal still unverified, and the screen is
  /// still willing to wait for it.
  ///
  /// ⚠️ Arms [_terminalWait] on the first frame that waits, and is called from `build` — a timer,
  /// not a rebuild, so it changes nothing in the frame it is created in. It cannot be armed with
  /// [_restoreDeadline] instead: that one starts when the record is read, while this wait only
  /// begins once a machine has listed the agent, which may be seconds later.
  bool _terminalStillComing(
    List<AgentEntry> entries,
    ({String machineId, String agentId}) agent,
  ) {
    if (_terminalWaitGaveUp) return false;
    if (_pendingEntryFor(entries, agent) == null) return false;
    _terminalWait ??= Timer(_terminalWaitTimeout, () {
      if (!mounted) return;
      setState(() => _terminalWaitGaveUp = true);
    });
    return true;
  }

  /// Whether the screen is currently holding out for the remembered agent — see [_target]. Read by
  /// build so the wait draws as "Connecting…", never as the empty state.
  bool _waitingForRestore = false;

  /// Whether that wait is for the agent's own terminal rather than for its machine — see
  /// [_terminalStillComing]. Only the message differs; saying "Connecting to your computer…" over a
  /// machine that has already answered names the wrong thing to be patient with.
  bool _waitingForTerminal = false;

  /// Whether the screen is holding out for the desk's tabs before it falls back — see [_target].
  bool _waitingForDesk = false;

  /// What to tell somebody while the screen holds out for the agent it means to reopen.
  String? _restoreMessage() {
    if (_waitingForTerminal) return 'Reopening your harness…';
    // Every other machine may be up and loaded while the one holding the remembered agent is still
    // dialling — without this the wait would draw as "No agents yet".
    if (_waitingForRestore) return 'Connecting to your computer…';
    if (_waitingForDesk) return 'Opening your tabs…';
    return null;
  }

  /// The agent to draw, given what the account can currently reach.
  ///
  /// In order:
  ///  - a machine just unlocked has the first claim, once it has an agent to offer;
  ///  - otherwise the pager already up keeps the screen, wherever its own swipes have taken it —
  ///    and through its machine going away for a moment ([_awayEntryFor]);
  ///  - failing that the agent this screen last held, then the first agent of the tab the phone
  ///    was last in ([_firstOfLastTab]), then the most recently active one — a home screen with no
  ///    list behind it cannot afford to show nothing while agents exist;
  ///  - nothing openable at all → null, and the empty state says so.
  AgentEntry? _target(List<AgentEntry> entries) {
    _waitingForRestore = false;
    _waitingForTerminal = false;
    _waitingForDesk = false;
    // Picked by hand elsewhere — see [AgentHome.openAgent]. Until it is in the list, the screen keeps
    // what it has rather than blanking.
    final requested = _requestedAgent;
    if (requested != null) {
      // ⚠️ **Listed but not verified yet is taken too — see [_pendingEntryFor].** A computer just
      // set up from this phone has its OpenCode listed, but nobody has looked at its pane, so it
      // reads unopenable until something attaches it — and the screen kept the pane of another
      // computer, forever, while waiting for that. The pager built for it attaches it.
      final picked =
          _entryFor(entries, requested) ?? _pendingEntryFor(entries, requested);
      if (picked != null) return picked;
    }
    // The onboarding's computer, joined: the session used on it last — the one in focus there,
    // which the desktop marks opened as its pane takes focus — and failing that the account's. The
    // phone has no say of its own in which (owner, 2026-10-12): the computer decides.
    final joining = _joining;
    if (joining != null && _onboarding) {
      final pick =
          _lastUsed(
            entries.where((entry) => entry.machineId == joining.machineId),
          ) ??
          _lastUsed(entries);
      if (pick != null) return pick;
    }
    // A machine just unlocked outranks what is on screen — see [AgentHome.openMachineId]. Until it
    // has an agent to offer, everything below carries on as usual, so the screen keeps showing
    // something real while the machine dials rather than blanking to a skeleton.
    final awaiting = _awaitingMachine;
    if (awaiting != null) {
      final arrival = _mostRecentOpenable(
        entries.where((entry) => entry.machineId == awaiting),
      );
      if (arrival != null) return arrival;
    }
    // ⚠️ **The pager the screen already holds is asked FIRST, before [_showing], and that ordering
    // is what keeps swiping alive.** A swipe moves the pager and reports the agent it arrived at,
    // which lands in [_showing] — so asking [_showing] first would name an agent the live pager was
    // not built for, the key below would change, and the pager would be torn down and rebuilt on
    // every swipe. Asked in this order, a pager that is still openable simply stays.
    final opened = _neighboursFor;
    if (opened != null) {
      final live = _entryFor(entries, opened);
      if (live != null) return live;
      // ⚠️ **Unopenable for a moment is not gone — see [_pendingEntryFor].** Returned so `chosen`
      // goes on naming the agent the pager was built for: the key and the snapshot below are left
      // exactly as they are, and the terminal on screen reattaches by itself once the pane is
      // verified (`_attachPendingPanes`). Falling through instead moved somebody off the terminal
      // they were reading, onto an unrelated agent, for a flag that flips back a second later.
      // A real deletion still takes the pager away, through [_dropPagerIfShownAgentWasDeleted].
      final pending = _pendingEntryFor(entries, opened);
      if (pending != null) return pending;
      // ⚠️ **Its machine away for a moment is not the agent gone either — see [_awayEntryFor].**
      // Falling through here is what sent the screen to another machine's agent seconds after an
      // agent was picked in Find, and kept it there once the machine came back.
      final away = _awayEntryFor(opened);
      if (away != null) return away;
    }
    final showing = _showing;
    if (showing != null) {
      final held = _entryFor(entries, showing);
      if (held != null) return held;
      // ⚠️ **The agent from last time is waited for while its machine is still coming up.** With two
      // machines, the one that answers first used to win: its first agent took the screen, a pager
      // was built around it, and when the machine holding the remembered agent arrived a second
      // later there was no going back to it. Only before any pager is up, only while that machine
      // is genuinely on its way, and only until [_restoreDeadline] — an agent that was deleted, or a
      // machine that stays down, still falls through to the first agent below.
      if (_neighboursFor == null && !_restoreGaveUp) {
        if (_machineStillComing(showing.machineId)) {
          _waitingForRestore = true;
          return null;
        }
        // ⚠️ **And the agent's own terminal is waited for after that, which is a different wait.**
        // Its machine can be answering with a loaded list and the agent on it still be unopenable,
        // for the seconds its pane takes to be verified — see [_terminalStillComing]. Without this
        // the record lost its claim in exactly that window, and the launch settled for the first
        // agent that happened to have been verified already.
        if (_terminalStillComing(entries, showing)) {
          _waitingForRestore = true;
          _waitingForTerminal = true;
          return null;
        }
      }
    }
    // ⚠️ **The tabs are waited for before settling on anything.** They are read over the network
    // (`PhoneDesk`), and a fallback taken before they land picks from the whole account — then holds
    // the screen, because a pager up is not moved. Bounded by the launch's own deadline.
    if (!widget.notifier.deskSettled && !_restoreGaveUp) {
      _waitingForDesk = true;
      return null;
    }
    return _firstOfLastTab(entries) ?? _mostRecentOpenable(entries);
  }

  /// The first agent of the tab the phone was last in — or, when that tab has nothing to open, of
  /// the first tab that does. Null on a phone with no tabs.
  ///
  /// ⚠️ **What a launch falls back on when the agent it left cannot be opened (owner, 2026-09-24).**
  /// The phone is built around tabs, so the agent somebody expects is the one heading the tab they
  /// were working in — not the most recently active harness anywhere on the account, which is a
  /// stranger to that tab as often as not. [AppNotifier.activeDeskTabId] names it: this phone's own
  /// choice, carried over from the last run by [_readLast].
  AgentEntry? _firstOfLastTab(List<AgentEntry> entries) {
    final notifier = widget.notifier;
    if (notifier.deskTabs.isEmpty) return null;
    final tabs = [
      for (final tab in deskGroups(notifier, entries))
        if (!tab.isEmpty) tab,
    ];
    final last = notifier.activeDeskTabId;
    final tab =
        tabs.where((tab) => tab.id == last).firstOrNull ?? tabs.firstOrNull;
    return tab?.entries.first;
  }

  /// The agent to fall back on: the one whose conversation moved last, of those that can be opened.
  ///
  /// ⚠️ **Not the first in the list, which is what it was — and the first is the OLDEST.** [entries]
  /// run in each machine's own order, which is creation order, so every miss of the record above —
  /// the agent left on paused from the desktop's monitor since, deleted, or no record at all — landed
  /// on the same agent untouched for days, and the pager then remembered THAT, so it stuck. The
  /// desktop's monitor puts the most recently active harness on top ([compareMonitorOrder]); this is
  /// the agent somebody means when the one they left is gone.
  static AgentEntry? _mostRecentOpenable(Iterable<AgentEntry> entries) {
    AgentEntry? best;
    for (final entry in entries) {
      if (!entry.agent.terminalAvailable) continue;
      if (best == null || compareMonitorOrder(entry, best) < 0) best = entry;
    }
    return best;
  }

  /// The openable agent used last — the later of its conversation moving and an app opening it
  /// ([Agent.lastUsedAt]) — for the onboarding's first session only. Everywhere else the phone
  /// follows the conversation alone ([compareMonitorOrder], owner's call): this one follows the
  /// desktop, whose focused pane is stamped opened, so the phone opens what the computer is on.
  static AgentEntry? _lastUsed(Iterable<AgentEntry> entries) {
    AgentEntry? best;
    for (final entry in entries) {
      if (!entry.agent.terminalAvailable) continue;
      if (best == null) {
        best = entry;
        continue;
      }
      final used = entry.agent.lastUsedAt, bestUsed = best.agent.lastUsedAt;
      final later = switch ((used, bestUsed)) {
        (final a?, final b?) => a.isAfter(b),
        (_?, null) => true,
        (null, _?) => false,
        (null, null) => compareMonitorOrder(entry, best) < 0,
      };
      if (later) best = entry;
    }
    return best;
  }

  /// Whether any machine can currently host an agent.
  ///
  /// The gate between the two empty screens, and the same test every `+` in the app applies: an
  /// agent needs a machine that answers, so while none does there is nothing an Agents screen could
  /// offer and the machines screen is the whole answer.
  bool _anyMachineReady() => filterableMachines(
    widget.notifier,
  ).any((machine) => phoneMachineStatusOf(machine) == PhoneMachineStatus.ready);

  /// What to tell somebody who is waiting, or null once there is nothing left to wait for.
  ///
  /// Null is the whole point of the return type: it is what separates "still coming" from "answered,
  /// and the answer is nothing", and only the second one may draw an empty state. Getting that
  /// backwards in either direction is a real bug on a launch screen — a spinner that never stops
  /// looks broken, and "No agents yet" shown a second before the agents arrive is a lie the person
  /// acts on.
  ///
  /// The message names the step actually in progress rather than saying "Loading…" throughout. On a
  /// cold launch these run several seconds each, and a line that changes is how somebody can tell a
  /// slow connection from a stuck one.

  /// The last line [_traceLoading] wrote, so a wait is logged as a step rather
  /// than as one line per frame.
  String? _tracedLoading;
  bool _tracedReady = false;

  /// Record each step of the wait as the screen enters it.
  ///
  /// This is the wait as the PERSON experiences it, which is the only timeline
  /// that settles whether a launch is slow: everything else in the log measures
  /// one operation, while this measures how long the phone showed a given
  /// sentence. "Connecting to your computer…" covers a dial, an E2EE handshake
  /// and an agent list (see `phone_status.dart`), so the gap between this line
  /// and the next is the only place that stretch appears as a number at all.
  ///
  /// ⚠️ Called from `build`, so it must write only on a CHANGE. [appLog] is a
  /// synchronous flushed file write (`logging/log_file.dart`); at 60fps an
  /// unguarded call here would fsync a line per frame and slow down the very
  /// wait it claims to be measuring.
  void _traceLoading(String? message) {
    if (message == null) {
      // The first screen with real content on it ends the launch — and only the
      // first: a later empty state is not a launch, and re-arming this would
      // report the wait as starting over.
      if (_tracedReady) return;
      _tracedReady = true;
      _tracedLoading = null;
      StartupTrace.mark('home.ready');
      return;
    }
    if (message == _tracedLoading) return;
    _tracedLoading = message;
    StartupTrace.mark('home.waiting: $message');
  }

  String? _loadingMessage() {
    // Waited long enough — see [_loadingTimeout]. ⚠️ Checked before [_readingLast] and not after:
    // the local read is the one step that cannot be retried from the empty state, so if even that
    // has not landed in 45 seconds the screen has to stop waiting on it too.
    if (_gaveUpWaiting) return null;
    // The local record first: it is read from storage and decides which agent is even wanted, so
    // until it lands nothing else has been decided either.
    if (_readingLast) return 'Getting things ready…';
    final notifier = widget.notifier;
    // Then the account's machines, over the network.
    if (notifier.machines.isEmpty) {
      return notifier.machinesLoading ? 'Looking for your computers…' : null;
    }
    final machines = filterableMachines(notifier);
    // ⚠️ **The first machine to answer ends the wait; the others catch up behind
    // a screen that is already usable.** Both tests below ask whether ANY
    // machine is still coming, which made a launch as slow as the SLOWEST
    // machine on the account: one box still dialling held a full-screen spinner
    // over agents that another machine had already listed and was ready to open.
    //
    // Once a machine has delivered its agents there is nothing left to wait for.
    // The caller opens one, and a machine that answers a second later simply
    // adds its agents to a list that is already on screen — which is what
    // `phoneMachineListsAgents` and the pager have always done for a machine
    // that reconnects.
    //
    // The remembered agent keeps its head start regardless: this runs only when
    // [_target] found nothing to show, and [_target]'s own `_waitingForRestore`
    // (checked by the caller) still holds the screen while the machine holding
    // that agent is genuinely on its way.
    if (machines.any(phoneMachineListsAgents)) return null;
    // Then each machine's own socket. `connecting` covers both the dial and the handshake after it.
    //
    // ⚠️ A machine locked while the device key log is still being read counts as connecting: on a
    // phone just signed in, every machine is locked until the log vouches for it, which it does a
    // few seconds later and opens the machine by itself — see [AppNotifier.deviceTrustSettling].
    // Drawn as the machines list meanwhile, it said "locked · scan its code" and then jumped away.
    if (machines.any(
      (machine) => switch (phoneMachineStatusOf(machine)) {
        PhoneMachineStatus.connecting => true,
        PhoneMachineStatus.needsPassword => notifier.deviceTrustSettling,
        PhoneMachineStatus.ready || PhoneMachineStatus.offline => false,
      },
    )) {
      return 'Connecting to your computer…';
    }
    // And finally the agent list a connected machine still owes. ⚠️ Only from machines that are
    // READY: an offline one is left at whatever `agentLoadStatus` it had when it dropped, and
    // waiting on that never ends.
    final loadingAgents = machines.any((machine) {
      if (phoneMachineStatusOf(machine) != PhoneMachineStatus.ready) {
        return false;
      }
      return switch (machine.agentLoadStatus) {
        AgentLoadStatus.idle || AgentLoadStatus.loading => true,
        AgentLoadStatus.loaded ||
        AgentLoadStatus.error ||
        AgentLoadStatus.needsLink => false,
      };
    });
    return loadingAgents ? 'Loading your harnesses…' : null;
  }

  /// The entry naming [agent], if it is in [entries] and can actually be opened.
  AgentEntry? _entryFor(
    List<AgentEntry> entries,
    ({String machineId, String agentId}) agent,
  ) => entries
      .where(
        (entry) =>
            entry.machineId == agent.machineId &&
            entry.agent.id == agent.agentId &&
            entry.agent.terminalAvailable,
      )
      .firstOrNull;

  /// The entry naming [agent] while it is LISTED but not attachable yet — the machine has it, its
  /// terminal has simply not been verified in this instant. Null for an agent that is not there,
  /// and for a stopped one, whose terminal is not coming back on its own.
  ///
  /// ⚠️ **"No terminal" is what an agent looks like while nobody has LOOKED at its pane, not what a
  /// missing agent looks like.** The daemon clears every agent's availability as it loads its
  /// registry (`cli/src/lib/registry.ts`) and fills it back in one agent at a time, as its terminal
  /// reconciler observes each pane — so a restart leaves every agent on the machine reading
  /// unopenable for a moment, and each `agent_synced` frame after it turns one of them back on.
  /// Reading that as "gone" is what sent a launch, and a pager mid-session, to whichever agent
  /// happened to be verified first: the oldest one on the machine.
  AgentEntry? _pendingEntryFor(
    List<AgentEntry> entries,
    ({String machineId, String agentId}) agent,
  ) => entries
      .where(
        (entry) =>
            entry.machineId == agent.machineId &&
            entry.agent.id == agent.agentId &&
            !entry.agent.terminalAvailable &&
            !entry.agent.isStopped,
      )
      .firstOrNull;

  /// The entry naming [agent] while its MACHINE is away for a moment — offline, or redialling with
  /// no list to show — so the agent is missing from [entries] altogether rather than listed and
  /// unopenable ([_pendingEntryFor]). Built from the machine's own list, which going away leaves
  /// exactly as it was.
  ///
  /// Null once the machine answers (a loaded list without the agent is a real deletion, which
  /// [_dropPagerIfShownAgentWasDeleted] handles), when it wants its password (nothing comes back
  /// until somebody enters it), for a machine no longer on the account, and for a stopped agent,
  /// whose terminal is not coming back on its own.
  ///
  /// ⚠️ **Why the pager holds on here rather than falling back (owner, 2026-09-30).** [entries]
  /// only carries the machines [phoneMachineListsAgents] lets through, and a machine drops out of
  /// it the moment it reads offline — which a timed-out request (`_recoverStaleSession` in
  /// `app_state.dart`) or a `node_status` push makes it do for a few seconds, while it redials and
  /// comes straight back. The agent on screen went with it: [_target] found neither the pager's
  /// agent nor [_showing], and settled for the first agent of the last tab — on ANOTHER machine,
  /// one still answering. A pager was built around that one, and when the machine came back a
  /// second later nothing moved the screen back, because a pager that is up is never moved. Seen
  /// as: pick "hn" in Find and two seconds later the phone is back on the agent it launched on;
  /// pick "cmd p" and twenty seconds later, the same again.
  ///
  /// Held with no deadline, on purpose. The terminal on screen already says its machine is offline
  /// or reconnecting and reattaches by itself when it answers, and Find leaves it at any time — a
  /// screen that swaps to another agent on its own, under somebody reading, is the bug. Except with
  /// every machine away, when there is no other agent to swap to: [_dropPagerIfEveryMachineAway].
  AgentEntry? _awayEntryFor(({String machineId, String agentId}) agent) {
    final machine = widget.notifier.stateOf(agent.machineId);
    if (machine == null || phoneMachineListsAgents(machine)) return null;
    if (phoneMachineStatusOf(machine) == PhoneMachineStatus.needsPassword) {
      return null;
    }
    final held = machine.agents
        .where((listed) => listed.id == agent.agentId && !listed.isStopped)
        .firstOrNull;
    return held == null ? null : AgentEntry(machine: machine, agent: held);
  }

  @override
  Widget build(BuildContext context) => ListenWhileInSight(
    // Out of sight under Swarm Home it builds nothing, however busy the app is, and catches up
    // when shown ([OutOfSight]).
    listenable: widget.notifier,
    builder: (context) {
      if (kTypingTrace) typingCount('home.build');
      AppTheme.watch(context);
      // Signed in from a scanned "Add phone" QR: once its computer is here and locked, pair with
      // the QR's code — no password. See `welcome/connect_code.dart`.
      if (widget.notifier.pendingPairing case final pending?) {
        final machine = widget.notifier.machineStates[pending.machineId];
        // ⚠️ Kept up once its pairing has begun ([AppNotifier.pendingPairingTried]), not only while
        // the machine reads locked: a redial that unlocks it for a moment took the page down
        // mid-pairing, and built it again to spend the one-time code a second time.
        if (machine != null &&
            (machine.needsLink || widget.notifier.pendingPairingTried)) {
          _endLaunchWait();
          return PairingWithCode(
            key: ValueKey('pairing-${pending.machineId}'),
            notifier: widget.notifier,
            machineId: pending.machineId,
            code: pending.code,
          );
        }
      }
      _noticeJoin();
      final entries = visibleAgents(agentIndex(widget.notifier));
      _openNewAgentIfUnlockedMachineIsEmpty(entries);
      _dropPagerIfShownAgentWasDeleted(entries);
      _dropPagerIfEveryMachineAway();
      // ⚠️ `_readingLast` holds the screen back so the record gets to name the agent before the
      // fallback does — but only while the screen is still willing to wait at all. Past
      // [_loadingTimeout] a read that has not returned is not going to, and going on to pick an
      // agent beats holding an empty screen against one that is sitting right there.
      final target = (_readingLast && !_gaveUpWaiting)
          ? null
          : _target(entries);
      if (_holdForJoin(target)) {
        _endLaunchWait();
        return _joinStage(target);
      }
      if (target == null) {
        // ⚠️ Still on its way in and actually empty are two different screens, and the difference
        // matters more here than it did on a list. A list could show its own shape greyed out while
        // it filled; what is coming here is a TERMINAL, so a placeholder in the shape of a list of
        // cards promises the wrong thing and then never delivers it. [_AgentHomeLoading] says what
        // is happening in words instead, and hands over to the terminal's own "Attaching…" — the
        // two are built to read as one sequence.
        final loading = _loadingMessage() ?? _restoreMessage();
        _traceLoading(loading);
        if (loading != null) {
          _holdLaunchWait();
          if (_onboarding) return _onboardingWait(loading);
          return _AgentHomeLoading(
            message: loading,
            notifier: widget.notifier,
            slow: _loadingSlow,
          );
        }
        _endLaunchWait();
        // ⚠️ **No machine is open → this is a MACHINE problem, so the machine screen is what the
        // person gets.** An "Agents" header over "No machines are open yet" named the thing that is
        // missing rather than the thing to do about it, and the only route to a password form was
        // the search glyph in the corner — the least likely place to look for one. An agent cannot
        // exist before a machine is linked, so until one is, this screen IS the machines screen:
        // rows to tap, a password form behind the one that wants it, and pull-to-refresh.
        //
        // The Machines TAB itself is untouched and still reachable by every other route; this just
        // borrows its body rather than growing a second, drifting copy of the same list.
        if (!_anyMachineReady()) {
          // No computer at all: how to set one up, watching for it to appear. One that is there
          // but locked or asleep: the machines list, with its password form.
          if (widget.notifier.machines.isEmpty &&
              !widget.notifier.machinesLoading) {
            // ⚠️ **A list that could not be read is not an empty account.** A first fetch that
            // failed leaves the list empty and not loading, exactly as an account with no computer
            // does, and this drew "Get Harness for your computer" — with "Not you? Sign out" — for
            // somebody who has computers, over a reason ("Could not load machines…") said nowhere.
            // The machines screen says it, with its Try again. A list neither answered nor failed
            // still gets the set-up page, whose watch asks again every few seconds.
            if (_machinesUnreadable) {
              return MachinesTab(notifier: widget.notifier);
            }
            return _goToYourComputer();
          }
          // The one computer there is, awake and waiting for its phone password: the unlock
          // itself, not a list of one to tap through — the moment setup pays off.
          final only = widget.notifier.machineStates.values
              .where(
                (state) => state.machine.authMode == MachineAuthMode.remote,
              )
              .toList();
          if (only.length == 1 &&
              only.single.needsLink &&
              only.single.nodeOnline != false) {
            return LinkPage(
              notifier: widget.notifier,
              machineId: only.single.machine.machineId,
              embedded: true,
            );
          }
          return MachinesTab(notifier: widget.notifier);
        }
        _openNewAgentAfterLastOneWent();
        return _AgentHomeEmpty(notifier: widget.notifier);
      }
      _endLaunchWait();
      // The onboarding handing over to the session it was waiting for: it grows in, once.
      final handOver = _onboarding && _joining != null;
      if (handOver) _measureHandOver();
      // Nothing remembered, nothing picked: the sessions, each a tap from its terminal — but not at
      // the end of the onboarding, which opens the computer's own session ([_target]).
      if (!handOver &&
          _welcome &&
          _neighboursFor == null &&
          _requestedAgent == null) {
        _onboardingDone = true;
        return PickUpPage(notifier: widget.notifier);
      }
      _onboardingDone = true;
      final chosen = (machineId: target.machineId, agentId: target.agent.id);
      // Its one line by the mic, for the session's page to say until the first send.
      if (handOver) {
        widget.notifier.firstSessionLine = (
          machineId: chosen.machineId,
          agentId: chosen.agentId,
          text: _firstLine(target),
        );
      }
      // ⚠️ **A swipe stays inside one tab, and this is where that happens.** The
      // account's tabs are the desk's (`state/phone_desk.dart`); [deskGroups]
      // fills each one with the agents of it this phone can reach, and the tab
      // the agent about to be shown belongs to is the one the screen is in. The
      // pager is given THAT tab's agents and nothing else — so a tab of four is
      // four swipes, and the other tabs are a tap on the strip away.
      //
      // Derived from the agent rather than held as state on purpose: an agent
      // can arrive from search, from a notification or from the record of last
      // time, none of which know about tabs, and the strip still lights the tab
      // it belongs to. An account with no tabs gets one group over everything,
      // which is the phone exactly as it was.
      final groups = deskGroups(widget.notifier, entries);
      // The agent ON SCREEN while the pager is staying up — it may have been swiped to from the one
      // the pager opened on — and the tab the phone is in is that agent's. The agent held onto may be
      // in a different tab than the one the target named: a tab closed on another computer moves
      // what is on screen into another tab, or out of them all.
      final showing = _showing;
      final onScreen = _neighboursFor == chosen && showing != null
          ? _entryFor(entries, showing)
          : null;
      final here = onScreen == null
          ? chosen
          : (machineId: onScreen.machineId, agentId: onScreen.agent.id);
      // An agent no tab holds — opened from search — is swiped alone: there is no "Other" group to
      // walk any more (see [deskGroups]), and its neighbours are no tab's.
      final group = isUntabbed(widget.notifier, here)
          ? untabbedGroup(onScreen ?? target)
          : activeDeskGroup(widget.notifier, groups, here);
      // What the phone is in, recorded for the paths that cannot derive it: an
      // agent created here joins this tab (`PhoneDesk.adopt`).
      widget.notifier.noteDeskTab(group.id);
      // A pager already up for this agent is LEFT ALONE — same key, same snapshot, so it keeps the
      // page it is on, and [_showing] keeps naming whatever it has been swiped to. A pager is built
      // here only when there is none, or when the one there opened on an agent that can no longer be
      // opened; only then does this screen's own idea of where it is get overwritten.
      //
      // ⚠️ **[_showing] is set HERE and not from [target] unconditionally, which is a bug that was
      // in this line.** While a pager is live, `target` is by construction the agent it OPENED on
      // (see [_target]) — not the agent on screen — so assigning it every build would quietly undo
      // every swipe the pager reported, one frame after it reported it.
      if (_neighboursFor != chosen) {
        if (kTypingTrace) {
          typingEvent('switch: pager built for ${_shortId(chosen.agentId)}');
        }
        _neighboursFor = chosen;
        _neighbours = AgentSwipeList(group.entries);
        _showing = chosen;
        // ⚠️ **The attach, which nothing else makes for the page this screen opens on.** A pager
        // pushed from a list got it from `openAgent`, which starts `selectAgent` beside the push;
        // this pager is built in place, and [AgentSwipeHost] only attaches the agents it is SWIPED
        // to. Without this the opening agent sat on "Attaching…" forever — while the page one swipe
        // over came up Live — unless a pane for it happened to survive from an earlier run.
        //
        // After the frame, because this is build. `selectAgent` reuses a pane already there and only
        // reopens a session that is dead, so a pager rebuilt around a live agent costs nothing.
        final attach = chosen;
        WidgetsBinding.instance.addPostFrameCallback((_) {
          if (!mounted || _neighboursFor != attach) return;
          unawaited(_attachOnly(attach));
        });
      }
      // Spent only by an agent of the machine the jump actually named. Not by [_onAgentChanged],
      // which would treat the unrelated agent drawn while that machine is still dialling as the jump
      // having been met — and it would then never fire.
      if (_awaitingMachine == chosen.machineId) _awaitingMachine = null;
      // Met: from here the pager built for it holds the screen, the ordinary way.
      if (_requestedAgent == chosen) _requestedAgent = null;
      final opened = chosen;
      // ⚠️ **Keyed by the agent the pager OPENED on, not by the agent on screen, and the two come
      // apart the moment somebody swipes.** The pager moves through its own pages internally; this
      // screen hears about it through [_onAgentChanged] and records it in [_showing] — but if the key
      // followed that, every swipe would hand Flutter a new key, tear the pager down and build a
      // fresh one around the agent just arrived at. The swipe would appear to work once and then the
      // screen would sit frozen on it, having thrown away the pager whose pages are the only way on.
      //
      // So the key changes only when [_target] picks a DIFFERENT agent than the pager was built for,
      // which happens when the one it opened on can no longer be opened at all.
      // Always under [_GrowIn], growing or not: the pager's place in the tree stays the same, so a
      // pager already up is never rebuilt for it.
      return _GrowIn(
        grow: handOver,
        child: AgentSwipeHost(
          // The generation is what lets a pager be REBUILT around the same opening agent — see
          // [_dropPagerIfShownAgentWasDeleted]; the agent alone would hand Flutter the same key.
          key: ValueKey(
            '${opened.machineId}/${opened.agentId}#$_pagerGeneration',
          ),
          notifier: widget.notifier,
          machineId: opened.machineId,
          agentId: opened.agentId,
          // ⚠️ **No neighbours: Focus holds ONE agent, and there is no sideways swipe.** The person
          // moves with Find, the sheet the handle at the foot of the terminal brings up (see
          // `docs/plans/2026-09-26-001-mobile-zero-questions.md`). A swipe was hidden — nothing said
          // it was there or what came next — and it fired by accident while scrolling or typing.
          // [_neighbours] is still taken for the tab, but only to pick where to land when the agent
          // on screen is deleted.
          neighbours: null,
          // Told where it has swiped to, so [_showing] follows the pager rather than the pager
          // being dragged back to where this screen last put it.
          onAgentChanged: _onAgentChanged,
        ),
      );
    },
  );

  /// A wait while the onboarding is still under way ([_onboarding]): the picture looking, and the
  /// step in progress on the line under it — "Looking for your computer" while the account's
  /// computers are not known yet, the ordinary step after that ("Connecting to your computer").
  ///
  /// The same [OnboardingStage] as [_goToYourComputer] and in the same place, so the picture carries
  /// on from one to the other. Settings, and the computers, once the wait is slow — as on
  /// [_AgentHomeLoading].
  Widget _onboardingWait(String step) {
    final notifier = widget.notifier;
    final said = notifier.machines.isEmpty
        ? OnboardingCopy.looking
        : _withoutEllipsis(step);
    return OnboardingStage(
      headline: '',
      scene: OnboardingScene.looking,
      enterFrom: notifier.signedInThisRun ? OnboardingScene.welcome : null,
      status: OnboardingStatus(said),
      trailing: _loadingSlow ? PhoneSettingsButton(notifier: notifier) : null,
      actions: _loadingSlow
          ? Center(
              child: TtyTextButton(
                key: const ValueKey('home-wait-computers'),
                label: 'See your computers ›',
                size: TtySize.meta,
                onPressed: () => _seeComputers(context, notifier),
              ),
            )
          : null,
    );
  }

  /// ② Your computer, at home: an account with no computer yet. "On your computer, go to" and the
  /// address that sends the download, the picture looking, the account watched every few seconds —
  /// the computer turning up takes this away by itself (`welcome/your_computer.dart`).
  ///
  /// Settings at the top right is the way out (Sign out among it): a "looking" with no way out is
  /// one of the things the onboarding leaves out on purpose.
  ///
  /// ⚠️ **What to do on the computer, said under the link, until the phone adds it itself** —
  /// download and install Harness, and sign in with this account ([GoToComputer]). The spec's
  /// computer is added by the waiting phone and never signs in; until that lands (it needs the
  /// desktop and the backend), the computer signs in on its own — with this account, and it joins,
  /// and this screen moves on; with one of the person's other Google accounts, and it never does.
  Widget _goToYourComputer() {
    final notifier = widget.notifier;
    if (_onboarding) {
      _awaitedComputer = true;
      notifier.onboardingMeasurement.start(ProductFlow.computerWait);
    }
    return OnboardingStage(
      headline: OnboardingCopy.goToHeadline,
      headlineKey: const ValueKey('home-go-to'),
      scene: OnboardingScene.looking,
      enterFrom: notifier.signedInThisRun ? OnboardingScene.welcome : null,
      underHeadline: ComputerWatch(
        notifier: notifier,
        child: GoToComputer(
          account: notifier.currentUser?.email,
          notYou: NotYouSignOut(notifier: notifier),
          onSent: () => notifier.onboardingMeasurement.mark(
            ProductFlow.computerWait,
            OnboardingMark.linkShared,
          ),
        ),
      ),
      status: const OnboardingStatus(OnboardingCopy.looking),
      trailing: PhoneSettingsButton(notifier: notifier),
    );
  }

  /// A step's words for the status line, whose cursor already says it is still going: the
  /// ellipsis would say it twice.
  static String _withoutEllipsis(String step) =>
      step.endsWith('…') ? step.substring(0, step.length - 1) : step;

  /// Whether the onboarding has a computer to join now, and starts its moment if so. Called from
  /// build; the moment itself starts after the frame.
  ///
  /// Which computer: after "On your computer, go to", the first on the account — the one set up for
  /// this phone, which is also named to the device log as the person's own
  /// ([AppNotifier.welcomeMachine]: no "New device" for it). Signed in to an account that already
  /// had computers, the first of them to answer.
  void _noticeJoin() {
    if (_joining != null || !_onboarding) return;
    final notifier = widget.notifier;
    if (_awaitedComputer) {
      final machine = notifier.machines.firstOrNull;
      if (machine == null) return;
      _joining = (machineId: machine.machineId, name: machine.displayName);
      notifier.onboardingMeasurement.end(
        ProductFlow.computerWait,
        ProductOutcome.ok,
      );
      // After the frame: it may take a "New device" down, which notifies — not during a build.
      final welcomed = machine.machineId;
      WidgetsBinding.instance.addPostFrameCallback((_) {
        if (mounted) notifier.welcomeMachine(welcomed);
      });
    } else {
      final ready = filterableMachines(notifier)
          .where(
            (machine) =>
                phoneMachineStatusOf(machine) == PhoneMachineStatus.ready,
          )
          .firstOrNull;
      if (ready == null) return;
      _joining = (
        machineId: ready.machine.machineId,
        name: ready.machine.displayName,
      );
    }
    notifier.onboardingMeasurement.start(ProductFlow.sessionOpen);
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (mounted) _moment.start();
    });
  }

  /// Whether "… is ready." holds the screen: through the moment, and after it while the computer's
  /// session is still on its way — the computer connecting, its list loading, or, connected and
  /// listed, no session on it yet (its own tour starts one) for up to [_firstSessionPatience]. A
  /// computer that turns out to want a password, or that the account says is down, lets go: what
  /// home shows for those is what to do about them.
  bool _holdForJoin(AgentEntry? target) {
    final joining = _joining;
    if (joining == null || !_onboarding) return false;
    // A session picked by hand meanwhile — in Find, from a notice — is a choice the moment does not
    // stand in front of.
    if (_requestedAgent != null) return false;
    if (!_moment.done) return true;
    if (target != null || _firstSessionGaveUp) return false;
    final notifier = widget.notifier;
    final machine = notifier.stateOf(joining.machineId);
    if (machine == null) return false;
    return switch (phoneMachineStatusOf(machine)) {
      PhoneMachineStatus.needsPassword => _holdUnless(
        notifier.deviceTrustSettling,
        OnboardingMark.blockedPassword,
      ),
      PhoneMachineStatus.offline => _holdUnless(
        phoneAccountSaysOnline(machine.machine.status),
        OnboardingMark.blockedOffline,
      ),
      PhoneMachineStatus.connecting => true,
      PhoneMachineStatus.ready => _waitForFirstSession(),
    };
  }

  /// [holding] as it is; letting go, the session will not open by itself, and [why] is counted.
  bool _holdUnless(bool holding, OnboardingMark why) {
    if (!holding) {
      widget.notifier.onboardingMeasurement.mark(ProductFlow.sessionOpen, why);
    }
    return holding;
  }

  /// The onboarding hands over to a session — its computer's own, or one picked meanwhile — and
  /// the first message there is next.
  void _measureHandOver() {
    final onboarding = widget.notifier.onboardingMeasurement;
    onboarding.end(ProductFlow.sessionOpen, ProductOutcome.ok);
    onboarding.start(ProductFlow.firstMessage);
  }

  /// Arms [_firstSessionPatience] on the first frame that waits for it. Called from build: a timer,
  /// not a rebuild.
  bool _waitForFirstSession() {
    _firstSessionWait ??= Timer(_firstSessionPatience, () {
      widget.notifier.onboardingMeasurement.end(
        ProductFlow.sessionOpen,
        ProductOutcome.failed,
      );
      if (!mounted) return;
      setState(() => _firstSessionGaveUp = true);
    });
    return true;
  }

  /// "MacBook Pro is ready." — the computer joining, on the same [OnboardingStage] as the wait and
  /// "On your computer, go to" before it, so the picture goes on from where it was: the laptop
  /// draws itself, links to the phone and lights, and the agent about to open types its name on it.
  /// A tap goes on sooner.
  ///
  /// Past the moment, while its session is still on its way, what it waits on is said under the
  /// picture, and Settings comes back — a wait is never without a way out.
  Widget _joinStage(AgentEntry? target) {
    final joining = _joining!;
    final notifier = widget.notifier;
    String? waiting;
    if (_moment.done && target == null) {
      final step = _loadingMessage() ?? _restoreMessage();
      waiting = step == null
          ? OnboardingCopy.waitingForSession
          : _withoutEllipsis(step);
    }
    return OnboardingStage(
      headline: OnboardingCopy.ready(joining.name),
      headlineKey: const ValueKey('home-ready'),
      scene: OnboardingScene.joined,
      enterFrom: OnboardingScene.looking,
      agent: target?.agent.engine,
      join: _moment.picture,
      status: waiting == null ? null : OnboardingStatus(waiting),
      trailing: waiting == null
          ? null
          : PhoneSettingsButton(notifier: notifier),
      onTap: _moment.done ? null : _moment.skip,
    );
  }

  /// What the phone says by the mic as the onboarding's session opens: one line, by what the
  /// computer opened (`docs/research/2026-10-11-phone-onboarding`, "Which session the phone opens").
  String _firstLine(AgentEntry target) {
    // Harness was already on the computer: whatever is on it, talk to it.
    if (!_awaitedComputer) return OnboardingCopy.micTalk;
    final agent = target.agent;
    // A conversation with a past — Claude Code or Codex resumed where it was left.
    if (agent.updatedAt != null) return OnboardingCopy.micPickUp;
    // OpenCode with the desktop's starter task typed into it, not sent.
    if (agent.engine == 'opencode') return OnboardingCopy.micSendIt;
    // A fresh session, at an empty prompt.
    return OnboardingCopy.micSayWhat;
  }

  /// Bumped whenever the pager is thrown away and rebuilt, and part of its key.
  int _pagerGeneration = 0;

  /// Enough of an agent id to tell agents apart in the typing trace.
  static String _shortId(String id) => id.length > 8 ? id.substring(0, 8) : id;

  /// The agent on screen was deleted while the pager's OPENING agent still exists: rebuild.
  ///
  /// ⚠️ **The pager is keyed by the agent it opened on, so it survives anything short of that
  /// agent going away — including the agent actually on screen going away.** Swipe from A to B,
  /// delete B, and [_target] still answers A, the key does not change, and the pager stays parked on
  /// B's page: a header reading "Agent" over "Attaching…" to a terminal that no longer exists, with
  /// nothing to leave to because this screen is the root.
  ///
  /// Only for a real deletion: the agent's machine is still answering with a loaded list, and the
  /// agent is not on it. A machine dropping out empties its entries too, and rebuilding for that
  /// would move the screen to another machine's agent when this one comes back in a moment.
  ///
  /// The last agent is left to [_openNewAgentAfterLastOneWent], which needs [_neighboursFor] intact
  /// to know there was a terminal to lose.
  void _dropPagerIfShownAgentWasDeleted(List<AgentEntry> entries) {
    final showing = _showing;
    if (_neighboursFor == null || showing == null) return;
    if (_entryFor(entries, showing) != null) return;
    final machine = widget.notifier.stateOf(showing.machineId);
    if (machine == null ||
        phoneMachineStatusOf(machine) != PhoneMachineStatus.ready ||
        machine.agentLoadStatus != AgentLoadStatus.loaded ||
        // A STOPPED agent stays on its machine's list (a stop arrives as `agent_synced`, and is
        // kept so it can be resumed) but there is nothing left on screen to show for it.
        machine.agents.any(
          (agent) => agent.id == showing.agentId && !agent.isStopped,
        )) {
      return;
    }
    if (!entries.any((entry) => entry.agent.terminalAvailable)) return;
    final next = _nextAfter(showing, entries);
    _neighboursFor = null;
    _neighbours = null;
    // The agent that was one swipe to the RIGHT of the deleted one takes its place — what the
    // person would have reached by swiping on. Null only if the snapshot has nothing still standing,
    // and then [_target] falls back to the first agent.
    _showing = next;
    _pagerGeneration++;
  }

  /// Every machine asleep: the pager goes, and the screen falls to the machines list.
  ///
  /// ⚠️ **The one exception to [_awayEntryFor]'s hold, and why it can be one.** That hold keeps the
  /// agent on screen through its machine going away, so the screen never swaps to ANOTHER machine's
  /// agent under somebody reading. With every machine away there is no other agent to swap to and
  /// nothing on its way: held, the phone sat on the terminal of a computer that was off — a
  /// skeleton, or its last screen — for as long as it stayed off (owner, 2026-10-08: it should go
  /// back to the machines screen). That list is what [build] shows when no machine can host
  /// anything, and it says which one is asleep and what to do about it.
  ///
  /// [_showing] is KEPT, and it is what brings the agent back: when its machine answers again,
  /// [_target] finds it, and a pager is built around it and attached, exactly as on a launch.
  ///
  /// Away as [phoneMachineAway] means it — the account agrees — so a socket dropping for the
  /// seconds of a redial never takes the terminal down.
  void _dropPagerIfEveryMachineAway() {
    if (_neighboursFor == null || !_everyMachineAway()) return;
    _neighboursFor = null;
    _neighbours = null;
    _pagerGeneration++;
  }

  /// Whether no machine on the account answers or is on its way: each one asleep, or locked for a
  /// password nothing here enters by itself. False before the account's machines are known — that
  /// is a launch, not an answer.
  bool _everyMachineAway() {
    final notifier = widget.notifier;
    final machines = filterableMachines(notifier);
    return machines.isNotEmpty &&
        machines.every(
          (machine) => switch (phoneMachineStatusOf(machine)) {
            PhoneMachineStatus.ready || PhoneMachineStatus.connecting => false,
            // A phone just signed in has every machine locked until the device key log vouches for
            // it, a few seconds later — see [AppNotifier.deviceTrustSettling].
            PhoneMachineStatus.needsPassword => !notifier.deviceTrustSettling,
            PhoneMachineStatus.offline => phoneMachineAway(machine),
          },
        );
  }

  /// The first agent after [deleted] in the pager's own order — wrapping past the end, as the pager
  /// does — that can still be opened.
  ///
  /// The SNAPSHOT's order, not a fresh [visibleAgents]: "the one to the right" means the page the
  /// person would have swiped to, and the live list may have reordered since the pager opened.
  ({String machineId, String agentId})? _nextAfter(
    ({String machineId, String agentId}) deleted,
    List<AgentEntry> entries,
  ) {
    final order = _neighbours?.entries ?? const <AgentEntry>[];
    final at = order.indexWhere(
      (entry) =>
          entry.machineId == deleted.machineId &&
          entry.agent.id == deleted.agentId,
    );
    if (at < 0) return null;
    for (var step = 1; step < order.length; step++) {
      final candidate = order[(at + step) % order.length];
      final ref = (machineId: candidate.machineId, agentId: candidate.agent.id);
      if (_entryFor(entries, ref) != null) return ref;
    }
    return null;
  }

  /// A machine just unlocked that turns out to have no agents: the form for its first one, rather
  /// than a screen saying there is nothing here.
  ///
  /// Somebody who has just entered a password came to use that machine, and with nothing on it the
  /// only next step is creating an agent — so the phone takes that step for them. The form opens on
  /// the machine the password was for, which is the one they will want it on.
  ///
  /// ⚠️ Only once the machine has ANSWERED with its list — ready and `loaded` — never while it is
  /// still dialling. Before that an empty list means "not yet", and opening the form then would put
  /// it over the agent that arrives a second later. The request is spent here either way, so the
  /// form opens once and backing out of it does not bring it straight back.
  ///
  /// Pushed after the frame: this runs inside build, where a push trips the navigator's lock.
  void _openNewAgentIfUnlockedMachineIsEmpty(List<AgentEntry> entries) {
    final awaiting = _awaitingMachine;
    if (awaiting == null) return;
    final machine = widget.notifier.stateOf(awaiting);
    if (machine == null ||
        phoneMachineStatusOf(machine) != PhoneMachineStatus.ready ||
        machine.agentLoadStatus != AgentLoadStatus.loaded) {
      return;
    }
    final hasAgent = entries.any(
      (entry) => entry.machineId == awaiting && entry.agent.terminalAvailable,
    );
    if (hasAgent) return;
    _awaitingMachine = null;
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (!mounted) return;
      unawaited(openNewAgent(context, widget.notifier, awaiting));
    });
  }

  /// Attaches the agent a new pager opened on, then closes every other pane no pager is holding.
  ///
  /// The close is what `openAgent` used to do beside its push (`keepOthers: false`), and it matters
  /// more now that agents are switched IN PLACE: the pager being replaced keeps the pane of the
  /// agent it last showed — right for a pager popped back to a list, wrong here, where nothing will
  /// ever show that pane again. Without it every agent picked from search would leave a live remote
  /// stream behind.
  ///
  /// ⚠️ **Not the panes the new pager holds.** It attaches the pages beside its own ahead of the
  /// first swipe (see [agentPaneHeldByPager]), and closing those here would undo that a frame after
  /// it started; they are that pager's to close, and it does, a beat after each swipe.
  ///
  /// Skipped if the screen has moved on to another pager by the time the attach lands.
  Future<void> _attachOnly(({String machineId, String agentId}) agent) async {
    final notifier = widget.notifier;
    await notifier.selectAgent(agent.machineId, agent.agentId);
    if (!mounted || _neighboursFor != agent) return;
    for (final pane in [...notifier.panes]) {
      if (pane.machineId == agent.machineId && pane.agentId == agent.agentId) {
        continue;
      }
      final paneAgentId = pane.agentId;
      if (paneAgentId != null &&
          agentPaneHeldByPager((
            machineId: pane.machineId,
            agentId: paneAgentId,
          ))) {
        continue;
      }
      await notifier.closePane(pane.id);
    }
  }

  /// The last agent was just deleted: the form for a new one, instead of "No agents yet".
  ///
  /// With no list screen left, the terminal WAS the app — deleting the last agent took it away and
  /// left a page whose only real action is the `+` in its corner. So that step is taken for them,
  /// on the machine the deleted agent ran on — the form lets them pick another.
  ///
  /// ⚠️ Only on the way DOWN from a terminal to nothing — [_neighboursFor] still naming the pager
  /// that was up — and the record is cleared as the form opens. That is what makes it once: backing
  /// out of the form lands on the empty state, whose next rebuild finds no pager to have lost and
  /// leaves the person there rather than pushing the form straight back over them. A launch onto a
  /// machine that never had agents is not this path either; nothing was on screen to lose.
  ///
  /// Pushed after the frame: this runs inside build, where a push trips the navigator's lock.
  void _openNewAgentAfterLastOneWent() {
    final lost = _neighboursFor;
    if (lost == null) return;
    // ⚠️ Deleted, not merely unopenable for a moment. An agent being restarted can report no
    // terminal while it comes back, which also empties the openable list — and a form popping over
    // a restart would be the screen acting on something that is not happening. Its machine still
    // answering with an agent list that has NO agents on it is what a deletion looks like.
    final machine = widget.notifier.stateOf(lost.machineId);
    if (machine == null ||
        phoneMachineStatusOf(machine) != PhoneMachineStatus.ready ||
        machine.agentLoadStatus != AgentLoadStatus.loaded ||
        machine.agents.isNotEmpty) {
      return;
    }
    _neighboursFor = null;
    _neighbours = null;
    _showing = null;
    final machineId = lost.machineId;
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (!mounted) return;
      unawaited(openNewAgent(context, widget.notifier, machineId));
    });
  }

  /// The pager reports a SWIPE: the agent arrived at is the one this screen now holds.
  ///
  /// ⚠️ Assigned without setState on purpose. This arrives during the pager's own rebuild, and
  /// nothing on screen is derived from the field in the frame it changes — it exists so the NEXT
  /// rebuild keeps the agent the person swiped to instead of snapping back to the one opened on.
  void _onAgentChanged(({String machineId, String agentId}) agent) {
    _showing = agent;
    // A swipe is a choice made by hand, so any jump still pending is abandoned rather than allowed
    // to move the screen again a second later. See [_awaitingMachine].
    _awaitingMachine = null;
    _requestedAgent = null;
  }
}

/// The screen the app opens on while it is still working out which terminal to show.
///
/// ⚠️ **Deliberately not a skeleton, and that is the point of it.** A skeleton is a promise about
/// the SHAPE of what is coming, and it used to be right here because the Agents tab's root was a
/// list of cards. What lands now is one agent's terminal, so a column of grey cards promised a
/// screen that never arrived — visible for the seconds a cold launch takes, which is exactly when
/// somebody is deciding whether the app is working.
///
/// ⚠️ **No header either.** "Agents" over a big empty area is the list screen's chrome, and search
/// sitting in the corner offers something to do at the one moment nothing can be done yet. The
/// screen is one centred line saying what is happening, which is also what [_Attaching] in
/// `terminal_page.dart` looks like — same spinner, same size, same type — so the two read as one
/// sequence rather than two unrelated waits.
///
/// ⚠️ **Until the wait is [slow].** Then it says so, and offers the two ways off it: the computers,
/// with what each one needs, and Settings — Sign out among it — at the top right, where every
/// screen before the first harness has it. Without them a wait that stalled ("Connecting to your
/// computer…" over an agent list that never came) was a spinner with nothing on screen to leave
/// it by.
class _AgentHomeLoading extends StatelessWidget {
  const _AgentHomeLoading({
    required this.message,
    required this.notifier,
    this.slow = false,
  });

  /// The step in progress, in the person's words — see [_AgentHomeState._loadingMessage].
  final String message;

  final AppNotifier notifier;

  /// Up for [_AgentHomeState._slowAfter] without a break.
  final bool slow;

  @override
  Widget build(BuildContext context) {
    AppTheme.watch(context);
    return Scaffold(
      backgroundColor: AppPalette.windowBg,
      body: SafeArea(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            // The row Settings stands in on the screens before the first harness — empty until the
            // wait is slow, so a launch that is merely loading stays one centred line.
            SizedBox(
              height: 44,
              child: slow
                  ? Align(
                      alignment: Alignment.centerRight,
                      child: PhoneSettingsButton(notifier: notifier),
                    )
                  : null,
            ),
            Expanded(
              child: Center(
                child: Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 32),
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      SizedBox.square(
                        dimension: 22,
                        child: CircularProgressIndicator(
                          strokeWidth: 2,
                          color: AppPalette.accent,
                        ),
                      ),
                      const SizedBox(height: 14),
                      // ⚠️ Keyed by the text so a change between steps CROSS-FADES rather than
                      // snapping. These lines replace each other while somebody is reading them,
                      // and a hard swap at that moment reads as a glitch instead of as progress.
                      AnimatedSwitcher(
                        duration: const Duration(milliseconds: 220),
                        child: Text(
                          message,
                          key: ValueKey(message),
                          textAlign: TextAlign.center,
                          style: TextStyle(
                            color: AppPalette.textSecondary,
                            fontSize: 14,
                          ),
                        ),
                      ),
                      AnimatedSwitcher(
                        duration: const Duration(milliseconds: 220),
                        child: slow
                            ? _SlowWaitHint(
                                key: const ValueKey('home-wait-slow'),
                                notifier: notifier,
                              )
                            : const SizedBox.shrink(),
                      ),
                    ],
                  ),
                ),
              ),
            ),
            // The top row's height again, so the line stays where it was: the screen's middle.
            const SizedBox(height: 44),
          ],
        ),
      ),
    );
  }
}

/// "See your computers ›" under a wait: Computers over the wait, counted as asked for by a button.
void _seeComputers(BuildContext context, AppNotifier notifier) {
  notifier.productMeasurement.screenOpened(
    PhoneScreen.computers,
    ScreenOpening.button,
  );
  unawaited(
    Navigator.of(context)
        .push(phoneRoute((_) => MachinesTab(notifier: notifier, large: false))),
  );
}

/// Under a wait that has gone on: what is true, and the computers — each with what it needs, a
/// password form behind a locked one — over the wait rather than in place of it, so back returns
/// to it and a wait that ends meanwhile still lands where it would have.
class _SlowWaitHint extends StatelessWidget {
  const _SlowWaitHint({super.key, required this.notifier});

  final AppNotifier notifier;

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(top: 18),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Text(
            'This is taking longer than usual.',
            textAlign: TextAlign.center,
            style: TextStyle(color: AppPalette.textSecondary, fontSize: 13),
          ),
          const SizedBox(height: 4),
          TtyTextButton(
            key: const ValueKey('home-wait-computers'),
            label: 'See your computers ›',
            onPressed: () => _seeComputers(context, notifier),
          ),
        ],
      ),
    );
  }
}

/// The one empty case left on this screen: a machine is open and able to host an agent, and there
/// simply is not an agent yet.
///
/// ⚠️ **Every other empty case belongs to [MachinesTab] and is routed there instead.** No machines
/// on the account, machines that all want a password, machines that are switched off — those are
/// machine problems wearing an Agents header, and the thing to do about them is a row on the
/// machines list, not a sentence pointing at one. By the time this widget is built the only thing
/// missing is the agent, which is exactly what its `+` creates.
class _AgentHomeEmpty extends StatelessWidget {
  const _AgentHomeEmpty({required this.notifier});

  final AppNotifier notifier;

  @override
  Widget build(BuildContext context) {
    AppTheme.watch(context);
    // ⚠️ Recomputed rather than passed in. This is built from a `build`, so the machine that was
    // ready a frame ago may not be now — and `ready.first` below is dereferenced.
    final ready = [
      for (final machine in filterableMachines(notifier))
        if (phoneMachineStatusOf(machine) == PhoneMachineStatus.ready) machine,
    ];
    // The caller only builds this when a machine is ready, but a rebuild can arrive between that
    // test and this one. Falling back to the machines screen keeps the two in step rather than
    // drawing a `+` that cannot fire.
    if (ready.isEmpty) return MachinesTab(notifier: notifier);
    final tty = Tty.of(context);
    final machine = ready.first.machine;
    // A computer, and nothing running on it: say so in a line, and the one thing to do — start one.
    return Scaffold(
      backgroundColor: tty.ground,
      body: SafeArea(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            // The machine, and the paired daemon at the line's right end — where a terminal's title
            // carries it (see `daemon_chip.dart`) — then Settings, at the top right as on every
            // screen before the first harness. ⚠️ This is the first screen a new account stands on
            // once its computer is open, and nothing else on it leads to Settings — or Sign out:
            // Find and a terminal's menu, the other ways there, both need a harness.
            SizedBox(
              height: 44,
              child: Row(
                children: [
                  const SizedBox(width: Tty.origin),
                  Expanded(
                    child: TtyText(
                      machine.displayName,
                      size: TtySize.meta,
                      color: tty.green,
                    ),
                  ),
                  const DaemonChip(margin: EdgeInsets.only(left: 12)),
                  PhoneSettingsButton(notifier: notifier),
                ],
              ),
            ),
            Expanded(
              child: Padding(
                padding: const EdgeInsets.fromLTRB(
                  Tty.origin,
                  0,
                  Tty.origin,
                  16,
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: [
                    const Spacer(),
                    TtyText(
                      'Nothing running yet.',
                      size: 24,
                      weight: FontWeight.w600,
                    ),
                    const SizedBox(height: 12),
                    // ⚠️ No "Swipe right any time to find one started elsewhere": the swipe is the
                    // terminal's (`terminal_page.dart`), it does nothing here, and with no harness on
                    // any open computer there is nothing elsewhere to find.
                    Text(
                      'Start a harness — an agent on a project on your computer — and '
                      'watch it work from here.',
                      style: tty.style(size: TtySize.row, color: tty.faint),
                    ),
                    const Spacer(),
                    TtyPrimaryButton(
                      label: 'Start a harness',
                      onPressed: () =>
                          openNewAgent(context, notifier, machine.machineId),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

/// The session the onboarding hands over to, growing into the screen — the laptop's lit screen
/// becoming the session, in the spec's words: a 420ms spring from a little smaller, fading in; a
/// 200ms fade under Reduce Motion. Only when [grow] is set as it first comes up; afterwards, and
/// for every other pager, it is the child as it is.
class _GrowIn extends StatefulWidget {
  const _GrowIn({required this.grow, required this.child});

  final bool grow;
  final Widget child;

  @override
  State<_GrowIn> createState() => _GrowInState();
}

class _GrowInState extends State<_GrowIn> with SingleTickerProviderStateMixin {
  late final AnimationController _grow = AnimationController(
    vsync: this,
    duration: const Duration(milliseconds: 420),
    value: widget.grow ? 0 : 1,
  );
  bool _still = false;

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _still = MediaQuery.maybeDisableAnimationsOf(context) ?? false;
    if (_grow.value < 1 && !_grow.isAnimating) {
      _grow.duration = Duration(milliseconds: _still ? 200 : 420);
      unawaited(_grow.forward());
    }
  }

  @override
  void dispose() {
    _grow.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) => AnimatedBuilder(
    animation: _grow,
    child: widget.child,
    builder: (context, child) {
      final t = _grow.value;
      final scale = _still || t >= 1
          ? 1.0
          : 0.9 + 0.1 * Curves.easeOutBack.transform(t);
      // ⚠️ **The same two wrappers at every value, grown included.** Dropped once it had grown,
      // they changed the pager's place in the tree, and Flutter built the pager — the terminal and
      // its attach — over again, half a second after it opened. At 1 they cost nothing: an opaque
      // opacity and an identity scale paint the child as it is.
      return Opacity(
        opacity: Curves.easeOut.transform((t * 2).clamp(0.0, 1.0)),
        child: Transform.scale(scale: scale, child: child),
      );
    },
  );
}