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.

refactor: decouple terminal liveness from engine activity and update tmux parser to support path delimiters

0xken15a39d45db3c11
diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.ts
index d340b4a21..655da2595 100644
--- a/cli/src/backendSocket.spec.ts
+++ b/cli/src/backendSocket.spec.ts
@@ -201,7 +201,8 @@ describe('BackendSocket outbound queue', () => {
lastHookAt: 1,
lastTranscriptAt: 1,
}
- vi.spyOn(registry, 'active').mockReturnValue([session])
+ vi.spyOn(registry, 'advertised').mockReturnValue([session])
+ vi.spyOn(registry, 'terminalAvailable').mockReturnValue(true)
const socket = new BackendSocket('token')
socket.connect()
const ws = wsMock.instances[0]
@@ -221,7 +222,10 @@ describe('BackendSocket outbound queue', () => {
await vi.waitFor(() => {
expect(wrapReply).toHaveBeenCalledWith('web-1', 'agents_list_result', 'agents-1', {
- agents: [expect.objectContaining({ id: 'agent-1', sessionId: 'session-1', engine: 'codex' })],
+ agents: [expect.objectContaining({
+ id: 'agent-1', sessionId: 'session-1', engine: 'codex',
+ terminal: expect.objectContaining({ available: true }),
+ })],
})
})
await socket.stop()
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
index ce183b1e9..707a0e69f 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -916,7 +916,7 @@ export class BackendSocket {
}
case 'agents_list': {
- const projects = await Promise.all(registry.active().map((s) => this.toProject(s)))
+ const projects = await Promise.all(registry.advertised().map((s) => this.toProject(s)))
// Ordered by creation time, oldest → newest — a stable tab order that doesn't reshuffle as
// sessions become active (createdAt = the session's registeredAt). The id breaks a tie so the
// order is TOTAL: without it two agents registered in the same millisecond fall through to array
@@ -1216,7 +1216,7 @@ export class BackendSocket {
reply(type, requestId, { error: 'MISSING_TRANSCRIPT' })
return
}
- const projects = (await Promise.all(registry.active().map((s) => this.toProject(s)))).slice(0, 24) // cap the router prompt (mirror the hosted runtime path)
+ const projects = (await Promise.all(registry.advertised().map((s) => this.toProject(s)))).slice(0, 24) // cap the router prompt (mirror the hosted runtime path)
const agents = projects.map((p) => {
// Use the last 3 turns' recaps (not just 1) — a single turn can misrepresent what the agent is
// actually working on; 3 gives the router a more stable picture.
@@ -1405,7 +1405,7 @@ export class BackendSocket {
/** Map a registered tmux session onto the web's Project shape (tabs in ProjectTabs). */
private async toProject(s: RegisteredSession): Promise<{
id: string; sessionId: string; userId: string; name: string; status: string
- createdAt: string; updatedAt: string; tmuxPane: string | null; terminal: { primary: string; runtimes: RegisteredSession['runtimes'] }; engine: RegisteredSession['engine']; selectedModel: string | null
+ createdAt: string; updatedAt: string; tmuxPane: string | null; terminal: { available: boolean; primary: string; runtimes: RegisteredSession['runtimes'] }; engine: RegisteredSession['engine']; selectedModel: string | null
}> {
const st = s.transcriptPath ? await stat(s.transcriptPath).catch(() => null) : null
return {
@@ -1417,7 +1417,7 @@ export class BackendSocket {
createdAt: new Date(s.registeredAt).toISOString(),
updatedAt: new Date(st?.mtimeMs ?? s.updatedAt).toISOString(),
tmuxPane: s.tmuxPane || null,
- terminal: { primary: s.primaryRuntimeKey, runtimes: s.runtimes },
+ terminal: { available: registry.terminalAvailable(s.agentId), primary: s.primaryRuntimeKey, runtimes: s.runtimes },
engine: s.engine,
selectedModel: this.runtimeProfileProvider?.(s) ?? null,
}
diff --git a/cli/src/cable/cableHost.spec.ts b/cli/src/cable/cableHost.spec.ts
index aabac0206..a6d93af03 100644
--- a/cli/src/cable/cableHost.spec.ts
+++ b/cli/src/cable/cableHost.spec.ts
@@ -4,11 +4,12 @@ import { describe, expect, it, vi } from 'vitest'
import { DaemonCableHost, type CableHostWiring } from './cableHost.js'
import type { FleetMachine, MachineFleet } from './machineFleet.js'
-const AGENTS: Array<{ agentId: string; registeredAt: number; active: boolean; engine: string }> = []
+const AGENTS: Array<{ agentId: string; registeredAt: number; active: boolean; terminalAvailable: boolean; engine: string }> = []
vi.mock('../lib/registry.js', () => ({
registry: {
list: () => AGENTS,
active: () => AGENTS.filter((a) => a.active),
+ advertised: () => AGENTS.filter((a) => a.terminalAvailable),
},
projectDisplayName: (s: { agentId: string }) => s.agentId,
}))
@@ -89,17 +90,21 @@ describe('DaemonCableHost.listMachines', () => {
})
describe('DaemonCableHost.listAgents', () => {
- const set = (rows: Array<{ agentId: string; registeredAt: number; active?: boolean }>): void => {
+ const set = (rows: Array<{ agentId: string; registeredAt: number; active?: boolean; terminalAvailable?: boolean }>): void => {
AGENTS.length = 0
- for (const r of rows) AGENTS.push({ engine: 'claude', active: true, ...r })
+ for (const r of rows) AGENTS.push({ engine: 'claude', active: true, terminalAvailable: true, ...r })
}
- it('lists only ACTIVE agents — the same set the web and the app are given', async () => {
+ it('lists only terminal-available agents — including a dormant engine with a live pane', async () => {
// Two surfaces reading one registry must not disagree about what is on it. A dead agent holding a tile
// on the dial and nowhere else is a tile that cannot be driven and cannot be explained.
- set([{ agentId: 'a', registeredAt: 1 }, { agentId: 'b', registeredAt: 2, active: false }])
+ set([
+ { agentId: 'a', registeredAt: 1 },
+ { agentId: 'b', registeredAt: 2, active: false },
+ { agentId: 'stale', registeredAt: 3, terminalAvailable: false },
+ ])
const host = new DaemonCableHost(wiring())
- expect((await host.listAgents()).map((a) => a.id)).toEqual(['a'])
+ expect((await host.listAgents()).map((a) => a.id)).toEqual(['a', 'b'])
})
it('orders oldest first', async () => {
@@ -221,7 +226,7 @@ describe('DaemonCableHost.listAgents across machines', () => {
// The order IS the contract: the dial swipes through it and the desktop app's rail reads top to
// bottom in the same order, so the two surfaces can be compared by eye.
AGENTS.length = 0
- AGENTS.push({ agentId: 'local-1', registeredAt: 1, active: true, engine: 'claude' })
+ AGENTS.push({ agentId: 'local-1', registeredAt: 1, active: true, terminalAvailable: true, engine: 'claude' })
const second: FleetMachine = { machineId: 'third', name: 'studio', state: 'ready', authMode: 'remote' }
const host = new DaemonCableHost(
wiring(),
@@ -273,7 +278,7 @@ describe('DaemonCableHost.listAgents across machines', () => {
it('keeps a local agent local even while another machine is selected', async () => {
AGENTS.length = 0
- AGENTS.push({ agentId: 'local-1', registeredAt: 1, active: true, engine: 'claude' })
+ AGENTS.push({ agentId: 'local-1', registeredAt: 1, active: true, terminalAvailable: true, engine: 'claude' })
const sendTurn = vi.fn()
const fleet = crossFleet({ other: [] })
const host = new DaemonCableHost(wiring({ sendTurn }), fleet)
diff --git a/cli/src/cable/cableHost.ts b/cli/src/cable/cableHost.ts
index 5ac7f978f..952b52235 100644
--- a/cli/src/cable/cableHost.ts
+++ b/cli/src/cable/cableHost.ts
@@ -244,10 +244,10 @@ export class DaemonCableHost implements CableHost {
/** This computer's own agents, in the order every other surface reads them in. */
private localAgents(): CableAgent[] {
- // `active()`, not `list()` — the SAME set `agents_list` answers the web and the desktop app with. They
+ // `advertised()`, not `list()` — the SAME set `agents_list` answers the web and the desktop app with. They
// read one registry and must not disagree about what is on it: a dead agent holding a tile on the dial
// and nowhere else is a tile that cannot be driven and cannot be explained.
- const sessions = registry.active()
+ const sessions = registry.advertised()
// Oldest → newest, and TOTAL: the id breaks a tie so the order cannot fall through to array position,
// which is Map insertion order and differs between daemon runs. Both producers sort identically, so
// the dial and the app cannot drift apart while reading the same registry.
@@ -616,4 +616,3 @@ export function cableQuestionCloseFor(
if (typeof requestId !== 'string' || !requestId) return null
return { agentId: frame.agentId, requestId }
}
-
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index 54698729c..f412d6358 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -650,7 +650,7 @@ async function projectFrame(s: RegisteredSession, selectedModel: string | null):
createdAt: new Date(s.registeredAt).toISOString(),
updatedAt: new Date(st?.mtimeMs ?? s.updatedAt).toISOString(),
tmuxPane: s.tmuxPane || null,
- terminal: { primary: s.primaryRuntimeKey, runtimes: s.runtimes },
+ terminal: { available: registry.terminalAvailable(s.agentId), primary: s.primaryRuntimeKey, runtimes: s.runtimes },
engine: s.engine,
selectedModel,
}
@@ -673,6 +673,8 @@ async function statBirthMs(path: string): Promise<number> {
async function runForeground(session: AuthSession): Promise<void> {
installTimestampedConsole() // daemon-only: every harness.log line gets a wall-clock timestamp
const startedAt = Date.now()
+ let discoveryReady = false
+ let discoveryError: string | null = null
// Claim the pid file for OURSELVES, first thing. It used to be written by whoever spawned us — the
// update-restart's parent, after supervising the handover — so a parent that died mid-handover (a
@@ -980,6 +982,11 @@ async function runForeground(session: AuthSession): Promise<void> {
// server may fall back to a free port if env.PORT is taken, and the hooks must point at the real one.
const syncSession = (s: RegisteredSession, opts: { device?: boolean } = {}): void => {
+ if (!registry.terminalAvailable(s.agentId)) {
+ backendRef?.send({ type: 'agent_deleted', payload: { agentId: s.agentId } })
+ if (opts.device !== false) backendRef?.sendCommander({ type: 'agent_deleted', payload: { agentId: s.agentId } })
+ return
+ }
void projectFrame(s, runtimeProfiles.selectedModel(s))
.then((project) => {
const frame = { type: 'agent_synced', payload: { agent: project } }
@@ -1023,7 +1030,7 @@ async function runForeground(session: AuthSession): Promise<void> {
const auth = new AuthSessionManager(backendHttpBase())
const backend = new BackendSocket(session.machineId ?? session.computerId, auth, (connected) => {
if (!connected) return
- const sessions = registry.active()
+ const sessions = registry.advertised()
console.log(`[cli] connected · ${sessions.length} agent(s) registered`)
void fullReconcile(true).catch((err) => {
console.error('[runtime-profile] connect reconcile failed:', err instanceof Error ? err.message : err)
@@ -2024,13 +2031,21 @@ async function runForeground(session: AuthSession): Promise<void> {
stopHeartbeat(agent.sessionId)
}
console.log(`[discovery] ${sid(agent.agentId)} dormant · ${reason}`)
- backend.send({ type: 'agent_deleted', payload: { agentId: agent.agentId } })
- backend.sendCommander({ type: 'agent_deleted', payload: { agentId: agent.agentId } })
+ announceSession(agent)
},
onRemoved: (agent, reason) => {
console.log(`[discovery] ${sid(agent.agentId)} removed · ${reason}`)
forgetSession(agent.agentId, { force: true })
},
+ onTerminalAvailability: (agent, available) => {
+ const changed = registry.terminalAvailable(agent.agentId) !== available
+ registry.setTerminalAvailable(agent.agentId, available)
+ if (available && changed) announceSession(agent)
+ },
+ onProbeStatus: (status) => {
+ discoveryReady = status.ready
+ discoveryError = status.error
+ },
})
// SessionEnd describes the mutable engine session, never process lifetime. Reconcile now; discovery
@@ -2364,6 +2379,8 @@ async function runForeground(session: AuthSession): Promise<void> {
deviceTransportConnected: backend.hasCommander(),
deviceE2eeConnected: backend.deviceE2eeConnected(),
uptimeSec: Math.round((Date.now() - startedAt) / 1000),
+ discoveryReady,
+ discoveryError,
fingerprint: backend.e2eeFingerprint(),
config: {
watching: `${terminalConfig.backends.join(' + ')} terminals across all supported engines`,
@@ -2385,14 +2402,14 @@ async function runForeground(session: AuthSession): Promise<void> {
dataDir: tildify(env.ADAPTER_DATA_DIR),
port: daemonPort(),
},
- sessions: registry.active().map((s) => ({
+ sessions: registry.advertised().map((s) => ({
id: s.agentId,
sessionId: s.sessionId,
name: projectDisplayName(s),
engine: s.engine,
cwd: tildify(s.cwd ?? ''),
tmuxPane: s.tmuxPane || null,
- terminal: { primary: s.primaryRuntimeKey, runtimes: s.runtimes },
+ terminal: { available: registry.terminalAvailable(s.agentId), primary: s.primaryRuntimeKey, runtimes: s.runtimes },
updatedAt: s.updatedAt,
})),
pairs: backend.listPairs(),
@@ -2550,7 +2567,7 @@ async function runForeground(session: AuthSession): Promise<void> {
}
watcher.start()
await cursorDiscovery.start()
- agentReconciler.start(env.TERMINAL_RECONCILE_INTERVAL_MS ?? env.TMUX_REAP_INTERVAL_MS)
+ await agentReconciler.start(env.TERMINAL_RECONCILE_INTERVAL_MS ?? env.TMUX_REAP_INTERVAL_MS)
for (const task of await loadCursorPendingTasks(env.ADAPTER_DATA_DIR)) {
onCursorTaskStart(task.sessionId, task.toolUseId, task.input)
}
@@ -2565,9 +2582,9 @@ async function runForeground(session: AuthSession): Promise<void> {
if (reconcileInFlight) return reconcileInFlight
reconcileInFlight = (async () => {
await runtimeProfiles.withoutChangeEvents(async () => {
- await Promise.all(registry.list().map((session) => runtimeProfiles.ingestConfig(session, true)))
+ await Promise.all(registry.advertised().map((session) => runtimeProfiles.ingestConfig(session, true)))
await watcher.pollAll()
- await Promise.all(registry.list().map(async (session) => {
+ await Promise.all(registry.advertised().map(async (session) => {
const capture = await captureTerminal(session.agentId, 120)
if (capture) runtimeProfiles.ingestPane(session, capture, true)
}))
@@ -2575,7 +2592,7 @@ async function runForeground(session: AuthSession): Promise<void> {
await syncTerminalTitles()
const includeDevice = reconcileNeedsDeviceAnnouncement
reconcileNeedsDeviceAnnouncement = false
- for (const session of registry.list()) {
+ for (const session of registry.advertised()) {
if (includeDevice) announceSession(session)
else syncSession(session)
}
@@ -3195,20 +3212,26 @@ async function runForeground(session: AuthSession): Promise<void> {
* makes the version one too. Falls back to the local constant when the daemon cannot be reached, which is
* exactly the case where the printing process IS the only build there is.
*/
-async function runningDaemonVersion(): Promise<string> {
+async function runningDaemonStatus(): Promise<{ version: string; sessions: number } | null> {
try {
const res = await fetch(`http://127.0.0.1:${daemonPort()}/api/status`, {
signal: AbortSignal.timeout(1_500),
})
- if (!res.ok) return VERSION
+ if (!res.ok) return null
const body: unknown = await res.json()
- const version = (body as { version?: unknown } | null)?.version
- return typeof version === 'string' && version ? version : VERSION
+ const status = body as { version?: unknown; sessions?: unknown } | null
+ const version = typeof status?.version === 'string' && status.version ? status.version : VERSION
+ const sessions = Array.isArray(status?.sessions) ? status.sessions.length : 0
+ return { version, sessions }
} catch {
- return VERSION
+ return null
}
}
+async function runningDaemonVersion(): Promise<string> {
+ return (await runningDaemonStatus())?.version ?? VERSION
+}
+
// `status` is a definitive state — `launch` only prints this after "[backend] connected" (so it's
// "● connected", never a one-shot never-updating "connecting…"); `status` prints running/stopped.
function printInfoBlock(opts: {
@@ -3229,7 +3252,7 @@ function printInfoBlock(opts: {
console.log(row('version', `v${opts.version}`))
console.log(row('backend', env.BACKEND_WS_URL))
console.log(row('watching', tildify(env.CLAUDE_PROJECTS_DIR)))
- console.log(row('agents', `${opts.sessions} running`))
+ console.log(row('agents', `${opts.sessions} available`))
console.log(row('pid', String(opts.pid)))
console.log(row('logs', tildify(LOG_FILE)))
console.log(row('dashboard', `http://127.0.0.1:${daemonPort()}`))
@@ -3389,13 +3412,13 @@ async function launch(foreground: boolean): Promise<void> {
process.exit(0) // daemon stays alive
}
- registry.load()
+ const daemonStatus = await runningDaemonStatus()
printInfoBlock({
status: '● connected',
pid: child.pid ?? 0,
machineId: session.machineId,
- sessions: registry.list().length,
- version: await runningDaemonVersion(),
+ sessions: daemonStatus?.sessions ?? 0,
+ version: daemonStatus?.version ?? VERSION,
})
process.exit(0)
}
@@ -3896,14 +3919,15 @@ async function status(): Promise<void> {
const alive = pid != null && isAlive(pid)
const session = readAuthSession()
if (!session) { console.log('machine: not signed in. Run: harness login'); process.exit(0) }
- registry.load()
+ const daemonStatus = alive ? await runningDaemonStatus() : null
+ if (!alive) registry.load()
printInfoBlock({
status: alive ? '● running' : '○ stopped',
pid: pid ?? 0,
machineId: session.machineId,
- sessions: registry.list().length,
+ sessions: daemonStatus?.sessions ?? 0,
// A stopped daemon answers nothing, so this falls back to the local build — which is what will run.
- version: alive ? await runningDaemonVersion() : VERSION,
+ version: daemonStatus?.version ?? VERSION,
})
process.exit(0)
}
diff --git a/cli/src/lib/childLocale.spec.ts b/cli/src/lib/childLocale.spec.ts
index f2495edeb..87b4d149a 100644
--- a/cli/src/lib/childLocale.spec.ts
+++ b/cli/src/lib/childLocale.spec.ts
@@ -1,7 +1,7 @@
import { describe, expect, it } from 'vitest'
import { ensureUtf8Locale } from './childLocale.js'
-const linux = process.platform === 'linux'
+const supported = process.platform === 'linux' || process.platform === 'darwin'
describe('ensureUtf8Locale', () => {
/**
@@ -11,19 +11,19 @@ describe('ensureUtf8Locale', () => {
* ZERO panes, so discovery has nowhere to attach the engine process it did find and no agent is ever
* created. Under LC_ALL=C.UTF-8 the same call returns real tabs.
*/
- it.skipIf(!linux)('supplies a UTF-8 locale when the environment has none', () => {
+ it.skipIf(!supported)('supplies a UTF-8 locale when the environment has none', () => {
const env: NodeJS.ProcessEnv = {}
ensureUtf8Locale(env)
expect(env.LC_ALL).toBe('C.UTF-8')
})
- it.skipIf(!linux)('overrides a non-UTF-8 locale', () => {
+ it.skipIf(!supported)('overrides a non-UTF-8 locale', () => {
const env: NodeJS.ProcessEnv = { LANG: 'POSIX' }
ensureUtf8Locale(env)
expect(env.LC_ALL).toBe('C.UTF-8')
})
- it.skipIf(!linux)('leaves a UTF-8 locale the user configured alone', () => {
+ it.skipIf(!supported)('leaves a UTF-8 locale the user configured alone', () => {
for (const key of ['LC_ALL', 'LC_CTYPE', 'LANG'] as const) {
const env: NodeJS.ProcessEnv = { [key]: 'en_US.UTF-8' }
ensureUtf8Locale(env)
@@ -34,9 +34,7 @@ describe('ensureUtf8Locale', () => {
expect(lowercase.LC_ALL).toBeUndefined()
})
- // macOS passes every byte through regardless of locale (verified: default, C.UTF-8 and POSIX all
- // return `⌘` intact from ps), so there is nothing to fix and nothing to risk changing.
- it.skipIf(linux)('does nothing off Linux', () => {
+ it.skipIf(supported)('does nothing on unsupported platforms', () => {
const env: NodeJS.ProcessEnv = {}
ensureUtf8Locale(env)
expect(env.LC_ALL).toBeUndefined()
diff --git a/cli/src/lib/childLocale.ts b/cli/src/lib/childLocale.ts
index fb8714ce4..434ef6733 100644
--- a/cli/src/lib/childLocale.ts
+++ b/cli/src/lib/childLocale.ts
@@ -1,5 +1,5 @@
/**
- * Give this process (and therefore every child it spawns) a UTF-8 locale on Linux.
+ * Give this process (and therefore every child it spawns) a UTF-8 locale on macOS and Linux.
*
* Linux tools sanitize bytes they cannot represent in the current locale, and a daemon usually has NO
* locale at all: `LANG` is unset under systemd, under `docker run`, and in an ssh session that forwards
@@ -21,7 +21,7 @@
* not exist glibc falls back to C, i.e. no worse than doing nothing.
*/
export function ensureUtf8Locale(env: NodeJS.ProcessEnv = process.env): void {
- if (process.platform !== 'linux') return
+ if (process.platform !== 'linux' && process.platform !== 'darwin') return
const configured = env.LC_ALL || env.LC_CTYPE || env.LANG
if (configured && /utf-?8/i.test(configured)) return
env.LC_ALL = 'C.UTF-8'
diff --git a/cli/src/lib/registry.spec.ts b/cli/src/lib/registry.spec.ts
index 42057699b..a794c0177 100644
--- a/cli/src/lib/registry.spec.ts
+++ b/cli/src/lib/registry.spec.ts
@@ -754,6 +754,7 @@ describe('agent identity: the process owns the agent, the session is bound to it
expect(opened?.isNew).toBe(true)
expect(opened?.entry.sessionId).toBe('')
expect(registry.unbound().map((s) => s.agentId)).toEqual(['agent-1'])
+ expect(registry.advertised().map((s) => s.agentId)).toEqual(['agent-1'])
expect(registry.resolve('agent-1')?.agentId).toBe('agent-1')
expect(projectDisplayName(opened!.entry)).toContain('demo') // nameable while unbound
@@ -765,6 +766,20 @@ describe('agent identity: the process owns the agent, the session is bound to it
expect(registry.resolve('s1')?.agentId).toBe('agent-1')
})
+ it('does not advertise persisted terminal locators before this daemon verifies them', async () => {
+ const { registry } = await loadRegistryModule()
+ registry.load()
+ registry.openProcessAgent({ agentId: 'agent-1', engine: 'claude', tmuxPane: '%1', cwd: '/tmp/demo', processIdentity: processIdentity(101) })
+ expect(registry.advertised()).toHaveLength(1)
+
+ registry.load()
+
+ expect(registry.list()).toHaveLength(1)
+ expect(registry.advertised()).toHaveLength(0)
+ registry.setTerminalAvailable('agent-1', true)
+ expect(registry.advertised().map((s) => s.agentId)).toEqual(['agent-1'])
+ })
+
it('keeps the agent id when an unbound launcher becomes a new process in the same pane', async () => {
const { registry } = await loadRegistryModule()
registry.load()
diff --git a/cli/src/lib/registry.ts b/cli/src/lib/registry.ts
index c03f6428e..7fb2d5f9f 100644
--- a/cli/src/lib/registry.ts
+++ b/cli/src/lib/registry.ts
@@ -58,7 +58,7 @@ function modelString(value: unknown): string | null {
export interface RegisteredSession {
/** Per-row marker; the top-level array is retained for backward-reader safety. */
schemaVersion: 2
- /** Dormant records retain identity/bindings but are not advertised until a runtime is verified again. */
+ /** Whether the supported engine process is currently identified; terminal liveness is tracked separately. */
active: boolean
/**
* THE AGENT. Public identity: this is what web tabs, device tiles and every inbound frame address.
@@ -329,6 +329,7 @@ function strictPersistedRow(value: unknown): RegisteredSession | null {
const row = value as Partial<RegisteredSession>
const runtimes = normalizedRuntimes(row.runtimes, row.tmuxPane)
const primary = typeof row.primaryRuntimeKey === 'string' ? row.primaryRuntimeKey : ''
+ const normalizedPrimary = selectedRuntimeKey(runtimes, primary)
const active = row.active === true
const projectedTmuxPane = tmuxProjection(runtimes)
if (row.schemaVersion !== 2
@@ -340,8 +341,10 @@ function strictPersistedRow(value: unknown): RegisteredSession | null {
|| typeof row.primaryRuntimeKey !== 'string'
|| !Array.isArray(row.runtimes) || runtimes.length !== row.runtimes.length || !runtimes.length
|| (projectedTmuxPane ? row.tmuxPane !== projectedTmuxPane : row.tmuxPane !== undefined)
- || (active && !runtimes.some((runtime) => terminalRouteKey(runtime) === primary))
- || (!active && primary !== '')
+ || (primary !== '' && !runtimes.some((runtime) => terminalRouteKey(runtime) === primary))
+ // Older dormant rows intentionally persisted an empty primary. Accept and repair those once; new
+ // rows keep terminal routing independent from engine activity.
+ || (active && primary === '')
|| (row.processIdentity !== null && !validProcessIdentity(row.processIdentity))) return null
const placements = runtimes.map(terminalPlacementKey)
if (new Set(placements).size !== placements.length) return null
@@ -357,7 +360,7 @@ function strictPersistedRow(value: unknown): RegisteredSession | null {
projectDir: row.projectDir,
cwd: typeof row.cwd === 'string' ? row.cwd : null,
runtimes,
- primaryRuntimeKey: primary,
+ primaryRuntimeKey: normalizedPrimary,
tmuxPane: projectedTmuxPane,
source: typeof row.source === 'string' ? row.source : null,
title: typeof row.title === 'string' ? row.title : null,
@@ -533,6 +536,12 @@ class Registry {
private runtimeIndex = new Map<string, string>()
/** engine + PID start marker → agentId. This is authoritative across nested multiplexers. */
private processIndex = new Map<string, string>()
+ /**
+ * Ephemeral terminal liveness, deliberately not persisted. A locator loaded from disk is only a hint
+ * until this daemon has seen the backend placement again. Engine activity and terminal availability
+ * are separate: a trust/setup/shell prompt can remain viewable after the engine process goes dormant.
+ */
+ private terminalAvailableAgents = new Set<string>()
private transactionDepth = 0
private savePending = false
/** Root corruption/unknown schemas are read-only until the operator restores valid bytes. */
@@ -581,6 +590,7 @@ class Registry {
this.sessionIndex.clear()
this.runtimeIndex.clear()
this.processIndex.clear()
+ this.terminalAvailableAgents.clear()
this.writeBlocked = false
this.persistedBaseline.clear()
try {
@@ -702,7 +712,7 @@ class Registry {
: (bound ? rawSessionId : agentId),
tmuxPane: pane,
runtimes,
- primaryRuntimeKey: active ? selectedRuntimeKey(runtimes, raw.primaryRuntimeKey) : '',
+ primaryRuntimeKey: selectedRuntimeKey(runtimes, raw.primaryRuntimeKey),
cwd: typeof raw.cwd === 'string' ? raw.cwd : null,
source: bound && typeof raw.source === 'string' ? raw.source : null,
cliVersion: typeof raw.cliVersion === 'string' ? raw.cliVersion : null,
@@ -812,6 +822,7 @@ class Registry {
if (input.gateway !== undefined) existing.gateway = input.gateway
existing.updatedAt = Date.now()
this.index(existing)
+ this.terminalAvailableAgents.add(existing.agentId)
this.save()
return { entry: existing, isNew: false, evicted: null }
}
@@ -828,6 +839,7 @@ class Registry {
other.primaryRuntimeKey = selectedRuntimeKey(other.runtimes, other.primaryRuntimeKey)
other.active = other.runtimes.length > 0
if (other.runtimes.length) this.index(other)
+ else this.terminalAvailableAgents.delete(other.agentId)
evicted ??= other.sessionId || other.agentId
}
const now = Date.now()
@@ -856,6 +868,7 @@ class Registry {
lastTranscriptAt: now,
}
this.index(entry)
+ this.terminalAvailableAgents.add(entry.agentId)
this.save()
return { entry, isNew: true, evicted }
}
@@ -978,6 +991,7 @@ class Registry {
const entry = this.bySession(sessionId)
if (!entry) return false
this.drop(entry)
+ this.terminalAvailableAgents.delete(entry.agentId)
this.save()
return true
}
@@ -997,6 +1011,7 @@ class Registry {
const entry = this.agents.get(agentId)
if (!entry) return false
this.drop(entry)
+ this.terminalAvailableAgents.delete(agentId)
this.save()
return true
}
@@ -1040,6 +1055,7 @@ class Registry {
entry.active = true
entry.updatedAt = Date.now()
this.index(entry)
+ this.terminalAvailableAgents.add(entry.agentId)
this.save()
return true
}
@@ -1048,12 +1064,23 @@ class Registry {
const entry = this.agents.get(agentId)
if (!entry || entry.active === active) return !!entry
entry.active = active
- entry.primaryRuntimeKey = active ? selectedRuntimeKey(entry.runtimes, entry.primaryRuntimeKey) : ''
entry.updatedAt = Date.now()
this.save()
return true
}
+ /** Mark whether at least one backend placement was verified by this daemon process. */
+ setTerminalAvailable(agentId: string, available: boolean): boolean {
+ if (!this.agents.has(agentId)) return false
+ if (available) this.terminalAvailableAgents.add(agentId)
+ else this.terminalAvailableAgents.delete(agentId)
+ return true
+ }
+
+ terminalAvailable(agentId: string): boolean {
+ return this.terminalAvailableAgents.has(agentId)
+ }
+
/** The one lookup for anything that arrives from outside: web and device address an agent by `agentId`
* for most things but by a bare `sessionId` for turn control, and both must land on the same record. */
resolve(id: string): RegisteredSession | undefined {
@@ -1138,6 +1165,11 @@ class Registry {
return this.list().filter((entry) => entry.active)
}
+ /** The one public list: a verified terminal pane is sufficient even when its engine is dormant. */
+ advertised(): RegisteredSession[] {
+ return this.list().filter((entry) => this.terminalAvailableAgents.has(entry.agentId))
+ }
+
async transaction<T>(apply: () => T | Promise<T>): Promise<T> {
this.transactionDepth++
try {
diff --git a/cli/src/lib/terminalAgentReconciler.spec.ts b/cli/src/lib/terminalAgentReconciler.spec.ts
index 907e3df47..fc30a7b23 100644
--- a/cli/src/lib/terminalAgentReconciler.spec.ts
+++ b/cli/src/lib/terminalAgentReconciler.spec.ts
@@ -34,6 +34,65 @@ function probe(targets: TerminalAgentProbe['targets'], agents: DiscoveredTermina
}
describe('composite terminal reconciliation', () => {
+ it('advertises a retained pane even when no engine process is observed', async () => {
+ const current = { ...session([tmux]), active: false }
+ const onTerminalAvailability = vi.fn()
+ const reconciler = new TerminalAgentReconciler({
+ current: () => [current], backends: [], backendOrder: ['tmux'], herdrSessionOrder: [],
+ onDiscovered: vi.fn(), onObserved: vi.fn(), onDormant: vi.fn(), onRemoved: vi.fn(),
+ onTerminalAvailability,
+ probe: async () => probe([
+ { instanceId: 'tmux:default', result: { state: 'available', roots: [{ runtime: tmux, rootPid: 1, cwd: '/work' }] } },
+ ]),
+ })
+
+ await reconciler.trigger()
+
+ expect(onTerminalAvailability).toHaveBeenCalledWith(current, true)
+ })
+
+ it('still verifies retained panes when the process table is unavailable', async () => {
+ const current = { ...session([tmux]), active: false }
+ const onTerminalAvailability = vi.fn()
+ const onProbeStatus = vi.fn()
+ const reconciler = new TerminalAgentReconciler({
+ current: () => [current], backends: [], backendOrder: ['tmux'], herdrSessionOrder: [],
+ onDiscovered: vi.fn(), onObserved: vi.fn(), onDormant: vi.fn(), onRemoved: vi.fn(),
+ onTerminalAvailability, onProbeStatus,
+ probe: async () => ({
+ processTableAvailable: false,
+ targets: [{ instanceId: 'tmux:default', result: { state: 'available', roots: [{ runtime: tmux, rootPid: 1, cwd: '/work' }] } }],
+ agents: [], ambiguousPlacements: new Set(),
+ }),
+ })
+
+ await reconciler.trigger()
+
+ expect(onTerminalAvailability).toHaveBeenCalledWith(current, true)
+ expect(onProbeStatus).toHaveBeenCalledWith({ ready: true, error: 'process table unavailable' })
+ })
+
+ it('awaits the initial discovery pass before start resolves', async () => {
+ let release!: () => void
+ const pending = new Promise<void>((resolve) => { release = resolve })
+ const probed = vi.fn(async () => {
+ await pending
+ return probe([{ instanceId: 'tmux:default', result: { state: 'available', roots: [] } }])
+ })
+ const reconciler = new TerminalAgentReconciler({
+ current: () => [], backends: [], backendOrder: ['tmux'], herdrSessionOrder: [],
+ onDiscovered: vi.fn(), onObserved: vi.fn(), onDormant: vi.fn(), onRemoved: vi.fn(), probe: probed,
+ })
+ let started = false
+ const start = reconciler.start(60_000).then(() => { started = true })
+ await Promise.resolve()
+ expect(started).toBe(false)
+ release()
+ await start
+ expect(started).toBe(true)
+ reconciler.stop()
+ })
+
it('does not count an unavailable endpoint as a confirmed miss', async () => {
const current = session([herdr])
const onDormant = vi.fn()
@@ -92,7 +151,7 @@ describe('composite terminal reconciliation', () => {
expect(validate).toHaveBeenCalledTimes(2)
})
- it('keeps an agent active when pane-specific validation proves a process missed by the aggregate scan', async () => {
+ it('keeps a pane advertised but marks its missing engine dormant after two scans', async () => {
const current = session([tmux])
const onDormant = vi.fn()
const onRemoved = vi.fn()
@@ -109,7 +168,8 @@ describe('composite terminal reconciliation', () => {
await reconciler.trigger()
expect(validate).toHaveBeenCalledTimes(3)
- expect(onDormant).not.toHaveBeenCalled()
+ expect(onDormant).toHaveBeenCalledTimes(1)
+ expect(onDormant).toHaveBeenCalledWith(current, 'engine process absent after 2 confirmed scans')
expect(onRemoved).not.toHaveBeenCalled()
})
diff --git a/cli/src/lib/terminalAgentReconciler.ts b/cli/src/lib/terminalAgentReconciler.ts
index baf488138..13871218a 100644
--- a/cli/src/lib/terminalAgentReconciler.ts
+++ b/cli/src/lib/terminalAgentReconciler.ts
@@ -21,6 +21,8 @@ export interface TerminalAgentReconcilerDeps {
onObserved: (agent: DiscoveredTerminalAgent, current: RegisteredSession) => void | Promise<void>
onDormant: (current: RegisteredSession, reason: string) => void | Promise<void>
onRemoved: (current: RegisteredSession, reason: string) => void | Promise<void>
+ onTerminalAvailability?: (current: RegisteredSession, available: boolean) => void | Promise<void>
+ onProbeStatus?: (status: { ready: true; error: string | null }) => void
transaction?: <T>(apply: () => T | Promise<T>) => Promise<T>
/** Refresh configured backend instances before each immutable probe cycle. */
beforeProbe?: () => void | Promise<void>
@@ -72,6 +74,7 @@ function unboundRouteObservation(
/** Serialized, failure-isolated reconciliation across every enabled backend instance. */
export class TerminalAgentReconciler {
private readonly misses = new Map<string, number>()
+ private readonly engineMisses = new Map<string, number>()
private readonly suppressed = new Set<string>()
private readonly hints = new Map<string, AgentEngine>()
private pending = false
@@ -80,8 +83,8 @@ export class TerminalAgentReconciler {
constructor(private readonly deps: TerminalAgentReconcilerDeps) {}
- start(intervalMs: number): void {
- void this.trigger()
+ async start(intervalMs: number): Promise<void> {
+ await this.trigger()
this.timer = setInterval(() => { void this.trigger() }, intervalMs)
this.timer.unref?.()
}
@@ -110,6 +113,7 @@ export class TerminalAgentReconciler {
const before = this.deps.current()
const current = before.find((candidate) => currentProcessKey(candidate) === key)
?? unboundRouteOwner(before, observed)
+ if (current) await this.deps.onTerminalAvailability?.(current, true)
if (current) await this.deps.onObserved(observed, current)
else await this.deps.onDiscovered(observed)
const after = this.deps.current()
@@ -149,8 +153,30 @@ export class TerminalAgentReconciler {
this.deps.daemonPid ?? process.pid,
hints,
))
+ const availableTargets = probe.targets.filter((target) => target.result.state === 'available')
+ const livePlacements = new Set(availableTargets.flatMap((target) =>
+ target.result.state === 'available'
+ ? target.result.roots.map((root) => terminalPlacementKey(root.runtime))
+ : []))
+ const probeError = !probe.processTableAvailable
+ ? 'process table unavailable'
+ : probe.targets.length > 0 && availableTargets.length === 0
+ ? probe.targets.map((target) => `${target.instanceId}: ${target.result.state === 'available' ? 'available' : target.result.reason}`).join('; ')
+ : null
+ // Terminal placement liveness does not depend on finding an engine process. This is what keeps a
+ // retained trust/setup/shell pane visible after restart, including when `ps` itself is unavailable.
+ const markVerifiedPlacements = async (): Promise<void> => {
+ for (const current of this.deps.current()) {
+ if (current.runtimes.some((runtime) => livePlacements.has(terminalPlacementKey(runtime)))) {
+ await this.deps.onTerminalAvailability?.(current, true)
+ }
+ }
+ }
+ if (this.deps.transaction) await this.deps.transaction(markVerifiedPlacements)
+ else await markVerifiedPlacements()
if (!probe.processTableAvailable) {
console.warn('[discovery] process table unavailable; keeping existing terminal agents')
+ this.deps.onProbeStatus?.({ ready: true, error: probeError })
return
}
this.hints.clear()
@@ -176,16 +202,26 @@ export class TerminalAgentReconciler {
if (observed) matchedProcesses.add(processIdentityKey(observed.engine, observed.processIdentity))
let nextRuntimes = current.runtimes
+ let terminalVerified = current.runtimes.some((runtime) => livePlacements.has(terminalPlacementKey(runtime)))
for (const runtime of current.runtimes) {
const target = targetForRuntime(probe, runtime)
if (!target || target.result.state !== 'available') continue
const placement = terminalPlacementKey(runtime)
- if (probe.ambiguousPlacements.has(placement)) continue
const replacement = observed?.runtimes.find((candidate) => terminalPlacementKey(candidate) === placement)
const missKey = `${current.agentId}\u0000${placement}`
+ // Inventory is the authority for terminal existence. A live pane without a recognized engine
+ // is a dormant but still viewable agent, not a missing runtime.
+ if (livePlacements.has(placement)) {
+ this.misses.delete(missKey)
+ terminalVerified = true
+ if (replacement) nextRuntimes = mergeTerminalRuntimes(nextRuntimes, [replacement])
+ continue
+ }
+ if (probe.ambiguousPlacements.has(placement)) continue
if (replacement) {
this.misses.delete(missKey)
nextRuntimes = mergeTerminalRuntimes(nextRuntimes, [replacement])
+ terminalVerified = true
continue
}
// The aggregate inventory/process snapshot is deliberately cheap, but it is not stronger
@@ -197,17 +233,16 @@ export class TerminalAgentReconciler {
if (backend && current.processIdentity) {
const validation = await backend.validate(runtime, {
engine: current.engine,
- // Before an engine session exists, the pane is the agent. Claude and other native
- // launchers may replace their process while a first-run prompt is visible; requiring the
- // earlier PID here deletes a perfectly live sessionless tile. A bound session keeps the
- // strict PID/start-marker check so another process cannot inherit its transcript.
- processIdentity: current.sessionId ? current.processIdentity : undefined,
+ // This check answers only whether the terminal placement still exists. Engine/process
+ // identity is reconciled independently from the aggregate process snapshot below.
+ processIdentity: undefined,
}).catch((error: unknown) => ({
state: 'unknown' as const,
reason: error instanceof Error ? error.message : 'terminal validation failed',
}))
if (validation.state === 'alive') {
this.misses.delete(missKey)
+ terminalVerified = true
continue
}
// A timeout/unreadable backend is not evidence that the process exited. Preserve both the
@@ -223,6 +258,20 @@ export class TerminalAgentReconciler {
nextRuntimes = nextRuntimes.filter((candidate) => terminalPlacementKey(candidate) !== placement)
}
+ if (terminalVerified) await this.deps.onTerminalAvailability?.(current, true)
+ if (observed) {
+ this.engineMisses.delete(current.agentId)
+ } else if (current.active && terminalVerified && !current.runtimes.some((runtime) =>
+ probe.ambiguousPlacements.has(terminalPlacementKey(runtime)))) {
+ const misses = (this.engineMisses.get(current.agentId) ?? 0) + 1
+ if (misses >= MISS_LIMIT) {
+ this.engineMisses.delete(current.agentId)
+ await this.deps.onDormant(current, `engine process absent after ${MISS_LIMIT} confirmed scans`)
+ } else {
+ this.engineMisses.set(current.agentId, misses)
+ }
+ }
+
if (observed) {
const availableInstances = new Set(probe.targets
.filter((target) => target.result.state === 'available')
@@ -237,6 +286,7 @@ export class TerminalAgentReconciler {
await this.deps.onObserved(merged, current)
} else if (nextRuntimes.length < current.runtimes.length) {
if (nextRuntimes.length === 0) {
+ await this.deps.onTerminalAvailability?.(current, false)
await this.deps.onRemoved(current, `terminal runtime absent after ${MISS_LIMIT} confirmed scans`)
} else {
await this.deps.onObserved({
@@ -262,5 +312,8 @@ export class TerminalAgentReconciler {
if (this.deps.transaction) await this.deps.transaction(apply)
else await apply()
+ // Readiness is published last: clients must never observe ready=true between the inventory read and
+ // the authoritative availability/registry update.
+ this.deps.onProbeStatus?.({ ready: true, error: probeError })
}
}
diff --git a/cli/src/lib/tmux.ts b/cli/src/lib/tmux.ts
index a1ceea8a6..114ca2303 100644
--- a/cli/src/lib/tmux.ts
+++ b/cli/src/lib/tmux.ts
@@ -27,13 +27,15 @@ function cleanPaneTitle(title: string): string | null {
/** Current tmux pane titles keyed by pane id. AI CLIs update this with their live session title. */
export function listPaneTitles(): Promise<Map<string, string>> {
return new Promise((resolve) => {
- execFile('tmux', ['list-panes', '-a', '-F', '#{pane_id}\t#{pane_title}'], { timeout: 2000 }, (err, stdout) => {
+ execFile('tmux', ['list-panes', '-a', '-F', '#{pane_id}|#{pane_title}'], { timeout: 2000 }, (err, stdout) => {
const titles = new Map<string, string>()
if (err) { resolve(titles); return }
for (const line of stdout.split('\n')) {
- const [pane, ...titleParts] = line.split('\t')
+ const separator = line.indexOf('|')
+ if (separator < 0) continue
+ const pane = line.slice(0, separator)
if (!/^%\d+$/.test(pane)) continue
- const title = cleanPaneTitle(titleParts.join('\t'))
+ const title = cleanPaneTitle(line.slice(separator + 1))
if (title) titles.set(pane, title)
}
resolve(titles)
diff --git a/cli/src/lib/tmuxAgentDiscovery.spec.ts b/cli/src/lib/tmuxAgentDiscovery.spec.ts
index 41152580f..5c4c77f79 100644
--- a/cli/src/lib/tmuxAgentDiscovery.spec.ts
+++ b/cli/src/lib/tmuxAgentDiscovery.spec.ts
@@ -6,6 +6,7 @@ import type { RegisteredSession } from './registry.js'
import {
TmuxAgentReconciler,
discoverTmuxAgentsFromSnapshot,
+ parsePanes,
runtimeKey,
type DiscoveredTmuxAgent,
type TmuxAgentProbe,
@@ -25,6 +26,13 @@ const ownership = (cursor: string[] = [], grok: string[] = []): AgentCommandOwne
grokCandidates: [],
})
+it('parses printable tmux separators without truncating a pipe in cwd', () => {
+ expect(parsePanes('%1|42|/work/a|b\n%2|84|/tmp\n')).toEqual([
+ { tmuxPane: '%1', rootPid: 42, cwd: '/work/a|b' },
+ { tmuxPane: '%2', rootPid: 84, cwd: '/tmp' },
+ ])
+})
+
describe('tmux process agent snapshot discovery', () => {
const fixtures: Array<[AgentEngine, string, string]> = [
['claude', 'claude', 'claude'],
diff --git a/cli/src/lib/tmuxAgentDiscovery.ts b/cli/src/lib/tmuxAgentDiscovery.ts
index f6955f4e8..3385d0d07 100644
--- a/cli/src/lib/tmuxAgentDiscovery.ts
+++ b/cli/src/lib/tmuxAgentDiscovery.ts
@@ -75,10 +75,14 @@ function execText(command: string, args: string[], timeout: number): Promise<{ o
export function parsePanes(stdout: string): TmuxPaneSnapshot[] {
const panes: TmuxPaneSnapshot[] = []
for (const line of stdout.split('\n')) {
- const [tmuxPane, pidText, ...cwdParts] = line.split('\t')
+ const first = line.indexOf('|')
+ const second = first < 0 ? -1 : line.indexOf('|', first + 1)
+ if (first < 0 || second < 0) continue
+ const tmuxPane = line.slice(0, first)
+ const pidText = line.slice(first + 1, second)
const rootPid = Number(pidText)
if (!/^%\d+$/.test(tmuxPane) || !Number.isSafeInteger(rootPid) || rootPid <= 0) continue
- panes.push({ tmuxPane, rootPid, cwd: cwdParts.join('\t') })
+ panes.push({ tmuxPane, rootPid, cwd: line.slice(second + 1) })
}
return panes
}
@@ -89,7 +93,9 @@ export type TmuxPaneInventory =
/** One bounded tmux inventory read, shared by discovery and the neutral backend adapter. */
export async function listTmuxPanes(): Promise<TmuxPaneInventory> {
- const result = await execText('tmux', ['list-panes', '-a', '-F', '#{pane_id}\t#{pane_pid}\t#{pane_current_path}'], 2_000)
+ // Printable delimiters survive tmux's POSIX-locale output sanitiser. Split only the two fixed
+ // separators so a legitimate `|` in pane_current_path remains part of the path.
+ const result = await execText('tmux', ['list-panes', '-a', '-F', '#{pane_id}|#{pane_pid}|#{pane_current_path}'], 2_000)
return result.ok ? { ok: true, panes: parsePanes(result.stdout) } : result
}
diff --git a/cli/src/webui.ts b/cli/src/webui.ts
index 063a1b4d7..aa130856d 100644
--- a/cli/src/webui.ts
+++ b/cli/src/webui.ts
@@ -258,7 +258,9 @@ function render(s){
d.innerHTML = '<span class="dot '+(deviceOnline?'on':deviceTransport?'idle':'off')+'"></span> <span class="mut">device '+(deviceOnline?'connected':deviceTransport?'pairing':'offline')+'</span>';
document.getElementById('agent').textContent = (s.agentId||'').slice(0,8) || '—';
const nAgents = (s.sessions||[]).length;
- document.getElementById('agents').textContent = nAgents === 0 ? 'no agents' : nAgents + (nAgents === 1 ? ' agent' : ' agents');
+ document.getElementById('agents').textContent = s.discoveryReady === false
+ ? 'discovering terminal agents…'
+ : nAgents === 0 ? 'no agents' : nAgents + (nAgents === 1 ? ' agent' : ' agents');
document.getElementById('uptime').textContent = fmtDur(s.uptimeSec);
document.getElementById('fp').textContent = s.fingerprint || '—';
const wl = document.getElementById('weblink');
@@ -266,9 +268,11 @@ function render(s){
// sessions
const se = document.getElementById('sessions');
- se.innerHTML = (s.sessions&&s.sessions.length) ? s.sessions.map(x =>
+ se.innerHTML = s.discoveryReady === false
+ ? '<div class="empty">Discovering terminal agents…</div>'
+ : (s.sessions&&s.sessions.length) ? s.sessions.map(x =>
'<div class="row"><div class="main"><div class="name">'+esc(x.name)+'</div><div class="sub">'+esc(x.cwd||'')+' · '+esc((x.terminal&&x.terminal.primary)||x.tmuxPane||'')+'</div></div><div class="mut" style="font-size:12px">'+fmtWhen(x.updatedAt)+'</div></div>'
- ).join('') : '<div class="empty">No active terminal agents.</div>';
+ ).join('') : '<div class="empty">'+(s.discoveryError ? esc('Terminal discovery unavailable: '+s.discoveryError) : 'No terminal agents.')+'</div>';
// pairs
const pe = document.getElementById('pairs');