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.

7.6 KB
Raw Blame
import 'package:harness_mobile/core/models.dart';
import 'package:harness_mobile/state/app_state.dart';

/// How a phone status line is coloured. The widgets turn this into a palette colour, so the
/// rules below stay testable without a theme.
enum PhoneTone { good, busy, attention, bad, quiet }

/// A status line: what it says, and how it is coloured.
typedef PhoneSummary = ({String label, PhoneTone tone});

/// What a machine's row says, and so where a tap on it goes.
enum PhoneMachineStatus {
  /// Reachable, but this device holds no link to it yet. A tap asks for THAT machine's remote
  /// password — every machine sets its own.
  needsPassword,

  /// Harness is not running there, so none of its agents can be reached until it is.
  offline,

  /// The socket is still coming up, or its agent list has not answered yet.
  connecting,

  /// Linked and answering: a tap lists its agents.
  ready,
}

PhoneMachineStatus phoneMachineStatusOf(MachineState machine) {
  // ⚠️ Offline FIRST. A machine that is switched off is almost always also unlinked from here — the
  // relay refuses the dial before the other computer is ever reached — so asking about the link
  // first called a powered-down machine "Needs its password" and offered a form that could only
  // fail. The password is worth asking for once there is something to give it to, which is what the
  // desktop's "Offline · Link required" already says.
  if (machine.nodeOnline == false) return PhoneMachineStatus.offline;
  // Its key not in the account's log yet ([MachineState.awaitingKey]): late, not locked. It comes
  // in by itself once the key lands; only a wait that runs out asks for its password.
  if (machine.needsLink) {
    return machine.awaitingKey
        ? PhoneMachineStatus.connecting
        : PhoneMachineStatus.needsPassword;
  }
  final answering =
      machine.connectionStatus == ConnectionStatus.connected &&
      machine.agentLoadStatus != AgentLoadStatus.loading;
  return answering ? PhoneMachineStatus.ready : PhoneMachineStatus.connecting;
}

/// The machine list's own word on whether a machine is up — its `/api/machines` status, not the
/// socket.
bool phoneAccountSaysOnline(String? status) =>
    switch (status?.trim().toLowerCase()) {
      'running' || 'online' || 'connected' || 'ready' => true,
      _ => false,
    };

/// Whether this phone can open [machine]'s terminals now: one it has, linked,
/// and not reported offline — the rule the terminal search draws "Offline" by
/// (`phone_search_catalog.dart`). A machine not heard from yet counts.
bool phoneMachineOpensTerminals(MachineState? machine) =>
    machine != null && !machine.needsLink && machine.nodeOnline != false;

/// Whether [machine] is away for real: offline by its socket's word, and the account's own record
/// agrees.
///
/// ⚠️ **Both, because the socket alone flaps.** One that drops while it is still being dialled
/// marks the node offline for a moment, for a machine that answers seconds later — saying "offline"
/// over that would flash a wrong word at every redial. A machine the account also lists as down is
/// one with nothing on the way: switched off, or Harness not running there yet (a computer just
/// restarted was measured taking 70s to reach the relay).
bool phoneMachineAway(MachineState machine) =>
    phoneMachineStatusOf(machine) == PhoneMachineStatus.offline &&
    !phoneAccountSaysOnline(machine.machine.status);

/// Whether [machine]'s agents belong on the agent screens: it is answering, or it answered and its
/// socket is only dialling again.
///
/// ⚠️ **The second half is what keeps a terminal on screen through a dropped socket.** Backgrounding
/// the app drops it every time, and a machine counted only while [PhoneMachineStatus.ready] took its
/// agents out of the list for the length of the redial — the pager, whose pages ARE that list, was
/// thrown away and the screen fell back to "Connecting to your computer…" on every return to the app.
/// A first connect has no list yet, so it still waits like one.
/// ⚠️ **Agents restored from the last run count too, and that is the whole
/// point of restoring them.** A warm-started machine is `connecting` (its socket
/// is genuinely still coming up) and `loading` (it genuinely still owes a list),
/// so the `loaded` test below hid exactly the agents the cache exists to show —
/// the phone read nine of them off disk at 520ms and still sat on "Connecting to
/// your machine…" until the handshake finished two seconds later.
///
/// Showing them is safe for the same reason showing a RECONNECTING machine's
/// agents is safe, which is what the paragraph above describes: the names are
/// last known good, the real list replaces them the moment it lands, and
/// `_replaceAgents` retires anything that has gone. The difference is only how
/// long ago "last known" was.
bool phoneMachineListsAgents(MachineState machine) =>
    switch (phoneMachineStatusOf(machine)) {
      PhoneMachineStatus.ready => true,
      PhoneMachineStatus.connecting =>
        machine.agentLoadStatus == AgentLoadStatus.loaded ||
            machine.agentsFromCache,
      PhoneMachineStatus.needsPassword || PhoneMachineStatus.offline => false,
    };

/// What a computer in [status] is called — one word, the same on every phone screen that names it:
/// Computers, Find, Settings ▸ Profile, a harness whose computer is away, and (capitalised, by
/// [phoneMachineSummary]) the New form's computer and a computer's own page.
///
/// ⚠️ **One word per state.** Computers and Profile said "asleep" and "locked" while the New form
/// and a computer's page said "Offline" and "Needs its password": one computer, two names a screen
/// apart. "offline" is the desktop's word. "locked" is kept over the desktop's "Link required"
/// because the phone's way in is Unlock — the row's "tap to unlock", the sheet's "Unlock…", the
/// Unlock page — and its first way is a scanned code, not a password.
String phoneMachineWord(PhoneMachineStatus status) => switch (status) {
  PhoneMachineStatus.ready => 'ready',
  PhoneMachineStatus.connecting => 'connecting',
  PhoneMachineStatus.needsPassword => 'locked',
  PhoneMachineStatus.offline => 'offline',
};

PhoneSummary phoneMachineSummary(MachineState machine) {
  final status = phoneMachineStatusOf(machine);
  final word = phoneMachineWord(status);
  final label = '${word[0].toUpperCase()}${word.substring(1)}';
  return switch (status) {
    PhoneMachineStatus.needsPassword => (
      label: label,
      tone: PhoneTone.attention,
    ),
    PhoneMachineStatus.offline => (label: label, tone: PhoneTone.bad),
    PhoneMachineStatus.connecting => (label: '$label…', tone: PhoneTone.busy),
    PhoneMachineStatus.ready => (
      label: _agentCount(machine.agents.length),
      tone: PhoneTone.good,
    ),
  };
}

String _agentCount(int count) => switch (count) {
  0 => 'No harnesses yet',
  1 => '1 harness',
  _ => '$count harnesses',
};

/// What an agent is doing, as its row says it. Waiting on the person outranks working, which
/// outranks everything else: it is the one state somebody has to act on.
PhoneSummary phoneAgentSummary(MachineState machine, Agent agent) {
  if (machine.blockedAgents.containsKey(agent.id)) {
    return (label: 'Waiting for you', tone: PhoneTone.attention);
  }
  if (machine.processingAgentIds.contains(agent.id)) {
    return (label: 'Working…', tone: PhoneTone.busy);
  }
  if (!agent.terminalAvailable) {
    return (
      label: agent.terminalUnavailableReason ?? 'No terminal',
      tone: PhoneTone.quiet,
    );
  }
  return (
    label: agent.engineDisplayName ?? agent.engine ?? 'Agent',
    tone: PhoneTone.quiet,
  );
}