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
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { commandAvailableInInteractiveShell } from '../../lib/engineLaunch.js'
import type { RegisteredSession } from '../../lib/registry.js'
import { resolvePaneEngineProcess } from '../../lib/paneEngineProcess.js'
import type { TerminalBackend } from '../../lib/terminalBackend.js'
import { createPaneWatcher, type PaneWatcherDeps } from './newPane.js'
vi.mock('../../lib/paneEngineProcess.js', async (real) => ({
...await real<object>(),
resolvePaneEngineProcess: vi.fn(async () => null),
}))
vi.mock('../../lib/engineLaunch.js', async (real) => ({ ...await real<object>(), commandAvailableInInteractiveShell: vi.fn(async () => true) }))
const pending = { agentId: 'a1', sessionId: '', engine: 'claude', runtimes: [{ backend: 'tmux', paneId: '%7' }] } as RegisteredSession
const runtime = { backend: 'tmux', paneId: '%7' }
const spawned = { runtime } as never
const identity = { pid: 99, startMarker: 'now' }
// The pane's backend: what the watcher asks about the pane it opened.
const paneState = vi.fn<TerminalBackend['paneState']>(async () => ({ dead: false, engineExit: null }) as never)
const releaseHold = vi.fn<TerminalBackend['releaseHold']>(async () => {})
const backend = { paneState, releaseHold } as unknown as TerminalBackend
/** The pane's own backend, answering whether it holds the launch's inert shell (`TerminalBackend.isHeld`). */
const holding = (isHeld: TerminalBackend['isHeld']): Partial<PaneWatcherDeps> => ({ terminals: { backendFor: vi.fn(() => ({ ...backend, isHeld }) as TerminalBackend) } })
function setup(over: Partial<PaneWatcherDeps> = {}) {
const rows = new Map<string, RegisteredSession>([['a1', pending]])
const deps: PaneWatcherDeps = {
registry: {
byAgent: vi.fn((agentId: string) => rows.get(agentId)),
updateProcessIdentity: vi.fn(),
setLaunch: vi.fn((_agentId: string, launch: { state: string }) => ({ ...pending, launch }) as RegisteredSession),
setTerminalAvailable: vi.fn(() => true),
releaseEngine: vi.fn(() => ({ ...pending, engine: 'terminal' }) as RegisteredSession),
} as unknown as PaneWatcherDeps['registry'],
announceSession: vi.fn(),
triggerHint: vi.fn(async () => {}),
captureTerminal: vi.fn(async () => 'error: unknown flag --plan'),
retainExitedSession: vi.fn(),
terminals: { backendFor: vi.fn(() => backend) },
...over,
}
return { deps, rows, watch: createPaneWatcher(deps) }
}
describe('watching a new pane', () => {
it.each(['held', 'row removed', 'not held', 'unknown', 'no probe'] as const)('retains a post-rc native guard hold without failing or archiving: %s', async result => {
const entry = { ...pending, launch: { state: 'starting', nativeToken: 'fixture-native' } } as RegisteredSession
const waitingPane = vi.fn(async () => result === 'unknown' ? 'unknown' as const : result === 'held' || result === 'row removed')
const { deps, rows, watch } = setup(result === 'no probe' ? {} : holding(waitingPane))
rows.set('a1', entry)
if (result === 'row removed') vi.mocked(deps.registry.setLaunch).mockReturnValue(null)
const watching = watch('claude', entry, spawned, ['claude'], undefined, 1)
await vi.advanceTimersByTimeAsync(50)
await watching
expect(deps.retainExitedSession).not.toHaveBeenCalled()
expect(deps.registry.releaseEngine).not.toHaveBeenCalled()
if (result === 'held' || result === 'row removed') {
expect(deps.registry.setLaunch).toHaveBeenCalledWith('a1', expect.objectContaining({ state: 'held', service: 'native', nativeToken: 'fixture-native' }))
expect(deps.announceSession).toHaveBeenCalledTimes(result === 'held' ? 1 : 0)
} else expect(deps.registry.setLaunch).toHaveBeenCalledWith('a1', expect.objectContaining({ state: 'held', service: 'native', nativeToken: 'fixture-native' }))
})
beforeEach(() => {
vi.useFakeTimers()
vi.spyOn(console, 'log').mockImplementation(() => {})
vi.spyOn(console, 'warn').mockImplementation(() => {})
vi.mocked(resolvePaneEngineProcess).mockReset().mockResolvedValue(null)
paneState.mockReset().mockResolvedValue({ dead: false, engineExit: null } as never)
releaseHold.mockClear()
vi.mocked(commandAvailableInInteractiveShell).mockReset().mockResolvedValue(true)
})
afterEach(() => { vi.useRealTimers(); vi.restoreAllMocks() })
it('asks a ptyhost pane\'s own backend whether it holds the launch, never tmux', async () => {
const pty = { backend: 'ptyhost' as const, instance: 'p1', paneId: '%7' }
const entry = { ...pending, runtimes: [pty], launch: { state: 'starting', nativeToken: 'fixture-native' } } as RegisteredSession
const isHeld = vi.fn(async () => true as const)
const ptyBackend = { ...backend, isHeld } as TerminalBackend
const backendFor = vi.fn(() => ptyBackend)
const { deps, rows, watch } = setup({ terminals: { backendFor } })
rows.set('a1', entry)
await watch('claude', entry, { runtime: pty }, ['claude'], undefined, 1)
expect(backendFor).toHaveBeenCalledWith(pty)
expect(isHeld).toHaveBeenCalledExactlyOnceWith(pty, 'fixture-native')
expect(deps.registry.setLaunch).toHaveBeenCalledWith('a1', expect.objectContaining({ state: 'held', service: 'native', nativeToken: 'fixture-native' }))
})
it.each(['token', 'route', 'binding', 'removed', 'stopped', 'ready'] as const)('discards a delayed native hold after its %s changes', async change => {
const entry = { ...pending, launch: { state: 'starting', nativeToken: 'original' } } as RegisteredSession
let finish!: (waiting: true) => void
const waitingPane = vi.fn(() => new Promise<true>(done => { finish = done }))
const { deps, rows, watch } = setup(holding(waitingPane))
rows.set('a1', entry)
const watching = watch('claude', entry, spawned, ['claude'], undefined)
await vi.advanceTimersByTimeAsync(0)
expect(waitingPane).toHaveBeenCalledOnce()
const replacement = structuredClone(entry)
if (change === 'token') replacement.launch = { state: 'starting', nativeToken: 'replacement' }
if (change === 'route') replacement.runtimes = [{ backend: 'tmux', paneId: '%8' }]
if (change === 'binding') replacement.sessionId = 'new-conversation'
if (change === 'stopped') replacement.active = false
if (change === 'ready') replacement.launch = { state: 'ready' }
if (change === 'removed') rows.delete('a1'); else rows.set('a1', replacement)
finish(true)
await watching
expect(deps.registry.setLaunch).not.toHaveBeenCalled()
expect(deps.announceSession).not.toHaveBeenCalled()
expect(rows.get('a1')).toEqual(change === 'removed' ? undefined : replacement)
})
it.each(['before probe', 'process', 'state', 'installed', 'capture', 'clear', 'sleep'] as const)(
'fences native watcher effects when superseded at %s', async stage => {
const entry = { ...pending, launch: { state: 'starting', nativeToken: 'original' } } as RegisteredSession
const { deps, rows, watch } = setup()
rows.set('a1', entry)
const replace = () => rows.set('a1', { ...entry, launch: { state: 'starting', nativeToken: 'replacement' } })
if (stage === 'before probe') replace()
if (stage === 'process') vi.mocked(resolvePaneEngineProcess).mockImplementationOnce(async () => { replace(); return identity as never })
if (stage === 'state') paneState.mockImplementationOnce(async () => { replace(); return 'gone' })
if (stage === 'installed') {
paneState.mockResolvedValueOnce({ dead: true, engineExit: null } as never)
vi.mocked(commandAvailableInInteractiveShell).mockImplementationOnce(async () => { replace(); return false })
}
if (stage === 'capture' || stage === 'clear') {
paneState.mockResolvedValueOnce({ dead: false, engineExit: 2 } as never)
if (stage === 'capture') vi.mocked(deps.captureTerminal).mockImplementationOnce(async () => { replace(); return 'old exit' })
else releaseHold.mockImplementationOnce(async () => { replace() })
}
const watching = watch('claude', entry, spawned, ['claude'], undefined, 1)
await vi.advanceTimersByTimeAsync(0)
if (stage === 'sleep') replace()
await vi.advanceTimersByTimeAsync(50)
await watching
expect(deps.registry.setLaunch).not.toHaveBeenCalled()
expect(deps.registry.updateProcessIdentity).not.toHaveBeenCalled()
expect(deps.registry.releaseEngine).not.toHaveBeenCalled()
expect(deps.retainExitedSession).not.toHaveBeenCalled()
})
it('marks the agent ready once its engine process shows up, and asks discovery to bind it', async () => {
const { deps, watch } = setup()
vi.mocked(resolvePaneEngineProcess).mockResolvedValueOnce(null).mockResolvedValueOnce(identity as never)
const done = watch('claude', pending, spawned, ['claude'], undefined)
await vi.advanceTimersByTimeAsync(50)
await done
expect(deps.registry.updateProcessIdentity).toHaveBeenCalledWith('a1', identity)
expect(deps.registry.setLaunch).toHaveBeenCalledWith('a1', { state: 'ready' })
expect(deps.terminals.backendFor).toHaveBeenCalledWith(runtime)
expect(resolvePaneEngineProcess).toHaveBeenCalledWith(backend, runtime, 'claude')
expect(paneState).toHaveBeenCalledWith(runtime)
expect(releaseHold).toHaveBeenCalledWith(runtime)
expect(deps.announceSession).toHaveBeenCalledWith(expect.objectContaining({ launch: { state: 'ready' } }))
expect(deps.triggerHint).toHaveBeenCalledWith(runtime, 'claude')
})
it('says so when the background bind fails, and announces nothing for a row the registry no longer has', async () => {
const warn = vi.mocked(console.warn)
const { deps, watch } = setup({ triggerHint: vi.fn(async () => { throw new Error('scan failed') }) })
vi.mocked(deps.registry.setLaunch).mockReturnValueOnce(null)
vi.mocked(resolvePaneEngineProcess).mockResolvedValueOnce(identity as never)
await watch('claude', pending, spawned, ['claude'], undefined)
await vi.advanceTimersByTimeAsync(0)
expect(deps.announceSession).not.toHaveBeenCalled()
const worse = setup({ triggerHint: vi.fn(async () => { throw 'worse' }) })
vi.mocked(resolvePaneEngineProcess).mockResolvedValueOnce(identity as never)
await worse.watch('claude', pending, spawned, ['claude'], undefined)
await vi.advanceTimersByTimeAsync(0)
expect(warn.mock.calls.map(([line]) => String(line)).filter((line) => line.includes('background bind failed'))).toEqual([
'[agent] background bind failed · claude · scan failed',
'[agent] background bind failed · claude · worse',
])
})
it('stops watching an agent that was removed meanwhile', async () => {
const { deps, rows, watch } = setup()
rows.clear()
await watch('claude', pending, spawned, ['claude'], undefined)
expect(resolvePaneEngineProcess).not.toHaveBeenCalled()
expect(deps.announceSession).not.toHaveBeenCalled()
})
it('marks the terminal unavailable when the pane is gone', async () => {
const { deps, watch } = setup()
paneState.mockResolvedValueOnce('gone')
await watch('claude', pending, spawned, ['claude'], undefined)
expect(deps.registry.setTerminalAvailable).toHaveBeenCalledWith('a1', false)
expect(deps.announceSession).toHaveBeenCalledWith(pending)
})
it('asks again when tmux could not say, and finds the engine once it can', async () => {
// A read that timed out while the daemon's event loop was held, then the engine it was looking for.
const { deps, watch } = setup()
paneState.mockResolvedValueOnce('unknown')
vi.mocked(resolvePaneEngineProcess).mockResolvedValueOnce(null).mockResolvedValueOnce({ pid: 7, executable: 'claude', startMarker: 'm' })
const done = watch('claude', pending, spawned, ['claude'], undefined)
await vi.advanceTimersByTimeAsync(50)
await done
expect(deps.registry.setTerminalAvailable).not.toHaveBeenCalled()
expect(deps.registry.setLaunch).toHaveBeenCalledWith('a1', { state: 'ready' })
})
it('fails a launch whose pane died: not installed, or did not start', async () => {
const { deps, watch } = setup()
paneState.mockResolvedValue({ dead: true, engineExit: null } as never)
await watch('claude', pending, spawned, ['claude'], undefined)
vi.mocked(commandAvailableInInteractiveShell).mockResolvedValueOnce(false)
await watch('claude', pending, spawned, ['claude'], undefined)
expect(vi.mocked(deps.registry.setLaunch).mock.calls.map(([, launch]) => (launch as { error: string }).error)).toEqual(['ENGINE_DID_NOT_START', 'ENGINE_NOT_INSTALLED'])
expect(deps.announceSession).toHaveBeenCalledTimes(2)
vi.mocked(deps.registry.setLaunch).mockReturnValueOnce(null)
await watch('claude', pending, spawned, ['claude'], undefined)
expect(deps.announceSession).toHaveBeenCalledTimes(2)
})
it('keeps a pane whose engine started and exited before it was seen as a terminal, saying why', async () => {
const warn = vi.mocked(console.warn)
const { deps, rows, watch } = setup()
paneState.mockResolvedValue({ dead: false, engineExit: 2 } as never)
await watch('claude', pending, spawned, ['claude'], undefined)
expect(deps.registry.releaseEngine).toHaveBeenCalledWith('a1')
expect(deps.announceSession).toHaveBeenCalledWith(expect.objectContaining({ engine: 'terminal' }))
expect(releaseHold).toHaveBeenCalledWith(runtime, expect.any(Function))
expect(warn.mock.calls.map(([line]) => String(line)).some((line) => line.includes('exited (2) before ready · agent a1 kept as a terminal'))).toBe(true)
// A hook bound a conversation meanwhile: that conversation is kept, the engine not released.
rows.set('a1', { ...pending, sessionId: 's1' } as RegisteredSession)
vi.mocked(deps.captureTerminal).mockResolvedValueOnce(null)
await watch('claude', pending, spawned, ['claude'], undefined)
expect(deps.retainExitedSession).toHaveBeenCalledWith(expect.objectContaining({ sessionId: 's1' }), true)
expect(deps.registry.releaseEngine).toHaveBeenCalledTimes(1)
// Released into nothing: nothing to announce.
rows.set('a1', pending)
vi.mocked(deps.registry.releaseEngine).mockReturnValueOnce(null)
vi.mocked(deps.announceSession).mockClear()
await watch('claude', pending, spawned, ['claude'], undefined)
expect(deps.announceSession).not.toHaveBeenCalled()
})
it('backs off between looks, and gives up on a start that never shows, keeping the terminal', async () => {
const warn = vi.mocked(console.warn)
const { deps, watch } = setup()
const done = watch('claude', pending, spawned, ['claude'], undefined, 3_000)
await vi.advanceTimersByTimeAsync(3_000)
await done
// 50, 100, 200, 400, then every 750 ms.
expect(vi.mocked(resolvePaneEngineProcess).mock.calls.length).toBeGreaterThanOrEqual(6)
expect(vi.mocked(resolvePaneEngineProcess).mock.calls.length).toBeLessThanOrEqual(8)
expect(deps.registry.setLaunch).toHaveBeenCalledWith('a1', { state: 'failed', error: 'START_TIMEOUT', detail: expect.stringContaining('did not expose an engine process') })
expect(deps.announceSession).toHaveBeenCalled()
expect(warn.mock.calls.map(([line]) => String(line))).toContain('[agent] create timed out · claude · agent a1')
vi.mocked(deps.registry.setLaunch).mockReturnValueOnce(null)
vi.mocked(deps.announceSession).mockClear()
await watch('claude', pending, spawned, ['claude'], undefined, 0)
expect(deps.announceSession).not.toHaveBeenCalled()
})
it('reports a pane no configured backend holds, and asks nothing about it', async () => {
const warn = vi.mocked(console.warn)
const { deps, watch } = setup({ terminals: { backendFor: vi.fn(() => undefined) } })
await watch('claude', pending, spawned, ['claude'], undefined)
expect(resolvePaneEngineProcess).not.toHaveBeenCalled()
expect(deps.registry.setLaunch).not.toHaveBeenCalled()
expect(warn.mock.calls.map(([line]) => String(line))).toEqual(['[agent] create watch failed · claude · no terminal backend for tmux:%7'])
})
it('reports a watch that fails', async () => {
const warn = vi.mocked(console.warn)
const { watch } = setup()
vi.mocked(resolvePaneEngineProcess).mockRejectedValueOnce(new Error('ps failed')).mockRejectedValueOnce('worse')
await watch('claude', pending, spawned, ['claude'], undefined)
await watch('claude', pending, spawned, ['claude'], undefined)
expect(warn.mock.calls.map(([line]) => String(line))).toEqual([
'[agent] create watch failed · claude · ps failed',
'[agent] create watch failed · claude · worse',
])
})
})