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.

Merge batch 11-04 b2207: #3021 #3029 (#3037)

0xken15fef974a9cada
diff --git a/cli/src/lib/agentFrame.spec.ts b/cli/src/lib/agentFrame.spec.ts
index 8bc0f016f..d3f82c597 100644
--- a/cli/src/lib/agentFrame.spec.ts
+++ b/cli/src/lib/agentFrame.spec.ts
@@ -26,6 +26,13 @@ describe('agentFrame', () => {
expect(await agentFrame(row, { selectedModel: null, terminalAvailable: true }))
.toMatchObject({ sessionId: 's1', status: 'active', identityHold: row.identityHold })
})
+ it('says its name was not chosen by a person when nobody renamed it, whatever its session title says', async () => {
+ const row = { ...session(null), title: 'cd /Users/macbookpro/projects/lamp' }
+ const frame = await agentFrame(row, { selectedModel: null, terminalAvailable: true })
+ expect(frame).toHaveProperty('nameChosen', false)
+ // The name it shows is the title, which is why the flag is needed.
+ expect(frame.name).toContain('cd /Users')
+ })
it('carries only the owning machine’s cached token snapshot, including a measured zero', async () => {
const context = { selectedModel: null, terminalAvailable: true }
const usage = { totalTokens: 0, updatedAt: '2026-09-22T16:00:00Z' }
diff --git a/cli/src/lib/agentFrame.ts b/cli/src/lib/agentFrame.ts
index f2b19e73b..ec8892cb2 100644
--- a/cli/src/lib/agentFrame.ts
+++ b/cli/src/lib/agentFrame.ts
@@ -30,7 +30,7 @@ import type { AgentOutputStats } from './agentOutputStats.js'
import type { GridAssignment } from './gridAssignment.js'
import type { GridWebSearchStatus } from './gridLaunchWire.js'
import type { AgentGridTarget, GridAnnotation } from './gridAnnotation.js'
-import { projectDisplayName, sessionDisplayTitle, type RegisteredSession } from './registry.js'
+import { isNameChosen, projectDisplayName, sessionDisplayTitle, type RegisteredSession } from './registry.js'
import { engineCanFork } from './forkAgent.js'
import { resumeMode, type ResumeMode } from './resumeCapability.js'
import type { DshVerdict } from '../dsh/verdict.js'
@@ -54,6 +54,12 @@ export type AgentFrame = {
sessionId: string
userId: string
name: string
+ /**
+ * Whether a person chose `name` (they renamed the agent), as against the name it was created with or its session
+ * title (registry.ts, `isNameChosen`). A client sends only a chosen name to the Swarm (task #2920). Absent from a
+ * daemon before it: a client reads that as "unknown" and sends nothing.
+ */
+ nameChosen: boolean
/**
* What the agent is on, in its own words — the session title (Claude Code's, Codex's), cleaned;
* null when there is none or it is the name already. It is usually the name too (registry.ts,
@@ -224,6 +230,7 @@ export async function agentFrame(
sessionId: s.sessionId,
userId: '',
name: projectDisplayName(s),
+ nameChosen: isNameChosen(s),
title: frameTitle(s),
status: s.active ? 'active' : 'offline',
activity: contextActivity?.() ?? null,
diff --git a/cli/src/lib/cloudAgents.ts b/cli/src/lib/cloudAgents.ts
index 0b3b7dae9..a2eeac133 100644
--- a/cli/src/lib/cloudAgents.ts
+++ b/cli/src/lib/cloudAgents.ts
@@ -183,6 +183,8 @@ export function cloudAgentFrame(harness: CloudHarness): CloudAgentFrame {
sessionId: harness.agentId,
userId: '',
name: harness.name,
+ // Whether a person chose it is not known here: a client sends nothing for it (agentFrame.ts).
+ nameChosen: false,
title: null,
status: harness.state === 'stopped' ? 'stopped' : 'active',
activity: { state: working ? 'working' : 'idle', epoch: harness.agentId, revision: Date.parse(harness.updatedAt), validForMs: working ? 120_000 : 0 },
diff --git a/cli/src/lib/registry.spec.ts b/cli/src/lib/registry.spec.ts
index d8ad3df17..b6fac281f 100644
--- a/cli/src/lib/registry.spec.ts
+++ b/cli/src/lib/registry.spec.ts
@@ -105,6 +105,28 @@ describe('registry remote display names', () => {
expect(projectDisplayName(registry.bySession('session-1')!)).toBe('Fix the login test')
})
+ // Task #2920: the agent frame says which names a person chose, so Desktop can send those to the Swarm and never an
+ // engine's session title.
+ it('says a name was chosen by a person only for a rename, and keeps saying so after a restart', async () => {
+ const transcriptPath = join(dataDir, 'session-1.jsonl')
+ writeFileSync(transcriptPath, '{}\n')
+ let { registry, isNameChosen } = await loadRegistryModule()
+ registry.load()
+ const registered = registerProcess(registry, { launcherId: 'h1', sessionId: 'session-1', transcriptPath, tmuxPane: '%1', cwd: '/tmp/demo' })
+ // Nobody renamed it: its name is the engine's session title or the name it was created with.
+ registered!.entry.title = 'cd /Users/macbookpro/projects/lamp'
+ expect(isNameChosen(registered!.entry)).toBe(false)
+ registered!.entry.defaultName = 'Builder'
+ expect(isNameChosen(registered!.entry)).toBe(false)
+ registry.rename('session-1', 'Release notes')
+ expect(isNameChosen(registry.bySession('session-1')!)).toBe(true)
+
+ // A new process of the daemon reads the names file.
+ ;({ registry, isNameChosen } = await loadRegistryModule())
+ registry.load()
+ expect(isNameChosen(registry.bySession('session-1')!)).toBe(true)
+ })
+
it('persists renamed display names independently from session removal', async () => {
const transcriptPath = join(dataDir, 'session-1.jsonl')
writeFileSync(transcriptPath, '{}\n')
diff --git a/cli/src/lib/registry.ts b/cli/src/lib/registry.ts
index 12405f864..c91f4e85e 100644
--- a/cli/src/lib/registry.ts
+++ b/cli/src/lib/registry.ts
@@ -360,6 +360,13 @@ export function projectDisplayName(s: RegisteredSession): string {
}
+/** Whether a person chose [s]'s name: they renamed it (kept in agent-names.json), as against the name it was created with
+ * or the engine's session title, which `projectDisplayName` falls back to. The agent frame carries it (`nameChosen`), so
+ * a client sends only a chosen name to the Swarm and never a title (task #2920). */
+export function isNameChosen(s: RegisteredSession): boolean {
+ return !!(NAME_OVERRIDES.get(s.sessionId) || NAME_OVERRIDES.get(s.agentId))
+}
+
/** The engine's own name for this session, or null while it has none worth showing. */
export function sessionDisplayTitle(s: RegisteredSession): string | null {
return namingTitle(titleDisplayName(s.title), { engine: s.engine, cwd: s.cwd, defaultName: s.defaultName })
diff --git a/desktop/lib/core/models.dart b/desktop/lib/core/models.dart
index ef69ee017..af6821654 100644
--- a/desktop/lib/core/models.dart
+++ b/desktop/lib/core/models.dart
@@ -484,6 +484,12 @@ class Agent {
final DateTime? lastActivityAt;
final DateTime? createdAt;
final bool closeSupported;
+
+ /// Whether a person chose [name] (the daemon's `nameChosen`: they renamed the
+ /// agent), as against the name it was created with or the engine's session
+ /// title. Null from a daemon that does not say; only a true one is sent to
+ /// the Swarm (task #2920).
+ final bool? nameChosen;
final String? closePlanState;
final String? closePlanDetail;
@@ -594,6 +600,7 @@ class Agent {
this.lastActivityAt,
this.createdAt,
this.closeSupported = false,
+ this.nameChosen,
this.closePlanState,
this.closePlanDetail,
this.lastOpenedAt,
@@ -768,6 +775,7 @@ class Agent {
? DateTime.tryParse(j['createdAt'] as String)
: null,
closeSupported: j['closeSupported'] == true,
+ nameChosen: j['nameChosen'] is bool ? j['nameChosen'] as bool : null,
closePlanState:
j['closePlan'] is Map &&
const {'waiting', 'failed'}.contains(j['closePlan']['state'])
@@ -847,6 +855,7 @@ class Agent {
lastActivityAt: lastActivityAt,
createdAt: createdAt,
closeSupported: closeSupported,
+ nameChosen: nameChosen,
closePlanState: clearClosePlan ? null : closePlanState,
closePlanDetail: clearClosePlan ? null : closePlanDetail,
lastOpenedAt: lastOpenedAt ?? this.lastOpenedAt,
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index d2a4f58dd..65ee42719 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -1892,7 +1892,7 @@ class AppNotifier extends ChangeNotifier {
/// views; Settings ▸ Account's Clear now clears it with them.
final browserCopies = BrowserCopies();
- late final superTabs = SuperTabClient(
+ late final SuperTabClient superTabs = SuperTabClient(
storage: localStore ?? HarnessFileStore.shared,
viewStorage: swarmViewStore(beside: localStore),
upload:
@@ -1992,6 +1992,11 @@ class AppNotifier extends ChangeNotifier {
controller.accountId != currentUser?.id) {
return;
}
+ // Only when this Swarm's agents or their names changed: a message in it
+ // is not a reason to look (review of #3021).
+ if (superTabs.agentNamesChanged(controller.tabId)) {
+ _syncChosenNames(tabId: controller.tabId);
+ }
var shown = false;
for (final tab in swarms.where((s) => s.superTabId == controller.tabId)) {
if (tab.name != controller.snapshot!.name || !tab.nameIsCustom) {
@@ -11391,6 +11396,7 @@ class AppNotifier extends ChangeNotifier {
prev.lastActivityAt != agent.lastActivityAt ||
prev.createdAt != agent.createdAt ||
prev.closeSupported != agent.closeSupported ||
+ prev.nameChosen != agent.nameChosen ||
prev.closePlanState != agent.closePlanState ||
prev.closePlanDetail != agent.closePlanDetail ||
prev.lastOpenedAt != agent.lastOpenedAt ||
@@ -14061,6 +14067,9 @@ class AppNotifier extends ChangeNotifier {
_cancelTurnActivity(machine.machine.machineId, agentId);
}
machine.agents = agents;
+ for (final agent in agents) {
+ _syncChosenName(machine, agent, previous[agent.id]);
+ }
_watchHeldLaunches(machine);
for (final agent in agents) {
_reconcileAgentActivity(machine, agent, previous[agent.id]);
@@ -14160,6 +14169,7 @@ class AppNotifier extends ChangeNotifier {
} else {
machine.agents = [...machine.agents]..[index] = agent;
}
+ _syncChosenName(machine, agent, previous);
_reconcileAgentActivity(machine, agent, previous);
if (previous?.name != agent.name) _recordAgentName(machine, agent);
_syncAgentName(machine, agent);
@@ -14212,6 +14222,55 @@ class AppNotifier extends ChangeNotifier {
return true;
}
+ bool _syncingChosenNames = false, _chosenNamesAgain = false;
+
+ /// An agent that arrives flagged as having a chosen name, or whose chosen
+ /// name changed: the only machine-side news worth a look (task #2920).
+ void _syncChosenName(MachineState machine, Agent agent, Agent? previous) {
+ if (agent.nameChosen != true) return;
+ if (previous?.nameChosen == true && previous?.name == agent.name) return;
+ _syncChosenNames(machineId: machine.machine.machineId, harnessId: agent.id);
+ }
+
+ /// Sends the names people chose for their agents, as the daemon says, to the
+ /// Swarms that show something else (task #2920): an agent renamed before
+ /// the rename reached the Swarm shows its name with no second rename. Runs
+ /// for one Swarm when its agents change, and for one harness when it arrives
+ /// flagged; each name goes once. Only this person's own machines: a harness
+ /// shared to watch is view-only.
+ void _syncChosenNames({String? tabId, String? machineId, String? harnessId}) {
+ if (_disposed) return;
+ if (_syncingChosenNames) {
+ // Something changed while names were going out: look everywhere again after.
+ _chosenNamesAgain = true;
+ return;
+ }
+ _syncingChosenNames = true;
+ unawaited(
+ superTabs
+ .syncChosenNames(
+ (machineId, harnessId) {
+ final machine = machineStates[machineId];
+ if (machine == null || machine.machine.isShared) return null;
+ return machine.agents
+ .where((agent) => agent.id == harnessId)
+ .firstOrNull;
+ },
+ tabId: tabId,
+ machineId: machineId,
+ harnessId: harnessId,
+ )
+ .then((_) {}, onError: (Object _) {})
+ .whenComplete(() {
+ _syncingChosenNames = false;
+ if (_chosenNamesAgain) {
+ _chosenNamesAgain = false;
+ _syncChosenNames();
+ }
+ }),
+ );
+ }
+
bool _renameAgent(MachineState machine, String agentId, String name) {
final index = machine.agents.indexWhere((agent) => agent.id == agentId);
if (index == -1 || name.trim().isEmpty) return false;
diff --git a/desktop/lib/super_tabs/client.dart b/desktop/lib/super_tabs/client.dart
index 73e823a5b..9c5e86c59 100644
--- a/desktop/lib/super_tabs/client.dart
+++ b/desktop/lib/super_tabs/client.dart
@@ -5,6 +5,7 @@ import 'package:clock/clock.dart';
import 'package:flutter/foundation.dart';
import '../core/local_key_value_store.dart';
+import '../core/models.dart';
import 'account_keys.dart';
import 'attachment_upload.dart';
import 'avatar_upload.dart';
@@ -414,6 +415,78 @@ class SuperTabClient {
return errors;
}
+ /// Names already sent by [syncChosenNames]: Swarm, agent and name, so each is
+ /// sent once per run, a refused one included.
+ final _chosenNamesSent = <String>{};
+
+ /// What each Swarm's agents and their names were when [agentNamesChanged]
+ /// last looked.
+ final _agentNamesSeen = <String, String>{};
+
+ /// Whether Swarm [tabId]'s agents or the names it shows for them changed
+ /// since this last said so: a message or a task moving in it is not a change,
+ /// so the sync of chosen names does not run for it (review of #3021).
+ bool agentNamesChanged(String tabId) {
+ final snapshot = _loaded[tabId]?.snapshot;
+ if (snapshot == null) return false;
+ final now = [
+ for (final agent in snapshot.agents)
+ '${agent.id}:${snapshot.agentName(agent.id)}',
+ ].join('|');
+ if (_agentNamesSeen[tabId] == now) return false;
+ _agentNamesSeen[tabId] = now;
+ return true;
+ }
+
+ /// A name as the Swarm keeps it: one space between words, trimmed.
+ static String _spaced(String name) =>
+ name.replaceAll(RegExp(r'\s+'), ' ').trim();
+
+ /// Sends the names people chose for their agents to the Swarms that show
+ /// something else (task #2920): an agent renamed before the rename reached
+ /// the Swarm shows its new name with no second rename. [native] reads the
+ /// harness an agent runs as on this person's own machines, null for one this
+ /// app cannot see or may not rename.
+ ///
+ /// Only a name the daemon says a person chose, never the creation name or an
+ /// engine's session title; a daemon that does not say sends nothing. Only for
+ /// an agent this person may rename (its contributor or its machine's owner,
+ /// as the Swarm decides), and never a Buddy, whose name its own settings set.
+ /// [tabId] narrows it to one Swarm, [machineId] and [harnessId] to one
+ /// harness: only what changed is looked at. Returns how many were sent.
+ Future<int> syncChosenNames(
+ Agent? Function(String machineId, String harnessId) native, {
+ String? tabId,
+ String? machineId,
+ String? harnessId,
+ }) async {
+ var sent = 0;
+ for (final MapEntry(key: swarm, value: controller)
+ in _loaded.entries.toList()) {
+ if (tabId != null && swarm != tabId) continue;
+ final snapshot = controller.snapshot;
+ if (snapshot == null) continue;
+ for (final agent in snapshot.agents.toList()) {
+ if (machineId != null && agent.machineId != machineId) continue;
+ if (harnessId != null && agent.harnessId != harnessId) continue;
+ final person = controller.accountId;
+ if (agent.isBuddy ||
+ (agent.contributorId != person && agent.machineOwnerId != person)) {
+ continue;
+ }
+ final local = native(agent.machineId, agent.harnessId);
+ if (local == null || local.nameChosen != true) continue;
+ final name = _spaced(local.name);
+ if (name.isEmpty || name == _spaced(snapshot.agentName(agent.id))) {
+ continue;
+ }
+ if (!_chosenNamesSent.add('$swarm|${agent.id}|$name')) continue;
+ if (await controller.renameAgent(agent.id, name) == null) sent++;
+ }
+ }
+ return sent;
+ }
+
/// The coordinator's name in the project the machine's harness coordinates.
String? leadCoordinatorForHarness(String machineId, String harnessId) =>
_leadOfHarness(machineId, harnessId)?.coordinator;
diff --git a/desktop/test/super_tab_chosen_names_test.dart b/desktop/test/super_tab_chosen_names_test.dart
new file mode 100644
index 000000000..86a4174c6
--- /dev/null
+++ b/desktop/test/super_tab_chosen_names_test.dart
@@ -0,0 +1,220 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/super_tabs/client.dart';
+
+import 'support/super_tab_fixture.dart';
+import 'swarm_state_test.dart' show MemoryStore;
+
+/// Names a person chose before #3015 reach the Swarm on their own (task
+/// #2920, Darren): the daemon's frame says `nameChosen`, and Desktop sends
+/// only those names, once.
+/// The `agent.rename` commands a Swarm received.
+int renames(ConversationServer server) => [
+ for (final post in server.posts)
+ if ((post['command'] as Map)['type'] == 'agent.rename') post,
+].length;
+
+void main() {
+ group('the agent frame', () {
+ test(
+ 'carries whether a person chose the name; an older daemon says nothing',
+ () {
+ expect(
+ Agent.fromJson({'id': 'a', 'name': 'x', 'nameChosen': true})
+ .nameChosen,
+ isTrue,
+ );
+ expect(
+ Agent.fromJson({'id': 'a', 'name': 'x', 'nameChosen': false})
+ .nameChosen,
+ isFalse,
+ );
+ expect(Agent.fromJson({'id': 'a', 'name': 'x'}).nameChosen, isNull);
+ },
+ );
+
+ test('a change of it is a change of the agent', () {
+ final before = Agent.fromJson({'id': 'a', 'name': 'x'});
+ final after = Agent.fromJson({
+ 'id': 'a',
+ 'name': 'x',
+ 'nameChosen': true,
+ });
+ expect(AppNotifier.agentsEqual([before], [after]), isFalse);
+ });
+ });
+
+ group('sending chosen names to the Swarm', () {
+ // A Swarm that holds the harness with the name it was added with: the
+ // terminal title, as Darren's list showed.
+ ConversationServer swarm({String contributor = 'owner'}) {
+ final server = ConversationServer()..state['id'] = 'tab';
+ server.state['agents'] = [
+ {
+ 'id': 'pm',
+ 'name': 'Lead',
+ 'displayName': 'cd /Users/macbookpro/proj…',
+ 'machineId': 'm',
+ 'harnessId': 'native-pm',
+ 'contributorId': contributor,
+ 'machineOwnerId': contributor,
+ 'configuration': {'engine': 'claude'},
+ },
+ ];
+ return server;
+ }
+
+ Future<(SuperTabClient, ConversationServer)> opened({
+ String contributor = 'owner',
+ }) async {
+ final server = swarm(contributor: contributor);
+ final client = SuperTabClient(
+ transport: (method, path, {body}) async {
+ if (Uri.parse(path).path == '/api/super-tabs/list') {
+ return {
+ 'tabs': [
+ {'id': 'tab', 'name': 'Pilot'},
+ ],
+ 'next': null,
+ };
+ }
+ return server.request(method, path, body: body);
+ },
+ storage: MemoryStore(),
+ onTabs: (_, _) {},
+ )..bind('owner');
+ // The Swarm's first read has landed, as when the sidebar shows it.
+ await (await client.open('tab')).refresh();
+ addTearDown(client.dispose);
+ return (client, server);
+ }
+
+ Agent Function(String, String) local(Map<String, dynamic> frame) =>
+ (machineId, harnessId) =>
+ Agent.fromJson({'id': 'native-pm', 'name': 'Darren PM', ...frame});
+
+ test(
+ 'a name chosen before the update shows in the Swarm, with no rename',
+ () async {
+ final (client, _) = await opened();
+ final sent = await client.syncChosenNames(local({'nameChosen': true}));
+ expect(sent, 1);
+ final c = await client.open('tab');
+ await c.refresh();
+ expect(c.snapshot!.agentName('pm'), 'Darren PM');
+ },
+ );
+
+ test('once per agent and name: the next look sends nothing', () async {
+ final (client, server) = await opened();
+ final lookup = local({'nameChosen': true});
+ expect(await client.syncChosenNames(lookup), 1);
+ expect(await client.syncChosenNames(lookup), 0);
+ expect(renames(server), 1);
+ });
+
+ test('a name nobody chose never sends the session title', () async {
+ final (client, server) = await opened();
+ final sent = await client.syncChosenNames(
+ local({'name': 'cd /Users/macbookpro/proj…', 'nameChosen': false}),
+ );
+ expect(sent, 0);
+ expect(renames(server), 0);
+ });
+
+ test('an older daemon, with no flag, sends nothing', () async {
+ final (client, server) = await opened();
+ expect(await client.syncChosenNames(local({})), 0);
+ expect(renames(server), 0);
+ });
+
+ test('the Swarm already shows the name: nothing is sent', () async {
+ final (client, server) = await opened();
+ final sent = await client.syncChosenNames(
+ local({'name': 'cd /Users/macbookpro/proj…', 'nameChosen': true}),
+ );
+ expect(sent, 0);
+ expect(renames(server), 0);
+ });
+
+ test('an agent this person does not run is left alone', () async {
+ final (client, server) = await opened(contributor: 'teammate');
+ expect(await client.syncChosenNames(local({'nameChosen': true})), 0);
+ expect(renames(server), 0);
+ });
+
+ // Review of #3021 (Sage): it must not scan every Swarm on every change.
+ test('a sync for one harness looks up only that harness', () async {
+ final (client, _) = await opened();
+ final looked = <String>[];
+ final sent = await client.syncChosenNames(
+ (machineId, harnessId) {
+ looked.add('$machineId/$harnessId');
+ return Agent.fromJson({
+ 'id': harnessId,
+ 'name': 'Darren PM',
+ 'nameChosen': true,
+ });
+ },
+ machineId: 'm',
+ harnessId: 'elsewhere',
+ );
+ expect(sent, 0);
+ expect(looked, isEmpty);
+ expect(
+ await client.syncChosenNames(
+ local({'nameChosen': true}),
+ machineId: 'm',
+ harnessId: 'native-pm',
+ ),
+ 1,
+ );
+ });
+
+ test(
+ 'a Swarm\'s agents are looked at again only when they changed',
+ () async {
+ final (client, server) = await opened();
+ expect(client.agentNamesChanged('tab'), isTrue);
+ expect(client.agentNamesChanged('tab'), isFalse);
+ (server.state['agents'] as List)[0]['displayName'] = 'Someone else';
+ await (await client.open('tab')).refresh();
+ expect(client.agentNamesChanged('tab'), isTrue);
+ expect(client.agentNamesChanged('tab'), isFalse);
+ },
+ );
+
+ test('spacing alone is no difference: the Swarm keeps one space', () async {
+ final (client, server) = await opened();
+ (server.state['agents'] as List)[0]['displayName'] = 'Darren PM';
+ await (await client.open('tab')).refresh();
+ final sent = await client.syncChosenNames(
+ local({'name': 'Darren PM', 'nameChosen': true}),
+ );
+ expect(sent, 0);
+ expect(renames(server), 0);
+ });
+
+ test(
+ 'a Buddy is left alone: its name is set in its own settings',
+ () async {
+ final (client, server) = await opened();
+ (server.state['agents'] as List)[0]['buddyOf'] = {
+ 'personId': 'owner',
+ 'projectId': 'lead',
+ 'generation': 'g',
+ };
+ await (await client.open('tab')).refresh();
+ expect(await client.syncChosenNames(local({'nameChosen': true})), 0);
+ expect(renames(server), 0);
+ },
+ );
+
+ test('a harness this machine does not know is left alone', () async {
+ final (client, server) = await opened();
+ expect(await client.syncChosenNames((_, _) => null), 0);
+ expect(renames(server), 0);
+ });
+ });
+}
diff --git a/desktop/test/super_tab_swarm_switcher_test.dart b/desktop/test/super_tab_swarm_switcher_test.dart
index c47736abc..ed378c548 100644
--- a/desktop/test/super_tab_swarm_switcher_test.dart
+++ b/desktop/test/super_tab_swarm_switcher_test.dart
@@ -1618,4 +1618,92 @@ void main() {
});
});
});
+
+ // Task #2920 (review of #3021): the app starts the sync of names people chose, on its own triggers.
+ group('names a person chose reach the Swarm on their own', () {
+ Map<String, dynamic> swarmAgent(String machineId, String harnessId) => {
+ 'id': 'pm',
+ 'name': 'Lead',
+ 'displayName': 'cd /Users/macbookpro/proj…',
+ 'machineId': machineId,
+ 'harnessId': harnessId,
+ 'contributorId': 'owner',
+ 'machineOwnerId': 'owner',
+ 'configuration': {'engine': 'claude'},
+ };
+ String shown(_Backend backend) =>
+ (backend.servers['alpha']!.state['agents'] as List).first['displayName']
+ as String;
+ int renames(_Backend backend) => [
+ for (final post in backend.servers['alpha']!.posts)
+ if ((post['command'] as Map?)?['type'] == 'agent.rename') post,
+ ].length;
+ Map<String, dynamic> frame(String id, {bool? chosen}) => {
+ 'id': id,
+ 'name': 'Darren PM',
+ 'engine': 'claude',
+ 'terminal': {'available': true},
+ 'nameChosen': ?chosen,
+ };
+
+ Future<(AppNotifier, _Backend)> loaded({
+ String machine = 'm',
+ String harness = 'a0',
+ }) async {
+ final backend = _Backend()..add('alpha', 'Alpha');
+ backend.servers['alpha']!.state['agents'] = [
+ swarmAgent(machine, harness),
+ ];
+ final app = _computer(backend, MemoryStore());
+ // A harness shared to watch is view-only here: its rename is refused.
+ const watched = Machine(
+ machineId: 's',
+ authMode: MachineAuthMode.remote,
+ name: 'Watched',
+ isShared: true,
+ );
+ app.machines = [...app.machines, watched];
+ app.machineStates['s'] = MachineState(watched)
+ ..nodeOnline = true
+ ..connectionStatus = ConnectionStatus.connected;
+ return (app, backend);
+ }
+
+ test('a flagged agent on this person\'s machine is sent when its Swarm '
+ 'loads', () async {
+ final (app, backend) = await loaded();
+ app.machineStates['m']!.agents = [
+ Agent.fromJson(frame('a0', chosen: true)),
+ ];
+ await app.superTabs.open('alpha');
+ await _settle();
+ expect(shown(backend), 'Darren PM');
+ });
+
+ test('the same agent on a shared machine sends nothing', () async {
+ final (app, backend) = await loaded(machine: 's', harness: 'x');
+ app.machineStates['s']!.agents = [
+ Agent.fromJson(frame('x', chosen: true)),
+ ];
+ await app.superTabs.open('alpha');
+ await _settle();
+ expect(renames(backend), 0);
+ expect(shown(backend), startsWith('cd /Users'));
+ });
+
+ test('an agent with no flag sends nothing until the flag arrives, then '
+ 'it is sent', () async {
+ final (app, backend) = await loaded();
+ app.machineStates['m']!.agents = [Agent.fromJson(frame('a0'))];
+ await app.superTabs.open('alpha');
+ await _settle();
+ expect(renames(backend), 0);
+ await app.handleMachineEventForTest('m', {
+ 'type': 'agent_synced',
+ 'payload': {'agent': frame('a0', chosen: true)},
+ });
+ await _settle();
+ expect(shown(backend), 'Darren PM');
+ });
+ });
}
diff --git a/docs/plans/2026-11-04-chosen-agent-names-plan.md b/docs/plans/2026-11-04-chosen-agent-names-plan.md
new file mode 100644
index 000000000..d73627247
--- /dev/null
+++ b/docs/plans/2026-11-04-chosen-agent-names-plan.md
@@ -0,0 +1,56 @@
+# Names a person already chose reach the Swarm Implementation Plan
+
+> Implemented by the task's Engineer task by task, each failing test committed before its code (project instructions,
+> Engineer). One independent review on the pull request.
+
+**Goal:** An agent a person renamed before #3015 shows that name in the Swarm after its next connect, with no second
+rename. An agent nobody renamed never sends its engine session title to the Swarm (task #2920, Darren).
+
+**Architecture:** The daemon's `name` in an agent frame is the person's rename, else the name the agent was created with,
+else the engine's session title (`projectDisplayName`); nothing says which. Builds on #3015's `agent.rename`.
+
+- CLI: the agent frame gains `nameChosen`, true only when the name is in agent-names.json (`isNameChosen`, a rename kept
+ by `registry.rename`). Cloud agents send false.
+- Desktop: `Agent.nameChosen` is true, false, or null when the daemon is older. `SuperTabClient.syncChosenNames` sends a
+ chosen name through #3015's `renameAgent` for each loaded Swarm agent on this person's own machine whose Swarm name
+ differs, once per Swarm, agent and name. `AppNotifier` runs it when a Swarm loads and when a machine's agents change.
+
+**Tech Stack:** TypeScript (cli, vitest), Flutter (Desktop and web share this code).
+
+**Spec:** task #2920's brief.
+
+## Global Constraints
+
+- Red first for each acceptance check: a renamed agent's name reaches the Swarm with no rename; an unrenamed agent's
+ title never does; a daemon without the flag sends nothing.
+- Swarm code stays out of `cli/src/core`: the flag is in `cli/src/lib`'s frame, which is not Swarm code.
+- Desktop tests use a memory store and a fake sign-in.
+
+## Design
+
+- growth: N/A because one extra boolean per agent frame; nothing accumulates. The sent-once memory is per run.
+- concurrency: the Swarm applies each rename in its one transaction; a repeat of the same name is a no-op.
+- read cost: N/A because no read is added; it compares names already loaded.
+- scale: one command per agent per run at most, only for agents whose names differ.
+- compatibility: an older daemon sends no flag, Desktop sends nothing; an older Desktop ignores the flag.
+- migration + rollback: N/A because nothing is stored; revert the commits.
+- audience: the Swarm enforces #3015's rule (contributor or machine owner); Desktop also sends only for agents it may
+ rename.
+- identity: the signed-in person's own commands, never the machine owner's login.
+- failure: a refusal (a role's name, a name another agent has) is not retried this run and does not change the local
+ name.
+- platforms: all; shared Flutter code and the daemon.
+
+## Review Focus
+
+- `nameChosen` is true only for a rename, never for a title or a creation name.
+- Nothing is sent for an agent whose daemon sent no flag, on a shared machine, or that this person may not rename.
+
+## Task 1: the frame says when a name was chosen
+
+**Files:** `cli/src/lib/registry.ts`, `cli/src/lib/agentFrame.ts`, `cli/src/lib/cloudAgents.ts`, their specs.
+
+## Task 2: Desktop sends chosen names once
+
+**Files:** `desktop/lib/core/models.dart`, `desktop/lib/super_tabs/client.dart`, `desktop/lib/state/app_state.dart`,
+`desktop/test/super_tab_chosen_names_test.dart`.
diff --git a/docs/plans/2026-11-04-phone-lead-start-card-plan.md b/docs/plans/2026-11-04-phone-lead-start-card-plan.md
new file mode 100644
index 000000000..b7a5a418f
--- /dev/null
+++ b/docs/plans/2026-11-04-phone-lead-start-card-plan.md
@@ -0,0 +1,180 @@
+# Phone Start Lead card Implementation Plan
+
+> This plan follows the project's own way of working (project instructions, Engineer): each plan task commits its
+> failing test before its code, and the pull request's one review step is the independent review. There is no
+> execution handoff; the Engineer implements it.
+
+**Goal:** In a Personal Swarm, the phone's empty project chat with no Lead shows Desktop's Start card (#2815): pick
+one of the person's computers and Claude Code or Codex (only the ones signed in there), Start Lead, then Starting…,
+or "Couldn’t start a Lead: <reason>" and Start Lead again.
+
+**Architecture:** Desktop starts a Personal project's Lead itself (`desktop/lib/super_tabs/personal_lead.dart`):
+`lead.claim` (backend `leadStart.ts`), then the person's computer starts the agent in the project's repo folder (or a
+new folder in its Harness projects folder) over Desktop's connection to it, then `agent.add` joins it as Lead. The
+Swarm's own start (`lead.start`) can't serve a Personal project: it needs the project's repository on the server, and
+a Personal project never sends one (`personal_projects.dart`). The phone has the same connection to the person's
+computers (`AppNotifier.createAgent`), so it runs Desktop's three steps: it runs nothing itself, the computer does.
+No backend change.
+
+**Tech Stack:** Flutter (mobile/), widget tests with the Swarm fixture server (`test/swarm/swarm_fixture.dart`) and
+a fake of the person's computers; `AppNotifier` rig tests (`test/app_state_agent_rpcs_test.dart`) for the computer
+call.
+
+**Spec:** Swarm task #2941's brief (Huy, 11-04), quoted in the pull request; Desktop's card plan
+`docs/plans/2026-11-04-personal-lead-start-card-plan.md`.
+
+## Global Constraints
+
+- Only a Personal Swarm (named `Personal`, owned by the reader, no one else in it, Desktop's `PersonalProjects.eligible`)
+ shows the card, in a project's own chat that is open, has no Lead, and the reader can write. Team Swarms unchanged;
+ the server refuses `lead.claim` outside a Personal Swarm anyway (`PERSONAL_SWARM_ONLY`).
+- Computers: the person's own connected computers (never shared, never a Harness Team account, never one waiting for a
+ link). Engines: Claude Code, then Codex, each only when installed (or installable) and not signed out there; an
+ engine list not read yet offers Claude Code, as Desktop does.
+- Folder: the project's repo folder on that computer when one of its agents there works in a checkout whose remote
+ makes this project's id (`personal-repo-<sha256 24>`, Desktop's `personalProjectOperation`), else a new folder in the
+ Harness projects folder.
+- Copy, as Desktop: "This project has no Lead yet", "Start Lead", "Starting…", "Folder: <path>", "A new folder in your
+ Harness projects folder", "Couldn’t start a Lead: <reason>", "Can’t start a Lead: <reason>". The last line on the
+ phone is "Or send a message below: the Lead reads it when it starts." (a phone message waits for the Lead and
+ doesn't start it; told to Huy with the mockup).
+- The start sends what Desktop's sends: `lead.claim {projectId, machineId}`; the computer's `agent_create` with
+ `engine`, `cwd` or the generated project folder (label `Lead`, the project's name), `permissionMode: full`,
+ `swarmRole: lead`, `swarmSkillMode` (the project's), Desktop's Lead launch prompt, and for Claude `model: opus`,
+ `effort: xhigh`; then `agent.add {conversationId, machineId, harnessId, name: Lead, lead: true, project, configuration}`.
+- Harness design language: the phone's theme tokens only (`grid.App*`), no new numeric `EdgeInsets`, `Color` or radius.
+- Never install on anyone's phone; screenshots come from widget tests in light and dark.
+
+## Review Focus
+
+- Start Lead tapped twice, or a second tap while the claim is out: one claim, one computer start.
+- The computer started the agent and `agent.add` failed: Start Lead again joins that same agent, never starts a
+ second one.
+- Another of the person's machines holds the claim (`leadStart: waiting`): the card shows Starting…, and the phone
+ starts nothing.
+- None of the person's computers is connected, or no engine is signed in on the one picked: the card says why and
+ offers no Start.
+- The Lead joins while the card shows (another machine started it): the card goes on the next read.
+- A failed join, then another computer picked: Start again claims the kept harness's computer and joins it; the card
+ shows that computer and engine and offers no other until it joins (review of #3029).
+
+Known limits (review of #3029, Minor): the harness kept for a failed join lives in memory only, so after the app
+restarts Start Lead starts a second one; Desktop resumes its journal, the phone has none. The new folder is
+`ProjectFolderRequest.forTask(projectName)` where Desktop sends `generated(label: Lead, name: projectName)`: both send
+the project's name as a suggested folder name the computer numbers past one that exists.
+
+---
+
+### Task 1: The start, as Desktop runs it
+
+**Files:**
+- Create: `mobile/lib/swarm/swarm_lead_start.dart`
+- Test: `mobile/test/swarm/swarm_lead_start_test.dart`
+
+**Interfaces:**
+- Produces: `typedef SwarmLeadComputer = ({String id, String name, List<String> engines, Map<String, String> folders})`,
+ `folders` keyed by normalized remote (`github.com/owner/repo`).
+- Produces: `typedef SwarmLeadLaunch = ({String engine, String? folder, String projectName, String prompt, String skillMode})`.
+- Produces: `typedef SwarmLeadStarted = ({String harnessId, String? cwd, String? remote})`: the harness started, and the
+ folder and remote it reports (for `agent.add`'s `project`).
+- Produces: `abstract interface class SwarmLeadComputers implements Listenable { List<SwarmLeadComputer> get leadComputers;
+ Future<SwarmLeadStarted> startLead(String machineId, SwarmLeadLaunch launch); }`: throws a `SuperTabFailure` with the
+ reason.
+- Produces: `bool swarmWantsLeadStart(SwarmReader reader, String chatId)`.
+- Produces: `String? swarmNormalizedRemote(String? remote)` and `String swarmPersonalProjectOperation(String repo)`
+ (ports of Desktop's `normalizedRemote` and `personalProjectOperation`).
+- Produces: `typedef SwarmLeadPlan = ({String machineId, String engine, String? folder})`;
+ `SwarmLeadPlan swarmLeadPlan(SwarmReader reader, SwarmLeadComputers computers, String chatId, {String? machineId, String? engine})`,
+ throwing `SuperTabFailure('NO_MACHINE', 'none of your computers is online')` or `('NO_ENGINE', 'Claude Code and Codex
+ aren’t signed in on <name>')`.
+- Produces: `class SwarmLeadStatus { starting | failed(reason) }` and `class SwarmLeadStarter extends ChangeNotifier`
+ with `static SwarmLeadStarter of(SwarmReader reader)`, `SwarmLeadStatus? statusOf(String chatId)`,
+ `Future<void> start(SwarmReader reader, SwarmLeadComputers computers, String chatId, {required String machineId, required String engine})`.
+- Produces: `String swarmLeadLaunchPrompt({required String tabId, required String conversationId})`, Desktop's
+ `superTabLaunchPrompt(lead: true)` word for word.
+
+- [ ] **Step 1: Write the failing tests** in `swarm_lead_start_test.dart`, on the Swarm fixture server with a Personal
+ Swarm (`name: Personal`, owner `me`, only `me`) and a fake `SwarmLeadComputers`:
+ - `wants a Lead only in a Personal Swarm's empty project chat`: true for the project chat with no Lead; false with a
+ Lead joined, in a Team Swarm (another person in it, or another name), in a task chat, for a reader who can't write.
+ - `the plan is the repo's folder on the picked computer, else a new one`: folders keyed by the remote whose
+ `swarmPersonalProjectOperation` is the project's id give that folder; another computer gives null.
+ - `the plan says why there is nothing to start on`: no computers → `none of your computers is online`; a computer
+ with no engines → `Claude Code and Codex aren’t signed in on Studio`.
+ - `start claims, starts on the computer, then joins it as Lead`: commands sent in order `lead.claim`
+ (`projectId`, `machineId`), then `startLead` with engine `codex`, the folder, the project's name, the prompt and
+ skill mode, then `agent.add` with `harnessId` from `startLead`, `name: Lead`, `lead: true`, `project.cwd`.
+ - `two taps make one claim and one start`.
+ - `a claim another machine holds starts nothing here and shows starting`.
+ - `a failure shows its reason, and Start again joins the agent already started`: `agent.add` refused with
+ `This project already has its Lead.` → status failed with `This project already has its Lead`; a second start
+ sends `lead.claim` and `agent.add` again but no second `startLead`.
+- [ ] **Step 2: Run them and watch them fail:** `flutter test test/swarm/swarm_lead_start_test.dart` fails to compile
+ (no `swarm_lead_start.dart`).
+- [ ] **Step 3: Implement** the interfaces above. The started harness is kept per chat until its join succeeds.
+- [ ] **Step 4: Run them and watch them pass** (same command).
+- [ ] **Step 5: Commit** the tests, then the code.
+
+### Task 2: The card in the empty project chat
+
+**Files:**
+- Create: `mobile/lib/swarm/swarm_lead_start_card.dart`
+- Modify: `mobile/lib/swarm/swarm_conversation_page.dart` (the `No messages yet.` branch)
+- Test: `mobile/test/swarm/swarm_lead_start_card_test.dart`
+
+**Interfaces:**
+- Consumes: Task 1's `swarmWantsLeadStart`, `swarmLeadPlan`, `SwarmLeadStarter`, `SwarmLeadComputers`.
+- Produces: `SwarmLeadStartCard({required SwarmReader reader, required SwarmLeadComputers computers, required String chatId})`,
+ keyed `swarm-lead-start`; its fields `swarm-lead-start-machine`, `swarm-lead-start-engine`, button
+ `swarm-lead-start-button`, lines `swarm-lead-start-folder`, `swarm-lead-start-error`, `swarm-lead-start-unavailable`.
+
+- [ ] **Step 1: Write the failing tests** in `swarm_lead_start_card_test.dart`, opening the conversation page on the
+ fixture with `SwarmScope` computers that implement `SwarmLeadComputers`:
+ - `an empty Personal project chat shows the Start card with the person's computers and signed-in engines`: card
+ with `This project has no Lead yet`, machine field `Studio`, picking lists `Studio` and `Air`, engine field lists only
+ the engines of the picked computer (`Claude Code` only on Air), `Folder: /Users/me/games`.
+ - `Start sends Desktop's start and shows Starting…`: tap → `lead.claim` then `startLead` on the picked computer and
+ engine, button reads `Starting…` and is disabled.
+ - `a failed start shows its reason and Start Lead tries again`: `startLead` throws `Codex isn’t signed in` →
+ `Couldn’t start a Lead: Codex isn’t signed in`; tap again → a second `startLead`.
+ - `no computer online says why and offers no Start`.
+ - `a Team Swarm's project chat shows no card` and `a project with a Lead shows no card`.
+ - With `LEAD_CARD_SHOTS=<dir>`, light and dark screenshots of the card ready, starting and failed.
+- [ ] **Step 2: Run them and watch them fail:** `flutter test test/swarm/swarm_lead_start_card_test.dart` fails
+ (no `swarm-lead-start`).
+- [ ] **Step 3: Implement** the card with the phone's theme tokens: a title, a full-width machine field, an engine
+ field, the folder line, a full-width filled button, the error line and the message line. In the conversation page,
+ show it in place of `No messages yet.` while `swarmWantsLeadStart` holds and `SwarmScope.computersOf(context)` is a
+ `SwarmLeadComputers`.
+- [ ] **Step 4: Run them and watch them pass,** then the files that draw the conversation page:
+ `flutter test test/swarm/swarm_conversation_test.dart test/swarm/swarm_chat_agents_test.dart`.
+- [ ] **Step 5: Commit** the tests, then the code.
+
+### Task 3: The app's computers start the Lead
+
+**Files:**
+- Modify: `mobile/lib/state/app_state.dart` (`createAgent`: `swarmRole`, `swarmSkillMode`, `launchModel`)
+- Modify: `mobile/lib/swarm/swarm_computers.dart` (`AppSwarmComputers implements SwarmLeadComputers`)
+- Test: `mobile/test/app_state_agent_rpcs_test.dart`, `mobile/test/swarm/swarm_lead_computers_test.dart`
+
+**Interfaces:**
+- Consumes: Task 1's `SwarmLeadComputers`, `SwarmLeadComputer`, `SwarmLeadLaunch`, `swarmNormalizedRemote`.
+- Produces: `AppNotifier.createAgent(..., String? swarmRole, String? swarmSkillMode, ({String model, String? effort})? launchModel)`,
+ sending `swarmRole`/`swarmSkillMode` for claude and codex only, and `model`/`effort`, as Desktop's.
+
+- [ ] **Step 1: Write the failing tests:**
+ - In `app_state_agent_rpcs_test.dart`, `a Swarm Lead's create carries its role, skill mode and model`:
+ `agent_create` has `swarmRole: lead`, `swarmSkillMode: default`, `model: opus`, `effort: xhigh`; a terminal's has
+ none of the Swarm keys.
+ - In `swarm_lead_computers_test.dart`, on the `AppNotifier` rig: `leadComputers lists the person's own connected
+ computers with their signed-in engines and repo folders` (a Team account and a shared computer left out; an
+ engine signed out left out; an agent's `project.remote` and `root` give `folders`), and `startLead creates the
+ agent in the folder, or a generated Lead folder, and answers its id`.
+- [ ] **Step 2: Run them and watch them fail:** `flutter test test/app_state_agent_rpcs_test.dart
+ test/swarm/swarm_lead_computers_test.dart`.
+- [ ] **Step 3: Implement.** `startLead` calls `createAgent` with `permissionMode: 'full'`, `prompt`,
+ `swarmRole: 'lead'`, `swarmSkillMode`, Claude's `launchModel` `(model: 'opus', effort: 'xhigh')`, and either
+ `folder` or `ProjectFolderRequest.forTask`-style generated folder named after the project; a failure string becomes
+ `SuperTabFailure('CREATE_FAILED', failure)`; no agent id becomes `the computer didn’t say which harness it started`.
+- [ ] **Step 4: Run them and watch them pass,** then `flutter test test/swarm/swarm_lead_start_card_test.dart`.
+- [ ] **Step 5: Commit** the tests, then the code.
diff --git a/docs/plans/assets/2026-11-04-phone-lead-start/lead-start-failed-dark.png b/docs/plans/assets/2026-11-04-phone-lead-start/lead-start-failed-dark.png
new file mode 100644
index 000000000..63e208ac3
Binary files /dev/null and b/docs/plans/assets/2026-11-04-phone-lead-start/lead-start-failed-dark.png differ
diff --git a/docs/plans/assets/2026-11-04-phone-lead-start/lead-start-failed-light.png b/docs/plans/assets/2026-11-04-phone-lead-start/lead-start-failed-light.png
new file mode 100644
index 000000000..f67de2189
Binary files /dev/null and b/docs/plans/assets/2026-11-04-phone-lead-start/lead-start-failed-light.png differ
diff --git a/docs/plans/assets/2026-11-04-phone-lead-start/lead-start-ready-dark.png b/docs/plans/assets/2026-11-04-phone-lead-start/lead-start-ready-dark.png
new file mode 100644
index 000000000..84de4ecfd
Binary files /dev/null and b/docs/plans/assets/2026-11-04-phone-lead-start/lead-start-ready-dark.png differ
diff --git a/docs/plans/assets/2026-11-04-phone-lead-start/lead-start-ready-light.png b/docs/plans/assets/2026-11-04-phone-lead-start/lead-start-ready-light.png
new file mode 100644
index 000000000..b9b20e1ca
Binary files /dev/null and b/docs/plans/assets/2026-11-04-phone-lead-start/lead-start-ready-light.png differ
diff --git a/docs/plans/assets/2026-11-04-phone-lead-start/lead-start-starting-dark.png b/docs/plans/assets/2026-11-04-phone-lead-start/lead-start-starting-dark.png
new file mode 100644
index 000000000..810cfaadd
Binary files /dev/null and b/docs/plans/assets/2026-11-04-phone-lead-start/lead-start-starting-dark.png differ
diff --git a/docs/plans/assets/2026-11-04-phone-lead-start/lead-start-starting-light.png b/docs/plans/assets/2026-11-04-phone-lead-start/lead-start-starting-light.png
new file mode 100644
index 000000000..04151a551
Binary files /dev/null and b/docs/plans/assets/2026-11-04-phone-lead-start/lead-start-starting-light.png differ
diff --git a/mobile/lib/state/app_state.dart b/mobile/lib/state/app_state.dart
index 36b30b0a6..810de07fc 100644
--- a/mobile/lib/state/app_state.dart
+++ b/mobile/lib/state/app_state.dart
@@ -223,6 +223,24 @@ class AgentCreationAttempt {
String? _outcome;
String? _agentId;
+ /// The machine's code for the refusal this attempt ended on, if it did.
+ String? _refusal;
+
+ /// The launch model the machine refused, so the agent runs its engine's
+ /// own (Desktop's `launchModelRefused`); null when it took it or none was
+ /// asked for.
+ ({String model, String? effort})? get launchModelRefused => _launchRefused;
+ ({String model, String? effort})? _launchRefused;
+
+ /// After the machine refused a launch model before launching anything: the
+ /// request may be sent again without it.
+ void _retryWithoutLaunchModel(({String model, String? effort}) refused) {
+ _launchRefused = refused;
+ _finished = false;
+ _outcome = null;
+ _refusal = null;
+ }
+
bool get awaitingConfirmation => _awaitingConfirmation;
/// The machine holds this request before starting anything (an engine it is installing), so it
@@ -7050,6 +7068,17 @@ class AppNotifier extends ChangeNotifier {
AgentCreationAttempt? attempt,
String? prompt,
String? name,
+
+ /// A Swarm agent's role and skill mode for the machine's Swarm skill
+ /// (Desktop's `swarmRole`, `swarmSkillMode`): sent for Claude Code and
+ /// Codex only.
+ String? swarmRole,
+ String? swarmSkillMode,
+
+ /// The model and effort it starts on, as Desktop's Lead starts (`model`,
+ /// `effort`). A machine that refuses them before starting anything gets
+ /// the request again without them ([AgentCreationAttempt.launchModelRefused]).
+ ({String model, String? effort})? launchModel,
}) {
final creation = attempt ?? AgentCreationAttempt();
final task = prompt?.trim();
@@ -7078,8 +7107,14 @@ class AppNotifier extends ChangeNotifier {
'codexHome': ?codexHome,
'gridModel': ?model?.id,
'gridName': ?model?.grid,
+ if (engine == 'claude' || engine == 'codex') ...{
+ 'swarmRole': ?swarmRole,
+ 'swarmSkillMode': ?swarmSkillMode,
+ },
+ 'model': ?launchModel?.model,
+ 'effort': ?launchModel?.effort,
};
- final created = _create(
+ Future<String?> ask() => _create(
machineId,
choices,
swarmId: swarmId,
@@ -7087,6 +7122,22 @@ class AppNotifier extends ChangeNotifier {
newDeskTab: newDeskTab,
attempt: creation,
);
+ final created = launchModel == null
+ ? ask()
+ : ask().then<String?>((error) {
+ if (error == null ||
+ !_launchModelRefusals.contains(creation._refusal)) {
+ return error;
+ }
+ // Refused before anything launched: the same request without them,
+ // so the agent starts on its engine's own model rather than not at
+ // all (Desktop's createAgent).
+ choices
+ ..remove('model')
+ ..remove('effort');
+ creation._retryWithoutLaunchModel(launchModel);
+ return ask();
+ });
if (task == null || task.isEmpty) return created;
// A task typed into New Harness is a message sent to a session too: the onboarding's first
// message, if it is still waiting for one (`terminal_page.dart` counts every other send).
@@ -7290,6 +7341,12 @@ class AppNotifier extends ChangeNotifier {
return null;
}
+ /// A machine's refusals of a launch model, made before anything launched.
+ static const _launchModelRefusals = {
+ 'LAUNCH_MODEL_UNSUPPORTED',
+ 'INVALID_LAUNCH_MODEL',
+ };
+
String _creationFailureMessage(
String code,
String? detail,
@@ -7551,8 +7608,10 @@ class AppNotifier extends ChangeNotifier {
'SESSION_OPEN_IN_TERMINAL',
'SESSION_BUSY_IN_TERMINAL',
'SESSION_STOP_FAILED',
+ ..._launchModelRefusals,
};
if (refusedBeforeLaunch.contains(failure.code)) {
+ creation._refusal = failure.code;
return creation._complete(
_creationFailureMessage(
failure.code,
@@ -7605,6 +7664,7 @@ class AppNotifier extends ChangeNotifier {
case 'failed':
final failure = result['failure'];
if (failure is! Map || failure['code'] is! String) return unconfirmed;
+ creation._refusal = failure['code'] as String;
return creation._complete(
_creationFailureMessage(
failure['code'] as String,
diff --git a/mobile/lib/swarm/swarm_computers.dart b/mobile/lib/swarm/swarm_computers.dart
index 9e07f069e..912fba816 100644
--- a/mobile/lib/swarm/swarm_computers.dart
+++ b/mobile/lib/swarm/swarm_computers.dart
@@ -4,6 +4,7 @@ import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import '../core/models.dart';
+import '../core/project_folder.dart';
import '../phone/agent_index.dart';
import '../phone/agents_list_page.dart';
import '../phone/phone_navigation.dart';
@@ -12,6 +13,8 @@ import '../phone/welcome/your_computer.dart';
import '../state/app_state.dart';
import 'swarm_agents.dart';
import 'swarm_chat_agents.dart';
+import 'swarm_lead_start.dart';
+import 'swarm_request.dart';
import 'swarm_start.dart';
/// The account's computers for Swarm's start screens, from the app's own
@@ -25,7 +28,11 @@ import 'swarm_start.dart';
///
/// It also lists the sessions running on them, for Add agent ([running]).
class AppSwarmComputers extends ChangeNotifier
- implements SwarmComputers, SwarmAgentsSource, SwarmRunningSessions {
+ implements
+ SwarmComputers,
+ SwarmAgentsSource,
+ SwarmRunningSessions,
+ SwarmLeadComputers {
AppSwarmComputers(this.notifier) {
notifier.addListener(_changed);
_changed();
@@ -88,6 +95,106 @@ class AppSwarmComputers extends ChangeNotifier
notifyListeners();
}
+ /// The person's own connected computers a Personal project's Lead starts
+ /// on (task #2941), as Desktop's card lists them (personal_lead.dart
+ /// `machinesFor`): never shared, a Harness Team account or one waiting for
+ /// a link. Each with Claude Code then Codex where installed (or installable)
+ /// and not signed out; a list not read yet asks the computer and offers
+ /// Claude Code meanwhile, as Desktop does. And each repo its agents work
+ /// in, by remote, with the checkout's folder.
+ @override
+ List<SwarmLeadComputer> get leadComputers => [
+ for (final machine in notifier.machineStates.values)
+ if (!machine.machine.shared &&
+ machine.machine.sessionKind != 'team' &&
+ !machine.needsLink &&
+ machine.connectionStatus == ConnectionStatus.connected)
+ (
+ id: machine.machine.machineId,
+ name: machine.machine.displayName,
+ engines: _leadEngines(machine),
+ folders: {
+ for (final agent in machine.agents)
+ if (agent.project case final project?)
+ ?swarmNormalizedRemote(project.remote):
+ project.root ?? project.cwd,
+ },
+ ),
+ ];
+
+ /// The computers whose engines the card asked for: once each, as a computer
+ /// that cannot answer stays unread and would be asked at every draw.
+ final _probed = <String>{};
+ bool _disposed = false;
+
+ List<String> _leadEngines(MachineState machine) {
+ final engines = machine.engines;
+ if (!engines.loaded) {
+ if (_probed.add(machine.machine.machineId)) {
+ unawaited(
+ notifier.probeEngines(machine.machine.machineId).then((_) {
+ if (!_disposed) notifyListeners();
+ }),
+ );
+ }
+ return const ['claude'];
+ }
+ return [
+ for (final engine in const ['claude', 'codex'])
+ if (engines[engine] case final known?
+ when (known.installed || known.installable) &&
+ known.signedIn != false)
+ engine,
+ ];
+ }
+
+ /// Starts the Lead on [machineId] as Desktop's card does (personal_lead.dart
+ /// `_launch`): approving everything, as a Swarm agent, with the Lead's
+ /// prompt and Claude's Lead model, in the repo's folder or a new one named
+ /// after the project.
+ @override
+ Future<SwarmLeadStarted> startLead(
+ String machineId,
+ SwarmLeadLaunch launch,
+ ) async {
+ final attempt = AgentCreationAttempt();
+ final failure = await notifier.createAgent(
+ machineId,
+ engine: launch.engine,
+ folder: launch.folder,
+ projectFolder: launch.folder == null
+ ? ProjectFolderRequest.forTask(launch.projectName)
+ : null,
+ permissionMode: 'full',
+ prompt: launch.prompt,
+ swarmRole: 'lead',
+ swarmSkillMode: launch.skillMode,
+ launchModel: launch.engine == 'claude'
+ ? (model: 'opus', effort: 'xhigh')
+ : null,
+ attempt: attempt,
+ );
+ if (failure != null) throw SuperTabFailure('CREATE_FAILED', failure);
+ final harnessId = attempt.agentId;
+ if (harnessId == null) {
+ throw const SuperTabFailure(
+ 'CREATE_FAILED',
+ 'the computer didn’t say which harness it started',
+ );
+ }
+ final project = notifier
+ .stateOf(machineId)
+ ?.agents
+ .where((a) => a.id == harnessId)
+ .firstOrNull
+ ?.project;
+ return (
+ harnessId: harnessId,
+ cwd: project == null ? launch.folder : project.root ?? project.cwd,
+ remote: project?.remote,
+ );
+ }
+
/// 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. Told of like [computers].
@@ -124,6 +231,7 @@ class AppSwarmComputers extends ChangeNotifier
@override
void dispose() {
+ _disposed = true;
notifier.removeListener(_changed);
agents.dispose();
super.dispose();
diff --git a/mobile/lib/swarm/swarm_conversation_page.dart b/mobile/lib/swarm/swarm_conversation_page.dart
index 9f83b11dd..ae0fa4829 100644
--- a/mobile/lib/swarm/swarm_conversation_page.dart
+++ b/mobile/lib/swarm/swarm_conversation_page.dart
@@ -42,6 +42,8 @@ import 'swarm_face.dart';
import 'swarm_file_picker.dart';
import 'swarm_outgoing_files.dart';
import 'swarm_inbox.dart';
+import 'swarm_lead_start.dart';
+import 'swarm_lead_start_card.dart';
import 'swarm_reader.dart';
import 'swarm_live_card.dart';
import 'swarm_link_previews.dart';
@@ -2075,6 +2077,23 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
return const SwarmChatSkeleton();
}
if (view.decisions.isEmpty) {
+ // A Personal project with no Lead offers to start one, as Desktop's
+ // empty chat does (task #2941).
+ if (SwarmScope.computersOf(context)
+ case final SwarmLeadComputers computers
+ when swarmWantsLeadStart(c.reader, c.id)) {
+ return Align(
+ alignment: Alignment.topCenter,
+ child: Padding(
+ padding: const EdgeInsets.all(AppSpace.screenInset),
+ child: SwarmLeadStartCard(
+ reader: c.reader,
+ computers: computers,
+ chatId: c.id,
+ ),
+ ),
+ );
+ }
return _said(
'No messages yet.',
key: const ValueKey('swarm-chat-empty'),
diff --git a/mobile/lib/swarm/swarm_lead_start.dart b/mobile/lib/swarm/swarm_lead_start.dart
new file mode 100644
index 000000000..153610bce
--- /dev/null
+++ b/mobile/lib/swarm/swarm_lead_start.dart
@@ -0,0 +1,372 @@
+import 'dart:async';
+import 'dart:convert';
+
+import 'package:cryptography/dart.dart';
+import 'package:flutter/foundation.dart';
+
+import 'model.dart';
+import 'swarm_buddy.dart' show swarmCanWrite;
+import 'swarm_reader.dart';
+import 'swarm_request.dart';
+
+/// The name Desktop gives the person's Personal Swarm (`kPersonalSwarmName`).
+const swarmPersonalName = 'Personal';
+
+/// How long a start the phone asked for shows as starting: the server's claim
+/// holds as long (backend leadStart.ts `LEAD_CLAIM_MS`).
+const swarmLeadStartWindow = Duration(minutes: 10);
+
+/// One of the person's own computers a Lead can start on: its name, the
+/// engines signed in there (Claude Code first), and the folder of each repo
+/// its agents work in, by remote ([swarmNormalizedRemote]).
+typedef SwarmLeadComputer = ({
+ String id,
+ String name,
+ List<String> engines,
+ Map<String, String> folders,
+});
+
+/// What the computer is asked to start: the Lead's engine, the repo's folder
+/// there or null for a new one named after [projectName], its first prompt,
+/// and the project's skill mode.
+typedef SwarmLeadLaunch = ({
+ String engine,
+ String? folder,
+ String projectName,
+ String prompt,
+ String skillMode,
+});
+
+/// The harness a computer started, and the folder and remote it reports.
+typedef SwarmLeadStarted = ({String harnessId, String? cwd, String? remote});
+
+/// The person's computers that start a Personal project's Lead, as Desktop
+/// starts it on another of theirs (desktop personal_lead.dart): the computer
+/// runs it, never the phone.
+abstract interface class SwarmLeadComputers implements Listenable {
+ /// The person's own connected computers, never shared nor a Harness Team
+ /// account.
+ List<SwarmLeadComputer> get leadComputers;
+
+ /// Starts the Lead on [machineId]; answers what it started, or throws a
+ /// [SuperTabFailure] saying why not.
+ Future<SwarmLeadStarted> startLead(String machineId, SwarmLeadLaunch launch);
+}
+
+/// Where a project's Lead starts: the computer, its engine, and the repo's
+/// folder there, or null for a new folder in the Harness projects folder.
+typedef SwarmLeadPlan = ({String machineId, String engine, String? folder});
+
+/// Whether [chatId] of [reader] offers to start its project's Lead, as
+/// Desktop's card shows (personal_lead.dart `wants`): the person's own
+/// Personal Swarm with no one else in it, a project's chat that is open, no
+/// Lead there, and a reader who may write.
+bool swarmWantsLeadStart(SwarmReader reader, String chatId) {
+ final snapshot = reader.snapshot;
+ if (reader.accessRevoked || snapshot == null) return false;
+ if (snapshot.name.trim() != swarmPersonalName ||
+ snapshot.ownerId != reader.accountId ||
+ snapshot.people.any((p) => p.id != reader.accountId) ||
+ !swarmCanWrite(reader)) {
+ return false;
+ }
+ final chat = snapshot.conversation(chatId);
+ if (chat == null || chat.archived || chat.isBuddyChat) return false;
+ if (!snapshot.isProjectLead(chatId)) return false;
+ final project = snapshot.projectFor(chatId);
+ if (project == null) return false;
+ final leadId = chat.leadId;
+ return leadId == null ||
+ !chat.agentIds.contains(leadId) ||
+ snapshot.agent(leadId) == null;
+}
+
+/// Where [chatId]'s Lead starts, or throws why it cannot (Desktop's
+/// `planFor`): the computer picked, else the first that holds the project's
+/// repo, else the first; the engine picked, else its first signed in.
+SwarmLeadPlan swarmLeadPlan(
+ SwarmReader reader,
+ SwarmLeadComputers computers,
+ String chatId, {
+ String? machineId,
+ String? engine,
+}) {
+ final projectId = reader.snapshot?.projectFor(chatId)?.id;
+ final all = computers.leadComputers;
+ String? folderOn(SwarmLeadComputer c) => projectId == null
+ ? null
+ : c.folders.entries
+ .where((e) => swarmPersonalProjectOperation(e.key) == projectId)
+ .firstOrNull
+ ?.value;
+ final picked = machineId == null
+ ? null
+ : all.where((c) => c.id == machineId).firstOrNull;
+ if (machineId != null && picked == null) {
+ throw const SuperTabFailure('NO_MACHINE', 'that computer isn’t online');
+ }
+ final chosen =
+ picked ??
+ all.where((c) => folderOn(c) != null).firstOrNull ??
+ all.firstOrNull;
+ if (chosen == null) {
+ throw const SuperTabFailure(
+ 'NO_MACHINE',
+ 'none of your computers is online',
+ );
+ }
+ final runs = engine != null && chosen.engines.contains(engine)
+ ? engine
+ : chosen.engines.firstOrNull;
+ if (runs == null) {
+ throw SuperTabFailure(
+ 'NO_ENGINE',
+ 'Claude Code and Codex aren’t signed in on ${chosen.name}',
+ );
+ }
+ return (machineId: chosen.id, engine: runs, folder: folderOn(chosen));
+}
+
+/// What the phone knows of a chat's Lead start: starting since [at], or
+/// failed with [reason].
+@immutable
+class SwarmLeadStatus {
+ const SwarmLeadStatus.starting(DateTime this.at) : reason = null;
+ const SwarmLeadStatus.failed(String this.reason) : at = null;
+ final DateTime? at;
+ final String? reason;
+ bool get failed => reason != null;
+}
+
+/// Starts a Personal project's Lead from the phone, once per chat, the way
+/// Desktop does (personal_lead.dart `start`): one claim (`lead.claim`) keeps
+/// two of the person's devices from starting two, the computer starts the
+/// agent, and `agent.add` joins it as Lead. One per [SwarmReader].
+class SwarmLeadStarter extends ChangeNotifier {
+ SwarmLeadStarter._();
+ static final _of = Expando<SwarmLeadStarter>('SwarmLeadStarter');
+ static SwarmLeadStarter of(SwarmReader reader) =>
+ _of[reader] ??= SwarmLeadStarter._();
+
+ final _status = <String, SwarmLeadStatus>{};
+
+ /// A harness started for a chat whose join has not gone through: Start
+ /// again joins it rather than starting a second.
+ final _started =
+ <String, ({String machineId, String engine, SwarmLeadStarted started})>{};
+
+ /// The computer and engine of [chatId]'s harness started but not joined
+ /// yet: Start again claims that computer and joins it, so the card shows it
+ /// and offers no other.
+ ({String machineId, String engine})? kept(String chatId) =>
+ switch (_started[chatId]) {
+ (:final machineId, :final engine, started: _) => (
+ machineId: machineId,
+ engine: engine,
+ ),
+ null => null,
+ };
+
+ /// [chatId]'s start as the phone knows it: one starting for longer than
+ /// the claim holds is no longer shown.
+ SwarmLeadStatus? statusOf(String chatId) {
+ final status = _status[chatId];
+ if (status?.at case final at?
+ when DateTime.now().difference(at) >= swarmLeadStartWindow) {
+ return null;
+ }
+ return status;
+ }
+
+ void _set(String chatId, SwarmLeadStatus status) {
+ _status[chatId] = status;
+ notifyListeners();
+ }
+
+ /// Starts [chatId]'s Lead on [machineId] with [engine], unless a start is
+ /// already under way.
+ Future<void> start(
+ SwarmReader reader,
+ SwarmLeadComputers computers,
+ String chatId, {
+ required String machineId,
+ required String engine,
+ }) async {
+ if (statusOf(chatId) case final status? when !status.failed) return;
+ _set(chatId, SwarmLeadStatus.starting(DateTime.now()));
+ try {
+ final project = reader.snapshot?.projectFor(chatId);
+ if (project == null) {
+ throw const SuperTabFailure(
+ 'PROJECT_UNAVAILABLE',
+ 'this project is no longer available',
+ );
+ }
+ // A harness already started whose join did not go through is the one:
+ // its computer is claimed and it joins, whatever was picked since
+ // (review of #3029).
+ final kept = _started[chatId];
+ final plan = kept != null
+ ? (machineId: kept.machineId, engine: kept.engine, folder: null)
+ : swarmLeadPlan(
+ reader,
+ computers,
+ chatId,
+ machineId: machineId,
+ engine: engine,
+ );
+ final claim = await _command(reader, {
+ 'type': 'lead.claim',
+ 'projectId': project.id,
+ 'machineId': plan.machineId,
+ });
+ // Another of the person's machines starts it: its join ends the note.
+ if (claim['leadStart'] == 'waiting') return;
+ final machine = plan.machineId;
+ final runs = plan.engine;
+ final started =
+ kept?.started ??
+ await computers.startLead(plan.machineId, (
+ engine: plan.engine,
+ folder: plan.folder,
+ projectName: project.name,
+ prompt: swarmLeadLaunchPrompt(
+ tabId: reader.tabId,
+ conversationId: chatId,
+ ),
+ skillMode: project.skillMode,
+ ));
+ _started[chatId] = (machineId: machine, engine: runs, started: started);
+ await _command(reader, {
+ 'type': 'agent.add',
+ 'conversationId': chatId,
+ 'machineId': machine,
+ 'harnessId': started.harnessId,
+ 'name': 'Lead',
+ 'lead': true,
+ if (started.cwd case final cwd?)
+ 'project': {
+ 'cwd': cwd,
+ 'repositoryUrl': superTabRepositoryUrl(started.remote),
+ },
+ // What it runs is its host's to report (agent.configuration).
+ 'configuration': {
+ 'engine': runs,
+ 'model': null,
+ 'effort': null,
+ 'contextWindow': null,
+ 'engineVersion': null,
+ },
+ });
+ _started.remove(chatId);
+ // Starting until the chat reads its Lead.
+ unawaited(reader.refresh().catchError((Object _) {}));
+ } on SuperTabFailure catch (failure) {
+ _set(chatId, SwarmLeadStatus.failed(_reason(failure)));
+ } catch (error) {
+ _set(chatId, SwarmLeadStatus.failed(_trim('$error')));
+ }
+ }
+
+ Future<Map<String, dynamic>> _command(
+ SwarmReader reader,
+ Map<String, dynamic> command,
+ ) async {
+ final answer = await reader.request(
+ 'POST',
+ '/api/super-tabs/${Uri.encodeComponent(reader.tabId)}/commands',
+ body: {'operationId': superTabOperationId(), 'command': command},
+ );
+ return superTabMap(superTabMap(answer)['result']);
+ }
+
+ /// A failure in the receipt's words: a server that does not know the claim
+ /// says so, any other its own reason, without a final full stop.
+ String _reason(SuperTabFailure failure) => failure.code == 'VALIDATION_ERROR'
+ ? 'this Swarm’s server needs an update'
+ : _trim(failure.message);
+
+ String _trim(String text) {
+ final line = text.trim().split('\n').first;
+ return line.endsWith('.') ? line.substring(0, line.length - 1) : line;
+ }
+}
+
+/// The form an agent reports its project's remote in: `host[:port]/owner/repo`
+/// with no scheme, user or `.git` (Desktop's `_canonicalRemote`).
+final _canonicalRemote = RegExp(
+ r'^[a-z0-9][a-z0-9._-]*[a-z0-9](?::\d+)?/\S+$',
+ caseSensitive: false,
+);
+
+/// A repo as one string on every computer, as Desktop's `normalizedRemote`
+/// makes it: the remote's host and path, lower case, without scheme, user,
+/// password, port or `.git`. Null for no remote, or a folder.
+String? swarmNormalizedRemote(String? remote) {
+ var text = remote?.trim() ?? '';
+ if (text.isEmpty) return null;
+ if (_canonicalRemote.hasMatch(text)) text = 'https://$text';
+ String? host, path;
+ final url = RegExp(
+ r'^([a-z][a-z0-9+.-]*)://(.*)$',
+ caseSensitive: false,
+ ).firstMatch(text);
+ if (url != null) {
+ if (url.group(1)!.toLowerCase() == 'file') return null;
+ final rest = url.group(2)!;
+ final slash = rest.indexOf('/');
+ if (slash <= 0) return null;
+ var authority = rest.substring(0, slash);
+ authority = authority.substring(authority.lastIndexOf('@') + 1);
+ host = authority.replaceFirst(RegExp(r':\d*$'), '');
+ path = rest.substring(slash + 1);
+ } else {
+ // scp-like `user@host:owner/repo`; a path (`/x`, `./x`, `C:\x`) is no remote.
+ final scp = RegExp(r'^(?:[^@/\\]+@)?([^:/\\]+):(?!//)(.+)$')
+ .firstMatch(text);
+ if (scp == null || scp.group(1)!.length < 2) return null;
+ host = scp.group(1);
+ path = scp.group(2);
+ }
+ final parts = path!
+ .replaceFirst(RegExp(r'\.git/*$', caseSensitive: false), '')
+ .split('/')
+ .where((p) => p.isNotEmpty && p != '.' && p != '..')
+ .toList();
+ if (host == null || host.isEmpty || parts.isEmpty) return null;
+ return [host, ...parts].join('/').toLowerCase();
+}
+
+/// The id of [repo]'s Personal project, as Desktop creates it on every
+/// computer of the person's (`personalProjectOperation`; backend
+/// `project.create` takes the request id as the project's).
+String swarmPersonalProjectOperation(String repo) {
+ final digest = const DartSha256()
+ .hashSync(utf8.encode(repo))
+ .bytes
+ .map((b) => b.toRadixString(16).padLeft(2, '0'))
+ .join();
+ return 'personal-repo-${digest.substring(0, 24)}';
+}
+
+/// The Lead's first prompt, Desktop's `superTabLaunchPrompt(lead: true)` word
+/// for word (desktop super_tabs/launch_prompt.dart).
+String swarmLeadLaunchPrompt({
+ required String tabId,
+ required String conversationId,
+}) =>
+ 'Harness Swarm agent. '
+ 'You are the Lead. '
+ 'Use `harness super-tab --tab $tabId` subcommands. '
+ 'First: `status`. Retry AGENT_UNAVAILABLE briefly; do not work or post before registration. '
+ 'Read `messages $conversationId` for the full request; if empty, ask what to work on. '
+ 'Reply: `post GROUP "message" UNIQUE_OPERATION_ID [--reply-to MESSAGE_ID]`. '
+ 'Use --reply-to for existing messages; answer each message once, do not post again. Retry lost replies with the same ID and text. '
+ 'Terminal output is not shared chat. If sandbox blocks commands, request permission. '
+ "Read your role in the project's instructions: `harness super-tab --tab $tabId instructions`. "
+ 'Be a helpful colleague: answer first, in their language, under 150 words unless asked. Hide commands, internal IDs and field names. Give results with revision/links. '
+ "Keep the project's status card current with project.report, the whole card as text: one short line per active task, where it is and what it waits on; it posts nothing. "
+ 'Post in the Lead chat only when work merges or ships, a person must decide something new, or work is badly stuck: one or two lines with the link. '
+ 'Ask a person a question once, as a decision; never repeat it. Answer questions, blockers and completion at once. '
+ 'On scheduled requests read new reports, then use project.report with the whole card, or text:null when nothing changed. No per-turn summarizer. '
+ 'Scope workgroups and sessions to this project.';
diff --git a/mobile/lib/swarm/swarm_lead_start_card.dart b/mobile/lib/swarm/swarm_lead_start_card.dart
new file mode 100644
index 000000000..c2b8c24c2
--- /dev/null
+++ b/mobile/lib/swarm/swarm_lead_start_card.dart
@@ -0,0 +1,259 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:lucide_icons_flutter/lucide_icons.dart';
+
+import 'package:harness_mobile/phone/phone_sheet.dart';
+import 'package:harness_mobile/shared/theme/app_icon_size.dart';
+import 'package:harness_mobile/shared/theme/app_space.dart';
+import 'package:harness_mobile/shared/theme/app_theme.dart';
+import 'package:harness_mobile/shared/theme/app_type.dart';
+import 'package:harness_mobile/shared/widgets/touch_target.dart';
+
+import 'swarm_lead_start.dart';
+import 'swarm_new_project_sheet.dart' show swarmLeadEngineLabel;
+import 'swarm_reader.dart';
+import 'swarm_request.dart';
+import 'swarm_row.dart';
+import 'swarm_style.dart';
+
+/// A Personal project chat with no Lead, empty: Desktop's Start card (#2815)
+/// on the phone (task #2941, Huy 11-04). The person picks one of their
+/// computers and an engine signed in there, and the computer starts the Lead
+/// in the project's folder ([SwarmLeadStarter]); the phone runs nothing. Laid
+/// out as Start your Buddy is on the phone (swarm_buddy_chat.dart).
+class SwarmLeadStartCard extends StatefulWidget {
+ const SwarmLeadStartCard({
+ super.key = const ValueKey('swarm-lead-start'),
+ required this.reader,
+ required this.computers,
+ required this.chatId,
+ });
+
+ final SwarmReader reader;
+ final SwarmLeadComputers computers;
+ final String chatId;
+
+ @override
+ State<SwarmLeadStartCard> createState() => _SwarmLeadStartCardState();
+}
+
+class _SwarmLeadStartCardState extends State<SwarmLeadStartCard> {
+ /// What the person picked; null keeps the plan's own choice.
+ String? _machine, _engine;
+
+ SwarmLeadStarter get _starter => SwarmLeadStarter.of(widget.reader);
+
+ Future<void> _pickMachine(String chosen) => showPhoneSheet(
+ context,
+ title: 'Computer',
+ actions: [
+ for (final c in widget.computers.leadComputers)
+ PhoneSheetAction(
+ icon: c.id == chosen ? LucideIcons.check : LucideIcons.laptop,
+ label: c.name,
+ onTap: () {
+ if (mounted) setState(() => _machine = c.id);
+ },
+ ),
+ ],
+ );
+
+ @override
+ Widget build(BuildContext context) => ListenableBuilder(
+ listenable: Listenable.merge([_starter, widget.computers]),
+ builder: (context, _) {
+ AppTheme.watch(context);
+ final status = _starter.statusOf(widget.chatId);
+ final starting = status != null && !status.failed;
+ // A Lead started there whose join did not go through: Start again
+ // joins it, so its computer and engine are the only ones.
+ final kept = _starter.kept(widget.chatId);
+ final picked = kept?.machineId ?? _machine;
+ SwarmLeadPlan? plan;
+ String? unavailable;
+ try {
+ plan = swarmLeadPlan(
+ widget.reader,
+ widget.computers,
+ widget.chatId,
+ machineId: widget.computers.leadComputers.any((c) => c.id == picked)
+ ? picked
+ : null,
+ engine: kept?.engine ?? _engine,
+ );
+ } on SuperTabFailure catch (failure) {
+ unavailable = failure.message;
+ }
+ // The plan's computer; with no plan, the one picked, so another can be.
+ final shownId = plan?.machineId ?? picked;
+ final machine = widget.computers.leadComputers
+ .where((c) => c.id == shownId)
+ .firstOrNull;
+ return DecoratedBox(
+ decoration: BoxDecoration(
+ color: AppCard.base,
+ borderRadius: BorderRadius.circular(AppCard.radius),
+ border: Border.all(color: AppCard.hair),
+ ),
+ child: Padding(
+ padding: const EdgeInsets.all(AppSpace.m),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Text(
+ 'This project has no Lead yet',
+ style: AppType.body(
+ color: AppPalette.textPrimary,
+ fontWeight: FontWeight.w600,
+ ),
+ ),
+ if (machine != null)
+ _Field(
+ label: 'Computer',
+ child: Semantics(
+ button: true,
+ label: 'Computer, ${machine.name}',
+ excludeSemantics: true,
+ child: InkWell(
+ key: const ValueKey('swarm-lead-start-machine'),
+ borderRadius: BorderRadius.circular(AppControl.radius),
+ onTap: starting || kept != null
+ ? null
+ : () => unawaited(_pickMachine(machine.id)),
+ child: ConstrainedBox(
+ constraints: const BoxConstraints(
+ minHeight: minTouchTarget,
+ ),
+ child: Row(
+ children: [
+ Expanded(
+ child: Text(
+ machine.name,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: AppType.body(
+ color: AppPalette.textPrimary,
+ ),
+ ),
+ ),
+ Icon(
+ LucideIcons.chevronDown,
+ size: AppIconSize.besideText,
+ color: AppPalette.textSecondary,
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ ),
+ if (plan case final plan? when machine != null) ...[
+ _Field(
+ label: 'Agent',
+ child: Wrap(
+ spacing: AppSpace.s,
+ runSpacing: AppSpace.xs,
+ children: [
+ for (final engine in machine.engines)
+ Semantics(
+ selected: engine == plan.engine,
+ child: SwarmButton(
+ key: ValueKey('swarm-lead-start-engine-$engine'),
+ label: swarmLeadEngineLabel(engine),
+ icon: engine == plan.engine
+ ? LucideIcons.check
+ : null,
+ onPressed: starting || kept != null
+ ? null
+ : () => setState(() => _engine = engine),
+ ),
+ ),
+ ],
+ ),
+ ),
+ const SizedBox(height: AppSpace.xs),
+ SwarmRow.line(
+ switch (plan.folder) {
+ final folder? => 'Folder: $folder',
+ null => 'A new folder in your Harness projects folder',
+ },
+ key: const ValueKey('swarm-lead-start-folder'),
+ lines: 2,
+ ),
+ const SizedBox(height: AppSpace.m),
+ SwarmButton(
+ key: const ValueKey('swarm-lead-start-button'),
+ label: 'Start Lead',
+ style: SwarmButtonStyle.fill,
+ wide: true,
+ busy: starting,
+ busyLabel: 'Starting…',
+ onPressed: () => unawaited(
+ _starter.start(
+ widget.reader,
+ widget.computers,
+ widget.chatId,
+ machineId: plan.machineId,
+ engine: plan.engine,
+ ),
+ ),
+ ),
+ ] else ...[
+ const SizedBox(height: AppSpace.xs),
+ Text(
+ 'Can’t start a Lead: $unavailable',
+ key: const ValueKey('swarm-lead-start-unavailable'),
+ style: AppType.body(color: AppPalette.textPrimary),
+ ),
+ ],
+ if (status?.reason case final reason?) ...[
+ const SizedBox(height: AppSpace.s),
+ Text(
+ 'Couldn’t start a Lead: $reason',
+ key: const ValueKey('swarm-lead-start-error'),
+ style: AppType.body(color: AppPalette.textPrimary),
+ ),
+ ],
+ const SizedBox(height: AppSpace.s),
+ SwarmRow.line(
+ 'Or send a message below: the Lead reads it when it starts.',
+ lines: 2,
+ ),
+ ],
+ ),
+ ),
+ );
+ },
+ );
+}
+
+/// One choice of the card: its name, then what is chosen (Start your Buddy's
+/// `_Field`).
+class _Field extends StatelessWidget {
+ const _Field({required this.label, required this.child});
+
+ final String label;
+ final Widget child;
+
+ @override
+ Widget build(BuildContext context) => Padding(
+ padding: const EdgeInsets.only(top: AppSpace.xs),
+ child: Row(
+ children: [
+ SizedBox(
+ width: _labelWidth,
+ child: Text(
+ label,
+ style: AppType.body(color: AppPalette.textSecondary),
+ ),
+ ),
+ Expanded(child: child),
+ ],
+ ),
+ );
+
+ /// Wide enough for "Computer" at the largest text the chat allows.
+ static const _labelWidth = AppSpace.xl * 3 + AppSpace.l;
+}
diff --git a/mobile/test/app_state_agent_rpcs_test.dart b/mobile/test/app_state_agent_rpcs_test.dart
index dc8aa7d0e..5b70834a1 100644
--- a/mobile/test/app_state_agent_rpcs_test.dart
+++ b/mobile/test/app_state_agent_rpcs_test.dart
@@ -98,6 +98,88 @@ void main() {
},
);
+ test('a Swarm Lead\'s create carries its role, skill mode and model, '
+ 'as Desktop\'s does (#2941)', () async {
+ final rig = await signedInWith({'m': []});
+ addTearDown(rig.app.dispose);
+ rig.conn('m').answers['agent_create'] = (p) => created(p, 'lead');
+ final attempt = AgentCreationAttempt();
+
+ final error = await measured(
+ rig,
+ 'm',
+ rig.app.createAgent(
+ 'm',
+ engine: 'claude',
+ folder: '/work',
+ permissionMode: 'full',
+ swarmRole: 'lead',
+ swarmSkillMode: 'default',
+ launchModel: (model: 'opus', effort: 'xhigh'),
+ attempt: attempt,
+ ),
+ );
+
+ expect(error, isNull);
+ final asked = rig.conn('m').payloadsOf('agent_create').single;
+ expect(asked['swarmRole'], 'lead');
+ expect(asked['swarmSkillMode'], 'default');
+ expect(asked['model'], 'opus');
+ expect(asked['effort'], 'xhigh');
+ expect(attempt.launchModelRefused, isNull);
+ });
+
+ test('a machine that refuses the Lead\'s model starts it on its engine\'s '
+ 'own, once', () async {
+ final rig = await signedInWith({'m': []});
+ addTearDown(rig.app.dispose);
+ rig.conn('m').answers['agent_create'] = (p) => p.containsKey('model')
+ ? throw refusal('LAUNCH_MODEL_UNSUPPORTED', detail: 'update claude')
+ : created(p, 'lead');
+ final attempt = AgentCreationAttempt();
+
+ final error = await measured(
+ rig,
+ 'm',
+ rig.app.createAgent(
+ 'm',
+ engine: 'claude',
+ folder: '/work',
+ swarmRole: 'lead',
+ launchModel: (model: 'opus', effort: 'xhigh'),
+ attempt: attempt,
+ ),
+ );
+
+ expect(error, isNull);
+ expect(attempt.agentId, 'lead');
+ final asked = rig.conn('m').payloadsOf('agent_create');
+ expect(asked, hasLength(2));
+ expect(asked.last.containsKey('model'), isFalse);
+ expect(asked.last['swarmRole'], 'lead');
+ expect(attempt.launchModelRefused, (model: 'opus', effort: 'xhigh'));
+ });
+
+ test('a terminal is sent none of a Swarm agent\'s keys', () async {
+ final rig = await signedInWith({'m': []});
+ addTearDown(rig.app.dispose);
+ rig.conn('m').answers['agent_create'] = (p) => created(p, 'shell');
+ await measured(
+ rig,
+ 'm',
+ rig.app.createAgent(
+ 'm',
+ engine: 'terminal',
+ folder: null,
+ swarmRole: 'lead',
+ swarmSkillMode: 'default',
+ ),
+ );
+ final asked = rig.conn('m').payloadsOf('agent_create').single;
+ expect(asked.containsKey('swarmRole'), isFalse);
+ expect(asked.containsKey('swarmSkillMode'), isFalse);
+ });
+
test('a terminal with no folder is sent no cwd at all, and the machine '
'opens it at home', () async {
final rig = await signedInWith({'m': []});
@@ -567,57 +649,52 @@ void main() {
});
}
- test(
- 'a folder named after the task, taken on an older machine, says how to get a new one',
- () async {
- final rig = await signedInWith({'m': []});
- addTearDown(rig.app.dispose);
- // A machine that predates `projectNameMode` refuses the name the phone
- // made up, in words written for a name somebody typed.
- const taken =
- '“robot-talks-to-gemini” already exists. Select that folder from '
- 'your projects.';
- rig.conn('m').answers['agent_create'] = (_) =>
- throw refusal('PROJECT_EXISTS', detail: taken);
- final attempt = AgentCreationAttempt();
+ test('a folder named after the task, taken on an older machine, says how to get a new one', () async {
+ final rig = await signedInWith({'m': []});
+ addTearDown(rig.app.dispose);
+ // A machine that predates `projectNameMode` refuses the name the phone
+ // made up, in words written for a name somebody typed.
+ const taken =
+ '“robot-talks-to-gemini” already exists. Select that folder from '
+ 'your projects.';
+ rig.conn('m').answers['agent_create'] = (_) =>
+ throw refusal('PROJECT_EXISTS', detail: taken);
+ final attempt = AgentCreationAttempt();
- final error = await rig.app.createAgent(
+ final error = await rig.app.createAgent(
+ 'm',
+ engine: 'claude',
+ folder: '',
+ projectFolder: ProjectFolderRequest.forTask('Robot talks to Gemini'),
+ prompt: 'Robot talks to Gemini',
+ attempt: attempt,
+ );
+
+ expect(error, contains('named after this task already exists'));
+ expect(error, contains('update Harness there'));
+ expect(attempt.awaitingConfirmation, isFalse);
+ expect(
+ rig.conn('m').payloadsOf('agent_create').single['projectNameMode'],
+ 'suggested',
+ );
+
+ // The same, when the refusal arrives as the receipt.
+ rig.conn('m').answers['agent_create'] = (p) => {
+ 'creationId': p['creationId'],
+ 'state': 'failed',
+ 'failure': {'code': 'PROJECT_EXISTS', 'detail': taken},
+ };
+ expect(
+ await rig.app.createAgent(
'm',
engine: 'claude',
folder: '',
projectFolder: ProjectFolderRequest.forTask('Robot talks to Gemini'),
prompt: 'Robot talks to Gemini',
- attempt: attempt,
- );
-
- expect(error, contains('named after this task already exists'));
- expect(error, contains('update Harness there'));
- expect(attempt.awaitingConfirmation, isFalse);
- expect(
- rig.conn('m').payloadsOf('agent_create').single['projectNameMode'],
- 'suggested',
- );
-
- // The same, when the refusal arrives as the receipt.
- rig.conn('m').answers['agent_create'] = (p) => {
- 'creationId': p['creationId'],
- 'state': 'failed',
- 'failure': {'code': 'PROJECT_EXISTS', 'detail': taken},
- };
- expect(
- await rig.app.createAgent(
- 'm',
- engine: 'claude',
- folder: '',
- projectFolder: ProjectFolderRequest.forTask(
- 'Robot talks to Gemini',
- ),
- prompt: 'Robot talks to Gemini',
- ),
- error,
- );
- },
- );
+ ),
+ error,
+ );
+ });
test('an old engine with no reason names the way out', () async {
final rig = await signedInWith({'m': []});
@@ -1104,23 +1181,26 @@ void main() {
expect(rig.app.stateOf('m')!.agents.single.id, 'a');
});
- test('a stop the machine says to ask again is asked again, then goes', () async {
- // IDENTITY_UNAVAILABLE: the conversation file changed under the machine's lookup.
- final rig = await signedInWith({
- 'm': ['a', 'b'],
- });
- addTearDown(rig.app.dispose);
- rig.app.stopRetryDelays = const [Duration.zero, Duration.zero];
- var asked = 0;
- rig.conn('m').answers['agent_delete'] = (_) => ++asked == 1
- ? {'error': 'IDENTITY_UNAVAILABLE', 'held': true, 'retryable': true}
- : {'deleted': true};
+ test(
+ 'a stop the machine says to ask again is asked again, then goes',
+ () async {
+ // IDENTITY_UNAVAILABLE: the conversation file changed under the machine's lookup.
+ final rig = await signedInWith({
+ 'm': ['a', 'b'],
+ });
+ addTearDown(rig.app.dispose);
+ rig.app.stopRetryDelays = const [Duration.zero, Duration.zero];
+ var asked = 0;
+ rig.conn('m').answers['agent_delete'] = (_) => ++asked == 1
+ ? {'error': 'IDENTITY_UNAVAILABLE', 'held': true, 'retryable': true}
+ : {'deleted': true};
- expect(await rig.app.deleteAgent('m', 'a'), isNull);
+ expect(await rig.app.deleteAgent('m', 'a'), isNull);
- expect(rig.conn('m').payloadsOf('agent_delete'), hasLength(2));
- expect(rig.app.stateOf('m')!.agents.map((a) => a.id), ['b']);
- });
+ expect(rig.conn('m').payloadsOf('agent_delete'), hasLength(2));
+ expect(rig.app.stateOf('m')!.agents.map((a) => a.id), ['b']);
+ },
+ );
test('asks again at most twice, then says why', () async {
final rig = await signedInWith({
@@ -1128,8 +1208,10 @@ void main() {
});
addTearDown(rig.app.dispose);
rig.app.stopRetryDelays = const [Duration.zero, Duration.zero];
- rig.conn('m').answers['agent_delete'] = (_) =>
- {'error': 'IDENTITY_UNAVAILABLE', 'retryable': true};
+ rig.conn('m').answers['agent_delete'] = (_) => {
+ 'error': 'IDENTITY_UNAVAILABLE',
+ 'retryable': true,
+ };
expect(
await rig.app.deleteAgent('m', 'a'),
@@ -1147,7 +1229,9 @@ void main() {
});
addTearDown(rig.app.dispose);
rig.app.stopRetryDelays = const [Duration.zero, Duration.zero];
- rig.conn('m').answers['agent_delete'] = (_) => {'error': 'STOP_UNCONFIRMED'};
+ rig.conn('m').answers['agent_delete'] = (_) => {
+ 'error': 'STOP_UNCONFIRMED',
+ };
expect(
await rig.app.deleteAgent('m', 'a'),
@@ -1839,8 +1923,10 @@ void main() {
await rig.app.retargetAgentToGridModel('m', 'a', 'qwen'),
'Use another engine.',
);
- rig.conn('m').answers['agent_retarget'] = (_) =>
- throw refusal('PTY_HOST_UNAVAILABLE', detail: 'harness-pty is not installed');
+ rig.conn('m').answers['agent_retarget'] = (_) => throw refusal(
+ 'PTY_HOST_UNAVAILABLE',
+ detail: 'harness-pty is not installed',
+ );
expect(
await rig.app.clearAgentGrid('m', 'a'),
"This machine's terminals did not answer. Run harness start there, then try again.",
diff --git a/mobile/test/swarm/swarm_lead_computers_test.dart b/mobile/test/swarm/swarm_lead_computers_test.dart
new file mode 100644
index 000000000..3dd597037
--- /dev/null
+++ b/mobile/test/swarm/swarm_lead_computers_test.dart
@@ -0,0 +1,189 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/core/engine_availability.dart';
+import 'package:harness_mobile/core/models.dart';
+import 'package:harness_mobile/swarm/swarm_computers.dart';
+import 'package:harness_mobile/swarm/swarm_request.dart';
+
+import '../viewer_app_fixture.dart';
+
+/// The app's own computers start a Personal project's Lead (task #2941): the
+/// person's connected computers with the engines signed in there and the
+/// folders of the repos their agents work in, and the start itself, asked of
+/// the computer as Desktop asks it.
+void main() {
+ Map<String, dynamic> created(Map<String, dynamic> payload, String id) => {
+ 'creationId': payload['creationId'],
+ 'state': 'created',
+ 'agent': agentJson(
+ id,
+ extra: {
+ 'project': {
+ 'name': 'games',
+ 'cwd': payload['cwd'] ?? '/Users/me/Harness/games',
+ 'remote': payload['cwd'] == null ? null : 'github.com/acme/games',
+ },
+ },
+ ),
+ };
+
+ EngineAvailability engine(String id, {bool? signedIn = true}) =>
+ EngineAvailability(engine: id, installed: true, signedIn: signedIn);
+
+ test('leadComputers lists the person\'s own connected computers with their '
+ 'signed-in engines and repo folders', () async {
+ final rig = await signedInWith({'m': [], 'n': []});
+ addTearDown(rig.app.dispose);
+ rig.conn('m').answers['agents_list'] = (_) => {
+ 'agents': [
+ agentJson(
+ 'a1',
+ extra: {
+ 'project': {
+ 'name': 'games',
+ 'cwd': '/Users/me/games/web',
+ 'root': '/Users/me/games',
+ 'remote': 'github.com/Acme/Games',
+ },
+ },
+ ),
+ ],
+ };
+ await rig.app.syncAgentsForTest('m');
+ rig.app.stateOf('m')!.engines.replace([
+ engine('claude'),
+ engine('codex', signedIn: false),
+ ]);
+ rig.app.stateOf('n')!.engines.replace([engine('codex')]);
+ final computers = AppSwarmComputers(rig.app);
+ addTearDown(computers.dispose);
+
+ final listed = {for (final c in computers.leadComputers) c.id: c};
+ expect(listed.keys, {'m', 'n'});
+ expect(listed['m']!.engines, ['claude']);
+ expect(listed['m']!.folders, {'github.com/acme/games': '/Users/me/games'});
+ expect(listed['n']!.engines, ['codex']);
+ expect(listed['n']!.folders, isEmpty);
+ });
+
+ test(
+ 'a computer not connected, shared, or a Team account is left out',
+ () async {
+ final rig = await signedInWith({'m': [], 't': [], 's': []});
+ addTearDown(rig.app.dispose);
+ rig.app.stateOf('t')!.machine = Machine(
+ machineId: 't',
+ authMode: MachineAuthMode.remote,
+ name: 'Team',
+ status: 'online',
+ sessionKind: 'team',
+ );
+ rig.app.stateOf('s')!.machine = Machine(
+ machineId: 's',
+ authMode: MachineAuthMode.remote,
+ name: 'Shared',
+ status: 'online',
+ shared: true,
+ );
+ final computers = AppSwarmComputers(rig.app);
+ addTearDown(computers.dispose);
+ expect([for (final c in computers.leadComputers) c.id], ['m']);
+ // An engine list not read yet offers Claude Code, as Desktop does.
+ expect(computers.leadComputers.single.engines, ['claude']);
+ },
+ );
+
+ test('an engine list that cannot be read is asked for once, not at every '
+ 'read of the computers', () async {
+ final rig = await signedInWith({'m': []});
+ addTearDown(rig.app.dispose);
+ rig.conn('m').answers['engines_probe'] = (_) =>
+ throw refusal('UNSUPPORTED');
+ final computers = AppSwarmComputers(rig.app);
+ addTearDown(computers.dispose);
+
+ for (var i = 0; i < 3; i++) {
+ expect(computers.leadComputers.single.engines, ['claude']);
+ await settle();
+ }
+ expect(rig.conn('m').payloadsOf('engines_probe'), hasLength(1));
+ });
+
+ test('startLead creates the Lead in the repo\'s folder and answers what it '
+ 'started', () async {
+ final rig = await signedInWith({'m': []});
+ addTearDown(rig.app.dispose);
+ rig.conn('m').answers['agent_create'] = (p) => created(p, 'lead');
+ final computers = AppSwarmComputers(rig.app);
+ addTearDown(computers.dispose);
+
+ final started = await computers.startLead('m', (
+ engine: 'claude',
+ folder: '/Users/me/games',
+ projectName: 'games',
+ prompt: 'Harness Swarm agent. You are the Lead.',
+ skillMode: 'default',
+ ));
+
+ expect(started.harnessId, 'lead');
+ expect(started.cwd, '/Users/me/games');
+ expect(started.remote, 'github.com/acme/games');
+ final asked = rig.conn('m').payloadsOf('agent_create').single;
+ expect(asked['engine'], 'claude');
+ expect(asked['cwd'], '/Users/me/games');
+ expect(asked['permissionMode'], 'full');
+ expect(asked['swarmRole'], 'lead');
+ expect(asked['swarmSkillMode'], 'default');
+ expect(asked['prompt'], 'Harness Swarm agent. You are the Lead.');
+ expect(asked['model'], 'opus');
+ expect(asked['effort'], 'xhigh');
+ });
+
+ test('with no repo there, a new folder named after the project; Codex runs '
+ 'its own model', () async {
+ final rig = await signedInWith({'m': []});
+ addTearDown(rig.app.dispose);
+ rig.conn('m').answers['agent_create'] = (p) => created(p, 'lead');
+ final computers = AppSwarmComputers(rig.app);
+ addTearDown(computers.dispose);
+
+ await computers.startLead('m', (
+ engine: 'codex',
+ folder: null,
+ projectName: 'games',
+ prompt: 'Lead',
+ skillMode: 'orchestration',
+ ));
+
+ final asked = rig.conn('m').payloadsOf('agent_create').single;
+ expect(asked.containsKey('cwd'), isFalse);
+ expect(asked['projectSource'], 'new');
+ expect(asked['projectName'], 'games');
+ expect(asked.containsKey('model'), isFalse);
+ });
+
+ test('a computer that refuses says why', () async {
+ final rig = await signedInWith({'m': []});
+ addTearDown(rig.app.dispose);
+ rig.conn('m').answers['agent_create'] = (_) =>
+ throw refusal('TMUX_UNAVAILABLE');
+ final computers = AppSwarmComputers(rig.app);
+ addTearDown(computers.dispose);
+
+ expect(
+ computers.startLead('m', (
+ engine: 'claude',
+ folder: '/Users/me/games',
+ projectName: 'games',
+ prompt: 'Lead',
+ skillMode: 'default',
+ )),
+ throwsA(
+ isA<SuperTabFailure>().having(
+ (f) => f.message,
+ 'message',
+ contains('tmux'),
+ ),
+ ),
+ );
+ });
+}
diff --git a/mobile/test/swarm/swarm_lead_start_card_test.dart b/mobile/test/swarm/swarm_lead_start_card_test.dart
new file mode 100644
index 000000000..d25c934aa
--- /dev/null
+++ b/mobile/test/swarm/swarm_lead_start_card_test.dart
@@ -0,0 +1,357 @@
+import 'dart:async';
+import 'dart:convert';
+import 'dart:io';
+import 'dart:ui' as ui;
+
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+
+import 'package:harness_mobile/notify/system_notices.dart';
+import 'package:harness_mobile/settings/experimental_features.dart';
+import 'package:harness_mobile/shared/theme/app_theme.dart';
+import 'package:harness_mobile/shared/theme/color_palette.dart';
+import 'package:harness_mobile/swarm/swarm_conversation_page.dart';
+import 'package:harness_mobile/swarm/swarm_lead_start.dart';
+import 'package:harness_mobile/swarm/swarm_project_page.dart';
+import 'package:harness_mobile/swarm/swarm_request.dart';
+import 'package:harness_mobile/swarm/swarm_session.dart';
+
+import '../voice_fakes.dart';
+import 'swarm_computers_fake.dart';
+import 'swarm_fixture.dart';
+import 'swarm_lead_start_fixture.dart';
+
+/// The person's computers, as Swarm's screens and the Start Lead card read
+/// them.
+class _Computers extends FakeComputers implements SwarmLeadComputers {
+ _Computers(this.lead) : super(const [(name: 'Studio', away: false)]);
+
+ final FakeLeadComputers lead;
+
+ @override
+ List<SwarmLeadComputer> get leadComputers => lead.leadComputers;
+
+ @override
+ Future<SwarmLeadStarted> startLead(
+ String machineId,
+ SwarmLeadLaunch launch,
+ ) => lead.startLead(machineId, launch);
+}
+
+/// Light and dark screenshots of the card, to the folder this names.
+final shots = Platform.environment['LEAD_CARD_SHOTS'];
+
+/// The phone's empty Personal project chat offers to start its Lead, as
+/// Desktop's does (#2815): the person's computers and the engines signed in
+/// on each, Start Lead, Starting…, and a failure's reason with Start Lead
+/// again (task #2941, Huy 11-04).
+void main() {
+ late FakeSwarm swarm;
+ late FakeLeadComputers lead;
+ late SwarmHost host;
+
+ setUpAll(() async {
+ if (shots == null || !Platform.isMacOS) return;
+ final sf = ByteData.sublistView(
+ await File('/System/Library/Fonts/SFNS.ttf').readAsBytes(),
+ );
+ for (final family in ['.AppleSystemUIFont', 'Roboto']) {
+ await (FontLoader(family)..addFont(Future.value(sf))).load();
+ }
+ final mono = ByteData.sublistView(
+ await File('/System/Library/Fonts/SFNSMono.ttf').readAsBytes(),
+ );
+ for (final family in ['.AppleSystemUIFontMonospaced', 'monospace']) {
+ await (FontLoader(family)..addFont(Future.value(mono))).load();
+ }
+ final manifest =
+ jsonDecode(await rootBundle.loadString('FontManifest.json')) as List;
+ for (final entry in manifest.cast<Map<String, dynamic>>()) {
+ final loader = FontLoader(entry['family'] as String);
+ for (final font in (entry['fonts'] as List).cast<Map>()) {
+ loader.addFont(rootBundle.load(font['asset'] as String));
+ }
+ await loader.load();
+ }
+ });
+
+ final boundary = GlobalKey();
+
+ Future<void> pump(
+ WidgetTester tester, {
+ Map<String, dynamic>? load,
+ Brightness brightness = Brightness.dark,
+ Widget? home,
+ }) async {
+ lead = FakeLeadComputers([
+ computer('mac-1', 'Studio', folders: {repo: '/Users/me/games'}),
+ computer('mac-2', 'Air', engines: ['claude']),
+ ]);
+ swarm = FakeSwarm();
+ swarm.routes['/api/super-tabs/list'] = (_) => {
+ 'tabs': [
+ {'id': tab, 'name': 'Personal', 'ownerId': me},
+ ],
+ 'next': null,
+ };
+ swarm.routes['/api/super-tabs/$tab/parts'] = (_) => load ?? personalLoad();
+ swarm.routes['/api/super-tabs/$tab/changes'] = (_) => changes(cursor: 'c2');
+ swarm.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {
+ 'decisions': <Object>[],
+ };
+ swarm.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {
+ 'mentions': <Object>[],
+ };
+ swarm.routes['/api/super-tabs/$tab/leaderboard'] = (_) =>
+ leaderboardData(people: const []);
+ swarm.routes['/api/super-tabs/$tab/conversations/$personalChat/messages'] =
+ (_) => {'messages': <Object>[], 'next': null};
+ swarm.routes['/api/super-tabs/$tab/commands'] = (body) {
+ final command = body!['command'] as Map<String, dynamic>;
+ return switch (command['type']) {
+ 'lead.claim' => {
+ 'result': {'leadStart': 'start'},
+ },
+ _ => {'result': <String, Object>{}},
+ };
+ };
+ final account = ValueNotifier<String?>(me);
+ host = SwarmHost(
+ accountId: () => account.value,
+ account: account,
+ request: swarm.request,
+ upload: refuseSwarmUpload,
+ notices: SilentSystemNotices(),
+ computers: _Computers(lead),
+ features: ExperimentalFeaturesStore(storage: MemoryKeyValueStore())
+ ..value = {PhoneExperiment.swarm},
+ )..foreground = false;
+ addTearDown(host.dispose);
+ final palette = brightness == Brightness.dark
+ ? HarnessPalette.graphite
+ : HarnessPalette.paper;
+ AppTheme.palette.value = palette;
+ AppTheme.brightness.value = brightness;
+ await tester.pumpWidget(
+ RepaintBoundary(
+ key: boundary,
+ child: MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: buildAppTheme(brightness: brightness),
+ builder: (context, child) =>
+ SwarmScope(notifier: host, child: child!),
+ home: Scaffold(
+ body:
+ home ??
+ const SwarmConversationPage(
+ swarmId: tab,
+ conversationId: personalChat,
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ }
+
+ Finder key(String value) => find.byKey(ValueKey(value));
+
+ /// The start's requests answered: a few frames, since Starting… spins
+ /// until the Lead joins and never settles.
+ Future<void> frames(WidgetTester tester) async {
+ for (var i = 0; i < 5; i++) {
+ await tester.pump(const Duration(milliseconds: 50));
+ }
+ }
+
+ List<String> sent() => [for (final c in swarm.commands) c['type'] as String];
+
+ Future<void> capture(WidgetTester tester, String name) async {
+ if (shots == null) return;
+ await tester.runAsync(() async {
+ final image =
+ await (boundary.currentContext!.findRenderObject()!
+ as RenderRepaintBoundary)
+ .toImage(pixelRatio: 3);
+ final png = await image.toByteData(format: ui.ImageByteFormat.png);
+ await File('$shots/lead-start-$name.png')
+ .writeAsBytes(png!.buffer.asUint8List());
+ image.dispose();
+ });
+ }
+
+ testWidgets('an empty Personal project chat shows the Start card with the '
+ 'person\'s computers and signed-in engines', (tester) async {
+ await pump(tester);
+
+ expect(key('swarm-lead-start'), findsOneWidget);
+ expect(find.text('This project has no Lead yet'), findsOneWidget);
+ expect(find.text('No messages yet.'), findsNothing);
+ expect(
+ find.descendant(
+ of: key('swarm-lead-start-machine'),
+ matching: find.text('Studio'),
+ ),
+ findsOneWidget,
+ );
+ expect(key('swarm-lead-start-engine-claude'), findsOneWidget);
+ expect(key('swarm-lead-start-engine-codex'), findsOneWidget);
+ expect(find.text('Folder: /Users/me/games'), findsOneWidget);
+ expect(find.text('Start Lead'), findsOneWidget);
+ expect(
+ find.text('Or send a message below: the Lead reads it when it starts.'),
+ findsOneWidget,
+ );
+
+ // The machine sheet lists both computers; the Air has Claude Code only.
+ await tester.tap(key('swarm-lead-start-machine'));
+ await tester.pumpAndSettle();
+ expect(find.text('Studio'), findsWidgets);
+ await tester.tap(find.text('Air').last);
+ await tester.pumpAndSettle();
+ expect(
+ find.descendant(
+ of: key('swarm-lead-start-machine'),
+ matching: find.text('Air'),
+ ),
+ findsOneWidget,
+ );
+ expect(key('swarm-lead-start-engine-claude'), findsOneWidget);
+ expect(key('swarm-lead-start-engine-codex'), findsNothing);
+ expect(
+ find.text('A new folder in your Harness projects folder'),
+ findsOneWidget,
+ );
+ });
+
+ testWidgets('Start sends Desktop\'s start and shows Starting…', (
+ tester,
+ ) async {
+ await pump(tester);
+ lead.held = Completer();
+ await tester.tap(key('swarm-lead-start-engine-codex'));
+ await tester.pumpAndSettle();
+ await tester.tap(key('swarm-lead-start-button'));
+ await tester.pump();
+ await tester.pump();
+
+ expect(find.text('Starting…'), findsOneWidget);
+ expect(sent(), ['lead.claim']);
+ expect(lead.starts.single.$1, 'mac-1');
+ expect(lead.starts.single.$2.engine, 'codex');
+ // A second tap while it starts starts nothing more.
+ await tester.tap(key('swarm-lead-start-button'));
+ await tester.pump();
+
+ lead.held!.complete();
+ await frames(tester);
+ expect(sent(), ['lead.claim', 'agent.add']);
+ expect(lead.starts, hasLength(1));
+ expect(swarm.commands.last['lead'], isTrue);
+ });
+
+ testWidgets('a failed start shows its reason and Start Lead tries again', (
+ tester,
+ ) async {
+ await pump(tester);
+ lead.failure = const SuperTabFailure(
+ 'CREATE_FAILED',
+ 'Codex isn’t signed in.',
+ );
+ await tester.tap(key('swarm-lead-start-button'));
+ await tester.pumpAndSettle();
+ expect(
+ find.text('Couldn’t start a Lead: Codex isn’t signed in'),
+ findsOneWidget,
+ );
+ expect(find.text('Start Lead'), findsOneWidget);
+
+ lead.failure = null;
+ await tester.tap(key('swarm-lead-start-button'));
+ await frames(tester);
+ expect(lead.starts, hasLength(2));
+ expect(sent(), ['lead.claim', 'lead.claim', 'agent.add']);
+ });
+
+ testWidgets('after a failed join the card keeps the computer the agent '
+ 'started on', (tester) async {
+ await pump(tester);
+ final routes = swarm.routes['/api/super-tabs/$tab/commands']!;
+ swarm.routes['/api/super-tabs/$tab/commands'] = (body) {
+ final command = body!['command'] as Map<String, dynamic>;
+ if (command['type'] == 'agent.add') {
+ throw const SuperTabFailure('UNAVAILABLE', 'The Swarm did not answer.');
+ }
+ return routes(body);
+ };
+ await tester.tap(key('swarm-lead-start-button'));
+ await tester.pumpAndSettle();
+ expect(
+ find.text('Couldn’t start a Lead: The Swarm did not answer'),
+ findsOneWidget,
+ );
+ // Its agent runs on Studio: no other computer is offered until it joins.
+ await tester.tap(key('swarm-lead-start-machine'));
+ await tester.pumpAndSettle();
+ expect(find.text('Air'), findsNothing);
+ });
+
+ testWidgets('no computer online says why and offers no Start', (
+ tester,
+ ) async {
+ await pump(tester);
+ lead.leadComputers = [];
+ // The card reads the computers as it draws.
+ (host.computers! as ChangeNotifier).notifyListeners();
+ await tester.pumpAndSettle();
+ expect(
+ find.text('Can’t start a Lead: none of your computers is online'),
+ findsOneWidget,
+ );
+ expect(key('swarm-lead-start-button'), findsNothing);
+ });
+
+ testWidgets('a Team Swarm\'s project chat shows no card', (tester) async {
+ await pump(tester, load: personalLoad(name: 'Phone Swarm'));
+ expect(key('swarm-lead-start'), findsNothing);
+ expect(find.text('No messages yet.'), findsOneWidget);
+ });
+
+ testWidgets('a project with a Lead shows no card', (tester) async {
+ await pump(tester, load: personalLoad(leadId: 'agent-lead'));
+ expect(key('swarm-lead-start'), findsNothing);
+ });
+
+ testWidgets('screenshots of the card in both phone themes', (tester) async {
+ if (shots == null) return;
+ await tester.binding.setSurfaceSize(const Size(390, 844));
+ tester.view.physicalSize = const Size(390 * 3, 844 * 3);
+ tester.view.devicePixelRatio = 3;
+ addTearDown(tester.view.reset);
+ for (final brightness in Brightness.values) {
+ // As the person opens it: the project, its chat filling the screen.
+ await pump(
+ tester,
+ brightness: brightness,
+ home: SwarmProjectPage(swarmId: tab, projectId: personal),
+ );
+ expect(key('swarm-lead-start'), findsOneWidget);
+ await capture(tester, 'ready-${brightness.name}');
+ lead.held = Completer();
+ await tester.tap(key('swarm-lead-start-button'));
+ await tester.pump();
+ await tester.pump();
+ await capture(tester, 'starting-${brightness.name}');
+ lead.failure = const SuperTabFailure(
+ 'CREATE_FAILED',
+ 'Codex isn’t signed in on Studio.',
+ );
+ lead.held!.complete();
+ await tester.pumpAndSettle();
+ await capture(tester, 'failed-${brightness.name}');
+ await tester.pumpWidget(const SizedBox.shrink());
+ }
+ });
+}
diff --git a/mobile/test/swarm/swarm_lead_start_fixture.dart b/mobile/test/swarm/swarm_lead_start_fixture.dart
new file mode 100644
index 000000000..442e08866
--- /dev/null
+++ b/mobile/test/swarm/swarm_lead_start_fixture.dart
@@ -0,0 +1,97 @@
+import 'dart:async';
+
+import 'package:flutter/foundation.dart';
+
+import 'package:harness_mobile/swarm/swarm_lead_start.dart';
+import 'package:harness_mobile/swarm/swarm_request.dart';
+
+import 'swarm_fixture.dart';
+
+/// A Personal Swarm and the person's computers, for the phone's Start Lead
+/// card (task #2941).
+
+/// The person's computers a Lead can start on, as a test scripts them: each
+/// start is remembered, and answers [started] or throws [failure].
+class FakeLeadComputers extends ChangeNotifier implements SwarmLeadComputers {
+ FakeLeadComputers(this.leadComputers);
+
+ @override
+ List<SwarmLeadComputer> leadComputers;
+
+ final starts = <(String, SwarmLeadLaunch)>[];
+ SuperTabFailure? failure;
+
+ /// Holds a start until completed.
+ Completer<void>? held;
+
+ @override
+ Future<SwarmLeadStarted> startLead(
+ String machineId,
+ SwarmLeadLaunch launch,
+ ) async {
+ starts.add((machineId, launch));
+ await held?.future;
+ if (failure case final failure?) throw failure;
+ return (
+ harnessId: 'harness-new',
+ cwd: launch.folder ?? '/Users/me/Harness/Games-Lead',
+ remote: launch.folder == null ? null : 'github.com/acme/games',
+ );
+ }
+}
+
+/// The repo the Personal project is made for, and that project's id as every
+/// computer of the person's makes it (Desktop's personalProjectOperation).
+const repo = 'github.com/acme/games';
+final personal = swarmPersonalProjectOperation(repo);
+const personalChat = 'project-personal';
+
+SwarmLeadComputer computer(
+ String id,
+ String name, {
+ List<String> engines = const ['claude', 'codex'],
+ Map<String, String> folders = const {},
+}) => (id: id, name: name, engines: engines, folders: folders);
+
+/// A Swarm read with one project whose chat has [leadId] as its Lead, or none.
+Map<String, dynamic> personalLoad({
+ String name = 'Personal',
+ String? leadId,
+ List<String> people = const [me],
+ String role = 'owner',
+}) => {
+ ...firstLoad(
+ head: headData(
+ name: name,
+ projects: [
+ {
+ 'id': personal,
+ 'name': 'games',
+ 'ownerId': me,
+ 'leadConversationId': personalChat,
+ 'visibility': 'private',
+ 'members': <Object>[],
+ 'updateMinutes': 5,
+ 'skillMode': 'default',
+ },
+ ],
+ ),
+ agents: [if (leadId != null) agent(leadId, name: 'Lead')],
+ groups: [
+ {
+ ...groupData(
+ personalChat,
+ title: 'games',
+ agentIds: [?leadId],
+ leadId: leadId,
+ ),
+ 'projectId': personal,
+ },
+ {...groupData('g-task', title: 'Fix it'), 'projectId': personal},
+ ],
+ ),
+ 'members': [
+ for (final id in people)
+ part(id, 1, person(id, role: id == me ? role : 'collaborator')),
+ ],
+};
diff --git a/mobile/test/swarm/swarm_lead_start_test.dart b/mobile/test/swarm/swarm_lead_start_test.dart
new file mode 100644
index 000000000..e3d015daa
--- /dev/null
+++ b/mobile/test/swarm/swarm_lead_start_test.dart
@@ -0,0 +1,338 @@
+import 'dart:async';
+
+import 'package:flutter_test/flutter_test.dart';
+
+import 'package:harness_mobile/swarm/model.dart';
+import 'package:harness_mobile/swarm/swarm_lead_start.dart';
+import 'package:harness_mobile/swarm/swarm_reader.dart';
+import 'package:harness_mobile/swarm/swarm_request.dart';
+
+import 'swarm_fixture.dart';
+import 'swarm_lead_start_fixture.dart';
+
+void main() {
+ late FakeSwarm swarm;
+ late SwarmReader reader;
+ late FakeLeadComputers computers;
+
+ /// What lead.claim and agent.add answer, by command type.
+ late Map<String, FutureOr<Object?> Function(Map<String, dynamic>)> answers;
+
+ Future<void> open([Map<String, dynamic>? load]) async {
+ swarm = FakeSwarm();
+ answers = {
+ 'lead.claim': (_) => {
+ 'result': {'leadStart': 'start'},
+ },
+ 'agent.add': (_) => {'result': <String, Object>{}},
+ };
+ swarm.routes['/api/super-tabs/$tab/parts'] = (_) => load ?? personalLoad();
+ swarm.routes['/api/super-tabs/$tab/changes'] = (_) => changes(cursor: 'c2');
+ swarm.routes['/api/super-tabs/$tab/commands'] = (body) {
+ final command = body!['command'] as Map<String, dynamic>;
+ return answers[command['type']]!(command);
+ };
+ reader = SwarmReader(tabId: tab, accountId: me, request: swarm.request);
+ addTearDown(reader.dispose);
+ await reader.refresh();
+ computers = FakeLeadComputers([
+ computer('mac-1', 'Studio', folders: {repo: '/Users/me/games'}),
+ computer('mac-2', 'Air', engines: ['claude']),
+ ]);
+ }
+
+ List<String> sent() => [for (final c in swarm.commands) c['type'] as String];
+
+ test('wants a Lead only in a Personal Swarm\'s empty project chat', () async {
+ await open();
+ expect(swarmWantsLeadStart(reader, personalChat), isTrue);
+ expect(swarmWantsLeadStart(reader, 'g-task'), isFalse);
+
+ await open(personalLoad(leadId: 'agent-lead'));
+ expect(swarmWantsLeadStart(reader, personalChat), isFalse);
+
+ await open(personalLoad(name: 'Phone Swarm'));
+ expect(swarmWantsLeadStart(reader, personalChat), isFalse);
+
+ await open(personalLoad(people: [me, 'person-dee']));
+ expect(swarmWantsLeadStart(reader, personalChat), isFalse);
+
+ await open(personalLoad(role: 'viewer'));
+ expect(swarmWantsLeadStart(reader, personalChat), isFalse);
+ });
+
+ test('a remote is one string on every computer, as on Desktop', () {
+ for (final form in [
+ '[email protected]:Acme/Api.git',
+ 'https://github.com/acme/api',
+ 'https://user:[email protected]/acme/api',
+ 'github.com/acme/api/',
+ ]) {
+ expect(swarmNormalizedRemote(form), 'github.com/acme/api', reason: form);
+ }
+ expect(swarmNormalizedRemote('/srv/api'), isNull);
+ expect(swarmNormalizedRemote(null), isNull);
+ // Desktop's id for this repo's project (personal_projects.dart).
+ expect(
+ swarmPersonalProjectOperation('github.com/acme/api'),
+ 'personal-repo-e1dcaa3496b93562cbcd84ea',
+ );
+ });
+
+ test('the plan is the repo\'s folder on the picked computer, else a new '
+ 'one', () async {
+ await open();
+ final first = swarmLeadPlan(reader, computers, personalChat);
+ expect(first, (
+ machineId: 'mac-1',
+ engine: 'claude',
+ folder: '/Users/me/games',
+ ));
+ final air = swarmLeadPlan(
+ reader,
+ computers,
+ personalChat,
+ machineId: 'mac-2',
+ );
+ expect(air, (machineId: 'mac-2', engine: 'claude', folder: null));
+ expect(
+ swarmLeadPlan(reader, computers, personalChat, engine: 'codex').engine,
+ 'codex',
+ );
+ });
+
+ test('the plan says why there is nothing to start on', () async {
+ await open();
+ computers.leadComputers = [];
+ expect(
+ () => swarmLeadPlan(reader, computers, personalChat),
+ throwsA(
+ isA<SuperTabFailure>().having(
+ (f) => f.message,
+ 'message',
+ 'none of your computers is online',
+ ),
+ ),
+ );
+ computers.leadComputers = [computer('mac-1', 'Studio', engines: [])];
+ expect(
+ () => swarmLeadPlan(reader, computers, personalChat),
+ throwsA(
+ isA<SuperTabFailure>().having(
+ (f) => f.message,
+ 'message',
+ 'Claude Code and Codex aren’t signed in on Studio',
+ ),
+ ),
+ );
+ });
+
+ test('start claims, starts on the computer, then joins it as Lead', () async {
+ await open();
+ await SwarmLeadStarter.of(reader).start(
+ reader,
+ computers,
+ personalChat,
+ machineId: 'mac-1',
+ engine: 'codex',
+ );
+
+ expect(sent(), ['lead.claim', 'agent.add']);
+ expect(swarm.commands.first, {
+ 'type': 'lead.claim',
+ 'projectId': personal,
+ 'machineId': 'mac-1',
+ });
+ final (machine, launch) = computers.starts.single;
+ expect(machine, 'mac-1');
+ expect(launch.engine, 'codex');
+ expect(launch.folder, '/Users/me/games');
+ expect(launch.projectName, 'games');
+ expect(launch.skillMode, 'default');
+ expect(
+ launch.prompt,
+ swarmLeadLaunchPrompt(tabId: tab, conversationId: personalChat),
+ );
+ expect(
+ launch.prompt,
+ startsWith('Harness Swarm agent. You are the Lead. '),
+ );
+ final join = swarm.commands.last;
+ expect(join['conversationId'], personalChat);
+ expect(join['machineId'], 'mac-1');
+ expect(join['harnessId'], 'harness-new');
+ expect(join['name'], 'Lead');
+ expect(join['lead'], isTrue);
+ expect(join['project'], {
+ 'cwd': '/Users/me/games',
+ 'repositoryUrl': 'https://github.com/acme/games',
+ });
+ expect(superTabMap(join['configuration'])['engine'], 'codex');
+ expect(
+ SwarmLeadStarter.of(reader).statusOf(personalChat)?.failed,
+ isFalse,
+ reason: 'starting until the chat reads its Lead',
+ );
+ });
+
+ test('two taps make one claim and one start', () async {
+ await open();
+ computers.held = Completer();
+ final starter = SwarmLeadStarter.of(reader);
+ final first = starter.start(
+ reader,
+ computers,
+ personalChat,
+ machineId: 'mac-1',
+ engine: 'claude',
+ );
+ await starter.start(
+ reader,
+ computers,
+ personalChat,
+ machineId: 'mac-1',
+ engine: 'claude',
+ );
+ computers.held!.complete();
+ await first;
+ expect(sent(), ['lead.claim', 'agent.add']);
+ expect(computers.starts, hasLength(1));
+ });
+
+ test('a claim another machine holds starts nothing here and shows '
+ 'starting', () async {
+ await open();
+ answers['lead.claim'] = (_) => {
+ 'result': {'leadStart': 'waiting'},
+ };
+ final starter = SwarmLeadStarter.of(reader);
+ await starter.start(
+ reader,
+ computers,
+ personalChat,
+ machineId: 'mac-1',
+ engine: 'claude',
+ );
+ expect(sent(), ['lead.claim']);
+ expect(computers.starts, isEmpty);
+ expect(starter.statusOf(personalChat)?.failed, isFalse);
+ });
+
+ test('a failure shows its reason, and Start again joins the agent already '
+ 'started', () async {
+ await open();
+ answers['agent.add'] = (_) => throw const SuperTabFailure(
+ 'LEAD_EXISTS',
+ 'This project already has its Lead.',
+ );
+ final starter = SwarmLeadStarter.of(reader);
+ await starter.start(
+ reader,
+ computers,
+ personalChat,
+ machineId: 'mac-1',
+ engine: 'claude',
+ );
+ expect(
+ starter.statusOf(personalChat)?.reason,
+ 'This project already has its Lead',
+ );
+
+ answers['agent.add'] = (_) => {'result': <String, Object>{}};
+ await starter.start(
+ reader,
+ computers,
+ personalChat,
+ machineId: 'mac-1',
+ engine: 'claude',
+ );
+ expect(sent(), ['lead.claim', 'agent.add', 'lead.claim', 'agent.add']);
+ expect(computers.starts, hasLength(1));
+ expect(swarm.commands.last['harnessId'], 'harness-new');
+ expect(starter.statusOf(personalChat)?.failed, isFalse);
+ });
+
+ test('a computer that could not start it says why, and Start tries '
+ 'again', () async {
+ await open();
+ computers.failure = const SuperTabFailure(
+ 'CREATE_FAILED',
+ 'Codex isn’t signed in.',
+ );
+ final starter = SwarmLeadStarter.of(reader);
+ await starter.start(
+ reader,
+ computers,
+ personalChat,
+ machineId: 'mac-1',
+ engine: 'codex',
+ );
+ expect(starter.statusOf(personalChat)?.reason, 'Codex isn’t signed in');
+ expect(sent(), ['lead.claim']);
+
+ computers.failure = null;
+ await starter.start(
+ reader,
+ computers,
+ personalChat,
+ machineId: 'mac-1',
+ engine: 'codex',
+ );
+ expect(computers.starts, hasLength(2));
+ expect(sent(), ['lead.claim', 'lead.claim', 'agent.add']);
+ });
+ test('Start again after a failed join claims the kept computer and joins '
+ 'its agent, whatever is picked since', () async {
+ await open();
+ // The server holds one claim: another computer's claim waits (backend
+ // commands.ts lead.claim).
+ String? held;
+ answers['lead.claim'] = (command) {
+ final machine = command['machineId'] as String;
+ if (held != null && held != machine) {
+ return {
+ 'result': {'leadStart': 'waiting'},
+ };
+ }
+ held = machine;
+ return {
+ 'result': {'leadStart': 'start'},
+ };
+ };
+ answers['agent.add'] = (_) =>
+ throw const SuperTabFailure('UNAVAILABLE', 'The Swarm did not answer.');
+ final starter = SwarmLeadStarter.of(reader);
+ await starter.start(
+ reader,
+ computers,
+ personalChat,
+ machineId: 'mac-1',
+ engine: 'codex',
+ );
+ expect(starter.kept(personalChat), (machineId: 'mac-1', engine: 'codex'));
+
+ answers['agent.add'] = (_) => {'result': <String, Object>{}};
+ await starter.start(
+ reader,
+ computers,
+ personalChat,
+ machineId: 'mac-2',
+ engine: 'claude',
+ );
+ expect(
+ [for (final c in swarm.commands) (c['type'], c['machineId'])],
+ [
+ ('lead.claim', 'mac-1'),
+ ('agent.add', 'mac-1'),
+ ('lead.claim', 'mac-1'),
+ ('agent.add', 'mac-1'),
+ ],
+ );
+ expect(computers.starts, hasLength(1));
+ expect(
+ superTabMap(swarm.commands.last['configuration'])['engine'],
+ 'codex',
+ );
+ expect(starter.kept(personalChat), isNull);
+ });
+}