Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Swarm Manage models: delete a saved API, and take it off every Swarm first

bitcoinbuildercb93d27d92d4
diff --git a/cli/src/lib/apiConnectionsRpc.spec.ts b/cli/src/lib/apiConnectionsRpc.spec.ts
index dae48e0a5..f327271c9 100644
--- a/cli/src/lib/apiConnectionsRpc.spec.ts
+++ b/cli/src/lib/apiConnectionsRpc.spec.ts
@@ -15,7 +15,7 @@ function socketWithModels(): BackendSocket {
const socket = relaySocket('fixture')
const host = createServiceHost(emptyPorts())
// Served alone, under a name of its own: `models` is a port's name, which `serve` keeps for `start`.
- host.serve('launch-targets', launchTargetRequests, fakeCore(), ['api_connections', 'codex_profiles_list', 'codex_profile_link'])
+ host.serve('launch-targets', (core) => launchTargetRequests(core, async () => {}), fakeCore(), ['api_connections', 'codex_profiles_list', 'codex_profile_link'])
socket.serviceRouter = host.route
return socket
}
diff --git a/cli/src/lib/swarmApiShares.spec.ts b/cli/src/lib/swarmApiShares.spec.ts
index 761011cbc..5b456c476 100644
--- a/cli/src/lib/swarmApiShares.spec.ts
+++ b/cli/src/lib/swarmApiShares.spec.ts
@@ -67,6 +67,23 @@ describe('an API shared with a Swarm', () => {
expect(answer.status).toBe(204)
})
+ it('takes every share of a deleted API off its grid and closes it, even when grid refuses, and keeps the others', async () => {
+ const stateFile = join(await mkdtemp(join(tmpdir(), 'shares-')), 'shares.json')
+ const f = setup({ stateFile }); open = f.shares
+ await f.shares.share(GRID, 'c1', 'deepseek/deepseek-chat')
+ await f.shares.share('swarm-ffffffffffff', 'c1', 'deepseek/deepseek-chat')
+ await f.shares.share(GRID, 'c2', 'google/gemini')
+ f.exec.mockImplementation(async (args) => args.includes('leave') ? { ...ok, code: 'GRID_FAILED' as const, exitCode: 1, stderr: 'grid is down' } : ok)
+ await f.shares.stopConnection('c1')
+ expect(f.exec.mock.calls.filter(c => c[0].includes('leave')).map(c => c[0][2])).toEqual([GRID, 'swarm-ffffffffffff'])
+ expect(f.shares.list().map(s => s.connectionId)).toEqual(['c2'])
+ expect(JSON.parse(await readFile(stateFile, 'utf8')).map((r: { connectionId: string }) => r.connectionId)).toEqual(['c2'])
+ // Nothing shared: nothing asked of grid.
+ f.exec.mockClear()
+ await f.shares.stopConnection('c9')
+ expect(f.exec).not.toHaveBeenCalled()
+ })
+
it('stops by leaving the grid and closing its endpoint, and says why when grid or the API refuses', async () => {
const f = setup(); open = f.shares
await f.shares.share(GRID, 'c1', 'm')
diff --git a/cli/src/lib/swarmApiShares.ts b/cli/src/lib/swarmApiShares.ts
index 69c2e6713..661835bf8 100644
--- a/cli/src/lib/swarmApiShares.ts
+++ b/cli/src/lib/swarmApiShares.ts
@@ -156,6 +156,20 @@ export class SwarmApiShares {
await writeFile(this.deps.stateFile, JSON.stringify([...this.running.values()].map(({ grid, alias, connectionId, port, token }) => ({ grid, alias, connectionId, port, token }))), { mode: 0o600 }).catch(() => {})
}
+ /** Every share of the saved API [connectionId] off its grid, its endpoint closed whether or not grid answers: the API
+ * is being deleted, and a share holds its key in this process, so it would serve on a key the person removed. */
+ stopConnection(connectionId: string): Promise<void> {
+ return this.serial(async () => {
+ const gone = [...this.running.values()].filter(share => share.connectionId === connectionId)
+ for (const share of gone) {
+ await this.deps.exec(['--remote', 'leave', share.grid, '--engine', share.alias]).catch(() => {})
+ share.server.close()
+ this.running.delete(keyOf(share))
+ }
+ if (gone.length) await this.note()
+ })
+ }
+
/** Every share off its grid, as the process ends: an endpoint that is gone serves nothing. */
async stopAll(): Promise<void> {
for (const share of [...this.running.values()]) await this.stop(share.grid, share.connectionId, share.model).catch(() => {})
diff --git a/cli/src/services/models.spec.ts b/cli/src/services/models.spec.ts
index ca62de553..a303c6537 100644
--- a/cli/src/services/models.spec.ts
+++ b/cli/src/services/models.spec.ts
@@ -44,6 +44,7 @@ const apiShares = vi.hoisted(() => ({
list: vi.fn((_grid?: string) => [{ grid: 'swarm-0123456789ab', connectionId: 'c1', model: 'm', name: 'OpenRouter' }]),
restore: vi.fn(async (): Promise<void> => {}),
rejoin: vi.fn(async () => ({ ok: true })),
+ stopConnection: vi.fn(async (): Promise<void> => {}),
}))
const swarmOffers = vi.hoisted(() => ({
set: vi.fn((): unknown[] => [{ grid: 'swarm-0123456789ab', sharedGrid: 'team', model: 'muse' }]),
@@ -857,7 +858,12 @@ describe('the models service', () => {
expect(rememberSavedApis).toHaveBeenCalledTimes(1)
expect(await ask('api_connections', { action: 'save', connection: { name: 'x' } })).toEqual({ connections: [], presets: [], action: 'save' })
expect(rememberSavedApis).toHaveBeenCalledTimes(2)
+ apiShares.stopConnection.mockClear()
expect(await ask('api_connections', { action: 'remove', id: 'a' })).toEqual({ connections: [], presets: [], action: 'remove' })
+ // A deleted API comes off every Swarm first: its share holds the key.
+ expect(apiShares.stopConnection).toHaveBeenCalledExactlyOnceWith('a')
+ await ask('api_connections', { action: 'remove', id: 7 })
+ expect(apiShares.stopConnection).toHaveBeenCalledOnce()
expect(await ask('api_connections', { action: 'models', id: 'a' })).toEqual({ id: 'a', models: ['m1'] })
expect(apiModelsRequest).toHaveBeenCalledOnce()
expect(rememberSavedApis).toHaveBeenCalledTimes(2)
diff --git a/cli/src/services/models.ts b/cli/src/services/models.ts
index 4d1e0cf1e..9bb712be5 100644
--- a/cli/src/services/models.ts
+++ b/cli/src/services/models.ts
@@ -405,7 +405,7 @@ function modelsRequests(core: CoreApi, grid: GridSetUp, privateGridName: () => P
return { ...await heal.check(payload.grid) }
},
...gridCommands(grid, core.dataDir, shares),
- ...launchTargetRequests(core),
+ ...launchTargetRequests(core, (id) => shares.stopConnection(id)),
}
}
@@ -487,15 +487,17 @@ function gridCommands(grid: GridSetUp, dataDir: string, shares: SwarmApiShares =
* socket's switch (docs/design/2026-10-06-core-boundary-next.md, step 4). Its own function so the socket's
* specs can serve it alone behind the gates.
*/
-export function launchTargetRequests(core: CoreApi): ServiceRequests {
+export function launchTargetRequests(core: CoreApi, onRemove: (connectionId: string) => Promise<void>): ServiceRequests {
// The saved APIs, a file in the data folder (lib/apiConnections.ts): read afresh on every request.
const apiConnections = new ApiConnections(core.dataDir)
return {
// The APIs saved on this machine (lib/apiConnections.ts): list, save and remove one, and one API's
// models. Their keys stay here, so only the owner manages them: this machine's app, or its paired one.
- api_connections: internalOnThrow('api_connections', (payload, asker) => {
+ api_connections: internalOnThrow('api_connections', async (payload, asker) => {
if (!asker.owner) return { error: 'OWNER_REQUIRED' }
if (payload.action === 'models') return apiModelsRequest(apiConnections, payload)
+ // A deleted API comes off every Swarm it is shared with first: its share holds the key and would go on serving.
+ if (payload.action === 'remove' && typeof payload.id === 'string') await onRemove(payload.id)
const reply = apiConnectionsRequest(apiConnections, payload)
if (payload.action === 'save') rememberSavedApis(apiConnections)
return reply
diff --git a/desktop/lib/widgets/api_picker_form.dart b/desktop/lib/widgets/api_picker_form.dart
index 970ba1dcd..3f0b6d898 100644
--- a/desktop/lib/widgets/api_picker_form.dart
+++ b/desktop/lib/widgets/api_picker_form.dart
@@ -27,10 +27,15 @@ class ApiPickerForm extends StatefulWidget {
this.onSwitchPane,
this.connectionId,
this.removing = false,
+ this.swarmShares,
});
final ApiConnectionsController controller;
final String? connectionId;
final bool removing;
+
+ /// In a Swarm's Manage models: how many of this API's models are shared with the Swarm, which stop when it is
+ /// deleted (the CLI takes them off first). Null elsewhere.
+ final int? swarmShares;
final ValueChanged<String?> onClose;
final ValueChanged<bool> onFocusChanged;
final VoidCallback? onSwitchPane;
@@ -470,6 +475,36 @@ class ApiPickerFormState extends State<ApiPickerForm> {
_ => null,
};
+ /// What deleting takes from the Swarm, in a quiet warning beside the sentence.
+ Widget _sharesNote(int shares) {
+ final warn = grid.AppPalette.warn;
+ return Container(
+ key: const ValueKey('api-form:shares-note'),
+ padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
+ decoration: BoxDecoration(
+ color: warn.withValues(alpha: .10),
+ borderRadius: BorderRadius.circular(8),
+ border: Border.all(color: warn.withValues(alpha: .30)),
+ ),
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Icon(AppIcons.triangleAlert, size: 14, color: warn),
+ const SizedBox(width: 8),
+ // Wraps in a narrow pane rather than running past it.
+ Flexible(
+ child: Text(
+ shares == 1
+ ? '1 model stops being shared with this Swarm'
+ : '$shares models stop being shared with this Swarm',
+ style: DesktopChrome.text(size: 12, color: warn),
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+
Widget _actionButton(({String id, String label, VoidCallback? run}) action) {
final node = _buttons.putIfAbsent(
action.id,
@@ -632,9 +667,21 @@ class ApiPickerFormState extends State<ApiPickerForm> {
!widget.removing &&
_editing!.provider != 'custom')
Text(_editing!.baseUrl, style: muted),
- if (widget.removing)
+ if (widget.removing && desktop) ...[
+ const SizedBox(height: 12),
+ // Plain, and true for any API: a custom one's name ("hehe") made "your hehe account" read oddly.
Text(
- 'Remove this saved connection and key?',
+ 'This removes the API and its saved key from ${controller.hostLabel}.',
+ style: style.copyWith(height: 1.5),
+ ),
+ // The CLI takes its models off every Swarm they are shared with first (services/models.ts).
+ if ((widget.swarmShares ?? 0) > 0) ...[
+ const SizedBox(height: 12),
+ _sharesNote(widget.swarmShares!),
+ ],
+ ] else if (widget.removing)
+ Text(
+ 'Remove this saved connection and key? Any Swarm it is shared with stops using it.',
style: style,
),
if (controller.loading && !controller.saving)
@@ -770,68 +817,102 @@ class ApiPickerFormState extends State<ApiPickerForm> {
Text('Saving…', style: muted),
SizedBox(height: cell.height),
],
- _keys(
- desktop && _editing == null
- ? Column(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- for (final action in _actions)
- Padding(
- padding: const EdgeInsets.only(bottom: 8),
- child: _actionButton(action),
- ),
- ],
- )
- : Wrap(
- direction: _editing == null
- ? Axis.vertical
- : Axis.horizontal,
- spacing: desktop ? 8 : cell.width * 2,
- runSpacing: desktop ? 8 : cell.height,
- children: [
- for (final action in _shownActions)
- _actionButton(action),
- ],
- ),
- buttons: true,
- ),
+ // Delete on the desktop: its buttons are the bar at the foot, as every other card's actions.
+ if (!(desktop && widget.removing))
+ _keys(
+ desktop && _editing == null
+ ? Column(
+ crossAxisAlignment:
+ CrossAxisAlignment.stretch,
+ children: [
+ for (final action in _actions)
+ Padding(
+ padding: const EdgeInsets.only(
+ bottom: 8,
+ ),
+ child: _actionButton(action),
+ ),
+ ],
+ )
+ : Wrap(
+ direction: _editing == null
+ ? Axis.vertical
+ : Axis.horizontal,
+ spacing: desktop ? 8 : cell.width * 2,
+ runSpacing: desktop ? 8 : cell.height,
+ children: [
+ for (final action in _shownActions)
+ _actionButton(action),
+ ],
+ ),
+ buttons: true,
+ ),
],
),
),
),
- Padding(
- padding: EdgeInsets.symmetric(
- horizontal: cell.width * 2,
- vertical: cell.height,
- ),
- child: Text(
- [
- for (final (command, label) in [
- (
- 'picker.accept',
- _editing == null || widget.removing ? 'select' : 'save',
- ),
- (
- 'picker.complete',
- desktop ||
- widget.onSwitchPane == null ||
- _visibleFields.isNotEmpty
- ? 'next'
- : 'pane',
- ),
- ('picker.cancel', 'back'),
- ])
- if (effectiveCommandHint(
- context,
- command,
- contextKind: KeymapContext.picker,
- )
- case final hint?)
- '${hint.replaceAll('⇥', 'Tab').replaceAll('↵', 'Enter')} $label',
- ].join(' · '),
- style: desktop ? DesktopChrome.metadata() : muted,
+ if (desktop && widget.removing)
+ _keys(
+ Container(
+ key: const ValueKey('api-form:delete-bar'),
+ padding: const EdgeInsets.symmetric(
+ horizontal: 20,
+ vertical: 14,
+ ),
+ decoration: BoxDecoration(
+ border: Border(top: BorderSide(color: DesktopChrome.rim)),
+ ),
+ child: Row(
+ mainAxisAlignment: MainAxisAlignment.end,
+ children: [
+ for (final id in const ['cancel', 'delete'])
+ for (final action in _actions.where(
+ (action) => action.id == id,
+ )) ...[
+ if (id == 'delete') const SizedBox(width: 8),
+ _actionButton(action),
+ ],
+ ],
+ ),
+ ),
+ buttons: true,
+ )
+ else
+ Padding(
+ padding: EdgeInsets.symmetric(
+ horizontal: cell.width * 2,
+ vertical: cell.height,
+ ),
+ child: Text(
+ [
+ for (final (command, label) in [
+ (
+ 'picker.accept',
+ _editing == null || widget.removing
+ ? 'select'
+ : 'save',
+ ),
+ (
+ 'picker.complete',
+ desktop ||
+ widget.onSwitchPane == null ||
+ _visibleFields.isNotEmpty
+ ? 'next'
+ : 'pane',
+ ),
+ ('picker.cancel', 'back'),
+ ])
+ if (effectiveCommandHint(
+ context,
+ command,
+ contextKind: KeymapContext.picker,
+ )
+ case final hint?)
+ '${hint.replaceAll('⇥', 'Tab').replaceAll('↵', 'Enter')} $label',
+ ].join(' · '),
+ style: desktop ? DesktopChrome.metadata() : muted,
+ ),
),
- ),
],
),
),
diff --git a/desktop/lib/widgets/swarm_resource_preview.dart b/desktop/lib/widgets/swarm_resource_preview.dart
index 4e6bae754..736d3cba9 100644
--- a/desktop/lib/widgets/swarm_resource_preview.dart
+++ b/desktop/lib/widgets/swarm_resource_preview.dart
@@ -688,14 +688,23 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
List<_ResourceAction> _visibleActions() => [
..._actions(),
- // A Swarm's Manage models has no Actions menu: an API's one other action, Edit, is beside its button.
+ // A Swarm's Manage models has no Actions menu: an API's other actions, Edit and Delete, are beside its button.
+ // Delete asks first, as ⌘I's does; the CLI takes the API off every Swarm it is shared with before removing it.
if (_swarmCards) ...[
- if (model?.api case final api? when model?.apiModel == null)
+ if (model?.api case final api? when model?.apiModel == null) ...[
_ResourceAction(
'Edit connection',
_pending.contains(row?.id) ? null : () => _editApi(api.id),
command: 'picker.resource_settings',
),
+ _ResourceAction(
+ 'Delete',
+ _pending.contains(row?.id)
+ ? null
+ : () => _editApi(api.id, removing: true),
+ command: 'picker.resource_remove',
+ ),
+ ],
] else if (!_isManagement &&
row?.isCreate != true &&
_commands().isNotEmpty)
@@ -2585,6 +2594,9 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
controller: widget.search.models!.manager.apis,
connectionId: _apiConnectionId,
removing: _apiRemoving,
+ swarmShares: widget.search.isSwarmModels && row != null
+ ? widget.search.swarmApiShareCount(row!)
+ : null,
onClose: _closeApiForm,
onFocusChanged: widget.search.setManaging,
onSwitchPane: _switchPane,
diff --git a/desktop/test/desktop_resource_forms_edge_test.dart b/desktop/test/desktop_resource_forms_edge_test.dart
index 261fde5f5..869d01198 100644
--- a/desktop/test/desktop_resource_forms_edge_test.dart
+++ b/desktop/test/desktop_resource_forms_edge_test.dart
@@ -258,6 +258,55 @@ void main() {
expect(tester.takeException(), isNull);
});
+ testWidgets(
+ 'deleting an API shared with the Swarm says what stops, its buttons in a bar at the foot, Cancel first',
+ (tester) async {
+ final app = _App();
+ final controller = ApiConnectionsController(app, machineId: 'm')
+ ..loaded = true
+ ..connections = [_connection];
+ addTearDown(app.dispose);
+ addTearDown(controller.dispose);
+ Future<void> mountWith(int? shares) => _mount(
+ tester,
+ ApiPickerForm(
+ key: ValueKey(shares),
+ controller: controller,
+ connectionId: _connection.id,
+ removing: true,
+ swarmShares: shares,
+ onClose: (_) {},
+ onFocusChanged: (_) {},
+ ),
+ );
+ await mountWith(1);
+ expect(
+ find.text('1 model stops being shared with this Swarm'),
+ findsOneWidget,
+ );
+ expect(find.textContaining('This removes the API and its saved key from '), findsOneWidget);
+ final bar = find.byKey(const ValueKey('api-form:delete-bar'));
+ expect(
+ find.descendant(of: bar, matching: _api('delete')),
+ findsOneWidget,
+ );
+ expect(
+ tester.getTopLeft(_api('cancel')).dx,
+ lessThan(tester.getTopLeft(_api('delete')).dx),
+ );
+ await mountWith(3);
+ expect(
+ find.text('3 models stop being shared with this Swarm'),
+ findsOneWidget,
+ );
+ // Not shared, or outside a Swarm: no note.
+ await mountWith(0);
+ expect(find.byKey(const ValueKey('api-form:shares-note')), findsNothing);
+ await mountWith(null);
+ expect(find.byKey(const ValueKey('api-form:shares-note')), findsNothing);
+ },
+ );
+
testWidgets(
'native API deletion starts on Cancel and requires choosing Delete',
(tester) async {