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.

33.3 KB
Raw Blame
import 'dart:async';

import 'package:flutter/cupertino.dart' show CupertinoPageRoute;
import 'package:flutter/material.dart';

import 'package:harness_mobile/state/app_state.dart';

import '../demo/sample_mode.dart' show SampleMode;
import '../notify/system_notices.dart';
import '../p2p/phone_terminal_p2p.dart';
import '../swarm/swarm_activity_page.dart' show swarmActivityRoute;
import '../swarm/swarm_attachment_store.dart';
import '../swarm/swarm_computers.dart';
import '../swarm/swarm_home_root.dart';
import '../swarm/swarm_inbox.dart' show SwarmDecisionNeed;
import '../swarm/swarm_message_link.dart';
import '../swarm/swarm_profile.dart';
import '../swarm/swarm_project_page.dart' show swarmChatRoute;
import '../swarm/swarm_thread.dart' show SwarmThreadFocus;
import '../swarm/swarm_session.dart';
import '../swarm/swarm_tabs.dart';
import 'agent_home.dart';
import 'approve_sign_in.dart';
import 'browser_handoff.dart';
import 'devices_page.dart';
import 'exit_app.dart';
import 'new_device_banner.dart';
import 'phone_navigation.dart';
import 'phone_shell_scope.dart';
import 'phone_status.dart';
import 'resume_agent.dart';
import 'settings_page.dart' show openPhoneSettings;
import 'voice_recorder.dart';
import 'voice_input_scope.dart';
import 'welcome/connect_code.dart';

/// The signed-in phone app: one page stack, rooted in [AgentHome] — the terminal the phone opens
/// on and stays on. Machines and Settings are pages pushed onto it, from the terminal's menu and
/// from Find.
///
/// While Settings ▸ Experimental ▸ Swarm is on, the root is Swarm Home instead, with Harness (the
/// same [AgentHome]) one tap away in its drawer ([SwarmHomeRoot], [SwarmHomeChoice]).
///
/// ⚠️ **One stack, no tabs.** There were three — Agents, Machines, Settings — each with its own
/// navigator under a bottom bar. The bar was hidden once the terminal became the home screen, and
/// with no bar there was no way to reach the other two: they were built out of sight and never
/// shown, so they went with it.
///
/// Its own [Navigator], nested under the app's, on purpose: `RootShell` swaps this whole shell out
/// on sign-out, and the pages have to go with it rather than stay stacked over the sign-in screen,
/// as they would on the root navigator.
class PhoneShell extends StatefulWidget {
  const PhoneShell({super.key, required this.notifier});

  final AppNotifier notifier;

  @override
  State<PhoneShell> createState() => _PhoneShellState();
}

class _PhoneShellState extends State<PhoneShell> with WidgetsBindingObserver {
  late final BrowserHandoff _browser;
  final _navigator = GlobalKey<NavigatorState>();

  /// The nested navigator's own — see the note at the `HeroControllerScope` below.
  final _heroController = HeroController();

  /// Swarm, while Settings ▸ Experimental ▸ Swarm is on: one session for the signed-in account,
  /// read while the app is in front, for every page under this shell ([SwarmScope]).
  late final SwarmHost _swarm;

  /// The app's computers as Swarm's start screens read them; they hear only a computer coming,
  /// going or changing state.
  late final _swarmComputers = AppSwarmComputers(widget.notifier);

  /// Keeps Swarm's picture files to the signed-in account: emptied on sign-out, Swarm off, another
  /// account and a Swarm's removal.
  late final SwarmAttachmentKeeper _swarmFiles;

  /// What the stack's root shows: Swarm Home while Swarm is on, until the person goes to Harness.
  late final _home = SwarmHomeChoice(_swarm.features);

  /// The centre's Swarm notices: the app's own centre carries them; a stand-in that does not
  /// (a test's) gets a silent one.
  late final SwarmLinkChannel _links;

