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
CLI: review fixes for the terminal engine
0xken153a0b90669fdd
diff --git a/cli/scripts/remote-command-e2e.mts b/cli/scripts/remote-command-e2e.mtsnew file mode 100644index 000000000..2b08b8adc--- /dev/null+++ b/cli/scripts/remote-command-e2e.mts@@ -0,0 +1,142 @@+// End-to-end check of `harness remote` against a RUNNING daemon, over its loopback WS, standing in for+// the desktop: open a terminal tile on THIS machine, type `harness remote` into it, take the named+// machine in the picker, and watch what the window would see — the `remote_terminal_handoff` push+// naming this tile and the new agent, and `agent_created` on the other machine.+//+// npx tsx scripts/remote-command-e2e.mts <remoteMachineId> [remoteLabel]+// TILE_MACHINE_ID=<id> … the tile lives on THAT machine instead of this one (a hop between two+// relayed boxes: the push must reach a window that is not on the tile's+// machine, which is what `send()` rather than `sendLocal()` is for)+//+// Leaves nothing behind on a pass: both terminals are deleted at the end. Needs the remote machine+// linked here (`harness link list`) — the interactive link is not driven by this script.+import WebSocket from 'ws'+import { randomUUID } from 'node:crypto'+import { inflateSync } from 'node:zlib'+import { encodeTerminalLocal, decodeTerminalLocal, TerminalBinaryKind } from '../src/lib/terminalBinary.ts'+import { readAuthSession } from '../src/lib/authSession.ts'++const remoteMachineId = process.argv[2]+const remoteLabel = process.argv[3] ?? remoteMachineId?.slice(0, 8)+if (!remoteMachineId) throw new Error('remoteMachineId required')+const localMachineId = process.env.TILE_MACHINE_ID ?? readAuthSession()?.machineId+if (!localMachineId) throw new Error('not signed in')+const log = (m: string) => console.log(`[e2e] ${new Date().toISOString().slice(11, 19)} ${m}`)+const fail = (m: string): never => { console.error(`[e2e] FAIL ${m}`); process.exit(1) }+const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms))++class Client {+ ws = new WebSocket('ws://127.0.0.1:18473/api/local-ws')+ frames: Array<Record<string, any>> = []+ output = ''+ private waiters: Array<{ test: (f: Record<string, any>) => boolean; resolve: (f: Record<string, any>) => void }> = []+ constructor(readonly name: string) {+ this.ws.on('close', (code, reason) => log(`${name}: ws closed ${code} ${reason.toString()}`))+ this.ws.on('message', (raw, isBinary) => {+ if (isBinary) {+ const f = decodeTerminalLocal(new Uint8Array(raw as Buffer))+ if (f && (f.kind === TerminalBinaryKind.output || f.kind === TerminalBinaryKind.keyframe)) {+ this.output += (f.compressed ? inflateSync(Buffer.from(f.bytes)) : Buffer.from(f.bytes)).toString('utf8')+ }+ return+ }+ const f = JSON.parse(raw.toString()) as Record<string, any>+ this.frames.push(f)+ for (const w of [...this.waiters]) if (w.test(f)) { this.waiters.splice(this.waiters.indexOf(w), 1); w.resolve(f) }+ })+ }+ send(type: string, payload: Record<string, unknown>): void { this.ws.send(JSON.stringify({ type, payload })) }+ waitFor(test: (f: Record<string, any>) => boolean, ms = 20_000, what = 'frame'): Promise<Record<string, any>> {+ return new Promise((resolve, reject) => {+ const hit = this.frames.find(test)+ if (hit) return resolve(hit)+ const t = setTimeout(() => reject(new Error(`${this.name}: timeout waiting for ${what}`)), ms)+ this.waiters.push({ test, resolve: (f) => { clearTimeout(t); resolve(f) } })+ })+ }+ async rpc(type: string, payload: Record<string, unknown>, ms = 20_000): Promise<Record<string, any>> {+ const requestId = randomUUID()+ this.send(type, { requestId, ...payload })+ const r = await this.waitFor((f) => f.type === `${type}_result` && f.payload?.requestId === requestId, ms, `${type}_result`)+ return r.payload as Record<string, any>+ }+ async select(machineId: string): Promise<void> {+ await new Promise<void>((resolve) => this.ws.on('open', () => resolve()))+ this.send('machine_select', { machineId, localProtocolVersion: 1 })+ await this.waitFor((f) => f.type === 'connected', 20_000, 'connected')+ log(`${this.name}: connected to ${machineId.slice(0, 8)}`)+ }+}++// The window: on this machine, holding the tile `harness remote` is typed in.+const local = new Client('window')+await local.select(localMachineId)+// A second eye on the other machine, for its agent_created.+const remote = new Client('remote')+await remote.select(remoteMachineId)++const created = await local.rpc('agent_create', { engine: 'terminal', bypassPermission: false }, 30_000)+if (created.error) fail(`agent_create → ${created.error} ${created.detail ?? ''}`)+const tileAgentId: string = created.agent.id+log(`tile: terminal agent ${tileAgentId.slice(0, 8)} on ${localMachineId.slice(0, 8)}`)++const openId = randomUUID()+local.send('terminal_open', { requestId: openId, agentId: tileAgentId, cols: 120, rows: 40, protocolVersion: 3 })+const ready = await local.waitFor((f) => (f.type === 'terminal_ready' || f.type === 'terminal_error') && f.payload?.requestId === openId, 15_000, 'terminal_ready')+if (ready.type === 'terminal_error') fail(`terminal_open → ${JSON.stringify(ready.payload)}`)+const streamId: string = ready.payload.streamId+let seq = -1+const type = (text: string) => {+ const frame = encodeTerminalLocal({ kind: TerminalBinaryKind.input, streamId, seq: ++seq, bytes: Buffer.from(text, 'utf8'), compressed: false })+ if (!frame) fail('could not encode input')+ local.ws.send(frame, { binary: true })+}+await sleep(2500) // the shell's prompt++type('harness remote\r')+const until = Date.now() + 20_000+while (Date.now() < until && !local.output.includes('Open a terminal on:')) await sleep(250)+if (!local.output.includes('Open a terminal on:')) fail(`picker did not draw; tail: ${JSON.stringify(local.output.slice(-600))}`)+log('picker drew:\n' + local.output.split('Open a terminal on:')[1].split('\n').slice(0, 10).map((l) => ' ' + l.replace(/\x1b\[[0-9;]*[A-Za-z]/g, '')).join('\n'))+log(`first-terminal hint shown: ${local.output.includes('harness remote') && local.output.includes('pick the machine')}`)+if (!local.output.includes('Online') || !local.output.includes('Offline')) log('note: expected both Online and Offline rows in this account')++// Walk to the wanted row: ↓ until the ❯ line names it, then Enter.+const cursorLine = (): string => {+ const lines = local.output.replace(/\x1b\[[0-9;]*[A-Za-z]/g, '').split('\n')+ return lines.filter((l) => l.includes('❯')).at(-1) ?? ''+}+for (let i = 0; i < 12 && !cursorLine().includes(remoteLabel); i++) { type('\x1b[B'); await sleep(200) }+if (!cursorLine().includes(remoteLabel)) fail(`could not reach ${remoteLabel} in the picker; cursor: ${cursorLine()}`)+log(`cursor on: ${cursorLine().trim()}`)+type('\r')++const handoff = await local.waitFor((f) => f.type === 'remote_terminal_handoff', 60_000, 'remote_terminal_handoff push')+log(`window got remote_terminal_handoff ${JSON.stringify(handoff.payload)}`)+if (handoff.payload.fromAgentId !== tileAgentId) fail(`fromAgentId ${handoff.payload.fromAgentId} is not the tile's ${tileAgentId}`)+if (handoff.payload.machineId !== remoteMachineId) fail(`machineId ${handoff.payload.machineId} is not ${remoteMachineId}`)+const remoteAgentId: string = handoff.payload.agentId+// The other machine lists it (the push may or may not reach a second relay session; the window+// re-asks the list either way, see AppNotifier._awaitAgent).+let row: Record<string, any> | undefined+for (let i = 0; i < 20 && !row; i++) {+ const list = await remote.rpc('agents_list', {})+ row = (list.agents as any[] | undefined)?.find((a) => a.id === remoteAgentId)+ if (!row) await sleep(1000)+}+if (!row) fail('the remote machine does not list the new agent')+const pushed = remote.frames.some((f) => f.type === 'agent_created' && f.payload?.agent?.id === remoteAgentId)+log(`remote lists agent ${remoteAgentId.slice(0, 8)} engine=${row.engine} (agent_created push seen by the second session: ${pushed})`)+if (row.engine !== 'terminal') fail('the remote agent is not a terminal')+await sleep(1500)+const said = local.output.replace(/\x1b\[[0-9;]*[A-Za-z]/g, '')+if (!said.includes('Switching this tile to')) fail(`the command did not say it switched; tail: ${JSON.stringify(said.slice(-400))}`)+log('the command said: ' + said.split('\n').filter((l) => l.includes('✓')).join(' | ').trim())++// What the window then does: end the old shell (the tile is the remote's now). Both go here.+const del = await local.rpc('agent_delete', { agentId: tileAgentId })+if (del.error) fail(`agent_delete (tile) → ${del.error}`)+const delRemote = await remote.rpc('agent_delete', { agentId: remoteAgentId })+if (delRemote.error) fail(`agent_delete (remote) → ${delRemote.error}`)+log('PASS — both terminals deleted')+process.exit(0)diff --git a/cli/src/backendSocket.handoff.spec.ts b/cli/src/backendSocket.handoff.spec.tsnew file mode 100644index 000000000..6bd6ae0a9--- /dev/null+++ b/cli/src/backendSocket.handoff.spec.ts@@ -0,0 +1,73 @@+// remote_terminal_handoff through the socket a local client talks to: `harness remote`, typed in a+// tile, names the tile by its tmux pane; the daemon names the agent and tells every OTHER loopback+// client (the window) to swap the tile over. Loopback in, loopback out.+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { BackendSocket } from './backendSocket.js'+import { terminalHandoffRequest } from './lib/terminalHandoff.js'++describe('remote_terminal_handoff on the local socket', () => {+ let socket: BackendSocket+ let cli: Array<{ type: string; payload: Record<string, unknown> }>+ let window: Array<{ type: string; payload: Record<string, unknown> }>+ beforeEach(() => {+ socket = new BackendSocket('token')+ cli = []+ window = []+ socket.registerLocalClient('local:cli', { sendFrame: (frame) => { cli.push(frame as (typeof cli)[number]); return true }, sendBinary: () => true })+ socket.registerLocalClient('local:window', { sendFrame: (frame) => { window.push(frame as (typeof window)[number]); return true }, sendBinary: () => true })+ socket.onTerminalHandoff = (tmuxPane) => (tmuxPane === '%7' ? 'agent-local-7' : null)+ })+ afterEach(async () => {+ await socket.unregisterLocalClient('local:cli')+ await socket.unregisterLocalClient('local:window')+ await socket.stop()+ })++ const ask = (payload: Record<string, unknown>): void => socket.handleLocalFrame('local:cli', { type: 'remote_terminal_handoff', payload })+ const replies = (): Array<Record<string, unknown>> => cli.filter((frame) => frame.type === 'remote_terminal_handoff_result').map((frame) => frame.payload)++ it('names the tile by its pane, pushes the swap to the other loopback clients, and says how many heard', async () => {+ ask({ requestId: 'h-1', tmuxPane: '%7', machineId: 'machine-b', agentId: 'agent-remote-1' })+ await vi.waitFor(() => expect(replies()).toHaveLength(1))+ expect(replies()[0]).toEqual({ requestId: 'h-1', ok: true, fromAgentId: 'agent-local-7', windows: 1 })+ expect(window.filter((frame) => frame.type === 'remote_terminal_handoff').map((frame) => frame.payload))+ .toEqual([{ fromAgentId: 'agent-local-7', machineId: 'machine-b', agentId: 'agent-remote-1' }])+ })++ it('a pane that is not a Harness tile is refused, and nothing is pushed', async () => {+ ask({ requestId: 'h-2', tmuxPane: '%9', machineId: 'machine-b', agentId: 'agent-remote-1' })+ await vi.waitFor(() => expect(replies()).toHaveLength(1))+ expect(replies()[0]).toMatchObject({ requestId: 'h-2', error: 'NOT_A_HARNESS_PANE' })+ expect(window.some((frame) => frame.type === 'remote_terminal_handoff')).toBe(false)+ })++ it('a malformed request is refused before the registry is asked', async () => {+ const asked = vi.fn(() => 'agent-local-7')+ socket.onTerminalHandoff = asked+ ask({ requestId: 'h-3', tmuxPane: 'not-a-pane', machineId: 'machine-b', agentId: 'agent-remote-1' })+ await vi.waitFor(() => expect(replies()).toHaveLength(1))+ expect(replies()[0]).toMatchObject({ requestId: 'h-3', error: 'INVALID_HANDOFF' })+ expect(asked).not.toHaveBeenCalled()+ })++ it('counts no windows when the CLI is the only loopback client', async () => {+ await socket.unregisterLocalClient('local:window')+ ask({ requestId: 'h-4', tmuxPane: '%7', machineId: 'machine-b', agentId: 'agent-remote-1' })+ await vi.waitFor(() => expect(replies()).toHaveLength(1))+ expect(replies()[0]).toMatchObject({ ok: true, windows: 0 })+ socket.registerLocalClient('local:window', { sendFrame: () => true, sendBinary: () => true })+ })+})++describe('terminalHandoffRequest', () => {+ it('takes a tmux pane id and two bounded ids, nothing else', () => {+ expect(terminalHandoffRequest({ tmuxPane: '%0', machineId: 'm-1', agentId: 'a_1' })).toEqual({ tmuxPane: '%0', machineId: 'm-1', agentId: 'a_1' })+ for (const bad of [+ { tmuxPane: '0', machineId: 'm', agentId: 'a' },+ { tmuxPane: '%1234567890', machineId: 'm', agentId: 'a' },+ { tmuxPane: '%1', machineId: '../m', agentId: 'a' },+ { tmuxPane: '%1', machineId: 'm', agentId: '' },+ { tmuxPane: '%1', machineId: 'm' },+ ]) expect(terminalHandoffRequest(bad), JSON.stringify(bad)).toBeNull()+ })+})diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.tsindex cbc5e250b..a09ab5630 100644--- a/cli/src/backendSocket.ts+++ b/cli/src/backendSocket.ts@@ -53,6 +53,7 @@ import { DSH_ID_RE } from './dsh/manifest.js'import { refreshDshRegistry } from './dsh/catalog.js'import type { DshInstallProgress } from './dsh/install.js'import { dshInstallReply, dshInstallRequest, dshInstallStatus, dshListRows, dshRemoveId, dshRemoveReply } from './dsh/wire.js'+import { terminalHandoffRequest } from './lib/terminalHandoff.js'import { routeVoiceTask } from './lib/voiceRouter.js'import { tailFile } from './lib/sessions.js'import { messagesToEvents, windowRawLines, subagentStatsFromRawLines, type SessionEvent } from './lib/normalize.js'@@ -401,6 +402,8 @@ export class BackendSocket {Promise<{ ok: true; id: string } | { ok: false; error: string; detail: string }>) | null = null/** Called on `dsh_remove` — cli.ts uninstalls the harness from this machine. */onDshRemove: ((id: string) => { ok: true } | { ok: false; error: string; detail: string }) | null = null+ /** Called on `remote_terminal_handoff` — cli.ts names the agent whose tile is that tmux pane, or null. */+ onTerminalHandoff: ((tmuxPane: string) => string | null) | null = null/** What the daemon knows about an agent's DSH companions (viewer URL, verdict); null when nothing. */harnessSharing: HarnessShareOwner | null = nulldshFrameProvider: ((session: RegisteredSession) => AgentDshContext | null) | null = null@@ -1718,6 +1721,27 @@ export class BackendSocket {return}+ case 'remote_terminal_handoff': {+ // `harness remote`, typed INSIDE one of this machine's terminal tiles, opened a terminal on+ // another machine and asks the window showing the tile to swap it over: the tile it was+ // typed in (named by its tmux pane, the one fact the shell has about itself) becomes the new+ // agent's, and the old shell is ended by the window. Asked over loopback only (the command+ // runs on this machine), but PUSHED to every audience: the window showing a tile of this+ // machine may be on another computer, reached through the relay — nothing in the payload+ // but ids, so it travels plain like dsh_install_status.+ if (!this.localClients.has(connId)) { reply(type, requestId, { error: 'UNSUPPORTED' }); return }+ const handoff = terminalHandoffRequest(payload)+ if (!handoff) { reply(type, requestId, { error: 'INVALID_HANDOFF', detail: 'remote_terminal_handoff needs tmuxPane (%N), machineId and agentId' }); return }+ const fromAgentId = this.onTerminalHandoff?.(handoff.tmuxPane) ?? null+ if (!fromAgentId) { reply(type, requestId, { error: 'NOT_A_HARNESS_PANE', detail: `${handoff.tmuxPane} is not a Harness terminal on this machine` }); return }+ // Who could hear it: other loopback clients (a window on this computer) and the web audience+ // (a window elsewhere, relayed). None means nobody is here to swap the tile.+ const windows = [...this.localClients.keys()].filter((id) => id !== connId).length + this.commanderCount+ this.send({ type: 'remote_terminal_handoff', payload: { fromAgentId, machineId: handoff.machineId, agentId: handoff.agentId } })+ reply(type, requestId, { ok: true, fromAgentId, windows })+ return+ }+case 'dsh_update': {if (!this.onDshUpdate) { reply(type, requestId, { error: 'UNSUPPORTED_ON_REMOTE' }); return }const id = dshRemoveId(payload)diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex bd6b8873f..abd392dcc 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -47,7 +47,7 @@ import { registry, projectDisplayName, type RegisteredSession } from './lib/regiimport { engineSessionTitle } from './lib/sessionTitle.js'import { installAmpPlugin, installCodexHooks, installCommandCodeHooks, installCursorHooks, installDevinHooks, installGrokHooks, installAgyHooks, installCopilotHooks, installHermesHooks, installKiloPlugin, installOpencodePlugin, installPiExtension, installSessionHooks } from './lib/hooks.js'import { installOpencodeHarnessComputeSkill } from './lib/harnessComputeSkill.js'-import { PID_FILE, daemonPort, isAlive, readPid } from './lib/daemonState.js'+import { PID_FILE, daemonPort, isAlive, isDaemonRunning, readPid } from './lib/daemonState.js'import {BIND_WAIT_MS, connectFailure, defaultLaunchDeps, removePidFileIf, waitForBind, waitForReady,} from './lib/daemonLaunch.js'@@ -116,6 +116,7 @@ import { TerminalStreamManager } from './lib/terminalStreamManager.js'import { terminalRouteKey, terminalRuntimeLabel } from './lib/terminalRuntime.js'import { TerminalAgentReconciler } from './lib/terminalAgentReconciler.js'import { processRows, type DiscoveredTerminalAgent } from './lib/terminalAgentDiscovery.js'+import { remoteCommand } from './remoteCommand.js'import {terminalActionNotStarted,type HookTerminalHint,@@ -200,7 +201,6 @@ import { RuntimeProfileManager, parseRuntimeProfile } from './lib/runtimeProfileimport { RuntimeProfileController, inspectRuntimePane } from './lib/runtimeProfileController.js'import { deviceErrorText } from './lib/deviceErrors.js'import { correlateAgentEvent, turnHeartbeatFrame } from './lib/agentEvent.js'-// Before ANY child is spawned: on Linux an absent locale makes tmux and ps mangle their output,// which silently costs the daemon every pane it would have discovered. See lib/childLocale.ts.ensureUtf8Locale()@@ -209,6 +209,9 @@ import {prepareLogFile, trimLogFile, LOG_CHECK_INTERVAL_MS,} from './lib/log.js'+/** Written once the first terminal on this machine has said how `harness remote` works (engineLaunch.ts). */+const TERMINAL_HINT_MARKER = join(env.ADAPTER_DATA_DIR, 'terminal-remote-hint-shown')+// Claude's Stop hook fires when the agent finishes, but the transcript can lag a moment behind// (docs: "the transcript file may lag behind the in-memory conversation"). Acting immediately races// that flush → an empty recap + a premature close. So the Stop hook is a DELAYED fallback: poll, and@@ -314,6 +317,7 @@ Machine:harness logs export zip the last 7 days of logs (app, CLI, dial, daemon) to the Desktopharness machines list the machines on this account (this computer's is marked)harness machines delete <id> remove ANOTHER machine (refuses this one; use \`harness logout\`)+ harness remote from a Harness terminal tile: open a terminal on another machine and switch to itharness version print the installed version (v${VERSION})harness update [--force] update to the latest build now (it also self-updates in the background;neither touches a local install-cli.sh build without --force)@@ -2231,6 +2235,10 @@ async function runForeground(session: AuthSession): Promise<void> {backend.runtimeProfileProvider = (session) => runtimeProfiles.selectedModel(session)backend.dshFrameProvider = dshFrameContextbackend.onDshRemove = (id) => removeDsh(id)+ // `harness remote` names the tile it was typed in by its tmux pane; the registry knows whose it is.+ backend.onTerminalHandoff = (tmuxPane) => registry.advertised()+ .find((session) => session.tmuxPane === tmuxPane+ || session.runtimes.some((runtime) => runtime.backend === 'tmux' && runtime.paneId === tmuxPane))?.agentId ?? nullbackend.onDshInstall = (input, progress) => mutateDsh(input, progress)backend.onDshUpdate = (id, progress) => mutateDsh({ id, update: true }, progress)backend.onAgentRename = (session, name) => { void terminals.setTitle(session, name) }@@ -2697,7 +2705,9 @@ async function runForeground(session: AuthSession): Promise<void> {// The live argv is the truth about the bypass flag, and this is the one place every running// agent passes through — so a row written before the flag was persisted at all (or by a build// that did not yet) learns it here, before any pane recreation ever needs it.- registry.setBypassPermission(current.agentId, bypassPermissionActive(current.engine, observed.args))+ // `observed.engine`, not `current.engine`: for a terminal that just adopted one, the row's+ // engine was `terminal` a line ago, which has no bypass flag and would read every launch as "no".+ registry.setBypassPermission(current.agentId, bypassPermissionActive(observed.engine, observed.args))// Same idea for a Codex profile: a row that never learned which CODEX_HOME its process runs// under learns it from the process, before the hook path validates a transcript against it.// Fill-only — a profile the row already knows is never re-derived.@@ -3763,6 +3773,7 @@ async function runForeground(session: AuthSession): Promise<void> {const { env: launchEnv, extraArgs, clearEnv } = built.overridesconst argv = buildEngineLaunchArgv(entry.engine, {...opts,+ terminalHintMarker: TERMINAL_HINT_MARKER,bypassPermission: entry.bypassPermission === true,...(entry.permissionMode ? { permissionMode: entry.permissionMode } : {}),installIfMissing: enginePathOverride(entry.engine) ? undefined : engineInstallRecipe(entry.engine),@@ -4052,7 +4063,7 @@ async function runForeground(session: AuthSession): Promise<void> {const extraArgs = [...(gridLaunch?.args ?? []), ...dshArgs, ...(agent ? namedAgentArgs(engine, agent) : [])]// The first prompt is a launch option only — never part of `extraArgs`, which the registry row// carries into a relaunch (engineLaunch.ts, `firstPrompt`).- const launchOptions = { bypassPermission, ...(permissionMode ? { permissionMode } : {}), extraArgs: extraArgs.length ? extraArgs : undefined, installIfMissing, clearEnv, cwd, harnessNode: dsh ? true : undefined, ...(prompt ? { firstPrompt: prompt } : {}) }+ const launchOptions = { bypassPermission, ...(permissionMode ? { permissionMode } : {}), extraArgs: extraArgs.length ? extraArgs : undefined, installIfMissing, clearEnv, cwd, harnessNode: dsh ? true : undefined, ...(prompt ? { firstPrompt: prompt } : {}), terminalHintMarker: TERMINAL_HINT_MARKER }const command = buildEngineCommandArgv(engine, launchOptions)const argv = buildEngineLaunchArgv(engine, launchOptions)// A tmux route is enough to stream its screen. Register it before looking for a process so both@@ -4472,7 +4483,7 @@ async function runForeground(session: AuthSession): Promise<void> {if (tmuxBackend) {const runtimes = s.runtimes.filter((runtime): runtime is TmuxRuntimeRef => runtime.backend === 'tmux')void Promise.all(runtimes.map((runtime) => tmuxBackend.kill(runtime))).then(() => {- console.log(`[delete] ${sid(sessionId)} terminal · pane closed`)+ console.log(`[delete] ${sid(sessionId)} ${s.engine} · pane closed`)if (isTerminalEngine(s.engine)) clearDeleted(sessionId)void agentReconciler.trigger()}).catch((err) => {@@ -5722,6 +5733,36 @@ async function linkConnectCommand(machineId: string | undefined, stdin: boolean,process.exit(0)}+/**+ * The link itself, as `harness link connect` and `harness remote` both do it: this computer's SSO+ * token and identity, the remote password proved against THAT machine, and its peer pinned here.+ */+async function linkMachineWithPassword(machineId: string, password: string, displayName?: string): Promise<{ ok: true; fingerprint: string } | { ok: false; error: string; message: string }> {+ const session = readAuthSession()+ if (!session) return { ok: false, error: 'NOT_SIGNED_IN', message: 'Not signed in. Run: harness login' }+ const auth = new AuthSessionManager(backendHttpBase())+ let accessToken: string+ try {+ accessToken = await auth.accessToken()+ } catch (err) {+ const detail = err instanceof Error ? err.message : String(err)+ return { ok: false, error: 'AUTH_FAILED', message: `Could not refresh this computer's SSO session (${detail}). Run: harness login` }+ }+ const store = new E2eeStore()+ store.init()+ const result = await connectWithPassword({+ targetMachineId: machineId,+ password,+ selfIdentity: store.getIdentity(),+ accessToken,+ backendWsBase: env.BACKEND_WS_URL.replace(/\/$/, ''),+ autonomousEnv: session.autonomousEnv,+ })+ if (!result.ok) return { ok: false, error: result.error, message: humanizeLinkError(result.error, displayName || machineId, result.retryAt) }+ new MachinePeerStore().pin(machineId, b64e(result.peerPub), 'harness link', Date.now())+ return { ok: true, fingerprint: result.fingerprint }+}+/** `harness link list` — machines this one has linked (CLI-to-CLI/machine-node trust, not browsers). */async function linkListCommand(): Promise<void> {const peers = new MachinePeerStore().list()@@ -6010,6 +6051,29 @@ switch (cmd) {.then((code) => { process.exitCode = code }).catch(onError)break+ case 'remote':+ remoteCommand({+ tmuxPane: process.env.TMUX_PANE,+ localMachineId: readAuthSession()?.machineId ?? null,+ port: daemonPort(),+ daemonRunning: isDaemonRunning,+ listMachines: async () => {+ const { session, headers } = await controlPlaneAuth()+ return (await fetchMachines(headers)).map((machine) => ({+ machineId: machine.machineId,+ label: machineLabel(machine),+ status: machine.status || 'unknown',+ current: machine.machineId === session.machineId,+ }))+ },+ isLinked: (machineId) => new MachinePeerStore().get(machineId) !== null,+ link: (machineId, password) => linkMachineWithPassword(machineId, password),+ promptPassword,+ input: process.stdin,+ output: process.stdout,+ error: (line) => console.error(line),+ }).then((code) => { process.exitCode = code }).catch(onError)+ breakcase 'machines':if (!args[0]) machinesListCommand(flags.includes('--json')).catch(onError)else if (args[0] === 'list') machinesListCommand(flags.includes('--json')).catch(onError)diff --git a/cli/src/device/deviceFleet.spec.ts b/cli/src/device/deviceFleet.spec.tsindex 6818348f0..9d253eefe 100644--- a/cli/src/device/deviceFleet.spec.ts+++ b/cli/src/device/deviceFleet.spec.ts@@ -46,6 +46,16 @@ function make(over: { rows?: Partial<Listed>[]; linked?: string[]; rpc?: (t: str}describe('DeviceFleet', () => {+ it('never lists another machine\'s terminal to the dial — the far daemon answers as to an app', async () => {+ const { fleet } = make({+ rpc: async () => ({ agents: [+ { id: 't1', name: 'Terminal 1', engine: 'terminal' },+ { id: 'c1', name: 'Claude 1', engine: 'claude' },+ ] }),+ })+ expect((await fleet.listAgents('m1')).map((a) => a.id)).toEqual(['c1'])+ })+it('throws away the E2EE session after two missed round trips, and keeps the last verdict', async () => {// THE FAILURE THIS EXISTS FOR IS SILENT AND PERMANENT. A session outlives the machine that agreed to// it: establish() returns instantly for anything in the map, so once the far end stops answering,diff --git a/cli/src/device/deviceFleet.ts b/cli/src/device/deviceFleet.tsindex ba1c01420..5190b45e2 100644--- a/cli/src/device/deviceFleet.ts+++ b/cli/src/device/deviceFleet.ts@@ -4,6 +4,7 @@// The split is deliberate and load-bearing. The LIST costs an HTTP read and works signed-in-but-offline;// the LANE costs a cloud socket and only exists while the user is actually looking at another machine. A// dial parked on the local machine — which is where it sits most of the time — holds no socket at all.+import { isTerminalEngine } from '../engines/types.js'import { FleetError, type FleetEvent, type FleetMachine, type MachineFleet } from '../cable/machineFleet.js'import type { CableAgent } from '../cable/cableSession.js'import type { RecentTurn } from '../cable/cableHost.js'@@ -162,7 +163,11 @@ export class DeviceFleet implements MachineFleet {async listAgents(machineId: string): Promise<CableAgent[]> {const res = await this.rpc(machineId, 'agents_list', {})const raw = Array.isArray(res.agents) ? res.agents : []- return raw.map(toCableAgent).filter((a) => a.id)+ // This asks the far daemon as an ordinary client, so its answer is the app's list, terminals+ // included — and the dial drives agents only, the same rule its own machine's list keeps+ // (`deviceAgentRow`, `cableHost.localAgents`). A far daemon too old to know the engine sends+ // none, which is the same thing.+ return raw.map(toCableAgent).filter((a) => a.id && !isTerminalEngine(a.engine))}/**diff --git a/cli/src/lib/engineLaunch.spec.ts b/cli/src/lib/engineLaunch.spec.tsindex a71df81d3..5a9870e7f 100644--- a/cli/src/lib/engineLaunch.spec.ts+++ b/cli/src/lib/engineLaunch.spec.ts@@ -1,5 +1,5 @@import { afterAll, afterEach, beforeEach, describe, expect, it } from 'vitest'-import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'+import { chmodSync, existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'import { execFileSync } from 'node:child_process'import { tmpdir } from 'node:os'import { join } from 'node:path'@@ -12,6 +12,7 @@ import {NAMED_AGENT_ARGS,NamedAgentUnsupportedError,PERMISSION_MODES,+ TERMINAL_HINT_LINES,buildEngineCommandArgv,buildEngineLaunchArgv,commandAvailableInInteractiveShell,@@ -91,7 +92,7 @@ describe('buildEngineLaunchArgv', () => {})it('marks the pane with the exit status through the daemon\'s own tmux, and only then hands over a shell', () => {const prelude = engineFallbackPrelude('codex', '/bin/bash', '/opt/homebrew/bin/tmux')- expect(prelude).toContain(`'/opt/homebrew/bin/tmux' set-option -p -t "$TMUX_PANE" @harness_engine_exit "$harness_status"`)+ expect(prelude).toContain(`[ -n "\${TMUX_PANE:-}" ] && '/opt/homebrew/bin/tmux' set-option -p -t "$TMUX_PANE" @harness_engine_exit "$harness_status"`)expect(prelude.indexOf('set-option')).toBeLessThan(prelude.indexOf("exec '/bin/bash'"))expect(prelude).toContain('if [ "$harness_status" -eq 127 ]; then exit 127; fi')// zsh is a login shell; bash keeps its interactive rc (same rule as a terminal).@@ -105,20 +106,20 @@ describe('buildEngineLaunchArgv', () => {it('is the login shell itself behind a non-interactive wrapper that only raises the limit and enters the folder', () => {expect(buildEngineLaunchArgv('terminal', { cwd: '/work/project' }, '/bin/zsh')).toEqual(['/bin/zsh', '-c',- `${RAISE_OPEN_FILES_SH}if ! cd -- "$1"; then printf '%s\\n' 'harness: the selected working directory is unavailable.' >&2; fi\nshift\nexec "$@"`,- 'harness-terminal', '/work/project', '/bin/zsh', '-l',+ `${RAISE_OPEN_FILES_SH}if ! cd -- "$1"; then printf '%s\\n' 'harness: the selected working directory is unavailable.' >&2; fi\nshift 2\nexec "$@"`,+ 'harness-terminal', '/work/project', '', '/bin/zsh', '-l',])})it('gives bash no login flag (its rc file is where Ubuntu keeps PATH edits), and no folder means no cd', () => {expect(buildEngineLaunchArgv('terminal', {}, '/bin/bash')).toEqual([- '/bin/bash', '-c', `${RAISE_OPEN_FILES_SH}shift\nexec "$@"`, 'harness-terminal', '', '/bin/bash',+ '/bin/bash', '-c', `${RAISE_OPEN_FILES_SH}shift 2\nexec "$@"`, 'harness-terminal', '', '', '/bin/bash',])})it('falls back to /bin/sh rather than to an engine command when no shell resolves', () => {expect(buildEngineLaunchArgv('terminal', {}, 'relative-shell')).toEqual([- '/bin/sh', '-c', `${RAISE_OPEN_FILES_SH}shift\nexec "$@"`, 'harness-terminal', '', '/bin/sh',+ '/bin/sh', '-c', `${RAISE_OPEN_FILES_SH}shift 2\nexec "$@"`, 'harness-terminal', '', '', '/bin/sh',])})@@ -136,9 +137,31 @@ describe('buildEngineLaunchArgv', () => {expect(() => execFileSync('/bin/sh', ['-n', '-c', script])).not.toThrow()// The wrapper's `exec "$@"` runs the shell handed in argv; `true` in its place proves the// wrapper reaches the exec even when the cd failed (the terminal still opens, at $HOME).- const out = execFileSync('/bin/sh', ['-c', script, 'harness-terminal', '/nowhere/at/all', '/bin/sh', '-c', 'echo reached'], { stdio: ['ignore', 'pipe', 'pipe'] })+ const out = execFileSync('/bin/sh', ['-c', script, 'harness-terminal', '/nowhere/at/all', '', '/bin/sh', '-c', 'echo reached'], { stdio: ['ignore', 'pipe', 'pipe'] })expect(out.toString()).toContain('reached')})++ it('says how `harness remote` works before the first prompt on a machine, and never again', () => {+ const dir = mkdtempSync(join(tmpdir(), 'terminal-hint-'))+ const marker = join(dir, 'shown')+ const argv = buildEngineLaunchArgv('terminal', { terminalHintMarker: marker }, '/bin/sh')+ expect(argv.slice(4, 6)).toEqual(['', marker])+ expect(() => execFileSync('/bin/sh', ['-n', '-c', argv[2]])).not.toThrow()+ const run = (): string => execFileSync('/bin/sh', ['-c', argv[2], 'harness-terminal', '', marker, '/bin/sh', '-c', 'echo prompt'], { stdio: ['ignore', 'pipe', 'pipe'] }).toString()+ const first = run()+ for (const line of TERMINAL_HINT_LINES) expect(first).toContain(line)+ expect(first.trim().endsWith('prompt')).toBe(true)+ expect(existsSync(marker)).toBe(true)+ const second = run()+ expect(second).not.toContain('harness remote')+ expect(second.trim()).toBe('prompt')+ rmSync(dir, { recursive: true, force: true })+ })++ it('with no marker named (a test, an older caller) there is no hint', () => {+ const script = buildEngineLaunchArgv('terminal', {}, '/bin/sh')[2]+ expect(script).not.toContain('harness remote')+ })})it('hands the engine a soft open-files limit fit for it, however low the pane started', async () => {diff --git a/cli/src/lib/engineLaunch.ts b/cli/src/lib/engineLaunch.tsindex a0d029274..e7b035586 100644--- a/cli/src/lib/engineLaunch.ts+++ b/cli/src/lib/engineLaunch.ts@@ -206,6 +206,12 @@ export interface LaunchCommandOptions {* what the user typed.*/firstPrompt?: string+ /**+ * Terminal only: a file whose absence means this machine has not yet been told about+ * `harness remote`; the shell prints the hint before its prompt and writes the file. The daemon+ * names one under its data dir; a test names none and gets no hint.+ */+ terminalHintMarker?: string/*** Extra argv the caller has already composed, appended last.*@@ -423,8 +429,10 @@ export function buildEngineLaunchArgv(*/export function engineFallbackPrelude(engine: AgentEngine, shellPath: string, tmuxBinary: string | null): string {const loginArgs = basename(shellPath).toLowerCase() === 'zsh' ? ' -l' : ''+ // Named by the command a person would type (`cursor-agent`, `cmd`), not the engine id.+ const command = basename(engineBin(engine)) || engineconst mark = tmuxBinary && isAbsolute(tmuxBinary)- ? ` [ -n "$TMUX_PANE" ] && ${shellSingleQuote(tmuxBinary)} set-option -p -t "$TMUX_PANE" ${ENGINE_EXIT_PANE_OPTION} "$harness_status" >/dev/null 2>&1 || true\n`+ ? ` [ -n "\${TMUX_PANE:-}" ] && ${shellSingleQuote(tmuxBinary)} set-option -p -t "$TMUX_PANE" ${ENGINE_EXIT_PANE_OPTION} "$harness_status" >/dev/null 2>&1 || true\n`: ''return 'harness_engine() {\n'+ ' harness_status=0\n'@@ -434,7 +442,7 @@ export function engineFallbackPrelude(engine: AgentEngine, shellPath: string, tm// Only a pane — something with a terminal on stdin — gets a shell to type into. Run without one// (a spec exercising the script, a wrapper piped somewhere) the engine's own status is the answer.+ ' if ! [ -t 0 ]; then exit "$harness_status"; fi\n'- + ` printf '\\n%s\\n' ${shellSingleQuote(`harness: ${engine} exited ($harness_status). This pane is a shell now — run ${engine} again, or stop the pane.`).replace('($harness_status)', `('"$harness_status"')`)}\n`+ + ` printf '\\n%s\\n' ${shellSingleQuote(`harness: ${command} exited ($harness_status). This pane is a shell now — run ${command} again, or stop the pane.`).replace('($harness_status)', `('"$harness_status"')`)}\n`+ ` exec ${shellSingleQuote(shellPath)}${loginArgs}\n`+ '}\n'}@@ -451,8 +459,19 @@ export function engineFallbackPrelude(engine: AgentEngine, shellPath: string, tm* `interactiveEngineShell`). Without a resolvable shell the pane runs `/bin/sh`, which at least* gives the person a prompt.*/+/**+ * What the first terminal on a machine says before its prompt — once, ever: the marker file names+ * the machine as told. Only a tile can act on it (`harness remote` swaps the tile it is typed in),+ * and a tile is where every terminal the daemon opens lives.+ */+export const TERMINAL_HINT_LINES = [+ 'harness: a terminal on this machine. To open one on another of your machines, type',+ 'harness: harness remote',+ 'harness: pick the machine, and this tile switches to it.',+] as const+export function buildTerminalLaunchArgv(- opts: Pick<LaunchCommandOptions, 'cwd'> = {},+ opts: Pick<LaunchCommandOptions, 'cwd' | 'terminalHintMarker'> = {},shell: string | undefined = undefined,): string[] {const candidate = shell === undefined ? currentUserShell() : shell@@ -461,7 +480,13 @@ export function buildTerminalLaunchArgv(const cwdPrelude = opts.cwd? `if ! cd -- "$1"; then printf '%s\\n' 'harness: the selected working directory is unavailable.' >&2; fi\n`: ''- return [path, '-c', RAISE_OPEN_FILES_SH + cwdPrelude + 'shift\nexec "$@"', 'harness-terminal', opts.cwd ?? '', path, ...loginArgs]+ // `$2` is the marker: absent, the hint is printed and the marker written, so it is said once per+ // machine. Written with `:>` rather than touch, so nothing outside the shell is needed; a folder+ // that cannot be written just says it again next time.+ const hintPrelude = opts.terminalHintMarker+ ? `if [ -n "$2" ] && [ ! -e "$2" ]; then printf '%s\\n' ${TERMINAL_HINT_LINES.map(shellSingleQuote).join(' ')} ''; : > "$2" 2>/dev/null || true; fi\n`+ : ''+ return [path, '-c', RAISE_OPEN_FILES_SH + cwdPrelude + hintPrelude + 'shift 2\nexec "$@"', 'harness-terminal', opts.cwd ?? '', opts.terminalHintMarker ?? '', path, ...loginArgs]}/**diff --git a/cli/src/lib/registry.spec.ts b/cli/src/lib/registry.spec.tsindex e63a6083c..d38cc53dd 100644--- a/cli/src/lib/registry.spec.ts+++ b/cli/src/lib/registry.spec.ts@@ -1644,8 +1644,9 @@ describe('a terminal: a pane that becomes an engine and back', () => {const released = registry.releaseEngine(opened.agentId)!expect(released.agentId).toBe(opened.agentId)- expect(released).toMatchObject({ engine: 'terminal', terminalHost: true, active: true, launch: { state: 'ready' }, sessionId: '', processIdentity: null, transcriptPath: null })- expect(released.bypassPermission).toBeUndefined()+ expect(released).toMatchObject({ engine: 'terminal', terminalHost: true, active: true, launch: { state: 'ready' }, sessionId: '', processIdentity: null, transcriptPath: null, grid: null, model: null })+ // The pane's launch shape survives the engine: the same flags come back with the next launch.+ expect(released.bypassPermission).toBe(true)expect(registry.bySession('session-r')).toBeUndefined()expect(registry.byProcess('claude', processIdentity(912))).toBeUndefined()expect(registry.byRuntimeTerminal(pane)?.agentId).toBe(opened.agentId)diff --git a/cli/src/lib/registry.ts b/cli/src/lib/registry.tsindex 13057fcc0..ef63b38b0 100644--- a/cli/src/lib/registry.ts+++ b/cli/src/lib/registry.ts@@ -1429,12 +1429,18 @@ class Registry {** For every agent, not only one that began as a terminal — an engine the app launched runs* inside its pane's shell too (engineLaunch.ts `harness_engine`), and `/exit` or Ctrl-C leaves- * that shell at its prompt with the engine's last screen above it. Everything that belonged to- * the engine goes — session, transcript, process, grid, profile, model, permission choices —- * because the next thing typed into this shell may be a different engine, and `unboundRouteOwner`- * only claims a route for a row with no session. The row itself, its id, its pane and its name- * stay: this is the opposite of dormant, the terminal is live. `terminalHost` is set from here on,- * since that is what the pane now is.+ * that shell at its prompt with the engine's last screen above it.+ *+ * What goes is what described the PROCESS and its session — session id, transcript, pid,+ * gateway, grid assignment, model, title — because the next thing typed into this shell may be a+ * different engine, and `unboundRouteOwner` only claims a route for a row with no session. What+ * stays is what describes the PANE's launch — `gridLaunch`, `codexHome`, `dsh`, `agent`, the+ * permission choice: the tmux session's environment still carries the grid endpoint and the+ * Codex profile, the workspace is still that harness's, and a restart or a relaunch after a+ * reboot puts the same engine back with the same shape. Dropping `gridLaunch` in particular made+ * a released grid agent unrestorable ("credential not persisted"). The row itself, its id, its+ * pane and its name stay: this is the opposite of dormant, the terminal is live. `terminalHost`+ * is set from here on, since that is what the pane now is.*/releaseEngine(agentId: string): RegisteredSession | null {const entry = this.agents.get(agentId)@@ -1448,16 +1454,9 @@ class Registry {entry.active = trueentry.gateway = nullentry.grid = null- entry.gridLaunch = null- entry.gridWebSearch = nullentry.subscriptionModel = null- entry.codexHome = null- entry.dsh = null- entry.agent = nullentry.model = nullentry.title = null- delete entry.bypassPermission- delete entry.permissionModeentry.updatedAt = Date.now()this.index(entry)this.terminalAvailableAgents.add(entry.agentId)diff --git a/cli/src/lib/remoteRelay.spec.ts b/cli/src/lib/remoteRelay.spec.tsindex d918acaf6..4859e0949 100644--- a/cli/src/lib/remoteRelay.spec.ts+++ b/cli/src/lib/remoteRelay.spec.ts@@ -541,3 +541,77 @@ describe('RemoteRelayPool sendBinary backpressure handling', () => {expect(demoteP2p).not.toHaveBeenCalled()})})++describe('RemoteRelayPool shares one upstream between every local client selected onto a machine', () => {+ // `acquire` on an entry that already exists never dials: it attaches. So the pool is seeded with an+ // entry the way a completed dial leaves one, and acquire/detach are driven from there.+ function poolWithEntry() {+ const pool = new RemoteRelayPool(+ { accessToken: async () => 'unused' } as never,+ 'ws://unused',+ { pub: new Uint8Array(), priv: new Uint8Array() } as never,+ { pin: () => {}, get: () => null } as never,+ )+ const entry = fakeEntry({ attached: new Set(), sink: null, ws: { send: vi.fn(), close: vi.fn() }, viewers: { reset: vi.fn(), close: vi.fn() } }) as unknown as {+ attached: Set<unknown>+ sink: { sendFrame: (frame: unknown) => boolean; sendBinary: (frame: Uint8Array) => boolean } | null+ onClosed: ((code: number, reason: string) => void) | null+ lingerTimer: ReturnType<typeof setTimeout> | null+ viewers: { reset: ReturnType<typeof vi.fn>; close: ReturnType<typeof vi.fn> }+ }+ ;(pool as unknown as { entries: Map<string, unknown> }).entries.set('m1', entry)+ return { pool, entry }+ }+ const sink = () => ({ sendFrame: vi.fn(() => true), sendBinary: vi.fn(() => true) })++ it('a second client joins the first, both get every frame, and detaching one leaves the other on', async () => {+ const { pool, entry } = poolWithEntry()+ const desktop = sink()+ const cli = sink()+ const desktopClosed = vi.fn()+ const cliClosed = vi.fn()+ const a = await pool.acquire('m1', 'env', { type: 'machine_select', payload: {} }, desktop, desktopClosed)+ const b = await pool.acquire('m1', 'env', { type: 'machine_select', payload: {} }, cli, cliClosed)+ expect(desktop.sendFrame).toHaveBeenCalledWith({ type: 'connected', payload: { machineId: 'm1', e2ee: false } })+ expect(cli.sendFrame).toHaveBeenCalledWith({ type: 'connected', payload: { machineId: 'm1', e2ee: false } })++ // What the machine sends comes to both.+ entry.sink!.sendFrame({ type: 'agent_created', payload: {} })+ expect(desktop.sendFrame).toHaveBeenLastCalledWith({ type: 'agent_created', payload: {} })+ expect(cli.sendFrame).toHaveBeenLastCalledWith({ type: 'agent_created', payload: {} })++ // The CLI leaves: the desktop is still attached, still hears, and nothing lingers or resets.+ b.detach()+ expect(entry.attached.size).toBe(1)+ expect(entry.lingerTimer).toBeNull()+ expect(entry.viewers.reset).not.toHaveBeenCalled()+ entry.sink!.sendFrame({ type: 'agent_deleted', payload: {} })+ expect(desktop.sendFrame).toHaveBeenLastCalledWith({ type: 'agent_deleted', payload: {} })+ expect(cli.sendFrame).not.toHaveBeenCalledWith({ type: 'agent_deleted', payload: {} })++ // A close from upstream reaches the one still attached.+ entry.onClosed!(1006, 'gone')+ expect(desktopClosed).toHaveBeenCalledWith(1006, 'gone')+ expect(cliClosed).not.toHaveBeenCalled()++ // The last one leaving is what starts the linger.+ a.detach()+ expect(entry.attached.size).toBe(0)+ expect(entry.sink).toBeNull()+ expect(entry.lingerTimer).not.toBeNull()+ expect(entry.viewers.reset).toHaveBeenCalled()+ clearTimeout(entry.lingerTimer!)+ })++ it('a client whose socket refuses a frame is dropped; the rest keep receiving', async () => {+ const { pool, entry } = poolWithEntry()+ const live = sink()+ const dead = { sendFrame: vi.fn(() => false), sendBinary: vi.fn(() => false) }+ await pool.acquire('m1', 'env', { type: 'machine_select', payload: {} }, live, vi.fn())+ await pool.acquire('m1', 'env', { type: 'machine_select', payload: {} }, dead, vi.fn())+ expect(entry.sink!.sendFrame({ type: 'x', payload: {} })).toBe(true)+ expect(entry.attached.size).toBe(1)+ expect(entry.sink!.sendBinary(new Uint8Array([1]))).toBe(true)+ expect(live.sendBinary).toHaveBeenCalled()+ })+})diff --git a/cli/src/lib/remoteRelay.ts b/cli/src/lib/remoteRelay.tsindex 94c300ec1..0380059fd 100644--- a/cli/src/lib/remoteRelay.ts+++ b/cli/src/lib/remoteRelay.ts@@ -90,10 +90,52 @@ function binaryBytes(raw: RawData): Uint8Array {return new Uint8Array()}+/** One local client attached to a pooled upstream: where its frames go, and what to tell it on close. */+interface AttachedClient {+ sink: LocalClientSink+ onClosed: (code: number, reason: string) => void+}++/**+ * `entry.sink` / `entry.onClosed` as the fan-out over what is attached: a frame reaches every client,+ * a client whose socket refuses it is dropped, and a close is told to each. Null when nobody is+ * attached — which is what the linger and the viewer proxy already key on.+ */+function bindAttached(entry: Entry): void {+ const clients = entry.attached+ if (clients.size === 0) { entry.sink = null; entry.onClosed = null; return }+ entry.sink = {+ sendFrame: (frame) => {+ let delivered = false+ for (const client of [...clients]) {+ if (client.sink.sendFrame(frame)) delivered = true+ else clients.delete(client)+ }+ return delivered+ },+ sendBinary: (frame) => {+ let delivered = false+ for (const client of [...clients]) {+ if (client.sink.sendBinary(frame)) delivered = true+ else clients.delete(client)+ }+ return delivered+ },+ }+ entry.onClosed = (code, reason) => { for (const client of [...clients]) client.onClosed(code, reason) }+}+interface Entry {viewers?: RemoteViewerProxyws: WebSocketcrypto: RelaySessionCrypto+ /**+ * Every local client selected onto this machine right now. ONE upstream session per machine — the+ * desktop's, usually — but a second local client (`harness remote` creating a terminal there, an+ * E2E script watching) must not take the desktop's place: `sink` fans out to all of them and+ * `onClosed` tells each, and the entry lingers only once the last one has detached.+ */+ attached: Set<AttachedClient>sink: LocalClientSink | nullonClosed: ((code: number, reason: string) => void) | nulllingerTimer: ReturnType<typeof setTimeout> | null@@ -220,23 +262,24 @@ export class RemoteRelayPool {sink: LocalClientSink,onClosed: (code: number, reason: string) => void,): Promise<RelaySession> {+ const client: AttachedClient = { sink, onClosed }const existing = this.entries.get(machineId)if (existing) {if (existing.lingerTimer) { clearTimeout(existing.lingerTimer); existing.lingerTimer = null }- existing.sink = sink- existing.onClosed = onClosed+ existing.attached.add(client)+ bindAttached(existing)sink.sendFrame({ type: 'connected', payload: { machineId, e2ee: false } })- return this.sessionFor(machineId, existing)+ return this.sessionFor(machineId, existing, client)}const inFlight = this.pending.get(machineId)const entry = await (inFlight ?? this.connect(machineId, autonomousEnv, selectFrame))- entry.sink = sink+ entry.attached.add(client)+ bindAttached(entry)// The real backend `connected{machineId}` ack that resolved the connect above was consumed// internally by dial()'s handshake logic, not forwarded — this local client (whether it triggered// the dial or joined one already in flight) still needs its own ack to know the select succeeded.sink.sendFrame({ type: 'connected', payload: { machineId, e2ee: false } })- entry.onClosed = onClosed- return this.sessionFor(machineId, entry)+ return this.sessionFor(machineId, entry, client)}private connect(machineId: string, autonomousEnv: string, selectFrame: Frame): Promise<Entry> {@@ -274,6 +317,7 @@ export class RemoteRelayPool {const entry: Entry = {ws,crypto,+ attached: new Set(),sink: null,onClosed: null,lingerTimer: null,@@ -515,7 +559,7 @@ export class RemoteRelayPool {return entry}- private sessionFor(machineId: string, entry: Entry): RelaySession {+ private sessionFor(machineId: string, entry: Entry, client: AttachedClient | null = null): RelaySession {return {send: async (frame) => {const payload = framePayload(frame)@@ -566,9 +610,12 @@ export class RemoteRelayPool {if (p2pFailed) this.demoteP2p(machineId, entry, 'send_failed')},detach: () => {+ // This client only; the upstream stays for whoever else is on it, and lingers a while for+ // the next select once nobody is.+ if (client) entry.attached.delete(client)+ bindAttached(entry)+ if (entry.attached.size > 0) returnentry.viewers?.reset()- entry.sink = null- entry.onClosed = nullentry.lingerTimer = setTimeout(() => {if (!entry.sink) {if (entry.p2pRetryTimer) clearTimeout(entry.p2pRetryTimer)diff --git a/cli/src/lib/terminalHandoff.ts b/cli/src/lib/terminalHandoff.tsnew file mode 100644index 000000000..afb0316fc--- /dev/null+++ b/cli/src/lib/terminalHandoff.ts@@ -0,0 +1,29 @@+/**+ * `remote_terminal_handoff` — the wire shape behind `harness remote`.+ *+ * Typed inside one of this machine's terminal tiles, `harness remote` opens a terminal on another+ * machine and then asks the window in front of it to swap the tile over. The shell knows one thing+ * about itself: its tmux pane (`$TMUX_PANE`, `%N`). The daemon turns that into the agent whose tile it+ * is, and pushes the swap to the loopback clients — the desktop — as a `remote_terminal_handoff` event. (Not `terminal_*`: those frames are the+ * terminal streams' and never reach the RPC switch.)+ */++export interface TerminalHandoffRequest {+ /** The pane `harness remote` was typed in: tmux's `%N`. */+ tmuxPane: string+ /** The machine the new terminal is on, and the agent it is there. */+ machineId: string+ agentId: string+}++export const TMUX_PANE_RE = /^%\d{1,9}$/+const ID_RE = /^[A-Za-z0-9_-]{1,128}$/++/** The request as the wire may carry it — bounded, printable ids, a real pane id — or null. */+export function terminalHandoffRequest(payload: Record<string, unknown>): TerminalHandoffRequest | null {+ const { tmuxPane, machineId, agentId } = payload+ if (typeof tmuxPane !== 'string' || !TMUX_PANE_RE.test(tmuxPane)) return null+ if (typeof machineId !== 'string' || !ID_RE.test(machineId)) return null+ if (typeof agentId !== 'string' || !ID_RE.test(agentId)) return null+ return { tmuxPane, machineId, agentId }+}diff --git a/cli/src/remoteCommand.spec.ts b/cli/src/remoteCommand.spec.tsnew file mode 100644index 000000000..eb3cff546--- /dev/null+++ b/cli/src/remoteCommand.spec.ts@@ -0,0 +1,300 @@+// `harness remote`: the picker on a fake tty, the loopback calls against a fake daemon socket, and the+// lines it says when something on the way refuses.+import { EventEmitter } from 'node:events'+import { PassThrough } from 'node:stream'+import { describe, expect, it, vi } from 'vitest'+import {+ LoopbackClient, LoopbackError, handoffTerminal, openRemoteTerminal, orderForPicker, pickMachine, remoteCommand, remoteFailureLine,+ type LoopbackSocket, type RemoteCommandDeps, type RemoteMachineChoice,+} from './remoteCommand.js'++const machines: RemoteMachineChoice[] = [+ { machineId: 'this-mac', label: 'MacbookPro.local', status: 'running', current: true },+ { machineId: 'box-1', label: 'machine-remote-1', status: 'offline', current: false },+ { machineId: 'box-2', label: 'machine-remote-2', status: 'running', current: false },+]++/** A tty for the picker: keys go in as the escape sequences a terminal sends, output is captured. */+function tty(): { input: RemoteCommandDeps['input']; output: RemoteCommandDeps['output']; written: () => string; press: (...keys: string[]) => void } {+ const input = new PassThrough() as unknown as RemoteCommandDeps['input'] & { setRawMode: (raw: boolean) => void }+ input.isTTY = true+ input.setRawMode = vi.fn()+ const chunks: string[] = []+ const output = new PassThrough() as unknown as RemoteCommandDeps['output']+ output.isTTY = true+ output.on('data', (chunk: Buffer) => chunks.push(chunk.toString()))+ const codes: Record<string, string> = { up: '\x1b[A', down: '\x1b[B', enter: '\r', esc: '\x1b', q: 'q', j: 'j', k: 'k', 'ctrl-c': '\x03' }+ return {+ input, output,+ written: () => chunks.join(''),+ press: (...keys) => { for (const key of keys) (input as unknown as PassThrough).write(codes[key] ?? key) },+ }+}++/** The daemon's loopback end, as `harness remote` sees it: a socket per connection, scripted replies. */+class FakeDaemon {+ readonly sent: Array<{ type: string; payload: Record<string, unknown> }> = []+ constructor(private readonly answer: (socket: FakeSocket, frame: { type: string; payload: Record<string, unknown> }) => void) {}+ connect = (url: string): LoopbackSocket => {+ expect(url).toBe('ws://127.0.0.1:18473/api/local-ws')+ const socket = new FakeSocket((frame) => { this.sent.push(frame); this.answer(socket, frame) })+ setTimeout(() => socket.emit('open'), 0)+ return socket+ }+}++class FakeSocket extends EventEmitter implements LoopbackSocket {+ closed = false+ constructor(private readonly onSend: (frame: { type: string; payload: Record<string, unknown> }) => void) { super() }+ send(data: string): void { this.onSend(JSON.parse(data) as { type: string; payload: Record<string, unknown> }) }+ reply(type: string, payload: Record<string, unknown>): void { this.emit('message', JSON.stringify({ type, payload }), false) }+ close(): void { this.closed = true; this.emit('close', 1000, '') }+}++/** The daemon as it behaves when everything works: selects, creates, hands off. */+function workingDaemon(windows = 1): FakeDaemon {+ return new FakeDaemon((socket, frame) => {+ if (frame.type === 'machine_select') socket.reply('connected', { machineId: frame.payload.machineId })+ if (frame.type === 'agent_create') socket.reply('agent_create_result', { requestId: frame.payload.requestId, agent: { id: 'agent-remote-1', engine: frame.payload.engine } })+ if (frame.type === 'remote_terminal_handoff') socket.reply('remote_terminal_handoff_result', { requestId: frame.payload.requestId, ok: true, fromAgentId: 'agent-local-7', windows })+ })+}++function deps(overrides: Partial<RemoteCommandDeps> = {}): RemoteCommandDeps & { errors: string[]; io: ReturnType<typeof tty>; links: string[] } {+ const io = tty()+ const errors: string[] = []+ const links: string[] = []+ return {+ tmuxPane: '%7',+ localMachineId: 'this-mac',+ port: 18473,+ daemonRunning: () => true,+ listMachines: async () => machines,+ isLinked: () => true,+ link: async (machineId, password) => { links.push(`${machineId}:${password}`); return { ok: true, fingerprint: 'AB:CD' } },+ promptPassword: async () => 'hunter2',+ input: io.input,+ output: io.output,+ error: (line) => errors.push(line),+ connect: workingDaemon().connect,+ ...overrides,+ errors,+ io,+ links,+ }+}++describe('pickMachine', () => {+ it('starts on the first online machine, says Online/Offline on every row, moves with the arrows, and takes Enter', async () => {+ const io = tty()+ const picked = pickMachine(machines.filter((m) => !m.current), io)+ await new Promise((resolve) => setTimeout(resolve, 5))+ expect(io.written()).toContain('❯ machine-remote-2 Online')+ expect(io.written()).toContain(' machine-remote-1 Offline')+ io.press('up')+ await new Promise((resolve) => setTimeout(resolve, 5))+ expect(io.written().split('❯ ').at(-1)).toMatch(/^machine-remote-1/)+ io.press('down', 'enter')+ expect(await picked).toEqual(machines[2])+ })++ it('an offline machine cannot be taken: Enter says so and the list stays', async () => {+ const io = tty()+ const picked = pickMachine(machines.filter((m) => !m.current), io)+ await new Promise((resolve) => setTimeout(resolve, 5))+ io.press('up', 'enter') // onto machine-remote-1 (offline)+ await new Promise((resolve) => setTimeout(resolve, 5))+ expect(io.written()).toContain('machine-remote-1 is offline — run `harness start` there, or choose one that is online.')+ io.press('down', 'enter')+ expect(await picked).toEqual(machines[2])+ })++ it('wraps at both ends and also answers to j and k', async () => {+ const io = tty()+ const picked = pickMachine(machines.filter((m) => !m.current), io)+ await new Promise((resolve) => setTimeout(resolve, 5))+ io.press('j', 'j', 'k', 'k', 'k', 'k', 'enter') // 2→1→2→1→2→1→2+ expect(await picked).toEqual(machines[2])+ })++ it('Esc, q and Ctrl-C leave with nothing chosen', async () => {+ for (const key of ['esc', 'q', 'ctrl-c']) {+ const io = tty()+ const picked = pickMachine(machines.filter((m) => !m.current), io)+ await new Promise((resolve) => setTimeout(resolve, 5))+ io.press(key)+ expect(await picked, key).toBeNull()+ }+ })+})++describe('orderForPicker', () => {+ it('lists the online machines first, keeping each group in the order the account gave', () => {+ const rows: RemoteMachineChoice[] = [+ { machineId: 'a', label: 'a', status: 'offline', current: false },+ { machineId: 'b', label: 'b', status: 'running', current: false },+ { machineId: 'c', label: 'c', status: 'offline', current: false },+ { machineId: 'd', label: 'd', status: 'online', current: false },+ ]+ expect(orderForPicker(rows).map((row) => row.machineId)).toEqual(['b', 'd', 'a', 'c'])+ })+})++describe('the loopback calls', () => {+ it('openRemoteTerminal selects the machine and creates a terminal agent at home', async () => {+ const daemon = workingDaemon()+ expect(await openRemoteTerminal({ port: 18473, connect: daemon.connect }, 'box-2')).toBe('agent-remote-1')+ expect(daemon.sent.map((frame) => frame.type)).toEqual(['machine_select', 'agent_create'])+ expect(daemon.sent[0].payload).toEqual({ machineId: 'box-2', localProtocolVersion: 1 })+ expect(daemon.sent[1].payload).toMatchObject({ engine: 'terminal', bypassPermission: false })+ expect(daemon.sent[1].payload).not.toHaveProperty('cwd')+ })++ it('handoffTerminal selects this machine and names the pane', async () => {+ const daemon = workingDaemon(2)+ const result = await handoffTerminal({ port: 18473, connect: daemon.connect }, 'this-mac', { tmuxPane: '%7', machineId: 'box-2', agentId: 'agent-remote-1' })+ expect(result).toEqual({ fromAgentId: 'agent-local-7', windows: 2 })+ expect(daemon.sent[0].payload.machineId).toBe('this-mac')+ expect(daemon.sent[1].payload).toMatchObject({ tmuxPane: '%7', machineId: 'box-2', agentId: 'agent-remote-1' })+ })++ it('a machine the daemon closes on with 4404 is NO_PEER_LINK; a reply with error is thrown by code', async () => {+ const unlinked = new FakeDaemon((socket, frame) => { if (frame.type === 'machine_select') { socket.emit('close', 4404, 'NO_PEER_LINK') } })+ await expect(openRemoteTerminal({ port: 18473, connect: unlinked.connect }, 'box-1')).rejects.toMatchObject({ code: 'NO_PEER_LINK' })+ const refusing = new FakeDaemon((socket, frame) => {+ if (frame.type === 'machine_select') socket.reply('connected', {})+ if (frame.type === 'agent_create') socket.reply('agent_create_result', { requestId: frame.payload.requestId, error: 'INVALID_ENGINE', detail: 'no' })+ })+ await expect(openRemoteTerminal({ port: 18473, connect: refusing.connect }, 'box-1')).rejects.toMatchObject({ code: 'INVALID_ENGINE', message: 'no' })+ })++ it('a daemon that never answers is a TIMEOUT, not a hang', async () => {+ const silent = new FakeDaemon(() => {})+ const client = new LoopbackClient('ws://127.0.0.1:18473/api/local-ws', silent.connect)+ await expect(client.select('box-1', 30)).rejects.toMatchObject({ code: 'TIMEOUT' })+ client.close()+ })+})++describe('remoteCommand', () => {+ it('outside a Harness tile it says where it works and does nothing', async () => {+ for (const tmuxPane of [undefined, '', '%x']) {+ const d = deps({ tmuxPane })+ expect(await remoteCommand(d)).toBe(1)+ expect(d.errors[0]).toContain('inside one of the Harness app')+ expect(d.io.written()).toBe('')+ }+ })++ it('needs the daemon, a sign-in, and another machine', async () => {+ const down = deps({ daemonRunning: () => false })+ expect(await remoteCommand(down)).toBe(1)+ expect(down.errors[0]).toContain('harness start')+ const signedOut = deps({ localMachineId: null })+ expect(await remoteCommand(signedOut)).toBe(1)+ expect(signedOut.errors[0]).toContain('harness login')+ const alone = deps({ listMachines: async () => [machines[0]] })+ expect(await remoteCommand(alone)).toBe(1)+ expect(alone.errors[0]).toContain('No other machines')+ const allOffline = deps({ listMachines: async () => [machines[0], machines[1]] })+ expect(await remoteCommand(allOffline)).toBe(1)+ expect(allOffline.errors[0]).toContain('No other machine is online right now (machine-remote-1)')+ })++ it('a machine not linked yet is linked first, with its remote password', async () => {+ const daemon = workingDaemon()+ const d = deps({ connect: daemon.connect, isLinked: () => false })+ const run = remoteCommand(d)+ await new Promise((resolve) => setTimeout(resolve, 5))+ d.io.press('enter')+ expect(await run).toBe(0)+ expect(d.links).toEqual(['box-2:hunter2'])+ expect(d.io.written()).toContain('machine-remote-2 is not linked to this computer yet.')+ expect(d.io.written()).toContain('✓ Linked machine-remote-2 (fingerprint AB:CD)')+ expect(d.io.written()).toContain('Switching this tile to machine-remote-2')+ })++ it('an empty password, or a link the other machine refuses, stops before anything opens', async () => {+ const daemon = workingDaemon()+ const empty = deps({ connect: daemon.connect, isLinked: () => false, promptPassword: async () => ' ' })+ const emptyRun = remoteCommand(empty)+ await new Promise((resolve) => setTimeout(resolve, 5))+ empty.io.press('enter')+ expect(await emptyRun).toBe(1)+ expect(empty.errors[0]).toContain('No password entered')+ expect(daemon.sent).toEqual([])+ const refused = deps({ connect: daemon.connect, isLinked: () => false, link: async () => ({ ok: false, message: 'Wrong password for machine-remote-2.' }) })+ const refusedRun = remoteCommand(refused)+ await new Promise((resolve) => setTimeout(resolve, 5))+ refused.io.press('enter')+ expect(await refusedRun).toBe(1)+ expect(refused.errors[0]).toContain('Wrong password')+ expect(daemon.sent).toEqual([])+ })++ it('picks, opens the terminal there, hands the tile over, and says so', async () => {+ const daemon = workingDaemon()+ const d = deps({ connect: daemon.connect })+ const run = remoteCommand(d)+ await new Promise((resolve) => setTimeout(resolve, 5))+ d.io.press('enter') // the first online one: machine-remote-2+ expect(await run).toBe(0)+ expect(d.errors).toEqual([])+ expect(d.io.written()).toContain('Opening a terminal on machine-remote-2')+ expect(d.io.written()).toContain('Switching this tile to machine-remote-2')+ expect(daemon.sent.map((frame) => frame.type)).toEqual(['machine_select', 'agent_create', 'machine_select', 'remote_terminal_handoff'])+ })++ it('cancelling is exit 0 and no call', async () => {+ const daemon = workingDaemon()+ const d = deps({ connect: daemon.connect })+ const run = remoteCommand(d)+ await new Promise((resolve) => setTimeout(resolve, 5))+ d.io.press('esc')+ expect(await run).toBe(0)+ expect(d.io.written()).toContain('Cancelled.')+ expect(daemon.sent).toEqual([])+ })++ it('with no window listening the terminal is still open, and it says where to find it', async () => {+ const d = deps({ connect: workingDaemon(0).connect })+ const run = remoteCommand(d)+ await new Promise((resolve) => setTimeout(resolve, 5))+ d.io.press('enter')+ expect(await run).toBe(0)+ expect(d.io.written()).toContain('no Harness window is here')+ })++ it('a pin the daemon does not accept is linked again, once, and the open retried', async () => {+ let dials = 0+ const daemon = new FakeDaemon((socket, frame) => {+ if (frame.type === 'machine_select' && frame.payload.machineId === 'box-2' && ++dials === 1) { socket.emit('close', 4404, 'NO_PEER_LINK'); return }+ if (frame.type === 'machine_select') socket.reply('connected', {})+ if (frame.type === 'agent_create') socket.reply('agent_create_result', { requestId: frame.payload.requestId, agent: { id: 'agent-remote-1' } })+ if (frame.type === 'remote_terminal_handoff') socket.reply('remote_terminal_handoff_result', { requestId: frame.payload.requestId, ok: true, fromAgentId: 'a', windows: 1 })+ })+ const d = deps({ connect: daemon.connect }) // isLinked says yes; the daemon disagrees+ const run = remoteCommand(d)+ await new Promise((resolve) => setTimeout(resolve, 5))+ d.io.press('enter')+ expect(await run).toBe(0)+ expect(d.links).toEqual(['box-2:hunter2'])+ expect(d.io.written()).toContain('Switching this tile to machine-remote-2')+ // And when the second link is refused too, the command says what to run.+ const stubborn = new FakeDaemon((socket, frame) => { if (frame.type === 'machine_select') socket.emit('close', 4404, 'NO_PEER_LINK') })+ const e = deps({ connect: stubborn.connect })+ const eRun = remoteCommand(e)+ await new Promise((resolve) => setTimeout(resolve, 5))+ e.io.press('enter')+ expect(await eRun).toBe(1)+ expect(e.errors[0]).toContain('harness link connect box-2')+ })++ it('remoteFailureLine puts the daemon\'s codes into words', () => {+ const box = machines[1]+ expect(remoteFailureLine(new LoopbackError('NOT_A_HARNESS_PANE'), box)).toContain('inside a Harness terminal')+ expect(remoteFailureLine(new LoopbackError('DAEMON_UNREACHABLE', 'ECONNREFUSED'), box)).toContain('harness start')+ expect(remoteFailureLine(new LoopbackError('WEIRD', 'because'), box)).toBe('WEIRD: because')+ expect(remoteFailureLine(new Error('plain'), box)).toBe('plain')+ })+})diff --git a/cli/src/remoteCommand.ts b/cli/src/remoteCommand.tsnew file mode 100644index 000000000..7705f5a7c--- /dev/null+++ b/cli/src/remoteCommand.ts@@ -0,0 +1,342 @@+/**+ * `harness remote` — from inside one of the app's terminal tiles, open a terminal on ANOTHER of your+ * machines and have the window swap this tile over to it.+ *+ * Typed in a tile, it lists the account's other machines, takes one with ↑/↓ and Enter, creates a+ * `terminal` agent there through the daemon's loopback socket (the daemon relays to the other machine+ * the way it does for the desktop), then asks the daemon to tell the window: `remote_terminal_handoff`+ * names this tile by its tmux pane — `$TMUX_PANE`, the one fact a shell has about itself — and the+ * window swaps the tile to the new agent and ends this shell.+ *+ * Only a Harness tile qualifies. Another terminal app, or a tmux of the user's own, has no tile for+ * the window to swap, so the command says so and does nothing. A machine not linked to this computer+ * yet is linked on the spot — the remote password is asked for, as `harness link connect` asks — and+ * an offline machine is listed but cannot be taken: there is nothing there to open a shell on.+ */+import { randomUUID } from 'node:crypto'+import { emitKeypressEvents } from 'node:readline'+import { WebSocket } from 'ws'+import { TMUX_PANE_RE } from './lib/terminalHandoff.js'++export interface RemoteMachineChoice {+ machineId: string+ /** What the row says: the machine's name, else its hostname. */+ label: string+ /** As the control plane reports it: `running`, `offline`, … */+ status: string+ /** This computer — never offered, since the tile is already here. */+ current: boolean+}++/** The words the control plane uses for a machine that is up — the same set the desktop reads. */+const ONLINE_STATUSES = new Set(['running', 'online', 'connected', 'ready'])+export const isOnline = (choice: RemoteMachineChoice): boolean => ONLINE_STATUSES.has(choice.status.trim().toLowerCase())++/** The picker's order: the machines a terminal can open on first, each group as the account lists it. */+export function orderForPicker(choices: RemoteMachineChoice[]): RemoteMachineChoice[] {+ return [...choices.filter(isOnline), ...choices.filter((choice) => !isOnline(choice))]+}++export interface RemoteCommandDeps {+ /** `process.env.TMUX_PANE` — set by tmux in every pane, `%N`. */+ tmuxPane: string | undefined+ /** This machine's id, from the SSO session; null when not signed in. */+ localMachineId: string | null+ /** The daemon's loopback port, and whether it is up at all. */+ port: number+ daemonRunning: () => boolean+ listMachines: () => Promise<RemoteMachineChoice[]>+ /** Whether this computer holds [machineId]'s peer pin (`harness link list`). */+ isLinked: (machineId: string) => boolean+ /** `harness link connect`, as a call: proves the remote password, pins the peer. */+ link: (machineId: string, password: string) => Promise<{ ok: true; fingerprint: string } | { ok: false; message: string }>+ promptPassword: (prompt: string) => Promise<string>+ input: NodeJS.ReadStream & { isTTY?: boolean }+ output: NodeJS.WriteStream & { isTTY?: boolean }+ error: (line: string) => void+ /** Test seam: what opens a loopback socket. */+ connect?: (url: string) => LoopbackSocket+}++/** The slice of `ws.WebSocket` the loopback client uses — a test stands one in. */+export interface LoopbackSocket {+ on(event: 'open', listener: () => void): unknown+ on(event: 'message', listener: (raw: unknown, isBinary: boolean) => void): unknown+ on(event: 'close', listener: (code: number, reason: Buffer | string) => void): unknown+ on(event: 'error', listener: (error: Error) => void): unknown+ send(data: string): void+ close(): void+}++/** How a loopback call ended, in the daemon's words. */+export class LoopbackError extends Error {+ constructor(readonly code: string, detail?: string) {+ super(detail ?? code)+ }+}++/**+ * Pick one of [choices] on a tty, in the order given (the command passes them online first): ↑/↓+ * (or k/j) move, Enter takes, Esc / q / Ctrl-C leave with null. Every row says Online or Offline;+ * Enter on an offline one says why it cannot be taken and stays.+ * Drawn in place — the rows are rewritten on every move, never scrolled.+ */+export function pickMachine(+ choices: RemoteMachineChoice[],+ io: { input: RemoteCommandDeps['input']; output: RemoteCommandDeps['output'] },+): Promise<RemoteMachineChoice | null> {+ const { input, output } = io+ return new Promise((resolve) => {+ let index = Math.max(0, choices.findIndex(isOnline))+ let drawn = 0+ let note = ''+ const width = Math.max(...choices.map((choice) => choice.label.length))+ const draw = (): void => {+ if (drawn) output.write(`\x1b[${drawn}A\x1b[J`)+ const lines = [+ ' Open a terminal on: ↑/↓ choose · Enter open · Esc cancel',+ ...choices.map((choice, at) => {+ const mark = at === index ? '❯' : ' '+ const status = isOnline(choice) ? 'Online' : 'Offline'+ return ` ${mark} ${choice.label.padEnd(width)} ${status}`+ }),+ ...(note ? [` ${note}`] : []),+ ]+ output.write(lines.join('\n') + '\n')+ drawn = lines.length+ }+ const finish = (choice: RemoteMachineChoice | null): void => {+ input.off('keypress', onKey)+ if (input.isTTY) input.setRawMode(false)+ input.pause()+ resolve(choice)+ }+ const onKey = (_text: string | undefined, key: { name?: string; ctrl?: boolean } = {}): void => {+ if ((key.ctrl && key.name === 'c') || key.name === 'escape' || key.name === 'q') { finish(null); return }+ if (key.name === 'return' || key.name === 'enter') {+ const choice = choices[index]+ if (choice && !isOnline(choice)) { note = `${choice.label} is offline — run \`harness start\` there, or choose one that is online.`; draw(); return }+ finish(choice ?? null); return+ }+ if (key.name === 'up' || key.name === 'k') index = (index - 1 + choices.length) % choices.length+ else if (key.name === 'down' || key.name === 'j') index = (index + 1) % choices.length+ else return+ note = ''+ draw()+ }+ emitKeypressEvents(input)+ if (input.isTTY) input.setRawMode(true)+ input.resume()+ input.on('keypress', onKey)+ draw()+ })+}++/**+ * One connection to the daemon's loopback socket, selected onto one machine — this one, or one the+ * daemon relays to — with the request/reply shape every local client uses (`<type>_result` carrying+ * the request's id).+ */+export class LoopbackClient {+ private readonly frames: Array<{ type: string; payload: Record<string, unknown> }> = []+ private readonly waiters: Array<{ test: (frame: { type: string; payload: Record<string, unknown> }) => boolean; resolve: (frame: { type: string; payload: Record<string, unknown> }) => void }> = []+ private closed: { code: number; reason: string } | null = null+ private readonly socket: LoopbackSocket+ private readonly opened: Promise<void>++ constructor(url: string, connect: (url: string) => LoopbackSocket = (target) => new WebSocket(target) as unknown as LoopbackSocket) {+ this.socket = connect(url)+ this.opened = new Promise((resolve, reject) => {+ this.socket.on('open', () => resolve())+ this.socket.on('error', (error) => reject(new LoopbackError('DAEMON_UNREACHABLE', error.message)))+ })+ this.socket.on('message', (raw, isBinary) => {+ if (isBinary) return+ let frame: { type?: unknown; payload?: unknown }+ try { frame = JSON.parse(String(raw)) as { type?: unknown; payload?: unknown } } catch { return }+ if (typeof frame.type !== 'string') return+ const parsed = { type: frame.type, payload: (frame.payload ?? {}) as Record<string, unknown> }+ this.frames.push(parsed)+ for (const waiter of [...this.waiters]) {+ if (waiter.test(parsed)) { this.waiters.splice(this.waiters.indexOf(waiter), 1); waiter.resolve(parsed) }+ }+ })+ this.socket.on('close', (code, reason) => { this.closed = { code, reason: String(reason) } })+ }++ private send(type: string, payload: Record<string, unknown>): void {+ this.socket.send(JSON.stringify({ type, payload }))+ }++ private waitFor(test: (frame: { type: string; payload: Record<string, unknown> }) => boolean, ms: number, what: string): Promise<{ type: string; payload: Record<string, unknown> }> {+ return new Promise((resolve, reject) => {+ const hit = this.frames.find(test)+ if (hit) { resolve(hit); return }+ // Every way out clears the other two: a timer or an interval left behind would hold the+ // process open after the command has already said its last line.+ const waiter = { test, resolve: (frame: { type: string; payload: Record<string, unknown> }) => { settle(); resolve(frame) } }+ const timer = setTimeout(() => { settle(); reject(new LoopbackError('TIMEOUT', `no ${what} from the daemon within ${ms / 1000}s`)) }, ms)+ const poll = setInterval(() => {+ if (!this.closed) return+ settle()+ // The daemon's close codes are its answer: 4404 is a machine that has never been linked.+ const code = this.closed.code === 4404 ? 'NO_PEER_LINK' : this.closed.code === 4403 ? 'MACHINE_UNAVAILABLE' : 'DISCONNECTED'+ reject(new LoopbackError(code, this.closed.reason || `the daemon closed the connection (${this.closed.code})`))+ }, 50)+ const settle = (): void => {+ clearTimeout(timer)+ clearInterval(poll)+ const at = this.waiters.indexOf(waiter)+ if (at >= 0) this.waiters.splice(at, 1)+ }+ this.waiters.push(waiter)+ })+ }++ /** Select [machineId]; resolves once the daemon (or the machine it relays to) has answered. */+ async select(machineId: string, ms = 20_000): Promise<void> {+ await this.opened+ this.send('machine_select', { machineId, localProtocolVersion: 1 })+ const answer = await this.waitFor((frame) => frame.type === 'connected' || frame.type === 'machine_select_error', ms, 'machine_select answer')+ if (answer.type === 'machine_select_error') {+ const error = typeof answer.payload.error === 'string' ? answer.payload.error : 'MACHINE_UNAVAILABLE'+ throw new LoopbackError(error, typeof answer.payload.detail === 'string' ? answer.payload.detail : undefined)+ }+ }++ /** A request and its `<type>_result`; an `error` field in the reply is thrown as a LoopbackError. */+ async rpc(type: string, payload: Record<string, unknown>, ms = 30_000): Promise<Record<string, unknown>> {+ const requestId = randomUUID()+ this.send(type, { requestId, ...payload })+ const reply = await this.waitFor((frame) => frame.type === `${type}_result` && frame.payload.requestId === requestId, ms, `${type}_result`)+ if (typeof reply.payload.error === 'string') {+ throw new LoopbackError(reply.payload.error, typeof reply.payload.detail === 'string' ? reply.payload.detail : undefined)+ }+ return reply.payload+ }++ close(): void {+ try { this.socket.close() } catch { /* already gone */ }+ }+}++export function loopbackUrl(port: number): string {+ return `ws://127.0.0.1:${port}/api/local-ws`+}++/** A `terminal` agent on [machineId], created the way the desktop's ⌘⇧T creates one: at home. */+export async function openRemoteTerminal(deps: Pick<RemoteCommandDeps, 'port' | 'connect'>, machineId: string): Promise<string> {+ const client = new LoopbackClient(loopbackUrl(deps.port), deps.connect)+ try {+ await client.select(machineId)+ const created = await client.rpc('agent_create', { engine: 'terminal', bypassPermission: false })+ const agent = created.agent as { id?: unknown } | undefined+ if (!agent || typeof agent.id !== 'string' || !agent.id) throw new LoopbackError('INTERNAL', 'the machine created no agent')+ return agent.id+ } finally {+ client.close()+ }+}++/** Tell the window to swap this tile over; how many windows heard it comes back. */+export async function handoffTerminal(+ deps: Pick<RemoteCommandDeps, 'port' | 'connect'>,+ localMachineId: string,+ handoff: { tmuxPane: string; machineId: string; agentId: string },+): Promise<{ fromAgentId: string; windows: number }> {+ const client = new LoopbackClient(loopbackUrl(deps.port), deps.connect)+ try {+ await client.select(localMachineId)+ const reply = await client.rpc('remote_terminal_handoff', handoff, 10_000)+ return { fromAgentId: String(reply.fromAgentId ?? ''), windows: Number(reply.windows ?? 0) }+ } finally {+ client.close()+ }+}++/** What an error on the way is worth saying, in one line the tile shows. */+export function remoteFailureLine(error: unknown, machine: RemoteMachineChoice): string {+ if (error instanceof LoopbackError) {+ switch (error.code) {+ case 'NO_PEER_LINK': return `${machine.label} is not linked to this computer yet. Run: harness link connect ${machine.machineId}`+ case 'DAEMON_UNREACHABLE': return 'The Harness daemon is not answering. Run `harness start` and try again.'+ case 'MACHINE_UNAVAILABLE': return `${machine.label} cannot be reached right now (${error.message}).`+ case 'NOT_A_HARNESS_PANE': return 'This shell is not one of the app\'s terminal tiles, so there is no tile to switch. Run `harness remote` inside a Harness terminal.'+ case 'TIMEOUT': return `${machine.label} did not answer in time (${error.message}).`+ default: return `${error.code}${error.message && error.message !== error.code ? `: ${error.message}` : ''}`+ }+ }+ return error instanceof Error ? error.message : String(error)+}++/** Link [choice] now, the way `harness link connect` does: its remote password, proved, pins it. */+async function linkNow(deps: RemoteCommandDeps, choice: RemoteMachineChoice): Promise<boolean> {+ const { output, error } = deps+ output.write(` ${choice.label} is not linked to this computer yet.\n`)+ output.write(' Enter the remote password set on THAT machine (`harness remote-password set` there).\n')+ const password = (await deps.promptPassword(` Remote password for ${choice.label}: `)).trim()+ if (!password) { error(' ✗ No password entered; nothing was linked.'); return false }+ const linked = await deps.link(choice.machineId, password)+ if (!linked.ok) { error(` ✗ ${linked.message}`); return false }+ output.write(` ✓ Linked ${choice.label} (fingerprint ${linked.fingerprint})\n`)+ return true+}++/** Exit code: 0 when the tile was handed over (or the person cancelled), 1 otherwise. */+export async function remoteCommand(deps: RemoteCommandDeps): Promise<number> {+ const { tmuxPane, output, error } = deps+ if (!tmuxPane || !TMUX_PANE_RE.test(tmuxPane)) {+ error('`harness remote` works inside one of the Harness app\'s terminal tiles (New Harness → Terminal, or ⌘⇧T).')+ error('Open one there and run it again.')+ return 1+ }+ if (!deps.input.isTTY || !output.isTTY) { error('`harness remote` needs a terminal to choose a machine in.'); return 1 }+ if (!deps.localMachineId) { error('Not signed in. Run `harness login`.'); return 1 }+ if (!deps.daemonRunning()) { error('The Harness daemon is not running. Run `harness start`.'); return 1 }+ let machines: RemoteMachineChoice[]+ try { machines = await deps.listMachines() } catch (failure) {+ error(failure instanceof Error ? failure.message : String(failure))+ return 1+ }+ const others = machines.filter((machine) => !machine.current)+ if (!others.length) {+ error('No other machines on this account. Run `harness start` on another computer to connect it.')+ return 1+ }+ if (!others.some(isOnline)) {+ error(`No other machine is online right now (${others.map((machine) => machine.label).join(', ')}). Run \`harness start\` there first.`)+ return 1+ }+ const choice = await pickMachine(orderForPicker(others), deps)+ if (!choice) { output.write(' Cancelled.\n'); return 0 }+ // Linked first, when it is not: the relay refuses a machine this computer has no peer pin for.+ if (!deps.isLinked(choice.machineId) && !(await linkNow(deps, choice))) return 1+ output.write(` Opening a terminal on ${choice.label}…\n`)+ let agentId: string+ try { agentId = await openRemoteTerminal(deps, choice.machineId) } catch (failure) {+ // The pin this computer holds is not one the daemon accepts (rotated on the other side, say):+ // link again, once, and retry.+ if (failure instanceof LoopbackError && failure.code === 'NO_PEER_LINK' && await linkNow(deps, choice)) {+ try { agentId = await openRemoteTerminal(deps, choice.machineId) } catch (again) {+ error(` ✗ ${remoteFailureLine(again, choice)}`)+ return 1+ }+ } else {+ error(` ✗ ${remoteFailureLine(failure, choice)}`)+ return 1+ }+ }+ try {+ const { windows } = await handoffTerminal(deps, deps.localMachineId, { tmuxPane, machineId: choice.machineId, agentId })+ if (windows === 0) {+ output.write(` ✓ Terminal open on ${choice.label} — no Harness window is here to switch this tile; find it in the app's agent list.\n`)+ return 0+ }+ output.write(` ✓ Switching this tile to ${choice.label}.\n`)+ return 0+ } catch (failure) {+ error(` ✗ ${remoteFailureLine(failure, choice)}`)+ error(` The terminal is open on ${choice.label} all the same (agent ${agentId.slice(0, 8)}); find it in the app's agent list.`)+ return 1+ }+}