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.

Phone: the Buddy picker lists all your own computers and adds none to the Swarm (#2240)

0xken151a7bac2bcc54
diff --git a/mobile/lib/core/models.dart b/mobile/lib/core/models.dart
index 557517572..a1bee0473 100644
--- a/mobile/lib/core/models.dart
+++ b/mobile/lib/core/models.dart
@@ -77,6 +77,14 @@ class Machine {
final String? hostname;
final String? status;
+ /// Another account's machine shared with this one (the list's `shared` or
+ /// `share`): never where this person's Buddy runs.
+ final bool shared;
+
+ /// How its computer signed in on its last connect: `team` for a Harness
+ /// Team account, which is never a person's own machine for a Buddy.
+ final String? sessionKind;
+
const Machine({
required this.machineId,
this.apiKey = '',
@@ -86,6 +94,8 @@ class Machine {
this.name,
this.hostname,
this.status,
+ this.shared = false,
+ this.sessionKind,
});
String get displayName => (name != null && name!.isNotEmpty)
@@ -104,6 +114,8 @@ class Machine {
name: j['name'] as String?,
hostname: j['hostname'] as String?,
status: j['status'] as String?,
+ shared: j['shared'] == true || j['share'] is Map,
+ sessionKind: j['sessionKind'] as String?,
);
Machine copyWith({String? name}) => Machine(
@@ -115,6 +127,8 @@ class Machine {
name: name ?? this.name,
hostname: hostname,
status: status,
+ shared: shared,
+ sessionKind: sessionKind,
);
}
diff --git a/mobile/lib/state/app_state.dart b/mobile/lib/state/app_state.dart
index d825b355c..3cc578e17 100644
--- a/mobile/lib/state/app_state.dart
+++ b/mobile/lib/state/app_state.dart
@@ -6579,6 +6579,49 @@ class AppNotifier extends ChangeNotifier {
return answer['value'];
}
+ /// Asks the account's own computer [machineId] a Swarm question of its own
+ /// (`super_tabs`), such as preparing a Buddy's folder there
+ /// (`prepareContribution`, as the desktop's `prepareBuddyMachine` asks it).
+ /// A refusal throws; so does an account change while it was asked.
+ Future<Map<String, dynamic>> swarmAskComputer(
+ String machineId,
+ Map<String, dynamic> payload,
+ ) async {
+ final machine = machineStates[machineId];
+ if (machine == null || machine.needsLink) {
+ throw const SuperTabFailure(
+ 'MACHINE_UNAVAILABLE',
+ 'This computer is not connected. Open Harness on it, then try again.',
+ );
+ }
+ final revision = _authRevision;
+ void stillThisAccount() {
+ if (!_authWorkCurrent(revision)) {
+ throw const SuperTabFailure(
+ 'ACCOUNT_CHANGED',
+ 'The account changed. Open Swarm again.',
+ );
+ }
+ }
+
+ final Map<String, dynamic> answer;
+ try {
+ answer = await _conn(machineId).request(
+ 'super_tabs',
+ payload: payload,
+ timeout: const Duration(seconds: 30),
+ );
+ } on WsRequestFailure catch (failure) {
+ stillThisAccount();
+ throw SuperTabFailure(
+ failure.code,
+ failure.detail ?? 'Could not reach this computer.',
+ );
+ }
+ stillThisAccount();
+ return answer;
+ }
+
Future<Map<String, dynamic>> connectors(
String machineId,
Map<String, dynamic> payload, {
diff --git a/mobile/lib/swarm/swarm_buddy.dart b/mobile/lib/swarm/swarm_buddy.dart
index 0f7a172ce..0f4feb804 100644
--- a/mobile/lib/swarm/swarm_buddy.dart
+++ b/mobile/lib/swarm/swarm_buddy.dart
@@ -4,6 +4,7 @@ import 'identity.dart';
import 'model.dart';
import 'swarm_reader.dart';
import 'swarm_request.dart';
+import 'swarm_start.dart';
/// What the phone knows of Buddies (spec: Buddies, 10-28; in every Swarm
/// since #2090, where they replaced Chat with PM): each person's Buddy chat in
@@ -237,29 +238,178 @@ bool swarmCanWrite(SwarmReader reader) =>
?.canWrite ??
false;
-/// A machine a Buddy may start on, as Start your Buddy lists it.
-typedef SwarmBuddyMachine = ({String id, String name});
-
-/// The person's own machines in the Swarm: a Buddy runs only there, like a
-/// Lead, whatever its engine (Ken, 10-28). Not a machine someone else shared
-/// with them, and not another person's; the backend refuses any other (the
-/// desktop's `buddyMachines`).
-List<SwarmBuddyMachine> swarmBuddyMachines(SwarmReader reader) => [
- for (final m in reader.snapshot?.machines ?? const <Map<String, dynamic>>[])
- if (m['hostMachineId'] == null &&
- m['contributorId'] == reader.accountId &&
- m['machineId'] is String)
- (id: m['machineId'] as String, name: _machineName(m['name'])),
-];
-
-/// The machine [machineId] by its name in the Swarm, as a Buddy's chat
-/// says what it runs on; "another machine" while the Swarm names none (the
-/// desktop's `buddyMachineName`).
-String swarmBuddyMachineName(SwarmReader reader, String machineId) =>
- _machineName(
- reader.snapshot?.pool(machineId)?['name'],
- fallback: 'another machine',
+/// A machine a Buddy may start on, as Start your Buddy lists it: one of the
+/// person's own. One outside the Swarm ([inSwarm] false) stays theirs: the
+/// server records it for their Buddies alone and never adds it to the Swarm
+/// (Dee, 10-29). An [away] one is listed but cannot be picked.
+typedef SwarmBuddyMachine = ({String id, String name, bool inSwarm, bool away});
+
+/// The menu's group of the person's own machines: the picker has only its
+/// heading, machine names and 'offline' (Dee, 10-29).
+const swarmBuddyOwnMachines = 'Your machines';
+
+/// Why a row cannot be picked, as the sidebar says a Buddy is 'not started'.
+const swarmBuddyMachineOffline = 'offline';
+
+/// What Start your Buddy says when none of the person's machines can take a
+/// Buddy now: none is signed in to their account, or all are offline (the
+/// desktop's words).
+const swarmBuddyNoMachine =
+ 'Your Buddy runs on one of your own computers. Open Harness on one, '
+ 'signed in to your account.';
+const swarmBuddyAllOffline =
+ 'Your machines are offline. Open Harness on one of them to start your '
+ 'Buddy there.';
+
+/// The person's own machines a Buddy may run on, like a Lead, whatever its
+/// engine (Ken, 10-28): those of their account ([computers]), in the Swarm or
+/// not, and those of theirs the Swarm lists. Never a machine someone shared
+/// with them, nor a Harness Team account; the backend refuses any other.
+/// Each by the name its person gave it.
+///
+/// A phone has no "this computer" (Lead's ruling on #2240): online machines
+/// come first, the one the person last started a Buddy on before the rest,
+/// which go by name; offline ones last. A Swarm row no account record
+/// confirms is online only while its own reading is fresh, so before the
+/// account's list answers nothing unconfirmed is offered as up.
+List<SwarmBuddyMachine> swarmBuddyMachines(
+ SwarmReader reader, {
+ List<SwarmOwnComputer> computers = const [],
+ DateTime? now,
+}) {
+ final at = now ?? DateTime.now();
+ final byId = <String, SwarmBuddyMachine>{};
+ for (final m in reader.snapshot?.machines ?? const <Map<String, dynamic>>[]) {
+ if (m['hostMachineId'] != null ||
+ m['contributorId'] != reader.accountId ||
+ m['machineId'] is! String) {
+ continue;
+ }
+ final id = m['machineId'] as String;
+ byId[id] = (
+ id: id,
+ name: _machineName(m['name']),
+ inSwarm: true,
+ away: !_reporting(m, at),
+ );
+ }
+ for (final c in computers) {
+ final listed = byId[c.id];
+ byId[c.id] = (
+ id: c.id,
+ name: _machineName(c.name.isEmpty ? listed?.name : c.name),
+ inSwarm: listed != null,
+ away: c.away,
);
+ }
+ final last = _lastBuddyMachine(reader);
+ int byName(SwarmBuddyMachine a, SwarmBuddyMachine b) =>
+ a.name.toLowerCase().compareTo(b.name.toLowerCase());
+ final online = byId.values.where((m) => !m.away).toList()
+ ..sort((a, b) {
+ if ((a.id == last) != (b.id == last)) return a.id == last ? -1 : 1;
+ return byName(a, b);
+ });
+ final away = byId.values.where((m) => m.away).toList()..sort(byName);
+ return [...online, ...away];
+}
+
+/// Whether [pool]'s own reading is fresh (backend `MACHINE_FRESH_MS`, as the
+/// route reads a machine): no reading is no answer.
+bool _reporting(Map<String, dynamic> pool, DateTime now) {
+ final observation = pool['observation'];
+ final at = observation is Map ? observation['receivedAt'] : null;
+ return at is num &&
+ now.difference(DateTime.fromMillisecondsSinceEpoch(at.toInt())) <=
+ const Duration(seconds: 45);
+}
+
+/// The machine of the person's newest Buddy start in this Swarm, if any.
+String? _lastBuddyMachine(SwarmReader reader) {
+ final mine = reader.snapshot?.buddyStarts.where(
+ (s) =>
+ superTabMap(superTabMap(s['request'])['buddyOf'])['personId'] ==
+ reader.accountId,
+ );
+ final request = mine == null || mine.isEmpty
+ ? null
+ : superTabMap(mine.last['request']);
+ return request?['machineId'] as String?;
+}
+
+/// The machine [machineId] by the name its person gave it, else its name in
+/// the Swarm, as a Buddy's chat says what it runs on; "another machine" while
+/// neither names it (the desktop's `buddyMachineName`). A machine of the
+/// person's own outside the Swarm is in no Swarm list (backend buddyOnly), so
+/// their account names it.
+String swarmBuddyMachineName(
+ SwarmReader reader,
+ String machineId, {
+ List<SwarmOwnComputer> computers = const [],
+}) {
+ final given = computers.where((c) => c.id == machineId).firstOrNull?.name;
+ return _machineName(
+ given != null && given.isNotEmpty
+ ? given
+ : reader.snapshot?.pool(machineId)?['name'],
+ fallback: 'another machine',
+ );
+}
+
+/// The setup a Buddy sends for [machineId], one of the person's own machines
+/// outside the Swarm: prepared there as Add machine prepares one (its folder
+/// and engines, `prepareContribution`), so the server records it for their
+/// Buddies alone (the desktop's `prepareBuddyMachine`). Asked again a second
+/// apart while it reports `preparing`, for up to five minutes; [setupId] names
+/// the setup, so asking again joins the one under way. A refusal throws.
+Future<Map<String, dynamic>> prepareSwarmBuddyMachine(
+ SwarmComputers computers,
+ SwarmReader reader,
+ SwarmBuddyMachine machine, {
+ required String setupId,
+ Duration pause = const Duration(seconds: 1),
+ Duration limit = const Duration(minutes: 5),
+}) async {
+ final deadline = DateTime.now().add(limit);
+ while (true) {
+ final prepared = await computers.ask(machine.id, {
+ 'action': 'prepareContribution',
+ 'tabId': reader.tabId,
+ 'scope': 'swarm',
+ 'operationId': setupId,
+ });
+ if (prepared['state'] == 'ready' && prepared['scope'] == 'swarm') {
+ final engines = [
+ for (final e in prepared['engines'] as List? ?? const [])
+ if (e == 'claude' || e == 'codex') e as String,
+ ];
+ if (engines.isEmpty) {
+ throw const SuperTabFailure(
+ 'NO_SWARM_ENGINE',
+ 'Install Claude Code or Codex on this computer, then try again.',
+ );
+ }
+ return {
+ 'name': machine.name,
+ 'cwd': prepared['cwd'],
+ 'engines': engines.toSet().toList(),
+ };
+ }
+ if (prepared['state'] != 'preparing') {
+ throw const SuperTabFailure(
+ 'UPDATE_REQUIRED',
+ 'Update Harness on this computer, then try again.',
+ );
+ }
+ if (DateTime.now().isAfter(deadline)) {
+ throw const SuperTabFailure(
+ 'SETUP_PENDING',
+ 'Setup is still running on this computer. Try again to check it.',
+ );
+ }
+ await Future<void>.delayed(pause);
+ }
+}
/// A machine's name without its `.local`, as the desktop shows it.
String _machineName(Object? name, {String fallback = 'Your machine'}) {
@@ -315,12 +465,14 @@ Future<String?> startSwarmBuddy(
required String projectId,
required String machineId,
required String engine,
+ Map<String, dynamic>? setup,
}) async {
final result = await _command(reader, {
'type': 'buddy.create',
'projectId': projectId,
'machineId': machineId,
'engine': engine,
+ 'setup': ?setup,
});
await reader.refresh();
return result['conversationId'] as String?;
@@ -352,17 +504,46 @@ class SwarmBuddyActions extends ChangeNotifier {
/// What went wrong with the last one; null when it went through.
String? get error => _error;
- /// Starts the Buddy on [machineId] with [engine] ([startSwarmBuddy]).
- Future<void> start({required String machineId, required String engine}) =>
- _run(
- () => startSwarmBuddy(
+ /// The setup under way for a machine outside the Swarm, kept between
+ /// tries so a setup still running is joined, not started again.
+ String? _setupId;
+
+ /// Starts the Buddy on [machineId] with [engine] ([startSwarmBuddy]). For
+ /// [machine], one of the person's own outside the Swarm, it is prepared
+ /// there first through [computers] ([prepareSwarmBuddyMachine]) and its
+ /// setup sent; nothing adds it to the Swarm.
+ Future<void> start({
+ required String machineId,
+ required String engine,
+ SwarmBuddyMachine? machine,
+ SwarmComputers? computers,
+ }) => _run(() async {
+ Map<String, dynamic>? setup;
+ if (machine != null && !machine.inSwarm && computers != null) {
+ final id = _setupId ??=
+ 'buddy-setup-${DateTime.now().microsecondsSinceEpoch}';
+ try {
+ setup = await prepareSwarmBuddyMachine(
+ computers,
reader,
- projectId: projectId,
- machineId: machineId,
- engine: engine,
- ),
- "Couldn't start your Buddy. Try again.",
- );
+ machine,
+ setupId: id,
+ );
+ _setupId = null;
+ } on SuperTabFailure catch (failure) {
+ if (failure.code != 'SETUP_PENDING') _setupId = null;
+ rethrow;
+ }
+ if (_disposed) return null;
+ }
+ return startSwarmBuddy(
+ reader,
+ projectId: projectId,
+ machineId: machineId,
+ engine: engine,
+ setup: setup,
+ );
+ }, "Couldn't start your Buddy. Try again.");
/// Removes the Buddy ([removeSwarmBuddy]); its chat stays.
Future<void> remove() => _run(
diff --git a/mobile/lib/swarm/swarm_buddy_chat.dart b/mobile/lib/swarm/swarm_buddy_chat.dart
index 5575a65a6..65a5d2bbf 100644
--- a/mobile/lib/swarm/swarm_buddy_chat.dart
+++ b/mobile/lib/swarm/swarm_buddy_chat.dart
@@ -18,6 +18,8 @@ import 'swarm_conversation_page.dart';
import 'swarm_reader.dart';
import 'swarm_request.dart';
import 'swarm_row.dart';
+import 'swarm_session.dart' show SwarmScope;
+import 'swarm_start.dart' show SwarmOwnComputer;
import 'swarm_style.dart';
/// Opens the person's Buddy chat in [projectId] over [context]'s page, on the
@@ -66,7 +68,11 @@ class SwarmBuddyBar extends StatelessWidget {
final error = actions.error;
final body = switch (swarmBuddy(reader, actions.projectId)) {
final agent? => _running(reader, agent, canWrite),
- null => _starting(reader, canWrite),
+ null => _starting(
+ reader,
+ canWrite,
+ SwarmScope.computersOf(context)?.own ?? const [],
+ ),
};
if (body == null && error == null) return const SizedBox.shrink();
return DecoratedBox(
@@ -147,7 +153,11 @@ class SwarmBuddyBar extends StatelessWidget {
/// A start under way, or one that failed with Start again; with none,
/// Start your Buddy. Null for a viewer, who starts none.
- Widget? _starting(SwarmReader reader, bool canWrite) {
+ Widget? _starting(
+ SwarmReader reader,
+ bool canWrite,
+ List<SwarmOwnComputer> own,
+ ) {
final start = swarmBuddyStart(reader, actions.projectId);
final error = start?['error'];
if (start == null || (error is! String && start['harnessId'] != null)) {
@@ -174,7 +184,7 @@ class SwarmBuddyBar extends StatelessWidget {
}
return SwarmRow.line(
'Starting ${swarmBuddyEngineName(engine)} on '
- '${swarmBuddyMachineName(reader, machineId)}…',
+ '${swarmBuddyMachineName(reader, machineId, computers: own)}…',
key: const ValueKey('swarm-buddy-starting'),
lines: 2,
);
@@ -233,29 +243,42 @@ class _BuddyStartState extends State<_BuddyStart> {
String? _machine;
String _engine = 'claude';
- Future<void> _pickMachine(List<SwarmBuddyMachine> machines, String chosen) =>
+ /// The machines under their one heading, each by its name; an offline one
+ /// says so and cannot be picked (Dee, 10-29: no notes).
+ Future<void> _pickMachine(List<SwarmBuddyMachine> machines, String? chosen) =>
showPhoneSheet(
context,
title: 'Machine',
- actions: [
- for (final m in machines)
- PhoneSheetAction(
- icon: m.id == chosen ? LucideIcons.check : LucideIcons.laptop,
- label: m.name,
- onTap: () {
- if (mounted) setState(() => _machine = m.id);
- },
- ),
+ sections: [
+ PhoneSheetSection(
+ caption: swarmBuddyOwnMachines,
+ actions: [
+ for (final m in machines)
+ PhoneSheetAction(
+ icon: m.id == chosen ? LucideIcons.check : LucideIcons.laptop,
+ label: m.name,
+ value: m.away ? swarmBuddyMachineOffline : null,
+ enabled: !m.away,
+ onTap: () {
+ if (mounted) setState(() => _machine = m.id);
+ },
+ ),
+ ],
+ ),
],
);
@override
Widget build(BuildContext context) {
final actions = widget.actions;
- final machines = swarmBuddyMachines(actions.reader);
+ final computers = SwarmScope.computersOf(context);
+ final machines = swarmBuddyMachines(
+ actions.reader,
+ computers: computers?.own ?? const [],
+ );
final machine =
- machines.where((m) => m.id == _machine).firstOrNull ??
- machines.firstOrNull;
+ machines.where((m) => m.id == _machine && !m.away).firstOrNull ??
+ machines.where((m) => !m.away).firstOrNull;
final busy = actions.busy;
return Column(
key: const ValueKey('swarm-buddy-start'),
@@ -273,13 +296,24 @@ class _BuddyStartState extends State<_BuddyStart> {
Padding(
padding: const EdgeInsets.only(top: AppSpace.xs),
child: SwarmRow.line(
- 'A Buddy runs on one of your own machines. Add one of yours to '
- 'this Swarm first.',
+ machines.isEmpty ? swarmBuddyNoMachine : swarmBuddyAllOffline,
key: const ValueKey('swarm-buddy-no-machine'),
lines: 3,
),
- )
- else ...[
+ ),
+ if (machine == null && machines.isNotEmpty)
+ _Field(
+ label: 'Machine',
+ child: TextButton(
+ key: const ValueKey('swarm-buddy-machine'),
+ onPressed: () => unawaited(_pickMachine(machines, null)),
+ child: const Align(
+ alignment: Alignment.centerLeft,
+ child: Text('Choose a machine'),
+ ),
+ ),
+ ),
+ if (machine != null) ...[
_Field(
label: 'Machine',
child: Semantics(
@@ -355,7 +389,12 @@ class _BuddyStartState extends State<_BuddyStart> {
busy: busy,
busyLabel: 'Starting…',
onPressed: () => unawaited(
- actions.start(machineId: machine.id, engine: _engine),
+ actions.start(
+ machineId: machine.id,
+ engine: _engine,
+ machine: machine,
+ computers: computers,
+ ),
),
),
],
diff --git a/mobile/lib/swarm/swarm_computers.dart b/mobile/lib/swarm/swarm_computers.dart
index 3be74f9dd..95cd7eccf 100644
--- a/mobile/lib/swarm/swarm_computers.dart
+++ b/mobile/lib/swarm/swarm_computers.dart
@@ -64,6 +64,29 @@ class AppSwarmComputers extends ChangeNotifier implements SwarmComputers {
notifyListeners();
}
+ /// The account's own computers, as the Buddy picker lists them: never one
+ /// shared with this person, nor a Harness Team account, nor one waiting for
+ /// a link.
+ @override
+ List<SwarmOwnComputer> get own => [
+ if (notifier.machinesAnswered)
+ for (final machine in notifier.machineStates.values)
+ if (!machine.machine.shared &&
+ machine.machine.sessionKind != 'team' &&
+ !machine.needsLink)
+ (
+ id: machine.machine.machineId,
+ name: machine.machine.displayName,
+ away: phoneMachineAway(machine),
+ ),
+ ];
+
+ @override
+ Future<Map<String, dynamic>> ask(
+ String machineId,
+ Map<String, dynamic> payload,
+ ) => notifier.swarmAskComputer(machineId, payload);
+
/// The machines tab's Try again: the account's list read again.
@override
Future<void> recheck() => notifier.retryMachines();
diff --git a/mobile/lib/swarm/swarm_start.dart b/mobile/lib/swarm/swarm_start.dart
index 50e3f17dc..a94f1c249 100644
--- a/mobile/lib/swarm/swarm_start.dart
+++ b/mobile/lib/swarm/swarm_start.dart
@@ -16,6 +16,10 @@ import 'swarm_session.dart';
/// and whether it is away for real (`phoneMachineAway`).
typedef SwarmComputer = ({String name, bool away});
+/// One of the person's own computers a Buddy may run on: never one shared
+/// with them, nor a Harness Team account. [away] ones are listed, not picked.
+typedef SwarmOwnComputer = ({String id, String name, bool away});
+
/// What Swarm shows before there is a Swarm to show — one screen each, with
/// one button. Swarm turned off is not one of them: the app is as it was, and
/// Settings offers Swarm.
@@ -67,6 +71,17 @@ abstract interface class SwarmComputers implements Listenable {
/// Opens the steps to connect a computer.
void add(BuildContext context);
+
+ /// The person's own computers ([SwarmOwnComputer]); empty until the list
+ /// has answered.
+ List<SwarmOwnComputer> get own;
+
+ /// Asks the person's own computer [machineId] one Swarm question of its
+ /// own, such as preparing a Buddy's folder (`prepareContribution`).
+ Future<Map<String, dynamic>> ask(
+ String machineId,
+ Map<String, dynamic> payload,
+ );
}
/// The start screen Swarm Home shows in place of its body, or null when it
diff --git a/mobile/test/swarm/swarm_buddy_chat_test.dart b/mobile/test/swarm/swarm_buddy_chat_test.dart
index 8652e67df..b66628fee 100644
--- a/mobile/test/swarm/swarm_buddy_chat_test.dart
+++ b/mobile/test/swarm/swarm_buddy_chat_test.dart
@@ -11,6 +11,12 @@ import 'package:harness_mobile/swarm/swarm_request.dart';
import 'package:harness_mobile/swarm/swarm_session.dart';
import '../voice_fakes.dart';
+
+import 'package:harness_mobile/swarm/swarm_buddy.dart'
+ show swarmBuddyMachineOffline, swarmBuddyOwnMachines;
+import 'package:harness_mobile/swarm/swarm_start.dart' show SwarmComputers;
+
+import 'swarm_computers_fake.dart';
import 'swarm_fixture.dart';
/// The person's own Buddy chat on the phone (#2090; Desktop's Buddy chat,
@@ -66,6 +72,8 @@ void main() {
'name': name,
'contributorId': owner,
'engines': ['claude', 'codex'],
+ // Reporting now: in no account list here, so only this says it is up.
+ 'observation': {'receivedAt': DateTime.now().millisecondsSinceEpoch},
};
Map<String, dynamic> wren({String? downSince}) => {
@@ -129,7 +137,11 @@ void main() {
return fake;
}
- Future<SwarmHost> pump(WidgetTester tester, FakeSwarm fake) async {
+ Future<SwarmHost> pump(
+ WidgetTester tester,
+ FakeSwarm fake, {
+ SwarmComputers? computers,
+ }) async {
final features = ExperimentalFeaturesStore(storage: MemoryKeyValueStore())
..value = {PhoneExperiment.swarm};
final account = ValueNotifier<String?>(me);
@@ -140,6 +152,7 @@ void main() {
upload: refuseSwarmUpload,
notices: SilentSystemNotices(),
features: features,
+ computers: computers,
)..foreground = false;
addTearDown(host.dispose);
await tester.pumpWidget(
@@ -599,17 +612,80 @@ void main() {
await tester.tap(key('swarm-buddy-machine'));
await tester.pumpAndSettle();
- await tester.tap(find.text('Mac Studio'));
+ await tester.tap(find.text('Tonys-MacBook-Pro').last);
+ await tester.pumpAndSettle();
+ await tester.tap(key('swarm-buddy-start-button'));
+ await tester.pumpAndSettle();
+
+ expect(fake.commands, [
+ {
+ 'type': 'buddy.create',
+ 'projectId': project,
+ 'machineId': 'mac-1',
+ 'engine': 'claude',
+ },
+ ]);
+ });
+
+ // Dee, 10-29: every computer of the person's own, under one heading,
+ // each by its name; an offline one says so and cannot be picked; one
+ // outside the Swarm is prepared there and never added to it.
+ testWidgets('the sheet lists every computer of their own under one '
+ 'heading, an offline one turned off, and one outside the Swarm starts '
+ 'with its setup', (tester) async {
+ final fake = backend(machines: [machine('mac-1', 'Tonys-MacBook-Pro')]);
+ final computers = FakeComputers(const [])
+ ..own = [
+ (id: 'mac-1', name: 'tropic', away: false),
+ (id: 'studio', name: 'Studio', away: false),
+ (id: 'air', name: 'MacBook Air', away: true),
+ ]
+ ..answer = (_, _) => {
+ 'ok': true,
+ 'state': 'ready',
+ 'scope': 'swarm',
+ 'cwd': '/home/me/swarm',
+ 'engines': ['claude', 'codex'],
+ };
+ await pump(tester, fake, computers: computers);
+
+ // Online ones by name, none started on before: Studio first.
+ expect(
+ find.descendant(
+ of: key('swarm-buddy-machine'),
+ matching: find.text('Studio'),
+ ),
+ findsOneWidget,
+ );
+ await tester.tap(key('swarm-buddy-machine'));
+ await tester.pumpAndSettle();
+ expect(find.text(swarmBuddyOwnMachines.toLowerCase()), findsOneWidget);
+ expect(find.text(swarmBuddyMachineOffline), findsOneWidget);
+ expect(find.textContaining('Swarm'), findsNothing);
+ await tester.tap(find.text('MacBook Air'), warnIfMissed: false);
+ await tester.pumpAndSettle();
+ expect(
+ find.text(swarmBuddyOwnMachines.toLowerCase()),
+ findsOneWidget,
+ reason: 'not picked: the sheet stays',
+ );
+ await tester.tap(find.text('Studio').last);
await tester.pumpAndSettle();
await tester.tap(key('swarm-buddy-start-button'));
await tester.pumpAndSettle();
+ expect(computers.asked.single.$1, 'studio');
expect(fake.commands, [
{
'type': 'buddy.create',
'projectId': project,
- 'machineId': 'mac-4',
+ 'machineId': 'studio',
'engine': 'claude',
+ 'setup': {
+ 'name': 'Studio',
+ 'cwd': '/home/me/swarm',
+ 'engines': ['claude', 'codex'],
+ },
},
]);
});
diff --git a/mobile/test/swarm/swarm_buddy_test.dart b/mobile/test/swarm/swarm_buddy_test.dart
index 0aab0f1bc..e27bdc37c 100644
--- a/mobile/test/swarm/swarm_buddy_test.dart
+++ b/mobile/test/swarm/swarm_buddy_test.dart
@@ -7,6 +7,7 @@ import 'package:harness_mobile/swarm/swarm_project_page.dart';
import 'package:harness_mobile/swarm/swarm_reader.dart';
import 'package:harness_mobile/swarm/swarm_request.dart';
+import 'swarm_computers_fake.dart';
import 'swarm_fixture.dart';
/// Buddies on the phone (spec: Buddies, 10-28; every Swarm since #2090): each
@@ -406,6 +407,8 @@ void main() {
'contributorId': owner,
'hostMachineId': ?host,
'engines': ['claude', 'codex'],
+ // Reporting now: in no account list here, so only this says it is up.
+ 'observation': {'receivedAt': DateTime.now().millisecondsSinceEpoch},
};
test("are the person's own, named without .local; never one shared with "
@@ -425,11 +428,110 @@ void main() {
await r.refresh();
expect(swarmBuddyMachines(r), [
- (id: 'mac-1', name: 'Tonys-MacBook-Pro'),
- (id: 'mac-4', name: 'Mac Studio'),
+ (id: 'mac-4', name: 'Mac Studio', inSwarm: true, away: false),
+ (id: 'mac-1', name: 'Tonys-MacBook-Pro', inSwarm: true, away: false),
]);
});
+ // Dee, 10-29: a Buddy runs on any of the person's own computers without
+ // adding it to the Swarm; each by the name its person gave it.
+ test('are every computer of their own too, by its given name, online ones '
+ 'first and offline ones last', () async {
+ final swarm = FakeSwarm();
+ swarm.routes['/api/super-tabs/$tab/parts'] = (_) =>
+ firstLoad(machines: [pool('mac-1', 'Tonys-MacBook-Pro.local')]);
+ final r = reader(swarm);
+ addTearDown(r.dispose);
+ await r.refresh();
+
+ expect(
+ swarmBuddyMachines(
+ r,
+ computers: [
+ (id: 'air', name: 'MacBook Air', away: true),
+ (id: 'mac-1', name: 'tropic', away: false),
+ (id: 'studio', name: 'Studio', away: false),
+ ],
+ ),
+ [
+ (id: 'studio', name: 'Studio', inSwarm: false, away: false),
+ (id: 'mac-1', name: 'tropic', inSwarm: true, away: false),
+ (id: 'air', name: 'MacBook Air', inSwarm: false, away: true),
+ ],
+ );
+ expect(
+ swarmBuddyMachineName(
+ r,
+ 'studio',
+ computers: [(id: 'studio', name: 'Studio', away: false)],
+ ),
+ 'Studio',
+ );
+ });
+
+ // Review of #2240: a Swarm row no account record confirms read as up.
+ test('count a Swarm machine the account does not list as offline until '
+ 'its own reading is fresh', () async {
+ final swarm = FakeSwarm();
+ final stale = DateTime.now()
+ .subtract(const Duration(minutes: 5))
+ .millisecondsSinceEpoch;
+ swarm.routes['/api/super-tabs/$tab/parts'] = (_) => firstLoad(
+ machines: [
+ {...pool('silent', 'Silent Mac'), 'observation': null},
+ {
+ ...pool('stale', 'Stale Mac'),
+ 'observation': {'receivedAt': stale},
+ },
+ pool('fresh', 'Fresh Mac'),
+ ],
+ );
+ final r = reader(swarm);
+ addTearDown(r.dispose);
+ await r.refresh();
+
+ expect(
+ [for (final m in swarmBuddyMachines(r)) (m.id, m.away)],
+ [('fresh', false), ('silent', true), ('stale', true)],
+ );
+ });
+
+ // Lead's ruling on #2240: a phone has no "this computer".
+ test('put the one the person last started a Buddy on first among the '
+ 'online, the rest by name, offline last', () async {
+ final swarm = FakeSwarm();
+ swarm.routes['/api/super-tabs/$tab/parts'] = (_) => firstLoad(
+ machines: [pool('alpha', 'Alpha'), pool('zulu', 'Zulu')],
+ starts: [
+ buddyStartData('old', chatId: 'chat', machineId: 'alpha'),
+ buddyStartData('new', chatId: 'chat', machineId: 'zulu'),
+ buddyStartData(
+ 'theirs',
+ chatId: 'other',
+ owner: 'person-dee',
+ machineId: 'alpha',
+ ),
+ ],
+ );
+ final r = reader(swarm);
+ addTearDown(r.dispose);
+ await r.refresh();
+
+ expect(
+ [
+ for (final m in swarmBuddyMachines(
+ r,
+ computers: [
+ (id: 'beta', name: 'Beta', away: false),
+ (id: 'aaa', name: 'Aaa', away: true),
+ ],
+ ))
+ m.id,
+ ],
+ ['zulu', 'alpha', 'beta', 'aaa'],
+ );
+ });
+
test('are none before the Swarm is read', () {
final r = reader(FakeSwarm());
addTearDown(r.dispose);
@@ -550,6 +652,97 @@ void main() {
expect(actions.error, isNull);
});
+ test('on a computer of their own outside the Swarm prepares it there, '
+ 'then starts the Buddy with its setup', () async {
+ final (swarm, r) = await read();
+ swarm.routes[commands] = (_) => {'result': <String, dynamic>{}};
+ final computers = FakeComputers(const []);
+ var asks = 0;
+ computers.answer = (_, payload) => ++asks == 1
+ ? {'ok': true, 'state': 'preparing'}
+ : {
+ 'ok': true,
+ 'state': 'ready',
+ 'scope': 'swarm',
+ 'cwd': '/home/me/swarm',
+ 'engines': ['claude', 'pi'],
+ };
+ final actions = SwarmBuddyActions(r, project);
+ addTearDown(actions.dispose);
+
+ await actions.start(
+ machineId: 'studio',
+ engine: 'claude',
+ machine: (id: 'studio', name: 'Studio', inSwarm: false, away: false),
+ computers: computers,
+ );
+
+ expect(actions.error, isNull);
+ expect(computers.asked.map((a) => a.$1), ['studio', 'studio']);
+ expect(computers.asked.first.$2, {
+ 'action': 'prepareContribution',
+ 'tabId': tab,
+ 'scope': 'swarm',
+ 'operationId': computers.asked.last.$2['operationId'],
+ });
+ expect(swarm.commands, [
+ {
+ 'type': 'buddy.create',
+ 'projectId': project,
+ 'machineId': 'studio',
+ 'engine': 'claude',
+ 'setup': {
+ 'name': 'Studio',
+ 'cwd': '/home/me/swarm',
+ 'engines': ['claude'],
+ },
+ },
+ ]);
+ });
+
+ test('on a machine already in the Swarm sends no setup and asks the '
+ 'computer nothing', () async {
+ final (swarm, r) = await read();
+ swarm.routes[commands] = (_) => {'result': <String, dynamic>{}};
+ final computers = FakeComputers(const []);
+ final actions = SwarmBuddyActions(r, project);
+ addTearDown(actions.dispose);
+
+ await actions.start(
+ machineId: 'mac-1',
+ engine: 'claude',
+ machine: (id: 'mac-1', name: 'tropic', inSwarm: true, away: false),
+ computers: computers,
+ );
+
+ expect(computers.asked, isEmpty);
+ expect(swarm.commands.single, isNot(contains('setup')));
+ });
+
+ test(
+ 'a computer that cannot prepare says why and starts nothing',
+ () async {
+ final (swarm, r) = await read();
+ final computers = FakeComputers(const [])
+ ..answer = (_, _) => {'ok': true, 'state': 'unknown'};
+ final actions = SwarmBuddyActions(r, project);
+ addTearDown(actions.dispose);
+
+ await actions.start(
+ machineId: 'studio',
+ engine: 'claude',
+ machine: (id: 'studio', name: 'Studio', inSwarm: false, away: false),
+ computers: computers,
+ );
+
+ expect(
+ actions.error,
+ 'Update Harness on this computer, then try again.',
+ );
+ expect(swarm.commands, isEmpty);
+ },
+ );
+
test('says why a start was refused, and forgets it once the next goes '
'through', () async {
final (swarm, r) = await read();
diff --git a/mobile/test/swarm/swarm_computers_fake.dart b/mobile/test/swarm/swarm_computers_fake.dart
index 73a5e28fa..9002f77ed 100644
--- a/mobile/test/swarm/swarm_computers_fake.dart
+++ b/mobile/test/swarm/swarm_computers_fake.dart
@@ -5,6 +5,24 @@ import 'package:harness_mobile/swarm/swarm_start.dart';
/// The person's computers as a test scripts them.
class FakeComputers extends ChangeNotifier implements SwarmComputers {
+ /// The person's own computers a Buddy may run on.
+ @override
+ List<SwarmOwnComputer> own = const [];
+
+ /// Each question asked of a computer, and how the computer answers it.
+ final asked = <(String, Map<String, dynamic>)>[];
+ Map<String, dynamic> Function(String machineId, Map<String, dynamic> payload)?
+ answer;
+
+ @override
+ Future<Map<String, dynamic>> ask(
+ String machineId,
+ Map<String, dynamic> payload,
+ ) async {
+ asked.add((machineId, payload));
+ return answer?.call(machineId, payload) ?? const {};
+ }
+
FakeComputers(this.computers);
@override
diff --git a/mobile/test/swarm/swarm_home_test.dart b/mobile/test/swarm/swarm_home_test.dart
index 53cf44d98..4599a1300 100644
--- a/mobile/test/swarm/swarm_home_test.dart
+++ b/mobile/test/swarm/swarm_home_test.dart
@@ -27,6 +27,15 @@ import 'swarm_fixture.dart';
/// The person's computers as a test sets them.
class _Computers extends ChangeNotifier implements SwarmComputers {
+ @override
+ List<SwarmOwnComputer> get own => const [];
+
+ @override
+ Future<Map<String, dynamic>> ask(
+ String machineId,
+ Map<String, dynamic> payload,
+ ) async => throw UnimplementedError();
+
_Computers(this.computers);
@override
diff --git a/mobile/test/swarm/swarm_models_devices_test.dart b/mobile/test/swarm/swarm_models_devices_test.dart
index 5774b92b8..a2750d722 100644
--- a/mobile/test/swarm/swarm_models_devices_test.dart
+++ b/mobile/test/swarm/swarm_models_devices_test.dart
@@ -527,6 +527,15 @@ void main() {
/// The person's computers as a test sets them.
class _Computers extends ChangeNotifier implements SwarmComputers {
+ @override
+ List<SwarmOwnComputer> get own => const [];
+
+ @override
+ Future<Map<String, dynamic>> ask(
+ String machineId,
+ Map<String, dynamic> payload,
+ ) async => throw UnimplementedError();
+
_Computers(this.computers);
@override
diff --git a/mobile/test/swarm/swarm_session_test.dart b/mobile/test/swarm/swarm_session_test.dart
index 848f18531..26d55bcc6 100644
--- a/mobile/test/swarm/swarm_session_test.dart
+++ b/mobile/test/swarm/swarm_session_test.dart
@@ -549,6 +549,15 @@ void main() {
/// The account's computers, told by hand.
class _Computers extends ChangeNotifier implements SwarmComputers {
+ @override
+ List<SwarmOwnComputer> get own => const [];
+
+ @override
+ Future<Map<String, dynamic>> ask(
+ String machineId,
+ Map<String, dynamic> payload,
+ ) async => throw UnimplementedError();
+
@override
List<SwarmComputer>? computers = const [(name: 'Studio Mac', away: false)];