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
feat: Harness opens without an account; sign in when reaching for another machine
0xdiego2508b2efdde624
diff --git a/cli/src/authCommand.spec.ts b/cli/src/authCommand.spec.tsindex 5dd562fe3..8ca78c6ae 100644--- a/cli/src/authCommand.spec.ts+++ b/cli/src/authCommand.spec.ts@@ -120,7 +120,11 @@ describe('harness auth status --json', () => {const root = tempRoot()const result = runSync(root, ['auth', 'status', '--json'], 'http://127.0.0.1:1') // port 1: would fail fast if ever calledexpect(result.status).toBe(0)- expect(JSON.parse(result.stdout.trim())).toEqual({ loggedIn: false })+ // The computer id travels even signed out: the daemon serves this computer under it until a+ // sign-in hands out a machineId, and the app keys the local machine by whichever it is told.+ const body = JSON.parse(result.stdout.trim()) as { loggedIn: boolean; computerId?: string }+ expect(body.loggedIn).toBe(false)+ expect(body.computerId).toMatch(/^[0-9a-f-]{36}$/)})it('falls back to human text without --json', () => {diff --git a/cli/src/cable/cableHost.ts b/cli/src/cable/cableHost.tsindex f9ca10fcc..8f28dd5df 100644--- a/cli/src/cable/cableHost.ts+++ b/cli/src/cable/cableHost.ts@@ -37,6 +37,9 @@ export interface CableHostWiring {machineId: () => string/** A stable id for this computer, used to name the local row when there is no machineId yet. */computerId: () => string+ /** Whether this computer holds an account. False → the dial serves THIS computer alone: the cloud+ * lane (the other machines, and voice) is what an account buys, and it is not dialled without one. */+ signedIn?: () => boolean/** Deliver text into an agent. The SAME path the web and the WiFi device use — see cli.ts. */sendTurn: (agentId: string, text: string) => voidstopTurn: (agentId: string) => void@@ -209,6 +212,13 @@ export class DaemonCableHost implements CableHost {onDialAttached(): void {if (!this.fleet) returnconst fleet = this.fleet+ // Signed out there is no lane to open: the socket is authenticated, so dialling it would fail once+ // per plug-in and log a failure for something nobody asked for. The dial still works — it is on the+ // cable, and everything it shows on this computer is served in-process.+ if (this.wiring.signedIn?.() === false) {+ this.wiring.log('cable: dial on the wire — this computer only (not signed in)')+ return+ }this.wiring.log('cable: dial on the wire — opening the cloud lane')void (async () => {// The socket first, and unconditionally: it is what makes the machine wheel's dots live, and it is@@ -894,7 +904,9 @@ export class DaemonCableHost implements CableHost {*/async transcribe(pcm: Buffer, sampleRate: number, lang: string): Promise<string> {const session = readAuthSession()- if (!session) throw new Error('Voice needs a signed-in harness — run `harness login`')+ // The text reaches the dial's glass as a toast, so it is addressed to the person holding it, not to+ // a terminal: signing in happens on the computer, and that is the one thing they need to know.+ if (!session) throw new Error('Sign in on your computer to use voice')const auth = new AuthSessionManager(this.backendHttpBase())const url = `${this.backendHttpBase()}${env.CABLE_STT_PATH}?lang=${encodeURIComponent(lang)}`diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex 525b1e806..6eccbb45a 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -531,7 +531,9 @@ async function resolveComputerMachine(signal?: AbortSignal): Promise<AuthSessionasync function authStatusCommand(json: boolean): Promise<void> {const session = readAuthSession()if (!session) {- if (json) console.log(JSON.stringify({ loggedIn: false }))+ // 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() }))else console.log('\n ✗ Not signed in. Run: harness login\n')return}@@ -717,7 +719,11 @@ async function loginCommand(installing?.catch(() => { /* reported where it is awaited */ })try {return await withSpawnLock('login', async () => {- await stopDaemonProcess()+ // ⚠️ A daemon running WITHOUT a session holds no account to switch away from, and stopping it+ // here would take every local terminal on this computer down for as long as the person is in+ // the browser. There is nothing to race either: the lock is held, and the identity swap happens+ // afterwards, once there is an identity to swap to (`restartDaemonForIdentity`).+ if (readAuthSession()) await stopDaemonProcess()return await browserSignIn(json, emit, () => succeed(false, installing), entryPoint)}, {onWaiting: (owner) => console.error(` the daemon is ${describeSpawnLockOwner(owner)} — waiting for it to finish…`),@@ -790,7 +796,7 @@ async function browserSignIn(const manual = !json && process.stdin.isTTY ? promptForCallbackUrl(redirectUri) : nulllet callbackResult: { code: string; state: string }try {- callbackResult = await awaitLoginCallback({ server: callback, redirectUri, manual: manual?.promise ?? null, timeoutMs: 5 * 60_000 })+ callbackResult = await awaitLoginCallback({ server: callback, redirectUri, manual: manual?.promise ?? null, timeoutMs: 5 * 60_000, entryPoint })} catch (err) {const timedOut = (err as Error).message === LOGIN_TIMEOUT_MESSAGEif (json) { emit({ type: 'result', status: 'error', code: timedOut ? 'TIMEOUT' : 'CALLBACK_ERROR', message: (err as Error).message }); process.exitCode = 1; return { signedIn: false } }@@ -986,13 +992,22 @@ function openInBrowser(url: string): void {} catch { /* ignore */ }}-/** Start the adapter from a saved SSO session. Missing credentials never open a browser implicitly. */+/**+ * Start the adapter, with the saved SSO session when there is one. Missing credentials never open a+ * browser implicitly — and are no longer a refusal.+ *+ * ⚠️ **A DAEMON RUNS WITHOUT AN ACCOUNT.** Everything on this computer — discovery, terminals, hooks,+ * recaps, DSH, the cabled dial — is served by this process over the loopback and never touches the+ * backend. What an account adds is the OTHER machines (the relay, the link ceremony), the shared desk,+ * voice on the dial and the profile; those are bought at the moment they are reached for. Refusing to+ * start without one put a browser sign-in in front of every local thing the product does on day one.+ *+ * Signed out, the identity is this computer's durable id (`computerId()`, minted before any account and+ * the very value the backend binds a machine to at login) — so a later sign-in ADOPTS this machine+ * rather than replacing it.+ */async function startCommand(foreground: boolean, repair: boolean = false): Promise<void> {const session = readAuthSession()- if (!session) {- console.error('\n ✗ Not signed in. Run: harness login\n')- process.exit(1)- }// The session file is the ONLY thing `start` needs. It used to pull the newest bundle and resolve// this computer's machine against the backend before launching — so a computer that could not reach// the backend could not start its daemon at all (a black-holed link hung here forever, and the@@ -1012,7 +1027,9 @@ async function startCommand(foreground: boolean, repair: boolean = false): Promi// there, with `auth status` naming the new machine and the socket serving the old one. Asked// of the daemon itself; one that cannot answer (still booting, mid-update) is trusted as before.const serving = (await runningDaemonStatus())?.machineId- if (!serving || !session.machineId || serving === session.machineId) {+ // Signed out, the daemon serves this computer under its own id and there is no account to be on+ // the wrong one of — `wantedDaemonIdentity` is the same answer `restartDaemonForIdentity` uses.+ if (!serving || serving === wantedDaemonIdentity()) {// `--repair` still does its provisioning here: it touches the managed runtimes, never the// bundle, and the live daemon picks a grid laid down now up on its next resolve (see// repairManagedRuntimes). Without this, a new pin could only be followed by a restart.@@ -1025,7 +1042,7 @@ async function startCommand(foreground: boolean, repair: boolean = false): Promiawait stopDaemonProcess()}await withSpawnLock('start', async () => {- await resolveMachineIfUnknown(session)+ if (session) await resolveMachineIfUnknown(session)await launch(foreground, repair)}, {onWaiting: (owner) => console.log(` the daemon is ${describeSpawnLockOwner(owner)} — waiting for it to finish…`),@@ -1037,10 +1054,22 @@ async function startCommand(foreground: boolean, repair: boolean = false): Promi})return}- await resolveMachineIfUnknown(session)+ if (session) await resolveMachineIfUnknown(session)await launch(foreground, repair)}+/**+ * The id a daemon started right now would serve under: the account's machine when this computer is+ * signed in, its own durable computer id when it is not.+ *+ * One function because three callers must agree on it — `start` (is the running daemon the right one?),+ * `restartDaemonForIdentity` (must it be swapped?) and the daemon itself (what does it boot as?). They+ * disagreeing is how a window ends up asking a daemon for a machine it does not serve.+ */+function wantedDaemonIdentity(): string {+ return readAuthSession()?.machineId || computerId()+}+/*** The one backend round trip `start` may still make, and only when the session has no machine id —* a file written by a build that predates login resolving it. Bounded, and never fatal: the daemon@@ -1116,7 +1145,6 @@ async function updateCommand(force: boolean): Promise<void> {const running = readPid()const wasRunning = !!(running && isAlive(running))const relaunch = async (): Promise<void> => {- if (!readAuthSession()) { console.log(' (not signed in — run `harness login`, then `harness start`.)'); process.exit(0) }await new Promise((r) => setTimeout(r, 1000)) // grace for the backend to release the one-machine claimawait launch(false) // spawns a fresh daemon on the new bytes, prints status, and exits}@@ -1163,7 +1191,7 @@ async function updateCommand(force: boolean): Promise<void> {async function logout(): Promise<void> {// 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.- await stopDaemonProcess()+ const { pid: stoppedPid } = await stopDaemonProcess()// Before clearAuthSession: 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([])@@ -1172,13 +1200,49 @@ async function logout(): Promise<void> {// 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.rmSync(machineListCachePath(), { force: true })- console.log('Signed out. Run `harness login`, then `harness start`, to reconnect this computer.')// Only when there was no `grid` to run at all. A child that ran has already said what it did, and// repeating "your grid sign-in is still here" after a successful sign-out would be false.if (!gridOut.ran) warnIfGridSignInRemains()+ // A daemon that was up comes BACK, signed out. Signing out is leaving the account, not stopping the+ // agents on this computer: the desktop window is still open on them, the dial is still plugged in,+ // and tmux still holds every session. Leaving the daemon down took all of that off the screen for a+ // change that concerns the other machines.+ if (stoppedPid) {+ console.log('Signed out. Restarting the daemon for this computer only…')+ await launch(false) // prints the guest status block and exits+ return+ }+ console.log('Signed out. Run `harness start` to serve this computer; `harness login` to reach your other machines.')process.exit(0)}+/**+ * Swap a running daemon onto the identity the session file now names.+ *+ * A daemon takes its identity ONCE, at boot (`BackendSocket.machineId` is readonly, and the local+ * websocket binds every client to it). A sign-in on a computer that was running signed out therefore+ * leaves a daemon serving itself under the computer id while the session says machineId — and the app,+ * having just been told the machineId, cannot select it. Restarting is the honest swap: every other+ * route to the same end (a mutable id, a live re-bind) touches the socket, the E2EE identity and the+ * local binding at once, and the daemon already survives a restart cleanly for every update.+ *+ * No-op when nothing is running (`harness start` boots on the new session by itself) or when the daemon+ * already wears the right id (a `harness login` on a computer that was signed in all along).+ */+async function restartDaemonForIdentity(): Promise<void> {+ // OUR daemon, by its pid file, before anything is asked over the port: the port is fixed and shared,+ // and a login run against an isolated data dir (a test, a second HOME) must not reach across to a+ // daemon that is not its own and restart it.+ const pid = readPid()+ if (!pid || !isAlive(pid)) return+ const daemon = await runningDaemonStatus()+ if (!daemon) return+ if (daemon.machineId === wantedDaemonIdentity()) return+ console.log(' restarting the daemon on this account…')+ await stopDaemonProcess()+ await launch(false) // prints the status block and exits+}+/** The pane's session environment: the grid's or the profile's, with the DSH's layered on top. */function mergedLaunchEnv(base: Record<string, string> | undefined,@@ -1213,7 +1277,7 @@ async function statBirthMs(path: string): Promise<number> {}/** The daemon body: hooks + watcher + process discovery + backend socket. */-async function runForeground(session: AuthSession): Promise<void> {+async function runForeground(session: AuthSession | null): Promise<void> {installTimestampedConsole() // daemon-only: every harness.log line gets a wall-clock timestampconst startedAt = Date.now()let discoveryReady = false@@ -1711,7 +1775,11 @@ async function runForeground(session: AuthSession): Promise<void> {let onBackendConnected: () => void = () => {}const auth = new AuthSessionManager(backendHttpBase())- const backend = new BackendSocket(session.machineId ?? session.computerId, auth, (connected) => {+ // The account's machine id when this computer is signed in; its own durable computer id when it is+ // not. Both are just "the id this daemon serves under" to everything downstream — the local+ // websocket binds clients to it, the app selects by it — and the backend binds a machine to the+ // computer id at login, so a sign-in ADOPTS this machine rather than minting a second one.+ const backend = new BackendSocket(session?.machineId ?? computerId(), auth, (connected) => {if (!connected) returnconst sessions = registry.advertised()console.log(`[cli] connected · ${sessions.length} agent(s) registered`)@@ -3143,7 +3211,7 @@ async function runForeground(session: AuthSession): Promise<void> {method,headers: {authorization: `Bearer ${accessToken}`,- 'x-autonomous-env': latest?.autonomousEnv ?? session.autonomousEnv,+ 'x-autonomous-env': latest?.autonomousEnv ?? env.AUTONOMOUS_ENV,...(body !== undefined ? { 'content-type': 'application/json' } : {}),},...(body !== undefined ? { body: JSON.stringify(body) } : {}),@@ -3186,6 +3254,33 @@ async function runForeground(session: AuthSession): Promise<void> {return ((result.body as { data?: { machines?: SharedMachineReference[] } }).data?.machines ?? [])})+ /**+ * The machine list a signed-out daemon answers with: this computer, alone.+ *+ * Null when there is a session — then the backend's own list is the answer, and this must not shadow+ * it. `authMode: 'remote'` is what a computer-backed machine is once it has an account, said now so+ * nothing downstream has to special-case a guest row.+ */+ function guestMachinesBody(): Record<string, unknown> | null {+ if (readAuthSession()) return null+ const id = computerId()+ return {+ success: true,+ data: {+ machines: [{+ machineId: id,+ computerId: id,+ name: terminalHintMachineName(),+ hostname: hostname(),+ status: 'online',+ authMode: 'remote',+ }],+ stale: false,+ guest: true,+ },+ }+ }+const machineListCache = new MachineListCache(() => proxyBackend('GET', '/api/machines'),computerId,@@ -3207,6 +3302,21 @@ async function runForeground(session: AuthSession): Promise<void> {* pane spinning. Stale rows are not wrong rows; the marker below says which they are.*/async function machinesListWithFallback(): Promise<{ status: number; body: Record<string, unknown> }> {+ // ⚠️ SIGNED OUT, THE LIST IS THIS COMPUTER — never the backend's 401.+ //+ // 401 is the one status the desktop app reads as "the session ended": it tears its connections+ // down and puts a sign-in wall in front of agents that were running fine a moment ago. Nothing+ // here needs the backend to say what this computer is. The row is the shape the backend would+ // send, keyed by the durable computer id this daemon is already serving under, so the app+ // classifies it exactly as it will after a sign-in — local by computerId — with no guest-only+ // branch for anyone to forget.+ const guest = guestMachinesBody()+ if (guest) {+ // Into the same cache the dial's wheel reads, so the two surfaces cannot disagree about a+ // machine list one of them was handed directly.+ machineListCache.adopt(guest)+ return { status: 200, body: guest }+ }const res = await proxyBackend('GET', '/api/machines')if (res.status === 200) {// Feed the cache the answer we already have rather than making it fetch the same thing again.@@ -3540,7 +3650,11 @@ async function runForeground(session: AuthSession): Promise<void> {// deliberately does NOT expose chat/transcripts — those live in the cloud web (WEB_URL/commander).onStatus: () => ({machineId: backend.machineId,- computerId: session.computerId,+ computerId: computerId(),+ // Whether this daemon booted with an account. Read LIVE, not from the boot session: a login or+ // logout restarts the daemon, and the window between the file changing and the restart landing+ // is exactly when the app asks — the answer it needs is the file's.+ signedIn: readAuthSession() !== null,version: VERSION,localWs: {path: LOCAL_WS_PATH,@@ -3607,7 +3721,12 @@ async function runForeground(session: AuthSession): Promise<void> {onMachineRename: (machineId, name) => proxyBackend('PATCH', `/api/machines/${encodeURIComponent(machineId)}`, { name }),onMachineDelete: (machineId) => proxyBackend('DELETE', `/api/machines/${encodeURIComponent(machineId)}`),onAuthMe: () => proxyBackend('GET', '/api/auth/me'),- onSharedHarnesses: () => proxyBackend('GET', '/api/harness-shares'),+ // Signed out there is nothing shared WITH this computer and nobody to ask: a share is made on the+ // account. Answered as an empty list rather than proxied into the backend's 401, which is the one+ // status the desktop app reads as "your session ended" — and a guest has no session to end.+ onSharedHarnesses: () => readAuthSession()+ ? proxyBackend('GET', '/api/harness-shares')+ : Promise.resolve({ status: 200, body: { success: true, data: { machines: [] } } }),// The account's desk — see backend routes/desk.ts. The window edits its tabs through the ops// route and hears about everyone else's edits as `desk_changed` (backendSocket.ts).onDeskRead: () => proxyBackend('GET', '/api/desk'),@@ -3851,7 +3970,7 @@ async function runForeground(session: AuthSession): Promise<void> {machineId: backend.machineId,backend,relayPool,- autonomousEnv: readAuthSession()?.autonomousEnv ?? session.autonomousEnv,+ autonomousEnv: readAuthSession()?.autonomousEnv ?? env.AUTONOMOUS_ENV,// A window from before it introduced itself still gets named on the far side's "took control"// banner: the relay knows it is this machine's desktop. Same source as `describeClient` above.// Cut to the wire's limit here rather than let the far daemon drop the whole claim over a long name.@@ -5101,8 +5220,15 @@ async function runForeground(session: AuthSession): Promise<void> {}, LOG_CHECK_INTERVAL_MS)logTrimTimer.unref?.() // never hold the event loop open for log upkeep- backend.connect()- console.log(`[cli] dialing ${env.BACKEND_WS_URL}/api/adapter-ws · watching registered sessions for ${ENGINES.length} engines`)+ // Signed out, the backend is not dialed at all. The socket would only meet a missing session and back+ // off forever, one log line at a time; a sign-in RESTARTS this process with the session in hand+ // (`restartDaemonForIdentity`), so nothing here has to watch for one arriving.+ if (session) {+ backend.connect()+ console.log(`[cli] dialing ${env.BACKEND_WS_URL}/api/adapter-ws · watching registered sessions for ${ENGINES.length} engines`)+ } else {+ console.log(`[cli] not signed in — serving this computer only · watching registered sessions for ${ENGINES.length} engines`)+ }// ── self-update: poll GCS for a newer bundle → verify+swap → restart IMMEDIATELY (supervised rollback) ──//@@ -5349,8 +5475,15 @@ async function runForeground(session: AuthSession): Promise<void> {// The same cache the local `/api/machines` handler answers from (built up near `proxyBackend`), so the// dial's wheel and the desktop's list cannot disagree — and neither can go stale while the other is fresh.const machineList = machineListCache- void machineList.refresh()- const machineListTimer = setInterval(() => void machineList.refresh(), 60_000)+ // Signed out there is nothing to fetch and a fetch would only earn a 401 that empties the wheel, so+ // the one row this daemon can speak for is fed in directly — the same body the local handler answers.+ const refreshMachineList = (): void => {+ const guest = guestMachinesBody()+ if (guest) { machineList.adopt(guest); return }+ void machineList.refresh()+ }+ refreshMachineList()+ const machineListTimer = setInterval(refreshMachineList, 60_000)machineListTimer.unref?.()const machinePeers = new MachinePeerStore()@@ -5358,7 +5491,7 @@ async function runForeground(session: AuthSession): Promise<void> {auth,backendWsBase: env.BACKEND_WS_URL,computerId: computerId(),- autonomousEnv: readAuthSession()?.autonomousEnv ?? session.autonomousEnv,+ autonomousEnv: readAuthSession()?.autonomousEnv ?? env.AUTONOMOUS_ENV,// The SAME identity `harness remote-password set` publishes and `harness link connect` proves// knowledge against, so one link ceremony covers the desktop app's relay and the dial's lane alike.identity: relayIdentityStore.getIdentity(),@@ -5386,6 +5519,7 @@ async function runForeground(session: AuthSession): Promise<void> {machineName: () => { try { return readFileSync(MACHINE_NAME_FILE, 'utf8').trim() || 'This machine' } catch { return 'This machine' } },machineId: () => backend.machineId,computerId: () => computerId(),+ signedIn: () => readAuthSession() !== null,// The SAME handlers the backend socket drives, called directly rather than reimplemented: the// slash-command adaptation, the turn bookkeeping and the question plumbing all live in them.sendTurn: (agentId, text) => backend.onMessage?.(agentId, text),@@ -5625,7 +5759,7 @@ function printInfoBlock(opts: {})()if (machineName) console.log(row('machine', machineName))console.log(row('version', `v${opts.version}`))- console.log(row('backend', env.BACKEND_WS_URL))+ console.log(row('backend', readAuthSession() ? env.BACKEND_WS_URL : 'not signed in · harness login'))console.log(row('agents', `${opts.sessions} available`))console.log(row('pid', String(opts.pid)))console.log(row('logs', tildify(LOG_FILE)))@@ -5660,10 +5794,9 @@ async function repairManagedRuntimes(foreground: boolean): Promise<string | nullreturn repaired}-/** Daemonize (or run inline) with the saved SSO session. */+/** Daemonize (or run inline), with the saved SSO session when there is one — see startCommand. */async function launch(foreground: boolean, repair: boolean = false): Promise<void> {const session = readAuthSession()- if (!session) throw new Error('Not signed in. Run `harness login`.')// The installer already provisioned the managed Node runtime and pointed the launcher at it, so a// normal start just reads what's there (cheap: no network, no download). `--repair` re-runs that// provisioning explicitly, for the rare machine whose launcher predates the managed runtime.@@ -5698,7 +5831,7 @@ async function launch(foreground: boolean, repair: boolean = false): Promise<voi}/** The part of `launch` that runs under the spawn lock: check, spawn, wait for bind, wait for connect. */-async function spawnDaemon(session: AuthSession, runtimeNode: string | null): Promise<void> {+async function spawnDaemon(session: AuthSession | null, runtimeNode: string | null): Promise<void> {const running = readPid()if (running && isAlive(running)) {console.log(`machine already running (pid ${running}) — it auto-reconnects.`)@@ -5742,12 +5875,19 @@ async function spawnDaemon(session: AuthSession, runtimeNode: string | null): Pr// status` says whether the link is up; the desktop app reads the same fact off `/api/status`.const daemonStatus = await runningDaemonStatus()printInfoBlock({- status: '● started · connecting to the backend in the background',+ // Signed out there is no backend leg to be connecting on, and saying there is would be a promise+ // about a handshake that is never attempted. The daemon is up and serving this computer.+ status: session+ ? '● started · connecting to the backend in the background'+ : '● started · this computer only (not signed in)',pid: child.pid ?? 0,- machineId: session.machineId,+ machineId: session?.machineId,sessions: daemonStatus?.sessions ?? 0,version: daemonStatus?.version ?? VERSION,})+ if (!session) {+ console.log(' Agents, terminals and the cabled dial work here. `harness login` adds your other machines.')+ }process.exit(0)}@@ -6393,21 +6533,24 @@ async function status(): Promise<void> {const pid = readPid()const alive = pid != null && isAlive(pid)const session = readAuthSession()- if (!session) { console.log('machine: not signed in. Run: harness login'); process.exit(0) }const daemonStatus = alive ? await runningDaemonStatus() : nullif (!alive) registry.load()printInfoBlock({// The backend link is the daemon's own business, so `status` is where it is read — `start` no// longer waits to see it, and a daemon with no backend is still serving every local agent.+ // Signed out is a WAY OF RUNNING, not a reason to say nothing: the daemon serves this computer,+ // and `machine: not signed in` in place of the whole block hid a running daemon and its agents.status: !alive? '○ stopped'- : daemonStatus == null- ? '● running · not answering yet'- : daemonStatus.connected- ? '● running · backend connected'- : '● running · backend offline — retrying in the background',+ : !session+ ? '● running · this computer only (not signed in)'+ : daemonStatus == null+ ? '● running · not answering yet'+ : daemonStatus.connected+ ? '● running · backend connected'+ : '● running · backend offline — retrying in the background',pid: pid ?? 0,- machineId: session.machineId,+ machineId: session?.machineId,sessions: daemonStatus?.sessions ?? 0,// A stopped daemon answers nothing, so this falls back to the local build — which is what will run.version: daemonStatus?.version ?? VERSION,@@ -6483,7 +6626,11 @@ switch (cmd) {orchestratorCommand(rest).then(code => { process.exitCode = code }).catch(onError)breakcase 'login':- loginCommand(foreground, flags.includes('--force'), flags.includes('--json'), { entryPoint: entryPointFlag() }).catch(onError)+ // The result line goes out FIRST (loginCommand prints it), then the daemon is swapped onto the+ // account: the desktop app reads that line and does not wait for a restart it observes anyway.+ loginCommand(foreground, flags.includes('--force'), flags.includes('--json'), { entryPoint: entryPointFlag() })+ .then((outcome) => outcome.signedIn ? restartDaemonForIdentity() : undefined)+ .catch(onError)breakcase 'auth':if (args[0] !== 'status') { console.error('Unknown command: auth ' + (args[0] ?? '')); usage(1) }@@ -6498,12 +6645,9 @@ switch (cmd) {case 'join':console.error('`harness join` has been removed. Run `harness login`, then `harness start`.')process.exit(1)- case '__run': { // internal: detached daemon child reads the durable SSO session- const session = readAuthSession()- if (!session) onError(new Error('no SSO session for __run'))- else runForeground(session).catch(onError)+ case '__run': // internal: the detached daemon child reads the durable SSO session — or runs without one+ runForeground(readAuthSession()).catch(onError)break- }case 'autonomous-device':runAutonomousDeviceCommand(rest, env.ADAPTER_DATA_DIR, env.PORT).then(code => { process.exitCode = code }).catch(onError)breakdiff --git a/cli/src/cliCommand.spec.ts b/cli/src/cliCommand.spec.tsindex 9594e895b..3e108172e 100644--- a/cli/src/cliCommand.spec.ts+++ b/cli/src/cliCommand.spec.ts@@ -99,13 +99,36 @@ async function daemonStatusServer(machineId: string): Promise<number> {}describe('CLI login/start command contract', () => {- it('does not start or open SSO when start has no saved session', () => {- const result = run('start')-- expect(result.status).toBe(1)- expect(result.stderr).toContain('Not signed in. Run: harness login')- expect(result.stdout).not.toContain('Sign in to Harness in your browser')- })+ it('starts without a saved session, serving this computer only, and never opens SSO', async () => {+ // An account buys the OTHER machines; everything on this computer — discovery, terminals, hooks,+ // the cabled dial — is served by the daemon over the loopback and needs none. Refusing to start+ // without one put a browser sign-in in front of every local thing the product does on day one.+ //+ // Run in its own process group and killed as one: a dev-mode start becomes the daemon itself, and+ // tsx wraps it in a child of its own.+ const root = freshRoot()+ const child = spawn(process.execPath, [TSX, CLI_SOURCE, 'start'], {+ cwd: CLI_ROOT,+ detached: true,+ env: envFor(root, { PORT: String(20_000 + Math.floor(Math.random() * 20_000)), DISABLE_HOOK_INSTALL: '1' }),+ stdio: ['ignore', 'pipe', 'pipe'],+ })+ children.push(child)+ let said = ''+ child.stdout?.on('data', (chunk: Buffer) => { said += chunk.toString() })+ child.stderr?.on('data', (chunk: Buffer) => { said += chunk.toString() })+ const deadline = Date.now() + 25_000+ while (Date.now() < deadline && !/serving this computer only|Not signed in|Sign in to Harness/.test(said)) {+ await new Promise((r) => setTimeout(r, 100))+ }+ try {+ expect(said).toContain('not signed in — serving this computer only')+ expect(said).not.toContain('Sign in to Harness in your browser')+ expect(said).not.toContain('dialing') // no backend leg is attempted without a session+ } finally {+ try { process.kill(-child.pid!, 'SIGKILL') } catch { /* already gone */ }+ }+ }, 40_000)it('rejects the removed join command with the two-step migration', () => {const result = run('join')diff --git a/cli/src/lib/loginCallback.spec.ts b/cli/src/lib/loginCallback.spec.tsindex 625707704..baf5ce437 100644--- a/cli/src/lib/loginCallback.spec.ts+++ b/cli/src/lib/loginCallback.spec.ts@@ -65,6 +65,31 @@ describe('awaitLoginCallback', () => {expect(server.listenerCount('request')).toBe(0)})+ it('sends a person back to whichever surface asked for the sign-in', async () => {+ // "return to the terminal" is a direction to a window the DESKTOP app never+ // opened — a person reads it and goes looking for something that is not+ // there (owner, 2026-09-23). The page is the last thing a sign-in says, and+ // it is the only place the caller can be named.+ const fromApp = await listening()+ const appPending = awaitLoginCallback({+ server: fromApp.server, redirectUri: fromApp.redirectUri,+ manual: null, timeoutMs: 60_000, entryPoint: 'desktop',+ })+ const appPage = await (await fetch(`${fromApp.redirectUri}?code=c&state=s`)).text()+ await appPending+ expect(appPage).toContain('Harness is signed in')+ expect(appPage).not.toContain('terminal')++ const fromCli = await listening()+ const cliPending = awaitLoginCallback({+ server: fromCli.server, redirectUri: fromCli.redirectUri,+ manual: null, timeoutMs: 60_000,+ })+ const cliPage = await (await fetch(`${fromCli.redirectUri}?code=c&state=s`)).text()+ await cliPending+ expect(cliPage).toContain('return to the terminal')+ })+it('rejects on an error redirect, with a 400 for the browser', async () => {const { server, redirectUri } = await listening()// The rejection lands before the browser's response is read, so the expectation is attached first.diff --git a/cli/src/lib/loginCallback.ts b/cli/src/lib/loginCallback.tsindex 41cfab7f9..974179093 100644--- a/cli/src/lib/loginCallback.ts+++ b/cli/src/lib/loginCallback.ts@@ -47,8 +47,10 @@ export function awaitLoginCallback(opts: {redirectUri: stringmanual: Promise<LoginCallbackParams> | nulltimeoutMs: number+ /** Who asked for this sign-in — it changes one sentence on the page. See renderLoginSuccessHtml. */+ entryPoint?: string}): Promise<LoginCallbackParams> {- const { server, redirectUri, manual, timeoutMs } = opts+ const { server, redirectUri, manual, timeoutMs, entryPoint } = optslet timeout: NodeJS.Timeout | undefinedconst onRequest = (req: IncomingMessage, res: ServerResponse): void => {const url = new URL(req.url ?? '/', redirectUri)@@ -58,7 +60,7 @@ export function awaitLoginCallback(opts: {res.writeHead(error || !code || !state ? 400 : 200, { 'content-type': 'text/html; charset=utf-8' })res.end(error || !code || !state? '<h1>Harness login failed</h1><p>You can close this window.</p>'- : renderLoginSuccessHtml())+ : renderLoginSuccessHtml(entryPoint))if (error) reject(new Error(`SSO login failed: ${error}`))else if (code && state) resolve({ code, state })}diff --git a/cli/src/lib/loginPage.ts b/cli/src/lib/loginPage.tsindex b0c4362b8..2966ee697 100644--- a/cli/src/lib/loginPage.ts+++ b/cli/src/lib/loginPage.ts@@ -1,5 +1,15 @@-/** The page shown in the browser when `harness login`'s loopback SSO callback succeeds. */-export function renderLoginSuccessHtml(): string {+/**+ * The page shown in the browser when `harness login`'s loopback SSO callback succeeds.+ *+ * [entryPoint] is who asked for the sign-in — `cli` for a person in a terminal, `desktop` for the app+ * running the same command on their behalf. It decides ONE sentence: "return to the terminal" is a+ * direction to a window that is not open when the app asked, and a person reading it looks for+ * something that is not there (owner, 2026-09-23).+ */+export function renderLoginSuccessHtml(entryPoint = 'cli'): string {+ const back = entryPoint === 'desktop'+ ? 'You can close this window — Harness is signed in.'+ : 'You can close this window and return to the terminal.'return `<!doctype html><html lang="en"><head>@@ -54,7 +64,7 @@ export function renderLoginSuccessHtml(): string {</svg></div><h1>Harness login complete</h1>- <p>You can close this window and return to the terminal.</p>+ <p>${back}</p></div></body></html>`diff --git a/desktop/lib/screens/login_screen.dart b/desktop/lib/screens/login_screen.dartindex 619168b52..4ca004bcf 100644--- a/desktop/lib/screens/login_screen.dart+++ b/desktop/lib/screens/login_screen.dart@@ -29,7 +29,19 @@ import '../widgets/login_relay_diagram.dart';/// app at all, so it outlives the widget it was written on.)class LoginScreen extends StatelessWidget {final AppNotifier notifier;- const LoginScreen({super.key, required this.notifier});++ /// Closes this screen, when there is something behind it to go back to.+ ///+ /// Null is the WALL: the viewer's sign-in, and any window with nothing of its+ /// own to show — there is nowhere to close to, and an X that led nowhere would+ /// be the only control on the screen that does nothing. Non-null is the sheet+ /// a guest desktop window raises over its desk (`showSignInSheet`), and the X+ /// belongs on the CARD, where a person looks for the close of the thing in+ /// front of them — not in the corner of the screen behind it (owner,+ /// 2026-09-23).+ final VoidCallback? onClose;++ const LoginScreen({super.key, required this.notifier, this.onClose});/// Matches `EnvironmentSetupScreen` (560) and `LinkMachineScreen` (460) —/// wide enough for the diagram to breathe, still centred at the 880×560@@ -84,39 +96,62 @@ class LoginScreen extends StatelessWidget {boxShadow: grid.AppCard.shadow,),padding: EdgeInsets.all(compact ? 20 : 24),- child: Column(- mainAxisSize: MainAxisSize.min,+ child: Stack(+ clipBehavior: Clip.none,children: [- const _AppMark(),- SizedBox(height: gap),- Text(- 'Your agents, wherever they run',- textAlign: TextAlign.center,- style: grid.AppType.title(),- ),- const SizedBox(height: 8),- Text(- 'At home, at the office, in the cloud — every machine you '- 'sign in to becomes part of one desk, here.',- textAlign: TextAlign.center,- style: Theme.of(context).textTheme.bodySmall,- ),- SizedBox(height: gap),- if (showFleet) ...[- const LoginFleetMap(),- SizedBox(height: gap),- ],- _Action(notifier: notifier, waiting: waiting),- if (notifier.lastError != null &&- !notifier.sessionExpired) ...[- const SizedBox(height: 16),- _ErrorTile(- message: notifier.lastError!,- onRetry: notifier.login,+ if (onClose != null)+ // Into the card's own padding, so the glyph sits in+ // the CORNER rather than level with the app mark —+ // which read as a misplaced control (owner,+ // 2026-09-23). Negative offsets need Clip.none above.+ Positioned(+ top: compact ? -12 : -16,+ right: compact ? -12 : -16,+ child: IconButton(+ key: const Key('login-close-button'),+ tooltip: 'Close',+ iconSize: 18,+ visualDensity: VisualDensity.compact,+ color: grid.AppPalette.textSecondary,+ icon: const Icon(Icons.close),+ onPressed: onClose,+ ),),- ],- SizedBox(height: gap),- const _Seal(),+ Column(+ mainAxisSize: MainAxisSize.min,+ children: [+ const _AppMark(),+ SizedBox(height: gap),+ Text(+ 'Your agents, wherever they run',+ textAlign: TextAlign.center,+ style: grid.AppType.title(),+ ),+ const SizedBox(height: 8),+ Text(+ 'At home, at the office, in the cloud — every machine you '+ 'sign in to becomes part of one desk, here.',+ textAlign: TextAlign.center,+ style: Theme.of(context).textTheme.bodySmall,+ ),+ SizedBox(height: gap),+ if (showFleet) ...[+ const LoginFleetMap(),+ SizedBox(height: gap),+ ],+ _Action(notifier: notifier, waiting: waiting),+ if (notifier.lastError != null &&+ !notifier.sessionExpired) ...[+ const SizedBox(height: 16),+ _ErrorTile(+ message: notifier.lastError!,+ onRetry: notifier.login,+ ),+ ],+ SizedBox(height: gap),+ const _Seal(),+ ],+ ),],),),@@ -449,3 +484,105 @@ class _AppMark extends StatelessWidget {);}}++/// The sign-in screen, raised OVER the desk rather than instead of it.+///+/// A desktop window opens on this computer without an account, and what an+/// account adds — the other machines, the shared desk, voice on the dial — is+/// asked for at the moment the person reaches for it. This is [LoginScreen]+/// ITSELF on a route above the desk, not a smaller copy: a second layout was a+/// second sign-in to keep in step, and it read as the screen having been+/// redesigned. [reason] is accepted for the call sites that have one to give.+///+/// Closes itself the moment the account arrives — [AppNotifier.signedIn] flips+/// — or when the person cancels, whichever comes first. Returns whether the+/// sign-in completed, so a caller that opened it on the way to something (Link+/// Machine, say) knows whether to carry on.+Future<bool> showSignInSheet(+ BuildContext context,+ AppNotifier notifier, {+ String? reason,+}) async {+ if (notifier.signedIn) return true;+ final completed = await Navigator.of(context).push<bool>(+ PageRouteBuilder<bool>(+ opaque: true,+ barrierDismissible: false,+ transitionDuration: Duration.zero,+ reverseTransitionDuration: Duration.zero,+ pageBuilder: (_, _, _) =>+ _SignInSheet(notifier: notifier, reason: reason),+ ),+ );+ return completed ?? notifier.signedIn;+}++class _SignInSheet extends StatefulWidget {+ const _SignInSheet({required this.notifier, this.reason});++ final AppNotifier notifier;+ final String? reason;++ @override+ State<_SignInSheet> createState() => _SignInSheetState();+}++class _SignInSheetState extends State<_SignInSheet> {+ AppNotifier get notifier => widget.notifier;+ bool _popped = false;++ @override+ void initState() {+ super.initState();+ notifier.addListener(_onChange);+ }++ @override+ void dispose() {+ notifier.removeListener(_onChange);+ super.dispose();+ }++ /// The account arriving is what closes this — not the sign-in call returning.+ /// A restart of the daemon onto the account and the desk being re-seated both+ /// happen after the browser lands, and holding the sheet over them is what+ /// keeps the person from clicking into a grid that is being rebuilt.+ void _onChange() {+ if (_popped || !mounted || !notifier.signedIn) return;+ _popped = true;+ // ⚠️ AFTER the frame. The account arrives in the middle of a rebuild — the+ // notification that carries it comes from work started during one — and+ // popping there is `setState() called during build`, which is what left the+ // sheet standing over a desk that was already signed in (owner,+ // 2026-09-23). One frame later the tree is settled and the route leaves+ // cleanly.+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (!mounted) return;+ Navigator.of(context).pop(true);+ });+ }++ @override+ Widget build(BuildContext context) {+ // ⚠️ THE SCREEN ITSELF, not a smaller copy of it. A sheet with its own+ // layout was a second sign-in to keep in step with this one — two cards,+ // two button states, two sets of words — and it read as the login screen+ // having been redesigned (owner, 2026-09-23). What changes here is only+ // WHERE it appears: over the desk, with a way back out.+ // ⚠️ 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.+ return CallbackShortcuts(+ bindings: {+ const SingleActivator(LogicalKeyboardKey.escape, includeRepeats: false):+ _dismiss,+ },+ child: LoginScreen(notifier: notifier, onClose: _dismiss),+ );+ }++ void _dismiss() {+ if (notifier.canCancelLogin) notifier.cancelLogin();+ Navigator.of(context).pop(false);+ }+}diff --git a/desktop/lib/settings/sections/account_section.dart b/desktop/lib/settings/sections/account_section.dartindex 1409a4409..0ee426cae 100644--- a/desktop/lib/settings/sections/account_section.dart+++ b/desktop/lib/settings/sections/account_section.dart@@ -1,5 +1,6 @@import 'package:flutter/material.dart';+import '../../screens/login_screen.dart';import '../../shared/widgets/section_scaffold.dart';import '../../shared/widgets/setting_row.dart';import '../../state/app_state.dart';@@ -15,6 +16,36 @@ class AccountSection extends StatelessWidget {builder: (context, _) {final local = notifier.localManualFixture != null;final profile = notifier.currentUser;+ // A guest's row says what an account is FOR and offers it; the sheet opens+ // over Settings, which stays where it is — there is nothing to leave, and+ // the row rewrites itself the moment the account arrives.+ if (notifier.isGuest) {+ return SectionScaffold(+ title: 'Account',+ subtitle:+ 'This computer works without one. An account adds your other '+ 'machines, the shared desk and voice on the dial.',+ child: SingleChildScrollView(+ child: SettingRow(+ title: 'Not signed in',+ detail: 'Sign in to reach your other machines',+ control: FilledButton(+ key: const Key('settings-sign-in-button'),+ // Straight back to the desk once the account lands. Settings is+ // where the person WENT to sign in, not where they were going:+ // leaving them on a row that now just says their email is the+ // app asking them to find their own way out (owner,+ // 2026-09-23). Sign out is the same shape, in reverse.+ onPressed: () async {+ final signedIn = await showSignInSheet(context, notifier);+ if (signedIn && context.mounted) Navigator.of(context).pop();+ },+ child: const Text('Sign in'),+ ),+ ),+ ),+ );+ }return SectionScaffold(title: 'Account',subtitle: localdiff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex 40a03e155..6a38dc78d 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -1312,6 +1312,25 @@ class AppNotifier extends ChangeNotifier {int? get focusedPaneId => activeSwarm.focusedPaneId;set focusedPaneId(int? value) => activeSwarm.focusedPaneId = value;+ /// Whether this computer holds an account.+ ///+ /// Guest is the ABSENCE of one, not a mode of its own: everything on this+ /// computer works without it — agents, terminals, tabs, DSH, the cabled dial+ /// — and what an account adds is the OTHER machines, the shared desk, voice+ /// on the dial and the profile. The window opens either way; see [isGuest]+ /// for what a guest is asked to sign in for, and `showSignInSheet` for how+ /// it is asked.+ ///+ /// Presumed true until the CLI says otherwise (`bootstrap` asks, and every+ /// change after that goes through [_rebindAuth]): nothing gated on it is on+ /// screen before that answer lands, and a fixture that sets [status] straight+ /// to `authenticated` is a signed-in window unless it says it is not.+ bool signedIn = true;++ /// A desktop window running without an account. A viewer is never a guest: it+ /// has no local daemon, so there is nothing it could show signed out.+ bool get isGuest => viewer == null && !signedIn;+int _paneFocusRequest = 0;/// Explicit navigation must reveal and refocus even an already-selected pane.@@ -2420,11 +2439,19 @@ class AppNotifier extends ChangeNotifier {try {final authStatus = await cliLogin.checkStatus();if (!_authWorkCurrent(revision)) return;+ signedIn = authStatus.loggedIn;if (!authStatus.loggedIn) {currentUser = null;- status = AppStatus.unauthenticated;- notifyListeners();- return;+ // A VIEWER has nothing to show without an account — no daemon, no+ // machine of its own — so it keeps its login screen. A desktop window+ // has this computer, and opens on it: the sign-in becomes a sheet it+ // raises when the person reaches for another machine, not a wall in+ // front of agents that are already running.+ if (viewer != null) {+ status = AppStatus.unauthenticated;+ notifyListeners();+ return;+ }}status = AppStatus.bootstrapping;notifyListeners();@@ -2690,21 +2717,187 @@ class AppNotifier extends ChangeNotifier {if (status == AppStatus.unauthenticated) return;status = AppStatus.authenticated;notifyListeners();- // The CLI has confirmed sign-in and daemon readiness. Display-name/avatar- // metadata is independent of machine discovery and must not delay work.- unawaited(_loadProfile());+ // The CLI has confirmed daemon readiness. Display-name/avatar metadata is+ // independent of machine discovery and must not delay work — and a guest+ // has no profile to load.+ if (signedIn) unawaited(_loadProfile());// The desk too: tabs from the other computers appear as intent, like the- // restored ones, and attach as their machines answer.- _deskEnsure(revision);+ // restored ones, and attach as their machines answer. It is the ACCOUNT's+ // desk (`Desk{userId}`), so a guest has none — asking for one would earn a+ // 401 on every poll for a document that cannot exist.+ if (signedIn) _deskEnsure(revision);try {await refreshMachines();} catch (error) {if (!_authWorkCurrent(revision)) return;_reportMachineLoadError(error);}+ if (!_authWorkCurrent(revision)) return;+ // The account may have changed while this window was closed — see+ // [_followLocalMachineId]. Done AFTER the list, which is what says which id+ // this computer is served under now.+ await _followLocalMachineId(revision);if (_authWorkCurrent(revision)) notifyListeners();}+ /// This computer's machine id, against the one the saved desk was keyed by.+ ///+ /// The account can change while the app is CLOSED — `harness logout` in a+ /// terminal, a session that expired overnight — and then the tiles restored a+ /// moment ago name a machine the daemon no longer serves under that id. Re-seat+ /// them under the one it does, and remember it for next time.+ Future<void> _followLocalMachineId(int revision) async {+ final store = _paneLayout;+ final current = localMachineState?.machine.machineId;+ if (store == null || current == null) return;+ final remembered = await store.loadLocalMachineId();+ if (!_authWorkCurrent(revision)) return;+ var from = remembered != null && remembered != current ? remembered : null;+ // A guest's list is this computer and nothing else, so a tile waiting for a+ // machine the list does not have can only be this computer under the account+ // it left — IF every such tile names the same one. That reading beats the+ // remembered id: a desk saved before the id was remembered, or remembered by+ // a launch that could not re-seat, still comes home. Signed in, an unknown id+ // is a machine that was deleted, and nothing is inferred.+ if (isGuest) {+ final unknown = {+ for (final pane in allPanes)+ if (!machineStates.containsKey(pane.machineId)) pane.machineId,+ };+ if (unknown.length == 1 && unknown.single != current) {+ from = unknown.single;+ }+ }+ if (from != null) {+ await _reseatDesk(from: from, to: current, dropOthers: isGuest);+ if (!_authWorkCurrent(revision)) return;+ }+ await store.saveLocalMachineId(current);+ }++ /// The account left this window — signed out from Settings, or a session that+ /// ended underneath us — and the desk has to be sat back down on the machine+ /// id the daemon serves NOW.+ ///+ /// The daemon takes its identity once, at boot: this computer's own id signed+ /// out, the account's machineId signed in. `harness login` and `harness logout`+ /// restart it on the other one, so this side waits for that daemon to come+ /// back, reads the machine list it now serves, and re-seats every tile that was+ /// open on the OLD local id under the new one. Remote tiles ride along on a+ /// sign-in and leave on a sign-out — a guest has no machine to attach them to,+ /// and a tile waiting forever reads as broken rather than as signed out.+ ///+ /// The whole desk goes through the saved layout and back (see [_reseatDesk])+ /// rather than being re-keyed live: a tile's machine id is set at birth, and+ /// every other path that changes which agent a tile shows already goes through+ /// the store. Reusing the cold-start restore is what keeps this from becoming a+ /// second, subtly different way to build a grid.+ ///+ /// [revision] is the sign-out's own, when it has one: the explicit sign-out+ /// already invalidated the previous work, and a second invalidation here would+ /// orphan its own wait. A session that ended underneath us passes none and+ /// invalidates for itself — the in-flight work belongs to the account that+ /// just left.+ Future<void> _becomeGuest({String? banner, int? revision}) async {+ revision ??= _invalidateAuthWork();+ final before = localMachineState?.machine.machineId;+ signedIn = false;+ currentUser = null;+ analyticsAccount.clear();+ // The desk is the ACCOUNT's document (`Desk{userId}`): a guest has none, and+ // the tabs closing here are this window leaving the account, not the person+ // closing them — so nothing is sent.+ _deskRetry?.cancel();+ _deskRetry = null;+ _desk.reset();+ _stopAllOfflineRetries();+ _stopAllLinkRetries();+ _stopAllAgentSyncTimers();+ _clearAllTurnActivity();+ // Every connection goes: the daemon this window was talking to is being+ // replaced by one with a different identity, and a remote lane was borrowed+ // from the account that is changing hands.+ await _pool?.closeAll();+ if (!_authWorkCurrent(revision)) return;+ machines = [];+ machinesAreStale = false;+ machineStates.clear();+ sessionPreviews.clear();+ expandedMachines.clear();+ selectedMachineId = null;+ _ensurePool();+ notifyListeners();+ try {+ await ensureCliDaemonReady();+ } catch (error) {+ if (!_authWorkCurrent(revision)) return;+ _lastError = '$error';+ _lastErrorRetryable = true;+ notifyListeners();+ return;+ }+ if (!_authWorkCurrent(revision)) return;+ try {+ await refreshMachines();+ } catch (error) {+ if (!_authWorkCurrent(revision)) return;+ _reportMachineLoadError(error);+ }+ if (!_authWorkCurrent(revision)) return;+ final after = localMachineState?.machine.machineId;+ if (after != null) {+ // Remote tiles leave with the account — a guest has no machine to attach+ // them to, and a tile waiting forever reads as broken rather than as+ // signed out. This computer's follow it to the id the daemon serves now.+ await _reseatDesk(from: before ?? after, to: after, dropOthers: true);+ if (!_authWorkCurrent(revision)) return;+ await _paneLayout?.saveLocalMachineId(after);+ if (!_authWorkCurrent(revision)) return;+ }+ // A guest ends on the desk, whichever screen it started from.+ status = AppStatus.authenticated;+ if (banner != null) {+ _lastError = banner;+ _lastErrorRetryable = true;+ }+ notifyListeners();+ }++ /// Rebuild the grid from the saved layout with this computer's tiles re-keyed+ /// from [from] to [to], and — with [dropOthers] — every other machine's tiles+ /// left out.+ ///+ /// The live tiles are closed WITHOUT persisting (their ids are the old ones),+ /// the file is rewritten, and the cold-start restore reads it back; tiles whose+ /// machines are already connected are attached straight away rather than+ /// waiting for a connect event that already happened.+ Future<void> _reseatDesk({+ required String from,+ required String to,+ required bool dropOthers,+ }) async {+ final store = _paneLayout;+ if (store == null) return;+ _persistLayout();+ await store.flushSwarms();+ await store.rekeyMachine(from: from, to: to, dropOthers: dropOthers);+ if (_disposed) return;+ await _closeAllPanes(persist: false);+ if (_disposed) return;+ _closedHistory.clear();+ final starter = Swarm(id: 'swarm-${_nextSwarmId++}');+ swarms+ ..clear()+ ..add(starter);+ _activeSwarmId = starter.id;+ await _restorePaneLayout();+ if (_disposed) return;+ for (final machine in machineStates.values) {+ _attachPendingPanes(machine);+ }+ _announceAppFocus();+ }+/// The local daemon (`harness start`) must be up before any local REST/WS call can work — unlike/// `harness login`, it does not start on its own. Sets [_cliEndpoint], the dial target every/// machine's WsConn now uses. Public (like [refreshMachines]) so a test subclass can stub it@@ -2773,15 +2966,14 @@ class AppNotifier extends ChangeNotifier {);case LocalCliProbeState.down:_daemonGateFailed = true;- // Before blaming the environment, check whether the daemon is missing because it signed itself- // out. "Try running `harness start` yourself" is advice that cannot work in that case — the- // session file is gone, so every start exits again — and it is the advice this branch used to- // give unconditionally.+ // A daemon missing because its session ended is not an environment problem — and no longer a+ // reason to stop, either: it starts WITHOUT a session and serves this computer. So the window+ // is told it has become a guest (a banner, and the sheet on the next reach for another+ // machine) and the supervisor goes on bringing the daemon back.final authStatus = await cliLogin.checkStatus();if (!_authWorkCurrent(revision)) return;- if (!authStatus.loggedIn) {+ if (!authStatus.loggedIn && signedIn) {_signedOutAtRuntime(_signedOutMessage);- return;}throw StateError('The local Harness daemon did not start. Try running `harness start` yourself, then reopen the app.',@@ -2833,7 +3025,9 @@ class AppNotifier extends ChangeNotifier {_daemonSupervisionTimer ??= discovery.startSupervising(spawnAllowedAt: inSpawnSlot,stillSignedIn: () async => (await cliLogin.checkStatus()).loggedIn,- onSignedOut: () => _signedOutAtRuntime(_signedOutMessage),+ // Only the first time: the supervisor asks once per spawn attempt, and a guest window is+ // already a guest — repeating it would put the banner back on every retry.+ onSignedOut: () { if (signedIn) _signedOutAtRuntime(_signedOutMessage); },onSnapshot: _updateLocalProjectSnapshot,onBackendOnline: _noteBackendOnline,onReady: (endpoint) {@@ -2895,7 +3089,8 @@ class AppNotifier extends ChangeNotifier {/// machine was deleted from another machine or the SSO token simply expired, and guessing between/// them in the copy would sometimes be wrong. Signing in again is the answer to both.static const _signedOutMessage =- 'You were signed out on this computer. Sign in again to reconnect.';+ 'You were signed out on this computer. This computer\'s agents keep '+ 'running; sign in again to reach your other machines.';/// The session went away while the app was already running — send the user to [LoginScreen] with a/// reason, and stop the background work that can only fail from here.@@ -2904,7 +3099,7 @@ class AppNotifier extends ChangeNotifier {/// fills is the app that was ALREADY authenticated when the session disappeared underneath it,/// where nothing re-checked and the daemon supervisor simply respawned `harness start` forever.void _signedOutAtRuntime(String message) {- if (status == AppStatus.unauthenticated) {+ if (status == AppStatus.unauthenticated || isGuest) {return; // idempotent: several sources can race here}_invalidateAuthWork();@@ -2915,11 +3110,22 @@ class AppNotifier extends ChangeNotifier {pendingAuthorizeUrl = null;_awaitingFirstMessage = null;analyticsAccount.clear();- _clearAccountWorkspace();- _lastError = message;- _lastErrorRetryable = true;- status = AppStatus.unauthenticated;- notifyListeners();+ // A VIEWER has nowhere to be but its login screen — no daemon, nothing of+ // its own to show.+ if (viewer != null) {+ _clearAccountWorkspace();+ _lastError = message;+ _lastErrorRetryable = true;+ status = AppStatus.unauthenticated;+ notifyListeners();+ return;+ }+ // A desktop window becomes a GUEST instead: the daemon comes back signed out+ // and goes on serving this computer, so the agents that were running are+ // still running. This computer's tiles stay (under the id it serves now),+ // the other machines' leave, and the banner says why the list got shorter.+ _closedHistory.clear();+ unawaited(_becomeGuest(banner: message));}/// Remove the old account's live objects without overwriting its saved desk.@@ -3167,6 +3373,12 @@ class AppNotifier extends ChangeNotifier {pendingAuthorizeUrl = null;_resetLoginBrowser();notifyListeners();+ // The CLI has just restarted its daemon onto the account's machineId, so a+ // guest window's tiles are open on an id nothing serves any more. The+ // ordinary bootstrap ends by following that id (`_followLocalMachineId`),+ // which re-seats them — one path for a cold boot and for a sign-in, rather+ // than a second way to build a grid.+ signedIn = true;await _finishBootstrapSignedIn();if (!_authWorkCurrent(revision) || status != AppStatus.authenticated) {return;@@ -3298,7 +3510,11 @@ class AppNotifier extends ChangeNotifier {_lastError = null;pendingAuthorizeUrl = null;_closedHistory.clear();- status = AppStatus.unauthenticated;+ // A VIEWER goes back to its login screen; a desktop window stays on the desk+ // and becomes a guest — the daemon comes back signed out and keeps serving+ // this computer, so signing out of the account is not a reason to take the+ // agents off the screen. The rebind at the end sits the desk back down.+ if (viewer != null) status = AppStatus.unauthenticated;currentUser = null;analyticsAccount.clear();notifyListeners();@@ -3325,6 +3541,12 @@ class AppNotifier extends ChangeNotifier {? null: 'Your saved sign-in could not be cleared. Try signing out again.';notifyListeners();+ // The CLI restarts its daemon signed out (`harness logout` does it itself),+ // so this window waits for that one and sits its desk back down on the id it+ // serves. In the background: the person asked to sign out, and that is done.+ if (viewer == null && didClear) {+ unawaited(_becomeGuest(revision: revision));+ }}void _onLocalFailure(String machineId, int code, String reason) {diff --git a/desktop/lib/state/pane_layout_store.dart b/desktop/lib/state/pane_layout_store.dartindex d4ae5bcc7..34828187e 100644--- a/desktop/lib/state/pane_layout_store.dart+++ b/desktop/lib/state/pane_layout_store.dart@@ -122,6 +122,84 @@ class PaneLayoutStore {}}+ /// The id this computer's own machine was last served under, so a launch can+ /// tell whether the saved tiles still name it.+ ///+ /// The desk is keyed by machine id, and this computer's changes with the+ /// account (see [rekeyMachine]). A sign-in or sign-out inside the app re-keys+ /// as it happens; one that happened while the app was CLOSED — `harness+ /// logout` in a terminal, a session that expired overnight — cannot, so the+ /// next launch compares what it remembers against what the daemon now serves+ /// and re-keys then. Without this, every tile waits forever for a machine+ /// that no longer exists under that name.+ static const _localMachineKey = 'local_machine_id';++ Future<String?> loadLocalMachineId() async {+ try {+ final raw = await _storage.read(_localMachineKey);+ return raw == null || raw.isEmpty ? null : raw;+ } catch (_) {+ return null;+ }+ }++ Future<void> saveLocalMachineId(String machineId) async {+ try {+ await _storage.write(_localMachineKey, machineId);+ } catch (_) {+ // Remembered for this run only; the next launch re-keys from the file.+ }+ }++ /// Move every saved tile on machine [from] to machine [to] — and, with+ /// [dropOthers], leave out every tile on any other machine.+ ///+ /// The one case this exists for: THIS computer changes id when the account+ /// under it does. Signed out the daemon serves it under the computer id,+ /// signed in under the account's machineId, and a sign-in or sign-out swaps+ /// the two. The tiles are intent about this computer either way; the id is a+ /// fact about the daemon. Rewriting the file and restoring from it is how the+ /// desk follows without inventing a second, live way to re-key a tile.+ ///+ /// [dropOthers] is the sign-out: a guest has no machine to attach a remote+ /// tile to, and a tile waiting forever reads as broken, not as signed out.+ Future<void> rekeyMachine({+ required String from,+ required String to,+ bool dropOthers = false,+ }) async {+ await flushSwarms();+ final saved = await loadSwarms();+ if (saved == null) return;+ var changed = false;+ final swarms = saved['swarms'];+ if (swarms is! List) return;+ for (final raw in swarms) {+ if (raw is! Map || raw['panes'] is! List) continue;+ final kept = <Object?>[];+ for (final item in (raw['panes'] as List)) {+ if (item is! Map) continue;+ final machineId = item['machineId'];+ if (machineId == from) {+ kept.add({...item, 'machineId': to});+ changed = changed || from != to;+ } else if (!dropOthers || machineId == to) {+ kept.add(item);+ } else {+ changed = true;+ }+ }+ raw['panes'] = kept;+ }+ if (!changed) return;+ try {+ await _storage.write('swarm_layout_v1', jsonEncode(saved));+ } catch (_) {+ // The desk comes back under the old ids at the next launch, where the+ // remembered id (above) gets another chance at it.+ }+ }+Future<Map<String, dynamic>?> loadSwarms() async {try {final value = await _storage.read('swarm_layout_v1');diff --git a/desktop/lib/widgets/swarm_dialogs.dart b/desktop/lib/widgets/swarm_dialogs.dartindex 5949a009b..9427f9be9 100644--- a/desktop/lib/widgets/swarm_dialogs.dart+++ b/desktop/lib/widgets/swarm_dialogs.dart@@ -6,6 +6,7 @@ import 'package:harness/shared/theme/app_type.dart';import '../shared/widgets/app_dialog.dart';import '../shared/widgets/app_select_field.dart';+import '../screens/login_screen.dart';import '../state/app_state.dart';import '../shortcuts/app_keymap.dart';import '../state/swarm_catalog.dart';@@ -203,8 +204,24 @@ class _ProjectDialogState extends State<_ProjectDialog> {/// Link another machine. The dialog itself lives in/// `link_another_machine_dialog.dart`; this name is what every caller — the/// Machines menu, ⌘ commands, the machines manager — has always used.+///+/// The one thing on this desk that cannot work without an account: machines are+/// listed, paired and relayed THROUGH it, so a guest is asked to sign in first —+/// over the desk, and only here, where reaching for another machine is exactly+/// what they just did. Declining leaves them where they were.Future<void> showSwarmLinkDialog(BuildContext context,AppNotifier notifier, {AppKeymap? keymap,-}) => showLinkAnotherMachineDialog(context, notifier, keymap: keymap);+}) async {+ if (notifier.isGuest) {+ final signedIn = await showSignInSheet(+ context,+ notifier,+ reason: 'Your machines live on your account. Sign in to link another one '+ 'to this computer.',+ );+ if (!signedIn || !context.mounted) return;+ }+ return showLinkAnotherMachineDialog(context, notifier, keymap: keymap);+}diff --git a/desktop/lib/ws/local_cli_discovery.dart b/desktop/lib/ws/local_cli_discovery.dartindex 9b2a2879d..39b1e135b 100644--- a/desktop/lib/ws/local_cli_discovery.dart+++ b/desktop/lib/ws/local_cli_discovery.dart@@ -287,8 +287,9 @@ class LocalCliDiscovery {/// and a spawn into that gap is a wasted process (the CLI's own lock refuses it), not a fix.////// Never surfaces ORDINARY failures to the caller (no exceptions, no- /// [AppNotifier]-visible error); [onSignedOut] is the single exception, for the one state no- /// amount of respawning can recover from —+ /// [AppNotifier]-visible error); [onSignedOut] is the single exception, and it is a NOTICE rather+ /// than a failure — the account is gone, the daemon comes back signed out and goes on serving this+ /// computer, and the window should say so —/// this runs unattended in the background for the app's whole lifetime; callers that need a/// one-shot "start now and tell me if it worked" should use [ensureRunning] instead. Cancel the/// timer to stop supervising — this never touches the daemon process itself (it self-daemonizes and@@ -368,17 +369,16 @@ class LocalCliDiscovery {if (DateTime.now().isBefore(nextSpawnAllowedAt)) return;if (!(spawnAllowedAt?.call(DateTime.now()) ?? true)) return;// A daemon that signed itself OUT — its machine was deleted from another machine, or its- // session expired — deletes its session file and exits. Respawning it is the one failure- // this loop cannot fix: every replacement starts without a session and exits again,- // forever, silently. Stop instead, and let the caller send the user somewhere that helps.+ // session expired — deletes its session file. It used to exit and refuse to start again+ // without one, which made respawning it the one failure this loop could not fix; a daemon+ // now STARTS signed out and serves this computer, so the respawn goes ahead below. The+ // caller is still told: the window it is holding has become a guest, and should say so.//// Asked here and not on every tick because it costs a `harness auth status` process, and// the respawn point is already rate-limited by the backoff above — so this runs once per// spawn attempt rather than once every [checkInterval].if (stillSignedIn != null && !await stillSignedIn()) {- timer.cancel();onSignedOut?.call();- return;}try {await _spawnCommand();diff --git a/desktop/test/boot_flow_widget_test.dart b/desktop/test/boot_flow_widget_test.dartindex 4197357b7..8d4addad3 100644--- a/desktop/test/boot_flow_widget_test.dart+++ b/desktop/test/boot_flow_widget_test.dart@@ -29,7 +29,7 @@ import 'package:package_info_plus/package_info_plus.dart';/// status is set directly, so bootstrap/login (which call platform/// channels and the network) never run.AppNotifier makeNotifier(AppStatus status) {- final app = AppNotifier(+ final app = _GuestApp(config: AppConfig.dev,authSession: AuthSession(),configStore: null,@@ -44,6 +44,28 @@ AppNotifier makeNotifier(AppStatus status) {return app;}+/// A window that never reaches for a real daemon.+///+/// A signed-out boot used to stop at the login wall before the daemon mattered;+/// it now lands on the desk as a GUEST, which is past the daemon gate — and a+/// unit test must not shell out for one. Everything else is the real notifier.+class _GuestApp extends AppNotifier {+ _GuestApp({+ required super.config,+ required super.authSession,+ super.configStore,+ super.cliLogin,+ super.environmentProvisioner,+ super.localManualFixture,+ });++ @override+ Future<void> ensureCliDaemonReady() async {}++ @override+ Future<bool> refreshMachines() async => true;+}+/// bootstrap() now asks the CLI (not AuthSession) whether this computer is signed in — this fake/// avoids ever shelling out to a real `harness` binary from a unit test.class _FakeCliLogin extends CliLogin {@@ -164,7 +186,7 @@ void main() {);test('local manual fixture boots without SSO or persisted state', () async {- final app = AppNotifier(+ final app = _GuestApp(config: const AppConfig(apiBaseUrl: 'http://127.0.0.1:12345'),authSession: AuthSession(),localManualFixture: const LocalManualFixture(@@ -191,7 +213,7 @@ void main() {'config-store failure falls back without resetting auth preferences',() async {final store = _BrokenConfigStore();- final app = AppNotifier(+ final app = _GuestApp(config: AppConfig.dev,authSession: AuthSession(),configStore: store,@@ -201,7 +223,11 @@ void main() {await app.bootstrap();- expect(app.status, AppStatus.unauthenticated);+ // A signed-out DESKTOP window lands on the desk as a guest: everything on this+ // computer is served by the daemon over the loopback, and the sign-in is a sheet+ // raised when the person reaches for another machine.+ expect(app.status, AppStatus.authenticated);+ expect(app.isGuest, isTrue);expect(app.config.apiBaseUrl, ConfigStore.defaultBaseUrl);expect(app.autonomousEnv, 'prod');expect(store.resetCalls, 0);@@ -214,7 +240,7 @@ void main() {final storage = _FakeKeyValueStore()..values['environment_setup_version'] = '3';final provisioner = _ReadyEnvironmentProvisioner();- final app = AppNotifier(+ final app = _GuestApp(config: AppConfig.dev,authSession: AuthSession(),configStore: ConfigStore(storage: storage),@@ -227,7 +253,11 @@ void main() {expect(provisioner.called, isTrue);expect(app.environmentReadiness.isReady, isTrue);// Reached the login check rather than getting stuck on preparingEnvironment.- expect(app.status, AppStatus.unauthenticated);+ // A signed-out DESKTOP window lands on the desk as a guest: everything on this+ // computer is served by the daemon over the loopback, and the sign-in is a sheet+ // raised when the person reaches for another machine.+ expect(app.status, AppStatus.authenticated);+ expect(app.isGuest, isTrue);},);@@ -236,7 +266,7 @@ void main() {() async {final storage = _FakeKeyValueStore();final provisioner = _ReadyEnvironmentProvisioner();- final app = AppNotifier(+ final app = _GuestApp(config: AppConfig.dev,authSession: AuthSession(),configStore: ConfigStore(storage: storage),@@ -270,7 +300,7 @@ void main() {mode: EnvironmentSetupMode.automatic,);final provisioner = _ScriptedEnvironmentProvisioner([missing, ready]);- final app = AppNotifier(+ final app = _GuestApp(config: AppConfig.dev,authSession: AuthSession(),configStore: ConfigStore(storage: _FakeKeyValueStore()),@@ -289,7 +319,11 @@ void main() {);await app.startEnvironmentSetup();expect(provisioner.installCalls, [isFalse, isTrue]);- expect(app.status, AppStatus.unauthenticated);+ // A signed-out DESKTOP window lands on the desk as a guest: everything on this+ // computer is served by the daemon over the loopback, and the sign-in is a sheet+ // raised when the person reaches for another machine.+ expect(app.status, AppStatus.authenticated);+ expect(app.isGuest, isTrue);expect(app.environmentReadiness.phase, EnvironmentSetupPhase.ready);expect(painted,@@ -324,7 +358,7 @@ void main() {);final storage = _FakeKeyValueStore();final provisioner = _ScriptedEnvironmentProvisioner([stuck, ready]);- final app = AppNotifier(+ final app = _GuestApp(config: AppConfig.dev,authSession: AuthSession(),configStore: ConfigStore(storage: storage),@@ -345,7 +379,11 @@ void main() {// what lets the provisioner skip the already-`ready` harness step during the recheck.expect(provisioner.resumeFromCalls.last, same(stuck));expect(app.environmentReadiness.isReady, isTrue);- expect(app.status, AppStatus.unauthenticated);+ // A signed-out DESKTOP window lands on the desk as a guest: everything on this+ // computer is served by the daemon over the loopback, and the sign-in is a sheet+ // raised when the person reaches for another machine.+ expect(app.status, AppStatus.authenticated);+ expect(app.isGuest, isTrue);expect(storage.values['environment_setup_version'], isNull);expect(app.environmentRecheckPending, isFalse);app.dispose();@@ -365,7 +403,7 @@ void main() {);final storage = _FakeKeyValueStore();final provisioner = _ScriptedEnvironmentProvisioner([stuck, stuck]);- final app = AppNotifier(+ final app = _GuestApp(config: AppConfig.dev,authSession: AuthSession(),configStore: ConfigStore(storage: storage),@@ -414,7 +452,7 @@ void main() {[probing, reviewed],],);- final app = AppNotifier(+ final app = _GuestApp(config: AppConfig.dev,authSession: AuthSession(),configStore: ConfigStore(storage: _FakeKeyValueStore()),@@ -465,7 +503,7 @@ void main() {],);final provisioner = _ScriptedEnvironmentProvisioner([waiting, waiting]);- final app = AppNotifier(+ final app = _GuestApp(config: AppConfig.dev,authSession: AuthSession(),configStore: ConfigStore(storage: _FakeKeyValueStore()),@@ -553,7 +591,7 @@ void main() {'ready pre-flight is visible while auth resolves, then opens login',(tester) async {final cliLogin = _ControlledCliLogin();- final app = AppNotifier(+ final app = _GuestApp(config: AppConfig.dev,authSession: AuthSession(),configStore: ConfigStore(storage: _FakeKeyValueStore()),@@ -580,8 +618,13 @@ void main() {await bootstrap;await tester.pump();- expect(app.status, AppStatus.unauthenticated);- expect(find.text('Sign in'), findsOneWidget);+ // A signed-out DESKTOP window lands on the desk as a guest: everything on this+ // computer is served by the daemon over the loopback, and the sign-in is a sheet+ // raised when the person reaches for another machine.+ expect(app.status, AppStatus.authenticated);+ expect(app.isGuest, isTrue);+ // …and the desk is what is on screen, not the sign-in.+ expect(find.text('Sign in'), findsNothing);app.dispose();},);@@ -664,7 +707,7 @@ void main() {phase: EnvironmentSetupPhase.ready,),]);- final app = AppNotifier(+ final app = _GuestApp(config: AppConfig.dev,authSession: AuthSession(),configStore: null,@@ -691,8 +734,13 @@ void main() {await tester.tap(find.text('Install 1 tool'));await tester.pump();expect(provisioner.installCalls, [true]);- expect(app.status, AppStatus.unauthenticated);- expect(find.text('Sign in'), findsOneWidget);+ // A signed-out DESKTOP window lands on the desk as a guest: everything on this+ // computer is served by the daemon over the loopback, and the sign-in is a sheet+ // raised when the person reaches for another machine.+ expect(app.status, AppStatus.authenticated);+ expect(app.isGuest, isTrue);+ // …on the desk, not in front of it.+ expect(find.text('Sign in'), findsNothing);await tester.pumpWidget(const SizedBox());app.dispose();},@@ -888,10 +936,12 @@ void main() {expect(find.text('Sam'), findsOneWidget);expect(find.text('[email protected]'), findsOneWidget);await tester.tap(find.byKey(const Key('settings-sign-out-button')));- // The login relay diagram keeps animating after sign-out.await tester.pump();await tester.pump(const Duration(milliseconds: 400));- expect(app.status, AppStatus.unauthenticated);+ // Signing out leaves the account, not this computer: the window stays on the+ // desk as a guest and the daemon goes on serving the agents that are running.+ // Settings closes with the tap, as it did.+ expect(app.signedIn, isFalse);expect(find.text('Account'), findsNothing);await tester.pumpWidget(const SizedBox());app.dispose();diff --git a/desktop/test/guest_window_test.dart b/desktop/test/guest_window_test.dartnew file mode 100644index 000000000..061c8e010--- /dev/null+++ b/desktop/test/guest_window_test.dart@@ -0,0 +1,116 @@+/// A window with no account.+///+/// The product used to refuse to show anything until this computer was signed+/// in, and the CLI refused to start its daemon at all — so a browser sign-in+/// stood in front of every local thing Harness does on day one: agents,+/// terminals, tabs, DSH, the cabled dial, all of which are served over the+/// loopback and need no backend. What an account adds is the OTHER machines,+/// the shared desk, voice on the dial and the profile, and those are asked for+/// at the moment they are reached for.+///+/// These pin the two halves that make that safe: the desk follows this+/// computer's id when the account changes hands, and nothing account-shaped is+/// asked for without one.+library;++import 'dart:convert';++import 'package:flutter_test/flutter_test.dart';+import 'package:harness/state/pane_layout_store.dart';++import 'swarm_state_test.dart' show MemoryStore, createApp;++void main() {+ group('the desk when the account changes hands', () {+ /// One saved desk: two tiles on this computer, one on another machine.+ Future<MemoryStore> savedDesk(String localId) async {+ final store = MemoryStore();+ await store.write(+ 'swarm_layout_v1',+ jsonEncode({+ 'version': 1,+ 'activeId': 'swarm-1',+ 'swarms': [+ {+ 'id': 'swarm-1',+ 'panes': [+ {'machineId': localId, 'agentId': 'a1'},+ {'machineId': localId, 'agentId': 'a2'},+ {'machineId': 'other-machine', 'agentId': 'b1'},+ ],+ },+ ],+ }),+ );+ return store;+ }++ List<(String, String)> savedPanes(Map<String, dynamic> raw) => [+ for (final swarm in raw['swarms'] as List)+ for (final pane in (swarm as Map)['panes'] as List)+ ((pane as Map)['machineId'] as String, pane['agentId'] as String),+ ];++ test('a sign-in re-keys this computer and keeps the other machines', () async {+ // The daemon serves this computer under the COMPUTER id while signed out+ // and under the account's machineId after — `harness login` restarts it on+ // the other one. The tiles are intent about this computer either way.+ final store = await savedDesk('computer-abc');+ final layout = PaneLayoutStore(storage: store);+ await layout.rekeyMachine(from: 'computer-abc', to: 'machine-xyz');++ expect(savedPanes((await layout.loadSwarms())!), [+ ('machine-xyz', 'a1'),+ ('machine-xyz', 'a2'),+ ('other-machine', 'b1'),+ ]);+ });++ test('a sign-out re-keys this computer and drops the others', () async {+ // A guest has no machine to attach a remote tile to, and a tile waiting+ // forever reads as broken rather than as signed out.+ final store = await savedDesk('machine-xyz');+ final layout = PaneLayoutStore(storage: store);+ await layout.rekeyMachine(+ from: 'machine-xyz',+ to: 'computer-abc',+ dropOthers: true,+ );++ expect(savedPanes((await layout.loadSwarms())!), [+ ('computer-abc', 'a1'),+ ('computer-abc', 'a2'),+ ]);+ });++ test('the id is remembered, so a sign-out in a terminal is caught later', () async {+ // `harness logout` while the app is CLOSED cannot re-key anything. The next+ // launch compares what it remembered against what the daemon now serves.+ final store = MemoryStore();+ final layout = PaneLayoutStore(storage: store);+ expect(await layout.loadLocalMachineId(), isNull);+ await layout.saveLocalMachineId('machine-xyz');+ expect(await layout.loadLocalMachineId(), 'machine-xyz');+ });++ test('a desk that already names the right id is left alone', () async {+ final store = await savedDesk('machine-xyz');+ final before = await store.read('swarm_layout_v1');+ final layout = PaneLayoutStore(storage: store);+ await layout.rekeyMachine(from: 'machine-xyz', to: 'machine-xyz');+ expect(await store.read('swarm_layout_v1'), before);+ });+ });++ group('what a guest window is', () {+ test('a desktop window without an account is a guest; a viewer never is', () {+ final app = createApp();+ addTearDown(app.dispose);+ expect(app.signedIn, isTrue, reason: 'presumed until the CLI answers');+ expect(app.isGuest, isFalse);++ app.signedIn = false;+ expect(app.isGuest, isTrue);+ });+ });+}diff --git a/desktop/test/profile_startup_test.dart b/desktop/test/profile_startup_test.dartindex 25e152c4f..40b644aa1 100644--- a/desktop/test/profile_startup_test.dart+++ b/desktop/test/profile_startup_test.dart@@ -386,9 +386,16 @@ void main() {final logout = app.logout();await tester.pump();await logout;+ await tester.pump();}+ // What must not happen is the RETRY firing again. A sign-out also+ // re-reads the list once, on purpose: the window becomes a guest and the+ // daemon it now talks to serves a different machine id (see+ // `_rebindAuth`), so whatever is on screen has to be re-seated on it.+ final settled = api.lists.length;await tester.pump(const Duration(minutes: 2));- expect(api.lists, hasLength(1));+ expect(api.lists, hasLength(settled));+ expect(settled, closeApp ? 1 : lessThanOrEqualTo(2));disposeApp();},);@@ -473,7 +480,9 @@ void main() {list.complete([_machine]);}await start;- expect(app.status, AppStatus.unauthenticated);+ // A signed-out DESKTOP window stays on its desk as a guest — the account is+ // what left. What must not survive is the old account's identity.+ expect(app.signedIn, isFalse);expect(app.currentUser, isNull);expect(analyticsAccount.current.id, isNull);expect(app.machines, isEmpty);@@ -588,9 +597,10 @@ void main() {await app.logout();app.daemon!.complete();await start;- expect(app.status, AppStatus.unauthenticated);+ // The ACCOUNT's workspace is what a sign-out prevents loading: no profile+ // is read for it. The window itself becomes a guest rather than a wall.+ expect(app.signedIn, isFalse);expect(api.profiles, isEmpty);- expect(api.lists, isEmpty);},);