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.

fix: a phone sign-in shows its QR over the desk, and a left-behind one stops

0xken154dd1a7cca7ad
diff --git a/cli/scripts/remote-machine.sh b/cli/scripts/remote-machine.sh
index 5a7f4a5c7..06decf35b 100755
--- a/cli/scripts/remote-machine.sh
+++ b/cli/scripts/remote-machine.sh
@@ -150,7 +150,7 @@ cmd_login() {
"socat TCP-LISTEN:${LOGIN_PORT},bind=\$(hostname -i),fork,reuseaddr TCP:127.0.0.1:${LOGIN_PORT}"
note "signing the box in — approve the URL below, then come back"
- docker exec -i "$CONTAINER" harness login --json | node -e '
+ docker exec "$CONTAINER" harness login --json | node -e '
const rl = require("readline").createInterface({ input: process.stdin })
rl.on("line", (line) => {
let e; try { e = JSON.parse(line) } catch { return }
diff --git a/cli/src/authCommand.spec.ts b/cli/src/authCommand.spec.ts
index 4c7299daf..6009e0eb1 100644
--- a/cli/src/authCommand.spec.ts
+++ b/cli/src/authCommand.spec.ts
@@ -1,6 +1,6 @@
import { spawn, spawnSync } from 'child_process'
import { createServer, type Server } from 'http'
-import { existsSync, mkdtempSync, rmSync, writeFileSync, mkdirSync } from 'fs'
+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync, mkdirSync } from 'fs'
import { tmpdir } from 'os'
import { join } from 'path'
import { fileURLToPath } from 'url'
@@ -91,25 +91,33 @@ function runAsync(root: string, args: string[], backendUrl?: string): Promise<{
}
/** A minimal fake backend for the two `/api/auth/*` + resolve-computer calls `harness login`/
- * `auth status` make — real network shape, canned answers, so the CLI's own code runs unmodified. */
+ * `auth status` make — real network shape, canned answers, so the CLI's own code runs unmodified.
+ * `routes` stubs any other path (the QR sign-in's `/api/auth/qr/*`). A handler may answer with a
+ * promise, so a test can hold a step open. `calls` records every request in arrival order. */
function fakeBackend(handlers: {
authorizeNative?: (body: any) => any
exchange?: (body: any) => any
resolveComputer?: (body: any) => any
-}): Promise<{ server: Server; base: string }> {
+ routes?: Record<string, (body: any) => unknown | Promise<unknown>>
+}): Promise<{ server: Server; base: string; calls: Array<{ url: string; body: unknown }> }> {
+ const calls: Array<{ url: string; body: unknown }> = []
return new Promise((resolve) => {
const server = createServer((req, res) => {
let raw = ''
req.on('data', (c) => { raw += c })
req.on('end', () => {
const body = raw ? JSON.parse(raw) : {}
+ calls.push({ url: req.url ?? '', body })
const send = (data: unknown): void => {
res.writeHead(200, { 'content-type': 'application/json' })
res.end(JSON.stringify({ success: true, data }))
}
- 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 }
+ const answer = (h: (body: any) => unknown): void => { void Promise.resolve(h(body)).then(send) }
+ if (req.url === '/api/auth/authorize-native' && handlers.authorizeNative) { answer(handlers.authorizeNative); return }
+ if (req.url === '/api/auth/exchange' && handlers.exchange) { answer(handlers.exchange); return }
+ if (req.url === '/api/machines/resolve-computer' && handlers.resolveComputer) { answer(handlers.resolveComputer); return }
+ const route = req.url ? handlers.routes?.[req.url] : undefined
+ if (route) { answer(route); return }
res.writeHead(404, { 'content-type': 'application/json' })
res.end(JSON.stringify({ success: false, error: { message: 'not stubbed' } }))
})
@@ -118,11 +126,16 @@ function fakeBackend(handlers: {
server.listen(0, '127.0.0.1', () => {
const address = server.address()
const port = typeof address === 'object' && address ? address.port : 0
- resolve({ server, base: `http://127.0.0.1:${port}` })
+ resolve({ server, base: `http://127.0.0.1:${port}`, calls })
})
})
}
+/** Resolves [value] after [ms] — a backend step that takes a moment, so a test can act inside it. */
+function later<T>(ms: number, value: T): Promise<T> {
+ return new Promise((resolve) => setTimeout(() => resolve(value), ms))
+}
+
describe('harness auth status --json', () => {
it('reports loggedIn:false with no saved session, and never touches the network', () => {
const root = tempRoot()
@@ -169,7 +182,133 @@ describe('harness auth status --json', () => {
})
})
+/** A `harness … --json` child driven the way the desktop app drives it: stdin left open (closing it is
+ * the app going away), stdout read one JSON line at a time. */
+function jsonChild(root: string, backendUrl: string, args: string[]) {
+ const child = spawn(process.execPath, [TSX, CLI_SOURCE, ...args], { cwd: CLI_ROOT, env: envFor(root, backendUrl) })
+ const lines: Record<string, unknown>[] = []
+ const waiters: Array<(line: Record<string, unknown>) => void> = []
+ let buffer = ''
+ child.stdout.on('data', (chunk: Buffer) => {
+ buffer += chunk.toString()
+ while (buffer.includes('\n')) {
+ const idx = buffer.indexOf('\n')
+ const line = buffer.slice(0, idx).trim()
+ buffer = buffer.slice(idx + 1)
+ if (!line) continue
+ const parsed = JSON.parse(line) as Record<string, unknown>
+ const waiter = waiters.shift()
+ if (waiter) waiter(parsed)
+ else lines.push(parsed)
+ }
+ })
+ const exit = new Promise<number | null>((resolve) => child.once('exit', resolve))
+ // 'exit' can beat the last of stdout; 'close' is when every line is in.
+ const closed = new Promise<void>((resolve) => child.once('close', () => resolve()))
+ return {
+ child,
+ exit,
+ next: (): Promise<Record<string, unknown>> => {
+ const queued = lines.shift()
+ return queued ? Promise.resolve(queued) : new Promise((resolve) => waiters.push(resolve))
+ },
+ /** Every line not yet taken by `next`, once the child's output has ended. */
+ rest: async (): Promise<Record<string, unknown>[]> => { await closed; return lines.splice(0) },
+ }
+}
+
describe('harness login --json', () => {
+ it('a sign-in whose app has gone stops and frees the lock; the one waiting on it says so, then goes on', async () => {
+ const root = tempRoot()
+ const { base } = await fakeBackend({
+ authorizeNative: () => ({ authorizeUrl: 'https://sso.example.test/authorize?tx=abc', tx: 'tx_abc' }),
+ })
+ const first = jsonChild(root, base, ['login', '--force', '--json'])
+ expect(await first.next()).toMatchObject({ type: 'authorize_url' })
+ // A second sign-in while the first waits on its browser: it waits on the spawn lock, and says so
+ // where the app reads — not only on stderr, which left a sign-in screen blank (2026-10-01).
+ const second = jsonChild(root, base, ['login', '--force', '--json'])
+ expect(await second.next()).toEqual({ type: 'waiting', message: expect.stringContaining('Another sign-in') })
+ // The first one's app goes away (quit, restart): its end of stdin closes, and the sign-in stops.
+ first.child.stdin.end()
+ expect(await first.next()).toMatchObject({ type: 'result', status: 'error', code: 'CANCELLED' })
+ expect(await first.exit).toBe(1)
+ expect(await second.next()).toMatchObject({ type: 'authorize_url' })
+ second.child.kill()
+ await second.exit
+ }, 30_000)
+
+ /** The QR backend for a sign-in that waits on a phone which never answers. */
+ const pendingQr = () => ({
+ '/api/auth/qr/start': () => ({ code: 'hnq_x', pollToken: 'hnp_poll', expiresIn: 120 }),
+ '/api/auth/qr/poll': () => ({ status: 'pending' }),
+ '/api/auth/qr/cancel': () => ({ cancelled: true }),
+ })
+
+ it('a QR sign-in whose app goes away while it waits on the phone says CANCELLED and takes its code back', async () => {
+ // Left running, the code would stay scannable on a screen nobody is watching, and the sign-in
+ // would hold the spawn lock for minutes.
+ const root = tempRoot()
+ const { base, calls } = await fakeBackend({ routes: pendingQr() })
+ const login = jsonChild(root, base, ['login', '--force', '--qr', '--json'])
+ expect(await login.next()).toMatchObject({ type: 'qr' })
+ login.child.stdin.end()
+ expect(await login.next()).toMatchObject({ type: 'result', status: 'error', code: 'CANCELLED' })
+ expect(await login.exit).toBe(1)
+ expect(calls).toContainEqual({ url: '/api/auth/qr/cancel', body: { pollToken: 'hnp_poll' } })
+ }, 30_000)
+
+ it('a QR sign-in stopped by SIGTERM while it waits on the phone takes its code back', async () => {
+ // The app's Cancel and its quit both send SIGTERM; the code must not outlive either.
+ const root = tempRoot()
+ const { base, calls } = await fakeBackend({ routes: pendingQr() })
+ const login = jsonChild(root, base, ['login', '--force', '--qr', '--json'])
+ expect(await login.next()).toMatchObject({ type: 'qr' })
+ login.child.kill('SIGTERM')
+ expect(await login.exit).toBe(1)
+ expect(calls).toContainEqual({ url: '/api/auth/qr/cancel', body: { pollToken: 'hnp_poll' } })
+ }, 30_000)
+
+ it('a QR sign-in the person said yes to finishes though its app goes away right after', async () => {
+ // Once the person has said yes the sign-in is theirs: the session write is quick, and taking the
+ // code back then would race its claim and leave them signed out for no reason.
+ const root = tempRoot()
+ const { base, calls } = await fakeBackend({
+ routes: {
+ '/api/auth/qr/start': () => ({ code: 'hnq_x', pollToken: 'hnp_poll', expiresIn: 120 }),
+ '/api/auth/qr/poll': () => ({ status: 'approved', email: '[email protected]' }),
+ '/api/auth/qr/claim': () => ({ token: 'tok_qr', refreshToken: 'r', expiresIn: 3600, email: '[email protected]' }),
+ '/api/auth/qr/cancel': () => ({ cancelled: true }),
+ },
+ // Held open so the app's pipe has closed well before the sign-in is done.
+ resolveComputer: () => later(500, { machine: { machineId: 'm_qr' } }),
+ })
+ const login = jsonChild(root, base, ['login', '--force', '--qr', '--json'])
+ expect(await login.next()).toMatchObject({ type: 'qr' })
+ expect(await login.next()).toEqual({ type: 'confirm', email: '[email protected]' })
+ login.child.stdin.end('yes\n')
+ expect(await login.next()).toEqual({ type: 'result', status: 'success', email: '[email protected]' })
+ expect(await login.exit).toBe(0)
+ const session = JSON.parse(readFileSync(join(root, 'auth', 'session.json'), 'utf8')) as Record<string, unknown>
+ expect(session).toMatchObject({ accessToken: 'tok_qr', method: 'qr' })
+ expect(calls.map((c) => c.url)).not.toContain('/api/auth/qr/cancel')
+ }, 30_000)
+
+ it('already signed in, an app that closes its pipe at once still gets the one success line', async () => {
+ // Nothing waits on a person here, so the app going away is no reason to stop: the answer it
+ // asked for is already on its way, and a CANCELLED here would read as a failed sign-in.
+ const root = tempRoot()
+ seedSession(root)
+ const { base } = await fakeBackend({
+ resolveComputer: () => later(500, { machine: { machineId: 'm_seeded' } }),
+ })
+ const login = jsonChild(root, base, ['login', '--json'])
+ login.child.stdin.end()
+ expect(await login.next()).toEqual({ type: 'result', status: 'success', alreadySignedIn: true })
+ expect(await login.exit).toBe(0)
+ expect(await login.rest()).toEqual([])
+ }, 15_000)
+
it('already-signed-in short-circuit emits a single success result line', async () => {
const root = tempRoot()
seedSession(root)
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index 9587ca703..099ede608 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -59,7 +59,7 @@ import { awakeTimeout } from './lib/sleepAware.js'
import {
BIND_WAIT_MS, connectFailure, defaultLaunchDeps, removePidFileIf, waitForBind, waitForReady,
} from './lib/daemonLaunch.js'
-import { SpawnLockBusyError, describeSpawnLockBusyPlainly, describeSpawnLockFailure, describeSpawnLockOwner, withSpawnLock } from './lib/daemonSpawnLock.js'
+import { SpawnLockBusyError, describeSpawnLockBusyPlainly, describeSpawnLockFailure, describeSpawnLockOwner, describeSpawnLockWaitPlainly, withSpawnLock } from './lib/daemonSpawnLock.js'
import { stopDaemonProcess } from './lib/daemonStop.js'
import { ensureTmuxOnPath } from './lib/tmuxOnPath.js'
import { flashCommand } from './lib/flash.js'
@@ -72,6 +72,7 @@ import { DAEMONS_OFF, DAEMONS_OFF_DETAIL, DaemonsSwitch, localKillSwitch, zooPas
import { handOffToGrid } from './lib/gridHandoff.js'
import { qrSignIn } from './lib/qrSignIn.js'
import { pickSignInMethod } from './lib/signInMethodPicker.js'
+import { watchJsonDriver, type JsonDriver } from './lib/jsonDriver.js'
import { terminalQr } from './lib/terminalQr.js'
import { ensureGridInstalled } from './lib/gridInstall.js'
import { ensureHarnessGrid, type EnsureStatus } from './lib/gridEnsure.js'
@@ -737,6 +738,16 @@ type SignInOutcome =
/** Refused. Under `--json` its own coded result line has already been emitted. */
| { signedIn: false }
+/** What the `--json` client and the sign-in itself tell each other beyond the result line. */
+interface SignInHooks {
+ /** The --json client's answers. */
+ driver?: JsonDriver | null
+ /** The QR exists: how to take it back. */
+ onStarted?: (cancel: () => Promise<void>) => void
+ /** The person said yes / the browser came back: finish the sign-in, do not abandon it. */
+ onCommitted?: () => void
+}
+
/**
* The account's private grid exists — its name minted or read, then the grid itself created if it is
* not there yet.
@@ -780,7 +791,10 @@ async function loginCommand(
// Which surface asked to sign in. A person in a terminal is `cli`; the desktop app runs this same
// command and says so with `--entry-point=desktop`. Analytics only — it names no privilege.
const entryPoint = opts.entryPoint ?? 'cli'
- const emit = (line: Record<string, unknown>): void => { if (json) console.log(JSON.stringify(line)) }
+ // Once the sign-in has been abandoned nothing more is written: the reader is gone, and a late line
+ // would only meet a closed pipe.
+ let abandoned = false
+ const emit = (line: Record<string, unknown>): void => { if (json && !abandoned) console.log(JSON.stringify(line)) }
// Harness only. Grid is an add-on: this computer is signed in to it the first time a grid feature is
// used (`ensureGrid` in the daemon, `lib/gridAttach.ts`) — with this session's token, no second
// browser — and never as a side effect of signing in to Harness.
@@ -794,9 +808,49 @@ async function loginCommand(
// SSO in the browser, or a QR the phone scans. Asked only of a person at a terminal with no flag; a
// client driving --json says `--qr` or gets the browser, as before.
let method: 'sso' | 'qr' = opts.method === 'qr' ? 'qr' : 'sso'
- const signIn = (): Promise<SignInOutcome> => method === 'qr'
- ? qrSignInCommand(json, emit, (email) => succeed(false, email))
- : browserSignIn(json, emit, () => succeed(false), entryPoint)
+ // The app driving --json: its answers, and its going away. A sign-in it left behind (the app quit
+ // or restarted) would otherwise wait on — minutes, holding the daemon spawn lock — and the app's
+ // next sign-in would sit behind it with nothing on screen. So while it waits on a person it takes
+ // its QR back and stops. Once the person has said yes the sign-in finishes instead: the session
+ // write is quick, and cancelling the code then would race its claim.
+ const driver = json ? watchJsonDriver() : null
+ const GONE = 'Sign-in stopped: the app that started it has gone.'
+ let takeBack: (() => Promise<void>) | null = null
+ let waiting = false
+ let driverGone = false
+ const abandon = async (message: string): Promise<void> => {
+ if (abandoned) return
+ emit({ type: 'result', status: 'error', code: 'CANCELLED', message })
+ abandoned = true
+ await Promise.race([takeBack?.() ?? Promise.resolve(), new Promise((r) => setTimeout(r, 3_000))])
+ process.exit(1)
+ }
+ // An app that went away before the wait began (during the lock wait) is acted on the moment it does.
+ const setWaiting = (on: boolean): void => {
+ waiting = on
+ if (on && driverGone) void abandon(GONE)
+ }
+ if (driver) {
+ // EPIPE once the app has gone: `gone` handles that. Left unhandled it would crash the process
+ // before the QR is taken back.
+ process.stdout.on('error', () => {})
+ void driver.gone.then(() => {
+ driverGone = true
+ if (waiting) void abandon(GONE)
+ })
+ // The app's Cancel / quit sends SIGTERM — the code goes back with it. Otherwise exit as SIGTERM
+ // would, with the spawn-lock exit hook still run.
+ process.on('SIGTERM', () => { if (waiting) void abandon('Sign-in was cancelled.'); else process.exit(143) })
+ }
+ const signIn = async (): Promise<SignInOutcome> => {
+ try {
+ return method === 'qr'
+ ? await qrSignInCommand(json, emit, (email) => succeed(false, email), { driver, onStarted: (cancel) => { takeBack = cancel }, onCommitted: () => setWaiting(false) })
+ : await browserSignIn(json, emit, () => succeed(false), entryPoint, { onCommitted: () => setWaiting(false) })
+ } finally {
+ setWaiting(false)
+ }
+ }
if (readAuthSession() && !force) {
// Guarded exactly like the identical call after the exchange below. Unguarded, a hiccup on
// `/api/machines/resolve-computer` reached `onError`, which is JSON-unaware — so the ONE mode a
@@ -826,6 +880,7 @@ async function loginCommand(
}
method = picked
}
+ setWaiting(true)
if (!force) return await signIn()
// 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 — and no NEW daemon
@@ -845,9 +900,15 @@ async function loginCommand(
if (readAuthSession()) await stopDaemonProcess()
return await signIn()
}, {
- onWaiting: (owner) => console.error(` the daemon is ${describeSpawnLockOwner(owner)} — waiting for it to finish…`),
+ onWaiting: (owner) => {
+ // On stdout too, for the app: stderr is a developer's, and a sign-in that shows nothing while
+ // it waits looks broken.
+ emit({ type: 'waiting', message: describeSpawnLockWaitPlainly(owner) })
+ console.error(` the daemon is ${describeSpawnLockOwner(owner)} — waiting for it to finish…`)
+ },
})
} catch (err) {
+ setWaiting(false)
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
@@ -895,6 +956,7 @@ async function qrSignInCommand(
json: boolean,
emit: (line: Record<string, unknown>) => void,
succeed: (email: string) => Promise<SignInOutcome>,
+ hooks: SignInHooks = {},
): Promise<SignInOutcome> {
const fail = (code: string, message: string): SignInOutcome => {
if (json) emit({ type: 'result', status: 'error', code, message })
@@ -905,6 +967,7 @@ async function qrSignInCommand(
let shown = false
const result = await qrSignIn({
post: (path, body) => postJson(path, body),
+ ...(hooks.onStarted ? { onStarted: hooks.onStarted } : {}),
label: hostname().slice(0, 80),
computerId: computerId(),
show: (link, expiresIn) => {
@@ -918,10 +981,14 @@ async function qrSignInCommand(
confirm: async (email) => {
if (json) {
emit({ type: 'confirm', email })
- return (await askLine('')).trim().toLowerCase() === 'yes'
+ const yes = ((hooks.driver ? await hooks.driver.nextLine() : await askLine('')) ?? '').trim().toLowerCase() === 'yes'
+ if (yes) hooks.onCommitted?.()
+ return yes
}
const answer = await askLine(`\n Your phone approved this sign-in for ${email}.\n Sign in as ${email}? [Y/n] `)
- return !/^n/i.test(answer.trim())
+ const yes = !/^n/i.test(answer.trim())
+ if (yes) hooks.onCommitted?.()
+ return yes
},
})
if (!result.ok) return fail(result.code, result.message)
@@ -955,6 +1022,7 @@ async function browserSignIn(
emit: (line: Record<string, unknown>) => void,
succeed: () => Promise<SignInOutcome>,
entryPoint: string,
+ hooks: Pick<SignInHooks, 'onCommitted'> = {},
): Promise<SignInOutcome> {
const callback = createServer()
await new Promise<void>((resolve, reject) => {
@@ -1001,6 +1069,8 @@ async function browserSignIn(
} finally {
manual?.cancel()
}
+ // The browser came back: from here the exchange and the session write run to the end.
+ hooks.onCommitted?.()
let exchanged: { token?: string; refreshToken?: string; expiresIn?: number; autonomousEnv?: 'prod' | 'stag' }
try {
exchanged = await postJson<{ token?: string; refreshToken?: string; expiresIn?: number; autonomousEnv?: 'prod' | 'stag' }>('/api/auth/exchange', {
diff --git a/cli/src/lib/daemonSpawnLock.spec.ts b/cli/src/lib/daemonSpawnLock.spec.ts
index c6b476470..f83aa1960 100644
--- a/cli/src/lib/daemonSpawnLock.spec.ts
+++ b/cli/src/lib/daemonSpawnLock.spec.ts
@@ -191,6 +191,21 @@ describe('daemon spawn lock', () => {
.toBe('Harness cannot sign in on this computer right now. Run `harness login --force` in a terminal to see why.')
})
+ it('tells a sign-in that waits on the lock what it waits for, in a person\'s words', async () => {
+ // The desktop shows the waiting line verbatim while a sign-in sits behind the lock, so it names
+ // what Harness is doing — and, when the holder is another sign-in, says exactly that.
+ const lock = await loadLock()
+ const owner = (purpose: 'start' | 'update' | 'handoff' | 'stop' | 'login') =>
+ ({ pid: 4242, startMarker: '', token: 't', purpose, since: Date.now() })
+ for (const purpose of ['start', 'update', 'handoff', 'stop', 'login'] as const) {
+ const said = lock.describeSpawnLockWaitPlainly(owner(purpose))
+ expect(said).toMatch(/^[^.]+ — waiting for it to finish…$/)
+ expect(said).not.toMatch(/pid|4242|lock/)
+ }
+ expect(lock.describeSpawnLockWaitPlainly(owner('login'))).toMatch(/^Another sign-in/)
+ expect(lock.describeSpawnLockWaitPlainly(owner('update'))).toBe('Harness is still updating on this computer — waiting for it to finish…')
+ })
+
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.ts
index c5dd5adc8..17a9ede30 100644
--- a/cli/src/lib/daemonSpawnLock.ts
+++ b/cli/src/lib/daemonSpawnLock.ts
@@ -94,6 +94,15 @@ export function describeSpawnLockOwner(owner: SpawnLockOwner): string {
return `${verb[owner.purpose]} by pid ${owner.pid} for ${secs}s`
}
+/** What Harness is still doing on this computer, by whoever holds the lock — in a person's words. */
+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',
+}
+
/**
* 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
@@ -103,14 +112,12 @@ export function describeSpawnLockOwner(owner: SpawnLockOwner): string {
*/
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.`
+ return `${error.owner ? STILL[error.owner.purpose] : 'Harness is busy on this computer'}. Try again in a moment.`
+}
+
+/** For a sign-in waiting on the lock — the desktop shows it verbatim, so no pid. */
+export function describeSpawnLockWaitPlainly(owner: SpawnLockOwner): string {
+ return `${STILL[owner.purpose]} — waiting for it to finish…`
}
let held: { token: string; purpose: SpawnLockPurpose; depth: number } | null = null
diff --git a/cli/src/lib/jsonDriver.spec.ts b/cli/src/lib/jsonDriver.spec.ts
new file mode 100644
index 000000000..8854538f9
--- /dev/null
+++ b/cli/src/lib/jsonDriver.spec.ts
@@ -0,0 +1,58 @@
+import { PassThrough } from 'node:stream'
+import { describe, expect, it, vi } from 'vitest'
+import { watchJsonDriver } from './jsonDriver.js'
+
+describe('watchJsonDriver', () => {
+ it('hands over the client\'s lines in order, whether they came before or after the ask', async () => {
+ const input = new PassThrough()
+ const driver = watchJsonDriver(input, () => true)!
+ input.write('early\n')
+ await new Promise((r) => setTimeout(r, 5))
+ expect(await driver.nextLine()).toBe('early')
+ const next = driver.nextLine()
+ input.write('yes\n')
+ expect(await next).toBe('yes')
+ })
+
+ it('knows when the client has gone, and answers nothing after', async () => {
+ const input = new PassThrough()
+ const driver = watchJsonDriver(input, () => true)!
+ const waiting = driver.nextLine()
+ let gone = false
+ void driver.gone.then(() => { gone = true })
+ input.end()
+ expect(await waiting).toBeNull()
+ await new Promise((r) => setTimeout(r, 5))
+ expect(gone).toBe(true)
+ expect(await driver.nextLine()).toBeNull()
+ })
+
+ it('keeps the process alive only while it waits for an answer', async () => {
+ // A finished sign-in must exit on its own with the app's pipe still open; one waiting for "yes"
+ // must not exit under the app. So stdin is unref'd from the start, ref'd for the wait, and
+ // unref'd again once the answer is in.
+ const input = Object.assign(new PassThrough(), { ref: vi.fn(), unref: vi.fn() })
+ const driver = watchJsonDriver(input, () => true)!
+ expect(input.unref).toHaveBeenCalledTimes(1)
+ expect(input.ref).not.toHaveBeenCalled()
+ const answer = driver.nextLine()
+ expect(input.ref).toHaveBeenCalledTimes(1)
+ input.write('yes\n')
+ expect(await answer).toBe('yes')
+ expect(input.unref).toHaveBeenCalledTimes(2)
+ })
+
+ it('does not hold the process for an answer that is already in', async () => {
+ const input = Object.assign(new PassThrough(), { ref: vi.fn(), unref: vi.fn() })
+ const driver = watchJsonDriver(input, () => true)!
+ input.write('yes\n')
+ await new Promise((r) => setTimeout(r, 5))
+ expect(await driver.nextLine()).toBe('yes')
+ expect(input.ref).not.toHaveBeenCalled()
+ expect(input.unref).toHaveBeenCalledTimes(1)
+ })
+
+ it('watches nothing when stdin is not a pipe (a script with < /dev/null)', () => {
+ expect(watchJsonDriver(new PassThrough(), () => false)).toBeNull()
+ })
+})
diff --git a/cli/src/lib/jsonDriver.ts b/cli/src/lib/jsonDriver.ts
new file mode 100644
index 000000000..f9696b6b0
--- /dev/null
+++ b/cli/src/lib/jsonDriver.ts
@@ -0,0 +1,70 @@
+import { fstatSync } from 'node:fs'
+import { createInterface } from 'node:readline'
+
+/**
+ * The client driving `harness login --json` — the desktop app — on standard input: its answers, one
+ * line each, and its going away. A sign-in holds the daemon spawn lock for as long as it waits on a
+ * browser or a phone (minutes), so one whose app quit or restarted must not wait on: the next sign-in
+ * would sit behind it, silent. The app's end of the pipe closing is the cue.
+ */
+export interface JsonDriver {
+ /** The next line the client sends, or null once it has gone. */
+ nextLine(): Promise<string | null>
+ /** Resolves when the client has gone (its end of stdin closed). */
+ readonly gone: Promise<void>
+}
+
+type Input = NodeJS.ReadableStream & { fd?: number; ref?: () => void; unref?: () => void }
+
+/**
+ * Null unless stdin is a pipe or a socket — something a client holds open. `< /dev/null` (a script
+ * that answers nothing) ends at once, and that is no sign of anyone having gone.
+ */
+export function watchJsonDriver(
+ input: Input = process.stdin,
+ isPipe: () => boolean = () => stdinIsPipe(),
+): JsonDriver | null {
+ if (!isPipe()) return null
+ const lines: string[] = []
+ const waiters: Array<(line: string | null) => void> = []
+ let closed = false
+ let markGone!: () => void
+ const gone = new Promise<void>((resolve) => { markGone = resolve })
+ const rl = createInterface({ input })
+ // Listening must not keep the process alive once the sign-in is done; only a wait for an answer does.
+ input.unref?.()
+ rl.on('line', (line) => {
+ const waiter = waiters.shift()
+ if (waiter) waiter(line)
+ else lines.push(line)
+ })
+ rl.on('close', () => {
+ closed = true
+ for (const waiter of waiters.splice(0)) waiter(null)
+ markGone()
+ })
+ return {
+ gone,
+ nextLine: () => {
+ const queued = lines.shift()
+ if (queued !== undefined) return Promise.resolve(queued)
+ if (closed) return Promise.resolve(null)
+ input.ref?.()
+ return new Promise((resolve) => {
+ waiters.push((line) => {
+ input.unref?.()
+ resolve(line)
+ })
+ })
+ },
+ }
+}
+
+function stdinIsPipe(): boolean {
+ try {
+ const stat = fstatSync(0)
+ return stat.isFIFO() || stat.isSocket()
+ } catch {
+ return false
+ }
+}
diff --git a/cli/src/lib/qrSignIn.spec.ts b/cli/src/lib/qrSignIn.spec.ts
index fc740d7b0..59ab9d29d 100644
--- a/cli/src/lib/qrSignIn.spec.ts
+++ b/cli/src/lib/qrSignIn.spec.ts
@@ -58,6 +58,16 @@ describe('qrSignIn', () => {
expect(b.paths()).toContain('/api/auth/qr/cancel')
})
+ it('hands its caller a way to take the code back, the moment there is one', async () => {
+ // `harness login --json` keeps it: when the app driving it goes away, the code goes with it.
+ const b = backend([{ status: 'approved', email: '[email protected]' }])
+ let takeBack: (() => Promise<void>) | undefined
+ await qrSignIn({ ...b.deps(), onStarted: (cancel) => { takeBack = cancel } })
+ expect(takeBack).toBeTypeOf('function')
+ await takeBack!()
+ expect(b.calls.at(-1)).toEqual({ path: '/api/auth/qr/cancel', body: { pollToken: 'hnp_poll' } })
+ })
+
it('reports a denial', async () => {
const r = await qrSignIn(backend([{ status: 'denied' }]).deps())
expect(r).toMatchObject({ ok: false, code: 'DENIED' })
diff --git a/cli/src/lib/qrSignIn.ts b/cli/src/lib/qrSignIn.ts
index ba87b67fd..a56f8fcbe 100644
--- a/cli/src/lib/qrSignIn.ts
+++ b/cli/src/lib/qrSignIn.ts
@@ -42,6 +42,8 @@ export interface QrSignInDeps {
sleep?: (ms: number) => Promise<void>
now?: () => number
pollEveryMs?: number
+ /** Called once the code exists, with how to take it back — for a caller that must stop early. */
+ onStarted?: (cancel: () => Promise<void>) => void
}
/** Extend the code this long before it runs out, so an approval given at the last moment counts. */
@@ -62,6 +64,7 @@ export async function qrSignIn(deps: QrSignInDeps): Promise<QrSignInResult> {
let expiresAt = now() + started.expiresIn * 1000
deps.show(link, started.expiresIn)
const cancel = async (): Promise<void> => { await deps.post('/api/auth/qr/cancel', { pollToken }).catch(() => {}) }
+ deps.onStarted?.(cancel)
for (;;) {
await sleep(every)
if (expiresAt - now() < EXTEND_BEFORE_MS) {
diff --git a/desktop/lib/app_shell.dart b/desktop/lib/app_shell.dart
index 7985e7eca..48ce8a8c3 100644
--- a/desktop/lib/app_shell.dart
+++ b/desktop/lib/app_shell.dart
@@ -211,12 +211,16 @@ class _RootShellState extends ConsumerState<RootShell>
@override
Future<AppExitResponse> didRequestAppExit() async {
+ final app = ref.read(appStateProvider);
+ // A sign-in still waiting on the browser or a phone ends with the app: its
+ // CLI would otherwise wait on, holding the lock the next sign-in needs.
+ if (app.canCancelLogin) app.cancelLogin();
// Save the final arrangement, with a bound so an unavailable disk cannot
// trap the user in the app. Input and tab switching never wait for disk.
- await ref
- .read(appStateProvider)
- .flushPaneLayout()
- .timeout(const Duration(seconds: 1), onTimeout: () {});
+ await app.flushPaneLayout().timeout(
+ const Duration(seconds: 1),
+ onTimeout: () {},
+ );
return AppExitResponse.exit;
}
diff --git a/desktop/lib/auth/cli_login.dart b/desktop/lib/auth/cli_login.dart
index 0c1cee56f..a24e6b818 100644
--- a/desktop/lib/auth/cli_login.dart
+++ b/desktop/lib/auth/cli_login.dart
@@ -2,6 +2,8 @@ import 'dart:async';
import 'dart:convert';
import 'dart:io';
+import 'package:flutter/foundation.dart';
+
import '../core/harness_cli_runner.dart';
import 'phone_sign_in.dart';
import 'sign_in_client.dart';
@@ -54,6 +56,11 @@ class CliLogin implements SignInClient, PhoneSignInClient {
CliLogin({HarnessCliRunner? runner}) : _runner = runner ?? HarnessCliRunner();
+ /// While a sign-in waits on something before it can start — another sign-in on this computer
+ /// still holding the daemon spawn lock — what the CLI said about it (its `waiting` event); null
+ /// otherwise. A wait the app shows nothing for reads as a sign-in that is broken.
+ final ValueNotifier<String?> waitingNote = ValueNotifier(null);
+
@override
Future<CliAuthStatus> checkStatus() async {
final result = await _run(['auth', 'status', '--json']);
@@ -138,7 +145,11 @@ class CliLogin implements SignInClient, PhoneSignInClient {
} catch (_) {
continue;
}
+ if (json['type'] != 'waiting') waitingNote.value = null;
switch (json['type']) {
+ case 'waiting':
+ final note = json['message'];
+ if (note is String && note.isNotEmpty) waitingNote.value = note;
case 'authorize_url':
// Asked for a QR and given a browser page: a CLI from before `--qr`, which ignores the
// flag and starts SSO. Nothing would ever be shown — stop it and say why.
@@ -192,6 +203,7 @@ class CliLogin implements SignInClient, PhoneSignInClient {
}
} finally {
if (identical(_activeProcess, process)) _activeProcess = null;
+ if (revision == _loginRevision) waitingNote.value = null;
}
}
@@ -200,6 +212,7 @@ class CliLogin implements SignInClient, PhoneSignInClient {
@override
void cancel() {
++_loginRevision;
+ waitingNote.value = null;
final process = _activeProcess;
_activeProcess = null;
process?.kill();
diff --git a/desktop/lib/screens/login_screen.dart b/desktop/lib/screens/login_screen.dart
index e051e0023..5fc513267 100644
--- a/desktop/lib/screens/login_screen.dart
+++ b/desktop/lib/screens/login_screen.dart
@@ -509,6 +509,8 @@ class _ActionState extends State<_Action> {
final url = notifier.pendingAuthorizeUrl;
final message =
notifier.loginBrowserError ??
+ // The CLI is waiting before it can even start: say on what.
+ notifier.loginWaitingNote ??
(url != null && _copyFailureUrl == url
? 'Couldn’t copy the link. Try opening your browser again.'
: null);
@@ -822,12 +824,18 @@ class _SignInSheetState extends State<_SignInSheet> {
// ⚠️ Esc is bound OUT HERE, around the screen, so the screen's own Esc — which
// cancels a sign-in that is in flight — wins while there is one to cancel.
// The X itself is the SCREEN's, on its card: see LoginScreen.onClose.
+ // ⚠️ This route is built once, apart from the shell that rebuilds the
+ // full-window screen, so it follows the notifier itself: a sign-in shows
+ // what arrives mid-flight here too — the phone's QR, then whose account.
return CallbackShortcuts(
bindings: {
const SingleActivator(LogicalKeyboardKey.escape, includeRepeats: false):
_dismiss,
},
- child: LoginScreen(notifier: notifier, onClose: _dismiss),
+ child: ListenableBuilder(
+ listenable: notifier,
+ builder: (_, _) => LoginScreen(notifier: notifier, onClose: _dismiss),
+ ),
);
}
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index acb95bc24..dfbfe2363 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -2100,6 +2100,17 @@ class AppNotifier extends ChangeNotifier {
/// Whether this build can sign in by a phone at all (the CLI's, and a viewer's, can).
bool get canSignInWithPhone => cliLogin is PhoneSignInClient;
+
+ /// What a sign-in in progress is waiting on before it can start — another sign-in on this
+ /// computer, say — for the login screen to show; null when it is not waiting.
+ String? get loginWaitingNote => switch (cliLogin) {
+ CliLogin(:final waitingNote) => waitingNote.value,
+ _ => null,
+ };
+
+ void _loginWaitingChanged() {
+ if (!_disposed) notifyListeners();
+ }
bool openingLoginBrowser = false;
String? loginBrowserError;
int _loginBrowserRevision = 0;
@@ -2175,6 +2186,9 @@ class AppNotifier extends ChangeNotifier {
: null) {
_cliLink = cliLink;
this.cliLogin = cliLogin ?? this.viewer?.login ?? CliLogin();
+ if (this.cliLogin case final CliLogin cli) {
+ cli.waitingNote.addListener(_loginWaitingChanged);
+ }
this.peerLinks = peerLinks ?? this.viewer?.links ?? this.cliLink;
_autonomousEnv = this.config.autonomousEnv;
api = _newApiClient();
@@ -13839,6 +13853,9 @@ class AppNotifier extends ChangeNotifier {
@override
void dispose() {
+ if (cliLogin case final CliLogin cli) {
+ cli.waitingNote.removeListener(_loginWaitingChanged);
+ }
experimentalFeatures.dispose();
viewer?.auth.dispose();
_deviceVisit?.dispose();
diff --git a/desktop/test/login_screen_phone_test.dart b/desktop/test/login_screen_phone_test.dart
index f8075f7e0..2bf55af54 100644
--- a/desktop/test/login_screen_phone_test.dart
+++ b/desktop/test/login_screen_phone_test.dart
@@ -1,7 +1,10 @@
import 'dart:async';
+import 'dart:ui' show AppExitResponse;
import 'package:flutter/material.dart';
+import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/app_shell.dart';
import 'package:harness/auth/auth_session.dart';
import 'package:harness/auth/cli_login.dart';
import 'package:harness/auth/sign_in_client.dart';
@@ -31,6 +34,48 @@ class _PhoneLogin extends CliLogin {
}
}
+/// A sign-in that waits behind another one — what the CLI's `waiting` event sets — until released.
+class _WaitingLogin extends CliLogin {
+ static const note = 'Another sign-in on this computer is still running — waiting for it to finish…';
+ final release = Completer<void>();
+
+ @override
+ Future<void> loginWithPhone({
+ required void Function(String link, int expiresIn) onQr,
+ required Future<bool> Function(String email) onConfirm,
+ }) async {
+ waitingNote.value = note;
+ await release.future;
+ throw StateError('Sign-in was cancelled.');
+ }
+}
+
+/// A phone sign-in that never hears back from the phone, and counts how often it is told to stop.
+class _HangingLogin extends CliLogin {
+ var cancels = 0;
+
+ @override
+ Future<void> loginWithPhone({
+ required void Function(String link, int expiresIn) onQr,
+ required Future<bool> Function(String email) onConfirm,
+ }) async {
+ onQr('https://harness.autonomous.ai/signin#k=hnq_${'a' * 43}', 120);
+ await Completer<void>().future;
+ }
+
+ @override
+ void cancel() {
+ cancels++;
+ super.cancel();
+ }
+}
+
+/// The whole app, the way it runs — for what happens when the person quits it.
+Widget _wholeApp(AppNotifier app) => ProviderScope(
+ overrides: [appStateProvider.overrideWithValue(app)],
+ child: HarnessApp(authenticatedScreen: (_) => const SizedBox()),
+);
+
Widget _host(AppNotifier app) => MaterialApp(
theme: grid.buildAppTheme(brightness: Brightness.light),
home: MediaQuery(
@@ -67,6 +112,99 @@ void main() {
expect(find.byKey(const Key('login-scan-with-phone')), findsOneWidget);
});
+ testWidgets('over the desk (a guest signing in), the QR still appears and the question too', (tester) async {
+ // The sheet is its own route, built once: it has to follow the notifier itself, or a QR that
+ // arrives after the click is never drawn (2026-10-01, a guest's "Scan with your phone").
+ grid.AppTheme.brightness.value = Brightness.light;
+ final login = _PhoneLogin();
+ final app = AppNotifier(config: AppConfig.dev, authSession: AuthSession(), configStore: null, cliLogin: login)
+ ..status = AppStatus.authenticated
+ ..signedIn = false;
+ addTearDown(app.dispose);
+ await tester.pumpWidget(MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.light),
+ home: MediaQuery(
+ data: const MediaQueryData(size: Size(880, 700)),
+ child: grid.BrightnessScope(
+ child: Builder(
+ builder: (context) => Center(
+ child: TextButton(
+ key: const Key('open-sheet'),
+ onPressed: () => unawaited(showSignInSheet(context, app)),
+ child: const Text('Sign in'),
+ ),
+ ),
+ ),
+ ),
+ ),
+ ));
+ await tester.tap(find.byKey(const Key('open-sheet')));
+ await tester.pump();
+ await tester.tap(find.byKey(const Key('login-scan-with-phone')));
+ await tester.pump();
+ expect(find.byKey(const Key('login-phone-qr')), findsOneWidget);
+
+ await tester.pump(const Duration(milliseconds: 20));
+ expect(find.text('Sign in as [email protected]?'), findsOneWidget);
+ await tester.tap(find.byKey(const Key('login-phone-refuse')));
+ await tester.pump();
+ expect(login.answers, [false]);
+ login.finished.complete();
+ await tester.pump();
+ });
+
+ testWidgets('a sign-in waiting behind another one says so, rather than showing nothing', (tester) async {
+ grid.AppTheme.brightness.value = Brightness.light;
+ final login = _WaitingLogin();
+ final app = AppNotifier(config: AppConfig.dev, authSession: AuthSession(), configStore: null, cliLogin: login)
+ ..status = AppStatus.unauthenticated;
+ addTearDown(app.dispose);
+ await tester.pumpWidget(_host(app));
+ await tester.tap(find.byKey(const Key('login-scan-with-phone')));
+ await tester.pump();
+ expect(find.text(_WaitingLogin.note), findsOneWidget);
+ // Its turn comes: the note goes with the wait.
+ login.waitingNote.value = null;
+ await tester.pump();
+ expect(find.text(_WaitingLogin.note), findsNothing);
+ login.release.complete();
+ await tester.pump();
+ });
+
+ testWidgets('quitting the app stops a phone sign-in still waiting on the phone', (tester) async {
+ // Its CLI would otherwise wait on after the app has gone — minutes, holding the lock the next
+ // sign-in needs, with its QR still good for anyone who scans it.
+ final login = _HangingLogin();
+ final app = AppNotifier(config: AppConfig.dev, authSession: AuthSession(), configStore: null, cliLogin: login)
+ ..status = AppStatus.unauthenticated;
+ unawaited(app.loginWithPhone());
+ await tester.pumpWidget(_wholeApp(app));
+ await tester.pump();
+ expect(app.signingIn, isTrue);
+ expect(app.pendingQrLink, isNotNull);
+
+ final observer = tester.state(find.byType(RootShell)) as WidgetsBindingObserver;
+ expect(await observer.didRequestAppExit(), AppExitResponse.exit);
+ expect(login.cancels, 1);
+ expect(app.signingIn, isFalse);
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ });
+
+ testWidgets('quitting with no sign-in in flight stops nothing', (tester) async {
+ // A signed-out app on its login screen quits as before: there is no CLI to stop.
+ final login = _HangingLogin();
+ final app = AppNotifier(config: AppConfig.dev, authSession: AuthSession(), configStore: null, cliLogin: login)
+ ..status = AppStatus.unauthenticated;
+ await tester.pumpWidget(_wholeApp(app));
+ await tester.pump();
+ final observer = tester.state(find.byType(RootShell)) as WidgetsBindingObserver;
+ expect(await observer.didRequestAppExit(), AppExitResponse.exit);
+ expect(login.cancels, 0);
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ });
+
testWidgets('a build that cannot sign in by phone does not offer it', (tester) async {
grid.AppTheme.brightness.value = Brightness.light;
final app = AppNotifier(config: AppConfig.dev, authSession: AuthSession(), configStore: null, cliLogin: _SsoOnly())
diff --git a/desktop/test/phone_sign_in_test.dart b/desktop/test/phone_sign_in_test.dart
index f57d196dc..198d005d8 100644
--- a/desktop/test/phone_sign_in_test.dart
+++ b/desktop/test/phone_sign_in_test.dart
@@ -143,6 +143,23 @@ void main() {
expect(asked, ['[email protected]']);
});
+ test('a wait behind another sign-in is shown until the CLI moves on', () async {
+ final process = _Process();
+ final login = CliLogin(runner: _Runner(process));
+ final done = login.loginWithPhone(onQr: (_, _) {}, onConfirm: (_) async => false);
+ await Future<void>.delayed(Duration.zero);
+ process.emit({'type': 'waiting', 'message': 'Another sign-in on this computer is still running — waiting for it to finish…'});
+ await Future<void>.delayed(const Duration(milliseconds: 20));
+ expect(login.waitingNote.value, startsWith('Another sign-in'));
+ process.emit({'type': 'qr', 'url': 'https://harness.autonomous.ai/signin#k=hnq_x', 'expiresIn': 120});
+ await Future<void>.delayed(const Duration(milliseconds: 20));
+ expect(login.waitingNote.value, isNull);
+ process.emit({'type': 'result', 'status': 'error', 'code': 'CANCELLED', 'message': 'x'});
+ process.finish(1);
+ await expectLater(done, throwsA(isA<PhoneSignInException>()));
+ expect(login.waitingNote.value, isNull);
+ });
+
test('says no on stdin when the person refuses the account, and reports why it ended', () async {
final process = _Process();
final done = CliLogin(runner: _Runner(process))