The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Add API connections and an All tab to Models (#289)
Dee57d6959ced79
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.tsindex 3bdad2aa1..710a6b4e3 100644--- a/cli/src/backendSocket.ts+++ b/cli/src/backendSocket.ts@@ -34,6 +34,7 @@ import { linkCodexProfile, listCodexProfiles } from './lib/codexProfiles.js'import { gridCliPresence } from './lib/gridExec.js'import { GridFleetRpc, GRID_FLEET_PROTOCOL, GRID_FLEET_MAX_TIMEOUT_MS, parseGridFleetRequest } from './lib/gridFleetRpc.js'import { LocalModels } from './lib/localModels.js'+import { ApiConnections, apiConnectionsRequest } from './lib/apiConnections.js'import { gridCapableEngines, parseGridLaunchOverride, type GridLaunchOverride } from './lib/gridLaunch.js'import { listAllGridModels, resolveGridTarget } from './lib/gridModels.js'import { deriveHarnessGridName } from './lib/gridDerive.js'@@ -366,6 +367,7 @@ async function enrichSubagentStats(events: SessionEvent[], transcriptPath: strinexport class BackendSocket {private readonly gridFleet = new GridFleetRpc()private readonly localModels = new LocalModels({ stateDir: join(env.ADAPTER_DATA_DIR, 'local-models') })+ private readonly apiConnections = new ApiConnections(env.ADAPTER_DATA_DIR)private ws: WebSocket | null = nullprivate connecting = false/** A 401 on the upgrade is being answered with a token refresh; that refresh owns the next connect. */@@ -1502,6 +1504,12 @@ export class BackendSocket {const payload = (frame.payload ?? {}) as Record<string, unknown>const requestId = payload.requestId+ if (type === 'api_connections') {+ if (!local) { reply(type, requestId, { error: 'LOCAL_ONLY', detail: 'Manage APIs on this computer.' }); return }+ reply(type, requestId, apiConnectionsRequest(this.apiConnections, payload))+ return+ }+// Same-host only until remote viewer transport and remote task ownership exist.// Refuse before parsing project content; never send it to the relay as plaintext.if (type === 'orchestrator') {diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex 7d141d0db..5376fb9c0 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -111,6 +111,9 @@ import { DshViewerManager } from './dsh/viewer.js'import { ViewerLedger } from './dsh/viewerLedger.js'import { DshVerdictWatcher, type DshVerdict } from './dsh/verdict.js'import { dshCommand, dshUsage } from './dsh/command.js'+import { ApiConnections } from './lib/apiConnections.js'+import { apiCommand, apiUsage } from './lib/apiCommand.js'+import { prepareApiInstructions } from './lib/apiInstructions.js'import type { AgentDshContext } from './lib/agentFrame.js'import { basename } from 'node:path'import {@@ -382,6 +385,8 @@ Grid (the fleet of AI engines the \`grid\` CLI serves — needs \`grid\` on PATH${dshUsage()}+${apiUsage}+Browser end-to-end encryption:harness browser-link print a reusable 7-day setup link for browsersharness autonomous-device <command> pair/status/list/revoke an Autonomous device@@ -1283,6 +1288,12 @@ async function statBirthMs(path: string): Promise<number> {/** The daemon body: hooks + watcher + process discovery + backend socket. */async function runForeground(session: AuthSession | null): Promise<void> {installTimestampedConsole() // daemon-only: every harness.log line gets a wall-clock timestamp+ const savedApis = new ApiConnections(env.ADAPTER_DATA_DIR)+ const prepareApiTools = (cwd: string | null | undefined, engine: string): void => {+ if (!cwd) return+ try { prepareApiInstructions(savedApis, cwd, engine) }+ catch { console.warn('[apis] Tool instructions could not be added. Saved connections remain available through harness api.') }+ }const startedAt = Date.now()let discoveryReady = falselet discoveryError: string | null = null@@ -4186,8 +4197,10 @@ async function runForeground(session: AuthSession | null): Promise<void> {// Whatever the source (the row itself, or a grid override the desktop just sent), the agent's DSH,// workspace and named agent come from the row: a retarget must not silently drop the harness the// agent is, or bring a pane opened as `harness-compute` back as a general session.- const relaunchOverrides = (session: RegisteredSession, source: LaunchSource = session): Promise<LaunchOverridesResult> =>- buildLaunchOverrides(launchOverridesDeps, session.engine, { dsh: session.dsh ?? null, cwd: session.cwd, agent: session.agent ?? null, ...source }, session.agentId)+ const relaunchOverrides = (session: RegisteredSession, source: LaunchSource = session): Promise<LaunchOverridesResult> => {+ prepareApiTools(session.cwd, session.engine)+ return buildLaunchOverrides(launchOverridesDeps, session.engine, { dsh: session.dsh ?? null, cwd: session.cwd, agent: session.agent ?? null, ...source }, session.agentId)+ }/*** A restart or a post-reboot restore rebuilds the ROW's own launch, and the machine may decide@@ -4681,6 +4694,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {// answered and refused (`SPAWN_FAILED`) — see createAgentPane.ts. Registration itself is retried// there: a stale registry entry from a previous tmux-server generation occasionally collides with// a freshly-minted pane id, and that collision clears on its own on the very next pane.+ prepareApiTools(cwd, engine)// Mutually exclusive with a grid (backendSocket.ts refuses the two together): a chosen Codex// profile becomes the new session's CODEX_HOME, the same `-e` mechanism a grid's own env rides.const result = await createAndRegisterPane({@@ -4782,6 +4796,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {...(plan.level === 'native' ? { forkSessionId: plan.forkSessionId } : {}),...(firstPrompt ? { firstPrompt } : {}),}+ prepareApiTools(source.cwd, engine)const command = buildEngineCommandArgv(engine, launchOptions)const argv = buildEngineLaunchArgv(engine, launchOptions)const result = await createAndRegisterPane({@@ -6723,6 +6738,10 @@ switch (cmd) {.then((code) => { process.exitCode = code }).catch(onError)break+ case 'api':+ apiCommand(rest, new ApiConnections(env.ADAPTER_DATA_DIR))+ .then(code => { process.exitCode = code }).catch(onError)+ breakcase 'new':// `rest`, not args/flags: a first message and a folder are words in the order they were typed.newCommand({diff --git a/cli/src/lib/apiCommand.spec.ts b/cli/src/lib/apiCommand.spec.tsnew file mode 100644index 000000000..98e60efde--- /dev/null+++ b/cli/src/lib/apiCommand.spec.ts@@ -0,0 +1,111 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { existsSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'+import { createServer, type Server } from 'node:http'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { ApiConnections } from './apiConnections.js'+import { apiCommand } from './apiCommand.js'+import { prepareApiInstructions } from './apiInstructions.js'++let directory: string, store: ApiConnections, server: Server | undefined+const secret = 'fixture-key-for-local-http-only'+beforeEach(() => {+ directory = mkdtempSync(join(tmpdir(), 'harness-api-command-'))+ store = new ApiConnections(directory)+ vi.spyOn(console, 'log').mockImplementation(() => {})+ vi.spyOn(console, 'error').mockImplementation(() => {})+})+afterEach(async () => {+ if (server) { server.closeAllConnections(); await new Promise<void>(resolve => server!.close(() => resolve())); server = undefined }+ vi.restoreAllMocks()+ rmSync(directory, { recursive: true, force: true })+})++describe('API tools', () => {+ it('lists metadata, handles help/invalid commands, and never prints keys', async () => {+ expect(await apiCommand([], store)).toBe(0)+ expect(await apiCommand(['help'], store)).toBe(0)+ expect(await apiCommand(['--help'], store)).toBe(0)+ expect(await apiCommand(['list'], store)).toBe(0)+ store.save({ provider: 'fal', apiKey: secret })+ expect(await apiCommand(['list', '--json'], store)).toBe(0)+ expect(await apiCommand(['list'], store)).toBe(0)+ for (const command of [['wrong'], ['wrong', 'fal'], ['run', 'fal'], ['request', 'fal'], ['request', 'fal', 'jobs', '--wrong', 'v'], ['request', 'fal', 'jobs', '--method']]) {+ expect(await apiCommand(command, store)).toBe(1)+ }+ expect(JSON.stringify(vi.mocked(console.log).mock.calls)).not.toContain(secret)+ expect(JSON.stringify(vi.mocked(console.error).mock.calls)).not.toContain(secret)+ })++ it('gives the selected key only to a real child tool, preserves arguments and exit code', async () => {+ store.save({ provider: 'fal', apiKey: secret })+ const marker = join(directory, 'child.txt')+ const program = `require('node:fs').writeFileSync(process.argv[1], JSON.stringify({ok: process.env.FAL_KEY === '${secret}',url: process.env.HARNESS_API_BASE_URL,arg: process.argv[2]})); process.exit(7)`+ const before = process.env.FAL_KEY+ expect(await apiCommand(['run', 'fal-ai', '--', process.execPath, '-e', program, marker, 'literal $(no-shell)'], store)).toBe(7)+ expect(JSON.parse(readFileSync(marker, 'utf8'))).toEqual({ ok: true, url: 'https://queue.fal.run', arg: 'literal $(no-shell)' })+ expect(process.env.FAL_KEY).toBe(before)+ expect(await apiCommand(['run', 'fal-ai', '--', '/nonexistent-fixture-command'], store)).toBe(1)+ expect(await apiCommand(['run', 'missing', '--', process.execPath], store)).toBe(1)+ })++ it('makes a real authenticated HTTP call, supports JSON files, and reports provider rejection', async () => {+ const requests: { url: string; key: string; body: string; method: string }[] = []+ server = createServer(async (request, response) => {+ let body = ''; for await (const chunk of request) body += chunk+ requests.push({ url: request.url!, key: request.headers['x-api-key'] as string, body, method: request.method! })+ response.writeHead(request.url === '/v1/denied' ? 401 : 200, { 'Content-Type': 'application/json' })+ response.end('{"answer":"fixture"}')+ })+ await new Promise<void>((resolve, reject) => { server!.once('error', reject); server!.listen(0, '127.0.0.1', resolve) })+ const port = (server.address() as { port: number }).port+ store.save({ provider: 'custom', name: 'Fixture', baseUrl: `http://127.0.0.1:${port}/v1`, apiKey: secret, authHeader: 'x-api-key', authPrefix: '' })+ const body = join(directory, 'request.json'); writeFileSync(body, '{"prompt":"hello"}')+ expect(await apiCommand(['request', 'fixture', 'generate', '--method', 'POST', '--data', '@' + body], store)).toBe(0)+ expect(requests[0]).toEqual({ url: '/v1/generate', key: secret, body: '{"prompt":"hello"}', method: 'POST' })+ expect(await apiCommand(['request', 'fixture', 'generate', '--method', 'POST', '--data', '{"inline":true}'], store)).toBe(0)+ expect(requests[1].body).toBe('{"inline":true}')+ expect(await apiCommand(['request', 'fixture', 'denied'], store)).toBe(1)+ expect(await apiCommand(['request', 'fixture', 'generate', '--method', 'TRACE'], store)).toBe(1)+ expect(await apiCommand(['request', 'fixture', 'generate', '--data', '{}'], store)).toBe(1)+ expect(await apiCommand(['request', 'fixture', 'generate', '--method', 'POST', '--data', '@/missing-file-fixture'], store)).toBe(1)+ expect(JSON.stringify(vi.mocked(console.log).mock.calls)).not.toContain(secret)+ })++ it('does not follow redirects or print network errors containing credentials', async () => {+ server = createServer((_request, response) => { response.writeHead(302, { Location: 'http://127.0.0.1:1/steal' }); response.end() })+ await new Promise<void>((resolve, reject) => { server!.once('error', reject); server!.listen(0, '127.0.0.1', resolve) })+ const port = (server.address() as { port: number }).port+ store.save({ provider: 'custom', name: 'Redirect', baseUrl: `http://127.0.0.1:${port}`, apiKey: secret })+ expect(await apiCommand(['request', 'redirect', ''], store)).toBe(1)+ vi.spyOn(globalThis, 'fetch').mockRejectedValue(new Error(secret))+ expect(await apiCommand(['request', 'redirect', ''], store)).toBe(1)+ expect(JSON.stringify(vi.mocked(console.error).mock.calls)).not.toContain(secret)+ })++ it.each(['codex', 'claude', 'gemini'])('makes API tools discoverable in %s without keys or replacing existing instructions', engine => {+ prepareApiInstructions(store, directory, engine)+ store.save({ provider: 'fal', apiKey: secret })+ const file = join(directory, engine === 'claude' ? 'CLAUDE.md' : engine === 'gemini' ? 'GEMINI.md' : 'AGENTS.md')+ writeFileSync(file, '# My project\nKeep these instructions.\n')+ prepareApiInstructions(store, directory, engine)+ prepareApiInstructions(store, directory, engine)+ const text = readFileSync(file, 'utf8')+ expect(text).toContain('# My project\nKeep these instructions.')+ expect(text.split('<!-- harness:apis -->')).toHaveLength(2)+ expect(text).toContain('harness api run')+ expect(text).not.toContain(secret)+ })++ it('creates instructions only when needed and leaves terminal and symlinked instruction files alone', () => {+ store.save({ provider: 'fal', apiKey: secret })+ prepareApiInstructions(store, directory, 'terminal')+ expect(existsSync(join(directory, 'AGENTS.md'))).toBe(false)+ prepareApiInstructions(store, directory, 'codex')+ expect(readFileSync(join(directory, 'AGENTS.md'), 'utf8')).toContain('harness api list')+ const target = join(directory, 'my-instructions.md'); writeFileSync(target, 'Preserve me')+ symlinkSync(target, join(directory, 'CLAUDE.md'))+ prepareApiInstructions(store, directory, 'claude')+ expect(readFileSync(target, 'utf8')).toBe('Preserve me')+ })+})diff --git a/cli/src/lib/apiCommand.ts b/cli/src/lib/apiCommand.tsnew file mode 100644index 000000000..9e70c75ec--- /dev/null+++ b/cli/src/lib/apiCommand.ts@@ -0,0 +1,61 @@+import { spawn } from 'node:child_process'+import { readFileSync } from 'node:fs'+import { ApiConnectionError, ApiConnections } from './apiConnections.js'++export const apiUsage = `Saved APIs (Models → APIs):+ harness api list [--json] list connections, never keys+ harness api request <id> <path> [--method POST] [--data @file.json]+ call an API with its saved authentication+ harness api run <id> -- <command> [args] give one tool its API key environment variable+ and HARNESS_API_BASE_URL; no engine login changes`++export async function apiCommand(argv: readonly string[], store: ApiConnections): Promise<number> {+ try {+ const [verb, connectionId, ...rest] = argv+ if (!verb || verb === 'help' || verb === '--help') { console.log(apiUsage); return 0 }+ if (verb === 'list') {+ const connections = store.list()+ console.log(argv.includes('--json') ? JSON.stringify(connections) : connections.length+ ? connections.map(row => `${row.id} · ${row.name} · ${row.baseUrl}`).join('\n')+ : 'No saved APIs. Add one in Models → APIs.')+ return 0+ }+ if (!connectionId) throw new ApiConnectionError(apiUsage)+ if (verb === 'run') {+ if (rest[0] !== '--' || !rest[1]) throw new ApiConnectionError(apiUsage)+ const environment = store.toolEnvironment(connectionId)+ return await new Promise<number>(resolve => {+ const child = spawn(rest[1], rest.slice(2), { stdio: 'inherit', env: { ...process.env, ...environment }, shell: false })+ child.once('error', () => { console.error('The API tool could not start. Check its command.'); resolve(1) })+ child.once('close', code => resolve(code ?? 1))+ })+ }+ if (verb === 'request') {+ const [path, ...flags] = rest+ if (path === undefined) throw new ApiConnectionError(apiUsage)+ let method = 'GET', body: string | undefined+ for (let at = 0; at < flags.length; at += 2) {+ const value = flags[at + 1]+ if (!value) throw new ApiConnectionError(apiUsage)+ if (flags[at] === '--method') method = value.toUpperCase()+ else if (flags[at] === '--data') body = value.startsWith('@') ? readFileSync(value.slice(1), 'utf8') : value+ else throw new ApiConnectionError(apiUsage)+ }+ if (!['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'].includes(method) || (body !== undefined && ['GET', 'HEAD'].includes(method))) {+ throw new ApiConnectionError('Choose an HTTP method that supports this request.')+ }+ const config = store.requestConfig(connectionId, path)+ const response = await fetch(config.url, {+ method, body, headers: { ...config.headers, ...(body !== undefined ? { 'Content-Type': 'application/json' } : {}) },+ redirect: 'error', signal: AbortSignal.timeout(120_000),+ })+ console.log(await response.text())+ if (!response.ok) console.error(`API request failed (HTTP ${response.status}).`)+ return response.ok ? 0 : 1+ }+ throw new ApiConnectionError(apiUsage)+ } catch (error) {+ console.error(error instanceof ApiConnectionError ? error.message : 'The API request could not finish. Check the connection and try again.')+ return 1+ }+}diff --git a/cli/src/lib/apiConnections.spec.ts b/cli/src/lib/apiConnections.spec.tsnew file mode 100644index 000000000..24632c29e--- /dev/null+++ b/cli/src/lib/apiConnections.spec.ts@@ -0,0 +1,174 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { mkdtempSync, readFileSync, rmSync, statSync, symlinkSync, writeFileSync, mkdirSync } from 'node:fs'+import * as fs from 'node:fs'+import * as crypto from 'node:crypto'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { API_PRESETS, ApiConnections, apiConnectionsRequest } from './apiConnections.js'+import { encryptDownFrame, encryptRpcResult } from './e2ee/applicationFrames.js'++vi.mock('node:fs', async importOriginal => {+ const actual = await importOriginal<typeof import('node:fs')>()+ return { ...actual, renameSync: vi.fn(actual.renameSync), fsyncSync: vi.fn(actual.fsyncSync) }+})+vi.mock('node:crypto', async importOriginal => {+ const actual = await importOriginal<typeof import('node:crypto')>()+ return { ...actual, randomUUID: vi.fn(actual.randomUUID) }+})++let directory: string, store: ApiConnections+const secret = 'fixture-private-credential-never-in-metadata'+const custom = { provider: 'custom', name: 'My images', baseUrl: 'https://images.example.test/v2', apiKey: secret }+beforeEach(() => { directory = mkdtempSync(join(tmpdir(), 'harness-api-store-')); store = new ApiConnections(directory) })+afterEach(() => { vi.restoreAllMocks(); rmSync(directory, { recursive: true, force: true }) })++describe('saved API connections', () => {+ it('lists empty storage and presets without creating a file or calling any API', () => {+ expect(store.list()).toEqual([])+ const result = apiConnectionsRequest(store, { action: 'list' })+ expect(result).toEqual({ connections: [], presets: API_PRESETS })+ expect(API_PRESETS.map(row => row.provider)).toEqual(['openrouter', 'fal', 'openai', 'anthropic', 'replicate'])+ expect(encryptDownFrame('api_connections')).toBe(true)+ expect(encryptRpcResult('api_connections_result')).toBe(true)+ })++ it.each(API_PRESETS)('saves $name with its default authentication and returns no credential', preset => {+ const connection = store.save({ provider: preset.provider, apiKey: ` ${secret} ` })+ expect(connection).toMatchObject({ name: preset.name, baseUrl: preset.baseUrl, keyEnv: preset.keyEnv })+ expect(JSON.stringify(store.list())).not.toContain(secret)+ expect(JSON.stringify(connection)).not.toContain('apiKey')+ const environment = store.toolEnvironment(connection.id)+ expect(environment).toEqual({ [preset.keyEnv]: secret, HARNESS_API_BASE_URL: preset.baseUrl })+ const request = store.requestConfig(connection.id, '/models?limit=2')+ expect(request.url.toString()).toBe(`${preset.baseUrl}/models?limit=2`)+ expect(request.headers[preset.authHeader]).toBe(`${preset.authPrefix ? preset.authPrefix + ' ' : ''}${secret}`)+ if (preset.provider === 'anthropic') expect(request.headers['anthropic-version']).toBe('2023-06-01')+ })++ it('supports any named API, a custom header, no prefix, and explicit SDK environment variable', () => {+ const saved = store.save({ ...custom, authHeader: 'x-vendor-key', authPrefix: '', keyEnv: 'VENDOR_TOKEN' })+ expect(saved.id).toBe('my-images')+ expect(store.requestConfig(saved.id, 'render').headers).toEqual({ 'x-vendor-key': secret })+ expect(store.toolEnvironment(saved.id).VENDOR_TOKEN).toBe(secret)+ expect(new ApiConnections(directory).list()).toEqual([saved])+ })++ it('keeps the key on edit, can rotate it, preserves the id, and removes without exposing it', () => {+ const saved = store.save(custom)+ const edited = store.save({ ...saved, name: 'Work images', apiKey: '' })+ expect(edited.id).toBe(saved.id)+ expect(store.toolEnvironment(saved.id).MY_IMAGES_API_KEY).toBe(secret)+ store.save({ ...edited, apiKey: 'rotated-fixture-key' })+ expect(store.toolEnvironment(saved.id).MY_IMAGES_API_KEY).toBe('rotated-fixture-key')+ store.remove(saved.id)+ store.remove(saved.id)+ expect(store.list()).toEqual([])+ expect(() => store.toolEnvironment(saved.id)).toThrow('not saved')+ expect(() => store.save({ ...saved, apiKey: secret })).toThrow('was removed')+ })++ it('keeps multiple connections for one provider and refuses duplicate names', () => {+ store.save({ provider: 'openrouter', apiKey: secret })+ store.save({ provider: 'openrouter', name: 'OpenRouter Work', apiKey: 'second-private-key' })+ expect(store.list()).toHaveLength(2)+ expect(() => store.save({ provider: 'openrouter', name: 'OPENROUTER', apiKey: secret })).toThrow('already exists')+ expect(() => store.save({ ...custom, name: 'OpenRouter!' })).toThrow('already exists')+ })++ it('writes owner-only credentials atomically outside the project', () => {+ store.save(custom)+ const path = join(directory, 'api-connections', 'connections.json')+ expect(statSync(path).mode & 0o777).toBe(0o600)+ expect(statSync(join(directory, 'api-connections')).mode & 0o777).toBe(0o700)+ expect(JSON.parse(readFileSync(path, 'utf8')).connections[0].apiKey).toBe(secret)+ store.save({ ...store.list()[0], apiKey: 'new-key' })+ expect(statSync(path).mode & 0o777).toBe(0o600)+ })++ it.each([+ { name: '' }, { name: 'has\na newline' }, { provider: 'not-a-preset' }, { name: '🧠' },+ { baseUrl: 'not-a-url' }, { baseUrl: 'file:///tmp/private' },+ { baseUrl: 'https://user:[email protected]' }, { baseUrl: 'https://api.test?key=private' },+ { baseUrl: 'https://api.test/#private' }, { apiKey: '' }, { apiKey: 'line\nbreak' },+ { apiKey: 'a'.repeat(8193) }, { keyEnv: 'NODE_OPTIONS' }, { keyEnv: 'PATH' },+ { keyEnv: 'LD_PRELOAD' }, { keyEnv: 'DYLD_INSERT_LIBRARIES' }, { keyEnv: 'bad-name' },+ { authHeader: 'Host' }, { authHeader: 'Content-Length' }, { authHeader: 'x-key\r\nevil' },+ { authPrefix: 'Bearer\nevil' }, { authPrefix: 'a'.repeat(41) },+ ])('rejects malformed connection settings without saving anything: %j', fields => {+ const result = apiConnectionsRequest(store, { action: 'save', connection: { ...custom, ...fields } })+ expect(result.error).toBe('API_CONNECTIONS_FAILED')+ expect(JSON.stringify(result)).not.toContain(secret)+ expect(store.list()).toEqual([])+ })++ it.each(['https://other.test/steal', '//other.test/steal', 'file:///tmp/key'])('refuses a request to another endpoint: %s', path => {+ const saved = store.save(custom)+ expect(() => store.requestConfig(saved.id, path)).toThrow('relative')+ })++ it('refuses a corrupt store instead of overwriting saved credentials', () => {+ store.save(custom)+ const path = join(directory, 'api-connections', 'connections.json')+ const original = '{broken' + secret+ writeFileSync(path, original)+ expect(apiConnectionsRequest(store, { action: 'save', connection: custom })).toEqual({+ error: 'API_CONNECTIONS_FAILED', detail: 'Saved APIs could not be read. Your keys have not been changed.',+ })+ expect(readFileSync(path, 'utf8')).toBe(original)+ })++ it('refuses symlinked credential storage', () => {+ const target = join(directory, 'outside'); mkdirSync(target)+ symlinkSync(target, join(directory, 'api-connections'))+ expect(() => store.save(custom)).toThrow('could not be read')+ })++ it('keeps the old credentials after failed writes and cleans up only its own temporary file', () => {+ store.save(custom)+ const previous = readFileSync(join(directory, 'api-connections', 'connections.json'), 'utf8')+ vi.mocked(fs.renameSync).mockImplementationOnce(() => { throw new Error(secret) })+ expect(() => store.save({ ...store.list()[0], apiKey: 'new-key' })).toThrow('could not be saved')+ expect(readFileSync(join(directory, 'api-connections', 'connections.json'), 'utf8')).toBe(previous)+ expect(fs.readdirSync(join(directory, 'api-connections'))).toEqual(['connections.json'])+ vi.mocked(fs.fsyncSync).mockImplementationOnce(() => { throw new Error(secret) })+ expect(() => store.save({ ...store.list()[0], apiKey: 'new-key' })).toThrow('could not be saved')+ expect(readFileSync(join(directory, 'api-connections', 'connections.json'), 'utf8')).toBe(previous)+ const uuid = '00000000-0000-4000-8000-000000000000'+ vi.mocked(crypto.randomUUID).mockReturnValueOnce(uuid)+ const collision = join(directory, 'api-connections', `.connections-${uuid}.tmp`)+ writeFileSync(collision, 'another operation owns this file')+ expect(() => store.save({ ...store.list()[0], apiKey: 'new-key' })).toThrow('could not be saved')+ expect(readFileSync(collision, 'utf8')).toBe('another operation owns this file')+ })++ it('refuses non-files, duplicate stored ids, oversized storage and too many connections', () => {+ mkdirSync(join(directory, 'api-connections'))+ expect(store.list()).toEqual([])+ const path = join(directory, 'api-connections', 'connections.json')+ mkdirSync(path)+ expect(() => store.list()).toThrow('could not be read')+ rmSync(path, { recursive: true })+ writeFileSync(path, 'x'.repeat(2 * 1024 * 1024 + 1))+ expect(() => store.list()).toThrow('could not be read')+ rmSync(path)+ store.save(custom)+ const row = JSON.parse(readFileSync(path, 'utf8')).connections[0]+ writeFileSync(path, JSON.stringify({ version: 1, connections: [row, row] }))+ expect(() => store.list()).toThrow('could not be read')+ writeFileSync(path, JSON.stringify({ version: 1, connections: Array.from({ length: 100 }, (_, n) => ({ ...row, id: `api-${n}`, name: `API ${n}` })) }))+ expect(() => store.save(custom)).toThrow('Remove an API')+ expect(store.list()).toHaveLength(100)+ })++ it('sanitizes RPC failures, validates actions, and returns the updated list on save/remove', () => {+ expect(apiConnectionsRequest(store, { action: 'save', connection: [] }).error).toBeTruthy()+ expect(apiConnectionsRequest(store, { action: 'save' }).error).toBeTruthy()+ expect(apiConnectionsRequest(store, { action: 'unknown' }).error).toBeTruthy()+ expect(apiConnectionsRequest(store, { action: 'remove', id: '../private' }).error).toBeTruthy()+ expect(apiConnectionsRequest(store, { action: 'save', connection: custom }).connections).toHaveLength(1)+ expect(apiConnectionsRequest(store, { action: 'remove', id: 'my-images' }).connections).toEqual([])+ vi.spyOn(store, 'list').mockImplementation(() => { throw new Error(secret) })+ const failed = apiConnectionsRequest(store, { action: 'list' })+ expect(failed).toEqual({ error: 'API_CONNECTIONS_FAILED', detail: 'APIs are unavailable. Try again.' })+ })+})diff --git a/cli/src/lib/apiConnections.ts b/cli/src/lib/apiConnections.tsnew file mode 100644index 000000000..c4ba55aa5--- /dev/null+++ b/cli/src/lib/apiConnections.ts@@ -0,0 +1,160 @@+/** Machine-local API connections. Only child tools receive credentials; model/subscription+ * selection and the daemon's own environment are never changed by saving a key. */+import { chmodSync, closeSync, existsSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'+import { join } from 'node:path'+import { randomUUID } from 'node:crypto'+import { z } from 'zod'++const text = z.string().trim().min(1).max(120).regex(/^[^\x00-\x1f\x7f]+$/)+const id = z.string().regex(/^[a-z0-9][a-z0-9-]{0,63}$/)+const environmentName = z.string().regex(/^[A-Z][A-Z0-9_]{0,79}$/).refine(+ value => !/^(PATH|HOME|SHELL|ENV|BASH_ENV|ZDOTDIR|NODE_OPTIONS|LD_.+|DYLD_.+|HARNESS_.+)$/.test(value),+)+const baseUrl = z.string().max(2048).url().refine(value => {+ const url = new URL(value)+ return ['https:', 'http:'].includes(url.protocol) && !url.username && !url.password && !url.search && !url.hash+})+const metadata = z.object({+ id,+ provider: id,+ name: text,+ baseUrl,+ keyEnv: environmentName,+ authHeader: z.string().regex(/^[A-Za-z][A-Za-z0-9-]{0,79}$/).refine(value =>+ !['host', 'content-length', 'connection', 'transfer-encoding', 'cookie'].includes(value.toLowerCase())),+ authPrefix: z.string().trim().max(40).regex(/^[A-Za-z0-9_-]*$/),+})+const stored = metadata.extend({ apiKey: z.string().trim().min(1).max(8192).regex(/^[^\s\x00-\x1f\x7f]+$/) })+const storeSchema = z.object({ version: z.literal(1), connections: z.array(stored).max(100) })+export type ApiConnection = z.infer<typeof metadata>+type StoredConnection = z.infer<typeof stored>+export type ApiPreset = Omit<ApiConnection, 'id'> & { keyUrl: string; docsUrl: string }++/** Defaults verified against each provider's public authentication docs. Custom APIs use the+ * same store and execution path; presets are conveniences, never a provider allowlist. */+export const API_PRESETS: ApiPreset[] = [+ { provider: 'openrouter', name: 'OpenRouter', baseUrl: 'https://openrouter.ai/api/v1', keyEnv: 'OPENROUTER_API_KEY', authHeader: 'Authorization', authPrefix: 'Bearer', keyUrl: 'https://openrouter.ai/settings/keys', docsUrl: 'https://openrouter.ai/docs/api/reference/authentication' },+ { provider: 'fal', name: 'fal.ai', baseUrl: 'https://queue.fal.run', keyEnv: 'FAL_KEY', authHeader: 'Authorization', authPrefix: 'Key', keyUrl: 'https://fal.ai/dashboard/keys', docsUrl: 'https://fal.ai/docs' },+ { provider: 'openai', name: 'OpenAI', baseUrl: 'https://api.openai.com/v1', keyEnv: 'OPENAI_API_KEY', authHeader: 'Authorization', authPrefix: 'Bearer', keyUrl: 'https://platform.openai.com/api-keys', docsUrl: 'https://developers.openai.com/api/reference/overview' },+ { provider: 'anthropic', name: 'Anthropic', baseUrl: 'https://api.anthropic.com/v1', keyEnv: 'ANTHROPIC_API_KEY', authHeader: 'x-api-key', authPrefix: '', keyUrl: 'https://platform.claude.com/settings/keys', docsUrl: 'https://platform.claude.com/docs/en/api/overview' },+ { provider: 'replicate', name: 'Replicate', baseUrl: 'https://api.replicate.com/v1', keyEnv: 'REPLICATE_API_TOKEN', authHeader: 'Authorization', authPrefix: 'Bearer', keyUrl: 'https://replicate.com/account/api-tokens', docsUrl: 'https://replicate.com/docs/topics/security/api-tokens' },+]++export class ApiConnectionError extends Error {}+const message = (value: string): never => { throw new ApiConnectionError(value) }+const publicConnection = (value: StoredConnection): ApiConnection => metadata.parse(value)++export class ApiConnections {+ private readonly dir: string+ private readonly file: string+ constructor(dataDir: string) {+ this.dir = join(dataDir, 'api-connections')+ this.file = join(this.dir, 'connections.json')+ }++ private read(): StoredConnection[] {+ try {+ if (!existsSync(this.dir)) return []+ if (!lstatSync(this.dir).isDirectory() || lstatSync(this.dir).isSymbolicLink()) throw new Error()+ if (!existsSync(this.file)) return []+ const stat = lstatSync(this.file)+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 2 * 1024 * 1024) throw new Error()+ const parsed = storeSchema.parse(JSON.parse(readFileSync(this.file, 'utf8'))).connections+ if (new Set(parsed.map(row => row.id)).size !== parsed.length) throw new Error()+ return parsed+ } catch { return message('Saved APIs could not be read. Your keys have not been changed.') }+ }++ private write(connections: StoredConnection[]): void {+ const temporary = join(this.dir, `.connections-${randomUUID()}.tmp`)+ let fd: number | undefined+ let created = false+ try {+ mkdirSync(this.dir, { recursive: true, mode: 0o700 })+ if (lstatSync(this.dir).isSymbolicLink()) throw new Error()+ chmodSync(this.dir, 0o700)+ fd = openSync(temporary, 'wx', 0o600)+ created = true+ writeFileSync(fd, JSON.stringify({ version: 1, connections }))+ fsyncSync(fd)+ closeSync(fd)+ fd = undefined+ renameSync(temporary, this.file)+ } catch { message('This API could not be saved. Try again.') }+ finally {+ if (fd !== undefined) closeSync(fd)+ if (created) rmSync(temporary, { force: true })+ }+ }++ list(): ApiConnection[] { return this.read().map(publicConnection) }++ save(input: Record<string, unknown>): ApiConnection {+ const connections = this.read()+ const previous = input.id === undefined ? undefined : connections.find(row => row.id === input.id)+ if (input.id !== undefined && !previous) return message('This API was removed. Add it again.')+ const preset = API_PRESETS.find(row => row.provider === input.provider)+ if (input.provider !== 'custom' && !preset) return message('Choose an API or Custom API.')+ const name = typeof input.name === 'string' ? input.name.trim() : preset?.name ?? ''+ const slug = name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 64)+ const parsed = stored.safeParse({+ ...preset, ...previous, ...input,+ id: previous?.id ?? slug,+ name,+ baseUrl: typeof input.baseUrl === 'string' ? input.baseUrl.trim().replace(/\/+$/, '') : preset?.baseUrl,+ keyEnv: input.keyEnv || preset?.keyEnv || `${slug.replace(/-/g, '_').toUpperCase()}_API_KEY`,+ authHeader: input.authHeader ?? preset?.authHeader ?? 'Authorization',+ authPrefix: input.authPrefix ?? preset?.authPrefix ?? 'Bearer',+ apiKey: typeof input.apiKey === 'string' && input.apiKey.trim() ? input.apiKey.trim() : previous?.apiKey,+ })+ if (!parsed.success) return message('Check the name, URL, key, and authentication settings.')+ const value = parsed.data+ if (connections.some(row => row.id !== previous?.id && (row.id === value.id || row.name.toLowerCase() === value.name.toLowerCase()))) {+ return message('An API with this name already exists. Choose another name.')+ }+ if (!previous && connections.length >= 100) return message('Remove an API before adding another.')+ this.write(previous ? connections.map(row => row.id === value.id ? value : row) : [...connections, value])+ return publicConnection(value)+ }++ remove(connectionId: unknown): void {+ if (!id.safeParse(connectionId).success) return message('Choose a saved API.')+ this.write(this.read().filter(row => row.id !== connectionId))+ }++ private connection(connectionId: string): StoredConnection {+ return this.read().find(row => row.id === connectionId) ?? message('This API is not saved. Add it in Models → APIs.')+ }++ /** Never merge this into an agent's global environment: a vendor key can override its subscription.+ * It belongs ONLY to the explicitly requested tool process (harness api run). */+ toolEnvironment(connectionId: string): Record<string, string> {+ const connection = this.connection(connectionId)+ return { [connection.keyEnv]: connection.apiKey, HARNESS_API_BASE_URL: connection.baseUrl }+ }++ requestConfig(connectionId: string, path: string): { url: URL; headers: Record<string, string> } {+ const connection = this.connection(connectionId)+ if (/^[a-z][a-z0-9+.-]*:|^\/\//i.test(path)) return message('Use a path relative to this API.')+ const url = new URL(`${connection.baseUrl.replace(/\/+$/, '')}/${path.replace(/^\/+/, '')}`)+ if (url.origin !== new URL(connection.baseUrl).origin || url.username || url.password) return message('Use a path relative to this API.')+ return { url, headers: {+ [connection.authHeader]: `${connection.authPrefix ? `${connection.authPrefix} ` : ''}${connection.apiKey}`,+ ...(connection.provider === 'anthropic' ? { 'anthropic-version': '2023-06-01' } : {}),+ } }+ }+}++/** No credentials in replies, including validation, filesystem and unexpected failures. */+export function apiConnectionsRequest(store: ApiConnections, payload: Record<string, unknown>): Record<string, unknown> {+ try {+ if (payload.action === 'save') {+ if (!payload.connection || typeof payload.connection !== 'object' || Array.isArray(payload.connection)) return { error: 'API_CONNECTIONS_FAILED', detail: 'Choose an API to save.' }+ store.save(payload.connection as Record<string, unknown>)+ } else if (payload.action === 'remove') store.remove(payload.id)+ else if (payload.action !== 'list') return { error: 'API_CONNECTIONS_FAILED', detail: 'Choose an API action.' }+ return { connections: store.list(), presets: API_PRESETS }+ } catch (error) {+ return { error: 'API_CONNECTIONS_FAILED', detail: error instanceof ApiConnectionError ? error.message : 'APIs are unavailable. Try again.' }+ }+}diff --git a/cli/src/lib/apiConnectionsRpc.spec.ts b/cli/src/lib/apiConnectionsRpc.spec.tsnew file mode 100644index 000000000..839b5a6bb--- /dev/null+++ b/cli/src/lib/apiConnectionsRpc.spec.ts@@ -0,0 +1,47 @@+import { afterEach, describe, expect, it, vi } from 'vitest'+import { BackendSocket } from '../backendSocket.js'+import { ApiConnections } from './apiConnections.js'++afterEach(() => vi.restoreAllMocks())+describe('API connection RPC', () => {+ it.each(['list', 'save', 'remove'])('handles local %s and returns only public metadata', async action => {+ const socket = new BackendSocket('fixture')+ const frames: any[] = []+ socket.registerLocalClient('local:apis', { sendFrame: frame => { frames.push(frame); return true }, sendBinary: () => true })+ vi.spyOn(ApiConnections.prototype, 'list').mockReturnValue([])+ const save = vi.spyOn(ApiConnections.prototype, 'save').mockReturnValue({ id: 'fixture' } as any)+ const remove = vi.spyOn(ApiConnections.prototype, 'remove').mockImplementation(() => {})+ socket.handleLocalFrame('local:apis', { type: 'api_connections', payload: { requestId: 'fixture-request', action, id: 'fixture', connection: { provider: 'fal', apiKey: 'private-fixture-key' } } })+ await vi.waitFor(() => expect(frames.some(frame => frame.type === 'api_connections_result')).toBe(true))+ const result = frames.find(frame => frame.type === 'api_connections_result')+ expect(result.payload).toMatchObject({ requestId: 'fixture-request', connections: [] })+ expect(JSON.stringify(result)).not.toContain('private-fixture-key')+ if (action === 'save') expect(save).toHaveBeenCalledWith({ provider: 'fal', apiKey: 'private-fixture-key' })+ if (action === 'remove') expect(remove).toHaveBeenCalledWith('fixture')+ await socket.stop()+ })++ it('refuses remote access before touching the credential store', async () => {+ const socket = new BackendSocket('fixture')+ const list = vi.spyOn(ApiConnections.prototype, 'list')+ const save = vi.spyOn(ApiConnections.prototype, 'save')+ await (socket as any).dispatchDown({ type: 'api_connections', payload: { action: 'list', requestId: 'remote' } }, 'remote')+ await (socket as any).dispatchDown({ type: 'api_connections', payload: { action: 'save', requestId: 'remote', connection: { apiKey: 'must-not-persist' } } }, 'remote')+ expect(list).not.toHaveBeenCalled()+ expect(save).not.toHaveBeenCalled()+ await socket.stop()+ })++ it('refuses authenticated encrypted remote management too', async () => {+ const socket = new BackendSocket('fixture')+ const save = vi.spyOn(ApiConnections.prototype, 'save')+ const reply = vi.spyOn(socket as any, 'emitReply').mockImplementation(() => {})+ vi.spyOn((socket as any).e2ee, 'unwrapDown').mockReturnValue({+ type: 'api_connections', payload: { action: 'save', requestId: 'remote', connection: { provider: 'fal', apiKey: 'must-stay-local' } },+ })+ await (socket as any).dispatchDown({ type: 'api_connections', payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'fixture' } } }, 'remote')+ expect(save).not.toHaveBeenCalled()+ expect(reply).toHaveBeenCalledWith('remote', 'api_connections', 'remote', { error: 'LOCAL_ONLY', detail: 'Manage APIs on this computer.' })+ await socket.stop()+ })+})diff --git a/cli/src/lib/apiInstructions.ts b/cli/src/lib/apiInstructions.tsnew file mode 100644index 000000000..f4c64fdf6--- /dev/null+++ b/cli/src/lib/apiInstructions.ts@@ -0,0 +1,28 @@+/** Discoverable tool access, without copying credentials or model settings into projects. */+import { existsSync, lstatSync, readFileSync, writeFileSync } from 'node:fs'+import { join } from 'node:path'+import type { ApiConnections } from './apiConnections.js'++const marker = '<!-- harness:apis -->'+export const API_INSTRUCTIONS = `${marker}+## Saved APIs++The user can save API connections in Harness → Models → APIs on this computer.+Run \`harness api list --json\` to discover the current connections; the list contains no keys.+Use \`harness api request <id> <path> --method POST --data @request.json\` for JSON APIs,+or \`harness api run <id> -- <command> [args]\` for a provider SDK/tool. The latter supplies+the connection's documented key variable and HARNESS_API_BASE_URL to that tool only.+Use these APIs when needed for the user's task. Never print, paste, or save API keys in a project.+Adding an API does not change this harness's model or subscription.+`++/** Only Harness-created workspaces with saved APIs. Existing instructions are kept;+ * no global agent settings or credentials are written into the project. */+export function prepareApiInstructions(store: ApiConnections, workspace: string, engine: string): void {+ if (engine === 'terminal' || !store.list().length) return+ const name = engine === 'claude' ? 'CLAUDE.md' : engine === 'gemini' ? 'GEMINI.md' : 'AGENTS.md'+ const file = join(workspace, name)+ if (existsSync(file) && (!lstatSync(file).isFile() || lstatSync(file).isSymbolicLink())) return+ const previous = existsSync(file) ? readFileSync(file, 'utf8') : ''+ if (!previous.includes(marker)) writeFileSync(file, `${previous.trimEnd()}${previous ? '\n\n' : ''}${API_INSTRUCTIONS}`)+}diff --git a/cli/src/lib/e2ee/applicationFrames.ts b/cli/src/lib/e2ee/applicationFrames.tsindex ab9fa78f0..e225ffc36 100644--- a/cli/src/lib/e2ee/applicationFrames.ts+++ b/cli/src/lib/e2ee/applicationFrames.ts@@ -14,7 +14,7 @@ import { VIEWER_DOWN_TYPES } from '../viewerWire.js'const FLEET_REQUESTS = new Set(['grid_fleet_capabilities', 'grid_fleet_run', 'grid_fleet_cancel','grid_fleet_models_list', 'grid_fleet_model_start', 'grid_fleet_model_stop'])const FLEET_RESULTS = new Set([...FLEET_REQUESTS].map(type => `${type}_result`))-const MACHINE_REQUESTS = new Set(['git_project_info', 'git_pull_request', 'machine_resources'])+const MACHINE_REQUESTS = new Set(['git_project_info', 'git_pull_request', 'machine_resources', 'api_connections'])const MACHINE_RESULTS = new Set([...MACHINE_REQUESTS].map(type => `${type}_result`))export const encryptDownFrame = (type: string): boolean =>isEncryptedDownType(type) || MACHINE_REQUESTS.has(type) || FLEET_REQUESTS.has(type) || SHARE_REQUEST_TYPES.has(type) || VIEWER_DOWN_TYPES.has(type)diff --git a/desktop/lib/models/api_connections_controller.dart b/desktop/lib/models/api_connections_controller.dartnew file mode 100644index 000000000..f3add784e--- /dev/null+++ b/desktop/lib/models/api_connections_controller.dart@@ -0,0 +1,151 @@+import 'dart:async';++import 'package:flutter/foundation.dart';++import '../core/models.dart';+import '../state/app_state.dart';+import '../ws/ws_conn.dart';++/// The desktop retains public metadata only. Keys travel once to the local CLI;+/// replies, preferences, and provider rows never contain them.+class ApiConnection {+ const ApiConnection(this.data);+ final Map<String, dynamic> data;+ String get id => data['id'] as String? ?? '';+ String get provider => data['provider'] as String? ?? 'custom';+ String get name => data['name'] as String? ?? '';+ String get baseUrl => data['baseUrl'] as String? ?? '';+ String get host => Uri.tryParse(baseUrl)?.host ?? baseUrl;+ String get keyEnv => data['keyEnv'] as String? ?? '';+ String get authHeader => data['authHeader'] as String? ?? 'Authorization';+ String get authPrefix => data['authPrefix'] as String? ?? 'Bearer';+ String? get keyUrl => data['keyUrl'] as String?;+ bool matches(String query) =>+ '$name $baseUrl'.toLowerCase().contains(query.toLowerCase());++ factory ApiConnection.fromJson(Map<String, dynamic> json) => ApiConnection({+ for (final key in [+ 'id',+ 'provider',+ 'name',+ 'baseUrl',+ 'keyEnv',+ 'authHeader',+ 'authPrefix',+ 'keyUrl',+ 'docsUrl',+ ])+ if (json[key] is String) key: json[key],+ });+}++class ApiConnectionsController extends ChangeNotifier {+ ApiConnectionsController(this.app) {+ app.addListener(_observe);+ _owner = app.localMachineState;+ _connected = available;+ }+ final AppNotifier app;+ MachineState? _owner;+ bool _disposed = false;+ bool _connected = false;+ int _revision = 0;+ List<ApiConnection> connections = [], presets = [];+ bool loading = false, saving = false, loaded = false;+ String? error;++ bool get available => _owner?.connectionStatus == ConnectionStatus.connected;+ void _changed() {+ if (!_disposed) notifyListeners();+ }++ void _observe() {+ if (identical(_owner, app.localMachineState)) {+ if (_connected != available) {+ _connected = available;+ if (!_connected) error = 'Connect this computer to manage APIs.';+ _changed();+ if (_connected) unawaited(refresh());+ }+ return;+ }+ _owner = app.localMachineState;+ _connected = available;+ _revision++;+ connections = [];+ presets = [];+ loading = saving = loaded = false;+ error = null;+ unawaited(refresh());+ }++ Future<bool> refresh() => _request({'action': 'list'});+ Future<bool> save(Map<String, dynamic> connection) =>+ _request({'action': 'save', 'connection': connection});+ Future<bool> remove(String id) => _request({'action': 'remove', 'id': id});++ Future<bool> _request(Map<String, dynamic> payload) async {+ if (_disposed || saving) return false;+ final owner = _owner;+ if (owner == null || !available) {+ error = 'Connect this computer to manage APIs.';+ _changed();+ return false;+ }+ final revision = ++_revision;+ final mutation = payload['action'] != 'list';+ loading = true;+ saving = mutation;+ error = null;+ _changed();+ bool current() =>+ !_disposed &&+ revision == _revision &&+ identical(owner, app.localMachineState);+ try {+ final answer = await app.apiConnections(owner.machine.machineId, payload);+ if (!current()) return false;+ if (answer['error'] != null) {+ error =+ answer['detail'] as String? ?? 'APIs are unavailable. Try again.';+ return false;+ }+ if (answer['connections'] is! List || answer['presets'] is! List) {+ error = 'Update Harness on this computer to connect APIs.';+ return false;+ }+ List<ApiConnection> rows(String key) => (answer[key] as List)+ .whereType<Map<String, dynamic>>()+ .map(ApiConnection.fromJson)+ .toList();+ connections = rows('connections');+ presets = rows('presets');+ loaded = true;+ return true;+ } on WsRequestFailure catch (failure) {+ if (current()) {+ error = failure.detail ?? 'APIs are unavailable. Try again.';+ }+ return false;+ } catch (_) {+ if (current()) {+ error = mutation+ ? 'Could not confirm the change. Go back and refresh.'+ : 'APIs are unavailable. Try again.';+ }+ return false;+ } finally {+ if (current()) {+ loading = saving = false;+ _changed();+ }+ }+ }++ @override+ void dispose() {+ _disposed = true;+ app.removeListener(_observe);+ super.dispose();+ }+}diff --git a/desktop/lib/models/api_connections_panel.dart b/desktop/lib/models/api_connections_panel.dartnew file mode 100644index 000000000..8522dfa9e--- /dev/null+++ b/desktop/lib/models/api_connections_panel.dart@@ -0,0 +1,530 @@+import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:lucide_icons_flutter/lucide_icons.dart';+import 'package:url_launcher/url_launcher.dart';++import '../shared/theme/app_theme.dart';+import 'api_connections_controller.dart';+import 'model_mark.dart';++/// The same row rhythm as Models. The editor stays inside the panel instead of+/// opening another settings window or sending credentials to a chat.+class ApiConnectionsPanel extends StatefulWidget {+ const ApiConnectionsPanel({+ super.key,+ required this.controller,+ required this.query,+ required this.onEditingChanged,+ this.showPresets = true,+ });+ final ApiConnectionsController controller;+ final String query;+ final ValueChanged<bool> onEditingChanged;+ final bool showPresets;+ @override+ State<ApiConnectionsPanel> createState() => _ApiConnectionsPanelState();+}++class _ApiConnectionsPanelState extends State<ApiConnectionsPanel> {+ ApiConnection? _editing;+ String? _removing;++ void _edit(ApiConnection? connection) {+ if (connection != null && connection.provider != 'custom') {+ final selected = connection;+ final preset = widget.controller.presets+ .where((row) => row.provider == selected.provider)+ .firstOrNull;+ var name = selected.name;+ if (selected.id.isEmpty) {+ var suffix = 2;+ while (widget.controller.connections.any(+ (row) => row.name.toLowerCase() == name.toLowerCase(),+ )) {+ name = '${selected.name} ${suffix++}';+ }+ }+ connection = ApiConnection({+ ...?preset?.data,+ ...selected.data,+ 'name': name,+ });+ }+ setState(() {+ _editing = connection;+ _removing = null;+ });+ widget.onEditingChanged(connection != null);+ }++ @override+ Widget build(BuildContext context) => ListenableBuilder(+ listenable: widget.controller,+ builder: (context, _) {+ final controller = widget.controller;+ final editing = _editing;+ if (editing != null) {+ return _ApiEditor(+ key: ValueKey('${editing.id}:${editing.provider}'),+ connection: editing,+ controller: controller,+ backLabel: widget.showPresets ? 'Back to APIs' : 'Back to all models',+ onClose: () => _edit(null),+ );+ }+ final query = widget.query.toLowerCase();+ final connections = controller.connections+ .where((row) => row.matches(query))+ .toList();+ final presets = controller.presets+ // Subscription providers remain usable through Custom API and any+ // saved connections, without suggesting a second setup here.+ .where(+ (row) =>+ row.provider != 'openai' &&+ row.provider != 'anthropic' &&+ row.matches(query),+ )+ .toList();+ final customMatches = 'custom api'.contains(query);+ return Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ if (controller.error case final error?)+ Padding(+ padding: const EdgeInsets.all(12),+ child: Row(+ children: [+ Expanded(+ child: Text(+ error,+ style: AppType.monoMeta(color: AppPalette.textSecondary),+ ),+ ),+ TextButton(+ onPressed: controller.loading ? null : controller.refresh,+ child: const Text('Refresh'),+ ),+ ],+ ),+ ),+ if (!controller.loaded && controller.loading) _note('Loading APIs…'),+ if (connections.isNotEmpty) ...[+ _note(widget.showPresets ? 'Saved' : 'APIs'),+ for (final connection in connections) _row(connection, saved: true),+ ],+ if (controller.loaded && widget.showPresets) ...[+ _note('Add API'),+ for (final preset in presets) _row(preset),+ if (customMatches)+ _row(+ const ApiConnection({+ 'provider': 'custom',+ 'name': 'Custom API',+ }),+ ),+ if (connections.isEmpty && presets.isEmpty && !customMatches)+ _note('No matching APIs'),+ ],+ ],+ );+ },+ );++ Widget _note(String text) => Padding(+ padding: const EdgeInsets.fromLTRB(12, 14, 12, 6),+ child: Text(text, style: AppType.monoMeta(color: AppPalette.textSecondary)),+ );++ Widget _row(ApiConnection connection, {bool saved = false}) {+ final controller = widget.controller;+ final removing = _removing == connection.id && saved;+ final enabled = controller.available && !controller.saving;+ return Padding(+ padding: const EdgeInsets.fromLTRB(12, 14, 6, 14),+ child: Row(+ children: [+ if (connection.provider == 'openai' ||+ connection.provider == 'anthropic')+ ModelMark(model: connection.provider)+ else+ const Icon(LucideIcons.plug, size: 20),+ const SizedBox(width: 12),+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(+ connection.name,+ style: AppType.label(+ color: AppPalette.textPrimary,+ height: 1.3,+ ),+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ ),+ const SizedBox(height: 6),+ Text(+ removing+ ? 'Remove this saved key?'+ : connection.provider == 'custom' && !saved+ ? 'Your endpoint and key'+ : connection.host,+ style: AppType.monoMeta(+ color: AppPalette.textSecondary,+ height: 1.3,+ ),+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ ),+ ],+ ),+ ),+ if (removing) ...[+ TextButton(+ onPressed: enabled+ ? () async {+ if (await controller.remove(connection.id) && mounted) {+ setState(() => _removing = null);+ }+ }+ : null,+ child: const Text('Remove'),+ ),+ IconButton(+ tooltip: 'Keep ${connection.name}',+ onPressed: () => setState(() => _removing = null),+ icon: const Icon(LucideIcons.x, size: 16),+ ),+ ] else ...[+ IconButton(+ tooltip: '${saved ? 'Edit' : 'Add'} ${connection.name}',+ onPressed: enabled ? () => _edit(connection) : null,+ icon: Icon(+ saved ? LucideIcons.pencil : LucideIcons.plus,+ size: 18,+ ),+ ),+ if (saved)+ IconButton(+ tooltip: 'Remove ${connection.name}',+ onPressed: enabled+ ? () => setState(() => _removing = connection.id)+ : null,+ icon: const Icon(LucideIcons.trash2, size: 16),+ ),+ ],+ ],+ ),+ );+ }+}++class _ApiEditor extends StatefulWidget {+ const _ApiEditor({+ super.key,+ required this.connection,+ required this.controller,+ required this.onClose,+ required this.backLabel,+ });+ final ApiConnection connection;+ final ApiConnectionsController controller;+ final VoidCallback onClose;+ final String backLabel;+ @override+ State<_ApiEditor> createState() => _ApiEditorState();+}++class _ApiEditorState extends State<_ApiEditor> {+ final _form = GlobalKey<FormState>();+ late final _name = TextEditingController(+ text: custom && !existing ? '' : widget.connection.name,+ );+ late final _url = TextEditingController(text: widget.connection.baseUrl);+ late final _environment = TextEditingController(+ text: widget.connection.keyEnv,+ );+ late final _header = TextEditingController(+ text: widget.connection.authHeader,+ );+ late final _prefix = TextEditingController(+ text: widget.connection.authPrefix,+ );+ final _key = TextEditingController();+ bool _advanced = false, _visible = false;+ String? _linkError, _clipboardError;+ bool get custom => widget.connection.provider == 'custom';+ bool get existing => widget.connection.id.isNotEmpty;++ @override+ void dispose() {+ for (final field in [_name, _url, _environment, _header, _prefix, _key]) {+ field.clear();+ field.dispose();+ }+ super.dispose();+ }++ Future<void> _save() async {+ if (widget.controller.saving || !_form.currentState!.validate()) return;+ final saved = await widget.controller.save({+ if (existing) 'id': widget.connection.id,+ 'provider': widget.connection.provider,+ 'name': _name.text,+ 'baseUrl': _url.text,+ 'keyEnv': _environment.text,+ 'authHeader': _header.text,+ 'authPrefix': _prefix.text,+ 'apiKey': _key.text,+ });+ if (saved && mounted) widget.onClose();+ }++ Future<void> _openKeyPage(String url) async {+ try {+ final opened = await launchUrl(+ Uri.parse(url),+ mode: LaunchMode.externalApplication,+ );+ if (mounted) {+ setState(+ () => _linkError = opened+ ? null+ : 'Could not open the browser. Try again.',+ );+ }+ } catch (_) {+ if (mounted) {+ setState(() => _linkError = 'Could not open the browser. Try again.');+ }+ }+ }++ Future<void> _pasteKey() async {+ final previous = _key.value;+ try {+ final text = (await Clipboard.getData(Clipboard.kTextPlain))?.text+ ?.trim();+ if (!mounted || widget.controller.saving || _key.value != previous) {+ return;+ }+ setState(() {+ _clipboardError = text == null || text.isEmpty+ ? 'Copy an API key first.'+ : null;+ if (_clipboardError == null) {+ _key.value = TextEditingValue(+ text: text!,+ selection: TextSelection.collapsed(offset: text.length),+ );+ }+ });+ } catch (_) {+ if (mounted) {+ setState(() => _clipboardError = 'Could not paste. Try again.');+ }+ }+ }++ @override+ Widget build(BuildContext context) {+ final controller = widget.controller;+ final enabled = controller.available && !controller.saving;+ return CallbackShortcuts(+ bindings: {+ const SingleActivator(LogicalKeyboardKey.escape): widget.onClose,+ },+ child: FocusScope(+ child: Padding(+ padding: const EdgeInsets.fromLTRB(12, 4, 12, 12),+ child: Form(+ key: _form,+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Row(+ children: [+ IconButton(+ onPressed: widget.onClose,+ tooltip: widget.backLabel,+ icon: const Icon(LucideIcons.arrowLeft, size: 18),+ ),+ const SizedBox(width: 4),+ Expanded(+ child: Text(+ custom ? 'Custom API' : widget.connection.name,+ style: AppType.label(color: AppPalette.textPrimary),+ ),+ ),+ ],+ ),+ const SizedBox(height: 12),+ if (custom || _advanced) ...[+ _field(+ _name,+ 'Name',+ autofocus: custom,+ validator: _required,+ ),+ _field(+ _url,+ 'Base URL',+ hint: 'https://api.example.com/v1',+ validator: (value) {+ final url = Uri.tryParse(value?.trim() ?? '');+ return url == null ||+ !['https', 'http'].contains(url.scheme) ||+ url.host.isEmpty ||+ url.userInfo.isNotEmpty ||+ url.hasQuery ||+ url.hasFragment+ ? 'Enter an API URL without credentials or query parameters.'+ : null;+ },+ ),+ ],+ _field(+ _key,+ 'API key',+ autofocus: !custom,+ hint: existing ? 'Leave blank to keep saved key' : null,+ secret: true,+ validator: (value) => existing ? null : _required(value),+ ),+ if (widget.connection.keyUrl case final keyUrl?)+ Align(+ alignment: Alignment.centerLeft,+ child: TextButton.icon(+ onPressed: () => _openKeyPage(keyUrl),+ icon: const Icon(LucideIcons.arrowUpRight, size: 14),+ label: const Text('Get API key'),+ ),+ ),+ Align(+ alignment: Alignment.centerLeft,+ child: TextButton.icon(+ onPressed: () => setState(() => _advanced = !_advanced),+ icon: Icon(+ _advanced+ ? LucideIcons.chevronUp+ : LucideIcons.chevronDown,+ size: 14,+ ),+ label: const Text('Advanced'),+ ),+ ),+ if (_advanced) ...[+ _field(+ _environment,+ 'Key environment variable',+ hint: 'MY_API_KEY',+ ),+ _field(+ _header,+ 'Authentication header',+ hint: 'Authorization',+ validator: _required,+ ),+ _field(+ _prefix,+ 'Key prefix',+ hint: 'Bearer, Key, or leave blank',+ ),+ ],+ if ((controller.error ?? _clipboardError ?? _linkError)+ case final error?)+ Padding(+ padding: const EdgeInsets.symmetric(vertical: 10),+ child: Text(+ error,+ style: AppType.monoMeta(color: AppPalette.textSecondary),+ ),+ ),+ const SizedBox(height: 12),+ Row(+ children: [+ Expanded(+ child: Text(+ 'Stored on this computer.',+ style: AppType.monoMeta(+ color: AppPalette.textSecondary,+ ),+ ),+ ),+ const SizedBox(width: 8),+ FilledButton(+ onPressed: enabled ? _save : null,+ child: Text(controller.saving ? 'Saving…' : 'Save'),+ ),+ ],+ ),+ ],+ ),+ ),+ ),+ ),+ );+ }++ String? _required(String? value) =>+ value == null || value.trim().isEmpty ? 'Required' : null;+ Widget _field(+ TextEditingController field,+ String label, {+ String? hint,+ bool secret = false,+ bool autofocus = false,+ String? Function(String?)? validator,+ }) => Padding(+ padding: const EdgeInsets.only(bottom: 12),+ child: TextFormField(+ key: ValueKey('api-field-$label'),+ controller: field,+ autofocus: autofocus,+ enabled: !widget.controller.saving,+ obscureText: secret && !_visible,+ enableSuggestions: false,+ autocorrect: false,+ style: AppType.monoLabel(),+ validator: validator,+ onChanged: secret+ ? (_) {+ if (_clipboardError != null) {+ setState(() => _clipboardError = null);+ }+ }+ : null,+ onFieldSubmitted: (_) => _save(),+ decoration: InputDecoration(+ labelText: label,+ hintText: hint,+ labelStyle: AppType.monoMeta(color: AppPalette.textSecondary),+ hintStyle: AppType.monoMeta(color: AppPalette.textFaint),+ filled: true,+ fillColor: AppPalette.windowBg,+ border: OutlineInputBorder(borderRadius: BorderRadius.circular(8)),+ suffixIcon: secret+ ? Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ IconButton(+ tooltip: 'Paste API key',+ onPressed: widget.controller.saving ? null : _pasteKey,+ icon: const Icon(LucideIcons.clipboardPaste, size: 16),+ ),+ IconButton(+ tooltip: _visible ? 'Hide API key' : 'Show API key',+ onPressed: () => setState(() => _visible = !_visible),+ icon: Icon(+ _visible ? LucideIcons.eyeOff : LucideIcons.eye,+ size: 16,+ ),+ ),+ ],+ )+ : null,+ ),+ ),+ );+}diff --git a/desktop/lib/models/model_manager_controller.dart b/desktop/lib/models/model_manager_controller.dartindex b4761d2d2..e246ed17e 100644--- a/desktop/lib/models/model_manager_controller.dart+++ b/desktop/lib/models/model_manager_controller.dart@@ -10,6 +10,7 @@ import '../core/test_run.dart';import '../state/app_state.dart';import '../widgets/grid_model_picker.dart' show modelPickerSupports;import 'local_model.dart';+import 'api_connections_controller.dart';const modelManagerName = 'Model Manager';@@ -24,6 +25,8 @@ class ModelManagerController extends ChangeNotifier {final AppNotifier app;final LocalKeyValueStore? _storage;final bool poll;+ ApiConnectionsController? _apis;+ ApiConnectionsController get apis => _apis ??= ApiConnectionsController(app);static const introKey = 'models.introduction.dismissed';MachineState? _machine;Future<void>? _preparing, _opening, _refreshing;@@ -422,6 +425,7 @@ class ModelManagerController extends ChangeNotifier {@overridevoid dispose() {_disposed = true;+ _apis?.dispose();_timer?.cancel();if (_started) app.removeListener(_observe);super.dispose();diff --git a/desktop/lib/models/models_panel.dart b/desktop/lib/models/models_panel.dartindex 1959d242c..52b0c151b 100644--- a/desktop/lib/models/models_panel.dart+++ b/desktop/lib/models/models_panel.dart@@ -11,8 +11,9 @@ import 'local_model.dart';import 'model_manager_controller.dart';import 'model_mark.dart';import '../widgets/onboarding_card.dart';+import 'api_connections_panel.dart';-enum ModelsTab { subscriptions, local, shared }+enum ModelsTab { all, subscriptions, local, shared, apis }class ModelsPanel extends StatefulWidget {const ModelsPanel({@@ -24,7 +25,7 @@ class ModelsPanel extends StatefulWidget {this.newModelIds = const {},this.showOnboarding = false,this.onDismissOnboarding,- this.initialTab = ModelsTab.subscriptions,+ this.initialTab = ModelsTab.all,});final ModelManagerController controller;final ModelsMenuController subscriptions;@@ -42,8 +43,15 @@ class _ModelsPanelState extends State<ModelsPanel> {bool _exploring = false;final _searchFocus = FocusNode(debugLabel: 'Search models');late ModelsTab _selectedTab = widget.initialTab;+ bool _editingApi = false;ModelManagerController get controller => widget.controller;ModelsMenuController get subscriptions => widget.subscriptions;+ @override+ void initState() {+ super.initState();+ unawaited(controller.apis.refresh());+ }+@overridevoid dispose() {_search.dispose();@@ -53,9 +61,10 @@ class _ModelsPanelState extends State<ModelsPanel> {@overrideWidget build(BuildContext context) => ListenableBuilder(- listenable: Listenable.merge([controller, subscriptions]),+ listenable: Listenable.merge([controller, subscriptions, controller.apis]),builder: (context, _) {final query = _search.text.trim().toLowerCase();+ final all = _selectedTab == ModelsTab.all;final subscriptionRows = subscriptions.rows;final matchingSubscriptions = subscriptionRows.where((row) => [@@ -91,6 +100,17 @@ class _ModelsPanelState extends State<ModelsPanel> {m.id.toLowerCase().contains(query),).toList();+ final hasShared = matchingShared.any(+ (section) => section.models.isNotEmpty,+ );+ final hasApis = controller.apis.connections.any(+ (row) => row.matches(query),+ );+ final noMatches =+ matchingSubscriptions.isEmpty &&+ models.isEmpty &&+ !hasShared &&+ !hasApis;int rank(LocalModel m) => controller.operationFor(m)?.active == true? 0: m.running@@ -136,7 +156,7 @@ class _ModelsPanelState extends State<ModelsPanel> {],),),- if (widget.showOnboarding && !_exploring)+ if (widget.showOnboarding && !_exploring && !_editingApi)OnboardingCard(title: 'Power a harness with local AI',description: 'Choose a model that runs on your computer. Then select it in a harness’s model picker.',@@ -148,56 +168,63 @@ class _ModelsPanelState extends State<ModelsPanel> {}),onDismiss: widget.onDismissOnboarding ?? () {},),- Padding(- padding: const EdgeInsets.symmetric(horizontal: 16),- child: TextField(- key: const ValueKey('models-search'),- controller: _search,- focusNode: _searchFocus,- autofocus: true,- style: AppType.monoLabel(),- decoration: InputDecoration(- hintText: _selectedTab == ModelsTab.subscriptions- ? 'Search subscriptions…'- : 'Search models…',- hintStyle: AppType.monoLabel(color: AppPalette.textFaint),- prefixIcon: Icon(- LucideIcons.search,- size: 15,- color: AppPalette.textFaint,- ),- prefixIconConstraints: const BoxConstraints(minWidth: 36),- suffixIcon: _search.text.isEmpty- ? null- : IconButton(- tooltip: 'Clear search',- icon: const Icon(LucideIcons.x, size: 14),- onPressed: () {- setState(_search.clear);- _searchFocus.requestFocus();- },- ),- isDense: true,- filled: true,- fillColor: AppPalette.windowBg,- contentPadding: const EdgeInsets.symmetric(- vertical: 12,- horizontal: 12,- ),- border: OutlineInputBorder(- borderRadius: BorderRadius.circular(8),- borderSide: BorderSide.none,- ),- focusedBorder: OutlineInputBorder(- borderRadius: BorderRadius.circular(8),- borderSide: BorderSide(- color: AppPalette.accent.withValues(alpha: .8),+ if (!_editingApi)+ Padding(+ padding: const EdgeInsets.symmetric(horizontal: 16),+ child: TextField(+ key: const ValueKey('models-search'),+ controller: _search,+ focusNode: _searchFocus,+ autofocus: true,+ style: AppType.monoLabel(),+ decoration: InputDecoration(+ hintText: _selectedTab == ModelsTab.subscriptions+ ? 'Search subscriptions…'+ : _selectedTab == ModelsTab.apis+ ? 'Search APIs…'+ : 'Search models…',+ hintStyle: AppType.monoLabel(+ color: AppPalette.textFaint,+ ),+ prefixIcon: Icon(+ LucideIcons.search,+ size: 15,+ color: AppPalette.textFaint,+ ),+ prefixIconConstraints: const BoxConstraints(+ minWidth: 36,+ ),+ suffixIcon: _search.text.isEmpty+ ? null+ : IconButton(+ tooltip: 'Clear search',+ icon: const Icon(LucideIcons.x, size: 14),+ onPressed: () {+ setState(_search.clear);+ _searchFocus.requestFocus();+ },+ ),+ isDense: true,+ filled: true,+ fillColor: AppPalette.windowBg,+ contentPadding: const EdgeInsets.symmetric(+ vertical: 12,+ horizontal: 12,+ ),+ border: OutlineInputBorder(+ borderRadius: BorderRadius.circular(8),+ borderSide: BorderSide.none,+ ),+ focusedBorder: OutlineInputBorder(+ borderRadius: BorderRadius.circular(8),+ borderSide: BorderSide(+ color: AppPalette.accent.withValues(alpha: .8),+ ),),),+ onChanged: (_) => setState(() {}),),- onChanged: (_) => setState(() {}),),- ),Padding(padding: const EdgeInsets.fromLTRB(16, 10, 12, 8),child: Align(@@ -206,6 +233,14 @@ class _ModelsPanelState extends State<ModelsPanel> {scrollDirection: Axis.horizontal,child: Row(children: [+ _tab(+ ModelsTab.all,+ 'All',+ subscriptionRows.length ++ controller.localModels.length ++ sharedCount ++ controller.apis.connections.length,+ ),_tab(ModelsTab.subscriptions,'Subscriptions',@@ -217,6 +252,11 @@ class _ModelsPanelState extends State<ModelsPanel> {controller.localModels.length,),_tab(ModelsTab.shared, 'Shared', sharedCount),+ _tab(+ ModelsTab.apis,+ 'APIs',+ controller.apis.connections.length,+ ),],),),@@ -236,7 +276,16 @@ class _ModelsPanelState extends State<ModelsPanel> {child: Column(crossAxisAlignment: CrossAxisAlignment.stretch,children: [- if (_selectedTab == ModelsTab.subscriptions) ...[+ if (all &&+ !_editingApi &&+ query.isNotEmpty &&+ noMatches)+ _empty('No matches'),+ if (_selectedTab == ModelsTab.subscriptions ||+ (all &&+ !_editingApi &&+ matchingSubscriptions.isNotEmpty)) ...[+ if (all) _heading('Subscriptions'),if (matchingSubscriptions.isEmpty)_empty(query.isEmpty@@ -246,7 +295,10 @@ class _ModelsPanelState extends State<ModelsPanel> {for (final row in matchingSubscriptions)_subscription(row),],- if (_selectedTab == ModelsTab.local) ...[+ if (_selectedTab == ModelsTab.local ||+ (all &&+ !_editingApi &&+ (query.isEmpty || models.isNotEmpty))) ...[Padding(padding: const EdgeInsets.fromLTRB(12, 10, 12, 4),child: Text(@@ -272,7 +324,8 @@ class _ModelsPanelState extends State<ModelsPanel> {),for (final model in models) _model(model),],- if (_selectedTab == ModelsTab.shared) ...[+ if (_selectedTab == ModelsTab.shared ||+ (all && !_editingApi && hasShared)) ...[if (controller.models?.reachable == false)_retry('Shared models are unavailable.')else if (controller.models == null &&@@ -290,7 +343,9 @@ class _ModelsPanelState extends State<ModelsPanel> {),for (final section in matchingShared)if (section.models.isNotEmpty) ...[- _heading(section.name),+ _heading(+ all ? 'Shared · ${section.name}' : section.name,+ ),for (final model in section.models)Padding(padding: const EdgeInsets.fromLTRB(@@ -335,6 +390,16 @@ class _ModelsPanelState extends State<ModelsPanel> {),],],+ if (_selectedTab == ModelsTab.apis ||+ (all && (hasApis || _editingApi)))+ ApiConnectionsPanel(+ key: const ValueKey('models-api-connections'),+ controller: controller.apis,+ query: query,+ showPresets: !all,+ onEditingChanged: (editing) =>+ setState(() => _editingApi = editing),+ ),],),),@@ -351,7 +416,9 @@ class _ModelsPanelState extends State<ModelsPanel> {if (constraints.maxWidth >= 440)Expanded(child: Text(- 'Select models in a session’s model picker.',+ _selectedTab == ModelsTab.apis || _editingApi+ ? 'Available to harness tools on this computer.'+ : 'Select models in a session’s model picker.',style: AppType.monoMeta(color: AppPalette.textSecondary,),@@ -359,16 +426,17 @@ class _ModelsPanelState extends State<ModelsPanel> {)elseconst Spacer(),- TextButton(- onPressed: controller.opening- ? null- : widget.onManage,- style: TextButton.styleFrom(- foregroundColor: AppPalette.textSecondary,- textStyle: AppType.monoMeta(),+ if (_selectedTab != ModelsTab.apis && !_editingApi)+ TextButton(+ onPressed: controller.opening+ ? null+ : widget.onManage,+ style: TextButton.styleFrom(+ foregroundColor: AppPalette.textSecondary,+ textStyle: AppType.monoMeta(),+ ),+ child: const Text('Manage models'),),- child: const Text('Manage models'),- ),],),),@@ -387,7 +455,13 @@ class _ModelsPanelState extends State<ModelsPanel> {selected: _selectedTab == tab,child: TextButton(key: ValueKey('models-tab-${tab.name}'),- onPressed: () => setState(() => _selectedTab = tab),+ onPressed: () {+ if (_selectedTab == tab) return;+ setState(() {+ _selectedTab = tab;+ _editingApi = false;+ });+ },style: TextButton.styleFrom(backgroundColor: _selectedTab == tab? AppPalette.textPrimary.withValues(alpha: .08)diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dartindex 44b35fe52..1e4534feb 100644--- a/desktop/lib/screens/swarm_screen.dart+++ b/desktop/lib/screens/swarm_screen.dart@@ -2303,7 +2303,7 @@ class _SwarmScreenState extends State<SwarmScreen>}}- void _toggleModels({ModelsTab initialTab = ModelsTab.subscriptions}) {+ void _toggleModels({ModelsTab initialTab = ModelsTab.all}) {if (_modelsOverlay != null) {_closeModels();return;diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex 6836b3ebf..6bba1222e 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -5104,6 +5104,15 @@ class AppNotifier extends ChangeNotifier {timeout: const Duration(seconds: 90),);+ Future<Map<String, dynamic>> apiConnections(+ String machineId,+ Map<String, dynamic> payload,+ ) => _conn(machineId).request(+ 'api_connections',+ payload: payload,+ timeout: const Duration(seconds: 10),+ );+Future<Map<String, dynamic>> controlLocalModel(String machineId,String modelId, {diff --git a/desktop/test/api_connections_test.dart b/desktop/test/api_connections_test.dartnew file mode 100644index 000000000..f8a14a35d--- /dev/null+++ b/desktop/test/api_connections_test.dart@@ -0,0 +1,904 @@+import 'dart:async';+import 'dart:io';+import 'dart:ui' as ui;++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/models.dart';+import 'package:harness/logging/redact.dart';+import 'package:harness/models/api_connections_controller.dart';+import 'package:harness/models/model_manager_controller.dart';+import 'package:harness/models/models_panel.dart';+import 'package:harness/usage/models_menu_controller.dart';+import 'package:harness/ws/ws_conn.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;++import 'support/model_manager.dart';+import 'support/real_fonts.dart';++const preset = {+ 'provider': 'openrouter',+ 'name': 'OpenRouter',+ 'baseUrl': 'https://openrouter.ai/api/v1',+ 'keyEnv': 'OPENROUTER_API_KEY',+ 'authHeader': 'Authorization',+ 'authPrefix': 'Bearer',+ 'keyUrl': 'https://openrouter.ai/settings/keys',+};++class _ApiApp extends ModelManagerTestApp {+ _ApiApp() : super(ModelManagerConnection());+ final requests = <Map<String, dynamic>>[];+ List<Map<String, dynamic>> rows = [];+ bool allPresets = false;+ Object? failure;+ Completer<Map<String, dynamic>>? held;+ Map<String, dynamic>? response;++ @override+ Future<Map<String, dynamic>> apiConnections(+ String machineId,+ Map<String, dynamic> payload,+ ) async {+ expect(machineId, 'm');+ requests.add(payload);+ if (failure != null) throw failure!;+ if (held != null) {+ final reply = held!;+ held = null;+ return reply.future;+ }+ if (response != null) return response!;+ if (payload['action'] == 'save') {+ final input = Map<String, dynamic>.from(payload['connection'] as Map);+ input.remove('apiKey');+ input['id'] ??= input['provider'] == 'custom'+ ? 'custom-fixture'+ : 'openrouter';+ rows = [...rows.where((row) => row['id'] != input['id']), input];+ } else if (payload['action'] == 'remove') {+ rows = rows.where((row) => row['id'] != payload['id']).toList();+ }+ return {+ 'connections': rows,+ 'presets': [+ preset,+ if (allPresets) ...[+ {+ ...preset,+ 'provider': 'fal',+ 'name': 'fal.ai',+ 'baseUrl': 'https://queue.fal.run',+ 'keyEnv': 'FAL_KEY',+ 'authPrefix': 'Key',+ },+ {+ ...preset,+ 'provider': 'openai',+ 'name': 'OpenAI',+ 'baseUrl': 'https://api.openai.com/v1',+ },+ {+ ...preset,+ 'provider': 'anthropic',+ 'name': 'Anthropic',+ 'baseUrl': 'https://api.anthropic.com/v1',+ },+ {+ ...preset,+ 'provider': 'replicate',+ 'name': 'Replicate',+ 'baseUrl': 'https://api.replicate.com/v1',+ },+ ],+ ],+ };+ }+}++void main() {+ setUpAll(() async {+ await loadRealFonts();+ await (FontLoader('packages/lucide_icons_flutter/Lucide')..addFont(+ rootBundle.load('packages/lucide_icons_flutter/assets/lucide.ttf'),+ ))+ .load();+ });+ test('metadata and frame logging strip credentials', () {+ final value = ApiConnection.fromJson({+ ...preset,+ 'id': 'or',+ 'apiKey': 'private-key',+ });+ expect(value.data.containsKey('apiKey'), isFalse);+ expect(value.host, 'openrouter.ai');+ expect(+ summariseForLog({+ 'connection': {...preset, 'apiKey': 'private-key'},+ }),+ isNot(contains('private-key')),+ );+ });++ test('controller saves, edits, removes and handles old daemons and explicit failures', () async {+ final app = _ApiApp();+ final controller = ApiConnectionsController(app);+ addTearDown(() {+ controller.dispose();+ app.dispose();+ });+ expect(await controller.refresh(), isTrue);+ expect(controller.presets.single.name, 'OpenRouter');+ expect(await controller.save({...preset, 'apiKey': 'fixture-key'}), isTrue);+ expect(controller.connections.single.id, 'openrouter');+ expect(await controller.remove('openrouter'), isTrue);+ expect(controller.connections, isEmpty);+ app.response = {};+ expect(await controller.refresh(), isFalse);+ expect(controller.error, contains('Update Harness'));+ app.response = {+ 'error': 'API_CONNECTIONS_FAILED',+ 'detail': 'Check the URL.',+ };+ expect(await controller.save(preset), isFalse);+ expect(controller.error, 'Check the URL.');+ app.response = null;+ app.failure = const WsRequestFailure(+ responseType: 'api_connections_result',+ code: 'LOCAL_ONLY',+ detail: 'Manage APIs on this computer.',+ );+ expect(await controller.refresh(), isFalse);+ expect(controller.error, 'Manage APIs on this computer.');+ app.failure = StateError('private-network-detail');+ expect(await controller.save(preset), isFalse);+ expect(+ controller.error,+ 'Could not confirm the change. Go back and refresh.',+ );+ expect(await controller.refresh(), isFalse);+ expect(controller.error, 'APIs are unavailable. Try again.');+ app.stateOf('m')!.connectionStatus = ConnectionStatus.disconnected;+ expect(await controller.refresh(), isFalse);+ expect(controller.error, contains('Connect this computer'));+ });++ test('an older inventory cannot overwrite a save and double clicks do not repeat it', () async {+ final app = _ApiApp();+ final controller = ApiConnectionsController(app);+ addTearDown(() {+ controller.dispose();+ app.dispose();+ });+ final read = Completer<Map<String, dynamic>>();+ app.held = read;+ final refreshing = controller.refresh();+ final write = Completer<Map<String, dynamic>>();+ app.held = write;+ final saving = controller.save({...preset, 'apiKey': 'fixture'});+ expect(controller.saving, isTrue);+ expect(await controller.save(preset), isFalse);+ expect(await controller.remove('openrouter'), isFalse);+ expect(await controller.refresh(), isFalse);+ write.complete({+ 'connections': [+ {...preset, 'id': 'openrouter'},+ ],+ 'presets': [preset],+ });+ expect(await saving, isTrue);+ read.complete({'connections': [], 'presets': []});+ expect(await refreshing, isFalse);+ expect(controller.connections.single.id, 'openrouter');+ expect(+ app.requests.where((request) => request['action'] == 'save'),+ hasLength(1),+ );+ });++ test('disposal and local machine replacement ignore late replies', () async {+ final app = _ApiApp();+ final controller = ApiConnectionsController(app);+ final read = Completer<Map<String, dynamic>>();+ app.held = read;+ final refreshing = controller.refresh();+ app.machineStates.remove('m');+ app.notifyListeners();+ read.complete({+ 'connections': [+ {...preset, 'id': 'old'},+ ],+ 'presets': [],+ });+ expect(await refreshing, isFalse);+ expect(controller.connections, isEmpty);+ controller.dispose();+ expect(await controller.refresh(), isFalse);+ app.dispose();+ });++ test('reconnect refreshes APIs and reports an offline computer', () async {+ final app = _ApiApp();+ final controller = ApiConnectionsController(app);+ addTearDown(() {+ controller.dispose();+ app.dispose();+ });+ await controller.refresh();+ app.stateOf('m')!.connectionStatus = ConnectionStatus.disconnected;+ app.notifyListeners();+ expect(controller.available, isFalse);+ expect(controller.error, contains('Connect this computer'));+ app.stateOf('m')!.connectionStatus = ConnectionStatus.connected;+ app.notifyListeners();+ await Future<void>.delayed(Duration.zero);+ expect(controller.available, isTrue);+ expect(controller.error, isNull);+ });++ Future<(_ApiApp, ModelManagerController)> mount(+ WidgetTester tester, {+ double width = 640,+ double height = 820,+ ModelsTab initialTab = ModelsTab.apis,+ bool showOnboarding = false,+ }) async {+ tester.view.resetPhysicalSize();+ tester.view.physicalSize = const Size(1280, 1100);+ tester.view.devicePixelRatio = 1;+ addTearDown(tester.view.resetPhysicalSize);+ addTearDown(tester.view.resetDevicePixelRatio);+ final app = _ApiApp();+ final controller = ModelManagerController(app, poll: false);+ final subscriptions = ModelsMenuController();+ addTearDown(() {+ controller.dispose();+ subscriptions.dispose();+ app.dispose();+ });+ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(+ body: Center(+ child: SizedBox(+ width: width,+ height: height,+ child: ModelsPanel(+ controller: controller,+ subscriptions: subscriptions,+ initialTab: initialTab,+ showOnboarding: showOnboarding,+ onClose: () {},+ onManage: () {},+ ),+ ),+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ return (app, controller);+ }++ Finder field(String label) => find.byKey(ValueKey('api-field-$label'));++ testWidgets('All groups and searches every source with stable total counts', (+ tester,+ ) async {+ final (app, controller) = await mount(tester, initialTab: ModelsTab.all);+ app.rows = [+ {...preset, 'id': 'openrouter'},+ ];+ app.inventory = const GridModels(+ gridName: 'home',+ models: [],+ grids: [+ GridSection(+ name: 'Team',+ own: false,+ models: [GridModel(id: 'Shared DeepSeek', node: 'Team computer')],+ ),+ ],+ );+ await controller.refresh();+ await controller.apis.refresh();+ await tester.pumpAndSettle();+ expect(find.text('All 9'), findsOneWidget);+ expect(find.text('Subscriptions'), findsOneWidget);+ expect(find.text('Shared · Team'), findsOneWidget);+ expect(find.text('Shared DeepSeek'), findsOneWidget);+ expect(find.text('Qwen3.8-27B'), findsOneWidget);+ expect(find.text('APIs'), findsOneWidget);+ expect(find.byTooltip('Edit OpenRouter'), findsOneWidget);+ expect(find.text('Add API'), findsNothing);+ expect(find.byTooltip('Add OpenRouter'), findsNothing);+ final search = find.byKey(const ValueKey('models-search'));+ for (final (query, match) in [+ ('anthropic', 'Anthropic'),+ ('qwen3.8-27b', 'Qwen3.8-27B'),+ ('TEAM COMPUTER', 'Shared DeepSeek'),+ ('openrouter.ai', 'OpenRouter'),+ ]) {+ await tester.enterText(search, query);+ await tester.pumpAndSettle();+ expect(find.text(match), findsOneWidget);+ expect(find.text('All 9'), findsOneWidget);+ expect(find.text('No matches'), findsNothing);+ expect(find.text('No matching models'), findsNothing);+ }+ await tester.enterText(search, 'no-such-model-or-api');+ await tester.pumpAndSettle();+ expect(find.text('No matches'), findsOneWidget);+ await tester.tap(find.byTooltip('Clear search'));+ await tester.pumpAndSettle();+ final action = find.byKey(const ValueKey('model-action-qwen'));+ await tester.ensureVisible(action);+ await tester.tap(action);+ await tester.pump();+ expect(app.actions.single.start, isTrue);+ expect(find.text('Downloading · 42%'), findsOneWidget);+ await tester.tap(find.byKey(const ValueKey('models-tab-local')));+ await tester.pump();+ expect(find.text('Downloading · 42%'), findsOneWidget);+ await tester.tap(find.byKey(const ValueKey('models-tab-all')));+ await tester.pump();+ expect(app.actions, hasLength(1));+ expect(find.text('Downloading · 42%'), findsOneWidget);+ expect(tester.takeException(), isNull);+ });++ testWidgets('All edits and removes saved APIs without exposing presets', (+ tester,+ ) async {+ final (app, controller) = await mount(tester, initialTab: ModelsTab.all);+ app.rows = [+ {...preset, 'id': 'openrouter'},+ ];+ await controller.refresh();+ await controller.apis.refresh();+ await tester.pumpAndSettle();+ final edit = find.byTooltip('Edit OpenRouter');+ await tester.ensureVisible(edit);+ await tester.tap(edit);+ await tester.pumpAndSettle();+ expect(field('API key'), findsOneWidget);+ expect(find.text('Qwen3.8-27B'), findsNothing);+ expect(find.text('Subscriptions'), findsNothing);+ expect(find.text('Manage models'), findsNothing);+ await tester.tap(find.byKey(const ValueKey('models-tab-all')));+ await tester.pump();+ expect(field('API key'), findsOneWidget);+ expect(find.byKey(const ValueKey('models-search')), findsNothing);+ await tester.tap(find.byTooltip('Back to all models'));+ await tester.pumpAndSettle();+ expect(find.text('Qwen3.8-27B'), findsOneWidget);+ await tester.enterText(+ find.byKey(const ValueKey('models-search')),+ 'openrouter',+ );+ await tester.pumpAndSettle();+ await tester.tap(find.byTooltip('Remove OpenRouter'));+ await tester.pump();+ await tester.tap(find.text('Remove'));+ await tester.pumpAndSettle();+ expect(find.text('All 7'), findsOneWidget);+ expect(find.text('No matches'), findsOneWidget);+ expect(find.text('Add API'), findsNothing);+ expect(tester.takeException(), isNull);+ });++ testWidgets('paste button masks the key and recovers from clipboard errors', (+ tester,+ ) async {+ final (app, _) = await mount(tester);+ await tester.tap(find.byTooltip('Add OpenRouter'));+ await tester.pumpAndSettle();+ final messenger =+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;+ String? clipboard;+ bool denied = false;+ messenger.setMockMethodCallHandler(SystemChannels.platform, (call) async {+ if (call.method != 'Clipboard.getData') return null;+ if (denied) throw PlatformException(code: 'denied');+ return clipboard == null ? null : {'text': clipboard};+ });+ addTearDown(+ () => messenger.setMockMethodCallHandler(SystemChannels.platform, null),+ );+ final paste = find.byTooltip('Paste API key');+ await tester.tap(paste);+ await tester.pumpAndSettle();+ expect(find.text('Copy an API key first.'), findsOneWidget);+ await tester.enterText(field('API key'), 'manual-fixture');+ await tester.pump();+ expect(find.text('Copy an API key first.'), findsNothing);+ denied = true;+ await tester.tap(paste);+ await tester.pumpAndSettle();+ expect(find.text('Could not paste. Try again.'), findsOneWidget);+ expect(+ tester.widget<TextFormField>(field('API key')).controller!.text,+ 'manual-fixture',+ );+ denied = false;+ clipboard = ' pasted-button-fixture\n';+ await tester.tap(paste);+ await tester.pumpAndSettle();+ expect(find.text('Could not paste. Try again.'), findsNothing);+ final input = tester.widget<TextFormField>(field('API key')).controller!;+ expect(input.text, 'pasted-button-fixture');+ expect(input.selection.extentOffset, input.text.length);+ expect(+ tester+ .widget<TextField>(+ find.descendant(+ of: field('API key'),+ matching: find.byType(TextField),+ ),+ )+ .obscureText,+ isTrue,+ );+ await tester.tap(find.text('Save'));+ await tester.pumpAndSettle();+ expect(+ (app.requests.last['connection'] as Map)['apiKey'],+ 'pasted-button-fixture',+ );+ });++ testWidgets(+ 'late clipboard replies do not replace edits or reopen an editor',+ (tester) async {+ await mount(tester);+ final messenger =+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;+ var clipboard = Completer<Map<String, String>>();+ messenger.setMockMethodCallHandler(SystemChannels.platform, (call) async {+ if (call.method == 'Clipboard.getData') return clipboard.future;+ return null;+ });+ addTearDown(+ () => messenger.setMockMethodCallHandler(SystemChannels.platform, null),+ );+ await tester.tap(find.byTooltip('Add OpenRouter'));+ await tester.pumpAndSettle();+ await tester.tap(find.byTooltip('Paste API key'));+ await tester.enterText(field('API key'), 'newer-fixture');+ clipboard.complete({'text': 'stale-fixture'});+ await tester.pumpAndSettle();+ expect(+ tester.widget<TextFormField>(field('API key')).controller!.text,+ 'newer-fixture',+ );+ clipboard = Completer<Map<String, String>>();+ await tester.tap(find.byTooltip('Paste API key'));+ await tester.tap(find.byTooltip('Back to APIs'));+ await tester.pumpAndSettle();+ clipboard.complete({'text': 'stale-fixture'});+ await tester.pumpAndSettle();+ expect(find.byTooltip('Add OpenRouter'), findsOneWidget);+ expect(tester.takeException(), isNull);+ },+ );++ testWidgets(+ 'API key supports Mac select-all and paste without revealing it',+ (tester) async {+ final (app, _) = await mount(tester);+ await tester.tap(find.byTooltip('Add OpenRouter'));+ await tester.pumpAndSettle();+ await tester.enterText(field('API key'), 'replace-this-fixture');+ final messenger =+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;+ messenger.setMockMethodCallHandler(SystemChannels.platform, (call) async {+ if (call.method == 'Clipboard.getData') {+ return {'text': 'pasted-test-key'};+ }+ if (call.method == 'Clipboard.hasStrings') return {'value': true};+ return null;+ });+ addTearDown(+ () => messenger.setMockMethodCallHandler(SystemChannels.platform, null),+ );+ await tester.sendKeyDownEvent(LogicalKeyboardKey.metaLeft);+ await tester.sendKeyEvent(LogicalKeyboardKey.keyA);+ await tester.sendKeyUpEvent(LogicalKeyboardKey.metaLeft);+ await tester.pump();+ final input = tester.widget<TextFormField>(field('API key')).controller!;+ expect(input.selection.baseOffset, 0);+ expect(input.selection.extentOffset, input.text.length);+ await tester.sendKeyDownEvent(LogicalKeyboardKey.metaLeft);+ await tester.sendKeyEvent(LogicalKeyboardKey.keyV);+ await tester.sendKeyUpEvent(LogicalKeyboardKey.metaLeft);+ await tester.pumpAndSettle();+ expect(input.text, 'pasted-test-key');+ expect(+ tester+ .widget<TextField>(+ find.descendant(+ of: field('API key'),+ matching: find.byType(TextField),+ ),+ )+ .obscureText,+ isTrue,+ );+ await tester.tap(find.text('Save'));+ await tester.pumpAndSettle();+ expect(+ (app.requests.last['connection'] as Map)['apiKey'],+ 'pasted-test-key',+ );+ },+ variant: TargetPlatformVariant.only(TargetPlatform.macOS),+ );++ testWidgets(+ 'preset key save, edit without retrieving the key, and reversible remove',+ (tester) async {+ final (app, controller) = await mount(tester);+ expect(find.text('APIs 0'), findsOneWidget);+ expect(find.text('Search APIs…'), findsOneWidget);+ await tester.tap(find.byTooltip('Add OpenRouter'));+ await tester.pumpAndSettle();+ expect(find.byKey(const ValueKey('models-search')), findsNothing);+ expect(find.text('Get API key'), findsOneWidget);+ await tester.tap(find.text('Save'));+ await tester.pump();+ expect(find.text('Required'), findsOneWidget);+ await tester.enterText(field('API key'), 'private-fixture');+ expect(+ tester+ .widget<TextField>(+ find.descendant(+ of: field('API key'),+ matching: find.byType(TextField),+ ),+ )+ .obscureText,+ isTrue,+ );+ await tester.tap(find.byTooltip('Show API key'));+ await tester.pump();+ expect(+ tester+ .widget<TextField>(+ find.descendant(+ of: field('API key'),+ matching: find.byType(TextField),+ ),+ )+ .obscureText,+ isFalse,+ );+ await tester.tap(find.byTooltip('Hide API key'));+ await tester.tap(find.text('Save'));+ await tester.pumpAndSettle();+ expect(find.text('APIs 1'), findsOneWidget);+ expect(find.byTooltip('Edit OpenRouter'), findsOneWidget);+ expect(+ controller.apis.connections.single.data.values,+ isNot(contains('private-fixture')),+ );+ await tester.tap(find.byTooltip('Edit OpenRouter'));+ await tester.pumpAndSettle();+ expect(+ tester.widget<TextFormField>(field('API key')).controller!.text,+ isEmpty,+ );+ expect(find.text('Leave blank to keep saved key'), findsOneWidget);+ await tester.tap(find.text('Advanced'));+ await tester.pumpAndSettle();+ await tester.enterText(field('Name'), 'OpenRouter work');+ await tester.ensureVisible(find.text('Save'));+ await tester.tap(find.text('Save'));+ await tester.pumpAndSettle();+ expect((app.requests.last['connection'] as Map)['apiKey'], '');+ await tester.tap(find.byTooltip('Remove OpenRouter work'));+ await tester.pump();+ expect(find.text('Remove this saved key?'), findsOneWidget);+ await tester.tap(find.byTooltip('Keep OpenRouter work'));+ await tester.pump();+ expect(controller.apis.connections, hasLength(1));+ await tester.tap(find.byTooltip('Remove OpenRouter work'));+ await tester.pump();+ await tester.tap(find.text('Remove'));+ await tester.pumpAndSettle();+ expect(controller.apis.connections, isEmpty);+ expect(tester.takeException(), isNull);+ },+ );++ testWidgets(+ 'custom API supports URL, key environment and header with no vendor restriction',+ (tester) async {+ final (app, _) = await mount(tester);+ await tester.tap(find.byTooltip('Add Custom API'));+ await tester.pumpAndSettle();+ await tester.enterText(field('Name'), 'My image service');+ await tester.enterText(+ field('Base URL'),+ 'https://images.example.test/v2',+ );+ await tester.enterText(field('API key'), 'fixture-key');+ await tester.tap(find.text('Advanced'));+ await tester.pumpAndSettle();+ await tester.enterText(field('Key environment variable'), 'IMAGES_KEY');+ await tester.enterText(field('Authentication header'), 'x-images-key');+ await tester.enterText(field('Key prefix'), '');+ await tester.ensureVisible(find.text('Save'));+ await tester.tap(find.text('Save'));+ await tester.pumpAndSettle();+ expect(app.requests.last['connection'], containsPair('authPrefix', ''));+ expect(+ app.requests.last['connection'],+ containsPair('keyEnv', 'IMAGES_KEY'),+ );+ expect(find.text('My image service'), findsOneWidget);+ expect(tester.takeException(), isNull);+ },+ );++ testWidgets(+ 'search, escape, tabs, short windows and pending saves remain usable',+ (tester) async {+ final (app, controller) = await mount(tester, width: 500, height: 510);+ final search = find.byKey(const ValueKey('models-search'));+ await tester.enterText(search, 'nothing-like-this');+ await tester.pump();+ expect(find.text('No matching APIs'), findsOneWidget);+ await tester.tap(find.byTooltip('Clear search'));+ await tester.pump();+ await tester.tap(find.byTooltip('Add OpenRouter'));+ await tester.pumpAndSettle();+ await tester.enterText(field('API key'), 'not-saved');+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);+ await tester.pumpAndSettle();+ expect(find.text('Search APIs…'), findsOneWidget);+ expect(+ app.requests.where((request) => request['action'] == 'save'),+ isEmpty,+ );+ await tester.tap(find.byTooltip('Add OpenRouter'));+ await tester.pumpAndSettle();+ await tester.enterText(field('API key'), 'fixture');+ final held = Completer<Map<String, dynamic>>();+ app.held = held;+ await tester.ensureVisible(find.text('Save'));+ await tester.tap(find.text('Save'));+ await tester.pump();+ expect(find.text('Saving…'), findsOneWidget);+ expect(+ tester.widget<FilledButton>(find.byType(FilledButton)).onPressed,+ isNull,+ );+ await tester.tap(find.byKey(const ValueKey('models-tab-subscriptions')));+ await tester.pump();+ held.complete({+ 'connections': [+ {...preset, 'id': 'openrouter'},+ ],+ 'presets': [preset],+ });+ await tester.pumpAndSettle();+ expect(controller.apis.connections, hasLength(1));+ await tester.tap(find.text('APIs 1'));+ await tester.pumpAndSettle();+ expect(find.byTooltip('Edit OpenRouter'), findsOneWidget);+ expect(tester.takeException(), isNull);+ },+ );++ testWidgets('API editing preserves the local-model onboarding flow', (+ tester,+ ) async {+ await mount(tester, showOnboarding: true);+ expect(find.text('Explore local models'), findsOneWidget);+ await tester.tap(find.byTooltip('Add OpenRouter'));+ await tester.pumpAndSettle();+ expect(find.text('Explore local models'), findsNothing);+ expect(field('API key'), findsOneWidget);+ await tester.tap(find.byTooltip('Back to APIs'));+ await tester.pumpAndSettle();+ await tester.tap(find.text('Explore local models'));+ await tester.pumpAndSettle();+ expect(find.text('Explore local models'), findsNothing);+ expect(find.text('Search models…'), findsOneWidget);+ expect(field('API key'), findsNothing);+ expect(find.byTooltip('Add OpenRouter'), findsNothing);+ expect(tester.takeException(), isNull);+ });++ testWidgets('subscription providers stay editable without API suggestions', (+ tester,+ ) async {+ final (app, controller) = await mount(tester);+ app.allPresets = true;+ app.rows = [+ {+ ...preset,+ 'id': 'openai',+ 'provider': 'openai',+ 'name': 'OpenAI',+ 'baseUrl': 'https://api.openai.com/v1',+ },+ {+ ...preset,+ 'id': 'anthropic',+ 'provider': 'anthropic',+ 'name': 'Anthropic',+ 'baseUrl': 'https://api.anthropic.com/v1',+ },+ ];+ await controller.apis.refresh();+ await tester.pumpAndSettle();+ for (final provider in ['OpenAI', 'Anthropic']) {+ expect(find.byTooltip('Add $provider'), findsNothing);+ await tester.tap(find.byTooltip('Edit $provider'));+ await tester.pumpAndSettle();+ expect(find.text('Leave blank to keep saved key'), findsOneWidget);+ await tester.tap(find.byTooltip('Back to APIs'));+ await tester.pumpAndSettle();+ }+ expect(find.byTooltip('Add OpenRouter'), findsOneWidget);+ expect(find.byTooltip('Add fal.ai'), findsOneWidget);+ expect(find.byTooltip('Add Replicate'), findsOneWidget);+ expect(find.byTooltip('Add Custom API'), findsOneWidget);+ expect(tester.takeException(), isNull);+ });++ testWidgets('API list and editor render in the Models panel', (tester) async {+ tester.view.physicalSize = const Size(760, 920);+ tester.view.devicePixelRatio = 1;+ addTearDown(tester.view.resetPhysicalSize);+ addTearDown(tester.view.resetDevicePixelRatio);+ final previous = grid.AppTheme.brightness.value;+ grid.AppTheme.brightness.value = Brightness.dark;+ addTearDown(() => grid.AppTheme.brightness.value = previous);+ final app = _ApiApp();+ app.rows = [+ {...preset, 'id': 'openrouter', 'name': 'OpenRouter work'},+ ];+ app.allPresets = true;+ final controller = ModelManagerController(app, poll: false);+ final subscriptions = ModelsMenuController();+ addTearDown(() {+ controller.dispose();+ subscriptions.dispose();+ app.dispose();+ });+ final boundary = GlobalKey();+ await tester.pumpWidget(+ RepaintBoundary(+ key: boundary,+ child: MaterialApp(+ debugShowCheckedModeBanner: false,+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ home: Scaffold(+ body: Center(+ child: ConstrainedBox(+ constraints: const BoxConstraints(+ maxWidth: 640,+ maxHeight: 820,+ ),+ child: ModelsPanel(+ controller: controller,+ subscriptions: subscriptions,+ initialTab: ModelsTab.apis,+ onClose: () {},+ onManage: () {},+ ),+ ),+ ),+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ Future<void> capture(String name) async {+ final output = Platform.environment['HARNESS_APIS_CAPTURE_DIR'];+ if (output == null) return;+ await tester.runAsync(() async {+ final rendered =+ boundary.currentContext!.findRenderObject()!+ as RenderRepaintBoundary;+ final image = await rendered.toImage(pixelRatio: 2);+ final bytes = await image.toByteData(format: ui.ImageByteFormat.png);+ await File('$output/$name.png').create(recursive: true);+ await File('$output/$name.png')+ .writeAsBytes(bytes!.buffer.asUint8List());+ image.dispose();+ });+ }++ expect(find.byTooltip('Add OpenAI'), findsNothing);+ expect(find.byTooltip('Add Anthropic'), findsNothing);+ await capture('apis-list');+ await tester.tap(find.byTooltip('Add Custom API'));+ await tester.pumpAndSettle();+ await tester.enterText(field('Name'), 'My image service');+ await tester.enterText(field('Base URL'), 'https://api.example.com/v1');+ await tester.pumpAndSettle();+ await capture('apis-custom');+ await tester.tap(find.byKey(const ValueKey('models-tab-all')));+ app.localInventory = modelInventory(scenario: 'ready');+ await controller.refresh();+ await tester.pumpAndSettle();+ await capture('models-all');+ expect(tester.takeException(), isNull);+ });++ testWidgets(+ 'duplicate providers, browser failure, failed save, retry and form validation',+ (tester) async {+ final (app, controller) = await mount(tester);+ app.rows = [+ {...preset, 'id': 'openrouter'},+ ];+ await controller.apis.refresh();+ await tester.pumpAndSettle();+ await tester.tap(find.byTooltip('Add OpenRouter'));+ await tester.pumpAndSettle();+ expect(find.text('OpenRouter 2'), findsOneWidget);+ const channel = MethodChannel('plugins.flutter.io/url_launcher');+ var opens = 0;+ tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, (+ call,+ ) async {+ opens++;+ if (opens == 1) throw PlatformException(code: 'unavailable');+ return opens > 2;+ });+ addTearDown(+ () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(+ channel,+ null,+ ),+ );+ await tester.tap(find.text('Get API key'));+ await tester.pumpAndSettle();+ expect(+ find.text('Could not open the browser. Try again.'),+ findsOneWidget,+ );+ await tester.tap(find.text('Get API key'));+ await tester.pumpAndSettle();+ expect(+ find.text('Could not open the browser. Try again.'),+ findsOneWidget,+ );+ await tester.tap(find.text('Get API key'));+ await tester.pumpAndSettle();+ expect(find.text('Could not open the browser. Try again.'), findsNothing);+ await tester.enterText(field('API key'), 'fixture');+ app.response = {+ 'error': 'API_CONNECTIONS_FAILED',+ 'detail': 'Could not save this API.',+ };+ await tester.testTextInput.receiveAction(TextInputAction.done);+ await tester.pumpAndSettle();+ expect(find.text('Could not save this API.'), findsOneWidget);+ await tester.tap(find.byTooltip('Back to APIs'));+ await tester.pumpAndSettle();+ app.response = null;+ await tester.tap(find.text('Refresh'));+ await tester.pumpAndSettle();+ expect(find.text('Could not save this API.'), findsNothing);+ await tester.tap(find.byTooltip('Add Custom API'));+ await tester.pumpAndSettle();+ await tester.enterText(field('Name'), 'My service');+ await tester.enterText(field('Base URL'), 'file:///not-an-api');+ await tester.enterText(field('API key'), 'fixture');+ await tester.tap(find.text('Save'));+ await tester.pumpAndSettle();+ expect(+ find.text('Enter an API URL without credentials or query parameters.'),+ findsOneWidget,+ );+ expect(tester.takeException(), isNull);+ },+ );+}diff --git a/desktop/test/models_menu_test.dart b/desktop/test/models_menu_test.dartindex d29051796..c9d9c0a14 100644--- a/desktop/test/models_menu_test.dart+++ b/desktop/test/models_menu_test.dart@@ -475,7 +475,8 @@ void main() {final app = ModelManagerTestApp(connection);await openGridDoor(tester, app, command: 'models');expect(find.byType(ModelsPanel), findsOneWidget);- expect(find.text('Search subscriptions…'), findsOneWidget);+ expect(find.text('Search models…'), findsOneWidget);+ expect(find.byKey(const ValueKey('models-tab-all')), findsOneWidget);expect(connection.creations, isEmpty);await tester.sendKeyEvent(LogicalKeyboardKey.escape);await tester.pumpAndSettle();diff --git a/desktop/test/models_panel_test.dart b/desktop/test/models_panel_test.dartindex 1c7d0eb56..6004bc17b 100644--- a/desktop/test/models_panel_test.dart+++ b/desktop/test/models_panel_test.dart@@ -92,6 +92,7 @@ void main() {controller: controller,subscriptions: subscriptions,newModelIds: const {'qwen'},+ initialTab: ModelsTab.subscriptions,onClose: () => closed++,onManage: () {},),@@ -103,7 +104,7 @@ void main() {expect(find.text('Subscriptions 2'), findsOneWidget);expect(find.text('Local 0'), findsOneWidget);expect(find.text('Shared 0'), findsOneWidget);- expect(find.textContaining('All '), findsNothing);+ expect(find.text('All 2'), findsOneWidget);expect(find.textContaining('Running '), findsNothing);expect(find.text('Account abc123'), findsOneWidget);expect(find.text('Account def456'), findsOneWidget);@@ -726,7 +727,10 @@ void main() {lessThan(tester.getRect(find.byTooltip('Harnesses')).left),);expect(find.byType(Dialog), findsNothing);- expect(find.text('Search subscriptions…'), findsOneWidget);+ expect(find.text('Search models…'), findsOneWidget);+ expect(find.text('All 14'), findsOneWidget);+ expect(find.text('Subscriptions'), findsOneWidget);+ expect(find.text('Qwen3.8-27B'), findsOneWidget);expect(find.text('Run AI on this computer'), findsNothing);expect(app.activeSwarmId, tab);expect(app.panes.map((pane) => pane.id), panes);diff --git a/desktop/tool/check_models_coverage.mjs b/desktop/tool/check_models_coverage.mjsindex 60b65fcd3..176ba4c61 100644--- a/desktop/tool/check_models_coverage.mjs+++ b/desktop/tool/check_models_coverage.mjs@@ -1,4 +1,4 @@-// Run the Models tests with --coverage, then check the feature's four modules.+// Run the Models and API tests with --coverage, then check all six feature modules.import { readFileSync } from 'node:fs'const expected = new Set([@@ -6,6 +6,8 @@ const expected = new Set(['model_manager_controller.dart','model_mark.dart','models_panel.dart',+ 'api_connections_controller.dart',+ 'api_connections_panel.dart',])let covered = 0, total = 0for (const record of readFileSync(process.argv[2] ?? 'coverage/lcov.info', 'utf8').split('end_of_record')) {@@ -20,4 +22,4 @@ for (const record of readFileSync(process.argv[2] ?? 'coverage/lcov.info', 'utf8covered += hit}if (expected.size) throw new Error(`Missing Models coverage: ${[...expected].join(', ')}`)-console.log(`Models desktop: ${covered}/${total} lines (100%) across four feature modules.`)+console.log(`Models desktop: ${covered}/${total} lines (100%) across six feature modules.`)diff --git a/docs/api-connections.md b/docs/api-connections.mdnew file mode 100644index 000000000..b73eb150b--- /dev/null+++ b/docs/api-connections.md@@ -0,0 +1,91 @@+# Saved APIs++Models opens on **All**, with subscriptions, local models, shared models, and saved+APIs grouped in one searchable view. The source tabs narrow the list.++++Open **Models → APIs**, choose a provider, paste its key, and select **Save**.+The clipboard icon pastes the key directly; it remains hidden until you reveal it.+OpenRouter, fal.ai, and Replicate have presets. **Custom API**+accepts a name, base URL, and key; **Advanced** controls the key environment+variable, authentication header, and optional prefix.++++Connections are available to every local harness's tools. They do not change+the harness's selected model or subscription. Saving stores the connection;+it does not call the provider, validate account credit, or make a paid request.++To edit a connection, select its pencil icon. Leave the key blank to keep the+saved key, or paste a replacement. The trash icon removes the saved connection+after confirmation; revoke the key at the provider if it should stop working+outside Harness too. Multiple named connections to one provider are supported.++++## Using a connection++Harness adds a short **Saved APIs** instruction section when starting, restarting,+or forking a local harness while connections exist. It preserves existing project+instructions and appends the section only once, in `AGENTS.md` (`CLAUDE.md` for+Claude, `GEMINI.md` for Gemini). The section contains commands, never credentials.+Already running harnesses can use those commands immediately:++```sh+# Discover connection IDs and public settings. Keys are never listed.+harness api list --json++# Authenticated JSON API request; the path is relative to the saved base URL.+harness api request openrouter /models+harness api request my-images /render --method POST --data @request.json++# Give a provider SDK or tool its saved key environment variable.+harness api run fal-ai -- node generate-image.mjs+```++Use the ID returned by `list`; renaming an existing connection preserves its ID.+`request` attaches the configured authentication header, returns the response+body, and exits nonzero on network/HTTP failure. It does not follow redirects.+`run` passes the selected key variable and `HARNESS_API_BASE_URL` to the child+process only; an SDK may need its base URL configured explicitly. Its arguments,+standard input/output, and exit code pass through normally.++Header-based JSON APIs work with `request`. Other protocols and authentication+schemes can use their own SDK/tool through `run`; Harness does not provide OAuth+sign-in or provider-specific polling and file-upload interfaces.++## Storage and scope++The local CLI stores keys in `api-connections/connections.json` inside its data+directory (`~/.harness/cli/data` by default), with owner-only directory/file permissions+(`0700`/`0600`). This is a local credential file, not an OS keychain. Writes are+atomic, and unreadable/corrupt storage is never silently replaced.++Management requests use the local daemon connection; remote requests are refused.+Keys are not returned to the UI, included in connection lists, copied into project+instructions, or exported into an engine's environment. An explicitly invoked+tool receives the selected credential. Connections do not sync between machines.++Preset defaults come from the providers' documentation:+[OpenRouter](https://openrouter.ai/docs/api/reference/authentication),+[fal.ai](https://fal.ai/models/fal-ai/flux/dev/api), and+[Replicate](https://replicate.com/docs/reference/http).++## Validation++```sh+cd cli+npm run typecheck+npx vitest run src/lib/apiConnections.spec.ts src/lib/apiCommand.spec.ts src/lib/apiConnectionsRpc.spec.ts++cd ../desktop+flutter test --coverage test/api_connections_test.dart test/models_panel_test.dart test/model_mark_test.dart test/model_manager_controller_test.dart+node tool/check_models_coverage.mjs+```++Backend tests use synthetic credentials and a local HTTP server. They cover+storage/rotation/removal, all preset defaults, custom authentication, child-process+isolation, HTTP success/failure/redirect handling, local-only RPCs, and instruction+preservation. UI tests cover forms, key masking, validation, search, repeated+providers, editing/removal, reconnects, stale responses, and small windows.diff --git a/docs/images/models-all.png b/docs/images/models-all.pngnew file mode 100644index 000000000..b5ca2a869Binary files /dev/null and b/docs/images/models-all.png differdiff --git a/docs/images/models-api-custom.png b/docs/images/models-api-custom.pngnew file mode 100644index 000000000..77ac3b38aBinary files /dev/null and b/docs/images/models-api-custom.png differdiff --git a/docs/images/models-apis.png b/docs/images/models-apis.pngnew file mode 100644index 000000000..d7d8841a2Binary files /dev/null and b/docs/images/models-apis.png differ