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.

Swarm v3: join with your agent and create Regular or PM agents (#3448)

harness-for-autonomous[bot]f31f3ac57550
diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dart
index d44a3844b..0d6d64c5b 100644
--- a/desktop/lib/screens/swarm_screen.dart
+++ b/desktop/lib/screens/swarm_screen.dart
@@ -87,8 +87,6 @@ import '../super_tabs/launch.dart';
import '../super_tabs/message_link.dart' show swarmMessageLinkInbox;
import '../super_tabs/buddy_chat.dart' show countText;
import '../super_tabs/buddy_chat_shortcut.dart';
-import '../super_tabs/join_machine.dart';
-import '../super_tabs/join_machine_note.dart';
import '../super_tabs/team_account_setup.dart';
import '../super_tabs/workspace.dart';
import '../super_tabs/quick_switcher.dart';
@@ -331,7 +329,6 @@ class _SwarmScreenState extends State<SwarmScreen> {
StreamSubscription<void>? _modelsRequests;
StreamSubscription<String>? _superTabClosures;
StreamSubscription<String>? _teamSetupAsks;
- StreamSubscription<SwarmJoinedMachine>? _joinedMachines;
// The one Swarm notice: whether it exists (queued or shown), whether it
// is on screen, and the closed tab its Reopen restores.
int _superTabNoticeSerial = 0;
@@ -913,10 +910,6 @@ class _SwarmScreenState extends State<SwarmScreen> {
_teamSetupAsks = app.teamSetupAsks.listen((_) {
if (mounted) unawaited(showTeamAccountSetup(context, app, asked: true));
});
- // This computer, added to a Swarm as its person joined it (super_tabs/join_machine.dart).
- _joinedMachines = app.joinedMachines.listen((note) {
- if (mounted) showJoinedMachineNote(context, app.superTabs.open, note);
- });
if (!kUnderTest) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
@@ -1074,7 +1067,6 @@ class _SwarmScreenState extends State<SwarmScreen> {
_modelsRequests?.cancel();
_superTabClosures?.cancel();
_teamSetupAsks?.cancel();
- _joinedMachines?.cancel();
_keymap.removeListener(_keymapChanged);
_defaultKeymap.dispose();
grid.AppTheme.palette.removeListener(_paletteChanged);
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index 39b18f53d..de249b470 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -2765,12 +2765,6 @@ class AppNotifier extends ChangeNotifier {
}
}
- final StreamController<SwarmJoinedMachine> _joinedMachines =
- StreamController<SwarmJoinedMachine>.broadcast();
-
- /// This computer, added to a Swarm as its person joined it
- /// ([addMachineOnJoin]): the screen shows a note, with Pause and Remove.
- Stream<SwarmJoinedMachine> get joinedMachines => _joinedMachines.stream;
final _joinAdding = <String>{};
/// The Swarms the join's add already ran or was decided for, per account on
@@ -2812,17 +2806,15 @@ class AppNotifier extends ChangeNotifier {
SwarmJoinAccountRequest? get joinAccountRequest =>
_joinAccountRequests.where((r) => !r.answered).firstOrNull;
- /// Adds a new collaborator's computer, using the choice made on the join
- /// surface or asking before contribution. Existing members/viewers and
- /// systems without local Team accounts are left alone.
+ /// Offers a new collaborator their Buddy after a successful membership join.
+ /// Existing members and viewers never enter the bring-agent flow here.
Future<void> addMachineOnJoin(
String tabId, {
required String role,
bool alreadyMember = false,
- bool? ownAccount,
}) async {
if (alreadyMember || role != 'collaborator') return;
- await _addMachineToSwarm(tabId, joined: true, ownAccount: ownAccount);
+ await _offerBringAgent(tabId);
}
/// Swarm discovery's list ([listed]), however each was joined: a domain
@@ -2840,13 +2832,17 @@ class AppNotifier extends ChangeNotifier {
try {
final fresh = await record.fresh(account, listed, knownHere: knownHere);
for (final tabId in fresh) {
- if (_disposed ||
- currentUser?.id != account ||
- _teamAccountHere() == null) {
+ if (_disposed || currentUser?.id != account) {
return;
}
if (_joinPassed.contains('$account/$tabId')) continue;
- await _addMachineToSwarm(tabId, joined: false);
+ // Discovery already knows the owner; only new collaborators need
+ // the offer, without opening an owner's other Swarms to find out.
+ if (superTabs.ownerOf(tabId) == account) {
+ _joinPassed.add('$account/$tabId');
+ continue;
+ }
+ await _offerBringAgent(tabId);
}
} catch (error) {
appLog.info('super-tabs', 'joined Swarms not checked: $error');
@@ -2856,120 +2852,68 @@ class AppNotifier extends ChangeNotifier {
}();
}
- /// The join's add for one Swarm this account is in. The person's role is
- /// read from the Swarm itself: a viewer's Swarm is neither added nor
- /// recorded, so it is asked about again; an owner's is recorded and left.
- /// A step that fails for a collaborator shows them a note saying what to do
- /// (task #3160). [joined]: they joined it at this computer just now, so
- /// they are known to be one before the Swarm is read; a Swarm only listed
- /// that cannot be read says nothing yet, since they may be a viewer, and is
- /// asked about again on the next discovery.
- Future<void> _addMachineToSwarm(
- String tabId, {
- required bool joined,
- bool? ownAccount,
- }) async {
- final here = _teamAccountHere();
+ /// Offers the new collaborator their own Buddy on this computer. Discovery
+ /// remembers the offer so reconnects do not reopen a dismissed prompt.
+ Future<void> _offerBringAgent(String tabId) async {
final accountId = currentUser?.id;
- if (here == null || accountId == null || !_joinAdding.add(tabId)) return;
+ if (accountId == null || !_joinAdding.add(tabId)) return;
bool current() =>
!_disposed &&
status == AppStatus.authenticated &&
currentUser?.id == accountId;
- final machineName = stateOf(here)?.machine.displayName ?? 'This computer';
- // Opened only for this add: let go after it, unless the person went to it
- // meanwhile, so it does not keep polling unseen (review of #3115).
final openedHere = superTabs.peek(tabId) == null;
- var collaborator = joined;
- void failed(String problem) {
- if (!collaborator || !current()) return;
- _joinedMachines.add(
- SwarmJoinedMachine(
- tabId: tabId,
- swarmName: superTabName(tabId) ?? 'the Swarm',
- machineId: here,
- machineName: machineName,
- problem: problem,
- ),
- );
- }
-
try {
final c = await superTabs.open(tabId);
if (!current()) return;
- await c.refresh();
+ // Reuse the state already read for an open Swarm. Discovery must not
+ // add a second read when the connection comes back.
+ if (c.snapshot == null) await c.refresh();
if (!current()) return;
final snapshot = c.snapshot;
if (snapshot == null) {
- appLog.info('super-tabs', 'machine not added on join: unread Swarm');
- if (!collaborator) _joinPassed.add('$accountId/$tabId');
- failed('Could not reach the Swarm. Add this computer from Machines.');
+ appLog.info('super-tabs', 'bring-agent join deferred: org unreadable');
return;
}
final role = snapshot.people
.where((p) => p.id == accountId)
.firstOrNull
?.role;
- if (role == null || role == 'viewer') {
+ if (role != 'collaborator') {
_joinPassed.add('$accountId/$tabId');
return;
}
- collaborator = role == 'collaborator';
await _joinRecord?.mark(accountId, tabId);
- if (!collaborator) return;
- if (!snapshot.teamAccounts ||
- !c.canWrite ||
- snapshot.machines.any((m) => m['machineId'] == here) ||
- snapshot.removedMachines.any((id) => sameMachineId(id, here))) {
+ if (!c.canWrite ||
+ snapshot.agents.any(
+ (agent) => agent.isMainBuddy && agent.buddyOf == accountId,
+ )) {
return;
}
- if (ownAccount == null) {
- final request = SwarmJoinAccountRequest(snapshot.name, accountId);
- _joinAccountRequests.add(request);
- notifyListeners();
- try {
- ownAccount = await request.answer.timeout(
- const Duration(minutes: 15),
- onTimeout: () {
- appLog.info('super-tabs', 'join account choice expired');
- return null;
- },
- );
- } finally {
- request.complete(null);
- _joinAccountRequests.remove(request);
- if (!_disposed) notifyListeners();
- }
- if (!current()) return;
- if (ownAccount == null) {
- failed('Add it from Machines.');
- return;
- }
- }
- final note =
- await SwarmJoinMachine(
- machineRequest: superTabMachineRequest,
- readResources: readMachineResources,
- wake: wakeSuperTabHost,
- ).add(
- c,
- machineId: here,
- machineName: machineName,
- current: current,
- ownAccount: ownAccount,
- );
- if (note == null || !current()) return;
- _joinedMachines.add(note);
- // Joined by the person at this computer: the system asks once for the
- // Harness Team account (cli/src/team/autoSetup.ts).
- if (!note.added || ownAccount) return;
- if (!await offerTeamAccount('join', tabId: tabId) && current()) {
- _joinedMachines.add(note.withoutTeamOffer());
+ final request = SwarmJoinAccountRequest(
+ snapshot.name,
+ accountId,
+ tabId: tabId,
+ );
+ _joinAccountRequests.add(request);
+ notifyListeners();
+ try {
+ await request.answer.timeout(
+ const Duration(minutes: 15),
+ onTimeout: () {
+ appLog.info('super-tabs', 'bring-agent join prompt expired');
+ return null;
+ },
+ );
+ } finally {
+ request.complete(null);
+ _joinAccountRequests.remove(request);
+ if (!_disposed) notifyListeners();
}
- } catch (error) {
- appLog.info('super-tabs', 'machine not added on join: $error');
- if (!collaborator) _joinPassed.add('$accountId/$tabId');
- failed('Could not add this computer. Add it from Machines.');
+ } catch (_) {
+ appLog.info(
+ 'super-tabs',
+ 'bring-agent join deferred: org request failed',
+ );
} finally {
_joinAdding.remove(tabId);
if (openedHere &&
@@ -15758,25 +15702,15 @@ class AppNotifier extends ChangeNotifier {
}
/// What every connected REMOTE machine's agent accounts have spent, asked in
- /// parallel and read there with that machine's own credentials (`usage_read`).
- ///
- /// This computer's own accounts are not asked here — the app reads those
- /// directly, the Keychain included. A remote machine may be signed in to a
- /// different subscription, and a rate limit belongs to an account rather than
- /// a computer, so the only honest way to show that one is to ask the machine
- /// that holds it.
- ///
- /// ⚠️ **A machine whose CLI predates `usage_read` does not refuse it — it goes
- /// silent.** The frame reaches it as an E2EE envelope it does not know to
- /// open, so the requestId inside is never read and nothing replies. That is a
- /// timeout, not an `UNSUPPORTED`, which is why this asks with a short one and
- /// treats every failure alike: a machine that cannot say has nothing to add,
- /// and it must never hold up the figures of the ones that can.
+ /// through their own CLI rate-limit reports. This computer uses the same
+ /// transport: Desktop never opens a vendor credential or usage endpoint.
Future<List<MachineUsage>> readRemoteUsage() async {
final remotes = [
for (final machine in machineStates.values)
- if (!machine.isLocalMachine &&
- machine.connectionStatus == ConnectionStatus.connected)
+ if (machine.connectionStatus == ConnectionStatus.connected &&
+ !machine.needsLink &&
+ !machine.belongsToOtherAccount &&
+ !machine.machine.isTeamAccount)
machine,
];
final answers = await Future.wait([
@@ -16010,6 +15944,7 @@ class AppNotifier extends ChangeNotifier {
if (readings.isEmpty) return null;
return MachineUsage(
machineName: machine.machine.displayName,
+ isLocal: machine.isLocalMachine,
readings: readings,
);
} catch (_) {
@@ -24357,7 +24292,6 @@ class AppNotifier extends ChangeNotifier {
request.complete(null);
}
unawaited(_teamSetupAsks.close());
- unawaited(_joinedMachines.close());
super.dispose();
}
}
diff --git a/desktop/lib/super_tabs/join/agent_dialog.dart b/desktop/lib/super_tabs/join/agent_dialog.dart
new file mode 100644
index 000000000..75e7f6624
--- /dev/null
+++ b/desktop/lib/super_tabs/join/agent_dialog.dart
@@ -0,0 +1,214 @@
+import 'package:flutter/material.dart';
+
+import '../../shared/widgets/app_select_field.dart';
+import '../../widgets/desktop_chrome.dart';
+import '../../widgets/desktop_prompt_surface.dart';
+import '../controller.dart' show superTabOperationId;
+import 'agent_launcher.dart';
+
+/// Starts only through the authenticated owner's daemon adapter. The dialog
+/// never reads CLI settings, credentials or another machine's login.
+typedef SwarmAgentCreate = Future<Map<String, dynamic>> Function(
+ String engine,
+ String kind,
+ String? projectName,
+ String operationId,
+);
+
+class SwarmAgentDialog extends StatefulWidget {
+ const SwarmAgentDialog({
+ super.key,
+ required this.engines,
+ required this.create,
+ required this.isCurrent,
+ this.bringing = false,
+ });
+ final List<String> engines;
+ final SwarmAgentCreate create;
+ final bool Function() isCurrent;
+ final bool bringing;
+
+ @override
+ State<SwarmAgentDialog> createState() => _SwarmAgentDialogState();
+}
+
+class _SwarmAgentDialogState extends State<SwarmAgentDialog> {
+ final _project = TextEditingController();
+ final _operation = superTabOperationId();
+ late String? _engine = widget.engines.firstOrNull;
+ String _kind = 'regular';
+ bool _busy = false, _submitted = false, _invalid = false;
+ String? _error;
+ String get _selectedKind => widget.bringing ? 'buddy' : _kind;
+
+ Future<void> _submit() async {
+ if (_busy || _invalid || _engine == null) return;
+ if (!widget.isCurrent()) {
+ setState(() {
+ _invalid = true;
+ _error = 'Your account changed. Close this dialog and try again.';
+ });
+ return;
+ }
+ setState(() {
+ _busy = true;
+ _submitted = true;
+ _error = null;
+ });
+ try {
+ final result = await widget
+ .create(
+ _engine!,
+ _selectedKind,
+ _selectedKind == 'pm' ? _project.text.trim() : null,
+ _operation,
+ )
+ .timeout(const Duration(seconds: 80));
+ if (!mounted) return;
+ if (!widget.isCurrent()) {
+ setState(() {
+ _invalid = true;
+ _error = 'Your account changed. Close this dialog and try again.';
+ });
+ return;
+ }
+ if (result['agentId'] is! String && result['startId'] is! String) {
+ throw const FormatException('Agent start not acknowledged');
+ }
+ Navigator.pop(context, result);
+ } catch (failure) {
+ if (mounted) {
+ setState(
+ () => _error = failure is SwarmAgentLaunchFailure ? failure.message : 'Could not start your agent. Check this computer’s connection and try again.',
+ );
+ }
+ } finally {
+ if (mounted) setState(() => _busy = false);
+ }
+ }
+
+ @override
+ void dispose() {
+ _project.dispose();
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final enabled =
+ !_busy &&
+ !_invalid &&
+ _engine != null &&
+ (_selectedKind != 'pm' || _project.text.trim().isNotEmpty);
+ return DesktopPromptSurface(
+ body: DesktopPromptScrollBody(
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ DesktopDialogHeader(
+ title: widget.bringing ? 'Bring your agent' : 'New agent',
+ padding: EdgeInsets.zero,
+ onClose: () => Navigator.pop(context),
+ ),
+ const SizedBox(height: 16),
+ Text(
+ widget.bringing
+ ? 'Choose the agent you use on this computer. It becomes your Buddy.'
+ : 'Regular agents work across projects. A PM starts and leads a project.',
+ style: DesktopChrome.text(),
+ ),
+ const SizedBox(height: 16),
+ if (!widget.bringing) ...[
+ SegmentedButton<String>(
+ style: ButtonStyle(
+ foregroundColor: WidgetStateProperty.resolveWith(
+ (states) => states.contains(WidgetState.selected)
+ ? DesktopChrome.onSelection
+ : DesktopChrome.foreground,
+ ),
+ ),
+ segments: const [
+ ButtonSegment(value: 'regular', label: Text('Regular')),
+ ButtonSegment(value: 'pm', label: Text('PM')),
+ ],
+ selected: {_kind},
+ onSelectionChanged: _submitted
+ ? null
+ : (values) => setState(() => _kind = values.single),
+ ),
+ const SizedBox(height: 16),
+ ],
+ if (widget.engines.isEmpty)
+ Text(
+ 'Install Claude Code or Codex on this computer, then open this dialog again.',
+ style: DesktopChrome.text(),
+ )
+ else
+ AppSelectField<String>(
+ key: const Key('swarm-agent-engine'),
+ value: _engine!,
+ semanticLabel: 'Engine',
+ options: [
+ for (final e in widget.engines)
+ SelectOption(
+ value: e,
+ label: e == 'claude'
+ ? 'Claude Code'
+ : e == 'codex'
+ ? 'Codex'
+ : e,
+ ),
+ ],
+ onChanged: (value) {
+ if (!_submitted) setState(() => _engine = value);
+ },
+ ),
+ if (_selectedKind == 'pm') ...[
+ const SizedBox(height: 16),
+ TextField(
+ key: const Key('swarm-agent-project'),
+ controller: _project,
+ enabled: !_submitted,
+ maxLength: 120,
+ decoration: const InputDecoration(labelText: 'Project name'),
+ onChanged: (_) => setState(() {}),
+ onSubmitted: (_) {
+ if (enabled) _submit();
+ },
+ ),
+ ],
+ const SizedBox(height: 8),
+ Text(
+ 'On this computer, with your own agent settings.',
+ style: DesktopChrome.metadata(),
+ ),
+ if (_error != null) ...[
+ const SizedBox(height: 12),
+ Text(
+ _error!,
+ key: const Key('swarm-agent-error'),
+ style: DesktopChrome.text(),
+ ),
+ ],
+ ],
+ ),
+ ),
+ actions: [
+ FilledButton(
+ key: const Key('swarm-agent-submit'),
+ onPressed: enabled ? _submit : null,
+ child: Text(
+ _busy
+ ? 'Starting…'
+ : _error != null && !_invalid
+ ? 'Retry'
+ : widget.bringing
+ ? 'Bring agent'
+ : 'Create agent',
+ ),
+ ),
+ ],
+ );
+ }
+}
diff --git a/desktop/lib/super_tabs/join/agent_launcher.dart b/desktop/lib/super_tabs/join/agent_launcher.dart
new file mode 100644
index 000000000..aa731f307
--- /dev/null
+++ b/desktop/lib/super_tabs/join/agent_launcher.dart
@@ -0,0 +1,94 @@
+/// Safe presentation text for a refused own-agent start. Never carries a raw
+/// daemon or network error, which can contain personal paths or content.
+class SwarmAgentLaunchFailure implements Exception {
+ const SwarmAgentLaunchFailure(this.message);
+ final String message;
+}
+
+/// One dialog's start transaction. Preparation and machine admission are kept
+/// across retries; each server mutation has its own stable operation receipt.
+class SwarmAgentLauncher {
+ SwarmAgentLauncher({
+ required this.machineId,
+ required this.machineName,
+ required bool inSwarm,
+ required this.isCurrent,
+ required this.prepare,
+ required this.command,
+ }) : _admitted = inSwarm;
+
+ final String machineId, machineName;
+ final bool Function() isCurrent;
+ final Future<Map<String, dynamic>> Function(String operationId) prepare;
+ final Future<Map<String, dynamic>> Function(
+ Map<String, dynamic> command,
+ String operationId,
+ )
+ command;
+ bool _admitted;
+ Map<String, dynamic>? _prepared;
+
+ void _guard() {
+ if (!isCurrent()) {
+ throw const SwarmAgentLaunchFailure(
+ 'Your account changed. Close this dialog and try again.',
+ );
+ }
+ }
+
+ Future<Map<String, dynamic>> create(
+ String engine,
+ String kind,
+ String? projectName,
+ String operationId,
+ ) async {
+ _guard();
+ if (!const {'buddy', 'regular', 'pm'}.contains(kind) ||
+ (kind == 'pm' && (projectName?.trim().isEmpty ?? true))) {
+ throw const SwarmAgentLaunchFailure('Enter a project name for your PM.');
+ }
+ if (!_admitted) {
+ _prepared ??= await prepare('$operationId-prepare')
+ .timeout(const Duration(seconds: 25));
+ _guard();
+ _prepared = {
+ ..._prepared!,
+ 'engines': [
+ for (final engine in _prepared!['engines'] as List? ?? const [])
+ if (engine == 'claude' || engine == 'codex') engine,
+ ],
+ };
+ if (kind != 'buddy') {
+ await command({
+ 'type': 'machine.contribute',
+ 'machineId': machineId,
+ 'name': machineName,
+ 'cwd': _prepared!['cwd'],
+ 'scope': 'swarm',
+ 'engines': _prepared!['engines'],
+ 'maxAgents': 16,
+ 'agents': 'memory',
+ // Listing this computer must never authorize a teammate to use
+ // its person's login. Keep the existing owner-project restriction.
+ 'teamAccountOnly': true,
+ }, '$operationId-machine').timeout(const Duration(seconds: 25));
+ _admitted = true;
+ }
+ }
+ _guard();
+ final result = await command({
+ 'type': kind == 'buddy' ? 'buddy.create' : 'agent.new',
+ 'machineId': machineId,
+ 'engine': engine,
+ if (kind == 'buddy' && !_admitted) 'setup': _prepared,
+ if (kind != 'buddy') ...{
+ 'kind': kind,
+ if (kind == 'regular')
+ 'name': engine == 'claude' ? 'Claude Code' : 'Codex',
+ if (kind == 'pm') 'projectName': projectName!.trim(),
+ },
+ }, '$operationId-start').timeout(const Duration(seconds: 25));
+ _guard();
+ return result;
+ }
+}
diff --git a/desktop/lib/super_tabs/join/new_agent_dialog.dart b/desktop/lib/super_tabs/join/new_agent_dialog.dart
new file mode 100644
index 000000000..aace083c1
--- /dev/null
+++ b/desktop/lib/super_tabs/join/new_agent_dialog.dart
@@ -0,0 +1,157 @@
+import 'dart:convert';
+
+import 'package:flutter/material.dart';
+
+import '../../shared/widgets/app_dialog.dart';
+import '../../state/app_state.dart';
+import '../../logging/app_log.dart';
+import '../controller.dart';
+import 'agent_dialog.dart';
+import 'agent_launcher.dart';
+
+/// Shared entry for the left pane and the post-join Buddy prompt. The local
+/// transport's identity is used directly; a remote machine is never a fallback.
+Future<Map<String, dynamic>?> showSwarmNewAgentDialog(
+ BuildContext context, {
+ required SuperTabController controller,
+ required AppNotifier app,
+ bool bringing = false,
+ bool Function()? isCurrent,
+}) async {
+ final accountId = app.currentUser?.id;
+ final here = app.machineStates.values
+ .where(
+ (m) =>
+ m.isLocalMachine &&
+ !m.belongsToOtherAccount &&
+ !m.machine.isTeamAccount &&
+ !m.needsLink,
+ )
+ .firstOrNull;
+ bool current() =>
+ context.mounted &&
+ app.status == AppStatus.authenticated &&
+ app.currentUser?.id == accountId &&
+ accountId == controller.accountId &&
+ !controller.accessRevoked &&
+ (isCurrent?.call() ?? true);
+ if (!current()) return null;
+ if (here == null) {
+ await showAppDialog<void>(
+ context: context,
+ builder: (context) => AlertDialog(
+ title: const Text('Connect this computer'),
+ content: const Text(
+ 'Wait for this computer’s Harness connection, then try bringing your agent again.',
+ ),
+ actions: [
+ TextButton(
+ onPressed: () => Navigator.pop(context),
+ child: const Text('Close'),
+ ),
+ ],
+ ),
+ );
+ return null;
+ }
+ final machineId = here.machine.machineId;
+ // Probe executables through the existing hidden native path; do not inspect
+ // a sign-in or read settings here. Those belong to the owner's actual CLI.
+ await app
+ .probeEngines(machineId, force: true)
+ .timeout(const Duration(seconds: 20), onTimeout: () {});
+ if (!current()) return null;
+ final engines = [
+ for (final e in ['claude', 'codex'])
+ if (here.engines[e]?.installed == true) e,
+ ];
+ final launcher = SwarmAgentLauncher(
+ machineId: machineId,
+ machineName: here.machine.displayName,
+ inSwarm:
+ controller.snapshot?.machines.any(
+ (m) => m['machineId'] == machineId && m['buddyOnly'] != true,
+ ) ==
+ true,
+ isCurrent: current,
+ prepare: (operation) async {
+ final prepared = await app
+ .superTabMachineRequest(machineId, {
+ 'action': 'prepareContribution',
+ 'tabId': controller.tabId,
+ 'scope': 'swarm',
+ 'operationId': operation,
+ })
+ .timeout(const Duration(seconds: 20));
+ if (prepared['state'] == 'preparing') {
+ throw const SwarmAgentLaunchFailure(
+ 'Your agent’s folder is still being prepared. Retry to check it.',
+ );
+ }
+ if (prepared['state'] != 'ready' ||
+ prepared['cwd'] is! String ||
+ prepared['engines'] is! List) {
+ throw const SwarmAgentLaunchFailure(
+ 'Update Harness on this computer, then try again.',
+ );
+ }
+ return {
+ 'name': here.machine.displayName,
+ 'cwd': prepared['cwd'],
+ 'engines': prepared['engines'],
+ };
+ },
+ command: (command, operation) async {
+ final pending = controller.pendingCommand;
+ if (pending != null && jsonEncode(pending) != jsonEncode(command)) {
+ throw const SwarmAgentLaunchFailure(
+ 'Finish or retry the pending action in this org first.',
+ );
+ }
+ final result = pending == null
+ ? await controller.command(command, operationId: operation)
+ : await controller.retry();
+ if (result != null) return result;
+ if (const {
+ 'INVALID_COMMAND',
+ 'VALIDATION_ERROR',
+ 'UPDATE_REQUIRED',
+ }.contains(controller.operationErrorCode)) {
+ throw const SwarmAgentLaunchFailure(
+ 'Update Harness to use this agent flow.',
+ );
+ }
+ throw const SwarmAgentLaunchFailure(
+ 'The agent start is not confirmed. Retry to check it.',
+ );
+ },
+ );
+ if (!context.mounted || !current()) return null;
+ final result = await showAppDialog<Map<String, dynamic>>(
+ context: context,
+ builder: (_) => SwarmAgentDialog(
+ bringing: bringing,
+ engines: engines,
+ create: launcher.create,
+ isCurrent: current,
+ ),
+ );
+ if (!current() || result == null) return null;
+ final conversation = result['conversationId'];
+ if (conversation is String) await controller.select(conversation);
+ if (current()) {
+ // Refresh the host without making a failed wake turn a confirmed start
+ // into a second start. Host liveness is still visible through existing UI.
+ try {
+ await app
+ .wakeSuperTabHost(machineId)
+ .timeout(const Duration(seconds: 10));
+ } catch (_) {
+ appLog.info(
+ 'super-tabs',
+ 'own-agent host wake failed; host status remains visible',
+ );
+ }
+ }
+ return current() ? result : null;
+}
diff --git a/desktop/lib/super_tabs/join_account_choice.dart b/desktop/lib/super_tabs/join_account_choice.dart
deleted file mode 100644
index 28829090b..000000000
--- a/desktop/lib/super_tabs/join_account_choice.dart
+++ /dev/null
@@ -1,125 +0,0 @@
-import 'package:flutter/material.dart';
-
-import '../core/runtime_platform.dart';
-import '../widgets/desktop_chrome.dart';
-import '../widgets/desktop_prompt_surface.dart';
-
-/// The same informed choice for link joins, invitations and discovered joins.
-class SwarmJoinAccountChoice extends StatelessWidget {
- const SwarmJoinAccountChoice({
- super.key,
- required this.ownAccount,
- required this.onChanged,
- this.operatingSystem,
- });
-
- final bool ownAccount;
- final ValueChanged<bool>? onChanged;
- final String? operatingSystem;
-
- @override
- Widget build(BuildContext context) {
- final system = operatingSystem ?? RuntimePlatform.operatingSystem;
- final here = system == 'macos' ? 'this Mac' : 'this computer';
- final permission = system == 'windows'
- ? 'One-time setup asks for Windows administrator permission.'
- : 'One-time setup asks for your ${system == 'macos' ? 'Mac' : 'computer'} password.';
- return Column(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- mainAxisSize: MainAxisSize.min,
- children: [
- Text(
- "Where should teammates' agents run on $here?",
- style: DesktopChrome.text(),
- ),
- const SizedBox(height: 8),
- RadioGroup<bool>(
- groupValue: ownAccount,
- onChanged: (value) {
- if (value != null) onChanged?.call(value);
- },
- child: Column(
- mainAxisSize: MainAxisSize.min,
- children: [
- RadioListTile<bool>(
- value: false,
- enabled: onChanged != null,
- contentPadding: EdgeInsets.zero,
- title: Text(
- 'Separate Harness Team account',
- style: DesktopChrome.text(),
- ),
- subtitle: Text(
- "Teammates' agents cannot read your files or use your personal sign-ins. "
- "Uses $here's Claude Code and Codex subscriptions. $permission",
- style: DesktopChrome.metadata(),
- ),
- ),
- RadioListTile<bool>(
- value: true,
- enabled: onChanged != null,
- contentPadding: EdgeInsets.zero,
- title: Text('My account', style: DesktopChrome.text()),
- subtitle: Text(
- "No Team setup. Teammates' agents in this Swarm run as you and can access "
- 'your files, tools, keychain and signed-in apps. Your other Swarms keep their own choice.',
- style: DesktopChrome.metadata(),
- ),
- ),
- ],
- ),
- ),
- const SizedBox(height: 8),
- Text(
- "You can change this later in this machine's settings.",
- style: DesktopChrome.metadata(),
- ),
- ],
- );
- }
-}
-
-/// Joins without a link dialog (invitation acceptance or discovery) still ask
-/// before preparing this computer or asking for administrator permission.
-class SwarmJoinAccountDialog extends StatefulWidget {
- const SwarmJoinAccountDialog({super.key, required this.swarmName});
- final String swarmName;
-
- @override
- State<SwarmJoinAccountDialog> createState() => _SwarmJoinAccountDialogState();
-}
-
-class _SwarmJoinAccountDialogState extends State<SwarmJoinAccountDialog> {
- bool _ownAccount = false;
-
- @override
- Widget build(BuildContext context) => DesktopPromptSurface(
- body: DesktopPromptScrollBody(
- child: Column(
- mainAxisSize: MainAxisSize.min,
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- DesktopDialogHeader(
- title: 'Join Swarm',
- padding: EdgeInsets.zero,
- onClose: () => Navigator.pop(context),
- ),
- const SizedBox(height: 16),
- Text(widget.swarmName, style: DesktopChrome.heading()),
- const SizedBox(height: 12),
- SwarmJoinAccountChoice(
- ownAccount: _ownAccount,
- onChanged: (value) => setState(() => _ownAccount = value),
- ),
- ],
- ),
- ),
- actions: [
- FilledButton(
- key: const Key('swarm-join-account-continue'),
- onPressed: () => Navigator.pop(context, _ownAccount),
- child: const Text('Continue'),
- ),
- ],
- );
-}
diff --git a/desktop/lib/super_tabs/join_dialog.dart b/desktop/lib/super_tabs/join_dialog.dart
index 60df5391b..78a04ac9a 100644
--- a/desktop/lib/super_tabs/join_dialog.dart
+++ b/desktop/lib/super_tabs/join_dialog.dart
@@ -8,7 +8,7 @@ import '../widgets/desktop_chrome.dart';
import '../widgets/desktop_prompt_surface.dart';
import 'controller.dart';
import 'join_link.dart';
-import 'join_account_choice.dart';
+import 'join/new_agent_dialog.dart';
import 'join_machine.dart' show swarmNewMemberRole;
/// The native URL channel queues links before authentication. This host only
@@ -56,26 +56,23 @@ class _SwarmJoinHostState extends State<SwarmJoinHost> {
_presenting = true;
final accountId = account!.id!;
try {
- final choice = await showAppDialog<bool>(
- context: context,
- builder: (context) => ListenableBuilder(
- listenable: app,
- builder: (context, _) =>
- app.status == AppStatus.authenticated &&
- app.currentUser?.id == accountId &&
- !accountRequest.answered
- ? SwarmJoinAccountDialog(swarmName: accountRequest.swarmName)
- : AlertDialog(
- content: const Text('This join is no longer active.'),
- actions: [
- TextButton(
- onPressed: () => Navigator.pop(context),
- child: const Text('Close'),
- ),
- ],
- ),
- ),
+ final c = await app.superTabs.open(accountRequest.tabId);
+ if (!mounted || app.currentUser?.id != accountId) return;
+ final started = await showSwarmNewAgentDialog(
+ context,
+ controller: c,
+ app: app,
+ bringing: true,
+ isCurrent: () =>
+ app.currentUser?.id == accountId && !accountRequest.answered,
);
+ if (started != null &&
+ mounted &&
+ app.status == AppStatus.authenticated &&
+ app.currentUser?.id == accountId) {
+ app.openSuperTab(accountRequest.tabId, accountRequest.swarmName);
+ }
+ final choice = started != null;
accountRequest.complete(
app.status == AppStatus.authenticated &&
app.currentUser?.id == accountId
@@ -118,18 +115,6 @@ class _SwarmJoinHostState extends State<SwarmJoinHost> {
if (!current()) return;
app.openSuperTab(id, name);
},
- // The choice is explicit before this computer is shared.
- showAccountChoice: app.canSetUpTeamAccount,
- onNewMemberAccount: (id, role, ownAccount) {
- if (!current()) return;
- unawaited(
- app.addMachineOnJoin(
- id,
- role: role,
- ownAccount: ownAccount,
- ),
- );
- },
onNewMember: (id, role) {
if (!current()) return;
unawaited(app.addMachineOnJoin(id, role: role));
@@ -173,8 +158,6 @@ class SwarmJoinDialog extends StatefulWidget {
required this.onJoined,
required this.isCurrent,
this.onNewMember,
- this.onNewMemberAccount,
- this.showAccountChoice = true,
});
final SwarmJoinLink link;
final String accountEmail;
@@ -184,9 +167,6 @@ class SwarmJoinDialog extends StatefulWidget {
/// After a join that made this account a member, with the role it joined
/// as; never for someone who was one already.
final void Function(String id, String role)? onNewMember;
- final bool showAccountChoice;
- final void Function(String id, String role, bool ownAccount)?
- onNewMemberAccount;
final bool Function() isCurrent;
@override
@@ -197,11 +177,6 @@ class _SwarmJoinDialogState extends State<SwarmJoinDialog> {
final _operationId = superTabOperationId();
Map<String, dynamic>? _preview;
bool _loading = true, _joining = false;
- bool _ownAccount = false;
- bool get _choosesAccount =>
- widget.showAccountChoice &&
- _preview?['alreadyMember'] != true &&
- _preview?['role'] == 'collaborator';
String? _error;
String get _path =>
'/api/super-tabs/${Uri.encodeComponent(widget.link.tabId)}/join';
@@ -270,13 +245,7 @@ class _SwarmJoinDialogState extends State<SwarmJoinDialog> {
if (!_current) return;
widget.onJoined(widget.link.tabId, _preview!['name'] as String);
if (newRole != null) {
- if (newRole == 'collaborator' &&
- _choosesAccount &&
- widget.onNewMemberAccount != null) {
- widget.onNewMemberAccount!(widget.link.tabId, newRole, _ownAccount);
- } else {
- widget.onNewMember?.call(widget.link.tabId, newRole);
- }
+ widget.onNewMember?.call(widget.link.tabId, newRole);
}
if (mounted) Navigator.pop(context);
} catch (failure) {
@@ -335,15 +304,6 @@ class _SwarmJoinDialogState extends State<SwarmJoinDialog> {
],
const SizedBox(height: 12),
Text(widget.accountEmail, style: DesktopChrome.metadata()),
- if (_choosesAccount) ...[
- const SizedBox(height: 16),
- SwarmJoinAccountChoice(
- ownAccount: _ownAccount,
- onChanged: _joining
- ? null
- : (value) => setState(() => _ownAccount = value),
- ),
- ],
if (_error != null) ...[
const SizedBox(height: 12),
Text(_error!, style: DesktopChrome.text()),
diff --git a/desktop/lib/super_tabs/join_machine.dart b/desktop/lib/super_tabs/join_machine.dart
index eee57676d..3e49de367 100644
--- a/desktop/lib/super_tabs/join_machine.dart
+++ b/desktop/lib/super_tabs/join_machine.dart
@@ -1,13 +1,17 @@
import 'dart:async';
import '../core/machine_resources.dart';
-import '../core/models.dart' show sameMachineId;
import 'controller.dart';
-/// A join waiting for the local person's account choice. Never persisted;
-/// closing the UI cancels it without enabling own-account work.
+/// A join waiting for the person to bring their own agent. Never persisted;
+/// closing the prompt starts nothing and never enrolls a machine.
class SwarmJoinAccountRequest {
- SwarmJoinAccountRequest(this.swarmName, this.accountId);
+ SwarmJoinAccountRequest(
+ this.swarmName,
+ this.accountId, {
+ required this.tabId,
+ });
+ final String tabId;
final String swarmName, accountId;
final _answer = Completer<bool?>();
bool get answered => _answer.isCompleted;
@@ -74,199 +78,3 @@ class SwarmInviteAccepts {
return reply;
}
}
-
-/// The engines a Swarm machine runs (backend `swarmEngine`).
-const _swarmEngines = {'claude', 'codex'};
-
-/// This computer, added to a Swarm by the join that just let its person in
-/// (Scholes, 2026-10-29): what [SwarmJoinMachine.add] did, for the note the
-/// person sees. [problem]: why it was not added, in a sentence for them.
-/// [teamProblem]: it was added, but its Harness Team account could not be
-/// offered, and where to set it up (task #3160).
-class SwarmJoinedMachine {
- const SwarmJoinedMachine({
- required this.tabId,
- required this.swarmName,
- required this.machineId,
- required this.machineName,
- this.problem,
- this.teamProblem,
- this.ownAccount = false,
- this.accountProblem,
- });
-
- final String tabId, swarmName, machineId, machineName;
- final String? problem, teamProblem, accountProblem;
- final bool ownAccount;
- bool get added => problem == null;
-
- /// The same machine, added, whose Team account offer failed.
- SwarmJoinedMachine withoutTeamOffer() => SwarmJoinedMachine(
- tabId: tabId,
- swarmName: swarmName,
- machineId: machineId,
- machineName: machineName,
- teamProblem: 'Set it up from Machines.',
- );
-}
-
-/// Adds this computer to a Swarm its person just joined, with Add machine's
-/// defaults: the Claude Code and Codex it has, the folder its daemon sets up,
-/// and the number of agents its memory suggests. It is added as
-/// `teamAccountOnly`, so the server sends teammates' work to it only through
-/// its Harness Team account whose privacy check passed (backend
-/// superTabs/machines.ts `teamWorkRefusal`); until then it runs only its
-/// person's own projects.
-///
-/// Only a new collaborator's computer, in a Swarm that uses Harness Team
-/// accounts: a viewer, a computer already in the Swarm, one its person took
-/// out of it, and a Swarm whose server does not try Team accounts yet are left
-/// as they are.
-class SwarmJoinMachine {
- SwarmJoinMachine({
- required this.machineRequest,
- required this.readResources,
- required this.wake,
- this.pause = const Duration(seconds: 1),
- this.deadline = const Duration(minutes: 5),
- });
-
- /// A `super_tabs` request to this computer's own daemon.
- final Future<Map<String, dynamic>> Function(
- String machineId,
- Map<String, dynamic> payload,
- )
- machineRequest;
- final Future<MachineResources?> Function(String machineId) readResources;
-
- /// Tells the daemon it is in the Swarm now, so it starts hosting at once.
- final Future<void> Function(String machineId) wake;
-
- /// Between two reads of a folder setup still running, and how long the
- /// whole setup may take, as Add machine waits.
- final Duration pause, deadline;
-
- /// Null when nothing was to be done, or the account changed or signed out
- /// meanwhile ([current] false): nothing is added or said then.
- Future<SwarmJoinedMachine?> add(
- SuperTabController c, {
- required String machineId,
- required String machineName,
- required bool Function() current,
- bool ownAccount = false,
- }) async {
- final snapshot = c.snapshot;
- if (snapshot == null || !current()) return null;
- if (!snapshot.teamAccounts || !c.canWrite) return null;
- final me = snapshot.people.where((p) => p.id == c.accountId).firstOrNull;
- if (me?.role != 'collaborator') return null;
- if (snapshot.machines.any((m) => m['machineId'] == machineId)) return null;
- // Its person took it out, on any computer, a reinstall of this one
- // included: it stays out until they add it with Add machine (backend
- // commands.ts machine.remove; task #3212).
- if (snapshot.removedMachines.any((id) => sameMachineId(id, machineId))) {
- return null;
- }
- SwarmJoinedMachine note([String? problem]) => SwarmJoinedMachine(
- tabId: c.tabId,
- swarmName: snapshot.name,
- machineId: machineId,
- machineName: machineName,
- problem: problem,
- );
-
- final operationId = superTabOperationId();
- final until = DateTime.now().add(deadline);
- Map<String, dynamic> prepared;
- while (true) {
- try {
- prepared = await machineRequest(machineId, {
- 'action': 'prepareContribution',
- 'tabId': c.tabId,
- 'scope': 'swarm',
- 'operationId': operationId,
- });
- } catch (_) {
- if (!current()) return null;
- return note(
- 'Could not reach Harness on this computer. Add it from Machines.',
- );
- }
- if (!current()) return null;
- if (prepared['state'] == 'ready' && prepared['scope'] == 'swarm') break;
- if (prepared['state'] != 'preparing') {
- return note(
- 'Update Harness on this computer, then add it from Machines.',
- );
- }
- if (DateTime.now().isAfter(until)) {
- return note(
- 'Setting up this computer took too long. Add it from Machines.',
- );
- }
- await Future<void>.delayed(pause);
- }
- final engines = [
- for (final engine in prepared['engines'] as List? ?? const [])
- if (_swarmEngines.contains(engine)) engine as String,
- ];
- if (engines.isEmpty) {
- return note(
- 'Install Claude Code or Codex on this computer, then add it from Machines.',
- );
- }
- MachineResources? resources;
- try {
- resources = await readResources(machineId);
- } catch (_) {
- // Its offer below stands in.
- }
- final offered = prepared['maxAgents'];
- final slots =
- superTabSuggestedAgentSlots(resources) ??
- (offered is num ? offered.toInt().clamp(1, 1024) : 4);
- if (!current() || !c.canWrite) return null;
- final result = await c.command({
- 'type': 'machine.contribute',
- 'machineId': machineId,
- 'name': machineName,
- 'cwd': prepared['cwd'],
- 'scope': 'swarm',
- 'engines': engines,
- 'maxAgents': slots,
- // Joining sets no limit: free memory is checked at each start.
- 'agents': 'memory',
- 'teamAccountOnly': true,
- });
- if (!current()) return null;
- if (result == null) {
- return note(
- c.operationError ??
- 'Could not add this computer. Add it from Machines.',
- );
- }
- try {
- await wake(machineId);
- } catch (_) {
- // Its daemon finds the Swarm on its next read anyway.
- }
- if (!current()) return null;
- if (!ownAccount) return note();
- final consent = await c.command({
- 'type': 'machine.ownAccountWork',
- 'machineId': machineId,
- 'allowed': true,
- });
- if (!current()) return null;
- return SwarmJoinedMachine(
- tabId: c.tabId,
- swarmName: snapshot.name,
- machineId: machineId,
- machineName: machineName,
- ownAccount: consent != null,
- accountProblem: consent == null
- ? 'Could not confirm the account setting. Check Machines to confirm or try again.'
- : null,
- );
- }
-}
diff --git a/desktop/lib/super_tabs/join_machine_note.dart b/desktop/lib/super_tabs/join_machine_note.dart
deleted file mode 100644
index e6cf009d4..000000000
--- a/desktop/lib/super_tabs/join_machine_note.dart
+++ /dev/null
@@ -1,132 +0,0 @@
-import 'dart:async';
-
-import 'package:flutter/material.dart';
-
-import '../core/runtime_platform.dart';
-import 'controller.dart';
-import 'join_machine.dart';
-
-/// The note after joining a Swarm (Scholes, 2026-10-29): this computer was
-/// added, teammates' agents run here only in Harness Team, never as the
-/// person, and Pause or Remove undo it at once. When it could not be added,
-/// why, and where to add it.
-///
-/// [open]: the Swarm's controller ([SuperTabs.open]), which Pause and Remove
-/// command.
-void showJoinedMachineNote(
- BuildContext context,
- Future<SuperTabController> Function(String tabId) open,
- SwarmJoinedMachine note, {
- String? operatingSystem,
-}) {
- final messenger = ScaffoldMessenger.maybeOf(context);
- if (messenger == null) return;
- final here = (operatingSystem ?? RuntimePlatform.operatingSystem) == 'macos'
- ? 'This Mac'
- : 'This computer';
- final text = switch (note) {
- SwarmJoinedMachine(added: false) =>
- '$here was not added to ${note.swarmName}. ${note.problem}',
- SwarmJoinedMachine(accountProblem: final String problem) =>
- '$here was added to ${note.swarmName}. $problem',
- SwarmJoinedMachine(ownAccount: true) =>
- '$here was added to ${note.swarmName}. Teammates\' agents run as you '
- 'and can access your files, tools and sign-ins.',
- SwarmJoinedMachine(teamProblem: final String problem) =>
- '$here was added to ${note.swarmName}, but Harness could not offer its '
- 'Harness Team account. $problem',
- _ =>
- '$here was added to ${note.swarmName}. Teammates\' agents run here '
- 'only in Harness Team, never as you.',
- };
- // Pause and Remove came with the note that it was added.
- final undo = note.added && note.teamProblem == null;
- messenger.showSnackBar(
- SnackBar(
- key: const Key('swarm-joined-machine-note'),
- duration: const Duration(seconds: 12),
- showCloseIcon: true,
- content: Row(
- children: [
- Expanded(child: Text(text)),
- if (undo) ...[
- const SizedBox(width: 12),
- _NoteAction(
- key: const Key('swarm-joined-machine-pause'),
- label: 'Pause',
- run: () => _act(open, note, {
- 'type': 'machine.pause',
- 'machineId': note.machineId,
- 'paused': true,
- }),
- messenger: messenger,
- ),
- _NoteAction(
- key: const Key('swarm-joined-machine-remove'),
- label: 'Remove',
- run: () => _act(open, note, {
- 'type': 'machine.remove',
- 'machineId': note.machineId,
- }),
- messenger: messenger,
- ),
- ],
- ],
- ),
- ),
- );
-}
-
-/// Null when it was done; otherwise the Swarm's own sentence.
-Future<String?> _act(
- Future<SuperTabController> Function(String tabId) open,
- SwarmJoinedMachine note,
- Map<String, dynamic> command,
-) async {
- try {
- final c = await open(note.tabId);
- final result = await c.command(command);
- return result == null
- ? c.operationError ?? 'Could not do that. Try again from Machines.'
- : null;
- } catch (_) {
- return 'Could not do that. Try again from Machines.';
- }
-}
-
-class _NoteAction extends StatefulWidget {
- const _NoteAction({
- super.key,
- required this.label,
- required this.run,
- required this.messenger,
- });
-
- final String label;
- final Future<String?> Function() run;
- final ScaffoldMessengerState messenger;
-
- @override
- State<_NoteAction> createState() => _NoteActionState();
-}
-
-class _NoteActionState extends State<_NoteAction> {
- bool _busy = false;
-
- Future<void> _press() async {
- if (_busy) return;
- setState(() => _busy = true);
- final failure = await widget.run();
- if (!widget.messenger.mounted) return;
- widget.messenger.hideCurrentSnackBar();
- if (failure != null) {
- widget.messenger.showSnackBar(SnackBar(content: Text(failure)));
- }
- }
-
- @override
- Widget build(BuildContext context) => TextButton(
- onPressed: _busy ? null : () => unawaited(_press()),
- child: Text(widget.label),
- );
-}
diff --git a/desktop/lib/usage/claude_usage_report.dart b/desktop/lib/usage/claude_usage_report.dart
new file mode 100644
index 000000000..fe86aac6d
--- /dev/null
+++ b/desktop/lib/usage/claude_usage_report.dart
@@ -0,0 +1,66 @@
+import 'usage_source.dart';
+import 'usage_window.dart';
+
+/// Pure mapping of CLI-reported limit windows; performs no I/O.
+abstract final class _ClaudeUsageWindows {
+ static ProviderUsage _mapWindows(
+ Map<Object?, Object?> data, {
+ String? account,
+ String? email,
+ }) {
+ final windows = <UsageWindow>[
+ ?_window('Session', data['five_hour']),
+ ?_window(kWeeklyWindowLabel, data['seven_day']),
+ ?_window(
+ 'Fable',
+ data['fable_weekly'] ??
+ data['fable_seven_day'] ??
+ data['seven_day_fable'],
+ ),
+ ];
+ if (windows.isEmpty) {
+ return const ProviderUsage(
+ provider: UsageProvider.claude,
+ status: UsageStatus.failed,
+ message: 'Claude reported no limits',
+ );
+ }
+ return ProviderUsage(
+ provider: UsageProvider.claude,
+ status: UsageStatus.ok,
+ windows: windows,
+ fetchedAt: DateTime.now(),
+ account: account,
+ email: email,
+ );
+ }
+
+ static UsageWindow? _window(String label, Object? raw) {
+ if (raw is! Map) return null;
+ final used = parseUsedPercent([raw['utilization'], raw['used_percentage']]);
+ if (used == null) return null;
+ return UsageWindow(
+ label: label,
+ usedPercent: used,
+ resetsAt: parseResetTimestamp(raw['resets_at']),
+ );
+ }
+}
+
+ProviderUsage claudeUsageFromAnswer({
+ required int? statusCode,
+ required Object? body,
+ String? account,
+ String? email,
+}) {
+ final failure = usageFailureFor(UsageProvider.claude, statusCode);
+ if (failure != null) return failure;
+ if (body is! Map) {
+ return const ProviderUsage(
+ provider: UsageProvider.claude,
+ status: UsageStatus.failed,
+ message: 'Claude answered in a shape this build cannot read',
+ );
+ }
+ return _ClaudeUsageWindows._mapWindows(body, account: account, email: email);
+}
diff --git a/desktop/lib/usage/claude_usage_source.dart b/desktop/lib/usage/claude_usage_source.dart
deleted file mode 100644
index c661c3057..000000000
--- a/desktop/lib/usage/claude_usage_source.dart
+++ /dev/null
@@ -1,142 +0,0 @@
-import 'package:dio/dio.dart';
-
-import '../logging/http_log.dart';
-import 'usage_account_key.dart';
-import 'usage_credentials.dart';
-import 'usage_source.dart';
-import 'usage_window.dart';
-
-/// Claude Code's rate limits, read with the token `claude login` left behind.
-///
-/// ⚠️ **This endpoint is undocumented.** It is what the CLI itself asks when it
-/// prints `/usage`, and it answers only to a token minted for the CLI — hence
-/// the beta header and the CLI's own user agent, which together are what make
-/// an OAuth token issued to Claude Code acceptable here. It can change without
-/// notice, and when it does the failure is a parse error or a 4xx, both of
-/// which this reports as a state rather than a crash. **TODO(BE):** replace
-/// with a supported endpoint if one appears.
-class ClaudeUsageSource implements UsageSource {
- ClaudeUsageSource({Dio? dio, UsageCredentials? credentials})
- : _dio = dio ?? attachHttpLog(buildUsageDio()),
- _credentials = credentials ?? const UsageCredentials();
-
- final Dio _dio;
- final UsageCredentials _credentials;
-
- static const _url = 'https://api.anthropic.com/api/oauth/usage';
-
- @override
- UsageProvider get provider => UsageProvider.claude;
-
- @override
- Future<ProviderUsage> read() async {
- final token = await _credentials.claude();
- if (token == null) return signedOut(provider);
- final accountId = await _credentials.claudeAccountId();
- final email = await _credentials.claudeAccountEmail();
- // An expired token is spent as a sign-in rather than as a round trip: this
- // app does not refresh what the CLI owns, so the request could only fail.
- if (token.isExpired) {
- return ProviderUsage(
- provider: provider,
- status: UsageStatus.signedOut,
- message: 'Claude session expired — run claude to sign in again',
- );
- }
- try {
- final response = await _dio.getUri<Object?>(
- Uri.parse(_url),
- options: Options(
- headers: {
- 'Authorization': 'Bearer ${token.accessToken}',
- 'anthropic-beta': 'oauth-2025-04-20',
- 'User-Agent': 'claude-code/2.1.0',
- },
- ),
- );
- return claudeUsageFromAnswer(
- statusCode: response.statusCode,
- body: response.data,
- email: email,
- account: accountId == null
- ? null
- : usageAccountKey(provider, accountId),
- );
- } on DioException {
- return usageFailureFor(provider, null)!;
- }
- }
-
- /// The three windows the CLI itself shows, in the order they bite.
- ///
- /// Fable's weekly allowance has been spelled three ways across releases, so
- /// all three are tried — an absent window is simply not drawn, which is why
- /// a build reading a newer server loses a row rather than the whole panel.
- static ProviderUsage _mapWindows(
- Map<Object?, Object?> data, {
- String? account,
- String? email,
- }) {
- final windows = <UsageWindow>[
- ?_window('Session', data['five_hour']),
- ?_window(kWeeklyWindowLabel, data['seven_day']),
- ?_window(
- 'Fable',
- data['fable_weekly'] ??
- data['fable_seven_day'] ??
- data['seven_day_fable'],
- ),
- ];
- if (windows.isEmpty) {
- return const ProviderUsage(
- provider: UsageProvider.claude,
- status: UsageStatus.failed,
- message: 'Claude reported no limits',
- );
- }
- return ProviderUsage(
- provider: UsageProvider.claude,
- status: UsageStatus.ok,
- windows: windows,
- fetchedAt: DateTime.now(),
- account: account,
- email: email,
- );
- }
-
- static UsageWindow? _window(String label, Object? raw) {
- if (raw is! Map) return null;
- final used = parseUsedPercent([raw['utilization'], raw['used_percentage']]);
- if (used == null) return null;
- return UsageWindow(
- label: label,
- usedPercent: used,
- resetsAt: parseResetTimestamp(raw['resets_at']),
- );
- }
-}
-
-/// What Claude's usage endpoint said, as the rail draws it.
-///
-/// Shared by the two places an answer comes from — this computer asking with
-/// its own token, and a REMOTE machine asking with its own and handing back
-/// exactly what the vendor sent (`usage_read`, see `remote_usage.dart`). One
-/// reading of the answer for both, so a window cannot be named one way here and
-/// another way for a machine across the relay.
-ProviderUsage claudeUsageFromAnswer({
- required int? statusCode,
- required Object? body,
- String? account,
- String? email,
-}) {
- final failure = usageFailureFor(UsageProvider.claude, statusCode);
- if (failure != null) return failure;
- if (body is! Map) {
- return const ProviderUsage(
- provider: UsageProvider.claude,
- status: UsageStatus.failed,
- message: 'Claude answered in a shape this build cannot read',
- );
- }
- return ClaudeUsageSource._mapWindows(body, account: account, email: email);
-}
diff --git a/desktop/lib/usage/codex_usage_source.dart b/desktop/lib/usage/codex_usage_report.dart
similarity index 50%
rename from desktop/lib/usage/codex_usage_source.dart
rename to desktop/lib/usage/codex_usage_report.dart
index b0dd0b918..d7d230834 100644
--- a/desktop/lib/usage/codex_usage_source.dart
+++ b/desktop/lib/usage/codex_usage_report.dart
@@ -1,64 +1,8 @@
-import 'package:dio/dio.dart';
-
-import '../logging/http_log.dart';
-import 'usage_account_key.dart';
-import 'usage_credentials.dart';
import 'usage_source.dart';
import 'usage_window.dart';
-/// Codex's rate limits, read with the token `codex login` left in
-/// `~/.codex/auth.json`.
-///
-/// ⚠️ Undocumented, on the same terms as [ClaudeUsageSource]: this is the
-/// backend the Codex CLI itself asks, and it can change without notice.
-///
-/// Codex numbers its windows rather than naming them — a primary and a
-/// secondary, whose real durations arrive in the payload — so the labels here
-/// are derived from `limit_window_seconds` instead of hardcoded. A build that
-/// printed "5h" for a window the server had quietly changed to 24h would be
-/// confidently wrong, which is worse than saying nothing.
-class CodexUsageSource implements UsageSource {
- CodexUsageSource({Dio? dio, UsageCredentials? credentials})
- : _dio = dio ?? attachHttpLog(buildUsageDio()),
- _credentials = credentials ?? const UsageCredentials();
-
- final Dio _dio;
- final UsageCredentials _credentials;
-
- static const _url = 'https://chatgpt.com/backend-api/wham/usage';
-
- @override
- UsageProvider get provider => UsageProvider.codex;
-
- @override
- Future<ProviderUsage> read() async {
- final token = await _credentials.codex();
- if (token == null) return signedOut(provider);
- final accountId = await _credentials.codexAccountId();
- final email = await _credentials.codexAccountEmail();
- try {
- final response = await _dio.getUri<Object?>(
- Uri.parse(_url),
- options: Options(
- headers: {
- 'Authorization': 'Bearer ${token.accessToken}',
- 'ChatGPT-Account-Id': ?accountId,
- },
- ),
- );
- return codexUsageFromAnswer(
- statusCode: response.statusCode,
- body: response.data,
- email: email,
- account: accountId == null
- ? null
- : usageAccountKey(provider, accountId),
- );
- } on DioException {
- return usageFailureFor(provider, null)!;
- }
- }
-
+/// Pure mapping of CLI-reported limit windows; performs no I/O.
+abstract final class _CodexUsageWindows {
static ProviderUsage _mapWindows(
Map<Object?, Object?> data, {
String? account,
@@ -117,9 +61,6 @@ class CodexUsageSource implements UsageSource {
}
}
-/// What Codex's usage endpoint said, as the rail draws it — shared by this
-/// computer's own reading and a remote machine's, for the reason
-/// [claudeUsageFromAnswer] gives.
ProviderUsage codexUsageFromAnswer({
required int? statusCode,
required Object? body,
@@ -135,5 +76,5 @@ ProviderUsage codexUsageFromAnswer({
message: 'Codex answered in a shape this build cannot read',
);
}
- return CodexUsageSource._mapWindows(body, account: account, email: email);
+ return _CodexUsageWindows._mapWindows(body, account: account, email: email);
}
diff --git a/desktop/lib/usage/remote_usage.dart b/desktop/lib/usage/remote_usage.dart
index 7ad6bd790..1373411cc 100644
--- a/desktop/lib/usage/remote_usage.dart
+++ b/desktop/lib/usage/remote_usage.dart
@@ -1,16 +1,12 @@
-import 'claude_usage_source.dart';
-import 'codex_usage_source.dart';
+import 'claude_usage_report.dart';
+import 'codex_usage_report.dart';
import 'usage_source.dart';
import 'usage_window.dart';
/// One remote machine's `usage_read_result`, as readings the rail can draw.
///
-/// The machine answered with its vendors' replies exactly as they came — HTTP
-/// status and body (`autonomous-harness/cli/src/lib/accountUsage.ts`) — so they
-/// are read here by the SAME mappers that read this computer's own
-/// ([claudeUsageFromAnswer], [codexUsageFromAnswer]). A window cannot be named
-/// one way for this Mac and another way for a machine across the relay, because
-/// there is only one place that names it.
+/// Only the CLI supplies readings. Desktop maps reported windows and never
+/// opens a vendor session or reads a credential.
///
/// Never throws: an entry this build cannot read is dropped rather than failing
/// the machine's whole answer, and an answer with no readable entry is empty —
diff --git a/desktop/lib/usage/usage_accounts.dart b/desktop/lib/usage/usage_accounts.dart
index 790a79264..65e601b44 100644
--- a/desktop/lib/usage/usage_accounts.dart
+++ b/desktop/lib/usage/usage_accounts.dart
@@ -1,9 +1,14 @@
import 'usage_window.dart';
-/// One remote machine's answer to `usage_read`: what ITS agent accounts have
-/// spent, read there with its own credentials.
+/// One computer's CLI rate-limit report, without credential access in Desktop.
class MachineUsage {
- const MachineUsage({required this.machineName, required this.readings});
+ const MachineUsage({
+ required this.machineName,
+ required this.readings,
+ this.isLocal = false,
+ });
+
+ final bool isLocal;
/// How the machine is named on screen — the strip's label for a figure that
/// is not this computer's.
diff --git a/desktop/lib/usage/usage_controller.dart b/desktop/lib/usage/usage_controller.dart
index 2d1a18d2f..e69c09971 100644
--- a/desktop/lib/usage/usage_controller.dart
+++ b/desktop/lib/usage/usage_controller.dart
@@ -3,16 +3,13 @@ import 'dart:async';
import 'package:flutter/foundation.dart';
import '../core/test_run.dart';
-import '../core/viewer_mode.dart';
-import 'claude_usage_source.dart';
-import 'codex_usage_source.dart';
import 'usage_accounts.dart';
import 'usage_source.dart';
import 'usage_window.dart';
/// What each agent account has spent, kept current for the status rail.
///
-/// Polling, because neither vendor pushes,
+/// Polling the connected CLIs, which own their own rate-limit reports,
/// and neither figure moves fast enough to be worth a socket. A minute is also
/// the granularity the countdowns are printed at, so a faster poll would redraw
/// the same minute.
@@ -27,14 +24,7 @@ class UsageController extends ChangeNotifier {
this.remote,
this.interval = const Duration(seconds: 60),
bool autoStart = true,
- bool? readsThisComputer,
- }) : _sources =
- sources ??
- // A viewer build (a browser) runs no agent CLI, so it has no tokens of its own to
- // read: its figures are the account's computers' ([remote]).
- ((readsThisComputer ?? !kViewerMode)
- ? [ClaudeUsageSource(), CodexUsageSource()]
- : const []) {
+ }) : _sources = sources ?? const [] {
for (final source in _sources) {
_readings[source.provider] = ProviderUsage.loading(source.provider);
}
@@ -46,9 +36,8 @@ class UsageController extends ChangeNotifier {
final List<UsageSource> _sources;
- /// Asks every connected remote machine what ITS accounts have spent
- /// (`AppNotifier.readRemoteUsage`). Null reads this computer only — every
- /// test, and anything that has no machines to ask.
+ /// Asks connected computers for their CLI reports, including this computer.
+ /// Null leaves only explicitly injected sources (used by tests).
final Future<List<MachineUsage>> Function()? remote;
List<MachineUsage> _remote = const [];
@@ -83,6 +72,8 @@ class UsageController extends ChangeNotifier {
/// Every provider's reading, in the order the sources were given.
List<ProviderUsage> get readings => [
for (final source in _sources) _readings[source.provider]!,
+ for (final machine in _remote.where((machine) => machine.isLocal))
+ ...machine.readings,
];
/// The providers with figures worth printing on the rail.
@@ -94,7 +85,10 @@ class UsageController extends ChangeNotifier {
/// One figure per ACCOUNT, this computer's first — see [groupUsageAccounts].
///
/// [readings] stays this computer's alone; this is the grouped view.
- List<UsageAccount> get accounts => groupUsageAccounts(readings, _remote);
+ List<UsageAccount> get accounts => groupUsageAccounts(
+ readings,
+ _remote.where((machine) => !machine.isLocal).toList(),
+ );
/// Whether the rail has anything at all to say — figures, or a reason there
/// are none. False only before the first cycle resolves.
@@ -125,11 +119,22 @@ class UsageController extends ChangeNotifier {
answers = await ask();
} catch (_) {
// Keep the last good answer, the same rule the local half follows.
+ if (!_disposed && request == _remoteRequest && _sources.isEmpty) {
+ _landed = true;
+ stale = true;
+ notifyListeners();
+ }
return;
}
// A slower, older answer must not overwrite a newer one.
if (_disposed || request != _remoteRequest) return;
_remote = answers;
+ if (_sources.isEmpty) {
+ _landed = true;
+ stale = !answers.any(
+ (machine) => machine.readings.any((r) => r.hasFigures),
+ );
+ }
notifyListeners();
}
@@ -145,6 +150,10 @@ class UsageController extends ChangeNotifier {
Future<void> _refreshLocal() async {
_started = true;
+ if (_sources.isEmpty) {
+ if (remote == null) _landed = true;
+ return;
+ }
final request = ++_request;
final results = await Future.wait(_sources.map((s) => s.read()));
// A refresh that finished after a newer one started is thrown away: its
diff --git a/desktop/lib/usage/usage_credentials.dart b/desktop/lib/usage/usage_credentials.dart
deleted file mode 100644
index c1d8482f0..000000000
--- a/desktop/lib/usage/usage_credentials.dart
+++ /dev/null
@@ -1,235 +0,0 @@
-/// Where the agent CLIs keep the tokens their usage endpoints want.
-///
-/// This app reads them; it never writes them and never refreshes them. One
-/// sign-in per machine, owned by the CLI that made it. A second copy here
-/// would be a second thing to expire and to disagree about.
-///
-/// **Nothing in this file may be logged.** Every value it returns is a bearer
-/// token or account identity; the CLI transcript keeps secrets out of argv, and
-/// a `print` here would undo that. Callers get the token and nothing else —
-/// no wrapper carrying it into an error message.
-library;
-
-import '../core/home_dir.dart';
-
-import 'dart:convert';
-import 'dart:io';
-
-import 'package:cryptography/dart.dart';
-
-import '../core/runtime_platform.dart';
-
-/// A token, and when it stops working.
-class UsageToken {
- const UsageToken({required this.accessToken, this.expiresAt});
-
- final String accessToken;
-
- /// When the token expires, when the store said so. Null means unknown, which
- /// is treated as "try it" rather than "assume dead" — the endpoint answering
- /// 401 is a better authority than a clock we may be reading wrong.
- final DateTime? expiresAt;
-
- /// Already dead, so the request can be skipped and reported as a sign-in
- /// rather than spent as a round trip that will fail.
- bool get isExpired {
- final at = expiresAt;
- return at != null && at.isBefore(DateTime.now());
- }
-}
-
-/// Reads the tokens the usage endpoints need, from wherever each CLI put them.
-class UsageCredentials {
- const UsageCredentials({this.home, this.runProcess, this.environment});
-
- /// Overridden by tests. Null means this machine's real home.
- final String? home;
-
- /// Overridden by tests. Null means this process's real environment — the same one Claude Code
- /// reads `USER` and `CLAUDE_CONFIG_DIR` from when it names its Keychain item.
- final Map<String, String>? environment;
-
- /// Overridden by tests so nothing shells out to the real `security`.
- final Future<ProcessResult> Function(String, List<String>)? runProcess;
-
- String? get _home => home ?? maybeHomeDir();
- Map<String, String> get _env => environment ?? RuntimePlatform.environment;
-
- /// The Keychain SERVICE Claude Code writes its OAuth token under — its own rule, read off
- /// Claude Code 2.1.272: `Claude Code-credentials`, plus `-<sha256(configDir)[0..8]>` when
- /// `CLAUDE_CONFIG_DIR` is set, so profiles kept in different directories get different items.
- /// (`CLAUDE_SECURESTORAGE_CONFIG_DIR` overrides the directory that is hashed; empty means the
- /// plain name even with a config dir set.)
- static String keychainService(Map<String, String> env) {
- final secure = env['CLAUDE_SECURESTORAGE_CONFIG_DIR'];
- final configDir = env['CLAUDE_CONFIG_DIR'];
- final plain = secure != null
- ? secure.isEmpty
- : configDir == null || configDir.isEmpty;
- if (plain) return _claudeKeychainService;
- final hashed = secure ?? configDir!;
- final digest = const DartSha256().hashSync(utf8.encode(hashed)).bytes;
- final prefix = digest
- .take(4)
- .map((b) => b.toRadixString(16).padLeft(2, '0'))
- .join();
- return '$_claudeKeychainService-$prefix';
- }
-
- /// The Keychain ACCOUNT Claude Code writes under — again its own rule: `USER`, else the OS
- /// username, and a fixed placeholder when that is not a plain account name.
- ///
- /// ⚠️ This is the half that was missing. `security find-generic-password -s <service>` alone
- /// returns whichever item matches the service FIRST, and a Keychain that has seen more than one
- /// account (a stale item under another user name, say) answered with the stale one — an expired
- /// token, so the menu said "Not signed in" beside a Claude Code that was signed in and working.
- static String keychainAccount(
- Map<String, String> env, {
- required String username,
- }) {
- final name = env['USER'] ?? username;
- return _claudeAccountPattern.hasMatch(name) ? name : 'claude-code-user';
- }
-
- static const _claudeKeychainService = 'Claude Code-credentials';
- static final _claudeAccountPattern = RegExp(r'^[a-zA-Z0-9._-]+$');
-
- /// Claude Code's OAuth token.
- ///
- /// macOS keeps it in the login Keychain and Linux in a file, so both are
- /// tried in that order — and the file is tried on macOS too, because a
- /// Keychain that will not answer (a locked login chain, a Finder launch with
- /// no authorization) is a state, not the end of the road.
- Future<UsageToken?> claude() async {
- final fromKeychain = await _readKeychain();
- final token =
- _parseClaude(fromKeychain) ??
- _parseClaude(_readFile('.claude/.credentials.json'));
- return token;
- }
-
- /// Codex's OAuth token, written by `codex login`.
- Future<UsageToken?> codex() async {
- final raw = _readFile('.codex/auth.json');
- if (raw == null) return null;
- final decoded = _decode(raw);
- final tokens = decoded?['tokens'];
- if (tokens is! Map) return null;
- final access = tokens['access_token'];
- if (access is! String || access.isEmpty) return null;
- return UsageToken(accessToken: access);
- }
-
- /// The account id Codex's backend scopes the reading to.
- Future<String?> codexAccountId() async {
- final decoded = _decode(_readFile('.codex/auth.json'));
- final tokens = decoded?['tokens'];
- if (tokens is! Map) return null;
- final id = tokens['account_id'];
- return id is String && id.isNotEmpty ? id : null;
- }
-
- /// The account Claude Code is signed in as: `oauthAccount.accountUuid` in
- /// `~/.claude.json`, which is where it records who it is on every platform.
- /// The token store — Keychain or `.credentials.json` — does not carry it.
- Future<String?> claudeAccountId() async {
- final profile = _decode(_readFile('.claude.json'))?['oauthAccount'];
- if (profile is! Map) return null;
- final id = profile['accountUuid'];
- return id is String && id.isNotEmpty ? id : null;
- }
-
- /// Display metadata from the same profile that supplies [claudeAccountId].
- Future<String?> claudeAccountEmail() async {
- final profile = _decode(_readFile('.claude.json'))?['oauthAccount'];
- return profile is Map ? _email(profile['emailAddress']) : null;
- }
-
- /// The ID token's email is a display label, never an authentication decision.
- Future<String?> codexAccountEmail() async {
- final tokens = _decode(_readFile('.codex/auth.json'))?['tokens'];
- final token = tokens is Map ? tokens['id_token'] : null;
- if (token is! String) return null;
- final parts = token.split('.');
- if (parts.length != 3) return null;
- try {
- final claims = _decode(
- utf8.decode(base64Url.decode(base64Url.normalize(parts[1]))),
- );
- return _email(claims?['email']);
- } on FormatException {
- return null;
- }
- }
-
- String? _email(Object? value) =>
- value is String && value.trim().isNotEmpty ? value.trim() : null;
-
- UsageToken? _parseClaude(String? raw) {
- if (raw == null) return null;
- final oauth = _decode(raw)?['claudeAiOauth'];
- if (oauth is! Map) return null;
- final access = oauth['accessToken'];
- if (access is! String || access.isEmpty) return null;
- final expires = oauth['expiresAt'];
- return UsageToken(
- accessToken: access,
- expiresAt: expires is num
- ? DateTime.fromMillisecondsSinceEpoch(expires.round())
- : null,
- );
- }
-
- Map<String, Object?>? _decode(String? raw) {
- if (raw == null) return null;
- try {
- final decoded = jsonDecode(raw);
- return decoded is Map<String, Object?> ? decoded : null;
- } on FormatException {
- // A half-written credentials file is not news: the CLI that owns it is
- // mid-refresh, and the next poll a minute from now will read it whole.
- return null;
- }
- }
-
- String? _readFile(String relative) {
- final home = _home;
- if (home == null) return null;
- final file = File('$home${RuntimePlatform.pathSeparator}$relative');
- if (!file.existsSync()) return null;
- try {
- return file.readAsStringSync();
- } on FileSystemException {
- return null;
- }
- }
-
- /// The macOS Keychain item Claude Code writes — looked up by service AND account, exactly the
- /// way Claude Code reads it back ([keychainService], [keychainAccount]), so this app and the
- /// CLI that signed in cannot be reading two different items.
- ///
- /// `security` is used rather than a plugin because the item is a plain
- /// generic password and this is one read on a timer — a native channel would
- /// be a second thing to keep in step across two platforms for it.
- Future<String?> _readKeychain() async {
- if (!RuntimePlatform.isMacOS && runProcess == null) return null;
- final run = runProcess ?? Process.run;
- final env = _env;
- try {
- final result = await run('security', [
- 'find-generic-password',
- '-a',
- // Claude Code falls back to `os.userInfo().username`; the nearest thing here is LOGNAME.
- keychainAccount(env, username: env['LOGNAME'] ?? 'claude-code-user'),
- '-s',
- keychainService(env),
- '-w',
- ]);
- if (result.exitCode != 0) return null;
- final out = result.stdout;
- return out is String && out.trim().isNotEmpty ? out.trim() : null;
- } on ProcessException {
- return null;
- }
- }
-}
diff --git a/desktop/lib/usage/usage_source.dart b/desktop/lib/usage/usage_source.dart
index 679d088cf..5e5806172 100644
--- a/desktop/lib/usage/usage_source.dart
+++ b/desktop/lib/usage/usage_source.dart
@@ -1,5 +1,3 @@
-import 'package:dio/dio.dart';
-
import 'usage_window.dart';
/// One account's usage, fetched from whoever knows it.
@@ -20,19 +18,6 @@ abstract class UsageSource {
Future<ProviderUsage> read();
}
-/// A Dio configured the way every usage call wants it.
-///
-/// `validateStatus` lets 4xx through so a 401 can be read as "sign in" rather
-/// than surfacing as a transport failure — the split [ApiClient] draws too.
-Dio buildUsageDio({String? baseUrl}) => Dio(
- BaseOptions(
- baseUrl: baseUrl ?? '',
- connectTimeout: const Duration(seconds: 10),
- receiveTimeout: const Duration(seconds: 15),
- validateStatus: (status) => status != null && status >= 200 && status < 600,
- ),
-);
-
/// Turns a finished request into the state the rail should draw.
///
/// Shared because the two vendors fail in the same four ways even though they
diff --git a/desktop/test/api_connections_test.dart b/desktop/test/api_connections_test.dart
index f5336b439..bcb5f23b3 100644
--- a/desktop/test/api_connections_test.dart
+++ b/desktop/test/api_connections_test.dart
@@ -13,6 +13,8 @@ import 'package:harness/models/model_manager_controller.dart';
import 'package:harness/models/models_panel.dart';
import 'package:harness/widgets/api_picker_form.dart';
import 'package:harness/usage/models_menu_controller.dart';
+import 'package:harness/usage/usage_accounts.dart';
+import 'package:harness/usage/usage_window.dart';
import 'package:harness/ws/ws_conn.dart';
import 'package:harness/shared/theme/app_theme.dart' as grid;
@@ -453,7 +455,19 @@ void main() {
addTearDown(tester.view.resetDevicePixelRatio);
final app = _ApiApp();
final controller = ModelManagerController(app, poll: false);
- final subscriptions = ModelsMenuController();
+ final subscriptions = ModelsMenuController(
+ remote: () async => [
+ MachineUsage(
+ machineName: 'This computer',
+ isLocal: true,
+ readings: [
+ for (final provider in UsageProvider.values)
+ ProviderUsage.loading(provider),
+ ],
+ ),
+ ],
+ );
+ await subscriptions.refresh();
addTearDown(() {
controller.dispose();
subscriptions.dispose();
@@ -965,7 +979,19 @@ void main() {
];
app.allPresets = true;
final controller = ModelManagerController(app, poll: false);
- final subscriptions = ModelsMenuController();
+ final subscriptions = ModelsMenuController(
+ remote: () async => [
+ MachineUsage(
+ machineName: 'This computer',
+ isLocal: true,
+ readings: [
+ for (final provider in UsageProvider.values)
+ ProviderUsage.loading(provider),
+ ],
+ ),
+ ],
+ );
+ await subscriptions.refresh();
addTearDown(() {
controller.dispose();
subscriptions.dispose();
diff --git a/desktop/test/grid_model_picker_test.dart b/desktop/test/grid_model_picker_test.dart
index 879afd200..de68f3c7b 100644
--- a/desktop/test/grid_model_picker_test.dart
+++ b/desktop/test/grid_model_picker_test.dart
@@ -336,7 +336,7 @@ void main() {
await tester.pumpAndSettle();
final subscription = tester
.widgetList<ModelPickerRow>(find.byType(ModelPickerRow))
- .singleWhere((row) => row.title == 'OpenAI');
+ .singleWhere((row) => row.title == 'Codex');
expect(subscription.selected, isTrue);
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pumpAndSettle();
@@ -368,10 +368,11 @@ void main() {
// A picker that can only move an agent ONTO a grid is a one-way door, so the engine's own login
// is always the first row. It is named the way the window's own Models menu names it — by
- // PROVIDER ('Anthropic'), not by engine ('Claude') — so the two controls agree about what the
+ // PROVIDER ('Claude'), not by engine ('Claude') — so the two controls agree about what the
// thing is called, and it carries that menu's status text beside it.
- expect(find.text('Anthropic').last, findsOneWidget);
- expect(find.textContaining('usage'), findsOneWidget);
+ expect(find.text('Claude').last, findsOneWidget);
+ expect(find.textContaining('usage'), findsNothing);
+ // The fixture supplies model inventory, not a CLI usage report.
});
testWidgets(
@@ -399,7 +400,7 @@ void main() {
),
),
);
- expect(find.text('OpenAI'), findsNothing);
+ expect(find.text('Codex'), findsNothing);
controller.open();
await tester.pumpAndSettle();
expect(find.text('local-model'), findsOneWidget);
@@ -874,13 +875,13 @@ void main() {
var calls = 0;
// Already on its own login: re-selecting it would respawn the pane for nothing.
await open(tester, currentModel: null, onOwnLogin: () => calls++);
- await tester.tap(find.text('Anthropic').last);
+ await tester.tap(find.text('Claude').last);
await tester.pumpAndSettle();
expect(calls, 0);
// On a grid model: now it has somewhere to go.
await open(tester, currentModel: 'Qwen-Test', onOwnLogin: () => calls++);
- await tester.tap(find.text('Anthropic').last);
+ await tester.tap(find.text('Claude').last);
await tester.pumpAndSettle();
expect(calls, 1);
},
@@ -900,7 +901,7 @@ void main() {
);
await open(tester);
- for (final row in ['Anthropic', 'Qwen-Test']) {
+ for (final row in ['Claude', 'Qwen-Test']) {
final inkWell = tester.widget<InkWell>(
find.ancestor(of: find.text(row), matching: find.byType(InkWell)).first,
);
@@ -1196,7 +1197,7 @@ void main() {
expect(rowFor(tester, 'Qwen-Test').selected, isTrue);
expect(rowFor(tester, 'DeepSeek-Test').selected, isFalse);
- expect(rowFor(tester, 'Anthropic').selected, isFalse);
+ expect(rowFor(tester, 'Claude').selected, isFalse);
expect(find.byIcon(AppIcons.check), findsOneWidget);
expect(
find.descendant(
@@ -1226,12 +1227,12 @@ void main() {
);
await open(tester);
- expect(rowFor(tester, 'Anthropic').selected, isTrue);
+ expect(rowFor(tester, 'Claude').selected, isTrue);
expect(rowFor(tester, 'Qwen-Test').selected, isFalse);
expect(find.byIcon(AppIcons.check), findsOneWidget);
expect(
find.descendant(
- of: find.byWidget(rowFor(tester, 'Anthropic')),
+ of: find.byWidget(rowFor(tester, 'Claude')),
matching: find.byIcon(AppIcons.check),
),
findsOneWidget,
@@ -1354,7 +1355,7 @@ void main() {
isTrue,
reason: 'a restarting pane is not an answer',
);
- expect(ticked(tester, 'Anthropic'), isFalse);
+ expect(ticked(tester, 'Claude'), isFalse);
// And comes back up on what was asked for.
report('gemma-4-31B-it');
@@ -1399,15 +1400,15 @@ void main() {
);
final report = await openLive(tester, currentModel: 'gemma-4-31B-it');
- await tester.tap(find.text('Anthropic').last);
+ await tester.tap(find.text('Claude').last);
await tester.pumpAndSettle();
await tester.tap(find.byType(GridModelPicker));
await tester.pumpAndSettle();
- expect(ticked(tester, 'Anthropic'), isTrue);
+ expect(ticked(tester, 'Claude'), isTrue);
report(null);
await tester.pumpAndSettle();
- expect(ticked(tester, 'Anthropic'), isTrue);
+ expect(ticked(tester, 'Claude'), isTrue);
expect(ticked(tester, 'gemma-4-31B-it'), isFalse);
// And the guess is RELEASED by that confirmation, not merely agreed with: the next thing the
@@ -1416,7 +1417,7 @@ void main() {
report('gemma-4-31B-it');
await tester.pumpAndSettle();
expect(ticked(tester, 'gemma-4-31B-it'), isTrue);
- expect(ticked(tester, 'Anthropic'), isFalse);
+ expect(ticked(tester, 'Claude'), isFalse);
},
);
diff --git a/desktop/test/resource_picker_test.dart b/desktop/test/resource_picker_test.dart
index 1e847de88..aabfe6826 100644
--- a/desktop/test/resource_picker_test.dart
+++ b/desktop/test/resource_picker_test.dart
@@ -1,4 +1,6 @@
import 'support/open_harness.dart';
+import 'package:harness/usage/usage_accounts.dart';
+import 'package:harness/usage/usage_window.dart';
import 'dart:io';
import 'dart:async';
@@ -60,8 +62,26 @@ Future<void> tabTo(
fail('Tab could not reach $target');
}
+/// Explicit CLI reports keep model-search fixtures independent of Desktop defaults.
+class _ReportedModelApp extends ModelManagerTestApp {
+ _ReportedModelApp() : super(ModelManagerConnection());
+
+ @override
+ Future<List<MachineUsage>> readRemoteUsage() async => [
+ MachineUsage(
+ machineName: 'This computer',
+ isLocal: true,
+ readings: [
+ for (final provider in UsageProvider.values)
+ ProviderUsage.loading(provider),
+ ],
+ ),
+ ];
+}
+
Future<ModelManagerTestApp> fixture({ModelManagerTestApp? provided}) async {
- final app = provided ?? ModelManagerTestApp(ModelManagerConnection());
+ final app = provided ?? _ReportedModelApp();
+ await app.modelsMenu.refresh();
await seedPreviews(app);
app.adoptSessionForTest(terminal('a69', []));
app.machineStates['m']!.dsh.replace(const [
@@ -166,8 +186,7 @@ class _MachineApp extends ModelManagerTestApp {
Future<String?> clearRemotePassword() => change('clear', 'm', '');
}
-class _ModelSelectionApp extends ModelManagerTestApp {
- _ModelSelectionApp() : super(ModelManagerConnection());
+class _ModelSelectionApp extends _ReportedModelApp {
bool completeStarts = false;
@override
diff --git a/desktop/test/resting_model_picker_test.dart b/desktop/test/resting_model_picker_test.dart
index e7acca9da..18be36b15 100644
--- a/desktop/test/resting_model_picker_test.dart
+++ b/desktop/test/resting_model_picker_test.dart
@@ -57,50 +57,50 @@ void main() {
double top(WidgetTester tester, Finder finder) =>
tester.getTopLeft(finder).dy;
- testWidgets('with no new field the menu is exactly the one it always was', (
- tester,
- ) async {
- // What the build before this one drew for this very answer, text for text, captured from it.
- serve([
- section(
- 'home',
- own: true,
- models: [
- row('Qwen3.5-4B', 'macbook'),
- // An older daemon folds the label into the node; this build shows it as it comes.
- row('LFM2.5-8B', 'studio · seems offline'),
- ],
- ),
- section('team', models: [row('DeepSeek-V4-Flash', 'scholes-60001')]),
- section('empty-team'),
- ]);
- await open(tester, currentModel: 'Qwen3.5-4B');
- expect(textsUnder(tester), [
- 'Qwen3.5-4B',
- 'Search models or machines',
- 'Subscription',
- 'Anthropic',
- 'Checking usage…',
- 'On your machines',
- '2',
- 'Qwen3.5-4B',
- 'macbook',
- 'LFM2.5-8B',
- 'studio · seems offline',
- 'Shared · team',
- '1',
- 'DeepSeek-V4-Flash',
- 'scholes-60001',
- '3 models available',
- 'Local models',
- ]);
- // No row is greyed and no pick is gated: nothing said any of them was offline.
- for (final row in tester.widgetList<ModelPickerRow>(
- find.byType(ModelPickerRow),
- )) {
- expect(row.dimmed, isFalse);
- }
- });
+ testWidgets(
+ 'older model replies keep their rows without inventing a usage report',
+ (tester) async {
+ // Model compatibility is independent of CLI usage. No CLI report means no usage row.
+ serve([
+ section(
+ 'home',
+ own: true,
+ models: [
+ row('Qwen3.5-4B', 'macbook'),
+ // An older daemon folds the label into the node; this build shows it as it comes.
+ row('LFM2.5-8B', 'studio · seems offline'),
+ ],
+ ),
+ section('team', models: [row('DeepSeek-V4-Flash', 'scholes-60001')]),
+ section('empty-team'),
+ ]);
+ await open(tester, currentModel: 'Qwen3.5-4B');
+ expect(textsUnder(tester), [
+ 'Qwen3.5-4B',
+ 'Search models or machines',
+ 'Subscription',
+ 'Claude',
+ 'On your machines',
+ '2',
+ 'Qwen3.5-4B',
+ 'macbook',
+ 'LFM2.5-8B',
+ 'studio · seems offline',
+ 'Shared · team',
+ '1',
+ 'DeepSeek-V4-Flash',
+ 'scholes-60001',
+ '3 models available',
+ 'Local models',
+ ]);
+ // No row is greyed and no pick is gated: nothing said any of them was offline.
+ for (final row in tester.widgetList<ModelPickerRow>(
+ find.byType(ModelPickerRow),
+ )) {
+ expect(row.dimmed, isFalse);
+ }
+ },
+ );
testWidgets('every read the picker makes asks for row state', (tester) async {
serve([
diff --git a/desktop/test/swarm_first_join_paths_test.dart b/desktop/test/swarm_first_join_paths_test.dart
index 33ddf0652..a1922c255 100644
--- a/desktop/test/swarm_first_join_paths_test.dart
+++ b/desktop/test/swarm_first_join_paths_test.dart
@@ -1,136 +1,48 @@
import 'package:flutter_test/flutter_test.dart';
-import 'package:harness/state/app_state.dart';
-import 'package:harness/state/swarm.dart';
-import 'super_tab_launch_test.dart' show SuperTabLaunchFixture, tabId;
-
-// Task #3791 (Scholes, 11-06): a new member on Desktop 1.3.82 still had to click Add machine and never saw the Harness
-// Team account / My account choice. The join's add (#3115) and its choice (#3178) must run on every first join, however
-// it happened, once for each Swarm on this computer and account, and never for a computer the person removed (#3138).
-
-/// A fresh install's app: signed in, this Mac's own row not known yet, so nothing can be added until it is, and the
-/// Swarm's server state naming the person a collaborator.
-SuperTabLaunchFixture _freshComputer({bool chooseTeam = true}) {
- final f = SuperTabLaunchFixture();
- f.app.status = AppStatus.authenticated;
- f.app.teamAccountHereForTest = false;
- f.connection.teamCheck = {'state': 'wanted'};
- f.connection.server.state
- ..['ownerId'] = 'boss'
- ..['people'] = <dynamic>[
- {'id': 'boss', 'email': '[email protected]', 'role': 'owner'},
- {'id': 'owner', 'email': '[email protected]', 'role': 'collaborator'},
- ];
- if (chooseTeam) {
- f.app.addListener(() => f.app.joinAccountRequest?.complete(false));
- }
- return f;
-}
-
-/// What the Join Swarm dialog does once the server took the join
-/// (`SwarmJoinDialog._join`): opens the Swarm, then asks for the add.
-Future<void> _joinInTheDialog(SuperTabLaunchFixture f) async {
- f.app.openSuperTab(tabId, 'Swarm');
- await f.app.addMachineOnJoin(tabId, role: 'collaborator');
-}
-
-/// One discovery, and the add it started run to its end.
-Future<void> _discover(SuperTabLaunchFixture f) async {
- await f.app.superTabs.refreshTabs();
- await f.app.joinAddPassForTest;
- await pumpEventQueue();
-}
-
-List<Map> _contributions(SuperTabLaunchFixture f) => [
- for (final post in f.connection.server.posts)
- if ((post['command'] as Map)['type'] == 'machine.contribute')
- post['command'] as Map,
-];
+import 'super_tab_launch_test.dart' show tabId;
+import 'swarm_join_any_test.dart' show newMember, discover, expectNoEnrollment;
void main() {
- test('an invite joined before this Mac\'s own row is known adds it once the row is, with no click', () async {
- final f = _freshComputer();
- await _joinInTheDialog(f);
- // Nothing could be added yet: this Mac's own row was not known.
- expect(_contributions(f), isEmpty);
-
- // The row arrives; the person never opens Machines. The first discovery
- // for this account must not take the Swarm they just joined as one they
- // already had (the update's baseline).
- f.app.teamAccountHereForTest = true;
- await _discover(f);
- expect(_contributions(f), [containsPair('teamAccountOnly', true)]);
+ test('link join and later discovery offer only one bring prompt', () async {
+ final f = newMember();
+ var prompts = 0;
+ f.app.addListener(() {
+ if (f.app.joinAccountRequest case final request?) {
+ prompts++;
+ request.complete(false);
+ }
+ });
+ f.app.openSuperTab(tabId, 'Pilot');
+ await f.app.addMachineOnJoin(tabId, role: 'collaborator');
+ await discover(f);
+ expect(prompts, 1);
+ expectNoEnrollment(f);
});
- test('the account choice appears for an invite joined before this Mac\'s own row is known', () async {
- final f = _freshComputer(chooseTeam: false);
- await _joinInTheDialog(f);
- f.app.teamAccountHereForTest = true;
- // The add waits for the person's answer, so the pass is not awaited here.
- await f.app.superTabs.refreshTabs();
- await pumpEventQueue();
- expect(f.app.joinAccountRequest, isNotNull);
- expect(f.app.joinAccountRequest!.swarmName, isNotEmpty);
- f.app.joinAccountRequest!.complete(false);
- await f.app.joinAddPassForTest;
- expect(_contributions(f), [containsPair('teamAccountOnly', true)]);
- });
-
- test('a domain auto-join listed at sign-in, then opened here, is added with the choice when this Mac\'s row is known', () async {
- // River, 11-06: the Swarm arrives at sign-in, before the add and the choice can run, and was then taken as one
- // the person already had. No dialog: the server joined them as someone at the owner's email domain.
- final f = _freshComputer(chooseTeam: false);
- (f.connection.server.state['people'] as List)[1]['joinedVia'] = 'domain';
- // Sign-in's discovery lists the Swarm; no Swarm view is open, so nothing runs.
- await f.app.superTabs.refreshTabs();
- await f.app.joinAddPassForTest;
- expect(_contributions(f), isEmpty);
-
- // The Swarm is shown (it is the person's only one), and this Mac's row arrives.
- f.app.openSuperTab(tabId, 'Swarm');
- f.app.teamAccountHereForTest = true;
- await f.app.superTabs.refreshTabs();
- await pumpEventQueue();
- expect(f.app.joinAccountRequest, isNotNull);
- f.app.joinAccountRequest!.complete(false);
- await f.app.joinAddPassForTest;
- expect(_contributions(f), [containsPair('teamAccountOnly', true)]);
- });
-
- test('a computer the person removed stays out of an invite joined before its row is known', () async {
- final f = _freshComputer();
- f.connection.server.state['removedMachines'] = ['m'];
- await _joinInTheDialog(f);
- f.app.teamAccountHereForTest = true;
- await _discover(f);
- expect(_contributions(f), isEmpty);
- expect(f.app.joinAccountRequest, isNull);
- });
-
- test('a Swarm the person hid before the update and reopens is still never added or asked about', () async {
- // Review of #3367: reopening clears the hidden state at once, so the reopened Swarm must still read as one they had.
- final f = _freshComputer(chooseTeam: false);
- await f.app.superTabs.setTabVisible(tabId, false);
- expect(f.app.superTabs.hiddenIds, contains(tabId));
- f.app.openSuperTab(tabId, 'Swarm');
- f.app.teamAccountHereForTest = true;
- // Not _discover: an add would wait for the person's answer.
- await f.app.superTabs.refreshTabs();
- await pumpEventQueue();
- expect(f.app.joinAccountRequest, isNull);
- expect(_contributions(f), isEmpty);
- });
-
- test('a Swarm the person already had open before the update is still never added', () async {
- // The baseline's own job (#3115): a long-time member's Swarms stay as they chose.
- final f = _freshComputer();
- // Restored from the saved layout at launch: not opened in this run.
- f.app.swarms.add(
- Swarm(id: 'restored', name: 'Swarm', nameIsCustom: true, kind: 'superTab')
- ..superTabId = tabId,
- );
- f.app.teamAccountHereForTest = true;
- await _discover(f);
- expect(_contributions(f), isEmpty);
- });
+ test(
+ 'existing membership never offers bringing from the join result',
+ () async {
+ final f = newMember();
+ await f.app.addMachineOnJoin(
+ tabId,
+ role: 'collaborator',
+ alreadyMember: true,
+ );
+ expect(f.app.joinAccountRequest, isNull);
+ expectNoEnrollment(f);
+ },
+ );
+
+ test(
+ 'a hidden Swarm reopened after the update is not a new membership',
+ () async {
+ final f = newMember();
+ await f.app.superTabs.setTabVisible(tabId, false);
+ f.app.openSuperTab(tabId, 'Pilot');
+ await discover(f);
+ expect(f.app.joinAccountRequest, isNull);
+ expectNoEnrollment(f);
+ },
+ );
}
diff --git a/desktop/test/swarm_first_join_widget_test.dart b/desktop/test/swarm_first_join_widget_test.dart
index 8c0b567e3..da6503ee6 100644
--- a/desktop/test/swarm_first_join_widget_test.dart
+++ b/desktop/test/swarm_first_join_widget_test.dart
@@ -1,164 +1,83 @@
-import 'dart:async';
-
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/shared/theme/app_theme.dart' as grid;
-import 'package:harness/state/app_state.dart';
+import 'package:harness/super_tabs/join/agent_dialog.dart';
import 'package:harness/super_tabs/join_dialog.dart';
-import 'super_tab_launch_test.dart' show SuperTabLaunchFixture, tabId;
-
-// Task #3791 (Scholes, 11-06; Rowtest's review): the first-join paths as a person sees them. Each mounts the join host
-// the workspace mounts (`SwarmJoinHost`), so the account choice is the real dialog, and ends with this Mac added or
-// not, with no click on Add machine. The state-level cases are in swarm_first_join_paths_test.dart.
-
-/// A new member's app: signed in as a collaborator the server joined by their email domain, this Mac's own row known.
-/// [swarmMode] false is a fresh sign-in, before any Swarm view has put the app in Swarm mode.
-SuperTabLaunchFixture _newMember({bool swarmMode = true}) {
- final f = SuperTabLaunchFixture(swarmMode: swarmMode);
- f.app.status = AppStatus.authenticated;
- f.app.teamAccountHereForTest = true;
- f.connection.teamCheck = {'state': 'wanted'};
- f.connection.server.state
- ..['ownerId'] = 'boss'
- ..['people'] = <dynamic>[
- {'id': 'boss', 'email': '[email protected]', 'role': 'owner'},
- {
- 'id': 'owner',
- 'email': '[email protected]',
- 'role': 'collaborator',
- 'joinedVia': 'domain',
- },
- ];
- return f;
-}
+import 'support/capture.dart';
+import 'swarm_join_any_test.dart' show newMember, expectNoEnrollment;
+import 'super_tab_launch_test.dart' show tabId;
-Future<void> _mount(WidgetTester tester, SuperTabLaunchFixture f) async {
- await tester.pumpWidget(
- MaterialApp(
- theme: grid.buildAppTheme(brightness: Brightness.light),
- home: SwarmJoinHost(app: f.app, child: const Scaffold()),
- ),
- );
- addTearDown(() => tester.binding.setSurfaceSize(null));
- await tester.binding.setSurfaceSize(const Size(900, 700));
-}
-
-/// One discovery, with the real timers of the fake server running.
-Future<void> _discover(WidgetTester tester, SuperTabLaunchFixture f) async {
- await tester.runAsync(() async {
- await f.app.superTabs.refreshTabs();
- await pumpEventQueue();
- });
- await tester.pump();
- await tester.pump(const Duration(milliseconds: 50));
-}
-
-List<Map> _contributions(SuperTabLaunchFixture f) => [
- for (final post in f.connection.server.posts)
- if ((post['command'] as Map)['type'] == 'machine.contribute')
- post['command'] as Map,
-];
-
-/// The person answers the choice with its default, a separate Harness Team account, and waits for the add.
-Future<void> _continueWithTeamAccount(
- WidgetTester tester,
- SuperTabLaunchFixture f,
-) async {
- expect(find.text('Separate Harness Team account'), findsOneWidget);
- expect(find.text('My account'), findsOneWidget);
- await tester.tap(find.byKey(const Key('swarm-join-account-continue')));
- await tester.pump();
- await tester.runAsync(() async {
- await f.app.joinAddPassForTest;
- await pumpEventQueue();
- });
- await tester.pump(const Duration(milliseconds: 50));
-}
+import 'dart:io';
void main() {
- testWidgets(
- 'a domain auto-join listed at sign-in, then opened from the picker, shows the choice and adds this Mac',
- (tester) async {
- // Sign-in's discovery lists the Swarm before the app is in Swarm mode: the result is dropped. The person then
- // opens that Swarm, so it is open here by the time the first pass that can add runs; it must still be new.
- final f = _newMember(swarmMode: false);
- await _mount(tester, f);
- await _discover(tester, f);
- expect(find.text('Separate Harness Team account'), findsNothing);
- expect(_contributions(f), isEmpty);
-
- f.app.openSuperTab(tabId, 'Swarm');
- await _discover(tester, f);
- await _continueWithTeamAccount(tester, f);
- expect(_contributions(f), [containsPair('teamAccountOnly', true)]);
- expect(_contributions(f).single['machineId'], 'm');
- },
- );
-
- testWidgets(
- 'a Swarm joined on the phone or in a Workspace, listed when Swarm mode is on, shows the choice and adds this Mac',
- (tester) async {
- final f = _newMember();
- await _mount(tester, f);
- await _discover(tester, f);
- await _continueWithTeamAccount(tester, f);
- expect(_contributions(f), [containsPair('teamAccountOnly', true)]);
- },
- );
-
- testWidgets(
- 'an invite joined in the dialog before this Mac\'s row is known shows the choice once it is, and adds this Mac',
- (tester) async {
- final f = _newMember();
- f.app.teamAccountHereForTest = false;
- await _mount(tester, f);
- // What the dialog does once the server took the join: opens the Swarm, then asks for the add.
- f.app.openSuperTab(tabId, 'Swarm');
- await tester.runAsync(
- () => f.app.addMachineOnJoin(tabId, role: 'collaborator'),
+ final shots = Platform.environment['HARNESS_V3_JOIN_SHOTS'];
+ setUpAll(() => loadCaptureFonts(shots));
+ for (final brightness in Brightness.values) {
+ testWidgets('new membership brings own agent in ${brightness.name}', (
+ tester,
+ ) async {
+ grid.AppTheme.brightness.value = brightness;
+ addTearDown(() => grid.AppTheme.brightness.value = Brightness.light);
+ final f = newMember();
+ await tester.binding.setSurfaceSize(const Size(1000, 760));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ await tester.pumpWidget(
+ MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: grid.buildAppTheme(brightness: brightness),
+ home: SwarmJoinHost(app: f.app, child: const Scaffold()),
+ ),
);
+ late Future<void> joining;
+ await tester.runAsync(() async {
+ joining = f.app.addMachineOnJoin(tabId, role: 'collaborator');
+ await pumpEventQueue();
+ });
await tester.pump();
+ await tester.runAsync(() async => pumpEventQueue());
+ await tester.pumpAndSettle();
+ expect(find.byType(SwarmAgentDialog), findsOneWidget);
+ expect(find.text('Bring your agent'), findsOneWidget);
expect(find.text('Separate Harness Team account'), findsNothing);
-
- f.app.teamAccountHereForTest = true;
- await _discover(tester, f);
- await _continueWithTeamAccount(tester, f);
- expect(_contributions(f), [containsPair('teamAccountOnly', true)]);
- },
- );
-
- testWidgets(
- 'a Swarm the person hid and reopens shows no choice and adds nothing',
- (tester) async {
- final f = _newMember();
- await _mount(tester, f);
- // The hidden id is set at once; its saved write is not what this checks.
- unawaited(f.app.superTabs.setTabVisible(tabId, false));
- expect(f.app.superTabs.hiddenIds, contains(tabId));
- f.app.openSuperTab(tabId, 'Swarm');
- await _discover(tester, f);
- // Nothing waits for an answer, so the pass ends by itself.
- await tester.runAsync(() => f.app.joinAddPassForTest);
- await tester.pump();
- expect(find.text('Separate Harness Team account'), findsNothing);
- expect(f.app.joinAccountRequest, isNull);
- expect(_contributions(f), isEmpty);
- },
- );
-
- testWidgets(
- 'a computer the person removed from the Swarm shows no choice and stays out',
- (tester) async {
- final f = _newMember();
- f.connection.server.state['removedMachines'] = ['m'];
- await _mount(tester, f);
- await _discover(tester, f);
- await tester.runAsync(() => f.app.joinAddPassForTest);
- await tester.pump();
- expect(find.text('Separate Harness Team account'), findsNothing);
- expect(f.app.joinAccountRequest, isNull);
- expect(_contributions(f), isEmpty);
- },
- );
+ expect(find.text('Add machine'), findsNothing);
+ await captureWindow(tester, shots, 'bring-agent-${brightness.name}');
+ if (brightness == Brightness.dark) {
+ await tester.tap(find.byTooltip('Close').first);
+ await tester.pumpAndSettle();
+ await tester.runAsync(() => joining);
+ expectNoEnrollment(f);
+ } else {
+ await tester.runAsync(() async {
+ await tester.tap(find.byKey(const Key('swarm-agent-submit')));
+ await pumpEventQueue();
+ });
+ await tester.pumpAndSettle();
+ if (find.text('Retry').evaluate().isNotEmpty) {
+ await tester.runAsync(() async {
+ await tester.tap(find.text('Retry'));
+ await pumpEventQueue();
+ });
+ await tester.pumpAndSettle();
+ }
+ expect(find.byType(SwarmAgentDialog), findsNothing);
+ await tester.runAsync(() => joining);
+ final starts = f.connection.server.posts.where(
+ (post) => (post['command'] as Map)['type'] == 'buddy.create',
+ );
+ expect(starts, hasLength(1));
+ expect(f.app.activeSwarm.superTabId, tabId);
+ expect(starts.single['command'], containsPair('engine', 'claude'));
+ expect(starts.single['command'], containsPair('machineId', 'm'));
+ expect(
+ f.connection.server.posts.where(
+ (post) => (post['command'] as Map)['type'] == 'machine.contribute',
+ ),
+ isEmpty,
+ );
+ }
+ await tester.pumpWidget(const SizedBox());
+ f.dispose();
+ });
+ }
}
diff --git a/desktop/test/swarm_join_account_choice_test.dart b/desktop/test/swarm_join_account_choice_test.dart
index 6a25a518b..29918667d 100644
--- a/desktop/test/swarm_join_account_choice_test.dart
+++ b/desktop/test/swarm_join_account_choice_test.dart
@@ -3,14 +3,11 @@ import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/super_tabs/join_dialog.dart';
-import 'package:harness/super_tabs/join_account_choice.dart';
-import 'package:harness/state/app_state.dart';
-import 'package:harness/core/models.dart';
+
import 'package:harness/shared/theme/app_theme.dart' as grid;
import 'package:harness/super_tabs/join_link.dart';
import 'support/capture.dart';
-import 'super_tab_launch_test.dart' show SuperTabLaunchFixture, tabId;
void main() {
final shots = Platform.environment['HARNESS_JOIN_ACCOUNT_SHOTS'];
@@ -37,7 +34,9 @@ void main() {
accountEmail: '[email protected]',
isCurrent: current ?? () => true,
onJoined: (_, _) {},
- onNewMemberAccount: (_, _, own) => selected(own),
+ onNewMember: (_, role) {
+ if (role == 'collaborator') selected(true);
+ },
request: (_, path, {body}) async => path.endsWith('/preview')
? {
'id': 'pilot',
@@ -62,26 +61,13 @@ void main() {
await tester.pumpAndSettle();
}
- testWidgets('Team stays default and preserves setup choice', (tester) async {
- final choices = <bool>[];
- await mount(tester, selected: choices.add);
- expect(find.text('Separate Harness Team account'), findsOneWidget);
- expect(find.text('My account'), findsOneWidget);
- await tester.tap(find.byKey(const Key('swarm-join-confirm')));
- await tester.pumpAndSettle();
- expect(choices, [false]);
- });
-
- testWidgets('own account requires selection after access warning', (
+ testWidgets('join uses the signed-in account without a Team choice', (
tester,
) async {
final choices = <bool>[];
await mount(tester, selected: choices.add);
- expect(find.textContaining('keychain'), findsOneWidget);
- await tester.ensureVisible(find.text('My account'));
- await tester.tap(find.text('My account'));
- await tester.pump();
- expect(choices, isEmpty);
+ expect(find.text('Separate Harness Team account'), findsNothing);
+ expect(find.text('My account'), findsNothing);
await tester.tap(find.byKey(const Key('swarm-join-confirm')));
await tester.pumpAndSettle();
expect(choices, [true]);
@@ -111,8 +97,6 @@ void main() {
(tester) async {
final choices = <bool>[];
await mount(tester, selected: choices.add, resultAlready: true);
- await tester.ensureVisible(find.text('My account'));
- await tester.tap(find.text('My account'));
await tester.tap(find.byKey(const Key('swarm-join-confirm')));
await tester.pumpAndSettle();
expect(choices, isEmpty);
@@ -125,170 +109,9 @@ void main() {
var active = true;
final choices = <bool>[];
await mount(tester, selected: choices.add, current: () => active);
- await tester.ensureVisible(find.text('My account'));
- await tester.tap(find.text('My account'));
active = false;
await tester.tap(find.byKey(const Key('swarm-join-confirm')));
await tester.pumpAndSettle();
expect(choices, isEmpty);
});
- testWidgets(
- 'the Desktop host presents and completes a discovered account choice',
- (tester) async {
- final f = SuperTabLaunchFixture();
- f.app.status = AppStatus.authenticated;
- f.app.teamAccountHereForTest = true;
- f.connection.server.state
- ..['ownerId'] = 'boss'
- ..['people'] = <dynamic>[
- {'id': 'boss', 'email': '[email protected]', 'role': 'owner'},
- {'id': 'owner', 'email': '[email protected]', 'role': 'collaborator'},
- ];
- await tester.pumpWidget(
- MaterialApp(
- home: SwarmJoinHost(
- app: f.app,
- child: const Scaffold(body: Text('workspace')),
- ),
- ),
- );
- late Future<void> joining;
- await tester.runAsync(() async {
- joining = f.app.addMachineOnJoin(tabId, role: 'collaborator');
- for (var i = 0; f.app.joinAccountRequest == null && i < 200; i++) {
- await Future<void>.delayed(const Duration(milliseconds: 10));
- }
- expect(f.app.joinAccountRequest, isNotNull);
- });
- await tester.pumpAndSettle();
- expect(find.byType(SwarmJoinAccountDialog), findsOneWidget);
- await tester.ensureVisible(find.text('My account'));
- await tester.tap(find.text('My account'));
- await tester.tap(find.byKey(const Key('swarm-join-account-continue')));
- await tester.pumpAndSettle();
- await tester.runAsync(() => joining);
- expect(f.app.joinAccountRequest, isNull);
- expect(f.app.teamSetupLocked, isFalse);
- expect(
- f.connection.server.posts.last['command'],
- containsPair('allowed', true),
- );
- await tester.pumpWidget(const SizedBox());
- },
- );
-
- testWidgets(
- 'a queued choice from another account is discarded without showing its Swarm',
- (tester) async {
- final f = SuperTabLaunchFixture();
- f.app.status = AppStatus.authenticated;
- f.app.teamAccountHereForTest = true;
- f.connection.server.state
- ..['ownerId'] = 'boss'
- ..['people'] = <dynamic>[
- {'id': 'boss', 'email': '[email protected]', 'role': 'owner'},
- {'id': 'owner', 'email': '[email protected]', 'role': 'collaborator'},
- ];
- late Future<void> joining;
- await tester.runAsync(() async {
- joining = f.app.addMachineOnJoin(tabId, role: 'collaborator');
- for (var i = 0; f.app.joinAccountRequest == null && i < 200; i++) {
- await Future<void>.delayed(const Duration(milliseconds: 10));
- }
- expect(f.app.joinAccountRequest, isNotNull);
- });
- f.app.currentUser = const CurrentUserProfile(
- id: 'different',
- email: '[email protected]',
- );
- await tester.pumpWidget(
- MaterialApp(
- home: SwarmJoinHost(
- app: f.app,
- child: const Scaffold(body: Text('workspace')),
- ),
- ),
- );
- await tester.pumpAndSettle();
- expect(find.byType(SwarmJoinAccountDialog), findsNothing);
- await tester.runAsync(() => joining);
- expect(f.connection.server.posts, isEmpty);
- await tester.pumpWidget(const SizedBox());
- },
- );
-
- for (final system in ['windows', 'linux']) {
- testWidgets('the account choice uses $system permission wording', (
- tester,
- ) async {
- await tester.pumpWidget(
- MaterialApp(
- home: Scaffold(
- body: SwarmJoinAccountChoice(
- ownAccount: false,
- onChanged: (_) {},
- operatingSystem: system,
- ),
- ),
- ),
- );
- expect(find.textContaining('this computer'), findsWidgets);
- expect(find.textContaining('this Mac'), findsNothing);
- expect(find.textContaining('your Mac'), findsNothing);
- expect(
- find.textContaining(
- system == 'windows'
- ? 'Windows administrator permission'
- : 'computer password',
- ),
- findsOneWidget,
- );
- });
- }
-
- for (final brightness in Brightness.values) {
- testWidgets(
- 'join account choices fit and remain usable in ${brightness.name}',
- (tester) async {
- grid.AppTheme.brightness.value = brightness;
- addTearDown(() => grid.AppTheme.brightness.value = Brightness.light);
- await tester.binding.setSurfaceSize(const Size(900, 800));
- addTearDown(() => tester.binding.setSurfaceSize(null));
- await mount(tester, selected: (_) {}, brightness: brightness);
- expect(tester.takeException(), isNull);
- await captureWindow(
- tester,
- shots,
- 'join-account-team-${brightness.name}',
- );
- await tester.ensureVisible(find.text('My account'));
- await tester.tap(find.text('My account'));
- await tester.pumpAndSettle();
- await captureWindow(
- tester,
- shots,
- 'join-account-own-${brightness.name}',
- );
- await tester.pumpWidget(const SizedBox());
- await tester.pump();
- await tester.pumpWidget(
- MaterialApp(
- theme: grid.buildAppTheme(brightness: brightness),
- home: const Scaffold(
- body: SwarmJoinAccountDialog(swarmName: 'Pilot'),
- ),
- ),
- );
- await tester.pumpAndSettle();
- expect(tester.takeException(), isNull);
- expect(find.byType(SwarmJoinDialog), findsNothing);
- expect(find.byType(SwarmJoinAccountDialog), findsOneWidget);
- await captureWindow(
- tester,
- shots,
- 'join-account-discovery-${brightness.name}',
- );
- },
- );
- }
}
diff --git a/desktop/test/swarm_join_any_test.dart b/desktop/test/swarm_join_any_test.dart
index 8eec34ec8..7d923a8c8 100644
--- a/desktop/test/swarm_join_any_test.dart
+++ b/desktop/test/swarm_join_any_test.dart
@@ -2,30 +2,15 @@ import 'package:fake_async/fake_async.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/state/app_state.dart';
import 'package:harness/state/swarm.dart';
-import 'package:harness/super_tabs/join_machine.dart';
-import 'package:harness/ws/ws_conn.dart';
import 'super_tab_launch_test.dart' show SuperTabLaunchFixture, tabId;
-// Task #3160 (Scholes, 11-05): about a dozen new members joined through a
-// domain auto-join, a Workspace-open join or on the phone or web first, and
-// were never offered the Harness Team account: the add ran only from
-// Desktop's own join dialog. Discovery now runs it once for any Swarm new here.
-
-/// This Mac's app, signed in, its Swarm list naming one Swarm the person is
-/// in as [role], joined on the server (a domain auto-join) with no client
-/// asking.
-SuperTabLaunchFixture _computer({
- String role = 'collaborator',
- bool chooseTeam = true,
-}) {
+SuperTabLaunchFixture newMember({String role = 'collaborator'}) {
final f = SuperTabLaunchFixture();
f.app.status = AppStatus.authenticated;
- f.app.teamAccountHereForTest = true;
- f.connection.teamCheck = {'state': 'wanted'};
f.connection.server.state
..['ownerId'] = 'boss'
- ..['people'] = <dynamic>[
+ ..['people'] = [
{'id': 'boss', 'email': '[email protected]', 'role': 'owner'},
{
'id': 'owner',
@@ -34,328 +19,96 @@ SuperTabLaunchFixture _computer({
'joinedVia': 'domain',
},
];
- if (chooseTeam) {
- f.app.addListener(() => f.app.joinAccountRequest?.complete(false));
- }
return f;
}
-/// One discovery, and the add it started run to its end.
-Future<void> _discover(SuperTabLaunchFixture f) async {
+Future<void> discover(SuperTabLaunchFixture f) async {
await f.app.superTabs.refreshTabs();
await f.app.joinAddPassForTest;
- // The notes reach their listeners after it.
- await pumpEventQueue();
}
-List<Map> _contributions(SuperTabLaunchFixture f) => [
- for (final post in f.connection.server.posts)
- if ((post['command'] as Map)['type'] == 'machine.contribute')
- post['command'] as Map,
-];
-
-List<Map> _teamOffers(SuperTabLaunchFixture f) => [
- for (final (type, payload) in f.connection.calls)
- if (type == 'super_tabs' && payload['action'] == 'teamSetupCheck') payload,
-];
-
-/// The Swarm's first loads: each is a read of its whole state.
-int _firstLoads(SuperTabLaunchFixture f) => [
- for (final (type, payload) in f.connection.calls)
- if (type == 'super_tabs' &&
- payload['method'] == 'GET' &&
- payload['path'] == '/api/super-tabs/$tabId/parts')
- payload,
-].length;
+void expectNoEnrollment(SuperTabLaunchFixture f) {
+ expect(f.connection.server.posts, isEmpty);
+ expect(
+ f.connection.calls.where((c) => c.$2['action'] == 'teamSetupCheck'),
+ isEmpty,
+ );
+}
void main() {
- test('explicit own-account join skips every Team setup offer', () async {
- final f = _computer();
- final notes = <SwarmJoinedMachine>[];
- final listening = f.app.joinedMachines.listen(notes.add);
- await f.app.addMachineOnJoin(tabId, role: 'collaborator', ownAccount: true);
- await pumpEventQueue();
- expect(_teamOffers(f), isEmpty);
- expect(f.app.teamSetupLocked, isFalse);
- expect(notes.single.ownAccount, isTrue);
- expect(f.connection.server.posts.last['command'], {
- 'type': 'machine.ownAccountWork',
- 'machineId': 'm',
- 'allowed': true,
- });
- await listening.cancel();
- });
-
- test('discovery asks where agents run before adding the computer', () async {
- final f = _computer(chooseTeam: false);
- var asked = 0;
+ test('domain discovery offers bringing an agent once and never enrolls a machine', () async {
+ final f = newMember();
+ var prompts = 0;
f.app.addListener(() {
final request = f.app.joinAccountRequest;
- if (request == null || request.answered) return;
- expect(_contributions(f), isEmpty);
- asked++;
- request.complete(true);
+ if (request == null) return;
+ prompts++;
+ expect(request.tabId, tabId);
+ request.complete(false);
});
- await _discover(f);
- expect(asked, 1);
- expect(_teamOffers(f), isEmpty);
- expect(
- f.connection.server.posts.last['command'],
- containsPair('allowed', true),
- );
- });
-
- test('cancelled choice contributes nothing and starts no setup', () async {
- final f = _computer(chooseTeam: false);
- final notes = <SwarmJoinedMachine>[];
- final listening = f.app.joinedMachines.listen(notes.add);
- f.app.addListener(() => f.app.joinAccountRequest?.complete(null));
- await _discover(f);
- expect(_contributions(f), isEmpty);
- expect(_teamOffers(f), isEmpty);
- expect(notes.single.added, isFalse);
- expect(notes.single.problem, 'Add it from Machines.');
- await listening.cancel();
+ await discover(f);
+ await discover(f);
+ expect(prompts, 1);
+ expectNoEnrollment(f);
+ expect(f.app.superTabs.peek(tabId), isNull);
+ final restarted = newMember();
+ restarted.store.values.addAll(f.store.values);
+ await discover(restarted);
+ expect(restarted.app.joinAccountRequest, isNull);
+ expectNoEnrollment(restarted);
});
- test(
- 'expired account choice says the computer was not added and how to add it',
- () {
- fakeAsync((time) {
- final f = _computer(chooseTeam: false);
- final notes = <SwarmJoinedMachine>[];
- f.app.joinedMachines.listen(notes.add);
- var finished = false;
- f.app
- .addMachineOnJoin(tabId, role: 'collaborator')
- .then((_) => finished = true);
- time.elapse(const Duration(seconds: 5));
- expect(f.app.joinAccountRequest, isNotNull);
- expect(finished, isFalse);
- expect(notes, isEmpty);
- time.elapse(const Duration(minutes: 15));
- expect(finished, isTrue);
- expect(_contributions(f), isEmpty);
- expect(_teamOffers(f), isEmpty);
- expect(notes.single.added, isFalse);
- expect(notes.single.problem, 'Add it from Machines.');
- f.dispose();
- });
- },
- );
-
- test(
- 'account change while choosing never contributes or sends consent',
- () async {
- final f = _computer(chooseTeam: false);
- f.app.addListener(() {
- final request = f.app.joinAccountRequest;
- if (request == null || request.answered) return;
- f.app.currentUser = null;
- request.complete(true);
- });
- await _discover(f);
- expect(_contributions(f), isEmpty);
- expect(_teamOffers(f), isEmpty);
- },
- );
-
- test(
- 'refused own-account setting never starts Team setup as an alternative',
- () async {
- final f = _computer();
- f.connection.server.unknownCommand = (c) =>
- c['type'] == 'machine.ownAccountWork';
- final notes = <SwarmJoinedMachine>[];
- final listening = f.app.joinedMachines.listen(notes.add);
- await f.app.addMachineOnJoin(
- tabId,
- role: 'collaborator',
- ownAccount: true,
- );
- await pumpEventQueue();
- expect(_teamOffers(f), isEmpty);
- expect(notes.single.ownAccount, isFalse);
- expect(notes.single.accountProblem, isNotEmpty);
- await listening.cancel();
- },
- );
-
- test('a Swarm first seen through a domain auto-join adds this Mac and offers the Team account, once', () async {
- final f = _computer();
- final notes = <SwarmJoinedMachine>[];
- final listening = f.app.joinedMachines.listen(notes.add);
- await _discover(f);
- expect(_contributions(f), [containsPair('teamAccountOnly', true)]);
- expect(_contributions(f).single['machineId'], 'm');
- expect(_teamOffers(f), [
- {'action': 'teamSetupCheck', 'reason': 'join', 'tabId': tabId},
- ]);
- expect(notes.map((n) => (n.tabId, n.added)), [(tabId, true)]);
- expect(f.app.teamSetupLocked, isTrue);
+ for (final role in ['viewer', 'owner']) {
+ test('$role is not prompted by first-member discovery', () async {
+ final f = newMember(role: role);
+ await discover(f);
+ await discover(f);
+ expect(f.app.joinAccountRequest, isNull);
+ expectNoEnrollment(f);
+ });
+ }
- // The person removed this Mac again: the next discovery leaves it so.
- f.connection.server.state['machines'] = <dynamic>[];
- await _discover(f);
- expect(_contributions(f), hasLength(1));
- expect(_teamOffers(f), hasLength(1));
- expect(notes, hasLength(1));
- await listening.cancel();
+ test('account change while bringing starts nothing', () async {
+ final f = newMember();
+ f.app.addListener(() {
+ final request = f.app.joinAccountRequest;
+ if (request == null) return;
+ f.app.currentUser = null;
+ request.complete(null);
+ });
+ await discover(f);
+ expectNoEnrollment(f);
});
- test(
- 'it never runs again for the same Swarm and person after a restart',
- () async {
- final first = _computer();
- await _discover(first);
- expect(_contributions(first), hasLength(1));
-
- final restarted = _computer();
- restarted.store.values.addAll(first.store.values);
- await _discover(restarted);
- expect(_contributions(restarted), isEmpty);
- expect(_teamOffers(restarted), isEmpty);
- },
- );
-
- test('a viewer is never added and never offered the Team account', () async {
- final f = _computer(role: 'viewer');
- final notes = <SwarmJoinedMachine>[];
- final listening = f.app.joinedMachines.listen(notes.add);
- await _discover(f);
- await _discover(f);
- expect(_contributions(f), isEmpty);
- expect(_teamOffers(f), isEmpty);
- expect(notes, isEmpty);
- await listening.cancel();
+ test('an unanswered bring prompt expires without enrollment', () {
+ fakeAsync((time) {
+ final f = newMember();
+ var ended = false;
+ f.app
+ .addMachineOnJoin(tabId, role: 'collaborator')
+ .then((_) => ended = true);
+ time.flushMicrotasks();
+ expect(f.app.joinAccountRequest, isNotNull);
+ expect(ended, isFalse);
+ time.elapse(const Duration(minutes: 15));
+ expect(ended, isTrue);
+ expect(f.app.joinAccountRequest, isNull);
+ expectNoEnrollment(f);
+ f.dispose();
+ });
});
test(
- 'a Swarm already shown on this computer before the update is left as it is',
+ 'restored Swarms keep their existing membership without a prompt',
() async {
- final f = _computer();
- // Restored from the saved layout at launch, as a long-time member's Swarm
- // is; a Swarm opened in this run is new here (task #3791).
+ final f = newMember();
f.app.swarms.add(
- Swarm(
- id: 'restored',
- name: 'Pilot',
- nameIsCustom: true,
- kind: 'superTab',
- )..superTabId = tabId,
+ Swarm(id: 'restored', name: 'Pilot', kind: 'superTab')
+ ..superTabId = tabId,
);
- await _discover(f);
- expect(_contributions(f), isEmpty);
- expect(_teamOffers(f), isEmpty);
- },
- );
-
- test(
- 'a join in Desktop and the discovery after it add this Mac once',
- () async {
- final f = _computer();
- await f.app.addMachineOnJoin(tabId, role: 'collaborator');
- expect(_contributions(f), hasLength(1));
- f.connection.server.state['machines'] = <dynamic>[];
- await _discover(f);
- expect(_contributions(f), hasLength(1));
- expect(_teamOffers(f), hasLength(1));
- },
- );
-
- // Review of #3115: a Swarm opened only for the add kept polling, and a
- // viewer's was read in full on every discovery.
- test('a Swarm opened only to add this Mac is let go, and a viewer\'s is read once', () async {
- final viewer = _computer(role: 'viewer');
- await _discover(viewer);
- await _discover(viewer);
- expect(_firstLoads(viewer), 1);
- expect(viewer.app.superTabs.peek(tabId), isNull);
-
- final collaborator = _computer();
- await _discover(collaborator);
- expect(_contributions(collaborator), hasLength(1));
- expect(collaborator.app.superTabs.peek(tabId), isNull);
- });
-
- test('a first discovery before this Mac\'s own row is known still takes the update\'s baseline', () async {
- final f = _computer();
- f.app.teamAccountHereForTest = false;
- await _discover(f);
- expect(_contributions(f), isEmpty);
- // Discovery showed the Swarm meanwhile; it is still new to the add.
- f.app.teamAccountHereForTest = true;
- await _discover(f);
- expect(_contributions(f), hasLength(1));
- });
-
- // Task #3212: a reinstall (an empty record here) added this Mac back to a
- // Swarm its person had taken it out of.
- test(
- 'after its person took this Mac out, a fresh install does not add it back',
- () async {
- final f = _computer();
- // As the Swarm tells this person: their own removed computers.
- f.connection.server.state['removedMachines'] = ['m'];
- await _discover(f);
- expect(_contributions(f), isEmpty);
- expect(_teamOffers(f), isEmpty);
- // Decided for this Swarm: the next discovery does not read it again.
- final loads = _firstLoads(f);
- await _discover(f);
- expect(_firstLoads(f), loads);
- },
- );
-
- test(
- 'a fresh install still adds this Mac to a Swarm it was never taken out of',
- () async {
- final f = _computer();
- f.connection.server.state['removedMachines'] = ['another-computer'];
- await _discover(f);
- expect(_contributions(f), hasLength(1));
- expect(_teamOffers(f), hasLength(1));
+ await discover(f);
+ expect(f.app.joinAccountRequest, isNull);
+ expectNoEnrollment(f);
},
);
-
- group('a failed step shows the person a note', () {
- test(
- 'a Team account this Mac could not be offered says where to set it up',
- () async {
- final f = _computer();
- // A daemon that cannot say whether the account is wanted.
- f.connection.teamCheck = null;
- final notes = <SwarmJoinedMachine>[];
- final listening = f.app.joinedMachines.listen(notes.add);
- await _discover(f);
- expect(notes.map((n) => (n.added, n.teamProblem)), [
- (true, null),
- (true, 'Set it up from Machines.'),
- ]);
- await listening.cancel();
- },
- );
-
- test('a Swarm joined here that cannot be read says to add this Mac from Machines', () async {
- final f = _computer();
- f.connection.backendFailure = const WsRequestFailure(
- responseType: 'super_tabs_result',
- code: 'UNAVAILABLE',
- detail: 'The Swarm service is unavailable.',
- payload: {'status': 503},
- );
- final notes = <SwarmJoinedMachine>[];
- final listening = f.app.joinedMachines.listen(notes.add);
- await f.app.addMachineOnJoin(tabId, role: 'collaborator');
- await pumpEventQueue();
- expect(notes.map((n) => (n.tabId, n.added, n.problem)), [
- (
- tabId,
- false,
- 'Could not reach the Swarm. Add this computer from Machines.',
- ),
- ]);
- await listening.cancel();
- });
- });
}
diff --git a/desktop/test/swarm_join_machine_test.dart b/desktop/test/swarm_join_machine_test.dart
index b280ac556..1689487b9 100644
--- a/desktop/test/swarm_join_machine_test.dart
+++ b/desktop/test/swarm_join_machine_test.dart
@@ -1,396 +1,12 @@
-import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
-import 'package:harness/core/machine_resources.dart';
import 'package:harness/super_tabs/controller.dart';
import 'package:harness/super_tabs/join_machine.dart';
-import 'package:harness/super_tabs/join_machine_note.dart';
import 'package:harness/super_tabs/model.dart';
import 'support/super_tab_fixture.dart';
-const _gib = 1024 * 1024 * 1024;
-
-/// This computer's daemon, as the join step asks it: setup of the Swarm's
-/// folder (`prepareContribution`), then a wake once the machine is added.
-class _Daemon {
- final asked = <Map<String, dynamic>>[];
- final woken = <String>[];
-
- /// Answers to `prepareContribution`, in turn; the last one repeats.
- List<Object> prepared = [
- {
- 'ok': true,
- 'state': 'ready',
- 'scope': 'swarm',
- 'cwd': '/Users/mate/Harness/Swarm',
- 'engines': ['claude', 'codex', 'opencode'],
- 'maxAgents': 4,
- 'maxAvailableAgents': 16,
- },
- ];
- MachineResources? resources = const MachineResources(
- memoryTotalBytes: 32.0 * _gib,
- );
-
- Future<Map<String, dynamic>> request(
- String machineId,
- Map<String, dynamic> payload,
- ) async {
- asked.add({'machineId': machineId, ...payload});
- final next = prepared.length > 1 ? prepared.removeAt(0) : prepared.first;
- if (next is Exception) throw next;
- return Map<String, dynamic>.of(next as Map<String, dynamic>);
- }
-
- SwarmJoinMachine adder() => SwarmJoinMachine(
- machineRequest: request,
- readResources: (_) async => resources,
- wake: (id) async => woken.add(id),
- pause: Duration.zero,
- deadline: const Duration(milliseconds: 200),
- );
-}
-
void main() {
- late ConversationServer server;
- late _Daemon daemon;
-
- /// The Swarm as [person] sees it right after joining with [role].
- ConversationServer joinedAs(String role, {String person = 'mate'}) {
- final s = ConversationServer();
- (s.state['people'] as List).add({
- 'id': person,
- 'email': '[email protected]',
- 'role': role,
- });
- return s;
- }
-
- List<Map<String, dynamic>> contributions() => [
- for (final post in server.posts)
- if ((post['command'] as Map)['type'] == 'machine.contribute')
- Map<String, dynamic>.from(post['command'] as Map),
- ];
-
- setUp(() {
- server = joinedAs('collaborator');
- daemon = _Daemon();
- });
-
- test('adds this computer with Add machine\'s defaults, only through a Team account for teammates', () async {
- final c = server.controller(account: 'mate');
- await c.refresh();
- final note = await daemon.adder().add(
- c,
- machineId: 'mate-mac',
- machineName: 'MacBook Air',
- current: () => true,
- );
- expect(note?.added, isTrue);
- expect(note?.tabId, 'tab');
- expect(note?.machineId, 'mate-mac');
- expect(contributions(), [
- {
- 'type': 'machine.contribute',
- 'machineId': 'mate-mac',
- 'name': 'MacBook Air',
- 'cwd': '/Users/mate/Harness/Swarm',
- 'scope': 'swarm',
- // Only the engines a Swarm runs.
- 'engines': ['claude', 'codex'],
- // Half its memory in agents, at most 16: 32 GiB suggests 8.
- 'maxAgents': 8,
- // Joining sets no limit (Dee, 2026-11-04: "remove the limit").
- 'agents': 'memory',
- 'teamAccountOnly': true,
- },
- ]);
- expect(daemon.asked.single, {
- 'machineId': 'mate-mac',
- 'action': 'prepareContribution',
- 'tabId': 'tab',
- 'scope': 'swarm',
- 'operationId': isA<String>(),
- });
- expect(daemon.woken, ['mate-mac']);
- c.dispose();
- });
-
- test('own account is enabled only after a restricted contribution', () async {
- final c = server.controller(account: 'mate');
- await c.refresh();
- final note = await daemon.adder().add(
- c,
- machineId: 'mate-mac',
- machineName: 'MacBook Air',
- current: () => true,
- ownAccount: true,
- );
- expect(contributions().single['teamAccountOnly'], isTrue);
- expect(server.posts.map((p) => (p['command'] as Map)['type']), [
- 'machine.contribute',
- 'machine.ownAccountWork',
- ]);
- expect(server.posts.last['command'], {
- 'type': 'machine.ownAccountWork',
- 'machineId': 'mate-mac',
- 'allowed': true,
- });
- expect(note?.ownAccount, isTrue);
- expect(note?.accountProblem, isNull);
- c.dispose();
- });
-
- test(
- 'a refused own-account choice is visible and never reported as enabled',
- () async {
- server.unknownCommand = (command) =>
- command['type'] == 'machine.ownAccountWork';
- final c = server.controller(account: 'mate');
- await c.refresh();
- final note = await daemon.adder().add(
- c,
- machineId: 'mate-mac',
- machineName: 'MacBook Air',
- current: () => true,
- ownAccount: true,
- );
- expect(note?.added, isTrue);
- expect(note?.ownAccount, isFalse);
- expect(note?.accountProblem, isNotEmpty);
- c.dispose();
- },
- );
-
- test('account change after contribution never sends consent', () async {
- final c = server.controller(account: 'mate');
- await c.refresh();
- var active = true;
- final adder = SwarmJoinMachine(
- machineRequest: daemon.request,
- readResources: (_) async => daemon.resources,
- wake: (_) async {
- active = false;
- },
- );
- final note = await adder.add(
- c,
- machineId: 'mate-mac',
- machineName: 'MacBook Air',
- current: () => active,
- ownAccount: true,
- );
- expect(note, isNull);
- expect(server.posts.map((p) => (p['command'] as Map)['type']), [
- 'machine.contribute',
- ]);
- c.dispose();
- });
-
- test('waits for the folder setup, then falls back to its offer when memory cannot be read', () async {
- daemon.resources = null;
- daemon.prepared = [
- {'ok': true, 'state': 'preparing'},
- {'ok': true, 'state': 'preparing'},
- {...daemon.prepared.single as Map<String, dynamic>, 'maxAgents': 6},
- ];
- final c = server.controller(account: 'mate');
- await c.refresh();
- final note = await daemon.adder().add(
- c,
- machineId: 'mate-mac',
- machineName: 'MacBook Air',
- current: () => true,
- );
- expect(note?.added, isTrue);
- expect(contributions().single['maxAgents'], 6);
- // One operation for the whole setup, so the daemon answers the same one.
- expect(daemon.asked.map((a) => a['operationId']).toSet(), hasLength(1));
- expect(daemon.asked, hasLength(3));
- c.dispose();
- });
-
- test('leaves a viewer, a machine already in the Swarm and a Swarm without Team accounts alone', () async {
- for (final setup in <void Function()>[
- () => server = joinedAs('viewer'),
- () => server.state['machines'] = [
- {
- 'machineId': 'mate-mac',
- 'name': 'MacBook Air',
- 'contributorId': 'mate',
- 'engines': ['codex'],
- 'maxAgents': 2,
- },
- ],
- () => server.state['teamAccounts'] = false,
- ]) {
- server = joinedAs('collaborator');
- daemon = _Daemon();
- setup();
- final c = server.controller(account: 'mate');
- await c.refresh();
- final note = await daemon.adder().add(
- c,
- machineId: 'mate-mac',
- machineName: 'MacBook Air',
- current: () => true,
- );
- expect(note, isNull);
- expect(contributions(), isEmpty);
- expect(daemon.asked, isEmpty);
- c.dispose();
- }
- });
-
- // Task #3212: a reinstall added a Mac back to a Swarm its person had taken
- // it out of. The Swarm tells each reader their own removed computers.
- test(
- 'leaves out a computer its person took out of the Swarm, and only that one',
- () async {
- server.state['removedMachines'] = ['MATE-MAC'];
- final c = server.controller(account: 'mate');
- await c.refresh();
- final note = await daemon.adder().add(
- c,
- machineId: 'mate-mac',
- machineName: 'MacBook Air',
- current: () => true,
- );
- expect(note, isNull);
- expect(contributions(), isEmpty);
- expect(daemon.asked, isEmpty);
-
- // Another of their computers, taken out: this one is still added.
- server.state['removedMachines'] = ['mate-old-laptop'];
- await c.refresh();
- final added = await daemon.adder().add(
- c,
- machineId: 'mate-mac',
- machineName: 'MacBook Air',
- current: () => true,
- );
- expect(added?.added, isTrue);
- expect(contributions(), hasLength(1));
- c.dispose();
- },
- );
-
- test('says why it could not add it: no Claude Code or Codex, Harness too old, or refused', () async {
- Future<SwarmJoinedMachine?> attempt() async {
- final c = server.controller(account: 'mate');
- await c.refresh();
- try {
- return await daemon.adder().add(
- c,
- machineId: 'mate-mac',
- machineName: 'MacBook Air',
- current: () => true,
- );
- } finally {
- c.dispose();
- }
- }
-
- daemon.prepared = [
- {
- ...daemon.prepared.single as Map<String, dynamic>,
- 'engines': ['opencode'],
- },
- ];
- expect(
- (await attempt())?.problem,
- 'Install Claude Code or Codex on this computer, then add it from Machines.',
- );
- expect(contributions(), isEmpty);
-
- daemon = _Daemon()
- ..prepared = [
- {'ok': true, 'state': 'unknown'},
- ];
- expect(
- (await attempt())?.problem,
- 'Update Harness on this computer, then add it from Machines.',
- );
-
- daemon = _Daemon();
- server.refuse = {
- 'code': 'MACHINE_LIMIT_PER_PERSON',
- 'message':
- 'You have 20 machines in this Swarm, the most one person can add.'
- ' Remove one before adding another.',
- };
- final refused = await attempt();
- expect(refused?.added, isFalse);
- expect(
- refused?.problem,
- 'You have 20 machines in this Swarm, the most one person can add.'
- ' Remove one before adding another.',
- );
- expect(daemon.woken, isEmpty);
- });
-
- test('gives up within its deadline when setup never finishes or the daemon cannot be reached', () async {
- daemon.prepared = [
- {'ok': true, 'state': 'preparing'},
- ];
- final c = server.controller(account: 'mate');
- await c.refresh();
- final slow = await daemon.adder().add(
- c,
- machineId: 'mate-mac',
- machineName: 'MacBook Air',
- current: () => true,
- );
- expect(
- slow?.problem,
- 'Setting up this computer took too long. Add it from Machines.',
- );
- daemon = _Daemon()..prepared = [Exception('socket closed')];
- final unreachable = await daemon.adder().add(
- c,
- machineId: 'mate-mac',
- machineName: 'MacBook Air',
- current: () => true,
- );
- expect(
- unreachable?.problem,
- 'Could not reach Harness on this computer. Add it from Machines.',
- );
- expect(daemon.asked, hasLength(1));
- expect(contributions(), isEmpty);
- c.dispose();
- });
-
- test('stops, adding nothing and saying nothing, once the account changed or signed out', () async {
- var current = true;
- daemon.prepared = [
- {'ok': true, 'state': 'preparing'},
- daemon.prepared.single,
- ];
- final c = server.controller(account: 'mate');
- await c.refresh();
- final adder = SwarmJoinMachine(
- machineRequest: (id, payload) {
- current = false;
- return daemon.request(id, payload);
- },
- readResources: (_) async => daemon.resources,
- wake: (id) async => daemon.woken.add(id),
- pause: Duration.zero,
- deadline: const Duration(milliseconds: 200),
- );
- final note = await adder.add(
- c,
- machineId: 'mate-mac',
- machineName: 'MacBook Air',
- current: () => current,
- );
- expect(note, isNull);
- expect(contributions(), isEmpty);
- expect(daemon.asked, hasLength(1));
- c.dispose();
- });
-
+ final server = ConversationServer();
test(
'a snapshot reads whether the Swarm uses Team accounts, absent meaning yes',
() {
@@ -483,188 +99,4 @@ void main() {
);
expect(receipts, hasLength(1));
});
-
- group('the note after joining', noteTests);
-}
-
-void noteTests() {
- late ConversationServer server;
- setUp(() => server = ConversationServer());
-
- Future<SuperTabController> mount(
- WidgetTester tester,
- SwarmJoinedMachine note,
- ) async {
- final c = server.controller();
- await c.refresh();
- await tester.pumpWidget(
- MaterialApp(
- home: Scaffold(
- body: Builder(
- builder: (context) => TextButton(
- onPressed: () => showJoinedMachineNote(
- context,
- (_) async => c,
- note,
- operatingSystem: 'macos',
- ),
- child: const Text('show'),
- ),
- ),
- ),
- ),
- );
- await tester.tap(find.text('show'));
- await tester.pumpAndSettle();
- return c;
- }
-
- const added = SwarmJoinedMachine(
- tabId: 'tab',
- swarmName: 'Pilot',
- machineId: 'mate-mac',
- machineName: 'MacBook Air',
- );
-
- testWidgets('says this Mac was added, and Pause pauses it', (tester) async {
- final c = await mount(tester, added);
- expect(
- find.text(
- 'This Mac was added to Pilot. Teammates\' agents run here only in '
- 'Harness Team, never as you.',
- ),
- findsOneWidget,
- );
- await tester.tap(find.byKey(const Key('swarm-joined-machine-pause')));
- await tester.pumpAndSettle();
- expect(server.posts.map((p) => p['command']), [
- {'type': 'machine.pause', 'machineId': 'mate-mac', 'paused': true},
- ]);
- expect(find.byKey(const Key('swarm-joined-machine-note')), findsNothing);
- c.dispose();
- });
-
- testWidgets('Remove removes it; a refusal says why', (tester) async {
- server.refuse = {
- 'code': 'FORBIDDEN',
- 'message': 'Only its owner can remove it.',
- };
- final c = await mount(tester, added);
- await tester.tap(find.byKey(const Key('swarm-joined-machine-remove')));
- await tester.pumpAndSettle();
- expect(server.posts.map((p) => p['command']), [
- {'type': 'machine.remove', 'machineId': 'mate-mac'},
- ]);
- expect(find.text('Only its owner can remove it.'), findsOneWidget);
- c.dispose();
- });
-
- testWidgets('a computer that was not added says why, with nothing to undo', (
- tester,
- ) async {
- final c = await mount(
- tester,
- const SwarmJoinedMachine(
- tabId: 'tab',
- swarmName: 'Pilot',
- machineId: 'mate-mac',
- machineName: 'MacBook Air',
- problem: 'Install Claude Code or Codex on this computer, then add it from Machines.',
- ),
- );
- expect(
- find.text(
- 'This Mac was not added to Pilot. Install Claude Code or Codex on this '
- 'computer, then add it from Machines.',
- ),
- findsOneWidget,
- );
- expect(find.byKey(const Key('swarm-joined-machine-pause')), findsNothing);
- expect(find.byKey(const Key('swarm-joined-machine-remove')), findsNothing);
- c.dispose();
- });
-
- // Task #3160: a failed Team account offer was only a log line.
- testWidgets(
- 'a Team account that could not be offered says where to set it up',
- (tester) async {
- final c = await mount(
- tester,
- const SwarmJoinedMachine(
- tabId: 'tab',
- swarmName: 'Pilot',
- machineId: 'mate-mac',
- machineName: 'MacBook Air',
- teamProblem: 'Set it up from Machines.',
- ),
- );
- expect(
- find.text(
- 'This Mac was added to Pilot, but Harness could not offer its Harness '
- 'Team account. Set it up from Machines.',
- ),
- findsOneWidget,
- );
- expect(find.byKey(const Key('swarm-joined-machine-pause')), findsNothing);
- c.dispose();
- },
- );
-
- testWidgets('own-account join note discloses actual access', (tester) async {
- final c = await mount(
- tester,
- const SwarmJoinedMachine(
- tabId: 'tab',
- swarmName: 'Pilot',
- machineId: 'mate-mac',
- machineName: 'MacBook Air',
- ownAccount: true,
- ),
- );
- expect(find.textContaining('run as you'), findsOneWidget);
- expect(find.textContaining('only in Harness Team'), findsNothing);
- expect(find.byKey(const Key('swarm-joined-machine-pause')), findsOneWidget);
- c.dispose();
- });
-
- testWidgets('unconfirmed consent tells the person to check Machines', (
- tester,
- ) async {
- final c = await mount(
- tester,
- const SwarmJoinedMachine(
- tabId: 'tab',
- swarmName: 'Pilot',
- machineId: 'mate-mac',
- machineName: 'MacBook Air',
- accountProblem: 'Check Machines to confirm the account setting.',
- ),
- );
- expect(find.textContaining('Check Machines'), findsOneWidget);
- expect(find.textContaining('only in Harness Team'), findsNothing);
- c.dispose();
- });
-
- testWidgets('a Swarm at its limit says so after joining', (tester) async {
- final c = await mount(
- tester,
- const SwarmJoinedMachine(
- tabId: 'tab',
- swarmName: 'Pilot',
- machineId: 'mate-mac',
- machineName: 'MacBook Air',
- problem:
- 'You have 20 machines in this Swarm, the most one person can add.'
- ' Remove one before adding another.',
- ),
- );
- expect(
- find.text(
- 'This Mac was not added to Pilot. You have 20 machines in this Swarm, t'
- 'he most one person can add. Remove one before adding another.',
- ),
- findsOneWidget,
- );
- c.dispose();
- });
}
diff --git a/desktop/test/swarm_v3_agent_dialog_test.dart b/desktop/test/swarm_v3_agent_dialog_test.dart
new file mode 100644
index 000000000..5e1bab453
--- /dev/null
+++ b/desktop/test/swarm_v3_agent_dialog_test.dart
@@ -0,0 +1,204 @@
+import 'dart:async';
+import 'dart:io';
+
+import 'support/capture.dart';
+
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/super_tabs/join/agent_dialog.dart';
+import 'package:harness/widgets/desktop_chrome.dart';
+
+Future<void> mount(
+ WidgetTester tester, {
+ bool bringing = false,
+ Brightness brightness = Brightness.light,
+ List<String> engines = const ['claude', 'codex'],
+ required SwarmAgentCreate create,
+ bool Function()? current,
+}) async {
+ grid.AppTheme.brightness.value = brightness;
+ addTearDown(() => grid.AppTheme.brightness.value = Brightness.light);
+ await tester.pumpWidget(
+ MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: grid.buildAppTheme(brightness: brightness),
+ home: Builder(
+ builder: (context) => Scaffold(
+ body: TextButton(
+ onPressed: () => showDialog<Map<String, dynamic>>(
+ context: context,
+ builder: (_) => SwarmAgentDialog(
+ bringing: bringing,
+ engines: engines,
+ create: create,
+ isCurrent: current ?? () => true,
+ ),
+ ),
+ child: const Text('Open'),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.tap(find.text('Open'));
+ await tester.pumpAndSettle();
+}
+
+void main() {
+ final shots = Platform.environment['HARNESS_V3_JOIN_SHOTS'];
+ setUpAll(() => loadCaptureFonts(shots));
+ for (final brightness in Brightness.values) {
+ testWidgets('new agent forms fit in ${brightness.name}', (tester) async {
+ await tester.binding.setSurfaceSize(const Size(1000, 760));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ await mount(
+ tester,
+ brightness: brightness,
+ create: (_, _, _, _) async => {'startId': 'one'},
+ );
+ final segments = tester.widget<SegmentedButton<String>>(find.byType(SegmentedButton<String>));
+ expect(segments.style?.foregroundColor?.resolve({WidgetState.selected}), DesktopChrome.onSelection);
+ expect(tester.takeException(), isNull);
+ await captureWindow(tester, shots, 'new-regular-${brightness.name}');
+ await tester.tap(find.text('PM'));
+ await tester.pumpAndSettle();
+ await tester.enterText(
+ find.byKey(const Key('swarm-agent-project')),
+ 'My project',
+ );
+ await tester.pumpAndSettle();
+ expect(tester.takeException(), isNull);
+ await captureWindow(tester, shots, 'new-pm-${brightness.name}');
+ });
+ }
+
+ testWidgets('bringing an agent picks its engine and makes it the Buddy', (
+ tester,
+ ) async {
+ final submitted = <(String, String, String?)>[];
+ await mount(
+ tester,
+ bringing: true,
+ create: (engine, kind, project, operation) async {
+ submitted.add((engine, kind, project));
+ return {'agentId': 'buddy'};
+ },
+ );
+ expect(find.text('Bring your agent'), findsOneWidget);
+ expect(find.textContaining('Team account'), findsNothing);
+ expect(find.textContaining('Add machine'), findsNothing);
+ expect(find.text('Regular'), findsNothing);
+ await tester.tap(find.byKey(const Key('swarm-agent-engine')));
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('Codex').last);
+ await tester.pumpAndSettle();
+ await tester.tap(find.byKey(const Key('swarm-agent-submit')));
+ await tester.pumpAndSettle();
+ expect(submitted, [('codex', 'buddy', null)]);
+ expect(find.text('Bring your agent'), findsNothing);
+ });
+
+ testWidgets('Regular has no project; PM requires a trimmed project name', (
+ tester,
+ ) async {
+ final submitted = <(String, String, String?)>[];
+ Future<Map<String, dynamic>> create(
+ String e,
+ String k,
+ String? p,
+ String op,
+ ) async {
+ submitted.add((e, k, p));
+ return {'agentId': k};
+ }
+
+ await mount(tester, create: create);
+ expect(find.byKey(const Key('swarm-agent-project')), findsNothing);
+ await tester.tap(find.byKey(const Key('swarm-agent-submit')));
+ await tester.pumpAndSettle();
+ expect(submitted.single, ('claude', 'regular', null));
+ await mount(tester, create: create);
+ await tester.tap(find.text('PM'));
+ await tester.pumpAndSettle();
+ expect(
+ tester
+ .widget<FilledButton>(find.byKey(const Key('swarm-agent-submit')))
+ .onPressed,
+ isNull,
+ );
+ await tester.enterText(
+ find.byKey(const Key('swarm-agent-project')),
+ ' Compiler ',
+ );
+ await tester.pump();
+ await tester.tap(find.byKey(const Key('swarm-agent-submit')));
+ await tester.pumpAndSettle();
+ expect(submitted.last, ('claude', 'pm', 'Compiler'));
+ });
+
+ testWidgets(
+ 'lost response retries one operation and never shows raw failures',
+ (tester) async {
+ final operations = <String>[];
+ await mount(
+ tester,
+ create: (e, k, p, op) async {
+ operations.add(op);
+ if (operations.length == 1) throw StateError('private-token-value');
+ return {'agentId': 'one'};
+ },
+ );
+ await tester.tap(find.byKey(const Key('swarm-agent-submit')));
+ await tester.pumpAndSettle();
+ expect(find.textContaining('private-token-value'), findsNothing);
+ expect(find.text('Retry'), findsOneWidget);
+ await tester.tap(find.text('Retry'));
+ await tester.pumpAndSettle();
+ expect(operations, hasLength(2));
+ expect(operations.toSet(), hasLength(1));
+ },
+ );
+
+ testWidgets('no local engine cannot launch and explains how to recover', (
+ tester,
+ ) async {
+ await mount(
+ tester,
+ engines: [],
+ create: (e, k, p, op) async => throw StateError('must not launch'),
+ );
+ expect(find.textContaining('Install'), findsOneWidget);
+ expect(
+ tester
+ .widget<FilledButton>(find.byKey(const Key('swarm-agent-submit')))
+ .onPressed,
+ isNull,
+ );
+ });
+
+ testWidgets(
+ 'pending submission is single and account changes invalidate it',
+ (tester) async {
+ final answer = Completer<Map<String, dynamic>>();
+ var calls = 0, current = true;
+ await mount(
+ tester,
+ current: () => current,
+ create: (e, k, p, op) {
+ calls++;
+ return answer.future;
+ },
+ );
+ await tester.tap(find.byKey(const Key('swarm-agent-submit')));
+ await tester.pump();
+ await tester.tap(find.byKey(const Key('swarm-agent-submit')));
+ expect(calls, 1);
+ current = false;
+ answer.complete({'agentId': 'old-account'});
+ await tester.pumpAndSettle();
+ expect(find.text('New agent'), findsOneWidget);
+ expect(find.textContaining('account changed'), findsOneWidget);
+ },
+ );
+}
diff --git a/desktop/test/swarm_v3_agent_launcher_test.dart b/desktop/test/swarm_v3_agent_launcher_test.dart
new file mode 100644
index 000000000..7f9eecc80
--- /dev/null
+++ b/desktop/test/swarm_v3_agent_launcher_test.dart
@@ -0,0 +1,149 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/super_tabs/join/agent_launcher.dart';
+
+void main() {
+ for (final kind in ['buddy', 'regular', 'pm']) {
+ test(
+ '$kind uses this computer and owner command without a login or Team setup',
+ () async {
+ final sent = <Map<String, dynamic>>[];
+ final launcher = SwarmAgentLauncher(
+ machineId: 'local',
+ machineName: 'My computer',
+ inSwarm: false,
+ isCurrent: () => true,
+ prepare: (operation) async => {
+ 'name': 'My computer',
+ 'cwd': '/work',
+ 'engines': ['codex', 'pi'],
+ },
+ command: (command, operation) async {
+ sent.add(command);
+ return command['type'] == 'machine.contribute'
+ ? {}
+ : {'startId': 'start', 'conversationId': 'chat'};
+ },
+ );
+ final result = await launcher.create(
+ 'codex',
+ kind,
+ kind == 'pm' ? 'Compiler' : null,
+ 'operation',
+ );
+ expect(result['startId'], 'start');
+ final start = sent.last;
+ expect(start['machineId'], 'local');
+ if (kind == 'buddy') {
+ expect(sent, hasLength(1));
+ expect(start['type'], 'buddy.create');
+ expect(start['setup'], containsPair('cwd', '/work'));
+ expect((start['setup'] as Map)['engines'], ['codex']);
+ } else {
+ expect(sent.first['type'], 'machine.contribute');
+ expect(sent.first['teamAccountOnly'], isTrue);
+ expect(sent.first.containsKey('ifMissing'), isFalse);
+ expect(start['type'], 'agent.new');
+ expect(start['kind'], kind);
+ if (kind == 'pm') expect(start.containsKey('name'), isFalse);
+ expect(start['projectName'], kind == 'pm' ? 'Compiler' : null);
+ }
+ expect(sent.toString(), isNot(contains('teamSetup')));
+ },
+ );
+ }
+ for (final kind in ['regular', 'pm']) {
+ test(
+ 'a non-owner collaborator can create $kind without sharing their login',
+ () async {
+ final calls = <Map<String, dynamic>>[];
+ final launcher = SwarmAgentLauncher(
+ machineId: 'collaborator-computer',
+ machineName: 'This computer',
+ inSwarm: false,
+ isCurrent: () => true,
+ prepare: (_) async => {
+ 'cwd': '/work',
+ 'engines': ['claude'],
+ },
+ command: (command, operation) async {
+ // This transport represents a collaborator, not the org owner. The
+ // backend reserves automatic ifMissing admission for the owner.
+ if (command['type'] == 'machine.contribute' &&
+ command['ifMissing'] == true) {
+ throw const SwarmAgentLaunchFailure(
+ 'Only the org owner adds a machine automatically.',
+ );
+ }
+ calls.add(command);
+ return command['type'] == 'machine.contribute'
+ ? <String, dynamic>{}
+ : {'startId': 'started', 'conversationId': 'own-chat'};
+ },
+ );
+ final result = await launcher.create(
+ 'claude',
+ kind,
+ kind == 'pm' ? 'Compiler' : null,
+ 'collaborator-operation',
+ );
+ expect(result['startId'], 'started');
+ expect(calls, hasLength(2));
+ expect(calls.first['teamAccountOnly'], isTrue);
+ expect(calls.first.containsKey('ownAccountWork'), isFalse);
+ expect(calls.last['type'], 'agent.new');
+ },
+ );
+ }
+ test('a retry retains preparation and each command operation', () async {
+ var prepares = 0, starts = 0;
+ final ops = <String>[];
+ final launcher = SwarmAgentLauncher(
+ machineId: 'local',
+ machineName: 'Mac',
+ inSwarm: false,
+ isCurrent: () => true,
+ prepare: (op) async {
+ prepares++;
+ return {
+ 'cwd': '/work',
+ 'engines': ['claude'],
+ };
+ },
+ command: (cmd, op) async {
+ ops.add(op);
+ if (cmd['type'] == 'agent.new' && starts++ == 0)
+ throw StateError('lost');
+ return {'startId': 'one'};
+ },
+ );
+ await expectLater(
+ launcher.create('claude', 'regular', null, 'op'),
+ throwsStateError,
+ );
+ await launcher.create('claude', 'regular', null, 'op');
+ expect(prepares, 1);
+ expect(ops.where((op) => op.endsWith('-start')).toSet(), hasLength(1));
+ expect(ops.where((op) => op.endsWith('-machine')), hasLength(1));
+ });
+ test('account invalidation after prepare never sends a command', () async {
+ var current = true;
+ final launcher = SwarmAgentLauncher(
+ machineId: 'local',
+ machineName: 'Mac',
+ inSwarm: false,
+ isCurrent: () => current,
+ prepare: (op) async {
+ current = false;
+ return {
+ 'cwd': '/work',
+ 'engines': ['claude'],
+ };
+ },
+ command: (cmd, op) async => throw StateError('must not send'),
+ );
+ await expectLater(
+ launcher.create('claude', 'buddy', null, 'op'),
+ throwsA(isA<SwarmAgentLaunchFailure>()),
+ );
+ });
+}
diff --git a/desktop/test/swarm_v3_join_integration_test.dart b/desktop/test/swarm_v3_join_integration_test.dart
new file mode 100644
index 000000000..73a2d462b
--- /dev/null
+++ b/desktop/test/swarm_v3_join_integration_test.dart
@@ -0,0 +1,45 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/state/app_state.dart';
+
+import 'super_tab_launch_test.dart' show SuperTabLaunchFixture, tabId;
+
+void main() {
+ test(
+ 'new collaborator joins without machine admission or Team setup',
+ () async {
+ final f = SuperTabLaunchFixture();
+ f.app.status = AppStatus.authenticated;
+ f.app.teamAccountHereForTest = true;
+ f.connection.teamCheck = {'state': 'wanted'};
+ f.connection.server.state['people'] = [
+ {'id': 'boss', 'email': '[email protected]', 'role': 'owner'},
+ {'id': 'owner', 'email': '[email protected]', 'role': 'collaborator'},
+ ];
+ f.connection.server.state['ownerId'] = 'boss';
+ var prompts = 0;
+ f.app.addListener(() {
+ final request = f.app.joinAccountRequest;
+ if (request != null && !request.answered) {
+ prompts++;
+ request.complete(false);
+ }
+ });
+ await f.app.addMachineOnJoin(tabId, role: 'collaborator');
+ expect(
+ f.connection.server.posts.where(
+ (post) => (post['command'] as Map)['type'] == 'machine.contribute',
+ ),
+ isEmpty,
+ );
+ expect(
+ f.connection.calls.where(
+ (call) =>
+ call.$1 == 'super_tabs' && call.$2['action'] == 'teamSetupCheck',
+ ),
+ isEmpty,
+ );
+ expect(prompts, 1);
+ f.dispose();
+ },
+ );
+}
diff --git a/desktop/test/swarm_v3_usage_transport_test.dart b/desktop/test/swarm_v3_usage_transport_test.dart
new file mode 100644
index 000000000..aaaa82573
--- /dev/null
+++ b/desktop/test/swarm_v3_usage_transport_test.dart
@@ -0,0 +1,61 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/usage/usage_controller.dart';
+import 'package:harness/usage/usage_window.dart';
+
+import 'super_tab_launch_test.dart';
+import 'swarm_state_test.dart' show MemoryStore;
+
+class ReportConnection extends SuperTabFixtureConnection {
+ ReportConnection(super.store);
+ var reads = 0;
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) async {
+ if (type != 'usage_read') {
+ return super.request(type, payload: payload, timeout: timeout);
+ }
+ reads++;
+ return {
+ 'providers': [
+ {
+ 'provider': 'claude',
+ 'outcome': 'answered',
+ 'httpStatus': 200,
+ 'body': {
+ 'five_hour': {
+ 'utilization': 42,
+ 'resets_at': '2099-01-01T00:00:00Z',
+ },
+ },
+ },
+ ],
+ };
+ }
+}
+
+void main() {
+ test(
+ 'this computer reports usage through its CLI and retains local identity',
+ () async {
+ late ReportConnection connection;
+ final f = SuperTabLaunchFixture(
+ connectionFactory: (MemoryStore store) =>
+ connection = ReportConnection(store),
+ );
+ final usage = UsageController(
+ autoStart: false,
+ remote: f.app.readRemoteUsage,
+ );
+ addTearDown(usage.dispose);
+ await usage.refresh();
+ expect(connection.reads, 1);
+ expect(usage.readings.single.provider, UsageProvider.claude);
+ expect(usage.accounts.single.isLocal, isTrue);
+ expect(usage.hasAnswer, isTrue);
+ expect(usage.stale, isFalse);
+ },
+ );
+}
diff --git a/desktop/test/usage_credentials_test.dart b/desktop/test/usage_credentials_test.dart
deleted file mode 100644
index 590a76c75..000000000
--- a/desktop/test/usage_credentials_test.dart
+++ /dev/null
@@ -1,142 +0,0 @@
-// How the app finds Claude Code's OAuth token in the macOS Keychain — the same lookup Claude Code
-// itself performs, or it reads a different item than the CLI that is signed in.
-import 'dart:io';
-import 'dart:convert';
-
-import 'package:flutter_test/flutter_test.dart';
-import 'package:harness/usage/usage_credentials.dart';
-
-/// A Keychain holding several `Claude Code-credentials` items, the way a real one does after a
-/// few years of use: the first item `security` returns for the bare service name is a stale one
-/// under another account, and the live one is keyed by THIS user's account.
-class _Keychain {
- _Keychain({required this.user});
- final String user;
- final calls = <List<String>>[];
-
- static String _item(int expiresAt) =>
- '{"claudeAiOauth":{"accessToken":"tok-$expiresAt","refreshToken":"r","expiresAt":$expiresAt}}';
-
- Future<ProcessResult> run(String executable, List<String> args) async {
- calls.add([executable, ...args]);
- if (executable != 'security') {
- return ProcessResult(0, 1, '', 'no such command');
- }
- final service = args[args.indexOf('-s') + 1];
- final account = args.contains('-a') ? args[args.indexOf('-a') + 1] : null;
- // Only the plain service, the way current Claude Code names it without CLAUDE_CONFIG_DIR.
- if (service != 'Claude Code-credentials') {
- return ProcessResult(0, 44, '', 'not found');
- }
- // The stale first match — what `security` answers for the bare service name.
- if (account == null) return ProcessResult(0, 0, _item(1000), '');
- // 2100-01-01: the live item, under this user's account.
- if (account == user) return ProcessResult(0, 0, _item(4102444800000), '');
- return ProcessResult(0, 44, '', 'not found');
- }
-}
-
-void main() {
- test(
- 'unavailable or malformed account emails do not break credential reads',
- () async {
- final home = Directory.systemTemp.createTempSync('usage-email-');
- addTearDown(() => home.deleteSync(recursive: true));
- final credentials = UsageCredentials(
- home: home.path,
- environment: const {},
- );
- expect(await credentials.claudeAccountEmail(), isNull);
- expect(await credentials.codexAccountEmail(), isNull);
- Directory('${home.path}/.codex').createSync();
- for (final value in [
- null,
- '',
- ' ',
- 42,
- 'not-a-jwt',
- 'a.%%%.b',
- 'a.bnVsbA.b',
- ]) {
- File('${home.path}/.claude.json').writeAsStringSync(
- jsonEncode({
- 'oauthAccount': {'accountUuid': 'account', 'emailAddress': value},
- }),
- );
- File('${home.path}/.codex/auth.json').writeAsStringSync(
- jsonEncode({
- 'tokens': {'access_token': 'test-token', 'id_token': value},
- }),
- );
- if (value is! String || value.trim().isEmpty) {
- expect(await credentials.claudeAccountEmail(), isNull);
- }
- expect(await credentials.codexAccountEmail(), isNull);
- expect((await credentials.codex())?.accessToken, 'test-token');
- }
- },
- );
-
- test(
- 'reads the item Claude Code itself reads: service AND this user\'s account',
- () async {
- final keychain = _Keychain(user: 'macbookpro');
- final credentials = UsageCredentials(
- home: Directory.systemTemp.path,
- environment: const {'USER': 'macbookpro'},
- runProcess: keychain.run,
- );
-
- final token = await credentials.claude();
-
- expect(token?.accessToken, 'tok-4102444800000');
- expect(token?.isExpired, isFalse);
- final security = keychain.calls.singleWhere((c) => c.first == 'security');
- expect(security, containsAllInOrder(['-a', 'macbookpro']));
- expect(security, containsAllInOrder(['-s', 'Claude Code-credentials']));
- },
- );
-
- test('falls back to the OS username when USER is unset, and to Claude Code\'s placeholder when it is unusable', () {
- expect(
- UsageCredentials.keychainAccount(const {}, username: 'macbookpro'),
- 'macbookpro',
- );
- // Claude Code refuses an account name outside `[a-zA-Z0-9._-]` and uses a fixed one instead,
- // so the same name has to be looked up here or the item is simply never found.
- expect(
- UsageCredentials.keychainAccount(const {
- 'USER': 'mac book',
- }, username: 'ignored'),
- 'claude-code-user',
- );
- expect(
- UsageCredentials.keychainAccount(const {
- 'USER': 'kelvin.dev',
- }, username: 'ignored'),
- 'kelvin.dev',
- );
- });
-
- test('names the per-profile item when CLAUDE_CONFIG_DIR is set, as Claude Code does', () {
- expect(
- UsageCredentials.keychainService(const {}),
- 'Claude Code-credentials',
- );
- // sha256('/Users/macbookpro/.claude-work').substring(0, 8) — a worked example, not recomputed
- // here, so a drift in the hashing would be caught rather than mirrored.
- expect(
- UsageCredentials.keychainService(const {
- 'CLAUDE_CONFIG_DIR': '/Users/macbookpro/.claude-work',
- }),
- 'Claude Code-credentials-${_sha256Prefix('/Users/macbookpro/.claude-work')}',
- );
- });
-}
-
-/// The known-good prefix for the profile-dir example above, computed once with
-/// `printf '%s' '/Users/macbookpro/.claude-work' | shasum -a 256 | cut -c1-8`.
-String _sha256Prefix(String dir) {
- const known = {'/Users/macbookpro/.claude-work': '138c714b'};
- return known[dir]!;
-}
diff --git a/desktop/test/usage_no_credentials_test.dart b/desktop/test/usage_no_credentials_test.dart
new file mode 100644
index 000000000..ba901055c
--- /dev/null
+++ b/desktop/test/usage_no_credentials_test.dart
@@ -0,0 +1,51 @@
+import 'dart:io';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/usage/usage_controller.dart';
+
+void main() {
+ test(
+ 'Desktop usage never opens CLI logins or calls vendor usage endpoints',
+ () {
+ // CLI reports are the only usage boundary. Keep file/process/token access
+ // out of this directory so adding a provider cannot restore credential reads.
+ final forbidden = RegExp(
+ r"dart:io|usage_credentials|UsageCredentials|Authorization|api/oauth/usage|backend-api/wham/usage|find-generic-password|auth\.json|\.credentials\.json",
+ );
+ final violations = <String>[];
+ for (final file in Directory('lib/usage').listSync().whereType<File>()) {
+ if (file.path.endsWith('.dart') &&
+ forbidden.hasMatch(file.readAsStringSync())) {
+ violations.add(file.path);
+ }
+ }
+ final credentialNames = RegExp(
+ r"auth\.json|\.credentials\.json|find-generic-password|api/oauth/usage|backend-api/wham/usage",
+ );
+ for (final file in Directory(
+ 'lib',
+ ).listSync(recursive: true).whereType<File>()) {
+ if (file.path.endsWith('.dart') &&
+ credentialNames.hasMatch(file.readAsStringSync())) {
+ violations.add(file.path);
+ }
+ }
+ expect(
+ violations,
+ isEmpty,
+ reason: 'Usage must consume CLI reports, never logins.',
+ );
+ },
+ );
+
+ test(
+ 'default Desktop usage has no local credential-backed sources',
+ () async {
+ final usage = UsageController(autoStart: false);
+ addTearDown(usage.dispose);
+ expect(usage.readings, isEmpty);
+ await usage.refresh();
+ expect(usage.readings, isEmpty);
+ },
+ );
+}
diff --git a/desktop/test/usage_test.dart b/desktop/test/usage_test.dart
index f12933026..40a523336 100644
--- a/desktop/test/usage_test.dart
+++ b/desktop/test/usage_test.dart
@@ -1,90 +1,11 @@
-import 'dart:convert';
-import 'dart:io';
-
-import 'package:dio/dio.dart';
import 'package:flutter_test/flutter_test.dart';
-import 'package:harness/usage/claude_usage_source.dart';
-import 'package:harness/usage/codex_usage_source.dart';
-import 'package:harness/usage/usage_credentials.dart';
+import 'package:harness/usage/claude_usage_report.dart';
+import 'package:harness/usage/codex_usage_report.dart';
import 'package:harness/usage/usage_controller.dart';
import 'package:harness/usage/usage_source.dart';
import 'package:harness/usage/usage_window.dart';
-import 'package:harness/usage/usage_account_key.dart';
-
-/// A Dio that answers every request with one canned payload, so a source can be
-/// exercised without a socket or a credential.
-Dio _dioAnswering(Object? body, {int status = 200}) {
- final dio = Dio(
- BaseOptions(validateStatus: (s) => s != null && s >= 200 && s < 600),
- );
- dio.interceptors.add(
- InterceptorsWrapper(
- onRequest: (options, handler) => handler.resolve(
- Response<Object?>(
- requestOptions: options,
- statusCode: status,
- data: body,
- ),
- ),
- ),
- );
- return dio;
-}
-
-/// Credentials backed by a throwaway home directory, read the same way on
-/// every platform this app ships to.
-///
-/// The token goes in the FILE, never through the stubbed keychain. An earlier
-/// version supplied it as fake `security` output, which passed here and failed
-/// on the Linux CI: `UsageCredentials` reads the Keychain only on macOS, so on
-/// Linux the stub was never called and every one of these tests saw an account
-/// with no session. Linux is a released target, not a second-class one, and a
-/// helper that only works on the author's laptop hides exactly this.
-///
-/// The keychain stub stays, and always fails, for the opposite reason: without
-/// it a macOS run would shell out to the real `security` and read whoever is
-/// signed in on the machine.
-UsageCredentials _creds({
- String? claudeJson,
- String? claudeProfile,
- String? codexJson,
-}) {
- final dir = Directory.systemTemp.createTempSync('harness-usage-test');
- addTearDown(() => dir.deleteSync(recursive: true));
- void write(String folder, String file, String body) {
- Directory('${dir.path}/$folder').createSync();
- File('${dir.path}/$folder/$file').writeAsStringSync(body);
- }
-
- if (claudeJson != null) write('.claude', '.credentials.json', claudeJson);
- if (claudeProfile != null)
- File('${dir.path}/.claude.json').writeAsStringSync(claudeProfile);
- if (codexJson != null) write('.codex', 'auth.json', codexJson);
- return UsageCredentials(
- home: dir.path,
- runProcess: (_, _) async => ProcessResult(0, 1, '', ''),
- );
-}
void main() {
- group('whose computer is read (P3)', () {
- test('Desktop reads this computer\'s Claude and Codex accounts', () {
- final usage = UsageController(autoStart: false);
- addTearDown(usage.dispose);
- expect(
- usage.readings.map((r) => r.provider),
- [UsageProvider.claude, UsageProvider.codex],
- );
- });
-
- test('a viewer build has no agent CLI here: no reading of its own', () {
- final usage = UsageController(autoStart: false, readsThisComputer: false);
- addTearDown(usage.dispose);
- expect(usage.readings, isEmpty);
- expect(usage.accounts.where((a) => a.isLocal), isEmpty);
- });
- });
-
group('reset timestamps', () {
test('seconds and milliseconds are told apart by magnitude', () {
final seconds = parseResetTimestamp(1770000000);
@@ -166,106 +87,47 @@ void main() {
expect(reading.tightest?.label, 'Weekly');
});
- group('Claude source', () {
- test('maps the three windows the CLI itself shows', () async {
- final source = ClaudeUsageSource(
- dio: _dioAnswering({
+ group('CLI-reported windows', () {
+ test('maps Claude windows and preserves CLI account identity', () {
+ final reading = claudeUsageFromAnswer(
+ statusCode: 200,
+ account: 'opaque-account',
+ email: '[email protected]',
+ body: {
'five_hour': {'utilization': 2, 'resets_at': 1770000000},
'seven_day': {'used_percentage': 16},
'fable_weekly': {'utilization': 0},
- }),
- credentials: _creds(
- claudeJson: '{"claudeAiOauth":{"accessToken":"t"}}',
- claudeProfile: '{"oauthAccount":{"accountUuid":"acct-123","emailAddress":"[email protected]"}}',
- ),
+ },
);
- final reading = await source.read();
-
expect(reading.status, UsageStatus.ok);
+ expect(reading.account, 'opaque-account');
expect(reading.email, '[email protected]');
- expect(
- reading.account,
- usageAccountKey(UsageProvider.claude, 'acct-123'),
- );
expect(
reading.windows.map((w) => '${w.label} ${w.usedPercent.round()}'),
['Session 2', 'Weekly 16', 'Fable 0'],
);
- // Shortest window first, because that is the one about to bite.
- expect(reading.windows.first.label, 'Session');
});
-
- test('Fable is found under any of the three names it has had', () async {
+ test('maps every reported Fable spelling', () {
for (final key in [
'fable_weekly',
'fable_seven_day',
'seven_day_fable',
]) {
- final source = ClaudeUsageSource(
- dio: _dioAnswering({
- key: {'utilization': 7},
- }),
- credentials: _creds(
- claudeJson: '{"claudeAiOauth":{"accessToken":"t"}}',
- ),
- );
- final reading = await source.read();
- expect(reading.windows.single.label, 'Fable', reason: key);
- }
- });
-
- test('no credential is a sign-in, not a failure', () async {
- final reading = await ClaudeUsageSource(
- dio: _dioAnswering(const {}),
- credentials: _creds(),
- ).read();
- // Retrying a sign-out fails identically forever, so the two states must
- // not render the same.
- expect(reading.status, UsageStatus.signedOut);
- });
-
- test(
- 'an expired token is spent as a sign-in, not as a round trip',
- () async {
- var called = false;
- final dio = _dioAnswering(const {});
- dio.interceptors.add(
- InterceptorsWrapper(
- onRequest: (o, h) {
- called = true;
- h.next(o);
+ expect(
+ claudeUsageFromAnswer(
+ statusCode: 200,
+ body: {
+ key: {'utilization': 7},
},
- ),
+ ).windows.single.label,
+ 'Fable',
);
- final reading = await ClaudeUsageSource(
- dio: dio,
- credentials: _creds(
- claudeJson: '{"claudeAiOauth":{"accessToken":"t","expiresAt":1}}',
- ),
- ).read();
-
- expect(reading.status, UsageStatus.signedOut);
- expect(called, isFalse);
- },
- );
-
- test('a 401 is a sign-in and a 500 is a failure', () async {
- Future<UsageStatus> statusFor(int code) async => (await ClaudeUsageSource(
- dio: _dioAnswering(const {}, status: code),
- credentials: _creds(
- claudeJson: '{"claudeAiOauth":{"accessToken":"t"}}',
- ),
- ).read()).status;
-
- expect(await statusFor(401), UsageStatus.signedOut);
- expect(await statusFor(500), UsageStatus.failed);
+ }
});
- });
-
- group('Codex source', () {
- test('names each window by how long it actually is', () async {
- final source = CodexUsageSource(
- dio: _dioAnswering({
+ test('names Codex windows from reported durations', () {
+ final reading = codexUsageFromAnswer(
+ statusCode: 200,
+ body: {
'rate_limit': {
'primary_window': {
'used_percent': 9,
@@ -276,54 +138,31 @@ void main() {
'limit_window_seconds': 604800,
},
},
- }),
- credentials: _creds(
- codexJson: jsonEncode({
- 'tokens': {
- 'access_token': 't',
- 'account_id': 'acct',
- 'id_token':
- 'e30.${base64Url.encode(utf8.encode(jsonEncode({'email': '[email protected]'}))).replaceAll('=', '')}.signature',
- },
- }),
- ),
+ },
);
- final reading = await source.read();
-
- expect(reading.status, UsageStatus.ok);
- expect(reading.email, '[email protected]');
- expect(reading.account, usageAccountKey(UsageProvider.codex, 'acct'));
- // 18000s is 5h; 604800s is the week, which earns the name rather than
- // the arithmetic "7d".
expect(reading.windows.map((w) => w.label), ['5h', 'Weekly']);
expect(reading.windows.first.usedPercent, 9);
- });
-
- test(
- 'a window whose duration was never sent is not given a made-up one',
- () async {
- final reading = await CodexUsageSource(
- dio: _dioAnswering({
+ expect(
+ codexUsageFromAnswer(
+ statusCode: 200,
+ body: {
'rate_limit': {
'primary_window': {'used_percent': 9},
},
- }),
- credentials: _creds(
- codexJson: '{"tokens":{"access_token":"t","account_id":"acct"}}',
- ),
- ).read();
-
- // A confident "5h" beside a real percentage would be read as measured.
- expect(reading.windows.single.label, 'Limit');
- },
- );
-
- test('no auth.json is a sign-in, not a failure', () async {
- final reading = await CodexUsageSource(
- dio: _dioAnswering(const {}),
- credentials: _creds(),
- ).read();
- expect(reading.status, UsageStatus.signedOut);
+ },
+ ).windows.single.label,
+ 'Limit',
+ );
+ });
+ test('reported sign-out and failure stay distinct', () {
+ expect(
+ claudeUsageFromAnswer(statusCode: 401, body: {}).status,
+ UsageStatus.signedOut,
+ );
+ expect(
+ codexUsageFromAnswer(statusCode: 500, body: {}).status,
+ UsageStatus.failed,
+ );
});
});
diff --git a/desktop/test/web_tab_switcher_test.dart b/desktop/test/web_tab_switcher_test.dart
index 5be08710b..a3855e96e 100644
--- a/desktop/test/web_tab_switcher_test.dart
+++ b/desktop/test/web_tab_switcher_test.dart
@@ -311,7 +311,8 @@ void main() {
expect(find.byKey(const ValueKey('swarm-store-button')), findsNothing);
expect(
find.byKey(const ValueKey('workspace-subscription-usage')),
- findsOneWidget,
+ findsNothing,
+ reason: 'No CLI usage report was supplied by this fixture',
);
expect(
find.byKey(const ValueKey('workspace-machine-resources')),
diff --git a/desktop/test/windows_words_test.dart b/desktop/test/windows_words_test.dart
index a74b09d98..ca5437ea8 100644
--- a/desktop/test/windows_words_test.dart
+++ b/desktop/test/windows_words_test.dart
@@ -16,8 +16,6 @@ const _sayMacBehindACheck = {
'lib/shortcuts/shortcut_recorder.dart',
'lib/state/harness_monitor.dart',
'lib/super_tabs/team_account_setup.dart',
- // Platform copy is covered by swarm_join_account_choice_test.dart.
- 'lib/super_tabs/join_account_choice.dart',
'lib/super_tabs/voice_row.dart',
'lib/autonomous_device/autonomous_device_cli.dart',
'lib/devices/wifi_robots.dart',
diff --git a/docs/plans/2026-11-07-v3-agent-join-plan.md b/docs/plans/2026-11-07-v3-agent-join-plan.md
new file mode 100644
index 000000000..1ef8cd14f
--- /dev/null
+++ b/docs/plans/2026-11-07-v3-agent-join-plan.md
@@ -0,0 +1,86 @@
+# Swarm v3 agent join implementation plan
+
+> Implement task by task with tests committed and observed failing before code, followed by independent review and security reviews.
+
+**Goal:** Join an org by bringing an agent on this computer, and create Regular or PM agents without the old add-machine/Team-account sequence.
+**Architecture:** Reuse the authenticated join transport and native prompt surfaces. Own join widgets under `desktop/lib/super_tabs/join/`; keep shell wiring with #4118 and consume #4116's v3 command contract. Engine selection starts the person's own CLI settings. New Regular agents have no project; PM creation names and starts one.
+**Tech Stack:** Flutter/Dart; existing SuperTab request/controller, memory fixtures and fake sign-in.
+**Spec:** Task #4121; shared docs/specs/2026-11-07-swarm-v3.md from #4116.
+
+## Global Constraints
+
+- Desktop only, light and dark; no phone/web work.
+- No login reads, Team account setup, subscription relay or add-machine step.
+- Use existing native launch path; no process spawning in widgets.
+- Server/daemon enforce owner identity and capability. Never accept identity from form input.
+- Backend contract ships first. No legacy fallback that reads credentials or enrolls a machine.
+
+## Design
+
+- Growth: form state and operation receipts exist only for the current dialog; persisted agents/projects use #4116's bounded lifecycle.
+- Concurrency: one in-flight submission; retries reuse the operation ID. Backend/daemon own mutation locks.
+- Read cost: use existing local machine/engine observations, no new polling or full-state scans.
+- Scale: one bounded engine picker and one mutation per submission; no fan-out. Backend command latency is the first warning metric.
+- Compatibility: unsupported v3 backend reports an actionable upgrade error, never falls back to Team setup.
+- Migration/rollback: backend first; no Desktop data migration. Revert widgets if necessary without deleting agents/projects.
+- Audience: existing authenticated membership/visibility enforcement on server.
+- Identity: current signed-in person's local agent, never another machine owner's login.
+- Failure: visible bounded-time failure/retry, stable operation ID, account-change/dismiss guards.
+- Platforms: macOS, Linux, Windows Desktop; offscreen tests on macOS, no new process launch path.
+
+## Review Focus
+
+- Join acknowledgement followed by lost agent-start response retries without duplicating membership or Buddy.
+- Account switches and late responses cannot open another account's org or agent.
+- PM project name is trimmed/required; Regular creation sends no project.
+- Missing local daemon/engine is visible and recoverable without enrolling a remote machine.
+- No raw network errors or secrets appear in UI.
+
+## Task 1: Join with an engine
+
+**Files:** `desktop/lib/super_tabs/join/agent_dialog.dart`, existing `join_dialog.dart`; `desktop/test/swarm_v3_join_integration_test.dart`.
+**Interfaces:** authenticated join request; #4116 local bring-agent command; current-account guard; completion callback to select Buddy.
+
+- [x] Commit failing tests for engine selection, no Team/machine choice, join/Buddy completion, timeout/retry and account changes.
+- [x] Observe red, implement the flow using the confirmed contract, run affected join tests.
+- [x] Commit implementation and push draft PR.
+
+## Task 2: Regular or PM creation
+
+**Files:** `desktop/lib/super_tabs/join/new_agent_dialog.dart`; `desktop/test/swarm_v3_agent_dialog_test.dart`.
+**Interfaces:** `showSwarmNewAgentDialog` for #4118; current local machine and available engines; #4116 own-agent creation contract.
+
+- [x] Commit failing tests for Regular, PM project validation/start, duplicate submissions and safe visible failures.
+- [x] Observe red, implement native prompt and contract request, run affected tests.
+- [x] Commit and push; coordinate shell integration and remove obsolete join choice presentation.
+
+## Task 3: Evidence and handoff
+
+**Files:** screenshot fixture under `desktop/test/`; plan results.
+**Interfaces:** memory store/fake sign-in; light/dark captures of both flows.
+
+- [x] Capture both themes, analyze changed files, run style gate and affected integration tests.
+- [ ] Record red/green evidence, platforms and limitations; ready PR with review and two independent security reviews requested.
+
+## Authorized usage scope (#4121, River 00:17 VN)
+
+Desktop usage sources under `usage/` are in scope; #4117 owns CLI reporting. Delete credential readers and vendor endpoint calls. Read this computer and remote computers through their CLI reports; preserve local identity, account grouping and freshness. A source regression scans all Desktop code for login filenames/vendor endpoints, and prohibits I/O in the usage adapter layer.
+
+- [x] Commit regression and observe failures from existing credential sources.
+- [x] Remove sources; preserve window mapping as pure functions.
+- [x] Commit local CLI transport test, observe no local read, implement and verify local identity and freshness.
+- [ ] Confirm #4117 final report shape/capability before coordinated release.
+
+## Validation so far
+
+- Join/launcher/widget selection: 29 passed before additional screenshot cases; final capture group 9 passed (Bring agent light/dark, Regular and PM light/dark, guards and retries).
+- Usage transport/parser/controller: 24 passed; follow-up freshness group 22 passed.
+- Related usage presentation, account grouping, models menu, join-seen and Windows wording: 65 passed.
+- Join error presentation: 4 passed alongside capture group (13 total in that run).
+- New dialog/usage code analyzer: no issues. Full changed-file analysis also sees existing brace-style infos and two unused imports in the large shell/state files; no type errors.
+- UI style gate passes against origin/main.
+- Captures use memory fixtures, fake sign-in and capture fonts, on macOS offscreen. Windows/Linux signed-window checks remain independent platform evidence; this change adds no process-launch code.
+
+## Compatibility and ownership
+
+Use #4116 Buddy preparation and own-agent commands. An unlisted computer is silently listed for Regular/PM only, with no machine UI or Team-account setup. Backend must ship first; unsupported commands show Update Harness. #4118 owns the shell entry. Integration removes the replaced join choice, automatic enrollment and obsolete post-enrollment note listener. #4117 must supply CLI-only quota reports before release; no Desktop vendor fallback remains.