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.

Merge origin/main into feat/api-models

bitcoinbuilder010e237a2232
diff --cc cli/src/backendSocket.ts
index fc9ad7a23,b324dadb9..264355668
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@@ -1644,13 -1678,8 +1679,13 @@@ export class BackendSocket
const requestId = payload.requestId
if (type === 'api_connections') {
- if (!local) { reply(type, requestId, { error: 'LOCAL_ONLY', detail: 'Manage APIs on this computer.' }); return }
+ if (!local && this.e2ee.sessionRole(connId) !== 'web') { reply(type, requestId, { error: 'OWNER_REQUIRED' }); return }
+ if (payload.action === 'models') {
+ reply(type, requestId, await apiModelsRequest(this.apiConnections, payload))
+ return
+ }
reply(type, requestId, apiConnectionsRequest(this.apiConnections, payload))
+ if (payload.action === 'save') rememberSavedApis(this.apiConnections)
return
}
@@@ -2520,26 -2577,6 +2583,27 @@@
// ever crosses the relay and the app cannot be the source of truth for an address it does
// not know. A client that sends the full `grid` object still works unchanged.
const picked = typeof payload.gridModel === 'string' ? payload.gridModel : ''
- // `apiConnection` + `apiModel`: a model of an API saved on this computer. Same rule as a grid
++ // `apiConnection` + `apiModel`: a model of an API saved on this machine. Same rule as a grid
+ // model — the app names it, and the endpoint and key are read here, from the store — and
- // only from this computer, where the key is kept and its owner is the one asking.
++ // only for whoever may manage those APIs (`api_connections`): this machine's own app, or
++ // its owner's paired session. The key itself never leaves this daemon either way.
+ const api = typeof payload.apiConnection === 'string' ? payload.apiConnection : ''
+ if (api && (picked || payload.grid !== undefined || clear)) {
+ reply(type, requestId, { error: 'INVALID_GRID', detail: 'Choose an API model, a grid model or the own login, not several.' })
+ return
+ }
+ if (api) {
- if (!local) { reply(type, requestId, { error: 'LOCAL_ONLY', detail: 'Use saved APIs on this computer.' }); return }
++ if (!local && this.e2ee.sessionRole(connId) !== 'web') { reply(type, requestId, { error: 'OWNER_REQUIRED' }); return }
+ try {
+ payload.grid = await resolveApiTarget(this.apiConnections, api, typeof payload.apiModel === 'string' ? payload.apiModel.trim() : '')
+ } catch (error) {
+ reply(type, requestId, {
+ error: 'API_UNAVAILABLE',
+ detail: error instanceof ApiConnectionError ? error.message : 'This API could not be used. Try again.',
+ })
+ return
+ }
+ }
if (picked && payload.grid === undefined && !clear) {
// The grid the model was picked FROM, when the picker says (a shared grid's section);
// the account's own grid otherwise, as before.
diff --cc cli/src/lib/apiModels.spec.ts
index c743dac71,000000000..6497696f2
mode 100644,000000..100644
--- a/cli/src/lib/apiModels.spec.ts
+++ b/cli/src/lib/apiModels.spec.ts
@@@ -1,196 -1,0 +1,214 @@@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { mkdtempSync, rmSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { BackendSocket } from '../backendSocket.js'
+import { ApiConnections } from './apiConnections.js'
+import { apiModelsRequest, chatModels, forgetApiModels, listApiModels, refreshApiLaunch, resolveApiTarget } from './apiModels.js'
+import { classifyGridAssignment } from './gridAssignment.js'
+import { buildGridEngineLaunch } from './gridLaunch.js'
+
+const secret = 'fixture-openrouter-key'
+const newSecret = 'fixture-rotated-key'
+let directory: string, store: ApiConnections
+
+const listing = {
+ data: [
+ { id: 'anthropic/claude-sonnet-4.6', name: 'Anthropic: Claude Sonnet 4.6', context_length: 1_000_000, supported_parameters: ['tools', 'temperature'], architecture: { output_modalities: ['text'] } },
+ { id: 'z-ai/glm-5', context_length: 202_752, supported_parameters: ['tools'] },
+ { id: 'small/no-room', context_length: 32_768, supported_parameters: ['tools'] },
+ { id: 'plain/no-tools', context_length: 262_144, supported_parameters: ['temperature'] },
+ { id: 'images/only', context_length: 262_144, supported_parameters: ['tools'], architecture: { output_modalities: ['image'] } },
+ ],
+}
+
+function answering(body: unknown, status = 200) {
+ return vi.fn(async (_url: string | URL | Request, _init?: RequestInit) =>
+ new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } }))
+}
+
+beforeEach(() => {
+ directory = mkdtempSync(join(tmpdir(), 'harness-api-models-'))
+ store = new ApiConnections(directory)
+ forgetApiModels()
+})
+afterEach(() => {
+ vi.restoreAllMocks()
+ rmSync(directory, { recursive: true, force: true })
+})
+
+describe('an API as a model source', () => {
+ it('keeps the models a coding agent can run on, and every row of an API that says nothing', () => {
+ expect(chatModels(listing).map((model) => model.id)).toEqual(['anthropic/claude-sonnet-4.6', 'z-ai/glm-5'])
+ expect(chatModels(listing)[0]).toEqual({ id: 'anthropic/claude-sonnet-4.6', name: 'Anthropic: Claude Sonnet 4.6', contextWindow: 1_000_000 })
+ expect(chatModels({ data: [{ id: 'deepseek-chat', object: 'model' }, { id: 'deepseek-chat' }, { id: '' }, 'x'] }))
+ .toEqual([{ id: 'deepseek-chat' }])
+ // Replicate's `/models` is not an OpenAI list: it has no chat models to offer.
+ expect(chatModels({ results: [{ name: 'flux' }] })).toEqual([])
+ expect(chatModels(null)).toEqual([])
+ })
+
+ it('reads the list with the saved Bearer key, keeps it, and reads again when the key changes', async () => {
+ const saved = store.save({ provider: 'openrouter', apiKey: secret })
+ const fetch = answering(listing)
+ expect((await listApiModels(store, saved.id, { fetch })).length).toBe(2)
+ await listApiModels(store, saved.id, { fetch })
+ expect(fetch).toHaveBeenCalledTimes(1)
+ const [url, init] = fetch.mock.calls[0]!
+ expect(url).toBe('https://openrouter.ai/api/v1/models')
+ expect((init?.headers as Record<string, string>).authorization).toBe(`Bearer ${secret}`)
+ store.save({ id: saved.id, provider: 'openrouter', apiKey: newSecret })
+ await listApiModels(store, saved.id, { fetch })
+ expect(fetch).toHaveBeenCalledTimes(2)
+ expect((fetch.mock.calls[1]![1]?.headers as Record<string, string>).authorization).toBe(`Bearer ${newSecret}`)
+ })
+
+ it('says why a list failed, never with the key, and refuses an API agents cannot authenticate to', async () => {
+ const saved = store.save({ provider: 'openrouter', apiKey: secret })
+ const refused = await apiModelsRequest(store, { id: saved.id }, { fetch: answering({ error: 'no' }, 401) })
+ expect(refused).toEqual({ error: 'API_MODELS_FAILED', detail: 'OpenRouter did not accept the saved key. Edit the connection and paste a new key.' })
+ const fal = store.save({ provider: 'fal', apiKey: secret })
+ const fetch = answering(listing)
+ const answer = await apiModelsRequest(store, { id: fal.id }, { fetch })
+ expect(answer).toEqual({ error: 'API_MODELS_FAILED', detail: 'fal.ai does not take a Bearer key, so coding agents cannot run on it.' })
+ expect(fetch).not.toHaveBeenCalled()
+ const listed = await apiModelsRequest(store, { id: saved.id }, { fetch })
+ expect(listed).toMatchObject({ id: saved.id, models: [{ id: 'anthropic/claude-sonnet-4.6' }, { id: 'z-ai/glm-5' }] })
+ expect(JSON.stringify([refused, answer, listed])).not.toContain(secret)
+ })
+
+ it('builds the launch every engine reaches OpenRouter through, and refuses a model it does not list', async () => {
+ const saved = store.save({ provider: 'openrouter', apiKey: secret })
+ const fetch = answering(listing)
+ const target = await resolveApiTarget(store, saved.id, 'anthropic/claude-sonnet-4.6', { fetch })
+ expect(target).toEqual({
+ networkId: 'api:openrouter',
+ networkName: 'OpenRouter',
+ baseUrl: 'https://openrouter.ai/api/v1',
+ apiKey: secret,
+ model: 'anthropic/claude-sonnet-4.6',
+ contextWindow: 1_000_000,
+ })
+ await expect(resolveApiTarget(store, saved.id, 'plain/no-tools', { fetch }))
+ .rejects.toThrow('OpenRouter does not list plain/no-tools for coding agents.')
+
+ // OpenRouter's documented Claude Code setup: `ANTHROPIC_BASE_URL=https://openrouter.ai/api`.
+ const claude = buildGridEngineLaunch('claude', target, { hermesSystemManaged: false })
+ expect(claude.ok && claude.launch.env).toMatchObject({
+ ANTHROPIC_BASE_URL: 'https://openrouter.ai/api',
+ ANTHROPIC_AUTH_TOKEN: secret,
+ ANTHROPIC_MODEL: 'anthropic/claude-sonnet-4.6',
+ CLAUDE_CODE_MAX_CONTEXT_TOKENS: '1000000',
+ })
+ const codex = buildGridEngineLaunch('codex', target, { hermesSystemManaged: false })
+ expect(codex.ok && codex.launch.args).toEqual(expect.arrayContaining(['model_providers.grid.base_url="https://openrouter.ai/api/v1"', 'model_providers.grid.wire_api="responses"']))
+ expect(JSON.stringify(codex.ok && codex.launch.args)).not.toContain(secret)
+ // Its own provider id: OpenCode merges a block named `openrouter` into its built-in provider.
+ const opencode = buildGridEngineLaunch('opencode', target, { hermesSystemManaged: false })
+ expect(opencode.ok && opencode.launch.args).toEqual(['-m', 'api-openrouter/anthropic/claude-sonnet-4.6'])
+ expect(opencode.ok && opencode.launch.configDir!.files[0]!.content).not.toContain(secret)
+ })
+
+ it('reports an agent moved onto a saved API as on its model, and a stranger endpoint as not', async () => {
+ const env = { ANTHROPIC_BASE_URL: 'https://openrouter.ai/api', ANTHROPIC_MODEL: 'z-ai/glm-5' }
+ const saved = store.save({ provider: 'openrouter', apiKey: secret })
+ expect(classifyGridAssignment('claude', { ...env, ANTHROPIC_BASE_URL: 'https://other.example.test/api' })).toBeNull()
+ await resolveApiTarget(store, saved.id, 'z-ai/glm-5', { fetch: answering(listing) })
+ expect(classifyGridAssignment('claude', env)).toEqual({ baseUrl: 'https://openrouter.ai/api', model: 'z-ai/glm-5' })
+ expect(classifyGridAssignment('codex', {}, '-c model_providers.grid.base_url="https://openrouter.ai/api/v1" -m z-ai/glm-5'))
+ .toEqual({ baseUrl: 'https://openrouter.ai/api/v1', model: 'z-ai/glm-5' })
+ })
+
+ it('relaunches with the key saved now, and refuses once the API is removed', async () => {
+ const saved = store.save({ provider: 'openrouter', apiKey: secret })
+ const launch = await resolveApiTarget(store, saved.id, 'z-ai/glm-5', { fetch: answering(listing) })
+ store.save({ id: saved.id, provider: 'openrouter', apiKey: newSecret })
+ expect(refreshApiLaunch(store, launch)).toEqual({ ...launch, apiKey: newSecret })
+ const grid = { networkId: 'grid-1', networkName: 'home', baseUrl: 'https://grid.example.test/relay/v1', apiKey: 'grid-key' }
+ expect(refreshApiLaunch(store, grid)).toBe(grid)
+ store.remove(saved.id)
+ expect(() => refreshApiLaunch(store, launch)).toThrow('This API is not saved. Add it in Models → APIs.')
+ })
+})
+
+describe('agent_retarget onto an API model', () => {
+ function retarget(socket: BackendSocket, payload: Record<string, unknown>, connId = 'local:apis') {
+ return (socket as any).dispatchDown({ type: 'agent_retarget', payload: { requestId: 'r', agentId: 'agent-1', ...payload } }, connId, connId === 'remote' ? 'relay' : 'local')
+ }
+
+ it('resolves the endpoint and key on this computer and hands the engine launch that override', async () => {
+ const socket = new BackendSocket('fixture')
+ const reply = vi.spyOn(socket as any, 'emitReply').mockImplementation(() => {})
+ const saved = store.save({ provider: 'openrouter', apiKey: secret })
+ const access = vi.spyOn(ApiConnections.prototype, 'modelAccess').mockImplementation(() => ({
+ connection: saved,
+ apiKey: secret,
+ }))
+ vi.spyOn(globalThis, 'fetch').mockImplementation(answering(listing))
+ const moved = vi.fn(async () => ({ ok: true as const }))
+ socket.onRetargetAgent = moved
+ await retarget(socket, { apiConnection: 'openrouter', apiModel: 'z-ai/glm-5' })
+ expect(access).toHaveBeenCalledWith('openrouter')
+ expect(moved).toHaveBeenCalledWith({
+ agentId: 'agent-1',
+ grid: {
+ networkId: 'api:openrouter',
+ networkName: 'OpenRouter',
+ baseUrl: 'https://openrouter.ai/api/v1',
+ apiKey: secret,
+ model: 'z-ai/glm-5',
+ contextWindow: 202_752,
+ },
+ })
+ expect(reply).toHaveBeenCalledWith('local:apis', 'agent_retarget', 'r', { retargeted: true })
+ await socket.stop()
+ })
+
- it('refuses a remote client, and a frame naming an API with anything else', async () => {
++ it('refuses a session that is not the owner\'s, and a frame naming an API with anything else', async () => {
+ const socket = new BackendSocket('fixture')
+ const reply = vi.spyOn(socket as any, 'emitReply').mockImplementation(() => {})
+ const moved = vi.fn(async () => ({ ok: true as const }))
+ socket.onRetargetAgent = moved
- // Authenticated and encrypted, and still refused: the key stays with its owner on this computer.
++ // Encrypted, but not the owner's paired session: refused, as managing these APIs would be.
+ vi.spyOn((socket as any).e2ee, 'unwrapDown').mockReturnValueOnce({
+ type: 'agent_retarget', payload: { requestId: 'r', agentId: 'agent-1', apiConnection: 'openrouter', apiModel: 'z-ai/glm-5' },
+ })
+ await (socket as any).dispatchDown({ type: 'agent_retarget', payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'fixture' } } }, 'remote')
- expect(reply).toHaveBeenLastCalledWith('remote', 'agent_retarget', 'r', { error: 'LOCAL_ONLY', detail: 'Use saved APIs on this computer.' })
++ expect(reply).toHaveBeenLastCalledWith('remote', 'agent_retarget', 'r', { error: 'OWNER_REQUIRED' })
+ await retarget(socket, { apiConnection: 'openrouter', apiModel: 'z-ai/glm-5', gridModel: 'Qwen' })
+ expect(reply).toHaveBeenLastCalledWith('local:apis', 'agent_retarget', 'r', expect.objectContaining({ error: 'INVALID_GRID' }))
+ await retarget(socket, { apiConnection: 'openrouter', clearGrid: true })
+ expect(reply).toHaveBeenLastCalledWith('local:apis', 'agent_retarget', 'r', expect.objectContaining({ error: 'INVALID_GRID' }))
+ expect(moved).not.toHaveBeenCalled()
+ await socket.stop()
+ })
+
++ it('lets the owner\'s paired session use the API, as it may manage it', async () => {
++ const socket = new BackendSocket('fixture')
++ const reply = vi.spyOn(socket as any, 'emitReply').mockImplementation(() => {})
++ const saved = store.save({ provider: 'openrouter', apiKey: secret })
++ vi.spyOn(ApiConnections.prototype, 'modelAccess').mockImplementation(() => ({ connection: saved, apiKey: secret }))
++ vi.spyOn(globalThis, 'fetch').mockImplementation(answering(listing))
++ vi.spyOn((socket as any).e2ee, 'sessionRole').mockReturnValue('web')
++ vi.spyOn((socket as any).e2ee, 'unwrapDown').mockReturnValueOnce({
++ type: 'agent_retarget', payload: { requestId: 'r', agentId: 'agent-1', apiConnection: 'openrouter', apiModel: 'z-ai/glm-5' },
++ })
++ const moved = vi.fn(async () => ({ ok: true as const }))
++ socket.onRetargetAgent = moved
++ await (socket as any).dispatchDown({ type: 'agent_retarget', payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'fixture' } } }, 'owner')
++ expect(moved).toHaveBeenCalledWith(expect.objectContaining({ grid: expect.objectContaining({ networkId: 'api:openrouter', model: 'z-ai/glm-5' }) }))
++ expect(reply).toHaveBeenLastCalledWith('owner', 'agent_retarget', 'r', { retargeted: true })
++ await socket.stop()
++ })
++
+ it('answers why an API cannot be used, without touching the pane', async () => {
+ const socket = new BackendSocket('fixture')
+ const reply = vi.spyOn(socket as any, 'emitReply').mockImplementation(() => {})
+ const moved = vi.fn(async () => ({ ok: true as const }))
+ socket.onRetargetAgent = moved
+ await retarget(socket, { apiConnection: 'never-saved', apiModel: 'z-ai/glm-5' })
+ expect(reply).toHaveBeenLastCalledWith('local:apis', 'agent_retarget', 'r', expect.objectContaining({ error: 'API_UNAVAILABLE' }))
+ expect(moved).not.toHaveBeenCalled()
+ await socket.stop()
+ })
+})
diff --cc desktop/lib/models/api_connections_controller.dart
index cdd91e952,2cd328ea6..5315efba1
--- a/desktop/lib/models/api_connections_controller.dart
+++ b/desktop/lib/models/api_connections_controller.dart
@@@ -45,42 -39,39 +45,71 @@@ class ApiConnection
});
}
+/// One chat model a saved API lists — no key, only what the API says about the model.
+class ApiModel {
+ const ApiModel({required this.id, this.name, this.contextWindow});
+ final String id;
+ final String? name;
+ final int? contextWindow;
+
+ static ApiModel? fromJson(Object? json) {
+ if (json is! Map<String, dynamic>) return null;
+ final id = json['id'];
+ if (id is! String || id.trim().isEmpty) return null;
+ final name = json['name'];
+ final window = json['contextWindow'];
+ return ApiModel(
+ id: id,
+ name: name is String && name.trim().isNotEmpty ? name : null,
+ contextWindow: window is int && window > 0 ? window : null,
+ );
+ }
+}
+
+/// What reading one API's models answered: the list, or why there is none.
+class ApiModels {
+ const ApiModels({this.models = const [], this.loading = false, this.error});
+ final List<ApiModel> models;
+ final bool loading;
+ final String? error;
+}
+
class ApiConnectionsController extends ChangeNotifier {
- ApiConnectionsController(this.app) {
+ ApiConnectionsController(this.app, {String? machineId})
+ : _machineId =
+ machineId ??
+ (app.viewer == null
+ ? null
+ : app.ownedActionMachine?.machine.machineId) {
app.addListener(_observe);
- _owner = app.localMachineState;
+ _owner = _target;
_connected = available;
}
final AppNotifier app;
+ String? _machineId;
+ MachineState? get _target {
+ if (_machineId != null) return app.stateOf(_machineId!);
+ if (app.viewer == null) return app.localMachineState;
+ final machine = app.ownedActionMachine;
+ _machineId = machine?.machine.machineId;
+ return machine;
+ }
+
++ /// The machine these APIs are saved on — the only one whose harnesses can run on their models.
++ String? get machineId => _owner?.machine.machineId;
++
+ String get hostLabel => app.viewer == null && _machineId == null
+ ? 'this computer'
+ : _owner?.machine.displayName ?? 'a connected machine';
+ String get _connectMessage => 'Connect $hostLabel to manage APIs.';
+
+ /// Called between panels, never while an API editor is open.
+ void useMachine(String machineId) {
+ if (_disposed || saving || machineId == _machineId) return;
+ _machineId = machineId;
+ _observe();
+ }
+
MachineState? _owner;
bool _disposed = false;
bool _connected = false;
@@@ -89,13 -80,12 +118,18 @@@
bool loading = false, saving = false, loaded = false;
String? error;
+ /// Each saved API's chat models, by connection id, read while a model list is on screen
+ /// ([loadModels]). An API that takes no Bearer key has no entry: it is for tools only.
+ final Map<String, ApiModels> models = {};
+ bool _modelsWanted = false;
+ int _modelsRevision = 0;
+
- bool get available => _owner?.connectionStatus == ConnectionStatus.connected;
+ bool get available =>
+ _owner != null &&
+ !_owner!.machine.isShared &&
+ !_owner!.needsLink &&
+ _owner!.nodeOnline != false &&
+ _owner!.connectionStatus == ConnectionStatus.connected;
void _changed() {
if (!_disposed) notifyListeners();
}
@@@ -110,13 -100,11 +144,13 @@@
}
return;
}
- _owner = app.localMachineState;
+ _owner = _target;
_connected = available;
_revision++;
+ _modelsRevision++;
connections = [];
presets = [];
+ models.clear();
loading = saving = loaded = false;
error = null;
unawaited(refresh());
diff --cc desktop/lib/state/app_state.dart
index b6af06ff6,53d4466b4..e24e51902
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@@ -5521,11 -5752,26 +5797,27 @@@ class AppNotifier extends ChangeNotifie
Future<Map<String, dynamic>> apiConnections(
String machineId,
- Map<String, dynamic> payload,
- ) async {
+ Map<String, dynamic> payload, {
+ Duration timeout = const Duration(seconds: 10),
- }) =>
- _conn(machineId)
- .request('api_connections', payload: payload, timeout: timeout);
++ }) async {
+ final machine = stateOf(machineId);
+ if (machine == null ||
+ machine.machine.isShared ||
+ machine.needsLink ||
+ machine.nodeOnline == false ||
+ machine.connectionStatus != ConnectionStatus.connected) {
+ throw StateError('Reconnect this machine to manage its APIs.');
+ }
+ final connection = _conn(machineId);
+ if (!connection.isReady) {
+ throw StateError('Reconnect this machine to manage its APIs.');
+ }
+ return connection.request(
+ 'api_connections',
+ payload: payload,
- timeout: const Duration(seconds: 10),
++ timeout: timeout,
+ );
+ }
Future<Map<String, dynamic>> controlLocalModel(
String machineId,
diff --cc desktop/lib/state/swarm_search.dart
index 6df3fecc8,79ae96e0f..954266c2a
--- a/desktop/lib/state/swarm_search.dart
+++ b/desktop/lib/state/swarm_search.dart
@@@ -96,76 -95,6 +96,77 @@@ class SwarmSearchController extends Cha
bool modelDownloadsVisible = false;
bool isModelDownloadsRow(SwarmDestination? row) =>
isModelMode && row?.id == 'model:downloads';
+
+ /// Saved APIs whose models are shown under them. An API such as OpenRouter lists hundreds, so
+ /// they stay folded until Enter on the API's row — or a search that matches them.
+ final expandedApis = <String>{};
+
+ /// [row] is a saved API's own row (not one of its models).
+ bool isApiRow(SwarmDestination? row) {
+ final entry = models?.entries[row?.modelId];
+ return entry?.api != null && entry?.apiModel == null;
+ }
+
+ /// [row] is one of a saved API's models, listed under the API's row.
+ bool isApiModelRow(SwarmDestination? row) =>
+ models?.entries[row?.modelId]?.apiModel != null;
+
+ /// Whether [row]'s API has its models shown under it, and the words at the end of its row: how
+ /// many models it lists, or that it is for tools. Null for any other row.
+ ({bool open, String hint})? apiRowState(SwarmDestination? row) {
+ if (!isModelMode || !isApiRow(row)) return null;
+ final api = models!.entries[row!.modelId]!.api!;
+ final listed = models!.manager.apis.models[api.id];
+ final count = listed?.models.length ?? 0;
+ return (
+ // Open while any of its models is listed under it: unfolded, or found by a search.
+ open: rows.any(
+ (shown) =>
+ models!.entries[shown.modelId]?.apiModel != null &&
+ models!.entries[shown.modelId]!.api!.id == api.id,
+ ),
+ hint: !api.servesModels
+ ? 'Tools'
+ : listed?.loading == true && count == 0
+ ? 'Loading…'
+ : count > 0
+ ? '$count ${count == 1 ? 'model' : 'models'}'
+ : 'Tools',
+ );
+ }
+
+ /// Enter on [row] shows or hides its API's models: it lists some, or is still reading them.
+ bool canExpandApi(SwarmDestination? row) {
+ if (!isModelMode || !isApiRow(row)) return false;
+ final api = models!.entries[row!.modelId]!.api!;
+ final listed = models!.manager.apis.models[api.id];
+ return api.servesModels &&
+ listed != null &&
+ (listed.models.isNotEmpty || listed.loading);
+ }
+
+ /// The API model [row] offers the focused harness, or null when it cannot run on it: only a
- /// harness on this computer, where the API's key is kept, on an engine that can be re-pointed.
++ /// harness on the machine the APIs are saved on (this computer, in the desktop app), where the
++ /// key is kept, on an engine that can be re-pointed.
+ ({ApiConnection api, ApiModel model})? selectableApiModel(
+ SwarmDestination? row,
+ ) {
+ if (!isModelMode || modelSelectionEngine == null) return null;
+ final entry = models?.entries[row?.modelId];
+ final api = entry?.api, model = entry?.apiModel;
+ if (api == null || model == null || !api.servesModels) return null;
+ if (_modelChoices?.canRunLocally(modelSelectionEngine) == false) {
+ return null;
+ }
+ final machine = app.stateOf(_modelSelectionMachineId ?? '');
+ if (machine == null ||
- !machine.isLocalMachine ||
++ machine.machine.machineId != models!.manager.apis.machineId ||
+ machine.connectionStatus != ConnectionStatus.connected) {
+ return null;
+ }
+ return (api: api, model: model);
+ }
+
late final _showDownloadsRow = SwarmDestination(
id: 'model:downloads',
modelId: 'model:downloads',
@@@ -235,14 -164,7 +236,15 @@@
if (subscription['status'] == 'Not signed in') return 'Not signed in';
return 'Other account';
}
- if (entry.api != null) return 'Tools only';
+ if (entry.apiModel != null) {
+ final machine = app.stateOf(_modelSelectionMachineId ?? '');
- if (machine != null && !machine.isLocalMachine) {
- return 'This computer only';
++ if (machine != null &&
++ machine.machine.machineId != models!.manager.apis.machineId) {
++ return 'Other machine';
+ }
+ return 'Not available to this harness';
+ }
+ if (entry.api != null) return canExpandApi(row) ? null : 'Tools only';
if (entry.gridModel?.unavailable != null) return 'Offline';
if (entry.needsDownload) return 'Download first';
if (entry.local case final local?) {
diff --cc desktop/lib/widgets/api_picker_form.dart
index 6d977a47f,10abc3c0a..5fe366f73
--- a/desktop/lib/widgets/api_picker_form.dart
+++ b/desktop/lib/widgets/api_picker_form.dart
@@@ -548,12 -502,13 +550,15 @@@ class ApiPickerFormState extends State<
),
),
if (_editing != null && !widget.removing) ...[
- Text('Stored on this computer.', style: muted),
+ Text(
+ 'Stored on ${controller.hostLabel}.',
+ style: muted,
+ ),
SizedBox(height: cell.height),
],
- if (_error ?? controller.error case final error?) ...[
+ if ((_errorField == null ? _error : null) ??
+ controller.error
+ case final error?) ...[
Text(
error,
style: terminalContentStyle(color: theme.yellow),
diff --cc desktop/lib/widgets/swarm_resource_preview.dart
index afff23083,bba0c5867..ed44f9d14
--- a/desktop/lib/widgets/swarm_resource_preview.dart
+++ b/desktop/lib/widgets/swarm_resource_preview.dart
@@@ -1115,63 -1095,6 +1113,65 @@@ class _SwarmResourcePreviewState extend
], controls: true);
}
+ static const _kDetailLabelColumns = 9;
+
+ /// A saved API, or one of its models: a summary line, then labelled facts, then what it is for.
+ Widget _apiPreview(ModelSearchEntry entry) {
+ final api = entry.api!;
+ final listed = widget.search.models!.manager.apis.models[api.id];
+ final model = entry.apiModel;
+ if (model != null) {
+ final reason = widget.search.modelUseReason(row);
+ return _details([
+ entry.name,
+ [
+ api.name,
+ if (model.contextWindow case final window?)
+ '${contextWindowLabel(window)} context',
+ ].join(' · '),
+ '',
+ if (model.name case final name?) ('Name', name),
+ ('Via', '${api.name} · ${api.host}'),
+ '',
+ if (reason == null)
- 'Use runs this harness on it, with the key saved on this computer.'
- else if (reason == 'This computer only')
- 'Saved APIs run the harnesses on this computer only.'
++ 'Use runs this harness on it, with the key saved on '
++ '${widget.search.models!.manager.apis.hostLabel}.'
++ else if (reason == 'Other machine')
++ 'Its key is saved on ${widget.search.models!.manager.apis.hostLabel}, '
++ 'so only the harnesses there can run on it.'
+ else
+ reason,
+ ], controls: true);
+ }
+ final count = listed?.models.length ?? 0;
+ // One line for what the API is for: a harness runs on its models (Use), or harness agents call
+ // it (Tools) — fal.ai, Replicate, and any API that lists no models a coding agent can run on.
+ final summary = !api.servesModels || count > 0
+ ? null
+ : switch (listed) {
+ ApiModels(loading: true) => 'Loading models…',
+ ApiModels(error: _?) => 'Models unavailable',
+ _ => null,
+ };
+ return _details([
+ entry.name,
+ ['API', ?summary].join(' · '),
+ '',
+ ('URL', api.baseUrl),
+ if (count > 0)
+ (
+ 'Use',
+ 'pick one of its $count ${count == 1 ? 'model' : 'models'} to run a harness on it',
+ )
+ else if (summary == null)
+ (
+ 'Tools',
+ 'harness agents on this computer can call it with the saved key',
+ ),
+ if (listed?.error case final error?) ...['', error],
+ ], controls: true);
+ }
+
Widget _machinePreview() {
final machine = app.stateOf(row!.machineId!);
if (machine == null) return _details([row!.title, 'Unavailable']);
diff --cc desktop/test/api_model_picker_test.dart
index 55ca71f43,000000000..e48068b4f
mode 100644,000000..100644
--- a/desktop/test/api_model_picker_test.dart
+++ b/desktop/test/api_model_picker_test.dart
@@@ -1,646 -1,0 +1,646 @@@
+// A saved API as a place to run a harness (Cmd-I / Cmd-P `:`): an API that takes a Bearer key lists
+// its chat models folded under its row, Enter shows them, and Use moves the focused pane's agent onto
+// one through the daemon — which reads the endpoint and key itself. Only this computer's harnesses
+// can use its APIs, and an API that takes no Bearer key stays tools-only.
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/models/api_connections_controller.dart';
+import 'package:harness/models/model_search_catalog.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/state/retarget_refusal.dart';
+import 'package:harness/state/swarm_navigation.dart';
+import 'package:harness/state/swarm_search.dart';
+import 'package:harness/widgets/swarm_resource_preview.dart';
+import 'package:harness/widgets/swarm_switcher.dart';
+import 'package:harness/ws/local_cli_discovery.dart';
+
+import 'keymap_host_test.dart' show MemoryKeymap, key;
+import 'keymap_runtime_test.dart' as configured;
+import 'resource_picker_test.dart' show fixture;
+import 'support/model_manager.dart';
+import 'support/real_fonts.dart';
+
+final field = find.byKey(const ValueKey('swarm-search-input'));
+SwarmSearchController search(WidgetTester tester) =>
+ tester.widget<SwarmSearchResults>(find.byType(SwarmSearchResults)).search;
+
+const openRouter = ApiConnection({
+ 'id': 'openrouter',
+ 'provider': 'openrouter',
+ 'name': 'OpenRouter',
+ 'baseUrl': 'https://openrouter.ai/api/v1',
+ 'keyEnv': 'OPENROUTER_API_KEY',
+ 'authHeader': 'Authorization',
+ 'authPrefix': 'Bearer',
+});
+const customDs = ApiConnection({
+ 'id': 'custom-ds',
+ 'provider': 'custom',
+ 'name': 'custom ds',
+ 'baseUrl': 'https://relay.example.test/v1',
+ 'keyEnv': 'CUSTOM_DS_API_KEY',
+ 'authHeader': 'Authorization',
+ 'authPrefix': 'Bearer',
+});
+const fal = ApiConnection({
+ 'id': 'fal-ai',
+ 'provider': 'fal',
+ 'name': 'fal.ai',
+ 'baseUrl': 'https://queue.fal.run',
+ 'keyEnv': 'FAL_KEY',
+ 'authHeader': 'Authorization',
+ 'authPrefix': 'Key',
+});
+
+class _ApiApp extends ModelManagerTestApp {
+ _ApiApp() : super(ModelManagerConnection());
+ final modelReads = <String>[];
+ final moves = <({String machine, String agent, String api, String model})>[];
+ Map<String, dynamic> Function(String id)? answer;
+
+ @override
+ Future<Map<String, dynamic>> apiConnections(
+ String machineId,
+ Map<String, dynamic> payload, {
+ Duration timeout = const Duration(seconds: 10),
+ }) async {
+ if (payload['action'] == 'models') {
+ final id = payload['id'] as String;
+ modelReads.add(id);
+ return answer?.call(id) ??
+ {
+ 'id': id,
+ 'models': [
+ {
+ 'id': 'anthropic/claude-sonnet-4.6',
+ 'name': 'Anthropic: Claude Sonnet 4.6',
+ 'contextWindow': 1000000,
+ },
+ {'id': 'z-ai/glm-5', 'contextWindow': 202752},
+ ],
+ };
+ }
+ if (payload['action'] == 'save') {
+ final input = Map<String, dynamic>.from(payload['connection'] as Map)
+ ..remove('apiKey');
+ input['id'] = '${input['name']}'.toLowerCase().replaceAll(
+ RegExp('[^a-z0-9]+'),
+ '-',
+ );
+ listed = [...listed.where((row) => row['id'] != input['id']), input];
+ }
+ return {'connections': listed, 'presets': const <Object>[]};
+ }
+
+ /// The APIs the CLI would list: the fixture's, then any saved through the editor.
+ List<Map<String, dynamic>> listed = [openRouter.data, fal.data];
+
+ @override
+ Future<void> retargetAgentToApiModel(
+ String machineId,
+ String agentId, {
+ required String connectionId,
+ required String modelId,
+ }) async {
+ moves.add((
+ machine: machineId,
+ agent: agentId,
+ api: connectionId,
+ model: modelId,
+ ));
+ }
+}
+
+Future<_ApiApp> _apiFixture({String agentMachine = 'm', Agent? agent}) async {
+ final app = _ApiApp()
+ ..inventory = const GridModels(
+ gridName: 'home',
+ models: [],
+ grids: [GridSection(name: 'home', own: true, models: [])],
+ );
+ await fixture(provided: app);
+ app.modelManager.apis.connections = [openRouter, fal];
+ final machine = app.machineStates[agentMachine]!
+ ..localEndpoint = LocalCliEndpoint(
+ computerId: 'fixture',
+ wsUri: Uri.parse('ws://fixture.invalid'),
+ protocolVersion: 1,
+ terminalProtocolVersion: 3,
+ )
+ ..connectionStatus = ConnectionStatus.connected
+ ..agentLoadStatus = AgentLoadStatus.loaded;
+ machine.agents.add(
+ agent ??
+ const Agent(
+ id: 'a69',
+ name: 'Current harness',
+ engine: 'claude',
+ terminalAvailable: true,
+ ),
+ );
+ return app;
+}
+
+String rowTitle(SwarmDestination row) => row.title;
+
+Finder inPreview(String text) => find.descendant(
+ of: find.byType(SwarmResourcePreview),
+ matching: find.text(text),
+);
+
+void main() {
+ setUpAll(loadRealFonts);
+
+ testWidgets(
+ "an API's models stay folded until Enter on its row, and Use moves the pane onto one",
+ (tester) async {
+ final app = await _apiFixture();
+ final map = MemoryKeymap();
+ try {
+ await configured.mount(tester, app, map);
+ await key(tester, LogicalKeyboardKey.keyI, cmd: true);
+ await tester.pumpAndSettle();
+ final picker = search(tester);
+ expect(picker.modelSelectionEngine, 'claude');
+ // Read once for the API that takes a Bearer key; fal.ai is for tools only.
+ expect(app.modelReads, ['openrouter']);
+ expect(
+ picker.rows.where(
+ (row) => row.modelId?.startsWith('model:apimodel:') == true,
+ ),
+ isEmpty,
+ );
+ final apiRow = picker.rows.singleWhere(
+ (row) => row.modelId == 'model:api:openrouter',
+ );
+ expect(picker.canExpandApi(apiRow), isTrue);
+ expect(
+ picker.canExpandApi(
+ picker.rows.singleWhere((row) => row.modelId == 'model:api:fal-ai'),
+ ),
+ isFalse,
+ );
+ // fal.ai lists no models to run a harness on: its preview says what it is for instead.
+ final falRow = picker.rows.singleWhere(
+ (row) => row.modelId == 'model:api:fal-ai',
+ );
+ picker.move(picker.rows.indexOf(falRow) - picker.cursor);
+ await tester.pump();
+ expect(inPreview('Tools'), findsOneWidget);
+ expect(
+ find.text(
+ 'harness agents on this computer can call it with the saved key',
+ ),
+ findsOneWidget,
+ );
+ expect(find.textContaining('models to run a harness'), findsNothing);
+
+ // Folded: a marker to open it, and how many models it has at the end of its row.
+ expect(
+ tester
+ .widget<Text>(
+ find.byKey(
+ const ValueKey('api-row-marker:model:api:openrouter'),
+ ),
+ )
+ .data,
+ '▸',
+ );
+ expect(
+ tester
+ .widget<Text>(
+ find.byKey(const ValueKey('api-row-hint:model:api:openrouter')),
+ )
+ .data,
+ '2 models',
+ );
+ expect(
+ tester
+ .widget<Text>(
+ find.byKey(const ValueKey('api-row-hint:model:api:fal-ai')),
+ )
+ .data,
+ 'Tools',
+ );
+ picker.move(picker.rows.indexOf(apiRow) - picker.cursor);
+ await tester.pump();
+ expect(
+ find.text('pick one of its 2 models to run a harness on it'),
+ findsOneWidget,
+ );
+ expect(find.text('Use'), findsWidgets);
+ expect(find.text('https://openrouter.ai/api/v1'), findsOneWidget);
+ expect(inPreview('Key'), findsNothing);
+ expect(find.textContaining('OPENROUTER_API_KEY'), findsNothing);
+ expect(inPreview('Tools'), findsNothing);
+ expect(picker.actionLabel(apiRow), 'Show models');
+
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pump();
+ expect(picker.expandedApis, {'openrouter'});
+ expect(
+ picker.selected!.modelId,
+ apiModelRowId('openrouter', 'anthropic/claude-sonnet-4.6'),
+ );
+ // Named alone, one step in under its API, which now says it is open.
+ expect(picker.selected!.title, 'anthropic/claude-sonnet-4.6');
+ final marker = find.byKey(
+ const ValueKey('api-row-marker:model:api:openrouter'),
+ );
+ expect(tester.widget<Text>(marker).data, '▾');
+ expect(
+ tester
+ .getTopLeft(
+ find.descendant(
+ of: find.byKey(
+ ValueKey(
+ 'swarm-search-line:${apiModelRowId('openrouter', 'anthropic/claude-sonnet-4.6')}',
+ ),
+ ),
+ matching: find.text('anthropic/claude-sonnet-4.6'),
+ ),
+ )
+ .dx,
+ greaterThan(
+ tester
+ .getTopLeft(
+ find.descendant(
+ of: find.byKey(
+ const ValueKey('swarm-search-line:model:api:openrouter'),
+ ),
+ matching: find.text('OpenRouter'),
+ ),
+ )
+ .dx,
+ ),
+ );
+ expect(picker.modelRowAction(picker.selected!), 'Use');
+ expect(find.text('OpenRouter · 1M context'), findsOneWidget);
+ expect(find.text('Anthropic: Claude Sonnet 4.6'), findsOneWidget);
+ expect(app.moves, isEmpty);
+
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(app.moves, [
+ (
+ machine: 'm',
+ agent: 'a69',
+ api: 'openrouter',
+ model: 'anthropic/claude-sonnet-4.6',
+ ),
+ ]);
+ expect(find.byType(SwarmSearchResults), findsNothing);
+ expect(tester.takeException(), isNull);
+ } finally {
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ map.dispose();
+ }
+ },
+ );
+
+ testWidgets(
+ '[ Add ] under APIs says what an API is for, and nothing about local models',
+ (tester) async {
+ final app = await _apiFixture();
+ final map = MemoryKeymap();
+ try {
+ await configured.mount(tester, app, map);
+ await key(tester, LogicalKeyboardKey.keyI, cmd: true);
+ await tester.pumpAndSettle();
+ final picker = search(tester);
+ final add = picker.rows.singleWhere((row) => row.isCreate);
+ picker.move(picker.rows.indexOf(add) - picker.cursor);
+ await tester.pump();
+ expect(find.text('Add an API key'), findsOneWidget);
+ expect(
+ find.text(
+ 'OpenRouter or a Custom API: Use its models to run a harness.',
+ ),
+ findsOneWidget,
+ );
+ expect(
+ find.text(
+ 'fal.ai or Replicate: harness agents can call it as a tool.',
+ ),
+ findsOneWidget,
+ );
+ expect(find.textContaining('local model'), findsNothing);
+ } finally {
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ map.dispose();
+ }
+ },
+ );
+
+ testWidgets(
+ 'a search finds API models without unfolding them, each under its own API',
+ (tester) async {
+ final app = await _apiFixture();
+ app.modelManager.apis.connections = [openRouter, customDs, fal];
+ final map = MemoryKeymap();
+ try {
+ await configured.mount(tester, app, map);
+ await key(tester, LogicalKeyboardKey.keyI, cmd: true);
+ await tester.pumpAndSettle();
+ await tester.enterText(field, ':glm');
+ await tester.pumpAndSettle();
+ final picker = search(tester);
+ final apis = picker.rows
+ .where((row) => picker.isApiRow(row) || picker.isApiModelRow(row))
+ .map((row) => row.modelId)
+ .toList();
+ // Both APIs list the model: each copy sits under its own API, and neither API unfolded.
+ expect(apis, [
+ 'model:api:openrouter',
+ apiModelRowId('openrouter', 'z-ai/glm-5'),
+ 'model:api:custom-ds',
+ apiModelRowId('custom-ds', 'z-ai/glm-5'),
+ ]);
+ expect(picker.expandedApis, isEmpty);
+ expect(find.text('z-ai/glm-5'), findsNWidgets(2));
+ expect(find.textContaining('· OpenRouter'), findsNothing);
+ } finally {
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ map.dispose();
+ }
+ },
+ );
+
+ testWidgets('Save returns to the list on the new API, ready to open it', (
+ tester,
+ ) async {
+ final app = await _apiFixture();
+ final map = MemoryKeymap();
+ try {
+ await configured.mount(tester, app, map);
+ await key(tester, LogicalKeyboardKey.keyI, cmd: true);
+ await tester.pumpAndSettle();
+ final picker = search(tester);
+ final add = picker.rows.singleWhere((row) => row.isCreate);
+ picker.move(picker.rows.indexOf(add) - picker.cursor);
+ await tester.pump();
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ await tester.tap(find.byKey(const ValueKey('api-form:provider:custom')));
+ await tester.pumpAndSettle();
+ await tester.enterText(
+ find.byKey(const ValueKey('api-form-input:name')),
+ 'haha cust',
+ );
+ await key(tester, LogicalKeyboardKey.tab);
+ expect(
+ tester
+ .widget<TextField>(find.byKey(const ValueKey('api-form-input:url')))
+ .focusNode!
+ .hasFocus,
+ isTrue,
+ );
+ await tester.enterText(
+ find.byKey(const ValueKey('api-form-input:url')),
+ 'https://relay.example.test/v1',
+ );
+ await tester.enterText(
+ find.byKey(const ValueKey('api-form-input:key')),
+ 'fixture-key',
+ );
+ // Tab from the last field reaches Save; Enter presses it.
+ await key(tester, LogicalKeyboardKey.tab);
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+
+ // Back on the list, on the API just saved, with the keys in the list rather than the pane.
+ expect(find.byKey(const ValueKey('api-form:save')), findsNothing);
+ expect(picker.selected?.modelId, 'model:api:haha-cust');
+ expect(picker.managing, isFalse);
+ expect(tester.widget<TextField>(field).focusNode!.hasFocus, isTrue);
+ await tester.pumpAndSettle();
+ // Enter opens its models straight away.
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pump();
+ expect(picker.expandedApis, contains('haha-cust'));
+ expect(
+ picker.selected?.modelId,
+ apiModelRowId('haha-cust', 'anthropic/claude-sonnet-4.6'),
+ );
+ } finally {
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ map.dispose();
+ }
+ });
+
+ testWidgets('a URL that is not one says how to fix it, under the URL', (
+ tester,
+ ) async {
+ final app = await _apiFixture();
+ final map = MemoryKeymap();
+ try {
+ await configured.mount(tester, app, map);
+ await key(tester, LogicalKeyboardKey.keyI, cmd: true);
+ await tester.pumpAndSettle();
+ final picker = search(tester);
+ final add = picker.rows.singleWhere((row) => row.isCreate);
+ picker.move(picker.rows.indexOf(add) - picker.cursor);
+ await tester.pump();
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ await tester.tap(find.byKey(const ValueKey('api-form:provider:custom')));
+ await tester.pumpAndSettle();
+ Finder input(String id) => find.byKey(ValueKey('api-form-input:$id'));
+ await tester.enterText(input('name'), 'fdafd');
+ await tester.enterText(input('url'), 'fdfd');
+ await tester.enterText(input('key'), 'fixture-key');
+ await tester.tap(find.byKey(const ValueKey('api-form:save')));
+ await tester.pumpAndSettle();
+
+ final error = find.byKey(const ValueKey('api-form-error:url'));
+ expect(
+ tester.widget<Text>(error).data,
+ 'Enter the full URL, starting with https://, '
+ 'for example https://openrouter.ai/api/v1.',
+ );
+ // Under the URL, above the next field — and nothing was saved.
+ expect(
+ tester.getTopLeft(error).dy,
+ greaterThan(tester.getTopLeft(input('url')).dy),
+ );
+ expect(
+ tester.getTopLeft(error).dy,
+ lessThan(tester.getTopLeft(input('key')).dy),
+ );
+ expect(
+ tester.widget<TextField>(input('url')).focusNode!.hasFocus,
+ isTrue,
+ );
+ expect(find.byKey(const ValueKey('api-form:save')), findsOneWidget);
+ expect(app.listed.map((row) => row['name']), isNot(contains('fdafd')));
+ // Typing a fix takes the sentence away.
+ await tester.enterText(input('url'), 'https://relay.example.test/v1');
+ await tester.pump();
+ expect(error, findsNothing);
+ } finally {
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ map.dispose();
+ }
+ });
+
+ testWidgets('the model the pane is already on moves nothing', (tester) async {
+ final app = await _apiFixture(
+ agent: const Agent(
+ id: 'a69',
+ name: 'Current harness',
+ engine: 'claude',
+ terminalAvailable: true,
+ gridModel: 'z-ai/glm-5',
+ // What the daemon reads off Claude Code: the endpoint without `/v1`.
+ gridBaseUrl: 'https://openrouter.ai/api',
+ ),
+ );
+ final map = MemoryKeymap();
+ try {
+ await configured.mount(tester, app, map);
+ await key(tester, LogicalKeyboardKey.keyI, cmd: true);
+ await tester.pumpAndSettle();
+ await tester.enterText(field, ':glm');
+ await tester.pumpAndSettle();
+ final picker = search(tester);
+ final row = picker.rows.singleWhere(
+ (row) => row.modelId == apiModelRowId('openrouter', 'z-ai/glm-5'),
+ );
+ picker.move(picker.rows.indexOf(row) - picker.cursor);
+ await tester.pump();
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(app.moves, isEmpty);
+ expect(find.byType(SwarmSearchResults), findsNothing);
+ } finally {
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ map.dispose();
+ }
+ });
+
+ testWidgets('a harness on another computer cannot use this one’s APIs', (
+ tester,
+ ) async {
+ final app = await _apiFixture();
+ app.machineStates['other']!
+ ..connectionStatus = ConnectionStatus.connected
+ ..nodeOnline = true;
+ final map = MemoryKeymap();
+ try {
+ await configured.mount(tester, app, map);
+ await key(tester, LogicalKeyboardKey.keyI, cmd: true);
+ await tester.pumpAndSettle();
+ final picker = search(tester);
+ final row = picker
+ .models!
+ .entries[apiModelRowId('openrouter', 'z-ai/glm-5')]!
+ .destination;
+ expect(picker.canSelectModel(row), isTrue);
+ // The same list, opened for a harness on the other computer: shown, and says why not.
+ picker.setModelSelection('claude', app.inventory, machineId: 'other');
+ expect(picker.canSelectModel(row), isFalse);
- expect(picker.modelUseReason(row), 'This computer only');
++ expect(picker.modelUseReason(row), 'Other machine');
+ // And an engine the daemon cannot re-point is refused here too.
+ picker.setModelSelection(
+ 'cursor',
+ const GridModels(
+ gridName: 'home',
+ models: [],
+ localModelEngines: {'claude'},
+ ),
+ machineId: 'm',
+ );
+ expect(picker.canSelectModel(row), isFalse);
+ expect(picker.modelUseReason(row), 'Not available to this harness');
+ } finally {
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ map.dispose();
+ }
+ });
+
+ group('the words', () {
+ test('each thing wrong with an API URL has its own fix', () {
+ expect(apiUrlProblem(''), "Enter the API's URL.");
+ const full =
+ 'Enter the full URL, starting with https://, '
+ 'for example https://openrouter.ai/api/v1.';
+ expect(apiUrlProblem('fdfd'), full);
+ expect(apiUrlProblem('openrouter.ai/api/v1'), full);
+ expect(apiUrlProblem('file:///not-an-api'), full);
+ expect(
+ apiUrlProblem('https://me:[email protected]/v1'),
+ 'Take the username or password out of the URL. The key has its own field.',
+ );
+ expect(
+ apiUrlProblem('https://api.example.test/v1?key=1'),
+ 'Take the ? or # part off the end of the URL.',
+ );
+ expect(apiUrlProblem(' https://openrouter.ai/api/v1 '), isNull);
+ expect(apiUrlProblem('http://localhost:8080/v1'), isNull);
+ });
+
+ test('context windows read the way people say them', () {
+ expect(contextWindowLabel(65536), '64K');
+ expect(contextWindowLabel(131072), '128K');
+ expect(contextWindowLabel(200000), '200K');
+ expect(contextWindowLabel(1000000), '1M');
+ expect(contextWindowLabel(1048576), '1M');
+ expect(contextWindowLabel(2000000), '2M');
+ });
+
+ test('an API refusal says what the daemon said, in API terms', () {
+ expect(
+ retargetRefusalMessage(
+ 'API_UNAVAILABLE',
+ engineLabel: 'Claude Code',
+ api: true,
+ detail: 'OpenRouter did not accept the saved key.',
+ ),
+ 'OpenRouter did not accept the saved key.',
+ );
+ expect(
+ retargetRefusalMessage(
+ 'GRID_ENGINE_UNSUPPORTED',
+ engineLabel: 'Cursor',
+ api: true,
+ ),
+ 'Cursor can only run on its own login, not an API model.',
+ );
+ expect(
+ retargetRefusalMessage(
+ 'GRID_ENGINE_UNSUPPORTED',
+ engineLabel: 'Cursor',
+ ),
+ 'Cursor can only run on its own login, not a Local model.',
+ );
+ });
+
+ test('an agent is on an API model only at that API’s endpoint', () {
+ const onIt = Agent(
+ id: 'a',
+ name: 'a',
+ gridModel: 'z-ai/glm-5',
+ gridBaseUrl: 'https://openrouter.ai/api/v1',
+ );
+ expect(agentOnApiModel(onIt, openRouter, 'z-ai/glm-5'), isTrue);
+ expect(agentOnApiModel(onIt, openRouter, 'other'), isFalse);
+ const grid = Agent(
+ id: 'a',
+ name: 'a',
+ gridModel: 'z-ai/glm-5',
+ gridBaseUrl: 'https://grid.example.test/relay/v1',
+ );
+ expect(agentOnApiModel(grid, openRouter, 'z-ai/glm-5'), isFalse);
+ expect(agentOnApiModel(null, openRouter, 'z-ai/glm-5'), isFalse);
+ });
+ });
+}