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(cli, desktop): Harness signs a machine out only when a person signs out (#1866)
0xken154ff5afa86d55
diff --git a/cli/src/authCommand.spec.ts b/cli/src/authCommand.spec.tsindex 539730a45..660b24a42 100644--- a/cli/src/authCommand.spec.ts+++ b/cli/src/authCommand.spec.ts@@ -222,6 +222,53 @@ describe.skipIf(process.platform === 'win32')('harness status connection setting})})+// 10-27: a desktop test ran the real `harness logout` with no person anywhere near it, and signed the whole Mac+// out, every agent on it with it. The sign-in goes only when a person asks: at a terminal, or through the+// desktop app's sign-out button, which says so with a flag. Every removal is logged with who asked.+describe('signing out takes a person', () => {+ const sessionFile = (root: string): string => join(root, 'auth', 'session.json')+ const logFile = (root: string): string => join(root, 'data', 'harness.log')++ it.each([['logout'], ['reset']])('%s with no terminal and no flag refuses, and keeps the sign-in', (command) => {+ const root = tempRoot()+ seedSession(root)++ const result = runSync(root, [command])++ expect(result.status).toBe(1)+ expect(result.stderr).toContain('--from-sign-out-button')+ expect(existsSync(sessionFile(root))).toBe(true)+ })++ it('reset logs its removal though it empties the data folder that holds harness.log', () => {+ const root = tempRoot()+ seedSession(root)++ const result = runSync(root, ['reset', '--from-sign-out-button'])++ expect(result.status, result.stderr).toBe(0)+ expect(existsSync(sessionFile(root))).toBe(false)+ expect(readFileSync(logFile(root), 'utf8')).toMatch(/\[auth\] sign-in removed · reason=reset · asked=sign-out button/)+ })++ it('logout from the sign-out button signs out, and harness.log names what asked and its parent', () => {+ const root = tempRoot()+ seedSession(root)++ const result = runSync(root, ['logout', '--from-sign-out-button'])++ expect(result.status, result.stderr).toBe(0)+ expect(existsSync(sessionFile(root))).toBe(false)+ const line = readFileSync(logFile(root), 'utf8').split('\n').find((l) => l.includes('[auth]'))+ expect(line).toContain('sign-in removed')+ expect(line).toContain('reason=logout')+ expect(line).toContain('asked=sign-out button')+ expect(line).toContain(`parent=${process.pid}`)+ // The parent's own command line: here, the node running this suite.+ expect(line).toContain(process.execPath.split('/').pop()!)+ })+})+describe('harness auth status --json', () => {it('reports loggedIn:false with no saved session, and never touches the network', () => {const root = tempRoot()@@ -280,6 +327,41 @@ describe('harness auth status --json', () => {expect(JSON.parse(result.stdout.trim())).toMatchObject({ loggedIn: true, offline: true, machineId: 'm_seeded' })})+ // 10-27: nothing automatic deletes the sign-in any more; it is kept, marked signed out (lib/authSession.ts+ // `markSignedOut`), and the app is told which kind so it can say what happens next.+ it('a sign-in whose refresh was refused reports signed out, waiting for a refresh, and keeps it', async () => {+ const root = tempRoot()+ seedSession(root, { overrides: { signedOut: { at: 1, reason: 'refresh-refused' } } })+ const backend = await fakeBackend({ routes: { '/api/auth/refresh': () => new Refusal(401, 'REFRESH_TOKEN_INVALID', 'expired') } })++ const result = await runAsync(root, ['auth', 'status', '--json'], backend.base)++ expect(result.status).toBe(0)+ expect(JSON.parse(result.stdout.trim())).toMatchObject({ loggedIn: false, signedOut: 'pending-refresh' })+ expect(backend.calls.map((c) => c.url)).toEqual(['/api/auth/refresh'])+ expect(existsSync(join(root, 'auth', 'session.json'))).toBe(true)+ })++ it('a refused refresh the service now renews signs the computer back in', async () => {+ const root = tempRoot()+ seedSession(root, { overrides: { signedOut: { at: 1, reason: 'refresh-refused' } } })+ const backend = await fakeBackend({ routes: { '/api/auth/refresh': () => ({ token: 'tok_renewed', refreshToken: 'refresh_2', expiresIn: 3600 }) } })++ const result = await runAsync(root, ['auth', 'status', '--json'], backend.base)++ expect(JSON.parse(result.stdout.trim())).toMatchObject({ loggedIn: true, machineId: 'm_seeded' })+ expect(JSON.parse(readFileSync(join(root, 'auth', 'session.json'), 'utf8'))).not.toHaveProperty('signedOut')+ })++ it('a revoked sign-in reports signed out, waiting for a sign-in, and asks the network nothing', () => {+ const root = tempRoot()+ seedSession(root, { overrides: { signedOut: { at: 1, reason: 'revoked' } } })++ const result = runSync(root, ['auth', 'status', '--json'], 'http://127.0.0.1:1')++ expect(JSON.parse(result.stdout.trim())).toMatchObject({ loggedIn: false, signedOut: 'waiting-for-sign-in' })+ })+it('carries this machine\'s fingerprint when its key is on disk', () => {const root = tempRoot()seedSession(root)diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex 0ab1fc326..d0cc4d09e 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -48,7 +48,8 @@ import { serviceCommand, serviceCommandDeps } from './lib/serviceCommand.js'import { infoBlockFooter } from './lib/infoBlockFooter.js'import { flashCommand } from './lib/flash.js'import { awaitLoginCallback, extractCallbackParams, LOGIN_TIMEOUT_MESSAGE, type LoginCallbackParams } from './lib/loginCallback.js'-import { AUTH_DIR, AuthSessionError, AuthSessionManager, clearAuthSession, knownSsoClientId, newSignInEpoch, readAuthSession, ssoClientIdFor, writeAuthSession, type AuthSession } from './lib/authSession.js'+import { ancestorsOnce, removeSignIn, SIGN_OUT_BUTTON_FLAG, signOutAsked, type Asker, type SignOutAsked } from './lib/signOut.js'+import { AUTH_DIR, AuthSessionError, AuthSessionManager, knownSsoClientId, newSignInEpoch, readAuthSession, readSignedOut, ssoClientIdFor, writeAuthSession, type AuthSession } from './lib/authSession.js'import { handOffToGrid } from './lib/gridHandoff.js'import { claimTicket, qrSignIn, type QrSignInTokens } from './lib/qrSignIn.js'import { pickSignInMethod, signInMethodFlag, signInProviderName, withSignInProvider, type SignInMethod, type SignInProvider } from './lib/signInMethodPicker.js'@@ -334,15 +335,19 @@ function thisDeviceFingerprint(create: boolean): string | null {* on-disk-but-about-to-expire gets refreshed here rather than reporting loggedIn:true and 401ing on* the caller's very next request. */async function authStatusCommand(json: boolean): Promise<void> {- const session = readAuthSession()+ const auth = new AuthSessionManager(backendHttpBase())+ // A sign-in whose refresh was refused is kept, marked signed out (lib/authSession.ts `markSignedOut`), and+ // tried again each time this is asked: the refusal may have been the service's. A revoked one is not.+ const session = readAuthSession() ?? (await auth.retrySignedOut() ? readAuthSession() : null)if (!session) {// The computer id travels even signed out: it is the id this computer's daemon serves itself// under, and the app keys the local machine by it until a sign-in hands out a machineId.- if (json) console.log(JSON.stringify({ loggedIn: false, computerId: computerId() }))+ const waiting = signedOutWaiting()+ if (json) console.log(JSON.stringify({ loggedIn: false, computerId: computerId(), ...(waiting ? { signedOut: waiting } : {}) }))+ else if (waiting === 'pending-refresh') console.log('\n ✗ Signed out: this computer\'s sign-in could not be renewed. It is tried again; or run: harness login\n')else console.log('\n ✗ Not signed in. Run: harness login\n')return}- const auth = new AuthSessionManager(backendHttpBase())let loggedIn = truelet offline = falsetry {@@ -358,8 +363,10 @@ async function authStatusCommand(json: boolean): Promise<void> {const latest = readAuthSession()const signedIn = loggedIn && latest !== nullconst fingerprintNow = thisDeviceFingerprint(false)+ const waiting = signedIn ? null : signedOutWaiting()const payload = {loggedIn: signedIn,+ ...(waiting ? { signedOut: waiting } : {}),...(signedIn && offline ? { offline: true } : {}),computerId: latest?.computerId,machineId: latest?.machineId,@@ -1321,13 +1328,15 @@ async function updateCommand(force: boolean): Promise<void> {* on this box first, while the token that makes their deregistration authoritative still exists.*/async function logout(): Promise<void> {+ const chain = ancestorsOnce()+ const asked = personAsked('logout', chain)// Through the lock-taking stop, not an inline kill: a logout that lands mid-handoff would otherwise// SIGTERM the OLD daemon, leave the new one coming up, and then delete the session under it.const { pid: stoppedPid } = await stopDaemonOrExit()- // Before clearAuthSession: see the note above on serve children. Its exit code is deliberately+ // Before removeSignIn: see the note above on serve children. Its exit code is deliberately// dropped — this command cannot fail — and its own words have already reached the terminal.const gridOut = await passThroughToGridLogout([])- clearAuthSession()+ removeSignIn('logout', asked, chain)rmSync(MACHINE_NAME_FILE, { force: true })// Same reason as the name above: the cached machine list describes the account that just left, and the// local `/api/machines` fallback would otherwise hand it to whoever signs in next on this computer.@@ -1738,14 +1747,36 @@ function clearAdapterState(): void {rmStateFiles(cliDir)}+/** Why a sign-in kept on disk is signed out, as `auth status` tells the app: waiting for its refresh to be+ * tried again, or for a new sign-in (a revoke). Null when there is none, or it is signed in. */+function signedOutWaiting(): 'pending-refresh' | 'waiting-for-sign-in' | null {+ const signedOut = readSignedOut()+ return signedOut === null ? null : signedOut.reason === 'refresh-refused' ? 'pending-refresh' : 'waiting-for-sign-in'+}++/**+ * How a person asked for `harness [command]` to take this computer's sign-in away; exits with why not when+ * nothing says one did. 10-27: a desktop test ran the real `harness logout`, with no person anywhere near it,+ * and signed the whole Mac out, every agent on it with it (lib/signOut.ts).+ */+function personAsked(command: string, chain: () => readonly Asker[]): SignOutAsked {+ const asked = signOutAsked({ interactive: process.stdin.isTTY === true, flags: process.argv.slice(2), ancestors: chain })+ if (asked) return asked+ console.error(`\n✗ \`harness ${command}\` signs this computer out, and nothing says a person asked: it has no terminal, `+ + `and no ${SIGN_OUT_BUTTON_FLAG} from the desktop app's Sign out button. Run it in a terminal.\n`)+ process.exit(1)+}+/** Stop the daemon and clear local state so the next login starts fresh. */async function resetCommand(): Promise<void> {+ const chain = ancestorsOnce()+ const asked = personAsked('reset', chain)// Before anything is cleared: a pid file removed under a Harness still running leaves nothing able to stop it.const r = await stopDaemonOrExit()clearAdapterState()console.log(`\n ✓ Cleared local machine CLI state at ${tildify(env.ADAPTER_DATA_DIR)}.`)if (r.pid) console.log(` Stopped adapter process ${r.pid}.`)- clearAuthSession()+ removeSignIn('reset', asked, chain)console.log('\n Start again with: harness login, then harness start\n')// The SECOND door onto the sign-out `logout` performs, and it clears MORE, so somebody running it// is if anything likelier to believe nothing is left. Same call, so the two cannot drift.diff --git a/cli/src/cliStopFirst.spec.ts b/cli/src/cliStopFirst.spec.tsindex bfda1ada1..4e15dd1b9 100644--- a/cli/src/cliStopFirst.spec.ts+++ b/cli/src/cliStopFirst.spec.ts@@ -32,14 +32,14 @@ function at(text: string, call: string, after = 0): number {/** What changes the computer's state, or starts Harness: none of it may run before a stop's outcome is known. */const MUTATING = [- 'clearAdapterState(', 'clearAuthSession(', 'writeAuthSession(', 'saveAuthSession(', 'rmSync(', 'writeFileSync(', 'renameSync(',+ 'clearAdapterState(', 'clearAuthSession(', 'removeSignIn(', 'writeAuthSession(', 'saveAuthSession(', 'rmSync(', 'writeFileSync(', 'renameSync(','launch(', 'relaunch(', 'passThroughToGridLogout(', 'runUpdateSteps(', 'signIn(', 'resolveMachineIfUnknown(',]describe('commands that stop Harness first (cli.ts)', () => {it.each([- ['resetCommand', ['clearAdapterState(', 'clearAuthSession(']],- ['logout', ['passThroughToGridLogout(', 'clearAuthSession(', 'launch(']],+ ['resetCommand', ['clearAdapterState(', 'removeSignIn(']],+ ['logout', ['passThroughToGridLogout(', 'removeSignIn(', 'launch(']],['updateCommand', ['runUpdateSteps(', 'relaunch()']],])('%s goes on only once Harness has stopped', (name, after) => {const text = body(name)diff --git a/cli/src/core/main.ts b/cli/src/core/main.tsindex 66d31ffe2..195384fee 100644--- a/cli/src/core/main.ts+++ b/cli/src/core/main.ts@@ -60,7 +60,7 @@ import { awakeTimeout } from '../lib/sleepAware.js'import { removePidFileIf, onError } from '../lib/daemonLaunch.js'import { harnessdEnv, holdHarnessdEnv } from '../lib/harnessdEnv.js'import { dropAgentSessionEnv } from '../lib/agentSessionEnv.js'-import { AUTH_DIR, AuthSessionManager, clearAuthSession, ensureSignInEpoch, readAuthSession, signInOf, type AuthSession } from '../lib/authSession.js'+import { AUTH_DIR, AuthSessionManager, ensureSignInEpoch, markSignedOut, readAuthSession, signInOf, type AuthSession } from '../lib/authSession.js'import { ENGINES, enginePathOverride } from '../lib/engineBin.js'import { isTerminalEngine, type AgentEngine } from '../engines/types.js'import { engineInstallRecipe } from '../lib/engineInstall.js'@@ -3131,15 +3131,21 @@ async function runForeground(session: AuthSession | null): Promise<void> {// Windows: the master's stop is a message (harnessd/protocol.ts `harnessd:shutdown`), never a signal.coreLink.onShutdown(() => void shutdown('the harnessd master asked this core to stop'))- // A machine revocation or invalid SSO refresh ends this adapter session permanently.+ // A machine revocation, a 401/403 on the backend link, or a refused SSO refresh ends this signed-in+ // session: the daemon stops and comes back signed out. The sign-in is kept, marked signed out, and nothing+ // reads it again until a new sign-in replaces it. 10-27: a sign-out nobody asked for stalled a whole Mac;+ // only a person deletes it (lib/signOut.ts).backend.onRevoked = () => {- console.log('[cli] this computer was removed from the machine — clearing credentials and stopping')- clearAuthSession()+ console.log('[cli] this computer\'s sign-in was revoked or refused — signed out, keeping it until a new sign-in, and stopping')// The web-tools cache lives exactly as long as the sign-in. `harness logout` and `reset` stop// the daemon outright; this is the one sign-out the daemon learns of from inside.ports.models?.signedOut()swarmDoors?.cards.reset()- void shutdown('revoked')+ // Marked before the stop: the core that comes back must read it as signed out. The mark waits for a+ // refresh another process has under way, so that refresh's save cannot write over it.+ void markSignedOut('revoked')+ .catch((error: unknown) => console.log(`[cli] could not mark the sign-in signed out (${error instanceof Error ? error.message : String(error)})`))+ .finally(() => void shutdown('revoked'))}// Mirror the machine's display name to disk so `harness status` (a separate process) can print it.diff --git a/cli/src/gridCommand.spec.ts b/cli/src/gridCommand.spec.tsindex 59e8f3058..0ff80381f 100644--- a/cli/src/gridCommand.spec.ts+++ b/cli/src/gridCommand.spec.ts@@ -18,6 +18,7 @@ import { delimiter, join } from 'path'import { fileURLToPath } from 'url'import { afterEach, describe, expect, it } from 'vitest'import { useBundledCli } from './__fixtures__/bundledCli.js'+import { SIGN_OUT_BUTTON_FLAG } from './lib/signOut.js'const CLI_ROOT = fileURLToPath(new URL('..', import.meta.url))const cli = useBundledCli()@@ -735,7 +736,8 @@ function seedGridCredentials(dir: string): string {* `undefined` drops the variable from the child's environment altogether, which is the state the* `~/.grid` default is for. */function runLogout(root: string, gridHome?: string, grid: GridOnPath = 'runnable'): Promise<Run> {- return run(root, ['logout'], 'http://127.0.0.1:1', { GRID_HOME: gridHome }, grid)+ // As the desktop app's Sign out runs it: with no terminal, a sign-out needs the button's flag (lib/signOut.ts).+ return run(root, ['logout', SIGN_OUT_BUTTON_FLAG], 'http://127.0.0.1:1', { GRID_HOME: gridHome }, grid)}describe('harness grid logout', () => {@@ -909,7 +911,7 @@ describe('harness logout — the grid sign-out it now performs', () => {seedSession(root)// `grid logout` refuses over a serve child it cannot confirm stopped. That must be reported and// never propagated: a grid condition cannot block a harness sign-out.- const result = await run(root, ['logout'], 'http://127.0.0.1:1', {+ const result = await run(root, ['logout', SIGN_OUT_BUTTON_FLAG], 'http://127.0.0.1:1', {FAKE_GRID_EXIT: '1',FAKE_GRID_STDERR: 'dt-edge: still serving on pid 4242. Stop it, or sign out with --force.\n',})@@ -993,7 +995,7 @@ describe('harness reset — the second door onto the same sign-out', () => {// `reset` clears the SSO session exactly as `logout` does, and more besides — so somebody who// runs it is if anything likelier to believe nothing is left behind. A warning written at one// door and not the other is a warning the other silently does without.- const result = await run(root, ['reset'], 'http://127.0.0.1:1', { GRID_HOME: undefined })+ const result = await run(root, ['reset', SIGN_OUT_BUTTON_FLAG], 'http://127.0.0.1:1', { GRID_HOME: undefined })expect(result.status).toBe(0)expect(result.stderr).toContain('harness grid logout')@@ -1005,7 +1007,7 @@ describe('harness reset — the second door onto the same sign-out', () => {const root = tempRoot()seedSession(root)- const result = await run(root, ['reset'], 'http://127.0.0.1:1', { GRID_HOME: undefined })+ const result = await run(root, ['reset', SIGN_OUT_BUTTON_FLAG], 'http://127.0.0.1:1', { GRID_HOME: undefined })expect(result.status).toBe(0)expect(result.stderr).not.toContain('grid logout')diff --git a/cli/src/lib/authSession.spec.ts b/cli/src/lib/authSession.spec.tsindex 5d532f4dc..152b951d1 100644--- a/cli/src/lib/authSession.spec.ts+++ b/cli/src/lib/authSession.spec.ts@@ -12,8 +12,11 @@ const {AuthSessionManager,clearAuthSession,ensureSignInEpoch,+ hasAuthSession,+ markSignedOut,newSignInEpoch,readAuthSession,+ readSignedOut,releaseHeldAuthLock,signInOf,writeAuthSession,@@ -235,15 +238,100 @@ describe('AuthSessionManager', () => {expect(readAuthSession()).toMatchObject({ refreshToken: 'refresh-1' })})- it('clears an invalid refresh session instead of retrying it forever', async () => {+ // 10-27: a sign-out nobody asked for stalled a whole Mac. Nothing automatic deletes the sign-in: it is kept,+ // marked signed out, and nothing reads it as signed in again until a new sign-in replaces it.+ const refusal = (): Response => new Response(JSON.stringify({+ success: false,+ error: { code: 'REFRESH_TOKEN_INVALID', message: 'expired' },+ }), { status: 401 })+ const renewal = (): Response => new Response(JSON.stringify({+ success: true,+ data: { token: 'renewed-access', refreshToken: 'refresh-2', expiresIn: 3600 },+ }), { status: 200 })++ it('a refused refresh keeps the sign-in, marked signed out: nothing uses it, nor refreshes it again', async () => {writeAuthSession(baseSession())- vi.stubGlobal('fetch', vi.fn<typeof fetch>().mockResolvedValue(new Response(JSON.stringify({- success: false,- error: { code: 'REFRESH_TOKEN_INVALID', message: 'expired' },- }), { status: 401 })))+ const refused = vi.fn<typeof fetch>().mockImplementation(async () => refusal())+ vi.stubGlobal('fetch', refused)const manager = new AuthSessionManager('https://api.example.test')await expect(manager.accessToken()).rejects.toMatchObject({ name: AuthSessionError.name, code: 'INVALID_REFRESH' })++ expect(readAuthSession()).toBeNull()+ expect(readSignedOut()).toMatchObject({ reason: 'refresh-refused' })+ expect(JSON.parse(await readFile(AUTH_SESSION_FILE, 'utf8'))).toMatchObject({ refreshToken: 'refresh-1' })+ await expect(manager.accessToken()).rejects.toMatchObject({ code: 'MISSING' })+ expect(refused).toHaveBeenCalledTimes(1)+ })++ // The app asks `auth status` often; each ask must not be a refresh request (review of #1866).+ it('a refused refresh is tried again a minute on, then twice as long each time, and a refresh that now works '+ + 'signs the computer back in', async () => {+ const at = 1_000_000+ writeAuthSession(baseSession())+ await markSignedOut('refresh-refused', at)+ const refused = vi.fn<typeof fetch>().mockImplementation(async () => refusal())+ vi.stubGlobal('fetch', refused)+ const manager = new AuthSessionManager('https://api.example.test')++ expect(await manager.retrySignedOut(at + 30_000)).toBe(false)+ expect(refused).not.toHaveBeenCalled()+ expect(await manager.retrySignedOut(at + 60_000)).toBe(false)+ expect(refused).toHaveBeenCalledTimes(1)+ expect(await manager.retrySignedOut(at + 60_000 + 119_000)).toBe(false)+ expect(refused).toHaveBeenCalledTimes(1)+ expect(readSignedOut()).toMatchObject({ reason: 'refresh-refused' })++ vi.stubGlobal('fetch', vi.fn<typeof fetch>().mockImplementation(async () => renewal()))+ expect(await manager.retrySignedOut(at + 60_000 + 120_000)).toBe(true)++ expect(readSignedOut()).toBeNull()+ expect(readAuthSession()).toMatchObject({ accessToken: 'renewed-access', refreshToken: 'refresh-2', machineId: 'machine-1' })+ })++ // Review of #1866: a revoke marked while another process refreshed was written over by that refresh's+ // save, and the revoked sign-in was used again.+ it('a revoke that lands while a refresh runs holds: the refresh saves first, and the mark stays', async () => {+ writeAuthSession(baseSession())+ let answer!: (response: Response) => void+ vi.stubGlobal('fetch', vi.fn<typeof fetch>().mockImplementation(() => new Promise<Response>((resolve) => { answer = resolve })))+ const refreshing = new AuthSessionManager('https://api.example.test').accessToken()+ await vi.waitFor(() => expect(answer).toBeTypeOf('function'))++ const marked = markSignedOut('revoked')+ answer(renewal())+ await refreshing+ await marked++ expect(readSignedOut()).toMatchObject({ reason: 'revoked' })expect(readAuthSession()).toBeNull()})++ // The daemon stops on a revoke and comes back signed out (core/main.ts `onRevoked`): it boots signed in+ // only on a sign-in it can read, and every request takes its token from here.+ it('a revoked sign-in is never acted on again: no token, no refresh, until a new sign-in', async () => {+ writeAuthSession({ ...baseSession(), expiresAt: Date.now() + 3_600_000 })+ await markSignedOut('revoked')+ const fetched = vi.fn<typeof fetch>()+ vi.stubGlobal('fetch', fetched)+ const manager = new AuthSessionManager('https://api.example.test')++ expect(hasAuthSession()).toBe(false)+ await expect(manager.accessToken()).rejects.toMatchObject({ code: 'MISSING' })+ await expect(manager.accessToken({ force: true })).rejects.toMatchObject({ code: 'MISSING' })+ expect(await manager.retrySignedOut()).toBe(false)++ expect(fetched).not.toHaveBeenCalled()+ expect(readSignedOut()).toMatchObject({ reason: 'revoked' })+ })++ it('a new sign-in replaces one marked signed out', async () => {+ writeAuthSession(baseSession())+ await markSignedOut('revoked')++ writeAuthSession({ ...baseSession(), accessToken: 'new-sign-in' })++ expect(readSignedOut()).toBeNull()+ expect(readAuthSession()).toMatchObject({ accessToken: 'new-sign-in' })+ })})diff --git a/cli/src/lib/authSession.ts b/cli/src/lib/authSession.tsindex 9f2e638c0..4fa8639af 100644--- a/cli/src/lib/authSession.ts+++ b/cli/src/lib/authSession.ts@@ -115,8 +115,35 @@ export function signInOf(epoch: string | undefined | null, acct?: string | null)return { epoch, adopted, at: at ? Number(at[1]) : null, ...(acct && !adopted ? { acct } : {}) }}+/** A sign-in's signed-out mark ([markSignedOut]): why and since when, and for a refused refresh, when it+ * may be tried again and how long the last wait was ([AuthSessionManager.retrySignedOut]). */+export interface SignedOutMark { at: number; reason: SignedOutReason; retryAt?: number; retryWait?: number }++/** The session on disk, and its signed-out mark when it has one ([markSignedOut]). */+function readStored(): { session: AuthSession; signedOut: SignedOutMark | null } | null {+ let raw: string+ try { raw = readFileSync(AUTH_SESSION_FILE, 'utf8') } catch { return null }+ const session = parse(raw)+ if (!session) return null+ let mark: unknown+ try { mark = (JSON.parse(raw) as { signedOut?: unknown }).signedOut } catch { mark = undefined }+ const signedOut = typeof mark === 'object' && mark !== null+ && ((mark as { reason?: unknown }).reason === 'refresh-refused' || (mark as { reason?: unknown }).reason === 'revoked')+ ? {+ at: Number((mark as { at?: unknown }).at) || 0,+ reason: (mark as { reason: SignedOutReason }).reason,+ ...(typeof (mark as { retryAt?: unknown }).retryAt === 'number' ? { retryAt: (mark as { retryAt: number }).retryAt } : {}),+ ...(typeof (mark as { retryWait?: unknown }).retryWait === 'number' ? { retryWait: (mark as { retryWait: number }).retryWait } : {}),+ }+ : null+ return { session, signedOut }+}++/** This computer's sign-in, or null when it has none, or has one marked signed out ([markSignedOut]): nothing+ * acts on that one again until a new sign-in replaces it. */export function readAuthSession(): AuthSession | null {- try { return parse(readFileSync(AUTH_SESSION_FILE, 'utf8')) } catch { return null }+ const stored = readStored()+ return stored && !stored.signedOut ? stored.session : null}export function hasAuthSession(): boolean { return readAuthSession() !== null }@@ -139,6 +166,42 @@ export function writeAuthSession(session: AuthSession): void {}}+/** Why a sign-in kept on disk is signed out: its refresh was refused, or it was revoked. */+export type SignedOutReason = 'refresh-refused' | 'revoked'++/**+ * Marks this computer's sign-in signed out, and keeps it. 10-27: a sign-out nobody asked for stalled a whole+ * Mac for hours. Nothing automatic deletes the sign-in any more (a refused refresh, a 401 or 403, a revoke):+ * it is marked instead, [readAuthSession] reads it as none, and a new sign-in's [writeAuthSession] replaces+ * it. Only a person deletes it (lib/signOut.ts `removeSignIn`). A refused refresh is tried again+ * ([AuthSessionManager.retrySignedOut]); a revoked one is not.+ */+export function markSignedOut(reason: SignedOutReason, at = Date.now()): Promise<void> {+ // Under the refresh lock: a refresh another process has under way saves its session when it is done, and a+ // mark written before that save was written over by it, and the revoked sign-in used again (review of #1866).+ return withLock(async () => markSignedOutHeld(reason, at))+}++/** The first wait before a refused refresh is tried again, and the longest. The app asks `auth status` often,+ * and each ask must not be a refresh request. */+const RETRY_FIRST_MS = 60_000+const RETRY_LONGEST_MS = 60 * 60_000++/** [markSignedOut], by a caller that holds the refresh lock already: the refresh that was refused. */+function markSignedOutHeld(reason: SignedOutReason, at: number): void {+ const stored = readStored()+ if (!stored || stored.signedOut) return+ const mark: SignedOutMark = reason === 'refresh-refused'+ ? { at, reason, retryAt: at + RETRY_FIRST_MS, retryWait: RETRY_FIRST_MS }+ : { at, reason }+ writeAuthSession({ ...stored.session, signedOut: mark } as AuthSession)+}++/** Why and since when this computer's sign-in is signed out, kept on disk; null when it is not. */+export function readSignedOut(): SignedOutMark | null {+ return readStored()?.signedOut ?? null+}+export function clearAuthSession(): void {try { rmSync(AUTH_SESSION_FILE, { force: true }) } catch { /* ignore */ }}@@ -301,7 +364,7 @@ export class AuthSessionManager {writeAuthSession(next)return next.accessToken} catch (err) {- if (err instanceof AuthSessionError && err.code === 'INVALID_REFRESH') clearAuthSession()+ if (err instanceof AuthSessionError && err.code === 'INVALID_REFRESH') markSignedOutHeld('refresh-refused', Date.now())throw err}})@@ -309,6 +372,39 @@ export class AuthSessionManager {try { return await running } finally { if (this.refreshInFlight === running) this.refreshInFlight = null }}+ /**+ * Tries a refused refresh again: the refusal may have been the service's, not the sign-in's. One that works+ * signs this computer back in. A revoked sign-in is never tried: it waits for a new one. True when the+ * computer is signed in again.+ */+ async retrySignedOut(now = Date.now()): Promise<boolean> {+ const due = (mark: SignedOutMark | null | undefined): boolean =>+ mark?.reason === 'refresh-refused' && now >= (mark.retryAt ?? 0)+ if (!due(readStored()?.signedOut)) return false+ return withLock(async () => {+ const stored = readStored()+ if (!stored || !stored.signedOut) return stored !== null+ const mark = stored.signedOut+ if (!due(mark)) return false+ try {+ const refreshed = await refreshRequest(this.backendBaseUrl, stored.session, this.opts.refreshTimeoutMs)+ writeAuthSession({+ ...stored.session,+ accessToken: refreshed.token,+ ...(refreshed.refreshToken ? { refreshToken: refreshed.refreshToken } : {}),+ ...(refreshed.expiresIn ? { expiresAt: Date.now() + refreshed.expiresIn * 1000 } : {}),+ updatedAt: Date.now(),+ })+ return true+ } catch {+ // Not yet: tried again after twice the last wait, at most an hour on.+ const wait = Math.min((mark.retryWait ?? RETRY_FIRST_MS) * 2, RETRY_LONGEST_MS)+ writeAuthSession({ ...stored.session, signedOut: { ...mark, retryAt: now + wait, retryWait: wait } } as AuthSession)+ return false+ }+ })+ }+updateMachineId(machineId: string): void {const current = readAuthSession()if (!current || current.machineId === machineId) returndiff --git a/cli/src/lib/signOut.spec.ts b/cli/src/lib/signOut.spec.tsnew file mode 100644index 000000000..c5c13da8e--- /dev/null+++ b/cli/src/lib/signOut.spec.ts@@ -0,0 +1,71 @@+import { describe, expect, it, vi } from 'vitest'+import { isDesktopApp, removalLine, SIGN_OUT_BUTTON_FLAG, signOutAsked, type Asker } from './signOut.js'++// 10-27: a desktop test ran the real `harness logout` and signed the whole Mac out. Only a person asks.+describe('who asked for the sign-in to go', () => {+ const shell: Asker = { pid: 10, command: '-zsh' }+ const tester: Asker = { pid: 11, command: '/Users/me/flutter/bin/cache/artifacts/engine/darwin-x64/flutter_tester --run-forever' }+ const app: Asker = { pid: 12, command: '/Applications/Harness.app/Contents/MacOS/Harness' }+ const never = (): boolean => false++ // Review of #1866: on Windows the processes above come from PowerShell, which takes a while; a terminal or+ // the button's flag decides without them.+ it('reads the processes above only when a terminal or the flag does not decide', () => {+ const above = vi.fn((): Asker[] => [tester])+ expect(signOutAsked({ interactive: false, flags: [SIGN_OUT_BUTTON_FLAG], ancestors: above, isApp: never })).toBe('sign-out button')+ expect(signOutAsked({ interactive: true, flags: [], ancestors: above, isApp: never })).toBe('terminal')+ expect(above).not.toHaveBeenCalled()++ expect(signOutAsked({ interactive: false, flags: [], ancestors: above, isApp: never })).toBeNull()+ expect(above).toHaveBeenCalledTimes(1)+ })++ it('a terminal is a person', () => {+ expect(signOutAsked({ interactive: true, flags: [], ancestors: () => [shell], isApp: never })).toBe('terminal')+ })++ it("the desktop app's Sign out button says so", () => {+ expect(signOutAsked({ interactive: false, flags: [SIGN_OUT_BUTTON_FLAG], ancestors: () => [], isApp: never })).toBe('sign-out button')+ })++ it('an app from before the flag is known by its process, above the CLI or its launcher', () => {+ const isApp = (asker: Asker): boolean => isDesktopApp(asker, 'darwin')+ expect(signOutAsked({ interactive: false, flags: [], ancestors: () => [app], isApp })).toBe('desktop app')+ expect(signOutAsked({ interactive: false, flags: [], ancestors: () => [{ pid: 13, command: '/bin/sh /Users/me/.local/bin/harness logout' }, app], isApp })).toBe('desktop app')+ })++ it.runIf(process.platform === 'darwin')('by default, the app is known on this platform', () => {+ expect(signOutAsked({ interactive: false, flags: [], ancestors: () => [shell, app] })).toBe('desktop app')+ expect(signOutAsked({ interactive: false, flags: [], ancestors: () => [tester, shell] })).toBeNull()+ })++ it('a test, an agent or a script with no terminal and no flag is not', () => {+ const isApp = (asker: Asker): boolean => isDesktopApp(asker, 'darwin')+ expect(signOutAsked({ interactive: false, flags: ['--json'], ancestors: () => [tester, shell], isApp })).toBeNull()+ })++ it.each([+ ['darwin', '/Applications/Harness.app/Contents/MacOS/Harness', true],+ ['darwin', '/Users/me/build/Harness Dev.app/Contents/MacOS/Harness Dev', true],+ ['darwin', '/Users/me/.local/bin/harness logout', false],+ ['win32', '"C:\\Program Files\\Harness\\harness-desktop.exe"', true],+ ['win32', 'C:\\Users\\me\\.harness\\bin\\harness.exe logout', false],+ ] as const)('on %s, %s is the desktop app: %s', (platform, command, expected) => {+ expect(isDesktopApp({ pid: 99_999_999, command }, platform)).toBe(expected)+ })+})++describe("harness.log's line for a removal", () => {+ it('says why, how a person asked, and every process from the command up', () => {+ const line = removalLine({+ reason: 'logout',+ asked: 'terminal',+ self: { pid: 3, command: 'node cli.js logout' },+ ancestors: [{ pid: 2, command: '-zsh' }, { pid: 1, command: 'tmux' }],+ now: new Date(2026, 9, 27, 6, 45, 20, 22),+ })++ expect(line).toBe('2026-10-27 06:45:20.022 [auth] sign-in removed · reason=logout · asked=terminal · '+ + 'pid=3 (node cli.js logout) · parent=2 (-zsh) · above=1 (tmux)')+ })+})diff --git a/cli/src/lib/signOut.ts b/cli/src/lib/signOut.tsnew file mode 100644index 000000000..06f8aaafd--- /dev/null+++ b/cli/src/lib/signOut.ts@@ -0,0 +1,135 @@+/**+ * Who may take this computer's sign-in away, and the record of each time it goes.+ *+ * 10-27: a desktop test ran the real `harness logout` with no person anywhere near it, seven times, and each+ * run signed the whole Mac out, every agent on it with it, for hours. The sign-in now goes only when a person+ * asks for it on this computer: at a terminal, or through the desktop app's Sign out button, which says so+ * with [SIGN_OUT_BUTTON_FLAG]. An app from before the flag is known by its process. Nothing automatic deletes+ * it (an expired token, a refused refresh, a revoke): those report the computer signed out and wait for a+ * sign-in. Every removal is written to harness.log with the command and the processes above it.+ */+import { execFileSync } from 'child_process'+import { appendFileSync, existsSync, mkdirSync, readlinkSync } from 'fs'+import { dirname, join } from 'path'+import { env } from '../config/env.js'+import { clearAuthSession } from './authSession.js'++/** What the desktop app's Sign out button passes to `harness logout`: a person asked, in the app. */+export const SIGN_OUT_BUTTON_FLAG = '--from-sign-out-button'++/** A process, as harness.log names it. */+export interface Asker { pid: number; command: string }++/** How a person asked: at a terminal, with the app's button, or through an app from before the flag. */+export type SignOutAsked = 'terminal' | 'sign-out button' | 'desktop app'++/**+ * How a person asked for the sign-in to go, or null when nothing says one did: a test, an agent, a script.+ * [ancestors] reads the processes above this one, nearest first, and is called only when the button's flag+ * or a terminal has not decided: on Windows it asks PowerShell, which takes a while (review of #1866).+ */+export function signOutAsked(opts: {+ interactive: boolean+ flags: readonly string[]+ ancestors: () => readonly Asker[]+ isApp?: (asker: Asker) => boolean+}): SignOutAsked | null {+ if (opts.flags.includes(SIGN_OUT_BUTTON_FLAG)) return 'sign-out button'+ if (opts.interactive) return 'terminal'+ const isApp = opts.isApp ?? ((asker: Asker): boolean => isDesktopApp(asker))+ if (opts.ancestors().some((asker) => isApp(asker))) return 'desktop app'+ return null+}++/** [ancestors], read at most once: what decides a sign-out and what its log line names are the same. */+export function ancestorsOnce(): () => Asker[] {+ let read: Asker[] | undefined+ return () => read ??= ancestors()+}++/**+ * Whether [asker] is the Harness desktop app. On a Mac its bundle's executable; on Windows `harness-desktop.exe`.+ * Linux names the app `harness`, as the CLI is, so there it is the `harness` that sits beside a Flutter bundle.+ */+export function isDesktopApp(asker: Asker, platform: NodeJS.Platform = process.platform): boolean {+ if (platform === 'darwin') return /\/Harness[^/]*\.app\/Contents\/MacOS\//.test(asker.command)+ if (platform === 'win32') return /(^|[\\/"])harness-desktop\.exe\b/i.test(asker.command)+ try {+ return existsSync(join(dirname(readlinkSync(`/proc/${asker.pid}/exe`)), 'data', 'flutter_assets'))+ } catch {+ return false+ }+}++/** The processes above this one, nearest first, at most [depth]: who ran this command, and who ran that. */+export function ancestors(depth = 3): Asker[] {+ const found: Asker[] = []+ let pid = process.ppid+ for (let i = 0; i < depth && pid > 1; i++) {+ const read = readProcess(pid)+ if (!read) break+ found.push({ pid, command: read.command })+ pid = read.parent+ }+ return found+}++function readProcess(pid: number): { parent: number; command: string } | null {+ try {+ if (process.platform === 'win32') {+ const out = execFileSync('powershell.exe', [+ '-NoProfile', '-NonInteractive', '-Command',+ `Get-CimInstance Win32_Process -Filter "ProcessId=${pid}" | Select-Object ParentProcessId,CommandLine | ConvertTo-Json -Compress`,+ ], { encoding: 'utf8', timeout: 5_000, windowsHide: true })+ const row = JSON.parse(out) as { ParentProcessId?: number; CommandLine?: string | null }+ return { parent: row.ParentProcessId ?? 0, command: row.CommandLine ?? '' }+ }+ const out = execFileSync('ps', ['-o', 'ppid=,command=', '-p', String(pid)], { encoding: 'utf8', timeout: 5_000 })+ const match = /^\s*(\d+)\s+(.*)$/.exec(out.trim())+ return match ? { parent: Number(match[1]), command: match[2] } : null+ } catch {+ return null+ }+}++/** The line harness.log gets for one removal of the sign-in: why, how a person asked, and who ran it. */+export function removalLine(opts: {+ reason: string+ asked: string+ self: Asker+ ancestors: readonly Asker[]+ now?: Date+}): string {+ const [parent, ...above] = opts.ancestors+ const named = (asker: Asker): string => `${asker.pid} (${asker.command || 'unknown'})`+ return [+ `${stamp(opts.now ?? new Date())} [auth] sign-in removed`,+ `reason=${opts.reason}`,+ `asked=${opts.asked}`,+ `pid=${named(opts.self)}`,+ `parent=${parent ? named(parent) : 'unknown'}`,+ ...above.map((asker) => `above=${named(asker)}`),+ ].join(' · ')+}++/** harness.log's own time format: local time, to the millisecond. */+function stamp(at: Date): string {+ const two = (n: number): string => String(n).padStart(2, '0')+ return `${at.getFullYear()}-${two(at.getMonth() + 1)}-${two(at.getDate())} `+ + `${two(at.getHours())}:${two(at.getMinutes())}:${two(at.getSeconds())}.${String(at.getMilliseconds()).padStart(3, '0')}`+}++/**+ * Takes this computer's sign-in away, after writing to harness.log why, how a person asked, and which+ * processes ran it. The one way the CLI deletes it: [signOutAsked] said a person asked first. A log that+ * cannot be written does not keep the person signed in.+ */+export function removeSignIn(reason: string, asked: SignOutAsked, chain: () => readonly Asker[] = ancestorsOnce()): void {+ try {+ const self = { pid: process.pid, command: process.argv.join(' ') }+ // `harness reset` has just emptied the folder the log lives in.+ mkdirSync(env.ADAPTER_DATA_DIR, { recursive: true })+ appendFileSync(join(env.ADAPTER_DATA_DIR, 'harness.log'), removalLine({ reason, asked, self, ancestors: chain() }) + '\n')+ } catch { /* the log is a record, not a gate */ }+ clearAuthSession()+}diff --git a/cli/src/team/command.spec.ts b/cli/src/team/command.spec.tsindex 938b17870..2d1784f99 100644--- a/cli/src/team/command.spec.ts+++ b/cli/src/team/command.spec.ts@@ -3,6 +3,7 @@*/import { describe, expect, it, vi } from 'vitest'import type { AuthSession } from '../lib/authSession.js'+import { SIGN_OUT_BUTTON_FLAG, signOutAsked } from '../lib/signOut.js'import type { AdminScript, RunAdmin } from './admin.js'import { REPAIR_PROMPT, SETUP_PROMPT, teamCommand, type TeamCommandDeps } from './command.js'import type { TeamConfig } from './config.js'@@ -47,7 +48,8 @@ function fake(over: Partial<TeamCommandDeps> & { adminResult?: Awaited<ReturnTypout: (line) => out.push(line), err: (line) => err.push(line),user: () => 'owner-placeholder', home: () => OWNER_HOME, uid: () => 501, hostname: () => 'Mac-placeholder',env: {}, interactive: false, ask: vi.fn(async () => 'y'), now: () => now, sleep: vi.fn(async (ms: number) => { now += ms }),- session: () => session, writeSession: vi.fn((s: AuthSession) => { session = s }), clearSession: vi.fn(() => { session = null }),+ session: () => session, writeSession: vi.fn((s: AuthSession) => { session = s }), signOutAsked: (flags) => signOutAsked({ interactive: over.interactive ?? false, flags, ancestors: () => [], isApp: () => false }),+ removeSignIn: vi.fn(() => { session = null }),auth: vi.fn(async () => ({ session: session!, headers: { authorization: 'Bearer x' } })), post: post as never,get: vi.fn(async (path: string) => path === '/api/machines' ? { machines: MACHINES } : { user: { id: 'user-placeholder-1' } }) as never,delete: vi.fn(async () => ({ deleted: true })) as never, machineKey: () => ({ priv: new Uint8Array(32).fill(9) }),@@ -463,6 +465,21 @@ describe('harness team on and off', () => {expect(old.deps.startDaemon).toHaveBeenCalled()})+ // 10-27: a sign-out nobody asked for (a desktop test's `harness logout`) signed a whole Mac out. `team off`+ // takes the sign-in away too, so it asks the same: a terminal, or the flag a person's button passes.+ it('off with no terminal and no flag refuses, and keeps the team sign-in and its refresh token', async () => {+ const f = fake()+ const team = { ...computer, kind: 'team' as const, refreshToken: 'htr_team' }+ f.setSession(team)++ expect(await teamCommand(['off'], f.deps)).toBe(1)++ expect(f.session()).toEqual(team)+ expect(f.post).not.toHaveBeenCalledWith('/api/auth/revoke', expect.anything())+ expect(f.deps.stopDaemon).not.toHaveBeenCalled()+ expect(f.err.join('\n')).toContain('--from-sign-out-button')+ })+it('off: signs the team session out, then the ordinary sign-in at a terminal, or says how', async () => {const signIn = vi.fn(async () => {})const f = fake({ interactive: true, signIn })@@ -473,12 +490,12 @@ describe('harness team on and off', () => {expect(signIn).toHaveBeenCalledWith(true)const quiet = fake()quiet.setSession({ ...computer, kind: 'team' })- expect(await teamCommand(['off'], quiet.deps)).toBe(0)+ expect(await teamCommand(['off', SIGN_OUT_BUTTON_FLAG], quiet.deps)).toBe(0)expect(quiet.out.join('\n')).toContain('harness login')expect(quiet.deps.startDaemon).toHaveBeenCalled()const json = fake()json.setSession({ ...computer, kind: 'team' })- expect(await teamCommand(['off', '--json'], json.deps)).toBe(0)+ expect(await teamCommand(['off', '--json', SIGN_OUT_BUTTON_FLAG], json.deps)).toBe(0)expect(JSON.parse(json.out[0]!)).toMatchObject({ ok: true, changed: true, next: 'harness login' })const notTeam = fake()expect(await teamCommand(['off'], notTeam.deps)).toBe(0)diff --git a/cli/src/team/command.ts b/cli/src/team/command.tsindex dbe38b3ea..235477b10 100644--- a/cli/src/team/command.ts+++ b/cli/src/team/command.ts@@ -13,6 +13,7 @@* team work does not run as the owner instead.*/import type { AuthSession } from '../lib/authSession.js'+import { SIGN_OUT_BUTTON_FLAG, type SignOutAsked } from '../lib/signOut.js'import type { RunAdmin } from './admin.js'import { teamConfigJson, type TeamConfig } from './config.js'import { engineLines, type TeamEngines } from './engines.js'@@ -78,7 +79,10 @@ export interface TeamCommandDeps {session(): AuthSession | nullwriteSession(session: AuthSession): void- clearSession(): void+ /** How a person asked for this computer's sign-in to go, or null when nothing says one did (lib/signOut.ts). */+ signOutAsked(flags: readonly string[]): SignOutAsked | null+ /** Takes the sign-in away, logged with who asked (lib/signOut.ts `removeSignIn`). */+ removeSignIn(asked: SignOutAsked): void/** Bearer headers for this computer's sign-in, refreshed when stale (lib/controlPlane.ts). */auth(): Promise<{ session: AuthSession; headers: Record<string, string> }>post: Post@@ -131,7 +135,7 @@ export async function teamCommand(argv: string[], deps: TeamCommandDeps): Promiscase 'status': return await status(deps, json)case 'remove': return await remove(deps, json)case 'on': return await teamOn(deps, json, flags.includes('--yes'))- case 'off': return await teamOff(deps, json)+ case 'off': return await teamOff(deps, json, flags)case '__handoff': return await handoff(deps)case '__start': return await jobStart(deps, words[1])default:@@ -455,16 +459,22 @@ async function teamOn(deps: TeamCommandDeps, json: boolean, yes: boolean): Promireturn 0}-async function teamOff(deps: TeamCommandDeps, json: boolean): Promise<number> {+async function teamOff(deps: TeamCommandDeps, json: boolean, flags: readonly string[]): Promise<number> {const session = deps.session()if (session?.kind !== 'team') {if (json) deps.out(JSON.stringify({ ok: true, changed: false }))else deps.out('This computer does not run team work only; nothing to change.')return 0}+ // Before anything stops or is revoked. 10-27: a `harness logout` nobody asked for signed a whole Mac out.+ const asked = deps.signOutAsked(flags)+ if (!asked) {+ return fail(deps, json, 'NOT_A_PERSON', '`harness team off` signs this computer out, and nothing says a person '+ + `asked: it has no terminal, and no ${SIGN_OUT_BUTTON_FLAG}. Run it in a terminal.`)+ }const wasRunning = await deps.stopDaemon()await revokeHarnessRefresh(deps.post, session.refreshToken)- deps.clearSession()+ deps.removeSignIn(asked)if (json) {deps.out(JSON.stringify({ ok: true, changed: true, next: 'harness login' }))if (wasRunning) await deps.startDaemon()diff --git a/cli/src/team/deps.ts b/cli/src/team/deps.tsindex 9afad3049..b53f792b7 100644--- a/cli/src/team/deps.ts+++ b/cli/src/team/deps.ts@@ -4,13 +4,14 @@ import { homedir, hostname, userInfo } from 'node:os'import { dirname, join } from 'node:path'import { createInterface } from 'node:readline'import { env } from '../config/env.js'-import { clearAuthSession, readAuthSession, writeAuthSession } from '../lib/authSession.js'+import { readAuthSession, writeAuthSession } from '../lib/authSession.js'import { controlPlaneAuth, postJson, requestJson } from '../lib/controlPlane.js'import { computerId } from '../lib/daemonState.js'import { peekIdentity } from '../lib/e2ee/store.js'import { runGuestCommand, type GuestRunner } from '../lib/guestAccounts.js'import { managedNodeRuntimeDir } from '../lib/guestHelperInstall.js'import { managedNodePath } from '../lib/nodeRuntime.js'+import { ancestorsOnce, removeSignIn, signOutAsked } from '../lib/signOut.js'import { managedTmuxPath } from '../lib/tmuxOnPath.js'import { adminRunner } from './admin.js'import type { JobState, TeamCommandDeps } from './command.js'@@ -35,6 +36,8 @@ export function teamCommandDeps(options: {runner?: GuestRunner}): TeamCommandDeps {const runner = options.runner ?? runGuestCommand+ // Read once: the same processes decide whether a person asked and are named in the log.+ const chain = ancestorsOnce()return {platform: process.platform,out: (line) => console.log(line),@@ -53,7 +56,8 @@ export function teamCommandDeps(options: {sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),session: readAuthSession,writeSession: writeAuthSession,- clearSession: clearAuthSession,+ signOutAsked: (flags) => signOutAsked({ interactive: process.stdin.isTTY === true, flags, ancestors: chain }),+ removeSignIn: (asked) => removeSignIn('team off', asked, chain),auth: controlPlaneAuth,post: (path, body, headers) => postJson(path, body, headers ?? {}),get: (path, headers) => requestJson('GET', path, undefined, headers ?? {}),diff --git a/desktop/lib/auth/cli_login.dart b/desktop/lib/auth/cli_login.dartindex 68726ace7..82f181ca4 100644--- a/desktop/lib/auth/cli_login.dart+++ b/desktop/lib/auth/cli_login.dart@@ -5,6 +5,7 @@ import 'dart:io';import 'package:flutter/foundation.dart';import '../core/harness_cli_runner.dart';+import '../core/test_run.dart';import 'phone_sign_in.dart';import 'sign_in_client.dart';import 'sign_in_provider.dart';@@ -46,6 +47,17 @@ class CliNotAvailableException implements Exception {String toString() => message;}+/// A test signed out through the real Harness CLI: `harness logout` would sign this computer out+/// for real, and every agent on it with it (10-27). An [Error], not an exception: the test is wrong,+/// and nothing should catch this and carry on.+class CliSignOutUnderTestError extends Error {+ @override+ String toString() =>+ 'A test signed out through the real Harness CLI, which would sign this computer out for '+ 'real. Give the app a fake sign-in client (AppNotifier(cliLogin: ...)), or CliLogin a fake '+ 'runner.';+}+/// Talks to the local `harness` CLI for everything auth-related: whether this computer already has a/// signed-in session, and driving `harness login --json`'s NDJSON event stream when it does not. The/// CLI owns the SSO session end to end (`~/.harness/auth/session.json`) — this app never sees, stores,@@ -55,7 +67,10 @@ class CliLogin implements SignInClient, PhoneSignInClient {Process? _activeProcess;int _loginRevision = 0;- CliLogin({HarnessCliRunner? runner}) : _runner = runner ?? HarnessCliRunner();+ /// Under flutter test with no [runner], one that runs nothing ([_NoCliUnderTest]): a test must+ /// not reach this computer's real CLI, whose `harness logout` signs the whole computer out.+ CliLogin({HarnessCliRunner? runner})+ : _runner = runner ?? (kUnderTest ? _NoCliUnderTest() : 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@@ -228,11 +243,20 @@ class CliLogin implements SignInClient, PhoneSignInClient {@overrideFuture<void> logout() async {+ if (_runner is _NoCliUnderTest) {+ // Reported to the test's zone as well as thrown: the app's sign-out catches what this throws+ // and shows "could not be cleared", which a test can pass straight through.+ final error = CliSignOutUnderTestError();+ Zone.current.handleUncaughtError(error, StackTrace.current);+ throw error;+ }// Own a process handle: a timed-out logout must not remain alive and erase// the credentials saved by the user's next sign-in.final Process process;try {- process = await _runner.start(['logout']);+ // A person pressed Sign out: the CLI refuses a sign-out nothing says a person asked for (10-27, when+ // a test's `harness logout` signed a whole Mac out). A CLI from before the flag ignores it.+ process = await _runner.start(['logout', '--from-sign-out-button']);} catch (error) {throw CliNotAvailableException('Could not run the harness CLI: $error');}@@ -271,3 +295,21 @@ class CliLogin implements SignInClient, PhoneSignInClient {return lines.isEmpty ? null : lines.last.trim();}}++/// [CliLogin]'s runner under flutter test when a test gives none: the CLI reads as not installed+/// here, as on a computer without Harness (CI), and nothing is ever run.+class _NoCliUnderTest extends HarnessCliRunner {+ ProcessException _refused(List<String> arguments) => ProcessException(+ 'harness',+ arguments,+ 'The real Harness CLI is never run under flutter test.',+ );++ @override+ Future<ProcessResult> run(List<String> arguments) async =>+ throw _refused(arguments);++ @override+ Future<Process> start(List<String> arguments) async =>+ throw _refused(arguments);+}diff --git a/desktop/lib/core/harness_cli_runner.dart b/desktop/lib/core/harness_cli_runner.dartindex 504b85bd6..c59705670 100644--- a/desktop/lib/core/harness_cli_runner.dart+++ b/desktop/lib/core/harness_cli_runner.dart@@ -5,6 +5,7 @@ import 'package:path/path.dart' as p;import '../logging/cli_transcript.dart';import 'hidden_process.dart';import 'home_dir.dart';+import 'test_run.dart';import 'windows_layout.dart';/// Runs the Harness CLI owned by this desktop app without depending on a@@ -86,7 +87,26 @@ class HarnessCliRunner {),),_runProcess = runProcess ?? runHidden,- _startProcess = startProcess ?? startHidden;+ _startProcess = startProcess ?? startHidden,+ _realRun = runProcess == null,+ _realStart = startProcess == null;++ /// Whether [run] and [start] would spawn the real CLI: no process functions were given. Under+ /// flutter test they refuse instead ([_refuseUnderTest]).+ final bool _realRun, _realStart;++ /// 10-27: a test reached this computer's real CLI, and its `harness logout` signed the whole+ /// computer out. A test supplies its own process functions, or gets what a computer without the+ /// CLI gives (CI): a [ProcessException].+ void _refuseUnderTest(bool real, List<String> arguments) {+ if (!real || !kUnderTest) return;+ throw ProcessException(+ 'harness',+ arguments,+ 'The real Harness CLI is never run under flutter test: give the runner its own process '+ 'functions.',+ );+ }Directory get _runtimeDirectory =>Directory('${harnessHome.path}${Platform.pathSeparator}runtime');@@ -190,6 +210,7 @@ class HarnessCliRunner {}Future<ProcessResult> run(List<String> arguments) async {+ _refuseUnderTest(_realRun, arguments);final invocation = await resolve(arguments);return logProcessRun(_displayLine(arguments),@@ -212,6 +233,7 @@ class HarnessCliRunner {}Future<Process> start(List<String> arguments) async {+ _refuseUnderTest(_realStart, arguments);final invocation = await resolve(arguments);return logProcessStart(_displayLine(arguments),diff --git a/desktop/test/cli_login_test.dart b/desktop/test/cli_login_test.dartindex cca5907f9..30a3fafe4 100644--- a/desktop/test/cli_login_test.dart+++ b/desktop/test/cli_login_test.dart@@ -7,6 +7,8 @@ import 'package:harness/auth/cli_login.dart';import 'package:harness/auth/sign_in_provider.dart';import 'package:harness/core/harness_cli_runner.dart';+import 'swarm_state_test.dart' show createApp;+class _Runner extends HarnessCliRunner {_Runner({this.method = const []});@@ -91,6 +93,54 @@ class _TimeoutProcess extends _Process {}void main() {+ // 10-27: a test signed the app out with no fake sign-in client, which ran the+ // real `harness logout` and signed the whole Mac out, again on every run.+ group('under flutter test, with no runner given', () {+ /// What [body] threw, and the errors it reported to its zone, where the+ /// test framework fails the test on them.+ Future<(Object?, List<Object>)> guarded(Future<void> Function() body) {+ final reported = <Object>[];+ final done = Completer<Object?>();+ runZonedGuarded(() async {+ try {+ await body();+ done.complete(null);+ } catch (error) {+ done.complete(error);+ }+ }, (error, _) => reported.add(error));+ return done.future.then((thrown) => (thrown, reported));+ }++ test('it never runs the real CLI: it reads as no CLI here', () async {+ await expectLater(+ CliLogin().checkStatus(),+ throwsA(isA<CliNotAvailableException>()),+ );+ });++ test('signing out fails the test loudly, and runs nothing', () async {+ final (thrown, reported) = await guarded(() => CliLogin().logout());++ expect(thrown, isA<CliSignOutUnderTestError>());+ expect(reported, [isA<CliSignOutUnderTestError>()]);+ });++ test('an app signed out with no fake sign-in client fails the test '+ 'loudly', () async {+ final app = createApp();+ addTearDown(app.dispose);++ final (_, reported) = await guarded(app.logout);++ expect(reported, [isA<CliSignOutUnderTestError>()]);+ expect(+ reported.single.toString(),+ contains('would sign this computer out'),+ );+ });+ });+test('logout reports a nonzero CLI exit as a failure', () async {final process = _Process()..finish(1);final runner = _LogoutRunner(process);@@ -112,8 +162,10 @@ void main() {process.errors.add(utf8.encode('fixture diagnostic'));process.finish();await pending;+ // A person asked, with the app's Sign out button: the CLI refuses a sign-out nothing says a+ // person asked for (10-27).expect(runner.arguments, [- ['logout'],+ ['logout', '--from-sign-out-button'],]);},);diff --git a/desktop/test/harness_cli_runner_test.dart b/desktop/test/harness_cli_runner_test.dartindex 29e956e0c..78406b9f8 100644--- a/desktop/test/harness_cli_runner_test.dart+++ b/desktop/test/harness_cli_runner_test.dart@@ -16,6 +16,36 @@ void main() {if (await scratch.exists()) await scratch.delete(recursive: true);});+ // 10-27: a test reached this computer's real CLI and signed it out. `harness stop` and `start`+ // from a test would take its daemon down the same way.+ test('under flutter test, a runner with the real process functions runs '+ 'nothing', () async {+ final home = Directory('${scratch.path}/home')..createSync();+ final harnessHome = Directory('${home.path}/.harness')..createSync();+ final calls = File('${scratch.path}/calls.txt');+ // A stand-in for the managed Node: it only writes down what it was asked.+ final node = File('${harnessHome.path}/runtime/node-v22/bin/node')+ ..createSync(recursive: true)+ ..writeAsStringSync('#!/bin/sh\necho "\$@" >> ${calls.path}\n');+ await Process.run('chmod', ['+x', node.path]);+ File('${harnessHome.path}/runtime/current-node')+ ..createSync(recursive: true)+ ..writeAsStringSync('${node.path}\n');+ File('${harnessHome.path}/cli/cli.js').createSync(recursive: true);+ final runner = HarnessCliRunner(+ harnessHome: harnessHome,+ environment: {'HOME': home.path, 'PATH': '/usr/bin'},+ isWindows: false,+ );++ await expectLater(runner.run(['stop']), throwsA(isA<ProcessException>()));+ await expectLater(+ runner.start(['logout']),+ throwsA(isA<ProcessException>()),+ );+ expect(calls.existsSync(), isFalse, reason: 'nothing was run');+ }, skip: Platform.isWindows);+test('uses the managed Node runtime and CLI bundle without a shell',() async {