  late final SwarmNotices _swarmNotices =
      switch (widget.notifier.agentNotices.system) {
        final SwarmNotices notices => notices,
        _ => SilentSystemNotices(),
      };

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    // A page a harness's program opened while this phone was typing there (Claude Code's `/login`).
    _browser = BrowserHandoff(
      widget.notifier,
      say: (text) =>
          ScaffoldMessenger.maybeOf(context)
              ?.showSnackBar(SnackBar(content: Text(text))),
    );
    widget.notifier.onBrowserOpen = (machineId, _, url) =>
        unawaited(_browser.open(machineId, url));
    final notices = widget.notifier.agentNotices.system;
    notices.opened.addListener(_openNoticedAgent);
    notices.openedDevice.addListener(_openNoticedDevice);
    final state = WidgetsBinding.instance.lifecycleState;
    _swarm = SwarmHost(
      accountId: () => widget.notifier.swarmAccountId,
      accountReading: () => widget.notifier.accountReading,
      account: widget.notifier,
      request: widget.notifier.swarmRequest,
      upload: widget.notifier.swarmUpload,
      notices: _swarmNotices,
      // Swarm Home's start screens: which computers the account has, and
      // whether any is online.
      computers: _swarmComputers,
      // A photo goes straight to the backend with this app's own sign-in;
      // the computer a Swarm call goes through carries text only.
      uploadAvatar: swarmAvatarUploadVia(
        (tabId, png) => widget.notifier.api.uploadSwarmAvatar(tabId, png),
      ),
      // A chat's mic records voice messages with the terminal's recorder. Not
      // in sample mode, which has no account to send them with.
      voice: VoiceInputScope.maybeOf(context) == null
          ? MicVoiceRecorder.new
          : null,
    )..foreground = _swarmFront = state == null || _inFront(state);
    _swarmFiles = SwarmAttachmentKeeper(_swarm);
    _swarmNotices.openedSwarm.addListener(_openNoticedSwarm);
    // A message link (Desktop's Copy link to message): one that launched the
    // app or came before sign-in waits on the native side until now.
    _links = SwarmLinkChannel(_openLinkedMessage)..listen();
    // Install tap callbacks and read the launch payload even when no new notice
    // arrives. Checking permission does not ask for it.
    unawaited(noticesEnabled(notices));
    // A tap that launched the app is read before this shell exists, so its value is already set and
    // no listener will ever fire for it: take it once the navigator is up.
    if (notices.opened.value != null ||
        notices.openedDevice.value != null ||
        _swarmNotices.openedSwarm.value != null) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        if (!mounted) return;
        _openNoticedAgent();
        _openNoticedDevice();
        _openNoticedSwarm();
      });
    }
    // A computer's sign-in QR read before this phone was signed in: the sign-in was the way to
    // answer it, and this shell is the first thing up after it — see [_approveHeldComputerSignIn].
    if (widget.notifier.pendingComputerSignIn != null) {
      WidgetsBinding.instance.addPostFrameCallback(
        (_) => _approveHeldComputerSignIn(),
      );
    }
    // ⚠️ Not asked here any more. Signed in with nothing on screen, "Harness would like to send you
    // notifications" is a question with no reason attached. It is asked the first time a harness
    // is on screen — see `FocusHints.onDone` in `terminal_page.dart`.
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    widget.notifier.onBrowserOpen = null;
    unawaited(_browser.dispose());
    widget.notifier.agentNotices.system.opened.removeListener(
      _openNoticedAgent,
    );
    widget.notifier.agentNotices.system.openedDevice.removeListener(
      _openNoticedDevice,
    );
    _swarmNotices.openedSwarm.removeListener(_openNoticedSwarm);
    _links.close();
    _home.dispose();
    _swarmFiles.dispose();
    _swarm.dispose();
    _swarmComputers.dispose();
    _linkedMachineId.dispose();
    _openAgentRequest.dispose();
    _heroController.dispose();
    super.dispose();
  }

  // ── Where the app lands ───────────────────────────────────────────────────────────────────────
  //
  // Almost nothing, now — and that is the change. The shell used to reopen the last agent itself,
  // fall back to Machines when nothing answered, and time the wait out after 45 seconds, because
  // the thing it was steering towards was a page it had to PUSH over an agents list. There is no
  // list and no push: [AgentHome] is the stack's root, and it reads the last-agent record, waits
  // for the machines to answer and picks the agent, all as part of drawing itself.
  //
  // One move is left, because no page can make it alone: a password accepted on a page pushed over
  // the home screen takes the person back to it, where the machine they just opened is about to
  // bring its agents with it.

  /// The machine whose password was just accepted, for [AgentHome] to open once it answers.
  ///
  /// ⚠️ **A notifier and not a field on this State, because a field cannot reach [AgentHome] at
  /// all.** The stack's root is built inside `onGenerateRoute`, which a nested [Navigator] runs ONCE
  /// when it creates that route — so the root keeps forever whatever arguments it was first given,
  /// and `setState` here rebuilds this widget without ever rebuilding it. A value passed down as a
  /// constructor field would have been read on the first launch frame, when no machine had been
  /// linked, and never again.
  ///
  /// Handed over once, at construction, and written to afterwards: [AgentHome] listens, so a value
  /// set at any point reaches it. Never reset here — [AgentHome] spends the request itself, on the
  /// agent arriving or on a swipe away from it.
  final _linkedMachineId = ValueNotifier<String?>(null);

  /// A password was accepted: the agent is what the person came for, so the phone points itself at
  /// that machine.
  ///
  /// No waiting and no timeout here, which is what this used to be full of. The machine is still
  /// connecting at this point and [AgentHome] is already watching for exactly that — it holds
  /// whatever is on screen while the machine dials, then opens the first agent it reports.
  void _followLinkedMachine(String machineId) {
    ++_navigationRequest;
    _linkedMachineId.value = machineId;
    _home.showHarness();
  }

  /// An agent somebody picked — from search, the new-agent form, the attention list — for
  /// [AgentHome] to put on screen. A notifier for the reason [_linkedMachineId] is one.
  final _openAgentRequest =
      ValueNotifier<({String machineId, String agentId})?>(null);

  /// Opens an agent AS the home screen rather than on top of it.
  ///
  /// ⚠️ **This is what took the back button off the terminal.** A terminal pushed over search, or
  /// over the new-agent form, had a page under it, so its header drew a chevron back to a screen the
  /// person had finished with. The stack is emptied back to its root instead and the root terminal
  /// switches agent, so there is never anything to go back to.
  void _openAgentAtHome(String machineId, String agentId) {
    ++_navigationRequest;
    _navigator.currentState?.popUntil((route) => route.isFirst);
    // Reset first, so picking the agent already requested last time still notifies.
    _openAgentRequest.value = null;
    _openAgentRequest.value = (machineId: machineId, agentId: agentId);
    _home.showHarness();
    setState(() => _canPop = false);
  }

  /// Swarm Home, from the terminal's Swarm mark or Find: back to the root.
  void _showSwarm() {
    ++_navigationRequest;
    _navigator.currentState?.popUntil((route) => route.isFirst);
    _home.showSwarm();
  }

  /// The computer whose sign-in QR (`harness login --qr`) the welcome screen read before this phone
  /// was signed in ([AppNotifier.pendingComputerSignIn]): the approval it asked for, now that it can
  /// be given. Spent here whatever the answer — a code is one computer's sign-in, once.
  ///
  /// From this shell's context and not a page's: the home page under it is still settling (the
  /// machines loading, "Waiting for your computer…" swapping with "Looking for your computers…") and
  /// a page swapped out mid-answer would drop it. The dialog stands on the root navigator either way.
  void _approveHeldComputerSignIn() {
    final code = widget.notifier.pendingComputerSignIn;
    if (!mounted || code == null) return;
    widget.notifier.pendingComputerSignIn = null;
    unawaited(
      approveComputerSignIn(
        context,
        widget.notifier,
        SignInCode(code),
        scanAgain: 'Show it again on the computer, then scan it from Settings ▸ Sign in a computer.',
      ),
    );
  }

  /// A tapped "agent finished" notice: that agent, as the home screen — the
  /// dial's drawer row opening its agent.
  void _openNoticedAgent() {
    final opened = widget.notifier.agentNotices.system.opened;
    final agent = opened.value;
    if (agent == null) return;
    opened.value = null;
    if (_swarm.session case final session?) {
      unawaited(_openSwarmAgent(session, agent.machineId, agent.agentId));
    } else {
      _openAgentAtHome(agent.machineId, agent.agentId);
    }
  }

  // Shared by notification reads, explicit root changes and route transitions.
  int _navigationRequest = 0;

  Future<void> _openSwarmAgent(
    SwarmSession session,
    String machineId,
    String harnessId,
  ) async {
    final request = ++_navigationRequest;
    // Join the cold-start read; a background tap must use the current assignment.
    await session.inbox.refresh();
    if (!mounted ||
        _swarm.session != session ||
        request != _navigationRequest) {
      return;
    }
    for (final swarm in session.inbox.swarms) {
      final snapshot = session.inbox.reader(swarm.id)?.snapshot;
      if (snapshot == null) continue;
      for (final agent in snapshot.agents) {
        if (agent.machineId != machineId || agent.harnessId != harnessId) {
          continue;
        }
        final groups = snapshot.conversations.where(
          (g) =>
              !g.closed && !snapshot.isProjectLead(g.id) && g.audience == null,
        );
        final assigned = groups.where(
          (g) =>
              g.assignment?['agentId'] == agent.id &&
              !const ['done', 'cancelled'].contains(g.assignment?['status']),
        );
        final member = groups.where((g) => g.agentIds.contains(agent.id));
        final conversationId =
            assigned.firstOrNull?.id ??
            member.firstOrNull?.id ??
            snapshot.projectById(agent.projectId)?.leadConversationId;
        if (conversationId != null) {
          _showNoticedChat((
            swarmId: swarm.id,
            conversationId: conversationId,
            messageId: null,
            decisionId: null,
            threadId: null,
          ));
          return;
        }
      }
    }
    _showSwarm();
    ScaffoldMessenger.maybeOf(context)?.showSnackBar(
      const SnackBar(content: Text('This agent’s chat is unavailable.')),
    );
  }

  /// A tapped "new device" notice: that device's page. One this phone has just been told of opens as
  /// new (so does one the log still holds as pending); one already seen but still on the account opens
  /// plain; one that is gone opens the list, which says so by not showing it.
  void _openNoticedDevice() {
    final opened = widget.notifier.agentNotices.system.openedDevice;
    final pub = opened.value;
    if (pub == null) return;
    opened.value = null;
    unawaited(_showDevice(pub));
  }

  /// A tapped Swarm notice: Swarm Home, and over it the conversation the notice was about — back
  /// from it is the rest of what Swarm asks of the person.
  void _openNoticedSwarm() {
    final opened = _swarmNotices.openedSwarm;
    final target = opened.value;
    if (target == null || _navigator.currentState == null) return;
    opened.value = null;
    // Swarm off cancels its notices. A stale tap must not open a disabled UI.
    if (_swarm.session == null) return;
    _showNoticedChat(target);
  }

  /// A message link: Swarm Home, and over it the chat at that message. The
  /// chat says "not open" for one the person cannot read, as for a notice.
  void _openLinkedMessage(SwarmMessageLink link) {
    if (!mounted) return;
    if (_navigator.currentState == null) {
      WidgetsBinding.instance.addPostFrameCallback(
        (_) => _openLinkedMessage(link),
      );
      WidgetsBinding.instance.ensureVisualUpdate();
      return;
    }
    if (_swarm.session == null) {
      ScaffoldMessenger.maybeOf(context)?.showSnackBar(
        const SnackBar(
          content: Text('Turn on Swarm in Settings to open this link.'),
        ),
      );
      return;
    }
    _showNoticedChat((
      swarmId: link.tabId,
      conversationId: link.conversationId,
      messageId: link.messageId,
      decisionId: null,
      threadId: null,
    ));
  }

  void _showNoticedChat(SwarmNoticeTarget target) {
    ++_navigationRequest;
    final navigator = _navigator.currentState;
    if (navigator == null) return;
    navigator.popUntil((route) => route.isFirst);
    _home.showSwarm();
    // A decision opens in Activity, where it is answered, as Desktop opens
    // it in Notifications: no chat shows decisions. Activity says so when it
    // is no longer open, whoever's it was.
    if (target.decisionId case final decisionId?) {
      unawaited(
        navigator.push(
          swarmActivityRoute(
            focus: SwarmDecisionNeed.keyOf(decisionId),
            swarmId: target.swarmId,
          ),
        ),
      );
      return;
    }
    // A project's own chat opens as its project, on Swarm Home C's tabs.
    unawaited(
      navigator.push(
        swarmChatRoute(
          swarmId: target.swarmId,
          conversationId: target.conversationId,
          // A message only in its thread: the chat at the thread's root, the
          // thread open over it at that message, as Activity opens a reply.
          messageId: target.threadId ?? target.messageId,
          threadId: target.threadId,
          threadFocus: target.threadId != null && target.messageId != null
              ? SwarmThreadFocus.message(target.messageId!)
              : null,
        ),
      ),
    );
  }

  /// In front of the person: resumed, or only covered for a moment (the app switcher, a call).
  /// Whether Swarm was last told the app is in front ([didChangeAppLifecycleState]).
  bool _swarmFront = true;

  /// Back in front: what pushes showed while the app was away is told already
  /// (task #2905), so the reads that start now post none of it again.
  Future<void> _swarmToFront() async {
    final shown = await widget.notifier.pushesShown();
    if (!mounted || !_swarmFront) return;
    _swarm.toldElsewhere(shown);
    _swarm.foreground = true;
  }

  static bool _inFront(AppLifecycleState state) =>
      state == AppLifecycleState.resumed || state == AppLifecycleState.inactive;

  Future<void> _showDevice(String key) async {
    final navigator = _navigator.currentState;
    if (navigator == null) return;
    // A removal by a new device is keyed `removedBy:<signer>:<removed pub>`: it opens the signer.
    var pub = key;
    if (key.startsWith('removedBy:')) {
      final rest = key.substring('removedBy:'.length);
      final cut = rest.indexOf(':');
      pub = cut < 0 ? rest : rest.substring(0, cut);
    }
    // From the log's own listing, never a row made up from the notice: it carries the real
    // `suspended` and `pending` flags (a tap that launched the app comes before the banner list is
    // rebuilt from the log, and is still news while the log holds it pending).
    await openDeviceFromLog(navigator, widget.notifier, pub);
  }

  /// Back in the foreground: a p2p retry waiting out its delay fires now, and so does every machine
  /// socket the phone lost while it was away. Going to the background needs nothing — the OS
  /// suspends the socket, and the redial tears the old wire down and negotiates a fresh one.
  ///
  /// ⚠️ The two used to be one line, and the missing half showed. P2P was kicked here from the
  /// start; the WebSocket underneath it was not, so a phone coming back sat through a backoff that
  /// had already climbed to its 30s ceiling — the machine list saying "Connecting…" at somebody
  /// who was looking straight at it, with a network that would have answered at once.
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    // Swarm is read only in front of the person.
    if (!_inFront(state)) {
      _swarmFront = false;
      _swarm.foreground = false;
    } else if (!_swarmFront) {
      _swarmFront = true;
      unawaited(_swarmToFront());
    }
    if (state == AppLifecycleState.inactive) {
      // The app switcher coming up is `inactive`, and a swipe there can end the app without it
      // ever reaching `paused` — so the machine cache is written here as well. See
      // [AppNotifier.handleAppInactive].
      widget.notifier.handleAppInactive();
      return;
    }
    if (state == AppLifecycleState.paused) {
      // The other half of the resume below: work that only makes sense in
      // front of somebody stops here. The sockets are not touched — the OS
      // suspends them, and the redial on the way back is what recovers them.
      widget.notifier.handleAppPaused();
      return;
    }
    if (state != AppLifecycleState.resumed) return;
    phoneTerminalP2p.kickRetry();
    widget.notifier.handleAppResumed();
  }

  /// Whether the stack has a page to go back to — what [PopScope] is given.
  ///
  /// Kept as state rather than read inline in `build`, because a push or pop inside a nested
  /// [Navigator] does not rebuild this widget: the flag has to be pushed here by the notification
  /// below, or `canPop` would answer with whatever was true when the shell last happened to build.
  bool _canPop = false;

  /// Android's back button: the stack's own pages first, then the question before leaving the app.
  ///
  /// The notification is used only as a SIGNAL that the stack moved, and the answer is then read
  /// from the navigator itself.
  bool _onNavigation(NavigationNotification notification) {
    _syncCanPop();
    // Let it keep bubbling: the root navigator above this shell tracks its own state from it.
    return false;
  }

  void _syncCanPop() {
    final next = _navigator.currentState?.canPop() ?? false;
    if (next == _canPop) return;
    // The notification arrives mid-build of the subtree that sent it, so defer rather than calling
    // setState inside another widget's build.
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (!mounted) return;
      final current = _navigator.currentState?.canPop() ?? false;
      if (current == _canPop) return;
      setState(() => _canPop = current);
    });
  }

  void _handleBack(bool didPop, Object? result) {
    if (didPop) return;
    unawaited(_back());
  }

  /// The stack's own pages first; what is left is leaving the app, which Android asks about.
  ///
  /// ⚠️ **The stack is ASKED, rather than judged by its `canPop`.** `maybePop` answers false only
  /// when the root has nothing to close. `canPop` is false at the root even while something there
  /// holds the press itself — Find over the terminal, whose own [PopScope] steps out of it — and
  /// back used to leave the app from under an open Find because of it.
  ///
  /// ⚠️ **Only the app's own root asks.** The sample runs this same shell on a route pushed over the
  /// welcome screen, and back at ITS root has always left the sample for that screen — so a shell
  /// with a route under it pops that route instead. `pop`, not `maybePop`: this shell's own
  /// [PopScope] is what refuses the pop, and asking the route again would land straight back here.
  Future<void> _back() async {
    ++_navigationRequest;
    final handled = await _navigator.currentState?.maybePop() ?? false;
    if (!mounted) return;
    _syncCanPop();
    if (handled) return;
    // Harness, reached from Swarm Home's drawer: back is Swarm Home, the app's Home.
    if (_home.harnessOverSwarm) {
      _home.showSwarm();
      return;
    }
    if (!confirmsExitOnBack) return;
    final route = ModalRoute.of(context);
    if (route != null && !route.isFirst) {
      // Only while it is still on top: a sheet pushed meanwhile is what the next press closes.
      if (route.isCurrent) Navigator.of(context).pop();
      return;
    }
    await confirmExitApp(context);
  }

  /// The pages on the stack that count on being rebuilt from here — see [_LeansOnShell].
  late final _leaning = _LeansOnShell(() => ++_navigationRequest);

  /// The page stack, made once and handed through every rebuild of the shell untouched, so that
  /// nothing on the stack is rebuilt from here unless a page there needs it ([build]).
  ///
  /// ⚠️ **Not made afresh in [build], and it used to be.** The shell rebuilds itself whenever a
  /// push or pop changes whether it can go back ([_syncCanPop]) — that is, on every push, during
  /// the push's own animation. A fresh stack each time told every route on it that the world had
  /// changed, so opening a project or a chat built Swarm Home again under the page sliding in.
  late final Widget _stack = _pages();

  /// The page stack. A fresh widget each call — what makes the [Navigator] tell every route on it
  /// that the world may have changed (`Route.changedExternalState`), and so rebuild every page.
  // Under [SwarmScope], so every page on the stack can reach the account's Swarm.
  Widget _pages() => SwarmScope(
    notifier: _swarm,
    child: HeroControllerScope(
      controller: _heroController,
      child: Navigator(
        key: _navigator,
        // ⚠️ The controller goes in the SCOPE ONLY, never also in `observers`.
        // `NavigatorState._updateEffectiveObservers` appends the scope's controller
        // to `widget.observers` itself, so listing it here registers it twice and
        // trips "A HeroController can not be shared by multiple Navigators" — which
        // reads like a sharing bug and is really a double-subscription by one
        // navigator.
        observers: [_leaning],
        // ⚠️ **The same kind of route as every page pushed over it ([phoneRoute]).** The root was
        // a `MaterialPageRoute` under Cupertino pages, and the two hand their transition to each
        // other: each push and pop changed the shape of the tree around the root's page, so
        // Swarm Home was taken out and put back — and built again — as a project or chat slid in.
        onGenerateRoute: (_) => CupertinoPageRoute<void>(
          builder: (_) => SwarmHomeRoot(
            choice: _home,
            harness: AgentHome(
              notifier: widget.notifier,
              openMachineId: _linkedMachineId,
              openAgent: _openAgentRequest,
            ),
            swarm: (_) => SwarmTabsPage(
              onSettings: (context) =>
                  openPhoneSettings(context, widget.notifier, swarm: true),
              // You's Notifications, not in the sample, as Settings leaves
              // it out there: its notices go nowhere.
              notices: SampleMode.ofNotifier(widget.notifier) == null
                  ? widget.notifier.agentNotices.system
                  : null,
            ),
          ),
        ),
      ),
    ),
  );

  @override
  Widget build(BuildContext context) {
    return PhoneShellScope(
      onMachineLinked: _followLinkedMachine,
      onOpenAgent: _openAgentAtHome,
      onShowSwarm: _showSwarm,
      home: _home,
      canOpenMachine: (machineId) =>
          phoneMachineOpensTerminals(widget.notifier.machineStates[machineId]),
      agentStopped: (machineId, agentId) =>
          phoneAgentStopped(widget.notifier, machineId, agentId),
      onResumeAgent: (machineId, agentId) =>
          phoneResumeAgent(widget.notifier, machineId, agentId),
      // Rebuilt when the root switches, so back from Harness can reach Swarm Home.
      child: ListenableBuilder(
        listenable: _home,
        builder: (context, child) => PopScope<Object?>(
          // False while the stack has somewhere to go back to, so the gesture reaches [_handleBack]
          // instead of leaving the app. True at its root: the press then belongs to the system —
          // except on Android, where the root asks before the app is left ([confirmExitApp]), so
          // every press is the shell's — and except at Harness over Swarm Home, which back leaves
          // for Swarm Home.
          canPop: !confirmsExitOnBack && !_canPop && !_home.harnessOverSwarm,
          onPopInvokedWithResult: _handleBack,
          child: child!,
        ),
        child: NotificationListener<NavigationNotification>(
          onNotification: _onNavigation,
          child: Scaffold(
            // ⚠️ The nested navigator needs its OWN HeroController, and without this the
            // engine-mark flights simply never happen — silently, with no error.
            //
            // `MaterialApp` installs one controller for the ROOT navigator only; a nested
            // `Navigator` inherits nothing, so its routes have no observer to drive a flight.
            //
            // ⚠️ **Only the bands and the inset under them are rebuilt by the notifier, and the
            // page stack is not — while the home screen is all there is.** This used to wrap the
            // whole shell, so every tick of the notifier (an agent synced on any machine, a turn
            // starting) handed the [Navigator] a new widget, which rebuilds EVERY route on it:
            // the home screen down to the terminal being typed into, several times a second in a
            // burst. The home screen listens to the notifier for itself ([AgentHome]), so at the
            // root the stack is handed through untouched. A page PUSHED over it may not listen —
            // it may read the notifier in `build` and count on being rebuilt — so while one is up
            // the stack is rebuilt on every tick exactly as before, unless it was pushed as one
            // that listens for itself (Swarm's project and chat pages, [phoneRoute]). Opening a
            // project or a chat then rebuilds nothing under it: on Tony's iPhone 14 those pushes
            // were the slowest frames of the app (20–42 ms of layout and paint, 2026-10-27).
            body: ListenableBuilder(
              listenable: widget.notifier,
              child: _stack,
              builder: (context, pages) => Column(
                children: [
                  // A device this phone had never trusted joined the account (device key log).
                  NewDeviceBanner(
                    notifier: widget.notifier,
                    navigator: _navigator,
                  ),
                  Expanded(
                    // While a band shows it has taken the status-bar inset, so the pages under it must
                    // not take it again (a blank gap the height of the notch otherwise).
                    //
                    // ⚠️ **Read under the Scaffold, through this Builder — never through the shell's
                    // own context.** The Scaffold has resized its body for the keyboard, and hands the
                    // body a MediaQuery with the keyboard's inset taken out so nothing below takes it
                    // again. The shell's context sits ABOVE the Scaffold and still holds that inset:
                    // rebuilt from it, every page in this navigator read the keyboard afresh and its
                    // own Scaffold shrank for it a second time. The terminal page lost twice the
                    // keyboard's height, its key bar left floating halfway up the screen over an
                    // empty band. See `TerminalPage.didChangeMetrics`, which relies on the inset
                    // being gone here.
                    child: Builder(
                      builder: (context) => MediaQuery.removePadding(
                        context: context,
                        removeTop: NewDeviceBanner.showing(widget.notifier),
                        child: _leaning.any ? _pages() : pages!,
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}

/// The pages pushed over the stack's root that may read the app in `build` without listening to
/// it, and so count on the shell rebuilding the stack on every tick: every pushed page but those
/// that listen for themselves ([phoneRouteListensForItself]). The root listens for itself.
///
/// Told by the [Navigator] of every route that comes and goes. Read by the shell on each tick; it
/// rebuilds nothing by itself.
class _LeansOnShell extends NavigatorObserver {
  _LeansOnShell(this.onNavigation);

  /// A newer route wins over notification navigation still waiting on a read.
  final VoidCallback onNavigation;

  final _pushed = <Route<Object?>>{};

  /// A page that needs the stack rebuilt from above is on it.
  bool get any => _pushed.isNotEmpty;

  void _add(Route<Object?>? route) {
    if (route == null || route.isFirst) return;
    if (phoneRouteListensForItself(route)) return;
    _pushed.add(route);
  }

  @override
  void didPush(Route<Object?> route, Route<Object?>? previousRoute) {
    onNavigation();
    _add(route);
  }

  @override
  void didPop(Route<Object?> route, Route<Object?>? previousRoute) {
    onNavigation();
    _pushed.remove(route);
  }

  @override
  void didRemove(Route<Object?> route, Route<Object?>? previousRoute) {
    onNavigation();
    _pushed.remove(route);
  }

  @override
  void didReplace({Route<Object?>? newRoute, Route<Object?>? oldRoute}) {
    onNavigation();
    _pushed.remove(oldRoute);
    _add(newRoute);
  }
}