The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
fix: bound the grid sign-in child, and let `harness grid login` finish the job
Kelvind7b7d717c2e7
diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex ca108e197..224d12bd5 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -55,7 +55,7 @@ import { renderLoginSuccessHtml } from './lib/loginPage.js'import { AuthSessionError, AuthSessionManager, clearAuthSession, readAuthSession, writeAuthSession, type AuthSession } from './lib/authSession.js'import { handOffToGrid } from './lib/gridHandoff.js'import { ensureGridInstalled } from './lib/gridInstall.js'-import { ensureHarnessGrid } from './lib/gridEnsure.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'@@ -555,22 +555,39 @@ async function attachGridToSignIn(token: string, json: boolean): Promise<Record<note(handoff.message)return { grid: { signedIn: false, code: handoff.code } }}- // The name is the backend's to mint and remember — this CLI holds neither the account's email nor- // its id (see backend/src/routes/grid.ts). A backend without the route is simply an older backend:- // no grid is ensured, nothing fails, and the next sign-in after it ships picks this up.+ 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.+ *+ * The second half of attaching a machine to grid, and the half `harness grid login` used to skip:+ * that command signed in and stopped, so an account whose grid had never been created was left+ * signed in to nothing, with an empty model picker and no way to tell why. Shared from here so the+ * sign-in's grid half and the explicit command cannot drift apart again.+ *+ * **The name is the backend's to mint and remember** — this CLI holds neither the account's email+ * nor its id (see `backend/src/routes/grid.ts`). A backend without the route is simply an older+ * backend: no grid is ensured, nothing fails, and the next sign-in after it ships picks this up.+ *+ * Best-effort throughout: every failure is a note through `note` and nothing more.+ */+async function ensureAccountGrid(note: (line: string) => void): Promise<{ status: EnsureStatus; name: string | null }> {let gridName: string | null = nulltry {const { headers } = await controlPlaneAuth()gridName = (await postJson<{ gridName?: string }>('/api/grid/name', {}, headers)).gridName ?? null} catch (err) {note(`Could not read this account's grid name (${(err as Error).message}); skipping grid setup.`)- return { grid: { signedIn: true, ensured: 'skipped' } }+ return { status: 'skipped', name: null }}- if (!gridName) return { grid: { signedIn: true, ensured: 'skipped' } }+ if (!gridName) return { status: 'skipped', name: null }const ensured = await ensureHarnessGrid(gridName)if (ensured.status === 'failed' || ensured.status === 'skipped') note(ensured.message)else if (ensured.status === 'created') note(`Created your private grid '${gridName}'.`)- return { grid: { signedIn: true, ensured: ensured.status, name: gridName } }+ return { status: ensured.status, name: gridName }}async function loginCommand(@@ -757,6 +774,14 @@ async function gridLoginCommand(force: boolean, json: boolean): Promise<void> {}const handoff = await handOffToGrid(token, { json })if (handoff.code !== 'OK') { fail(handoff.code, handoff.message, handoff.exitCode, gridSaid(handoff)); return }+ // The sign-in on its own leaves an account whose grid was never created signed in to nothing —+ // this command used to stop here, and the empty model picker that followed named no cause. Same+ // second half the harness sign-in does, and best-effort in the same way.+ //+ // Deliberately NOT on the result line: that line is this command's pinned contract (the sign-in's+ // outcome and what `grid` itself said), and a client driving it reads exactly those keys. A person+ // on the human path gets the notes on stderr, where every other note from this command goes.+ await ensureAccountGrid((line) => { if (!json) console.error(` · ${line}`) })if (!json) return// The same key `harness login --json` uses, present only when it is true, so a client driving the// two reads one contract rather than two — the harness sign-in's own line is worded exactly so.@@ -1598,11 +1623,10 @@ async function runForeground(session: AuthSession): Promise<void> {let gridAttachDone = falselet gridAttachAttempts = 0// A hard ceiling on how long the RPCs will gate on an attempt, 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 an attempt 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; an attempt that- // lands later still publishes the name through `onName`.+ // Every step inside an attempt is bounded on its own now — `mintName` by its abort signal, the+ // hand-off and the ensure by their own watchdogs — so this is the backstop rather than the only+ // guard: whatever an attempt does, the RPCs stop paying for it after the ceiling. Past it the+ // probe returns null; an attempt that lands later still publishes the name through `onName`.let gridAttachDeadline = 0const runGridAttach = (): void => {diff --git a/cli/src/gridCommand.spec.ts b/cli/src/gridCommand.spec.tsindex 75fcb9149..372f29178 100644--- a/cli/src/gridCommand.spec.ts+++ b/cli/src/gridCommand.spec.ts@@ -188,6 +188,9 @@ function fakeBackend(handlers: {exchange?: (body: any) => anyresolveComputer?: (body: any) => anyrefresh?: (body: any) => { status: number; body: unknown }+ /** `POST /api/grid/name` — the account's minted grid name. Absent = an older backend, which is+ * what every case that does not stub it is exercising (the route 404s and grid setup is skipped). */+ gridName?: (body: any) => any}): Promise<{ server: Server; base: string }> {return new Promise((resolve) => {const server = createServer((req, res) => {@@ -202,6 +205,7 @@ function fakeBackend(handlers: {if (req.url === '/api/auth/authorize-native' && handlers.authorizeNative) { send(handlers.authorizeNative(body)); return }if (req.url === '/api/auth/exchange' && handlers.exchange) { send(handlers.exchange(body)); return }if (req.url === '/api/machines/resolve-computer' && handlers.resolveComputer) { send(handlers.resolveComputer(body)); return }+ if (req.url === '/api/grid/name' && handlers.gridName) { send(handlers.gridName(body)); return }if (req.url === '/api/auth/refresh' && handlers.refresh) {const answer = handlers.refresh(body)res.writeHead(answer.status, { 'content-type': 'application/json' })@@ -291,6 +295,39 @@ describe('harness grid login — an already-signed-in computer', () => {expect(readRecord(root).args).toEqual(['login', '--harness'])}, 20_000)+ it('also makes sure the account\'s grid exists, without changing its result line', async () => {+ // Signing in and stopping is what this command used to do, and it left an account whose grid had+ // never been created signed in to nothing — an empty model picker naming no cause. The second+ // half now runs here too, and the fake records the LAST `grid` it ran: anything other than+ // `login` is proof the ensure happened.+ const root = tempRoot()+ seedSession(root)+ const { base } = await fakeBackend({+ resolveComputer: () => ({ machine: { machineId: 'm_seeded' } }),+ gridName: () => ({ gridName: 'someone-7f3a91c4' }),+ })++ const result = await run(root, ['grid', 'login', '--json'], base)++ expect(result.status).toBe(0)+ // The contract a client reads is untouched: the sign-in's outcome, and nothing about the ensure.+ expect(ndjson(result.stdout)).toEqual([{ type: 'result', status: 'success', alreadySignedIn: true }])+ expect(readRecord(root).args[0]).not.toBe('login')+ }, 20_000)++ it('leaves the grid alone when the backend mints no name — an older backend is not a failure', async () => {+ const root = tempRoot()+ seedSession(root)+ const { base } = await signedInBackend() // no `/api/grid/name` route++ const result = await run(root, ['grid', 'login', '--json'], base)++ expect(result.status).toBe(0)+ expect(ndjson(result.stdout)).toEqual([{ type: 'result', status: 'success', alreadySignedIn: true }])+ // Nothing after the hand-off, so the sign-in is still the last thing that ran.+ expect(readRecord(root).args).toEqual(['login', '--harness', '--json'])+ }, 20_000)+it('carries the child\'s JSON answer out on the result line', async () => {const root = tempRoot()seedSession(root)diff --git a/cli/src/lib/gridHandoff.spec.ts b/cli/src/lib/gridHandoff.spec.tsindex 62ebaa575..3f7e83091 100644--- a/cli/src/lib/gridHandoff.spec.ts+++ b/cli/src/lib/gridHandoff.spec.ts@@ -105,3 +105,45 @@ describe('handOffToGrid — which grid it runs', () => {expect(result.message).toContain('grid')})})++/**+ * The watchdog. `grid login --harness` makes two control-plane round trips, and a connection that is+ * accepted and then answered by nobody used to leave this promise pending for good — a `harness+ * login` that never returned, and a daemon reconcile that never settled.+ */+describe('handOffToGrid — a child that never answers', () => {+ /** A `grid` that reads the token and then hangs, the shape of a black-holed control plane. */+ function hangingGrid(dir: string): string {+ mkdirSync(dir, { recursive: true })+ const bin = join(dir, 'grid')+ writeFileSync(bin, ['#!/bin/sh', '/bin/cat > /dev/null', 'sleep 60', ''].join('\n'), { mode: 0o755 })+ return bin+ }++ it('kills it and reports a timeout rather than awaiting forever', async () => {+ process.env.HARNESS_GRID_BIN = hangingGrid(join(root, 'hangs'))+ const { handOffToGrid } = await load()++ const started = Date.now()+ const result = await handOffToGrid('tok_hang', { json: true, timeoutMs: 300 })++ // It returned at all — the property the whole watchdog exists for.+ expect(Date.now() - started).toBeLessThan(10_000)+ // Classified as the ordinary failure rather than a new code, so every caller's existing+ // handling applies unchanged (the same choice `gridExec` makes for its own timeout).+ expect(result).toMatchObject({ code: 'GRID_LOGIN_FAILED', exitCode: 1 })+ expect(result.message).toContain('did not answer')+ }, 20_000)++ it('does not arm the timeout against a child that answers promptly', async () => {+ fakeGrid(join(root, 'prompt-bin'), 'prompt')+ process.env.HARNESS_GRID_BIN = join(root, 'prompt-bin', 'grid')+ const { handOffToGrid } = await load()++ // A timeout far shorter than the case would take if the timer were not cleared on success.+ const result = await handOffToGrid('tok_fast', { json: true, timeoutMs: 5_000 })++ expect(result.code).toBe('OK')+ expect(argsOf('prompt')).toEqual(['login', '--harness', '--json'])+ })+})diff --git a/cli/src/lib/gridHandoff.ts b/cli/src/lib/gridHandoff.tsindex e6764613f..08e851b30 100644--- a/cli/src/lib/gridHandoff.ts+++ b/cli/src/lib/gridHandoff.ts@@ -61,6 +61,25 @@ const OUTDATED_MESSAGE =`Your \`grid\` CLI is too old: it does not understand \`grid login ${GRID_HANDOFF_FLAG}\`. Update `+ 'it, then run `harness grid login` again.'+/**+ * How long the child may take before it is killed and reported as a failure.+ *+ * ⚠️ Without this the spawn had no watchdog at all, unlike every other `grid` call+ * (`gridExec`'s `DEFAULT_TIMEOUT_MS`): a control plane that accepts the connection and then answers+ * nothing left this promise pending forever — a `harness login` that never returned, and, once the+ * daemon began reconciling on its own (`lib/gridAttach.ts`), an attempt that never settled.+ *+ * Longer than `gridExec`'s 30s on purpose. This child makes TWO control-plane round trips (the+ * token exchange, then the per-grid token fetch) where the others make one, and it is the call a+ * person is most likely to be watching — cutting a slow but working sign-in off would be worse than+ * waiting. It is a bound on a hang, not a performance budget.+ */+const HANDOFF_TIMEOUT_MS = 60_000++function timedOutMessage(timeoutMs: number): string {+ return `\`grid login ${GRID_HANDOFF_FLAG}\` did not answer within ${Math.round(timeoutMs / 1000)}s.`+}+function failedMessage(status: number | null, signal: NodeJS.Signals | null): string {const how = status === null ? `was killed by ${signal ?? 'a signal'}` : `exited ${status}`// No "see the output above": under --json there IS no above for whatever is reading the stream.@@ -80,7 +99,7 @@ function failedMessage(status: number | null, signal: NodeJS.Signals | null): st*/export async function handOffToGrid(token: string,- opts: { json?: boolean } = {},+ opts: { json?: boolean; timeoutMs?: number } = {},): Promise<GridHandoffResult> {// Asking by reading rather than by spawning to find out: a missing `grid` is a sentence about// installing one, not a spawn error the caller has to recognise — and a present-but-unrunnable@@ -90,6 +109,7 @@ export async function handOffToGrid(if (!binaryOnPath(binary)) {return { code: 'GRID_CLI_MISSING', exitCode: 1, message: MISSING_MESSAGE, stdout: '', stderr: '' }}+ const timeoutMs = opts.timeoutMs ?? HANDOFF_TIMEOUT_MSconst args = ['login', GRID_HANDOFF_FLAG, ...(opts.json ? ['--json'] : [])]return await new Promise<GridHandoffResult>((resolve) => {const child = spawn(binary, args, {@@ -107,7 +127,22 @@ export async function handOffToGrid(})let settled = false- const settle = (result: GridHandoffResult): void => { if (!settled) { settled = true; resolve(result) } }+ let timer: ReturnType<typeof setTimeout> | undefined+ const settle = (result: GridHandoffResult): void => {+ if (settled) return+ settled = true+ if (timer) clearTimeout(timer)+ resolve(result)+ }++ // The watchdog, armed before anything can block. `SIGKILL` with no `SIGTERM` first, exactly as+ // `gridExec` does: what is being bounded is a child that has stopped responding, and a graceful+ // signal it may never handle is one more thing to wait for. The `close` this provokes finds+ // `settled` already true, so the kill reports the timeout rather than a signal death.+ timer = setTimeout(() => {+ try { child.kill('SIGKILL') } catch { /* already gone */ }+ settle({ code: 'GRID_LOGIN_FAILED', exitCode: 1, message: timedOutMessage(timeoutMs), stdout, stderr })+ }, timeoutMs)// stdio[0] is a pipe, so this is never null. Refusing loudly anyway rather than optional-chaining// past it: with no pipe the token is never delivered, and a `grid` left waiting for one on a