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
Open without an account; sign in when reaching for another machine
0xdiego2526af46275624
diff --git a/cli/src/authCommand.spec.ts b/cli/src/authCommand.spec.tsindex ef7d738f2..e5f3be842 100644--- a/cli/src/authCommand.spec.ts+++ b/cli/src/authCommand.spec.ts@@ -116,7 +116,9 @@ 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 the daemon is wearing.+ expect(JSON.parse(result.stdout.trim())).toEqual({ loggedIn: false, computerId: expect.any(String) })})it('falls back to human text without --json', () => {diff --git a/cli/src/cable/cableHost.ts b/cli/src/cable/cableHost.tsindex aa184112c..76a23e14f 100644--- a/cli/src/cable/cableHost.ts+++ b/cli/src/cable/cableHost.ts@@ -800,7 +800,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 01022c122..61ee2c605 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -462,7 +462,9 @@ async function resolveComputerMachine(): Promise<AuthSession> {async 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}@@ -538,8 +540,11 @@ async function loginCommand(return succeed(true)}// A forced login may intentionally switch SSO accounts. The old daemon must not keep streaming- // under its existing socket while this process replaces the durable session.- if (force) await stopDaemonProcess()+ // under its existing socket while this process replaces the durable session. A daemon running+ // WITHOUT a session holds no account to switch away from, and stopping it here would take every+ // local terminal down for as long as the person is in the browser — it is swapped afterwards+ // instead (restartDaemonForIdentity), once there is an identity to swap to.+ if (force && readAuthSession()) await stopDaemonProcess()const callback = createServer()await new Promise<void>((resolve, reject) => {callback.once('error', reject)@@ -799,12 +804,21 @@ function openInBrowser(url: string): void {} catch { /* ignore */ }}-/** Start the adapter from a saved SSO session. Missing credentials never open a browser implicitly. */+/**+ * The canonical machine for this computer, IF this computer is signed in.+ *+ * A daemon runs without an account: everything on this computer — agents, terminals, the cabled dial —+ * is served from this process over the loopback, and the backend is one leg among several. What the+ * account buys is the other machines, and that can be bought later. So a missing session here is not a+ * refusal; it is a computer that has not been introduced to the backend yet, and `null` says so.+ */+async function resolveComputerMachineIfSignedIn(): Promise<AuthSession | null> {+ return readAuthSession() ? resolveComputerMachine() : null+}++/** Start the adapter, with the saved SSO session when there is one. Missing credentials never open a+ * browser implicitly — and never stop the daemon either; see resolveComputerMachineIfSignedIn. */async function startCommand(foreground: boolean, repair: boolean = false): Promise<void> {- if (!readAuthSession()) {- console.error('\n ✗ Not signed in. Run: harness login\n')- process.exit(1)- }// Update-before-connect: pull the newest bundle so a machine always reconnects on the latest build.// Staging swaps ~/.harness/cli/cli.js, and the daemon start spawns below (`node cli.js __run`)// executes those fresh bytes. Skipped in the foreground (THIS process becomes the long-lived daemon@@ -832,7 +846,7 @@ async function startCommand(foreground: boolean, repair: boolean = false): Promiawait withSpawnLock('start', async () => {const [v] = await Promise.all([stageLatestBundle((m) => console.log(m)),- resolveComputerMachine(),+ resolveComputerMachineIfSignedIn(),])if (v) console.log(` ✓ updated to v${v} — connecting on the new build`)await launch(foreground, repair)@@ -846,7 +860,7 @@ async function startCommand(foreground: boolean, repair: boolean = false): Promi})return}- await resolveComputerMachine()+ await resolveComputerMachineIfSignedIn()await launch(foreground, repair)}@@ -926,7 +940,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}@@ -966,19 +979,54 @@ 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 { stopped } = await stopDaemonProcess()clearAuthSession()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.rmSync(machineListCachePath(), { force: true })- console.log('Signed out. Run `harness login`, then `harness start`, to reconnect this computer.')// Existence is the whole of the test — nothing is read out of the store, and nothing is written// into it. On stderr, so a script reading this command's output is unaffected by it.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, and the dial is still plugged in.+ if (stopped) {+ 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 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 clients 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 re-bind) touches the socket, the E2EE identity and the local binding,+ * and the daemon already survives a restart cleanly for updates.+ *+ * 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+ const wanted = readAuthSession()?.machineId ?? computerId()+ if (daemon.machineId === wanted) 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,@@ -1013,7 +1061,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@@ -1453,7 +1501,10 @@ async function runForeground(session: AuthSession): Promise<void> {let fullReconcile: (announceDevice?: boolean) => Promise<void> = async () => {}const auth = new AuthSessionManager(backendHttpBase())- const backend = new BackendSocket(session.machineId ?? session.computerId, auth, (connected) => {+ // The machine's id when this computer is signed in; its durable computer id when it is not. The+ // daemon runs either way — everything on this computer is served from this process over the+ // loopback, and the backend leg is what an account adds, later, by restarting us with a session.+ const backend = new BackendSocket(session?.machineId ?? computerId(), auth, (connected) => {if (!connected) returnconst sessions = registry.advertised()console.log(`[cli] connected · ${sessions.length} agent(s) registered`)@@ -2720,7 +2771,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) } : {}),@@ -2763,6 +2814,36 @@ 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. The backend would answer 401, and 401 is the one status the+ // desktop app reads as "the session ended" — it tears its connections down and shows 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 same shape the backend would send, keyed by the durable+ // computer id the daemon is already running under (see BackendSocket's construction).+ if (!readAuthSession()) {+ // The backend's envelope, `{ success, data }`, because the app unwraps every answer the same way+ // and this one is not special to it.+ return {+ status: 200,+ body: {+ success: true,+ data: {+ machines: [{+ machineId: computerId(),+ computerId: computerId(),+ name: hostname(),+ hostname: hostname(),+ status: 'online',+ // What a computer-backed machine is once it has an account. Saying so now means the app+ // classifies this row exactly as it will after sign-in — local by computerId, remote by+ // authMode — with no guest-only branch to forget.+ authMode: 'remote',+ }],+ stale: false,+ guest: true,+ },+ },+ }+ }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.@@ -3095,7 +3176,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 rather than from the boot-time session:+ // a login/logout restarts the daemon, but the window between the file changing and the restart+ // landing is exactly when the app is asking, and the answer it needs is the file's.+ signedIn: readAuthSession() !== null,version: VERSION,localWs: {path: LOCAL_WS_PATH,@@ -3395,7 +3480,7 @@ async function runForeground(session: AuthSession): Promise<void> {machineId: backend.machineId,backend,relayPool,- autonomousEnv: readAuthSession()?.autonomousEnv ?? session.autonomousEnv,+ autonomousEnv: readAuthSession()?.autonomousEnv ?? env.AUTONOMOUS_ENV,})// Install both CLI hooks with the port the local server actually bound.if (!env.DISABLE_HOOK_INSTALL) {@@ -4274,8 +4359,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. `connectWithSession` 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 (see `login`), so nothing here has to notice 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) ──//@@ -4524,7 +4616,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(),@@ -4706,17 +4798,19 @@ async function runForeground(session: AuthSession): Promise<void> {* makes the version one too. Falls back to the local constant when the daemon cannot be reached, which is* exactly the case where the printing process IS the only build there is.*/-async function runningDaemonStatus(): Promise<{ version: string; sessions: number } | null> {+async function runningDaemonStatus(): Promise<{ version: string; sessions: number; machineId: string } | null> {try {const res = await fetch(`http://127.0.0.1:${daemonPort()}/api/status`, {signal: AbortSignal.timeout(1_500),})if (!res.ok) return nullconst body: unknown = await res.json()- const status = body as { version?: unknown; sessions?: unknown } | null+ const status = body as { version?: unknown; sessions?: unknown; machineId?: unknown } | nullconst version = typeof status?.version === 'string' && status.version ? status.version : VERSIONconst sessions = Array.isArray(status?.sessions) ? status.sessions.length : 0- return { version, sessions }+ // The id the daemon booted under — a machineId when it had a session, the computer id when not.+ const machineId = typeof status?.machineId === 'string' ? status.machineId : ''+ return { version, sessions, machineId }} catch {return null}@@ -4743,7 +4837,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)))@@ -4760,10 +4854,9 @@ const launchDeps = defaultLaunchDeps(LOG_FILE, daemonPort())// ── daemon start / stop / status ───────────────────────────────────────────────────────────────-/** Daemonize (or run inline) with the saved SSO session. */+/** Daemonize (or run inline), with the saved SSO session when there is one. */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.@@ -4801,7 +4894,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.`)@@ -4838,6 +4931,18 @@ async function spawnDaemon(session: AuthSession, runtimeNode: string | null): Prprocess.exit(1)}+ // SIGNED OUT: bound is ready. There is no backend leg to wait for — the daemon serves this computer+ // and nothing else until a sign-in restarts it — so waiting CONNECT_WAIT_MS for a `[backend] connected`+ // that cannot come would only end in a "not connected yet" that is not true.+ if (!session) {+ const daemonStatus = await runningDaemonStatus()+ console.log(`\n● adapter started · this computer only · pid ${child.pid}`)+ console.log(' Not signed in — agents, terminals and the dial work here. Sign in to reach other machines.')+ console.log(` sign in harness login · status harness status · stop harness stop`)+ console.log(` version v${daemonStatus?.version ?? VERSION} · logs ${tildify(LOG_FILE)}`)+ process.exit(0)+ }+const ready = await waitForReady(logOffset, CONNECT_WAIT_MS, launchDeps)// DEAUTH (401/403): the saved credential is no longer valid — this computer was removed from the machine@@ -5516,13 +5621,13 @@ 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({- status: alive ? '● running' : '○ stopped',+ // Signed out is a way of running, not a reason to say nothing: the daemon serves this computer.+ status: alive ? (session ? '● running' : '● running · this computer only (not signed in)') : '○ stopped',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,@@ -5589,7 +5694,11 @@ const onError = (err: unknown): never => {switch (cmd) {case 'login':- loginCommand(foreground, flags.includes('--force'), flags.includes('--json')).catch(onError)+ // The result line goes out FIRST (loginCommand prints it), then the daemon is swapped: the desktop+ // app reads that line and does not wait for the restart it is about to observe anyway.+ loginCommand(foreground, flags.includes('--force'), flags.includes('--json'))+ .then((outcome) => outcome.signedIn ? restartDaemonForIdentity() : undefined)+ .catch(onError)breakcase 'auth':if (args[0] !== 'status') { console.error('Unknown command: auth ' + (args[0] ?? '')); usage(1) }@@ -5604,12 +5713,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: 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 268bfdd4c..972ad4784 100644--- a/cli/src/cliCommand.spec.ts+++ b/cli/src/cliCommand.spec.ts@@ -1,4 +1,4 @@-import { spawnSync } from 'child_process'+import { spawn, spawnSync } from 'child_process'import { mkdtempSync, rmSync } from 'fs'import { tmpdir } from 'os'import { join } from 'path'@@ -12,35 +12,75 @@ const dirs: string[] = []afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }) })-function run(...args: string[]) {+function envFor(root: string, extra: NodeJS.ProcessEnv = {}): NodeJS.ProcessEnv {+ return {+ ...process.env,+ HOME: root,+ HARNESS_AUTH_DIR: join(root, 'auth'),+ ADAPTER_DATA_DIR: join(root, 'data'),+ ADAPTER_CLI_DIR: join(root, 'cli'),+ ADAPTER_COMPUTER_ID_FILE: join(root, 'computer-id'),+ ADAPTER_UPDATE_DISABLE: 'true',+ ...extra,+ }+}++/** A long-running command in its own process group, with everything it prints collected as it comes. */+function spawnDetached(args: string[], extra: NodeJS.ProcessEnv) {+ const root = mkdtempSync(join(tmpdir(), 'harness-cli-command-'))+ dirs.push(root)+ const child = spawn(process.execPath, [TSX, CLI_SOURCE, ...args], {+ cwd: CLI_ROOT,+ detached: true,+ env: envFor(root, extra),+ stdio: ['ignore', 'pipe', 'pipe'],+ })+ const output = { text: '' }+ child.stdout.on('data', (chunk: Buffer) => { output.text += chunk.toString() })+ child.stderr.on('data', (chunk: Buffer) => { output.text += chunk.toString() })+ return { child, output }+}++async function waitFor(output: { text: string }, pattern: RegExp, timeoutMs: number): Promise<string> {+ const deadline = Date.now() + timeoutMs+ while (Date.now() < deadline) {+ if (pattern.test(output.text)) return output.text+ await new Promise((r) => setTimeout(r, 100))+ }+ return output.text+}++function run(args: string[], opts: { env?: NodeJS.ProcessEnv; timeout?: number } = {}) {const root = mkdtempSync(join(tmpdir(), 'harness-cli-command-'))dirs.push(root)return spawnSync(process.execPath, [TSX, CLI_SOURCE, ...args], {cwd: CLI_ROOT,encoding: 'utf8',- env: {- ...process.env,- HOME: root,- HARNESS_AUTH_DIR: join(root, 'auth'),- ADAPTER_DATA_DIR: join(root, 'data'),- ADAPTER_CLI_DIR: join(root, 'cli'),- ADAPTER_COMPUTER_ID_FILE: join(root, 'computer-id'),- ADAPTER_UPDATE_DISABLE: 'true',- },+ ...(opts.timeout ? { timeout: opts.timeout } : {}),+ env: envFor(root, opts.env),})}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 () => {+ // The account buys the other machines; everything on THIS computer is served from the daemon over+ // the loopback, so a missing session is not a reason to refuse. A dev-mode start runs the daemon in+ // the foreground, so this holds it on a port of its own until it has said what it is doing, then+ // kills the whole process group (tsx wraps the daemon in a child of its own).+ const port = String(20_000 + Math.floor(Math.random() * 20_000))+ const { child, output } = spawnDetached(['start'], { PORT: port, DISABLE_HOOK_INSTALL: '1' })+ try {+ const said = await waitFor(output, /serving this computer only|Not signed in|Sign in to Harness/, 20_000)+ 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 without a session+ } finally {+ try { process.kill(-child.pid!, 'SIGKILL') } catch { /* already gone */ }+ }})it('rejects the removed join command with the two-step migration', () => {- const result = run('join')+ const result = run(['join'])expect(result.status).toBe(1)expect(result.stderr).toContain('`harness join` has been removed.')@@ -48,14 +88,14 @@ describe('CLI login/start command contract', () => {})it('no longer has an analytics command (usage metering upload was removed)', () => {- const result = run('analytics')+ const result = run(['analytics'])expect(result.status).toBe(1)expect(result.stderr).toContain('Unknown command: analytics')})it('returns a nonzero status for an unknown command', () => {- const result = run('not-a-command')+ const result = run(['not-a-command'])expect(result.status).toBe(1)expect(result.stderr).toContain('Unknown command: not-a-command')diff --git a/desktop/lib/screens/login_screen.dart b/desktop/lib/screens/login_screen.dartindex 67b119efb..5c3b07e89 100644--- a/desktop/lib/screens/login_screen.dart+++ b/desktop/lib/screens/login_screen.dart@@ -1,12 +1,139 @@import 'package:flutter/material.dart';import 'package:flutter/services.dart';-import '../shared/theme/app_theme.dart' as grid;+import '../shared/widgets/app_dialog.dart';import '../state/app_state.dart';import '../widgets/login_relay_diagram.dart';import '../widgets/welcome_workspace_preview.dart';+/// The sign-in, raised OVER the desk rather than in front of it.+///+/// A desktop window opens on this computer without an account, and what an+/// account adds — the other machines, voice on the dial — is asked for at the+/// moment the person reaches for it. So this is a sheet with one line saying+/// what it is for ([reason]), the same button and browser wait [LoginScreen]+/// has, and nothing else: the workspace preview and the pitch belong to a+/// window that has nothing to show yet, and this one is showing the work.+///+/// 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 showAppDialog<bool>(+ context: context,+ builder: (dialogContext) =>+ _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();+ }++ void _onChange() {+ if (_popped || !mounted || !notifier.signedIn) return;+ _popped = true;+ // After the frame: the notification can land mid-build.+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (mounted && Navigator.of(context).canPop()) {+ Navigator.of(context).pop(true);+ }+ });+ }++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ return ListenableBuilder(+ listenable: notifier,+ builder: (context, _) {+ final waiting = notifier.signingIn;+ return Dialog(+ child: ConstrainedBox(+ constraints: const BoxConstraints(maxWidth: 400),+ child: Padding(+ padding: const EdgeInsets.fromLTRB(24, 24, 24, 20),+ child: Column(+ mainAxisSize: MainAxisSize.min,+ children: [+ const _AppMark(),+ const SizedBox(height: 16),+ Text(+ 'Sign in to Harness',+ textAlign: TextAlign.center,+ style: Theme.of(context).textTheme.titleLarge,+ ),+ const SizedBox(height: 8),+ Text(+ widget.reason ??+ 'Reach your other machines and use voice on the dial. '+ 'Everything on this computer keeps working either way.',+ textAlign: TextAlign.center,+ style: Theme.of(context).textTheme.bodySmall,+ ),+ const SizedBox(height: 20),+ _Action(notifier: notifier, waiting: waiting),+ if (notifier.lastError != null && !waiting) ...[+ const SizedBox(height: 16),+ _ErrorTile(+ message: notifier.lastError!,+ onRetry: notifier.login,+ ),+ ],+ if (!waiting) ...[+ const SizedBox(height: 12),+ TextButton(+ onPressed: () {+ if (_popped) return;+ _popped = true;+ Navigator.of(context).pop(false);+ },+ style: TextButton.styleFrom(+ foregroundColor: grid.AppPalette.textSecondary,+ ),+ child: const Text('Not now'),+ ),+ ],+ ],+ ),+ ),+ ),+ );+ },+ );+ }+}+/// The sign-in screen.////// Lead with the work: real agents together in one workspace. A staticdiff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dartindex 51183edc8..1aaabe606 100644--- a/desktop/lib/screens/swarm_screen.dart+++ b/desktop/lib/screens/swarm_screen.dart@@ -600,7 +600,7 @@ class _SwarmScreenState extends State<SwarmScreen> {case 'addProject':await _addProject();case 'linkMachine':- await _dialog(() => showSwarmLinkDialog(context, app));+ await _dialog(() => linkMachineOrSignIn(context, app));case 'manageMachines':unawaited(_dialog(() => showMachinesManager(context, app)));case 'refreshMachines':@@ -769,7 +769,7 @@ class _SwarmScreenState extends State<SwarmScreen> {folder ?? (agent == null ? null : machine?.projectOf(agent)?.cwd);await _dialog(() async {if (id == null) {- await showSwarmLinkDialog(context, app);+ await linkMachineOrSignIn(context, app);return;}await showNewAgentDialog(@@ -1238,7 +1238,7 @@ class _SwarmScreenState extends State<SwarmScreen> {for (var i = 1; i <= 9; i++)'pane.focus_$i': () => app.focusPaneByIndex(i - 1),'navigation.commands': _showSearchCommands,- 'machine.link': () => _dialog(() => showSwarmLinkDialog(context, app)),+ 'machine.link': () => _dialog(() => linkMachineOrSignIn(context, app)),'machines.manage': () => _dialog(() => showMachinesManager(context, app)),'project.add': _addProject,'keyboard.open_config': () => openKeyboardConfig(context),@@ -1428,59 +1428,59 @@ class _SwarmScreenState extends State<SwarmScreen> {source: 'tab',)else- Padding(- padding: app.panes.isEmpty- ? EdgeInsets.zero- : const EdgeInsets.all(10),- child: Focus.withExternalFocusNode(- focusNode: _canvasFocus,- includeSemantics: false,- child: Stack(- children: [- Positioned.fill(- child: PaneGrid(- notifier: app,- swarmMode: true,- onSplit: (paneId, axis) => unawaited(- _splitAgent(axis, paneId: paneId),- ),- onNewSplit: (paneId, axis) => unawaited(- _splitAgent(- axis,- paneId: paneId,- create: true,+ Padding(+ padding: app.panes.isEmpty+ ? EdgeInsets.zero+ : const EdgeInsets.all(10),+ child: Focus.withExternalFocusNode(+ focusNode: _canvasFocus,+ includeSemantics: false,+ child: Stack(+ children: [+ Positioned.fill(+ child: PaneGrid(+ notifier: app,+ swarmMode: true,+ onSplit: (paneId, axis) => unawaited(+ _splitAgent(axis, paneId: paneId),+ ),+ onNewSplit: (paneId, axis) => unawaited(+ _splitAgent(+ axis,+ paneId: paneId,+ create: true,+ ),),+ empty: app.panes.isEmpty+ ? HarnessStartPage(+ key: ValueKey(+ 'harness-start:${app.activeSwarmId}',+ ),+ focusNode: _startSearchFocus,+ createSearch: () =>+ SwarmSearchController(+ app,+ _navigation.recent,+ projects: _projects,+ commands: _searchCommands,+ adding: true,+ catalog: _searchCatalog,+ ),+ onNew: _newAgent,+ onStore: app.openStore,+ onChoose: (selection) =>+ _activateSearch(+ selection,+ app.activeSwarmId,+ ),+ )+ : null,),- empty: app.panes.isEmpty- ? HarnessStartPage(- key: ValueKey(- 'harness-start:${app.activeSwarmId}',- ),- focusNode: _startSearchFocus,- createSearch: () =>- SwarmSearchController(- app,- _navigation.recent,- projects: _projects,- commands: _searchCommands,- adding: true,- catalog: _searchCatalog,- ),- onNew: _newAgent,- onStore: app.openStore,- onChoose: (selection) =>- _activateSearch(- selection,- app.activeSwarmId,- ),- )- : null,),- ),- ],+ ],+ ),),),- ),],),),@@ -1571,7 +1571,9 @@ class _SwarmScreenState extends State<SwarmScreen> {// The Store shares the app's icon.Image.asset(kStoreMarkAsset,- key: ValueKey('tab-store:${swarm.id}'),+ key: ValueKey(+ 'tab-store:${swarm.id}',+ ),width: 16,height: 16,)diff --git a/desktop/lib/settings/sections/account_section.dart b/desktop/lib/settings/sections/account_section.dartindex 1409a4409..cf5c33da8 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';@@ -14,7 +15,30 @@ class AccountSection extends StatelessWidget {listenable: notifier,builder: (context, _) {final local = notifier.localManualFixture != null;+ final guest = notifier.isGuest;final profile = notifier.currentUser;+ // A guest's row says what the 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 (guest) {+ return SectionScaffold(+ title: 'Account',+ subtitle:+ 'This computer works without one. An account reaches your '+ 'other machines 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'),+ onPressed: () => showSignInSheet(context, notifier),+ 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 4cb165b4e..e83e35db1 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -288,6 +288,7 @@ class AppNotifier extends ChangeNotifier {final AuthSession session;AppConfig config;late ApiClient api;+/// Signs in, and says whether this computer is signed in: the harness CLI in a desktop build,/// [ViewerServices.login] in a viewer build — which has no CLI — under one name, so every call/// site reads the same in both.@@ -460,6 +461,23 @@ class AppNotifier extends ChangeNotifier {);AppStatus status = AppStatus.bootstrapping;++ /// Whether this computer holds an account. Guest is the ABSENCE of one, not a+ /// state of its own: everything on this computer works without it — agents,+ /// terminals, tabs, the dial — and the account buys the other machines. The+ /// window opens either way; see [isGuest] for what a guest is asked to sign+ /// in for, and [_rebindAuth] for what changes when the answer changes.+ ///+ /// Presumed 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;+CurrentUserProfile? currentUser;List<Machine> machines = [];final Map<String, MachineState> machineStates = {};@@ -498,11 +516,9 @@ class AppNotifier extends ChangeNotifier {final target = swarms.where((s) => s.id == entry.swarmId).firstOrNull;return target == null ||target.panes.length < maxPanes ||- target.panes.any(- (p) =>- p.machineId == entry.machineId &&- p.agentId == entry.agentId,- );+ target.panes.any(+ (p) => p.machineId == entry.machineId && p.agentId == entry.agentId,+ );}bool _canReopenSwarm(ClosedSwarm saved) {@@ -1972,11 +1988,17 @@ 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. A desktop window+ // has this computer, and opens on it — the sign-in is a sheet it+ // raises when the person reaches for another machine, not a wall.+ if (viewer != null) {+ status = AppStatus.unauthenticated;+ notifyListeners();+ return;+ }}status = AppStatus.bootstrapping;notifyListeners();@@ -2227,18 +2249,56 @@ 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 none to load.+ if (signedIn) unawaited(_loadProfile());try {await refreshMachines();} catch (error) {if (!_authWorkCurrent(revision)) return;_reportMachineLoadError(error);}+ if (!_authWorkCurrent(revision)) return;+ 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 — 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 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@@ -2306,15 +2366,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 that is missing because its session ended is not an environment problem — but it+ // is no longer a reason to stop either: the daemon starts without a session and serves this+ // computer. So the window is told it is a guest now (a banner, the sheet on the next reach+ // for another machine) and the supervisor below 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.',@@ -2331,7 +2390,9 @@ class AppNotifier extends ChangeNotifier {_daemonSupervisionTimer ??= discovery.startSupervising(spawnAllowedAt: inSpawnSlot,stillSignedIn: () async => (await cliLogin.checkStatus()).loggedIn,- onSignedOut: () => _signedOutAtRuntime(_signedOutMessage),+ onSignedOut: () {+ if (signedIn) _signedOutAtRuntime(_signedOutMessage);+ },onSnapshot: _updateLocalProjectSnapshot,onReady: (endpoint) {// Back (or here for the first time). If the app is sitting on the error strip from a boot@@ -2401,23 +2462,165 @@ 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 || (viewer == null && !signedIn)) {return; // idempotent: several sources can race here}+ // A viewer has nowhere to be but the login screen.+ if (viewer != null) {+ _invalidateAuthWork();+ currentUser = null;+ signingIn = false;+ pendingAuthorizeUrl = null;+ _awaitingFirstMessage = null;+ analyticsAccount.clear();+ _daemonSupervisionTimer?.cancel();+ _daemonSupervisionTimer = null;+ _cliEndpoint = null;+ unawaited(_pool?.closeAll());+ _pool = null;+ _lastError = message;+ _lastErrorRetryable = true;+ status = AppStatus.unauthenticated;+ notifyListeners();+ return;+ }+ // A desktop window becomes a guest: this computer's tiles stay, the other machines' leave, and the+ // banner says why the rail just got shorter._invalidateAuthWork();- currentUser = null;signingIn = false;pendingAuthorizeUrl = null;_awaitingFirstMessage = null;- analyticsAccount.clear();+ _closedHistory.clear();+ unawaited(_rebindAuth(signedIn: false, banner: message));+ }++ /// The account under this window changed — a sign-in from the sheet, a sign-out from the footer, or+ /// a session that ended underneath us — and the desk has to be sat back down on the machine ids 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 for one+ /// reads as broken rather than as signed out.+ ///+ /// The whole desk goes through the saved layout and back (see [_reseatDesk]) rather than being+ /// rekeyed 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 being a second, subtly different way to build a grid.+ ///+ /// [revision] is the sign-in's own: `login` has already invalidated the+ /// previous work and holds `_loginAuthorized` for the sheet, and a second+ /// invalidation here would drop that flag mid-wait. A sign-out passes none+ /// and invalidates for itself — its in-flight work belongs to the account+ /// that just left.+ Future<void> _rebindAuth({+ required bool signedIn,+ String? banner,+ int? revision,+ }) async {+ revision ??= _invalidateAuthWork();+ final before = localMachineState?.machine.machineId;+ // A sign-out is a fact the moment it is known; a sign-in is announced only+ // once the desk is sat down on the account (at the end), so the sheet that+ // started it keeps its spinner until there is something to come back to.+ if (!signedIn) {+ this.signedIn = false;+ currentUser = null;+ analyticsAccount.clear();+ }+ _stopAllOfflineRetries();+ _stopAllLinkRetries();+ _stopAllAgentSyncTimers();_daemonSupervisionTimer?.cancel();_daemonSupervisionTimer = null;+ _daemonGateFailed = false;_cliEndpoint = null;- unawaited(_pool?.closeAll());+ _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;_pool = null;- _lastError = message;- _lastErrorRetryable = true;- status = AppStatus.unauthenticated;+ machines = [];+ 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;+ // The profile rides beside the machine list, as it does on a cold boot:+ // display-name metadata must not delay the desk, and needs only the daemon.+ if (signedIn) unawaited(_loadProfile());+ try {+ await refreshMachines();+ } catch (error) {+ if (!_authWorkCurrent(revision)) return;+ _reportMachineLoadError(error);+ }+ if (!_authWorkCurrent(revision)) return;+ final after = localMachineState?.machine.machineId;+ if (after != null && (before != after || !signedIn)) {+ await _reseatDesk(+ from: before ?? after,+ to: after,+ dropOthers: !signedIn,+ );+ if (!_authWorkCurrent(revision)) return;+ }+ if (after != null) await _paneLayout?.saveLocalMachineId(after);+ if (!_authWorkCurrent(revision)) return;+ this.signedIn = signedIn;+ // A rebind 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();+ swarms+ ..clear()+ ..add(Swarm(id: 'swarm-1'));+ _activeSwarmId = 'swarm-1';+ await _restorePaneLayout();+ if (_disposed) return;+ for (final machine in machineStates.values) {+ _attachPendingPanes(machine);+ }+ _announceAppFocus();notifyListeners();}@@ -2512,9 +2715,14 @@ class AppNotifier extends ChangeNotifier {Future<void> login() async {if (_disposed || signingIn) return;final revision = _invalidateAuthWork();- _closedHistory.clear();_lastError = null;- status = AppStatus.bootstrapping;+ // A viewer signs in on a screen of its own; a desktop window signs in on a+ // sheet over the desk it is already showing, and the desk stays where it is+ // — including its history — until the account has actually changed hands.+ if (viewer != null) {+ _closedHistory.clear();+ status = AppStatus.bootstrapping;+ }signingIn = true;pendingAuthorizeUrl = null;notifyListeners();@@ -2538,6 +2746,18 @@ class AppNotifier extends ChangeNotifier {pendingAuthorizeUrl = null;_resetLoginBrowser();notifyListeners();+ if (viewer == null) {+ // The CLI has restarted the daemon on the account's machineId by the+ // time `harness login` returns; the desk follows it there. `signingIn`+ // holds until it has, so the sheet's spinner covers the whole wait.+ await _rebindAuth(signedIn: true, revision: revision);+ if (!_authWorkCurrent(revision)) return;+ signingIn = false;+ notifyListeners();+ analytics.signedIn();+ _armFirstMessage('sign_in');+ return;+ }await _finishBootstrapSignedIn();if (!_authWorkCurrent(revision) || status != AppStatus.authenticated) {return;@@ -2549,7 +2769,9 @@ class AppNotifier extends ChangeNotifier {_armFirstMessage('sign_in');} catch (error) {if (!_authWorkCurrent(revision)) return;- status = AppStatus.unauthenticated;+ // A desktop window is still on its desk, as a guest; only a viewer has+ // a login screen to fall back to.+ if (viewer != null) status = AppStatus.unauthenticated;_lastError = error.toString();_lastErrorRetryable = true;// A short code, never `error.toString()` — a CLI failure carries paths@@ -2633,7 +2855,7 @@ class AppNotifier extends ChangeNotifier {_invalidateAuthWork();signingIn = false;pendingAuthorizeUrl = null;- status = AppStatus.unauthenticated;+ if (viewer != null) status = AppStatus.unauthenticated;_lastError = null;_lastErrorRetryable = false;cliLogin.cancel();@@ -2641,10 +2863,45 @@ class AppNotifier extends ChangeNotifier {}Future<void> logout() async {- final revision = _invalidateAuthWork();+ // Nothing to leave: a guest holds no account, and `harness logout` would+ // only restart a daemon that is already serving this computer alone.+ if (isGuest) return;cliLogin.cancel();signingIn = false;pendingAuthorizeUrl = null;+ if (viewer == null) {+ // The account is gone the moment this returns: what it owned — the+ // profile, the history (a remote tile in it could be reopened by whoever+ // signs in next), the connections to its machines — goes now. The desk+ // follows in the background, once `harness logout` has restarted the+ // daemon signed out: the rebind has to find THAT daemon, the one serving+ // this computer under its own id, not the one going away. This computer's+ // tiles stay; the other machines' leave with the account.+ final revision = _invalidateAuthWork();+ signedIn = false;+ currentUser = null;+ _closedHistory.clear();+ _awaitingFirstMessage = null;+ analyticsAccount.clear();+ analytics.signedOut();+ _stopAllOfflineRetries();+ _stopAllLinkRetries();+ _stopAllAgentSyncTimers();+ _daemonSupervisionTimer?.cancel();+ _daemonSupervisionTimer = null;+ _cliEndpoint = null;+ unawaited(_pool?.closeAll());+ _pool = null;+ notifyListeners();+ unawaited(+ cliLogin.logout().then((_) {+ if (_disposed || !_authWorkCurrent(revision)) return null;+ return _rebindAuth(signedIn: false, revision: revision);+ }),+ );+ return;+ }+ final revision = _invalidateAuthWork();_closedHistory.clear();// Best-effort and fire-and-forget: local state is cleared below regardless of whether the CLI// process could be reached, but a real `harness logout` clears its saved session so the NEXTdiff --git a/desktop/lib/state/pane_layout_store.dart b/desktop/lib/state/pane_layout_store.dartindex d4ae5bcc7..e11dae2a0 100644--- a/desktop/lib/state/pane_layout_store.dart+++ b/desktop/lib/state/pane_layout_store.dart@@ -138,6 +138,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 with what the daemon now serves+ /// and re-keys then. Without this, every tile waits 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 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 a second, live way of re-keying 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;+ for (final raw in saved['swarms'] as List) {+ 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;+ }+ }+ // Focus and zoom are indexes into this list; a shorter list is repaired+ // by the restore, which clamps them to the first tile.+ raw['panes'] = kept;+ }+ if (!changed) return;+ try {+ await _storage.write('swarm_layout_v1', jsonEncode(saved));+ } catch (_) {+ // The next launch restores the old ids; a tile that then waits for a+ // machine is the smaller wrong than a sign-in that throws.+ }+ }+Future<void> saveSwarms(List<Swarm> swarms, String activeId) {// Capture each request before yielding, but keep only the latest snapshot// while a write is pending. Holding a navigation key must not queue a fulldiff --git a/desktop/lib/widgets/account_footer.dart b/desktop/lib/widgets/account_footer.dartindex 4bdc42238..30c214d47 100644--- a/desktop/lib/widgets/account_footer.dart+++ b/desktop/lib/widgets/account_footer.dart@@ -3,6 +3,7 @@ import 'dart:async';import 'package:flutter/material.dart';import 'package:lucide_icons_flutter/lucide_icons.dart';+import '../screens/login_screen.dart';import '../state/app_state.dart';import '../shared/theme/app_theme.dart' as grid;import '../shared/widgets/app_menu.dart';@@ -39,9 +40,16 @@ class _AccountFooterState extends State<AccountFooter> {grid.AppTheme.watch(context);final profile = widget.notifier.currentUser;final isLocal = widget.notifier.localManualFixture != null;- final primary =- profile?.email ?? (isLocal ? 'local terminal' : 'signed in');- final secondary = isLocal ? 'LOCAL SESSION' : null;+ final guest = widget.notifier.isGuest;+ // A guest's pill says so, and says what signing in is for — this is the+ // one place in the rail the account lives, so it is where the absence of+ // one is read.+ final primary = guest+ ? 'Not signed in'+ : profile?.email ?? (isLocal ? 'local terminal' : 'signed in');+ final secondary = guest+ ? 'THIS COMPUTER ONLY'+ : (isLocal ? 'LOCAL SESSION' : null);return MenuAnchor(controller: _menu,@@ -96,20 +104,31 @@ class _AccountFooterState extends State<AccountFooter> {},),const AppMenuDivider(),- AppMenuItem(- key: const Key('sign-out-menu-item'),- icon: LucideIcons.logOut300,- label: isLocal ? 'Disconnect local session' : 'Sign out',- // The one row here that ENDS something. It sat in a group of its own- // already, which said "this is different" — but drew in the same ink- // as Settings, which said the opposite louder. [AppMenuItem] has- // carried the treatment all along; this row simply never asked.- danger: true,- onPressed: () {- _menu.close();- widget.notifier.logout();- },- ),+ if (guest)+ AppMenuItem(+ key: const Key('sign-in-menu-item'),+ icon: LucideIcons.logIn300,+ label: 'Sign in…',+ onPressed: () {+ _menu.close();+ unawaited(showSignInSheet(context, widget.notifier));+ },+ )+ else+ AppMenuItem(+ key: const Key('sign-out-menu-item'),+ icon: LucideIcons.logOut300,+ label: isLocal ? 'Disconnect local session' : 'Sign out',+ // The one row here that ENDS something. It sat in a group of its own+ // already, which said "this is different" — but drew in the same ink+ // as Settings, which said the opposite louder. [AppMenuItem] has+ // carried the treatment all along; this row simply never asked.+ danger: true,+ onPressed: () {+ _menu.close();+ widget.notifier.logout();+ },+ ),],builder: (context, controller, child) => Padding(// The pill floats inside the rail rather than spanning it. A full-width@@ -120,13 +139,25 @@ class _AccountFooterState extends State<AccountFooter> {? Center(child: _AvatarButton(onTap: controller.isOpen ? controller.close : controller.open,- initials: profile?.initials ?? (isLocal ? 'L' : '?'),+ initials:+ profile?.initials ??+ (isLocal+ ? 'L'+ : guest+ ? '·'+ : '?'),),): _AccountPill(open: controller.isOpen,onTap: controller.isOpen ? controller.close : controller.open,- initials: profile?.initials ?? (isLocal ? 'L' : '?'),+ initials:+ profile?.initials ??+ (isLocal+ ? 'L'+ : guest+ ? '·'+ : '?'),primary: primary,secondary: secondary,),@@ -264,6 +295,7 @@ class _AccountSummary extends StatelessWidget {grid.AppTheme.watch(context);final profile = notifier.currentUser;final isLocal = notifier.localManualFixture != null;+ final guest = notifier.isGuest;return Padding(// 15 = the row gutter (6) plus a row's own inner padding (9), so this// block starts on the same left edge as the glyphs under it instead of@@ -272,7 +304,13 @@ class _AccountSummary extends StatelessWidget {child: Row(children: [_Avatar(- initials: profile?.initials ?? (isLocal ? 'L' : '?'),+ initials:+ profile?.initials ??+ (isLocal+ ? 'L'+ : guest+ ? '·'+ : '?'),large: true,),const SizedBox(width: 12),@@ -282,7 +320,11 @@ class _AccountSummary extends StatelessWidget {children: [Text(profile?.displayName ??- (isLocal ? 'Local session' : 'Autonomous user'),+ (isLocal+ ? 'Local session'+ : guest+ ? 'Not signed in'+ : 'Autonomous user'),maxLines: 1,overflow: TextOverflow.ellipsis,// Semibold, not w700: the weight ladder has three steps and@@ -307,7 +349,11 @@ class _AccountSummary extends StatelessWidget {const SizedBox(height: 3),Text(profile?.email ??- (isLocal ? 'loopback backend' : 'profile unavailable'),+ (isLocal+ ? 'loopback backend'+ : guest+ ? 'Sign in to reach your other machines'+ : 'profile unavailable'),maxLines: 1,overflow: TextOverflow.ellipsis,style: TextStyle(diff --git a/desktop/lib/widgets/link_machine_dialog.dart b/desktop/lib/widgets/link_machine_dialog.dartindex c08cf5eb7..469f9a70e 100644--- a/desktop/lib/widgets/link_machine_dialog.dart+++ b/desktop/lib/widgets/link_machine_dialog.dart@@ -3,6 +3,7 @@ import 'dart:async';import 'package:flutter/material.dart';import '../auth/cli_link.dart';+import '../screens/login_screen.dart';import '../shared/widgets/app_dialog.dart';import '../state/app_state.dart';import '../shared/widgets/skeleton.dart';@@ -12,7 +13,22 @@ import '../theme/app_theme.dart';/// with `harness link connect` — no code to copy/paste. To link a specific machine FROM here/// instead, select it in the sidebar (see `machine_rail.dart`'s `selectMachineForSetup`), not/// duplicated here — that flow lives in `link_machine_screen.dart`.-Future<void> showLinkMachineDialog(BuildContext context, AppNotifier notifier) {+Future<void> showLinkMachineDialog(+ BuildContext context,+ AppNotifier notifier,+) async {+ // A remote password is published under the account, for machines on the+ // same account to prove knowledge of. Without an account there is nowhere to+ // publish it and nobody who could connect — so the sheet comes first.+ if (notifier.isGuest) {+ final signedIn = await showSignInSheet(+ context,+ notifier,+ reason: 'Sign in to let your other machines connect to this one.',+ );+ if (!signedIn || !context.mounted) return;+ }+ if (!context.mounted) return;return showAppDialog<void>(context: context,builder: (context) => _LinkMachineDialog(notifier: notifier),diff --git a/desktop/lib/widgets/machines_manager.dart b/desktop/lib/widgets/machines_manager.dartindex 5bba61b46..8ad9e28f7 100644--- a/desktop/lib/widgets/machines_manager.dart+++ b/desktop/lib/widgets/machines_manager.dart@@ -1,10 +1,29 @@import 'package:flutter/material.dart';import '../shared/theme/app_theme.dart' as grid;+import '../screens/login_screen.dart';import '../shared/widgets/app_dialog.dart';import '../state/app_state.dart';import 'swarm_dialogs.dart';+/// Link Machine, behind the sign-in when there is no account: linking is the+/// one thing a guest cannot do, and the sheet says so on its own line.+Future<void> linkMachineOrSignIn(+ BuildContext context,+ AppNotifier notifier,+) async {+ if (notifier.isGuest) {+ final signedIn = await showSignInSheet(+ context,+ notifier,+ reason: 'Sign in to link your other machines and see their agents here.',+ );+ if (!signedIn || !context.mounted) return;+ }+ if (!context.mounted) return;+ await showSwarmLinkDialog(context, notifier);+}+Future<void> showMachinesManager(BuildContext context, AppNotifier notifier) =>showAppDialog<void>(context: context,@@ -95,14 +114,29 @@ class _MachinesManagerState extends State<_MachinesManager> {if (machines[i].needsLink) 'Link required',].join(' · '),),- trailing: TextButton(- onPressed: () => showMachineRenameDialog(- context,- widget.notifier,- machines[i].machine.machineId,- machines[i].machine.displayName,- ),- child: const Text('Rename'),+ // A guest's one machine is named by its hostname and+ // has no record on the backend to rename.+ trailing: widget.notifier.isGuest+ ? null+ : TextButton(+ onPressed: () => showMachineRenameDialog(+ context,+ widget.notifier,+ machines[i].machine.machineId,+ machines[i].machine.displayName,+ ),+ child: const Text('Rename'),+ ),+ ),+ ],+ if (widget.notifier.isGuest) ...[+ const Divider(height: 1),+ Padding(+ padding: const EdgeInsets.symmetric(vertical: 16),+ child: Text(+ 'Link another computer to see its agents here — '+ 'sign in to start.',+ style: Theme.of(context).textTheme.bodySmall,),),],@@ -117,7 +151,7 @@ class _MachinesManagerState extends State<_MachinesManager> {child: Text(_refreshing ? 'Refreshing…' : 'Refresh'),),TextButton.icon(- onPressed: () => showSwarmLinkDialog(context, widget.notifier),+ onPressed: () => linkMachineOrSignIn(context, widget.notifier),icon: const Icon(Icons.add, size: 18),label: const Text('Link Machine'),),diff --git a/desktop/lib/ws/local_cli_discovery.dart b/desktop/lib/ws/local_cli_discovery.dartindex 30a0287a6..d0cff6069 100644--- a/desktop/lib/ws/local_cli_discovery.dart+++ b/desktop/lib/ws/local_cli_discovery.dart@@ -273,8 +273,8 @@ 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, not a+ /// failure — the account is gone, the daemon comes back signed out, 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@@ -344,17 +344,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; it now+ // starts signed out and serves this computer, so the respawn goes ahead. 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();@@ -466,7 +465,12 @@ class LocalCliDiscovery {// it, so treating discovery-ready as "ready" raced the handshake and surfaced as a bogus 30s// receive-timeout right after boot. `connected` is the daemon's own backend-socket state// (missing field ⇒ older CLI ⇒ accepted, same idiom as above).- if (body['connected'] == false) {+ //+ // Unless the daemon is running without an account: then there is no backend leg to wait for —+ // `/api/machines` answers for this computer from the daemon itself — and "not connected" would+ // hold the window on a spinner for a handshake that is never attempted. A daemon too old to say+ // `signedIn` is one that refused to start signed out, so a missing field means signed in.+ if (body['connected'] == false && body['signedIn'] != false) {return LocalCliProbe.notReady('not connected to the backend yet',pid: pid,diff --git a/desktop/test/account_footer_test.dart b/desktop/test/account_footer_test.dartindex f4b6d5080..9d3baaa67 100644--- a/desktop/test/account_footer_test.dart+++ b/desktop/test/account_footer_test.dart@@ -29,6 +29,9 @@ void main() {authSession: AuthSession(),configStore: null,);+ // A signed-in footer: the profile alone is not the account (it loads+ // after), and a window without one is a guest with a Sign in row instead.+ notifier.signedIn = true;notifier.currentUser = const CurrentUserProfile(name: 'Avery Example',email: '[email protected]',diff --git a/desktop/test/boot_flow_widget_test.dart b/desktop/test/boot_flow_widget_test.dartindex b99a2b70f..fc7398385 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,@@ -58,6 +58,26 @@ class _FakeCliLogin extends CliLogin {CliAuthStatus(loggedIn: loggedIn);}+/// 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 home as a+/// guest, which is past the daemon gate — and a test must not shell out for it.+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<void> refreshMachines() async {}+}+class _ControlledCliLogin extends CliLogin {final Completer<CliAuthStatus> status = Completer<CliAuthStatus>();@@ -163,7 +183,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(@@ -190,7 +210,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,@@ -200,7 +220,8 @@ void main() {await app.bootstrap();- expect(app.status, AppStatus.unauthenticated);+ expect(app.status, AppStatus.authenticated);+ expect(app.isGuest, isTrue);expect(app.config.apiBaseUrl, ConfigStore.defaultBaseUrl);expect(app.autonomousEnv, 'prod');expect(store.resetCalls, 0);@@ -213,7 +234,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),@@ -225,8 +246,9 @@ 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);+ // Reached the sign-in check rather than getting stuck on preparingEnvironment.+ expect(app.status, AppStatus.authenticated);+ expect(app.isGuest, isTrue);},);@@ -235,7 +257,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),@@ -269,7 +291,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()),@@ -288,7 +310,8 @@ void main() {);await app.startEnvironmentSetup();expect(provisioner.installCalls, [isFalse, isTrue]);- expect(app.status, AppStatus.unauthenticated);+ expect(app.status, AppStatus.authenticated);+ expect(app.isGuest, isTrue);expect(app.environmentReadiness.phase, EnvironmentSetupPhase.ready);expect(painted,@@ -322,7 +345,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),@@ -343,7 +366,8 @@ 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);+ expect(app.status, AppStatus.authenticated);+ expect(app.isGuest, isTrue);expect(storage.values['environment_setup_version'], isNull);expect(app.environmentRecheckPending, isFalse);app.dispose();@@ -363,7 +387,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),@@ -412,7 +436,7 @@ void main() {[probing, reviewed],],);- final app = AppNotifier(+ final app = _GuestApp(config: AppConfig.dev,authSession: AuthSession(),configStore: ConfigStore(storage: _FakeKeyValueStore()),@@ -463,7 +487,7 @@ void main() {],);final provisioner = _ScriptedEnvironmentProvisioner([waiting, waiting]);- final app = AppNotifier(+ final app = _GuestApp(config: AppConfig.dev,authSession: AuthSession(),configStore: ConfigStore(storage: _FakeKeyValueStore()),@@ -551,7 +575,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()),@@ -578,8 +602,10 @@ void main() {await bootstrap;await tester.pump();- expect(app.status, AppStatus.unauthenticated);- expect(find.text('Sign in'), findsOneWidget);+ // A signed-out desktop boots onto home as a guest; the sign-in is a+ // sheet it raises later, not a wall here.+ expect(app.status, AppStatus.authenticated);+ expect(app.isGuest, isTrue);app.dispose();},);@@ -662,7 +688,7 @@ void main() {phase: EnvironmentSetupPhase.ready,),]);- final app = AppNotifier(+ final app = _GuestApp(config: AppConfig.dev,authSession: AuthSession(),configStore: null,@@ -689,8 +715,10 @@ 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 boots onto home as a guest; the sign-in is a+ // sheet it raises later, not a wall here.+ expect(app.status, AppStatus.authenticated);+ expect(app.isGuest, isTrue);await tester.pumpWidget(const SizedBox());app.dispose();},@@ -877,10 +905,11 @@ 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 desk where it is, as a guest's.+ expect(app.status, AppStatus.authenticated);+ expect(app.isGuest, isTrue);expect(find.text('Account'), findsNothing);await tester.pumpWidget(const SizedBox());app.dispose();diff --git a/desktop/test/profile_startup_test.dart b/desktop/test/profile_startup_test.dartindex c697ea14c..3110ec3c8 100644--- a/desktop/test/profile_startup_test.dart+++ b/desktop/test/profile_startup_test.dart@@ -341,13 +341,17 @@ void main() {await logout;}await tester.pump(const Duration(minutes: 2));- expect(api.lists, hasLength(1));+ // A sign-out reads the list ONCE more — this computer's, as a guest —+ // and the recovery timer that was retrying the account's is gone.+ expect(api.lists, hasLength(closeApp ? 1 : 2));disposeApp();},);}test('a late profile response cannot restore a signed-out account', () async {+ // A desktop signs in from its desk, never from a wall.+ app.status = AppStatus.authenticated;final start = app.login();await Future<void>.delayed(Duration.zero);await app.logout();@@ -357,7 +361,9 @@ void main() {list.complete([_machine]);}await start;- expect(app.status, AppStatus.unauthenticated);+ // Signed out on a desktop is a guest on the same desk, not a login wall.+ expect(app.status, AppStatus.authenticated);+ expect(app.isGuest, isTrue);expect(app.currentUser, isNull);expect(analyticsAccount.current.id, isNull);expect(app.machines, isEmpty);@@ -420,18 +426,21 @@ void main() {test('old sign-in completion cannot replace a new account or its loading state',() async {+ app.status = AppStatus.authenticated; // signed in from the deskfinal oldLogin = app.login();await _tick();await app.logout();+ await _tick();final newLogin = app.login();await _tick();+ // Two profiles, one per sign-in; three list reads — the sign-out reads+ // this computer's own list, as a guest, between them.expect(api.profiles, hasLength(2));- expect(api.lists, hasLength(2));+ expect(api.lists, hasLength(3));api.profiles.first.complete(_profile('old'));api.lists.first.complete([_machine]);await oldLogin;expect(app.signingIn, isTrue);- expect(app.machinesLoading, isTrue);expect(app.currentUser, isNull);expect(app.machines, isEmpty);api.profiles.last.complete(_profile('new'));@@ -455,9 +464,16 @@ void main() {await app.logout();app.daemon!.complete();await start;- expect(app.status, AppStatus.unauthenticated);+ await _tick();+ // The account's workspace never loaded: no profile, and the one list+ // read is the sign-out's own, for this computer as a guest.+ expect(api.profiles, isEmpty);+ expect(api.lists, hasLength(1));+ api.lists.single.complete([_machine]);+ await _tick();+ expect(app.status, AppStatus.authenticated);+ expect(app.isGuest, isTrue);expect(api.profiles, isEmpty);- expect(api.lists, isEmpty);},);diff --git a/desktop/test/signin_recovery_test.dart b/desktop/test/signin_recovery_test.dartindex da25fc1e0..b123b669e 100644--- a/desktop/test/signin_recovery_test.dart+++ b/desktop/test/signin_recovery_test.dart@@ -189,7 +189,9 @@ void main() {expect(app.canCancelLogin, isFalse);expect(app.pendingAuthorizeUrl, isNull);app.cancelLogin();- expect(app.status, AppStatus.bootstrapping);+ // A desktop window signs in on a sheet over its desk: the status it was+ // in (the guest's home) is the status it stays in, start to finish.+ expect(app.status, AppStatus.unauthenticated);expect(cli.cancellations, 0);app.daemon!.completeError(StateError('Fixture service unavailable'));await login;diff --git a/desktop/test/swarm_reopen_test.dart b/desktop/test/swarm_reopen_test.dartindex e1b72236f..b490c6d56 100644--- a/desktop/test/swarm_reopen_test.dart+++ b/desktop/test/swarm_reopen_test.dart@@ -22,10 +22,27 @@ class _NoopLogin extends CliLogin {}}+/// Signing out re-seats the desk on the daemon this computer now runs as;+/// this test is about the history and must not reach for a real daemon.+class _DeskOnlyApp extends AppNotifier {+ _DeskOnlyApp({+ required super.config,+ required super.authSession,+ super.configStore,+ super.cliLogin,+ });++ @override+ Future<void> ensureCliDaemonReady() async {}++ @override+ Future<void> refreshMachines() async {}+}+void main() {test('recently closed agents and swarms do not survive sign-out', () async {final login = _NoopLogin();- final app = AppNotifier(+ final app = _DeskOnlyApp(config: AppConfig.dev,authSession: AuthSession(),configStore: null,