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
Swarm local models: run and stop for a Swarm on a new account, and show changes sooner
bitcoinbuilder7d548ef653fd
diff --git a/backend/src/superTabs/machines.test.ts b/backend/src/superTabs/machines.test.tsindex 78230d511..f128699e0 100644--- a/backend/src/superTabs/machines.test.ts+++ b/backend/src/superTabs/machines.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest'import { createSuperTab, SuperTabError, type AgentStart, type AgentStartRequest, type SuperTabState } from './model.js'-import { admitMachineStart, machineSlots, machineObservationSchema, type ContributedMachine } from './machines.js'+import { admitMachineStart, machineSlots, machineObservationSchema, servedLocalModels, type ContributedMachine } from './machines.js'const NOW = 1_000_000const requirements = { memoryBytes: 1, diskBytes: 1, maxCpuPercent: 50, tools: ['git'], devices: [], quotaRequired: false }@@ -13,6 +13,21 @@ it('accepts optional tool probe failures while preserving older observations', (expect(machineObservationSchema.safeParse({ ...sent, tools: { git: true }, toolProbeErrors: { flutter: 'interactive shell timed out' } }).success).toBe(true)})+it('takes a model that is starting, and never counts it as served for a Builder', () => {+ const { receivedAt: _receivedAt, ...sent } = observation+ const model = { grid: 'swarm-0123456789ab', model: 'qwen3', kind: 'local' as const }+ expect(machineObservationSchema.safeParse({ ...sent, localModels: [{ ...model, starting: true }] }).success).toBe(true)+ const state: SuperTabState = createSuperTab('tab', 'Team', { id: 'owner', email: '[email protected]' }, 'test')+ state.localModels = { grid: model.grid, enabled: true }+ const pool = (starting: boolean) => [{ machineId: 'host', name: 'Mac', contributorId: 'owner', membershipGeneration: 'tab', generation: 'g1',+ cwd: '/x', scope: 'swarm' as const, engines: ['claude'], maxAgents: 2, paused: false,+ observation: { ...observation, localModels: [{ ...model, ...(starting ? { starting } : {}) }] } }]+ state.machines = pool(true) as never+ expect(servedLocalModels(state, NOW)).toEqual([])+ state.machines = pool(false) as never+ expect(servedLocalModels(state, NOW).map(l => l.model)).toEqual(['qwen3'])+})+it('accepts the served models Builders are not offered, with why', () => {const { receivedAt: _receivedAt, ...sent } = observationconst refused = { grid: 'swarm-0123456789ab', model: 'llama3.2:3b', name: 'llama3.2:3b', why: 'llama3.2:3b is too small for a coding agent.' }diff --git a/backend/src/superTabs/machines.ts b/backend/src/superTabs/machines.tsindex 2414b2102..7f3baf598 100644--- a/backend/src/superTabs/machines.ts+++ b/backend/src/superTabs/machines.ts@@ -81,7 +81,9 @@ export const machineObservationSchema = z.object({ generation: z.string().max(16* on this machine, since only its sign-in reaches that grid. */localModels: z.array(z.object({ grid: z.string().min(1).max(160), model: z.string().min(1).max(200),name: z.string().max(200).optional(), contextWindow: z.number().int().positive().nullable().optional(),- kind: z.enum(['local', 'api', 'shared']).optional() }).strict()).max(64).optional(),+ kind: z.enum(['local', 'api', 'shared']).optional(),+ /** Started or shared on this machine, not yet listed by the grid: shown as starting, never offered to a Builder. */+ starting: z.boolean().optional() }).strict()).max(64).optional(),/** Models this machine serves on the Swarm's grid that Builders are not offered, too small or too slow to drive a coding* agent (cli/src/lib/codingModel.ts), with why: so the route can tell a Lead asked for one why it is not offered. */refusedModels: z.array(z.object({ grid: z.string().min(1).max(160), model: z.string().min(1).max(200),@@ -375,7 +377,7 @@ export function servedLocalModels(state: SuperTabState, now: number) {const grid = state.localModels?.enabled ? state.localModels.grid : nullif (!grid) return []return (state.machines ?? []).flatMap(m => !m.observation || now - m.observation.receivedAt > MACHINE_FRESH_MS ? []- : (m.observation.localModels ?? []).filter(l => l.grid === grid).map(l => ({ ...l, machineId: m.machineId })))+ : (m.observation.localModels ?? []).filter(l => l.grid === grid && !l.starting).map(l => ({ ...l, machineId: m.machineId })))}/** Whether a start names a model it may run on now: one the Swarm's grid serves, from any machine; or one on another grid@@ -387,7 +389,7 @@ export function localModelAllowed(state: SuperTabState, request: AgentStartRequeif (request.gridName === grid) return servedLocalModels(state, now).some(l => l.model === request.gridModel)const pool = (state.machines ?? []).find(m => m.machineId === request.machineId)return !!pool?.observation && now - pool.observation.receivedAt <= MACHINE_FRESH_MS- && (pool.observation.localModels ?? []).some(l => l.grid === request.gridName && l.model === request.gridModel)+ && (pool.observation.localModels ?? []).some(l => l.grid === request.gridName && l.model === request.gridModel && !l.starting)}/** `teamMachines`: the tab's machines whose account row is signed in as a team account, read by the store. A start isdiff --git a/cli/src/lib/localModels.spec.ts b/cli/src/lib/localModels.spec.tsindex 4ff7366d1..1ae353937 100644--- a/cli/src/lib/localModels.spec.ts+++ b/cli/src/lib/localModels.spec.ts@@ -698,6 +698,21 @@ describe('local model discovery and lifecycle', () => {expect(JSON.stringify(snapshot)).not.toContain('private detail')})+ // 2026-10-26: a new account's own grid is made only when something needs it, while its Swarm's grid was ready. Read+ // as "could not be checked", every Start went dark, Run for Swarm too.+ it('an own grid this account does not have yet runs nothing: every model can start, and nothing is wrong', async () => {+ const original = run.getMockImplementation()!+ run.mockImplementation(async (args, output) => args.includes('ls')+ ? ok([{ grid: 'swarm-0123456789ab', id: 'grid-swarm' }]) : original(args, output))+ inventory.mockImplementation(async () => ({ state: 'unknown', nodes: [], status: null }))+ const snapshot = await service.list('home', true)+ expect(snapshot.notice).toBeUndefined()+ expect(snapshot.models[0]).toMatchObject({ canStart: true })+ // A grid list that did not answer a list says nothing about the grid: still unchecked.+ run.mockImplementation(async (args, output) => args.includes('ls') ? ok({ error: 'signed out' }) : original(args, output))+ expect((await service.list('home', true)).notice).toContain('Running models could not be checked')+ })+it.each(['stopped', 'asleep'] as const)('Start brings a %s grid up before joining it', async state => {gridState = stateawait service.act('home', 'org/Small-GGUF', 'start'); await service.settled()@@ -872,6 +887,24 @@ describe('local model discovery and lifecycle', () => {expect(calls.some(args => args.includes('leave'))).toBe(false)})+ it('stops a model beside the APIs a Swarm shares, which run nothing here, and not beside another engine', async () => {+ await service.act('home', 'org/Small-GGUF', 'start'); await service.settled()+ const record = JSON.parse(await readFile(join(records, 'remote.json'), 'utf8'))+ const share = { endpoint_url: `http://127.0.0.1:41001/${'a'.repeat(36)}/v1`, models: ['deepseek/x'] }+ await writeFile(join(records, 'remote.json'), JSON.stringify({ ...record, engines: [...record.engines, share] }))+ await service.act('home', 'org/Small-GGUF', 'stop'); await service.settled()+ expect((await service.list('home')).models[0].operation?.error ?? '').not.toContain('share its engine')+ expect(calls.some(args => args.includes('leave'))).toBe(true)+ // An engine that is not a share's endpoint still is one.+ await service.act('home', 'org/Small-GGUF', 'start'); await service.settled()+ const again = JSON.parse(await readFile(join(records, 'remote.json'), 'utf8'))+ await writeFile(join(records, 'remote.json'), JSON.stringify({ ...again, engines: [...again.engines, { endpoint_url: 'http://127.0.0.1:41003/v1', models: ['y'] }] }))+ calls.length = 0+ 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()diff --git a/cli/src/lib/localModels.ts b/cli/src/lib/localModels.tsindex 5a708c82b..35f7e0925 100644--- a/cli/src/lib/localModels.ts+++ b/cli/src/lib/localModels.ts@@ -576,7 +576,10 @@ export class LocalModels {const advertised = Array.isArray(named) ? named.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,- pidAlive, dead, siblings: specs.length + (record.media ? 1 : 0) })+ // An API a Swarm shares is a spec of the same engine process but runs nothing here, and a leave by this+ // file's selector leaves it serving: it is no sibling (2026-10-26: Stop for Swarm on Qwen3.6 was refused,+ // "Other models share its engine", beside a shared DeepSeek).+ pidAlive, dead, siblings: specs.filter(s => !SWARM_API_SHARE.test(str(s.endpoint_url))).length + (record.media ? 1 : 0) })if (!dead) blocker = `Stop ${cleanName(aliases[0])} first to start another local model.`}}@@ -829,9 +832,11 @@ export class LocalModels {await Promise.all([this.loadCatalog(force), this.readReceipt(grid)])let owned: Owned[] = [], nodes: Record<string, any>[] = [], inventoryError: string | undefined, asleep = false// `grid ls` once: the own grid's records, and every other grid this computer may serve on.- let grids: Record<string, any>[] = []+ let grids: Record<string, any>[] = [], listed = falseconst ownedHere = async () => {- grids = validArg(grid) ? rows(await this.json(['--remote', 'ls', '--json'])) : []+ const answer = validArg(grid) ? await this.json(['--remote', 'ls', '--json']) : null+ listed = Array.isArray(answer)+ grids = rows(answer)return this.owned(grid, grids)}try {@@ -840,7 +845,11 @@ export class LocalModels {// A grid that is down — its owner status says stopped or asleep (DOWN) — runs nothing: an answer,// not a gap, so Start stays enabled (and brings it back up). Asleep says so even to a member, in// the grid's own answer. Only a read that failed some other way is "could not be checked".- if (inventory.state === 'unknown' && !DOWN.has(inventory.status ?? '')) throw new Error('unanswered')+ // A grid this account does not have yet runs nothing either: the CLI makes the account's own grid only when+ // something needs it, and a Swarm's models run on the Swarm's grid. Read as unchecked, every Start went dark,+ // Run for Swarm too, for a new account whose Swarm grid was ready (2026-10-26). `grid ls` answered, without it.+ const missing = listed && !grids.some(row => row.grid === grid)+ if (inventory.state === 'unknown' && !DOWN.has(inventory.status ?? '') && !missing) throw new Error('unanswered')asleep = inventory.state === 'asleep' || inventory.status === 'asleep'nodes = inventory.state === 'awake' ? rows(inventory.nodes) : []} catch { inventoryError = 'Running models could not be checked. Try again.' }diff --git a/cli/src/services/models.spec.ts b/cli/src/services/models.spec.tsindex 29c852558..ca62de553 100644--- a/cli/src/services/models.spec.ts+++ b/cli/src/services/models.spec.ts@@ -734,10 +734,15 @@ describe('the models service', () => {it('a start or stop with a Swarm `grid` runs on that grid; a download, or a name that is not a Swarm grid, does not', async () => {const { ask } = setup([], named)local.act.mockClear()+ access.ensure.mockClear()await ask('grid_fleet_model_start', { modelId: 'org/Model-GGUF', grid: 'swarm-0123456789ab' })+ // The Swarm's grid is its owner's: a start there signs grid in and never makes the account's own grid+ // (2026-10-26: one at the plan's network limit failed every Run for Swarm).+ expect(access.ensure.mock.calls).toEqual([[{ ownGrid: false }]])await ask('grid_fleet_model_stop', { modelId: 'org/Model-GGUF', grid: 'swarm-0123456789ab' })await ask('grid_fleet_model_download', { modelId: 'org/Model-GGUF', grid: 'swarm-0123456789ab' })await ask('grid_fleet_model_start', { modelId: 'org/Model-GGUF', grid: 'someone-elses-grid' })+ expect(access.ensure.mock.calls.at(-1)).toEqual([{ ownGrid: true }])expect(local.act.mock.calls).toEqual([['swarm-0123456789ab', 'org/Model-GGUF', 'start'], ['swarm-0123456789ab', 'org/Model-GGUF', 'stop'],['kelvin-1a2b3c4d', 'org/Model-GGUF', 'download'], ['kelvin-1a2b3c4d', 'org/Model-GGUF', 'start'],diff --git a/cli/src/services/models.ts b/cli/src/services/models.tsindex dad70ee12..4d1e0cf1e 100644--- a/cli/src/services/models.ts+++ b/cli/src/services/models.ts@@ -303,7 +303,11 @@ function modelsRequests(core: CoreApi, grid: GridSetUp, privateGridName: () => Ptry {const list = type === 'grid_fleet_models_list'const setup = list ? payload.setup === true : type !== 'grid_fleet_model_stop'- const unready = setup ? await notReady(grid, type !== 'grid_fleet_model_download') : null+ // A start or stop for a Swarm runs on the Swarm's grid, which its owner's computer made: it needs grid signed in,+ // not the account's own grid. Asked to make that too, a Run for Swarm failed on an account at its plan's network+ // limit ("Free plan allows 5 networks") while the Swarm's grid stood ready (2026-10-26).+ const forSwarm = !list && type !== 'grid_fleet_model_download' && typeof payload.grid === 'string' && SWARM_GRID.test(payload.grid)+ const unready = setup ? await notReady(grid, type !== 'grid_fleet_model_download' && !forSwarm) : nullconst gridName = await privateGridName()if (list) {const snapshot = await localModels.list(gridName, payload.refresh === true || setup)diff --git a/cli/src/superTabs/machines.spec.ts b/cli/src/superTabs/machines.spec.tsindex 92c29ab1a..d366666e6 100644--- a/cli/src/superTabs/machines.spec.ts+++ b/cli/src/superTabs/machines.spec.ts@@ -1,17 +1,18 @@import { execFileSync } from 'node:child_process'import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'+import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'import { tmpdir } from 'node:os'import { join } from 'node:path'import { afterEach, describe, expect, it, vi } from 'vitest'import type { RegisteredSession } from '../lib/registry.js'import { fakeCore } from '../testing/fakeCore.js'-import { apisOn, ContributedMachines, liveOn, offered, refusedOn, servedOn, sharedWith, swarmWorktreesFile } from './machines.js'+import { apisOn, ContributedMachines, liveOn, localModelsStamp, offered, refusedOn, servedOn, sharedWith, swarmWorktreesFile } from './machines.js'import { SuperTabHostError } from './host.js'import { startAgent } from './start.js'import type { PrivacyObservation } from '../team/privacy.js'function fixture(env: NodeJS.ProcessEnv = {}, privacy: () => PrivacyObservation | null = () => null) {- let now = 1000+ let now = 1000, stamp = 's0'const core = fakeCore({ dataDir: '/isolated-pool-fixture', agents: {byAgent: vi.fn(id => id === 'running' ? { agentId: id } as never : undefined),stopped: vi.fn(async id => id === 'stopped'),@@ -26,8 +27,10 @@ function fixture(env: NodeJS.ProcessEnv = {}, privacy: () => PrivacyObservationconst start = vi.fn(async () => ({ ok: true }))const prepare = vi.fn(async () => {})const log = vi.fn()- const machine = new ContributedMachines(core, 'host', { backend, open, capabilities, start, prepare, log, env, privacy, now: () => now } as never)- return { machine, pool, core, backend, open, request, close, capabilities, start, prepare, log, advance: () => { now += 16000 }, step: (ms: number) => { now += ms } }+ const modelsStamp = vi.fn(async () => stamp)+ const machine = new ContributedMachines(core, 'host', { backend, open, capabilities, start, prepare, log, env, privacy, modelsStamp, now: () => now } as never)+ return { machine, pool, core, backend, open, request, close, capabilities, start, prepare, log, modelsStamp, advance: () => { now += 16000 }, step: (ms: number) => { now += ms },+ stamp: (next: string) => { stamp = next } }}describe('contributed machine executor', () => {@@ -242,7 +245,7 @@ describe('contributed machine executor', () => {f.step(60_000); await f.machine.tick()expect(reads()).toBe(before + 1)})- it('reports what it serves on the Swarm\'s grid only while the grid lists it, and everything when the grid is unread', async () => {+ it('reports what the Swarm\'s grid does not list yet as starting, and everything as it is when the grid is unread', async () => {const GRID = 'swarm-0123456789ab'const f = fixture()Object.assign(f.pool, { localGrid: GRID })@@ -253,14 +256,71 @@ describe('contributed machine executor', () => {? { shares: [{ grid: GRID, connectionId: 'c1', model: 'deepseek/deepseek-chat' }] }: type === 'grid_fleet_models_list' ? { models: [{ servedOn: [{ grid: GRID, servedAs: ['qwen3'] }] }] }: type === 'grid_swarm_heal' ? heal : { providers: [] }) as never)- const reported = async () => { f.advance(); await f.machine.tick(); return (f.backend.mock.calls.filter(c => c[1] === 'POST').at(-1)![3] as { localModels: Array<{ model: string }> }).localModels.map(m => m.model) }- expect(await reported()).toEqual(['qwen3'])+ const reported = async () => { f.advance(); await f.machine.tick()+ return (f.backend.mock.calls.filter(c => c[1] === 'POST').at(-1)![3] as { localModels: Array<{ model: string; starting?: true }> }).localModels+ .map(m => m.starting ? `${m.model} (starting)` : m.model) }+ expect(await reported()).toEqual(['qwen3', 'deepseek/deepseek-chat (starting)'])expect(local.request).toHaveBeenCalledWith('grid_swarm_heal', { grid: GRID }, 30_000)heal = { live: null, missing: [] }expect(await reported()).toEqual(['qwen3', 'deepseek/deepseek-chat'])heal = Promise.reject(new Error('older daemon'))expect(await reported()).toEqual(['qwen3', 'deepseek/deepseek-chat'])})+ // 2026-10-26: a model run for the Swarm waited for the next 15 s beat to reach the machine's panel, then for the grid.+ it('sends a reading on the next pass when its Swarm models change, and every pass while one is starting', async () => {+ const GRID = 'swarm-0123456789ab'+ const f = fixture()+ Object.assign(f.pool, { localGrid: GRID })+ await f.machine.tick()+ const local = (await f.open.mock.results[0]!.value) as { request: ReturnType<typeof vi.fn> }+ let live: string[] = []+ local.request.mockImplementation((async (type: string) => type === 'grid_fleet_models_list'+ ? { models: [{ servedOn: [{ grid: GRID, servedAs: ['qwen3'] }] }] }+ : type === 'grid_swarm_heal' ? { live, missing: [] } : { providers: [] }) as never)+ const posts = () => f.backend.mock.calls.filter(c => c[1] === 'POST').length+ const pass = async () => { f.step(6_000); await f.machine.tick() }+ await pass()+ const quiet = posts()+ await pass()+ expect(posts()).toBe(quiet)+ // A start: the engine records change, so this pass sends it, as starting, and the next ones too until it is listed.+ f.stamp('s1')+ await pass()+ expect(posts()).toBe(quiet + 1)+ expect((f.backend.mock.calls.at(-1)![3] as { localModels: unknown[] }).localModels).toEqual([{ grid: GRID, model: 'qwen3', kind: 'local', starting: true }])+ await pass()+ expect(posts()).toBe(quiet + 2)+ live = ['qwen3']+ await pass()+ expect((f.backend.mock.calls.filter(c => c[1] === 'POST').at(-1)![3] as { localModels: unknown[] }).localModels).toEqual([{ grid: GRID, model: 'qwen3', kind: 'local' }])+ const listed = posts()+ await pass()+ expect(posts()).toBe(listed)+ // A backend before `starting` refuses it, and gets what the grid lists rather than no models at all.+ const original = f.backend.getMockImplementation()!+ f.backend.mockImplementation(async (core, method, path, body) => {+ if (method === 'POST' && JSON.stringify(body).includes('"starting"')) throw new SuperTabHostError('VALIDATION_ERROR', 'Unrecognized key: starting', 400)+ return original(core, method, path, body)+ })+ live = []+ f.stamp('s2')+ await pass()+ expect((f.backend.mock.calls.at(-1)![3] as { localModels: unknown[] }).localModels).toEqual([])+ f.backend.mockImplementation(original)+ })+ it('stamps the files that change with this machine\'s Swarm models, never reading them', async () => {+ const home = await mkdtemp(join(tmpdir(), 'models-stamp-'))+ try {+ const before = await localModelsStamp(home, { GRID_HOME: join(home, 'grid') })+ await mkdir(join(home, 'grid', 'run', 'engines', 'grid-1'), { recursive: true })+ await writeFile(join(home, 'grid', 'run', 'engines', 'grid-1', 'remote.json'), '{}')+ await writeFile(join(home, 'swarm-api-shares.json'), '[]')+ const after = await localModelsStamp(home, { GRID_HOME: join(home, 'grid') })+ expect(after).not.toBe(before)+ expect(after.split(',')).toHaveLength(2)+ expect(await localModelsStamp(home, { HOME: home })).toMatch(/^\d/)+ } finally { await rm(home, { recursive: true, force: true }) }+ })it('reads the models a heal answer says are live', () => {expect(liveOn({ live: ['a', 7, 'b'] })).toEqual(new Set(['a', 'b']))expect(liveOn({ live: null })).toBeNull()diff --git a/cli/src/superTabs/machines.ts b/cli/src/superTabs/machines.tsindex ba81651c8..97216757f 100644--- a/cli/src/superTabs/machines.ts+++ b/cli/src/superTabs/machines.ts@@ -1,5 +1,5 @@import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'-import { lstat, readFile, realpath, rm } from 'node:fs/promises'+import { lstat, readdir, readFile, realpath, rm, stat } from 'node:fs/promises'import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'import type { CoreApi } from '../core/api.js'import { openDaemon } from '../agentClient/daemon.js'@@ -85,7 +85,7 @@ export class ContributedMachines {/** Per tab, when its observation was last sent and what it said that matters to a reader: the harnesses* running and stopped, whether new work is paused, and which starts are waiting. A change in any of them is* sent at once; otherwise the heartbeat keeps the reading fresh. */- private readonly published = new Map<string, { at: number; signature: string }>()+ private readonly published = new Map<string, { at: number; signature: string; starting?: boolean }>()/** Shell tool availability belongs to this machine, not a tab. Resource readings still refresh every heartbeat. */private readonly toolCache = new Map<string, { value: boolean | null; detail?: string; until: number }>()/** Per waiting start, why it was last not started, so the log says it once per reason, not every pass. */@@ -123,7 +123,9 @@ export class ContributedMachines {/** Whether this daemon runs team work only (a Harness Team account, `harness team on`): it has no git login of its own. */team?: () => boolean/** The Harness Team account's privacy check (team/privacy.ts): null for the owner's own daemon. */- privacy?: () => PrivacyObservation | null } =+ privacy?: () => PrivacyObservation | null+ /** What says this machine's Swarm models changed, read every pass without asking the daemon ([localModelsStamp]). */+ modelsStamp?: () => Promise<string> } ={ backend, open: openDaemon, capabilities: readCapabilities, start: startAgent, now: Date.now }) {}stop() { this.stopped = true }/** DESKTOP-0TFH0OJ, 2026-10-23: every Claude start there was refused (CLI 0.4.57 took an API-key Claude for one not@@ -152,6 +154,10 @@ export class ContributedMachines {for (const id of this.waiting.keys()) if (!pendingIds.has(id)) this.waiting.delete(id)for (const tab of this.published.keys()) if (!pools.some(row => row.tabId === tab)) this.published.delete(tab)const privacy = this.privacy()+ // A model run or stopped for a Swarm, or an API shared with it, is sent on this pass, not on the next beat: the+ // machine's panel waited up to 15 s more for it (2026-10-26). Files only, so a pass with nothing new asks nobody.+ const modelsStamp = pools.some(row => typeof row.localGrid === 'string')+ ? await (this.deps.modelsStamp ?? (() => localModelsStamp(this.core.dataDir, this.deps.env ?? process.env)))().catch(() => '') : ''// The local daemon is reached only for a reading to send, never for a pass that has nothing to say.let local: Awaited<ReturnType<typeof openDaemon>> | null = nulllet usage: Record<string, unknown> | null = null@@ -173,9 +179,11 @@ export class ContributedMachines {const signature = JSON.stringify([row.reservations, pool.generation, [...running].sort(), [...stopped].sort(), row.paused === true || pool.paused === true,pending.map(start => start.id).sort(),// A privacy result that changes (a home folder opened again) is sent at once, not on the next beat.- privacy ? [privacy.mode, 'passed' in privacy ? privacy.passed : null, 'item' in privacy ? privacy.item : null] : null])+ privacy ? [privacy.mode, 'passed' in privacy ? privacy.passed : null, 'item' in privacy ? privacy.item : null] : null,+ typeof row.localGrid === 'string' ? modelsStamp : null])const last = this.published.get(String(row.tabId))- if (!last || last.signature !== signature || began - last.at >= MACHINE_HEARTBEAT_MS) {+ // A model still starting is read again every pass until the grid lists it, so the panel shows it live at once.+ if (!last || last.signature !== signature || last.starting || began - last.at >= MACHINE_HEARTBEAT_MS) {local ??= await this.deps.open(where)// The existing usage reader owns its provider cache. Raw responses and// account credentials never leave this machine.@@ -214,12 +222,14 @@ export class ContributedMachines {// it again). Unknown — the grid could not be read — keeps the reading as it is.const live = typeof row.localGrid === 'string'? liveOn(await local.request('grid_swarm_heal', { grid: row.localGrid }, 30_000).catch(() => ({}))) : null- const listed = (m: LocalModelReading) => !live || live.has(m.model)+ // Not yet listed by the grid (a start or a share still registering): sent as starting, which the panel shows and+ // the route never offers, rather than left out until the grid lists it.+ const marked = (m: LocalModelReading): LocalModelReading => !live || live.has(m.model) ? m : { ...m, starting: true }const fleet = typeof row.localGrid === 'string' ? await local.request('grid_fleet_models_list', {}, 20_000).catch(() => ({})) : nullconst refusedModels = typeof row.localGrid === 'string' ? refusedOn(fleet, row.localGrid) : []const localModels = typeof row.localGrid === 'string' ? [- ...servedOn(fleet, row.localGrid).filter(listed),- ...apisOn(await local.request('grid_swarm_api_shares', { grid: row.localGrid }, 10_000).catch(() => ({})), row.localGrid).filter(listed),+ ...servedOn(fleet, row.localGrid).map(marked),+ ...apisOn(await local.request('grid_swarm_api_shares', { grid: row.localGrid }, 10_000).catch(() => ({})), row.localGrid).map(marked),...offered(sharedWith(await this.gridModels(local), row.localGrid),await local.request('grid_swarm_offers', { grid: row.localGrid }, 10_000).catch(() => ({}))),].slice(0, MAX_LOCAL_MODELS) : null@@ -247,7 +257,10 @@ export class ContributedMachines {// unverified tool, and a reading without privacy is never one a Team machine passes on.const { privacy: _privacy, ...withoutPrivacy } = observationconst { toolProbeErrors: _probeErrors, localModels: _served, refusedModels: _refused, ...legacy } = withoutPrivacy- const attempts = [observation, ...('privacy' in observation ? [withoutPrivacy] : []),+ // A backend before `starting` refuses it: it gets the models the grid lists, as before, not none at all.+ const listedOnly = localModels?.some(m => m.starting)+ ? [{ ...withoutPrivacy, localModels: localModels.filter(m => !m.starting) }] : []+ const attempts = [observation, ...('privacy' in observation ? [withoutPrivacy] : []), ...listedOnly,...('toolProbeErrors' in observation || 'localModels' in observation || 'refusedModels' in observation ? [legacy] : [])]for (const [index, attempt] of attempts.entries()) {try {@@ -258,7 +271,7 @@ export class ContributedMachines {if (attempt === observation && 'privacy' in observation) this.privacyRefusedUntil = began + PRIVACY_REFUSED_MS}}- this.published.set(String(row.tabId), { at: began, signature })+ this.published.set(String(row.tabId), { at: began, signature, starting: !!localModels?.some(m => m.starting) })} catch (error) { this.failed = true; throw error }}this.repairTrust ??= createSwarmCloneTrustRepair(this.core, this.deps.now)@@ -401,7 +414,18 @@ const GRID_MODELS_MS = 60_000/** Every Swarm's grid, as the backend mints its name: their models belong to their own Swarm. */const SWARM_GRID = /^swarm-[0-9a-f]{12}$/-type LocalModelReading = { grid: string; model: string; name?: string; contextWindow?: number; kind: 'local' | 'api' | 'shared' }+type LocalModelReading = { grid: string; model: string; name?: string; contextWindow?: number; kind: 'local' | 'api' | 'shared'; starting?: true }++/** When this machine's Swarm models last changed, from the files that change with them: the APIs it shares+ * (`swarm-api-shares.json`) and grid's engine records (`run/engines/<grid>/remote.json`, rewritten on every join and+ * leave). Their modification times, never their contents. */+export async function localModelsStamp(dataDir: string, env: NodeJS.ProcessEnv): Promise<string> {+ const engines = join(env.GRID_HOME || join(env.HOME ?? '', '.grid'), 'run', 'engines')+ const files = [join(dataDir, 'swarm-api-shares.json'),+ ...(await readdir(engines).catch(() => [] as string[])).sort().map(grid => join(engines, grid, 'remote.json'))]+ const times = await Promise.all(files.map(file => stat(file).then(s => s.mtimeMs, () => 0)))+ return times.join(',')+}/** The models a `grid_swarm_heal` answer says the Swarm's grid lists, or null when it could not say (an older daemon, or* the grid unread). */diff --git a/cli/src/superTabs/routeCommand.spec.ts b/cli/src/superTabs/routeCommand.spec.tsindex cdc7bf36d..2d3f04b47 100644--- a/cli/src/superTabs/routeCommand.spec.ts+++ b/cli/src/superTabs/routeCommand.spec.ts@@ -916,6 +916,10 @@ describe('local models on the Swarm\'s grid', () => {expect(offered(state({ starts: [start({ error: 'NO_CAPACITY' })] }))).toHaveLength(1)expect(offered(state({ starts: [{ request: { model: 'opus' } }, {}] }))).toHaveLength(1)})+ it('never offers a model that is still starting: the grid does not list it yet', () => {+ expect(offered(state({ machines: [served([{ grid: GRID, model: 'qwen3', name: 'Qwen 3', starting: true }])] }))).toEqual([])+ expect(offered(state({ machines: [served([{ grid: GRID, model: 'qwen3', name: 'Qwen 3', starting: false }])] }))).toHaveLength(1)+ })it('lets up to four Builders share an API model, which answers several requests at once', () => {const api = state({ machines: [served([{ grid: GRID, model: 'ds', name: 'DeepSeek', kind: 'api' }])] })const starts = (n: number) => Array.from({ length: n }, (_, i) => ({ request: { gridModel: 'ds' }, harnessId: `h${i}` }))diff --git a/cli/src/superTabs/routeCommand.ts b/cli/src/superTabs/routeCommand.tsindex cbf12f765..5546c25c1 100644--- a/cli/src/superTabs/routeCommand.ts+++ b/cli/src/superTabs/routeCommand.ts@@ -256,7 +256,8 @@ function servedModels(state: Json, swarm: string, now: number): Map<string, Servconst observed = object(machine.observation)if (!finite(observed.receivedAt) || now - observed.receivedAt > LOCAL_FRESH_MS) continuefor (const l of list(observed.localModels)) {- if (typeof l.grid !== 'string' || typeof l.model !== 'string') continue+ // A model still starting (the grid does not list it yet) is the panel's to show, not a Builder's to run on.+ if (typeof l.grid !== 'string' || typeof l.model !== 'string' || l.starting === true) continueconst key = `${l.grid}\0${l.model}`, anywhere = l.grid === swarmconst kind = l.kind === 'api' || l.kind === 'shared' ? l.kind : anywhere ? 'local' : 'shared'const known = served.get(key) ?? { grid: l.grid, model: l.model, label: text(l.name) ?? l.model, kind, machines: anywhere ? null : new Set<string>(), holders: [] }diff --git a/desktop/lib/models/model_manager_controller.dart b/desktop/lib/models/model_manager_controller.dartindex 00f3dc723..9407fa243 100644--- a/desktop/lib/models/model_manager_controller.dart+++ b/desktop/lib/models/model_manager_controller.dart@@ -9,6 +9,7 @@ import '../core/project_folder.dart';import '../core/test_run.dart';import '../state/app_state.dart';import '../widgets/grid_model_picker.dart' show modelPickerSupports;+import '../ws/ws_conn.dart' show WsRequestFailure;import 'local_model.dart';import 'api_connections_controller.dart';@@ -720,7 +721,13 @@ class ModelManagerController extends ChangeNotifier {}/// [grid]: start or stop it on that Swarm's grid instead of the account's own (docs/plans/2026-10-23-swarm-local-models.md).- Future<void> control(LocalModel model, String action, {String? grid}) async {+ /// Answers why the request was refused, or null. The answer is kept for the caller: the list read that follows+ /// clears [error], and a refused Run for Swarm said nothing (2026-10-26: "Free plan allows 5 networks").+ Future<String?> control(+ LocalModel model,+ String action, {+ String? grid,+ }) async {final owner = machine;if (owner == null ||owner.connectionStatus != ConnectionStatus.connected ||@@ -729,22 +736,25 @@ class ModelManagerController extends ChangeNotifier {owner.machine.isShared ||busy ||!inventoryAvailable) {- return;+ return null;}final current = localModels.where((entry) => entry.id == model.id).firstOrNull;- if (current == null) return;+ if (current == null) return null;final download = action == 'download';final startModel = action == 'start';if (download) {- if (!supportsDownload || current.downloaded || !current.canStart) return;+ if (!supportsDownload || current.downloaded || !current.canStart) {+ return null;+ }} else if (startModel) {- if (!current.canStart) return;+ if (!current.canStart) return null;} else if (action != 'stop' ||!(grid == null ? current.canStop : current.servedOn(grid))) {- return;+ return null;}+ String? refused;pendingId = model.id;_actionRevision++;inventoryAvailable = false;@@ -762,10 +772,13 @@ class ModelManagerController extends ChangeNotifier {start: startModel,grid: grid,);- if (!_current(owner)) return;- error = answer['error'] as String?;+ if (!_current(owner)) return null;+ error = refused = answer['error'] as String?;pendingOperation = LocalModelOperation.parse(answer['operation']);operationBusy = pendingOperation?.active == true;+ } on WsRequestFailure catch (failure) {+ // The CLI refused it, in its own words (grid's plan limit, a sign-in): those, not a generic retry.+ if (_current(owner)) error = refused = failure.detail ?? failure.code;} catch (_) {if (_current(owner)) {error =@@ -781,6 +794,7 @@ class ModelManagerController extends ChangeNotifier {if (_current(owner)) await refresh();}}+ return refused;}@overridediff --git a/desktop/lib/state/swarm_search.dart b/desktop/lib/state/swarm_search.dartindex b84c5ecdc..d9afe6197 100644--- a/desktop/lib/state/swarm_search.dart+++ b/desktop/lib/state/swarm_search.dart@@ -516,12 +516,13 @@ class SwarmSearchController extends ChangeNotifier {// The Swarm's grid is read when the action runs: a first run sets the Swarm's models up, and names it then.Future<String?> Function() act(String action, {bool forSwarm = false}) =>() async {- await owner.control(- local,- action,- grid: forSwarm ? swarm.grid : null,- );- return owner.error;+ // What control answers: the read after it clears [owner.error], and a refused Run for Swarm said nothing.+ return await owner.control(+ local,+ action,+ grid: forSwarm ? swarm.grid : null,+ ) ??+ owner.error;};if (local.servedOn(swarm.grid)) {return (diff --git a/desktop/lib/super_tabs/machines.dart b/desktop/lib/super_tabs/machines.dartindex 9dc12a3a6..b91b40836 100644--- a/desktop/lib/super_tabs/machines.dart+++ b/desktop/lib/super_tabs/machines.dart@@ -1100,6 +1100,10 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {if (m is! Map || m['model'] is! String) continue;final model = m['model'] as String;final named = m['name'] is String ? m['name'] as String : model;+ final starting = m['starting'] == true;+ final state = starting+ ? '\nStarting: not on the Swarm\'s grid yet'+ : '';switch (m['kind']) {case 'api' when m['grid'] == local.grid:final via = named.contains(' · ')@@ -1109,14 +1113,24 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {name: model.contains('/')? model.substring(model.lastIndexOf('/') + 1): model,- tip: [model, if (via != null) 'Shared from $via'].join('\n'),+ tip:+ [model, if (via != null) 'Shared from $via'].join('\n') ++ state,+ starting: starting,));case 'shared' when swarmSharedWithYouShown:- localModels.add((name: named, tip: '$named\nShared with you'));+ localModels.add((+ name: named,+ tip: '$named\nShared with you',+ starting: false,+ ));case 'local' || null when m['grid'] == local.grid:localModels.add((name: named,- tip: '$named\nRunning on this machine',+ tip: starting+ ? '$named\nStarting on this machine'+ : '$named\nRunning on this machine',+ starting: starting,));}}@@ -1956,7 +1970,8 @@ class _MachineView {}/// A model a machine offers its Swarm: its short name on the row, the whole of it on hover.-typedef _ServedModel = ({String name, String tip});+/// [starting]: run or shared here, not yet listed by the Swarm's grid (CLI `superTabs/machines.ts`).+typedef _ServedModel = ({String name, String tip, bool starting});/// An allowance's note, from its detail lines: the window that stops work first, and its reset. Another machine's/// lines put that window first (`5-hour: 44% remaining · resets in 2h 10m`); this computer's name it@@ -2539,7 +2554,7 @@ class _MachineReadings extends StatelessWidget {height: 22,padding: const EdgeInsets.symmetric(horizontal: 8),decoration: BoxDecoration(- color: local+ color: local && !model.starting? grid.AppPalette.online.withValues(alpha: .13): DesktopChrome.foreground.withValues(alpha: .06),borderRadius: BorderRadius.circular(6),@@ -2547,12 +2562,14 @@ class _MachineReadings extends StatelessWidget {child: Row(mainAxisSize: MainAxisSize.min,children: [- if (local) ...[+ if (local || model.starting) ...[Container(width: 5,height: 5,decoration: BoxDecoration(- color: grid.AppPalette.online,+ color: model.starting+ ? DesktopChrome.muted+ : grid.AppPalette.online,shape: BoxShape.circle,),),@@ -2567,10 +2584,23 @@ class _MachineReadings extends StatelessWidget {maxLines: 1,overflow: TextOverflow.ellipsis,style: grid.AppType.monoMeta(- color: DesktopChrome.foreground,+ color: model.starting+ ? DesktopChrome.muted+ : DesktopChrome.foreground,),),),+ if (model.starting) ...[+ const SizedBox(width: 5),+ Text(+ 'starting…',+ style: DesktopChrome.text(+ size: 11,+ height: 1.3,+ color: DesktopChrome.muted,+ ),+ ),+ ],],),),diff --git a/desktop/lib/super_tabs/model.dart b/desktop/lib/super_tabs/model.dartindex 16ade4b23..ca3b676ea 100644--- a/desktop/lib/super_tabs/model.dart+++ b/desktop/lib/super_tabs/model.dart@@ -396,7 +396,13 @@ List<SuperTabLocalModelRow> superTabLocalModelRows(in observation['localModels'] is List? observation['localModels'] as List: const []) {- if (m is! Map || m['grid'] is! String || m['model'] is! String) continue;+ // Still starting (the grid does not list it yet): not usable by the Swarm now.+ if (m is! Map ||+ m['grid'] is! String ||+ m['model'] is! String ||+ m['starting'] == true) {+ continue;+ }final grid = m['grid'] as String, model = m['model'] as String;if (rows.any((r) => r.grid == grid && r.model == model)) continue;rows.add((@@ -439,7 +445,10 @@ List<SuperTabServedModel> superTabServedModels(in observation['localModels'] is List? observation['localModels'] as List: const [])- if (m is Map && m['grid'] == grid && m['model'] is String)+ if (m is Map &&+ m['grid'] == grid &&+ m['model'] is String &&+ m['starting'] != true)(model: m['model'] as String,name: m['name'] is Stringdiff --git a/desktop/test/super_tab_machines_test.dart b/desktop/test/super_tab_machines_test.dartindex 519aa8cb5..d6c23ad61 100644--- a/desktop/test/super_tab_machines_test.dart+++ b/desktop/test/super_tab_machines_test.dart@@ -1023,6 +1023,13 @@ void main() {machine(served: [{'grid': swarmGrid, 'model': 'qwen3', 'name': 'Qwen 3'},+ // Run here, not yet listed by the Swarm's grid: shown as starting.+ {+ 'grid': swarmGrid,+ 'model': 'qwen36',+ 'name': 'Qwen 3.6',+ 'starting': true,+ },{'grid': 'swarm-ffffffffffff', 'model': 'other'},{'grid': swarmGrid,@@ -1049,6 +1056,11 @@ void main() {find.byKey(const ValueKey('super-machine-local-studio-Qwen 3')),findsOneWidget,);+ expect(+ find.byKey(const ValueKey('super-machine-local-studio-Qwen 3.6')),+ findsOneWidget,+ );+ expect(find.text('starting…'), findsOneWidget);expect(find.text('API'), findsOneWidget);expect(find.byKey(diff --git a/desktop/test/swarm_local_models_picker_test.dart b/desktop/test/swarm_local_models_picker_test.dartindex 45d3b9766..f5fbd7b75 100644--- a/desktop/test/swarm_local_models_picker_test.dart+++ b/desktop/test/swarm_local_models_picker_test.dart@@ -1,3 +1,5 @@+import 'dart:async';+import 'package:flutter_test/flutter_test.dart';import 'package:harness/core/models.dart';import 'package:harness/models/model_search_catalog.dart';@@ -5,6 +7,7 @@ import 'package:harness/models/swarm_models_target.dart';import 'package:harness/state/swarm_navigation.dart';import 'package:harness/state/swarm_search.dart';import 'package:harness/usage/models_menu_controller.dart';+import 'package:harness/ws/ws_conn.dart';import 'support/model_manager.dart';@@ -247,6 +250,22 @@ void main() {expect(search.modelRowStatus(row('served')), 'In Swarm');expect(search.swarmModelAction(row('served'))!.label, 'Stop for Swarm');expect(search.swarmModelAction(row('catalog'))!.label, 'Get');+ // A start the CLI refuses says why, in its words, though the list read after it clears the manager's error+ // (2026-10-26: a Run for Swarm refused at the plan's network limit said nothing).+ final refusal = Completer<Map<String, dynamic>>();+ app.actionReply = refusal;+ final refused = search.swarmModelAction(row('downloaded'))!.run!();+ refusal.completeError(+ const WsRequestFailure(+ responseType: 'grid_fleet_model_start_result',+ code: 'Free plan allows 5 networks; upgrade to create more',+ ),+ );+ expect(+ await refused,+ 'Free plan allows 5 networks; upgrade to create more',+ );+ app.actionReply = null;final run = search.swarmModelAction(row('downloaded'))!;expect(run.label, 'Run for Swarm');expect(await run.run!(), isNull);