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
feat(swarm): remove a machine from a Swarm
bitcoinbuilderd9074501ae73
diff --git a/backend/src/superTabs/commands.test.ts b/backend/src/superTabs/commands.test.tsindex 1ba1187aa..b57196850 100644--- a/backend/src/superTabs/commands.test.ts+++ b/backend/src/superTabs/commands.test.ts@@ -1469,3 +1469,87 @@ describe('the owner\'s rules, after review', () => {}})})++describe('machine.remove', () => {+ const contribute = (f: ReturnType<typeof fixture>, contributorId = 'owner', machineId = 'host') => {+ const generation = f.state.people.find(p => p.id === contributorId)!.generation+ f.state.machines = [...(f.state.machines ?? []), { machineId, name: 'Studio', contributorId, membershipGeneration: generation, generation: 'g1',+ cwd: '/repo', engines: ['claude'], maxAgents: 2, paused: false } as never]+ }+ const start = (f: ReturnType<typeof fixture>, group: string, dispatched = false) => {+ f.state.starts = [...(f.state.starts ?? []), { id: `start-${(f.state.starts ?? []).length}`, creationId: 'creation', actorKey: 'agent:lead', contributorId: 'owner',+ membershipGeneration: f.state.people[0]!.generation, machineOwnerId: 'host-owner', hostGrant: null, ...(dispatched ? { dispatched: true } : {}),+ request: { conversationId: group, machineId: 'host', engine: 'claude', name: 'Builder', cwd: '/repo', worktree: true,+ requirements: { memoryBytes: 0, diskBytes: 0, maxCpuPercent: 100, tools: [], devices: [], quotaRequired: false } } } as never]+ }++ it('takes the machine out with the Swarm\'s agents on it, and tells each group whose task needs a new worker', () => {+ const f = fixture(), lead = f.add('lead', 'owner', 'lead', true), group = f.group(), worker = f.add('worker', 'owner', group)+ contribute(f)+ f.run({ type: 'work.assign', conversationId: group, agentId: worker })+ f.state.harnessReservations = [{ machineId: 'host', harnessId: 'old', generation: 'g0', renewed: false }, { machineId: 'elsewhere', harnessId: 'x', generation: 'g0', renewed: false }]+ const named = (id: string) => { const a = f.state.agents.find(x => x.id === id)!; return a.displayName ?? a.name }+ const workerName = named(worker), leadName = named(lead)+ const effects = f.run({ type: 'machine.remove', machineId: 'host' })++ expect(f.state.machines).toEqual([])+ expect(f.state.agents).toEqual([])+ expect(effects.result.removedAgents).toEqual([lead, worker])+ expect(f.state.harnessReservations).toEqual([expect.objectContaining({ machineId: 'elsewhere' })])+ expect(f.state.conversations.find(c => c.id === group)!.assignment!.status).toBe('reconciling')+ const notice = effects.messages.find(m => m.conversationId === group)!+ expect(notice).toMatchObject({ author: { kind: 'person', id: 'owner' }, source: { kind: 'system' } })+ // The group's Lead left with the machine too.+ expect(notice.text).toBe(`owner removed Studio from the Swarm, and ${leadName} and ${workerName} with it. Its task "Offline editing" needs to be assigned again or closed.`)+ expect(notice.recipients).toEqual([])+ expect(effects.messages.find(m => m.conversationId === 'lead')!.text).toBe(`owner removed Studio from the Swarm, and ${leadName} with it.`)+ expect(new Set(effects.messages.map(m => m.id)).size).toBe(effects.messages.length)+ })++ it('removes a machine that only runs agents, so nothing lists it any more', () => {+ const f = fixture(), worker = f.add('worker')+ f.run({ type: 'machine.remove', machineId: 'host' })+ expect(f.state.agents.some(a => a.id === worker)).toBe(false)+ expect(f.state.machines ?? []).toEqual([])+ })++ it('fails the starts still waiting for it, and waits for one already launching', () => {+ const f = fixture(), group = f.group()+ contribute(f)+ start(f, group)+ const effects = f.run({ type: 'machine.remove', machineId: 'host' })+ expect(f.state.starts![0]!.error).toBe('Its machine was removed from the Swarm.')+ expect(effects.messages).toEqual([expect.objectContaining({ conversationId: group, text: 'Builder will not start: its machine was removed from the Swarm.' })])++ const g = fixture(), other = g.group()+ contribute(g)+ start(g, other, true)+ expect(() => g.run({ type: 'machine.remove', machineId: 'host' })).toThrow(expect.objectContaining({ code: 'STARTS_PENDING' }))+ expect(g.state.machines).toHaveLength(1)+ })++ it('lets the machine\'s owner take back what is all theirs, and leaves anyone else\'s to the Swarm owner', () => {+ const f = fixture()+ f.invite()+ contribute(f, 'peer')+ f.add('theirs', 'peer')+ f.run({ type: 'machine.remove', machineId: 'host' }, peer)+ expect(f.state.machines).toEqual([])++ const g = fixture()+ g.invite()+ contribute(g, 'peer')+ g.add('owners', 'owner')+ expect(() => g.run({ type: 'machine.remove', machineId: 'host' }, peer)).toThrow(expect.objectContaining({ code: 'FORBIDDEN', status: 403 }))+ g.run({ type: 'machine.remove', machineId: 'host' })+ expect(g.state.machines).toEqual([])+ })++ it('is a person\'s to do, and only for a machine in the Swarm', () => {+ const f = fixture(), lead = f.add('lead', 'owner', 'lead', true)+ expect(() => f.run({ type: 'machine.remove', machineId: 'host' }, { kind: 'agent', agentId: lead, machineOwnerId: 'host-owner' }))+ .toThrow(expect.objectContaining({ code: 'HUMAN_REQUIRED', status: 403 }))+ expect(() => f.run({ type: 'machine.remove', machineId: 'nowhere' })).toThrow(expect.objectContaining({ code: 'NOT_FOUND', status: 404 }))+ expect(commandSchema.safeParse({ type: 'machine.remove', machineId: 'host', extra: true }).success).toBe(false)+ })+})diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.tsindex b9cf3fde4..f9614cdd1 100644--- a/backend/src/superTabs/commands.ts+++ b/backend/src/superTabs/commands.ts@@ -55,6 +55,7 @@ export const commandSchema = z.discriminatedUnion('type', [z.object({ type: z.literal('machine.contribute'), machineId: id, name: title, cwd: path, scope: z.literal('swarm').optional(), engines: z.array(z.string().regex(/^[a-z][a-z0-9_-]{0,79}$/)).min(1).max(32), maxAgents: z.number().int().min(1).max(16),ifMissing: z.literal(true).optional() }).strict(),z.object({ type: z.literal('machine.pause'), machineId: id, paused: z.boolean() }).strict(),+ z.object({ type: z.literal('machine.remove'), machineId: id }).strict(),z.object({ type: z.literal('tab.rename'), name: title }).strict(),z.object({ type: z.literal('tab.project'), machineId: id, project }).strict(),z.object({ type: z.literal('tab.pause'), paused: z.boolean() }).strict(),@@ -429,6 +430,47 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commapool.paused = command.pausedbreak}+ case 'machine.remove': {+ // A machine leaves the Swarm with the Swarm's agents on it, the way Remove from Swarm withdraws one agent: their+ // processes keep running there, nothing is stopped. Withdrawing the contribution alone would leave it listed+ // wherever an agent still runs (desktop/lib/super_tabs/machines.dart lists both), and the host of an owner's+ // Lead adds such a machine back by itself (joinSwarm in store.ts).+ if (actor.kind !== 'person') fail('HUMAN_REQUIRED', 'A person removes a machine from the Swarm.', 403)+ const pool = state.machines?.find(m => m.machineId === command.machineId)+ const members = state.agents.filter(a => a.machineId === command.machineId)+ if (!pool && !members.length) fail('NOT_FOUND', 'This machine is not in the Swarm.', 404)+ // Its owner may take back what is all theirs; another person's agent on it is the Swarm owner's to remove.+ const theirs = (!pool || pool.contributorId === actor.userId) && members.every(a => a.contributorId === actor.userId)+ if (actor.userId !== state.ownerId && !theirs) fail('FORBIDDEN', 'Only the Swarm owner or the machine\'s owner can remove it.', 403)+ const pending = state.starts?.filter(s => s.request.machineId === command.machineId && !s.harnessId && !s.error) ?? []+ // A launch already under way would arrive with nowhere to go; it finishes in moments.+ if (pending.some(s => s.dispatched)) fail('STARTS_PENDING', 'An agent is starting on this machine. Try again in a moment.')+ for (const start of pending) {+ start.error = 'Its machine was removed from the Swarm.'+ effects.messages.push({ id: stableId(operationId, 'start', start.id), conversationId: start.request.conversationId, author: sender,+ text: `${start.request.name} will not start: its machine was removed from the Swarm.`, replyTo: null, recipients: [], source: SYSTEM_ROW })+ }+ const removed = new Set(members.map(a => a.id))+ const affected = state.conversations.filter(group => group.agentIds.some(a => removed.has(a))+ || (group.leadId && removed.has(group.leadId)) || (group.assignment && removed.has(group.assignment.agentId)))+ .map(group => ({ group, names: members.filter(a => group.agentIds.includes(a.id) || group.leadId === a.id || group.assignment?.agentId === a.id)+ .map(a => a.displayName ?? a.name), task: !!group.assignment && removed.has(group.assignment.agentId) && activeWork(group) }))+ for (const target of members) removeAgent(target)+ state.machines = state.machines?.filter(m => m.machineId !== command.machineId)+ // Its capacity left with it: no slot there is held for anyone now.+ state.harnessReservations = state.harnessReservations?.filter(r => r.machineId !== command.machineId)+ state.releasedHarnesses = state.releasedHarnesses?.filter(r => r.machineId !== command.machineId)+ const machine = pool?.name ?? 'a machine'+ for (const { group, names, task } of affected) {+ const lead = group.leadId && group.agentIds.includes(group.leadId) ? group.leadId : null+ const join = names.length > 1 ? `${names.slice(0, -1).join(', ')} and ${names.at(-1)}` : names[0]+ effects.messages.push({ id: stableId(operationId, 'machine-removed', group.id), conversationId: group.id, author: sender,+ text: `${who} removed ${machine} from the Swarm, and ${join} with it.${task ? ` Its task "${group.title}" needs to be assigned again or closed.` : ''}`,+ replyTo: null, recipients: lead ? [lead] : [], source: SYSTEM_ROW })+ }+ result.removedAgents = [...removed]+ break+ }case 'tab.rename':// Writable people manage the swarm even when its original project is// gone. Agents retain the existing Lead-conversation authority.diff --git a/desktop/lib/super_tabs/machines.dart b/desktop/lib/super_tabs/machines.dartindex 0bdd2c0d7..6c7a78d09 100644--- a/desktop/lib/super_tabs/machines.dart+++ b/desktop/lib/super_tabs/machines.dart@@ -1072,6 +1072,154 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {);}+ /// Every agent of the Swarm on [machineId]: removing the machine takes them all with it.+ List<SuperTabAgent> _agentsOn(String machineId) => [+ for (final a in c.snapshot?.agents ?? const <SuperTabAgent>[])+ if (a.machineId == machineId) a,+ ];++ /// The Swarm owner removes any machine; anyone else, one that is all theirs: their contribution and+ /// only their agents (backend `machine.remove`).+ bool _canRemove(String machineId) {+ if (!c.canWrite) return false;+ if (c.isOwner) return true;+ final pool = c.snapshot?.machines+ .where((m) => m['machineId'] == machineId)+ .firstOrNull;+ final contributor = pool?['contributorId'] as String?;+ return (contributor == null || contributor == c.accountId) &&+ _agentsOn(machineId).every((a) => a.contributorId == c.accountId);+ }++ /// Takes a machine out of this Swarm, and the Swarm's agents on it with it, after a yes. Their sessions keep+ /// running on the machine, as Remove from Swarm leaves one agent's (roster.dart).+ Future<void> _remove(_MachineView v) async {+ final id = v.id, name = superTabMachineName(v.name);+ var busy = false, attempted = false;+ await showAppDialog<void>(+ context: context,+ builder: (context) => SuperTabDialogScope(+ controller: c,+ child: StatefulBuilder(+ builder: (context, update) => ListenableBuilder(+ listenable: c,+ builder: (context, _) {+ final pending = c.pendingCommand;+ final checking =+ pending?['type'] == 'machine.remove' &&+ pending?['machineId'] == id;+ final available = _ids.contains(id) || checking || busy;+ final permitted = _canRemove(id) || checking;+ final enabled =+ permitted &&+ !busy &&+ !c.saving &&+ (checking || !c.hasPendingAction);+ final names = [+ for (final a in _agentsOn(id)) c.snapshot!.agentName(a.id),+ ];+ final shown = names.length > 4+ ? '${names.take(3).join(', ')} and ${names.length - 3} more'+ : names.length > 1+ ? '${names.take(names.length - 1).join(', ')} and ${names.last}'+ : names.firstOrNull;+ return PopScope(+ canPop: !busy,+ child: AlertDialog(+ title: Text(+ available+ ? 'Remove $name from this Swarm?'+ : 'Machine unavailable',+ ),+ content: SizedBox(+ width: 400,+ child: SingleChildScrollView(+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(+ !available || !permitted+ ? 'This action is no longer available.'+ : shown == null+ ? 'The Swarm stops using it for new work.'+ : '$shown ${names.length == 1 ? 'leaves' : 'leave'} the Swarm with it and keep running on $name. '+ 'Any open task needs to be assigned again or closed.',+ ),+ if (attempted && c.operationError != null) ...[+ const SizedBox(height: 12),+ Text(c.operationError!),+ ],+ ],+ ),+ ),+ ),+ actions: [+ TextButton(+ autofocus: true,+ onPressed: busy ? null : () => Navigator.pop(context),+ child: Text(+ checking || !available || !permitted+ ? 'Close'+ : 'Cancel',+ ),+ ),+ if (available && permitted)+ FilledButton(+ key: const ValueKey('super-machine-remove-confirm'),+ style: grid.dangerButtonStyle(),+ onPressed: !enabled+ ? null+ : () async {+ update(() {+ busy = true;+ attempted = true;+ });+ final result = checking+ ? await c.retry()+ : await c.command({+ 'type': 'machine.remove',+ 'machineId': id,+ });+ if (!context.mounted) return;+ if (result != null) {+ Navigator.pop(context);+ } else {+ update(() => busy = false);+ }+ },+ child: Text(checking ? 'Retry' : 'Remove from Swarm'),+ ),+ ],+ ),+ );+ },+ ),+ ),+ ),+ );+ }++ /// A machine row's right-click: its details, and Remove from Swarm for whoever may.+ Future<void> _menu(_MachineView view, Offset at) async {+ final choice = await showMenu<String>(+ context: context,+ position: RelativeRect.fromLTRB(at.dx, at.dy, at.dx, at.dy),+ items: [+ const PopupMenuItem(value: 'details', child: Text('Details')),+ if (_canRemove(view.id))+ const PopupMenuItem(+ key: ValueKey('super-machine-menu-remove'),+ value: 'remove',+ child: Text('Remove from Swarm'),+ ),+ ],+ );+ if (!mounted) return;+ if (choice == 'details') await _openDetails(view);+ if (choice == 'remove' && _canRemove(view.id)) await _remove(view);+ }+Future<void> _details(_MachineView v) {final id = v.id, name = v.name, person = v.owner, shared = v.shared;final contributor = v.contributor, paused = v.paused, dim = v.dim;@@ -1083,7 +1231,26 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {controller: c,requireWrite: false,child: AlertDialog(- title: Text(superTabMachineName(name)),+ title: Row(+ children: [+ Expanded(child: Text(superTabMachineName(name))),+ // Out of the way of the everyday actions below: a quiet mark that turns red when pointed at.+ if (_canRemove(id))+ AppIconButton(+ key: const ValueKey('super-machine-remove'),+ icon: AppIcons.trash2,+ tooltip: 'Remove from Swarm',+ color: DesktopChrome.muted,+ destructive: true,+ onPressed: () {+ Navigator.pop(context);+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (mounted) unawaited(_remove(v));+ });+ },+ ),+ ],+ ),content: SuperTabMachineDetails(name: name,owner: person?.email,@@ -1158,6 +1325,8 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {child: InkWell(key: ValueKey('super-machine-${view.id}'),onTap: () => unawaited(_openDetails(view)),+ onSecondaryTapUp: (event) =>+ unawaited(_menu(view, event.globalPosition)),hoverColor: grid.AppSurface.hoverFill,focusColor: grid.AppSurface.hoverFill,borderRadius: BorderRadius.circular(DesktopChrome.rowRadius),diff --git a/desktop/test/super_tab_machines_test.dart b/desktop/test/super_tab_machines_test.dartindex c940793eb..0369c0ea8 100644--- a/desktop/test/super_tab_machines_test.dart+++ b/desktop/test/super_tab_machines_test.dart@@ -1,6 +1,7 @@import 'dart:io';import 'dart:ui' show PointerDeviceKind;+import 'package:flutter/gestures.dart' show kSecondaryMouseButton;import 'package:flutter/material.dart';import 'package:flutter/rendering.dart';import 'package:flutter/services.dart';@@ -279,9 +280,13 @@ void main() {await tester.pumpAndSettle();expect(find.byType(AlertDialog), findsOneWidget);expect(- (tester.widget<AlertDialog>(find.byType(AlertDialog)).title! as Text)- .data,- 'M2',+ find.descendant(+ of: find.byWidget(+ tester.widget<AlertDialog>(find.byType(AlertDialog)).title!,+ ),+ matching: find.text('M2'),+ ),+ findsOneWidget,);expect(find.text('Available capacity'), findsNothing);expect(find.text('Model allowances'), findsNothing);@@ -870,6 +875,154 @@ void main() {},);+ group('Remove from Swarm', () {+ Map<String, dynamic> machine(String contributorId) => {+ 'machineId': 'studio',+ 'name': 'Studio',+ 'contributorId': contributorId,+ 'observation': {'receivedAt': DateTime.now().millisecondsSinceEpoch},+ };+ Map<String, dynamic> agent(String id, String contributorId) => {+ 'id': id,+ 'name': id,+ 'displayName': id == 'a1' ? 'Mira' : 'River',+ 'machineId': 'studio',+ 'harnessId': 'h-$id',+ 'contributorId': contributorId,+ 'machineOwnerId': contributorId,+ 'configuration': <String, dynamic>{'engine': 'claude'},+ };+ Future<void> mount(WidgetTester tester, dynamic c) async {+ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(+ body: SuperTabMachines(controller: c, onAddAgent: (_) {}),+ ),+ ),+ );+ await tester.pumpAndSettle();+ }++ testWidgets(+ 'the owner removes a machine and its agents after a yes, from its details',+ (tester) async {+ final server = ConversationServer();+ server.state['machines'] = [machine('owner')];+ server.state['agents'] = [agent('a1', 'owner'), agent('a2', 'owner')];+ final c = server.controller();+ await c.refresh();+ await mount(tester, c);+ await tester.tap(find.byKey(const ValueKey('super-machine-studio')));+ await tester.pumpAndSettle();+ await tester.tap(find.byKey(const ValueKey('super-machine-remove')));+ await tester.pumpAndSettle();+ expect(find.text('Remove Studio from this Swarm?'), findsOneWidget);+ expect(+ find.textContaining(+ 'Mira and River leave the Swarm with it and keep running on Studio.',+ ),+ findsOneWidget,+ );+ // Cancel sends nothing.+ await tester.tap(find.widgetWithText(TextButton, 'Cancel'));+ await tester.pumpAndSettle();+ expect(+ server.posts.where(+ (p) => (p['command'] as Map?)?['type'] == 'machine.remove',+ ),+ isEmpty,+ );++ await tester.tap(find.byKey(const ValueKey('super-machine-studio')));+ await tester.pumpAndSettle();+ await tester.tap(find.byKey(const ValueKey('super-machine-remove')));+ await tester.pumpAndSettle();+ await tester.tap(+ find.byKey(const ValueKey('super-machine-remove-confirm')),+ );+ await tester.pumpAndSettle();+ expect(+ server.posts+ .map((p) => p['command'])+ .where((cmd) => (cmd as Map)['type'] == 'machine.remove')+ .single,+ {'type': 'machine.remove', 'machineId': 'studio'},+ );+ expect(find.text('Remove Studio from this Swarm?'), findsNothing);+ await tester.pumpWidget(const SizedBox());+ await c.flush();+ c.dispose();+ },+ );++ testWidgets('a right-click offers it to whoever may remove the machine', (+ tester,+ ) async {+ final server = ConversationServer();+ server.state['machines'] = [machine('owner')];+ final c = server.controller();+ await c.refresh();+ await mount(tester, c);+ await tester.tap(+ find.byKey(const ValueKey('super-machine-studio')),+ buttons: kSecondaryMouseButton,+ );+ await tester.pumpAndSettle();+ expect(find.text('Details'), findsOneWidget);+ await tester.tap(find.byKey(const ValueKey('super-machine-menu-remove')));+ await tester.pumpAndSettle();+ expect(find.text('Remove Studio from this Swarm?'), findsOneWidget);+ expect(+ find.text('The Swarm stops using it for new work.'),+ findsOneWidget,+ );+ await tester.tap(find.widgetWithText(TextButton, 'Cancel'));+ await tester.pumpAndSettle();+ await tester.pumpWidget(const SizedBox());+ await c.flush();+ c.dispose();+ });++ testWidgets('a collaborator removes only a machine that is all theirs', (+ tester,+ ) async {+ final server = ConversationServer();+ (server.state['people'] as List).add({+ 'id': 'peer',+ 'email': '[email protected]',+ 'role': 'collaborator',+ });+ // Their machine, running the owner's agent: the Swarm owner's to remove.+ server.state['machines'] = [machine('peer')];+ server.state['agents'] = [agent('a1', 'owner')];+ final c = server.controller(account: 'peer');+ await c.refresh();+ await mount(tester, c);+ await tester.tap(find.byKey(const ValueKey('super-machine-studio')));+ await tester.pumpAndSettle();+ expect(find.byKey(const ValueKey('super-machine-remove')), findsNothing);+ await tester.tap(find.widgetWithText(TextButton, 'Close'));+ await tester.pumpAndSettle();++ // All theirs: theirs to remove.+ server.state['agents'] = [agent('a1', 'peer')];+ server.revision++;+ await c.refresh();+ await tester.pumpAndSettle();+ await tester.tap(find.byKey(const ValueKey('super-machine-studio')));+ await tester.pumpAndSettle();+ expect(+ find.byKey(const ValueKey('super-machine-remove')),+ findsOneWidget,+ );+ await tester.tap(find.widgetWithText(TextButton, 'Close'));+ await tester.pumpAndSettle();+ await tester.pumpWidget(const SizedBox());+ await c.flush();+ c.dispose();+ });+ });+for (final brightness in [Brightness.dark, Brightness.light]) {for (final textScale in [1.0, 2.0]) {for (final width in [280.0, 380.0]) {