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.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
desktop: restart a daemon the app did not launch, so it gets Local Network access
0xken1509d915773876
diff --git a/desktop/lib/core/process_responsibility.dart b/desktop/lib/core/process_responsibility.dartnew file mode 100644index 000000000..fc6219fbf--- /dev/null+++ b/desktop/lib/core/process_responsibility.dart@@ -0,0 +1,218 @@+import 'dart:ffi';+import 'dart:io' show Platform;++import 'package:ffi/ffi.dart';++/// Who macOS holds responsible for a process — the identity its Local Network permission is judged by.+///+/// A daemon this app spawns inherits the app as its responsible process, so it inherits the app's+/// Local Network grant (Info.plist declares `NSLocalNetworkUsageDescription` and the Bonjour type). A+/// daemon started anywhere else does not: `harness start` from a tmux or ssh shell leaves the bare+/// `node` binary responsible for itself, and macOS then refuses it every LAN address without ever+/// asking — robot discovery fails with `LOCAL_NETWORK_BLOCKED` and terminal P2P loses its LAN path.+abstract interface class ResponsibilityProbe {+ /// The responsible process of [pid], or null when it cannot be asked.+ int? responsiblePid(int pid);++ /// [pid]'s executable, or null when the process is gone.+ String? executablePath(int pid);+}++/// libSystem's answers. `responsibility_get_pid_responsible_for_pid` is private API, so every lookup+/// degrades to null — which the verdict below reads as "cannot tell", never as "restart".+class MacResponsibilityProbe implements ResponsibilityProbe {+ MacResponsibilityProbe();++ static const _maxPath = 4096;++ late final int Function(int)? _responsible = _lookup(+ () => DynamicLibrary.process()+ .lookupFunction<Int32 Function(Int32), int Function(int)>(+ 'responsibility_get_pid_responsible_for_pid',+ ),+ );++ late final int Function(int, Pointer<Uint8>, int)? _pidPath = _lookup(+ () =>+ DynamicLibrary.process().lookupFunction<+ Int32 Function(Int32, Pointer<Uint8>, Uint32),+ int Function(int, Pointer<Uint8>, int)+ >('proc_pidpath'),+ );++ static T? _lookup<T>(T Function() find) {+ if (!Platform.isMacOS) return null;+ try {+ return find();+ } on ArgumentError {+ return null;+ }+ }++ @override+ int? responsiblePid(int pid) {+ final responsible = _responsible?.call(pid);+ return responsible == null || responsible <= 0 ? null : responsible;+ }++ @override+ String? executablePath(int pid) {+ final pidPath = _pidPath;+ if (pidPath == null) return null;+ final buffer = calloc<Uint8>(_maxPath);+ try {+ final length = pidPath(pid, buffer, _maxPath);+ return length <= 0+ ? null+ : buffer.cast<Utf8>().toDartString(length: length);+ } finally {+ calloc.free(buffer);+ }+ }+}++enum DaemonOwnerAction {+ keep,+ restart,++ /// The owner alone cannot settle it: ask the daemon to reach the LAN, restart only if refused.+ testLan,+}++/// What to do about the daemon, and why — the why goes to the log.+class DaemonOwnerVerdict {+ final DaemonOwnerAction action;+ final String reason;++ const DaemonOwnerVerdict._(this.action, this.reason);+ const DaemonOwnerVerdict.keep(String reason)+ : this._(DaemonOwnerAction.keep, reason);+ const DaemonOwnerVerdict.restart(String reason)+ : this._(DaemonOwnerAction.restart, reason);+ const DaemonOwnerVerdict.testLan(String reason)+ : this._(DaemonOwnerAction.testLan, reason);++ bool get restart => action == DaemonOwnerAction.restart;+}++/// Restart only on proof. Every answer that cannot be established keeps the daemon: a restart+/// interrupts every terminal the app has open, and a guess is not worth that.+DaemonOwnerVerdict judgeDaemonOwner({+ required int daemonPid,+ required int ownPid,+ required ResponsibilityProbe probe,+}) {+ final mine = probe.responsiblePid(ownPid);+ final theirs = probe.responsiblePid(daemonPid);+ if (mine == null || theirs == null) {+ return const DaemonOwnerVerdict.keep('owner unknown');+ }+ if (theirs == mine) return const DaemonOwnerVerdict.keep('owned by this app');+ // Ambiguous, measured: a daemon started from a tmux/ssh shell answers this (and is refused the+ // LAN), but so does one whose app has since QUIT — and that one keeps the app's grant. Only+ // asking the daemon to use the network tells the two apart.+ if (theirs == daemonPid) {+ return DaemonOwnerVerdict.testLan(+ 'macOS names it its own owner (${probe.executablePath(daemonPid) ?? 'pid $daemonPid'})',+ );+ }+ final theirPath = probe.executablePath(theirs);+ // Gone: most often an earlier launch of this app, which macOS still counts as the owner.+ if (theirPath == null) {+ return DaemonOwnerVerdict.keep('owner pid $theirs has exited');+ }+ final myPath = probe.executablePath(mine);+ if (myPath != null && theirPath == myPath) {+ return const DaemonOwnerVerdict.keep('owned by another launch of this app');+ }+ return DaemonOwnerVerdict.restart('owned by $theirPath');+}++/// Checks each daemon pid once and restarts the ones this app does not own — at boot and from the+/// supervisor's interval check alike, so a daemon replaced from a terminal while the app is open is+/// caught within one tick.+class DaemonOwnerGuard {+ DaemonOwnerGuard({+ required this.probe,+ required this.ownPid,+ required this.restart,+ required this.lanBlocked,+ required this.log,+ this.paused,+ });++ final ResponsibilityProbe probe;+ final int ownPid;++ /// Stops the daemon and brings one back through this app; the new daemon's pid once it is ready,+ /// or null when none came back.+ final Future<int?> Function() restart;++ /// Asks the running daemon to reach the LAN: true when macOS refused it, false when it got+ /// through, null when the daemon could not say.+ final Future<bool?> Function() lanBlocked;+ final void Function(String line) log;++ /// True while the daemon must not be touched (a firmware flash holds its port).+ final bool Function()? paused;++ final _judged = <int>{};+ Future<bool>? _inFlight;+ bool _gaveUp = false;++ /// Judges [daemonPid] if it is new, restarting it when needed. True when a restart happened.+ Future<bool> check(int daemonPid) {+ // A restart in progress is the answer for every caller, whichever pid they saw.+ final inFlight = _inFlight;+ if (inFlight != null) return inFlight;+ if (_gaveUp || _judged.contains(daemonPid)) return Future.value(false);+ if (paused?.call() ?? false) return Future.value(false);+ return _inFlight ??= _check(daemonPid).whenComplete(() => _inFlight = null);+ }++ Future<bool> _check(int daemonPid) async {+ _judged.add(daemonPid);+ final verdict = judgeDaemonOwner(+ daemonPid: daemonPid,+ ownPid: ownPid,+ probe: probe,+ );+ var reason = verdict.reason;+ if (verdict.action == DaemonOwnerAction.testLan) {+ final blocked = await lanBlocked();+ if (blocked != true) {+ log(+ 'daemon pid $daemonPid kept: $reason, but it '+ '${blocked == false ? 'reaches the local network' : 'could not test the local network'}',+ );+ return false;+ }+ reason = '$reason, and macOS refuses it the local network';+ } else if (!verdict.restart) {+ log('daemon pid $daemonPid kept: $reason');+ return false;+ }+ log('restarting daemon pid $daemonPid through the app: $reason');+ final next = await restart();+ if (next == null) {+ log('restart: no daemon came back ready');+ return true;+ }+ _judged.add(next);+ final again = judgeDaemonOwner(+ daemonPid: next,+ ownPid: ownPid,+ probe: probe,+ );+ if (again.action != DaemonOwnerAction.keep) {+ // Restarting again would give the same answer: stop rather than loop.+ _gaveUp = true;+ log(+ 'restart did not change the owner of pid $next (${again.reason}); not retrying this session',+ );+ } else {+ log('daemon pid $next: ${again.reason}');+ }+ return true;+ }+}diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex 13d407dfe..b05c88da7 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -1,5 +1,5 @@import 'dart:async';-import 'dart:io' show Directory, exit, pid;+import 'dart:io' show Directory, Platform, exit, pid;import 'dart:math' show Random;import 'package:dio/dio.dart';@@ -47,6 +47,9 @@ import '../core/project_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 '../autonomous_device/autonomous_device_cli.dart';import '../settings/config_store.dart';import '../settings/experimental_features.dart';import '../stats/harness_stats.dart';@@ -657,6 +660,38 @@ class AppNotifier extends ChangeNotifier {/// 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,+ paused: () =>+ SerialPortLease.held || SerialPortLease.heldByAnotherProcess(),+ restart: () async {+ final probe = await _discovery.restart();+ return probe.ready ? probe.pid : null;+ },+ lanBlocked: () async {+ try {+ await AutonomousDeviceCli().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;final DesktopUpdater? desktopUpdater;@visibleForTesting@@ -3802,8 +3837,15 @@ class AppNotifier extends ChangeNotifier {if (viewer != null) return;final revision = _authRevision;final discovery = _discovery;- final probe = await discovery.ensureRunning();+ 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:@@ -3889,6 +3931,9 @@ class AppNotifier extends ChangeNotifier {},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.diff --git a/desktop/lib/ws/local_cli_discovery.dart b/desktop/lib/ws/local_cli_discovery.dartindex b2c514b4f..5fc0abe26 100644--- a/desktop/lib/ws/local_cli_discovery.dart+++ b/desktop/lib/ws/local_cli_discovery.dart@@ -114,6 +114,10 @@ Future<void> runHarnessStart(HarnessCliRunner runner) async {Future<void> _defaultSpawnCommand() => runHarnessStart(HarnessCliRunner());+Future<void> _defaultStopCommand() async {+ await HarnessCliRunner().run(['stop']);+}+/// The wall-clock window in which the supervisor may spawn `harness start`: seconds :10–:20 of/// every minute. The CLI's own updater ticks at :45 (`ADAPTER_UPDATE_SLOT_SEC` in the harness CLI's/// `config/env.ts`), so a spawn and an update handoff — both of which take the daemon's spawn lock —@@ -192,6 +196,7 @@ class LocalCliDiscovery {final Dio _dio;final LocalMachineIdentity identity;final Future<void> Function() _spawnCommand;+ final Future<void> Function() _stopCommand;/// Which way the daemon is reached — its socket or the loopback port. Shared/// with REST and the local WebSocket; [probe] decides it.@@ -202,12 +207,14 @@ class LocalCliDiscovery {Dio? dio,LocalMachineIdentity? identity,Future<void> Function()? spawnCommand,+ Future<void> Function()? stopCommand,LocalDaemonTransport? transport,}) : identity = identity ?? LocalMachineIdentity(),transport =transport ??LocalDaemonTransport.detect(Uri.parse(config.localCliBaseUrl)),_spawnCommand = spawnCommand ?? _defaultSpawnCommand,+ _stopCommand = stopCommand ?? _defaultStopCommand,_dio =dio ??Dio(@@ -281,6 +288,26 @@ class LocalCliDiscovery {return last;}+ /// Stops the running daemon and starts one from this process, so the new daemon descends from+ /// the app (see `core/process_responsibility.dart` on why that matters). Returns the probe+ /// [ensureRunning] ends on.+ Future<LocalCliProbe> restart({+ Duration stopTimeout = const Duration(seconds: 10),+ }) async {+ try {+ await _stopCommand();+ } catch (_) {+ // Judged by the port below, not by the exit code.+ }+ final deadline = DateTime.now().add(stopTimeout);+ var seen = await probe();+ while (seen.alive && DateTime.now().isBefore(deadline)) {+ await Future.delayed(const Duration(milliseconds: 250));+ seen = await probe();+ }+ return ensureRunning();+ }+/// 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@@ -326,8 +353,11 @@ class LocalCliDiscovery {void Function(LocalCliEndpoint endpoint)? onReady,void Function(LocalCliEndpoint endpoint)? onSnapshot,void Function(bool online)? onBackendOnline,+ Future<void> Function(int pid)? checkOwner,}) {var backoff = initialBackoff;+ // The daemon pid [checkOwner] last saw: it is asked once per daemon, not once per tick.+ int? ownerCheckedPid;var nextSpawnAllowedAt = DateTime.now();var quietTicks = 0;var wasReady = false;@@ -377,6 +407,17 @@ class LocalCliDiscovery {}final seen = await probe();observe(seen);+ // A new daemon — replaced from a terminal while the app is open, say. Awaited inside the+ // tick so the spawn path below cannot race a restart [checkOwner] makes.+ final seenPid = seen.pid;+ if (checkOwner != null &&+ seen.ready &&+ seenPid != null &&+ seenPid != ownerCheckedPid) {+ ownerCheckedPid = seenPid;+ await checkOwner(seenPid);+ return;+ }// Running — ready or on its way. Nothing to spawn, nothing to back off from.if (seen.alive) return;quietTicks += 1;diff --git a/desktop/pubspec.lock b/desktop/pubspec.lockindex 336f63073..363684103 100644--- a/desktop/pubspec.lock+++ b/desktop/pubspec.lock@@ -146,7 +146,7 @@ packages:source: hostedversion: "1.3.3"ffi:- dependency: transitive+ dependency: "direct main"description:name: ffisha256: "6d7fd89431262d8f3125e81b50d3847a091d846eafcd4fdb88dd06f36d705a45"diff --git a/desktop/pubspec.yaml b/desktop/pubspec.yamlindex 1d4f5705f..ba278c9dc 100644--- a/desktop/pubspec.yaml+++ b/desktop/pubspec.yaml@@ -68,6 +68,8 @@ dependencies:# XDG portal on Linux. Used ONLY for a machine that is this computer — see# `widgets/new_agent_dialog.dart`.file_selector: ^1.0.3+ # `core/process_responsibility.dart`: a native buffer for `proc_pidpath`. Pure Dart, no plugin.+ ffi: ^2.2.0# Reads OpenCode's own database for the usage ledger — `usage/ledger/`. The# Dart-only FFI package on purpose, NOT `sqlite3_flutter_libs`: this dlopens# the sqlite the OS already ships (every macOS has one, every Ubuntu desktopdiff --git a/desktop/test/daemon_readiness_test.dart b/desktop/test/daemon_readiness_test.dartindex 5b8007793..a997dd7aa 100644--- a/desktop/test/daemon_readiness_test.dart+++ b/desktop/test/daemon_readiness_test.dart@@ -45,6 +45,7 @@ class _ScriptedDiscovery extends LocalCliDiscovery {void Function(LocalCliEndpoint endpoint)? onReady,void Function(LocalCliEndpoint endpoint)? onSnapshot,void Function(bool online)? onBackendOnline,+ Future<void> Function(int pid)? checkOwner,}) {superviseCalls++;this.onReady = onReady;diff --git a/desktop/test/local_cli_discovery_test.dart b/desktop/test/local_cli_discovery_test.dartindex df4c7becf..a3532bb4d 100644--- a/desktop/test/local_cli_discovery_test.dart+++ b/desktop/test/local_cli_discovery_test.dart@@ -199,6 +199,7 @@ void main() {int port,File identityFile, {Future<void> Function()? spawnCommand,+ Future<void> Function()? stopCommand,}) => LocalCliDiscovery(config: AppConfig(apiBaseUrl: 'https://harness-api.autonomous.ai',@@ -206,8 +207,64 @@ void main() {),identity: LocalMachineIdentity(computerIdFile: identityFile),spawnCommand: spawnCommand,+ stopCommand: stopCommand,);+ test('supervision asks checkOwner once per daemon pid, and never for one that is not ready', () async {+ const computerId = '0123456789abcdef0123456789abcdef';+ final identityFile = File('${scratch.path}/computer-id')+ ..writeAsStringSync(computerId);+ var status = readyStatus(computerId, extra: {'discoveryReady': false});+ server = await serveStatus(await freePort(), () => status);+ final checked = <int>[];+ final discovery = discoveryFor(+ server!.port,+ identityFile,+ spawnCommand: () async =>+ fail('A running daemon must not be spawned over'),+ );+ final timer = discovery.startSupervising(+ checkInterval: const Duration(milliseconds: 20),+ checkOwner: (pid) async => checked.add(pid),+ );+ addTearDown(timer.cancel);+ await Future.delayed(const Duration(milliseconds: 150));+ expect(checked, isEmpty, reason: 'not ready: no owner check');+ status = readyStatus(computerId);+ await Future.delayed(const Duration(milliseconds: 200));+ status = readyStatus(computerId, extra: {'pid': 5353});+ await Future.delayed(const Duration(milliseconds: 200));+ expect(checked, [4242, 5353]);+ });++ test('restart stops the daemon, waits for its port to go quiet, and spawns a new one', () async {+ const computerId = '0123456789abcdef0123456789abcdef';+ final identityFile = File('${scratch.path}/computer-id')+ ..writeAsStringSync(computerId);+ final port = await freePort();+ server = await serveStatus(port, () => readyStatus(computerId));+ final calls = <String>[];+ final discovery = discoveryFor(+ port,+ identityFile,+ stopCommand: () async {+ calls.add('stop');+ await server!.close(force: true);+ },+ spawnCommand: () async {+ calls.add('start');+ server = await serveStatus(+ port,+ () => readyStatus(computerId, extra: {'pid': 7777}),+ );+ },+ );+ final probe = await discovery.restart();+ expect(calls, ['stop', 'start']);+ expect(probe.ready, isTrue);+ expect(probe.pid, 7777);+ });+test('reads real working folders from older local status snapshots',() async {diff --git a/desktop/test/process_responsibility_test.dart b/desktop/test/process_responsibility_test.dartnew file mode 100644index 000000000..51b3d9f0a--- /dev/null+++ b/desktop/test/process_responsibility_test.dart@@ -0,0 +1,244 @@+import 'dart:async';+import 'dart:io';++import 'package:flutter_test/flutter_test.dart';+import 'package:harness/core/process_responsibility.dart';++/// pid → responsible pid, and pid → executable for the processes that are alive.+class FakeProbe implements ResponsibilityProbe {+ FakeProbe(this.owners, this.paths);++ final Map<int, int> owners;+ final Map<int, String> paths;++ @override+ int? responsiblePid(int pid) => owners[pid];++ @override+ String? executablePath(int pid) => paths[pid];+}++const app = 100;+const daemon = 200;+const harness = '/Applications/Harness.app/Contents/MacOS/Harness';+const node = '/Users/me/.harness/runtime/node/bin/node';++DaemonOwnerVerdict judge(Map<int, int> owners, Map<int, String> paths) =>+ judgeDaemonOwner(+ daemonPid: daemon,+ ownPid: app,+ probe: FakeProbe(owners, paths),+ );++void main() {+ group('judgeDaemonOwner', () {+ test('keeps a daemon this app launched', () {+ final verdict = judge({app: app, daemon: app}, {app: harness});+ expect(verdict.restart, isFalse);+ expect(verdict.reason, 'owned by this app');+ });++ // Measured both ways: a daemon started from a tmux shell AND one whose app has quit are+ // reported as their own owner — and only the first is refused the LAN.+ test('asks for a LAN test when the daemon is named its own owner', () {+ final verdict = judge(+ {app: app, daemon: daemon},+ {app: harness, daemon: node},+ );+ expect(verdict.action, DaemonOwnerAction.testLan);+ expect(verdict.reason, contains(node));+ });++ test('restarts a daemon a terminal is responsible for', () {+ const terminal = 300;+ final verdict = judge(+ {app: app, daemon: terminal},+ {+ app: harness,+ terminal: '/System/Applications/Utilities/Terminal.app/Contents/MacOS/Terminal',+ },+ );+ expect(verdict.restart, isTrue);+ expect(verdict.reason, contains('Terminal'));+ });++ test('keeps a daemon an earlier launch of this app started, while it still runs', () {+ const earlier = 150;+ final verdict = judge(+ {app: app, daemon: earlier},+ {app: harness, earlier: harness},+ );+ expect(verdict.restart, isFalse);+ });++ test(+ 'keeps a daemon whose owner has exited — the app quit and reopened',+ () {+ final verdict = judge({app: app, daemon: 150}, {app: harness});+ expect(verdict.restart, isFalse);+ expect(verdict.reason, contains('exited'));+ },+ );++ test('keeps the daemon when either side cannot be asked', () {+ expect(judge({daemon: daemon}, const {}).restart, isFalse);+ expect(judge({app: app}, const {}).restart, isFalse);+ });++ test('shares a dev launch with the terminal both run under', () {+ const shell = 400;+ final verdict = judge({app: shell, daemon: shell}, const {});+ expect(verdict.restart, isFalse);+ });+ });++ group('DaemonOwnerGuard', () {+ late Map<int, int> owners;+ late List<String> lines;+ late int restarts;++ late List<String> lanTests;++ DaemonOwnerGuard guard({+ Future<int?> Function()? restart,+ bool Function()? paused,+ bool? lanBlocked = true,+ }) => DaemonOwnerGuard(+ probe: FakeProbe(owners, {app: harness, daemon: node}),+ ownPid: app,+ restart:+ restart ??+ () async {+ restarts++;+ owners[201] = app;+ return 201;+ },+ lanBlocked: () async {+ lanTests.add('lan');+ return lanBlocked;+ },+ log: lines.add,+ paused: paused,+ );++ setUp(() {+ owners = {app: app, daemon: daemon};+ lines = [];+ restarts = 0;+ lanTests = [];+ });++ test(+ 'keeps a self-owned daemon that still reaches the LAN — its app has quit',+ () async {+ final g = guard(lanBlocked: false);+ expect(await g.check(daemon), isFalse);+ expect(restarts, 0);+ expect(lines.single, contains('reaches the local network'));+ },+ );++ test('keeps a self-owned daemon when the LAN test cannot answer', () async {+ final g = guard(lanBlocked: null);+ expect(await g.check(daemon), isFalse);+ expect(restarts, 0);+ expect(lines.single, contains('could not test'));+ });++ test(+ 'restarts a daemon another running app owns, without a LAN test',+ () async {+ owners[daemon] = 300;+ final g = DaemonOwnerGuard(+ probe: FakeProbe(owners, {+ app: harness,+ 300: '/Applications/iTerm.app/Contents/MacOS/iTerm2',+ }),+ ownPid: app,+ restart: () async {+ restarts++;+ owners[201] = app;+ return 201;+ },+ lanBlocked: () async => fail('an app owner needs no LAN test'),+ log: lines.add,+ );+ expect(await g.check(daemon), isTrue);+ expect(restarts, 1);+ expect(lines.first, contains('iTerm'));+ },+ );++ test('restarts a self-owned daemon refused the LAN, once, and judges the new one', () async {+ final g = guard();+ expect(await g.check(daemon), isTrue);+ expect(restarts, 1);+ expect(lanTests, ['lan']);+ expect(lines.first, startsWith('restarting daemon pid 200'));+ expect(lines.last, 'daemon pid 201: owned by this app');+ // Both pids are judged: neither the old one nor the new one is looked at again.+ expect(await g.check(daemon), isFalse);+ expect(await g.check(201), isFalse);+ expect(restarts, 1);+ });++ test('checks a pid once, however often it is asked', () async {+ owners[daemon] = app;+ final g = guard();+ await g.check(daemon);+ await g.check(daemon);+ expect(lines, ['daemon pid 200 kept: owned by this app']);+ });++ test('concurrent checks share one restart', () async {+ final gate = Completer<int?>();+ final g = guard(+ restart: () {+ restarts++;+ return gate.future;+ },+ );+ final first = g.check(daemon);+ final second = g.check(daemon);+ gate.complete(null);+ expect(await first, isTrue);+ expect(await second, isTrue);+ expect(restarts, 1);+ });++ test(+ 'gives up for the session when a restart does not change the owner',+ () async {+ final g = guard(+ restart: () async {+ restarts++;+ owners[201] = 201;+ return 201;+ },+ );+ expect(await g.check(daemon), isTrue);+ expect(lines.last, contains('not retrying this session'));+ owners[202] = 202;+ expect(await g.check(202), isFalse);+ expect(restarts, 1);+ },+ );++ test('touches nothing while the daemon is paused for a flash', () async {+ var flashing = true;+ final g = guard(paused: () => flashing);+ expect(await g.check(daemon), isFalse);+ expect(restarts, 0);+ flashing = false;+ expect(await g.check(daemon), isTrue);+ expect(restarts, 1);+ });+ });++ test('MacResponsibilityProbe answers for this very process', () {+ final probe = MacResponsibilityProbe();+ expect(probe.responsiblePid(pid), isNotNull);+ expect(probe.executablePath(pid), isNotEmpty);+ expect(probe.executablePath(-1), isNull);+ }, skip: !Platform.isMacOS);+}