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: hold the daemon spawn lock through `harness login --force`
Kelvin192d0d0c5218
diff --git a/cli/README.md b/cli/README.mdindex 0765363d1..fc33c51f4 100644--- a/cli/README.md+++ b/cli/README.md@@ -74,6 +74,11 @@ harness logout # stop the adapter and clear this computer's SSO sessionbackend-resolved machine id are stored atomically with owner-only permissions in`~/.harness/auth/session.json`; the immutable computer id lives separately at`~/.harness/computer-id`. Later `harness start` invocations reuse and refresh that session as needed.+`login --force` holds the daemon's spawn lock from the moment it stops the old daemon until the new+session is on disk, so a `harness start` that lands while the browser is open (the desktop app runs+one whenever the daemon is down) waits its turn rather than bringing a daemon up on the account being+replaced. `harness start` beside a running daemon also asks it which machine it serves, and restarts+one that answers for another account instead of reporting it "already running".Raw daemon logs go to `${ADAPTER_DATA_DIR}/harness.log`.The log is **capped at 10 MB**: the daemon checks the size every minute and, over the cap, rewrites thediff --git a/cli/src/cli.ts b/cli/src/cli.tsindex b2a3d2e77..e759ccf76 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -51,7 +51,7 @@ import { PID_FILE, daemonPort, isAlive, isDaemonRunning, readPid } from './lib/dimport {BIND_WAIT_MS, connectFailure, defaultLaunchDeps, removePidFileIf, waitForBind, waitForReady,} from './lib/daemonLaunch.js'-import { SpawnLockBusyError, describeSpawnLockFailure, describeSpawnLockOwner, withSpawnLock } from './lib/daemonSpawnLock.js'+import { SpawnLockBusyError, describeSpawnLockBusyPlainly, describeSpawnLockFailure, describeSpawnLockOwner, withSpawnLock } from './lib/daemonSpawnLock.js'import { stopDaemonProcess } from './lib/daemonStop.js'import { ensureTmuxOnPath, requireTmuxAvailable } from './lib/tmuxOnPath.js'import { flashCommand } from './lib/flash.js'@@ -59,7 +59,7 @@ import { readOrMintComputerId } from './lib/computerIdentity.js'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 { ensureGridInstalled, type GridInstallResult } from './lib/gridInstall.js'import { ensureHarnessGrid, type EnsureStatus } from './lib/gridEnsure.js'import { passThroughToGridLogout } from './lib/gridLogout.js'import { clearGridMcpUrlCache } from './lib/gridMcpUrl.js'@@ -557,13 +557,20 @@ type SignInOutcome =** Returns what happened, so `--json` callers can carry it on their own result line.*/-async function attachGridToSignIn(token: string, json: boolean): Promise<Record<string, unknown>> {+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.- const install = await ensureGridInstalled()+ // 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 installingif (install.status === 'installed') note(install.message)else if (install.status !== 'present') note(install.message)const handoff = await handOffToGrid(token, { json: true })@@ -594,7 +601,9 @@ async function ensureAccountGrid(note: (line: string) => void): Promise<{ statuslet gridName: string | null = nulltry {const { headers } = await controlPlaneAuth()- gridName = (await postJson<{ gridName?: string }>('/api/grid/name', {}, headers)).gridName ?? null+ // Bounded like the daemon's own mint (reconcileGridAttach): a forced sign-in runs this under the+ // daemon spawn lock, and a stalled control-plane connection must not hold that lock open.+ gridName = (await postJson<{ gridName?: string }>('/api/grid/name', {}, headers, AbortSignal.timeout(GRID_MINT_TIMEOUT_MS))).gridName ?? null} catch (err) {note(`Could not read this account's grid name (${(err as Error).message}); skipping grid setup.`)return { status: 'skipped', name: null }@@ -614,13 +623,13 @@ async function loginCommand(): Promise<SignInOutcome> {if (foreground) throw new Error('`harness login` does not run the adapter. Use `harness start -f`.')const emit = (line: Record<string, unknown>): void => { if (json) console.log(JSON.stringify(line)) }- const succeed = async (alreadySignedIn: boolean): Promise<SignInOutcome> => {+ 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)+ 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.@@ -653,9 +662,60 @@ async function loginCommand(}return await succeed(true)}+ if (!force) return await browserSignIn(json, emit, () => succeed(false))// A forced login may intentionally switch SSO accounts. The old daemon must not keep streaming- // under its existing socket while this process replaces the durable session.- if (force) await stopDaemonProcess()+ // under its existing socket while this process replaces the durable session — and no NEW daemon+ // may come up on the old session in the meantime. The desktop app re-runs `harness start` whenever+ // the control port goes quiet, which it does the moment the old daemon is stopped, and that start+ // 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+ // 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 () => {+ await stopDaemonProcess()+ return await browserSignIn(json, emit, () => succeed(false, installing))+ }, {+ onWaiting: (owner) => console.error(` the daemon is ${describeSpawnLockOwner(owner)} — waiting for it to finish…`),+ })+ } catch (err) {+ if (!(err instanceof SpawnLockBusyError)) throw err+ // A holder that outlived the wait is not something a sign-in can override the way `stop` does:+ // signing in AROUND it is the race above. Say so and stop. The person gets what Harness is still+ // doing and what to do — the desktop shows `message` as is — and the pid and the lock go to+ // stderr, where a developer reads them (the desktop keeps that stream in its log).+ const message = describeSpawnLockBusyPlainly(err)+ const detail = `the daemon spawn lock is ${describeSpawnLockFailure(err)}`+ if (json) {+ emit({ type: 'result', status: 'error', code: 'DAEMON_BUSY', message })+ console.error(` ${detail}`)+ } else {+ console.error(`\n ✗ ${message}\n (${detail})\n`)+ }+ process.exitCode = 1+ return { signedIn: false }+ }+}++/**+ * The browser half of a sign-in: a loopback callback server, the SSO page, the code exchange, and+ * the new session — machine id included — on disk. Under --json every failure is a result line and+ * an exit code (`emit`); on the human path it is thrown. `succeed` finishes the job once the+ * session is on disk.+ */+async function browserSignIn(+ json: boolean,+ emit: (line: Record<string, unknown>) => void,+ succeed: () => Promise<SignInOutcome>,+): Promise<SignInOutcome> {const callback = createServer()await new Promise<void>((resolve, reject) => {callback.once('error', reject)@@ -744,7 +804,7 @@ async function loginCommand(if (json) { emit({ type: 'result', status: 'error', code: 'BACKEND_ERROR', message: (err as Error).message }); process.exitCode = 1; return { signedIn: false } }throw err}- return await succeed(false)+ return await succeed()} finally {await new Promise<void>((resolve) => callback.close(() => resolve()))}@@ -925,7 +985,8 @@ function openInBrowser(url: string): void {/** Start the adapter from a saved SSO session. Missing credentials never open a browser implicitly. */async function startCommand(foreground: boolean, repair: boolean = false): Promise<void> {- if (!readAuthSession()) {+ const session = readAuthSession()+ if (!session) {console.error('\n ✗ Not signed in. Run: harness login\n')process.exit(1)}@@ -949,13 +1010,23 @@ async function startCommand(foreground: boolean, repair: boolean = false): Promi// lock, for the daemon that comes up while we are waiting our turn.const running = readPid()if (running && isAlive(running)) {- // `--repair` still does its provisioning here: it touches the managed runtimes, never the- // bundle, and the live daemon picks a grid laid down now up on its next resolve (see- // repairManagedRuntimes). Without this, a new pin could only be followed by a restart.- if (repair) await repairManagedRuntimes(false)- console.log(`machine already running (pid ${running}) — it auto-reconnects.`)- console.log(' check: harness status · stop: harness stop · update now: harness update')- process.exit(0)+ // Left alone only when it serves THIS sign-in. A daemon on another account — what a forced+ // login left behind whenever a start landed while its browser was open — is stopped here and+ // started over on the session that is on disk: "already running" is exactly what kept it+ // there, with `auth status` naming the new machine and the socket serving the old one. Asked+ // of the daemon itself; one that cannot answer (still booting, mid-update) is trusted as before.+ const serving = (await runningDaemonStatus())?.machineId+ if (!serving || !session.machineId || serving === session.machineId) {+ // `--repair` still does its provisioning here: it touches the managed runtimes, never the+ // bundle, and the live daemon picks a grid laid down now up on its next resolve (see+ // repairManagedRuntimes). Without this, a new pin could only be followed by a restart.+ if (repair) await repairManagedRuntimes(false)+ console.log(`machine already running (pid ${running}) — it auto-reconnects.`)+ console.log(' check: harness status · stop: harness stop · update now: harness update')+ process.exit(0)+ }+ console.log(`machine running (pid ${running}) as another account — restarting it on this sign-in`)+ await stopDaemonProcess()}await withSpawnLock('start', async () => {const [v] = await Promise.all([@@ -5300,18 +5371,23 @@ async function runForeground(session: AuthSession): Promise<void> {* by `version v0.0.20`). Every other row here is a fact about the daemon (pid, sessions, dashboard); this* makes the version one too. Falls back to the local constant when the daemon cannot be reached, which is* exactly the case where the printing process IS the only build there is.+ *+ * `machineId` is the machine the daemon's backend socket is serving — fixed for its lifetime, so it is+ * the one fact that tells a daemon on THIS sign-in from one left over from the previous account (see+ * startCommand). Null when the daemon does not say.*/-async function runningDaemonStatus(): Promise<{ version: string; sessions: number } | null> {+async function runningDaemonStatus(): Promise<{ version: string; sessions: number; machineId: string | null } | null> {try {const res = await fetch(`http://127.0.0.1:${daemonPort()}/api/status`, {signal: AbortSignal.timeout(1_500),})if (!res.ok) return nullconst body: unknown = await res.json()- const status = body as { version?: unknown; sessions?: unknown } | null+ const status = body as { version?: unknown; sessions?: unknown; machineId?: unknown } | nullconst version = typeof status?.version === 'string' && status.version ? status.version : VERSIONconst sessions = Array.isArray(status?.sessions) ? status.sessions.length : 0- return { version, sessions }+ const machineId = typeof status?.machineId === 'string' && status.machineId ? status.machineId : null+ return { version, sessions, machineId }} catch {return null}diff --git a/cli/src/cliCommand.spec.ts b/cli/src/cliCommand.spec.tsindex 8ae53423a..65741d0be 100644--- a/cli/src/cliCommand.spec.ts+++ b/cli/src/cliCommand.spec.ts@@ -1,6 +1,6 @@-import { spawn, spawnSync } from 'child_process'-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'fs'-import { createServer } from 'node:http'+import { spawn, spawnSync, type ChildProcess } from 'child_process'+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'fs'+import { createServer, type Server } from 'node:http'import type { AddressInfo } from 'node:net'import { tmpdir } from 'os'import { join } from 'path'@@ -11,8 +11,19 @@ const CLI_ROOT = fileURLToPath(new URL('..', import.meta.url))const CLI_SOURCE = join(CLI_ROOT, 'src', 'cli.ts')const TSX = join(CLI_ROOT, 'node_modules', 'tsx', 'dist', 'cli.mjs')const dirs: string[] = []+const children: ChildProcess[] = []+const servers: Server[] = []-afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }) })+afterEach(async () => {+ for (const child of children.splice(0)) {+ if (child.exitCode === null && child.signalCode === null) child.kill('SIGKILL')+ }+ for (const server of servers.splice(0)) {+ server.closeAllConnections?.()+ await new Promise<void>((resolve) => server.close(() => resolve()))+ }+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true })+})/** A throwaway HOME for one CLI run; every path the CLI writes is under it. */function freshRoot(): string {@@ -30,6 +41,11 @@ function envFor(root: string, extra: NodeJS.ProcessEnv = {}): NodeJS.ProcessEnvADAPTER_CLI_DIR: join(root, 'cli'),ADAPTER_COMPUTER_ID_FILE: join(root, 'computer-id'),ADAPTER_UPDATE_DISABLE: 'true',+ // Nothing listens on port 1. A `start` asks the daemon on PORT which account it serves and would+ // otherwise ask this machine's REAL daemon — and the backend is where a start that decided to+ // (re)start goes next, which must never be the production one.+ PORT: '1',+ BACKEND_WS_URL: 'http://127.0.0.1:1',...extra,}}@@ -60,10 +76,26 @@ function seedSession(root: string): void {}))}-/** A daemon that is up, as `start` sees one: a pid file naming a live process — this one. */-function seedRunningDaemon(root: string): void {+/** A daemon that is up, as `start` sees one: a pid file naming a live process. A child that idles,+ * never this process — a `start` that finds the daemon on another account stops it. */+function seedRunningDaemon(root: string): { pid: number; exited: Promise<void> } {+ const child = spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], { stdio: 'ignore' })+ children.push(child)mkdirSync(join(root, 'data'), { recursive: true })- writeFileSync(join(root, 'data', 'adapter.pid'), `${process.pid}\n`)+ writeFileSync(join(root, 'data', 'adapter.pid'), `${child.pid}\n`)+ return { pid: child.pid ?? -1, exited: new Promise((resolve) => child.once('exit', () => resolve())) }+}++/** The one thing `start` asks a live daemon: GET /api/status, for the machine it serves. Bound to a+ * port of its own, which the test hands the CLI as PORT. */+async function daemonStatusServer(machineId: string): Promise<number> {+ const server = createServer((_req, res) => {+ res.setHeader('content-type', 'application/json')+ res.end(JSON.stringify({ machineId, version: '0.0.0-test', sessions: [] }))+ })+ servers.push(server)+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))+ return (server.address() as AddressInfo).port}describe('CLI login/start command contract', () => {@@ -152,3 +184,43 @@ describe('start --repair beside a running daemon', () => {expect(result.stdout).not.toContain('installing the Harness grid runtime')}, 20_000)})++describe('start beside a daemon that serves another account', () => {+ // A forced login stops the daemon and waits for the browser, and a start that landed in that window+ // used to bring a daemon up on the OLD session (closed under the spawn lock now — loginForceRace.spec.ts).+ // "Already running" is what kept it there: `auth status` named the new machine, the socket served the+ // old one. However a daemon ends up on the wrong account, this is where it is noticed — `start` asks+ // the live daemon which machine it serves before leaving it alone.++ it('stops it and starts over on the session that is on disk', async () => {+ const root = freshRoot()+ seedSession(root) // machineId m_seeded+ const daemon = seedRunningDaemon(root)+ const port = await daemonStatusServer('m_other')++ const result = await runAsync(root, ['start'], { PORT: String(port) })++ expect(result.stdout).toContain(`machine running (pid ${daemon.pid}) as another account — restarting it`)+ expect(result.stdout).not.toContain('already running')+ await daemon.exited+ expect(existsSync(join(root, 'data', 'adapter.pid'))).toBe(false)+ // The restart itself goes on to resolve this session's machine with the backend, which is refused+ // here (port 1) — past the point under test, and the one place a repo run could boot a daemon.+ expect(result.status).toBe(1)+ }, 20_000)++ it('leaves one that serves this session alone', async () => {+ const root = freshRoot()+ seedSession(root)+ const daemon = seedRunningDaemon(root)+ const port = await daemonStatusServer('m_seeded')++ const result = await runAsync(root, ['start'], { PORT: String(port) })++ expect(result.status).toBe(0)+ expect(result.stdout).toContain('already running')+ expect(existsSync(join(root, 'data', 'adapter.pid'))).toBe(true)+ await expect(Promise.race([daemon.exited.then(() => 'exited'), new Promise((r) => setTimeout(() => r('alive'), 300))]))+ .resolves.toBe('alive')+ }, 20_000)+})diff --git a/cli/src/lib/daemonSpawnLock.spec.ts b/cli/src/lib/daemonSpawnLock.spec.tsindex c5833ea01..0a5fad38e 100644--- a/cli/src/lib/daemonSpawnLock.spec.ts+++ b/cli/src/lib/daemonSpawnLock.spec.ts@@ -172,6 +172,24 @@ describe('daemon spawn lock', () => {expect(lock.describeSpawnLockFailure(new lock.SpawnLockBusyError(null, 'why'))).toBe('why')})+ it('tells a person what Harness is still doing, without a pid or a lock in the sentence', async () => {+ // The desktop's sign-in screen shows this verbatim: the technical line is for stderr.+ const lock = await loadLock()+ const busy = (purpose: 'start' | 'update' | 'handoff' | 'stop' | 'login') =>+ new lock.SpawnLockBusyError({ pid: 4242, startMarker: '', token: 't', purpose, since: Date.now() })+ expect(lock.describeSpawnLockBusyPlainly(busy('update'))).toBe('Harness is still updating on this computer. Try again in a moment.')+ expect(lock.describeSpawnLockBusyPlainly(busy('login'))).toBe('Another sign-in is already in progress on this computer. Try again in a moment.')+ for (const purpose of ['start', 'handoff', 'stop'] as const) {+ const said = lock.describeSpawnLockBusyPlainly(busy(purpose))+ expect(said).toMatch(/^Harness is still .* on this computer\. Try again in a moment\.$/)+ expect(said).not.toMatch(/4242|lock|pid/)+ }+ expect(lock.describeSpawnLockBusyPlainly(new lock.SpawnLockBusyError(null))).toBe('Harness is busy on this computer. Try again in a moment.')+ // Not a lock at all is not going to clear itself: no "try again", a terminal instead.+ expect(lock.describeSpawnLockBusyPlainly(new lock.SpawnLockBusyError(null, 'not a lock this CLI made: /x — remove it by hand')))+ .toBe('Harness cannot sign in on this computer right now. Run `harness login --force` in a terminal to see why.')+ })+it('serializes two real spawners racing for the lock', async () => {// Each child takes the lock, appends "<pid> in", sleeps, appends "<pid> out". Serialized, the// trace is in/out/in/out; a broken lock interleaves in/in.diff --git a/cli/src/lib/daemonSpawnLock.ts b/cli/src/lib/daemonSpawnLock.tsindex 4bd506e1c..ef950f04d 100644--- a/cli/src/lib/daemonSpawnLock.ts+++ b/cli/src/lib/daemonSpawnLock.ts@@ -41,7 +41,9 @@ import { env } from '../config/env.js'import { lockOwnerAlive, processStartMarker } from './processLiveness.js'import { secureStateDirectory } from './secureState.js'-export type SpawnLockPurpose = 'start' | 'update' | 'handoff' | 'stop'+/** `login` is a forced sign-in: the daemon is stopped and the session on disk is about to change+ * hands, so nothing may start a daemon — on the OLD session — until the new one is written. */+export type SpawnLockPurpose = 'start' | 'update' | 'handoff' | 'stop' | 'login'export interface SpawnLockOwner {pid: number@@ -85,11 +87,31 @@ export function describeSpawnLockFailure(error: unknown): string {export function describeSpawnLockOwner(owner: SpawnLockOwner): string {const verb: Record<SpawnLockPurpose, string> = {start: 'being started', update: 'being updated', handoff: 'restarting for an update', stop: 'being stopped',+ login: 'being signed in',}const secs = Math.max(0, Math.round((Date.now() - owner.since) / 1000))return `${verb[owner.purpose]} by pid ${owner.pid} for ${secs}s`}+/**+ * The same failure for a person who is not debugging anything — the desktop's sign-in screen shows+ * this verbatim. No pid, no lock, no seconds: what Harness is still doing on this computer, so that+ * "try again in a moment" reads as advice rather than a shrug. Something that is not a lock at the+ * lock path is not going to clear itself; that case sends them to the terminal, where the technical+ * line (`describeSpawnLockFailure`) says what to remove.+ */+export function describeSpawnLockBusyPlainly(error: SpawnLockBusyError): string {+ if (error.reason) return 'Harness cannot sign in on this computer right now. Run `harness login --force` in a terminal to see why.'+ const still: Record<SpawnLockPurpose, string> = {+ start: 'Harness is still starting on this computer',+ update: 'Harness is still updating on this computer',+ handoff: 'Harness is still restarting on this computer',+ stop: 'Harness is still shutting down on this computer',+ login: 'Another sign-in is already in progress on this computer',+ }+ return `${error.owner ? still[error.owner.purpose] : 'Harness is busy on this computer'}. Try again in a moment.`+}+let held: { token: string; purpose: SpawnLockPurpose; depth: number } | null = nulllet exitHookInstalled = false@@ -132,7 +154,7 @@ export function readSpawnLockOwner(): SpawnLockOwner | null {}function isPurpose(value: unknown): value is SpawnLockPurpose {- return value === 'start' || value === 'update' || value === 'handoff' || value === 'stop'+ return value === 'start' || value === 'update' || value === 'handoff' || value === 'stop' || value === 'login'}/** Create the lock for this process. Returns the token, or null when someone else holds it. */diff --git a/cli/src/loginForceRace.spec.ts b/cli/src/loginForceRace.spec.tsnew file mode 100644index 000000000..b8494d37b--- /dev/null+++ b/cli/src/loginForceRace.spec.ts@@ -0,0 +1,215 @@+/**+ * `harness login --force` beside a `harness start` — the desktop's daemon supervisor, in practice.+ *+ * A forced login stops the daemon and then waits, for as long as the person takes in the browser,+ * before it puts the new session on disk. The desktop app re-runs `harness start` whenever the+ * control port goes quiet, and `start` reads whatever session is on disk — for the whole of that+ * wait, the OLD account's. The daemon it spawned came up on the old account and stayed: the+ * `harness start` the login recommends afterwards found it "already running", `auth status` named+ * the new machine, the socket served the old one, and every local RPC got 4404 NO_PEER_LINK.+ *+ * Process-boundary tests, in the shape of cliCommand.spec.ts: a real `harness login --force --json`,+ * a real `harness start` landing mid-wait, a fake backend that records the token every call+ * carried, and a stand-in daemon (a child that idles until it is stopped) for the stop to kill.+ */+import { spawn, type ChildProcess } from 'child_process'+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs'+import { createServer, type IncomingMessage, type Server } from 'http'+import type { AddressInfo } from 'net'+import { tmpdir } from 'os'+import { join } from 'path'+import { fileURLToPath } from 'url'+import { afterEach, describe, expect, it } from 'vitest'++const CLI_ROOT = fileURLToPath(new URL('..', import.meta.url))+const CLI_SOURCE = join(CLI_ROOT, 'src', 'cli.ts')+const TSX = join(CLI_ROOT, 'node_modules', 'tsx', 'dist', 'cli.mjs')+const dirs: string[] = []+const servers: Server[] = []+const children: ChildProcess[] = []++afterEach(async () => {+ for (const child of children.splice(0)) {+ if (child.exitCode === null && child.signalCode === null) child.kill('SIGKILL')+ }+ for (const server of servers.splice(0)) {+ // close() only stops NEW connections; the CLI's fetch keeps a pooled socket open.+ server.closeAllConnections?.()+ await new Promise<void>((resolve) => server.close(() => resolve()))+ }+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true })+})++/** A throwaway HOME for one scenario; every path the CLI writes is under it. */+function tempRoot(): string {+ const root = mkdtempSync(join(tmpdir(), 'harness-login-race-'))+ dirs.push(root)+ return root+}++function envFor(root: string, backendBase: string): NodeJS.ProcessEnv {+ return {+ ...process.env,+ HOME: root,+ HARNESS_AUTH_DIR: join(root, 'auth'),+ ADAPTER_DATA_DIR: join(root, 'data'),+ ADAPTER_CLI_DIR: join(root, 'cli'),+ ADAPTER_COMPUTER_ID_FILE: join(root, 'computer-id'),+ ADAPTER_UPDATE_DISABLE: 'true',+ BACKEND_WS_URL: backendBase,+ // The daemon's control port. Nothing listens on 1, so a `start` in here can never take this+ // machine's real daemon for the one under test.+ PORT: '1',+ // The sign-in's grid half: no installer, no binary — it reports a missing `grid` and moves on,+ // rather than handing a made-up token to whatever `grid` this machine has on PATH.+ DISABLE_GRID_INSTALL: 'true',+ HARNESS_GRID_BIN: join(root, 'no-grid'),+ }+}++function seedSession(root: string, account: { accessToken: string; machineId: string }): void {+ mkdirSync(join(root, 'auth'), { recursive: true })+ writeFileSync(join(root, 'auth', 'session.json'), JSON.stringify({+ version: 1, refreshToken: 'refresh', expiresAt: Date.now() + 3_600_000,+ autonomousEnv: 'prod', computerId: 'a'.repeat(32), updatedAt: Date.now(), ...account,+ }))+}++/** A daemon as `login --force` and `start` see one: a live process named by the pid file. It idles+ * until it is stopped, which is all a stand-in has to do — the stop needs something to kill. */+function idleDaemon(root: string): { pid: number; exited: Promise<void> } {+ const child = spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], { stdio: 'ignore' })+ children.push(child)+ mkdirSync(join(root, 'data'), { recursive: true })+ writeFileSync(join(root, 'data', 'adapter.pid'), `${child.pid}\n`)+ return { pid: child.pid ?? -1, exited: new Promise((resolve) => child.once('exit', () => resolve())) }+}++interface CliRun {+ stdout: () => string+ /** Exit status, once every stdio pipe has drained. */+ exit: Promise<number | null>+ /** Resolves once stdout satisfies `test`; rejects if the process ends without it ever doing so. */+ until: (test: (stdout: string) => boolean) => Promise<void>+}++function runCli(root: string, args: string[], backendBase: string): CliRun {+ const child = spawn(process.execPath, [TSX, CLI_SOURCE, ...args], {+ cwd: CLI_ROOT, env: envFor(root, backendBase), stdio: ['ignore', 'pipe', 'pipe'],+ })+ children.push(child)+ let stdout = ''+ const watchers = new Set<() => void>()+ child.stdout.on('data', (chunk: Buffer) => {+ stdout += chunk.toString()+ for (const watch of [...watchers]) watch()+ })+ child.stderr.on('data', () => { /* drained: a full pipe would stall the child */ })+ const exit = new Promise<number | null>((resolve) => child.once('close', (code) => resolve(code)))+ return {+ stdout: () => stdout,+ exit,+ until: (test) => new Promise((resolve, reject) => {+ const watch = (): void => {+ if (!test(stdout)) return+ watchers.delete(watch)+ resolve()+ }+ watchers.add(watch)+ watch()+ void exit.then(() => {+ if (!watchers.delete(watch)) return+ reject(new Error(`\`harness ${args.join(' ')}\` ended before its stdout matched:\n${stdout}`))+ })+ }),+ }+}++interface BackendCall { path: string; bearer: string | undefined }+type BackendAnswer = { data: unknown } | { status: number; error: string }++/** The three control-plane calls a sign-in and a start make, answered by `answer`, and every call's+ * path and bearer token kept — which session a process acted on is the token it presented. */+function fakeBackend(+ answer: (req: IncomingMessage, body: Record<string, unknown>) => BackendAnswer,+): Promise<{ base: string; calls: BackendCall[] }> {+ const calls: BackendCall[] = []+ return new Promise((resolve) => {+ const server = createServer((req, res) => {+ let raw = ''+ req.on('data', (chunk) => { raw += chunk })+ req.on('end', () => {+ calls.push({ path: req.url ?? '', bearer: req.headers.authorization })+ const out = answer(req, raw ? JSON.parse(raw) as Record<string, unknown> : {})+ if ('data' in out) {+ res.writeHead(200, { 'content-type': 'application/json' })+ res.end(JSON.stringify({ success: true, data: out.data }))+ return+ }+ res.writeHead(out.status, { 'content-type': 'application/json' })+ res.end(JSON.stringify({ success: false, error: { message: out.error } }))+ })+ })+ servers.push(server)+ server.listen(0, '127.0.0.1', () => {+ resolve({ base: `http://127.0.0.1:${(server.address() as AddressInfo).port}`, calls })+ })+ })+}++describe('login --force beside a start that lands mid-sign-in', () => {+ it('never lets the start act on the account the login is replacing', async () => {+ const root = tempRoot()+ seedSession(root, { accessToken: 'tok_old', machineId: 'm_old' })+ const daemon = idleDaemon(root)+ let redirectUri = ''+ let resolvedForNew = 0+ const backend = await fakeBackend((req, body) => {+ switch (req.url) {+ case '/api/auth/authorize-native':+ redirectUri = String(body.redirectUri)+ return { data: { authorizeUrl: 'https://sso.example.test/authorize?tx=t', tx: 't' } }+ case '/api/auth/exchange':+ return { data: { token: 'tok_new', refreshToken: 'refresh_new', expiresIn: 3600, autonomousEnv: 'prod' } }+ case '/api/machines/resolve-computer':+ // The login's own resolve — the first to carry the new token — is answered. Every other+ // resolve is refused: a `start` that got past it would boot a daemon inside this test+ // (a repo run has no bundle to spawn, so it runs the daemon inline), and which session it+ // acted on is already on record in the token it presented.+ if (req.headers.authorization === 'Bearer tok_new' && resolvedForNew++ === 0) {+ return { data: { machine: { machineId: 'm_new' } } }+ }+ return { status: 503, error: 'no daemon in this test' }+ default:+ return { status: 404, error: 'not stubbed' }+ }+ })++ const login = runCli(root, ['login', '--force', '--json'], backend.base)+ await login.until((out) => out.includes('"authorize_url"'))+ // The browser is "open": the old daemon is gone and the session on disk is still the old account.+ await daemon.exited++ // The desktop supervisor sees a quiet control port and runs `harness start`. Let it get as far+ // as it will — to the backend and out (the bug), or to the spawn lock (the fix) — before the+ // person finishes in the browser.+ const start = runCli(root, ['start'], backend.base)+ await Promise.race([start.exit, start.until((out) => out.includes('waiting for it to finish'))])+ await fetch(`${redirectUri}?code=code_1&state=state_1`)++ expect(await login.exit).toBe(0)+ await start.exit++ // Nothing acted on the old account once its daemon was stopped: the start resolved its machine+ // with the NEW session or not at all.+ const resolves = backend.calls.filter((call) => call.path === '/api/machines/resolve-computer')+ expect(resolves.map((call) => call.bearer)).not.toContain('Bearer tok_old')+ expect(start.stdout()).toContain('the daemon is being signed in')+ // The login's pinned contract holds: exactly one result line, and a success.+ const results = login.stdout().trim().split('\n').map((line) => JSON.parse(line) as { type: string })+ .filter((line) => line.type === 'result')+ expect(results).toEqual([expect.objectContaining({ type: 'result', status: 'success' })])+ expect(JSON.parse(readFileSync(join(root, 'auth', 'session.json'), 'utf8')))+ .toMatchObject({ accessToken: 'tok_new', machineId: 'm_new' })+ }, 30_000)+})