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.

Grid on Windows follows the pin; a failed grid setup is held instead of retried every 2 s (#1933)

lingrd3de7e79e28c1
diff --git a/cli/src/lib/gridAttach.spec.ts b/cli/src/lib/gridAttach.spec.ts
index 1929746ad..55a56657e 100644
--- a/cli/src/lib/gridAttach.spec.ts
+++ b/cli/src/lib/gridAttach.spec.ts
@@ -231,7 +231,7 @@ describe('reconcileGridAttach — a hand-off grid refuses', () => {
/**
* 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.
+ * already done, and a failure not asked again for a while.
*/
describe('createGridAccess — grid set up when a feature asks', () => {
const result = (status: GridAttachResult['status'], ownGrid?: GridAttachResult['ownGrid']): GridAttachResult =>
@@ -273,13 +273,49 @@ describe('createGridAccess — grid set up when a feature asks', () => {
expect(attempt).toHaveBeenCalledTimes(1)
})
- 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')
+ it('holds a failure for a minute, then tries again', async () => {
+ let now = 0
+ const attempt = vi.fn(async () => (attempt.mock.calls.length === 1 ? result('no-cli') : result('signed-in')))
+ const grid = createGridAccess({ attempt, signedIn: () => true, log: () => {}, now: () => now })
+ expect((await grid.ensure()).status).toBe('no-cli')
+ now = 59_000
+ expect((await grid.ensure()).status).toBe('no-cli')
+ expect(attempt).toHaveBeenCalledTimes(1)
+ now = 60_000
expect((await grid.ensure()).status).toBe('signed-in')
expect(attempt).toHaveBeenCalledTimes(2)
})
+ it('waits twice as long after each failure in a row, never more than ten minutes', async () => {
+ // DESKTOP-0TFH0OJ, 2026-10-26: a held Swarm start asked every 2 seconds (core/agents/pendingLaunches.ts) and each
+ // ask ran grid's installer again, which failed the same way 13,658 times in two days.
+ let now = 0
+ const attempt = vi.fn(async () => result('no-cli'))
+ const grid = createGridAccess({ attempt, signedIn: () => true, log: () => {}, now: () => now })
+ const asked: number[] = []
+ for (now = 0; now <= 40 * 60_000; now += 2_000) {
+ const before = attempt.mock.calls.length
+ await grid.ensure()
+ if (attempt.mock.calls.length > before) asked.push(now / 60_000)
+ }
+ expect(asked).toEqual([0, 1, 3, 7, 15, 25, 35])
+ })
+
+ it('a success clears the wait: the next failure waits a minute again', async () => {
+ let now = 0
+ let signedIn = true
+ const answers = [result('no-cli'), result('no-cli'), result('signed-in'), result('no-cli'), result('signed-in')]
+ const attempt = vi.fn(async () => answers.shift()!)
+ const grid = createGridAccess({ attempt, signedIn: () => signedIn, log: () => {}, now: () => now })
+ await grid.ensure()
+ now = 60_000; await grid.ensure()
+ now = 180_000; expect((await grid.ensure()).status).toBe('signed-in')
+ signedIn = false
+ now = 181_000; expect((await grid.ensure()).status).toBe('no-cli')
+ now = 241_000; expect((await grid.ensure()).status).toBe('signed-in')
+ expect(attempt).toHaveBeenCalledTimes(5)
+ })
+
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')
diff --git a/cli/src/lib/gridAttach.ts b/cli/src/lib/gridAttach.ts
index 34da14927..650c99986 100644
--- a/cli/src/lib/gridAttach.ts
+++ b/cli/src/lib/gridAttach.ts
@@ -187,8 +187,14 @@ export interface GridAccessOptions {
* since forgets what this daemon remembered. */
signedIn: () => boolean
log: (line: string) => void
+ /** Injected for the tests. */
+ now?: () => number
}
+/** How long a failure is answered as it is before grid is asked again: a minute, doubled for each failure in a row. */
+const FAILURE_HOLD_MS = 60_000
+const MAX_FAILURE_HOLD_MS = 10 * 60_000
+
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. */
@@ -204,30 +210,42 @@ export interface GridAccess {
* - **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.
+ * - **A failure is held.** Not every ask is a person acting: a held Swarm start asks every 2 seconds
+ * (core/agents/pendingLaunches.ts) and each owner's Swarm every minute (superTabs/swarmGrids.ts), and each ask that
+ * failed ran grid's installer again. A failure answers as it is for a minute, twice as long after each failure in a
+ * row up to ten; a success clears it.
*/
export function createGridAccess(opts: GridAccessOptions): GridAccess {
+ const now = opts.now ?? Date.now
let signedIn = false
let ownGridThere = false
let last: GridAttachResult | null = null
+ let failure: { result: GridAttachResult; until: number; hold: number } | null = null
let queue: Promise<unknown> = Promise.resolve()
+ const failed = (result: GridAttachResult): GridAttachResult => {
+ const hold = failure ? Math.min(failure.hold * 2, MAX_FAILURE_HOLD_MS) : FAILURE_HOLD_MS
+ failure = { result, until: now() + hold, hold }
+ return result
+ }
+
const once = async (ownGrid: boolean): Promise<GridAttachResult> => {
if (!opts.signedIn()) signedIn = ownGridThere = false
if (last && signedIn && (!ownGrid || ownGridThere)) return last
+ if (failure && now() < failure.until) return failure.result
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 }
- }
- if (result.status === 'converged' || result.status === 'signed-in') {
- signedIn = true
- if (result.ownGrid && OWN_GRID_THERE.has(result.ownGrid)) ownGridThere = true
- last = result
+ return failed({ status: 'handoff-failed', name: null, detail })
}
+ if (result.status !== 'converged' && result.status !== 'signed-in') return failed(result)
+ failure = null
+ signedIn = true
+ if (result.ownGrid && OWN_GRID_THERE.has(result.ownGrid)) ownGridThere = true
+ last = result
return result
}
diff --git a/cli/src/lib/gridCalls.spec.ts b/cli/src/lib/gridCalls.spec.ts
new file mode 100644
index 000000000..54dd5ae87
--- /dev/null
+++ b/cli/src/lib/gridCalls.spec.ts
@@ -0,0 +1,48 @@
+import { describe, expect, it } from 'vitest'
+import { gridCallStarted, withGridCallsPaused } from './gridCalls.js'
+
+const tick = () => new Promise((resolve) => setTimeout(resolve, 5))
+
+describe('withGridCallsPaused — an install and the grid calls Harness makes', () => {
+ it('waits for the grid calls already running before it starts', async () => {
+ const done = await gridCallStarted()
+ let ran = false
+ const install = withGridCallsPaused(async () => { ran = true })
+ await tick()
+ expect(ran).toBe(false)
+ done()
+ await install
+ expect(ran).toBe(true)
+ })
+
+ it('holds a grid call asked for meanwhile until the install is over', async () => {
+ let finish: () => void = () => {}
+ const install = withGridCallsPaused(() => new Promise<void>((resolve) => { finish = resolve }))
+ await tick()
+ let started = false
+ const call = gridCallStarted().then((done) => { started = true; return done })
+ await tick()
+ expect(started).toBe(false)
+ finish()
+ await install
+ ;(await call)()
+ expect(started).toBe(true)
+ })
+
+ it('starts anyway once the wait is over — grid\'s installer still refuses to replace a running grid', async () => {
+ const done = await gridCallStarted()
+ let ran = false
+ await withGridCallsPaused(async () => { ran = true }, 20)
+ expect(ran).toBe(true)
+ done()
+ })
+
+ it('a call counted twice as done is counted once', async () => {
+ const done = await gridCallStarted()
+ done()
+ done()
+ let ran = false
+ await withGridCallsPaused(async () => { ran = true })
+ expect(ran).toBe(true)
+ })
+})
diff --git a/cli/src/lib/gridCalls.ts b/cli/src/lib/gridCalls.ts
new file mode 100644
index 000000000..0d932c280
--- /dev/null
+++ b/cli/src/lib/gridCalls.ts
@@ -0,0 +1,49 @@
+/**
+ * The `grid` children this process runs, and a pause an install holds.
+ *
+ * On Windows a running grid holds its install's files open. grid's installer (`install.ps1`) then refuses to replace
+ * it — and a grid started after its check, while `uv tool install --force` is replacing files, leaves an install that
+ * cannot even `grid stop`. A Swarm machine starts a short grid call every few seconds, so an install (Windows' pin,
+ * `gridWindowsPin.ts`) holds new ones back and waits for those running to end before it begins.
+ */
+
+let running = 0
+let paused: Promise<void> | null = null
+let idle: (() => void) | null = null
+
+/** Wait out an install, then count one grid child as running; call the answer when it has ended. */
+export async function gridCallStarted(): Promise<() => void> {
+ while (paused) await paused
+ running++
+ let ended = false
+ return () => {
+ if (ended) return
+ ended = true
+ running--
+ if (running === 0) idle?.()
+ }
+}
+
+/** How long an install waits for the grid calls already running. Past it, it starts anyway: grid's installer looks
+ * for a running grid itself and refuses rather than replace one. */
+const DRAIN_MS = 60_000
+
+/** Run [install] with no new grid call starting, once those running have ended (or [drainMs] has passed). */
+export async function withGridCallsPaused<T>(install: () => Promise<T>, drainMs: number = DRAIN_MS): Promise<T> {
+ while (paused) await paused
+ let release: () => void = () => {}
+ paused = new Promise<void>((resolve) => { release = resolve })
+ try {
+ if (running > 0) {
+ await new Promise<void>((resolve) => {
+ const timer = setTimeout(resolve, drainMs)
+ idle = () => { clearTimeout(timer); resolve() }
+ })
+ idle = null
+ }
+ return await install()
+ } finally {
+ paused = null
+ release()
+ }
+}
diff --git a/cli/src/lib/gridExec.spec.ts b/cli/src/lib/gridExec.spec.ts
index f00837c0c..7e7a7d96a 100644
--- a/cli/src/lib/gridExec.spec.ts
+++ b/cli/src/lib/gridExec.spec.ts
@@ -6,7 +6,7 @@
* order is the contract: the developer override, then the managed runtime's pointer, then PATH —
* with the pointer trusted only when it names something runnable INSIDE the runtime dir.
*/
-import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { chmodSync, existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
@@ -146,6 +146,37 @@ describe('gridExec', () => {
expect(result).toMatchObject({ code: 'GRID_CLI_MISSING', exitCode: 1 })
expect(result.message).toContain('grid')
})
+
+ it('waits while an install holds grid calls back (gridCalls.ts)', async () => {
+ process.env.HARNESS_GRID_BIN = fakeGrid(join(root, 'elsewhere'))
+ const { gridExec } = await load()
+ const { withGridCallsPaused } = await import('./gridCalls.js')
+ let finish: () => void = () => {}
+ const install = withGridCallsPaused(() => new Promise<void>((resolve) => { finish = resolve }))
+ let answered = false
+ const call = gridExec(['--version']).then((result) => { answered = true; return result })
+ await new Promise((resolve) => setTimeout(resolve, 300))
+ expect(answered).toBe(false)
+ finish()
+ await install
+ expect((await call).code).toBe('OK')
+ })
+
+ it('an install waits for a grid call already running', async () => {
+ mkdirSync(join(root, 'slow'))
+ const slow = join(root, 'slow', 'grid')
+ const exited = join(root, 'slow', 'exited')
+ writeFileSync(slow, `#!/bin/sh\n/bin/sleep 0.3\n: > "${exited}"\nexit 0\n`, { mode: 0o755 })
+ process.env.HARNESS_GRID_BIN = slow
+ const { gridExec } = await load()
+ const { withGridCallsPaused } = await import('./gridCalls.js')
+ const call = gridExec(['--version'])
+ await new Promise((resolve) => setTimeout(resolve, 50))
+ let childGoneWhenInstallRan = false
+ await withGridCallsPaused(async () => { childGoneWhenInstallRan = existsSync(exited) })
+ await call
+ expect(childGoneWhenInstallRan).toBe(true)
+ })
})
/**
diff --git a/cli/src/lib/gridExec.ts b/cli/src/lib/gridExec.ts
index a4150995b..aa1ea3a0b 100644
--- a/cli/src/lib/gridExec.ts
+++ b/cli/src/lib/gridExec.ts
@@ -22,6 +22,7 @@
import { spawn } from 'node:child_process'
import { binaryOnPath } from './binaryOnPath.js'
import { GRID_NO_UPDATE_CHECK_VAR, gridBinaryPath, gridChildEnv, gridCommand } from './gridBinary.js'
+import { gridCallStarted } from './gridCalls.js'
// Which `grid` to run is gridBinary.ts's, which the core keeps for its launches; said again here for
// every grid call that imports it from this module.
@@ -99,6 +100,8 @@ export async function gridExec(args: readonly string[], opts: GridExecOptions =
if (!binaryOnPath(binary, processEnv)) {
return { code: 'GRID_CLI_MISSING', exitCode: 1, stdout: '', stderr: '', message: MISSING_MESSAGE }
}
+ // Not while grid's installer replaces the install, and counted so an install waits for this (gridCalls.ts).
+ const ended = await gridCallStarted()
return await new Promise<GridResult>((resolve) => {
const command = gridCommand(binary, args)
const child = spawn(command.file, command.args, { stdio: ['pipe', 'pipe', 'pipe'], env: gridChildEnv(processEnv) })
@@ -109,6 +112,7 @@ export async function gridExec(args: readonly string[], opts: GridExecOptions =
if (settled) return
settled = true
clearTimeout(timer)
+ ended()
resolve(result)
}
const timer = setTimeout(() => {
@@ -180,6 +184,12 @@ export async function gridVersion(opts: GridExecOptions = {}): Promise<string |
return match ? match[1] : null
}
+/** A plain release number such as `0.3.61`: three whole numbers and nothing else (no `-rc1`, no spaces, no quotes). */
+export function isReleaseNumber(value: string): boolean {
+ const parts = value.split('.')
+ return parts.length === 3 && parts.every((part) => String(Number.parseInt(part, 10)) === part)
+}
+
/** Ordinary three-part semver compare, enough for a floor check. A version that cannot be parsed is
* treated as NOT meeting the floor: refusing to drive an unknown build is the safe direction. */
export function meetsVersionFloor(version: string | null, floor: string = GRID_VERSION_FLOOR): boolean {
diff --git a/cli/src/lib/gridFleetRpc.spec.ts b/cli/src/lib/gridFleetRpc.spec.ts
index fdaeddf1e..e88a56c75 100644
--- a/cli/src/lib/gridFleetRpc.spec.ts
+++ b/cli/src/lib/gridFleetRpc.spec.ts
@@ -1,8 +1,9 @@
import { afterEach, describe, expect, it } from 'vitest'
-import { chmodSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { chmodSync, existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { GridFleetRpc, GridOutputCapture, parseGridFleetRequest } from './gridFleetRpc.js'
+import { withGridCallsPaused } from './gridCalls.js'
import { encryptDownFrame, encryptRpcResult } from './e2ee/applicationFrames.js'
const directories: string[] = []
@@ -23,6 +24,19 @@ describe('paired Grid fleet commands', () => {
const result=await rpc.run('owner','one',{args,timeoutMs:3000})
expect(result.code).toBe(7);expect(result.ok).toBe(false);expect(JSON.parse(result.stdout)).toEqual(args)
})
+ it('waits while an install holds grid calls back (gridCalls.ts)', async () => {
+ const started=join(mkdtempSync(join(tmpdir(), 'grid-fleet-started-')), 'started')
+ const rpc=fixture(`require('node:fs').writeFileSync(${JSON.stringify(started)}, '');process.exit(0)`)
+ let finish: () => void = () => {}
+ const install=withGridCallsPaused(() => new Promise<void>((resolve) => { finish = resolve }))
+ const call=rpc.run('owner','paused',{args:['ls'],timeoutMs:10_000})
+ // A Node child takes about half a second to start on a busy Mac: give it well over that.
+ await new Promise((resolve) => setTimeout(resolve, 2_000))
+ expect(existsSync(started)).toBe(false)
+ finish(); await install
+ expect((await call).ok).toBe(true)
+ expect(existsSync(started)).toBe(true)
+ })
it('keeps timeout failures even when a child handles SIGTERM with exit zero', async () => {
const rpc=fixture("process.on('SIGTERM',()=>process.exit(0));setInterval(()=>{},1000)")
const result=await rpc.run('owner','timeout',{args:['join'],timeoutMs:200})
diff --git a/cli/src/lib/gridFleetRpc.ts b/cli/src/lib/gridFleetRpc.ts
index 4d3a12bc3..caa4cc689 100644
--- a/cli/src/lib/gridFleetRpc.ts
+++ b/cli/src/lib/gridFleetRpc.ts
@@ -1,5 +1,6 @@
/** Grid's complete argv API, carried over the existing paired-machine connection. No shell. */
import { spawn } from 'node:child_process'
+import { gridCallStarted } from './gridCalls.js'
import { gridBinaryPath, gridChildEnv, gridCommand } from './gridExec.js'
import { GRID_FLEET_MAX_TIMEOUT_MS } from './gridFleetProtocol.js'
@@ -57,6 +58,8 @@ export class GridFleetRpc {
const controller = new AbortController()
this.jobs.set(key, controller)
try {
+ // Not while grid's installer replaces the install, and counted so an install waits for this (gridCalls.ts).
+ const ended = await gridCallStarted()
return await new Promise<GridFleetResult>(resolve => {
const output = { stdout: new GridOutputCapture(), stderr: new GridOutputCapture() }
let stopped: string | null = null, done = false
@@ -69,7 +72,7 @@ export class GridFleetRpc {
})
const finish = (code: number, error: string | null) => {
if (done) return
- done = true; clearTimeout(timeout); clearTimeout(kill)
+ done = true; clearTimeout(timeout); clearTimeout(kill); ended()
resolve({ ok: code === 0 && !error, code, stdout: output.stdout.text, stderr: output.stderr.text, error })
}
const stop = (reason: string) => {
diff --git a/cli/src/lib/gridHandoff.spec.ts b/cli/src/lib/gridHandoff.spec.ts
index 9c812e228..2a84708d9 100644
--- a/cli/src/lib/gridHandoff.spec.ts
+++ b/cli/src/lib/gridHandoff.spec.ts
@@ -84,6 +84,21 @@ describe('handOffToGrid — which grid it runs', () => {
expect(updateCheckSeenBy('override')).toBe('1')
})
+ it('waits while an install holds grid calls back (gridCalls.ts)', async () => {
+ process.env.HARNESS_GRID_BIN = fakeGrid(join(root, 'elsewhere'), 'override')
+ const { handOffToGrid } = await load()
+ const { withGridCallsPaused } = await import('./gridCalls.js')
+ let finish: () => void = () => {}
+ const install = withGridCallsPaused(() => new Promise<void>((resolve) => { finish = resolve }))
+ const call = handOffToGrid('tok_1', { json: true })
+ // Spawning takes up to half a second on a busy Mac: give it well over that.
+ await new Promise((resolve) => setTimeout(resolve, 2_000))
+ expect(ran('override')).toBe(false)
+ finish()
+ await install
+ expect((await call).code).toBe('OK')
+ })
+
it('prefers the managed runtime over a grid on PATH', async () => {
fakeGrid(join(root, 'path-bin'), 'path')
process.env.PATH = join(root, 'path-bin')
diff --git a/cli/src/lib/gridHandoff.ts b/cli/src/lib/gridHandoff.ts
index 0f16c8225..14a38514a 100644
--- a/cli/src/lib/gridHandoff.ts
+++ b/cli/src/lib/gridHandoff.ts
@@ -24,6 +24,7 @@
import { spawn } from 'node:child_process'
import { binaryOnPath } from './binaryOnPath.js'
import { gridEnvelopes } from './gridEnvelope.js'
+import { gridCallStarted } from './gridCalls.js'
import { gridBinaryPath, gridChildEnv, gridCommand } from './gridExec.js'
/** The flag on `grid login` that means "read the token off stdin" (autonomous-grid's `cli/parser.py`).
@@ -130,6 +131,8 @@ export async function handOffToGrid(
}
const timeoutMs = opts.timeoutMs ?? HANDOFF_TIMEOUT_MS
const args = ['login', GRID_HANDOFF_FLAG, ...(opts.json ? ['--json'] : [])]
+ // Not while grid's installer replaces the install, and counted so an install waits for this (gridCalls.ts).
+ const ended = await gridCallStarted()
return await new Promise<GridHandoffResult>((resolve) => {
const command = gridCommand(binary, args)
const child = spawn(command.file, command.args, {
@@ -152,6 +155,7 @@ export async function handOffToGrid(
if (settled) return
settled = true
if (timer) clearTimeout(timer)
+ ended()
resolve(result)
}
diff --git a/cli/src/lib/gridInstall.spec.ts b/cli/src/lib/gridInstall.spec.ts
index a2af41922..8d0217ce3 100644
--- a/cli/src/lib/gridInstall.spec.ts
+++ b/cli/src/lib/gridInstall.spec.ts
@@ -1,5 +1,5 @@
import { describe, expect, it, vi } from 'vitest'
-import { ensureGridInstalled, GRID_INSTALL_PS1_URL, GRID_INSTALL_URL, installerCommand, type GridInstallDeps } from './gridInstall.js'
+import { ensureGridInstalled, GRID_INSTALL_PS1_URL, GRID_INSTALL_URL, installerCommand, installGrid, windowsInstallScript, type GridInstallDeps } from './gridInstall.js'
function deps(overrides: Partial<GridInstallDeps> = {}): GridInstallDeps & { runs: string[] } {
const runs: string[] = []
@@ -81,7 +81,55 @@ describe('ensureGridInstalled', () => {
run: async (script) => { runs.push(script); installed = true; return { exitCode: 0, output: 'ok' } },
})
expect((await ensureGridInstalled(d)).status).toBe('installed')
- expect(runs).toEqual([`irm ${GRID_INSTALL_PS1_URL} | iex`])
+ expect(runs).toEqual([windowsInstallScript(null)])
+ })
+})
+
+describe('windowsInstallScript', () => {
+ it("runs grid's install.ps1, and prints only the sentence it fails with — not PowerShell's error record around it", () => {
+ expect(windowsInstallScript(null)).toBe(
+ `try { irm ${GRID_INSTALL_PS1_URL} | iex } catch { [Console]::Error.WriteLine($_.Exception.Message); exit 1 }`)
+ })
+
+ it('tells it which release to lay down', () => {
+ expect(windowsInstallScript('0.3.62')).toBe(
+ `try { $env:GRID_VERSION='0.3.62'; irm ${GRID_INSTALL_PS1_URL} | iex } catch { [Console]::Error.WriteLine($_.Exception.Message); exit 1 }`)
+ })
+})
+
+describe('installGrid', () => {
+ it('tells the Windows installer which release to lay down, over the grid already there', async () => {
+ const runs: string[] = []
+ const d = deps({
+ platform: 'win32',
+ available: () => true,
+ run: async (script) => { runs.push(script); return { exitCode: 0, output: 'ok' } },
+ })
+ expect((await installGrid('0.3.62', d)).status).toBe('installed')
+ expect(runs).toEqual([windowsInstallScript('0.3.62')])
+ })
+
+ it('on Windows runs the installer with no grid call of this process running (gridCalls.ts)', async () => {
+ const order: string[] = []
+ const pause = async <T>(install: () => Promise<T>): Promise<T> => { order.push('pause'); const r = await install(); order.push('resume'); return r }
+ const run = async () => { order.push('run'); return { exitCode: 0, output: '' } }
+ await installGrid('0.3.62', deps({ platform: 'win32', available: () => true, pause, run }))
+ expect(order).toEqual(['pause', 'run', 'resume'])
+ order.length = 0
+ await installGrid(null, deps({ available: () => true, pause, run }))
+ expect(order).toEqual(['run'])
+ })
+
+ it("logs Windows' last lines without their carriage returns", async () => {
+ const output = '>>> Resolving grid wheel (0.3.60 -> v0.3.60)...\r\nERROR: grid is running from this install (pid 9044).\r\n'
+ const result = await installGrid('0.3.60', deps({ platform: 'win32', run: async () => ({ exitCode: 1, output }) }))
+ expect(result.message).toBe('grid installer exited 1 · >>> Resolving grid wheel (0.3.60 -> v0.3.60)... · ERROR: grid is running from this install (pid 9044).')
+ })
+
+ it('refuses a version that is not a plain release number — it goes into a PowerShell line', async () => {
+ const d = deps({ platform: 'win32' })
+ expect((await installGrid("1'; Remove-Item ~ -Recurse; '", d)).status).toBe('skipped')
+ expect(d.runs).toEqual([])
})
})
diff --git a/cli/src/lib/gridInstall.ts b/cli/src/lib/gridInstall.ts
index 82968c37a..40d90f844 100644
--- a/cli/src/lib/gridInstall.ts
+++ b/cli/src/lib/gridInstall.ts
@@ -14,7 +14,8 @@
*
* ⚠️ Best-effort, never a reason `harness start` or `harness login` fails. No `curl`, no network, a
* refused download — every one is a sentence in the log and a daemon that runs as before. A
- * machine that already has `grid` is never touched; nothing here updates a binary that exists.
+ * machine that already has `grid` is never touched by [ensureGridInstalled]; only Windows' pin
+ * ([installGrid], `gridWindowsPin.ts`) installs over one.
*
* Idempotent and serialised: two callers (start and a login that follows it) share one in-flight
* install rather than racing two installers into the same directory.
@@ -24,7 +25,8 @@ import { homedir } from 'node:os'
import { delimiter, join, win32 } from 'node:path'
import { env } from '../config/env.js'
import { binaryOnPath } from './binaryOnPath.js'
-import { gridAvailable } from './gridExec.js'
+import { withGridCallsPaused } from './gridCalls.js'
+import { gridAvailable, isReleaseNumber } from './gridExec.js'
export const GRID_INSTALL_URL = 'https://grid.autonomous.ai/install.sh'
@@ -49,6 +51,15 @@ export function installerCommand(
}
}
+/**
+ * grid's PowerShell installer, told which release to lay down when [version] is given. install.ps1 fails by `throw`;
+ * caught here, its sentence is printed alone instead of inside PowerShell's error record.
+ */
+export function windowsInstallScript(version: string | null): string {
+ const pinned = version ? `$env:GRID_VERSION='${version}'; ` : ''
+ return `try { ${pinned}irm ${GRID_INSTALL_PS1_URL} | iex } catch { [Console]::Error.WriteLine($_.Exception.Message); exit 1 }`
+}
+
/** Where grid's installer puts the binary on both platforms — the reason `gridBinaryPath` falls
* back to this directory when `~/.local/bin` is not on the daemon's PATH. */
export const GRID_INSTALL_DIR = join(homedir(), '.local', 'bin')
@@ -83,6 +94,8 @@ export interface GridInstallDeps {
enabled: boolean
/** Defaults to this machine's. Injected so the Windows branch is tested on any OS. */
platform?: NodeJS.Platform
+ /** Windows: runs the installer with this process's grid calls held back ([withGridCallsPaused] unless injected). */
+ pause?: <T>(install: () => Promise<T>) => Promise<T>
}
function capped(sofar: string, chunk: Buffer): string {
@@ -133,7 +146,20 @@ let inFlight: Promise<GridInstallResult> | null = null
*/
export function ensureGridInstalled(deps: GridInstallDeps = defaultGridInstallDeps): Promise<GridInstallResult> {
if (deps.available()) return Promise.resolve({ status: 'present', message: '`grid` is installed' })
+ return installGrid(null, deps)
+}
+
+/**
+ * Run grid's installer, whether or not `grid` is already there: the latest release, or — on Windows, where
+ * Harness follows its pin this way (`gridWindowsPin.ts`) — [version], over the grid already installed.
+ * Shares one in-flight run with [ensureGridInstalled].
+ */
+export function installGrid(version: string | null, deps: GridInstallDeps = defaultGridInstallDeps): Promise<GridInstallResult> {
if (!deps.enabled) return Promise.resolve({ status: 'skipped', message: 'grid install is switched off (DISABLE_GRID_INSTALL)' })
+ // It goes into a PowerShell line: a plain release number, nothing else.
+ if (version !== null && !isReleaseNumber(version)) {
+ return Promise.resolve({ status: 'skipped', message: `not a grid release number: ${JSON.stringify(version)}` })
+ }
const windows = (deps.platform ?? process.platform) === 'win32'
if (!windows && !deps.curlOnPath()) {
return Promise.resolve({ status: 'skipped', message: 'no `grid` on this machine and no `curl` to fetch its installer with — install it from ' + GRID_INSTALL_URL })
@@ -141,9 +167,12 @@ export function ensureGridInstalled(deps: GridInstallDeps = defaultGridInstallDe
if (inFlight) return inFlight
inFlight = (async (): Promise<GridInstallResult> => {
try {
- const script = windows ? `irm ${GRID_INSTALL_PS1_URL} | iex` : `curl -fsSL ${GRID_INSTALL_URL} | bash`
- const { exitCode, output } = await deps.run(script, INSTALL_TIMEOUT_MS)
- const tail = output.trim().split('\n').slice(-3).join(' · ').replace(/\[[0-9;]*m/g, '')
+ const script = windows ? windowsInstallScript(version) : `curl -fsSL ${GRID_INSTALL_URL} | bash`
+ // On Windows, with no grid call of this process running: a running grid makes install.ps1 refuse, and one
+ // started while it replaces files breaks the install (gridCalls.ts).
+ const run = () => deps.run(script, INSTALL_TIMEOUT_MS)
+ const { exitCode, output } = windows ? await (deps.pause ?? withGridCallsPaused)(run) : await run()
+ const tail = output.trim().split('\n').map((line) => line.trimEnd()).slice(-3).join(' · ').replace(/\[[0-9;]*m/g, '')
if (exitCode !== 0) {
return { status: 'failed', message: `grid installer exited ${exitCode}${tail ? ` · ${tail}` : ''}` }
}
diff --git a/cli/src/lib/gridWindowsPin.spec.ts b/cli/src/lib/gridWindowsPin.spec.ts
new file mode 100644
index 000000000..b5158d510
--- /dev/null
+++ b/cli/src/lib/gridWindowsPin.spec.ts
@@ -0,0 +1,75 @@
+/**
+ * The grid pin on Windows, where there is no managed grid build: grid's own installer lays the pinned release down.
+ */
+import { describe, expect, it, vi } from 'vitest'
+import { followWindowsGridPin, GRID_WINDOWS_VERSION_FLOOR, type WindowsGridPinDeps } from './gridWindowsPin.js'
+
+const PIN = '0.3.62'
+
+function manifest(entry: unknown): unknown {
+ return { grid: { 'darwin-arm64': { version: '0.3.59', url: 'https://example.test/grid.tar.gz' }, 'win32-x64': entry } }
+}
+
+function deps(overrides: Partial<WindowsGridPinDeps> = {}): WindowsGridPinDeps & { install: ReturnType<typeof vi.fn>; lines: string[] } {
+ const lines: string[] = []
+ return {
+ lines,
+ key: 'win32-x64',
+ manifest: async () => manifest({ version: PIN }),
+ installedVersion: async () => '0.3.61',
+ install: vi.fn(async () => ({ status: 'installed' as const, message: 'installed' })),
+ log: (line: string) => { lines.push(line) },
+ ...overrides,
+ } as WindowsGridPinDeps & { install: ReturnType<typeof vi.fn>; lines: string[] }
+}
+
+describe('followWindowsGridPin', () => {
+ it('installs the pinned version when the installed grid is another', async () => {
+ const d = deps()
+ await followWindowsGridPin(d)
+ expect(d.install.mock.calls).toEqual([[PIN]])
+ expect(d.lines.join('\n')).toContain(PIN)
+ })
+
+ it('does nothing when the installed grid is the pin', async () => {
+ const d = deps({ installedVersion: async () => PIN })
+ await followWindowsGridPin(d)
+ expect(d.install).not.toHaveBeenCalled()
+ expect(d.lines).toEqual([])
+ })
+
+ it('installs the pin on a machine with no grid', async () => {
+ const d = deps({ installedVersion: async () => null })
+ await followWindowsGridPin(d)
+ expect(d.install.mock.calls).toEqual([[PIN]])
+ })
+
+ it(`never follows a pin below ${GRID_WINDOWS_VERSION_FLOOR}, the first grid that runs on Windows as Harness drives it`, async () => {
+ const d = deps({ manifest: async () => manifest({ version: '0.3.59' }) })
+ await followWindowsGridPin(d)
+ expect(d.install).not.toHaveBeenCalled()
+ })
+
+ it('does nothing without an entry for this computer, or with a version that is not a plain release number', async () => {
+ for (const entry of [undefined, {}, { version: 7 }, { version: "0.3.62'; Remove-Item -Recurse ~; '" }, { version: '0.3.62-rc1' }]) {
+ const d = deps({ manifest: async () => manifest(entry) })
+ await followWindowsGridPin(d)
+ expect(d.install).not.toHaveBeenCalled()
+ }
+ })
+
+ it('does nothing on an unknown architecture, or when the manifest cannot be read', async () => {
+ const noKey = deps({ key: null })
+ await followWindowsGridPin(noKey)
+ const unreadable = deps({ manifest: async () => { throw new Error('offline') } })
+ await followWindowsGridPin(unreadable)
+ expect(noKey.install).not.toHaveBeenCalled()
+ expect(unreadable.install).not.toHaveBeenCalled()
+ })
+
+ it("logs the installer's own sentence when the install fails", async () => {
+ const d = deps({ install: vi.fn(async () => ({ status: 'failed' as const, message: 'grid installer exited 1 · grid is running' })) })
+ await followWindowsGridPin(d)
+ expect(d.lines.at(-1)).toBe('grid installer exited 1 · grid is running')
+ })
+})
diff --git a/cli/src/lib/gridWindowsPin.ts b/cli/src/lib/gridWindowsPin.ts
new file mode 100644
index 000000000..045287fab
--- /dev/null
+++ b/cli/src/lib/gridWindowsPin.ts
@@ -0,0 +1,41 @@
+/**
+ * The grid pin on Windows.
+ *
+ * On macOS and Linux the pin is a managed runtime: an archive Harness builds, downloads and points `current-grid` at
+ * (`ensureManagedGrid`, runtimeInstall.ts). Windows has no such build — an unsigned grid.exe is what Smart App Control
+ * blocks — so the manifest's `win32-*` entry carries a version only, and grid's own installer (`install.ps1`, the one
+ * that copes with Smart App Control) lays that release down in `%USERPROFILE%\.local\bin`. Before this, a Windows
+ * machine stayed on whatever release was latest the day grid was first installed there.
+ */
+import type { GridInstallResult } from './gridInstall.js'
+import { isReleaseNumber, meetsVersionFloor } from './gridExec.js'
+
+/** The first grid that runs on Windows as Harness drives it: `grid.cmd` where Smart App Control blocks `grid.exe`,
+ * and a `grid update` that leaves the install whole. A lower pin — the one for macOS and Linux may be — is not
+ * followed here. */
+export const GRID_WINDOWS_VERSION_FLOOR = '0.3.61'
+
+export interface WindowsGridPinDeps {
+ /** This computer's manifest key (`win32-x64`), or null on an architecture the manifest does not name. */
+ key: string | null
+ manifest: () => Promise<unknown>
+ /** What the installed grid says it is; null when there is none. */
+ installedVersion: () => Promise<string | null>
+ install: (version: string) => Promise<GridInstallResult>
+ log: (message: string) => void
+}
+
+/** Install the pinned grid when this computer runs another. Best-effort: every failure is a log line at most. */
+export async function followWindowsGridPin(deps: WindowsGridPinDeps): Promise<void> {
+ if (!deps.key) return
+ let document: unknown
+ try { document = await deps.manifest() } catch { return }
+ const entry = (document as Record<string, Record<string, { version?: unknown } | undefined> | undefined> | null)?.grid?.[deps.key]
+ const version = entry?.version
+ if (typeof version !== 'string' || !isReleaseNumber(version)) return
+ if (!meetsVersionFloor(version) || !meetsVersionFloor(version, GRID_WINDOWS_VERSION_FLOOR)) return
+ if (await deps.installedVersion() === version) return
+ deps.log(`▸ installing grid ${version}, the version Harness pins (grid's Windows installer)…`)
+ const result = await deps.install(version)
+ deps.log(result.status === 'installed' ? ` ✓ grid ${version} installed` : result.message)
+}
diff --git a/cli/src/lib/runtimeInstall.spec.ts b/cli/src/lib/runtimeInstall.spec.ts
index 2d2136920..8091f11bb 100644
--- a/cli/src/lib/runtimeInstall.spec.ts
+++ b/cli/src/lib/runtimeInstall.spec.ts
@@ -732,9 +732,14 @@ describe('the managed runtimes on Windows', () => {
expect(runtimeLayout('linux')).toEqual({ archiveSuffix: '.tar.gz', nodeBinary: join('bin', 'node'), eol: '\n' })
})
- it('installs no grid on Windows: nothing is fetched and nothing is laid down, even with a pointer left behind', async () => {
+ it('lays no managed grid down on Windows: only the manifest is read, for the version grid\'s installer lays down (gridWindowsPin.ts)', async () => {
installedGrid('0.3.47', 'win32-x64', true)
- const fetchSpy = vi.fn()
+ const before = readdirSync(runtimeDir).sort()
+ // An archive entry, as a mistaken publish could leave: still never downloaded. Its version is below Windows'
+ // floor, so no installer runs either.
+ const fetchSpy = vi.fn(async () => new Response(JSON.stringify({ grid: { 'win32-x64': {
+ version: '0.3.48', url: 'https://example.test/grid.tar.gz', sha256: 'x', archiveRoot: 'grid-0.3.48-win32-x64',
+ } } })))
vi.stubGlobal('fetch', fetchSpy)
const { ensureManagedGrid } = await load()
const platform = process.platform
@@ -744,6 +749,7 @@ describe('the managed runtimes on Windows', () => {
} finally {
Object.defineProperty(process, 'platform', { value: platform })
}
- expect(fetchSpy).not.toHaveBeenCalled()
+ expect(fetchSpy.mock.calls.map((call) => String((call as unknown[])[0]))).toEqual(['https://example.test/runtime/grid/metadata.json'])
+ expect(readdirSync(runtimeDir).sort()).toEqual(before)
})
})
diff --git a/cli/src/lib/runtimeInstall.ts b/cli/src/lib/runtimeInstall.ts
index 69cf3060f..59fc5b012 100644
--- a/cli/src/lib/runtimeInstall.ts
+++ b/cli/src/lib/runtimeInstall.ts
@@ -3,7 +3,9 @@ import { chmodSync, existsSync, mkdirSync, readdirSync, renameSync, rmSync, writ
import { dirname, join, sep, win32 } from 'node:path'
import { env } from '../config/env.js'
-import { gridChildEnv, managedGridPath, meetsVersionFloor } from './gridExec.js'
+import { gridAvailable, gridChildEnv, gridVersion, managedGridPath, meetsVersionFloor } from './gridExec.js'
+import { installGrid } from './gridInstall.js'
+import { followWindowsGridPin } from './gridWindowsPin.js'
import { managedNodePath } from './nodeRuntime.js'
import { RUNTIME_DOWNLOAD_LIMITS, downloadVerified } from './selfUpdate.js'
@@ -319,9 +321,23 @@ export async function ensureManagedRuntime(log: (message: string) => void = () =
* it outranks the pin at resolution, so a pin laid down under it would be work nobody asked for.
*/
export async function ensureManagedGrid(log: (message: string) => void = () => {}): Promise<string | null> {
- // Not on Windows (spec section 1): no grid is published for it, and an agent's pane there has no grid to run.
- if (process.platform === 'win32') return null
if (process.env.HARNESS_GRID_BIN?.trim()) return null
+ // No managed grid build on Windows: grid's own installer lays the pinned release down there, and there is no
+ // managed binary to return (gridWindowsPin.ts).
+ if (process.platform === 'win32') {
+ await followWindowsGridPin({
+ key: platformKey(),
+ manifest: async () => {
+ const response = await fetch(env.ADAPTER_GRID_RUNTIME_METADATA_URL)
+ if (!response.ok) throw new Error(`manifest answered ${response.status}`)
+ return response.json()
+ },
+ installedVersion: () => gridAvailable() ? gridVersion() : Promise.resolve(null),
+ install: (version) => installGrid(version),
+ log,
+ })
+ return null
+ }
return ensureManagedArchive({
name: 'grid',
label: 'grid',
diff --git a/cli/src/services/models.spec.ts b/cli/src/services/models.spec.ts
index 33ab0f9df..6a692f4ab 100644
--- a/cli/src/services/models.spec.ts
+++ b/cli/src/services/models.spec.ts
@@ -276,6 +276,22 @@ describe('the models service', () => {
vi.mocked(managedGridPath).mockReturnValue(null)
}
})
+
+ it('on Windows, which has no managed grid, follows the pin with the grid installed there — and installs none', async () => {
+ const platform = process.platform
+ Object.defineProperty(process, 'platform', { value: 'win32' })
+ try {
+ vi.mocked(gridAvailable).mockReturnValue(false)
+ setup()
+ expect(ensureManagedGrid).not.toHaveBeenCalled()
+ vi.mocked(gridAvailable).mockReturnValue(true)
+ await vi.mocked(startGridPinRecheck).mock.calls.at(-1)![0]!.ensure!()
+ expect(ensureManagedGrid).toHaveBeenCalledOnce()
+ } finally {
+ Object.defineProperty(process, 'platform', { value: platform })
+ vi.mocked(gridAvailable).mockReturnValue(true)
+ }
+ })
})
describe('its port', () => {
diff --git a/cli/src/services/models.ts b/cli/src/services/models.ts
index 164657799..cb9b4cf09 100644
--- a/cli/src/services/models.ts
+++ b/cli/src/services/models.ts
@@ -67,8 +67,9 @@ export function startModels(core: CoreApi, ports: CorePorts, swarm?: SwarmModels
// installed the first time a grid feature is used (`ensure`, below). Not awaited, and asynchronous
// throughout (`runtimeInstall.ts`): every grid call resolves the binary afresh (`gridBinaryPath`), so
// whatever lands is picked up as it lands. It keeps following it while this runs: a pin moved after
- // the start reaches it within ten minutes rather than at the next restart (`startGridPinRecheck`).
- const followGridPin = (): Promise<unknown> => managedGridPath()
+ // the start reaches it within ten minutes rather than at the next restart (`startGridPinRecheck`). Windows has no
+ // managed grid: there the grid installed already follows the pin (`lib/gridWindowsPin.ts`).
+ const followGridPin = (): Promise<unknown> => managedGridPath() || (process.platform === 'win32' && gridAvailable())
? ensureManagedGrid((m) => console.log(`[grid-runtime] ${m}`))
: Promise.resolve(null)
void followGridPin()
diff --git a/desktop/scripts/publish-managed-grid-runtime.sh b/desktop/scripts/publish-managed-grid-runtime.sh
index 51274ab88..d4986193c 100755
--- a/desktop/scripts/publish-managed-grid-runtime.sh
+++ b/desktop/scripts/publish-managed-grid-runtime.sh
@@ -65,6 +65,9 @@ GCS_BUCKET="${GCS_BUCKET:-s3-autonomous-upgrade-3}"
PUBLIC_BASE="${GCS_PUBLIC_BASE_URL:-https://storage.googleapis.com/${GCS_BUCKET}}"
METADATA_PATH="${METADATA_PATH:-harness/runtime/grid/metadata.json}"
PLATFORMS="${GRID_PLATFORMS:-darwin-arm64 darwin-x64 linux-x64 linux-arm64}"
+# Windows has no archive: its entry is the version alone, which the daemon there installs with grid's own
+# install.ps1 (cli/src/lib/gridWindowsPin.ts). GRID_WINDOWS_PLATFORMS="" publishes none.
+WINDOWS_PLATFORMS="${GRID_WINDOWS_PLATFORMS-win32-x64}"
WORK_DIR="$(mktemp -d)"
SRC="$WORK_DIR/metadata.json"
DST="$WORK_DIR/metadata.next.json"
@@ -103,8 +106,9 @@ if ! gcs_cp "gs://${GCS_BUCKET}/${METADATA_PATH}" "$SRC" 2>/dev/null; then
printf '{}' > "$SRC"
fi
+GRID_PIN_VERSION="$VERSION" GRID_WINDOWS_PLATFORMS="$WINDOWS_PLATFORMS" \
python3 - "$SRC" "$DST" "${PUBLIC_BASE%/}" "${ENTRIES[@]}" <<'PY'
-import json, sys
+import json, os, sys
src, dst, public_base, *entries = sys.argv[1:]
try:
with open(src) as f:
@@ -126,6 +130,8 @@ for entry in entries:
"size": int(size),
"archiveRoot": root,
}
+for platform in os.environ["GRID_WINDOWS_PLATFORMS"].split():
+ grid[platform] = {"version": os.environ["GRID_PIN_VERSION"]}
with open(dst, "w") as f:
json.dump(document, f, indent=2)
f.write("\n")
@@ -134,5 +140,5 @@ PY
gcs_cp "$DST" "gs://${GCS_BUCKET}/${METADATA_PATH}" \
'no-cache, no-store, must-revalidate' 'application/json'
-echo ">> published managed grid ${VERSION} for: ${PLATFORMS}"
+echo ">> published managed grid ${VERSION} for: ${PLATFORMS}${WINDOWS_PLATFORMS:+ (version only: ${WINDOWS_PLATFORMS})}"
echo ">> manifest: ${PUBLIC_BASE%/}/${METADATA_PATH}"