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.

feat(swarm): the owner sets a machine's agent slots in Add and Configure machine (#1536)

0xken155a71ee3e6c1c
diff --git a/desktop/lib/super_tabs/machines.dart b/desktop/lib/super_tabs/machines.dart
index 1ae021b15..833236441 100644
--- a/desktop/lib/super_tabs/machines.dart
+++ b/desktop/lib/super_tabs/machines.dart
@@ -28,6 +28,29 @@ import 'section_heading.dart';
export 'machine_status.dart';
+/// The owner's agent slots run 1–8 here, though the backend itself accepts up
+/// to 16: widening the UI to the backend's ceiling would only invite a number
+/// the machine cannot run.
+const _agentSlotsMin = 1;
+const _agentSlotsMax = 8;
+
+/// What one more agent needs to start, the CLI's own figure
+/// (`START_REQUIREMENTS.memoryBytes`, `cli/src/superTabs/capacity.ts`).
+const _agentMemoryBytes = 2 * 1024 * 1024 * 1024;
+
+int _clampAgentSlots(num value) =>
+ value.toInt().clamp(_agentSlotsMin, _agentSlotsMax);
+
+/// What this machine's free memory suggests, by the CLI's own arithmetic: one
+/// agent per [_agentMemoryBytes] free. Null when the reading does not say how
+/// much memory there is.
+int? _suggestedAgentSlots(MachineResources? resources) {
+ final total = resources?.memoryTotalBytes;
+ final used = resources?.memoryUsedBytes;
+ if (total == null || used == null) return null;
+ return _clampAgentSlots(((total - used) / _agentMemoryBytes).floor());
+}
+
class SuperTabMachines extends StatefulWidget {
const SuperTabMachines({
super.key,
@@ -77,6 +100,99 @@ class _MachineChoice {
final ({IconData icon, String message})? unavailable;
}
+/// "Agent slots" — how many agents this machine offers the Swarm — with the one
+/// thing the number is not: a promise. Its free memory is what it was suggested
+/// from, and what is free moves.
+///
+/// A stepper rather than a number field, so no keystroke can leave the dialog
+/// holding a count the backend would refuse; both buttons go dead at the bounds
+/// rather than staying lit and doing nothing.
+class _AgentSlots extends StatelessWidget {
+ const _AgentSlots({
+ required this.value,
+ required this.busy,
+ required this.onChanged,
+ this.cappedFrom,
+ });
+
+ final int value;
+ final bool busy;
+ final ValueChanged<int> onChanged;
+
+ /// The number this machine was contributed with, when it is above what this
+ /// form offers: saving would lower it, and the owner is told so.
+ final int? cappedFrom;
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ final value = this.value;
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Row(
+ children: [
+ Expanded(child: Text('Agent slots', style: DesktopChrome.text())),
+ Container(
+ width: 96,
+ constraints: const BoxConstraints(
+ minHeight: grid.AppControl.height,
+ ),
+ padding: const EdgeInsets.symmetric(horizontal: 4),
+ decoration: BoxDecoration(
+ // The same recessed well the picker's control sits in.
+ color: grid.AppSurface.recess,
+ borderRadius: BorderRadius.circular(grid.AppControl.radius),
+ ),
+ child: Row(
+ mainAxisAlignment: MainAxisAlignment.spaceBetween,
+ children: [
+ AppIconButton(
+ key: const ValueKey('agent-slots-fewer'),
+ icon: AppIcons.minus,
+ size: 16,
+ tooltip: 'Fewer slots',
+ onPressed: busy || value <= _agentSlotsMin
+ ? null
+ : () => onChanged(value - 1),
+ ),
+ Text(
+ value.toString(),
+ key: const ValueKey('agent-slots-value'),
+ style: DesktopChrome.control(),
+ ),
+ AppIconButton(
+ key: const ValueKey('agent-slots-more'),
+ icon: AppIcons.plus,
+ size: 16,
+ tooltip: 'More slots',
+ onPressed: busy || value >= _agentSlotsMax
+ ? null
+ : () => onChanged(value + 1),
+ ),
+ ],
+ ),
+ ),
+ ],
+ ),
+ const SizedBox(height: 4),
+ Text(
+ 'Each new agent still needs free memory when it starts.',
+ style: DesktopChrome.metadata(),
+ ),
+ if (cappedFrom case final from?) ...[
+ const SizedBox(height: 4),
+ Text(
+ 'This machine was set to $from agent slots. This form offers up to '
+ '$_agentSlotsMax, and saving here lowers it.',
+ style: DesktopChrome.metadata(),
+ ),
+ ],
+ ],
+ );
+ }
+}
+
/// Unlike an ordinary choice field, this inventory also explains computers
/// that cannot be selected. Standard menu buttons own their disabled semantics
/// and keyboard traversal; the shared menu theme supplies their appearance.
@@ -404,6 +520,81 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {
String? error;
var busy = false;
String? setupId;
+ // The agent slots the owner is choosing. A machine already in this Swarm
+ // starts at the number it has; a new one starts at what its free memory
+ // suggests, worked out here rather than by preparation (below).
+ int? storedSlots(String? id) {
+ final row = id == null
+ ? null
+ : c.snapshot?.machines.where((m) => m['machineId'] == id).firstOrNull;
+ final current = row?['maxAgents'];
+ return current is num ? current.toInt() : null;
+ }
+
+ /// A machine contributed before this form had a range keeps its number
+ /// until the owner saves, and is told when saving would lower it.
+ int? storedOverRange(String? id) {
+ final stored = storedSlots(id);
+ return stored != null && stored > _agentSlotsMax ? stored : null;
+ }
+
+ // Readings this dialog has taken itself, keyed by machine. The panel's own
+ // samples stand in for a machine it already reads.
+ final suggestions = <String, int>{};
+
+ /// What this machine's own memory says, once a reading has answered. Null
+ /// while one is still coming, or when it failed.
+ int? memorySuggestion(String? id) => id == null
+ ? null
+ : suggestions[id] ?? _suggestedAgentSlots(_samples[id]?.$1);
+
+ int slotsFor(String? id) {
+ final stored = storedSlots(id);
+ if (stored != null) return _clampAgentSlots(stored);
+ return memorySuggestion(id) ?? _agentSlotsMin;
+ }
+
+ var slots = slotsFor(machineId);
+ var slotsEdited = false;
+ // The open dialog and its own setState, once it is built: a reading
+ // answers while the form is open, and the field has to repaint when it
+ // does. Both are read only while the dialog is still there — one that
+ // arrives after it closed has nothing to repaint.
+ BuildContext? dialog;
+ void Function(void Function())? repaint;
+ final reading = <String>{};
+
+ /// Start the field where this machine's own memory says, without asking
+ /// preparation: preparation sets the project up, probes engines and takes
+ /// one of its 32 setup slots, and opening a form the owner may cancel is
+ /// no reason to do that. A machine with a number of its own needs no
+ /// reading at all.
+ Future<void> suggestSlots() async {
+ final id = machineId;
+ if (id == null ||
+ storedSlots(id) != null ||
+ !canSelect(app.stateOf(id)) ||
+ !reading.add(id)) {
+ return;
+ }
+ MachineResources? resources;
+ try {
+ resources = await (widget.readLocal ?? app.readMachineResources)(id);
+ } catch (_) {
+ return;
+ }
+ final suggested = _suggestedAgentSlots(resources);
+ // The picker may have moved on to another machine, whose own reading is
+ // the one that belongs in the field now — or the dialog may have closed.
+ if (suggested == null || machineId != id || dialog?.mounted != true) {
+ return;
+ }
+ suggestions[id] = suggested;
+ // Never over a number the owner has set meanwhile.
+ if (slotsEdited) return;
+ repaint?.call(() => slots = suggested);
+ }
+
await showAppDialog<void>(
context: context,
builder: (context) => SuperTabDialogScope(
@@ -412,6 +603,12 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {
listenable: app,
builder: (context, _) => StatefulBuilder(
builder: (context, update) {
+ dialog = context;
+ repaint = update;
+ // Not awaited: the form is usable immediately, and the number
+ // only has to be there by the time the owner reads it. Each
+ // machine is read once, so a rebuild does not read again.
+ unawaited(suggestSlots());
Future<void> save() async {
if (busy ||
!c.canWrite ||
@@ -458,19 +655,45 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {
}
if (!context.mounted || !c.canWrite) return;
final machine = app.stateOf(selected);
- final result =
- c.pendingCommand?['type'] == 'machine.contribute'
- ? await c.retry()
- : await c.command({
- 'type': 'machine.contribute',
- 'machineId': selected,
- 'name': machine!.machine.displayName,
- 'cwd': prepared['cwd'],
- if (prepared['scope'] != null)
- 'scope': prepared['scope'],
- 'engines': prepared['engines'],
- 'maxAgents': prepared['maxAgents'],
- });
+ // A machine with no number of its own whose reading failed,
+ // or had not answered yet, is showing the floor rather than
+ // a suggestion. The owner never chose that, so send what
+ // preparation offered instead — the number the field would
+ // have shown had the reading arrived.
+ final offered = prepared['maxAgents'];
+ if (!slotsEdited &&
+ storedSlots(selected) == null &&
+ memorySuggestion(selected) == null &&
+ offered is num) {
+ slots = _clampAgentSlots(offered);
+ }
+ // An earlier lost reply leaves an uncertain attempt holding
+ // its own receipt, and only one action may be in flight:
+ // check that one first, then send the number the owner is
+ // looking at — the stored attempt cannot know it was changed.
+ if (c.pendingCommand?['type'] == 'machine.contribute') {
+ // If that attempt cannot be confirmed, its own error is
+ // the one worth showing: it says why it is still unclear.
+ if (await c.retry() == null) {
+ if (!context.mounted) return;
+ throw SuperTabFailure(
+ c.operationErrorCode ?? 'CONTRIBUTION_FAILED',
+ c.operationError ??
+ 'The earlier attempt is still not confirmed. '
+ 'Try again to check it.',
+ );
+ }
+ if (!context.mounted || !c.canWrite) return;
+ }
+ final result = await c.command({
+ 'type': 'machine.contribute',
+ 'machineId': selected,
+ 'name': machine!.machine.displayName,
+ 'cwd': prepared['cwd'],
+ if (prepared['scope'] != null) 'scope': prepared['scope'],
+ 'engines': prepared['engines'],
+ 'maxAgents': slots,
+ });
if (result == null) {
throw SuperTabFailure(
'CONTRIBUTION_FAILED',
@@ -500,76 +723,95 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {
title: Text(isConfigure ? 'Configure machine' : 'Add machine'),
content: SizedBox(
width: 360,
- child: Column(
- mainAxisSize: MainAxisSize.min,
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- if (own.isNotEmpty)
- _MachinePicker(
- value: machineId,
- busy: busy,
- choices: [
- for (final m in own)
- _MachineChoice(
- id: m.machine.machineId,
- label: labelFor(m),
- unavailable: unavailable(m),
- ),
- ],
- onChanged: (id) {
- if (busy || !canSelect(app.stateOf(id))) return;
- update(() {
- machineId = id;
- setupId = null;
- error = null;
- });
- },
- )
- else
- Text(
- 'No computer is connected to this account yet.',
- style: DesktopChrome.text(),
- ),
- const SizedBox(height: 16),
- if (own.isNotEmpty) ...[
- Text(
- 'Let the product manager run agents here using this machine’s signed-in accounts.',
- style: DesktopChrome.text(),
- ),
- const SizedBox(height: 4),
- Text(
- 'Agents the Swarm starts on this machine run without asking for permission.',
- style: DesktopChrome.text(),
- ),
- const SizedBox(height: 12),
- Text(
- 'Harness clones each project into ~/harnesses/swarms and lets '
- "the Swarm's agents work in it.",
- style: DesktopChrome.text(),
- ),
- ] else ...[
- Text(
- 'To add another computer, install Harness on it and sign in with '
- 'this account, or approve a device with no screen from Machines.',
- style: DesktopChrome.text(),
- ),
- const SizedBox(height: 4),
- Align(
- alignment: Alignment.centerLeft,
- child: TextButton(
- onPressed: () {
- Navigator.pop(context);
- app.requestMachines();
+ child: SingleChildScrollView(
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ if (own.isNotEmpty)
+ _MachinePicker(
+ value: machineId,
+ busy: busy,
+ choices: [
+ for (final m in own)
+ _MachineChoice(
+ id: m.machine.machineId,
+ label: labelFor(m),
+ unavailable: unavailable(m),
+ ),
+ ],
+ onChanged: (id) {
+ if (busy || !canSelect(app.stateOf(id))) return;
+ update(() {
+ machineId = id;
+ setupId = null;
+ error = null;
+ // Another machine has its own number: the one it
+ // already offers, or its own suggestion.
+ slots = slotsFor(id);
+ slotsEdited = false;
+ });
+ unawaited(suggestSlots());
},
- child: const Text('Open Machines'),
+ )
+ else
+ Text(
+ 'No computer is connected to this account yet.',
+ style: DesktopChrome.text(),
),
- ),
- ],
- if (error != null) ...[
- const SizedBox(height: 12),
- Text(error!, style: DesktopChrome.metadata()),
+ const SizedBox(height: 16),
+ if (own.isNotEmpty) ...[
+ Text(
+ 'Let the product manager run agents here using this machine’s signed-in accounts.',
+ style: DesktopChrome.text(),
+ ),
+ const SizedBox(height: 4),
+ Text(
+ 'Agents the Swarm starts on this machine run without asking for permission.',
+ style: DesktopChrome.text(),
+ ),
+ const SizedBox(height: 12),
+ Text(
+ 'Harness clones each project into ~/harnesses/swarms and lets '
+ "the Swarm's agents work in it.",
+ style: DesktopChrome.text(),
+ ),
+ ] else ...[
+ Text(
+ 'To add another computer, install Harness on it and sign in with '
+ 'this account, or approve a device with no screen from Machines.',
+ style: DesktopChrome.text(),
+ ),
+ const SizedBox(height: 4),
+ Align(
+ alignment: Alignment.centerLeft,
+ child: TextButton(
+ onPressed: () {
+ Navigator.pop(context);
+ app.requestMachines();
+ },
+ child: const Text('Open Machines'),
+ ),
+ ),
+ ],
+ if (own.isNotEmpty) ...[
+ const SizedBox(height: 16),
+ _AgentSlots(
+ value: slots,
+ busy: busy,
+ cappedFrom: storedOverRange(machineId),
+ onChanged: (next) => update(() {
+ slots = next;
+ slotsEdited = true;
+ }),
+ ),
+ ],
+ if (error != null) ...[
+ const SizedBox(height: 12),
+ Text(error!, style: DesktopChrome.metadata()),
+ ],
],
- ],
+ ),
),
),
actions: [
diff --git a/desktop/test/super_tab_launch_test.dart b/desktop/test/super_tab_launch_test.dart
index 48db4080b..09ada0b27 100644
--- a/desktop/test/super_tab_launch_test.dart
+++ b/desktop/test/super_tab_launch_test.dart
@@ -42,6 +42,12 @@ class SuperTabFixtureConnection extends WsConn {
final calls = <(String, Map<String, dynamic>)>[];
final extraEngines = <String>[];
final joins = <Map<String, dynamic>>[];
+
+ /// Preparation operations this fixture has already answered: the daemon
+ /// answers a new one with `preparing` and is ready only when it is read
+ /// again (`cli/src/superTabs/contribution.ts`), so a client that gives up
+ /// after one answer never sees anything ready.
+ final prepared = <Object?>{};
bool loseCreate = false, loseJoin = false;
bool failNative = false;
WsRequestFailure? backendFailure;
@@ -143,6 +149,9 @@ class SuperTabFixtureConnection extends WsConn {
}
if (payload['action'] == 'wake') return {'ok': true};
if (payload['action'] == 'prepareContribution') {
+ if (prepared.add(payload['operationId'])) {
+ return {'ok': true, 'state': 'preparing'};
+ }
return {
'ok': true,
'state': 'ready',
diff --git a/desktop/test/super_tab_machines_test.dart b/desktop/test/super_tab_machines_test.dart
index f3fa84124..cde8752dc 100644
--- a/desktop/test/super_tab_machines_test.dart
+++ b/desktop/test/super_tab_machines_test.dart
@@ -6,6 +6,7 @@ import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/machine_resources.dart';
import 'package:harness/core/models.dart';
import 'package:harness/shared/theme/app_icons.dart';
import 'package:harness/shared/theme/status_line_style.dart';
@@ -16,6 +17,7 @@ import 'package:harness/super_tabs/identity.dart';
import 'package:harness/super_tabs/model.dart';
import 'package:harness/super_tabs/section_heading.dart';
import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/shared/widgets/app_icon_button.dart';
import 'package:harness/widgets/desktop_chrome.dart';
import 'package:harness/widgets/engine_identity.dart';
@@ -23,12 +25,21 @@ import 'super_tab_launch_test.dart' show SuperTabLaunchFixture, tabId;
import 'support/capture.dart';
import 'support/super_tab_fixture.dart';
+/// What a machine with this much free memory is expected to offer: the same
+/// one-agent-per-2-GiB arithmetic the CLI works the suggestion out with.
+MachineResources _reading({required double freeGiB, double totalGiB = 32}) =>
+ MachineResources(
+ memoryTotalBytes: totalGiB * 1024 * 1024 * 1024,
+ memoryUsedBytes: (totalGiB - freeGiB) * 1024 * 1024 * 1024,
+ );
+
Future<void> _openAddMachineDialog(
WidgetTester tester,
SuperTabLaunchFixture f,
dynamic c, {
Brightness brightness = Brightness.dark,
double textScale = 1,
+ Future<MachineResources?> Function(String)? readLocal,
}) async {
final previousBrightness = grid.AppTheme.brightness.value;
grid.AppTheme.brightness.value = brightness;
@@ -49,6 +60,7 @@ Future<void> _openAddMachineDialog(
controller: c,
app: f.app,
onAddAgent: (_) {},
+ readLocal: readLocal,
),
),
),
@@ -59,6 +71,43 @@ Future<void> _openAddMachineDialog(
await tester.pumpAndSettle();
}
+/// The machine card's own way into the same form: open the card, then Configure.
+Future<void> _openConfigureDialog(
+ WidgetTester tester,
+ SuperTabLaunchFixture f,
+ dynamic c, {
+ Future<MachineResources?> Function(String)? readLocal,
+}) async {
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: SizedBox(
+ width: 300,
+ height: 400,
+ child: SuperTabMachines(
+ controller: c,
+ app: f.app,
+ onAddAgent: (_) {},
+ readLocal: readLocal,
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ // A machine that has not reported reads as offline and waits under "Offline · 1",
+ // which is closed until the owner opens it.
+ final card = find.byKey(const ValueKey('super-machine-m'));
+ if (card.evaluate().isEmpty) {
+ await tester.tap(find.byKey(const ValueKey('super-machines-offline')));
+ await tester.pumpAndSettle();
+ }
+ await tester.tap(card);
+ await tester.pumpAndSettle();
+ await tester.tap(find.widgetWithText(TextButton, 'Configure'));
+ await tester.pumpAndSettle();
+}
+
final _picker = find.byKey(const ValueKey('swarm-machine-picker'));
/// What hovering or focusing a machine row says.
@@ -80,6 +129,28 @@ String _lineOf(WidgetTester tester, String id) => find
Finder _option(String id) => find.byKey(ValueKey('swarm-machine-option-$id'));
+/// The number the Agent slots stepper reads.
+String? _agentSlots(WidgetTester tester) =>
+ tester.widget<Text>(find.byKey(const ValueKey('agent-slots-value'))).data;
+
+Finder _slotsStep(String direction) =>
+ find.byKey(ValueKey('agent-slots-$direction'));
+
+/// Both ends of the range are the controls going dead, not a press that lands
+/// and does nothing.
+AppIconButton _slotsButton(WidgetTester tester, String direction) =>
+ tester.widget<AppIconButton>(_slotsStep(direction));
+
+/// Saving reads preparation more than once: a new operation answers `preparing`
+/// and is only ready from a later read, a second apart — what the real daemon
+/// does (`cli/src/superTabs/contribution.ts`), and the fixture with it.
+Future<void> _settleSave(WidgetTester tester) async {
+ for (var i = 0; i < 3; i++) {
+ await tester.pump(const Duration(seconds: 1));
+ await tester.pumpAndSettle();
+ }
+}
+
void main() {
final capture = Platform.environment['HARNESS_SUPER_TAB_CAPTURE'];
setUpAll(() => loadCaptureFonts(capture));
@@ -1336,6 +1407,7 @@ void main() {
controller: c,
app: f.app,
onAddAgent: (_) {},
+ readLocal: (_) async => _reading(freeGiB: 8),
),
),
),
@@ -1368,7 +1440,7 @@ void main() {
findsOneWidget,
);
await tester.tap(find.widgetWithText(FilledButton, 'Add machine'));
- await tester.pumpAndSettle();
+ await _settleSave(tester);
expect(find.byType(AlertDialog), findsNothing);
expect(f.connection.server.posts.single['command'], {
'type': 'machine.contribute',
@@ -1849,4 +1921,343 @@ void main() {
await tester.pump();
},
);
+
+ testWidgets(
+ 'Add machine starts at the suggested slots and contributes the number the owner picks',
+ (tester) async {
+ final f = SuperTabLaunchFixture();
+ f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Pilot');
+ f.connection.server.state['project'] = {
+ 'machineId': 'm',
+ 'cwd': '/work/project',
+ 'scope': 'swarm',
+ 'repositoryUrl': null,
+ };
+ final c = await f.app.superTabs.open(tabId);
+ await c.refresh();
+ // 8 GiB free: the two-gibibyte-per-agent arithmetic both this form and
+ // the CLI's own suggestion use.
+ await _openAddMachineDialog(
+ tester,
+ f,
+ c,
+ readLocal: (_) async => _reading(freeGiB: 8),
+ );
+
+ // This machine's free memory says four, so the field opens on four
+ // instead of making the owner count it out.
+ expect(_agentSlots(tester), '4');
+ expect(
+ find.text('Each new agent still needs free memory when it starts.'),
+ findsOneWidget,
+ );
+ // Opening the form sets nothing up on the machine — no project folder,
+ // no engine probe, no setup slot — until the owner saves.
+ expect(
+ f.connection.calls.where(
+ (call) =>
+ call.$1 == 'super_tabs' &&
+ call.$2['action'] == 'prepareContribution',
+ ),
+ isEmpty,
+ );
+
+ // What the owner picks is what goes out — the suggestion is only a start.
+ // Stepped off it and back, so the number that saves is the one in the
+ // field rather than the one the memory reading happened to offer.
+ await tester.tap(_slotsStep('fewer'));
+ await tester.pumpAndSettle();
+ expect(_agentSlots(tester), '3');
+ await tester.tap(_slotsStep('more'));
+ await tester.pumpAndSettle();
+ expect(_agentSlots(tester), '4');
+
+ await tester.tap(find.widgetWithText(FilledButton, 'Add machine'));
+ await _settleSave(tester);
+ expect(find.byType(AlertDialog), findsNothing);
+ expect(f.connection.server.posts.single['command'], {
+ 'type': 'machine.contribute',
+ 'machineId': 'm',
+ 'name': f.app.stateOf('m')!.machine.displayName,
+ 'cwd': '/work/project',
+ 'scope': 'swarm',
+ 'engines': ['claude', 'codex', 'pi'],
+ 'maxAgents': 4,
+ });
+ expect(tester.takeException(), isNull);
+
+ await tester.pumpWidget(const SizedBox());
+ await c.flush();
+ f.app.superTabs.dispose();
+ await tester.pump();
+ },
+ );
+
+ testWidgets(
+ 'Configure starts at the machine’s own slots and saves the new number',
+ (tester) async {
+ final f = SuperTabLaunchFixture();
+ f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Pilot');
+ f.connection.server.state['machines'] = [
+ {'machineId': 'm', 'contributorId': 'owner', 'maxAgents': 2},
+ ];
+ final c = await f.app.superTabs.open(tabId);
+ await c.refresh();
+ // Sixteen gibibytes free would suggest 8: this machine's own 2 is what
+ // the field shows, because its own number is not a suggestion.
+ await _openConfigureDialog(
+ tester,
+ f,
+ c,
+ readLocal: (_) async => _reading(freeGiB: 16),
+ );
+
+ // The machine's own number — 2, not the 8 its memory would suggest: an
+ // owner who opens this form and saves it keeps what they had chosen.
+ expect(_agentSlots(tester), '2');
+ await tester.tap(_slotsStep('more'));
+ await tester.pumpAndSettle();
+ await tester.tap(_slotsStep('more'));
+ await tester.pumpAndSettle();
+ expect(_agentSlots(tester), '4');
+
+ await tester.tap(find.widgetWithText(FilledButton, 'Save'));
+ await _settleSave(tester);
+ expect(find.byType(AlertDialog), findsNothing);
+ expect(f.connection.server.posts.single['command'], {
+ 'type': 'machine.contribute',
+ 'machineId': 'm',
+ 'name': f.app.stateOf('m')!.machine.displayName,
+ 'cwd': '/work/project',
+ 'scope': 'swarm',
+ 'engines': ['claude', 'codex', 'pi'],
+ 'maxAgents': 4,
+ });
+ expect(tester.takeException(), isNull);
+
+ await tester.pumpWidget(const SizedBox());
+ await c.flush();
+ f.app.superTabs.dispose();
+ await tester.pump();
+ },
+ );
+
+ testWidgets(
+ 'an unconfirmed contribution is checked first, then the number on screen saves',
+ (tester) async {
+ final f = SuperTabLaunchFixture();
+ f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Pilot');
+ f.connection.server.state['project'] = {
+ 'machineId': 'm',
+ 'cwd': '/work/project',
+ 'scope': 'swarm',
+ 'repositoryUrl': null,
+ };
+ final c = await f.app.superTabs.open(tabId);
+ await c.refresh();
+ await _openAddMachineDialog(
+ tester,
+ f,
+ c,
+ readLocal: (_) async => _reading(freeGiB: 8),
+ );
+ // The first attempt reaches the server and its reply is lost, which
+ // leaves that attempt holding its own receipt — the state the next press
+ // finds.
+ f.connection.server.loseReply = true;
+ await tester.tap(find.widgetWithText(FilledButton, 'Add machine'));
+ await _settleSave(tester);
+ expect(find.byType(AlertDialog), findsOneWidget);
+ expect(f.connection.server.posts.single['command']!['maxAgents'], 4);
+
+ // The owner changes their mind before trying again.
+ await tester.tap(_slotsStep('more'));
+ await tester.pumpAndSettle();
+ await tester.tap(_slotsStep('more'));
+ await tester.pumpAndSettle();
+ expect(_agentSlots(tester), '6');
+
+ await tester.tap(find.widgetWithText(FilledButton, 'Add machine'));
+ await _settleSave(tester);
+ expect(find.byType(AlertDialog), findsNothing);
+ // The stored attempt is settled first, and then the six on screen — the
+ // four it was built with is not what the machine ends up with.
+ expect(f.connection.server.posts.last['command']!['maxAgents'], 6);
+ expect(tester.takeException(), isNull);
+
+ await tester.pumpWidget(const SizedBox());
+ await c.flush();
+ f.app.superTabs.dispose();
+ await tester.pump();
+ },
+ );
+
+ testWidgets(
+ 'a new machine no reading answered for contributes what was suggested',
+ (tester) async {
+ final f = SuperTabLaunchFixture();
+ f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Pilot');
+ f.connection.server.state['project'] = {
+ 'machineId': 'm',
+ 'cwd': '/work/project',
+ 'scope': 'swarm',
+ 'repositoryUrl': null,
+ };
+ final c = await f.app.superTabs.open(tabId);
+ await c.refresh();
+ // This machine's memory does not answer — a reading that failed or had
+ // not arrived — so the field has no suggestion of its own and sits at
+ // the floor of the range.
+ await _openAddMachineDialog(tester, f, c, readLocal: (_) async => null);
+ expect(_agentSlots(tester), '1');
+
+ // The owner never touched it, so the 1 is not a number they chose and
+ // must not be what the machine is contributed with: preparation's own
+ // suggestion is the number the field would have shown.
+ await tester.tap(find.widgetWithText(FilledButton, 'Add machine'));
+ await _settleSave(tester);
+ expect(find.byType(AlertDialog), findsNothing);
+ expect(f.connection.server.posts.single['command']!['maxAgents'], 4);
+ expect(tester.takeException(), isNull);
+
+ await tester.pumpWidget(const SizedBox());
+ await c.flush();
+ f.app.superTabs.dispose();
+ await tester.pump();
+ },
+ );
+
+ testWidgets(
+ 'a check of an earlier attempt that fails says why that attempt is unclear',
+ (tester) async {
+ final f = SuperTabLaunchFixture();
+ f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Pilot');
+ f.connection.server.state['project'] = {
+ 'machineId': 'm',
+ 'cwd': '/work/project',
+ 'scope': 'swarm',
+ 'repositoryUrl': null,
+ };
+ final c = await f.app.superTabs.open(tabId);
+ await c.refresh();
+ await _openAddMachineDialog(
+ tester,
+ f,
+ c,
+ readLocal: (_) async => _reading(freeGiB: 8),
+ );
+ f.connection.server.loseReply = true;
+ await tester.tap(find.widgetWithText(FilledButton, 'Add machine'));
+ await _settleSave(tester);
+ expect(find.byType(AlertDialog), findsOneWidget);
+
+ // Now the earlier attempt cannot be checked either, and the reason it
+ // gives is the one worth reading.
+ f.connection.server.refuse = {
+ 'code': 'MACHINE_NOT_FOUND',
+ 'message': 'This machine is no longer linked to this Swarm.',
+ };
+ await tester.tap(find.widgetWithText(FilledButton, 'Add machine'));
+ await _settleSave(tester);
+ expect(find.byType(AlertDialog), findsOneWidget);
+ expect(
+ find.text('This machine is no longer linked to this Swarm.'),
+ findsOneWidget,
+ );
+ expect(find.textContaining('Could not add this machine'), findsNothing);
+ // The check re-sent the attempt it was already holding, untouched, and
+ // no second, new one followed it out.
+ expect(f.connection.server.posts, hasLength(2));
+ expect(
+ f.connection.server.posts.last['command'],
+ f.connection.server.posts.first['command'],
+ );
+ expect(tester.takeException(), isNull);
+
+ await tester.pumpWidget(const SizedBox());
+ await c.flush();
+ f.app.superTabs.dispose();
+ await tester.pump();
+ },
+ );
+
+ testWidgets('a machine over the range opens at 8, and 8 is what saves', (
+ tester,
+ ) async {
+ final f = SuperTabLaunchFixture();
+ f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Pilot');
+ // Contributed before this form had a range: the backend accepts 16, and
+ // the dialog must not hand the owner a number it would then refuse.
+ f.connection.server.state['machines'] = [
+ {'machineId': 'm', 'contributorId': 'owner', 'maxAgents': 16},
+ ];
+ final c = await f.app.superTabs.open(tabId);
+ await c.refresh();
+ await _openConfigureDialog(tester, f, c);
+
+ expect(_agentSlots(tester), '8');
+ // The top is the top: the button is dead, so no press can make it nine.
+ expect(_slotsButton(tester, 'more').onPressed, isNull);
+ expect(_slotsButton(tester, 'fewer').onPressed, isNotNull);
+ // Saving quietly drops a number the owner chose on a machine that still
+ // has it, so the form says so instead of doing it in silence.
+ expect(
+ find.textContaining('This machine was set to 16 agent slots'),
+ findsOneWidget,
+ );
+
+ await tester.tap(find.widgetWithText(FilledButton, 'Save'));
+ await _settleSave(tester);
+ // The 16 the machine was stored with never leaves the dialog.
+ expect(f.connection.server.posts.single['command'], {
+ 'type': 'machine.contribute',
+ 'machineId': 'm',
+ 'name': f.app.stateOf('m')!.machine.displayName,
+ 'cwd': '/work/project',
+ 'scope': 'swarm',
+ 'engines': ['claude', 'codex', 'pi'],
+ 'maxAgents': 8,
+ });
+ expect(tester.takeException(), isNull);
+
+ await tester.pumpWidget(const SizedBox());
+ await c.flush();
+ f.app.superTabs.dispose();
+ await tester.pump();
+ });
+
+ testWidgets('Agent slots stop at 1 and stop at 8', (tester) async {
+ final f = SuperTabLaunchFixture();
+ f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Pilot');
+ f.connection.server.state['machines'] = [
+ {'machineId': 'm', 'contributorId': 'owner', 'maxAgents': 3},
+ ];
+ final c = await f.app.superTabs.open(tabId);
+ await c.refresh();
+ await _openConfigureDialog(tester, f, c);
+
+ expect(_agentSlots(tester), '3');
+ for (var i = 0; i < 5; i++) {
+ await tester.tap(_slotsStep('more'));
+ await tester.pumpAndSettle();
+ }
+ expect(_agentSlots(tester), '8');
+ // Neither end is a press that lands and does nothing: the button is dead.
+ expect(_slotsButton(tester, 'more').onPressed, isNull);
+ expect(_slotsButton(tester, 'fewer').onPressed, isNotNull);
+
+ for (var i = 0; i < 7; i++) {
+ await tester.tap(_slotsStep('fewer'));
+ await tester.pumpAndSettle();
+ }
+ expect(_agentSlots(tester), '1');
+ expect(_slotsButton(tester, 'fewer').onPressed, isNull);
+ expect(_slotsButton(tester, 'more').onPressed, isNotNull);
+ expect(tester.takeException(), isNull);
+
+ await tester.pumpWidget(const SizedBox());
+ await c.flush();
+ f.app.superTabs.dispose();
+ await tester.pump();
+ });
}