Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

feat(grid): set Grid up on first use, never as part of a Harness sign-in

bitcoinbuilder450b5da95701
diff --git a/cli/src/authCommand.spec.ts b/cli/src/authCommand.spec.ts
index 8ca78c6ae..354549a3b 100644
--- a/cli/src/authCommand.spec.ts
+++ b/cli/src/authCommand.spec.ts
@@ -1,6 +1,6 @@
import { spawn, spawnSync } from 'child_process'
import { createServer, type Server } from 'http'
-import { mkdtempSync, rmSync, writeFileSync, mkdirSync } from 'fs'
+import { existsSync, mkdtempSync, rmSync, writeFileSync, mkdirSync } from 'fs'
import { tmpdir } from 'os'
import { join } from 'path'
import { fileURLToPath } from 'url'
@@ -60,6 +60,14 @@ function envFor(root: string, backendUrl?: string): NodeJS.ProcessEnv {
}
}
+/** A `grid` that records every call it gets, at the path [envFor] hands the child — for pinning that
+ * signing in to Harness runs none. Returns where the calls land (absent while there were none). */
+function recordingGrid(root: string): string {
+ const calls = join(root, 'grid-calls')
+ writeFileSync(join(root, 'grid-unavailable'), `#!/bin/sh\necho "$*" >> '${calls}'\nexit 0\n`, { mode: 0o755 })
+ return calls
+}
+
function runSync(root: string, args: string[], backendUrl?: string) {
return spawnSync(process.execPath, [TSX, CLI_SOURCE, ...args], {
cwd: CLI_ROOT,
@@ -164,22 +172,17 @@ describe('harness login --json', () => {
it('already-signed-in short-circuit emits a single success result line', async () => {
const root = tempRoot()
seedSession(root)
+ const gridCalls = recordingGrid(root)
const { base } = await fakeBackend({
resolveComputer: () => ({ machine: { machineId: 'm_seeded' } }),
})
const result = await runAsync(root, ['login', '--json'], base)
expect(result.status).toBe(0)
const lines = result.stdout.trim().split('\n').map((l) => JSON.parse(l))
- // The sign-in now also hands its token to `grid` and makes sure the account's private grid
- // exists — best-effort, reported on this line rather than allowed to change its status. There is
- // no `grid` on PATH in this test, so it reports the attempt and the harness sign-in still
- // succeeds, which is the property worth pinning.
- expect(lines).toEqual([{
- type: 'result',
- status: 'success',
- alreadySignedIn: true,
- grid: { signedIn: false, code: expect.any(String) },
- }])
+ // Harness only: grid is an add-on, signed in the first time a grid feature is used — so the line
+ // says nothing about grid, and not one `grid` command ran, though a `grid` was right there.
+ expect(lines).toEqual([{ type: 'result', status: 'success', alreadySignedIn: true }])
+ expect(existsSync(gridCalls)).toBe(false)
})
it('emits a BACKEND_ERROR result line (not a stack trace) when authorize-native is unreachable', async () => {
@@ -199,6 +202,7 @@ describe('harness login --json', () => {
resolveComputer: () => ({ machine: { machineId: 'm_new' } }),
})
+ const gridCalls = recordingGrid(root)
const child = spawn(process.execPath, [TSX, CLI_SOURCE, 'login', '--json'], {
cwd: CLI_ROOT,
env: envFor(root, base),
@@ -228,12 +232,8 @@ describe('harness login --json', () => {
expect(exitCode).toBe(0)
// Drain any trailing buffered line after exit.
if (stdout.trim()) lines.push(JSON.parse(stdout.trim()))
- // Same contract as the already-signed-in line: the grid hand-off is reported here, and its
- // failure (no `grid` on PATH in this test) never changes `status`.
- expect(lines[1]).toEqual({
- type: 'result',
- status: 'success',
- grid: { signedIn: false, code: expect.any(String) },
- })
+ // Same contract as the already-signed-in line: a fresh Harness sign-in signs in to Harness alone.
+ expect(lines[1]).toEqual({ type: 'result', status: 'success' })
+ expect(existsSync(gridCalls)).toBe(false)
}, 15_000)
})
diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.ts
index 6274c4975..80d638a2f 100644
--- a/cli/src/backendSocket.spec.ts
+++ b/cli/src/backendSocket.spec.ts
@@ -24,6 +24,7 @@ import { randomUUID } from 'node:crypto'
import { fakeGridAnswers, installFakeGrid, type FakeGrid } from './lib/__fixtures__/fakeGrid.js'
import { clearGridMcpUrlCache } from './lib/gridMcpUrl.js'
import { LocalModels } from './lib/localModels.js'
+import type { GridAttachResult } from './lib/gridAttach.js'
import { STRICT_DOWN_TYPES } from './lib/e2ee/applicationFrames.js'
describe('local model lifecycle RPCs', () => {
@@ -2594,30 +2595,108 @@ describe('grid_models_list says whether this machine has a grid CLI', () => {
expect(await listModels()).toMatchObject({ gridName: GRID_NAME, gridCli: 'path' })
})
+})
- it('waits for an in-flight grid reconcile before answering, so the first open after an update is not empty', async () => {
- fake = installFakeGrid(plan)
+describe('grid is set up on demand — by an act, never by a read', () => {
+ afterEach(() => { vi.restoreAllMocks() })
+
+ const READY: GridAttachResult = { status: 'signed-in', name: 'kelvin-1a2b3c4d', detail: '', ownGrid: 'created' }
+
+ /** A daemon whose grid set-up and local models are stubs, asked over a local frame. */
+ function daemon(ready: GridAttachResult = READY) {
const socket = new BackendSocket('token')
- // No local fallback and no machine_meta: the name can only come from the reconcile below, so a
- // non-empty answer proves the RPC waited for it rather than answering "no grid" straight away.
- socket.deriveGridName = async () => null
- let settle: () => void = () => {}
- const reconcile = new Promise<void>((resolve) => {
- settle = () => { socket.setHarnessGridName(GRID_NAME); resolve() }
+ socket.deriveGridName = async () => 'kelvin-1a2b3c4d'
+ let setUp = false
+ const ensureGrid = vi.fn(async (_request?: { ownGrid?: boolean }) => {
+ if (ready.status === 'signed-in' || ready.status === 'converged') setUp = true
+ return ready
})
- socket.gridReadyProbe = () => reconcile
- socket.connect()
- const ws = wsMock.instances[0]
- ws.open()
- ws.message(sealedDown(socket, 'web-1', 'grid_models_list', { requestId: 'r' }))
- // The reconcile lands a moment later, within the RPC's wait window.
- setTimeout(() => settle(), 20)
- await vi.waitFor(() => expect(parseSent(ws).some((item) => (item.frame as { type?: string } | undefined)?.type === 'grid_models_list_result')).toBe(true), { timeout: 10_000 })
- const reply = parseSent(ws)
- .map((item) => item.frame as { type?: string; payload?: Record<string, unknown> } | undefined)
- .find((frame) => frame?.type === 'grid_models_list_result')
- await socket.stop()
- expect(reply?.payload).toMatchObject({ gridName: GRID_NAME })
+ socket.ensureGrid = ensureGrid
+ socket.gridSetUp = () => setUp
+ const list = vi.fn(async () => ({ models: [], observedAt: 'now', busy: false }))
+ const act = vi.fn(async () => ({}))
+ Object.assign(socket as unknown as Record<string, unknown>, { localModels: { list, act } })
+ socket.onRetargetAgent = async () => ({ ok: true })
+ const frames: Array<Record<string, unknown>> = []
+ socket.registerLocalClient('local:grid', { sendFrame: (frame) => { frames.push(frame); return true }, sendBinary: () => true })
+ let asked = 0
+ const ask = async (type: string, payload: Record<string, unknown> = {}): Promise<Record<string, unknown>> => {
+ const requestId = `${type}-${++asked}`
+ socket.handleLocalFrame('local:grid', { type, payload: { requestId, ...payload } })
+ const answer = (): Record<string, unknown> | undefined => frames
+ .map((frame) => frame.payload as Record<string, unknown> | undefined)
+ .find((body) => body?.requestId === requestId)
+ await vi.waitFor(() => expect(answer()).toBeDefined())
+ return answer()!
+ }
+ return { socket, ensureGrid, list, act, ask, done: async () => { await socket.unregisterLocalClient('local:grid'); await socket.stop() } }
+ }
+
+ it('the list read a picker polls sets nothing up, and says when it is needed', async () => {
+ const d = daemon()
+ const answer = await d.ask('grid_fleet_models_list')
+ expect(d.ensureGrid).not.toHaveBeenCalled()
+ expect(answer).toMatchObject({ gridSetupNeeded: true })
+ await d.done()
+ })
+
+ it("Set up — a list read carrying `setup` — signs grid in with the account's own grid, then answers", async () => {
+ const d = daemon()
+ const answer = await d.ask('grid_fleet_models_list', { setup: true })
+ expect(d.ensureGrid).toHaveBeenCalledExactlyOnceWith({ ownGrid: true })
+ expect(answer).not.toHaveProperty('gridSetupNeeded')
+ expect(answer).not.toHaveProperty('gridSetupError')
+ // Read fresh: the catalog was unreachable a moment ago.
+ expect(d.list).toHaveBeenCalledWith('kelvin-1a2b3c4d', true)
+ await d.done()
+ })
+
+ it("a Get signs grid in; a Use also makes sure of the account's grid; a Stop does neither", async () => {
+ const d = daemon()
+ await d.ask('grid_fleet_model_download', { modelId: 'org/Model-GGUF' })
+ await d.ask('grid_fleet_model_start', { modelId: 'org/Model-GGUF' })
+ await d.ask('grid_fleet_model_stop', { modelId: 'org/Model-GGUF' })
+ expect(d.ensureGrid.mock.calls).toEqual([[{ ownGrid: false }], [{ ownGrid: true }]])
+ expect(d.act.mock.calls.map((call) => (call as unknown[])[2])).toEqual(['download', 'start', 'stop'])
+ await d.done()
+ })
+
+ it('a set-up grid refused is said, and the act waiting on it does not run', async () => {
+ const d = daemon({ status: 'handoff-failed', name: 'kelvin-1a2b3c4d', detail: 'grid is too old for --harness' })
+ expect(await d.ask('grid_fleet_model_start', { modelId: 'org/Model-GGUF' })).toMatchObject({ error: 'grid is too old for --harness' })
+ expect(d.act).not.toHaveBeenCalled()
+ expect(await d.ask('grid_fleet_models_list', { setup: true }))
+ .toMatchObject({ gridSetupNeeded: true, gridSetupError: 'grid is too old for --harness' })
+ await d.done()
+ })
+
+ it("an account grid that could not be made fails a Use, not a Get", async () => {
+ const d = daemon({ status: 'signed-in', name: 'kelvin-1a2b3c4d', detail: 'free plan: one grid per account', ownGrid: 'failed' })
+ expect(await d.ask('grid_fleet_model_start', { modelId: 'org/Model-GGUF' })).toMatchObject({ error: 'free plan: one grid per account' })
+ await d.ask('grid_fleet_model_download', { modelId: 'org/Model-GGUF' })
+ expect(d.act.mock.calls.map((call) => (call as unknown[])[2])).toEqual(['download'])
+ await d.done()
+ })
+
+ it('a Grid harness command runs against grid as it stands — its viewer asks on its own, so it never sets grid up', async () => {
+ const d = daemon()
+ const run = vi.fn(async () => ({ ok: true, code: 0, stdout: '[]', stderr: '', error: null }))
+ Object.assign(d.socket as unknown as Record<string, unknown>, { gridFleet: { run, cancel: () => false } })
+ await d.ask('grid_fleet_run', { args: ['--remote', 'ls', '--json'], timeoutMs: 5_000 })
+ expect(run).toHaveBeenCalledTimes(1)
+ expect(d.ensureGrid).not.toHaveBeenCalled()
+ await d.done()
+ })
+
+ it("a move onto a grid model signs grid in first — with the account's own grid only when the model is on it", async () => {
+ // Refused, so the move stops at the set-up and no grid is read: what is pinned is what was asked.
+ const d = daemon({ status: 'handoff-failed', name: null, detail: 'no grid on this computer' })
+ expect(await d.ask('agent_retarget', { agentId: 'a1', gridModel: 'Shared-Model', gridName: 'team-grid-0000aaaa' }))
+ .toMatchObject({ error: 'GRID_UNAVAILABLE', detail: 'no grid on this computer' })
+ expect(await d.ask('agent_retarget', { agentId: 'a1', gridModel: 'Own-Model' }))
+ .toMatchObject({ error: 'GRID_UNAVAILABLE' })
+ expect(d.ensureGrid.mock.calls).toEqual([[{ ownGrid: false }], [{ ownGrid: true }]])
+ await d.done()
})
})
@@ -2632,8 +2711,7 @@ describe('the connect burst with no network', () => {
// three again, for as long as the wifi stayed off. The terminal on the same computer read
// "offline" the whole time.
const socket = new BackendSocket('token')
- socket.deriveGridName = async () => null
- socket.gridReadyProbe = () => new Promise<void>(() => {}) // a reconcile that never lands
+ socket.deriveGridName = () => new Promise<null>(() => {}) // a grid read that never lands
socket.accountUsageReader = () => new Promise(() => {}) // a vendor that never answers
const frames: Array<Record<string, unknown>> = []
socket.registerLocalClient('local:burst', { sendFrame: (frame) => { frames.push(frame); return true }, sendBinary: () => true })
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
index faeb5629a..f4f43ad8e 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -44,6 +44,7 @@ import {
forgetGridModels, gridInventory, listAllGridModels, onGridModelsChanged, presentGridSections, retargetPrewarm, type GridSection,
} from './lib/gridModels.js'
import { resolveGridTarget } from './lib/gridTarget.js'
+import type { GridAttachResult } from './lib/gridAttach.js'
import { parseNewAgentModel, resolveNewAgentModel } from './lib/newAgentModel.js'
import { deriveHarnessGridName } from './lib/gridDerive.js'
import { AGENT_NAME_RE, FirstPromptUnsupportedError, MAX_FIRST_PROMPT_CHARS, NamedAgentUnsupportedError, permissionModeApproves, permissionModeFlags, supportsFirstPrompt, supportsNamedAgent } from './lib/engineLaunch.js'
@@ -163,10 +164,6 @@ const APP_PRESENCE_UP_MS = 60_000
// `this.ws` set, every later connect() returning early, and the daemon reporting "cloud
// reconnecting…" until someone restarted it.
const HANDSHAKE_TIMEOUT_MS = 15_000
-/** How long `resolveGridName` waits for a grid reconcile still in flight before answering with
- * whatever is resolved. Well under the app's 12s `grid_models_list` timeout, leaving that RPC room
- * for its own `grid` spawns; a reconcile slower than this lands by the next open. */
-const GRID_ATTACH_WAIT_MS = 6_000
/** An `agent_update {opened: true}` for an agent opened less than this long ago is answered but not
* stamped or broadcast: a person flicking between two tabs, or two apps opening the same agent at
* once, would otherwise push a frame to every client for each flick. Exported for the spec. */
@@ -982,10 +979,14 @@ export class BackendSocket {
private harnessGridName: string | null = null
/** Injected so the derivation (a `grid` spawn) is a seam in tests; see `lib/gridDerive.ts`. */
deriveGridName: () => Promise<string | null> = deriveHarnessGridName
- /** The daemon-start grid reconcile (`lib/gridAttach.ts`), while it is running — so the first
- * `grid_models_list` / retarget after an update waits for the sign-in it may still be arranging
- * rather than answering "no grid". Set by `cli.ts`; returns null when nothing is in flight. */
- gridReadyProbe: (() => Promise<unknown> | null) | null = null
+ /** Have grid ready for a grid feature the person is using now (`lib/gridAttach.ts`): `grid` installed,
+ * signed in as this account with its harness token, and — `ownGrid` — the account's own grid there.
+ * Asked by acts only (Set up, Get, Use, a move onto a grid model, a Model Manager command), never by
+ * a read. Set by `cli.ts`; null (tests) reads grid as it stands. */
+ ensureGrid: ((request?: { ownGrid?: boolean }) => Promise<GridAttachResult>) | null = null
+ /** Offline, cheap: is there a `grid` here holding a sign-in? Answers the list read's
+ * `gridSetupNeeded`. Null (tests) reads as set up. */
+ gridSetUp: (() => boolean) | null = null
/** Set the account's private grid name from the reconcile that just confirmed it, so the RPCs
* answer with it at once rather than waiting for the next `machine_meta` (`lib/gridAttach.ts`). */
@@ -1020,26 +1021,27 @@ export class BackendSocket {
* work out for itself (`lib/gridDerive.ts`). A backend that predates `machine_meta.gridName`
* left every picker empty while `grid models` listed the model fine; the derivation is the
* skill's own rule, so the daemon and the agent it opens agree on which grid is "yours".
- *
- * Waits, once and briefly, for a grid reconcile still in flight — the machine that just updated is
- * signing in to grid in the background, and a picker opened in that window would otherwise read
- * "no grid" for the one moment the answer is about to arrive. Bounded so a slow reconcile (a fresh
- * sign-in and a grid create) never holds the RPC past the app's own timeout; whatever is resolved
- * by then is answered, and the next open — after the reconcile has landed — is correct regardless.
*/
private async resolveGridName(): Promise<string | null> {
- const inFlight = this.gridReadyProbe?.()
- if (inFlight) {
- let timer: ReturnType<typeof setTimeout> | undefined
- await Promise.race([
- inFlight.catch(() => {}),
- new Promise<void>((resolve) => { timer = setTimeout(resolve, GRID_ATTACH_WAIT_MS) }),
- ])
- if (timer) clearTimeout(timer)
- }
return this.harnessGridName ?? await this.deriveGridName()
}
+ /**
+ * Grid set up for an act, or the sentence saying why it could not be: null when it is ready — or
+ * when this daemon has no [ensureGrid] to ask (tests), which reads grid as it stands.
+ */
+ private async gridNotReady(ownGrid: boolean): Promise<string | null> {
+ if (!this.ensureGrid) return null
+ const ready = await this.ensureGrid({ ownGrid })
+ if (ready.status !== 'converged' && ready.status !== 'signed-in') {
+ return ready.detail || 'Grid could not be set up on this computer. Try again.'
+ }
+ if (ownGrid && ready.ownGrid && !['created', 'existed', 'adopted'].includes(ready.ownGrid)) {
+ return ready.detail || 'Your grid could not be created. Try again.'
+ }
+ return null
+ }
+
connect(): void {
if (this.closed || this.ws || this.connecting) return
this.connecting = true
@@ -2026,9 +2028,25 @@ export class BackendSocket {
case 'grid_fleet_model_stop': {
// A daemon-owned operation survives panel closure and a lost reply.
// Keep hardware/catalog/network reads off the ordered terminal queue.
- void this.resolveGridName().then(async grid => type === 'grid_fleet_models_list'
- ? this.localModels.list(grid, payload.refresh === true)
- : this.localModels.act(grid, payload.modelId, type === 'grid_fleet_model_download' ? 'download' : type === 'grid_fleet_model_start' ? 'start' : 'stop'))
+ //
+ // Grid is set up here only for an ACT: the picker's Set up (a list read carrying `setup`),
+ // a Get, a Use. The list read the app polls while a picker is open never sets anything up —
+ // it says whether it is needed (`gridSetupNeeded`). A Get needs a sign-in (the catalog is
+ // grid's); a Use serves on the account's own grid, and so does the Set up that offers it.
+ void (async () => {
+ const list = type === 'grid_fleet_models_list'
+ const setup = list ? payload.setup === true : type !== 'grid_fleet_model_stop'
+ const notReady = setup ? await this.gridNotReady(type !== 'grid_fleet_model_download') : null
+ const grid = await this.resolveGridName()
+ if (list) {
+ const snapshot = await this.localModels.list(grid, payload.refresh === true || setup)
+ const needed = this.gridSetUp ? !this.gridSetUp() : false
+ if (setup && !notReady) void this.pushGridModels()
+ return { ...snapshot, ...(needed ? { gridSetupNeeded: true } : {}), ...(notReady ? { gridSetupError: notReady } : {}) }
+ }
+ if (notReady) return { error: notReady }
+ return this.localModels.act(grid, payload.modelId, type === 'grid_fleet_model_download' ? 'download' : type === 'grid_fleet_model_start' ? 'start' : 'stop')
+ })()
.then(result => reply(type, requestId, { ...result }))
.catch(() => reply(type, requestId, { error: 'Models are unavailable. Try again.' }))
return
@@ -2040,6 +2058,11 @@ export class BackendSocket {
const request = parseGridFleetRequest(payload)
if (!request || typeof requestId !== 'string') { reply(type, requestId, { error: 'INVALID_GRID_COMMAND' }); return }
// Detached: pulls/builds can take minutes. Keep typing, cancellation, and telemetry responsive.
+ // ⚠️ Run against grid AS IT STANDS — never set up first. A Grid harness session issues these
+ // on its own the moment its viewer comes up (every open one, on every daemon start), so
+ // setting grid up here signed a machine in to grid right after a Harness-only sign-in,
+ // with nobody asking. A person sets grid up through the picker's Set up or by opening the
+ // Model Manager; until then grid answers these in its own words.
void this.gridFleet.run(connId, requestId, request)
.then(result => reply(type, requestId, { ...result }))
.catch(() => reply(type, requestId, { ok: false, code: 1, error: 'Grid command failed unexpectedly.' }))
@@ -2882,9 +2905,15 @@ export class BackendSocket {
if (picked && payload.grid === undefined && !clear) {
// The grid the model was picked FROM, when the picker says (a shared grid's section);
// the account's own grid otherwise, as before.
- const pickedGrid = typeof payload.gridName === 'string' && payload.gridName.trim()
- ? payload.gridName.trim()
- : await this.resolveGridName()
+ // A move onto a grid model is a grid feature in use: grid is signed in first, if it is not
+ // yet — and the account's own grid made sure of when that is where the model is.
+ const named = typeof payload.gridName === 'string' && payload.gridName.trim() ? payload.gridName.trim() : null
+ const notReady = await this.gridNotReady(!named || named === this.harnessGridName)
+ if (notReady) {
+ reply(type, requestId, { error: 'GRID_UNAVAILABLE', detail: notReady })
+ return
+ }
+ const pickedGrid = named ?? await this.resolveGridName()
const resolved = await resolveGridTarget(pickedGrid, picked)
if (!resolved) {
reply(type, requestId, { error: 'GRID_UNAVAILABLE', detail: 'Could not read this machine\'s grid endpoint.' })
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index 58436198b..945780d83 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -70,15 +70,15 @@ import { LocalPresence, PAIR_HARNESS_DSH, ZooTurnCounter, ZooTurnReporter } from
import { ZooLessonReporter } from './lib/zooLessons.js'
import { DAEMONS_OFF, DAEMONS_OFF_DETAIL, DaemonsSwitch, localKillSwitch, zooPassthrough, type ZooRead } from './lib/daemonsSwitch.js'
import { handOffToGrid } from './lib/gridHandoff.js'
-import { ensureGridInstalled, type GridInstallResult } from './lib/gridInstall.js'
+import { ensureGridInstalled } from './lib/gridInstall.js'
import { ensureHarnessGrid, type EnsureStatus } from './lib/gridEnsure.js'
import { passThroughToGridLogout } from './lib/gridLogout.js'
import { clearGridMcpUrlCache } from './lib/gridMcpUrl.js'
import { warnIfGridSignInRemains } from './lib/gridCredentials.js'
-import { reconcileGridAttach, gridNamesLocal, createGridAttachRunner } from './lib/gridAttach.js'
+import { reconcileGridAttach, gridNamesLocal, createGridAccess } from './lib/gridAttach.js'
import { signedInGridEmail, resetGridDeriveMemo } from './lib/gridDerive.js'
import { forgetGridModels, gridAnnotation, keystrokePrewarm, observeMachineList, onGridModelsChanged, warmGridModels } from './lib/gridModels.js'
-import { gridAvailable } from './lib/gridExec.js'
+import { gridAvailable, managedGridPath } from './lib/gridExec.js'
import { ENGINE_CLI_COMMANDS, ENGINES, PROCESS_ENGINES, engineBin, enginePathOverride } from './lib/engineBin.js'
import { isTerminalEngine, type AgentEngine } from './engines/types.js'
import { PairJournal } from './pair/journal.js'
@@ -367,22 +367,9 @@ const ATTACH_CONCURRENCY = 4
// reported by the daemon in words rather than by the app as a timeout.
const PROXY_BACKEND_TIMEOUT_MS = 20_000
-/** Bounds the `POST /api/grid/name` inside the daemon-start grid reconcile, so a stalled control-plane
- * connection cannot hold it open. */
+/** Bounds the `POST /api/grid/name` a grid set-up makes (`ensureGrid`, `harness grid login`), so a
+ * stalled control-plane connection cannot hold it open. */
const GRID_MINT_TIMEOUT_MS = 10_000
-/** How long the grid RPCs will gate on a grid-attach attempt before answering without it, whether or
- * not it has settled — the ceiling that keeps a stuck attempt from degrading every grid RPC for the
- * daemon's whole life (`gridReadyProbe`). */
-const GRID_ATTACH_CEILING_MS = 30_000
-/** How many grid-attach attempts one daemon makes before giving up until its next start. A machine
- * still unattached after this many reachable moments has a problem that retrying will not fix, and
- * each attempt past that is a grid sign-in — and a token rotation — bought for nothing. */
-const GRID_ATTACH_MAX_ATTEMPTS = 5
-/** The soonest one attempt may follow another. Retries are driven by backend reconnects, and waking
- * a laptop, changing network or toggling a VPN produces several within seconds; without this floor
- * one moment of ordinary churn spent the whole allowance above and the feature went quiet for the
- * daemon's life. Requests inside the window are deferred to its end, not dropped. */
-const GRID_ATTACH_MIN_INTERVAL_MS = 60_000
/** Between session-binding attempts for a process whose engine store is not resolvable yet. */
const REPAIR_RETRY_MS = 60_000
@@ -724,42 +711,6 @@ type SignInOutcome =
/** Refused. Under `--json` its own coded result line has already been emitted. */
| { signedIn: false }
-/**
- * Sign this computer in to its grid too, and make sure the account's private harness grid exists.
- *
- * ⚠️ **Best-effort, always.** A machine with no `grid`, one too old for `--harness`, a grid sign-in
- * that fails, a backend that predates `POST /api/grid/name` — every one of them is a sentence on
- * stderr and a harness sign-in that still succeeds. The harness is what the person asked for; the
- * grid is what it can usually also arrange. `harness grid login` stays the explicit path, where the
- * same failure IS the command's failure and exits non-zero.
- *
- * Returns what happened, so `--json` callers can carry it on their own result line.
- */
-async function attachGridToSignIn(
- token: string,
- json: boolean,
- installing: Promise<GridInstallResult> = ensureGridInstalled(),
-): Promise<Record<string, unknown>> {
- const note = (line: string): void => { if (!json) console.error(` · ${line}`) }
- // A machine with no `grid` gets one first, from grid's own installer — the sign-in that follows
- // is what makes it useful, and "install the grid CLI yourself" was the sentence every fresh
- // machine used to stop at. Best-effort: a failed install is a note, and the hand-off below then
- // reports the missing binary exactly as before. A forced sign-in starts the install before it
- // takes the daemon spawn lock and hands the promise in (see loginCommand): the installer is
- // account-agnostic and can run for minutes, and neither the browser wait nor a start queued on
- // that lock should be spent on it.
- const install = await installing
- if (install.status === 'installed') note(install.message)
- else if (install.status !== 'present') note(install.message)
- const handoff = await handOffToGrid(token, { json: true })
- if (handoff.code !== 'OK') {
- note(handoff.message)
- return { grid: { signedIn: false, code: handoff.code } }
- }
- const { status, name } = await ensureAccountGrid(note)
- return { grid: { signedIn: true, ensured: status, ...(name ? { name } : {}) } }
-}
-
/**
* The account's private grid exists — its name minted or read, then the grid itself created if it is
* not there yet.
@@ -804,21 +755,12 @@ async function loginCommand(
// command and says so with `--entry-point=desktop`. Analytics only — it names no privilege.
const entryPoint = opts.entryPoint ?? 'cli'
const emit = (line: Record<string, unknown>): void => { if (json) console.log(JSON.stringify(line)) }
- const succeed = async (alreadySignedIn: boolean, installing?: Promise<GridInstallResult>): Promise<SignInOutcome> => {
- // `chained` is `harness grid login`, which runs the hand-off itself and reports it as its own
- // result — doing it here too would sign in to the grid twice and print two answers for one act.
- let grid: Record<string, unknown> = {}
- if (!opts.chained) {
- try {
- grid = await attachGridToSignIn(await new AuthSessionManager(backendHttpBase()).accessToken(), json, installing)
- } catch {
- // The harness session is already saved and valid; a grid step that throws is still only a
- // grid step. Never let it turn a completed sign-in into a failure.
- grid = {}
- }
- }
+ // Harness only. Grid is an add-on: this computer is signed in to it the first time a grid feature is
+ // used (`ensureGrid` in the daemon, `lib/gridAttach.ts`) — with this session's token, no second
+ // browser — and never as a side effect of signing in to Harness.
+ const succeed = async (alreadySignedIn: boolean): Promise<SignInOutcome> => {
if (opts.chained) return { signedIn: true, alreadySignedIn }
- if (json) emit(alreadySignedIn ? { type: 'result', status: 'success', alreadySignedIn: true, ...grid } : { type: 'result', status: 'success', ...grid })
+ if (json) emit(alreadySignedIn ? { type: 'result', status: 'success', alreadySignedIn: true } : { type: 'result', status: 'success' })
else if (alreadySignedIn) console.log('\n ✓ Already signed in. Run `harness start` to connect this computer.\n')
else console.log('\n ✓ Signed in. Run `harness start` to connect this computer.\n')
return { signedIn: true, alreadySignedIn }
@@ -851,15 +793,8 @@ async function loginCommand(
// reads whatever session is on disk: for as long as the browser is open, the old account's. The
// daemon it spawned came up on the old account and stayed — the `harness start` this command
// recommends afterwards found it "already running" — so the whole switch, from the stop until the
- // new session (and its grid hand-off) is on disk, holds the daemon spawn lock: a start that lands
+ // new session is on disk, holds the daemon spawn lock: a start that lands
// meanwhile waits its turn and then reads the new session.
- //
- // The grid CLI install is the one long thing in there that needs no account, so it starts NOW —
- // before the lock, before the old daemon is stopped — and runs under the browser wait; `succeed`
- // awaits only what is left of it. The handler keeps a failed download from being an unhandled
- // rejection while nobody is waiting on it: the sign-in reads the outcome later, as a note.
- const installing = opts.chained ? undefined : ensureGridInstalled()
- installing?.catch(() => { /* reported where it is awaited */ })
try {
return await withSpawnLock('login', async () => {
// ⚠️ A daemon running WITHOUT a session holds no account to switch away from, and stopping it
@@ -867,7 +802,7 @@ async function loginCommand(
// the browser. There is nothing to race either: the lock is held, and the identity swap happens
// afterwards, once there is an identity to swap to (`restartDaemonForIdentity`).
if (readAuthSession()) await stopDaemonProcess()
- return await browserSignIn(json, emit, () => succeed(false, installing), entryPoint)
+ return await browserSignIn(json, emit, () => succeed(false), entryPoint)
}, {
onWaiting: (owner) => console.error(` the daemon is ${describeSpawnLockOwner(owner)} — waiting for it to finish…`),
})
@@ -1501,18 +1436,19 @@ async function runForeground(session: AuthSession | null): Promise<void> {
catch { console.warn('[apis] Tool instructions could not be added. Saved connections remain available through harness api.') }
}
- // The managed grid follows its pin on EVERY daemon start — this one, and the restart a self-update
- // ends in — not only on `--repair`: the pin is expected to move, and a machine installed last month
- // has to notice. Not awaited here: a download must never hold the control port back, and every grid
- // call resolves the binary afresh (`gridBinaryPath`), so whatever lands is picked up as it lands.
- // Best-effort by construction — it returns rather than throws — and the fatal guard above is the
- // net under the promise itself. The promise is kept so the grid reconcile below can wait for the
- // pinned binary before it hands a token over.
- const managedGridReady = ensureManagedGrid((m) => console.log(`[grid-runtime] ${m}`))
- void managedGridReady
+ // A managed grid already here follows its pin on EVERY daemon start — this one, and the restart a
+ // self-update ends in — not only on `--repair`: the pin is expected to move, and a machine installed
+ // last month has to notice. A machine with none gets none from a start: grid is an add-on, installed
+ // the first time a grid feature is used (`ensureGrid`, below). Not awaited: a download must never
+ // hold the control port back, and every grid call resolves the binary afresh (`gridBinaryPath`), so
+ // whatever lands is picked up as it lands. Best-effort by construction — it returns, never throws.
+ const followGridPin = (): Promise<unknown> => managedGridPath()
+ ? ensureManagedGrid((m) => console.log(`[grid-runtime] ${m}`))
+ : Promise.resolve(null)
+ void followGridPin()
// …and keeps following it while this daemon runs: a pin moved after the start reaches it within ten
// minutes rather than at the next restart (`startGridPinRecheck`).
- startGridPinRecheck()
+ startGridPinRecheck({ ensure: followGridPin })
registry.load()
// Persisted locators are hints until this process has observed their terminal root and PID/start marker.
@@ -1989,36 +1925,26 @@ async function runForeground(session: AuthSession | null): Promise<void> {
backendRef = backend
backend.viewerTargetProvider = (agentId) => dshViewers.forwardingUrl(agentId)
- // Bring this machine's grid sign-in into line with its harness sign-in, in the background.
- // This is what makes a machine that signed in to the harness BEFORE grid existed usable after an
- // update: it has the `grid` binary now (above), but no grid credentials and no grid to point at
- // until something signs it in — and the login *event* that used to do that never fires again for
- // an already-signed-in account. Reconciling on daemon start (the path every update takes) removes
- // the `harness logout` / `harness login` a person would otherwise have to run by hand.
- //
- // Best-effort and non-blocking: it awaits the managed grid, mints/reads the account's name, and
- // signs in + creates the grid only when the machine is not already there. The RPCs that need the
- // name wait briefly for it through `gridReadyProbe`.
- //
- // ⚠️ Retried on backend RECONNECT, not just at start, and this is not belt-and-braces: the daemon
- // OUTLIVES the desktop app (it must keep running after the window closes), and `harness start`
- // against a live daemon returns without starting a new one. So "start" can be days ago, and a
- // single attempt that lost to a control plane which was not reachable yet — the ordinary shape of
- // a daemon coming up with the network — would leave the account with no grid until the next real
- // restart. A connect is the evidence the control plane is reachable, so it is when to try again.
- // How long the RPCs gate on an attempt, and how many attempts there are, live in the runner —
- // `lib/gridAttach.ts`, beside the reconcile itself, so the coordination has a unit test rather
- // than only a comment. Everything below is the daemon-shaped half: what one attempt actually does.
try { ensureBundledModelManager() }
catch (error) { console.warn('[model-manager] Could not prepare the bundled harness:', error instanceof Error ? error.message : String(error)) }
- const gridAttach = createGridAttachRunner({
- maxAttempts: GRID_ATTACH_MAX_ATTEMPTS,
- minIntervalMs: GRID_ATTACH_MIN_INTERVAL_MS,
- ceilingMs: GRID_ATTACH_CEILING_MS,
- log: (line) => console.log(`[grid-attach] ${line}`),
- attempt: () => reconcileGridAttach({
- managedGridReady,
+ // Grid is an add-on (`lib/gridAttach.ts`): nothing on this path installs `grid`, signs this machine in
+ // to it or creates a grid. The first grid feature a person uses — the models picker's Set up, a local
+ // model's Get or Use, an agent moved onto a grid model, the Model Manager — asks `backend.ensureGrid`,
+ // which does it then, with this machine's harness token (no second browser) and, only for what needs
+ // one, the account's own grid. It used to run here on every start and every reconnect.
+ const gridLog = (line: string): void => console.log(`[grid-attach] ${line}`)
+ const gridAccess = createGridAccess({
+ signedIn: () => signedInGridEmail() !== null,
+ log: gridLog,
+ attempt: ({ ownGrid, signedInThisRun }) => reconcileGridAttach({
+ // The pinned managed runtime first; grid's own installer when there is none to follow.
+ installCli: async () => {
+ await ensureManagedGrid((m) => console.log(`[grid-runtime] ${m}`))
+ if (gridAvailable()) return
+ const installed = await ensureGridInstalled()
+ if (installed.status !== 'present') gridLog(installed.message)
+ },
gridAvailable: () => gridAvailable(),
// The backend mints and remembers the name; this CLI holds neither the account's email nor its
// id. An older backend (no route) answers nothing, which the reconcile treats as "no grid yet".
@@ -2040,17 +1966,16 @@ async function runForeground(session: AuthSession | null): Promise<void> {
resetGridDeriveMemo()
clearGridMcpUrlCache()
},
- log: (line) => console.log(`[grid-attach] ${line}`),
- }),
+ log: gridLog,
+ }, { ownGrid, signedInThisRun }),
})
-
- // While an attempt is running AND within its ceiling, the RPCs that need the grid name wait
- // briefly on it; otherwise they read the name directly.
- backend.gridReadyProbe = () => gridAttach.probe()
+ backend.ensureGrid = (request) => gridAccess.ensure(request)
+ // Offline, for every list read: is there a `grid` here holding a sign-in? What decides whether the
+ // picker offers local and shared models or a Set up row.
+ backend.gridSetUp = () => gridAvailable() && signedInGridEmail() !== null
// Re-read the zoo on every reconnect as well, while daemons are on: a `zoo_changed` sent while the link
// was down is lost. Off, a reconnect asks nothing (lib/daemonsSwitch.ts).
- onBackendConnected = () => { gridAttach.run(); daemons.connected() }
- gridAttach.run()
+ onBackendConnected = () => { daemons.connected() }
/**
* Is ANY device surface watching this machine?
@@ -4979,12 +4904,6 @@ async function runForeground(session: AuthSession | null): Promise<void> {
hookStep('codex', () => installCodexHooks(hookPort))
hookStep('cursor', () => installCursorHooks(hookPort))
hookStep('opencode', () => installOpencodePlugin(hookPort))
- // The `grid` CLI the Grid harness shells out to, for a machine that signed in before this
- // existed or whose sign-in could not fetch it. In the background: a download must not hold
- // the daemon's own start, and nothing here waits on it.
- void ensureGridInstalled().then((result) => {
- if (result.status !== 'present') console.log(`[grid] ${result.message}`)
- })
hookStep('kilo', () => installKiloPlugin(hookPort))
hookStep('pi', () => installPiExtension(hookPort))
// A self-update refreshes plugin files here; running engine processes pick them up according to each
diff --git a/cli/src/lib/daemonsSwitch.spec.ts b/cli/src/lib/daemonsSwitch.spec.ts
index a76548dfa..cef558e90 100644
--- a/cli/src/lib/daemonsSwitch.spec.ts
+++ b/cli/src/lib/daemonsSwitch.spec.ts
@@ -470,7 +470,7 @@ describe('cli.ts routes everything daemon-related through the switch', () => {
}
expect(source).toContain('onDaemonShown: (connId, payload) => { if (daemons.on()) pairBrain?.onShown(connId, payload) }')
expect(source).toContain('if (daemons.on()) pairBrain?.onPresence(connId, payload, meta)')
- expect(source).toContain('onBackendConnected = () => { gridAttach.run(); daemons.connected() }')
+ expect(source).toContain('onBackendConnected = () => { daemons.connected() }')
expect(source).toContain('backend.onZooChanged = () => daemons.zooChanged()')
})
})
diff --git a/cli/src/lib/gridAttach.spec.ts b/cli/src/lib/gridAttach.spec.ts
index 0dc1cd96c..71a303d7a 100644
--- a/cli/src/lib/gridAttach.spec.ts
+++ b/cli/src/lib/gridAttach.spec.ts
@@ -1,5 +1,5 @@
import { describe, expect, it, vi } from 'vitest'
-import { reconcileGridAttach, createGridAttachRunner, type GridAttachDeps, type GridAttachResult } from './gridAttach.js'
+import { reconcileGridAttach, createGridAccess, type GridAttachDeps, type GridAttachResult } from './gridAttach.js'
import type { GridHandoffResult } from './gridHandoff.js'
import type { EnsureResult } from './gridEnsure.js'
@@ -20,7 +20,7 @@ function deps(over: Partial<GridAttachDeps> = {}): GridAttachDeps & {
onName: ReturnType<typeof vi.fn>
} {
const base = {
- managedGridReady: Promise.resolve(),
+ installCli: async () => {},
gridAvailable: () => true,
mintName: async () => NAME,
accessToken: async () => 'tok',
@@ -34,7 +34,7 @@ function deps(over: Partial<GridAttachDeps> = {}): GridAttachDeps & {
return { ...base, ...over } as never
}
-describe('reconcileGridAttach — the daemon-start convergence', () => {
+describe('reconcileGridAttach — bringing grid into line for a grid feature', () => {
it('does nothing but publish the name when already signed in as the right account with the grid present', async () => {
const d = deps()
const r = await reconcileGridAttach(d)
@@ -138,12 +138,12 @@ describe('reconcileGridAttach — the daemon-start convergence', () => {
expect(d.onName).not.toHaveBeenCalled()
})
- it('waits for the managed grid runtime before checking the binary', async () => {
+ it('installs grid before checking the binary', async () => {
const order: string[] = []
let releaseRuntime = (): void => {}
const runtime = new Promise<void>((res) => { releaseRuntime = () => { order.push('runtime'); res() } })
const d = deps({
- managedGridReady: runtime,
+ installCli: () => runtime,
gridAvailable: () => { order.push('available'); return false },
})
@@ -156,150 +156,115 @@ describe('reconcileGridAttach — the daemon-start convergence', () => {
expect(order).toEqual(['runtime', 'available'])
})
- it('does not let a rejected runtime promise throw — a failed download is best-effort', async () => {
- const d = deps({ managedGridReady: Promise.reject(new Error('download failed')), gridAvailable: () => false })
+ it('does not let a failed install throw — the binary check says what is missing', async () => {
+ const d = deps({ installCli: async () => { throw new Error('download failed') }, gridAvailable: () => false })
await expect(reconcileGridAttach(d)).resolves.toMatchObject({ status: 'no-cli' })
})
-})
-
-/**
- * The coordination half: WHEN a reconcile runs. The daemon calls `run()` at start and again on every
- * backend reconnect, so every property here is about the interaction of those calls.
- */
-describe('createGridAttachRunner — when a reconcile runs', () => {
- const result = (status: GridAttachResult['status']): GridAttachResult => ({ status, name: NAME, detail: '' })
- /** A clock the test moves by hand, so nothing here waits on real time. */
- function clock(start = 1_000_000) {
- let t = start
- return { now: () => t, advance: (ms: number) => { t += ms } }
- }
-
- function runner(over: Partial<Parameters<typeof createGridAttachRunner>[0]> = {}, c = clock()) {
- const attempt = vi.fn(async () => result('converged'))
- const logs: string[] = []
- const r = createGridAttachRunner({
- attempt,
- maxAttempts: 3,
- minIntervalMs: 1_000,
- ceilingMs: 5_000,
- now: c.now,
- log: (line) => logs.push(line),
- ...over,
- })
- return { r, attempt: (over.attempt ?? attempt) as ReturnType<typeof vi.fn>, logs, clock: c }
- }
-
- it('runs once and stops once attached — a later reconnect costs nothing', async () => {
- const { r, attempt, clock: c } = runner()
+ it("signs in without making a grid when the feature needs no grid of the account's own", async () => {
+ const d = deps({ signedInEmail: () => null, gridNames: async () => [] })
+ const r = await reconcileGridAttach(d, { ownGrid: false })
+ expect(r).toMatchObject({ status: 'signed-in', name: NAME })
+ expect(r).not.toHaveProperty('ownGrid')
+ expect(d.handoff).toHaveBeenCalledWith('tok')
+ expect(d.ensure).not.toHaveBeenCalled()
+ })
- r.run()
- await r.probe()
- expect(attempt).toHaveBeenCalledOnce()
+ it('reports what making the own grid came to', async () => {
+ const d = deps({ signedInEmail: () => null, gridNames: async () => [], ensure: vi.fn(async () => CREATED) })
+ expect(await reconcileGridAttach(d, { ownGrid: true })).toMatchObject({ status: 'signed-in', ownGrid: 'created' })
+ expect(await reconcileGridAttach(deps(), { ownGrid: true })).toMatchObject({ status: 'converged', ownGrid: 'existed' })
+ })
- c.advance(10_000) // well past the interval, so only "already attached" can stop a second run
- r.run()
- expect(attempt).toHaveBeenCalledOnce()
+ it('signed in earlier this run: a feature with no own grid to make needs nothing more', async () => {
+ // No own grid yet, so the gate cannot prove the account — the earlier sign-in this run does.
+ const d = deps({ gridNames: async () => [] })
+ expect(await reconcileGridAttach(d, { ownGrid: false, signedInThisRun: true })).toMatchObject({ status: 'converged' })
+ expect(d.handoff).not.toHaveBeenCalled()
+ expect(d.ensure).not.toHaveBeenCalled()
})
- it('does not overlap: a reconnect during an in-flight attempt is a no-op', async () => {
- let release = (): void => {}
- const gate = new Promise<void>((res) => { release = res })
- const attempt = vi.fn(async () => { await gate; return result('converged') })
- const { r, clock: c } = runner({ attempt })
-
- r.run()
- c.advance(10_000)
- r.run()
- r.run()
- expect(attempt).toHaveBeenCalledOnce()
-
- release()
- await r.probe()
- expect(attempt).toHaveBeenCalledOnce()
+ it('signed in earlier this run and now the own grid is wanted: made, without a second hand-off', async () => {
+ // Every hand-off rotates the account's grid token; one per sign-in is the whole budget.
+ const d = deps({ gridNames: async () => [], ensure: vi.fn(async () => CREATED) })
+ expect(await reconcileGridAttach(d, { ownGrid: true, signedInThisRun: true })).toMatchObject({ status: 'signed-in', ownGrid: 'created' })
+ expect(d.handoff).not.toHaveBeenCalled()
+ expect(d.ensure).toHaveBeenCalledWith(NAME)
})
+})
- it('retries after an attempt that did not attach, once the interval has passed', async () => {
- const attempt = vi.fn(async () => result('no-name'))
- const { r, clock: c } = runner({ attempt })
+/**
+ * The coordination half: when a reconcile runs — on demand, one at a time, never twice for what is
+ * already done, and never as a remembered failure.
+ */
+describe('createGridAccess — grid set up when a feature asks', () => {
+ const result = (status: GridAttachResult['status'], ownGrid?: GridAttachResult['ownGrid']): GridAttachResult =>
+ ({ status, name: NAME, detail: '', ...(ownGrid ? { ownGrid } : {}) })
- r.run()
- await r.probe()
- expect(attempt).toHaveBeenCalledOnce()
+ function access(answers: GridAttachResult[], signedIn = () => true) {
+ const attempt = vi.fn(async (_request: { ownGrid: boolean; signedInThisRun: boolean }) => answers.shift() ?? result('converged', 'existed'))
+ return { attempt, grid: createGridAccess({ attempt, signedIn, log: () => {} }) }
+ }
- c.advance(1_000)
- r.run()
- await r.probe()
- expect(attempt).toHaveBeenCalledTimes(2)
+ it('remembers a sign-in: asking again for the same costs nothing', async () => {
+ const { attempt, grid } = access([result('signed-in')])
+ await grid.ensure()
+ await grid.ensure()
+ expect(attempt.mock.calls).toEqual([[{ ownGrid: false, signedInThisRun: false }]])
})
- it('collapses a burst of reconnects into ONE deferred attempt instead of burning the budget', async () => {
- vi.useFakeTimers()
- try {
- const attempt = vi.fn(async () => result('no-name'))
- // A real clock is not advanced by fake timers, so the runner reads the same injected one.
- const c = clock()
- const { r } = runner({ attempt }, c)
-
- r.run()
- await r.probe()
- expect(attempt).toHaveBeenCalledTimes(1)
-
- // Waking a laptop: several reconnects inside the interval. None may start an attempt, and
- // together they must cost exactly one — the whole point of deferring rather than dropping.
- for (let i = 0; i < 5; i++) r.run()
- expect(attempt).toHaveBeenCalledTimes(1)
- expect(r.attempts()).toBe(1)
-
- c.advance(1_000)
- await vi.advanceTimersByTimeAsync(1_000)
- expect(attempt).toHaveBeenCalledTimes(2)
- // Four attempts' worth of churn cost one, so the cap of 3 is not spent.
- expect(r.attempts()).toBe(2)
- } finally {
- vi.useRealTimers()
- }
+ it('asks again for the own grid, telling the reconcile this run is already signed in', async () => {
+ const { attempt, grid } = access([result('signed-in'), result('signed-in', 'created')])
+ await grid.ensure({ ownGrid: false })
+ await grid.ensure({ ownGrid: true })
+ await grid.ensure({ ownGrid: true })
+ expect(attempt.mock.calls).toEqual([
+ [{ ownGrid: false, signedInThisRun: false }],
+ [{ ownGrid: true, signedInThisRun: true }],
+ ])
})
- it('gives up out loud at the cap, and says it only once', async () => {
- const attempt = vi.fn(async () => result('no-name'))
- const { r, logs, clock: c } = runner({ attempt })
-
- for (let i = 0; i < 3; i++) {
- c.advance(1_000)
- r.run()
- await r.probe()
- }
- expect(attempt).toHaveBeenCalledTimes(3)
-
- c.advance(1_000)
- r.run()
- c.advance(1_000)
- r.run()
- expect(attempt).toHaveBeenCalledTimes(3)
- expect(logs.filter((l) => l.includes('giving up'))).toHaveLength(1)
+ it('one at a time: a Set up and a Get pressed together make one sign-in', async () => {
+ let finish: (r: GridAttachResult) => void = () => {}
+ const attempt = vi.fn(() => new Promise<GridAttachResult>((resolve) => { finish = resolve }))
+ const grid = createGridAccess({ attempt, signedIn: () => true, log: () => {} })
+ const first = grid.ensure({ ownGrid: true })
+ const second = grid.ensure({ ownGrid: false })
+ await Promise.resolve()
+ finish(result('signed-in', 'created'))
+ expect((await first).status).toBe('signed-in')
+ expect((await second).status).toBe('signed-in')
+ expect(attempt).toHaveBeenCalledTimes(1)
})
- it('a rejected attempt is logged and retried, never thrown', async () => {
- const attempt = vi.fn(async () => { throw new Error('boom') })
- const { r, logs, clock: c } = runner({ attempt })
-
- expect(() => r.run()).not.toThrow()
- await r.probe()
- expect(logs.some((l) => l.includes('boom'))).toBe(true)
-
- c.advance(1_000)
- r.run()
+ it('does not remember a failure: the next ask is a person acting again, so it tries again', async () => {
+ const { attempt, grid } = access([result('handoff-failed'), result('signed-in')])
+ expect((await grid.ensure()).status).toBe('handoff-failed')
+ expect((await grid.ensure()).status).toBe('signed-in')
expect(attempt).toHaveBeenCalledTimes(2)
})
- it('probe stops offering the attempt once its ceiling passes, so an RPC never waits on a stuck one', async () => {
- const attempt = vi.fn(async () => new Promise<GridAttachResult>(() => {})) // never settles
- const { r, clock: c } = runner({ attempt })
+ it('an own grid that could not be made is asked for again next time', async () => {
+ const { attempt, grid } = access([result('signed-in', 'failed'), result('signed-in', 'created')])
+ expect((await grid.ensure({ ownGrid: true })).ownGrid).toBe('failed')
+ expect((await grid.ensure({ ownGrid: true })).ownGrid).toBe('created')
+ expect(attempt.mock.calls[1]).toEqual([{ ownGrid: true, signedInThisRun: true }])
+ })
+
+ it('forgets everything once grid holds no sign-in — a `grid logout` run by hand', async () => {
+ let signedIn = true
+ const { attempt, grid } = access([result('signed-in', 'created'), result('signed-in', 'existed')], () => signedIn)
+ await grid.ensure({ ownGrid: true })
+ signedIn = false
+ await grid.ensure({ ownGrid: true })
+ expect(attempt.mock.calls).toEqual([
+ [{ ownGrid: true, signedInThisRun: false }],
+ [{ ownGrid: true, signedInThisRun: false }],
+ ])
+ })
- r.run()
- expect(r.probe()).not.toBeNull()
- c.advance(5_000)
- expect(r.probe()).toBeNull()
+ it('an attempt that throws resolves as a failed hand-off — it never rejects on the caller', async () => {
+ const grid = createGridAccess({ attempt: async () => { throw new Error('boom') }, signedIn: () => true, log: () => {} })
+ await expect(grid.ensure()).resolves.toMatchObject({ status: 'handoff-failed', detail: 'boom' })
})
})
diff --git a/cli/src/lib/gridAttach.ts b/cli/src/lib/gridAttach.ts
index 326ec0677..34da14927 100644
--- a/cli/src/lib/gridAttach.ts
+++ b/cli/src/lib/gridAttach.ts
@@ -1,42 +1,28 @@
/**
- * Bring this machine's grid sign-in into line with its harness sign-in — on every daemon start.
+ * Bring this machine's grid sign-in into line with its harness sign-in — when a grid feature needs it.
*
- * The harness sign-in and the grid sign-in used to be one act, wired to the login *event*
- * (`attachGridToSignIn` in `cli.ts`). A machine that signed in to the harness before grid existed
- * never re-runs that event, so after an update it has a `grid` binary but no grid credentials and no
- * grid to point at — the Local model picker reads "No local models on this account yet." and there
- * is nothing a person can do about it but `harness logout` / `harness login`.
+ * Grid is an add-on to Harness, not part of signing in: a person who never touches local or shared
+ * models never gets a `grid` binary, a grid sign-in or a grid of their own. The first time something
+ * does need grid — "Set up" on the models picker's local and shared models, a local model's Get or
+ * Use, an agent moved onto a grid model, the Model Manager — the daemon calls [GridAccess.ensure],
+ * which installs `grid` if it is missing, hands this machine's harness token to `grid login --harness`
+ * over stdin (no second browser, `gridHandoff.ts`), and — only for what needs one — makes sure the
+ * account's private grid exists. It used to run on every daemon start and every backend reconnect,
+ * and signing in to Harness did it too; neither does now.
*
- * This is the reconcile that removes that step. It runs once per daemon start (the point every update
- * path — `harness start`, `harness update`, the self-update restart, the desktop's re-probe — passes
- * through) and answers one question: *is this machine already signed in to grid as the right account,
- * with the account's private grid present?* If yes, it does nothing but publish the name. If no, it
- * hands the harness token to `grid login --harness` and makes sure the grid exists — the same two
- * steps the login event does, now driven by state rather than by an event that will not fire again.
+ * **Silent account switch.** When this machine is signed in to grid as a *different* account, the
+ * hand-off overwrites it without asking, matching `grid login`'s own rule (a swap is a line, never a
+ * refusal): Harness's grid features run as the Harness account or not at all. `grid login --harness`
+ * never touches a running `grid join --serve` child; it only warns about one whose grid has gone.
*
- * **Best-effort by construction.** A machine with no `grid`, an older backend that mints no name, a
- * control plane having a bad minute — each is a log line and a daemon that runs exactly as before.
- * Nothing here can fail a daemon start.
- *
- * **Convergence, not a timer.** The gate below is almost entirely offline (a file read and one
- * `grid ls` that makes no network call), so the common path — a machine already set up — costs one
- * `POST /api/grid/name` (idempotent, mostly a read) and nothing else. A grid sign-in is created or
- * refreshed only when the gate says it is missing or belongs to another account.
- *
- * ⚠️ It converges only where the grid CAN exist. An account that cannot hold this grid at all — the
- * free-plan network limit is the real case — never satisfies the gate, so every daemon start signs in
- * again and tries again. That costs a token rotation per start, not a loop within one, and it is the
- * deliberate trade: the alternative is remembering a failure across starts on disk, which would also
- * remember it after the account was fixed. `ensure`'s own message says which limit was hit.
- *
- * **Overwrite is deliberate.** When this machine is signed in to grid as a *different* account, the
- * hand-off overwrites it, matching `grid login`'s own rule (a swap is a line, never a refusal) and
- * the harness's "grid sign-in is part of harness sign-in" contract. `grid login --harness` never
- * touches a running `grid join --serve` child; it only warns about one whose grid has gone.
+ * **Cheap when there is nothing to do.** The gate is almost entirely offline (a file read and one
+ * `grid ls` that makes no network call) plus one idempotent `POST /api/grid/name`, and a success is
+ * remembered for the daemon's life ([createGridAccess]), so the acts that ask again pay nothing.
*/
+
import { gridJson } from './gridExec.js'
import type { GridHandoffResult } from './gridHandoff.js'
-import type { EnsureResult } from './gridEnsure.js'
+import type { EnsureResult, EnsureStatus } from './gridEnsure.js'
export type GridAttachStatus =
/** No `grid` on this machine — there is nothing to attach a sign-in to. */
@@ -46,8 +32,8 @@ export type GridAttachStatus =
/** This machine's `grid` already knows the account's grid — signed in as the right account, grid
* present. Nothing was changed. */
| 'converged'
- /** The token was handed over (a fresh sign-in, a re-sign-in, or an account swap), then the grid
- * ensured. */
+ /** The token was handed over (a fresh sign-in, a re-sign-in, or an account swap) — then, when it
+ * was asked for, the account's grid ensured ([GridAttachResult.ownGrid]). */
| 'signed-in'
/** The hand-off was needed and did not succeed. The harness sign-in is untouched. */
| 'handoff-failed'
@@ -58,6 +44,9 @@ export interface GridAttachResult {
name: string | null
/** One sentence for a caller that wants to log the outcome. Never contains a credential. */
detail: string
+ /** What making sure the account's own grid exists came to, when it was asked for; absent when only
+ * a sign-in was needed. `converged` means the grid is there already. */
+ ownGrid?: EnsureStatus
}
/**
@@ -66,10 +55,10 @@ export interface GridAttachResult {
* which alone holds the HTTP helpers and the live `BackendSocket`.
*/
export interface GridAttachDeps {
- /** Awaited first: the managed grid runtime may still be landing, and the hand-off must run on the
- * pinned binary rather than whatever PATH had a moment earlier. A rejection is ignored — a failed
- * download is the binary check's story to tell, not this await's. */
- managedGridReady: Promise<unknown>
+ /** Awaited first: puts `grid` on a machine that has none (the pinned managed runtime, else grid's
+ * own installer), so the hand-off runs on the binary that will serve. A rejection is ignored — a
+ * failed download is the binary check's story to tell, not this await's. */
+ installCli: () => Promise<unknown>
/** Is there a `grid` to run at all? */
gridAvailable: () => boolean
/** `POST /api/grid/name` — the account's private grid name, minted if this is its first ask. Null
@@ -100,9 +89,12 @@ function msg(err: unknown): string {
* Reconcile this machine's grid sign-in with its harness account. See the module comment for the
* shape of the decision; the branches below are exactly its four answers.
*/
-export async function reconcileGridAttach(deps: GridAttachDeps): Promise<GridAttachResult> {
- // A download must not hold this back, but the hand-off below needs whatever it produced.
- try { await deps.managedGridReady } catch { /* the binary check answers a failed download */ }
+export async function reconcileGridAttach(
+ deps: GridAttachDeps,
+ opts: { ownGrid?: boolean; signedInThisRun?: boolean } = {},
+): Promise<GridAttachResult> {
+ const ownGrid = opts.ownGrid ?? true
+ try { await deps.installCli() } catch { /* the binary check answers a failed download */ }
if (!deps.gridAvailable()) {
deps.log('no grid CLI on this machine yet — nothing to attach a sign-in to')
@@ -142,6 +134,13 @@ export async function reconcileGridAttach(deps: GridAttachDeps): Promise<GridAtt
if (email && names.includes(name)) {
deps.onName(name)
deps.log(`already signed in with grid '${name}' — nothing to do`)
+ return { status: 'converged', name, detail: '', ...(ownGrid ? { ownGrid: 'existed' as const } : {}) }
+ }
+ // Signed in as this account earlier in this daemon's life, and nothing here needs the account's own
+ // grid: the sign-in is all there is to have. (A grid of its own is not proof this machine is signed
+ // in — the gate above — only for an account that has one.)
+ if (!ownGrid && email && opts.signedInThisRun) {
+ deps.onName(name)
return { status: 'converged', name, detail: '' }
}
@@ -151,113 +150,93 @@ export async function reconcileGridAttach(deps: GridAttachDeps): Promise<GridAtt
// (decision 1, and the module comment). When it was already the right account but the grid was
// merely missing locally, this re-fetches the account's grids before ensuring — a small redundancy
// that only recurs until the grid is created and synced, after which the converged path skips it.
- let token: string
- try {
- token = await deps.accessToken()
- } catch (err) {
- deps.log(`no harness token to hand to grid (${msg(err)})`)
- return { status: 'handoff-failed', name, detail: msg(err) }
+ // Signed in as this account already this run: only the grid is missing, so no second hand-off —
+ // each one rotates the account's grid token.
+ if (!(email && opts.signedInThisRun)) {
+ let token: string
+ try {
+ token = await deps.accessToken()
+ } catch (err) {
+ deps.log(`no harness token to hand to grid (${msg(err)})`)
+ return { status: 'handoff-failed', name, detail: msg(err) }
+ }
+ const handoff = await deps.handoff(token)
+ if (handoff.code !== 'OK') {
+ deps.log(`grid sign-in did not happen: ${handoff.message}`)
+ return { status: 'handoff-failed', name, detail: handoff.message }
+ }
}
- const handoff = await deps.handoff(token)
- if (handoff.code !== 'OK') {
- deps.log(`grid sign-in did not happen: ${handoff.message}`)
- return { status: 'handoff-failed', name, detail: handoff.message }
+ if (!ownGrid) {
+ deps.onName(name)
+ deps.log(`signed grid in as this account ('${name}' not needed yet)`)
+ return { status: 'signed-in', name, detail: '' }
}
const ensured = await deps.ensure(name)
deps.onName(name)
deps.log(`signed grid in and ensured '${name}': ${ensured.status}${ensured.message ? ` — ${ensured.message}` : ''}`)
- return { status: 'signed-in', name, detail: ensured.message }
+ return { status: 'signed-in', name, detail: ensured.message, ownGrid: ensured.status }
}
-/**
- * The grid names this machine's `grid` knows locally. `grid --remote ls` reads the stored registry
- * and makes no network call (autonomous-grid `cli/remote_grid.py`), so the reconcile's gate stays
- * cheap. An unparsable answer is no names, which the caller treats as "ensure it".
- */
-export interface GridAttachRunnerOptions {
- /** Runs one reconcile. Injected so the coordination below is testable without a daemon. */
- attempt: () => Promise<GridAttachResult>
- /** How many attempts this runner will ever make before it stops trying. */
- maxAttempts: number
- /** The soonest a new attempt may START after the previous one did. */
- minIntervalMs: number
- /** How long an in-flight attempt is worth making an RPC wait for, from when it started. */
- ceilingMs: number
- /** Injected clock, for tests. */
- now?: () => number
+/** A grid of the account's own is there: made, found, or won by another machine's create. */
+const OWN_GRID_THERE: ReadonlySet<string> = new Set(['created', 'existed', 'adopted'])
+
+export interface GridAccessOptions {
+ /** Runs one reconcile ([reconcileGridAttach]). Injected so the coordination is testable alone. */
+ attempt: (request: { ownGrid: boolean; signedInThisRun: boolean }) => Promise<GridAttachResult>
+ /** Whether `grid` still holds a sign-in on this machine (a file read) — a `grid logout` run by hand
+ * since forgets what this daemon remembered. */
+ signedIn: () => boolean
log: (line: string) => void
}
-export interface GridAttachRunner {
- /** Start an attempt if one is warranted. Safe to call as often as a reconnect fires. */
- run: () => void
- /** The in-flight attempt while it is still worth waiting for, else null. */
- probe: () => Promise<unknown> | null
- /** How many attempts have been started. Diagnostics and tests. */
- attempts: () => number
+export interface GridAccess {
+ /** Have grid ready for what the caller is about to do: signed in as this account, and — `ownGrid` —
+ * the account's grid there too. Resolves with what happened; never rejects. */
+ ensure: (request?: { ownGrid?: boolean }) => Promise<GridAttachResult>
}
/**
- * Decides WHEN to reconcile, as opposed to {@link reconcileGridAttach}, which decides what to do.
- *
- * Its own unit because the daemon calls `run()` from two places — once at start, then on every
- * backend reconnect — and every interesting property is about the interaction of those calls: two
- * attempts must not overlap, a burst of reconnects must not turn into a burst of grid sign-ins, and
- * the whole thing must eventually stop rather than rotate this account's tokens forever.
- *
- * **A burst collapses into one attempt, it does not burn the budget.** A laptop waking, changing
- * network or toggling a VPN produces several reconnects in seconds. Counting each as an attempt
- * spent the entire allowance on one moment of ordinary churn and then went quiet for the daemon's
- * life — which can be days. Requests inside `minIntervalMs` are therefore DEFERRED to the end of
- * that window rather than dropped, so the churn yields exactly one attempt and the opportunity is
- * not lost either. The timer is unref'd: it must never be a reason a process stays alive.
+ * When to reconcile, as opposed to {@link reconcileGridAttach}, which decides what to do: on demand,
+ * one at a time, and never twice for what is already done.
*
- * **It gives up out loud.** Reaching the cap says so once. Silence there was indistinguishable from
- * a feature that was working.
+ * - **One at a time.** Calls queue behind the one in flight and each then reads what it left behind,
+ * so a picker's Set up and a Get pressed a moment later make one sign-in, not two token rotations.
+ * - **Remembered.** A sign-in as this account, and the account's grid once it is there, hold for the
+ * daemon's life — until `grid` no longer holds a sign-in at all, which a hand-run `grid logout`
+ * leaves behind.
+ * - **Failures are not remembered.** Every ask is a person acting, so the next one simply tries again.
*/
-export function createGridAttachRunner(opts: GridAttachRunnerOptions): GridAttachRunner {
- const now = opts.now ?? Date.now
- let inFlight: Promise<unknown> | null = null
- let deferred: ReturnType<typeof setTimeout> | null = null
- let done = false
- let attempts = 0
- let lastStartedAt = Number.NEGATIVE_INFINITY
- let deadline = 0
- let saidGaveUp = false
+export function createGridAccess(opts: GridAccessOptions): GridAccess {
+ let signedIn = false
+ let ownGridThere = false
+ let last: GridAttachResult | null = null
+ let queue: Promise<unknown> = Promise.resolve()
- const run = (): void => {
- if (done || inFlight || deferred) return
- if (attempts >= opts.maxAttempts) {
- if (!saidGaveUp) {
- saidGaveUp = true
- opts.log(`no grid after ${attempts} attempts — giving up until this machine restarts, or you sign in to Harness again`)
- }
- return
+ const once = async (ownGrid: boolean): Promise<GridAttachResult> => {
+ if (!opts.signedIn()) signedIn = ownGridThere = false
+ if (last && signedIn && (!ownGrid || ownGridThere)) return last
+ let result: GridAttachResult
+ try {
+ result = await opts.attempt({ ownGrid, signedInThisRun: signedIn })
+ } catch (err) {
+ const detail = err instanceof Error ? err.message : String(err)
+ opts.log(`attempt failed: ${detail}`)
+ return { status: 'handoff-failed', name: null, detail }
}
- const wait = opts.minIntervalMs - (now() - lastStartedAt)
- if (wait > 0) {
- deferred = setTimeout(() => { deferred = null; run() }, wait)
- deferred.unref?.()
- return
+ if (result.status === 'converged' || result.status === 'signed-in') {
+ signedIn = true
+ if (result.ownGrid && OWN_GRID_THERE.has(result.ownGrid)) ownGridThere = true
+ last = result
}
- attempts += 1
- lastStartedAt = now()
- deadline = lastStartedAt + opts.ceilingMs
- inFlight = opts.attempt()
- .then((result) => {
- // Only an outcome that actually attached stops the retries. `no-cli`, `no-name` and
- // `handoff-failed` are all "this machine or the control plane was not ready", which is
- // exactly what a later connect may have fixed.
- if (result.status === 'converged' || result.status === 'signed-in') done = true
- })
- .catch((err) => { opts.log(`attempt failed: ${err instanceof Error ? (err.stack ?? err.message) : String(err)}`) })
- .finally(() => { inFlight = null })
+ return result
}
return {
- run,
- probe: () => (inFlight && now() < deadline ? inFlight : null),
- attempts: () => attempts,
+ ensure: (request = {}) => {
+ const next = queue.then(() => once(request.ownGrid ?? false))
+ queue = next.catch(() => {})
+ return next
+ },
}
}
diff --git a/desktop/design/terminal-dialogs.md b/desktop/design/terminal-dialogs.md
index d6fec2c99..b246e0581 100644
--- a/desktop/design/terminal-dialogs.md
+++ b/desktop/design/terminal-dialogs.md
@@ -137,7 +137,11 @@ Each hint is also a plain-text button: clicking it inserts the prefix into the
same editor and keeps typing focus there. Selected harnesses open with Enter.
Machines use Enter to **Manage**: focus moves to their controls without invoking
one. Models use five sections: **Subscriptions**, **APIs**, **Your models**,
-the downloads, and **Shared with you**. Headers are plain muted text and never
+the downloads, and **Shared with you**. Grid is an add-on: on a computer where
+it is not set up, local and shared models are one row under Your models,
+**[ Set up local & shared models ]**, and the downloads and Shared with you
+headings are not shown. Enter on it sets Grid up with the Harness account (no
+second sign-in); opening the picker never does. Headers are plain muted text and never
take selection. Put **[ Add ]** within APIs. Your models puts downloaded models
first, followed by models served on the user's machines. The downloads are
headed with the machine they are for and its memory (`Get for this Mac · 64 GB`),
diff --git a/desktop/lib/models/model_manager_controller.dart b/desktop/lib/models/model_manager_controller.dart
index 7b9f2b5b6..f5e7989b1 100644
--- a/desktop/lib/models/model_manager_controller.dart
+++ b/desktop/lib/models/model_manager_controller.dart
@@ -67,6 +67,25 @@ class ModelManagerController extends ChangeNotifier {
bool preparing = false, opening = false, scanning = false, loaded = false;
bool inventoryAvailable = false, operationBusy = false;
bool supportsDownload = false;
+
+ /// Grid is not set up on this machine yet: no `grid`, or no sign-in. Grid is an add-on, set up the
+ /// first time a person asks for a grid feature ([setUpGrid]) — never by opening the app, a picker
+ /// or a list. Until then the pickers offer a Set up row in place of local and shared models.
+ bool gridSetupNeeded = false;
+
+ /// [setUpGrid] is under way.
+ bool settingUpGrid = false;
+
+ /// Why the last [setUpGrid] did not finish, in the daemon's words; null once it has.
+ String? gridSetupError;
+
+ /// Set up was pressed signed out of Harness. Grid is set up with the Harness account, so the press
+ /// started the sign-in and the set-up waits for it: it runs once the account's machine is back
+ /// ([_observe]) — one press, not a sign-in followed by a second trip to the picker.
+ bool _setUpAfterSignIn = false;
+
+ /// [setUpGrid] is waiting for the Harness sign-in it started.
+ bool get setUpWaitsForSignIn => _setUpAfterSignIn && app.signingIn;
LocalModelOperation? pendingOperation;
String? pendingId;
bool pendingStart = true;
@@ -128,6 +147,12 @@ class ModelManagerController extends ChangeNotifier {
// A minimised or background app reads nothing, busy or not: the daemon owns the operation
// either way, and the one refresh on return ([_foregroundChanged]) catches up.
if (!app.inForeground) return;
+ // Grid not set up and nobody looking: nothing to watch. While a picker is open it keeps
+ // reading, so grid set up some other way — a terminal's `harness grid login` — shows at
+ // once instead of leaving a Set up row that is no longer true.
+ if (gridSetupNeeded && !settingUpGrid && !busy && !_panelVisible) {
+ return;
+ }
if (targetMachineId != null && !_panelVisible && !busy) return;
if (busy ||
_panelVisible ||
@@ -167,6 +192,9 @@ class ModelManagerController extends ChangeNotifier {
loaded = false;
inventoryAvailable = false;
supportsDownload = false;
+ gridSetupNeeded = false;
+ settingUpGrid = false;
+ gridSetupError = null;
operationBusy = false;
pendingOperation = null;
pendingId = null;
@@ -190,12 +218,26 @@ class ModelManagerController extends ChangeNotifier {
current.agentLoadStatus == AgentLoadStatus.loaded) &&
!_autoPrepared) {
_autoPrepared = true;
- if (targetMachineId == null) unawaited(prepare());
+ // The Model Manager is NOT prepared here: it is a grid feature, made ready when it is opened
+ // ([open]), never by the app starting on a machine that may not use grid at all.
// In the background the first read waits for the app to come back ([_foregroundChanged]).
if (app.inForeground && (targetMachineId == null || _panelVisible)) {
unawaited(refresh());
}
}
+ // Set up pressed while signed out: once the sign-in it started has landed and this machine is
+ // connected on the account, the set-up it was for runs — whether the sign-in moved the app onto
+ // the account's machine or left it where it was.
+ if (_setUpAfterSignIn &&
+ !app.isGuest &&
+ !app.signingIn &&
+ targetMachineId == null &&
+ current != null &&
+ current.connectionStatus == ConnectionStatus.connected &&
+ current.agentLoadStatus == AgentLoadStatus.loaded) {
+ _setUpAfterSignIn = false;
+ unawaited(setUpGrid());
+ }
_changed();
}
@@ -306,6 +348,13 @@ class ModelManagerController extends ChangeNotifier {
error = null;
_changed();
try {
+ // Opening the Model Manager is a grid feature in use: grid is set up first, if it is not yet.
+ if (gridSetupNeeded && !await setUpGrid()) {
+ error =
+ gridSetupError ??
+ 'Grid could not be set up on this computer. Try again.';
+ return;
+ }
if (_creation?.agentId == null &&
_creation?.awaitingConfirmation == false &&
!preparing) {
@@ -387,7 +436,47 @@ class ModelManagerController extends ChangeNotifier {
});
}
- Future<void> _refresh({required bool force}) async {
+ /// Sets grid up on this machine — `grid` installed, signed in with this Harness account (its token:
+ /// no second browser), the account's grid made — then reads the lists it unlocks. The one door to
+ /// grid for a person who has not used it: the pickers' Set up row, or opening the Model Manager.
+ /// True when grid is set up afterwards.
+ Future<bool> setUpGrid() async {
+ if (settingUpGrid || app.signingIn) return !gridSetupNeeded;
+ // Grid is set up with the Harness account, so signed out, Set up starts with signing in — the
+ // app's own sign-in, in the browser — and finishes itself once that lands (see [_observe]).
+ // Failing the set-up instead ("Not signed in") left a person with nowhere to go but a terminal.
+ if (app.isGuest) {
+ _setUpAfterSignIn = true;
+ gridSetupError = null;
+ _changed();
+ await app.login();
+ // Cancelled or refused: nothing is left waiting to set Grid up behind a later sign-in.
+ if (app.isGuest) _setUpAfterSignIn = false;
+ _changed();
+ return false;
+ }
+ final owner = machine;
+ if (owner == null) return !gridSetupNeeded;
+ settingUpGrid = true;
+ gridSetupError = null;
+ _changed();
+ try {
+ // After any read already under way, so its stale answer cannot land over this one.
+ await _refreshing;
+ if (!_current(owner)) return false;
+ await (_refreshing = _refresh(force: true, setup: true).whenComplete(() {
+ if (identical(machine, owner)) _refreshing = null;
+ }));
+ return _current(owner) && !gridSetupNeeded;
+ } finally {
+ if (_current(owner)) {
+ settingUpGrid = false;
+ _changed();
+ }
+ }
+ }
+
+ Future<void> _refresh({required bool force, bool setup = false}) async {
final owner = machine;
if (owner == null ||
owner.connectionStatus != ConnectionStatus.connected ||
@@ -426,13 +515,21 @@ class ModelManagerController extends ChangeNotifier {
final answer = await app.localModels(
owner.machine.machineId,
refresh: force,
+ setup: setup,
);
if (!_current(owner) || revision != _actionRevision) return;
// `notice` is a sentence BESIDE the list. A reply carrying `error` never reaches here:
// the RPC layer fails it whole and keeps nothing, which is how a daemon that sent its
// warning in `error` once emptied this list. `error` is still read for a daemon too old
// to send models at all.
- error = (answer['notice'] ?? answer['error']) as String?;
+ //
+ // Not while Grid is not set up here: then the note is only that ("Sign in to find models
+ // for this computer."), which the pickers' Set up row already says — as a line on every
+ // preview it read as something wrong with whatever row was selected.
+ gridSetupNeeded = answer['gridSetupNeeded'] == true;
+ error = gridSetupNeeded
+ ? null
+ : (answer['notice'] ?? answer['error']) as String?;
if (answer['models'] is! List) {
inventoryAvailable = false;
error ??= 'Models are unavailable. Try again.';
@@ -454,6 +551,11 @@ class ModelManagerController extends ChangeNotifier {
hardware = answer['hardware'] as String?;
operationBusy = answer['busy'] == true;
supportsDownload = answer['supportsDownload'] == true;
+ final setupError = answer['gridSetupError'];
+ gridSetupError =
+ setup && setupError is String && setupError.isNotEmpty
+ ? setupError
+ : null;
inventoryAvailable = true;
loaded = true;
_lastLocalRead = DateTime.now();
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index b05c88da7..c79ca6d1e 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -6214,13 +6214,18 @@ class AppNotifier extends ChangeNotifier {
ModelsMenuController get modelsMenu =>
_modelsMenu ??= ModelsMenuController(remote: readRemoteUsage);
+ /// This machine's local models. [setup] makes it Grid's first use there too: `grid` installed,
+ /// signed in with this Harness account (its token, no second browser) and the account's grid
+ /// made, before the list answers — minutes, on a machine with no `grid` yet. Grid is an add-on:
+ /// nothing but this, and the acts that need it, ever sets it up.
Future<Map<String, dynamic>> localModels(
String machineId, {
bool refresh = false,
+ bool setup = false,
}) => _conn(machineId).request(
'grid_fleet_models_list',
- payload: {'refresh': refresh},
- timeout: const Duration(seconds: 90),
+ payload: {'refresh': refresh, if (setup) 'setup': true},
+ timeout: setup ? const Duration(minutes: 5) : const Duration(seconds: 90),
);
Future<Map<String, dynamic>> apiConnections(
diff --git a/desktop/lib/state/swarm_search.dart b/desktop/lib/state/swarm_search.dart
index 34cbf0edd..ed18e1a32 100644
--- a/desktop/lib/state/swarm_search.dart
+++ b/desktop/lib/state/swarm_search.dart
@@ -105,6 +105,29 @@ class SwarmSearchController extends ChangeNotifier {
bool isModelDownloadsRow(SwarmDestination? row) =>
isModelMode && row?.id == 'model:downloads';
+ /// Grid is not set up on this machine, so local and shared models are one row offering to set it
+ /// up — Grid is an add-on, set up the first time a person asks for it, never by opening a picker.
+ bool get gridSetupOffered {
+ final manager = models?.manager;
+ return manager != null &&
+ (manager.gridSetupNeeded || manager.settingUpGrid);
+ }
+
+ /// The row that sets Grid up ([gridSetupOffered]).
+ bool isGridSetupRow(SwarmDestination? row) =>
+ isModelMode && row?.id == gridSetupRowId;
+
+ static const gridSetupRowId = 'model:grid-setup';
+
+ late final _gridSetupRow = SwarmDestination(
+ id: gridSetupRowId,
+ modelId: gridSetupRowId,
+ title: '[ Set up local & shared models ]',
+ detail: '',
+ swarmId: null,
+ current: false,
+ );
+
/// Saved APIs whose models are shown under them. An API such as OpenRouter lists hundreds, so
/// they stay folded until Enter on the API's row — or a search that matches them.
final expandedApis = <String>{};
@@ -195,10 +218,27 @@ class SwarmSearchController extends ChangeNotifier {
ModelSearchSection modelSection(SwarmDestination row) => row.isCreate
? ModelSearchSection.apis
+ : isGridSetupRow(row)
+ ? ModelSearchSection.local
: isModelDownloadsRow(row)
? ModelSearchSection.catalog
: models?.entries[row.modelId]?.section ?? ModelSearchSection.local;
+ /// Whether a search should still show the Set up row: always with nothing typed, and for words that
+ /// ask for what it unlocks.
+ bool _offersGridSetupFor(String query) {
+ final words = query.trim().toLowerCase();
+ if (words.isEmpty) return true;
+ return const [
+ 'set up',
+ 'setup',
+ 'local',
+ 'shared',
+ 'grid',
+ 'download',
+ ].any((word) => word.contains(words) || words.contains(word));
+ }
+
/// A section's heading in the list. The downloads name the machine they are for.
String modelSectionLabel(ModelSearchSection section) =>
section == ModelSearchSection.catalog && models != null
@@ -220,6 +260,14 @@ class SwarmSearchController extends ChangeNotifier {
/// (In use); only a row with no action says its state. Operation words come from the catalogue's
/// [ModelSearchCatalog.localStatusWord], which the preview's status also reads.
String? modelRowStatus(SwarmDestination row) {
+ if (isGridSetupRow(row)) {
+ final manager = models!.manager;
+ return manager.settingUpGrid
+ ? 'Setting up…'
+ : manager.setUpWaitsForSignIn
+ ? 'Signing in…'
+ : null;
+ }
final catalog = models;
final entry = catalog?.entries[row.modelId];
if (entry == null || catalog == null) return null;
@@ -266,6 +314,10 @@ class SwarmSearchController extends ChangeNotifier {
/// Whether the model row is live right now: running, in use, or a download, start or stop under
/// way. Only a live row's word is green.
bool modelRowLive(SwarmDestination row) {
+ if (isGridSetupRow(row)) {
+ final manager = models!.manager;
+ return manager.settingUpGrid || manager.setUpWaitsForSignIn;
+ }
final catalog = models;
final entry = catalog?.entries[row.modelId];
if (entry == null || catalog == null) return false;
@@ -1193,6 +1245,14 @@ class SwarmSearchController extends ChangeNotifier {
? isModelMode
? 'Add'
: row!.title
+ : isGridSetupRow(row)
+ ? models!.manager.settingUpGrid
+ ? 'Setting up…'
+ : app.signingIn
+ ? 'Signing in…'
+ : app.isGuest
+ ? 'Sign in'
+ : 'Set up'
: isModelDownloadsRow(row)
? modelDownloadsVisible
? 'Show fewer'
@@ -1690,6 +1750,17 @@ class SwarmSearchController extends ChangeNotifier {
if (matchQuery.trim().isEmpty && _downloadCount > shownDownloads) {
rows = [...rows, _downloadsRow];
}
+ if (gridSetupOffered) {
+ // Local and shared models are this one row until Grid is set up: a downloaded file, a
+ // download or a model shared on a grid cannot be used before then, and a list of them
+ // beside "Set up" read as if they could.
+ rows = rows.where((row) {
+ final section = modelSection(row);
+ return section == ModelSearchSection.subscriptions ||
+ section == ModelSearchSection.apis;
+ }).toList();
+ if (_offersGridSetupFor(matchQuery)) rows = [...rows, _gridSetupRow];
+ }
// An API's models are listed under its row, as a group: a search that matches a model and not
// its API still shows the API above it, and the models of two APIs never interleave.
final shown = {for (final row in rows) row.modelId};
@@ -1791,7 +1862,11 @@ class SwarmSearchController extends ChangeNotifier {
_selectedId = selected?.id;
matchCount = rows
.where(
- (row) => !row.isCreate && !row.isNote && !isModelDownloadsRow(row),
+ (row) =>
+ !row.isCreate &&
+ !row.isNote &&
+ !isModelDownloadsRow(row) &&
+ !isGridSetupRow(row),
)
.length;
}
@@ -1876,6 +1951,14 @@ class SwarmSearchController extends ChangeNotifier {
notifyListeners();
return null;
}
+ if (isGridSetupRow(destination)) {
+ final manager = models!.manager;
+ if (!manager.settingUpGrid && !app.signingIn) {
+ unawaited(manager.setUpGrid());
+ }
+ notifyListeners();
+ return null;
+ }
if (isModelDownloadsRow(destination)) {
modelDownloadsVisible = !modelDownloadsVisible;
_filter();
@@ -1978,6 +2061,8 @@ class SwarmSearchController extends ChangeNotifier {
? false
: isModelDownloadsRow(row)
? true
+ : isGridSetupRow(row)
+ ? !models!.manager.settingUpGrid && !app.signingIn
: row?.pickerQuery != null
? isHelpMode && _commandIds.contains(row!.id)
: row?.isModel == true
diff --git a/desktop/lib/widgets/swarm_resource_preview.dart b/desktop/lib/widgets/swarm_resource_preview.dart
index 07ef1b685..2f8541362 100644
--- a/desktop/lib/widgets/swarm_resource_preview.dart
+++ b/desktop/lib/widgets/swarm_resource_preview.dart
@@ -349,6 +349,7 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
if (widget.search.canSelectModel(row) ||
widget.search.canGetModelForUse(row) ||
widget.search.isModelDownloadsRow(row) ||
+ widget.search.isGridSetupRow(row) ||
widget.search.canExpandApi(row)) {
_open();
return true;
@@ -657,6 +658,7 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
widget.search.canSelectModel(row) ||
widget.search.canGetModel(row) ||
widget.search.isModelDownloadsRow(row) ||
+ widget.search.isGridSetupRow(row) ||
widget.search.canExpandApi(row))
'$enter ${managing
? 'select'
@@ -664,7 +666,7 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
? 'Use'
: widget.search.canGetModel(row)
? 'Get'
- : widget.search.isModelDownloadsRow(row) || widget.search.canExpandApi(row)
+ : widget.search.isModelDownloadsRow(row) || widget.search.isGridSetupRow(row) || widget.search.canExpandApi(row)
? widget.search.actionLabel(row)
: _isManagement
? _machineSetup
@@ -700,12 +702,21 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
if (search.isModelDownloadsRow(selected)) {
return [
_ResourceAction(
- search.modelDownloadsVisible ? 'Hide catalog' : 'Get models',
+ search.actionLabel(selected),
_open,
command: 'picker.accept',
),
];
}
+ if (search.isGridSetupRow(selected)) {
+ return [
+ _ResourceAction(
+ search.actionLabel(selected),
+ search.models!.manager.settingUpGrid || app.signingIn ? null : _open,
+ command: 'picker.accept',
+ ),
+ ];
+ }
if (selected?.isCreate == true) {
if (search.isMachineMode) {
return [
@@ -1053,6 +1064,35 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
Widget _modelPreview() {
final catalog = widget.search.models!;
+ if (widget.search.isGridSetupRow(row)) {
+ final manager = catalog.manager;
+ final here = thisComputerName();
+ // Signed out of Harness: the set-up is done with the Harness account, so this starts there.
+ // What a person reads names Harness only; Grid is how it works, not what they chose.
+ final signedOut = app.isGuest;
+ return _details([
+ 'Local & shared models',
+ 'Download models to run on $here, and use the models other people share with you.',
+ '',
+ if (signedOut) ...[
+ "You're using Harness on this computer only. Local and shared models belong to your "
+ 'Harness account, so you need to sign in to use them.',
+ "Sign in opens in your browser. Setup finishes here on its own once you're signed in.",
+ ] else
+ "Set up gets $here ready for them with your Harness account. You won't be asked to "
+ 'sign in again.',
+ if (manager.settingUpGrid) ...[
+ '',
+ 'Setting up…',
+ ] else if (manager.setUpWaitsForSignIn) ...[
+ '',
+ 'Signing in… Finish in your browser, and setup continues here.',
+ ] else if (!signedOut && manager.gridSetupError != null) ...[
+ '',
+ 'Could not set up: ${manager.gridSetupError}',
+ ],
+ ], controls: true);
+ }
if (widget.search.isModelDownloadsRow(row)) {
return _details(
widget.search.modelDownloadsVisible
diff --git a/desktop/lib/widgets/swarm_switcher.dart b/desktop/lib/widgets/swarm_switcher.dart
index ad87168ac..633b5ec5c 100644
--- a/desktop/lib/widgets/swarm_switcher.dart
+++ b/desktop/lib/widgets/swarm_switcher.dart
@@ -509,10 +509,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.
+ // 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.
if (indices.isEmpty &&
(search.matchQuery.trim().isNotEmpty ||
- section == ModelSearchSection.catalog)) {
+ section == ModelSearchSection.catalog ||
+ (section == ModelSearchSection.shared &&
+ search.gridSetupOffered))) {
continue;
}
if (items.isNotEmpty) items.add((index: null, heading: null, key: null));
@@ -1384,11 +1387,14 @@ class _SearchRowContentState extends State<_SearchRowContent> {
: !widget.enabled ||
(row.isModel &&
!widget.search.isModelDownloadsRow(row) &&
+ !widget.search.isGridSetupRow(row) &&
!widget.search.canExpandApi(row) &&
!widget.search.canSelectModel(row) &&
!widget.search.canGetModel(row))
? theme.foreground.withValues(alpha: .28)
- : row.isCreate || widget.search.isModelDownloadsRow(row)
+ : row.isCreate ||
+ widget.search.isModelDownloadsRow(row) ||
+ widget.search.isGridSetupRow(row)
? theme.cursor
: theme.foreground,
);
diff --git a/desktop/test/grid_on_demand_test.dart b/desktop/test/grid_on_demand_test.dart
new file mode 100644
index 000000000..0fa34a118
--- /dev/null
+++ b/desktop/test/grid_on_demand_test.dart
@@ -0,0 +1,418 @@
+// Grid is an add-on: the app never sets it up by starting, by opening a picker or by reading a list.
+// It is set up the first time a person asks for a grid feature — the models picker's Set up row, or
+// opening the Model Manager — through the daemon, with this Harness account's token (no second
+// browser). Until then the picker offers that one row in place of local and shared models.
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/local_key_value_store.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/models/model_manager_controller.dart';
+import 'package:harness/models/model_search_catalog.dart';
+import 'package:harness/state/swarm_search.dart';
+import 'package:harness/widgets/swarm_resource_preview.dart';
+import 'package:harness/widgets/swarm_switcher.dart';
+
+import 'keymap_host_test.dart' show MemoryKeymap, key;
+import 'keymap_runtime_test.dart' as configured;
+import 'resource_picker_test.dart' show fixture;
+import 'support/model_manager.dart';
+import 'support/real_fonts.dart';
+
+class _MemoryStore implements LocalKeyValueStore {
+ final values = <String, String>{};
+ @override
+ Future<String?> read(String key) async => values[key];
+ @override
+ Future<void> write(String key, String value) async => values[key] = value;
+ @override
+ Future<void> delete(String key) async => values.remove(key);
+}
+
+/// What the daemon lists on a machine whose Grid is not set up: nothing, and that it is needed.
+Map<String, dynamic> _notSetUp() => {
+ 'models': <Object>[],
+ 'supportsDownload': true,
+ 'busy': false,
+ 'gridSetupNeeded': true,
+ // What the daemon notes beside the list with no grid sign-in; the Set up row already says it.
+ 'notice': 'Sign in to find models for this computer.',
+};
+
+SwarmSearchController search(WidgetTester tester) =>
+ tester.widget<SwarmSearchResults>(find.byType(SwarmSearchResults)).search;
+
+Finder _inPreview(String text) => find.descendant(
+ of: find.byType(SwarmResourcePreview),
+ matching: find.textContaining(text),
+);
+
+void main() {
+ group('the Model Manager controller', () {
+ late ModelManagerConnection connection;
+ late ModelManagerTestApp app;
+ late ModelManagerController controller;
+ setUp(() {
+ connection = ModelManagerConnection();
+ app = ModelManagerTestApp(connection)..installed = false;
+ controller = ModelManagerController(
+ app,
+ storage: _MemoryStore(),
+ poll: false,
+ );
+ });
+ tearDown(() {
+ controller.dispose();
+ app.dispose();
+ });
+
+ test('the app starting prepares nothing: no Grid harness installed, no Model Manager made', () async {
+ controller.start();
+ await controller.refresh();
+ await pumpEventQueue();
+ expect(app.installs, 0);
+ expect(connection.creations, isEmpty);
+ expect(app.gridSetups, isEmpty);
+ });
+
+ test('a list read says Grid is not set up, and sets nothing up', () async {
+ app.localInventory = _notSetUp();
+ controller.start();
+ await controller.refresh();
+ await controller.refresh(force: true);
+ expect(controller.gridSetupNeeded, isTrue);
+ expect(app.gridSetups, isEmpty);
+ // The daemon's note about it is not an error: the Set up row is the whole of the message.
+ expect(controller.error, isNull);
+ });
+
+ test(
+ 'Set up sets Grid up once, and the list then reads it set up',
+ () async {
+ app.localInventory = _notSetUp();
+ controller.start();
+ await controller.refresh();
+ expect(await controller.setUpGrid(), isTrue);
+ expect(app.gridSetups, ['m']);
+ expect(controller.gridSetupNeeded, isFalse);
+ expect(controller.settingUpGrid, isFalse);
+ expect(controller.gridSetupError, isNull);
+ },
+ );
+
+ test('a set-up refused keeps the Set up offered, and says why', () async {
+ app
+ ..localInventory = _notSetUp()
+ ..gridSetupFailure = 'grid is too old for --harness';
+ controller.start();
+ await controller.refresh();
+ expect(await controller.setUpGrid(), isFalse);
+ expect(controller.gridSetupNeeded, isTrue);
+ expect(controller.gridSetupError, 'grid is too old for --harness');
+ // A plain read afterwards does not carry the last attempt's words forward.
+ await controller.refresh(force: true);
+ expect(controller.gridSetupError, isNull);
+ });
+
+ test('opening the Model Manager sets Grid up first', () async {
+ app.localInventory = _notSetUp();
+ controller.start();
+ await controller.refresh();
+ await controller.open();
+ expect(app.gridSetups, ['m']);
+ expect(app.installs, 1);
+ expect(connection.creations, hasLength(1));
+ });
+
+ test('signed out of Harness, Set up signs in first, then sets Grid up by itself', () async {
+ app
+ ..localInventory = _notSetUp()
+ ..signedIn = false;
+ controller.start();
+ await controller.refresh();
+ // One press: it opens the Harness sign-in rather than failing with "Not signed in".
+ expect(await controller.setUpGrid(), isFalse);
+ expect(app.logins, 1);
+ // The sign-in landed and this machine is connected: the set-up it was for runs, unasked.
+ await pumpEventQueue();
+ expect(app.gridSetups, ['m']);
+ expect(controller.gridSetupNeeded, isFalse);
+ expect(controller.gridSetupError, isNull);
+ });
+
+ test('a sign-in cancelled leaves nothing waiting to set Grid up behind a later one', () async {
+ app
+ ..localInventory = _notSetUp()
+ ..signedIn = false
+ ..loginLands = false;
+ controller.start();
+ await controller.refresh();
+ await controller.setUpGrid();
+ await pumpEventQueue();
+ expect(app.logins, 1);
+ expect(app.gridSetups, isEmpty);
+ // Signing in some other way later does not set Grid up on its own.
+ app
+ ..signedIn = true
+ ..notifyListeners();
+ await pumpEventQueue();
+ expect(app.gridSetups, isEmpty);
+ });
+
+ test(
+ 'a Model Manager whose Grid could not be set up is not made',
+ () async {
+ app
+ ..localInventory = _notSetUp()
+ ..gridSetupFailure = 'no grid on this computer';
+ controller.start();
+ await controller.refresh();
+ await controller.open();
+ expect(controller.error, 'no grid on this computer');
+ expect(app.installs, 0);
+ expect(connection.creations, isEmpty);
+ },
+ );
+ });
+
+ group('the models picker', () {
+ setUpAll(loadRealFonts);
+
+ Future<ModelManagerTestApp> notSetUp() async {
+ final app = await fixture();
+ app.localInventory = _notSetUp();
+ await app.modelManager.refresh(force: true);
+ return app;
+ }
+
+ testWidgets(
+ 'offers one Set up row for local and shared models, and sets Grid up only on Enter',
+ (tester) async {
+ final app = await notSetUp();
+ final map = MemoryKeymap();
+ try {
+ await configured.mount(tester, app, map);
+ await key(tester, LogicalKeyboardKey.keyI, cmd: true);
+ await tester.pumpAndSettle();
+ final picker = search(tester);
+ final setup = picker.rows.singleWhere(picker.isGridSetupRow);
+ expect(setup.title, '[ Set up local & shared models ]');
+ expect(picker.modelSection(setup), ModelSearchSection.local);
+ // It stands for what is shared with you too; there is nothing to download yet.
+ expect(
+ find.byKey(const ValueKey('model-section:Shared with you')),
+ findsNothing,
+ );
+ expect(
+ find.byKey(const ValueKey('model-section:Get models')),
+ findsNothing,
+ );
+ // Opening the picker, and reading it, set nothing up.
+ expect(app.gridSetups, isEmpty);
+ // And no row's preview repeats "sign in" in yellow: the Set up row says it once.
+ expect(
+ find.byKey(const ValueKey('local-model-inventory-notice')),
+ findsNothing,
+ );
+ expect(find.textContaining('Sign in to find models'), findsNothing);
+
+ picker.move(picker.rows.indexOf(setup) - picker.cursor);
+ await tester.pump();
+ expect(_inPreview('Local & shared models'), findsOneWidget);
+ expect(
+ _inPreview("You won't be asked to sign in again."),
+ findsOneWidget,
+ );
+ expect(picker.actionLabel(setup), 'Set up');
+
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(app.gridSetups, ['m']);
+ expect(picker.rows.where(picker.isGridSetupRow), isEmpty);
+ expect(
+ find.byKey(const ValueKey('model-section:Shared with you')),
+ findsOneWidget,
+ );
+ } finally {
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ map.dispose();
+ }
+ },
+ );
+
+ testWidgets('a set-up refused stays offered, with why in the preview', (
+ tester,
+ ) async {
+ final app = await notSetUp();
+ app.gridSetupFailure = 'grid is too old for --harness';
+ final map = MemoryKeymap();
+ try {
+ await configured.mount(tester, app, map);
+ await key(tester, LogicalKeyboardKey.keyI, cmd: true);
+ await tester.pumpAndSettle();
+ final picker = search(tester);
+ picker.move(
+ picker.rows.indexWhere(picker.isGridSetupRow) - picker.cursor,
+ );
+ await tester.pump();
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(app.gridSetups, ['m']);
+ expect(picker.rows.where(picker.isGridSetupRow), hasLength(1));
+ expect(
+ _inPreview('Could not set up: grid is too old for --harness'),
+ findsOneWidget,
+ );
+ } finally {
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ map.dispose();
+ }
+ });
+
+ testWidgets(
+ 'signed out, the row signs in and says so — no dead end at "Not signed in"',
+ (tester) async {
+ final app = await notSetUp();
+ app.signedIn = false;
+ // The workspace starts the Model Manager's watch outside tests; the sign-in's follow-up
+ // set-up rides on it.
+ app.modelManager.start();
+ final map = MemoryKeymap();
+ try {
+ await configured.mount(tester, app, map);
+ await key(tester, LogicalKeyboardKey.keyI, cmd: true);
+ await tester.pumpAndSettle();
+ final picker = search(tester);
+ final setup = picker.rows.singleWhere(picker.isGridSetupRow);
+ picker.move(picker.rows.indexOf(setup) - picker.cursor);
+ await tester.pump();
+ expect(picker.actionLabel(setup), 'Sign in');
+ // Why a sign-in: the models belong to the Harness account this computer is not using.
+ expect(
+ _inPreview(
+ 'belong to your Harness account, so you need to sign in',
+ ),
+ findsOneWidget,
+ );
+ expect(_inPreview('Sign in opens in your browser.'), findsOneWidget);
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(app.logins, 1);
+ expect(app.gridSetups, ['m']);
+ expect(find.textContaining('Not signed in'), findsNothing);
+ } finally {
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ map.dispose();
+ }
+ },
+ );
+
+ testWidgets(
+ 'while Set up is offered, nothing it stands for is listed beside it',
+ (tester) async {
+ final app = await fixture();
+ // A downloaded file on disk, and models shared on a grid this Mac read before: neither can be
+ // used until Grid is set up, so neither is listed next to the row that sets it up.
+ app
+ ..localInventory = {
+ ..._notSetUp(),
+ 'models': [
+ {
+ 'id': 'local:Qwen3.6-35B-A3B-UD-Q5_K_XL.gguf',
+ 'name': 'Qwen3.6-35B-A3B',
+ 'state': 'downloaded',
+ 'sizeBytes': 27159116064,
+ 'canStart': true,
+ },
+ ],
+ }
+ ..inventory = const GridModels(
+ gridName: 'home',
+ models: [],
+ grids: [
+ GridSection(
+ name: 'Team',
+ own: false,
+ models: [GridModel(id: 'Shared Qwen', node: 'team.lan')],
+ ),
+ ],
+ );
+ await app.modelManager.refresh(force: true);
+ final map = MemoryKeymap();
+ try {
+ await configured.mount(tester, app, map);
+ await key(tester, LogicalKeyboardKey.keyI, cmd: true);
+ await tester.pumpAndSettle();
+ final picker = search(tester);
+ final sections = picker.rows.map(picker.modelSection).toSet();
+ expect(
+ picker.rows
+ .where(
+ (row) => picker.modelSection(row) == ModelSearchSection.local,
+ )
+ .map((row) => row.id),
+ [SwarmSearchController.gridSetupRowId],
+ );
+ expect(sections, isNot(contains(ModelSearchSection.shared)));
+ expect(sections, isNot(contains(ModelSearchSection.catalog)));
+ expect(find.text('Qwen3.6-35B-A3B'), findsNothing);
+ expect(find.textContaining('Shared Qwen'), findsNothing);
+ } finally {
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ map.dispose();
+ }
+ },
+ );
+
+ testWidgets(
+ 'an open picker notices Grid set up some other way, and drops the Set up row',
+ (tester) async {
+ final app = await notSetUp();
+ // The workspace starts the Model Manager's watch outside tests.
+ app.modelManager.start();
+ final map = MemoryKeymap();
+ try {
+ await configured.mount(tester, app, map);
+ await key(tester, LogicalKeyboardKey.keyI, cmd: true);
+ await tester.pumpAndSettle();
+ final picker = search(tester);
+ expect(picker.rows.where(picker.isGridSetupRow), hasLength(1));
+ // Set up elsewhere — a terminal's `harness grid login` — while the picker stays open.
+ app.localInventory = {..._notSetUp()}
+ ..remove('gridSetupNeeded')
+ ..remove('notice');
+ await tester.pump(const Duration(seconds: 5));
+ await tester.pumpAndSettle();
+ expect(picker.rows.where(picker.isGridSetupRow), isEmpty);
+ expect(app.gridSetups, isEmpty);
+ } finally {
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ map.dispose();
+ }
+ },
+ );
+
+ testWidgets('a set-up Grid is not offered again', (tester) async {
+ final app = await fixture();
+ final map = MemoryKeymap();
+ try {
+ await configured.mount(tester, app, map);
+ await key(tester, LogicalKeyboardKey.keyI, cmd: true);
+ await tester.pumpAndSettle();
+ final picker = search(tester);
+ expect(picker.gridSetupOffered, isFalse);
+ expect(picker.rows.where(picker.isGridSetupRow), isEmpty);
+ } finally {
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ map.dispose();
+ }
+ });
+ });
+}
diff --git a/desktop/test/support/model_manager.dart b/desktop/test/support/model_manager.dart
index ed33e139b..1af121829 100644
--- a/desktop/test/support/model_manager.dart
+++ b/desktop/test/support/model_manager.dart
@@ -148,13 +148,45 @@ class ModelManagerTestApp extends AppNotifier {
bool localReadFails = false, actionReplyLost = false;
Completer<Map<String, dynamic>>? actionReply;
+
+ /// Harness sign-ins started ([login]), and whether the next one lands — the browser completing it
+ /// — or is cancelled.
+ int logins = 0;
+ bool loginLands = true;
+
+ @override
+ Future<void> login() async {
+ logins++;
+ signingIn = true;
+ notifyListeners();
+ await Future<void>.delayed(Duration.zero);
+ if (loginLands) signedIn = true;
+ signingIn = false;
+ notifyListeners();
+ }
+
+ /// Machines Grid was set up on, in order — a list read carrying `setup`.
+ final gridSetups = <String>[];
+
+ /// What the daemon says when setting Grid up fails; null sets it up.
+ String? gridSetupFailure;
+
@override
Future<Map<String, dynamic>> localModels(
String machineId, {
bool refresh = false,
+ bool setup = false,
}) async {
localReads++;
inventoryReads.add(machineId);
+ if (setup) {
+ gridSetups.add(machineId);
+ final inventory = inventoryFor(machineId);
+ if (gridSetupFailure != null) {
+ return {...inventory, 'gridSetupError': gridSetupFailure};
+ }
+ setInventoryFor(machineId, {...inventory}..remove('gridSetupNeeded'));
+ }
final held = localReply;
if (held != null) {
localReply = null;