The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
feat: desktop app reaches the daemon over a Unix socket, TCP as fallback (#364)
0xken15468979983431
diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex 8c922b9b3..9997fe46c 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -24,7 +24,7 @@ import { AutonomousDeviceDirect } from './lib/autonomous-device/direct.js'*/import 'dotenv/config'-import { readFileSync, writeFileSync, mkdirSync, openSync, existsSync, rmSync, statSync } from 'fs'+import { readFileSync, readdirSync, writeFileSync, mkdirSync, openSync, existsSync, rmSync, statSync } from 'fs'import { join, resolve } from 'path'import { fileURLToPath } from 'url'import { spawn } from 'child_process'@@ -154,6 +154,7 @@ import {import { readTerminalConfigSnapshot, writeTerminalConfigSnapshot } from './lib/terminalConfigSnapshot.js'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 { commandBarService } from './lib/commandBar.js'import { BackendSocket, isLocalClientId } from './backendSocket.js'import { AutonomousDeviceService } from './lib/autonomous-device/service.js'@@ -476,13 +477,15 @@ const daemonBoot: {updater: Poller | null/** The hook server, once bound — the only thing a mid-boot handoff has to release. */hookServer: Server | null+ /** Its Unix-socket twin (lib/localSocket.ts), when one could be opened. Read by `/api/status`. */+ localSocket: LocalSocketServer | null/** Set by the body so a failed boot can flip its own `/api/status` to not-ready. */markNotReady: ((reason: string) => void) | null/** Why this daemon is in safe mode, or null while it is healthy. Read by `/api/status`. */safeMode: string | nullhandingOff: booleanapplyStagedUpdate: (version: string) => void | Promise<void>-} = { updater: null, hookServer: null, markNotReady: null, safeMode: null, handingOff: false, applyStagedUpdate: bootHandoff }+} = { updater: null, hookServer: null, localSocket: null, markNotReady: null, safeMode: null, handingOff: false, applyStagedUpdate: bootHandoff }/*** Hand the machine to a newer build without finishing start-up.@@ -505,6 +508,7 @@ function bootHandoff(version: string): void {closeServer: () => {try { (daemonBoot.hookServer as unknown as { closeAllConnections?: () => void } | null)?.closeAllConnections?.() } catch { /* already gone */ }try { daemonBoot.hookServer?.close() } catch { /* already gone */ }+ try { daemonBoot.localSocket?.closeSync() } catch { /* already gone */ }},// Only if it still names us — a no-op when start-up never got as far as claiming it.removePidFile: () => { removePidFileIf(process.pid) },@@ -3626,7 +3630,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {}- const { server: hookServer, port: hookPort } = await startHookServer(env.PORT, {+ const { server: hookServer, port: hookPort, localSocket } = await startHookServer(env.PORT, {onCommandBar: commandBarService,onAutonomousDeviceRequest: async (method, target, body) => {if (!autonomousDeviceService) return { status: 503, body: { error: { code: 'UNAVAILABLE', message: 'Autonomous device service is starting' } } }@@ -3946,6 +3950,9 @@ async function runForeground(session: AuthSession | null): Promise<void> {terminalProtocolVersion: TERMINAL_BINARY_VERSION,e2ee: false,},+ // The same REST and local WS, over the daemon's Unix socket (lib/localSocket.ts). Null where+ // none could be opened; clients then stay on this port.+ localSocket: daemonBoot.localSocket?.path ?? null,backendUrl: env.BACKEND_WS_URL,webUrl: env.WEB_URL,connected: backend.isConnected(),@@ -4019,7 +4026,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {onDeskRead: () => proxyBackend('GET', '/api/desk'),onDeskOps: (body) => proxyBackend('POST', '/api/desk/ops', body),onStore: (method, path, body) => proxyBackend(method, path, body),- })+ }, { socketPath: localSocketPath(env.ADAPTER_DATA_DIR, env.PORT) })// 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@@ -4030,6 +4037,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {// The one thing a handoff that happens before start-up finishes has to release: the port has no// fallback, so a successor that cannot bind it is a daemon that does not come up (see bootHandoff).daemonBoot.hookServer = hookServer+ daemonBoot.localSocket = localSocketconsole.log(`[cli] daemon pid ${process.pid} · v${VERSION}${process.env.ADAPTER_UPDATED_TO ? ' · updated' : ''} · listening on 127.0.0.1:${hookPort}`)// Same on-disk identity `harness remote-password set`/`link connect` use (E2eeStore.init() is// idempotent per file, so a separate in-memory instance here just reads the one this machine@@ -4059,6 +4067,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {})const localWsServer = attachLocalWsServer(hookServer, {+ localSocketServer: localSocket?.server ?? null,shareRelay,// The window and the dial are one desk: opening an agent in the app brings the dial to it, switching// the dial's machine first when the app moved to another one.@@ -5696,6 +5705,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {sharedViewers.stop()await localWsServer.close()hookServer.close()+ await localSocket?.close()shutdownSummaryPool()shutdownVoiceRouter()// The new daemon starts its own viewers for the agents it restores; ours must not hold the ports.@@ -5801,6 +5811,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {sharedViewers.stop()await localWsServer.close()hookServer.close()+ await localSocket?.close()shutdownSummaryPool()shutdownVoiceRouter()await dshViewers.stopAll()@@ -6313,6 +6324,10 @@ 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.+ try {+ for (const name of readdirSync(dir)) if (isLocalSocketName(name)) rmSync(join(dir, name), { force: true })+ } catch { /* no such directory */ }}if (dataDir === cliDir) rmStateFiles(dataDir)else rmSync(dataDir, { recursive: true, force: true })diff --git a/cli/src/hookServer.spec.ts b/cli/src/hookServer.spec.tsindex 972dc3da6..de2335397 100644--- a/cli/src/hookServer.spec.ts+++ b/cli/src/hookServer.spec.ts@@ -365,3 +365,57 @@ describe('requests must name this server', () => {expect(await send(base, 'GET', '/api/status', { host: `127.0.0.1:${port}`, origin: 'http://evil.example' })).toBe(403)})})++describe('the daemon socket', () => {+ function viaSocket(socketPath: string, method: string, path: string, headers: Record<string, string> = {}): Promise<number> {+ return new Promise((resolve, reject) => {+ const r = request({ socketPath, path, method, headers }, (res) => { res.resume(); resolve(res.statusCode ?? 0) })+ r.on('error', reject)+ r.end()+ })+ }++ it('serves the same routes with no loopback Host, and keeps every other guard', async () => {+ const dir = mkdtempSync('/tmp/hsock-')+ const socketPath = join(dir, 'daemon.sock')+ const onStatus = vi.fn(() => ({ ok: true }))+ const commandBar = { status: vi.fn(async () => ({ configured: false })), decide: vi.fn() }+ const started = await startHookServer(0, { onRegistered: vi.fn(), onSessionEnd: vi.fn(), onStatus, onCommandBar: commandBar as never }, { socketPath })+ server = started.server+ try {+ expect(started.localSocket?.path).toBe(socketPath)+ // Node sends `Host: localhost` without a port over a socket — refused on TCP, fine here.+ expect(await viaSocket(socketPath, 'GET', '/api/status')).toBe(200)+ expect(await viaSocket(socketPath, 'GET', '/api/status', { host: 'rebind.evil.example' })).toBe(200)+ expect(onStatus).toHaveBeenCalledTimes(2)+ // The command bar asked for a loopback PEER; a socket peer has no address and is let in.+ expect(await viaSocket(socketPath, 'GET', '/api/command-bar/status', { 'x-adapter-local': '1' })).toBe(200)+ expect(await viaSocket(socketPath, 'GET', '/api/command-bar/status')).toBe(403)+ // Mutations still need the CSRF header, hooks still need their credential.+ expect(await viaSocket(socketPath, 'POST', '/api/stop')).toBe(403)+ expect(await viaSocket(socketPath, 'POST', '/api/hook/session-start')).not.toBe(200)+ // The TCP port is untouched: a foreign Host is still refused there.+ const port = (started.server.address() as { port: number }).port+ const tcp = await new Promise<number>((resolve, reject) => {+ const r = request({ host: '127.0.0.1', port, path: '/api/status', headers: { host: 'rebind.evil.example' } }, (res) => { res.resume(); resolve(res.statusCode ?? 0) })+ r.on('error', reject)+ r.end()+ })+ expect(tcp).toBe(403)+ } finally {+ await started.localSocket?.close()+ rmSync(dir, { recursive: true, force: true })+ }+ })++ it('starts on TCP alone when the socket cannot be opened', async () => {+ const dir = mkdtempSync('/tmp/hsock-')+ const blocked = join(dir, 'daemon.sock')+ writeFileSync(blocked, 'not a socket')+ const started = await startHookServer(0, { onRegistered: vi.fn(), onSessionEnd: vi.fn() }, { socketPath: blocked })+ server = started.server+ expect(started.localSocket).toBeNull()+ expect(started.port).toBeGreaterThan(0)+ rmSync(dir, { recursive: true, force: true })+ })+})diff --git a/cli/src/hookServer.ts b/cli/src/hookServer.tsindex 893f30f9b..9cea48fbc 100644--- a/cli/src/hookServer.ts+++ b/cli/src/hookServer.ts@@ -24,6 +24,7 @@ import { ENGINES, type AgentEngine } from './engines/types.js'import type { CommandBarService } from './lib/commandBar.js'import { handleCommandBarHttp } from './lib/commandBarHttp.js'import { isLoopbackRequest, loopbackHosts } from './lib/loopbackRequest.js'+import { isTrustedLocal, listenLocalSocket, type LocalSocketServer } from './lib/localSocket.js'/*** Which agent does a hook belong to, given the two grades of evidence?@@ -367,23 +368,32 @@ async function awaitHermesKind(body: RegisterInput, handlers: HookServerHandlershandlers.onRegistered(result.entry, { isNew: result.isNew, evicted: result.evicted, rebound: result.rebound, orphaned: result.orphaned, hookEvent: body.hookEvent })}+export interface HookServerOptions {+ /** Also serve on this Unix socket (see lib/localSocket.ts). Null or absent: TCP only. */+ socketPath?: string | null+}+export function startHookServer(port: number,handlers: HookServerHandlers,-): Promise<{ server: http.Server; port: number }> {+ options: HookServerOptions = {},+): Promise<{ server: http.Server; port: number; localSocket: LocalSocketServer | null }> {const hookCredential = loadOrCreateHookCredential(env.ADAPTER_DATA_DIR)// Filled in once the port is bound: the Host a request must name is the port actually taken.let hosts: ReadonlySet<string> = new Set()let lastRefusalLogAt = 0- const server = http.createServer((req, res) => {+ const handle: http.RequestListener = (req, res) => {void (async () => {const url = (req.url ?? '').split('?')[0]const json = (code: number, body: unknown): void => {res.writeHead(code, { 'Content-Type': 'application/json' })res.end(JSON.stringify(body))}+ // Over the daemon's own socket the filesystem already said who this is, and no browser can get+ // there; everything else must prove it was addressed to this loopback server.+ const trustedLocal = isTrustedLocal(req)// Before any route, reads included. See lib/loopbackRequest.ts.- if (!isLoopbackRequest(req, hosts)) {+ if (!trustedLocal && !isLoopbackRequest(req, hosts)) {// At most one line a minute: enough to explain a client that was refused, not a lever for a// page to flood the log. Host and Origin are the sender's, so they are escaped and bounded.if (Date.now() - lastRefusalLogAt > 60_000) {@@ -412,7 +422,7 @@ export function startHookServer(if (url.startsWith('/api/autonomous-device/')) {const peer = req.socket.remoteAddress- const loopback = peer === '127.0.0.1' || peer === '::1' || peer === '::ffff:127.0.0.1'+ const loopback = trustedLocal || peer === '127.0.0.1' || peer === '::1' || peer === '::ffff:127.0.0.1'const bearer = req.headers.authorization?.startsWith('Bearer ') ? req.headers.authorization.slice(7) : undefinedif (!loopback || req.headers.origin || !hookCredentialMatches(hookCredential, bearer)) {json(403, { error: { code: 'FORBIDDEN', message: 'Authenticated native loopback client required' } }); return@@ -732,7 +742,8 @@ export function startHookServer(json(404, { error: 'not found' })})()- })+ }+ const server = http.createServer(handle)return new Promise((resolve, reject) => {server.once('error', (err: NodeJS.ErrnoException) => {@@ -751,7 +762,20 @@ export function startHookServer(const actual = (server.address() as AddressInfo).porthosts = loopbackHosts(actual)console.log(`[hooks] listening on 127.0.0.1:${actual} (SessionStart/SessionEnd callbacks)`)- resolve({ server, port: actual })+ 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.+ listenLocalSocket(handle, socketPath).then(+ (localSocket) => {+ console.log(`[hooks] listening on ${socketPath}`)+ resolve({ server, port: actual, localSocket })+ },+ (error: unknown) => {+ console.warn(`[hooks] local socket unavailable (${socketPath}): ${error instanceof Error ? error.message : error}`)+ resolve({ server, port: actual, localSocket: null })+ },+ )})})}diff --git a/cli/src/lib/commandBarHttp.ts b/cli/src/lib/commandBarHttp.tsindex fc959bdff..ad67175a6 100644--- a/cli/src/lib/commandBarHttp.ts+++ b/cli/src/lib/commandBarHttp.ts@@ -1,5 +1,6 @@import type { IncomingMessage, ServerResponse } from 'node:http'import { CommandBarError, type CommandBarService } from './commandBar.js'+import { isTrustedLocal } from './localSocket.js'/** Shared by the daemon and the isolated experiment server. Returns false for other routes. */export async function handleCommandBarHttp(@@ -14,7 +15,7 @@ export async function handleCommandBarHttp(}const fail = (status: number, code: string, message: string) => json(status, { success: false, error: { code, message } })const peer = req.socket.remoteAddress- const loopback = peer === '127.0.0.1' || peer === '::1' || peer === '::ffff:127.0.0.1'+ const loopback = isTrustedLocal(req) || peer === '127.0.0.1' || peer === '::1' || peer === '::ffff:127.0.0.1'if (req.headers['x-adapter-local'] !== '1' || !loopback || req.headers.origin) {fail(403, 'FORBIDDEN', 'Native local client required.'); return true}diff --git a/cli/src/lib/localSocket.spec.ts b/cli/src/lib/localSocket.spec.tsnew file mode 100644index 000000000..258e6d654--- /dev/null+++ b/cli/src/lib/localSocket.spec.ts@@ -0,0 +1,143 @@+import { request } from 'node:http'+import { connect } from 'node:net'+import { existsSync, mkdirSync, mkdtempSync, rmSync, statSync, writeFileSync } from 'node:fs'+import { join } from 'node:path'+import { afterEach, describe, expect, it } from 'vitest'+import { isLocalSocketName, isTrustedLocal, listenLocalSocket, localSocketName, localSocketPath, type LocalSocketServer } from './localSocket.js'++const LOCAL_SOCKET_NAME = localSocketName(18473)++// Socket paths are capped near 104 bytes; the test tmpdir on macOS is far longer.+const dirs: string[] = []+const opened: LocalSocketServer[] = []+function shortDir(): string {+ const dir = mkdtempSync('/tmp/hsock-')+ dirs.push(dir)+ return dir+}++afterEach(async () => {+ for (const socket of opened.splice(0)) await socket.close()+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true })+})++function get(socketPath: string, path: string): Promise<{ status: number; body: string }> {+ return new Promise((resolve, reject) => {+ const r = request({ socketPath, path }, (res) => {+ let body = ''+ res.on('data', (chunk) => { body += chunk })+ res.on('end', () => resolve({ status: res.statusCode ?? 0, body }))+ })+ r.on('error', reject)+ r.end()+ })+}++describe('localSocketPath', () => {+ it('names one socket per control port, and none on Windows or past the length limit', () => {+ expect(localSocketPath('/Users/me/.harness/cli/data', 18473, 'darwin')).toBe('/Users/me/.harness/cli/data/daemon-18473.sock')+ expect(localSocketPath('/home/me/.harness/cli/data', 18474, 'linux')).toBe('/home/me/.harness/cli/data/daemon-18474.sock')+ expect(localSocketPath('C:\\Users\\me\\.harness', 18473, 'win32')).toBeNull()+ expect(localSocketPath(`/tmp/${'x'.repeat(100)}`, 18473, 'darwin')).toBeNull()+ // 96 bytes fits (the staging name adds 4, still under macOS's 104 with the terminator); 97 does not.+ const dirFor = (total: number) => `/${'d'.repeat(total - '/daemon-18473.sock'.length - 1)}`+ expect(localSocketPath(dirFor(96), 18473, 'darwin')).toHaveLength(96)+ expect(localSocketPath(dirFor(97), 18473, 'darwin')).toBeNull()+ expect(isLocalSocketName('daemon-18473.sock')).toBe(true)+ expect(isLocalSocketName('daemon.sock')).toBe(false)+ expect(isLocalSocketName('daemon-18473.sock.bak')).toBe(false)+ })+})++describe('listenLocalSocket', () => {+ it('serves over a socket only its owner can open, and trusts exactly those requests', async () => {+ const path = join(shortDir(), LOCAL_SOCKET_NAME)+ let trusted: boolean | null = null+ const socket = await listenLocalSocket((req, res) => { trusted = isTrustedLocal(req); res.end('hi') }, path)+ opened.push(socket)++ expect(statSync(path).mode & 0o777).toBe(0o600)+ expect(await get(path, '/')).toEqual({ status: 200, body: 'hi' })+ expect(trusted).toBe(true)+ expect(isTrustedLocal(undefined)).toBe(false)+ })++ it('replaces a crashed daemon\'s socket file, and refuses to replace anything else', async () => {+ const dir = shortDir()+ const path = join(dir, LOCAL_SOCKET_NAME)+ // A socket file nobody listens on any more: what a crash leaves.+ const first = await listenLocalSocket((_req, res) => res.end('old'), path)+ first.server.close()+ const second = await listenLocalSocket((_req, res) => res.end('new'), path)+ opened.push(second)+ expect((await get(path, '/')).body).toBe('new')++ const notASocket = join(dir, 'plain')+ writeFileSync(notASocket, 'keep me')+ await expect(listenLocalSocket((_req, res) => res.end(), notASocket)).rejects.toThrow(/not a socket/)+ expect(existsSync(notASocket)).toBe(true)+ })++ it('gives daemons on different ports a socket each, in one data directory', async () => {+ // Each port has its own name, so a second daemon never touches the first one's socket and a+ // client that knows its port reaches the daemon on that port.+ const dir = shortDir()+ const first = await listenLocalSocket((_req, res) => res.end('18473'), localSocketPath(dir, 18473, 'darwin')!)+ const second = await listenLocalSocket((_req, res) => res.end('18474'), localSocketPath(dir, 18474, 'darwin')!)+ opened.push(first, second)+ expect((await get(first.path, '/')).body).toBe('18473')+ expect((await get(second.path, '/')).body).toBe('18474')+ })++ it('closes at once even while a peer holds an upgraded connection open', async () => {+ // What a restart-for-update meets: a WebSocket the app has not finished closing. Waiting on+ // `server.close`'s callback would hang the restart until that peer let go.+ const path = join(shortDir(), LOCAL_SOCKET_NAME)+ const socket = await listenLocalSocket((_req, res) => res.end(), path)+ const held: Array<import('node:net').Socket> = []+ socket.server.on('upgrade', (_req, raw) => {+ held.push(raw as import('node:net').Socket)+ raw.write('HTTP/1.1 101 Switching Protocols\r\nUpgrade: test\r\nConnection: Upgrade\r\n\r\n')+ })+ const client = connect(path)+ await new Promise<void>((resolve) => client.once('connect', () => resolve()))+ client.write('GET / HTTP/1.1\r\nHost: localhost\r\nUpgrade: test\r\nConnection: Upgrade\r\n\r\n')+ await new Promise<void>((resolve) => client.once('data', () => resolve()))++ const closed = await Promise.race([+ socket.close().then(() => 'closed'),+ new Promise((resolve) => setTimeout(() => resolve('hung'), 1000)),+ ])+ expect(closed).toBe('closed')+ expect(existsSync(path)).toBe(false)+ client.destroy()+ for (const raw of held) raw.destroy()+ })++ it('listens at the longest path it allows', async () => {+ const dir = shortDir()+ const padded = join(dir, 'p'.repeat(96 - dir.length - 1 - '/daemon-1.sock'.length))+ mkdirSync(padded)+ const path = localSocketPath(padded, 1, 'darwin')!+ expect(Buffer.byteLength(path)).toBe(96)+ const socket = await listenLocalSocket((_req, res) => res.end('long'), path)+ opened.push(socket)+ expect((await get(path, '/')).body).toBe('long')+ expect(statSync(path).mode & 0o777).toBe(0o600)+ })++ it('removes the socket file when it closes', async () => {+ const path = join(shortDir(), LOCAL_SOCKET_NAME)+ const socket = await listenLocalSocket((_req, res) => res.end(), path)+ await socket.close()+ expect(existsSync(path)).toBe(false)+ await expect(new Promise((resolve, reject) => {+ const c = connect(path, () => { c.end(); resolve(true) })+ c.on('error', reject)+ })).rejects.toThrow()++ const again = await listenLocalSocket((_req, res) => res.end(), path)+ again.closeSync()+ expect(existsSync(path)).toBe(false)+ })+})diff --git a/cli/src/lib/localSocket.ts b/cli/src/lib/localSocket.tsnew file mode 100644index 000000000..a462b7781--- /dev/null+++ b/cli/src/lib/localSocket.ts@@ -0,0 +1,119 @@+/**+ * The daemon's Unix domain socket: the desktop app'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+ * daemon's data directory (0700) and is itself 0600, so the filesystem is the credential: only this+ * user's processes can connect. A request that arrives over it is from this user, and needs none of+ * the address checks a TCP request does — its peer has no address at all.+ *+ * TCP stays: the CLI, engine hooks and the dashboard (a browser cannot reach a socket file) still use+ * it, as do app builds that predate this. Windows has no socket here; there everything is TCP.+ */+import http from 'node:http'+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.+ */+export function localSocketName(port: number): string {+ return `daemon-${port}.sock`+}++/** Whether a file in the data directory is one of these sockets (for `harness reset`). */+export function isLocalSocketName(name: string): boolean {+ return /^daemon-\d+\.sock$/.test(name)+}++/** sockaddr_un.sun_path is 104 bytes on macOS, 108 on Linux, terminator included; the socket is+ * created under a name 4 bytes longer (see [listenLocalSocket]) and must fit too. */+const MAX_SOCKET_PATH_BYTES = 96++const trustedSockets = new WeakSet<Socket>()++/** Where the socket for the daemon on `port` lives in this data directory, or null where there is none. */+export function localSocketPath(dataDir: string, port: number, platform: NodeJS.Platform = process.platform): string | null {+ if (platform === 'win32') return null+ const path = join(dataDir, localSocketName(port))+ return Buffer.byteLength(path) <= MAX_SOCKET_PATH_BYTES ? path : null+}++/** Whether this request (or raw socket) came in over the daemon's own Unix socket. */+export function isTrustedLocal(target: IncomingMessage | Socket | null | undefined): boolean {+ if (!target) return false+ const socket = 'socket' in target && target.socket ? target.socket : target as Socket+ return trustedSockets.has(socket)+}++export interface LocalSocketServer {+ server: http.Server+ path: string+ /** Stop listening and remove the socket file. */+ close: () => Promise<void>+ /** The same, for the synchronous boot handoff. */+ closeSync: () => void+}++/**+ * 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.+ */+export async function listenLocalSocket(handler: http.RequestListener, path: string): Promise<LocalSocketServer> {+ removeStaleSocket(path)+ const server = http.createServer(handler)+ server.on('connection', (socket) => trustedSockets.add(socket))+ const unlink = (): void => {+ try { if (lstatSync(path).isSocket()) unlinkSync(path) } catch { /* already gone */ }+ }+ // Stop listening, drop what is connected and remove the file — without waiting on `close`'s+ // callback, which waits for every socket to end: an upgraded WebSocket the peer never finishes+ // closing would otherwise hold a restart-for-update open indefinitely.+ const closeNow = (): void => {+ server.closeAllConnections()+ server.close()+ unlink()+ }+ // `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.+ const staging = `${path}.new`+ try { if (lstatSync(staging).isSocket()) unlinkSync(staging) } catch { /* nothing left over */ }+ return new Promise((resolve, reject) => {+ server.once('error', reject)+ server.listen(staging, () => {+ server.off('error', reject)+ try {+ chmodSync(staging, 0o600)+ renameSync(staging, path)+ } catch (error) {+ server.closeAllConnections()+ server.close()+ try { unlinkSync(staging) } catch { /* never created, or already moved */ }+ reject(error)+ return+ }+ resolve({ server, path, close: async () => closeNow(), closeSync: closeNow })+ })+ })+}++function removeStaleSocket(path: string): void {+ let isSocket: boolean+ try {+ isSocket = lstatSync(path).isSocket()+ } catch {+ return // nothing there+ }+ if (!isSocket) throw new Error(`${path} exists and is not a socket; not replacing it`)+ unlinkSync(path)+}diff --git a/cli/src/localWsServer.spec.ts b/cli/src/localWsServer.spec.tsindex a0c543468..4dd4b6100 100644--- a/cli/src/localWsServer.spec.ts+++ b/cli/src/localWsServer.spec.ts@@ -5,6 +5,9 @@ import { WebSocket } from 'ws'import type { Frame, LocalClientSink } from './backendSocket.js'import { attachLocalWsServer, type LocalWsBackend, type LocalWsServer, type LocalWsServerOptions } from './localWsServer.js'import { encodeTerminalLocal, TerminalBinaryKind, type TerminalBinaryClear } from './lib/terminalBinary.js'+import { listenLocalSocket } from './lib/localSocket.js'+import { mkdtempSync, rmSync } from 'node:fs'+import { join } from 'node:path'const machineId = 'machine-123'const streamId = '00112233-4455-6677-8899-aabbccddeeff'@@ -71,6 +74,35 @@ describe('local CLI WebSocket', () => {return `ws://127.0.0.1:${port}/api/local-ws`}+ it('serves the same endpoint over the daemon socket, with no Host to name and no Origin allowed', async () => {+ const dir = mkdtempSync('/tmp/hsock-')+ const socketPath = join(dir, 'daemon.sock')+ const backend = new FakeBackend()+ const unix = await listenLocalSocket((_req, res) => { res.statusCode = 404; res.end() }, socketPath)+ await start(backend, { localSocketServer: unix.server })+ const url = `ws+unix://${socketPath}:/api/local-ws`+ try {+ // No port, no loopback Host — refused on TCP, served here.+ const ws = new WebSocket(url, { headers: { host: 'rebind.evil.example' } })+ await onceOpen(ws)+ const connected = onceMessage(ws)+ ws.send(JSON.stringify({ type: 'machine_select', payload: { machineId, localProtocolVersion: 1 } }))+ expect(await connected).toMatchObject({ type: 'connected', payload: { machineId, transport: 'local' } })+ expect(backend.connId).toMatch(/^local:/)+ ws.close()++ // A browser still has no business here, whichever way it arrived.+ const browser = new WebSocket(url, { headers: { origin: 'http://localhost' } })+ const status = await new Promise<number>((resolve) => browser.once('unexpected-response', (_req, res) => resolve(res.statusCode ?? 0)))+ expect(status).toBe(403)+ } finally {+ await local?.close()+ local = null+ await unix.close()+ rmSync(dir, { recursive: true, force: true })+ }+ })+it('refuses an upgrade whose Host is not a loopback name for this port', async () => {const url = await start(new FakeBackend())const ws = new WebSocket(url, { headers: { host: 'rebind.evil.example:' + new URL(url).port } })diff --git a/cli/src/localWsServer.ts b/cli/src/localWsServer.tsindex b4c46fdcb..8acc9f4c4 100644--- a/cli/src/localWsServer.ts+++ b/cli/src/localWsServer.ts@@ -6,6 +6,7 @@ import type { Socket } from 'node:net'import { WebSocket, WebSocketServer, type RawData } from 'ws'import { watchSocketLiveness } from './lib/wsLiveness.js'import { isLoopbackRequest, loopbackHosts } from './lib/loopbackRequest.js'+import { isTrustedLocal } from './lib/localSocket.js'import type { Frame, LocalClientSink } from './backendSocket.js'import {decodeTerminalLocal,@@ -40,6 +41,8 @@ export interface LocalWsBackend {export interface LocalWsServerOptions {machineId: stringbackend: LocalWsBackend+ /** The daemon's Unix-socket server (lib/localSocket.ts), served the same endpoint beside TCP. */+ localSocketServer?: http.Server | null/** Serves a `machine_select` for any OTHER machine this signed-in user owns, by relaying to* backend's `/api/web-ws` — see lib/remoteRelay.ts. Omit to keep today's own-machine-only behavior. */relayPool?: RemoteRelayPool@@ -239,6 +242,13 @@ export function attachLocalWsServer(server: http.Server, options: LocalWsServerOconst onUpgrade = (req: http.IncomingMessage, socket: Socket, head: Buffer): void => {const path = (req.url ?? '').split('?')[0]if (path !== LOCAL_WS_PATH) return+ // Over the daemon's own socket (lib/localSocket.ts) the filesystem already vouched for the peer;+ // it has no address or port to check. It still must not be a browser.+ if (isTrustedLocal(req)) {+ if (req.headers.origin) { rejectUpgrade(socket, 403, 'Forbidden'); return }+ wss.handleUpgrade(req, socket, head, (ws) => wss.emit('connection', ws, req))+ return+ }if (!isLoopback(req.socket.remoteAddress)) {rejectUpgrade(socket, 403, 'Forbidden')return@@ -251,7 +261,8 @@ export function attachLocalWsServer(server: http.Server, options: LocalWsServerO}wss.handleUpgrade(req, socket, head, (ws) => wss.emit('connection', ws, req))}- server.on('upgrade', onUpgrade)+ const servers = [server, ...(options.localSocketServer ? [options.localSocketServer] : [])]+ for (const each of servers) each.on('upgrade', onUpgrade)wss.on('connection', (ws) => {const connId = `local:${randomUUID()}`@@ -582,7 +593,7 @@ export function attachLocalWsServer(server: http.Server, options: LocalWsServerOreturn {close: async () => {- server.off('upgrade', onUpgrade)+ for (const each of servers) each.off('upgrade', onUpgrade)for (const client of wss.clients) client.close(1001, 'server shutting down')await new Promise<void>((resolve) => wss.close(() => resolve()))},diff --git a/desktop/CLAUDE.md b/desktop/CLAUDE.mdindex 86e4d4c05..e14fb866a 100644--- a/desktop/CLAUDE.md+++ b/desktop/CLAUDE.md@@ -127,6 +127,16 @@ holds an SSO token:`LocalCliDiscovery`, which runs `harness start` when needed). The CLI terminates E2EE for relayedmachines; the app carries no crypto. Close code `4404`/`NO_PEER_LINK` means the machine needs`harness link import` — surfaced as `MachineState.needsLink` and polled via `_linkRetryTimers`.+- **Both REST and the local WS prefer the daemon's Unix socket** (`lib/ws/local_daemon_transport.dart`;+ CLI `lib/localSocket.ts`): `~/.harness/cli/data/daemon-<port>.sock`, 0600, named for the port in+ `localCliBaseUrl` so it always leads to the same daemon as the TCP fallback. The loopback port takes+ any local user's process; the socket only this user's. One `LocalDaemonTransport`, owned by+ `LocalCliDiscovery`, is shared by `ApiClient` (a Dio adapter that only routes the daemon's own+ address) and `WsPool`/`WsConn`. Discovery probes the socket first and the port second; a request or+ dial that cannot reach the socket retries on the port, and each WS connect re-checks whether the+ socket file exists, so a daemon restart does not strand the app on TCP. Windows and paths over 96+ bytes have no socket. The CLI, engine hooks and the dashboard stay on TCP. Under `flutter test`+ `LocalDaemonTransport.detect` finds no socket, so tests never reach a real daemon.- The **only** direct-to-backend path is `LocalManualFixture` (`lib/main_local_manual.dart`), acompile-time-gated dev entrypoint fed by `scripts/start-terminal-local-manual.sh`. It fails closedunless every `--dart-define` is present.diff --git a/desktop/lib/api/api_client.dart b/desktop/lib/api/api_client.dartindex b599ef00a..a14d30046 100644--- a/desktop/lib/api/api_client.dart+++ b/desktop/lib/api/api_client.dart@@ -6,6 +6,7 @@ import '../auth/auth_session.dart';import '../core/config.dart';import '../core/models.dart';import '../logging/http_log.dart';+import '../ws/local_daemon_transport.dart';import 'access_token_source.dart';import 'bearer_auth_interceptor.dart';@@ -27,9 +28,18 @@ class ApiClient {final AppConfig config;final AuthSession session;final AccessTokenSource? auth;++ /// How the local CLI is reached — its Unix socket or the loopback port (see+ /// [LocalDaemonTransport]). Null keeps the loopback port, as before.+ final LocalDaemonTransport? localTransport;late final Dio _dio = _buildDio();- ApiClient({required this.config, required this.session, this.auth});+ ApiClient({+ required this.config,+ required this.session,+ this.auth,+ this.localTransport,+ });Dio _buildDio() {final dio = attachHttpLog(@@ -45,6 +55,13 @@ class ApiClient {),),);+ final transport = localTransport;+ if (auth == null && transport != null) {+ dio.httpClientAdapter = LocalDaemonHttpAdapter(+ transport,+ daemonBase: Uri.parse(config.localCliBaseUrl),+ );+ }final source = auth;if (source != null) {dio.interceptors.add(diff --git a/desktop/lib/sharing/shared_harness_panel.dart b/desktop/lib/sharing/shared_harness_panel.dartindex e7ab590c3..a2c4f29d3 100644--- a/desktop/lib/sharing/shared_harness_panel.dart+++ b/desktop/lib/sharing/shared_harness_panel.dart@@ -80,6 +80,7 @@ class _SharedHarnessPanelState extends State<SharedHarnessPanel> {observerShareId: widget.grant.id,transportKind: WsTransportKind.localPlaintext,localWsUri: uri,+ localTransport: widget.notifier.localDaemonTransport,accessTokenProvider: (_, _) async => '',onAuthFailure: (reason) {if (generation == _generation) _end(reason);diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex 6b9214b3c..b4b2024f9 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -64,6 +64,7 @@ import '../update/manual_update_check.dart';import '../ws/ws_conn.dart';import 'retarget_refusal.dart';import '../ws/local_cli_discovery.dart';+import '../ws/local_daemon_transport.dart';import '../ws/ws_pool.dart';import 'pane_preset.dart';import 'pane_arrangement.dart';@@ -1743,8 +1744,17 @@ class AppNotifier extends ChangeNotifier {}/// Through the local CLI in a desktop build; straight to the backend, signed, in a viewer.- ApiClient _newApiClient() =>- ApiClient(config: config, session: session, auth: viewer?.auth);+ ApiClient _newApiClient() => ApiClient(+ config: config,+ session: session,+ auth: viewer?.auth,+ localTransport: localDaemonTransport,+ );++ /// How this app reaches the local CLI — its Unix socket or the loopback+ /// port. Owned by discovery, which decides it; REST and the local WebSocket+ /// follow it.+ LocalDaemonTransport get localDaemonTransport => _discovery.transport;String? get lastError => _lastError;@@ -3991,6 +4001,7 @@ class AppNotifier extends ChangeNotifier {void _ensurePool() {if (_pool != null) return;_pool = WsPool(+ localTransport: localDaemonTransport,wsBaseUrl: config.wsBaseUrl,autonomousEnv: _autonomousEnv,// Every real desktop WsConn dials the local CLI's loopback WS (transportKind.localPlaintext, seediff --git a/desktop/lib/ws/local_cli_discovery.dart b/desktop/lib/ws/local_cli_discovery.dartindex 39b1e135b..760911507 100644--- a/desktop/lib/ws/local_cli_discovery.dart+++ b/desktop/lib/ws/local_cli_discovery.dart@@ -2,6 +2,7 @@ import 'dart:async';import 'dart:io';import 'package:dio/dio.dart';+import 'package:dio/io.dart';import 'package:flutter/foundation.dart';import '../core/serial_port_lease.dart';@@ -9,6 +10,7 @@ import '../core/config.dart';import '../core/harness_cli_runner.dart';import '../core/harness_file_store.dart';import '../core/models.dart';+import 'local_daemon_transport.dart';const localWsProtocolVersion = 1;const localTerminalProtocolVersion = 3;@@ -35,6 +37,10 @@ class LocalCliEndpoint {/// project metadata in agent frames. This snapshot never describes a peer.final Map<String, AgentProject> agentProjects;+ /// The daemon's Unix socket when it answered there, or null when it answered+ /// on the loopback port. [wsUri] names the same endpoint either way.+ final String? socketPath;+const LocalCliEndpoint({required this.computerId,required this.wsUri,@@ -43,6 +49,7 @@ class LocalCliEndpoint {this.machineId,this.backendOnline = true,this.agentProjects = const {},+ this.socketPath,});}@@ -186,12 +193,20 @@ class LocalCliDiscovery {final LocalMachineIdentity identity;final Future<void> Function() _spawnCommand;+ /// Which way the daemon is reached — its socket or the loopback port. Shared+ /// with REST and the local WebSocket; [probe] decides it.+ final LocalDaemonTransport transport;+LocalCliDiscovery({required this.config,Dio? dio,LocalMachineIdentity? identity,Future<void> Function()? spawnCommand,+ LocalDaemonTransport? transport,}) : identity = identity ?? LocalMachineIdentity(),+ transport =+ transport ??+ LocalDaemonTransport.detect(Uri.parse(config.localCliBaseUrl)),_spawnCommand = spawnCommand ?? _defaultSpawnCommand,_dio =dio ??@@ -423,14 +438,71 @@ class LocalCliDiscovery {return const LocalCliProbe.down('computer id mismatch');}final base = Uri.parse(config.localCliBaseUrl);+ // The socket first: only this user can have opened it. A daemon that+ // answers there — ready or not — is the daemon; one that does not may+ // predate the socket, so the port is asked next.+ final socket = transport.candidate;+ if (socket != null && transport.socketPresent) {+ final viaSocket = await _probeStatus(+ _socketDio(socket),+ Uri.parse('http://localhost/api/status'),+ base,+ localComputerId,+ socketPath: socket,+ );+ if (viaSocket.state != LocalCliProbeState.down) {+ transport.useSocket();+ return viaSocket;+ }+ }+ transport.useTcp();if (base.host != '127.0.0.1' && base.host != 'localhost') {return const LocalCliProbe.down('the local CLI address is not loopback');}+ return _probeStatus(+ _dio,+ base.resolve('/api/status'),+ base,+ localComputerId,+ socketPath: null,+ );+ }++ Dio? _socketProbe;+ String? _socketProbePath;++ Dio _socketDio(String path) {+ if (_socketProbe == null || _socketProbePath != path) {+ _socketProbe?.close(force: true);+ _socketProbePath = path;+ _socketProbe =+ Dio(+ BaseOptions(+ connectTimeout: const Duration(milliseconds: 400),+ receiveTimeout: const Duration(milliseconds: 400),+ sendTimeout: const Duration(milliseconds: 400),+ ),+ )+ ..httpClientAdapter = IOHttpClientAdapter(+ createHttpClient: () => unixHttpClient(path),+ );+ }+ return _socketProbe!;+ }++ /// Reads and validates `/api/status` from [statusUri] with [dio]. [base] is+ /// the loopback address the WebSocket URI is named from, whichever way the+ /// status was read.+ Future<LocalCliProbe> _probeStatus(+ Dio dio,+ Uri statusUri,+ Uri base,+ String localComputerId, {+ required String? socketPath,+ }) async {final Map<String, dynamic>? body;try {- final response = await _dio.getUri<Map<String, dynamic>>(- base.resolve('/api/status'),- );+ final response = await dio.getUri<Map<String, dynamic>>(statusUri);body = response.data;} on DioException catch (error) {switch (error.type) {@@ -540,6 +612,7 @@ class LocalCliDiscovery {body['sessions'],identity.environment,),+ socketPath: socketPath,),pid: pid,version: version,diff --git a/desktop/lib/ws/local_daemon_transport.dart b/desktop/lib/ws/local_daemon_transport.dartnew file mode 100644index 000000000..2b76cb4f2--- /dev/null+++ b/desktop/lib/ws/local_daemon_transport.dart@@ -0,0 +1,160 @@+import 'dart:async';+import 'dart:convert';+import 'dart:io';+import 'dart:typed_data';++import 'package:dio/dio.dart';+import 'package:dio/io.dart';++import '../core/test_run.dart';++/// The daemon's Unix socket, beside its loopback port (CLI `lib/localSocket.ts`).+///+/// The loopback port takes requests from any process on this computer, any+/// user's; the socket file is 0600 in a 0700 directory, so only this user's+/// processes can open it. The app prefers it for both REST and the local+/// WebSocket and falls back to the port — for a daemon that predates the+/// socket, one that could not open it, or a moment when it is missing.+///+/// There is one socket per control port, `daemon-<port>.sock`, named for the+/// port the app would otherwise dial: the socket and the fallback always lead+/// to the same daemon, even with a second one on another port.+String daemonSocketName(int port) => 'daemon-$port.sock';++/// The daemon opens no socket path longer than this (`sockaddr_un.sun_path`+/// is 104 bytes on macOS, less the daemon's staging suffix), so neither does+/// the app look for one.+const _maxSocketPathBytes = 96;++/// Where the socket of the daemon on [port] would be —+/// `$ADAPTER_DATA_DIR/daemon-<port>.sock`, by default+/// `~/.harness/cli/data/daemon-<port>.sock` — or null where there is none+/// (Windows, or a path too long to be a socket).+String? defaultDaemonSocketPath(+ int port, {+ Map<String, String>? environment,+ bool? isWindows,+}) {+ if (isWindows ?? Platform.isWindows) return null;+ final env = environment ?? Platform.environment;+ final home = env['HOME'];+ final dataDir =+ env['ADAPTER_DATA_DIR'] ??+ (home == null || home.isEmpty ? null : '$home/.harness/cli/data');+ if (dataDir == null) return null;+ final path = '$dataDir/${daemonSocketName(port)}';+ return utf8.encode(path).length <= _maxSocketPathBytes ? path : null;+}++/// An [HttpClient] whose every connection goes to the socket at [path],+/// whatever host the URL names.+HttpClient unixHttpClient(String path) => HttpClient()+ ..connectionFactory = (uri, proxyHost, proxyPort) => Socket.startConnect(+ InternetAddress(path, type: InternetAddressType.unix),+ 0,+ );++/// Which way the app currently reaches the daemon. One instance is shared by+/// discovery, REST and the local WebSocket so they agree.+class LocalDaemonTransport {+ LocalDaemonTransport({this.candidate});++ /// The transport to the daemon at [daemonBase] (the loopback address the app+ /// would otherwise dial): the socket named for its port, except under+ /// `flutter test`, where a real daemon's socket must never be reached.+ factory LocalDaemonTransport.detect(Uri daemonBase) => LocalDaemonTransport(+ candidate: kUnderTest ? null : defaultDaemonSocketPath(daemonBase.port),+ );++ /// Where the socket would be, or null when this app never uses one.+ final String? candidate;++ String? _active;++ /// The socket to use now, or null for the loopback port. Set by discovery+ /// once the daemon answered over it; dropped when a connection to it fails.+ String? get socketPath => _active;++ /// Whether a socket file is there to try.+ bool get socketPresent {+ final path = candidate;+ return path != null &&+ FileSystemEntity.typeSync(path, followLinks: false) ==+ FileSystemEntityType.unixDomainSock;+ }++ void useSocket() => _active = candidate;++ void useTcp() => _active = null;+}++/// Whether [error] means nothing could be reached — as opposed to a daemon+/// that answered badly, which a retry elsewhere would not fix.+bool isConnectionFailure(Object error) {+ if (error is SocketException) return true;+ if (error is DioException) {+ return error.type == DioExceptionType.connectionError ||+ error.type == DioExceptionType.connectionTimeout ||+ error.error is SocketException;+ }+ return false;+}++/// Sends daemon REST over [transport]'s socket when there is one, and over the+/// loopback port otherwise — including, once, when the socket cannot be+/// reached: the request is retried on the port and the transport falls back+/// until discovery finds the socket again.+class LocalDaemonHttpAdapter implements HttpClientAdapter {+ LocalDaemonHttpAdapter(this.transport, {required this.daemonBase});++ final LocalDaemonTransport transport;++ /// The daemon's loopback address. Only requests to it take the socket; one+ /// the same client sends anywhere else (a loopback override for another+ /// local service) goes where its URL says.+ final Uri daemonBase;+ final IOHttpClientAdapter _tcp = IOHttpClientAdapter();+ IOHttpClientAdapter? _unix;+ String? _unixPath;++ IOHttpClientAdapter _unixFor(String path) {+ if (_unix == null || _unixPath != path) {+ _unix?.close(force: true);+ _unixPath = path;+ _unix = IOHttpClientAdapter(createHttpClient: () => unixHttpClient(path));+ }+ return _unix!;+ }++ @override+ Future<ResponseBody> fetch(+ RequestOptions options,+ Stream<Uint8List>? requestStream,+ Future<void>? cancelFuture,+ ) async {+ final path = transport.socketPath;+ final uri = options.uri;+ final toDaemon =+ uri.scheme == daemonBase.scheme &&+ uri.host == daemonBase.host &&+ uri.port == daemonBase.port;+ if (path == null || !toDaemon) {+ return _tcp.fetch(options, requestStream, cancelFuture);+ }+ try {+ return await _unixFor(path).fetch(options, requestStream, cancelFuture);+ } catch (error) {+ if (!isConnectionFailure(error)) rethrow;+ // Nothing was sent: the socket could not be opened. The port can still+ // serve this request, and discovery will find the socket again later.+ transport.useTcp();+ return _tcp.fetch(options, requestStream, cancelFuture);+ }+ }++ @override+ void close({bool force = false}) {+ _tcp.close(force: force);+ _unix?.close(force: force);+ }+}diff --git a/desktop/lib/ws/ws_conn.dart b/desktop/lib/ws/ws_conn.dartindex a9e9e8433..6451a83e9 100644--- a/desktop/lib/ws/ws_conn.dart+++ b/desktop/lib/ws/ws_conn.dart@@ -1,13 +1,16 @@import 'dart:async';import 'dart:convert';+import 'dart:io';import 'dart:math';import 'package:flutter/foundation.dart';+import 'package:web_socket_channel/io.dart';import 'package:web_socket_channel/web_socket_channel.dart';import '../logging/app_log.dart';import '../logging/redact.dart';import '../core/models.dart';+import 'local_daemon_transport.dart';import 'relay_codec.dart';import 'terminal_transport_plugin.dart';@@ -77,6 +80,11 @@ class WsConn {final WsTransportKind transportKind;final Uri? localWsUri;+ /// How the local daemon is reached (see [LocalDaemonTransport]). When it+ /// names a socket, a local connection dials [localWsUri]'s path over it and+ /// falls back to [localWsUri] itself if the socket cannot be reached.+ final LocalDaemonTransport? localTransport;+/// Retained only for fixture constructor compatibility. Local transport ignores it.final String? localApiKey;final String? observerShareId;@@ -181,6 +189,7 @@ class WsConn {required this.onStatus,this.transportKind = WsTransportKind.cloudE2ee,this.localWsUri,+ this.localTransport,this.localApiKey,this.observerShareId,this.localProtocolVersion = 1,@@ -189,6 +198,41 @@ class WsConn {this.transportPlugins,});+ /// The socket to dial, decided afresh on every connect: whether the file is+ /// there now, not whether it was the last time something looked. A dial+ /// that failed while the daemon restarted must not keep this connection on+ /// the port for good once the daemon is back with its socket.+ String? _localSocket() {+ final transport = localTransport;+ if (transport == null) return null;+ if (transport.socketPresent) return transport.candidate;+ transport.useTcp();+ return null;+ }++ /// The local WebSocket over the daemon's Unix socket, or null when that+ /// failed and the loopback port should be used instead. A socket that could+ /// not be reached at all sends everything back to the port until discovery+ /// finds it again.+ Future<WebSocketChannel?> _connectLocalSocket(Uri uri, String socket) async {+ final pending = WebSocket.connect(+ Uri(scheme: 'ws', host: 'localhost', path: uri.path).toString(),+ customClient: unixHttpClient(socket),+ );+ try {+ return IOWebSocketChannel(+ await pending.timeout(const Duration(seconds: 5)),+ );+ } on TimeoutException {+ // The dial goes on after the timeout; a socket it opens late is nobody's.+ unawaited(pending.then((ws) => ws.close(), onError: (_) {}));+ return null;+ } catch (error) {+ if (isConnectionFailure(error)) localTransport?.useTcp();+ return null;+ }+ }+Future<void> connect() async {if (_closing || _connecting) return;_connecting = true;@@ -236,9 +280,17 @@ class WsConn {},);}- final channel = isLocal- ? WebSocketChannel.connect(uri)- : WebSocketChannel.connect(uri, protocols: [token!]);+ final socket = isLocal ? _localSocket() : null;+ final channel = !isLocal+ ? WebSocketChannel.connect(uri, protocols: [token!])+ : socket != null+ ? await _connectLocalSocket(uri, socket) ??+ WebSocketChannel.connect(uri)+ : WebSocketChannel.connect(uri);+ if (_closing) {+ await channel.sink.close();+ return;+ }_channel = channel;await channel.ready;if (_closing || !identical(_channel, channel)) {diff --git a/desktop/lib/ws/ws_pool.dart b/desktop/lib/ws/ws_pool.dartindex 6798266a3..c10618147 100644--- a/desktop/lib/ws/ws_pool.dart+++ b/desktop/lib/ws/ws_pool.dart@@ -1,5 +1,6 @@import 'dart:async';+import 'local_daemon_transport.dart';import 'relay_codec.dart';import 'terminal_transport_plugin.dart';@@ -27,7 +28,12 @@ class WsPool {final Map<String, WsConn> _conns = {};+ /// How local connections reach the daemon — its socket or the loopback+ /// port. Null keeps the port.+ final LocalDaemonTransport? localTransport;+WsPool({+ this.localTransport,required this.wsBaseUrl,required this.autonomousEnv,this.relayCodecs,@@ -91,6 +97,7 @@ class WsPool {},transportKind: transportKind,localWsUri: localWsUri,+ localTransport: localTransport,localApiKey: localApiKey,localProtocolVersion: localProtocolVersion,fixedReconnectDelay: fixedReconnectDelay,diff --git a/desktop/test/local_daemon_transport_test.dart b/desktop/test/local_daemon_transport_test.dartnew file mode 100644index 000000000..7cc0573e3--- /dev/null+++ b/desktop/test/local_daemon_transport_test.dart@@ -0,0 +1,272 @@+import 'dart:convert';+import 'dart:io';++import 'package:dio/dio.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/api/api_client.dart';+import 'package:harness/auth/auth_session.dart';+import 'package:harness/core/config.dart';+import 'package:harness/ws/local_cli_discovery.dart';+import 'package:harness/ws/local_daemon_transport.dart';+import 'package:harness/ws/ws_conn.dart';++const _computerId = '0123456789abcdef0123456789abcdef';++/// A stand-in daemon: `/api/status`, `/api/auth/me` and the local WebSocket,+/// on whatever [HttpServer] it is given, counting what reached it.+class _Daemon {+ _Daemon(this.server, this.name) {+ server.listen((request) async {+ hits.add(request.uri.path);+ if (WebSocketTransformer.isUpgradeRequest(request)) {+ final ws = await WebSocketTransformer.upgrade(request);+ ws.listen((data) {+ final frame = jsonDecode(data as String) as Map<String, dynamic>;+ if (frame['type'] == 'machine_select') {+ selects++;+ ws.add(jsonEncode({'type': 'connected', 'payload': frame['payload']}));+ }+ });+ return;+ }+ request.response.headers.contentType = ContentType.json;+ if (request.uri.path == '/api/status') {+ request.response.write(+ jsonEncode({+ 'computerId': _computerId,+ 'localWs': {+ 'path': '/api/local-ws',+ 'protocolVersion': 1,+ 'terminalProtocolVersion': 3,+ 'e2ee': false,+ },+ }),+ );+ } else {+ request.response.write(+ jsonEncode({+ 'success': true,+ 'data': {'via': name},+ }),+ );+ }+ await request.response.close();+ });+ }++ final HttpServer server;+ final String name;+ final List<String> hits = [];+ int selects = 0;++ static Future<_Daemon> tcp() async =>+ _Daemon(await HttpServer.bind(InternetAddress.loopbackIPv4, 0), 'tcp');++ static Future<_Daemon> unix(String path) async => _Daemon(+ await HttpServer.bind(InternetAddress(path, type: InternetAddressType.unix), 0),+ 'unix',+ );++ Future<void> close() => server.close(force: true);+}++void main() {+ late Directory scratch;+ late String socketPath;+ late File identityFile;+ final daemons = <_Daemon>[];++ setUp(() async {+ // Socket paths are capped near 104 bytes; the default temp dir is longer.+ scratch = await Directory('/tmp').createTemp('hsock-');+ socketPath = '${scratch.path}/daemon.sock';+ identityFile = File('${scratch.path}/computer-id')+ ..writeAsStringSync(_computerId);+ });++ tearDown(() async {+ for (final daemon in daemons.reversed) {+ await daemon.close();+ }+ daemons.clear();+ if (await scratch.exists()) await scratch.delete(recursive: true);+ });++ Future<_Daemon> start(Future<_Daemon> daemon) async {+ final started = await daemon;+ daemons.add(started);+ return started;+ }++ AppConfig configFor(_Daemon tcp) => AppConfig(+ apiBaseUrl: 'http://unused.invalid',+ localCliBaseUrl: 'http://127.0.0.1:${tcp.server.port}',+ );++ group('defaultDaemonSocketPath', () {+ test('is the socket for the daemon\'s port in the CLI data directory', () {+ expect(+ defaultDaemonSocketPath(18473, environment: {'HOME': '/Users/me'}, isWindows: false),+ '/Users/me/.harness/cli/data/daemon-18473.sock',+ );+ // Another port, another daemon, another socket.+ expect(+ defaultDaemonSocketPath(+ 18474,+ environment: {'HOME': '/Users/me', 'ADAPTER_DATA_DIR': '/srv/h'},+ isWindows: false,+ ),+ '/srv/h/daemon-18474.sock',+ );+ expect(defaultDaemonSocketPath(18473, environment: {'HOME': '/Users/me'}, isWindows: true), isNull);+ expect(+ defaultDaemonSocketPath(18473, environment: {'HOME': '/${'x' * 100}'}, isWindows: false),+ isNull,+ );+ });++ test('is never looked for under flutter test', () {+ expect(+ LocalDaemonTransport.detect(Uri.parse('http://127.0.0.1:18473')).candidate,+ isNull,+ );+ });+ });++ group('discovery', () {+ test('asks the socket first and keeps the port untouched', () async {+ final tcp = await start(_Daemon.tcp());+ await start(_Daemon.unix(socketPath));+ final transport = LocalDaemonTransport(candidate: socketPath);+ final endpoint = await LocalCliDiscovery(+ config: configFor(tcp),+ identity: LocalMachineIdentity(computerIdFile: identityFile),+ transport: transport,+ ).discover();++ expect(endpoint?.socketPath, socketPath);+ expect(transport.socketPath, socketPath);+ // The WebSocket keeps its loopback name, so the pool's key is unchanged.+ expect(endpoint?.wsUri.toString(), 'ws://127.0.0.1:${tcp.server.port}/api/local-ws');+ expect(tcp.hits, isEmpty);+ });++ test('falls back to the port when there is no socket', () async {+ final tcp = await start(_Daemon.tcp());+ final transport = LocalDaemonTransport(candidate: socketPath)..useSocket();+ final endpoint = await LocalCliDiscovery(+ config: configFor(tcp),+ identity: LocalMachineIdentity(computerIdFile: identityFile),+ transport: transport,+ ).discover();++ expect(endpoint, isNotNull);+ expect(endpoint!.socketPath, isNull);+ expect(transport.socketPath, isNull);+ expect(tcp.hits, ['/api/status']);+ });+ });++ group('REST', () {+ test('goes over the socket, and back to the port once it is gone', () async {+ final tcp = await start(_Daemon.tcp());+ final unix = await start(_Daemon.unix(socketPath));+ final transport = LocalDaemonTransport(candidate: socketPath)..useSocket();+ final api = ApiClient(+ config: configFor(tcp),+ session: AuthSession(),+ localTransport: transport,+ );++ expect(await api.me(), {'via': 'unix'});+ expect(unix.hits, ['/api/auth/me']);++ await unix.close();+ daemons.remove(unix);+ // Closing the server removes its socket file; make sure nothing is left to dial.+ if (File(socketPath).existsSync()) File(socketPath).deleteSync();+ expect(await api.me(), {'via': 'tcp'});+ expect(transport.socketPath, isNull);+ });++ test('never sends a request for another address down the socket', () async {+ final tcp = await start(_Daemon.tcp());+ final other = await start(_Daemon.tcp());+ final unix = await start(_Daemon.unix(socketPath));+ final transport = LocalDaemonTransport(candidate: socketPath)..useSocket();+ final dio = Dio()+ ..httpClientAdapter = LocalDaemonHttpAdapter(+ transport,+ daemonBase: Uri.parse('http://127.0.0.1:${tcp.server.port}'),+ );++ final response = await dio.get<Map<String, dynamic>>(+ 'http://127.0.0.1:${other.server.port}/api/elsewhere',+ );+ expect(response.data?['data'], {'via': 'tcp'});+ expect(other.hits, ['/api/elsewhere']);+ expect(unix.hits, isEmpty);+ });+ });++ group('local WebSocket', () {+ WsConn connFor(_Daemon tcp, LocalDaemonTransport transport) => WsConn(+ wsBaseUrl: 'wss://unused.example',+ autonomousEnv: 'prod',+ machineId: 'm1',+ accessTokenProvider: (_, _) async => '',+ onAuthFailure: (_) {},+ onEvent: (_) {},+ onStatus: (_) {},+ transportKind: WsTransportKind.localPlaintext,+ localWsUri: Uri.parse('ws://127.0.0.1:${tcp.server.port}/api/local-ws'),+ localTransport: transport,+ );++ Future<void> until(bool Function() done) async {+ for (var i = 0; i < 100 && !done(); i++) {+ await Future<void>.delayed(const Duration(milliseconds: 10));+ }+ }++ test('dials the socket when discovery chose it', () async {+ final tcp = await start(_Daemon.tcp());+ final unix = await start(_Daemon.unix(socketPath));+ final conn = connFor(tcp, LocalDaemonTransport(candidate: socketPath)..useSocket());+ addTearDown(conn.close);+ await conn.connect();+ await until(() => unix.selects > 0);++ expect(unix.selects, 1);+ expect(tcp.selects, 0);+ expect(unix.hits, ['/api/local-ws']);+ });++ test('goes back to the socket once it is there again', () async {+ // A dial during a daemon restart fails and drops the transport to the+ // port; the next connect must still find the socket the new daemon made.+ final tcp = await start(_Daemon.tcp());+ final unix = await start(_Daemon.unix(socketPath));+ final transport = LocalDaemonTransport(candidate: socketPath)..useTcp();+ final conn = connFor(tcp, transport);+ addTearDown(conn.close);+ await conn.connect();+ await until(() => unix.selects > 0);++ expect(unix.selects, 1);+ expect(tcp.selects, 0);+ });++ test('falls back to the port when the socket is not there', () async {+ final tcp = await start(_Daemon.tcp());+ final transport = LocalDaemonTransport(candidate: socketPath)..useSocket();+ final conn = connFor(tcp, transport);+ addTearDown(conn.close);+ await conn.connect();+ await until(() => tcp.selects > 0);++ expect(tcp.selects, 1);+ expect(transport.socketPath, isNull);+ });+ });+}