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
Discover and run local models from the Models overview (#276)
Dee988ac19bacfe
diff --git a/cli/build-bundle.mjs b/cli/build-bundle.mjsindex 717afc76a..4d5275d3f 100644--- a/cli/build-bundle.mjs+++ b/cli/build-bundle.mjs@@ -12,6 +12,9 @@import * as esbuild from 'esbuild'import { readFileSync, copyFileSync, rmSync } from 'fs'import { readDshRegistry } from './scripts/lib/dshRegistry.mjs'+import { readModelManagerBundle } from './scripts/lib/modelManagerBundle.mjs'+import { fileURLToPath } from 'node:url'+const modelManagerBundle = JSON.stringify(readModelManagerBundle(fileURLToPath(new URL('../store/agents/autonomous-grid', import.meta.url))))const version =process.env.ADAPTER_VERSION ||@@ -34,6 +37,7 @@ await esbuild.build({define: {__ADAPTER_VERSION__: JSON.stringify(version),__DSH_REGISTRY__: JSON.stringify(dshRegistry),+ __MODEL_MANAGER_BUNDLE__: JSON.stringify(modelManagerBundle),},// The copyright line is MIT's one condition — it has to travel with the copy the user actually// receives, and the published bundle IS that copy (upload-cli.sh ships `cli.js` and `notify.mjs`,diff --git a/cli/build.mjs b/cli/build.mjsindex 2d42cc4a2..533d5c546 100644--- a/cli/build.mjs+++ b/cli/build.mjs@@ -2,6 +2,9 @@ import * as esbuild from 'esbuild'import { readdirSync, statSync, readFileSync } from 'fs'import { join } from 'path'import { readDshRegistry } from './scripts/lib/dshRegistry.mjs'+import { readModelManagerBundle } from './scripts/lib/modelManagerBundle.mjs'+import { fileURLToPath } from 'node:url'+const modelManagerBundle = JSON.stringify(readModelManagerBundle(fileURLToPath(new URL('../store/agents/autonomous-grid', import.meta.url))))// Bake the version in so `node dist/cli.js version` works in the dev/per-file build too (parity with// build-bundle.mjs). The bundle build overrides this from ADAPTER_VERSION at release time.@@ -39,6 +42,7 @@ try {define: {__ADAPTER_VERSION__: JSON.stringify(version),__DSH_REGISTRY__: JSON.stringify(dshRegistry),+ __MODEL_MANAGER_BUNDLE__: JSON.stringify(modelManagerBundle),},logLevel: 'info',})diff --git a/cli/package.json b/cli/package.jsonindex 9d04685fb..712671b0f 100644--- a/cli/package.json+++ b/cli/package.json@@ -12,6 +12,7 @@"typecheck": "tsc --noEmit","start": "node dist/cli.js","test": "vitest run",+ "test:local-models": "vitest run src/lib/localModels.spec.ts src/lib/localModels.integration.spec.ts src/dsh/builtins.spec.ts src/lib/gridFleetRpc.spec.ts --coverage --coverage.include=src/lib/localModels.ts --coverage.include=src/dsh/builtins.ts --coverage.thresholds.lines=100 --coverage.thresholds.statements=100 --coverage.thresholds.functions=100 --coverage.thresholds.branches=100 --coverage.reporter=text --coverage.reporter=json-summary --coverage.reportsDirectory=coverage/local-models","test:orchestrator": "vitest run src/orchestrator --maxWorkers=1 --coverage --coverage.include='src/orchestrator/**' --coverage.thresholds.lines=100 --coverage.thresholds.statements=100 --coverage.thresholds.functions=100 --coverage.thresholds.branches=100 --coverage.reporter=text --coverage.reporter=json --coverage.reportsDirectory=coverage/orchestrator","test:dsh-updates": "vitest run --config vitest.dsh-updates.config.ts","test:sharing": "vitest run src/sharing --coverage --coverage.include='src/sharing/**' --coverage.thresholds.lines=100 --coverage.thresholds.statements=100 --coverage.thresholds.branches=100 --coverage.thresholds.functions=100",diff --git a/cli/scripts/install.sh b/cli/scripts/install.shindex 9eb944f0f..1b8ff0231 100755--- a/cli/scripts/install.sh+++ b/cli/scripts/install.sh@@ -654,6 +654,7 @@ HARNESSJSif [ "$INSTALL_MODE" != "host" ]; thenecho "▸ Installing the managed grid into $RUNTIME_DIR"install_managed_grid || echo " · the grid runtime will be fetched by the daemon on its next start"+ "$NODE_BIN" "$HOME/.harness/cli/cli.js" dsh builtins || echo " · Model Manager will be prepared on the next start"fi# 4. Ensure ~/.local/bin is on PATH (per shell), idempotently — defined up with the other helpers.diff --git a/cli/scripts/lib/modelManagerBundle.mjs b/cli/scripts/lib/modelManagerBundle.mjsnew file mode 100644index 000000000..ec34bd35e--- /dev/null+++ b/cli/scripts/lib/modelManagerBundle.mjs@@ -0,0 +1,19 @@+import { readdirSync, readFileSync, statSync } from 'node:fs'+import { join } from 'node:path'++// Ship the manager itself with the CLI. No clone, package manager, or model+// download is needed to make its conversation and viewer available.+export function readModelManagerBundle(root) {+ const files = {}+ const visit = relative => {+ const path = join(root, relative)+ const stat = statSync(path)+ if (stat.isDirectory()) {+ for (const name of readdirSync(path).sort()) visit(join(relative, name))+ } else {+ files[relative] = { content: readFileSync(path, 'utf8'), executable: Boolean(stat.mode & 0o111) }+ }+ }+ for (const path of ['harness.json', 'AGENTS.md', 'LICENSE', 'VERSIONS', 'viewer.sh', 'viewer.mjs', 'viewer', 'lib', 'toolchain', 'template', 'skills']) visit(path)+ return files+}diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.tsindex a941c35be..b075a989c 100644--- a/cli/src/backendSocket.spec.ts+++ b/cli/src/backendSocket.spec.ts@@ -19,6 +19,53 @@ import * as storeCatalog from './dsh/catalog.js'import { randomUUID } from 'node:crypto'import { fakeGridAnswers, installFakeGrid, type FakeGrid } from './lib/__fixtures__/fakeGrid.js'import { clearGridMcpUrlCache } from './lib/gridMcpUrl.js'+import { LocalModels } from './lib/localModels.js'++describe('local model lifecycle RPCs', () => {+ afterEach(() => vi.restoreAllMocks())+ it.each(['grid_fleet_models_list', 'grid_fleet_model_start', 'grid_fleet_model_stop'])('dispatches %s and returns its correlated result', async type => {+ const socket = new BackendSocket('fixture')+ socket.setHarnessGridName('home')+ const frames: any[] = []+ socket.registerLocalClient('local:models', { sendFrame: frame => { frames.push(frame); return true }, sendBinary: () => true })+ const list = vi.spyOn(LocalModels.prototype, 'list').mockResolvedValue({ models: [], busy: false, observedAt: 'fixture' })+ const act = vi.spyOn(LocalModels.prototype, 'act').mockResolvedValue({ error: 'fixture refusal' })+ socket.handleLocalFrame('local:models', { type, payload: { requestId: 'models-rpc', modelId: 'fixture/model', refresh: true } })+ await vi.waitFor(() => expect(frames.some(frame => frame.type === `${type}_result`)).toBe(true))+ expect(frames.find(frame => frame.type === `${type}_result`).payload.requestId).toBe('models-rpc')+ if (type === 'grid_fleet_models_list') expect(list).toHaveBeenCalledWith('home', true)+ else expect(act).toHaveBeenCalledWith('home', 'fixture/model', type.endsWith('start') ? 'start' : 'stop')+ await socket.stop()+ })++ it('a slow catalog never blocks terminal or agent inventory, and errors stay redacted', async () => {+ const socket = new BackendSocket('fixture')+ socket.setHarnessGridName('home')+ const frames: any[] = []+ socket.registerLocalClient('local:models', { sendFrame: frame => { frames.push(frame); return true }, sendBinary: () => true })+ let reject!: (cause: Error) => void+ vi.spyOn(LocalModels.prototype, 'list').mockReturnValue(new Promise((_resolve, fail) => { reject = fail }))+ socket.handleLocalFrame('local:models', { type: 'grid_fleet_models_list', payload: { requestId: 'catalog' } })+ socket.handleLocalFrame('local:models', { type: 'agents_list', payload: { requestId: 'agents' } })+ await vi.waitFor(() => expect(frames.some(frame => frame.type === 'agents_list_result')).toBe(true))+ expect(frames.some(frame => frame.type === 'grid_fleet_models_list_result')).toBe(false)+ reject(new Error('private-token'))+ await vi.waitFor(() => expect(frames.some(frame => frame.type === 'grid_fleet_models_list_result')).toBe(true))+ expect(frames.find(frame => frame.type === 'grid_fleet_models_list_result').payload).toMatchObject({ requestId: 'catalog', error: 'Models are unavailable. Try again.' })+ expect(JSON.stringify(frames)).not.toContain('private-token')+ await socket.stop()+ })++ it('rejects unencrypted remote lifecycle requests before reaching the model service', async () => {+ const socket = new BackendSocket('fixture')+ const act = vi.spyOn(LocalModels.prototype, 'act')+ for (const type of ['grid_fleet_model_start', 'grid_fleet_model_stop']) {+ await (socket as any).dispatchDown({ type, payload: { requestId: 'unsafe', modelId: 'fixture/model' } }, 'remote')+ }+ expect(act).not.toHaveBeenCalled()+ await socket.stop()+ })+})describe('confirmed harness pause replies', () => {it.each(['unsupported', 'unconfirmed', 'confirmed'] as const)('%s stop never sends a false success', async state => {diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.tsindex 56fadbddb..0f9d75caa 100644--- a/cli/src/backendSocket.ts+++ b/cli/src/backendSocket.ts@@ -33,6 +33,7 @@ import { listDir } from './lib/fsBrowse.js'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 { gridCapableEngines, parseGridLaunchOverride, type GridLaunchOverride } from './lib/gridLaunch.js'import { listAllGridModels, resolveGridTarget } from './lib/gridModels.js'import { deriveHarnessGridName } from './lib/gridDerive.js'@@ -363,6 +364,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 ws: WebSocket | null = nullprivate connecting = false/** A 401 on the upgrade is being answered with a token refresh; that refresh owns the next connect. */@@ -1525,6 +1527,18 @@ export class BackendSocket {try {switch (type) {+ case 'grid_fleet_models_list':+ case 'grid_fleet_model_start':+ case 'grid_fleet_model_stop': {+ // A daemon-owned operation survives panel closure and a lost reply.+ // Keep hardware/catalog/network reads off the ordered terminal queue.+ void this.resolveGridName().then(async grid => type === 'grid_fleet_models_list'+ ? this.localModels.list(grid, payload.refresh === true)+ : this.localModels.act(grid, payload.modelId, type === 'grid_fleet_model_start' ? 'start' : 'stop'))+ .then(result => reply(type, requestId, { ...result }))+ .catch(() => reply(type, requestId, { error: 'Models are unavailable. Try again.' }))+ return+ }case 'grid_fleet_capabilities':reply(type, requestId, { protocol: GRID_FLEET_PROTOCOL, gridCli: gridCliPresence(), maxTimeoutMs: GRID_FLEET_MAX_TIMEOUT_MS, thinkingControl: true })returndiff --git a/cli/src/cli.ts b/cli/src/cli.tsindex 9ee39981f..364af3eed 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -1,4 +1,5 @@#!/usr/bin/env node+import { ensureBundledModelManager } from './dsh/builtins.js'import { createDeviceStore, deviceStoreAgents } from './lib/autonomous-device/storeRuntime.js'import { mutateDsh } from './dsh/service.js'import { HarnessShareOwner } from './sharing/owner.js'@@ -1828,6 +1829,9 @@ async function runForeground(session: AuthSession | null): Promise<void> {// How long the RPCs gate on an attempt, and how many attempts there are, live in the runner —// `lib/gridAttach.ts`, beside the reconcile itself, so the coordination has a unit test rather// than only a comment. Everything below is the daemon-shaped half: what one attempt actually does.+ try { ensureBundledModelManager() }+ catch (error) { console.warn('[model-manager] Could not prepare the bundled harness:', error instanceof Error ? error.message : String(error)) }+const gridAttach = createGridAttachRunner({maxAttempts: GRID_ATTACH_MAX_ATTEMPTS,minIntervalMs: GRID_ATTACH_MIN_INTERVAL_MS,diff --git a/cli/src/cliCommand.spec.ts b/cli/src/cliCommand.spec.tsindex 3e108172e..e70d3bb33 100644--- a/cli/src/cliCommand.spec.ts+++ b/cli/src/cliCommand.spec.ts@@ -41,6 +41,13 @@ function envFor(root: string, extra: NodeJS.ProcessEnv = {}): NodeJS.ProcessEnvADAPTER_CLI_DIR: join(root, 'cli'),ADAPTER_COMPUTER_ID_FILE: join(root, 'computer-id'),ADAPTER_UPDATE_DISABLE: 'true',+ // HOME does not isolate tmux's /tmp socket. Never discover or attach to the+ // developer's real panes during a CLI startup test.+ TERMINAL_BACKENDS: 'tmux',+ TMUX: '',+ TMUX_TMPDIR: root,+ DISABLE_GRID_INSTALL: 'true',+ DISABLE_HOOK_INSTALL: 'true',// Nothing listens on port 1. A `start` asks the daemon on PORT which account it serves and would// otherwise ask this machine's REAL daemon — and the backend is where a start that decided to// (re)start goes next, which must never be the production one.@@ -110,7 +117,7 @@ describe('CLI login/start command contract', () => {const child = spawn(process.execPath, [TSX, CLI_SOURCE, 'start'], {cwd: CLI_ROOT,detached: true,- env: envFor(root, { PORT: String(20_000 + Math.floor(Math.random() * 20_000)), DISABLE_HOOK_INSTALL: '1' }),+ env: envFor(root, { PORT: String(20_000 + Math.floor(Math.random() * 20_000)) }),stdio: ['ignore', 'pipe', 'pipe'],})children.push(child)diff --git a/cli/src/dsh/builtins.spec.ts b/cli/src/dsh/builtins.spec.tsnew file mode 100644index 000000000..4fefb373c--- /dev/null+++ b/cli/src/dsh/builtins.spec.ts@@ -0,0 +1,88 @@+import { afterEach, beforeEach, expect, it, vi } from 'vitest'+import { existsSync, mkdtempSync, readFileSync, rmSync, statSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { env } from '../config/env.js'+import { ensureBundledModelManager, MODEL_MANAGER_ID } from './builtins.js'+import { installedDsh, invalidateInstalledDsh, upsertInstalledRecord } from './installed.js'+import { lockDsh } from './lock.js'++let root: string+let original: string+beforeEach(() => {+ root = mkdtempSync(join(tmpdir(), 'model-manager-bundle-'))+ original = env.DSH_DIR+ env.DSH_DIR = root+ invalidateInstalledDsh()+})+afterEach(() => {+ vi.unstubAllGlobals()+ env.DSH_DIR = original+ invalidateInstalledDsh()+ rmSync(root, { recursive: true, force: true })+})++it('uses the embedded release bundle and returns unavailable in unbundled development', () => {+ expect(ensureBundledModelManager()).toBe(false)+ expect(ensureBundledModelManager({})).toBe(false)+ vi.stubGlobal('__MODEL_MANAGER_BUNDLE__', JSON.stringify(bundle()))+ expect(ensureBundledModelManager()).toBe(true)+ expect(installedDsh(MODEL_MANAGER_ID)?.manifest.name).toBe('Model Manager')+})++it('joins a later attempt after another installer releases the package lock', () => {+ const release = lockDsh(MODEL_MANAGER_ID)!+ expect(ensureBundledModelManager(bundle())).toBe(false)+ expect(installedDsh(MODEL_MANAGER_ID)).toBeUndefined()+ release()+ expect(ensureBundledModelManager(bundle())).toBe(true)+})++it('reuses an already materialized package when restoring an older bundled revision', () => {+ ensureBundledModelManager(bundle('one'))+ const first = installedDsh(MODEL_MANAGER_ID)!+ ensureBundledModelManager(bundle('two'))+ expect(ensureBundledModelManager(bundle('one'))).toBe(true)+ expect(installedDsh(MODEL_MANAGER_ID)?.dir).toBe(first.dir)+})++it.each(['not json', JSON.stringify({ spec: 1, id: 'other/package', name: 'Wrong', engine: 'codex' })])('rejects an invalid embedded manifest and releases its lock', content => {+ expect(() => ensureBundledModelManager({ ...bundle(), 'harness.json': { content, executable: false } })).toThrow('Invalid bundled Model Manager')+ expect(installedDsh(MODEL_MANAGER_ID)).toBeUndefined()+ expect(ensureBundledModelManager(bundle())).toBe(true)+})+const bundle = (instructions = 'Help with local models') => ({+ 'harness.json': { content: JSON.stringify({ spec: 1, id: MODEL_MANAGER_ID, name: 'Model Manager', engine: 'codex' }), executable: false },+ 'AGENTS.md': { content: instructions, executable: false },+ 'toolchain/fleet': { content: '#!/bin/sh\nexit 0\n', executable: true },+})++it('installs offline, preserves executable files, and reuses the installed version', () => {+ expect(ensureBundledModelManager(bundle())).toBe(true)+ const first = installedDsh(MODEL_MANAGER_ID)!+ expect(first.manifest.name).toBe('Model Manager')+ expect(statSync(join(first.dir, 'toolchain/fleet')).mode & 0o777).toBe(0o700)+ expect(ensureBundledModelManager(bundle())).toBe(true)+ expect(installedDsh(MODEL_MANAGER_ID)?.dir).toBe(first.dir)+})++it('updates the bundled version without deleting resources a running manager uses', () => {+ ensureBundledModelManager(bundle('version one'))+ const first = installedDsh(MODEL_MANAGER_ID)!+ ensureBundledModelManager(bundle('version two'))+ const second = installedDsh(MODEL_MANAGER_ID)!+ expect(second.dir).not.toBe(first.dir)+ expect(readFileSync(join(second.dir, 'AGENTS.md'), 'utf8')).toBe('version two')+ expect(existsSync(join(first.dir, 'AGENTS.md'))).toBe(true)+})++it('keeps a developer linked package and refuses invalid bundled paths', () => {+ expect(() => ensureBundledModelManager({ ...bundle(), '../escape': { content: 'no', executable: false } })).toThrow('Invalid built-in package path')+ expect(installedDsh(MODEL_MANAGER_ID)).toBeUndefined()+ ensureBundledModelManager(bundle())+ const first = installedDsh(MODEL_MANAGER_ID)!+ upsertInstalledRecord({ ...first, linked: true, source: '/my/checkout' })+ expect(ensureBundledModelManager(bundle('release update'))).toBe(true)+ expect(installedDsh(MODEL_MANAGER_ID)?.source).toBe('/my/checkout')+ expect(readFileSync(join(first.dir, 'AGENTS.md'), 'utf8')).toBe('Help with local models')+})diff --git a/cli/src/dsh/builtins.ts b/cli/src/dsh/builtins.tsnew file mode 100644index 000000000..b6f3f3770--- /dev/null+++ b/cli/src/dsh/builtins.ts@@ -0,0 +1,46 @@+import { createHash, randomUUID } from 'node:crypto'+import { existsSync, mkdirSync, renameSync, rmSync, writeFileSync } from 'node:fs'+import { dirname, join } from 'node:path'+import { dshRootDir, installedDsh, upsertInstalledRecord } from './installed.js'+import { lockDsh } from './lock.js'+import { readDshManifest } from './manifest.js'++declare const __MODEL_MANAGER_BUNDLE__: string+export const MODEL_MANAGER_ID = 'autonomous/autonomous-grid'+type BundledFiles = Record<string, { content: string; executable: boolean }>++/** Install the trusted, release-bundled harness. Runtime provisioning remains+ * owned by the existing managed Grid installer. Versioned package directories+ * keep running managers intact while a newer CLI installs its own resources. */+export function ensureBundledModelManager(files?: BundledFiles): boolean {+ files ??= typeof __MODEL_MANAGER_BUNDLE__ === 'string' ? JSON.parse(__MODEL_MANAGER_BUNDLE__) as BundledFiles : undefined+ if (!files || !files['harness.json']) return false+ const current = installedDsh(MODEL_MANAGER_ID)+ // A developer's linked checkout is theirs. Never replace it with release files.+ if (current?.linked) return true+ const revision = createHash('sha256').update(JSON.stringify(files)).digest('hex')+ if (current?.source === 'builtin:model-manager' && current.revision === revision) return true+ const unlock = lockDsh(MODEL_MANAGER_ID)+ if (!unlock) return false+ const dir = join(dshRootDir(), '.bundled', 'model-manager', revision)+ const staging = `${dir}.${randomUUID()}.tmp`+ try {+ if (!existsSync(dir)) {+ for (const [path, file] of Object.entries(files)) {+ if (!path || path.startsWith('/') || path.split(/[\\/]/).includes('..')) throw new Error('Invalid built-in package path')+ const destination = join(staging, path)+ mkdirSync(dirname(destination), { recursive: true, mode: 0o700 })+ writeFileSync(destination, file.content, { mode: file.executable ? 0o700 : 0o600 })+ }+ const manifest = readDshManifest(staging)+ if (!manifest.ok || manifest.manifest.id !== MODEL_MANAGER_ID) throw new Error('Invalid bundled Model Manager')+ renameSync(staging, dir)+ }+ upsertInstalledRecord({ id: MODEL_MANAGER_ID, dir, source: 'builtin:model-manager', ref: null,+ commit: null, revision, linked: false, installedAt: current?.installedAt ?? Date.now(), updatedAt: Date.now() })+ return true+ } finally {+ rmSync(staging, { recursive: true, force: true })+ unlock()+ }+}diff --git a/cli/src/dsh/command.ts b/cli/src/dsh/command.tsindex 803a3822b..1bc998a82 100644--- a/cli/src/dsh/command.ts+++ b/cli/src/dsh/command.ts@@ -2,6 +2,7 @@* `harness dsh …` — the terminal face of domain-specific harnesses, for a server with no desktop* and for the development loop (`--link` a checkout, iterate, no re-clone).*/+import { ensureBundledModelManager } from './builtins.js'import { listDshState, installedDsh } from './installed.js'import { DSH_ID_RE, dshTier } from './manifest.js'import { registrySourceUrl } from './registry.js'@@ -35,6 +36,8 @@ export async function dshCommand(verb: string | undefined, rest: readonly stringconst valued = new Set(['--ref', '--path'])const args = rest.filter((arg, at) => !arg.startsWith('-') && !valued.has(rest[at - 1] ?? ''))switch (verb) {+ case 'builtins':+ return ensureBundledModelManager() ? 0 : 1case 'list': {const { installed, broken } = listDshState()const registry = await refreshDshRegistry()diff --git a/cli/src/lib/e2ee/applicationFrames.ts b/cli/src/lib/e2ee/applicationFrames.tsindex 31e818d96..a35cf8d36 100644--- a/cli/src/lib/e2ee/applicationFrames.ts+++ b/cli/src/lib/e2ee/applicationFrames.ts@@ -11,7 +11,8 @@ import { ENCRYPTED_RPC_RESULT_TYPES, isEncryptedDownType } from './core.js'import { SHARE_REQUEST_TYPES, SHARE_RESULT_TYPES } from '../../sharing/protocol.js'import { VIEWER_DOWN_TYPES } from '../viewerWire.js'-const FLEET_REQUESTS = new Set(['grid_fleet_capabilities', 'grid_fleet_run', 'grid_fleet_cancel'])+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`))export const encryptDownFrame = (type: string): boolean =>isEncryptedDownType(type) || (type === 'git_project_info' || type === 'git_pull_request') || FLEET_REQUESTS.has(type) || SHARE_REQUEST_TYPES.has(type) || VIEWER_DOWN_TYPES.has(type)diff --git a/cli/src/lib/gridFleetRpc.ts b/cli/src/lib/gridFleetRpc.tsindex f8555f50c..5db78b430 100644--- a/cli/src/lib/gridFleetRpc.ts+++ b/cli/src/lib/gridFleetRpc.ts@@ -46,7 +46,7 @@ export class GridFleetRpc {return !!job}- async run(owner: string, id: string, request: GridFleetRequest): Promise<GridFleetResult> {+ async run(owner: string, id: string, request: GridFleetRequest, onOutput?: (chunk: string) => void, maxOutput = MAX_OUTPUT): Promise<GridFleetResult> {const fail = (code: number, error: string): GridFleetResult => ({ ok: false, code, stdout: '', stderr: '', error })if (!owner || !/^[a-zA-Z0-9_-]{1,100}$/.test(id)) return fail(2, 'Invalid Grid request identity.')const key = JSON.stringify([owner, id])@@ -77,8 +77,9 @@ export class GridFleetRpc {const capture = (which: 'stdout' | 'stderr', chunk: string) => {if (stopped) returnoutput[which].append(chunk)- if (Buffer.byteLength(output.stdout.text) + Buffer.byteLength(output.stderr.text) > MAX_OUTPUT) {- stop('Grid output exceeded 512 KiB; use a narrower query.'); return+ onOutput?.(chunk)+ if (Buffer.byteLength(output.stdout.text) + Buffer.byteLength(output.stderr.text) > maxOutput) {+ stop(`Grid output exceeded ${maxOutput / 1024} KiB; use a narrower query.`); return}}child.stdout.setEncoding('utf8').on('data', (data: string) => capture('stdout', data))diff --git a/cli/src/lib/localModels.integration.spec.ts b/cli/src/lib/localModels.integration.spec.tsnew file mode 100644index 000000000..67f2115f9--- /dev/null+++ b/cli/src/lib/localModels.integration.spec.ts@@ -0,0 +1,85 @@+import { it, expect } from 'vitest'+import { createServer } from 'node:http'+import { mkdtemp, mkdir, writeFile, readFile, rm, stat } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { LocalModels } from './localModels.js'++it('discovers, downloads, starts, verifies, stops and restarts across real subprocesses and HTTP', async () => {+ const root = await mkdtemp(join(tmpdir(), 'models-pipeline-'))+ const gridHome = join(root, 'grid-home'), stateDir = join(root, 'state')+ const modelId = 'fixture/Tiny-GGUF'+ let replies = 0, catalogReads = 0+ const server = createServer(async (req, res) => {+ const chunks: Buffer[] = []+ for await (const chunk of req) chunks.push(Buffer.from(chunk))+ const body = JSON.parse(Buffer.concat(chunks).toString())+ res.setHeader('content-type', 'application/json')+ if (req.url === '/v1/grid/catalog') {+ expect(req.headers.authorization).toBe('Bearer catalog-fixture')+ expect(body.device.usable_bytes).toBe(16 * 1024 ** 3)+ catalogReads+++ res.end(JSON.stringify({ models: [{ repo_id: modelId, runnable: true, task: 'text-generation', format: 'GGUF',+ fit: { version: 'Q4', ctx: 4096 }, versions: [{ version: 'Q4', size_bytes: 64, pull_spec: `${modelId}:tiny.gguf` }] }] }))+ } else {+ expect(req.url).toBe('/v1/chat/completions')+ expect(req.headers.authorization).toBe('Bearer inference-fixture')+ expect(body).toMatchObject({ model: 'tiny.gguf', max_tokens: 8 })+ replies+++ res.end(JSON.stringify({ choices: [{ message: { content: 'ok' } }] }))+ }+ })+ await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve))+ const address = server.address() as { port: number }+ const base = `http://127.0.0.1:${address.port}`+ let service: LocalModels | undefined+ try {+ await mkdir(gridHome)+ await writeFile(join(gridHome, 'credentials.toml'), `session_token = 'catalog-fixture'\napi_url = '${base}'\n`)+ const executable = join(root, 'grid.mjs')+ await writeFile(executable, `#!${process.execPath}+import { mkdirSync, writeFileSync, appendFileSync, existsSync, rmSync } from 'node:fs';+import { join } from 'node:path';+const home = process.env.GRID_HOME, args = process.argv.slice(2);+const recordDir = join(home, 'run', 'engines', 'fixture-grid');+const record = join(recordDir, 'remote.json');+appendFileSync(join(home, 'calls.jsonl'), JSON.stringify(args) + '\\n');+const result = value => console.log(JSON.stringify(value));+if (args[0] === 'device-info') result({ usable_bytes: 16 * 1024 ** 3, device_class: 'cpu', backend: 'cpu', memory: { total_gb: 16 } });+else if (args.includes('ls')) result([{ grid: 'home', id: 'fixture-grid' }]);+else if (args.includes('engines')) result(existsSync(record) ? [{ node_id: 'fixture-node', online: true, models: ['tiny.gguf'] }] : []);+else if (args[0] === 'pull') { mkdirSync(join(home, 'models'), { recursive: true }); process.stderr.write('42%\\r100%\\n'); writeFileSync(join(home, 'models', 'tiny.gguf'), Buffer.alloc(64)); }+else if (args[0] === 'engine') { mkdirSync(join(home, 'bin'), { recursive: true }); writeFileSync(join(home, 'bin', 'llama-server'), '#!/bin/sh\\nexit 0\\n', { mode: 0o700 }); }+else if (args.includes('join')) { mkdirSync(recordDir, { recursive: true }); writeFileSync(record, JSON.stringify({ node_id: 'fixture-node', engines: [{ models: ['tiny.gguf'] }] })); writeFileSync(join(recordDir, 'remote.heartbeat'), ''); }+else if (args.includes('leave')) rmSync(record);+else if (args.includes('info')) console.log("export OPENAI_BASE_URL='${base}/v1'\\nexport OPENAI_API_KEY='inference-fixture'");+else process.exitCode = 2;+`, { mode: 0o700 })+ const options = { stateDir, processEnv: { GRID_HOME: gridHome, HARNESS_GRID_BIN: executable, PATH: root } }+ service = new LocalModels(options)+ expect((await service.list('home')).models[0]).toMatchObject({ state: 'available', canStart: true })+ expect(replies).toBe(0)+ await service.act('home', modelId, 'start'); await service.settled()+ expect((await service.list('home')).models[0]).toMatchObject({ state: 'running', canStop: true, operation: { phase: 'done' } })+ expect(replies).toBe(1)+ // A fresh client/service can recover the completed status from disk.+ service = new LocalModels(options)+ expect((await service.list('home')).models[0].operation?.phase).toBe('done')+ await service.act('home', modelId, 'stop'); await service.settled()+ expect((await service.list('home')).models[0].state).toBe('downloaded')+ expect((await stat(join(gridHome, 'models', 'tiny.gguf'))).size).toBe(64)+ await service.act('home', modelId, 'start'); await service.settled()+ expect((await service.list('home')).models[0].state).toBe('running')+ const calls = (await readFile(join(gridHome, 'calls.jsonl'), 'utf8')).trim().split('\n').map(line => JSON.parse(line) as string[])+ expect(calls.filter(args => args[0] === 'pull')).toHaveLength(1)+ expect(calls.filter(args => args[0] === 'engine')).toHaveLength(1)+ expect(calls.find(args => args.includes('leave'))).toEqual(['--remote', 'leave', 'home', '--engine', 'tiny.gguf'])+ expect(catalogReads).toBeGreaterThan(1)+ expect(replies).toBe(2)+ } finally {+ await service?.settled()+ server.closeAllConnections()+ await new Promise<void>(resolve => server.close(() => resolve()))+ await rm(root, { recursive: true, force: true })+ }+}, 20_000)diff --git a/cli/src/lib/localModels.spec.ts b/cli/src/lib/localModels.spec.tsnew file mode 100644index 000000000..9e6d03a9f--- /dev/null+++ b/cli/src/lib/localModels.spec.ts@@ -0,0 +1,616 @@+import { afterEach, beforeEach, describe, expect, it, vi, type Mock } from 'vitest'+import { mkdtemp, mkdir, writeFile, readFile, readdir, rm, stat } from 'node:fs/promises'+import { join } from 'node:path'+import { tmpdir } from 'node:os'+import { createHash } from 'node:crypto'+import { rmSync, writeFileSync } from 'node:fs'+import { compatibleModels, LocalModels } from './localModels.js'+import { GridFleetRpc, type GridFleetResult } from './gridFleetRpc.js'+import { encryptDownFrame, encryptRpcResult } from './e2ee/applicationFrames.js'++const card = (id = 'org/Small-GGUF') => ({ repo_id: id, runnable: true, task: 'text-generation', format: 'GGUF',+ fit: { version: 'Q4', ctx: 32768, size: 64 },+ versions: [{ version: 'Q4', size_bytes: 64, pull_spec: `${id}:Small-Q4.gguf`, urls: ['https://example.test/Small-Q4.gguf'] }] })+const ok = (value: unknown = {}) => ({ ok: true, code: 0, stdout: JSON.stringify(value), stderr: '', error: null })+const response = (body: unknown) => new Response(JSON.stringify(body), { status: 200, headers: { 'content-type': 'application/json' } })+let root: string, home: string, stateDir: string, records: string+let calls: string[][], serving: boolean, catalogCards: ReturnType<typeof card>[], service: LocalModels+let request: Mock<(url: string | URL, init?: RequestInit) => Promise<Response>>+let run: Mock<(args: string[], output?: (s: string) => void) => Promise<GridFleetResult>>+let downloadFails: boolean, catalogFails: boolean+beforeEach(async () => {+ root = await mkdtemp(join(tmpdir(), 'local-models-'))+ home = join(root, 'grid'); stateDir = join(root, 'receipts'); records = join(home, 'run', 'engines', 'grid-home')+ await mkdir(records, { recursive: true }); await mkdir(join(home, 'models'))+ await writeFile(join(home, 'credentials.toml'), 'session_token = "test-only-token"\napi_url = "https://catalog.example.test"\n')+ calls = []; serving = false; catalogCards = [card()]; downloadFails = false; catalogFails = false+ run = vi.fn(async (args: string[], output?: (s: string) => void) => {+ calls.push(args)+ if (args[0] === 'device-info') return ok({ device_class: 'apple-silicon', backend: 'metal', usable_bytes: 54 * 1024 ** 3, memory: { total_gb: 64 } })+ if (args.includes('ls')) return ok([{ grid: 'home', id: 'grid-home' }])+ if (args.includes('engines')) return ok(serving ? [{ node_id: 'local-node', online: true, models: ['Small-Q4.gguf'], throughput_tok_s: 17.6,+ vram_used_mb: 99999, answered: { window_seconds: 3600, requests: 4, by_model: [{ model: 'Small-Q4.gguf', requests: 4 }] } }] : [])+ if (args[0] === 'pull') {+ output?.('42%')+ if (downloadFails) return { ...ok(), ok: false, code: 1 }+ await writeFile(join(home, 'models', 'Small-Q4.gguf'), Buffer.alloc(64))+ }+ if (args[0] === 'engine' && args[1] === 'install') {+ await mkdir(join(home, 'bin'), { recursive: true })+ await writeFile(join(home, 'bin', 'llama-server'), '#!/bin/sh\nexit 0\n', { mode: 0o755 })+ }+ if (args.includes('join')) {+ serving = true+ await writeFile(join(records, 'remote.json'), JSON.stringify({ node_id: 'local-node', engines: [{ endpoint_url: null, models: ['Small-Q4.gguf'] }], advertise_as: [] }))+ await writeFile(join(records, 'remote.heartbeat'), '')+ }+ if (args.includes('leave')) { serving = false; await rm(join(records, 'remote.json'), { force: true }) }+ if (args.includes('info')) return { ...ok(), stdout: "export OPENAI_BASE_URL='https://inference.example.test/v1'\nexport OPENAI_API_KEY='test-inference-token'\n" }+ return ok()+ })+ request = vi.fn(async (url: string | URL, _init?: RequestInit) => {+ if (String(url).includes('/catalog')) {+ if (catalogFails) throw new Error('private raw error must never escape')+ return response({ models: catalogCards, runnable_total: catalogCards.length, pagination: { page: 1, total_pages: 1 } })+ }+ return response({ choices: [{ message: { content: 'ok' } }] })+ })+ service = new LocalModels({ stateDir, processEnv: { GRID_HOME: home }, run, request: request as typeof fetch })+})+afterEach(async () => { await service.settled(); vi.useRealTimers(); vi.restoreAllMocks(); vi.unstubAllEnvs(); vi.unstubAllGlobals(); await rm(root, { recursive: true, force: true }) })++describe('local model discovery and lifecycle', () => {+ it('inspects silently and offers only confirmed compatible chat models', async () => {+ expect(compatibleModels([card()])).toEqual([])+ expect(compatibleModels({ models: [card(), { ...card('no'), runnable: false }, { ...card('image'), task: 'image-generation' }] })).toHaveLength(1)+ const snapshot = await service.list('home')+ expect(snapshot.models).toMatchObject([{ name: 'Small', state: 'available', sizeBytes: 64, canStart: true, canStop: false }])+ expect(snapshot.memoryBytes).toBe(64 * 1024 ** 3)+ expect(calls.some(args => ['pull', 'join', 'leave', 'install'].some(a => args.includes(a)))).toBe(false)+ expect(JSON.stringify(snapshot)).not.toContain('test-only-token')+ })++ it('paginates all compatible models and does not fetch incompatible trailing pages', async () => {+ request.mockImplementation(async (_url, init) => {+ const page = JSON.parse(String(init?.body)).page+ return response({ models: [card(`org/Model${page}-GGUF`)], runnable_total: 2, pagination: { page, total_pages: 7 } })+ })+ expect((await service.list('home')).models).toHaveLength(2)+ expect(request).toHaveBeenCalledTimes(2)+ })++ it('rejects catalog pagination that repeats a page', async () => {+ request.mockResolvedValue(response({ models: [card()], runnable_total: 100, pagination: { page: 1, total_pages: 7 } }))+ // Fresh Response objects (bodies are single-consumption).+ request.mockImplementation(async () => response({ models: [card()], runnable_total: 100, pagination: { page: 1, total_pages: 7 } }))+ expect((await service.list('home')).error).toContain('incomplete')+ })++ it('downloads, loads and verifies without another user step', async () => {+ const ack = await service.act('home', 'org/Small-GGUF', 'start')+ expect(ack.operation?.phase).toBe('running')+ await service.settled()+ const snapshot = await service.list('home')+ expect(snapshot.models[0]).toMatchObject({ state: 'running', canStop: true,+ tokensPerSecond: 17.6, requests: 4, windowSeconds: 3600, operation: { phase: 'done', stage: 'verifying' } })+ expect(snapshot.models[0]).not.toHaveProperty('memoryBytes')+ expect(calls.find(args => args.includes('join'))).toEqual(['--remote', 'join', 'home', '--serve', 'Small-Q4.gguf', '--max-concurrency', '1', '--ctx-size', '16384', '--reasoning-budget', '0'])+ expect(request.mock.calls.some(([url]) => String(url).includes('chat/completions'))).toBe(true)+ expect(await readFile(join(stateDir, (await readdir(stateDir))[0]), 'utf8')).not.toContain('token')+ })++ it('uses an already downloaded complete file, and Stop retains it', async () => {+ await writeFile(join(home, 'models', 'Small-Q4.gguf'), Buffer.alloc(64))+ expect((await service.list('home')).models[0].state).toBe('downloaded')+ await service.act('home', 'org/Small-GGUF', 'start'); await service.settled()+ expect(calls.some(args => args[0] === 'pull')).toBe(false)+ await service.act('home', 'org/Small-GGUF', 'stop'); await service.settled()+ expect(calls.find(args => args.includes('leave'))).toEqual(['--remote', 'leave', 'home', '--engine', 'Small-Q4.gguf'])+ expect((await stat(join(home, 'models', 'Small-Q4.gguf'))).size).toBe(64)+ expect((await service.list('home')).models[0]).toMatchObject({ state: 'downloaded', canStop: false, canStart: true })+ })++ it('reuses the installed engine on subsequent starts', async () => {+ await service.act('home', 'org/Small-GGUF', 'start'); await service.settled()+ await service.act('home', 'org/Small-GGUF', 'stop'); await service.settled()+ await service.act('home', 'org/Small-GGUF', 'start'); await service.settled()+ expect(calls.filter(args => args[0] === 'engine' && args[1] === 'install')).toHaveLength(1)+ expect(calls.filter(args => args[0] === 'pull')).toHaveLength(1)+ })++ it('does not count partial files as downloaded', async () => {+ await writeFile(join(home, 'models', 'Small-Q4.gguf'), Buffer.alloc(12))+ await writeFile(join(home, 'models', 'Small-Q4.gguf.part'), Buffer.alloc(64))+ expect((await service.list('home')).models[0].state).toBe('available')+ await service.act('home', 'org/Small-GGUF', 'start'); await service.settled()+ expect(calls.some(args => args[0] === 'pull')).toBe(true)+ })++ it('joins repeated clicks, serializes other models, and keeps status independent of its caller', async () => {+ let release!: () => void+ const barrier = new Promise<void>(resolve => { release = resolve })+ const original = request.getMockImplementation()!+ request.mockImplementation(async (url, init) => { if (String(url).includes('chat/completions')) await barrier; return original(url, init) })+ const first = await service.act('home', 'org/Small-GGUF', 'start')+ const second = await service.act('home', 'org/Small-GGUF', 'start')+ expect(second.operation?.id).toBe(first.operation?.id)+ expect((await service.act('home', 'other', 'start')).error).toContain('Wait')+ await vi.waitFor(() => expect(request.mock.calls.some(([url]) => String(url).includes('chat/completions'))).toBe(true))+ expect((await service.list('home')).models[0].operation).toMatchObject({ stage: 'verifying', phase: 'running' })+ release(); await service.settled()+ expect(calls.filter(args => args.includes('join'))).toHaveLength(1)+ })++ it('reports a failed download and retries it without starting an incomplete model', async () => {+ downloadFails = true+ await service.act('home', 'org/Small-GGUF', 'start'); await service.settled()+ expect((await service.list('home')).models[0].operation).toMatchObject({ phase: 'failed', error: 'The download stopped. Start again to resume.' })+ expect(calls.some(args => args.includes('join'))).toBe(false)+ downloadFails = false+ await service.act('home', 'org/Small-GGUF', 'start'); await service.settled()+ expect((await service.list('home')).models[0].operation?.phase).toBe('done')+ })++ it('never offers Stop for an external endpoint or another machine', async () => {+ serving = true+ await writeFile(join(records, 'remote.json'), JSON.stringify({ node_id: 'local-node', engines: [{ endpoint_url: 'http://localhost:1234', models: ['Small-Q4.gguf'] }] }))+ await writeFile(join(records, 'remote.heartbeat'), '')+ const snapshot = await service.list('home')+ expect(snapshot.models[0].canStop).toBe(false)+ await service.act('home', 'org/Small-GGUF', 'stop'); await service.settled()+ expect(calls.some(args => args.includes('leave'))).toBe(false)+ })++ it('keeps existing local engines visible when the catalog cannot be reached', async () => {+ await service.act('home', 'org/Small-GGUF', 'start'); await service.settled()+ catalogFails = true+ const fresh = new LocalModels({ stateDir, processEnv: { GRID_HOME: home }, run, request: request as typeof fetch })+ const snapshot = await fresh.list('home')+ expect(snapshot.models[0]).toMatchObject({ state: 'running', canStop: true })+ expect(snapshot.error).toContain('unavailable')+ expect(JSON.stringify(snapshot)).not.toContain('private raw')+ })++ it('does not silently evict an existing model to fit the next one', async () => {+ await service.act('home', 'org/Small-GGUF', 'start'); await service.settled()+ const next = card('org/Next-GGUF'); next.versions[0].pull_spec = 'org/Next-GGUF:Next.gguf'; next.versions[0].urls = ['https://example.test/Next.gguf']+ catalogCards = [card(), next]+ await service.list('home', true)+ request.mockImplementation(async (_url, init) => response({ models: JSON.parse(String(init?.body)).device.usable_bytes < 54 * 1024 ** 3 ? [] : catalogCards, pagination: { total_pages: 1 } }))+ await service.act('home', 'org/Next-GGUF', 'start'); await service.settled()+ const snapshot = await service.list('home')+ expect(snapshot.models.find(m => m.id === 'org/Next-GGUF')?.operation?.error).toContain('Stop Small-Q4 first')+ expect(calls.some(args => args.includes('leave'))).toBe(false)+ })++ it('rejects arbitrary model ids without passing them to Grid', async () => {+ await service.act('home', '--serve /arbitrary', 'start'); await service.settled()+ expect(calls.some(args => args.includes('--serve /arbitrary'))).toBe(false)+ expect(calls.some(args => args[0] === 'pull')).toBe(false)+ })++ it('imports an existing local setup, keeps it after Stop, and can start it again', async () => {+ catalogCards = []+ serving = true+ await writeFile(join(home, 'models', 'Small-Q4.gguf'), Buffer.alloc(64))+ await writeFile(join(records, 'remote.json'), JSON.stringify({ node_id: 'local-node', meta_name: 'This computer', ctx_size: 8192,+ engines: [{ endpoint_url: null, models: ['Small-Q4.gguf'] }], advertise_as: ['Small-Q4.gguf'] }))+ await writeFile(join(records, 'remote.heartbeat'), '')+ const first = await service.list('home')+ expect(first.models[0]).toMatchObject({ id: 'local:Small-Q4.gguf', state: 'running', canStop: true })+ await service.act('home', first.models[0].id, 'stop'); await service.settled()+ const fresh = new LocalModels({ stateDir, processEnv: { GRID_HOME: home }, run, request: request as typeof fetch })+ expect((await fresh.list('home')).models[0]).toMatchObject({ state: 'downloaded', canStart: true })+ await fresh.act('home', first.models[0].id, 'start'); await fresh.settled()+ expect(calls.some(args => args[0] === 'pull')).toBe(false)+ expect((await fresh.list('home')).models[0].operation?.phase).toBe('done')+ })++ it('reuses an already downloaded fitting quant of the same model', async () => {+ catalogCards[0].versions.push({ version: 'Q3', size_bytes: 48, pull_spec: 'org/Small-GGUF:Small-Q3.gguf', urls: ['https://example.test/Small-Q3.gguf'] })+ await writeFile(join(home, 'models', 'Small-Q3.gguf'), Buffer.alloc(48))+ const snapshot = await service.list('home')+ expect(snapshot.models[0]).toMatchObject({ state: 'downloaded', sizeBytes: 48, quant: 'Q3' })+ })++ it('matches the current CLI engine shape without attributing another model’s requests', async () => {+ await service.act('home', 'org/Small-GGUF', 'start'); await service.settled()+ const record = JSON.parse(await readFile(join(records, 'remote.json'), 'utf8'))+ record.meta_name = 'My laptop'+ await writeFile(join(records, 'remote.json'), JSON.stringify(record))+ const original = run.getMockImplementation()!+ run.mockImplementation(async (args, output) => args.includes('engines') ? ok([{+ name: 'My laptop', online: true, models: ['Small-Q4.gguf'], throughput_tok_s: 12,+ answered: { requests: 99, window_seconds: 86400, by_model: [{ model: 'prior-model', requests: 99 }] },+ }]) : original(args, output))+ const view = await service.list('home')+ expect(view.models[0]).toMatchObject({ state: 'running', tokensPerSecond: 12 })+ expect(view.models[0].requests).toBeUndefined()+ })++ it('encrypts inventory and lifecycle requests and responses', () => {+ for (const type of ['grid_fleet_models_list', 'grid_fleet_model_start', 'grid_fleet_model_stop']) {+ expect(encryptDownFrame(type)).toBe(true); expect(encryptRpcResult(`${type}_result`)).toBe(true)+ }+ })++ it('coalesces discovery, caches it briefly, and isolates different accounts', async () => {+ const [first, duplicate, other] = await Promise.all([service.list('home'), service.list('home'), service.list('other')])+ expect(duplicate).toEqual(first)+ expect(other.busy).toBe(false)+ expect(calls.filter(args => args[0] === 'device-info')).toHaveLength(1)+ const before = calls.length+ expect(await service.list('other')).toEqual(other)+ expect(calls).toHaveLength(before)+ await service.list('home', true)+ expect(calls.filter(args => args[0] === 'device-info')).toHaveLength(2)+ expect(await service.list(null)).toMatchObject({ models: [], busy: false, error: expect.stringContaining('Sign in') })+ expect((await service.act(null, 'x', 'start')).error).toBeTruthy()+ expect((await service.act('home', {}, 'start')).error).toBeTruthy()+ })++ it.each([+ ['missing credentials', ''],+ ['no session token', 'api_url = "https://catalog.example.test"'],+ ['malformed token', 'session_token = "invalid\\q"'],+ ])('reports sign-in for %s without sending credentials', async (_name, credentials) => {+ await writeFile(join(home, 'credentials.toml'), credentials)+ expect((await service.list('home')).error).toContain('Sign in')+ expect(request).not.toHaveBeenCalled()+ })++ it.each(['http://catalog.example.test', 'file:///tmp/catalog'])('refuses insecure catalog address %s', async base => {+ await writeFile(join(home, 'credentials.toml'), `session_token = 'private'\napi_url = '${base}'`)+ expect((await service.list('home')).error).toContain('address')+ expect(request).not.toHaveBeenCalled()+ })++ it.each(['http://localhost:1234', 'http://127.0.0.1:1234', 'http://[::1]:1234'])('permits an explicitly configured local catalog at %s', async base => {+ await writeFile(join(home, 'credentials.toml'), `session_token = 'test-only-token'\napi_url = '${base}'`)+ expect((await service.list('home')).error).toBeUndefined()+ expect(String(request.mock.calls[0][0])).toBe(`${base}/v1/grid/catalog`)+ expect(request.mock.calls[0][1]).toMatchObject({ redirect: 'error' })+ })++ it.each([undefined, 'https://alternate.example.test'])('uses the configured or default catalog when the credential store omits it', async base => {+ await writeFile(join(home, 'credentials.toml'), 'session_token = "test-only-token"\n')+ service = new LocalModels({ stateDir, processEnv: { GRID_HOME: home, GRID_CONTROL_PLANE_URL: base }, run, request: request as typeof fetch })+ await service.list('home')+ expect(String(request.mock.calls[0][0])).toBe(`${base ?? 'https://api-grid.autonomous.ai'}/v1/grid/catalog`)+ })++ it.each(['http failure', 'missing rows', 'empty intermediate page', 'unbounded pages'])('handles a catalog %s without inventing compatibility', async scenario => {+ request.mockImplementation(async (_url, init) => {+ const page = JSON.parse(String(init?.body)).page+ return scenario === 'http failure' ? new Response('private detail', { status: 401 })+ : response(scenario === 'missing rows' ? { error: 'private detail' }+ : { models: scenario === 'empty intermediate page' ? [] : [card()], pagination: { page, total_pages: 101 } })+ })+ const snapshot = await service.list('home')+ expect(snapshot.models).toEqual([])+ expect(snapshot.error).toBeTruthy()+ expect(JSON.stringify(snapshot)).not.toContain('private detail')+ expect(request.mock.calls.length).toBeLessThanOrEqual(100)+ })++ it('supports an unpaginated catalog, prefers a useful small download, and skips unfitted versions', async () => {+ const large = card('org/Large-GGUF'), small = card('org/Fast-GGUF')+ large.versions[0].size_bytes = 20 * 1024 ** 3+ small.versions[0].size_bytes = 2 * 1024 ** 3+ small.versions.push({ ...small.versions[0], version: 'Q8', size_bytes: 4 * 1024 ** 3 })+ small.versions.push({ ...small.versions[0], version: 'unknown', size_bytes: undefined as any })+ request.mockImplementation(async () => response({ models: [large, small] }))+ expect((await service.list('home')).models.map(m => [m.name, m.recommended])).toEqual([['Fast', true], ['Large', false]])+ })++ it.each(['failed command', 'invalid json'])('disables actions when inventory returns %s', async scenario => {+ await service.list('home')+ const original = run.getMockImplementation()!+ run.mockImplementation(async (args, output) => args.includes('engines')+ ? { ...ok(), ok: scenario !== 'failed command', stdout: 'not json' } : original(args, output))+ const snapshot = await service.list('home', true)+ expect(snapshot.error).toContain('Running models could not be checked')+ expect(snapshot.models.every(m => !m.canStart && !m.canStop)).toBe(true)+ })++ it.each(['missing grid', 'invalid grid id', 'missing record directory', 'corrupt record'])('ignores %s without exposing a Stop action', async scenario => {+ const original = run.getMockImplementation()!+ if (scenario === 'missing grid' || scenario === 'invalid grid id') {+ run.mockImplementation(async (args, output) => args.includes('ls') ? ok(scenario === 'missing grid' ? [] : [{ grid: 'home', id: '../escape' }]) : original(args, output))+ } else if (scenario === 'missing record directory') await rm(records, { recursive: true })+ else await writeFile(join(records, 'broken.json'), 'not-json')+ expect((await service.list('home')).models[0].canStop).toBe(false)+ expect((await service.list('-invalid', true)).models[0].canStop).toBe(false)+ })++ it.each([+ {}, { engines: [{ models: ['--bad.gguf'] }] }, { engines: [{ models: ['file.bin'] }] },+ { engines: [{ api_kind: 'openai', models: ['Small-Q4.gguf'] }] },+ { engines: [{ models: ['one.gguf', 'two.gguf'] }] },+ ])('does not treat an unowned or malformed run record as a controllable model: %j', async record => {+ await writeFile(join(records, 'remote.json'), JSON.stringify(record))+ expect((await service.list('home')).models[0].canStop).toBe(false)+ })++ it.each(['missing heartbeat', 'offline node', 'ambiguous node', 'missing models', 'missing file'])('does not claim running from %s alone', async scenario => {+ await service.act('home', 'org/Small-GGUF', 'start'); await service.settled()+ if (scenario === 'missing heartbeat') await rm(join(records, 'remote.heartbeat'))+ if (scenario === 'missing file') { catalogCards = []; await rm(join(home, 'models', 'Small-Q4.gguf')); serving = false }+ const original = run.getMockImplementation()!+ run.mockImplementation(async (args, output) => {+ const result = await original(args, output)+ if (!args.includes('engines') || scenario === 'missing heartbeat' || scenario === 'missing file') return result+ const node = JSON.parse(result.stdout)[0]+ return ok(scenario === 'ambiguous node' ? [node, node] : [{ ...node, ...(scenario === 'offline node' ? { online: false } : { models: null }) }])+ })+ const snapshot = await service.list('home', true)+ expect(snapshot.models[0]).toMatchObject({ canStop: true })+ expect(snapshot.models[0].state).not.toBe('running')+ expect(snapshot.models[0].tokensPerSecond).toBeUndefined()+ })++ it('keeps a missing-file engine stoppable and requires live inventory to call it running', async () => {+ catalogCards = []+ serving = true+ await writeFile(join(records, 'remote.json'), JSON.stringify({ node_id: 'local-node', engines: [{ models: ['Small-Q4.gguf'] }] }))+ await writeFile(join(records, 'remote.heartbeat'), '')+ expect((await service.list('home')).models[0]).toMatchObject({ state: 'running', canStart: false, canStop: true })+ await service.act('home', 'local:Small-Q4.gguf', 'stop'); await service.settled()+ expect(calls.some(args => args.includes('leave'))).toBe(true)+ expect((await service.list('home')).models).toEqual([])+ })++ it('matches object-shaped aliases and never substitutes engine-total request counts', async () => {+ await service.act('home', 'org/Small-GGUF', 'start'); await service.settled()+ const original = run.getMockImplementation()!+ run.mockImplementation(async (args, output) => args.includes('engines') ? ok([{+ id: 'local-node', online: true, models: [{ model: 'SMALL-Q4.GGUF' }],+ answered: { requests: 200, window_seconds: 3600 },+ }]) : original(args, output))+ expect((await service.list('home')).models[0]).toMatchObject({ state: 'running', requests: undefined })+ })++ it('marks an unfinished receipt interrupted after restart without replaying a command', async () => {+ await mkdir(stateDir)+ const hash = createHash('sha256').update('home').digest('hex').slice(0, 24)+ await writeFile(join(stateDir, `${hash}.json`), JSON.stringify({ spec: 1, grid: 'home', operation: {+ id: 'interrupted', modelId: 'org/Small-GGUF', action: 'start', stage: 'downloading', phase: 'running', updatedAt: '2026-01-01T00:00:00Z',+ } }))+ expect((await service.list('home')).models[0].operation).toMatchObject({ phase: 'failed', error: expect.stringContaining('interrupted') })+ expect(calls.some(args => args[0] === 'pull' || args.includes('join'))).toBe(false)+ })++ it.each([{ spec: 9, grid: 'home' }, { spec: 1, grid: 'somebody-else' }])('discards an invalid or different-account receipt: %j', async receipt => {+ await mkdir(stateDir)+ const hash = createHash('sha256').update('home').digest('hex').slice(0, 24)+ await writeFile(join(stateDir, `${hash}.json`), JSON.stringify({ ...receipt, operation: { id: 'private', modelId: 'org/Small-GGUF' } }))+ expect((await service.list('home')).models[0].operation).toBeUndefined()+ })++ it('refuses to start if a durable receipt cannot be created', async () => {+ await writeFile(stateDir, 'not a directory')+ expect((await service.act('home', 'org/Small-GGUF', 'start')).error).toContain('saved')+ expect(calls).toEqual([])+ await rm(stateDir)+ await service.act('home', 'org/Small-GGUF', 'start'); await service.settled()+ expect((await service.list('home')).models[0].operation?.phase).toBe('done')+ })++ it.each(['model no longer fits', 'smaller fit only', 'no machine budget'])('checks changed hardware before downloading: %s', async scenario => {+ await service.list('home')+ if (scenario === 'no machine budget') {+ const original = run.getMockImplementation()!+ run.mockImplementation(async (args, output) => args[0] === 'device-info' ? ok({}) : original(args, output))+ }+ request.mockImplementation(async () => response({ models: scenario === 'smaller fit only'+ ? [{ ...card(), versions: [{ ...card().versions[0], size_bytes: 32 }] }] : [] }))+ await service.act('home', 'org/Small-GGUF', 'start'); await service.settled()+ expect((await service.list('home')).models[0].operation?.error).toContain('make room')+ expect(calls.some(args => args[0] === 'pull' || args.includes('join'))).toBe(false)+ })++ it('does not download when free disk space is insufficient', async () => {+ catalogCards[0].versions[0].size_bytes = Number.MAX_SAFE_INTEGER+ await service.act('home', 'org/Small-GGUF', 'start'); await service.settled()+ expect((await service.list('home')).models[0].operation?.error).toContain('disk space')+ expect(calls.some(args => args[0] === 'pull')).toBe(false)+ })++ it('does not start an incomplete download even after the downloader exits successfully', async () => {+ const original = run.getMockImplementation()!+ run.mockImplementation(async (args, output) => args[0] === 'pull' ? ok() : original(args, output))+ await service.act('home', 'org/Small-GGUF', 'start'); await service.settled()+ expect((await service.list('home')).models[0].operation?.error).toContain('incomplete')+ expect(calls.some(args => args.includes('join'))).toBe(false)+ })++ it.each(['engine', 'join', 'info', 'leave'])('reports a failed %s without inventing success', async step => {+ if (step === 'leave') { await service.act('home', 'org/Small-GGUF', 'start'); await service.settled() }+ const original = run.getMockImplementation()!+ run.mockImplementation(async (args, output) => args.includes(step) ? { ...ok(), ok: false, stderr: 'private-token' } : original(args, output))+ await service.act('home', 'org/Small-GGUF', step === 'leave' ? 'stop' : 'start'); await service.settled()+ const snapshot = await service.list('home')+ expect(snapshot.models[0].operation?.phase).toBe('failed')+ expect(JSON.stringify(snapshot)).not.toContain('private-token')+ })++ it('keeps Stop available while a successful leave has not removed its run record', async () => {+ await service.act('home', 'org/Small-GGUF', 'start'); await service.settled()+ const original = run.getMockImplementation()!+ run.mockImplementation(async (args, output) => args.includes('leave') ? ok() : original(args, output))+ await service.act('home', 'org/Small-GGUF', 'stop'); await service.settled()+ expect((await service.list('home')).models[0]).toMatchObject({ canStop: true, operation: { phase: 'failed', error: expect.stringContaining('still stopping') } })+ })++ it('protects a shared runtime from simple Stop and Start', async () => {+ await service.act('home', 'org/Small-GGUF', 'start'); await service.settled()+ const record = JSON.parse(await readFile(join(records, 'remote.json'), 'utf8'))+ record.media = { port: 1234 }+ await writeFile(join(records, 'remote.json'), JSON.stringify(record))+ await service.act('home', 'org/Small-GGUF', 'stop'); await service.settled()+ expect((await service.list('home')).models[0].operation?.error).toContain('share its engine')+ expect(calls.some(args => args.includes('leave'))).toBe(false)+ })++ it('reverifies an already owned instance without downloading or joining again', async () => {+ await service.act('home', 'org/Small-GGUF', 'start'); await service.settled()+ await service.act('home', 'org/Small-GGUF', 'start'); await service.settled()+ expect(calls.filter(args => args.includes('join'))).toHaveLength(1)+ expect(request.mock.calls.filter(([url]) => String(url).includes('chat/completions'))).toHaveLength(2)+ })++ it.each([false, true])('handles an explicit engine override (available=%s)', async available => {+ const binary = join(root, 'custom-llama')+ if (available) await writeFile(binary, '#!/bin/sh\nexit 0', { mode: 0o700 })+ service = new LocalModels({ stateDir, processEnv: { GRID_HOME: home, LLAMA_SERVER: binary }, run, request: request as typeof fetch })+ await service.act('home', 'org/Small-GGUF', 'start'); await service.settled()+ const operation = (await service.list('home')).models[0].operation+ expect(operation?.phase).toBe(available ? 'done' : 'failed')+ expect(calls.some(args => args[0] === 'engine')).toBe(false)+ })++ it('keeps a missing endpoint recoverable without sending a test to an unknown address', async () => {+ const original = run.getMockImplementation()!+ run.mockImplementation(async (args, output) => args.includes('info') ? ok() : original(args, output))+ await service.act('home', 'org/Small-GGUF', 'start'); await service.settled()+ expect((await service.list('home')).models[0].operation?.phase).toBe('failed')+ expect(request.mock.calls.some(([url]) => String(url).includes('chat/completions'))).toBe(false)+ })++ it.each(['reasoning only', 'http error', 'network error'])('requires a real test reply and bounds retries for %s', async scenario => {+ const original = request.getMockImplementation()!+ let attempted!: () => void+ const first = new Promise<void>(resolve => { attempted = resolve })+ request.mockImplementation(async (url, init) => {+ if (String(url).includes('/catalog')) return original(url, init)+ attempted()+ if (scenario === 'network error') throw new Error('private-token')+ return scenario === 'http error' ? new Response('private-token', { status: 503 })+ : response({ choices: [{ message: { reasoning_content: 'ok' } }] })+ })+ vi.useFakeTimers({ toFake: ['setTimeout', 'Date'] })+ await service.act('home', 'org/Small-GGUF', 'start')+ await first+ await vi.advanceTimersByTimeAsync(182_000)+ await service.settled()+ expect((await service.list('home')).models[0].operation).toMatchObject({ phase: 'failed', error: expect.stringContaining('did not answer') })+ expect(JSON.stringify(await service.list('home'))).not.toContain('private-token')+ vi.useRealTimers()+ })++ it('rejects unsafe, incomplete and duplicate fit cards while supporting split downloads', () => {+ const invalid = [null, {}, { ...card(), runnable: false }, { ...card(), format: 'safetensors' },+ { ...card(), repo_id: '' }, { ...card(), fit: {} },+ ...['--flag:model.gguf', 'repo-only', 'org/repo:model.bin'].map(pull_spec => ({ ...card(), versions: [{ ...card().versions[0], pull_spec }] })),+ { ...card(), fit: { version: 'Q4', ctx: 0 } },+ { ...card(), versions: [{ ...card().versions[0], size_bytes: -1 }] }]+ expect(compatibleModels({ models: invalid })).toEqual([])+ expect(compatibleModels({ models: [card(), card()] })).toHaveLength(1)+ expect(compatibleModels({ models: [{ ...card(), versions: [{ ...card().versions[0], urls: ['bad-url'] }] }] })[0].files).toEqual(['Small-Q4.gguf'])+ expect(compatibleModels({ models: [{ ...card(), versions: [{ ...card().versions[0], urls: null }] }] })[0].files).toEqual(['Small-Q4.gguf'])+ expect(compatibleModels({ models: [{ ...card(), task: 'image-text-to-text', versions: [{ ...card().versions[0], urls: ['https://example.test/part-1.gguf', 'https://example.test/part-2.gguf'] }] }] })[0].files).toEqual(['part-1.gguf', 'part-2.gguf'])+ })++ it('routes production-default dependencies through the bounded Grid subprocess runner', async () => {+ vi.stubEnv('GRID_HOME', home)+ vi.stubGlobal('fetch', request)+ const rpc = vi.spyOn(GridFleetRpc.prototype, 'run').mockImplementation(async (_owner, _id, options, output) => run(options.args, output))+ service = new LocalModels({ stateDir })+ await service.act('home', 'org/Small-GGUF', 'start'); await service.settled()+ expect((await service.list('home')).models[0].operation?.phase).toBe('done')+ expect(rpc).toHaveBeenCalledWith('local-models', expect.any(String), expect.objectContaining({ timeoutMs: 30_000, thinking: false }), undefined, 4 * 1024 * 1024)+ expect(rpc.mock.calls.find(call => call[2].args[0] === 'pull')?.[2].timeoutMs).toBe(30 * 60_000)+ })++ it.each(['memory changed', 'file removed'])('rechecks an imported deployment before restarting when %s', async scenario => {+ catalogCards = []+ await writeFile(join(home, 'models', 'Small-Q4.gguf'), Buffer.alloc(64))+ await run(['--remote', 'join', 'home'])+ await service.list('home')+ await service.act('home', 'local:Small-Q4.gguf', 'stop'); await service.settled()+ const original = run.getMockImplementation()!+ run.mockImplementation(async (args, output) => {+ if (args[0] === 'device-info') {+ if (scenario === 'file removed') await rm(join(home, 'models', 'Small-Q4.gguf'))+ else return ok({ usable_bytes: 0 })+ }+ return original(args, output)+ })+ const ack = await service.act('home', 'local:Small-Q4.gguf', 'start'); await service.settled()+ expect(ack.operation).toMatchObject({ phase: 'failed', error: expect.stringContaining(scenario === 'memory changed' ? 'make room' : 'no longer available') })+ expect(calls.filter(args => args.includes('join'))).toHaveLength(1)+ })++ it('keeps imported downloads visible, merges catalog matches, and removes deleted files', async () => {+ catalogCards = []+ await writeFile(join(home, 'models', 'Small-Q4.gguf'), Buffer.alloc(64))+ await run(['--remote', 'join', 'home'])+ await service.list('home')+ await service.act('home', 'local:Small-Q4.gguf', 'stop'); await service.settled()+ expect((await service.list('home')).models[0].state).toBe('downloaded')+ catalogCards = [card()]+ expect((await service.list('home', true)).models).toHaveLength(1)+ catalogCards = []+ await rm(join(home, 'models', 'Small-Q4.gguf'))+ expect((await service.list('home', true)).models).toEqual([])+ })++ it('does not mistake a directory for downloaded weights or fabricate unavailable device memory', async () => {+ await mkdir(join(home, 'models', 'Small-Q4.gguf'))+ const original = run.getMockImplementation()!+ run.mockImplementation(async (args, output) => args[0] === 'device-info' ? ok({}) : original(args, output))+ const view = await service.list('home')+ expect(view.models[0].state).toBe('available')+ expect(view.memoryBytes).toBeUndefined()+ })++ it('cannot start a stale catalog choice while compatibility is unavailable', async () => {+ await service.list('home')+ catalogFails = true+ await service.list('home', true)+ const ack = await service.act('home', 'org/Small-GGUF', 'start'); await service.settled()+ expect(ack.operation).toMatchObject({ phase: 'failed', error: expect.stringContaining('could not be checked') })+ expect(calls.some(args => args[0] === 'pull')).toBe(false)+ })++ it('ignores non-progress output and boundedly saves valid download progress', async () => {+ const original = run.getMockImplementation()!+ run.mockImplementation(async (args, output) => {+ if (args[0] === 'pull') { output?.('connecting…'); output?.('150%'); output?.('0%'); output?.('2%') }+ return original(args, output)+ })+ await service.act('home', 'org/Small-GGUF', 'start'); await service.settled()+ expect((await service.list('home')).models[0].operation?.phase).toBe('done')+ })++ it('releases the operation after receipt storage fails during a download', async () => {+ const original = run.getMockImplementation()!+ run.mockImplementation(async (args, output) => {+ if (args[0] === 'pull') {+ rmSync(stateDir, { recursive: true, force: true }); writeFileSync(stateDir, 'storage unavailable')+ output?.('42%')+ await new Promise(resolve => setImmediate(resolve))+ throw new Error('private filesystem detail')+ }+ return original(args, output)+ })+ const ack = await service.act('home', 'org/Small-GGUF', 'start'); await service.settled()+ expect(ack.operation).toMatchObject({ phase: 'failed', error: 'The model could not finish. Start again to retry.' })+ expect((await service.list('home')).busy).toBe(false)+ await rm(stateDir)+ run.mockImplementation(original)+ await service.act('home', 'org/Small-GGUF', 'start'); await service.settled()+ expect((await service.list('home')).models[0].operation?.phase).toBe('done')+ })++ it('recovers malformed aliases and preserves failure status for a model with missing weights', async () => {+ catalogCards = []+ serving = true+ await writeFile(join(records, 'remote.json'), JSON.stringify({ node_id: 'local-node', advertise_as: [42, ''], engines: [{ models: ['Small-Q4.gguf'] }] }))+ await writeFile(join(records, 'remote.heartbeat'), '')+ const original = run.getMockImplementation()!+ run.mockImplementation(async (args, output) => args.includes('leave') ? { ...ok(), ok: false } : original(args, output))+ await service.act('home', 'local:Small-Q4.gguf', 'stop'); await service.settled()+ expect((await service.list('home')).models[0]).toMatchObject({ name: 'Small-Q4', state: 'running', operation: { phase: 'failed' } })+ })+})diff --git a/cli/src/lib/localModels.ts b/cli/src/lib/localModels.tsnew file mode 100644index 000000000..545d3f2d1--- /dev/null+++ b/cli/src/lib/localModels.ts@@ -0,0 +1,432 @@+/** The Models popover's local lifecycle. Grid remains the hardware, catalog,+ * download and process authority. A click is a durable daemon operation, never a chat task. */+import { createHash, randomUUID } from 'node:crypto'+import { readFile, readdir, stat, mkdir, rename, writeFile, statfs } from 'node:fs/promises'+import { basename, dirname, join } from 'node:path'+import { GridFleetRpc, type GridFleetResult } from './gridFleetRpc.js'+import { gridCredentialsPath } from './gridCredentials.js'+import { forgetGridModels } from './gridModels.js'+import { binaryOnPath } from './binaryOnPath.js'++const GiB = 1024 ** 3+const obj = (v: unknown): Record<string, any> => v && typeof v === 'object' && !Array.isArray(v) ? v : {}+const rows = (v: unknown): Record<string, any>[] => Array.isArray(v) ? v.map(obj) : []+const str = (v: unknown): string => typeof v === 'string' ? v : ''+const num = (v: unknown): number | undefined => typeof v === 'number' && Number.isFinite(v) && v >= 0 ? v : undefined+const key = (v: string): string => createHash('sha256').update(v).digest('hex').slice(0, 24)+const cleanName = (v: string): string => basename(v).replace(/\.gguf$/i, '').replace(/-GGUF$/i, '')+const validArg = (v: string): boolean => !!v && !v.startsWith('-') && !/[\x00-\x1f]/.test(v)++export interface LocalModel {+ id: string; name: string; state: 'available' | 'downloaded' | 'running'+ sizeBytes?: number; quant?: string; recommended?: boolean; canStart: boolean; canStop: boolean+ tokensPerSecond?: number; requests?: number; windowSeconds?: number+ operation?: ModelOperation+}+export interface ModelOperation {+ id: string; modelId: string; action: 'start' | 'stop'; phase: 'running' | 'done' | 'failed'+ stage: 'checking' | 'downloading' | 'starting' | 'verifying' | 'stopping'+ progress?: number; error?: string; updatedAt: string+}+export interface LocalModelsSnapshot {+ models: LocalModel[]; memoryBytes?: number; hardware?: string; error?: string+ observedAt: string; busy: boolean+}+interface Candidate {+ id: string; name: string; pull: string; file: string; files: string[]; size: number; quant: string; context: number+}+interface Owned { file: string; selector: string; aliases: string[]; nodeId: string; name: string; live: boolean; context: number; siblings: number }+interface Receipt { spec: 1; grid: string; operation?: ModelOperation }+interface Options {+ stateDir: string; processEnv?: NodeJS.ProcessEnv+ run?: (args: string[], output?: (chunk: string) => void, timeout?: number) => Promise<GridFleetResult>+ request?: typeof fetch+}++/** One concrete, machine-fitted version per model. Non-chat and unprobed offline+ * catalog rows are never called compatible. Split GGUF files stay one model. */+export function compatibleModels(raw: unknown): Candidate[] {+ const seen = new Set<string>()+ return rows(obj(raw).models).flatMap(row => {+ const fit = obj(row.fit)+ if (row.runnable !== true || !['text-generation', 'image-text-to-text'].includes(row.task) || row.format !== 'GGUF') return []+ const version = rows(row.versions).find(v => v.version === fit.version)+ const pull = str(version?.pull_spec), size = num(version?.size_bytes)+ const id = str(row.repo_id), split = pull.indexOf(':')+ if (!id || seen.has(id) || !validArg(pull) || split < 1 || !size || !num(fit.ctx)) return []+ const file = basename(pull.slice(split + 1))+ if (!file.toLowerCase().endsWith('.gguf')) return []+ const files = (Array.isArray(version?.urls) ? version.urls : []).flatMap((url: unknown) => {+ try { return [basename(decodeURIComponent(new URL(str(url)).pathname))] } catch { return [] }+ })+ seen.add(id)+ return [{ id, name: cleanName(id), pull, file, files: files.length ? files : [file], size,+ quant: str(fit.version), context: Math.min(16384, Math.floor(fit.ctx)) }]+ })+}++export class LocalModels {+ private readonly processEnv: NodeJS.ProcessEnv+ private readonly home: string+ private readonly run: NonNullable<Options['run']>+ private readonly request: typeof fetch+ private candidates: Candidate[] = []+ private device: Record<string, any> = {}+ private catalogAt = 0+ private catalogError: string | undefined+ private catalogPending?: Promise<void>+ private listPending?: Promise<LocalModelsSnapshot>+ private listGrid?: string+ private cached?: { at: number; grid: string; value: LocalModelsSnapshot }+ private active?: { grid: string; operation: ModelOperation; done: Promise<void> }+ private receipt?: Receipt+ private receiptScope?: string+ private knownByGrid = new Map<string, Candidate[]>()+ private blockers = new Map<string, string>()++ constructor(private readonly options: Options) {+ this.processEnv = options.processEnv ?? process.env+ this.home = dirname(gridCredentialsPath(this.processEnv))+ const rpc = new GridFleetRpc(this.processEnv)+ this.run = options.run ?? ((args, output, timeout = 30_000) =>+ rpc.run('local-models', randomUUID(), { args, timeoutMs: timeout, thinking: false }, output, 4 * 1024 * 1024))+ this.request = options.request ?? fetch+ }++ private async json(args: string[]): Promise<any> {+ const result = await this.run(args)+ if (!result.ok) throw new Error('Models could not be checked. Try again.')+ try { return JSON.parse(result.stdout) } catch { throw new Error('Models could not be checked. Try again.') }+ }++ /** The same authenticated catalog Grid uses, paged until every compatible row+ * is included. Credentials never enter RPC replies, receipts, arguments or logs. */+ private async catalog(device: Record<string, any>): Promise<unknown> {+ const top = (await readFile(gridCredentialsPath(this.processEnv), 'utf8')).split(/^\s*\[/m)[0]+ const value = (name: string): string => {+ const match = new RegExp(`^\\s*${name}\\s*=\\s*("(?:[^"\\\\]|\\\\.)*"|'[^']*')\\s*$`, 'm').exec(top)+ if (!match) return ''+ try { return match[1][0] === '"' ? JSON.parse(match[1]) : match[1].slice(1, -1) } catch { return '' }+ }+ const token = value('session_token')+ if (!token) throw new Error('Sign in to find models for this computer.')+ const base = value('api_url') || this.processEnv.GRID_CONTROL_PLANE_URL || 'https://api-grid.autonomous.ai'+ const url = new URL(`${base.replace(/\/$/, '')}/v1/grid/catalog`)+ if (url.protocol !== 'https:' && !(url.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname))) {+ throw new Error('The model catalog address is unavailable.')+ }+ const all: any[] = []+ for (let page = 1; page <= 100; page++) {+ const response = await this.request(url, {+ method: 'POST', headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },+ body: JSON.stringify({ browse: true, page, page_size: 50, device: {+ device_class: device.device_class, usable_bytes: device.usable_bytes, backend: device.backend,+ } }), signal: AbortSignal.timeout(20_000), redirect: 'error',+ })+ if (!response.ok) throw new Error('Compatible models are unavailable. Try again.')+ const body = obj(await response.json())+ if (!Array.isArray(body.models)) throw new Error('Compatible models are unavailable. Try again.')+ all.push(...body.models)+ const totalPages = num(obj(body.pagination).total_pages) ?? 1+ if (page >= totalPages || (num(body.runnable_total) !== undefined && all.filter(m => m.runnable === true).length >= body.runnable_total)) return { models: all }+ if (!body.models.length || obj(body.pagination).page !== page) throw new Error('The model catalog is incomplete. Try again.')+ }+ throw new Error('The model catalog is incomplete. Try again.')+ }++ private async loadCatalog(force = false): Promise<void> {+ if (!force && this.catalogAt && Date.now() - this.catalogAt < 5 * 60_000) return+ return this.catalogPending ??= (async () => {+ try {+ this.device = obj(await this.json(['device-info', '--json']))+ const catalog = obj(await this.catalog(this.device))+ this.candidates = compatibleModels(catalog)+ // Prefer an already downloaded fitting quant rather than downloading+ // the catalog's default version of the same model again.+ for (let i = 0; i < this.candidates.length; i++) {+ const chosen = this.candidates[i]+ if (await this.downloaded(chosen)) continue+ const source = rows(catalog.models).find(m => m.repo_id === chosen.id)+ for (const version of rows(source?.versions)) {+ if ((num(version.size_bytes) ?? Infinity) > chosen.size) continue+ const alternate = compatibleModels({ models: [{ ...source, fit: { ...source?.fit, version: version.version } }] })[0]+ if (alternate && await this.downloaded(alternate)) { this.candidates[i] = alternate; break }+ }+ }+ // A useful small download makes the first reply arrive sooner. Keep+ // the catalog's relevance order within that group, and show all others.+ const suggested = this.candidates.findIndex(c => c.size <= 8 * GiB && c.size >= GiB)+ if (suggested > 0) this.candidates.unshift(...this.candidates.splice(suggested, 1))+ this.catalogError = undefined+ this.catalogAt = Date.now()+ } catch (error) {+ this.catalogError = error instanceof Error && /^(Sign in|The model catalog)/.test(error.message)+ ? error.message : 'Compatible models are unavailable. Try again.'+ }+ })().finally(() => { this.catalogPending = undefined })+ }++ private async downloaded(candidate: Candidate): Promise<boolean> {+ const sizes = await Promise.all(candidate.files.map(file => stat(join(this.home, 'models', file)).then(s => s.isFile() ? s.size : 0).catch(() => 0)))+ return sizes.every(size => size > 0) && sizes.reduce((sum, size) => sum + size, 0) === candidate.size+ }++ /** Grid's non-secret run records distinguish locally owned --serve processes+ * from external endpoints. Stop delegates identity checks and teardown to Grid. */+ private async owned(grid: string): Promise<Owned[]> {+ this.blockers.delete(grid)+ if (!validArg(grid)) return []+ const grids = rows(await this.json(['--remote', 'ls', '--json']))+ const gridId = str(grids.find(g => g.grid === grid)?.id)+ if (!gridId || basename(gridId) !== gridId) return []+ const folder = join(this.home, 'run', 'engines', gridId)+ const names = await readdir(folder).catch(() => [])+ const result: Owned[] = []+ for (const name of names.filter(n => n.endsWith('.json'))) {+ let record: Record<string, any>+ try { record = obj(JSON.parse(await readFile(join(folder, name), 'utf8'))) } catch { continue }+ const heartbeat = await stat(join(folder, name.replace(/\.json$/, '.heartbeat'))).catch(() => null)+ const live = heartbeat !== null && Date.now() - heartbeat.mtimeMs < 90_000+ const specs = rows(record.engines)+ if (specs.length || record.media) this.blockers.set(grid, 'Open Model Manager to add a model alongside those already running.')+ for (const spec of specs) {+ if (spec.endpoint_url || spec.api_kind || !Array.isArray(spec.models) || spec.models.length !== 1) continue+ const file = str(spec.models[0])+ if (!validArg(file) || !file.toLowerCase().endsWith('.gguf')) continue+ const advertised = Array.isArray(record.advertise_as) && specs.length === 1+ ? record.advertise_as.filter((v: unknown) => typeof v === 'string' && v.length > 0) : []+ const aliases: string[] = advertised.length ? advertised : [file]+ result.push({ file: basename(file), selector: file, aliases, nodeId: str(record.node_id), name: str(record.meta_name), live, context: Math.min(16384, num(record.ctx_size) || 8192), siblings: specs.length + (record.media ? 1 : 0) })+ this.blockers.set(grid, `Stop ${cleanName(aliases[0])} first to start another local model.`)+ }+ }+ return result+ }++ /** Keep models imported from an existing Grid setup after Stop removes its+ * run record. Only completed local files that this computer already served+ * become restartable; arbitrary downloaded GGUFs are not assumed compatible. */+ private async known(grid: string, owned: Owned[]): Promise<Candidate[]> {+ const path = join(this.options.stateDir, `${key(grid)}.known.json`)+ let known = this.knownByGrid.get(grid)+ if (!known) {+ try {+ known = rows(JSON.parse(await readFile(path, 'utf8'))).filter(c =>+ c.id === `local:${c.file}` && basename(str(c.file)) === c.file && validArg(c.file) &&+ c.pull === '' && typeof c.name === 'string' && c.name.length < 256 && num(c.size) && num(c.context) && c.context <= 16384 &&+ Array.isArray(c.files) && c.files.length === 1 && c.files[0] === c.file) as Candidate[]+ } catch { known = [] }+ this.knownByGrid.set(grid, known)+ }+ let changed = false+ for (const instance of owned) {+ if (this.candidates.some(c => c.file === instance.file) || known.some(c => c.file === instance.file)) continue+ const file = await stat(join(this.home, 'models', instance.file)).catch(() => null)+ if (!file?.isFile() || !file.size) continue+ known.push({ id: `local:${instance.file}`, name: cleanName(instance.aliases[0]),+ file: instance.file, files: [instance.file], pull: '', size: file.size, quant: '', context: instance.context })+ changed = true+ }+ if (changed) {+ await mkdir(this.options.stateDir, { recursive: true, mode: 0o700 })+ const temp = `${path}.${randomUUID()}.tmp`+ await writeFile(temp, JSON.stringify(known), { mode: 0o600 }); await rename(temp, path)+ }+ const existing = await Promise.all(known.map(async candidate => await this.downloaded(candidate) ? candidate : null))+ return existing.filter((c): c is Candidate => c !== null)+ }++ private receiptPath(grid: string): string { return join(this.options.stateDir, `${key(grid)}.json`) }+ private async readReceipt(grid: string): Promise<void> {+ if (this.receiptScope === grid) return+ this.receiptScope = grid+ this.receipt = undefined+ try {+ const value = JSON.parse(await readFile(this.receiptPath(grid), 'utf8')) as Receipt+ if (value.spec === 1 && value.grid === grid) {+ this.receipt = value+ if (value.operation?.phase === 'running' && this.active?.operation.id !== value.operation.id) {+ value.operation.phase = 'failed'+ value.operation.error = 'Setup was interrupted. Start again to continue.'+ }+ }+ } catch { /* no prior operation */ }+ }+ private async save(grid: string, operation: ModelOperation): Promise<void> {+ const value: Receipt = { spec: 1, grid, operation: { ...operation, updatedAt: new Date().toISOString() } }+ this.receipt = value; this.receiptScope = grid; this.cached = undefined+ await mkdir(this.options.stateDir, { recursive: true, mode: 0o700 })+ const file = this.receiptPath(grid), temp = `${file}.${randomUUID()}.tmp`+ await writeFile(temp, JSON.stringify(value), { mode: 0o600 })+ await rename(temp, file)+ }++ async list(grid: string | null, force = false): Promise<LocalModelsSnapshot> {+ if (!grid) return { models: [], error: 'Sign in to find models for this computer.', observedAt: new Date().toISOString(), busy: false }+ if (!force && this.cached?.grid === grid && Date.now() - this.cached.at < 2500) return this.cached.value+ if (this.listPending) {+ if (this.listGrid === grid) return this.listPending+ await this.listPending; return this.list(grid, force)+ }+ this.listGrid = grid+ this.listPending = this.readList(grid, force)+ try { return await this.listPending } finally { this.listPending = undefined }+ }+ private async readList(grid: string, force: boolean): Promise<LocalModelsSnapshot> {+ await Promise.all([this.loadCatalog(force), this.readReceipt(grid)])+ let owned: Owned[] = [], nodes: Record<string, any>[] = [], inventoryError: string | undefined+ try {+ [owned, nodes] = await Promise.all([this.owned(grid), this.json(['--remote', 'engines', grid, '--json']).then(rows)])+ } catch { inventoryError = 'Running models could not be checked. Try again.' }+ const operation = this.active?.grid === grid ? this.active.operation : this.receipt?.grid === grid ? this.receipt.operation : undefined+ const choices = [...this.candidates, ...(await this.known(grid, owned)).filter(k => !this.candidates.some(c => c.file === k.file))]+ const servingNode = (instance?: Owned): Record<string, any> | undefined => {+ const matches = instance?.live ? nodes.filter(n => n.online === true &&+ (str(n.node_id || n.id) ? str(n.node_id || n.id) === instance.nodeId :+ !!instance.name && str(n.name) === instance.name) &&+ instance.aliases.every(alias => (Array.isArray(n.models) ? n.models : []).some((m: unknown) =>+ str(typeof m === 'string' ? m : obj(m).model).toLowerCase() === alias.toLowerCase()))) : []+ return matches.length === 1 ? matches[0] : undefined+ }+ const models = await Promise.all(choices.map(async (candidate, index): Promise<LocalModel> => {+ const instance = owned.find(o => o.file === candidate.file)+ const node = servingNode(instance)+ const running = !!node+ const available = await this.downloaded(candidate)+ const answered = obj(node?.answered)+ const perModel = rows(answered.by_model).find(a => instance?.aliases.some(alias => alias.toLowerCase() === str(a.model).toLowerCase()))+ const single = Array.isArray(node?.models) && node.models.length === 1+ return { id: candidate.id, name: candidate.name, state: running ? 'running' : available ? 'downloaded' : 'available',+ sizeBytes: candidate.size, quant: candidate.quant, recommended: index === 0,+ canStart: !inventoryError && (!this.catalogError || !candidate.pull) && !instance, canStop: !inventoryError && !!instance,+ // Device memory is deliberately not presented as this model's memory.+ tokensPerSecond: single && running ? num(node?.throughput_tok_s) : undefined,+ requests: running ? num(perModel?.requests) : undefined,+ windowSeconds: running ? num(answered.window_seconds) : undefined,+ operation: operation?.modelId === candidate.id ? operation : undefined }+ }))+ for (const instance of owned.filter(o => !choices.some(c => c.file === o.file))) {+ models.push({ id: `local:${instance.file}`, name: cleanName(instance.aliases[0]),+ state: servingNode(instance) ? 'running' : 'available', canStart: false, canStop: !inventoryError,+ operation: operation?.modelId === `local:${instance.file}` ? operation : undefined })+ }+ const value: LocalModelsSnapshot = { models, memoryBytes: num(obj(this.device.memory).total_gb) === undefined ? undefined : this.device.memory.total_gb * GiB,+ hardware: str(obj(this.device.machine).model || obj(this.device.cpu).brand), error: inventoryError || this.catalogError,+ observedAt: new Date().toISOString(), busy: !!this.active }+ this.cached = { grid, at: Date.now(), value }+ return value+ }++ /** A repeated click or lost RPC acknowledgement joins the same operation.+ * A different model waits: starts/stops must not race on the machine's budget. */+ async act(grid: string | null, modelId: unknown, action: 'start' | 'stop'): Promise<{ operation?: ModelOperation; error?: string }> {+ if (!grid || typeof modelId !== 'string') return { error: 'The model is unavailable. Refresh and try again.' }+ if (this.active) return this.active.grid === grid && this.active.operation.modelId === modelId && this.active.operation.action === action+ ? { operation: this.active.operation } : { error: 'Wait for the current model to finish starting or stopping.' }+ const operation: ModelOperation = { id: randomUUID(), modelId, action, stage: action === 'start' ? 'checking' : 'stopping', phase: 'running', updatedAt: new Date().toISOString() }+ // Reserve before any await; independent RPCs may arrive on separate connections.+ const active = { grid, operation, done: Promise.resolve() }+ this.active = active+ try { await this.save(grid, operation) } catch { this.active = undefined; return { error: 'Setup could not be saved. Try again.' } }+ active.done = this.perform(grid, operation).catch(async error => {+ operation.phase = 'failed'+ operation.error = error instanceof ModelError ? error.message : 'The model could not finish. Start again to retry.'+ await this.save(grid, operation).catch(() => {})+ }).finally(() => { this.active = undefined; this.cached = undefined; forgetGridModels() })+ return { operation }+ }++ async settled(): Promise<void> { await this.active?.done }++ private async perform(grid: string, operation: ModelOperation): Promise<void> {+ const change = async (stage: ModelOperation['stage']) => {+ operation.stage = stage; delete operation.progress; await this.save(grid, operation)+ }+ const must = async (args: string[], message: string, output?: (chunk: string) => void) => {+ if (!(await this.run(args, output, 30 * 60_000)).ok) throw new ModelError(message)+ }+ if (operation.action === 'start') await this.loadCatalog()+ const owned = await this.owned(grid)+ const candidate = [...this.candidates, ...await this.known(grid, owned)].find(c => c.id === operation.modelId)+ const instance = owned.find(o => candidate ? o.file === candidate.file : operation.modelId === `local:${o.file}`)+ if (operation.action === 'stop') {+ if (instance) {+ if (instance.siblings > 1) throw new ModelError('Open Model Manager to stop this model. Other models share its engine.')+ await must(['--remote', 'leave', grid, '--engine', instance.selector], 'The model could not stop. Try again.')+ if ((await this.owned(grid)).some(o => o.file === instance.file)) throw new ModelError('The model is still stopping. Check again in a moment.')+ }+ } else {+ if (!candidate || (this.catalogError && candidate.pull)) throw new ModelError('This model could not be checked. Refresh and try again.')+ if (!instance) {+ // The pinned Grid runtime respawns its union when adding --serve.+ // Do not interrupt existing engines as a side effect of a simple Start.+ if (this.blockers.has(grid)) throw new ModelError(this.blockers.get(grid)!)+ // Recheck the machine immediately before downloading or allocating.+ const currentDevice = obj(await this.json(['device-info', '--json']))+ const budget = num(currentDevice.usable_bytes) ?? 0+ if (candidate.pull) {+ const current = compatibleModels(await this.catalog({ ...currentDevice, usable_bytes: Math.max(0, budget) })).find(c => c.id === candidate.id)+ if (!current || current.size < candidate.size) throw new ModelError('Stop a running model to make room, then try again.')+ candidate.context = Math.min(candidate.context, current.context)+ } else if (candidate.size * 1.25 + 2 * GiB > budget) {+ throw new ModelError('Stop a running model to make room, then try again.')+ }+ if (!await this.downloaded(candidate)) {+ if (!candidate.pull) throw new ModelError('The downloaded file is no longer available. Open Model Manager to restore it.')+ await mkdir(join(this.home, 'models'), { recursive: true })+ const disk = await statfs(join(this.home, 'models'))+ if (disk.bavail * disk.bsize < candidate.size + GiB) throw new ModelError('Free up disk space, then start again.')+ await change('downloading')+ let last = 0, progressWrites = Promise.resolve()+ await must(['pull', candidate.pull], 'The download stopped. Start again to resume.', chunk => {+ const matches = [...chunk.matchAll(/(\d+(?:\.\d+)?)\s*%/g)]+ const percent = matches.length ? Number(matches.at(-1)![1]) : NaN+ if (Number.isFinite(percent) && percent >= 0 && percent <= 100 && Date.now() - last > 500) {+ last = Date.now(); operation.progress = percent / 100+ progressWrites = progressWrites.then(() => this.save(grid, operation)).catch(() => {})+ }+ })+ await progressWrites+ if (!await this.downloaded(candidate)) throw new ModelError('The download is incomplete. Start again to resume.')+ }+ await change('starting')+ const override = this.processEnv.LLAMA_SERVER+ const installed = override ? binaryOnPath(override, this.processEnv)+ : binaryOnPath(join(this.home, 'bin', 'llama-server'), this.processEnv) || binaryOnPath('llama-server', this.processEnv)+ if (!installed) {+ if (override) throw new ModelError('The local engine needs attention. Open Model Manager.')+ await must(['engine', 'install', 'llama.cpp'], 'The model engine could not start. Try again.')+ }+ await must(['--remote', 'join', grid, '--serve', candidate.file,+ '--max-concurrency', '1', '--ctx-size', String(candidate.context), '--reasoning-budget', '0'],+ 'The model could not start. Try again.')+ }+ await change('verifying')+ await this.verify(grid, instance?.aliases[0] || candidate.file)+ }+ operation.phase = 'done'+ await this.save(grid, operation)+ }++ private async verify(grid: string, model: string): Promise<void> {+ const info = await this.run(['--remote', 'info', grid, '--env'])+ const exports: Record<string, string> = {}+ for (const match of info.stdout.matchAll(/^export\s+(OPENAI_BASE_URL|OPENAI_API_KEY)=(.*)$/gm)) exports[match[1]] = match[2].trim().replace(/^["']|["']$/g, '')+ if (!info.ok || !exports.OPENAI_BASE_URL || !exports.OPENAI_API_KEY) throw new ModelError('The model is starting, but could not be checked. Try again shortly.')+ const deadline = Date.now() + 180_000+ do {+ try {+ const response = await this.request(`${exports.OPENAI_BASE_URL.replace(/\/$/, '')}/chat/completions`, {+ method: 'POST', headers: { authorization: `Bearer ${exports.OPENAI_API_KEY}`, 'content-type': 'application/json' },+ body: JSON.stringify({ model, messages: [{ role: 'user', content: 'Reply with the single word: ok' }], max_tokens: 8 }),+ signal: AbortSignal.timeout(30_000), redirect: 'error',+ })+ const body = response.ok ? obj(await response.json()) : {}+ if (/^\s*ok[.!]?\s*$/i.test(str(obj(rows(body.choices)[0]?.message).content))) return+ } catch { /* registration and first warmup take time; status remains verifying */ }+ await new Promise(resolve => setTimeout(resolve, 1500))+ } while (Date.now() < deadline)+ throw new ModelError('The model did not answer. Stop it, then start again.')+ }+}+class ModelError extends Error {}diff --git a/desktop/assets/model-icons/LICENSE b/desktop/assets/model-icons/LICENSEnew file mode 100644index 000000000..1dd53d2a9--- /dev/null+++ b/desktop/assets/model-icons/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2023 LobeHub++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/desktop/assets/model-icons/NOTICE.md b/desktop/assets/model-icons/NOTICE.mdnew file mode 100644index 000000000..539c98e46--- /dev/null+++ b/desktop/assets/model-icons/NOTICE.md@@ -0,0 +1,7 @@+# Model artwork++Logos identify their respective models and providers; they do not imply endorsement.++SVG artwork from [Lobe Icons](https://github.com/lobehub/lobe-icons/tree/5c1ecb4fb06b92519a39102482d4e8273f000422/packages/static-svg/icons), revision `5c1ecb4fb06b92519a39102482d4e8273f000422` (MIT; see LICENSE). PNGs are rasterized to 128 × 128 with their aspect ratios and colors preserved. OpenAI and Z.ai use theme-aware monochrome artwork.++The original SVG sources are retained beside their PNGs.diff --git a/desktop/assets/model-icons/claude.png b/desktop/assets/model-icons/claude.pngnew file mode 100644index 000000000..21e0b1194Binary files /dev/null and b/desktop/assets/model-icons/claude.png differdiff --git a/desktop/assets/model-icons/claude.svg b/desktop/assets/model-icons/claude.svgnew file mode 100644index 000000000..62dc0db12--- /dev/null+++ b/desktop/assets/model-icons/claude.svg@@ -0,0 +1 @@+<svg height="1em" style="flex:none;line-height:1" viewBox="0 0 24 24" width="1em" xmlns="http://www.w3.org/2000/svg"><title>Claude</title><path d="M4.709 15.955l4.72-2.647.08-.23-.08-.128H9.2l-.79-.048-2.698-.073-2.339-.097-2.266-.122-.571-.121L0 11.784l.055-.352.48-.321.686.06 1.52.103 2.278.158 1.652.097 2.449.255h.389l.055-.157-.134-.098-.103-.097-2.358-1.596-2.552-1.688-1.336-.972-.724-.491-.364-.462-.158-1.008.656-.722.881.06.225.061.893.686 1.908 1.476 2.491 1.833.365.304.145-.103.019-.073-.164-.274-1.355-2.446-1.446-2.49-.644-1.032-.17-.619a2.97 2.97 0 01-.104-.729L6.283.134 6.696 0l.996.134.42.364.62 1.414 1.002 2.229 1.555 3.03.456.898.243.832.091.255h.158V9.01l.128-1.706.237-2.095.23-2.695.08-.76.376-.91.747-.492.584.28.48.685-.067.444-.286 1.851-.559 2.903-.364 1.942h.212l.243-.242.985-1.306 1.652-2.064.73-.82.85-.904.547-.431h1.033l.76 1.129-.34 1.166-1.064 1.347-.881 1.142-1.264 1.7-.79 1.36.073.11.188-.02 2.856-.606 1.543-.28 1.841-.315.833.388.091.395-.328.807-1.969.486-2.309.462-3.439.813-.042.03.049.061 1.549.146.662.036h1.622l3.02.225.79.522.474.638-.079.485-1.215.62-1.64-.389-3.829-.91-1.312-.329h-.182v.11l1.093 1.068 2.006 1.81 2.509 2.33.127.578-.322.455-.34-.049-2.205-1.657-.851-.747-1.926-1.62h-.128v.17l.444.649 2.345 3.521.122 1.08-.17.353-.608.213-.668-.122-1.374-1.925-1.415-2.167-1.143-1.943-.14.08-.674 7.254-.316.37-.729.28-.607-.461-.322-.747.322-1.476.389-1.924.315-1.53.286-1.9.17-.632-.012-.042-.14.018-1.434 1.967-2.18 2.945-1.726 1.845-.414.164-.717-.37.067-.662.401-.589 2.388-3.036 1.44-1.882.93-1.086-.006-.158h-.055L4.132 18.56l-1.13.146-.487-.456.061-.746.231-.243 1.908-1.312-.006.006z" fill="#D97757" fill-rule="nonzero"></path></svg>\ No newline at end of filediff --git a/desktop/assets/model-icons/deepseek.png b/desktop/assets/model-icons/deepseek.pngnew file mode 100644index 000000000..590e3b1c3Binary files /dev/null and b/desktop/assets/model-icons/deepseek.png differdiff --git a/desktop/assets/model-icons/deepseek.svg b/desktop/assets/model-icons/deepseek.svgnew file mode 100644index 000000000..3fc230240--- /dev/null+++ b/desktop/assets/model-icons/deepseek.svg@@ -0,0 +1 @@+<svg height="1em" style="flex:none;line-height:1" viewBox="0 0 24 24" width="1em" xmlns="http://www.w3.org/2000/svg"><title>DeepSeek</title><path d="M23.748 4.482c-.254-.124-.364.113-.512.234-.051.039-.094.09-.137.136-.372.397-.806.657-1.373.626-.829-.046-1.537.214-2.163.848-.133-.782-.575-1.248-1.247-1.548-.352-.156-.708-.311-.955-.65-.172-.241-.219-.51-.305-.774-.055-.16-.11-.323-.293-.35-.2-.031-.278.136-.356.276-.313.572-.434 1.202-.422 1.84.027 1.436.633 2.58 1.838 3.393.137.093.172.187.129.323-.082.28-.18.552-.266.833-.055.179-.137.217-.329.14a5.526 5.526 0 01-1.736-1.18c-.857-.828-1.631-1.742-2.597-2.458a11.365 11.365 0 00-.689-.471c-.985-.957.13-1.743.388-1.836.27-.098.093-.432-.779-.428-.872.004-1.67.295-2.687.684a3.055 3.055 0 01-.465.137 9.597 9.597 0 00-2.883-.102c-1.885.21-3.39 1.102-4.497 2.623C.082 8.606-.231 10.684.152 12.85c.403 2.284 1.569 4.175 3.36 5.653 1.858 1.533 3.997 2.284 6.438 2.14 1.482-.085 3.133-.284 4.994-1.86.47.234.962.327 1.78.397.63.059 1.236-.03 1.705-.128.735-.156.684-.837.419-.961-2.155-1.004-1.682-.595-2.113-.926 1.096-1.296 2.746-2.642 3.392-7.003.05-.347.007-.565 0-.845-.004-.17.035-.237.23-.256a4.173 4.173 0 001.545-.475c1.396-.763 1.96-2.015 2.093-3.517.02-.23-.004-.467-.247-.588zM11.581 18c-2.089-1.642-3.102-2.183-3.52-2.16-.392.024-.321.471-.235.763.09.288.207.486.371.739.114.167.192.416-.113.603-.673.416-1.842-.14-1.897-.167-1.361-.802-2.5-1.86-3.301-3.307-.774-1.393-1.224-2.887-1.298-4.482-.02-.386.093-.522.477-.592a4.696 4.696 0 011.529-.039c2.132.312 3.946 1.265 5.468 2.774.868.86 1.525 1.887 2.202 2.891.72 1.066 1.494 2.082 2.48 2.914.348.292.625.514.891.677-.802.09-2.14.11-3.054-.614zm1-6.44a.306.306 0 01.415-.287.302.302 0 01.2.288.306.306 0 01-.31.307.303.303 0 01-.304-.308zm3.11 1.596c-.2.081-.399.151-.59.16a1.245 1.245 0 01-.798-.254c-.274-.23-.47-.358-.552-.758a1.73 1.73 0 01.016-.588c.07-.327-.008-.537-.239-.727-.187-.156-.426-.199-.688-.199a.559.559 0 01-.254-.078c-.11-.054-.2-.19-.114-.358.028-.054.16-.186.192-.21.356-.202.767-.136 1.146.016.352.144.618.408 1.001.782.391.451.462.576.685.914.176.265.336.537.445.848.067.195-.019.354-.25.452z" fill="#4D6BFE"></path></svg>\ No newline at end of filediff --git a/desktop/assets/model-icons/gemma.png b/desktop/assets/model-icons/gemma.pngnew file mode 100644index 000000000..e97de5b87Binary files /dev/null and b/desktop/assets/model-icons/gemma.png differdiff --git a/desktop/assets/model-icons/gemma.svg b/desktop/assets/model-icons/gemma.svgnew file mode 100644index 000000000..92c3a5237--- /dev/null+++ b/desktop/assets/model-icons/gemma.svg@@ -0,0 +1 @@+<svg height="1em" style="flex:none;line-height:1" viewBox="0 0 24 24" width="1em" xmlns="http://www.w3.org/2000/svg"><title>Gemma</title><defs><linearGradient id="lobe-icons-gemma-_R_0_" x1="24.419%" x2="75.194%" y1="75.581%" y2="25.194%"><stop offset="0%" stop-color="#446EFF"></stop><stop offset="36.661%" stop-color="#2E96FF"></stop><stop offset="83.221%" stop-color="#B1C5FF"></stop></linearGradient></defs><path d="M12.34 5.953a8.233 8.233 0 01-.247-1.125V3.72a8.25 8.25 0 015.562 2.232H12.34zm-.69 0c.113-.373.199-.755.257-1.145V3.72a8.25 8.25 0 00-5.562 2.232h5.304zm-5.433.187h5.373a7.98 7.98 0 01-.267.696 8.41 8.41 0 01-1.76 2.65L6.216 6.14zm-.264-.187H2.977v.187h2.915a8.436 8.436 0 00-2.357 5.767H0v.186h3.535a8.436 8.436 0 002.357 5.767H2.977v.186h2.976v2.977h.187v-2.915a8.436 8.436 0 005.767 2.357V24h.186v-3.535a8.436 8.436 0 005.767-2.357v2.915h.186v-2.977h2.977v-.186h-2.915a8.436 8.436 0 002.357-5.767H24v-.186h-3.535a8.436 8.436 0 00-2.357-5.767h2.915v-.187h-2.977V2.977h-.186v2.915a8.436 8.436 0 00-5.767-2.357V0h-.186v3.535A8.436 8.436 0 006.14 5.892V2.977h-.187v2.976zm6.14 14.326a8.25 8.25 0 005.562-2.233H12.34c-.108.367-.19.743-.247 1.126v1.107zm-.186-1.087a8.015 8.015 0 00-.258-1.146H6.345a8.25 8.25 0 005.562 2.233v-1.087zm-8.186-7.285h1.107a8.23 8.23 0 001.125-.247V6.345a8.25 8.25 0 00-2.232 5.562zm1.087.186H3.72a8.25 8.25 0 002.232 5.562v-5.304a8.012 8.012 0 00-1.145-.258zm15.47-.186a8.25 8.25 0 00-2.232-5.562v5.315c.367.108.743.19 1.126.247h1.107zm-1.086.186c-.39.058-.772.144-1.146.258v5.304a8.25 8.25 0 002.233-5.562h-1.087zm-1.332 5.69V12.41a7.97 7.97 0 00-.696.267 8.409 8.409 0 00-2.65 1.76l3.346 3.346zm0-6.18v-5.45l-.012-.013h-5.451c.076.235.162.468.26.696a8.698 8.698 0 001.819 2.688 8.698 8.698 0 002.688 1.82c.228.097.46.183.696.259zM6.14 17.848V12.41c.235.078.468.167.696.267a8.403 8.403 0 012.688 1.799 8.404 8.404 0 011.799 2.688c.1.228.19.46.267.696H6.152l-.012-.012zm0-6.245V6.326l3.29 3.29a8.716 8.716 0 01-2.594 1.728 8.14 8.14 0 01-.696.259zm6.257 6.257h5.277l-3.29-3.29a8.716 8.716 0 00-1.728 2.594 8.135 8.135 0 00-.259.696zm-2.347-7.81a9.435 9.435 0 01-2.88 1.96 9.14 9.14 0 012.88 1.94 9.14 9.14 0 011.94 2.88 9.435 9.435 0 011.96-2.88 9.14 9.14 0 012.88-1.94 9.435 9.435 0 01-2.88-1.96 9.434 9.434 0 01-1.96-2.88 9.14 9.14 0 01-1.94 2.88z" fill="url(#lobe-icons-gemma-_R_0_)" fill-rule="evenodd"></path></svg>\ No newline at end of filediff --git a/desktop/assets/model-icons/kimi.png b/desktop/assets/model-icons/kimi.pngnew file mode 100644index 000000000..c956b6909Binary files /dev/null and b/desktop/assets/model-icons/kimi.png differdiff --git a/desktop/assets/model-icons/kimi.svg b/desktop/assets/model-icons/kimi.svgnew file mode 100644index 000000000..83878fa28--- /dev/null+++ b/desktop/assets/model-icons/kimi.svg@@ -0,0 +1 @@+<svg height="1em" style="flex:none;line-height:1" viewBox="0 0 24 24" width="1em" xmlns="http://www.w3.org/2000/svg"><title>Kimi</title><path d="M21.846 0a1.923 1.923 0 110 3.846H20.15a.226.226 0 01-.227-.226V1.923C19.923.861 20.784 0 21.846 0z" fill="#1783FF"></path><path d="M11.065 11.199l7.257-7.2c.137-.136.06-.41-.116-.41H14.3a.164.164 0 00-.117.051l-7.82 7.756c-.122.12-.302.013-.302-.179V3.82c0-.127-.083-.23-.185-.23H3.186c-.103 0-.186.103-.186.23V19.77c0 .128.083.23.186.23h2.69c.103 0 .186-.102.186-.23v-3.25c0-.069.025-.135.069-.178l2.424-2.406a.158.158 0 01.205-.023l6.484 4.772a7.677 7.677 0 003.453 1.283c.108.012.2-.095.2-.23v-3.06c0-.117-.07-.212-.164-.227a5.028 5.028 0 01-2.027-.807l-5.613-4.064c-.117-.078-.132-.279-.028-.381z" fill="#fff"></path></svg>\ No newline at end of filediff --git a/desktop/assets/model-icons/meta.png b/desktop/assets/model-icons/meta.pngnew file mode 100644index 000000000..ca97d552aBinary files /dev/null and b/desktop/assets/model-icons/meta.png differdiff --git a/desktop/assets/model-icons/meta.svg b/desktop/assets/model-icons/meta.svgnew file mode 100644index 000000000..a8a8d9485--- /dev/null+++ b/desktop/assets/model-icons/meta.svg@@ -0,0 +1 @@+<svg height="1em" style="flex:none;line-height:1" viewBox="0 0 24 24" width="1em" xmlns="http://www.w3.org/2000/svg"><title>Meta</title><path d="M6.897 4h-.024l-.031 2.615h.022c1.715 0 3.046 1.357 5.94 6.246l.175.297.012.02 1.62-2.438-.012-.019a48.763 48.763 0 00-1.098-1.716 28.01 28.01 0 00-1.175-1.629C10.413 4.932 8.812 4 6.896 4z" fill="url(#lobe-icons-meta-0-_R_0_)"></path><path d="M6.873 4C4.95 4.01 3.247 5.258 2.02 7.17a4.352 4.352 0 00-.01.017l2.254 1.231.011-.017c.718-1.083 1.61-1.774 2.568-1.785h.021L6.896 4h-.023z" fill="url(#lobe-icons-meta-1-_R_0_)"></path><path d="M2.019 7.17l-.011.017C1.2 8.447.598 9.995.274 11.664l-.005.022 2.534.6.004-.022c.27-1.467.786-2.828 1.456-3.845l.011-.017L2.02 7.17z" fill="url(#lobe-icons-meta-2-_R_0_)"></path><path d="M2.807 12.264l-2.533-.6-.005.022c-.177.918-.267 1.851-.269 2.786v.023l2.598.233v-.023a12.591 12.591 0 01.21-2.44z" fill="url(#lobe-icons-meta-3-_R_0_)"></path><path d="M2.677 15.537a5.462 5.462 0 01-.079-.813v-.022L0 14.468v.024a8.89 8.89 0 00.146 1.652l2.535-.585a4.106 4.106 0 01-.004-.022z" fill="url(#lobe-icons-meta-4-_R_0_)"></path><path d="M3.27 16.89c-.284-.31-.484-.756-.589-1.328l-.004-.021-2.535.585.004.021c.192 1.01.568 1.85 1.106 2.487l.014.017 2.018-1.745a2.106 2.106 0 01-.015-.016z" fill="url(#lobe-icons-meta-5-_R_0_)"></path><path d="M10.78 9.654c-1.528 2.35-2.454 3.825-2.454 3.825-2.035 3.2-2.739 3.917-3.871 3.917a1.545 1.545 0 01-1.186-.508l-2.017 1.744.014.017C2.01 19.518 3.058 20 4.356 20c1.963 0 3.374-.928 5.884-5.33l1.766-3.13a41.283 41.283 0 00-1.227-1.886z" fill="#0082FB"></path><path d="M13.502 5.946l-.016.016c-.4.43-.786.908-1.16 1.416.378.483.768 1.024 1.175 1.63.48-.743.928-1.345 1.367-1.807l.016-.016-1.382-1.24z" fill="url(#lobe-icons-meta-6-_R_0_)"></path><path d="M20.918 5.713C19.853 4.633 18.583 4 17.225 4c-1.432 0-2.637.787-3.723 1.944l-.016.016 1.382 1.24.016-.017c.715-.747 1.408-1.12 2.176-1.12.826 0 1.6.39 2.27 1.075l.015.016 1.589-1.425-.016-.016z" fill="#0082FB"></path><path d="M23.998 14.125c-.06-3.467-1.27-6.566-3.064-8.396l-.016-.016-1.588 1.424.015.016c1.35 1.392 2.277 3.98 2.361 6.971v.023h2.292v-.022z" fill="url(#lobe-icons-meta-7-_R_0_)"></path><path d="M23.998 14.15v-.023h-2.292v.022c.004.14.006.282.006.424 0 .815-.121 1.474-.368 1.95l-.011.022 1.708 1.782.013-.02c.62-.96.946-2.293.946-3.91 0-.083 0-.165-.002-.247z" fill="url(#lobe-icons-meta-8-_R_0_)"></path><path d="M21.344 16.52l-.011.02c-.214.402-.519.67-.917.787l.778 2.462a3.493 3.493 0 00.438-.182 3.558 3.558 0 001.366-1.218l.044-.065.012-.02-1.71-1.784z" fill="url(#lobe-icons-meta-9-_R_0_)"></path><path d="M19.92 17.393c-.262 0-.492-.039-.718-.14l-.798 2.522c.449.153.927.222 1.46.222.492 0 .943-.073 1.352-.215l-.78-2.462c-.167.05-.341.075-.517.073z" fill="url(#lobe-icons-meta-10-_R_0_)"></path><path d="M18.323 16.534l-.014-.017-1.836 1.914.016.017c.637.682 1.246 1.105 1.937 1.337l.797-2.52c-.291-.125-.573-.353-.9-.731z" fill="url(#lobe-icons-meta-11-_R_0_)"></path><path d="M18.309 16.515c-.55-.642-1.232-1.712-2.303-3.44l-1.396-2.336-.011-.02-1.62 2.438.012.02.989 1.668c.959 1.61 1.74 2.774 2.493 3.585l.016.016 1.834-1.914a2.353 2.353 0 01-.014-.017z" fill="url(#lobe-icons-meta-12-_R_0_)"></path><defs><linearGradient id="lobe-icons-meta-0-_R_0_" x1="75.897%" x2="26.312%" y1="89.199%" y2="12.194%"><stop offset=".06%" stop-color="#0867DF"></stop><stop offset="45.39%" stop-color="#0668E1"></stop><stop offset="85.91%" stop-color="#0064E0"></stop></linearGradient><linearGradient id="lobe-icons-meta-1-_R_0_" x1="21.67%" x2="97.068%" y1="75.874%" y2="23.985%"><stop offset="13.23%" stop-color="#0064DF"></stop><stop offset="99.88%" stop-color="#0064E0"></stop></linearGradient><linearGradient id="lobe-icons-meta-2-_R_0_" x1="38.263%" x2="60.895%" y1="89.127%" y2="16.131%"><stop offset="1.47%" stop-color="#0072EC"></stop><stop offset="68.81%" stop-color="#0064DF"></stop></linearGradient><linearGradient id="lobe-icons-meta-3-_R_0_" x1="47.032%" x2="52.15%" y1="90.19%" y2="15.745%"><stop offset="7.31%" stop-color="#007CF6"></stop><stop offset="99.43%" stop-color="#0072EC"></stop></linearGradient><linearGradient id="lobe-icons-meta-4-_R_0_" x1="52.155%" x2="47.591%" y1="58.301%" y2="37.004%"><stop offset="7.31%" stop-color="#007FF9"></stop><stop offset="100%" stop-color="#007CF6"></stop></linearGradient><linearGradient id="lobe-icons-meta-5-_R_0_" x1="37.689%" x2="61.961%" y1="12.502%" y2="63.624%"><stop offset="7.31%" stop-color="#007FF9"></stop><stop offset="100%" stop-color="#0082FB"></stop></linearGradient><linearGradient id="lobe-icons-meta-6-_R_0_" x1="34.808%" x2="62.313%" y1="68.859%" y2="23.174%"><stop offset="27.99%" stop-color="#007FF8"></stop><stop offset="91.41%" stop-color="#0082FB"></stop></linearGradient><linearGradient id="lobe-icons-meta-7-_R_0_" x1="43.762%" x2="57.602%" y1="6.235%" y2="98.514%"><stop offset="0%" stop-color="#0082FB"></stop><stop offset="99.95%" stop-color="#0081FA"></stop></linearGradient><linearGradient id="lobe-icons-meta-8-_R_0_" x1="60.055%" x2="39.88%" y1="4.661%" y2="69.077%"><stop offset="6.19%" stop-color="#0081FA"></stop><stop offset="100%" stop-color="#0080F9"></stop></linearGradient><linearGradient id="lobe-icons-meta-9-_R_0_" x1="30.282%" x2="61.081%" y1="59.32%" y2="33.244%"><stop offset="0%" stop-color="#027AF3"></stop><stop offset="100%" stop-color="#0080F9"></stop></linearGradient><linearGradient id="lobe-icons-meta-10-_R_0_" x1="20.433%" x2="82.112%" y1="50.001%" y2="50.001%"><stop offset="0%" stop-color="#0377EF"></stop><stop offset="99.94%" stop-color="#0279F1"></stop></linearGradient><linearGradient id="lobe-icons-meta-11-_R_0_" x1="40.303%" x2="72.394%" y1="35.298%" y2="57.811%"><stop offset=".19%" stop-color="#0471E9"></stop><stop offset="100%" stop-color="#0377EF"></stop></linearGradient><linearGradient id="lobe-icons-meta-12-_R_0_" x1="32.254%" x2="68.003%" y1="19.719%" y2="84.908%"><stop offset="27.65%" stop-color="#0867DF"></stop><stop offset="100%" stop-color="#0471E9"></stop></linearGradient></defs></svg>\ No newline at end of filediff --git a/desktop/assets/model-icons/microsoft.png b/desktop/assets/model-icons/microsoft.pngnew file mode 100644index 000000000..821c8ec78Binary files /dev/null and b/desktop/assets/model-icons/microsoft.png differdiff --git a/desktop/assets/model-icons/microsoft.svg b/desktop/assets/model-icons/microsoft.svgnew file mode 100644index 000000000..4d95a08eb--- /dev/null+++ b/desktop/assets/model-icons/microsoft.svg@@ -0,0 +1 @@+<svg height="1em" style="flex:none;line-height:1" viewBox="0 0 24 24" width="1em" xmlns="http://www.w3.org/2000/svg"><title>Azure</title><path d="M11.49 2H2v9.492h9.492V2h-.002z" fill="#F25022"></path><path d="M22 2h-9.492v9.492H22V2z" fill="#7FBA00"></path><path d="M11.49 12.508H2V22h9.492v-9.492h-.002z" fill="#00A4EF"></path><path d="M22 12.508h-9.492V22H22v-9.492z" fill="#FFB900"></path></svg>\ No newline at end of filediff --git a/desktop/assets/model-icons/mistral.png b/desktop/assets/model-icons/mistral.pngnew file mode 100644index 000000000..6c5ae32deBinary files /dev/null and b/desktop/assets/model-icons/mistral.png differdiff --git a/desktop/assets/model-icons/mistral.svg b/desktop/assets/model-icons/mistral.svgnew file mode 100644index 000000000..8e03e244b--- /dev/null+++ b/desktop/assets/model-icons/mistral.svg@@ -0,0 +1 @@+<svg height="1em" style="flex:none;line-height:1" viewBox="0 0 24 24" width="1em" xmlns="http://www.w3.org/2000/svg"><title>Mistral</title><path d="M3.428 3.4h3.429v3.428H3.428V3.4zm13.714 0h3.43v3.428h-3.43V3.4z" fill="gold"></path><path d="M3.428 6.828h6.857v3.429H3.429V6.828zm10.286 0h6.857v3.429h-6.857V6.828z" fill="#FFAF00"></path><path d="M3.428 10.258h17.144v3.428H3.428v-3.428z" fill="#FF8205"></path><path d="M3.428 13.686h3.429v3.428H3.428v-3.428zm6.858 0h3.429v3.428h-3.429v-3.428zm6.856 0h3.43v3.428h-3.43v-3.428z" fill="#FA500F"></path><path d="M0 17.114h10.286v3.429H0v-3.429zm13.714 0H24v3.429H13.714v-3.429z" fill="#E10500"></path></svg>\ No newline at end of filediff --git a/desktop/assets/model-icons/openai.png b/desktop/assets/model-icons/openai.pngnew file mode 100644index 000000000..d7a569dd3Binary files /dev/null and b/desktop/assets/model-icons/openai.png differdiff --git a/desktop/assets/model-icons/openai.svg b/desktop/assets/model-icons/openai.svgnew file mode 100644index 000000000..78caf4fa2--- /dev/null+++ b/desktop/assets/model-icons/openai.svg@@ -0,0 +1 @@+<svg fill="currentColor" fill-rule="evenodd" height="1em" style="flex:none;line-height:1" viewBox="0 0 24 24" width="1em" xmlns="http://www.w3.org/2000/svg"><title>OpenAI</title><path d="M9.205 8.658v-2.26c0-.19.072-.333.238-.428l4.543-2.616c.619-.357 1.356-.523 2.117-.523 2.854 0 4.662 2.212 4.662 4.566 0 .167 0 .357-.024.547l-4.71-2.759a.797.797 0 00-.856 0l-5.97 3.473zm10.609 8.8V12.06c0-.333-.143-.57-.429-.737l-5.97-3.473 1.95-1.118a.433.433 0 01.476 0l4.543 2.617c1.309.76 2.189 2.378 2.189 3.948 0 1.808-1.07 3.473-2.76 4.163zM7.802 12.703l-1.95-1.142c-.167-.095-.239-.238-.239-.428V5.899c0-2.545 1.95-4.472 4.591-4.472 1 0 1.927.333 2.712.928L8.23 5.067c-.285.166-.428.404-.428.737v6.898zM12 15.128l-2.795-1.57v-3.33L12 8.658l2.795 1.57v3.33L12 15.128zm1.796 7.23c-1 0-1.927-.332-2.712-.927l4.686-2.712c.285-.166.428-.404.428-.737v-6.898l1.974 1.142c.167.095.238.238.238.428v5.233c0 2.545-1.974 4.472-4.614 4.472zm-5.637-5.303l-4.544-2.617c-1.308-.761-2.188-2.378-2.188-3.948A4.482 4.482 0 014.21 6.327v5.423c0 .333.143.571.428.738l5.947 3.449-1.95 1.118a.432.432 0 01-.476 0zm-.262 3.9c-2.688 0-4.662-2.021-4.662-4.519 0-.19.024-.38.047-.57l4.686 2.71c.286.167.571.167.856 0l5.97-3.448v2.26c0 .19-.07.333-.237.428l-4.543 2.616c-.619.357-1.356.523-2.117.523zm5.899 2.83a5.947 5.947 0 005.827-4.756C22.287 18.339 24 15.84 24 13.296c0-1.665-.713-3.282-1.998-4.448.119-.5.19-.999.19-1.498 0-3.401-2.759-5.947-5.946-5.947-.642 0-1.26.095-1.88.31A5.962 5.962 0 0010.205 0a5.947 5.947 0 00-5.827 4.757C1.713 5.447 0 7.945 0 10.49c0 1.666.713 3.283 1.998 4.448-.119.5-.19 1-.19 1.499 0 3.401 2.759 5.946 5.946 5.946.642 0 1.26-.095 1.88-.309a5.96 5.96 0 004.162 1.713z"></path></svg>\ No newline at end of filediff --git a/desktop/assets/model-icons/qwen.png b/desktop/assets/model-icons/qwen.pngnew file mode 100644index 000000000..2befc0f75Binary files /dev/null and b/desktop/assets/model-icons/qwen.png differdiff --git a/desktop/assets/model-icons/qwen.svg b/desktop/assets/model-icons/qwen.svgnew file mode 100644index 000000000..f2d0ada16--- /dev/null+++ b/desktop/assets/model-icons/qwen.svg@@ -0,0 +1 @@+<svg height="1em" style="flex:none;line-height:1" viewBox="0 0 24 24" width="1em" xmlns="http://www.w3.org/2000/svg"><title>Qwen</title><path d="M12.604 1.34c.393.69.784 1.382 1.174 2.075a.18.18 0 00.157.091h5.552c.174 0 .322.11.446.327l1.454 2.57c.19.337.24.478.024.837-.26.43-.513.864-.76 1.3l-.367.658c-.106.196-.223.28-.04.512l2.652 4.637c.172.301.111.494-.043.77-.437.785-.882 1.564-1.335 2.34-.159.272-.352.375-.68.37-.777-.016-1.552-.01-2.327.016a.099.099 0 00-.081.05 575.097 575.097 0 01-2.705 4.74c-.169.293-.38.363-.725.364-.997.003-2.002.004-3.017.002a.537.537 0 01-.465-.271l-1.335-2.323a.09.09 0 00-.083-.049H4.982c-.285.03-.553-.001-.805-.092l-1.603-2.77a.543.543 0 01-.002-.54l1.207-2.12a.198.198 0 000-.197 550.951 550.951 0 01-1.875-3.272l-.79-1.395c-.16-.31-.173-.496.095-.965.465-.813.927-1.625 1.387-2.436.132-.234.304-.334.584-.335a338.3 338.3 0 012.589-.001.124.124 0 00.107-.063l2.806-4.895a.488.488 0 01.422-.246c.524-.001 1.053 0 1.583-.006L11.704 1c.341-.003.724.032.9.34zm-3.432.403a.06.06 0 00-.052.03L6.254 6.788a.157.157 0 01-.135.078H3.253c-.056 0-.07.025-.041.074l5.81 10.156c.025.042.013.062-.034.063l-2.795.015a.218.218 0 00-.2.116l-1.32 2.31c-.044.078-.021.118.068.118l5.716.008c.046 0 .08.02.104.061l1.403 2.454c.046.081.092.082.139 0l5.006-8.76.783-1.382a.055.055 0 01.096 0l1.424 2.53a.122.122 0 00.107.062l2.763-.02a.04.04 0 00.035-.02.041.041 0 000-.04l-2.9-5.086a.108.108 0 010-.113l.293-.507 1.12-1.977c.024-.041.012-.062-.035-.062H9.2c-.059 0-.073-.026-.043-.077l1.434-2.505a.107.107 0 000-.114L9.225 1.774a.06.06 0 00-.053-.031zm6.29 8.02c.046 0 .058.02.034.06l-.832 1.465-2.613 4.585a.056.056 0 01-.05.029.058.058 0 01-.05-.029L8.498 9.841c-.02-.034-.01-.052.028-.054l.216-.012 6.722-.012z" fill="url(#lobe-icons-qwen-_R_0_)" fill-rule="nonzero"></path><defs><linearGradient id="lobe-icons-qwen-_R_0_" x1="0%" x2="100%" y1="0%" y2="0%"><stop offset="0%" stop-color="#6336E7" stop-opacity=".84"></stop><stop offset="100%" stop-color="#6F69F7" stop-opacity=".84"></stop></linearGradient></defs></svg>\ No newline at end of filediff --git a/desktop/assets/model-icons/zai.png b/desktop/assets/model-icons/zai.pngnew file mode 100644index 000000000..dc8305b02Binary files /dev/null and b/desktop/assets/model-icons/zai.png differdiff --git a/desktop/assets/model-icons/zai.svg b/desktop/assets/model-icons/zai.svgnew file mode 100644index 000000000..04ba2d985--- /dev/null+++ b/desktop/assets/model-icons/zai.svg@@ -0,0 +1 @@+<svg fill="currentColor" fill-rule="evenodd" height="1em" style="flex:none;line-height:1" viewBox="0 0 24 24" width="1em" xmlns="http://www.w3.org/2000/svg"><title>Z.ai</title><path d="M12.105 2L9.927 4.953H.653L2.83 2h9.276zM23.254 19.048L21.078 22h-9.242l2.174-2.952h9.244zM24 2L9.264 22H0L14.736 2H24z"></path></svg>\ No newline at end of filediff --git a/desktop/assets/models.LICENSE b/desktop/assets/models.LICENSEnew file mode 100644index 000000000..718bb3f0e--- /dev/null+++ b/desktop/assets/models.LICENSE@@ -0,0 +1,43 @@+ISC License++Copyright (c) 2026 Lucide Icons and Contributors++Permission to use, copy, modify, and/or distribute this software for any+purpose with or without fee is hereby granted, provided that the above+copyright notice and this permission notice appear in all copies.++THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES+WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF+MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR+ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES+WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN+ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF+OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.++---++The following Lucide icons are derived from the Feather project:++airplay, alert-circle, alert-octagon, alert-triangle, aperture, arrow-down-circle, arrow-down-left, arrow-down-right, arrow-down, arrow-left-circle, arrow-left, arrow-right-circle, arrow-right, arrow-up-circle, arrow-up-left, arrow-up-right, arrow-up, at-sign, calendar, cast, check, chevron-down, chevron-left, chevron-right, chevron-up, chevrons-down, chevrons-left, chevrons-right, chevrons-up, circle, clipboard, clock, code, columns, command, compass, corner-down-left, corner-down-right, corner-left-down, corner-left-up, corner-right-down, corner-right-up, corner-up-left, corner-up-right, crosshair, database, divide-circle, divide-square, dollar-sign, download, external-link, feather, frown, hash, headphones, help-circle, info, italic, key, layout, life-buoy, link-2, link, loader, lock, log-in, log-out, maximize, meh, minimize, minimize-2, minus-circle, minus-square, minus, monitor, moon, more-horizontal, more-vertical, move, music, navigation-2, navigation, octagon, pause-circle, percent, plus-circle, plus-square, plus, power, radio, rss, search, server, share, shopping-bag, sidebar, smartphone, smile, square, table-2, tablet, target, terminal, trash-2, trash, triangle, tv, type, upload, x-circle, x-octagon, x-square, x, zoom-in, zoom-out++The MIT License (MIT) (for the icons listed above)++Copyright (c) 2013-present Cole Bemis++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/desktop/assets/models.png b/desktop/assets/models.pngnew file mode 100644index 000000000..b77488f42Binary files /dev/null and b/desktop/assets/models.png differdiff --git a/desktop/assets/models.svg b/desktop/assets/models.svgnew file mode 100644index 000000000..d7aa64a23--- /dev/null+++ b/desktop/assets/models.svg@@ -0,0 +1,37 @@+<svg version="1.1"+ xmlns="http://www.w3.org/2000/svg"+ width="256"+ height="256"+ viewBox="0 0 24 24"+ fill="none"+ stroke="#B5A0FF"+ stroke-width="1.8"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <!-- Lucide Brain: https://lucide.dev/icons/brain+ISC License++Copyright (c) 2026 Lucide Icons and Contributors++Permission to use, copy, modify, and/or distribute this software for any+purpose with or without fee is hereby granted, provided that the above+copyright notice and this permission notice appear in all copies.++THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES+WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF+MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR+ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES+WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN+ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF+OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.+ -->+ <path d="M12 18V5" />+ <path d="M15 13a4.17 4.17 0 0 1-3-4 4.17 4.17 0 0 1-3 4" />+ <path d="M17.598 6.5A3 3 0 1 0 12 5a3 3 0 1 0-5.598 1.5" />+ <path d="M17.997 5.125a4 4 0 0 1 2.526 5.77" />+ <path d="M18 18a4 4 0 0 0 2-7.464" />+ <path d="M19.967 17.483A4 4 0 1 1 12 18a4 4 0 1 1-7.967-.517" />+ <path d="M6 18a4 4 0 0 1-2-7.464" />+ <path d="M6.003 5.125a4 4 0 0 0-2.526 5.77" />+</svg>diff --git a/desktop/lib/e2ee/envelope.dart b/desktop/lib/e2ee/envelope.dartindex 6a5976dc3..62b637dd2 100644--- a/desktop/lib/e2ee/envelope.dart+++ b/desktop/lib/e2ee/envelope.dart@@ -17,6 +17,9 @@ const Set<String> encryptedDownTypes = {'grid_fleet_capabilities','grid_fleet_run','grid_fleet_cancel',+ 'grid_fleet_models_list',+ 'grid_fleet_model_start',+ 'grid_fleet_model_stop','message','question_response','agents_list',@@ -65,8 +68,13 @@ const Set<String> encryptedDownTypes = {'p2p_promote',};-Uint8List _aad(int v, String type, String dbSessionId, String k, String epoch) =>- utf8Bytes('$v|$type|$dbSessionId|$k|$epoch');+Uint8List _aad(+ int v,+ String type,+ String dbSessionId,+ String k,+ String epoch,+) => utf8Bytes('$v|$type|$dbSessionId|$k|$epoch');/// Seals [payload] under [key]: [k] is 'p' (pairwise session) or 'g' (the machine's group key,/// which also carries an [epoch]).@@ -102,7 +110,11 @@ Map<String, dynamic>? unwrapPayload() {final v = env['v'], k = env['k'], n = env['n'], ct = env['ct'];final epoch = env['epoch'] ?? '';- if (v is! int || k is! String || n is! int || ct is! String || epoch is! String) {+ if (v is! int ||+ k is! String ||+ n is! int ||+ ct is! String ||+ epoch is! String) {return null;}final Uint8List sealed;@@ -111,11 +123,17 @@ Map<String, dynamic>? unwrapPayload(} on FormatException {return null;}- final clear = aeadOpen(key, n, _aad(v, frameType, dbSessionId ?? '', k, epoch), sealed);+ final clear = aeadOpen(+ key,+ n,+ _aad(v, frameType, dbSessionId ?? '', k, epoch),+ sealed,+ );return clear == null ? null : jsonObjectOf(clear);}-bool isWrapped(Object? payload) => payload is Map && payload.containsKey('__e2e');+bool isWrapped(Object? payload) =>+ payload is Map && payload.containsKey('__e2e');/// UTF-8 JSON that must be an object; null for anything else.Map<String, dynamic>? jsonObjectOf(List<int> utf8Json) {diff --git a/desktop/lib/models/local_model.dart b/desktop/lib/models/local_model.dartnew file mode 100644index 000000000..68f42b2fb--- /dev/null+++ b/desktop/lib/models/local_model.dart@@ -0,0 +1,93 @@+/// The local daemon reports lifecycle and measured telemetry. Unknown values+/// stay absent; a weights file's size is never relabelled as memory use.+class LocalModel {+ const LocalModel({+ required this.id,+ required this.name,+ this.state = 'available',+ this.sizeBytes,+ this.quant,+ this.recommended = false,+ this.canStart = false,+ this.canStop = false,+ this.tokensPerSecond,+ this.requests,+ this.windowSeconds,+ this.operation,+ });+ final String id, name, state;+ final String? quant;+ final double? sizeBytes, tokensPerSecond, requests, windowSeconds;+ final bool recommended, canStart, canStop;+ final LocalModelOperation? operation;+ bool get running => state == 'running';+ bool get downloaded => state == 'downloaded' || running;++ factory LocalModel.fromJson(Map<String, dynamic> data) => LocalModel(+ id: data['id'] as String? ?? '',+ name: data['name'] as String? ?? '',+ state: data['state'] as String? ?? 'available',+ sizeBytes: _number(data['sizeBytes']),+ quant: data['quant'] as String?,+ recommended: data['recommended'] == true,+ canStart: data['canStart'] == true,+ canStop: data['canStop'] == true,+ tokensPerSecond: _number(data['tokensPerSecond']),+ requests: _number(data['requests']),+ windowSeconds: _number(data['windowSeconds']),+ operation: LocalModelOperation.parse(data['operation']),+ );+}++class LocalModelOperation {+ const LocalModelOperation({+ required this.id,+ required this.modelId,+ required this.action,+ required this.stage,+ required this.phase,+ this.progress,+ this.error,+ });+ final String id, modelId, action, stage, phase;+ final double? progress;+ final String? error;+ bool get active => phase == 'running';+ bool get failed => phase == 'failed';+ bool get started => phase == 'done' && action == 'start';+ String get label => switch (stage) {+ 'downloading' => 'Downloading',+ 'starting' => 'Starting',+ 'verifying' => 'Testing',+ 'stopping' => 'Stopping',+ _ => 'Checking',+ };+ static LocalModelOperation? parse(Object? raw) {+ if (raw is! Map<String, dynamic> ||+ raw['id'] is! String ||+ raw['modelId'] is! String ||+ !['start', 'stop'].contains(raw['action']) ||+ ![+ 'checking',+ 'downloading',+ 'starting',+ 'verifying',+ 'stopping',+ ].contains(raw['stage']) ||+ !['running', 'done', 'failed'].contains(raw['phase'])) {+ return null;+ }+ return LocalModelOperation(+ id: raw['id'] as String,+ modelId: raw['modelId'] as String,+ action: raw['action'] as String,+ stage: raw['stage'] as String,+ phase: raw['phase'] as String,+ progress: _number(raw['progress'])?.clamp(0, 1),+ error: raw['error'] as String?,+ );+ }+}++double? _number(Object? value) =>+ value is num && value.isFinite && value >= 0 ? value.toDouble() : null;diff --git a/desktop/lib/models/model_manager_controller.dart b/desktop/lib/models/model_manager_controller.dartnew file mode 100644index 000000000..b4761d2d2--- /dev/null+++ b/desktop/lib/models/model_manager_controller.dart@@ -0,0 +1,429 @@+import 'dart:async';++import 'package:flutter/foundation.dart';++import '../core/harness_file_store.dart';+import '../core/local_key_value_store.dart';+import '../core/models.dart';+import '../core/project_folder.dart';+import '../core/test_run.dart';+import '../state/app_state.dart';+import '../widgets/grid_model_picker.dart' show modelPickerSupports;+import 'local_model.dart';++const modelManagerName = 'Model Manager';++/// Shared by the toolbar, panel and picker. The daemon owns downloads and+/// engines; closing a surface never cancels work or creates a conversation.+class ModelManagerController extends ChangeNotifier {+ ModelManagerController(+ this.app, {+ LocalKeyValueStore? storage,+ this.poll = true,+ }) : _storage = storage ?? (kUnderTest ? null : HarnessFileStore.shared);+ final AppNotifier app;+ final LocalKeyValueStore? _storage;+ final bool poll;+ static const introKey = 'models.introduction.dismissed';+ MachineState? _machine;+ Future<void>? _preparing, _opening, _refreshing;+ Timer? _timer;+ bool _started = false, _disposed = false, _preferencesLoaded = false;+ bool _introDismissed = false, _autoPrepared = false;+ AgentCreationAttempt? _creation;+ ProjectFolderRequest? _folder;+ DateTime? _lastModelsRead, _lastLocalRead;+ bool _panelVisible = false;+ int _actionRevision = 0;+ String? _dismissedReadyId;+ GridModels? models;+ List<LocalModel> localModels = const [];+ double? memoryBytes;+ String? hardware, error, _managerError;+ bool preparing = false, opening = false, scanning = false, loaded = false;+ bool inventoryAvailable = false, operationBusy = false;+ LocalModelOperation? pendingOperation;+ String? pendingId;+ bool pendingStart = true;++ MachineState? get machine => app.localMachineState;+ Agent? get manager => machine?.agents+ .where((a) => a.dsh == AppNotifier.gridHarness)+ .firstOrNull;+ List<GridSection> get sections => models?.sections ?? const [];+ bool get hasOwnModels => localModels.any((model) => model.running);+ bool get busy =>+ operationBusy || pendingId != null || pendingOperation?.active == true;+ bool get showIntroduction =>+ _preferencesLoaded &&+ !_introDismissed &&+ loaded &&+ localModels.isNotEmpty &&+ !hasOwnModels &&+ !busy &&+ app.machineStates.values.any(+ (m) => m.agents.any(+ (a) =>+ a.dsh != AppNotifier.gridHarness &&+ !a.isStopped &&+ modelPickerSupports(a.engine),+ ),+ );+ LocalModel? get readyModel => localModels+ .where(+ (m) =>+ m.running &&+ m.operation?.started == true &&+ m.operation?.id != _dismissedReadyId,+ )+ .firstOrNull;+ LocalModelOperation? operationFor(LocalModel model) =>+ pendingOperation?.modelId == model.id+ ? pendingOperation+ : model.operation;++ void dismissReady() {+ _dismissedReadyId = readyModel?.operation?.id;+ _changed();+ }++ void start() {+ if (_started || _disposed) return;+ _started = true;+ app.addListener(_observe);+ unawaited(_loadPreferences());+ _observe();+ if (poll) {+ _timer = Timer.periodic(const Duration(seconds: 4), (_) {+ if (busy ||+ _panelVisible ||+ _lastLocalRead == null ||+ DateTime.now().difference(_lastLocalRead!) >+ const Duration(seconds: 60)) {+ unawaited(refresh());+ }+ });+ }+ }++ Future<void> _loadPreferences() async {+ try {+ _introDismissed = await _storage?.read(introKey) == 'true';+ } catch (_) {}+ _preferencesLoaded = true;+ _changed();+ }++ void _observe() {+ if (_disposed) return;+ final current = machine;+ if (!identical(current, _machine)) {+ _machine = current;+ _autoPrepared = false;+ _creation = null;+ _folder = null;+ _preparing = null;+ _opening = null;+ _refreshing = null;+ _lastModelsRead = null;+ _lastLocalRead = null;+ preparing = false;+ opening = false;+ scanning = false;+ loaded = false;+ inventoryAvailable = false;+ operationBusy = false;+ pendingOperation = null;+ pendingId = null;+ _dismissedReadyId = null;+ models = null;+ localModels = const [];+ memoryBytes = null;+ hardware = null;+ error = null;+ _managerError = null;+ }+ if (current?.connectionStatus != ConnectionStatus.connected) {+ inventoryAvailable = false;+ }+ if (current != null &&+ current.connectionStatus == ConnectionStatus.connected &&+ current.agentLoadStatus == AgentLoadStatus.loaded &&+ !_autoPrepared) {+ _autoPrepared = true;+ unawaited(prepare());+ unawaited(refresh());+ }+ _changed();+ }++ bool _current(MachineState owner) => !_disposed && identical(machine, owner);+ void _changed() {+ if (!_disposed) notifyListeners();+ }++ Future<void> dismissIntroduction() async {+ _introDismissed = true;+ _changed();+ try {+ await _storage?.write(introKey, 'true');+ } catch (_) {}+ }++ Future<void> prepare() {+ final owner = machine;+ return _preparing ??= _prepare().whenComplete(() {+ if (identical(machine, owner)) _preparing = null;+ });+ }++ Future<void> _prepare() async {+ final owner = machine;+ if (owner == null || manager != null) return;+ preparing = true;+ _managerError = null;+ _changed();+ try {+ final id = owner.machine.machineId;+ await app.probeDsh(id);+ if (!_current(owner)) return;+ if (owner.dsh[AppNotifier.gridHarness]?.installed != true) {+ final failure = await app.installDsh(id, AppNotifier.gridHarness);+ if (!_current(owner)) return;+ if (failure != null) {+ _managerError = failure;+ return;+ }+ }+ if (manager != null) return;+ _creation ??= AgentCreationAttempt(background: true);+ _folder ??= ProjectFolderRequest.generated(+ label: 'model-manager',+ at: DateTime.now(),+ );+ final failure = await app.createAgent(+ id,+ engine: 'codex',+ folder: null,+ projectFolder: _folder,+ dsh: AppNotifier.gridHarness,+ name: modelManagerName,+ attempt: _creation,+ );+ if (_current(owner)) _managerError = failure;+ } catch (_) {+ if (_current(owner)) {+ _managerError = 'Model Manager could not open. Try again.';+ }+ } finally {+ if (_current(owner)) {+ preparing = false;+ _changed();+ }+ }+ }++ Future<void> open() {+ final owner = machine;+ return _opening ??= _open().whenComplete(() {+ if (identical(machine, owner)) _opening = null;+ });+ }++ Future<void> _open() async {+ final owner = machine;+ if (owner == null) {+ error = 'Connect this computer to open Model Manager.';+ _changed();+ return;+ }+ opening = true;+ error = null;+ _changed();+ try {+ if (_creation?.agentId == null &&+ _creation?.awaitingConfirmation == false &&+ !preparing) {+ _creation = null;+ }+ await prepare();+ if (!_current(owner)) return;+ final agent = manager;+ if (agent == null) {+ error =+ _managerError ??+ 'Model Manager is still starting. Try again in a moment.';+ return;+ }+ if (agent.isStopped) {+ final result = await app.resumeAgent(owner.machine.machineId, agent.id);+ if (!_current(owner)) return;+ if (result.error != null) {+ error = result.error;+ return;+ }+ }+ await _showAgent(owner, agent.id, modelManagerName);+ } catch (_) {+ if (_current(owner)) error = 'Could not open Model Manager. Try again.';+ } finally {+ if (_current(owner)) {+ opening = false;+ _changed();+ }+ }+ }++ Future<void> _showAgent(+ MachineState owner,+ String agentId,+ String title,+ ) async {+ // paneOfAgent searches only the selected tab. Opening from another session+ // must reveal the existing manager, including one still attaching.+ final tab = app.swarms+ .where(+ (swarm) => swarm.panes.any(+ (pane) =>+ pane.machineId == owner.machine.machineId &&+ pane.agentId == agentId,+ ),+ )+ .firstOrNull;+ if (tab != null) {+ app.selectSwarm(tab.id);+ await app.selectAgent(owner.machine.machineId, agentId);+ return;+ }+ app.newSwarm(name: title);+ await app.assignAgentToPane(null, owner.machine.machineId, agentId);+ }++ void setPanelVisible(bool visible) {+ _panelVisible = visible;+ }++ Future<void> refresh({bool force = false}) {+ final owner = machine;+ return _refreshing ??= _refresh(force: force).whenComplete(() {+ if (identical(machine, owner)) _refreshing = null;+ });+ }++ Future<void> _refresh({required bool force}) async {+ final owner = machine;+ if (owner == null || owner.connectionStatus != ConnectionStatus.connected) {+ inventoryAvailable = false;+ error = 'Connect this computer to see its models.';+ _changed();+ return;+ }+ scanning = true;+ _changed();+ final readShared =+ force ||+ _lastModelsRead == null ||+ DateTime.now().difference(_lastModelsRead!) >+ const Duration(seconds: 20);+ await Future.wait([+ if (readShared)+ app.gridModels(owner.machine.machineId).then((answer) {+ if (_current(owner)) {+ models = answer;+ _lastModelsRead = DateTime.now();+ }+ }),+ (() async {+ final revision = _actionRevision;+ try {+ final answer = await app.localModels(+ owner.machine.machineId,+ refresh: force,+ );+ if (!_current(owner) || revision != _actionRevision) return;+ error = answer['error'] as String?;+ if (answer['models'] is! List) {+ inventoryAvailable = false;+ return;+ }+ localModels = (answer['models'] as List)+ .whereType<Map<String, dynamic>>()+ .map(LocalModel.fromJson)+ .where((m) => m.id.isNotEmpty)+ .toList();+ final memory = answer['memoryBytes'];+ memoryBytes = memory is num && memory.isFinite && memory > 0+ ? memory.toDouble()+ : null;+ hardware = answer['hardware'] as String?;+ operationBusy = answer['busy'] == true;+ inventoryAvailable = true;+ loaded = true;+ _lastLocalRead = DateTime.now();+ // A daemon receipt supersedes our acknowledgement, including a completed+ // operation after a dropped connection. Never replay an uncertain click.+ if (pendingOperation != null &&+ (!operationBusy ||+ localModels.any(+ (m) => m.operation?.id == pendingOperation?.id,+ ))) {+ pendingOperation = null;+ }+ } catch (_) {+ if (_current(owner) && revision == _actionRevision) {+ inventoryAvailable = false;+ error = 'Models are unavailable. Try again.';+ }+ }+ })(),+ ]);+ if (_current(owner)) {+ scanning = false;+ _changed();+ }+ }++ Future<void> toggle(LocalModel model) async {+ final owner = machine;+ if (owner == null || busy || !inventoryAvailable) return;+ final startModel = !model.canStop;+ if (startModel && !model.canStart) return;+ pendingId = model.id;+ _actionRevision++;+ inventoryAvailable = false;+ pendingStart = startModel;+ error = null;+ unawaited(dismissIntroduction());+ _changed();+ try {+ final answer = await app.controlLocalModel(+ owner.machine.machineId,+ model.id,+ start: startModel,+ );+ if (!_current(owner)) return;+ error = answer['error'] as String?;+ pendingOperation = LocalModelOperation.parse(answer['operation']);+ operationBusy = pendingOperation?.active == true;+ } catch (_) {+ if (_current(owner)) error = 'Checking whether the model started. Your click will not be repeated.';+ } finally {+ if (_current(owner)) {+ pendingId = null;+ _changed();+ // Finish any inventory request issued before this click, then ask for+ // its receipt. A stale read must never overwrite a new acknowledgement.+ await _refreshing;+ if (_current(owner)) await refresh();+ }+ }+ }++ @override+ void dispose() {+ _disposed = true;+ _timer?.cancel();+ if (_started) app.removeListener(_observe);+ super.dispose();+ }+}diff --git a/desktop/lib/models/model_mark.dart b/desktop/lib/models/model_mark.dartnew file mode 100644index 000000000..10de74c52--- /dev/null+++ b/desktop/lib/models/model_mark.dart@@ -0,0 +1,65 @@+import 'package:flutter/material.dart';++/// Provider artwork for known models; the brain identifies Models and unknown models.+class ModelMark extends StatelessWidget {+ const ModelMark({super.key, this.model, this.size = 22, this.semanticLabel});++ final String? model;+ final double size;+ final String? semanticLabel;++ static const _brands = {+ 'qwen': 'qwen',+ 'qwq': 'qwen',+ 'gemma': 'gemma',+ 'deepseek': 'deepseek',+ 'gpt-oss': 'openai',+ 'openai': 'openai',+ 'codex': 'openai',+ 'llama': 'meta',+ 'mistral': 'mistral',+ 'mixtral': 'mistral',+ 'ministral': 'mistral',+ 'codestral': 'mistral',+ 'devstral': 'mistral',+ 'phi': 'microsoft',+ 'glm': 'zai',+ 'zai': 'zai',+ 'kimi': 'kimi',+ 'claude': 'claude',+ 'anthropic': 'claude',+ };+ static final _family = RegExp(+ '(?:^|[^a-z0-9])(${_brands.keys.join('|')})(?=\$|[^a-z])',+ );++ /// Match the model name, not a hosting organization or a coincidental substring.+ /// The first family wins for names such as DeepSeek-R1-Distill-Qwen.+ static String? assetFor(String? model) {+ final name = model?.trim().toLowerCase().split('/').last ?? '';+ final family = _family.firstMatch(name)?.group(1);+ return family == null ? null : 'assets/model-icons/${_brands[family]}.png';+ }++ @override+ Widget build(BuildContext context) {+ final asset = assetFor(model);+ final light = Theme.of(context).brightness == Brightness.light;+ final monochrome =+ asset == 'assets/model-icons/openai.png' ||+ asset == 'assets/model-icons/zai.png';+ return Image.asset(+ asset ?? 'assets/models.png',+ width: size,+ height: size,+ filterQuality: FilterQuality.high,+ color: monochrome+ ? (light ? const Color(0xff252429) : const Color(0xffeeeef0))+ : asset == null && light+ ? const Color(0xff7051c9)+ : null,+ semanticLabel: semanticLabel,+ excludeFromSemantics: semanticLabel == null,+ );+ }+}diff --git a/desktop/lib/models/models_panel.dart b/desktop/lib/models/models_panel.dartnew file mode 100644index 000000000..0b52c43de--- /dev/null+++ b/desktop/lib/models/models_panel.dart@@ -0,0 +1,693 @@+import 'dart:async';++import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:lucide_icons_flutter/lucide_icons.dart';++import '../shared/theme/app_theme.dart';+import '../theme/app_theme.dart';+import '../usage/models_menu_controller.dart';+import 'local_model.dart';+import 'model_manager_controller.dart';+import 'model_mark.dart';++class ModelsPanel extends StatefulWidget {+ const ModelsPanel({+ super.key,+ required this.controller,+ required this.subscriptions,+ required this.onClose,+ required this.onManage,+ });+ final ModelManagerController controller;+ final ModelsMenuController subscriptions;+ final VoidCallback onClose, onManage;+ @override+ State<ModelsPanel> createState() => _ModelsPanelState();+}++enum _Filter { all, running }++class _ModelsPanelState extends State<ModelsPanel> {+ final _search = TextEditingController();+ final _searchFocus = FocusNode(debugLabel: 'Search models');+ _Filter _filter = _Filter.all;+ ModelManagerController get controller => widget.controller;+ ModelsMenuController get subscriptions => widget.subscriptions;+ @override+ void dispose() {+ _search.dispose();+ _searchFocus.dispose();+ super.dispose();+ }++ @override+ Widget build(BuildContext context) => ListenableBuilder(+ listenable: Listenable.merge([controller, subscriptions]),+ builder: (context, _) {+ final query = _search.text.trim().toLowerCase();+ final models = controller.localModels+ .where(+ (m) =>+ (m.name.toLowerCase().contains(query) ||+ m.id.toLowerCase().contains(query)) &&+ switch (_filter) {+ _Filter.all => true,+ _Filter.running => m.running,+ },+ )+ .toList();+ int rank(LocalModel m) => controller.operationFor(m)?.active == true+ ? 0+ : m.running+ ? 1+ : m.downloaded+ ? 2+ : 3;+ models.sort((a, b) {+ final byState = rank(a).compareTo(rank(b));+ return byState != 0+ ? byState+ : controller.localModels+ .indexOf(a)+ .compareTo(controller.localModels.indexOf(b));+ });+ return CallbackShortcuts(+ bindings: {+ const SingleActivator(LogicalKeyboardKey.escape): widget.onClose,+ },+ child: FocusScope(+ child: Material(+ color: AppPalette.panelBg,+ shape: RoundedRectangleBorder(+ borderRadius: BorderRadius.circular(14),+ side: BorderSide(+ color: AppPalette.textPrimary.withValues(alpha: .12),+ ),+ ),+ clipBehavior: Clip.antiAlias,+ child: Column(+ mainAxisSize: MainAxisSize.min,+ children: [+ Padding(+ padding: const EdgeInsets.fromLTRB(20, 10, 12, 8),+ child: Row(+ children: [+ Expanded(child: Text('Models', style: AppType.heading())),+ IconButton(+ onPressed: widget.onClose,+ tooltip: 'Close Models',+ icon: const Icon(LucideIcons.x, size: 16),+ ),+ ],+ ),+ ),+ 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: '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(() {}),+ ),+ ),+ Padding(+ padding: const EdgeInsets.fromLTRB(16, 10, 12, 8),+ child: Align(+ alignment: Alignment.centerLeft,+ child: SingleChildScrollView(+ scrollDirection: Axis.horizontal,+ child: Row(+ children: [+ _tab(+ _Filter.all,+ 'All',+ controller.localModels.length,+ ),+ _tab(+ _Filter.running,+ 'Running',+ controller.localModels+ .where((m) => m.running)+ .length,+ ),+ ],+ ),+ ),+ ),+ ),+ Divider(+ height: 1,+ color: AppPalette.textPrimary.withValues(alpha: .08),+ ),+ Flexible(+ child: SingleChildScrollView(+ padding: const EdgeInsets.symmetric(+ horizontal: 8,+ vertical: 6,+ ),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Padding(+ padding: const EdgeInsets.fromLTRB(12, 10, 12, 4),+ child: Text(+ [+ 'This computer',+ if (controller.memoryBytes case final memory?)+ '${_size(memory)} memory',+ ].join(' · '),+ style: AppType.monoMeta(+ color: AppPalette.textSecondary,+ ),+ ),+ ),+ const SizedBox(height: 4),+ if (controller.error case final error?)+ Padding(+ padding: const EdgeInsets.symmetric(+ horizontal: 12,+ vertical: 12,+ ),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(+ error,+ style: AppType.body(color: AppColors.warning),+ ),+ TextButton(+ onPressed: controller.scanning+ ? null+ : () => unawaited(+ controller.refresh(force: true),+ ),+ child: const Text('Try again'),+ ),+ ],+ ),+ ),+ if (!controller.loaded && controller.error == null)+ Padding(+ padding: const EdgeInsets.symmetric(+ horizontal: 12,+ vertical: 28,+ ),+ child: Text(+ 'Finding models that fit…',+ style: AppType.body(color: AppColors.textSoft),+ ),+ )+ else if (models.isEmpty && controller.error == null)+ Padding(+ padding: const EdgeInsets.symmetric(+ horizontal: 12,+ vertical: 28,+ ),+ child: Text(+ query.isNotEmpty+ ? 'No matching models'+ : switch (_filter) {+ _Filter.running => 'No models running',+ _Filter.all =>+ 'No compatible models found',+ },+ style: AppType.body(color: AppColors.textSoft),+ ),+ ),+ for (final model in models) _model(model),+ if (_filter == _Filter.all &&+ query.isEmpty &&+ subscriptions.rows.isNotEmpty) ...[+ _heading('Subscriptions'),+ for (final row in subscriptions.rows)+ _subscription(row),+ ],+ if (_filter == _Filter.all)+ for (final section in controller.sections.where(+ (s) => !s.own && s.models.isNotEmpty,+ )) ...[+ if (section.models.any(+ (m) => m.id.toLowerCase().contains(query),+ ))+ _heading('Shared · ${section.name}'),+ for (final model in section.models.where(+ (m) => m.id.toLowerCase().contains(query),+ ))+ Padding(+ padding: const EdgeInsets.fromLTRB(+ 12,+ 14,+ 6,+ 14,+ ),+ child: Row(+ children: [+ ModelMark(model: model.id),+ const SizedBox(width: 12),+ Expanded(+ child: Column(+ crossAxisAlignment:+ CrossAxisAlignment.start,+ children: [+ Text(+ model.id,+ style: AppType.label(+ color: AppPalette.textPrimary,+ height: 1.3,+ ),+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ ),+ const SizedBox(height: 6),+ Text(+ model.node,+ style: AppType.monoMeta(+ color: AppPalette.textSecondary,+ height: 1.3,+ ),+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ ),+ ],+ ),+ ),+ ],+ ),+ ),+ ],+ ],+ ),+ ),+ ),+ Divider(+ height: 1,+ color: AppPalette.textPrimary.withValues(alpha: .08),+ ),+ Padding(+ padding: const EdgeInsets.fromLTRB(20, 8, 12, 8),+ child: LayoutBuilder(+ builder: (context, constraints) => Row(+ children: [+ if (constraints.maxWidth >= 440)+ Expanded(+ child: Text(+ 'Select models in a session’s model picker.',+ style: AppType.monoMeta(+ color: AppPalette.textSecondary,+ ),+ ),+ )+ else+ const Spacer(),+ TextButton(+ onPressed: controller.opening+ ? null+ : widget.onManage,+ style: TextButton.styleFrom(+ foregroundColor: AppPalette.textSecondary,+ textStyle: AppType.monoMeta(),+ ),+ child: const Text('Model Manager'),+ ),+ ],+ ),+ ),+ ),+ ],+ ),+ ),+ ),+ );+ },+ );++ Widget _tab(_Filter filter, String title, int count) => Padding(+ padding: const EdgeInsets.only(right: 4),+ child: Semantics(+ selected: _filter == filter,+ child: TextButton(+ onPressed: () => setState(() => _filter = filter),+ style: TextButton.styleFrom(+ backgroundColor: _filter == filter+ ? AppPalette.textPrimary.withValues(alpha: .08)+ : Colors.transparent,+ foregroundColor: _filter == filter+ ? AppPalette.textPrimary+ : AppPalette.textSecondary,+ textStyle: AppType.monoMeta(),+ minimumSize: const Size(0, 30),+ padding: const EdgeInsets.symmetric(horizontal: 10),+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(6)),+ ),+ child: Text('$title $count'),+ ),+ ),+ );++ Widget _model(LocalModel model) {+ final pending = controller.pendingId == model.id;+ final reported = controller.operationFor(model);+ // A previous completed receipt must not label a new pause click "Testing".+ final operation = pending && reported?.active != true ? null : reported;+ final active = operation?.active == true || pending;+ final failed = operation?.failed == true;+ final status = active+ ? [+ operation?.label ??+ (controller.pendingStart ? 'Starting' : 'Stopping'),+ if (operation?.progress case final progress?)+ '${(progress * 100).floor()}%',+ ].join(' · ')+ : failed+ ? operation?.error ?? 'Could not finish. Try again.'+ : [+ if (model.sizeBytes case final size?) _size(size),+ if (model.tokensPerSecond case final speed? when model.running)+ '${speed.toStringAsFixed(1)} tok/s',+ if (model.requests case final requests?+ when model.running && model.windowSeconds != null)+ '${requests.toInt()} ${requests == 1 ? 'request' : 'requests'} / ${_window(model.windowSeconds!)}',+ ].join(' · ');+ final action = model.canStop ? 'Pause' : 'Start';+ final tooltip = active+ ? status+ : model.canStop+ ? 'Pause ${model.name} and free memory. The download is kept.'+ : 'Start ${model.name}';+ return Padding(+ padding: const EdgeInsets.fromLTRB(12, 14, 6, 14),+ child: Row(+ children: [+ ModelMark(model: model.name),+ const SizedBox(width: 12),+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Tooltip(+ message: model.name,+ child: Text(+ model.name,+ style: AppType.label(+ color: AppPalette.textPrimary,+ height: 1.3,+ ),+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ ),+ ),+ const SizedBox(height: 6),+ Text(+ status,+ style: AppType.monoMeta(+ color: failed+ ? AppColors.warning+ : AppPalette.textSecondary,+ height: 1.3,+ ),+ maxLines: failed ? 3 : 2,+ overflow: TextOverflow.ellipsis,+ ),+ if (active)+ Padding(+ padding: const EdgeInsets.only(top: 8, right: 12),+ child: LinearProgressIndicator(+ value: operation?.stage == 'downloading'+ ? operation?.progress+ : null,+ color: AppColors.textSoft,+ backgroundColor: AppColors.border,+ minHeight: 2,+ ),+ ),+ ],+ ),+ ),+ const SizedBox(width: 8),+ Tooltip(+ message: tooltip,+ child: SizedBox(+ width: 40,+ height: 40,+ child: active+ ? Semantics(+ liveRegion: true,+ label: '$status ${model.name}',+ child: Center(+ child: SizedBox(+ width: 15,+ height: 15,+ child: CircularProgressIndicator(+ strokeWidth: 1.5,+ color: AppPalette.textSecondary,+ ),+ ),+ ),+ )+ : IconButton(+ key: ValueKey('model-action-${model.id}'),+ onPressed:+ controller.busy ||+ !controller.inventoryAvailable ||+ (!model.canStart && !model.canStop)+ ? null+ : () => unawaited(controller.toggle(model)),+ icon: Icon(+ model.canStop ? LucideIcons.pause : LucideIcons.play,+ size: 17,+ semanticLabel: '$action ${model.name}',+ ),+ style: IconButton.styleFrom(+ foregroundColor: AppPalette.textPrimary,+ disabledForegroundColor: AppPalette.textFaint+ .withValues(alpha: .4),+ ),+ ),+ ),+ ),+ ],+ ),+ );+ }++ String _size(double bytes) {+ final gb = bytes / (1024 * 1024 * 1024);+ return '${gb.toStringAsFixed(gb == gb.roundToDouble() ? 0 : 1)} GB';+ }++ String _window(double seconds) => seconds > 0 && seconds % 3600 == 0+ ? '${(seconds / 3600).toInt()}h'+ : seconds > 0 && seconds % 60 == 0+ ? '${(seconds / 60).toInt()}m'+ : '${seconds.toInt()}s';+ Widget _heading(String title) => Padding(+ padding: const EdgeInsets.fromLTRB(12, 20, 12, 6),+ child: Text(+ title,+ style: AppType.monoMeta(color: AppPalette.textSecondary),+ ),+ );++ Widget _subscription(Map<String, Object?> row) {+ final account =+ subscriptions.rows.where((r) => r['title'] == row['title']).length > 1+ ? row['account'] as String? ?? ''+ : '';+ final percent = row['remainingPercent'] as double?;+ return Padding(+ padding: const EdgeInsets.fromLTRB(12, 14, 12, 14),+ child: Row(+ children: [+ ModelMark(model: row['title'] as String?),+ const SizedBox(width: 12),+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(+ '${row['title'] ?? ''}',+ style: AppType.label(+ color: AppPalette.textPrimary,+ height: 1.3,+ ),+ ),+ if (account.isNotEmpty) ...[+ const SizedBox(height: 6),+ Text(+ 'Account ···$account',+ style: AppType.monoMeta(+ color: AppPalette.textSecondary,+ height: 1.3,+ ),+ ),+ ],+ ],+ ),+ ),+ const SizedBox(width: 12),+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.end,+ children: [+ Text(+ '${row['status'] ?? ''}'.replaceAll('remaining', 'left'),+ textAlign: TextAlign.right,+ style: AppType.monoMeta(+ color: percent == 0+ ? AppColors.warning+ : AppPalette.textSecondary,+ ),+ ),+ if (percent != null) ...[+ const SizedBox(height: 6),+ SizedBox(+ width: 80,+ child: LinearProgressIndicator(+ value: percent / 100,+ minHeight: 3,+ color: AppColors.textSoft,+ backgroundColor: AppColors.border,+ ),+ ),+ ],+ ],+ ),+ ),+ ],+ ),+ );+ }+}++/// Discovery appears once. Completion explains where model selection lives;+/// the overview never creates a session or changes its model implicitly.+class LocalModelInvitation extends StatelessWidget {+ const LocalModelInvitation({+ super.key,+ required this.controller,+ required this.onOpen,+ });+ final ModelManagerController controller;+ final VoidCallback onOpen;+ @override+ Widget build(BuildContext context) => ListenableBuilder(+ listenable: controller,+ builder: (context, _) {+ final ready = controller.readyModel;+ if (ready == null && !controller.showIntroduction) {+ return const SizedBox.shrink();+ }+ return Align(+ alignment: Alignment.bottomRight,+ child: Padding(+ padding: const EdgeInsets.all(18),+ child: ConstrainedBox(+ constraints: const BoxConstraints(maxWidth: 400),+ child: Material(+ elevation: 8,+ color: AppColors.surface,+ shape: RoundedRectangleBorder(+ borderRadius: BorderRadius.circular(12),+ side: BorderSide(color: AppColors.borderStrong),+ ),+ child: Padding(+ padding: const EdgeInsets.fromLTRB(16, 10, 8, 10),+ child: Row(+ children: [+ if (ready == null)+ const ModelMark()+ else+ Icon(+ LucideIcons.circleCheckBig,+ color: AppColors.success,+ size: 22,+ ),+ const SizedBox(width: 12),+ Expanded(+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(+ ready == null+ ? 'Run AI on this computer'+ : '${ready.name} is running',+ style: AppType.label(color: AppColors.text),+ ),+ if (ready == null)+ TextButton(+ onPressed: onOpen,+ style: TextButton.styleFrom(+ padding: EdgeInsets.zero,+ alignment: Alignment.centerLeft,+ ),+ child: const Text('Explore models'),+ )+ else+ Padding(+ padding: const EdgeInsets.only(top: 5),+ child: Text(+ 'Select it from the model picker in a session.',+ style: AppType.body(color: AppColors.textSoft),+ ),+ ),+ ],+ ),+ ),+ IconButton(+ tooltip: 'Dismiss',+ onPressed: () => ready == null+ ? unawaited(controller.dismissIntroduction())+ : controller.dismissReady(),+ icon: const Icon(Icons.close, size: 17),+ ),+ ],+ ),+ ),+ ),+ ),+ ),+ );+ },+ );+}diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dartindex 17ba52140..c510cfdd6 100644--- a/desktop/lib/screens/swarm_screen.dart+++ b/desktop/lib/screens/swarm_screen.dart@@ -14,6 +14,8 @@ import '../core/harness_file_store.dart';import '../core/project_folder.dart';import '../core/test_run.dart';import '../logging/debug_surface.dart';+import '../models/models_panel.dart';+import '../models/model_mark.dart';import '../settings/settings_screen.dart';import '../settings/settings_section.dart';import '../shared/theme/app_theme.dart' as grid;@@ -138,10 +140,13 @@ class _SwarmScreenState extends State<SwarmScreen>widget.projectStore ??SwarmProjectStore(storage: kUnderTest ? null : HarnessFileStore.shared);StreamSubscription<SpokenTaskRequest>? _spokenTasks;+ StreamSubscription<void>? _modelsRequests;final _shellFocus = FocusNode(debugLabel: 'Swarm shell');final _sessionsButton = GlobalKey();OverlayEntry? _sessionsOverlay;VoidCallback? _unregisterSessions;+ OverlayEntry? _modelsOverlay;+ VoidCallback? _unregisterModels;late final _minimize = PaneMinimizeController(vsync: this);bool _closingPane = false;OverlayEntry? _minimizeOverlay;@@ -247,10 +252,18 @@ class _SwarmScreenState extends State<SwarmScreen>unawaited(_projects.load());unawaited(_navigation.load());_spokenTasks = app.spokenTasks.listen(_openSpokenTask);+ _modelsMenu =+ widget.modelsMenu ?? ModelsMenuController(remote: app.readRemoteUsage);+ app.modelManager.addListener(_modelManagerChanged);+ _modelsRequests = app.modelsRequests.listen((_) {+ if (mounted && _modelsOverlay == null) _toggleModels();+ });+ if (!kUnderTest) {+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (mounted) app.modelManager.start();+ });+ }if (_native) {- _modelsMenu =- widget.modelsMenu ??- ModelsMenuController(remote: app.readRemoteUsage);_modelsMenu!.addListener(_syncModels);// Same trigger as the subscription rows: the daemon memoises its answer, so opening the menu// repeatedly costs nothing after the first.@@ -276,12 +289,16 @@ class _SwarmScreenState extends State<SwarmScreen>if (_routeIsCurrent == current) return;_routeIsCurrent = current;if (!current &&- (_search != null || _commandBarOpen || _sessionsOverlay != null)) {+ (_search != null ||+ _commandBarOpen ||+ _sessionsOverlay != null ||+ _modelsOverlay != null)) {WidgetsBinding.instance.addPostFrameCallback((_) {if (mounted && !_routeIsCurrent) {_closeSearch(restoreFocus: false);_closeCommandBar(restoreFocus: false);_closeSessions(restoreFocus: false);+ _closeModels(restoreFocus: false);}});}@@ -290,6 +307,12 @@ class _SwarmScreenState extends State<SwarmScreen>@overridevoid dispose() {+ app.modelManager.removeListener(_modelManagerChanged);+ app.modelManager.setPanelVisible(false);+ _modelsRequests?.cancel();+ _unregisterModels?.call();+ _modelsOverlay?.remove();+ _modelsOverlay?.dispose();_unregisterSessions?.call();_sessionsOverlay?.remove();_sessionsOverlay?.dispose();@@ -323,9 +346,9 @@ class _SwarmScreenState extends State<SwarmScreen>_commandFocus.dispose();if (_hasCommandBar) _commandBar.dispose();unawaited(_spokenTasks?.cancel());+ _modelsMenu?.removeListener(_syncModels);+ if (widget.modelsMenu == null) _modelsMenu?.dispose();if (_native) {- _modelsMenu?.removeListener(_syncModels);- if (widget.modelsMenu == null) _modelsMenu?.dispose();unawaited(_channel.invokeMethod<void>('modelsState', {'subscriptions': []}),);@@ -386,6 +409,7 @@ class _SwarmScreenState extends State<SwarmScreen>void _runShortcut(String id) {if (_sessionsOverlay != null) _closeSessions();+ if (_modelsOverlay != null) _closeModels();if (id != 'navigation.command_bar') _closeCommandBar();if (id == 'agent.new' && _search != null) {final target = _search!.targetId;@@ -625,6 +649,8 @@ class _SwarmScreenState extends State<SwarmScreen>// key it does not know.'unread': _unread,'sessionsOpen': _sessionsOverlay != null,+ 'modelsOpen': _modelsOverlay != null,+ 'localModelReady': app.modelManager.readyModel != null,'runningSessions': harnessSessions(app).where((row) => row.running).length,@@ -908,6 +934,11 @@ class _SwarmScreenState extends State<SwarmScreen>await WidgetsBinding.instance.endOfFrame;return;}+ if (call.method == 'models') {+ _toggleModels();+ await WidgetsBinding.instance.endOfFrame;+ return;+ }if (call.method == 'modelsOpened') {await _modelsMenu?.refresh();return;@@ -1027,20 +1058,7 @@ class _SwarmScreenState extends State<SwarmScreen>case 'restartAgent':unawaited(_restartAgent());case 'runLocalModel':- // Native commands arrive above the Actions subtree. Use the same- // product entry directly; a dialog guard would block the dock.- Future<void> open() => app.runLocalModel(- context,- machineId: args['machineId'] is String- ? args['machineId'] as String- : null,- onOpenHarness: newHarnessOpensInBox ? _openProduct : null,- );- if (newHarnessOpensInBox) {- await open();- } else {- await _dialog(open);- }+ _toggleModels();case 'splitRight':unawaited(_splitAgent(PaneResizeAxis.x));case 'splitDown':@@ -1984,6 +2002,112 @@ class _SwarmScreenState extends State<SwarmScreen>app.openStore();}+ void _modelManagerChanged() {+ if (_native && mounted) _syncNative();+ }++ Future<void> _openModelManager() async {+ final openingPanel = _modelsOverlay;+ if (openingPanel == null) dismissTransientMenus();+ await app.modelManager.open();+ if (app.modelManager.error == null &&+ identical(_modelsOverlay, openingPanel)) {+ _closeModels(restoreFocus: false);+ }+ if (app.modelManager.error case final error? when mounted) {+ if (_modelsOverlay == null) {+ ScaffoldMessenger.of(context)+ .showSnackBar(SnackBar(content: Text(error)));+ }+ }+ }++ void _toggleModels() {+ if (_modelsOverlay != null) {+ _closeModels();+ return;+ }+ if (_newHarness?.requestDismiss() == false) return;+ _closeNewHarness(restoreFocus: false);+ _closeSearch(restoreFocus: false);+ _closeCommandBar(restoreFocus: false);+ dismissTransientMenus();+ _preparePaneFocus();+ app.modelManager.setPanelVisible(true);+ unawaited(app.modelManager.dismissIntroduction());+ unawaited(app.modelManager.refresh());+ unawaited(_modelsMenu!.refresh());+ _modelsOverlay = OverlayEntry(+ builder: (context) => LayoutBuilder(+ builder: (context, constraints) => Stack(+ children: [+ Positioned.fill(+ child: GestureDetector(+ behavior: HitTestBehavior.opaque,+ onTap: _closeModels,+ child: const SizedBox.expand(),+ ),+ ),+ Positioned(+ top: (_native ? 0.0 : _tabBarHeight) + 8,+ right: 10,+ width: (constraints.maxWidth - 20).clamp(0, 640),+ child: ConstrainedBox(+ constraints: BoxConstraints(+ maxHeight:+ (constraints.maxHeight -+ (_native ? 0 : _tabBarHeight) -+ 20)+ .clamp(0, 620),+ ),+ child: DecoratedBox(+ decoration: BoxDecoration(+ borderRadius: BorderRadius.circular(14),+ boxShadow: [+ BoxShadow(+ color: Colors.black.withValues(alpha: .35),+ blurRadius: 36,+ offset: const Offset(0, 12),+ ),+ ],+ ),+ child: ModelsPanel(+ controller: app.modelManager,+ subscriptions: _modelsMenu!,+ onClose: _closeModels,+ onManage: () => unawaited(_openModelManager()),+ ),+ ),+ ),+ ),+ ],+ ),+ ),+ );+ Overlay.of(context).insert(_modelsOverlay!);+ _unregisterModels = registerTransientMenu(_closeModels);+ if (_native) _syncNative();+ setState(() {});+ }++ void _closeModels({bool restoreFocus = true}) {+ if (_modelsOverlay == null) return;+ _unregisterModels?.call();+ _unregisterModels = null;+ _modelsOverlay?.remove();+ _modelsOverlay?.dispose();+ _modelsOverlay = null;+ app.modelManager.setPanelVisible(false);+ if (!mounted) return;+ if (_native) _syncNative();+ setState(() {});+ if (restoreFocus) {+ _shellFocus.requestFocus();+ final pane = app.focusedPane;+ if (pane != null) app.focusPane(pane.id, reveal: true);+ }+ }+void _toggleSessions({SessionFilter? filter}) {if (_sessionsOverlay != null) {_closeSessions(restoreFocus: filter == null);@@ -3265,6 +3389,11 @@ class _SwarmScreenState extends State<SwarmScreen>// Last in the stack, so a banner is never painted// under a pane, a tab or the palette. It takes// pointers only on the banners themselves.+ if (!_commandBarOpen && _newHarness == null)+ LocalModelInvitation(+ controller: app.modelManager,+ onOpen: _toggleModels,+ ),AgentAlertBanners(notifier: app),],),@@ -3332,6 +3461,8 @@ class _SwarmScreenState extends State<SwarmScreen>Widget _tabStrip() => LayoutBuilder(builder: (context, constraints) {+ final compactTools =+ constraints.maxWidth < 650 * grid.appTextScaleOf(context);return Container(height: _tabBarHeight,color: grid.AppPalette.swarmTabBar,@@ -3518,6 +3649,14 @@ class _SwarmScreenState extends State<SwarmScreen>),),const SizedBox(width: 6),+ IconButton(+ key: const ValueKey('swarm-models-button'),+ tooltip: 'AI Models',+ onPressed: _toggleModels,+ isSelected: _modelsOverlay != null,+ icon: const ModelMark(size: 20, semanticLabel: 'AI Models'),+ ),+ const SizedBox(width: 6),Tooltip(message: 'Harness Store ${_keymap.hint('app.store') ?? ''}'.trim(),@@ -3544,7 +3683,9 @@ class _SwarmScreenState extends State<SwarmScreen>),),icon: const StoreMark(),- label: const Text('Harness Store'),+ label: compactTools+ ? const SizedBox.shrink()+ : const Text('Harness Store'),),),const SizedBox(width: 6),diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex a51810129..1db0af616 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -12,6 +12,7 @@ import 'package:flutter/widgets.dart'import 'package:flutter_riverpod/flutter_riverpod.dart';import '../analytics/analytics.dart';+import '../models/model_manager_controller.dart';import '../api/api_client.dart';import '../viewer/sign_in_browser.dart';import '../viewer/viewer_services.dart';@@ -177,6 +178,7 @@ class AgentForkAttempt {/// One deliberate creation, retained by the form if its reply is lost. Reusing/// it checks the original request; opening New agent starts a fresh intent.class AgentCreationAttempt {+ AgentCreationAttempt({this.background = false});String _id = _newCreationId();String? _machineId, _targetId;Map<String, dynamic>? _choices;@@ -184,6 +186,11 @@ class AgentCreationAttempt {HarnessPlacement? _placement;Future<String?>? _inFlight;bool _awaitingConfirmation = false, _finished = false;++ /// Prepare a session without adding a pane or changing the selected tab.+ final bool background;+ String? _agentId;+ String? get agentId => _agentId;String? _outcome;String? _preparedFolder;ProjectFolderRequest? _projectFolder;@@ -427,6 +434,7 @@ class _AgentStop {class AppNotifier extends ChangeNotifier {final AuthSession session;+/// The noise this window makes when an agent finishes or gets stuck.final AlertSounds alerts;@@ -489,6 +497,9 @@ class AppNotifier extends ChangeNotifier {/// Words from the dial, for whoever can put a palette on screen.Stream<SpokenTaskRequest> get spokenTasks => _spokenTasks.stream;+ final StreamController<void> _modelsRequests =+ StreamController<void>.broadcast();+ Stream<void> get modelsRequests => _modelsRequests.stream;final LocalManualFixture? localManualFixture;final Duration turnActivityTimeout;final LocalCliDiscovery? localCliDiscovery;@@ -3086,7 +3097,9 @@ class AppNotifier extends ChangeNotifier {stillSignedIn: () async => (await cliLogin.checkStatus()).loggedIn,// Only the first time: the supervisor asks once per spawn attempt, and a guest window is// already a guest — repeating it would put the banner back on every retry.- onSignedOut: () { if (signedIn) _signedOutAtRuntime(_signedOutMessage); },+ onSignedOut: () {+ if (signedIn) _signedOutAtRuntime(_signedOutMessage);+ },onSnapshot: _updateLocalProjectSnapshot,onBackendOnline: _noteBackendOnline,onReady: (endpoint) {@@ -5013,68 +5026,43 @@ class AppNotifier extends ChangeNotifier {}}- /// The Store harness every "Open Grid" door opens: Grid, the agent that- /// manages the models on a machine or a fleet, with its live viewer.+ /// Model Manager keeps the original package ID for installed workspaces.static const gridHarness = 'autonomous/autonomous-grid';+ ModelManagerController? _modelManager;+ ModelManagerController get modelManager =>+ _modelManager ??= ModelManagerController(this);- /// The one action behind every "Open Grid" entry — the pane picker's button- /// and the Models menu — and it is exactly what the Store's Open button- /// does: a draft tab of its own, then New Agent with Grid already chosen on- /// [machineId]. Not a dialog of this feature's own: a second way to open a- /// harness would be a second definition of what opening one means.- ///- /// Grid not installed on that machine → the Store, open on Grid's page,- /// whose Install is the way in. Nothing here reports progress: the tab- /// appearing is the confirmation.- ///- /// Takes the caller's [context] because New Agent needs one and this- /// notifier holds none — the same shape as every other dialog a door opens.- ///- /// [machineId] is the computer Grid opens on — the pane's own machine from a- /// pane's picker, the one chosen from the Models menu's list. Absent (a menu- /// with one machine, or none named), it is this computer's own when the app- /// has one, else whatever the person is looking at. Never guessed past a- /// named machine: a picker on a remote pane that opened on this computer was- /// the bug this argument exists to end.+ Future<Map<String, dynamic>> localModels(+ String machineId, {+ bool refresh = false,+ }) => _conn(machineId).request(+ 'grid_fleet_models_list',+ payload: {'refresh': refresh},+ timeout: const Duration(seconds: 90),+ );++ Future<Map<String, dynamic>> controlLocalModel(+ String machineId,+ String modelId, {+ required bool start,+ }) => _conn(machineId).request(+ start ? 'grid_fleet_model_start' : 'grid_fleet_model_stop',+ payload: {'modelId': modelId},+ timeout: const Duration(seconds: 12),+ );++ /// The session picker opens the same local Models overview as the toolbar.Future<void> runLocalModel(BuildContext context, {String? machineId,Future<void> Function(String harnessId, String machineId)? onOpenHarness,}) async {- final machine = machineId != null- ? machineStates[machineId]- : _localModelMachine();- if (machine == null) {- _lastError = machineId != null- ? 'That machine is no longer linked.'- : 'Connect a machine before opening Grid.';- _lastErrorRetryable = false;- notifyListeners();- return;- }- machineId = machine.machine.machineId;- // Whether Grid is installed THERE, from the machine's own list — a stored- // answer is fine here, since an install this app started is pushed into- // it as it lands.- await probeDsh(machineId);- if (machine.dsh[gridHarness]?.installed != true) {- openStore(harness: gridHarness);- return;- }- if (!context.mounted) return;- if (onOpenHarness != null) {- await onOpenHarness(gridHarness, machineId);- return;- }- await openStoreAgent(context, this, gridHarness, machineId);+ _modelsRequests.add(null);}- /// The Store harness the Machines menu opens: Machine Monitor, the fleet- /// itself, managed by talking to it, with the live map of every machine- /// beside the terminal.static const machinesHarness = 'autonomous/machine-monitor';- /// Open Machine Monitor, the same way [runLocalModel] opens Grid.+ /// Open Machine Monitor on this computer.////// It belongs on THIS computer and nowhere else: everything it reads — the/// machine list, each machine's roster — it reads through the local daemon,@@ -6544,11 +6532,19 @@ class AppNotifier extends ChangeNotifier {}/// PR lookup runs on the agent's machine using that machine's GitHub access.- Future<Map<String, dynamic>> readAgentPullRequest(String machineId, String agentId) async {+ Future<Map<String, dynamic>> readAgentPullRequest(+ String machineId,+ String agentId,+ ) async {try {- return await _conn(machineId).request('git_pull_request',- payload: {'agentId': agentId}, timeout: const Duration(seconds: 30));- } catch (_) { return {'status': 'unavailable'}; }+ return await _conn(machineId).request(+ 'git_pull_request',+ payload: {'agentId': agentId},+ timeout: const Duration(seconds: 30),+ );+ } catch (_) {+ return {'status': 'unavailable'};+ }}/// Reads source material only on the machine that owns the selected path.@@ -6695,7 +6691,8 @@ class AppNotifier extends ChangeNotifier {// start page the user is already on IS that tab. A split was asked for// by name and wins; so does a tab other than the current one. The// current tab is what the dialog passes when nothing was chosen.- if (dsh != null &&+ if (!creation.background &&+ dsh != null &&placement == null &&split == null &&(swarmId == null || swarmId == activeSwarmId)) {@@ -6820,11 +6817,9 @@ class AppNotifier extends ChangeNotifier {// A status check must remain possible even if the destination closed or a// capability probe changed while the first create was already in flight.if (!creation.awaitingConfirmation) {- final placementError = _creationPlacementError(- targetId,- split,- placement: placement,- );+ final placementError = creation.background+ ? null+ : _creationPlacementError(targetId, split, placement: placement);if (placementError != null) return placementError;if (choices['codexHome'] != null) {if (choices['engine'] != 'codex') {@@ -6880,11 +6875,9 @@ class AppNotifier extends ChangeNotifier {}// Preparation may be slow. Revalidate before starting a process, using// the original machine and split rather than the current selection.- final placementError = _creationPlacementError(- targetId,- split,- placement: placement,- );+ final placementError = creation.background+ ? null+ : _creationPlacementError(targetId, split, placement: placement);if (placementError != null) return creation._complete(placementError);if (_disposed ||machineStates[machineId] != machine ||@@ -7045,6 +7038,7 @@ class AppNotifier extends ChangeNotifier {}creation._complete(null);if (_disposed || machineStates[machineId] != machine) return null;+ creation._agentId = agent.id;_upsertAgent(machine, agent);// Apply each creation receipt once, even if its transport result is replayed.// A Git start remembers its repository, never the worktree it made.@@ -7058,6 +7052,7 @@ class AppNotifier extends ChangeNotifier {}harnessStats.onAgentSpawned();notifyListeners();+ if (creation.background) return null;if (_creationPlacementError(targetId, split, placement: placement) !=null) {_lastError =@@ -10674,6 +10669,7 @@ class AppNotifier extends ChangeNotifier {@overridevoid dispose() {+ _modelManager?.dispose();for (final project in _orchestratorProjects.values) {project.dispose();}@@ -10705,6 +10701,7 @@ class AppNotifier extends ChangeNotifier {swarm.panes.clear();}unawaited(_spokenTasks.close());+ unawaited(_modelsRequests.close());super.dispose();}}diff --git a/desktop/lib/store/store_editorial.dart b/desktop/lib/store/store_editorial.dartindex 798d7d35a..82c92267c 100644--- a/desktop/lib/store/store_editorial.dart+++ b/desktop/lib/store/store_editorial.dart@@ -67,9 +67,9 @@ const storeStories = <String, StoreStory>{'autonomous/autonomous-grid': StoreStory(benefit: 'Your machines. Your models. One conversation.',headline: 'Meet your\npersonal AI fleet.',- description: 'Deploy open-weight models by talking to Grid.\nWatch your machines, models, and performance live.',+ description: 'Deploy open-weight models by talking to Model Manager.\nWatch your machines, models, and performance live.',asset: 'assets/store/grid-fleet.png',- caption: 'Grid Viewer · Illustrative telemetry',+ caption: 'Model Manager · Illustrative telemetry',prompts: ['Discover my machines and deploy an open-weight model that fits.','Find the best placement for a coding model and a fast chat model across my fleet.',diff --git a/desktop/lib/widgets/engine_identity.dart b/desktop/lib/widgets/engine_identity.dartindex 96fd5ee82..852b2ef66 100644--- a/desktop/lib/widgets/engine_identity.dart+++ b/desktop/lib/widgets/engine_identity.dart@@ -420,7 +420,7 @@ const _harnesses = <String, EngineIdentity>{// branding/app_icon.svg); ours, like Circuit's and Workshop's.'autonomous/autonomous-grid': EngineIdentity(id: 'autonomous/autonomous-grid',- label: 'Grid',+ label: 'Model Manager',category: 'Local AI',tagline: 'Deploy open-weight models across your machines and watch the fleet live',creator: 'Autonomous',diff --git a/desktop/lib/widgets/grid_model_picker.dart b/desktop/lib/widgets/grid_model_picker.dartindex 4c75e60d3..07f752b5b 100644--- a/desktop/lib/widgets/grid_model_picker.dart+++ b/desktop/lib/widgets/grid_model_picker.dart@@ -57,11 +57,7 @@ class GridModelPicker extends StatefulWidget {/// have to know a command for.final VoidCallback? onUseOwnLogin;- /// Called when the Local section's action — "Open Grid" — is chosen. An action, not a- /// destination: it opens the Grid harness, the agent that puts models on the user's machines,- /// which is the answer to the empty section this menu otherwise stops at. Always offered,- /// whether or not anything is being served yet: a person with no Local models is exactly who- /// needs the door.+ /// Opens the local Models overview to discover and start compatible models.final VoidCallback? onRunLocalModel;/// The grid model this agent is on right now, or null when it is on its own login. Drives the@@ -343,13 +339,13 @@ class _GridModelPickerState extends State<GridModelPicker> {// The machine's gap before the account's: with no `grid` on this computer there is nothing a// sign-in could set up here, and the feature's name is the only word for it a person knows.if (answer.gridCli == GridCli.missing) {- return "Harness Compute isn't installed on this machine.";+ return 'Model Manager can finish setting up this computer.';}// The account's rest are the models on the user's own machines; an empty list there needs a// sentence under the heading. Shared grids are never drawn empty (see _sectionsToDraw), so// this branch only ever fires for the own grid.if (section.own) {- return 'No local models on this account yet.';+ return 'Set up your first local model on this computer.';}return null;}@@ -424,6 +420,23 @@ class _GridModelPickerState extends State<GridModelPicker> {return false;}}+ if (a.grids.length != b.grids.length) return false;+ for (var i = 0; i < a.grids.length; i += 1) {+ final left = a.grids[i];+ final right = b.grids[i];+ if (left.name != right.name ||+ left.own != right.own ||+ left.models.length != right.models.length) {+ return false;+ }+ for (var j = 0; j < left.models.length; j += 1) {+ if (left.models[j].id != right.models[j].id ||+ left.models[j].node != right.models[j].node ||+ left.models[j].grid != right.models[j].grid) {+ return false;+ }+ }+ }return true;}@@ -431,34 +444,21 @@ class _GridModelPickerState extends State<GridModelPicker> {Widget build(BuildContext context) {TerminalFontScope.watch(context);final sentence = _webSearchSentence;- if (widget.compact) {- return IconButton(- tooltip: sentence == null- ? 'Where this agent runs'- : 'Where this agent runs\n$sentence',- onPressed: _open,- icon: _loading- ? const SizedBox(- width: 14,- height: 14,- child: CircularProgressIndicator(strokeWidth: 1.5),- )- : const Icon(Icons.tune, size: 16),- style: IconButton.styleFrom(- foregroundColor: AppColors.mutedStrong,- fixedSize: const Size(28, 28),- minimumSize: const Size(28, 28),- padding: EdgeInsets.zero,- tapTargetSize: MaterialTapTargetSize.shrinkWrap,- ),- );- }+ final current =+ widget.currentModel ??+ switch (widget.engineLabel?.toLowerCase()) {+ 'codex' => 'OpenAI',+ 'claude' => 'Anthropic',+ 'opencode' => 'OpenCode',+ _ => 'Model',+ };+ final label = _expecting ? 'Switching…' : current;return Tooltip(// The same sentence the menu shows, one line under the control's own — so a person can learn// the agent has no web search without opening the menu at all.message: sentence == null- ? 'Where this agent runs'- : 'Where this agent runs\n$sentence',+ ? 'Model: $current · Click to switch'+ : 'Model: $current · Click to switch\n$sentence',waitDuration: const Duration(milliseconds: 700),child: MouseRegion(// Stated rather than inherited. The pane header sits over a terminal, and the cursor a@@ -477,33 +477,41 @@ class _GridModelPickerState extends State<GridModelPicker> {mouseCursor: SystemMouseCursors.click,borderRadius: BorderRadius.circular(4),child: Padding(- padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 3),+ padding: EdgeInsets.symmetric(+ horizontal: widget.compact ? 3 : 6,+ vertical: 3,+ ),child: Row(mainAxisSize: MainAxisSize.min,children: [- // No leading glyph: the word carries the control, and a header this dense reads- // better with one fewer mark in it. The spinner takes that space only while a read- // is in flight, so the label does not shift when nothing is happening.- if (_loading) ...[- const SizedBox(- width: 11,- height: 11,- child: CircularProgressIndicator(strokeWidth: 1.5),+ ConstrainedBox(+ constraints: BoxConstraints(+ maxWidth: widget.compact ? 44 : 140,),- const SizedBox(width: 5),- ],- Text(- 'Model',- style: AppType.monoLabel(- fontWeight: FontWeight.w400,- color: AppColors.textSoft,+ child: Text(+ label,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: AppType.monoLabel(+ fontWeight: FontWeight.w400,+ color: AppColors.textSoft,+ ),),),- Icon(- Icons.arrow_drop_down,- size: 14,- color: AppColors.mutedStrong,- ),+ // Replace the arrow while loading so a read cannot squeeze+ // the session name or move the pane's other controls.+ if (_loading)+ const SizedBox(+ width: 14,+ height: 14,+ child: CircularProgressIndicator(strokeWidth: 1.5),+ )+ else+ Icon(+ Icons.arrow_drop_down,+ size: 14,+ color: AppColors.mutedStrong,+ ),],),),@@ -670,7 +678,7 @@ class _ModelPickerPanelState extends State<_ModelPickerPanel> {),ModelPickerFooter(summary: total == 1 ? '1 model available' : '$total models available',- actionLabel: 'Manage in Grid',+ actionLabel: 'Local models',onAction: () => widget.close(const _Choice.runLocalModel()),),],@@ -691,8 +699,9 @@ class _ModelPickerPanelState extends State<_ModelPickerPanel> {subtitle: account.isEmpty ? '' : 'key ···$account',selected: widget.currentModel == null,avatar: ModelAvatar(- label: widget.engineLabel ?? '',- child: EngineMark(engine: widget.engineLabel, size: 17),+ label:+ (widget.subscription?['title'] as String?) ??+ engineIdentity(widget.engineLabel).label,),// Absent rather than "unknown": a row that cannot say how much is left says nothing, which// reads as "no figure" instead of as a figure that happens to be missing.@@ -712,9 +721,8 @@ class _ModelPickerPanelState extends State<_ModelPickerPanel> {const SizedBox(height: 2),Text(low ? 'Running low' : 'Healthy',- style: AppType.body(- color: AppColors.muted,- ).copyWith(fontSize: 11),+ style: AppType.body(color: AppColors.muted)+ .copyWith(fontSize: 11),),],],diff --git a/desktop/lib/widgets/model_picker_chrome.dart b/desktop/lib/widgets/model_picker_chrome.dartindex 910cce193..67b33e5a1 100644--- a/desktop/lib/widgets/model_picker_chrome.dart+++ b/desktop/lib/widgets/model_picker_chrome.dart@@ -13,6 +13,7 @@ library;import 'package:flutter/material.dart';import 'package:flutter/services.dart';+import '../models/model_mark.dart';import '../shared/theme/app_type.dart';import '../theme/app_theme.dart';@@ -23,70 +24,24 @@ const double kModelPickerWidth = 376;/// The avatar's side, and the gutter its column occupies on every row.const double kModelAvatarSize = 34;-/// One tile per model, lettered and tinted.-///-/// The tint is DERIVED from the id rather than assigned, so the same model wears the same colour-/// in every section and on every machine — the point of a coloured tile is that it is recognisable-/// before it is read, which an arbitrary per-list colour would defeat.+/// The same model artwork used in Models, with a brain fallback for unknown names.class ModelAvatar extends StatelessWidget {const ModelAvatar({super.key, required this.label, this.child});- /// What the tile is lettered with. The first letter or digit of the model's id.final String label;-- /// Drawn instead of the letter — a subscription's own logo.final Widget? child;- /// The tints, in the order [_tintFor] walks them. Low-alpha so they read as a surface rather- /// than as a badge, with the letter carrying the saturated version of the same hue.- static const _tints = <(Color, Color)>[- (Color(0xFF6D5BD0), Color(0xFFC3B9F5)), // violet- (Color(0xFF2F5BEA), Color(0xFFAFC4FA)), // blue- (Color(0xFF1F8A5B), Color(0xFFA9E2C7)), // green- (Color(0xFFC77A16), Color(0xFFF2D19B)), // amber- (Color(0xFFB84A6A), Color(0xFFF1B3C4)), // rose- (Color(0xFF1B8A99), Color(0xFFA6DFE6)), // teal- ];-- static (Color, Color) _tintFor(String seed) {- if (seed.isEmpty) return _tints.first;- var hash = 0;- for (final unit in seed.codeUnits) {- hash = (hash * 31 + unit) & 0x7FFFFFFF;- }- return _tints[hash % _tints.length];- }-- /// The one character a model is lettered with: its first letter or digit, so `Qwen/Qwen3.8` and- /// `qwen3.8` letter the same and a leading slash or dash letters as nothing.- static String initialOf(String id) {- for (final rune in id.runes) {- final ch = String.fromCharCode(rune);- if (RegExp(r'[A-Za-z0-9]').hasMatch(ch)) return ch.toUpperCase();- }- return '?';- }-@override- Widget build(BuildContext context) {- final (fill, ink) = _tintFor(label);- return Container(- width: kModelAvatarSize,- height: kModelAvatarSize,- alignment: Alignment.center,- decoration: BoxDecoration(- color: child != null ? AppColors.surface : fill.withValues(alpha: 0.30),- borderRadius: BorderRadius.circular(9),- ),- child:- child ??- Text(- initialOf(label),- style: AppType.body(color: ink)- .copyWith(fontWeight: FontWeight.w600, fontSize: 13),- ),- );- }+ Widget build(BuildContext context) => Container(+ width: kModelAvatarSize,+ height: kModelAvatarSize,+ alignment: Alignment.center,+ decoration: BoxDecoration(+ color: AppColors.surface,+ borderRadius: BorderRadius.circular(9),+ ),+ child: child ?? ModelMark(model: label),+ );}/// The field that narrows the list. Its own widget so the panel can keep the query and rebuilddiff --git a/desktop/lib/widgets/pane_header_actions.dart b/desktop/lib/widgets/pane_header_actions.dartindex a2c673381..a78c3442c 100644--- a/desktop/lib/widgets/pane_header_actions.dart+++ b/desktop/lib/widgets/pane_header_actions.dart@@ -61,12 +61,7 @@ class PaneHeaderActions extends StatelessWidget {/// Supplemental branch context, hidden with details when controls appear.final Widget? trailing;- /// Where this agent runs, shown with the controls rather than beside the name.- ///- /// It belongs here for the same reason the icons do: a header this narrow has room for the agent's- /// NAME or for what you can do to it, not both, and what you can do to it is worth reading only- /// when you are reaching for it. Parked on the left of the cluster, so the four icons a person- /// aims at by muscle memory keep the right edge they have always had.+ /// The current model stays visible beside the pane's contextual controls.final Widget? modelPicker;@override@@ -119,10 +114,6 @@ class PaneHeaderActions extends StatelessWidget {action('Share harness', Icons.person_add_alt_1_outlined, onShare),const SizedBox(width: 2),],- if (modelPicker != null) ...[- modelPicker!,- const SizedBox(width: 4),- ],if (compact)_CompactPaneActions(items: [@@ -201,33 +192,43 @@ class PaneHeaderActions extends StatelessWidget {),),);- if (details == null) return controls;- return Stack(- alignment: Alignment.centerRight,+ final actionArea = details == null+ ? controls+ : Stack(+ alignment: Alignment.centerRight,+ children: [+ IgnorePointer(+ ignoring: visible,+ child: AnimatedOpacity(+ key: const ValueKey('pane-header-details'),+ opacity: visible ? 0 : 1,+ duration: MediaQuery.disableAnimationsOf(context)+ ? Duration.zero+ : grid.AppMotion.hover,+ child: ExcludeSemantics(+ excluding: visible,+ child: trailing == null+ ? details!+ : Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ Flexible(child: details!),+ trailing!,+ ],+ ),+ ),+ ),+ ),+ controls,+ ],+ );+ if (modelPicker == null) return actionArea;+ return Row(+ mainAxisSize: MainAxisSize.min,children: [- IgnorePointer(- ignoring: visible,- child: AnimatedOpacity(- key: const ValueKey('pane-header-details'),- opacity: visible ? 0 : 1,- duration: MediaQuery.disableAnimationsOf(context)- ? Duration.zero- : grid.AppMotion.hover,- child: ExcludeSemantics(- excluding: visible,- child: trailing == null- ? details!- : Row(- mainAxisSize: MainAxisSize.min,- children: [- Flexible(child: details!),- trailing!,- ],- ),- ),- ),- ),- controls,+ modelPicker!,+ const SizedBox(width: 4),+ Flexible(child: actionArea),],);}diff --git a/desktop/lib/widgets/terminal_panel.dart b/desktop/lib/widgets/terminal_panel.dartindex 0c03438cc..dd0f0ad2f 100644--- a/desktop/lib/widgets/terminal_panel.dart+++ b/desktop/lib/widgets/terminal_panel.dart@@ -1903,12 +1903,10 @@ class _TerminalHeader extends StatelessWidget {!isTerminalEngine(session.engineId)? onToggleComposer: null;- // The icon cluster, plus the model picker that now sits at its left — without the extra the- // constraint clips the picker rather than the details it was measured for. Zero on an engine- // that gets no picker, so those headers keep the width they always had.- final showModelPicker =- status == null && !readOnly && modelPickerSupports(session.engineId);- final pickerWidth = showModelPicker ? 72.0 : 0.0;+ // Reserve space for the visible model name and the pane controls.+ // Engines without a picker keep their existing header width.+ final showModelPicker = !readOnly && modelPickerSupports(session.engineId);+ final pickerWidth = showModelPicker ? 170.0 : 0.0;final actionsWidth =(remoteComposer == null ? 148.0 : 178.0) +pickerWidth +@@ -2093,10 +2091,8 @@ class _TerminalHeader extends StatelessWidget {): null,compact: narrow,- // Where this agent runs, with the controls rather than beside the name — the- // header has room for one of the two, and this is the half you only read while- // reaching for it. Absent while a notice is showing: a header asking to- // reconnect is not the moment to offer a menu.+ // Keep the current model visible, including while the+ // terminal reconnects, without shifting the other controls.modelPicker: showModelPicker? GridModelPicker(compact: narrow,@@ -2119,9 +2115,8 @@ class _TerminalHeader extends StatelessWidget {session.agentId,),),- // The pane's own context, because the door opens New Agent — and- // the pane's own MACHINE, because a picker on a remote agent's pane- // is asking about the models that computer can serve, not this one's.+ // Discovery opens the local Models popover. Selection above+ // continues to target this pane's existing session.onRunLocalModel: () => unawaited(notifier.runLocalModel(context,diff --git a/desktop/macos/Runner/SwarmTitlebar.swift b/desktop/macos/Runner/SwarmTitlebar.swiftindex 2d7c8e279..aabda3227 100644--- a/desktop/macos/Runner/SwarmTitlebar.swift+++ b/desktop/macos/Runner/SwarmTitlebar.swift@@ -123,7 +123,7 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {}private func sendTabAction(_ method: String, arguments: Any?) {- guard ["select", "close", "new", "rename", "commands", "notifications", "store", "sessions", "addAgent", "newAgent", "newTerminal", "cloneAgent", "restartAgent", "movePaneToTab", "runLocalModel", "splitRight", "splitDown", "zoomPane", "pinPane", "machineDestination", "machineAgent", "manageMachines", "machineList"].contains(method) else {+ guard ["select", "close", "new", "rename", "commands", "notifications", "store", "sessions", "models", "addAgent", "newAgent", "newTerminal", "cloneAgent", "restartAgent", "movePaneToTab", "runLocalModel", "splitRight", "splitDown", "zoomPane", "pinPane", "machineDestination", "machineAgent", "manageMachines", "machineList"].contains(method) else {channel.invokeMethod(method, arguments: arguments)return}@@ -618,23 +618,10 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {}}modelsMenu.addItem(.separator())- let run = NSMenuItem(title: "Manage Local Models in Grid…", action: nil, keyEquivalent: "")- run.identifier = NSUserInterfaceItemIdentifier(HarnessKeymapMenu.actionPrefix + "runLocalModel")- if machines.filter({ !$0.shared }).count > 1 {- let pick = NSMenu(title: run.title)- for machine in machines where !machine.shared {- let item = NSMenuItem(title: machine.local ? "\(machine.name) (this computer)" : machine.name,- action: #selector(runLocalModelAction(_:)), keyEquivalent: "")- item.target = self- item.representedObject = machine.id- pick.addItem(item)- }- run.submenu = pick- } else {- run.target = self- run.action = #selector(menuAction(_:))- run.representedObject = "runLocalModel"- }+ let run = NSMenuItem(title: "Open Models…", action: #selector(menuAction(_:)), keyEquivalent: "")+ run.identifier = NSUserInterfaceItemIdentifier(HarnessKeymapMenu.actionPrefix + "models")+ run.target = self+ run.representedObject = "models"modelsMenu.addItem(run)}@@ -1222,7 +1209,7 @@ private final class SwarmHistoryIcons {/// lib/store/store_mark.dart). Any other path draws the engine's initial,/// which is how the store tab once read "S".static func opens(_ asset: String) -> Bool {- !asset.contains("..") && (asset == "assets/app_icon.png" || asset == "assets/harnesses.png" || asset == "assets/store/polymath.png"+ !asset.contains("..") && (asset == "assets/app_icon.png" || asset == "assets/harnesses.png" || asset == "assets/models.png" || asset == "assets/store/polymath.png"|| asset.hasPrefix("assets/engine-icons/") && asset.hasSuffix(".png"))}@@ -1493,6 +1480,7 @@ private final class SwarmTabStrip: NSView {private let document = NSView()fileprivate let newButton = SwarmIconButton()fileprivate let storeButton = SwarmStoreButton(title: "Harness Store", target: nil, action: nil)+ fileprivate let modelsButton = SwarmIconButton()fileprivate let sessionsButton = SwarmSessionsButton()private var tabs: [SwarmTabButton] = []private let icons = SwarmHistoryIcons()@@ -1557,7 +1545,12 @@ private final class SwarmTabStrip: NSView {storeButton.toolTip = "Harness Store ⌘S"storeButton.setAccessibilityLabel("Harness Store")addSubview(storeButton)- setAccessibilityChildren([scroll, newButton, sessionsButton, storeButton])+ button(modelsButton, "brain", "AI Models", #selector(openModels))+ modelsButton.image = icons.image(engine: "models", asset: "assets/models.png", pointSize: 20)+ modelsButton.symbolConfiguration = nil+ modelsButton.isEnabled = false+ modelsButton.toolTip = "AI Models"+ setAccessibilityChildren([scroll, newButton, sessionsButton, modelsButton, storeButton])registerForDraggedTypes([swarmPasteboardType])}required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }@@ -1569,6 +1562,7 @@ private final class SwarmTabStrip: NSView {newButton.contentTintColor = palette.accentsessionsButton.contentTintColor = palette.accentstoreButton.palette = palette+ modelsButton.contentTintColor = palette.accentfor tab in tabs { tab.palette = palette }needsDisplay = true}@@ -1638,6 +1632,10 @@ private final class SwarmTabStrip: NSView {document.setAccessibilityChildren(tabs)newButton.isEnabled = actionsEnabledstoreButton.isEnabled = actionsEnabled+ modelsButton.isEnabled = actionsEnabled+ let modelReady = state["localModelReady"] as? Bool == true+ modelsButton.toolTip = modelReady ? "AI Models · Your local model is running" : "AI Models"+ modelsButton.setAccessibilityValue(state["modelsOpen"] as? Bool == true ? "Expanded" : "Collapsed")sessionsButton.isEnabled = actionsEnabledsessionsButton.running = state["runningSessions"] as? Int ?? 0sessionsButton.expanded = state["sessionsOpen"] as? Bool == true@@ -1683,12 +1681,13 @@ private final class SwarmTabStrip: NSView {let spacious = bounds.width >= 480let trailing: CGFloat = spacious ? 12 : 8let storeWidth = storeButton.preferredWidth+ let modelsWidth: CGFloat = 28newButton.isHidden = false// A reserve after the "+" that tabs never grow into — Chrome's gap. It is// where a full strip can still be dragged and double-clicked to zoom// (owner, 2026-09-15); tabs shrink and then scroll instead of taking it.let grip: CGFloat = spacious ? 84 : 44- let available = max(32, bounds.width - leading - trailing - (newButton.isHidden ? 0 : 36) - grip - storeWidth - 44)+ let available = max(32, bounds.width - leading - trailing - (newButton.isHidden ? 0 : 36) - grip - storeWidth - modelsWidth - 52)// As in Chrome, tabs keep shrinking until they are only their mark, so thirty tabs still sit in// one strip with nothing hidden; only past that does the strip scroll (the wheel scrolls it).let width = min(220, max(min(SwarmTabButton.minimumWidth, available), available / CGFloat(max(1, tabs.count))))@@ -1704,7 +1703,8 @@ private final class SwarmTabStrip: NSView {let buttonY = (bounds.height - 28) / 2newButton.frame = NSRect(x: leading + occupied + 4, y: buttonY, width: 28, height: 28)storeButton.frame = NSRect(x: bounds.width - trailing - storeWidth, y: buttonY, width: storeWidth, height: 28)- sessionsButton.frame = NSRect(x: storeButton.frame.minX - 36, y: buttonY, width: 28, height: 28)+ modelsButton.frame = NSRect(x: storeButton.frame.minX - modelsWidth - 8, y: buttonY, width: modelsWidth, height: 28)+ sessionsButton.frame = NSRect(x: modelsButton.frame.minX - 36, y: buttonY, width: 28, height: 28)let geometryChanged = scroll.frame.size != previousScrollSize || document.frame.size != previousDocumentSizeif let active, revealActiveAfterLayout || (activeWasVisible && (geometryChanged || tabOrderChanged)) {document.scrollToVisible(active.frame)@@ -1748,6 +1748,9 @@ private final class SwarmTabStrip: NSView {@objc private func openSessions() {if actionsEnabled { emit?("sessions", nil) }}+ @objc private func openModels() {+ if actionsEnabled { emit?("models", nil) }+ }private func draggedTab(_ sender: NSDraggingInfo) -> SwarmTabButton? {guard actionsEnabled, sender.draggingSourceOperationMask.contains(.move),diff --git a/desktop/pubspec.yaml b/desktop/pubspec.yamlindex 702ebfbf8..32b2391a8 100644--- a/desktop/pubspec.yaml+++ b/desktop/pubspec.yaml@@ -118,6 +118,8 @@ flutter:- assets/app_icon.png# Original stacked-terminal logo, retained for Harness Monitor.- assets/harnesses.png+ - assets/models.png+ - assets/model-icons/- assets/harness_device.png- assets/harness_device_studio.png- assets/harness_store_card.pngdiff --git a/desktop/test/grid_model_picker_test.dart b/desktop/test/grid_model_picker_test.dartindex 3277546d3..ae1e7db35 100644--- a/desktop/test/grid_model_picker_test.dart+++ b/desktop/test/grid_model_picker_test.dart@@ -9,10 +9,8 @@ import 'package:harness/auth/auth_session.dart';import 'package:harness/core/config.dart';import 'package:harness/core/models.dart';import 'package:harness/state/app_state.dart';-import 'package:harness/theme/app_theme.dart';import 'package:harness/widgets/grid_model_picker.dart';import 'package:harness/widgets/model_picker_chrome.dart';-import 'package:harness/widgets/pane_menu.dart';import 'package:harness/ws/ws_conn.dart';/// A connection that answers the picker's one RPC immediately. Without it the menu waits out the@@ -133,7 +131,7 @@ void main() {),),);- await tester.tap(find.text('Model'));+ await tester.tap(find.byType(GridModelPicker));// The menu waits on the grid read AND the usage read; settle covers both plus the open animation.await tester.pumpAndSettle();}@@ -154,7 +152,7 @@ void main() {// is always the first row. It is named the way the window's own Models menu names it — by// PROVIDER ('Anthropic'), not by engine ('Claude') — so the two controls agree about what the// thing is called, and it carries that menu's status text beside it.- expect(find.text('Anthropic'), findsOneWidget);+ expect(find.text('Anthropic').last, findsOneWidget);expect(find.textContaining('usage'), findsOneWidget);});@@ -187,7 +185,7 @@ void main() {),);await tester.pumpAndSettle();- final trigger = Focus.of(tester.element(find.byIcon(Icons.tune)));+ final trigger = Focus.of(tester.element(find.text('fixture-model')));trigger.requestFocus();await tester.pump();await tester.sendKeyEvent(LogicalKeyboardKey.enter);@@ -226,7 +224,11 @@ void main() {// has not been found. Left failing-and-named rather than deleted, because deleting it would// turn a regression into an absence nobody would notice.var ownLogin = 0;- build(models: const [{'id': 'Qwen-Test', 'node': 'macbook'}]);+ build(+ models: const [+ {'id': 'Qwen-Test', 'node': 'macbook'},+ ],+ );await open(tester, onOwnLogin: () => ownLogin++);await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);await tester.pumpAndSettle();@@ -259,7 +261,10 @@ void main() {tester,) async {await open(tester);- expect(find.text('No local models on this account yet.'), findsOneWidget);+ expect(+ find.text('Set up your first local model on this computer.'),+ findsOneWidget,+ );// The user's vocabulary is "Local models", never "grid" — the grid is how a Local model is// served, not a thing the picker asks anyone to know about.expect(find.textContaining('grid'), findsNothing);@@ -274,10 +279,13 @@ void main() {build(gridName: 'someone-7f3a91c4', gridCli: 'missing');await open(tester);expect(- find.text("Harness Compute isn't installed on this machine."),+ find.text('Model Manager can finish setting up this computer.'),findsOneWidget,);- expect(find.text('No local models on this account yet.'), findsNothing);+ expect(+ find.text('Set up your first local model on this computer.'),+ findsNothing,+ );expect(find.textContaining('grid'), findsNothing);},);@@ -289,7 +297,7 @@ void main() {await open(tester);expect(find.text('Nothing is being served yet.'), findsNothing);expect(find.text('Could not reach this machine.'), findsNothing);- expect(find.text('Manage in Grid'), findsOneWidget);+ expect(find.text('Local models'), findsOneWidget);},);@@ -321,7 +329,7 @@ void main() {await tester.tapAt(const Offset(5, 5));await tester.pumpAndSettle();served.add({'id': 'LFM2.5-8B', 'node': 'macbook'});- await tester.tap(find.text('Model'));+ await tester.tap(find.byType(GridModelPicker));await tester.pumpAndSettle();expect(find.text('Qwen3.5-4B'), findsOneWidget);@@ -330,6 +338,33 @@ void main() {expect(find.text('ON YOUR MACHINES'), findsOneWidget);});+ testWidgets('shared model changes refresh the open picker', (tester) async {+ final grids = <Map<String, Object?>>[+ {'name': 'home', 'own': true, 'models': <Object?>[]},+ {+ 'name': 'Team',+ 'own': false,+ 'models': <Object?>[+ {'id': 'Old model', 'node': 'Team computer'},+ ],+ },+ ];+ notifier.dispose();+ build(gridName: 'home', grids: grids);+ await open(tester);+ expect(find.text('Old model'), findsOneWidget);+ await tester.tapAt(const Offset(5, 5));+ await tester.pumpAndSettle();+ grids[1]['models'] = <Object?>[+ {'id': 'New model', 'node': 'Team computer'},+ ];+ await tester.tap(find.byType(GridModelPicker));+ await tester.pumpAndSettle();+ expect(find.text('Old model'), findsNothing);+ expect(find.text('New model'), findsOneWidget);+ expect(find.text('SHARED · TEAM'), findsOneWidget);+ });+testWidgets('every grid the machine is in gets a section, own first as Local',(tester) async {@@ -467,7 +502,7 @@ void main() {),),);- await tester.tap(find.text('Model'));+ await tester.tap(find.byType(GridModelPicker));await tester.pumpAndSettle();expect(find.text('SUBSCRIPTION'), findsOneWidget);@@ -587,13 +622,13 @@ void main() {var calls = 0;// Already on its own login: re-selecting it would respawn the pane for nothing.await open(tester, currentModel: null, onOwnLogin: () => calls++);- await tester.tap(find.text('Anthropic'));+ await tester.tap(find.text('Anthropic').last);await tester.pumpAndSettle();expect(calls, 0);// On a grid model: now it has somewhere to go.await open(tester, currentModel: 'Qwen-Test', onOwnLogin: () => calls++);- await tester.tap(find.text('Anthropic'));+ await tester.tap(find.text('Anthropic').last);await tester.pumpAndSettle();expect(calls, 1);},@@ -696,10 +731,12 @@ void main() {await open(tester);expect(find.text('1 model available'), findsOneWidget);- expect(find.text('Manage in Grid'), findsOneWidget);+ expect(find.text('Local models'), findsOneWidget);});- testWidgets('is never the marked row, whatever is selected', (tester) async {+ testWidgets('is never the marked row, whatever is selected', (+ tester,+ ) async {build(models: served);await open(tester, currentModel: 'Qwen-Test');@@ -708,7 +745,7 @@ void main() {final titles = tester.widgetList<ModelPickerRow>(find.byType(ModelPickerRow)).map((r) => r.title);- expect(titles, isNot(contains('Manage in Grid')));+ expect(titles, isNot(contains('Local models')));expect(find.byIcon(Icons.check), findsOneWidget);});@@ -721,7 +758,7 @@ void main() {onRunLocalModel: () => ran++,onSelected: (model) => picked = model,);- await tester.tap(find.text('Manage in Grid'));+ await tester.tap(find.text('Local models'));await tester.pumpAndSettle();expect(ran, 1);expect(picked, isNull);@@ -753,7 +790,7 @@ void main() {.first,).message,- 'Where this agent runs',+ 'Model: Qwen-Test · Click to switch',);});@@ -776,22 +813,22 @@ void main() {// Under the CURRENT model, not every model: the status is about this agent's launch, and the// other rows are places it could go, about which nothing is yet known.final subtitle = tester.getTopLeft(find.text('Web search unavailable'));- final current = tester.getTopLeft(find.text('Qwen-Test'));+ final current = tester.getTopLeft(find.text('Qwen-Test').last);final other = tester.getTopLeft(find.text('Other-Model'));expect(subtitle.dy, greaterThan(current.dy));expect(subtitle.dy, lessThan(other.dy));expect(tester- .widget<Tooltip>(- find- .ancestor(- of: find.text('Qwen-Test'),- matching: find.byType(Tooltip),- )- .first,- )- .message,- 'Where this agent runs\nWeb search unavailable',+ .widget<Tooltip>(+ find+ .ancestor(+ of: find.text('Qwen-Test'),+ matching: find.byType(Tooltip),+ )+ .first,+ )+ .message,+ 'Model: Qwen-Test · Click to switch\nWeb search unavailable',);},);@@ -820,7 +857,7 @@ void main() {.first,).message,- 'Where this agent runs\nWeb search not supported by this engine',+ 'Model: Qwen-Test · Click to switch\nWeb search not supported by this engine',);});@@ -895,7 +932,9 @@ void main() {.widgetList<ModelPickerRow>(find.byType(ModelPickerRow)).firstWhere((r) => r.title == title);- testWidgets('exactly one row is marked, and it carries the tick', (tester) async {+ testWidgets('exactly one row is marked, and it carries the tick', (+ tester,+ ) async {build(models: [{'id': 'Qwen-Test', 'node': 'macbook'},@@ -913,7 +952,11 @@ void main() {testWidgets('the subscription row is the marked one when no model is set', (tester,) async {- build(models: [{'id': 'Qwen-Test', 'node': 'macbook'}]);+ build(+ models: [+ {'id': 'Qwen-Test', 'node': 'macbook'},+ ],+ );await open(tester);expect(rowFor(tester, 'Anthropic').selected, isTrue);@@ -927,40 +970,45 @@ void main() {// changes once the daemon has done the work. The menu reopened with the tick still on the row// the person had just left, which reads as the click having done nothing.- testWidgets('a fresh currentModel while the menu is open does not crash the frame', (tester) async {- // The first attempt at this redrew the overlay from `didUpdateWidget`, which runs mid-build:- // "setState() or markNeedsBuild() called during build" across the whole window.- build(models: [- {'id': 'Qwen-Test', 'node': 'macbook'},- {'id': 'DeepSeek-Test', 'node': 'zeus'},- ]);-- Widget app(String? current) => MaterialApp(- home: Scaffold(- body: Center(- child: GridModelPicker(- notifier: notifier,- machineId: 'local',- engineLabel: 'claude',- currentModel: current,+ testWidgets(+ 'a fresh currentModel while the menu is open does not crash the frame',+ (tester) async {+ // The first attempt at this redrew the overlay from `didUpdateWidget`, which runs mid-build:+ // "setState() or markNeedsBuild() called during build" across the whole window.+ build(+ models: [+ {'id': 'Qwen-Test', 'node': 'macbook'},+ {'id': 'DeepSeek-Test', 'node': 'zeus'},+ ],+ );++ Widget app(String? current) => MaterialApp(+ home: Scaffold(+ body: Center(+ child: GridModelPicker(+ notifier: notifier,+ machineId: 'local',+ engineLabel: 'claude',+ currentModel: current,+ ),),),- ),- );+ );- tester.view.physicalSize = const Size(1200, 900);- tester.view.devicePixelRatio = 1;- addTearDown(tester.view.reset);- await tester.pumpWidget(app(null));- await tester.tap(find.text('Model'));- await tester.pumpAndSettle();- expect(find.text('Qwen-Test'), findsOneWidget);+ tester.view.physicalSize = const Size(1200, 900);+ tester.view.devicePixelRatio = 1;+ addTearDown(tester.view.reset);+ await tester.pumpWidget(app(null));+ await tester.tap(find.byType(GridModelPicker));+ await tester.pumpAndSettle();+ expect(find.text('Qwen-Test'), findsOneWidget);- // The daemon's frame lands while the menu is still open.- await tester.pumpWidget(app('Qwen-Test'));- await tester.pumpAndSettle();- expect(tester.takeException(), isNull);- });+ // The daemon's frame lands while the menu is still open.+ await tester.pumpWidget(app('Qwen-Test'));+ await tester.pumpAndSettle();+ expect(tester.takeException(), isNull);+ },+ );/// Open the picker as a rebuildable host, so a test can change `currentModel` under it the way/// the daemon's frames do.@@ -996,7 +1044,7 @@ void main() {),),);- await tester.tap(find.text('Model'));+ await tester.tap(find.byType(GridModelPicker));await tester.pumpAndSettle();return (String? next) => setHost(() => current = next);}@@ -1005,25 +1053,33 @@ void main() {.widgetList<ModelPickerRow>(find.byType(ModelPickerRow)).any((r) => r.title == title && r.selected);- testWidgets('the tick stays on the picked model through the respawn', (tester) async {+ testWidgets('the tick stays on the picked model through the respawn', (+ tester,+ ) async {// A retarget restarts the pane, and a restarting pane reports NO model for a moment. Taking// that null as the answer put the tick back on Subscription mid-move, and the row the person// clicked only claimed it once the respawn finished — the flicker between two answers.- build(models: [- {'id': 'gemma-4-31B-it', 'node': '3d-artist-diego'},- ]);+ build(+ models: [+ {'id': 'gemma-4-31B-it', 'node': '3d-artist-diego'},+ ],+ );final report = await openLive(tester, currentModel: 'Qwen-Old');await tester.tap(find.text('gemma-4-31B-it'));await tester.pumpAndSettle();- await tester.tap(find.text('Model'));+ await tester.tap(find.byType(GridModelPicker));await tester.pumpAndSettle();expect(ticked(tester, 'gemma-4-31B-it'), isTrue);// The pane goes down: no model at all.report(null);await tester.pumpAndSettle();- expect(ticked(tester, 'gemma-4-31B-it'), isTrue, reason: 'a restarting pane is not an answer');+ expect(+ ticked(tester, 'gemma-4-31B-it'),+ isTrue,+ reason: 'a restarting pane is not an answer',+ );expect(ticked(tester, 'Anthropic'), isFalse);// And comes back up on what was asked for.@@ -1032,11 +1088,15 @@ void main() {expect(ticked(tester, 'gemma-4-31B-it'), isTrue);});- testWidgets('a model the menu did not ask for wins over the guess', (tester) async {- build(models: [- {'id': 'gemma-4-31B-it', 'node': '3d-artist-diego'},- {'id': 'Qwen-Test', 'node': 'macbook'},- ]);+ testWidgets('a model the menu did not ask for wins over the guess', (+ tester,+ ) async {+ build(+ models: [+ {'id': 'gemma-4-31B-it', 'node': '3d-artist-diego'},+ {'id': 'Qwen-Test', 'node': 'macbook'},+ ],+ );// Starts on the engine's own login, so the report below is a real CHANGE. A daemon that// re-sends the value it already held is not a new answer, and the guess then waits out its// own timer rather than being contradicted.@@ -1044,7 +1104,7 @@ void main() {await tester.tap(find.text('gemma-4-31B-it'));await tester.pumpAndSettle();- await tester.tap(find.text('Model'));+ await tester.tap(find.byType(GridModelPicker));await tester.pumpAndSettle();expect(ticked(tester, 'gemma-4-31B-it'), isTrue);@@ -1055,29 +1115,34 @@ void main() {expect(ticked(tester, 'gemma-4-31B-it'), isFalse);});- testWidgets('choosing the own login is confirmed BY a null, not broken by one', (tester) async {- build(models: [- {'id': 'gemma-4-31B-it', 'node': '3d-artist-diego'},- ]);- final report = await openLive(tester, currentModel: 'gemma-4-31B-it');+ testWidgets(+ 'choosing the own login is confirmed BY a null, not broken by one',+ (tester) async {+ build(+ models: [+ {'id': 'gemma-4-31B-it', 'node': '3d-artist-diego'},+ ],+ );+ final report = await openLive(tester, currentModel: 'gemma-4-31B-it');- await tester.tap(find.text('Anthropic'));- await tester.pumpAndSettle();- await tester.tap(find.text('Model'));- await tester.pumpAndSettle();- expect(ticked(tester, 'Anthropic'), isTrue);+ await tester.tap(find.text('Anthropic').last);+ await tester.pumpAndSettle();+ await tester.tap(find.byType(GridModelPicker));+ await tester.pumpAndSettle();+ expect(ticked(tester, 'Anthropic'), isTrue);- report(null);- await tester.pumpAndSettle();- expect(ticked(tester, 'Anthropic'), isTrue);- expect(ticked(tester, 'gemma-4-31B-it'), isFalse);+ report(null);+ await tester.pumpAndSettle();+ expect(ticked(tester, 'Anthropic'), isTrue);+ expect(ticked(tester, 'gemma-4-31B-it'), isFalse);- // And the guess is RELEASED by that confirmation, not merely agreed with: the next thing the- // machine says has to land. A guess that only ever expired on its clock would hold the tick on- // Subscription for another half minute after the agent had moved on.- report('gemma-4-31B-it');- await tester.pumpAndSettle();- expect(ticked(tester, 'gemma-4-31B-it'), isTrue);- expect(ticked(tester, 'Anthropic'), isFalse);- });+ // And the guess is RELEASED by that confirmation, not merely agreed with: the next thing the+ // machine says has to land. A guess that only ever expired on its clock would hold the tick on+ // Subscription for another half minute after the agent had moved on.+ report('gemma-4-31B-it');+ await tester.pumpAndSettle();+ expect(ticked(tester, 'gemma-4-31B-it'), isTrue);+ expect(ticked(tester, 'Anthropic'), isFalse);+ },+ );}diff --git a/desktop/test/model_manager_controller_test.dart b/desktop/test/model_manager_controller_test.dartnew file mode 100644index 000000000..eb9787a1a--- /dev/null+++ b/desktop/test/model_manager_controller_test.dart@@ -0,0 +1,472 @@+import 'dart:async';++import 'package:flutter_test/flutter_test.dart';+import 'package:harness/core/models.dart';+import 'package:harness/models/model_manager_controller.dart';+import 'package:harness/models/local_model.dart';+import 'package:harness/state/app_state.dart';++import 'support/model_manager.dart';+import 'swarm_screen_test.dart' show terminal;+import 'swarm_state_test.dart' show MemoryStore;++void main() {+ TestWidgetsFlutterBinding.ensureInitialized();+ late ModelManagerConnection connection;+ late ModelManagerTestApp app;+ late ModelManagerController controller;+ setUp(() {+ connection = ModelManagerConnection();+ app = ModelManagerTestApp(connection);+ controller = ModelManagerController(+ app,+ storage: MemoryStore(),+ poll: false,+ );+ });+ tearDown(() {+ controller.dispose();+ app.dispose();+ });++ test('silent discovery preserves the workspace and never starts a model or sends a chat', () async {+ connection.holdCreation = Completer<void>();+ final original = app.activeSwarmId;+ controller.start();+ final prepare = controller.prepare();+ await controller.refresh();+ expect(controller.localModels, hasLength(5));+ expect(app.actions, isEmpty);+ expect(app.sent, isEmpty);+ expect(app.panes, isEmpty);+ connection.holdCreation!.complete();+ await prepare;+ await controller.prepare();+ expect(connection.creations, hasLength(1));+ expect(controller.manager?.dsh, AppNotifier.gridHarness);+ expect(app.activeSwarmId, original);+ });++ test(+ 'advanced manager opens locally without an unsolicited setup task',+ () async {+ app.installed = false;+ controller.start();+ await controller.open();+ await controller.open();+ expect(app.installs, 1);+ expect(connection.creations, hasLength(1));+ expect(app.sent, isEmpty);+ expect(app.activeSwarm.name, modelManagerName);+ expect(app.allPanes.single.agentId, 'manager');+ },+ );++ test('a lost manager creation acknowledgement reuses its receipt', () async {+ connection.loseFirstReply = true;+ controller.start();+ await controller.prepare();+ expect(controller.manager, isNull);+ await controller.open();+ expect(connection.creations, hasLength(1));+ expect(controller.manager?.id, 'manager');+ });++ test(+ 'opening the manager from another tab reuses its pending pane',+ () async {+ app.stateOf('m')!.agents = [+ const Agent(id: 'source', name: 'Work', engine: 'codex'),+ ];+ app.adoptSessionForTest(terminal('source', []));+ final sourceTab = app.activeSwarmId;+ await controller.open();+ final managerTab = app.activeSwarmId;+ final count = app.swarms.length;+ expect(managerTab, isNot(sourceTab));+ app.selectSwarm(sourceTab);+ await controller.open();+ expect(app.activeSwarmId, managerTab);+ expect(app.swarms, hasLength(count));+ expect(app.allPanes.where((p) => p.agentId == 'manager'), hasLength(1));+ expect(connection.creations, hasLength(1));+ },+ );++ test(+ 'Start submits one local operation and never changes or creates a session',+ () async {+ app.stateOf('m')!.agents = [+ const Agent(id: 'source', name: 'Work', engine: 'codex'),+ ];+ app.adoptSessionForTest(terminal('source', []));+ controller.start();+ await controller.prepare();+ await controller.refresh();+ final tab = app.activeSwarmId;+ final row = controller.localModels.first;+ await controller.toggle(row);+ await controller.toggle(row);+ expect(app.actions, [(machine: 'm', model: 'qwen', start: true)]);+ expect(+ controller.operationFor(controller.localModels.first)?.progress,+ .42,+ );+ expect(app.activeSwarmId, tab);+ expect(app.focusedPane?.agentId, 'source');+ expect(+ app.stateOf('m')!.agents.firstWhere((a) => a.id == 'source').gridModel,+ isNull,+ );+ expect(app.sent, isEmpty);+ expect(connection.creations, hasLength(1));+ },+ );++ test('downloaded models use the same Start action', () async {+ await controller.refresh();+ await controller.toggle(+ controller.localModels.firstWhere((m) => m.downloaded),+ );+ expect(app.actions.single, (machine: 'm', model: 'gemma', start: true));+ });++ test(+ 'the acknowledgement supplies progress while fresh inventory is in flight',+ () async {+ await controller.refresh();+ final row = controller.localModels.first;+ final reply = Completer<Map<String, dynamic>>();+ app.localReply = reply;+ final action = controller.toggle(row);+ await Future<void>.delayed(Duration.zero);+ expect(controller.operationFor(row)?.label, 'Downloading');+ expect(controller.operationFor(row)?.progress, .42);+ reply.complete(app.localInventory);+ await action;+ },+ );++ test('Stop explicitly unloads a running model', () async {+ app.localInventory = modelInventory(scenario: 'ready');+ await controller.refresh();+ await controller.toggle(controller.localModels.first);+ expect(app.actions.single, (machine: 'm', model: 'qwen', start: false));+ });++ test(+ 'a lost action acknowledgement is recovered from status without replaying',+ () async {+ app.actionReplyLost = true;+ await controller.refresh();+ await controller.toggle(controller.localModels.first);+ expect(app.actions, hasLength(1));+ expect(controller.busy, isTrue);+ expect(controller.localModels.first.operation?.progress, .42);+ expect(controller.error, isNull);+ },+ );++ test(+ 'readiness requires a completed test reply, not a running process alone',+ () async {+ app.localInventory = modelInventory(scenario: 'ready');+ final models = app.localInventory['models'] as List;+ models[0]['operation']['phase'] = 'running';+ await controller.refresh();+ expect(controller.readyModel, isNull);+ models[0]['operation']['phase'] = 'done';+ await controller.refresh();+ expect(controller.readyModel?.name, 'Qwen3.8-27B');+ controller.dismissReady();+ expect(controller.readyModel, isNull);+ },+ );++ test(+ 'an unavailable inventory disables actions while preserving the last view',+ () async {+ await controller.refresh();+ app.localReadFails = true;+ await controller.refresh();+ expect(controller.localModels, hasLength(5));+ expect(controller.inventoryAvailable, isFalse);+ await controller.toggle(controller.localModels.first);+ expect(app.actions, isEmpty);+ },+ );++ test('an account change discards an in-flight action result', () async {+ controller.start();+ await controller.prepare();+ await controller.refresh();+ app.actionReply = Completer<Map<String, dynamic>>();+ final pending = controller.toggle(controller.localModels.first);+ app.machineStates.clear();+ app.notifyListeners();+ app.actionReply!.complete({+ 'operation': {+ 'id': 'old',+ 'modelId': 'qwen',+ 'action': 'start',+ 'stage': 'downloading',+ 'phase': 'running',+ },+ });+ await pending;+ expect(controller.localModels, isEmpty);+ expect(controller.pendingOperation, isNull);+ expect(controller.busy, isFalse);+ });++ test(+ 'discovery invites a supported session once and remembers dismissal',+ () async {+ app.stateOf('m')!.agents = [+ const Agent(id: 'work', name: 'Work', engine: 'codex'),+ ];+ controller.start();+ controller.start();+ await controller.prepare();+ await controller.refresh();+ expect(controller.showIntroduction, isTrue);+ expect(controller.hasOwnModels, isFalse);+ await controller.dismissIntroduction();+ expect(controller.showIntroduction, isFalse);+ expect(app.actions, isEmpty);+ },+ );++ test(+ 'an unavailable local connection shows a next step and cannot act',+ () async {+ await controller.refresh();+ final model = controller.localModels.first;+ app.machineStates.clear();+ await controller.refresh();+ expect(controller.error, contains('Connect this computer'));+ await controller.toggle(model);+ await controller.open();+ expect(controller.error, contains('Connect this computer'));+ expect(app.actions, isEmpty);+ },+ );++ test(+ 'disconnect immediately disables actions on the last observed inventory',+ () async {+ controller.start();+ await controller.prepare();+ await controller.refresh();+ app.stateOf('m')!.connectionStatus = ConnectionStatus.disconnected;+ app.notifyListeners();+ expect(controller.inventoryAvailable, isFalse);+ await controller.toggle(controller.localModels.first);+ expect(app.actions, isEmpty);+ },+ );++ for (final failure in ['install', 'probe', 'create']) {+ test(+ 'advanced manager recovers from $failure failure while discovery stays usable',+ () async {+ if (failure == 'install') {+ app.installed = false;+ app.installError = 'Install interrupted';+ }+ if (failure == 'probe') app.probeError = 'Unavailable';+ if (failure == 'create') {+ connection.creationError = 'Create interrupted';+ }+ await controller.open();+ expect(controller.error, isNotNull);+ expect(controller.opening, isFalse);+ expect(controller.preparing, isFalse);+ await controller.refresh();+ expect(controller.localModels, isNotEmpty);+ expect(controller.inventoryAvailable, isTrue);+ app.installError = app.probeError = connection.creationError = null;+ await controller.open();+ expect(controller.error, isNull);+ expect(app.activeSwarm.name, modelManagerName);+ },+ );+ }++ for (final failure in ['none', 'error', 'throw']) {+ test(+ 'resuming an existing manager handles $failure without creating another',+ () async {+ app.stateOf('m')!.agents = [+ const Agent(+ id: 'manager',+ name: modelManagerName,+ engine: 'codex',+ dsh: AppNotifier.gridHarness,+ status: 'stopped',+ ),+ ];+ app.resumeError = failure == 'error' ? 'Could not resume' : null;+ app.resumeThrows = failure == 'throw';+ await controller.open();+ expect(app.resumes, 1);+ expect(connection.creations, isEmpty);+ expect(controller.error, failure == 'none' ? isNull : isNotNull);+ expect(controller.opening, isFalse);+ },+ );+ }++ test(+ 'a read issued before Start cannot overwrite its acknowledgement',+ () async {+ await controller.refresh();+ final stale = Map<String, dynamic>.of(app.localInventory);+ final read = Completer<Map<String, dynamic>>();+ app.localReply = read;+ final refreshing = controller.refresh();+ final toggling = controller.toggle(controller.localModels.first);+ await Future<void>.delayed(Duration.zero);+ read.complete(stale);+ await refreshing;+ await toggling;+ expect(app.actions, hasLength(1));+ expect(controller.localModels.first.operation?.active, isTrue);+ expect(controller.busy, isTrue);+ },+ );++ test('a completed operation on a removed catalog row cannot leave controls busy forever', () async {+ await controller.refresh();+ app.actionReply = Completer<Map<String, dynamic>>();+ final action = controller.toggle(controller.localModels.first);+ app.localInventory = {'models': [], 'busy': false};+ app.actionReply!.complete({+ 'operation': {+ 'id': 'gone',+ 'modelId': 'qwen',+ 'action': 'start',+ 'stage': 'checking',+ 'phase': 'running',+ },+ });+ await action;+ expect(controller.busy, isFalse);+ expect(controller.pendingOperation, isNull);+ expect(controller.localModels, isEmpty);+ });++ test('an old daemon or malformed inventory disables actions without clearing the last view', () async {+ await controller.refresh();+ app.localInventory = {'error': 'Update Harness to manage local models.'};+ await controller.refresh();+ expect(controller.localModels, hasLength(5));+ expect(controller.inventoryAvailable, isFalse);+ expect(controller.error, contains('Update Harness'));+ app.localInventory = {+ 'models': [+ {'id': 7},+ ],+ };+ await controller.refresh();+ expect(controller.error, contains('unavailable'));+ });++ test(+ 'late discovery and manager setup cannot publish to another account',+ () async {+ controller.start();+ await controller.prepare();+ await controller.refresh();+ final reply = Completer<Map<String, dynamic>>();+ app.localReply = reply;+ final pending = controller.refresh();+ app.machineStates.clear();+ app.notifyListeners();+ reply.complete(modelInventory(scenario: 'ready'));+ await pending;+ expect(controller.readyModel, isNull);+ expect(controller.localModels, isEmpty);+ },+ );++ test('a model with no supported control is never submitted', () async {+ await controller.refresh();+ await controller.toggle(+ const LocalModel(id: 'read-only', name: 'External'),+ );+ expect(app.actions, isEmpty);+ });++ testWidgets('polls visible or active work and stays quiet when closed', (+ tester,+ ) async {+ final polling = ModelManagerController(app);+ polling.start();+ await tester.pump();+ final initial = app.localReads;+ await tester.pump(const Duration(seconds: 8));+ expect(app.localReads, initial);+ polling.setPanelVisible(true);+ await tester.pump(const Duration(seconds: 4));+ expect(app.localReads, greaterThan(initial));+ polling.setPanelVisible(false);+ await polling.toggle(polling.localModels.first);+ final busyReads = app.localReads;+ await tester.pump(const Duration(seconds: 4));+ expect(app.localReads, greaterThan(busyReads));+ polling.dispose();+ final disposedReads = app.localReads;+ polling.start();+ await tester.pump(const Duration(seconds: 8));+ expect(app.localReads, disposedReads);+ });++ test('model data keeps unknown telemetry absent and parses only valid operations', () {+ final base = {+ 'id': 'job',+ 'modelId': 'model',+ 'action': 'start',+ 'phase': 'running',+ 'stage': 'checking',+ };+ for (final stage in [+ 'checking',+ 'downloading',+ 'starting',+ 'verifying',+ 'stopping',+ ]) {+ expect(+ LocalModelOperation.parse({...base, 'stage': stage})?.label,+ {+ 'checking': 'Checking',+ 'downloading': 'Downloading',+ 'starting': 'Starting',+ 'verifying': 'Testing',+ 'stopping': 'Stopping',+ }[stage],+ );+ }+ for (final raw in [+ null,+ {},+ {...base, 'action': 'delete'},+ {...base, 'phase': 'unknown'},+ {...base, 'stage': 'unknown'},+ ]) {+ expect(LocalModelOperation.parse(raw), isNull);+ }+ final model = LocalModel.fromJson({+ 'id': 'model',+ 'sizeBytes': double.nan,+ 'requests': -1,+ 'tokensPerSecond': double.infinity,+ 'operation': {...base, 'progress': 2},+ });+ expect(model.sizeBytes, isNull);+ expect(model.requests, isNull);+ expect(model.tokensPerSecond, isNull);+ expect(model.operation?.progress, 1);+ });+}diff --git a/desktop/test/model_mark_test.dart b/desktop/test/model_mark_test.dartnew file mode 100644index 000000000..f5014f7c6--- /dev/null+++ b/desktop/test/model_mark_test.dart@@ -0,0 +1,103 @@+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/models/model_mark.dart';++void main() {+ test(+ 'recognizes model families across hosts, versions and quantizations',+ () {+ const names = {+ 'Qwen/Qwen3.8-27B': 'qwen',+ 'unsloth/Qwen3-Coder-30B-A3B-Q4_K_M.gguf': 'qwen',+ 'M2-qwen3.8-27b': 'qwen',+ 'QwQ-32B': 'qwen',+ 'google/gemma-4-12b-it': 'gemma',+ 'DeepSeek-R1-Distill-Qwen-32B': 'deepseek',+ 'openai/gpt-oss-20b': 'openai',+ 'OpenAI': 'openai',+ 'Codex': 'openai',+ 'meta-llama/Llama-3.3-70B-Instruct': 'meta',+ 'Mistral-Small-3.2': 'mistral',+ 'Mixtral-8x7B': 'mistral',+ 'Ministral-8B': 'mistral',+ 'Codestral-22B': 'mistral',+ 'Devstral-Small-24B': 'mistral',+ 'microsoft/Phi-4-mini-instruct': 'microsoft',+ 'zai-org/GLM-4.5': 'zai',+ 'Zai': 'zai',+ 'moonshotai/Kimi-K2': 'kimi',+ 'Claude': 'claude',+ 'Anthropic': 'claude',+ };+ for (final entry in names.entries) {+ expect(+ ModelMark.assetFor(entry.key),+ 'assets/model-icons/${entry.value}.png',+ reason: entry.key,+ );+ }+ for (final unknown in [+ null,+ '',+ 'Team coding model',+ 'qwen-owner/custom-model',+ 'Gemmax',+ 'Alphine',+ ]) {+ expect(ModelMark.assetFor(unknown), isNull, reason: '$unknown');+ }+ },+ );++ for (final brightness in Brightness.values) {+ testWidgets(+ 'all model marks render in ${brightness.name}, unknowns use the brain',+ (tester) async {+ const models = [+ 'Qwen3',+ 'Gemma-4',+ 'GPT-OSS',+ 'DeepSeek',+ 'Llama',+ 'Mistral',+ 'Phi-4',+ 'GLM-4',+ 'Kimi',+ 'Claude',+ 'Team coding model',+ ];+ await tester.pumpWidget(+ MaterialApp(+ theme: ThemeData(brightness: brightness),+ home: Scaffold(+ body: Wrap(+ children: [+ const ModelMark(semanticLabel: 'AI Models'),+ for (final model in models) ModelMark(model: model),+ ],+ ),+ ),+ ),+ );+ await tester.runAsync(() async {+ for (final image in tester.widgetList<Image>(find.byType(Image))) {+ await precacheImage(image.image, tester.element(find.byType(Wrap)));+ }+ });+ await tester.pump();+ final images = tester.widgetList<Image>(find.byType(Image)).toList();+ expect(images.length, models.length + 1);+ expect(+ (images.first.image as AssetImage).assetName,+ 'assets/models.png',+ );+ expect(+ (images.last.image as AssetImage).assetName,+ 'assets/models.png',+ );+ expect(images.first.semanticLabel, 'AI Models');+ expect(tester.takeException(), isNull);+ },+ );+ }+}diff --git a/desktop/test/models_menu_test.dart b/desktop/test/models_menu_test.dartindex 514a34966..7727e12a2 100644--- a/desktop/test/models_menu_test.dart+++ b/desktop/test/models_menu_test.dart@@ -6,8 +6,6 @@ import 'package:flutter_test/flutter_test.dart';import 'package:harness/core/models.dart';import 'package:harness/core/dsh_catalog.dart';import 'package:harness/widgets/agent_picker.dart';-import 'package:harness/shared/widgets/app_choice_picker.dart';-import 'package:harness/store/store_screen.dart';import 'package:harness/core/config.dart';import 'package:harness/auth/auth_session.dart';import 'package:harness/screens/swarm_screen.dart';@@ -24,6 +22,10 @@ import 'package:harness/widgets/new_harness_box.dart';import 'swarm_screen_test.dart' show terminal;import 'swarm_state_test.dart' show createApp;+import 'support/model_manager.dart';++import 'package:harness/models/models_panel.dart';+import 'keymap_host_test.dart' show key;/// Stands in for the machine behind the Open Grid door: the probes New Agent@@ -350,7 +352,7 @@ void main() {/// `runLocalModel` command, with or without a machine.Future<void> openGridDoor(WidgetTester tester,- _GridApp app, {+ AppNotifier app, {String? machineId,String command = 'runLocalModel',}) async {@@ -383,12 +385,17 @@ void main() {),(_) => reply.complete(),);- await tester.pumpAndSettle();+ if (command == 'runLocalModel') {+ for (var i = 0; i < 15; i++) {+ await tester.pump(const Duration(milliseconds: 50));+ }+ expect(reply.isCompleted, isTrue);+ } else {+ await tester.pumpAndSettle();+ }}for (final (command, harness, stem, machineId) in [- ('runLocalModel', AppNotifier.gridHarness, 'grid', null),- ('runLocalModel', AppNotifier.gridHarness, 'grid', 'other'),('manageMachines', AppNotifier.machinesHarness, 'machine-monitor', null),]) {testWidgets('native $command opens the product dock on $machineId', (@@ -441,62 +448,37 @@ void main() {});}- testWidgets('native runLocalModel opens New Agent with Grid chosen', (- tester,- ) async {- // The Models menu's command arrives as a bare method call, the way Link- // Machine… does. Grid is installed here, so the door is the Store's Open- // button in another place: a draft tab, New Agent, Grid already chosen.- final app = _gridApp(grid: {'m': true});- await openGridDoor(tester, app);-- // The dialog is open (its title also names the tab and the start card).- expect(find.byType(AgentPicker), findsOneWidget);- final picker = tester.widget<AgentPicker>(find.byType(AgentPicker));- expect(picker.value, AppNotifier.gridHarness);- expect(app.activeSwarm.isStore, isFalse);- expect(app.panes, isEmpty);-- await tester.pumpWidget(const SizedBox());- app.dispose();- });-- testWidgets('native runLocalModel with a machineId opens on THAT machine', (- tester,- ) async {- // With two machines linked the native menu lists them and names the chosen- // one: New Harness opens with that machine selected, so Grid manages the- // models of the computer it runs on.- final app = _gridApp(grid: {'m': true, 'other': true}, secondMachine: true);- await openGridDoor(tester, app, machineId: 'other');-- expect(find.byType(AgentPicker), findsOneWidget);- expect(- tester.widget<AgentPicker>(find.byType(AgentPicker)).value,- AppNotifier.gridHarness,+ for (final remote in [false, true]) {+ testWidgets(+ 'native local models opens the overview (remote argument: $remote)',+ (tester) async {+ final connection = ModelManagerConnection();+ final app = ModelManagerTestApp(connection);+ await openGridDoor(tester, app, machineId: remote ? 'other' : null);+ expect(find.byType(AgentPicker), findsNothing);+ expect(find.byType(NewHarnessBox), findsNothing);+ expect(app.activeSwarm.isStore, isFalse);+ expect(app.allPanes, isEmpty);+ expect(find.byType(ModelsPanel), findsOneWidget);+ expect(app.sent, isEmpty);+ await tester.pumpWidget(const SizedBox());+ app.dispose();+ },);- final machines = tester.widget<AppChoicePicker<String>>(- find.byKey(const Key('new-agent-machine-field')),- );- expect(machines.value, 'other');-- await tester.pumpWidget(const SizedBox());- app.dispose();- });+ }- testWidgets("without Grid installed, the door is the Store on Grid's page", (+ testWidgets('native Models opens the overview without creating a session', (tester,) async {- // No harness to open yet: the Store's page for Grid has Install, and that- // is the way in. No New Harness, no pane.- final app = _gridApp(grid: {'m': false});- await openGridDoor(tester, app);-- expect(find.byType(AgentPicker), findsNothing);- expect(app.activeSwarm.isStore, isTrue);- expect(find.byType(StoreTab), findsOneWidget);- expect(app.panes, isEmpty);-+ final connection = ModelManagerConnection();+ final app = ModelManagerTestApp(connection);+ await openGridDoor(tester, app, command: 'models');+ expect(find.byType(ModelsPanel), findsOneWidget);+ expect(find.text('Search models…'), findsOneWidget);+ expect(connection.creations, isEmpty);+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);+ await tester.pumpAndSettle();+ expect(find.byType(ModelsPanel), findsNothing);await tester.pumpWidget(const SizedBox());app.dispose();});diff --git a/desktop/test/models_panel_test.dart b/desktop/test/models_panel_test.dartnew file mode 100644index 000000000..60c895ee1--- /dev/null+++ b/desktop/test/models_panel_test.dart@@ -0,0 +1,595 @@+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:lucide_icons_flutter/lucide_icons.dart';+import 'package:harness/core/models.dart';+import 'package:harness/models/model_manager_controller.dart';+import 'package:harness/models/models_panel.dart';+import 'package:harness/screens/swarm_screen.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/state/swarm_catalog.dart';+import 'package:harness/usage/models_menu_controller.dart';+import 'package:harness/usage/usage_controller.dart';+import 'package:harness/usage/usage_source.dart';+import 'package:harness/usage/usage_window.dart';+import 'package:harness/ws/local_cli_discovery.dart';++import 'support/model_manager.dart';+import 'support/real_fonts.dart';+import 'swarm_screen_test.dart' show terminal;++class _Subscription implements UsageSource {+ @override+ UsageProvider get provider => UsageProvider.codex;+ @override+ Future<ProviderUsage> read() async => ProviderUsage(+ provider: provider,+ status: UsageStatus.ok,+ account: 'aabbccddeeff0011',+ fetchedAt: DateTime.now(),+ windows: const [UsageWindow(label: 'Session', usedPercent: 24)],+ );+}++class _SubscriptionRows extends ModelsMenuController {+ @override+ List<Map<String, Object?>> get rows => const [+ {+ 'title': 'OpenAI',+ 'account': 'abc123',+ 'status': '0% remaining',+ 'remainingPercent': 0.0,+ },+ {'title': 'OpenAI', 'account': 'def456', 'status': 'Usage unavailable'},+ ];+ @override+ Future<void> refresh() async {}+}++void main() {+ setUpAll(() async {+ await loadRealFonts();+ await (FontLoader(+ 'MaterialIcons',+ )..addFont(rootBundle.load('fonts/MaterialIcons-Regular.otf'))).load();+ await (FontLoader('packages/lucide_icons_flutter/Lucide')..addFont(+ rootBundle.load('packages/lucide_icons_flutter/assets/lucide.ttf'),+ ))+ .load();+ });++ testWidgets(+ 'discovery, empty filters, shared models and retry all have clear states',+ (tester) async {+ tester.view.devicePixelRatio = 1;+ tester.view.physicalSize = const Size(700, 800);+ addTearDown(tester.view.reset);+ final app = ModelManagerTestApp(ModelManagerConnection());+ final controller = ModelManagerController(app, poll: false);+ final subscriptions = _SubscriptionRows();+ addTearDown(() {+ controller.dispose();+ subscriptions.dispose();+ app.dispose();+ });+ var closed = 0;+ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(+ body: Center(+ child: SizedBox(+ width: 640,+ child: ModelsPanel(+ controller: controller,+ subscriptions: subscriptions,+ onClose: () => closed++,+ onManage: () {},+ ),+ ),+ ),+ ),+ ),+ );+ expect(find.text('Finding models that fit…'), findsOneWidget);+ app.localInventory = {'models': [], 'busy': false};+ await controller.refresh();+ await tester.pump();+ expect(find.text('No compatible models found'), findsOneWidget);+ expect(find.text('Account ···abc123'), findsOneWidget);+ expect(find.text('Account ···def456'), findsOneWidget);+ expect(find.text('0% left'), findsOneWidget);+ await tester.tap(find.text('Running 0'));+ await tester.pump();+ expect(find.text('No models running'), findsOneWidget);+ expect(find.textContaining('Downloaded'), findsNothing);+ await tester.enterText(+ find.byKey(const ValueKey('models-search')),+ 'missing',+ );+ await tester.pump();+ expect(find.text('No matching models'), findsOneWidget);+ await tester.sendKeyDownEvent(LogicalKeyboardKey.metaLeft);+ await tester.sendKeyEvent(LogicalKeyboardKey.keyA);+ await tester.sendKeyUpEvent(LogicalKeyboardKey.metaLeft);+ final field = tester.widget<TextField>(+ find.byKey(const ValueKey('models-search')),+ );+ expect(+ field.controller!.selection,+ const TextSelection(baseOffset: 0, extentOffset: 7),+ );+ await tester.tap(find.byTooltip('Clear search'));+ await tester.pump();+ expect(find.byTooltip('Clear search'), findsNothing);+ expect(find.text('No matching models'), findsNothing);+ expect(field.focusNode!.hasFocus, isTrue);+ await tester.tap(find.text('All 0'));+ app.inventory = const GridModels(+ gridName: 'home',+ models: [],+ grids: [+ GridSection(+ name: 'Team',+ own: false,+ models: [GridModel(id: 'Shared Qwen', node: 'Team computer')],+ ),+ ],+ );+ app.localInventory = modelInventory();+ await controller.refresh(force: true);+ await tester.pump();+ expect(find.text('gemma-4-12B'), findsOneWidget);+ expect(find.text('Qwen3.8-27B'), findsOneWidget);+ expect(find.text('7.3 GB'), findsOneWidget);+ expect(find.text('16.2 GB'), findsOneWidget);+ expect(find.textContaining(' on disk'), findsNothing);+ expect(find.textContaining(' download'), findsNothing);+ await tester.enterText(+ find.byKey(const ValueKey('models-search')),+ 'shared',+ );+ await tester.pump();+ expect(find.text('Shared · Team'), findsOneWidget);+ expect(find.text('Shared Qwen'), findsOneWidget);+ expect(find.text('Team computer'), findsOneWidget);+ await tester.enterText(find.byKey(const ValueKey('models-search')), '');+ app.localReadFails = true;+ await controller.refresh();+ await tester.pump();+ expect(find.text('Models are unavailable. Try again.'), findsOneWidget);+ expect(+ tester+ .widget<IconButton>(+ find.byKey(const ValueKey('model-action-gemma')),+ )+ .onPressed,+ isNull,+ );+ app.localReadFails = false;+ await tester.tap(find.text('Try again'));+ await tester.pump();+ expect(find.text('Models are unavailable. Try again.'), findsNothing);+ await tester.tap(find.byTooltip('Close Models'));+ expect(closed, 1);+ expect(tester.takeException(), isNull);+ await tester.pumpWidget(const SizedBox());+ },+ variant: TargetPlatformVariant.only(TargetPlatform.macOS),+ );++ testWidgets('play and pause show pending status before the acknowledgement', (+ tester,+ ) async {+ tester.view.devicePixelRatio = 1;+ tester.view.physicalSize = const Size(700, 800);+ addTearDown(tester.view.reset);+ final app = ModelManagerTestApp(ModelManagerConnection());+ final controller = ModelManagerController(app, poll: false);+ final subscriptions = _SubscriptionRows();+ addTearDown(() {+ controller.dispose();+ subscriptions.dispose();+ app.dispose();+ });+ for (final running in [false, true]) {+ app.localInventory = modelInventory(+ scenario: running ? 'ready' : 'first',+ );+ await controller.refresh();+ app.actionReply = Completer<Map<String, dynamic>>();+ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(+ body: Center(+ child: SizedBox(+ width: 640,+ child: ModelsPanel(+ controller: controller,+ subscriptions: subscriptions,+ onClose: () {},+ onManage: () {},+ ),+ ),+ ),+ ),+ ),+ );+ final control = find.byKey(const ValueKey('model-action-qwen'));+ expect(+ find.descendant(+ of: control,+ matching: find.byIcon(running ? LucideIcons.pause : LucideIcons.play),+ ),+ findsOneWidget,+ );+ expect(tester.getSize(control), const Size(40, 40));+ expect(+ find.byTooltip(+ running+ ? 'Pause Qwen3.8-27B and free memory. The download is kept.'+ : 'Start Qwen3.8-27B',+ ),+ findsOneWidget,+ );+ await tester.tap(control);+ await tester.pump();+ expect(find.text(running ? 'Stopping' : 'Starting'), findsOneWidget);+ expect(control, findsNothing);+ expect(find.byType(CircularProgressIndicator), findsOneWidget);+ expect(+ tester+ .widget<IconButton>(+ find.byKey(const ValueKey('model-action-gemma')),+ )+ .onPressed,+ isNull,+ );+ app.actionReply!.complete({'error': 'Operation refused'});+ await tester.pump();+ expect(app.actions.last.start, !running);+ }+ app.localInventory = modelInventory(scenario: 'ready');+ for (final seconds in [60, 65]) {+ (app.localInventory['models'] as List).first['windowSeconds'] = seconds;+ await controller.refresh();+ await tester.pump();+ expect(+ find.text(+ '16.2 GB · 17.6 tok/s · 42 requests / ${seconds == 60 ? '1m' : '65s'}',+ ),+ findsOneWidget,+ );+ }+ (app.localInventory['models'] as List).first['requests'] = 1;+ await controller.refresh();+ await tester.pump();+ expect(find.text('16.2 GB · 17.6 tok/s · 1 request / 65s'), findsOneWidget);+ await tester.pumpWidget(const SizedBox());+ });++ testWidgets(+ 'the one-time invitation leads to discovery and verified readiness explains selection',+ (tester) async {+ final app = ModelManagerTestApp(ModelManagerConnection());+ app.stateOf('m')!.agents = [+ const Agent(id: 'work', name: 'Work', engine: 'codex'),+ ];+ final controller = ModelManagerController(app, poll: false);+ addTearDown(() {+ controller.dispose();+ app.dispose();+ });+ controller.start();+ await controller.prepare();+ await controller.refresh();+ var opens = 0;+ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(+ body: LocalModelInvitation(+ controller: controller,+ onOpen: () => opens++,+ ),+ ),+ ),+ );+ expect(find.text('Run AI on this computer'), findsOneWidget);+ await tester.tap(find.text('Explore models'));+ expect(opens, 1);+ await tester.tap(find.byTooltip('Dismiss'));+ await tester.pump();+ expect(find.text('Run AI on this computer'), findsNothing);+ app.localInventory = modelInventory(scenario: 'ready');+ await controller.refresh();+ await tester.pump();+ expect(find.text('Qwen3.8-27B is running'), findsOneWidget);+ expect(+ find.text('Select it from the model picker in a session.'),+ findsOneWidget,+ );+ await tester.tap(find.byTooltip('Dismiss'));+ await tester.pump();+ expect(find.text('Qwen3.8-27B is running'), findsNothing);+ expect(app.sent, isEmpty);+ await tester.pump(const Duration(milliseconds: 100));+ await tester.pumpWidget(const SizedBox());+ },+ );++ for (final brightness in [Brightness.dark, Brightness.light]) {+ for (final scenario in [+ 'first',+ 'downloading',+ 'ready',+ 'error',+ 'narrow',+ ]) {+ testWidgets('Models $scenario in ${brightness.name}', (tester) async {+ final narrow = scenario == 'narrow';+ tester.view.devicePixelRatio = 1;+ tester.view.physicalSize = narrow+ ? const Size(360, 500)+ : const Size(700, 780);+ addTearDown(tester.view.reset);+ final previous = grid.AppTheme.brightness.value;+ grid.AppTheme.brightness.value = brightness;+ addTearDown(() => grid.AppTheme.brightness.value = previous);+ final app = ModelManagerTestApp(ModelManagerConnection());+ final controller = ModelManagerController(app, poll: false);+ final usage = UsageController(+ sources: [_Subscription()],+ autoStart: false,+ );+ final subscriptions = ModelsMenuController(usage: usage);+ addTearDown(() {+ controller.dispose();+ subscriptions.dispose();+ usage.dispose();+ app.dispose();+ });+ await subscriptions.refresh();+ app.localInventory = modelInventory(scenario: scenario);+ await controller.refresh();+ var manages = 0, closes = 0;+ final boundary = GlobalKey();+ await tester.pumpWidget(+ RepaintBoundary(+ key: boundary,+ child: MaterialApp(+ debugShowCheckedModeBanner: false,+ theme: grid.buildAppTheme(brightness: brightness),+ builder: (context, child) => MediaQuery(+ data: MediaQuery.of(context)+ .copyWith(textScaler: TextScaler.linear(narrow ? 1.7 : 1)),+ child: child!,+ ),+ home: Scaffold(+ body: Center(+ child: Padding(+ padding: const EdgeInsets.all(14),+ child: SizedBox(+ width: 640,+ child: ModelsPanel(+ controller: controller,+ subscriptions: subscriptions,+ onClose: () => closes++,+ onManage: () => manages++,+ ),+ ),+ ),+ ),+ ),+ ),+ ),+ );+ await tester.runAsync(() async {+ for (final asset in [+ 'assets/model-icons/qwen.png',+ 'assets/model-icons/gemma.png',+ 'assets/model-icons/openai.png',+ ]) {+ await precacheImage(+ AssetImage(asset),+ tester.element(find.byType(ModelsPanel)),+ );+ }+ });+ await tester.pump(const Duration(milliseconds: 300));+ expect(tester.takeException(), isNull);+ expect(find.text('Models'), findsOneWidget);+ expect(find.text('Chat'), findsNothing);+ expect(find.text('Use'), findsNothing);+ expect(find.widgetWithText(TextButton, 'Start'), findsNothing);+ expect(find.widgetWithText(TextButton, 'Stop'), findsNothing);+ expect(find.text('Set up local model'), findsNothing);+ expect(find.textContaining('Downloaded'), findsNothing);+ expect(find.textContaining('Running ·'), findsNothing);+ if (scenario == 'downloading') {+ expect(find.text('Downloading · 42%'), findsOneWidget);+ expect(+ tester+ .widget<LinearProgressIndicator>(+ find.byType(LinearProgressIndicator).first,+ )+ .value,+ .42,+ );+ }+ if (scenario == 'ready') {+ expect(find.byIcon(LucideIcons.pause), findsOneWidget);+ expect(+ find.text('16.2 GB · 17.6 tok/s · 42 requests / 24h'),+ findsOneWidget,+ );+ }+ if (scenario == 'error') {+ expect(+ find.text('The download stopped. Start again to resume.'),+ findsOneWidget,+ );+ }+ final output = Platform.environment['HARNESS_MODELS_CAPTURE_DIR'];+ if (output != null) {+ 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 Directory(output).create(recursive: true);+ await File('$output/${brightness.name}-$scenario.png')+ .writeAsBytes(bytes!.buffer.asUint8List());+ image.dispose();+ });+ }+ if (scenario == 'first') {+ await tester.tap(find.byKey(const ValueKey('model-action-qwen')));+ await tester.pump();+ expect(app.actions.single.start, isTrue);+ expect(app.sent, isEmpty);+ expect(app.panes, isEmpty);+ expect(closes, 0);+ await tester.enterText(+ find.byKey(const ValueKey('models-search')),+ 'gpt',+ );+ await tester.pump();+ expect(find.text('gpt-oss-20b'), findsOneWidget);+ expect(find.text('Qwen3.8-27B'), findsNothing);+ }+ if (scenario == 'ready') {+ await tester.tap(find.text('Running 1'));+ await tester.pump();+ expect(find.text('Qwen3.8-27B'), findsOneWidget);+ expect(find.text('gemma-4-12B'), findsNothing);+ }+ await tester.tap(find.text('Model Manager'));+ expect(manages, 1);+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);+ await tester.pump();+ expect(closes, 1);+ await tester.pumpWidget(const SizedBox());+ });+ }+ }++ testWidgets('Models opens beside the monitor and preserves the workspace', (+ tester,+ ) async {+ tester.view.devicePixelRatio = 1;+ tester.view.physicalSize = const Size(1200, 760);+ addTearDown(tester.view.reset);+ final previous = grid.AppTheme.brightness.value;+ grid.AppTheme.brightness.value = Brightness.dark;+ addTearDown(() => grid.AppTheme.brightness.value = previous);+ final app = ModelManagerTestApp(ModelManagerConnection());+ app.stateOf('m')!.localEndpoint = LocalCliEndpoint(+ computerId: 'preview-computer',+ wsUri: Uri.parse('ws://fixture.invalid'),+ protocolVersion: 1,+ terminalProtocolVersion: 3,+ );+ app.stateOf('m')!.agents = [+ const Agent(id: 'work', name: 'Build the next thing', engine: 'codex'),+ ];+ final session = terminal('work', [])..agentName = 'Build the next thing';+ session.terminal.write(+ ' Ready when you are.\r\n\r\n'+ ' Ask me to build, fix, or explore something.\r\n',+ );+ app.adoptSessionForTest(session);+ app.renameSwarm(app.activeSwarmId, 'My project');+ final projects = SwarmProjectStore();+ final usage = UsageController(sources: [_Subscription()], autoStart: false);+ final subscriptions = ModelsMenuController(usage: usage);+ addTearDown(() {+ subscriptions.dispose();+ usage.dispose();+ projects.dispose();+ app.dispose();+ });+ final boundary = GlobalKey();+ await tester.pumpWidget(+ RepaintBoundary(+ key: boundary,+ child: MaterialApp(+ debugShowCheckedModeBanner: false,+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ home: SwarmScreen(+ notifier: app,+ nativeTabs: false,+ projectStore: projects,+ modelsMenu: subscriptions,+ ),+ ),+ ),+ );+ final tab = app.activeSwarmId;+ final panes = app.panes.map((pane) => pane.id).toList();+ final button = find.byKey(const ValueKey('swarm-models-button'));+ await tester.tap(button);+ await tester.pump();+ await tester.runAsync(() async {+ for (final asset in [+ 'assets/engine-icons/codex.png',+ 'assets/harnesses.png',+ 'assets/models.png',+ 'assets/model-icons/qwen.png',+ 'assets/model-icons/gemma.png',+ 'assets/model-icons/openai.png',+ 'assets/store/polymath.png',+ ]) {+ await precacheImage(+ AssetImage(asset),+ tester.element(find.byType(ModelsPanel)),+ );+ }+ });+ await tester.pump(const Duration(milliseconds: 300));+ final panel = tester.getRect(find.byType(ModelsPanel));+ expect(panel.right, 1190);+ expect(panel.top, greaterThan(tester.getRect(button).bottom));+ expect(panel.width, 640);+ expect(+ tester.getRect(find.byTooltip('Harness Monitor')).right,+ lessThan(tester.getRect(button).left),+ );+ expect(find.byType(Dialog), findsNothing);+ expect(find.text('Run AI on this computer'), findsNothing);+ expect(app.activeSwarmId, tab);+ expect(app.panes.map((pane) => pane.id), panes);+ expect(tester.takeException(), isNull);++ final output = Platform.environment['HARNESS_MODELS_CAPTURE_DIR'];+ if (output != null) {+ 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/workspace.png')+ .writeAsBytes(bytes!.buffer.asUint8List());+ image.dispose();+ });+ }+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);+ await tester.pump();+ expect(find.byType(ModelsPanel), findsNothing);+ await tester.tap(button);+ await tester.pump();+ await tester.tapAt(const Offset(50, 400));+ await tester.pump();+ expect(find.byType(ModelsPanel), findsNothing);+ expect(app.activeSwarmId, tab);+ expect(app.panes.map((pane) => pane.id), panes);+ await tester.pumpWidget(const SizedBox());+ });+}diff --git a/desktop/test/support/model_manager.dart b/desktop/test/support/model_manager.dartnew file mode 100644index 000000000..09af2bd53--- /dev/null+++ b/desktop/test/support/model_manager.dart@@ -0,0 +1,270 @@+import 'dart:async';++import 'package:harness/auth/auth_session.dart';+import 'package:harness/core/config.dart';+import 'package:harness/core/dsh_catalog.dart';+import 'package:harness/core/models.dart';+import 'package:harness/core/project_folder.dart';+import 'package:harness/state/app_state.dart';+import 'package:harness/ws/ws_conn.dart';++class ModelManagerConnection extends WsConn {+ ModelManagerConnection()+ : super(+ wsBaseUrl: 'ws://fixture.invalid',+ autonomousEnv: 'test',+ machineId: 'm',+ accessTokenProvider: (_, _) async => '',+ onAuthFailure: (_) {},+ onEvent: (_) {},+ onStatus: (_) {},+ );+ final creations = <Map<String, dynamic>>[];+ Completer<void>? holdCreation;+ bool loseFirstReply = false;+ String? creationError;++ @override+ Future<Map<String, dynamic>> request(+ String type, {+ Map<String, dynamic> payload = const {},+ Duration timeout = const Duration(seconds: 20),+ }) async {+ if (type == 'agent_create' || type == 'agent_create_status') {+ if (type == 'agent_create') creations.add(Map.of(payload));+ await holdCreation?.future;+ if (creationError != null) {+ return {+ 'creationId': payload['creationId'],+ 'state': 'failed',+ 'failure': {'code': 'LAUNCH_FAILED', 'detail': creationError},+ };+ }+ if (type == 'agent_create' && loseFirstReply) {+ loseFirstReply = false;+ throw const WsRequestTimeout('agent_create');+ }+ final choice = creations.last;+ return {+ 'state': 'created',+ 'creationId': payload['creationId'],+ 'agent': {+ 'id': choice['dsh'] == null ? 'local-session' : 'manager',+ 'name': choice['name'],+ 'engine': 'codex',+ 'dsh': choice['dsh'],+ 'terminal': {'available': true},+ },+ };+ }+ return {};+ }+}++class ModelManagerTestApp extends AppNotifier {+ ModelManagerTestApp(this.connection)+ : super(+ config: AppConfig.dev,+ authSession: AuthSession(),+ configStore: null,+ connectionForTest: (_) => connection,+ ) {+ hasNavigationRail = false;+ const local = Machine(+ machineId: 'm',+ authMode: MachineAuthMode.remote,+ name: 'This Mac',+ );+ const remote = Machine(+ machineId: 'other',+ authMode: MachineAuthMode.remote,+ name: 'Other computer',+ );+ machines = [local, remote];+ machineStates['m'] = MachineState(local)+ ..localOnly = true+ ..connectionStatus = ConnectionStatus.connected+ ..agentLoadStatus = AgentLoadStatus.loaded;+ machineStates['other'] = MachineState(remote)+ ..agentLoadStatus = AgentLoadStatus.loaded;+ }+ final ModelManagerConnection connection;+ bool installed = true;+ String? installError, probeError, resumeError;+ bool resumeThrows = false;+ int localReads = 0, resumes = 0;+ Completer<Map<String, dynamic>>? localReply;+ Completer<void>? probeReply;+ String? sendError;+ int installs = 0;+ GridModels inventory = const GridModels(gridName: 'home', models: []);+ final sent = <({String id, String machine, String task})>[];++ Map<String, dynamic> localInventory = modelInventory();+ final actions = <({String machine, String model, bool start})>[];+ bool localReadFails = false, actionReplyLost = false;+ Completer<Map<String, dynamic>>? actionReply;+ @override+ Future<Map<String, dynamic>> localModels(+ String machineId, {+ bool refresh = false,+ }) async {+ localReads++;+ final held = localReply;+ if (held != null) {+ localReply = null;+ return held.future;+ }+ if (localReadFails) throw StateError('offline');+ return localInventory;+ }++ @override+ Future<Map<String, dynamic>> controlLocalModel(+ String machineId,+ String modelId, {+ required bool start,+ }) async {+ actions.add((machine: machineId, model: modelId, start: start));+ if (actionReply != null) return actionReply!.future;+ final operation = <String, dynamic>{+ 'id': 'operation',+ 'modelId': modelId,+ 'action': start ? 'start' : 'stop',+ 'stage': start ? 'downloading' : 'stopping',+ 'phase': 'running',+ if (start) 'progress': .42,+ };+ localInventory = {+ ...localInventory,+ 'busy': true,+ 'models': [+ for (final raw in localInventory['models'] as List)+ if (raw['id'] == modelId)+ {...raw as Map<String, dynamic>, 'operation': operation}+ else+ raw,+ ],+ };+ if (actionReplyLost) throw StateError('lost acknowledgement');+ return {'operation': operation};+ }++ @override+ Future<String> prepareLocalProjectFolder(+ ProjectFolderRequest request, {+ String label = 'harness',+ }) async => '/fixture/$label';+ @override+ Future<void> probeDsh(String machineId, {bool force = false}) async {+ await probeReply?.future;+ if (probeError != null) throw StateError(probeError!);+ stateOf(machineId)!.dsh.replace([+ DshEntry(+ id: AppNotifier.gridHarness,+ name: 'Model Manager',+ engine: 'codex',+ description: '',+ installed: installed,+ ),+ ]);+ }++ @override+ Future<String?> installDsh(String machineId, String harness) async {+ installs++;+ if (installError != null) return installError;+ installed = true;+ return null;+ }++ @override+ Future<GridModels> gridModels(String machineId) async => inventory;+ @override+ Future<RestartAgentResult> resumeAgent(+ String machineId,+ String agentId,+ ) async {+ resumes++;+ if (resumeThrows) throw StateError('resume unavailable');+ return RestartAgentResult(error: resumeError);+ }++ @override+ Future<String?> sendRoutedTask(+ String agentId,+ String agentMachineId,+ String text,+ ) async {+ sent.add((id: agentId, machine: agentMachineId, task: text));+ return sendError;+ }+}++Map<String, dynamic> modelInventory({String scenario = 'first'}) {+ final running = scenario == 'ready';+ return {+ 'memoryBytes': 64 * 1024 * 1024 * 1024,+ 'hardware': 'Apple M2 Max',+ 'busy': scenario == 'downloading',+ 'models': [+ {+ 'id': 'qwen',+ 'name': 'Qwen3.8-27B',+ 'state': running ? 'running' : 'available',+ 'sizeBytes': 16.2 * 1024 * 1024 * 1024,+ 'canStart': !running,+ 'canStop': running,+ 'recommended': true,+ if (running) ...{+ 'tokensPerSecond': 17.6,+ 'requests': 42,+ 'windowSeconds': 86400,+ },+ if (scenario == 'downloading' || running || scenario == 'error')+ 'operation': {+ 'id': 'operation',+ 'modelId': 'qwen',+ 'action': 'start',+ 'stage': running ? 'verifying' : 'downloading',+ 'phase': running+ ? 'done'+ : scenario == 'error'+ ? 'failed'+ : 'running',+ if (scenario == 'downloading') 'progress': .42,+ if (scenario == 'error')+ 'error': 'The download stopped. Start again to resume.',+ },+ },+ {+ 'id': 'gemma',+ 'name': 'gemma-4-12B',+ 'state': 'downloaded',+ 'sizeBytes': 7.3 * 1024 * 1024 * 1024,+ 'canStart': true,+ },+ {+ 'id': 'qwen-small',+ 'name': 'Qwen3.8-8B',+ 'state': 'available',+ 'sizeBytes': 4.8 * 1024 * 1024 * 1024,+ 'canStart': true,+ },+ {+ 'id': 'qwen-coder',+ 'name': 'Qwen3-Coder-30B-A3B',+ 'state': 'available',+ 'sizeBytes': 18.6 * 1024 * 1024 * 1024,+ 'canStart': true,+ },+ {+ 'id': 'gpt-oss',+ 'name': 'gpt-oss-20b',+ 'state': 'available',+ 'sizeBytes': 12.1 * 1024 * 1024 * 1024,+ 'canStart': true,+ },+ ],+ };+}diff --git a/desktop/test/swarm_screen_test.dart b/desktop/test/swarm_screen_test.dartindex 927035c51..d1d54fcab 100644--- a/desktop/test/swarm_screen_test.dart+++ b/desktop/test/swarm_screen_test.dart@@ -549,7 +549,7 @@ void main() {find.byKey(const ValueKey('harness-start-search')),findsOneWidget,);- expect(find.text('Models'), findsNothing);+ expect(find.byKey(const ValueKey('swarm-models-button')), findsOneWidget);expect(find.text('Machines'), findsNothing);await chord(tester, LogicalKeyboardKey.keyO);await tester.pump();diff --git a/desktop/tool/models_review.dart b/desktop/tool/models_review.dartnew file mode 100644index 000000000..c0aece5df--- /dev/null+++ b/desktop/tool/models_review.dart@@ -0,0 +1,340 @@+// Interactive native review of the real Models UI, with isolated model responses.+// FLUTTER_TEST=1 flutter run -d macos -t tool/models_review.dart+// F6 theme, F7 connection failure, F8 fail next download, F9 large text.+// No model files, credentials, production daemons, or live sessions are used.+import 'dart:async';++import 'package:flutter/foundation.dart';+import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:harness/core/models.dart';+import 'package:harness/core/test_run.dart';+import 'package:harness/screens/swarm_screen.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/terminal/terminal_session.dart';+import 'package:harness/usage/models_menu_controller.dart';+import 'package:harness/ws/local_cli_discovery.dart';+import 'package:window_manager/window_manager.dart';++import '../test/support/model_manager.dart';++class ReviewSubscriptions extends ModelsMenuController {+ @override+ List<Map<String, Object?>> get rows => const [+ {+ 'title': 'OpenAI',+ 'account': 'aabbcc',+ 'status': '76% remaining',+ 'remainingPercent': 76.0,+ 'iconAsset': 'assets/engine-icons/codex.png',+ },+ {'title': 'Anthropic', 'status': 'Usage unavailable'},+ ];+ @override+ Future<void> refresh() async {}+}++class ReviewApp extends ModelManagerTestApp {+ ReviewApp() : super(ModelManagerConnection());+ bool failNextDownload = false;+ int serial = 0;+ final timers = <Timer>[];++ void publish(String id, Map<String, dynamic> fields, {required bool busy}) {+ localInventory = {+ ...localInventory,+ 'busy': busy,+ 'models': [+ for (final raw in localInventory['models'] as List)+ if (raw['id'] == id)+ {...raw as Map<String, dynamic>, ...fields}+ else+ raw,+ ],+ };+ unawaited(modelManager.refresh());+ }++ @override+ Future<Map<String, dynamic>> controlLocalModel(+ String machineId,+ String modelId, {+ required bool start,+ }) async {+ final rows = (localInventory['models'] as List)+ .cast<Map<String, dynamic>>();+ final current = rows.firstWhere((r) => r['id'] == modelId);+ final other = rows+ .where((r) => r['state'] == 'running' && r['id'] != modelId)+ .firstOrNull;+ final operation = <String, dynamic>{+ 'id': 'review-${++serial}',+ 'modelId': modelId,+ 'action': start ? 'start' : 'stop',+ 'phase': 'running',+ 'stage': start ? 'checking' : 'stopping',+ };+ publish(modelId, {+ 'operation': {...operation},+ }, busy: true);+ void later(int seconds, void Function() action) =>+ timers.add(Timer(Duration(seconds: seconds), action));+ if (start && other != null) {+ later(+ 1,+ () => publish(modelId, {+ 'operation': {+ ...operation,+ 'phase': 'failed',+ 'error':+ 'Stop ${other['name']} first to start another local model.',+ },+ }, busy: false),+ );+ } else if (!start) {+ later(+ 2,+ () => publish(modelId, {+ 'state': 'downloaded',+ 'canStop': false,+ 'canStart': true,+ 'operation': {...operation, 'phase': 'done'},+ }, busy: false),+ );+ } else {+ final shouldFail = failNextDownload;+ failNextDownload = false;+ final downloaded = current['state'] == 'downloaded';+ if (!downloaded) {+ later(+ 1,+ () => publish(modelId, {+ 'operation': {+ ...operation,+ 'stage': 'downloading',+ 'progress': .42,+ },+ }, busy: true),+ );+ }+ if (shouldFail) {+ later(+ 3,+ () => publish(modelId, {+ 'operation': {+ ...operation,+ 'phase': 'failed',+ 'stage': 'downloading',+ 'error': 'The download stopped. Start again to resume.',+ },+ }, busy: false),+ );+ } else {+ later(+ downloaded ? 1 : 4,+ () => publish(modelId, {+ 'operation': {...operation, 'stage': 'starting'},+ }, busy: true),+ );+ later(+ downloaded ? 3 : 6,+ () => publish(modelId, {+ 'operation': {...operation, 'stage': 'verifying'},+ }, busy: true),+ );+ later(+ downloaded ? 5 : 8,+ () => publish(modelId, {+ 'state': 'running',+ 'canStart': false,+ 'canStop': true,+ 'tokensPerSecond': 17.6,+ 'requests': 1,+ 'windowSeconds': 86400,+ 'operation': {...operation, 'stage': 'verifying', 'phase': 'done'},+ }, busy: false),+ );+ }+ }+ return {+ 'operation': {...operation},+ };+ }++ @override+ Future<GridModels> gridModels(String machineId) async => GridModels(+ gridName: 'home',+ models: [+ for (final raw in localInventory['models'] as List)+ if (raw['state'] == 'running')+ GridModel(+ id: raw['name'] as String,+ node: 'This computer',+ grid: 'home',+ ),+ ],+ gridCli: GridCli.managed,+ grids: [+ GridSection(+ name: 'home',+ own: true,+ models: [+ for (final raw in localInventory['models'] as List)+ if (raw['state'] == 'running')+ GridModel(+ id: raw['name'] as String,+ node: 'This computer',+ grid: 'home',+ ),+ ],+ ),+ const GridSection(+ name: 'Team',+ own: false,+ models: [+ GridModel(+ id: 'Team coding model',+ node: 'Shared computer',+ grid: 'Team',+ ),+ ],+ ),+ ],+ );++ void choose(String? model) {+ stateOf('m')!.agents = [+ for (final agent in stateOf('m')!.agents)+ if (agent.id == 'work')+ Agent(+ id: 'work',+ name: 'Write a README',+ engine: 'codex',+ terminalAvailable: true,+ gridModel: model,+ )+ else+ agent,+ ];+ activeTerminal?.terminal.write('\r\n Selected ${model ?? 'OpenAI'}.\r\n');+ notifyListeners();+ }++ @override+ Future<void> retargetAgentToGridModel(+ String machineId,+ String agentId,+ String modelId, {+ String? gridName,+ }) async => choose(modelId);+ @override+ Future<void> clearAgentGrid(String machineId, String agentId) async =>+ choose(null);+ @override+ void dispose() {+ for (final timer in timers) {+ timer.cancel();+ }+ super.dispose();+ }+}++Future<void> main() async {+ if (!kUnderTest) {+ throw StateError('Launch this isolated review with FLUTTER_TEST=1.');+ }+ // FLUTTER_TEST defaults Flutter's platform to Android. Keep the native Mac+ // editing shortcuts in this guarded interactive test.+ debugDefaultTargetPlatformOverride = TargetPlatform.macOS;+ WidgetsFlutterBinding.ensureInitialized();+ await windowManager.ensureInitialized();+ await const MethodChannel('harness/swarm_tabs').invokeMethod('configure', {+ 'palette': grid.AppTheme.palette.value.nativeColors,+ });+ await windowManager.setSize(const Size(1200, 800));+ await windowManager.setTitle('Models user test');+ final app = ReviewApp();+ app.stateOf('m')!.localEndpoint = LocalCliEndpoint(+ computerId: 'review-computer',+ wsUri: Uri.parse('ws://fixture.invalid'),+ protocolVersion: 1,+ terminalProtocolVersion: 3,+ );+ app.stateOf('m')!.agents = [+ const Agent(+ id: 'work',+ name: 'Write a README',+ engine: 'codex',+ terminalAvailable: true,+ ),+ ];+ final session =+ TerminalSession(+ machineId: 'm',+ agentId: 'work',+ agentName: 'Write a README',+ engineId: 'codex',+ send: (_, _) async => true,+ sendBinary: (_) async => true,+ )+ ..status = TerminalSessionStatus.controlling+ ..streamId = 'review-stream';+ session.terminal.write(+ ' Write a concise README for a notes app.\r\n\r\n This is an isolated UI review. Model responses are fixtures.\r\n',+ );+ // This guarded entry point is an interactive test, with no real session.+ // ignore: invalid_use_of_visible_for_testing_member+ app.adoptSessionForTest(session);+ app.renameSwarm(app.activeSwarmId, 'Models user test');+ final subscriptions = ReviewSubscriptions();+ runApp(ReviewHost(app: app, subscriptions: subscriptions));+ app.modelManager.start();+ await windowManager.show();+ await windowManager.focus();+}++class ReviewHost extends StatefulWidget {+ const ReviewHost({super.key, required this.app, required this.subscriptions});+ final ReviewApp app;+ final ReviewSubscriptions subscriptions;+ @override+ State<ReviewHost> createState() => _ReviewHostState();+}++class _ReviewHostState extends State<ReviewHost> {+ bool large = false;+ @override+ Widget build(BuildContext context) => ValueListenableBuilder(+ valueListenable: grid.AppTheme.brightness,+ builder: (context, brightness, _) => MaterialApp(+ debugShowCheckedModeBanner: false,+ theme: grid.buildAppTheme(brightness: brightness),+ builder: (context, child) => CallbackShortcuts(+ bindings: {+ const SingleActivator(LogicalKeyboardKey.f6): () =>+ grid.AppTheme.brightness.value = brightness == Brightness.dark+ ? Brightness.light+ : Brightness.dark,+ const SingleActivator(LogicalKeyboardKey.f7): () {+ widget.app.localReadFails = !widget.app.localReadFails;+ unawaited(widget.app.modelManager.refresh());+ },+ const SingleActivator(LogicalKeyboardKey.f8): () =>+ widget.app.failNextDownload = true,+ const SingleActivator(LogicalKeyboardKey.f9): () =>+ setState(() => large = !large),+ },+ child: MediaQuery(+ data: MediaQuery.of(context)+ .copyWith(textScaler: TextScaler.linear(large ? 1.7 : 1)),+ child: child!,+ ),+ ),+ home: SwarmScreen(+ notifier: widget.app,+ nativeTabs: true,+ modelsMenu: widget.subscriptions,+ ),+ ),+ );+}diff --git a/docs/plans/2026-09-23-001-model-discovery.md b/docs/plans/2026-09-23-001-model-discovery.mdnew file mode 100644index 000000000..7967dd166--- /dev/null+++ b/docs/plans/2026-09-23-001-model-discovery.md@@ -0,0 +1,47 @@+# Models: discover, start, select++A single violet brain opens the Models popover beside Harness Monitor. It silently checks this computer and lists all+compatible chat models from Grid's paginated hardware-fit catalog, including supported multimodal+chat models. One fitted version per model keeps the list simple. A completed fitting download is+preferred to another download; an existing locally managed deployment remains restartable after Pause.++The interface follows Harness Monitor: search, All / Running filters, plain rows,+and a second line for size and live metrics. Each model uses its own logo, with the brain as a+fallback. Typography, search, filter chips, and icon controls use the same scale as Harness Monitor.+Play/pause tooltips explain the memory and download behavior. Running models come first, then downloaded models,+then compatible choices. A useful smaller download leads the available choices. There is no hidden+model list, setup card, Chat button, or Use action.++- **Play** checks the machine again, downloads if necessary, installs the existing Grid engine,+ loads the model, and tests a real reply. Progress stays on its row. Repeated clicks join the+ same operation; the panel and conversation do not own its lifetime.+- **Pause** unloads the exact Grid-managed local engine and keeps the download. External endpoints+ and other computers are not stopped by these controls.+- **Select** a running model in an existing session's visible model picker. Starting a model never+ creates a session, sends a conversation message, or changes the current session's model.+- **Model Manager** remains a quiet advanced link. Its stable Grid package ID is unchanged; the+ package is bundled and a local manager is prepared without moving the workspace. Setup no+ longer depends on a seeded chat task or an LLM account.++Rows show size in GB without download or state labels. Running models also show observed decode+throughput and completed requests over Grid's actual reporting window where those+metrics can be attributed to the model. Machine memory is labelled at the machine level. No engine+or system memory figure is presented as a model's RAM footprint, and absent telemetry stays absent.++The daemon exposes encrypted inventory/start/stop RPCs over the existing connection. It keeps+atomic operation receipts, serialized machine mutations, and imported-model metadata. A lost reply+is reconciled through status, never automatically replayed. Restarted daemons mark unfinished+operations interrupted; they do not silently resubmit a deployment. Grid owns downloads, engine+installation, process identity checks, and inference. Credentials stay in the daemon's memory and+Grid's existing credential store, not in RPC replies, operation files, or logs.++The pinned Grid runtime restarts its engine union when a built-in model is added. The simple Start+flow therefore asks to stop the current local model first, before downloading another. Existing+shared-runtime setups go through Model Manager for changes that could interrupt sibling engines.+The UI does not imply that all individually compatible models can be loaded simultaneously.++Discovery caches machine-fit results for five minutes, refreshes live state while the popover is+open or an operation is active, and polls only once a minute otherwise. The session picker remains the explicit handoff to the first local response.++Validation is recorded in [the test report](../testing/local-models-2026-09-23.md), including+coverage boundaries, native click-through findings, baseline failures, and reproduction commands.diff --git a/docs/testing/local-models-2026-09-23.md b/docs/testing/local-models-2026-09-23.mdnew file mode 100644index 000000000..2eba97fcd--- /dev/null+++ b/docs/testing/local-models-2026-09-23.md@@ -0,0 +1,143 @@+# Local models validation — 2026-09-23++Tested on macOS with Flutter 3.47.2 and Node 22.23.1. Base: `b5edd10a`.++## Monitor styling follow-up++Models now uses Harness Monitor's panel width, type scale, search and filter styling,+unboxed 22 px row marks, and 40 px play/pause controls. A single brain identifies Models in+both toolbars and the introduction. Model rows and the session picker use provider artwork,+with the brain as the fallback. Idle rows show only size in GB; running rows add available+throughput and request counts. All / Running filters remain. Play retains the existing+download/start operation; pause unloads the model and keeps its download.+Accessible action names and tooltips describe those effects; active operations replace+the control with a spinner and keep their progress in the row.++The focused panel/controller/picker suite passed 97 tests (one existing skip).+Model modules retain 100% executable line coverage: panel 335/335, mark 17/17,+controller 254/254, and lifecycle values 43/43. Changed Dart files analyze cleanly,+and the macOS review build passes. Updated captures cover first run, downloading,+running, errors, both themes, and a 360 px window at 1.7× text. Native computer-use+retesting verified the brain entry, branded rows, size-only idle copy, running telemetry,+play/pause, All / Running, and search/clear. The broader journeys below were also exercised+on the original implementation.++## Automated checks++| Check | Result |+| --- | --- |+| Full CLI suite | 4,218 passed, 63 skipped |+| Local-model lifecycle, bundled installer, Grid subprocess gate | 100 passed |+| New CLI lifecycle + installer coverage | 277/277 lines; 393/393 statements; 344/344 branches; 75/75 functions |+| Focused Flutter marks, controller, popover, picker, native menu, terminal presentation | 97 passed, 1 existing skip |+| New Flutter model modules | 649/649 executable lines |+| Full desktop suite | 2,981 passed, 12 skipped, 17 baseline failures |+| Model Manager operation/viewer tests | 43 passed |+| CLI typecheck and release bundle | Passed |+| Bundled installation, manifest check, repeated installation | Passed in a fresh temporary DSH directory |+| macOS debug build | Passed |+| Static analysis | No new findings; 15 existing findings elsewhere |++The CLI coverage gate covers `cli/src/lib/localModels.ts` and `cli/src/dsh/builtins.ts`.+Flutter coverage covers `local_model.dart` (43/43), `model_manager_controller.dart` (254/254),+`models_panel.dart` (335/335), and `model_mark.dart` (17/17). These are scope-specific measurements, not 100% repository+coverage or a claim that every hardware/model combination has been exercised.++The subprocess integration test uses the real process runner, a temporary Grid executable,+a local HTTP catalog/inference server, durable receipts, and an actual downloaded fixture file.+It exercises discovery → download → start → verified response → stop → restart, confirming+that restarting keeps the file and does not download again. Other regressions cover pagination,+partial files, disk/memory pressure, engine ownership, shared runtimes, failed starts and stops,+stale inventory, concurrent clicks, dropped acknowledgements, account changes, interrupted+operations, credential redaction, and encrypted RPC routing.++## Native user testing++Clicked the actual Flutter/macOS interface with computer use. Model operations used controlled+responses in `desktop/tool/models_review.dart`; this did not download or stop real models.++| Journey | Observed result |+| --- | --- |+| Toolbar Models icon and native Models → Open Models | Anchored popover; workspace stays in place |+| First-run Explore models | Opens the same list; invitation dismissed after discovery |+| All / Running | Correct counts, rows, and empty states |+| Search, no results, clear search | Filters immediately; one click restores the list |+| Start a missing model | Checking/download/start/test progress followed by Running |+| Start a downloaded model | Reaches Running without another download |+| Close and reopen during setup | Operation finishes; completed state survives panel closure |+| Start while another model runs | Clear instruction to stop the existing model |+| Pause | Progress, then size-only idle row; file remains available |+| Interrupted download and Start again | Recoverable row error; successful retry clears it |+| Unavailable inventory and Try again | Actions disabled; reconnection restores them |+| Session OpenAI → local model → OpenAI | Header and selected row follow the explicit choice |+| Models ↔ Harness Monitor | One popover at a time |+| Model Manager from another tab | Existing manager tab reused, including while attaching |+| Tab, Enter, Escape | Filters can be selected and the popover dismissed with the keyboard |+| Light/dark, 1.7× text, smaller window, scrolling | Actions and footer remain reachable |++Native testing caught and fixed duplicate Model Manager tabs, the truncated discovery link,+missing search clearing, the lingering first-run prompt, and singular request-count copy.+Regression work also fixed stale operation status, disconnected actions, the immediate Stop+label, shared-model picker refresh, and narrow pane-header overflow.++Command+A was verified by a macOS widget regression. The computer-use key injection did not+deliver the Command modifier to Flutter, so that native shortcut was not certified by automation.+The advanced manager's terminal stream is not simulated; native testing verifies its opening+and reuse, while package tests cover its operations and viewer.++## Existing failures and limits++All 17 desktop failures were reproduced on the unchanged base in an isolated checkout:++| Suite | Failures |+| --- | ---: |+| `workspace_account_lifecycle_test.dart` | 8 |+| `signout_recovery_test.dart` | 2 |+| `workspace_expiry_screen_test.dart` | 4 |+| `local_cli_discovery_test.dart` | 1 |+| `environment_setup_screen_test.dart` | 1 |+| `environment_recheck_timer_test.dart` | 1 |++The CLI startup test initially discovered the developer's existing tmux sessions and timed out.+It now has its own socket directory, pins the terminal backend, and disables provisioning and+hook installation. All 10 startup contracts and the subsequent full CLI suite pass.++Read-only integration on the real 64 GB Mac returned 30 compatible catalog models and the+existing Qwen deployment, with 17.6 tok/s and 1 completed request over 24 hours. Total engine+requests were not attributed to that model. Real model downloads, GPU allocation, and unloading+were not exercised on the user's machine. No live conversations or models were changed.++## Reproduce++From `cli/`:++```sh+npm run test:local-models+npm test -- --maxWorkers=2+npm run typecheck+npm run bundle+```++From `desktop/`:++```sh+flutter test --coverage test/model_mark_test.dart test/model_manager_controller_test.dart test/models_panel_test.dart test/grid_model_picker_test.dart test/models_menu_test.dart test/terminal_panel_presentation_test.dart+flutter test --concurrency=4+flutter analyze+flutter build macos --debug+FLUTTER_TEST=1 flutter run -d macos -t tool/models_review.dart+```++The review entry point refuses to run without `FLUTTER_TEST`. F6 changes its theme, F7 toggles+an inventory failure, F8 fails the next download, and F9 changes text size. All responses are+fixtures. Use a separate review app identity if another Harness build is already open.++From the repository root:++```sh+node --test store/agents/autonomous-grid/test/*.test.mjs+node cli/dist/cli.js dsh check store/agents/autonomous-grid+```++Set `HARNESS_MODELS_CAPTURE_DIR` when running `models_panel_test.dart` to regenerate the widget+PNGs. Final workspace, downloading, and running captures are in `output/visualizations/`.diff --git a/output/visualizations/models-downloading.png b/output/visualizations/models-downloading.pngnew file mode 100644index 000000000..6462a6e99Binary files /dev/null and b/output/visualizations/models-downloading.png differdiff --git a/output/visualizations/models-overview.png b/output/visualizations/models-overview.pngnew file mode 100644index 000000000..f239f3ffbBinary files /dev/null and b/output/visualizations/models-overview.png differdiff --git a/output/visualizations/models-running.png b/output/visualizations/models-running.pngnew file mode 100644index 000000000..0a9674f5eBinary files /dev/null and b/output/visualizations/models-running.png differdiff --git a/store/agents/autonomous-grid/AGENTS.md b/store/agents/autonomous-grid/AGENTS.mdindex 173271759..fe88cdf2c 100644--- a/store/agents/autonomous-grid/AGENTS.md+++ b/store/agents/autonomous-grid/AGENTS.md@@ -1,9 +1,9 @@-# Grid agent+# Model ManagerThese instructions apply in a **materialized Grid workspace** containing `grid-fleet.json`.You look after the models on the user's machines — one laptop or a whole fleet. They say what theywant to run; you find a place for it, start it with the real CLI, verify an answer, and keep the-viewer current. The feature is called **Harness Compute** (or "your fleet"): never say "grid" to+viewer current. The feature is called **Model Manager**: never say "grid" tothe user, and never hand them a command to type — everything below is something you run when theysay what they want in plain words. The one exception is `harness login`, when they are not signed in.@@ -55,8 +55,10 @@ Keep the user informed in plain language: which machine, which model, how much rwhat changed. Use real measurements; never manufacture utilization, temperatures, benchmark scores,discovered machines, or a successful deployment. Hardware data that Grid cannot report isunavailable, not zero. An API or subscription engine does not contribute its host's RAM to model-capacity. When a model is up, the hand-off is the **model picker at the top of any agent's pane**:-say so, and name the model as it appears there.+capacity. Models automatically lists compatible local models, and its Start button downloads,+loads, and tests the chosen model directly. Stop unloads it and keeps the download. This chat is+for advanced management. When you finish a deployment, name the model exactly as it appears in+the session's model picker and tell the user to select it there.Keep durable user preferences and explicitly configured machine access in `grid-fleet.json`; putplans and measured comparisons in `plans/`. Credentials belong in Grid's or SSH's existing credentialdiff --git a/store/agents/autonomous-grid/README.md b/store/agents/autonomous-grid/README.mdindex bf4fb5aa4..1f057259b 100644--- a/store/agents/autonomous-grid/README.md+++ b/store/agents/autonomous-grid/README.md@@ -1,6 +1,6 @@# Grid, as a Harness agent-Manage open-weight models across your machines by talking to Grid. The agent uses the existing+Manage open-weight models across your machines by talking to Model Manager. The agent uses the existing[Grid CLI](https://github.com/autonomous-ai/autonomous-grid), with a live fleet viewer beside it:gold connections, machine and engine details, model placement, memory, GPU temperature, power,utilization, decode estimates, recent telemetry, and operation progress. Topology and rack viewsdiff --git a/store/agents/autonomous-grid/harness.json b/store/agents/autonomous-grid/harness.jsonindex 0c3c5ebc3..ee589f2b3 100644--- a/store/agents/autonomous-grid/harness.json+++ b/store/agents/autonomous-grid/harness.json@@ -1,10 +1,10 @@{"spec": 1,"id": "autonomous/autonomous-grid",- "name": "Grid",+ "name": "Model Manager","category": "Local AI","author": "Autonomous",- "description": "Talk to your fleet. Deploy open-weight models, find the right machine for each workload, and watch your Grid come alive with a live map of engines, models, memory, temperature and performance.",+ "description": "Run your first local model. Find a model that fits your computer, start it, and use it in Harness. Manage models across your machines in one conversation.","engine": "codex","workspace": {"template": "template",@@ -13,7 +13,9 @@},"agent": {"instructions": "AGENTS.md",- "skills": ["skills"],+ "skills": [+ "skills"+ ],"env": {"GRID_CLI": "${dsh}/toolchain/grid.sh","GRID_FLEET": "${dsh}/toolchain/fleet",diff --git a/store/agents/autonomous-grid/lib/fleet.mjs b/store/agents/autonomous-grid/lib/fleet.mjsindex a276da9ab..a3ce29152 100644--- a/store/agents/autonomous-grid/lib/fleet.mjs+++ b/store/agents/autonomous-grid/lib/fleet.mjs@@ -74,7 +74,7 @@ export function invocation(machine, args, env = process.env, thinking) {return { file: 'ssh', args: [...argv, machine.host, remote], env: childEnv };}-export function execute(machine, args, { timeoutMs = 15_000, inherit = false, env = process.env, signal, thinking } = {}) {+export function execute(machine, args, { timeoutMs = 15_000, inherit = false, env = process.env, signal, thinking, onOutput } = {}) {if (thinking !== undefined && typeof thinking !== 'boolean') throw new Error('Thinking must be a boolean.');if (machine.transport === 'harness') {if (!Array.isArray(args) || args.some(a => typeof a !== 'string' || a.includes('\0'))) throw new Error('Grid arguments must be strings without NUL bytes.');@@ -95,13 +95,17 @@ export function execute(machine, args, { timeoutMs = 15_000, inherit = false, enkillTimer = setTimeout(() => { child.kill('SIGKILL'); finish({ ok: false, code: 124, error: message }); }, 1500);};const abort = () => stop('Grid command was interrupted; verify the engine state before retrying.');- try { child = spawn(call.file, call.args, { env: call.env, stdio: inherit ? 'inherit' : ['ignore', 'pipe', 'pipe'] }); }+ try { child = spawn(call.file, call.args, { env: call.env, stdio: inherit && !onOutput ? 'inherit' : ['ignore', 'pipe', 'pipe'] }); }catch (error) { finish({ ok: false, code: 127, error: error.message }); return; }let stopping = false;const capture = which => chunk => {if (stopping) return;if (stdout.length + stderr.length + chunk.length > 4 * 1024 * 1024) { stopping = true; stop('Grid output exceeded 4 MiB.'); return; }if (which === 'out') stdout += chunk; else stderr += chunk;+ if (onOutput) {+ onOutput(chunk);+ if (inherit) (which === 'out' ? process.stdout : process.stderr).write(chunk);+ }};child.stdout?.setEncoding('utf8').on('data', capture('out'));child.stderr?.setEncoding('utf8').on('data', capture('err'));@@ -204,18 +208,54 @@ export async function operations(workspace) {});}+// Only the public status receipt goes through the app's existing project-file+// reader. Internal state and endpoint credentials stay hidden under .harness.+export async function publishSetup(workspace, record) {+ const file = join(stateDir(workspace), 'setup.json');+ const current = await readJson(file, null).catch(() => null);+ if (current?.id !== record.id && current?.startedAt > record.startedAt) return;+ if (record.stage === 'checking' && current?.stage !== 'checking' &&+ ['running', 'done'].includes(current?.phase)) return;+ const updatedAt = now();+ await atomicJson(file, { spec: 1, ...record, updatedAt });+ const { id, stage, phase, model, grid, progressPercent } = record;+ await atomicJson(join(workspace, 'model-setup.json'), {+ spec: 1, id, stage, phase, model, grid, progressPercent, updatedAt,+ });+}+export async function runTracked(workspace, machine, mode, args, options = {}) {const command = args.find(a => !a.startsWith('-')) || 'overview';const op = { id: randomUUID(), machine: machine.id, command: `grid ${text(command, 40)}`, phase: 'running', startedAt: now(), endedAt: null, exitCode: null, pid: process.pid };const file = join(stateDir(workspace), 'operations', `${op.id}.json`);- await atomicJson(file, op);+ const stage = command === 'pull' ? 'downloading' : command === 'join' || (command === 'engine' && args.includes('install')) ? 'starting' : ['device-info', 'catalog', 'ctx'].includes(command) ? 'checking' : null;+ let pending = Promise.resolve(), lastProgress = 0, outputTail = '';+ const publish = () => {+ const snapshot = { ...op };+ pending = pending.then(async () => {+ await atomicJson(file, snapshot);+ if (stage) await publishSetup(workspace, { ...snapshot, stage });+ });+ return pending;+ };+ await publish();+ const heartbeat = setInterval(() => { void publish().catch(() => {}); }, 5000);+ heartbeat.unref();try {- const result = await execute(machine, [`--${mode}`, ...args], { inherit: true, timeoutMs: 30 * 60_000, ...options });+ const result = await execute(machine, [`--${mode}`, ...args], { inherit: true, timeoutMs: 30 * 60_000, ...options,+ ...(stage === 'downloading' && machine.transport !== 'harness' ? { onOutput(chunk) {+ outputTail = (outputTail + chunk).slice(-1024);+ const match = [...outputTail.matchAll(/(?:^|[\s(])([0-9]+(?:\.[0-9]+)?)%/g)].at(-1);+ if (match) op.progressPercent = Math.min(100, Number(match[1]));+ if (match && Date.now() - lastProgress > 500) { lastProgress = Date.now(); void publish().catch(() => {}); }+ } } : {}),+ });Object.assign(op, { phase: result.ok ? 'done' : result.code === 124 ? 'interrupted' : 'failed', endedAt: now(), exitCode: result.code });- await atomicJson(file, op);+ await publish();return result;} catch (error) {- await atomicJson(file, { ...op, phase: 'failed', endedAt: now(), exitCode: 1 });+ Object.assign(op, { phase: 'failed', endedAt: now(), exitCode: 1 });+ await publish();throw error;- }+ } finally { clearInterval(heartbeat); }}diff --git a/store/agents/autonomous-grid/lib/verify.mjs b/store/agents/autonomous-grid/lib/verify.mjsnew file mode 100644index 000000000..d6ab8b40c--- /dev/null+++ b/store/agents/autonomous-grid/lib/verify.mjs@@ -0,0 +1,49 @@+import { randomUUID } from 'node:crypto';+import { join } from 'node:path';+import { atomicJson, execute, now, publishSetup, stateDir } from './fleet.mjs';++/** The same bounded OpenAI-compatible request the manager already performs,+ * with a durable receipt the Models panel can read. Credentials stay in memory. */+export async function verifyModel(workspace, machine, mode, grid, model, { run = execute, request = fetch } = {}) {+ if (!grid || !model || [grid, model].some(v => typeof v !== 'string' || v.startsWith('-') || /[\x00-\x1f]/.test(v))) throw new Error('A grid and model name are required.');+ const record = { spec: 1, id: randomUUID(), stage: 'verifying', phase: 'running', model, grid, command: 'Verify model', machine: machine.id, startedAt: now(), updatedAt: now(), pid: process.pid };+ let pending = Promise.resolve();+ const publish = () => {+ const snapshot = { ...record, updatedAt: now() };+ pending = pending.then(async () => {+ await atomicJson(join(stateDir(workspace), 'operations', `${record.id}.json`), snapshot);+ await publishSetup(workspace, snapshot);+ });+ return pending;+ };+ await publish();+ const heartbeat = setInterval(() => { void publish().catch(() => {}); }, 5000);+ heartbeat.unref();+ try {+ const info = await run(machine, [`--${mode}`, 'info', grid, '--env']);+ if (!info.ok) throw new Error('Could not read the model endpoint. Check Model Manager and retry.');+ const values = {};+ for (const match of info.stdout.matchAll(/^export\s+(OPENAI_BASE_URL|OPENAI_API_KEY)=(.*)$/gm)) {+ const value = match[2].trim();+ values[match[1]] = value.length >= 2 && ['"', "'"].includes(value[0]) && value.at(-1) === value[0] ? value.slice(1, -1) : value;+ }+ if (!values.OPENAI_BASE_URL || !values.OPENAI_API_KEY) throw new Error('The model endpoint is not ready yet.');+ const response = await request(`${values.OPENAI_BASE_URL.replace(/\/$/, '')}/chat/completions`, {+ method: 'POST', headers: { authorization: `Bearer ${values.OPENAI_API_KEY}`, 'content-type': 'application/json' },+ body: JSON.stringify({ model, messages: [{ role: 'user', content: 'Reply with the single word: ok' }], max_tokens: 8 }),+ signal: AbortSignal.timeout(420_000),+ });+ if (!response.ok) throw new Error(`The model did not answer successfully (HTTP ${response.status}).`);+ const answer = await response.json();+ if (!/^\s*ok[.!]?\s*$/i.test(answer?.choices?.[0]?.message?.content ?? '')) throw new Error('The model did not complete the test reply. Ask Model Manager to check it.');+ record.phase = 'done';+ await publish();+ return { ok: true, model };+ } catch (error) {+ record.phase = 'failed';+ await publish();+ // No raw response bodies, endpoint credentials or arbitrary network errors.+ throw new Error(error.name === 'TimeoutError' ? 'The model did not answer in time. Ask Model Manager to check it.' :+ /^(Could not read|The model|The model endpoint)/.test(error.message) ? error.message : 'The model check was interrupted. Ask Model Manager to retry.');+ } finally { clearInterval(heartbeat); }+}diff --git a/store/agents/autonomous-grid/skills/grid-operations/SKILL.md b/store/agents/autonomous-grid/skills/grid-operations/SKILL.mdindex 5aa2d611e..75d37bcb0 100644--- a/store/agents/autonomous-grid/skills/grid-operations/SKILL.md+++ b/store/agents/autonomous-grid/skills/grid-operations/SKILL.md@@ -73,6 +73,27 @@ input; Harness transport is noninteractive, so sign-in prompts belong in that mathe default execution machine. Model files and `join`/`leave` operations belong on the machinethat runs the engine; listing, routing and requests can run on the controller.+## First local model: help from this conversation++The Models panel normally handles discovery and Start/Stop directly. If the user asks this+conversation to help set up a local model, begin inspecting+this computer immediately. This is the short onboarding path: coding and everyday work, one+person, a responsive first reply, and enough free memory for other apps. Prefer a suitable+model already running or downloaded. Inspect device-info and the live catalog, choose one+comfortable fit, and explain the download size and memory needs in plain words. Offer+**Start this model** and **Other options** through the question tool. That single choice+covers installing the required engine and downloading/starting the recommended model.+Choose context from the model's measured fit and the session's needs. Do not ask the user to+choose an engine, quantization, token count, concurrency, or vision setting. Use suitable+existing defaults; extra questions belong to explicit advanced requests. Keep setup on this+computer. Other machines are available when the user asks for them.++Use the tracked fleet runner for hardware checks, downloads, and startup, so the viewer retains+progress while the conversation is closed or interrupted. After the model appears in discovery,+run `"$GRID_FLEET" verify --grid GRID --model MODEL_ALIAS` once. This bounded check records+readiness only after a real reply. On failure, report the problem and offer recovery. On success,+say **"Your model is running. Select it from the model picker in a session."** The setup ends at a usable model.+## Start a modelSlow steps are a real stop: a download or an engine build is asked about through the question tool@@ -173,9 +194,7 @@ for the relay to list it (a call before that answers `No providers available foris "not yet", not "broken"):until "$GRID_FLEET" run -- models GRID 2>/dev/null | grep -qx 'MODEL_ALIAS'; do sleep 10; done- eval "$("$GRID_FLEET" run -- info GRID --env)" && curl -s --max-time 420 "$OPENAI_BASE_URL/chat/completions" \- -H "Authorization: Bearer $OPENAI_API_KEY" -H 'content-type: application/json' \- -d '{"model":"MODEL_ALIAS","messages":[{"role":"user","content":"Reply with the single word: ok"}],"max_tokens":8}'+ "$GRID_FLEET" verify --grid GRID --model MODEL_ALIAS⚠️ Not `chat` for this check. `chat` sets no output limit and the engine's default is tens ofthousands of tokens, so a small model that runs away answering "ok" holds the slot for minutes — and@@ -192,8 +211,8 @@ one step larger from the same list (tiny models loop), or more requests at once,not acceptance. Then `"$GRID_FLEET" refresh`.**7. Say where it is.** "<alias> is running on <machine>, N at a time, vision on/off. Pick it from-the model dropdown at the top of any agent's pane, and that agent switches to it." The window's-Models menu only lists Local models; it does not switch. Don't offer to wire it into an agent's+the model dropdown at the top of any agent's pane, and that agent switches to it." In the Models+panel, **Use** returns to the person's session or opens one when needed. Don't offer to wire it into an agent'sconfig or add a provider — the picker is the whole hand-off.## Change a running modeldiff --git a/store/agents/autonomous-grid/test/setup.test.mjs b/store/agents/autonomous-grid/test/setup.test.mjsnew file mode 100644index 000000000..6a81625cc--- /dev/null+++ b/store/agents/autonomous-grid/test/setup.test.mjs@@ -0,0 +1,60 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { publishSetup, runTracked } from '../lib/fleet.mjs';+import { verifyModel } from '../lib/verify.mjs';++const temporary = async t => { const dir = await mkdtemp(join(tmpdir(), 'model-setup-')); t.after(() => rm(dir, { recursive: true, force: true })); return dir; };+const receipt = async dir => JSON.parse(await readFile(join(dir, 'model-setup.json'), 'utf8'));+const machine = { id: 'local', transport: 'local' };+const run = async () => ({ ok: true, stdout: "export OPENAI_BASE_URL='http://fixture.invalid/v1'\nexport OPENAI_API_KEY='private-secret'\n" });++test('downloading publishes measured progress to a readable, credential-free project file', async t => {+ const dir = await temporary(t), grid = join(dir, 'grid');+ await writeFile(grid, '#!/bin/sh\necho "(42.5%)"\nexit 0\n', { mode: 0o755 });+ await runTracked(dir, { ...machine, gridBinary: grid }, 'local', ['pull', 'model'], { inherit: false });+ assert.deepEqual({ ...(await receipt(dir)), id: null, updatedAt: null }, {+ spec: 1, id: null, updatedAt: null, stage: 'downloading', phase: 'done', progressPercent: 42.5,+ });+});++test('ready requires a completed content reply; HTTP success and reasoning alone are insufficient', async t => {+ const dir = await temporary(t);+ for (const answer of [{ choices: [] }, { choices: [{ message: { reasoning_content: 'ok' } }] }]) {+ await assert.rejects(verifyModel(dir, machine, 'local', 'home', 'qwen', {+ run, request: async () => ({ ok: true, json: async () => answer }),+ }), /did not complete/);+ assert.equal((await receipt(dir)).phase, 'failed');+ }+ const result = await verifyModel(dir, machine, 'local', 'home', 'qwen', {+ run, request: async (url, options) => {+ assert.equal(url, 'http://fixture.invalid/v1/chat/completions');+ assert.equal(JSON.parse(options.body).max_tokens, 8);+ assert.equal((await receipt(dir)).phase, 'running');+ return { ok: true, json: async () => ({ choices: [{ message: { content: 'ok' } }] }) };+ },+ });+ assert.equal(result.ok, true);+ assert.equal((await receipt(dir)).phase, 'done');+ assert.equal((await receipt(dir)).stage, 'verifying');+ assert.doesNotMatch(JSON.stringify(await receipt(dir)), /private-secret|fixture.invalid|pid|command/);+});++test('a failed request leaves recoverable status and never persists network secrets', async t => {+ const dir = await temporary(t);+ await assert.rejects(verifyModel(dir, machine, 'local', 'home', 'qwen', {+ run, request: async () => { throw new Error('private-secret'); },+ }), /check was interrupted/);+ assert.equal((await receipt(dir)).phase, 'failed');+ assert.doesNotMatch(JSON.stringify(await receipt(dir)), /private-secret/);+});++test('a later inspection or old operation cannot erase readiness', async t => {+ const dir = await temporary(t);+ await publishSetup(dir, { id: 'ready', startedAt: '2026-09-23T10:00:00Z', stage: 'verifying', phase: 'done', model: 'qwen' });+ await publishSetup(dir, { id: 'check', startedAt: '2026-09-23T11:00:00Z', stage: 'checking', phase: 'running' });+ await publishSetup(dir, { id: 'old-download', startedAt: '2026-09-23T09:00:00Z', stage: 'downloading', phase: 'done' });+ assert.equal((await receipt(dir)).id, 'ready');+});diff --git a/store/agents/autonomous-grid/toolchain/fleet.mjs b/store/agents/autonomous-grid/toolchain/fleet.mjsindex 22e9c3a11..e5c6e1b01 100644--- a/store/agents/autonomous-grid/toolchain/fleet.mjs+++ b/store/agents/autonomous-grid/toolchain/fleet.mjs@@ -1,4 +1,5 @@#!/usr/bin/env node+import { verifyModel } from '../lib/verify.mjs';import { join, resolve } from 'node:path';import { atomicJson, DEFAULT_CONFIG, execute, readConfig, runTracked } from '../lib/fleet.mjs';import { createCollector } from '../lib/telemetry.mjs';@@ -50,6 +51,15 @@ try {process.exitCode = snapshot.status === 'unavailable' ? 1 : 0;} else if (command === 'config') {console.log(JSON.stringify(await readConfig(workspace), null, 2));+ } else if (command === 'verify') {+ const flags = new Map();+ for (let i = 0; i < args.length; i += 2) {+ if (!['--grid', '--model'].includes(args[i]) || !args[i + 1] || flags.has(args[i])) throw new Error('Use: fleet verify --grid NAME --model MODEL');+ flags.set(args[i], args[i + 1]);+ }+ const config = await readConfig(workspace);+ const machine = config.machines.find(m => m.id === config.controller);+ console.log(JSON.stringify(await verifyModel(workspace, machine, config.mode, flags.get('--grid') || config.grid, flags.get('--model'))));} else if (command === 'run') {const boundary = args.indexOf('--');if (boundary < 0 || boundary === args.length - 1) throw new Error('Use: fleet run [--machine ID] -- <grid arguments>');@@ -77,6 +87,8 @@ try {fleet connect --mode MODE --grid NAME [--remember]Select a reachable grid; optionally reuse it in new workspacesfleet status [--json] Read the viewer's observations without network access+ fleet verify --grid NAME --model MODEL+ Verify a first reply and publish readiness to Modelsfleet doctor Check Grid and Nodefleet discover [--add] Discover your Harness machinesfleet config Validate and print fleet inventorydiff --git a/store/agents/autonomous-grid/viewer.mjs b/store/agents/autonomous-grid/viewer.mjsindex 06ca76d5e..94d939081 100644--- a/store/agents/autonomous-grid/viewer.mjs+++ b/store/agents/autonomous-grid/viewer.mjs@@ -49,7 +49,7 @@ export function createViewer({ workspace, port = 0, intervalMs = 8000, collect =try { await selectGrid(grid); json(res, 200, { ok: true, grid }); } catch (err) { json(res, 409, { error: err.message }); }return;}- if (!['GET', 'HEAD'].includes(req.method)) { res.setHeader('allow', 'GET, HEAD, POST'); json(res, 405, { error: 'This viewer is read-only. Talk to the Grid agent to make changes.' }); return; }+ if (!['GET', 'HEAD'].includes(req.method)) { res.setHeader('allow', 'GET, HEAD, POST'); json(res, 405, { error: 'This viewer is read-only. Talk to the Model Manager to make changes.' }); return; }if (url.pathname === '/health') { json(res, 200, { ok: true }); return; }if (url.pathname === '/api/snapshot') { json(res, 200, snapshot); wake(); return; }if (url.pathname === '/events') {diff --git a/store/agents/autonomous-grid/viewer/app.js b/store/agents/autonomous-grid/viewer/app.jsindex 71c4c33e4..cc71b739d 100644--- a/store/agents/autonomous-grid/viewer/app.js+++ b/store/agents/autonomous-grid/viewer/app.js@@ -54,7 +54,7 @@$('map-subtitle').textContent=snapshot.nodes.length>12?`12 of ${snapshot.nodes.length} engines · see every engine in Rack`:'Every machine has a place.';$('map-empty').hidden=graphNodes.length>0;$('hub').hidden=graphNodes.length===0;- $('empty-message').textContent=snapshot.status==='unconfigured'?'Ask the Grid agent to connect one of your existing grids, or help you create your first fleet.':snapshot.status==='unavailable'?'Grid isn’t reachable yet. Ask the agent to check your connection, choose a grid, or start one.':'Ask the Grid agent to discover this machine and deploy your first model.';+ $('empty-message').textContent=snapshot.status==='unconfigured'?'Ask the Model Manager to connect one of your existing grids, or help you create your first fleet.':snapshot.status==='unavailable'?'Grid isn’t reachable yet. Ask the agent to check your connection, choose a grid, or start one.':'Ask the Model Manager to discover this machine and deploy your first model.';$('hub-status').textContent=available?`${snapshot.summary.enginesOnline || 0} engines online`:'awaiting connection';const ids=new Set(graphNodes.map(n=>n.id));for (const [id,b] of nodeButtons) if (!ids.has(id)) { b.remove();nodeButtons.delete(id); }@@ -90,7 +90,7 @@}const pair=(label,value)=>`<div class="detail-pair"><span>${escape(label)}</span><strong>${escape(value)}</strong></div>`;const detailMetric=(label,value,unit,hint='')=>`<div class="detail-metric"><span class="label">${escape(label)}</span><span class="value">${fmt(value)} <small>${escape(unit)}</small></span>${hint?`<span class="hint">${escape(hint)}</span>`:''}</div>`;- function prompt(text) {return `<div class="ask-prompt"><span>ASK YOUR GRID AGENT</span><p>${escape(text)}</p><button class="copy-prompt" type="button" data-prompt="${escape(text)}">Copy request ↗</button></div>`;}+ function prompt(text) {return `<div class="ask-prompt"><span>ASK YOUR MODEL MANAGER</span><p>${escape(text)}</p><button class="copy-prompt" type="button" data-prompt="${escape(text)}">Copy request ↗</button></div>`;}function gpuDetails(g) {const used=finite(g.memoryUsedGb)&&g.memoryGb>0?Math.max(0,Math.min(100,g.memoryUsedGb/g.memoryGb*100)):0;return `<div class="gpu-detail"><div class="model-entry"><span class="model-glyph">▧</span><span class="model-title">${escape(g.name)}<span class="model-caption">${fmt(g.memoryUsedGb)} / ${fmt(g.memoryGb)} GB used</span></span></div><div class="memory-track"><span style="width:${used}%"></span></div><div class="memory-labels"><span>${fmt(g.utilizationPct)}% load</span><span>${fmt(g.temperatureC)} °C · ${fmt(g.powerW)} W</span></div></div>`;@@ -275,7 +275,7 @@document.addEventListener('click',async event=>{const close=event.target.closest('[data-close]'),selection=event.target.closest('[data-select]'),copy=event.target.closest('[data-prompt]');if(close){selected=null;render();}else if(selection)select(selection.dataset.select);- else if(copy){try{await navigator.clipboard.writeText(copy.dataset.prompt);toast('Request copied. Paste it into your Grid agent.');}catch{toast('Select the request text and paste it into your Grid agent.');}}+ else if(copy){try{await navigator.clipboard.writeText(copy.dataset.prompt);toast('Request copied. Paste it into your Model Manager.');}catch{toast('Select the request text and paste it into your Model Manager.');}}});new ResizeObserver(()=>resize()).observe(stage);const stream=new EventSource('events');diff --git a/store/agents/autonomous-grid/viewer/index.html b/store/agents/autonomous-grid/viewer/index.htmlindex e4e1aee75..564ea4485 100644--- a/store/agents/autonomous-grid/viewer/index.html+++ b/store/agents/autonomous-grid/viewer/index.html@@ -4,7 +4,7 @@<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="color-scheme" content="dark">- <title>Grid · Your AI fleet</title>+ <title>Model Manager</title><link rel="stylesheet" href="app.css"><script src="app.js" defer></script></head>@@ -21,7 +21,7 @@<div class="map-heading"><span class="eyebrow">YOUR COMPUTE, CONNECTED</span><span class="map-subtitle" id="map-subtitle">Every machine has a place.</span></div><div class="node-layer" id="nodes" aria-label="Grid engines"></div><button class="hub" id="hub" type="button" aria-label="Inspect your grid"><span class="hub-kicker">THE NETWORK</span><span class="hub-name">your grid</span><span class="hub-status" id="hub-status">connecting</span></button>- <div class="map-empty" id="map-empty" hidden><span class="empty-orbit" aria-hidden="true">◎</span><h1>Your fleet starts here.</h1><p id="empty-message">Ask the Grid agent to discover this machine and connect your first model.</p></div>+ <div class="map-empty" id="map-empty" hidden><span class="empty-orbit" aria-hidden="true">◎</span><h1>Your fleet starts here.</h1><p id="empty-message">Ask the Model Manager to discover this machine and connect your first model.</p></div><div class="map-controls"><span id="map-legend">Links show Grid membership</span><button type="button" id="motion" aria-pressed="false">Pause motion</button></div></div><section class="rack scrolls" id="rack" aria-label="Engine rack" hidden></section>