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
Jev (System One) models: their own section, how to call them, and Get with an engine update (#755)
scholes-autonomous3c86a75ce4b8
diff --git a/cli/src/backendSocket.gridReads.spec.ts b/cli/src/backendSocket.gridReads.spec.tsindex 88cca217a..9c1bd2ccf 100644--- a/cli/src/backendSocket.gridReads.spec.ts+++ b/cli/src/backendSocket.gridReads.spec.ts@@ -150,7 +150,9 @@ describe('grid_fleet_models_list (the Model Manager) on a sleeping own grid', ()const reply = await ask('grid_fleet_models_list', { refresh: true })expect(reply.error).not.toBe('Running models could not be checked. Try again.')- expect(reply.models).toEqual([expect.objectContaining({ id: 'local:Small-Q4.gguf', state: 'running', gridAsleep: true, canStop: true })])+ // (The Jev models offered to get are not this grid's engines; they are listed whatever it runs.)+ expect((reply.models as Array<{ kind?: string }>).filter((m) => m.kind !== 'decision'))+ .toEqual([expect.objectContaining({ id: 'local:Small-Q4.gguf', state: 'running', gridAsleep: true, canStop: true })])expect(seen.map((r) => r.path)).toEqual([`/g/${OWN_ID}${OVERVIEW}`])expectNoCredential()// The owner status is asked once and remembered, not asked on every tick.diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex d5bf9ca96..e638afddb 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -74,7 +74,7 @@ import { ensureHarnessGrid, type EnsureStatus } from './lib/gridEnsure.js'import { passThroughToGridLogout } from './lib/gridLogout.js'import { warnIfGridSignInRemains } from './lib/gridCredentials.js'import { observeMachineList } from './lib/gridModels.js'-import { managedGridPath } from './lib/gridExec.js'+import { gridExec, managedGridPath } from './lib/gridExec.js'import { ENGINE_CLI_COMMANDS, ENGINES, PROCESS_ENGINES, enginePathOverride } from './lib/engineBin.js'import { isTerminalEngine } from './engines/types.js'import { engineInstallRecipe } from './lib/engineInstall.js'@@ -375,6 +375,8 @@ Grid (the fleet of AI engines the \`grid\` CLI serves — needs \`grid\` on PATHharness grid logout [flags] sign out of your grid — the whole of \`grid logout\`, which stops whatthis box is serving BEFORE deleting anything. Flags go straight to it:--force signs out over a serve child it could not confirm stopped+ harness grid env <grid> print <grid>'s relay address and key as shell exports, for+ eval "$(harness grid env <grid>)" — through the harness's own \`grid\`${dshUsage()}@@ -1184,6 +1186,27 @@ async function gridLogoutCommand(args: string[]): Promise<void> {process.exitCode = outcome.exitCode}+/**+ * `harness grid env <grid>` — `grid --remote info <grid> --env` through the harness's own `grid`, so a+ * shell can `eval` a grid's relay address and key with no `grid` of its own on PATH, or an older one+ * that refuses a resting grid. The Models view's Jev pane builds its copy-paste request on it.+ *+ * A passthrough like `grid logout`: the exports, the refusals and the exit code are `grid`'s. The key+ * goes to this process's stdout only — the explicit disclosure `info --env` exists for — never a log.+ */+async function gridEnvCommand(grid: string | undefined): Promise<void> {+ if (!grid?.trim() || grid.startsWith('-')) {+ console.error('Usage: harness grid env <grid>')+ process.exitCode = 2+ return+ }+ const result = await gridExec(['--remote', 'info', grid, '--env'])+ if (result.stdout) process.stdout.write(result.stdout)+ if (result.stderr) process.stderr.write(result.stderr)+ if (result.code === 'GRID_CLI_MISSING') console.error(`\n ✗ ${result.message}\n`)+ process.exitCode = result.exitCode+}+/*** Fallback for a browser that cannot reach this machine's loopback callback (running `harness login`* over SSH: the user's browser is on a different box, so its own 127.0.0.1 has nothing listening).@@ -5597,6 +5620,7 @@ switch (cmd) {// token goes: filtering by value instead would eat an option's *value* the day `grid logout`// takes one, forwarding the flag with nothing behind it.else if (args[0] === 'logout') gridLogoutCommand(withoutFirst(rest, 'logout')).catch(onError)+ else if (args[0] === 'env') gridEnvCommand(args[1]).catch(onError)else { console.error(`Unknown command: grid ${args[0] ?? ''}`); usage(1) }breakcase 'dsh':diff --git a/cli/src/gridCommand.spec.ts b/cli/src/gridCommand.spec.tsindex 56fa2bc32..2a6c2af37 100644--- a/cli/src/gridCommand.spec.ts+++ b/cli/src/gridCommand.spec.ts@@ -764,6 +764,43 @@ describe('harness grid logout', () => {}, 20_000)})+describe('harness grid env', () => {+ it('prints the grid\'s exports from the harness\'s own grid, for a shell to eval', async () => {+ const root = tempRoot()+ seedSession(root)+ const exports = "export OPENAI_BASE_URL='https://relay.example/g/1/relay/v1'\nexport OPENAI_API_KEY='k'\n"++ const result = await run(root, ['grid', 'env', 'team grid'], 'http://127.0.0.1:1', { FAKE_GRID_STDOUT: exports })++ expect(result.status).toBe(0)+ expect(result.stdout).toBe(exports)+ expect(readRecord(root).args).toEqual(['--remote', 'info', 'team grid', '--env'])+ }, 20_000)++ it('carries the grid\'s refusal out in its own words and exit code', async () => {+ const root = tempRoot()+ seedSession(root)++ const result = await run(root, ['grid', 'env', 'home'], 'http://127.0.0.1:1',+ { FAKE_GRID_EXIT: '1', FAKE_GRID_STDERR: 'Unknown grid home.\n' })++ expect(result.status).toBe(1)+ expect(result.stderr).toContain('Unknown grid home.')+ expect(result.stdout).toBe('')+ }, 20_000)++ it('asks for a grid, and never passes a flag to grid as one', async () => {+ const root = tempRoot()+ seedSession(root)++ for (const args of [['grid', 'env'], ['grid', 'env', '--help']]) {+ const result = await run(root, args, 'http://127.0.0.1:1')+ expect(result.status).toBe(2)+ expect(result.stderr).toContain('Usage: harness grid env <grid>')+ }+ }, 20_000)+})+describe('harness logout — the grid sign-out it now performs', () => {// ⚠️ This suite used to be named "the grid credential it will not touch" and asserted the// OPPOSITE: that `harness logout` only ever printed a sentence about the grid. The one-sign-indiff --git a/cli/src/lib/gridModels.ts b/cli/src/lib/gridModels.tsindex 9966f351e..17d46f4fb 100644--- a/cli/src/lib/gridModels.ts+++ b/cli/src/lib/gridModels.ts@@ -28,7 +28,7 @@ import { signedInGridEmail } from './gridDerive.js'import { gridJson } from './gridExec.js'import {advertisedNow, emptyPicture, mergeAwake, idKey, parsePicture, provenStopped, sectionView, servedKey, servesAModel, unspelled, withAsleep,- withSpellings, withUnknown, withWindows, type GridPicture, type LocalRecord, type PictureState, type RowUnavailable,+ withDecisions, withSpellings, withUnknown, withWindows, type GridPicture, type LocalRecord, type PictureState, type RowUnavailable,type SectionView, type ServedHere,} from './gridPicture.js'import { ComputerPresence, computersIn, MACHINE_LIST_FRESH_MS } from './gridPresence.js'@@ -48,6 +48,9 @@ export interface GridModel {/** Every computer serving it seems offline — sent only to a client that asked for row state* ([presentGridSections]); an older one reads it in `node` instead. */unavailable?: RowUnavailable+ /** `decision`: a Jev (System One) model, called at `/v1/systemone` and never run as an agent — a picker+ * lists it in its own section. Absent for a chat model; an older app ignores it. */+ kind?: 'decision'}/** How an explicit wake that did not show models ended: the grid did not come up in time, or came up@@ -440,6 +443,7 @@ export class GridModelsService {let picture = mergeAwake(previous, read.nodes, now, isMine, (name, key) => provenStopped(previous, here, name, key))const spelled = withSpellings(picture.caseMap, [...read.curatedIds, ...here.records.flatMap((r) => r.ids)])picture = withWindows({ ...picture, caseMap: withSpellings(spelled, advertisedNow(here.records), true) }, read.windows)+ picture = withDecisions(picture, read.nodes)const unknownIds = unspelled(picture, read.nodes).filter((key) => !tracked.spelled.has(key))if (unknownIds.length && base) {unknownIds.forEach((key) => tracked.spelled.add(key))diff --git a/cli/src/lib/gridPicture.ts b/cli/src/lib/gridPicture.tsindex d78021dc6..217456427 100644--- a/cli/src/lib/gridPicture.ts+++ b/cli/src/lib/gridPicture.ts@@ -77,10 +77,13 @@ export interface GridPicture {caseMap: Record<string, string>/** lower-case id → the model's context window, as the last awake read that reported one said. */windows: Record<string, number>+ /** lower-case ids of the Jev (System One) decision models the last awake reads said a node serves —+ * rows a picker lists apart from chat models, since none of them can run an agent. */+ decisions: string[]}export function emptyPicture(): GridPicture {- return { spec: 1, state: 'unknown', seenAt: null, listAt: null, nodes: [], caseMap: {}, windows: {} }+ return { spec: 1, state: 'unknown', seenAt: null, listAt: null, nodes: [], caseMap: {}, windows: {}, decisions: [] }}/** `windows` (keyed without case) with a read's figures folded in — the latest figure for a model wins. */@@ -91,6 +94,24 @@ export function withWindows(picture: GridPicture, windows: Record<string, numberreturn { ...picture, windows: Object.fromEntries(kept) }}+/**+ * `decisions` after an awake answer (`picture` is the answer already merged in). A model a node listed is+ * a decision model exactly when that node's `decisions` names it; a model no node listed keeps its mark+ * for as long as the picture retains it. A node that does not say (the CLI fallback) changes nothing.+ */+export function withDecisions(picture: GridPicture, nodes: readonly ReadNode[]): GridPicture {+ const told = nodes.filter((node) => node.decisions !== undefined)+ const listed = new Set(told.flatMap((node) => node.models.map(idKey)))+ const marked = new Set(told.flatMap((node) => node.decisions!.map(idKey)).filter((key) => key && listed.has(key)))+ const retained = new Set(picture.nodes.flatMap((node) => node.models.map((model) => model.key)))+ const decisions = [...new Set([+ ...picture.decisions.filter((key) => retained.has(key) && !listed.has(key)),+ ...marked,+ ])].slice(-MAX_SAVED_DECISIONS)+ const same = decisions.length === picture.decisions.length && decisions.every((key, i) => key === picture.decisions[i])+ return same ? picture : { ...picture, decisions }+}+/** The join key for a model id across every source: trimmed, without case. (Not `localModels.ts`'s own* private key, which also strips `.gguf` for a different comparison.) */export const idKey = (id: string): string => id.trim().toLowerCase()@@ -283,6 +304,8 @@ export interface GridModelRow {node: string/** Every computer serving it seems offline (issue 03). Absent otherwise. */unavailable?: RowUnavailable+ /** `decision`: a Jev (System One) model — called at `/v1/systemone`, never chatted with. Absent for chat. */+ kind?: 'decision'}export interface SectionView {@@ -343,9 +366,10 @@ export function sectionView(picture: GridPicture, here: ServedHere, now: number,const since = Math.min(...readings.map((reading) => reading!.since))return { reason: 'offline', machine: first.machine, since: new Date(since).toISOString() }}+ const decisions = new Set(picture.decisions)const rows = [...namedBy].map(([key, node]): GridModelRow => {const label = unavailable(key)- return { id: caseMap[key] ?? key, node, ...(label ? { unavailable: label } : {}) }+ return { id: caseMap[key] ?? key, node, ...(label ? { unavailable: label } : {}), ...(decisions.has(key) ? { kind: 'decision' as const } : {}) }})return {models: rows,@@ -363,6 +387,7 @@ const MAX_SAVED_MODELS_PER_NODE = 256const MAX_SAVED_TEXT = 256const MAX_SAVED_SPELLINGS = 4096const MAX_SAVED_WINDOWS = 4096+const MAX_SAVED_DECISIONS = 4096/** A picture read back from disk, or null when it is not one this module wrote. Never trusts the file. */export function parsePicture(value: unknown): GridPicture | null {@@ -399,6 +424,11 @@ export function parsePicture(value: unknown): GridPicture | null {if (key && key === idKey(key) && typeof window === 'number' && Number.isSafeInteger(window) && window > 0) windows[key.slice(0, MAX_SAVED_TEXT)] = window}}+ // Absent from a picture written before Jev models were told apart: none known, as an empty list says.+ const decisions = Array.isArray(record.decisions)+ ? [...new Set(record.decisions.filter((key): key is string => typeof key === 'string' && !!key && key === idKey(key))+ .map((key) => key.slice(0, MAX_SAVED_TEXT)))].slice(0, MAX_SAVED_DECISIONS)+ : []return {spec: 1,// Waking is a person's request in flight, and that request died with the process that made it.@@ -408,5 +438,6 @@ export function parsePicture(value: unknown): GridPicture | null {nodes,caseMap,windows,+ decisions,}}diff --git a/cli/src/lib/gridReader.ts b/cli/src/lib/gridReader.tsindex 4fbf2c701..547cc24b7 100644--- a/cli/src/lib/gridReader.ts+++ b/cli/src/lib/gridReader.ts@@ -68,6 +68,10 @@ export interface ReadNode {name: stringengine: stringmodels: string[]+ /** The subset of `models` that are Jev (System One) decision models — the overview's `systemone_models`.+ * They answer typed decisions at `/v1/systemone` and cannot chat, so they are never an agent's model.+ * Absent from the CLI fallback, which cannot tell: absent says nothing, where `[]` says "none". */+ decisions?: string[]/** The provider's account, when the grid publishes it (it withholds it on an `os-community` grid).* Read only to decide whether a node is the account's own, and never persisted. */providerEmail: string | null@@ -160,6 +164,7 @@ function readNodes(value: unknown): ReadNode[] {name: text(node.name),engine: text(node.engine),models: strings(node.models, MAX_MODELS_PER_NODE),+ decisions: strings(node.systemone_models, MAX_MODELS_PER_NODE),providerEmail: typeof node.provider_email === 'string' && node.provider_email ? node.provider_email : null,}))}diff --git a/cli/src/lib/gridReads.spec.ts b/cli/src/lib/gridReads.spec.tsindex 20931d9e9..7ac1d17b4 100644--- a/cli/src/lib/gridReads.spec.ts+++ b/cli/src/lib/gridReads.spec.ts@@ -462,6 +462,42 @@ describe('the grid list', () => {})})+describe('Jev (System One) decision models', () => {+ const kinds = (s: GridSection) => Object.fromEntries(s.models.map((m) => [m.id, m.kind ?? 'chat']))++ it('are the rows the overview lists in a node\'s systemone_models; every other row is chat', async () => {+ answer(TEAM_ID, OVERVIEW, awake([node('rig', ['qwen', 'laya-english'], { systemone_models: ['laya-english'] })]))++ expect(kinds(section(await look(), TEAM))).toEqual({ qwen: 'chat', 'laya-english': 'decision' })+ })++ it('keep the mark while a missed read retains them, lose it once listed as chat, and never gain it unlisted', async () => {+ answer(TEAM_ID, OVERVIEW, awake([node('rig', ['laya'], { systemone_models: ['laya', 'ghost'] })]))+ await look()+ later(20)+ answer(TEAM_ID, OVERVIEW, awake([]))+ expect(kinds(section(await look(), TEAM))).toEqual({ laya: 'decision' })++ later(20)+ answer(TEAM_ID, OVERVIEW, awake([node('rig', ['laya'])]))+ expect(kinds(section(await look(), TEAM))).toEqual({ laya: 'chat' })+ })++ it('keep the mark through the CLI fallback, which cannot tell, and through a daemon restart', async () => {+ answer(TEAM_ID, OVERVIEW, awake([node('rig', ['Laya'], { systemone_models: ['laya'] })]))+ await look()+ grid.replan(plan({ teamUrl: 'ftp://nowhere.example', models: { stdout: JSON.stringify([+ { model: 'Laya', engine: 'llama.cpp', node: 'rig' },+ ]) } }))+ forgetGridModels()+ later()+ expect(kinds(section(await look(), TEAM))).toEqual({ Laya: 'decision' })++ service = resetGridModels({ now: () => clock, dataDir: () => join(root, 'data'), gridHome: () => gridHome, email: () => EMAIL })+ expect(kinds(section(await listAllGridModels(OWN), TEAM))).toEqual({ Laya: 'decision' })+ })+})+describe('what an older desktop reads', () => {it('every section stays a valid {name, own, models:[{id,node}]}, and a sleeping one keeps its models', async () => {answer(OWN_ID, OVERVIEW, asleep(record(60, [{ name: 'mac', models: ['small-q4'] }])))diff --git a/cli/src/lib/localModels.spec.ts b/cli/src/lib/localModels.spec.tsindex 3348ee856..ba5c29db4 100644--- a/cli/src/lib/localModels.spec.ts+++ b/cli/src/lib/localModels.spec.ts@@ -1444,3 +1444,121 @@ describe('models other apps downloaded, started in their own app', () => {expect(ops.start).not.toHaveBeenCalled()})})++describe('Jev models: Get brings Grid\'s llama.cpp up to a build that serves them', () => {+ const GiB = 1024 ** 3+ const LAYA = 'jev:ggml-org/Laya-GGUF', LAYA_SIZE = 449_397_600+ const gemma: AppModel = { id: 'app:lm-studio:google/gemma-4-e2b', name: 'gemma-4-e2b', app: 'lm-studio', engine: 'lm-studio',+ ref: 'google/gemma-4-e2b', binary: '/home/me/.lmstudio/bin/lms', sizeBytes: 4 * GiB, contextLength: 131072 }+ let up: Set<string>, joined: Set<string>, installBuild: string, decisions: string[]+ let ops: { [K in keyof AppEngineOps]: Mock<AppEngineOps[K]> }+ const engine = async (build: string) => {+ await mkdir(join(home, 'bin'), { recursive: true })+ await writeFile(join(home, 'bin', 'llama-server'), `#!/bin/sh\necho "version: ${build}"\n`, { mode: 0o755 })+ }+ const jevService = (env: NodeJS.ProcessEnv = {}) => {+ const base = run.getMockImplementation()!+ run.mockImplementation(async (args, output) => {+ if (args[0] === 'pull' && args[1] === 'ggml-org/Laya-GGUF:Laya-Q8_0.gguf') {+ calls.push(args); output?.('100%')+ const file = join(home, 'models', 'Laya-Q8_0.gguf')+ await writeFile(file, ''); await (await import('node:fs/promises')).truncate(file, LAYA_SIZE)+ return ok()+ }+ if (args[0] === 'engine' && args[1] === 'install') { calls.push(args); await engine(installBuild); return ok() }+ if (args.includes('join') && args.includes('--at')) { calls.push(args); joined.add(args[args.indexOf('--advertise-as') + 1]!); return ok() }+ if (args.includes('leave') && joined.has(args[args.indexOf('--engine') + 1]!)) { calls.push(args); joined.delete(args[args.indexOf('--engine') + 1]!); return ok() }+ return base(args, output)+ })+ inventory.mockImplementation(async () => ({ state: 'awake', status: 'running',+ nodes: [...joined].map(alias => ({ node_id: 'local-node', online: true, models: [alias] })) }))+ request.mockImplementation(async (url: string | URL, init?: RequestInit) => {+ if (String(url).endsWith('/systemone')) {+ decisions.push(JSON.parse(String(init?.body)).model)+ return response({ model: 'laya-english', answers: { refund: { type: 'noul', noul: 0.91 } }, usage: { input_tokens: 41, output_tokens: 0 } })+ }+ return response({ choices: [{ message: { content: 'ok' } }] })+ })+ return new LocalModels({ stateDir, processEnv: { GRID_HOME: home, ...env }, run, request: request as typeof fetch, inventory,+ appModels: async () => [gemma], appEngines: ops as unknown as AppEngineOps })+ }+ const laya = async (models: LocalModels) => (await models.list('home', true)).models.find(m => m.id === LAYA)!+ beforeEach(() => {+ up = new Set(); joined = new Set(); installBuild = '0.5.0-dev (build 11378, commit edd6e2bbd)'; decisions = []+ ops = {+ start: vi.fn(async (model: AppModel) => {+ up.add(model.id)+ return { engine: model.engine as AppEngineRecord['engine'], served: model.name, alias: model.name, port: 41001, binary: model.binary!, pid: 4343 }+ }),+ alive: vi.fn(async (record: AppEngineRecord) => up.has(record.modelId)),+ loadedContext: vi.fn(async () => 131072),+ stop: vi.fn(async (record: AppEngineRecord) => { up.delete(record.modelId) }),+ }+ })++ it('is listed as a decision model, to get, and a download alone touches no engine', async () => {+ const models = jevService()+ expect(await laya(models)).toMatchObject({ name: 'laya-english', kind: 'decision', state: 'available', sizeBytes: LAYA_SIZE, canStart: true, canStop: false })+ await models.act('home', LAYA, 'download'); await models.settled()+ expect(await laya(models)).toMatchObject({ state: 'downloaded', app: 'Grid', operation: { phase: 'done' } })+ expect(calls.some(args => args[0] === 'engine')).toBe(false)+ expect(ops.start).not.toHaveBeenCalled()+ })++ it('updates an engine too old for it, runs it beside a chat model, checks it with a decision, and stops it', async () => {+ await engine('10369 (6e62ba538)')+ const models = jevService()+ // A chat model already running in its own app does not stand in the way, as it would for another chat model.+ await models.act('home', gemma.id, 'start'); await models.settled()+ // Every stage the operation passes through, as the app is told of it.+ const stages: string[] = []+ const save = (models as any).save.bind(models)+ vi.spyOn(models as any, 'save').mockImplementation(async (grid: unknown, operation: any) => { stages.push(operation.stage); return save(grid, operation) })+ await models.act('home', LAYA, 'start'); await models.settled()+ const order = calls.map(args => args.join(' '))+ const pulled = order.indexOf('pull ggml-org/Laya-GGUF:Laya-Q8_0.gguf'), installed = order.indexOf('engine install llama.cpp')+ expect(pulled).toBeGreaterThanOrEqual(0)+ expect(installed).toBeGreaterThan(pulled)+ expect(stages).toContain('updating')+ expect(ops.start).toHaveBeenLastCalledWith(expect.objectContaining({ id: LAYA, engine: 'llama.cpp', binary: join(home, 'bin', 'llama-server'),+ ref: join(home, 'models', 'Laya-Q8_0.gguf') }), 8192, join(stateDir, 'logs'))+ expect(calls.find(args => args.includes('--at') && args.includes('laya-english'))).toEqual(['--remote', 'join', 'home', '--at',+ 'http://127.0.0.1:41001/v1', '-m', 'laya-english', '--advertise-as', 'laya-english', '--max-concurrency', '1'])+ expect(decisions).toEqual(['laya-english'])+ expect(await laya(models)).toMatchObject({ kind: 'decision', state: 'running', canStop: true, operation: { phase: 'done' } })+ // And a running Jev model blocks no chat model either.+ const list = await models.list('home', true)+ expect(list.models.find(m => m.id === gemma.id)).toMatchObject({ state: 'running' })++ await models.act('home', LAYA, 'stop'); await models.settled()+ expect(calls.some(args => args.join(' ') === '--remote leave home --engine laya-english')).toBe(true)+ expect(ops.stop).toHaveBeenCalledWith(expect.objectContaining({ modelId: LAYA, pid: 4343 }))+ expect(await laya(models)).toMatchObject({ state: 'downloaded', canStart: true, canStop: false })+ })++ it('leaves an engine new enough alone', async () => {+ await engine('0.5.0-dev (build 11378, commit edd6e2bbd)')+ const models = jevService()+ await models.act('home', LAYA, 'start'); await models.settled()+ expect(calls.some(args => args[0] === 'engine')).toBe(false)+ expect(await laya(models)).toMatchObject({ state: 'running' })+ })++ it('says so when the update still leaves the engine too old, and starts nothing', async () => {+ await engine('10369 (6e62ba538)')+ installBuild = '10369 (6e62ba538)'+ const models = jevService()+ await models.act('home', LAYA, 'start'); await models.settled()+ expect((await laya(models)).operation).toMatchObject({ phase: 'failed', error: expect.stringContaining('still too old for Jev models (build 10369') })+ expect(ops.start).not.toHaveBeenCalled()+ })++ it('never replaces an engine named by LLAMA_SERVER: one too old is refused by name', async () => {+ const custom = join(root, 'custom-llama-server')+ await writeFile(custom, '#!/bin/sh\necho "version: 0.5.0 (build 11146, commit 7fe450e19)"\n', { mode: 0o755 })+ const models = jevService({ LLAMA_SERVER: custom })+ await models.act('home', LAYA, 'start'); await models.settled()+ expect((await laya(models)).operation).toMatchObject({ phase: 'failed', error: 'LLAMA_SERVER is llama.cpp build 11146; Jev models need build 11361 or newer.' })+ expect(calls.some(args => args[0] === 'engine')).toBe(false)+ })+})diff --git a/cli/src/lib/localModels.ts b/cli/src/lib/localModels.tsindex 2f26a1c06..bf72fe3ae 100644--- a/cli/src/lib/localModels.ts+++ b/cli/src/lib/localModels.ts@@ -1,5 +1,6 @@/** 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 { execFile } from 'node:child_process'import { createHash, randomUUID } from 'node:crypto'import { readFile, readdir, stat, mkdir, rename, writeFile, statfs, symlink, lstat, readlink } from 'node:fs/promises'import { createServer, type AddressInfo } from 'node:net'@@ -35,6 +36,35 @@ export const MIN_CODING_CONTEXT = 64 * 1024* to hold for a 35B model, one step above the floor. */const UNREAD_CONTEXT = 128 * 1024+/**+ * Jev (System One) decision models this harness can get and run here: they answer typed questions at+ * `/v1/systemone` and never run a harness, so they are listed apart and never moved onto. Hand-duplicated+ * with autonomous-grid's catalog (`shared/models/catalog.py`, its `kind="decision"` rows); `size` is the+ * file's own, which is how a finished download is told from a partial one.+ */+export const JEV_MODELS: ReadonlyArray<{ id: string; name: string; pull: string; file: string; size: number; quant: string }> = [+ { id: 'jev:ggml-org/Laya-GGUF', name: 'laya-english', pull: 'ggml-org/Laya-GGUF:Laya-Q8_0.gguf', file: 'Laya-Q8_0.gguf', size: 449_397_600, quant: 'Q8_0' },+]+const isJev = (id: string): boolean => id.startsWith('jev:')+/** The first llama.cpp build that serves `/v1/systemone` (ggml-org/llama.cpp#29818). An older one+ * cannot even load a decision GGUF, so Get updates Grid's engine below it — and Grid itself refuses. */+export const MIN_JEV_BUILD = 11361+/** A decision model's window: its state and options, never a conversation. */+const JEV_CONTEXT = 8192++/** The build a llama-server reports (`version: 0.5.0 (build 11146, …)`, or `version: 10369 (…)` before+ * llama.cpp's semver releases); undefined when it is missing or does not say. 30 s: a binary macOS has+ * not run lately took 10.7 s to answer its first `--version` [run]. */+export function llamaBuild(binary: string, env: NodeJS.ProcessEnv = process.env): Promise<number | undefined> {+ return new Promise(resolve => {+ execFile(binary, ['--version'], { env, timeout: 30_000 }, (_error, stdout, stderr) => {+ const text = `${stdout ?? ''}${stderr ?? ''}`+ const build = /\(build (\d+)/.exec(text)?.[1] ?? /version:\s*(\d+)\b/.exec(text)?.[1]+ resolve(build ? Number(build) : undefined)+ })+ })+}+/** The context sizes a start tries, largest first: [first], then halved, ending on the 64K floor.* 256K → 128K → 64K. Empty when even [first] is under the floor. */export function contextLadder(first: number): number[] {@@ -67,6 +97,8 @@ export interface LocalModel {id: string; name: string; state: 'available' | 'downloaded' | 'running'sizeBytes?: number; quant?: string; recommended?: boolean; canStart: boolean; canStop: booleantokensPerSecond?: number; requests?: number; windowSeconds?: number+ /** `decision`: a Jev (System One) model — Get and Stop, never Use (additive; an older app ignores it). */+ kind?: 'decision'/** What the catalog says of this model on THIS machine, for choosing between models before any* download: the window it will be given, its estimated speed, and its size in billions of* parameters. Absent for a model found on disk, which the catalog never sized. */@@ -80,7 +112,7 @@ export interface LocalModel {}export interface ModelOperation {id: string; modelId: string; action: 'download' | 'start' | 'stop'; phase: 'running' | 'done' | 'failed'- stage: 'checking' | 'downloading' | 'starting' | 'verifying' | 'stopping'+ stage: 'checking' | 'downloading' | 'updating' | 'starting' | 'verifying' | 'stopping'progress?: number; error?: string; updatedAt: string}export interface LocalModelsSnapshot {@@ -391,6 +423,10 @@ export class LocalModels {})().finally(() => { this.catalogPending = undefined })}+ private async fileComplete(file: string, size: number): Promise<boolean> {+ return stat(join(this.home, 'models', file)).then(s => s.isFile() && s.size === size, () => false)+ }+private async downloaded(candidate: Candidate): Promise<boolean> {if (candidate.appPath) return stat(candidate.appPath).then(s => s.isFile() && s.size === candidate.size, () => false)const sizes = await Promise.all(candidate.files.map(file => stat(join(this.home, 'models', file)).then(s => s.isFile() ? s.size : 0).catch(() => 0)))@@ -644,7 +680,10 @@ export class LocalModels {} 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 : undefinedconst apps = await this.apps(force)- const records = (await readAppRecords(this.appRecordsFile)).filter(record => record.grid === grid)+ const allRecords = (await readAppRecords(this.appRecordsFile)).filter(record => record.grid === grid)+ // A Jev engine is tiny and joins beside the rest: it neither blocks a chat model nor is blocked by one.+ const jevRecords = allRecords.filter(record => isJev(record.modelId))+ const records = allRecords.filter(record => !isJev(record.modelId))// An engine this daemon started is read from its record, whatever a later scan makes of the model: a// scan that missed the person's llama-server (busy serving, it answered `--version` late) once listed// a running engine as Grid's, and Stop then had nothing to stop.@@ -723,6 +762,15 @@ export class LocalModels {for (const record of records.filter(r => !apps.some(a => a.id === r.modelId))) {models.push({ ...await appRow(record.modelId, record.name, record.engine, record, {}), canStart: false })}+ // Jev models: Get downloads one, brings Grid's llama.cpp up to a build that serves it, and runs it on+ // the grid beside whatever else is there; it is listed `running` once the grid lists it. Offered only+ // where this daemon can start an engine of its own, which is how one runs.+ for (const jev of this.options.appEngines ? JEV_MODELS : []) {+ const record = jevRecords.find(r => r.modelId === jev.id)+ const have = await this.fileComplete(jev.file, jev.size)+ const row = await appRow(jev.id, jev.name, 'llama.cpp', record, { sizeBytes: jev.size, quant: jev.quant, kind: 'decision' })+ models.push({ ...row, app: GRID_LABEL, state: row.state === 'running' ? 'running' : have ? 'downloaded' : 'available' })+ }const freeDiskBytes = await statfs(join(this.home, 'models')).catch(() => statfs(this.home)).then(disk => disk.bavail * disk.bsize, () => undefined)const value: LocalModelsSnapshot = { models: withoutCopiesOfOwned(models), memoryBytes: num(obj(this.device.memory).total_gb) === undefined ? undefined : this.device.memory.total_gb * GiB,@@ -767,6 +815,7 @@ export class LocalModels {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 (isJev(operation.modelId)) return this.performJev(grid, operation, change, must)if (operation.action !== 'stop') await this.loadCatalog()if (operation.action === 'start') {// Leaving the last engine removes Grid's local registration. Restore the@@ -938,7 +987,7 @@ export class LocalModels {// Asked now, not taken from the last list: Use stops the model running and starts this one at// once, and the list read before that stop still named it.await this.owned(grid)- const running = records.find(r => r.grid === grid && r.modelId !== app.id)+ const running = records.find(r => r.grid === grid && r.modelId !== app.id && !isJev(r.modelId))if (running) throw new ModelError(`Stop ${cleanName(running.name)} first to start another local model.`)if (this.blockers.has(grid)) throw new ModelError(this.blockers.get(grid)!)const device = obj(await this.json(['device-info', '--json']))@@ -977,6 +1026,119 @@ export class LocalModels {await this.save(grid, operation)}+ /**+ * A Jev model's Get, Start and Stop. Get is the whole of it: the weights, an engine that can serve them,+ * and the model on the grid — so a person never meets "too old" for an engine they did not choose.+ *+ * ⚠️ Grid's own llama.cpp is updated in place (`grid engine install llama.cpp`) when it is older than+ * [MIN_JEV_BUILD], exactly as a missing one is installed for a chat model: nothing else upgrades the engine+ * a machine already has when Grid's pin moves. The model runs in that engine on its own loopback port and+ * joins `--at`, so the grid adds it beside the models already there without restarting them.+ */+ private async performJev(grid: string, operation: ModelOperation,+ change: (stage: ModelOperation['stage']) => Promise<void>,+ must: (args: string[], message: string, output?: (chunk: string) => void) => Promise<void>): Promise<void> {+ const jev = JEV_MODELS.find(m => m.id === operation.modelId)+ const ops = this.options.appEngines+ if (!jev || !ops) throw new ModelError('This model could not be checked. Refresh and try again.')+ const records = await readAppRecords(this.appRecordsFile)+ const record = records.find(r => r.modelId === jev.id && r.grid === grid)+ const takeDown = async (started: AppEngineRecord) => {+ await this.run(['--remote', 'leave', grid, '--engine', started.alias], undefined, 5 * 60_000)+ await ops.stop(started)+ await writeAppRecords(this.appRecordsFile, (await readAppRecords(this.appRecordsFile)).filter(r => !(r.modelId === jev.id && r.grid === grid)))+ }+ if (operation.action === 'stop') {+ if (record) await takeDown(record)+ } else if (!record) {+ if (!await this.fileComplete(jev.file, jev.size)) {+ await mkdir(join(this.home, 'models'), { recursive: true })+ const disk = await statfs(join(this.home, 'models'))+ if (disk.bavail * disk.bsize < jev.size + GiB) throw new ModelError('Free up disk space, then start again.')+ await change('downloading')+ let last = 0, progressWrites = Promise.resolve()+ await must(['pull', jev.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.fileComplete(jev.file, jev.size)) throw new ModelError('The download is incomplete. Start again to resume.')+ }+ if (operation.action === 'start') {+ const binary = await this.jevEngine(change, must)+ await change('starting')+ if (DOWN.has(await this.gridStatus(grid).catch(() => ''))) await must(['--remote', 'start', grid], 'Your grid could not start. Try again.')+ const model: AppModel = { id: jev.id, name: jev.name, app: 'llama.cpp', engine: 'llama.cpp', ref: join(this.home, 'models', jev.file), binary, sizeBytes: jev.size }+ let started: AppEngineRecord+ try {+ started = { spec: 1, modelId: jev.id, grid, name: jev.name, ...await ops.start(model, JEV_CONTEXT, join(this.options.stateDir, 'logs')) }+ } catch (error) {+ throw new ModelError(error instanceof AppStartError ? error.message : 'The model could not start. Try again.')+ }+ await writeAppRecords(this.appRecordsFile, [...(await readAppRecords(this.appRecordsFile)).filter(r => !(r.modelId === jev.id && r.grid === grid)), started])+ const named = this.options.machineName?.()?.trim()+ const joined = await this.run(['--remote', 'join', grid, '--at', `http://127.0.0.1:${started.port}/v1`, '-m', started.served,+ '--advertise-as', started.alias, '--max-concurrency', '1', ...(named && validArg(named) ? ['--name', named] : [])], undefined, 10 * 60_000)+ if (!joined.ok) { await takeDown(started); throw new ModelError('The model could not join your grid. Try again.') }+ await change('verifying')+ try { await this.verifyDecision(grid, started.alias) } catch (error) {+ await takeDown(started)+ throw error instanceof ModelError ? error : new ModelError('The model did not answer. Try again.')+ }+ }+ }+ operation.phase = 'done'+ delete operation.progress+ await this.save(grid, operation)+ }++ /** Grid's llama-server, brought up to a build that serves Jev models first when it is older (or missing). */+ private async jevEngine(change: (stage: ModelOperation['stage']) => Promise<void>,+ must: (args: string[], message: string) => Promise<void>): Promise<string> {+ const override = this.processEnv.LLAMA_SERVER+ if (override) {+ const build = await llamaBuild(override, this.processEnv)+ if (build !== undefined && build < MIN_JEV_BUILD) throw new ModelError(`LLAMA_SERVER is llama.cpp build ${build}; Jev models need build ${MIN_JEV_BUILD} or newer.`)+ return override+ }+ const managed = join(this.home, 'bin', 'llama-server')+ const build = binaryOnPath(managed, this.processEnv) ? await llamaBuild(managed, this.processEnv) : undefined+ if (build !== undefined && build >= MIN_JEV_BUILD) return managed+ await change('updating')+ await must(['engine', 'install', 'llama.cpp'], 'The model engine could not be updated. Try again.')+ const updated = await llamaBuild(managed, this.processEnv)+ if (updated === undefined || updated < MIN_JEV_BUILD) {+ throw new ModelError(`Grid's model engine is still too old for Jev models (build ${updated ?? 'unknown'}; they need ${MIN_JEV_BUILD} or newer). Update Grid, then try again.`)+ }+ return managed+ }++ /** One decision through the grid, as a caller would ask: the model is up when it answers one. */+ private async verifyDecision(grid: string, model: string): Promise<void> {+ const info = await this.run(['--remote', 'info', grid, '--env'])+ const { baseUrl, apiKey } = readEnvExports(info.stdout)+ if (!info.ok || !baseUrl || !apiKey) 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(`${baseUrl.replace(/\/$/, '')}/systemone`, {+ method: 'POST', headers: { authorization: `Bearer ${apiKey}`, 'content-type': 'application/json' },+ body: JSON.stringify({ model, state: 'I was charged twice. Please refund the duplicate.',+ questions: { refund: { type: 'noul', instructions: 'Is a refund requested?' } } }),+ signal: AbortSignal.timeout(30_000), redirect: 'error',+ })+ const answer = obj(obj(response.ok ? await response.json() : {}).answers).refund+ if (typeof obj(answer).noul === 'number') return+ } catch { /* registration takes 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.')+ }+private async verify(grid: string, model: string): Promise<void> {const info = await this.run(['--remote', 'info', grid, '--env'])const { baseUrl, apiKey } = readEnvExports(info.stdout)diff --git a/desktop/lib/core/models.dart b/desktop/lib/core/models.dartindex 9d476daf7..c7b674512 100644--- a/desktop/lib/core/models.dart+++ b/desktop/lib/core/models.dart@@ -1174,11 +1174,17 @@ class GridModel {/// for every other row, and always from a daemon that predates it.final GridModelUnavailable? unavailable;+ /// A Jev (System One) decision model (`kind: decision`): it answers typed questions at+ /// `/v1/systemone` and cannot chat, so no harness runs on it — the picker lists it apart and+ /// shows how to call it instead. False for every chat model, and from a daemon that predates it.+ final bool decision;+const GridModel({required this.id,required this.node,this.grid,this.unavailable,+ this.decision = false,});}@@ -1403,6 +1409,7 @@ class GridModels {node: m['node'] is String ? m['node'] as String : '',grid: grid,unavailable: GridModelUnavailable.fromWire(m['unavailable']),+ decision: m['kind'] == 'decision',),).where((m) => m.id.isNotEmpty)diff --git a/desktop/lib/models/local_model.dart b/desktop/lib/models/local_model.dartindex 708b14ff6..ea432393e 100644--- a/desktop/lib/models/local_model.dart+++ b/desktop/lib/models/local_model.dart@@ -19,9 +19,14 @@ class LocalModel {this.estTokS,this.paramsB,this.app,+ this.decision = false,});final String id, name, state;+ /// A Jev (System One) decision model (`kind: decision`): Get downloads it, updates Grid's engine when+ /// it is too old to serve one, and runs it on the grid — it is called, never a harness's model. False+ /// for every chat model, and from an older daemon.+/// The app this model was downloaded with and starts in (`Ollama`, `LM Studio`, `llama.cpp`): one found/// in that app's folder. Null for Grid's own models, and from an older daemon.final String? app;@@ -39,6 +44,7 @@ class LocalModel {/// itself on the next message, so the row says so rather than reading as a plain `running`. An/// older daemon never sends it.final bool gridAsleep;+ final bool decision;bool get running => state == 'running';/// Running, and resting until somebody sends a message — see [gridAsleep].@@ -85,6 +91,7 @@ class LocalModel {final String app when app.trim().isNotEmpty => app.trim(),_ => null,},+ decision: data['kind'] == 'decision',);}@@ -106,6 +113,7 @@ class LocalModelOperation {bool get started => phase == 'done' && action == 'start';String get label => switch (stage) {'downloading' => 'Downloading',+ 'updating' => 'Updating engine','starting' => 'Starting','verifying' => 'Testing','stopping' => 'Stopping',@@ -119,6 +127,7 @@ class LocalModelOperation {!['checking','downloading',+ 'updating','starting','verifying','stopping',diff --git a/desktop/lib/models/model_search_catalog.dart b/desktop/lib/models/model_search_catalog.dartindex 8c7bd52da..b59d12b91 100644--- a/desktop/lib/models/model_search_catalog.dart+++ b/desktop/lib/models/model_search_catalog.dart@@ -1,4 +1,5 @@import 'dart:async';+import 'dart:convert';import 'package:flutter/foundation.dart';@@ -18,7 +19,11 @@ enum ModelSearchSection {/// Models a machine of yours can download: the grid catalog's picks for it. Its heading names the/// machine and its memory ([ModelSearchCatalog.catalogHeading]); this label is its search word.catalog('Get models'),- shared('Shared with you');+ shared('Shared with you'),++ /// Jev (System One) decision models, from any grid: they answer typed questions and cannot run+ /// a harness, so they are listed last, apart from every model a harness can use.+ jev('Jev models');const ModelSearchSection(this.label);final String label;@@ -58,10 +63,15 @@ class ModelSearchEntry {final GridModel? gridModel;final String? sharedBy;+ /// A Jev (System One) decision model: called at `/v1/systemone`, never run as a harness.+ bool get isJev => gridModel?.decision == true || local?.decision == true;+ModelSearchSection get section => subscription != null? ModelSearchSection.subscriptions: api != null? ModelSearchSection.apis+ : isJev+ ? ModelSearchSection.jev: isDownload? ModelSearchSection.catalog: own@@ -266,10 +276,13 @@ class ModelSearchCatalog extends ChangeNotifier {for (final section in manager.sections) {for (final model in section.models) {final owner = section.own ? _hostFor(model.node) : null;+ // A Jev model folds only into a Jev model of yours, a chat model only into a chat one: a chat+ // row would offer a Jev model to a harness.final matches =owner?.localModels.where((local) =>+ local.decision == model.decision &&(local.downloaded || local.canStop) &&(local.name.toLowerCase() == model.id.toLowerCase() ||local.id.toLowerCase() == model.id.toLowerCase()),@@ -283,6 +296,7 @@ class ModelSearchCatalog extends ChangeNotifier {node: model.node,grid: model.grid ?? section.name,unavailable: model.unavailable,+ decision: model.decision,);if (owner != null && matches.length == 1) {served[_managedKey(owner, matches.single)] = gridModel;@@ -301,7 +315,11 @@ class ModelSearchCatalog extends ChangeNotifier {? 'On your machines': 'Shared · ${section.name}',node: owner?.machine?.machine.displayName ?? model.node,- searchAliases: [model.node, if (section.own) 'local'],+ searchAliases: [+ model.node,+ if (section.own) 'local',+ if (model.decision) ...['jev', 'decision'],+ ],own: section.own,controller: owner,gridModel: gridModel,@@ -317,9 +335,21 @@ class ModelSearchCatalog extends ChangeNotifier {);}}+ // A Jev model a machine of yours serves (`grid join --serve` of a decision GGUF) is listed once,+ // under Jev models: its local row would offer it to a harness, which cannot run on it.+ final deciders = {+ for (final section in manager.sections)+ if (section.own)+ for (final model in section.models)+ if (model.decision) model.id.toLowerCase(),+ };final local = [for (final owner in [manager, ..._hosts.values])- for (final model in owner.localModels) (owner: owner, model: model),+ for (final model in owner.localModels)+ if (model.decision ||+ (!deciders.contains(model.name.toLowerCase()) &&+ !deciders.contains(model.id.toLowerCase())))+ (owner: owner, model: model),];int rank(ModelManagerController owner, LocalModel model) =>owner.operationFor(model)?.active == true@@ -517,3 +547,28 @@ String gigabytesLabel(double bytes) {String thisComputerName() => defaultTargetPlatform == TargetPlatform.macOS? 'this Mac': 'this computer';++/// How to call the Jev model [model] served on [grid], as a person pastes it into a terminal: load+/// the grid's address and key with `harness grid env` (the harness's own `grid`, so no `grid` of+/// one's own is needed, nor one new enough to call a resting grid), then ask it one decision. The+/// key never appears here; the shell reads it from the variable that sets.+String jevRequest(String grid, String model) {+ final body = jsonEncode({+ 'model': model,+ 'state': 'I was charged twice. Please refund the duplicate.',+ 'questions': {+ 'refund': {'type': 'noul', 'instructions': 'Is a refund requested?'},+ },+ });+ return 'eval "\$(harness grid env ${_shellWord(grid)})"\n'+ 'curl "\$OPENAI_BASE_URL/systemone" \\\n'+ ' -H "Authorization: Bearer \$OPENAI_API_KEY" \\\n'+ ' -H "Content-Type: application/json" \\\n'+ " -d ${_shellWord(body)}";+}++/// [value] as one shell word: bare when it is plainly safe, single-quoted otherwise.+String _shellWord(String value) =>+ RegExp(r'^[A-Za-z0-9._:@/+-]+$').hasMatch(value)+ ? value+ : "'${value.replaceAll("'", r"'\''")}'";diff --git a/desktop/lib/state/swarm_search.dart b/desktop/lib/state/swarm_search.dartindex 42b788e44..4171d17ac 100644--- a/desktop/lib/state/swarm_search.dart+++ b/desktop/lib/state/swarm_search.dart@@ -250,6 +250,10 @@ class SwarmSearchController extends ChangeNotifier {? models!.catalogHeading: section.label;+ /// A Jev (System One) model's row: nothing to Use, its pane says how to call it.+ bool isJevRow(SwarmDestination? row) =>+ models?.entries[row?.modelId]?.isJev == true;+String? modelRowAction(SwarmDestination row) {final entry = models?.entries[row.modelId];if (entry == null) return null;@@ -257,6 +261,14 @@ class SwarmSearchController extends ChangeNotifier {? 'Use': canGetModel(row)? 'Get'+ : canStartJev(row)+ ? 'Start'+ // A Jev model on a grid: Enter copies how to call it — a resting grid wakes on that call,+ // so its rest is the pane's to say, not the row's.+ : entry.isJev &&+ entry.gridModel != null &&+ entry.gridModel!.unavailable == null+ ? 'Copy': null;}@@ -399,16 +411,46 @@ class SwarmSearchController extends ChangeNotifier {if (!canGetModel(row)) return null;final entry = models!.entries[row.modelId]!;final owner = entry.controller!;+ // A Jev model's Get is the whole of it — download, an engine new enough to serve it, and the model+ // on the grid — since nothing else would ever start one.await owner.control(entry.local!,- owner.supportsDownload ? 'download' : 'start',+ entry.isJev || !owner.supportsDownload ? 'start' : 'download',);return owner.error;}+ /// A Jev model of yours that is downloaded and not running: Start runs it on your grid, beside the+ /// models already there.+ bool canStartJev(SwarmDestination? row) {+ if (!isModelMode) return false;+ final entry = models?.entries[row?.modelId];+ final local = entry?.local, owner = entry?.controller;+ return entry != null &&+ entry.isJev &&+ local != null &&+ owner != null &&+ local.downloaded &&+ !local.running &&+ local.canStart &&+ owner.operationFor(local)?.active != true &&+ owner.inventoryAvailable &&+ !owner.busy &&+ owner.machine?.connectionStatus == ConnectionStatus.connected &&+ owner.machine?.needsLink == false;+ }++ Future<String?> startJev(SwarmDestination row) async {+ if (!canStartJev(row)) return null;+ final entry = models!.entries[row.modelId]!;+ await entry.controller!.control(entry.local!, 'start');+ return entry.controller!.error;+ }+String? modelUseReason(SwarmDestination? row) {final entry = models?.entries[row?.modelId];if (entry == null || canSelectModel(row)) return null;+ if (entry.isJev) return 'Jev model';if (modelSelectionEngine == null) return 'No active harness';if (entry.subscription case final subscription?) {if (subscription['engine'] != modelSelectionEngine) {@@ -534,7 +576,10 @@ class SwarmSearchController extends ChangeNotifier {}}final offered = entry?.gridModel;- if (offered == null || offered.unavailable != null) return null;+ // A Jev model answers decisions, not a harness's turns: there is nothing to run on it.+ if (offered == null || offered.unavailable != null || offered.decision) {+ return null;+ }for (final section in _modelChoices!.sections) {if (section.name != offered.grid && !(section.own && entry!.own)) {continue;@@ -592,6 +637,7 @@ class SwarmSearchController extends ChangeNotifier {return model != null &&owner != null &&entry!.own &&+ !entry.isJev &&model.downloaded &&!model.running &&model.canStart &&@@ -624,10 +670,11 @@ class SwarmSearchController extends ChangeNotifier {/// running on that machine is stopped first ([otherRunningModel]): it runs one at a time.bool canGetModelForUse(SwarmDestination? row) =>canGetModel(row) &&+ !models!.entries[row!.modelId]!.isJev &&modelSelectionEngine != null &&_modelChoices?.reachable == true &&_modelChoices?.canRunLocally(modelSelectionEngine) == true &&- models!.entries[row!.modelId]!.own;+ models!.entries[row.modelId]!.own;/// Another model of yours running on [row]'s machine — the one to stop before [row]'s can run.LocalModel? otherRunningModel(SwarmDestination? row) {@@ -1377,6 +1424,10 @@ class SwarmSearchController extends ChangeNotifier {? 'Use': canGetModel(row)? 'Get'+ : canStartJev(row)+ ? 'Start'+ : isJevRow(row) && models!.entries[row!.modelId]!.gridModel != null+ ? 'Copy request': row?.isModel == true? 'Unavailable': setupLayout && row?.isMachine == true@@ -2138,6 +2189,11 @@ class SwarmSearchController extends ChangeNotifier {if (destination.isModel &&!canSelectModel(destination) &&!canGetModel(destination)) {+ // A Jev model has nothing to Use: clicking one shows its pane, which says how to call it.+ if (isJevRow(destination)) {+ final index = rows.indexWhere((row) => row.id == destination.id);+ if (index >= 0 && index != cursor) move(index - cursor);+ }return null;}if (setupLayout && (destination.isMachine || destination.isModel)) {diff --git a/desktop/lib/widgets/swarm_resource_preview.dart b/desktop/lib/widgets/swarm_resource_preview.dartindex 2b9aff214..517ff4a58 100644--- a/desktop/lib/widgets/swarm_resource_preview.dart+++ b/desktop/lib/widgets/swarm_resource_preview.dart@@ -60,6 +60,13 @@ class SearchPreviewControls {}}+/// A block of text a person copies as it is — a command — drawn monospace and selectable by+/// [_SwarmResourcePreviewState._details].+class _Code {+ const _Code(this.text);+ final String text;+}+class _ResourceAction {const _ResourceAction(this.label,@@ -400,6 +407,17 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {final selected = row!;unawaited(_run(() => widget.search.getModel(selected)));}+ // A Jev model has nothing to Use: Enter starts one of yours that is downloaded, and copies+ // how to call one that is on a grid.+ if (row != null && widget.search.canStartJev(row)) {+ final selected = row!;+ unawaited(_run(() => widget.search.startJev(selected)));+ } else if (widget.search.models?.entries[row?.modelId] case final jev?+ when jev.isJev &&+ jev.gridModel != null &&+ !widget.search.canGetModel(row)) {+ _copyJevRequest(jev);+ }if (row?.isCreate == true) _addApi();// Model rows perform Use/Get directly; unavailable rows stay put.return true;@@ -727,9 +745,12 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {widget.search.canGetModel(row) ||widget.search.isModelDownloadsRow(row) ||widget.search.isGridSetupRow(row) ||- widget.search.canExpandApi(row))+ widget.search.canExpandApi(row) ||+ widget.search.isJevRow(row))'$enter ${managing? 'select'+ : widget.search.isJevRow(row)+ ? widget.search.actionLabel(row): widget.search.canSelectModel(row)? 'Use': widget.search.canGetModel(row)@@ -840,6 +861,48 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {final local = model?.local;final api = model?.api;final owner = model?.controller ?? catalog.manager;+ if (model case final jev? when jev.isJev) {+ final mine = jev.local;+ final operating =+ mine != null && owner.operationFor(mine)?.active == true;+ return [+ if (mine != null && mine.canStop)+ _ResourceAction(+ 'Stop',+ busy || operating || owner.busy+ ? null+ : () => unawaited(+ _run(() async {+ await owner.control(mine, 'stop');+ return owner.error;+ }),+ ),+ command: 'picker.model_stop',+ )+ else if (mine != null && !mine.downloaded)+ _ResourceAction(+ 'Get',+ !busy && search.canGetModel(selected)+ ? () => unawaited(_run(() => search.getModel(selected)))+ : null,+ command: 'picker.model_download',+ )+ else if (mine != null)+ _ResourceAction(+ 'Start',+ !busy && search.canStartJev(selected)+ ? () => unawaited(_run(() => search.startJev(selected)))+ : null,+ command: 'picker.model_start',+ ),+ if (jev.gridModel != null)+ _ResourceAction(+ 'Copy request',+ () => _copyJevRequest(jev),+ command: 'picker.accept',+ ),+ ];+ }if (local != null) {final enabled =!busy &&@@ -1200,6 +1263,7 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {final opActive = operation?.active == true;// API entries have their own dedicated preview; keep main's dispatch.if (entry.api != null) return _apiPreview(entry);+ if (entry.isJev) return _jevPreview(entry);String windowLabel(double? seconds) {if (seconds == null) return '—';@@ -1509,6 +1573,88 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {], controls: true);}+ /// A Jev model's pane: what it is, and how to call it — no harness runs on it.+ Widget _jevPreview(ModelSearchEntry entry) {+ final served = entry.gridModel;+ final local = entry.local;+ final catalog = widget.search.models!;+ final owner = entry.controller ?? catalog.manager;+ final grid = served?.grid ?? '';+ final state = catalog.manager.sections+ .where((section) => section.name == grid)+ .firstOrNull+ ?.state;+ final operation = local == null ? null : owner.operationFor(local);+ final here = thisComputerName();+ final machine = local != null+ ? '${here[0].toUpperCase()}${here.substring(1)}'+ : entry.node;+ return _details([+ entry.name,+ ['Jev model', ?machine, if (grid.isNotEmpty) grid].join(' · '),+ '',+ 'Answers questions about a state with probabilities: a choice between named options, '+ 'yes or no, or a score. It does not chat, so no harness runs on it.',+ if (local != null) ...[+ '',+ if (operation?.active == true)+ catalog.localStatus(local, controller: owner)+ else if (operation?.error case final error?)+ error+ else if (local.running)+ 'Running on $here, on your grid.'+ else if (local.downloaded)+ 'Downloaded. Start runs it on your grid, beside the models already running there.'+ else+ 'Get downloads it${local.sizeBytes == null ? '' : ' (${gigabytesLabel(local.sizeBytes!)})'}, '+ 'updates Grid\'s model engine first if it is too old to serve Jev models, and runs it '+ 'on your grid, beside the models already running there.',+ '',+ if (local.sizeBytes case final size?) ('Size', gigabytesLabel(size)),+ ('Runs in', 'Grid\'s llama.cpp'),+ ],+ if (served == null)+ ...[]+ else if (served.unavailable case final away?) ...[+ '',+ '${away.machine} seems offline. It answers again when that computer is back.',+ ] else if (state == GridSectionState.asleep ||+ state == GridSectionState.waking) ...[+ '',+ 'Its grid is resting. Your first request wakes it, which takes a few seconds.',+ ],+ if (served != null) ...[+ '',+ ('Model', entry.name),+ if (grid.isNotEmpty) ('Grid', grid),+ ('Endpoint', 'POST \$OPENAI_BASE_URL/systemone'),+ '',+ 'Call it from a terminal:',+ _Code(jevRequest(grid, entry.name)),+ ?_messages[row!.id],+ '',+ 'The first line loads this grid\'s address and key into your shell; the key is never '+ 'shown here. Each question is a choice (named options), a noul (yes or no) or a score '+ '(2–10 ordered levels).',+ ],+ ], controls: true);+ }++ void _copyJevRequest(ModelSearchEntry entry) {+ final id = row?.id;+ unawaited(+ Clipboard.setData(+ ClipboardData(+ text: jevRequest(entry.gridModel?.grid ?? '', entry.name),+ ),+ ).then((_) {+ if (mounted && id != null) {+ setState(() => _messages[id] = 'Copied. Paste it into a terminal.');+ }+ }),+ );+ }+Widget _machinePreview() {final machine = app.stateOf(row!.machineId!);if (machine == null) return _details([row!.title, 'Unavailable']);@@ -1592,6 +1738,22 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {label,value,),+ final _Code code => Container(+ margin: const EdgeInsets.only(top: 4, bottom: 4),+ padding: const EdgeInsets.all(10),+ decoration: BoxDecoration(+ color: DesktopChrome.field,+ border: Border.all(color: DesktopChrome.rim),+ borderRadius: BorderRadius.circular(+ DesktopChrome.controlRadius,+ ),+ ),+ child: SelectableText(+ code.text,+ style: DesktopChrome.text(size: 11.5)+ .copyWith(fontFamily: grid.AppType.monoFamily),+ ),+ ),final line => Padding(padding: EdgeInsets.only(bottom: i == 0 ? 5 : 3),child: Text(@@ -1625,6 +1787,10 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {for (var i = 0; i < lines.length; i++)switch (lines[i]) {'' => SizedBox(height: cell.height),+ final _Code code => SelectableText(+ code.text,+ style: terminalContentStyle(color: theme.foreground),+ ),(final String label, final String value) => Row(crossAxisAlignment: CrossAxisAlignment.start,children: [diff --git a/desktop/lib/widgets/swarm_switcher.dart b/desktop/lib/widgets/swarm_switcher.dartindex 201f8320c..4e47f7ae9 100644--- a/desktop/lib/widgets/swarm_switcher.dart+++ b/desktop/lib/widgets/swarm_switcher.dart@@ -565,11 +565,13 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {if (search.modelSection(row) == section) index,];// An empty section still says it is there, so there is somewhere to add to — except the- // downloads, which a machine with the whole catalog, or none, has nothing under, and what is- // shared with you while Grid is not set up: the Set up row under Your models stands for it.+ // downloads, which a machine with the whole catalog, or none, has nothing under, what is+ // shared with you while Grid is not set up (the Set up row under Your models stands for+ // it), and Jev models, which nobody adds from here.if (indices.isEmpty &&(search.matchQuery.trim().isNotEmpty ||section == ModelSearchSection.catalog ||+ section == ModelSearchSection.jev ||(section == ModelSearchSection.shared &&search.gridSetupOffered))) {continue;@@ -1923,6 +1925,7 @@ class _SearchRowContentState extends State<_SearchRowContent> {!widget.search.isModelDownloadsRow(row) &&!widget.search.isGridSetupRow(row) &&!widget.search.canExpandApi(row) &&+ !widget.search.isJevRow(row) &&!widget.search.canSelectModel(row) &&!widget.search.canGetModel(row))? theme.foreground.withValues(alpha: .28)diff --git a/desktop/test/local_model_picker_test.dart b/desktop/test/local_model_picker_test.dartindex ee1e521b2..19dcd2ef7 100644--- a/desktop/test/local_model_picker_test.dart+++ b/desktop/test/local_model_picker_test.dart@@ -709,4 +709,106 @@ void main() {}},);++ testWidgets(+ 'Get on a Jev model starts it, never moves the harness, and then it is one Jev row to stop or call',+ (tester) async {+ const laya = 'jev:ggml-org/Laya-GGUF';+ final app = await _localFixture(onModel: 'Qwen3.6-35B-A3B');+ try {+ app.localInventory = {+ ..._inventory(),+ 'models': [+ ...(_inventory()['models'] as List),+ {+ 'id': laya,+ 'name': 'laya-english',+ 'kind': 'decision',+ 'state': 'available',+ 'sizeBytes': 449397600,+ 'quant': 'Q8_0',+ 'canStart': true,+ },+ ],+ };+ await app.modelManager.refresh(force: true);+ final picker = await _open(tester, app);+ var row = _row(picker, 'laya-english');+ expect(picker.modelSection(row), ModelSearchSection.jev);+ expect(picker.canSelectModel(row), isFalse);+ expect(picker.canGetModelForUse(row), isFalse);+ expect(picker.modelRowAction(row), 'Get');+ expect(picker.actionLabel(row), 'Get');+ picker.move(picker.rows.indexOf(row) - picker.cursor);+ await tester.pumpAndSettle();+ expect(+ find.descendant(+ of: find.byType(SwarmResourcePreview),+ matching: find.textContaining(+ "updates Grid's model engine first if it is too old to serve Jev models",+ ),+ ),+ findsOneWidget,+ );++ expect(find.text('Enter Get · Tab controls'), findsOneWidget);+ // Get is the whole of it — a start, which downloads, updates and runs — not a download alone,+ // and no harness is moved onto it.+ await key(tester, LogicalKeyboardKey.enter);+ await tester.pumpAndSettle();+ expect(app.actions, [(machine: 'm', model: laya, start: true)]);+ expect(app.downloads, isEmpty);+ expect(app.selections, isEmpty);++ // Running, and listed by the own grid as a Jev model: one row, under Jev models, to stop or call.+ final running = app.localInventory;+ app.localInventory = {+ ...running,+ 'models': [+ for (final model in running['models'] as List)+ if ((model as Map<String, dynamic>)['id'] == laya)+ {+ ...model,+ 'state': 'running',+ 'canStart': false,+ 'canStop': true,+ }+ else+ model,+ ],+ };+ app.inventory = const GridModels(+ gridName: 'home',+ models: [+ GridModel(id: 'Qwen3.6-35B-A3B', node: 'This Mac'),+ GridModel(id: 'laya-english', node: 'This Mac', decision: true),+ ],+ );+ await app.modelManager.refresh(force: true);+ await tester.pumpAndSettle();+ final layas = picker.rows+ .where((r) => r.title == 'laya-english')+ .toList();+ expect(layas, hasLength(1));+ row = layas.single;+ expect(picker.modelSection(row), ModelSearchSection.jev);+ expect(picker.modelRowAction(row), 'Copy');+ picker.move(picker.rows.indexOf(row) - picker.cursor);+ await tester.pumpAndSettle();+ expect(+ find.byKey(const ValueKey('resource-action:picker.model_stop')),+ findsOneWidget,+ );+ expect(+ find.byKey(const ValueKey('resource-action:picker.accept')),+ findsOneWidget,+ );+ expect(_inPreview(jevRequest('home', 'laya-english')), findsOneWidget);+ expect(tester.takeException(), isNull);+ } finally {+ await tester.pumpWidget(const SizedBox());+ app.dispose();+ }+ },+ );}diff --git a/desktop/test/resource_picker_test.dart b/desktop/test/resource_picker_test.dartindex 1c9bacf09..4df587801 100644--- a/desktop/test/resource_picker_test.dart+++ b/desktop/test/resource_picker_test.dart@@ -14,7 +14,7 @@ import 'package:harness/auth/cli_link.dart';import 'package:harness/core/models.dart';import 'package:harness/models/api_connections_controller.dart';import 'package:harness/models/model_search_catalog.dart'- show ModelSearchSection;+ show ModelSearchSection, jevRequest;import 'package:harness/widgets/api_picker_form.dart';import 'package:harness/widgets/desktop_chrome.dart';import 'package:harness/shared/theme/app_theme.dart' as grid;@@ -983,6 +983,190 @@ void main() {},);+ testWidgets(+ 'Jev models are listed apart, and their pane says how to call them instead of offering Use',+ (tester) async {+ final app = _ModelSelectionApp()+ ..inventory = const GridModels(+ gridName: 'home',+ models: [],+ grids: [+ GridSection(+ name: 'home',+ own: true,+ models: [+ GridModel(id: 'qwen3.8-27b', node: 'mac.lan'),+ GridModel(id: 'laya-english', node: 'mac.lan', decision: true),+ ],+ ),+ GridSection(+ name: 'Team',+ own: false,+ state: GridSectionState.asleep,+ models: [+ GridModel(id: 'nimble', node: 'shared.lan', decision: true),+ ],+ ),+ ],+ );+ await fixture(provided: app);+ app.machineStates['m']!+ ..localEndpoint = LocalCliEndpoint(+ computerId: 'fixture',+ wsUri: Uri.parse('ws://fixture.invalid'),+ protocolVersion: 1,+ terminalProtocolVersion: 3,+ )+ ..agents.add(+ const Agent(+ id: 'a69',+ name: 'Current harness',+ engine: 'codex',+ terminalAvailable: true,+ ),+ );+ // The own grid's Jev model is served by another machine of yours (`grid join --serve`), whose+ // model list has it running: it is still listed once, under Jev models, never as a local row.+ app.machineStates['other']!+ ..machine = const Machine(+ machineId: 'other',+ authMode: MachineAuthMode.remote,+ name: 'M2',+ hostname: 'mac.lan',+ )+ ..connectionStatus = ConnectionStatus.connected+ ..nodeOnline = true;+ app.machineInventories['other'] = {+ 'models': [+ {+ 'id': 'local:Laya-English-Q8_0.gguf',+ 'name': 'laya-english',+ 'state': 'running',+ 'canStop': true,+ 'sizeBytes': 449397600,+ },+ ],+ };+ String? copied;+ tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(+ SystemChannels.platform,+ (call) async {+ if (call.method == 'Clipboard.setData') {+ copied = (call.arguments as Map)['text'] as String;+ }+ return null;+ },+ );+ addTearDown(+ () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(+ SystemChannels.platform,+ null,+ ),+ );+ final map = MemoryKeymap();+ try {+ await configured.mount(tester, app, map);+ await key(tester, LogicalKeyboardKey.keyI, cmd: true);+ final rows = search(tester).rows.where((row) => row.isModel);+ String section(String title) => search(tester)+ .modelSection(rows.firstWhere((row) => row.title.startsWith(title)))+ .label;+ // From the own grid and a shared one alike, a Jev model is under its own heading, last.+ expect(section('laya-english'), 'Jev models');+ expect(section('nimble'), 'Jev models');+ expect(section('qwen3.8-27b'), isNot('Jev models'));+ expect(+ rows.where((row) => row.title.startsWith('laya-english')),+ hasLength(1),+ reason: rows.map((row) => row.title).join('\n'),+ );+ expect(ModelSearchSection.values.last, ModelSearchSection.jev);++ // Clicking a Jev row shows how to call it, and neither copies nor moves the harness.+ expect(search(tester).isJevRow(search(tester).selected), isFalse);+ final layaRow = find.text('laya-english', findRichText: true);+ await tester.scrollUntilVisible(+ layaRow,+ 100,+ scrollable: find+ .ancestor(+ of: find.text('Your models', findRichText: true),+ matching: find.byType(Scrollable),+ )+ .first,+ );+ await tester.tap(layaRow);+ await tester.pumpAndSettle();+ expect(search(tester).selected!.title, 'laya-english');+ expect(find.text(jevRequest('home', 'laya-english')), findsOneWidget);+ expect(copied, isNull);+ expect(app.selections, isEmpty);++ await tester.enterText(field, ':laya');+ await tester.pumpAndSettle();+ final laya = search(tester).selected!;+ expect(laya.title, 'laya-english');+ expect(search(tester).isJevRow(laya), isTrue);+ expect(search(tester).canSelectModel(laya), isFalse);+ expect(search(tester).modelRowAction(laya), 'Copy');+ expect(search(tester).actionLabel(laya), 'Copy request');+ expect(find.text('Call it from a terminal:'), findsOneWidget);+ expect(find.text(jevRequest('home', 'laya-english')), findsOneWidget);+ expect(+ find.text('Enter Copy request · Tab controls'),+ findsOneWidget,+ );++ await key(tester, LogicalKeyboardKey.enter);+ await tester.pumpAndSettle();+ expect(copied, jevRequest('home', 'laya-english'));+ expect(find.text('Copied. Paste it into a terminal.'), findsOneWidget);+ expect(app.selections, isEmpty);+ // An awake grid's pane says nothing of rest; a resting one says the call wakes it, and its+ // row still offers the copy rather than reading as unavailable.+ expect(find.textContaining('resting'), findsNothing);+ await tester.enterText(field, ':nimble');+ await tester.pumpAndSettle();+ expect(search(tester).selected!.title, startsWith('nimble'));+ expect(search(tester).modelRowAction(search(tester).selected!), 'Copy');+ expect(+ find.text(+ 'Its grid is resting. Your first request wakes it, which takes a few seconds.',+ ),+ findsOneWidget,+ );+ expect(tester.takeException(), isNull);+ } finally {+ await tester.pumpWidget(const SizedBox());+ app.dispose();+ map.dispose();+ }+ },+ );++ test(+ 'a Jev request loads the grid\'s key from its env and never names it',+ () {+ final request = jevRequest('home', 'laya-english');+ expect(request, startsWith('eval "\$(harness grid env home)"\n'));+ expect(request, contains('curl "\$OPENAI_BASE_URL/systemone"'));+ expect(request, contains('Authorization: Bearer \$OPENAI_API_KEY'));+ expect(request, contains('"model":"laya-english"'));+ // A name a shell would read as syntax is quoted; a quote in it cannot end the word early.+ expect(+ jevRequest('my grid', "o'brien"),+ allOf(+ contains("harness grid env 'my grid')"),+ contains(+ r'"model":"o'+ "'\\''"+ 'brien"',+ ),+ ),+ );+ },+ );+testWidgets('platform picker and command shortcuts',(tester) async {diff --git a/docs/cli.md b/docs/cli.mdindex 0f77221da..2f772433a 100644--- a/docs/cli.md+++ b/docs/cli.md@@ -25,6 +25,7 @@ works the same on a headless Linux server; the app is not required on a machine,| `harness remote` | From a Harness terminal tile: choose another of your machines (linking it on the spot if needed), open a terminal there and move this tile to it. || `harness devices [list] [--json]` · `show <#\|fp>` · `remove <fp>` · `history [--json]` · `dismiss [<#\|fp>]` · `rebaseline [--yes]` | The account's devices as this machine verified them (below): list · one in full · take one out on every device · every add and removal, newest first · mark new ones seen · review and trust a frozen list again. || `harness grid login [--force] [--json]` · `harness grid logout` | Sign the `grid` CLI in with this computer's account, no second browser. |+| `harness grid env <grid>` | `<grid>`'s relay address and key as shell exports, through the harness's own `grid`: `eval "$(harness grid env <grid>)"` before calling a Jev model at `$OPENAI_BASE_URL/systemone`. || `harness flash [flags]` | Re-flash a plugged-in Harness device over USB. Flags pass straight to the flasher. || `harness autonomous-device discover\|status\|list\|pair\|revoke` | Pair Autonomous OS devices found on the LAN, directly, with no relay. |diff --git a/tui/src/input.rs b/tui/src/input.rsindex dc5e8b9a3..9c8c3d1b3 100644--- a/tui/src/input.rs+++ b/tui/src/input.rs@@ -677,7 +677,12 @@ fn fill_rows(app: &App, kind: &PickerKind, picker: &mut Picker) {if let Some(want) = in_use.or(top) { picker.select(&want); picker.placed = picker.selected_id.clone() }}picker.right_half = true;- picker.hints = vec![("enter", "use · get"), ("C-s", "stop a local model")];+ // (On a Jev model there is nothing to use: Enter copies how to call it.)+ picker.hints = match picker.selected_id.as_deref() {+ Some(id) if id.starts_with("mv:jev:") => vec![("enter", "copy how to call it")],+ Some(id) if id.starts_with("mv:jevlocal:") => vec![("enter", "get · start · copy"), ("C-s", "stop it")],+ _ => vec![("enter", "use · get"), ("C-s", "stop a local model")],+ };picker.empty = if crate::models::target(app).is_none() { crate::models::no_target_why(app) } else { "Loading its models…".into() };picker.status = app.focused().and_then(|f| app.panes.get(&f)).and_then(|p| app.fleet.agent(&p.machine_id, &p.agent_id)).map(|a| a.name.clone()).unwrap_or_default();}diff --git a/tui/src/keys.rs b/tui/src/keys.rsindex 306a2eecd..c74618e6b 100644--- a/tui/src/keys.rs+++ b/tui/src/keys.rs@@ -158,7 +158,7 @@ impl Keymap {b(ch('T'), "new-terminal", false, "New terminal (a shell) beside this pane");b(ch('a'), "next-harness", false, "Go to the next harness that needs you");b(ch('A'), "choose-tree -a", false, "Harnesses waiting on you — answer from the list");- b(ch('I'), "choose-tree -i", false, "Models: subscriptions, APIs, your models, downloads, shared");+ b(ch('I'), "choose-tree -i", false, "Models: subscriptions, APIs, your models, downloads, shared, Jev");b(ch('S'), "choose-tree -S", false, "The Harness Store");b(ch('g'), "command-prompt -p (send) { send-task \"%%\" }", false, "Send a task — Harness picks the harness");b(ch('B'), "command-prompt -p (broadcast) { broadcast \"%%\" }", false, "Send one message to every harness in this window");diff --git a/tui/src/models.rs b/tui/src/models.rsindex 3b2e1c04a..930176cd8 100644--- a/tui/src/models.rs+++ b/tui/src/models.rs@@ -51,13 +51,13 @@ impl Operation {pub fn parse(v: &Value) -> Option<Operation> {let s = |k: &str| v.get(k).and_then(Value::as_str).map(str::to_string);let (action, stage, phase) = (s("action")?, s("stage")?, s("phase")?);- if !["download", "start", "stop"].contains(&action.as_str()) || !["checking", "downloading", "starting", "verifying", "stopping"].contains(&stage.as_str()) || !["running", "done", "failed"].contains(&phase.as_str()) { return None }+ if !["download", "start", "stop"].contains(&action.as_str()) || !["checking", "downloading", "updating", "starting", "verifying", "stopping"].contains(&stage.as_str()) || !["running", "done", "failed"].contains(&phase.as_str()) { return None }Some(Operation { id: s("id")?, model: s("modelId")?, action, stage, phase, progress: v.get("progress").and_then(num).map(|p| p.clamp(0.0, 1.0)), error: s("error") })}pub fn active(&self) -> bool { self.phase == "running" }pub fn failed(&self) -> bool { self.phase == "failed" }pub fn label(&self) -> &'static str {- match self.stage.as_str() { "downloading" => "Downloading", "starting" => "Starting", "verifying" => "Testing", "stopping" => "Stopping", _ => "Checking" }+ match self.stage.as_str() { "downloading" => "Downloading", "updating" => "Updating engine", "starting" => "Starting", "verifying" => "Testing", "stopping" => "Stopping", _ => "Checking" }}/// `Downloading 42%`: what a row and its preview say while it runs.pub fn word(&self) -> String { match self.progress { Some(p) => format!("{} {}%", self.label(), (p * 100.0).floor() as u32), None => self.label().to_string() } }@@ -75,6 +75,9 @@ pub struct LocalModel {/// The app it runs in: `Ollama`, `LM Studio` or `llama.cpp` for one that app downloaded, `Grid`/// for Grid's own engine (absent from an older daemon).pub app: Option<String>,+ /// A Jev (System One) model (`kind: decision`): Get downloads it, updates Grid's engine when too old+ /// to serve one, and runs it on the grid. Listed under [JEV]; never a harness's model.+ pub decision: bool,}impl LocalModel {@@ -85,7 +88,7 @@ impl LocalModel {size: num(&v["sizeBytes"]), quant: text(&v["quant"]), recommended: v["recommended"] == true, can_start: v["canStart"] == true, can_stop: v["canStop"] == true,tok_s: num(&v["tokensPerSecond"]), requests: num(&v["requests"]), window_secs: num(&v["windowSeconds"]),context: num(&v["contextWindow"]), est_tok_s: num(&v["estTokS"]), params_b: num(&v["paramsB"]),- operation: Operation::parse(&v["operation"]), asleep: v["gridAsleep"] == true, app: text(&v["app"]), id,+ operation: Operation::parse(&v["operation"]), asleep: v["gridAsleep"] == true, app: text(&v["app"]), decision: v["kind"] == "decision", id,})}pub fn running(&self) -> bool { self.state == "running" }@@ -120,8 +123,10 @@ pub fn parse_local(reply: &Value) -> Option<Snapshot> {}/// A model a grid serves; `offline` names the computer when every one serving it seems offline.+/// `decision`: a Jev (System One) model (`kind: decision`) — called at `/v1/systemone`, never a+/// harness's model, so it is listed under [JEV] and Enter copies how to call it.#[derive(Clone, Debug, PartialEq)]-pub struct GridModel { pub id: String, pub node: String, pub offline: Option<String> }+pub struct GridModel { pub id: String, pub node: String, pub offline: Option<String>, pub decision: bool }/// One grid this computer is signed into: the account's own, or a shared one, and how it answered/// the daemon's last look (`awake`, `asleep`, `waking`, `unknown`; empty from an older daemon).@@ -148,7 +153,7 @@ pub fn parse_grids(reply: &Value) -> Grids {Value::Bool(true) => Some(node.clone()),_ => None,};- Some(GridModel { id, node, offline })+ Some(GridModel { id, node, offline, decision: m["kind"] == "decision" })}).collect::<Vec<_>>();let mut sections: Vec<Section> = reply["grids"].as_array().into_iter().flatten().filter_map(|g| Some(Section {name: text(&g["name"])?, own: g["own"] == true, models: models(&g["models"]), state: g["state"].as_str().unwrap_or("").to_string(),@@ -632,6 +637,61 @@ fn grid_row(app: &App, s: &Section, x: &GridModel, t: Option<&Target>, group: &s.right(word)}+/// A Jev model's row: its machine and grid, and what Enter does — copy how to call it.+fn jev_row(s: &Section, x: &GridModel) -> Row {+ let (dot, color) = if x.offline.is_some() { ("· ", theme::MUTED) } else { ("◆ ", theme::SOFT) };+ Row::new(format!("mv:jev:{}\t{}\t{}", s.name, x.node, x.id), x.id.clone()).group(JEV)+ .extra(format!("{} {} jev decision", s.name, x.node))+ .lead(vec![span(dot, fg(color))])+ .detail(vec![span([x.node.as_str(), s.name.as_str()].into_iter().filter(|w| !w.is_empty()).collect::<Vec<_>>().join(" · "), fg(theme::MUTED))])+ .right(if x.offline.is_some() { "Offline" } else { "Copy" })+}++/// A Jev model of this computer's: what Enter does with it — Get, Start, or copy how to call it.+fn jev_local_row(app: &App, m: &LocalModel) -> Row {+ let op = app.models_view.op_for(&app.fleet.local_id, m).filter(|o| o.active() || o.failed());+ let word = match (op, jev_local_grid(app, m)) {+ (Some(o), _) if o.active() => o.word(),+ (Some(_), _) => "Failed".to_string(),+ (None, Some(_)) => "Copy".into(),+ _ if m.running() => "Running".into(),+ _ if m.downloaded() => "Start".into(),+ _ => "Get".into(),+ };+ let (dot, color) = if m.running() { ("◆ ", theme::accent()) } else if m.downloaded() { ("· ", theme::SOFT) } else { ("↓ ", theme::MUTED) };+ let detail = [this_computer().to_string(), m.size.map(gb).unwrap_or_default()].into_iter().filter(|w| !w.is_empty()).collect::<Vec<_>>().join(" · ");+ Row::new(format!("mv:jevlocal:{}", m.id), m.name.clone()).group(JEV)+ .extra(format!("{} local jev decision", m.id))+ .lead(vec![span(dot, fg(color))])+ .detail(vec![span(detail, fg(theme::MUTED))])+ .right(word)+}++/// The own grid a running Jev model of this computer's is listed on, by name — where it can be called.+fn jev_local_grid(app: &App, m: &LocalModel) -> Option<String> {+ if !m.running() { return None }+ let g = app.models_view.grids.get(&app.fleet.local_id)?;+ g.sections.iter().find(|s| s.own && s.models.iter().any(|x| x.decision && x.id.eq_ignore_ascii_case(&m.name))).map(|s| s.name.clone())+}++/// How to call the Jev model [model] on [grid] from a terminal: load the grid's address and key with+/// `harness grid env` (the harness's own `grid`, so none of one's own is needed, nor one new enough to+/// call a resting grid), then ask one decision. The key is never in it; the shell reads the variable.+pub fn jev_request(grid: &str, model: &str) -> String {+ // (Written in the order a person reads it — model, state, questions — as the desktop's is.)+ let body = format!(r#"{{"model":{},"state":{},"questions":{}}}"#, json!(model),+ json!("I was charged twice. Please refund the duplicate."),+ r#"{"refund":{"type":"noul","instructions":"Is a refund requested?"}}"#);+ format!("eval \"$(harness grid env {})\"\ncurl \"$OPENAI_BASE_URL/systemone\" \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -d {}",+ shell_word(grid), shell_word(&body))+}++/// [value] as one shell word: bare when plainly safe, single-quoted otherwise.+fn shell_word(value: &str) -> String {+ if !value.is_empty() && value.chars().all(|c| c.is_ascii_alphanumeric() || "._:@/+-".contains(c)) { value.to_string() }+ else { format!("'{}'", value.replace('\'', "'\\''")) }+}+fn sub_word(app: &App, sub: &Sub, t: Option<&Target>) -> String {if t.is_some_and(|t| t.engine == sub.engine) && switching_for(app, t) == Some("") { return SWITCHING.into() }match sub_payload(app, sub, t) { Ok(_) => "Use".into(), Err(why) if why == IN_USE => "✓ In use".into(), Err(_) => String::new() }@@ -663,9 +723,11 @@ const SUBSCRIPTIONS: &str = "Subscriptions";const APIS: &str = "APIs";const YOUR_MODELS: &str = "Your models";const SHARED: &str = "Shared with you";+/// Jev (System One) decision models from every grid, last: none of them can run a harness.+const JEV: &str = "Jev models";/// The rows of the Models view: the desktop picker's sections in its order (`model_search_catalog.dart`)-/// — Subscriptions, APIs, Your models, the downloads for this computer, Shared with you — drawn from+/// — Subscriptions, APIs, Your models, the downloads for this computer, Shared with you, Jev models — drawn from/// the top as the desktop's are (`settings::top_down`). [query]: what is typed (a search lists what/// "More models" and a folded API hide).pub fn rows(app: &App, query: &str) -> Vec<Row> {@@ -716,7 +778,7 @@ pub fn rows(app: &App, query: &str) -> Vec<Row> {out.push(note("engine", &format!("{} can only run on its own login.", engine_label(&t.engine)), YOUR_MODELS));}let own = |g: &Grids| -> Vec<(Section, GridModel)> {- g.sections.iter().filter(|s| s.own).flat_map(|s| s.models.iter().map(move |x| (s.clone(), x.clone()))).collect()+ g.sections.iter().filter(|s| s.own).flat_map(|s| s.models.iter().filter(|x| !x.decision).map(move |x| (s.clone(), x.clone()))).collect()};match snap {None => {@@ -727,7 +789,12 @@ pub fn rows(app: &App, query: &str) -> Vec<Row> {Some(s) => {if let Some(n) = &s.notice { out.push(note("notice", n, YOUR_MODELS)) }let rank = |m: &LocalModel| if v.op_for(&machine, m).is_some_and(Operation::active) || v.pending.as_ref().is_some_and(|p| p.1 == m.id) { 0 } else if m.running() { 1 } else { 2 };- let mut mine: Vec<(u8, usize, Row)> = s.models.iter().enumerate().filter(|(_, m)| m.downloaded() || m.can_stop)+ // (A Jev model this computer serves is listed once, under Jev models: as a local row it+ // would be offered to a harness, which cannot run on it.)+ let deciders: Vec<String> = v.grids.get(&machine).into_iter().flat_map(|g| g.sections.iter().filter(|s| s.own))+ .flat_map(|s| s.models.iter().filter(|x| x.decision).map(|x| x.id.to_lowercase())).collect();+ let decides = |m: &LocalModel| deciders.iter().any(|d| d.eq_ignore_ascii_case(&m.id) || d.eq_ignore_ascii_case(&m.name));+ let mut mine: Vec<(u8, usize, Row)> = s.models.iter().enumerate().filter(|(_, m)| (m.downloaded() || m.can_stop) && !m.decision && !decides(m)).map(|(i, m)| (rank(m), i, local_row(app, m, t, YOUR_MODELS))).collect();mine.sort_by_key(|(r, i, _)| (*r, *i));// (This computer's running ones are listed by their local names, above.)@@ -746,7 +813,7 @@ pub fn rows(app: &App, query: &str) -> Vec<Row> {if let Some(s) = snap {let head = catalog_heading(snap);let busy = |m: &LocalModel| v.op_for(&machine, m).is_some_and(Operation::active) || v.pending.as_ref().is_some_and(|p| p.1 == m.id);- let (now, rest): (Vec<&LocalModel>, Vec<&LocalModel>) = s.models.iter().filter(|m| !m.downloaded() && !m.can_stop).partition(|m| busy(m));+ let (now, rest): (Vec<&LocalModel>, Vec<&LocalModel>) = s.models.iter().filter(|m| !m.downloaded() && !m.can_stop && !m.decision).partition(|m| busy(m));let shown = if v.more || searching { rest.len() } else { rest.len().min(SHOWN_DOWNLOADS) };out.extend(now.iter().chain(rest.iter().take(shown)).map(|m| local_row(app, m, t, &head)));if !searching && rest.len() > SHOWN_DOWNLOADS {@@ -763,7 +830,8 @@ pub fn rows(app: &App, query: &str) -> Vec<Row> {// (A grid with no model to show is not shown — "Nobody was serving here…" says nothing// you can use; one that is resting with models to wake keeps its "Show models".)let asleep_empty = s.state == "asleep" && !words.offer_wake && !v.asking.contains(&s.name);- if s.models.is_empty() && (searching || asleep_empty || (words.subtitle.is_none() && words.sentence.is_none() && !words.offer_wake)) { continue }+ let chat: Vec<&GridModel> = s.models.iter().filter(|x| !x.decision).collect();+ if chat.is_empty() && (searching || asleep_empty || (words.subtitle.is_none() && words.sentence.is_none() && !words.offer_wake)) { continue }if !searching {if let Some(sentence) = &words.sentence { out.push(note(&format!("grid:{}", s.name), &format!("{} · {sentence}", s.name), SHARED)) }if words.offer_wake {@@ -771,12 +839,26 @@ pub fn rows(app: &App, query: &str) -> Vec<Row> {.lead(vec![span("↻ ", fg(theme::accent()))]).right("usually 15–40 s"));}}- for x in &s.models {+ for x in chat {let detail = [x.node.as_str(), s.name.as_str(), words.subtitle.as_deref().unwrap_or("")].into_iter().filter(|w| !w.is_empty()).collect::<Vec<_>>().join(" · ");out.push(grid_row(app, s, x, t, SHARED).detail(vec![span(detail, fg(theme::MUTED))]));}}if !g.reachable && !searching { out.push(note("shared", "Shared models are unavailable.", SHARED)) }++ }++ // Jev models, last: this computer's own (to get, start, stop — and to call once its grid lists it),+ // then every grid's, each naming its machine and grid. A Jev model of this computer's that its own+ // grid lists is one row, this computer's.+ let mine: Vec<&LocalModel> = snap.map(|s| s.models.iter().filter(|m| m.decision).collect()).unwrap_or_default();+ for m in &mine { out.push(jev_local_row(app, m)) }+ if let Some(g) = v.grids.get(&machine) {+ for s in &g.sections {+ for x in s.models.iter().filter(|x| x.decision && !(s.own && mine.iter().any(|m| m.name.eq_ignore_ascii_case(&x.id)))) {+ out.push(jev_row(s, x))+ }+ }}out@@ -794,6 +876,8 @@ const IN_USE: &str = "This harness is on it";/// The word on a row, and on the pane, while the harness moves onto it.pub const SWITCHING: &str = "Switching…";const NO_HARNESS: &str = "Focus a harness to move it onto a model";+/// What Enter on a Jev model says once its request is copied.+const JEV_COPIED: &str = "Copied — paste it into a terminal.";/// What a key on a row comes to — decided here, done by [run]; the tests read the plan.#[derive(Clone, Debug, PartialEq)]@@ -812,6 +896,8 @@ pub enum Plan {Wake(String),More,Api(String),+ /// Put [text] on the clipboard (and in a paste buffer): how to call a Jev model.+ Copy(String),}fn local_model(app: &App, id: &str) -> Option<LocalModel> { app.models_view.local.get(&app.fleet.local_id)?.models.iter().find(|m| m.id == id).cloned() }@@ -848,6 +934,19 @@ pub fn plan_enter(app: &App, id: &str) -> Plan {if id == "mv:more" { return Plan::More }if let Some(name) = id.strip_prefix("mv:wake:") { return if v.asking.contains(name) { say(STARTING_UP_WAIT) } else { Plan::Wake(name.to_string()) } }if let Some(key) = id.strip_prefix("mv:api:") { return Plan::Api(key.to_string()) }+ if let Some(rest) = id.strip_prefix("mv:jev:") {+ let mut parts = rest.splitn(3, '\t');+ let (Some(grid), Some(_node), Some(model)) = (parts.next(), parts.next(), parts.next()) else { return Plan::Nothing };+ return Plan::Copy(jev_request(grid, model));+ }+ if let Some(model) = id.strip_prefix("mv:jevlocal:") {+ let Some(m) = local_model(app, model) else { return say("This model is gone. Try again in a moment.") };+ if let Some(o) = v.op_for(&app.fleet.local_id, &m).filter(|o| o.active()) { return Plan::Say(o.word()) }+ if let Some(grid) = jev_local_grid(app, &m) { return Plan::Copy(jev_request(&grid, &m.name)) }+ if m.running() { return say("It is starting on your grid — Enter copies how to call it once the grid lists it.") }+ // Get is the whole of it: the download, an engine new enough to serve it, and the model on the grid.+ return if m.can_start { Plan::Act { model: m.id.clone(), action: "start" } } else { say("Wait for the current model operation to finish.") };+ }if let Some(rest) = id.strip_prefix("mv:apimodel:") {let Some((api, model)) = rest.split_once('\t') else { return Plan::Nothing };let Some(api) = v.apis.as_ref().and_then(|a| a.as_ref().ok()).and_then(|l| l.iter().find(|x| x.id == api)) else { return Plan::Nothing };@@ -913,7 +1012,7 @@ pub fn plan_enter(app: &App, id: &str) -> Plan {/// What ^S does on row [id]: stop a local model (asked first).pub fn plan_stop(app: &App, id: &str) -> Plan {- let Some(m) = id.strip_prefix("mv:local:").and_then(|model| local_model(app, model)) else { return Plan::Nothing };+ let Some(m) = id.strip_prefix("mv:local:").or_else(|| id.strip_prefix("mv:jevlocal:")).and_then(|model| local_model(app, model)) else { return Plan::Nothing };let f = facts(app, &m, None);if f.busy { return Plan::Say("Wait for the current model operation to finish.".into()) }if !m.can_stop { return Plan::Say(if m.running() { "Other models share its engine — stop it from the desktop's Model Manager".into() } else { "It is not running".into() }) }@@ -957,6 +1056,12 @@ fn run(app: &mut App, picker: &mut Picker, plan: Plan, key: &str) {let v = &mut app.models_view;if !v.api_open.remove(&key) { v.api_open.insert(key.clone()); if !v.api_models.contains_key(&key) { read_api_models(app, &key) } }}+ Plan::Copy(text) => {+ if !app.headless { crate::clipboard::store(&text) }+ let limit = app.buffer_limit();+ app.paste.add(text, limit);+ picker.say(JEV_COPIED);+ }}}@@ -1498,7 +1603,7 @@ pub fn preview(app: &App, id: &str) -> Vec<Line<'static>> {let x = section.and_then(|s| s.models.iter().find(|x| x.id == model));let own = section.is_some_and(|s| s.own);let status = match x.and_then(|x| x.offline.clone()) { Some(who) => format!("{who} seems offline — its models come back when it does"), None => "Available".into() };- let status = match grid_word(app, x.cloned().as_ref().unwrap_or(&GridModel { id: model.to_string(), node: node.to_string(), offline: None }), t).as_str() {+ let status = match grid_word(app, x.cloned().as_ref().unwrap_or(&GridModel { id: model.to_string(), node: node.to_string(), offline: None, decision: false }), t).as_str() {SWITCHING => format!("{SWITCHING} this harness is moving onto it"),"✓ In use" => format!("{status} · this harness is on it"),_ => status,@@ -1512,6 +1617,68 @@ pub fn preview(app: &App, id: &str) -> Vec<Line<'static>> {if !said.is_empty() { out.push(Line::raw("")); out.push(Line::from(span(said, fg(theme::accent())))) }return out;}+ if let Some(model) = id.strip_prefix("mv:jevlocal:") {+ let Some(m) = local_model(app, model) else { return vec![dim("(gone)")] };+ let here = this_computer();+ let grid = jev_local_grid(app, &m);+ let op = v.op_for(&machine, &m);+ let mut out = vec![bold(m.name.clone()), Line::raw(["Jev model", &capital(here), grid.as_deref().unwrap_or("")].into_iter().filter(|w| !w.is_empty()).collect::<Vec<_>>().join(" · "))];+ out.push(Line::raw(""));+ out.push(Line::raw("Answers questions about a state with probabilities: a choice between named options, yes or no, or a score. It does not chat, so no harness runs on it."));+ out.push(Line::raw(""));+ out.push(match op {+ Some(o) if o.active() => Line::raw(o.word()),+ Some(o) if o.failed() => warn(o.error.clone().unwrap_or_else(|| "It could not start. Try again.".into())),+ _ if m.running() => Line::raw(format!("Running on {here}, on your grid.")),+ _ if m.downloaded() => Line::raw("Downloaded. Start runs it on your grid, beside the models already running there."),+ _ => Line::raw(format!("Get downloads it{}, updates Grid's model engine first if it is too old to serve Jev models, and runs it on your grid, beside the models already running there.",+ m.size.map(|s| format!(" ({})", gb(s))).unwrap_or_default())),+ });+ out.push(Line::raw(""));+ if let Some(size) = m.size { out.push(kv("Size", gb(size))) }+ out.push(kv("Runs in", "Grid's llama.cpp"));+ if let Some(grid) = &grid {+ out.push(kv("Grid", grid.clone()));+ out.push(kv("Endpoint", "POST $OPENAI_BASE_URL/systemone"));+ out.push(Line::raw(""));+ out.push(Line::raw("Call it from a terminal:"));+ out.extend(jev_request(grid, &m.name).lines().map(|l| Line::from(span(l.to_string(), fg(theme::SOFT)))));+ out.push(Line::raw(""));+ out.push(dim("The first line loads this grid's address and key into your shell; the key is never shown here."));+ }+ let said = match (grid.is_some(), m.running(), m.downloaded()) {+ (true, _, _) => "Enter copies how to call it. ^S stops it and frees its memory. The download is kept.",+ (false, true, _) => "^S stops it and frees its memory. The download is kept.",+ (false, false, true) => "Enter starts it.",+ _ => "Enter gets it.",+ };+ if op.is_none_or(|o| !o.active()) { out.push(Line::raw("")); out.push(Line::from(span(said, fg(theme::accent())))) }+ return out;+ }+ if let Some(rest) = id.strip_prefix("mv:jev:") {+ let mut parts = rest.splitn(3, '\t');+ let (grid, node, model) = (parts.next().unwrap_or(""), parts.next().unwrap_or(""), parts.next().unwrap_or(""));+ let section = v.grids.get(&machine).and_then(|g| g.sections.iter().find(|s| s.name == grid));+ let offline = section.and_then(|s| s.models.iter().find(|x| x.id == model)).and_then(|x| x.offline.clone());+ let resting = section.is_some_and(|s| s.state == "asleep" || s.state == "waking");+ let mut out = vec![bold(model.to_string()), Line::raw(["Jev model", node, grid].into_iter().filter(|w| !w.is_empty()).collect::<Vec<_>>().join(" · "))];+ out.push(Line::raw(""));+ out.push(Line::raw("Answers questions about a state with probabilities: a choice between named options, yes or no, or a score. It does not chat, so no harness runs on it."));+ if let Some(who) = offline { out.push(Line::raw("")); out.push(warn(format!("{who} seems offline — it answers again when that computer is back"))) }+ else if resting { out.push(Line::raw("")); out.push(dim("Its grid is resting. Your first request wakes it, which takes a few seconds.")) }+ out.push(Line::raw(""));+ out.push(kv("Model", model.to_string()));+ out.push(kv("Grid", grid.to_string()));+ out.push(kv("Endpoint", "POST $OPENAI_BASE_URL/systemone"));+ out.push(Line::raw(""));+ out.push(Line::raw("Call it from a terminal:"));+ out.extend(jev_request(grid, model).lines().map(|l| Line::from(span(l.to_string(), fg(theme::SOFT)))));+ out.push(Line::raw(""));+ out.push(dim("The first line loads this grid's address and key into your shell; the key is never shown here. Each question is a choice (named options), a noul (yes or no) or a score (2–10 ordered levels)."));+ out.push(Line::raw(""));+ out.push(Line::from(span("Enter copies it.", fg(theme::accent()))));+ return out;+ }if let Some(name) = id.strip_prefix("mv:wake:") {return vec![bold(format!("Shared · {name}")), Line::raw("Resting to save resources. It starts by itself when you send a message."), Line::raw(""),Line::from(span("Enter wakes it to show its models (usually 15–40 s).", fg(theme::accent())))];@@ -2207,7 +2374,7 @@ mod tests {#[test]fn a_resting_section_says_what_the_desktop_says() {let s = |state: &str, models: usize, age: Option<u64>, outcome: &str| Section { name: "team".into(), state: state.into(), age, outcome: outcome.into(),- models: (0..models).map(|i| GridModel { id: format!("m{i}"), node: "n".into(), offline: None }).collect(), ..Default::default() };+ models: (0..models).map(|i| GridModel { id: format!("m{i}"), node: "n".into(), offline: None, decision: false }).collect(), ..Default::default() };assert_eq!(section_words(&s("asleep", 1, Some(180), ""), false).subtitle.as_deref(), Some("Asleep 3min ago"));assert!(section_words(&s("asleep", 0, None, ""), false).offer_wake);assert_eq!(section_words(&s("asleep", 0, None, ""), true), Words { subtitle: None, sentence: Some(STARTING_UP_WAIT.into()), offer_wake: false });@@ -2336,4 +2503,103 @@ mod tests {// It is in the Commands panel, in the Harness group.assert!(crate::modal::command_rows(&app).iter().any(|r| r.id == "cmd:models" && r.group.as_deref() == Some("Harness")));}++ /// Jev (System One) models: listed last under their own heading, from the own grid and a shared+ /// one alike — never under Your models or Shared with you, never a harness's — and Enter puts how+ /// to call one on the clipboard, which the panel shows too.+ #[test]+ fn jev_models_are_listed_apart_and_enter_copies_how_to_call_one() {+ let mut app = app();+ app.headless = true;+ on_local(&mut app, "local", Ok(local_reply(qwen("running", Value::Null), false)));+ let mut g = grids_reply(&["box-model"]);+ g["grids"][0]["models"].as_array_mut().unwrap().push(json!({ "id": "laya-english", "node": "studio", "kind": "decision" }));+ g["grids"][1]["models"].as_array_mut().unwrap().push(json!({ "id": "nimble", "node": "gpu-box", "kind": "decision" }));+ on_grids(&mut app, "local", Ok(g));+ let rows = rows_of(&app);+ let jev: Vec<&str> = rows.iter().filter(|r| r.group.as_deref() == Some(JEV)).map(|r| r.id.as_str()).collect();+ assert_eq!(jev, vec!["mv:jev:own-grid\tstudio\tlaya-english", "mv:jev:team\tgpu-box\tnimble"]);+ assert_eq!(rows.last().and_then(|r| r.group.as_deref()), Some(JEV), "the last section");+ assert!(rows.iter().filter(|r| r.group.as_deref() != Some(JEV)).all(|r| r.label != "laya-english" && r.label != "nimble"));+ let laya = row(&rows, "mv:jev:own-grid\tstudio\tlaya-english");+ assert_eq!(laya.right.trim(), "Copy");+ assert_eq!(laya.detail.iter().map(|s| s.content.as_ref()).collect::<String>(), "studio · own-grid");++ let request = jev_request("own-grid", "laya-english");+ assert!(request.starts_with("eval \"$(harness grid env own-grid)\"\n"), "{request}");+ assert!(request.contains("curl \"$OPENAI_BASE_URL/systemone\"") && request.contains("Bearer $OPENAI_API_KEY"), "{request}");+ assert!(request.contains("\"model\":\"laya-english\""), "{request}");+ // Byte for byte the desktop's (`jevRequest` in model_search_catalog.dart).+ assert!(request.ends_with(r#"-d '{"model":"laya-english","state":"I was charged twice. Please refund the duplicate.","questions":{"refund":{"type":"noul","instructions":"Is a refund requested?"}}}'"#), "{request}");+ assert_eq!(shell_word("my grid"), "'my grid'");+ assert_eq!(shell_word("o'brien"), "'o'\\''brien'");++ let panel = text(&preview(&app, "mv:jev:own-grid\tstudio\tlaya-english"));+ assert!(panel.contains("Jev model · studio · own-grid") && panel.contains("Call it from a terminal:"), "{panel}");+ assert!(panel.contains(&request), "{panel}");+ assert_eq!(plan_enter(&app, "mv:jev:own-grid\tstudio\tlaya-english"), Plan::Copy(request.clone()));++ let mut picker = Picker::new("models", "");+ choose(&mut app, &mut picker, "mv:jev:own-grid\tstudio\tlaya-english", false);+ assert_eq!(picker.flash.as_ref().map(|(t, _)| t.as_str()), Some(JEV_COPIED));+ assert_eq!(app.paste.top().map(|b| b.data.clone()), Some(request), "in a paste buffer too");+ assert!(app.models_view.switching.is_none(), "no harness was moved");++ // This computer serving the own grid's Jev model (`grid join --serve`): listed once, under Jev models.+ let mut served = local_reply(qwen("running", Value::Null), false);+ served["models"].as_array_mut().unwrap().push(json!({ "id": "local:Laya-English-Q8_0.gguf", "name": "laya-english", "state": "running", "canStop": true, "sizeBytes": 449397600u64 }));+ on_local(&mut app, "local", Ok(served));+ assert_eq!(rows_of(&app).iter().filter(|r| r.label.starts_with("laya-english")).map(|r| r.group.clone().unwrap_or_default()).collect::<Vec<_>>(), vec![JEV.to_string()]);++ // A resting grid wakes on the request: the panel says so, and the row still offers the copy.+ assert!(!text(&preview(&app, "mv:jev:team\tgpu-box\tnimble")).contains("resting"));+ app.models_view.grids.get_mut("local").unwrap().sections.iter_mut().find(|s| s.name == "team").unwrap().state = "asleep".into();+ assert!(text(&preview(&app, "mv:jev:team\tgpu-box\tnimble")).contains("Its grid is resting. Your first request wakes it"));+ assert_eq!(row(&rows_of(&app), "mv:jev:team\tgpu-box\tnimble").right.trim(), "Copy");+ }++ /// A Jev model this computer can get: under Jev models (never the downloads), Get starts it — the+ /// daemon downloads it, updates Grid's engine and runs it — and once the own grid lists it, it is one+ /// row whose Enter copies how to call it and whose ^S asks before it stops.+ #[test]+ fn a_jev_model_of_this_computer_is_got_started_called_and_stopped_from_its_one_row() {+ let mut app = app();+ let laya = |state: &str, op: Value| json!({ "id": "jev:ggml-org/Laya-GGUF", "name": "laya-english", "kind": "decision", "state": state,+ "sizeBytes": 449397600u64, "quant": "Q8_0", "canStart": state != "running", "canStop": state == "running", "app": "Grid", "operation": op });+ let mut reply = local_reply(qwen("running", Value::Null), false);+ reply["models"].as_array_mut().unwrap().push(laya("available", Value::Null));+ on_local(&mut app, "local", Ok(reply.clone()));+ on_grids(&mut app, "local", Ok(grids_reply(&["box-model"])));+ let id = "mv:jevlocal:jev:ggml-org/Laya-GGUF";+ let rows = rows_of(&app);+ assert_eq!(row(&rows, id).group.as_deref(), Some(JEV));+ assert_eq!(row(&rows, id).right.trim(), "Get");+ assert!(rows.iter().filter(|r| r.label == "laya-english").count() == 1, "never also offered among the downloads");+ assert!(text(&preview(&app, id)).contains("updates Grid's model engine first if it is too old to serve Jev models"));+ assert_eq!(plan_enter(&app, id), Plan::Act { model: "jev:ggml-org/Laya-GGUF".into(), action: "start" });++ // Its engine being updated says so, on the row and in the panel.+ let mut updating = reply.clone();+ updating["models"].as_array_mut().unwrap().pop();+ updating["models"].as_array_mut().unwrap().push(laya("available", json!({ "id": "op-jev", "modelId": "jev:ggml-org/Laya-GGUF", "action": "start",+ "stage": "updating", "phase": "running", "updatedAt": "2026-09-30T00:00:00.000Z" })));+ on_local(&mut app, "local", Ok(updating));+ assert_eq!(row(&rows_of(&app), id).right.trim(), "Updating engine");+ assert!(text(&preview(&app, id)).contains("Updating engine"));++ // Running, and the own grid lists it as a Jev model: one row — this computer's — to call or stop.+ let mut running = reply.clone();+ running["models"].as_array_mut().unwrap().pop();+ running["models"].as_array_mut().unwrap().push(laya("running", Value::Null));+ on_local(&mut app, "local", Ok(running));+ let mut g = grids_reply(&["box-model"]);+ g["grids"][0]["models"].as_array_mut().unwrap().push(json!({ "id": "laya-english", "node": "studio", "kind": "decision" }));+ on_grids(&mut app, "local", Ok(g));+ let rows = rows_of(&app);+ assert_eq!(rows.iter().filter(|r| r.label.starts_with("laya-english")).map(|r| r.id.as_str()).collect::<Vec<_>>(), vec![id]);+ assert_eq!(row(&rows, id).right.trim(), "Copy");+ assert_eq!(plan_enter(&app, id), Plan::Copy(jev_request("own-grid", "laya-english")));+ assert!(text(&preview(&app, id)).contains(&jev_request("own-grid", "laya-english")));+ assert!(matches!(plan_stop(&app, id), Plan::Arm(_, ref then) if **then == Plan::Act { model: "jev:ggml-org/Laya-GGUF".into(), action: "stop" }));+ }}