The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Desktop: a new joiner's first Bring agent works, and the join forms explain themselves (#4442) (#3530)
0xken15a1c62e12f232
diff --git a/desktop/lib/state/harness_launch_integration.dart b/desktop/lib/state/harness_launch_integration.dartindex e7233666f..cf987593b 100644--- a/desktop/lib/state/harness_launch_integration.dart+++ b/desktop/lib/state/harness_launch_integration.dart@@ -47,8 +47,15 @@ class HarnessLaunchIntegration {this.agentKind,this.ownMachinesOnly = false,this.startBuddy,+ this.stopBuddy,+ this.heading,+ this.intro,});final String creationId, actionLabel;++ /// What the form is for and one sentence on it, above its pickers, where+ /// the form alone doesn't say: Join's Bring agent (#4442). Null shows none.+ final String? heading, intro;String? swarmRole;String? swarmSkillMode;@@ -84,6 +91,10 @@ class HarnessLaunchIntegration {/// project and takes no first message.final Future<void> Function(String machineId, String engine)? startBuddy;+ /// Stops [startBuddy] while it only waits for the computer, so the form+ /// closes at once; false once the start is sent (#4442).+ final bool Function()? stopBuddy;+/// A new project in a Swarm: the Swarm's machines its Product Manager may/// start on, best first. The form then shows only the task, repo and/// visibility, with the machine on a "Product Manager:" line. Null keepsdiff --git a/desktop/lib/state/new_harness.dart b/desktop/lib/state/new_harness.dartindex 2b552feb4..0535e59eb 100644--- a/desktop/lib/state/new_harness.dart+++ b/desktop/lib/state/new_harness.dart@@ -3698,8 +3698,7 @@ class NewHarnessController extends ChangeNotifier {])if (!machine.machine.isShared &&(integration?.ownMachinesOnly != true ||- !machine.belongsToOtherAccount &&- !machine.machine.isTeamAccount))+ !machine.belongsToOtherAccount && !machine.machine.isTeamAccount))NewHarnessOption(id: machine.machine.machineId,title: machine.machine.displayName,@@ -4564,7 +4563,7 @@ class NewHarnessController extends ChangeNotifier {warn('Linking the profile. You can close once it is done.');return false;}- if (busy) {+ if (busy && integration?.stopBuddy?.call() != true) {warn('Still working on it. You can close once it is done.');return false;}diff --git a/desktop/lib/super_tabs/join/agent_launcher.dart b/desktop/lib/super_tabs/join/agent_launcher.dartindex bab3b9ee6..a110ccd5c 100644--- a/desktop/lib/super_tabs/join/agent_launcher.dart+++ b/desktop/lib/super_tabs/join/agent_launcher.dart@@ -1,3 +1,9 @@+import 'dart:async';++import 'package:clock/clock.dart';++import '../../logging/app_log.dart';+/// 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 {@@ -31,8 +37,23 @@ class SwarmAgentLauncher {command;final bool _listed;Map<String, dynamic>? _prepared;+ bool _sent = false, _stopped = false;++ /// The person closed the form before the start was sent: nothing exists+ /// yet, so the wait for the computer ends here (#4442). False once+ /// buddy.create is on its way, which only its answer settles.+ bool stop() {+ if (_sent) return false;+ _stopped = true;+ return true;+ }void _guard() {+ if (_stopped) {+ throw const SwarmAgentLaunchFailure(+ 'You closed the form before your Buddy started.',+ );+ }if (!isCurrent()) {throw const SwarmAgentLaunchFailure('Your account changed. Close this form and try again.',@@ -40,15 +61,37 @@ class SwarmAgentLauncher {}}+ /// Fails only with a [SwarmAgentLaunchFailure]: a timeout or a raw error+ /// becomes a sentence naming the computer, never its text.Future<Map<String, dynamic>> create(String engine, String operationId) async {+ try {+ return await _create(engine, operationId);+ } on SwarmAgentLaunchFailure {+ rethrow;+ } on TimeoutException {+ throw SwarmAgentLaunchFailure(+ '$machineName didn’t answer in time. Check that Harness is running there, then try again.',+ );+ } catch (failure) {+ appLog.info(+ 'super-tabs',+ 'own-agent start failed: ${failure.runtimeType}',+ );+ throw SwarmAgentLaunchFailure(+ 'Couldn’t reach Harness on $machineName. Check that it’s running, then try again.',+ );+ }+ }++ Future<Map<String, dynamic>> _create(+ String engine,+ String operationId,+ ) async {_guard();// A computer the Swarm does not list yet is recorded Buddy-only with its// folder and engines (backend buddy.create setup).if (!_listed) {- _prepared ??= await prepare(- '$operationId-prepare',- ).timeout(const Duration(seconds: 25));- _guard();+ _prepared ??= await _prepareUntilReady('$operationId-prepare');_prepared = {..._prepared!,'engines': [@@ -58,6 +101,7 @@ class SwarmAgentLauncher {};}_guard();+ _sent = true;final result = await command({'type': 'buddy.create','machineId': machineId,@@ -67,4 +111,24 @@ class SwarmAgentLauncher {_guard();return result;}++ /// The computer answers "preparing" while it sets the folder up, which a+ /// first ask always gets: ask again a second apart, as Add computer does+ /// (machines.dart), for up to five minutes.+ Future<Map<String, dynamic>> _prepareUntilReady(String operationId) async {+ final deadline = clock.now().add(const Duration(minutes: 5));+ while (true) {+ final answer = await prepare(operationId)+ .timeout(const Duration(seconds: 25));+ _guard();+ if (answer['state'] != 'preparing') return answer;+ if (clock.now().isAfter(deadline)) {+ throw SwarmAgentLaunchFailure(+ '$machineName is still preparing your agent’s folder. Try again in a minute.',+ );+ }+ await Future<void>.delayed(const Duration(seconds: 1));+ _guard();+ }+ }}diff --git a/desktop/lib/super_tabs/join/bring_agent.dart b/desktop/lib/super_tabs/join/bring_agent.dartindex b9a393292..e3c38cea1 100644--- a/desktop/lib/super_tabs/join/bring_agent.dart+++ b/desktop/lib/super_tabs/join/bring_agent.dart@@ -68,11 +68,7 @@ Future<Map<String, dynamic>?> showBringAgentForm('operationId': operation,}).timeout(const Duration(seconds: 20));- if (prepared['state'] == 'preparing') {- throw const SwarmAgentLaunchFailure(- 'Your agent’s folder is still being prepared. Try again to check it.',- );- }+ if (prepared['state'] == 'preparing') return prepared;if (prepared['state'] != 'ready' ||prepared['cwd'] is! String ||prepared['engines'] is! List) {@@ -90,13 +86,25 @@ Future<Map<String, dynamic>?> showBringAgentForm(final pending = controller.pendingCommand;if (pending != null && jsonEncode(pending) != jsonEncode(command)) {throw const SwarmAgentLaunchFailure(- 'Finish or retry the pending action in this org first.',+ 'Finish or retry the pending action in this Swarm first.',);}final result = pending == null? await controller.command(command, operationId: operation): await controller.retry();if (result != null) return result;+ final refusal = controller.operationError;+ if (controller.pendingCommand == null &&+ refusal != null &&+ !const {+ 'INVALID_COMMAND',+ 'VALIDATION_ERROR',+ 'UPDATE_REQUIRED',+ }.contains(controller.operationErrorCode)) {+ // Refused, with nothing kept to retry: the server's own sentence+ // (a full or paused computer, say).+ throw SwarmAgentLaunchFailure(refusal);+ }if (const {'INVALID_COMMAND','VALIDATION_ERROR',@@ -113,9 +121,16 @@ Future<Map<String, dynamic>?> showBringAgentForm();Map<String, dynamic>? started;String? startedOn;+ SwarmAgentLauncher? starting;+ final swarm = controller.snapshot?.name ?? 'this Swarm';final integration = HarnessLaunchIntegration(creationId: superTabOperationId(),actionLabel: 'Bring agent',+ heading: 'Bring your agent to $swarm',+ intro:+ 'Your Buddy is your own agent in $swarm: it runs on your computer, '+ 'under your sign-in, and you can also start it later from your Buddy '+ 'chat.',engines: const ['claude', 'codex'],ownMachinesOnly: true,prepare: (_, task, _) async => task,@@ -126,7 +141,13 @@ Future<Map<String, dynamic>?> showBringAgentForm(launcherFor(machineId),superTabOperationId(),);- final result = await launcher.create(engine, operation);+ starting = launcher;+ final Map<String, dynamic> result;+ try {+ result = await launcher.create(engine, operation);+ } finally {+ starting = null;+ }if (result['agentId'] is! String && result['startId'] is! String) {throw const SwarmAgentLaunchFailure('Your agent’s start is not confirmed. Try again to check it.',@@ -135,6 +156,7 @@ Future<Map<String, dynamic>?> showBringAgentForm(started = result;startedOn = machineId;},+ stopBuddy: () => starting?.stop() ?? false,);final box = NewHarnessController(app,@@ -151,6 +173,9 @@ Future<Map<String, dynamic>?> showBringAgentForm(context: context,transitionDuration: Duration.zero,veilBlur: 0,+ // The offer doesn't come back by itself: only ×, Not now or Esc, each+ // a choice, close it; a stray click outside doesn't (#4442).+ barrierDismissible: false,builder: (dialog) => Padding(padding: const EdgeInsets.all(DesktopChrome.panelPadding),child: NewHarnessForm(diff --git a/desktop/lib/super_tabs/join_dialog.dart b/desktop/lib/super_tabs/join_dialog.dartindex 18915a9b5..ffc58f581 100644--- a/desktop/lib/super_tabs/join_dialog.dart+++ b/desktop/lib/super_tabs/join_dialog.dart@@ -177,6 +177,10 @@ class _SwarmJoinDialogState extends State<SwarmJoinDialog> {Map<String, dynamic>? _preview;bool _loading = true, _joining = false;String? _error;++ /// The link can never work for this account (revoked, invalid, not+ /// theirs): Close is the only action, never a Retry that fails again.+ bool _unavailable = false;String get _path =>'/api/super-tabs/${Uri.encodeComponent(widget.link.tabId)}/join';Map<String, dynamic> get _token => {@@ -263,6 +267,7 @@ class _SwarmJoinDialogState extends State<SwarmJoinDialog> {'LINK_REVOKED','JOIN_UNAVAILABLE',}.contains(failure.code)) {+ _unavailable = true;return 'This link is unavailable for your account. Ask the owner for an invitation.';}if (failure.code == 'SIGNED_OUT' || failure.code == 'ACCOUNT_CHANGED') {@@ -313,17 +318,23 @@ class _SwarmJoinDialogState extends State<SwarmJoinDialog> {actions: [FilledButton(key: const Key('swarm-join-confirm'),- onPressed: _loading || _joining+ onPressed: _unavailable+ ? () => Navigator.pop(context)+ : _loading || _joining? null: _preview == null? _load: _join,+ // Named for what it will do: Join Swarm while the invitation loads,+ // Retry only after a failure a retry can fix (audit finding 13).child: Text(- _joining+ _unavailable+ ? 'Close'+ : _joining? 'Joining…'- : _preview == null+ : _preview == null && !_loading? 'Retry'- : _preview!['alreadyMember'] == true+ : _preview?['alreadyMember'] == true? 'Open Swarm': 'Join Swarm',),diff --git a/desktop/lib/widgets/new_harness_form.dart b/desktop/lib/widgets/new_harness_form.dartindex 42bc1de4b..58284cb26 100644--- a/desktop/lib/widgets/new_harness_form.dart+++ b/desktop/lib/widgets/new_harness_form.dart@@ -1721,6 +1721,24 @@ class NewHarnessFormState extends State<NewHarnessForm> {child: Column(crossAxisAlignment: CrossAxisAlignment.stretch,children: [+ if (box.integration?.heading+ case final heading?) ...[+ Text(+ heading,+ style: DesktopChrome.heading(),+ ),+ if (box.integration?.intro+ case final intro?) ...[+ const SizedBox(height: 4),+ Text(+ intro,+ style: DesktopChrome.text(+ color: DesktopChrome.muted,+ ),+ ),+ ],+ const SizedBox(height: 14),+ ],_desktopHeader(),const SizedBox(height: 12),if (_installing case final run?)@@ -2649,6 +2667,15 @@ class NewHarnessFormState extends State<NewHarnessForm> {if (includeProjectVisibility &&box.integration?.projectVisibility != null)_desktopProjectVisibility(9.95),+ // A Buddy is an offer: saying no is as plain as saying yes (#4442).+ if (box.bringsBuddy && !widget.embedded)+ TextButton(+ key: const ValueKey('new-harness-not-now'),+ onPressed: () {+ if (box.requestDismiss()) widget.onClose();+ },+ child: const Text('Not now'),+ ),_desktopStartButton(),],);diff --git a/desktop/test/swarm_first_join_widget_test.dart b/desktop/test/swarm_first_join_widget_test.dartindex 7e19b8686..1ed065153 100644--- a/desktop/test/swarm_first_join_widget_test.dart+++ b/desktop/test/swarm_first_join_widget_test.dart@@ -2,14 +2,23 @@ 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/widgets/new_harness_form.dart';+import 'package:harness/super_tabs/controller.dart';import 'package:harness/super_tabs/join_dialog.dart';+import 'package:harness/super_tabs/join_link.dart';import 'support/capture.dart';import 'swarm_join_any_test.dart' show newMember, expectNoEnrollment;import 'super_tab_launch_test.dart' show tabId;+import 'dart:async';import 'dart:io';+import 'package:harness/ws/ws_conn.dart';++const bringAgentIntro =+ 'Your Buddy is your own agent in Pilot: it runs on your computer, under '+ 'your sign-in, and you can also start it later from your Buddy chat.';+void main() {final shots = Platform.environment['HARNESS_V3_JOIN_SHOTS'];setUpAll(() => loadCaptureFonts(shots));@@ -50,10 +59,20 @@ void main() {);expect(find.text('Separate Harness Team account'), findsNothing);expect(find.text('Add machine'), findsNothing);+ // Audit finding 10 (#4442): it names the Swarm, says what it does and+ // that it can wait.+ expect(find.text('Bring your agent to Pilot'), findsOneWidget);+ expect(find.text(bringAgentIntro), findsOneWidget);+ expect(find.text('Not now'), findsOneWidget);await captureWindow(tester, shots, 'bring-agent-${brightness.name}');if (brightness == Brightness.dark) {- await tester.tap(find.byKey(const ValueKey('new-harness-close')));+ // A stray click outside keeps the offer; Not now closes it.+ await tester.tapAt(const Offset(4, 4));+ await tester.pumpAndSettle();+ expect(find.byType(NewHarnessForm), findsOneWidget);+ await tester.tap(find.text('Not now'));await tester.pumpAndSettle();+ expect(find.byType(NewHarnessForm), findsNothing);await tester.runAsync(() => joining);expectNoEnrollment(f);} else {@@ -61,16 +80,25 @@ void main() {await tester.tap(find.text('Bring agent'));await pumpEventQueue();});- await tester.pumpAndSettle();- // The machine prepares its Buddy folder on the first ask, as a real- // one may; the person tries again.- if (find.textContaining('still being prepared').evaluate().isNotEmpty) {- await tester.runAsync(() async {- await tester.tap(find.text('Bring agent'));- await pumpEventQueue();- });- await tester.pumpAndSettle();+ // The computer answers its first ask "preparing", as a real one does+ // for a Swarm that doesn't list it yet: one click still starts the+ // Buddy (audit finding 2, #4442).+ // The ask again is a second later, in real time: wait for the form+ // to close, up to ten seconds.+ for (+ var i = 0;+ i < 100 && find.byType(NewHarnessForm).evaluate().isNotEmpty;+ i+++ ) {+ await tester.runAsync(+ () => Future<void>.delayed(const Duration(milliseconds: 100)),+ );+ await tester.pump();}+ // Past the opened Swarm's view save.+ await tester.pump(const Duration(seconds: 1));+ await tester.pumpAndSettle();+ expect(find.textContaining('still being prepared'), findsNothing);expect(find.byType(NewHarnessForm), findsNothing);await tester.runAsync(() => joining);final starts = f.connection.server.posts.where(@@ -91,4 +119,177 @@ void main() {f.dispose();});}++ // Audit findings 2 and 10 (#4442): while the computer prepares the form+ // keeps "Starting your Buddy…"; a refused start says the server's reason,+ // not "not confirmed".+ for (final brightness in Brightness.values) {+ testWidgets(+ 'a refused Bring agent shows the server\'s reason 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();+ f.connection+ ..backendFailureOnCommandsOnly = true+ ..backendFailure = const WsRequestFailure(+ responseType: 'super_tabs_result',+ code: 'MACHINE_FULL',+ detail: 'My Mac is running as many agents as it allows.',+ payload: {'status': 409},+ );+ await tester.runAsync(() async {+ await tester.tap(find.text('Bring agent'));+ await pumpEventQueue();+ });+ await tester.pump();+ // The first ask answered "preparing": it waits, saying so.+ expect(find.textContaining('Starting your Buddy on'), findsOneWidget);+ await captureWindow(+ tester,+ shots,+ 'bring-agent-preparing-${brightness.name}',+ );+ const reason = 'My Mac is running as many agents as it allows.';+ for (var i = 0; i < 100 && find.text(reason).evaluate().isEmpty; i++) {+ await tester.runAsync(+ () => Future<void>.delayed(const Duration(milliseconds: 100)),+ );+ await tester.pump();+ }+ expect(find.text(reason), findsOneWidget);+ expect(find.textContaining('not confirmed'), findsNothing);+ await captureWindow(+ tester,+ shots,+ 'bring-agent-refused-${brightness.name}',+ );+ await tester.tap(find.text('Not now'));+ await tester.pumpAndSettle();+ await tester.runAsync(() => joining);+ await tester.pumpWidget(const SizedBox());+ f.dispose();+ },+ );+ }++ // Review of #4442: a computer that stays preparing never holds the form+ // open; Not now closes it at once and nothing starts.+ testWidgets('Not now while the computer prepares closes and starts nothing', (+ tester,+ ) async {+ 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.light),+ 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();+ f.connection.keepPreparing = true;+ await tester.runAsync(() async {+ await tester.tap(find.text('Bring agent'));+ await pumpEventQueue();+ });+ await tester.pump();+ expect(find.textContaining('Starting your Buddy on'), findsOneWidget);+ await tester.tap(find.text('Not now'));+ await tester.pump();+ await tester.pump();+ expect(find.textContaining('Still working on it'), findsNothing);+ expect(find.byType(NewHarnessForm), findsNothing);+ // Ready now, in real time past the next ask: the closed form starts nothing.+ f.connection.keepPreparing = false;+ await tester.runAsync(+ () => Future<void>.delayed(const Duration(milliseconds: 1500)),+ );+ await tester.pump();+ await tester.runAsync(() => joining);+ expect(+ f.connection.server.posts.where(+ (post) => (post['command'] as Map)['type'] == 'buddy.create',+ ),+ isEmpty,+ );+ await tester.pumpWidget(const SizedBox());+ f.dispose();+ });++ // Audit finding 13 (#4442), in both themes for the pull request.+ for (final brightness in Brightness.values) {+ testWidgets('join dialog loading and dead link in ${brightness.name}', (+ tester,+ ) async {+ grid.AppTheme.brightness.value = brightness;+ addTearDown(() => grid.AppTheme.brightness.value = Brightness.light);+ await tester.binding.setSurfaceSize(const Size(720, 420));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ Future<void> show(String name, SuperTabRequest request) async {+ await tester.pumpWidget(+ MaterialApp(+ debugShowCheckedModeBanner: false,+ theme: grid.buildAppTheme(brightness: brightness),+ home: Scaffold(+ body: Center(+ child: SizedBox(+ width: 480,+ child: SwarmJoinDialog(+ key: ValueKey(name),+ link: const SwarmJoinLink('tab', token: 'invite'),+ accountEmail: '[email protected]',+ isCurrent: () => true,+ onJoined: (_, _) {},+ request: request,+ ),+ ),+ ),+ ),+ ),+ );+ await tester.pump();+ await captureWindow(tester, shots, 'join-$name-${brightness.name}');+ }++ final loading = Completer<Map<String, dynamic>>();+ await show('loading', (_, _, {body}) => loading.future);+ expect(find.text('Join Swarm'), findsWidgets);+ expect(find.text('Retry'), findsNothing);+ await show(+ 'dead-link',+ (_, _, {body}) async =>+ throw const SuperTabFailure('LINK_REVOKED', 'x', statusCode: 410),+ );+ expect(find.text('Close'), findsOneWidget);+ expect(find.text('Retry'), findsNothing);+ loading.complete({'id': 'tab', 'name': 'Pilot', 'role': 'viewer'});+ await tester.pumpWidget(const SizedBox());+ });+ }}diff --git a/desktop/test/swarm_sharing_test.dart b/desktop/test/swarm_sharing_test.dartindex d8b4a2c70..5c725092f 100644--- a/desktop/test/swarm_sharing_test.dart+++ b/desktop/test/swarm_sharing_test.dart@@ -718,11 +718,82 @@ void main() {),findsOneWidget,);- expect(find.text('Retry'), findsOneWidget);+ // Audit finding 13 (#4442): a link that can't work offers only Close.+ expect(find.text('Retry'), findsNothing);+ expect(+ tester.widget<FilledButton>(find.byKey(const Key('swarm-join-confirm'))),+ isA<FilledButton>().having(+ (b) => (b.child as Text).data,+ 'label',+ 'Close',+ ),+ );expect(find.text('private server text'), findsNothing);expect(opened, false);});+ testWidgets(+ 'while the invitation loads the button reads Join Swarm, greyed',+ (tester) async {+ final answer = Completer<Map<String, dynamic>>();+ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(+ body: SwarmJoinDialog(+ link: _link,+ accountEmail: '[email protected]',+ isCurrent: () => true,+ onJoined: (_, _) {},+ request: (_, _, {body}) => answer.future,+ ),+ ),+ ),+ );+ await tester.pump();+ final button = tester.widget<FilledButton>(+ find.byKey(const Key('swarm-join-confirm')),+ );+ expect((button.child as Text).data, 'Join Swarm');+ expect(button.onPressed, isNull);+ expect(find.text('Retry'), findsNothing);+ answer.complete({'id': _link.tabId, 'name': 'Pilot', 'role': 'viewer'});+ await tester.pumpAndSettle();+ },+ );++ testWidgets('a lost connection keeps Retry, which loads again', (+ tester,+ ) async {+ var asks = 0;+ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(+ body: SwarmJoinDialog(+ link: _link,+ accountEmail: '[email protected]',+ isCurrent: () => true,+ onJoined: (_, _) {},+ request: (_, _, {body}) async {+ if (asks++ == 0) throw const SocketException('offline');+ return {'id': _link.tabId, 'name': 'Pilot', 'role': 'viewer'};+ },+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ expect(+ find.text(+ 'Could not open this Swarm. Check your connection and try again.',+ ),+ findsOneWidget,+ );+ await tester.tap(find.text('Retry'));+ await tester.pumpAndSettle();+ expect(find.text('Pilot'), findsOneWidget);+ expect(find.text('Join Swarm'), findsWidgets);+ });+// Scholes, 2026-10-29: joining adds this computer, so only a join that made// the person a member says so, with the role; someone already in it, never.testWidgets('tells only a new member\'s join, with its role', (tester) async {diff --git a/desktop/test/swarm_v3_agent_launcher_test.dart b/desktop/test/swarm_v3_agent_launcher_test.dartindex df8a04a3f..eef085d8b 100644--- a/desktop/test/swarm_v3_agent_launcher_test.dart+++ b/desktop/test/swarm_v3_agent_launcher_test.dart@@ -1,38 +1,38 @@+import 'dart:async';++import 'package:fake_async/fake_async.dart';import 'package:flutter_test/flutter_test.dart';import 'package:harness/super_tabs/join/agent_launcher.dart';// The Buddy a person brings as they join starts through the Swarm on their own// computer (buddy.create), whichever form chose its engine (task #4196).void main() {- test(- 'a Buddy 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 {'startId': 'start', 'conversationId': 'chat'};- },- );- final result = await launcher.create('codex', 'operation');- expect(result['startId'], 'start');- expect(sent, hasLength(1));- expect(sent.single['type'], 'buddy.create');- expect(sent.single['machineId'], 'local');- expect(sent.single['setup'], containsPair('cwd', '/work'));- expect((sent.single['setup'] as Map)['engines'], ['codex']);- expect(sent.toString(), isNot(contains('teamSetup')));- },- );+ test('a Buddy 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 {'startId': 'start', 'conversationId': 'chat'};+ },+ );+ final result = await launcher.create('codex', 'operation');+ expect(result['startId'], 'start');+ expect(sent, hasLength(1));+ expect(sent.single['type'], 'buddy.create');+ expect(sent.single['machineId'], 'local');+ expect(sent.single['setup'], containsPair('cwd', '/work'));+ expect((sent.single['setup'] as Map)['engines'], ['codex']);+ expect(sent.toString(), isNot(contains('teamSetup')));+ });test('a computer already in the Swarm sends no setup', () async {final sent = <Map<String, dynamic>>[];@@ -72,7 +72,10 @@ void main() {return {'startId': 'one'};},);- await expectLater(launcher.create('claude', 'op'), throwsStateError);+ await expectLater(+ launcher.create('claude', 'op'),+ throwsA(isA<SwarmAgentLaunchFailure>()),+ );await launcher.create('claude', 'op');expect(prepares, 1);expect(ops.toSet(), {'op-start'});@@ -99,4 +102,182 @@ void main() {throwsA(isA<SwarmAgentLaunchFailure>()),);});++ // Audit finding 2 (#4442): a computer the Swarm doesn't list yet answers its+ // first ask "preparing"; the start waits for it, as Add computer does.+ test(+ 'a computer still preparing is asked again until ready, and starts once',+ () {+ fakeAsync((async) {+ final asks = <String>[];+ final sent = <Map<String, dynamic>>[];+ final launcher = SwarmAgentLauncher(+ machineId: 'local',+ machineName: 'Mac',+ inSwarm: false,+ isCurrent: () => true,+ prepare: (op) async {+ asks.add(op);+ return asks.length < 3+ ? {'state': 'preparing'}+ : {+ 'cwd': '/work',+ 'engines': ['claude'],+ };+ },+ command: (command, op) async {+ sent.add(command);+ return {'startId': 'one'};+ },+ );+ Map<String, dynamic>? result;+ Object? failure;+ launcher+ .create('claude', 'op')+ .then<void>(+ (r) {+ result = r;+ },+ onError: (Object e) {+ failure = e;+ },+ );+ async.elapse(const Duration(seconds: 5));+ expect(failure, isNull);+ expect(result?['startId'], 'one');+ expect(asks, ['op-prepare', 'op-prepare', 'op-prepare']);+ expect(sent.single['setup'], containsPair('cwd', '/work'));+ expect((sent.single['setup'] as Map).containsKey('state'), isFalse);+ });+ },+ );++ // Review of #4442: closing the form while the computer prepares stops the+ // wait; nothing is started, and once the start is sent it can't stop.+ test(+ 'stop during the preparing wait sends no start; after it, stop refuses',+ () {+ fakeAsync((async) {+ var asks = 0;+ final sent = <Map<String, dynamic>>[];+ final launcher = SwarmAgentLauncher(+ machineId: 'local',+ machineName: 'Mac',+ inSwarm: false,+ isCurrent: () => true,+ prepare: (op) async {+ asks++;+ return {'state': 'preparing'};+ },+ command: (command, op) async {+ sent.add(command);+ return {'startId': 'one'};+ },+ );+ Object? failure;+ launcher.create('claude', 'op').catchError((Object e) {+ failure = e;+ return <String, dynamic>{};+ });+ async.elapse(const Duration(seconds: 3));+ expect(launcher.stop(), isTrue);+ final asked = asks;+ async.elapse(const Duration(seconds: 10));+ expect(failure, isA<SwarmAgentLaunchFailure>());+ expect(asks, asked);+ expect(sent, isEmpty);++ final listed = SwarmAgentLauncher(+ machineId: 'local',+ machineName: 'Mac',+ inSwarm: true,+ isCurrent: () => true,+ prepare: (op) async => throw StateError('must not prepare'),+ command: (command, op) => Completer<Map<String, dynamic>>().future,+ );+ listed.create('claude', 'op').ignore();+ async.flushMicrotasks();+ expect(listed.stop(), isFalse);+ });+ },+ );++ test('a computer that never finishes preparing gives up in plain words', () {+ fakeAsync((async) {+ final launcher = SwarmAgentLauncher(+ machineId: 'local',+ machineName: 'Mac',+ inSwarm: false,+ isCurrent: () => true,+ prepare: (op) async => {'state': 'preparing'},+ command: (command, op) async => throw StateError('must not send'),+ );+ Object? failure;+ launcher.create('claude', 'op').catchError((Object e) {+ failure = e;+ return <String, dynamic>{};+ });+ async.elapse(const Duration(minutes: 4));+ expect(failure, isNull);+ async.elapse(const Duration(minutes: 2));+ expect(+ failure,+ isA<SwarmAgentLaunchFailure>().having(+ (f) => f.message,+ 'message',+ 'Mac is still preparing your agent’s folder. Try again in a minute.',+ ),+ );+ });+ });++ // Audit finding 10 (#4442): never a raw TimeoutException or daemon error.+ test('a computer that doesn\'t answer times out in plain words', () {+ fakeAsync((async) {+ final launcher = SwarmAgentLauncher(+ machineId: 'local',+ machineName: 'Mac',+ inSwarm: false,+ isCurrent: () => true,+ prepare: (op) => Completer<Map<String, dynamic>>().future,+ command: (command, op) async => throw StateError('must not send'),+ );+ Object? failure;+ launcher.create('claude', 'op').catchError((Object e) {+ failure = e;+ return <String, dynamic>{};+ });+ async.elapse(const Duration(seconds: 30));+ expect(+ failure,+ isA<SwarmAgentLaunchFailure>().having(+ (f) => f.message,+ 'message',+ 'Mac didn’t answer in time. Check that Harness is running there, then try again.',+ ),+ );+ });+ });++ test('a raw failure becomes a sentence without its text', () async {+ final launcher = SwarmAgentLauncher(+ machineId: 'local',+ machineName: 'Mac',+ inSwarm: true,+ isCurrent: () => true,+ prepare: (op) async => throw StateError('unused'),+ command: (command, op) async =>+ throw StateError('/Users/someone/private path'),+ );+ await expectLater(+ launcher.create('claude', 'op'),+ throwsA(+ isA<SwarmAgentLaunchFailure>().having(+ (f) => f.message,+ 'message',+ 'Couldn’t reach Harness on Mac. Check that it’s running, then try again.',+ ),+ ),+ );+ });}diff --git a/docs/plans/2026-11-07-desktop-bring-agent-join-plan.md b/docs/plans/2026-11-07-desktop-bring-agent-join-plan.mdnew file mode 100644index 000000000..1e46e53dd--- /dev/null+++ b/docs/plans/2026-11-07-desktop-bring-agent-join-plan.md@@ -0,0 +1,124 @@+# Bring agent and Join dialog fixes Implementation Plan++> Written by the writing-plans skill as this project's Engineer role adapts it: the Engineer implements it task by+> task, test first, each failing test committed before its code; the pull request's review step is the one review.++**Goal:** A new joiner's first Bring agent starts their Buddy on one click, the bring-agent form says what it is and+survives a stray click, its errors are plain words or the server's own reason, and the Join dialog offers Retry only+after a failure that a retry can fix (audit findings 2, 10 and 13, task #4442).++**Architecture:** `SwarmAgentLauncher` (`super_tabs/join/agent_launcher.dart`) asks the computer to prepare again+every second while it answers `preparing`, as Add computer does (`super_tabs/machines.dart` `_prepareContribution`),+and turns a timeout or any other raw failure into a `SwarmAgentLaunchFailure` sentence. `showBringAgentForm` passes a+heading and one sentence to the Cmd-N form through `HarnessLaunchIntegration`, which the form shows above its pickers+with a Not now button beside Bring agent; the dialog no longer closes on a click outside. `SwarmJoinDialog` labels+its button by what it will do.++**Tech Stack:** Flutter (Dart), flutter_test, fake_async, the `SuperTabLaunchFixture` memory store and fake sign-in.++**Spec:** `docs/audits/2026-11-07-desktop-1.3.89.md` findings 2, 10 and 13 (PR #3526, task #4436).++## Global Constraints++- Desktop only (`desktop/lib/`); no server change.+- Reuse existing components and styles: `DesktopChrome` text styles, the form's own buttons.+- Desktop tests use a memory store and a fake sign-in; never sign in or read a login.+- Copy says "Swarm", never "org".+- Light and dark screenshots of each changed screen in the pull request.+- Platforms: shared Flutter code, so macOS, Windows and Linux alike; checked offscreen on macOS.++## Review Focus++- A computer that stays `preparing` for minutes: the form keeps "Starting your Buddy on <computer>…" and gives up+ after 5 minutes with a sentence, never a spinner forever (Task 1 test: never-ready computer).+- The account changing while it polls: no start is sent (Task 1 keeps `_guard()` after every answer).+- A refused start versus a lost answer: a refusal shows the server's sentence; a lost answer keeps "not confirmed,+ try again" and its receipt, so a second click cannot start a second Buddy (Task 2 tests both).+- Esc still closes the form: a key press is a choice, a click outside is not; the copy says how to start later.+- A link that fails on the network keeps Retry; only an unavailable link loses it (Task 3 tests both).++---++### Task 1: Bring agent waits while the folder is prepared (finding 2)++**Files:**+- Modify: `desktop/lib/super_tabs/join/agent_launcher.dart`+- Modify: `desktop/lib/super_tabs/join/bring_agent.dart:72-98`+- Test: `desktop/test/swarm_v3_agent_launcher_test.dart`, `desktop/test/swarm_first_join_widget_test.dart`++**Interfaces:**+- `SwarmAgentLauncher.prepare` may now return `{'state': 'preparing'}`; any other answer is the setup.+- `create` polls `prepare` with the same operation id every 1 s, each ask bounded by 25 s, for at most 5 minutes.++- [ ] **Step 1: Write the failing tests**+ - `a computer still preparing is asked again until ready, and starts once` (fake_async): prepare answers+ preparing, preparing, then the setup; expect 3 asks, all `op-prepare`, and one `buddy.create`.+ - `a computer that never finishes preparing gives up in plain words`: prepare always answers preparing; after+ 5 minutes `create` throws `SwarmAgentLaunchFailure` whose message names the computer and no command is sent.+ - In `swarm_first_join_widget_test.dart`, remove the second click: one click on Bring agent starts the Buddy.+- [ ] **Step 2: Run them and see them fail**: `flutter test test/swarm_v3_agent_launcher_test.dart+ test/swarm_first_join_widget_test.dart`; expected: "still being prepared" failures.+- [ ] **Step 3: Implement the poll in `create`; `bring_agent.dart`'s prepare returns the preparing answer as is.**+- [ ] **Step 4: Run them and see them pass.**+- [ ] **Step 5: Commit.**++### Task 2: The bring-agent form explains itself and keeps its offer (finding 10)++**Files:**+- Modify: `desktop/lib/state/harness_launch_integration.dart` (add `heading`, `intro`)+- Modify: `desktop/lib/widgets/new_harness_form.dart` (show them; Not now beside the action for a Buddy)+- Modify: `desktop/lib/super_tabs/join/bring_agent.dart`, `desktop/lib/super_tabs/join/agent_launcher.dart`,+- Test: `desktop/test/swarm_first_join_widget_test.dart`, `desktop/test/swarm_v3_agent_launcher_test.dart`++**Interfaces:**+- `HarnessLaunchIntegration({String? heading, String? intro})`: null shows nothing, as today.+- The Swarm's name is the controller's snapshot name; `showBringAgentForm` keeps its signature.++Copy, exact:+- Heading: `Bring your agent to <Swarm>`.+- Intro: `Your Buddy is your own agent in <Swarm>: it runs on your computer, under your sign-in, and you can also+ start it later from your Buddy chat.`+- Not now: `Not now`.+- Timeout: `<computer> didn’t answer in time. Check that Harness is running there, then try again.`+- Any other raw failure: `Couldn’t reach Harness on <computer>. Check that it’s running, then try again.`+- No local computer: main's waiting box from task #4220 (`Waiting for this computer’s Harness connection. This goes on+ by itself once it is up.`) stays as it is.+- Closing while the computer prepares (×, Esc or Not now) stops the wait at once: nothing exists before `buddy.create`+ is sent (review of #3530).+- Pending action: `Finish or retry the pending action in this Swarm first.`+- A refused start: the server's sentence as the controller keeps it (`operationError`).++- [ ] **Step 1: Write the failing tests**+ - Widget, light and dark: the form shows the heading with `Pilot`, the intro and `Not now`; a tap outside the form+ leaves it open; `Not now` closes it with no enrollment.+ - Widget: the backend refuses `buddy.create` with 409 "This computer is full." and the form shows that sentence.+ - Unit: prepare that never answers times out to the timeout sentence, not `TimeoutException`; a `StateError` from+ the command becomes the could-not-reach sentence.+- [ ] **Step 2: Run them and see them fail.**+- [ ] **Step 3: Implement; `showAppDialog(barrierDismissible: false)` for the form.**+- [ ] **Step 4: Run them, the form's own tests (`test/new_harness_form*_test.dart`) and see them pass.**+- [ ] **Step 5: Commit.**++### Task 3: Join dialog offers Retry only after a failure a retry can fix (finding 13)++**Files:**+- Modify: `desktop/lib/super_tabs/join_dialog.dart:257-332`+- Test: `desktop/test/swarm_sharing_test.dart`++**Interfaces:** none new.++- [ ] **Step 1: Write the failing tests**+ - `while the invitation loads the button reads Join Swarm, greyed`: a request that never answers; the confirm+ button reads `Join Swarm` and is disabled; no `Retry`.+ - The revoked-link test expects `Close` and no `Retry`; tapping Close closes the dialog.+ - `a network failure keeps Retry`: a request that throws a non-link failure shows `Retry`.+- [ ] **Step 2: Run them and see them fail.**+- [ ] **Step 3: Implement: keep whether the failure is an unavailable link; the button is Close for it, Retry for any+ other failure, and Join Swarm (disabled) while loading.**+- [ ] **Step 4: Run them and see them pass.**+- [ ] **Step 5: Commit.**++### Task 4: Screenshots++- [ ] Run the shot tests with `HARNESS_V3_JOIN_SHOTS=<dir>` for the form and the Join dialog, light and dark, and+ attach them to the pull request.diff --git a/docs/plans/assets/bring-agent-join/bring-agent-dark.png b/docs/plans/assets/bring-agent-join/bring-agent-dark.pngnew file mode 100644index 000000000..6c91b651aBinary files /dev/null and b/docs/plans/assets/bring-agent-join/bring-agent-dark.png differdiff --git a/docs/plans/assets/bring-agent-join/bring-agent-light.png b/docs/plans/assets/bring-agent-join/bring-agent-light.pngnew file mode 100644index 000000000..303dbcc51Binary files /dev/null and b/docs/plans/assets/bring-agent-join/bring-agent-light.png differdiff --git a/docs/plans/assets/bring-agent-join/bring-agent-preparing-dark.png b/docs/plans/assets/bring-agent-join/bring-agent-preparing-dark.pngnew file mode 100644index 000000000..13afbc5caBinary files /dev/null and b/docs/plans/assets/bring-agent-join/bring-agent-preparing-dark.png differdiff --git a/docs/plans/assets/bring-agent-join/bring-agent-preparing-light.png b/docs/plans/assets/bring-agent-join/bring-agent-preparing-light.pngnew file mode 100644index 000000000..09cb0f69aBinary files /dev/null and b/docs/plans/assets/bring-agent-join/bring-agent-preparing-light.png differdiff --git a/docs/plans/assets/bring-agent-join/bring-agent-refused-dark.png b/docs/plans/assets/bring-agent-join/bring-agent-refused-dark.pngnew file mode 100644index 000000000..2025cc7a0Binary files /dev/null and b/docs/plans/assets/bring-agent-join/bring-agent-refused-dark.png differdiff --git a/docs/plans/assets/bring-agent-join/bring-agent-refused-light.png b/docs/plans/assets/bring-agent-join/bring-agent-refused-light.pngnew file mode 100644index 000000000..fd4bcedd5Binary files /dev/null and b/docs/plans/assets/bring-agent-join/bring-agent-refused-light.png differdiff --git a/docs/plans/assets/bring-agent-join/join-dead-link-dark.png b/docs/plans/assets/bring-agent-join/join-dead-link-dark.pngnew file mode 100644index 000000000..4c70997d8Binary files /dev/null and b/docs/plans/assets/bring-agent-join/join-dead-link-dark.png differdiff --git a/docs/plans/assets/bring-agent-join/join-dead-link-light.png b/docs/plans/assets/bring-agent-join/join-dead-link-light.pngnew file mode 100644index 000000000..79dd96df0Binary files /dev/null and b/docs/plans/assets/bring-agent-join/join-dead-link-light.png differdiff --git a/docs/plans/assets/bring-agent-join/join-loading-dark.png b/docs/plans/assets/bring-agent-join/join-loading-dark.pngnew file mode 100644index 000000000..36b573361Binary files /dev/null and b/docs/plans/assets/bring-agent-join/join-loading-dark.png differdiff --git a/docs/plans/assets/bring-agent-join/join-loading-light.png b/docs/plans/assets/bring-agent-join/join-loading-light.pngnew file mode 100644index 000000000..35a03395aBinary files /dev/null and b/docs/plans/assets/bring-agent-join/join-loading-light.png differ