Skip to content

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

feat: implement filesystem browsing, engine launch command configuration, and update E2EE core hash

0xken1582057bfdfa7b
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
index 932d4088b..68e9eeec2 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -14,12 +14,14 @@
import { WebSocket } from 'ws'
import { stat, readFile } from 'fs/promises'
-import { join } from 'path'
+import { isAbsolute, join } from 'path'
import { hostname } from 'os'
import { createHash } from 'crypto'
import { env } from './config/env.js'
import { VERSION } from './version.js'
import { registry, projectDisplayName, type RegisteredSession } from './lib/registry.js'
+import { ENGINES, type AgentEngine } from './engines/types.js'
+import { listDir } from './lib/fsBrowse.js'
import { routeVoiceTask } from './lib/voiceRouter.js'
import { tailFile } from './lib/sessions.js'
import { messagesToEvents, windowRawLines, subagentStatsFromRawLines, type SessionEvent } from './lib/normalize.js'
@@ -274,6 +276,10 @@ export class BackendSocket {
/** Called when the web deletes an agent (`agent_delete`) — cli.ts signals only the validated engine
* process and forgets the session. Keeps recap + agent name. */
onDeleteAgent: ((sessionId: string) => void) | null = null
+ /** Called on `agent_create` — cli.ts spawns a fresh tmux session running the requested engine in the
+ * requested folder and returns the registered session once discovery has picked it up. */
+ onCreateAgent: ((input: { engine: AgentEngine; cwd: string; bypassPermission: boolean }) =>
+ Promise<{ ok: true; session: RegisteredSession } | { ok: false; error: string }>) | null = null
/** Called when the web/device sends chat input to an agent terminal. */
onMessage: ((sessionId: string, content: string) => void) | null = null
/** Best-effort terminal-native title sync after a user renames an agent. */
@@ -1130,10 +1136,17 @@ export class BackendSocket {
return
}
- // A project is backed by an existing local terminal agent; the web/device cannot create one remotely.
- case 'agent_create':
- reply(type, requestId, { error: 'UNSUPPORTED_ON_REMOTE' })
+ case 'agent_create': {
+ const engine = payload.engine as AgentEngine | undefined
+ const cwd = payload.cwd as string | undefined
+ if (!engine || !ENGINES.includes(engine)) { reply(type, requestId, { error: 'INVALID_ENGINE' }); return }
+ if (!cwd || !isAbsolute(cwd)) { reply(type, requestId, { error: 'INVALID_CWD' }); return }
+ if (!this.onCreateAgent) { reply(type, requestId, { error: 'UNSUPPORTED_ON_REMOTE' }); return }
+ const result = await this.onCreateAgent({ engine, cwd, bypassPermission: payload.bypassPermission === true })
+ if (!result.ok) { reply(type, requestId, { error: result.error }); return }
+ reply(type, requestId, { agent: await this.toProject(result.session) })
return
+ }
// Delete an agent: signal its validated engine process and drop it from the list. Idempotent — an already
// gone target still acks + re-emits agent_deleted so the web/device converge. E2EE-gated (the
@@ -1157,6 +1170,15 @@ export class BackendSocket {
return
}
+ case 'fs_list_dir': {
+ // One-level remote directory listing for the New Agent folder browser.
+ const path = typeof payload.path === 'string' ? payload.path : ''
+ const result = listDir(path)
+ if ('error' in result) { reply(type, requestId, { error: result.error }); return }
+ reply(type, requestId, { ...result })
+ return
+ }
+
case 'agent_read_file': {
// View one file — ≤5MB, text-only (mirror the hosted runtime’s guard).
const projectId = payload.agentId as string | undefined
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index a1e75bf62..43a64d742 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -28,6 +28,7 @@ import { installAmpPlugin, installCodexHooks, installCommandCodeHooks, installCu
import { PID_FILE, TOKEN_FILE, daemonPort, isAlive, readPid } from './lib/daemonState.js'
import { flashCommand } from './lib/flash.js'
import { ENGINE_CLI_COMMANDS, ENGINES } from './lib/engineBin.js'
+import { buildEngineLaunchArgv } from './lib/engineLaunch.js'
import { clearDeleted, isRecentlyDeleted, markDeleted } from './lib/deletedSessions.js'
import { terminateDeletedAgent } from './lib/deleteAgentFallback.js'
import { findLiveSession } from './lib/sessionRepair.js'
@@ -2307,6 +2308,38 @@ async function runForeground(token: string): Promise<void> {
mirror.cancel(sessionId) // close the device's "Working…" tile (bare done, no recap) — a cancel emits no turn_ended
}
+ /**
+ * Web requested a new agent (`agent_create`): spawn a fresh tmux session running the chosen engine in
+ * the chosen folder, then hand it to the SAME discovery path organic sessions go through
+ * (`agentReconciler.triggerHint` → `onDiscovered` → registry + `announceSession`) rather than
+ * duplicating registration here.
+ *
+ * The freshly-exec'd engine process may not be visible to `ps` the instant tmux returns, so one probe
+ * pass can miss it — retry `triggerHint` a few times with backoff before giving up.
+ */
+ backend.onCreateAgent = async ({ engine, cwd, bypassPermission }) => {
+ if (!tmuxBackend) return { ok: false, error: 'TMUX_UNAVAILABLE' }
+ try {
+ if (!statSync(cwd).isDirectory()) return { ok: false, error: 'CWD_NOT_FOUND' }
+ } catch {
+ return { ok: false, error: 'CWD_NOT_FOUND' }
+ }
+ const label = `${engine}-${Date.now()}`.replace(/[^A-Za-z0-9_-]/g, '-')
+ const spawned = await tmuxBackend.create({
+ cwd,
+ label,
+ command: buildEngineLaunchArgv(engine, { bypassPermission }),
+ })
+ if (spawned.state !== 'succeeded') return { ok: false, error: 'SPAWN_FAILED' }
+ for (const delayMs of [150, 400, 800]) {
+ await new Promise((resolve) => setTimeout(resolve, delayMs))
+ await agentReconciler.triggerHint(spawned.runtime, engine)
+ const session = registry.byRuntimeEngine(spawned.runtime, engine)
+ if (session) return { ok: true, session }
+ }
+ return { ok: false, error: 'ENGINE_DID_NOT_START' }
+ }
+
/**
* Web or device deleted an agent (`agent_delete`): end the AGENT, not the user's window.
*
diff --git a/cli/src/config/env.ts b/cli/src/config/env.ts
index c8098a0e2..7a0535167 100644
--- a/cli/src/config/env.ts
+++ b/cli/src/config/env.ts
@@ -98,6 +98,9 @@ const envSchema = z.object({
// Connect token (the agent apiKey). Usually passed as `adapter start <token>` and persisted to
// ${ADAPTER_DATA_DIR}/token; this env var overrides both.
ADAPTER_TOKEN: z.string().optional(),
+ // Set to '1' to let the New Agent folder browser (fs_list_dir) list directories outside $HOME.
+ // Off by default so a fat-fingered path or a compromised relay hop can't walk the whole filesystem.
+ HARNESS_FS_BROWSE_UNRESTRICTED: z.string().optional(),
// Where Claude Code writes its per-session JSONL transcripts.
CLAUDE_PROJECTS_DIR: z.string().default(join(homedir(), '.claude', 'projects')),
// Codex state root. Only hook-registered rollout files beneath <CODEX_HOME>/sessions are exposed.
diff --git a/cli/src/lib/e2ee/core.test.ts b/cli/src/lib/e2ee/core.test.ts
index 6c817d5bb..865a18a94 100644
--- a/cli/src/lib/e2ee/core.test.ts
+++ b/cli/src/lib/e2ee/core.test.ts
@@ -187,6 +187,6 @@ describe('e2ee core — interop keystone', () => {
it('core.ts still hashes to the pinned value shared with the other implementations', () => {
const here = dirname(fileURLToPath(import.meta.url))
const actual = createHash('sha256').update(readFileSync(join(here, 'core.ts'))).digest('hex')
- expect(actual).toBe('e08eafcdd0a820992fee2ba5e598b94db9877d4e16c8bea8cba49a2690071db7')
+ expect(actual).toBe('d90702b3385c2b2a75e5cdce49094a5646bb9831e2abaefb73f513185beb853a')
})
})
diff --git a/cli/src/lib/e2ee/core.ts b/cli/src/lib/e2ee/core.ts
index cfa52f2ed..5b48c236d 100644
--- a/cli/src/lib/e2ee/core.ts
+++ b/cli/src/lib/e2ee/core.ts
@@ -350,6 +350,8 @@ export const ENCRYPTED_RPC_RESULT_TYPES = new Set<string>([
// Device RPC replies that carry adapter content (recap headline/body, new agent name). Must be
// ciphertext so the backend relay can't read them — device↔adapter E2EE parity with web.
'agent_recent_result', 'agent_create_result',
+ // A remote-machine directory listing (New Agent folder browser) — leaks filesystem layout if plaintext.
+ 'fs_list_dir_result',
])
/** Client→adapter frames that carry or can trigger adapter-local user data. */
export const ENCRYPTED_DOWN_TYPES = new Set<string>([
@@ -361,6 +363,7 @@ export const ENCRYPTED_DOWN_TYPES = new Set<string>([
'question_response',
'agents_list', 'sessions_list', 'session_get', 'models_list',
'agent_create', 'agent_delete', 'agent_recent', 'agent_update', 'agent_files', 'agent_read_file',
+ 'fs_list_dir',
'device_e2ee_pair', 'e2ee_pairings_list', 'e2ee_pairing_unpair',
'e2ee_pairings_unpair_all', 'e2ee_browser_link_create',
// Remote terminal control is always pairwise E2EE. The relay may route by outer type/connId but must
diff --git a/cli/src/lib/engineLaunch.spec.ts b/cli/src/lib/engineLaunch.spec.ts
new file mode 100644
index 000000000..1cc4bf4cb
--- /dev/null
+++ b/cli/src/lib/engineLaunch.spec.ts
@@ -0,0 +1,33 @@
+import { describe, expect, it } from 'vitest'
+import { BYPASS_PERMISSION_FLAGS, buildEngineLaunchArgv } from './engineLaunch.js'
+import { ENGINES } from '../engines/types.js'
+import { engineBin } from './engineBin.js'
+
+describe('buildEngineLaunchArgv', () => {
+ it('starts with the resolved binary and adds nothing when bypass is not requested', () => {
+ expect(buildEngineLaunchArgv('claude')).toEqual([engineBin('claude')])
+ expect(buildEngineLaunchArgv('claude', { bypassPermission: false })).toEqual([engineBin('claude')])
+ })
+
+ it('appends the confirmed flag for engines with a known bypass flag', () => {
+ expect(buildEngineLaunchArgv('claude', { bypassPermission: true }))
+ .toEqual([engineBin('claude'), '--dangerously-skip-permissions'])
+ expect(buildEngineLaunchArgv('codex', { bypassPermission: true }))
+ .toEqual([engineBin('codex'), '--dangerously-bypass-approvals-and-sandbox'])
+ expect(buildEngineLaunchArgv('cursor', { bypassPermission: true }))
+ .toEqual([engineBin('cursor'), '--force'])
+ expect(buildEngineLaunchArgv('opencode', { bypassPermission: true }))
+ .toEqual([engineBin('opencode'), '--auto'])
+ })
+
+ it('is a no-op for engines with no confirmed flag, even when bypass is requested', () => {
+ expect(buildEngineLaunchArgv('pi', { bypassPermission: true })).toEqual([engineBin('pi')])
+ expect(buildEngineLaunchArgv('hermes', { bypassPermission: true })).toEqual([engineBin('hermes')])
+ })
+
+ it('has an entry (possibly null) for every known engine — no engine silently falls through', () => {
+ for (const engine of ENGINES) {
+ expect(Object.prototype.hasOwnProperty.call(BYPASS_PERMISSION_FLAGS, engine)).toBe(true)
+ }
+ })
+})
diff --git a/cli/src/lib/engineLaunch.ts b/cli/src/lib/engineLaunch.ts
new file mode 100644
index 000000000..392a1a7ea
--- /dev/null
+++ b/cli/src/lib/engineLaunch.ts
@@ -0,0 +1,40 @@
+import type { AgentEngine } from '../engines/types.js'
+import { engineBin } from './engineBin.js'
+
+/**
+ * Best-effort "skip permission prompts" flag per engine, confirmed against each vendor's own docs.
+ * `null` = no known/safe flag — callers must hide the option rather than guess one.
+ */
+export const BYPASS_PERMISSION_FLAGS: Readonly<Record<AgentEngine, string[] | null>> = {
+ claude: ['--dangerously-skip-permissions'],
+ codex: ['--dangerously-bypass-approvals-and-sandbox'],
+ cursor: ['--force'],
+ opencode: ['--auto'],
+ // No permission-prompt system to bypass (pi), or config-file based rather than a flag (hermes).
+ pi: null,
+ hermes: null,
+ // Unconfirmed — do not guess a flag for a CLI we haven't verified.
+ commandcode: null,
+ devin: null,
+ muse: null,
+ amp: null,
+ kilo: null,
+ grok: null,
+ agy: null,
+ copilot: null,
+}
+
+export interface LaunchCommandOptions {
+ bypassPermission?: boolean
+}
+
+/** Full argv (binary first) to launch `engine` in a fresh tmux pane. `cwd` is set separately via
+ * tmux `new-session -c`, not part of this argv. */
+export function buildEngineLaunchArgv(engine: AgentEngine, opts: LaunchCommandOptions = {}): string[] {
+ const argv = [engineBin(engine)]
+ if (opts.bypassPermission) {
+ const flags = BYPASS_PERMISSION_FLAGS[engine]
+ if (flags) argv.push(...flags)
+ }
+ return argv
+}
diff --git a/cli/src/lib/fsBrowse.spec.ts b/cli/src/lib/fsBrowse.spec.ts
new file mode 100644
index 000000000..a4deadfdf
--- /dev/null
+++ b/cli/src/lib/fsBrowse.spec.ts
@@ -0,0 +1,63 @@
+import { afterAll, describe, expect, it } from 'vitest'
+import { mkdirSync, mkdtempSync, chmodSync, rmSync, writeFileSync } from 'fs'
+import { homedir, tmpdir } from 'os'
+import { join } from 'path'
+import { listDir } from './fsBrowse.js'
+
+const root = mkdtempSync(join(homedir(), '.harness-fsbrowse-test-'))
+mkdirSync(join(root, 'Projects'))
+mkdirSync(join(root, 'workspace'))
+mkdirSync(join(root, '.hidden'))
+mkdirSync(join(root, 'restricted'))
+try { chmodSync(join(root, 'restricted'), 0o000) } catch { /* best effort — see permission-denied test below */ }
+
+afterAll(() => {
+ try { chmodSync(join(root, 'restricted'), 0o700) } catch { /* ignore */ }
+ rmSync(root, { recursive: true, force: true })
+})
+
+describe('listDir', () => {
+ it('lists directories, sorted, excluding hidden entries', () => {
+ const result = listDir(root)
+ expect('error' in result).toBe(false)
+ if ('error' in result) return
+ expect(result.entries).toEqual([
+ { name: 'Projects', isDir: true },
+ { name: 'restricted', isDir: true },
+ { name: 'workspace', isDir: true },
+ ])
+ expect(result.truncated).toBe(false)
+ })
+
+ it('defaults to the home directory when path is empty', () => {
+ const result = listDir('')
+ expect('error' in result).toBe(false)
+ if (!('error' in result)) expect(result.path).toBe(homedir())
+ })
+
+ it('rejects a relative path', () => {
+ expect(listDir('relative/path')).toEqual({ error: 'INVALID_PATH' })
+ })
+
+ it('rejects a path outside $HOME by default', () => {
+ expect(listDir(tmpdir())).toEqual({ error: 'FORBIDDEN' })
+ })
+
+ it('reports NOT_FOUND for a missing directory', () => {
+ expect(listDir(join(root, 'does-not-exist'))).toEqual({ error: 'NOT_FOUND' })
+ })
+
+ it('reports NOT_A_DIRECTORY for a file', () => {
+ const filePath = join(root, 'a-file.txt')
+ writeFileSync(filePath, 'x')
+ expect(listDir(filePath)).toEqual({ error: 'NOT_A_DIRECTORY' })
+ })
+
+ // Skipped when running as root (e.g. some CI containers), where chmod 000 doesn't block reads.
+ it.skipIf(typeof process.getuid === 'function' && process.getuid() === 0)(
+ 'maps EACCES to PERMISSION_DENIED',
+ () => {
+ expect(listDir(join(root, 'restricted'))).toEqual({ error: 'PERMISSION_DENIED' })
+ },
+ )
+})
diff --git a/cli/src/lib/fsBrowse.ts b/cli/src/lib/fsBrowse.ts
new file mode 100644
index 000000000..04ce6b6b5
--- /dev/null
+++ b/cli/src/lib/fsBrowse.ts
@@ -0,0 +1,53 @@
+import { readdirSync, statSync } from 'fs'
+import { homedir } from 'os'
+import { isAbsolute, resolve, sep } from 'path'
+import { env } from '../config/env.js'
+
+export interface DirEntry { name: string; isDir: true }
+export interface ListDirResult { path: string; entries: DirEntry[]; truncated: boolean }
+export type ListDirError = { error: 'INVALID_PATH' | 'NOT_FOUND' | 'NOT_A_DIRECTORY' | 'FORBIDDEN' | 'PERMISSION_DENIED' }
+
+// A giant directory (e.g. someone browsing to `/`) must not produce an unbounded reply — nothing
+// upstream (backend relay, hub) caps non-terminal frame size, so this is the only bound in the path.
+const MAX_ENTRIES = 2_000
+
+/** Restrict browsing to under the user's home directory by default — the machine a user runs
+ * `harness` on is "theirs", but a fat-fingered path (or a compromised relay hop) walking arbitrary
+ * system directories is still worth guarding against. Same opt-out convention as CLAUDE_PATH etc. */
+function isAllowed(path: string): boolean {
+ if (env.HARNESS_FS_BROWSE_UNRESTRICTED === '1') return true
+ const home = resolve(homedir())
+ return path === home || path.startsWith(home + sep)
+}
+
+/** One-level directory listing (folders only) rooted at `path`, or `homedir()` when omitted. */
+export function listDir(path: string): ListDirResult | ListDirError {
+ const target = path || homedir()
+ if (!isAbsolute(target)) return { error: 'INVALID_PATH' }
+ const resolved = resolve(target)
+ if (!isAllowed(resolved)) return { error: 'FORBIDDEN' }
+
+ let st
+ try {
+ st = statSync(resolved)
+ } catch (e) {
+ return { error: (e as NodeJS.ErrnoException).code === 'EACCES' ? 'PERMISSION_DENIED' : 'NOT_FOUND' }
+ }
+ if (!st.isDirectory()) return { error: 'NOT_A_DIRECTORY' }
+
+ let raw
+ try {
+ raw = readdirSync(resolved, { withFileTypes: true })
+ } catch (e) {
+ return { error: (e as NodeJS.ErrnoException).code === 'EACCES' ? 'PERMISSION_DENIED' : 'NOT_FOUND' }
+ }
+
+ const dirs: DirEntry[] = []
+ for (const d of raw) {
+ if (d.name.startsWith('.')) continue // hidden — same convention as files.ts's isHidden
+ if (d.isDirectory()) dirs.push({ name: d.name, isDir: true })
+ }
+ dirs.sort((a, b) => a.name.localeCompare(b.name))
+ const truncated = dirs.length > MAX_ENTRIES
+ return { path: resolved, entries: truncated ? dirs.slice(0, MAX_ENTRIES) : dirs, truncated }
+}
diff --git a/cli/src/lib/terminalStreamManager.spec.ts b/cli/src/lib/terminalStreamManager.spec.ts
index a3bdb3a46..316b3dd90 100644
--- a/cli/src/lib/terminalStreamManager.spec.ts
+++ b/cli/src/lib/terminalStreamManager.spec.ts
@@ -190,21 +190,37 @@ describe('TerminalStreamManager', () => {
expect(binarySent[0].frame.seq).toBe(0)
})
- it('rejects a second controller and expires the first lease after heartbeat timeout', async () => {
+ it('takes over the first controller and expires the replacement lease after heartbeat timeout', async () => {
await manager.handleFrame('web-1', 'terminal_open', {
requestId: 'open-1', protocolVersion: 3, agentId: 'agent-1', cols: 100, rows: 30,
})
+ const firstStream = stream
+ const firstStreamId = sent.findLast((frame) => frame.type === 'terminal_ready')?.payload.streamId as string
await manager.handleFrame('web-2', 'terminal_open', {
requestId: 'open-2', protocolVersion: 3, agentId: 'agent-1', cols: 100, rows: 30,
})
- expect(sent.at(-1)?.payload.code).toBe('CONTROL_LEASE_HELD')
+ expect(firstStream.closed).toBe(true)
+ expect(sent.some((frame) => frame.connId === 'web-1'
+ && frame.type === 'terminal_closed'
+ && frame.payload.code === 'TERMINAL_TAKEN_OVER')).toBe(true)
+ expect(sent.findLast((frame) => frame.type === 'terminal_ready')?.connId).toBe('web-2')
+ await manager.handleBinary('web-1', {
+ kind: TerminalBinaryKind.input,
+ streamId: firstStreamId,
+ seq: 0,
+ compressed: false,
+ bytes: Buffer.from('stale input'),
+ })
+ expect(stream.writes).toHaveLength(0)
await vi.advanceTimersByTimeAsync(30_000)
expect(stream.closed).toBe(true)
- expect(sent.some((frame) => frame.type === 'terminal_closed' && frame.payload.reason === 'heartbeat timeout')).toBe(true)
+ expect(sent.some((frame) => frame.connId === 'web-2'
+ && frame.type === 'terminal_closed'
+ && frame.payload.reason === 'heartbeat timeout')).toBe(true)
})
- it('rejects a second agent alias that resolves to the same tmux pane', async () => {
+ it('takes over a second agent alias that resolves to the same tmux pane', async () => {
agents.set('agent-alias', session('claude', 'agent-alias'))
await manager.handleFrame('web-1', 'terminal_open', {
requestId: 'open-1', protocolVersion: 3, agentId: 'agent-1', cols: 100, rows: 30,
@@ -212,7 +228,10 @@ describe('TerminalStreamManager', () => {
await manager.handleFrame('web-2', 'terminal_open', {
requestId: 'open-2', protocolVersion: 3, agentId: 'agent-alias', cols: 100, rows: 30,
})
- expect(sent.at(-1)?.payload.code).toBe('CONTROL_LEASE_HELD')
+ expect(sent.some((frame) => frame.connId === 'web-1'
+ && frame.type === 'terminal_closed'
+ && frame.payload.code === 'TERMINAL_TAKEN_OVER')).toBe(true)
+ expect(sent.findLast((frame) => frame.type === 'terminal_ready')?.connId).toBe('web-2')
})
it('uses frequent ACKs rather than the five-second heartbeat for output backpressure', async () => {
diff --git a/cli/src/lib/terminalStreamManager.ts b/cli/src/lib/terminalStreamManager.ts
index 732662a39..d9eecbacf 100644
--- a/cli/src/lib/terminalStreamManager.ts
+++ b/cli/src/lib/terminalStreamManager.ts
@@ -103,6 +103,9 @@ export class TerminalStreamManager {
private readonly streams = new Map<string, ActiveStream>()
private readonly controllerByAgent = new Map<string, string>()
private readonly controllerByPlacement = new Map<string, string>()
+ // Terminal opens from different backend connections can arrive concurrently. Serialize opens for
+ // the same tmux placement so takeover is deterministic and never leaves two live controllers.
+ private readonly leaseLocks = new Map<string, Promise<void>>()
private readonly now: () => number
private readonly expiryTimer: ReturnType<typeof setInterval>
@@ -112,6 +115,20 @@ export class TerminalStreamManager {
this.expiryTimer.unref?.()
}
+ private async withLeaseLock<T>(key: string, operation: () => Promise<T>): Promise<T> {
+ const previous = this.leaseLocks.get(key) ?? Promise.resolve()
+ let release!: () => void
+ const current = new Promise<void>((resolve) => { release = resolve })
+ this.leaseLocks.set(key, current)
+ await previous
+ try {
+ return await operation()
+ } finally {
+ release()
+ if (this.leaseLocks.get(key) === current) this.leaseLocks.delete(key)
+ }
+ }
+
async handleFrame(connId: string, type: string, payload: FramePayload): Promise<boolean> {
switch (type) {
case 'terminal_capabilities':
@@ -201,11 +218,6 @@ export class TerminalStreamManager {
this.sendError(connId, 'TERMINAL_ENGINE_UNSUPPORTED', { requestId })
return
}
- const controller = this.controllerByAgent.get(session.agentId)
- if (controller && controller !== connId) {
- this.sendError(connId, 'CONTROL_LEASE_HELD', { requestId })
- return
- }
const streamRuntime = session.runtimes.find((runtime) => runtime.backend === 'tmux'
&& terminalRouteKey(runtime) === session.primaryRuntimeKey)
?? session.runtimes.find((runtime) => runtime.backend === 'tmux')
@@ -214,104 +226,103 @@ export class TerminalStreamManager {
return
}
const reservedPlacement = terminalPlacementKey(streamRuntime)
- const placementController = this.controllerByPlacement.get(reservedPlacement)
- if (placementController && placementController !== connId) {
- this.sendError(connId, 'CONTROL_LEASE_HELD', { requestId })
- return
- }
-
- await this.closeConnection(connId, 'replaced', false)
- this.controllerByAgent.set(session.agentId, connId)
- this.controllerByPlacement.set(reservedPlacement, connId)
- const streamId = randomUUID()
- const buffered: Buffer[] = []
- let state: ActiveStream | null = null
- let opened: Awaited<ReturnType<TerminalBackendCoordinator['openStream']>>
- try {
- opened = await this.deps.terminals.openStream(session, size, {
- onData: (bytes) => {
- if (state) this.onOutput(state, bytes)
- else buffered.push(Buffer.from(bytes))
- },
- onClose: (reason) => {
- if (state) void this.closeStream(state, reason, true)
- },
- })
- } catch {
- if (this.controllerByAgent.get(session.agentId) === connId) this.controllerByAgent.delete(session.agentId)
- if (this.controllerByPlacement.get(reservedPlacement) === connId) this.controllerByPlacement.delete(reservedPlacement)
- this.sendError(connId, 'TERMINAL_OPEN_FAILED', { requestId })
- return
- }
- if (opened.state !== 'succeeded') {
- if (this.controllerByAgent.get(session.agentId) === connId) this.controllerByAgent.delete(session.agentId)
- if (this.controllerByPlacement.get(reservedPlacement) === connId) this.controllerByPlacement.delete(reservedPlacement)
- this.sendError(connId, opened.reason, { requestId })
- return
- }
+ await this.withLeaseLock(reservedPlacement, async () => {
+ // A terminal is single-controller. A later client explicitly wins the lease and the incumbent
+ // receives a targeted close notification; it must not be broadcast to other clients.
+ await this.closeStreamsForTakeover(session.agentId, reservedPlacement, connId)
+ await this.closeConnection(connId, 'replaced', false)
+ this.controllerByAgent.set(session.agentId, connId)
+ this.controllerByPlacement.set(reservedPlacement, connId)
+ const streamId = randomUUID()
+ const buffered: Buffer[] = []
+ let state: ActiveStream | null = null
+ let opened: Awaited<ReturnType<TerminalBackendCoordinator['openStream']>>
+ try {
+ opened = await this.deps.terminals.openStream(session, size, {
+ onData: (bytes) => {
+ if (state) this.onOutput(state, bytes)
+ else buffered.push(Buffer.from(bytes))
+ },
+ onClose: (reason) => {
+ if (state) void this.closeStream(state, reason, true)
+ },
+ })
+ } catch {
+ if (this.controllerByAgent.get(session.agentId) === connId) this.controllerByAgent.delete(session.agentId)
+ if (this.controllerByPlacement.get(reservedPlacement) === connId) this.controllerByPlacement.delete(reservedPlacement)
+ this.sendError(connId, 'TERMINAL_OPEN_FAILED', { requestId })
+ return
+ }
+ if (opened.state !== 'succeeded') {
+ if (this.controllerByAgent.get(session.agentId) === connId) this.controllerByAgent.delete(session.agentId)
+ if (this.controllerByPlacement.get(reservedPlacement) === connId) this.controllerByPlacement.delete(reservedPlacement)
+ this.sendError(connId, opened.reason, { requestId })
+ return
+ }
- const placementKey = terminalPlacementKey(opened.value.runtime)
- const actualController = this.controllerByPlacement.get(placementKey)
- if (actualController && actualController !== connId) {
- if (this.controllerByAgent.get(session.agentId) === connId) this.controllerByAgent.delete(session.agentId)
- if (this.controllerByPlacement.get(reservedPlacement) === connId) this.controllerByPlacement.delete(reservedPlacement)
- await opened.value.close().catch(() => { /* best effort */ })
- this.sendError(connId, 'CONTROL_LEASE_HELD', { requestId })
- return
- }
- if (reservedPlacement !== placementKey && this.controllerByPlacement.get(reservedPlacement) === connId) {
- this.controllerByPlacement.delete(reservedPlacement)
- }
- this.controllerByPlacement.set(placementKey, connId)
-
- const requestedCompression = Array.isArray(payload.compression) ? payload.compression : []
- state = {
- connId,
- streamId,
- agentId: session.agentId,
- engineId: session.engine,
- placementKey,
- handle: opened.value,
- compression: requestedCompression.includes('zlib') ? 'zlib' : 'none',
- expiresAt: this.now() + HEARTBEAT_TIMEOUT_MS,
- lastSyncAt: this.now(),
- nextSeq: 0,
- lastInputSeq: -1,
- lastResizeSeq: -1,
- pending: [],
- pendingBytes: 0,
- output: buffered,
- outputBytes: buffered.reduce((sum, chunk) => sum + chunk.length, 0),
- flushTimer: null,
- snapshotting: false,
- resyncing: false,
- closing: false,
- outputPaused: false,
- stallTimer: null,
- openedAt: this.now(),
- outputFrames: 0,
- outputPlainBytes: 0,
- keyframes: 0,
- syncFrames: 0,
- resyncs: 0,
- peakBufferedBytes: 0,
- pausedAt: null,
- pausedMs: 0,
- }
- this.streams.set(streamId, state)
- if (!this.deps.sendTarget(connId, 'terminal_ready', {
- requestId,
- protocolVersion: PROTOCOL_VERSION,
- streamId,
- agentId: session.agentId,
- engineId: session.engine,
- backend: 'tmux',
- })) {
- await this.closeStream(state, 'backend disconnected', false)
- return
- }
- this.diagnostic(state, 'opened', { cols: size.cols, rows: size.rows, compression: state.compression })
- await this.sendKeyframe(state)
+ const placementKey = terminalPlacementKey(opened.value.runtime)
+ const actualController = this.controllerByPlacement.get(placementKey)
+ if (actualController && actualController !== connId) {
+ if (this.controllerByAgent.get(session.agentId) === connId) this.controllerByAgent.delete(session.agentId)
+ if (this.controllerByPlacement.get(reservedPlacement) === connId) this.controllerByPlacement.delete(reservedPlacement)
+ await opened.value.close().catch(() => { /* best effort */ })
+ this.sendError(connId, 'CONTROL_LEASE_HELD', { requestId })
+ return
+ }
+ if (reservedPlacement !== placementKey && this.controllerByPlacement.get(reservedPlacement) === connId) {
+ this.controllerByPlacement.delete(reservedPlacement)
+ }
+ this.controllerByPlacement.set(placementKey, connId)
+
+ const requestedCompression = Array.isArray(payload.compression) ? payload.compression : []
+ state = {
+ connId,
+ streamId,
+ agentId: session.agentId,
+ engineId: session.engine,
+ placementKey,
+ handle: opened.value,
+ compression: requestedCompression.includes('zlib') ? 'zlib' : 'none',
+ expiresAt: this.now() + HEARTBEAT_TIMEOUT_MS,
+ lastSyncAt: this.now(),
+ nextSeq: 0,
+ lastInputSeq: -1,
+ lastResizeSeq: -1,
+ pending: [],
+ pendingBytes: 0,
+ output: buffered,
+ outputBytes: buffered.reduce((sum, chunk) => sum + chunk.length, 0),
+ flushTimer: null,
+ snapshotting: false,
+ resyncing: false,
+ closing: false,
+ outputPaused: false,
+ stallTimer: null,
+ openedAt: this.now(),
+ outputFrames: 0,
+ outputPlainBytes: 0,
+ keyframes: 0,
+ syncFrames: 0,
+ resyncs: 0,
+ peakBufferedBytes: 0,
+ pausedAt: null,
+ pausedMs: 0,
+ }
+ this.streams.set(streamId, state)
+ if (!this.deps.sendTarget(connId, 'terminal_ready', {
+ requestId,
+ protocolVersion: PROTOCOL_VERSION,
+ streamId,
+ agentId: session.agentId,
+ engineId: session.engine,
+ backend: 'tmux',
+ })) {
+ await this.closeStream(state, 'backend disconnected', false)
+ return
+ }
+ this.diagnostic(state, 'opened', { cols: size.cols, rows: size.rows, compression: state.compression })
+ await this.sendKeyframe(state)
+ })
}
private streamFor(connId: string, payload: FramePayload): ActiveStream | null {
@@ -613,7 +624,24 @@ export class TerminalStreamManager {
})
}
- private async closeStream(state: ActiveStream, reason: string, notify: boolean): Promise<void> {
+ private async closeStreamsForTakeover(agentId: string, placementKey: string, nextConnId: string): Promise<void> {
+ const incumbents = [...this.streams.values()].filter((state) =>
+ !state.closing && state.connId !== nextConnId
+ && (state.agentId === agentId || state.placementKey === placementKey))
+ await Promise.all(incumbents.map((state) => this.closeStream(
+ state,
+ 'another client connected',
+ true,
+ 'TERMINAL_TAKEN_OVER',
+ )))
+ }
+
+ private async closeStream(
+ state: ActiveStream,
+ reason: string,
+ notify: boolean,
+ code?: string,
+ ): Promise<void> {
if (state.closing) return
state.closing = true
if (state.pausedAt != null) state.pausedMs += Math.max(0, this.now() - state.pausedAt)
@@ -641,6 +669,7 @@ export class TerminalStreamManager {
protocolVersion: PROTOCOL_VERSION,
streamId: state.streamId,
reason,
+ ...(code ? { code } : {}),
})
}
diff --git a/cli/src/lib/terminalTypes.ts b/cli/src/lib/terminalTypes.ts
index fe843884d..7e98986cd 100644
--- a/cli/src/lib/terminalTypes.ts
+++ b/cli/src/lib/terminalTypes.ts
@@ -62,6 +62,8 @@ export type TerminalActionResult =
export interface TerminalCreateRequest {
cwd?: string
label?: string
+ /** argv (binary first) to run instead of the backend's default shell, e.g. an engine CLI launch. */
+ command?: string[]
}
export type TerminalCreateResult<Ref extends TerminalRuntimeRef = TerminalRuntimeRef> =
diff --git a/cli/src/lib/tmuxBackend.ts b/cli/src/lib/tmuxBackend.ts
index 2388427a9..134d1fb8a 100644
--- a/cli/src/lib/tmuxBackend.ts
+++ b/cli/src/lib/tmuxBackend.ts
@@ -75,6 +75,9 @@ export class TmuxBackend implements TerminalBackend<TmuxRuntimeRef> {
const args = ['new-session', '-d', '-P', '-F', '#{pane_id}']
if (request.cwd) args.push('-c', request.cwd)
if (request.label) args.push('-s', request.label)
+ // Trailing args after this point become the session's shell-command. tmux execs them directly
+ // (no shell interposed) when given as separate argv elements, so no quoting/escaping is needed.
+ if (request.command?.length) args.push(...request.command)
const result = await new Promise<{ error: NodeJS.ErrnoException | null; stdout: string }>((resolve) => {
execFile('tmux', args, { timeout: 5_000 }, (error, stdout) => resolve({
error: error as NodeJS.ErrnoException | null,