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.

refactor(mobile): drop local harness CLI discovery and daemon supervision

dee2707a9ab0fee
diff --git a/mobile/lib/core/local_git_projects.dart b/mobile/lib/core/local_git_projects.dart
deleted file mode 100644
index d3e4d010b..000000000
--- a/mobile/lib/core/local_git_projects.dart
+++ /dev/null
@@ -1,337 +0,0 @@
-import 'dart:async';
-import 'dart:convert';
-import 'dart:io';
-
-import 'package:path/path.dart' as p;
-
-import 'models.dart';
-
-/// Compatibility for this computer's older daemon. Reads only Git metadata;
-/// directory watches invalidate the cache when a checkout or remote changes.
-/// No Git processes, network calls, terminal reads, or work on the render path.
-class LocalGitProjects {
- LocalGitProjects({required this.onChanged, DateTime Function()? now})
- : _now = now ?? DateTime.now;
- final void Function() onChanged;
- final DateTime Function() _now;
- static const _cacheAge = Duration(minutes: 1);
- final _entries = <String, _LocalGitEntry>{};
- bool _disposed = false;
-
- AgentProject? cached(String cwd) => _entries[cwd]?.project;
-
- Future<void> read(String cwd) {
- if (_disposed || !p.isAbsolute(cwd)) return Future.value();
- final existing = _entries[cwd];
- if (existing != null) {
- if (existing.pending != null) return existing.pending!;
- // Even a live watcher can miss a rename or a coalesced OS event. Check
- // again on ordinary discovery after the TTL; there is no polling timer.
- if (_now().difference(existing.checkedAt) < _cacheAge) {
- return Future.value();
- }
- return _refresh(cwd, existing);
- }
- if (_entries.length >= 256) {
- _entries.remove(_entries.keys.first)?.dispose();
- }
- final entry = _LocalGitEntry();
- _entries[cwd] = entry;
- return _refresh(cwd, entry);
- }
-
- Future<void> _refresh(String cwd, _LocalGitEntry entry) {
- if (_disposed || entry.disposed) return Future.value();
- if (entry.pending != null) {
- entry.dirty = true;
- return entry.pending!;
- }
- return entry.pending = _refreshEntry(cwd, entry);
- }
-
- Future<void> _refreshEntry(String cwd, _LocalGitEntry entry) async {
- try {
- do {
- entry.dirty = false;
- await _resolve(cwd, entry);
- } while (entry.dirty && !_disposed && !entry.disposed);
- } finally {
- entry.checkedAt = _now();
- entry.pending = null;
- }
- }
-
- Future<void> _resolve(String cwd, _LocalGitEntry entry) async {
- final targets = <String, Set<String>>{};
- void watch(String directory, Set<String> names) =>
- (targets[directory] ??= {}).addAll(names);
- try {
- if (!await Directory(cwd).exists()) {
- _publish(entry, null);
- return;
- }
- watch(p.normalize(cwd), {'.git'});
- var root = p.normalize(cwd);
- String? gitDir;
- for (var depth = 0; depth < 32; depth++) {
- final marker = p.join(root, '.git');
- final type = await FileSystemEntity.type(marker);
- if (type == FileSystemEntityType.directory) {
- gitDir = marker;
- break;
- }
- if (type == FileSystemEntityType.file) {
- targets.clear();
- watch(root, {'.git'});
- final pointer = await _text(marker);
- if (pointer?.startsWith('gitdir: ') == true) {
- final path = pointer!.substring(8).trim();
- if (path.isNotEmpty) gitDir = p.normalize(p.join(root, path));
- }
- break;
- }
- final parent = p.dirname(root);
- if (parent == root) break;
- root = parent;
- }
- if (gitDir == null) {
- _publish(entry, null);
- return;
- }
- // The working tree owns the .git pointer (and directory replacement),
- // while HEAD/config may live elsewhere. Keep watching that connection.
- targets.clear();
- watch(root, {'.git'});
- if (!await Directory(gitDir).exists()) {
- _publish(entry, null);
- return;
- }
- watch(gitDir, {'HEAD', 'commondir'});
- final shared = await _text(p.join(gitDir, 'commondir'));
- final common = shared == null
- ? gitDir
- : p.normalize(p.join(gitDir, shared.trim()));
- watch(common, {'config'});
- final head = (await _text(p.join(gitDir, 'HEAD')))?.trim();
- final config = await _text(p.join(common, 'config'));
- if (_disposed || entry.disposed) return;
- final branch = head?.startsWith('ref: refs/heads/') == true
- ? head!.substring(16)
- : head != null && RegExp(r'^[a-fA-F0-9]{40,64}$').hasMatch(head)
- ? 'Detached ${head.substring(0, 7)}'
- : null;
- final project = AgentProject.fromJson({
- 'name': p.basename(root),
- 'cwd': cwd,
- 'root': root,
- 'remote': _origin(config),
- 'branch': branch,
- });
- _publish(entry, project);
- } on FileSystemException {
- // A removed/unreadable working folder must not interfere with discovery.
- _publish(entry, null);
- } finally {
- if (!_disposed && !entry.disposed) _syncWatches(cwd, entry, targets);
- }
- }
-
- void _publish(_LocalGitEntry entry, AgentProject? project) {
- if (_disposed || entry.disposed || entry.project == project) return;
- entry.project = project;
- onChanged();
- }
-
- void _invalidate(String cwd, _LocalGitEntry entry) {
- if (_disposed || entry.disposed) return;
- entry.debounce?.cancel();
- entry.debounce = Timer(const Duration(milliseconds: 100), () {
- entry.debounce = null;
- unawaited(_refresh(cwd, entry));
- });
- }
-
- void _syncWatches(
- String cwd,
- _LocalGitEntry entry,
- Map<String, Set<String>> targets,
- ) {
- entry.watchTargets = targets;
- for (final directory in entry.watchers.keys.toList()) {
- if (!targets.containsKey(directory)) {
- unawaited(entry.watchers.remove(directory)!.cancel());
- }
- }
- entry.retryWatchAt.removeWhere((path, _) => !targets.containsKey(path));
- for (final directory in targets.keys) {
- if (entry.watchers.containsKey(directory) ||
- entry.retryWatchAt[directory]?.isAfter(_now()) == true) {
- continue;
- }
- late StreamSubscription<FileSystemEvent> subscription;
- void lost() {
- if (_disposed ||
- entry.disposed ||
- entry.watchers[directory] != subscription) {
- return;
- }
- entry.watchers.remove(directory);
- unawaited(subscription.cancel());
- // Refresh the data once, but wait for later discovery to retry a
- // failed watch. A permanently unavailable watcher must not loop.
- entry.retryWatchAt[directory] = _now().add(_cacheAge);
- _invalidate(cwd, entry);
- }
-
- bool related(String path) =>
- p.normalize(path) == directory ||
- entry.watchTargets[directory]?.contains(p.basename(path)) == true;
- try {
- subscription = Directory(directory).watch().listen(
- (event) {
- if (_disposed ||
- entry.disposed ||
- entry.watchers[directory] != subscription) {
- return;
- }
- if (related(event.path) ||
- event is FileSystemMoveEvent &&
- event.destination != null &&
- related(event.destination!)) {
- if (event.isDirectory &&
- (event is FileSystemCreateEvent ||
- event is FileSystemDeleteEvent ||
- event is FileSystemMoveEvent)) {
- // A replacement can reuse the path while the OS watch still
- // follows the old directory. Rebind those subscriptions.
- final changed = {
- p.normalize(event.path),
- if (event is FileSystemMoveEvent && event.destination != null)
- p.normalize(event.destination!),
- };
- for (final watched in entry.watchers.keys.toList()) {
- if (changed.any(
- (path) => path == watched || p.isWithin(path, watched),
- )) {
- unawaited(entry.watchers.remove(watched)!.cancel());
- entry.retryWatchAt.remove(watched);
- }
- }
- }
- _invalidate(cwd, entry);
- }
- },
- onError: (Object _) => lost(),
- onDone: lost,
- cancelOnError: true,
- );
- entry.watchers[directory] = subscription;
- entry.retryWatchAt.remove(directory);
- } on FileSystemException {
- entry.retryWatchAt[directory] = _now().add(_cacheAge);
- } on UnsupportedError {
- entry.retryWatchAt[directory] = _now().add(_cacheAge);
- }
- }
- }
-
- Future<String?> _text(String path) async {
- try {
- final file = await File(path).open();
- try {
- // Bound the read itself, including a file growing during discovery.
- final bytes = await file.read(64 * 1024 + 1);
- return bytes.length <= 64 * 1024 ? utf8.decode(bytes) : null;
- } finally {
- await file.close();
- }
- } on FileSystemException {
- return null;
- } on FormatException {
- return null;
- }
- }
-
- String? _origin(String? config) {
- if (config == null) return null;
- var origin = false;
- for (final line in config.split('\n')) {
- final text = line.trim();
- if (text.startsWith('[')) {
- origin = RegExp(
- r'^\[remote\s+"origin"\]$',
- caseSensitive: false,
- ).hasMatch(text);
- } else if (origin) {
- final match = RegExp(
- r'^url\s*=\s*(.+)$',
- caseSensitive: false,
- ).firstMatch(text);
- if (match != null) return canonicalGitRemote(match.group(1)!);
- }
- }
- return null;
- }
-
- void dispose() {
- _disposed = true;
- for (final entry in _entries.values) {
- entry.dispose();
- }
- _entries.clear();
- }
-}
-
-String? canonicalGitRemote(String raw) {
- raw = raw.trim();
- if (raw.startsWith('"') && raw.endsWith('"')) {
- raw = raw.substring(1, raw.length - 1);
- }
- final scp = RegExp(r'^(?:[^@/\s]+@)?([^:/\s]+):([^\s]+)$').firstMatch(raw);
- final uri = Uri.tryParse(
- scp != null && !raw.contains('://')
- ? 'ssh://${scp.group(1)}/${scp.group(2)}'
- : raw,
- );
- if (uri == null ||
- !{'ssh', 'https', 'http', 'git'}.contains(uri.scheme) ||
- uri.host.isEmpty) {
- return null;
- }
- var path = uri.path
- .replaceAll(RegExp(r'^/+|/+$'), '')
- .replaceFirst(RegExp(r'\.git$', caseSensitive: false), '');
- if (path.isEmpty || RegExp(r'[\x00-\x20]').hasMatch(path)) return null;
- final host = uri.host.toLowerCase();
- if (host == 'github.com' || host == 'bitbucket.org') {
- path = path.toLowerCase();
- }
- final defaultPort = switch (uri.scheme) {
- 'ssh' => 22,
- 'git' => 9418,
- 'https' => 443,
- _ => 80,
- };
- final port = uri.hasPort && uri.port != defaultPort ? ':${uri.port}' : '';
- return '$host$port/$path';
-}
-
-class _LocalGitEntry {
- DateTime checkedAt = DateTime.fromMillisecondsSinceEpoch(0);
- AgentProject? project;
- Future<void>? pending;
- bool dirty = false;
- final watchers = <String, StreamSubscription<FileSystemEvent>>{};
- Map<String, Set<String>> watchTargets = {};
- final retryWatchAt = <String, DateTime>{};
- Timer? debounce;
- bool disposed = false;
- void dispose() {
- disposed = true;
- debounce?.cancel();
- for (final watcher in watchers.values) {
- unawaited(watcher.cancel());
- }
- watchers.clear();
- }
-}
diff --git a/mobile/lib/core/serial_port_lease.dart b/mobile/lib/core/serial_port_lease.dart
deleted file mode 100644
index 7717d2371..000000000
--- a/mobile/lib/core/serial_port_lease.dart
+++ /dev/null
@@ -1,74 +0,0 @@
-import 'dart:async';
-import 'dart:io';
-
-import 'harness_file_store.dart';
-
-/// Held while something outside the daemon needs the dial's USB serial port to itself.
-///
-/// Exists because two parts of this app want that port and neither knew about the other. Flashing
-/// runs `harness stop` first — a serial port on macOS is exclusive, so the daemon has to let go — and
-/// then writes for the better part of a minute. Meanwhile the app supervises that same daemon on a
-/// five-second timer and starts it again the moment it notices it is gone. The daemon comes up,
-/// reopens the dial, and esptool loses the port mid-write: the flash dies a few tens of kilobytes in
-/// with "No more data to read from the serial port", which reads like broken hardware and is not.
-///
-/// A counter rather than a boolean so overlapping holders cannot release each other's claim, and
-/// [hold] releases in a `finally` so a thrown or cancelled flash cannot leave supervision switched
-/// off for the rest of the session — which would be a worse bug than the one this fixes, and a
-/// silent one.
-abstract final class SerialPortLease {
- static int _holders = 0;
-
- /// True while the daemon must not be started, because it would take the port.
- static bool get held => _holders > 0;
-
- /// How long a flag left behind by a flash that could not clean up is believed.
- ///
- /// A write takes a couple of minutes; ten is generous and still bounded. Without a bound, a script
- /// killed with -9 would switch daemon supervision off for the rest of the machine's life — a worse
- /// fault than the one this prevents, and a silent one.
- static const _staleAfter = Duration(minutes: 10);
-
- /// Whether a flash started OUTSIDE this app is holding the port.
- ///
- /// The in-process counter only knows about flashes this app started. Someone running
- /// `harness flash` in a terminal while the app is open hits exactly the same collision — the app
- /// restarts the daemon underneath them and their flash dies — and that is the case that matters
- /// most, because it is how a device already in someone's hands gets updated.
- ///
- /// The flasher writes this file before it stops the daemon and removes it when it starts it again.
- static bool heldByAnotherProcess({Map<String, String>? environment}) {
- try {
- // Honours the same override the flasher script reads, so the two sides cannot end up looking
- // in different places.
- final env = environment ?? Platform.environment;
- final dir =
- env['HARNESS_FLASHER_CACHE'] ??
- HarnessFileStore.defaultDirectoryPath(
- environment: environment,
- name: 'flasher',
- );
- final file = File('$dir/flashing');
- if (!file.existsSync()) return false;
- final started = int.tryParse(file.readAsStringSync().trim());
- if (started == null) return false;
- final age = DateTime.now().difference(
- DateTime.fromMillisecondsSinceEpoch(started * 1000),
- );
- return !age.isNegative && age < _staleAfter;
- } catch (_) {
- // Unreadable is not "being flashed": failing open here only risks the collision this guards
- // against, while failing closed would strand the daemon on any filesystem hiccup.
- return false;
- }
- }
-
- static Future<T> hold<T>(Future<T> Function() action) async {
- _holders++;
- try {
- return await action();
- } finally {
- _holders--;
- }
- }
-}
diff --git a/mobile/lib/phone/agent_index.dart b/mobile/lib/phone/agent_index.dart
index 443559576..982ad6611 100644
--- a/mobile/lib/phone/agent_index.dart
+++ b/mobile/lib/phone/agent_index.dart
@@ -19,10 +19,8 @@ class AgentEntry {
String get machineId => machine.machine.machineId;
String get machineName => machine.machine.displayName;
- /// The folder this agent works in, as [AgentContextLine] names it. Through [MachineState.projectOf]
- /// rather than `agent.project` directly: a locally launched agent carries its project on the
- /// machine's own side, and a row reading the field alone shows nothing for exactly those agents.
- AgentProject? get project => machine.projectOf(agent);
+ /// The folder this agent works in, as [AgentContextLine] names it.
+ AgentProject? get project => agent.project;
/// Whether this agent is blocked on an answer from the person holding the phone.
bool get isWaiting => machine.blockedAgents.containsKey(agent.id);
diff --git a/mobile/lib/phone/agent_tile.dart b/mobile/lib/phone/agent_tile.dart
index 03ff7a98c..d378dc973 100644
--- a/mobile/lib/phone/agent_tile.dart
+++ b/mobile/lib/phone/agent_tile.dart
@@ -75,7 +75,7 @@ class AgentTile extends StatelessWidget {
StatusPill(summary: phoneAgentSummary(machine, agent)),
const SizedBox(height: 3),
AgentContextLine(
- project: machine.projectOf(agent),
+ project: agent.project,
machineName: machine.machine.displayName,
),
],
diff --git a/mobile/lib/state/app_state.dart b/mobile/lib/state/app_state.dart
index 1489be09b..42f7b5e52 100644
--- a/mobile/lib/state/app_state.dart
+++ b/mobile/lib/state/app_state.dart
@@ -22,11 +22,9 @@ import '../core/agent_preference.dart';
import '../core/engine_availability.dart';
import '../core/device_name.dart';
import '../core/permission_modes.dart';
-import '../core/local_git_projects.dart';
import '../core/last_opened_agent.dart';
import '../core/phone_search_history.dart';
import '../core/machine_cache.dart';
-import '../core/test_run.dart';
import '../core/models.dart';
import '../core/project_folder.dart';
import '../core/project_history.dart';
@@ -51,7 +49,6 @@ import 'phone_desk.dart';
import 'swarm.dart';
import '../terminal/terminal_binary.dart';
import '../ws/ws_conn.dart';
-import '../ws/local_cli_discovery.dart';
import '../ws/ws_pool.dart';
import 'pending_question.dart';
import 'search_when.dart';
@@ -64,8 +61,6 @@ enum AppStatus { bootstrapping, 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
@@ -116,22 +111,9 @@ class AgentCreationAttempt {
}
}
-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;
-}
-
class MachineState {
Machine machine;
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
@@ -232,13 +214,6 @@ class MachineState {
MachineState(this.machine);
bool get isRemote => machine.authMode == MachineAuthMode.remote;
- bool get isLocalMachine => localOnly || localEndpoint != null;
- bool get usesLocalTransport => localEndpoint != null;
-
- AgentProject? projectOf(Agent agent) =>
- agent.project ??
- localProjects[agent.id] ??
- localEndpoint?.agentProjects[agent.id];
Agent? get activeAgent {
for (final agent in agents) {
@@ -327,17 +302,6 @@ class AppNotifier extends ChangeNotifier {
/// Words from the dial, for whoever can put a palette on screen.
Stream<SpokenTaskRequest> get spokenTasks => _spokenTasks.stream;
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);
@visibleForTesting
final WsConn Function(String machineId)? connectionForTest;
final Map<String, Timer> _turnActivityWatchdogs = {};
@@ -417,14 +381,6 @@ class AppNotifier extends ChangeNotifier {
// (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 = {};
- // 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;
-
- /// 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;
final Set<String> _offlinePollsInFlight = {};
final Set<String> _offlineRecoveryInFlight = {};
bool _disposed = false;
@@ -457,13 +413,6 @@ class AppNotifier extends ChangeNotifier {
// 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;
- // 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;
CurrentUserProfile? currentUser;
@@ -1030,7 +979,6 @@ class AppNotifier extends ChangeNotifier {
required AppConfig config,
required AuthSession authSession,
ConfigStore? configStore,
- this.localCliDiscovery,
this.connectionForTest,
SignInClient? cliLogin,
CliLink? cliLink,
@@ -1578,22 +1526,7 @@ class AppNotifier extends ChangeNotifier {
);
if (!_authWorkCurrent(revision)) return;
_ensurePool();
- try {
- await ensureCliDaemonReady();
- } catch (error) {
- if (!_authWorkCurrent(revision)) return;
- _bootStatusMessage = null;
- status = AppStatus.authenticated;
- _lastError = '$error';
- _lastErrorRetryable = true;
- notifyListeners();
- return;
- }
- if (!_authWorkCurrent(revision)) return;
_bootStatusMessage = null;
- // `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;
notifyListeners();
// The CLI has confirmed sign-in and daemon readiness. Display-name/avatar
@@ -1622,10 +1555,6 @@ class AppNotifier extends ChangeNotifier {
if (_authWorkCurrent(revision)) notifyListeners();
}
- /// 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
@@ -1664,118 +1593,6 @@ class AppNotifier extends ChangeNotifier {
}
}
- 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;
- final probe = await discovery.ensureRunning();
- if (!_authWorkCurrent(revision)) return;
- switch (probe.state) {
- case LocalCliProbeState.ready:
- _cliEndpoint = probe.endpoint;
- _daemonGateFailed = false;
- 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 has not '
- 'connected to the backend yet — ${probe.reason}. It usually finishes on its own; '
- 'retry in a moment.',
- );
- case LocalCliProbeState.down:
- _daemonGateFailed = true;
- // Before blaming the environment, check whether the daemon is missing because it signed itself
- // out. "Try running `harness start` yourself" is advice that cannot work in that case — the
- // session file is gone, so every start exits again — and it is the advice this branch used to
- // give unconditionally.
- final authStatus = await cliLogin.checkStatus();
- if (!_authWorkCurrent(revision)) return;
- if (!authStatus.loggedIn) {
- _signedOutAtRuntime(_signedOutMessage);
- return;
- }
- throw StateError(
- 'The local Harness daemon did not start. Try running `harness start` yourself, then reopen the app.',
- );
- }
- _startDaemonSupervision(discovery);
- }
-
- /// 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(
- stillSignedIn: () async => (await cliLogin.checkStatus()).loggedIn,
- onSignedOut: () => _signedOutAtRuntime(_signedOutMessage),
- onSnapshot: _updateLocalProjectSnapshot,
- 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;
- var changed = false;
- for (final machine in machineStates.values) {
- final previous = machine.localEndpoint;
- if (previous == null || previous.computerId != endpoint.computerId) {
- continue;
- }
- if (!mapEquals(previous.agentProjects, endpoint.agentProjects)) {
- machine.localEndpoint = endpoint;
- changed = 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.
- static const _signedOutMessage =
- 'You were signed out on this computer. Sign in again to reconnect.';
-
/// The session went away while the app was already running — send the user to the signed-out screen with a
/// reason, and stop the background work that can only fail from here.
///
@@ -1795,9 +1612,6 @@ class AppNotifier extends ChangeNotifier {
_awaitingFirstMessage = null;
_desk.reset();
analyticsAccount.clear();
- _daemonSupervisionTimer?.cancel();
- _daemonSupervisionTimer = null;
- _cliEndpoint = null;
unawaited(_pool?.closeAll());
_pool = null;
_lastError = message;
@@ -2052,12 +1866,6 @@ class AppNotifier extends ChangeNotifier {
await _pool?.closeAll();
if (!_authWorkCurrent(revision)) return;
_pool = null;
- _cliEndpoint = null;
- // Nothing to supervise for a signed-out app — and a daemon started by hand
- // on the login screen must not have its ready transition retry the machines.
- _daemonSupervisionTimer?.cancel();
- _daemonSupervisionTimer = null;
- _daemonGateFailed = false;
_clearAllTurnActivity();
// The desk belongs to the account, not to the phone: its tabs go with the
// session, writes this phone never managed to send included.
@@ -2178,14 +1986,6 @@ class AppNotifier extends ChangeNotifier {
// A daemon restarted mid-session therefore had nothing to say, and a dial that re-anchored onto
// the wrong tile stayed there.
_announceAppFocus();
- // 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;
- } 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
@@ -2197,9 +1997,6 @@ class AppNotifier extends ChangeNotifier {
nextStatus == ConnectionStatus.disconnected) {
_stopAgentSyncTimer(machineId);
_clearMachineActivity(machine);
- if (machine.isLocalMachine) {
- machine.transportMode = MachineTransportMode.localOffline;
- }
// 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
@@ -2273,16 +2070,7 @@ class AppNotifier extends ChangeNotifier {
Future<void> _refreshMachines(int revision) 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 (!_authWorkCurrent(revision)) return;
- final localFuture =
- discovery?.discover(expectedComputerId: localComputerId) ??
- Future<LocalCliEndpoint?>.value();
final list = await _fetchMachines();
- final localEndpoint = await localFuture;
if (!_authWorkCurrent(revision)) return;
machines = list
.where((machine) => machine.authMode == MachineAuthMode.remote)
@@ -2320,35 +2108,12 @@ class AppNotifier extends ChangeNotifier {
(state) => state..machine = machine,
ifAbsent: () => MachineState(machine),
);
- state.localOnly =
- localComputerId != null &&
- _normalizeComputerId(machine.computerId) == localComputerId;
- if (state.localOnly && localEndpoint?.computerId == localComputerId) {
- state.localEndpoint = localEndpoint;
- if (state.connectionStatus == ConnectionStatus.connected) {
- state.transportMode = MachineTransportMode.localPlaintext;
- } else {
- state.transportMode = MachineTransportMode.localOffline;
- }
- } 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.
- state.localEndpoint = null;
- state.transportMode = MachineTransportMode.localOffline;
- state.nodeOnline = false;
- _startOfflineRetry(state);
- } else {
- state.localEndpoint = null;
- state.transportMode = MachineTransportMode.cloudE2ee;
- }
final reportedOnline = _nodeOnlineFromStatus(machine.status);
- if (!state.isLocalMachine &&
- reportedOnline != null &&
+ if (reportedOnline != null &&
(state.nodeOnline == null || state.nodeOnline != reportedOnline)) {
unawaited(_applyNodeStatus(state, reportedOnline));
}
}
- if (localEndpoint != null) _updateLocalProjectSnapshot(localEndpoint);
_autoConnectAndLoadMachines();
// The list that just landed is what the NEXT launch starts from. Never
// awaited: it is a hint for a future run and must not add a disk write to
@@ -2382,8 +2147,7 @@ class AppNotifier extends ChangeNotifier {
void _startOfflineRetry(MachineState machine) {
final machineId = machine.machine.machineId;
- if (machine.nodeOnline != false ||
- (!machine.isLocalMachine && machine.pendingOfflineAgentId == null)) {
+ if (machine.nodeOnline != false || machine.pendingOfflineAgentId == null) {
_stopOfflineRetry(machineId);
return;
}
@@ -2719,34 +2483,12 @@ class AppNotifier extends ChangeNotifier {
final machine = machineStates[machineId];
if (machine == null ||
machine.nodeOnline != false ||
- (!machine.isLocalMachine && machine.pendingOfflineAgentId == null) ||
+ machine.pendingOfflineAgentId == null ||
_offlinePollsInFlight.contains(machineId)) {
return;
}
_offlinePollsInFlight.add(machineId);
try {
- if (machine.isLocalMachine) {
- final discovery = _discovery;
- final localComputerId = await discovery.computerId();
- if (localComputerId == null ||
- _normalizeComputerId(machine.machine.computerId) !=
- localComputerId) {
- return;
- }
- final endpoint = await discovery.discover(
- expectedComputerId: localComputerId,
- );
- if (endpoint == null || endpoint.computerId != localComputerId) return;
- machine.localEndpoint = 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,
);
@@ -2774,16 +2516,7 @@ class AppNotifier extends ChangeNotifier {
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;
+ selectedMachineId = machines.first.machineId;
}
for (final machine in machines) {
final state = machineStates[machine.machineId]!;
@@ -2819,8 +2552,7 @@ class AppNotifier extends ChangeNotifier {
// caller sets through an unawaited `_applyNodeStatus`: that happens to
// assign synchronously today, so both agree, but this loop should not be
// the thing that breaks if it ever gains an await before the assignment.
- if (!state.isLocalMachine &&
- _nodeOnlineFromStatus(machine.status) == false) {
+ if (_nodeOnlineFromStatus(machine.status) == false) {
StartupTrace.mark('skipped offline machine ${machine.machineId}');
continue;
}
@@ -2879,18 +2611,6 @@ class AppNotifier extends ChangeNotifier {
Future<void> _performRetryMachines() async {
final revision = _authRevision;
- if (!_authWorkCurrent(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;
- _lastError = '$error';
- _lastErrorRetryable = true;
- notifyListeners();
- return;
- }
if (!_authWorkCurrent(revision) || status == AppStatus.unauthenticated) {
return;
}
@@ -2957,27 +2677,17 @@ class AppNotifier extends ChangeNotifier {
// 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);
- }
+ if (_pool != null) _conn(machine.machine.machineId);
}
WsConn _conn(String machineId) {
final testConnection = connectionForTest;
if (testConnection != null) return testConnection(machineId);
- // A viewer dials the relay itself. On a desktop every machine 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).
- final connection = viewer != null
- ? _pool!.connFor(machineId, transportKind: WsTransportKind.cloudE2ee)
- : _pool!.connFor(
- machineId,
- transportKind: WsTransportKind.localPlaintext,
- localWsUri: _cliEndpoint?.wsUri,
- localProtocolVersion:
- _cliEndpoint?.protocolVersion ?? localWsProtocolVersion,
- );
+ // Every machine is dialled through the relay: there is no local CLI to proxy for it.
+ final connection = _pool!.connFor(
+ machineId,
+ transportKind: WsTransportKind.cloudE2ee,
+ );
_wireConnectionHooks(connection, machineId);
return connection;
}
@@ -3084,7 +2794,6 @@ class AppNotifier extends ChangeNotifier {
machine.machineId,
() => MachineState(machine),
);
- state.transportMode = MachineTransportMode.cloudE2ee;
// ⚠️ **The agents go in as PROVISIONAL, and the flag below is what keeps
// them honest.** With them the phone draws its terminal — the right
// agent's name on it, from the record it already had — while the real list
@@ -3179,17 +2888,6 @@ class AppNotifier extends ChangeNotifier {
}) async {
if (!_machineWorkCurrent(machine, _authRevision)) return;
if (machine.agentLoadStatus == AgentLoadStatus.loaded && !force) return;
- if (machine.isLocalMachine && !machine.usesLocalTransport) {
- machine.transportMode = MachineTransportMode.localOffline;
- machine.nodeOnline = false;
- 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;
@@ -3323,9 +3021,8 @@ class AppNotifier extends ChangeNotifier {
if (!_machineWorkCurrent(machine, revision)) return;
machine.agentsRefreshing = false;
if (error is WsRequestTimeout) {
- machine.agentsLoadError = machine.isLocalMachine
- ? 'Harness is offline — run harness login'
- : 'Harness is offline — run harness start on that machine';
+ machine.agentsLoadError =
+ 'Harness is offline — run harness start on that machine';
_recoverStaleSession(machine, connection);
} else if (connection.isClosed || machine.nodeOnline == false) {
machine.agentsLoadError = 'Could not load harnesses: $error';
@@ -3385,7 +3082,6 @@ class AppNotifier extends ChangeNotifier {
if (machine.nodeOnline != false) {
unawaited(_applyNodeStatus(machine, false));
}
- if (machine.isLocalMachine) return;
unawaited(connection.forceReconnect());
}
@@ -3910,14 +3606,12 @@ class AppNotifier extends ChangeNotifier {
]);
}
- /// What every connected REMOTE machine's agent accounts have spent, asked in
+ /// What every connected machine's agent accounts have spent, asked in
/// parallel and read there with that machine's own credentials (`usage_read`).
///
- /// This computer's own accounts are not asked here — the app reads those
- /// directly, the Keychain included. A remote machine may be signed in to a
- /// different subscription, and a rate limit belongs to an account rather than
- /// a computer, so the only honest way to show that one is to ask the machine
- /// that holds it.
+ /// A machine may be signed in to a different subscription, and a rate limit
+ /// belongs to an account rather than a computer, so the only honest way to
+ /// show that one is to ask the machine that holds it.
///
/// ⚠️ **A machine whose CLI predates `usage_read` does not refuse it — it goes
/// silent.** The frame reaches it as an E2EE envelope it does not know to
@@ -3928,9 +3622,7 @@ class AppNotifier extends ChangeNotifier {
Future<List<MachineUsage>> readRemoteUsage() async {
final remotes = [
for (final machine in machineStates.values)
- if (!machine.isLocalMachine &&
- machine.connectionStatus == ConnectionStatus.connected)
- machine,
+ if (machine.connectionStatus == ConnectionStatus.connected) machine,
];
final answers = await Future.wait([
for (final machine in remotes) _readMachineUsage(machine),
@@ -4947,9 +4639,7 @@ class AppNotifier extends ChangeNotifier {
if (!online) {
_markSessionsUnreachable(
machine,
- machine.isLocalMachine
- ? 'Harness is offline. Run harness login to reconnect.'
- : 'Harness is offline. Run harness start on that machine to reconnect.',
+ 'Harness is offline. Run harness start on that machine to reconnect.',
);
_startOfflineRetry(machine);
} else {
@@ -5292,7 +4982,7 @@ class AppNotifier extends ChangeNotifier {
if (machine == null) return;
_dismissedLinkPrompts.remove(machineId);
selectedMachineId = machineId;
- if (machine.isRemote && !machine.isLocalMachine && machine.needsLink) {
+ if (machine.isRemote && machine.needsLink) {
notifyListeners();
return;
}
@@ -6005,8 +5695,7 @@ class AppNotifier extends ChangeNotifier {
return machine != null &&
machine.nodeOnline != false &&
machine.terminalCapabilityAvailable &&
- !(machine.isRemote && !machine.isLocalMachine && machine.needsLink) &&
- (!machine.isLocalMachine || machine.usesLocalTransport) &&
+ !(machine.isRemote && machine.needsLink) &&
machine.agents.any((a) => a.id == agentId && a.terminalAvailable);
}
@@ -6508,11 +6197,9 @@ class AppNotifier extends ChangeNotifier {
@override
void dispose() {
- _localGitProjects.dispose();
_disposed = true;
if (signingIn) cliLogin.cancel();
_closedHistory.clear();
- _daemonSupervisionTimer?.cancel();
_stopAllOfflineRetries();
_stopAllLinkRetries();
_stopAllAgentSyncTimers();
diff --git a/mobile/lib/terminal/terminal_session.dart b/mobile/lib/terminal/terminal_session.dart
index 3a9860ba2..b3e8c89db 100644
--- a/mobile/lib/terminal/terminal_session.dart
+++ b/mobile/lib/terminal/terminal_session.dart
@@ -1168,7 +1168,7 @@ class TerminalSession extends ChangeNotifier {
/// write it to disk on its own (REMOTE) machine and paste that path as text. Only meaningful for
/// a genuinely remote pane: a LOCAL file already has a valid path on this same machine, so
/// callers should paste that path directly via [pasteText] instead and never reach this method
- /// at all — see [MachineState.isLocalMachine].
+ /// at all. A phone has no local pane.
///
/// The caller must check [MachineState.terminalPasteFileAvailable] first, same reason
/// [pasteImage] checks `terminalImagePasteAvailable`: an older CLI does not know this binary kind
diff --git a/mobile/lib/widgets/terminal_panel.dart b/mobile/lib/widgets/terminal_panel.dart
index a9fda2c1b..89b98e758 100644
--- a/mobile/lib/widgets/terminal_panel.dart
+++ b/mobile/lib/widgets/terminal_panel.dart
@@ -738,7 +738,7 @@ class _TerminalPanelState extends State<TerminalPanel>
/// app share the exact same OS clipboard. The wire-based `pasteImage` (chunked
/// upload, daemon writes the far side's OS clipboard, daemon replays Ctrl+V) is
/// reserved for a genuinely REMOTE pane, whose engine reads a DIFFERENT
- /// clipboard than this one — see `MachineState.isLocalMachine`.
+ /// clipboard than this one — which, on a phone, is every pane.
/// An image handed over by the software keyboard's own clipboard.
///
/// This is the phone's ONLY way to get an image into a pane: Flutter's
@@ -775,9 +775,7 @@ class _TerminalPanelState extends State<TerminalPanel>
return;
}
final machine = widget.notifier.stateOf(widget.session.machineId);
- if (machine != null &&
- !machine.isLocalMachine &&
- machine.terminalImagePasteAvailable) {
+ if (machine != null && machine.terminalImagePasteAvailable) {
final imageBytes = await NativeClipboard.readImagePng();
if (imageBytes != null &&
imageBytes.isNotEmpty &&
@@ -1017,8 +1015,8 @@ class _TerminalPanelState extends State<TerminalPanel>
try {
final message = await _linkOpener.open(
target,
- isLocalMachine:
- notifier.stateOf(session.machineId)?.isLocalMachine == true,
+ // The agent runs on another machine: a file it names is there, not here.
+ isLocalMachine: false,
isCancelled: () =>
cancellation.isCancelled ||
!mounted ||
diff --git a/mobile/lib/ws/local_cli_discovery.dart b/mobile/lib/ws/local_cli_discovery.dart
deleted file mode 100644
index 988187963..000000000
--- a/mobile/lib/ws/local_cli_discovery.dart
+++ /dev/null
@@ -1,567 +0,0 @@
-import 'dart:async';
-import 'dart:io';
-
-import 'package:dio/dio.dart';
-import 'package:flutter/foundation.dart';
-
-import '../core/serial_port_lease.dart';
-import '../core/config.dart';
-import '../core/harness_cli_runner.dart';
-import '../core/harness_file_store.dart';
-import '../core/models.dart';
-
-const localWsProtocolVersion = 1;
-const localTerminalProtocolVersion = 3;
-
-class LocalCliEndpoint {
- final String computerId;
- final Uri wsUri;
- final int protocolVersion;
- final int terminalProtocolVersion;
-
- /// Older daemons report local working folders in status before they support
- /// project metadata in agent frames. This snapshot never describes a peer.
- final Map<String, AgentProject> agentProjects;
-
- const LocalCliEndpoint({
- required this.computerId,
- required this.wsUri,
- required this.protocolVersion,
- required this.terminalProtocolVersion,
- this.agentProjects = const {},
- });
-}
-
-/// Reads the stable identity shared by the Harness CLI and backend machine record.
-class LocalMachineIdentity {
- final File computerIdFile;
- final Map<String, String> environment;
-
- LocalMachineIdentity({File? computerIdFile, Map<String, String>? environment})
- : environment = environment ?? Platform.environment,
- computerIdFile =
- computerIdFile ??
- File(defaultComputerIdPath(environment: environment));
-
- static String defaultComputerIdPath({Map<String, String>? environment}) {
- final desktopDirectory = HarnessFileStore.defaultDirectoryPath(
- environment: environment,
- );
- final harnessHome = Directory(desktopDirectory).parent.path;
- return _joinPath(harnessHome, 'computer-id');
- }
-
- Future<String?> computerId() async {
- final pinned = _normalizeComputerId(environment['ADAPTER_COMPUTER_ID']);
- if (pinned != null) return pinned;
- try {
- final id = (await computerIdFile.readAsString()).trim();
- return _normalizeComputerId(id);
- } catch (_) {
- return null;
- }
- }
-}
-
-String _joinPath(String parent, String child) =>
- '$parent${Platform.pathSeparator}$child';
-
-/// Discovers only the CLI bound to the fixed loopback address. The response
-/// advertises capabilities but never contains the machine API key.
-/// Starts the owned CLI directly. Finder does not need a shell/PATH in order
-/// to locate the managed Node runtime and CLI bundle.
-///
-/// A non-zero exit is a FAILED spawn and must read as one: the CLI exits 1
-/// when it could not start (a port clash, a spawn lock it gave up waiting on)
-/// and 0 for every "fine, nothing to do" (already running, still connecting,
-/// busy elsewhere) — which is exactly the signal the supervisor's backoff
-/// wants. It used to swallow the code, so a `harness start` that failed
-/// outright looked like one that worked.
-Future<void> runHarnessStart(HarnessCliRunner runner) async {
- final result = await runner.run(['start']);
- if (result.exitCode != 0) {
- throw ProcessException(
- 'harness',
- const ['start'],
- '${result.stderr}'.trim().isEmpty
- ? '${result.stdout}'.trim()
- : '${result.stderr}'.trim(),
- result.exitCode,
- );
- }
-}
-
-Future<void> _defaultSpawnCommand() => runHarnessStart(HarnessCliRunner());
-
-/// What one look at the daemon's control port found.
-///
-/// THREE answers, not two, and the middle one is the point. A port that
-/// nobody answers on means the daemon is down and spawning it is the fix. A
-/// port that answers but is not yet ready — a daemon that just came up after
-/// a self-update and has not finished its backend handshake, or one still
-/// scanning for agents — means a daemon is RUNNING, and spawning another can
-/// only fail on the port it already holds. Collapsing the two into "not
-/// ready" had the supervisor re-running `harness start` every few seconds
-/// for the whole length of every update, and the boot path calling a daemon
-/// that was busy connecting "did not start".
-enum LocalCliProbeState { down, notReady, ready }
-
-class LocalCliProbe {
- final LocalCliProbeState state;
-
- /// Non-null exactly when [state] is [LocalCliProbeState.ready].
- final LocalCliEndpoint? endpoint;
-
- /// Why it is not ready, for a log line or an error strip. Null when ready.
- final String? reason;
-
- /// What the daemon said about itself, when it answered at all.
- final int? pid;
- final String? version;
-
- const LocalCliProbe._({
- required this.state,
- this.endpoint,
- this.reason,
- this.pid,
- this.version,
- });
-
- const LocalCliProbe.down(String reason)
- : this._(state: LocalCliProbeState.down, reason: reason);
-
- const LocalCliProbe.notReady(String reason, {int? pid, String? version})
- : this._(
- state: LocalCliProbeState.notReady,
- reason: reason,
- pid: pid,
- version: version,
- );
-
- const LocalCliProbe.ready(
- LocalCliEndpoint endpoint, {
- int? pid,
- String? version,
- }) : this._(
- state: LocalCliProbeState.ready,
- endpoint: endpoint,
- pid: pid,
- version: version,
- );
-
- /// Something owns the port and answers on it — whether or not it is ready.
- bool get alive => state != LocalCliProbeState.down;
- bool get ready => state == LocalCliProbeState.ready;
-
- @override
- String toString() =>
- 'LocalCliProbe(${state.name}${reason == null ? '' : ': $reason'})';
-}
-
-class LocalCliDiscovery {
- final AppConfig config;
- final Dio _dio;
- final LocalMachineIdentity identity;
- final Future<void> Function() _spawnCommand;
-
- LocalCliDiscovery({
- required this.config,
- Dio? dio,
- LocalMachineIdentity? identity,
- Future<void> Function()? spawnCommand,
- }) : identity = identity ?? LocalMachineIdentity(),
- _spawnCommand = spawnCommand ?? _defaultSpawnCommand,
- _dio =
- dio ??
- Dio(
- BaseOptions(
- connectTimeout: const Duration(milliseconds: 400),
- receiveTimeout: const Duration(milliseconds: 400),
- sendTimeout: const Duration(milliseconds: 400),
- ),
- );
-
- Future<String?> computerId() => identity.computerId();
-
- /// How long a daemon that ANSWERS is given to become ready before
- /// [ensureRunning] gives up waiting on it. Long, because the common reason
- /// is a backend handshake after a self-update restart, and the daemon keeps
- /// retrying that on its own — there is nothing to do here but wait.
- static const Duration defaultReadyTimeout = Duration(seconds: 45);
-
- /// Makes sure the local `harness` daemon is up and answering `/api/status`, spawning `harness
- /// start` ONLY if a probe finds nobody on the port — every local REST/WS call needs this daemon
- /// running, and unlike `harness login` it does not start on its own. A daemon that answers but is
- /// not ready yet is waited on (up to [readyTimeout]) rather than spawned over: it is already
- /// running, and a second one can only fail on the port. Returns the last probe, so a caller can
- /// tell "never came up" from "up, still connecting" — the two call for different words.
- Future<LocalCliProbe> ensureRunning({
- Duration timeout = const Duration(seconds: 15),
- Duration readyTimeout = defaultReadyTimeout,
- }) async {
- var last = await probe();
- if (last.ready) return last;
- if (!last.alive) {
- // Same reason as the supervisor: while the dial is being flashed the daemon is down on purpose
- // and its port belongs to esptool. Down is the honest answer here — it really is not running.
- if (SerialPortLease.held || SerialPortLease.heldByAnotherProcess()) {
- return last;
- }
- try {
- await _spawnCommand();
- } catch (_) {
- return last;
- }
- final deadline = DateTime.now().add(timeout);
- while (!last.alive && DateTime.now().isBefore(deadline)) {
- await Future.delayed(const Duration(milliseconds: 500));
- last = await probe();
- }
- if (last.ready || !last.alive) return last;
- }
- // Alive, not ready. Wait for it — and if it goes DOWN meanwhile (it was a daemon on its way
- // out, say), fall back to one spawn rather than sitting on a port that just went quiet.
- final deadline = DateTime.now().add(readyTimeout);
- var spawned = false;
- while (DateTime.now().isBefore(deadline)) {
- await Future.delayed(const Duration(milliseconds: 500));
- last = await probe();
- if (last.ready) return last;
- if (!last.alive) {
- if (spawned ||
- SerialPortLease.held ||
- SerialPortLease.heldByAnotherProcess()) {
- return last;
- }
- spawned = true;
- try {
- await _spawnCommand();
- } catch (_) {
- return last;
- }
- }
- }
- return last;
- }
-
- /// Keeps the local daemon alive for as long as the returned [Timer] runs: polls [probe] every
- /// [checkInterval] and, when the port has gone quiet, spawns `harness start` and gives it a short
- /// grace window to bind its port before concluding the attempt failed. Failed spawn attempts back
- /// off exponentially (capped) so a persistently broken environment doesn't spin — the poll itself
- /// keeps going at [checkInterval] regardless, since backoff only gates the next SPAWN, not the next
- /// probe.
- ///
- /// A daemon that ANSWERS but is not ready is left alone, however long that lasts: it is running,
- /// it is the one that has to finish, and a `harness start` beside it can only fail. That is the
- /// state a daemon sits in for the length of every self-update's backend handshake, and it is what
- /// this loop used to spawn into every few seconds.
- ///
- /// Spawning waits for [spawnAfter] consecutive quiet ticks rather than one: a self-update leaves
- /// the port unowned for a second or two between the old daemon closing it and the new one binding,
- /// and a spawn into that gap is a wasted process (the CLI's own lock refuses it), not a fix.
- ///
- /// Never surfaces ORDINARY failures to the caller (no exceptions, no
- /// [AppNotifier]-visible error); [onSignedOut] is the single exception, for the one state no
- /// amount of respawning can recover from —
- /// this runs unattended in the background for the app's whole lifetime; callers that need a
- /// one-shot "start now and tell me if it worked" should use [ensureRunning] instead. Cancel the
- /// timer to stop supervising — this never touches the daemon process itself (it self-daemonizes and
- /// must keep running after the app quits, see `harness_daemon_keep_alive` plan).
- ///
- /// [onReady] fires on every transition INTO ready — the daemon coming back after an update, or
- /// after a spawn — so the app can pick up where it left off without a click.
- /// [onSnapshot] receives each ready probe, including changing local working folders.
- Timer startSupervising({
- Duration checkInterval = const Duration(seconds: 5),
- Duration graceStep = const Duration(milliseconds: 500),
- Duration graceWindow = const Duration(seconds: 5),
- Duration initialBackoff = const Duration(seconds: 2),
- Duration maxBackoff = const Duration(seconds: 30),
- int spawnAfter = 2,
- Future<bool> Function()? stillSignedIn,
- void Function()? onSignedOut,
- void Function(LocalCliEndpoint endpoint)? onReady,
- void Function(LocalCliEndpoint endpoint)? onSnapshot,
- }) {
- var backoff = initialBackoff;
- var nextSpawnAllowedAt = DateTime.now();
- var quietTicks = 0;
- var wasReady = false;
- // A spawn+grace-window cycle can outlast `checkInterval` — without this, an overlapping tick
- // would race a second `harness start` before the first cycle's backoff state even lands (the same
- // "port already in use" failure mode a second concurrent spawn hits today).
- var cycleInFlight = false;
-
- void failedSpawn() {
- nextSpawnAllowedAt = DateTime.now().add(backoff);
- backoff = (backoff * 2) > maxBackoff ? maxBackoff : backoff * 2;
- }
-
- void observe(LocalCliProbe seen) {
- if (seen.ready) {
- backoff = initialBackoff;
- quietTicks = 0;
- onSnapshot?.call(seen.endpoint!);
- if (!wasReady) onReady?.call(seen.endpoint!);
- wasReady = true;
- return;
- }
- wasReady = false;
- if (seen.alive) quietTicks = 0;
- }
-
- late final Timer timer;
- timer = Timer.periodic(checkInterval, (_) {
- if (cycleInFlight) return;
- cycleInFlight = true;
- unawaited(() async {
- try {
- // The daemon is DELIBERATELY down while the dial is being flashed — it was stopped so the
- // port could be handed over. Starting it here takes the port back mid-write and kills the
- // flash, which is what made a firmware update fail at a few tens of kilobytes.
- if (SerialPortLease.held || SerialPortLease.heldByAnotherProcess()) {
- return;
- }
- final seen = await probe();
- observe(seen);
- // Running — ready or on its way. Nothing to spawn, nothing to back off from.
- if (seen.alive) return;
- quietTicks += 1;
- if (quietTicks < spawnAfter) return;
- if (DateTime.now().isBefore(nextSpawnAllowedAt)) return;
- // A daemon that signed itself OUT — its machine was deleted from another machine, or its
- // session expired — deletes its session file and exits. Respawning it is the one failure
- // this loop cannot fix: every replacement starts without a session and exits again,
- // forever, silently. Stop instead, and let the caller send the user somewhere that helps.
- //
- // Asked here and not on every tick because it costs a `harness auth status` process, and
- // the respawn point is already rate-limited by the backoff above — so this runs once per
- // spawn attempt rather than once every [checkInterval].
- if (stillSignedIn != null && !await stillSignedIn()) {
- timer.cancel();
- onSignedOut?.call();
- return;
- }
- try {
- await _spawnCommand();
- } catch (error) {
- debugPrint(
- 'LocalCliDiscovery.startSupervising: spawn failed: $error',
- );
- failedSpawn();
- return;
- }
- // The grace window ends the moment SOMETHING answers on the port — bound is what the
- // spawn was for; ready is the daemon's own business from there.
- final deadline = DateTime.now().add(graceWindow);
- while (DateTime.now().isBefore(deadline)) {
- await Future.delayed(graceStep);
- final after = await probe();
- observe(after);
- if (after.alive) return;
- }
- failedSpawn();
- } finally {
- cycleInFlight = false;
- }
- }());
- });
- return timer;
- }
-
- /// The ready endpoint, or null. Kept for the callers that only ever wanted
- /// "can I dial it now" — see [probe] for the three-way answer.
- Future<LocalCliEndpoint?> discover({String? expectedComputerId}) async =>
- (await probe(expectedComputerId: expectedComputerId)).endpoint;
-
- Future<LocalCliProbe> probe({String? expectedComputerId}) async {
- final localComputerId = await computerId();
- if (localComputerId == null) {
- return const LocalCliProbe.down(
- 'this computer has no Harness identity yet',
- );
- }
- if (expectedComputerId != null && expectedComputerId != localComputerId) {
- return const LocalCliProbe.down('computer id mismatch');
- }
- final base = Uri.parse(config.localCliBaseUrl);
- if (base.host != '127.0.0.1' && base.host != 'localhost') {
- return const LocalCliProbe.down('the local CLI address is not loopback');
- }
- final Map<String, dynamic>? body;
- try {
- final response = await _dio.getUri<Map<String, dynamic>>(
- base.resolve('/api/status'),
- );
- body = response.data;
- } on DioException catch (error) {
- switch (error.type) {
- // Nobody on the port. The one case where spawning helps — and still
- // not on the first sighting: an update handoff leaves the port unowned
- // for a second or two between the old daemon closing it and the new
- // one binding, so the supervisor waits for a SECOND quiet tick (see
- // [startSupervising]'s `spawnAfter`). A single `down` is not proof.
- case DioExceptionType.connectionError:
- case DioExceptionType.connectionTimeout:
- return const LocalCliProbe.down('connection refused');
- // Something owns the port — a daemon mid-boot, a foreign process, a
- // daemon too busy to answer in time. Spawning over it can only fail.
- case DioExceptionType.badResponse:
- return LocalCliProbe.notReady(
- 'http ${error.response?.statusCode ?? '?'} from the control port',
- );
- case DioExceptionType.receiveTimeout:
- case DioExceptionType.sendTimeout:
- return const LocalCliProbe.notReady('timed out answering');
- case DioExceptionType.badCertificate:
- case DioExceptionType.cancel:
- case DioExceptionType.transformTimeout:
- case DioExceptionType.unknown:
- // A refused socket surfaces as `unknown` wrapping the SocketException
- // on older adapters — still nobody on the port. A socket that was
- // ACCEPTED and then dropped (an HttpException, "connection closed
- // while receiving") is not: something answered, then went away —
- // the old daemon mid-close, say — and that reads as alive.
- if (error.error is SocketException) {
- return const LocalCliProbe.down('connection refused');
- }
- return LocalCliProbe.notReady(error.message ?? 'unexpected answer');
- }
- } catch (error) {
- return LocalCliProbe.notReady('unexpected answer: $error');
- }
- final pid = body?['pid'] is int ? body!['pid'] as int : null;
- final version = body?['version'] is String
- ? body!['version'] as String
- : null;
- if (body == null) {
- return const LocalCliProbe.notReady('not a harness status');
- }
- // New CLIs expose the initial terminal scan explicitly. A missing field means an older CLI and
- // remains accepted for backward compatibility; false means the daemon is alive but not ready to
- // publish an authoritative empty/non-empty agent list yet.
- if (body['discoveryReady'] == false) {
- return LocalCliProbe.notReady(
- 'still scanning for agents',
- pid: pid,
- version: version,
- );
- }
- // `discoveryReady` is local-only (tmux/agent-process scanning) and can go true well before the
- // daemon has actually connected to the backend — `/api/machines` and friends proxy straight to
- // it, so treating discovery-ready as "ready" raced the handshake and surfaced as a bogus 30s
- // receive-timeout right after boot. `connected` is the daemon's own backend-socket state
- // (missing field ⇒ older CLI ⇒ accepted, same idiom as above).
- if (body['connected'] == false) {
- return LocalCliProbe.notReady(
- 'not connected to the backend yet',
- pid: pid,
- version: version,
- );
- }
- final advertisedComputerId = _normalizeComputerId(body['computerId']);
- final advertised = body['localWs'];
- if (advertisedComputerId != localComputerId) {
- return LocalCliProbe.notReady(
- 'a daemon for a different computer',
- pid: pid,
- version: version,
- );
- }
- if (advertised is! Map) {
- return LocalCliProbe.notReady(
- 'not a harness status',
- pid: pid,
- version: version,
- );
- }
- final localWs = Map<String, dynamic>.from(advertised);
- final path = localWs['path'];
- final protocolVersion = localWs['protocolVersion'];
- final terminalProtocolVersion = localWs['terminalProtocolVersion'];
- if (path is! String ||
- !path.startsWith('/') ||
- protocolVersion != localWsProtocolVersion ||
- terminalProtocolVersion != localTerminalProtocolVersion ||
- localWs['e2ee'] != false) {
- return LocalCliProbe.notReady(
- 'protocol mismatch',
- pid: pid,
- version: version,
- );
- }
- return LocalCliProbe.ready(
- LocalCliEndpoint(
- computerId: localComputerId,
- wsUri: base
- .resolve(path)
- .replace(scheme: base.scheme == 'https' ? 'wss' : 'ws'),
- protocolVersion: protocolVersion as int,
- terminalProtocolVersion: terminalProtocolVersion as int,
- agentProjects: _localAgentProjects(
- body['sessions'],
- identity.environment,
- ),
- ),
- pid: pid,
- version: version,
- );
- }
-}
-
-Map<String, AgentProject> _localAgentProjects(
- Object? sessions,
- Map<String, String> environment,
-) {
- if (sessions is! List) return const {};
- final projects = <String, AgentProject>{};
- final home = environment['HOME'] ?? environment['USERPROFILE'];
- for (final session in sessions) {
- if (session is! Map || session['id'] is! String) continue;
- final id = session['id'] as String;
- final rawCwd = session['cwd'];
- if (id.isEmpty ||
- rawCwd is! String ||
- rawCwd.isEmpty ||
- rawCwd.length > 4096 ||
- RegExp(r'[\x00-\x1f\x7f]').hasMatch(rawCwd)) {
- continue;
- }
- String cwd = rawCwd;
- if (cwd == '~' ||
- cwd.startsWith('~/') ||
- (Platform.isWindows && cwd.startsWith('~\\'))) {
- if (home == null || home.isEmpty) continue;
- cwd = '$home${cwd.substring(1)}';
- }
- final absolute = Platform.isWindows
- ? RegExp(r'^[A-Za-z]:[\\/]|^\\\\').hasMatch(cwd)
- : cwd.startsWith('/');
- if (!absolute) continue;
- try {
- cwd = File(cwd).uri.normalizePath().toFilePath();
- // Directory paths in the status may carry a trailing separator.
- final separator = Platform.pathSeparator;
- while (cwd.length > 1 &&
- cwd.endsWith(separator) &&
- !(Platform.isWindows && RegExp(r'^[A-Za-z]:\\$').hasMatch(cwd))) {
- cwd = cwd.substring(0, cwd.length - 1);
- }
- final parts = cwd.split(separator).where((part) => part.isNotEmpty);
- final project = AgentProject.fromJson({
- 'name': parts.isEmpty ? cwd : parts.last,
- 'cwd': cwd,
- });
- if (project != null) projects[id] = project;
- } on FormatException {
- // A malformed status row must not prevent discovery of the daemon.
- }
- }
- return Map.unmodifiable(projects);
-}
-
-String? _normalizeComputerId(Object? raw) {
- if (raw is! String) return null;
- final value = raw.trim().toLowerCase().replaceAll('-', '');
- return RegExp(r'^[a-f0-9]{16,64}$').hasMatch(value) ? value : null;
-}
diff --git a/mobile/test/connect_computer_test.dart b/mobile/test/connect_computer_test.dart
index e5ae1394a..ddf056640 100644
--- a/mobile/test/connect_computer_test.dart
+++ b/mobile/test/connect_computer_test.dart
@@ -11,6 +11,8 @@ import 'package:harness_mobile/phone/welcome/scan_to_connect.dart';
import 'package:harness_mobile/phone/welcome/set_up_computer.dart';
import 'package:harness_mobile/state/app_state.dart';
+import 'viewer_app_fixture.dart' show FakeApi;
+
class _Links implements PeerLinkClient {
final codes = <(String, String)>[];
@@ -57,6 +59,9 @@ void main() {
configStore: null,
peerLinks: links,
);
+ // The account's REST API, answered in memory: its machines are asked for again before a
+ // scanned computer is looked for, and none is on it unless a test says so.
+ app.api = FakeApi();
backs = [];
});
tearDown(() => app.dispose());
diff --git a/mobile/test/machines_load_failure_test.dart b/mobile/test/machines_load_failure_test.dart
index 9a7d403d5..9c1be80d3 100644
--- a/mobile/test/machines_load_failure_test.dart
+++ b/mobile/test/machines_load_failure_test.dart
@@ -1,34 +1,19 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
-import 'package:harness_mobile/auth/auth_session.dart';
-import 'package:harness_mobile/core/config.dart';
import 'package:harness_mobile/phone/machines_tab.dart';
-import 'package:harness_mobile/state/app_state.dart';
-/// An account whose machines cannot be fetched — the relay down, the phone offline.
-class _Unreachable extends AppNotifier {
- _Unreachable()
- : super(
- config: AppConfig.dev,
- authSession: AuthSession(),
- configStore: null,
- );
-
- int attempts = 0;
-
- @override
- Future<void> ensureCliDaemonReady() async {
- attempts++;
- throw StateError('The network connection was lost.');
- }
-}
+import 'viewer_app_fixture.dart';
void main() {
testWidgets('machines that could not load say so, and offer another go', (
tester,
) async {
- final app = _Unreachable();
+ // An account whose machines cannot be fetched — the relay down, the phone offline.
+ final rig = viewerApp();
+ final app = rig.app;
addTearDown(app.dispose);
+ rig.api.onMachines = () async =>
+ throw StateError('The network connection was lost.');
await app.retryMachines();
await tester.pumpWidget(MaterialApp(home: MachinesTab(notifier: app)));
@@ -40,6 +25,6 @@ void main() {
await tester.tap(find.text('Try again'));
await tester.pump();
- expect(app.attempts, 2);
+ expect(rig.api.machineFetches, 2);
});
}