Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Fix hn local startup and per-user daemon discovery (#503)

Dee4844f2745e17
diff --git a/cli/README.md b/cli/README.md
index 999b1810e..f82467547 100644
--- a/cli/README.md
+++ b/cli/README.md
@@ -63,20 +63,20 @@ it uses temporary identities and loopback sockets, never live machine state.
## Install & run (`harness`)
-Install the CLI, then sign in once with the same SSO account used by Harness:
+Install the CLI and run `hn` to work locally. Sign in when you want to connect other machines:
```bash
curl -fsSL https://harness.autonomous.ai/cli/install.sh | bash
```
(The installer is a first-party hosted script. It brings its own Node, downloads the published
-bundle and writes the `~/.local/bin/harness` command, and `hn`: Harness in a terminal, which signs in
-and starts the daemon the first time you run it.)
+bundle and writes the `~/.local/bin/harness` command, and `hn`: Harness in a terminal, which starts
+your local daemon the first time you run it. Local use requires no login.)
```bash
harness login # opens browser SSO and saves this computer's session
harness login --force # stop the daemon and sign in as a different SSO account
-harness start # starts the adapter from the saved SSO session
+harness start # starts the local adapter; uses a saved SSO session if present
harness start -f # foreground mode for a supervisor; logs to stdout
harness status # is it running? shows pid + the chat link
harness stop # stop the background adapter
diff --git a/cli/scripts/install.sh b/cli/scripts/install.sh
index 2986b030c..358b12c95 100755
--- a/cli/scripts/install.sh
+++ b/cli/scripts/install.sh
@@ -10,7 +10,7 @@
# curl -fsSL https://cdn.autonomous.ai/harness/cli/install.sh | bash # the CLI and hn
# curl -fsSL https://cdn.autonomous.ai/harness/cli/install.sh | sh -s -- --desktop # Desktop: runtime + CLI only
# curl -fsSL https://cdn.autonomous.ai/harness/cli/install.sh | sh -s -- --host # Desktop: host requirements only
-# hn # Harness in this terminal: signs in and starts the daemon the first time
+# hn # Harness in this terminal: starts locally, no login required
# harness login
# harness start
# harness remote-password set # so your other machines (and `harness remote`) can reach this one
@@ -770,7 +770,7 @@ else
echo ""
echo " Start here — every harness on every machine, in this terminal:"
echo ""
- echo " hn # signs in and connects this computer the first time"
+ echo " hn # start locally; no login required"
echo ""
echo " Or set this computer up step by step — three commands, in this order:"
echo ""
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index 5cbcf808a..d5134c04c 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -194,6 +194,7 @@ import {
import { Watcher, type HistoryEvent, type LineEvent } from './watcher/watcher.js'
import { chooseHookAgent, startHookServer } from './hookServer.js'
import { isLocalSocketName, localSocketPath, type LocalSocketServer } from './lib/localSocket.js'
+import { legacyDaemonStatus, localDaemonStatus, saveDaemonPort } from './lib/daemonEndpoint.js'
import { commandBarService } from './lib/commandBar.js'
import { BackendSocket, isLocalClientId } from './backendSocket.js'
import { AutonomousDeviceService } from './lib/autonomous-device/service.js'
@@ -1331,9 +1332,8 @@ async function logout(): Promise<void> {
* 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.
+ // OUR daemon, by its pid file and private socket. A login in another HOME must never restart a
+ // different OS user's daemon just because it happens to hold the default TCP port.
const pid = readPid()
if (!pid || !isAlive(pid)) return
const daemon = await runningDaemonStatus()
@@ -3874,7 +3874,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
}
- const { server: hookServer, port: hookPort, localSocket } = await startHookServer(env.PORT, {
+ const { server: hookServer, port: hookPort, localSocket } = await startHookServer(daemonPort(), {
onPromptContext: (agentId) => companionPromptContext(agentId),
onCommandBar: commandBarService,
onAutonomousDeviceRequest: async (method, target, body) => {
@@ -4266,7 +4266,12 @@ async function runForeground(session: AuthSession | null): Promise<void> {
onZooRead: () => zooProxy.read(),
onZooOps: (body) => zooProxy.ops(body),
onStore: (method, path, body) => proxyBackend(method, path, body),
- }, { socketPath: localSocketPath(env.ADAPTER_DATA_DIR, env.PORT) })
+ }, { socketPath: localSocketPath(env.ADAPTER_DATA_DIR, env.PORT), allowPortFallback: true })
+ try { saveDaemonPort(env.ADAPTER_DATA_DIR, env.PORT, hookPort) } catch (error) {
+ await localSocket?.close()
+ hookServer.close()
+ throw error
+ }
// Claim the pid file for OURSELVES, and only now that the control port is bound. It used to be
// written by whoever spawned us — so a parent that died mid-handover left a daemon nothing could
// manage — and then, for a while, by us at the top of this function, before the bind — so a child
@@ -6998,11 +7003,9 @@ async function runForeground(session: AuthSession | null): Promise<void> {
*/
async function runningDaemonStatus(): Promise<{ version: string; sessions: number; machineId: string | null; connected: boolean } | null> {
try {
- const res = await fetch(`http://127.0.0.1:${daemonPort()}/api/status`, {
- signal: AbortSignal.timeout(1_500),
- })
- if (!res.ok) return null
- const body: unknown = await res.json()
+ 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 version = typeof status?.version === 'string' && status.version ? status.version : VERSION
const sessions = Array.isArray(status?.sessions) ? status.sessions.length : 0
@@ -7208,9 +7211,11 @@ function clearAdapterState(): void {
]) {
rmSync(join(dir, name), { recursive: true, force: true })
}
- // One daemon socket per control port (lib/localSocket.ts) — whichever ports have run here.
+ // Private sockets and actual TCP port records — whichever configured ports have run here.
try {
- for (const name of readdirSync(dir)) if (isLocalSocketName(name)) rmSync(join(dir, name), { force: true })
+ for (const name of readdirSync(dir)) {
+ if (isLocalSocketName(name) || /^daemon-\d+\.json$/.test(name)) rmSync(join(dir, name), { force: true })
+ }
} catch { /* no such directory */ }
}
if (dataDir === cliDir) rmStateFiles(dataDir)
@@ -8022,7 +8027,8 @@ const enterSafeMode = (err: unknown): void => {
// itself was what failed, or we never got that far — take the port for the status alone, so the app
// still reads not-ready rather than down. A port we cannot take at all leaves only a ticking clock.
if (!daemonBoot.hookServer) {
- const hosts = loopbackHosts(env.PORT)
+ const port = daemonPort()
+ const hosts = loopbackHosts(port)
const status = createServer((req, res) => {
if (!isLoopbackRequest(req, hosts)) { res.writeHead(403).end(); return }
const body = safeModeStatusBody({
@@ -8033,11 +8039,11 @@ const enterSafeMode = (err: unknown): void => {
res.end(JSON.stringify(body))
})
status.on('error', (e) => {
- console.error(`[safe-mode] could not serve status on ${env.PORT}: ${e instanceof Error ? e.message : e}`)
+ console.error(`[safe-mode] could not serve status on ${port}: ${e instanceof Error ? e.message : e}`)
// A ref'd timer, unlike the updater's: something has to hold the event loop open.
setInterval(() => console.log(`[safe-mode] still waiting for a fixed build · v${VERSION}`), 10 * 60_000)
})
- status.listen(env.PORT, '127.0.0.1')
+ status.listen(port, '127.0.0.1')
}
// Bounded on purpose. A cause that has since cleared — tmux not yet on PATH after a reboot, a lock
@@ -8091,7 +8097,7 @@ switch (cmd) {
runForeground(readAuthSession()).catch(enterSafeMode)
break
case 'autonomous-device':
- runAutonomousDeviceCommand(rest, env.ADAPTER_DATA_DIR, env.PORT).then(code => { process.exitCode = code }).catch(onError)
+ runAutonomousDeviceCommand(rest, env.ADAPTER_DATA_DIR, daemonPort()).then(code => { process.exitCode = code }).catch(onError)
break
case 'pair': {
// `harness pair <code>` pairs a browser; `harness pair <verb>` is the daemon's control interface
@@ -8184,7 +8190,7 @@ switch (cmd) {
}).then((code) => { process.exitCode = code }).catch(onError)
break
case 'tui':
- tuiCommand(rest, { port: daemonPort(), signedIn: () => readAuthSession() !== null }).then((code) => { process.exitCode = code }).catch(onError)
+ tuiCommand(rest, { port: env.PORT, dataDir: env.ADAPTER_DATA_DIR, identity: wantedDaemonIdentity }).then((code) => { process.exitCode = code }).catch(onError)
break
case 'remote':
remoteCommand({
diff --git a/cli/src/cliCommand.spec.ts b/cli/src/cliCommand.spec.ts
index 798022bc7..72dd95209 100644
--- a/cli/src/cliCommand.spec.ts
+++ b/cli/src/cliCommand.spec.ts
@@ -1,11 +1,11 @@
import { spawn, spawnSync, type ChildProcess } from 'child_process'
import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'fs'
-import { createServer, type Server } from 'node:http'
+import { createServer, type RequestListener, type Server } from 'node:http'
import type { AddressInfo } from 'node:net'
-import { tmpdir } from 'os'
import { join } from 'path'
import { fileURLToPath } from 'url'
import { afterEach, describe, expect, it } from 'vitest'
+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')
@@ -27,7 +27,8 @@ afterEach(async () => {
/** A throwaway HOME for one CLI run; every path the CLI writes is under it. */
function freshRoot(): string {
- const root = mkdtempSync(join(tmpdir(), 'harness-cli-command-'))
+ // Keep the private socket below macOS's sockaddr_un path limit.
+ const root = mkdtempSync('/tmp/hn-cli-command-')
dirs.push(root)
return root
}
@@ -93,16 +94,21 @@ function seedRunningDaemon(root: string): { pid: number; exited: Promise<void> }
return { pid: child.pid ?? -1, exited: new Promise((resolve) => child.once('exit', () => resolve())) }
}
-/** The one thing `start` asks a live daemon: GET /api/status, for the machine it serves. Bound to a
- * port of its own, which the test hands the CLI as PORT. */
-async function daemonStatusServer(machineId: string): Promise<number> {
- const server = createServer((_req, res) => {
+/** The daemon's status through this user's private socket, plus its occupied TCP control port. */
+async function daemonStatusServer(root: string, machineId: string): Promise<number> {
+ const handler: RequestListener = (_req, res) => {
res.setHeader('content-type', 'application/json')
res.end(JSON.stringify({ machineId, version: '0.0.0-test', sessions: [] }))
- })
+ }
+ const server = createServer(handler)
servers.push(server)
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))
- return (server.address() as AddressInfo).port
+ const port = (server.address() as AddressInfo).port
+ const dir = join(root, 'data')
+ mkdirSync(dir, { recursive: true, mode: 0o700 })
+ const privateServer = await listenLocalSocket(handler, localSocketPath(dir, port)!)
+ servers.push(privateServer.server)
+ return port
}
describe('CLI login/start command contract', () => {
@@ -232,7 +238,7 @@ describe('start beside a daemon that serves another account', () => {
const root = freshRoot()
seedSession(root) // machineId m_seeded
const daemon = seedRunningDaemon(root)
- const port = await daemonStatusServer('m_other')
+ const port = await daemonStatusServer(root, 'm_other')
const result = await runAsync(root, ['start'], { PORT: String(port) })
@@ -240,8 +246,8 @@ describe('start beside a daemon that serves another account', () => {
expect(result.stdout).not.toContain('already running')
await daemon.exited
expect(existsSync(join(root, 'data', 'adapter.pid'))).toBe(false)
- // The restart goes on to boot a daemon inline (a repo run) — which fails to bind, because the port
- // it was handed is this test's own status server. Past the point under test; the backend is never
+ // The restart goes on to boot a daemon inline (a repo run) — which refuses to displace this
+ // fixture's still-live private socket. Past the point under test; the backend is never
// consulted (start no longer resolves the machine when the session already names one).
expect(result.status).toBe(1)
expect(result.stdout + result.stderr).not.toContain('resolve-computer')
@@ -249,11 +255,11 @@ describe('start beside a daemon that serves another account', () => {
it('starts without the backend: a session that already names its machine never calls it', async () => {
// Offline is the case this exists for. The backend here is port 1 — refused instantly — and the
- // only thing that stops the boot is the port clash with this test's status server, AFTER the point
+ // only thing that stops the boot is this fixture's live private socket, AFTER the point
// where `start` used to abort on the resolve. No "Failed to start adapter: fetch failed".
const root = freshRoot()
seedSession(root)
- const port = await daemonStatusServer('m_other')
+ const port = await daemonStatusServer(root, 'm_other')
const result = await runAsync(root, ['start'], { PORT: String(port) })
@@ -269,7 +275,7 @@ describe('start beside a daemon that serves another account', () => {
version: 1, accessToken: 'tok', refreshToken: 'refresh', expiresAt: Date.now() + 3_600_000,
autonomousEnv: 'prod', computerId: 'a'.repeat(32), updatedAt: Date.now(),
}))
- const port = await daemonStatusServer('m_other')
+ const port = await daemonStatusServer(root, 'm_other')
const result = await runAsync(root, ['start'], { PORT: String(port) })
@@ -281,7 +287,7 @@ describe('start beside a daemon that serves another account', () => {
const root = freshRoot()
seedSession(root)
const daemon = seedRunningDaemon(root)
- const port = await daemonStatusServer('m_seeded')
+ const port = await daemonStatusServer(root, 'm_seeded')
const result = await runAsync(root, ['start'], { PORT: String(port) })
diff --git a/cli/src/config/env.ts b/cli/src/config/env.ts
index 0c4285912..d09beffd2 100644
--- a/cli/src/config/env.ts
+++ b/cli/src/config/env.ts
@@ -117,9 +117,9 @@ migrateLegacyAdapterState()
const envSchema = z.object({
NODE_ENV: z.enum(['development', 'production', 'test']).default('development'),
- // Localhost port the SessionStart/SessionEnd hook callbacks POST to (hook/notify.mjs). A quiet FIXED
- // value (below the OS ephemeral range, outside the project's 80xx/8100-8999/9001-9999 ranges). No
- // free-port fallback — if it's taken, the adapter reports it (another adapter is likely running).
+ // Preferred localhost control port, also the stable name of this user's private daemon socket.
+ // When another OS user holds it, Unix daemons record a separate TCP port in this user's data dir;
+ // engine hooks and CLI commands use that actual port while native clients use the private socket.
PORT: z.string().default('18473').transform(Number),
// The loopback port `harness login` listens on for the SSO redirect. 0 (the default) takes whatever
// the OS gives, which is right on a real computer: the browser and the listener are the same
diff --git a/cli/src/hookServer.ts b/cli/src/hookServer.ts
index d09e0fe6f..8444fb681 100644
--- a/cli/src/hookServer.ts
+++ b/cli/src/hookServer.ts
@@ -386,6 +386,8 @@ async function awaitHermesKind(body: RegisterInput, handlers: HookServerHandlers
export interface HookServerOptions {
/** Also serve on this Unix socket (see lib/localSocket.ts). Null or absent: TCP only. */
socketPath?: string | null
+ /** A private socket identifies this user's daemon even when another OS user holds the TCP port. */
+ allowPortFallback?: boolean
}
export function startHookServer(
@@ -835,36 +837,49 @@ export function startHookServer(
const server = http.createServer(handle)
return new Promise((resolve, reject) => {
- server.once('error', (err: NodeJS.ErrnoException) => {
- // FIXED port — no OS-assigned fallback. A free-port fallback made the daemon land on an
- // unpredictable port, so a leftover/zombie couldn't be found by `lsof :<port>`. On a clash we
- // fail loudly with the exact port instead (the CLI turns this into a clear "already running?").
+ let fellBack = false
+ const failed = (err: NodeJS.ErrnoException): void => {
+ if (err.code === 'EADDRINUSE' && !fellBack && options.allowPortFallback && options.socketPath) {
+ fellBack = true
+ console.log(`[hooks] control port ${port} unavailable; assigning a separate port for this user`)
+ server.once('error', failed)
+ server.listen(0, '127.0.0.1')
+ return
+ }
if (err.code === 'EADDRINUSE') {
console.error(`[hooks] 127.0.0.1:${port} is already in use — another adapter is probably running.`)
- console.error(` Stop it: harness stop or find it: lsof -ti :${port} | xargs kill`)
+ console.error(' Use a different PORT; no other user\'s daemon was stopped.')
} else {
console.error('[hooks] listen failed:', err)
}
reject(err)
- })
- server.listen(port, '127.0.0.1', () => {
+ }
+ server.once('error', failed)
+ server.once('listening', () => {
const actual = (server.address() as AddressInfo).port
hosts = loopbackHosts(actual)
console.log(`[hooks] listening on 127.0.0.1:${actual} (SessionStart/SessionEnd callbacks)`)
const socketPath = options.socketPath
if (!socketPath) { resolve({ server, port: actual, localSocket: null }); return }
- // After the port, never before: holding it is what makes a socket file already there stale.
- // A socket that cannot be opened costs the app its fast path, not the daemon its start.
+ // The private socket is mandatory when opting into multi-user startup. A duplicate daemon
+ // must not survive on a random port while another one owns this user's socket.
listenLocalSocket(handle, socketPath).then(
(localSocket) => {
console.log(`[hooks] listening on ${socketPath}`)
resolve({ server, port: actual, localSocket })
},
(error: unknown) => {
+ if (options.allowPortFallback) {
+ server.closeAllConnections()
+ server.close()
+ reject(error)
+ return
+ }
console.warn(`[hooks] local socket unavailable (${socketPath}): ${error instanceof Error ? error.message : error}`)
resolve({ server, port: actual, localSocket: null })
},
)
})
+ server.listen(port, '127.0.0.1')
})
}
diff --git a/cli/src/lib/daemonEndpoint.spec.ts b/cli/src/lib/daemonEndpoint.spec.ts
new file mode 100644
index 000000000..ac6712783
--- /dev/null
+++ b/cli/src/lib/daemonEndpoint.spec.ts
@@ -0,0 +1,85 @@
+import { createServer } from 'node:http'
+import { chmodSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { afterEach, describe, expect, it } from 'vitest'
+import { legacyDaemonStatus, localDaemonStatus, saveDaemonPort, savedDaemonPort } from './daemonEndpoint.js'
+import { listenLocalSocket, localSocketPath } from './localSocket.js'
+
+const cleanup: Array<() => void | Promise<void>> = []
+afterEach(async () => { for (const close of cleanup.splice(0).reverse()) await close() })
+function directory(): string {
+ const path = mkdtempSync('/tmp/hn-owner-')
+ cleanup.push(() => rmSync(path, { recursive: true, force: true }))
+ return path
+}
+
+describe('per-user daemon discovery', () => {
+ it('never accepts another user\'s TCP status, including when this user has no socket', async () => {
+ let foreignRequests = 0
+ const foreign = createServer((_req, res) => { foreignRequests++; res.end(JSON.stringify({ machineId: 'other-account' })) })
+ await new Promise<void>((resolve) => foreign.listen(0, '127.0.0.1', resolve))
+ cleanup.push(() => new Promise<void>((resolve) => foreign.close(() => resolve())))
+ const port = (foreign.address() as { port: number }).port
+ const userA = directory(), userB = directory()
+ const a = await listenLocalSocket((_req, res) => res.end(JSON.stringify({ machineId: 'account-a' })), localSocketPath(userA, port)!)
+ cleanup.push(a.close)
+ expect(await localDaemonStatus(userB, port)).toBeNull()
+ const b = await listenLocalSocket((_req, res) => res.end(JSON.stringify({ machineId: 'account-b', signedIn: false })), localSocketPath(userB, port)!)
+ cleanup.push(b.close)
+ expect(await localDaemonStatus(userA, port)).toEqual({ machineId: 'account-a' })
+ expect(await localDaemonStatus(userB, port)).toEqual({ machineId: 'account-b', signedIn: false })
+ expect(foreignRequests).toBe(0)
+ })
+
+ it('refuses a socket accessible to other OS users', async () => {
+ const dir = directory(), port = 19418
+ let requests = 0
+ const socket = await listenLocalSocket((_req, res) => { requests++; res.end('{}') }, localSocketPath(dir, port)!)
+ cleanup.push(socket.close)
+ chmodSync(socket.path, 0o666)
+ expect(await localDaemonStatus(dir, port)).toBeNull()
+ expect(requests).toBe(0)
+ })
+
+ it('treats invalid status responses as unavailable', async () => {
+ const dir = directory(), port = 19418
+ let body = 'not json', status = 200
+ const socket = await listenLocalSocket((_req, res) => { res.statusCode = status; res.end(body) }, localSocketPath(dir, port)!)
+ cleanup.push(socket.close)
+ expect(await localDaemonStatus(dir, port)).toBeNull()
+ body = '[]'
+ expect(await localDaemonStatus(dir, port)).toBeNull()
+ body = '{}'; status = 503
+ expect(await localDaemonStatus(dir, port)).toBeNull()
+ })
+
+ it('persists separate TCP port records per user and configured endpoint', () => {
+ const a = directory(), b = directory()
+ expect(savedDaemonPort(a, 18473)).toBe(18473)
+ saveDaemonPort(a, 18473, 24567)
+ expect(savedDaemonPort(a, 18473)).toBe(24567)
+ expect(savedDaemonPort(b, 18473)).toBe(18473)
+ expect(savedDaemonPort(a, 18474)).toBe(18474)
+ const file = join(a, 'daemon-18473.json')
+ expect(statSync(file).mode & 0o777).toBe(0o600)
+ expect(JSON.parse(readFileSync(file, 'utf8'))).toEqual({ port: 24567 })
+ for (const body of ['broken', '{}', '{"port":-1}', '{"port":65536}', '{"port":"24567"}']) {
+ writeFileSync(file, body)
+ expect(savedDaemonPort(a, 18473)).toBe(18473)
+ }
+ })
+
+ it('accepts legacy CLI status only when both the saved PID and computer identity match', async () => {
+ const status = { pid: 43210, computerId: 'this-user', machineId: 'signed-out-local' }
+ let requests = 0
+ const server = createServer((_req, res) => { requests++; res.end(JSON.stringify(status)) })
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))
+ cleanup.push(() => new Promise<void>((resolve) => { server.closeAllConnections(); server.close(() => resolve()) }))
+ const port = (server.address() as { port: number }).port
+ expect(await legacyDaemonStatus(port, null, 'this-user')).toBeNull()
+ expect(requests).toBe(0)
+ expect(await legacyDaemonStatus(port, 43211, 'this-user')).toBeNull()
+ expect(await legacyDaemonStatus(port, 43210, 'other-user')).toBeNull()
+ expect(await legacyDaemonStatus(port, 43210, 'this-user')).toEqual(status)
+ })
+})
diff --git a/cli/src/lib/daemonEndpoint.ts b/cli/src/lib/daemonEndpoint.ts
new file mode 100644
index 000000000..4221563e8
--- /dev/null
+++ b/cli/src/lib/daemonEndpoint.ts
@@ -0,0 +1,75 @@
+import { request } from 'node:http'
+import { lstatSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { localSocketPath } from './localSocket.js'
+
+// The configured port names the private socket. TCP may use another port when a different OS
+// user's daemon already holds that number; remember it in THIS user's data directory.
+function portFile(dataDir: string, configuredPort: number): string {
+ return join(dataDir, `daemon-${configuredPort}.json`)
+}
+
+export function savedDaemonPort(dataDir: string, configuredPort: number): number {
+ try {
+ const { port } = JSON.parse(readFileSync(portFile(dataDir, configuredPort), 'utf8'))
+ if (Number.isInteger(port) && port > 0 && port <= 65535) return port
+ } catch { /* a first start, or an unreadable old record */ }
+ return configuredPort
+}
+
+export function saveDaemonPort(dataDir: string, configuredPort: number, port: number): void {
+ mkdirSync(dataDir, { recursive: true, mode: 0o700 })
+ const target = portFile(dataDir, configuredPort)
+ const temporary = `${target}.${process.pid}.tmp`
+ try {
+ writeFileSync(temporary, JSON.stringify({ port }) + '\n', { mode: 0o600 })
+ renameSync(temporary, target)
+ } finally {
+ rmSync(temporary, { force: true })
+ }
+}
+
+/** A native client must reach this OS user's socket, never whoever happens to hold a TCP port. */
+export async function localDaemonStatus(dataDir: string, configuredPort: number): Promise<Record<string, unknown> | null> {
+ const socketPath = localSocketPath(dataDir, configuredPort)
+ if (!socketPath) return null
+ try {
+ const entry = lstatSync(socketPath)
+ if (!entry.isSocket() || (process.geteuid && entry.uid !== process.geteuid()) || (entry.mode & 0o077) !== 0) return null
+ } catch { return null }
+ return new Promise((resolve) => {
+ const req = request({ socketPath, path: '/api/status', signal: AbortSignal.timeout(2_000) }, (res) => {
+ let text = ''
+ res.setEncoding('utf8')
+ res.on('data', (chunk: string) => {
+ text += chunk
+ if (text.length > 4 * 1024 * 1024) req.destroy(new Error('status response too large'))
+ })
+ res.on('error', () => resolve(null))
+ res.on('end', () => {
+ try {
+ const value: unknown = JSON.parse(text)
+ resolve(res.statusCode === 200 && value !== null && typeof value === 'object' && !Array.isArray(value)
+ ? value as Record<string, unknown> : null)
+ } catch { resolve(null) }
+ })
+ })
+ req.on('error', () => resolve(null))
+ req.end()
+ })
+}
+
+/** Read-only compatibility for CLI status on Windows and older daemons without a Unix socket.
+ * Native hn connections must use localDaemonStatus instead. Never accept another daemon's status.
+ */
+export async function legacyDaemonStatus(port: number, pid: number | null, computerId: string): Promise<Record<string, unknown> | null> {
+ if (!pid || !computerId) return null
+ try {
+ const response = await fetch(`http://127.0.0.1:${port}/api/status`, { signal: AbortSignal.timeout(1_500) })
+ if (!response.ok) return null
+ const value: unknown = await response.json()
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return null
+ const status = value as Record<string, unknown>
+ return status.pid === pid && status.computerId === computerId ? status : null
+ } catch { return null }
+}
diff --git a/cli/src/lib/daemonLaunch.ts b/cli/src/lib/daemonLaunch.ts
index 1f470abbf..b9bf81d25 100644
--- a/cli/src/lib/daemonLaunch.ts
+++ b/cli/src/lib/daemonLaunch.ts
@@ -2,7 +2,7 @@
* The parts of starting a daemon that decide whether it WORKED — pulled out of cli.ts so they can be
* tested without a backend, a bundle, or a real child.
*
- * Two phases, and the split is the point. A spawned child first has to BIND the fixed control port;
+ * Two phases, and the split is the point. A spawned child first has to BIND its control endpoints;
* only then does it try the backend. The old single wait watched the log for "[backend] connected"
* and, when that never came inside ten seconds, gave up with "unreachable" — leaving a child that was
* still booting (a slow login shell, tmux adoption) with no pid file and nothing guarding it, which is
@@ -23,7 +23,7 @@ export interface LaunchDeps {
readLogSlice: (sinceOffset: number) => string
now: () => number
sleep: (ms: number) => Promise<void>
- /** The fixed control port, for the EADDRINUSE message. */
+ /** The requested control port, for the EADDRINUSE message. */
port: number
}
@@ -59,10 +59,10 @@ export function connectFailure(tail: string, port: number): ConnectFailure | nul
if (tail.includes('[backend] machine busy')) {
return { detail: 'this machine is already connected from another computer', fatal: true, busy: true }
}
- // The daemon couldn't bind the (fixed) hook port → another adapter is almost certainly already
- // running. Fatal: don't sit on "retrying"; tell the user how to find/stop the other one.
+ // A bind failed even with the private-socket fallback. Do not advise killing an unknown listener:
+ // on a shared computer the requested port may belong to another OS user's daemon.
if (/EADDRINUSE|already in use/.test(tail)) {
- return { detail: `hook port ${port} is already in use — is another machine daemon running? (harness stop, or lsof -ti :${port} | xargs kill)`, fatal: true }
+ return { detail: `hook port ${port} is already in use — check harness status or choose a different PORT`, fatal: true }
}
const m = tail.match(/Unexpected server response: (\d+)/)
if (m) {
diff --git a/cli/src/lib/daemonState.ts b/cli/src/lib/daemonState.ts
index deef912c7..33b0774a3 100644
--- a/cli/src/lib/daemonState.ts
+++ b/cli/src/lib/daemonState.ts
@@ -1,6 +1,6 @@
/**
* On-disk daemon state that BOTH the daemon (`cli.ts`) and short-lived CLI commands need to read —
- * the pid file, the saved credential, and the fixed loopback control port.
+ * the pid file, the saved credential, and this user's recorded loopback control port.
*
* Kept in its own module so management commands can inspect daemon state without importing `cli.ts`,
* which would execute the command dispatcher.
@@ -10,13 +10,13 @@ import { readFileSync } from 'fs'
import { join } from 'path'
import { env } from '../config/env.js'
import { hasAuthSession } from './authSession.js'
+import { savedDaemonPort } from './daemonEndpoint.js'
export const PID_FILE = join(env.ADAPTER_DATA_DIR, 'adapter.pid')
-/** The daemon's localhost control port — FIXED at env.PORT (no fallback), so pair/status/stop always
- * reach it and a leftover is findable with `lsof :<PORT>`. */
+/** This user's recorded TCP port; the configured port still names its private Unix socket. */
export function daemonPort(): number {
- return env.PORT
+ return savedDaemonPort(env.ADAPTER_DATA_DIR, env.PORT)
}
export function readPid(): number | null {
diff --git a/cli/src/lib/localSocket.ts b/cli/src/lib/localSocket.ts
index a462b7781..38f69dbd0 100644
--- a/cli/src/lib/localSocket.ts
+++ b/cli/src/lib/localSocket.ts
@@ -1,5 +1,5 @@
/**
- * The daemon's Unix domain socket: the desktop app's way in, beside the loopback TCP port.
+ * The daemon's Unix domain socket: the desktop app's and hn's way in, beside the loopback TCP port.
*
* The loopback port carries no credential — every process on this computer, any user's, can open it,
* and the Host/Origin checks (lib/loopbackRequest.ts) only keep web pages out. The socket lives in the
@@ -11,17 +11,16 @@
* it, as do app builds that predate this. Windows has no socket here; there everything is TCP.
*/
import http from 'node:http'
+import { connect } from 'node:net'
import type { IncomingMessage } from 'node:http'
import type { Socket } from 'node:net'
import { chmodSync, lstatSync, renameSync, unlinkSync } from 'node:fs'
import { join } from 'node:path'
/**
- * One socket per control port: `daemon-<port>.sock`. Holding the port is what makes a daemon the only
- * one, so it is also what makes that daemon the socket's only rightful owner — a file already there is
- * a dead daemon's for that same port. And a client derives the name from the port it would otherwise
- * dial, so the socket it opens always leads to the same daemon its loopback fallback does, even with a
- * second daemon on another port sharing the data directory.
+ * One socket per configured port in this OS user's data directory: `daemon-<port>.sock`. Its name
+ * stays stable when a different user's daemon holds the requested TCP port and this daemon receives
+ * another one. Native clients derive this private path; CLI TCP clients read the saved actual port.
*/
export function localSocketName(port: number): string {
return `daemon-${port}.sock`
@@ -62,12 +61,13 @@ export interface LocalSocketServer {
}
/**
- * Serve `handler` on a Unix socket at `path` — the socket named for the port this daemon holds
- * ([localSocketName]). Call only once that port is bound: a socket file already there is then a dead
- * daemon's for the same port, and is removed. Anything there that is not a socket is left alone, and
- * this refuses to start.
+ * Serve `handler` on a Unix socket at `path`. Refuse a live listener or a non-socket file, and remove
+ * only a stale socket. CLI startup is serialized by the per-user spawn lock.
*/
export async function listenLocalSocket(handler: http.RequestListener, path: string): Promise<LocalSocketServer> {
+ // A TCP collision can now move this user to another port. Holding a TCP port no longer proves
+ // an existing Unix socket is stale: never unlink a live daemon belonging to this user.
+ await refuseLiveSocket(path)
removeStaleSocket(path)
const server = http.createServer(handler)
server.on('connection', (socket) => trustedSockets.add(socket))
@@ -85,7 +85,7 @@ export async function listenLocalSocket(handler: http.RequestListener, path: str
// `listen` creates the file with the process umask. It is made owner-only under a private name and
// only then renamed into place — atomically — so no client ever sees it looser than 0600, and the
// umask (process-wide, shared with whatever fs work is in flight) is never touched.
- // The daemon holding this port is the only one that uses this name, so a fixed suffix cannot clash.
+ // CLI startup holds the per-user spawn lock while claiming this stable socket name.
const staging = `${path}.new`
try { if (lstatSync(staging).isSocket()) unlinkSync(staging) } catch { /* nothing left over */ }
return new Promise((resolve, reject) => {
@@ -107,6 +107,24 @@ export async function listenLocalSocket(handler: http.RequestListener, path: str
})
}
+async function refuseLiveSocket(path: string): Promise<void> {
+ await new Promise<void>((resolve, reject) => {
+ const socket = connect(path)
+ socket.once('connect', () => {
+ socket.destroy()
+ reject(Object.assign(new Error(`A Harness daemon is already serving ${path}`), { code: 'EADDRINUSE' }))
+ })
+ socket.once('error', (error: NodeJS.ErrnoException) => {
+ if (error.code === 'ENOENT' || error.code === 'ECONNREFUSED' || error.code === 'ENOTSOCK') resolve()
+ else reject(error)
+ })
+ socket.setTimeout(1_000, () => {
+ socket.destroy()
+ reject(new Error(`Could not verify whether ${path} is in use`))
+ })
+ })
+}
+
function removeStaleSocket(path: string): void {
let isSocket: boolean
try {
diff --git a/cli/src/multiUserDaemon.spec.ts b/cli/src/multiUserDaemon.spec.ts
new file mode 100644
index 000000000..948d5c88d
--- /dev/null
+++ b/cli/src/multiUserDaemon.spec.ts
@@ -0,0 +1,35 @@
+import { mkdtempSync, rmSync } from 'node:fs'
+import { afterEach, expect, it, vi } from 'vitest'
+import { startHookServer } from './hookServer.js'
+import { localSocketPath } from './lib/localSocket.js'
+import { localDaemonStatus } from './lib/daemonEndpoint.js'
+
+const cleanup: Array<() => void | Promise<void>> = []
+afterEach(async () => { for (const close of cleanup.splice(0).reverse()) await close() })
+function directory(): string {
+ const path = mkdtempSync('/tmp/hn-users-')
+ cleanup.push(() => rmSync(path, { recursive: true, force: true }))
+ return path
+}
+async function start(dir: string, configuredPort: number, listenPort: number, machineId: string) {
+ const daemon = await startHookServer(listenPort, {
+ onRegistered: vi.fn(), onSessionEnd: vi.fn(), onStatus: () => ({ machineId, signedIn: false }),
+ }, { socketPath: localSocketPath(dir, configuredPort), allowPortFallback: true })
+ cleanup.push(async () => {
+ await daemon.localSocket?.close()
+ daemon.server.closeAllConnections()
+ await new Promise<void>((resolve) => daemon.server.close(() => resolve()))
+ })
+ return daemon
+}
+
+it('starts two OS-user services independently even when both request the same TCP port', async () => {
+ const a = directory(), b = directory(), configuredPort = 19418
+ const first = await start(a, configuredPort, 0, 'account-a')
+ const second = await start(b, configuredPort, first.port, 'account-b')
+ expect(second.port).not.toBe(first.port)
+ expect((await localDaemonStatus(a, configuredPort))?.machineId).toBe('account-a')
+ expect((await localDaemonStatus(b, configuredPort))?.machineId).toBe('account-b')
+ await expect(start(a, configuredPort, first.port, 'duplicate')).rejects.toThrow(/already serving/)
+ expect((await localDaemonStatus(a, configuredPort))?.machineId).toBe('account-a')
+})
diff --git a/cli/src/tui/index.spec.ts b/cli/src/tui/index.spec.ts
index a710b9c87..339f0ca30 100644
--- a/cli/src/tui/index.spec.ts
+++ b/cli/src/tui/index.spec.ts
@@ -4,6 +4,8 @@ import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { findTuiBinary, opensClient, platformKey, tuiCommand } from './index.js'
+import { localDaemonStatus } from '../lib/daemonEndpoint.js'
+vi.mock('../lib/daemonEndpoint.js', () => ({ localDaemonStatus: vi.fn() }))
// No test may start a real binary, daemon or login flow, or make a network request.
vi.mock('node:child_process', async (original) => ({ ...await original<typeof import('node:child_process')>(), spawnSync: vi.fn() }))
@@ -17,11 +19,13 @@ describe('harness tui launcher', () => {
binary = join(home, 'hn')
writeFileSync(binary, '#!/bin/sh\n', { mode: 0o755 })
vi.stubEnv('HOME', home)
+ vi.stubEnv('ADAPTER_DATA_DIR', join(home, '.harness', 'cli', 'data'))
vi.stubEnv('HARNESS_TUI_BIN', binary)
vi.stubEnv('PORT', '19418')
vi.stubEnv('HN_SOCKET_NAME', 'hnr19fix-launcher')
for (const key of ['TMUX', 'TMUX_PANE', 'HN_SOCKET']) vi.stubEnv(key, undefined)
vi.mocked(spawnSync).mockReset().mockReturnValue(ok)
+ vi.mocked(localDaemonStatus).mockReset().mockResolvedValue(null)
vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('offline')))
vi.spyOn(console, 'log').mockImplementation(() => {})
vi.spyOn(console, 'error').mockImplementation(() => {})
@@ -65,24 +69,39 @@ describe('harness tui launcher', () => {
expect(findTuiBinary()).not.toBe(join(home, 'missing'))
})
- it('launches local shells even if login is cancelled', async () => {
- vi.mocked(spawnSync).mockReturnValueOnce({ ...ok, status: 1 })
+ it('starts the local daemon and client without requiring an account or opening login', async () => {
+ vi.mocked(localDaemonStatus).mockResolvedValueOnce(null).mockResolvedValue({ machineId: 'guest-computer', signedIn: false })
const args = ['-L', 'hnr19fix-launcher', '--port', '19418']
- await expect(tuiCommand(args, { port: 19418, signedIn: () => false })).resolves.toBe(0)
+ await expect(tuiCommand(args, { port: 19418 })).resolves.toBe(0)
expect(spawnSync).toHaveBeenCalledTimes(2)
- expect(vi.mocked(spawnSync).mock.calls[0][1]).toContain('login')
+ expect(vi.mocked(spawnSync).mock.calls[0][1]).toContain('start')
+ expect(vi.mocked(spawnSync).mock.calls.flatMap((call) => call[1])).not.toContain('login')
expect(spawnSync).toHaveBeenLastCalledWith(binary, args, expect.objectContaining({
- env: expect.objectContaining({ HOME: home, PORT: '19418' }),
+ env: expect.objectContaining({ HOME: home, PORT: '19418', ADAPTER_DATA_DIR: join(home, '.harness', 'cli', 'data') }),
}))
expect(fetch).not.toHaveBeenCalled()
})
+ it('reuses this user\'s signed-out daemon', async () => {
+ vi.mocked(localDaemonStatus).mockResolvedValue({ machineId: 'guest-computer', signedIn: false })
+ await expect(tuiCommand([], { port: 19418, identity: () => 'guest-computer' })).resolves.toBe(0)
+ expect(spawnSync).toHaveBeenCalledTimes(1)
+ expect(vi.mocked(spawnSync).mock.calls[0][0]).toBe(binary)
+ })
+
+ it('asks start to reconcile a daemon still serving a previous sign-in', async () => {
+ vi.mocked(localDaemonStatus).mockResolvedValueOnce({ machineId: 'old-account' }).mockResolvedValue({ machineId: 'new-account' })
+ await expect(tuiCommand([], { port: 19418, identity: () => 'new-account' })).resolves.toBe(0)
+ expect(vi.mocked(spawnSync).mock.calls[0][1]).toContain('start')
+ expect(spawnSync).toHaveBeenCalledTimes(2)
+ })
+
it('uses the explicit port for daemon status, daemon start and the native client', async () => {
vi.mocked(spawnSync).mockReturnValueOnce({ ...ok, status: 1 })
const args = ['-L', 'hnr19fix-launcher', '--port', '19419']
- await expect(tuiCommand(args, { port: 19418, signedIn: () => true })).resolves.toBe(0)
- expect(fetch).toHaveBeenCalledTimes(1)
- expect(fetch).toHaveBeenCalledWith('http://127.0.0.1:19419/api/status', expect.anything())
+ await expect(tuiCommand(args, { port: 19418 })).resolves.toBe(0)
+ expect(localDaemonStatus).toHaveBeenCalledWith(join(home, '.harness', 'cli', 'data'), 19419)
+ expect(fetch).not.toHaveBeenCalled()
const calls = vi.mocked(spawnSync).mock.calls
expect(calls[0][1]).toContain('start')
expect(calls[0][2]?.env?.PORT).toBe('19419')
@@ -93,7 +112,7 @@ describe('harness tui launcher', () => {
it('opens a local client after the daemon startup deadline', async () => {
vi.useFakeTimers()
- const launched = tuiCommand(['-L', 'hnr19fix-launcher', '--port', '19418'], { port: 19418, signedIn: () => true })
+ const launched = tuiCommand(['-L', 'hnr19fix-launcher', '--port', '19418'], { port: 19418 })
await vi.runAllTimersAsync()
await expect(launched).resolves.toBe(0)
expect(vi.mocked(spawnSync).mock.calls[0][1]).toContain('start')
@@ -101,15 +120,16 @@ describe('harness tui launcher', () => {
})
it('leaves commands and invalid arguments to the native binary without bootstrapping', async () => {
- const signedIn = vi.fn(() => false)
+ const identity = vi.fn(() => 'current-user')
for (const args of [
['--port', 'broken'], ['--port', '65536'], ['--port'], ['--unknown'],
['-c', 'true'], ['--headless'], ['--local-server'], ['-C'],
['list-panes'], ['--', 'ls'], ['-L'],
]) {
- await tuiCommand(['-L', 'hnr19fix-launcher', '--port', '19418', ...args], { port: 19418, signedIn })
+ await tuiCommand(['-L', 'hnr19fix-launcher', '--port', '19418', ...args], { port: 19418, identity })
}
- expect(signedIn).not.toHaveBeenCalled()
+ expect(identity).not.toHaveBeenCalled()
+ expect(localDaemonStatus).not.toHaveBeenCalled()
expect(fetch).not.toHaveBeenCalled()
expect(vi.mocked(spawnSync).mock.calls.every(([command]) => command === binary)).toBe(true)
})
diff --git a/cli/src/tui/index.ts b/cli/src/tui/index.ts
index 2c52d740e..40cab5212 100644
--- a/cli/src/tui/index.ts
+++ b/cli/src/tui/index.ts
@@ -13,10 +13,12 @@
import { spawnSync } from 'node:child_process'
import { existsSync } from 'node:fs'
import { dirname, resolve } from 'node:path'
+import { homedir } from 'node:os'
import { fileURLToPath } from 'node:url'
import { installedTuiPath, installTui } from './install.js'
import { installManagedTui } from './manage.js'
+import { localDaemonStatus } from '../lib/daemonEndpoint.js'
export { installTui, platformKey, TUI_MANIFEST_URL } from './install.js'
export function findTuiBinary(): string | null {
@@ -70,44 +72,43 @@ export function opensClient(argv: string[]): boolean {
return clientPort(argv, 1) !== null
}
-async function daemonUp(port: number): Promise<boolean> {
- try { return (await fetch(`http://127.0.0.1:${port}/api/status`, { signal: AbortSignal.timeout(2_000) })).ok } catch { return false }
+async function daemonUp(port: number, dataDir: string, identity?: () => string): Promise<boolean> {
+ const status = await localDaemonStatus(dataDir, port)
+ return typeof status?.machineId === 'string' && status.machineId.length > 0
+ && (!identity || status.machineId === identity())
}
-/** This CLI, run again: `harness login`, `harness start`. Their output is the person's to read. */
-function runSelf(args: string[], port: number): number {
+/** Start this user's local service. Signing in is a separate, explicit action. */
+function runSelf(args: string[], port: number, dataDir: string): number {
const script = process.argv[1]
- const result = spawnSync(process.execPath, [...process.execArgv, ...(script ? [script] : []), ...args], { stdio: 'inherit', env: { ...process.env, PORT: String(port), HARNESS_SELF: '1' } })
+ const result = spawnSync(process.execPath, [...process.execArgv, ...(script ? [script] : []), ...args], { stdio: 'inherit', env: { ...process.env, PORT: String(port), ADAPTER_DATA_DIR: dataDir, HARNESS_SELF: '1' } })
return result.status ?? 1
}
/**
- * One command on a fresh server: sign in if this computer never has (over SSH the login prints a URL
- * and takes the pasted callback), start the daemon if it is down, then open.
+ * Local use requires no account. Start the local daemon if needed, whether signed in or out.
+ * Readiness is checked through this user's private socket; another user's TCP listener is irrelevant.
*/
-async function ensureDaemon(port: number, signedIn: () => boolean): Promise<boolean> {
- if (!signedIn()) {
- console.log('\n This computer is not signed in to Harness yet.')
- if (runSelf(['login'], port) !== 0 || !signedIn()) return false
- }
- if (await daemonUp(port)) return true
+async function ensureDaemon(port: number, dataDir: string, identity?: () => string): Promise<boolean> {
+ if (await daemonUp(port, dataDir, identity)) return true
console.log(' Starting the Harness daemon…')
- if (runSelf(['start'], port) !== 0) return false
+ if (runSelf(['start'], port, dataDir) !== 0) return false
for (let i = 0; i < 60; i++) {
- if (await daemonUp(port)) return true
+ if (await daemonUp(port, dataDir, identity)) return true
await new Promise((resolve) => setTimeout(resolve, 250))
}
console.error(' ✗ The Harness daemon did not come up. See `harness status`.')
return false
}
-export async function tuiCommand(argv: string[], opts: { port: number; signedIn?: () => boolean }): Promise<number> {
+export async function tuiCommand(argv: string[], opts: { port: number; dataDir?: string; identity?: () => string }): Promise<number> {
if (argv[0] === '--install' || argv[0] === 'install') {
try { await installManagedTui(process.argv[1] ?? '', (line) => console.log(line)); return 0 } catch (error) { console.error(` ✗ ${(error as Error).message}`); return 1 }
}
if (argv[0] === '--where') { console.log(findTuiBinary() ?? '(not installed)'); return 0 }
const port = clientPort(argv, opts.port)
- if (port !== null && opts.signedIn && !(await ensureDaemon(port, opts.signedIn))) {
+ const dataDir = opts.dataDir ?? process.env.ADAPTER_DATA_DIR ?? resolve(homedir(), '.harness', 'cli', 'data')
+ if (port !== null && !(await ensureDaemon(port, dataDir, opts.identity))) {
console.log(' Opening a local shell; Harness will reconnect when available.')
}
let binary = findTuiBinary()
@@ -120,7 +121,7 @@ export async function tuiCommand(argv: string[], opts: { port: number; signedIn?
const result = spawnSync(binary, argv, {
stdio: 'inherit',
// How the TUI runs this CLI back (`harness link connect` for a machine it has to link).
- env: { ...process.env, PORT: String(port ?? opts.port), HARNESS_CLI: process.execPath, HARNESS_SELF: '1', HARNESS_CLI_ARGS: JSON.stringify([...process.execArgv, process.argv[1] ?? '']) },
+ env: { ...process.env, PORT: String(port ?? opts.port), ADAPTER_DATA_DIR: dataDir, HARNESS_CLI: process.execPath, HARNESS_SELF: '1', HARNESS_CLI_ARGS: JSON.stringify([...process.execArgv, process.argv[1] ?? '']) },
})
if (result.error) { console.error(` ✗ Could not start ${binary}: ${result.error.message}`); return 1 }
return result.status ?? 0
diff --git a/tui/Cargo.lock b/tui/Cargo.lock
index 1eef90b79..2d473d91a 100644
--- a/tui/Cargo.lock
+++ b/tui/Cargo.lock
@@ -619,7 +619,7 @@ dependencies = [
[[package]]
name = "harness-tui"
-version = "0.1.4"
+version = "0.1.5"
dependencies = [
"alacritty_terminal",
"crossterm",
diff --git a/tui/Cargo.toml b/tui/Cargo.toml
index 9157a12ef..33c1f74b1 100644
--- a/tui/Cargo.toml
+++ b/tui/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "harness-tui"
-version = "0.1.4"
+version = "0.1.5"
edition = "2024"
[dependencies]
diff --git a/tui/README.md b/tui/README.md
index ec0c4bb61..e15c70d59 100644
--- a/tui/README.md
+++ b/tui/README.md
@@ -39,9 +39,11 @@ with the desktop and phone. With no daemon available, hn opens local shells inst
PTY supervisor keeps them running through detach, reconnect and a client crash. These local
sessions stay on this computer and remain intact when Harness reconnects.
-On a fresh server `hn` signs in (over SSH the login prints a URL and takes the pasted
-callback), starts the daemon, then opens. If sign-in or daemon startup fails, it still opens
-a local shell. Like `tmux new -A`, it restores your swarms if the desk has any,
+On a fresh computer `hn` starts your local daemon and opens without requiring an account.
+Sign in with `harness login` when you want your other machines and shared desk. If daemon startup
+fails, hn still opens a local shell. Each OS user connects through their own private Unix socket;
+hn never attaches to another user's daemon merely because it occupies the default TCP port.
+Like `tmux new -A`, it restores your swarms if the desk has any,
else window 0 is a shell on this computer, in the folder you ran `hn` in. `C-b s` finds every
harness. Closing the last window ends `hn` (`[exited]`, as tmux says it); `C-b d` detaches.
@@ -419,7 +421,8 @@ notify = true # OS notifications through the terminal
| `HARNESS_TUI_DESK=off` | keep tabs to this window |
| `HARNESS_TUI_PREDICT` | `off` / `always` (see Speed) |
| `HARNESS_TUI_BIN` | the binary `harness tui` runs |
-| `PORT` | the daemon's port (default 18473) |
+| `PORT` | the configured daemon port naming this user's private socket (default 18473) |
+| `ADAPTER_DATA_DIR` | daemon state directory (default `~/.harness/cli/data`); hn and the CLI must use the same one |
| `HN_DESKTOP=on` / `off` | whether the desktop app is running, instead of looking (see The dial) |
## Building
@@ -440,7 +443,7 @@ arm64, musl) with a checksummed manifest that `harness tui --install` verifies.
| File | |
|---|---|
-| `daemon.rs` | the loopback WebSocket per machine, requests, pushed frames |
+| `daemon.rs` | the private Unix-socket WebSocket per machine, requests, pushed frames |
| `proto.rs` | `HTRL` terminal frames (mirrors `cli/src/lib/terminalBinary.ts`) |
| `pane.rs` | one tile: `alacritty_terminal` grid, key/mouse encoding, selection, find, local echo |
| `app.rs` | all state: machines, streams, tabs, desk sync |
diff --git a/tui/src/app.rs b/tui/src/app.rs
index d4f8c1194..9eecf1c71 100644
--- a/tui/src/app.rs
+++ b/tui/src/app.rs
@@ -1099,17 +1099,14 @@ impl App {
// ── start: this machine, the account's machines, the desk ─────────────────
pub fn boot(&mut self) {
- if self.fleet.agents.is_empty() && self.fleet.machines.is_empty() { self.fleet.load_cache() }
let port = self.port;
self.spawn(async move { http_json(port, "GET", "/api/status", None).await }, |app, status| match status {
Ok(status) => {
app.daemon_down = false;
app.viewer_web_url = status.get("webUrl").and_then(Value::as_str).unwrap_or("").to_string();
let id = status.get("machineId").and_then(Value::as_str).unwrap_or("").to_string();
- if status.get("signedIn").and_then(Value::as_bool) == Some(false) {
- app.say("This computer is not signed in — run `harness login`", theme::DANGER);
- }
if id.is_empty() { return }
+ if app.fleet.agents.is_empty() && app.fleet.machines.is_empty() { app.fleet.load_cache(&id) }
app.fleet.local_id = id.clone();
for machine in &mut app.fleet.machines { machine.local = machine.id == id || crate::local::is_local(&machine.id); }
if app.fleet.machine(&id).is_none() {
diff --git a/tui/src/cli.rs b/tui/src/cli.rs
index fa927dc3e..5da4914ef 100644
--- a/tui/src/cli.rs
+++ b/tui/src/cli.rs
@@ -293,7 +293,7 @@ async fn offline(port: u16, args: &[String], name: Option<&str>) -> i32 {
let (local, list) = machines(port).await.unwrap_or_default();
let machine_name = list.iter().find(|(id, _, _)| *id == local).map(|(_, n, _)| n.clone()).unwrap_or_else(|| {
let mut fleet = crate::fleet::Fleet::default();
- fleet.load_cache();
+ fleet.load_cache(&local);
fleet.local_machine_name()
});
let rows = doc["sessions"].as_array().cloned().unwrap_or_default();
diff --git a/tui/src/daemon.rs b/tui/src/daemon.rs
index c6ab56b9c..d162f0d54 100644
--- a/tui/src/daemon.rs
+++ b/tui/src/daemon.rs
@@ -1,4 +1,4 @@
-//! One held connection per machine to the daemon's loopback socket (`/api/local-ws`), selected onto
+//! One held connection per machine to this OS user's private daemon socket (`/api/local-ws`), selected onto
//! that machine — this computer's own, or another the daemon relays to (relay + P2P live inside the
//! daemon; this side never sees anything but plaintext frames).
//!
@@ -9,6 +9,8 @@
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::time::Duration;
+use std::path::{Path, PathBuf};
+use std::os::unix::fs::{FileTypeExt, MetadataExt};
use futures_util::{SinkExt, StreamExt};
use serde_json::{json, Value};
@@ -45,6 +47,22 @@ impl<T: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send> SocketIo fo
type Pending = Arc<Mutex<HashMap<String, (String, oneshot::Sender<(String, Value)>)>>>;
+/// The daemon's owner-only socket, shared with Desktop. Never fall back to TCP: loopback is shared
+/// by every OS user, so the process holding a port may belong to a completely different account.
+pub fn socket_path(port: u16) -> PathBuf {
+ let dir = std::env::var_os("ADAPTER_DATA_DIR").filter(|s| !s.is_empty()).map(PathBuf::from)
+ .unwrap_or_else(|| PathBuf::from(std::env::var_os("HOME").unwrap_or_default()).join(".harness/cli/data"));
+ dir.join(format!("daemon-{port}.sock"))
+}
+
+async fn connect_owned(path: &Path) -> std::io::Result<tokio::net::UnixStream> {
+ let metadata = std::fs::symlink_metadata(path)?;
+ if !metadata.file_type().is_socket() || metadata.uid() != unsafe { libc::geteuid() } || metadata.mode() & 0o077 != 0 {
+ return Err(std::io::Error::new(std::io::ErrorKind::PermissionDenied, "Harness requires a private daemon socket owned by this OS user"));
+ }
+ tokio::net::UnixStream::connect(path).await
+}
+
// Clear requests on every exit, including cancellation and failures before selection.
// Otherwise RPC clones can keep their own waiters alive until the full request deadline.
struct PendingGuard(Pending);
@@ -67,6 +85,10 @@ pub struct Link {
impl Link {
/// Dial and select [machine_id]. Events (including `Connected` / `Closed`) arrive on [sink].
pub fn spawn(port: u16, machine_id: &str, generation: u64, sink: mpsc::UnboundedSender<Event>) -> Link {
+ Self::spawn_at(port, socket_path(port), machine_id, generation, sink)
+ }
+
+ fn spawn_at(port: u16, socket_path: PathBuf, machine_id: &str, generation: u64, sink: mpsc::UnboundedSender<Event>) -> Link {
let (tx, mut rx) = mpsc::unbounded_channel::<Out>();
let pending: Pending = Arc::new(Mutex::new(HashMap::new()));
let guard = PendingGuard(pending.clone());
@@ -85,7 +107,7 @@ impl Link {
let io: Box<dyn SocketIo> = if crate::local::is_local(&id) {
Box::new(crate::local::connect(port).await.map_err(tokio_tungstenite::tungstenite::Error::Io)?)
} else {
- Box::new(tokio::net::TcpStream::connect(("127.0.0.1", port)).await.map_err(tokio_tungstenite::tungstenite::Error::Io)?)
+ Box::new(connect_owned(&socket_path).await.map_err(tokio_tungstenite::tungstenite::Error::Io)?)
};
tokio_tungstenite::client_async(&url, io).await
}).await;
@@ -245,9 +267,13 @@ impl Link {
// ── REST on the same port (machines, desk, status) ──────────────────────────────
pub async fn http_json(port: u16, method: &str, path: &str, body: Option<&Value>) -> Result<Value, RpcError> {
+ http_json_at(port, &socket_path(port), method, path, body).await
+}
+
+async fn http_json_at(port: u16, socket: &Path, method: &str, path: &str, body: Option<&Value>) -> Result<Value, RpcError> {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let work = async {
- let mut stream = tokio::net::TcpStream::connect(("127.0.0.1", port)).await.map_err(|e| RpcError::new("DAEMON_UNREACHABLE", e.to_string()))?;
+ let mut stream = connect_owned(socket).await.map_err(|e| RpcError::new("DAEMON_UNREACHABLE", e.to_string()))?;
let body = body.map(|b| b.to_string()).unwrap_or_default();
let request = format!(
"{method} {path} HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nConnection: close\r\nAccept: application/json\r\nx-adapter-local: 1\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{body}",
@@ -288,11 +314,55 @@ fn dechunk(body: &[u8]) -> Vec<u8> {
#[cfg(test)]
mod recovery_tests {
use super::*;
+ use std::os::unix::fs::PermissionsExt;
+
+ struct TestSocket(PathBuf);
+ impl Drop for TestSocket { fn drop(&mut self) { let _ = std::fs::remove_file(&self.0); } }
+ fn listener() -> (tokio::net::UnixListener, TestSocket) {
+ let path = PathBuf::from(format!("/tmp/hn-daemon-{}.sock", uuid::Uuid::new_v4().simple()));
+ let listener = tokio::net::UnixListener::bind(&path).unwrap();
+ std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap();
+ (listener, TestSocket(path))
+ }
+
+ #[tokio::test]
+ async fn rest_uses_only_the_users_private_socket_and_never_the_tcp_listener() {
+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
+ let foreign = tokio::net::TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
+ let port = foreign.local_addr().unwrap().port();
+ let (owned, socket) = listener();
+ let server = tokio::spawn(async move {
+ let (mut peer, _) = owned.accept().await.unwrap();
+ let mut bytes = [0u8; 4096];
+ let n = peer.read(&mut bytes).await.unwrap();
+ assert!(String::from_utf8_lossy(&bytes[..n]).starts_with("GET /api/desk "));
+ let body = r#"{"owner":"this-user","tabs":[]}"#;
+ peer.write_all(format!("HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len()).as_bytes()).await.unwrap();
+ });
+ let desk = http_json_at(port, &socket.0, "GET", "/api/desk", None).await.unwrap();
+ assert_eq!(desk["owner"], "this-user");
+ server.await.unwrap();
+ std::fs::remove_file(&socket.0).unwrap();
+ assert!(http_json_at(port, &socket.0, "GET", "/api/desk", None).await.is_err());
+ assert!(tokio::time::timeout(Duration::from_millis(50), foreign.accept()).await.is_err());
+ }
+
+ #[tokio::test]
+ async fn rejects_public_sockets_and_symlinks_before_sending_any_request() {
+ let (owned, socket) = listener();
+ std::fs::set_permissions(&socket.0, std::fs::Permissions::from_mode(0o666)).unwrap();
+ assert_eq!(connect_owned(&socket.0).await.unwrap_err().kind(), std::io::ErrorKind::PermissionDenied);
+ std::fs::set_permissions(&socket.0, std::fs::Permissions::from_mode(0o600)).unwrap();
+ let alias = TestSocket(socket.0.with_extension("link"));
+ std::os::unix::fs::symlink(&socket.0, &alias.0).unwrap();
+ assert_eq!(connect_owned(&alias.0).await.unwrap_err().kind(), std::io::ErrorKind::PermissionDenied);
+ assert!(tokio::time::timeout(Duration::from_millis(50), owned.accept()).await.is_err());
+ }
#[tokio::test]
async fn cancel_closes_socket_and_releases_rpc_clones() {
- let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
- let port = listener.local_addr().unwrap().port();
+ let (listener, socket) = listener();
+ let port = 19418;
let (sink, mut events) = mpsc::unbounded_channel();
let (requested, request_seen) = oneshot::channel();
let server = tokio::spawn(async move {
@@ -307,7 +377,7 @@ mod recovery_tests {
}
}
});
- let link = Link::spawn(port, "test-peer", 1, sink);
+ let link = Link::spawn_at(port, socket.0.clone(), "test-peer", 1, sink);
assert!(matches!(tokio::time::timeout(Duration::from_secs(2), events.recv()).await.unwrap(), Some(Event::Machine { event: MachineEvent::Connected, .. })));
let clone = link.clone();
let rpc = tokio::spawn(async move { clone.request("terminal_open", json!({}), Duration::from_secs(45)).await });
@@ -323,8 +393,8 @@ mod recovery_tests {
#[tokio::test]
async fn selection_failure_releases_pending_requests_immediately() {
- let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
- let port = listener.local_addr().unwrap().port();
+ let (listener, socket) = listener();
+ let port = 19418;
let (sink, _events) = mpsc::unbounded_channel();
let server = tokio::spawn(async move {
let (socket, _) = listener.accept().await.unwrap();
@@ -332,7 +402,7 @@ mod recovery_tests {
let _select = ws.next().await;
ws.send(Message::text(json!({"type":"machine_select_error", "payload":{"error":"NO_PEER_LINK"}}).to_string())).await.unwrap();
});
- let link = Link::spawn(port, "test-peer", 1, sink);
+ let link = Link::spawn_at(port, socket.0.clone(), "test-peer", 1, sink);
let result = tokio::time::timeout(Duration::from_secs(2), link.request("agents_list", json!({}), Duration::from_secs(20))).await.unwrap();
assert_eq!(result.unwrap_err().code, "DISCONNECTED");
assert!(link.pending.lock().unwrap().is_empty());
diff --git a/tui/src/fleet.rs b/tui/src/fleet.rs
index e74017975..045d083d5 100644
--- a/tui/src/fleet.rs
+++ b/tui/src/fleet.rs
@@ -545,11 +545,16 @@ fn cache_path() -> std::path::PathBuf {
}
impl Fleet {
- /// Last run's machines and harnesses — searchable the instant the TUI opens, replaced by the
- /// live rosters as each machine answers.
- pub fn load_cache(&mut self) {
+ /// Restore only after this user's daemon identifies the current account's machine. Old caches
+ /// had no owner and may have come from another OS user's TCP listener; never adopt those.
+ pub fn load_cache(&mut self, owner: &str) {
let Ok(text) = std::fs::read_to_string(cache_path()) else { return };
let Ok(value) = serde_json::from_str::<Value>(&text) else { return };
+ self.restore_cache(&value, owner);
+ }
+
+ fn restore_cache(&mut self, value: &Value, owner: &str) {
+ if owner.is_empty() || value.get("owner").and_then(Value::as_str) != Some(owner) { return }
for m in value.get("machines").and_then(Value::as_array).into_iter().flatten() {
let id = s(m, "id");
if id.is_empty() || self.machine(&id).is_some() { continue }
@@ -567,7 +572,7 @@ impl Fleet {
}
pub fn save_cache(&self) {
- if self.agents.is_empty() { return }
+ if self.agents.is_empty() || self.local_id.is_empty() || crate::local::is_local(&self.local_id) { return }
let machines: Vec<Value> = self.machines.iter().map(|m| serde_json::json!({ "id": m.id, "name": m.name, "local": m.local, "status": m.status })).collect();
let agents: Vec<Value> = self.agents.values().map(|a| serde_json::json!({
"machine": a.machine_id, "activeAt": a.active_at,
@@ -578,7 +583,7 @@ impl Fleet {
let path = cache_path();
if let Some(dir) = path.parent() { let _ = std::fs::create_dir_all(dir); }
let temp = path.with_extension("json.tmp");
- if std::fs::write(&temp, serde_json::json!({ "machines": machines, "agents": agents }).to_string()).is_ok() { let _ = std::fs::rename(temp, path); }
+ if std::fs::write(&temp, serde_json::json!({ "owner": self.local_id, "machines": machines, "agents": agents }).to_string()).is_ok() { let _ = std::fs::rename(temp, path); }
}
}
@@ -598,6 +603,25 @@ pub fn ago(ms: u64) -> String {
mod tests {
use super::*;
+ #[test]
+ fn cache_needs_the_current_accounts_owner_and_drops_legacy_unscoped_data() {
+ let mut cached = serde_json::json!({
+ "owner": "account-a", "machines": [{"id": "remote-a", "name": "private-machine"}],
+ "agents": [{"machine": "remote-a", "row": {"id": "private-agent", "name": "private work"}}]
+ });
+ let mut fleet = Fleet::default();
+ fleet.restore_cache(&cached, "account-b");
+ assert!(fleet.machines.is_empty() && fleet.agents.is_empty());
+ cached.as_object_mut().unwrap().remove("owner");
+ fleet.restore_cache(&cached, "account-a");
+ fleet.restore_cache(&cached, "");
+ assert!(fleet.machines.is_empty() && fleet.agents.is_empty());
+ cached["owner"] = serde_json::json!("account-a");
+ fleet.restore_cache(&cached, "account-a");
+ assert_eq!(fleet.machines.len(), 1);
+ assert_eq!(fleet.agents.len(), 1);
+ }
+
#[test]
fn local_shells_share_the_app_name_without_changing_their_transport() {
let shell = crate::local::MACHINE;
diff --git a/tui/tests/e2e.sh b/tui/tests/e2e.sh
index 4e30d0b7f..da790f633 100755
--- a/tui/tests/e2e.sh
+++ b/tui/tests/e2e.sh
@@ -13,6 +13,7 @@ client="${HN_SOCKET_NAME:-e2e}-$$"
sock="harness-tui-e2e-$$"
home="$(mktemp -d /tmp/hn-e2e.XXXXXX)"
export HN_TMPDIR="$home"
+export ADAPTER_DATA_DIR="$home/.harness/cli/data"
tmux_() { tmux -L "$sock" "$@"; }
screen() { tmux_ capture-pane -p -t t; }
fail() { echo "✗ $1"; echo "--- screen ---"; screen || true; hn show-messages || true; hn display -p 'key-table=#{client_key_table} prefix=#{client_prefix} mode=#{pane_mode}' || true; exit 1; }
@@ -35,7 +36,7 @@ cleanup() {
}
trap cleanup EXIT
-node "$here/mock-daemon.mjs" "$port" >/dev/null &
+HOME="$home" node "$here/mock-daemon.mjs" "$port" >/dev/null &
mock=$!
sleep 0.5
# Its own client socket, named: the test's shell calls must never reach a client of yours
diff --git a/tui/tests/layout-sync.py b/tui/tests/layout-sync.py
index 1651e3081..7dd180616 100644
--- a/tui/tests/layout-sync.py
+++ b/tui/tests/layout-sync.py
@@ -31,6 +31,7 @@ def scenario(mode, port, read_only=False):
prefix = f'hn-layout-{os.getpid()}-{port}'
env = {k: os.environ[k] for k in ('PATH', 'LANG', 'LC_ALL', 'TZ') if k in os.environ}
env.update(HOME=str(base), HN_TMPDIR=str(base), HN_SOCKET_NAME=prefix, PORT=str(port),
+ ADAPTER_DATA_DIR=str(base / 'data'),
TERM='xterm-256color', SHELL='/bin/sh', HARNESS_TUI_DESK='read' if read_only else 'sync',
HN_DESKTOP='off', HARNESS_TUI_NOTIFY='off', MOCK_DEMO='1', MOCK_LAYOUT='1', MOCK_DESK=mode)
peer_env = dict(env, HOME=str(base / 'peer'), HN_SOCKET_NAME=prefix + '-peer')
diff --git a/tui/tests/local-first.py b/tui/tests/local-first.py
new file mode 100644
index 000000000..b43ebd3f2
--- /dev/null
+++ b/tui/tests/local-first.py
@@ -0,0 +1,133 @@
+#!/usr/bin/env python3
+"""Packaged CLI + hn: signed-out startup beside another user's daemon.
+
+Build cli/dist/cli.js with `cd cli && node build-bundle.mjs` first.
+HN_LOCAL_FIRST_BINARY selects the native hn build (default: tui/target/release/harness-tui).
+Only disposable homes, owned daemon processes, and explicitly named tmux servers are used.
+"""
+import http.client
+import json
+import os
+from pathlib import Path
+import shlex
+import shutil
+import socket
+import subprocess
+import tempfile
+import time
+
+REPO = Path(__file__).resolve().parents[2]
+BASE = Path(tempfile.mkdtemp(prefix='hnown-', dir='/tmp')).resolve()
+NODE = shutil.which('node')
+TMUX = shutil.which('tmux')
+HN = os.environ.get('HN_LOCAL_FIRST_BINARY', str(REPO / 'tui/target/release/harness-tui'))
+assert NODE and TMUX, 'node and tmux are required'
+assert Path(HN).is_file() and (REPO / 'cli/dist/cli.js').is_file(), 'build hn and bundle the CLI first'
+PREFIX = f'hn-owners-{os.getpid()}'
+CLI = [NODE, str(REPO / 'cli/dist/cli.js')]
+children = []
+environments = []
+logs = []
+with socket.socket() as probe:
+ probe.bind(('127.0.0.1', 0))
+ PORT = probe.getsockname()[1]
+
+def fixture(label):
+ root = BASE / label
+ (root / 'bin').mkdir(parents=True)
+ for command in ('open', 'xdg-open'):
+ path = root / 'bin' / command
+ path.write_text('#!/bin/sh\necho unexpected-login >> ' + shlex.quote(str(root / 'browser-opened')) + '\nexit 1\n')
+ path.chmod(0o700)
+ wrapper = root / 'bin/tmux'
+ wrapper.write_text('#!/bin/sh\nfor arg in "$@"; do case "$arg" in -L*|-S*) exit 125;; esac; done\nexec ' + shlex.join([TMUX, '-L', PREFIX + '-' + label]) + ' "$@"\n')
+ wrapper.chmod(0o700)
+ env = {k: os.environ[k] for k in ('PATH', 'LANG', 'LC_ALL', 'TZ') if k in os.environ}
+ env.update(HOME=str(root), PATH=str(root / 'bin') + ':' + env['PATH'], PORT=str(PORT),
+ ADAPTER_DATA_DIR=str(root / 'data'), ADAPTER_CLI_DIR=str(root / 'cli'),
+ HARNESS_AUTH_DIR=str(root / 'auth'), ADAPTER_COMPUTER_ID=label * 32,
+ ADAPTER_COMPUTER_ID_FILE=str(root / 'computer-id'), ADAPTER_RUNTIME_DIR=str(root / 'runtime'),
+ DSH_DIR=str(root / 'dsh'), HARNESS_GRID_BIN=str(root / 'no-grid'),
+ BACKEND_WS_URL='ws://127.0.0.1:1', WEB_URL='http://127.0.0.1:1',
+ HARNESS_STORE_CATALOG_URL='http://127.0.0.1:1/catalog', DISABLE_GRID_INSTALL='true',
+ DISABLE_HOOK_INSTALL='true', ADAPTER_UPDATE_DISABLE='true', ANALYTICS_ENABLED='false',
+ RECAP_FORCE='false', RECAP_WITHOUT_DEVICE='false', CABLE_DISABLE='true', CABLE_FW_DISABLE='true',
+ HARNESS_DAEMONS='0', TERMINAL_BACKENDS='tmux', HN_DESKTOP='off', HARNESS_TUI_NOTIFY='off',
+ HN_TMPDIR=str(root), HN_SOCKET_NAME=PREFIX + '-' + label, HARNESS_TUI_BIN=HN,
+ TERM='xterm-256color', SHELL='/bin/sh')
+ environments.append((root, env))
+ subprocess.run([TMUX, '-L', PREFIX + '-' + label, '-f', '/dev/null', 'new-session', '-d', '-s', 'fixture-keeper'], env=env, check=True)
+ return root, env
+
+def status(root):
+ conn = http.client.HTTPConnection('localhost', timeout=2)
+ conn.sock = socket.socket(socket.AF_UNIX)
+ conn.sock.settimeout(2)
+ try:
+ conn.sock.connect(str(root / 'data' / f'daemon-{PORT}.sock'))
+ conn.request('GET', '/api/status')
+ response = conn.getresponse()
+ assert response.status == 200
+ return json.load(response)
+ finally:
+ conn.close()
+
+def wait(fn, label, seconds=60):
+ deadline = time.monotonic() + seconds
+ while time.monotonic() < deadline:
+ try:
+ result = fn()
+ if result:
+ return result
+ except (OSError, ValueError, http.client.HTTPException):
+ pass
+ time.sleep(.15)
+ raise AssertionError(label)
+
+def outer(*args, check=True):
+ return subprocess.run([TMUX, '-L', PREFIX + '-outer', *args], text=True, capture_output=True, check=check, timeout=10)
+
+def screen():
+ return outer('capture-pane', '-p', '-t', 'guest').stdout
+
+try:
+ a, env_a = fixture('a')
+ log = open(a / 'daemon.log', 'w'); logs.append(log)
+ children.append(subprocess.Popen([*CLI, '__run'], cwd=REPO / 'cli', env=env_a, stdout=log, stderr=log))
+ first = wait(lambda: (s if (s := status(a)).get('discoveryReady') else None), 'first local daemon')
+ assert first['machineId'] == 'a' * 32 and first['signedIn'] is False
+ b, env_b = fixture('b')
+ cache = b / '.harness/tui/fleet.json'
+ cache.parent.mkdir(parents=True)
+ cache.write_text(json.dumps({'machines': [{'id': 'old-account', 'name': 'OTHER_ACCOUNT_PRIVATE'}],
+ 'agents': [{'machine': 'old-account', 'row': {'id': 'private-pane', 'name': 'OTHER_ACCOUNT_PRIVATE'}}]}))
+ command = shlex.join(['env', '-u', 'TMUX', '-u', 'TMUX_PANE', '-u', 'HN_SOCKET',
+ *[f'{k}={v}' for k, v in env_b.items()], *CLI, 'tui', '-L', PREFIX + '-b'])
+ outer('-f', '/dev/null', 'new-session', '-d', '-s', 'guest', '-x', '110', '-y', '34', '-c', str(REPO / 'cli'), command)
+ second = wait(lambda: (s if (s := status(b)).get('discoveryReady') else None), 'guest hn bootstrap')
+ assert second['machineId'] == 'b' * 32 and second['signedIn'] is False
+ assert second['config']['port'] != first['config']['port']
+ assert status(a)['pid'] == first['pid']
+ wait(lambda: 'Nothing running.' in (s := screen()) or 'Terminal on ' in s, 'guest home or local terminal')
+ assert 'OTHER_ACCOUNT_PRIVATE' not in screen()
+ assert not (b / 'browser-opened').exists()
+ assert not (b / 'auth/session.json').exists()
+ print('PASS: real hn starts signed out beside another user daemon, with distinct ports and no browser login', flush=True)
+ outer('send-keys', '-t', 'guest', 'C-b', 'N')
+ wait(lambda: 'New Harness' in screen() and 'Project' in screen(), 'signed-out New Harness popup', 15)
+ assert 'OTHER_ACCOUNT_PRIVATE' not in screen()
+ print('PASS: local New Harness opens; old unscoped account cache is ignored; first daemon stays running', flush=True)
+finally:
+ (BASE / 'guest-screen.txt').write_text(outer('capture-pane', '-p', '-t', 'guest', check=False).stdout)
+ for root, env in reversed(environments):
+ subprocess.run([HN, '-L', env['HN_SOCKET_NAME'], 'kill-server'], env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=15)
+ subprocess.run([*CLI, 'stop'], cwd=REPO / 'cli', env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=20)
+ for child in children:
+ if child.poll() is None: child.terminate()
+ try: child.wait(timeout=10)
+ except subprocess.TimeoutExpired: child.kill(); child.wait()
+ outer('kill-server', check=False)
+ for root, _ in environments:
+ subprocess.run([TMUX, '-L', PREFIX + '-' + root.name, 'kill-server'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
+ for log in logs: log.close()
+ print('Isolated logs:', BASE, flush=True)
diff --git a/tui/tests/mock-daemon.mjs b/tui/tests/mock-daemon.mjs
index 8b2962c7b..58cc3c154 100644
--- a/tui/tests/mock-daemon.mjs
+++ b/tui/tests/mock-daemon.mjs
@@ -2,6 +2,7 @@
// machines, fake harnesses, and terminals that echo what is typed. Fuzzing and end-to-end checks run
// against this — never against a daemon whose agents are somebody's real work.
//
+// export HOME="$(mktemp -d /tmp/hn-mock.XXXXXX)" ADAPTER_DATA_DIR=
// node tui/tests/mock-daemon.mjs 18999 &
// PORT=18999 HARNESS_TUI_DESK=off tui/target/release/harness-tui
//
@@ -11,7 +12,8 @@ import http from 'node:http'
import { randomUUID } from 'node:crypto'
import { createRequire } from 'node:module'
import { fileURLToPath } from 'node:url'
-import { dirname, join } from 'node:path'
+import { dirname, join, resolve } from 'node:path'
+import { chmodSync, mkdirSync, unlinkSync } from 'node:fs'
const here = dirname(fileURLToPath(import.meta.url))
const require = createRequire(join(here, '../../cli/package.json'))
@@ -509,4 +511,17 @@ wss.on('connection', (ws) => {
}
})
})
-server.listen(port, '127.0.0.1', () => console.log(`mock daemon on ${port}`))
+// Real native clients use an OS-user-owned socket. Tests supply a disposable HOME.
+const mockHome = process.env.HOME || ''
+if (!/^\/(?:private\/)?(?:tmp\/|var\/folders\/)/.test(mockHome)) throw new Error('mock-daemon requires a temporary HOME')
+const socketDir = process.env.ADAPTER_DATA_DIR || join(mockHome, '.harness', 'cli', 'data')
+if (!resolve(socketDir).startsWith(resolve(mockHome) + '/')) throw new Error('mock-daemon data must be inside its temporary HOME')
+mkdirSync(socketDir, { recursive: true, mode: 0o700 })
+const socketPath = join(socketDir, `daemon-${port}.sock`)
+try { unlinkSync(socketPath) } catch (error) { if (error.code !== 'ENOENT') throw error }
+const privateServer = http.createServer(server.listeners('request')[0])
+privateServer.on('upgrade', (req, socket, head) => wss.handleUpgrade(req, socket, head, (ws) => wss.emit('connection', ws, req)))
+privateServer.listen(socketPath, () => {
+ chmodSync(socketPath, 0o600)
+ server.listen(port, '127.0.0.1', () => console.log(`mock daemon on ${port}`))
+})