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: sign in to grid and create the private grid on daemon start

Kelvind92820b7c347
diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.ts
index 9270c5b78..87936f4ae 100644
--- a/cli/src/backendSocket.spec.ts
+++ b/cli/src/backendSocket.spec.ts
@@ -1645,6 +1645,62 @@ 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)
+ 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.gridReadyProbe = () => reconcile
+ socket.connect()
+ const ws = wsMock.instances[0]
+ ws.open()
+ ws.message({ t: 'down', connId: 'web-1', frame: { type: 'grid_models_list', payload: { 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 })
+ })
+})
+
+describe('machine_meta carries the grid name without clobbering it on rename', () => {
+ afterEach(() => { wsMock.instances.length = 0 })
+
+ it('keeps the grid name when a later rename frame omits gridName, and clears it only on an explicit null', async () => {
+ const socket = new BackendSocket('token')
+ // Frames are processed through a queue, so `onMachineMeta` is how a test knows one has landed.
+ const namesSeen: Array<string | null> = []
+ socket.onMachineMeta = (n) => { namesSeen.push(n) }
+ socket.connect()
+ const ws = wsMock.instances[0]
+ ws.open()
+
+ // Connect frame: name and grid together.
+ ws.message({ t: 'down', connId: 'web-1', frame: { type: 'machine_meta', payload: { name: 'mac', gridName: 'someone-7f3a91c4' } } })
+ await vi.waitFor(() => expect(socket.gridName()).toBe('someone-7f3a91c4'))
+
+ // A rename pushes `{ name }` alone — it must NOT wipe the grid name (the bug that left the picker
+ // empty the moment a machine was renamed). Wait until the rename is observably processed, then
+ // confirm the grid name survived it.
+ ws.message({ t: 'down', connId: 'web-1', frame: { type: 'machine_meta', payload: { name: 'renamed' } } })
+ await vi.waitFor(() => expect(namesSeen).toContain('renamed'))
+ expect(socket.gridName()).toBe('someone-7f3a91c4')
+
+ // An explicit null is the account genuinely having no grid, and does clear it.
+ ws.message({ t: 'down', connId: 'web-1', frame: { type: 'machine_meta', payload: { name: 'renamed', gridName: null } } })
+ await vi.waitFor(() => expect(socket.gridName()).toBeNull())
+
+ await socket.stop()
+ })
})
/** The read-only hardware line for the run-a-harness-compute dialog, answered next to `grid_models_list`. */
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
index bd782b808..fa95e3a3a 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -119,6 +119,10 @@ 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
const BASE_DELAY_MS = 1_000
const MAX_DELAY_MS = 30_000
const QUEUE_MAX = 2_000
@@ -602,6 +606,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
+
+ /** 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`). */
+ setHarnessGridName(name: string | null): void { this.harnessGridName = name }
/** Which grid this machine's agents can be pointed at — for `harness status` and the models RPC. */
gridName(): string | null { return this.harnessGridName }
@@ -611,8 +623,23 @@ 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()
}
@@ -1232,12 +1259,20 @@ export class BackendSocket {
// Machine display name (seed on connect + web renames) — mirrored locally for `harness status`.
if (type === 'machine_meta') {
- const meta = frame.payload as { name?: unknown; gridName?: unknown } | undefined
- const name = meta?.name
- // The account's private grid, pushed on every connect. Held in memory only: it is the
- // backend's value, and a daemon that cached it on disk would keep answering with a stale one
- // after the account's grid changed.
- this.harnessGridName = typeof meta?.gridName === 'string' && meta.gridName.trim() ? meta.gridName.trim() : null
+ // A malformed/hostile frame's payload need not be an object; `'gridName' in meta` would throw
+ // on a primitive (and drop the whole frame via enqueueDown's catch). Guard the type first, the
+ // way the plain property reads elsewhere in this dispatcher tolerate one.
+ const meta = (typeof frame.payload === 'object' && frame.payload !== null ? frame.payload : {}) as { name?: unknown; gridName?: unknown }
+ const name = meta.name
+ // The account's private grid, pushed on connect. Held in memory only: it is the backend's
+ // value, and a daemon that cached it on disk would keep answering with a stale one after the
+ // account's grid changed. Only ACT on the key when it is present: the connect frame always
+ // carries it (a string or null), but a rename pushes `{name}` alone — and treating that
+ // absence as null used to WIPE a grid name a moment after it was set, leaving the picker
+ // empty. Absent ⇒ unchanged; null ⇒ this account has none; a string ⇒ that grid.
+ if ('gridName' in meta) {
+ this.harnessGridName = typeof meta.gridName === 'string' && meta.gridName.trim() ? meta.gridName.trim() : null
+ }
this.onMachineMeta?.(typeof name === 'string' && name.trim() ? name.trim() : null)
return
}
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index adcb7ef6c..d498c04d8 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -59,6 +59,10 @@ import { ensureHarnessGrid } 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 } from './lib/gridAttach.js'
+import { signedInGridEmail, resetGridDeriveMemo } from './lib/gridDerive.js'
+import { forgetGridModels } from './lib/gridModels.js'
+import { gridAvailable } from './lib/gridExec.js'
import { ENGINE_CLI_COMMANDS, ENGINES, engineBin, enginePathOverride } from './lib/engineBin.js'
import type { AgentEngine } from './engines/types.js'
import { engineInstallRecipe } from './lib/engineInstall.js'
@@ -274,6 +278,14 @@ const PROXY_BACKEND_TIMEOUT_MS = 20_000
// declaring an error. A healthy backend connects in well under this; a timeout ⇒ unreachable.
const CONNECT_WAIT_MS = 10_000
+/** Bounds the `POST /api/grid/name` inside the daemon-start grid reconcile, 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 the daemon-start reconcile before answering without it,
+ * whether or not it has settled — the ceiling that keeps a stuck reconcile from degrading every
+ * grid RPC for the daemon's whole life (`gridReadyProbe`). */
+const GRID_ATTACH_CEILING_MS = 30_000
+
/** Between session-binding attempts for a process whose engine store is not resolvable yet. */
const REPAIR_RETRY_MS = 60_000
/** A NEW process is waiting for a session that is about to appear. Muse makes
@@ -393,18 +405,22 @@ function setupBrowserLink(machineId: string, token: string): string {
return u.toString()
}
-/** One control-plane call, returning the backend's `data` envelope; throws on a non-2xx / bad body. */
+/** One control-plane call, returning the backend's `data` envelope; throws on a non-2xx / bad body.
+ * `signal` lets a caller bound the request — a bare `fetch` that accepts the TCP handshake and then
+ * never answers would otherwise await forever. */
async function requestJson<T>(
method: 'GET' | 'POST' | 'DELETE',
path: string,
body?: unknown,
headers: Record<string, string> = {},
+ signal?: AbortSignal,
): Promise<T> {
// A GET/DELETE with no body must not carry a content-type — some proxies reject that pairing.
const res = await fetch(`${backendHttpBase()}${path}`, {
method,
headers: body === undefined ? headers : { 'content-type': 'application/json', ...headers },
...(body === undefined ? {} : { body: JSON.stringify(body) }),
+ ...(signal ? { signal } : {}),
})
const json = (await res.json().catch(() => ({}))) as { success?: boolean; data?: T; error?: { message?: string } }
if (!res.ok || json.success === false) {
@@ -414,8 +430,8 @@ async function requestJson<T>(
}
/** POST JSON to the backend and return its `data` envelope; throws on a non-2xx / bad body. */
-async function postJson<T>(path: string, body: unknown, headers: Record<string, string> = {}): Promise<T> {
- return requestJson<T>('POST', path, body, headers)
+async function postJson<T>(path: string, body: unknown, headers: Record<string, string> = {}, signal?: AbortSignal): Promise<T> {
+ return requestJson<T>('POST', path, body, headers, signal)
}
/**
@@ -1111,11 +1127,13 @@ async function runForeground(session: AuthSession): Promise<void> {
// 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: a download must never hold the control port back, and every grid
+ // 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.
- void ensureManagedGrid((m) => console.log(`[grid-runtime] ${m}`))
+ // 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
registry.load()
// Persisted locators are hints until this process has observed their terminal root and PID/start marker.
@@ -1551,6 +1569,57 @@ async function runForeground(session: AuthSession): Promise<void> {
}, computerId())
backendRef = backend
+ // Bring this machine's grid sign-in into line with its harness sign-in, once, 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`.
+ let gridAttachSettled = false
+ // A hard ceiling on how long the RPCs will gate on the reconcile, INDEPENDENT of whether it
+ // settled. `mintName` is bounded below, but the hand-off child (`grid login --harness`) has no
+ // watchdog of its own — a control plane that black-holes its connection could keep the reconcile
+ // pending for the daemon's life, and without this ceiling every grid RPC would then pay the full
+ // per-call wait forever. Past the ceiling the probe returns null and the RPCs stop waiting; a
+ // reconcile that lands later still publishes the name through `onName`.
+ const gridReadyDeadline = Date.now() + GRID_ATTACH_CEILING_MS
+ const gridAttachInFlight = reconcileGridAttach({
+ managedGridReady,
+ 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".
+ // Bounded so a stalled control-plane connection cannot hold the reconcile open indefinitely.
+ mintName: async () => {
+ const { headers } = await controlPlaneAuth()
+ return (await postJson<{ gridName?: string }>('/api/grid/name', {}, headers, AbortSignal.timeout(GRID_MINT_TIMEOUT_MS))).gridName ?? null
+ },
+ accessToken: () => new AuthSessionManager(backendHttpBase()).accessToken(),
+ signedInEmail: () => signedInGridEmail(),
+ gridNames: () => gridNamesLocal(),
+ handoff: (token) => handOffToGrid(token, { json: true }),
+ ensure: (name) => ensureHarnessGrid(name),
+ onName: (name) => {
+ // Answer the picker with this account's grid at once, and drop the memos a stale or absent
+ // sign-in may have filled — the model list, the derived name, and the web-tools URL.
+ backend.setHarnessGridName(name)
+ forgetGridModels()
+ resetGridDeriveMemo()
+ clearGridMcpUrlCache()
+ },
+ log: (line) => console.log(`[grid-attach] ${line}`),
+ }).catch((err) => {
+ console.error('[grid-attach] reconcile failed:', err instanceof Error ? (err.stack ?? err.message) : err)
+ return null
+ }).finally(() => { gridAttachSettled = true })
+ void gridAttachInFlight
+ // While the reconcile is still running AND within the ceiling, the RPCs that need the grid name
+ // wait briefly on it; once it settles, or the ceiling passes, they read the name directly.
+ backend.gridReadyProbe = () => (gridAttachSettled || Date.now() >= gridReadyDeadline ? null : gridAttachInFlight)
+
/**
* Is ANY device surface watching this machine?
*
diff --git a/cli/src/lib/gridAttach.spec.ts b/cli/src/lib/gridAttach.spec.ts
new file mode 100644
index 000000000..596497e4b
--- /dev/null
+++ b/cli/src/lib/gridAttach.spec.ts
@@ -0,0 +1,152 @@
+import { describe, expect, it, vi } from 'vitest'
+import { reconcileGridAttach, type GridAttachDeps } from './gridAttach.js'
+import type { GridHandoffResult } from './gridHandoff.js'
+import type { EnsureResult } from './gridEnsure.js'
+
+const NAME = 'someone-7f3a91c4'
+const EMAIL = '[email protected]'
+
+const OK_HANDOFF: GridHandoffResult = { code: 'OK', exitCode: 0, message: '', stdout: '', stderr: '' }
+const MISSING_HANDOFF: GridHandoffResult = {
+ code: 'GRID_CLI_MISSING', exitCode: 1, message: 'no grid', stdout: '', stderr: '',
+}
+const EXISTED: EnsureResult = { status: 'existed', message: '' }
+const CREATED: EnsureResult = { status: 'created', message: '' }
+
+/** Deps with every seam a no-op success, so a test overrides only the one it is about. */
+function deps(over: Partial<GridAttachDeps> = {}): GridAttachDeps & {
+ handoff: ReturnType<typeof vi.fn>
+ ensure: ReturnType<typeof vi.fn>
+ onName: ReturnType<typeof vi.fn>
+} {
+ const base = {
+ managedGridReady: Promise.resolve(),
+ gridAvailable: () => true,
+ mintName: async () => NAME,
+ accessToken: async () => 'tok',
+ signedInEmail: () => EMAIL,
+ gridNames: async () => [NAME],
+ handoff: vi.fn(async () => OK_HANDOFF),
+ ensure: vi.fn(async () => EXISTED),
+ onName: vi.fn(),
+ log: () => {},
+ }
+ return { ...base, ...over } as never
+}
+
+describe('reconcileGridAttach — the daemon-start convergence', () => {
+ 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)
+
+ expect(r.status).toBe('converged')
+ expect(r.name).toBe(NAME)
+ expect(d.handoff).not.toHaveBeenCalled()
+ expect(d.ensure).not.toHaveBeenCalled()
+ expect(d.onName).toHaveBeenCalledWith(NAME)
+ })
+
+ it('re-signs in and ensures when the account name is not known locally (never created, or not synced here)', async () => {
+ // The name is not in the local `grid ls`, so the machine cannot be proven to be set up — it
+ // (re)signs in as this account and ensures the grid rather than acting on a weaker guess.
+ const d = deps({ gridNames: async () => [], ensure: vi.fn(async () => CREATED) })
+ const r = await reconcileGridAttach(d)
+
+ expect(r.status).toBe('signed-in')
+ expect(d.handoff).toHaveBeenCalledWith('tok')
+ expect(d.ensure).toHaveBeenCalledWith(NAME)
+ expect(d.onName).toHaveBeenCalledWith(NAME)
+ })
+
+ it('does not false-positive across two accounts sharing an email local-part', async () => {
+ // Signed in to grid as `someone@personal` (grid `someone-11112222`) while the harness account is
+ // `someone@company` (minted `someone-7f3a91c4`). The names differ, so the local `grid ls` does
+ // NOT contain the harness account's name — this must overwrite, not skip.
+ const d = deps({ signedInEmail: () => '[email protected]', gridNames: async () => ['someone-11112222'] })
+ const r = await reconcileGridAttach(d)
+
+ expect(r.status).toBe('signed-in')
+ expect(d.handoff).toHaveBeenCalledOnce()
+ expect(d.ensure).toHaveBeenCalledWith(NAME)
+ })
+
+ it('hands the token over, then ensures, when this machine has no grid sign-in', async () => {
+ const d = deps({ signedInEmail: () => null, gridNames: async () => [] })
+ const r = await reconcileGridAttach(d)
+
+ expect(r.status).toBe('signed-in')
+ expect(d.handoff).toHaveBeenCalledWith('tok')
+ expect(d.ensure).toHaveBeenCalledWith(NAME)
+ expect(d.onName).toHaveBeenCalledWith(NAME)
+ })
+
+ it('overwrites a different account: signed in as someone else means a hand-off', async () => {
+ // The signed-in email's pattern does not match the account's minted name.
+ const d = deps({ signedInEmail: () => '[email protected]', gridNames: async () => ['other-11112222'] })
+ const r = await reconcileGridAttach(d)
+
+ expect(r.status).toBe('signed-in')
+ expect(d.handoff).toHaveBeenCalledOnce()
+ expect(d.ensure).toHaveBeenCalledWith(NAME)
+ })
+
+ it('does nothing and reports no-cli when there is no grid binary', async () => {
+ const d = deps({ gridAvailable: () => false, mintName: vi.fn() as never })
+ const r = await reconcileGridAttach(d)
+
+ expect(r.status).toBe('no-cli')
+ expect(d.onName).not.toHaveBeenCalled()
+ expect((d.mintName as ReturnType<typeof vi.fn>)).not.toHaveBeenCalled()
+ })
+
+ it('stops at no-name on an older backend that mints none, without touching grid', async () => {
+ const d = deps({ mintName: async () => null })
+ const r = await reconcileGridAttach(d)
+
+ expect(r.status).toBe('no-name')
+ expect(d.handoff).not.toHaveBeenCalled()
+ expect(d.ensure).not.toHaveBeenCalled()
+ expect(d.onName).not.toHaveBeenCalled()
+ })
+
+ it('stops at no-name when the control plane is unreachable — and will try again next start', async () => {
+ const d = deps({ mintName: async () => { throw new Error('ECONNREFUSED') } })
+ const r = await reconcileGridAttach(d)
+
+ expect(r.status).toBe('no-name')
+ expect(r.detail).toContain('ECONNREFUSED')
+ expect(d.handoff).not.toHaveBeenCalled()
+ })
+
+ it('reports handoff-failed without ensuring, leaving the harness sign-in untouched', async () => {
+ const d = deps({ signedInEmail: () => null, handoff: vi.fn(async () => MISSING_HANDOFF) })
+ const r = await reconcileGridAttach(d)
+
+ expect(r.status).toBe('handoff-failed')
+ expect(d.ensure).not.toHaveBeenCalled()
+ expect(d.onName).not.toHaveBeenCalled()
+ })
+
+ it('waits for the managed grid runtime 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,
+ gridAvailable: () => { order.push('available'); return false },
+ })
+
+ const done = reconcileGridAttach(d)
+ // The binary check must not have run before the runtime promise settled.
+ await Promise.resolve()
+ expect(order).toEqual([])
+ releaseRuntime()
+ await done
+ 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 })
+ await expect(reconcileGridAttach(d)).resolves.toMatchObject({ status: 'no-cli' })
+ })
+})
diff --git a/cli/src/lib/gridAttach.ts b/cli/src/lib/gridAttach.ts
new file mode 100644
index 000000000..2b3bd9e58
--- /dev/null
+++ b/cli/src/lib/gridAttach.ts
@@ -0,0 +1,173 @@
+/**
+ * Bring this machine's grid sign-in into line with its harness sign-in — on every daemon start.
+ *
+ * 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`.
+ *
+ * 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.
+ *
+ * **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.
+ *
+ * **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.
+ */
+import { gridJson } from './gridExec.js'
+import type { GridHandoffResult } from './gridHandoff.js'
+import type { EnsureResult } from './gridEnsure.js'
+
+export type GridAttachStatus =
+ /** No `grid` on this machine — there is nothing to attach a sign-in to. */
+ | 'no-cli'
+ /** The backend issued no grid name (an older backend, or the control plane was unreachable). */
+ | 'no-name'
+ /** 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. */
+ | 'signed-in'
+ /** The hand-off was needed and did not succeed. The harness sign-in is untouched. */
+ | 'handoff-failed'
+
+export interface GridAttachResult {
+ status: GridAttachStatus
+ /** The account's private grid name, once known; null when the backend issued none. */
+ name: string | null
+ /** One sentence for a caller that wants to log the outcome. Never contains a credential. */
+ detail: string
+}
+
+/**
+ * The seams this reconcile runs through. The grid-facing ones default to the real modules
+ * ({@link defaultGridAttachDeps}); the network and daemon-facing ones are supplied by `cli.ts`,
+ * 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>
+ /** 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
+ * when the backend predates the route. Throws when the control plane cannot be reached. */
+ mintName: () => Promise<string | null>
+ /** A live harness access token, for the hand-off. Throws when the SSO session is gone. */
+ accessToken: () => Promise<string>
+ /** The email `grid` recorded for this machine's sign-in, or null when signed out of grid. */
+ signedInEmail: () => string | null
+ /** The grid names this machine's `grid` knows locally (`grid --remote ls`, no network call). */
+ gridNames: () => Promise<string[]>
+ /** Run `grid login --harness` with this token. */
+ handoff: (token: string) => Promise<GridHandoffResult>
+ /** Make sure the account's private grid exists. */
+ ensure: (name: string) => Promise<EnsureResult>
+ /** Publish the confirmed name into the daemon and drop the grid memos, so the next `grid_models_list`
+ * / retarget answers with this account's grid rather than a stale or absent one. */
+ onName: (name: string) => void
+ /** One sentence, prefixed by the caller. */
+ log: (line: string) => void
+}
+
+function msg(err: unknown): string {
+ return err instanceof Error ? err.message : String(err)
+}
+
+/**
+ * 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 */ }
+
+ if (!deps.gridAvailable()) {
+ deps.log('no grid CLI on this machine yet — nothing to attach a sign-in to')
+ return { status: 'no-cli', name: null, detail: '' }
+ }
+
+ let name: string | null
+ try {
+ name = await deps.mintName()
+ } catch (err) {
+ deps.log(`could not read this account's grid name (${msg(err)}) — will try again on the next start`)
+ return { status: 'no-name', name: null, detail: msg(err) }
+ }
+ if (!name) {
+ deps.log('this account has no grid name yet (older backend) — skipping grid setup')
+ return { status: 'no-name', name: null, detail: '' }
+ }
+
+ // The exact, unambiguous signal that this machine is already set up: the account's grid name is
+ // GLOBALLY UNIQUE (its suffix is a hash of the account id), so this machine's `grid` knowing that
+ // name locally can only mean it is signed in as this account AND the grid exists. A weaker check —
+ // "is the signed-in email's private-grid pattern a match" — would false-positive across two
+ // accounts sharing an email local-part (`kelvin@personal` vs `kelvin@company`), skip the overwrite
+ // decision (1) calls for, and then `ensure` under the wrong account. `grid ls` is a local read
+ // (no network), so this stays cheap on the common, already-set-up path.
+ const email = deps.signedInEmail()
+ let names: string[] = []
+ if (email) {
+ try {
+ names = await deps.gridNames()
+ } catch {
+ // A local read that failed reads as "not there", which the hand-off + ensure below handle.
+ }
+ }
+ if (email && names.includes(name)) {
+ deps.onName(name)
+ deps.log(`already signed in with grid '${name}' — nothing to do`)
+ return { status: 'converged', name, detail: '' }
+ }
+
+ // Everything else — signed out, signed in as a DIFFERENT account, or the grid not yet created /
+ // synced on this machine — is resolved by (re)signing in as this account and making sure the grid
+ // exists. When the machine was signed in as a different account, this overwrites it, by design
+ // (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) }
+ }
+ 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 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 }
+}
+
+/**
+ * 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 async function gridNamesLocal(): Promise<string[]> {
+ const { value } = await gridJson<Array<{ grid?: unknown }>>(['--remote', 'ls'])
+ if (!Array.isArray(value)) return []
+ return value.map((row) => (typeof row.grid === 'string' ? row.grid : '')).filter(Boolean)
+}
diff --git a/docs/skills/harness-compute.md b/docs/skills/harness-compute.md
index 1bd3a4f35..eda4527a3 100644
--- a/docs/skills/harness-compute.md
+++ b/docs/skills/harness-compute.md
@@ -97,8 +97,10 @@ they don't know, and there is nothing for them to choose. The name stays out of
it's an argument you pass, not a thing you mention.
No name (or more than one) means it isn't provisioned: stop and say, in plain words, "Harness
-Compute isn't set up on your account yet — sign in to Harness again and it will be." Don't invent
-a name or create one; a guessed name can collide with someone else's on the same shared service.
+Compute isn't set up on this machine yet — restart Harness and it will set itself up." Harness signs
+this machine in to its grid and creates the account's private grid on start, so a restart is what
+completes the setup; signing in again does the same. Don't invent a name or create one; a guessed
+name can collide with someone else's on the same shared service.
**If a command fails because the user isn't signed in**, stop and tell them to run
`harness login`. That's the only command in this whole feature that's ever theirs to run by hand.