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.

946 KB
Raw Blame
import '../core/home_dir.dart';
import '../usage/usage_account_key.dart';
import '../measurement/product_measurement.dart';
import '../measurement/speed_marks.dart';
import '../measurement/product_runtime_health.dart';
import '../measurement/product_connections.dart';
import '../core/crash_log.dart';
import '../core/guest_folders.dart';
import '../measurement/desktop_setup_report.dart';
import 'attached_task_delivery.dart';
import 'browser_copies.dart';
import 'harness_attachments.dart';
import 'task_route.dart';
import '../core/permission_modes.dart';

import 'dart:async';
import 'dart:convert' show jsonDecode, jsonEncode;
import 'dart:io'
    show Directory, FileSystemEntity, FileSystemEntityType, Platform, exit, pid;
import 'dart:math' show Random, min;

import 'package:clock/clock.dart';
import 'package:dio/dio.dart';

import 'dart:ui'
    show
        Color,
        Rect, // Rect: activeTileShape, the same one pane_preset.dart returns
        Size;

import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart'
    show AppLifecycleState, BuildContext, StringCharacters, WidgetsBinding;
import 'package:flutter_riverpod/flutter_riverpod.dart';

import '../models/model_manager_controller.dart';
import '../companions/coding_memory_connection.dart';
import 'first_arrival.dart';
import 'harness_monitor_controller.dart';
import 'essential_harness_controller.dart';
import 'agent_handoff_file.dart';
import 'agent_switch_handoff.dart';
import '../agent_messages/agent_messages.dart';
import '../finder/finder_roots.dart';
import '../agent_messages/shared_tab_errors.dart';
import '../agent_messages/shared_tab_placement.dart';
import '../agent_messages/shared_tabs.dart';
import '../agent_messages/shared_tabs_model.dart';
import '../agent_messages/tab_activity.dart';
import '../agent_messages/tab_settings.dart';
import '../api/api_client.dart';
import '../viewer/sign_in_browser.dart';
import '../viewer/direct_link.dart';
import '../viewer/viewer_services.dart';
import '../viewer/viewer_location.dart';
import '../viewer/group_sync.dart' show GroupSyncOutcome;
import '../auth/auth_session.dart';
import '../auth/peer_link_client.dart';
import '../auth/phone_sign_in.dart';
import '../auth/sign_in_client.dart';
import '../auth/sign_in_provider.dart';
import '../auth/cli_link.dart';
import '../auth/cli_login.dart';
import '../bootstrap/agent_prefetch.dart';
import '../bootstrap/windows_git_setup.dart';
import '../bootstrap/environment_provisioner.dart';
import '../bootstrap/setup_progress.dart';
import '../bootstrap/windows_self_install.dart';
import '../core/viewer_mode.dart';
import '../core/config.dart';
import '../core/sleep_aware.dart';
import '../core/agent_git_context.dart';
import '../core/agent_names.dart';
import '../core/agent_preference.dart';
import '../core/launch_setup.dart';
import '../core/dsh_catalog.dart';
import '../core/harness_catalog.dart';
import '../core/engine_availability.dart';
import '../core/browser_label.dart';
import '../core/local_hostname.dart';
import '../core/local_git_projects.dart';
import '../core/test_run.dart';
import '../core/runtime_platform.dart';
import '../core/agent_activity.dart';
import '../core/models.dart';
import '../core/harness_resources.dart';
import '../core/machine_resources.dart';
import '../core/project_folder.dart';
import '../core/git_worktree.dart';
import '../core/project_history.dart';
import '../core/task_history.dart';
import '../core/project_preview.dart';
import '../core/repository_clone.dart';
import '../core/retry.dart';
import '../core/process_responsibility.dart';
import '../core/serial_port_lease.dart';
import '../core/uninstall_marker.dart';
import '../autonomous_device/autonomous_device_cli.dart';
import '../settings/config_store.dart';
import '../settings/experimental_features.dart';
import '../core/local_key_value_store.dart';
import '../core/harness_file_store.dart';
import '../super_tabs/swarm_accounts.dart';
import '../super_tabs/attachment_upload.dart';
import '../super_tabs/attachment_viewer.dart' show superTabForgetPictures;
import '../super_tabs/image_cache.dart' show superTabImageCache;
import '../super_tabs/avatar_upload.dart';
import '../super_tabs/backend_transport.dart';
import '../super_tabs/client.dart';
import '../super_tabs/controller.dart';
import '../super_tabs/join_machine.dart';
import '../super_tabs/join_seen.dart';
import '../super_tabs/identity.dart' show superTabMachineName;
import '../super_tabs/view_store.dart';
import '../super_tabs/notifications.dart'
    show
        superTabChatNotice,
        superTabMentionNotice,
        superTabReminderNotice,
        superTabReplyNotice;
import '../measurement/setup_preference_store.dart';
import '../devices/device_hosts.dart';
import '../stats/harness_stats.dart';
import '../terminal/terminal_session.dart';
import '../terminal/terminal_theme.dart';
import '../terminal/terminal_theme_store.dart';
import '../logging/app_log.dart';
import '../shared/theme/app_theme.dart' as grid;
import '../terminal/remote_media_download.dart';
import 'take_over.dart';
import '../widgets/engine_identity.dart'
    show allEngines, engineIdentity, isCloudAgentId, isTerminalEngine;
import '../store/store_screen.dart' show openStoreAgent;
import 'dial_status.dart';
import 'machine_list_watch.dart';
import 'grid_pictures.dart';
import 'model_start_watch.dart';
import 'harness_placement.dart';
import 'harness_share_status.dart';
import 'desk_sync.dart';
import 'machine_profile.dart';
import 'pane_layout_store.dart';
import 'profile_cache.dart';
import 'terminal_pane.dart';
import 'device_visit.dart';
import 'started_children.dart';
import 'swarm.dart';
import '../terminal/terminal_binary.dart';
import '../update/desktop_updater.dart';
import '../update/manual_update_check.dart';
import '../ws/ws_conn.dart';
import 'retarget_refusal.dart';
import '../ws/local_cli_discovery.dart';
import '../ws/local_daemon_transport.dart';
import '../ws/ws_pool.dart';
import 'pane_preset.dart';
import 'pane_arrangement.dart';
import 'pending_question.dart';
import 'search_when.dart';
import 'session_content_search.dart';
import 'session_preview.dart';
import 'session_tail.dart';
import 'window_names.dart';
import '../shared/theme/appearance_prefs_store.dart';
import '../usage/models_menu_controller.dart';
import '../usage/remote_usage.dart';
import '../usage/usage_accounts.dart';
import '../orchestrator/orchestrator_controller.dart';
import '../notify/agent_alerts.dart';
import '../notify/alert_sounds.dart';
import '../notify/system_notifications.dart';
import '../notify/system_notifications.dart' as notify_system;
import 'account_devices.dart';
import '../viewer/device_log.dart' show DevLogHead;
import '../viewer/device_log_sync.dart';
import '../viewer/removed_machines.dart';
import '../e2ee/bytes.dart' show b64e;
import '../viewer/device_history.dart' show DeviceLogHistory;

enum AppStatus {
  bootstrapping,
  checkingEnvironment,
  preparingEnvironment,
  unauthenticated,
  authenticated,
}

enum AgentLoadStatus { idle, needsLink, loading, loaded, error }

enum MachineTransportMode { cloudE2ee, localPlaintext, localOffline }

/// Result of [AppNotifier.restartAgent]. [error] null means the RPC succeeded; [resumed] then says
/// whether the daemon reattached the agent's prior session or fell back to a fresh one (e.g. the
/// engine's resume flag wasn't recognized) — worth telling the user about, since it's not a failure
/// but the conversation may not have continued the way "Restart" implies.
class RestartAgentResult {
  final String? error;
  final bool resumed;
  final bool retryable;

  /// The daemon restarted without the requested launch flags and said nothing of them: it is older
  /// than the field. Never set by a status check, which does not echo them.
  final bool launchArgsIgnored;

  /// The daemon refused the requested launch flags (`INVALID_LAUNCH_ARGS`); [error] is its detail.
  final bool launchArgsRefused;

  /// The daemon answered but the engine did not come back (`unconfirmed`, `RESTART_FAILED` or
  /// `RESUME_UNCONFIRMED`). With launch flags in the request, the likeliest cause is the flags.
  final bool engineNotStarted;

  const RestartAgentResult({
    this.error,
    this.resumed = true,
    this.retryable = true,
    this.launchArgsIgnored = false,
    this.launchArgsRefused = false,
    this.engineNotStarted = false,
  });
}

/// A restart keeps its receipt when its progress prompt closes. Checking an
/// uncertain result must not replace the process a second time.
class AgentRestartAttempt {
  AgentRestartAttempt._(this._machine, this.agent, this._authRevision)
    : _removal = _machine?._agentRemovals[agent?.id],
      _stopRevision = _machine?._agentStopRevisions[agent?.id];
  final MachineState? _machine;
  final Agent? agent;
  final int _authRevision;
  final int? _removal, _stopRevision;
  String? _id;
  int _startedRevision = 0;
  bool _awaitingConfirmation = false;
  Future<RestartAgentResult>? _pending;
  RestartAgentResult? result;
  bool get awaitingConfirmation => _awaitingConfirmation;
  bool get busy => _pending != null;
  Future<RestartAgentResult>? get pending => _pending;
}

/// Result of [AppNotifier.forkAgent]. [error] null means the fork was created;
/// [level] then says what it got — `native` (the engine's own fork, the whole
/// context) or `handoff` (a first message composed from what the daemon
/// remembers of the source, for an engine that cannot fork).
class ForkAgentResult {
  final String? error;
  final String level;
  final String? agentId;
  final String? notice;

  const ForkAgentResult({
    this.error,
    this.level = 'native',
    this.agentId,
    this.notice,
  });
}

String _newCreationId() {
  final random = Random.secure();
  return List.generate(
    16,
    (_) => random.nextInt(256),
  ).map((byte) => byte.toRadixString(16).padLeft(2, '0')).join();
}

/// An in-memory draft and one deliberate fork. A lost receipt locks its
/// choices until status is checked or the user explicitly starts another fork.
class AgentForkAttempt {
  AgentForkAttempt._(
    this._machine,
    this.source,
    this._authRevision,
    this._removal, {
    this.name = '',
    this.prompt = '',
  });
  final MachineState? _machine;
  final Agent? source;
  final int _authRevision;
  final int? _removal;
  String name, prompt;
  String? _id;
  Swarm? _target;
  int? _focus;
  int _startedRevision = 0;
  bool _awaitingConfirmation = false;
  Future<ForkAgentResult>? _inFlight;
  ForkAgentResult? result;
  bool get awaitingConfirmation => _awaitingConfirmation;
  bool get busy => _inFlight != null;
  bool get locked => busy || awaitingConfirmation;
  Future<ForkAgentResult>? get pending => _inFlight;
}

/// One account an engine can run under on a machine, as Change agent offers it.
class AgentProfile {
  const AgentProfile({
    required this.id,
    required this.key,
    required this.label,
    this.path,
    this.percentLeft,
    this.offered = true,
    this.canOffer = false,
  });

  /// False when the machine's owner has not offered this account to the Swarm. Using it does not:
  /// only Swarm accounts… does ([AppNotifier.setAccountOffered]).
  final bool offered;

  /// Not the default account, on a CLI that says what is offered: Swarm accounts… can list it.
  final bool canOffer;

  /// The account's Swarm profile id ([swarmProfileId]): what `usage_read` and the current-account check use.
  final String id;

  /// What [AppNotifier.changeAgent] is given: the folder, or `'default'` for the default account.
  final String key;
  final String label;
  final String? path;

  /// Null when the machine could not read this account's usage.
  final int? percentLeft;
}

/// Null and `'default'` both mean the machine's default account.
bool sameAgentProfile(String? a, String? b) =>
    (a ?? 'default') == (b ?? 'default');

/// One deliberate creation, retained by the form if its reply is lost. Reusing
/// it checks the original request; opening New agent starts a fresh intent.
class _AgentChange {
  _AgentChange(this.source, this.engine, this.revision, [this.profile]);
  final Agent source;
  final String engine;

  /// The account folder to start in ([AgentProfile.key]); null keeps the default.
  final String? profile;
  final int revision;
  final creation = AgentCreationAttempt(background: true);
  Future<String?>? pending;
  bool preservingViews = false;
  bool handoffHeld = false;
  bool contextLoaded = false;

  /// Its machine prepared the handoff under this switch's id: its stop names
  /// the switch (a Swarm Product Manager's machine checks the two match).
  bool handoffPrepared = false;
  String? handoff;

  /// The handoff ran and left the new agent without a first prompt: say so once the switch is done.
  bool handoffEmpty = false;

  /// With [handoffEmpty]: the empty result came from the fallback road, so nobody confirmed the
  /// conversation is empty. Picks the failed hint over the no-history one.
  bool handoffFailed = false;
  String? companionTarget;
  bool launchFailed = false;
  bool replacementReported = false;
}

class AgentCreationAttempt {
  AgentCreationAttempt({
    this.background = false,
    String? creationId,
    this.holdWait,
    this.beforeSubmit,
    this.launchModel,
  }) : _id = creationId ?? _newCreationId();

  /// A model and effort for this session alone, passed as the engine's own
  /// flags (cli lib/launchModel.ts): a Product Manager's role default. A
  /// machine that cannot take them refuses before anything launches, and the
  /// same request then starts the agent on its engine's own model.
  final ({String model, String effort})? launchModel;
  bool _launchModelDropped = false;

  /// The [launchModel] the machine refused, once the agent started on its
  /// engine's own model instead; null when it launched with it.
  ({String model, String effort})? get launchModelRefused =>
      _launchModelDropped ? launchModel : null;

  /// How long a request the machine holds is waited for before the create
  /// answers ([AppNotifier._createFollowingHold]). Null answers at once with
  /// what it waits for, as a form wants: the person reads it and may cancel.
  final Duration? holdWait;
  final Future<void> Function(String machineId, String creationId)?
  beforeSubmit;
  String _id;
  String? _machineId, _targetId;
  Map<String, dynamic>? _choices;
  PaneSplitRequest? _split;
  HarnessPlacement? _placement;
  Future<String?>? _inFlight;
  bool _awaitingConfirmation = false, _finished = false;
  String? _holdReason;

  /// The machine answered `pending` with nothing held: it has begun starting
  /// this harness and ends it made or refused by itself, so it is asked after
  /// whatever [holdWait] says ([AppNotifier._createFollowingHold]).
  bool _starting = false;
  bool _cancelling = false;

  /// Prepare a session without adding a pane or changing the selected tab.
  final bool background;
  String? _agentId;
  String? get agentId => _agentId;
  String? _outcome;
  String? _preparedFolder;

  /// The SSH alias this attempt's own clone went through, until its harness
  /// starts and the person is told.
  String? _clonedVia;
  ProjectFolderRequest? _projectFolder;

  /// The worktree this computer made for this attempt, set only where it is
  /// made: [_preparedFolder] is also what a machine's refusal names. A
  /// confirmed cancel takes it back ([AppNotifier._discardCancelledWorktree]).
  ({String folder, bool keepBranch})? _worktreeMadeHere;
  String? _remoteProjectName;
  int _projectNameRetries = 0;

  /// The `codexHome` came off this machine's own agent frame (a clone), so the
  /// daemon there evidently supports it — the capability probe, which only
  /// New Harness runs, is not needed to prove it.
  bool _codexHomeTrusted = false;

  bool get awaitingConfirmation => _awaitingConfirmation;

  /// What the machine answered a create, for a test's fake `createAgent`: the harness it made, or that the
  /// start is still being confirmed.
  @visibleForTesting
  void answeredForTest({String? agentId, bool awaitingConfirmation = false}) {
    _agentId = agentId;
    _awaitingConfirmation = awaitingConfirmation;
  }

  bool get canCancelPending => _awaitingConfirmation && _holdReason != null;
  bool get canFollowPending =>
      _awaitingConfirmation && (_starting || _holdReason != null);

  /// The machine's code for a request it refused before launching anything,
  /// such as `SESSION_BUSY_IN_TERMINAL`: what a caller can offer next.
  String? _refusal;
  String? get refusal => _refusal;

  /// A completed folder survives a refused agent launch, so correcting the
  /// agent choice does not clone or create the same project again.
  String? get preparedFolder => _preparedFolder;

  /// On `PROJECT_EXISTS` for a new project's name the person typed: the
  /// folder already there, when it is one to start in. Unlike
  /// [preparedFolder] it is only offered ("Use the existing folder"), never
  /// used until the person chooses it.
  String? _existingFolder;
  String? get existingFolder => _existingFolder;

  /// After the machine refused a launch model before launching anything
  /// (AppNotifier.createAgent): the request may be sent again without it.
  void _retryWithoutLaunchModel() {
    _launchModelDropped = true;
    _finished = false;
    _outcome = null;
    _refusal = null;
  }

  String? _complete(String? error) {
    _finished = true;
    _awaitingConfirmation = false;
    _holdReason = null;
    _starting = false;
    return _outcome = error;
  }
}

String? _normalizeComputerId(String? raw) {
  if (raw == null) return null;
  final value = raw.trim().toLowerCase().replaceAll('-', '');
  return RegExp(r'^[a-f0-9]{16,64}$').hasMatch(value) ? value : null;
}

/// Explicit, compile-time guarded fixture used only by `main_local_manual.dart`.
///
/// It lets a normal Flutter window exercise the local Backend -> Harness CLI ->
/// tmux path without depending on SSO. The API key is a random, disposable
/// value produced by the local launcher and is never persisted.
class LocalManualFixture {
  final String apiBaseUrl;
  final String apiKey;
  final String machineId;
  final String machineName;

  const LocalManualFixture({
    required this.apiBaseUrl,
    required this.apiKey,
    required this.machineId,
    required this.machineName,
  });
}

@visibleForTesting
Map<String, dynamic> eventWithClearPayload(
  Map<String, dynamic> frame,
  String type,
  Map<String, dynamic> payload,
) => {...frame, 'type': type, 'payload': payload};

class MachineState {
  Machine machine;

  /// Whether this is not the signed-in account's own computer: one harness
  /// another account shares (`isShared`) or a whole machine another account
  /// shares (`isSharedMachine`). Its daemon answers as its owner, so shared
  /// tabs never ask it, and a harness on it is never this account's own.
  bool get belongsToOtherAccount => machine.isShared || machine.isSharedMachine;
  int _agentRevision = 0;
  final _agentRemovals = <String, int>{};
  final _agentStopRevisions = <String, int>{};
  final _agentRestartRevisions = <String, int>{};
  final _agentNames =
      <String, ({int revision, String? sessionId, String name})>{};
  ConnectionStatus connectionStatus = ConnectionStatus.disconnected;
  MachineTransportMode transportMode = MachineTransportMode.cloudE2ee;

  /// Set when this machine is bound to the local CLI's stable computer id. A
  /// local machine never falls back to cloud E2EE while that identity exists.
  bool localOnly = false;
  LocalCliEndpoint? localEndpoint;
  Map<String, AgentProject> localProjects = const {};
  // Set when the local CLI's relay reports NO_PEER_LINK for this (non-local) machine — it needs
  // `harness link connect <machineId>` (the other machine's remote password) before it can
  // connect. The CLI owns E2EE entirely now; this is just "is trust established yet", not a
  // crypto/pairing state the app has any data for.
  bool needsLink = false;
  List<Agent> _agents = [];

  /// This machine's agents. Every change counts in [agentsRevision].
  List<Agent> get agents => _agents;
  set agents(List<Agent> value) {
    _agents = value;
    agentsRevision++;
  }

  /// Moves with every change of [agents]: a list read before one is older than it
  /// ([AppNotifier._syncAgentsIfChanged]).
  int agentsRevision = 0;

  /// Whether this window has read the machine's whole list once. What was in
  /// it, or pushed before it, was there when the window came: a harness an
  /// agent started opens beside its starter only when it appears after
  /// (`AppNotifier._openStartedChild`), never on a restore.
  bool agentsListedOnce = false;
  AgentLoadStatus agentLoadStatus = AgentLoadStatus.idle;
  bool agentsRefreshing = false;
  String? agentsLoadError;
  Future<void>? agentsLoadInFlight;
  Future<void>? terminalCapabilityLoadInFlight;
  int _discoveryRevision = 0;
  String? activeAgentId;
  bool terminalCapabilityLoaded = false;
  bool terminalCapabilityAvailable = false;
  String? terminalCapabilityError;

  /// Whether this machine's CLI honours `takeover: false` on `terminal_open` —
  /// open as a watcher rather than closing whoever holds the terminal.
  ///
  /// ⚠️ False is not "opens are polite anyway", it is the opposite: an older
  /// CLI ignores the key and takes the terminal over like any other open. So
  /// nothing may be opened here without a person asking on this window — see
  /// [AppNotifier._attachPendingPanes] and [AttachIntent].
  bool terminalNoTakeoverAvailable = false;
  // Whether this machine's CLI daemon understands `terminal_paste` (a clipboard paste delivered as
  // one atomic tmux paste-buffer, not chunked like ordinary keystrokes — see TerminalSession.pasteText).
  // False for any CLI published before this existed; the panel falls back to the old chunked path.
  bool terminalPasteRawAvailable = false;
  // Whether this machine's CLI daemon understands TerminalBinaryKind.imagePaste (a native clipboard
  // IMAGE paste — see TerminalSession.pasteImage). False for any CLI published before this existed;
  // the panel falls back to forwarding a bare Ctrl+V, today's only option for an image paste.
  bool terminalImagePasteAvailable = false;
  // Whether this machine's CLI daemon understands TerminalBinaryKind.pasteFile (a dropped non-image
  // file, written to disk on that machine and pasted as a path — see TerminalSession.pasteFile).
  // Only consulted for a REMOTE pane; a local one pastes its own path directly and never needs this.
  bool terminalPasteFileAvailable = false;
  bool mediaPreviewAvailable = false;
  // Which engines this machine actually has, as this machine answered it. Kept
  // on MachineState rather than globally because that is the whole point: two
  // machines on one account hold different engines, and the Docker rig holds
  // exactly one. See `engines_probe` in the CLI's backendSocket.
  final MachineEngines engines = MachineEngines();
  // Which domain-specific harnesses this machine has or could install, as it
  // answered `dsh_list`. Per machine for the same reason `engines` is: an
  // install is a clone and a toolchain on ONE box.
  final MachineDsh dsh = MachineDsh();
  // Adapter/manager presence for this machine, from `node_status` pushes —
  // distinct from `connectionStatus`, which only reflects OUR websocket to
  // the backend. null = not seen yet (initial connect).
  bool? nodeOnline;
  // Captured only after machine selection succeeds, including the remote
  // handshake. Merely opening the socket to the local service is not enough.
  WsConn? _selectedConnection;
  bool get _selectedConnectionReady =>
      connectionStatus == ConnectionStatus.connected &&
      _selectedConnection?.isReady == true;
  // The agent the user selected while the Harness adapter was offline. Keep
  // this separate from activeAgentId so the UI can show a join guide without
  // opening a terminal stream against an unavailable node.
  String? pendingOfflineAgentId;
  final Set<String> processingAgentIds = {};
  final Set<String> unknownActivityAgentIds = {};
  final Map<String, AgentActivityOrder> activityOrder = {};
  final Set<String> legacyHeartbeatSeen = {};

  /// Successful turn events from work opened in this workspace: the daemon's
  /// `turn` and `store` habits (read only while daemons are on). Capture the
  /// harness and model at completion so later switches cannot earn them.
  /// Account changes discard MachineState; the zoo keeps what was earned.
  final completedHarnessUses = <({String harness, String? model})>{};
  int completedHarnessTurns = 0;

  /// The same turns when they ended with an error: the daemon's `fail`.
  int failedHarnessTurns = 0;

  /// The last few of those turn ends, newest last: which harness finished or
  /// failed, so the daemon can say who (and not about the pane in front).
  final recentTurnEnds = <({String agentId, bool failed})>[];

  /// Known harnesses whose last turn failed, until their next turn starts or
  /// ends well: the daemon's `fail` face while it lasts.
  final failedTurnAgents = <String>{};

  /// Paused harnesses this window resumed: the daemon's `resume` habit.
  int resumedHarnesses = 0;

  /// Agents whose `turn_started` this window saw live (not a heartbeat).
  final liveTurnAgents = <String>{};

  /// Turns counted the way harnessd counts them for the zoo
  /// (daemons/README.md, "What counts as a turn"): started live, ended without
  /// error or interrupt, not a sub-agent, a terminal or the pair harness. Only
  /// a guest's local zoo uses it; a signed-in harnessd reports its own.
  int zooTurns = 0;

  /// Agents on this machine that have stopped to ask something, by agentId.
  /// At most one per agent: a pane shows one dialog at a time, and the daemon
  /// re-announces the same open question rather than queueing a second.
  final Map<String, PendingQuestion> blockedAgents = {};
  final Map<String, String> sessionAgentIds = {};
  // Turn events can arrive while the initial agents_list RPC is still in
  // flight. Retain session correlation until that snapshot binds the row.
  final Set<String> pendingProcessingSessions = {};

  MachineState(this.machine);

  bool get isRemote => machine.authMode == MachineAuthMode.remote;
  bool get isLocalMachine => localOnly || localEndpoint != null;
  bool get usesLocalTransport => localEndpoint != null;

  /// Whether this machine can be given work right now.
  ///
  /// An explicit offline report always wins. A saved or hopeful [nodeOnline]
  /// value cannot override the inventory either. A successfully selected,
  /// still-ready connection is stronger evidence: the local relay acknowledges
  /// selection only after its handshake with the remote machine succeeds.
  /// This computer also remains usable when its backend inventory is stale.
  bool get isOffline =>
      nodeOnline == false ||
      (!isLocalMachine &&
          machine.reportedOnline == false &&
          !(nodeOnline == true && _selectedConnectionReady));

  AgentProject? projectOf(Agent agent) =>
      agent.displayProject ??
      localProjects[agent.id] ??
      localEndpoint?.agentProjects[agent.id];

  Agent? get activeAgent {
    for (final agent in agents) {
      if (agent.id == activeAgentId) return agent;
    }
    return null;
  }
}

/// Auth, Remote-machine discovery, E2EE and one explicit terminal attachment.
/// Structured chat intentionally does not exist in the Desktop MVP state.
/// A spoken task the daemon wants THIS window to route — see the `voice_route_request` case below.
///
/// Deliberately not the palette's own [SpokenTask]: this layer holds no callback and knows nothing about
/// dialogs. The screen that can open one turns this into that, and wires the answer back through
/// [AppNotifier.reportVoiceRoute].
class SpokenTaskRequest {
  const SpokenTaskRequest({
    required this.voiceId,
    required this.machineId,
    required this.text,
    required this.cmd,
  });

  final String voiceId;

  /// Which daemon asked — the answer has to go back to that one, not to whichever is selected when the
  /// person finally picks.
  final String machineId;
  final String text;

  /// 'goal', 'loop', or empty: which of the dial's three buttons was held.
  final String cmd;
}

/// One line in the rail: a machine, or an agent under one.
///
/// A record rather than a widget key, because the cursor has to survive a
/// rebuild that changes what is on screen — an agent finishing, a machine going
/// offline — and an index into a list of widgets does not.
@immutable
class RailRow {
  const RailRow({required this.machineId, this.agentId});

  final String machineId;

  /// Null for the machine's own row.
  final String? agentId;

  @override
  bool operator ==(Object other) =>
      other is RailRow &&
      other.machineId == machineId &&
      other.agentId == agentId;

  @override
  int get hashCode => Object.hash(machineId, agentId);
}

class _MachineLinkAttempt {
  _MachineLinkAttempt(this.authRevision);
  final int authRevision;
  final result = Completer<String?>();
  String stage = 'connecting';
}

class _RemotePasswordChange {
  _RemotePasswordChange(this.authRevision, {required this.clearing});
  final int authRevision;
  final bool clearing;
  final result = Completer<RemotePasswordStatus>();
}

class _MachineEdit {
  _MachineEdit(this.machine, this.authRevision, this.name);
  final MachineState machine;
  final int authRevision;
  final String? name; // null deletes the machine; a string renames it.
  final result = Completer<String?>();
}

class _AgentRename {
  _AgentRename(this.machine, this.agent, this.authRevision, this.name)
    : nameRevision = machine._agentRevision;
  final MachineState machine;
  final Agent agent;
  final int authRevision, nameRevision;
  final String name;
  final result = Completer<String?>();
}

class _AgentStop {
  _AgentStop(this.machine, this.agent, this.authRevision);
  final MachineState machine;
  final Agent agent;
  final int authRevision;
  bool confirmed = false;
  final result = Completer<String?>();
}

/// Who asked for a terminal to be opened.
///
/// A terminal has ONE controller and an ordinary `terminal_open` wins it, so
/// every attach has to say whether a person on THIS window asked for it.
/// [person] may take the terminal from whoever holds it; [automatic] never may
/// — it opens as a watcher where the daemon supports that, and does not open at
/// all where it does not. Everything that is not a gesture on this Mac is
/// automatic: a tab another Mac opened arriving over the desk, a reconnect, a
/// machine answering its agent list, a push, the dial turning, a handoff.
enum AttachIntent { person, automatic }

/// Machines asked for from outside the workspace ([AppNotifier.requestMachines]): the device to
/// select there, or the first phone or app.
typedef MachinesRequest = ({String? devicePub, bool phones});

const buddyKeepsItsEngine = 'A Buddy keeps its engine for now';

/// Change agent on a Swarm Buddy, which keeps running and so keeps its agent
/// (hn's `BUDDY_KEEPS_ITS_AGENT`, word for word).
const buddyKeepsItsAgent =
    'A Swarm Buddy keeps its agent. To use another agent, its person removes the Buddy and adds a new one.';

class AppNotifier extends ChangeNotifier {
  final AuthSession session;

  /// The noise this window makes when an agent finishes or gets stuck.
  final AlertSounds alerts;

  /// And what it puts on screen for the same two moments. Its own notifier, so
  /// a banner appearing does not rebuild the workspace.
  final AgentAlerts agentAlerts;

  /// And what it hands the operating system, for when the window is not in
  /// front and neither the banner nor the badge can be seen.
  final SystemNotifications systemNotifications;

  /// Which agents have news nobody has looked at. Marked on the same two
  /// moments and NOT behind the banner or sound switches — see [AgentUnread].
  final AgentUnread agentUnread;
  // Delivery deduplication only. The daemon owns notification eligibility for
  // both desktop and device; a raw turn_ended is not a completed result.
  final Set<String> _deliveredNotifications = {};
  // Read receipts suppress a restored question's notification, never the
  // question itself. A matching close or replacement gives the next one a
  // fresh identity; reconnecting the same question keeps it read.
  final Map<String, String> _readQuestionNotifications = {};

  AppConfig config;
  late ApiClient api;
  late final ProductMeasurement productMeasurement;
  ProductRuntimeHealth? productRuntimeHealth;
  late final ProductConnections productConnections;
  final _measurementResumes = <String, void Function(ProductOutcome)>{};
  void Function(bool)? _measurementError;
  int _measurementGeneration = -1;
  final _measurementConnections = <String, void Function(ProductOutcome)>{};

  /// Signs in, and says whether this computer is signed in: the harness CLI in a desktop build,
  /// [ViewerServices.login] in a viewer build — which has no CLI — under one name, so every call
  /// site reads the same in both.
  late final SignInClient cliLogin;
  CliLink? _cliLink;
  CliLink get cliLink => _cliLink ??= CliLink();

  /// Links to other machines by remote password: [cliLink] in a desktop build, the app itself in a
  /// viewer. THIS machine's own remote password stays on [cliLink] — a viewer is not a machine, and
  /// has no password for anyone to link to.
  late final PeerLinkClient peerLinks;
  final _machineLinks = <String, _MachineLinkAttempt>{};
  final _machineEdits = <String, _MachineEdit>{};
  final _agentRenames = <(String, String), _AgentRename>{};
  final _agentStops = <(String, String), _AgentStop>{};
  final _agentPauses = <(String, String), Future<String?>>{};

  /// The workspace supplies presentation; the model owns target identity and completion.
  Future<bool> Function(
    List<(String, Agent)>, {
    String? tabName,
    bool Function(String machineId, String agentId)? canStop,
  })?
  reviewSessionClose;
  final _viewCloseRequests = <String, Future<void>>{};
  final _closingViewAgents = <(String, String), int>{};
  final _agentForks = <(String, String), AgentForkAttempt>{};
  final _agentRestarts = <(String, String), AgentRestartAttempt>{};
  int _machineEditRevision = 0;
  // Account edits outrank inventories requested before them, and the daemon’s
  // offline cache. Keep per-id revisions for overlapping inventory requests.
  final _confirmedMachineEdits = <String, (int, String?)>{};

  /// Linking belongs to the machine, so closing its prompt cannot start a
  /// second handshake when the same prompt is reopened.
  Future<String?>? pendingMachineLink(String machineId) {
    final attempt = _machineLinks[machineId];
    return attempt != null && _authWorkCurrent(attempt.authRevision)
        ? attempt.result.future
        : null;
  }

  String? machineLinkStage(String machineId) =>
      pendingMachineLink(machineId) == null
      ? null
      : _machineLinks[machineId]?.stage;

  /// A viewer build's stand-ins for the harness CLI (`lib/viewer/`); null on a desktop build.
  final ViewerServices? viewer;
  final ConfigStore? _store;

  /// Spoken tasks waiting for a palette. Broadcast because the screen subscribes and unsubscribes with
  /// its own lifetime, and a request that arrives with no screen up is dropped rather than queued — the
  /// daemon's own deadline is the thing that decides how long a spoken task stays interesting.
  final StreamController<SpokenTaskRequest> _spokenTasks =
      StreamController<SpokenTaskRequest>.broadcast();

  /// Words from the dial, for whoever can put a palette on screen.
  Stream<SpokenTaskRequest> get spokenTasks => _spokenTasks.stream;

  final StreamController<void> _deviceWindowRequests =
      StreamController<void>.broadcast();

  /// Explicit gestures at this computer's device that need its window visible.
  /// Automatic question displays and status updates never request activation.
  Stream<void> get deviceWindowRequests => _deviceWindowRequests.stream;

  void _requestDeviceWindow(MachineState source) {
    if (!_disposed &&
        viewer == null &&
        source.usesLocalTransport &&
        !source.machine.isShared) {
      _deviceWindowRequests.add(null);
    }
  }

  final StreamController<void> _modelsRequests =
      StreamController<void>.broadcast();

  /// `zoo_changed` revisions, as harnessd relays them. The zoo lives beside the
  /// workspace (lib/daemons/zoo_controller.dart), not in this notifier.
  final StreamController<int?> _zooPushes = StreamController<int?>.broadcast();
  Stream<int?> get zooPushes => _zooPushes.stream;

  /// The pair brain's local frames (`daemon_state`, `daemon_say`, ...), heard
  /// only from this computer's own harnessd (daemons/BRAIN.md).
  final StreamController<({String type, Map<String, dynamic> payload})>
  _daemonFrames = StreamController.broadcast();
  Stream<({String type, Map<String, dynamic> payload})> get daemonFrames =>
      _daemonFrames.stream;

  /// Replaces the socket send in tests.
  @visibleForTesting
  bool Function(String type, Map<String, dynamic> payload)?
  daemonFrameSenderForTest;

  /// Send a `daemon_*` frame on the socket bound to this computer's own
  /// harnessd, never on a relayed one: an older daemon forwards unknown frames
  /// from a relayed socket to the cloud. False when there is no such socket.
  bool sendDaemonFrame(String type, Map<String, dynamic> payload) {
    final test = daemonFrameSenderForTest;
    if (test != null) return test(type, payload);
    for (final machine in machineStates.values) {
      if (!machine.usesLocalTransport) continue;
      final connection = _pool?[machine.machine.machineId];
      if (connection == null || !connection.isReady) return false;
      // Windows accepts these frames only over its private pipe.
      if (connection.trustedPipeMissing) {
        return false;
      }
      unawaited(
        connection.sendTerminalFrame(type, payload).catchError((_) => false),
      );
      return true;
    }
    return false;
  }

  /// Whether this computer's daemon pipe was missing or failed proof at the
  /// last connection attempt. Never true on macOS or Linux.
  bool get daemonTrustedConnectionMissing {
    for (final machine in machineStates.values) {
      if (!machine.usesLocalTransport) continue;
      final connection = _pool?[machine.machine.machineId];
      return connection != null && connection.trustedPipeMissing;
    }
    return false;
  }

  final _ownerMemoryConnections = <LocalCodingMemoryConnection>{};

  /// Only the already-discovered daemon on this computer. Inspecting memories
  /// never provisions a service, connects a remote machine or launches an agent.
  CodingMemoryConnection? openCodingMemoryConnection() {
    if (_disposed || viewer != null || kIsWeb) return null;
    final machine = machineStates.values
        .where((m) => m.usesLocalTransport)
        .firstOrNull;
    final endpoint = machine?.localEndpoint;
    if (machine == null || endpoint == null) return null;
    final auth = _authRevision, owner = currentUser?.id;
    final id = machine.machine.machineId;
    late final LocalCodingMemoryConnection connection;
    connection = LocalCodingMemoryConnection(
      endpoint: endpoint,
      machineId: id,
      localTransport: localDaemonTransport,
      isCurrent: () =>
          _authWorkCurrent(auth) &&
          currentUser?.id == owner &&
          machineStates[id]?.localEndpoint?.wsUri == endpoint.wsUri &&
          machineStates[id]?.localEndpoint?.protocolVersion ==
              endpoint.protocolVersion,
      onClosed: () => _ownerMemoryConnections.remove(connection),
    );
    _ownerMemoryConnections.add(connection);
    return connection;
  }

  void _closeOwnerMemories() {
    for (final connection in _ownerMemoryConnections.toList()) {
      connection.invalidate();
    }
    _ownerMemoryConnections.clear();
  }

  Stream<void> get modelsRequests => _modelsRequests.stream;
  final LocalManualFixture? localManualFixture;
  final Duration turnActivityTimeout;
  final LocalCliDiscovery? localCliDiscovery;

  /// ONE discovery for the whole notifier. It used to be built fresh at each of
  /// three call sites, which was harmless while it was stateless and is not
  /// now that the supervisor's ready-transition callback lives on it.
  ///
  /// `late`, so it reads `config` on first use — which is [ensureCliDaemonReady]
  /// during bootstrap, AFTER the persisted config has been loaded over the
  /// default. Touch it earlier and it freezes the wrong `localCliBaseUrl`.
  late final LocalCliDiscovery _discovery =
      localCliDiscovery ?? LocalCliDiscovery(config: config);

  /// Restarts a daemon this app did not launch, so it runs under the app's Local Network permission
  /// (see `core/process_responsibility.dart`). macOS only, and never under `flutter test` or with an
  /// injected discovery: a restart there would `harness stop` the real daemon of the machine the
  /// suite runs on.
  late final DaemonOwnerGuard? _daemonOwner =
      Platform.isMacOS &&
          !kUnderTest &&
          localCliDiscovery == null &&
          viewer == null
      ? DaemonOwnerGuard(
          probe: MacResponsibilityProbe(),
          ownPid: pid,
          // An uninstall at work as well: this restart is a `harness stop` and a start beside it.
          paused: () =>
              SerialPortLease.heldByAnotherProcess() || UninstallMarker.held(),
          restart: () async {
            final probe = await _discovery.restart();
            return probe.ready ? probe.pid : null;
          },
          lanBlocked: () async {
            try {
              final cli = AutonomousDeviceCli();
              // Discovery is what raises macOS's "find devices on local networks… Autonomous robots"
              // prompt. Everyone who reopened the app after its daemon outlived it saw that prompt on
              // their second session, robots or not (fresh macOS VM, 2026-10-08). Without a paired
              // robot nothing here needs the LAN, so it is not tested.
              final paired = (await cli.list())['devices'];
              if (!_localNetworkWanted && (paired is! List || paired.isEmpty)) {
                return null;
              }
              await cli.discover();
              return false;
            } on AutonomousDeviceCliException catch (error) {
              return error.localNetworkBlocked ? true : null;
            } catch (_) {
              return null;
            }
          },
          log: (line) => appLog.info('daemon', line),
        )
      : null;
  final EnvironmentProvisioner? environmentProvisioner;

  /// OpenCode downloaded beside a fresh computer's setup (see [AgentPrefetch]). Null under test
  /// unless a test passes one, so nothing there runs `curl`.
  final AgentPrefetch? agentPrefetch;
  final DesktopUpdater? desktopUpdater;

  /// Windows release builds hand a zip copy to its launcher before setup.
  final WindowsSelfInstall? windowsSelfInstall;
  final void Function(int code) _exitApp;
  @visibleForTesting
  final WsConn Function(String machineId)? connectionForTest;
  final Map<String, Timer> _turnActivityWatchdogs = {};

  /// What each machine's daemon last said the account's grids serve — the one list the pane
  /// picker, the macOS Models menu and the Model Manager all read. See [GridPictures].
  final GridPictures gridPictures = GridPictures();

  /// Which agents were sent a message while their model's computer was resting and have not
  /// answered yet — the pane chip's "Starting up…". Fed by [_watchModelStart] and ended with every
  /// turn ([_cancelTurnActivity]). See [ModelStartWatch] for why these signals and not others.
  final ModelStartWatch modelStarts = ModelStartWatch();

  /// Whether the app is in front of the person (`AppLifecycleState.resumed`). The three surfaces
  /// that refresh [gridPictures] on their own — the Model Manager's timer, the macOS menu's refresh
  /// and the pane picker's prefetch — run only while this is true, and each refreshes once when it
  /// turns true again. A minimised or background app asks nothing. True until the platform says
  /// otherwise, so a state nobody reported (a test, the first frame) behaves as it always did.
  final ValueNotifier<bool> foreground = ValueNotifier(true);

  bool get inForeground => foreground.value;

  /// Whether the window can be seen at all: in front, or in sight behind the window that has focus
  /// (`inactive`). A browser tab behind others, or a minimised window, cannot. Harness Monitor's
  /// page reads every machine while it is seen, and stops when this turns false.
  final ValueNotifier<bool> inSight = ValueNotifier(true);

  /// Fed by the workspace's [AppLifecycleListener]. A null state is unknown, read as foreground.
  void appLifecycleChanged(AppLifecycleState? state) {
    if (_disposed) return;
    final wasForeground = foreground.value, wasInSight = inSight.value;
    foreground.value = state == null || state == AppLifecycleState.resumed;
    inSight.value =
        state == null ||
        state == AppLifecycleState.resumed ||
        state == AppLifecycleState.inactive;
    if (wasInSight && !inSight.value) _pauseBackgroundRereads();
    if (!wasInSight && inSight.value) _resumeBackgroundRereads();
    // Every transition, not only the three the listener has callbacks for: hidden -> inactive fires
    // onShow, and a window shown again without focus must not keep telling the daemon it shows nothing.
    _announceVisibleAgents();
    if (wasForeground && !foreground.value) {
      _awaySince = phoneOfferClock();
      _missedWhileAway = null;
    }
    // Back in front: a viewer reads the device log again, and joins it if the boot never got in.
    if (foreground.value && !wasForeground) {
      final away = _awaySince, missed = _missedWhileAway;
      _awaySince = null;
      _missedWhileAway = null;
      if (away != null &&
          missed != null &&
          phoneOfferClock().difference(away) >= phoneOfferAwayAfter) {
        unawaited(_offerPhoneAway(missed));
      }
      if (_notificationOfferDue) {
        _notificationOfferDue = false;
        unawaited(notificationOfferStoreForTest.set(true));
        notificationOffer?.call();
      }
      _refreshDeviceLogAfterReconnect();
      // ...and, hearing no machine at all, looks again for one: the person most likely just went to
      // their computer to sign it in. The wait for the next read starts over too.
      _deafMachineListWatch.reset();
      unawaited(_rereadMachinesWhileDeaf());
    }
  }

  /// Bumped once per real agent event (a turn starting or ending, a tool
  /// starting or ending, output arriving): the daemon steps its work frame on
  /// it, so a still baton means a stalled agent. Its own notifier, so an event
  /// never rebuilds the workspace.
  final agentPulse = ValueNotifier<int>(0);

  late final sessionPreviews = SessionPreviewStore(
    canFetch: _canFetchPreview,
    fetchRecent: (key) => _conn(key.machineId).request(
      'agent_recent',
      payload: {'agentId': key.agentId, 'n': 3},
      timeout: const Duration(seconds: 6),
    ),
  );

  /// Which of the owner's harnesses are shared, and how — for marking panes.
  late final shareStatus = HarnessShareStatus(
    (machineId, agentId) => manageHarnessShares(machineId, agentId, 'list'),
  );

  /// The end of the session a Cmd-P row previews, from its machine's index
  /// (`session_tail`, cli/src/lib/sessionSearch/). Apart from
  /// [sessionPreviews], whose excerpts come from the live agent.
  late final sessionTails = SessionTails(readSessionTail);

  SessionPreviewKey previewKey(String machineId, Agent agent) =>
      (machineId: machineId, agentId: agent.id, sessionId: agent.sessionId);

  bool _canFetchPreview(SessionPreviewKey key) {
    if (_disposed || (_pool == null && connectionForTest == null)) return false;
    final machine = machineStates[key.machineId];
    return machine != null &&
        // A guest is read no conversation there (`agent_recent` is the owner's).
        !machine.machine.isSharedMachine &&
        machine.nodeOnline != false &&
        !machine.needsLink &&
        (machine.connectionStatus == ConnectionStatus.connected ||
            connectionForTest != null) &&
        machine.agents.any(
          (agent) =>
              agent.id == key.agentId && agent.sessionId == key.sessionId,
        );
  }

  void _warmPreviews(MachineState machine) => sessionPreviews.warm(
    machine.agents.map((agent) => previewKey(machine.machine.machineId, agent)),
  );

  final Map<String, Timer> _offlineRetryTimers = {};
  final Map<TerminalPane, Timer> _paneRetryTimers = {};
  final Map<TerminalPane, int> _paneRetryAttempts = {};

  /// What the pane sweep saw of each session when it last ran (see [_retryPhase]).
  final Map<TerminalSession, int> _sweptRetryPhases = {};
  int _paneSweeps = 0;

  /// How many times the pane sweep ([_schedulePaneRetries]) has run.
  @visibleForTesting
  int get paneSweepsForTest => _paneSweeps;

  /// When [_forceRedial] last redialled each machine, on [redialClock].
  final Map<String, Duration> _lastForcedRedial = {};

  /// Machines whose socket a forced redial has taken down and not yet brought back, with when it began.
  final Map<String, Duration> _forcedRedials = {};

  /// Monotonic, so a wall-clock change can neither hold redials off nor let a burst through.
  @visibleForTesting
  Duration Function() redialClock = _monotonicClock();

  static Duration Function() _monotonicClock() {
    final watch = Stopwatch()..start();
    return () => watch.elapsed;
  }

  /// One reload per machine, owed after this computer's daemon was too slow to answer its list while
  /// still on the socket — the error strip says "retrying", and this is the retry.
  final Map<String, Timer> _slowReloadTimers = {};
  // Periodic retry for a machine the relay reported NO_PEER_LINK for — a `harness link connect` run
  // in a terminal (or another app instance) has no way to notify this one, so this is what makes the
  // app pick up a fresh link instead of only on the next manual click/restart.
  // Native retries back off and never replace a connection still being established.
  final Map<String, Timer> _linkRetryTimers = {};
  final Map<String, Future<bool>> _trustedConnections = {};
  // Safety-net reconciliation for a connected machine's agent list, on top of the push events
  // (agent_synced/agent_created/agent_renamed/agent_deleted) that normally keep it live — catches the
  // rare case a push event was dropped. Runs silently: see _syncAgentsIfChanged.
  final Map<String, Timer> _agentSyncTimers = {};

  /// Machines with a harness the daemon holds back ([_watchHeldLaunches]).
  final Map<String, Timer> _heldSyncTimers = {};

  /// Reads in a row that found nothing new, per machine ([_watchHeldLaunches]).
  final Map<String, int> _heldSyncRounds = {};

  /// How often a machine with a held harness is read again ([_watchHeldLaunches]).
  @visibleForTesting
  Duration heldLaunchSyncInterval = const Duration(seconds: 3);
  // Keeps the local `harness` daemon alive for the whole app run — started once after the first
  // successful bootstrap (see `ensureCliDaemonReady`), cancelled on dispose. Cancelling only stops this
  // Dart-side loop; the daemon itself self-daemonizes and must keep running after the app quits.
  Timer? _daemonSupervisionTimer;
  // Backend REST can fail while the daemon and its WebSocket remain ready. Recover that list
  // independently, with capped backoff and the same in-flight request as a manual retry.
  Timer? _machineRecoveryTimer;
  Timer? _sharingDiscoveryTimer;
  // A `machines_changed` push waiting for its copies from the other machines ([machinesPushCollapse]).
  Timer? _machinesPushTimer;
  // A viewer with no machine socket open hears no push at all — a machine that joins the account is
  // only found by this. See [_rereadMachinesWhileDeaf].
  late final _deafMachineListWatch = MachineListWatch(
    wanted: () => _deafReadWanted,
    read: _rereadMachinesWhileDeaf,
    pace: () =>
        deafMachineListPaceForTest ??
        (waitsForFirstComputer
            ? firstComputerMachineListPace
            : asleepComputers.isNotEmpty
            ? asleepComputersMachineListPace
            : deafMachineListPace),
  );
  bool _sharingDiscoveryBusy = false;
  bool _sharingDiscoveryAgain = false;
  int _machineRecoveryAttempts = 0;
  String? _machineLoadError;

  /// The last [ensureCliDaemonReady] did not reach a ready daemon — the one
  /// error the supervisor's ready transition is allowed to retry away.
  bool _daemonGateFailed = false;

  /// The daemon's backend link as it last reported it (`/api/status.connected`), fed by the boot
  /// probe and then by the supervisor's 5s tick. Null until a daemon has answered at all. False is
  /// not an error: this computer's agents work over the loopback regardless; it is what makes the
  /// rail say "offline copy" and what keeps a failed machine list from raising the red strip.
  bool? _backendOnline;
  bool? get backendOnline => _backendOnline;
  // The last probe state the boot gate logged, so a daemon that sits in one state for a minute
  // costs one line, not one per 500ms tick.
  String? _loggedDaemonState;
  // Update checks do not depend on the daemon or SSO. A signed-out user should
  // still be able to replace a broken desktop build from the login screen.
  Timer? _updateCheckTimer;
  // A zip copy whose installer did not start can run, but cannot update itself.
  bool _selfInstallUnavailable = false;

  /// Ends the window in which a restored tile may still claim its terminal —
  /// see [TerminalPane.claimOnFirstAttach]. Without it a machine that only
  /// came back in the afternoon would be met by a claim made at breakfast.
  Timer? _launchClaimTimer;
  static const launchClaimWindow = Duration(minutes: 5);
  late final DesktopUpdater _updater = desktopUpdater ?? DesktopUpdater();
  Future<ManualUpdateCheck>? _manualUpdateCheckInFlight;
  DesktopUpdateCheck? lastUpdateCheck;
  bool get updateChecksEnabled =>
      viewer == null && !_selfInstallUnavailable && _updater.canCheck;
  String? _skippedDesktopUpdateVersion;
  UpdateInfo? availableUpdate;
  bool isCheckingForUpdate = false;
  bool isInstallingUpdate = false;

  /// How much of the new build has arrived, 0..1, while it is downloading;
  /// null before the first byte and again once the bytes are in — verifying and
  /// unpacking have no counter, so the bar goes back to indeterminate rather
  /// than sitting at a 100% that has not finished anything.
  double? updateDownloadFraction;
  String? updateError;
  bool windowsUpdatePartiallyPublished = false;
  final Set<String> _offlinePollsInFlight = {};
  final Map<String, Object> _offlineRecoveryInFlight = {};
  bool _disposed = false;

  // Account and inventory replies belong to the session that requested them.
  // Signing out invalidates them before asynchronous connection cleanup.
  int _authRevision = 0;

  /// Cancels work across account changes, independently of measurement preferences.
  int get accountGeneration => _authRevision;
  Future<void>? _profileInFlight;

  bool _authWorkCurrent(int revision) =>
      !_disposed && revision == _authRevision;

  int _invalidateAuthWork() {
    _closeAttachmentSessions();
    // A card a sign-out or another sign-in takes away went neither way.
    _endPhoneOffer(ProductOutcome.unknown);
    _phoneOffer = false;
    _phoneOfferAway = null;
    _missedWhileAway = null;
    _phoneOfferAfterWorkAsked = false;
    _phoneOfferAfterWorkUnanswered = 0;
    _accountHasPhone = false;
    _closeOwnerMemories();
    _stopMachineRecovery();
    api.resetAccountCache();
    _sessionExpired = false;
    _machineLoadError = null;
    _resetLoginBrowser();
    _loginAuthorized = false;
    _profileInFlight = null;
    _retryInFlight = null;
    machinesLoading = false;
    _machineInventoryLoaded = false;
    _linkedMachinesRequest = null;
    _unlinkRequests.clear();
    _machineEdits.clear();
    _agentRenames.clear();
    _agentStops.clear();
    _agentPauses.clear();
    _agentForks.clear();
    _agentRestarts.clear();
    _confirmedMachineEdits.clear();
    linkedMachines = [];
    linkedMachinesLoading = false;
    linkedMachinesError = null;
    return ++_authRevision;
  }

  WsPool? _pool;
  late String _autonomousEnv;
  String? _lastError;
  // Retrying re-runs `refreshMachines()` — a real fix for "could not load
  // machines" or a daemon hiccup, but a no-op for a failure that already
  // finished (an agent's launch), where the only honest control is to
  // dismiss it.
  bool _lastErrorRetryable = true;
  // Shown on the pre-navigation `bootstrapping` screen while [_finishBootstrapSignedIn] waits on the
  // local daemon — null the rest of the time, including once [status] flips to `authenticated`.
  String? _bootStatusMessage;
  EnvironmentReadiness environmentReadiness = EnvironmentReadiness.initial();
  bool _environmentSetupInFlight = false;
  bool _environmentInstallRequested = false;
  // Polls a step stuck in needsTerminal/failed every 5s (see `_scheduleEnvironmentRecheck`) so a user
  // who fixes it by hand in their own terminal doesn't have to remember to click Recheck. A one-shot
  // Timer that reschedules itself rather than `Timer.periodic`, so a slow recheck can't overlap with
  // the next tick.
  Timer? _environmentRecheckTimer;

  /// Whether a stuck step is being auto-polled right now — drives the "Checking automatically…"
  /// caption on [EnvironmentSetupScreen] alongside its Recheck button.
  bool get environmentRecheckPending => _environmentRecheckTimer != null;

  /// Whether a provisioning run (initial or a per-step recheck) is in flight — lets the setup
  /// screen disable its Recheck/Start over buttons and show a spinner instead of a second click
  /// racing the first.
  bool get environmentSetupInFlight => _environmentSetupInFlight;
  bool get environmentInstallRequested => _environmentInstallRequested;

  // --- Setup tour (onboarding redesign, 2026-10-08) -----------------------
  // A fresh computer whose setup installs with nobody at the keyboard sees a
  // tour of Harness instead of the install screen, with the install as one
  // line under it (`widgets/setup_tour.dart`). Everything else about setup is
  // unchanged; these three members are the whole of the tour's state here.
  bool _setupTour = false;

  /// Whether RootShell shows the setup tour in place of whatever [status]
  /// would show. Set when launch takes the unattended install path; cleared
  /// by [finishSetupTour] once the tour has opened Harness. It also gives way,
  /// for good, as soon as setup needs a person — a Terminal password, manual
  /// mode, or the method choice — because those are the existing setup
  /// screen's job.
  bool get setupTourShowing {
    if (_setupTour && _setupNeedsPerson(environmentReadiness)) {
      _setupTour = false;
    }
    return _setupTour;
  }

  static bool _setupNeedsPerson(EnvironmentReadiness readiness) =>
      readiness.mode == EnvironmentSetupMode.manual ||
      readiness.phase == EnvironmentSetupPhase.chooseMethod ||
      readiness.needsTerminal ||
      readiness.plan.any((item) => item.requiresTerminal);

  /// A computer new to Harness builds its first workspace behind the welcome tour, once signed in
  /// and ready, so one harness and its editable task are ready when the tour hands
  /// over: OpenCode's own first start took about 12 s after the tour had ended (fresh macOS VM,
  /// 2026-10-09). The workspace joins this run when it appears ([FirstArrival.run]).
  ///
  /// Off under test unless a test turns it on: its wait for the machine is a timer a widget test would
  /// find still pending.
  @visibleForTesting
  bool firstArrivalBehindTour = !kUnderTest;

  void _firstArrivalBehindTour() {
    if (!firstArrivalBehindTour ||
        viewer != null ||
        !signedIn ||
        // Behind the sign-in step as well: it stands where the tour stood.
        !(_setupTour || _signInStep) ||
        status != AppStatus.authenticated ||
        !firstArrival.pending) {
      return;
    }
    unawaited(firstArrival.run(this));
  }

  /// The tour has shown its last slide with everything done: show the app.
  void finishSetupTour() {
    if (!_setupTour) return;
    _setupTour = false;
    notifyListeners();
  }

  // --- Sign-in step (2026-10-11) ------------------------------------------
  // Desktop requires an account before opening the workspace, including on
  // computers that already have the CLI. The page stays until sign-in succeeds;
  // cancelling or restarting the app cannot bypass it. Explicit sign-out brings
  // it back, as does a session the server can no longer renew. A signed-in
  // offline launch needs no new sign-in. Design:
  // `docs/research/2026-10-08-onboarding-redesign/index.html`, section 1b.
  bool _signInStep = false;

  /// Whether the sign-in step comes after setup: this computer holds no
  /// account. Only meaningful once [status] has left
  /// setup — [signedIn] is presumed true until the CLI has been asked.
  bool get signInStepNext => _signInStep && viewer == null && !signedIn;

  /// Whether Harness was on this computer before this launch, so the sign-in
  /// page can say it is set up rather than look like a first run (Scholes's
  /// end-to-end test of 1.3.44, finding 5). False on the launch that first
  /// installed it, the tour's.
  bool get harnessSetUpBefore => !_firstHarnessLaunch;
  bool _firstHarnessLaunch = false;

  /// This computer as the sign-in page names it: its own row (the daemon's
  /// while signed out), else its host name, without Bonjour's `.local`.
  /// Null when neither is known. Only ever this computer's own name: no
  /// account, and no other machine.
  String? get thisComputerName {
    final row = localMachineState?.machine.name?.trim();
    final name = row != null && row.isNotEmpty ? row : localHostnameOrNull();
    if (name == null || name.isEmpty) return null;
    return superTabMachineName(name);
  }

  /// Whether RootShell shows the sign-in step in place of the workspace: from
  /// the moment setup (and its tour) hands over, until an account arrives.
  bool get signInStepShowing {
    if (!_signInStep || viewer != null || setupTourShowing) return false;
    final signingInHere = status == AppStatus.bootstrapping && signingIn;
    if (status != AppStatus.authenticated && !signingInHere) return false;
    // An account, from this page or from a terminal meanwhile: nothing to ask.
    // Held while the sign-in is still seating the desk, so the page does not
    // give way to a bare spinner for that moment.
    if (signedIn && !signingIn) {
      _signInStep = false;
      return false;
    }
    return true;
  }

  /// The sign-in step's buttons. Unlike the sign-in sheet, the page does not
  /// change while the browser is open, so every way in stays live: pressing
  /// one again opens the browser again, and another one switches to it.
  /// No [provider] is the sign-in page's own chooser — Email, GitHub or passkey.
  Future<void> signInFromStep([SignInProvider? provider]) async {
    if (signingIn) {
      // The same way in, pressed again: its page again, not a second sign-in
      // (the first one's browser tab would land on a listener that is gone).
      if (signInProvider == provider) {
        if (pendingAuthorizeUrl != null && !_loginAuthorized) {
          await openLoginBrowser();
        }
        return;
      }
      // Already approved in the browser: let it finish.
      if (!canCancelLogin) return;
      cancelLogin();
    }
    await login(provider);
  }

  /// What is still downloading beside setup (see [SetupDownloads]). The tour
  /// opens Harness only once this says done as well as setup. The agent
  /// downloads set `.value` here; nothing pending is the default, so a
  /// computer with nothing to download opens as soon as setup is finished.
  final ValueNotifier<SetupDownloads> setupDownloads = ValueNotifier(
    SetupDownloads.none,
  );

  /// How long OpenCode's download beside setup usually takes from its start (11–13 s on a fresh
  /// macOS VM, 2026-10-09). The tour counts down from it.
  @visibleForTesting
  static const agentDownloadsExpected = Duration(seconds: 15);

  /// The longest the tour waits for OpenCode, as long as a create waits ([agentPrefetchWait]).
  @visibleForTesting
  static const agentDownloadsCap = Duration(minutes: 10);

  Timer? _agentDownloadsTick;

  /// Feeds [setupDownloads] from [agentPrefetch] once it has started: pending at once, so the tour
  /// cannot open before OpenCode is in place, and done when OpenCode has settled or
  /// [agentDownloadsCap] passes. Codex and Claude Code go on downloading after the tour: their panes
  /// open at once and wait for them under the CLI's install line (`waitsForDownload`), which opens
  /// Harness 10–15 s sooner than waiting for all three (the owner, 2026-10-09: "boot into harness
  /// right away with 3 panes… downloading then jump into their default screen").
  void _publishAgentDownloads() {
    final prefetch = agentPrefetch;
    if (prefetch == null || !prefetch.started || _agentDownloadsTick != null) {
      return;
    }
    final began = DateTime.now();
    late final void Function() publish;
    void stop() {
      _agentDownloadsTick?.cancel();
      prefetch.progress.removeListener(publish);
    }

    publish = () {
      if (_disposed) return stop();
      final progress = prefetch.progress.value;
      final elapsed = DateTime.now().difference(began);
      final lines = [agentDownloadsLine(progress)];
      if (progress.finished ||
          progress.settled.contains('opencode') ||
          elapsed >= agentDownloadsCap) {
        stop();
        setupDownloads.value = SetupDownloads(lines: lines);
        return;
      }
      final left = agentDownloadsExpected - elapsed;
      // Past the usual time the tour says no number rather than a wrong one.
      setupDownloads.value = SetupDownloads.pending(
        left: left > Duration.zero ? left : null,
        lines: lines,
      );
    };
    prefetch.progress.addListener(publish);
    _agentDownloadsTick = Timer.periodic(
      const Duration(seconds: 1),
      (_) => publish(),
    );
    publish();
  }

  /// `Agents: OpenCode ✓ · Codex ✓ · Claude Code downloading`, for the tour's Details.
  @visibleForTesting
  static String agentDownloadsLine(AgentDownloads progress) {
    final parts = [
      for (final engine in const ['opencode', 'codex', 'claude'])
        '${engine == 'claude' ? 'Claude Code' : engineIdentity(engine).label} '
            '${progress.settled.contains(engine) ? '✓' : 'downloading'}',
    ];
    return 'Agents: ${parts.join(' · ')}';
  }

  // The daemon's own advertised local-ws endpoint — the dial target for EVERY machine's data plane
  // now, not just this computer's own one (see src/lib/remoteRelay.ts in the harness CLI repo: a
  // foreign machineId is relayed to backend transparently, so the app never dials backend directly).
  LocalCliEndpoint? _cliEndpoint;
  late final _localGitProjects = LocalGitProjects(
    onChanged: _applyLocalGitProjects,
  );

  AppStatus _status = AppStatus.bootstrapping;
  AppStatus get status => _status;
  set status(AppStatus value) {
    _status = value;
    // Device notices the log raised while the app was still starting are said now (and dropped for good
    // once the person is signed out).
    if (value == AppStatus.authenticated) _flushDeviceNotices();
    if (value == AppStatus.unauthenticated) _queuedDeviceNotices.clear();
  }

  CurrentUserProfile? _currentUser;
  CurrentUserProfile? get currentUser => _currentUser;
  set currentUser(CurrentUserProfile? profile) {
    if (_currentUser?.id != profile?.id) {
      // Initial identity loading may follow a restored Swarm; leaving a known
      // account must not reveal the feature to the next one.
      if (_currentUser != null) _superTabsEntered = false;
      _closeAttachmentSessions();
      _closeOwnerMemories();
      deviceHosts.clear();
      _deviceReads.clear();
      // Names and membership belong to the account that discovered them.
      _openedInRun.clear();
      _superTabNames = {};
    }
    _currentUser = profile;
    final id = profile?.id;
    superTabs.bind(id);
    experimentalFeatures.bind(
      id,
      transport: id == null ? null : _experimentTransport,
    );
  }

  late final experimentalFeatures = ExperimentalFeaturesStore(
    pollInterval: kUnderTest
        ? Duration.zero
        : ExperimentalFeaturesStore.safetyNet,
    seen: inSight,
  );
  final ExperimentalSettingsTransport? experimentalSettingsTransport;
  ApiClient? _experimentApi;
  ExperimentalSettingsTransport? _apiExperimentTransport;
  ExperimentalSettingsTransport? get _experimentTransport {
    if (experimentalSettingsTransport != null) {
      return experimentalSettingsTransport;
    }
    if (kUnderTest) return null;
    if (!identical(_experimentApi, api)) {
      _experimentApi = api;
      _apiExperimentTransport = ApiExperimentalSettingsTransport(api);
    }
    return _apiExperimentTransport;
  }

  List<Machine> machines = [];

  /// Machines other accounts share with this one's domain, not added yet: Add machine lists them, and
  /// [addSharedMachine] adds one.
  List<Machine> machinesToAdd = const [];

  /// Machines another account shared with this one and no longer does, by id: what a pane left on one
  /// says once the machine itself has left the list. Forgotten when it is shared again.
  final Map<String, ({String name, String owner})> _sharingEnded = {};

  /// Who stopped sharing [machineId] with this account, and its name, if they did.
  ({String name, String owner})? sharingEnded(String machineId) =>
      _sharingEnded[machineId];

  /// The "stopped sharing" message [lastError] shows, and for which machine: taken down once that
  /// machine is shared again, rather than left saying something no longer true.
  ({String machineId, String text})? _sharingEndedError;

  void _noteSharingEnded(Machine machine) {
    final share = machine.machineShare;
    if (share == null) return;
    _sharingEnded[machine.machineId] = (
      name: machine.displayName,
      owner: share.owner,
    );
  }

  final Map<String, MachineState> machineStates = {};
  final Set<String> expandedMachines = {};
  String? selectedMachineId;

  /// Swarms own arrangements; a shared pane owns one live terminal controller.
  final List<Swarm> swarms = [Swarm(id: 'swarm-1')];

  /// null shows every machine's tabs. A machine id shows only tabs whose
  /// agents all live on that computer. The account desk is not rewritten:
  /// the other computers' tabs stay, they are just not drawn here.
  String? _machineProfileId;
  String? get machineProfileId => _machineProfileId;
  List<Swarm> get profileSwarms =>
      swarmsForMachineProfile(swarms, _machineProfileId);

  // ── the desk: the account's tabs, the same on every computer ─────────────
  //
  // `desk_sync.dart` has the shape and the rules; this is the window's half.
  // Every layout change funnels through [_persistLayout], which diffs the
  // desk-shaped projection of `swarms` against what the desk last agreed to
  // and sends the difference as ops. A `desk_changed` push (backend → daemon →
  // here) or the 15 s poll fetches the document, and [_deskApply] reconciles
  // `swarms` to it — creating, closing, renaming and reordering tabs and their
  // panes, and touching nothing a window keeps for itself.
  final DeskSyncState _desk = DeskSyncState();
  Timer? _deskRetry;
  Future<void>? _deskJoining;
  @visibleForTesting
  DeskSyncState get deskSyncForTest => _desk;
  @visibleForTesting
  Future<void> deskStartForTest() => _deskStart(_authRevision);
  @visibleForTesting
  Future<void> deskFetchForTest() => _deskFetch();
  @visibleForTesting
  Future<void> deskFlushForTest() => _deskFlush();
  @visibleForTesting
  void persistLayoutForTest() => _persistLayout();
  String _activeSwarmId = 'swarm-1';
  int _nextSwarmId = 2;
  // No tab cap, as in Chrome: only the visible tab's panes are built, so a background tab costs its
  // terminal streams and nothing else — its web panes are unloaded until it is shown again.
  static const maxClosedSwarms = 24;
  final List<ClosedWork> _closedHistory = [];
  // The monitor follows user-visible panes, never the daemon's entire process
  // inventory. Keep identities after a pane is minimized, paused or closed.
  final _monitorHarnesses = <(String, String)>{};
  bool hasOpenedHarness(String machineId, String agentId) =>
      _monitorHarnesses.contains((machineId, agentId));

  /// Record pane intent, never daemon discovery. Saved with the existing layout.
  void rememberOpenedHarness(String machineId, String agentId) {
    if (machineId.isEmpty || agentId.isEmpty) return;
    final identity = (machineId, agentId);
    _monitorHarnesses.remove(identity);
    _monitorHarnesses.add(identity);
    if (_monitorHarnesses.length > 4096) {
      _monitorHarnesses.remove(_monitorHarnesses.first);
    }
  }

  int _nextClosedHistoryId = 1;
  List<ClosedWork> get closedHistory =>
      List.unmodifiable(_closedHistory.reversed);
  List<ClosedSwarm> get closedSwarms =>
      List.unmodifiable(_closedHistory.reversed.whereType<ClosedSwarm>());
  bool get canReopenClosedSwarm {
    final saved = _closedHistory.whereType<ClosedSwarm>().lastOrNull;
    return saved != null && _canReopenSwarm(saved);
  }

  bool get canReopenLastClosed =>
      _closedHistory.isNotEmpty &&
      canReopenClosed(_closedHistory.last.historyId);

  bool canReopenClosed(String historyId) {
    if (_disposed) return false;
    final entry = _closedHistory
        .where((entry) => entry.historyId == historyId)
        .firstOrNull;
    if (entry is ClosedSwarm) return _canReopenSwarm(entry);
    if (entry is! ClosedAgent) return false;
    final target = swarms.where((s) => s.id == entry.swarmId).firstOrNull;
    return target == null ||
        target.panes.length < maxPanes ||
        target.panes.any(
          (p) => p.machineId == entry.machineId && p.agentId == entry.agentId,
        );
  }

  bool _canReopenSwarm(ClosedSwarm saved) {
    if (_disposed) return false;
    if (saved.kind == 'devices' && !devicesEnabled) return false;
    final target = swarms.where((swarm) => swarm.id == saved.id).firstOrNull;
    if (target == null) return true;
    final present = {
      for (final pane in target.panes) (pane.machineId, pane.agentId),
    };
    final missing = {
      for (final pane in saved.panes)
        if (!present.contains((pane.machineId, pane.agentId)))
          (pane.machineId, pane.agentId),
    };
    return target.panes.length + missing.length <= maxPanes;
  }

  void _rememberClosed(ClosedWork entry) {
    if (entry is ClosedAgent) {
      rememberOpenedHarness(entry.machineId, entry.agentId);
    } else if (entry is ClosedSwarm) {
      for (final pane in entry.panes) {
        if (pane.agentId case final id?) {
          rememberOpenedHarness(pane.machineId, id);
        }
      }
    }
    // An unused starter has no work to recover. This also covers empty pages
    // restored from builds that did not mark them as drafts.
    if (entry is ClosedSwarm &&
        Swarm.normalizeName(entry.name) == Swarm.defaultName &&
        entry.panes.isEmpty &&
        entry.presets.isEmpty) {
      return;
    }
    _closedHistory.add(entry);
    if (_closedHistory.length > maxClosedSwarms) _closedHistory.removeAt(0);
  }

  Swarm get activeSwarm => swarms.firstWhere(
    (s) => s.id == _activeSwarmId,
    orElse: () => swarms.first,
  );
  List<TerminalPane> get panes => activeSwarm.panes;
  Set<TerminalPane> get allPanes => swarms.expand((s) => s.panes).toSet();
  String get activeSwarmId => activeSwarm.id;

  /// Agent Messages (docs/design/2026-10-10-agent-messages.md): whether the
  /// account has them, the traffic the daemons push as `messages_changed`, and
  /// the marks it leaves on panes. Its own notifier, so traffic never rebuilds
  /// the workspace. Whether agents may message is the account's experiment
  /// (Settings ▸ Experimental), not a tab's.
  late final agentMessages = AgentMessagesController(
    read: () => api.readAgentMessageTabs(),
    request: (machineId, payload) => _conn(machineId).request(
      'agent_messages',
      payload: payload,
      timeout: const Duration(seconds: 8),
    ),
    nameOf: (machineId, agentId) =>
        stateOf(machineId)?.agents
            .where((agent) => agent.id == agentId)
            .firstOrNull
            ?.displayName,
    // A member's shared tab: its desk id is derived from the shared tab id
    // the daemons file it under (R1).
    logTabsOf: (deskTabId) => sharedTabs.agentMessagesTabIds(deskTabId),
    deskTabOf: deskTabIdForMessages,
  );

  /// Tabs shared with other accounts, as this computer's daemon holds them
  /// (1c). On the web one of the account's own machines answers (R5): window
  /// frames reach only a computer's own windows, so the browser reads on open,
  /// after its actions and every 60 s in front.
  late final sharedTabs = SharedTabsController(
    measurement: productMeasurement,
    request: (payload) {
      final target = sharedTabsTarget;
      if (target == null) {
        return Future.error(
          WsRequestFailure(
            responseType: 'agent_messages_result',
            code: 'MACHINE_AWAY',
            detail: _teamComputer
                ? teamComputerSwarmMessage
                : 'No computer of yours is online.',
          ),
        );
      }
      try {
        return _conn(target.machine.machineId).request(
          'agent_messages',
          payload: payload,
          timeout: const Duration(seconds: 8),
        );
      } catch (error) {
        return Future.error(error);
      }
    },
    foreground: foreground,
    onActivity: applySharedActivity,
    // Off (the account default), every daemon refuses `shares`: not asked.
    messagesSwitch: ExperimentChoice(
      experimentalFeatures,
      ExperimentalFeature.agentMessages,
    ),
  );

  /// `tab_activity` on the computer [sharedTabs] asks: every harness of a desk
  /// tab with its state and summary.
  late final tabActivity = TabActivityReader(request: sharedTabs.request);

  /// Natively, this computer switched to a Harness Team account (`harness team
  /// on`): its daemon signs in as the team, which the server never lets act as
  /// the person, so none of the person's Swarm requests, files or profile
  /// pictures go out here.
  bool get _teamComputer =>
      viewer == null && localMachineState?.machine.isTeamAccount == true;

  /// What the person is told when [_teamComputer] stops a Swarm request.
  static const teamComputerSwarmMessage =
      'This computer runs Swarm agents for a Harness Team account, so it '
      'cannot send your own Swarm messages. Open Swarm on another of your '
      'machines.';

  /// The machine [sharedTabs] asks: this computer natively; on the web one of
  /// the account's own online machines, never a shared one. Never a Harness
  /// Team account's, here either (a computer switched with `harness team on`):
  /// its daemon relays under a team sign-in, which the server refuses to let
  /// speak as the person ("A team sign-in can only run Swarm agents on its own
  /// machine", every Buddy-chat post from a phone, 10-29), so nothing is sent.
  MachineState? get sharedTabsTarget {
    if (viewer == null) {
      final here = localMachineState;
      return here == null || here.machine.isTeamAccount ? null : here;
    }
    bool asks(MachineState machine) =>
        !machine.belongsToOtherAccount &&
        !machine.machine.isTeamAccount &&
        !machine.isOffline;
    final owned = ownedActionMachine;
    if (owned != null && asks(owned)) return owned;
    MachineState? best;
    for (final machine in machineStates.values) {
      if (!asks(machine)) continue;
      if (machine.connectionStatus != ConnectionStatus.connected) continue;
      if (best == null ||
          machine.machine.machineId.compareTo(best.machine.machineId) < 0) {
        best = machine;
      }
    }
    return best;
  }

  /// What a host keeps of the account on this device beside the Super Tab
  /// views; Settings ▸ Account's Clear now clears it with them.
  final browserCopies = BrowserCopies();

  late final SuperTabClient superTabs = SuperTabClient(
    storage: localStore ?? HarnessFileStore.shared,
    viewStorage: swarmViewStore(beside: localStore),
    upload:
        ({
          required tabId,
          required conversationId,
          required name,
          required mime,
          required file,
          required cancel,
          required onProgress,
        }) => _teamComputer
        ? Future.error(
            const SuperTabFailure(
              'MACHINE_UNAVAILABLE',
              teamComputerSwarmMessage,
            ),
          )
        : uploadWith(() => api)(
            tabId: tabId,
            conversationId: conversationId,
            name: name,
            mime: mime,
            file: file,
            cancel: cancel,
            onProgress: onProgress,
          ),
    avatarUpload: ({required tabId, required png}) => _teamComputer
        ? Future.error(
            const SuperTabFailure(
              'MACHINE_UNAVAILABLE',
              teamComputerSwarmMessage,
            ),
          )
        : uploadAvatarWith(() => api)(tabId: tabId, png: png),
    onMention: superTabMentionNotice(systemNotifications),
    onChatMessage: superTabChatNotice(systemNotifications),
    onReply: superTabReplyNotice(systemNotifications),
    onReminder: superTabReminderNotice(systemNotifications),
    onTagCounts: notifyListeners,
    onNotices: notifyListeners,
    discoveryInterval: kUnderTest ? Duration.zero : const Duration(seconds: 15),
    onTabs: (tabs, hidden) {
      // Discovery can finish while an already signed-in machine is re-seating
      // its saved desk, too. Publishing a SuperTab then advances the layout
      // revision and replaces regular tabs before their restore can finish.
      if (_disposed ||
          status != AppStatus.authenticated ||
          _paneLayoutRestores != 0 ||
          _workspaceCleanup != null ||
          !_superTabsEntered ||
          currentUser?.id == null) {
        return;
      }
      // However the person joined, this computer is added once to each Swarm
      // new here (task #3160).
      _addMachineWhereNew(
        [for (final tab in tabs) tab.id],
        {
          for (final swarm in swarms) ?swarm.superTabId,
          ...hidden,
        }.difference(_openedInRun),
      );
      var changed = false;
      // Membership and names for the closed list: a tab hidden before a
      // restart has no open view to take its name from.
      final names = {for (final tab in tabs) tab.id: tab.name};
      final namesChanged = !mapEquals(names, _superTabNames);
      _superTabNames = names;
      for (final tab in tabs) {
        final existing = swarms
            .where((s) => s.superTabId == tab.id)
            .firstOrNull;
        if (existing != null) {
          if (existing.name != tab.name || !existing.nameIsCustom) {
            existing.name = tab.name;
            existing.nameIsCustom = true;
            changed = true;
          }
        } else if (!hidden.contains(tab.id)) {
          _openedInRun.add(tab.id);
          swarms.add(
            Swarm(
              id: newDeskId(),
              name: tab.name,
              nameIsCustom: true,
              kind: 'superTab',
            )..superTabId = tab.id,
          );
          changed = true;
        }
      }
      if (changed) _persistLayout();
      // The closed list is read from these names, so it can change on its own.
      if (changed || namesChanged) notifyListeners();
    },
    onSelection: (controller) {
      if (_disposed || controller.accountId != currentUser?.id) return;
      // The Harness Pro shows the open project's Leads, so a project change
      // is a change to the desk it was told about.
      _announceOpenPanesToDial();
    },
    onSnapshot: (controller) {
      if (_disposed ||
          _paneLayoutRestores != 0 ||
          _workspaceCleanup != null ||
          controller.accountId != currentUser?.id) {
        return;
      }
      // Only when this Swarm's agents or their names changed: a message in it
      // is not a reason to look (review of #3021).
      if (superTabs.agentNamesChanged(controller.tabId)) {
        _syncChosenNames(tabId: controller.tabId);
      }
      var shown = false;
      for (final tab in swarms.where((s) => s.superTabId == controller.tabId)) {
        if (tab.name != controller.snapshot!.name || !tab.nameIsCustom) {
          tab.name = controller.snapshot!.name;
          tab.nameIsCustom = true;
          shown = true;
        }
      }
      if (shown) _persistLayout();
      // The dial is told the project open in a Swarm tab only once the Swarm
      // has loaded: a tab shown (or restored) before that went out with no
      // project, and nothing told the dial again, so it stayed on an empty
      // tab (Diego, 2026-10-28). Said again when that project changes, not on
      // every read.
      if (_dialProjects.containsKey(controller.tabId) &&
          _dialProjects[controller.tabId] != _dialProject(controller)) {
        _announceOpenPanesToDial();
      }
      notifyListeners();
    },
    transport: (method, path, {body}) async {
      // The web asks the backend itself, signed as the person in this
      // browser (docs/specs/2026-10-30-web-swarm-direct.md): no machine of
      // theirs needs to be online, a Team machine or a slow link in between.
      if (viewer != null) return _webSuperTabRequest(method, path, body: body);
      final target = sharedTabsTarget;
      if (target == null) {
        if (_teamComputer) {
          throw const SuperTabFailure(
            'MACHINE_UNAVAILABLE',
            teamComputerSwarmMessage,
            settled: true,
          );
        }
        throw const SuperTabFailure(
          'MACHINE_UNAVAILABLE',
          'Connect one of your machines to open Swarm.',
        );
      }
      final result = await superTabMachineRequest(target.machine.machineId, {
        'action': 'backend',
        'method': method,
        'path': path,
        'body': ?body,
      });
      return result['value'];
    },
  );

  late final SuperTabTransport _webSuperTabs = superTabBackendTransport(
    () => api,
  );

  /// A backend from before projects refuses `project.create` by its schema:
  /// the person is told it needs an update, not the schema's words.
  static SuperTabFailure? _tooOldForProjects(
    Object? body,
    String code,
    String? detail,
    int status,
  ) {
    final command = body is Map ? body['command'] : null;
    if (command is! Map ||
        command['type'] != 'project.create' ||
        code != 'VALIDATION_ERROR' ||
        detail?.contains('command.type') != true ||
        detail?.contains('discriminator') != true) {
      return null;
    }
    return SuperTabFailure(
      'UPDATE_REQUIRED',
      'The Swarm service needs an update before you can create a project. Your draft is saved.',
      statusCode: status,
    );
  }

  /// One Swarm call from the web, straight to the backend. An answer, or a
  /// refusal, that lands after the account changed is dropped, as a relayed
  /// one is ([superTabMachineRequest]).
  Future<Object?> _webSuperTabRequest(
    String method,
    String path, {
    Map<String, dynamic>? body,
  }) async {
    final revision = _authRevision;
    const changed = SuperTabFailure('ACCOUNT_CHANGED', 'The account changed.');
    final Object? value;
    try {
      value = await _webSuperTabs(method, path, body: body);
    } on SuperTabFailure catch (failure) {
      if (!_authWorkCurrent(revision)) throw changed;
      throw _tooOldForProjects(
            body,
            failure.code,
            failure.message,
            failure.statusCode,
          ) ??
          failure;
    }
    if (!_authWorkCurrent(revision)) throw changed;
    return value;
  }

  Map<String, String> _superTabNames = {};
  bool _superTabsEntered = false;

  /// Whether a machine could serve Swarm reads at the last connection change.
  bool _superTabsServed = false;

  /// Membership alone must not reveal the hidden feature in a regular workspace.
  /// The hidden shortcut, an explicit open, or a restored Swarm supplies that intent.
  void enterSuperTabs() => _superTabsEntered = true;

  final StreamController<String> _superTabClosures =
      StreamController<String>.broadcast();

  /// Closing a Swarm only hides it here, which looks like losing it. Each
  /// closure announces its history id so the screen can offer to reopen it.
  Stream<String> get superTabClosures => _superTabClosures.stream;

  /// The name of Swarm [tabId] if this account belongs to it, open here or
  /// not; null for one it is not in.
  String? superTabName(String tabId) =>
      swarms.where((s) => s.superTabId == tabId).firstOrNull?.name ??
      _superTabNames[tabId];

  /// Swarms hidden on this computer that the account still belongs to,
  /// by name. Saved with the hidden set, so a restart keeps them.
  List<({String id, String name})> get closedSuperTabs {
    final open = {for (final s in swarms) s.superTabId};
    return [
      for (final id in superTabs.hiddenIds)
        if (!open.contains(id) && _superTabNames.containsKey(id))
          (
            id: id,
            name: _superTabNames[id]!.trim().isEmpty
                ? 'Swarm'
                : _superTabNames[id]!,
          ),
    ]..sort((a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase()));
  }

  Future<Map<String, dynamic>> superTabMachineRequest(
    String machineId,
    Map<String, dynamic> payload,
  ) async {
    final revision = _authRevision;
    SuperTabFailure refusal(String code, String? detail, int status) {
      if (!_authWorkCurrent(revision)) {
        return const SuperTabFailure('ACCOUNT_CHANGED', 'The account changed.');
      }
      if (payload['action'] == 'backend') {
        final old = _tooOldForProjects(payload['body'], code, detail, status);
        if (old != null) return old;
      }
      return SuperTabFailure(
        code,
        detail ?? 'Could not reach this Swarm.',
        statusCode: status,
      );
    }

    // On the web only what acts on a machine comes here (adding it, sharing
    // its terminal, waking it): one that cannot do it says why, never the
    // catch-all (docs/specs/2026-10-30-web-swarm-direct.md).
    final machine = viewer == null ? null : machineStates[machineId];
    final name = machine?.machine.displayName;
    if (machine != null && machine.isOffline) {
      throw SuperTabFailure(
        'MACHINE_UNAVAILABLE',
        '$name is offline. Open Harness on it, then try again.',
      );
    }
    if (machine != null && machine.machine.isTeamAccount) {
      throw SuperTabFailure(
        'MACHINE_UNAVAILABLE',
        '$name runs Swarm agents for a Harness Team account, so it cannot do '
            'this for you. Use another of your machines.',
      );
    }
    final Map<String, dynamic> result;
    try {
      result = await _conn(machineId).request(
        'super_tabs',
        payload: payload,
        timeout: const Duration(seconds: 30),
      );
    } on WsRequestFailure catch (failure) {
      throw refusal(
        failure.code,
        failure.detail,
        (failure.payload['status'] as num?)?.toInt() ?? 0,
      );
    } on WsRequestTimeout {
      if (machine == null) rethrow;
      if (!_authWorkCurrent(revision)) {
        throw const SuperTabFailure('ACCOUNT_CHANGED', 'The account changed.');
      }
      throw SuperTabFailure(
        'MACHINE_SLOW',
        '$name is taking too long to answer. Its connection may be slow. '
            'Try again.',
      );
    }
    if (!_authWorkCurrent(revision)) {
      throw const SuperTabFailure('ACCOUNT_CHANGED', 'The account changed.');
    }
    if (result['error'] != null) {
      throw refusal(
        result['error'].toString(),
        result['detail'] as String?,
        (result['status'] as num?)?.toInt() ?? 0,
      );
    }
    return result;
  }

  /// Whether this computer's system can have a Harness Team account, for
  /// its join status. Off under test, on a Mac too, unless a test sets it.
  @visibleForTesting
  bool? teamAccountHereForTest;

  /// The systems a Harness Team account was made on, by
  /// [RuntimePlatform.operatingSystem]: a Mac, Linux and Windows
  /// (cli/src/team/layout.ts; Windows' daemon sets it up behind User Account
  /// Control); never a phone, a tablet or a browser.
  static bool teamAccountOn(String operatingSystem) =>
      const {'macos', 'linux', 'windows'}.contains(operatingSystem);

  bool get _teamAccountSystem =>
      teamAccountHereForTest ??
      (teamAccountOn(RuntimePlatform.operatingSystem) && !kUnderTest);

  /// This computer's own machine, when it can have a Harness Team account:
  /// never a machine shared with this account.
  String? _teamAccountHere() {
    if (!_teamAccountSystem) return null;
    return machineStates.values
        .where(
          (state) => state.isLocalMachine && !state.machine.isSharedMachine,
        )
        .firstOrNull
        ?.machine
        .machineId;
  }

  /// Why this Mac's Harness Team account, signed in, has not joined a Swarm
  /// yet (cli superTabs/service.ts `teamJoinStatus`, #3215): [failure], the
  /// last refusal or error of this Mac's join, and [hostRunning], whether this
  /// Mac's Swarm work runs at all. Null when it cannot say (a daemon too old).
  Future<({String? failure, bool hostRunning})?> teamJoinStatus() async {
    final here = _teamAccountHere();
    if (here == null) return null;
    try {
      final answer = await superTabMachineRequest(here, {
        'action': 'teamJoinStatus',
      });
      final failure = answer['failure'];
      final running = answer['hostRunning'];
      if (running is! bool) return null;
      return (
        failure: failure is String ? failure : null,
        hostRunning: running,
      );
    } catch (error) {
      appLog.debug('super-tabs', 'team join status not read: $error');
      return null;
    }
  }

  /// Retry on this Mac's row: its Swarm work starts if it never ran, and the
  /// Team account's join is tried at once (cli superTabs/service.ts).
  Future<void> retryTeamJoin() async {
    final here = _teamAccountHere();
    if (here == null) return;
    try {
      await superTabMachineRequest(here, {'action': 'teamJoinRetry'});
    } catch (error) {
      appLog.debug('super-tabs', 'team join retry not sent: $error');
    }
  }

  final _joinAdding = <String>{};

  /// The Swarms the join's add already ran or was decided for, per account on
  /// this computer (super_tabs/join_seen.dart). Null without a local store:
  /// nothing is added that could not be remembered.
  SwarmJoinSeen? get _joinRecord {
    final store = localStore;
    if (store == null) return null;
    if (!identical(store, _joinSeen?.store)) _joinSeen = SwarmJoinSeen(store);
    return _joinSeen;
  }

  SwarmJoinSeen? _joinSeen;
  Future<void>? _joinPass;

  /// Swarms tried in this run where the person is not known to be a
  /// collaborator or owner (a viewer, not listed yet, or a Swarm that could
  /// not be read): tried again at the next launch, never on every discovery
  /// (review of #3115).
  final _joinPassed = <String>{};

  /// The Swarms that became open on this computer during this run: joined in
  /// the dialog, opened by the person, or added by discovery. The update's
  /// baseline ([SwarmJoinSeen.fresh]) takes the Swarms a long-time member had
  /// open or hidden here as seen, never these: a new member's Swarm is open
  /// by the time the first pass that can add runs (this computer's own row,
  /// or Swarm mode, was not ready at sign-in), and counting it with the ones
  /// they had skipped the add and the account choice (task #3791). A Swarm the
  /// person had hidden and reopens stays known.
  final _openedInRun = <String>{};

  /// The pass discovery started last, for tests to wait on.
  @visibleForTesting
  Future<void> get joinAddPassForTest => _joinPass ?? Future.value();

  /// Joins awaiting the local person's choice, including ones discovered
  /// before the Desktop host has mounted. Each expires after 15 minutes.
  final _joinAccountRequests = <SwarmJoinAccountRequest>[];
  SwarmJoinAccountRequest? get joinAccountRequest =>
      _joinAccountRequests.where((r) => !r.answered).firstOrNull;

  /// Offers a new collaborator their Buddy after a successful membership join.
  /// Existing members and viewers never enter the bring-agent flow here.
  Future<void> addMachineOnJoin(
    String tabId, {
    required String role,
    bool alreadyMember = false,
  }) async {
    if (alreadyMember || role != 'collaborator') return;
    await _offerBringAgent(tabId);
  }

  /// Swarm discovery's list ([listed]), however each was joined: a domain
  /// auto-join, a Workspace-open join, a join on the phone or the web
  /// (Scholes, 2026-11-05, task #3160). The join's add runs once for each
  /// Swarm new here; [knownHere], the Swarms open or hidden on this computer,
  /// are taken as seen the first time, even by a pass that cannot add yet
  /// (this computer's own row not known). One pass at a time: a discovery
  /// while one runs leaves its list to the next.
  void _addMachineWhereNew(List<String> listed, Set<String> knownHere) {
    final record = _joinRecord;
    final account = currentUser?.id;
    if (_joinPass != null || record == null || account == null) return;
    _joinPass = () async {
      try {
        final fresh = await record.fresh(account, listed, knownHere: knownHere);
        for (final tabId in fresh) {
          if (_disposed || currentUser?.id != account) {
            return;
          }
          if (_joinPassed.contains('$account/$tabId')) continue;
          // Discovery already knows the owner; only new collaborators need
          // the offer, without opening an owner's other Swarms to find out.
          if (superTabs.ownerOf(tabId) == account) {
            _joinPassed.add('$account/$tabId');
            continue;
          }
          await _offerBringAgent(tabId);
        }
      } catch (error) {
        appLog.info('super-tabs', 'joined Swarms not checked: $error');
      } finally {
        _joinPass = null;
      }
    }();
  }

  /// Offers the new collaborator their own Buddy on this computer. Discovery
  /// remembers the offer so reconnects do not reopen a dismissed prompt.
  Future<void> _offerBringAgent(String tabId) async {
    final accountId = currentUser?.id;
    if (accountId == null || !_joinAdding.add(tabId)) return;
    bool current() =>
        !_disposed &&
        status == AppStatus.authenticated &&
        currentUser?.id == accountId;
    final openedHere = superTabs.peek(tabId) == null;
    try {
      final c = await superTabs.open(tabId);
      if (!current()) return;
      // Reuse the state already read for an open Swarm. Discovery must not
      // add a second read when the connection comes back.
      if (c.snapshot == null) await c.refresh();
      if (!current()) return;
      final snapshot = c.snapshot;
      if (snapshot == null) {
        appLog.info('super-tabs', 'bring-agent join deferred: org unreadable');
        return;
      }
      final role = snapshot.people
          .where((p) => p.id == accountId)
          .firstOrNull
          ?.role;
      if (role != 'collaborator') {
        _joinPassed.add('$accountId/$tabId');
        return;
      }
      await _joinRecord?.mark(accountId, tabId);
      if (!c.canWrite ||
          snapshot.agents.any(
            (agent) => agent.isMainBuddy && agent.buddyOf == accountId,
          )) {
        return;
      }
      final request = SwarmJoinAccountRequest(
        snapshot.name,
        accountId,
        tabId: tabId,
      );
      _joinAccountRequests.add(request);
      notifyListeners();
      try {
        await request.answer.timeout(
          const Duration(minutes: 15),
          onTimeout: () {
            appLog.info('super-tabs', 'bring-agent join prompt expired');
            return null;
          },
        );
      } finally {
        request.complete(null);
        _joinAccountRequests.remove(request);
        if (!_disposed) notifyListeners();
      }
    } catch (_) {
      appLog.info(
        'super-tabs',
        'bring-agent join deferred: org request failed',
      );
    } finally {
      _joinAdding.remove(tabId);
      if (openedHere &&
          !_disposed &&
          activeSwarm.superTabId != tabId &&
          superTabs.peek(tabId) != null) {
        superTabs.release(tabId);
      }
    }
  }

  Future<void> wakeSuperTabHost(String machineId) async {
    await superTabMachineRequest(machineId, {'action': 'wake'});
    // Share derives only the session views authorized by the tab. Its existing
    // observer protocol never exposes this machine's general command surface.
    await _conn(machineId).request('harness_share_rosters');
  }

  void bindSuperTab(String swarmId, String tabId, String name) {
    final swarm = swarms.where((s) => s.id == swarmId).firstOrNull;
    if (swarm == null) return;
    enterSuperTabs();
    // A discovery response can beat the creation response back to this
    // computer. Keep the lead form's tab and retain any already-open panes.
    for (final duplicate
        in swarms
            .where((s) => s.id != swarmId && s.superTabId == tabId)
            .toList()) {
      for (final pane in duplicate.panes) {
        if (!swarm.panes.contains(pane)) swarm.panes.add(pane);
      }
      if (_activeSwarmId == duplicate.id) _activeSwarmId = swarm.id;
      swarms.remove(duplicate);
    }
    swarm.kind = 'superTab';
    swarm.superTabId = tabId;
    swarm.name = name;
    swarm.nameIsCustom = true;
    swarm.isNewTabPage = false;
    // A tab bound here is one the person belongs to.
    _superTabNames[tabId] = name;
    _rememberSuperTabVisibility(tabId, true);
    _persistLayout();
    notifyListeners();
  }

  /// The one way to show a Swarm: focus its view if it is open, else give
  /// it one. An untouched New Tab page named by [intoSwarmId] becomes the view
  /// instead of being left behind. Any history entry for the tab is dropped, so
  /// Reopen later cannot add a second view.
  void openSuperTab(String tabId, String name, {String? intoSwarmId}) {
    enterSuperTabs();
    _noteOpenedInRun(tabId);
    _rememberSuperTabVisibility(tabId, true);
    _closedHistory.removeWhere(
      (entry) => entry is ClosedSwarm && entry.superTabId == tabId,
    );
    final existing = swarms.where((s) => s.superTabId == tabId).firstOrNull;
    if (existing != null) {
      selectSwarm(existing.id);
      return;
    }
    final page = swarms
        .where(
          (s) =>
              s.id == intoSwarmId &&
              s.panes.isEmpty &&
              (s.isNewTabPage || (s.isSuperTab && s.superTabId == null)),
        )
        .firstOrNull;
    if (page != null) {
      bindSuperTab(page.id, tabId, name);
      selectSwarm(page.id);
      return;
    }
    newSwarm(newTabPage: true);
    bindSuperTab(activeSwarmId, tabId, name);
  }

  /// Notes that Swarm [tabId] is about to open on this computer for the first
  /// time in this run ([_openedInRun]). Read before the visibility is saved:
  /// showing a Swarm clears its hidden state at once, and one the person had
  /// hidden and reopens is still one they had.
  void _noteOpenedInRun(String tabId) {
    if (!swarms.any((s) => s.superTabId == tabId) &&
        !superTabs.hiddenIds.contains(tabId)) {
      _openedInRun.add(tabId);
    }
  }

  /// Shows Swarm [tabId] in the Swarm tab [swarmId] in place of the Swarm it
  /// shows, from the Swarm dropdown: the tab keeps its place and its name
  /// follows. A Swarm already open in another tab is selected there instead,
  /// so no tab is added or closed. The Swarm the tab showed is hidden here as
  /// a closed one is, and let go, which keeps its draft for its return.
  void showSuperTabIn(String swarmId, String tabId, String name) {
    _noteOpenedInRun(tabId);
    final tab = swarms.where((s) => s.id == swarmId).firstOrNull;
    final previous = tab?.superTabId;
    if (tab == null || previous == null || previous == tabId) return;
    final open = swarms.where((s) => s.superTabId == tabId).firstOrNull;
    if (open != null) {
      selectSwarm(open.id);
      return;
    }
    // As openSuperTab: Reopen later must not add a second view of it.
    _closedHistory.removeWhere(
      (entry) => entry is ClosedSwarm && entry.superTabId == tabId,
    );
    _rememberSuperTabVisibility(previous, false);
    superTabs.release(previous);
    bindSuperTab(swarmId, tabId, name);
    selectSwarm(swarmId);
  }

  /// Opens a tab from [closedSuperTabs]. False when it is no longer listed
  /// (open already, or the account has left it).
  bool openClosedSuperTab(String tabId, {String? intoSwarmId}) {
    final closed = closedSuperTabs.where((tab) => tab.id == tabId).firstOrNull;
    if (closed == null) return false;
    openSuperTab(closed.id, closed.name, intoSwarmId: intoSwarmId);
    return true;
  }

  void _rememberSuperTabVisibility(String tabId, bool visible) {
    if (localStore == null) return;
    unawaited(
      superTabs.setTabVisible(tabId, visible).catchError((Object error) {
        appLog.warn('super-tab', 'Could not save tab visibility: $error');
      }),
    );
  }

  void markSuperTabDraft(String swarmId) {
    final swarm = swarms.where((s) => s.id == swarmId).firstOrNull;
    if (swarm == null) return;
    enterSuperTabs();
    swarm.kind = 'superTab';
    _persistLayout();
    notifyListeners();
  }

  /// Opening a recent harness uses the welcome page as an ordinary workspace.
  /// Consume only a successful open; a missing result leaves creation available.
  void finishSuperTabDraftNavigation(String swarmId) {
    final swarm = swarms.where((s) => s.id == swarmId).firstOrNull;
    if (swarm == null ||
        !swarm.isSuperTab ||
        swarm.superTabId != null ||
        swarm.panes.isEmpty) {
      return;
    }
    swarm.kind = 'harness';
    _persistLayout();
    notifyListeners();
  }

  Future<Agent> recoverSuperTabCreation(
    String machineId,
    String creationId, {
    bool cancelIfMissing = false,
  }) async {
    final revision = _authRevision, account = currentUser?.id;
    var result = await _conn(machineId).request(
      'agent_create_status',
      payload: {'creationId': creationId},
      timeout: const Duration(seconds: 10),
    );
    if (!_authWorkCurrent(revision) || currentUser?.id != account) {
      throw const SuperTabFailure('ACCOUNT_CHANGED', 'The account changed.');
    }
    // Older Swarm bootstraps exceeded the native prompt limit, which rejects
    // before writing a receipt. Fence that exact missing intent durably before
    // allowing a retry; an uncertain/mismatched response must stay locked.
    if (cancelIfMissing &&
        result['creationId'] == creationId &&
        result['state'] == 'missing') {
      result = await _conn(machineId).request(
        'agent_create_cancel',
        payload: {'creationId': creationId},
        timeout: const Duration(seconds: 10),
      );
      if (!_authWorkCurrent(revision) || currentUser?.id != account) {
        throw const SuperTabFailure('ACCOUNT_CHANGED', 'The account changed.');
      }
    }
    if (cancelIfMissing &&
        result['creationId'] == creationId &&
        result['state'] == 'cancelled') {
      throw const SuperTabFailure(
        'CREATION_FAILED',
        'The previous startup request was cancelled. Try again to start this project.',
      );
    }
    if (result['creationId'] == creationId && result['state'] == 'failed') {
      final failure = result['failure'] is Map
          ? result['failure'] as Map
          : const {};
      throw SuperTabFailure(
        'CREATION_FAILED',
        failure['detail'] as String? ?? result['error'] as String? ?? 'The machine could not start this harness. You can change its settings and try again.',
      );
    }
    // Nothing will start for these either: a cancel that went through (its
    // journal delete did not), or a harness that started and stopped again.
    // Read as pending, Check status repeated "not started yet" forever.
    if (result['creationId'] == creationId && result['state'] == 'cancelled') {
      throw const SuperTabFailure(
        'CREATION_FAILED',
        'This startup request was cancelled. Try again to start this project.',
      );
    }
    // Its own code, so the request that started it can say what to do (hotfix #4709).
    if (result['creationId'] == creationId &&
        result['state'] == 'unavailable') {
      throw const SuperTabFailure(
        'CREATION_STOPPED',
        'The harness started and then stopped. Start it again.',
      );
    }
    if (result['creationId'] != creationId ||
        result['state'] != 'created' ||
        result['agent'] is! Map) {
      throw const SuperTabFailure(
        'CREATION_PENDING',
        'The machine has not confirmed this launch. Check status before starting another agent.',
      );
    }
    return Agent.fromJson(Map<String, dynamic>.from(result['agent'] as Map));
  }

  /// Asks [machineId] to drop a Swarm launch's request. The reply is its
  /// receipt: `cancelled`, or what had already become of the request.
  Future<Map<String, dynamic>> cancelSuperTabCreation(
    String machineId,
    String creationId,
  ) async {
    final revision = _authRevision, account = currentUser?.id;
    final result = await _conn(machineId).request(
      'agent_create_cancel',
      payload: {'creationId': creationId},
      timeout: const Duration(seconds: 10),
    );
    if (!_authWorkCurrent(revision) || currentUser?.id != account) {
      throw const SuperTabFailure('ACCOUNT_CHANGED', 'The account changed.');
    }
    return result;
  }

  /// Where this computer keeps, per shared tab, the other accounts'
  /// harnesses it has seen in the roster (R2): `{sharedTabId: [paneKey]}`,
  /// one record per account, so one person's record on a shared computer
  /// never reads as another's closed tab.
  static String sharedTabsPlacedKey(String accountId) =>
      'shared_tabs.placed.$accountId';

  /// [sharedTabsPlacedKey] of [_sharedPlacedAccount] as last read or
  /// written; null until the first placement of this sign-in reads it.
  Map<String, Set<String>>? _sharedPlaced;
  String? _sharedPlacedAccount;
  bool _sharedPlacing = false, _sharedPlaceAgain = false;

  /// Machines a roster names that the inventory lacked (or had without the
  /// harness's grant) when placement or the desk wanted them: asked about
  /// once per roster read, so an absent grant is not a read loop.
  final _sharedRereadAsked = <String>{};

  void _sharedTabsChanged() {
    _sharedRereadAsked.clear();
    // A pane restored (or carried by the desk) before the roster was read,
    // whose machine this window does not know yet: the roster now says it is
    // another account's, so its machine is asked for (seam 2).
    for (final pane in allPanes) {
      if (pane.agentId != null && machineStates[pane.machineId] == null) {
        _bindShared(pane);
      }
    }
    _placeSharedPanesSoon();
  }

  void _placeSharedPanesSoon() => unawaited(_placeSharedPanes());

  /// Places other accounts' harnesses from the rosters this computer holds
  /// onto the desk, once each ([planSharedPlacement]; R1, R2): only while the
  /// desk is joined and the rosters are read. One run at a time; a call while
  /// one runs asks for one more after it.
  Future<void> _placeSharedPanes() async {
    if (_sharedPlacing) {
      _sharedPlaceAgain = true;
      return;
    }
    _sharedPlacing = true;
    try {
      do {
        _sharedPlaceAgain = false;
        await _placeSharedPanesOnce();
      } while (_sharedPlaceAgain && !_disposed);
    } finally {
      _sharedPlacing = false;
    }
  }

  Future<void> _placeSharedPanesOnce() async {
    if (_disposed ||
        !_desk.enabled ||
        workspaceEnabled?.call() == false ||
        sharedTabs.state != SharedTabsState.ready) {
      return;
    }
    final revision = _authRevision;
    final storage = _paneLayout?.storage;
    final account = sharedTabs.snapshot.me?.accountId;
    if (account == null) return;
    if (_sharedPlaced == null || _sharedPlacedAccount != account) {
      final loaded = <String, Set<String>>{};
      try {
        final raw = await storage?.read(sharedTabsPlacedKey(account));
        final json = raw == null ? null : jsonDecode(raw);
        if (json is Map) {
          for (final MapEntry(:key, :value) in json.entries) {
            if (key is String && value is List) {
              loaded[key] = {...value.whereType<String>()};
            }
          }
        }
      } catch (error) {
        appLog.warn('desk', 'shared tab placements unreadable: $error');
      }
      if (!_authWorkCurrent(revision)) return;
      if (_sharedPlaced == null || _sharedPlacedAccount != account) {
        _sharedPlaced = loaded;
        _sharedPlacedAccount = account;
      }
    }
    final snapshot = sharedTabs.snapshot;
    final me = snapshot.me?.accountId;
    if (me == null ||
        me != _sharedPlacedAccount ||
        !_desk.enabled ||
        sharedTabs.state != SharedTabsState.ready) {
      return;
    }
    // A member's desk tab is derived from the shared tab id (R1): only a
    // roster whose id has the shape the daemon accepts may make one.
    final tabs = snapshot.tabs
        .where((tab) => isSharedTabId(tab.sharedTabId))
        .toList();
    final deskTabs = swarms.where(_deskTracks).toList();
    final plan = planSharedPlacement(
      me: me,
      tabs: tabs,
      deskTabIds: {for (final tab in deskTabs) tab.id},
      deskPaneKeys: {
        for (final tab in deskTabs)
          for (final pane in tab.panes)
            if (pane.agentId != null) '${pane.machineId}\u0000${pane.agentId}',
      },
      seen: _sharedPlaced!,
    );
    final seen = plan.seen;
    for (final tab in plan.createTabs) {
      openSharedDeskTab(tab.id, tab.name);
    }
    final sharedTabFor = <String, String>{
      for (final tab in tabs) ?tab.deskTabId(me): tab.sharedTabId,
    };
    for (final add in plan.addPanes) {
      final machine = machineStates[add.machineId];
      final known =
          machine != null &&
          machine.agents.any((agent) => agent.id == add.agentId);
      final target = swarms.where((s) => s.id == add.deskTabId).firstOrNull;
      // The desk holds 9 harnesses a tab (`DESK_MAX_PANES`); the rest of a
      // shared tab is listed under People. Counted as [assignAgentToPane]
      // counts, so placement asks only for what it takes, and never sets an
      // error nobody asked for (final review of 1c, M1).
      final full =
          target != null &&
          (deskTabFull(target) || target.panes.length >= maxPanes);
      if (!known || target == null || full) {
        // Not placed, so not seen: tried again at the next inventory change
        // (or roster read), once the grant has reached this window or a pane
        // of the tab has gone.
        seen[sharedTabFor[add.deskTabId]]?.remove(
          '${add.machineId}\u0000${add.agentId}',
        );
        if (!known && _sharedRereadAsked.add(add.machineId)) {
          api.sharesChanged();
          unawaited(_rereadMachinesInBackground(pushed: true));
        }
        continue;
      }
      // Never `share_add` and never a person's intent: the roster already
      // lists it, and nobody at this window asked (C4 hooks the person's).
      // The pane goes in before the call's first wait, so whether it landed
      // is known at once.
      unawaited(
        assignAgentToPane(
          null,
          add.machineId,
          add.agentId,
          swarmId: add.deskTabId,
          focus: false,
          intent: AttachIntent.automatic,
        ),
      );
      if (!target.panes.any(
        (p) => p.machineId == add.machineId && p.agentId == add.agentId,
      )) {
        // Refused (the tab is full, the agent gone): not seen, so it is tried
        // again, as R2 says, rather than never placed.
        seen[sharedTabFor[add.deskTabId]]?.remove(
          '${add.machineId}\u0000${add.agentId}',
        );
      }
    }
    if (_sameSeen(_sharedPlaced!, seen)) return;
    _sharedPlaced = seen;
    try {
      await storage?.write(
        sharedTabsPlacedKey(account),
        jsonEncode({
          for (final MapEntry(:key, :value) in seen.entries)
            key: value.toList()..sort(),
        }),
      );
    } catch (error) {
      appLog.warn('desk', 'shared tab placements not saved: $error');
    }
  }

  /// Whether a shared desk tab holds all the harnesses the desk keeps a tab
  /// (`DESK_MAX_PANES`, [PaneLayoutStore.maxPanes]). The desk counts harness
  /// panes only (a viewer or an empty tile is not on it), so placement, a
  /// person's add and a move all count the same way (final review of 1c, M1).
  /// An unshared tab is held to [maxPanes] alone, as before.
  bool deskTabFull(Swarm swarm) =>
      sharedTabs.isShared(swarm.id) &&
      swarm.panes.where((p) => p.agentId != null).length >=
          PaneLayoutStore.maxPanes;

  static bool _sameSeen(
    Map<String, Set<String>> a,
    Map<String, Set<String>> b,
  ) {
    if (a.length != b.length) return false;
    for (final MapEntry(:key, :value) in a.entries) {
      final other = b[key];
      if (other == null ||
          other.length != value.length ||
          !other.containsAll(value)) {
        return false;
      }
    }
    return true;
  }

  /// A member's desk tab [id] (R1, derived from its shared tab's id by
  /// `memberDeskTabId`): a desk tab with that id,
  /// at the end of the row and not selected. The desk learns it through
  /// [_persistLayout] (`tab.create` takes the client's id, idempotently).
  /// [name] is another account's: it is made plain and fitted to the desk
  /// ([sharedDeskTabName]), since a name the desk refuses would fail every
  /// desk write queued with it.
  void openSharedDeskTab(String id, String name) {
    if (_disposed || swarms.any((s) => s.id == id)) return;
    swarms.add(
      Swarm(id: id, name: sharedDeskTabName(name) ?? Swarm.defaultName),
    );
    _persistLayout();
    notifyListeners();
  }

  /// The roster entry naming [agentId] on [machineId] under another account,
  /// in a shared tab this computer holds.
  ({SharedTab tab, SharedTabHarness harness})? _foreignRosterEntry(
    String machineId,
    String agentId,
  ) {
    final snapshot = sharedTabs.snapshot;
    final me = snapshot.me?.accountId;
    if (me == null) return null;
    for (final tab in snapshot.tabs) {
      for (final harness in tab.harnesses) {
        if (harness.accountId != me &&
            harness.machineId == machineId &&
            harness.agentId == agentId) {
          return (tab: tab, harness: harness);
        }
      }
    }
    return null;
  }

  /// Who a foreign pane waits for when its machine is not in this window's
  /// inventory yet (seam 3): the owner's name, else email, from the roster.
  /// Null when no roster this computer holds lists the harness.
  String? sharedWaitingName(String machineId, String agentId) {
    final entry = _foreignRosterEntry(machineId, agentId);
    if (entry == null) return null;
    final account = entry.harness.accountId;
    final member = entry.tab.members
        .where((m) => m.accountId == account)
        .firstOrNull;
    for (final candidate in [
      member?.name,
      member?.email,
      if (account == entry.tab.ownerAccountId) entry.tab.ownerEmail,
    ]) {
      final plain = plainSharedText(candidate ?? '');
      if (plain.isNotEmpty) return plain;
    }
    return 'Another account';
  }

  /// A pane on a shared machine is a Share pane at once (seam 2), as the
  /// inventory merge and [_attachSession] make it; a pane whose machine this
  /// window does not know yet, that a roster lists under another account,
  /// asks for the machine list once.
  void _bindShared(TerminalPane pane) {
    final agentId = pane.agentId;
    if (agentId == null) return;
    final machine = machineStates[pane.machineId];
    if (machine == null) {
      if (_foreignRosterEntry(pane.machineId, agentId) != null &&
          _sharedRereadAsked.add(pane.machineId)) {
        api.sharesChanged();
        unawaited(_rereadMachinesInBackground(pushed: true));
      }
      return;
    }
    if (!machine.machine.isShared) return;
    pane.sharedHarness =
        machine.machine.sharedHarnesses
            .where((g) => g.agentId == agentId)
            .firstOrNull ??
        pane.sharedHarness;
    pane.sharedOwnerName = machine.machine.ownerName;
  }

  /// Another account's harness in a shared tab started or stopped working
  /// (seam 1): its tab's status slot follows it, on the lease it was sent with.
  void applySharedActivity(SharedActivity a) {
    final machine = machineStates[a.machineId];
    // A machine another account shares whole counts too: a member's harness
    // can sit on it, and the roster names it by that machine's id.
    if (machine == null || !machine.belongsToOtherAccount) return;
    final applied = _applyReportedActivity(
      machine,
      a.agentId,
      // One epoch for every shared tab: the controller's revision already
      // grows across them, and an epoch per tab retired the first tab's for
      // good once a harness in two shared tabs was heard from the second
      // (final review of 1c, M2).
      AgentActivity(a.state, 'shared', a.revision, a.validForMs),
    );
    if (applied.changed) notifyListeners();
  }

  /// Whether a desk tab may be given a fresh desk id when its only agent ends
  /// (a Change agent, an engine that left its shell): never a shared tab,
  /// whose id the shared tab is found by — a member's (derived from its
  /// shared tab id, R1) or the one this account shares (`shares`' `tabId`).
  /// Re-minting the owner's would orphan its roster, and placement would read
  /// either as closed.
  /// Never either before the first `shares` answer after a launch: which tabs
  /// are shared is not known yet (final review of 1c, B3).
  bool _mayReidentify(Swarm swarm) =>
      isDeskId(swarm.id) &&
      sharedTabs.state != SharedTabsState.unknown &&
      !sharedTabs.isShared(swarm.id);

  /// Whether [tabId] has an Agent Messages log to show: a tab the desk holds,
  /// since the daemons know a tab by its desk id, once the daemon and backend
  /// have answered for Agent Messages. The Store, Devices and Companions, an
  /// orchestrator or a draft tab, a window before it joins the desk, and an
  /// older CLI or backend get no Show Agent Messages row or command.
  bool agentMessagesOffered(String tabId) {
    final swarm = swarms.where((s) => s.id == tabId).firstOrNull;
    return swarm != null &&
        _desk.enabled &&
        _deskTracks(swarm) &&
        isDeskId(swarm.id) &&
        agentMessages.loaded;
  }

  /// The account's Agent Messages switch (Settings ▸ Experimental, off by
  /// default), as the backend last answered it.
  bool get agentMessagesOn =>
      experimentalFeatures.enabled(ExperimentalFeature.agentMessages);

  /// Whether [tabId] offers what came with Tab Activity: the sidebar, Make
  /// Leader and the Leader chip, and an unshared tab's People and Tasks. The
  /// account's switch must be on, beside the support [agentMessagesOffered]
  /// checks: support alone showed all of it to every account with the switch
  /// off, the default (final review I1).
  bool tabActivityOffered(String tabId) =>
      agentMessagesOn && agentMessagesOffered(tabId);

  /// The machines of the owner's with a harness in [tabId], and this
  /// computer: every daemon that may hold part of the tab's log. A shared
  /// machine's harnesses never take part.
  Set<String> _agentMessageMembers(String tabId) {
    final tab = swarms.where((swarm) => swarm.id == tabId).firstOrNull;
    return {
      ?localMachineState?.machine.machineId,
      for (final pane in tab?.panes ?? const <TerminalPane>[])
        if (pane.agentId != null &&
            machineStates[pane.machineId]?.belongsToOtherAccount != true)
          pane.machineId,
    };
  }

  /// Of [_agentMessageMembers], those that can answer now.
  List<String> agentMessageMachines(String tabId) => [
    for (final id in _agentMessageMembers(tabId))
      if (machineStates[id] case final machine?
          when !machine.belongsToOtherAccount &&
              !machine.needsLink &&
              machine.nodeOnline != false &&
              machine.connectionStatus == ConnectionStatus.connected)
        id,
  ];

  /// [tabId]'s Agent Messages log, from every daemon that may hold part of it.
  Future<AgentMessageLog> readAgentMessages(String tabId) =>
      agentMessages.history(
        tabId,
        agentMessageMachines(tabId),
        expected: _agentMessageMembers(tabId),
      );

  /// The desk tabs with two or more of the owner's harnesses — the fewest
  /// that can message each other — each with its connected machines other
  /// than this computer: their daemons' `messages_changed` reaches only their
  /// own computer's windows, so [agentMessagesRemote] asks them instead. In a
  /// browser every machine is another computer. No tab has a switch to wait
  /// for: a computer whose account has messaging off just answers with nothing
  /// new.
  List<AgentMessagesRemoteTab> agentMessagesRemoteTabs() {
    final local = localMachineState?.machine.machineId;
    return [
      for (final swarm in swarms)
        if (agentMessagesOffered(swarm.id) && _messagingHarnesses(swarm) >= 2)
          if ([
                for (final id in agentMessageMachines(swarm.id))
                  if (id != local) id,
              ]
              case final remote when remote.isNotEmpty)
            (tabId: swarm.id, machineIds: remote),
    ];
  }

  /// How many of the owner's harnesses [swarm] holds, each once.
  int _messagingHarnesses(Swarm swarm) => {
    for (final pane in swarm.panes)
      if (pane.agentId case final agentId?
          when machineStates[pane.machineId]?.belongsToOtherAccount != true)
        agentMessageKey(pane.machineId, agentId),
  }.length;

  /// Polls [agentMessagesRemoteTabs] while the window is in front; the
  /// workspace starts it.
  late final agentMessagesRemote = AgentMessagesRemoteWatch(
    controller: agentMessages,
    foreground: foreground,
    tabs: agentMessagesRemoteTabs,
  );

  final _orchestratorProjects = <String, OrchestratorController>{};

  Future<Map<String, dynamic>> orchestratorRequest(
    String machineId,
    Map<String, dynamic> payload,
  ) async {
    final machine = stateOf(machineId);
    if (machine == null ||
        machine.machine.isShared ||
        machine.needsLink ||
        machine.nodeOnline == false ||
        machine.connectionStatus != ConnectionStatus.connected) {
      throw StateError(
        'Connect this machine to start an orchestrator project.',
      );
    }
    final connection = _conn(machineId);
    if (!connection.isReady) {
      throw StateError('Reconnect this machine to manage its projects.');
    }
    try {
      return await connection.request(
        'orchestrator',
        payload: payload,
        timeout: const Duration(seconds: 35),
      );
    } on WsRequestFailure catch (e) {
      if (e.code == 'UNSUPPORTED') {
        throw StateError(
          'Update Harness on this machine to use the orchestrator.',
        );
      }
      rethrow;
    }
  }

  OrchestratorController orchestratorProject(String machineId, String id) =>
      _orchestratorProjects.putIfAbsent(
        '$machineId/$id',
        () => OrchestratorController(
          id: id,
          request: (payload) => orchestratorRequest(machineId, payload),
        ),
      );

  void openOrchestratorProject(String machineId, String id, String title) {
    final existing = swarms
        .where(
          (s) => s.orchestratorId == id && s.orchestratorMachineId == machineId,
        )
        .firstOrNull;
    if (existing != null) {
      selectSwarm(existing.id);
      return;
    }
    final name = title.trim().replaceAll(RegExp(r'\s+'), ' ');
    newSwarm(
      name: name.isEmpty
          ? 'Orchestrator'
          : name.substring(0, name.length.clamp(0, 48)),
    );
    activeSwarm
      ..kind = 'orchestrator'
      ..orchestratorId = id
      ..orchestratorMachineId = machineId;
    _persistLayout();
    notifyListeners();
  }

  Future<void> inspectOrchestratorAgent(
    String machineId,
    String agentId,
  ) async {
    newSwarm(name: 'Inspect harness');
    await addAgentToSwarm(machineId, agentId, swarmId: activeSwarmId);
  }

  // Tabs created for a pending action stay temporary until they have content.
  // The return destination is session-local; abandoned drafts are never saved.
  final _draftSwarmReturns = <String, String>{};

  bool isDraftSwarm(String id) {
    if (!_draftSwarmReturns.containsKey(id) ||
        _activeAgentCreations.any((attempt) => attempt._targetId == id)) {
      return false;
    }
    final swarm = swarms.where((swarm) => swarm.id == id).firstOrNull;
    return swarm != null &&
        swarm.panes.isEmpty &&
        swarm.name == Swarm.defaultName &&
        swarm.presets.isEmpty;
  }

  void newSwarm({
    String name = Swarm.defaultName,
    bool draft = false,
    bool newTabPage = false,
  }) {
    name = Swarm.normalizeName(name);
    // Ordinary destinations can reuse an empty tab. Explicit New Tab always
    // creates its own tab with the same welcome content.
    if (name == Swarm.defaultName && !newTabPage) {
      final starter = activeSwarm.isEmptyStarter
          ? activeSwarm
          : swarms.where((swarm) => swarm.isEmptyStarter).firstOrNull;
      if (starter != null) {
        if (starter.id != activeSwarmId) selectSwarm(starter.id);
        return;
      }
    }
    while (swarms.any((s) => s.id == 'swarm-$_nextSwarmId')) {
      _nextSwarmId++;
    }
    // A desk id from the start when the desk is on: the tab will be everyone's
    // the moment it holds something.
    final swarm = Swarm(
      id: _desk.enabled ? newDeskId() : 'swarm-${_nextSwarmId++}',
      name: name,
      isNewTabPage: newTabPage,
    );
    if (draft) {
      _draftSwarmReturns[swarm.id] =
          _draftSwarmReturns[activeSwarmId] ?? activeSwarmId;
    }
    swarms.add(swarm);
    selectSwarm(swarm.id);
  }

  /// The Harness Store takes over the tab it was opened from — the New Tab
  /// whose start page carries the card — exactly as the first agent takes
  /// over a New Tab. One store tab per window, like one New Tab: when it is
  /// already open somewhere, that one is selected. From a tab with panes it
  /// gets a tab of its own.
  ///
  /// [harness] opens the Store straight on that harness's page — the model
  /// picker's door when Grid is not installed yet. Held until the Store tab
  /// reads it ([takePendingStoreHarness]): the tab may exist already, or be
  /// about to be built, and either way the page turns exactly once.
  void openStore({String? harness}) {
    if (harness != null) _pendingStoreHarness = harness;
    final current = activeSwarm;
    if (current.isStore) {
      if (harness != null) notifyListeners();
      return;
    }
    _storeOpenedByPerson = true;
    final existing = swarms.where((swarm) => swarm.isStore).firstOrNull;
    if (existing != null) {
      selectSwarm(existing.id);
      return;
    }
    if (current.isEmptyStarter) {
      current
        ..kind = 'store'
        ..name = Swarm.storeName;
      _draftSwarmReturns.remove(current.id);
      _persistLayout();
      notifyListeners();
      return;
    }
    while (swarms.any((s) => s.id == 'swarm-$_nextSwarmId')) {
      _nextSwarmId++;
    }
    final swarm = Swarm(
      id: 'swarm-${_nextSwarmId++}',
      name: Swarm.storeName,
      kind: 'store',
    );
    swarms.add(swarm);
    selectSwarm(swarm.id);
  }

  String? _pendingStoreHarness;

  /// A person opened the Store ([openStore]), not a tab restored at launch: the Store tab's first ask
  /// takes it ([takeStoreOpened]) and marks its `dsh_list` as theirs, all the Store's reach counts
  /// (`store_list_user_*`). Its minute refresh and reconnect asks carry no mark.
  bool _storeOpenedByPerson = false;

  bool takeStoreOpened() {
    final opened = _storeOpenedByPerson;
    _storeOpenedByPerson = false;
    return opened;
  }

  /// Devices is a regular workspace on the desktop app. A browser or a viewer
  /// build has no device on its desk to manage.
  bool get devicesEnabled => !kIsWeb && !kViewerMode;

  LocalKeyValueStore? get deviceLibraryStorage => _paneLayout?.storage;

  /// This computer's small preferences store (`state.json` natively, the
  /// origin's storage in a browser); null in a test that passes none.
  LocalKeyValueStore? get localStore => _paneLayout?.storage;
  final deviceHosts = DeviceHosts();
  final _deviceReads = <String, Future<void>>{};

  void _syncDeviceHosts() {
    deviceHosts.reconcile([
      for (final machine in machineStates.values)
        if (!machine.machine.isShared)
          DeviceHost(
            id: machine.machine.machineId,
            name: machine.machine.displayName,
            local: machine.isLocalMachine,
            online:
                machine.connectionStatus == ConnectionStatus.connected &&
                !machine.isOffline &&
                !machine.needsLink,
            error: machine.needsLink
                ? 'Link this computer in Machines to manage its devices.'
                : null,
          ),
    ]);
  }

  /// Read each owned machine through its existing authenticated connection.
  /// Reading devices never opens a terminal or powers on a stopped machine.
  Future<void> refreshDevices() async {
    if (!devicesEnabled || _disposed) return;
    _syncDeviceHosts();
    if (_pool == null && connectionForTest == null) return;
    await Future.wait([
      for (final machine in machineStates.values.toList())
        if (!machine.machine.isShared &&
            !machine.isOffline &&
            !machine.needsLink)
          _readDeviceHost(machine),
    ]);
  }

  Future<void> _readDeviceHost(MachineState machine) {
    final id = machine.machine.machineId;
    final active = _deviceReads[id];
    if (active != null) return active;
    final account = currentUser?.id;
    final experimentAccount = experimentalFeatures.accountId;
    final revision = _authRevision;
    bool current() =>
        !_disposed &&
        devicesEnabled &&
        currentUser?.id == account &&
        experimentalFeatures.accountId == experimentAccount &&
        _authRevision == revision &&
        identical(machineStates[id], machine);
    late final Future<void> read;
    read =
        (() async {
          try {
            final connection = _conn(id);
            await connection.waitUntilReady(
              timeout: const Duration(seconds: 8),
            );
            if (!current()) return;
            final result = await connection.request(
              'harness_devices_list',
              timeout: const Duration(seconds: 5),
            );
            if (!current() || machine.isOffline) return;
            _syncDeviceHosts();
            final status = result['status'];
            if (status is! Map<String, dynamic>) {
              throw const FormatException('Invalid device status');
            }
            deviceHosts.receive(
              id,
              DialStatus.fromJson(status),
              revision: result['revision'] is int
                  ? result['revision'] as int
                  : null,
            );
          } catch (error) {
            if (!current()) return;
            // Older local daemons already send addressed cable status. Never use
            // that fallback on a remote connection: dial_settings is local-only.
            if (error is WsRequestFailure &&
                error.code == 'UNSUPPORTED' &&
                machine.isLocalMachine &&
                dial.devices.isNotEmpty &&
                !machine.isOffline) {
              deviceHosts.receive(id, dial.status);
            } else {
              final unsupported =
                  error is WsRequestFailure && error.code == 'UNSUPPORTED';
              deviceHosts.failed(
                id,
                unsupported
                    ? 'Update Harness on ${machine.machine.displayName} to manage its devices.'
                    : 'Couldn’t reach ${machine.machine.displayName}. Reconnect or refresh to try again.',
              );
            }
          }
        })().whenComplete(() {
          if (identical(_deviceReads[id], read)) _deviceReads.remove(id);
        });
    return _deviceReads[id] = read;
  }

  Future<bool> setHostDeviceSettings(
    String machineId,
    String id,
    Map<String, Object?> patch,
  ) async {
    final machine = machineStates[machineId];
    final host = deviceHosts.host(machineId);
    final target = host?.devices.where((d) => d.id == id).firstOrNull;
    if (!devicesEnabled ||
        machine == null ||
        machine.machine.isShared ||
        machine.isOffline ||
        machine.needsLink ||
        host?.online != true ||
        host?.available != true ||
        target?.attached != true ||
        target?.updating != null ||
        patch.isEmpty ||
        (_pool == null && connectionForTest == null)) {
      return false;
    }
    final account = currentUser?.id;
    try {
      final reply = await _conn(machineId).request(
        'harness_device_settings',
        payload: {'id': id, 'patch': patch},
        timeout: const Duration(seconds: 6),
      );
      if (_disposed ||
          currentUser?.id != account ||
          !identical(machineStates[machineId], machine)) {
        return false;
      }
      if (reply['status'] case final Map<String, dynamic> status) {
        deviceHosts.receive(
          machineId,
          DialStatus.fromJson(status),
          revision: reply['revision'] is int ? reply['revision'] as int : null,
        );
      }
      return reply['ok'] == true;
    } on WsRequestFailure catch (failure) {
      if (failure.code == 'UNSUPPORTED' &&
          machine.isLocalMachine &&
          currentUser?.id == account) {
        return setDeviceSettings(id, patch);
      }
      return false;
    } catch (_) {
      return false;
    }
  }

  /// A pet request (`pet_preview`, `pet_apply`, `pet_reset`, `pet_status`) to
  /// this computer's daemon. They read files and drive the cable, so a relayed
  /// machine is refused here without sending anything. A refusal comes back as
  /// `{error, message}`, the same shape the daemon uses, not as an exception.
  Future<Map<String, dynamic>> petRequest(
    String machineId,
    String type,
    Map<String, Object?> payload,
  ) async {
    final machine = machineStates[machineId];
    if (machine == null ||
        !machine.isLocalMachine ||
        (_pool == null && connectionForTest == null)) {
      return {
        'error': 'LOCAL_ONLY',
        'message': 'Pets are set on this computer.',
      };
    }
    try {
      return await _conn(machineId).request(
        type,
        payload: payload,
        timeout: type == 'pet_preview'
            ? const Duration(seconds: 30)
            : const Duration(seconds: 6),
      );
    } on WsRequestFailure catch (failure) {
      return {
        'error': failure.code,
        'message': failure.payload['message'] is String
            ? failure.payload['message']
            : failure.detail ?? failure.code,
      };
    } catch (_) {
      return {
        'error': 'UNREACHABLE',
        'message': 'Couldn’t reach Harness on this computer. Try again.',
      };
    }
  }

  /// Devices stays inside an active Swarm; ordinary workspaces keep their
  /// existing utility tab. Opening it never changes the Swarm's membership.
  void openDevices() {
    if (!devicesEnabled) return;
    final swarm = activeSwarm;
    if (swarm.isSuperTab && swarm.superTabId != null) {
      final account = currentUser?.id;
      final controller = superTabs.peek(swarm.superTabId!);
      if (controller != null) {
        controller.selectDevices();
      } else {
        unawaited(
          superTabs
              .open(swarm.superTabId!)
              .then((controller) {
                if (!_disposed &&
                    currentUser?.id == account &&
                    identical(activeSwarm, swarm)) {
                  controller.selectDevices();
                }
              })
              .catchError((Object error) {
                if (!_disposed &&
                    currentUser?.id == account &&
                    identical(activeSwarm, swarm)) {
                  debugPrint('Could not open Devices in the Swarm: $error');
                }
              }),
        );
      }
      return;
    }
    final existing = swarms.where((s) => s.isDevices).firstOrNull;
    if (existing != null) {
      _ensureDevicesViewer(existing);
      selectSwarm(existing.id);
      return;
    }
    final current = activeSwarm;
    if (current.isEmptyStarter && !current.isUtility) {
      current
        ..kind = 'devices'
        ..name = Swarm.devicesName
        ..nameIsCustom = false
        ..isNewTabPage = false;
      _draftSwarmReturns.remove(current.id);
      _ensureDevicesViewer(current);
      _persistLayout();
      notifyListeners();
      return;
    }
    while (swarms.any((s) => s.id == 'swarm-$_nextSwarmId')) {
      _nextSwarmId++;
    }
    final tab = Swarm(
      id: 'swarm-${_nextSwarmId++}',
      name: Swarm.devicesName,
      kind: 'devices',
    );
    _ensureDevicesViewer(tab);
    swarms.add(tab);
    selectSwarm(tab.id);
  }

  void _ensureDevicesViewer(Swarm tab) {
    if (!devicesEnabled) return;
    if (!tab.panes.any((pane) => pane.isDevices)) {
      final pane = TerminalPane(
        id: _nextPaneId++,
        machineId: '',
        kind: PaneKind.devices,
      );
      tab.panes.insert(0, pane);
      tab.focusedPaneId ??= pane.id;
    }
    if (tab.isSuperTab) {
      // Your devices is a dashboard in the Swarm, without its own agent.
      // Clear ownership left by an earlier embedded conversation so closing
      // that old agent elsewhere cannot remove this independent viewer.
      final viewer = tab.panes.firstWhere((pane) => pane.isDevices)
        ..machineId = ''
        ..ownerAgentId = null
        ..fixedWidth = null;
      tab
        ..focusedPaneId = viewer.id
        ..previousPaneId = null
        ..zoomedPaneId = null
        ..arranged = null
        ..arrangedKey = null
        ..arrangedMinimum = null;
      return;
    }
    // Reserve the conversation before any network or launch work. Setup and
    // failures belong in this same right-hand pane, never above the dashboard.
    if (!tab.panes.any((pane) => !pane.isViewer)) {
      tab.panes.add(TerminalPane(id: _nextPaneId++, machineId: ''));
    }
    tab.paneSizes.putIfAbsent(
      '2:manual',
      () => PaneArrangement.viewerBesideTerminal,
    );
  }

  bool isDevicesWorkspace(Swarm tab) =>
      tab.isDevices ||
      (tab.isSuperTab &&
          tab.superTabId != null &&
          superTabs.peek(tab.superTabId!)?.devicesSelected == true);

  /// Called only after the Swarm has detached its previous group's views.
  void prepareSuperTabDevices(String swarmId) {
    final tab = swarms.where((tab) => tab.id == swarmId).firstOrNull;
    if (tab == null || !tab.isSuperTab || !isDevicesWorkspace(tab)) return;
    _ensureDevicesViewer(tab);
    notifyListeners();
  }

  Future<void> showDevicesTerminal(
    String machineId,
    String agentId, {
    String? swarmId,
  }) async {
    if (!devicesEnabled) return;
    final tab = swarms
        .where(
          (tab) =>
              (swarmId == null ? tab.isDevices : tab.id == swarmId) &&
              tab.isDevices,
        )
        .firstOrNull;
    if (tab == null) return;
    _ensureDevicesViewer(tab);
    final viewer = tab.panes.firstWhere((pane) => pane.isDevices);
    viewer.machineId = machineId;
    viewer.ownerAgentId = agentId;
    tab.paneSizes.putIfAbsent(
      '2:manual',
      () => PaneArrangement.viewerBesideTerminal,
    );
    await assignAgentToPane(
      tab.panes
          .where((pane) => !pane.isViewer && pane.agentId == null)
          .firstOrNull
          ?.id,
      machineId,
      agentId,
      swarmId: tab.id,
      focus: false,
      intent: tab == activeSwarm ? AttachIntent.person : AttachIntent.automatic,
    );
  }

  /// The companion's illustrated viewer and conversation, one per window.
  /// Its panes are bound only after the account's experimental gate is loaded.
  void openCompanions() {
    final existing = swarms.where((s) => s.isCompanions).firstOrNull;
    if (existing != null) {
      selectSwarm(existing.id);
      return;
    }
    final current = activeSwarm;
    if (current.isEmptyStarter && !current.isUtility) {
      current
        ..kind = 'companions'
        ..name = Swarm.companionsName
        ..nameIsCustom = false
        ..isNewTabPage = false;
      _draftSwarmReturns.remove(current.id);
      _persistLayout();
      notifyListeners();
      return;
    }
    while (swarms.any((s) => s.id == 'swarm-$_nextSwarmId')) {
      _nextSwarmId++;
    }
    final tab = Swarm(
      id: 'swarm-${_nextSwarmId++}',
      name: Swarm.companionsName,
      kind: 'companions',
    );
    swarms.add(tab);
    selectSwarm(tab.id);
  }

  /// The built-in companion viewer uses the same canvas, focus, geometry and
  /// terminal sessions as every DSH. These panes are derived from the enabled
  /// account and current individual, never restored before that gate is known.
  void syncCompanionViewer({required bool enabled, String? machineId}) {
    var changed = false;
    for (final tab in swarms.where((s) => s.isCompanions)) {
      if (!enabled) {
        for (final pane in tab.panes.toList()) {
          tab.remove(pane);
          if (!allPanes.contains(pane)) {
            unawaited(_detachSession(pane, sendClose: true));
          }
          changed = true;
        }
      } else if (!tab.panes.any((p) => p.isCompanion)) {
        final viewer = TerminalPane(
          id: _nextPaneId++,
          machineId: machineId ?? '',
          kind: PaneKind.companion,
        );
        tab.panes.insert(0, viewer);
        tab.focusedPaneId ??= viewer.id;
        changed = true;
      }
      if (enabled) {
        if (!tab.panes.any((pane) => !pane.isViewer)) {
          tab.panes.add(TerminalPane(id: _nextPaneId++, machineId: ''));
          changed = true;
        }
        tab.paneSizes.putIfAbsent(
          '2:manual',
          () => PaneArrangement.viewerBesideTerminal,
        );
      }
    }
    if (changed) notifyListeners();
  }

  Future<void> showCompanionTerminal(String? machineId, String? agentId) async {
    if (_agentChanges.values.any(
      (change) =>
          change.source.dsh == 'autonomous/pair' && change.preservingViews,
    )) {
      return;
    }
    final tab = swarms.where((s) => s.isCompanions).firstOrNull;
    final viewer = tab?.panes.where((p) => p.isCompanion).firstOrNull;
    if (tab == null || viewer == null) return;
    var changed =
        viewer.ownerAgentId != agentId || viewer.machineId != (machineId ?? '');
    viewer.ownerAgentId = agentId;
    viewer.machineId = machineId ?? '';
    for (final pane in tab.panes.where((p) => !p.isCompanion).toList()) {
      if (pane.agentId == null) continue;
      if (pane.machineId == machineId && pane.agentId == agentId) continue;
      tab.remove(pane);
      if (!allPanes.contains(pane)) {
        unawaited(_detachSession(pane, sendClose: true));
      }
      changed = true;
    }
    if (!tab.panes.any((pane) => !pane.isViewer)) {
      tab.panes.add(TerminalPane(id: _nextPaneId++, machineId: ''));
      changed = true;
    }
    if (changed) notifyListeners();
    if (machineId == null || agentId == null) return;
    // Keep the product's name and its standard viewer-left/terminal-right split.
    if (tab.paneSizes['2:manual'] == null) {
      tab.savePaneSizes('2:manual', PaneArrangement.viewerBesideTerminal);
    }
    await assignAgentToPane(
      tab.panes
          .where((pane) => !pane.isViewer && pane.agentId == null)
          .firstOrNull
          ?.id,
      machineId,
      agentId,
      swarmId: tab.id,
      focus: false,
      intent: tab == activeSwarm ? AttachIntent.person : AttachIntent.automatic,
    );
  }

  /// The harness page [openStore] was asked for, handed over once. The Store
  /// tab reads it when it is built and on every change while it is open.
  String? takePendingStoreHarness() {
    final id = _pendingStoreHarness;
    _pendingStoreHarness = null;
    return id;
  }

  void selectSwarm(String id, {bool attachPending = true}) {
    if (!swarms.any((s) => s.id == id)) return;
    if (id != activeSwarmId && isDraftSwarm(activeSwarmId)) {
      final abandoned = activeSwarmId;
      swarms.removeWhere((swarm) => swarm.id == abandoned);
      _draftSwarmReturns.remove(abandoned);
    }
    _activeSwarmId = id;
    railFocused = false;
    // A tab chosen — clicked, ⌘-number, ⌘] — is chosen to work in.
    _tabStripHold = null;
    _noteNavigation();
    final pane = focusedPane;
    selectedMachineId = pane?.machineId;
    _persistLayout();
    _announceAppFocus();
    if (attachPending) {
      for (final machine in machineStates.values) {
        // ⌘] / a tab clicked: a person is arriving at these tiles.
        _attachPendingPanes(
          machine,
          retryExisting: false,
          intent: AttachIntent.person,
        );
      }
      // A tile that was only WATCHING while this tab sat behind: arriving is
      // asking for its terminal, and the sweep above cannot do it — a watcher
      // is a live stream, so `_paneNeedsAttach` leaves it alone on purpose.
      for (final pane in panes) {
        if (pane.session?.watching != true) continue;
        if (!_canAttachPane(pane)) continue;
        unawaited(_reattachPane(pane, intent: AttachIntent.person));
      }
    }
    notifyListeners();
  }

  /// Cancel an untouched New Tab without closing a session or recording
  /// Recently Closed. If its return tab disappeared, restore onboarding.
  bool cancelSwarmDraft(String id) {
    final returnId = _draftSwarmReturns[id];
    final target = swarms.where((swarm) => swarm.id == id).firstOrNull;
    if (returnId == null ||
        !isDraftSwarm(id) ||
        target == null ||
        target.panes.isNotEmpty ||
        target.name != Swarm.defaultName ||
        target.presets.isNotEmpty) {
      return false;
    }
    final wasActive = activeSwarmId == id;
    swarms.remove(target);
    _draftSwarmReturns.remove(id);
    if (swarms.isEmpty) {
      swarms.add(Swarm(id: 'swarm-${_nextSwarmId++}'));
    }
    if (wasActive) {
      selectSwarm(
        swarms.any((swarm) => swarm.id == returnId) ? returnId : swarms.last.id,
      );
    } else {
      _persistLayout();
      notifyListeners();
    }
    return true;
  }

  /// Navigate to an existing view without opening, retrying or taking control
  /// of a terminal. A shared view prefers the current Swarm, then the requested
  /// owner. Publish the destination and its focus together, preserving layout.
  bool revealAgentView(
    String machineId,
    String agentId, {
    String? preferredSwarmId,
  }) {
    if (_disposed) return false;
    bool contains(Swarm swarm) => swarm.panes.any(
      (p) => p.machineId == machineId && p.agentId == agentId,
    );
    final owner = contains(activeSwarm)
        ? activeSwarm
        : swarms
                  .where((s) => s.id == preferredSwarmId && contains(s))
                  .firstOrNull ??
              swarms.where(contains).firstOrNull;
    if (owner == null) return false;
    final pane = owner.panes.firstWhere(
      (p) => p.machineId == machineId && p.agentId == agentId,
    );
    if (owner == activeSwarm) {
      focusPane(pane.id, reveal: true);
      return true;
    }
    if (owner.focusedPaneId != pane.id) {
      owner.previousPaneId = owner.focusedPaneId;
      owner.focusedPaneId = pane.id;
      _seeFocusedAgent();
    }
    if (owner.zoomedPaneId != null) owner.zoomedPaneId = pane.id;
    _activeSwarmId = owner.id;
    railFocused = false;
    selectedMachineId = machineId;
    _noteNavigation();
    _paneFocusRequest++;
    _persistLayout();
    _announceAppFocus();
    notifyListeners();
    return true;
  }

  /// Command-number follows the current visual tab order, retaining each tab's
  /// focused pane. A missing position is a no-op, never a pane selection.
  void selectSwarmByIndex(int index) {
    final view = profileSwarms;
    if (index < 0 || index >= view.length) return;
    selectSwarm(view[index].id);
  }

  void stepSwarm(int delta) {
    final view = profileSwarms;
    if (view.isEmpty) return;
    final index = view.indexWhere((swarm) => swarm.id == activeSwarmId);
    var next = index < 0 ? (delta < 0 ? -1 : 0) : index + delta;
    next %= view.length;
    if (next < 0) next += view.length;
    selectSwarm(view[next].id);
  }

  /// Show every machine, or only [machineId]. An empty value is every machine.
  /// The hidden tabs stay on the account desk.
  void setMachineProfile(String? machineId) {
    final next = machineId == null || machineId.isEmpty ? null : machineId;
    if (next == _machineProfileId) return;
    _machineProfileId = next;
    unawaited(_paneLayout?.saveMachineProfile(next));
    if (!profileSwarms.any((swarm) => swarm.id == _activeSwarmId)) {
      _ensureProfileFocus();
      _persistLayout();
    }
    notifyListeners();
  }

  void renameSwarm(String id, String name) {
    final clean = name.trim();
    if (clean.isEmpty) return;
    final swarm = swarms.where((s) => s.id == id).firstOrNull;
    if (swarm == null) return;
    swarm.name = clean.length > 80 ? clean.substring(0, 80) : clean;
    swarm.nameIsCustom = true;
    _persistLayout();
    notifyListeners();
  }

  void reorderSwarm(String id, int destination) {
    final view = List<Swarm>.of(profileSwarms);
    final from = view.indexWhere((swarm) => swarm.id == id);
    if (from < 0) return;
    final moved = view.removeAt(from);
    view.insert(destination.clamp(0, view.length), moved);
    if (view.length == swarms.length) {
      swarms
        ..clear()
        ..addAll(view);
    } else {
      var next = 0;
      for (var i = 0; i < swarms.length; i++) {
        if (swarmMatchesMachineProfile(swarms[i], _machineProfileId)) {
          swarms[i] = view[next++];
        }
      }
    }
    _persistLayout();
    notifyListeners();
  }

  Future<void> closeSwarm(String id, {bool persist = true}) async {
    if (cancelSwarmDraft(id)) return;
    final index = swarms.indexWhere((s) => s.id == id);
    if (index < 0) return;
    // Held ⌘W must not manufacture and close an endless sequence of blank
    // welcome tabs, evicting the real work from recently closed history.
    // Under a machine profile the hidden tabs do not count as something still
    // open: the last visible welcome is the one this window can see.
    final visible = profileSwarms;
    if (visible.length == 1 &&
        visible.single.id == id &&
        visible.single.panes.isEmpty &&
        visible.single.name == Swarm.defaultName &&
        visible.single.presets.isEmpty) {
      return;
    }
    final removed = swarms.removeAt(index);
    if (removed.superTabId case final tabId?) {
      _rememberSuperTabVisibility(tabId, false);
      superTabs.release(tabId);
    }
    Swarm? replacement;
    if (swarms.isEmpty) {
      replacement = Swarm(id: 'swarm-${_nextSwarmId++}');
      swarms.add(replacement);
    }
    final historyId = 'closed-${_nextClosedHistoryId++}';
    if (removed.superTabId != null && !_disposed) {
      _superTabClosures.add(historyId);
    }
    _rememberClosed(
      ClosedSwarm(
        removed,
        historyId: historyId,
        index: index,
        replacement: replacement,
        engine: removed.panes.length == 1
            ? stateOf(removed.panes.single.machineId)?.agents
                      .where(
                        (agent) => agent.id == removed.panes.single.agentId,
                      )
                      .firstOrNull
                      ?.identityEngine ??
                  removed.panes.single.session?.engineId
            : null,
      ),
    );
    if (_activeSwarmId == id) {
      // The next full-list tab may belong to another computer. Land on the
      // next tab this profile still shows. With none left the profile shows
      // every tab (see [profileSwarms]) rather than a new one being made: a
      // profile only hides, it never adds to the account desk.
      _activeSwarmId =
          profileNeighborId(swarms, _machineProfileId, index) ??
          swarms[index.clamp(0, swarms.length - 1)].id;
      // The tab beside it is shown and selected, but its terminal is not where
      // the next key goes: that key was typed at the work that just closed. The
      // keyboard waits on the tab strip ([tabStripFocused]). A fresh welcome
      // has no terminal to protect and keeps its own focus; closing a tab with
      // no panes (the Store, an unused New Tab) goes back to work as before.
      if (replacement == null && removed.panes.isNotEmpty) {
        _holdTabStrip();
      } else {
        _tabStripHold = null;
      }
    }
    selectedMachineId = focusedPane?.machineId;
    if (persist) _persistLayout();
    notifyListeners();
    _announceAppFocus();
    for (final machine in machineStates.values) {
      // Closing is navigation, just like selecting a tab. Attach newly visible
      // panes without retrying retained error streams in other tabs.
      _attachPendingPanes(
        machine,
        retryExisting: false,
        intent: AttachIntent.person,
      );
    }
    for (final pane in removed.panes) {
      if (!allPanes.contains(pane)) await _detachSession(pane, sendClose: true);
    }
  }

  /// Close removes these views. Swarms own work independently of their
  /// views; ordinary tabs stop a session only when its last view closes.
  Future<void> requestCloseSwarm(String id) {
    final tab = swarms.where((s) => s.id == id).firstOrNull;
    if (tab == null) return Future.value();
    final captured = tab.panes.toList();
    return _afterCloseGuards(
      captured,
      () => _requestViewClose(
        'tab:$id',
        tab,
        captured,
        () async {
          if (tab.panes.length != captured.length ||
              !captured.every(tab.panes.contains)) {
            return;
          }
          await closeSwarm(id);
        },
        tabName: tab.name,
        wholeTab: true,
      ),
    );
  }

  /// Runs [close] once every pane in [panes] with a close check has passed
  /// it — a Finder tile asks about its unsaved tabs (`TerminalPane.beforeClose`),
  /// one tile at a time. A tile kept open keeps the whole close from happening.
  Future<void> _afterCloseGuards(
    List<TerminalPane> panes,
    Future<void> Function() close,
  ) async {
    for (final pane in panes) {
      if (pane.beforeClose case final guard? when !await guard()) return;
    }
    await close();
  }

  Future<void> requestClosePane(int paneId) {
    final tab = activeSwarm;
    if (tab.isSuperTab && tab.superTabId != null) return Future.value();
    final pane = tab.panes.where((p) => p.id == paneId).firstOrNull;
    if (pane == null) return Future.value();
    if (tab.isCompanions || tab.isDevices) return requestCloseSwarm(tab.id);
    // A Finder and its chat are one group: closing the Finder closes the chat,
    // which takes the Finder with it, exactly as the chat's own Close does.
    if (pane.isFinder && pane.ownerAgentId != null) {
      final chat = tab.panes
          .where(
            (p) =>
                !p.isViewer &&
                p.machineId == pane.machineId &&
                p.agentId == pane.ownerAgentId,
          )
          .firstOrNull;
      if (chat != null) return requestClosePane(chat.id);
    }
    final captured = tab.panes
        .where(
          (p) =>
              identical(p, pane) || p.viewsAgent(pane.machineId, pane.agentId),
        )
        .toList();
    return _afterCloseGuards(
      captured,
      () =>
          _requestViewClose('pane:${tab.id}:$paneId', tab, captured, () async {
            if (tab.panes.contains(pane)) {
              await closePane(paneId, swarmId: tab.id);
            }
          }),
    );
  }

  Future<void> _requestViewClose(
    String key,
    Swarm tab,
    List<TerminalPane> closing,
    Future<void> Function() finish, {
    String? tabName,
    bool wholeTab = false,
  }) {
    if (_disposed) return Future.value();
    if (_viewCloseRequests[key] case final pending?) return pending;
    bool canStop(String machineId, String agentId) {
      // A Swarm pane is only a view into shared work. This guard also covers
      // the close shortcut, native menu and whole-tab dismissal, including a
      // regular tab becoming a Swarm while a close review is pending.
      // A Product Manager keeps running when its ordinary view closes too.
      if (tab.isSuperTab ||
          superTabs.leadProtectionReasonForHarness(machineId, agentId) !=
              null) {
        return false;
      }
      if (!swarms.contains(tab) ||
          (wholeTab &&
              (tab.panes.length != closing.length ||
                  !closing.every(tab.panes.contains)))) {
        return false;
      }
      bool showsAgent(TerminalPane pane) =>
          pane.machineId == machineId &&
          (pane.agentId ?? pane.ownerAgentId) == agentId;
      if (!closing.any(
        (pane) => showsAgent(pane) && tab.panes.contains(pane),
      )) {
        return false;
      }
      return !swarms.any(
        (other) => other.panes.any(
          (pane) =>
              showsAgent(pane) &&
              !(identical(other, tab) && closing.contains(pane)),
        ),
      );
    }

    final targets = <(String, Agent)>[];
    final seen = <(String, String)>{};
    for (final pane in closing) {
      final id = pane.agentId;
      if (pane.isWeb ||
          id == null ||
          !seen.add((pane.machineId, id)) ||
          !canStop(pane.machineId, id)) {
        continue;
      }
      final machine = stateOf(pane.machineId);
      final agent = machine?.agents.where((a) => a.id == id).firstOrNull;
      if (machine?.machine.isShared == true ||
          agent == null ||
          // The monitor is a reusable dashboard, including its assistant.
          // Dismissing it must work even when its machine cannot be reached.
          agent.dsh == harnessMonitorId ||
          agent.isStopped ||
          !agent.terminalAvailable ||
          !agent.closeSupported) {
        continue;
      }
      targets.add((pane.machineId, agent));
    }
    final revision = _authRevision;
    // The whole captured view belongs to Close, including sessions already
    // stopped or served by an older CLI. Peer pruning must not trim its undo.
    final held = {
      for (final pane in closing)
        if (pane.agentId ?? pane.ownerAgentId case final String id)
          (pane.machineId, id),
    };
    for (final target in held) {
      _closingViewAgents[target] = (_closingViewAgents[target] ?? 0) + 1;
    }
    final completion = Completer<void>();
    final request = completion.future;
    _viewCloseRequests[key] = request;
    unawaited(
      (() async {
        try {
          if (targets.isNotEmpty &&
              (reviewSessionClose == null ||
                  !await reviewSessionClose!(
                    targets,
                    tabName: tabName,
                    canStop: canStop,
                  ))) {
            return;
          }
          if (!_authWorkCurrent(revision) || !swarms.contains(tab)) return;
          await finish();
        } catch (_) {
          if (_authWorkCurrent(revision)) {
            _lastError = 'Could not close this session safely. Check its state and try again.';
            _lastErrorRetryable = true;
            notifyListeners();
          }
        } finally {
          for (final target in held) {
            final remaining = (_closingViewAgents[target] ?? 1) - 1;
            if (remaining == 0) {
              _closingViewAgents.remove(target);
            } else {
              _closingViewAgents[target] = remaining;
            }
          }
          if (identical(_viewCloseRequests[key], request)) {
            _viewCloseRequests.remove(key);
          }
          // A cancelled or partial close keeps its remaining local views. Once
          // the operation releases them, share that intent with the desk too.
          if (_authWorkCurrent(revision) && swarms.contains(tab)) {
            _persistLayout();
          }
          completion.complete();
        }
      })(),
    );
    return request;
  }

  /// Capture once before showing a prompt. Old/replaced targets cannot inherit its answer.
  /// [changeId]: the Change agent switch this close is part of, whose
  /// handoff was prepared under that id. A Swarm Product Manager's machine
  /// lets its stop through only for that switch (cli superTabs/leadSwitch.ts);
  /// any other close of one is refused as before.
  Future<Map<String, dynamic>> Function(String) prepareSessionClose(
    String machineId,
    Agent agent, {
    String? changeId,
  }) {
    final machine = stateOf(machineId);
    final revision = _authRevision;
    final removal = machine?._agentRemovals[agent.id];
    return (mode) async {
      // A harness reviewed before it bound its first conversation is the
      // same one once it has (`Agent.continuesSession`); the request below
      // still names the reviewed identity, so the daemon decides whether a
      // harness that bound since may close.
      bool sameAgent(Agent? current) =>
          current != null && current.continuesSession(agent);
      final current = machine?.agents
          .where((a) => a.id == agent.id)
          .firstOrNull;
      if (machine == null ||
          machine.machine.isShared ||
          !_machineWorkCurrent(machine, revision) ||
          machine._agentRemovals[agent.id] != removal ||
          !sameAgent(current)) {
        return {
          'error': 'AGENT_CHANGED',
          'detail': 'The session changed. Check it before closing.',
        };
      }
      if (agent.createdAt == null || !agent.closeSupported) {
        return {
          'error': 'UNSUPPORTED',
          'detail': 'Update the Harness CLI on this machine to close saved sessions safely.',
        };
      }
      Map<String, dynamic> result;
      try {
        result = await _conn(machineId).request(
          'agent_close',
          payload: {
            'agentId': agent.id,
            'sessionId': agent.sessionId ?? '',
            'createdAt': agent.createdAt!.toUtc().toIso8601String(),
            'mode': mode,
            'changeId': ?changeId,
          },
        );
      } on WsRequestFailure catch (failure) {
        // A refusal is an answer, not a lost connection. Keep its activity so
        // SESSION_NOT_IDLE can be reviewed, and its save/stop detail for the user.
        result = {
          ...failure.payload,
          'error': failure.code,
          if (failure.detail != null) 'detail': failure.detail,
        };
      } catch (_) {
        // A lost reply never causes a second Stop. Authoritative saved inventory
        // can confirm it; otherwise keep the pane and report uncertainty.
        await reloadMachineData(machineId);
        final observed = machine.agents
            .where((a) => a.id == agent.id)
            .firstOrNull;
        if (_machineWorkCurrent(machine, revision) &&
            sameAgent(observed) &&
            observed!.isStopped) {
          return {'closed': true};
        }
        return {
          'error': 'CLOSE_UNCONFIRMED',
          'detail': 'Could not confirm the close. Check the machine connection and try again.',
        };
      }
      if (!_machineWorkCurrent(machine, revision)) {
        return {'error': 'AGENT_CHANGED'};
      }
      final observed = machine.agents
          .where((a) => a.id == agent.id)
          .firstOrNull;
      if (observed != null && !sameAgent(observed)) {
        return {'error': 'AGENT_CHANGED'};
      }
      if (result['closed'] == true &&
          (observed == null || !observed.isStopped)) {
        _upsertAgent(
          machine,
          // The latest row seen, so a conversation bound since the review is
          // kept on the stopped harness for reopening.
          (observed ?? current!).copyWith(
            status: 'stopped',
            terminalAvailable: false,
            clearClosePlan: true,
          ),
        );
        notifyListeners();
      }
      if (result['cancelled'] == true && observed != null) {
        _upsertAgent(machine, observed.copyWith(clearClosePlan: true));
        notifyListeners();
      }
      return result;
    };
  }

  void reopenClosedSwarm({String? historyId}) {
    if (_disposed) return;
    final index = _closedHistory.lastIndexWhere(
      (entry) =>
          entry is ClosedSwarm &&
          (historyId == null || entry.historyId == historyId),
    );
    if (index < 0) return;
    final saved = _closedHistory[index] as ClosedSwarm;
    // The tab may have been opened another way since: focus that view.
    if (saved.superTabId case final tabId?) {
      final open = swarms.where((s) => s.superTabId == tabId).firstOrNull;
      if (open != null) {
        _closedHistory.removeAt(index);
        selectSwarm(open.id);
        return;
      }
    }
    if (!_canReopenSwarm(saved)) return;
    _closedHistory.removeAt(index);
    if (saved.superTabId case final tabId?) {
      _rememberSuperTabVisibility(tabId, true);
    }
    if (swarms.length == 1 && saved.replacesUntouchedWelcome(swarms.single)) {
      swarms.clear();
    }
    final pool = {
      for (final pane in allPanes) (pane.machineId, pane.agentId): pane,
    };
    final target = swarms.where((swarm) => swarm.id == saved.id).firstOrNull;
    if (target != null) {
      // Reopening an individual agent may have restored this swarm already.
      // Reunite its missing views without cloning the tab or overwriting edits
      // made since then. Live peers keep their terminal, draft and selection.
      final present = {
        for (final pane in target.panes) (pane.machineId, pane.agentId),
      };
      final previousCount = target.panes.length;
      for (final entry in saved.panes) {
        if (!present.add((entry.machineId, entry.agentId))) continue;
        target.panes.add(
          pool.putIfAbsent(
            (entry.machineId, entry.agentId),
            () => TerminalPane(
              id: _nextPaneId++,
              machineId: entry.machineId,
              agentId: entry.agentId,
            )..composerVisible = entry.composerVisible,
          ),
        );
      }
      if (target.panes.length != previousCount) {
        // An old manual shape for this count describes different membership.
        // Keep current presets/pins and use the normal layout for added views.
        target.paneSizes.remove('${target.panes.length}:manual');
        target.arranged = null;
        target.arrangedKey = null;
      }
      target.focusedPaneId ??= target.panes.firstOrNull?.id;
      _paneFocusRequest++;
      selectSwarm(target.id);
      _openSavedPanes(target.panes);
      return;
    }
    final restored =
        Swarm(
            id: saved.id,
            name: saved.name,
            kind: saved.kind,
            nameIsCustom: saved.nameIsCustom,
          )
          ..titleMachineId = saved.titleMachineId
          ..titleAgentId = saved.titleAgentId
          ..orchestratorId = saved.orchestratorId
          ..orchestratorMachineId = saved.orchestratorMachineId
          ..superTabId = saved.superTabId
          ..gridColumns = saved.gridColumns
          ..presets.addAll(saved.presets)
          ..paneSizes.addAll(saved.paneSizes);
    for (final entry in saved.panes) {
      final pane = pool.putIfAbsent(
        (entry.machineId, entry.agentId),
        () => TerminalPane(
          id: _nextPaneId++,
          machineId: entry.machineId,
          agentId: entry.agentId,
        )..composerVisible = entry.composerVisible,
      );
      restored.panes.add(pane);
      if (entry.pinnedSlot != null) {
        restored.pinnedSlots[pane.id] = entry.pinnedSlot!;
      }
    }
    int? paneAt(int index) => index >= 0 && index < restored.panes.length
        ? restored.panes[index].id
        : null;
    restored.focusedPaneId =
        paneAt(saved.focus) ?? restored.panes.firstOrNull?.id;
    restored.previousPaneId = paneAt(saved.previousFocus);
    restored.zoomedPaneId = paneAt(saved.zoom);
    swarms.insert(saved.index.clamp(0, swarms.length), restored);
    selectSwarm(restored.id);
    _openSavedPanes(restored.panes);
  }

  /// Reopen the chosen closure, or the newest closure for Cmd-Shift-T.
  /// Membership is restored synchronously; a slow detach cannot resurrect an
  /// old controller or redirect the destination after a network wait.
  bool reopenClosed({String? historyId}) {
    final id = historyId ?? _closedHistory.lastOrNull?.historyId;
    if (id == null || !canReopenClosed(id)) return false;
    final index = _closedHistory.indexWhere((entry) => entry.historyId == id);
    final saved = _closedHistory[index];
    if (saved is ClosedSwarm) {
      reopenClosedSwarm(historyId: id);
      return true;
    }
    final agent = saved as ClosedAgent;
    _closedHistory.removeAt(index);
    var target = swarms.where((s) => s.id == agent.swarmId).firstOrNull;
    if (target == null) {
      target = Swarm(id: agent.swarmId, name: agent.swarmName);
      swarms.add(target);
    }
    final pane =
        allPanes
            .where(
              (p) =>
                  p.machineId == agent.machineId && p.agentId == agent.agentId,
            )
            .firstOrNull ??
        (TerminalPane(
          id: _nextPaneId++,
          machineId: agent.machineId,
          agentId: agent.agentId,
        )..composerVisible = agent.composerVisible);
    if (!target.panes.contains(pane)) {
      final count = target.panes.length;
      final defaultPreset = PanePreset.defaultFor(count);
      final defaultTiles = defaultPreset == null
          ? null
          : PaneArrangement(defaultPreset.tilesFor(count)).fillRowEnds().tiles;
      // A close now leaves the default layout. The desk may have frozen it as
      // manual geometry; either form still permits undo until the user edits it.
      final restoreManual =
          agent.manualLayout != null &&
          listEquals(
            target.panes.map((p) => (p.machineId, p.agentId)).toList(),
            agent.remainingReadingOrder,
          ) &&
          !target.presets.containsKey(count) &&
          target.paneSizes.entries
              .where((entry) => entry.key.startsWith('$count:'))
              .every(
                (entry) =>
                    entry.key == '$count:manual' &&
                    listEquals(entry.value.tiles, defaultTiles),
              );
      if (restoreManual) {
        // The old split's rectangles still address the original list order.
        target.panes.sort(
          (a, b) => agent.remainingAgents
              .indexOf((a.machineId, a.agentId))
              .compareTo(
                agent.remainingAgents.indexOf((b.machineId, b.agentId)),
              ),
        );
      }
      target.panes.insert(agent.index.clamp(0, target.panes.length), pane);
      if (restoreManual) {
        final members = target.panes;
        target.pinnedSlots.updateAll(
          (id, _) => members.indexWhere((p) => p.id == id),
        );
        target.savePaneSizes(
          '${target.panes.length}:manual',
          agent.manualLayout!,
        );
      } else if (agent.manualLayout != null) {
        target.paneSizes.remove('${target.panes.length}:manual');
      }
      if (agent.pinnedSlot != null &&
          !target.pinnedSlots.containsValue(agent.pinnedSlot)) {
        target.pinnedSlots[pane.id] = agent.pinnedSlot!;
      }
    }
    if (target.focusedPaneId != pane.id) {
      target.previousPaneId = target.focusedPaneId;
    }
    target.focusedPaneId = pane.id;
    if (agent.zoomed || target.zoomedPaneId != null) {
      target.zoomedPaneId = pane.id;
    }
    _activeSwarmId = target.id;
    _settlePins();
    _paneFocusRequest++;
    selectSwarm(target.id);
    _openSavedPanes([pane]);
    return true;
  }

  void _openSavedPanes(Iterable<TerminalPane> restored) {
    for (final pane in restored) {
      final agent = stateOf(pane.machineId)?.agents
          .where((agent) => agent.id == pane.agentId)
          .firstOrNull;
      if (agent?.isStopped == true) unawaited(openSavedPane(pane.id));
    }
  }

  /// Explicit reopening resumes the saved conversation in its existing slot.
  /// A delayed response cannot follow focus into another tab or reopen a pane
  /// the person has since closed. Resume receipts deduplicate repeated clicks.
  Future<void> openSavedPane(int paneId) async {
    final pane = allPanes.where((pane) => pane.id == paneId).firstOrNull;
    final agentId = pane?.agentId;
    if (_disposed || pane == null || agentId == null) return;
    final revision = _authRevision;
    final request = resumeAgent(pane.machineId, agentId);
    notifyListeners();
    final result = await request;
    if (!_authWorkCurrent(revision) ||
        !allPanes.contains(pane) ||
        pane.agentId != agentId) {
      return;
    }
    if (result.error case final error?) {
      _lastError = error;
      _lastErrorRetryable = result.retryable;
      notifyListeners();
      return;
    }
    pane.claimOnFirstAttach = true;
    if (panes.contains(pane) &&
        _paneNeedsAttach(pane) &&
        _canAttachPane(pane)) {
      pane.claimOnFirstAttach = false;
      await _reattachPane(pane, intent: AttachIntent.person);
    }
  }

  /// Capture the destination before any network wait or tab change.
  Future<void> addAgentToSwarm(
    String machineId,
    String agentId, {
    String? swarmId,
    AttachIntent intent = AttachIntent.person,
  }) => assignAgentToPane(
    null,
    machineId,
    agentId,
    swarmId: swarmId,
    intent: intent,
  );

  Future<void> seedSwarm(
    String name,
    List<({String machineId, String agentId})> agents,
  ) async {
    final target = activeSwarm;
    renameSwarm(target.id, name);
    // Each call records membership synchronously, before its attachment waits.
    // A slow/offline host must not hold back the other panes or retarget a tab.
    final attachments = <Future<void>>[];
    for (final agent in agents) {
      attachments.add(
        addAgentToSwarm(agent.machineId, agent.agentId, swarmId: target.id),
      );
    }
    await Future.wait(attachments);
  }

  /// Which tile the keyboard, the dial and the rail's highlight all mean.
  ///
  /// Typing itself does NOT go through this on macOS — the renderer is a
  /// WebView, so a click makes that pane's WKWebView the first responder and
  /// AppKit routes keys there without asking. This is for everything that has
  /// no pointer behind it: the dial's scroll and focus frames, and which agent
  /// the rail draws as current.
  int? get focusedPaneId => activeSwarm.focusedPaneId;
  set focusedPaneId(int? value) => activeSwarm.focusedPaneId = value;

  /// Whether this computer holds an account.
  ///
  /// Local services can run without an account, but desktop launch requires
  /// one before the workspace opens ([signInStepShowing]). After runtime
  /// expiry, local recovery keeps agents, terminals, tabs and DSH available;
  /// remote machines, the shared desk and the profile require sign-in again.
  ///
  /// Presumed true until the CLI says otherwise (`bootstrap` asks, and every
  /// change after that goes through [_rebindAuth]): nothing gated on it is on
  /// screen before that answer lands, and a fixture that sets [status] straight
  /// to `authenticated` is a signed-in window unless it says it is not.
  bool signedIn = true;

  /// A desktop window running without an account. A viewer is never a guest: it
  /// has no local daemon, so there is nothing it could show signed out.
  bool get isGuest => viewer == null && !signedIn;

  int _paneFocusRequest = 0;

  /// Explicit navigation must reveal and refocus even an already-selected pane.
  int get paneFocusRequest => _paneFocusRequest;

  bool _paneFocusByUser = true;

  /// Whether the latest navigation — [paneFocusRequest], a tab switch, a
  /// focus move — was a person's gesture on this app.
  ///
  /// False while it was a device's doing: the dial turning, a notification or
  /// question shown there, the WiFi device asking for an agent. Those move the
  /// view and the keyboard exactly as a click does, and must NOT take a
  /// terminal back from whichever client holds it — `_autoTakeControl` in
  /// `terminal_panel.dart` reads this before retaking. A question re-shown on
  /// the dial used to count as a click: the app took back every pane, the
  /// re-attach redrew the dialog, the daemon announced it as a new question,
  /// the dial beeped and asked again, 1.5s round, until the cable came out
  /// (owner, 2026-09-22).
  bool get paneFocusByUser => _paneFocusByUser;

  bool _navigatingFromDevice = false;

  /// Run [navigate] as the device's move, not a person's — see
  /// [paneFocusByUser]. Covers only the synchronous part: an `async`
  /// navigation's body runs up to its first `await` inside this, which is
  /// where every focus and tab change happens, and the attach it waits on
  /// afterwards is not the device's to be blamed for.
  T _fromDevice<T>(T Function() navigate) {
    _navigatingFromDevice = true;
    try {
      return navigate();
    } finally {
      _navigatingFromDevice = false;
    }
  }

  /// A device picked a project of a Swarm: show that Swarm, then its Lead
  /// chat, or with [buddy] (a round dial on its Buddy side, or a tap on the
  /// reader's Buddy) the reader's own Buddy chat there when they have one.
  /// Never a terminal tab: closing one stopped the Buddy (Diego, 10-30).
  Future<void> _openSuperTabProject(
    MachineState source,
    String tabId,
    String projectId, {
    bool buddy = false,
  }) async {
    final open = swarms.where((s) => s.superTabId == tabId).firstOrNull;
    final name = open?.name ?? _superTabNames[tabId];
    // A tab this account does not belong to is nobody's to open.
    if (name == null) return;
    _requestDeviceWindow(source);
    // Every announce until the project lands says the device caused it: the
    // open and the refresh can take longer than the daemon's echo window, and
    // an announce naming the tab's old project would pull the device off the
    // Lead it just picked.
    final pick = ++_devicePick;
    _announceFromDevice = true;
    final abandon = Timer(const Duration(seconds: 5), () {
      if (_devicePick == pick) _announceFromDevice = false;
    });
    try {
      _fromDevice(
        () => open == null ? openSuperTab(tabId, name) : selectSwarm(open.id),
      );
      final controller = await superTabs.open(tabId);
      if (_disposed || _devicePick != pick || !_announceFromDevice) return;
      if (controller.snapshot == null) await controller.refresh();
      if (_disposed || _devicePick != pick || !_announceFromDevice) return;
      final project = controller.snapshot?.projects
          .where((p) => p.id == projectId)
          .firstOrNull;
      if (project == null) return;
      // Only an existing chat of the reader's own: a device never makes one.
      // Where the Swarm gives one Buddy per person, that is their Swarm chat
      // (# buddy, which names no project), whichever project the dial is on;
      // an earlier project chat there is history (Diego, 11-02).
      final buddyKey =
          controller.oneBuddy &&
              controller.buddyChat(SuperTabController.kSwarmBuddyKey) != null
          ? SuperTabController.kSwarmBuddyKey
          : projectId;
      if (buddy && controller.buddyChat(buddyKey) != null) {
        await (controller.buddyChatOpener ?? controller.openBuddyChat)(
          buddyKey,
        );
        if (_disposed || _devicePick != pick) return;
      } else {
        await controller.select(project.leadConversationId);
        if (_disposed || _devicePick != pick) return;
      }
      // Selecting what is already selected announces nothing by itself.
      _announceOpenPanesToDial();
    } catch (error) {
      appLog.warn('super-tab', 'Could not open the picked project: $error');
    } finally {
      abandon.cancel();
      if (_devicePick == pick) _announceFromDevice = false;
    }
  }

  /// A thread the dial opened ([root] a string) or closed (null) in
  /// [conversationId] of the Swarm tab [tabId], without any navigation.
  Future<void> _dialThreadOnly(
    String tabId,
    String conversationId,
    Object? root,
  ) async {
    if (!_superTabNames.containsKey(tabId) &&
        !swarms.any((s) => s.superTabId == tabId)) {
      return;
    }
    // Every thread frame, a leave included, supersedes a pending open.
    final token = ++_dialThreadToken;
    try {
      final controller = await superTabs.open(tabId);
      if (_disposed) return;
      if (root is String) {
        if (controller.snapshot == null) await controller.refresh();
        if (_disposed ||
            controller.snapshot?.conversation(conversationId) == null) {
          return;
        }
        if (controller.selectedId != conversationId) {
          await controller.select(conversationId);
        }
        if (_disposed || controller.selectedId != conversationId) return;
        if (_dialThreadToken != token) return;
        // Not a new pick: a later pick bumps [_devicePick] and drops this.
        await _openDialThread(controller, root, _devicePick, token);
      } else if (controller.openedThread?.conversationId == conversationId) {
        controller.closeThread();
      }
    } catch (error) {
      appLog.warn('super-tab', 'Could not open the dial\'s thread: $error');
    }
  }

  /// Opens [root] beside the selected chat once the chat holds it. The dial
  /// names a thread right after its post made the root, so the app often has
  /// not read it: read once, then wait for a later read, until another pick,
  /// another chat or 10 seconds. A root the chat never holds opens nothing.
  Future<void> _openDialThread(
    SuperTabController controller,
    String root,
    int pick, [
    int? token,
  ]) async {
    final id = controller.selectedId;
    // The person's own open or close while this waits makes it stale.
    final before = controller.openedThread;
    void open() {
      // The pane may not be on screen (another Swarm tab, background window):
      // the view's _syncThreadPane calls threadPaneShown when it is.
      controller.openThread(root, shown: false);
    }

    bool holds() =>
        controller.messages(id).any((m) => m.id == root || m.thread == root);
    if (!holds()) await controller.refresh();
    bool superseded() =>
        _disposed ||
        _devicePick != pick ||
        controller.selectedId != id ||
        (token != null && _dialThreadToken != token) ||
        controller.openedThread != before;
    if (superseded()) return;
    if (holds()) return open();
    Timer? giveUp;
    void listener() {
      final stale = superseded();
      if (!stale && !holds()) return;
      giveUp?.cancel();
      controller.removeListener(listener);
      if (!stale) open();
    }

    controller.addListener(listener);
    giveUp = Timer(dialThreadWaitForTest, () {
      controller.removeListener(listener);
      // A later dial frame asks again; nothing of the thread is logged.
      appLog.warn(
        'super-tab',
        'The dial\'s thread never reached its chat in '
            '${dialThreadWaitForTest.inSeconds} s; it stays closed',
      );
    });
  }

  void _noteNavigation() {
    _paneFocusByUser = !_navigatingFromDevice;
    // A device's move is not a person opening anything — but it does leave a
    // different harness in front, so the next gesture on it is an open again.
    if (_navigatingFromDevice) {
      _touchedFocus = null;
    } else {
      _touchFocusedAgent();
    }
  }

  /// Native focus also changes during reparenting and dialog dismissal. The
  /// model already records a click/shortcut before asking the renderer to
  /// focus, so that echo must not turn a layout change into a terminal claim.
  void focusPaneFromRenderer(int paneId) {
    // A terminal that took the keys while the strip held them (a Tab into the
    // grid) is where the keys are now; the model says so rather than lying.
    if (focusedPaneId == paneId && !tabStripFocused) return;
    _fromDevice(() => focusPane(paneId));
  }

  /// An explicit relayout reveals live output even in tiles whose rectangle
  /// does not change. This is view intent, so it is never persisted.
  int _paneLayoutRequest = 0;
  int get paneLayoutRequest => _paneLayoutRequest;

  /// The chosen shape for a grid of this size, or the shipped one.
  Map<int, PanePreset> get panePresets => activeSwarm.presets;

  PanePreset? presetFor(int paneCount) =>
      panePresets[paneCount] ?? PanePreset.defaultFor(paneCount);

  /// Choosing a preset also resets custom sizes for that pane count. Selecting
  /// the current preset in Command-S is the quick way back to its proportions.
  void setPreset(int paneCount, PanePreset preset) {
    if (!preset.supportsCount(paneCount)) return;
    final resized = activeSwarm.paneSizes.keys.any(
      (key) => key.startsWith('$paneCount:'),
    );
    _paneLayoutRequest++;
    if (presetFor(paneCount) == preset && !resized) {
      notifyListeners();
      return;
    }
    panePresets[paneCount] = preset;
    activeSwarm.paneSizes.removeWhere(
      (key, _) => key.startsWith('$paneCount:'),
    );
    activeSwarm.arranged = null;
    activeSwarm.arrangedKey = null;
    notifyListeners();
    _persistLayout();
    _personArranged(activeSwarm);
  }

  int _paneResizeRequest = 0;
  int get paneResizeRequest => _paneResizeRequest;
  void beginPaneResize() {
    if (panes.length < 2 || zoomedPaneId != null) return;
    _paneResizeRequest++;
    notifyListeners();
  }

  PaneSplitRequest? preparePaneSplit(PaneResizeAxis axis, {int? paneId}) {
    if (zoomedPaneId != null || panes.length >= maxPanes) return null;
    final targetId = paneId ?? focusedPaneId;
    final before = activeSwarm.arranged;
    final minimum = activeSwarm.arrangedMinimum;
    final index = panes.indexWhere(
      (p) => p.id == targetId && p.agentId != null,
    );
    if (before == null ||
        minimum == null ||
        before.tiles.length != panes.length) {
      return null;
    }
    final after = before.split(index, axis, minimum: minimum);
    if (after == null || targetId == null) return null;
    return PaneSplitRequest(
      swarmId: activeSwarmId,
      paneId: targetId,
      axis: axis,
      paneIds: panes.map((p) => p.id),
      before: before,
      after: after,
    );
  }

  bool isPaneSplitCurrent(PaneSplitRequest split) {
    final target = swarms.where((s) => s.id == split.swarmId).firstOrNull;
    final minimum = target?.arrangedMinimum;
    return !_disposed &&
        target != null &&
        target.zoomedPaneId == null &&
        minimum != null &&
        listEquals(target.panes.map((p) => p.id).toList(), split.paneIds) &&
        listEquals(target.arranged?.tiles, split.before.tiles) &&
        split.before.split(
              split.paneIds.indexOf(split.paneId),
              split.axis,
              minimum: minimum,
            ) !=
            null;
  }

  /// Drag frames only update in-memory intent. The completed gesture performs
  /// one ordinary coalesced layout save; terminal sessions remain untouched.
  bool resizePanes(
    String swarmId,
    String layoutKey,
    PaneArrangement arrangement, {
    bool persist = true,
  }) {
    if (activeSwarmId != swarmId ||
        zoomedPaneId != null ||
        arrangement.tiles.length != panes.length ||
        activeSwarm.arrangedKey != layoutKey) {
      return false;
    }
    if (identical(activeSwarm.paneSizes[layoutKey], arrangement)) {
      if (persist) {
        _persistLayout();
        _personArranged(activeSwarm);
      }
      return true;
    }
    activeSwarm.savePaneSizes(layoutKey, arrangement);
    activeSwarm.arranged = arrangement;
    _paneLayoutRequest++;
    notifyListeners();
    if (persist) {
      _persistLayout();
      _personArranged(activeSwarm);
    }
    return true;
  }

  final _arrangedListeners = <void Function(Swarm)>[];

  /// [listener] hears each time the person arranged a tab's panes: a
  /// finished divider drag or a preset chosen (a Personal project keeps its
  /// own sizes, task #3099).
  void addArrangedListener(void Function(Swarm) listener) =>
      _arrangedListeners.add(listener);

  void _personArranged(Swarm swarm) {
    for (final listener in _arrangedListeners.toList()) {
      listener(swarm);
    }
  }

  void resetPaneSizes() {
    setPreset(panes.length, presetFor(panes.length) ?? PanePreset.auto);
  }

  int _nextPaneId = 1;

  static const maxPanes = 64;
  // Set only while `harness login --force --json` is waiting for the user to finish SSO in their system
  // browser. It arrives PART WAY THROUGH the flow — the CLI has to start before it can hand one
  // over. It identifies the current sign-in link; [signingIn] tracks the whole
  // attempt, including CLI startup and workspace restoration.
  String? pendingAuthorizeUrl;

  /// The account the sign-in under way went to — which of the login screen's two buttons is
  /// working — and, once it has failed, the one [retryLogin] goes back to. Null for a sign-in
  /// that named none: the phone's QR, or one started away from those buttons.
  SignInProvider? signInProvider;

  /// Signing in by a phone (`auth/phone_sign_in.dart`): the QR to show while a phone approves it.
  String? pendingQrLink;

  /// The account a phone approved this sign-in for, waiting on [confirmPhoneSignIn] — someone
  /// else's phone may have approved it, and nothing is signed in until the person here says yes.
  String? pendingConfirmEmail;

  /// Who was signed in here before, so the confirmation can say when the account changes.
  String? previousAccountEmail;

  Completer<bool>? _phoneConfirm;

  /// Whether this build can sign in by a phone at all (the CLI's, and a viewer's, can).
  bool get canSignInWithPhone => cliLogin is PhoneSignInClient;

  /// Whether this build can sign in by a code another device types in (the CLI's can).
  bool get canSignInWithCode => cliLogin is CodeSignInClient;

  /// What a sign-in in progress is waiting on before it can start — another sign-in on this
  /// computer, say — for the login screen to show; null when it is not waiting.
  String? get loginWaitingNote => switch (cliLogin) {
    CliLogin(:final waitingNote) => waitingNote.value,
    _ => null,
  };

  void _loginWaitingChanged() {
    if (!_disposed) notifyListeners();
  }

  bool openingLoginBrowser = false;
  String? loginBrowserError;
  int _loginBrowserRevision = 0;
  bool _loginAuthorized = false;
  bool get canCancelLogin => signingIn && !_loginAuthorized;

  /// True from the moment the user presses Sign in until the flow settles, one way or the other.
  ///
  /// **Not the same question as `pendingAuthorizeUrl != null`, and the difference was a bug.**
  /// `login()` flips [status] to `bootstrapping` immediately, but the authorize URL only lands
  /// once the CLI has spawned Node and got as far as printing one — seconds later — and it is
  /// cleared again in `finally` while `_finishBootstrapSignedIn()` is still restoring panes and
  /// fetching machines. `RootShell` keyed the sign-in screen off the URL, so both of those windows
  /// dropped the user onto a bare full-screen spinner: the card they were looking at vanished on
  /// the click, came back, then vanished again on success.
  ///
  /// This flag spans the whole flow, so the screen the user pressed a button on stays put.
  bool signingIn = false;
  bool _sessionExpired = false;
  bool get sessionExpired => _sessionExpired;

  @visibleForTesting
  void handleAuthFailureForTest(String message) => _signedOutAtRuntime(message);
  bool signingOut = false;
  String? signOutError;
  Future<void>? _logoutInFlight;
  Future<void>? _workspaceCleanup;
  bool _guestDeskRestorePending = false;

  AppNotifier({
    required AppConfig config,
    required AuthSession authSession,
    ConfigStore? configStore,
    this.localManualFixture,
    this.localCliDiscovery,
    this.environmentProvisioner,
    AgentPrefetch? agentPrefetch,
    this.desktopUpdater,
    WindowsSelfInstall? windowsSelfInstall,
    void Function(int code)? exitApp,
    this.connectionForTest,
    ProductMeasurement? productMeasurement,
    SignInClient? cliLogin,
    CliLink? cliLink,
    PeerLinkClient? peerLinks,
    ViewerServices? viewer,
    PaneLayoutStore? paneLayoutStore,
    this.workspaceEnabled,
    this.turnActivityTimeout = const Duration(seconds: 12),
    AlertSounds? alerts,
    AgentAlerts? agentAlerts,
    AgentUnread? agentUnread,
    SystemNotifications? systemNotifications,
    this.experimentalSettingsTransport,
  }) : agentPrefetch =
           agentPrefetch ??
           (kUnderTest
               ? null
               : AgentPrefetch(log: (line) => appLog.info('setup', line))),
       windowsSelfInstall =
           windowsSelfInstall ??
           (RuntimePlatform.isWindows &&
                   kReleaseMode &&
                   !kUnderTest &&
                   !kViewerMode
               ? WindowsSelfInstall()
               : null),
       _exitApp = exitApp ?? exit,
       alerts = alerts ?? AlertSounds(store: alertSoundStore),
       agentAlerts = agentAlerts ?? AgentAlerts(),
       systemNotifications =
           systemNotifications ?? notify_system.systemNotifications,
       agentUnread = agentUnread ?? AgentUnread(),
       _paneLayout = paneLayoutStore,
       // Remembers "a dial has been seen here" on the same terms the pane
       // layout is remembered: with a layout store there is a state file, and
       // without one (the tests) nothing is written anywhere.
       dial = DialState(paneLayoutStore?.storage),
       agentPreference = AgentPreference(paneLayoutStore?.storage),
       firstArrival = FirstArrival(paneLayoutStore?.storage),
       projectHistory = ProjectHistory(paneLayoutStore?.storage),
       taskHistory = TaskHistory(paneLayoutStore?.storage),
       session = authSession,
       _store = configStore,
       config = configStore?.config ?? config,
       viewer =
           viewer ??
           (kViewerMode
               ? ViewerServices(
                   config: configStore?.config ?? config,
                   session: authSession,
                 )
               : null) {
    _cliLink = cliLink;
    this.cliLogin = cliLogin ?? this.viewer?.login ?? CliLogin();
    if (this.cliLogin case final CliLogin cli) {
      cli.waitingNote.addListener(_loginWaitingChanged);
    }
    this.peerLinks = peerLinks ?? this.viewer?.links ?? this.cliLink;
    _autonomousEnv = this.config.autonomousEnv;
    api = _newApiClient();
    this.productMeasurement =
        productMeasurement ??
        ProductMeasurement(
          surface: kIsWeb
              ? 'web'
              : this.viewer == null
              ? 'desktop'
              : 'phone',
          automatic: !kUnderTest,
          setupStorage: !kIsWeb && this.viewer == null && !kUnderTest
              ? SetupPreferenceStore()
              : null,
          context: !kIsWeb && this.viewer == null
              ? ProductUsageContext(
                  release: 'unknown',
                  platform: Platform.isMacOS
                      ? 'macos'
                      : Platform.isWindows
                      ? 'windows'
                      : Platform.isLinux
                      ? 'linux'
                      : 'other',
                  production:
                      kReleaseMode && this.config.autonomousEnv == 'prod',
                )
              : null,
          sendSetup: (report) =>
              sendDesktopSetupMeasurement(this.config.apiBaseUrl, report),
        );
    productConnections = ProductConnections(this.productMeasurement);
    this.agentPrefetch?.onDownload ??= this.productMeasurement.setupDownload;
    this.productMeasurement.addListener(_measurementChoiceChanged);
    if (!kUnderTest && this.productMeasurement.healthEnabled) {
      productRuntimeHealth = ProductRuntimeHealth(this.productMeasurement);
      _measurementError = (framework) => this.productMeasurement.health(
        framework
            ? ProductHealthMeasure.frameworkError
            : ProductHealthMeasure.asyncError,
      );
      CrashLog.healthError = _measurementError;
    }
    addListener(_syncProductMeasurement);
    _initDeviceLog();
    // `grid.AppTheme.palette`, not the prefs store: main.dart copies the saved
    // choice into the palette notifier while rebuilding, so the store fires
    // before the colours the panes actually use have moved.
    grid.AppTheme.palette.addListener(_announceTerminalThemeEverywhere);
    terminalThemeStore.addListener(_announceTerminalThemeEverywhere);
    // The active tab is set from a dozen places — a tab click, a number key,
    // closing a tab, a restored layout, a reveal. Listening here catches all of
    // them, and a clear that finds nothing to clear notifies nobody.
    addListener(seeWatchedAgents);
    // The dial is told the whole list whenever it changes, so a cable attaching
    // later is handed it without asking. See [_announceUnreadToDial].
    //
    // `this.` because the constructor's own parameter of the same name is in
    // scope here and is the nullable one.
    this.agentUnread.addListener(_announceUnreadToDial);
    addListener(_syncDeviceHosts);
    addListener(_firstArrivalBehindTour);
    _autoRenameTabs = appearancePrefsStore.value.autoRenameTabs;
    appearancePrefsStore.addListener(_autoRenameChanged);
    // Other accounts' harnesses reach the desk as the rosters are read (R2).
    sharedTabs.addListener(_sharedTabsChanged);
  }

  void _syncProductMeasurement() {
    final context = productMeasurement.context;
    final production = kReleaseMode && _autonomousEnv == 'prod';
    if (context != null && context.production != production) {
      productMeasurement.context = ProductUsageContext(
        release: context.release,
        platform: context.platform,
        production: production,
      );
    }
    final scope =
        signedIn &&
            !signingIn &&
            !signingOut &&
            status == AppStatus.authenticated &&
            currentUser?.id != null
        ? (api, currentUser!.id)
        : null;
    final client = api;
    productMeasurement.account(
      scope,
      choice: () => productUsageSettings(),
      // Health names newer than this computer's CLI are counted only once
      // it has said it forwards them (ProductHealthMeasure.vocabulary).
      send: (report) => client.productUsageReport(
        report,
        onVocabulary: (vocabulary) =>
            productMeasurement.proxyVocabulary = vocabulary,
      ),
    );
    productRuntimeHealth?.account(
      scope == null ? null : '$_autonomousEnv:${currentUser!.id}',
    );
    if (scope == null) {
      _measurementConnections.clear();
      productConnections.clear();
      _measurementResumes.clear();
    } else if (machineStates.values.any(
      (machine) => machine.connectionStatus == ConnectionStatus.connected,
    )) {
      productRuntimeHealth?.ready();
      productMeasurement.milestone(ProductHealthMeasure.funnelWorkspaceReady);
    }
    if (status == AppStatus.unauthenticated) {
      productMeasurement.milestone(ProductHealthMeasure.funnelSignInSeen);
    }
  }

  void _measurementChoiceChanged() {
    if (!productMeasurement.sharing ||
        _measurementGeneration != productMeasurement.observationGeneration) {
      _measurementConnections.clear();
      _measurementResumes.clear();
    }
    _measurementGeneration = productMeasurement.observationGeneration;
  }

  /// A Settings opt-out before sign-in applies to the account once it is known.
  /// Keep it pending locally until the server confirms it; a failed request or
  /// a default-on account response must not silently restore sharing.
  Future<Map<String, dynamic>> productUsageSettings({bool? enabled}) async {
    await productMeasurement.setupChoiceReady;
    return api.productUsageSettings(
      enabled:
          enabled ?? (productMeasurement.accountOptOutPending ? false : null),
    );
  }

  // Connection keys already belong to the app. Only fixed outcomes reach measurement, never the key.
  void _measureConnection(
    String key,
    ConnectionStatus status,
    ProductFlow flow, {
    bool suppressStart = false,
  }) {
    if (status == ConnectionStatus.connecting ||
        status == ConnectionStatus.reconnecting) {
      if (suppressStart) return;
      if (_measurementConnections.length < 64) {
        _measurementConnections.putIfAbsent(
          key,
          () => productMeasurement.begin(flow),
        );
      }
    } else {
      _measurementConnections
          .remove(key)
          ?.call(
            status == ConnectionStatus.connected
                ? ProductOutcome.ok
                : ProductOutcome.failed,
          );
    }
  }

  /// Through the local CLI in a desktop build; straight to the backend, signed, in a viewer.
  ApiClient _newApiClient() => ApiClient(
    config: config,
    session: session,
    auth: viewer?.auth,
    localTransport: viewer == null ? localDaemonTransport : null,
  );

  /// How this app reaches the local CLI — its Unix socket or the loopback
  /// port. Owned by discovery, which decides it; REST and the local WebSocket
  /// follow it.
  LocalDaemonTransport get localDaemonTransport => _discovery.transport;

  String? get lastError => _lastError;

  /// The machine list's own failure, separate from [lastError] — that slot is shared with agent-launch
  /// and other one-off errors, and is cleared by [dismissError]. A pane asking "is this machine missing
  /// because we could not read the list?" needs the narrower question.
  String? get machineListError => _machineLoadError;

  /// A completed inventory distinguishes initial waiting from an unavailable
  /// machine. This also covers cached results; [machinesAreStale] qualifies them.
  bool _machineInventoryLoaded = false;
  bool get machineInventoryLoaded => _machineInventoryLoaded;

  /// True when the machine list on screen came from the daemon's cache because the backend could not be
  /// reached. The rows are the last known-good ones, not current.
  bool machinesAreStale = false;

  /// Whether a machine-list recovery is armed. Mirrors [environmentRecheckPending] — the honest way for a
  /// test to ask "is this still trying?" without reaching into a private timer.
  bool get machineRecoveryPending => _machineRecoveryTimer != null;
  bool get lastErrorRetryable => _lastErrorRetryable;
  String? get bootStatusMessage => _bootStatusMessage;

  /// Clears the error strip without retrying anything, for a failure retrying
  /// cannot fix (see [_lastErrorRetryable]).
  void dismissError() {
    _lastError = null;
    notifyListeners();
  }

  String get autonomousEnv => _autonomousEnv;
  bool get hasAvailableUpdate => availableUpdate != null;

  /// [updateDownloadFraction] as whole percent, for the one word the banner,
  /// the dialog and Settings all show.
  int? get updateDownloadPercent {
    final fraction = updateDownloadFraction;
    return fraction == null ? null : (fraction * 100).clamp(0, 100).floor();
  }

  static const offlineRetryInterval = Duration(seconds: 5);

  /// How long an offline machine of another computer waits between asks while an agent waits on it
  /// ([_pollOfflineMachine]); the last repeats. Each ask is a whole machine-list read from the
  /// backend, since nothing pushes a machine coming back to this window: every 5 s it was 12 reads
  /// a minute for one sleeping computer, in every window (WebSocket roadmap, Phase 2 item 4). It
  /// ends at the backend's own retry-after for an offline machine (`OFFLINE_RETRY_AFTER_MS`), and
  /// Retry asks at once. This computer's own daemon keeps [offlineRetryInterval]: that probe
  /// never reaches the backend.
  static const remoteOfflineRetryDelays = <Duration>[
    Duration(seconds: 5),
    Duration(seconds: 10),
    Duration(seconds: 20),
    Duration(seconds: 30),
  ];

  /// Waits before each automatic reattach of a pane whose stream died while its machine stayed
  /// reachable; the last one repeats. A pane used to get one reopen and then sit on Reconnect until
  /// someone clicked it, in whatever tab it was (2026-10-16).
  static const paneRetryDelays = <Duration>[
    Duration(seconds: 1),
    Duration(seconds: 2),
    Duration(seconds: 4),
    Duration(seconds: 8),
    Duration(seconds: 16),
    Duration(seconds: 30),
  ];

  /// At most one forced redial of a machine's link in this long (see [_forceRedial]).
  static const forcedRedialWindow = Duration(seconds: 30);
  static const localDaemonReconnectDelay = Duration(seconds: 1);
  static const agentSyncInterval = Duration(seconds: 60);

  /// How often the machine list is re-read with nothing having asked for it.
  /// The list is PUSHED (`machines_changed`, backend → daemon → this window);
  /// this only catches a push that was missed. Minutes, never seconds: a re-read
  /// is two authenticated backend requests (`/api/machines` +
  /// `/api/harness-shares`) from every open app, and at 15s that — not people —
  /// was most of the backend's traffic.
  static const machineListSafetyNetInterval = Duration(minutes: 5);

  /// How long a `machines_changed` push waits for the same push from the other machines. The backend
  /// tells every daemon socket of the account, and each relays it, so it reaches a window once per
  /// connected machine: four at once on Diego's app (2026-10-28), each a read of its own.
  static const machinesPushCollapse = Duration(seconds: 2);

  /// How often a viewer that has no machine socket open re-reads the machine list. Every push
  /// (`machines_changed`, `device_keys_changed`) reaches a browser over the web socket of a machine
  /// it is connected to; with none connected — the person signed in on the web first and is now
  /// running `harness login` on their computer — nothing tells it that computer has joined, and the
  /// safety net above would leave the person staring at an empty list for five minutes. Only while
  /// it is deaf, so the traffic note above holds for every window that has a machine.
  ///
  /// Every 20 s, except under the browser's connect page and asleep band: there it backs off, soon
  /// at first and then less often while nothing changes, and soon again on a push, a return to the
  /// tab or the person's Retry ([MachineListWatch]). An account waiting for its first computer
  /// ([waitsForFirstComputer]) has a person at the connect page while it installs, which can take
  /// minutes, so it never waits long; one whose computers are all asleep ([asleepComputers]) can
  /// wait longer.
  static const deafMachineListPace = <Duration>[Duration(seconds: 20)];
  static const firstComputerMachineListPace = <Duration>[
    Duration(seconds: 4),
    Duration(seconds: 8),
    Duration(seconds: 10),
  ];
  static const asleepComputersMachineListPace = <Duration>[
    Duration(seconds: 4),
    Duration(seconds: 8),
    Duration(seconds: 15),
    Duration(seconds: 30),
  ];
  @visibleForTesting
  List<Duration>? deafMachineListPaceForTest;

  MachineState? stateOf(String machineId) => machineStates[machineId];

  // ── the grid ────────────────────────────────────────────────────────────────────────────────────

  /// Null means "remember nothing", which is what a test gets by default.
  ///
  /// Deliberately NOT `?? PaneLayoutStore()` like the stores above it. Those
  /// only read, and only when asked; this one WRITES on every pane change, and
  /// a widget test that opens an agent would otherwise rewrite the layout in
  /// the developer's own ~/.harness state file. Production passes one; see
  /// [appStateProvider].
  final PaneLayoutStore? _paneLayout;

  /// A viewer companion uses auth and machine connections without restoring, claiming or
  /// writing workspace panes. Read after OAuth has restored the browser destination.
  final bool Function()? workspaceEnabled;

  /// The dial on this desk, for the rail's device row. Fed by `dial_status`
  /// frames from the local daemon; its own notifier, so the row rebuilds
  /// without dragging the whole rail through a machine-list rebuild.
  final DialState dial;
  final AgentPreference agentPreference;
  final ProjectHistory projectHistory;

  /// ⌘B's recent prompts (`core/task_history.dart`).
  final TaskHistory taskHistory;

  /// The first workspace on a computer new to Harness opens with agents already in it.
  final FirstArrival firstArrival;

  /// Whether this computer had the Harness CLI before this launch's setup: `~/.harness/cli`
  /// exists. Tests answer no, as on a fresh computer.
  @visibleForTesting
  bool Function() harnessInstalledBefore = kUnderTest
      ? () => false
      : () {
          final home = maybeHomeDir();
          return home == null ||
              FileSystemEntity.typeSync(
                    '$home${Platform.pathSeparator}.harness'
                    '${Platform.pathSeparator}cli',
                  ) !=
                  FileSystemEntityType.notFound;
        };

  /// Whether the CLI's own sign-in file is on this computer (task #3561). Looked at, never read: this app holds no
  /// token. `harness logout` deletes it, so a sign-out in a terminal while the app was closed waits for the signed-in
  /// check as before. Product installs keep it at `~/.harness/auth/session.json`; tests answer no.
  @visibleForTesting
  bool Function() cliSessionOnDisk = kUnderTest
      ? () => false
      : () {
          final home = maybeHomeDir();
          if (home == null) return false;
          final sep = Platform.pathSeparator;
          return FileSystemEntity.typeSync(
                '$home$sep.harness${sep}auth${sep}session.json',
              ) ==
              FileSystemEntityType.file;
        };

  TerminalPane? get focusedPane {
    final id = focusedPaneId;
    if (id == null) return null;
    for (final pane in panes) {
      if (pane.id == id) return pane;
    }
    return null;
  }

  /// The one tile everything single-terminal still means.
  ///
  /// Kept as a getter rather than deleted because the alternative — teaching
  /// every caller about tiles — would have spread the grid across code that has
  /// no business knowing there is one (a rename arriving, an agent being
  /// deleted, the window closing). The handful of callers that must reach EVERY
  /// tile of a machine, rather than only the focused one, call [panesFor]
  /// instead; those are the transport-wide events, and they are marked.
  TerminalSession? get activeTerminal => focusedPane?.session;

  /// Dial scroll handlers of the mounted cloud chat panes. A cloud harness has no
  /// terminal session to scroll, so its conversation registers here, by machine
  /// and agent, for as long as it is on screen.
  final _cloudScrollHandlers =
      <(String, String), void Function(int phase, int dy, int velocity)>{};

  /// Called by a cloud chat pane while mounted; returns how to withdraw it.
  VoidCallback registerCloudScroll(
    String machineId,
    String agentId,
    void Function(int phase, int dy, int velocity) handler,
  ) {
    final key = (machineId, agentId);
    _cloudScrollHandlers[key] = handler;
    return () {
      if (identical(_cloudScrollHandlers[key], handler)) {
        _cloudScrollHandlers.remove(key);
      }
    };
  }

  /// Dial scroll handlers of the mounted Swarm chats, by Super Tab: a device with
  /// one of that Swarm's Leads open (a Pro's Lead view) scrolls its chat.
  final _superTabScrollHandlers =
      <String, void Function(int phase, int dy, int velocity)>{};

  /// Called by a Swarm's chat while mounted; returns how to withdraw it.
  VoidCallback registerSuperTabScroll(
    String superTabId,
    void Function(int phase, int dy, int velocity) handler,
  ) {
    _superTabScrollHandlers[superTabId] = handler;
    return () {
      if (identical(_superTabScrollHandlers[superTabId], handler)) {
        _superTabScrollHandlers.remove(superTabId);
      }
    };
  }

  bool get canAddPane => panes.length < maxPanes;

  Iterable<TerminalPane> panesFor(String machineId) =>
      allPanes.where((pane) => pane.machineId == machineId);

  TerminalPane? paneOfAgent(String machineId, String agentId) {
    for (final pane in panes) {
      if (pane.machineId == machineId && pane.agentId == agentId) return pane;
    }
    return null;
  }

  bool isAgentInPane(String machineId, String agentId) =>
      paneOfAgent(machineId, agentId) != null;

  /// True while the KEYBOARD is in the rail rather than on the grid.
  ///
  /// Folded into [isPaneFocused] on purpose, and it does two jobs at once. The
  /// terminal re-claims the native input connection when `focused` goes false →
  /// true (TerminalPanel.didUpdateWidget), so flipping this is what hands the
  /// keys over and what takes them back. And the focus ring leaves the tile
  /// while the rail has the cursor, which is the honest thing to draw: a ring on
  /// a pane that is not receiving keys is a lie the whole feature would rest on.
  bool railFocused = false;

  /// Which row the rail's cursor is on, indexing [railRows].
  int railCursor = 0;

  bool isPaneFocused(int paneId) =>
      !railFocused && !tabStripFocused && focusedPaneId == paneId;

  /// A harness's terminal and viewers stay clear together. Keyboard focus and
  /// its ring still belong to one pane, including while a menu owns input.
  bool isPaneEmphasized(TerminalPane pane) {
    final selected = focusedPane;
    if (selected == null) return false;
    if (selected.id == pane.id) return true;
    final agentId = selected.agentId ?? selected.ownerAgentId;
    return agentId != null &&
        selected.machineId == pane.machineId &&
        agentId == (pane.agentId ?? pane.ownerAgentId);
  }

  /// True while the KEYBOARD is on the tab strip rather than in any pane.
  ///
  /// Closing the ACTIVE tab with work in it — ⌘W, the strip's own close, or
  /// its final pane going (⌘⇧W, the pane's close button, the viewer toggle) —
  /// selects the tab beside it. That tab used to take the keys at once, so
  /// somebody still typing after the close typed into an agent they never
  /// chose. Now the neighbour is shown and selected, and its terminal takes
  /// the keyboard only when the person says so: a click in it, ⏎ on the strip
  /// ([focusFromTabStrip]), a focus-pane key, a tab chosen.
  ///
  /// Folded into [isPaneFocused] like [railFocused]: a terminal claims input
  /// when `focused` goes true, which is what hands the keys over when this
  /// lets go. Held against the tab, the pane and the focus request it was set
  /// for, so anything that moves the view on — another tab, a pane opened or
  /// chosen, a reveal — lets go by itself. Never persisted: it is view intent.
  bool get tabStripFocused {
    final hold = _tabStripHold;
    return hold != null &&
        hold.tab == activeSwarmId &&
        hold.pane == focusedPaneId &&
        hold.request == _paneFocusRequest;
  }

  ({String tab, int? pane, int request})? _tabStripHold;

  /// Bumped each time a close sends the keyboard to the tab strip, so the
  /// window moves its own focus there once per close.
  int get tabStripFocusRequest => _tabStripFocusRequest;
  int _tabStripFocusRequest = 0;

  void _holdTabStrip() {
    _tabStripHold = (
      tab: activeSwarmId,
      pane: focusedPaneId,
      request: _paneFocusRequest,
    );
    _tabStripFocusRequest++;
  }

  /// ⏎ on the tab strip: the selected tab's focused pane takes the keyboard.
  void focusFromTabStrip() {
    if (!tabStripFocused) return;
    _tabStripHold = null;
    _noteNavigation();
    _paneFocusRequest++;
    notifyListeners();
  }

  /// A focus-pane key pressed while the strip holds the keyboard goes back
  /// into the grid at the pane this tab already had focused — whichever arrow
  /// it was, the way off the strip is into the tab under it.
  bool _enterGridFromTabStrip() {
    if (!tabStripFocused) return false;
    final id = focusedPaneId ?? panes.firstOrNull?.id;
    if (id == null) return false;
    focusPane(id, reveal: true);
    return true;
  }

  /// The rail as a flat list of rows, in the order it is drawn.
  ///
  /// ONE source for the cursor and for the highlight. The rail builds its own
  /// tree from the same pieces, and a second traversal that "should" agree is
  /// exactly how an arrow key ends up selecting a different row than the one
  /// lit up — so the widget reads its highlight from this list too.
  ///
  /// Local machine first, then the backend's order, which is what the rail has
  /// always drawn; a machine that is collapsed contributes its own row and none
  /// of its agents, because a cursor cannot rest on something not on screen.
  List<RailRow> railRows() {
    final rows = <RailRow>[];
    final ordered = <Machine>[
      ...machines.where((m) => stateOf(m.machineId)?.isLocalMachine == true),
      ...machines.where((m) => stateOf(m.machineId)?.isLocalMachine != true),
    ];
    for (final machine in ordered) {
      rows.add(RailRow(machineId: machine.machineId));
      if (!expandedMachines.contains(machine.machineId)) continue;
      for (final agent
          in stateOf(machine.machineId)?.agents ?? const <Agent>[]) {
        rows.add(RailRow(machineId: machine.machineId, agentId: agent.id));
      }
    }
    return rows;
  }

  /// Hand the keyboard to the rail — ⌘h off the left edge of the grid.
  ///
  /// The cursor starts on the agent the window is already looking at, so the
  /// first press of `j` steps off it rather than jumping to the top of a list
  /// of thirty. Same reasoning as the layout palette's cursor.
  void focusRail() {
    final rows = railRows();
    if (rows.isEmpty) return;
    final pane = panes.where((p) => p.id == focusedPaneId).firstOrNull;
    var at = 0;
    if (pane?.agentId != null) {
      final found = rows.indexWhere(
        (row) =>
            row.agentId == pane!.agentId && row.machineId == pane.machineId,
      );
      if (found >= 0) at = found;
    }
    railFocused = true;
    railCursor = at;
    notifyListeners();
  }

  /// Give it back. The focused tile re-claims the keys on the next frame.
  void unfocusRail() {
    if (!railFocused) return;
    railFocused = false;
    notifyListeners();
  }

  /// The row the cursor is on, or null when the rail has changed under it.
  ///
  /// Bounds-checked rather than clamped, and that distinction is the point: an
  /// agent finishing or a machine collapsing can shorten the list between a
  /// keypress and the frame that draws it, and clamping would silently light up
  /// a DIFFERENT row than the one the cursor was on. Null draws nothing, which
  /// is the honest answer for one frame.
  RailRow? railRowAt(int index) {
    final rows = railRows();
    if (index < 0 || index >= rows.length) return null;
    return rows[index];
  }

  void moveRailCursor(int delta) {
    final rows = railRows();
    if (rows.isEmpty) return;
    // Clamped, not wrapped: the rail is a column you can see the ends of, and a
    // cursor that leaps from the last machine back to the first reads as a
    // mis-key. The grid's own focus wraps because it is a loop of tiles.
    railCursor = (railCursor + delta).clamp(0, rows.length - 1);
    notifyListeners();
  }

  /// Enter on the cursor's row.
  ///
  /// A machine row toggles; an agent row opens and gives the keyboard back —
  /// because "go to this agent" is a request to work in it, and leaving the
  /// keys in the sidebar would make every open a two-step.
  Future<void> activateRailRow() async {
    final rows = railRows();
    if (railCursor < 0 || railCursor >= rows.length) return;
    final row = rows[railCursor];
    if (row.agentId == null) {
      toggleExpand(row.machineId);
      return;
    }
    railFocused = false;
    notifyListeners();
    await selectAgent(row.machineId, row.agentId!);
  }

  /// `h` in the rail — out of an agent list, then out of the rail.
  ///
  /// Two steps rather than one, and that is the vim shape: `h` at the top level
  /// leaves, `h` inside something closes it first. Pressed on an agent it jumps
  /// to that agent's machine row and folds it, which is where the eye already
  /// is; pressed on a machine row it hands the keyboard back to the grid.
  void railCollapseOrExit() {
    final rows = railRows();
    if (railCursor < 0 || railCursor >= rows.length) {
      unfocusRail();
      return;
    }
    final row = rows[railCursor];
    if (row.agentId != null) {
      final head = rows.indexWhere(
        (r) => r.machineId == row.machineId && r.agentId == null,
      );
      if (head >= 0) railCursor = head;
      toggleExpand(row.machineId);
      notifyListeners();
      return;
    }
    if (expandedMachines.contains(row.machineId)) {
      toggleExpand(row.machineId);
      return;
    }
    unfocusRail();
  }

  /// Show or hide one tile's composer textbox, and remember the choice.
  void toggleComposer(int paneId) {
    for (final pane in panes) {
      if (pane.id != paneId) continue;
      pane.composerVisible = !pane.composerVisible;
      _persistLayout();
      notifyListeners();
      return;
    }
  }

  void focusPane(int paneId, {bool reveal = false}) {
    if (!panes.any((pane) => pane.id == paneId)) return;
    final moved = focusedPaneId != paneId || railFocused;
    railFocused = false;
    // A click in a tile or a focus key is the person going back into the grid.
    _tabStripHold = null;
    // Remembered only on a REAL move. Re-focusing the tile you are already on
    // happens constantly — see the note below about why it is announced anyway
    // — and recording it would make the previous-pane command return you to
    // where you already are.
    if (moved) _previousPaneId = focusedPaneId;
    focusedPaneId = paneId;
    selectedMachineId = focusedPane?.machineId;
    // Switching TO a harness is how its news gets read. Not only the routes
    // that go through a banner or the Harnesses list: clicking the tile, the
    // rail, ⌘-number, the dial — all of them arrive here, and all of them mean
    // the same thing to somebody who was told this one wanted them.
    _seeFocusedAgent();
    _noteNavigation();
    if (reveal) _paneFocusRequest++;
    if (zoomedPaneId != null) zoomedPaneId = paneId;
    // Announced even when this tile was ALREADY focused.
    //
    // The dial can be turned by hand, and then the two disagree with nobody
    // knowing. Choosing this agent — from the rail or by clicking its tile — is
    // how someone says "no, look at THIS one", so it has to be able to say it.
    //
    // The old guard here made that impossible in exactly the case that needed
    // it. An agent that is NOT open yet gets a fresh stream, and the daemon
    // follows `terminal_open` as a side effect; one that IS open opens nothing,
    // so `app_focus` is the only thing that can move the dial — and this
    // returned before sending it. That is why a single pane always worked
    // (every switch re-attached) and a second pane broke it.
    //
    // Re-sending the same agent is safe: the daemon drops it against the dial's
    // real position (`agentId === this.dialFocus` in cableSession), which is the
    // only side that can judge, because only it knows where the dial is.
    _announceAppFocus();
    if (moved) _persistLayout();
    if (moved || reveal) notifyListeners();
  }

  String? _announcedFocusMachineId;
  String? _deviceFocusRevision;

  @visibleForTesting
  Future<bool> Function(String machineId, String? agentId)?
  focusFrameSenderForTest;

  /// Publish the selected pane to the existing local CLI connection. The CLI
  /// shares this focus with paired devices and the dial; terminal attachments
  /// and operating-system window activation do not define the selected agent.
  /// The colours the panes are actually painted with — the terminal theme in
  /// force, not the app palette by assumption (Tango is its own scheme).
  static Map<String, String> terminalThemeColours() {
    final theme = terminalScreenThemeFor(
      grid.AppTheme.palette.value,
      terminalThemeStore.value,
    );
    String hex(Color color) =>
        '#${(color.toARGB32() & 0xFFFFFF).toRadixString(16).padLeft(6, '0')}';
    return {
      'background': hex(theme.background),
      'foreground': hex(theme.foreground),
    };
  }

  /// Tells one machine's daemon the pane colours (`theme_set`, answered by
  /// the CLI's lib/hostTheme.ts). Fire-and-forget: a daemon that predates the
  /// type cannot open the envelope and goes silent, and that is nothing to
  /// put on the error strip — the pane still opens, only a TUI's palette may
  /// guess wrong there.
  void _announceTerminalTheme(String machineId) {
    if (_disposed) return;
    final connection = _pool != null || connectionForTest != null
        ? _conn(machineId)
        : null;
    if (connection == null) return;
    unawaited(
      connection
          .request(
            'theme_set',
            payload: terminalThemeColours(),
            timeout: const Duration(seconds: 5),
          )
          .catchError((Object error) {
            appLog.debug('ws', 'theme_set not applied on $machineId: $error');
            return <String, dynamic>{};
          }),
    );
  }

  /// The palette or terminal theme changed: every connected machine hears it,
  /// so a session created after this on any of them starts with the new
  /// colours and existing ones are restyled on the daemon's next scan.
  void _announceTerminalThemeEverywhere() {
    for (final entry in machineStates.entries) {
      if (entry.value.connectionStatus != ConnectionStatus.connected) continue;
      _announceTerminalTheme(entry.key);
    }
  }

  /// What a machine hears the moment its socket is up — first connect, or a
  /// reconnect after its daemon restarted, which has forgotten all of it.
  /// [machineId]'s socket, if it has one: the test's stand-in, or the pool's.
  WsConn? _connectionOf(String machineId) =>
      connectionForTest?.call(machineId) ?? _pool?[machineId];

  void _onMachineConnected(String machineId, MachineState machine) {
    machine._selectedConnection =
        connectionForTest?.call(machineId) ?? _pool?[machineId];
    _rereadDevicesAfterDaemonReconnect(machineId);
    // The daemon may have restarted: read the shared tabs again now, not in 60 s.
    if (viewer == null && machine.isLocalMachine) sharedTabs.changed();
    // A viewer build keeps its own trust group (a CLI build's daemon keeps one for it): any session
    // that comes up is the moment to compare it with this machine.
    unawaited(_syncGroup(machineId));
    _resetMachineDiscovery(machine);
    _markSessionsUnreachable(
      machine,
      'Harness reconnected; restoring terminal…',
    );
    machine.needsLink = false;
    _stopLinkRetry(machineId);
    _forgetTrustSettle(machineId);
    // A daemon that just came up — first connect, or a reconnect after it
    // restarted — has never been told what is on the grid. Without this
    // the dial goes back to beeping about tiles in plain sight until the
    // next time a pane happens to change.
    _announcedVisible.remove(machineId);
    _announceOpenPanesToDial();
    _announceVisibleAgents();
    _announceUnreadToDial();
    // ...nor which tile this window is looking at. The daemon repeats that to the dial after every
    // list push, which is what keeps the two screens from drifting apart — but it can only repeat
    // something it has been told, and until now the first telling waited for the focus to CHANGE.
    // A daemon restarted mid-session therefore had nothing to say, and a dial that re-anchored onto
    // the wrong tile stayed there.
    _announceAppFocus();
    // ...nor what colour its panes are. tmux answers a TUI's "what is my background?"
    // (OSC 10/11 — Codex picks its light or dark diff palette from it) with whichever
    // terminal attached first, unless told; this tells it, for the sessions it owns.
    _announceTerminalTheme(machineId);
    // The local CLI never hands back `connected` until it has terminated E2EE (or confirmed
    // none is needed, for its own machine) — every machine's data is ready to load right away,
    // with no separate app-side readiness gate to wait on anymore.
    if (machine.isLocalMachine) {
      machine.transportMode = MachineTransportMode.localPlaintext;
      // The socket that just connected IS the endpoint. A machine refresh that ran while the
      // daemon was restarting (connection refused, or still scanning) had probed nothing and
      // cleared this — and with it `usesLocalTransport`, which `_canAttachPane` and the pane
      // header both read. The socket then came back on its own 1s retry, `nodeOnline` went true,
      // the offline poll (the one thing that would have re-probed) stopped, and the tiles sat on
      // "Offline" over a live terminal with nothing left to restore them. Measured 2026-09-18 21:50.
      machine.localEndpoint ??= _cliEndpoint;
    } else {
      machine.transportMode = MachineTransportMode.cloudE2ee;
    }
    // Route through _applyNodeStatus (not just `machine.nodeOnline = true`) for every machine,
    // not only the local one — a successful select IS the machine being reachable again, and
    // this is what lets a pending agent (captured below on disconnect) reattach automatically
    // instead of leaving the user stuck on the empty "select a machine" placeholder.
    unawaited(_applyNodeStatus(machine, true, why: 'socket connected'));
    unawaited(_loadMachineData(machine, force: true));
    // An install this socket was carrying when it dropped went on without it
    // (the daemon never heard the socket go); its outcome is in the list, so
    // the list is asked again now that someone is there to ask.
    if (_dshProbeOnReconnect.remove(machineId)) {
      unawaited(probeDsh(machineId, force: true));
    }
    _startAgentSyncTimer(machineId);
  }

  @visibleForTesting
  void onMachineConnectedForTest(String machineId) {
    final machine = machineStates[machineId];
    if (machine == null) return;
    machine.connectionStatus = ConnectionStatus.connected;
    _onMachineConnected(machineId, machine);
  }

  void _announceAppFocus() {
    final pane = focusedPane;
    // A viewer is its agent's, so focusing it is focusing that agent: the dial
    // and the daemon see one agent at this desk, not a tile they cannot name.
    final agentId = pane?.agentId ?? pane?.ownerAgentId;
    final machineId = agentId == null ? null : pane?.machineId;
    final previousMachineId = _announcedFocusMachineId;
    _announcedFocusMachineId = machineId;
    if (previousMachineId != null && previousMachineId != machineId) {
      _sendAppFocus(previousMachineId, null);
    }
    _announcedFocusAgentId = machineId == null ? null : agentId;
    if (machineId != null) _sendAppFocus(machineId, agentId);
    // The selected pane moved with a tab switch or a close, and the tiles on screen moved with it.
    _announceVisibleAgents();
  }

  String? _announcedFocusAgentId;

  /// The signature of the `visibleAgents` last sent to each machine's daemon, so a change in what is
  /// on screen is sent once and a repeat is not. Forgotten on (re)connect: a new daemon has no list.
  final Map<String, String> _announcedVisible = {};

  /// Whether the super tab [swarmId] shows its terminal canvas (it hides it behind chat or the
  /// member list, with the panes still mounted `Offstage`). Only the workspace knows.
  String? _superTerminalsShownSwarm;

  void setSuperTabTerminalsShown(String swarmId, bool shown) {
    final next = shown ? swarmId : null;
    if (_superTerminalsShownSwarm == next ||
        (!shown && _superTerminalsShownSwarm != swarmId)) {
      return;
    }
    _superTerminalsShownSwarm = next;
    _announceVisibleAgents();
  }

  /// The agents on [machineId] whose tiles a person can see in this window right now: the active
  /// tab's mounted, non-`Offstage` tiles (the zoomed one alone while zoomed), and none while the
  /// window is minimized or hidden to the tray. A window that is merely behind another app still
  /// shows its tiles, so it still lists them; only hidden/paused/detached empty the list.
  List<String> visibleAgentIds(String machineId) {
    switch (lifecycle()) {
      case AppLifecycleState.hidden:
      case AppLifecycleState.paused:
      case AppLifecycleState.detached:
        return const [];
      case AppLifecycleState.resumed:
      case AppLifecycleState.inactive:
      case null:
        break;
    }
    final tab = activeSwarm;
    if (tab.isStore || tab.isOrchestrator) return const [];
    if (tab.isSuperTab && _superTerminalsShownSwarm != tab.id) return const [];
    return [
      for (final pane in tab.panes)
        if (pane.machineId == machineId &&
            (tab.zoomedPaneId == null || pane.id == tab.zoomedPaneId))
          ?pane.agentId,
    ];
  }

  /// Tell each daemon on this computer which terminals are on screen, when that changed.
  void _announceVisibleAgents() {
    final pool = _pool;
    if (pool == null) return;
    for (final machineId in pool.machineIds) {
      final list = visibleAgentIds(machineId);
      if (_announcedVisible[machineId] == list.join(',')) continue;
      if (_deskConnection(machineId) == null) continue;
      _sendAppFocus(
        machineId,
        machineId == _announcedFocusMachineId ? _announcedFocusAgentId : null,
      );
    }
  }

  /// The socket [machineId]'s desk frames ride — `app_focus`, `app_panes`, `app_swarms`, `app_unread`,
  /// `agent_seen` — or null. They are this window's own state for the daemon on this computer
  /// (cli/src/localWsServer.ts), so only a loopback connection carries them: a viewer's are relayed
  /// to the machine, which refuses them unsealed and would hand the relay question prompts and tab
  /// names on the way. A viewer build sends none.
  WsConn? _deskConnection(String machineId, {WsPool? pool}) {
    final connection = (pool ?? _pool)?[machineId];
    return connection != null && connection.isLocal ? connection : null;
  }

  void _sendAppFocus(String machineId, String? agentId) {
    // Never create a socket just to move focus, and never queue stale focus
    // across a reconnect. The connected callback reasserts the current pane.
    final send = focusFrameSenderForTest;
    final visible = visibleAgentIds(machineId);
    _announcedVisible[machineId] = visible.join(',');
    final pending = send != null
        ? send(machineId, agentId)
        : _deskConnection(machineId)?.sendTerminalFrame('app_focus', {
            'agentId': agentId,
            // Every terminal of this machine that is on screen; [] for a hidden window. An older
            // daemon ignores it.
            'visibleAgents': visible,
            if (_deviceFocusRevision != null)
              'focusRevision': _deviceFocusRevision,
          });
    if (pending != null) unawaited(pending.catchError((_) => false));
  }

  /*
   * Change one device's settings.
   *
   * Addressed by the fleet's id: a desk can hold two robots, and a preference belongs to the glass it
   * was set on. Only the named fields go — absent means unchanged, so two windows open on one device
   * cannot overwrite each other with whatever each of them last saw.
   *
   * The return value confirms transport delivery only. Nothing is written here optimistically.
   * The device answers with what it now HOLDS, which arrives as the next `dial_status`; that is
   * also what corrects this window when the change was refused.
   */
  Future<bool> setDeviceSettings(String id, Map<String, Object?> patch) async {
    if (patch.isEmpty) return false;
    final target = dial.devices.where((device) => device.id == id).firstOrNull;
    if (target == null || !target.attached || target.updating != null) {
      return false;
    }
    final machineId = localMachineState?.machine.machineId;
    final connection = machineId == null ? null : _pool?[machineId];
    if (connection == null) return false;
    try {
      return await connection.sendTerminalFrame('dial_settings', {
        ...patch,
        'id': id,
      });
    } catch (_) {
      return false;
    }
  }

  /// Tell the daemon which agents have a tile on the grid, so the dial can stay
  /// quiet about a turn that finished in front of the person.
  ///
  /// An OPEN tile counts as seen. Not a focused one: with four tiles all four
  /// are on screen, and the window has no honest way to say which the eye is
  /// on. Nor is the window's own focus consulted — a decision, not an
  /// oversight: it means a turn that lands while the app is behind a browser
  /// stays silent, and the alternative is a dial that beeps about tiles you are
  /// looking straight at.
  ///
  /// Sent to EVERY connected daemon on this computer's loopback, with the full
  /// list across all machines. The dial belongs to whichever daemon owns the
  /// cable, and only a complete roster lets that one judge; the others store a
  /// list they never use, which costs nothing and saves the window from having
  /// to know which is which. Never over a relayed connection: see
  /// [_deskConnection].
  /// The newest eight unread harnesses, for a dial that has lost its drawer.
  ///
  /// The dial keeps its drawer in RAM, so a reboot — an OTA, a replug, a flash —
  /// wipes it while this window still holds its marks. Measured: a turn ended
  /// at 17:46:19, the dial came back at 17:46:26, a question arrived at
  /// 17:46:28, and the two screens then read 2 and 1 forever.
  ///
  /// Sent on every change rather than asked for: the daemon holds the latest and
  /// can hand it over the moment a cable attaches, without a round trip to a
  /// window that may be busy. Ids and kinds only — the daemon already knows each
  /// agent's name, machine and last recap, and re-deriving them here would be a
  /// second place for them to be wrong. The desktop inbox can retain more than
  /// the dial's eight rows; sending only that window preserves the wire limit.
  void _announceUnreadToDial() {
    final pool = _pool;
    if (pool == null) return;
    final items = [
      for (final mark in agentUnread.newestFirst.take(8))
        {
          'agentId': mark.agentId,
          'machineId': mark.machineId,
          'question': mark.kind == AlertKind.needsYou,
          'readToken': agentUnread.readTokenFor(mark.machineId, mark.agentId),
          // A QUESTION'S OWN WORDS, because nobody else has them. The daemon
          // fills in the recap for a finished turn from what it summarised, but
          // an open question lives here — in `blockedAgents` — and a dial that
          // rebooted has no memory of having asked it. Without this its drawer
          // row arrives blank and falls back to the word the row type used to
          // assume: "done", on a question nobody has answered.
          if (mark.kind == AlertKind.needsYou)
            'text':
                machineStates[mark.machineId]
                    ?.blockedAgents[mark.agentId]
                    ?.prompt ??
                '',
        },
    ];
    for (final machineId in pool.machineIds) {
      _deskConnection(machineId)
          ?.sendTerminalFrame('app_unread', {'items': items})
          .catchError((_) => false)
          .ignore();
    }
  }

  /// Re-send the tile roster because the WINDOW moved, not because the tiles
  /// did. Public so the lifecycle listener can say so; the roster itself is
  /// unchanged and the `foreground` flag riding with it is the point.
  void announceWindowForeground() {
    _announceOpenPanesToDial();
    _announceVisibleAgents();
  }

  bool _announceFromDevice = false;
  int _devicePick = 0;
  int _dialThreadToken = 0;

  /// How long the dial's thread waits for its root to reach the chat.
  @visibleForTesting
  Duration dialThreadWaitForTest = const Duration(seconds: 10);

  /// The project each Swarm tab's row last told the dial, by backend tab id;
  /// null while its Swarm had not loaded. See `onSnapshot`.
  final _dialProjects = <String, String?>{};

  String? _dialProject(SuperTabController controller) =>
      controller.snapshot?.projectFor(controller.selectedId)?.id;

  /// The project open in this Swarm tab for its dial row, kept as told.
  String? _rememberDialProject(String tabId) =>
      _dialProjects[tabId] = switch (superTabs.peek(tabId)) {
        final controller? => _dialProject(controller),
        null => null,
      };

  /// The conversation open in this Swarm tab (its Lead's, Chat with PM or a
  /// group), which the round dial's face follows (design
  /// 2026-10-28-round-dial-swarm-chat). Left out on the machines view and
  /// before the Swarm has loaded: the dial then shows each project's Lead.
  /// A change of it re-announces through `onSelection`, as a project's does.
  String? _dialConversation(String tabId) {
    final controller = superTabs.peek(tabId);
    if (controller == null || controller.devicesSelected) return null;
    final id = controller.selectedId;
    return controller.snapshot?.conversation(id) == null ? null : id;
  }

  /// The thread open beside that conversation, by its root, shown or hidden:
  /// the round dial shows and answers it while it stays open.
  String? _dialThread(String tabId) => _dialConversation(tabId) == null
      ? null
      : superTabs.peek(tabId)?.threadOnScreen;

  /// The tile roster and the tabs, to every daemon this window reaches over
  /// its loopback ([_deskConnection]) — never a relayed machine's.
  void _announceOpenPanesToDial() {
    final pool = _pool;
    if (pool == null) return;
    // Every tile that HAS an agent id, shells included. A terminal used to be
    // left out here — the dial drives agents, and a shell has no turn to watch
    // — but leaving it out is what made the dial disagree with its own promise
    // ("the dial follows the app. It shows what the app shows"): the window
    // drew a tile the dial had no row for, so it could neither be reached nor
    // explained. It is a real registry row on the daemon, with an id, and the
    // dial now draws it as what it is and stops short of driving it. The same
    // row becomes an ordinary agent the moment an engine is typed into it
    // (`registry.adoptEngine`), which `_upsertAgent` re-announces.
    //
    // A viewer tile still names nothing: it belongs to its agent through
    // `ownerAgentId` and carries no `agentId` of its own, so it is counted in
    // `panes` below and named nowhere.
    bool onDial(TerminalPane pane) => pane.agentId != null;

    final agentIds = <String>[
      for (final pane in panes)
        if (onDial(pane)) pane.agentId!,
    ];
    // THE ACTIVE SWARM'S SHAPE, for a device with a face big enough to draw it.
    //
    // This used to say "names and member ids only — the layout inside a swarm is this window's
    // business", and for the round dial that was right: 466px of circle holds one tile, so there was no
    // shape to send. The square device draws the tab as a grid, and a grid that does not follow the
    // window is worse than no grid — it puts an agent somewhere it is not (owner, 2026-09-27: "change
    // layout trên app, dưới device ko thấy change theo").
    //
    // RECTANGLES, NOT A PRESET NAME. Sending `cols3` would make the far side re-derive the geometry
    // from it, which is the duplication `pane_preset.dart` exists to prevent — and it could not express
    // `auto` (whose column count this window MEASURES) or a manual resize at all. These are the very
    // rectangles this window laid out, in thousandths so they cross as integers.
    //
    // ONE ROW PER PANE, including the ones the device cannot drive: a shell or a viewer holds its place
    // in the grid, and dropping it would leave the shape with a hole in it. `agentId` is empty for
    // those, which is how the far side knows to draw it as a pane rather than as an agent.
    final shape = activeTileShape;
    final activeTiles = shape == null
        ? const <Map<String, Object>>[]
        : [
            for (var i = 0; i < shape.length && i < panes.length; i++)
              {
                'x1': (shape[i].left * 1000).round(),
                'y1': (shape[i].top * 1000).round(),
                'x2': (shape[i].right * 1000).round(),
                'y2': (shape[i].bottom * 1000).round(),
                'agentId': panes[i].agentId ?? '',
              },
          ];
    // The swarms travel with the tiles: the dial names the one on screen above the agent and offers
    // the others, and a pick there comes back as `dial_swarm`.
    final fromDevice = _announceFromDevice;
    final swarmRows = [
      for (final swarm in swarms)
        {
          'id': swarm.id,
          'name': swarm.name,
          // The backend tab and the project open in it, for a device that
          // draws the Swarm's Leads and asks for one by these ids. Left out
          // while the tab has not loaded: a project is not guessed.
          if (swarm.superTabId case final tabId?) ...{
            'superTabId': tabId,
            'projectId': ?_rememberDialProject(tabId),
            'conversationId': ?_dialConversation(tabId),
            'threadRoot': ?_dialThread(tabId),
          },
          'agentIds': [
            for (final pane in swarm.panes)
              if (onDial(pane)) pane.agentId!,
          ],
          // NOT the length of `agentIds`, and the difference is the whole point
          // of sending it. A tab holding nothing but a shell — or nothing but a
          // viewer — names no agent the dial can drive, so its `agentIds` is
          // empty exactly as an untouched New Harness tab's is. The dial read
          // that emptiness as "nothing here" and left such a tab out of its
          // switcher, so a tab you could see while standing on it became
          // unreachable the moment you left it. This answers what the switcher
          // is actually asking — is there anything on this tab — and this side
          // is the only one that knows.
          'panes': swarm.panes.length,
        },
    ];
    for (final machineId in machineStates.keys) {
      final connection = _deskConnection(machineId, pool: pool);
      if (connection == null) continue;
      unawaited(
        connection
            .sendTerminalFrame('app_panes', {
              'agentIds': agentIds,
              // WHETHER THESE TILES ARE ACTUALLY IN FRONT OF ANYBODY.
              //
              // The daemon decides from this list whether a finished turn is
              // already on screen, and the list alone cannot say: every pane
              // keeps its place on the tab while this window sits behind a
              // browser. The dial therefore stayed quiet about work nobody
              // could see, which is the one case the notification exists for —
              // and this window, which DOES check (see `_visibleOnTab`), spoke
              // up. Two screens, two answers, from the same tab.
              //
              // Sent with the roster rather than on its own so the pair can
              // never be read half-updated. An older daemon ignores it and
              // behaves as it does today.
              'foreground': lifecycle() == AppLifecycleState.resumed,
            })
            .catchError((_) => false),
      );
      unawaited(
        connection
            .sendTerminalFrame('app_swarms', {
              'active': activeSwarmId,
              'swarms': swarmRows,
              // Set on the announces a device's pick caused, so the daemon
              // does not send the pick back to the device as a new focus.
              if (fromDevice) 'fromDevice': true,
              // Only the active one's. It is the only grid the device draws, and sending every tab's
              // geometry would be two dozen shapes to carry one.
              'tiles': activeTiles,
            })
            .catchError((_) => false),
      );
    }
  }

  /// Machines whose link prompt the user has waved away.
  ///
  /// Dismissing cannot mean "deselect": [activeMachineState] falls back to the
  /// first expanded machine, so clearing the selection would often re-arrive at
  /// the very machine that was just closed. And it must not mean "linked" —
  /// nothing changed about the machine, which still cannot be read and still
  /// says so in the rail. It means only that the pane stops insisting.
  ///
  /// Held in memory, not on disk, and cleared the moment the machine is chosen
  /// again: someone who clicks that row is asking to see it.
  final Set<String> _dismissedLinkPrompts = {};
  String? _requestedMachineLink;

  /// Explicit setup navigation must remain available even when a browser has
  /// another connected machine and suppresses its automatic startup picker.
  String? get requestedMachineLink => _requestedMachineLink;

  MachinesRequest? _machinesRequest;

  /// Machines was asked for from outside the workspace — a device band, the review line under a
  /// password prompt — and the workspace has not opened it yet.
  MachinesRequest? get machinesRequest => _machinesRequest;

  /// Opens Machines, where the account's computers, phones and apps are listed: [devicePub] selects
  /// that device, [phones] the first phone or app.
  void requestMachines({String? devicePub, bool phones = false}) {
    if (_disposed) return;
    _machinesRequest = (devicePub: devicePub, phones: phones);
    notifyListeners();
  }

  /// The workspace takes the request it is about to open.
  MachinesRequest? takeMachinesRequest() {
    final request = _machinesRequest;
    _machinesRequest = null;
    return request;
  }

  bool _sharedTabsRequest = false;

  /// Settings ▸ Tab invites was asked for from outside Settings (the invitation notice) and the
  /// workspace has not opened it yet.
  bool get sharedTabsRequested => _sharedTabsRequest;

  void requestSharedTabs() {
    if (_disposed) return;
    _sharedTabsRequest = true;
    notifyListeners();
  }

  /// The workspace takes the request it is about to open.
  bool takeSharedTabsRequest() {
    final requested = _sharedTabsRequest;
    _sharedTabsRequest = false;
    return requested;
  }

  String? _newHarnessRequest;

  /// The desk tab a New Harness was asked for from outside the workspace ("New
  /// Harness here" in Add harnesses), until the workspace opens it.
  String? get newHarnessRequested => _newHarnessRequest;

  /// New Harness in shared tab [sharedTabId], in its desk tab: the derived one
  /// for a member (R1, [memberDeskTabId]), the tab it shared for the owner.
  void requestNewHarnessInSharedTab(String sharedTabId) {
    if (_disposed) return;
    final desk = sharedDeskTabId(sharedTabId);
    if (desk == null || !swarms.any((s) => s.id == desk)) return;
    _newHarnessRequest = desk;
    notifyListeners();
  }

  /// The desk tab shared tab [sharedTabId] shows in: the tab the owner
  /// shared, or a member's derived one (R1), also before the roster is read.
  String? sharedDeskTabId(String sharedTabId) {
    final me = sharedTabs.snapshot.me?.accountId;
    final tab = sharedTabs.snapshot.tabs
        .where((t) => t.sharedTabId == sharedTabId)
        .firstOrNull;
    return tab == null || me == null
        ? memberDeskTabId(sharedTabId)
        : tab.deskTabId(me);
  }

  String? takeNewHarnessRequest() {
    final request = _newHarnessRequest;
    _newHarnessRequest = null;
    return request;
  }

  void acknowledgeMachineLinkRequest(String machineId) {
    if (_requestedMachineLink == machineId) _requestedMachineLink = null;
  }

  bool isLinkPromptDismissed(String machineId) =>
      _dismissedLinkPrompts.contains(machineId);

  void dismissLinkPrompt(String machineId) {
    if (_disposed) return;
    acknowledgeMachineLinkRequest(machineId);
    if (_dismissedLinkPrompts.add(machineId)) notifyListeners();
  }

  /// The person asked to see the prompt again — a deliberate open, not the
  /// reactive gate. Without this, every way in that does not go through
  /// [showMachinePane] (the welcome's Machines row) opened a dialog that its
  /// own "still needed?" check closed on the first frame: one popup, then
  /// nothing, for as long as the app ran.
  void revisitLinkPrompt(String machineId) {
    if (_dismissedLinkPrompts.remove(machineId)) notifyListeners();
  }

  // ── ⌘B: a typed task, and which agent it belongs to ────────────────────────────────────────────

  /// The machine this window is running ON — where the daemon that ANSWERS ⌘B lives.
  ///
  /// It is not the scope of the search: the daemon weighs agents on every machine and answers with the
  /// one each pick belongs to. This is only the socket the question travels on, because the router, the
  /// registry and the recap mirror it reads are all on this computer.
  MachineState? get localMachineState {
    for (final state in machineStates.values) {
      if (state.isLocalMachine) {
        return state; // the flag is the STATE's, not the machine row's
      }
    }
    return null;
  }

  /// Default host for machine-scoped tools. A dialog freezes this choice while someone edits it.
  /// Native windows retain their local host; a browser uses the focused linked host first.
  MachineState? get ownedActionMachine {
    if (viewer == null) return localMachineState;
    for (final id in [
      focusedPane?.machineId,
      selectedMachineId,
      ...machineStates.keys,
    ]) {
      final machine = machineStates[id];
      if (machine != null &&
          !machine.machine.isShared &&
          !machine.needsLink &&
          machine.nodeOnline != false &&
          machine.connectionStatus == ConnectionStatus.connected) {
        return machine;
      }
    }
    return null;
  }

  /// Ask the daemon which agent a typed task belongs to. Sends nothing.
  ///
  /// Rides the app's own rpc convention (`ws_conn.request`), so the pending map, the timeout and the
  /// logging are the ones every other request already uses. Returns null when there is nobody to ask —
  /// no local machine, or its socket is not up — which the palette says out loud rather than spinning.
  /// Answer the daemon about a spoken task it asked this window to route.
  ///
  /// Fire and forget, and correlated by `voiceId` rather than by the rpc convention ⌘B uses: the question
  /// travelled the other way this time, so the pending id belongs to the daemon and this is a report, not
  /// a request. Sent back to the machine that ASKED — with two daemons attached, answering the selected
  /// one leaves the asker waiting on a reply that went to a stranger.
  void reportVoiceRoute(
    String machineId,
    String voiceId,
    String state,
    String agentId,
  ) {
    final connection = _pool?[machineId];
    if (connection == null) return;
    unawaited(
      connection
          .sendTerminalFrame('voice_route_reply', {
            'voiceId': voiceId,
            'state': state,
            if (agentId.isNotEmpty) 'agentId': agentId,
          })
          .catchError((_) => false),
    );
  }

  Future<RouteAnswer?> routeTask(String text) async {
    final machineId = ownedActionMachine?.machine.machineId;
    final connection = machineId == null
        ? null
        : viewer == null
        ? (_pool?[machineId])
        : _conn(machineId);
    if (connection == null || !connection.isReady) return null;
    try {
      final reply = await connection.request(
        'route_task',
        payload: {'text': text},
        // Over the daemon's own classification budget — which is 20s on this path — plus room for
        // gathering the candidates and the round trip. A request that gives up BEFORE the router does
        // leaves the person with nothing WHILE the answer is on its way, which is the one outcome worse
        // than waiting; and at exactly 20s each it would be a coin toss which of the two fired first.
        timeout: const Duration(seconds: 35),
      );
      return RouteAnswer.fromJson(reply);
    } catch (_) {
      // A timeout or a transport failure is not an error the person can act on — the palette shows the
      // candidates it has and lets them choose, which is the same thing it does for a weak answer.
      return null;
    }
  }

  /// ⌘O's ranking of the person's sessions for words still being typed (docs/design/2026-10-09-auto-router.md).
  ///
  /// ⌘B's decision for a task (docs/design/2026-10-09-auto-router.md): the router, an experiment of its
  /// own in this computer's daemon (cli/src/services/router.ts), says which of [choices]' sessions the
  /// task belongs to, or that it is new work and how to set it up — Jev's pick, or new work when Jev is unsure. The card
  /// acts on it at once, through this app's own doors.
  ///
  /// A daemon that predates the router answers `UNSUPPORTED` at once and is not asked again until the
  /// app restarts; the card then asks Boss mode's old router, as it always did. Every other way the
  /// router can fail — Jev unreachable, the router busy, down or slow, an answer naming a session it was
  /// not offered — is a decision not made, which the card says and acts on by sending nothing: the old
  /// router sends on its own when it is confident, and that is not what ⌘B promised.
  Future<TaskRouteDecision?> routeDecide(
    String text,
    TaskRouteChoices choices,
  ) async {
    if (_routeDecideUnsupported) return null;
    final machineId = localMachineState?.machine.machineId;
    final connection =
        machineId == null || (_pool == null && connectionForTest == null)
        ? null
        : _conn(machineId);
    if (connection == null || !connection.isReady) return null;
    final last = lastRoutedTask;
    appLog.info(
      'route',
      'deciding over ${choices.sessions.length} sessions, ${choices.projects.length} projects, '
          '${choices.agents.length} agents',
    );
    try {
      final reply = await connection.request(
        'route_decide',
        payload: {
          'text': text,
          ...choices.toPayload(),
          if (last != null && choices.sessions.containsKey(last.id))
            'last': {
              'id': last.id,
              'agoMs': DateTime.now().difference(last.at).inMilliseconds,
            },
        },
        timeout: const Duration(seconds: 20),
      );
      return TaskRouteDecision.fromJson(reply, choices) ??
          const TaskRouteDecision.unavailable(
            'the router named a session it was not offered',
          );
    } on WsRequestFailure catch (failure) {
      if (failure.code == 'UNSUPPORTED') {
        _routeDecideUnsupported = true;
        return null;
      }
      return TaskRouteDecision.unavailable(
        failure.code == 'JEV_UNAVAILABLE'
            ? failure.detail ?? ''
            : 'the router answered ${failure.code}',
      );
    } catch (error) {
      appLog.warn('route', 'the router did not answer', error: error);
      return const TaskRouteDecision.unavailable('the router did not answer');
    }
  }

  bool _routeDecideUnsupported = false;

  /// A session's last turns as its machine tells them (`agent_recent`): the person's prompts (`asks`) and
  /// each turn's summary (`events`). Empty when the machine could not say.
  Future<Map<String, dynamic>> readRecentTurns(
    String machineId,
    String agentId,
  ) async {
    if (_pool == null && connectionForTest == null) return const {};
    try {
      final reply = await _conn(machineId).request(
        'agent_recent',
        payload: {'agentId': agentId, 'n': 3},
        timeout: const Duration(seconds: 4),
      );
      return reply['error'] != null ? const {} : reply;
    } catch (_) {
      return const {};
    }
  }

  /// The session ⌘B last sent a task to, which the router tells Jev so a follow-up finds it.
  ({String id, DateTime at})? lastRoutedTask;

  /// The pane a task just landed in — ⌘B's receipt: its rim lights once (`pane_grid.dart`), so the eye
  /// sees where the words went, in whichever tab. [seq] tells one landing from the next on the same pane.
  final paneLanding =
      ValueNotifier<
        ({String machineId, String agentId, int seq, DateTime at})?
      >(null);
  int _landings = 0;

  void markLanding(String machineId, String agentId) => paneLanding.value = (
    machineId: machineId,
    agentId: agentId,
    seq: ++_landings,
    at: DateTime.now(),
  );

  /// The landing is over: a pane of that session opened later (reopened from ⌘P, restored at sign-in)
  /// must not light for words that landed long ago.
  void endLanding(int seq) {
    if (paneLanding.value?.seq == seq) paneLanding.value = null;
  }

  /// ⌘B's send: the session's pane comes forward and the task goes into its prompt, through this app's
  /// own door on any machine (`deliverTask`). [stillWanted] is asked just before the words are typed:
  /// the pane comes forward first, and a person who sees the wrong one and presses Esc stops the send.
  /// Returns what went wrong, or null.
  ///
  /// A stopped session is resumed first, its own conversation, and its pane comes forward only once its
  /// terminal is up — as ⌘P opens one, so a resume that fails leaves no pane behind and says why, and
  /// an Esc while it resumes sends nothing.
  Future<String?> sendTaskToSession(
    String machineId,
    String agentId,
    String task, {
    bool Function()? stillWanted,
  }) async {
    if (await resumeStoppedSession(machineId, agentId) case final failure?) {
      return failure;
    }
    if (stillWanted != null && !stillWanted()) return 'Nothing was sent.';
    bringSessionForward(machineId, agentId);
    return deliverTask(
      this,
      machineId: machineId,
      agentId: agentId,
      task: task,
      stillWanted: stillWanted,
    );
  }

  /// The session's own pane, wherever it is: its tab comes forward and the pane takes focus. Only a
  /// session with no pane in any tab gets a new one, here. 2026-10-10: a task for "Personal AI
  /// Computer" opened a second pane on it in the current tab while its own sat in the Backlog tab.
  ///
  /// The pane revealed is then selected, as a click on it would: a pane in a tab behind this one that has
  /// no terminal yet (restored after a restart, say, or a session just resumed) is attached here, since
  /// nothing attaches a pane in a tab nobody was looking at.
  void bringSessionForward(String machineId, String agentId) {
    revealAgentView(machineId, agentId);
    unawaited(selectAgent(machineId, agentId));
  }

  /// Commit: deliver the task, then bring the agent onto the grid the way a rail click does.
  ///
  /// The daemon delivers it through the SAME door as the web's messages and the dial's — queueing,
  /// retries and the per-engine slash-command adaptation are not re-implemented for the caller that
  /// types instead of speaking.
  /// Commit: deliver the task, then bring the agent onto the grid the way a rail click does.
  ///
  /// Returns null when it landed, or a sentence saying why it did not — which the palette shows instead
  /// of closing. It ASKS rather than tells for a reason measured on the desk: the remote leg carries no
  /// ack of its own, so a machine that has gone deaf takes the turn and nothing comes back. A confident
  /// route closes this window silently, so without an answer that is a task that vanished with no mark
  /// anywhere — the worst outcome this flow can produce.
  ///
  /// [agentMachineId] is the agent's OWN machine, which is not this one when the router reached across.
  Future<String?> sendRoutedTask(
    String agentId,
    String agentMachineId,
    String text,
  ) async {
    final localId = viewer == null
        ? localMachineState?.machine.machineId
        : agentMachineId.isNotEmpty
        ? agentMachineId
        : ownedActionMachine?.machine.machineId;
    if (localId == null) return 'Connect a machine to send a task.';
    final targetMachine = stateOf(localId);
    if (viewer != null &&
        (targetMachine == null ||
            targetMachine.machine.isShared ||
            targetMachine.needsLink ||
            targetMachine.nodeOnline == false ||
            targetMachine.connectionStatus != ConnectionStatus.connected)) {
      return 'Reconnect this machine to send the task.';
    }
    final connection = viewer == null ? (_pool?[localId]) : _conn(localId);
    if (connection == null || !connection.isReady) {
      return 'Reconnect this machine to send the task.';
    }
    // Desktop dispatches through its local daemon; a browser uses the agent's linked owner.
    // Both enter the same daemon task-delivery path, including refusal acknowledgements.
    try {
      final reply = await connection.request(
        'route_send',
        payload: {'agentId': agentId, 'text': text},
        timeout: const Duration(seconds: 15),
      );
      if (reply['ok'] != true) {
        final machine = (reply['machine'] as String?) ?? '';
        final reason =
            (reply['reason'] as String?) ?? 'it could not be delivered';
        return machine.isEmpty
            ? 'Not sent — $reason.'
            : 'Not sent to $machine — $reason.';
      }
    } catch (_) {
      return 'The daemon did not answer. Nothing was sent.';
    }
    // …the PANE opens on the agent's machine. Falling back to this computer would open a tile for an
    // agent it does not have and leave the person looking at an empty terminal.
    final target = agentMachineId.isNotEmpty ? agentMachineId : localId;
    if (!revealAgentView(target, agentId)) await selectAgent(target, agentId);
    return null;
  }

  MachineState? get activeMachineState {
    final terminal = activeTerminal;
    if (terminal != null) return machineStates[terminal.machineId];
    final selected = selectedMachineId;
    if (selected != null) return machineStates[selected];
    return expandedMachines.isEmpty
        ? null
        : machineStates[expandedMachines.first];
  }

  Future<void> selectAutonomousEnv(String value) async {
    if (value != 'prod' && value != 'stag') return;
    _autonomousEnv = value;
    config = AppConfig(
      apiBaseUrl: config.apiBaseUrl,
      autonomousEnv: value,
      localCliBaseUrl: config.localCliBaseUrl,
    );
    _lastError = null;
    notifyListeners();
    await _store?.saveEnvironment(value);
  }

  /// How long into startup each step finished, in ms, for the log line and for tests. Task #2169.
  @visibleForTesting
  Map<String, int> get startupTimings => Map.unmodifiable(_startupTimings);
  final _startupTimings = <String, int>{};
  final _startupClock = Stopwatch();
  void _markStartup(String step) {
    speedMarks.launch(step);
    if (_startupClock.isRunning)
      _startupTimings[step] = _startupClock.elapsedMilliseconds;
  }

  /// Set by any install during this boot: what the CLI said before it is out of date.
  bool _installedThisBoot = false;

  Future<void> bootstrap() async {
    _startupTimings.clear();
    _startupClock
      ..reset()
      ..start();
    _installedThisBoot = false;
    final localFixture = localManualFixture;
    if (localFixture != null) {
      _bootstrapLocalManual(localFixture);
      return;
    }
    try {
      if (_store != null) {
        try {
          config = await _store.load().timeout(const Duration(seconds: 5));
        } catch (error) {
          // Connection settings are optional local preferences. An unavailable
          // state file must not invalidate an otherwise recoverable SSO flow;
          // use the store's safe cached/default production config.
          debugPrint(
            'bootstrap: config store unavailable, using defaults: $error',
          );
          config = _store.config;
        }
        // Forced, not read from persisted config: staging is a dev-only
        // escape hatch with no UI to reach it anymore (see login_screen.dart
        // history) — a stale `stag` value saved before that removal must
        // never silently resurrect it.
        _autonomousEnv = 'prod';
        api = _newApiClient();
        _skippedDesktopUpdateVersion = _store.skippedDesktopUpdateVersion;
      }
      // A viewer installs nothing and is updated by its store: provisioning and the updater both
      // serve a computer that runs the harness CLI. The updater is not merely useless there — it
      // throws on an architecture it has no channel for (`ios_arm64`), from inside bootstrap.
      if (viewer == null) {
        if (await _selfInstallTookOver()) return;
        if (!_selfInstallUnavailable) {
          _startUpdateChecking();
        }
        // Beside the tool probe, as neither waits on the other (task #2169). A fresh computer has no CLI yet: a check that
        // fails is asked again after. One from before a sign-out or an install says nothing about now.
        final askedAt = _authRevision;
        final early = cliLogin
            .checkStatus()
            .then<CliAuthStatus?>((status) {
              _markStartup('signed-in check');
              return status;
            })
            .catchError((Object _) => null);
        final environmentReady = await _prepareEnvironment();
        _markStartup('tools');
        if (!environmentReady) return;
        await _continueAfterEnvironmentReady(
          early: _installedThisBoot || askedAt != _authRevision ? null : early,
        );
        return;
      }
      await _continueAfterEnvironmentReady();
    } catch (error, stack) {
      debugPrint('bootstrap: fallback to login after error: $error\n$stack');
      currentUser = null;
      status = AppStatus.unauthenticated;
      if (viewer != null) {
        _lastError = 'Could not complete sign-in. Please sign in again.';
      }
      notifyListeners();
    }
  }

  /// A zip copy yields to Harness.exe; installed copies schedule cleanup.
  Future<bool> _selfInstallTookOver() async {
    final selfInstall = windowsSelfInstall;
    if (selfInstall == null) return false;
    switch (await selfInstall.ensureInstalled()) {
      case Relaunching():
        appLog.info('setup', 'handing over to Harness.exe --install');
        flushAppLog(durable: true);
        _exitApp(0);
        return true;
      case SelfInstallFailed(:final message):
        _selfInstallUnavailable = true;
        appLog.warn('setup', message);
        return false;
      case AlreadyInstalled():
        return false;
    }
  }

  /// Runs before we invoke a single Harness subcommand. A fresh mac used to
  /// fail here with a generic Sign in error because `harness` and its Node
  /// runtime were absent; provisioning now makes that a visible, recoverable
  /// first-run phase instead.
  Future<bool> _prepareEnvironment() async {
    // A viewer has nothing to provision. The provisioner looks for a shell, the
    // POSIX tools, tmux and a managed Node runtime under `~/.harness` — all of
    // which exist to host the local `harness` CLI, which a viewer build does
    // not have and does not want. Running it on a phone reported every step
    // missing and parked the app on a setup screen whose two actions, Retry
    // and Switch to Manual, could not succeed either. Treated as ready so
    // bootstrap goes on to ask about sign-in, which a viewer can answer.
    if (viewer != null) return true;
    if (_environmentSetupInFlight) return false;
    _environmentSetupInFlight = true;
    _environmentInstallRequested = false;
    status = AppStatus.checkingEnvironment;
    environmentReadiness = EnvironmentReadiness.initial();
    notifyListeners();
    try {
      // The probe is always read-only. What it finds missing is installed
      // straight away when the whole plan runs in-app; only a plan that needs
      // a password in Terminal waits on the wizard's Install action.
      var result = await _runProvisioner(install: false);
      // A computer that has never had Harness: the plan installs its CLI and there is no
      // `~/.harness/cli` at all. A CLI that is only too old, or whose Node went missing, is a repair
      // on a computer someone already uses, and gets neither the tour nor a first workspace.
      final firstHarness =
          result.plan.any((item) => item.step == EnvironmentStep.harness) &&
          !harnessInstalledBefore();
      // OpenCode, Codex and Claude Code download meanwhile when it has no agent at all
      // ([AgentPrefetch.start] decides), on Linux too, where the apt step waits for a password in
      // Terminal and setup keeps its own screen: a fresh Ubuntu VM (2026-10-09) ended setup on an empty
      // box and installed OpenCode in its first pane, about 90 s to a first result against 55 s on a Mac.
      // They wait for what setup brings until it is ready ([_continueAfterEnvironmentReady]).
      // Everyone on Windows, not only a first run: once, and it never holds anything up.
      unawaited(
        WindowsGitSetup(log: (line) => appLog.info('setup', line)).start(),
      );
      if (firstHarness) {
        _firstHarnessLaunch = true;
        agentPrefetch?.setupRunning = true;
        agentPrefetch?.start();
        // The tour's final line announces sign-in: see [signInStepShowing].
        _signInStep = true;
      }
      if (!result.isReady && _canInstallUnattended(result, mode: null)) {
        if (firstHarness) {
          _publishAgentDownloads();
          // Nobody needs to act on this install, so it runs under the welcome tour rather than on
          // the install screen.
          _setupTour = true;
        }
        status = AppStatus.preparingEnvironment;
        result = await _installUnattended(result);
      }
      if (firstHarness) {
        firstArrival.begin(downloads: agentPrefetch?.started ?? false);
        productRuntimeHealth?.newInstallation = true;
      }
      if (!result.isReady) {
        status = AppStatus.preparingEnvironment;
        notifyListeners();
        return false;
      }
      _cancelEnvironmentRecheckTimer();
      return true;
    } finally {
      _environmentSetupInFlight = false;
    }
  }

  /// Whether [probed] can be installed with nobody at the keyboard: it is a
  /// review of what is missing, the person has not chosen manual setup, and
  /// no step needs a password in Terminal (Linux apt). On macOS every step is
  /// in-app, so a fresh Mac never stops on an Install button.
  bool _canInstallUnattended(
    EnvironmentReadiness probed, {
    required EnvironmentSetupMode? mode,
  }) =>
      probed.phase == EnvironmentSetupPhase.review &&
      (mode ?? probed.mode) != EnvironmentSetupMode.manual &&
      !probed.plan.any((item) => item.requiresTerminal);

  /// The install [startEnvironmentSetup] runs, for a caller that already holds
  /// [_environmentSetupInFlight].
  Future<EnvironmentReadiness> _installUnattended(
    EnvironmentReadiness probed,
  ) async {
    _environmentInstallRequested = true;
    // Straight to the install progress: the review and its Install button
    // are never painted for a step nobody needs to approve. This is also the
    // state the provisioner resumes from — it re-probes every step — so its
    // first frame does not bring back the review's copy and red "Missing".
    final planned = {for (final item in probed.plan) item.step};
    environmentReadiness = probed.copyWith(
      phase: EnvironmentSetupPhase.installing,
      mode: EnvironmentSetupMode.automatic,
      message: 'Installing only the missing required tools.',
      steps: {
        for (final entry in probed.steps.entries)
          entry.key: planned.contains(entry.key)
              ? EnvironmentStepStatus.running
              : entry.value,
      },
    );
    notifyListeners();
    final result = await _runProvisioner(
      resumeFrom: environmentReadiness,
      install: true,
      mode: EnvironmentSetupMode.automatic,
    );
    if (!result.isReady) _scheduleEnvironmentRecheck();
    return result;
  }

  /// Shared with [_prepareEnvironment]: runs the provisioner, updates
  /// [environmentReadiness] as it streams progress, and reports the outcome.
  void _measureSetup(EnvironmentReadiness value) {
    productMeasurement.setupFacts({
      ProductFlow.setup: switch (value.phase) {
        EnvironmentSetupPhase.ready => 'ready',
        EnvironmentSetupPhase.failed => 'failed',
        _ => 'running',
      },
      // A check marks a tool that is not installed yet as failed, and setup then installs it. That
      // is `missing`, not a failure: on Oct 16 every new computer counted its Harness CLI and tmux
      // as failed steps while 0 setups failed. Only a setup that ends failed fails its step.
      for (final entry in value.steps.entries)
        switch (entry.key) {
          EnvironmentStep.harness => ProductFlow.setupHarness,
          EnvironmentStep.tmux => ProductFlow.setupTmux,
          EnvironmentStep.clipboard => ProductFlow.setupClipboard,
        }: entry.value == EnvironmentStepStatus.failed &&
                value.phase != EnvironmentSetupPhase.failed
            ? 'missing'
            : entry.value.name,
    });
  }

  Future<EnvironmentReadiness> _runProvisioner({
    EnvironmentReadiness? resumeFrom,
    bool install = false,
    EnvironmentSetupMode? mode,
    bool quiet = false,
  }) async {
    final provisioner = environmentProvisioner ?? EnvironmentProvisioner();
    if (install) _installedThisBoot = true;
    final result = await provisioner.ensureReady(
      onProgress: (value) {
        _measureSetup(value);
        if (quiet &&
            value.phase != EnvironmentSetupPhase.ready &&
            value.phase != EnvironmentSetupPhase.failed) {
          // A 5-second Terminal poll must not repaint the wizard through
          // preflight -> review -> waiting. Keep the stable handoff surface
          // and only stream its diagnostics until there is a real terminal
          // outcome or installation can continue.
          environmentReadiness = environmentReadiness.copyWith(
            output: value.output,
            terminalLogPath: value.terminalLogPath,
            terminalResultPath: value.terminalResultPath,
            terminalSetup: value.terminalSetup,
            plan: value.plan,
          );
        } else {
          environmentReadiness = value;
        }
        // A successful probe belongs to the quiet pre-flight surface, never
        // the installation wizard. This also prevents the setup screen from
        // flashing its own ready phase for one frame after an install/recheck.
        if (value.isReady) status = AppStatus.checkingEnvironment;
        notifyListeners();
      },
      resumeFrom: resumeFrom,
      install: install,
      mode: mode,
    );
    _measureSetup(result);
    environmentReadiness = result;
    return result;
  }

  /// What `bootstrap()` does right after the environment is confirmed ready — pulled out so
  /// [recheckEnvironmentStep] can reach the same destination without repeating `bootstrap()`'s config
  /// load and update-check startup, which already ran on the launch that got stuck here.
  Future<void> _continueAfterEnvironmentReady({
    Future<CliAuthStatus?>? early,
    bool fromKept = true,
  }) async {
    agentPrefetch?.setupRunning = false;
    final revision = _authRevision;
    if (!_authWorkCurrent(revision)) return;
    _cancelEnvironmentRecheckTimer();
    // A viewer skipped the preflight (see [_prepareEnvironment]), so there is no
    // preflight screen to hold while the sign-in is checked — it stays on the
    // boot spinner instead.
    status = viewer == null
        ? AppStatus.checkingEnvironment
        : AppStatus.bootstrapping;
    notifyListeners();
    // Auth now lives entirely with the local `harness` CLI — it owns the SSO session on disk and
    // refreshes it itself. This app never reads, stores, or refreshes a token of its own; it just
    // asks the CLI whether this computer is currently signed in.
    try {
      if (early != null &&
          fromKept &&
          await _openFromKeptSignIn(early, revision)) {
        return;
      }
      final authStatus = await early ?? await cliLogin.checkStatus();
      _markStartup('signed-in check');
      if (!_authWorkCurrent(revision)) return;
      signedIn = authStatus.loggedIn;
      await _useKeptProfile(authStatus, revision);
      if (!_authWorkCurrent(revision)) return;
      if (!authStatus.loggedIn) {
        currentUser = null;
        // Viewers keep their own login screen. Desktop can prepare the saved
        // workspace locally, but the required sign-in page stays in front of
        // it. Arm it on every signed-out launch, including existing installs
        // and a relaunch after leaving setup before signing in.
        if (viewer != null) {
          status = AppStatus.unauthenticated;
          notifyListeners();
          return;
        }
        _signInStep = true;
      }
      status = AppStatus.bootstrapping;
      notifyListeners();
      await _finishBootstrapSignedIn();
      unawaited(_offerPhoneAtLaunch(revision));
    } catch (error, stack) {
      if (!_authWorkCurrent(revision)) return;
      debugPrint(
        'continueAfterEnvironmentReady: fallback to login after error: '
        '$error\n$stack',
      );
      currentUser = null;
      status = AppStatus.unauthenticated;
      if (viewer != null) {
        _lastError = 'Could not complete sign-in. Please sign in again.';
      }
      notifyListeners();
    }
  }

  /// Opens the window as the account this computer was last proven signed in as, while `harness auth status` still
  /// runs (task #3561: 245 ms of a launch, a Node start). What is stored is the kept profile ([ProfileCache]): written
  /// only once the CLI named its machine and the server named the account, and cleared by every sign-out this app sees
  /// and every signed-out launch. With none kept, or no CLI sign-in file, the launch waits for the check as before.
  /// Whatever the check then says, [_confirmKeptSignIn] ends the launch where a launch that waited would have ended.
  Future<bool> _openFromKeptSignIn(
    Future<CliAuthStatus?> check,
    int revision,
  ) async {
    if (viewer != null || !cliSessionOnDisk()) return false;
    final kept = await _profileCache.readKept();
    if (kept == null || !_authWorkCurrent(revision)) return false;
    signedIn = true;
    // Shown, not proven: nothing is kept and no picture is claimed under it until the check names this machine.
    _provenMachineId = null;
    _keptProfileId = kept.profile.id;
    _profileConfirmed = false;
    currentUser = kept.profile;
    status = AppStatus.bootstrapping;
    notifyListeners();
    _launchProof = (revision: revision, settled: Completer<void>());
    unawaited(_confirmKeptSignIn(check, kept.machineId, revision));
    await _finishBootstrapSignedIn();
    unawaited(_offerPhoneAtLaunch(revision));
    return true;
  }

  /// Settles once the check behind a window [_openFromKeptSignIn] opened has answered. Until then the window shows only
  /// this computer's restored desk: the account's work (its profile, devices, machine list and desk) waits for it, since
  /// the CLI may be signed in as someone else and that work would run through their session (review of #3293).
  ({int revision, Completer<void> settled})? _launchProof;
  bool _layoutSaveHeld = false;

  /// The signed-in check behind a window [_openFromKeptSignIn] opened. The same machine: proven, as
  /// [_useKeptProfile] would have proven it. Signed out: the sign-in page, as when a sign-out elsewhere is noticed.
  /// Another account, or no answer: the launch starts again from the CLI's answer, as one with nothing kept does.
  Future<void> _confirmKeptSignIn(
    Future<CliAuthStatus?> check,
    String keptMachineId,
    int revision,
  ) async {
    CliAuthStatus? answer;
    try {
      answer = await check ?? await cliLogin.checkStatus();
    } catch (error) {
      debugPrint('bootstrap: signed-in check failed behind the window: $error');
    }
    _markStartup('signed-in check');
    // Each branch below decides synchronously, so the account work waiting on this resumes under its outcome: proven,
    // or invalidated.
    final proof = _launchProof;
    final held = _layoutSaveHeld;
    if (proof != null && proof.revision == revision) {
      _launchProof = null;
      _layoutSaveHeld = false;
      proof.settled.complete();
    }
    if (!_authWorkCurrent(revision)) return;
    if (answer != null &&
        answer.loggedIn &&
        answer.machineId == keptMachineId) {
      _provenMachineId = keptMachineId;
      unawaited(superTabImageCache.claim(keptMachineId));
      if (held) _persistLayout();
      return;
    }
    if (answer != null && !answer.loggedIn) {
      _signedOutAtRuntime(_signedOutMessage);
      return;
    }
    final again = _invalidateAuthWork();
    currentUser = null;
    _provenMachineId = null;
    _keptProfileId = null;
    _profileConfirmed = false;
    _clearAccountWorkspace();
    status = AppStatus.checkingEnvironment;
    notifyListeners();
    // Gone before the launch starts again, so it cannot open from it a second time.
    await _profileCache.clear();
    if (!_authWorkCurrent(again)) return;
    if (_workspaceCleanup case final cleanup?) {
      await cleanup;
      if (!_authWorkCurrent(again)) return;
    }
    // Never from the kept record again: a delete that failed leaves it readable (review of #3293).
    await _continueAfterEnvironmentReady(
      early: answer == null ? null : Future.value(answer),
      fromKept: false,
    );
  }

  void showEnvironmentReview() {
    environmentReadiness = environmentReadiness.copyWith(
      phase: EnvironmentSetupPhase.review,
    );
    notifyListeners();
  }

  void showEnvironmentMethodChoice() {
    environmentReadiness = environmentReadiness.copyWith(
      phase: EnvironmentSetupPhase.chooseMethod,
    );
    notifyListeners();
  }

  void selectEnvironmentSetupMode(EnvironmentSetupMode mode) {
    if (mode == EnvironmentSetupMode.manual) {
      _environmentInstallRequested = false;
    }
    environmentReadiness = environmentReadiness.copyWith(mode: mode);
    notifyListeners();
  }

  Future<void> startEnvironmentSetup() async {
    if (_environmentSetupInFlight) return;
    _cancelEnvironmentRecheckTimer();
    final mode = environmentReadiness.mode ?? EnvironmentSetupMode.automatic;
    if (mode == EnvironmentSetupMode.manual) {
      notifyListeners();
      return;
    }
    _environmentInstallRequested = true;
    _environmentSetupInFlight = true;
    notifyListeners();
    try {
      final result = await _runProvisioner(
        resumeFrom: environmentReadiness,
        install: true,
        mode: mode,
      );
      if (!result.isReady) {
        _scheduleEnvironmentRecheck();
        return;
      }
      await _continueAfterEnvironmentReady();
    } finally {
      _environmentSetupInFlight = false;
      notifyListeners();
    }
  }

  Future<void> continueAfterEnvironmentSetup() async {
    if (!environmentReadiness.isReady) return;
    await _continueAfterEnvironmentReady();
  }

  /// A manual repair always returns to a read-only probe. In automatic setup
  /// the probe is followed by the install when it can run unattended, as at
  /// launch.
  Future<void> retryEnvironmentSetup() async {
    if (_environmentSetupInFlight) return;
    _environmentSetupInFlight = true;
    notifyListeners();
    try {
      final mode = environmentReadiness.mode;
      var result = await _runProvisioner(install: false, mode: mode);
      if (!result.isReady && _canInstallUnattended(result, mode: mode)) {
        result = await _installUnattended(result);
      }
      if (result.isReady) await _continueAfterEnvironmentReady();
    } finally {
      _environmentSetupInFlight = false;
      notifyListeners();
    }
  }

  /// Rechecks a single stuck step (`failed`/`needsTerminal`) without re-running steps already
  /// `ready` — the user fixed it by hand (with the command the review lists) and this
  /// confirms it, then falls through to whatever step comes next, exactly like a fresh `bootstrap()`
  /// would have. [step] identifies which row's Recheck button was pressed; the provisioner itself
  /// decides what to (re-)attempt from the current [environmentReadiness], so an already-resolved
  /// step is never disturbed regardless of which row triggered this.
  Future<void> recheckEnvironmentStep(EnvironmentStep step) async {
    if (_environmentSetupInFlight) return;
    _cancelEnvironmentRecheckTimer();
    _environmentSetupInFlight = true;
    notifyListeners();
    try {
      final visibleBeforeProbe = environmentReadiness;
      final mode = environmentReadiness.mode;
      var result = await _runProvisioner(
        resumeFrom: environmentReadiness,
        install: false,
        mode: mode,
        quiet:
            mode == EnvironmentSetupMode.automatic &&
            environmentReadiness.phase ==
                EnvironmentSetupPhase.waitingForTerminal,
      );
      // Every host step done means only the Harness CLI is left, and that
      // installs in-app without another prompt — so carry on into it.
      if (!result.isReady &&
          _environmentInstallRequested &&
          mode == EnvironmentSetupMode.automatic &&
          result.phase != EnvironmentSetupPhase.failed &&
          result.phase != EnvironmentSetupPhase.waitingForTerminal &&
          result.hostReady) {
        result = await _runProvisioner(
          resumeFrom: result,
          install: true,
          mode: mode,
        );
      }
      if (!result.isReady) {
        if (mode == EnvironmentSetupMode.automatic &&
            result.phase != EnvironmentSetupPhase.failed) {
          environmentReadiness = visibleBeforeProbe.copyWith(
            phase: EnvironmentSetupPhase.waitingForTerminal,
            output: result.output,
            terminalLogPath: result.terminalLogPath,
            terminalResultPath: result.terminalResultPath,
            terminalSetup: result.terminalSetup,
            plan: result.plan,
          );
        }
        _scheduleEnvironmentRecheck();
        return;
      }
      await _continueAfterEnvironmentReady();
    } catch (error, stack) {
      debugPrint(
        'recheckEnvironmentStep: fallback to login after error: $error\n$stack',
      );
      currentUser = null;
      status = AppStatus.unauthenticated;
    } finally {
      _environmentSetupInFlight = false;
      notifyListeners();
    }
  }

  /// Polls the currently-stuck required step every 5s (see `_environmentRecheckTimer`'s doc) so
  /// fixing it in another window and forgetting to click Recheck still moves the app forward.
  /// A no-op unless automatic setup is waiting on the real Terminal window.
  void _scheduleEnvironmentRecheck() {
    _environmentRecheckTimer?.cancel();
    if (environmentReadiness.phase !=
            EnvironmentSetupPhase.waitingForTerminal ||
        environmentReadiness.mode != EnvironmentSetupMode.automatic) {
      return;
    }
    EnvironmentStep? stuck;
    for (final entry in environmentReadiness.steps.entries) {
      if (!entry.key.isRequired) continue;
      if (entry.value == EnvironmentStepStatus.needsTerminal ||
          entry.value == EnvironmentStepStatus.failed) {
        stuck = entry.key;
        break;
      }
    }
    if (stuck == null && environmentReadiness.terminalSetup == null) return;
    // Base system setup has no EnvironmentStep row of its own. The callback
    // argument is only a UI trigger; the provisioner rechecks the complete
    // environment and uses terminalSetup to attribute any failure.
    final step = stuck ?? EnvironmentStep.tmux;
    _environmentRecheckTimer = Timer(const Duration(seconds: 5), () {
      unawaited(recheckEnvironmentStep(step));
    });
  }

  void _cancelEnvironmentRecheckTimer() {
    _environmentRecheckTimer?.cancel();
    _environmentRecheckTimer = null;
  }

  void _bootstrapLocalManual(LocalManualFixture fixture) {
    _autonomousEnv = 'prod';
    config = AppConfig(apiBaseUrl: fixture.apiBaseUrl);
    api = _newApiClient();
    currentUser = const CurrentUserProfile.local();
    final machine = Machine(
      machineId: fixture.machineId,
      apiKey: fixture.apiKey,
      authMode: MachineAuthMode.remote,
      name: fixture.machineName,
      status: 'online',
    );
    machines = [machine];
    machineStates
      ..clear()
      ..[machine.machineId] = MachineState(machine);
    machineStates[machine.machineId]!.nodeOnline = true;
    expandedMachines.clear();
    selectedMachineId = null;
    status = AppStatus.authenticated;
    _lastError = null;
    _ensurePool();
    _autoConnectAndLoadMachines();
    notifyListeners();
  }

  /// Both `bootstrap()` (already signed in) and `login()` (just finished signing in) land here once
  /// the CLI confirms a session exists — ensure the local daemon is actually up first (it does not
  /// start on its own, and every call below is a local-CLI-proxied request that needs it), then fetch
  /// the profile and machine list independently over it.
  Future<void> _finishBootstrapSignedIn() async {
    final revision = _authRevision;
    if (!_authWorkCurrent(revision)) return;
    _localSeatFollowed = false;
    // Which sign-in this app is under is the device log's to know before anything below can read it
    // (a restored pane, the dial, the pool, a connection's push): synchronous, ahead of the first await.
    // A sign-in by hand just now is `fresh`; a stored session (the app opening) is not.
    if (signedIn)
      _deviceLog?.beginSignIn(
        fresh: viewer?.auth.consumeFreshSignIn() ?? false,
      );
    // Stays on the pre-navigation `bootstrapping` screen (main.dart) until the daemon is
    // confirmed reachable — flipping to `authenticated` any earlier is what let the home UI
    // race `harness start`'s own backend handshake and surface a bogus 30s "Could not load
    // machines" timeout. A daemon that never comes up still gets a home screen below, with
    // the failure shown there as before, since that's where the retry affordance lives.
    _bootStatusMessage = viewer == null
        ? 'Starting local service…'
        : 'Opening workspace…';
    notifyListeners();
    // Before the machines, deliberately: the tiles are intent, they render as
    // "waiting for that machine" on their own, and each attaches as its machine
    // answers. Waiting for the machine list first would leave the window empty
    // for as long as the slowest one takes, and would hand the first-run
    // auto-pick a window in which the grid still looks empty.
    // Every exit below clears the message: a boot superseded by a sign-out/sign-in mid-way (the
    // `_authWorkCurrent` returns) used to leave "Starting local service…" on a screen nothing would
    // ever repaint.
    await _identifyBeforeLayout(revision);
    _ensurePool();
    // The daemon check starts beside the restores, as neither waits on the other (task #2169). The window opens once both
    // have answered, so the tiles are there for it, as before.
    Object? daemonFailure;
    var daemonFailed = false;
    final daemon = ensureCliDaemonReady()
        .then<void>((_) => _markStartup('daemon'))
        .catchError((Object error) {
          daemonFailed = true;
          daemonFailure = error;
        });
    await _restorePaneLayout(claimOnAttach: true);
    _armLaunchClaimExpiry();
    if (!_authWorkCurrent(revision)) {
      _bootStatusMessage = null;
      return;
    }
    await dial.restore();
    await firstArrival.restore();
    _markStartup('saved tabs');
    if (!_authWorkCurrent(revision)) {
      _bootStatusMessage = null;
      return;
    }
    await daemon;
    if (daemonFailed) {
      final error = daemonFailure;
      _bootStatusMessage = null;
      if (!_authWorkCurrent(revision)) return;
      status = AppStatus.authenticated;
      _lastError = '$error';
      _lastErrorRetryable = true;
      notifyListeners();
      return;
    }
    _bootStatusMessage = null;
    if (!_authWorkCurrent(revision)) return;
    // `ensureCliDaemonReady` may have signed the app out instead of succeeding (daemon absent AND
    // the saved session gone) — that already routed to the login screen, so don't clobber it.
    if (status == AppStatus.unauthenticated) return;
    status = AppStatus.authenticated;
    _markStartup('window');
    appLog.info('startup', startupLogLine(_startupTimings));
    _startupClock.stop();
    notifyListeners();
    // A window opened from the kept sign-in asks nothing of the account until the check proves it ([_launchProof]).
    final proof = _launchProof;
    if (proof != null && proof.revision == revision) {
      await proof.settled.future;
      if (!_authWorkCurrent(revision)) return;
    }
    // The CLI has confirmed daemon readiness. Display-name/avatar metadata is
    // independent of machine discovery and must not delay work — and a guest
    // has no profile to load.
    if (signedIn) unawaited(_loadProfile());
    // The account's device key log: this app's key joins it (an existing sign-in too, from before
    // the log existed), and every machine it names is trusted with no password.
    if (signedIn) {
      if (_deviceLog case final log?) {
        // Which sign-in by hand this log's marks belong to is the log's own (minted at the start of
        // this boot by `beginSignIn`), never the profile's id — nothing to wait for.
        unawaited(
          log.register().whenComplete(() {
            unawaited(_syncPendingDevices());
            unawaited(_rereadRemovedMachines());
          }),
        );
      } else {
        // A desktop build: the daemon's own copy says which devices are still waiting to be seen.
        unawaited(_syncPendingDevices());
      }
    }
    try {
      await refreshMachines();
      speedMarks.launch('machines listed');
    } catch (error) {
      if (!_authWorkCurrent(revision)) return;
      _reportMachineLoadError(error);
    }
    if (!_authWorkCurrent(revision)) return;
    // The account may have changed while this window was closed — see
    // [_followLocalMachineId]. Done AFTER the list, which is what says which id
    // this computer is served under now. The desk follows it: tabs from the
    // other computers appear as intent and attach as their machines answer. It
    // is the ACCOUNT's desk (`Desk{userId}`), so a guest has none — asking for
    // one would earn a 401 on every poll for a document that cannot exist.
    await _followLocalMachineIdThenDesk(revision);
    if (_authWorkCurrent(revision)) notifyListeners();
  }

  /// This computer's machine id, against the one the saved desk was keyed by.
  ///
  /// The account can change while the app is CLOSED — `harness logout` in a
  /// terminal, a session that expired overnight — and then the tiles restored a
  /// moment ago name a machine the daemon no longer serves under that id. Re-seat
  /// them under the one it does, and remember it for next time.
  Future<void> _followLocalMachineId(int revision) async {
    final store = _paneLayout;
    final local = localMachineState?.machine;
    final current = local?.machineId;
    if (store == null || current == null) return;
    final remembered = await store.loadLocalMachineId();
    if (!_authWorkCurrent(revision)) return;
    var from = remembered != null && remembered != current ? remembered : null;
    // THIS COMPUTER'S OWN ID, on a tile, is this computer under the identity it
    // had while signed out — and that is a fact rather than a reading. The
    // daemon serves this machine under `computerId()` with no account and under
    // the account's `machineId` with one, and the machine row carries BOTH, so
    // a tile keyed by the first is one this window made before signing in.
    //
    // It outranks the remembered id because the remembered id can be wrong in
    // the one direction that matters: a pass that could not re-seat used to
    // record the new id anyway, erasing the only clue the next pass had. Seen
    // on a real desk — two harnesses made signed-out, `local_machine_id` already
    // the account's, and no way back (owner, 2026-09-24).
    final strandedOnThisComputer = _strandedGuestTiles(local);
    if (strandedOnThisComputer != null) from = strandedOnThisComputer;
    // A guest's list is this computer and nothing else, so a tile waiting for a
    // machine the list does not have can only be this computer under the account
    // it left — IF every such tile names the same one. Kept for the desk saved
    // before any of the ids above were recorded.
    if (from == null && isGuest) {
      final unknown = {
        for (final pane in allPanes)
          if (!machineStates.containsKey(pane.machineId)) pane.machineId,
      };
      if (unknown.length == 1 && unknown.single != current) {
        from = unknown.single;
      }
    }
    if (from != null) {
      final restored = await _reseatDesk(
        from: from,
        to: current,
        dropOthers: isGuest,
        revision: revision,
      );
      if (!_authWorkCurrent(revision) || !restored) return;
    }
    // ONLY ONCE THE DESK REALLY NAMES THIS MACHINE.
    //
    // This used to run whatever happened above, which is what made a single
    // missed re-seat permanent: the id it wrote was the evidence the next launch
    // needed. If tiles are still sitting on this computer's signed-out id, the
    // desk has not been re-seated and the old id has to stand.
    if (_strandedGuestTiles(local) == null) {
      await store.saveLocalMachineId(current);
    }
  }

  /// This computer's signed-out id, when tiles are still keyed by it.
  ///
  /// Returns the id AS THE TILES SPELL IT — the re-key rewrites what is on the
  /// desk, and the two sides spell the same id differently. See [sameMachineId].
  String? _strandedGuestTiles(Machine? local) {
    final computerId = local?.computerId;
    if (computerId == null || computerId.isEmpty) return null;
    if (sameMachineId(computerId, local!.machineId)) return null;
    for (final pane in allPanes) {
      if (sameMachineId(pane.machineId, computerId) &&
          !machineStates.containsKey(pane.machineId)) {
        return pane.machineId;
      }
    }
    return null;
  }

  /// The account left this window — signed out from Settings, or a session that
  /// ended underneath us — and the desk has to be sat back down on the machine
  /// id the daemon serves NOW.
  ///
  /// The daemon takes its identity once, at boot: this computer's own id signed
  /// out, the account's machineId signed in. `harness login` and `harness logout`
  /// restart it on the other one, so this side waits for that daemon to come
  /// back, reads the machine list it now serves, and re-seats every tile that was
  /// open on the OLD local id under the new one. Remote tiles ride along on a
  /// sign-in and leave on a sign-out — a guest has no machine to attach them to,
  /// and a tile waiting forever reads as broken rather than as signed out.
  ///
  /// The whole desk goes through the saved layout and back (see [_reseatDesk])
  /// rather than being re-keyed live: a tile's machine id is set at birth, and
  /// every other path that changes which agent a tile shows already goes through
  /// the store. Reusing the cold-start restore is what keeps this from becoming a
  /// second, subtly different way to build a grid.
  ///
  /// Both callers invalidate old account work before clearing its workspace.
  /// Reuse that revision so the expiry explanation survives the guest restore.
  Future<void> _becomeGuest({
    String? banner,
    String? previousMachineId,
    required int revision,
  }) async {
    _guestDeskRestorePending = true;
    signedIn = false;
    _signInStep = true;
    currentUser = null;
    _provenMachineId = null;
    _keptProfileId = null;
    _profileConfirmed = false;
    unawaited(_profileCache.clear());
    if (banner != null) {
      _lastError = banner;
      _lastErrorRetryable = true;
    }
    notifyListeners();
    // Account teardown already removed private remote content. Finish closing
    // its transports before restoring this computer from the saved desk.
    await _workspaceCleanup;
    if (!_authWorkCurrent(revision)) return;
    final before = previousMachineId ?? await _paneLayout?.loadLocalMachineId();
    if (!_authWorkCurrent(revision)) return;
    _ensurePool();
    notifyListeners();
    try {
      await ensureCliDaemonReady();
    } catch (error) {
      if (!_authWorkCurrent(revision)) return;
      _lastError = '$error';
      _lastErrorRetryable = true;
      notifyListeners();
      return;
    }
    if (!_authWorkCurrent(revision)) return;
    try {
      await refreshMachines();
    } catch (error) {
      if (!_authWorkCurrent(revision)) return;
      _reportMachineLoadError(error);
    }
    if (!_authWorkCurrent(revision)) return;
    final after = localMachineState?.machine.machineId;
    if (after != null) {
      // Remote tiles leave with the account — a guest has no machine to attach
      // them to, and a tile waiting forever reads as broken rather than as
      // signed out. This computer's follow it to the id the daemon serves now.
      final restored = await _reseatDesk(
        from: before ?? after,
        to: after,
        dropOthers: true,
        revision: revision,
        persistCurrent: false,
      );
      if (!_authWorkCurrent(revision)) return;
      if (!restored) {
        // Keep the restore pending and the old identity intact. The unchanged
        // saved layout may still contain private remote panes, so do not read it
        // back into the guest workspace until the filtered write succeeds.
        status = AppStatus.authenticated;
        notifyListeners();
        return;
      }
      await _paneLayout?.saveLocalMachineId(after);
      if (!_authWorkCurrent(revision)) return;
      _guestDeskRestorePending = false;
    }
    // A guest ends on the desk, whichever screen it started from.
    status = AppStatus.authenticated;
    if (banner != null) {
      _lastError = banner;
      _lastErrorRetryable = true;
    }
    notifyListeners();
  }

  /// Rebuild the grid from the saved layout with this computer's tiles re-keyed
  /// from [from] to [to], and — with [dropOthers] — every other machine's tiles
  /// left out.
  ///
  /// The live tiles are closed WITHOUT persisting (their ids are the old ones),
  /// the file is rewritten, and the cold-start restore reads it back; tiles whose
  /// machines are already connected are attached straight away rather than
  /// waiting for a connect event that already happened.
  ///
  /// The tiles detaching is teardown a sign-in waits for, and a sign-in that
  /// started meanwhile ([revision] superseded) owns the grid from there: this
  /// leaves it empty rather than restoring the desk this re-seat was for, and
  /// that sign-in's own bootstrap restores the file and follows the id.
  Future<bool> _reseatDesk({
    required String from,
    required String to,
    required bool dropOthers,
    required int revision,
    bool persistCurrent = true,
  }) {
    final previous = _workspaceCleanup;
    var restored = false;
    return _trackWorkspaceCleanup(() async {
      await previous;
      if (!_authWorkCurrent(revision)) return;
      restored = await _reseatDeskAfterCleanup(
        from: from,
        to: to,
        dropOthers: dropOthers,
        revision: revision,
        persistCurrent: persistCurrent,
      );
    }()).then((_) => restored);
  }

  Future<bool> _reseatDeskAfterCleanup({
    required String from,
    required String to,
    required bool dropOthers,
    required int revision,
    required bool persistCurrent,
  }) async {
    final store = _paneLayout;
    if (store == null) return true;
    // After sign-out the live grid is intentionally empty. Saving it here
    // would destroy the local work we are about to recover.
    if (persistCurrent) _persistLayout();
    await store.flushSwarms();
    if (!_authWorkCurrent(revision)) return false;
    if (!await store.rekeyMachine(from: from, to: to, dropOthers: dropOthers)) {
      if (_authWorkCurrent(revision)) {
        _lastError =
            'Could not restore this computer’s saved workspace. Try again.';
        _lastErrorRetryable = true;
      }
      return false;
    }
    if (_disposed) return false;
    // The file and the id it is keyed by move together, whatever happens next:
    // a sign-in that overtakes this re-seat finds the desk through that id.
    await store.saveLocalMachineId(to);
    if (_disposed) return false;
    await _closeAllPanes(persist: false);
    if (_disposed) return false;
    _closedHistory.clear();
    final starter = Swarm(id: 'swarm-${_nextSwarmId++}');
    swarms
      ..clear()
      ..add(starter);
    _activeSwarmId = starter.id;
    if (!_authWorkCurrent(revision)) return false;
    await _restorePaneLayout();
    if (!_authWorkCurrent(revision)) return false;
    for (final machine in machineStates.values) {
      // A restore at launch, or a machine re-seated under it.
      _attachPendingPanes(machine, intent: AttachIntent.automatic);
    }
    _announceAppFocus();
    return true;
  }

  /// The local daemon (`harness start`) must be up before any local REST/WS call can work — unlike
  /// `harness login`, it does not start on its own. Sets [_cliEndpoint], the dial target every
  /// machine's WsConn now uses. Public (like [refreshMachines]) so a test subclass can stub it
  /// without shelling out to a real `harness` binary.
  /// Who is signed in, from the daemon. Shared by the boot path and by the
  /// retry path, because a boot that found the daemon still connecting now
  /// finishes THROUGH the retry path — and a session that never learns its
  /// own account has an empty footer.
  Future<void> _loadProfile() {
    final pending = _profileInFlight;
    if (pending != null) return pending;
    final revision = _authRevision;
    late final Future<void> load;
    load = _readProfile(revision).whenComplete(() {
      if (identical(_profileInFlight, load)) _profileInFlight = null;
    });
    _profileInFlight = load;
    return load;
  }

  /// Who signed in, before the saved tabs are restored (see
  /// [PaneLayoutStore.restorableFor]). A browser is the window anyone may sign
  /// in on, and it has no daemon to wait for, so this costs one request there;
  /// a native build reaches the profile through its daemon and keeps restoring
  /// first. Unknown — the request failed — restores as before.
  Future<void> _identifyBeforeLayout(int revision) async {
    if (viewer == null || !signedIn) return;
    try {
      final me = await api.me();
      if (me != null && _authWorkCurrent(revision)) {
        currentUser = CurrentUserProfile.fromMe(me);
        _profileConfirmed = true;
      }
    } catch (_) {
      /* Unknown: the profile load after boot tries again. */
    }
  }

  /// The machine id `harness auth status` named at this boot: what a kept profile is checked against ([ProfileCache]).
  String? _provenMachineId;
  late final _profileCache = ProfileCache(_paneLayout?.storage);

  /// The account the kept profile showing now names, if one is: a server answer for another account clears it.
  String? _keptProfileId;

  /// Whether the server has answered who is signed in during this run. A kept profile shows until it has, and it is asked again
  /// when the backend returns, as a person with no profile at all is. Security review of #2617.
  bool _profileConfirmed = false;

  /// The last profile, when the CLI's session is the one it was read under; otherwise it goes (task #2169). A viewer has no CLI
  /// session to prove it, and reads its profile before the layout instead ([_identifyBeforeLayout]).
  Future<void> _useKeptProfile(CliAuthStatus authStatus, int revision) async {
    if (viewer != null) return;
    final machineId = authStatus.loggedIn ? authStatus.machineId : null;
    _provenMachineId = machineId;
    // The chat's pictures are tied the same way (task #3178): a sign-out this
    // app never saw, or another account on this computer, clears them here.
    unawaited(superTabImageCache.claim(machineId));
    _keptProfileId = null;
    _profileConfirmed = false;
    final kept = machineId == null ? null : await _profileCache.read(machineId);
    if (!_authWorkCurrent(revision)) return;
    if (kept == null) {
      await _profileCache.clear();
      return;
    }
    _keptProfileId = kept.id;
    currentUser = kept;
    notifyListeners();
  }

  /// Keeps what the server just answered, only where it can't name another account later: a machine id proves the account only
  /// while everything under it is that account's. Someone can sign in as another in a terminal while the answer is on its way,
  /// so an answer naming another account than the record goes, and a first record waits for the CLI to name the machine still.
  Future<void> _keepProfile(CurrentUserProfile profile, int revision) async {
    final machineId = _provenMachineId;
    if (machineId == null) return;
    final kept = _keptProfileId;
    if (kept != null && kept != profile.id) {
      _provenMachineId = null;
      _keptProfileId = null;
      await _profileCache.clear();
      return;
    }
    if (kept == null) {
      final CliAuthStatus still;
      try {
        still = await cliLogin.checkStatus();
      } catch (_) {
        return;
      }
      if (!_authWorkCurrent(revision) ||
          !still.loggedIn ||
          still.machineId != machineId)
        return;
      _keptProfileId = profile.id;
    }
    await _profileCache.write(machineId, profile);
    unawaited(superTabImageCache.owned(machineId));
  }

  /// Saves the signed-in person's own account name (Profile, task #2654) and
  /// shows it at once; answers why it was refused, in one short line, or null
  /// once saved.
  Future<String?> setAccountName(String name) async {
    final revision = _authRevision;
    try {
      final me = await api.updateMe(name: name);
      if (me == null || !_authWorkCurrent(revision)) return null;
      final profile = CurrentUserProfile.fromMe(me);
      // Another account's answer is not this one's name: leave it for the
      // next profile read to settle.
      if (currentUser?.id != null && profile.id != currentUser?.id) return null;
      currentUser = profile;
      unawaited(_keepProfile(profile, revision));
      notifyListeners();
      return null;
    } on ApiException catch (error) {
      // A daemon (or, in a browser, a backend) from before the route.
      if (error.status == 404) return 'Update Harness to change your name.';
      return error.message;
    } catch (_) {
      return 'Your name was not saved. Try again.';
    }
  }

  Future<void> _readProfile(int revision) async {
    try {
      final me = await api.me();
      if (!_authWorkCurrent(revision) || status != AppStatus.authenticated) {
        return;
      }
      if (me != null) {
        currentUser = CurrentUserProfile.fromMe(me);
        _profileConfirmed = true;
        if (currentUser case final profile?)
          unawaited(_keepProfile(profile, revision));
        // A sign-in by hand: the device log keeps which account it was made to.
        if (currentUser!.id case final id?)
          unawaited(_deviceLog?.signedInAs(id));
        notifyListeners();
      }
    } catch (error) {
      if (_authWorkCurrent(revision)) {
        debugPrint('bootstrap: profile unavailable: $error');
      }
    }
  }

  Future<void> ensureCliDaemonReady() async {
    // A viewer has no daemon to start: it reaches every machine through the relay.
    if (viewer != null) return;
    final revision = _authRevision;
    final discovery = _discovery;
    var probe = await discovery.ensureRunning();
    if (!_authWorkCurrent(revision)) return;
    final daemonPid = probe.pid;
    if (probe.ready &&
        daemonPid != null &&
        await (_daemonOwner?.check(daemonPid) ?? Future.value(false))) {
      probe = await discovery.ensureRunning();
      if (!_authWorkCurrent(revision)) return;
    }
    _logDaemonProbe(probe);
    switch (probe.state) {
      case LocalCliProbeState.ready:
        _cliEndpoint = probe.endpoint;
        _daemonGateFailed = false;
        _noteBackendOnline(probe.endpoint!.backendOnline);
      case LocalCliProbeState.notReady:
        _daemonGateFailed = true;
        // Running, not ready — most often a daemon fresh from a self-update still shaking hands
        // with the backend. Not "did not start": that sentence sends people to run `harness start`
        // against a daemon that is up, and the CLI's own lock will just tell them so. It keeps
        // retrying by itself; the supervisor below picks the app up the moment it gets there.
        _startDaemonSupervision(discovery);
        throw StateError(
          'Harness is running${probe.version == null ? '' : ' (v${probe.version})'} but is not '
          'ready yet — ${probe.reason}. It usually finishes on its own; retry in a moment.',
        );
      case LocalCliProbeState.down:
        _daemonGateFailed = true;
        // A daemon missing because its session ended is not an environment problem — and no longer a
        // reason to stop, either: it starts WITHOUT a session and serves this computer. So the window
        // is told it has become a guest (a banner, and the sheet on the next reach for another
        // machine) and the supervisor goes on bringing the daemon back.
        final authStatus = await cliLogin.checkStatus();
        if (!_authWorkCurrent(revision)) return;
        if (!authStatus.loggedIn && signedIn) {
          _signedOutAtRuntime(_signedOutMessage);
        }
        throw StateError(
          'The local Harness daemon did not start. Try running `harness start` yourself, then reopen the app.',
        );
    }
    _startDaemonSupervision(discovery);
  }

  /// Settings › Devices could not see the local network. Without a paired
  /// robot the daemon-owner check never tests the LAN (it is what raises the
  /// macOS prompt), so a daemon started from a terminal would stay refused it
  /// and the first robot could never be found. Asked here, by the person
  /// looking for one, the check runs again with the LAN test.
  bool _localNetworkWanted = false;

  Future<void> localNetworkBlocked() async {
    _localNetworkWanted = true;
    final guard = _daemonOwner;
    if (guard == null) return;
    final probe = await _discovery.ensureRunning();
    final pid = probe.pid;
    if (probe.ready && pid != null) await guard.recheck(pid);
  }

  /// One line per probe STATE the gate lands in, never per tick: this gate was silent, and the one
  /// machine that sat on "Starting local service…" for good had nothing in any log to say why.
  void _logDaemonProbe(LocalCliProbe probe) {
    final line = switch (probe.state) {
      LocalCliProbeState.ready =>
        'ready · backend ${probe.endpoint!.backendOnline ? 'online' : 'OFFLINE'}'
            '${probe.version == null ? '' : ' · v${probe.version}'}',
      LocalCliProbeState.notReady =>
        'not ready · ${probe.reason}${probe.version == null ? '' : ' · v${probe.version}'}',
      LocalCliProbeState.down => 'down · ${probe.reason}',
    };
    if (line == _loggedDaemonState) return;
    _loggedDaemonState = line;
    appLog.info('daemon', line);
  }

  /// The daemon's backend link changed (or was first seen). Coming BACK is the moment the app has
  /// been waiting for since it booted offline: the machine list (remote tiles, the real row for this
  /// computer) and the profile can be fetched now, without a click.
  ///
  /// [refetch] is false when the caller IS a machine refresh that just observed the flip through
  /// its own probe — it is already fetching, and a second run beside it would race the same state.
  void _noteBackendOnline(bool online, {bool refetch = true}) {
    if (_backendOnline == online) return;
    final wasOffline = _backendOnline == false;
    _backendOnline = online;
    appLog.info('daemon', 'backend ${online ? 'online' : 'offline'}');
    if (online && wasOffline && status == AppStatus.authenticated) {
      if (refetch && !machinesRefreshing) unawaited(retryMachines());
      if (!_profileConfirmed) unawaited(_loadProfile());
      _deskEnsure(_authRevision);
      // A daemon whose backend was away answered the last read with an error.
      if (_desk.enabled) unawaited(agentMessages.refresh());
      // The same for the Swarm's: a daemon just started has its backend a few seconds later
      // (6 s on 10-30), and the Swarm on screen would otherwise wait for its next poll.
      if (viewer == null) superTabs.serverAvailable();
    }
    notifyListeners();
  }

  @visibleForTesting
  void noteBackendOnlineForTest(bool online) => _noteBackendOnline(online);

  /// Supervision starts once the daemon is at least ANSWERING — ready or still connecting. It used to
  /// wait for ready, out of fear of a concurrent `harness start` from both places; the supervisor
  /// no longer spawns while anything answers on the port, so that race is gone, and starting it on
  /// a not-ready daemon is what lets a boot that landed mid-update recover without a click.
  void _startDaemonSupervision(LocalCliDiscovery discovery) {
    _daemonSupervisionTimer ??= discovery.startSupervising(
      spawnAllowedAt: inSpawnSlot,
      stillSignedIn: () async => (await cliLogin.checkStatus()).loggedIn,
      // Only the first time: the supervisor asks once per spawn attempt, and a guest window is
      // already a guest — repeating it would put the banner back on every retry.
      onSignedOut: () {
        if (signedIn) _signedOutAtRuntime(_signedOutMessage);
      },
      onSnapshot: _updateLocalProjectSnapshot,
      onBackendOnline: _noteBackendOnline,
      checkOwner: _daemonOwner == null
          ? null
          : (daemonPid) => _daemonOwner.check(daemonPid),
      onReady: (endpoint) {
        // Back (or here for the first time). If the app is sitting on the error strip from a boot
        // or reload that found the daemon not ready, this is the moment it was waiting for.
        //
        // Gated on OUR failure, not on `_lastError`: that strip is shared with errors this cannot
        // fix (an agent that failed to launch, say), and the supervisor's first tick after every
        // boot would otherwise clear one of those five seconds after it appeared.
        if (_cliEndpoint == null || _daemonGateFailed) {
          _cliEndpoint ??= endpoint;
          unawaited(retryMachines());
        }
      },
    );
  }

  void _updateLocalProjectSnapshot(LocalCliEndpoint endpoint) {
    if (_disposed) return;
    _followDaemonAccount(endpoint);
    // Every five seconds the daemon answers ready: the one steady witness that this computer's
    // machine is up, whatever a timeout or a missed probe said. It used to skip a row whose endpoint
    // had been cleared — the very row that needed it.
    for (final machine in machineStates.values) {
      if (machine.localOnly &&
          _normalizeComputerId(machine.machine.computerId) ==
              endpoint.computerId) {
        _healLocalMachine(machine, 'daemon ready', endpoint: endpoint);
      }
    }
    var changed = false;
    for (final machine in machineStates.values) {
      final previous = machine.localEndpoint;
      if (previous == null || previous.computerId != endpoint.computerId) {
        continue;
      }
      final scanEnded = previous.scanning && !endpoint.scanning;
      if (!mapEquals(previous.agentProjects, endpoint.agentProjects) ||
          previous.scanning != endpoint.scanning) {
        machine.localEndpoint = endpoint;
        changed = true;
      }
      // The list this window loaded while the daemon was still on its first scan may have been
      // missing agents (see LocalCliEndpoint.scanning): ask again now that it is complete.
      if (scanEnded) unawaited(_loadMachineData(machine, force: true));
      if (!kUnderTest) {
        for (final project in endpoint.agentProjects.values) {
          unawaited(_localGitProjects.read(project.cwd));
        }
      }
    }
    _applyLocalGitProjects();
    if (changed) notifyListeners();
  }

  void _applyLocalGitProjects() {
    if (_disposed) return;
    var changed = false;
    for (final machine in machineStates.values) {
      final projects = <String, AgentProject>{
        for (final entry
            in (machine.localEndpoint?.agentProjects ??
                    const <String, AgentProject>{})
                .entries)
          entry.key: ?_localGitProjects.cached(entry.value.cwd),
      };
      if (mapEquals(machine.localProjects, projects)) continue;
      machine.localProjects = Map.unmodifiable(projects);
      changed = true;
    }
    if (changed) notifyListeners();
  }

  /// Deliberately says nothing about WHY. The daemon clears its session identically whether the
  /// machine was deleted from another machine or the SSO token simply expired, and guessing between
  /// them in the copy would sometimes be wrong. Signing in again is the answer to both.
  /// A sign-in or sign-out made somewhere else on this computer — hn, a terminal's `harness login` or
  /// `harness logout` — that this window has not seen. The daemon says which on every ready probe
  /// (`/api/status.signedIn`), and the window follows it as it does its own: a guest window takes the
  /// sign-in ([_adoptSignInFromElsewhere]), a signed-in one becomes a guest ([_signedOutAtRuntime]).
  /// It used to learn the account only at launch and from its own buttons, so a sign-in from hn left
  /// Settings › Account saying "Not signed in" over a daemon that was signed in.
  ///
  /// Only on the CLI's own word (`harness auth status`), which owns the sign-in; asked at most every
  /// [_daemonAccountRecheck] while the two disagree, and never during this window's own sign-in or out.
  void _followDaemonAccount(LocalCliEndpoint endpoint) {
    final daemonSignedIn = endpoint.signedIn;
    if (daemonSignedIn == null ||
        viewer != null ||
        signingIn ||
        signingOut ||
        _followingDaemonAccount ||
        status != AppStatus.authenticated) {
      return;
    }
    final disagree = daemonSignedIn ? isGuest : signedIn;
    if (!disagree) return;
    final now = DateTime.now();
    if (_daemonAccountCheckedAt case final at?
        when now.difference(at) < _daemonAccountRecheck) {
      return;
    }
    _daemonAccountCheckedAt = now;
    unawaited(
      daemonSignedIn
          ? _adoptSignInFromElsewhere()
          : _followSignOutFromElsewhere(),
    );
  }

  static const _daemonAccountRecheck = Duration(seconds: 30);
  DateTime? _daemonAccountCheckedAt;
  bool _followingDaemonAccount = false;

  /// This computer was signed in elsewhere while this window was a guest: it ends as this window's own
  /// [login] does — the account's workspace built on the daemon the sign-in restarted.
  Future<void> _adoptSignInFromElsewhere() async {
    _followingDaemonAccount = true;
    int? revision;
    try {
      final confirmed = await cliLogin.checkStatus();
      if (_disposed ||
          !confirmed.loggedIn ||
          !isGuest ||
          signingIn ||
          signingOut) {
        return;
      }
      revision = _invalidateAuthWork();
      _closedHistory.clear();
      _monitorHarnesses.clear();
      _lastError = null;
      status = AppStatus.bootstrapping;
      notifyListeners();
      if (_workspaceCleanup case final cleanup?) {
        await cleanup;
        if (!_authWorkCurrent(revision)) return;
      }
      signedIn = true;
      await _finishBootstrapSignedIn();
      if (!_authWorkCurrent(revision) || status != AppStatus.authenticated) {
        return;
      }
      _guestDeskRestorePending = false;
    } catch (error) {
      debugPrint('AppNotifier: following a sign-in made elsewhere: $error');
      if (revision != null && _authWorkCurrent(revision)) {
        status = AppStatus.authenticated;
      }
    } finally {
      _followingDaemonAccount = false;
      if (!_disposed) notifyListeners();
    }
  }

  /// This computer was signed out elsewhere (hn, `harness logout`): this window becomes a guest, as it
  /// does when the account is lost under it.
  Future<void> _followSignOutFromElsewhere() async {
    _followingDaemonAccount = true;
    try {
      final confirmed = await cliLogin.checkStatus();
      if (_disposed ||
          confirmed.loggedIn ||
          !signedIn ||
          signingIn ||
          signingOut) {
        return;
      }
      _signedOutAtRuntime(_signedOutMessage);
    } catch (error) {
      debugPrint('AppNotifier: following a sign-out made elsewhere: $error');
    } finally {
      _followingDaemonAccount = false;
    }
  }

  /// Lets the next probe ask the CLI at once, as [_daemonAccountRecheck] later would.
  @visibleForTesting
  void debugForgetDaemonAccountCheckForTest() => _daemonAccountCheckedAt = null;

  /// Feeds [endpoint] to the daemon-account follower, as a ready probe does.
  @visibleForTesting
  void followDaemonAccountForTest(LocalCliEndpoint endpoint) =>
      _followDaemonAccount(endpoint);

  static const _signedOutMessage =
      'You were signed out on this computer. This computer\'s agents keep '
      'running; sign in again to continue.';

  /// Inject the same account-expiry event the connection pool reports, without a real daemon.
  @visibleForTesting
  void expireSessionForTest(String message) => _signedOutAtRuntime(message);

  /// A running session lost its account. Return to required sign-in while
  /// preserving this computer's saved workspace and running harnesses.
  void _signedOutAtRuntime(String message) {
    if (status == AppStatus.unauthenticated || isGuest) {
      return; // idempotent: several sources can race here
    }
    final revision = _invalidateAuthWork();
    cliLogin.cancel();
    _sessionExpired = true;
    currentUser = null;
    _provenMachineId = null;
    _keptProfileId = null;
    _profileConfirmed = false;
    unawaited(_profileCache.clear());
    signingIn = false;
    pendingAuthorizeUrl = null;
    final previousMachineId = localMachineState?.machine.machineId;
    _clearAccountWorkspace();
    // A VIEWER has nowhere to be but its login screen — no daemon, nothing of
    // its own to show.
    if (viewer != null || localManualFixture != null) {
      _lastError = message;
      _lastErrorRetryable = true;
      status = AppStatus.unauthenticated;
      notifyListeners();
      return;
    }
    // Restore local panes behind required sign-in. The daemon keeps serving
    // this computer so running agents survive; old account transports close.
    //
    // The work was invalidated above, so the guest transition runs under THIS
    // revision: invalidating again would clear [sessionExpired], and the banner
    // would read as a failed sign-in rather than as the session having ended.
    _closedHistory.clear();
    unawaited(
      _becomeGuest(
        banner: message,
        previousMachineId: previousMachineId,
        revision: revision,
      ),
    );
  }

  /// Remove the old account's live objects without overwriting its saved desk.
  /// In particular, multiple emptied tabs must not prevent the next restore.
  void _clearAccountWorkspace({bool notices = true}) {
    if (notices) _clearDeviceNoticeState();
    experimentalFeatures.bind(null);
    // The chat's pictures are the account's (task #3178).
    unawaited(superTabForgetPictures());
    agentMessages.reset();
    sharedTabs.reset();
    _sharedPlaced = null;
    _sharedRereadAsked.clear();
    _agentChanges.clear();
    ++_layoutRevision;
    // Sign-out sends the desk nothing: the tabs closing here are this window
    // leaving the account, not the person closing them.
    _deskRetry?.cancel();
    _deskRetry = null;
    _desk.reset();
    _stopAllOfflineRetries();
    _stopAllLinkRetries();
    _forgetAllTrustSettles();
    _stopAllAgentSyncTimers();
    _daemonSupervisionTimer?.cancel();
    _daemonSupervisionTimer = null;
    _sharingDiscoveryTimer?.cancel();
    _sharingDiscoveryTimer = null;
    _machinesPushTimer?.cancel();
    _machinesPushTimer = null;
    _deafMachineListWatch.stop();
    _groupSyncedAt.clear();
    _sharingDiscoveryBusy = false;
    _sharingDiscoveryAgain = false;
    _daemonGateFailed = false;
    _bootStatusMessage = null;
    _clearAllTurnActivity();
    // Start all terminal detachments while their original transports exist.
    final panesClosed = _closeAllPanes(persist: false);
    final pool = _pool;
    _pool = null;
    _cliEndpoint = null;
    _backendOnline = null;
    machines = [];
    machinesAreStale = false;
    machineStates.clear();
    sessionPreviews.clear();
    sessionTails.clear();
    shareStatus.clear();
    gridPictures.clear();
    // Pickers keep listening to this menu; only the old account's rows go.
    _modelsMenu?.reset();
    _stopWakeFollowers();
    expandedMachines.clear();
    selectedMachineId = null;
    _closedHistory.clear();
    _monitorHarnesses.clear();
    _draftSwarmReturns.clear();
    _localMismatchReported.clear();
    _dismissedLinkPrompts.clear();
    _requestedMachineLink = null;
    for (final controller in _orchestratorProjects.values) {
      controller.dispose();
    }
    _orchestratorProjects.clear();
    final starter = Swarm(id: 'swarm-${_nextSwarmId++}');
    swarms
      ..clear()
      ..add(starter);
    _activeSwarmId = starter.id;
    _autoPickedAgent = false;
    _trackWorkspaceCleanup(
      Future.wait<void>([panesClosed, if (pool != null) pool.closeAll()]),
    );
  }

  /// The old account's terminals detaching and its connections closing, which
  /// a sign-in waits for (see [login]) so it cannot overtake them: a new
  /// session must not be set up while the last one is still being torn down.
  /// Joins any teardown already in flight; completes when all of it has, and
  /// never with an error.
  Future<void> _trackWorkspaceCleanup(Future<void> work) {
    late final Future<void> cleanup;
    cleanup = Future.wait<void>([?_workspaceCleanup, work])
        .then<void>(
          (_) {},
          onError: (Object error) {
            debugPrint('account connection cleanup failed: $error');
          },
        )
        .whenComplete(() {
          if (identical(_workspaceCleanup, cleanup)) {
            _workspaceCleanup = null;
          }
        });
    _workspaceCleanup = cleanup;
    return cleanup;
  }

  void _startUpdateChecking() {
    _updateCheckTimer ??= _updater.startChecking(
      onCheckCompleted: (result) {
        if (_disposed) return;
        _recordUpdateCheck(result);
        notifyListeners();
      },
    );
  }

  void _recordUpdateCheck(DesktopUpdateCheck result, {bool manual = false}) {
    if (_disposed) return;
    lastUpdateCheck = result;
    if (windowsUpdatePartiallyPublished) return;
    if (isInstallingUpdate) return;
    final info = result.update;
    if (info != null) {
      if (!manual && _skippedDesktopUpdateVersion == info.version) {
        // A manual check may already be offering this skipped version. A
        // concurrent background answer must not withdraw that explicit offer.
        if (availableUpdate?.version != info.version) {
          availableUpdate = null;
          updateError = null;
        }
      } else {
        if (availableUpdate?.version != info.version) updateError = null;
        availableUpdate = info;
      }
    } else if (result.status == DesktopUpdateCheckStatus.upToDate) {
      availableUpdate = null;
      updateError = null;
    }
    // Failure/disabled leaves the last known offer and any install failure
    // intact. A check error is not an installation error or an all-clear.
  }

  /// A manual check deliberately returns a skipped version too, so the user
  /// can choose to install it from the account menu after changing their mind.
  Future<ManualUpdateCheck> checkForUpdates() {
    // Viewer builds are updated by their app store. Do not even construct a
    // desktop updater there: those platforms have no desktop artifact channel.
    if (viewer != null || _selfInstallUnavailable) {
      return Future.value(
        const ManualUpdateCheck(check: DesktopUpdateCheck.disabled()),
      );
    }
    final pending = _manualUpdateCheckInFlight;
    if (pending != null) return pending;
    if (_disposed) {
      return Future.value(
        const ManualUpdateCheck(check: DesktopUpdateCheck.failed()),
      );
    }
    final completion = Completer<ManualUpdateCheck>();
    _manualUpdateCheckInFlight = completion.future;
    isCheckingForUpdate = true;
    notifyListeners();
    unawaited(_checkForUpdates(completion));
    return completion.future;
  }

  Future<void> _checkForUpdates(Completer<ManualUpdateCheck> completion) async {
    final finish = productMeasurement.begin(ProductFlow.updateCheck);
    try {
      final result = await _updater.check();
      finish(
        result.status == DesktopUpdateCheckStatus.failed
            ? ProductOutcome.failed
            : result.status == DesktopUpdateCheckStatus.disabled
            ? ProductOutcome.cancelled
            : ProductOutcome.ok,
      );
      _recordUpdateCheck(result, manual: true);
      completion.complete(
        ManualUpdateCheck(
          check: result,
          isSkipped:
              result.update != null &&
              _skippedDesktopUpdateVersion == result.update!.version,
        ),
      );
    } catch (error) {
      finish(ProductOutcome.failed);
      debugPrint('AppNotifier.checkForUpdates: $error');
      const failed = DesktopUpdateCheck.failed();
      _recordUpdateCheck(failed);
      completion.complete(const ManualUpdateCheck(check: failed));
    } finally {
      _manualUpdateCheckInFlight = null;
      isCheckingForUpdate = false;
      if (!_disposed) notifyListeners();
    }
  }

  /// The build to install now: the newest the manifest offers, or [captured]
  /// when the manifest cannot be read or has nothing newer. Null means the
  /// manifest no longer offers anything at all — the build was pulled.
  ///
  /// Only ever forward: a manifest that regressed (a bad publish, a stale
  /// mirror) must not talk this into a downgrade, which is what `semverGt`
  /// settles. And never onto a version this person SKIPPED — pressing Update
  /// on one build is not consent to a different one they already said no to,
  /// and nothing is lost by installing what they pressed: the skipped newer
  /// one raises no offer afterwards either (`_recordUpdateCheck`).
  Future<UpdateInfo?> _freshestUpdate(UpdateInfo captured) async {
    final DesktopUpdateCheck result;
    try {
      result = await _updater.check();
    } catch (error) {
      // A network that cannot answer is not a reason to refuse an update whose
      // bytes are verified against their own sha256 anyway.
      debugPrint('AppNotifier.installAvailableUpdate: refresh failed · $error');
      return captured;
    }
    if (_disposed) return captured;
    lastUpdateCheck = result;
    final latest = result.update;
    if (latest != null) {
      final newer =
          semverGt(latest.version, captured.version) &&
          _skippedDesktopUpdateVersion != latest.version;
      return newer ? latest : captured;
    }
    return result.status == DesktopUpdateCheckStatus.upToDate ? null : captured;
  }

  /// Clears an untouched-install failure without burying the offer. A partial
  /// Windows publication clears the offer so it cannot prompt the same retry.
  ///
  /// Skipping is permanent — it records the version so the background check
  /// stops raising it. A failure is not a decision about the version, so the
  /// way out of one has to leave the update on the table.
  void dismissUpdateError() {
    if (updateError == null) return;
    updateError = null;
    if (windowsUpdatePartiallyPublished) availableUpdate = null;
    notifyListeners();
  }

  Future<void> skipAvailableUpdate({UpdateInfo? update}) async {
    final info = update ?? availableUpdate;
    if (_disposed || info == null || isInstallingUpdate) return;
    _skippedDesktopUpdateVersion = info.version;
    await _store?.saveSkippedDesktopUpdateVersion(info.version);
    if (_disposed) return;
    if (availableUpdate?.version == info.version) {
      availableUpdate = null;
      updateError = null;
    }
    notifyListeners();
  }

  /// Downloads, verifies, and installs only after an explicit user action.
  /// A Windows publication failure may leave installed files changed and
  /// requires a restart or launcher repair before another attempt.
  Future<bool> installAvailableUpdate({UpdateInfo? update}) async {
    final chosen = update ?? availableUpdate;
    if (_disposed ||
        viewer != null ||
        _selfInstallUnavailable ||
        chosen == null ||
        isInstallingUpdate ||
        windowsUpdatePartiallyPublished) {
      return false;
    }
    // Reassigned once the manifest has been re-read below; the failure messages
    // at the end name whichever build was actually attempted.
    final finish = productMeasurement.begin(ProductFlow.updateStage);
    void Function(ProductOutcome)? finishApply;
    var info = chosen;
    isInstallingUpdate = true;
    updateDownloadFraction = null;
    updateError = null;
    notifyListeners();
    try {
      final updater = _updater;
      // One press, the newest build. What is on screen can be minutes old, and
      // installing THAT only to be offered the next one on the way back is two
      // updates for one thing. The check costs a small GET against a manifest
      // the download already depends on.
      //
      // `isInstallingUpdate` is set above first, so the answer cannot race
      // `_recordUpdateCheck` — which bows out while an install is running —
      // and the offer is published here instead, once the version is settled.
      final fresh = await _freshestUpdate(info);
      if (fresh == null) {
        // Withdrawn from the channel between the offer and the press. Installing
        // a build that has just been pulled is the one outcome here worth
        // refusing; everything else falls through to the captured one.
        //
        // Not an `updateError`: nothing failed, and the banner that would carry
        // one is keyed on there being an offer — which there is not any more.
        // Dropping the offer IS the state, and the dialog that asked turns
        // itself into "You're up to date" on the false return.
        finish(ProductOutcome.cancelled);
        availableUpdate = null;
        updateError = null;
        return false;
      }
      info = fresh;
      availableUpdate = info;
      // Start the existing last-run flag while download I/O is in progress. Saving
      // it only just before exit races the asynchronous disk write on fast updates.
      // No reporting or disk flush is awaited by the update.
      productRuntimeHealth?.expectUpdate(info.version);
      // One notify per whole percent. Dio reports every chunk, and each notify
      // rebuilds the whole app shell (the banner lives in its ListenableBuilder),
      // so a 45 MB build would repaint thousands of times for a bar 200px wide.
      var shown = -1;
      final staged = await updater.downloadAndStage(
        info,
        onProgress: (received, total) {
          if (_disposed || total <= 0) return;
          final fraction = (received / total).clamp(0.0, 1.0);
          // The bytes are all in: verifying and unpacking follow, and neither
          // can be measured, so stop claiming a number for them.
          final next = fraction >= 1 ? null : fraction;
          final percent = next == null ? 100 : (next * 100).floor();
          if (percent == shown) return;
          shown = percent;
          updateDownloadFraction = next;
          notifyListeners();
        },
      );
      if (staged == null) {
        finish(ProductOutcome.failed);
        productRuntimeHealth?.cancelUpdate();
        updateError = 'Could not download and verify Harness ${info.version}.';
        return false;
      }
      // The next consented launch can confirm the version; never wait for reporting.
      finish(ProductOutcome.ok);
      finishApply = productMeasurement.begin(ProductFlow.updateApply);
      final applied = await updater.applyStaged(staged, selfPid: pid);
      finishApply(applied ? ProductOutcome.ok : ProductOutcome.failed);
      if (!applied) {
        productRuntimeHealth?.cancelUpdate();
        updateError =
            'This copy of Harness cannot install updates automatically.';
        return false;
      }
      flushAppLog(durable: true);
      productRuntimeHealth?.cleanExit();
      exit(0);
    } on WindowsPartialUpdateException catch (error) {
      finish(ProductOutcome.failed);
      finishApply?.call(ProductOutcome.failed);
      productRuntimeHealth?.cancelUpdate();
      windowsUpdatePartiallyPublished = true;
      updateError = error.launcherNeedsRepair
          ? 'Harness changed update files but could not finish. Close Harness, rename Harness.exe.old to Harness.exe in the install folder, then open Harness again.'
          : error.publicationIncomplete
          ? 'Harness changed update files but could not finish. Close Harness and open it again. The update may not be installed.'
          : 'Harness installed update files but could not open. Close Harness and open it again.';
      return false;
    } catch (error) {
      finish(ProductOutcome.failed);
      finishApply?.call(ProductOutcome.failed);
      productRuntimeHealth?.cancelUpdate();
      updateError = 'Could not install Harness ${info.version}: $error';
      return false;
    } finally {
      finish(ProductOutcome.unknown);
      finishApply?.call(ProductOutcome.unknown);
      isInstallingUpdate = false;
      updateDownloadFraction = null;
      if (!_disposed) notifyListeners();
    }
  }

  /// Sign in through the browser, on [provider]'s own sign-in. Without one — a caller with no
  /// button of its own to name it — the browser opens on the sign-in page's chooser.
  Future<void> login([SignInProvider? provider]) async {
    if (_disposed || signingIn || signingOut || signOutError != null) return;
    final measureSignIn = productMeasurement.begin(ProductFlow.signIn);
    var signedInHere = false;
    final wasGuest = isGuest;
    final revision = _invalidateAuthWork();
    _closedHistory.clear();
    _monitorHarnesses.clear();
    _lastError = null;
    status = AppStatus.bootstrapping;
    signingIn = true;
    signInProvider = provider;
    pendingAuthorizeUrl = null;
    notifyListeners();
    try {
      if (_workspaceCleanup case final cleanup?) {
        await cleanup;
        if (!_authWorkCurrent(revision)) return;
      }
      await cliLogin.login(
        provider: provider,
        onAuthorizeUrl: (url) {
          if (!_authWorkCurrent(revision)) return;
          if (pendingAuthorizeUrl == url) return;
          _resetLoginBrowser();
          pendingAuthorizeUrl = url;
          notifyListeners();
          // Through [openLoginBrowser] rather than straight to the launcher, so
          // the first handoff is the same one the login screen's retry button
          // takes and reports its outcome the same way. WHICH browser it opens
          // is decided in `viewer/sign_in_browser.dart`.
          unawaited(openLoginBrowser());
        },
      );
      if (!_authWorkCurrent(revision)) return;
      measureSignIn(ProductOutcome.ok);
      signedInHere = true;
      _loginAuthorized = true;
      pendingAuthorizeUrl = null;
      _resetLoginBrowser();
      notifyListeners();
      // The CLI has just restarted its daemon onto the account's machineId, so a
      // guest window's tiles are open on an id nothing serves any more. The
      // ordinary bootstrap ends by following that id (`_followLocalMachineId`),
      // which re-seats them — one path for a cold boot and for a sign-in, rather
      // than a second way to build a grid.
      signedIn = true;
      await _finishBootstrapSignedIn();
      if (!_authWorkCurrent(revision) || status != AppStatus.authenticated) {
        return;
      }
      _guestDeskRestorePending = false;
      // The first sign-in on this computer offers Add Phone; a later one does not.
      unawaited(_offerPhoneAfterSignIn(revision));
    } catch (error) {
      if (!signedInHere) _measureSignInEnd(measureSignIn, error, revision);
      if (!_authWorkCurrent(revision)) return;
      status = wasGuest ? AppStatus.authenticated : AppStatus.unauthenticated;
      _lastError = error.toString();
      _lastErrorRetryable = true;
      if (wasGuest && _guestDeskRestorePending && !signedIn) {
        unawaited(_becomeGuest(revision: revision));
      }
    } finally {
      measureSignIn(
        _authWorkCurrent(revision)
            ? ProductOutcome.unknown
            : ProductOutcome.cancelled,
      );
      // Takes the in-app browser view down once the redirect has landed; a no-op
      // where the page opened in a browser of its own.
      unawaited(closeSignInPage());
      // Cleared last, and only here: everything above may still be running when the URL goes, and
      // dropping the flag any earlier is what put a bare spinner over the user's own screen.
      if (_authWorkCurrent(revision)) {
        _resetLoginBrowser();
        _loginAuthorized = false;
        pendingAuthorizeUrl = null;
        signingIn = false;
      }
    }
    if (_authWorkCurrent(revision)) notifyListeners();
  }

  /// A sign-in that did not go through: its outcome, and why. The person moving on — Cancel, the
  /// other button, the app closing ([_authWorkCurrent] no longer) or turning it down on the phone —
  /// is `cancelled`, not `failed`. A page nobody came back from in time, or a QR nobody scanned, is
  /// `unknown`: they may have left, or finished and the callback never arrived, which only the
  /// reason (`timeout`, `expired`) tells apart from the rest. Everything else is `failed`.
  void _measureSignInEnd(
    void Function(ProductOutcome) finish,
    Object error,
    int revision,
  ) {
    final reason = revision == _refreshedAuthRevision
        ? SignInEndReason.expired
        : !_authWorkCurrent(revision)
        ? SignInEndReason.cancelled
        : switch (error) {
            SignInException(:final code) || PhoneSignInException(:final code) =>
              SignInEndReason.values.firstWhere(
                (reason) => reason.wire == code.toLowerCase(),
                orElse: () => SignInEndReason.other,
              ),
            CliNotAvailableException() => SignInEndReason.cliUnavailable,
            _ => SignInEndReason.other,
          };
    finish(switch (reason) {
      SignInEndReason.cancelled ||
      SignInEndReason.denied => ProductOutcome.cancelled,
      SignInEndReason.timeout ||
      SignInEndReason.expired => ProductOutcome.unknown,
      _ => ProductOutcome.failed,
    });
    productMeasurement.signInEnded(reason);
  }

  /// The failed sign-in again, to the account the person chose the first time.
  Future<void> retryLogin() => login(signInProvider);

  /// Whether the workspace offers Add Phone — "Your agents in your pocket.", a card in the window's
  /// top-right (`widgets/phone_offer_card.dart`): as a guest, whose Add Phone asks for the sign-in
  /// itself; signed in, on an account with no phone yet. Cleared when the account changes.
  ///
  /// ⚠️ **The phone's first screen counts on it (owner, 2026-10-08).** It tells a newcomer to open
  /// Add Phone on the computer (mobile `set_up_computer.dart`), so the button has to be on the
  /// screen without anyone finding it in a menu, or in the command palette on Linux. Not after
  /// [loginWithPhone]: that sign-in was a phone's, which has its way in already.
  ///
  /// ⚠️ **A card, not Add Phone opened by itself (owner, 2026-10-09).** A new install opens on
  /// agents already at work (`state/first_arrival.dart`); a dialog over them broke that first moment
  /// for everyone without a phone, to serve those with one. The card waits beside the work until it
  /// is used or put away.
  ///
  /// ⚠️ **Once per computer (owner, 2026-10-09)**, not once per sign-in: it is offered at the first
  /// launch, which a new install makes as a guest ([_offerPhoneAtLaunch]), or else after the first
  /// sign-in by hand ([_offerPhoneAfterSignIn]) — never again once Add Phone has been opened here,
  /// the card put away, or the account found to have a phone ([_phoneOfferDone]).
  ///
  /// Returning accounts get one launch card per account on this computer (owner, 2026-10-26),
  /// remembered only once on screen. It also spends the after-work showing and one away-card slot.
  /// The stopped record (a previous × or Add Phone opening) still rules out every later offer.
  bool get phoneOfferShowing => _phoneOffer;
  bool _phoneOffer = false;

  /// Which offer [_phoneOffer] is: the first one's, the one after work ([_offerPhoneAfterWork]) or
  /// the one after time away ([_offerPhoneAway]), each counted as its own flow.
  ProductFlow _phoneOfferFlow = ProductFlow.phoneOffer;
  String? _returningPhoneOfferAccount;
  bool _phoneOffersStoppedHere = false;

  int _phoneOfferSkipRevision = -1;
  final _phoneOfferSkips = <(String, String)>{};

  void _skipPhoneOffer(String path, String reason) {
    // Invalidation changes the revision on account transitions. Forget old
    // pairs rather than retaining a long-lived set for every previous account.
    if (_phoneOfferSkipRevision != _authRevision) {
      _phoneOfferSkips.clear();
      _phoneOfferSkipRevision = _authRevision;
    }
    if (_phoneOfferSkips.add((path, reason))) {
      productMeasurement.phoneOfferSkipped(reason);
    }
  }

  String? _phoneOfferBlock() {
    if (kIsWeb || viewer != null) return 'viewer';
    if (_phoneOffersStoppedHere) return 'stopped';
    if (_phoneOffer) return 'card_showing';
    if (!signedIn) return 'not_signed_in';
    if (_accountHasPhone) return 'has_phone';
    return null;
  }

  Future<String?> _phoneOfferStopReason({bool cap = false}) async {
    final storage = _paneLayout?.storage;
    if (storage == null) return 'no_storage';
    try {
      if (await storage.read(_phoneOfferStoppedKey) == '1') return 'stopped';
      if (cap &&
          (int.tryParse(await storage.read(_phoneOfferShowsKey) ?? '') ?? 0) >=
              phoneOfferMaxShows) {
        return 'cap_reached';
      }
      return null;
    } catch (_) {
      return 'no_storage';
    }
  }

  /// What the card says when it is offered after time away ([_offerPhoneAway]): the harness, whether
  /// it waited on the person or finished, and how many minutes ago. Null for the card's usual words.
  ({String agent, bool waited, int minutes})? get phoneOfferAway =>
      _phoneOffer ? _phoneOfferAway : null;
  ({String agent, bool waited, int minutes})? _phoneOfferAway;

  /// The card's observation ([ProductFlow.phoneOffer]): begun once it is on screen
  /// ([phoneOfferShown]), ended once — ok by its Add Phone, cancelled by its ×, unknown when the
  /// card goes another way (Add Phone opened from elsewhere, a sign-out).
  void Function(ProductOutcome)? _phoneOfferMeasure;

  /// The card is on screen. Its observation starts here, not at [_phoneOffer]: a new computer's
  /// first agents keep it off the screen while they open (`state/first_arrival.dart`). Once per
  /// offer, however often the card is built again.
  void phoneOfferShown() {
    if (!_phoneOffer || _phoneOfferMeasure != null) return;
    if (_phoneOfferFlow == ProductFlow.phoneOfferReturning) {
      final account = _returningPhoneOfferAccount;
      if (account != currentUser?.id) return;
      _markPhoneOfferDone();
      _paneLayout?.storage
          .write('phone_offer_returning.$account', '1')
          .catchError((_) {});
    }
    _markPhoneOfferSeen();
    _countPhoneOfferShown();
    _phoneOfferMeasure = productMeasurement.begin(_phoneOfferFlow);
  }

  void _endPhoneOffer(ProductOutcome outcome) {
    final finish = _phoneOfferMeasure;
    _phoneOfferMeasure = null;
    finish?.call(outcome);
  }

  /// Add Phone is opening, from [from]: counted by its way in, and this computer's offer spent
  /// ([dropPhoneOffer]) — ok for the card when it was the card's own button.
  void addPhoneOpened(AddPhoneOpening from) {
    productMeasurement.addPhoneOpened(from);
    if (from == AddPhoneOpening.offer) _endPhoneOffer(ProductOutcome.ok);
    _stopPhoneOffers();
    dropPhoneOffer();
  }

  /// The card's ×: put away for good ([dropPhoneOffer]), and no card after time away either.
  void dismissPhoneOffer() {
    _endPhoneOffer(ProductOutcome.cancelled);
    _stopPhoneOffers();
    dropPhoneOffer();
  }

  /// Add Phone was opened — from the card or by hand — or the card was put away: nothing is left to
  /// offer, now or on a later launch or sign-in. Also how a sign-in made from inside Add Phone (its
  /// "Sign in…") does not bring the card back.
  void dropPhoneOffer() {
    // Not by the card's own buttons ([addPhoneOpened], [dismissPhoneOffer]), which end it first.
    _endPhoneOffer(ProductOutcome.unknown);
    final showing = _phoneOffer;
    _phoneOffer = false;
    _phoneOfferAway = null;
    _markPhoneOfferDone();
    _markPhoneOfferSeen();
    if (showing) notifyListeners();
  }

  /// This computer's record that Add Phone has had its offer ([phoneOfferShowing]), in the desktop's
  /// state file beside the dial's ([DialState]).
  static const _phoneOfferDoneKey = 'phone_offer_done';

  /// [_phoneOfferDoneKey], once read or written.
  bool? _phoneOfferDoneHere;

  /// Whether Add Phone has had its offer on this computer.
  ///
  /// ⚠️ **Nowhere to remember it is taken as done.** A window with no state file (a test, a
  /// fixture) or one that cannot be read would offer Add Phone at every launch and sign-in — the
  /// very thing the record exists to stop — so it offers nothing.
  Future<bool> _phoneOfferDone() async {
    if (_phoneOfferDoneHere case final done?) return done;
    final storage = _paneLayout?.storage;
    if (storage == null) return true;
    try {
      return _phoneOfferDoneHere =
          (await storage.read(_phoneOfferDoneKey)) == '1';
    } catch (_) {
      return true;
    }
  }

  void _markPhoneOfferDone() {
    if (_phoneOfferDoneHere == true) return;
    _phoneOfferDoneHere = true;
    // Never awaited: a write that fails costs one more offer at the next launch.
    _paneLayout?.storage.write(_phoneOfferDoneKey, '1').catchError((_) {});
  }

  /// This computer's record that the card has been on its screen, or Add Phone opened here: unlike
  /// [_phoneOfferDoneKey], never written by a launch that only skipped the offer. What
  /// [_offerPhoneAfterWork] reads, so a computer sees the card once, whichever way it came.
  static const _phoneOfferSeenKey = 'phone_offer_seen';

  /// [_phoneOfferSeenKey], once read or written.
  bool? _phoneOfferSeenHere;

  /// Whether the card has had its one showing on this computer. Nowhere to remember it is taken as
  /// seen, as for [_phoneOfferDone].
  Future<bool> _phoneOfferSeen() async {
    if (_phoneOfferSeenHere case final seen?) return seen;
    final storage = _paneLayout?.storage;
    if (storage == null) return true;
    try {
      return _phoneOfferSeenHere =
          (await storage.read(_phoneOfferSeenKey)) == '1';
    } catch (_) {
      return true;
    }
  }

  void _markPhoneOfferSeen() {
    if (_phoneOfferSeenHere == true) return;
    _phoneOfferSeenHere = true;
    // Never awaited: a write that fails costs one more card on a later run.
    _paneLayout?.storage.write(_phoneOfferSeenKey, '1').catchError((_) {});
  }

  /// [_offerPhoneAfterWork] has been asked in this run, for this account: one devices read a run.
  bool _phoneOfferAfterWorkAsked = false;

  /// Device reads [_offerPhoneAfterWork] has had in this run that gave no list to judge by. An
  /// older CLI with no device list answers none at every finished turn, so it stops asking after
  /// [_phoneOfferUnansweredReads] rather than read at each one for the rest of the run.
  int _phoneOfferAfterWorkUnanswered = 0;
  static const _phoneOfferUnansweredReads = 3;

  /// A devices read in this run found a phone or a browser on this account: no card, and no read to
  /// find that out again at each return to the window ([_offerPhoneAway]) — each one reaches the
  /// backend through the daemon, for the many accounts that already have a phone.
  bool _accountHasPhone = false;

  /// The card for a computer that has never shown it ([_phoneOfferSeen]), on an account with no phone
  /// or browser yet: once, after one of the person's own harnesses here finished a turn — beside work
  /// that just went well, not over a launch.
  ///
  /// ⚠️ **Every computer that opened signed in was marked offered at launch and never saw the card**
  /// ([_offerPhoneAtLaunch]): in the week to 2026-10-19, 59 of the 103 people working on Desktop used
  /// no phone, with only the title bar's icon to find Add Phone by. Still once per computer: a computer that
  /// showed the first card, or opened Add Phone, has seen it.
  Future<void> _offerPhoneAfterWork() async {
    final blocked = _phoneOfferBlock();
    if (blocked != null) return _skipPhoneOffer('after_work', blocked);
    if (status != AppStatus.authenticated) {
      return _skipPhoneOffer('after_work', 'not_signed_in');
    }
    if (_phoneOfferAfterWorkAsked) {
      return _skipPhoneOffer(
        'after_work',
        _phoneOfferAfterWorkUnanswered >= _phoneOfferUnansweredReads
            ? 'read_limit'
            : 'already_shown',
      );
    }
    _phoneOfferAfterWorkAsked = true;
    final revision = _authRevision;
    final stopped = await _phoneOfferStopReason();
    if (stopped != null) return _skipPhoneOffer('after_work', stopped);
    if (await _phoneOfferSeen()) {
      return _skipPhoneOffer('after_work', 'already_shown');
    }
    // No list to judge by: asked again at a later finished turn, a few times a run at most.
    void unanswered() => _phoneOfferAfterWorkAsked =
        ++_phoneOfferAfterWorkUnanswered >= _phoneOfferUnansweredReads;
    bool hasPhone;
    try {
      final devices = await loadDevices();
      if (devices == null) {
        unanswered();
        return _skipPhoneOffer('after_work', 'no_device_list');
      }
      hasPhone = devices.devices.any(
        (device) => !device.isMachine && !device.self,
      );
    } catch (_) {
      unanswered();
      return _skipPhoneOffer('after_work', 'no_device_list');
    }
    if (!_authWorkCurrent(revision)) {
      return _skipPhoneOffer('after_work', 'account_changed');
    }
    final changed = _phoneOfferBlock();
    if (changed != null) return _skipPhoneOffer('after_work', changed);
    if (hasPhone) {
      _accountHasPhone = true;
      _markPhoneOfferSeen();
      return _skipPhoneOffer('after_work', 'has_phone');
    }
    _phoneOfferFlow = ProductFlow.phoneOfferAfterWork;
    _phoneOfferAway = null;
    _phoneOffer = true;
    notifyListeners();
  }

  /// [_offerPhoneAfterWork], as a finished turn runs it.
  @visibleForTesting
  Future<void> offerPhoneAfterWorkForTest() => _offerPhoneAfterWork();

  /// This computer's record that the person said no to the card (its ×) or opened Add Phone: no card
  /// after time away from then on ([_offerPhoneAway]).
  static const _phoneOfferStoppedKey = 'phone_offer_stopped';

  /// How many times a card has been on this computer's screen, every kind together ([phoneOfferShown]).
  static const _phoneOfferShowsKey = 'phone_offer_shows';

  /// The most cards a computer is shown, every kind together: a card left unanswered may come back
  /// after time away, but not forever.
  static const phoneOfferMaxShows = 3;

  /// How long the window must have been away for a harness's news to offer Add Phone: long enough to
  /// have left the computer, not only to have looked at another window.
  static const phoneOfferAwayAfter = Duration(minutes: 5);

  /// The clock time away is measured by. Injected so a test can move it.
  @visibleForTesting
  DateTime Function() phoneOfferClock = DateTime.now;

  /// When the window last left the front ([appLifecycleChanged]); null while it is in front.
  DateTime? _awaySince;

  /// The news a person away from the window missed that says best what a phone is for: a harness
  /// waiting on them first, else the first to finish, with when it happened ([_noteMissedWhileAway]).
  ({String agent, bool waited, DateTime at})? _missedWhileAway;

  void _stopPhoneOffers() {
    // A pending device read must not resurrect a card after Add Phone or ×.
    _phoneOffersStoppedHere = true;
    // Never awaited: a write that fails costs, at most, one more card after time away.
    _paneLayout?.storage.write(_phoneOfferStoppedKey, '1').catchError((_) {});
  }

  void _countPhoneOfferShown() {
    final storage = _paneLayout?.storage;
    if (storage == null) return;
    // Never awaited, and best effort: a count that is not kept costs one more card at most.
    unawaited(() async {
      try {
        final shows =
            int.tryParse(await storage.read(_phoneOfferShowsKey) ?? '') ?? 0;
        await storage.write(_phoneOfferShowsKey, '${shows + 1}');
      } catch (_) {}
    }());
  }

  /// [kind] of the harness [agent], called [title], told while the window was not in front: kept for
  /// the card when the person is back ([_offerPhoneAway]). Only one of the person's own harnesses here
  /// — not a shared computer's, not a plain terminal.
  void _noteMissedWhileAway(
    MachineState machine,
    Agent? agent,
    AlertKind kind,
    String title,
  ) {
    if (kind != AlertKind.done && kind != AlertKind.needsYou) return;
    if (agent == null ||
        machine.machine.isShared ||
        isTerminalEngine(agent.engine)) {
      return;
    }
    final waited = kind == AlertKind.needsYou;
    final missed = _missedWhileAway;
    // The longest wait or the earliest finish is the truest "while you were away"; a wait outranks
    // a finish, since that harness could not go on without the person.
    if (missed != null && (missed.waited || !waited)) return;
    _missedWhileAway = (agent: title, waited: waited, at: phoneOfferClock());
  }

  /// The card for a person back after [phoneOfferAwayAfter] or more away from the window, to a harness
  /// that waited on them or finished meanwhile ([missed]): what a phone would have told them where
  /// they were. On an account with no phone or browser yet, at most [phoneOfferMaxShows] cards a
  /// computer, and none once its card was put away or Add Phone opened ([_phoneOfferStopReason]).
  Future<void> _offerPhoneAway(
    ({String agent, bool waited, DateTime at}) missed,
  ) async {
    final blocked = _phoneOfferBlock();
    if (blocked != null) return _skipPhoneOffer('away', blocked);
    if (status != AppStatus.authenticated) {
      return _skipPhoneOffer('away', 'not_signed_in');
    }
    final revision = _authRevision;
    final stopped = await _phoneOfferStopReason(cap: true);
    if (stopped != null) return _skipPhoneOffer('away', stopped);
    bool hasPhone;
    try {
      final devices = await loadDevices();
      // No list to judge by: nothing this time; the next time away asks again.
      if (devices == null) return _skipPhoneOffer('away', 'no_device_list');
      hasPhone = devices.devices.any(
        (device) => !device.isMachine && !device.self,
      );
    } catch (_) {
      return _skipPhoneOffer('away', 'no_device_list');
    }
    if (!_authWorkCurrent(revision)) {
      return _skipPhoneOffer('away', 'account_changed');
    }
    final changed = _phoneOfferBlock();
    if (changed != null) return _skipPhoneOffer('away', changed);
    if (hasPhone) {
      _accountHasPhone = true;
      return _skipPhoneOffer('away', 'has_phone');
    }
    final minutes = phoneOfferClock().difference(missed.at).inMinutes;
    _phoneOfferFlow = missed.waited
        ? ProductFlow.phoneOfferAwayWaited
        : ProductFlow.phoneOfferAwayFinished;
    _phoneOfferAway = (
      agent: missed.agent,
      waited: missed.waited,
      minutes: minutes < 1 ? 1 : minutes,
    );
    _phoneOffer = true;
    notifyListeners();
  }

  /// The launch's half of the offer.
  ///
  /// ⚠️ **A new install opens as a guest**, on its desk, with no sign-in asked for — so "after the
  /// first sign-in" alone never came for the newcomer the phone sent here, who was left looking at a
  /// desk with no code on it. As a guest, Add Phone asks for the sign-in itself and then shows the
  /// code. A signed-in launch gets one returning-account card on this computer (owner, 2026-10-26),
  /// unless a phone already exists or the person stopped offers here.
  Future<void> _offerPhoneAtLaunch(int revision) async {
    if (kIsWeb || viewer != null) return _skipPhoneOffer('launch', 'viewer');
    if (!_authWorkCurrent(revision)) {
      return _skipPhoneOffer('launch', 'account_changed');
    }
    if (_phoneOffer) return _skipPhoneOffer('launch', 'card_showing');
    if (signedIn) {
      final stopped = await _phoneOfferStopReason();
      if (stopped != null) return _skipPhoneOffer('launch', stopped);
      // Boot loads the profile independently of machine discovery. Wait for that
      // identity here, without delaying the workspace or reading devices again.
      if (currentUser?.id?.isNotEmpty != true) await _loadProfile();
      final blocked = _phoneOfferBlock();
      if (blocked != null) return _skipPhoneOffer('launch', blocked);
      final account = currentUser?.id;
      if (account == null || account.isEmpty) {
        return _skipPhoneOffer('launch', 'not_signed_in');
      }
      try {
        if (await _paneLayout!.storage.read('phone_offer_returning.$account') ==
            '1') {
          return _skipPhoneOffer('launch', 'already_shown');
        }
        if (_accountHasPhone) return _skipPhoneOffer('launch', 'has_phone');
        final devices = await loadDevices();
        if (devices == null) return _skipPhoneOffer('launch', 'no_device_list');
        if (!_authWorkCurrent(revision) || currentUser?.id != account) {
          return _skipPhoneOffer('launch', 'account_changed');
        }
        final changed = _phoneOfferBlock();
        if (changed != null) return _skipPhoneOffer('launch', changed);
        if (devices.devices.any(
          (device) => !device.isMachine && !device.self,
        )) {
          _accountHasPhone = true;
          return _skipPhoneOffer('launch', 'has_phone');
        }
      } catch (_) {
        return _skipPhoneOffer('launch', 'no_device_list');
      }
      _returningPhoneOfferAccount = account;
      _phoneOfferFlow = ProductFlow.phoneOfferReturning;
      _phoneOfferAway = null;
      _phoneOffer = true;
      notifyListeners();
      return;
    }
    if (!isGuest) return _skipPhoneOffer('launch', 'not_signed_in');
    if (await _phoneOfferDone()) {
      return _skipPhoneOffer('launch', 'already_shown');
    }
    if (!_authWorkCurrent(revision) || !isGuest) {
      return _skipPhoneOffer('launch', 'account_changed');
    }
    _phoneOfferFlow = ProductFlow.phoneOffer;
    _phoneOfferAway = null;
    _phoneOffer = true;
    notifyListeners();
  }

  /// [_offerPhoneAtLaunch] or [_offerPhoneAfterSignIn], as launch and a sign-in by hand run them.
  @visibleForTesting
  Future<void> offerPhoneForTest({required bool atLaunch}) => atLaunch
      ? _offerPhoneAtLaunch(_authRevision)
      : _offerPhoneAfterSignIn(_authRevision);

  /// The first sign-in by hand on this computer offers Add Phone — unless the account already has a
  /// phone or a browser on it, which has its way in.
  Future<void> _offerPhoneAfterSignIn(int revision) async {
    final blocked = _phoneOfferBlock();
    if (blocked != null) return _skipPhoneOffer('sign_in', blocked);
    final stopped = await _phoneOfferStopReason();
    if (stopped != null) return _skipPhoneOffer('sign_in', stopped);
    if (await _phoneOfferDone()) {
      return _skipPhoneOffer('sign_in', 'already_shown');
    }
    var hasPhone = false;
    try {
      final devices = await loadDevices();
      hasPhone =
          devices?.devices.any((device) => !device.isMachine && !device.self) ??
          false;
    } catch (_) {
      // A list that cannot be read offers the card anyway: it costs one × to put away.
    }
    if (!_authWorkCurrent(revision)) {
      return _skipPhoneOffer('sign_in', 'account_changed');
    }
    final changed = _phoneOfferBlock();
    if (changed != null) return _skipPhoneOffer('sign_in', changed);
    if (hasPhone) {
      _markPhoneOfferDone();
      return _skipPhoneOffer('sign_in', 'has_phone');
    }
    _phoneOfferFlow = ProductFlow.phoneOffer;
    _phoneOfferAway = null;
    _phoneOffer = true;
    notifyListeners();
  }

  /// Sign in by a QR a signed-in phone approves, then a yes here to the account it names.
  Future<void> loginWithPhone() => _loginByApproval(ApprovalSignIn.phone);

  /// Sign in by a short code another signed-in device types in — a phone's Settings ▸ Sign in a
  /// computer ▸ Type a code instead, or a computer's Machines ▸ Approve a device — then a yes here.
  Future<void> loginWithCode() => _loginByApproval(ApprovalSignIn.code);

  /// The sign-in step's Scan with your phone and Sign in on another device. As [signInFromStep]:
  /// another way in under way ends and this one begins; the same one again changes nothing.
  Future<void> approveFromStep(ApprovalSignIn method) async {
    if (signingIn) {
      if (approvalSignIn == method) return;
      if (!canCancelLogin) return;
      cancelLogin();
    }
    await _loginByApproval(method);
  }

  /// A code's whole life at the backend, however often it is kept alive (`QR_SIGN_IN_MAX_LIFE_SEC`
  /// in backend `lib/harnessSession.ts`). Scholes's code ran out twice before he could type it
  /// (2026-10-31): the page swaps in a new one before then instead of showing a dead one.
  static const approvalCodeLife = Duration(minutes: 10);

  /// How long before a code's end the page swaps in the next: time for the swap itself, so the
  /// code on screen is always one that still works.
  static const approvalRefreshLead = Duration(seconds: 15);

  /// How many new codes a page left open gets before it stops asking (about an hour of them).
  /// Each is a sign-in record at the backend; a window nobody is looking at should not make them
  /// all night.
  static const maxApprovalRefreshes = 6;

  /// The approval sign-in under way, if any: what the step shows in place of its ways in.
  ApprovalSignIn? approvalSignIn;

  /// The code to type on another device ([loginWithCode]) while it waits for one to approve it.
  String? pendingSignInCode;

  /// When the page swaps in a new QR or code, for its "New code in" line. Null before the first.
  DateTime? approvalRefreshAt;

  Timer? _approvalRefresh;
  int _approvalRefreshes = 0;

  /// The attempt a refresh replaced: counted as expired, not as the person cancelling.
  int? _refreshedAuthRevision;

  Future<void> _loginByApproval(
    ApprovalSignIn method, {
    bool refreshing = false,
  }) async {
    final client = cliLogin;
    final supported = switch (method) {
      ApprovalSignIn.phone => client is PhoneSignInClient,
      ApprovalSignIn.code => client is CodeSignInClient,
    };
    if (_disposed ||
        (signingIn && !refreshing) ||
        signingOut ||
        signOutError != null ||
        !supported) {
      return;
    }
    final finish = productMeasurement.begin(ProductFlow.signIn);
    var signedInHere = false;
    var refreshAfter = false;
    final wasGuest = isGuest;
    final revision = _invalidateAuthWork();
    previousAccountEmail = currentUser?.email;
    _closedHistory.clear();
    _monitorHarnesses.clear();
    _lastError = null;
    status = AppStatus.bootstrapping;
    signingIn = true;
    signInProvider = null;
    pendingAuthorizeUrl = null;
    _clearPhoneSignIn();
    approvalSignIn = method;
    if (!refreshing) _approvalRefreshes = 0;
    notifyListeners();
    // When this attempt's code first showed, and how long a fresh one lives: the start of its
    // backend life, and the measure of a "less than usual" time left near its end.
    DateTime? shownAt;
    int? fullLife;
    void shown(int expiresIn) {
      final now = clock.now();
      shownAt ??= now;
      fullLife ??= expiresIn;
      var end = shownAt!.add(approvalCodeLife);
      // Less than a fresh code's time left: the backend is near the end of its life, whatever this
      // page assumes that life to be.
      final reported = now.add(Duration(seconds: expiresIn));
      if (expiresIn < fullLife! && reported.isBefore(end)) end = reported;
      final refreshAt = end.subtract(approvalRefreshLead);
      if (refreshAt == approvalRefreshAt) return;
      approvalRefreshAt = refreshAt;
      _approvalRefresh?.cancel();
      final wait = refreshAt.difference(now);
      _approvalRefresh = Timer(
        wait.isNegative ? Duration.zero : wait,
        () => _refreshApproval(revision),
      );
    }

    try {
      if (_workspaceCleanup case final cleanup?) {
        await cleanup;
        if (!_authWorkCurrent(revision)) return;
      }
      Future<bool> confirm(String email) {
        if (!_authWorkCurrent(revision)) return Future.value(false);
        final answer = _phoneConfirm = Completer<bool>();
        pendingConfirmEmail = email;
        notifyListeners();
        return answer.future;
      }

      switch (method) {
        case ApprovalSignIn.phone:
          await (client as PhoneSignInClient).loginWithPhone(
            onQr: (link, expiresIn) {
              if (!_authWorkCurrent(revision)) return;
              shown(expiresIn);
              if (pendingQrLink == link) return;
              pendingQrLink = link;
              notifyListeners();
            },
            onConfirm: confirm,
          );
        case ApprovalSignIn.code:
          await (client as CodeSignInClient).loginWithCode(
            onCode: (code, expiresIn) {
              if (!_authWorkCurrent(revision)) return;
              shown(expiresIn);
              if (pendingSignInCode == code) return;
              pendingSignInCode = code;
              notifyListeners();
            },
            onConfirm: confirm,
          );
      }
      if (!_authWorkCurrent(revision)) return;
      finish(ProductOutcome.ok);
      signedInHere = true;
      _loginAuthorized = true;
      _clearPhoneSignIn();
      notifyListeners();
      signedIn = true;
      await _finishBootstrapSignedIn();
      if (!_authWorkCurrent(revision) || status != AppStatus.authenticated) {
        return;
      }
      _guestDeskRestorePending = false;
    } catch (error) {
      if (!signedInHere) _measureSignInEnd(finish, error, revision);
      if (!_authWorkCurrent(revision)) return;
      // The code ran out before anyone used it (or while the person answered): a new one, on the
      // same page, until the bound.
      if (!signedInHere &&
          error is PhoneSignInException &&
          error.code == 'EXPIRED' &&
          _approvalRefreshes < maxApprovalRefreshes) {
        refreshAfter = true;
      } else {
        status = wasGuest ? AppStatus.authenticated : AppStatus.unauthenticated;
        _lastError = error is PhoneSignInException && error.code == 'EXPIRED'
            ? _approvalRanOut
            : error.toString();
        _lastErrorRetryable = true;
        if (wasGuest && _guestDeskRestorePending && !signedIn) {
          unawaited(_becomeGuest(revision: revision));
        }
      }
    } finally {
      finish(
        _authWorkCurrent(revision)
            ? ProductOutcome.unknown
            : ProductOutcome.cancelled,
      );
      if (_authWorkCurrent(revision)) {
        _loginAuthorized = false;
        _clearPhoneSignIn();
        signingIn = false;
      }
    }
    if (refreshAfter && _authWorkCurrent(revision)) {
      _approvalRefreshes++;
      // Synchronously up to its first wait, so no frame shows the ways in between the two codes.
      unawaited(_loginByApproval(method, refreshing: true));
      return;
    }
    if (_authWorkCurrent(revision)) notifyListeners();
  }

  static const _approvalRanOut =
      'The code ran out. Choose a way to sign in when you are ready.';

  /// The QR or code on screen is about to end: replace it with a new one, unless the person is
  /// answering whose account approved it — that answer belongs to this code.
  void _refreshApproval(int revision) {
    final method = approvalSignIn;
    if (!_authWorkCurrent(revision) ||
        !signingIn ||
        method == null ||
        pendingConfirmEmail != null ||
        approvalAnswered) {
      return;
    }
    _refreshedAuthRevision = revision;
    if (_approvalRefreshes >= maxApprovalRefreshes) {
      // Out of new codes: back to the ways in, saying why, with no dead code left on screen.
      final next = _invalidateAuthWork();
      signingIn = false;
      _clearPhoneSignIn();
      status = isGuest ? AppStatus.authenticated : AppStatus.unauthenticated;
      _lastError = _approvalRanOut;
      _lastErrorRetryable = true;
      cliLogin.cancel();
      notifyListeners();
      if (isGuest && _guestDeskRestorePending) {
        unawaited(_becomeGuest(revision: next));
      }
      return;
    }
    _approvalRefreshes++;
    cliLogin.cancel();
    unawaited(_loginByApproval(method, refreshing: true));
  }

  /// The person said yes to the account that approved: the QR or code has done its work, and no new
  /// one replaces it while the session is claimed.
  bool approvalAnswered = false;

  /// The person's answer to "Sign in as [pendingConfirmEmail]?".
  void confirmPhoneSignIn(bool yes) {
    final answer = _phoneConfirm;
    _phoneConfirm = null;
    pendingConfirmEmail = null;
    if (yes && answer != null && !answer.isCompleted) {
      approvalAnswered = true;
      approvalRefreshAt = null;
      _approvalRefresh?.cancel();
      _approvalRefresh = null;
    }
    if (answer != null && !answer.isCompleted) answer.complete(yes);
    notifyListeners();
  }

  void _clearPhoneSignIn() {
    pendingQrLink = null;
    pendingSignInCode = null;
    pendingConfirmEmail = null;
    approvalSignIn = null;
    approvalAnswered = false;
    approvalRefreshAt = null;
    _approvalRefresh?.cancel();
    _approvalRefresh = null;
    final answer = _phoneConfirm;
    _phoneConfirm = null;
    if (answer != null && !answer.isCompleted) answer.complete(false);
  }

  void _resetLoginBrowser() {
    ++_loginBrowserRevision;
    openingLoginBrowser = false;
    loginBrowserError = null;
  }

  /// Reopens the current authorization URL without creating another login.
  Future<void> openLoginBrowser() async {
    final url = pendingAuthorizeUrl;
    if (_disposed || !signingIn || url == null || openingLoginBrowser) return;
    final authRevision = _authRevision;
    final browserRevision = ++_loginBrowserRevision;
    openingLoginBrowser = true;
    loginBrowserError = null;
    notifyListeners();
    var opened = false;
    try {
      final uri = Uri.tryParse(url);
      if (uri != null &&
          uri.hasAuthority &&
          (uri.scheme == 'https' || uri.scheme == 'http')) {
        // Not `launchUrl(..., externalApplication)` directly: on a desktop
        // [openSignInPage] IS that call, and on a phone it must not be. Handing
        // a phone to Safari suspends this app, and with it the loopback listener
        // the page redirects back to — the sign-in could then never land.
        // ⚠️ The reason the desktop insists on a real browser survives here: this
        // SSO page's Google button uses Google's popup-based Identity Services
        // flow, where a popup window posts the result back to its opener. Whether
        // an in-app browser view can satisfy that is open, and flagged in
        // `sign_in_browser.dart`; it is why the phone case is confined to phones
        // rather than made the rule.
        opened = await openSignInPage(uri);
      }
    } catch (_) {
      // Browser handoff failure is recoverable within the same sign-in. Never
      // put a credential-bearing URL or a raw platform exception in the UI.
    }
    if (!_authWorkCurrent(authRevision) ||
        browserRevision != _loginBrowserRevision ||
        pendingAuthorizeUrl != url) {
      return;
    }
    openingLoginBrowser = false;
    if (!opened) {
      loginBrowserError =
          'Couldn’t open your browser. Open it again or copy the sign-in link.';
    }
    notifyListeners();
  }

  /// Return immediately; late URLs, results and browser replies belong to the
  /// cancelled attempt and cannot change a subsequent sign-in.
  void cancelLogin() {
    if (_disposed || !canCancelLogin) return;
    final revision = _invalidateAuthWork();
    signingIn = false;
    pendingAuthorizeUrl = null;
    _clearPhoneSignIn();
    status = isGuest ? AppStatus.authenticated : AppStatus.unauthenticated;
    _lastError = null;
    _lastErrorRetryable = false;
    cliLogin.cancel();
    notifyListeners();
    // Cancellation can supersede the guest restore while old terminals are
    // still detaching. Resume that restore under the new revision.
    if (isGuest && _guestDeskRestorePending) {
      unawaited(_becomeGuest(revision: revision));
    }
  }

  Future<void> logout() {
    if (_disposed) return Future<void>.value();
    if (_logoutInFlight case final pending?) return pending;
    final completion = Completer<void>();
    final result = _logoutInFlight = completion.future;
    unawaited(
      _logout().then(
        (_) {
          _logoutInFlight = null;
          completion.complete();
        },
        onError: (Object error, StackTrace stack) {
          _logoutInFlight = null;
          completion.completeError(error, stack);
        },
      ),
    );
    return result;
  }

  Future<void> _logout() async {
    // Signing out takes this app's key out of the account's devices, while the sign-in still works
    // to say so. Best effort, and brief: signing out must not wait on the network.
    if (_deviceLog case final log?) {
      try {
        await log.leave().timeout(const Duration(seconds: 5));
      } catch (_) {}
    }
    final revision = _invalidateAuthWork();
    final previousMachineId = localMachineState?.machine.machineId;
    cliLogin.cancel();
    signingIn = false;
    _clearPhoneSignIn();
    signingOut = true;
    signOutError = null;
    _lastError = null;
    pendingAuthorizeUrl = null;
    _closedHistory.clear();
    _monitorHarnesses.clear();
    // What was said about the account's devices was about this account's.
    _clearDeviceNoticeState();
    // A viewer goes back to its login screen; desktop returns to its required
    // sign-in page once credentials are cleared. Its local daemon and agents
    // keep running, and the rebind preserves the desk for the next sign-in.
    // The local-manual dev fixture goes back to the login screen too: it has
    // no daemon of its own, and a guest desk would be served by the REAL CLI.
    final becomesGuest = viewer == null && localManualFixture == null;
    if (!becomesGuest) status = AppStatus.unauthenticated;
    currentUser = null;
    _provenMachineId = null;
    _keptProfileId = null;
    _profileConfirmed = false;
    unawaited(_profileCache.clear());
    notifyListeners();
    // Clear saved credentials alongside connection cleanup. A new login must
    // wait for both, otherwise the old logout can delete its fresh session.
    // Disconnecting a development fixture must leave the real CLI alone.
    final cleared = localManualFixture != null
        ? Future<bool>.value(true)
        : Future<void>.sync(cliLogin.logout)
              .then((_) => true, onError: (Object _) => false);
    _clearAccountWorkspace(notices: false);
    notifyListeners();
    await _workspaceCleanup;
    final didClear = await cleared;
    if (!_authWorkCurrent(revision)) return;
    signingOut = false;
    signOutError = didClear
        ? null
        : 'Your saved sign-in could not be cleared. Try signing out again.';
    if (becomesGuest && didClear) {
      // Explicit sign-out returns to the required page. Set both together so
      // its getter cannot consume the gate under the account that just left.
      signedIn = false;
      _signInStep = true;
    }
    notifyListeners();
    // The CLI restarts its daemon signed out (`harness logout` does it itself),
    // so this window waits for that one and sits its desk back down on the id it
    // serves. In the background: the person asked to sign out, and that is done.
    if (becomesGuest && didClear) {
      unawaited(
        _becomeGuest(previousMachineId: previousMachineId, revision: revision),
      );
    }
  }

  /// The backend refused to select [machine] ([code]), straight or through this computer's daemon.
  void _selectRefused(MachineState machine, String code) {
    final name = machine.machine.displayName;
    if (code == 'NOT_YOUR_MACHINE' && machine.machine.machineShare != null) {
      // Its owner stopped sharing it: no retry brings it back, and the list drops it.
      _noteSharingEnded(machine.machine);
      _lastError =
          '${machine.machine.machineShare!.owner} stopped sharing $name with you.';
      _lastErrorRetryable = false;
      _sharingEndedError = (
        machineId: machine.machine.machineId,
        text: _lastError!,
      );
      unawaited(refreshMachines());
    } else {
      _lastError = machineSelectErrorText(code, name);
      _lastErrorRetryable =
          code != 'NOT_YOUR_MACHINE' && code != 'MACHINE_ENV_MISMATCH';
      // Removed from the account: its socket has stopped (WsConn), and the account's list, read
      // again, takes it out of the list and its tabs. Prod, 2026-10-28: a laptop removed in
      // September was still selected every few seconds.
      if (code == 'NOT_YOUR_MACHINE') unawaited(refreshMachines());
    }
    machine.connectionStatus = ConnectionStatus.disconnected;
  }

  void _onLocalFailure(String machineId, int code, String reason) {
    final machine = machineStates[machineId];
    if (machine == null) return;
    // The daemon's relay closing for a refusal no redial changes (WsConn), with the backend's code.
    if (finalSelectRefusals.contains(reason)) {
      productConnections.refused(
        machineId,
        ProductHealthMeasure.connectErrorOther,
      );
      _selectRefused(machine, reason);
      notifyListeners();
      return;
    }
    productConnections.refused(
      machineId,
      code == 4404
          ? ProductHealthMeasure.connectErrorUnlinked
          : code == 4401 || code == 4403
          ? ProductHealthMeasure.connectErrorAuth
          : ProductHealthMeasure.connectErrorOther,
    );
    if (code == 4403) {
      if (machine.isLocalMachine) {
        unawaited(_onLocalMachineMismatch(machine, reason));
      }
      return;
    }
    if (code != 4404) return;
    // A viewer refused for want of trust is usually only early: its key not yet in the account's
    // device log, or the machine not yet in this app's copy of it — a computer signed in after this
    // app did. That is settled first ([_settleTrust]), while the machine keeps showing as connecting;
    // only a refusal that outlasts it asks for a password.
    if (_deviceLog != null &&
        (reason == 'NO_PEER_LINK' || reason == 'E2E_DENIED')) {
      if ((_trustRounds[machineId] ?? 0) < _trustSettleRounds) {
        if (_trustSettling.add(machineId)) {
          unawaited(_settleTrust(machineId, reason));
        }
        return;
      }
      if (!machine.needsLink) {
        appLog.info(
          'link',
          '${_shortId(machineId)} still refused ($reason) after the device list was checked',
        );
      }
    }
    // A machine the account's device key log names may simply not have read it yet: read it again,
    // and the link retry below picks the machine up once it has.
    if (_deviceLog case final log?) unawaited(log.refresh());
    _markNeedsLink(machineId, machine);
  }

  void _markNeedsLink(String machineId, MachineState machine) {
    // The local CLI's relay found no linked trust for this machine — it now owns E2EE entirely.
    // A `harness link connect` run in a terminal (or another app instance) has no way to notify
    // this one directly, so poll every few seconds until it's picked up instead of waiting for
    // the user to click back into this machine.
    machine.needsLink = true;
    machine.agentLoadStatus = AgentLoadStatus.needsLink;
    // A 4404 can also arrive MID-SESSION ("peer revoked trust" in the CLI's
    // remoteRelay.ts) with terminals open on this machine. The disconnect
    // that follows deliberately no longer marks the node offline (see the
    // onStatus branch in _ensurePool), so the tiles have to be told here
    // instead — otherwise they keep rendering as live until a heartbeat
    // fails, and nothing records what to reattach once the machine is linked
    // again.
    _markSessionsUnreachable(
      machine,
      'This machine is no longer linked. Link it again to reconnect.',
    );
    notifyListeners();
    _startLinkRetry(machineId);
  }

  // -- a viewer refused for want of trust ([_onLocalFailure]) --------------------------------------

  /// How many refusals of each machine were settled since it last connected, and the ones under way —
  /// each with what ends its wait early (a pin landing: [_redialPinnedMachines]).
  final Map<String, int> _trustRounds = {};
  final Set<String> _trustSettling = {};
  final Map<String, Completer<void>> _trustWakes = {};
  static const _trustSettleRounds = 2;

  /// How long one settling round waits for the machine's key to land before dialling again: two
  /// rounds, about fifteen seconds, before a password is asked for.
  @visibleForTesting
  Duration trustSettleRound = const Duration(milliseconds: 7500);

  /// How long a machine that denied this app's key gets to read the account's log again (its CLI
  /// does on a hello from a key it does not know) before the first hello is said again.
  @visibleForTesting
  Duration trustDeniedWait = const Duration(seconds: 1);

  /// Hears every [_redial], for a test with no pool to dial through.
  @visibleForTesting
  void Function(String machineId)? onRedialForTest;

  static String _shortId(String id) => id.length > 8 ? id.substring(0, 8) : id;

  /// One round of settling [machineId]'s refusal ([reason]: `NO_PEER_LINK`, no key here for it, or
  /// `E2E_DENIED`, the machine does not know this app's): put this app into the account's device log
  /// and read it, then dial again — at once when the machine's key just landed, after a moment for a
  /// machine that has to read the log itself. A frozen log can settle nothing: the password it is.
  Future<void> _settleTrust(String machineId, String reason) async {
    final log = _deviceLog;
    if (log == null) return;
    final revision = _authRevision;
    final round = _trustRounds[machineId] = (_trustRounds[machineId] ?? 0) + 1;
    final wake = _trustWakes[machineId] = Completer<void>();
    final short = _shortId(machineId);
    bool current() =>
        !_disposed &&
        _authWorkCurrent(revision) &&
        identical(_trustWakes[machineId], wake) &&
        machineStates.containsKey(machineId);
    final started = Stopwatch()..start();
    try {
      final registration = await log.ensureRegistered().timeout(
        trustSettleRound,
        onTimeout: () => DeviceLogRegistration.missing,
      );
      if (!current()) return;
      if (registration == DeviceLogRegistration.frozen) {
        appLog.info(
          'link',
          '$short refused ($reason): the device list is frozen',
        );
        // The machine's password prompt says so (deviceListNeedsReview), from the listing.
        unawaited(_syncPendingDevices());
        _trustRounds[machineId] = _trustSettleRounds;
        _endTrustSettle(machineId);
        final machine = machineStates[machineId]!
          ..connectionStatus = ConnectionStatus.disconnected;
        _markNeedsLink(machineId, machine);
        return;
      }
      if (registration == DeviceLogRegistration.registered) {
        appLog.info(
          'link',
          '$short refused ($reason): this app joined the device list',
        );
      }
      final pinned = await _holdsMachineKey(machineId);
      if (!current()) return;
      if (reason == 'E2E_DENIED' || !pinned) {
        final rest = trustSettleRound - started.elapsed;
        final wait = reason == 'E2E_DENIED' && round == 1
            ? trustDeniedWait
            : rest.isNegative
            ? Duration.zero
            : rest;
        await Future.any([Future<void>.delayed(wait), wake.future]);
        if (!current()) return;
      }
      final now = pinned || await _holdsMachineKey(machineId);
      if (!current()) return;
      appLog.info(
        'link',
        '$short refused ($reason): ${now ? 'pinned' : 'no key yet'}, dialling again (round $round)',
      );
      _endTrustSettle(machineId);
      _redial(machineId);
    } finally {
      // However the round ended, a machine no longer being settled can be settled again.
      if (identical(_trustWakes[machineId], wake)) _endTrustSettle(machineId);
    }
  }

  void _endTrustSettle(String machineId) {
    _trustSettling.remove(machineId);
    final wake = _trustWakes.remove(machineId);
    if (wake != null && !wake.isCompleted) wake.complete();
  }

  /// [machineId] connected, or the account is left: its refusals start counting again.
  void _forgetTrustSettle(String machineId) {
    _trustRounds.remove(machineId);
    _endTrustSettle(machineId);
  }

  void _forgetAllTrustSettles() {
    for (final machineId in [..._trustRounds.keys, ..._trustSettling]) {
      _forgetTrustSettle(machineId);
    }
  }

  Future<bool> _holdsMachineKey(String machineId) async {
    try {
      return await viewer?.keys.peer(machineId) != null;
    } catch (_) {
      return false;
    }
  }

  /// Dial [machineId] again from scratch: a refused connection is closed for good
  /// ([WsConn.isClosed]), so it is closed and replaced, as the link retry does.
  void _redial(String machineId) {
    final machine = machineStates[machineId];
    if (machine == null) return;
    onRedialForTest?.call(machineId);
    unawaited(_pool?.closeMachine(machineId));
    _connectMachine(machine);
  }

  /// The device log changed: a machine waiting on trust — being settled, or asking for its password —
  /// that this app now holds a key for is dialled again at once rather than on the next retry tick.
  Future<void> _redialPinnedMachines() async {
    final revision = _authRevision;
    for (final entry in [...machineStates.entries]) {
      final machineId = entry.key;
      if (!_trustSettling.contains(machineId) && !entry.value.needsLink) {
        continue;
      }
      if (!await _holdsMachineKey(machineId) || !_authWorkCurrent(revision)) {
        continue;
      }
      if (_trustWakes[machineId] case final wake? when !wake.isCompleted) {
        wake.complete();
      } else if (entry.value.needsLink &&
          identical(machineStates[machineId], entry.value)) {
        appLog.info(
          'link',
          '${_shortId(machineId)} pinned from the device list, dialling again',
        );
        _redial(machineId);
      }
    }
  }

  /// The daemon on this computer closed our select with 4403: it serves a different machine id than
  /// the row we hold for "this computer". Ask it which (`/api/status.machineId`), say so in the log —
  /// this used to be a silent reconnect every 30s, forever — and stand its machine up beside the
  /// stale row so the person can keep working; the stale row's tiles are told why they are dark. A
  /// machine list refresh re-keys everything properly once the backend answers.
  Future<void> _onLocalMachineMismatch(
    MachineState machine,
    String reason,
  ) async {
    final machineId = machine.machine.machineId;
    if (!_localMismatchReported.add(machineId)) return;
    final endpoint = viewer == null ? await _discovery.discover() : null;
    final served = endpoint?.machineId;
    appLog.warn(
      'daemon',
      'refused machine_select for $machineId ($reason) — the daemon serves '
          '${served ?? 'an unknown machine id'}',
    );
    if (_disposed || served == null || served == machineId) return;
    _markSessionsUnreachable(
      machine,
      'This computer now runs as a different machine (sign-in changed). Open it from the rail.',
    );
    // Awaited: the close reports `disconnected`, whose handler arms the offline retry — stopping
    // it before that would be undone a microtask later. `_connectMachine` also refuses this id now.
    await _pool?.closeMachine(machineId);
    _stopOfflineRetry(machineId);
    if (!machineStates.containsKey(served)) {
      _adoptLocalMachineFromDaemon(
        endpoint,
        await _discovery.computerId(),
        listUnavailable: _backendOnline == false,
      );
      final adopted = machineStates[served];
      if (adopted != null) {
        adopted.localEndpoint = endpoint;
        adopted.transportMode = MachineTransportMode.localPlaintext;
        _connectMachine(adopted);
      }
    }
    notifyListeners();
    if (_backendOnline != false) unawaited(retryMachines());
  }

  /// Local machine ids a 4403 has already been reported for — one log line and one adoption per
  /// stale id, not one per 30s retry.
  final Set<String> _localMismatchReported = {};

  void _ensurePool() {
    if (_pool != null) return;
    _pool = WsPool(
      localTransport: viewer == null ? localDaemonTransport : null,
      wsBaseUrl: config.wsBaseUrl,
      autonomousEnv: _autonomousEnv,
      // Every real desktop WsConn dials the local CLI's loopback WS (transportKind.localPlaintext, see
      // _conn()), which never calls this — only the compile-time-only local-manual dev fixture (see
      // LocalManualFixture) still dials a backend directly with a token.
      accessTokenProvider: (force, failedToken) async {
        final directAuth = viewer?.auth;
        if (directAuth != null) {
          return directAuth.accessToken(force: force, failedToken: failedToken);
        }
        final fixture = localManualFixture;
        if (fixture != null) return fixture.apiKey;
        throw StateError(
          'unreachable: only a viewer build and the local-manual dev fixture use a token-bearing WS transport',
        );
      },
      relayCodecs: viewer?.relayCodecs,
      transportPlugins: viewer?.transportPlugins,
      onAuthFailure: _signedOutAtRuntime,
      onLocalFailure: _onLocalFailure,
      onEvent: _handleEvent,
      onStatus: _onConnectionStatus,
    );
  }

  void _onConnectionStatus(String machineId, ConnectionStatus nextStatus) {
    final machine = machineStates[machineId];
    if (machine == null) return;
    // A refusal being settled against the device log ([_settleTrust]) is still connecting.
    final settling =
        nextStatus == ConnectionStatus.disconnected &&
        _trustSettling.contains(machineId);
    final retryingLink =
        machine.needsLink &&
        (nextStatus == ConnectionStatus.connecting ||
            nextStatus == ConnectionStatus.reconnecting);
    // A forced redial ([_forceRedial]) takes a connected link down and dials it again: neither a
    // person nor the app connecting, so it opens no observation of its own, and one already open
    // still ends with it. Each one used to start a new remote_connect; the day #1378 made dead panes
    // redial, prod's remote_connect went from 1,683 to 2,834 started and 106 to 205 unknown
    // (2026-10-15 → 16). Bounded by the window, so a redial that never reported back cannot hide a
    // later ordinary connection.
    final forcedSince = _forcedRedials[machineId];
    final forced =
        forcedSince != null && redialClock() - forcedSince < forcedRedialWindow;
    if (!forced ||
        nextStatus == ConnectionStatus.connected ||
        (nextStatus == ConnectionStatus.disconnected && !settling)) {
      _forcedRedials.remove(machineId);
    }
    productConnections.status(
      machineId,
      connecting:
          settling ||
          nextStatus == ConnectionStatus.connecting ||
          nextStatus == ConnectionStatus.reconnecting,
      connected: nextStatus == ConnectionStatus.connected,
      suppressStart: (viewer == null && retryingLink) || forced,
      failure: machine.needsLink
          ? ProductHealthMeasure.connectErrorUnlinked
          : machine.nodeOnline == false
          ? ProductHealthMeasure.connectErrorOffline
          : null,
    );
    // An unlinked machine used to be redialled every 5 s and refused at once each time
    // (4404 NO_PEER_LINK): measured per dial, one such machine read as ~720 failed connects an hour,
    // and prod's first day showed 1,197 of 1,233 remote connects "failed", nearly all under a second.
    // The dial that found it unlinked is already open and still ends as one failure; the retry's
    // dials are not new attempts. A dial after linking (needsLink cleared first) is measured again.
    if (!retryingLink) {
      _measureConnection(
        machineId,
        settling ? ConnectionStatus.connecting : nextStatus,
        machine.isLocalMachine
            ? ProductFlow.workspaceConnect
            : ProductFlow.remoteConnect,
        suppressStart: forced,
      );
    }
    machine.connectionStatus = settling
        ? ConnectionStatus.connecting
        : nextStatus;
    if (nextStatus == ConnectionStatus.connected) {
      _onMachineConnected(machineId, machine);
      _refreshDeviceLogAfterReconnect();
    } else if (nextStatus == ConnectionStatus.reconnecting ||
        nextStatus == ConnectionStatus.disconnected) {
      _stopAgentSyncTimer(machineId);
      _clearMachineActivity(machine);
      if (machine.isLocalMachine) {
        machine.transportMode = MachineTransportMode.localOffline;
        dial.disconnect();
      }
      // Same reasoning as above, mirrored: capture pendingOfflineAgentId from the currently-open
      // terminal (if any) so the connected branch above can reattach it, for every machine — this
      // used to be local-only, which is why a remote machine's terminal never came back on its own
      // after `harness start` on that machine, even though the guide screen promised it would.
      //
      // NOT while the machine is unlinked. NO_PEER_LINK is the local CLI failing a lookup in its
      // own peer table (remoteRelay.ts `dial`) before anything is dialled, so neither that close
      // nor the one `_startLinkRetry`'s `closeMachine` fires every few seconds says anything about
      // whether the OTHER computer is up — our socket never reaches it. Forcing nodeOnline false
      // here overwrote the REST `/api/machines` status, the one signal that does, and painted
      // every unlinked machine as off. Keyed on the sticky flag rather than the 4404 close on
      // purpose: the retry loop's own close() lands as a plain `disconnected` too. needsLink is
      // set by onLocalFailure, which runs before this branch for 4404 (see WsConn._onDone).
      if (!machine.needsLink && !settling) {
        unawaited(
          _applyNodeStatus(machine, false, why: 'socket ${nextStatus.name}'),
        );
      }
    }
    // Natively, Swarm reads go through this computer's daemon: the moment it
    // can serve them again, the Swarm on screen reads
    // (`SuperTabReading.readsOnConnect`). The web reads the backend itself,
    // so a machine connecting there is no reason to read.
    if (viewer == null) {
      final served =
          sharedTabsTarget?.connectionStatus == ConnectionStatus.connected;
      if (served && !_superTabsServed) superTabs.serverAvailable();
      _superTabsServed = served;
    }
    notifyListeners();
  }

  @visibleForTesting
  void connectionStatusForTest(String machineId, ConnectionStatus status) =>
      _onConnectionStatus(machineId, status);

  /// The machine list is being fetched and there is nothing to show meanwhile.
  ///
  /// Only the FIRST fetch sets it: a refresh over a list already on screen
  /// keeps that list up (the rows are still true, just not from a moment ago)
  /// and reports nothing. The rail reads this to tell "loading" from "no
  /// machines", which an empty list alone cannot say.
  bool machinesLoading = false;

  /// This machine's sharing with other accounts (CLI services/sharedMachines.ts), asked of [machineId]
  /// itself: the policy lives on the machine. `{emails, sameDomain, domain, members}`, or `{error,
  /// message}`.
  Future<Map<String, dynamic>> machineSharing(String machineId) =>
      _sharedMachines(machineId, {'action': 'get'});

  /// Share [machineId] with these addresses and, when [sameDomain], everyone at its owner's domain.
  Future<Map<String, dynamic>> setMachineSharing(
    String machineId,
    List<String> emails, {
    required bool sameDomain,
  }) => _sharedMachines(machineId, {
    'action': 'set',
    'emails': emails,
    'sameDomain': sameDomain,
  });

  /// Turn guest access on at [machineId]: the helper that runs each guest's harnesses as their own
  /// account there (CLI lib/guestHelperInstall.ts), installed behind one admin prompt on that
  /// computer. Waits for the person at the prompt. `{ok, guestAccess}`, or `{error, message}`
  /// (`CANCELLED` when the prompt was dismissed).
  Future<Map<String, dynamic>> enableMachineGuests(String machineId) =>
      _sharedMachines(machineId, {
        'action': 'enable_guests',
      }, timeout: const Duration(minutes: 11));

  /// The folders guests may work in on [machineId], read only or editable (CLI services/sharedMachines.ts
  /// `set_folders`). The view as it is now, or `{error, message}`.
  Future<Map<String, dynamic>> setMachineGuestFolders(
    String machineId,
    List<GuestFolder> folders,
  ) => _sharedMachines(machineId, {
    'action': 'set_folders',
    'folders': [
      for (final folder in folders)
        {'path': folder.path, 'write': folder.write},
    ],
  });

  /// Where this account, a guest on [machineId], may start a harness: its workspace and the folders
  /// the machine's owner shares (`guest_folders`). Null when the machine cannot say (an older CLI).
  Future<GuestFolders?> guestFolders(String machineId) async {
    try {
      return GuestFolders.fromJson(
        await _conn(machineId).request(
          'guest_folders',
          payload: const {},
          timeout: const Duration(seconds: 15),
        ),
      );
    } catch (_) {
      return null;
    }
  }

  /// Add a machine shared with this account's domain to its machines, or take one back out
  /// ([remove]). Asked of this computer's daemon, which pins the machine's key; null when done, else
  /// what went wrong.
  Future<String?> addSharedMachine(
    String machineId, {
    bool remove = false,
  }) async {
    final here = machineStates.values
        .where(
          (state) => state.isLocalMachine && !state.machine.isSharedMachine,
        )
        .firstOrNull;
    if (here == null) return 'This computer’s Harness is not running.';
    try {
      final answer = await _sharedMachines(here.machine.machineId, {
        'action': remove ? 'remove' : 'add',
        'machineId': machineId,
      });
      if (answer['error'] != null) {
        return answer['message'] as String? ??
            'Could not ${remove ? 'remove' : 'add'} it: ${answer['error']}.';
      }
    } catch (error) {
      return 'Could not ${remove ? 'remove' : 'add'} it: $error';
    }
    await refreshMachines();
    return null;
  }

  /// A refusal is an answer (`{error, message}`), shown in the machine's own words: only a request that
  /// never got one is "could not reach".
  Future<Map<String, dynamic>> _sharedMachines(
    String machineId,
    Map<String, dynamic> payload, {
    Duration timeout = const Duration(seconds: 30),
  }) async {
    try {
      return await _conn(machineId)
          .request('shared_machines', payload: payload, timeout: timeout);
    } on WsRequestFailure catch (failure) {
      return {...failure.payload, 'error': failure.code};
    }
  }

  Future<Map<String, dynamic>> manageHarnessShares(
    String machineId,
    String agentId,
    String action, [
    Map<String, dynamic> payload = const {},
  ]) {
    if (machineStates[machineId]?.machine.isShared == true) {
      return Future.error(StateError('Only the owner can change sharing.'));
    }
    return _conn(machineId)
        .request(
          'harness_share_$action',
          payload: {'agentId': agentId, ...payload},
        )
        .then((response) {
          shareStatus.record(machineId, agentId, response);
          return response;
        });
  }

  /// The browser controls only a linked, owned machine's managed viewer. Requests fail while
  /// disconnected rather than replaying old clicks after a new connection takes over.
  Future<Map<String, dynamic>> viewerSurface(
    String machineId,
    String agentId,
    Map<String, dynamic> payload,
  ) {
    final machine = machineStates[machineId];
    if (machine == null ||
        machine.machine.isShared ||
        machine.needsLink ||
        machine.nodeOnline == false ||
        machine.connectionStatus != ConnectionStatus.connected) {
      return Future.error(
        StateError('Reconnect this machine to open its viewer.'),
      );
    }
    final connection = _conn(machineId);
    if (!connection.isReady) {
      return Future.error(
        StateError('Reconnect this machine to open its viewer.'),
      );
    }
    return connection.request(
      'viewer_surface',
      payload: {...payload, 'agentId': agentId},
      timeout: const Duration(seconds: 25),
    );
  }

  int _machineInventoryRevision = 0;

  bool _machineInventoryCurrent(int auth, int request) =>
      _authWorkCurrent(auth) && request == _machineInventoryRevision;

  /// Whether this refresh was applied, rather than superseded by another
  /// refresh or an account change.
  Future<bool> refreshMachines() async {
    final revision = _authRevision;
    final request = await _refreshMachineInventory();
    return request != null && _machineInventoryCurrent(revision, request);
  }

  // Return the request that published its result, so a retry's follow-up work
  // cannot dismiss an error or reload panes for a superseded request.
  Future<int?> _refreshMachineInventory() async {
    final revision = _authRevision;
    if (!_authWorkCurrent(revision)) return null;
    final request = ++_machineInventoryRevision;
    // From the first read on, answered or not: a list that failed is looked for again too.
    if (viewer != null) _deafMachineListWatch.start();
    if (localManualFixture != null) {
      _machineInventoryLoaded = true;
      notifyListeners();
      return request;
    }
    if (machines.isEmpty && !machinesLoading) {
      machinesLoading = true;
      notifyListeners();
    }
    try {
      await _refreshMachines(revision, request);
      if (_machineInventoryCurrent(revision, request)) {
        // A cached answer is readable but not current, so the job is not done: leave the recovery timer
        // running and it converges on its own once the backend is back. Without this the daemon's 200
        // would read as success, recovery would stop, and the app would sit on stale rows until
        // somebody pressed reload.
        if (machinesAreStale) {
          _scheduleMachineRecovery(revision);
        } else {
          _stopMachineRecovery();
        }
        if (_lastError != null && _lastError == _machineLoadError) {
          _lastError = null;
          notifyListeners();
        }
        _machineLoadError = null;
        return request;
      }
      return null;
    } catch (error) {
      if (!_machineInventoryCurrent(revision, request)) return null;
      if (viewer != null && isUnauthorizedError(error)) {
        _signedOutAtRuntime('Your sign-in expired. Sign in again.');
        return null;
      }
      if (isTransientApiError(error)) {
        _scheduleMachineRecovery(revision);
      } else {
        _stopMachineRecovery();
      }
      rethrow;
    } finally {
      // Said out loud: the list's own notify fires before this, so a flag
      // dropped silently here would leave the rail on its placeholders.
      if (_machineInventoryCurrent(revision, request) && machinesLoading) {
        machinesLoading = false;
        notifyListeners();
      }
    }
  }

  void _stopMachineRecovery() {
    _machineRecoveryTimer?.cancel();
    _machineRecoveryTimer = null;
    _recoveryParked = null;
    _machineRecoveryAttempts = 0;
  }

  void _scheduleMachineRecovery(int revision) {
    if (!_authWorkCurrent(revision) ||
        status != AppStatus.authenticated ||
        _machineRecoveryTimer != null) {
      return;
    }
    const seconds = [2, 4, 8, 16, 30];
    final delay = seconds[_machineRecoveryAttempts];
    if (_machineRecoveryAttempts < seconds.length - 1) {
      _machineRecoveryAttempts++;
    }
    _machineRecoveryTimer = Timer(Duration(seconds: delay), () {
      _machineRecoveryTimer = null;
      // Out of sight a failing list is not asked again and again: it is asked once on return.
      if (!inSight.value) {
        _recoveryParked = revision;
        _machineRecoveryAttempts = 0;
        return;
      }
      if (_authWorkCurrent(revision) && status == AppStatus.authenticated) {
        unawaited(
          _retryMachines(automatic: true).whenComplete(() {
            // A timer can join a manual retry already in progress. Keep recovering if that run
            // stopped at the daemon gate; success and non-transient errors reset the counter.
            if (_machineRecoveryAttempts > 0) {
              _scheduleMachineRecovery(revision);
            }
          }),
        );
      }
    });
  }

  void _reportMachineLoadError(Object error, {bool automatic = false}) {
    // Offline is not an error to shout about: the daemon said it has no backend, this computer's
    // machine is standing in from the daemon (see _refreshMachines), and the rail already reads
    // "offline copy". The strip is for a backend that SHOULD be reachable and is not.
    if (_backendOnline == false) {
      machinesAreStale = true;
      // A strip this raised while the backend still looked reachable comes down with it.
      if (_lastError != null && _lastError == _machineLoadError) {
        _lastError = null;
      }
      _machineLoadError = null;
      return;
    }
    final message = 'Could not load machines: ${describeApiError(error)}';
    // A recovery must not replace a later agent error or redisplay a dismissed strip.
    if (!automatic || (_lastError != null && _lastError == _machineLoadError)) {
      _lastError = message;
      _lastErrorRetryable = true;
    }
    _machineLoadError = message;
  }

  /// The machine THIS computer's daemon serves, built from the daemon's own answer
  /// (`/api/status.machineId`) when the backend could not list it — no cache yet, backend down. Its
  /// local WS only selects that exact id (`localWsServer` `machine_select`), so nothing else would
  /// attach. Added, never replaced: a later real list carries the same id and updates the row in
  /// place through `machineStates.update` above. No-op when the daemon is not ready, reports no id,
  /// or a row already exists for it.
  ///
  /// [listUnavailable] is true on the failure path: the rows are then a stand-in for a list that
  /// never came, and the rail says so ("offline copy") while the recovery timer keeps asking. A
  /// fresh list that simply does not name this computer is not stale — marking it so would keep
  /// the recovery timer polling a backend that has already answered.
  void _adoptLocalMachineFromDaemon(
    LocalCliEndpoint? endpoint,
    String? localComputerId, {
    required bool listUnavailable,
  }) {
    final machineId = endpoint?.machineId;
    if (endpoint == null || machineId == null) return;
    if (machineStates.containsKey(machineId)) return;
    final machine = Machine(
      machineId: machineId,
      computerId: localComputerId ?? endpoint.computerId,
      authMode: MachineAuthMode.remote,
      name: localHostnameOrNull(),
      status: 'online',
    );
    machines = [...machines, machine];
    machineStates[machineId] = MachineState(machine)
      ..localOnly = true
      ..nodeOnline = true;
    if (listUnavailable) machinesAreStale = true;
    appLog.info(
      'daemon',
      'no machine list from the backend — this computer stands in from the daemon',
    );
  }

  /// What the loopback probe means for one machine's transport.
  ///
  /// Written once because two callers need the same answer: the refresh loop, and the failure path that
  /// keeps this computer usable when the backend list could not be read.
  void _applyLocalTransport(
    MachineState state,
    LocalCliEndpoint? localEndpoint,
    String? localComputerId,
  ) {
    if (state.localOnly && localEndpoint?.computerId == localComputerId) {
      state.localEndpoint = localEndpoint;
      state.transportMode = state.connectionStatus == ConnectionStatus.connected
          ? MachineTransportMode.localPlaintext
          : MachineTransportMode.localOffline;
    } else if (state.localOnly &&
        localEndpoint == null &&
        (_localLinkLive(state) ||
            (state.localEndpoint != null &&
                state.connectionStatus == ConnectionStatus.connected))) {
      // The probe found nothing this time (the daemon mid-restart, or mid-scan) but the socket to
      // it is open and answering right now — the socket is the better witness. Keep the endpoint
      // it was dialed through; demoting a live connection to "offline" on a missed probe is what
      // took a working terminal's tiles dark. The probe that missed may even have been taken
      // before the socket answered and applied after (a refresh holds it across its fetch), so the
      // live socket is checked itself rather than the stored status, and a cleared endpoint comes
      // back from the one the app dialed.
      state.localEndpoint ??= _cliEndpoint;
      state.transportMode = MachineTransportMode.localPlaintext;
    } else if (state.localOnly) {
      // The token still identifies this as local, but the CLI is offline or
      // failed its identity/capability check. Never fall back to cloud E2EE.
      if (state.localEndpoint != null || state.nodeOnline != false) {
        _logLocalMachine(state, 'offline (daemon probe found nothing)');
      }
      state.localEndpoint = null;
      state.transportMode = MachineTransportMode.localOffline;
      state.nodeOnline = false;
      _startOfflineRetry(state);
    } else {
      state.localEndpoint = null;
      state.transportMode = MachineTransportMode.cloudE2ee;
    }
  }

  Future<void> _refreshMachines(int revision, int request) async {
    // No machine is "this computer" to a viewer, which has no local CLI: every one — even the one
    // it runs on — is reached through the relay.
    final discovery = viewer == null ? _discovery : null;
    // The CLI computer id is the local identity source of truth. The loopback
    // status endpoint is trusted only when it advertises that same identity.
    final localComputerId = await discovery?.computerId();
    if (!_machineInventoryCurrent(revision, request)) return;
    // Null in a viewer build, which has no local CLI to probe — see `discovery` above.
    final localFuture =
        discovery?.discover(expectedComputerId: localComputerId) ??
        Future<LocalCliEndpoint?>.value();
    // The two legs stay independent. The loopback probe reads a local file and asks 127.0.0.1, so it
    // cannot fail for a network reason — but awaiting it BEHIND the backend call meant a cloud outage
    // threw first and threw away an answer that was already correct, while awaiting it FIRST would let a
    // slow probe hold up the list. Latch it as it lands instead, and use it on both paths.
    LocalCliEndpoint? probed;
    final localSettled = localFuture.then((value) => probed = value).catchError(
      (Object error) {
        // A probe that fails is the CLI being unreachable, which the transport decision below already
        // handles — but swallowing it silently leaves nothing to diagnose from.
        debugPrint('local CLI probe failed: $error');
        return null;
      },
    );
    final List<Machine> list;
    final bool stale;
    final editRevision = _machineEditRevision;
    try {
      list = await _fetchMachines();
      stale = list is MachineInventory ? list.isStale : api.lastMachinesStale;
    } catch (_) {
      // A backend outage must not cost this computer its own transport. Without this the probe result
      // stayed unapplied, so `usesLocalTransport` went false and `_connectMachine` skipped the local
      // machine — while relayed machines, which never consult it, kept streaming. That asymmetry was the
      // bug: the local terminal stopped rendering and the relayed ones did not.
      await localSettled;
      if (_machineInventoryCurrent(revision, request)) {
        final endpoint = probed;
        // The probe is the freshest word on the backend link — fresher than the supervisor's last
        // tick — and it decides whether this failure is an outage to report or just "offline".
        if (endpoint != null) {
          _noteBackendOnline(endpoint.backendOnline, refetch: false);
        }
        // No list and no row for this computer — a first run offline, or a cache the daemon could
        // not serve. The daemon knows the machine it serves; stand it up from that so the person
        // can work locally, exactly as if the backend had listed it.
        _adoptLocalMachineFromDaemon(
          endpoint,
          localComputerId,
          listUnavailable: true,
        );
        for (final state in machineStates.values) {
          _applyLocalTransport(state, endpoint, localComputerId);
          _connectMachine(state);
        }
        if (endpoint != null) _updateLocalProjectSnapshot(endpoint);
        notifyListeners();
      }
      rethrow; // the recovery timer owns the retry; this only protects what already works
    }
    await localSettled;
    // Both legs are in: this is the one gate that decides whether a result that arrived after a
    // sign-out or a dispose may still be published.
    if (!_machineInventoryCurrent(revision, request)) return;
    _machineInventoryLoaded = true;
    machinesAreStale = stale;
    if (list is MachineInventory) machinesToAdd = list.toAdd;
    final localEndpoint = probed;
    if (localEndpoint != null) {
      _noteBackendOnline(localEndpoint.backendOnline, refetch: false);
    }
    machines = [];
    for (final machine in list) {
      if (machine.authMode != MachineAuthMode.remote) continue;
      final edit = _confirmedMachineEdits[machine.machineId];
      if (edit != null && (edit.$1 > editRevision || machinesAreStale)) {
        if (edit.$2 case final name?) {
          machines.add(machine.copyWith(name: name));
        }
      } else {
        machines.add(machine);
        if (edit != null) {
          // A newer authoritative inventory may contain a rename performed
          // elsewhere. Its value becomes the protection against cached reads.
          _confirmedMachineEdits[machine.machineId] = (
            edit.$1,
            machine.displayName,
          );
        }
      }
    }
    if (!machinesAreStale) {
      final listed = list.map((machine) => machine.machineId).toSet();
      _confirmedMachineEdits.updateAll(
        (id, edit) => edit.$1 <= editRevision && !listed.contains(id)
            ? (edit.$1, null)
            : edit,
      );
    }
    final visible = machines.map((machine) => machine.machineId).toSet();
    _sharingEnded.removeWhere((id, _) => visible.contains(id));
    // Seen 2026-10-16: "Tuan stopped sharing Mac Auto with you." stayed up after Tuan shared it again.
    final ended = _sharingEndedError;
    if (ended != null &&
        !machinesAreStale &&
        visible.contains(ended.machineId)) {
      _sharingEndedError = null;
      if (_lastError == ended.text) _lastError = null;
    }
    for (final entry in machineStates.entries) {
      if (!visible.contains(entry.key)) {
        // A shared machine that left the list was taken back by its owner (a fresh list says so).
        if (!machinesAreStale) _noteSharingEnded(entry.value.machine);
        _clearMachineActivity(entry.value);
        _stopOfflineRetry(entry.key);
        _stopLinkRetry(entry.key);
        _stopAgentSyncTimer(entry.key);
        // The socket goes too, as on mobile: left in the pool it kept selecting a machine the
        // backend refuses (roadmap Phase 1.1, 2026-10-28), and nothing here looked at it again.
        unawaited(_pool?.closeMachine(entry.key));
      }
    }
    machineStates.removeWhere((id, _) => !visible.contains(id));
    // A retired id the fresh list no longer carries has been re-keyed or removed — its 4403 verdict
    // is over with it. One the list STILL carries keeps the verdict: on the loopback the daemon is
    // the authority for which id it serves, and re-dialing on every 15s refresh would be a 4403
    // and a log line each time.
    _localMismatchReported.removeWhere((id) => !visible.contains(id));
    for (final machine in machines) {
      final state = machineStates.update(
        machine.machineId,
        (state) => state..machine = machine,
        ifAbsent: () => MachineState(machine),
      );
      if (machine.isShared) {
        state.agents = [
          for (final grant in machine.sharedHarnesses)
            Agent(
              id: grant.agentId,
              name: grant.name,
              engine: grant.engine,
              terminalAvailable: true,
            ),
        ];
        state.agentLoadStatus = AgentLoadStatus.loaded;
        state.needsLink = false;
        state.nodeOnline = machine.status == 'running';
        for (final pane in allPanes.where(
          (p) => p.machineId == machine.machineId,
        )) {
          pane.sharedHarness =
              machine.sharedHarnesses
                  .where((g) => g.agentId == pane.agentId)
                  .firstOrNull ??
              pane.sharedHarness;
          pane.sharedOwnerName = machine.ownerName;
        }
        continue;
      }
      state.localOnly =
          localComputerId != null &&
          _normalizeComputerId(machine.computerId) == localComputerId;
      _applyLocalTransport(state, localEndpoint, localComputerId);
      final reportedOnline = machine.reportedOnline;
      if (!state.isLocalMachine &&
          reportedOnline != null &&
          (state.nodeOnline == null || state.nodeOnline != reportedOnline)) {
        unawaited(_applyInventoryNodeStatus(state, reportedOnline));
      }
      // A relayed machine that was off waits for word it is back (WsConn.isParked), and this
      // list is that word, whether or not this row ever read as offline.
      if (!state.isLocalMachine && reportedOnline == true) {
        _connectionOf(machine.machineId)?.wake('listed online');
      }
    }
    // A list that arrived but does not name this computer (a stale copy from before this computer
    // was paired, say) still gets the daemon's own row, on the same rule as the failure path.
    if (localEndpoint != null &&
        localEndpoint.machineId != null &&
        !machineStates.containsKey(localEndpoint.machineId)) {
      _adoptLocalMachineFromDaemon(
        localEndpoint,
        localComputerId,
        listUnavailable: false,
      );
      _applyLocalTransport(
        machineStates[localEndpoint.machineId]!,
        localEndpoint,
        localComputerId,
      );
    }
    if (localEndpoint != null) _updateLocalProjectSnapshot(localEndpoint);
    _autoConnectAndLoadMachines();
    _startBackgroundRereads();
    notifyListeners();
    // A grant that has just arrived places what waited for it (R2).
    _placeSharedPanesSoon();
  }

  /// The background re-reads a signed-in window keeps: each connected
  /// machine's agent sync and the machine list's safety net. A guest keeps
  /// none (an unattended computer on the sign-in page goes idle); the local
  /// service itself stays supervised. Sign-out cancels them in
  /// [_clearAccountWorkspace], and sign-in starts them here again.
  void _startBackgroundRereads() {
    if (_disposed || isGuest) return;
    for (final machine in machineStates.values) {
      if (machine.connectionStatus == ConnectionStatus.connected) {
        _startAgentSyncTimer(machine.machine.machineId);
      }
    }
    _armMachineListSafetyNet();
  }

  /// The machine list's safety net, every [machineListSafetyNetInterval] while the window is in
  /// sight ([inSight]). The list is pushed (`machines_changed`); this only catches a missed push.
  void _armMachineListSafetyNet() {
    if (_disposed || isGuest || !inSight.value) return;
    _sharingDiscoveryTimer ??= Timer.periodic(machineListSafetyNetInterval, (
      timer,
    ) {
      // Belt and braces: sign-out cancels it, and a guest never arms it.
      if (isGuest) {
        timer.cancel();
        if (identical(_sharingDiscoveryTimer, timer)) {
          _sharingDiscoveryTimer = null;
        }
        return;
      }
      _machineListSafetyNetTick();
    });
  }

  void _machineListSafetyNetTick() {
    // The desk is pushed too, and a missed desk push is caught here as well:
    // one small GET, and an unchanged revision applies nothing.
    if (!_disposed &&
        status == AppStatus.authenticated &&
        _desk.enabled &&
        _desk.pending.isEmpty) {
      unawaited(_deskFetch());
    }
    // Agent Messages' first answer, when the read beside the desk failed
    // (a backend away at sign-in) and no backend-online flip followed.
    if (!_disposed &&
        status == AppStatus.authenticated &&
        _desk.enabled &&
        !agentMessages.loaded) {
      unawaited(agentMessages.refresh());
    }
    unawaited(_rereadMachinesInBackground(pushed: false));
  }

  /// When the window last went out of sight ([inSight] false); null while it is in sight.
  DateTime? _unseenSince;

  /// The window went out of sight: minimised, behind other windows, closed to the menu bar, or a
  /// browser tab in the background. Its background re-reads stop (Phase 3 of the WebSocket
  /// roadmap, task #2953): nobody sees what they would bring, and every open window kept asking
  /// every machine for its agents each minute and the backend for the machine list every five.
  /// Pushes still land; [_resumeBackgroundRereads] catches up on what came due meanwhile.
  void _pauseBackgroundRereads() {
    _unseenSince = clock.now();
    for (final timer in [
      ..._agentSyncTimers.values,
      ..._heldSyncTimers.values,
    ]) {
      timer.cancel();
    }
    _agentSyncTimers.clear();
    _heldSyncTimers.clear();
    _sharingDiscoveryTimer?.cancel();
    _sharingDiscoveryTimer = null;
  }

  /// Back in sight: each re-read that came due while away reads once, now, and every timer runs
  /// again from here. A glance away shorter than an interval reads nothing.
  void _resumeBackgroundRereads() {
    final since = _unseenSince;
    _unseenSince = null;
    if (_disposed || isGuest || status != AppStatus.authenticated) return;
    final away = since == null ? Duration.zero : clock.now().difference(since);
    for (final machine in machineStates.values.toList()) {
      if (machine.connectionStatus != ConnectionStatus.connected) continue;
      _startAgentSyncTimer(machine.machine.machineId);
      if (away >= agentSyncInterval) {
        unawaited(_syncAgentsIfChanged(machine));
      } else {
        _watchHeldLaunches(machine);
      }
    }
    _armMachineListSafetyNet();
    if (away >= machineListSafetyNetInterval) _machineListSafetyNetTick();
    final parked = _recoveryParked;
    _recoveryParked = null;
    if (parked != null) _scheduleMachineRecovery(parked);
    for (final machineId in _offlinePollsParked.toList()) {
      _offlinePollsParked.remove(machineId);
      final machine = machineStates[machineId];
      if (machine != null) _startOfflineRetry(machine);
    }
  }

  /// The machine list's recovery, waiting for the window to be in sight again: the auth revision
  /// it was for ([_scheduleMachineRecovery]).
  int? _recoveryParked;

  /// Remote machines whose offline poll waits for the window to be in sight again.
  final Set<String> _offlinePollsParked = {};

  /// The inventory has answered, and answered for now: loaded, not loading,
  /// not stale, no error. What the account HAS, independent of what is open.
  bool get machineInventorySettled =>
      machineInventoryLoaded &&
      !machinesLoading &&
      !machinesAreStale &&
      machineListError == null;

  /// A computer of the account's is connected, or on its way.
  bool get computerConnectedOrComing => machineStates.values.any(
    (machine) =>
        !machine.machine.isShared &&
        !machine.needsLink &&
        machine.nodeOnline != false &&
        (machine.connectionStatus == ConnectionStatus.connected ||
            machine.connectionStatus == ConnectionStatus.connecting ||
            machine.connectionStatus == ConnectionStatus.reconnecting),
  );

  /// What a host's connect page is for: before the machine list first
  /// answers, and once it has, while no computer of the account's is
  /// connected or on its way and none is only asleep ([asleepComputers]) —
  /// every one is missing, offline or waiting to be linked.
  bool get waitsForFirstComputer =>
      !computerConnectedOrComing &&
      (!machineInventoryLoaded ||
          (machineInventorySettled && asleepComputers.isEmpty));

  /// The account's own computers, all of them offline and none waiting on this
  /// one to be linked: set up before, asleep now. Empty for an account with
  /// none (a computer taken out of it does not count) — that one needs setting
  /// up — and while any is connected, on its way, or waiting to be linked.
  List<MachineState> get asleepComputers {
    final own = [
      for (final machine in machineStates.values)
        if (!machine.machine.isShared &&
            !removedMachines.containsKey(machine.machine.machineId))
          machine,
    ];
    if (own.any((machine) => machine.needsLink || !machine.isOffline)) {
      return const [];
    }
    return own;
  }

  /// Whether this viewer has no machine socket open, so no push can reach it.
  bool get _viewerIsDeaf =>
      viewer != null &&
      !machineStates.values.any(
        (m) =>
            !m.machine.isShared &&
            m.connectionStatus == ConnectionStatus.connected,
      );

  /// Whether the deaf watch's next tick reads: a viewer that hears nothing, in sight — a tab left
  /// open behind others, its machines all off, would otherwise ask for as long as the browser runs;
  /// the 5-minute safety net ([machineListSafetyNetInterval]) is the one read it still makes —
  /// and not while recovery is the one asking (a failed or stale list, see
  /// [_scheduleMachineRecovery]) or a reload is open, so two never read side by side.
  bool get _deafReadWanted =>
      inSight.value &&
      _viewerIsDeaf &&
      _machineRecoveryTimer == null &&
      _retryInFlight == null;

  /// A viewer that hears nothing re-reads the machine list: the computer the person is signing in
  /// on right now appears, and the dial that follows reads the device log for its key first.
  Future<void> _rereadMachinesWhileDeaf() async {
    if (_disposed || status != AppStatus.authenticated || !_viewerIsDeaf) {
      return;
    }
    await _rereadMachinesInBackground(pushed: false);
  }

  /// Re-read the machine list because something other than the person asked:
  /// a `machines_changed` push, or the safety-net timer.
  ///
  /// One at a time. A push that arrives while a read is open marks it dirty
  /// instead of starting another — the open read may predate that change, so
  /// exactly one more follows it. A bulk rename pushes once per machine;
  /// without this each push would be its own pair of requests. A timer tick
  /// that finds a read open has nothing to add and is dropped.
  Future<void> _rereadMachinesInBackground({required bool pushed}) async {
    if (_disposed || status != AppStatus.authenticated) return;
    if (pushed) _deafMachineListWatch.reset();
    if (_sharingDiscoveryBusy) {
      if (pushed) _sharingDiscoveryAgain = true;
      return;
    }
    if (machinesRefreshing && !pushed) return;
    final discoveryRevision = _authRevision;
    _sharingDiscoveryBusy = true;
    try {
      // This call owes one read; every push that lands while we are busy owes
      // one more (collapsed into a single follow-up by the flag).
      var owed = true;
      while (owed || _sharingDiscoveryAgain) {
        // Still ours? Checked BEFORE the flag is cleared: a run left over from
        // a session that has since signed out must not eat the dirty flag that
        // belongs to the new session's run.
        if (_disposed ||
            status != AppStatus.authenticated ||
            !_authWorkCurrent(discoveryRevision)) {
          return;
        }
        // A reload (the person's, or recovery's) that is open right now: let it
        // finish first, on EVERY pass. Its read may predate this push, and
        // starting ours beside it would supersede its request — it would then
        // give up before clearing its error and reloading the open machines.
        final reload = _retryInFlight;
        if (reload != null) {
          try {
            await reload;
          } catch (_) {}
          continue;
        }
        owed = false;
        _sharingDiscoveryAgain = false;
        await refreshMachines();
      }
    } catch (error) {
      if (_authWorkCurrent(discoveryRevision)) {
        _reportMachineLoadError(error, automatic: true);
        notifyListeners();
      }
    } finally {
      if (_authWorkCurrent(discoveryRevision)) _sharingDiscoveryBusy = false;
    }
  }

  // The daemon reports `connected` only once its own backend socket is open, but
  // `/api/machines` is a separate REST leg (fresh token refresh + fetch) that can still stall
  // briefly right after that — a bounded retry absorbs that transient window without falling
  // back to the 30s Dio timeout. Never retries an `ApiException` (a real HTTP error response);
  // only a `DioException` (timeout/connection failure) is worth a second try.
  // Capped at 2 attempts, not 3: `receiveTimeout` is 30s, so every retried attempt can cost
  // another 30s on a genuine failure — one retry absorbs the transient window above without
  // tripling how long a truly broken backend takes to surface its error.
  Future<List<Machine>> _fetchMachines() => withRetry(
    api.machines,
    maxAttempts: 2,
    initialDelay: const Duration(milliseconds: 500),
    isRetryable: (error) => error is DioException && isTransientApiError(error),
  );

  void _startOfflineRetry(MachineState machine) {
    final machineId = machine.machine.machineId;
    if (machine.nodeOnline != false ||
        (!machine.isLocalMachine && machine.pendingOfflineAgentId == null)) {
      _stopOfflineRetry(machineId);
      return;
    }
    if (_offlineRetryTimers.containsKey(machineId)) return;
    if (!machine.isLocalMachine) {
      _scheduleRemoteOfflinePoll(machineId, 0);
      return;
    }
    _offlineRetryTimers[machineId] = Timer.periodic(
      offlineRetryInterval,
      (_) => unawaited(_pollOfflineMachine(machineId)),
    );
  }

  /// The [attempt]th ask of [remoteOfflineRetryDelays], then the next once it answered, until
  /// [_stopOfflineRetry] takes its timer away.
  void _scheduleRemoteOfflinePoll(String machineId, int attempt) {
    final delay =
        remoteOfflineRetryDelays[min(
          attempt,
          remoteOfflineRetryDelays.length - 1,
        )];
    late final Timer timer;
    timer = Timer(delay, () async {
      // Out of sight, the machine is asked about again only once the window is back.
      if (!inSight.value) {
        if (identical(_offlineRetryTimers[machineId], timer)) {
          _offlineRetryTimers.remove(machineId);
          _offlinePollsParked.add(machineId);
        }
        return;
      }
      await _pollOfflineMachine(machineId);
      if (_disposed || !identical(_offlineRetryTimers[machineId], timer)) {
        return;
      }
      _scheduleRemoteOfflinePoll(machineId, attempt + 1);
    });
    _offlineRetryTimers[machineId] = timer;
  }

  void _stopOfflineRetry(String machineId) {
    _offlineRetryTimers.remove(machineId)?.cancel();
    _offlinePollsParked.remove(machineId);
  }

  /// Dials [machineId] now instead of at the link retry's next tick. Native
  /// callers join an already-running Connect for the same machine. A machine
  /// that trusts this device through the account's device key log answers with
  /// no password at all. True once it is connected; false when it still wants
  /// this device linked (a CLI from before the log, or a log that does not name
  /// this device yet), or has not answered within [timeout].
  Future<bool> connectTrusted(
    String machineId, {
    Duration timeout = const Duration(seconds: 12),
  }) {
    final state = machineStates[machineId];
    if (_disposed || state == null || state.machine.isShared) {
      return Future.value(false);
    }
    // Native Connect may be reached from more than one surface. Join its dial
    // instead of closing the socket another click is already waiting on.
    if (viewer == null) {
      final pending = _trustedConnections[machineId];
      if (pending != null) return pending;
    }
    late final Future<bool> work;
    work = _connectTrusted(machineId, state, timeout).whenComplete(() {
      if (identical(_trustedConnections[machineId], work)) {
        _trustedConnections.remove(machineId);
      }
    });
    if (viewer == null) _trustedConnections[machineId] = work;
    return work;
  }

  Future<bool> _connectTrusted(
    String machineId,
    MachineState state,
    Duration timeout,
  ) async {
    final revision = _authRevision;
    bool current() =>
        _authWorkCurrent(revision) &&
        identical(machineStates[machineId], state);
    final finishConnection = productConnections.manual(machineId);
    final done = Completer<bool>();
    var dialed = false;
    void settle() {
      final now = machineStates[machineId];
      if (done.isCompleted) return;
      if (!current() || now == null) return done.complete(false);
      final status = now.connectionStatus;
      if (status == ConnectionStatus.connected && !now.needsLink) {
        return done.complete(true);
      }
      if (status == ConnectionStatus.connecting ||
          status == ConnectionStatus.reconnecting) {
        dialed = true;
      } else if (dialed && now.needsLink) {
        done.complete(false);
      }
    }

    addListener(settle);
    final timer = Timer(timeout, () {
      if (!done.isCompleted) done.complete(false);
    });
    try {
      await _pool?.closeMachine(machineId);
      if (!current()) return false;
      _connectMachine(state);
      settle();
      final connected = await done.future;
      if (!current()) return false;
      if (!connected) {
        productConnections.refused(
          machineId,
          machineStates[machineId]?.needsLink == true
              ? ProductHealthMeasure.connectErrorUnlinked
              : ProductHealthMeasure.connectErrorTimeout,
        );
      }
      finishConnection(connected ? ProductOutcome.ok : ProductOutcome.failed);
      return connected;
    } finally {
      finishConnection(ProductOutcome.unknown);
      timer.cancel();
      removeListener(settle);
    }
  }

  /// Both builds back off the same way: a browser's retry used to redial every 5 s for good, each
  /// refusal reading the account's device list again — 12 dials and 12 reads a minute for one
  /// unlinked machine.
  void _startLinkRetry(String machineId) {
    if (_linkRetryTimers.containsKey(machineId)) return;
    _scheduleLinkRetry(machineId, offlineRetryInterval);
  }

  void _scheduleLinkRetry(String machineId, Duration delay) {
    final state = machineStates[machineId];
    if (state == null || !state.needsLink || _disposed) return;
    final revision = _authRevision;
    late final Timer timer;
    bool current() =>
        _authWorkCurrent(revision) &&
        identical(_linkRetryTimers[machineId], timer) &&
        identical(machineStates[machineId], state) &&
        state.needsLink;
    bool busy() =>
        _trustedConnections.containsKey(machineId) ||
        pendingMachineLink(machineId) != null ||
        state.connectionStatus == ConnectionStatus.connecting ||
        state.connectionStatus == ConnectionStatus.reconnecting ||
        state.connectionStatus == ConnectionStatus.connected;
    timer = Timer(delay, () async {
      try {
        if (!current() || busy()) return;
        // Await removal before redialling; a slow handshake belongs to the
        // existing transport, which has its own timeout/reconnect policy.
        await _pool?.closeMachine(machineId);
        if (!current() || busy()) return;
        _connectMachine(state);
      } catch (_) {
        // A failed close cannot stop recovery; the next bounded retry owns it.
      } finally {
        if (current()) {
          final next = delay * 2;
          _scheduleLinkRetry(
            machineId,
            next > const Duration(seconds: 30)
                ? const Duration(seconds: 30)
                : next,
          );
        } else if (identical(_linkRetryTimers[machineId], timer)) {
          _stopLinkRetry(machineId);
        }
      }
    });
    _linkRetryTimers[machineId] = timer;
  }

  void _stopLinkRetry(String machineId) {
    _linkRetryTimers.remove(machineId)?.cancel();
  }

  void _stopAllLinkRetries() {
    for (final timer in _linkRetryTimers.values) {
      timer.cancel();
    }
    _linkRetryTimers.clear();
    _trustedConnections.clear();
  }

  void _stopAllOfflineRetries() {
    for (final timer in _offlineRetryTimers.values) {
      timer.cancel();
    }
    _offlineRetryTimers.clear();
    _offlinePollsParked.clear();
    for (final timer in _slowReloadTimers.values) {
      timer.cancel();
    }
    _slowReloadTimers.clear();
    _offlinePollsInFlight.clear();
    _offlineRecoveryInFlight.clear();
    _cancelPaneRetries();
  }

  void _startAgentSyncTimer(String machineId) {
    // A guest asks nothing on a timer: an unattended computer on the sign-in
    // page must go idle. Sign-in starts it ([_startBackgroundRereads]).
    if (isGuest) return;
    // Out of sight it arms nothing; coming back does ([_resumeBackgroundRereads]).
    if (!inSight.value) return;
    if (_agentSyncTimers.containsKey(machineId)) return;
    _agentSyncTimers[machineId] = Timer.periodic(agentSyncInterval, (_) {
      final machine = machineStates[machineId];
      if (machine == null) {
        _stopAgentSyncTimer(machineId);
        return;
      }
      unawaited(_syncAgentsIfChanged(machine));
    });
  }

  void _stopAgentSyncTimer(String machineId) {
    _agentSyncTimers.remove(machineId)?.cancel();
    _heldSyncTimers.remove(machineId)?.cancel();
    _heldSyncRounds.remove(machineId);
  }

  void _stopAllAgentSyncTimers() {
    for (final timer in [
      ..._agentSyncTimers.values,
      ..._heldSyncTimers.values,
    ]) {
      timer.cancel();
    }
    _agentSyncTimers.clear();
    _heldSyncTimers.clear();
    _heldSyncRounds.clear();
  }

  /// Reads a machine's agents again while one of them is held: after [heldLaunchSyncInterval], then
  /// twice as long each time nothing changed, up to ten times it (3, 6, 12, 24, then 30 s), one read
  /// at a time.
  ///
  /// The daemon starts a held harness by itself (a conversation it could not yet verify, a move
  /// waiting for a turn to end), but the start reaches the app only with its next agent sync: on a
  /// fresh VM (2026-10-09) the reopened conversations ran for a minute under "Waiting", until the
  /// [agentSyncInterval] tick. The quiet re-read ([_syncAgentsIfChanged]) brings it within seconds;
  /// a hold that lasts (a turn running for minutes) costs a list every half minute.
  void _watchHeldLaunches(MachineState machine) {
    final machineId = machine.machine.machineId;
    final held =
        machine.connectionStatus == ConnectionStatus.connected &&
        machine.agents.any((agent) => agent.launchState == 'held');
    if (!held) {
      _heldSyncTimers.remove(machineId)?.cancel();
      _heldSyncRounds.remove(machineId);
      return;
    }
    // Out of sight the daemon's own push still says when it starts; the re-read waits for the
    // window to come back ([_resumeBackgroundRereads]).
    if (!inSight.value) return;
    if (_heldSyncTimers.containsKey(machineId)) return;
    final round = _heldSyncRounds[machineId] ?? 0;
    _heldSyncTimers[machineId] = Timer(
      heldLaunchSyncInterval * min(1 << min(round, 4), 10),
      () {
        final current = machineStates[machineId];
        if (current == null) {
          _heldSyncTimers.remove(machineId);
          _heldSyncRounds.remove(machineId);
          return;
        }
        final before = current.agentsRevision;
        unawaited(
          _syncAgentsIfChanged(current).whenComplete(() {
            if (_heldSyncTimers[machineId]?.isActive == false) {
              _heldSyncTimers.remove(machineId);
            }
            if (machineStates[machineId] != current) return;
            _heldSyncRounds[machineId] = current.agentsRevision == before
                ? round + 1
                : 0;
            _watchHeldLaunches(current);
          }),
        );
      },
    );
  }

  /// Silent safety-net reconciliation, ticked every [agentSyncInterval] while a machine is connected.
  /// Only writes/notifies if the fetched list actually differs from what's already shown — a steady
  /// state where push events (agent_synced et al.) have kept everything in sync produces zero visible
  /// effect. Deliberately does not touch agentLoadStatus/agentsLoadError/notifyListeners on failure:
  /// a real connectivity problem is already surfaced by the push path and the existing offline
  /// detection in _performMachineDataLoad, and a quiet background tick should not fight either.
  Future<void> _syncAgentsIfChanged(MachineState machine) async {
    final revision = _authRevision;
    final discoveryRevision = machine._discoveryRevision;
    if (!_machineWorkCurrent(machine, revision)) return;
    if (machine.connectionStatus != ConnectionStatus.connected) return;
    if (machine.agentsLoadInFlight != null) {
      return; // a real (foreground) load already owns this tick
    }
    final connection = _conn(machine.machine.machineId);
    final nameRevision = machine._agentRevision;
    final listRevision = machine.agentsRevision;
    try {
      final response = await connection.request(
        'agents_list',
        payload: const {'includeStopped': true},
        timeout: const Duration(seconds: 10),
      );
      if (!_machineDiscoveryCurrent(machine, revision, discoveryRevision)) {
        return;
      }
      // A push that landed while this was asked is newer than the answer.
      if (machine.agentsRevision != listRevision) return;
      final agents = _agentSnapshot(
        machine,
        (response['agents'] as List<dynamic>? ?? [])
            .map((item) => Agent.fromJson(item as Map<String, dynamic>))
            .toList(),
        nameRevision,
      );
      if (agentsEqual(machine.agents, agents)) {
        // A whole list read, even one that changes nothing: what pushes
        // brought before it was the window's restore, and what comes after it
        // is new (`_openStartedChild`). Left unset when the first load failed
        // and pushes filled the list, no harness an agent started would ever
        // open beside it (review of #1217).
        machine.agentsListedOnce = true;
        return;
      }
      _replaceAgents(machine, agents);
      notifyListeners();
    } catch (_) {
      // Silent by design — see doc comment above.
    }
  }

  /// Order-insensitive value equality for [Agent] lists — [Agent] has no operator== override, and a
  /// backend that returns the same agents in a different order must not register as "changed".
  ///
  /// ⚠️ Every field of [Agent] that the UI reads belongs here. This list is hand-maintained, and the
  /// cost of forgetting one is silent: the poll fetches the truth, compares it, decides nothing
  /// happened, and throws it away — so the field stays frozen at whatever it was for as long as the
  /// app runs. Add the field here in the same commit you add it to [Agent].
  @visibleForTesting
  static bool agentsEqual(List<Agent> a, List<Agent> b) {
    if (a.length != b.length) return false;
    final byId = {for (final agent in a) agent.id: agent};
    for (final agent in b) {
      final prev = byId[agent.id];
      if (prev == null ||
          prev.name != agent.name ||
          prev.title != agent.title ||
          prev.sessionId != agent.sessionId ||
          prev.activity != agent.activity ||
          prev.engine != agent.engine ||
          prev.engineDisplayName != agent.engineDisplayName ||
          prev.engineIconHint != agent.engineIconHint ||
          prev.codexHome != agent.codexHome ||
          prev.claudeHome != agent.claudeHome ||
          prev.modelName != agent.modelName ||
          prev.modelEffort != agent.modelEffort ||
          prev.gridModel != agent.gridModel ||
          prev.gridWebSearch != agent.gridWebSearch ||
          prev.gridBaseUrl != agent.gridBaseUrl ||
          prev.gridState != agent.gridState ||
          _gridNoteValue(prev.gridNote) != _gridNoteValue(agent.gridNote) ||
          prev.parentAgentId != agent.parentAgentId ||
          prev.project != agent.project ||
          prev.gitContext != agent.gitContext ||
          prev.lastActivityAt != agent.lastActivityAt ||
          prev.createdAt != agent.createdAt ||
          prev.closeSupported != agent.closeSupported ||
          prev.nameChosen != agent.nameChosen ||
          prev.closePlanState != agent.closePlanState ||
          prev.closePlanDetail != agent.closePlanDetail ||
          prev.lastOpenedAt != agent.lastOpenedAt ||
          prev.tokensUsed != agent.tokensUsed ||
          prev.outputStats != agent.outputStats ||
          prev.tokensUpdatedAt != agent.tokensUpdatedAt ||
          prev.launchState != agent.launchState ||
          prev.launchError != agent.launchError ||
          prev.launchDetail != agent.launchDetail ||
          prev.status != agent.status ||
          prev.terminalAvailable != agent.terminalAvailable ||
          prev.terminalUnavailableReason != agent.terminalUnavailableReason ||
          prev.dsh != agent.dsh ||
          prev.dshName != agent.dshName ||
          prev.viewerUrl != agent.viewerUrl ||
          prev.viewerError != agent.viewerError ||
          prev.viewerName != agent.viewerName ||
          prev.verdict != agent.verdict ||
          prev.forkedFrom?.agentId != agent.forkedFrom?.agentId ||
          prev.forkedFrom?.name != agent.forkedFrom?.name ||
          prev.forkable != agent.forkable ||
          prev.resumeMode != agent.resumeMode ||
          prev.permissionMode != agent.permissionMode ||
          prev.bypassPermission != agent.bypassPermission ||
          prev.namedAgent != agent.namedAgent) {
        return false;
      }
    }
    return true;
  }

  static (Type?, String?, String?) _gridNoteValue(GridNote? note) => (
    note?.runtimeType,
    note?.model,
    switch (note) {
      GridNoteOffline(:final machine) => machine,
      _ => null,
    },
  );

  /// Public retry hook used by the offline join guide's "Retry now" action.
  Future<void> retryOfflineMachine(String machineId) =>
      _pollOfflineMachine(machineId);

  /// Runs `harness link connect <machineId> --stdin --json` (via [CliLink]) for a machine the
  /// relay reported `NO_PEER_LINK` for, then reconnects it. Returns null on success, or an error
  /// message to show inline. The app never sees the password's cryptographic use — this just
  /// pipes it to the CLI on stdin, the same as typing it at a terminal prompt would.
  Future<String?> connectWithPassword(
    String machineId,
    String password, {
    void Function(String stage)? onProgress,
  }) {
    final pending = pendingMachineLink(machineId);
    if (pending != null) return pending;
    if (password.isEmpty) {
      return Future.value('Enter the remote password first');
    }
    if (_disposed) {
      return Future.value('This connection request is no longer active.');
    }
    final attempt = _MachineLinkAttempt(_authRevision);
    _machineLinks[machineId] = attempt;
    notifyListeners();
    unawaited(_connectWithPassword(machineId, password, attempt, onProgress));
    return attempt.result.future;
  }

  Future<void> _connectWithPassword(
    String machineId,
    String password,
    _MachineLinkAttempt attempt,
    void Function(String)? onProgress,
  ) async {
    final measureLink = productMeasurement.begin(ProductFlow.computerLink);
    String? error;
    try {
      final result = await peerLinks.connect(
        machineId,
        password,
        onProgress: (stage) {
          if (!_authWorkCurrent(attempt.authRevision)) return;
          attempt.stage = stage;
          onProgress?.call(stage);
          notifyListeners();
        },
        displayName: machineStates[machineId]?.machine.displayName,
      );
      error = result.error;
      if (!_authWorkCurrent(attempt.authRevision)) {
        error ??= 'This connection request is no longer active.';
        return;
      }
      if (error != null) return;
      final targetId = result.linkedMachineId ?? machineId;
      final state = machineStates[targetId];
      if (state != null) {
        state.needsLink = false;
        state.agentLoadStatus = AgentLoadStatus.idle;
        notifyListeners();
        // NO_PEER_LINK permanently closes the old socket. Dial a fresh one.
        await _pool?.closeMachine(targetId);
        if (_authWorkCurrent(attempt.authRevision)) _connectMachine(state);
      }
      // One password, the whole group: this machine learns this device's other machines, and they it.
      unawaited(_syncGroup(targetId, spread: true));
    } catch (_) {
      error = 'Could not link this machine. Try again.';
    } finally {
      measureLink(error == null ? ProductOutcome.ok : ProductOutcome.failed);
      if (identical(_machineLinks[machineId], attempt)) {
        _machineLinks.remove(machineId);
      }
      attempt.result.complete(error);
      if (_authWorkCurrent(attempt.authRevision)) notifyListeners();
    }
  }

  // -- the account's devices: the device key log (viewer/device_log_sync.dart) --------------------

  /// Viewer builds only: this app's copy of the account's device key log. A desktop build's daemon
  /// keeps its own (`harness devices`), and the Devices list reads it from there.
  ViewerDeviceLog? _deviceLog;

  /// Devices that joined the account and this end had never trusted, not yet dismissed.
  final List<NewDeviceNotice> newDevices = [];

  /// Each device [_announceDevice] says joined the account, as it is said — never the pending list
  /// rebuilt from the log ([_syncPendingDevices]), which is old news by then. Add Phone listens here
  /// for the phone it is adding (`widgets/add_phone_dialog.dart`). Broadcast: with nobody listening,
  /// a join is dropped, like [spokenTasks].
  final StreamController<NewDeviceNotice> _deviceJoins =
      StreamController<NewDeviceNotice>.broadcast();
  Stream<NewDeviceNotice> get deviceJoins => _deviceJoins.stream;

  /// Devices taken out of the account by another device, not yet dismissed. Not persisted: the
  /// history is the durable record.
  final List<DeviceRemovalNotice> deviceRemovals = [];

  /// The removal notices the band shows. A key that signed itself out and is also on the departed list
  /// (it joined and left before anyone looked) is told once, by the departed band: that band's "Got it"
  /// is its one dismissal, so the removal notice for the same key is left out, not dismissed.
  List<DeviceRemovalNotice> get visibleDeviceRemovals => [
    for (final n in deviceRemovals)
      if (!(n.selfRemoved && departedDevices.any((d) => d.pub == n.pub))) n,
  ];

  /// Keys that joined the account and were taken out again before anyone looked at them, not yet
  /// dismissed ("<label> joined your account and left before you looked."). The log keeps them (the
  /// daemon's, or this app's own), so they outlast a restart; only "Got it" clears one.
  final List<DeviceLogDeparted> departedDevices = [];

  /// Whether [departed] was removed by a key that is itself new and unlooked-at (or one that left that
  /// way): someone who just got in clearing up after themselves. A key's own sign-out is never red.
  bool departedIsRed(DeviceLogDeparted departed) {
    if (departed.selfRemoved || departed.removedBy == departed.pub)
      return false;
    return newDevices.any((d) => d.pub == departed.removedBy) ||
        departedDevices.any((d) => d.pub == departed.removedBy);
  }

  /// Another key holds this computer's id on the account (a desktop build's daemon says so); null
  /// when none does.
  DeviceConflict? deviceConflict;

  /// The conflict holder the band was dismissed for; the daemon keeps saying it until it is resolved.
  String? _dismissedConflict;

  /// New devices marked as seen here but not (yet) persisted — an in-flight write, or a daemon that
  /// predates `POST /api/devices/dismiss`. The pending sync leaves them out.
  final Set<String> _dismissedDevices = {};

  /// The "Already on your account" list was acknowledged here, whether or not it could be persisted.
  bool _baselineSeenLocally = false;
  bool get baselineSeenLocally => _baselineSeenLocally;

  /// Viewer builds only: this app's copy of the device log is frozen, so it pins no machine from it
  /// until someone reviews the list (Machines). A machine asking for its password says so.
  bool get deviceListNeedsReview => _deviceListFrozen;
  bool _deviceListFrozen = false;

  @visibleForTesting
  set deviceListNeedsReviewForTest(bool frozen) {
    _deviceListFrozen = frozen;
    notifyListeners();
  }

  /// The backend refused this device a place on the account: it has too many devices (`TOO_MANY`).
  /// A machine asking for its password says so, beside [deviceListNeedsReview].
  bool get deviceListTooMany => _deviceListTooMany;
  bool _deviceListTooMany = false;

  @visibleForTesting
  set deviceListTooManyForTest(bool tooMany) {
    _deviceListTooMany = tooMany;
    notifyListeners();
  }

  /// Everything this window said about the account's devices belongs to the account that is leaving
  /// (logout and a runtime sign-out both): the banners, the unsaved dismissals, and any read still in
  /// flight, which must not write the old account's listing under the next one.
  void _clearDeviceNoticeState() {
    newDevices.clear();
    departedDevices.clear();
    deviceRemovals.clear();
    removedMachines = const {};
    _queuedDeviceNotices.clear();
    deviceConflict = null;
    _dismissedConflict = null;
    _dismissedDevices.clear();
    _baselineSeenLocally = false;
    _deviceListFrozen = false;
    _deviceListTooMany = false;
    _pendingBootReadDone = false;
    _pendingSyncGeneration++;
  }

  /// Whether [machineId] is this computer's own daemon, as local discovery reported it — NOT
  /// `isLocalMachine`, which follows a backend-supplied computer id. Every machine's frames reach the
  /// app through that daemon, but only its own `device_*` frames are the daemon's word; a relayed
  /// machine's are anyone's.
  bool _isOwnDaemonMachine(String machineId) {
    if (viewer != null) return false;
    final own = _cliEndpoint?.machineId;
    return own != null && own.isNotEmpty && own == machineId;
  }

  /// Bumped whenever the account's devices may have changed; the Devices list re-reads on it.
  int devicesRevision = 0;

  void _initDeviceLog() {
    final services = viewer;
    if (services == null) return;
    final log = _deviceLog = ViewerDeviceLog(
      keys: services.keys,
      // This app's own key rides each read, so the backend counts it as used (not as abandoned).
      fetch: (since) async => api.deviceKeys(
        since,
        self: await services.keys.identity().then<String?>(
          (i) => b64e(i.pub),
          onError: (Object _) => null,
        ),
      ),
      append: (entry) => api.appendDeviceKey(entry),
      // "It's mine", once for the account: read what other devices confirmed, share what this one does.
      fetchAcks: (since) => api.deviceAcks(since),
      postAck: (ack) => api.postDeviceAck(ack),
      label: _deviceLabel,
      onAnnounce: (m) => _whenSignedIn(() {
        // A key the person has already dismissed (while this waited) is not news any more.
        if (_dismissedDevices.contains(m.pub)) return;
        // The log says each key once, so the notification goes out even when the banner (rebuilt from
        // the log's pending list meanwhile) already holds it.
        _announceDevice(NewDeviceNotice.fromMember(m), always: true);
        // The replay can name a key that has since left the pending list (removed, or dismissed on
        // another device): the log's own list says who is still new, so the banner follows it.
        unawaited(_syncPendingDevices());
      }),
      onRemoved: (n) => _whenSignedIn(() => _announceRemoval(n)),
      onSignedOut: _deviceRemovedHere,
      onChanged: () {
        devicesRevision++;
        unawaited(_syncPendingDevices());
        unawaited(_rereadRemovedMachines());
        unawaited(_redialPinnedMachines());
        if (!_disposed) notifyListeners();
      },
    );
    services.links.deviceLog = log;
  }

  /// Viewer builds only: machines the account's device key log took out and gave no new key since,
  /// by the seq of the removal (`viewer/removed_machines.dart`). The connect page says such a machine
  /// was removed rather than offline — it is signed out, and opening Harness on it will not bring it
  /// back.
  Map<String, int> removedMachines = const {};

  Future<void> _rereadRemovedMachines() async {
    final keys = viewer?.keys;
    if (keys == null) return;
    try {
      final next = removedMachinesOf(await keys.deviceLog());
      if (_disposed || mapEquals(next, removedMachines)) return;
      removedMachines = next;
      notifyListeners();
    } catch (_) {
      // Unreadable now; the next change to the log reads it again.
    }
  }

  /// What the device log announced while the app was not yet signed in (starting up): the log has
  /// already recorded it as announced, so it is said once the app is authenticated — never lost to the
  /// startup order, and dropped only when the person is signed out.
  final List<void Function()> _queuedDeviceNotices = [];

  void _whenSignedIn(void Function() say) {
    switch (_status) {
      case AppStatus.authenticated:
        say();
      case AppStatus.unauthenticated:
        break;
      case AppStatus.bootstrapping:
      case AppStatus.checkingEnvironment:
      case AppStatus.preparingEnvironment:
        _queuedDeviceNotices.add(say);
    }
  }

  void _flushDeviceNotices() {
    if (_queuedDeviceNotices.isEmpty) return;
    final queued = [..._queuedDeviceNotices];
    _queuedDeviceNotices.clear();
    for (final say in queued) {
      say();
    }
  }

  /// How this app names itself in the account's devices.
  String _deviceLabel() {
    // A browser has no computer name to give: "Chrome on macOS". An existing "Browser" entry is
    // renamed to this on its next sync (`viewer/device_log_sync.dart`).
    if (kIsWeb) return browserLabel();
    final host = localHostnameOrNull();
    return host != null && host.isNotEmpty ? host : 'Desktop app';
  }

  DateTime? _deviceLogReadAt;

  /// A socket came back (or the app is in front again): a `device_keys_changed` sent meanwhile reached
  /// nobody, so read the log again — and put this app's key into it if the boot's register could not —
  /// at most every half minute, since a reconnect is every machine at once.
  void _refreshDeviceLogAfterReconnect() {
    final log = _deviceLog;
    if (log == null) return;
    final now = DateTime.now();
    if (_deviceLogReadAt case final last?
        when now.difference(last) < const Duration(seconds: 30)) {
      return;
    }
    _deviceLogReadAt = now;
    unawaited(log.ensureRegistered());
  }

  /// A desktop build's link to its own daemon came back: a conflict, a new device or a departed key
  /// that arose while it was down was only said in frames nobody heard, so the daemon's listing is
  /// read again rather than waiting for the next change to the log.
  void _rereadDevicesAfterDaemonReconnect(String machineId) {
    if (_deviceLog != null || !_isOwnDaemonMachine(machineId)) return;
    unawaited(_syncPendingDevices());
  }

  void _announceDevice(NewDeviceNotice notice, {bool always = false}) {
    final shown = newDevices.any((d) => d.pub == notice.pub);
    // A daemon's frame can repeat; the viewer's log says each key once ([always]).
    if (shown && !always) return;
    if (!shown) {
      newDevices.add(notice);
      if (!_disposed) _deviceJoins.add(notice);
    }
    devicesRevision++;
    systemNotifications.postNotice(
      id: 'harness-device:${notice.pub}',
      title: 'New device on your account',
      body: '${notice.sentence} Not yours? Remove it in Machines.',
      devicePub: notice.pub,
    );
    notifyListeners();
  }

  /// Rebuilds [newDevices] from the copy of the log that persists them — this app's (viewer) or the
  /// daemon's (desktop) — so a restart, or a device the log read before this window opened, still
  /// shows. A daemon that predates `pending` sends none: the in-memory notices stay as they are.
  Future<void> _syncPendingDevices() async {
    // Reads can overlap (a `device_keys_changed` and the `device_key_added` that follows it): only the
    // latest one started may write, or an older listing could take back a device just announced.
    final generation = ++_pendingSyncGeneration;
    try {
      final List<String> pending;
      final List<NewDeviceNotice> known;
      final List<DeviceLogDeparted> departed;
      DeviceConflict? conflict;
      var daemon = false;
      var legacyDaemon = false;
      var frozen = false;
      String? registerError;
      if (_deviceLog case final log?) {
        final listing = await log.list();
        frozen = listing.frozen != null;
        registerError = listing.registerError;
        pending = listing.pending;
        departed = listing.departed;
        known = [
          for (final r in listing.members)
            NewDeviceNotice.fromMember(r.member, suspended: r.suspended),
        ];
      } else {
        final raw = await api.daemonDevices();
        if (raw == null) return;
        // A daemon that predates the persisted marks answers without `pending` (and without `departed`):
        // it has nothing to say about them, and asking again every recovery tick would not change that.
        legacyDaemon = raw['pending'] is! List;
        final devices = legacyDaemon ? null : AccountDevices.fromDaemon(raw);
        if (!legacyDaemon && devices == null) return;
        daemon = true;
        pending = devices?.pending ?? const [];
        departed = DeviceLogDeparted.listFromJson(raw['departed']);
        conflict = devices?.conflict;
        registerError = devices?.registerError;
        known = [
          for (final d in devices?.devices ?? const <AccountDevice>[])
            NewDeviceNotice(
              pub: d.pub,
              label: d.label,
              kind: d.kind,
              frameFingerprint: d.fingerprint,
              suspended: d.suspended,
            ),
        ];
      }
      // No account check: at boot the profile (which sets [currentUser]) and this read race, so one taken
      // before it would drop the listing for good. A sign-out bumps the generation instead
      // ([_clearDeviceNoticeState]), and a daemon's listing is the daemon's current account.
      // Nor after a sign-out: a read already in flight must not put the old account's banner back.
      if (_disposed ||
          generation != _pendingSyncGeneration ||
          status == AppStatus.unauthenticated)
        return;
      _pendingBootReadDone = true;
      if (legacyDaemon) return;
      final tooMany = registerError == 'TOO_MANY';
      var changed =
          frozen != _deviceListFrozen || tooMany != _deviceListTooMany;
      _deviceListFrozen = frozen;
      _deviceListTooMany = tooMany;
      // Oldest first: the band names the first, and "(+n more)" the rest.
      final order = {for (var i = 0; i < pending.length; i++) pending[i]: i};
      final next = [
        for (final n in known)
          if (order.containsKey(n.pub) && !_dismissedDevices.contains(n.pub)) n,
      ]..sort((a, b) => order[a.pub]!.compareTo(order[b.pub]!));
      if (!_samePubs(newDevices, next)) {
        changed = true;
        newDevices
          ..clear()
          ..addAll(next);
      }
      final nextDeparted = [
        for (final d in departed)
          if (!_dismissedDevices.contains(d.pub)) d,
      ];
      if (!_sameDeparted(departedDevices, nextDeparted)) {
        departedDevices
          ..clear()
          ..addAll(nextDeparted);
        changed = true;
      }
      if (conflict == null) _dismissedConflict = null;
      if (daemon &&
          deviceConflict?.pub !=
              (conflict?.pub == _dismissedConflict ? null : conflict?.pub)) {
        deviceConflict = conflict?.pub == _dismissedConflict ? null : conflict;
        changed = true;
      }
      if (changed) notifyListeners();
    } catch (_) {
      // Unreadable now; the next change retries.
    }
  }

  int _pendingSyncGeneration = 0;

  /// Whether the pending list has been read once under this sign-in. Until it has, a recovery tick
  /// reads it again (the first read may have found nothing yet, or been dropped); after, the log's own
  /// changes and the daemon's frames say when to read, so a recovery tick every few seconds does not.
  bool _pendingBootReadDone = false;

  static bool _sameDeparted(
    List<DeviceLogDeparted> a,
    List<DeviceLogDeparted> b,
  ) {
    if (a.length != b.length) return false;
    for (var i = 0; i < a.length; i++) {
      if (a[i].pub != b[i].pub || a[i].removedAt != b[i].removedAt)
        return false;
    }
    return true;
  }

  static bool _samePubs(List<NewDeviceNotice> a, List<NewDeviceNotice> b) {
    if (a.length != b.length) return false;
    for (var i = 0; i < a.length; i++) {
      if (a[i].pub != b[i].pub || a[i].suspended != b[i].suspended)
        return false;
    }
    return true;
  }

  /// Persists "seen" for [pub] (one), every device (neither) or the baseline panel, in whichever copy
  /// of the log this end keeps. Only when that cannot be — a daemon that predates it — does it stay
  /// in memory ([_dismissedDevices]). [confirm]: the person pressed "It's mine" for that one device, so
  /// the account's other devices are told too and stop showing it as new.
  Future<void> _persistSeen({
    String? pub,
    List<String>? pubs,
    bool baseline = false,
    bool confirm = false,
  }) async {
    // Which dismissals this write settles; the baseline panel's "Got it" settles none of them.
    void settled() {
      if (baseline) return;
      _dismissedDevices.removeWhere(
        (p) => pub != null ? p == pub : (pubs?.contains(p) ?? true),
      );
    }

    try {
      if (_deviceLog case final log?) {
        if (baseline) {
          await log.seeBaseline();
        } else {
          await log.dismiss(pub: pub, pubs: pubs, confirm: confirm);
        }
        settled();
        return;
      }
      if (await api.daemonDismissDevices(
        pub: pub,
        pubs: pubs,
        baseline: baseline,
        confirm: confirm,
      )) {
        settled();
      }
    } catch (_) {}
  }

  /// The devices list was opened: every device announced so far has been seen. [pending] is what the
  /// list itself read as still new, which is written back even when no banner was up for it (a seen
  /// that could not be written before, or a listing read before the banner's). Only the devices that
  /// were shown are marked: one that joined after the read stays new.
  ///
  /// [shown] is the banner's set as it was when the list was READ: the read can wait on the network,
  /// and a device announced meanwhile was never on screen. Without it, whatever the banner holds now.
  ///
  /// [departed] is what that same read listed as joined-and-left: at startup the app may not have read
  /// them as departed yet (a replayed "New device" put one in the banner), and the list did.
  void seenNewDevices({
    Iterable<String> pending = const [],
    Iterable<String>? shown,
    Iterable<String> departed = const [],
  }) {
    final banner = (shown ?? newDevices.map((d) => d.pub)).toSet();
    // A key that joined and left unseen is cleared by its own "Got it" only: opening the list must
    // not mark it seen (a startup replay can have put it in the banner set meanwhile).
    final gone = {for (final d in departedDevices) d.pub, ...departed};
    final seen = banner.difference(gone);
    final seenPending = pending.where((p) => !gone.contains(p)).toSet();
    if (banner.isEmpty && pending.isEmpty && _dismissedDevices.isEmpty) return;
    final marked = {...seen, ...seenPending, ..._dismissedDevices}.toList();
    if (marked.isEmpty) {
      // Only departed keys were up: nothing is marked, so a read of the list under way (the one a
      // startup replay starts, which takes their stale "New device" down) is not stale — let it land.
      final before = newDevices.length;
      newDevices.removeWhere((d) => banner.contains(d.pub));
      if (newDevices.length != before) notifyListeners();
      return;
    }
    _dismissedDevices
      ..addAll(seen)
      ..addAll(seenPending);
    newDevices.removeWhere((d) => banner.contains(d.pub));
    _pendingSyncGeneration++;
    notifyListeners();
    unawaited(_persistSeen(pubs: marked));
  }

  ///
  /// [pub] alone (the device's own page, where a suspension is shown) also lifts a suspension on it;
  /// the banner's "It's mine" does not — it dismisses through [pubs], which leaves a fork's
  /// suspension in place. Either way it is "It's mine" for this one device: the account's other
  /// devices are told, and stop showing it as new (opening the list, [seenNewDevices], tells nobody).
  void dismissNewDevice(String pub, {bool liftSuspension = false}) {
    newDevices.removeWhere((d) => d.pub == pub);
    // A key that joined and left before anyone looked: a "New device" for it is a stale replay, and its
    // flag is cleared by its own "Got it" only ([dismissDeparted]) — "It's mine" here takes the banner
    // down and marks nothing.
    if (departedDevices.any((d) => d.pub == pub)) {
      notifyListeners();
      return;
    }
    _dismissedDevices.add(pub);
    _pendingSyncGeneration++;
    notifyListeners();
    unawaited(
      liftSuspension
          ? _persistSeen(pub: pub, confirm: true)
          : _persistSeen(pubs: [pub], confirm: true),
    );
  }

  /// "Got it" on a key that joined and left before anyone looked: the one way its flag goes away (the
  /// removal band's own "Got it" and opening the list leave it). Persisted where the log lives.
  void dismissDeparted(String pub) => dismissDepartedAll([pub]);

  /// "Got it" on the departed band: the key it shows and the "+N more" behind it, cleared together in
  /// one persisted write (the History still lists each of them).
  void dismissDepartedAll(Iterable<String> pubs) {
    final cleared = pubs.toSet();
    if (cleared.isEmpty) return;
    _dismissedDevices.addAll(cleared);
    departedDevices.removeWhere((d) => cleared.contains(d.pub));
    // The departed band was the one telling of a key's own sign-out ([visibleDeviceRemovals] holds the
    // removal notice back for it): once it is read, that notice must not surface in its place.
    deviceRemovals.removeWhere((n) => n.selfRemoved && cleared.contains(n.pub));
    _pendingSyncGeneration++;
    notifyListeners();
    unawaited(_persistSeen(pubs: cleared.toList()));
  }

  /// "Got it" on the "Already on your account" panel.
  Future<void> seeDeviceBaseline() async {
    _baselineSeenLocally = true;
    await _persistSeen(baseline: true);
    devicesRevision++;
    notifyListeners();
  }

  /// Every add and remove on the account, newest first, as this end verified the log. Null when the
  /// daemon predates it; throws when it cannot be read.
  Future<DeviceLogHistory?> loadDeviceHistory() async {
    if (_deviceLog case final log?) return log.history();
    final raw = await api.daemonDeviceHistory();
    if (raw == null) return null;
    return DeviceLogHistory.fromJson(raw) ?? (throw StateError('BAD_HISTORY'));
  }

  /// Another device took [notice]'s device out of the account (or it signed itself out).
  void _announceRemoval(DeviceRemovalNotice notice) {
    // A red notice (a new device nobody looked at removed it) is never softened by a later one for the
    // same key — only the person's own dismissal takes it down.
    if (!notice.red && deviceRemovals.any((n) => n.pub == notice.pub && n.red))
      return;
    deviceRemovals.removeWhere((n) => n.pub == notice.pub);
    deviceRemovals.add(notice);
    devicesRevision++;
    systemNotifications.postNotice(
      id: 'harness-device-removed:${notice.pub}',
      title: notice.title,
      body: notice.sentence,
      // Red: a click opens the new device that did it.
      devicePub: notice.red ? notice.signer : null,
    );
    notifyListeners();
  }

  void dismissDeviceConflict() {
    _dismissedConflict = deviceConflict?.pub;
    deviceConflict = null;
    notifyListeners();
  }

  void dismissDeviceRemoval(String pub) {
    deviceRemovals.removeWhere((n) => n.pub == pub);
    notifyListeners();
  }

  /// This app's key was removed from the account: its identity is spent, and it signs out. The
  /// next sign-in is a new device, which every other device announces.
  Future<void> _deviceRemovedHere() async {
    final services = viewer;
    if (services == null) return;
    // Sign out first: it takes this app's key out of the log, which needs the key it is about.
    await logout();
    await services.keys.forgetIdentity();
  }

  /// Whether the account's device list can be read from here: through this app's own copy of the
  /// log (a viewer build), or through this computer's daemon once the app is connected to it. Not
  /// before — and never from a test, which has neither and must not dial for one.
  bool get accountDevicesReadable => _deviceLog != null || _pool != null;

  /// The account's devices, from whichever end verified the log. Null when it cannot be read.
  ///
  /// [onListed] hears the banner's devices the moment the listing is read — before the last-seen
  /// request, which the backend can delay — so the list marks as seen only what was shown with it.
  Future<AccountDevices?> loadDevices({
    void Function(List<String> banner)? onListed,
  }) async {
    if (_deviceLog case final log?) {
      final listing = AccountDevices.fromListing(await log.list());
      onListed?.call([for (final d in newDevices) d.pub]);
      return listing.withLastSeen(await api.deviceKeysSeen());
    }
    final raw = await api.daemonDevices();
    onListed?.call([for (final d in newDevices) d.pub]);
    return AccountDevices.fromDaemon(raw);
  }

  /// Take [pub] out of the account on every device. Null when done, else why not.
  Future<String?> removeDevice(String pub) async {
    final error = _deviceLog != null
        ? await _deviceLog!.remove(pub)
        : await api.daemonRemoveDevice(pub);
    if (error == null) newDevices.removeWhere((d) => d.pub == pub);
    devicesRevision++;
    notifyListeners();
    return error;
  }

  /// What trusting the backend's device list again would change; [confirm] does it — the one way
  /// out of a frozen list. Null when no valid list could be read.
  ///
  /// A confirm names the [head] the preview showed: if the backend's list is another by now, nothing is
  /// trusted and the answer is [DevicesRebaseline.logChanged]. Another account's list than the one
  /// signed in to is never trusted by a review ([DevicesRebaseline.otherAccount]): signing in again is.
  Future<DevicesRebaseline?> rebaselineDevices({
    required bool confirm,
    DevLogHead? head,
  }) async {
    final DevicesRebaseline? result;
    if (_deviceLog case final log?) {
      final r = await log.rebaseline(
        confirm: confirm,
        expectedHead: confirm ? head : null,
      );
      // Null is a log that could not be read; a head that moved is a result of its own.
      result = r == null ? null : DevicesRebaseline.fromViewer(r);
    } else {
      result = DevicesRebaseline.fromDaemon(
        await api.daemonRebaselineDevices(
          confirm: confirm,
          head: confirm ? head?.toJson() : null,
        ),
      );
    }
    if (confirm && result != null && !result.refused) {
      devicesRevision++;
      notifyListeners();
    }
    return result;
  }

  final Map<String, DateTime> _groupSyncedAt = {};
  static const _groupResync = Duration(minutes: 5);

  /// Viewer builds only: swaps trust-group rosters with [machineId] (`viewer/group_sync.dart`), at
  /// most every few minutes per machine. With [spread] (a machine was just linked) or when the swap
  /// taught this device a new machine, every other linked machine hears of it straight away. A
  /// machine waiting for its password that the group now vouches for is picked up by its link retry.
  /// No layout store means a test, which must not dial.
  Future<void> _syncGroup(String machineId, {bool spread = false}) async {
    // Only the app's own [DirectLink] dials for it: a CLI build's daemon keeps the group itself, and
    // a test hands over fake links.
    final links = peerLinks;
    if (links is! DirectLink || _paneLayout == null) return;
    final now = DateTime.now();
    final last = _groupSyncedAt[machineId];
    if (!spread && last != null && now.difference(last) < _groupResync) return;
    // Not stamped while the device log is still the last account's (DirectLink.syncGroup skips it
    // then): stamped, a machine reached right after an account switch went five minutes unsynced.
    if (await _deviceLog?.ownsLog() == false) return;
    _groupSyncedAt[machineId] = now;
    // Fire-and-forget from the connection handler: a state file that is locked for a moment must not
    // surface as an unhandled error. The next session retries.
    try {
      final label = _deviceLabel();
      final GroupSyncOutcome outcome = await links.syncGroup(
        machineId,
        label: label,
      );
      if (!spread && outcome.pinned.isEmpty) return;
      for (final other in [...machineStates.keys]) {
        if (other == machineId || machineStates[other]?.nodeOnline == false) {
          continue;
        }
        if (await links.keys.peer(other) == null) continue;
        _groupSyncedAt[other] = DateTime.now();
        await links.syncGroup(other, label: label);
      }
    } catch (_) {
      _groupSyncedAt.remove(machineId);
    }
  }

  List<LinkedMachine> linkedMachines = [];
  bool linkedMachinesLoading = false;
  String? linkedMachinesError;
  Future<void>? _linkedMachinesRequest;
  final _unlinkRequests = <String, Future<String?>>{};
  _RemotePasswordChange? _remotePasswordChange;
  int _remotePasswordRevision = 0;

  /// A password change survives closing its prompt. Reopening observes the
  /// same operation without retaining another copy of the password.
  Future<RemotePasswordStatus>? get pendingRemotePasswordChange {
    final change = _remotePasswordChange;
    return change != null && _authWorkCurrent(change.authRevision)
        ? change.result.future
        : null;
  }

  bool get clearingRemotePassword =>
      pendingRemotePasswordChange != null && _remotePasswordChange!.clearing;

  /// Sets (or replaces) THIS machine's persistent remote password (`harness remote-password
  /// set --stdin --json`) — another machine later connects with `connectWithPassword` using the
  /// same password, no token copy/paste involved.
  Future<RemotePasswordSetResult> setRemotePassword(String password) async {
    final status = await _changeRemotePassword(password);
    return RemotePasswordSetResult(
      error: status.error,
      fingerprint: status.fingerprint,
    );
  }

  /// Queries THIS machine's remote-password state (`harness remote-password status --json`).
  Future<RemotePasswordStatus> remotePasswordStatus() async {
    if (pendingRemotePasswordChange case final pending?) return pending;
    final authRevision = _authRevision;
    final passwordRevision = _remotePasswordRevision;
    if (!_authWorkCurrent(authRevision)) {
      return const RemotePasswordStatus(
        error: 'This request is no longer active.',
      );
    }
    RemotePasswordStatus result;
    try {
      result = await cliLink.remotePasswordStatus();
    } catch (_) {
      result = const RemotePasswordStatus(
        error: 'Could not read this computer’s password status. Try again.',
      );
    }
    if (!_authWorkCurrent(authRevision)) {
      return const RemotePasswordStatus(
        error: 'This request is no longer active.',
      );
    }
    // A slow read must not replace a password changed while it was running.
    if (passwordRevision != _remotePasswordRevision) {
      return remotePasswordStatus();
    }
    return result;
  }

  /// Clears THIS machine's remote password (`harness remote-password clear --json`). Returns null
  /// on success.
  Future<String?> clearRemotePassword() async =>
      (await _changeRemotePassword(null)).error;

  Future<RemotePasswordStatus> _changeRemotePassword(String? password) {
    if (_disposed) {
      return Future.value(
        const RemotePasswordStatus(error: 'This request is no longer active.'),
      );
    }
    if (pendingRemotePasswordChange != null) {
      return Future.value(
        const RemotePasswordStatus(
          error: 'A password change is already in progress.',
        ),
      );
    }
    final change = _RemotePasswordChange(
      _authRevision,
      clearing: password == null,
    );
    _remotePasswordChange = change;
    _remotePasswordRevision++;
    notifyListeners();
    unawaited(_runRemotePasswordChange(change, password));
    return change.result.future;
  }

  Future<void> _runRemotePasswordChange(
    _RemotePasswordChange change,
    String? password,
  ) async {
    RemotePasswordStatus result;
    try {
      if (password == null) {
        result = RemotePasswordStatus(
          error: await cliLink.clearRemotePassword(),
        );
      } else {
        final set = await cliLink.setRemotePassword(password);
        result = RemotePasswordStatus(
          error: set.error,
          hasPassword: set.error == null,
          fingerprint: set.fingerprint,
          setAt: set.error == null ? DateTime.now() : null,
        );
      }
    } catch (_) {
      result = RemotePasswordStatus(
        error: change.clearing
            ? 'Could not clear the password. Try again.'
            : 'Could not set the password. Try again.',
      );
    }
    if (!_authWorkCurrent(change.authRevision)) {
      result = const RemotePasswordStatus(
        error: 'This request is no longer active.',
      );
    }
    if (identical(_remotePasswordChange, change)) _remotePasswordChange = null;
    change.result.complete(result);
    if (_authWorkCurrent(change.authRevision)) notifyListeners();
  }

  /// Refreshes the "machines this one trusts" list (`harness link list`).
  Future<void> refreshLinkedMachines() {
    if (_disposed) return Future.value();
    if (_linkedMachinesRequest case final pending?) return pending;
    final result = Completer<void>();
    _linkedMachinesRequest = result.future;
    unawaited(_loadLinkedMachines(_authRevision, result));
    return result.future;
  }

  Future<void> _loadLinkedMachines(int revision, Completer<void> done) async {
    linkedMachinesLoading = true;
    notifyListeners();
    try {
      final result = await peerLinks.list();
      if (!_authWorkCurrent(revision)) return;
      linkedMachinesError = result.error;
      if (result.error == null) linkedMachines = result.machines;
    } catch (_) {
      if (_authWorkCurrent(revision)) {
        linkedMachinesError = 'Could not load linked machines. Try again.';
      }
    } finally {
      if (identical(_linkedMachinesRequest, done.future)) {
        _linkedMachinesRequest = null;
      }
      if (_authWorkCurrent(revision)) {
        linkedMachinesLoading = false;
        notifyListeners();
      }
      done.complete();
    }
  }

  /// Removes a linked machine's trust pin, then refreshes the list. Returns null on success.
  Future<String?> unlinkMachine(String machineId) {
    if (_disposed) return Future.value('This request is no longer active.');
    return _unlinkRequests.putIfAbsent(
      machineId,
      () => _unlinkMachine(machineId, _authRevision),
    );
  }

  bool unlinkingMachine(String machineId) =>
      _unlinkRequests.containsKey(machineId);

  Future<String?> _unlinkMachine(String machineId, int revision) async {
    try {
      final error = await peerLinks.unlink(machineId);
      if (!_authWorkCurrent(revision)) {
        return 'This request is no longer active.';
      }
      if (error == null) {
        // Keep a successful removal visible even if refreshing the CLI list fails.
        await _linkedMachinesRequest;
        if (!_authWorkCurrent(revision)) {
          return 'This request is no longer active.';
        }
        linkedMachines = linkedMachines
            .where((machine) => machine.machineId != machineId)
            .toList();
        await refreshLinkedMachines();
      }
      return error;
    } catch (_) {
      return 'Could not unlink this machine. Try again.';
    } finally {
      if (_authWorkCurrent(revision)) {
        _unlinkRequests.remove(machineId);
        notifyListeners();
      }
    }
  }

  /// Why the last offline poll of this computer's machine came back empty — logged once per change,
  /// not every five seconds, so a poll that keeps missing leaves one line saying why.
  String? _localPollMiss;

  void _noteLocalPollMiss(MachineState machine, String why) {
    if (_localPollMiss == why) return;
    _localPollMiss = why;
    _logLocalMachine(machine, 'still offline: $why');
  }

  Future<void> _pollOfflineMachine(String machineId) async {
    final machine = machineStates[machineId];
    if (machine == null ||
        machine.nodeOnline != false ||
        (!machine.isLocalMachine && machine.pendingOfflineAgentId == null) ||
        _offlinePollsInFlight.contains(machineId)) {
      return;
    }
    _offlinePollsInFlight.add(machineId);
    try {
      if (machine.isLocalMachine) {
        // The socket first: a daemon answering on it needs no probe to prove it is there.
        if (_healLocalMachine(machine, 'offline poll, socket live')) {
          _localPollMiss = null;
          return;
        }
        final discovery = _discovery;
        final localComputerId = await discovery.computerId();
        if (localComputerId == null ||
            _normalizeComputerId(machine.machine.computerId) !=
                localComputerId) {
          _noteLocalPollMiss(machine, 'computer id does not match');
          return;
        }
        final endpoint = await discovery.discover(
          expectedComputerId: localComputerId,
        );
        if (endpoint == null || endpoint.computerId != localComputerId) {
          _noteLocalPollMiss(machine, 'daemon probe found nothing');
          return;
        }
        _localPollMiss = null;
        _logLocalMachine(machine, 'online (offline poll found the daemon)');
        machine.localEndpoint = endpoint;
        // The gate never got here (the daemon was down at boot): this is the endpoint it would have
        // recorded, and every later dial reads it.
        _cliEndpoint ??= endpoint;
        machine.localOnly = true;
        machine.transportMode = MachineTransportMode.localPlaintext;
        machine.nodeOnline = true;
        _connectMachine(machine);
        await _loadMachineData(machine, force: true);
        final pending = machine.pendingOfflineAgentId;
        if (pending != null) unawaited(_recoverPendingAgent(machine, pending));
        return;
      }
      final latest = (await _fetchMachines()).where(
        (item) => item.machineId == machineId,
      );
      if (latest.isEmpty) return;
      final reportedOnline = latest.first.reportedOnline;
      if (reportedOnline == null) return;
      machine.machine = latest.first;
      await _applyInventoryNodeStatus(machine, reportedOnline);
    } catch (error) {
      debugPrint('offline node retry failed: $machineId: $error');
    } finally {
      _offlinePollsInFlight.remove(machineId);
    }
  }

  /// Open only the machine data sockets after discovery. Terminal panes remain
  /// lazy and are attached only when the user selects an agent row.
  void _autoConnectAndLoadMachines() {
    final visible = machines.map((machine) => machine.machineId).toSet();
    expandedMachines
      ..removeWhere((machineId) => !visible.contains(machineId))
      ..addAll(visible);
    if (machines.isEmpty) {
      selectedMachineId = null;
      return;
    }
    if (!visible.contains(selectedMachineId)) {
      // This computer, when it is one of them. The backend's order is its own
      // business and the local machine is not reliably first in it — landing on
      // someone else's box is a poor default when the user's own is right there.
      selectedMachineId = machines
          .firstWhere(
            (machine) =>
                machineStates[machine.machineId]?.isLocalMachine == true,
            orElse: () => machines.first,
          )
          .machineId;
    }
    if (_deviceLog case final log?) {
      unawaited(
        _connectAfterDeviceLog(log, [
          for (final machine in machines) machineStates[machine.machineId]!,
        ]),
      );
      return;
    }
    for (final machine in machines) {
      final state = machineStates[machine.machineId]!;
      if (_awaitingLink(state)) continue;
      _connectMachine(state);
      unawaited(_loadMachineData(state));
    }
  }

  /// An unlinked machine whose link retry is waiting: the retry dials it, a device list that pins
  /// its key dials it at once ([_redialPinnedMachines]), and the connection that follows a link
  /// loads its agents. A machine-list read dialling it as well was refused every time — every 4 s
  /// while a browser's connect page shows.
  bool _awaitingLink(MachineState machine) =>
      machine.needsLink &&
      _linkRetryTimers.containsKey(machine.machine.machineId);

  /// Viewer builds: a machine this app holds no key for may only be missing from its copy of the
  /// device log — a computer signed in after this app did — so the log is read first, briefly,
  /// rather than dialling a refusal. Machines with a key, and ones already asking for a password,
  /// dial at once.
  Future<void> _connectAfterDeviceLog(
    ViewerDeviceLog log,
    List<MachineState> states,
  ) async {
    final revision = _authRevision;
    final waiting = <MachineState>[];
    for (final state in states) {
      if (_awaitingLink(state)) continue;
      if (state.machine.isShared ||
          state.needsLink ||
          await _holdsMachineKey(state.machine.machineId)) {
        if (!_authWorkCurrent(revision)) return;
        _connectMachine(state);
        unawaited(_loadMachineData(state));
      } else {
        waiting.add(state);
      }
    }
    if (waiting.isEmpty) return;
    await log.refresh().timeout(const Duration(seconds: 5), onTimeout: () {});
    for (final state in waiting) {
      if (!_authWorkCurrent(revision) ||
          !identical(machineStates[state.machine.machineId], state)) {
        continue;
      }
      _connectMachine(state);
      unawaited(_loadMachineData(state));
    }
  }

  /// A user-triggered reload is in flight.
  ///
  /// Read by the rail's reload button, which spins its glyph and stops taking
  /// clicks while this is true. It is deliberately NOT [machinesLoading]: that
  /// one means "there is nothing on screen yet", and a refresh over a list
  /// already up leaves it false on purpose.
  bool get machinesRefreshing => _retryInFlight != null;

  /// The run itself, so a second press joins the first instead of starting a
  /// second `GET /api/machines` beside it. The button's disabled state makes
  /// this hard to reach by pointer, but ⌘R has no such guard, and neither has
  /// the error strip's own retry.
  Future<void>? _retryInFlight;

  Future<void> retryMachines() {
    _deafMachineListWatch.reset();
    return _retryMachines(automatic: false);
  }

  Future<void> _retryMachines({required bool automatic}) {
    if (_disposed) return Future<void>.value();
    final inFlight = _retryInFlight;
    if (inFlight != null) return inFlight;
    late final Future<void> run;
    run = _performRetryMachines(automatic: automatic).whenComplete(() {
      if (identical(_retryInFlight, run)) {
        _retryInFlight = null;
        if (!_disposed) notifyListeners();
      }
    });
    _retryInFlight = run;
    notifyListeners();
    return run;
  }

  Future<void> _performRetryMachines({required bool automatic}) async {
    final revision = _authRevision;
    if (!_authWorkCurrent(revision)) return;
    if (isGuest && _guestDeskRestorePending) {
      await _becomeGuest(revision: revision);
      return;
    }
    // Re-verify the daemon first: a retry that skips straight to `refreshMachines()` can hit
    // the exact same "daemon not connected yet" timeout the button was pressed to escape.
    try {
      await ensureCliDaemonReady();
    } catch (error) {
      if (!_authWorkCurrent(revision)) return;
      if (automatic) {
        _scheduleMachineRecovery(revision);
      } else {
        _lastError = '$error';
        _lastErrorRetryable = true;
      }
      notifyListeners();
      return;
    }
    if (!_authWorkCurrent(revision) || status == AppStatus.unauthenticated) {
      return;
    }
    if (signedIn && !_profileConfirmed) unawaited(_loadProfile());
    // A boot that found the daemon still connecting finishes THROUGH here (see
    // `_loadProfile`), so the local id is followed and the desk joined here as
    // well — once, after the list, as the boot does.
    if (signedIn) {
      // The first boot's read may have found nothing to say yet (or been dropped); read again —
      // until one has succeeded.
      if (!_pendingBootReadDone) unawaited(_syncPendingDevices());
    }
    try {
      if (!await refreshMachines() || !_authWorkCurrent(revision)) return;
      if (!automatic) _lastError = null;
      if (!_localSeatFollowed) await _followLocalMachineIdThenDesk(revision);
      if (signedIn) _deskEnsure(revision);
    } catch (error) {
      if (!_authWorkCurrent(revision)) return;
      _reportMachineLoadError(error, automatic: automatic);
      notifyListeners();
      return;
    }
    await Future.wait(expandedMachines.toList().map(reloadMachineData));
    if (_authWorkCurrent(revision)) notifyListeners();
  }

  void toggleExpand(String machineId) {
    if (expandedMachines.contains(machineId)) {
      expandedMachines.remove(machineId);
    } else {
      expandedMachines.add(machineId);
      selectedMachineId = machineId;
      final machine = machineStates[machineId];
      if (machine != null) {
        _connectMachine(machine);
        unawaited(_loadMachineData(machine));
      }
    }
    notifyListeners();
  }

  /// Makes [machineId] the workspace's machine, where New Harness starts,
  /// until focus moves to a pane on another one.
  void selectMachine(String machineId) {
    if (selectedMachineId == machineId) return;
    selectedMachineId = machineId;
    notifyListeners();
  }

  /// Selects a machine without toggling its tree. Setup/status rows use this
  /// action so clicking an E2EE prompt always opens that machine's setup pane.
  Future<void> selectMachineForSetup(String machineId) async {
    final machine = machineStates[machineId];
    if (machine == null) return;
    _dismissedLinkPrompts.remove(machineId);
    selectedMachineId = machineId;
    expandedMachines.add(machineId);
    // Nothing is torn down here any more. That line existed because the content
    // area was one terminal belonging to whichever machine was selected, so
    // browsing to a second machine's setup form would otherwise have left the
    // first machine's terminal rendering underneath it. Tiles now say what they
    // are on their own and outlive the rail's selection, which makes selecting
    // a machine navigation again — and closing someone's running terminals
    // because they clicked a row would be the surprise, not the fix.
    //
    // The form itself arrives as a tile, which is the only way it can arrive at
    // all: a machine that needs linking has no agents to open.
    showMachinePane(machineId);
    _connectMachine(machine);
    notifyListeners();
  }

  void _connectMachine(MachineState machine) {
    if (machine.machine.isShared) return;
    // A row the daemon has refused as "not the machine I serve" is retired until a machine list
    // re-keys it (_onLocalMachineMismatch): the offline poll and the 15s refresh both reconnect
    // every row, and would otherwise dial that id again every few seconds, 4403 after 4403.
    if (_localMismatchReported.contains(machine.machine.machineId)) return;
    // connFor() starts a new socket and reports `connecting` through onStatus,
    // or returns the existing socket with its current status intact. Do not
    // overwrite an already-connected socket when the user collapses and
    // re-expands the machine row; doing so leaves the UI permanently yellow
    // and disables every agent even though the transport is still ready.
    if (_pool != null &&
        (!machine.isLocalMachine || machine.usesLocalTransport)) {
      _conn(machine.machine.machineId);
    }
  }

  /// Put one agent back on its own vendor login — the Claude / Codex subscription it had before a
  /// grid model was chosen.
  ///
  /// `clearGrid` is a separate flag rather than `gridModel: null` on purpose: the daemon treats an
  /// absent field as "I did not mention the grid", so overloading null would make a forgotten field
  /// and a deliberate "put it back" the same frame. Same pane respawn as picking a model.
  Future<void> clearAgentGrid(String machineId, String agentId) async {
    try {
      await _conn(machineId).request(
        'agent_retarget',
        payload: {'agentId': agentId, 'clearGrid': true},
        timeout: const Duration(seconds: 30),
      );
    } on WsRequestFailure catch (failure) {
      _reportRetargetRefusal(
        machineId,
        agentId,
        failure.code,
        detail: failure.detail,
      );
    } catch (_) {
      // A transport failure or a timeout: the daemon may well have done the move, and the frame
      // that follows says where the agent is. A guess here would tell a story the pane contradicts.
    }
  }

  /// A refusal happens BEFORE the daemon touches the pane — an engine with no way onto a Local
  /// model, a busy agent, a machine that cannot resolve its Local models — so nothing in the
  /// terminal ever says why, and until this existed the click simply did nothing. One sentence, in
  /// the app's own words (`retargetRefusalMessage`); the daemon's detail names the grid.
  void _reportRetargetRefusal(
    String machineId,
    String agentId,
    String code, {
    bool api = false,
    String? detail,
  }) {
    final agent = machineStates[machineId]?.agents
        .where((a) => a.id == agentId)
        .firstOrNull;
    final label = engineIdentity(agent?.engine).label;
    _lastError = retargetRefusalMessage(
      code,
      engineLabel: label,
      api: api,
      detail: detail,
    );
    _lastErrorRetryable = false;
    notifyListeners();
  }

  /// Point one agent at a model on the account's private grid.
  ///
  /// Sends the model id and nothing else: the daemon on that machine resolves the endpoint and the
  /// credential from its own signed-in `grid`, so neither travels over the relay and the app never
  /// holds a grid key. Moving an agent re-execs its pane, which is why this is an explicit choice in
  /// a menu rather than something that can happen by hovering.
  /// [gridName] is the grid the model was picked from — a shared grid's section in the picker.
  /// Absent, the daemon uses the account's own grid, as it always did.
  Future<void> retargetAgentToGridModel(
    String machineId,
    String agentId,
    String modelId, {
    String? gridName,
  }) async {
    try {
      await _conn(machineId).request(
        'agent_retarget',
        payload: {
          'agentId': agentId,
          'gridModel': modelId,
          'gridName': ?gridName,
        },
        timeout: const Duration(seconds: 30),
      );
    } on WsRequestFailure catch (failure) {
      _reportRetargetRefusal(
        machineId,
        agentId,
        failure.code,
        detail: failure.detail,
      );
    } catch (_) {
      // See `clearAgentGrid`: a transport failure is not a refusal, and the next frame is the truth.
    }
  }

  /// Point one agent at [modelId] of the API saved as [connectionId] on this computer.
  ///
  /// Same rule as [retargetAgentToGridModel]: the app names the model, and the daemon reads the
  /// endpoint and key from its own store — the key never reaches the app. Only an agent on this
  /// computer can use its saved APIs; the daemon refuses any other.
  Future<void> retargetAgentToApiModel(
    String machineId,
    String agentId, {
    required String connectionId,
    required String modelId,
  }) async {
    try {
      await _conn(machineId).request(
        'agent_retarget',
        payload: {
          'agentId': agentId,
          'apiConnection': connectionId,
          'apiModel': modelId,
        },
        timeout: const Duration(seconds: 40),
      );
    } on WsRequestFailure catch (failure) {
      _reportRetargetRefusal(
        machineId,
        agentId,
        failure.code,
        api: true,
        detail: failure.detail,
      );
    } catch (_) {
      // See `clearAgentGrid`: a transport failure is not a refusal, and the next frame is the truth.
    }
  }

  /// One `grid_models_list` read of [machineId]'s daemon, as it answered — the raw read behind
  /// [refreshGridModels], which keeps the result as the app's one picture ([gridPictures]).
  ///
  /// The daemon answers from ITS picture of each grid, read without waking any of them, so a sleeping
  /// grid keeps its last known models. Surfaces read [readGridPicture]; a caller that must know this
  /// machine answered right now (the creation check) reads [refreshGridModels].
  ///
  /// Never throws — a machine whose daemon is too old to know the RPC, one with no grid, and one
  /// that timed out are all "nothing to offer", which is what the picker shows.
  Future<GridModels> gridModels(String machineId, {bool userAction = false}) =>
      _askGridModels(machineId, {
        'rowState': true,
        if (userAction) 'userAction': true,
      });

  /// A person opened the Models panel: read this computer's model list marked as theirs, all that
  /// the list's reach (`model_list_user_*`) counts. The panel's own refresh joins it in flight.
  void markModelsOpened() {
    if (localMachineState case final local?) {
      unawaited(refreshGridModels(local.machine.machineId, userAction: true));
    }
  }

  /// One `grid_models_list` ask with [payload].
  ///
  /// `rowState: true` on every ask this app makes: every surface here draws row state, so rows
  /// come back with `unavailable` beside a plain `node` rather than the old build's
  /// `<computer> · seems offline` folded into it — and a loopback window that asked this way gets
  /// its `grid_models_changed` pushes in the same form. An older daemon ignores the field.
  Future<GridModels> _askGridModels(
    String machineId,
    Map<String, dynamic> payload,
  ) async {
    try {
      final response = await _conn(machineId).request(
        'grid_models_list',
        payload: payload,
        timeout: const Duration(seconds: 12),
      );
      return GridModels.fromReply(response);
    } catch (_) {
      // NOT `gridName: null` with an empty list — that is the shape of "this account has no grid",
      // and a caller cannot tell it from "the machine did not answer". A signed-in user whose daemon
      // was offline was told to sign in again, which was both wrong and unactionable.
      return const GridModels.unreachable();
    }
  }

  /// A person asked to see what a resting section serves ("Show models"): ask [machineId]'s
  /// daemon to wake [sectionName], and take its answer as the picture like any read.
  ///
  /// This is one of the acts that may wake a grid — nothing automatic ever calls it. The daemon
  /// answers at once with the section `waking`; the wake itself (one credentialed read, then
  /// credential-less re-reads for up to 45 s) runs there. Its progress reaches a loopback window by
  /// `grid_models_changed`, and every other window only by asking again — which [_followWake] does,
  /// credential-less, for as long as the picture says something is waking.
  ///
  /// Not joined with [refreshGridModels]' in-flight read: that ask carries no `wake`, and folding
  /// this one into it would drop the person's request. An answer that was out when this one landed
  /// is older, and the picture's epoch keeps it from overwriting this.
  Future<GridModels> wakeGridModels(
    String machineId,
    String sectionName,
  ) async {
    final epoch = gridPictures.epochOf(machineId);
    final answer = await _askGridModels(machineId, {
      'rowState': true,
      'wake': [sectionName],
    });
    if (_disposed || !answer.reachable) return answer;
    gridPictures.adopt(machineId, answer, ifEpoch: epoch);
    _followWake(machineId);
    return answer;
  }

  /// How often, and for how long at most, a window re-reads a machine whose picture has a section
  /// waking. The daemon's own wake gives up at 45 s; the extra is its last re-read landing.
  static const _wakeFollowEvery = Duration(seconds: 5);
  static const _wakeFollowFor = Duration(seconds: 60);
  final Map<String, Timer> _wakeFollowers = {};

  bool _pictureWaking(String machineId) =>
      gridPictures[machineId]?.sections.any(
        (s) => s.state == GridSectionState.waking,
      ) ??
      false;

  /// Re-read [machineId] until no section in its picture is waking, or [_wakeFollowFor] passes.
  ///
  /// Harmless where pushes do arrive (this computer's own daemon): the read is the same
  /// credential-less one every surface makes, joined with any other in flight, and a push that
  /// already ended the wake ends this at its next tick. Skipped while the app is in the background,
  /// like every other refresher.
  void _followWake(String machineId) {
    _wakeFollowers.remove(machineId)?.cancel();
    if (!_pictureWaking(machineId)) return;
    final deadline = _wakeFollowFor.inMilliseconds;
    var elapsed = 0;
    _wakeFollowers[machineId] = Timer.periodic(_wakeFollowEvery, (timer) {
      elapsed += _wakeFollowEvery.inMilliseconds;
      if (_disposed || !_pictureWaking(machineId) || elapsed > deadline) {
        timer.cancel();
        if (identical(_wakeFollowers[machineId], timer)) {
          _wakeFollowers.remove(machineId);
        }
        return;
      }
      if (inForeground) unawaited(refreshGridModels(machineId));
    });
  }

  void _stopWakeFollowers() {
    for (final timer in _wakeFollowers.values) {
      timer.cancel();
    }
    _wakeFollowers.clear();
  }

  final Map<String, Future<GridModels>> _gridReads = {};

  /// Ask [machineId]'s daemon for the model list and take the answer as its [gridPictures] entry.
  ///
  /// One read feeds every surface. Reads for one machine that overlap are one request — the Model
  /// Manager, the menu and every pane's picker all refresh on the same return to the foreground, and
  /// that is one question to the daemon, not one per surface. An answer that was already on its way
  /// when a `grid_models_changed` push landed is returned to its caller but not adopted: the push is
  /// newer. An answer that is not one — the machine could not be asked — is returned but not adopted
  /// either: one surface's timed-out read must not blank the list every other surface is showing.
  ///
  /// [userAction] marks the read as a person opening a model list ([markModelsOpened]); joined with
  /// a read in flight, the mark is lost.
  Future<GridModels> refreshGridModels(
    String machineId, {
    bool userAction = false,
  }) {
    final inFlight = _gridReads[machineId];
    if (inFlight != null) return inFlight;
    final epoch = gridPictures.epochOf(machineId);
    late final Future<GridModels> read;
    read = gridModels(machineId, userAction: userAction)
        .then((answer) {
          if (!_disposed && answer.reachable) {
            gridPictures.adopt(machineId, answer, ifEpoch: epoch);
          }
          return answer;
        })
        .whenComplete(() {
          if (identical(_gridReads[machineId], read)) {
            _gridReads.remove(machineId);
          }
        });
    return _gridReads[machineId] = read;
  }

  /// What a surface shows after a read: the app's picture — newer than the answer when a push landed
  /// meanwhile, and the last good list when this read could not reach the machine — or the answer
  /// itself when there has never been a picture.
  Future<GridModels> readGridPicture(String machineId) async {
    final answer = await refreshGridModels(machineId);
    return gridPictures[machineId] ?? answer;
  }

  /// Model Manager keeps the original package ID for installed workspaces.
  static const gridHarness = 'autonomous/autonomous-grid';
  late final harnessMonitor = HarnessMonitorController(this);
  late final _essentials = <String, EssentialHarnessController>{
    harnessMonitorId: harnessMonitor,
  };

  /// The one-click opener for a Store essential (`essentialFor`), or null for any other harness.
  EssentialHarnessController? essential(String id) {
    final known = essentialFor(id);
    if (known == null) return null;
    return _essentials[id] ??= EssentialHarnessController(this, known);
  }

  ModelManagerController? _modelManager;
  ModelManagerController get modelManager =>
      _modelManager ??= ModelManagerController(this);

  ModelsMenuController? _modelsMenu;

  /// Subscription readings for the whole window: the Models panel, New Harness and every pane's model
  /// picker read this ONE controller. Each used to own its own, read at a different moment, and the
  /// picker said "Not signed in" beside a menu showing the same account with 8% left.
  ModelsMenuController get modelsMenu => _modelsMenu ??= ModelsMenuController(
    remote: readRemoteUsage,
    seen: inSight,
  );

  /// This machine's local models. [setup] makes it Grid's first use there too: `grid` installed,
  /// signed in with this Harness account (its token, no second browser) and the account's grid
  /// made, before the list answers — minutes, on a machine with no `grid` yet. Grid is an add-on:
  /// nothing but this, and the acts that need it, ever sets it up.
  Future<Map<String, dynamic>> localModels(
    String machineId, {
    bool refresh = false,
    bool setup = false,
  }) => _conn(machineId).request(
    'grid_fleet_models_list',
    payload: {'refresh': refresh, if (setup) 'setup': true},
    timeout: setup ? const Duration(minutes: 5) : const Duration(seconds: 90),
  );

  Future<Map<String, dynamic>> apiConnections(
    String machineId,
    Map<String, dynamic> payload, {
    Duration timeout = const Duration(seconds: 10),
  }) async {
    final machine = stateOf(machineId);
    if (machine == null ||
        machine.machine.isShared ||
        machine.needsLink ||
        machine.nodeOnline == false ||
        machine.connectionStatus != ConnectionStatus.connected) {
      throw StateError('Reconnect this machine to manage its APIs.');
    }
    final connection = _conn(machineId);
    if (!connection.isReady) {
      throw StateError('Reconnect this machine to manage its APIs.');
    }
    return connection.request(
      'api_connections',
      payload: payload,
      timeout: timeout,
    );
  }

  /// The `connectors` request to [machineId]'s daemon: its connected services
  /// (Settings → Connectors). Never carries a token either way.
  Future<Map<String, dynamic>> connectors(
    String machineId,
    Map<String, dynamic> payload, {
    Duration timeout = const Duration(seconds: 20),
  }) async {
    final machine = stateOf(machineId);
    if (machine == null ||
        machine.machine.isShared ||
        machine.needsLink ||
        machine.nodeOnline == false ||
        machine.connectionStatus != ConnectionStatus.connected) {
      throw StateError('Reconnect this computer to manage its connections.');
    }
    final connection = _conn(machineId);
    if (!connection.isReady) {
      throw StateError('Reconnect this computer to manage its connections.');
    }
    return connection.request('connectors', payload: payload, timeout: timeout);
  }

  /// Starts or stops a local model; with [grid], on that Swarm's grid instead of the account's own
  /// (docs/plans/2026-10-23-swarm-local-models.md).
  Future<Map<String, dynamic>> controlLocalModel(
    String machineId,
    String modelId, {
    required bool start,
    String? grid,
  }) => _conn(machineId).request(
    start ? 'grid_fleet_model_start' : 'grid_fleet_model_stop',
    payload: {'modelId': modelId, 'grid': ?grid},
    timeout: const Duration(seconds: 12),
  );

  /// Sets a Swarm's grid up on [machineId], this computer of the Swarm owner's (CLI `lib/swarmGrid.ts`): `grid`
  /// installed and signed in with the Harness account when it is not, the grid created, [members] added and anyone
  /// else removed. Minutes on a computer that has never run grid.
  Future<Map<String, dynamic>> swarmGridSync(
    String machineId,
    String grid,
    List<String> members,
  ) => _conn(machineId).request(
    'grid_swarm_sync',
    payload: {'grid': grid, 'members': members},
    timeout: const Duration(minutes: 5),
  );

  /// The models shared with this person that [machineId] offers to the Swarm whose grid is [grid] (CLI `lib/swarmOffers.ts`).
  Future<Map<String, dynamic>> swarmOffers(String machineId, String grid) =>
      _conn(machineId).request(
        'grid_swarm_offers',
        payload: {'grid': grid},
        timeout: const Duration(seconds: 10),
      );

  /// Offers [model], shared with this person on [sharedGrid], to the Swarm whose grid is [grid], or stops: the Swarm's
  /// Lead may then start Builders on [machineId] on it.
  Future<Map<String, dynamic>> swarmOffer(
    String machineId, {
    required String grid,
    required String sharedGrid,
    required String model,
    required bool start,
  }) => _conn(machineId).request(
    'grid_swarm_offer',
    payload: {
      'grid': grid,
      'sharedGrid': sharedGrid,
      'model': model,
      'action': start ? 'start' : 'stop',
    },
    timeout: const Duration(seconds: 10),
  );

  /// The saved APIs [machineId] shares with the Swarm whose grid is [grid] (CLI `lib/swarmApiShares.ts`).
  Future<Map<String, dynamic>> swarmApiShares(String machineId, String grid) =>
      _conn(machineId).request(
        'grid_swarm_api_shares',
        payload: {'grid': grid},
        timeout: const Duration(seconds: 10),
      );

  /// Shares [model] of the saved API [connectionId] with the Swarm whose grid is [grid], or stops: every Builder in
  /// the Swarm may then run on it, on this computer's key and credits.
  Future<Map<String, dynamic>> swarmApiShare(
    String machineId, {
    required String grid,
    required String connectionId,
    required String model,
    required bool start,
  }) => _conn(machineId).request(
    'grid_swarm_api_share',
    payload: {
      'grid': grid,
      'connectionId': connectionId,
      'model': model,
      'action': start ? 'start' : 'stop',
    },
    timeout: const Duration(minutes: 2),
  );

  Future<Map<String, dynamic>> downloadLocalModel(
    String machineId,
    String modelId,
  ) => _conn(machineId).request(
    'grid_fleet_model_download',
    payload: {'modelId': modelId},
    timeout: const Duration(seconds: 12),
  );

  /// The session picker opens the same local Models overview as the toolbar.
  Future<void> runLocalModel(
    BuildContext context, {
    String? machineId,
    Future<void> Function(String harnessId, String machineId)? onOpenHarness,
  }) async {
    _modelsRequests.add(null);
  }

  static const machinesHarness = 'autonomous/machine-monitor';

  /// Open Machine Monitor on this computer.
  ///
  /// It belongs on THIS computer and nowhere else: everything it reads — the
  /// machine list, each machine's roster — it reads through the local daemon,
  /// so a copy opened on a remote machine would be describing that machine's
  /// fleet, not the one in front of the person. Not installed here → the
  /// Store, open on its page, whose Install is the way in.
  Future<void> manageMachines(
    BuildContext context, {
    Future<void> Function(String harnessId, String machineId)? onOpenHarness,
  }) async {
    final machine = _localModelMachine();
    if (machine == null) {
      _lastError = 'Connect a machine before opening Machine Monitor.';
      _lastErrorRetryable = false;
      notifyListeners();
      return;
    }
    final machineId = machine.machine.machineId;
    await probeDsh(machineId);
    if (machine.dsh[machinesHarness]?.installed != true) {
      openStore(harness: machinesHarness);
      return;
    }
    if (!context.mounted) return;
    if (onOpenHarness != null) {
      await onOpenHarness(machinesHarness, machineId);
      return;
    }
    await openStoreAgent(context, this, machinesHarness, machineId);
  }

  /// The machine Grid and Machines belong on when no door named one: this
  /// computer's own when the app has one, else whatever the person is looking
  /// at.
  MachineState? _localModelMachine() {
    final local = machineStates.values
        .where((state) => state.isLocalMachine)
        .firstOrNull;
    if (local != null) return local;
    final focused = focusedPane?.machineId ?? selectedMachineId;
    return (focused == null ? null : machineStates[focused]) ??
        machineStates.values.firstOrNull;
  }

  /// A visible Machines panel uses the existing connection; it never dials a
  /// disconnected/unlinked host just to obtain optional system readings.
  Future<MachineResources?> readMachineResources(String machineId) async {
    final reply = await _readResourceSnapshot(machineId);
    return reply == null ? null : MachineResources.fromJson(reply);
  }

  Future<MachineHarnessResources?> readHarnessResources(
    String machineId,
  ) async {
    final reply = await _readResourceSnapshot(machineId, harnesses: true);
    return MachineHarnessResources.parse(reply?['harnesses']);
  }

  Future<Map<String, dynamic>?> _readResourceSnapshot(
    String machineId, {
    bool harnesses = false,
  }) async {
    final machine = machineStates[machineId];
    if (_disposed ||
        machine == null ||
        machine.machine.isShared ||
        machine.needsLink ||
        machine.nodeOnline == false ||
        machine.connectionStatus != ConnectionStatus.connected ||
        (_pool == null && connectionForTest == null)) {
      return null;
    }
    final revision = _authRevision;
    final discoveryRevision = machine._discoveryRevision;
    try {
      final connection = _conn(machineId);
      if (!connection.isReady) return null;
      final reply = await connection.request(
        'machine_resources',
        payload: harnesses
            ? const {'harnesses': true, 'storage': true}
            : const {},
        timeout: const Duration(seconds: 3),
      );
      if (!_machineDiscoveryCurrent(machine, revision, discoveryRevision) ||
          machine.needsLink ||
          machine.nodeOnline == false ||
          machine.connectionStatus != ConnectionStatus.connected ||
          reply['error'] != null) {
        return null;
      }
      return reply;
    } catch (_) {
      // Older daemons and temporarily unavailable readings leave the stats blank.
      return null;
    }
  }

  WsConn _conn(String machineId) {
    if (machineStates[machineId]?.machine.isShared == true) {
      throw StateError('This harness is shared with view-only access.');
    }
    // A machine id the loaded list does not name (a deleted machine a pane or a Swarm agent still
    // names) gets no socket: it would only select a machine the backend refuses (roadmap Phase 1.1).
    if (_machineInventoryLoaded && !machineStates.containsKey(machineId)) {
      throw StateError('This machine is no longer on your account.');
    }
    final testConnection = connectionForTest;
    if (testConnection != null) return testConnection(machineId);
    // The local-manual dev fixture exercises a locally-run backend+node stack directly (no real
    // `harness` CLI involved) — keep it on the old direct-cloud dial. Every other (real) machine now
    // goes through the local CLI daemon regardless of whether it's this computer's own machine or a
    // relayed one: the CLI proxies foreign machines to backend transparently (see `remoteRelay.ts` in
    // the harness CLI repo), so this app never dials backend's WS directly anymore.
    final connection = localManualFixture != null || viewer != null
        ? _pool!.connFor(machineId, transportKind: WsTransportKind.cloudE2ee)
        : _pool!.connFor(
            machineId,
            transportKind: WsTransportKind.localPlaintext,
            // The endpoint the offline poll (or the machine refresh) found for THIS row first; the
            // boot gate's global one only as the fallback. `_cliEndpoint` is set only by a gate that
            // succeeded, so a boot that found the daemon down and a poll that later found it up
            // used to dial a null uri — a StateError per attempt, never a socket.
            localWsUri:
                machineStates[machineId]?.localEndpoint?.wsUri ??
                _cliEndpoint?.wsUri,
            localProtocolVersion:
                machineStates[machineId]?.localEndpoint?.protocolVersion ??
                _cliEndpoint?.protocolVersion ??
                localWsProtocolVersion,
            // This computer's own daemon: retry every second (see WsConn.fixedReconnectDelay). A
            // relayed machine keeps the backoff — its select costs the daemon a backend dial.
            fixedReconnectDelay:
                machineStates[machineId]?.isLocalMachine == true
                ? localDaemonReconnectDelay
                : null,
            // This computer's window connection carries the daemon_* frames, which on Windows the
            // daemon takes only over its pipe (WsConn.trustedLocal). A relayed machine needs no trust.
            trustedLocal: machineStates[machineId]?.isLocalMachine == true,
          );
    _wireConnectionHooks(connection, machineId);
    return connection;
  }

  /// Force a fresh dial of [machineId]'s link ([WsConn.forceReconnect]), at most once per
  /// [forcedRedialWindow].
  ///
  /// A redial knocks every pane on the machine over, and since #1378 each dead pane's first reattach
  /// may ask for one when its open goes unanswered: N dead panes on one machine redialled it N times,
  /// each knocking the others' fresh opens over again. A stalled open inside the window resends on
  /// the link the first redial brought back instead ([TerminalSession]'s recovery polls for that).
  Future<void> _forceRedial(String machineId, [WsConn? connection]) {
    final now = redialClock();
    final last = _lastForcedRedial[machineId];
    if (last != null && now - last < forcedRedialWindow) {
      return Future<void>.value();
    }
    final link = connection ?? _conn(machineId);
    if (link.isClosed) return Future<void>.value();
    _lastForcedRedial[machineId] = now;
    _forcedRedials[machineId] = now;
    return link.forceReconnect();
  }

  @visibleForTesting
  Future<void> forceRedialForTest(String machineId) => _forceRedial(machineId);

  // Every machine — this computer's own, or a relayed one — now speaks the same plaintext local wire
  // protocol to the CLI (which terminates E2EE itself for relayed machines; see remoteRelay.ts in the
  // harness CLI repo). There is no per-machine branching left here at all.
  //
  // Known gap: LocalManualFixture (main_local_manual.dart, a compile-time-gated dev entry point that
  // exercises a locally-run backend+machine-node stack without SSO) used to run its OWN simulated E2EE
  // handshake against that local stack. That simulation depended on the crypto this app no longer
  // carries — the fixture now sends/receives plaintext-local-framed terminal data like every other
  // machine, which needs the target local machine-node to also expect plaintext for the fixture to
  // keep working end-to-end. Fixing that (if still desired) is a machine-node-side change, out of
  // scope here.
  void _wireConnectionHooks(WsConn connection, String machineId) {
    connection.onBinaryFrame = (frame) =>
        _handleTerminalBinary(machineId, frame);
  }

  /// Bulk terminal data for a machine, which may now be feeding several tiles.
  ///
  /// Read the live session identity instead of maintaining a second registry.
  /// Skip unrelated sessions before awaiting: every ignored async call adds a
  /// scheduling turn to the socket's incoming queue. Matching frames enter the
  /// session's ordered renderer queue synchronously, regardless of tab order.
  Future<void> _handleTerminalBinary(String machineId, Uint8List raw) async {
    final targets = _terminalSessionsFor(machineId).toList();
    if (targets.isEmpty) return;
    final clear = decodeTerminalLocal(raw);
    if (clear == null) {
      // Undecodable says the transport is wrong, not that one stream is — so
      // it goes to all of them.
      for (final terminal in targets) {
        terminal.transportLost('Binary terminal frame could not be decoded');
      }
      return;
    }
    for (final terminal in targets) {
      if (terminal.streamId == clear.streamId) {
        await terminal.handleBinary(clear);
      }
    }
  }

  Future<bool> _sendTerminalBinary(
    String machineId,
    TerminalBinaryFrame frame,
  ) async {
    final encoded = encodeTerminalLocal(frame);
    if (encoded == null) return false;
    return _conn(machineId).sendTerminalBinary(encoded);
  }

  Future<void> _loadMachineData(
    MachineState machine, {
    bool force = false,
  }) async {
    if (machine.machine.isShared) return;
    if (!_machineWorkCurrent(machine, _authRevision)) return;
    if (machine.agentLoadStatus == AgentLoadStatus.loaded && !force) return;
    // An unlinked machine refuses every load, and each refusal costs a dial, an error state and a
    // repaint: every machine-list read used to pay that again for nothing. Linking it connects it,
    // and the connection loads with force (`_onMachineConnected`); so does a person's reload.
    if (machine.needsLink && !force) return;
    if (machine.isLocalMachine &&
        !machine.usesLocalTransport &&
        _localLinkLive(machine) &&
        _cliEndpoint != null) {
      // The endpoint was cleared by a probe that missed, but the socket to the daemon is answering:
      // the socket is the better witness. Restore what it was dialed through and load.
      machine.localEndpoint ??= _cliEndpoint;
      _logLocalMachine(machine, 'endpoint restored for a load (socket live)');
    }
    if (machine.isLocalMachine && !machine.usesLocalTransport) {
      machine.transportMode = MachineTransportMode.localOffline;
      if (machine.nodeOnline != false) {
        _logLocalMachine(machine, 'offline (no local endpoint)');
      }
      machine.nodeOnline = false;
      // Offline with nothing to bring it back used to be possible from here: the poll that
      // re-probes the daemon is what ends this state.
      _startOfflineRetry(machine);
      machine.agentsRefreshing = false;
      machine.agentsLoadError = 'Harness is offline — run harness login';
      machine.agentLoadStatus = machine.agents.isEmpty
          ? AgentLoadStatus.error
          : AgentLoadStatus.loaded;
      notifyListeners();
      return;
    }
    final inFlight = machine.agentsLoadInFlight;
    if (inFlight != null) return inFlight;
    late final Future<void> load;
    load = _performMachineDataLoad(machine).whenComplete(() {
      if (identical(machine.agentsLoadInFlight, load)) {
        machine.agentsLoadInFlight = null;
      }
    });
    machine.agentsLoadInFlight = load;
    return load;
  }

  Future<void> _performMachineDataLoad(MachineState machine) async {
    final revision = _authRevision;
    final discoveryRevision = machine._discoveryRevision;
    final nameRevision = machine._agentRevision;
    final hadAgents = machine.agents.isNotEmpty;
    machine.agentsRefreshing = hadAgents;
    if (!hadAgents) machine.agentLoadStatus = AgentLoadStatus.loading;
    machine.agentsLoadError = null;
    notifyListeners();
    final connection = _conn(machine.machine.machineId);
    final deadline = Stopwatch()..start();
    debugPrint('agents_list start: ${machine.machine.machineId}');
    try {
      const inventoryTimeout = Duration(seconds: 10);
      await connection.waitUntilReady(timeout: inventoryTimeout);
      if (!_machineDiscoveryCurrent(machine, revision, discoveryRevision)) {
        return;
      }
      // Keep the inventory's existing total budget, including connection time.
      // Capabilities get their own budget only once the handshake is complete.
      // Never less than a few seconds for the list itself: `deadline` is wall time, and a wait that
      // spanned a sleep (the wait itself counts awake time) would otherwise leave the list none.
      final left = inventoryTimeout - deadline.elapsed;
      const floor = Duration(seconds: 3);
      final remaining = left < floor ? floor : left;
      final capabilities = _loadTerminalCapabilities(
        machine,
        connection,
        revision,
        discoveryRevision,
      );
      final response = await connection.request(
        'agents_list',
        payload: const {'includeStopped': true},
        timeout: remaining,
      );
      if (!_machineDiscoveryCurrent(machine, revision, discoveryRevision)) {
        return;
      }
      final agents = _agentSnapshot(
        machine,
        (response['agents'] as List<dynamic>? ?? [])
            .map((item) => Agent.fromJson(item as Map<String, dynamic>))
            .toList(),
        nameRevision,
      );
      _replaceAgents(machine, agents);
      machine.agentLoadStatus = AgentLoadStatus.loaded;
      machine.agentsRefreshing = false;
      machine.agentsLoadError = null;
      debugPrint(
        'agents_list success: ${machine.machine.machineId} '
        '(${machine.agents.length} agents)',
      );
      // Publish discovery immediately. The capability loader attaches waiting
      // panes when its reply arrives; either response may finish first.
      if (machine.terminalCapabilityLoadInFlight == null) {
        // The machine answered its agent list; nobody asked.
        _attachPendingPanes(machine, intent: AttachIntent.automatic);
        _autoPickFirstAgent();
      }
      notifyListeners();
      await capabilities;
      return;
    } catch (error) {
      if (!_machineDiscoveryCurrent(machine, revision, discoveryRevision)) {
        return;
      }
      machine.agentsRefreshing = false;
      // A request timing out while the local relay session still nominally reports "connected" means
      // the remote node itself has stopped answering — exactly what a REST-status flip to offline
      // means elsewhere, so route it through _applyNodeStatus (not just `nodeOnline = false`) so the
      // pending agent gets captured for auto-reattach, same as any other offline detection path.
      if (error is WsRequestTimeout && _localLinkLive(machine)) {
        // This computer's daemon is still on the socket: it is slow, not gone (just after a wake
        // it can take seconds to answer). Calling it offline here is what left local tiles dark
        // over a live socket until the app was restarted (2026-09-29). The minute's agent sync
        // asks again; a daemon that really died closes the socket, and that path marks it.
        machine.agentsLoadError = 'Harness is not responding — retrying';
        _logLocalMachine(machine, 'slow to answer ${error.type}; kept online');
        final machineId = machine.machine.machineId;
        _slowReloadTimers[machineId] ??= SleepAwareTimer(
          const Duration(seconds: 5),
          () {
            _slowReloadTimers.remove(machineId);
            if (_disposed ||
                !identical(machineStates[machineId], machine) ||
                !_localLinkLive(machine)) {
              return;
            }
            unawaited(_loadMachineData(machine, force: true));
          },
        );
      } else if (error is WsRequestTimeout) {
        machine.agentsLoadError = machine.isLocalMachine
            ? 'Harness is offline — run harness login'
            : 'Harness is offline — run harness start on that machine';
        if (machine.nodeOnline != false) {
          unawaited(
            _applyNodeStatus(machine, false, why: '${error.type} timed out'),
          );
        }
        if (!machine.isLocalMachine) {
          // The relay's cached upstream session can go stale at the E2EE-session layer without the
          // underlying transport ever closing — most commonly the relayed machine's own Harness
          // process restarting, which drops its in-memory session state but doesn't touch the socket.
          // Nothing else would ever notice, so force a fresh dial rather than let every future retry
          // keep timing out against the same dead session.
          unawaited(_forceRedial(machine.machine.machineId, connection));
        }
      } else {
        machine.agentsLoadError = 'Could not load harnesses: $error';
      }
      // A NO_PEER_LINK close already set needsLink (via onLocalFailure) perhaps a microtask before
      // this catch runs — don't downgrade that specific, actionable state back to a generic error.
      if (!hadAgents && machine.agentLoadStatus != AgentLoadStatus.needsLink) {
        machine.agentLoadStatus = AgentLoadStatus.error;
      }
      debugPrint('agents_list failed: ${machine.machine.machineId}: $error');
    }
    if (!_machineDiscoveryCurrent(machine, revision, discoveryRevision)) return;
    // Order matters: a restored tile for THIS machine claims its agent before
    // the first-run convenience gets to look, so the two can never both open.
    // Same list, the other branch of its reply.
    _attachPendingPanes(machine, intent: AttachIntent.automatic);
    _autoPickFirstAgent();
    notifyListeners();
  }

  bool _machineWorkCurrent(MachineState machine, int revision) =>
      _authWorkCurrent(revision) &&
      identical(machineStates[machine.machine.machineId], machine);

  bool _machineDiscoveryCurrent(
    MachineState machine,
    int auth,
    int discovery,
  ) =>
      _machineWorkCurrent(machine, auth) &&
      machine._discoveryRevision == discovery;

  /// A new transport must negotiate its own capabilities and inventory. Release
  /// the old futures immediately; their completions keep their original revision.
  void _resetMachineDiscovery(MachineState machine) {
    machine._discoveryRevision++;
    _offlineRecoveryInFlight.remove(machine.machine.machineId);
    machine.agentsLoadInFlight = null;
    machine.terminalCapabilityLoadInFlight = null;
    machine.agentsRefreshing = false;
    if (machine.agentLoadStatus == AgentLoadStatus.loading) {
      machine.agentLoadStatus = machine.agents.isEmpty
          ? AgentLoadStatus.idle
          : AgentLoadStatus.loaded;
    }
    machine.terminalCapabilityLoaded = false;
    machine.terminalCapabilityAvailable = false;
    machine.terminalCapabilityError = null;
    machine.terminalNoTakeoverAvailable = false;
    machine.terminalPasteRawAvailable = false;
    machine.terminalImagePasteAvailable = false;
    machine.terminalPasteFileAvailable = false;
    machine.mediaPreviewAvailable = false;
  }

  /// Whether the app has already opened a terminal on its own.
  ///
  /// Once, at startup, and never again: a later refresh must not reopen a
  /// terminal the user deliberately closed, and a machine that reconnects
  /// mid-session must not yank the pane away from whatever they are watching.
  bool _autoPickedAgent = false;

  /// Open the first agent on this computer, so the app arrives at work instead
  /// of at an instruction.
  ///
  /// "Select a machine, then an agent terminal" is a correct sentence and a
  /// poor first screen: in the ordinary case — one computer, agents already
  /// running on it — there is exactly one thing the user was going to click.
  ///
  /// Runs after a machine's data load rather than after the machine list,
  /// because [selectAgent] refuses on three counts that are only settled by
  /// then: the agent must exist, it must have a tmux terminal, and the
  /// machine's terminal protocol must have been negotiated. Called on every
  /// load and guarded, rather than wired to one specific load, because which
  /// machine answers first is not something this side decides.
  void _autoPickFirstAgent() {
    if (_autoPickedAgent) return;
    // V2 opens on the welcome screen; discovering an agent is not a request
    // to attach its terminal. Keep the startup gate settled for this run.
    _autoPickedAgent = true;
  }

  /// Ask a machine which engines it has.
  ///
  /// Called when the New Agent dialog opens, not at connect: the answer costs
  /// one interactive shell per engine on the far side, and it is only ever
  /// looked at in that dialog.
  ///
  /// That caller passes [force], and should: engines come and go through a
  /// terminal this app never sees, and an install the dialog itself started
  /// invalidates the stored answer as it finishes. Without it the app probes
  /// once per run and then insists, for the rest of the session, on what was
  /// true when it started. The cache is here to collapse a re-open into one
  /// sweep, not to spare the machine the question.
  ///
  /// Deduplicated on [MachineEngines.inFlight] so opening the dialog twice, or
  /// reopening it mid-probe, does not start a second sweep. Never throws — a
  /// machine that cannot answer leaves every engine unknown, and unknown is
  /// rendered as the dialog behaved before this existed.
  /// Which domain-specific harnesses [machineId] has or could install — the
  /// `dsh_list` answer, cached per machine and deduplicated on
  /// [MachineDsh.inFlight] exactly like [probeEngines]. The Create dialog asks
  /// with [force] on every open, since an install it started itself is what
  /// most often makes the stored answer stale.
  ///
  /// [userAction] marks the ask as a person opening the Store, for its reach. One that joins an ask
  /// already in flight loses the mark: the count is a lower bound.
  Future<void> probeDsh(
    String machineId, {
    bool force = false,
    bool userAction = false,
  }) {
    final machine = machineStates[machineId];
    if (machine == null) return Future.value();
    final existing = machine.dsh.inFlight;
    if (existing != null) return existing;
    if (machine.dsh.loaded && !force) return Future.value();
    final work = _probeDsh(machine, userAction: userAction);
    machine.dsh.inFlight = work;
    notifyListeners();
    return work;
  }

  Future<void> _probeDsh(
    MachineState machine, {
    bool userAction = false,
  }) async {
    try {
      final result = await _conn(machine.machine.machineId).request(
        'dsh_list',
        payload: userAction ? const {'userAction': true} : const {},
        timeout: const Duration(seconds: 30),
      );
      final raw = result['dsh'];
      if (raw is! List) throw const FormatException('dsh_list: no list');
      machine.dsh.replace(raw.map(DshEntry.fromJson).whereType<DshEntry>());
    } catch (error) {
      // A CLI that predates `dsh_list` refuses it by code, and the dialog then
      // offers only the harnesses this build ships a face for; the machine
      // has the final say at create time (`INVALID_DSH`).
      machine.dsh.error = error is WsRequestFailure
          ? (error.detail?.isNotEmpty == true ? error.detail : error.code)
          : 'This machine could not report its harnesses';
    } finally {
      machine.dsh.inFlight = null;
      notifyListeners();
    }
  }

  /// Uninstall the harness [id] from [machineId] (`dsh_remove`): the clone
  /// goes, a linked install loses only its link, and the machine's catalog is
  /// asked again so the store's "Installed" reads true. Null on success, else
  /// a sentence for the person who clicked.
  Future<String?> removeDsh(String machineId, String id) async {
    final machine = machineStates[machineId];
    if (machine == null) return 'Machine not found';
    final machineName = machine.machine.displayName;
    try {
      final result = await _conn(machineId).request(
        'dsh_remove',
        payload: {'id': id},
        timeout: const Duration(seconds: 30),
      );
      if (result['ok'] != true) {
        final detail = result['detail'];
        return detail is String && detail.isNotEmpty
            ? detail
            : 'Remove failed on $machineName';
      }
    } on WsRequestFailure catch (failure) {
      return switch (failure.code) {
        'UNSUPPORTED' || 'UNSUPPORTED_ON_REMOTE' =>
          'Update the harness CLI on $machineName to remove harnesses',
        _ =>
          failure.detail?.isNotEmpty == true
              ? failure.detail!
              : 'Remove failed on $machineName (${failure.code})',
      };
    } on WsRequestTimeout {
      return '$machineName did not answer. Try again.';
    } catch (_) {
      return 'Remove failed on $machineName';
    }
    await probeDsh(machineId, force: true);
    return null;
  }

  /// Install the harness [id] on [machineId]: clone, set up its toolchain, run
  /// its doctor. Minutes, not seconds — the Circuit toolchain alone is an
  /// `npm ci` — so the request carries its own long budget and the machine
  /// narrates progress through `dsh_install_status` pushes, which land in
  /// [MachineDsh.installs] for the dialog's status line. Null on success, else
  /// a sentence for the person who clicked.
  /// Machines whose socket dropped under a `dsh_install`/`dsh_update`: the
  /// daemon went on without us, so the list is asked once more when the
  /// socket is back. Consumed by [_onMachineConnected].
  final Set<String> _dshProbeOnReconnect = {};

  /// [trustUnverified] is the person's answer to the Store's warning about a
  /// package Harness has not reviewed ([DshEntry.unverified]). Without it such
  /// a package is refused here, so a way into an install that has no warning
  /// of its own — New Harness, a future caller — cannot run a stranger's setup
  /// script unannounced.
  Future<String?> installDsh(
    String machineId,
    String id, {
    bool trustUnverified = false,
  }) => _installOrUpdateDsh(
    machineId,
    id,
    update: false,
    trustUnverified: trustUnverified,
  );

  Future<String?> updateDsh(
    String machineId,
    String id, {
    bool trustUnverified = false,
  }) => _installOrUpdateDsh(
    machineId,
    id,
    update: true,
    trustUnverified: trustUnverified,
  );

  Future<String?> _installOrUpdateDsh(
    String machineId,
    String id, {
    required bool update,
    required bool trustUnverified,
  }) async {
    final machine = machineStates[machineId];
    if (machine == null) return 'Machine not found';
    final entry = machine.dsh[id];
    if (entry != null && entry.unverified && !trustUnverified) {
      return '${entry.name} is not reviewed by Harness. Open it in the Store '
          'to check its source before you ${update ? 'update' : 'install'} it.';
    }
    final machineName = machine.machine.displayName;
    final action = update ? 'Update' : 'Install';
    final verb = update ? 'update' : 'install';
    // A new run every time the button is pressed: a retry after a failure is
    // its own attempt, with its own clock.
    machine.dsh.runs.remove(id);
    machine.dsh.applyInstall(DshInstallProgress(id: id, phase: 'clone'));
    notifyListeners();
    try {
      final result = await _conn(machineId).request(
        update ? 'dsh_update' : 'dsh_install',
        payload: {'id': id},
        timeout: const Duration(minutes: 90),
      );
      if (result['ok'] != true) {
        final detail = result['detail'];
        final error = result['error'];
        return _finishInstall(
          machine,
          id,
          detail is String && detail.isNotEmpty
              ? detail
              : '$action failed on $machineName',
          code: error is String ? error : null,
        );
      }
    } on WsRequestFailure catch (failure) {
      return _finishInstall(machine, id, switch (failure.code) {
        'UNSUPPORTED' || 'UNSUPPORTED_ON_REMOTE' =>
          'Update the harness CLI on $machineName to $verb harnesses',
        _ =>
          failure.detail?.isNotEmpty == true
              ? failure.detail!
              : '$action failed on $machineName (${failure.code})',
      }, code: failure.code);
    } on WsRequestTimeout {
      return _finishInstall(
        machine,
        id,
        '$machineName is still ${update ? 'updating' : 'installing'}. Try again in a few minutes.',
        code: 'TIMEOUT',
      );
    } catch (error) {
      // The socket went away under the request — the daemon does not know, and
      // is most likely still ${verb}ing. Said as that, not as "failed"; the
      // list is asked again when the socket is back (`_onMachineConnected`), so an
      // install that landed reads as installed without another click. (Issue
      // #109: this was the bare "Install failed" whose retry "just worked".)
      appLog.warn('app', 'dsh_$verb $id on $machineName', error: error);
      _dshProbeOnReconnect.add(machineId);
      return _finishInstall(
        machine,
        id,
        'Lost the connection to $machineName while ${update ? 'updating' : 'installing'} — '
        'it may still be finishing there. Try again in a moment.',
        code: 'CONNECTION',
      );
    }
    machine.dsh.applyInstall(DshInstallProgress(id: id, phase: 'done'));
    notifyListeners();
    // The stored answer just became stale by the dialog's own hand.
    await probeDsh(machineId, force: true);
    return null;
  }

  String _finishInstall(
    MachineState machine,
    String id,
    String error, {
    String? code,
  }) {
    machine.dsh.failInstall(id, error, code: code);
    notifyListeners();
    return error;
  }

  Future<void> probeEngines(String machineId, {bool force = false}) {
    final machine = machineStates[machineId];
    if (machine == null) return Future.value();
    final existing = machine.engines.inFlight;
    if (existing != null) return existing;
    if (machine.engines.loaded && !force) return Future.value();
    final work = _probeEngines(machine);
    machine.engines.inFlight = work;
    notifyListeners();
    return work;
  }

  Future<void> _probeEngines(MachineState machine) async {
    try {
      final result = await _conn(machine.machine.machineId).request(
        'engines_probe',
        // The engine list travels so a machine only pays for what the dialog
        // shows. An older CLI that does not know this request answers with an
        // error, which lands in the catch below as "unknown" — never as a wrong
        // "not installed", because a CLI predating the feature would otherwise
        // report every engine missing and offer to install the ones already
        // there.
        payload: {'engines': allEngines.map((e) => e.id).toList()},
        timeout: const Duration(seconds: 30),
      );
      final raw = result['engines'];
      if (raw is! List) throw const FormatException('engines_probe: no list');
      machine.engines.replace(
        raw.map(EngineAvailability.fromJson).whereType<EngineAvailability>(),
      );
    } catch (error) {
      // A CLI that predates `engines_probe` refuses it by code; `detail` already
      // reads as a sentence when the peer sends one, so prefer it verbatim.
      machine.engines.error = error is WsRequestFailure
          ? (error.detail?.isNotEmpty == true ? error.detail : error.code)
          : 'This machine could not report its engines';
    } finally {
      machine.engines.inFlight = null;
      notifyListeners();
    }
  }

  Future<void> _loadTerminalCapabilities(
    MachineState machine,
    WsConn connection,
    int revision,
    int discoveryRevision,
  ) {
    final pending = machine.terminalCapabilityLoadInFlight;
    if (pending != null) return pending;
    late final Future<void> load;
    load =
        _readTerminalCapabilities(
          machine,
          connection,
          revision,
          discoveryRevision,
        ).whenComplete(() {
          if (identical(machine.terminalCapabilityLoadInFlight, load)) {
            machine.terminalCapabilityLoadInFlight = null;
          }
        });
    machine.terminalCapabilityLoadInFlight = load;
    return load;
  }

  Future<void> _readTerminalCapabilities(
    MachineState machine,
    WsConn connection,
    int revision,
    int discoveryRevision,
  ) async {
    try {
      final result = await connection.request(
        'terminal_capabilities',
        payload: {'protocolVersion': TerminalSession.protocolVersion},
        timeout: const Duration(seconds: 8),
      );
      if (!_machineDiscoveryCurrent(machine, revision, discoveryRevision)) {
        return;
      }
      machine.terminalCapabilityLoaded = true;
      machine.terminalCapabilityAvailable =
          result['protocolVersion'] == TerminalSession.protocolVersion &&
          result['backend'] == 'tmux' &&
          result['available'] == true;
      machine.terminalCapabilityError = machine.terminalCapabilityAvailable
          ? null
          : 'tmux terminal streaming is unavailable';
      final features = result['features'];
      machine.terminalPasteRawAvailable =
          features is Map && features['pasteRaw'] == true;
      machine.terminalImagePasteAvailable =
          features is Map && features['imagePaste'] == true;
      machine.terminalPasteFileAvailable =
          features is Map && features['pasteFile'] == true;
      machine.mediaPreviewAvailable =
          features is Map && features['mediaPreview'] == true;
      machine.terminalNoTakeoverAvailable =
          features is Map && features['noTakeover'] == true;
    } catch (_) {
      if (!_machineDiscoveryCurrent(machine, revision, discoveryRevision)) {
        return;
      }
      machine.terminalCapabilityLoaded = true;
      machine.terminalCapabilityAvailable = false;
      machine.terminalCapabilityError = 'Could not negotiate terminal protocol';
      machine.terminalPasteRawAvailable = false;
      machine.terminalImagePasteAvailable = false;
      machine.terminalPasteFileAvailable = false;
      machine.mediaPreviewAvailable = false;
    }
    if (!_machineDiscoveryCurrent(machine, revision, discoveryRevision)) return;
    if (machine.agentLoadStatus != AgentLoadStatus.loading &&
        !machine.agentsRefreshing) {
      // Terminal capabilities landed; nobody asked.
      _attachPendingPanes(machine, intent: AttachIntent.automatic);
      _autoPickFirstAgent();
      notifyListeners();
    }
  }

  List<Agent> _agentSnapshot(
    MachineState machine,
    List<Agent> incoming,
    int revision,
  ) {
    final agents = {
      for (final agent in incoming)
        agent.id: _preserveNewerName(machine, agent, revision),
    };
    for (final restart in machine._agentRestartRevisions.entries) {
      if (restart.value <= revision) continue;
      final current = machine.agents
          .where((agent) => agent.id == restart.key)
          .firstOrNull;
      if (current != null) agents[restart.key] = current;
    }
    for (final removal in machine._agentRemovals.entries) {
      if (removal.value <= revision) continue;
      final current = machine.agents
          .where((agent) => agent.id == removal.key)
          .firstOrNull;
      if (current == null) {
        agents.remove(removal.key);
      } else {
        // A new incarnation seen after the stop also outranks this old read.
        agents[removal.key] = current;
      }
    }
    return agents.values.toList();
  }

  Agent _preserveNewerName(MachineState machine, Agent agent, int revision) {
    final observed = machine._agentNames[agent.id];
    return observed != null &&
            observed.revision > revision &&
            observed.sessionId == agent.sessionId
        ? agent.copyWith(name: observed.name)
        : agent;
  }

  void _recordAgentName(MachineState machine, Agent agent) {
    machine._agentNames[agent.id] = (
      revision: ++machine._agentRevision,
      sessionId: agent.sessionId,
      name: agent.name,
    );
  }

  void _syncAgentName(MachineState machine, Agent agent) {
    for (final pane in panesFor(machine.machine.machineId)) {
      if (pane.agentId == agent.id) {
        pane.session?.renameAgent(agent.displayName);
      }
    }
    var changed = false;
    for (final tab in swarms) {
      // A Swarm's tab keeps the Swarm's name (task #2647).
      if (!tab.nameIsCustom &&
          !tab.isSuperTab &&
          !tab.isProjectTab &&
          tab.titleMachineId == machine.machine.machineId &&
          tab.titleAgentId == agent.id) {
        final title = Swarm.titleFor(agent);
        if (tab.name != title) {
          tab.name = title;
          changed = true;
        }
      }
    }
    if (changed) _persistLayout();
  }

  void _replaceAgents(MachineState machine, List<Agent> agents) {
    final listedBefore = machine.agentsListedOnce;
    machine.agentsListedOnce = true;
    final previousWork = {for (final agent in machine.agents) agent.id: agent};
    agents = [
      for (final agent in agents)
        if (previousWork[agent.id] case final previous?
            when previous.sessionId != agent.sessionId &&
                agent.activity != null &&
                machine.activityOrder[agent.id]?.isOlder(agent.activity!) ==
                    true)
          previous
        else
          retainNewerGitContext(agent, previousWork[agent.id]),
    ];
    final previous = {for (final agent in machine.agents) agent.id: agent};
    final nextIds = agents.map((agent) => agent.id).toSet();
    machine._agentNames.removeWhere((id, _) => !nextIds.contains(id));
    for (final old in machine.agents.where(
      (agent) => !nextIds.contains(agent.id),
    )) {
      _agentRenames.remove((machine.machine.machineId, old.id));
      sessionPreviews.removeAgent(machine.machine.machineId, old.id);
    }
    for (final agent in agents) {
      sessionPreviews.retainAgent(
        machine.machine.machineId,
        agent.id,
        agent.sessionId,
      );
    }
    for (final agentId in machine.processingAgentIds.difference(nextIds)) {
      _cancelTurnActivity(machine.machine.machineId, agentId);
    }
    machine.agents = agents;
    for (final agent in agents) {
      _syncChosenName(machine, agent, previous[agent.id]);
    }
    _watchHeldLaunches(machine);
    for (final agent in agents) {
      _reconcileAgentActivity(machine, agent, previous[agent.id]);
      if (previous[agent.id]?.name != agent.name) {
        _recordAgentName(machine, agent);
      }
      _syncAgentName(machine, agent);
    }
    final pending = machine.pendingOfflineAgentId;
    if (pending != null && !nextIds.contains(pending)) {
      machine.pendingOfflineAgentId = null;
      // A local machine is polled back from offline with or without a pending agent; stopping the
      // poll here left it offline with nothing to end that.
      if (!machine.isLocalMachine || machine.nodeOnline != false) {
        _stopOfflineRetry(machine.machine.machineId);
      }
    }
    if (machine.activeAgentId != null &&
        !nextIds.contains(machine.activeAgentId) &&
        panesFor(machine.machine.machineId).isEmpty) {
      machine.activeAgentId = null;
    }
    machine.processingAgentIds.removeWhere((id) => !nextIds.contains(id));
    machine.unknownActivityAgentIds.removeWhere((id) => !nextIds.contains(id));
    machine.activityOrder.removeWhere((id, _) => !nextIds.contains(id));
    machine.legacyHeartbeatSeen.removeWhere((id) => !nextIds.contains(id));
    machine.sessionAgentIds.clear();
    for (final agent in agents) {
      final sessionId = agent.sessionId;
      if (sessionId != null) machine.sessionAgentIds[sessionId] = agent.id;
    }
    for (final sessionId in machine.pendingProcessingSessions.toList()) {
      final agentId = machine.sessionAgentIds[sessionId];
      if (agentId == null) continue;
      machine.pendingProcessingSessions.remove(sessionId);
      if (!machine.activityOrder.containsKey(agentId)) {
        _markAgentProcessing(machine, agentId);
      }
    }
    _warmPreviews(machine);
    for (final agent in agents) {
      _syncViewerPane(machine, agent);
    }
    // A harness an agent started that this list brings for the first time:
    // beside its starter. Not from the first list, which is the restore.
    for (final agent in agents) {
      _openStartedChild(machine, agent, arrived: listedBefore);
    }
  }

  void _reconcileAgentActivity(
    MachineState machine,
    Agent agent,
    Agent? previous,
  ) {
    // Busy belongs to one conversation, not to the reusable harness ID. A
    // stopped or replaced conversation cannot keep its old working signal.
    if (agent.isStopped ||
        (previous?.sessionId != null &&
            previous!.sessionId != agent.sessionId)) {
      _cancelTurnActivity(machine.machine.machineId, agent.id);
      machine.liveTurnAgents.remove(agent.id);
      machine.legacyHeartbeatSeen.remove(agent.id);
      machine.pendingProcessingSessions.remove(previous?.sessionId);
      if (agent.isStopped) {
        machine.pendingProcessingSessions.remove(agent.sessionId);
      }
    }
    if (!agent.isStopped && agent.activity != null) {
      _applyReportedActivity(machine, agent.id, agent.activity!);
    }
  }

  bool _upsertAgent(MachineState machine, Agent agent) {
    final index = machine.agents.indexWhere((item) => item.id == agent.id);
    final previous = index == -1 ? null : machine.agents[index];
    if (previous?.sessionId != agent.sessionId &&
        agent.activity != null &&
        machine.activityOrder[agent.id]?.isOlder(agent.activity!) == true) {
      return false;
    }
    agent = retainNewerGitContext(agent, previous);
    // Discovery repeatedly sends the same snapshot. Preserve the existing
    // object (pane presentation keys include it), and do not refetch previews
    // or invalidate the workspace for a snapshot with no new information.
    if (previous != null &&
        agentsEqual([previous], [agent]) &&
        machine.agentLoadStatus == AgentLoadStatus.loaded &&
        machine.agentsLoadError == null &&
        !machine.pendingProcessingSessions.contains(agent.sessionId)) {
      // The layout can change independently of the agent snapshot: a newly
      // opened terminal still needs its viewer, and an orphaned viewer must go.
      return _syncViewerPane(machine, previous);
    }
    if (index == -1) {
      machine.agents = [...machine.agents, agent];
    } else {
      machine.agents = [...machine.agents]..[index] = agent;
    }
    _syncChosenName(machine, agent, previous);
    _reconcileAgentActivity(machine, agent, previous);
    if (previous?.name != agent.name) _recordAgentName(machine, agent);
    _syncAgentName(machine, agent);
    sessionPreviews.retainAgent(
      machine.machine.machineId,
      agent.id,
      agent.sessionId,
    );
    sessionPreviews.warm([previewKey(machine.machine.machineId, agent)]);
    machine.sessionAgentIds.removeWhere((_, id) => id == agent.id);
    final sessionId = agent.sessionId;
    if (sessionId != null) {
      machine.sessionAgentIds[sessionId] = agent.id;
      if (machine.pendingProcessingSessions.remove(sessionId) &&
          !machine.activityOrder.containsKey(agent.id)) {
        _markAgentProcessing(machine, agent.id);
      }
    }
    machine.agentLoadStatus = AgentLoadStatus.loaded;
    machine.agentsLoadError = null;
    _watchHeldLaunches(machine);
    _syncViewerPane(machine, agent);
    // A terminal that adopted an engine, or let one go: the tiles already
    // attached to it keep their stream and change their face. The dial's
    // tile list changes with it — a terminal is not on it, its engine is.
    if (previous != null && previous.engine != agent.engine) {
      for (final pane in panesFor(machine.machine.machineId)) {
        if (pane.agentId == agent.id) pane.session?.setEngineId(agent.engine);
      }
      _announceOpenPanesToDial();
    }
    if (agent.launchState == 'failed' && previous?.launchState != 'failed') {
      // Only where the person would otherwise never see it. A harness with a
      // pane open says this in the pane, with the button that answers it
      // (`pane_grid`'s notice) — and this push reaches EVERY client watching
      // the machine, so the window-wide band told people who had pressed
      // nothing to go and check a harness they were not looking at.
      final shown = allPanes.any(
        (pane) =>
            pane.machineId == machine.machine.machineId &&
            pane.agentId == agent.id,
      );
      if (!shown) {
        _lastError = agent.launchDetail ?? 'Failed to start ${agent.name}';
        // The launch already ran and failed (e.g. the engine's automatic
        // install failed) — reloading the machine list will not install it.
        _lastErrorRetryable = false;
      }
    }
    return true;
  }

  bool _syncingChosenNames = false, _chosenNamesAgain = false;

  /// An agent that arrives flagged as having a chosen name, or whose chosen
  /// name changed: the only machine-side news worth a look (task #2920).
  void _syncChosenName(MachineState machine, Agent agent, Agent? previous) {
    if (agent.nameChosen != true) return;
    if (previous?.nameChosen == true && previous?.name == agent.name) return;
    _syncChosenNames(machineId: machine.machine.machineId, harnessId: agent.id);
  }

  /// Sends the names people chose for their agents, as the daemon says, to the
  /// Swarms that show something else (task #2920): an agent renamed before
  /// the rename reached the Swarm shows its name with no second rename. Runs
  /// for one Swarm when its agents change, and for one harness when it arrives
  /// flagged; each name goes once. Only this person's own machines: a harness
  /// shared to watch is view-only.
  void _syncChosenNames({String? tabId, String? machineId, String? harnessId}) {
    if (_disposed) return;
    if (_syncingChosenNames) {
      // Something changed while names were going out: look everywhere again after.
      _chosenNamesAgain = true;
      return;
    }
    _syncingChosenNames = true;
    unawaited(
      superTabs
          .syncChosenNames(
            (machineId, harnessId) {
              final machine = machineStates[machineId];
              if (machine == null || machine.machine.isShared) return null;
              return machine.agents
                  .where((agent) => agent.id == harnessId)
                  .firstOrNull;
            },
            tabId: tabId,
            machineId: machineId,
            harnessId: harnessId,
          )
          .then((_) {}, onError: (Object _) {})
          .whenComplete(() {
            _syncingChosenNames = false;
            if (_chosenNamesAgain) {
              _chosenNamesAgain = false;
              _syncChosenNames();
            }
          }),
    );
  }

  bool _renameAgent(MachineState machine, String agentId, String name) {
    final index = machine.agents.indexWhere((agent) => agent.id == agentId);
    if (index == -1 || name.trim().isEmpty) return false;
    final cleanName = name.trim();
    if (machine.agents[index].name == cleanName) return false;
    machine.agents = [...machine.agents]
      ..[index] = machine.agents[index].copyWith(name: cleanName);
    _recordAgentName(machine, machine.agents[index]);
    _syncAgentName(machine, machine.agents[index]);
    return true;
  }

  // Creation can be in flight while a Stop reply removes the old final pane.
  final _activeAgentCreations = <AgentCreationAttempt>{};

  void _closeTabsEmptiedByStop(Set<Swarm> affected) {
    final activeIndex = swarms.indexWhere((tab) => tab.id == _activeSwarmId);
    final removable = affected.where(
      (tab) =>
          tab.kind == 'harness' &&
          tab.panes.isEmpty &&
          tab.presets.isEmpty &&
          !_activeAgentCreations.any((attempt) => attempt._targetId == tab.id),
    );
    final ids = removable.map((tab) => tab.id).toSet();
    if (ids.isEmpty) return;
    swarms.removeWhere((tab) => ids.contains(tab.id));
    for (final id in ids) {
      _draftSwarmReturns.remove(id);
    }
    if (swarms.isEmpty) {
      // A fresh start page gets the normal welcome/dock behavior. Never reuse
      // the stopped harness's name, which would suppress that entry behavior.
      swarms.add(Swarm(id: 'swarm-${_nextSwarmId++}'));
    }
    if (ids.contains(_activeSwarmId)) {
      _activeSwarmId = swarms[activeIndex.clamp(0, swarms.length - 1)].id;
      selectedMachineId = focusedPane?.machineId;
      _paneFocusRequest++;
    }
  }

  /// The first message each harness was created with, by machine and agent,
  /// for as long as this window runs. An agent that exits before it reads it
  /// hands it to the shell that keeps its pane, and a Change agent with no
  /// conversation to hand off starts the new agent on it: the person picked
  /// OpenCode after Claude Code could not reach Anthropic, and had to type
  /// their task again (fresh macOS VM, 2026-10-08).
  final _firstMessages = <(String, String), String>{};

  @visibleForTesting
  void rememberFirstMessageForTest(
    String machineId,
    String agentId,
    String message,
  ) => _firstMessages[(machineId, agentId)] = message;

  /// An engine that exited left its pane's shell running under [successor]
  /// (the daemon's retainExitedSession). Its tiles move to that shell instead
  /// of closing, so the engine's last screen — the reason it stopped — stays in
  /// front of the person. A first Claude Code harness that could not reach
  /// Anthropic closed its only pane and left a new user on an empty box with
  /// no message (fresh macOS VM, 2026-10-08). The retained deletion reloads the
  /// machine, and that load attaches the tiles once the successor is listed.
  Future<void> _handOverViews(
    MachineState machine,
    String agentId,
    String successor,
  ) async {
    final machineId = machine.machine.machineId;
    if (_firstMessages.remove((machineId, agentId)) case final message?) {
      _firstMessages[(machineId, successor)] = message;
    }
    // An explicit Close or a Change agent owns these panes until it finishes,
    // as [_removeAgent] honours; a shell must not take them from under it.
    if (_closingViewAgents.containsKey((machineId, agentId)) ||
        _agentChanges[(machineId, agentId)]?.preservingViews == true) {
      return;
    }
    final terminals = allPanes
        .where((p) => p.machineId == machineId && p.agentId == agentId)
        .toList();
    if (terminals.isEmpty) return;
    // As a Change agent does: a tab whose only agent was the one that ended
    // gets a fresh desk identity, so a peer that prunes that agent (an older
    // window ignores `successor`) cannot close the tab now showing the shell.
    final replacedTabs = _desk.enabled
        ? swarms.where((swarm) {
            final agents = swarm.panes.where((pane) => pane.agentId != null);
            return _deskTracks(swarm) &&
                _mayReidentify(swarm) &&
                agents.isNotEmpty &&
                agents.every(
                  (pane) =>
                      pane.machineId == machineId && pane.agentId == agentId,
                );
          }).toList()
        : <Swarm>[];
    for (final pane in terminals) {
      await _detachSession(pane, sendClose: false);
      if (allPanes.contains(pane) && pane.agentId == agentId) {
        pane.agentId = successor;
      }
    }
    for (final swarm in swarms) {
      if (swarm.titleMachineId == machineId && swarm.titleAgentId == agentId) {
        swarm.titleAgentId = successor;
      }
    }
    for (final swarm in replacedTabs) {
      if (!swarms.contains(swarm)) continue;
      final previousId = swarm.id;
      swarm.id = newDeskId();
      if (_activeSwarmId == previousId) _activeSwarmId = swarm.id;
      for (final entry in _draftSwarmReturns.entries.toList()) {
        if (entry.value == previousId) _draftSwarmReturns[entry.key] = swarm.id;
      }
    }
    _persistLayout();
    notifyListeners();
  }

  Future<void> _removeAgent(MachineState machine, String agentId) async {
    // Repeated retained-stop events must not invalidate the history refresh
    // already in flight. There is no newer removal when nothing changed.
    if (machine._agentRemovals.containsKey(agentId) &&
        !machine.agents.any((agent) => agent.id == agentId) &&
        !allPanes.any(
          (pane) =>
              pane.machineId == machine.machine.machineId &&
              (pane.agentId == agentId || pane.ownerAgentId == agentId),
        )) {
      return;
    }
    final stop = _agentStops[(machine.machine.machineId, agentId)];
    final confirmedStop = stop != null && _agentStopCurrent(stop) ? stop : null;
    confirmedStop?.confirmed = true;
    machine._agentRemovals[agentId] = ++machine._agentRevision;
    _firstMessages.remove((machine.machine.machineId, agentId));
    _agentRenames.remove((machine.machine.machineId, agentId));
    machine._agentNames.remove(agentId);
    sessionPreviews.removeAgent(machine.machine.machineId, agentId);
    machine.agents = machine.agents
        .where((agent) => agent.id != agentId)
        .toList();
    machine.sessionAgentIds.removeWhere((_, id) => id == agentId);
    _cancelTurnActivity(machine.machine.machineId, agentId);
    if (machine.activeAgentId == agentId) machine.activeAgentId = null;
    if (machine.pendingOfflineAgentId == agentId) {
      machine.pendingOfflineAgentId = null;
      if (!machine.isLocalMachine || machine.nodeOnline != false) {
        _stopOfflineRetry(machine.machine.machineId);
      }
    }
    // Every tile showing it, not just the focused one — and without
    // `terminal_close`, which would be addressed to an agent the machine has
    // already destroyed.
    final machineId = machine.machine.machineId;
    final closing = <Future<void>>[];
    final affected = <Swarm>{};
    for (final pane in allPanes.toList()) {
      final owned =
          pane.machineId == machineId &&
          (pane.agentId == agentId || pane.viewsAgent(machineId, agentId));
      if (!owned) continue;
      // The explicit Close owns these panes until its disk-safe acknowledgement,
      // so it can preserve recently-closed layout and composer history normally.
      if (_closingViewAgents.containsKey((machineId, agentId)) ||
          _agentChanges[(machineId, agentId)]?.preservingViews == true) {
        continue;
      }
      for (final swarm in swarms) {
        if (swarm.panes.contains(pane)) {
          affected.add(swarm);
          swarm.remove(pane);
        }
      }
      closing.add(_detachSession(pane, sendClose: false));
    }
    _closeTabsEmptiedByStop(affected);
    _dismissedViewers.remove(_viewerKey(machineId, agentId));
    finderRoots.forget(machineId, agentId);
    _persistLayout();
    _announceAppFocus();
    try {
      await Future.wait(closing);
    } catch (failure) {
      appLog.warn(
        'agents',
        'Agent stopped; local view cleanup failed: $failure',
      );
    }
    if (confirmedStop != null && !confirmedStop.result.isCompleted) {
      confirmedStop.result.complete(null);
    }
  }

  // ── harness viewers ─────────────────────────────────────────────────────────

  /// Viewer URLs the person closed, by `machine/agent`. A frame carrying the
  /// same URL again leaves the tile closed; a different URL reopens it. Memory
  /// only — a restart is a fresh look at whatever the agent is showing.
  final _dismissedViewers = <String, String>{};

  String _viewerKey(String machineId, String agentId) => '$machineId/$agentId';

  /// Keep [agent]'s viewer tile in step with its frame.
  ///
  /// The daemon says where the harness's viewer is (`viewerUrl`); this puts a
  /// web tile immediately to the RIGHT of the agent's terminal in whichever
  /// tab that shows that terminal, navigates an open tile when the URL
  /// changes, and takes the tile down when the viewer or the terminal goes.
  /// It never steals focus: the person is typing in the terminal the viewer
  /// belongs to. Nothing is persisted — see [PaneKind.web].
  bool _syncViewerPane(MachineState machine, Agent agent) {
    final machineId = machine.machine.machineId;
    if (_agentChanges[(machineId, agent.id)]?.preservingViews == true) {
      return false;
    }
    final url = agent.viewerUrl;
    final viewerState = url ?? agent.viewerError;
    final dismissed =
        viewerState != null &&
        _dismissedViewers[_viewerKey(machineId, agent.id)] == viewerState;
    var changed = _syncFinderPane(machineId, agent.id);
    // Tab by tab: wherever this agent's terminal is, its viewer is beside it,
    // and nowhere else. A terminal opened in a second tab gets a second
    // viewer; a tab whose terminal went loses its viewer.
    for (final swarm in swarms) {
      final at = swarm.panes.indexWhere(
        (pane) =>
            !pane.isWeb &&
            pane.machineId == machineId &&
            pane.agentId == agent.id,
      );
      final viewers = [
        for (final pane in swarm.panes)
          if (pane.isWeb &&
              pane.machineId == machineId &&
              pane.ownerAgentId == agent.id)
            pane,
      ];
      if (viewerState == null || at < 0) {
        for (final pane in viewers) {
          swarm.remove(pane);
          changed = true;
        }
        continue;
      }
      if (viewers.isNotEmpty) {
        // The same page again is nothing new; a different one navigates in
        // place rather than reopening a tile.
        for (final pane in viewers) {
          changed =
              changed ||
              pane.url != url ||
              pane.viewerError != agent.viewerError;
          pane.url = url;
          pane.viewerError = agent.viewerError;
        }
        continue;
      }
      if (dismissed || swarm.panes.length >= maxPanes) continue;
      // The viewer goes LEFT of the terminal: it is what the user watches, the
      // terminal is where they type, and reading order puts the product first.
      final insertion = at;
      final pane = TerminalPane(
        id: _nextPaneId++,
        machineId: machineId,
        kind: PaneKind.web,
        url: url,
        viewerError: agent.viewerError,
        ownerAgentId: agent.id,
      );
      _insertViewer(swarm, insertion, pane);
      // Counts opening a pane with a URL or a known launch error, not rendering its private page.
      productMeasurement.begin(ProductFlow.viewerOpen)(
        agent.viewerError == null ? ProductOutcome.ok : ProductOutcome.failed,
      );
      changed = true;
    }
    if (changed) _persistLayout();
    return changed;
  }

  /// Puts a viewer into [swarm] at [insertion], beside its terminal.
  void _insertViewer(Swarm swarm, int insertion, TerminalPane viewer) {
    swarm.panes.insert(insertion, viewer);
    // The same bookkeeping a split does when it grows the grid by one:
    // pins past the insertion slide right, and the shape is re-derived.
    swarm.pinnedSlots.updateAll(
      (_, slot) => slot >= insertion ? slot + 1 : slot,
    );
    swarm.arranged = null;
    swarm.arrangedKey = null;
    // Alone with its terminal, the viewer takes 70% of the tab and the
    // assistant keeps 30%. Only when nobody has sized this pair
    // by hand: a manual layout is the user's.
    if (swarm.panes.length == 2 && swarm.paneSizes['2:manual'] == null) {
      swarm.savePaneSizes('2:manual', PaneArrangement.viewerBesideTerminal);
    }
  }

  /// Opening an essential (Harness Monitor, Memories) reveals its ordinary DSH pair: its viewer is
  /// focused in the active tab, unzoomed. Zoom is an explicit pane action.
  void showHarnessViewer(String machineId, String agentId) {
    final pane = activeSwarm.panes
        .where(
          (p) =>
              p.isWeb && p.machineId == machineId && p.ownerAgentId == agentId,
        )
        .firstOrNull;
    if (pane == null) return;
    focusPane(pane.id);
    zoomedPaneId = null;
    _persistLayout();
    notifyListeners();
  }

  /// Only navigation crosses the viewer bridge. Lifecycle operations use the ordinary app APIs.
  Future<String?> handleHarnessMonitorAction(
    TerminalPane source,
    Map<String, dynamic> action,
  ) async {
    final owner = stateOf(source.machineId);
    final monitor = owner?.agents
        .where((a) => a.id == source.ownerAgentId && a.dsh == harnessMonitorId)
        .firstOrNull;
    if (!source.isWeb ||
        monitor == null ||
        !activeSwarm.panes.contains(source)) {
      return 'This monitor is no longer active.';
    }
    if (action['action'] == 'assistant') {
      final terminal = activeSwarm.panes
          .where(
            (p) => p.machineId == source.machineId && p.agentId == monitor.id,
          )
          .firstOrNull;
      if (terminal == null) return 'The assistant is unavailable.';
      zoomedPaneId = null;
      focusPane(terminal.id, reveal: true);
      _persistLayout();
      notifyListeners();
      return null;
    }
    final machineId = action['machineId'], agentId = action['agentId'];
    if (action['action'] != 'open' ||
        machineId is! String ||
        agentId is! String) {
      return 'Unknown monitor action.';
    }
    final machine = stateOf(machineId);
    if (machine == null ||
        machine.machine.isShared ||
        machine.connectionStatus != ConnectionStatus.connected) {
      return 'Connect the owning machine to open this session.';
    }
    await _loadMachineData(machine, force: true);
    if (!identical(stateOf(machineId), machine) ||
        !identical(stateOf(source.machineId), owner) ||
        !activeSwarm.panes.contains(source)) {
      return null;
    }
    if (machine.isOffline || machine.agentsLoadError != null) {
      return 'Reconnect the owning machine and refresh the monitor.';
    }
    final agent = machine.agents.where((a) => a.id == agentId).firstOrNull;
    if (agent == null) {
      return 'This session is no longer available. Refresh the monitor.';
    }
    if (agent.isStopped) {
      final result = await resumeAgent(machineId, agentId);
      if (result.error != null) return result.error;
      if (!identical(stateOf(machineId), machine) ||
          !activeSwarm.panes.contains(source)) {
        return null;
      }
    } else if (!agent.terminalAvailable) {
      return 'This session is not ready to open. Refresh the monitor.';
    }
    if (!revealAgentView(machineId, agentId)) {
      newSwarm();
      await addAgentToSwarm(
        machineId,
        agentId,
        swarmId: activeSwarmId,
        intent: AttachIntent.person,
      );
    }
    return null;
  }

  /// Whether the active tab shows this agent's viewer beside its terminal.
  bool viewerPaneShown(String machineId, String agentId) =>
      activeSwarm.panes.any(
        (pane) =>
            pane.isWeb &&
            pane.machineId == machineId &&
            pane.ownerAgentId == agentId,
      );

  /// The header's viewer control: hide the viewer in this tab, or bring it
  /// back beside the terminal. Bringing it back also lifts a dismissal, so a
  /// page closed by hand earlier opens again on request.
  Future<void> toggleViewerPane(String machineId, String agentId) async {
    final viewer = activeSwarm.panes
        .where(
          (pane) =>
              pane.isWeb &&
              pane.machineId == machineId &&
              pane.ownerAgentId == agentId,
        )
        .firstOrNull;
    if (viewer != null) {
      await closePane(viewer.id);
      return;
    }
    final machine = machineStates[machineId];
    final agent = machine?.agents.where((a) => a.id == agentId).firstOrNull;
    if (machine == null ||
        agent == null ||
        (agent.viewerUrl == null && agent.viewerError == null)) {
      return;
    }
    _dismissedViewers.remove(_viewerKey(machineId, agentId));
    _syncViewerPane(machine, agent);
    notifyListeners();
  }

  /// Every harness the person can see RIGHT NOW: each one with a pane on the tab
  /// in front of them, while the window itself is in front.
  ///
  /// The TAB, not the focused pane. A tab of three harnesses is three terminals
  /// on screen at once, and the one holding the cursor is not the only one being
  /// watched — a turn finishing in the pane beside it is visible the moment it
  /// happens. The harnesses on other tabs are the ones nobody can see, and those
  /// are what a notification is for.
  ///
  /// The window has to be in front as well. Every pane keeps its place on the
  /// tab while the app sits behind a browser, and treating that as "being
  /// watched" would swallow exactly the news this feature exists for.
  ///
  /// A seam, because reaching it through real panes means `focusPane`, which
  /// announces the focus to the machine, which dials it — and a test with no
  /// live connection hangs rather than fails.
  late Iterable<({String machineId, String agentId})> Function() watchedAgents =
      _visibleOnTab;

  /// The real answer, reachable from a test without going through `focusPane`.
  @visibleForTesting
  Iterable<({String machineId, String agentId})> visibleOnTabForTest() =>
      _visibleOnTab();

  Iterable<({String machineId, String agentId})> _visibleOnTab() {
    if (lifecycle() != AppLifecycleState.resumed) return const [];
    if (activeSwarm.isStore || activeSwarm.isOrchestrator) {
      return const [];
    }
    return [
      for (final pane in activeSwarm.panes)
        if (zoomedPaneId == null || pane.id == zoomedPaneId)
          if (pane.agentId case final agentId?)
            (machineId: pane.machineId, agentId: agentId),
    ];
  }

  bool _isBeingWatched(String machineId, String agentId) => watchedAgents().any(
    (w) => w.machineId == machineId && w.agentId == agentId,
  );

  /// Clear the mark of every harness now on screen.
  ///
  /// The mark means "something happened on a harness you cannot see". Once it
  /// is on screen that stops being true, however it got there — a tab switched
  /// to, a pane opened onto this tab, the window brought back to the front. So
  /// this runs on every change to the window rather than on each of those
  /// routes, which are many and would each have to remember.
  void seeWatchedAgents() {
    for (final w in watchedAgents()) {
      // A QUESTION IS NOT CLEARED BY BEING LOOKED AT. Everything else here is
      // news — an agent finished, and seeing it is the whole of what was owed.
      // A blocked agent is a job: it is still waiting on a person however many
      // times its tab came to the front, and a badge that stopped counting it
      // would be saying the work was done because somebody glanced at it. It
      // goes when the question is ANSWERED (`commander_question_close`).
      final kind = agentUnread.kindFor(w.machineId, w.agentId);
      if (kind == null || kind == AlertKind.needsYou) {
        continue;
      }
      _forgetUnread(w.machineId, w.agentId);
    }
  }

  /// Drop this harness's mark and tell the daemon, so the dial drops its drawer
  /// row for it too. Silent when there was no mark.
  void _forgetUnread(String machineId, String agentId) {
    if (agentUnread.kindFor(machineId, agentId) == null) return;
    final readToken = agentUnread.readTokenFor(machineId, agentId);
    agentUnread.clear(machineId, agentId);
    // Notification Center would otherwise keep saying "Finished" about an agent
    // the person has already gone and looked at.
    systemNotifications.withdraw(machineId, agentId);
    agentAlerts.dismiss(
      AgentAlert(
        machineId: machineId,
        agentId: agentId,
        title: '',
        kind: AlertKind.done,
        at: DateTime.now(),
      ),
    );
    _announceAgentSeen(machineId, agentId, readToken);
  }

  /// Reading is not answering. A device receipt clears only the exact message
  /// it displayed; the pending question and all pane/focus state remain intact.
  void readAgentNotification(
    String machineId,
    String agentId, {
    String? readToken,
  }) {
    if (readToken != null &&
        agentUnread.readTokenFor(machineId, agentId) != readToken) {
      return;
    }
    final question = questionFor(machineId, agentId);
    if (question != null) {
      final key = AgentUnread.keyFor(machineId, agentId);
      _readQuestionNotifications
        ..remove(key)
        ..[key] = question.requestId;
      while (_readQuestionNotifications.length > AgentUnread.capacity) {
        _readQuestionNotifications.remove(
          _readQuestionNotifications.keys.first,
        );
      }
    }
    _forgetUnread(machineId, agentId);
    if (question != null) notifyListeners();
  }

  bool questionNotificationRead(String machineId, String agentId) {
    final question = questionFor(machineId, agentId);
    return question != null &&
        _readQuestionNotifications[AgentUnread.keyFor(machineId, agentId)] ==
            question.requestId;
  }

  /// Tell the daemon this harness has been looked at, so the dial drops its
  /// drawer row for it.
  ///
  /// Device reads arrive separately from pane-open actions. Both converge on
  /// the same unread state, which is broadcast to every attached dial.
  ///
  /// Guarded by the caller on "there was a mark", so an ordinary tab switch
  /// does not put a frame on every socket.
  void _announceAgentSeen(String machineId, String agentId, String? readToken) {
    // No transport at all — a window still booting, or a plain `test()` with no
    // live pool. `_conn` asserts one exists rather than answering null, which
    // is right for the paths that cannot proceed without it and wrong for a
    // diagnostic aside like this one.
    if (_pool == null && connectionForTest == null) return;
    // Through `_conn`, the resolver everything else on this socket uses — it
    // refuses a shared harness, which this window has no business reporting on
    // anyway, by throwing rather than by returning null.
    // This window's desk state, for its own daemon only (see [_deskConnection]): a viewer has none,
    // and must not dial a machine just to say it.
    if (viewer != null) return;
    try {
      final connection = _conn(machineId);
      if (!connection.isLocal) return;
      unawaited(
        connection
            .sendTerminalFrame('agent_seen', {
              'agentId': agentId,
              'readToken': ?readToken,
            })
            .catchError((_) => false),
      );
    } on StateError {
      // A view-only harness. Nothing to tell the dial about something this
      // window does not drive.
    }
  }

  /// Where the app is. Injected so a test can say so without a real lifecycle.
  ///
  /// ⚠️ Tolerant of there being NO binding. This is read from `focusPane`, which
  /// plain `test()` files exercise in their dozens — and `WidgetsBinding
  /// .instance` THROWS when the binding has not been initialised rather than
  /// answering null. Reading it unguarded took out some fifty tests across the
  /// suite that have nothing to do with notifications.
  ///
  /// Unknown is treated as "not in front", which errs toward announcing news
  /// rather than swallowing it — the direction this feature cannot afford to
  /// get wrong.
  AppLifecycleState? Function() lifecycle = () {
    try {
      return WidgetsBinding.instance.lifecycleState;
    } catch (_) {
      return null;
    }
  };

  void _raiseAlert(
    MachineState machine,
    String agentId,
    AlertKind kind, {
    String? message,
  }) {
    // Nothing at all for the agent on screen in front of you. A sound, a banner
    // and a count are three ways of saying "look over here", and all three are
    // noise about the pane you are already in.
    //
    // A QUESTION IS THE EXCEPTION, and it is the same exception the sweep makes
    // (see [seeWatchedAgents]): it is a job rather than news, so it is owed
    // until it is ANSWERED and being looked at is not an answer. Skipping it
    // here would also have been self-defeating — a question asks the window to
    // bring its agent forward, so "already on screen" was true by construction
    // and the mark was never raised at all (owner, 2026-09-24).
    if (kind != AlertKind.needsYou &&
        _isBeingWatched(machine.machine.machineId, agentId)) {
      return;
    }
    final agent = machine.agents.where((a) => a.id == agentId).firstOrNull;
    // Before the banner and outside its switch: the mark is what the window can
    // still say when somebody has turned the interrupting halves off.
    agentUnread.mark(
      machine.machine.machineId,
      agentId,
      kind,
      fresh: true,
      message: message,
    );
    alerts.play(kind);
    final alert = AgentAlert(
      machineId: machine.machine.machineId,
      agentId: agentId,
      // The agent's own name, and its id only when it has none — a banner
      // naming a uuid tells nobody which pane to look at.
      title: (agent?.name.trim().isNotEmpty ?? false)
          ? agent!.name.trim()
          : agentId,
      kind: kind,
      at: DateTime.now(),
    );
    agentAlerts.post(alert);
    // The operating system only while the window is NOT in front. In front of
    // it the banner already says this, and a second notice in the corner of the
    // screen for the window you are looking at is the same news twice. Unknown
    // counts as not in front, for the reason [lifecycle] gives.
    if (lifecycle() != AppLifecycleState.resumed) {
      systemNotifications.post(alert);
      _noteNotificationOffer(kind);
      _noteMissedWhileAway(machine, agent, kind, alert.title);
    }
  }

  /// Called with the offer when the person is back in front of Harness: an
  /// agent finished (or needs them) while they were away and nothing told
  /// them, because notifications are off. The workspace shows it once.
  void Function()? notificationOffer;
  bool _notificationOfferDue = false;

  @visibleForTesting
  NotificationOfferStore notificationOfferStoreForTest = notificationOfferStore;

  void _noteNotificationOffer(AlertKind kind) {
    if (kind != AlertKind.done && kind != AlertKind.needsYou) return;
    if (systemNotifications.store.value ||
        !systemNotifications.supported ||
        notificationOfferStoreForTest.value) {
      return;
    }
    _notificationOfferDue = true;
  }

  /// Turns notifications on from the offer, asking the system's permission.
  Future<void> acceptNotificationOffer() =>
      systemNotifications.setEnabled(true);

  /// What clicking a banner does: show that agent, wherever it is.
  ///
  /// Reveal first — an agent already on screen just needs focus, and opening a
  /// second view of it would take the terminal away from the one that has it.
  /// Only an agent with no view at all is placed, on the current Swarm, in the
  /// same order [placeFork] uses for the same reason.
  Future<void> revealAgentFromAlert(String machineId, String agentId) async {
    readAgentNotification(machineId, agentId);
    systemNotifications.withdraw(machineId, agentId);
    agentAlerts.dismiss(
      AgentAlert(
        machineId: machineId,
        agentId: agentId,
        title: '',
        kind: AlertKind.done,
        at: DateTime.now(),
      ),
    );
    if (revealAgentView(machineId, agentId)) return;
    if (openSwarmAgentTerminal(machineId, agentId)) return;
    // A Swarm tab shows only its chats' terminals: a pane added to it would
    // be closed by its view, and the click would open nothing (#2792).
    if (activeSwarm.isUtility ||
        activeSwarm.isOrchestrator ||
        activeSwarm.isSuperTab ||
        activeSwarm.panes.length >= maxPanes) {
      newSwarm();
    }
    await addAgentToSwarm(machineId, agentId, swarmId: activeSwarmId);
    revealAgentView(machineId, agentId);
  }

  /// A loaded Swarm's agent running on [machineId] as [harnessId]: its Swarm
  /// comes forward and opens its terminal beside the chat it waits in (Huy,
  /// #2792). False when no Swarm this reader has loaded holds it.
  bool openSwarmAgentTerminal(String machineId, String harnessId) {
    for (final controller in superTabs.loadedControllers) {
      if (controller.accessRevoked) continue;
      final agent = controller.snapshot?.agents
          .where((a) => a.machineId == machineId && a.harnessId == harnessId)
          .firstOrNull;
      final name = superTabName(controller.tabId);
      if (agent == null || name == null) continue;
      openSuperTab(controller.tabId, name);
      controller.openAgentTerminal(agent.id);
      return true;
    }
    return false;
  }

  /// The person has gone to this agent — by clicking its row, its banner, or
  /// anything else that puts it in front of them. Whatever it was carrying has
  /// been seen.
  /// This harness has been gone to — from a banner, from the dial, from a row.
  ///
  /// Same rule as the sweep: arriving at a blocked harness is not answering it,
  /// so its mark stays. See [seeWatchedAgents].
  void markAgentSeen(String machineId, String agentId) {
    final kind = agentUnread.kindFor(machineId, agentId);
    if (kind == null || kind == AlertKind.needsYou) return;
    _forgetUnread(machineId, agentId);
  }

  /// Whatever tile is now in front of the person has been seen.
  ///
  /// Reads the focused pane rather than taking an id, so every route into a
  /// harness clears it without each one having to remember to.
  void _seeFocusedAgent() {
    seeWatchedAgents();
    // Its Agent Messages mark has done its job once the person is looking.
    if (focusedPane case TerminalPane(:final machineId, :final agentId?)) {
      agentMessages.seen(machineId, agentId);
    }
  }

  String? _eventAgentId(
    MachineState machine,
    Map<String, dynamic> event,
    Map<String, dynamic> payload,
  ) {
    final explicit = payload['agentId'] ?? event['agentId'];
    if (explicit is String && explicit.isNotEmpty) return explicit;
    final session = payload['sessionId'] ?? event['dbSessionId'];
    if (session is! String || session.isEmpty) return null;
    return machine.sessionAgentIds[session];
  }

  String? _eventSessionId(
    Map<String, dynamic> event,
    Map<String, dynamic> payload,
  ) {
    final session = payload['sessionId'] ?? event['dbSessionId'];
    return session is String && session.isNotEmpty ? session : null;
  }

  String _turnActivityKey(String machineId, String agentId) =>
      '$machineId\u0000$agentId';

  bool _markAgentProcessing(
    MachineState machine,
    String agentId, {
    Duration? lease,
  }) {
    var changed = machine.unknownActivityAgentIds.remove(agentId);
    changed = machine.processingAgentIds.add(agentId) || changed;
    final key = _turnActivityKey(machine.machine.machineId, agentId);
    _turnActivityWatchdogs.remove(key)?.cancel();
    _turnActivityWatchdogs[key] = Timer(lease ?? turnActivityTimeout, () {
      _turnActivityWatchdogs.remove(key);
      // Closed even when the machine has been replaced under us: this path is
      // the only end a stalled turn ever gets, and a stats turn left open would
      // sit there until quit and then bank every hour since as work.
      harnessStats.onTurnEnded(key);
      final current = machineStates[machine.machine.machineId];
      if (!identical(current, machine)) return;
      machine.unknownActivityAgentIds.add(agentId);
      if (machine.processingAgentIds.remove(agentId)) notifyListeners();
    });
    return changed;
  }

  ({bool accepted, bool changed}) _applyReportedActivity(
    MachineState machine,
    String agentId,
    AgentActivity activity,
  ) {
    final order = machine.activityOrder.putIfAbsent(
      agentId,
      AgentActivityOrder.new,
    );
    if (!order.accept(activity)) return (accepted: false, changed: false);
    if (activity.state == 'working' && activity.validForMs > 0) {
      return (
        accepted: true,
        changed: _markAgentProcessing(
          machine,
          agentId,
          lease: Duration(milliseconds: activity.validForMs),
        ),
      );
    }
    final wasWorking = machine.processingAgentIds.contains(agentId);
    final wasUnknown = machine.unknownActivityAgentIds.contains(agentId);
    _cancelTurnActivity(
      machine.machine.machineId,
      agentId,
      clearQuestion: false,
    );
    final unknown = activity.state != 'idle';
    if (unknown) machine.unknownActivityAgentIds.add(agentId);
    return (accepted: true, changed: wasWorking || wasUnknown != unknown);
  }

  /// Whether this agent is mid-turn, by the app's own reckoning.
  ///
  /// Fed by `turn_started`/`turn_heartbeat`/`turn_ended` and by the same watchdog that clears a
  /// stalled turn, so it answers what the tiles already draw rather than a second opinion.
  ///
  /// Read by the model menu, which disables itself for exactly the agents the CLI would refuse with
  /// AGENT_BUSY. It is deliberately NOT authoritative: only the CLI inspects the pane, and a turn
  /// can begin between a build and a tap. This spares the user the round trip in the common case;
  /// the refusal remains the thing that guarantees no turn is lost.
  bool agentIsProcessing(String machineId, String agentId) =>
      machineStates[machineId]?.processingAgentIds.contains(agentId) ?? false;

  /// Unknown after attaching to a turn already under way; do not invent an
  /// elapsed time from the last heartbeat or the last time its pane was opened.
  DateTime? agentWorkingSince(String machineId, String agentId) =>
      harnessStats.turnStartedAt(_turnActivityKey(machineId, agentId));

  // ── blocked agents ────────────────────────────────────────────────────────

  /// The question this agent stopped on, if it is waiting for one.
  ///
  /// Read by the tile, which rings itself while its agent is blocked. That ring
  /// is the whole surface: an agent asking something is a fact about the pane
  /// you are looking at, not a queue to be worked through somewhere else.
  PendingQuestion? questionFor(String machineId, String agentId) =>
      machineStates[machineId]?.blockedAgents[agentId];

  /// The per-agent events that only a model answering produces — the CLI's live event kinds
  /// (`SessionEvent` and `LiveEvent` in `cli/src/lib/normalize.ts`) other than the prompt itself
  /// (`turn_started`, `user_message`), the turn's end (which [_cancelTurnActivity] handles), and a
  /// compaction (`context_compact`, which is the engine, not the model). A reasoning model's first
  /// output is its thinking (`thinking_delta`, from the codex, hermes and grok normalizers among
  /// others), long before any text.
  static const _modelAnswerEvents = {
    'thinking_delta',
    'thinking_title',
    'text_delta',
    'tool_start',
    'tool_end',
    'subagent_finished',
    'done',
  };

  /// Start or end the pane chip from one of an agent's turn events — see [ModelStartWatch].
  ///
  /// A message is a `turn_started` that is not a `replay` (a turn picked back up at attach), for
  /// the agent's own session, while its frame says its model's grid is asleep or waking — the
  /// daemon's picture, carried on the agent (`grid.state`). Any of [_modelAnswerEvents] is the
  /// model answering; the turn's end comes through [_cancelTurnActivity]. Terminal bytes are not
  /// read at all: the first thing a pane prints after Enter is its own echo of the prompt.
  void _watchModelStart(
    MachineState machine,
    String type,
    Map<String, dynamic> event,
    Map<String, dynamic> payload,
  ) {
    final agentId = _eventAgentId(machine, event, payload);
    if (agentId == null) return;
    final machineId = machine.machine.machineId;
    if (_modelAnswerEvents.contains(type)) {
      modelStarts.end(machineId, agentId);
      return;
    }
    if (type != 'turn_started' || event['replay'] == true) return;
    final agent = machine.agents.where((a) => a.id == agentId).firstOrNull;
    if (agent == null || agent.gridState?.resting != true) return;
    final sessionId = _eventSessionId(event, payload);
    // A sub-agent's turn is not a message this pane sent.
    if (sessionId != null &&
        agent.sessionId != null &&
        sessionId != agent.sessionId) {
      return;
    }
    modelStarts.start(machineId, agentId);
  }

  void _cancelTurnActivity(
    String machineId,
    String agentId, {
    bool clearQuestion = true,
  }) {
    final key = _turnActivityKey(machineId, agentId);
    _turnActivityWatchdogs.remove(key)?.cancel();
    // Every ordinary end of a turn comes through here — `turn_ended`, a
    // disconnect, a deleted agent — so this is where the clock stops. An end for
    // a turn this process never saw start contributes nothing (see
    // `HarnessStats.onTurnEnded`), which is what makes the disconnect sweep safe.
    harnessStats.onTurnEnded(key);
    // The same ends close the pane's "Starting up…": a turn that ended, however, has nothing
    // left to start for.
    modelStarts.end(machineId, agentId);
    final machine = machineStates[machineId];
    machine?.processingAgentIds.remove(agentId);
    machine?.unknownActivityAgentIds.remove(agentId);
    // Raw turn endings do not decide whether a question is answered. The
    // shared daemon question-close event does. Disconnect/deletion still clear.
    if (clearQuestion) machine?.blockedAgents.remove(agentId);
  }

  void _clearMachineActivity(MachineState machine) {
    for (final agentId in machine.processingAgentIds.toList()) {
      _cancelTurnActivity(machine.machine.machineId, agentId);
    }
    machine.processingAgentIds.clear();
    machine.unknownActivityAgentIds.clear();
    machine.activityOrder.clear();
    machine.legacyHeartbeatSeen.clear();
    machine.pendingProcessingSessions.clear();
    machine.blockedAgents.clear();
  }

  void _clearAllTurnActivity() {
    for (final timer in _turnActivityWatchdogs.values) {
      timer.cancel();
    }
    _turnActivityWatchdogs.clear();
    modelStarts.clear();
    for (final machine in machineStates.values) {
      machine.processingAgentIds.clear();
      machine.unknownActivityAgentIds.clear();
      machine.activityOrder.clear();
      machine.legacyHeartbeatSeen.clear();
      machine.pendingProcessingSessions.clear();
      machine.blockedAgents.clear();
    }
  }

  Future<void> reloadMachineData(String machineId) async {
    final machine = machineStates[machineId];
    if (machine == null) return;
    _connectMachine(machine);
    await _loadMachineData(machine, force: true);
  }

  /// Arm the selected owner's daemon through an already linked browser. Never queue a QR code
  /// across reconnection: closing the dialog must end future pairing attempts.
  Future<Map<String, dynamic>> pairPhone(String machineId, String code) {
    final machine = stateOf(machineId);
    if (machine == null ||
        machine.machine.isShared ||
        machine.needsLink ||
        machine.nodeOnline == false ||
        machine.connectionStatus != ConnectionStatus.connected) {
      return Future.value({'error': 'BACKEND_DOWN'});
    }
    final connection = _conn(machineId);
    if (!connection.isReady) return Future.value({'error': 'BACKEND_DOWN'});
    return connection.request(
      'phone_pair',
      payload: {'code': code},
      timeout: const Duration(seconds: 60),
    );
  }

  /// What every connected REMOTE machine's agent accounts have spent, asked in
  /// through their own CLI rate-limit reports. This computer uses the same
  /// transport: Desktop never opens a vendor credential or usage endpoint.
  Future<List<MachineUsage>> readRemoteUsage() async {
    final remotes = [
      for (final machine in machineStates.values)
        if (machine.connectionStatus == ConnectionStatus.connected &&
            !machine.needsLink &&
            !machine.belongsToOtherAccount &&
            !machine.machine.isTeamAccount)
          machine,
    ];
    final answers = await Future.wait([
      for (final machine in remotes) _readMachineUsage(machine),
    ]);
    return [for (final answer in answers) ?answer];
  }

  /// What to call THIS computer wherever a usage figure has to say whose it is.
  ///
  /// The same `displayName` the sidebar prints and `_readMachineUsage` labels
  /// every remote machine with, so a panel listing one local and one remote
  /// account names them in one vocabulary rather than setting a hostname
  /// beside the words "this computer".
  ///
  /// Falls back to the OS hostname when the local machine has not been fetched
  /// yet — the rail can open before `refreshMachines` lands — and to null when
  /// even that is empty, which the caller renders by dropping the caption
  /// rather than printing a blank one.
  String? get thisMachineName {
    for (final state in machineStates.values) {
      if (state.isLocalMachine) return state.machine.displayName;
    }
    return localHostnameOrNull();
  }

  /// Machines whose daemon can be asked what was said in their sessions now.
  Iterable<String> get searchableMachineIds => [
    for (final machine in machineStates.values)
      if (machine.connectionStatus == ConnectionStatus.connected &&
          !machine.needsLink &&
          machine.nodeOnline != false)
        machine.machine.machineId,
  ];

  /// Every turn of every session on [machineId], searched by its daemon
  /// (`session_search`, cli/src/lib/sessionSearch/). Null when the machine
  /// cannot answer: offline, or a CLI that predates the request, which goes
  /// silent rather than refusing it — hence the short timeout.
  Future<List<SessionContentHit>?> searchSessions(
    String machineId,
    String query, {
    SearchWhen? when,
    int limit = 30,
    Duration budget = const Duration(seconds: 4),
  }) async {
    if (!searchableMachineIds.contains(machineId)) return null;
    final elapsed = Stopwatch()..start();
    List<SessionContentHit>? hits;
    try {
      // Discovery is asynchronous. An unfinished index is not a final empty
      // answer; ask again briefly, within the same budget as one slow request.
      final attempts = budget.inMilliseconds ~/ 200;
      for (var attempt = 0; attempt < attempts; attempt++) {
        if (_disposed || !searchableMachineIds.contains(machineId)) return hits;
        final remaining = budget - elapsed.elapsed;
        if (remaining <= Duration.zero) return hits;
        final reply = await _conn(machineId).request(
          'session_search',
          payload: {
            'query': query,
            'limit': limit,
            if (when != null) ...{
              'from': when.from.millisecondsSinceEpoch,
              'to': when.to.millisecondsSinceEpoch,
            },
          },
          timeout: remaining,
        );
        if (reply['error'] != null) return hits;
        hits = SessionContentHit.listFromReply(machineId, reply);
        // Older daemons omit ready; retain their single-request behavior.
        if (reply['ready'] != false || reply['discoveryError'] == true)
          return hits;
        if (attempt == attempts - 1 ||
            budget - elapsed.elapsed < const Duration(milliseconds: 200))
          return hits;
        await Future<void>.delayed(const Duration(milliseconds: 200));
      }
      return hits;
    } catch (_) {
      return hits;
    }
  }

  /// A cloud harness's conversation from message [after] on (`cloud_transcript`,
  /// CLI services/cloud.ts): `{messages: [{id, from, text, at}], total}`, or
  /// null when its machine cannot answer.
  Future<Map<String, dynamic>?> readCloudTranscript(
    String machineId,
    String agentId, {
    int after = 0,
  }) async {
    try {
      final reply = await _conn(machineId).request(
        'cloud_transcript',
        payload: {'agentId': agentId, if (after > 0) 'after': after},
        timeout: const Duration(seconds: 8),
      );
      return reply['error'] != null ? null : reply;
    } catch (_) {
      return null;
    }
  }

  /// The person's words for a cloud harness (`cloud_send`): null once its
  /// maker took them, else why not, in words a person reads ("Cursor Cloud is
  /// still working").
  Future<String?> sendCloudMessage(
    String machineId,
    String agentId,
    String text,
  ) async {
    try {
      final reply = await _conn(machineId).request(
        'cloud_send',
        payload: {'agentId': agentId, 'text': text},
        // Longer than the machine waits on its cloud service (3 min, CLI
        // core/api.ts LONG_ANSWERS): a maker answering slowly is not a failure.
        timeout: const Duration(seconds: 200),
      );
      if (reply['error'] == null) return null;
      final detail = reply['detail'];
      return detail is String && detail.isNotEmpty
          ? detail
          : 'It could not be sent. Try again.';
    } catch (_) {
      return 'It could not be sent. Try again.';
    }
  }

  /// The rows of [sessionId] on [machineId] before [beforeTurn], or its last
  /// rows (`session_tail`, the same index as [searchSessions]). Null when the
  /// machine cannot answer: offline, a CLI that predates the request, or a
  /// session its index does not hold.
  Future<Map<String, dynamic>?> readSessionTail(
    String machineId,
    String sessionId, {
    int? beforeTurn,
    int? maxChars,
  }) async {
    final reply = await readSessionTailReply(
      machineId,
      sessionId,
      beforeTurn: beforeTurn,
      maxChars: maxChars,
    );
    return reply == null || reply['error'] != null ? null : reply;
  }

  /// [readSessionTail]'s reply with its refusal kept (`NOT_INDEXED`: the
  /// machine's index no longer holds the session). Null when the machine did
  /// not answer.
  Future<Map<String, dynamic>?> readSessionTailReply(
    String machineId,
    String sessionId, {
    int? beforeTurn,
    int? maxChars,
  }) async {
    if (!searchableMachineIds.contains(machineId)) return null;
    try {
      return await _conn(machineId).request(
        'session_tail',
        payload: {
          'sessionId': sessionId,
          'beforeTurn': ?beforeTurn,
          'maxChars': ?maxChars,
        },
        timeout: const Duration(seconds: 4),
      );
    } on WsRequestFailure catch (failure) {
      // The connection throws a refusal; it is still an answer. Swallowed, a
      // NOT_INDEXED row read as no answer and was re-read every 5 seconds:
      // 2,139 failed reads in 3 hours from one computer (2026-10-29).
      return {...failure.payload, 'error': failure.code};
    } catch (_) {
      return null;
    }
  }

  /// Names for tabs from their machines' daemons, asked only while
  /// [autoRenameTabs] is on (see `workspaceTabNames`).
  late final windowNames = WindowNames(
    ask: (machineId, agentIds) => _conn(machineId).request(
      'window_name',
      payload: {'agentIds': agentIds},
      timeout: const Duration(seconds: 10),
    ),
    onChanged: () {
      if (!_disposed) notifyListeners();
    },
  );

  /// Settings ▸ Appearance ▸ Auto rename.
  bool get autoRenameTabs => _autoRenameTabs;
  bool _autoRenameTabs = false;

  void _autoRenameChanged() {
    final enabled = appearancePrefsStore.value.autoRenameTabs;
    if (enabled == _autoRenameTabs) return;
    _autoRenameTabs = enabled;
    // Every tab label switches between the daemon's name and the voted one.
    if (!_disposed) notifyListeners();
  }

  /// The daemon's name for one tab's [request], or null to keep the voted
  /// label. Only this computer's own daemon is asked: a relayed machine's
  /// request would cross the relay unsealed, since `window_name` is not in the
  /// e2ee lists (cli/src/lib/e2ee/core.ts) yet. A machine that is offline or
  /// shared view-only is not asked either: its silence would read as an
  /// older daemon and quiet it for long.
  String? windowNameFor(WindowNameRequest request) {
    final machine = machineStates[request.machineId];
    return windowNames.nameFor(
      request,
      reachable:
          machine != null &&
          machine.isLocalMachine &&
          !machine.machine.isShared &&
          !machine.needsLink &&
          machine.nodeOnline != false &&
          machine.connectionStatus == ConnectionStatus.connected,
    );
  }

  Future<MachineUsage?> _readMachineUsage(MachineState machine) async {
    try {
      final reply = await _conn(machine.machine.machineId)
          .request('usage_read', timeout: const Duration(seconds: 10));
      final readings = parseUsageReadResult(reply);
      if (readings.isEmpty) return null;
      return MachineUsage(
        machineName: machine.machine.displayName,
        isLocal: machine.isLocalMachine,
        readings: readings,
      );
    } catch (_) {
      return null;
    }
  }

  /// Media uses the existing machine-scoped, encrypted file RPC. It is never
  /// queued for a disconnected machine or resolved against this app's cwd.
  Future<Map<String, dynamic>> readRemoteMediaChunk(
    String machineId,
    String agentId,
    String target, {
    required int offset,
    String? revision,
  }) async {
    final machine = machineStates[machineId];
    if (machine == null ||
        machine.needsLink ||
        machine.nodeOnline == false ||
        machine.connectionStatus != ConnectionStatus.connected) {
      throw const RemoteMediaException(
        'This machine is disconnected. Reconnect and try opening the preview again.',
      );
    }
    if (!machine.mediaPreviewAvailable) {
      throw const RemoteMediaException(
        'Update the Harness CLI on this remote machine to open image and video previews.',
      );
    }
    final connection = _conn(machineId);
    if (!connection.isReady) {
      throw const RemoteMediaException(
        'This machine is disconnected. Reconnect and try opening the preview again.',
      );
    }
    try {
      return await connection.request(
        'agent_read_file',
        payload: {
          'agentId': agentId,
          'path': target,
          'media': true,
          'offset': offset,
          'revision': ?revision,
        },
        timeout: const Duration(seconds: 15),
      );
    } on WsRequestFailure catch (error) {
      throw RemoteMediaException(switch (error.code) {
        'MEDIA_NOT_FOUND' || 'NOT_FOUND' => 'This file is no longer available on the remote machine. It may have moved or been deleted.',
        'MEDIA_TOO_LARGE' => 'Remote previews support files up to 512 MB. Use a smaller export or transfer this file separately.',
        'MEDIA_CHANGED' => 'The file changed while downloading. Wait for it to finish generating and try again.',
        'MEDIA_UNSUPPORTED' => 'This file is not a supported image or video.',
        'MEDIA_INVALID_REQUEST' => 'This file is outside the folders Harness reads for this harness. Use one in its working folder or a temp folder.',
        'AGENT_NOT_FOUND' =>
          'This harness is no longer available. Reconnect and try again.',
        'NOT_TEXT' || 'FILE_TOO_LARGE' => 'Update the Harness CLI on this remote machine to open media previews.',
        _ => 'The remote machine could not read this file. Check that it is accessible and try again.',
      });
    } catch (_) {
      throw const RemoteMediaException(
        'The media download was interrupted. Check the connection and try again.',
      );
    }
  }

  /// One-level directory listing on the remote machine, for the New Agent folder browser.
  /// Returns `{path, entries: [{name, isDir}], truncated}` or `{error}` — the caller renders both.
  Future<Map<String, dynamic>> listRemoteFolder(
    String machineId,
    String? path,
  ) async {
    final connection = _conn(machineId);
    try {
      return await connection.request(
        'fs_list_dir',
        payload: {
          ...?path == null ? null : {'path': path},
        },
        timeout: const Duration(seconds: 10),
      );
    } on WsRequestFailure catch (failure) {
      // The machine answered. NOT_FOUND says a folder is not there, which a
      // machine that could not be reached does not know.
      return {'error': failure.code};
    } catch (error) {
      return {'error': 'UNREACHABLE'};
    }
  }

  @visibleForTesting
  Future<Map<String, dynamic>> Function(String machineId, String path)?
  gitProjectReaderForTest;

  /// Git choices are read on the machine that owns this project.
  Future<Map<String, dynamic>> readGitProject(
    String machineId,
    String path, {
    bool refresh = false,
  }) async {
    final machine = machineStates[machineId];
    if (machine == null) return {'error': 'UNAVAILABLE'};
    final reader = gitProjectReaderForTest;
    if (reader != null) return reader(machineId, path);
    if (machine.isLocalMachine) {
      if (!await Directory(path).exists()) {
        return {'error': 'PROJECT_UNAVAILABLE'};
      }
      return readLocalGitProject(path, refresh: refresh);
    }
    if (connectionForTest == null &&
        (machine.nodeOnline == false ||
            machine.needsLink ||
            machine.connectionStatus != ConnectionStatus.connected)) {
      return {'error': 'UNAVAILABLE'};
    }
    try {
      return await _conn(machineId).request(
        'git_project_info',
        payload: {'path': path, if (refresh) 'refresh': true},
        timeout: Duration(seconds: refresh ? 20 : 6),
      );
    } catch (_) {
      return {'error': 'UNAVAILABLE'};
    }
  }

  /// Linked Swarm PRs are read by this window's own computer, using its GitHub login.
  /// An agent changing branch or stopping must not change whose account reads a link.
  Future<Map<String, dynamic>> readPullRequestsStatus(List<String> urls) async {
    final machine = localMachineState, revision = _authRevision;
    if (machine == null) return {'error': 'LOCAL_GITHUB_UNAVAILABLE'};
    try {
      final result = await _conn(machine.machine.machineId).request(
        'git_pull_requests_status',
        payload: {'urls': urls},
        timeout: const Duration(seconds: 120),
      );
      if (!_machineWorkCurrent(machine, revision)) {
        return {'error': 'UNAVAILABLE'};
      }
      return result;
    } on WsRequestFailure catch (error) {
      if (!_machineWorkCurrent(machine, revision)) {
        return {'error': 'UNAVAILABLE'};
      }
      return {...error.payload, 'error': error.code};
    } catch (_) {
      return {'error': 'UNAVAILABLE'};
    }
  }

  /// PR lookup runs on the agent's machine using that machine's GitHub access.
  Future<Map<String, dynamic>> readAgentPullRequest(
    String machineId,
    String agentId,
  ) async {
    final machine = stateOf(machineId), revision = _authRevision;
    final agent = machine?.agents.where((a) => a.id == agentId).firstOrNull;
    if (machine == null || agent == null) return {'status': 'unavailable'};
    final identity = agent.gitContext?.requestIdentity;
    if (agent.gitContext != null && identity == null) {
      return {'status': 'unavailable'};
    }
    try {
      final result = await _conn(machineId).request(
        'git_pull_request',
        payload: {'agentId': agentId, 'context': ?identity},
        timeout: const Duration(seconds: 30),
      );
      if (!_machineWorkCurrent(machine, revision) ||
          !sameGitConversation(
            agent,
            machine.agents.where((a) => a.id == agentId).firstOrNull,
          )) {
        return {'status': 'unavailable'};
      }
      if (identity != null &&
          !mapEquals(
            identity,
            result['context'] is Map
                ? Map<String, Object?>.from(result['context'])
                : null,
          )) {
        return {'status': 'unavailable'};
      }
      return result;
    } catch (_) {
      return {'status': 'unavailable'};
    }
  }

  Future<Map<String, dynamic>> readAgentGitHistory(
    String machineId,
    String agentId, {
    int offset = 0,
  }) async {
    final machine = stateOf(machineId), revision = _authRevision;
    final agent = machine?.agents.where((a) => a.id == agentId).firstOrNull;
    if (machine == null || agent == null) return {'status': 'unavailable'};
    try {
      final result = await _conn(machineId).request(
        'git_pull_request',
        payload: {'agentId': agentId, 'history': true, 'offset': offset},
        timeout: const Duration(seconds: 45),
      );
      if (!_machineWorkCurrent(machine, revision) ||
          !sameGitConversation(
            agent,
            machine.agents.where((a) => a.id == agentId).firstOrNull,
          )) {
        return {'status': 'unavailable'};
      }
      return result;
    } catch (_) {
      return {'status': 'unavailable'};
    }
  }

  /// Reads source material only on the machine that owns the selected path.
  Future<Map<String, dynamic>> readProjectPreview(
    String machineId,
    String path,
  ) async {
    final machine = machineStates[machineId];
    if (machine == null) return {'error': 'UNAVAILABLE'};
    if (machine.isLocalMachine) {
      return readLocalProjectPreview(path).timeout(
        const Duration(seconds: 4),
        onTimeout: () => {'error': 'UNAVAILABLE'},
      );
    }
    if (machine.nodeOnline == false ||
        machine.needsLink ||
        machine.connectionStatus != ConnectionStatus.connected &&
            connectionForTest == null) {
      return {'error': 'UNAVAILABLE'};
    }
    try {
      return await _conn(machineId).request(
        'project_preview',
        payload: {'path': path},
        timeout: const Duration(seconds: 4),
      );
    } catch (_) {
      return {'error': 'UNAVAILABLE'};
    }
  }

  /// Every Codex profile folder the CLI on [machineId] can offer, merged with [observedPaths]
  /// (Codex homes already known from this same machine's other Codex agents). Runs entirely on that
  /// machine — this app never touches a filesystem itself, which is what makes it work for a remote
  /// machine too. Returns `{profiles: [{path, label}]}` or `{error}`.
  Future<Map<String, dynamic>> listCodexProfiles(
    String machineId, {
    Set<String> observedPaths = const {},
  }) async {
    final connection = _conn(machineId);
    try {
      return await connection.request(
        'codex_profiles_list',
        payload: {'observedPaths': observedPaths.toList()},
        timeout: const Duration(seconds: 10),
      );
    } catch (error) {
      return {'error': 'UNREACHABLE'};
    }
  }

  /// Links [path] as a Codex profile on [machineId], persisted there so it survives future
  /// requests. Returns `{profile: {path, label}}` or `{error}`.
  Future<Map<String, dynamic>> linkCodexProfile(
    String machineId,
    String path,
  ) async {
    final connection = _conn(machineId);
    try {
      return await connection.request(
        'codex_profile_link',
        payload: {'path': path},
        timeout: const Duration(seconds: 10),
      );
    } catch (error) {
      return {'error': 'UNREACHABLE'};
    }
  }

  Future<Map<String, dynamic>> listClaudeProfiles(
    String machineId, {
    Set<String> observedPaths = const {},
  }) async {
    try {
      return await _conn(machineId).request(
        'claude_profiles_list',
        payload: {'observedPaths': observedPaths.toList()},
        timeout: const Duration(seconds: 10),
      );
    } catch (error) {
      return {'error': 'UNREACHABLE'};
    }
  }

  final _addingClaude = <String>{};

  /// This computer's accounts its owner can offer to the Swarm or take back. Throws when it cannot
  /// tell, so the screen says so and never reads a failure as "no accounts".
  Future<List<SwarmAccount>> swarmAccounts(String machineId) async {
    if (stateOf(machineId)?.isLocalMachine != true) {
      throw StateError('not this computer');
    }
    final agents = stateOf(machineId)?.agents ?? const <Agent>[];
    return [
      for (final engine in const ['claude', 'codex'])
        ...await () async {
          final reply = engine == 'claude'
              ? await listClaudeProfiles(
                  machineId,
                  observedPaths: {for (final a in agents) ?a.claudeHome},
                )
              : await listCodexProfiles(
                  machineId,
                  observedPaths: {for (final a in agents) ?a.codexHome},
                );
          final rows = reply['profiles'];
          if (rows is! List) throw StateError('no list');
          return [
            for (final row in rows)
              if (row is Map &&
                  row['path'] is String &&
                  row['offered'] is bool &&
                  row['default'] != true)
                SwarmAccount(
                  engine: engine,
                  path: row['path'] as String,
                  label: row['label'] as String? ?? row['path'] as String,
                  offered: row['offered'] as bool,
                ),
          ];
        }(),
    ];
  }

  /// Offers an account of this computer to the Swarm, or takes it back. Null when done, or what to
  /// tell the owner.
  Future<String?> setAccountOffered(
    String machineId,
    String engine,
    String path,
    bool offered,
  ) async {
    if (stateOf(machineId)?.isLocalMachine != true) {
      return 'Accounts can be offered on their own computer only.';
    }
    String? code;
    try {
      final reply = await _conn(machineId).request(
        'swarm_account_offer',
        payload: {'engine': engine, 'path': path, 'offered': offered},
        timeout: const Duration(seconds: 10),
      );
      code = reply['error'] as String?;
    } on WsRequestFailure catch (failure) {
      code = failure.code;
    } catch (_) {
      code = 'UNREACHABLE';
    }
    return switch (code) {
      null => null,
      'NOT_FOUND' => 'That account’s folder is gone.',
      'UNSUPPORTED' ||
      'UNKNOWN_TYPE' => 'Update Harness on this computer to offer accounts.',
      'TOO_MANY' => 'Too many accounts are offered. Withdraw one first.',
      _ => 'Couldn’t reach this computer. Try again.',
    };
  }

  /// What `usage_read` last said per account, kept so opening the picker again does not call the vendors again.
  final _usageCache = <(String, String, String), ({DateTime at, int? left})>{};
  static const _usageFresh = Duration(minutes: 5);
  static const _usageReadsPerEngine = 8;

  /// Where Codex keeps the default account, which the picker names `'default'`.
  static String _codexDefaultHome() =>
      Platform.environment['CODEX_HOME'] ?? '${homeDir()}/.codex';

  /// The accounts [engine] runs under on [machineId], each with the share of its limit left when
  /// the machine can read it. Empty for any other engine or when the machine does not answer.
  Future<List<AgentProfile>> agentProfiles(
    String machineId,
    String engine,
  ) async {
    if (engine != 'claude' && engine != 'codex') return const [];
    // Profile requests are not sealed for the relay, so only this computer's own daemon is asked.
    if (stateOf(machineId)?.isLocalMachine != true) return const [];
    final observed = {
      for (final a in stateOf(machineId)?.agents ?? const <Agent>[])
        ?(engine == 'claude' ? a.claudeHome : a.codexHome),
    };
    final Map<String, dynamic> reply;
    try {
      reply = engine == 'claude'
          ? await listClaudeProfiles(machineId, observedPaths: observed)
          : await listCodexProfiles(machineId, observedPaths: observed);
    } catch (_) {
      return const [];
    }
    final rows = reply['profiles'];
    if (rows is! List) return const [];
    final defaultId = swarmProfileId(machineId, engine, 'default');
    final profiles = [
      for (final row in rows)
        if (row is Map && row['path'] is String)
          () {
            final path = row['path'] as String;
            final rowId = row['id'] as String?;
            // An old Claude CLI names its default account with the literal 'default'.
            final legacy = engine == 'claude' && rowId == 'default';
            // The CLI marks the default row; an old Codex CLI sends no flag, so its env folder is it.
            final isDefault =
                row['default'] == true ||
                legacy ||
                rowId == defaultId ||
                (engine == 'codex' &&
                    row['default'] == null &&
                    path == _codexDefaultHome());
            return (
              path: path,
              offered: row['offered'] != false,
              canOffer: row['offered'] is bool && !isDefault,
              label: row['label'] as String? ?? path,
              id: isDefault
                  ? defaultId
                  : (rowId ?? swarmProfileId(machineId, engine, path)),
              isDefault: isDefault,
              legacy: legacy,
            );
          }(),
    ];
    // One account has no choice to show, so its usage is not worth a vendor call.
    var budget = profiles.length > 1 ? _usageReadsPerEngine : 0;
    return Future.wait([
      for (final p in profiles)
        () async {
          final key = (machineId, engine, p.id);
          var cached = _usageCache[key];
          if ((cached == null ||
                  clock.now().difference(cached.at) >= _usageFresh) &&
              budget > 0) {
            budget--;
            int? left;
            try {
              // An old CLI does not know profile reads: its plain read answers both
              // engines' default accounts, so take the one for this engine.
              final usage = parseUsageReadResult(
                await _conn(machineId).request(
                  'usage_read',
                  payload: p.legacy
                      ? const {}
                      : {
                          'profile': {'engine': engine, 'id': p.id},
                        },
                  timeout: const Duration(seconds: 10),
                ),
              );
              final tightest =
                  (p.legacy
                          ? usage
                                .where((u) => u.provider.name == engine)
                                .firstOrNull
                          : usage.firstOrNull)
                      ?.tightest;
              if (tightest != null) {
                left = (100 - tightest.usedPercent).round().clamp(0, 100);
              }
            } catch (_) {}
            cached = _usageCache[key] = (at: clock.now(), left: left);
          }
          return AgentProfile(
            id: p.id,
            key: p.isDefault ? 'default' : p.path,
            label: p.label,
            path: p.path,
            percentLeft: cached?.left,
            offered: p.offered,
            canOffer: p.canOffer,
          );
        }(),
    ]);
  }

  /// Opens a Claude that is signed out in a new account folder beside the others on [machineId]:
  /// the picker lists it once the person has run /login there. A pane cannot be given an
  /// environment, so Claude is started with `claudeHome` instead of `CLAUDE_CONFIG_DIR`.
  Future<String?> addClaudeAccount(String machineId, String agentId) async {
    if (stateOf(machineId)?.isLocalMachine != true) {
      return 'A Claude account can be added on this computer only.';
    }
    final source = stateOf(machineId)?.agents
        .where((a) => a.id == agentId)
        .firstOrNull;
    final folder =
        source?.project?.cwd ??
        (source == null ? null : stateOf(machineId)?.projectOf(source)?.cwd);
    if (folder == null) {
      return 'This harness has no project folder to open Claude in.';
    }
    // One add at a time per machine: a second click would pick the same folder.
    if (!_addingClaude.add(machineId)) {
      return 'A Claude account is already being added.';
    }
    try {
      final listed = await listClaudeProfiles(machineId);
      final rows =
          (listed['profiles'] as List?)?.whereType<Map>().toList() ?? [];
      final home = rows.isEmpty ? null : rows.first['path'] as String?;
      if (home == null) return 'Could not reach this machine.';
      // A folder is free when the machine does not list it and no agent here runs in it.
      final taken = {
        for (final r in rows) r['path'],
        for (final a in stateOf(machineId)?.agents ?? const <Agent>[])
          a.claudeHome,
      };
      var n = 1;
      while (taken.contains('$home/.harness/claude-profiles/$n')) {
        n++;
      }
      final path = '$home/.harness/claude-profiles/$n';
      // The folder only exists once Claude has signed in there; the machine finds it by itself then.
      final error = await createAgent(
        machineId,
        engine: 'claude',
        folder: folder,
        claudeHome: path,
      );
      if (error == null) {
        agentChangeNotice?.call('Run /login, then pick it again');
      }
      return error;
    } finally {
      _addingClaude.remove(machineId);
    }
  }

  /// Starts an agent, or recovers this form's earlier request after a lost reply.
  /// Returns null on success, or an inline message; [attempt] tells the form
  /// whether to offer Check status instead of inviting another creation.
  Future<String> prepareLocalProjectFolder(
    ProjectFolderRequest request, {
    String label = 'harness',
  }) async {
    String? via;
    final folder = await request.prepareLocal(
      label: label,
      onClonedVia: (alias) => via = alias,
    );
    if (via case final alias?) rememberClonedVia(folder, alias);
    return folder;
  }

  @visibleForTesting
  void rememberClonedVia(String folder, String alias) =>
      _clonedViaFolders[folder] = alias;

  /// A folder this computer's own clone reached through an SSH alias, until
  /// its creation takes it. Kept by folder, it outlived a creation that failed,
  /// and a later start in that folder announced a clone it never made.
  final _clonedViaFolders = <String, String>{};

  /// The alias a machine's own clone went through (cli launches.ts
  /// `clonedVia`), when it names a safe one.
  static String? _clonedViaOf(Map<String, dynamic> result) {
    final via = result['clonedVia'];
    final alias = via is Map ? via['alias'] : null;
    return alias is String && isSafeSshAlias(alias) ? alias : null;
  }

  void _announceClonedVia(String? alias) {
    if (alias != null) agentChangeNotice?.call('Cloned via $alias');
  }

  Future<String?> createAgent(
    String machineId, {
    required String engine,

    /// Where the agent works. Null only for a terminal (`kTerminalEngine`),
    /// which the daemon then opens at the machine's home, as a terminal app
    /// would — every other engine is refused without one (`INVALID_CWD`).
    required String? folder,
    ProjectFolderRequest? projectFolder,
    bool bypassPermission = true,
    String? permissionMode,
    String? codexHome,
    String? claudeHome,
    String? dsh,
    String? swarmRole,
    String? swarmSkillMode,
    GridModel? model,
    String? prompt,
    String? name,
    String? agent,
    String? swarmId,
    PaneSplitRequest? split,
    AgentCreationAttempt? attempt,
    HarnessPlacement? placement,
  }) async {
    final creation = attempt ?? AgentCreationAttempt();
    final launch = creation._launchModelDropped ? null : creation.launchModel;
    final choices = <String, dynamic>{
      'engine': engine,
      if (projectFolder == null && folder != null) 'cwd': folder,
      ...?projectFolder?.payload,
      'bypassPermission': bypassPermission,
      // The mode picked in New Harness (`permission_modes.dart`). A daemon that
      // predates modes ignores it and goes by `bypassPermission`, which the
      // dialog derives from the same choice.
      'permissionMode': ?permissionMode,
      'codexHome': ?codexHome,
      'claudeHome': ?claudeHome,
      // The harness this agent is created from. `engine` above is its BASE —
      // the machine refuses the pair when they disagree (`INVALID_DSH`).
      'dsh': ?dsh,
      if (engine == 'claude' || engine == 'codex') ...{
        'swarmRole': ?swarmRole,
        'swarmSkillMode': ?swarmSkillMode,
      },
      'gridModel': ?model?.id,
      'gridName': ?model?.grid,
      'model': ?launch?.model,
      'effort': ?launch?.effort,
      // A first message the engine is opened with, and the pane's name before
      // the engine reports a session title. Both absent unless asked for: a
      // daemon that predates them ignores an unknown field, but one that knows
      // them refuses a prompt for an engine with no way to take one
      // (`PROMPT_UNSUPPORTED`), and an empty field would trip that for every
      // ordinary create.
      'prompt': ?prompt,
      'name': ?name,
      // The engine's own named agent to open AS (opencode `--agent <name>`):
      // the pane is that agent, with its name and system prompt, rather than
      // a general session. Same absent-unless-asked rule as `prompt`, and the
      // same refusal for an engine that has no such thing (`AGENT_UNSUPPORTED`).
      'agent': ?agent,
    };
    Future<String?> ask() => _create(
      machineId,
      choices,
      projectFolder: projectFolder,
      dsh: dsh,
      swarmId: swarmId,
      split: split,
      attempt: creation,
      placement: placement,
    );
    final answer = await _createFollowingHold(creation, creation.holdWait, ask);
    if (launch == null ||
        !_launchModelRefusals.contains(creation._refusal) ||
        _disposed) {
      return answer;
    }
    // Refused before any receipt: the same request, without them, so the
    // agent starts on its engine's own model rather than not at all.
    choices
      ..remove('model')
      ..remove('effort');
    creation._retryWithoutLaunchModel();
    return _createFollowingHold(creation, creation.holdWait, ask);
  }

  /// A machine's refusals of a launch model, made before anything launched.
  static const _launchModelRefusals = {
    'LAUNCH_MODEL_UNSUPPORTED',
    'INVALID_LAUNCH_MODEL',
  };

  /// How often a harness the machine holds or is starting is asked after
  /// ([_createFollowingHold]): the pace `harness new` asks at.
  @visibleForTesting
  Duration heldCreationInterval = const Duration(seconds: 2);

  /// How long a harness the machine has begun starting is asked after, from
  /// when it is first seen starting, before the create answers that it is
  /// still starting ([AgentCreationAttempt._starting]). A worktree from main
  /// took 13 s on the office Mac (2026-10-14); a minute covers that several
  /// times over. A form waiting on the create stays busy (it cannot be closed)
  /// for that long at most.
  @visibleForTesting
  Duration startingCreationWait = const Duration(minutes: 1);

  /// A create that waits out a hold. The machine starts a held harness by
  /// itself (an engine it is installing, a model waking) and answers `pending`
  /// meanwhile; [ask] again reads what became of that same request, never
  /// starts a second. Asked every [heldCreationInterval] until the harness is
  /// made, refused or cancelled, or [holdWait] has passed, when the hold's own
  /// words are the answer as they are without this. A null [holdWait] answers
  /// a hold at once, for a form whose person reads it and may cancel.
  ///
  /// For a caller nobody is watching. The first workspace on a new computer
  /// asked once, while setup was still downloading the agents, was told
  /// "Installing OpenCode. The harness starts once it is installed.", and
  /// opened nothing: the three harnesses then started with no pane anywhere
  /// (desktop 1.2.65 with CLI 0.3.77, a fresh Ubuntu VM, 2026-10-12).
  ///
  /// A harness the machine is already starting is asked after for every
  /// caller, for up to [startingCreationWait]: there is nothing to read or
  /// cancel, only a wait. The machine answers `pending` five seconds into a
  /// create, and a worktree from main took 13 s, so every such New Harness
  /// said "office is still starting your harness. Check again in a moment."
  /// in red and opened nothing until Check status was pressed (2026-10-14).
  Future<String?> _createFollowingHold(
    AgentCreationAttempt creation,
    Duration? holdWait,
    Future<String?> Function() ask,
  ) async {
    final began = DateTime.now();
    DateTime? starting;
    // What an earlier call was told is not this one's to follow: a call that
    // ends before reaching the machine (its choices changed) would otherwise
    // wait out the whole start without asking anything.
    creation._starting = false;
    var answer = await ask();
    while (!_disposed && !creation._finished) {
      final now = DateTime.now();
      final bool follow;
      if (creation._starting) {
        // From when it was first seen starting: a hold before it (an install
        // on a new computer) does not use up the start's own wait.
        final since = starting ??= now;
        follow = now.difference(since) < startingCreationWait;
      } else {
        follow =
            holdWait != null &&
            creation.canCancelPending &&
            now.difference(began) < holdWait;
      }
      if (!follow) break;
      await Future<void>.delayed(heldCreationInterval);
      if (_disposed || creation._finished) break;
      answer = await ask();
    }
    return answer;
  }

  /// A cloud harness (CLI services/cloud.ts): made by the machine's cloud
  /// service at its maker, opened in a pane as any new harness is. Null when it
  /// started; otherwise what to tell the person ("Add your Devin API key…").
  Future<String?> createCloudHarness(
    String machineId, {
    required String engine,
    required String prompt,
    String? repositoryUrl,
    int? acuLimit,
    String? swarmId,
    PaneSplitRequest? split,
    HarnessPlacement? placement,
  }) => _create(
    machineId,
    {
      'engine': engine,
      'prompt': prompt,
      'repositoryUrl': ?repositoryUrl,
      'acuLimit': ?acuLimit,
    },
    swarmId: swarmId,
    split: split,
    placement: placement,
  );

  /// How long, from its start, a create waits for its agent's download beside setup
  /// ([agentPrefetch]). OpenCode took 7–12 s in the VM runs, Codex and Claude Code (one npm, after
  /// setup's Node) 25 s more; on a slow network the wait is the download's, since a pane that stopped
  /// waiting would start a second npm install into the same prefix. Ten minutes bounds a download
  /// that hangs.
  @visibleForTesting
  Duration agentPrefetchWait = const Duration(minutes: 10);

  /// A Claude Code or Codex conversation Harness did not start, opened as a
  /// harness that resumes it, in its own folder (Cmd-P, `ExternalSessionRef`).
  /// The machine refuses one open elsewhere, already a harness, or whose folder
  /// is gone, and says why. Null when it started; otherwise what to tell the
  /// person.
  /// Opens a conversation Harness did not start as a new harness. One open in
  /// a terminal is refused unless [takeOver] says how to take it over from
  /// there; the refusal's code says whether that terminal is mid-turn.
  Future<({String? error, String? refusal})> resumeConversation(
    String machineId, {
    required String engine,
    required String folder,
    required String sessionId,
    String? name,
    String? swarmId,
    HarnessPlacement? placement,
    TakeOver? takeOver,
    AgentCreationAttempt? attempt,
  }) async {
    final creation = attempt ?? AgentCreationAttempt();
    final error = await _create(
      machineId,
      {
        'engine': engine,
        'cwd': folder,
        'bypassPermission': true,
        'name': ?name,
        'resumeSessionId': sessionId,
        'takeOver': ?takeOver?.name,
      },
      swarmId: swarmId,
      placement: placement,
      attempt: creation,
    );
    return (error: error, refusal: error == null ? null : creation.refusal);
  }

  Future<String?> _create(
    String machineId,
    Map<String, dynamic> choices, {
    ProjectFolderRequest? projectFolder,
    String? dsh,
    String? swarmId,
    PaneSplitRequest? split,
    AgentCreationAttempt? attempt,
    HarnessPlacement? placement,
  }) {
    final creation = attempt ?? AgentCreationAttempt();
    if (creation._choices != null &&
        (creation._machineId != machineId ||
            creation._projectFolder?.isGenerated !=
                projectFolder?.isGenerated ||
            !mapEquals(creation._choices, choices))) {
      return Future.value(
        'Check the original request before changing its choices.',
      );
    }
    if (creation._finished) return Future.value(creation._outcome);
    if (creation._inFlight case final inFlight?) return inFlight;
    if (creation._choices == null) {
      var targetId = split?.swarmId ?? swarmId ?? activeSwarmId;
      // A harness gets a tab of its own, named after it: its viewer is the
      // product and needs the width, and the two tiles read as one workspace
      // rather than two more tiles in whatever tab was open. A New Tab
      // start page the user is already on IS that tab. A split was asked for
      // by name and wins; so does a tab other than the current one. The
      // current tab is what the dialog passes when nothing was chosen.
      if (!creation.background &&
          dsh != null &&
          placement == null &&
          split == null &&
          (swarmId == null || swarmId == activeSwarmId)) {
        final label = engineIdentity(dsh).label;
        if (activeSwarm.isEmptyStarter) {
          renameSwarm(activeSwarmId, label);
        } else {
          newSwarm(name: label);
        }
        targetId = activeSwarmId;
      }
      creation._choices = choices;
      creation._projectFolder = projectFolder;
      creation._machineId = machineId;
      creation._targetId = targetId;
      creation._split = split;
      creation._placement = placement;
    }
    _activeAgentCreations.add(creation);
    final work = _createAgentWithReceipt(creation);
    creation._inFlight = work;
    return work.whenComplete(() {
      creation._inFlight = null;
      if (!creation.awaitingConfirmation) {
        _activeAgentCreations.remove(creation);
      }
    });
  }

  String? _creationPlacementError(
    String targetId,
    PaneSplitRequest? split, {
    HarnessPlacement? placement,
  }) {
    if (placement == HarnessPlacement.newTab) return null;
    if (split != null && !isPaneSplitCurrent(split)) {
      return 'The layout changed. Close this dialog and split the pane again.';
    }
    final target = swarms.where((s) => s.id == targetId).firstOrNull;
    if (target == null) return 'This tab was closed';
    if (placement != null && (target.isUtility || target.isOrchestrator)) {
      return 'Open a new tab to add a harness.';
    }
    if (target.panes.length >= maxPanes) {
      return 'This tab is full. Open a new tab to start a harness.';
    }
    return null;
  }

  String _creationFailureMessage(
    String code,
    String? detail,
    String machine,
  ) => switch (code) {
    'INVALID_PROJECT_SOURCE' ||
    'INVALID_REPOSITORY' ||
    'PROJECT_PREPARATION_FAILED' ||
    'PROJECT_EXISTS' ||
    'CLONE_FAILED' ||
    'CLONE_TIMEOUT' ||
    'GIT_PROJECT_UNAVAILABLE' ||
    'INVALID_BRANCH' ||
    'BRANCH_SWITCH_FAILED' ||
    'WORKTREE_FAILED' ||
    'GIT_UNAVAILABLE' =>
      detail ?? 'Could not prepare the project folder on $machine.',
    'CWD_NOT_FOUND' || 'INVALID_CWD' =>
      'The project folder is unavailable on $machine. '
          'Choose another folder and try again.',
    'TMUX_UNAVAILABLE' =>
      'Harness needs tmux to start harnesses on $machine. '
          'Install tmux there, then try again.',
    // Windows: the terminal service (the pty host) did not answer. Its own
    // reason is written for the log; the person needs the one fix.
    'PTY_HOST_UNAVAILABLE' =>
      'Harness could not open a terminal on $machine. '
          'Run harness start on that computer, then try again.',
    // Refused before any pane opened, in words the machine wrote for the
    // person (an engine Windows cannot start as asked).
    'ENGINE_LAUNCH_REFUSED' =>
      detail != null && detail.isNotEmpty
          ? detail
          : 'This engine cannot start on $machine. Nothing was started.',
    'CODEX_CLI_TOO_OLD' =>
      detail ??
          'The installed Codex CLI on $machine is too old for Auto approvals. '
              'Update Codex, or choose Ask permissions.',
    'UNSUPPORTED_ON_REMOTE' || 'UNSUPPORTED' =>
      'Update the harness CLI on this machine to start a harness',
    'INVALID_DSH' =>
      'This harness is not installed on $machine. '
          '${detail ?? 'Install it there, then try again.'}',
    'PROMPT_UNSUPPORTED' =>
      'This engine cannot be opened with a first message on $machine.',
    'PROMPT_TOO_LONG' =>
      'This first task is too long for $machine. Shorten it and try again.',
    'AGENT_UNSUPPORTED' =>
      'This engine cannot be opened as a named agent on $machine.',
    'INVALID_AGENT' =>
      'This engine cannot be opened as that named agent on $machine.',
    'INVALID_PERMISSION_MODE' =>
      'This engine has no such permission mode on $machine.',
    // Opening a conversation Harness did not start (`resumeSessionId`). The
    // machine says what stopped it: open elsewhere, already a harness, gone.
    'SESSION_OPEN_ELSEWHERE' ||
    'SESSION_IN_HARNESS' ||
    'SESSION_NOT_FOUND' ||
    'SESSION_FOLDER_GONE' ||
    'SESSION_OPEN_IN_TERMINAL' ||
    'SESSION_BUSY_IN_TERMINAL' ||
    'SESSION_STOP_FAILED' ||
    'INVALID_SESSION' =>
      detail ?? 'Could not open that conversation on $machine.',
    // A daemon that predates the terminal engine refuses it by name; the
    // fix is the same one the other UNSUPPORTED codes ask for.
    'INVALID_ENGINE' =>
      'Update the harness CLI on $machine to open this kind of pane.',
    // A guest's harness: its owner turns guest access on, and only Claude Code or Codex start.
    'GUEST_NOT_ALLOWED' =>
      'You can only start Claude Code or Codex on $machine.',
    'GUEST_UNSUPPORTED' ||
    'GUEST_HELPER_REQUIRED' ||
    'GUEST_UNAVAILABLE' ||
    'GUEST_ENGINE_UNSUPPORTED' ||
    'GUEST_INVALID' ||
    'GUEST_HELPER_MISSING' ||
    'GUEST_HELPER_NOT_AUTHORIZED' ||
    'GUEST_RELAY_FAILED' => detail ?? 'Could not start a harness on $machine.',
    _ => 'Could not start harness: ${detail ?? code}',
  };

  /// A typed new project's name that [folder] on [machine] already has. The
  /// machine's own words ("Select that folder from your projects") left
  /// nothing to press: PROJECT_EXISTS was 4 of 7 failed starts on Oct 18, all
  /// from the apps. The form offers "Use the existing folder" beside this.
  String _projectExistsMessage(String folder, String machine) {
    final name = folder
        .split(RegExp(r'[\\/]'))
        .lastWhere((part) => part.isNotEmpty, orElse: () => folder);
    return '“$name” already exists on $machine. '
        'Choose another name, or use the existing folder.';
  }

  /// A confirmed name collision happens before any process starts. Only then
  /// may an automatic suggestion advance to another name with a fresh receipt.
  /// Uncertain replies always keep their original receipt and never retry.
  Future<String?> _retryGeneratedProject(AgentCreationAttempt creation) {
    final project = creation._projectFolder!;
    creation._remoteProjectName = project.nextGeneratedName(
      creation._remoteProjectName ?? project.folderName!,
    );
    creation._projectNameRetries++;
    creation._id = _newCreationId();
    creation._awaitingConfirmation = false;
    return _createAgentWithReceipt(creation);
  }

  /// Cancellation is confirmed by the machine's durable receipt. Losing this
  /// reply cannot turn the original request into a fresh creation attempt.
  Future<String?> cancelAgentCreation(AgentCreationAttempt creation) async {
    if (!creation.canCancelPending ||
        creation._cancelling ||
        creation._inFlight != null) {
      return 'Check the request status before cancelling.';
    }
    final machineId = creation._machineId;
    if (machineId == null || !machineStates.containsKey(machineId)) {
      return 'The original machine is unavailable. The request is still saved.';
    }
    creation._cancelling = true;
    try {
      final result = await _conn(machineId).request(
        'agent_create_cancel',
        payload: {'creationId': creation._id},
        timeout: const Duration(seconds: 10),
      );
      if (result['creationId'] == creation._id &&
          result['state'] == 'cancelled') {
        creation._complete('Creation cancelled.');
        _activeAgentCreations.remove(creation);
        await _discardCancelledWorktree(creation);
        return null;
      }
      return 'The request may already be starting. Check status before starting another.';
    } catch (_) {
      return 'Cancellation is not confirmed. Check status before starting another.';
    } finally {
      creation._cancelling = false;
    }
  }

  /// Takes back the worktree this computer made for [creation], once its
  /// cancel is confirmed and nothing will start in it. Kept, it held its
  /// branch, and the next press was refused for that name (desktop 1.3.41,
  /// 2026-10-30). One it cannot take back stays and is logged: the cancel
  /// itself is done either way.
  Future<void> _discardCancelledWorktree(AgentCreationAttempt creation) async {
    final made = creation._worktreeMadeHere;
    if (made == null) return;
    creation._worktreeMadeHere = null;
    if (creation._preparedFolder == made.folder)
      creation._preparedFolder = null;
    try {
      if (!await discardLocalWorktree(
        made.folder,
        keepBranch: made.keepBranch,
      )) {
        appLog.info('worktree', 'kept after cancel: ${made.folder}');
      }
    } catch (error) {
      appLog.warn(
        'worktree',
        'not removed after cancel: ${made.folder}',
        error: error,
      );
    }
  }

  /// The local half of [_discardCancelledWorktree]; a test's seam, as
  /// [prepareLocalProjectFolder] is.
  Future<bool> discardLocalWorktree(String folder, {bool keepBranch = false}) =>
      discardPreparedWorktree(folder, keepBranch: keepBranch);

  Future<String?> _createAgentWithReceipt(AgentCreationAttempt creation) async {
    // Only this answer says whether it is starting; one that never reaches
    // the machine (it went offline) must not be followed as if it were.
    creation._starting = false;
    creation._existingFolder = null;
    final machineId = creation._machineId!;
    var targetId = creation._targetId!;
    final split = creation._split;
    final placement = creation._placement;
    final choices = creation._choices!;
    final machine = machineStates[machineId];
    if (machine == null) return 'Machine not found';
    final machineName = machine.machine.displayName;
    // A status check must remain possible even if the destination closed or a
    // capability probe changed while the first create was already in flight.
    if (!creation.awaitingConfirmation) {
      final placementError = creation.background
          ? null
          : _creationPlacementError(targetId, split, placement: placement);
      if (placementError != null) return placementError;
      if (choices['claudeHome'] != null && choices['engine'] != 'claude') {
        return 'Choose a Claude account only for Claude';
      }
      if (choices['codexHome'] != null) {
        if (choices['engine'] != 'codex') {
          return 'Choose a Codex profile only for Codex';
        }
        if (!creation._codexHomeTrusted &&
            machine.engines['codex']?.supportsCodexHome != true) {
          return 'Update the harness CLI on this machine to choose a Codex profile';
        }
      }
    }
    // Nothing to dial with before sign-in finishes (`_finishBootstrapSignedIn`
    // makes the pool) — a shortcut that fires in that window, such as ⌘⇧T, is
    // answered rather than crashed on.
    if (_pool == null && connectionForTest == null) {
      return 'Not connected to $machineName yet.';
    }
    final connection = _conn(machineId);
    if (!creation.awaitingConfirmation && choices['gridModel'] != null) {
      final models = await refreshGridModels(machineId);
      if (!models.reachable) {
        return creation._complete(
          'Could not verify models on $machineName. Refresh models or use your subscription.',
        );
      }
      if (!models.supportsModelLaunch) {
        return creation._complete(
          'Update Harness CLI on $machineName to choose a model before starting.',
        );
      }
      if (!models.canRunLocally(choices['engine'] as String) ||
          !models.sections.any(
            (section) =>
                section.name == choices['gridName'] &&
                section.models.any((model) => model.id == choices['gridModel']),
          )) {
        return creation._complete(
          'The selected model is unavailable. Refresh models or use your subscription.',
        );
      }
    }
    var launchChoices = choices;
    if (!creation.awaitingConfirmation &&
        choices['projectSource'] != null &&
        machine.isLocalMachine) {
      try {
        final repository = choices['repositoryUrl'];
        final projectName = choices['projectName'];
        final project =
            creation._projectFolder ??
            (repository is String
                ? ProjectFolderRequest.remote(
                    GitHubRepository.parse(repository)!,
                  )
                : ProjectFolderRequest.newProject(
                    name: projectName is String ? projectName : null,
                  ));
        final dshId = choices['dsh'];
        final preparedBefore = creation._preparedFolder;
        creation._preparedFolder ??= await prepareLocalProjectFolder(
          project,
          // The folder is named after who the harness is: the harness's own name, else the engine's.
          label: dshId is String && dshId.isNotEmpty
              ? (machine.dsh.entries
                        .where((entry) => entry.id == dshId)
                        .firstOrNull
                        ?.name ??
                    engineIdentity(dshId).label)
              : engineIdentity(choices['engine'] as String?).label,
        );
        if (preparedBefore == null) {
          creation._clonedVia = _clonedViaFolders.remove(
            creation._preparedFolder,
          );
        }
        if (preparedBefore == null && project.createsWorktree) {
          creation._worktreeMadeHere = (
            folder: creation._preparedFolder!,
            keepBranch: project.existingBranch,
          );
        }
      } on ProjectExistsException catch (error) {
        // This computer's own folder refuses a typed name as the machine
        // does, so the form offers the folder the same way.
        creation._refusal = 'PROJECT_EXISTS';
        if (error.folder case final folder?) {
          creation._existingFolder = folder;
          return creation._complete(_projectExistsMessage(folder, machineName));
        }
        return creation._complete(error.message);
      } on RepositoryCloneException catch (error) {
        return creation._complete(error.message);
      } catch (_) {
        return creation._complete(
          'Could not prepare the project folder. Browse for an existing folder.',
        );
      }
      // Preparation may be slow. Revalidate before starting a process, using
      // the original machine and split rather than the current selection.
      final placementError = creation.background
          ? null
          : _creationPlacementError(targetId, split, placement: placement);
      if (placementError != null) return creation._complete(placementError);
      if (_disposed ||
          machineStates[machineId] != machine ||
          !machine.isLocalMachine) {
        return creation._complete(
          'The selected machine changed. Choose the machine again.',
        );
      }
      launchChoices = Map.of(choices)
        ..remove('projectSource')
        ..remove('repositoryUrl')
        ..remove('projectName')
        ..remove('gitSource')
        ..remove('branchRef')
        ..['cwd'] = creation._preparedFolder;
    }
    if (!machine.isLocalMachine && creation._remoteProjectName != null) {
      launchChoices = {...choices, 'projectName': creation._remoteProjectName};
    }
    final canAdvanceProject =
        !machine.isLocalMachine &&
        creation._projectFolder?.isGenerated == true &&
        creation._projectNameRetries < 64;
    // An agent still downloading beside setup ([AgentPrefetch]): the pane would start a second install
    // of it. Waited for here, once the creation is registered (its tab and split are held), and only
    // for what is left of [agentPrefetchWait] since that download began. A CLI whose pane waits for
    // the download itself shows it in the pane instead, once the pane can see it.
    final prefetchedEngine = choices['engine'];
    if (!creation.awaitingConfirmation &&
        prefetchedEngine is String &&
        machine.isLocalMachine) {
      final download = agentPrefetch?.waitFor(
        prefetchedEngine,
        agentPrefetchWait,
        paneWaits: machine.engines[prefetchedEngine]?.waitsForDownload == true,
      );
      if (download != null) {
        await download;
        final moved = creation.background
            ? null
            : _creationPlacementError(targetId, split, placement: placement);
        if (moved != null) return creation._complete(moved);
        if (_disposed || machineStates[machineId] != machine) {
          return creation._complete(
            'The selected machine changed. Choose the machine again.',
          );
        }
      }
    }
    final operation = creation.awaitingConfirmation
        ? 'agent_create_status'
        : 'agent_create';
    final unconfirmed =
        '$machineName has not confirmed the new harness yet. '
        'Check status before starting another.';
    Map<String, dynamic> result;
    creation._awaitingConfirmation = true;
    try {
      if (operation == 'agent_create_status') {
        result = await connection.request(
          operation,
          payload: {'creationId': creation._id},
          timeout: const Duration(seconds: 10),
        );
        if (result['creationId'] != creation._id) return unconfirmed;
      } else {
        if (creation.beforeSubmit case final prepare?) {
          try {
            await prepare(machineId, creation._id);
          } catch (failure) {
            // The native request has not been sent. A failed local journal write
            // must leave the form editable instead of waiting on a nonexistent receipt.
            return creation._complete(
              'Could not save the launch request: $failure',
            );
          }
        }
        result = await connection.request(
          operation,
          payload: {...launchChoices, 'creationId': creation._id},
          timeout: const Duration(seconds: 20),
        );
      }
    } on WsRequestFailure catch (failure) {
      if (operation == 'agent_create' &&
          failure.code == 'PROJECT_EXISTS' &&
          canAdvanceProject) {
        return _retryGeneratedProject(creation);
      }
      if (operation == 'agent_create_status') {
        if (failure.code == 'UNSUPPORTED' ||
            failure.code == 'UNSUPPORTED_ON_REMOTE' ||
            failure.code == 'E2EE_REQUIRED') {
          return '$machineName cannot check this creation. '
              'Use Open Harness to look for it before starting another.';
        }
        return unconfirmed;
      }
      // Refusals that happen before a launch are safe to correct. INTERNAL,
      // spawn timeouts and connection failures cannot prove nothing started.
      const refusedBeforeLaunch = {
        ..._launchModelRefusals,
        'INVALID_PROJECT_SOURCE',
        'INVALID_REPOSITORY',
        'PROJECT_EXISTS',
        'CWD_NOT_FOUND',
        'INVALID_CWD',
        'INVALID_ENGINE',
        'INVALID_GRID',
        'GRID_UNAVAILABLE',
        'INVALID_CODEX_HOME',
        'INVALID_DSH',
        'PROMPT_UNSUPPORTED',
        'PROMPT_TOO_LONG',
        'INVALID_PROMPT',
        'AGENT_UNSUPPORTED',
        'INVALID_AGENT',
        'INVALID_PERMISSION_MODE',
        'TMUX_UNAVAILABLE',
        'PTY_HOST_UNAVAILABLE',
        'ENGINE_LAUNCH_REFUSED',
        'CODEX_CLI_TOO_OLD',
        'TMUX_TOO_OLD_FOR_GRID',
        'GRID_CONFIG_FAILED',
        'UNSUPPORTED_ON_REMOTE',
        'UNSUPPORTED',
        // A conversation Harness did not start, refused before its pane opens.
        'SESSION_OPEN_ELSEWHERE',
        'SESSION_IN_HARNESS',
        'SESSION_NOT_FOUND',
        'SESSION_FOLDER_GONE',
        'SESSION_OPEN_IN_TERMINAL',
        'SESSION_BUSY_IN_TERMINAL',
        'SESSION_STOP_FAILED',
        'INVALID_SESSION',
        // A guest on a machine shared with this account, refused before anything starts
        // (docs/plans/2026-10-19-guest-machine-sharing-plan.md).
        'GUEST_NOT_ALLOWED',
        'GUEST_UNSUPPORTED',
        'GUEST_HELPER_REQUIRED',
        'GUEST_UNAVAILABLE',
        'GUEST_ENGINE_UNSUPPORTED',
        'GUEST_INVALID',
        'GUEST_HELPER_MISSING',
        'GUEST_HELPER_NOT_AUTHORIZED',
        'GUEST_RELAY_FAILED',
      };
      // A cloud agent's service refuses in words a person reads ("Add your
      // Devin API key…"), and a retry of the same New Harness gets the same
      // harness (its `creationId`), so none of these is left unconfirmed.
      const cloudRefusals = {
        'NOT_CONNECTED',
        'INVALID_REQUEST',
        'CONNECTIONS_UNAVAILABLE',
        'CLOUD_FAILED',
        'BUSY',
        'RATE_LIMITED',
        'UNREACHABLE',
        'SERVICE_UNAVAILABLE',
      };
      final cloudRefusal =
          isCloudAgentId(choices['engine'] as String?) &&
          cloudRefusals.contains(failure.code);
      if (cloudRefusal) {
        creation._refusal = failure.code;
        return creation._complete(failure.detail ?? 'Could not start it.');
      }
      if (refusedBeforeLaunch.contains(failure.code)) {
        creation._refusal = failure.code;
        if (failure.code == 'INVALID_CWD' && choices['projectSource'] != null) {
          return creation._complete(
            'Update Harness CLI on $machineName to create or clone project folders. Local can open an existing folder.',
          );
        }
        return creation._complete(
          _creationFailureMessage(failure.code, failure.detail, machineName),
        );
      }
      return unconfirmed;
    } catch (_) {
      // Includes disconnects, malformed replies and timeouts. A transport error
      // is not evidence that the machine did not execute the request.
      return unconfirmed;
    }
    if ((result.containsKey('creationId') || result['state'] != null) &&
        result['creationId'] != creation._id) {
      return unconfirmed;
    }
    switch (result['state']) {
      case 'missing':
        // An old CLI may have created the agent before being updated to a
        // receipt-aware version. Missing is not proof that nothing started.
        // Check status stays read-only, even across upgrades and reconnects.
        return '$machineName has no record of this request. '
            'Use Open Harness to look for it before starting another.';
      case 'pending':
        final held = result['held'];
        if (held is Map) {
          final detail = held['detail'];
          if (detail is String && detail.isNotEmpty) {
            creation._holdReason = detail;
            return detail;
          }
        }
        creation._holdReason = null;
        // Nothing held: the machine has claimed the request and is starting
        // the harness now (making its worktree, opening its pane).
        creation._starting = held == null;
        return '$machineName is still starting your harness. Check again in a moment.';
      case 'cancelled':
        return creation._complete('Creation cancelled.');
      case 'unconfirmed':
        return '$machineName could not confirm whether this harness started. '
            'Use New Pane to look for it before starting another.';
      case 'unavailable':
        return creation._complete(
          'This harness started but is no longer available. '
          'You can start a new one.',
        );
      case 'failed':
        final failure = result['failure'];
        if (failure is! Map || failure['code'] is! String) return unconfirmed;
        if (failure['code'] == 'PROJECT_EXISTS' &&
            result['preparedFolder'] == null &&
            canAdvanceProject) {
          return _retryGeneratedProject(creation);
        }
        if (result['preparedFolder'] case final String folder
            when folder.isNotEmpty) {
          creation._preparedFolder = folder;
        }
        creation._refusal = failure['code'] as String;
        // A typed name the machine found already there, as a folder it can
        // open (CLI `existingFolder`): said so, and offered to the person.
        if (failure['existingFolder'] case final String folder
            when failure['code'] == 'PROJECT_EXISTS' &&
                (folder.startsWith('/') ||
                    RegExp(r'^[A-Za-z]:[\\/]').hasMatch(folder) ||
                    folder.startsWith(r'\\'))) {
          creation._existingFolder = folder;
          return creation._complete(_projectExistsMessage(folder, machineName));
        }
        // Every way that machine has to GitHub was refused (cli launches.ts
        // `access`): one short line, in the app's words, names the repository.
        final denied = failure['access'] == 'denied'
            ? GitHubRepository.parse('${choices['repositoryUrl'] ?? ''}')
            : null;
        if (denied != null) {
          return creation._complete(
            'No access to ${denied.slug} on $machineName.',
          );
        }
        return creation._complete(
          _creationFailureMessage(
            failure['code'] as String,
            failure['detail'] is String ? failure['detail'] as String : null,
            machineName,
          ),
        );
      case 'created':
      case null: // A successful first response from a CLI predating receipts.
        break;
      default:
        return unconfirmed;
    }
    final raw = result['agent'];
    if (raw is! Map || raw['id'] is! String || (raw['id'] as String).isEmpty) {
      return unconfirmed;
    }
    final Agent agent;
    try {
      agent = Agent.fromJson(Map<String, dynamic>.from(raw));
    } catch (_) {
      return unconfirmed;
    }
    creation._complete(null);
    if (_disposed || machineStates[machineId] != machine) return null;
    creation._agentId = agent.id;
    _announceClonedVia(creation._clonedVia ?? _clonedViaOf(result));
    creation._clonedVia = null;
    if (choices['prompt'] case final String prompt
        when prompt.trim().isNotEmpty) {
      _firstMessages[(machineId, agent.id)] = prompt;
    }
    _upsertAgent(machine, agent);
    // Apply each creation receipt once, even if its transport result is replayed.
    // A Git start remembers its repository, never the worktree it made.
    final projectPath =
        choices['gitSource'] ??
        agent.project?.cwd ??
        creation.preparedFolder ??
        choices['cwd'];
    if (!creation.background &&
        !isInternalLaunchHarness(agent.dsh ?? choices['dsh'] as String?) &&
        projectPath is String &&
        projectPath.isNotEmpty) {
      unawaited(projectHistory.select(machineId, projectPath, launched: true));
    }
    harnessStats.onAgentSpawned();
    notifyListeners();
    if (creation.background) return null;
    if (_creationPlacementError(targetId, split, placement: placement) !=
        null) {
      _lastError =
          'The harness started, but its original tab or layout changed. '
          'Use New Pane to find it.';
      _lastErrorRetryable = false;
      notifyListeners();
      return null;
    }
    // Do not allocate a tab while the picker, form, or request is pending.
    // Failed and unconfirmed requests leave the original layout intact.
    if (placement == HarnessPlacement.newTab) {
      newSwarm();
      targetId = activeSwarmId;
    }
    await assignAgentToPane(
      null,
      machineId,
      agent.id,
      swarmId: targetId,
      split: split,
      autoTile: placement != null,
      intent: AttachIntent.person,
    );
    return null;
  }

  _MachineEdit? _pendingMachineEdit(String machineId) {
    final edit = _machineEdits[machineId];
    return edit != null && _machineWorkCurrent(edit.machine, edit.authRevision)
        ? edit
        : null;
  }

  Future<String?>? pendingMachineRename(String machineId) {
    final edit = _pendingMachineEdit(machineId);
    return edit?.name != null ? edit!.result.future : null;
  }

  String? pendingMachineName(String machineId) =>
      _pendingMachineEdit(machineId)?.name;

  Future<String?>? pendingMachineDelete(String machineId) {
    final edit = _pendingMachineEdit(machineId);
    return edit != null && edit.name == null ? edit.result.future : null;
  }

  /// Machine names belong to the account. Requests survive their prompt and
  /// apply only to the machine identity/auth session that initiated them.
  Future<String?> renameMachine(String machineId, String name) =>
      _editMachine(machineId, name: name.trim());

  /// Deletes the machine from the account and closes its views in this window.
  /// This is separate from removing this computer's outgoing trust pin.
  Future<String?> deleteMachine(String machineId) => _editMachine(machineId);

  Future<String?> _editMachine(String machineId, {String? name}) {
    if (_disposed) return Future.value('This request is no longer active.');
    final machine = machineStates[machineId];
    if (machine == null) return Future.value('Machine not found');
    if (machine.machine.isShared) {
      return Future.value('Shared machines are view-only.');
    }
    if (machine.machine.isSharedMachine) {
      return Future.value('Only its owner can rename or remove this machine.');
    }
    if (name == null && machine.isLocalMachine) {
      return Future.value('This computer cannot be deleted here.');
    }
    if (name != null && name.isEmpty) {
      return Future.value('Name cannot be empty');
    }
    if (_pendingMachineEdit(machineId) case final edit?) {
      if (edit.name == name) return edit.result.future;
      return Future.value('A change to this machine is already in progress.');
    }
    if (name == machine.machine.displayName) return Future.value();
    final edit = _MachineEdit(machine, _authRevision, name);
    _machineEdits[machineId] = edit;
    notifyListeners();
    unawaited(_runMachineEdit(machineId, edit));
    return edit.result.future;
  }

  Future<void> _runMachineEdit(String machineId, _MachineEdit edit) async {
    String? error;
    try {
      if (edit.name case final name?) {
        final savedName = await api.renameMachine(
          machineId: machineId,
          name: name,
        );
        if (!_machineWorkCurrent(edit.machine, edit.authRevision)) {
          error = 'The machine changed while saving. Refresh and try again.';
          return;
        }
        edit.machine.machine = edit.machine.machine.copyWith(
          name: savedName?.trim().isNotEmpty == true ? savedName!.trim() : name,
        );
        final index = machines.indexWhere(
          (machine) => machine.machineId == machineId,
        );
        if (index != -1) machines[index] = edit.machine.machine;
        _confirmedMachineEdits[machineId] = (
          ++_machineEditRevision,
          edit.machine.machine.displayName,
        );
      } else {
        await api.deleteMachine(machineId: machineId);
        if (!_machineWorkCurrent(edit.machine, edit.authRevision)) {
          error = 'The machine changed while deleting. Refresh to check its status.';
          return;
        }
        final closing = <Future<void>>[];
        for (final pane in panesFor(machineId).toList()) {
          for (final swarm in swarms) {
            swarm.remove(pane);
          }
          closing.add(_detachSession(pane, sendClose: true));
        }
        _clearMachineActivity(edit.machine);
        _stopOfflineRetry(machineId);
        _stopLinkRetry(machineId);
        _stopAgentSyncTimer(machineId);
        machineStates.remove(machineId);
        machines.removeWhere((machine) => machine.machineId == machineId);
        _confirmedMachineEdits[machineId] = (++_machineEditRevision, null);
        if (selectedMachineId == machineId) selectedMachineId = null;
        _persistLayout();
        if (_pool case final pool?) closing.add(pool.closeMachine(machineId));
        notifyListeners();
        // Deletion is committed. A failed stream close must not offer another
        // destructive account request; sessions still dispose in finally.
        try {
          await Future.wait(closing);
        } catch (failure) {
          appLog.warn(
            'machines',
            'Machine deleted; closing its local views failed: $failure',
          );
        }
      }
    } catch (failure) {
      error = failure is ApiException
          ? '${edit.name == null ? 'Delete' : 'Rename'} failed: ${failure.message}'
          : 'Could not ${edit.name == null ? 'delete' : 'rename'} the machine. Try again.';
    } finally {
      if (identical(_machineEdits[machineId], edit)) {
        _machineEdits.remove(machineId);
      }
      edit.result.complete(error);
      if (_authWorkCurrent(edit.authRevision)) notifyListeners();
    }
  }

  bool _agentRenameCurrent(_AgentRename request) =>
      identical(
        _agentRenames[(request.machine.machine.machineId, request.agent.id)],
        request,
      ) &&
      _machineWorkCurrent(request.machine, request.authRevision) &&
      request.machine.agents.any(
        (agent) =>
            agent.id == request.agent.id &&
            agent.sessionId == request.agent.sessionId,
      );

  _AgentRename? _pendingAgentRename(String machineId, String agentId) {
    final request = _agentRenames[(machineId, agentId)];
    return request != null && _agentRenameCurrent(request) ? request : null;
  }

  Future<String?>? pendingAgentRename(String machineId, String agentId) =>
      _pendingAgentRename(machineId, agentId)?.result.future;

  String? pendingAgentName(String machineId, String agentId) =>
      _pendingAgentRename(machineId, agentId)?.name;

  /// Renames survive their editor. A second view joins the same request and a
  /// late reply cannot rename a replacement machine or agent session.
  Future<String?> renameAgent(String machineId, String agentId, String name) {
    if (_disposed) return Future.value('This request is no longer active.');
    final machine = machineStates[machineId];
    if (machine == null) return Future.value('Machine not found');
    final trimmed = name.trim();
    if (trimmed.isEmpty) return Future.value('Name cannot be empty');
    if (machine.machine.isShared) {
      return Future.value('Shared harnesses are view-only.');
    }
    if (pendingAgentStop(machineId, agentId) != null) {
      return Future.value('The harness is stopping.');
    }
    final agent = machine.agents
        .where((agent) => agent.id == agentId)
        .firstOrNull;
    if (agent == null) return Future.value('Harness not found');
    if (_pendingAgentRename(machineId, agentId) case final pending?) {
      if (pending.name == trimmed) return pending.result.future;
      return Future.value('A rename is already in progress for this harness.');
    }
    if (agent.name == trimmed) return Future.value();
    final request = _AgentRename(machine, agent, _authRevision, trimmed);
    _agentRenames[(machineId, agentId)] = request;
    notifyListeners();
    unawaited(_runAgentRename(request));
    return request.result.future;
  }

  Future<void> _runAgentRename(_AgentRename request) async {
    String? error;
    final machineId = request.machine.machine.machineId;
    final agentId = request.agent.id;
    try {
      final result = await _conn(machineId).request(
        'agent_update',
        payload: {'agentId': agentId, 'name': request.name},
      );
      if (!_agentRenameCurrent(request)) {
        error = 'The harness changed while saving. Refresh and try again.';
        return;
      }
      if (result['error'] case final String code) {
        final detail = result['detail'];
        error =
            'Rename failed: ${detail is String && detail.isNotEmpty ? detail : code}';
        return;
      }
      final returned = result['agent'];
      final rawName = returned is Map ? returned['name'] : null;
      final name = rawName is String && rawName.trim().isNotEmpty
          ? rawName.trim()
          : request.name;
      final observed = request.machine._agentNames[agentId];
      if (observed != null &&
          observed.revision > request.nameRevision &&
          observed.name != name) {
        error =
            'The name changed to “${observed.name}” while saving. Check it before retrying.';
        return;
      }
      _renameAgent(request.machine, agentId, name);
      // The Swarms that hold this harness show its agent by their own name:
      // the rename reaches everyone's sidebar (task #2912).
      try {
        final swarmErrors = await superTabs.renameHarnessAgent(
          machineId,
          agentId,
          name,
        );
        if (swarmErrors.isNotEmpty) {
          error =
              'Renamed here, but the Swarm kept the old name: ${swarmErrors.first}';
        }
      } catch (_) {
        // The harness is renamed; only the Swarm could not be reached.
        error =
            'Renamed here, but could not reach the Swarm to rename it there.';
      }
    } catch (failure) {
      error = failure is WsRequestTimeout
          ? 'Could not confirm the rename. Refresh harnesses to check the name.'
          : 'Could not rename the harness. Try again.';
    } finally {
      if (identical(_agentRenames[(machineId, agentId)], request)) {
        _agentRenames.remove((machineId, agentId));
      }
      request.result.complete(error);
      if (_authWorkCurrent(request.authRevision)) notifyListeners();
    }
  }

  /// How long a second open of the SAME harness, with no other harness
  /// opened in between, folds into the first. Only the same one: A, B, A in
  /// quick succession is three opens, or the order would say B was last.
  static const agentTouchDebounce = Duration(seconds: 3);

  ({String machineId, String agentId, DateTime at})? _lastAgentTouch;

  /// The harness the focus last stamped, so the grid's pointer-down — every
  /// click inside the tile already in front re-focuses it — is not an open.
  (String, String)? _touchedFocus;

  /// Tell a harness's own daemon that a person just opened or focused it, so
  /// its `lastOpenedAt` records the visit in every client
  /// (`agent_update {agentId, opened: true}`, sealed like any agent_update).
  ///
  /// Fire-and-forget. Nothing waits on it and nothing is said when it fails:
  /// an older daemon answers MISSING_UPDATE; a socket that is down loses one
  /// stamp. Conversation recency is independent of this. Never dials a socket
  /// for it, and never for a view-only shared harness — its owner's order is
  /// not this window's to move.
  void touchAgent(String machineId, String agentId) {
    if (_disposed) return;
    final machine = machineStates[machineId];
    if (machine == null ||
        machine.machine.isShared ||
        machine.needsLink ||
        machine.nodeOnline == false ||
        machine.connectionStatus != ConnectionStatus.connected ||
        (_pool == null && connectionForTest == null)) {
      return;
    }
    final now = DateTime.now();
    final last = _lastAgentTouch;
    final queuedClose = machine.agents.any(
      (a) => a.id == agentId && a.closePlanState != null,
    );
    if (!queuedClose &&
        !_closingViewAgents.containsKey((machineId, agentId)) &&
        last != null &&
        last.machineId == machineId &&
        last.agentId == agentId &&
        now.difference(last.at) < agentTouchDebounce) {
      return;
    }
    _lastAgentTouch = (machineId: machineId, agentId: agentId, at: now);
    unawaited(_sendAgentTouch(machine, agentId));
  }

  Future<void> _sendAgentTouch(MachineState machine, String agentId) async {
    final revision = _authRevision;
    try {
      final result = await _conn(machine.machine.machineId).request(
        'agent_update',
        payload: {'agentId': agentId, 'opened': true},
        timeout: const Duration(seconds: 10),
      );
      if (!_machineWorkCurrent(machine, revision)) return;
      // The daemon's own visit stamp, taken now rather than on the next push. Only
      // this one field: the reply is not a frame to rebuild the agent from.
      final returned = result['agent'];
      final raw = returned is Map && (returned['id'] ?? agentId) == agentId
          ? returned['lastOpenedAt']
          : null;
      final opened = raw is String ? DateTime.tryParse(raw) : null;
      if (opened == null) return;
      final index = machine.agents.indexWhere((a) => a.id == agentId);
      if (index == -1) return;
      final current = machine.agents[index];
      final known = current.lastOpenedAt;
      if (known != null && !opened.isAfter(known)) return;
      machine.agents = [...machine.agents]
        ..[index] = current.copyWith(lastOpenedAt: opened);
      notifyListeners();
    } catch (_) {
      // MISSING_UPDATE from an older daemon, a timeout, a dropped socket: the
      // stamp is a courtesy to the ordering, never worth an error band.
    }
  }

  /// Stamp the harness now in front, when it is a different one from the
  /// last stamped — see [touchAgent]. A viewer is its agent's, as in
  /// [_announceAppFocus].
  void _touchFocusedAgent() {
    final pane = focusedPane;
    final agentId = pane?.agentId ?? pane?.ownerAgentId;
    final focus = agentId == null ? null : (pane!.machineId, agentId);
    if (focus == _touchedFocus) return;
    _touchedFocus = focus;
    if (focus != null) touchAgent(focus.$1, focus.$2);
  }

  bool _agentStopCurrent(_AgentStop request) {
    if (!identical(
      _agentStops[(request.machine.machine.machineId, request.agent.id)],
      request,
    )) {
      return false;
    }
    if (!_machineWorkCurrent(request.machine, request.authRevision)) {
      return false;
    }
    final current = request.machine.agents
        .where((agent) => agent.id == request.agent.id)
        .firstOrNull;
    return request.confirmed ||
        current == null ||
        current.sessionId == request.agent.sessionId;
  }

  Future<String?>? pendingAgentStop(String machineId, String agentId) {
    final request = _agentStops[(machineId, agentId)];
    return request != null &&
            !request.confirmed &&
            !request.result.isCompleted &&
            _agentStopCurrent(request)
        ? request.result.future
        : null;
  }

  Future<String?>? pendingAgentPause(String machineId, String agentId) =>
      _agentPauses[(machineId, agentId)];

  /// Keep confirmed paused work visible even if its subsequent inventory refresh
  /// fails or the manager is dismissed. The daemon remains the durable authority.
  Future<String?> pauseAgent(String machineId, String agentId) {
    final key = (machineId, agentId);
    if (_agentPauses[key] case final pending?) return pending;
    final machine = stateOf(machineId);
    final agent = machine?.agents.where((a) => a.id == agentId).firstOrNull;
    if (machine == null || agent == null || !agent.canPauseAndResume) {
      return Future.value(
        'This harness has no supported saved conversation to open.',
      );
    }
    if (agent.isStopped) return Future.value(null);
    final revision = _authRevision;
    late final Future<String?> pause;
    pause =
        (() async {
          final error = await deleteAgent(machineId, agentId);
          if (!_machineWorkCurrent(machine, revision)) return error;
          final current = machine.agents
              .where((a) => a.id == agentId)
              .firstOrNull;
          if (error == null && current == null) {
            _upsertAgent(
              machine,
              agent.copyWith(status: 'stopped', terminalAvailable: false),
            );
            notifyListeners();
          }
          await reloadMachineData(machineId);
          if (!_machineWorkCurrent(machine, revision)) return error;
          final observed = machine.agents
              .where((a) => a.id == agentId)
              .firstOrNull;
          // A lost reply is resolved by authoritative inventory, never by resending Stop.
          if (observed?.isStopped == true &&
              observed?.sessionId == agent.sessionId) {
            return null;
          }
          return error;
        })().whenComplete(() {
          if (identical(_agentPauses[key], pause)) _agentPauses.remove(key);
          if (_authWorkCurrent(revision)) notifyListeners();
        });
    _agentPauses[key] = pause;
    return pause;
  }

  /// Stops the process through the CLI, retaining project files and history.
  /// The request outlives its confirmation and is shared by every view.
  ///
  /// Confirmation prompts use [prepareAgentStop] to retain the identity shown
  /// when they opened, before the person has confirmed the action.
  Future<String?> deleteAgent(String machineId, String agentId) {
    if (_disposed) return Future.value('This request is no longer active.');
    final machine = machineStates[machineId];
    if (machine == null) return Future.value('Machine not found');
    if (machine.machine.isShared) {
      return Future.value('Shared harnesses are view-only.');
    }
    if (pendingAgentStop(machineId, agentId) case final pending?) {
      return pending;
    }
    final agent = machine.agents
        .where((agent) => agent.id == agentId)
        .firstOrNull;
    if (agent == null) {
      return Future.value(
        'The harness is no longer listed. Refresh to check its status.',
      );
    }
    final request = _AgentStop(machine, agent, _authRevision);
    machine._agentStopRevisions[agentId] = ++machine._agentRevision;
    _agentStops[(machineId, agentId)] = request;
    notifyListeners();
    unawaited(_runAgentStop(request));
    return request.result.future;
  }

  /// Captures the confirmation's target without sending a request. A changed
  /// session, removed/recreated ID, replacement machine, or new login while the
  /// prompt is open must not turn its Stop button into an action on another agent.
  Future<String?> Function() prepareAgentStop(
    String machineId,
    String agentId,
  ) {
    final machine = machineStates[machineId];
    final agent = machine?.agents
        .where((agent) => agent.id == agentId)
        .firstOrNull;
    final authRevision = _authRevision;
    final removal = machine?._agentRemovals[agentId];
    return () {
      final current = machineStates[machineId]?.agents
          .where((agent) => agent.id == agentId)
          .firstOrNull;
      if (machine == null ||
          agent == null ||
          !_machineWorkCurrent(machine, authRevision) ||
          machine._agentRemovals[agentId] != removal ||
          current == null ||
          current.sessionId != agent.sessionId) {
        return Future.value(
          'The harness changed. Close this prompt and check it before stopping.',
        );
      }
      return deleteAgent(machineId, agentId);
    };
  }

  Future<void> _runAgentStop(_AgentStop request) async {
    String? error;
    final machineId = request.machine.machine.machineId;
    final agentId = request.agent.id;
    try {
      final result = await _conn(machineId)
          .request('agent_delete', payload: {'agentId': agentId});
      if (request.confirmed) return;
      if (!_agentStopCurrent(request)) {
        error =
            'The harness changed while stopping. Refresh to check its status.';
        return;
      }
      if (result['error'] case final String code) {
        final detail = result['detail'];
        error =
            'Stop failed: ${detail is String && detail.isNotEmpty ? detail : code}';
        return;
      }
      if (result['deleted'] != true) {
        error = 'Could not confirm the pause. Refresh to check its status.';
        return;
      }
      await _removeAgent(request.machine, agentId);
    } catch (failure) {
      if (!request.confirmed) {
        error = switch (failure) {
          WsRequestFailure(:final code, :final detail) =>
            'Stop failed: ${detail != null && detail.isNotEmpty ? detail : code}',
          WsRequestTimeout() => 'Could not confirm the stop. Refresh harnesses to check its status.',
          _ => 'Could not stop the harness. Try again.',
        };
      }
    } finally {
      if (identical(_agentStops[(machineId, agentId)], request)) {
        _agentStops.remove((machineId, agentId));
      }
      if (!request.result.isCompleted) request.result.complete(error);
      if (_authWorkCurrent(request.authRevision)) notifyListeners();
    }
  }

  /// Delete Harness: unlike Stop, which keeps the conversation to reopen, this
  /// stops a running harness and deletes its saved conversation for good, so it
  /// leaves Open Harness too. The daemon's reviewed deletion (`agent_purge`):
  /// reviewed first, then deleted under that review. Project files and
  /// worktrees are kept. Null on success, or a message for the prompt.
  Future<String?> purgeAgent(String machineId, String agentId) async {
    final machine = machineStates[machineId];
    final agent = machine?.agents
        .where((agent) => agent.id == agentId)
        .firstOrNull;
    final createdAt = agent?.createdAt;
    if (machine == null || agent == null || createdAt == null) {
      return 'This harness is no longer listed. Refresh and try again.';
    }
    final sessionId = agent.sessionId;
    final target = {
      'agentId': agentId,
      'sessionId': sessionId == null || sessionId.isEmpty ? null : sessionId,
      'createdAt': createdAt.millisecondsSinceEpoch,
    };
    String refused(Object? code, Object? detail) =>
        'Delete failed: ${detail is String && detail.isNotEmpty ? detail : code}';
    try {
      final review = await _conn(machineId).request(
        'agent_purge',
        payload: {...target, 'mode': 'inspect'},
        timeout: const Duration(seconds: 30),
      );
      if (review['error'] != null) {
        return refused(review['error'], review['detail']);
      }
      final reviewId = review['reviewId'];
      if (reviewId is! String)
        return 'Could not review this harness for deletion.';
      final result = await _conn(machineId).request(
        'agent_purge',
        payload: {...target, 'mode': 'delete', 'reviewId': reviewId},
        timeout: const Duration(seconds: 60),
      );
      if (result['error'] != null) {
        return refused(result['error'], result['detail']);
      }
      if (result['deleted'] != true) {
        return 'Could not confirm the deletion. Refresh harnesses to check.';
      }
    } on WsRequestFailure catch (failure) {
      return refused(failure.code, failure.detail);
    } on WsRequestTimeout {
      return 'Could not confirm the deletion. Refresh harnesses to check.';
    } catch (_) {
      return 'Could not delete the harness. Try again.';
    }
    await _removeAgent(machine, agentId);
    unawaited(_loadMachineData(machine, force: true));
    notifyListeners();
    return null;
  }

  bool _restartCurrent(AgentRestartAttempt attempt, {bool beforeSend = false}) {
    final machine = attempt._machine;
    final agent = attempt.agent;
    if (machine == null ||
        agent == null ||
        !_machineWorkCurrent(machine, attempt._authRevision) ||
        machine._agentRemovals[agent.id] != attempt._removal ||
        machine._agentStopRevisions[agent.id] != attempt._stopRevision) {
      return false;
    }
    final current = machine.agents
        .where((item) => item.id == agent.id)
        .firstOrNull;
    return current != null &&
        (!beforeSend || current.sessionId == agent.sessionId);
  }

  /// [fresh] starts a new intent with its own receipt, even while an earlier attempt is pending or
  /// awaiting confirmation; the earlier one keeps running on its own object.
  AgentRestartAttempt restartAttempt(
    String machineId,
    String agentId, {
    bool fresh = false,
  }) {
    final previous = _agentRestarts[(machineId, agentId)];
    if (!fresh &&
        previous != null &&
        _restartCurrent(
          previous,
          beforeSend: !previous.busy && !previous.awaitingConfirmation,
        )) {
      return previous;
    }
    final machine = machineStates[machineId];
    return _agentRestarts[(machineId, agentId)] = AgentRestartAttempt._(
      machine,
      machine?.agents.where((agent) => agent.id == agentId).firstOrNull,
      _authRevision,
    );
  }

  bool discardRestartAttempt(
    String machineId,
    String agentId,
    AgentRestartAttempt attempt,
  ) {
    if (attempt.busy ||
        !identical(_agentRestarts[(machineId, agentId)], attempt)) {
      return false;
    }
    _agentRestarts.remove((machineId, agentId));
    return true;
  }

  AgentRestartAttempt? pendingAgentRestart(String machineId, String agentId) =>
      _agentRestarts[(machineId, agentId)];

  /// Resume a stopped session's own conversation and wait for its terminal: null once it is up, or when
  /// the session was not stopped; otherwise why not. ⌘P opens a stopped session this way, and ⌘B sends to
  /// one, so both wait alike and fail alike.
  Future<String?> resumeStoppedSession(String machineId, String agentId) async {
    final agent = stateOf(machineId)?.agents
        .where((agent) => agent.id == agentId)
        .firstOrNull;
    if (agent?.isStopped != true) return null;
    final machine = stateOf(machineId);
    final terminalReady = Completer<void>();
    void observeRuntime() {
      if (terminalReady.isCompleted ||
          !identical(machine, stateOf(machineId)) ||
          pendingAgentStop(machineId, agentId) != null) {
        return;
      }
      final current = stateOf(machineId)?.agents
          .where((row) => row.id == agentId)
          .firstOrNull;
      // This opens a view of the allocated terminal, not a claim that history
      // has loaded. The native CLI may need login or hook review before it can
      // confirm the conversation; the receipt keeps verifying in the background.
      //
      // The conversation has to be the one asked for — unless none was: a resume
      // that was always going to open a new one (an engine with no resume argv, a
      // harness paused with nothing recorded) reports a different id because it
      // did as it was told, and the tile it opened is still this harness's.
      final fresh =
          agent?.resumesFreshConversation == true ||
          current?.resumesFreshConversation == true;
      if (current?.terminalAvailable == true &&
          (fresh || current?.sessionId == agent!.sessionId) &&
          current?.launchState != 'failed' &&
          current?.isStopped == false) {
        terminalReady.complete();
      }
    }

    addListener(observeRuntime);
    try {
      final confirmed = resumeAgent(
        machineId,
        agentId,
      ).then((result) => result.error);
      observeRuntime();
      return await Future.any<String?>([
        confirmed,
        terminalReady.future.then((_) => null),
      ]);
    } finally {
      removeListener(observeRuntime);
    }
  }

  /// Attach to a running harness or resume its saved conversation immediately.
  Future<RestartAgentResult> resumeAgent(String machineId, String agentId) {
    if (stateOf(machineId)?.machine.isSharedMachine == true) {
      return Future.value(
        const RestartAgentResult(
          error: 'On a computer shared with you, harnesses can’t be restarted, resumed or forked. Start a new one.',
          retryable: false,
        ),
      );
    }
    if (pendingAgentPause(machineId, agentId) != null) {
      return Future.value(
        const RestartAgentResult(
          error: 'The harness is still stopping. Try again in a moment.',
        ),
      );
    }
    final agent = stateOf(machineId)?.agents
        .where((agent) => agent.id == agentId)
        .firstOrNull;
    if (agent?.terminalAvailable == true) {
      return Future.value(const RestartAgentResult());
    }
    if (agent?.isStopped != true) {
      return Future.value(
        const RestartAgentResult(
          error: 'The saved harness is no longer available. Search again.',
          retryable: false,
        ),
      );
    }
    // Resume shares the receipt coordinator, while sending its own lifecycle
    // command. Repeated Enter checks the existing intent instead of relaunching.
    return restartAgent(machineId, agentId);
  }

  /// Restart keeps the agent, every view and the current focus. Only explicit
  /// new intent can repeat a request whose outcome is still unknown.
  Future<RestartAgentResult> restartAgent(
    String machineId,
    String agentId, {
    AgentRestartAttempt? attempt,
    String? launchArgs,
  }) {
    final operation = attempt ?? restartAttempt(machineId, agentId);
    if (operation.result case final result? when result.error == null) {
      return Future.value(result);
    }
    if (operation.pending case final pending?) return pending;
    late final Future<RestartAgentResult> request;
    request = _runAgentRestart(machineId, agentId, operation, launchArgs)
        .then((result) {
          operation.result = result;
          return result;
        })
        .whenComplete(() {
          if (identical(operation._pending, request)) operation._pending = null;
          if (_authWorkCurrent(operation._authRevision)) notifyListeners();
        });
    operation._pending = request;
    return request;
  }

  Future<RestartAgentResult> _runAgentRestart(
    String machineId,
    String agentId,
    AgentRestartAttempt attempt,
    String? launchArgs,
  ) async {
    final machine = attempt._machine;
    if (machine == null) {
      return const RestartAgentResult(
        error: 'Machine not found',
        retryable: false,
      );
    }
    if (machine.machine.isShared) {
      return const RestartAgentResult(
        error: 'Shared harnesses are view-only.',
        retryable: false,
      );
    }
    // Relaunched, a guest's harness would run the owner's way, as the owner: the daemon refuses it.
    if (machine.machine.isSharedMachine) {
      return const RestartAgentResult(
        error: 'On a computer shared with you, harnesses can’t be restarted, resumed or forked. Start a new one.',
        retryable: false,
      );
    }
    if (pendingAgentStop(machineId, agentId) != null) {
      return const RestartAgentResult(
        error: 'The harness is stopping.',
        retryable: false,
      );
    }
    if (machine.machine.machineId != machineId ||
        attempt.agent?.id != agentId ||
        !_restartCurrent(attempt, beforeSend: !attempt.awaitingConfirmation)) {
      return const RestartAgentResult(
        error: 'The harness changed. Close this prompt and check it before restarting.',
        retryable: false,
      );
    }
    final resuming = attempt.agent?.isStopped == true;
    if (resuming && machine.connectionStatus != ConnectionStatus.connected) {
      final connected = await connectTrusted(machineId);
      if (!_restartCurrent(
        attempt,
        beforeSend: !attempt.awaitingConfirmation,
      )) {
        return const RestartAgentResult(
          error: 'The harness changed while connecting. Select it again.',
          retryable: false,
        );
      }
      if (!connected) {
        return RestartAgentResult(
          error: machine.needsLink
              ? 'Connect this computer in Machines, then open the saved harness again.'
              : 'This computer is not connected. Bring it online and try again. Your saved conversation is kept.',
        );
      }
    }
    var checking = attempt.awaitingConfirmation;
    if (!checking) {
      attempt._id = _newCreationId();
      attempt._startedRevision = machine._agentRevision;
    }
    attempt._awaitingConfirmation = true;
    final measurementKey = _turnActivityKey(machineId, agentId);
    if (resuming &&
        !checking &&
        productMeasurement.healthEnabled &&
        productMeasurement.sharing) {
      if (_measurementResumes.length >= 64) {
        productMeasurement.health(ProductHealthMeasure.observationOverflow);
        _measurementResumes
            .remove(_measurementResumes.keys.first)
            ?.call(ProductOutcome.unknown);
      }
      _measurementResumes
          .remove(measurementKey)
          ?.call(ProductOutcome.cancelled);
      _measurementResumes[measurementKey] = productMeasurement.begin(
        ProductFlow.resumeRecovery,
      );
    }
    final sendsLaunchArgs = launchArgs != null && !checking;
    RestartAgentResult refused(String code, Object? detail) {
      attempt._awaitingConfirmation = false;
      if (resuming && code == 'AGENT_BUSY') {
        final live = machine.agents.where((a) => a.id == agentId).firstOrNull;
        if (live?.terminalAvailable == true &&
            live?.sessionId == attempt.agent?.sessionId &&
            live?.launchState != 'failed' &&
            live?.launchState != 'starting') {
          _agentRestarts.remove((machineId, agentId));
          return const RestartAgentResult();
        }
      }
      _measurementResumes.remove(measurementKey)?.call(ProductOutcome.failed);
      return RestartAgentResult(
        error: _restartFailure(code, detail, resuming: resuming),
        launchArgsRefused: code == 'INVALID_LAUNCH_ARGS',
      );
    }

    final unknown = RestartAgentResult(
      error: resuming
          ? 'Still waiting for the Open response. Select the harness again to check status.'
          : 'The restart is not confirmed yet. Check status, or close this prompt to inspect the terminal before restarting again.',
    );
    final notStarted = RestartAgentResult(
      error: unknown.error,
      engineNotStarted: true,
    );
    Map<String, dynamic> result;
    try {
      result = await _conn(machineId).request(
        checking
            ? 'agent_create_status'
            : resuming
            ? 'agent_resume'
            : 'agent_restart',
        payload: {
          'creationId': attempt._id,
          if (!checking) 'agentId': agentId,
          if (sendsLaunchArgs) 'launchArgs': launchArgs,
        },
      );
      if (checking &&
          resuming &&
          result['creationId'] == attempt._id &&
          result['state'] == 'missing' &&
          result['error'] == null &&
          _restartCurrent(attempt)) {
        // The original resume may never have reached the daemon. Checking a
        // missing receipt forever cannot recover it. Replay the SAME intent:
        // the daemon reserves it before launching, so a delayed original or
        // another retry cannot allocate a second terminal.
        checking = false;
        result = await _conn(machineId).request(
          'agent_resume',
          payload: {
            'creationId': attempt._id,
            'agentId': agentId,
            'launchArgs': ?launchArgs,
          },
        );
      }
    } on WsRequestFailure catch (failure) {
      // Refusals travel as exceptions in WsConn, not successful reply maps.
      // Treating every exception as a lost reply left a rejected resume on
      // "Check status" forever, hiding both its cause and the retry action.
      result = {
        ...failure.payload,
        'error': failure.code,
        'detail': ?failure.detail,
      };
    } catch (_) {
      return unknown;
    }
    if (!_restartCurrent(attempt)) {
      return const RestartAgentResult(
        error:
            'The harness changed while restarting. Check its current status.',
        retryable: false,
      );
    }
    if ((checking ||
            result.containsKey('creationId') ||
            result.containsKey('state')) &&
        result['creationId'] != attempt._id) {
      return unknown;
    }
    if (result['error'] case final String code) {
      if (code == 'RESTART_FAILED' || code == 'RESUME_UNCONFIRMED') {
        return notStarted;
      }
      if (checking || ['INTERNAL', 'CREATION_STORAGE_FAILED'].contains(code)) {
        return unknown;
      }
      return refused(code, result['detail']);
    }
    switch (result['state']) {
      case 'pending':
        return RestartAgentResult(
          error: resuming
              ? 'The machine is still resuming the harness. Select it again in a moment.'
              : 'The machine is still restarting the harness. Check again in a moment.',
        );
      case 'missing':
        return unknown;
      case 'unconfirmed':
        return notStarted;
      case 'unavailable':
        attempt._awaitingConfirmation = false;
        return const RestartAgentResult(
          error: 'The restarted harness is no longer available. Close this prompt and check current harnesses.',
          retryable: false,
        );
      case 'failed':
        final failure = result['failure'];
        if (failure is! Map || failure['code'] is! String) return unknown;
        return refused(failure['code'] as String, failure['detail']);
      case 'created':
      case null:
        break;
      default:
        return unknown;
    }
    final raw = result['agent'];
    // Older daemons can acknowledge a restart without an agent projection.
    if (raw != null || result['state'] == 'created') {
      if (raw is! Map || raw['id'] != agentId) return unknown;
      try {
        var updated = Agent.fromJson(Map<String, dynamic>.from(raw));
        // A resume that says it opened a NEW conversation is only a surprise
        // where an old one was promised. An engine with no resume argv, or a
        // harness paused before anything recorded a conversation, comes back as
        // a new one BECAUSE that is what it was asked for — and the button said
        // so beforehand — so the receipt is honoured rather than read as a
        // failure that leaves the row stuck.
        final fresh =
            attempt.agent!.resumesFreshConversation ||
            updated.resumesFreshConversation;
        if (resuming &&
            ((result['resumed'] == false && !fresh) ||
                (updated.sessionId != attempt.agent!.sessionId && !fresh) ||
                updated.launchState == 'starting' ||
                updated.launchState == 'failed')) {
          return unknown;
        }
        final current = machine.agents
            .where((agent) => agent.id == agentId)
            .first;
        // A newer observed session wins over the receipt of an older restart.
        if (current.sessionId == attempt.agent!.sessionId ||
            current.sessionId == updated.sessionId) {
          updated = _preserveNewerName(
            machine,
            updated,
            attempt._startedRevision,
          );
          final name = machine._agentNames[agentId];
          if (name != null &&
              name.revision > attempt._startedRevision &&
              name.sessionId == current.sessionId) {
            updated = updated.copyWith(name: name.name);
          }
          _upsertAgent(machine, updated);
        }
      } catch (_) {
        return unknown;
      }
    } else if (resuming || !result.containsKey('resumed')) {
      return unknown;
    }
    machine._agentRestartRevisions[agentId] = ++machine._agentRevision;
    if (resuming) machine.resumedHarnesses++;
    attempt._awaitingConfirmation = false;
    if (identical(_agentRestarts[(machineId, agentId)], attempt)) {
      _agentRestarts.remove((machineId, agentId));
    }
    return RestartAgentResult(
      resumed: result['resumed'] is bool ? result['resumed'] as bool : true,
      // Only a fresh restart is echoed; a status check never carries the words.
      launchArgsIgnored: sendsLaunchArgs && result['launchArgs'] == null,
    );
  }

  String _restartFailure(
    String code,
    Object? detail, {
    bool resuming = false,
  }) => code == 'PTY_HOST_UNAVAILABLE'
      // Its detail is written for the log.
      ? 'Harness could not open a terminal on this machine. Run harness start on it, then try again.'
      : detail is String &&
            detail.isNotEmpty &&
            !const {
              'IDENTITY_UNAVAILABLE',
              'CWD_NOT_FOUND',
              'SESSION_FOLDER_GONE',
              'GRID_CREDENTIAL_REQUIRED',
              'ENGINE_NOT_INSTALLED',
              'ENGINE_UNAVAILABLE',
            }.contains(code)
      ? detail
      : switch (code) {
          'ENGINE_LAUNCH_REFUSED' =>
            resuming
                ? 'This engine cannot start on this machine. Nothing was started.'
                : 'This engine cannot start on this machine. Nothing was stopped.',
          'UNSUPPORTED_ON_REMOTE' || 'UNSUPPORTED' =>
            resuming
                ? 'Update the harness CLI on this machine to open saved harnesses.'
                : 'Update the harness CLI on this machine to restart a harness.',
          'AGENT_BUSY' => 'Another operation is changing this harness. Wait for it to finish, then retry.',
          'RESUME_UNAVAILABLE' => 'The saved conversation is unavailable. The harness can still be started fresh.',
          'RESUME_SESSION_MISMATCH' => 'The harness came back on a different conversation. The saved one is still kept.',
          'RESUME_FAILED' => 'The harness did not come back. Its output and conversation are kept.',
          'IDENTITY_UNAVAILABLE' => 'The saved conversation could not be verified. Check that its agent account and project are still available, then retry. You can also start a new harness; the saved one is kept.',
          'CWD_NOT_FOUND' || 'SESSION_FOLDER_GONE' => 'The project folder is unavailable. Restore it, then retry, or start a new harness in another folder.',
          'GRID_CREDENTIAL_REQUIRED' => 'Reconnect the model provider in Models, then retry. Your saved conversation is kept.',
          'ENGINE_NOT_INSTALLED' || 'ENGINE_UNAVAILABLE' =>
            'Install this agent on the computer, then retry.',
          _ =>
            resuming
                ? 'Could not open this harness: $code'
                : 'Restart failed: $code',
        };

  bool _forkSourceCurrent(AgentForkAttempt attempt) {
    final machine = attempt._machine;
    final source = attempt.source;
    if (machine == null ||
        source == null ||
        !_machineWorkCurrent(machine, attempt._authRevision) ||
        machine._agentRemovals[source.id] != attempt._removal) {
      return false;
    }
    final current = machine.agents
        .where((agent) => agent.id == source.id)
        .firstOrNull;
    return current != null && current.sessionId == source.sessionId;
  }

  AgentForkAttempt forkAttempt(
    String machineId,
    String agentId, {
    String name = '',
    String prompt = '',
  }) {
    final existing = _agentForks[(machineId, agentId)];
    if (existing != null &&
        (_forkSourceCurrent(existing) ||
            (existing.locked &&
                existing._machine != null &&
                _machineWorkCurrent(
                  existing._machine,
                  existing._authRevision,
                )))) {
      return existing;
    }
    final machine = machineStates[machineId];
    final source = machine?.agents
        .where((agent) => agent.id == agentId)
        .firstOrNull;
    return _agentForks[(machineId, agentId)] = AgentForkAttempt._(
      machine,
      source,
      _authRevision,
      machine?._agentRemovals[agentId],
      name: name,
      prompt: prompt,
    );
  }

  /// Only an explicit New fork action may abandon an unconfirmed receipt.
  bool discardForkAttempt(
    String machineId,
    String agentId,
    AgentForkAttempt attempt,
  ) {
    if (attempt.busy ||
        !identical(_agentForks[(machineId, agentId)], attempt)) {
      return false;
    }
    _agentForks.remove((machineId, agentId));
    return true;
  }

  /// Clone (⌘⇧N): another agent of the same kind as [agentId], with a fresh
  /// conversation — fork minus the context. Same machine (its own or a relayed
  /// one: `agent_create` takes the same road either way), same project folder,
  /// same engine or harness, Codex profile, named agent and permission mode,
  /// every one read off the agent's own frame. Nothing of the source is
  /// touched — no session to bind, so a clone works while the source is busy
  /// or has no session yet, where a fork would wait or refuse.
  ///
  /// A daemon from before the frame carried the launch choices reports them
  /// null; the clone then opens the way New Harness would by default — auto
  /// mode, no named agent — while folder, harness and profile still carry. So
  /// does an agent Harness did not launch.
  ///
  /// Returns null once the agent exists, else the sentence to show. A terminal
  /// pane clones to a terminal in the same folder, exactly what ⌘⇧T opens; the
  /// daemon names those itself.
  Future<String?> cloneAgent(
    String machineId,
    String agentId, {
    String? swarmId,
  }) {
    final machine = machineStates[machineId];
    if (machine == null) return Future.value('Machine not found');
    if (machine.machine.isShared) {
      return Future.value('Shared harnesses are view-only.');
    }
    final source = machine.agents
        .where((agent) => agent.id == agentId)
        .firstOrNull;
    if (source == null) {
      return Future.value('The source harness is no longer available.');
    }
    final engine = source.engine;
    if (engine == null) {
      return Future.value('${source.displayName} has no engine to clone.');
    }
    if (!source.canClone) {
      return Future.value(
        '${source.displayName} runs on a grid; cloning a grid harness is not supported.',
      );
    }
    final terminal = isTerminalEngine(engine);
    final cwd = source.project?.cwd ?? machine.projectOf(source)?.cwd;
    if (cwd == null && !terminal) {
      return Future.value(
        '${source.displayName} has no project folder to clone into.',
      );
    }
    return createAgent(
      machineId,
      engine: engine,
      folder: cwd,
      dsh: source.dsh,
      codexHome: source.codexHome,
      attempt: AgentCreationAttempt().._codexHomeTrusted = true,
      agent: source.namedAgent,
      permissionMode: source.permissionMode,
      // Unrecorded is not "off": an older daemon's agent clones the way a new
      // one would open. A terminal has no permissions to bypass (⌘⇧T's choice).
      bypassPermission: source.bypassPermission ?? !terminal,
      name: terminal ? null : cloneNameFor(source.displayName),
      swarmId: swarmId ?? activeSwarmId,
      // The current tab, said out loud: without a placement a harness clone
      // would open a tab of its own (see `createAgent`), and the point of a
      // clone is another tile beside the one it came from.
      placement: HarnessPlacement.currentTab,
    );
  }

  final _agentChanges = <(String, String), _AgentChange>{};

  bool _keepsPendingAgent(String machineId, String? agentId) =>
      _closingViewAgents.containsKey((machineId, agentId)) ||
      _agentChanges[(machineId, agentId)]?.preservingViews == true;

  bool _keepsPendingPane(TerminalPane pane) =>
      _keepsPendingAgent(pane.machineId, pane.agentId ?? pane.ownerAgentId);

  Future<Map<String, dynamic>> Function(String sourceId, String engine)?
  changeCompanionAgent;
  bool Function(String machineId, String agentId)? canChangeCompanionAgent;
  void Function(String machineId, String agentId)? openAgentPicker;

  /// Shows the person a message once a switch is done (the handoff hints). Set by the screen on
  /// top, which shows it as a snack bar; null when no screen is listening.
  void Function(String message)? agentChangeNotice;

  /// Whether [agentId] is a Swarm Buddy, as any open Swarm's roster says. Its machine refuses to
  /// stop it, so Change agent cannot switch it.
  @visibleForTesting
  final buddyAgentsForTest = <(String, String)>{};

  bool isSwarmBuddy(String machineId, String agentId) =>
      buddyAgentsForTest.contains((machineId, agentId)) ||
      superTabs.loadedControllers.any(
        (c) =>
            c.snapshot?.agents.any(
              (a) =>
                  a.isBuddy &&
                  a.machineId == machineId &&
                  a.harnessId == agentId,
            ) ==
            true,
      );

  List<String> agentSwitchEngines(String machineId, Agent source) {
    if (source.dsh == 'autonomous/pair') {
      return const ['opencode', 'codex', 'claude'];
    }
    // Devices ships with the portable runtime but is deliberately omitted
    // from dsh_list. Its absence from the public catalog does not restrict
    // an existing Devices conversation to the engine it started with.
    final supported = source.dsh == null
        ? allEngines.map((engine) => engine.id).toList()
        : stateOf(machineId)?.dsh[source.dsh!]?.supportedEngines ??
              (source.dsh == 'autonomous/devices'
                  ? allEngines.map((engine) => engine.id).toList()
                  : [source.engine ?? '']);
    return [
      if (supported.contains('opencode')) 'opencode',
      ...supported.where((id) => id != 'opencode'),
    ];
  }

  /// One switch intent owns its creation receipt. Save the old conversation,
  /// then move all views as soon as the replacement terminal can be attached.
  Future<String?> changeAgent(
    String machineId,
    String agentId,
    String engine, {
    String? profile,
  }) {
    final source = stateOf(machineId)?.agents
        .where((a) => a.id == agentId)
        .firstOrNull;
    if (source == null) {
      return Future.value('This harness is no longer available.');
    }
    final currentProfile = source.engine == 'claude'
        ? source.claudeHome
        : source.codexHome;
    if (source.engine == engine &&
        (profile == null || sameAgentProfile(profile, currentProfile))) {
      return Future.value();
    }
    if (stateOf(machineId)?.machine.isShared != false) {
      return Future.value('Shared harnesses are view-only.');
    }
    if (stateOf(machineId)?.machine.isSharedMachine == true) {
      return Future.value(
        'On a computer shared with you, a harness keeps the agent it started with. Start a new one.',
      );
    }
    if (!agentSwitchEngines(machineId, source).contains(engine)) {
      return Future.value(
        'This agent is not supported by the installed harness.',
      );
    }
    if (isSwarmBuddy(machineId, agentId)) {
      return Future.value(buddyKeepsItsEngine);
    }
    final key = (machineId, agentId);
    if (source.dsh == 'autonomous/pair' &&
        _agentChanges[key] == null &&
        (changeCompanionAgent == null ||
            canChangeCompanionAgent?.call(machineId, agentId) != true)) {
      return Future.value(
        'Open this collection in Companions before changing its agent.',
      );
    }
    var operation = _agentChanges[key];
    if (operation?.pending case final pending?) {
      return operation!.engine == engine &&
              sameAgentProfile(operation.profile, profile)
          ? pending
          : Future.value('The agent is already switching.');
    }
    if (operation != null &&
        ((!operation.preservingViews &&
                (!operation.handoffHeld ||
                    operation.engine != engine ||
                    !sameAgentProfile(operation.profile, profile))) ||
            operation.launchFailed ||
            (operation.creation._finished &&
                operation.creation.agentId == null))) {
      _agentChanges.remove(key);
      operation = null;
    }
    if (operation != null &&
        (operation.engine != engine ||
            !sameAgentProfile(operation.profile, profile))) {
      return Future.value(
        'Check the pending switch to ${operation.engine} before choosing another agent.',
      );
    }
    final change = operation ??= _AgentChange(
      source,
      engine,
      _authRevision,
      profile,
    );
    _agentChanges[key] = change;
    return change.pending = _changeAgent(
      machineId,
      change,
    ).whenComplete(() => change.pending = null);
  }

  /// Keep explicit protocol refusals available to the compatibility and hold
  /// handling below. WsConn throws them; transport failures must still throw.
  Future<Map<String, dynamic>> _agentHandoffRequest(
    String machineId,
    String type, {
    required Map<String, dynamic> payload,
    required Duration timeout,
  }) async {
    try {
      return await _conn(machineId)
          .request(type, payload: payload, timeout: timeout);
    } on WsRequestFailure catch (failure) {
      return {...failure.payload, 'error': failure.code};
    }
  }

  /// Asks [machineId]'s daemon for the Change agent handoff of [agentId]
  /// (`agent_handoff_prepare`, owner only): the record and transcript it
  /// writes in the agent's folder under change [changeId], for an agent of
  /// [targetEngine]. Answers the daemon's reply, an explicit refusal included;
  /// throws when it gives none in time.
  Future<Map<String, dynamic>> prepareAgentHandoff(
    String machineId, {
    required String agentId,
    required String changeId,
    required String targetEngine,
  }) => _agentHandoffRequest(
    machineId,
    'agent_handoff_prepare',
    payload: {
      'agentId': agentId,
      'changeId': changeId,
      'targetEngine': targetEngine,
    },
    timeout: const Duration(seconds: 6),
  );

  /// Fill [change].handoff for the new agent, or return why the switch must not go on.
  ///
  /// First choice: the machine writes a record of the whole conversation into the project and the
  /// new agent is told to read it (agent_handoff_prepare). Unavailable or untrusted preparation
  /// holds the switch with the source still running. Only an explicit older-protocol UNSUPPORTED
  /// reply permits the bounded agent_recent compatibility path.
  /// Both reads happen BEFORE the source is closed: a creation retry must carry the same choices.
  /// Also sets the flags that pick the hint shown when the new agent gets no first prompt.
  Future<String?> _loadSwitchHandoff(
    String machineId,
    _AgentChange change,
    Agent source,
    String folder,
  ) async {
    change.handoffHeld = true;
    try {
      final reply = await prepareAgentHandoff(
        machineId,
        agentId: source.id,
        changeId: change.creation._id,
        targetEngine: change.engine,
      );
      final accepted = acceptAgentHandoffReply(
        reply,
        agentId: source.id,
        changeId: change.creation._id,
        folder: folder,
        sourceLabel: engineIdentity(source.engine).label,
      );
      if (accepted.accepted) {
        change.handoffPrepared = true;
        change.handoff = accepted.prompt;
        change.handoffEmpty = accepted.prompt == null;
        change.handoffFailed = false;
        change.contextLoaded = true;
        change.handoffHeld = false;
        _resendUnreadFirstMessage(machineId, change, source);
        return null;
      }
      if (reply['error'] == 'CHANGE_CONFLICT') {
        change.handoffHeld = false;
        return 'The conversation changed. Choose the agent again to start a new switch.';
      }
      if (reply['error'] != 'UNSUPPORTED') {
        return agentHandoffHeldMessage(
          reply['error'],
          reply['hold'],
          engineIdentity(source.engine).label,
        );
      }
    } catch (_) {
      return 'Waiting for the conversation handoff. Try switching again.';
    }
    try {
      final recent = await _conn(machineId).request(
        'agent_recent',
        payload: {'agentId': source.id, 'n': 5},
        timeout: const Duration(seconds: 4),
      );
      if (recent['error'] != null ||
          (recent['agentId'] != null && recent['agentId'] != source.id)) {
        return 'Could not read the conversation for the handoff. Try switching again.';
      }
      change.handoff = agentSwitchHandoff(
        source.engine ?? 'the previous agent',
        recent,
      );
      change.handoffEmpty = change.handoff == null;
      change.handoffFailed = change.handoffEmpty;
      change.contextLoaded = true;
      change.handoffHeld = false;
    } catch (_) {
      return 'Could not read the conversation for the handoff. Try switching again.';
    }
    _resendUnreadFirstMessage(machineId, change, source);
    return null;
  }

  /// Nothing to hand off, but the source was created with a first message:
  /// the new agent starts on it (see [_firstMessages]).
  void _resendUnreadFirstMessage(
    String machineId,
    _AgentChange change,
    Agent source,
  ) {
    if (!change.handoffEmpty) return;
    final message = _firstMessages[(machineId, source.id)];
    if (message == null) return;
    change.handoff = message;
    change.handoffEmpty = false;
    change.handoffFailed = false;
  }

  Future<String?> _changeAgent(String machineId, _AgentChange change) async {
    final machine = stateOf(machineId);
    final source = change.source;
    if (machine == null || !_machineWorkCurrent(machine, change.revision)) {
      return 'This switch is no longer active.';
    }
    final current = machine.agents.where((a) => a.id == source.id).firstOrNull;
    if (current == null ||
        current.createdAt != source.createdAt ||
        current.sessionId != source.sessionId) {
      change.handoffHeld = false;
      return 'The conversation changed. Reopen Change agent.';
    }
    final folder = source.project?.cwd ?? machine.projectOf(source)?.cwd;
    if (folder == null) {
      return 'This harness has no project folder to open with another agent.';
    }
    if (source.dsh != 'autonomous/pair' &&
        supportsAgentHandoff(change.engine) &&
        !change.contextLoaded) {
      final error = await _loadSwitchHandoff(machineId, change, source, folder);
      if (error != null) return error;
      if (!_machineWorkCurrent(machine, change.revision)) {
        return 'This switch is no longer active.';
      }
    }
    // Preparation can outlive a binding, runtime or project change. Close only the same source.
    final latest = machine.agents.where((a) => a.id == source.id).firstOrNull;
    if (latest == null ||
        latest.createdAt != source.createdAt ||
        latest.sessionId != source.sessionId ||
        latest.engine != source.engine ||
        (latest.project?.cwd ?? machine.projectOf(latest)?.cwd) != folder) {
      return 'The conversation changed. Reopen Change agent.';
    }
    // Named only after its handoff was prepared under this id: a Swarm
    // Product Manager's machine checks the two belong to one switch.
    final close = prepareSessionClose(
      machineId,
      latest,
      changeId: change.handoffPrepared ? change.creation._id : null,
    );
    change.preservingViews = true;
    if (!latest.isStopped) {
      final saved = await close('now');
      if (saved['closed'] != true) {
        change.preservingViews = false;
        // A Swarm Buddy keeps running, so it keeps its agent. The daemon's
        // refusal speaks of Stop Harness, which is no help here.
        if (saved['keptRunning'] == true) return buddyKeepsItsAgent;
        return saved['detail'] as String? ??
            'Could not save and stop this conversation. Its agent has not been changed.';
      }
    }
    if (!_machineWorkCurrent(machine, change.revision)) {
      return 'This switch is no longer active.';
    }
    final modes = permissionModesOf(change.engine);
    final mode = modes.any((mode) => mode.id == source.permissionMode)
        ? source.permissionMode
        : 'ask';
    String? nextId;
    if (source.dsh == 'autonomous/pair') {
      if (change.companionTarget == null) {
        final result = await changeCompanionAgent?.call(
          source.id,
          change.engine,
        );
        if (result?['ok'] != true) {
          return result?['detail'] as String? ??
              'Could not change the companion agent.';
        }
        if (!_machineWorkCurrent(machine, change.revision)) {
          return 'This switch is no longer active.';
        }
        change.companionTarget = result!['agentId'] as String?;
      }
      nextId = change.companionTarget;
      await reloadMachineData(machineId);
    } else {
      final error = await createAgent(
        machineId,
        engine: change.engine,
        folder: folder,
        dsh: source.dsh,
        codexHome: change.engine == 'codex' && change.profile != 'default'
            ? change.profile
            : null,
        claudeHome: change.engine == 'claude' && change.profile != 'default'
            ? change.profile
            : null,
        name: source.displayName,
        permissionMode: mode,
        bypassPermission: mode == 'auto' || mode == 'full',
        prompt: change.handoff,
        attempt: change.creation,
      );
      if (error != null) return error;
      nextId = change.creation.agentId;
    }
    if (nextId == null) {
      return 'The new agent has not confirmed its start yet. Choose it again to check.';
    }
    if (!_machineWorkCurrent(machine, change.revision)) {
      return 'This switch is no longer active.';
    }
    final target = machine.agents.where((a) => a.id == nextId).firstOrNull;
    // A launch receipt identifies the replacement's terminal before its engine
    // is ready. Attach now: shell, installer and onboarding prompts need input
    // during startup. Waiting for readiness leaves a stopped source onscreen
    // and can deadlock the very prompt the person must answer to become ready.
    if (target == null || !target.terminalAvailable) {
      change.launchFailed = target?.launchState == 'failed';
      return target?.launchDetail ??
          'The new terminal is not available yet. Choose the agent again to check.';
    }
    if (!change.replacementReported && source.dsh != 'autonomous/pair') {
      try {
        final reported = await _agentHandoffRequest(
          machineId,
          'agent_handoff_complete',
          payload: {
            'agentId': source.id,
            'replacementId': nextId,
            'changeId': change.creation._id,
            'targetEngine': change.engine,
          },
          timeout: const Duration(seconds: 5),
        );
        if (reported['ok'] != true && reported['error'] != 'UNSUPPORTED') {
          return 'The new agent started. Choose it again to finish the switch.';
        }
        change.replacementReported = true;
      } catch (_) {
        return 'The new agent started. Choose it again to finish the switch.';
      }
      if (!_machineWorkCurrent(machine, change.revision)) {
        return 'This switch is no longer active.';
      }
    }
    final terminals = allPanes
        .where((p) => p.machineId == machineId && p.agentId == source.id)
        .toList();
    final viewers = allPanes
        .where((p) => p.machineId == machineId && p.ownerAgentId == source.id)
        .toList();
    if (terminals.isEmpty) {
      return 'The original pane was closed. Open the new agent from Harness Monitor.';
    }
    // A peer can still have a queued tab.close for a tab whose only agent
    // was the stopped source. Give that replacement a fresh desk identity:
    // the Swarm/pane objects, active selection and geometry stay unchanged,
    // but an old close can no longer address the new conversation.
    final replacedTabs = _desk.enabled
        ? swarms.where((swarm) {
            final agents = swarm.panes.where((pane) => pane.agentId != null);
            return _deskTracks(swarm) &&
                _mayReidentify(swarm) &&
                agents.isNotEmpty &&
                agents.every(
                  (pane) =>
                      pane.machineId == machineId && pane.agentId == source.id,
                );
          }).toList()
        : <Swarm>[];
    // The old process has stopped and its panes were retained through the
    // acknowledgement. Replace their references without changing geometry.
    for (final pane in terminals) {
      await _detachSession(pane, sendClose: true);
      if (!_machineWorkCurrent(machine, change.revision)) {
        return 'This switch is no longer active.';
      }
      if (allPanes.contains(pane) && pane.agentId == source.id) {
        pane.agentId = nextId;
      }
    }
    for (final pane in viewers) {
      if (allPanes.contains(pane)) pane.ownerAgentId = nextId;
    }
    finderRoots.move(machineId, source.id, nextId);
    for (final swarm in swarms) {
      if (swarm.titleMachineId == machineId &&
          swarm.titleAgentId == source.id) {
        swarm.titleAgentId = nextId;
      }
    }
    for (final swarm in replacedTabs) {
      if (!swarms.contains(swarm)) continue;
      final previousId = swarm.id;
      swarm.id = newDeskId();
      if (_activeSwarmId == previousId) _activeSwarmId = swarm.id;
      for (final entry in _draftSwarmReturns.entries.toList()) {
        if (entry.value == previousId) _draftSwarmReturns[entry.key] = swarm.id;
      }
    }
    _agentChanges.remove((machineId, source.id));
    _syncViewerPane(machine, target);
    // Publish the replacement before yielding: a peer may already have
    // pruned the stopped source from the shared desk.
    _persistLayout();
    notifyListeners();
    await agentPreference.selectLaunch(change.engine, harnessId: source.dsh);
    if (!_machineWorkCurrent(machine, change.revision)) {
      return 'This switch is no longer active.';
    }
    for (final pane in terminals) {
      if (allPanes.contains(pane)) {
        unawaited(
          _attachSession(
            pane,
            intent: panes.contains(pane) && pane.id == focusedPaneId
                ? AttachIntent.person
                : AttachIntent.automatic,
          ),
        );
      }
    }
    if (change.handoffEmpty) {
      final from = engineIdentity(source.engine).label;
      final to = engineIdentity(change.engine).label;
      agentChangeNotice?.call(
        change.handoffFailed
            ? agentSwitchHandoffFailedHint(from, to)
            : agentSwitchNoHistoryHint(from, to),
      );
    }
    return null;
  }

  /// A fork keeps the originating tab and creation receipt while its prompt is
  /// closed. Reopening joins the request; checking an uncertain result never
  /// sends a second agent_fork. Old daemons can still return their legacy reply.
  Future<ForkAgentResult> forkAgent(
    String machineId,
    String agentId, {
    String? name,
    String? prompt,
    AgentForkAttempt? attempt,
  }) {
    final operation = attempt ?? forkAttempt(machineId, agentId);
    if (operation.result case final result?
        when result.error == null && result.agentId != null) {
      return Future.value(result);
    }
    if (operation.locked &&
        ((name != null && name.trim() != operation.name.trim()) ||
            (prompt != null && prompt != operation.prompt))) {
      return Future.value(
        const ForkAgentResult(
          error: 'Check the original fork before changing its choices.',
        ),
      );
    }
    if (operation.pending case final pending?) return pending;
    if (!operation.awaitingConfirmation) {
      if (name != null) operation.name = name;
      if (prompt != null) operation.prompt = prompt;
    }
    late final Future<ForkAgentResult> request;
    request = _runAgentFork(machineId, agentId, operation)
        .then((result) {
          operation.result = result;
          return result;
        })
        .whenComplete(() {
          if (identical(operation._inFlight, request)) {
            operation._inFlight = null;
          }
          if (_authWorkCurrent(operation._authRevision)) notifyListeners();
        });
    operation._inFlight = request;
    return request;
  }

  Future<ForkAgentResult> _runAgentFork(
    String machineId,
    String agentId,
    AgentForkAttempt attempt,
  ) async {
    final machine = attempt._machine;
    if (machine == null) {
      return const ForkAgentResult(error: 'Machine not found');
    }
    if (machine.machine.machineId != machineId ||
        attempt.source?.id != agentId) {
      return const ForkAgentResult(
        error: 'The source harness is no longer available.',
      );
    }
    if (!_machineWorkCurrent(machine, attempt._authRevision)) {
      return const ForkAgentResult(
        error: 'This fork is no longer active. Reopen Fork Harness.',
      );
    }
    if (machine.machine.isShared) {
      return const ForkAgentResult(error: 'Shared harnesses are view-only.');
    }
    if (machine.machine.isSharedMachine) {
      return const ForkAgentResult(
        error: 'On a computer shared with you, harnesses can’t be restarted, resumed or forked. Start a new one.',
      );
    }
    if (!attempt.awaitingConfirmation) {
      if (!_forkSourceCurrent(attempt)) {
        return const ForkAgentResult(
          error: 'The source harness changed. Close this prompt and reopen Fork Harness.',
        );
      }
      if (pendingAgentStop(machineId, agentId) != null) {
        return const ForkAgentResult(error: 'The source harness is stopping.');
      }
      if (attempt.source?.canFork != true) {
        return const ForkAgentResult(
          error: 'This harness does not support forking.',
        );
      }
      if (agentIsProcessing(machineId, agentId)) {
        return const ForkAgentResult(
          error: 'This harness is working. Wait for its turn to finish, then fork.',
        );
      }
      if (attempt.name.characters.length > 80) {
        return const ForkAgentResult(
          error: 'Use at most 80 characters for the name.',
        );
      }
      if (attempt.prompt.length > 2000) {
        return const ForkAgentResult(
          error: 'Use at most 2000 characters for the first task.',
        );
      }
      attempt._id = _newCreationId();
      attempt._target = activeSwarm;
      attempt._focus = focusedPaneId;
      attempt._startedRevision = machine._agentRevision;
    }
    final checking = attempt.awaitingConfirmation;
    attempt._awaitingConfirmation = true;
    const unknown = ForkAgentResult(
      error: 'The fork is not confirmed yet. Check status, or use New Pane to look for it before starting another.',
    );
    Map<String, dynamic> result;
    try {
      result = await _conn(machineId).request(
        checking ? 'agent_create_status' : 'agent_fork',
        payload: {
          'creationId': attempt._id,
          if (!checking) ...{
            'agentId': agentId,
            if (attempt.name.trim().isNotEmpty) 'name': attempt.name.trim(),
            if (attempt.prompt.trim().isNotEmpty) 'prompt': attempt.prompt,
          },
        },
      );
    } catch (_) {
      return unknown;
    }
    if (!_machineWorkCurrent(machine, attempt._authRevision)) {
      return const ForkAgentResult(
        error: 'The machine changed while forking. Check its harnesses after reconnecting.',
      );
    }
    if ((checking ||
            result.containsKey('creationId') ||
            result.containsKey('state')) &&
        result['creationId'] != attempt._id) {
      return unknown;
    }
    if (result['error'] case final String code) {
      // These are refusals before dispatch, including the legacy fork endpoint.
      if (checking ||
          [
            'INTERNAL',
            'CREATION_STORAGE_FAILED',
            'SPAWN_FAILED',
            'REGISTRATION_FAILED',
          ].contains(code)) {
        return unknown;
      }
      attempt._awaitingConfirmation = false;
      return ForkAgentResult(error: _forkFailure(code, result['detail']));
    }
    switch (result['state']) {
      case 'pending':
        return const ForkAgentResult(
          error: 'The machine is still starting the fork. Check again in a moment.',
        );
      case 'missing':
      case 'unconfirmed':
        return unknown;
      case 'unavailable':
        attempt._awaitingConfirmation = false;
        return const ForkAgentResult(
          error: 'The fork was created but is no longer available. You can start another.',
        );
      case 'failed':
        final failure = result['failure'];
        if (failure is! Map || failure['code'] is! String) return unknown;
        attempt._awaitingConfirmation = false;
        return ForkAgentResult(
          error: _forkFailure(failure['code'] as String, failure['detail']),
        );
      case 'created':
      case null:
        break;
      default:
        return unknown;
    }
    final raw = result['agent'];
    if (raw is! Map ||
        raw['id'] is! String ||
        (raw['id'] as String).isEmpty ||
        raw['id'] == agentId) {
      return unknown;
    }
    final Agent fork;
    try {
      fork = _preserveNewerName(
        machine,
        Agent.fromJson(Map<String, dynamic>.from(raw)),
        attempt._startedRevision,
      );
    } catch (_) {
      return unknown;
    }
    attempt._awaitingConfirmation = false;
    if (identical(_agentForks[(machineId, agentId)], attempt)) {
      _agentForks.remove((machineId, agentId));
    }
    if ((machine._agentRemovals[fork.id] ?? 0) > attempt._startedRevision) {
      return ForkAgentResult(
        agentId: fork.id,
        level: result['level'] == 'handoff' ? 'handoff' : 'native',
        notice: 'The fork was created but has since stopped. Use New Pane to check current harnesses.',
      );
    }
    _upsertAgent(machine, fork);
    notifyListeners();
    var target = attempt._target;
    final keepFocus = target == activeSwarm && focusedPaneId == attempt._focus;
    String? notice;
    if (target == null || !swarms.contains(target)) {
      notice =
          'Fork created. Its original tab closed; use New Pane to open it.';
    } else if (target.panes.length >= maxPanes && !keepFocus) {
      notice =
          'Fork created. Its original tab is full; use New Tab to open it.';
    } else {
      if (target.panes.length >= maxPanes) {
        newSwarm(name: fork.name);
        target = activeSwarm;
      }
      await assignAgentToPane(
        null,
        machineId,
        fork.id,
        swarmId: target.id,
        autoTile: true,
        focus: keepFocus,
      );
    }
    return ForkAgentResult(
      level: result['level'] == 'handoff' ? 'handoff' : 'native',
      agentId: fork.id,
      notice: notice,
    );
  }

  String _forkFailure(String code, Object? detail) =>
      detail is String && detail.isNotEmpty
      ? detail
      : switch (code) {
          'UNSUPPORTED_ON_REMOTE' || 'UNSUPPORTED' =>
            'Update the harness CLI on this machine to fork a harness.',
          'AGENT_BUSY' =>
            'This harness is working. Wait for its turn to finish, then fork.',
          _ => 'Fork failed: $code',
        };

  /// Put a fork on screen beside its source and focus it — the window's half
  /// of a fork asked for here or on the dial (`dial_forked`).
  Future<void> placeFork(
    String machineId,
    String agentId, {
    required String sourceAgentId,
  }) async {
    if (revealAgentView(machineId, agentId)) return;
    // The current tab: it is where the source was forked from, whether by the
    // pane's own menu or by the dial, which shows this tab too. `sourceAgentId`
    // is kept on the wire for a placement that wants the source's tab later.
    assert(sourceAgentId.isEmpty || sourceAgentId != agentId);
    if (activeSwarm.panes.length >= maxPanes) {
      // Beside the source is the wish; a tab of its own is the honest fallback.
      newSwarm();
    }
    await addAgentToSwarm(machineId, agentId, swarmId: activeSwarmId);
    revealAgentView(machineId, agentId);
  }

  /// Harnesses another harness's agent started that this window has already
  /// placed or passed over, by machine and agent id: each is decided once, the
  /// first time it is seen live, so a pane the person closes stays closed.
  final _decidedStartedChildren = <(String, String)>{};

  /// A harness an agent here started (`harness new`, or `harness_start`
  /// through `harness mcp`, from its pane) opens right beside that agent's
  /// pane, in the tab that shows it, without taking the focus or the terminal
  /// from anyone (owner, 2026-10-11; `state/started_children.dart`).
  ///
  /// Only one [arrived] after this window read the machine's list, and seen
  /// live: what the first list or a push before it brings is the window's
  /// restore, and is passed over for good. Never one this window has shown
  /// before ([hasOpenedHarness]): the person closed it. Where the starter is
  /// in no tab here nothing changes; it is in ⌘O as before.
  ///
  /// Every window that shows the starter does this, on every computer, and
  /// that is still one pane: each picks the same tab (the first in the desk's
  /// order that shows the starter), the desk's `pane.add` is idempotent per
  /// tab, machine and agent (`desk_sync.dart`), and a window that hears of the
  /// pane from the desk first finds the child already in a tab and leaves it.
  /// Placing it in the daemon instead would need the desk's layout rules
  /// there, and a signed-out computer has no desk at all.
  void _openStartedChild(
    MachineState machine,
    Agent child, {
    required bool arrived,
  }) {
    if (child.parentAgentId == null || machine.machine.isShared) return;
    final machineId = machine.machine.machineId;
    final key = (machineId, child.id);
    if (_decidedStartedChildren.contains(key)) return;
    if (arrived && !startedChildLive(child)) return;
    _decidedStartedChildren.add(key);
    if (_decidedStartedChildren.length > 4096) {
      _decidedStartedChildren.remove(_decidedStartedChildren.first);
    }
    if (!arrived || hasOpenedHarness(machineId, child.id)) return;
    final place = startedChildPlacement(
      tabs: swarms,
      machineId: machineId,
      child: child,
      now: DateTime.now(),
      maxPanes: maxPanes,
    );
    if (place == null) return;
    unawaited(
      assignAgentToPane(
        null,
        machineId,
        child.id,
        swarmId: place.tab.id,
        besidePaneId: place.parent.id,
        autoTile: true,
        focus: false,
        intent: AttachIntent.automatic,
      ),
    );
  }

  /// Every tile on the machine, not just the focused one: the machine is what
  /// went away, so a tile of the same machine sitting in another corner of the
  /// grid is just as dead and must say so rather than keep showing a terminal
  /// that can no longer receive anything. Records what was open so the next
  /// `connected` can put it back (`_recoverPendingAgent`).
  void _markSessionsUnreachable(MachineState machine, String message) {
    for (final pane in panesFor(machine.machine.machineId)) {
      final session = pane.session;
      if (session == null) continue;
      machine.activeAgentId ??= session.agentId;
      // A pane someone else already took over must stay frozen until the user retries it
      // themselves (see `_paneNeedsAttach`) — recording it here would have `_recoverPendingAgent`
      // call `selectAgent` on reconnect and silently win it back the moment the connection
      // returns, fighting whichever machine holds it now.
      if (session.status != TerminalSessionStatus.takenOver) {
        machine.pendingOfflineAgentId ??= session.agentId;
      }
      // Do not send terminal_close: the adapter is already gone and the
      // next client attachment should be the only stream that owns the pane.
      //
      // Once per outage, not once per reconnect attempt: the local socket retries every second
      // now, and each attempt lands here again through the `reconnecting` status. A pane already
      // dark with this very message has nothing to learn and nothing to repaint.
      if (session.status == TerminalSessionStatus.error &&
          session.errorCode == TerminalSession.disconnectedCode &&
          session.errorMessage == message) {
        continue;
      }
      session.transportLost(message);
    }
  }

  /// One line per change in this computer's own machine state, with why — the trail that was
  /// missing when a local tile sat on "Offline" over a live socket until the app was restarted
  /// (2026-09-29 19:13): nothing then said which of four writers had put it there.
  void _logLocalMachine(MachineState machine, String event) {
    final id = machine.machine.machineId;
    appLog.info(
      'machine',
      'local ${id.length > 8 ? id.substring(0, 8) : id}: $event',
    );
  }

  /// This computer's own daemon is answering on its socket right now.
  ///
  /// For the local machine that socket IS the machine: the daemon it reaches is the Harness running
  /// here, and it only selects once the daemon has taken the machine. So nothing weaker — an RPC that
  /// timed out, a status probe that missed its 400ms, a refresh applying a probe taken before the
  /// daemon was answering — may call it offline while this holds. A socket that really dies closes,
  /// and `reconnecting` takes the machine offline the ordinary way.
  bool _localLinkLive(MachineState machine) {
    if (!machine.localOnly || machine.machine.isShared) return false;
    final machineId = machine.machine.machineId;
    final testConnection = connectionForTest;
    final connection = testConnection != null
        ? testConnection(machineId)
        : _pool?[machineId];
    return connection != null && connection.isReady;
  }

  /// Bring this computer's machine back from "offline" when its socket says otherwise.
  ///
  /// Only one path restored it before, and that path runs when the socket RECONNECTS — which, once a
  /// wake stopped dropping the loopback socket, is exactly what no longer happens. A false timeout
  /// could then mark it offline for good over a socket that never dropped. Called from the three
  /// places that see the daemon answering: the supervisor's five-second snapshot, any frame arriving
  /// from it, and the offline poll.
  ///
  /// Deliberately NOT `_applyNodeStatus(true)`: that re-marks every pane's session unreachable, and
  /// the streams here may already be live again. Only tiles whose stream is actually dead reattach.
  /// Returns whether anything was restored.
  bool _healLocalMachine(
    MachineState machine,
    String why, {
    LocalCliEndpoint? endpoint,
  }) {
    if (_disposed || !_localLinkLive(machine)) return false;
    final restoredEndpoint = machine.localEndpoint == null
        ? (endpoint ?? _cliEndpoint)
        : null;
    final wasOffline = machine.nodeOnline == false;
    final staleStatus = machine.connectionStatus != ConnectionStatus.connected;
    if (!wasOffline && restoredEndpoint == null && !staleStatus) return false;
    if (machine.localEndpoint == null && restoredEndpoint == null) return false;
    machine.localEndpoint ??= restoredEndpoint;
    machine.connectionStatus = ConnectionStatus.connected;
    machine.transportMode = MachineTransportMode.localPlaintext;
    machine.nodeOnline = true;
    _stopOfflineRetry(machine.machine.machineId);
    // A `reconnecting` status that was never followed by `connected` stopped the minute's agent
    // sync; the socket being live again is the connect it was waiting for.
    _startAgentSyncTimer(machine.machine.machineId);
    _rereadDevicesAfterDaemonReconnect(machine.machine.machineId);
    _logLocalMachine(
      machine,
      'restored ($why${restoredEndpoint != null ? ', endpoint' : ''})',
    );
    final pending = machine.pendingOfflineAgentId;
    if (pending != null) {
      unawaited(_recoverPendingAgent(machine, pending));
    } else if (wasOffline ||
        restoredEndpoint != null ||
        panesFor(machine.machine.machineId).any(_paneNeedsAttach)) {
      unawaited(_loadMachineData(machine, force: true));
    }
    notifyListeners();
    return true;
  }

  /// An inventory snapshot can predate a successful remote selection. Keep its
  /// offline status from taking a live connection down; socket failures and
  /// explicit node_status pushes still go through _applyNodeStatus directly.
  Future<void> _applyInventoryNodeStatus(
    MachineState machine,
    bool online,
  ) async {
    if (!online &&
        machine.nodeOnline == true &&
        machine._selectedConnectionReady) {
      return;
    }
    await _applyNodeStatus(machine, online, why: 'machine inventory');
  }

  Future<void> _applyNodeStatus(
    MachineState machine,
    bool online, {
    String why = 'unspecified',
  }) async {
    if (_disposed) return;
    final machineId = machine.machine.machineId;
    final wasOnline = machine.nodeOnline;
    machine.nodeOnline = online;
    if (machine.localOnly && wasOnline != online) {
      _logLocalMachine(machine, online ? 'online ($why)' : 'offline ($why)');
    }

    if (!online) {
      if (wasOnline != false) _resetMachineDiscovery(machine);
      _markSessionsUnreachable(
        machine,
        machine.isLocalMachine
            ? 'Harness is offline. Run harness login to reconnect.'
            : 'Harness is offline. Run harness start on that machine to reconnect.',
      );
      _startOfflineRetry(machine);
    } else {
      _stopOfflineRetry(machineId);
      if (!machine.isLocalMachine) _connectionOf(machineId)?.wake('online');
      if (wasOnline == false) {
        _markSessionsUnreachable(
          machine,
          'Harness reconnected; restoring terminal…',
        );
      }
      final pending = machine.pendingOfflineAgentId;
      if (pending != null) {
        unawaited(_recoverPendingAgent(machine, pending));
      } else if (panesFor(machineId).any(_paneNeedsAttach)) {
        // A tile restored from the saved layout has no pendingOfflineAgentId —
        // nothing of its was interrupted, it simply arrived before its machine
        // did. Without this it would sit on "Attaching…" forever on a machine
        // that has since come back, because every other route to _attachSession
        // runs off a load that nothing here would trigger.
        unawaited(_loadMachineData(machine, force: true));
      }
    }
    notifyListeners();
  }

  Future<void> _recoverPendingAgent(
    MachineState machine,
    String agentId,
  ) async {
    final machineId = machine.machine.machineId;
    if (_offlineRecoveryInFlight.containsKey(machineId)) return;
    final owner = Object();
    _offlineRecoveryInFlight[machineId] = owner;
    final revision = _authRevision;
    final discoveryRevision = machine._discoveryRevision;
    bool current() =>
        _machineDiscoveryCurrent(machine, revision, discoveryRevision) &&
        machine.nodeOnline == true &&
        machine.pendingOfflineAgentId == agentId;
    try {
      // E2EE and agents_list can become ready in separate frames after a
      // node restart. Poll briefly instead of racing a single request.
      for (var attempt = 0; attempt < 40; attempt++) {
        if (!current()) return;
        await _loadMachineData(machine, force: true);
        if (!current()) return;
        final agent = machine.agents.cast<Agent?>().firstWhere(
          (candidate) => candidate?.id == agentId,
          orElse: () => null,
        );
        if (agent != null &&
            agent.terminalAvailable &&
            machine.terminalCapabilityAvailable) {
          machine.pendingOfflineAgentId = null;
          // Loading already reattaches retained panes across every tab. Selecting that agent
          // again would insert it into the current tab and steal focus from the user's work.
          // Only fulfill a pending selection when it has no pane yet and the user is still on
          // this machine; a reconnect must preserve the layout and selection they left open.
          final hasPane = allPanes.any(
            (pane) => pane.machineId == machineId && pane.agentId == agentId,
          );
          if (!hasPane && selectedMachineId == machineId) {
            // A machine coming back is not a gesture: the tile opens, but as a
            // watcher where the terminal is already somebody's.
            await addAgentToSwarm(
              machineId,
              agentId,
              intent: AttachIntent.automatic,
            );
          } else {
            notifyListeners();
          }
          return;
        }
        await Future<void>.delayed(const Duration(milliseconds: 250));
      }
    } finally {
      if (identical(_offlineRecoveryInFlight[machineId], owner)) {
        _offlineRecoveryInFlight.remove(machineId);
      }
    }
  }

  /// A dial notification was tapped: bring that agent to the front.
  ///
  /// The window is tabs now (owner, 2026-09-15): the tab that already holds
  /// the agent wins — the current one first, then any other — and the tab
  /// switches with the pane focused. No tab holds it: it gets a tab of its own
  /// rather than a tile squeezed into whatever happened to be open, which is
  /// also what keeps a full tab from turning a tap into a capacity error.
  ///
  /// Never opened twice: the daemon keeps a single controller per agent, so a
  /// second open is a takeover — the window would fight itself and the first
  /// tile would go dark with `TERMINAL_TAKEN_OVER`. [revealAgentView] is what
  /// Open Harness uses for the same reason.
  /// `harness remote`'s hand-over: the tile showing [fromAgentId] on
  /// [fromMachineId] becomes [agentId]'s on [machineId] — the SAME tile, in
  /// place: its slot, its pin, its cell key and so its widget all stay, only
  /// the machine and agent it points at change and the terminal inside it is
  /// replaced. The shell the command was typed in is then stopped, so the old
  /// terminal is gone rather than left behind. Nothing happens when no tile
  /// here shows that agent: the push reaches every window, and the tile is
  /// in one.
  ///
  /// Not [assignAgentToPane]: that removes the tile and inserts a new one,
  /// which remounts the cell and can slide the grid — a move should read as
  /// the tile changing what it shows, not as one tile leaving and another
  /// arriving.
  ///
  /// The new agent may not be in [machineId]'s list yet: its `agent_created`
  /// push travels on that machine's connection, the hand-over on this one, and
  /// the two are unordered. So the list is asked for again, and the agent is
  /// waited for a little, before the tile is pointed at it.
  Future<void> handoffTerminalPane(
    String fromMachineId,
    String fromAgentId,
    String machineId,
    String agentId,
  ) async {
    Swarm? tab;
    TerminalPane? tile;
    for (final swarm in swarms) {
      for (final pane in swarm.panes) {
        if (pane.machineId == fromMachineId && pane.agentId == fromAgentId) {
          tab = swarm;
          tile = pane;
          break;
        }
      }
      if (tile != null) break;
    }
    if (tab == null || tile == null) return;
    final target = machineStates[machineId];
    if (target == null) {
      _lastError = 'The machine the terminal opened on is not in this window.';
      _lastErrorRetryable = false;
      notifyListeners();
      return;
    }
    if (!await _awaitAgent(target, agentId)) {
      _lastError =
          '${target.machine.displayName} opened a terminal, but it has not appeared yet.';
      _lastErrorRetryable = false;
      notifyListeners();
      return;
    }
    if (_disposed || !allPanes.contains(tile)) return;
    // The old stream goes first (the cell shows "Attaching…" for the moment
    // between), then the tile is re-pointed and the new one attached.
    await _detachSession(tile, sendClose: true);
    if (_disposed) return;
    tile
      ..machineId = machineId
      ..agentId = agentId
      ..sharedHarness = null
      ..sharedOwnerName = null;
    target.activeAgentId = agentId;
    _dismissedLinkPrompts.remove(machineId);
    if (tab.id != activeSwarmId) selectSwarm(tab.id);
    if (tab == activeSwarm) selectedMachineId = machineId;
    focusPane(tile.id, reveal: true);
    notifyListeners();
    _persistLayout();
    unawaited(_attachSession(tile, intent: AttachIntent.automatic));
    // The old shell: `harness remote` has exited in it, and the tile is no
    // longer its. Ending it is what makes the switch a move, not a copy.
    await deleteAgent(fromMachineId, fromAgentId);
  }

  /// Whether [machine] lists [agentId], asking it again and watching for the
  /// push for a few seconds when it does not yet. The reload is not awaited:
  /// it waits on the connection being ready, and the agent's own
  /// `agent_created` usually lands on it first.
  Future<bool> _awaitAgent(MachineState machine, String agentId) async {
    bool known() => machine.agents.any((agent) => agent.id == agentId);
    if (known()) return true;
    unawaited(_loadMachineData(machine, force: true).catchError((_) {}));
    for (var attempt = 0; attempt < 32 && !_disposed; attempt++) {
      await Future<void>.delayed(const Duration(milliseconds: 250));
      if (known()) return true;
    }
    return known();
  }

  /// The dial asked for this agent on screen. A tap (a notification, the
  /// question's eyebrow, the carousel) gets a tile of its own when none shows
  /// the agent. A question screen that came up on its own ([fromQuestion])
  /// only brings the agent forward when it is already on screen: every
  /// unanswered question is re-shown on each reconnect, and a blink in the
  /// link used to open a row of tabs — on every Mac, once tabs were shared
  /// (owner, 2026-09-21).
  ///
  /// The device's move, never a person's — see [paneFocusByUser]: bringing
  /// the agent forward takes nothing back from another client, and the tile
  /// a tap opens claims only its own terminal.
  Future<void> openAgentFromDial(
    String machineId,
    String agentId, {
    bool fromQuestion = false,

    /// The dial's own opens are [AttachIntent.automatic]; the Store's Resume
    /// button borrows this door and IS a person, so it says so.
    AttachIntent intent = AttachIntent.automatic,
  }) async {
    if (_fromDevice(() => revealAgentView(machineId, agentId))) {
      selectedMachineId = machineId;
      notifyListeners();
      return;
    }
    if (fromQuestion) {
      appLog.debug(
        'dial',
        'question for $agentId not on screen — tabs left as they are',
      );
      return;
    }
    // Its own tab. newSwarm reuses an unused start page when there is one, and
    // at the tab limit leaves the current tab selected — the agent then lands
    // there, with the usual capacity message if that tab is full.
    await _fromDevice(() {
      newSwarm();
      return addAgentToSwarm(
        machineId,
        agentId,
        swarmId: activeSwarmId,
        intent: intent,
      );
    });
  }

  final _preparationOpens = <String, Future<bool>>{};
  final _revealedPreparations = <String>{};

  /// Reveal a prepared agent before its engine is ready, so login/trust stays
  /// interactive. This only opens UI; task delivery belongs to the device.
  Future<bool> revealPreparedAgent(
    String machineId,
    String agentId,
    String operationId,
  ) async {
    final key = '$_authRevision/$machineId/$operationId';
    if (_revealedPreparations.contains(key)) return true;
    final agentKey = '$_authRevision/$machineId/$agentId';
    final pending = _preparationOpens[agentKey];
    if (pending != null) {
      final opened = await pending;
      if (opened) _revealedPreparations.add(key);
      return opened;
    }
    final opening = _openPreparedAgent(machineId, agentId);
    _preparationOpens[agentKey] = opening;
    try {
      final opened = await opening;
      if (opened) _revealedPreparations.add(key);
      return opened;
    } finally {
      _preparationOpens.remove(agentKey);
    }
  }

  Future<bool> _openPreparedAgent(String machineId, String agentId) async {
    final revision = _authRevision;
    final machine = machineStates[machineId];
    if (_disposed || machine == null || !await _awaitAgent(machine, agentId)) {
      return false;
    }
    if (_disposed ||
        revision != _authRevision ||
        !identical(machineStates[machineId], machine)) {
      return false;
    }
    await openAgentFromDial(machineId, agentId);
    if (_disposed ||
        revision != _authRevision ||
        !identical(machineStates[machineId], machine) ||
        !allPanes.any(
          (p) => p.machineId == machineId && p.agentId == agentId,
        )) {
      return false;
    }
    // Reuse the generic package viewer path, including a late viewerUrl/error.
    final agent = machine.agents.where((a) => a.id == agentId).firstOrNull;
    if (agent != null) {
      _dismissedViewers.remove(_viewerKey(machineId, agentId));
      _syncViewerPane(machine, agent);
      activeSwarm.zoomedPaneId = null;
      _persistLayout();
      notifyListeners();
    }
    return true;
  }

  /// Enable-time fallback: preserve the user's current choice and acknowledge it.
  /// Selection records focus before waiting for terminal attachment, so a later
  /// user click is never overwritten by completion of an asynchronous open.
  Future<void> ensureDeviceFocus(Map<String, dynamic> payload) async {
    final expiresAt = payload['expiresAt'];
    final machineId = payload['machineId'];
    final agentId = payload['agentId'];
    final focusRevision = payload['focusRevision'];
    if (expiresAt is! num ||
        expiresAt <= DateTime.now().millisecondsSinceEpoch ||
        machineId is! String ||
        agentId is! String ||
        agentId.isEmpty ||
        focusRevision is! String ||
        focusRevision.isEmpty) {
      return;
    }
    if (focusedPane?.agentId != null) {
      _announceAppFocus();
      return;
    }
    // Tag only the synchronous fallback announcement, never a later user click.
    late Future<void> selection;
    _deviceFocusRevision = focusRevision;
    try {
      selection = focusAgentFromDevice(machineId, agentId);
    } finally {
      _deviceFocusRevision = null;
    }
    await selection;
  }

  /// The dial turned to an agent. Focus, the same move a click on the rail makes — minus the retake.
  ///
  /// It used to take a `DeskEdge` and, for an agent with no tile, replace the pane at that end — the
  /// dial's carousel could walk past the end of the desk onto an unopened agent, and the edge said
  /// which tile it had walked off. The carousel walks only open panes now, so there is no off-desk
  /// landing left to place and nothing to replace.
  Future<void> selectAgentFromDial(String machineId, String agentId) =>
      focusAgentFromDevice(machineId, agentId);

  /// A device Finder choice names an existing view, sometimes one exact tile.
  /// Reveal it without retrying a stream or treating device focus as a local
  /// keyboard/mouse takeover. A vanished tile must not turn into an Add.
  bool revealAgentViewFromDevice(
    String machineId,
    String agentId, {
    String? swarmId,
    int? paneId,
  }) {
    if (_disposed) return false;
    if (paneId == null) {
      return _fromDevice(
        () => revealAgentView(machineId, agentId, preferredSwarmId: swarmId),
      );
    }
    final owner = swarms.where((s) => s.id == swarmId).firstOrNull;
    final pane = owner?.panes
        .where(
          (p) =>
              p.id == paneId &&
              p.machineId == machineId &&
              p.agentId == agentId,
        )
        .firstOrNull;
    if (owner == null || pane == null) return false;
    return _fromDevice(() {
      selectSwarm(owner.id, attachPending: false);
      focusPane(pane.id, reveal: true);
      return true;
    });
  }

  /// Bring [agentId]'s tile forward because a device asked — the dial's
  /// carousel, the WiFi device's focus. The tab switches, the tile gets the
  /// keyboard and `app_focus` goes back to the daemon, exactly as
  /// [selectAgent] does; what it does NOT do is reopen a stream another
  /// client holds. [selectAgent] reopens every dead pane it lands on, and a
  /// `takenOver` pane is dead by that measure — so a turn of the dial was a
  /// takeover, and a question re-shown there took the whole desk back from
  /// the other Mac (see [paneFocusByUser]). Here the band stays up with its
  /// button, and only a hand on this app presses it.
  ///
  /// A tile that never attached (its machine was offline when it was
  /// restored) is attached now, as the ordinary reconnect would: nobody else
  /// can be holding a stream this app never opened. No tile at all opens one,
  /// the way a rail click does — that is an open, not a focus, and it claims
  /// only its own terminal.
  Future<void> focusAgentFromDevice(String machineId, String agentId) async {
    // Device focus can name a pane on another tab. The current-tab lookup
    // alone turns that focus into an Add and copies the view into this tab.
    final existing =
        paneOfAgent(machineId, agentId) ??
        allPanes
            .where(
              (pane) => pane.machineId == machineId && pane.agentId == agentId,
            )
            .firstOrNull;
    if (existing == null) {
      await _fromDevice(
        () =>
            addAgentToSwarm(machineId, agentId, intent: AttachIntent.automatic),
      );
      return;
    }
    _fromDevice(() => revealAgentView(machineId, agentId));
    machineStates[machineId]?.activeAgentId = agentId;
    // The dial turning is not a person at THIS Mac: show the terminal, never
    // take it from the window or phone that is driving it.
    if (existing.session == null) {
      await _attachSession(existing, intent: AttachIntent.automatic);
    }
  }

  Future<void> selectAgent(String machineId, String agentId) async {
    final existing = paneOfAgent(machineId, agentId);
    if (existing != null) {
      selectedMachineId = machineId;
      machineStates[machineId]?.activeAgentId = agentId;
      focusPane(existing.id);
      final terminal = existing.session;
      if (terminal == null) {
        // The pane wanted this agent before `_attachSession` could actually attach it (the agent's
        // terminal wasn't verified yet, the machine was briefly offline, ...). Nothing else retries a
        // null session on its own — see `_attachPendingPanes` — so a click here has to.
        await _attachSession(existing);
      } else if (terminal.watching) {
        if (!_canAttachPane(existing)) return;
        // A person landing on a pane this window is only WATCHING is the one
        // thing that turns it into control — the band's button takes this same
        // road. `force` arms the one takeover that asks for the terminal.
        await terminal.reopen(force: true);
      } else if (terminal.status != TerminalSessionStatus.opening &&
          terminal.status != TerminalSessionStatus.controlling &&
          terminal.status != TerminalSessionStatus.resyncing) {
        if (!_canAttachPane(existing)) return;
        // Retry the dead stream in place so its output and view context remain
        // available until the next keyframe. Healthy panes stay focus-only.
        await terminal.reopen(force: true);
      }
      return;
    }
    await addAgentToSwarm(machineId, agentId);
  }

  /// Show a MACHINE in the grid, for the states that belong to the machine
  /// rather than to any agent on it.
  ///
  /// It has to be a tile like any other — the alternative of letting a machine
  /// take over the whole content area would blank three working terminals
  /// belonging to two other machines. The one exception is a machine that
  /// already needs linking: selecting it brings up the Machines picker
  /// (`SwarmScreen._maybeLink`), so opening a tile here too would just be a
  /// redundant "not linked" pane sitting behind it. Selecting is still worth
  /// doing — it's what makes that gate notice this machine — the tile is not.
  /// A tile that ALREADY shows such a machine is a different case and keeps
  /// its own way out: its "Link…" button (`pane_grid.dart`).
  void showMachinePane(String machineId) {
    final machine = machineStates[machineId];
    if (machine == null) return;
    _dismissedLinkPrompts.remove(machineId);
    selectedMachineId = machineId;
    if (machine.isRemote && !machine.isLocalMachine && machine.needsLink) {
      _requestedMachineLink = machineId;
      notifyListeners();
      return;
    }

    final existing = panes
        .where(
          (pane) =>
              pane.machineId == machineId &&
              pane.agentId == null &&
              !pane.isWeb,
        )
        .firstOrNull;
    if (existing != null) {
      focusPane(existing.id);
      notifyListeners();
      return;
    }

    final target = focusedPane;
    if (target != null && target.agentId == null && !target.isWeb) {
      target.machineId = machineId;
      focusPane(target.id);
      notifyListeners();
      return;
    }
    if (!canAddPane) return;
    final pane = TerminalPane(id: _nextPaneId++, machineId: machineId);
    panes.add(pane);
    focusPane(pane.id);
    notifyListeners();
  }

  static bool _listedIn(SharedTab tab, String machineId, String agentId) => tab
      .harnesses
      .any((h) => h.machineId == machineId && h.agentId == agentId);

  /// Listed in [tab], or still `Joining…`: an add this computer's daemon holds
  /// for the owner's computer. Withdrawn then, it must be taken back too, or
  /// the owner applies it later (final review of 1c, I3).
  bool _inSharedTab(SharedTab tab, String machineId, String agentId) =>
      _listedIn(tab, machineId, agentId) ||
      sharedTabs.snapshot.pending.any(
        (p) =>
            p.op == 'add' &&
            p.sharedTabId == tab.sharedTabId &&
            p.machineId == machineId &&
            p.agentId == agentId,
      );

  /// Whether this account owns [tab]: its own harnesses are in it by being in
  /// the desk tab it shared, and the sharing computer refuses `share_add` and
  /// `share_remove` for them (`OWNER_PANE`; final review of 1c, I2).
  bool _ownsSharedTab(SharedTab tab) {
    final me = sharedTabs.snapshot.me?.accountId;
    return me != null && tab.ownedBy(me);
  }

  /// The leader of [deskTabId]: in a tab shared with this account the roster's
  /// (the owner's setting, re-signed by the sharing computer; none when it names
  /// none), otherwise the account's own setting.
  AgentMessageLeader? tabLeader(String deskTabId) {
    final tab = sharedTabs.tabForDesk(deskTabId);
    if (tab != null && !_ownsSharedTab(tab)) {
      final leader = tab.leader;
      return leader == null
          ? null
          : AgentMessageLeader(leader.machineId, leader.agentId);
    }
    return agentMessages.leaderOf(deskTabId);
  }

  /// Make [machineId]'s [agentId] the leader of [deskTabId]. A refusal keeps the
  /// old leader and is told in the transient notice.
  Future<void> setTabLeader(
    String deskTabId,
    String machineId,
    String agentId,
  ) => _writeLeader(deskTabId, AgentMessageLeader(machineId, agentId));

  Future<void> clearTabLeader(String deskTabId) =>
      _writeLeader(deskTabId, null);

  Future<void> _writeLeader(
    String deskTabId,
    AgentMessageLeader? leader,
  ) async {
    final auth = _authRevision;
    try {
      final answer = await api.setAgentMessageTab(
        deskTabId,
        leader: leader,
        clearLeader: leader == null,
      );
      // An answer for a session that has ended is not this one's.
      if (!_authWorkCurrent(auth)) return;
      agentMessages.applyTabSetting(
        deskTabId,
        AgentMessageLeader.fromJson(answer['leader']),
      );
    } catch (error) {
      if (!_authWorkCurrent(auth)) return;
      _lastError = error is ApiException && error.message.isNotEmpty
          ? error.message
          : 'Could not change the leader. Try again.';
      _lastErrorRetryable = false;
      notifyListeners();
    }
  }

  /// The desk tab whose panes hold this harness, or null.
  String? deskTabHolding(String machineId, String agentId) {
    for (final swarm in swarms) {
      if (swarm.panes.any(
        (p) => p.machineId == machineId && p.agentId == agentId,
      )) {
        return swarm.id;
      }
    }
    return null;
  }

  /// Whether this harness is the leader of the tab its pane is in. A leader
  /// whose pane left the tab is the leader of no pane anywhere. None while the
  /// account's Agent Messages switch is off: a leader leads only agents that
  /// may message.
  bool isTabLeader(String machineId, String agentId) {
    if (!agentMessagesOn) return false;
    final tab = deskTabHolding(machineId, agentId);
    final leader = tab == null ? null : tabLeader(tab);
    return leader != null &&
        leader.machineId == machineId &&
        leader.agentId == agentId;
  }

  /// What File, the palette and the pane offer for this harness: `'make'`,
  /// `'remove'` (it leads its tab) or null. Needs [tabActivityOffered].
  /// A member of a shared tab never chooses; its owner does, from any of its
  /// computers, among its own harnesses and the roster's members' harnesses
  /// that are panes of the tab. Another account's harness in a tab that is not
  /// shared with it is never offered.
  String? leaderActionFor(String machineId, String agentId) {
    final tabId = deskTabHolding(machineId, agentId);
    if (tabId == null || !tabActivityOffered(tabId)) return null;
    final own = machineStates[machineId]?.belongsToOtherAccount == false;
    final shared = sharedTabs.tabForDesk(tabId);
    if (shared != null) {
      if (!_ownsSharedTab(shared)) return null;
      if (!own && !_listedIn(shared, machineId, agentId)) return null;
    } else if (!own) {
      return null;
    }
    return isTabLeader(machineId, agentId) ? 'remove' : 'make';
  }

  /// Make Leader or Remove Leader for this harness, as [leaderActionFor] says.
  Future<void> toggleLeaderOf(String machineId, String agentId) async {
    final tabId = deskTabHolding(machineId, agentId);
    switch (leaderActionFor(machineId, agentId)) {
      case 'make':
        await setTabLeader(tabId!, machineId, agentId);
      case 'remove':
        await clearTabLeader(tabId!);
    }
  }

  /// The shared tab whose desk tab holds this harness, or null.
  SharedTab? sharedTabHolding(String machineId, String agentId) {
    for (final swarm in swarms) {
      if (!swarm.panes.any(
        (p) => p.machineId == machineId && p.agentId == agentId,
      )) {
        continue;
      }
      final tab = sharedTabs.tabForDesk(swarm.id);
      if (tab != null) return tab;
    }
    return null;
  }

  /// Whether Remove from Tab applies: one of the person's own harnesses that
  /// the shared tab lists, or that is still joining it, in a tab another
  /// account owns. In the tab this account shares, its harnesses follow the
  /// desk tab: moving the pane out is how one leaves.
  bool canRemoveFromSharedTab(String machineId, String agentId) {
    if (machineStates[machineId]?.belongsToOtherAccount != false) return false;
    final tab = sharedTabHolding(machineId, agentId);
    return tab != null &&
        !_ownsSharedTab(tab) &&
        _inSharedTab(tab, machineId, agentId);
  }

  /// Remove from Tab: the harness leaves the shared tab; its pane stays on the
  /// desk as an ordinary pane.
  Future<void> removeFromSharedTab(String machineId, String agentId) async {
    if (!canRemoveFromSharedTab(machineId, agentId)) return;
    await _shareAction(sharedTabHolding(machineId, agentId)!, 'share_remove', {
      'machineId': machineId,
      'agentId': agentId,
    });
  }

  /// The `share_add` for a person's pane in a shared tab; null when none is
  /// due. A refusal goes to [onFailure] when given (the Add harnesses dialog
  /// shows it), otherwise to the transient notice.
  Future<void>? _shareAddIfShared(
    String deskTabId,
    String machineId,
    String agentId, {
    void Function(SharedTabsFailure)? onFailure,
  }) {
    final tab = sharedTabs.tabForDesk(deskTabId);
    final state = machineStates[machineId];
    if (tab == null || state == null || state.belongsToOtherAccount)
      return null;
    // The owner's harnesses join by being in its desk tab.
    if (_ownsSharedTab(tab) || _listedIn(tab, machineId, agentId)) return null;
    final agent = state.agents.where((a) => a.id == agentId).firstOrNull;
    return _shareAction(tab, 'share_add', {
      'harness': {
        'machineId': machineId,
        'agentId': agentId,
        'name': agent?.displayName ?? agentId,
        'engine': agent?.engine ?? '',
      },
    }, onFailure: onFailure);
  }

  void _shareRemoveIfShared(
    String deskTabId,
    String machineId,
    String agentId,
  ) {
    final tab = sharedTabs.tabForDesk(deskTabId);
    if (tab == null ||
        _ownsSharedTab(tab) ||
        machineStates[machineId]?.belongsToOtherAccount != false ||
        !_inSharedTab(tab, machineId, agentId)) {
      return;
    }
    unawaited(
      _shareAction(tab, 'share_remove', {
        'machineId': machineId,
        'agentId': agentId,
      }),
    );
  }

  /// One add/remove for [tab]; a refusal is told in the transient notice, or
  /// handed to [onFailure] when the caller tells it itself.
  Future<void> _shareAction(
    SharedTab tab,
    String action,
    Map<String, dynamic> body, {
    void Function(SharedTabsFailure)? onFailure,
  }) async {
    try {
      await sharedTabs.act(action, {'sharedTabId': tab.sharedTabId, ...body});
    } on SharedTabsFailure catch (e) {
      if (onFailure != null) {
        onFailure(e);
        return;
      }
      if (_disposed) return;
      // The computer that is away is the one holding the harness, named when it
      // is one of the person's own.
      final holder =
          machineStates[body['machineId'] ??
              (body['harness'] as Map?)?['machineId']];
      _lastError = sharedTabErrorText(
        e,
        machine: holder != null && !holder.belongsToOtherAccount
            ? holder.machine.displayName
            : null,
      );
      _lastErrorRetryable = false;
      notifyListeners();
    }
  }

  /// Keep a group member visible while its terminal is unavailable.
  /// Takes pane [paneId] out of Swarm tab [swarmId] only: one of the person's
  /// own panes a Personal project showed behind its [term]
  /// (super_tabs/personal_projects.dart). The tab it lives in keeps it and its
  /// session, and nothing is remembered as closed.
  Future<void> releaseSuperTabView(String swarmId, int paneId) async {
    final tab = swarms
        .where((s) => s.id == swarmId && s.isSuperTab)
        .firstOrNull;
    final pane = tab?.panes.where((p) => p.id == paneId).firstOrNull;
    if (tab == null || pane == null || _disposed) return;
    final wasFocused = identical(activeSwarm, tab) && focusedPaneId == paneId;
    tab.remove(pane);
    _settlePins(tab);
    _persistLayout();
    selectedMachineId = focusedPane?.machineId;
    if (wasFocused) _announceAppFocus();
    notifyListeners();
    if (!allPanes.contains(pane)) await _detachSession(pane, sendClose: true);
  }

  /// Swarm tab [swarmId] lays out its panes as [source] does: a Personal
  /// project's panes that are exactly one tab's keep that tab's split sizes.
  void copySuperTabLayout(String swarmId, Swarm source) {
    final tab = swarms
        .where((s) => s.id == swarmId && s.isSuperTab)
        .firstOrNull;
    if (tab == null || _disposed || tab.panes.length != source.panes.length) {
      return;
    }
    final count = '${tab.panes.length}:';
    tab.presets.remove(tab.panes.length);
    if (source.presets[source.panes.length] case final preset?) {
      tab.presets[tab.panes.length] = preset;
    }
    tab.paneSizes.removeWhere((key, _) => key.startsWith(count));
    for (final MapEntry(:key, :value) in source.paneSizes.entries) {
      if (key.startsWith(count)) tab.paneSizes[key] = value;
    }
    final arranged = source.arrangedKey?.startsWith(count) == true;
    tab.arranged = arranged ? source.arranged : null;
    tab.arrangedKey = arranged ? source.arrangedKey : null;
    tab.gridColumns = source.gridColumns;
    _persistLayout();
    notifyListeners();
  }

  /// A saved arrangement for Swarm tab [swarmId]'s [count] panes (a Personal
  /// project's own, kept on this computer): what [copySuperTabLayout] takes
  /// from a tab, from a record instead.
  void applySuperTabLayout(
    String swarmId, {
    required int count,
    PanePreset? preset,
    Map<String, PaneArrangement> sizes = const {},
    String? arrangedKey,
    int? gridColumns,
  }) {
    final tab = swarms
        .where((s) => s.id == swarmId && s.isSuperTab)
        .firstOrNull;
    if (tab == null || _disposed || tab.panes.length != count) return;
    final prefix = '$count:';
    tab.presets.remove(count);
    if (preset != null && preset.supportsCount(count)) {
      tab.presets[count] = preset;
    }
    tab.paneSizes.removeWhere((key, _) => key.startsWith(prefix));
    for (final MapEntry(:key, :value) in sizes.entries) {
      if (key.startsWith(prefix) && value.tiles.length == count) {
        tab.paneSizes[key] = value;
      }
    }
    final arranged = arrangedKey == null ? null : tab.paneSizes[arrangedKey];
    tab.arranged = arranged;
    tab.arrangedKey = arranged == null ? null : arrangedKey;
    tab.gridColumns = gridColumns;
    _paneLayoutRequest++;
    _persistLayout();
    notifyListeners();
  }

  void reserveSuperTabPane(String swarmId, String machineId, String harnessId) {
    final tab = swarms
        .where((s) => s.id == swarmId && s.superTabId != null)
        .firstOrNull;
    if (tab == null || _disposed) return;
    final existing = tab.panes
        .where((p) => p.machineId == machineId && p.agentId == harnessId)
        .firstOrNull;
    if (existing != null) {
      existing.inputContext = null;
      existing.watchOnly = true;
      existing.session?.stageInputContext(null, watchOnly: true);
      unawaited(existing.session?.setInputContext(null, watchOnly: true));
      return;
    }
    if (tab.panes.length >= maxPanes) return;
    final controller = superTabs.peek(tab.superTabId!);
    if (controller?.snapshot?.agents.any(
          (a) => a.machineId == machineId && a.harnessId == harnessId,
        ) !=
        true) {
      return;
    }
    tab.panes.add(
      TerminalPane(id: _nextPaneId++, machineId: machineId, agentId: harnessId)
        ..watchOnly = true,
    );
    tab.presets.remove(tab.panes.length);
    tab.paneSizes.removeWhere(
      (key, _) => key.startsWith('${tab.panes.length}:'),
    );
    tab.arranged = null;
    tab.arrangedKey = null;
    notifyListeners();
  }

  /// Which folder each chat's Finder shows, kept so a Finder comes back
  /// beside its chat after a restart.
  late final finderRoots = FinderRoots(() => localStore);

  /// Opens a Finder tile on [root] LEFT of [agentId]'s terminal, where a
  /// harness's viewer sits: New Harness's Finder is a folder with a chat
  /// beside it, never a folder alone. It is that chat's viewer from then on
  /// ([TerminalPane.viewsAgent]) — it moves and closes with the terminal, and
  /// comes back with it ([finderRoots]). Returns why it could not open, or null.
  String? openFinderBeside(String machineId, String agentId, String root) {
    finderRoots.set(machineId, agentId, root);
    final shown = swarms.any(
      (swarm) => swarm.panes.any(
        (pane) =>
            !pane.isViewer &&
            pane.machineId == machineId &&
            pane.agentId == agentId,
      ),
    );
    if (!shown) return 'The chat closed before its Finder could open.';
    if (!_syncFinderPane(machineId, agentId)) {
      return 'This tab is full, so the Finder could not open beside the chat.';
    }
    notifyListeners();
    return null;
  }

  /// A tile's own pixel width ([TerminalPane.fixedWidth]), or null to give
  /// it back its share of the tab.
  void setPaneFixedWidth(int paneId, double? width) {
    final pane = allPanes.where((p) => p.id == paneId).firstOrNull;
    if (pane == null || pane.fixedWidth == width) return;
    pane.fixedWidth = width;
    notifyListeners();
  }

  /// Puts [agentId]'s Finder, if it has one, beside its terminal in every
  /// tab that shows that terminal without it. Whether one went in.
  bool _syncFinderPane(String machineId, String agentId) {
    final root = finderRoots.rootOf(machineId, agentId);
    if (root == null) return false;
    var changed = false;
    for (final swarm in swarms) {
      final at = swarm.panes.indexWhere(
        (pane) =>
            !pane.isViewer &&
            pane.machineId == machineId &&
            pane.agentId == agentId,
      );
      if (at < 0 ||
          swarm.panes.length >= maxPanes ||
          swarm.panes.any(
            (pane) => pane.isFinder && pane.viewsAgent(machineId, agentId),
          )) {
        continue;
      }
      _insertViewer(
        swarm,
        at,
        TerminalPane(
          id: _nextPaneId++,
          machineId: machineId,
          kind: PaneKind.finder,
          finderRoot: root,
          ownerAgentId: agentId,
        ),
      );
      changed = true;
    }
    return changed;
  }

  Future<void> assignAgentToPane(
    int? paneId,
    String machineId,
    String agentId, {
    String? swarmId,
    PaneSplitRequest? split,
    bool autoTile = false,
    bool focus = true,
    String? inputContext,
    bool watchOnly = false,

    /// A rail click, a drag, a picker — a person. The device's own doors pass
    /// [AttachIntent.automatic]: they put an agent on screen without anybody
    /// touching this Mac, so the terminal they show must not be taken from
    /// whoever is typing in it.
    AttachIntent intent = AttachIntent.person,

    /// A new tile goes right after this one, where the tab reads it, rather
    /// than at the end: a harness another harness started opens beside it.
    int? besidePaneId,

    /// Tells a refused `share_add` (a person's pane in a shared tab) to the
    /// caller instead of the transient notice; the call then waits for the
    /// daemon's answer.
    void Function(SharedTabsFailure)? onShareFailure,
  }) async {
    final target = swarms
        .where((s) => s.id == (swarmId ?? activeSwarmId))
        .firstOrNull;
    if (target == null || _disposed) return;
    if (split != null &&
        (split.swarmId != target.id ||
            paneId != null ||
            !isPaneSplitCurrent(split))) {
      return;
    }
    final targetPanes = target.panes;
    final machine = machineStates[machineId];
    if (machine == null) return;

    Agent? agent;
    for (final candidate in machine.agents) {
      if (candidate.id == agentId) {
        agent = candidate;
        break;
      }
    }
    if (agent == null) return;

    final shared = allPanes
        .where((p) => p.machineId == machineId && p.agentId == agentId)
        .firstOrNull;
    final existing = targetPanes
        .where((p) => p.machineId == machineId && p.agentId == agentId)
        .firstOrNull;
    if (paneId == null && existing != null) {
      existing.inputContext = inputContext;
      existing.watchOnly = watchOnly;
      await existing.session?.setInputContext(
        inputContext,
        watchOnly: watchOnly,
      );
      if (existing.session == null && target == activeSwarm) {
        await _attachSession(existing, intent: intent);
      }
      if (focus && target == activeSwarm) focusPane(existing.id);
      // A pane a refused share_add left unshared: a person's retry shares it.
      if (intent == AttachIntent.person) {
        final retry = _shareAddIfShared(
          target.id,
          machineId,
          agentId,
          onFailure: onShareFailure,
        );
        if (retry != null) {
          if (onShareFailure == null) {
            unawaited(retry);
          } else {
            await retry;
          }
        }
      }
      return;
    }
    final replaced = targetPanes.where((p) => p.id == paneId).firstOrNull;
    if (replaced == shared && shared != null) {
      shared.inputContext = inputContext;
      shared.watchOnly = watchOnly;
      await shared.session?.setInputContext(inputContext, watchOnly: watchOnly);
      if (focus && target == activeSwarm) focusPane(shared.id);
      return;
    }
    if (replaced == null &&
        existing == null &&
        targetPanes.length >= maxPanes) {
      _lastError =
          'This tab holds $maxPanes harnesses. Open another tab to add more.';
      _lastErrorRetryable = false;
      notifyListeners();
      return;
    }
    // A shared desk tab holds the desk's 9 harnesses: a 10th would never
    // reach the desk ([deskTabFull]). Placement asks quietly and tries again
    // later; a person is told.
    if (existing == null && replaced?.agentId == null && deskTabFull(target)) {
      if (intent == AttachIntent.person) {
        _lastError =
            'This tab holds ${PaneLayoutStore.maxPanes} harnesses. Close one, then try again.';
        _lastErrorRetryable = false;
        notifyListeners();
      }
      return;
    }
    final beside = replaced == null && split == null && besidePaneId != null
        ? targetPanes.where((p) => p.id == besidePaneId).firstOrNull
        : null;
    if (beside != null) {
      // The tab's reading order first, as `Swarm.remove` does: the reflow
      // below lays the list out in order, and a split earlier in the tab's
      // life may have put the list out of step with what the person sees.
      final ordered = target.panesInReadingOrder;
      targetPanes
        ..clear()
        ..addAll(ordered);
    }
    final insertion = replaced == null
        ? split == null
              ? beside == null
                    ? targetPanes.length
                    : targetPanes.indexOf(beside) + 1
              : split.paneIds.indexOf(split.paneId) + 1
        : targetPanes.indexOf(replaced);
    final pendingLayout =
        replaced != null && !replaced.isViewer && replaced.agentId == null
        ? target.manualLayout
        : null;
    if (existing != null) target.remove(existing);
    if (replaced != null) target.remove(replaced);
    final pane =
        shared ??
        TerminalPane(id: _nextPaneId++, machineId: machineId, agentId: agentId);
    pane.inputContext = inputContext;
    pane.watchOnly = watchOnly;
    pane.session?.stageInputContext(inputContext, watchOnly: watchOnly);
    final firstAgent = targetPanes.every((pane) => pane.agentId == null);
    if (machine.machine.isShared) {
      pane.sharedHarness = machine.machine.sharedHarnesses
          .where((g) => g.agentId == agentId)
          .firstOrNull;
      pane.sharedOwnerName = machine.machine.ownerName;
    }
    targetPanes.insert(insertion.clamp(0, targetPanes.length), pane);
    // Only a person's drop or New Harness puts a harness into a shared tab for
    // the others; placement and the desk's reconcile never do.
    Future<void>? shareAdd;
    if (intent == AttachIntent.person && existing == null) {
      shareAdd = _shareAddIfShared(
        target.id,
        machineId,
        agentId,
        onFailure: onShareFailure,
      );
      if (onShareFailure == null && shareAdd != null) {
        unawaited(shareAdd);
        shareAdd = null;
      }
    }
    // Attaching a conversation to a reserved slot is not a layout removal.
    if (pendingLayout != null &&
        pendingLayout.tiles.length == targetPanes.length) {
      target.savePaneSizes('${targetPanes.length}:manual', pendingLayout);
    }
    if (autoTile && split == null) {
      // A new pane reflows the whole tab. Old manual splits and remembered
      // sizes for this count must not silently override automatic placement.
      target.presets.remove(targetPanes.length);
      target.paneSizes.removeWhere(
        (key, _) => key.startsWith('${targetPanes.length}:'),
      );
      target.arranged = null;
      target.arrangedKey = null;
    }
    if (beside != null) {
      // Pins stay with their panes, wherever the new tile moved them.
      target.pinnedSlots.updateAll(
        (id, _) => targetPanes.indexWhere((p) => p.id == id),
      );
    }
    if (split != null) {
      target.pinnedSlots.updateAll(
        (_, slot) => slot >= insertion ? slot + 1 : slot,
      );
      final key = '${targetPanes.length}:manual';
      final after = _balancedIfAsked(split.after, target.arrangedMinimum);
      target.savePaneSizes(key, after);
      target.arranged = after;
      target.arrangedKey = key;
    }
    if (firstAgent &&
        !target.nameIsCustom &&
        !target.isSuperTab &&
        !target.isProjectTab &&
        !target.isCompanions &&
        !target.isDevices) {
      final agent = machine.agents
          .where((agent) => agent.id == agentId)
          .firstOrNull;
      target.titleMachineId = machineId;
      target.titleAgentId = agentId;
      target.name = Swarm.titleFor(agent);
    }
    if (replaced != null && !allPanes.contains(replaced)) {
      // Release just the desktop stream. The CLI agent process keeps running.
      unawaited(_detachSession(replaced, sendClose: true));
    }

    if (focus) {
      target.focusedPaneId = pane.id;
      target.zoomedPaneId = null;
      if (target == activeSwarm) {
        selectedMachineId = machineId;
        // A manual split can grow the canvas beyond the viewport. Announce
        // its reveal just as opening an existing pane does, before notifying.
        if (split != null) _paneFocusRequest++;
      }
    }
    _dismissedLinkPrompts.remove(machineId);
    if (focus) machine.activeAgentId = agentId;
    _persistLayout();
    // SAID OUTRIGHT, like every other move.
    //
    // This path — a rail click on an agent with no tile — was the one that never said it. It relied on
    // the daemon inferring the move from the `terminal_open` that follows, which is the old
    // one-terminal-per-window equivalence [see _announceAppFocus]. Two things wrong with that: the
    // roster below changes the dial's carousel, so the focus and the roster are one transaction and the
    // inference arrives after it by luck; and every early return under here (machine offline, terminal
    // capability missing, a session already attached) opens no stream at all, so nothing was ever sent
    // and the dial stayed on the old agent with the window on the new one.
    //
    // After _persistLayout, so the daemon has the new tile roster before it is told to move onto it. A
    // duplicate with the inferred one is free: the daemon drops the second against where the dial
    // already is.
    if (focus && target == activeSwarm) _announceAppFocus();
    // A new tile takes the focus without passing [focusPane], so the open is
    // said here — for a person's add only, never a device's door.
    if (focus &&
        target == activeSwarm &&
        intent == AttachIntent.person &&
        !_navigatingFromDevice) {
      _touchFocusedAgent();
    }
    // The agent may already have a viewer the grid could not show until now,
    // because this tile is what it hangs beside.
    _syncViewerPane(machine, agent);
    // The caller that tells a refusal itself waits for the daemon's answer.
    if (shareAdd != null) await shareAdd;

    if (machine.nodeOnline == false) {
      machine.pendingOfflineAgentId = agentId;
      _startOfflineRetry(machine);
      notifyListeners();
      return;
    }
    if (!machine.terminalCapabilityAvailable) {
      notifyListeners();
      return;
    }
    machine.pendingOfflineAgentId = null;
    _stopOfflineRetry(machineId);
    notifyListeners();
    if (target == activeSwarm || pane.session != null) {
      if (pane.session case final session?) {
        await session.setInputContext(inputContext, watchOnly: watchOnly);
      }
      await _attachSession(pane, intent: intent);
    }
  }

  /// How this window introduces itself on `terminal_open`, so a pane it
  /// displaces elsewhere can say "(this Mac) took control": this computer's
  /// machine in the fleet, by id and current name, else the hostname. A viewer
  /// (read-only) never takes control and so declares nothing.
  TerminalClientDescriptor? localClientDescriptor() {
    if (viewer != null) return null;
    final local = machineStates.values
        .where((state) => state.isLocalMachine)
        .firstOrNull
        ?.machine;
    final name = local?.displayName ?? localHostnameOrNull() ?? 'Desktop';
    return TerminalClientDescriptor(
      kind: 'desktop',
      name: name.length > TerminalClientDescriptor.nameMax
          ? name.substring(0, TerminalClientDescriptor.nameMax)
          : name,
      machineId: local?.machineId,
    );
  }

  /// Open the stream for a tile that already knows what it wants.
  ///
  /// Separate from [assignAgentToPane] because a restored tile takes this path
  /// on its own, later, when its machine finally answers — the intent was
  /// settled at launch, and nothing about the selection should move again then.
  Future<void> _attachSession(
    TerminalPane pane, {
    AttachIntent intent = AttachIntent.person,
  }) async {
    if (_disposed || !allPanes.contains(pane) || pane.session != null) return;
    final wantedAgentId = pane.agentId;
    if (wantedAgentId == null) return;
    final machine = machineStates[pane.machineId];
    if (machine == null) return;
    if (machine.machine.isShared) {
      pane.sharedHarness = machine.machine.sharedHarnesses
          .where((g) => g.agentId == wantedAgentId)
          .firstOrNull;
      pane.sharedOwnerName = machine.machine.ownerName;
      notifyListeners();
      return;
    }
    if (machine.nodeOnline == false) return;
    if (!machine.terminalCapabilityAvailable) return;

    Agent? agent;
    for (final candidate in machine.agents) {
      if (candidate.id == wantedAgentId) {
        agent = candidate;
        break;
      }
    }
    if (agent == null || !agent.terminalAvailable) return;

    final terminal = TerminalSession(
      machineId: pane.machineId,
      agentId: agent.id,
      agentName: agent.displayName,
      engineId: agent.engine,
      client: localClientDescriptor(),
      inputContext: pane.inputContext,
      watchOnly: pane.watchOnly,
      // Only a person at this window may take the terminal from whoever holds
      // it; everything else opens as a watcher. See [AttachIntent].
      takeover: intent == AttachIntent.person,
      send: (type, payload) =>
          _conn(pane.machineId).sendTerminalFrame(type, payload),
      sendBinary: (frame) => _sendTerminalBinary(pane.machineId, frame),
      onOpenStalled: () => _forceRedial(pane.machineId),
      // A `terminal_open` can round-trip app → local CLI → (for a relayed
      // machine) the E2EE relay → the remote peer → tmux → back, possibly
      // negotiating P2P on the way, so a cold open legitimately takes several
      // seconds. Give the open watchdog 15s before it forces a full redial, so
      // a merely slow open is not mistaken for a stale session and re-dialled
      // needlessly; the forced-reconnect recovery still runs if it elapses.
      resyncTimeout: const Duration(seconds: 15),
    );
    pane.session = terminal;
    terminal.addListener(_onSessionChanged);
    notifyListeners();
    // Wait for the pane's actual measured viewport before asking the daemon to open anything.
    // Sending the 80x24 fallback here used to make the daemon spawn the remote TTY (and render its
    // first keyframe) at that wrong size, which then had to be corrected by a resize round trip —
    // visible as the terminal's content briefly rendering narrow before snapping to full width. The
    // blank "Attaching…" placeholder already covers this measurement, which lands within a frame or
    // two of the panel mounting; `waitForViewportSize`'s own 2s timeout falls back to 80x24 only if
    // the pane genuinely never gets laid out.
    await terminal.open(waitForViewportSize: true);
  }

  // File delivery for a new background harness uses the same native terminal
  // protocol, without manufacturing a pane or changing the selected group.
  final _attachmentSessions = <TerminalSession>{};

  Iterable<TerminalSession> _terminalSessionsFor(String machineId) sync* {
    yield* panesFor(machineId).map((p) => p.session).nonNulls;
    yield* _attachmentSessions.where((s) => s.machineId == machineId);
  }

  void _closeAttachmentSessions() {
    final sessions = _attachmentSessions.toList();
    _attachmentSessions.clear();
    for (final session in sessions) {
      unawaited(session.close().whenComplete(session.dispose));
    }
  }

  Future<String?> deliverBackgroundAttachments({
    required String machineId,
    required String agentId,
    required List<HarnessAttachment> files,
    required String task,
  }) async {
    final machine = machineStates[machineId];
    final revision = _authRevision, account = currentUser?.id;
    bool current() =>
        currentUser?.id == account &&
        machine != null &&
        _machineWorkCurrent(machine, revision);
    if (!current() || machine!.machine.isShared) {
      return 'This machine is no longer available for file delivery.';
    }
    if (!machine.agents.any((a) => a.id == agentId)) {
      await _loadMachineData(machine, force: true);
    }
    if (!current()) return 'The account changed. No files were sent.';
    final agent = machine.agents.where((a) => a.id == agentId).firstOrNull;
    if (agent == null) {
      return 'The new harness is not available on its machine.';
    }
    final existing = panesFor(machineId)
        .where((p) => p.agentId == agentId)
        .map((p) => p.session)
        .nonNulls
        .firstOrNull;
    final connection = _conn(machineId);
    final session =
        existing ??
        TerminalSession(
          machineId: machineId,
          agentId: agentId,
          agentName: agent.displayName,
          engineId: agent.engine,
          client: localClientDescriptor(),
          takeover: true,
          send: (type, payload) => current() || type == 'terminal_close'
              ? connection.sendTerminalFrame(type, payload)
              : Future.value(false),
          sendBinary: (frame) {
            if (!current()) return Future.value(false);
            final bytes = encodeTerminalLocal(frame);
            return bytes == null
                ? Future.value(false)
                : connection.sendTerminalBinary(bytes);
          },
          onOpenStalled: () async {
            if (current()) await _forceRedial(machineId);
          },
          resyncTimeout: const Duration(seconds: 15),
        );
    if (existing == null) _attachmentSessions.add(session);
    try {
      if (existing == null) await session.open();
      return await deliverAttachedTask(
        this,
        machineId: machineId,
        agentId: agentId,
        files: files,
        task: task,
        terminal: session,
        stillWanted: current,
      );
    } finally {
      if (_attachmentSessions.remove(session)) {
        try {
          await session.close();
        } finally {
          session.dispose();
        }
      }
    }
  }

  Future<void> _detachSession(
    TerminalPane pane, {
    required bool sendClose,
  }) async {
    final terminal = pane.session;
    pane.session = null;
    if (terminal == null) return;
    terminal.removeListener(_onSessionChanged);
    try {
      if (sendClose) await terminal.close();
    } finally {
      terminal.dispose();
    }
  }

  /// Take a tile off the grid.
  ///
  /// Closing sends `terminal_close`, which is what lets the daemon put the
  /// agent's tmux window back to the size it had before this app borrowed it —
  /// a tile that vanished without saying so would leave that agent living in a
  /// quarter-width terminal.
  /// Put the pane at [paneId] where [targetPaneId] is, and that one where this
  /// one was.
  ///
  /// A SWAP, not an insert. Position here is nothing but the index in [panes] —
  /// PaneGrid lays the list out row-major — and on a 2x2 grid "between two
  /// cells" names no place, so shifting the others would move tiles the user
  /// did not touch. Swapping leaves every other tile exactly where it was.
  ///
  /// Focus follows the PANE, not the slot: `focusedPaneId` is an id, so a tile
  /// that was focused stays focused after it moves, which is what the hand that
  /// dragged it expects.
  /// The arrangement after [paneId] lands on [side] of [targetPaneId]; null
  /// when it can't, or when it is already there.
  PaneArrangement? _moveBesideShape(
    int paneId,
    int targetPaneId,
    PaneSide side,
  ) {
    if (paneId == targetPaneId || zoomedPaneId != null) return null;
    if (activeSwarm.isUtility || activeSwarm.isOrchestrator) return null;
    final shape = activeTileShape;
    final from = panes.indexWhere((pane) => pane.id == paneId);
    final to = panes.indexWhere((pane) => pane.id == targetPaneId);
    if (shape == null || from == -1 || to == -1) return null;
    final current = PaneArrangement(shape);
    if (current.isBeside(from, to, side)) return null;
    final minimum = activeSwarm.arrangedMinimum ?? Size.zero;
    final moved = current.moveBeside(from, to, side, minimum: minimum);
    if (moved != null) return moved;
    // A layout whose hole no neighbour can fill: the rest fall back to their
    // count's shape, as closing a pane there does, so an edge always moves it.
    final rest = panes.length - 1;
    final tiles = (presetFor(rest) ?? PanePreset.defaultFor(rest))?.tilesFor(
      rest,
    );
    if (tiles == null || tiles.length != rest) return null;
    return PaneArrangement(tiles)
        .fillRowEnds()
        .split(to > from ? to - 1 : to, side.axis, minimum: minimum);
  }

  /// Whether [paneId] is already on [side] of [targetPaneId], so a drop there
  /// changes nothing.
  bool isPaneBeside(int paneId, int targetPaneId, PaneSide side) {
    final shape = activeTileShape;
    final from = panes.indexWhere((pane) => pane.id == paneId);
    final to = panes.indexWhere((pane) => pane.id == targetPaneId);
    if (shape == null || from == -1 || to == -1 || from == to) return false;
    return PaneArrangement(shape).isBeside(from, to, side);
  }

  /// Whether a drop on [side] of [targetPaneId] can land [paneId] there.
  bool canMovePaneBeside(int paneId, int targetPaneId, PaneSide side) =>
      _moveBesideShape(paneId, targetPaneId, side) != null;

  /// Dragging a pane to another's edge: it takes half of that pane's room, as
  /// the TUI's join-pane does, and its sessions stay untouched.
  bool movePaneBeside(int paneId, int targetPaneId, PaneSide side) {
    final next = _moveBesideShape(paneId, targetPaneId, side);
    if (next == null) return false;
    final moved = panes.removeAt(panes.indexWhere((p) => p.id == paneId));
    final target = panes.indexWhere((p) => p.id == targetPaneId);
    panes.insert(side.before ? target : target + 1, moved);
    // Pins stay with their panes, wherever the list moved them.
    for (final (slot, pane) in panes.indexed) {
      if (isPanePinned(pane)) _setPin(pane, slot);
    }
    final key = '${panes.length}:manual';
    final after = _balancedIfAsked(next, activeSwarm.arrangedMinimum);
    activeSwarm.savePaneSizes(key, after);
    activeSwarm.arranged = after;
    activeSwarm.arrangedKey = key;
    _paneLayoutRequest++;
    _persistLayout();
    notifyListeners();
    return true;
  }

  /// [arrangement] evened out when Autobalance splits is on.
  PaneArrangement _balancedIfAsked(
    PaneArrangement arrangement,
    Size? minimum,
  ) => appearancePrefsStore.value.panes.autobalanceSplits
      ? arrangement.balanced(minimum: minimum ?? Size.zero)
      : arrangement;

  void reorderPane(int paneId, int targetPaneId, {bool reveal = false}) {
    if (paneId == targetPaneId) return;
    final from = panes.indexWhere((pane) => pane.id == paneId);
    final to = panes.indexWhere((pane) => pane.id == targetPaneId);
    if (from == -1 || to == -1) return;
    final moved = panes[from];
    panes[from] = panes[to];
    panes[to] = moved;
    // The pin follows the hand. A pinned tile dragged elsewhere is someone
    // saying "here now", and a pinned tile displaced by another drag was still
    // put there deliberately — bouncing either back would make the drag look
    // broken while the state was in fact correct.
    if (isPanePinned(panes[to])) _setPin(panes[to], to);
    if (isPanePinned(panes[from])) _setPin(panes[from], from);
    if (reveal && focusedPaneId == paneId) _paneFocusRequest++;
    _persistLayout();
    notifyListeners();
  }

  /// How many columns the grid last laid out.
  ///
  /// Only `auto` needs telling: it measures the window, so it is the one shape
  /// whose columns are not in its own description. Reported by the grid as it
  /// builds; null until then, and then the shape's own guess stands.
  /// The rectangles the active swarm's tiles actually occupy, as fractions of
  /// the grid — a manual arrangement when there is one, the chosen preset
  /// otherwise, and null when neither can describe this many panes.
  ///
  /// Written once and read from every place that needs to know where a tile is:
  /// the two wrap helpers, the neighbour walk, and the cable. It used to be
  /// copied out at each of those, which is the bug `pane_preset.dart` opens by
  /// warning about — a shape described twice drifts, and the copy on the cable
  /// would have drifted onto another screen.
  List<Rect>? get activeTileShape {
    final count = panes.length;
    if (count < 1) return null;
    final shape = activeSwarm.arranged?.tiles.length == count
        ? activeSwarm.arranged!.tiles
        : presetFor(count)?.tilesFor(count, columns: gridColumns);
    return (shape != null && shape.length == count) ? shape : null;
  }

  int? get gridColumns => activeSwarm.gridColumns;
  set gridColumns(int? value) => activeSwarm.gridColumns = value;

  bool hasNavigationRail = true;

  /// Focus the tile above or below the focused one — ⌘↑ / ⌘↓.
  ///
  /// SPATIAL, unlike the left/right pair, which walks the tiles in order. Down
  /// from the top-left of a 2×2 is the tile under it, not the next one along,
  /// because that is what the arrow is pointing at. The shapes are read from
  /// [PanePreset.tilesFor] — the same rectangles the layout is built from and
  /// the picker draws — so this cannot describe a grid the app does not build.
  ///
  /// Nothing above or below (a single row, or the edge) leaves the focus where
  /// it is: an arrow that wraps to the far side of the screen reads as a jump,
  /// not as a step.
  void focusPaneVertically(int delta) {
    if (_enterGridFromTabStrip()) return;
    final to = _neighbour(dx: 0, dy: delta) ?? _wrapVertically(delta);
    if (to != null) focusPane(panes[to].id, reveal: true);
  }

  /// The tile at the far end of this column — ⌘j off the bottom row, ⌘k off the
  /// top.
  ///
  /// IN COLUMN, not in list order. Wrapping to `panes.first` from the bottom
  /// right of a 2x2 would jump a column as well as a row, which reads as the key
  /// having misfired rather than as having come round. This finds the tile that
  /// still overlaps ours horizontally and sits furthest in the direction pressed
  /// — the one directly above or below, as far as it goes.
  int? _wrapVertically(int delta) {
    final count = panes.length;
    if (count < 2) return null;
    final shape = activeTileShape;
    if (shape == null) return null;
    final at = panes.indexWhere((pane) => pane.id == focusedPaneId);
    if (at < 0) return null;

    final from = shape[at];
    int? best;
    double bestEdge = 0;
    for (var i = 0; i < count; i++) {
      if (i == at) continue;
      final to = shape[i];
      if ((from.right < to.left + 0.001) || (to.right < from.left + 0.001)) {
        continue;
      }
      // Going DOWN wraps to the topmost; going up, to the bottom-most.
      final edge = delta > 0 ? -to.top : to.top;
      if (best == null || edge > bestEdge) {
        bestEdge = edge;
        best = i;
      }
    }
    return best;
  }

  /// ⌘h / ⌘l, and ⌘← / ⌘→ — the tile beside this one, by POSITION.
  ///
  /// Spatial, like its vertical twin, and that is a change: left and right used
  /// to walk the panes in list order while up and down read the geometry, so
  /// half the compass answered "the next one" and half answered "the one over
  /// there". A vim user pressing `l` means the window to their right, and a
  /// scheme that means it in two directions out of four is one nobody can hold.
  void focusPaneHorizontally(int delta) {
    // THE RAIL IS A SEAT IN THE RING, not a wall at one end of it.
    //
    // No new key for "go to the sidebar": the sidebar is what is to the left of
    // the leftmost tile, so the key that means left already says it — the motion
    // vim users have, where `Ctrl-w h` out of the last split does not stop, it
    // reaches the next thing.
    //
    // And the ring CLOSES. Walking off either edge seats you in the rail, and
    // walking out of the rail continues round to the far side: left out of it
    // lands on the last tile, right onto the first. A ring that stopped dead at
    // one end would make the same key mean "go left" in the middle of the grid
    // and "do nothing" at its edge, which is a key people stop trusting.
    if (_enterGridFromTabStrip()) return;
    if (railFocused) {
      if (panes.isEmpty) return;
      unfocusRail();
      focusPane(delta < 0 ? panes.last.id : panes.first.id, reveal: true);
      return;
    }
    final to = _neighbour(dx: delta, dy: 0);
    if (to != null) {
      focusPane(panes[to].id, reveal: true);
      return;
    }
    if (hasNavigationRail) focusRail();
    // An EMPTY rail is not a seat, so the ring skips it rather than stopping on
    // it. focusRail refuses when there is nothing to put a cursor on — no
    // machines yet, or a list that has not loaded — and without this the key
    // would simply do nothing at the edge, which is the exact behaviour the ring
    // exists to remove.
    if (!railFocused && panes.isNotEmpty) {
      focusPane(delta < 0 ? panes.last.id : panes.first.id, reveal: true);
    }
  }

  /// Shift-Command-arrows put this pane where its neighbour is, and that one here.
  ///
  /// A SWAP, not an insert. vim's `Ctrl-w H/J/K/L` — the capitals this mirrors —
  /// moves a window to the far edge, which needs a tree of splits to mean
  /// anything; this grid is a list of slots rendered into a shape, so the honest
  /// equivalent is to trade places with whoever is in the direction pressed.
  void movePaneDirection({required int dx, required int dy}) {
    final id = focusedPaneId;
    if (id == null) return;
    final to = _neighbour(dx: dx, dy: dy);
    if (to == null) return;
    reorderPane(id, panes[to].id, reveal: true);
  }

  /// The index of the tile in the given direction, or null at the edge.
  ///
  /// Reads the laid-out RECTANGLES rather than the list, so "left" means left on
  /// screen whatever order the panes happen to be in. The two rules that make it
  /// honest: the neighbour has to actually be on that side (a tile whose edge is
  /// level with ours is not beside us), and the two have to OVERLAP on the other
  /// axis — otherwise the tile diagonally across counts as "down", which is how
  /// a 2x2 ends up with a key that moves like a knight.
  int? _neighbour({required int dx, required int dy}) {
    final count = panes.length;
    if (count < 2) return null;
    final shape = activeTileShape;
    if (shape == null) return null;
    final at = panes.indexWhere((pane) => pane.id == focusedPaneId);
    if (at < 0) return null;

    final from = shape[at];
    int? best;
    double bestGap = double.infinity;
    for (var i = 0; i < count; i++) {
      if (i == at) continue;
      final to = shape[i];
      final double gap;
      final bool apart;
      if (dy != 0) {
        gap = dy > 0 ? to.top - from.top : from.top - to.top;
        apart =
            (from.right < to.left + 0.001) || (to.right < from.left + 0.001);
      } else {
        gap = dx > 0 ? to.left - from.left : from.left - to.left;
        apart =
            (from.bottom < to.top + 0.001) || (to.bottom < from.top + 0.001);
      }
      if (gap <= 0.001 || apart) continue;
      if (gap < bestGap) {
        bestGap = gap;
        best = i;
      }
    }
    return best;
  }

  /// The pane focused before this one, used by the remappable `pane.last`
  /// command to switch between two agents without walking the whole layout.
  int? get _previousPaneId => activeSwarm.previousPaneId;
  set _previousPaneId(int? value) => activeSwarm.previousPaneId = value;

  void focusLastPane() {
    if (_enterGridFromTabStrip()) return;
    final back = _previousPaneId;
    if (back == null) return;
    if (!panes.any((pane) => pane.id == back)) {
      // It was closed while we were away. Say nothing and stay put — jumping
      // somewhere arbitrary is worse than a key that did not fire.
      _previousPaneId = null;
      return;
    }
    focusPane(back, reveal: true);
  }

  /// ⌘⏎ — one pane filling the grid, and back.
  ///
  /// The id is held rather than a flag, so a zoom SURVIVES the thing that
  /// usually breaks this: focus moving. Zoomed on tile 3 and then jumping to
  /// tile 5 shows tile 5 zoomed, which is what tmux does and what the eye
  /// expects; a boolean would have shown tile 3 while the focus was elsewhere.
  int? get zoomedPaneId => activeSwarm.zoomedPaneId;
  set zoomedPaneId(int? value) => activeSwarm.zoomedPaneId = value;

  void toggleZoomPane() {
    if (activeSwarm.isSuperTab) return;
    final id = focusedPaneId;
    if (id == null || panes.length < 2) return;
    zoomedPaneId = zoomedPaneId == id ? null : id;
    _persistLayout();
    _announceVisibleAgents();
    notifyListeners();
  }

  /// Focus the nth tile on the grid — ⌘1…⌘9.
  ///
  /// The number is the tile's position on screen, which is also the number the
  /// dial walks, so "the third one" means one thing wherever it is said. A digit
  /// past the last tile does NOTHING: it used to address the sidebar instead,
  /// where ⌘3 opened an agent that was not on the grid and replaced a tile to
  /// show it — a key meant only to look, rearranging the desk.
  void focusPaneByIndex(int index) {
    if (index < 0 || index >= panes.length) return;
    focusPane(panes[index].id, reveal: true);
  }

  /// Walk the focus one tile — ⌘← / ⌘→, and ⌘[ / ⌘].
  ///
  /// Wraps, because the grid is what the eye reads as a loop of tiles; stopping
  /// dead at the last one reads as a broken key. Moves focus ONLY — nothing on
  /// the grid changes, which is what separates it from [movePaneBy].
  void focusPaneBy(int delta) {
    if (_enterGridFromTabStrip()) return;
    if (panes.length < 2) return;
    final at = panes.indexWhere((pane) => pane.id == focusedPaneId);
    final next = at < 0 ? 0 : (at + delta + panes.length) % panes.length;
    focusPane(panes[next].id, reveal: true);
  }

  /// Move the focused pane one slot, for the keyboard twin of the drag.
  ///
  /// Stops at the ends rather than wrapping: the grid is a shape, not a ring,
  /// and a tile jumping from the last slot to the first reads as a bug.
  void movePaneBy(int delta) {
    final id = focusedPaneId;
    if (id == null) return;
    final from = panes.indexWhere((pane) => pane.id == id);
    if (from == -1) return;
    final to = from + delta;
    if (to < 0 || to >= panes.length) return;
    reorderPane(id, panes[to].id, reveal: true);
  }

  /// Pin this tile to the slot it is in, or let it go.
  ///
  /// Pinning records the CURRENT slot rather than asking for one: the tile the
  /// user is looking at is the answer they mean, and a dialog asking "which
  /// number?" would be arithmetic about a thing they can already see.
  int? pinnedSlotFor(TerminalPane pane) =>
      hasNavigationRail ? pane.pinnedSlot : activeSwarm.pinnedSlots[pane.id];

  bool isPanePinned(TerminalPane pane) => pinnedSlotFor(pane) != null;

  void _setPin(TerminalPane pane, int? slot) {
    if (slot == null) {
      activeSwarm.pinnedSlots.remove(pane.id);
    } else {
      activeSwarm.pinnedSlots[pane.id] = slot;
    }
    if (hasNavigationRail) pane.pinnedSlot = slot;
  }

  void togglePinPane(int paneId) {
    final index = panes.indexWhere((pane) => pane.id == paneId);
    if (index == -1) return;
    final pane = panes[index];
    _setPin(pane, isPanePinned(pane) ? null : index);
    _persistLayout();
    notifyListeners();
  }

  /// Put pinned tiles back in their slots after the list moved under them.
  ///
  /// Lifted rather than swapped: after a close everyone has slid up one, and
  /// lifting the pinned tile back into its slot leaves that slide intact for
  /// every other tile. A swap would instead fling whichever tile inherited the
  /// slot to the far end of the grid — one close, two tiles moved, and only one
  /// of them explicable.
  ///
  /// A pin past the end of a shrunken grid is HELD, not dropped: the tiles that
  /// closed can come back, and forgetting the pin the moment the grid got small
  /// would quietly undo a choice the user never revisited.
  void _settlePins([Swarm? target]) {
    final tab = target ?? activeSwarm;
    final members = tab.panes;
    int? slot(TerminalPane pane) =>
        hasNavigationRail ? pane.pinnedSlot : tab.pinnedSlots[pane.id];
    final pinned = members.where((pane) => slot(pane) != null).toList()
      ..sort((a, b) => slot(a)!.compareTo(slot(b)!));
    for (final pane in pinned) {
      final want = slot(pane)!;
      if (want >= members.length) continue;
      final at = members.indexOf(pane);
      if (at == want) continue;
      members.removeAt(at);
      members.insert(want, pane);
    }
  }

  /// Move a pane to another tab, terminal and all.
  ///
  /// The tile is the SAME [TerminalPane] on the other side — never a fresh one
  /// — which is what keeps the terminal attached: the session hangs off the
  /// pane ([TerminalPane.session]), the cell is a `GlobalKey`, and
  /// `TerminalPanel` is built to survive a change of tab without remounting.
  /// Closing here and opening there would tear the session down and ask the
  /// daemon to open it again, losing the viewport and the scrollback.
  ///
  /// Refuses rather than half-moves: an unknown pane or tab, the tab it is
  /// already on, and a destination at [maxPanes] all leave everything as it
  /// was, the last one with the same message [assignAgentToPane] gives.
  ///
  /// A destination already showing this agent takes the move as a plain close
  /// here — one membership per tab, the rule [assignAgentToPane] keeps.
  bool movePaneToSwarm(
    int paneId,
    String swarmId, {
    bool follow = true,
    String? sourceSwarmId,
  }) {
    final source = sourceSwarmId == null
        ? activeSwarm
        : swarms.where((swarm) => swarm.id == sourceSwarmId).firstOrNull;
    final pane = source?.panes.where((p) => p.id == paneId).firstOrNull;
    final target = swarms.where((swarm) => swarm.id == swarmId).firstOrNull;
    if (source == null ||
        pane == null ||
        target == null ||
        target.id == source.id) {
      return false;
    }
    final twin = pane.agentId == null
        ? null
        : target.panes
              .where(
                (p) =>
                    p.machineId == pane.machineId && p.agentId == pane.agentId,
              )
              .firstOrNull;
    if (twin == null &&
        (target.panes.length >= maxPanes ||
            (pane.agentId != null && deskTabFull(target)))) {
      final most = target.panes.length >= maxPanes
          ? maxPanes
          : PaneLayoutStore.maxPanes;
      _lastError =
          'That tab holds $most harnesses. Close one there to move this in.';
      _lastErrorRetryable = false;
      notifyListeners();
      return false;
    }
    source.remove(pane);
    // Into a shared tab the harness joins it; out of one it leaves it.
    if (!pane.isWeb && pane.agentId != null) {
      _shareRemoveIfShared(source.id, pane.machineId, pane.agentId!);
      if (twin == null) {
        final add = _shareAddIfShared(target.id, pane.machineId, pane.agentId!);
        if (add != null) unawaited(add);
      }
    }
    // A harness's viewer lives beside its terminal, so it travels with it —
    // the same rule `closePane` keeps when the terminal goes.
    final viewers = <TerminalPane>[];
    if (!pane.isWeb && pane.agentId != null) {
      for (final viewer in source.panes.toList()) {
        if (viewer.viewsAgent(pane.machineId, pane.agentId)) {
          source.remove(viewer);
          viewers.add(viewer);
        }
      }
    }
    if (twin == null) {
      final firstAgent = target.panes.every((pane) => pane.agentId == null);
      target.panes.add(pane);
      // A tab that had no harness in it takes this one's name, the way it
      // would for a harness opened into it.
      if (firstAgent &&
          !target.nameIsCustom &&
          !target.isSuperTab &&
          !target.isProjectTab &&
          pane.agentId != null) {
        final agent = machineStates[pane.machineId]?.agents
            .where((agent) => agent.id == pane.agentId)
            .firstOrNull;
        target.titleMachineId = pane.machineId;
        target.titleAgentId = pane.agentId;
        target.name = Swarm.titleFor(agent);
      }
      for (final viewer in viewers) {
        if (target.panes.length >= maxPanes) break;
        target.panes.add(viewer);
      }
      // The destination reflows for a tile it has never held, exactly as it
      // would for a new one: remembered shapes for the old count cannot decide
      // where this lands.
      target.presets.remove(target.panes.length);
      target.paneSizes.removeWhere(
        (key, _) => key.startsWith('${target.panes.length}:'),
      );
      target.arranged = null;
      target.arrangedKey = null;
      if (target.focusedPaneId != pane.id) {
        target.previousPaneId = target.focusedPaneId;
        target.focusedPaneId = pane.id;
      }
      if (target.zoomedPaneId != null) target.zoomedPaneId = pane.id;
    }
    _settlePins();
    if (follow) {
      _activeSwarmId = target.id;
      railFocused = false;
      // Placement changes preserve terminal ownership. In particular, showing
      // the destination must not reclaim every terminal another window holds.
      _paneFocusByUser = false;
      _paneFocusRequest++;
    }
    selectedMachineId = focusedPane?.machineId;
    _persistLayout();
    _announceAppFocus();
    notifyListeners();
    return true;
  }

  Future<void> closePane(
    int paneId, {
    bool persist = true,
    String? swarmId,
  }) async {
    final tab = swarmId == null
        ? activeSwarm
        : swarms.where((s) => s.id == swarmId).firstOrNull;
    if (tab == null) return;
    final pane = tab.panes.where((p) => p.id == paneId).firstOrNull;
    if (pane == null) return;
    if (tab.isCompanions || tab.isDevices) {
      await closeSwarm(tab.id, persist: persist);
      return;
    }
    // A Finder closed by hand stays closed: its chat no longer brings it back.
    if (pane.isFinder && pane.ownerAgentId != null) {
      finderRoots.forget(pane.machineId, pane.ownerAgentId!);
    }
    if (pane.isWeb) {
      // A viewer closed by hand stays closed for THIS page: the agent's next
      // frame carries the same URL and must not reopen it. A different URL —
      // a new artifact, a restarted viewer — is news, and opens again.
      final owner = pane.ownerAgentId;
      final viewerState = pane.url ?? pane.viewerError;
      if (owner != null && viewerState != null) {
        _dismissedViewers[_viewerKey(pane.machineId, owner)] = viewerState;
      }
    }
    bool closesWithPane(TerminalPane candidate) =>
        candidate == pane || candidate.viewsAgent(pane.machineId, pane.agentId);
    if (tab.kind == 'harness' &&
        tab.panes.every(closesWithPane) &&
        !_activeAgentCreations.any((attempt) => attempt._targetId == tab.id)) {
      // The final pane closes its tab, including any viewer it owns. Use the
      // normal tab close so focus, history and the last-tab welcome agree.
      for (final viewer in tab.panes.where((p) => p != pane).toList()) {
        tab.remove(viewer);
      }
      await closeSwarm(tab.id, persist: persist);
      return;
    }
    if (pane.agentId != null) {
      final machine = stateOf(pane.machineId);
      final agent = machine?.agents
          .where((a) => a.id == pane.agentId)
          .firstOrNull;
      _rememberClosed(
        ClosedAgent(
          pane,
          tab,
          historyId: 'closed-${_nextClosedHistoryId++}',
          name: agent?.name ?? pane.session?.agentName ?? pane.agentId!,
          machineName: machine?.machine.displayName ?? pane.machineId,
          engine: agent?.identityEngine ?? pane.session?.engineId,
        ),
      );
    }
    // Only a close that moves the focus is worth telling the daemon about: a
    // background tile going away changes nothing the dial can see.
    final wasFocused = identical(activeSwarm, tab) && focusedPaneId == paneId;
    tab.remove(pane);
    // A harness's viewer lives beside its terminal and nowhere else: closing
    // the terminal in this tab takes the viewer in this tab with it. The
    // viewer's own close above is different — it is a choice about the page.
    if (!pane.isWeb && pane.agentId != null) {
      for (final viewer in tab.panes.toList()) {
        if (viewer.viewsAgent(pane.machineId, pane.agentId)) {
          tab.remove(viewer);
        }
      }
    }
    _settlePins(tab);
    if (persist) _persistLayout();
    selectedMachineId = focusedPane?.machineId;
    if (wasFocused) _announceAppFocus();
    notifyListeners();
    if (!allPanes.contains(pane)) await _detachSession(pane, sendClose: true);
  }

  Future<void> _closeAllPanes({bool persist = true}) async {
    final open = allPanes.toList();
    for (final swarm in swarms) {
      swarm.panes.clear();
      swarm.focusedPaneId = null;
      swarm.zoomedPaneId = null;
    }
    _announceAppFocus();
    await Future.wait(
      open.map((pane) async {
        try {
          await _detachSession(pane, sendClose: true);
        } catch (error) {
          // One disconnected terminal cannot prevent the others, or the saved
          // account, from being cleared during sign-out.
          debugPrint('sign-out terminal cleanup failed: $error');
        }
      }),
    );
    if (persist) _persistLayout();
  }

  int _layoutRevision = 0;
  int _paneLayoutRestores = 0;

  Future<void> flushPaneLayout() => workspaceEnabled?.call() == false
      ? Future<void>.value()
      : _paneLayout?.flushSwarms() ?? Future<void>.value();

  // ── desk sync ────────────────────────────────────────────────────────────

  /// Which tabs are the desk's business: harness tabs that are not drafts. The
  /// Store tab, orchestrator tabs and an untouched New Tab are this window's.
  bool _deskTracks(Swarm swarm) =>
      swarm.kind == 'harness' && !isDraftSwarm(swarm.id);

  /// The most tabs the desk keeps (backend `DESK_MAX_TABS`): it drops a 25th
  /// without an error, so a caller that adds one checks first.
  static const deskMaxTabs = 24;

  /// How many of this window's tabs the desk holds.
  int get deskTabCount => swarms.where(_deskTracks).length;

  /// Tab [id] takes [name] without it becoming the person's: a Personal
  /// project's tab following its project's rename. A name the person chose
  /// stays.
  void renameTabAutomatically(String id, String name) {
    final swarm = swarms.where((s) => s.id == id).firstOrNull;
    final clean = name.trim();
    if (swarm == null || swarm.nameIsCustom || clean.isEmpty) return;
    final next = clean.length > 80 ? clean.substring(0, 80) : clean;
    if (swarm.name == next) return;
    swarm.name = next;
    _persistLayout();
    notifyListeners();
  }

  /// Tab [id] named [name], made in the background when it is not here yet:
  /// the tab on screen stays, and the name is not the person's, so it may
  /// follow what it is named after (a Personal project's own tab, task
  /// #3099). It reaches the desk as any new tab does.
  Swarm ensureBackgroundTab(String id, String name) {
    final existing = swarms.where((s) => s.id == id).firstOrNull;
    if (existing != null) return existing;
    final swarm = Swarm(id: id, name: name, nameIsCustom: false);
    swarms.add(swarm);
    _persistLayout();
    notifyListeners();
    return swarm;
  }

  /// `swarms` as the desk would hold them.
  List<DeskTab> _deskProjection() => [
    for (final swarm in swarms)
      if (_deskTracks(swarm))
        DeskTab(
          id: swarm.id,
          name: swarm.name,
          nameIsCustom: swarm.nameIsCustom,
          panes: [
            for (final pane in swarm.panes)
              if (pane.agentId != null)
                DeskPaneRef(machineId: pane.machineId, agentId: pane.agentId!),
          ],
          layout: _deskLayoutOf(swarm),
        ),
  ];

  /// The tab's layout as the desk holds it: the chosen presets and the
  /// arrangements the window keeps (`paneSizes`), tiles as fractions. The
  /// desk carries at most 16 arrangements; the newest are the ones a hand
  /// just made, so those are what travel.
  static DeskLayout _deskLayoutOf(Swarm swarm) {
    final sizes = swarm.paneSizes.entries.toList();
    return DeskLayout(
      presets: {for (final e in swarm.presets.entries) '${e.key}': e.value.id},
      sizes: {
        for (final e in sizes.skip((sizes.length - 16).clamp(0, sizes.length)))
          e.key: e.value.toJson(),
      },
    );
  }

  /// Freeze a shared tab's geometry once. Window dimensions, font size and
  /// zoom only scale/scroll these slots; they never choose a new arrangement.
  /// A preset choice clears the current count's sizes and resolves here again.
  void _freezeDeskLayouts() {
    if (!_desk.enabled) return;
    for (final swarm in swarms) {
      final count = swarm.panes.length;
      // Viewers and drafts are local. Their slots cannot be assigned to the
      // desk's agent-only pane list. The desk currently accepts up to 9 panes.
      if (!_deskTracks(swarm) ||
          count < 2 ||
          count > 9 ||
          swarm.panes.any((pane) => pane.agentId == null)) {
        continue;
      }
      final manual = swarm.manualLayout;
      if (manual != null) {
        final filled = manual.fillRowEnds();
        if (!identical(filled, manual)) {
          swarm.savePaneSizes('$count:manual', filled);
        }
        continue;
      }
      final preset = swarm.presets[count] ?? PanePreset.defaultFor(count)!;
      final rendered = swarm.arranged?.tiles.length == count
          ? swarm.arranged
          : null;
      final saved = swarm.paneSizes.entries
          .where((e) => e.key.startsWith('$count:${preset.id}:'))
          .map((e) => e.value)
          .firstOrNull;
      final arrangement =
          (rendered ?? saved ?? PaneArrangement(preset.tilesFor(count)))
              .fillRowEnds();
      swarm.savePaneSizes('$count:manual', arrangement);
    }
  }

  /// The desk's layout for a tab, made this window's: presets the shape
  /// supports, arrangements whose tile count matches their key. Replaces
  /// what was there — a layout is one thing, not a merge of two.
  static void _applyDeskLayout(Swarm swarm, DeskLayout? layout) {
    swarm.presets.clear();
    swarm.paneSizes.clear();
    if (layout == null) return;
    for (final e in layout.presets.entries) {
      final count = int.tryParse(e.key);
      final preset = PanePreset.byId(e.value);
      if (count != null &&
          count >= 2 &&
          count <= maxPanes &&
          preset != null &&
          preset.supportsCount(count)) {
        swarm.presets[count] = preset;
      }
    }
    swarm.paneSizes.addAll(
      PaneArrangement.readSaved({
        for (final e in layout.sizes.entries) e.key: e.value,
      }),
    );
    swarm.arranged = null;
    swarm.arrangedKey = null;
  }

  /// First contact with the desk after sign-in. A daemon that predates the
  /// desk, or a signed-out one, answers null and this window keeps its tabs to
  /// itself. Otherwise the desk is read, this computer's own tabs from before
  /// the desk are given desk ids and seeded (every machine's tabs land; the
  /// person closes the extras), and the merged desk is applied.
  Future<void> _deskStart(int authRevision) async {
    if (workspaceEnabled?.call() == false) return;
    if (_deskJoining != null) return _deskJoining;
    final run = _deskJoin(authRevision);
    _deskJoining = run;
    try {
      await run;
    } finally {
      if (identical(_deskJoining, run)) _deskJoining = null;
    }
  }

  /// Join the desk unless this window already has (or is joining now). Every
  /// path that finishes a sign-in calls this — the boot, the retry the boot
  /// hands over to when the daemon is still connecting, and the daemon's
  /// backend link coming back — because a daemon whose backend was offline
  /// answered the first read with an error, not with a desk.
  void _deskEnsure(int authRevision) {
    if (workspaceEnabled?.call() == false) return;
    if (!_localSeatFollowed) return;
    if (_desk.enabled || _deskJoining != null) return;
    unawaited(_deskStart(authRevision));
  }

  /// Whether this sign-in has followed this computer's machine id
  /// ([_followLocalMachineId]) — re-seated the tiles this window made while
  /// signed out, which sit on the computer's own id. The desk is not joined
  /// before: its seed is every local tab it lacks, and a tab still on that id
  /// landed on the ACCOUNT's desk naming a machine nothing serves, opening on
  /// every window of it as "This machine isn't available" — a new user's first
  /// sign-in on the desktop did exactly that.
  bool _localSeatFollowed = false;

  /// [_followLocalMachineId], then the desk it was holding back.
  Future<void> _followLocalMachineIdThenDesk(int revision) async {
    await _followLocalMachineId(revision);
    if (!_authWorkCurrent(revision)) return;
    _localSeatFollowed = true;
    if (signedIn) _deskEnsure(revision);
  }

  Future<void> _deskJoin(int authRevision) async {
    // Edits remain available while the first read is pending. Remember the
    // existing desk tabs now so its eventual reply cannot undo a rename,
    // close, or move made during that wait. New/local tabs are seeded below.
    final beforeRead = _deskProjection()
        .where((tab) => isDeskId(tab.id))
        .toList();
    final beforeReadIds = beforeRead.map((tab) => tab.id).toSet();
    Map<String, dynamic>? raw;
    try {
      raw = await api.desk();
    } catch (error) {
      appLog.warn('desk', 'first read failed: $error');
      return;
    }
    if (_disposed || !_authWorkCurrent(authRevision)) return;
    final doc = DeskDoc.fromJson(raw);
    if (doc == null) {
      appLog.info('desk', 'not available here — tabs stay local');
      return;
    }
    _desk.enabled = true;
    // Whether the daemon and backend have Agent Messages, which Show Agent
    // Messages waits for, is read once the desk is.
    unawaited(agentMessages.refresh());
    unawaited(sharedTabs.refresh());
    // Tabs from before the desk carry per-window ids (`swarm-N`) two computers
    // would both mint. Give them desk ids once; the layout store keys by the
    // same string, so it follows on the next save.
    for (final swarm in swarms) {
      // A member's shared tab is a desk id already (R1, `memberDeskTabId`).
      if (_deskTracks(swarm) && !isDeskId(swarm.id)) {
        final was = swarm.id;
        swarm.id = newDeskId();
        if (_activeSwarmId == was) _activeSwarmId = swarm.id;
        for (final entry in _draftSwarmReturns.entries.toList()) {
          if (entry.value == was) _draftSwarmReturns[entry.key] = swarm.id;
        }
      }
    }
    final own = _deskProjection();
    final duringRead = deskDiff(
      beforeRead,
      own.where((tab) => beforeReadIds.contains(tab.id)).toList(),
    );
    final unknown = own
        .where((t) => !doc.tabs.any((d) => d.id == t.id))
        .toList();
    _desk.revision = doc.revision;
    // What this window believes at the join is its own layout: the desk's
    // order then wins where the two differ (it moved while this window was
    // away), and the seed is the desk learning the rest.
    _desk.synced = own;
    if (unknown.isNotEmpty) {
      _desk.pending.add({
        'op': 'seed',
        'tabs': [for (final t in unknown) t.toJson()],
      });
    }
    _desk.pending.addAll(duringRead);
    appLog.info(
      'desk',
      'joined at rev ${doc.revision} · ${doc.tabs.length} on the desk · ${unknown.length} of ours to seed',
    );
    _deskApply(doc, joining: true);
    await _deskFlush();
  }

  static String _layoutFingerprintOf(DeskLayout? layout) =>
      layout == null || layout.isEmpty ? '' : layout.fingerprint;

  static bool _sameKeys(List<String> a, List<String> b) {
    if (a.length != b.length) return false;
    for (var i = 0; i < a.length; i++) {
      if (a[i] != b[i]) return false;
    }
    return true;
  }

  /// Called from [_persistLayout]: whatever just changed, said to the desk as ops.
  void _deskQueueDiff() {
    if (!_desk.enabled) return;
    // A peer can prune stopped sessions while Close or a replacement is still
    // pending. Keep their local slots for history, without publishing them back
    // to the desk. The operation owns the final layout change.
    final projection = <DeskTab>[];
    for (final tab in _deskProjection()) {
      final synced = _desk.synced.where((t) => t.id == tab.id).firstOrNull;
      final known = {for (final p in synced?.panes ?? <DeskPaneRef>[]) p.key};
      final panes = tab.panes
          .where(
            (p) =>
                known.contains(p.key) ||
                !_keepsPendingAgent(p.machineId, p.agentId),
          )
          .toList();
      if (panes.length == tab.panes.length) {
        projection.add(tab);
      } else if (synced != null || panes.isNotEmpty) {
        projection.add(
          DeskTab(
            id: tab.id,
            name: tab.name,
            nameIsCustom: tab.nameIsCustom,
            panes: panes,
            layout: synced?.layout,
          ),
        );
      }
    }
    final ops = deskDiff(_desk.synced, projection);
    if (ops.isEmpty) return;
    // Optimistic: this window believes its own edit. The desk's answer (or a
    // document from elsewhere) is applied over it, with the pending ops laid
    // back on top until they are acknowledged.
    _desk.synced = projection;
    _desk.pending.addAll(ops);
    appLog.debug('desk', 'queued ${ops.map((o) => o['op']).join(' ')}');
    unawaited(_deskFlush());
  }

  Future<void> _deskFlush() async {
    if (!_desk.enabled ||
        _desk.inFlight ||
        _desk.pending.isEmpty ||
        _disposed) {
      return;
    }
    _desk.inFlight = true;
    final authRevision = _authRevision;
    final batch = List<Map<String, dynamic>>.from(_desk.pending);
    Map<String, dynamic>? raw;
    try {
      raw = await api.deskOps(batch);
    } catch (error) {
      _desk.inFlight = false;
      if (_disposed || !_authWorkCurrent(authRevision)) return;
      // Kept, not dropped: a tab closed while the backend was unreachable is
      // still closed everywhere once it is back. Backoff, capped at a minute.
      _desk.failures++;
      final wait = Duration(
        seconds: (5 * (1 << (_desk.failures - 1).clamp(0, 4))).clamp(5, 60),
      );
      appLog.warn(
        'desk',
        'write failed (${batch.length} ops, retry in ${wait.inSeconds}s): $error',
      );
      _deskRetry?.cancel();
      _deskRetry = Timer(wait, () => unawaited(_deskFlush()));
      return;
    }
    _desk.inFlight = false;
    if (_disposed || !_authWorkCurrent(authRevision)) return;
    _desk.failures = 0;
    _deskRetry?.cancel();
    _deskRetry = null;
    // Acknowledged (or, on null, refused for good — the daemon lost its
    // session): these ops are no longer pending either way.
    _desk.pending.removeRange(0, batch.length.clamp(0, _desk.pending.length));
    final doc = DeskDoc.fromJson(raw);
    if (doc == null) {
      appLog.info(
        'desk',
        'write not accepted — tabs stay local until the next sign-in',
      );
      _desk.enabled = false;
      _desk.pending.clear();
      return;
    }
    _deskApply(doc);
    if (_desk.pending.isNotEmpty) unawaited(_deskFlush());
  }

  Future<void> _deskFetch() async {
    if (!_desk.enabled || _disposed) return;
    final authRevision = _authRevision;
    Map<String, dynamic>? raw;
    try {
      raw = await api.desk();
    } catch (error) {
      appLog.warn('desk', 'read failed: $error');
      return;
    }
    if (_disposed || !_authWorkCurrent(authRevision)) return;
    final doc = DeskDoc.fromJson(raw);
    if (doc == null) return;
    _deskApply(doc);
  }

  /// Reconcile `swarms` to [doc], with this window's unacknowledged ops laid
  /// over it. Ignores a document older than one already applied.
  void _deskApply(DeskDoc doc, {bool joining = false}) {
    if (doc.revision < _desk.revision) return;
    _desk.revision = doc.revision;
    final target = applyDeskOps(doc.tabs, _desk.pending);
    final believed = _desk.synced;
    _desk.synced = target;
    _deskReconcile(target, believed: believed, joining: joining);
  }

  /// Make `swarms` say what [target] says, and no more: tabs the desk closed go
  /// (their streams released unless another tab still shows them), tabs it
  /// opened arrive as intent and attach as their machines answer, names the
  /// person chose follow, order follows. Focus, zoom, pins, viewers and
  /// this window's own local-only tabs are left exactly where they were.
  ///
  /// [believed] is the desk as this window last knew it. A tab's pane order is
  /// touched only where the desk's order MOVED since then — a drag on another
  /// Mac — and then only among the agent panes, each keeping its slot's size
  /// and its pin, the way a local drag does. Rebuilding the order from every
  /// document that arrived (the 15 s poll included) was what shuffled tiles
  /// and their sizes under a person's hands (owner, 2026-09-21).
  void _deskReconcile(
    List<DeskTab> target, {
    List<DeskTab> believed = const [],
    bool joining = false,
  }) {
    final targetById = {for (final t in target) t.id: t};
    final believedById = {for (final t in believed) t.id: t};
    final before = _deskProjection();
    final released = <TerminalPane>[];
    final previousFocus = focusedPane;
    final previousTab = activeSwarmId;
    // Keep the objects from the whole document until the move is complete.
    // Iterating source before destination used to remove the only reference,
    // create a replacement tile, and close its still-live terminal below.
    final existingPanes = {
      for (final pane in allPanes)
        if (pane.agentId != null)
          '${pane.machineId}\u0000${pane.agentId}': pane,
    };

    // Tabs the desk no longer has.
    final kept = <Swarm>[];
    for (final swarm in swarms) {
      if (_deskTracks(swarm) && !targetById.containsKey(swarm.id)) {
        if (!swarm.panes.any(_keepsPendingPane)) {
          released.addAll(swarm.panes);
          continue;
        }
        // Close keeps its complete layout until its acknowledgement can save
        // history. A replacement similarly owns its temporary local slot.
        // Other panes still follow closures from another window.
        for (final pane in swarm.panes.toList()) {
          if (_keepsPendingPane(pane)) continue;
          swarm.remove(pane);
          released.add(pane);
        }
      }
      kept.add(swarm);
    }
    swarms
      ..clear()
      ..addAll(kept);

    // Tabs, names and panes.
    for (final tab in target) {
      var swarm = swarms.where((s) => s.id == tab.id).firstOrNull;
      if (swarm == null) {
        swarm = Swarm(
          id: tab.id,
          name: tab.name,
          nameIsCustom: tab.nameIsCustom,
        );
        swarms.add(swarm);
      } else if (tab.nameIsCustom &&
          (swarm.name != tab.name || !swarm.nameIsCustom)) {
        swarm.name = tab.name;
        swarm.nameIsCustom = true;
      }
      final wanted = {for (final p in tab.panes) p.key};
      for (final pane in swarm.panes.toList()) {
        if (pane.agentId == null) continue;
        if (wanted.contains('${pane.machineId}\u0000${pane.agentId}')) continue;
        if (_keepsPendingPane(pane)) continue;
        swarm.remove(pane);
        released.add(pane);
        for (final viewer in swarm.panes.toList()) {
          if (viewer.viewsAgent(pane.machineId, pane.agentId)) {
            swarm.remove(viewer);
          }
        }
      }
      String keyOf(TerminalPane p) => '${p.machineId}\u0000${p.agentId}';
      for (var i = 0; i < tab.panes.length; i++) {
        final ref = tab.panes[i];
        if (swarm.panes.any((p) => keyOf(p) == ref.key)) continue;
        // One TerminalPane per (machine, agent) across tabs — the same rule the
        // restore keeps — so a second tab showing an agent reuses its stream.
        final pane = existingPanes.putIfAbsent(
          ref.key,
          () => TerminalPane(
            id: _nextPaneId++,
            machineId: ref.machineId,
            agentId: ref.agentId,
          ),
        );
        // Another account's harness the desk carries is a Share pane at once,
        // not an "Open here" tile until the next inventory (seam 2).
        _bindShared(pane);
        // After the agent pane the desk lists before it, whatever else (a
        // viewer, an empty tile) sits between; at the end when it is first.
        final after = i == 0
            ? -1
            : swarm.panes.indexWhere((p) => keyOf(p) == tab.panes[i - 1].key);
        swarm.panes.insert(
          after < 0 && i > 0 ? swarm.panes.length : after + 1,
          pane,
        );
        swarm.focusedPaneId ??= pane.id;
      }
      // Order among the agent panes: the desk's, but only where the desk's own
      // order moved since this window last agreed with it. The panes keep
      // their slots (so their sizes) and everything that is not an agent pane
      // stays exactly where it was; a pin follows its pane, as it does on a
      // local drag.
      final wantedOrder = [
        for (final ref in tab.panes)
          if (swarm.panes.any((p) => keyOf(p) == ref.key)) ref.key,
      ];
      final known = believedById[tab.id]?.panes.map((p) => p.key).toSet();
      final knownOrder = known == null
          ? null
          : [
              for (final ref in believedById[tab.id]!.panes)
                if (wantedOrder.contains(ref.key)) ref.key,
            ];
      final moved =
          knownOrder == null ||
          !_sameKeys(knownOrder, wantedOrder.where(known!.contains).toList());
      if (moved) {
        final slots = <int>[];
        for (var i = 0; i < swarm.panes.length; i++) {
          if (swarm.panes[i].agentId != null) slots.add(i);
        }
        final byKey = {for (final p in swarm.panes) keyOf(p): p};
        final inOrder = [for (final k in wantedOrder) byKey[k]!];
        if (slots.length == inOrder.length) {
          final pinnedAt = <TerminalPane, int>{};
          for (var j = 0; j < slots.length; j++) {
            final pane = inOrder[j];
            final was = swarm.panes.indexOf(pane);
            final slot = swarm.pinnedSlots[pane.id] ?? pane.pinnedSlot;
            if (slot != null && slot == was) pinnedAt[pane] = slots[j];
            swarm.panes[slots[j]] = pane;
          }
          for (final entry in pinnedAt.entries) {
            swarm.pinnedSlots[entry.key.id] = entry.value;
            if (hasNavigationRail) entry.key.pinnedSlot = entry.value;
          }
        }
      }
      // The layout: the desk's, but — like the order — only where the desk's
      // own layout moved since this window last agreed with it, so a drag in
      // progress here is not undone by a document that merely arrived. A tab
      // this window has never known takes the desk's layout as it is.
      final knownLayout = believedById.containsKey(tab.id)
          ? believedById[tab.id]!.layout
          : null;
      final layoutMoved =
          !believedById.containsKey(tab.id) ||
          _layoutFingerprintOf(knownLayout) != _layoutFingerprintOf(tab.layout);
      // At the join a desk that holds no layout for a tab this window has one
      // for learns this window's (the diff sends it up); it does not wipe it.
      final deskHasOne = tab.layout != null && !tab.layout!.isEmpty;
      final holdingSlot = swarm.panes.any(
        (pane) =>
            pane.agentId != null &&
            _keepsPendingPane(pane) &&
            !wanted.contains('${pane.machineId}\u0000${pane.agentId}'),
      );
      if (layoutMoved &&
          !holdingSlot &&
          (deskHasOne || !joining) &&
          _layoutFingerprintOf(tab.layout) !=
              _layoutFingerprintOf(_deskLayoutOf(swarm))) {
        _applyDeskLayout(swarm, tab.layout);
        _paneLayoutRequest++;
      }
      if (!swarm.nameIsCustom &&
          swarm.titleAgentId == null &&
          swarm.panes.isNotEmpty) {
        swarm.titleMachineId = swarm.panes.first.machineId;
        swarm.titleAgentId = swarm.panes.first.agentId;
      }
    }

    // Tab order: the desk's, with this window's local-only tabs where they were.
    // A tab the desk has is placed by the desk's order alone, even one this
    // window keeps to itself (a draft the desk learned while an agent was being
    // made in it): placed twice, its id reached native's tab strip twice, which
    // trapped on it and took the app down (1.2.57).
    final localOnly = <(int, Swarm)>[];
    for (var i = 0; i < kept.length; i++) {
      if (!targetById.containsKey(kept[i].id)) {
        localOnly.add((i, kept[i]));
      }
    }
    final ordered = <Swarm>[
      for (final tab in target) swarms.firstWhere((s) => s.id == tab.id),
    ];
    for (final (index, swarm) in localOnly) {
      ordered.insert(index.clamp(0, ordered.length), swarm);
    }
    final placed = <String>{};
    final duplicates = <String>[];
    swarms.clear();
    for (final swarm in ordered) {
      if (placed.add(swarm.id)) {
        swarms.add(swarm);
      } else {
        // The copy kept shows the same panes when it is the same tab; panes
        // only this copy held are let go below, like a closed tab's.
        duplicates.add(swarm.id);
        released.addAll(swarm.panes);
      }
    }
    if (duplicates.isNotEmpty) {
      appLog.warn('desk', 'dropped duplicate tab ${duplicates.join(', ')}');
    }
    if (swarms.isEmpty) swarms.add(Swarm(id: 'swarm-${_nextSwarmId++}'));
    if (!swarms.any((s) => s.id == _activeSwarmId)) {
      _activeSwarmId = swarms.first.id;
      selectedMachineId = focusedPane?.machineId;
    }
    if (activeSwarmId != previousTab ||
        !identical(focusedPane, previousFocus)) {
      // A peer moving the focused pane also focuses its neighbour. That is
      // remote navigation, just like a peer closing this window's active tab.
      // Treating it as a gesture here can start a terminal takeover loop.
      _paneFocusByUser = false;
    }
    final visible = profileSwarms;
    if (visible.isNotEmpty && visible.every((s) => s.id != _activeSwarmId)) {
      _activeSwarmId = visible.first.id;
      selectedMachineId = focusedPane?.machineId;
      _paneFocusByUser = false;
    }

    // Streams nobody shows any more.
    for (final pane in released.toSet()) {
      if (!allPanes.contains(pane)) {
        unawaited(_detachSession(pane, sendClose: true));
      }
    }
    _settlePins();
    final after = _deskProjection();
    if (deskDiff(before, after).isNotEmpty) {
      appLog.debug(
        'desk',
        'applied rev ${_desk.revision} · ${swarms.length} tabs',
      );
    }
    _persistLayout();
    for (final machine in machineStates.values) {
      // A desk another Mac wrote arriving here.
      _attachPendingPanes(
        machine,
        retryExisting: false,
        intent: AttachIntent.automatic,
      );
    }
    _announceAppFocus();
    notifyListeners();
    _placeSharedPanesSoon();
  }

  void _ensureProfileFocus() {
    if (_machineProfileId == null || _machineProfileId!.isEmpty) return;
    if (profileSwarms.any((swarm) => swarm.id == _activeSwarmId)) return;
    // Never empty while the desk has a tab: a profile that matches none shows
    // them all (swarmsForMachineProfile), so nothing is made to fill it.
    final visible = profileSwarms;
    if (visible.isEmpty) return;
    _activeSwarmId = visible.first.id;
    selectedMachineId = focusedPane?.machineId;
  }

  void _persistLayout() {
    if (workspaceEnabled?.call() == false) return;
    _ensureProfileFocus();
    for (final pane in allPanes) {
      if (pane.agentId case final id?) {
        rememberOpenedHarness(pane.machineId, id);
      }
    }
    _draftSwarmReturns.removeWhere((id, _) {
      final swarm = swarms.where((swarm) => swarm.id == id).firstOrNull;
      return swarm == null ||
          swarm.panes.isNotEmpty ||
          swarm.name != Swarm.defaultName ||
          swarm.presets.isNotEmpty;
    });
    _layoutRevision++;
    _announceOpenPanesToDial();
    _announceVisibleAgents();
    _freezeDeskLayouts();
    _deskQueueDiff();
    // Saved with an owner, so never under an account the signed-in check has not proven yet ([_launchProof]): held, and
    // saved once it is (review of #3293).
    if (_launchProof != null) {
      _layoutSaveHeld = true;
      return;
    }
    final saved = swarms.where((swarm) => !isDraftSwarm(swarm.id)).toList();
    if (saved.isEmpty) return;
    final savedActive = isDraftSwarm(activeSwarmId)
        ? _draftSwarmReturns[activeSwarmId]
        : activeSwarmId;
    unawaited(
      _paneLayout?.saveSwarms(
        saved,
        saved.any((swarm) => swarm.id == savedActive)
            ? savedActive!
            : saved.last.id,
        monitorHarnesses: _monitorHarnesses,
        owner: currentUser?.id,
      ),
    );
  }

  /// Closes the window in which a restored tile may still claim its terminal,
  /// so a machine that only answers hours later is met by the ordinary rule
  /// rather than by the gesture that opened the app.
  void _armLaunchClaimExpiry() {
    _launchClaimTimer?.cancel();
    _launchClaimTimer = Timer(launchClaimWindow, () {
      for (final pane in allPanes) {
        pane.claimOnFirstAttach = false;
      }
    });
  }

  /// Rebuild the grid from disk as INTENT only — the tiles appear immediately,
  /// each saying which machine it is waiting for, and attach themselves as
  /// their machines answer.
  ///
  /// The tiles cannot wait for the machines: machines answer in an order this
  /// side does not decide, a restored grid commonly spans two of them, and one
  /// being slow or offline must not hold the others blank.
  ///
  /// [claimOnAttach]: this restore is the app opening, so the tiles it brings
  /// back may take their terminals on their first attach — see
  /// [TerminalPane.claimOnFirstAttach]. False for a restore that is merely
  /// bookkeeping (a machine re-keyed under the window), which nobody asked for.
  Future<void> _restorePaneLayout({bool claimOnAttach = false}) async {
    if (workspaceEnabled?.call() == false) return;
    final store = _paneLayout;
    if (store == null) return;
    _paneLayoutRestores++;
    try {
      await _readPaneLayout(store, claimOnAttach: claimOnAttach);
    } finally {
      _paneLayoutRestores--;
    }
  }

  Future<void> _readPaneLayout(
    PaneLayoutStore store, {
    required bool claimOnAttach,
  }) async {
    // Before any chat is restored: its Finder comes back with its agent.
    await finderRoots.load();
    final initialSwarm = activeSwarm;
    final revision = _layoutRevision;
    final authRevision = _authRevision;
    final savedProfile = await store.loadMachineProfile();
    final loaded = await store.loadSwarms();
    // Another account's tabs and history — a browser someone else signed in
    // on — are not this one's to see: start from an empty desk instead.
    final foreign =
        loaded != null &&
        !PaneLayoutStore.restorableFor(loaded, currentUser?.id);
    final saved = foreign ? null : loaded;
    final known = foreign
        ? const <(String, String)>[]
        : await store.loadMonitorHarnesses(saved);
    if (!_authWorkCurrent(authRevision)) return;
    // This window's own choice, never the desk's. No saved choice — a window
    // that never picked one — is All machines.
    _machineProfileId = savedProfile == null || savedProfile.isEmpty
        ? null
        : savedProfile;
    for (final (machine, agent) in known) {
      rememberOpenedHarness(machine, agent);
    }
    if (revision != _layoutRevision) {
      _persistLayout();
      return;
    }
    if (saved != null &&
        allPanes.isEmpty &&
        swarms.length == 1 &&
        activeSwarm == initialSwarm) {
      final restored = <Swarm>[];
      final pool = <String, TerminalPane>{};
      for (final raw in (saved['swarms'] as List)) {
        if (raw is! Map || raw['id'] is! String || raw['panes'] is! List) {
          continue;
        }
        final id = raw['id'] as String;
        if (id.isEmpty || restored.any((s) => s.id == id)) continue;
        // An empty tab carrying the store's name is the store — a layout
        // saved by a build that did not yet write the kind — and one store
        // tab, as one New Tab: a second has nothing the first does not.
        final isStore =
            raw['kind'] == 'store' ||
            (raw['name'] == Swarm.storeName && (raw['panes'] as List).isEmpty);
        if (isStore && restored.any((s) => s.isStore)) continue;
        final isCompanions = raw['kind'] == 'companions';
        if (isCompanions && restored.any((s) => s.isCompanions)) continue;
        final isDevices = raw['kind'] == 'devices';
        if (isDevices &&
            (!devicesEnabled || restored.any((s) => s.isDevices))) {
          continue;
        }
        final swarm =
            Swarm(
                id: id,
                nameIsCustom: raw['nameIsCustom'] == true ? true : null,
                name:
                    raw['name'] is String &&
                        (raw['name'] as String).trim().isNotEmpty
                    ? (raw['name'] as String).substring(
                        0,
                        (raw['name'] as String).length.clamp(0, 80),
                      )
                    : Swarm.defaultName,
                kind: isStore
                    ? 'store'
                    : isDevices
                    ? 'devices'
                    : isCompanions
                    ? 'companions'
                    : raw['kind'] == 'superTab'
                    ? 'superTab'
                    : raw['kind'] == 'orchestrator'
                    ? 'orchestrator'
                    : 'harness',
              )
              ..superTabId =
                  raw['superTabId'] is String &&
                      RegExp(r'^[a-f0-9]{24}$')
                          .hasMatch(raw['superTabId'] as String)
                  ? raw['superTabId'] as String
                  : null
              ..orchestratorId =
                  raw['orchestratorId'] is String &&
                      RegExp(r'^[a-f0-9]{32}$')
                          .hasMatch(raw['orchestratorId'] as String)
                  ? raw['orchestratorId'] as String
                  : null
              ..orchestratorMachineId = raw['orchestratorMachineId'] is String
                  ? raw['orchestratorMachineId'] as String
                  : null;
        swarm.isNewTabPage = raw['newTabPage'] == true;
        swarm.titleMachineId = raw['titleMachineId'] as String?;
        swarm.titleAgentId = raw['titleAgentId'] as String?;
        swarm.nameIsCustom =
            raw['nameIsCustom'] == true ||
            (swarm.titleAgentId == null &&
                swarm.name != Swarm.defaultName &&
                !(swarm.isStore && swarm.name == Swarm.storeName) &&
                !(swarm.isCompanions && swarm.name == Swarm.companionsName) &&
                !(swarm.isDevices && swarm.name == Swarm.devicesName));
        for (final item
            in (swarm.isCompanions || swarm.isDevices
                    ? const []
                    : raw['panes'] as List)
                .take(maxPanes)) {
          final entry = PaneLayoutEntry.fromJson(item);
          if (entry == null) continue;
          final key = '${entry.machineId}\u0000${entry.agentId}';
          final pane = pool.putIfAbsent(
            key,
            () =>
                TerminalPane(
                    id: _nextPaneId++,
                    machineId: entry.machineId,
                    agentId: entry.agentId,
                  )
                  ..composerVisible = entry.composerVisible
                  ..claimOnFirstAttach = claimOnAttach
                  ..pinnedSlot = entry.pinnedSlot,
          );
          if (!swarm.panes.contains(pane)) {
            swarm.panes.add(pane);
            if (entry.pinnedSlot != null) {
              swarm.pinnedSlots[pane.id] = entry.pinnedSlot!;
            }
          }
        }
        if (!swarm.nameIsCustom &&
            swarm.titleAgentId == null &&
            swarm.panes.isNotEmpty) {
          swarm.titleMachineId = swarm.panes.first.machineId;
          swarm.titleAgentId = swarm.panes.first.agentId;
        }
        int? paneAt(Object? index) =>
            index is int && index >= 0 && index < swarm.panes.length
            ? swarm.panes[index].id
            : null;
        swarm.focusedPaneId =
            paneAt(raw['focus']) ?? swarm.panes.firstOrNull?.id;
        swarm.zoomedPaneId = paneAt(raw['zoom']);
        swarm.previousPaneId = paneAt(raw['previousFocus']);
        if (raw['presets'] case final Map presets) {
          for (final e in presets.entries) {
            final count = int.tryParse(e.key.toString());
            final preset = PanePreset.byId(e.value?.toString());
            if (count != null &&
                count >= 2 &&
                count <= maxPanes &&
                preset != null &&
                preset.supportsCount(count)) {
              swarm.presets[count] = preset;
            }
          }
        }
        swarm.paneSizes.addAll(PaneArrangement.readSaved(raw['paneSizes']));
        if (swarm.isDevices) _ensureDevicesViewer(swarm);
        restored.add(swarm);
      }
      if (restored.isNotEmpty) {
        // Older builds saved multiple unused start pages. Retain the selected
        // one when possible; custom names, presets and real work stay intact.
        final starters = restored.where(
          (swarm) => swarm.isEmptyStarter && !swarm.isNewTabPage,
        );
        final starter =
            starters
                .where((swarm) => swarm.id == saved['activeId'])
                .firstOrNull ??
            starters.firstOrNull;
        final hadDuplicateStarters = starters.length > 1;
        if (hadDuplicateStarters) {
          restored.removeWhere(
            (swarm) =>
                swarm.isEmptyStarter && !swarm.isNewTabPage && swarm != starter,
          );
        }
        swarms
          ..clear()
          ..addAll(restored);
        if (restored.any((swarm) => swarm.isSuperTab)) enterSuperTabs();
        _activeSwarmId = restored.any((s) => s.id == saved['activeId'])
            ? saved['activeId'] as String
            : restored.first.id;
        final restoredActive = _activeSwarmId;
        // A saved active tab can belong to another computer. The profile
        // choice has to win on launch, or the strip hides the tab on screen.
        _ensureProfileFocus();
        while (swarms.any((s) => s.id == 'swarm-$_nextSwarmId')) {
          _nextSwarmId++;
        }
        _autoPickedAgent = true;
        if (hadDuplicateStarters || _activeSwarmId != restoredActive) {
          _persistLayout();
        }
        notifyListeners();
        return;
      }
    }
    // Read before the guards below: the dividers are remembered even for a
    // grid this run has not restored any agents into, so a window that opens
    // empty and is then filled by hand still comes up the shape it was left.
    final legacyPresets = await store.loadPresets();
    if (!_authWorkCurrent(authRevision) || revision != _layoutRevision) return;
    if (allPanes.isNotEmpty ||
        swarms.length != 1 ||
        activeSwarm != initialSwarm) {
      return;
    }
    final entries = await store.load();
    if (!_authWorkCurrent(authRevision) || revision != _layoutRevision) return;
    panePresets.addAll(legacyPresets);
    if (entries.isEmpty) {
      if (panePresets.isNotEmpty) notifyListeners();
      return;
    }
    for (final entry in entries) {
      panes.add(
        TerminalPane(
            id: _nextPaneId++,
            machineId: entry.machineId,
            agentId: entry.agentId,
          )
          ..composerVisible = entry.composerVisible
          ..pinnedSlot = entry.pinnedSlot,
      );
    }
    // The saved order already puts everything where it was left, so this is
    // only a repair: a layout whose file was hand-edited, or trimmed by the
    // pane ceiling on the way in, can arrive with a pinned tile off its slot.
    _settlePins();
    focusedPaneId = panes.first.id;
    // A restored grid IS the choice of what to open, so the first-run
    // convenience must not also fire and add a fifth agent nobody asked for.
    _autoPickedAgent = true;
    notifyListeners();
  }

  /// Attach any tile of this machine that is still waiting.
  ///
  /// Called after every load rather than once, because the three things
  /// [_attachSession] insists on — the agent exists, it has a tmux terminal,
  /// and the machine's terminal protocol has been negotiated — become true at
  /// different moments, and a machine that goes away and returns has to be able
  /// to re-arrive at them.
  void _attachPendingPanes(
    MachineState machine, {
    bool retryExisting = true,
    required AttachIntent intent,
  }) {
    final machineId = machine.machine.machineId;
    for (final pane in allPanes.toList()) {
      if (pane.machineId != machineId) continue;
      // A shared machine's pane is drawn from its grant, never attached (seam 2).
      _bindShared(pane);
      if (!panes.contains(pane) && pane.session == null) continue;
      // Navigation may mount a new view; it must never retry a retained stream
      // or discard its output while the machine is unavailable.
      if (!retryExisting && pane.session != null) continue;
      if (!_paneNeedsAttach(pane)) continue;
      // A gesture reaches only the tab it was made in. A person opening the
      // app, switching to a tab or clicking a tile is asking about what is in
      // front of them; the tabs behind it are somebody else's business, and
      // two Macs sitting on two different tabs have to be able to work at the
      // same time. A tile the app restored carries the gesture that opened it
      // (once), but only once it is the tab being looked at — until then it
      // keeps the claim and watches.
      final inFocusedTab = panes.contains(pane);
      final asked = pane.claimOnFirstAttach || intent == AttachIntent.person;
      final paneIntent = asked && inFocusedTab
          ? AttachIntent.person
          : AttachIntent.automatic;
      // Nobody asked for this one, and this machine's CLI cannot open a
      // terminal without taking it from whoever has it: leave the tile as
      // intent (`pane_grid.dart` offers to open it) rather than pulling the
      // keyboard out from under somebody on another screen.
      if (paneIntent == AttachIntent.automatic &&
          !machine.terminalNoTakeoverAvailable) {
        continue;
      }
      // Asked before the claim is spent: a machine that is up but has not
      // verified this agent's terminal yet refuses here, and a claim spent on
      // that refusal would leave the tile watching the terminal it was opened
      // to take, once the agent does come ready.
      if (!_canAttachPane(pane)) continue;
      // Spent on the attach it pays for, and only when it was used: a tile in
      // a tab nobody has opened yet keeps its claim for the switch that brings
      // it forward.
      if (paneIntent == AttachIntent.person) pane.claimOnFirstAttach = false;
      // Covers a tile that never attached AND one holding a stream the machine
      // lost. Only the first used to be covered, and the second is why a
      // reconnect left every tile but one frozen on "restoring terminal…":
      // recovery ran off pendingOfflineAgentId, which is a single slot, so it
      // could only ever promise restoration to one of them.
      unawaited(_reattachPane(pane, intent: paneIntent));
    }
    // A load is also when a pane that could not be attached before (agents not listed yet) can be.
    _schedulePaneRetries();
  }

  /// Every session change repaints, and may mean a pane's stream just died.
  void _onSessionChanged() {
    notifyListeners();
    // Sessions notify on every change — a title, a resize, a watcher band — and the sweep answers
    // differently only when a stream dies, closes here or comes back live. Run on each notification,
    // it rebuilt the pane set for every dead pane and every timer: with 40 panes, 10 of them dead, a
    // notification cost ~53 µs, and ~3 µs with the set built once and this check (2026-10-17, VM test).
    if (_retryPhasesChanged()) _schedulePaneRetries();
  }

  /// What the sweep reads of a session's status: dead (error/closed, here or not), live (which resets
  /// the pane's backoff), or neither.
  static int _retryPhase(TerminalSession session) => switch (session.status) {
    TerminalSessionStatus.error ||
    TerminalSessionStatus.closed => session.closedHere ? 1 : 2,
    TerminalSessionStatus.controlling => 3,
    _ => 0,
  };

  bool _retryPhasesChanged() {
    for (final swarm in swarms) {
      for (final pane in swarm.panes) {
        final session = pane.session;
        if (session != null &&
            _sweptRetryPhases[session] != _retryPhase(session)) {
          return true;
        }
      }
    }
    return false;
  }

  /// Keep one timer for each pane whose stream died while its machine stays reachable, in whichever
  /// tab it is, and none for any other. Sessions notify on state changes, not on output, so the walk
  /// is cheap; an app with every terminal live holds no timer.
  void _schedulePaneRetries() {
    if (_disposed) return;
    _paneSweeps++;
    final all = allPanes;
    _sweptRetryPhases.clear();
    for (final pane in all) {
      if (pane.session case final session?) {
        _sweptRetryPhases[session] = _retryPhase(session);
      }
      if (!_paneRetryWanted(pane, all: all)) {
        _paneRetryTimers.remove(pane)?.cancel();
        if (pane.session?.status == TerminalSessionStatus.controlling) {
          _paneRetryAttempts.remove(pane);
        }
        continue;
      }
      if (_paneRetryTimers.containsKey(pane)) continue;
      final attempts = _paneRetryAttempts[pane] ?? 0;
      final delay = paneRetryDelays[min(attempts, paneRetryDelays.length - 1)];
      _paneRetryTimers[pane] = Timer(delay, () {
        _paneRetryTimers.remove(pane);
        if (!_paneRetryWanted(pane)) return;
        _paneRetryAttempts[pane] = attempts + 1;
        appLog.info(
          'terminal',
          'reattach machine=${pane.machineId} agent=${pane.agentId} attempt=${attempts + 1}',
        );
        final session = pane.session!;
        // A sweep reopen is never a gesture. It must not take the terminal on the strength of an
        // earlier click whose open failed, and only its first attempt may redial the machine's link:
        // a forced redial knocks every other pane on that machine over too.
        session.takeover = false;
        unawaited(session.reopen(redial: attempts == 0));
      });
    }
    _paneRetryTimers.removeWhere((pane, timer) {
      if (all.contains(pane)) return false;
      timer.cancel();
      return true;
    });
    _paneRetryAttempts.removeWhere((pane, _) => !all.contains(pane));
  }

  /// A dead stream on a machine that is up and can open terminals politely. Offline machines are left
  /// to the offline/online path, and `takenOver` panes to a person. A dead watcher is included, unlike
  /// in [_paneNeedsAttach]: the reopen is polite, so it comes back as a watcher and takes nothing.
  bool _paneRetryWanted(TerminalPane pane, {Set<TerminalPane>? all}) {
    final session = pane.session;
    final machine = machineStates[pane.machineId];
    return pane.agentId != null &&
        session != null &&
        !session.closedHere &&
        (session.status == TerminalSessionStatus.error ||
            session.status == TerminalSessionStatus.closed) &&
        machine != null &&
        machine.nodeOnline == true &&
        machine.terminalNoTakeoverAvailable &&
        _canAttachPane(pane, all: all);
  }

  void _cancelPaneRetries() {
    for (final timer in _paneRetryTimers.values) {
      timer.cancel();
    }
    _paneRetryTimers.clear();
    _paneRetryAttempts.clear();
  }

  /// Whether this tile is showing something that is not a working terminal.
  ///
  /// `takenOver` is deliberately absent. A stream someone else claimed is only
  /// reopened when a person asks for it — see [selectAgent], which is reached
  /// from the tile's own retry button. Doing it automatically would have two
  /// windows trading one terminal back and forth for as long as both stayed
  /// open.
  bool _paneNeedsAttach(TerminalPane pane) {
    if (pane.agentId == null) return false;
    final session = pane.session;
    if (session == null) return true;
    // A watcher is a live stream, not a tile waiting on one: reattaching it
    // would ask again for a terminal somebody else is working in.
    if (session.watching) return false;
    return switch (session.status) {
      TerminalSessionStatus.error || TerminalSessionStatus.closed => true,
      _ => false,
    };
  }

  /// Reopen a dead stream in its existing session, keeping its rendered output.
  /// An already-lost stream needs no close addressed to its previous owner.
  Future<void> _reattachPane(
    TerminalPane pane, {
    AttachIntent intent = AttachIntent.person,
  }) async {
    if (!_canAttachPane(pane)) return;
    final session = pane.session;
    if (session == null) {
      await _attachSession(pane, intent: intent);
    } else {
      await session.reopen(force: intent == AttachIntent.person);
    }
  }

  /// A person acted on this app — clicked a tile, brought the window forward
  /// — so every stream another client took from it comes back, not only the
  /// tile they touched: being at this tab is a fact about the tab, not about
  /// one pane.
  ///
  /// THIS tab only. A tile parked behind another tab is not what the person
  /// is looking at, and taking its terminal too is how two Macs sitting on two
  /// different tabs ended up fighting over terminals neither of them had on
  /// screen. Switching to that tab is its own gesture, and brings its tiles
  /// back then.
  ///
  /// Only ever from a user gesture — see
  /// `_TerminalPanelState._autoTakeControl` for why a session or focus
  /// callback must never call this.
  ///
  /// Reopens in place, as `selectAgent` does for a dead pane; `reopen` itself
  /// skips a pane already `opening`. A pane the daemon would refuse
  /// (`_canAttachPane`: machine offline, agent gone) keeps its band. Focus is
  /// not moved — the tile the person is on stays the one they are on.
  Future<void> retakeTakenOverPanes() async {
    final reopening = <Future<void>>[];
    for (final pane in panes) {
      final session = pane.session;
      if (session == null || session.readOnly) continue;
      // A watcher is the same thing from the other side: this window has the
      // output, another client has the terminal. Both come back on a gesture.
      if (session.status != TerminalSessionStatus.takenOver &&
          !session.watching) {
        continue;
      }
      if (!_canAttachPane(pane)) continue;
      // `force`: a person is asking, so this open may take the terminal. A
      // plain reopen would inherit the polite claim the session was opened
      // with (see [AttachIntent]) and be refused all over again.
      reopening.add(session.reopen(force: true));
    }
    await Future.wait(reopening);
  }

  /// [all] is [allPanes] when the caller already holds it.
  bool _canAttachPane(TerminalPane pane, {Set<TerminalPane>? all}) {
    if (_disposed || !(all ?? allPanes).contains(pane)) return false;
    final machine = machineStates[pane.machineId];
    return machine != null &&
        machine.nodeOnline != false &&
        machine.terminalCapabilityAvailable &&
        !(machine.isRemote && !machine.isLocalMachine && machine.needsLink) &&
        (!machine.isLocalMachine || machine.usesLocalTransport) &&
        machine.agents.any((a) => a.id == pane.agentId && a.terminalAvailable);
  }

  DeviceVisit? _deviceVisit;
  bool Function()? deviceNavigationAllowed;
  Future<Map<String, dynamic>> Function(String, Map<String, dynamic>)?
  deviceFormCommand;

  Future<Map<String, dynamic>?> formFromDevice(
    String connectionMachineId,
    Map<String, dynamic> command,
  ) async {
    final id = command['formId'], request = command['requestId'];
    bool identifier(Object? value) =>
        value is String && RegExp(r'^[a-zA-Z0-9-]{1,64}$').hasMatch(value);
    if (!identifier(id) ||
        !identifier(request) ||
        !const [
          'open',
          'state',
          'move',
          'activate',
          'back',
          'close',
          'query.begin',
          'query',
          'query.cancel',
        ].contains(command['op']) ||
        (command['surface'] != null &&
            !const ['new', 'find'].contains(command['surface'])) ||
        (command['queryId'] != null && !identifier(command['queryId'])) ||
        (command['text'] != null &&
            (command['text'] is! String ||
                (command['text'] as String).length > 240)) ||
        (command['revision'] != null && command['revision'] is! int) ||
        (command['delta'] != null &&
            (command['delta'] is! int ||
                (command['delta'] as int).abs() > 8))) {
      return null;
    }
    final reply = <String, dynamic>{'formId': id, 'requestId': request};
    final expires = command['expiresAt'];
    if (_disposed ||
        !inForeground ||
        viewer != null ||
        expires is! int ||
        expires <= DateTime.now().millisecondsSinceEpoch ||
        stateOf(connectionMachineId)?.machine.isShared != false) {
      return {
        ...reply,
        'ok': false,
        'active': false,
        'error': 'Return to the Harness window first.',
      };
    }
    final result =
        await deviceFormCommand?.call(connectionMachineId, command) ??
        {
          'ok': false,
          'active': false,
          'error': 'Open the Harness workspace first.',
        };
    return {...reply, ...result};
  }

  /// A hand on this desk visits an alert or the latest output and returns.
  /// Replies use the original socket, even if the destination is on another
  /// machine. No command here approves a request or retakes a terminal.
  Map<String, dynamic>? visitFromDevice(
    String connectionMachineId,
    Map<String, dynamic> command,
  ) {
    final id = command['visitId'];
    final request = command['requestId'];
    final op = command['op'];
    bool identifier(Object? value) =>
        value is String && RegExp(r'^[a-zA-Z0-9-]{1,64}$').hasMatch(value);
    if (!identifier(id) ||
        !identifier(request) ||
        !const ['open', 'latest', 'back', 'cancel'].contains(op)) {
      return null;
    }
    final reply = <String, dynamic>{'visitId': id, 'requestId': request};
    Map<String, dynamic> fail(String text) => {
      ...reply,
      'ok': false,
      'error': text,
      'active':
          _deviceVisit?.id == id &&
          _deviceVisit?.connectionMachineId == connectionMachineId,
    };
    void clear() {
      _deviceVisit?.dispose();
      _deviceVisit = null;
    }

    if (op == 'cancel') {
      if (_deviceVisit?.id == id &&
          _deviceVisit?.connectionMachineId == connectionMachineId) {
        clear();
      }
      return {
        ...reply,
        'ok': true,
        'active': false,
        'agentId': focusedPane?.agentId,
      };
    }
    final expires = command['expiresAt'];
    if (_disposed ||
        !inForeground ||
        viewer != null ||
        expires is! int ||
        expires <= DateTime.now().millisecondsSinceEpoch ||
        stateOf(connectionMachineId)?.machine.isShared != false) {
      return fail('Return to the Harness window first.');
    }
    if (deviceNavigationAllowed?.call() != true) {
      return fail('Close the picker and return to the terminal.');
    }
    bool atVisit(DeviceVisit v) =>
        activeSwarmId == v.visitingSwarm &&
        identical(focusedPane, v.visiting) &&
        focusedPane?.machineId == v.visitingMachine &&
        focusedPane?.agentId == v.visitingAgent;
    final previous = _deviceVisit;
    if (op == 'back') {
      if (previous == null ||
          previous.id != id ||
          previous.connectionMachineId != connectionMachineId) {
        return fail('The previous visit has ended.');
      }
      if (!atVisit(previous)) {
        clear();
        return fail('The pane changed. Choose your workspace from controls.');
      }
      final origin = swarms
          .where((s) => s.id == previous.originSwarm)
          .firstOrNull;
      if (origin == null ||
          !origin.panes.contains(previous.origin) ||
          previous.origin.machineId != previous.originMachine ||
          previous.origin.agentId != previous.originAgent) {
        clear();
        return fail('Your previous pane has closed.');
      }
      final restored = previous.bookmark.restore();
      _fromDevice(() {
        selectSwarm(origin.id, attachPending: false);
        focusPane(previous.origin.id, reveal: true);
      });
      clear();
      return {
        ...reply,
        'ok': true,
        'active': false,
        'agentId': focusedPane?.agentId,
        if (!restored)
          'note': 'Returned. The earlier text is no longer available.',
      };
    }
    final fromMachine = command['fromMachineId'];
    final fromAgent = command['fromAgentId'];
    final machineId = command['machineId'];
    final agentId = command['agentId'];
    final latest = op == 'latest';
    if (focusedPane?.machineId != fromMachine ||
        focusedPane?.agentId != fromAgent ||
        machineId is! String ||
        agentId is! String ||
        _dialFocusMachine(command, agentId) != machineId ||
        (latest && (machineId != fromMachine || agentId != fromAgent)) ||
        stateOf(machineId)?.machine.isShared != false) {
      return fail('The pane changed. Choose the action again.');
    }
    if (previous != null &&
        previous.id == id &&
        (previous.connectionMachineId != connectionMachineId ||
            !atVisit(previous))) {
      return fail('The pane changed. Open the alert again.');
    }
    // Validate that a picker, composer, or another route does not own input.
    final bookmark = focusedPane?.session?.bookmarkReading();
    if (bookmark == null) {
      return fail('Close the picker and return to the terminal.');
    }
    if (latest && focusedPane?.session?.showLatestReading() != true) {
      bookmark.dispose();
      return fail(
        'Latest output needs local terminal scrollback. Keep scrolling this program.',
      );
    }
    final DeviceVisit visit;
    if (previous != null && previous.id == id) {
      bookmark.dispose();
      visit = previous;
    } else {
      clear();
      final pane = focusedPane!;
      final agent = stateOf(pane.machineId)?.agents
          .where((a) => a.id == pane.agentId)
          .firstOrNull;
      visit = DeviceVisit(
        id: id as String,
        connectionMachineId: connectionMachineId,
        originSwarm: activeSwarmId,
        origin: pane,
        label: latest
            ? 'Your reading'
            : (agent?.name ?? activeSwarm.name).characters.take(48).toString(),
        bookmark: bookmark,
      );
    }
    // Membership and focus change synchronously. A network attachment may
    // finish later, but must not delay the return token or move focus again.
    if (!latest) {
      unawaited(openAgentFromDial(machineId, agentId).catchError((_) {}));
    }
    if (focusedPane?.machineId != machineId ||
        focusedPane?.agentId != agentId) {
      visit.dispose();
      _deviceVisit = null;
      return fail('That harness could not be opened.');
    }
    if (!latest &&
        identical(focusedPane, visit.origin) &&
        activeSwarmId == visit.originSwarm) {
      visit.dispose();
      _deviceVisit = null;
      return {
        ...reply,
        'ok': true,
        'active': false,
        'agentId': focusedPane?.agentId,
      };
    }
    visit.visiting = focusedPane;
    visit.visitingSwarm = activeSwarmId;
    visit.visitingMachine = machineId;
    visit.visitingAgent = agentId;
    _deviceVisit = visit;
    return {
      ...reply,
      'ok': true,
      'active': true,
      'label': visit.label,
      'agentId': focusedPane?.agentId,
    };
  }

  /// Reading context for the physical device. A cancel can clear its old pane;
  /// all other operations require the named pane to remain visibly focused.
  ({Map<String, dynamic> reply, TerminalSession? session})?
  _devicePassageTarget(
    String connectionMachineId,
    Map<String, dynamic> command,
  ) {
    final id = command['selectionId'];
    final request = command['requestId'];
    final agentId = command['agentId'];
    final machineId = command['machineId'];
    final revision = command['revision'];
    final op = command['op'];
    bool identifier(Object? v) =>
        v is String && RegExp(r'^[a-zA-Z0-9-]{1,64}$').hasMatch(v);
    if (!identifier(id) ||
        !identifier(request) ||
        agentId is! String ||
        agentId.isEmpty ||
        agentId.length > 200 ||
        machineId != connectionMachineId ||
        revision is! int ||
        revision < 1 ||
        revision > 0x7fffffff ||
        !const [
          'begin',
          'step',
          'extend',
          'pin',
          'cancel',
          'search',
          'match',
          'lines',
        ].contains(op)) {
      return null;
    }
    final reply = <String, dynamic>{
      'selectionId': id,
      'requestId': request,
      'agentId': agentId,
      'machineId': machineId,
      'revision': revision,
    };
    TerminalSession? session;
    if (op == 'cancel') {
      session = allPanes
          .where((p) => p.machineId == machineId && p.agentId == agentId)
          .map((p) => p.session)
          .whereType<TerminalSession>()
          .firstOrNull;
    } else if (inForeground &&
        focusedPane?.machineId == machineId &&
        focusedPane?.agentId == agentId &&
        focusedPane?.isWeb != true &&
        stateOf(connectionMachineId)?.machine.isShared != true) {
      session = focusedPane?.session;
    }
    return (reply: reply, session: session);
  }

  Map<String, dynamic>? selectDevicePassage(
    String connectionMachineId,
    Map<String, dynamic> command,
  ) {
    if (const ['search', 'match'].contains(command['op'])) return null;
    final target = _devicePassageTarget(connectionMachineId, command);
    if (target == null) return null;
    return {
      ...target.reply,
      ...?target.session?.selectPassage(command),
      if (target.session == null) ...{
        'ok': false,
        'error': 'Select that terminal pane in Harness first.',
      },
    };
  }

  Future<Map<String, dynamic>?> searchDevicePassage(
    String connectionMachineId,
    Map<String, dynamic> command,
  ) async {
    if (!const ['search', 'match'].contains(command['op'])) return null;
    final target = _devicePassageTarget(connectionMachineId, command);
    if (target == null) return null;
    final result = await target.session?.searchPassage(command);
    // Search yields during long scans. The owning window must still be active
    // when it returns; no result can silently move to a different terminal.
    final current = _devicePassageTarget(connectionMachineId, command);
    return {
      ...target.reply,
      if (target.session != null && identical(current?.session, target.session))
        ...?result
      else ...{
        'ok': false,
        'error': 'Select that terminal pane in Harness first.',
      },
    };
  }

  /// Resolve a dial agent to the machine that owns it.
  ///
  /// New CLIs state the machine explicitly. Older CLIs only sent an agent id;
  /// that is safe to retain only when the current snapshots contain exactly
  /// one matching machine. The websocket carrying the event is always the
  /// local daemon and is therefore not evidence that the agent is local.
  String? _dialFocusMachine(Map<String, dynamic> payload, String agentId) {
    final explicitMachineId = payload['machineId'];
    if (explicitMachineId is String && explicitMachineId.isNotEmpty) {
      final state = machineStates[explicitMachineId];
      if (state == null ||
          !state.agents.any((candidate) => candidate.id == agentId)) {
        return null;
      }
      return explicitMachineId;
    }

    String? match;
    for (final entry in machineStates.entries) {
      if (!entry.value.agents.any((candidate) => candidate.id == agentId)) {
        continue;
      }
      if (match != null) return null; // Ambiguous legacy event: do not guess.
      match = entry.key;
    }
    return match;
  }

  Future<void> _handleEvent(
    String machineId,
    Map<String, dynamic> event,
  ) async {
    final machine = machineStates[machineId];
    if (machine == null) return;
    // A frame from this computer's daemon is the daemon answering. Cheap: the flags are checked
    // first, and only a machine currently marked down goes on to look at the socket.
    if (machine.localOnly &&
        (machine.nodeOnline == false || machine.localEndpoint == null)) {
      _healLocalMachine(machine, 'frame from the daemon');
    }
    final type = event['type'] as String? ?? '';
    final payload = (event['payload'] as Map<String, dynamic>?) ?? {};
    if (type == 'orchestrator_changed') {
      _orchestratorProjects['$machineId/${payload['id']}']?.changed();
      return;
    }
    // A Swarm this account is in changed, or (naming none) the server pushes
    // (backend lib/swarmClientPushes.ts). On a computer only its own daemon
    // relays the server's word (CLI backendSocket.ts): another machine's
    // connection could forge it, and quiet this window's Swarm polls. A browser
    // hears it from the server on its own sockets.
    if (type == 'swarm_changed') {
      if (viewer != null || machine.isLocalMachine) {
        superTabs.swarmChanged(payload);
      }
      return;
    }
    // Window frames come only from this computer's own daemon; another
    // connection's are not about this window's tabs.
    if (type == 'shared_tabs_changed' || type == 'shared_activity') {
      if (viewer == null && machine.isLocalMachine) {
        if (type == 'shared_tabs_changed') {
          sharedTabs.changed();
        } else {
          sharedTabs.handleActivity(payload);
        }
      }
      return;
    }
    if (type == 'messages_changed') {
      // Before the activity check below: this payload is traffic between
      // harnesses, never a turn of the pane's own.
      agentMessages.handleEvent(payload);
      return;
    }
    // Only terminal protocol frames visit the session pool. Heartbeats, dial
    // scroll and discovery events must not await every retained terminal.
    // Each session still sees terminal frames: ready replies match their own
    // request/agent, while transport errors must reach the whole machine.
    if (type.startsWith('terminal_')) {
      for (final session in _terminalSessionsFor(machineId).toList()) {
        await session.handleFrame(type, payload);
      }
      return;
    }
    if (type == 'agent_activity' ||
        _modelAnswerEvents.contains(type) ||
        payload.containsKey('activity') ||
        type == 'turn_started' ||
        type == 'turn_heartbeat' ||
        type == 'turn_ended') {
      final agentId = _eventAgentId(machine, event, payload);
      final agent = machine.agents
          .where((agent) => agent.id == agentId)
          .firstOrNull;
      final sessionId = _eventSessionId(event, payload);
      // Heartbeats need the same conversation check as transcript events.
      // Late work from a previous conversation must neither revive this
      // harness nor end a newer turn after it has been resumed or replaced.
      if ((agent?.isStopped == true && type != 'turn_ended') ||
          (sessionId != null &&
              agent?.sessionId != null &&
              sessionId != agent!.sessionId)) {
        return;
      }
    }
    final reportedActivity = AgentActivity.fromJson(payload['activity']);
    if (reportedActivity != null) {
      final id = _eventAgentId(machine, event, payload);
      if (id != null) {
        final applied = _applyReportedActivity(machine, id, reportedActivity);
        if (applied.changed) notifyListeners();
        if (!applied.accepted &&
            (type == 'turn_ended' || type == 'turn_started')) {
          return;
        }
      }
    }
    if (type == 'agent_activity') return;
    if (type == 'text_delta' &&
        event['replay'] != true &&
        machine.liveTurnAgents.contains(
          _eventAgentId(machine, event, payload),
        )) {
      productMeasurement.milestone(ProductHealthMeasure.funnelFirstResponse);
      final id = _eventAgentId(machine, event, payload);
      if (id != null) productMeasurement.firstRunResponse(machineId, id);
    }
    if (reportedActivity == null &&
        event['replay'] != true &&
        const {
          'text_delta',
          'thinking_delta',
          'thinking_title',
          'tool_start',
          'tool_end',
        }.contains(type)) {
      final id = _eventAgentId(machine, event, payload);
      if (id != null && !machine.activityOrder.containsKey(id)) {
        machine.legacyHeartbeatSeen.remove(id);
        if (_markAgentProcessing(machine, id)) notifyListeners();
      }
    }

    // Before the preview's early returns: several first-output kinds (`thinking_delta`) are not
    // preview events at all.
    if (type == 'turn_started' || _modelAnswerEvents.contains(type)) {
      _watchModelStart(machine, type, event, payload);
    }
    if (SessionPreviewStore.eventTypes.contains(type)) {
      // A real agent event: the daemon's work frame may step once.
      if (type != 'user_message') agentPulse.value++;
      final agentId = _eventAgentId(machine, event, payload);
      final agent = machine.agents
          .where((agent) => agent.id == agentId)
          .firstOrNull;
      final sessionId = _eventSessionId(event, payload);
      if (agent != null &&
          sessionId != null &&
          agent.sessionId != null &&
          sessionId != agent.sessionId) {
        return;
      }
      if (agent != null &&
          (sessionId == null ||
              agent.sessionId == null ||
              sessionId == agent.sessionId)) {
        sessionPreviews.ingest(
          previewKey(machineId, agent),
          type,
          payload,
          streamingText: agent.engine == 'opencode' || agent.engine == 'kilo',
        );
      }
      // Content belongs to the preview's notifier. It must not invalidate the
      // entire workspace and catalog for every token or tool event.
      if (type != 'turn_started' && type != 'turn_ended') return;
    }
    switch (type) {
      // ── the dial, over the cable, forwarded by the local daemon ──────────────────────────────────
      // Local-only frames (backend.sendLocal in the harness CLI): they describe a hand at THIS desk, so
      // they never reach the cloud web audience, who may be sitting at another computer entirely.
      case 'dial_status':
        // The dial came, went, or started taking an update. Its own notifier —
        // see [dial] — so nothing else in the window rebuilds for it.
        if (!machine.isLocalMachine) return;
        dial.apply(DialStatus.fromJson(payload));
        _syncDeviceHosts();
        deviceHosts.receive(machineId, dial.status);
        return;
      case 'harness_devices_changed':
        if (machine.machine.isShared) return;
        if (payload['status'] case final Map<String, dynamic> status) {
          _syncDeviceHosts();
          deviceHosts.receive(
            machineId,
            DialStatus.fromJson(status),
            revision: payload['revision'] is int
                ? payload['revision'] as int
                : null,
          );
        }
        return;
      case 'dial_scroll':
        // Straight through, including the reports carrying no travel — the ends of a stroke are the point
        // of the message. The window does no arithmetic here; the terminal that owns the scrollback does.
        final phase = switch (payload['phase']) {
          'down' => 0,
          'up' => 2,
          _ => 1,
        };
        // A finger going down is the gesture; moves and the inertial tail
        // must not keep asking macOS for focus after the person switches away.
        if (phase == 0) _requestDeviceWindow(machine);
        final dy = (payload['dy'] as num?)?.round() ?? 0;
        final velocity = (payload['velocity'] as num?)?.round() ?? 0;
        // A Lead's view on the device: that Swarm's chat scrolls, never a pane.
        if (payload['superTabId'] case final String superTabId) {
          _superTabScrollHandlers[superTabId]?.call(phase, dy, velocity);
          return;
        }
        final pane = focusedPane;
        final cloudScroll = pane?.agentId == null
            ? null
            : _cloudScrollHandlers[(pane!.machineId, pane.agentId!)];
        if (cloudScroll != null) {
          cloudScroll(phase, dy, velocity);
        } else {
          activeTerminal?.scroll(phase, dy, velocity);
        }
        return;
      case 'dial_selection':
        final reply = const ['search', 'match'].contains(payload['op'])
            ? await searchDevicePassage(machineId, payload)
            : selectDevicePassage(machineId, payload);
        if (reply != null) {
          await _pool?[machineId]?.sendTerminalFrame(
            'app_selection_result',
            reply,
          );
        }
        return;
      case 'dial_visit':
        final result = visitFromDevice(machineId, payload);
        if (result != null) {
          await _pool?[machineId]?.sendTerminalFrame(
            'app_visit_result',
            result,
          );
        }
        return;
      case 'dial_form':
        final result = await formFromDevice(machineId, payload);
        if (result != null) {
          await _pool?[machineId]?.sendTerminalFrame('app_form_result', result);
        }
        return;
      case 'device_focus':
        unawaited(ensureDeviceFocus(payload));
        break;
      case 'dial_focus':
        // Turning the dial to an agent brings that agent's terminal up here — the ordinary selection
        // path, the same one a click on the rail takes, failing the same way for a missing terminal,
        // an offline machine or an unknown id.
        //
        // It used to carry an `edge` for an agent with no tile, naming which end of the desk the
        // carousel had walked off so a tile could be replaced there. The carousel walks only open
        // panes now, so every focus it sends is about a pane that already exists.
        final agentId = payload['agentId'];
        if (agentId is String && agentId.isNotEmpty) {
          final targetMachineId = _dialFocusMachine(payload, agentId);
          if (targetMachineId != null) {
            _requestDeviceWindow(machine);
            unawaited(selectAgentFromDial(targetMachineId, agentId));
          }
        }
        break;
      case 'voice_route_request':
        // WORDS SPOKEN INTO THE DIAL, handed here to be routed.
        //
        // The dial used to pick the agent itself with an older copy of this router — no candidate cap,
        // untrimmed recaps, a shorter budget, and no way to ask when it was unsure, so an uncertain
        // route was still a send. This window has the palette that can hold the answer up, so the
        // decision moved to it and the dial became the microphone.
        //
        // The daemon is waiting on a reply for this voiceId; SpokenTask is what guarantees one goes
        // back on every path out of the palette.
        final voiceId = payload['voiceId'];
        final spokenText = payload['text'];
        if (voiceId is String &&
            voiceId.isNotEmpty &&
            spokenText is String &&
            spokenText.trim().isNotEmpty) {
          _spokenTasks.add(
            SpokenTaskRequest(
              voiceId: voiceId,
              machineId: machineId,
              text: spokenText.trim(),
              cmd: payload['cmd'] is String ? payload['cmd'] as String : '',
            ),
          );
        }
        break;
      case 'dial_swarm':
        // The dial picked a swarm from its own list. The ordinary switch, exactly as ⌘] or a click on
        // the tab: the desk changes, `_persistLayout` re-describes it, and the dial's ring and swarm
        // line follow from that — nothing is answered to the dial directly.
        final swarmId = payload['swarmId'];
        if (swarmId is String && swarmId.isNotEmpty) {
          if (swarms.any((swarm) => swarm.id == swarmId)) {
            _requestDeviceWindow(machine);
          }
          _fromDevice(() => selectSwarm(swarmId));
        }
        break;
      case 'dial_super_tab':
        // The Harness Pro picked a Lead's project. Show that Swarm, then the
        // project's Lead chat as a click on its row in the sidebar does. A
        // round dial names the chat it shows: 'buddy' opens the reader's
        // Buddy chat there; anything else is the Lead chat.
        final tabId = payload['superTabId'];
        final projectId = payload['projectId'];
        if (payload['threadOnly'] == true) {
          // The dial opened or closed a thread of a chat the app already
          // shows: no window raised, no Swarm switched, no chat re-selected.
          final conversationId = payload['conversationId'];
          if (tabId is String && conversationId is String) {
            await _dialThreadOnly(
              tabId,
              conversationId,
              payload['threadRoot'] as Object?,
            );
          }
        } else if (tabId is String && projectId is String) {
          await _openSuperTabProject(
            machine,
            tabId,
            projectId,
            buddy: payload['chat'] == 'buddy',
          );
        }
        break;
      case 'dial_forked':
        // The dial forked an agent; the daemon already opened the pane on its
        // machine. Land it beside its source and focus it, as the window's own
        // Fork does.
        final forkId = payload['agentId'];
        final forkSource = payload['sourceAgentId'];
        if (forkId is String && forkId.isNotEmpty) {
          final targetMachineId = _dialFocusMachine(payload, forkId);
          if (targetMachineId != null) {
            _requestDeviceWindow(machine);
            unawaited(
              _fromDevice(
                () => placeFork(
                  targetMachineId,
                  forkId,
                  sourceAgentId: forkSource is String ? forkSource : '',
                ),
              ),
            );
          }
        }
        break;
      case 'grid_models_changed':
        // The daemon's picture of the account's grids changed — read without waking any of them,
        // so this arrives for a grid going to sleep as well as for a model coming up. The payload
        // is the whole `grid_models_list` document: adopted as it is, with no request.
        gridPictures.adopt(machineId, GridModels.fromReply(payload));
        break;
      case 'machines_changed':
        // The account's machine list changed somewhere: a machine created,
        // renamed or deleted, or a shared harness invited or taken back. The
        // payload is only a reason; the list itself is re-read, once for the
        // copies every connected machine relays. Only `harness_shares` has it
        // read the shares too, which take seconds (ApiClient.sharesChanged).
        if (payload['reason'] == 'harness_shares') api.sharesChanged();
        _machinesPushTimer ??= Timer(machinesPushCollapse, () {
          _machinesPushTimer = null;
          unawaited(_rereadMachinesInBackground(pushed: true));
        });
        break;
      case 'device_keys_changed':
        // The account's device key log grew. A viewer re-reads and verifies it itself; a desktop
        // build's daemon already did, and the Devices list re-reads it from there.
        if (_deviceLog case final log?) {
          unawaited(log.refresh());
        } else {
          unawaited(_syncPendingDevices());
        }
        devicesRevision++;
        notifyListeners();
        break;
      case 'device_key_removed':
        // Only this computer's own daemon says this (see [_isOwnDaemonMachine]).
        if (_isOwnDaemonMachine(machineId)) {
          if (DeviceRemovalNotice.fromJson(payload) case final notice?)
            _announceRemoval(notice);
        }
        break;
      case 'device_conflict':
        // A hint: the conflict itself is re-read from the daemon's listing, never taken from the frame.
        if (_isOwnDaemonMachine(machineId)) {
          devicesRevision++;
          unawaited(_syncPendingDevices());
        }
        break;
      case 'device_key_added':
        // Only this computer's own daemon says this (a viewer build has no daemon, and a machine's
        // frame must not be able to raise a notice here).
        if (_isOwnDaemonMachine(machineId)) {
          final pub = payload['pub'],
              label = payload['label'],
              kind = payload['kind'];
          if (pub is String && kind is String) {
            final fp = payload['fingerprint'];
            _announceDevice(
              NewDeviceNotice(
                pub: pub,
                label: label is String ? label : '',
                kind: kind,
                frameFingerprint: fp is String ? fp : null,
              ),
            );
            unawaited(_syncPendingDevices());
          }
        }
        break;
      case 'desk_changed':
        unawaited(experimentalFeatures.refresh());
        // A tab's leader is kept with the tabs and may have changed with them.
        unawaited(agentMessages.refresh());
        // Another window — on another computer, or this one — changed the
        // tabs. The payload is only the revision; the document is fetched.
        final deskRevision = payload['revision'];
        if (deskRevision is! int || deskRevision > _desk.revision) {
          unawaited(_deskFetch());
        }
        break;
      case 'daemon_state':
      case 'daemon_say':
      case 'daemon_unsay':
      case 'daemon_brief':
      case 'daemon_act_result':
      case 'daemon_confirm_result':
      case 'daemon_talk_result':
      case 'daemon_open_result':
      case 'pair_result':
      case 'daemon_plate':
        // Only from the loopback socket bound to this computer's harnessd.
        if (machine.usesLocalTransport) {
          _daemonFrames.add((type: type, payload: payload));
        }
        return;
      case 'zoo_changed':
        // The account's daemons and eggs changed (daemons/README.md). Its own
        // path: a zoo change never re-reads the desk, and the other way round.
        final zooRevision = payload['revision'];
        _zooPushes.add(zooRevision is int ? zooRevision : null);
        return;
      case 'device_prepare_open':
        final operationId = payload['operationId'];
        final prepareAgentId = payload['agentId'];
        final prepareMachineId = payload['machineId'];
        if (operationId is String &&
            RegExp(r'^[a-f0-9]{64}$').hasMatch(operationId) &&
            prepareAgentId is String &&
            prepareAgentId.isNotEmpty &&
            prepareMachineId == machineId) {
          unawaited(() async {
            try {
              if (await revealPreparedAgent(
                machineId,
                prepareAgentId,
                operationId,
              )) {
                await _pool?[machineId]?.sendTerminalFrame(
                  'device_prepare_opened',
                  {'operationId': operationId, 'agentId': prepareAgentId},
                );
              }
            } catch (error) {
              appLog.warn('device', 'Could not reveal prepared agent: $error');
            }
          }());
        }
        break;
      case 'dial_notification_read':
        final readId = payload['agentId'];
        final readMachine = payload['machineId'];
        final readToken = payload['readToken'];
        if (readId is String &&
            readMachine is String &&
            readToken is String &&
            readToken.isNotEmpty) {
          readAgentNotification(readMachine, readId, readToken: readToken);
        }
        break;
      case 'dial_open':
        // A notification was tapped on the dial. Unlike `dial_focus` this asks for a tile of its own —
        // see openAgentFromDial for why a finished turn is not a replacement for what is on screen.
        final openId = payload['agentId'];
        if (openId is String && openId.isNotEmpty) {
          final targetMachineId = _dialFocusMachine(payload, openId);
          if (targetMachineId != null) {
            if (payload['reason'] != 'question') _requestDeviceWindow(machine);
            unawaited(
              openAgentFromDial(
                targetMachineId,
                openId,
                fromQuestion: payload['reason'] == 'question',
              ),
            );
          }
        }
        break;
      case 'remote_terminal_handoff':
        // `harness remote`, typed in one of this window's terminal tiles, opened a
        // terminal on another machine: that tile becomes the new agent's, in
        // place, and the shell it was typed in is ended. Pushed to every
        // loopback client; only the window holding the tile acts.
        final fromAgentId = payload['fromAgentId'];
        final toMachineId = payload['machineId'];
        final toAgentId = payload['agentId'];
        if (fromAgentId is String &&
            fromAgentId.isNotEmpty &&
            toMachineId is String &&
            toMachineId.isNotEmpty &&
            toAgentId is String &&
            toAgentId.isNotEmpty) {
          unawaited(
            handoffTerminalPane(
              machine.machine.machineId,
              fromAgentId,
              toMachineId,
              toAgentId,
            ),
          );
        }
        break;
      case 'node_status':
        final online = payload['online'] == true;
        await _applyNodeStatus(machine, online, why: 'node_status');
        break;
      case 'machine_select_error':
        _selectRefused(machine, '${payload['error'] ?? ''}');
        break;
      case 'agent_synced':
        final raw = payload['agent'];
        if (raw is Map) {
          try {
            final agent = Agent.fromJson(Map<String, dynamic>.from(raw));
            var changed = _upsertAgent(machine, agent);
            _openStartedChild(
              machine,
              agent,
              arrived: machine.agentsListedOnce,
            );
            if (agent.terminalAvailable) {
              // A pane created before this agent's terminal was verified is still sitting on
              // "Attaching…" with no session — nothing else re-checks it once agentLoadStatus is
              // already `loaded`, so this push is the only signal that it can attach now.
              _attachPendingPanes(machine, intent: AttachIntent.automatic);
            } else {
              // A process replacement can briefly publish an agent before its
              // terminal route is verified. `agent_synced` is a snapshot, not
              // a deletion authority: removing every tile here turns that
              // short gap into a lost workspace even though tmux and the
              // agent are still alive. Keep the pane/layout intent and let a
              // later available sync reattach it. A confirmed `agent_deleted`
              // event remains the sole path that removes a person's panes.
              for (final pane in panesFor(machine.machine.machineId)) {
                if (pane.agentId != agent.id || pane.session == null) continue;
                await _detachSession(pane, sendClose: false);
                changed = true;
              }
            }
            if (!changed) return;
          } catch (_) {
            unawaited(_loadMachineData(machine, force: true));
          }
        } else {
          unawaited(_loadMachineData(machine, force: true));
        }
        break;
      case 'agent_created':
        final raw = payload['agent'];
        if (raw is Map && raw['terminal'] is Map) {
          try {
            final agent = Agent.fromJson(Map<String, dynamic>.from(raw));
            _upsertAgent(machine, agent);
            _openStartedChild(
              machine,
              agent,
              arrived: machine.agentsListedOnce,
            );
            // Same reattach as `agent_synced` above — a pane can be waiting on this exact agent
            // (e.g. one this window's own New Agent dialog just opened) with no session yet.
            _attachPendingPanes(machine, intent: AttachIntent.automatic);
          } catch (_) {
            unawaited(_loadMachineData(machine, force: true));
          }
        } else {
          unawaited(_loadMachineData(machine, force: true));
        }
        break;
      case 'agent_renamed':
        final agentId = _eventAgentId(machine, event, payload);
        final name = payload['name'];
        if (agentId != null && name is String) {
          if (!_renameAgent(machine, agentId, name)) return;
        } else {
          unawaited(_loadMachineData(machine, force: true));
        }
        break;
      case 'agent_deleted':
        final goneId = _eventAgentId(machine, event, payload);
        if (goneId != null) {
          agentUnread.forget(machineId, goneId);
          _readQuestionNotifications.remove(
            AgentUnread.keyFor(machineId, goneId),
          );
        }
        final agentId = _eventAgentId(machine, event, payload);
        final successor = payload['successor'];
        if (agentId != null && successor is String && successor.isNotEmpty) {
          await _handOverViews(machine, agentId, successor);
        }
        if (agentId != null) {
          await _removeAgent(machine, agentId);
        }
        // Only a daemon that retained this stop asks us to refresh history.
        // A legacy deletion must not race a newly reused identity with an
        // unnecessary inventory request.
        if (agentId == null || payload['retained'] == true) {
          unawaited(_loadMachineData(machine, force: true));
        }
        break;
      // An agent stopped and is waiting on the person. Ignored by this window
      // until now, even though the daemon had already shaped the question for
      // the dial — `sendCommander` is device-only, so it never came down this
      // wire at all.
      case 'dsh_install_status':
        // The machine narrating an install this window (or another) asked for.
        // Only ever advances a known install: a phase for an id nobody here
        // asked about is still worth showing, so it is recorded either way.
        final progress = DshInstallProgress.fromJson(payload);
        if (progress != null) machine.dsh.applyInstall(progress);
        break;
      case 'commander_question':
        final agentId = _eventAgentId(machine, event, payload);
        if (agentId != null) {
          final asked = PendingQuestion.fromPayload(
            machineId: machineId,
            agentId: agentId,
            payload: payload,
            now: DateTime.now(),
          );
          if (asked != null) {
            // The daemon re-announces an open question after a reconnect, and
            // on attaching to a turn that was already mid-dialog. Keep the
            // original clock in that case: this is the same wait continuing,
            // and restarting it would make a long block look new.
            final known = machine.blockedAgents[agentId];
            final repeat = known != null && known.sameAs(asked);
            machine.blockedAgents[agentId] = repeat
                ? asked.withSince(known.since)
                : asked;
            // Only a NEW question earns a sound. The daemon re-announces every open one after a
            // reconnect and when attaching to a turn that was already mid-dialog, and a window
            // that beeped at those would sound an alarm every time the network hiccuped.
            if (!repeat && !questionNotificationRead(machineId, agentId)) {
              _readQuestionNotifications.remove(
                AgentUnread.keyFor(machineId, agentId),
              );
              _raiseAlert(machine, agentId, AlertKind.needsYou);
            }
          }
        }
        break;
      // It stopped being on screen — answered here, in the pane by hand, on
      // another window, or on the dial. Whoever got there first, everyone else
      // is told to stop drawing it.
      case 'commander_question_close':
        final agentId = _eventAgentId(machine, event, payload);
        final requestId = payload['requestId'];
        if (agentId != null) {
          final open = machine.blockedAgents[agentId];
          if (open != null && open.requestId == requestId) {
            machine.blockedAgents.remove(agentId);
            _readQuestionNotifications.remove(
              AgentUnread.keyFor(machineId, agentId),
            );
            // An old question close cannot erase a newer completed result.
            if (agentUnread.kindFor(machineId, agentId) == AlertKind.needsYou) {
              _forgetUnread(machineId, agentId);
            }
          }
        }
        break;
      case 'turn_started':
      case 'turn_heartbeat':
        var changed = false;
        final agentId = _eventAgentId(machine, event, payload);
        if (agentId != null) {
          if (type == 'turn_started' && event['replay'] != true) {
            machine.liveTurnAgents.add(agentId);
            productMeasurement.milestone(ProductHealthMeasure.funnelFirstWork);
            productMeasurement.firstRunWork(machineId, agentId);
            _measurementResumes
                .remove(_turnActivityKey(machineId, agentId))
                ?.call(ProductOutcome.ok);
            changed = machine.failedTurnAgents.remove(agentId);
          }
          if (reportedActivity == null &&
              event['replay'] != true &&
              !machine.activityOrder.containsKey(agentId)) {
            if (type == 'turn_started') {
              machine.legacyHeartbeatSeen.remove(agentId);
            }
            // Older daemons renew historical turn flags forever. One unverified
            // heartbeat is bounded; only real new work can establish it again.
            if (type == 'turn_started' ||
                machine.legacyHeartbeatSeen.add(agentId)) {
              changed = _markAgentProcessing(machine, agentId) || changed;
            }
          }
          // Only a START opens a stats turn, for the reason above: a heartbeat
          // is a turn already under way, and counting one would report an agent
          // this app merely reconnected to as work somebody just asked for.
          if (type == 'turn_started' && event['replay'] != true) {
            final key = _turnActivityKey(machine.machine.machineId, agentId);
            changed = harnessStats.turnStartedAt(key) == null || changed;
            harnessStats.onTurnStarted(key);
          }
        } else {
          final sessionId = _eventSessionId(event, payload);
          if (sessionId != null &&
              event['replay'] != true &&
              reportedActivity == null) {
            changed = machine.pendingProcessingSessions.add(sessionId);
          }
        }
        // Renew the watchdog on every heartbeat, but redraw only when the
        // agent becomes busy or its start time becomes known. Expiry and turn
        // end publish separately.
        if (!changed) return;
        break;
      case 'turn_summary':
        final notification = payload['notification'];
        final agentId = _eventAgentId(machine, event, payload);
        if (agentId == null || notification is! Map) return;
        final id = notification['id'];
        if (id is! String || id.isEmpty || notification['kind'] != 'done') {
          return;
        }
        if (!_deliveredNotifications.add('$machineId/$id')) return;
        while (_deliveredNotifications.length > 512) {
          _deliveredNotifications.remove(_deliveredNotifications.first);
        }
        _raiseAlert(
          machine,
          agentId,
          AlertKind.done,
          message:
              previewText(payload['recap'], limit: 600) ??
              previewText(payload['text'], limit: 600),
        );
        break;
      case 'turn_ended':
        final agentId = _eventAgentId(machine, event, payload);
        if (agentId != null) {
          final live = machine.liveTurnAgents.remove(agentId);
          // A SUB-AGENT'S turn end is not news — an Orchestrator specialist, or
          // its Director while specialists are still out. The dial has always
          // known (`silent` on its summary card) and this window never did, so a
          // project of four specialists put one row on the dial and five marks
          // here. Same predicate now, asked on the daemon: `isSubagentSession`.
          if (event['subagent'] != true) {
            final failed = event['error'] != null || payload['error'] != null;
            final agent = machine.agents
                .where((a) => a.id == agentId)
                .firstOrNull;
            final ownWork =
                agent != null &&
                !machine.machine.isShared &&
                !isTerminalEngine(agent.engine) &&
                allPanes.any(
                  (pane) =>
                      pane.machineId == machine.machine.machineId &&
                      pane.agentId == agentId &&
                      pane.session != null,
                );
            // Activity belongs to the harness, even if its pane is currently
            // detached. The zoo counters below still count only our own work.
            if (agent != null && !isTerminalEngine(agent.engine)) {
              if (failed) {
                machine.failedTurnAgents.add(agentId);
              } else {
                machine.failedTurnAgents.remove(agentId);
              }
            }
            if (ownWork && !failed) {
              machine.completedHarnessUses.add((
                harness: agent.dsh == null
                    ? 'coding'
                    : canonicalHarnessId(agent.dsh!),
                model: agent.gridModel,
              ));
              machine.completedHarnessTurns++;
              unawaited(_offerPhoneAfterWork());
            } else if (ownWork) {
              machine.failedHarnessTurns++;
            }
            if (ownWork) {
              machine.recentTurnEnds.add((agentId: agentId, failed: failed));
              if (machine.recentTurnEnds.length > 16) {
                machine.recentTurnEnds.removeAt(0);
              }
            }
            if (live &&
                agent != null &&
                !failed &&
                payload['aborted'] != true &&
                !machine.machine.isShared &&
                !isTerminalEngine(agent.engine) &&
                agent.dsh != 'autonomous/pair') {
              machine.zooTurns++;
            }
          }
          _cancelTurnActivity(
            machine.machine.machineId,
            agentId,
            clearQuestion: false,
          );
        } else {
          final sessionId = _eventSessionId(event, payload);
          if (sessionId != null) {
            machine.pendingProcessingSessions.remove(sessionId);
          }
        }
        break;
      default:
        // RPC replies and frames owned by other controllers carry no app
        // state changes. They must not trigger a full workspace rebuild.
        return;
    }
    notifyListeners();
  }

  /// Feed one machine event straight into the dispatcher.
  ///
  /// The frames worth testing here have no terminal to route through and no
  /// socket to arrive on — what they exercise is the bookkeeping either side of
  /// that, which is exactly what a live socket makes hard to reach.
  @visibleForTesting
  Future<void> restorePaneLayoutForTest({bool claimOnAttach = false}) =>
      _restorePaneLayout(claimOnAttach: claimOnAttach);

  @visibleForTesting
  Future<void> syncAgentsIfChangedForTest(String machineId) =>
      _syncAgentsIfChanged(machineStates[machineId]!);

  @visibleForTesting
  Future<void> handleMachineEventForTest(
    String machineId,
    Map<String, dynamic> event,
  ) => _handleEvent(machineId, event);

  @visibleForTesting
  Future<void> handleTerminalBinaryForTest(String machineId, Uint8List frame) =>
      _handleTerminalBinary(machineId, frame);

  /// Put an already-built session on the grid.
  ///
  /// The seam tests used to get from assigning `activeTerminal` directly, which
  /// a grid cannot offer: a session on screen is a session in a TILE, and the
  /// tile is what every lifecycle path — a machine going offline, an agent
  /// being deleted, a frame arriving — actually looks for.
  @visibleForTesting
  TerminalPane adoptSessionForTest(TerminalSession session) {
    final pane = TerminalPane(
      id: _nextPaneId++,
      machineId: session.machineId,
      agentId: session.agentId,
    )..session = session;
    panes.add(pane);
    focusedPaneId = pane.id;
    session.addListener(_onSessionChanged);
    return pane;
  }

  @visibleForTesting
  Future<void> handleEventForTest(
    String machineId,
    Map<String, dynamic> event,
  ) => _handleEvent(machineId, event);

  @visibleForTesting
  void clearDeviceNoticeStateForTest() => _clearDeviceNoticeState();

  @visibleForTesting
  bool get pendingBootReadDoneForTest => _pendingBootReadDone;

  /// Local discovery having found this computer's own daemon, which serves [machineId].
  @visibleForTesting
  void ownDaemonMachineIdForTest(String? machineId) {
    _cliEndpoint = machineId == null
        ? null
        : LocalCliEndpoint(
            computerId: 'test-computer',
            wsUri: Uri.parse('ws://127.0.0.1:1/ws'),
            protocolVersion: localWsProtocolVersion,
            terminalProtocolVersion: localTerminalProtocolVersion,
            machineId: machineId,
          );
  }

  /// The supervisor's five-second "daemon ready" snapshot, without a supervisor.
  @visibleForTesting
  void daemonSnapshotForTest(LocalCliEndpoint endpoint) =>
      _updateLocalProjectSnapshot(endpoint);

  /// [connection] as [machineId]'s socket in the pool, which the frames this window broadcasts (the
  /// dial's roster, the unread list) are sent on — [connectionForTest] stands in for `_conn` only.
  @visibleForTesting
  void adoptPoolConnectionForTest(String machineId, WsConn connection) {
    _ensurePool();
    _pool!.adoptForTest(machineId, connection);
  }

  /// What the local CLI closing this machine's socket with [code] does to the
  /// model — the `WsPool.onLocalFailure` path, without a socket.
  @visibleForTesting
  void localFailureForTest(String machineId, int code, String reason) =>
      _onLocalFailure(machineId, code, reason);

  @override
  void dispose() {
    _approvalRefresh?.cancel();
    if (identical(CrashLog.healthError, _measurementError)) {
      CrashLog.healthError = null;
    }
    productRuntimeHealth?.dispose();
    productConnections.dispose();
    _measurementResumes.clear();
    productMeasurement.removeListener(_measurementChoiceChanged);
    productMeasurement.dispose();
    _measurementConnections.clear();
    if (cliLogin case final CliLogin cli) {
      cli.waitingNote.removeListener(_loginWaitingChanged);
    }
    paneLanding.dispose();
    _closeOwnerMemories();
    _agentDownloadsTick?.cancel();
    agentPrefetch?.close();
    setupDownloads.dispose();
    experimentalFeatures.dispose();
    deviceHosts.dispose();
    viewer?.auth.dispose();
    _deviceVisit?.dispose();
    _modelManager?.dispose();
    for (final controller in _essentials.values) {
      controller.dispose();
    }
    _modelsMenu?.dispose();
    agentMessagesRemote.dispose();
    agentMessages.dispose();
    sharedTabs.dispose();
    superTabs.dispose();
    for (final project in _orchestratorProjects.values) {
      project.dispose();
    }
    grid.AppTheme.palette.removeListener(_announceTerminalThemeEverywhere);
    terminalThemeStore.removeListener(_announceTerminalThemeEverywhere);
    appearancePrefsStore.removeListener(_autoRenameChanged);
    windowNames.dispose();
    _localGitProjects.dispose();
    sessionPreviews.dispose();
    agentPulse.dispose();
    sessionTails.dispose();
    gridPictures.dispose();
    _stopWakeFollowers();
    modelStarts.dispose();
    foreground.dispose();
    inSight.dispose();
    // Its sweep timer would otherwise outlive the window it was drawing into.
    agentAlerts.dispose();
    agentUnread.dispose();
    _disposed = true;
    _closeAttachmentSessions();
    _sharingDiscoveryTimer?.cancel();
    _machinesPushTimer?.cancel();
    _deafMachineListWatch.stop();
    _stopMachineRecovery();
    if (signingIn) cliLogin.cancel();
    _closedHistory.clear();
    _monitorHarnesses.clear();
    _daemonSupervisionTimer?.cancel();
    _updateCheckTimer?.cancel();
    _launchClaimTimer?.cancel();
    _environmentRecheckTimer?.cancel();
    _stopAllOfflineRetries();
    _stopAllLinkRetries();
    _stopAllAgentSyncTimers();
    _clearAllTurnActivity();
    for (final pane in allPanes) {
      pane.session?.removeListener(_onSessionChanged);
      pane.session?.dispose();
    }
    for (final swarm in swarms) {
      swarm.panes.clear();
    }
    unawaited(_spokenTasks.close());
    unawaited(_deviceWindowRequests.close());
    unawaited(_deviceJoins.close());
    unawaited(_zooPushes.close());
    unawaited(_daemonFrames.close());
    unawaited(_modelsRequests.close());
    unawaited(_superTabClosures.close());
    for (final request in _joinAccountRequests) {
      request.complete(null);
    }
    super.dispose();
  }
}

final appStateProvider = Provider<AppNotifier>((ref) {
  final app = AppNotifier(
    config: AppConfig.dev,
    authSession: AuthSession(),
    configStore: ConfigStore(),
    paneLayoutStore: PaneLayoutStore(),
    workspaceEnabled: () =>
        !kIsWeb || ViewerLocation.workspaceAllowed(Uri.base),
  );
  app.bootstrap();
  return app;
});

/// What a refused `machine_select` means, in words a person can act on (backend lib/webWs.ts codes).
String machineSelectErrorText(String code, String machine) => switch (code) {
  'NOT_YOUR_MACHINE' => '$machine is no longer on your account.',
  'MACHINE_ENV_MISMATCH' =>
    '$machine belongs to another Autonomous environment. Sign in to that one to use it.',
  'MACHINE_PAYMENT_PENDING' => '$machine is waiting for its payment to finish.',
  'MACHINE_SUBSCRIPTION_REQUIRED' =>
    'The subscription for $machine has ended. Renew it to use it again.',
  _ => 'Could not connect to $machine. Try again in a moment.',
};

/// The startup stopwatch as its log line: each step, in the order it finished.
String startupLogLine(Map<String, int> timings) => timings.entries
    .map((step) => '${step.key} after ${step.value} ms')
    .join(', ');