The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
fix(cli): keep machine connections stable across builds and restarts (#529)
Deec2a5e3c8f266
diff --git a/cli/.env.example b/cli/.env.exampleindex 7962df2f3..8e3ae2415 100644--- a/cli/.env.example+++ b/cli/.env.example@@ -1,3 +1,7 @@+# Load this file explicitly: HARNESS_ENV_FILE=/absolute/path/to/harness.env harness start+# Harness never reads the current project's .env automatically. Dev and release builds use the+# same production backend/account/state by default. Exported variables override this file.+# Backend the CLI dials (`/api/adapter-ws`). Local dev: ws://localhost:8090# BACKEND_WS_URL=wss://harness-api.autonomous.aidiff --git a/cli/README.md b/cli/README.mdindex f82467547..b97f932ea 100644--- a/cli/README.md+++ b/cli/README.md@@ -245,7 +245,21 @@ The suite uses isolated, test-owned lifecycle fixtures. Its engine matrix explicfirst-run onboarding that prevents a proprietary CLI from running is unavailable evidence and must bereported as such, not described as exercised.-## Config (`.env`, see `.env.example`)+## Config (environment variables; see `.env.example`)++Dev and release builds use the same production backend, account and machine state by default.+Harness does **not** load a project's `.env` when started from that folder. To run against a+different backend deliberately, export the settings or select a file explicitly:++```bash+HARNESS_ENV_FILE=/absolute/path/to/harness.env harness start+```++Exported variables take precedence. An explicit `DOTENV_CONFIG_PATH` remains supported.+If you previously relied on automatic `.env` loading, set one of these paths before starting+Harness. `harness status` reports the running daemon's backend, account environment and state+directories; those can differ from the shell that invokes the command. Older daemons may not+report all fields.| var | default | meaning ||-----|---------|---------|diff --git a/cli/scripts/check-connection-environment.mjs b/cli/scripts/check-connection-environment.mjsnew file mode 100644index 000000000..691f8b222--- /dev/null+++ b/cli/scripts/check-connection-environment.mjs@@ -0,0 +1,83 @@+// Packaged CLI smoke test. No real account, engine, tmux server or installed daemon is touched.+// Run after `npm run bundle`: node scripts/check-connection-environment.mjs+import { spawn } from 'node:child_process'+import { once } from 'node:events'+import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs'+import http from 'node:http'+import { join, dirname, delimiter } from 'node:path'+import { fileURLToPath } from 'node:url'+import assert from 'node:assert/strict'+import { WebSocketServer } from 'ws'++if (process.platform === 'win32') throw new Error('This isolated daemon smoke test needs a POSIX shell')+const bundle = fileURLToPath(new URL('../dist/cli.js', import.meta.url))+for (const [saved, configured] of [['stag', 'prod'], ['prod', 'stag']]) {+ const root = mkdtempSync('/tmp/hconn-')+ const auth = join(root, 'auth'), data = join(root, 'data'), bin = join(root, 'bin')+ for (const path of [auth, data, bin]) mkdirSync(path, { recursive: true })+ writeFileSync(join(bin, 'tmux'), '#!/bin/sh\nif [ "$1" = "-V" ]; then echo "tmux 3.5a"; exit 0; fi\necho "no server running" >&2\nexit 1\n', { mode: 0o700 })+ writeFileSync(join(auth, 'session.json'), JSON.stringify({+ version: 1, accessToken: 'fixture-access', refreshToken: 'fixture-refresh', expiresAt: Date.now() + 3600_000,+ autonomousEnv: saved, computerId: 'connection-fixture', machineId: '12341234123412341234123412341234', updatedAt: Date.now(),+ }), { mode: 0o600 })+ // Run from a project containing unrelated settings; the explicit daemon configuration must win.+ writeFileSync(join(root, '.env'), 'PORT=1\nBACKEND_WS_URL=ws://wrong-project.invalid\n')+ const server = http.createServer((req, res) => {+ res.setHeader('content-type', 'application/json')+ res.end(JSON.stringify({ data: { machines: [] } }))+ })+ const wss = new WebSocketServer({ server })+ let connectedUrl = null+ wss.on('connection', (ws, req) => {+ if (req.url?.startsWith('/api/adapter-ws')) connectedUrl = new URL(req.url, 'http://fixture')+ ws.on('error', () => {})+ })+ server.listen(0, '127.0.0.1')+ await once(server, 'listening')+ const backendUrl = `ws://127.0.0.1:${server.address().port}`+ let logs = ''+ const child = spawn(process.execPath, [bundle, '__run'], {+ cwd: root,+ env: {+ PATH: [bin, dirname(process.execPath), '/usr/bin', '/bin'].join(delimiter), HOME: root,+ NODE_ENV: 'test', PORT: '0', AUTONOMOUS_ENV: configured, BACKEND_WS_URL: backendUrl,+ ADAPTER_DATA_DIR: data, HARNESS_AUTH_DIR: auth, ADAPTER_RUNTIME_DIR: join(root, 'runtime'),+ ADAPTER_CLI_DIR: join(root, 'cli'), ADAPTER_COMPUTER_ID_FILE: join(root, 'computer-id'),+ ADAPTER_COMPUTER_ID: 'connection-fixture', ADAPTER_UPDATE_DISABLE: 'true',+ DISABLE_HOOK_INSTALL: 'true', DISABLE_GRID_INSTALL: 'true', CABLE_DISABLE: 'true',+ HARNESS_DAEMONS: 'off', HARNESS_CODING_MEMORY: '0',+ HARNESS_STORE_CATALOG_URL: `http://127.0.0.1:${server.address().port}/catalog`,+ },+ stdio: ['ignore', 'pipe', 'pipe'],+ })+ child.stdout.on('data', chunk => { logs += chunk })+ child.stderr.on('data', chunk => { logs += chunk })+ const exited = once(child, 'exit')+ try {+ const deadline = Date.now() + 25_000+ while (!connectedUrl && child.exitCode === null && Date.now() < deadline) await new Promise(resolve => setTimeout(resolve, 50))+ assert.ok(connectedUrl, `daemon failed to connect:\n${logs.slice(-4000)}`)+ assert.equal(connectedUrl.searchParams.get('autonomousEnv'), saved)+ const status = await new Promise((resolve, reject) => {+ const req = http.get({ socketPath: join(data, 'daemon-0.sock'), path: '/api/status', signal: AbortSignal.timeout(2000) }, res => {+ let body = ''; res.on('data', chunk => { body += chunk }); res.on('end', () => resolve(JSON.parse(body)))+ })+ req.on('error', reject)+ })+ assert.equal(status.autonomousEnv, saved)+ assert.equal(status.backendUrl, backendUrl)+ assert.equal(status.dataDir, data)+ assert.equal(status.authDir, auth)+ console.log(`PASS: saved ${saved} account overrides ${configured} shell; packaged daemon connects and reports its real settings`)+ } finally {+ child.kill('SIGTERM')+ const kill = setTimeout(() => child.kill('SIGKILL'), 3000)+ await exited+ clearTimeout(kill)+ for (const ws of wss.clients) ws.terminate()+ await new Promise(resolve => wss.close(resolve))+ server.closeAllConnections()+ await new Promise(resolve => server.close(resolve))+ rmSync(root, { recursive: true, force: true })+ }+}diff --git a/cli/src/authCommand.spec.ts b/cli/src/authCommand.spec.tsindex c8c963069..cbbcb4c67 100644--- a/cli/src/authCommand.spec.ts+++ b/cli/src/authCommand.spec.ts@@ -6,6 +6,7 @@ import { join } from 'path'import { fileURLToPath } from 'url'import { afterEach, describe, expect, it } from 'vitest'import { b64d, b64e, fingerprint, newIdentity } from './lib/e2ee/core.js'+import { listenLocalSocket, localSocketPath } from './lib/localSocket.js'const CLI_ROOT = fileURLToPath(new URL('..', import.meta.url))const CLI_SOURCE = join(CLI_ROOT, 'src', 'cli.ts')@@ -164,6 +165,54 @@ function seedDevLog(root: string, active: string[], removed: string[]): void {}))}+describe.skipIf(process.platform === 'win32')('harness status connection settings', () => {+ function statusRoot(): string {+ // macOS limits Unix socket paths to 104 bytes; its usual TMPDIR is already long.+ const root = mkdtempSync('/tmp/hstat-')+ dirs.push(root)+ return root+ }+ it.each([true, false])('reports the running daemon environment when caller signed in is %s', async callerSignedIn => {+ const root = statusRoot()+ if (callerSignedIn) seedSession(root)+ const data = join(root, 'data')+ mkdirSync(data)+ writeFileSync(join(data, 'adapter.pid'), String(process.pid))+ const socket = await listenLocalSocket((_req, res) => res.end(JSON.stringify({+ version: '0.3.40-dev.fixture', connected: true, signedIn: true, sessions: [],+ backendUrl: 'wss://daemon.example', autonomousEnv: 'stag', dataDir: '/daemon/state', authDir: '/daemon/auth',+ })), localSocketPath(data, Number(process.env.PORT ?? 18473))!)+ try {+ const result = await runAsync(root, ['status'], 'wss://caller.example')+ expect(result.status, result.stderr).toBe(0)+ expect(result.stdout).toContain('wss://daemon.example')+ expect(result.stdout).toMatch(/account\s+stag/)+ expect(result.stdout).toContain('running · backend connected')+ expect(result.stdout).toContain('/daemon/state')+ expect(result.stdout).toContain('/daemon/auth')+ expect(result.stdout).not.toContain('caller.example')+ } finally { await socket.close() }+ })++ it('works with an older daemon without guessing its missing account environment', async () => {+ const root = statusRoot()+ seedSession(root)+ const data = join(root, 'data')+ mkdirSync(data)+ writeFileSync(join(data, 'adapter.pid'), String(process.pid))+ const socket = await listenLocalSocket((_req, res) => res.end(JSON.stringify({+ version: '0.3.40', connected: true, sessions: [], backendUrl: 'wss://older.example',+ })), localSocketPath(data, Number(process.env.PORT ?? 18473))!)+ try {+ const result = await runAsync(root, ['status'], 'wss://caller.example')+ expect(result.status, result.stderr).toBe(0)+ expect(result.stdout).toContain('wss://older.example')+ expect(result.stdout).toMatch(/account\s+unknown/)+ expect(result.stdout).not.toContain('caller.example')+ } finally { await socket.close() }+ })+})+describe('harness auth status --json', () => {it('reports loggedIn:false with no saved session, and never touches the network', () => {const root = tempRoot()diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex f012aa380..dd576fa20 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -1,4 +1,5 @@#!/usr/bin/env node+import './config/loadEnv.js'import { CompanionZoo, readCompanionIdentity, type CompanionIdentity } from './cable/companionIdentity.js'import { ensureBundledModelManager } from './dsh/builtins.js'import { createDeviceStore, deviceStoreAgents } from './lib/autonomous-device/storeRuntime.js'@@ -25,7 +26,6 @@ import { AutonomousDeviceDirect } from './lib/autonomous-device/direct.js'* and the backend socket (events up / chat + RPCs down).*/-import 'dotenv/config'import { readFileSync, readdirSync, writeFileSync, mkdirSync, openSync, existsSync, rmSync, statSync, renameSync } from 'fs'import { dirname, join, resolve } from 'path'import { fileURLToPath } from 'url'@@ -66,7 +66,7 @@ import { ensureTmuxOnPath } from './lib/tmuxOnPath.js'import { flashCommand } from './lib/flash.js'import { readOrMintComputerId } from './lib/computerIdentity.js'import { awaitLoginCallback, extractCallbackParams, LOGIN_TIMEOUT_MESSAGE } from './lib/loginCallback.js'-import { AuthSessionError, AuthSessionManager, clearAuthSession, readAuthSession, writeAuthSession, type AuthSession } from './lib/authSession.js'+import { AUTH_DIR, AuthSessionError, AuthSessionManager, clearAuthSession, readAuthSession, writeAuthSession, type AuthSession } from './lib/authSession.js'import { LocalPresence, PAIR_HARNESS_DSH, ZooTurnCounter, ZooTurnReporter } from './lib/zooTurns.js'import { ZooLessonReporter } from './lib/zooLessons.js'import { DAEMONS_OFF, DAEMONS_OFF_DETAIL, DaemonsSwitch, localKillSwitch, zooPassthrough, type ZooRead } from './lib/daemonsSwitch.js'@@ -2185,6 +2185,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {const identityFile = join(env.ADAPTER_DATA_DIR, 'e2e', 'identity.json')try { renameSync(identityFile, `${identityFile}.removed-${Date.now()}`) } catch { /* already gone */ }}+ const autonomousEnv = session?.autonomousEnv ?? env.AUTONOMOUS_ENVconst backend = new BackendSocket(session?.machineId ?? computerId(), auth, (connected) => {if (!connected) returnconst sessions = registry.advertised()@@ -2193,7 +2194,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {console.error('[runtime-profile] connect reconcile failed:', err instanceof Error ? err.message : err)})onBackendConnected()- }, computerId())+ }, computerId(), autonomousEnv)backendRef = backendbackend.viewerTargetProvider = (agentId) => dshViewers.forwardingUrl(agentId)@@ -4040,13 +4041,13 @@ async function runForeground(session: AuthSession | null): Promise<void> {identity: sharingIdentity.getIdentity(),grants: new HarnessGrantStore(join(env.ADAPTER_DATA_DIR, 'harness-shares.json')),collaboration: new HarnessCollaborationStore(join(env.ADAPTER_DATA_DIR, 'harness-collaboration.json')),- autonomousEnv: env.AUTONOMOUS_ENV,+ autonomousEnv,terminals, resolveAgent: (id) => registry.resolve(id),send: (id, type, payload) => backend.sendObserver(id, type, payload),publish: (method, path, body) => proxyBackend(method, path, body),watchViewer: (id, send) => sharedViewers.watch(id, send),})- const shareRelay = new HarnessShareRelay(auth, env.BACKEND_WS_URL, env.AUTONOMOUS_ENV, async () => {+ const shareRelay = new HarnessShareRelay(auth, env.BACKEND_WS_URL, autonomousEnv, async () => {const result = await proxyBackend('GET', '/api/harness-shares')if (result.status !== 200) throw new Error('Shared harnesses are temporarily unavailable.')return ((result.body as { data?: { machines?: SharedMachineReference[] } }).data?.machines ?? [])@@ -4479,6 +4480,9 @@ async function runForeground(session: AuthSession | null): Promise<void> {// none could be opened; clients then stay on this port.localSocket: daemonBoot.localSocket?.path ?? null,backendUrl: env.BACKEND_WS_URL,+ autonomousEnv,+ dataDir: env.ADAPTER_DATA_DIR,+ authDir: AUTH_DIR,webUrl: env.WEB_URL,connected: backend.isConnected(),deviceTransportConnected: backend.hasCommander(),@@ -7427,18 +7431,32 @@ async function runForeground(session: AuthSession | null): Promise<void> {* the one fact that tells a daemon on THIS sign-in from one left over from the previous account (see* startCommand). Null when the daemon does not say.*/-async function runningDaemonStatus(): Promise<{ version: string; sessions: number; machineId: string | null; connected: boolean } | null> {+async function runningDaemonStatus(): Promise<{+ version: string; sessions: number; machineId: string | null; connected: boolean+ backendUrl: string | null; autonomousEnv: string | null; signedIn: boolean | null+ dataDir: string | null; authDir: string | null+} | null> {try {const body = await localDaemonStatus(env.ADAPTER_DATA_DIR, env.PORT)?? await legacyDaemonStatus(daemonPort(), readPid(), computerId())if (!body) return null- const status = body as { version?: unknown; sessions?: unknown; machineId?: unknown; connected?: unknown } | null+ const status = body as {+ version?: unknown; sessions?: unknown; machineId?: unknown; connected?: unknown+ backendUrl?: unknown; autonomousEnv?: unknown; signedIn?: unknown; dataDir?: unknown; authDir?: unknown+ } | nullconst version = typeof status?.version === 'string' && status.version ? status.version : VERSIONconst sessions = Array.isArray(status?.sessions) ? status.sessions.length : 0const machineId = typeof status?.machineId === 'string' && status.machineId ? status.machineId : null// Missing on a daemon too old to report it — read as connected, as the desktop app does.const connected = status?.connected !== false- return { version, sessions, machineId, connected }+ return {+ version, sessions, machineId, connected,+ backendUrl: typeof status?.backendUrl === 'string' ? status.backendUrl : null,+ autonomousEnv: typeof status?.autonomousEnv === 'string' ? status.autonomousEnv : null,+ signedIn: typeof status?.signedIn === 'boolean' ? status.signedIn : null,+ dataDir: typeof status?.dataDir === 'string' ? status.dataDir : null,+ authDir: typeof status?.authDir === 'string' ? status.authDir : null,+ }} catch {return null}@@ -7454,6 +7472,7 @@ function printInfoBlock(opts: {status: string; pid: number; machineId?: string; sessions: number; version: string/** The `device` row's text (this machine's key code and whether the account holds it); only `status` shows it. */device?: string+ connection: { backendUrl: string | null; autonomousEnv: string | null; signedIn: boolean; dataDir: string | null; authDir: string | null }}): void {const row = (k: string, v: string): string => ` ${k.padEnd(10)} ${v}`const rule = ' ' + '─'.repeat(37)@@ -7468,7 +7487,10 @@ function printInfoBlock(opts: {if (machineName) console.log(row('machine', machineName))if (opts.device) console.log(row('device', opts.device))console.log(row('version', `v${opts.version}`))- console.log(row('backend', readAuthSession() ? env.BACKEND_WS_URL : 'not signed in · harness login'))+ console.log(row('backend', opts.connection.signedIn ? opts.connection.backendUrl ?? 'unknown · daemon not answering' : 'not signed in · harness login'))+ console.log(row('account', opts.connection.autonomousEnv ?? 'unknown · older daemon'))+ if (opts.connection.dataDir) console.log(row('state', tildify(opts.connection.dataDir)))+ if (opts.connection.authDir) console.log(row('auth', tildify(opts.connection.authDir)))console.log(row('agents', `${opts.sessions} available`))console.log(row('pid', String(opts.pid)))console.log(row('logs', tildify(LOG_FILE)))@@ -7593,6 +7615,13 @@ async function spawnDaemon(session: AuthSession | null, runtimeNode: string | numachineId: session?.machineId,sessions: daemonStatus?.sessions ?? 0,version: daemonStatus?.version ?? VERSION,+ connection: {+ backendUrl: daemonStatus?.backendUrl ?? env.BACKEND_WS_URL,+ autonomousEnv: daemonStatus?.autonomousEnv ?? session?.autonomousEnv ?? env.AUTONOMOUS_ENV,+ signedIn: daemonStatus?.signedIn ?? session !== null,+ dataDir: daemonStatus?.dataDir ?? env.ADAPTER_DATA_DIR,+ authDir: daemonStatus?.authDir ?? AUTH_DIR,+ },})if (!session) {console.log(' Agents, terminals and the cabled dial work here. `harness login` adds your other machines.')@@ -8417,6 +8446,7 @@ async function status(): Promise<void> {const alive = pid != null && isAlive(pid)const session = readAuthSession()const daemonStatus = alive ? await runningDaemonStatus() : null+ const signedIn = daemonStatus?.signedIn ?? session !== nullif (!alive) registry.load()// A daemon whose start-up failed is alive and answering, but nothing on this machine works. Say so// in the one line a person reads, rather than leaving it looking like an ordinary slow start.@@ -8430,7 +8460,7 @@ async function status(): Promise<void> {? '○ stopped': safeMode? `◍ safe mode · start-up failed on v${safeMode.version} — waiting for a fixed build (${safeMode.error.split('\n')[0]})`- : !session+ : !signedIn? '● running · this computer only (not signed in)': daemonStatus == null? '● running · not answering yet'@@ -8456,6 +8486,15 @@ async function status(): Promise<void> {? deviceRegistration(peekIdentityPub(), new DeviceLogStore().read(), identitySpent()): !peekIdentityPub() && identitySpent() ? 'removed' : null,) ?? undefined,+ // A status command can run with different shell settings from the daemon. Report the daemon's+ // connection, not those of this short-lived caller; missing fields on older daemons stay unknown.+ connection: {+ backendUrl: alive ? daemonStatus?.backendUrl ?? null : env.BACKEND_WS_URL,+ autonomousEnv: alive ? daemonStatus?.autonomousEnv ?? null : session?.autonomousEnv ?? env.AUTONOMOUS_ENV,+ signedIn,+ dataDir: alive ? daemonStatus?.dataDir ?? null : env.ADAPTER_DATA_DIR,+ authDir: alive ? daemonStatus?.authDir ?? null : AUTH_DIR,+ },})process.exit(0)}diff --git a/cli/src/config/env.ts b/cli/src/config/env.tsindex d09beffd2..f374a6ac4 100644--- a/cli/src/config/env.ts+++ b/cli/src/config/env.ts@@ -1,4 +1,4 @@-import 'dotenv/config'+import './loadEnv.js'import { existsSync, mkdirSync, readdirSync, renameSync, rmSync } from 'fs'import { homedir } from 'os'import { join } from 'path'diff --git a/cli/src/config/loadEnv.spec.ts b/cli/src/config/loadEnv.spec.tsnew file mode 100644index 000000000..5291a86cd--- /dev/null+++ b/cli/src/config/loadEnv.spec.ts@@ -0,0 +1,60 @@+import { spawnSync } from 'node:child_process'+import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { fileURLToPath } from 'node:url'+import { afterEach, describe, expect, it } from 'vitest'++const tsx = fileURLToPath(new URL('../../node_modules/tsx/dist/cli.mjs', import.meta.url))+const loader = fileURLToPath(new URL('./loadEnv.ts', import.meta.url))+const roots: string[] = []+afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }) })++function project(): string {+ const root = mkdtempSync(join(tmpdir(), 'harness-env-'))+ roots.push(root)+ writeFileSync(join(root, '.env'), 'BACKEND_WS_URL=ws://sandbox.invalid:8090\nAUTONOMOUS_ENV=stag\nADAPTER_DATA_DIR=/sandbox/data\nHARNESS_AUTH_DIR=/sandbox/auth\nPORT=3000\n')+ return root+}++function run(cwd: string, overrides: NodeJS.ProcessEnv = {}) {+ const childEnv = { ...process.env }+ for (const key of ['BACKEND_WS_URL', 'AUTONOMOUS_ENV', 'ADAPTER_DATA_DIR', 'HARNESS_AUTH_DIR', 'PORT', 'HARNESS_ENV_FILE', 'DOTENV_CONFIG_PATH']) delete childEnv[key]+ const script = `import ${JSON.stringify(loader)}; console.log(JSON.stringify(Object.fromEntries(['BACKEND_WS_URL','AUTONOMOUS_ENV','ADAPTER_DATA_DIR','HARNESS_AUTH_DIR','PORT'].map(k => [k, process.env[k] ?? null]))));`+ return spawnSync(process.execPath, [tsx, '--eval', script], { cwd, env: { ...childEnv, ...overrides }, encoding: 'utf8', timeout: 10_000 })+}++describe('Harness environment loading', () => {+ it('does not adopt a project .env when a user starts Harness from that folder', () => {+ const result = run(project())+ expect(result.status, result.stderr).toBe(0)+ expect(JSON.parse(result.stdout)).toEqual({ BACKEND_WS_URL: null, AUTONOMOUS_ENV: null, ADAPTER_DATA_DIR: null, HARNESS_AUTH_DIR: null, PORT: null })+ })++ it('uses an explicitly selected file from any project, with exported variables taking precedence', () => {+ const root = project()+ const other = join(root, 'another-project')+ mkdirSync(other)+ const file = join(root, 'harness.env')+ writeFileSync(file, 'BACKEND_WS_URL=ws://chosen.invalid:8090\nAUTONOMOUS_ENV=stag\nADAPTER_DATA_DIR=/chosen/data\nHARNESS_AUTH_DIR=/chosen/auth\n')+ for (const cwd of [root, other]) {+ const result = run(cwd, { HARNESS_ENV_FILE: file, AUTONOMOUS_ENV: 'prod' })+ expect(result.status, result.stderr).toBe(0)+ expect(JSON.parse(result.stdout)).toEqual({ BACKEND_WS_URL: 'ws://chosen.invalid:8090', AUTONOMOUS_ENV: 'prod', ADAPTER_DATA_DIR: '/chosen/data', HARNESS_AUTH_DIR: '/chosen/auth', PORT: null })+ }+ })++ it('keeps explicitly configured DOTENV_CONFIG_PATH working', () => {+ const root = project()+ const result = run(root, { DOTENV_CONFIG_PATH: join(root, '.env') })+ expect(result.status, result.stderr).toBe(0)+ expect(JSON.parse(result.stdout)).toMatchObject({ BACKEND_WS_URL: 'ws://sandbox.invalid:8090', AUTONOMOUS_ENV: 'stag' })+ })++ it('fails clearly if the explicitly selected environment file cannot be read', () => {+ const root = project()+ const result = run(root, { HARNESS_ENV_FILE: join(root, 'missing.env') })+ expect(result.status).not.toBe(0)+ expect(result.stderr).toContain('Cannot read Harness environment file')+ })+})diff --git a/cli/src/config/loadEnv.ts b/cli/src/config/loadEnv.tsnew file mode 100644index 000000000..3c881b656--- /dev/null+++ b/cli/src/config/loadEnv.ts@@ -0,0 +1,12 @@+import { config } from 'dotenv'+import { resolve } from 'node:path'++// Harness is started from users' projects. Their .env belongs to the project, not to the daemon:+// reading it can move this machine to a different backend, account store or encryption identity.+// Dev and release builds use the same defaults. An isolated backend is always an explicit choice.+const file = process.env.HARNESS_ENV_FILE?.trim() || process.env.DOTENV_CONFIG_PATH?.trim()+if (file) {+ const path = resolve(file)+ const result = config({ path, quiet: true, override: false })+ if (result.error) throw new Error(`Cannot read Harness environment file: ${path}`, { cause: result.error })+}diff --git a/cli/src/lib/remoteRelay.ts b/cli/src/lib/remoteRelay.tsindex b4ba9158b..2ec16a9bb 100644--- a/cli/src/lib/remoteRelay.ts+++ b/cli/src/lib/remoteRelay.ts@@ -498,7 +498,14 @@ export class RemoteRelayPool {if (isBinary) returnlet frame: Frametry { frame = JSON.parse(raw.toString()) as Frame } catch { return }- const payload = frame.payload as { machineId?: unknown; error?: unknown; p2p?: unknown } | undefined+ const payload = frame.payload as { machineId?: unknown; error?: unknown; p2p?: unknown; online?: unknown } | undefined+ if (frame.type === 'node_status' && payload?.online === false) {+ if (!settled) {+ settled = true; clearTimeout(timeout)+ reject(new RelayConnectError('MACHINE_OFFLINE', 1013))+ }+ return+ }if (!selected) {// The socket's very first frame, before any select, is {type:'connected',payload:{userId}} —// pure backend bookkeeping with no machineId. Swallow it; it answers nothing this relay asked.@@ -593,6 +600,16 @@ export class RemoteRelayPool {}let frame: Frametry { frame = JSON.parse(raw.toString()) as Frame } catch { return }+ if (frame.type === 'node_status' && framePayload(frame).online === false) {+ // The backend socket outlives the remote daemon. Its next incarnation has no knowledge of+ // this session's keys, even when it runs the identical CLI version. Retire the session as+ // soon as presence goes offline so the next select does a fresh authenticated handshake.+ // Keep the identity pin: going offline is not a revocation or a reason to pair again.+ entry.sink?.sendFrame(frame)+ if (this.entries.get(machineId) === entry) this.entries.delete(machineId)+ try { ws.close(1012, 'remote machine disconnected') } catch { ws.terminate() }+ return+ }if (frame.type === 'e2e_rekey') { crypto.handleRekey((frame.payload ?? {}) as Record<string, unknown>); return }if (frame.type === 'e2e_denied') {// Mid-session revoke (e.g. `harness unpair` run on the peer while this relay was already@@ -674,13 +691,16 @@ export class RemoteRelayPool {ws.on('close', (code, reasonBuf) => {entry.viewers?.close()entry.heartbeat?.stop()+ if (entry.lingerTimer) clearTimeout(entry.lingerTimer)+ entry.lingerTimer = nullif (entry.p2pRetryTimer) clearTimeout(entry.p2pRetryTimer)if (entry.upgradeTimer) clearTimeout(entry.upgradeTimer)void entry.upgradeShadow?.stop('relay_closed', false)void entry.upgradeOrphan?.stop('relay_closed', false)void entry.p2p?.stop('relay_closed', false)entry.p2p = null- this.entries.delete(machineId)+ // An invalidated/retired socket can finish closing after its replacement has already dialed.+ if (this.entries.get(machineId) === entry) this.entries.delete(machineId)entry.onClosed?.(code, reasonBuf?.toString() ?? '')})entry.heartbeat = watchSocketLiveness(ws, {@@ -705,6 +725,7 @@ export class RemoteRelayPool {// Several local views share this upstream connection. Keep each view's terminal lease// distinct, but stable across its opens (and across relay/P2P transport changes).const viewId = randomUUID()+ let detached = falsereturn {send: async (frame) => {if (frame.type === 'terminal_open') {@@ -758,11 +779,14 @@ export class RemoteRelayPool {if (p2pFailed) this.demoteP2p(machineId, entry, 'send_failed')},detach: () => {+ if (detached) return+ detached = true// This client only; the upstream stays for whoever else is on it, and lingers a while for// the next select once nobody is.if (client) entry.attached.delete(client)bindAttached(entry)if (entry.attached.size > 0) return+ if (this.entries.get(machineId) !== entry) returnentry.viewers?.reset()entry.lingerTimer = setTimeout(() => {if (!entry.sink) {@@ -773,7 +797,7 @@ export class RemoteRelayPool {void entry.p2p?.stop('idle', false)entry.p2p = nulltry { entry.ws.close(1000, 'idle') } catch { /* ignore */ }- this.entries.delete(machineId)+ if (this.entries.get(machineId) === entry) this.entries.delete(machineId)}}, this.lingerMs)entry.lingerTimer.unref?.()diff --git a/cli/src/lib/remoteRelayRestart.spec.ts b/cli/src/lib/remoteRelayRestart.spec.tsnew file mode 100644index 000000000..7c068ce95--- /dev/null+++ b/cli/src/lib/remoteRelayRestart.spec.ts@@ -0,0 +1,127 @@+import { afterEach, describe, expect, it, vi } from 'vitest'+import { WebSocket, WebSocketServer } from 'ws'+import type { AddressInfo } from 'node:net'+import { RemoteRelayPool } from './remoteRelay.js'+import { E2eeManager } from './e2ee/manager.js'+import { MachinePeerStore } from './e2ee/machinePeers.js'+import { b64e, newIdentity } from './e2ee/core.js'+import { E2eeStore } from './e2ee/store.js'+import type { LocalClientSink } from '../backendSocket.js'++const machineId = 'abcdabcdabcdabcdabcdabcdabcdabcd'+type Frame = { type: string; payload?: Record<string, unknown> }+const cleanups: Array<() => Promise<void>> = []+afterEach(async () => { for (const cleanup of cleanups.splice(0)) await cleanup() })++async function fixture(opts: { offline?: boolean; lingerMs?: number } = {}) {+ const sockets = new Map<string, WebSocket>()+ let next = 0+ let hellos = 0+ const wss = new WebSocketServer({ port: 0, host: '127.0.0.1' })+ await new Promise<void>(resolve => wss.once('listening', resolve))+ const managerDeps = {+ machineId, isConnected: () => true,+ sendTo: (id: string, frame: unknown) => sockets.get(id)?.send(JSON.stringify(frame)),+ }+ let manager = new E2eeManager(managerDeps)+ const self = newIdentity()+ manager.trustPeer({ pub: b64e(self.pub), kind: 'machine', machineId: '12341234123412341234123412341234', label: 'test client' })+ const store = new E2eeStore(); store.init()+ const peerPub = b64e(store.getIdentity().pub)+ const peers = new MachinePeerStore(); peers.pin(machineId, peerPub, 'test remote')+ const pool = new RemoteRelayPool(+ { accessToken: async () => 'fixture-token' } as never,+ `ws://127.0.0.1:${(wss.address() as AddressInfo).port}`,+ self, peers, { p2p: false, lingerMs: opts.lingerMs },+ )+ wss.on('connection', ws => {+ const id = `remote-${++next}`+ sockets.set(id, ws)+ ws.on('close', () => { sockets.delete(id); manager.dropSession(id) })+ ws.on('message', raw => {+ const frame = JSON.parse(raw.toString()) as Frame+ if (frame.type === 'machine_select') {+ ws.send(JSON.stringify({ type: 'connected', payload: { machineId } }))+ if (opts.offline) ws.send(JSON.stringify({ type: 'node_status', payload: { online: false } }))+ } else if (frame.type === 'e2e_hello') {+ hellos+++ if (!opts.offline) manager.handleFrame(id, frame)+ } else if (frame.type === 'agents_list') {+ const clear = manager.unwrapDown(id, frame)+ if (clear) ws.send(JSON.stringify(manager.wrapTarget(id, 'agents_list_result', { ...clear.payload as object, agents: [{ id: 'still-here' }] })))+ }+ })+ })+ cleanups.push(async () => {+ pool.invalidate(machineId); pool.invalidateIsolated(machineId)+ for (const ws of wss.clients) ws.terminate()+ await new Promise<void>(resolve => wss.close(() => resolve()))+ })+ return {+ pool, peers, peerPub, hellos: () => hellos,+ select: { type: 'machine_select', payload: { machineId } },+ restart() { manager = new E2eeManager(managerDeps) },+ status(online: boolean) { for (const ws of sockets.values()) ws.send(JSON.stringify({ type: 'node_status', payload: { online } })) },+ }+}++describe('remote daemon restart recovery', () => {+ it('reports an offline peer immediately during the handshake and keeps its trust', async () => {+ const f = await fixture({ offline: true })+ await expect(f.pool.acquire(machineId, 'prod', f.select, { sendFrame: () => true, sendBinary: () => true }, () => {}))+ .rejects.toMatchObject({ message: 'MACHINE_OFFLINE', closeCode: 1013 })+ expect(f.peers.get(machineId)?.pub).toBe(f.peerPub)+ })++ it.each(['desktop', 'background'] as const)('renegotiates after a remote restart for a %s client, without discarding trust', async kind => {+ const f = await fixture()+ const inbox: Frame[] = []+ const closed = vi.fn()+ const sink: LocalClientSink = { sendFrame: frame => { inbox.push(frame as Frame); return true }, sendBinary: () => true }+ const acquire = () => kind === 'desktop'+ ? f.pool.acquire(machineId, 'prod', f.select, sink, closed)+ : f.pool.acquireIsolated(machineId, 'prod', f.select, sink, closed)+ const first = await acquire()+ await first.send({ type: 'agents_list', payload: { requestId: 'before' } })+ await vi.waitFor(() => expect(inbox.some(frame => frame.payload?.requestId === 'before')).toBe(true))+ // The backend WebSocket survives. Only the remote daemon, which owns the session keys, restarts.+ f.status(false)+ f.restart()+ await vi.waitFor(() => expect(closed).toHaveBeenCalledWith(1012, 'remote machine disconnected'))+ expect(f.peers.get(machineId)?.pub).toBe(f.peerPub)+ first.detach()+ const second = await acquire()+ f.status(true)+ await second.send({ type: 'agents_list', payload: { requestId: 'after' } })+ await vi.waitFor(() => expect(inbox.some(frame => frame.payload?.requestId === 'after')).toBe(true))+ expect(f.hellos()).toBe(2)+ second.detach()+ })++ it('preserves a healthy session when ordinary online presence arrives', async () => {+ const f = await fixture()+ const closed = vi.fn()+ const inbox: Frame[] = []+ const session = await f.pool.acquire(machineId, 'prod', f.select, { sendFrame: frame => { inbox.push(frame as Frame); return true }, sendBinary: () => true }, closed)+ f.status(true)+ await session.send({ type: 'agents_list', payload: { requestId: 'healthy' } })+ await vi.waitFor(() => expect(inbox.some(frame => frame.payload?.requestId === 'healthy')).toBe(true))+ expect(closed).not.toHaveBeenCalled()+ expect(f.hellos()).toBe(1)+ session.detach()+ })++ it('an obsolete view detaching cannot evict the replacement connection later', async () => {+ const f = await fixture({ lingerMs: 10 })+ const sink = { sendFrame: () => true, sendBinary: () => true }+ const first = await f.pool.acquire(machineId, 'prod', f.select, sink, () => {})+ f.pool.invalidate(machineId)+ const second = await f.pool.acquire(machineId, 'prod', f.select, sink, () => {})+ first.detach()+ first.detach()+ await new Promise(resolve => setTimeout(resolve, 40))+ const third = await f.pool.acquire(machineId, 'prod', f.select, sink, () => {})+ expect(f.hellos()).toBe(2)+ second.detach(); third.detach()+ })+})diff --git a/docs/development.md b/docs/development.mdindex 7f95ef507..cce4738ad 100644--- a/docs/development.md+++ b/docs/development.md@@ -85,6 +85,25 @@ brings up a second machine in Docker so the remote path can be exercised from on## Isolated end-to-end testing+A dev CLI uses the production backend and existing machine identity unless explicitly configured+otherwise. Running it from a repository does not load that repository's `.env`. For an intentional+local/staging daemon, export the settings or set `HARNESS_ENV_FILE` to an absolute config path+(see [CLI configuration](../cli/README.md)). Keep its+`ADAPTER_DATA_DIR`, `HARNESS_AUTH_DIR`, `ADAPTER_COMPUTER_ID_FILE` and port separate from the+everyday daemon. `harness status` reports the running daemon's backend and account environment.++The connection regression tests use local WebSockets and real encryption. The packaged daemon's+account routing and status can also be checked without a real account or installed daemon:++```bash+cd cli+npm run bundle+node scripts/check-connection-environment.mjs+```++This smoke test uses temporary state, a fixture tmux command and a loopback backend; it verifies+both production and staging sign-ins against conflicting shell settings.+With Node, tmux, Flutter and a running Docker engine, run from the repository root:```bash