Loading files
This file is pinned to the selected release. Download the original to open it in your design tool.
b6dddf934This file is pinned to the selected release. Download the original to open it in your design tool.
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'fs'
import { tmpdir } from 'os'
import { join } from 'path'
import type { AgentEngine } from '../engines/types.js'
import type { ProcessIdentity, RegisteredSession, RegisterInput } from './registry.js'
let dataDir = ''
const processIdentity = (pid: number) => ({
pid,
executable: 'claude',
startMarker: `Mon Aug 10 10:00:${String(pid % 60).padStart(2, '0')} 2026`,
})
function writeLegacyStateFile(path: string, value: string): void {
writeFileSync(path, value, { mode: 0o644 })
chmodSync(path, 0o644)
}
function registerProcess(
registry: {
byPaneEngine: (pane: string, engine: AgentEngine) => RegisteredSession | undefined
openProcessAgent: (input: {
agentId?: string
engine: AgentEngine
tmuxPane: string
cwd?: string | null
processIdentity: ProcessIdentity
}) => unknown
register: (input: RegisterInput) => {
entry: RegisteredSession
isNew: boolean
evicted: string | null
rebound: string | null
orphaned: { agentId: string; sessionId: string } | null
} | null
},
input: RegisterInput,
) {
const pane = String(input.tmuxPane ?? '')
const engine = input.engine ?? 'claude'
if (pane && !registry.byPaneEngine(pane, engine)) {
registry.openProcessAgent({
agentId: input.launcherId,
engine,
tmuxPane: pane,
cwd: input.cwd,
processIdentity: processIdentity(100 + Number(pane.slice(1) || 0)),
})
}
return registry.register(input)
}
async function loadRegistryModule() {
vi.resetModules()
process.env.ADAPTER_DATA_DIR = dataDir
process.env.CLAUDE_PROJECTS_DIR = dataDir
process.env.CODEX_HOME = dataDir
process.env.CURSOR_HOME = dataDir
return import('./registry.js')
}
describe('registry remote display names', () => {
beforeEach(() => {
vi.useFakeTimers()
dataDir = mkdtempSync(join(tmpdir(), 'adapter-registry-'))
})
afterEach(() => {
vi.useRealTimers()
rmSync(dataDir, { recursive: true, force: true })
delete process.env.ADAPTER_DATA_DIR
delete process.env.CLAUDE_PROJECTS_DIR
delete process.env.CODEX_HOME
delete process.env.CURSOR_HOME
})
it('persists renamed display names independently from session removal', async () => {
const transcriptPath = join(dataDir, 'session-1.jsonl')
writeFileSync(transcriptPath, '{}\n')
const { registry, projectDisplayName } = await loadRegistryModule()
registry.load()
const registered = registerProcess(registry, { launcherId: 'h1', sessionId: 'session-1', transcriptPath, tmuxPane: '%1', cwd: '/tmp/demo' })
expect(registered?.entry).toBeTruthy()
expect(JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf-8'))).toMatchObject([
{ sessionId: 'session-1', transcriptPath },
])
const renamed = registry.rename('session-1', 'Production API')
expect(renamed).toBeTruthy()
expect(projectDisplayName(registered!.entry)).toBe('Production API')
const persisted = JSON.parse(readFileSync(join(dataDir, 'agent-names.json'), 'utf-8')) as Record<string, string>
expect(persisted).toEqual({ 'session-1': 'Production API' })
registry.remove('session-1')
expect(registry.get('session-1')).toBeUndefined()
expect(JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf-8'))).toEqual([])
expect(JSON.parse(readFileSync(join(dataDir, 'agent-names.json'), 'utf-8'))).toEqual({ 'session-1': 'Production API' })
})
it('loads persisted names for active sessions', async () => {
const transcriptPath = join(dataDir, 'session-2.jsonl')
writeFileSync(transcriptPath, '{}\n')
chmodSync(dataDir, 0o755)
writeLegacyStateFile(join(dataDir, 'agent-names.json'), JSON.stringify({ 'session-2': 'Research box' }))
writeLegacyStateFile(join(dataDir, 'registry.json'), JSON.stringify([{
launcherId: 'h1',
sessionId: 'session-2',
transcriptPath,
projectDir: 'tmp-demo',
cwd: '/tmp/demo',
tmuxPane: '%2',
source: null,
title: null,
model: null,
registeredAt: 1,
updatedAt: 1,
}]))
const { registry, projectDisplayName } = await loadRegistryModule()
registry.load()
const session = registry.get('session-2')
expect(session).toBeTruthy()
expect(session?.engine).toBe('claude')
expect(projectDisplayName(session!)).toBe('Research box')
expect(JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf-8'))[0]).toMatchObject({
sessionId: 'session-2',
engine: 'claude',
tmuxPane: '%2',
})
expect(statSync(dataDir).mode & 0o777).toBe(0o700)
expect(statSync(join(dataDir, 'agent-names.json')).mode & 0o777).toBe(0o600)
expect(statSync(join(dataDir, 'registry.json')).mode & 0o777).toBe(0o600)
})
it('auto-follows the tmux pane title until renamed, then the manual name stays fixed', async () => {
const transcriptPath = join(dataDir, 'session-title.jsonl')
writeFileSync(transcriptPath, '{}\n')
const { registry, projectDisplayName } = await loadRegistryModule()
registry.load()
const registered = registerProcess(registry, {
launcherId: 'h1',
sessionId: 'session-title',
transcriptPath,
tmuxPane: '%7',
cwd: '/tmp/demo',
title: '📋 ✳ Clarify assistant identity',
})
expect(registered?.entry).toBeTruthy()
expect(registered?.entry.title).toBe('Clarify assistant identity')
// Un-renamed: display auto-follows the tmux title.
expect(projectDisplayName(registered!.entry)).toBe('Clarify assistant identity')
const updated = registry.updateTitle('session-title', '🧪 — * Ship settings page')
expect(updated?.title).toBe('Ship settings page')
expect(projectDisplayName(updated!)).toBe('Ship settings page')
// After a manual rename the override wins and is FIXED — it must NOT drift back to the title.
registry.rename('session-title', 'Manual name')
expect(projectDisplayName(updated!)).toBe('Manual name')
// A later tmux-title change (Claude rewrites it to the latest topic) does not move the display name.
const retitled = registry.updateTitle('session-title', '⚡ New convo topic')
expect(retitled?.title).toBe('New convo topic') // internal title still tracked
expect(projectDisplayName(retitled!)).toBe('Manual name') // display stays fixed
})
it('refuses a pane title that is only the machine\'s own name', async () => {
// Hermes titles its terminal with the hostname and leaves it there. Adopted as a name, every
// hermes agent on this machine is called the same thing — which is strictly worse than the
// folder-and-session default it displaced.
const { hostname } = await import('node:os')
const transcriptPath = join(dataDir, 'session-host.jsonl')
writeFileSync(transcriptPath, '{}\n')
const { registry, projectDisplayName } = await loadRegistryModule()
registry.load()
const registered = registerProcess(registry, {
launcherId: 'h9',
sessionId: 'session-host',
transcriptPath,
tmuxPane: '%9',
cwd: '/tmp/demo',
title: hostname(),
})
expect(registered?.entry.title).toBeNull()
expect(projectDisplayName(registered!.entry)).toBe('demo \u00b7 sess')
// The short form is the same machine wearing another name.
expect(registry.updateTitle('session-host', hostname().split('.')[0])?.title).toBeNull()
// Anything that is genuinely about the conversation still lands.
expect(registry.updateTitle('session-host', 'Ship settings page')?.title).toBe('Ship settings page')
})
it('only adds or updates agent-names.json entries', async () => {
const transcriptPath = join(dataDir, 'session-3.jsonl')
writeFileSync(transcriptPath, '{}\n')
writeLegacyStateFile(join(dataDir, 'agent-names.json'), JSON.stringify({ old: 'Keep me' }))
const { registry } = await loadRegistryModule()
registry.load()
registerProcess(registry, { launcherId: 'h1', sessionId: 'session-3', transcriptPath, tmuxPane: '%3', cwd: '/tmp/demo' })
registry.rename('session-3', 'New name')
expect(JSON.parse(readFileSync(join(dataDir, 'agent-names.json'), 'utf-8'))).toEqual({
old: 'Keep me',
'session-3': 'New name',
})
})
it('persists Codex engine metadata and preserves a malformed v2 row for operator recovery', async () => {
const sessionsDir = join(dataDir, 'sessions')
const transcriptPath = join(sessionsDir, 'codex-session.jsonl')
mkdirSync(sessionsDir)
writeFileSync(transcriptPath, '{}\n')
const { registry } = await loadRegistryModule()
registry.load()
registerProcess(registry, {
launcherId: 'h1',
engine: 'codex',
sessionId: 'codex-session',
transcriptPath,
tmuxPane: '%4',
cwd: '/tmp/codex',
})
const valid = registry.get('codex-session')
expect(valid?.engine).toBe('codex')
const persisted = JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf-8'))
persisted.push({
...persisted[0],
sessionId: 'invalid-session',
tmuxPane: 'not-a-pane',
runtimes: [{ backend: 'tmux', paneId: 'not-a-pane' }],
})
const malformed = JSON.stringify(persisted)
writeFileSync(join(dataDir, 'registry.json'), malformed)
registry.load()
expect(registry.list()).toEqual([])
expect(registry.get('invalid-session')).toBeUndefined()
expect(readFileSync(join(dataDir, 'registry.json'), 'utf-8')).toBe(malformed)
})
it('migrates legacy tmux rows additively without changing agent identity or binding', async () => {
const transcriptPath = join(dataDir, 'legacy.jsonl')
writeFileSync(transcriptPath, '{}\n')
writeLegacyStateFile(join(dataDir, 'registry.json'), JSON.stringify([{
agentId: 'stable-agent',
sessionId: 'legacy-session',
engine: 'claude',
transcriptPath,
projectDir: 'demo',
cwd: '/tmp/demo',
tmuxPane: '%17',
processIdentity: processIdentity(317),
registeredAt: 10,
updatedAt: 20,
}]))
const { registry } = await loadRegistryModule()
registry.load()
expect(registry.get('legacy-session')).toMatchObject({
agentId: 'stable-agent',
tmuxPane: '%17',
runtimes: [{ backend: 'tmux', paneId: '%17' }],
schemaVersion: 2,
// Saved as `updatedAt` before the row's bookkeeping time was named for what it is.
touchedAt: 20,
})
const saved = JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf8'))[0]
expect(saved).toMatchObject({
agentId: 'stable-agent',
tmuxPane: '%17',
runtimes: [{ backend: 'tmux', paneId: '%17' }],
touchedAt: 20,
})
expect(saved).not.toHaveProperty('updatedAt')
expect(JSON.parse(readFileSync(join(dataDir, 'registry.pre-v2.json'), 'utf8'))[0]).toMatchObject({
agentId: 'stable-agent', sessionId: 'legacy-session', tmuxPane: '%17',
})
expect(statSync(join(dataDir, 'registry.pre-v2.json')).mode & 0o777).toBe(0o600)
})
it.each([
['truncated JSON', '[{"agentId":'],
['non-array root', '{"schemaVersion":2}'],
['unknown row schema', JSON.stringify([{ schemaVersion: 99, agentId: 'future' }])],
['nonnumeric row schema', JSON.stringify([{ schemaVersion: '3', agentId: 'future' }])],
['empty legacy row', JSON.stringify([{}])],
['primitive legacy row', JSON.stringify([7])],
['legacy row without runtime', JSON.stringify([{ agentId: 'legacy-agent' }])],
])('preserves %s byte-for-byte and blocks later writes', async (_label, bytes) => {
const file = join(dataDir, 'registry.json')
writeLegacyStateFile(file, bytes)
const { registry } = await loadRegistryModule()
registry.load()
registry.openProcessAgent({
agentId: 'must-not-write',
engine: 'claude',
tmuxPane: '%88',
processIdentity: processIdentity(888),
})
expect(readFileSync(file, 'utf8')).toBe(bytes)
expect(registry.list()).toEqual([])
})
it('rejects a group-writable registry without tightening or overwriting it', async () => {
const file = join(dataDir, 'registry.json')
const bytes = '[]'
writeFileSync(file, bytes, { mode: 0o600 })
chmodSync(file, 0o660)
const { registry } = await loadRegistryModule()
registry.load()
registry.openProcessAgent({
agentId: 'must-not-write',
engine: 'claude',
tmuxPane: '%89',
processIdentity: processIdentity(889),
})
expect(readFileSync(file, 'utf8')).toBe(bytes)
expect(statSync(file).mode & 0o777).toBe(0o660)
expect(registry.list()).toEqual([])
})
it('merges a daemon-down writer committed after load instead of overwriting it', async () => {
const { registry } = await loadRegistryModule()
registry.load()
registry.openProcessAgent({
agentId: 'daemon-agent', engine: 'claude', tmuxPane: '%31', processIdentity: processIdentity(831),
})
const file = join(dataDir, 'registry.json')
const [daemonRow] = JSON.parse(readFileSync(file, 'utf8')) as Array<Record<string, unknown>>
const external = {
...daemonRow,
agentId: 'offline-agent',
sessionId: '',
tmuxPane: '%32',
runtimes: [{ backend: 'tmux', paneId: '%32' }],
primaryRuntimeKey: 'tmux\u0000%32',
processIdentity: processIdentity(832),
}
writeFileSync(file, JSON.stringify([daemonRow, external]), { mode: 0o600 })
registry.updateTitle('daemon-agent', 'updated by daemon')
expect(JSON.parse(readFileSync(file, 'utf8'))).toHaveLength(2)
expect(registry.byAgent('offline-agent')?.processIdentity?.pid).toBe(832)
expect(registry.byAgent('daemon-agent')?.title).toBe('updated by daemon')
})
it('reclaims a crashed lock whose PID has been reused by another process generation', async () => {
const { registry } = await loadRegistryModule()
registry.load()
const lockDir = join(dataDir, 'registry.json.lock')
mkdirSync(lockDir, { mode: 0o700 })
writeFileSync(join(lockDir, 'owner.json'), JSON.stringify({
pid: process.pid,
startMarker: 'different-process-generation',
token: 'stale-owner',
}), { mode: 0o600 })
expect(registry.openProcessAgent({
agentId: 'after-reused-pid-lock',
engine: 'claude',
tmuxPane: '%33',
processIdentity: processIdentity(833),
})?.entry.agentId).toBe('after-reused-pid-lock')
expect(registry.byAgent('after-reused-pid-lock')).toBeTruthy()
})
it('deduplicates nested backends by process identity while scoping Herdr routes to endpoints', async () => {
const { registry } = await loadRegistryModule()
registry.load()
const identity = processIdentity(700)
const tmux = registry.openProcessAgent({
agentId: 'nested-agent',
engine: 'claude',
tmuxPane: '%7',
processIdentity: identity,
})
const herdrRuntime = {
backend: 'herdr' as const,
endpointId: 'herdr:default:abc',
sessionName: 'default',
terminalId: 'terminal-a',
paneId: 'w1:p1',
}
const nested = registry.openProcessAgent({
engine: 'claude',
runtimes: [herdrRuntime],
processIdentity: identity,
})
const other = registry.openProcessAgent({
agentId: 'other-endpoint-agent',
engine: 'claude',
runtimes: [{ ...herdrRuntime, endpointId: 'herdr:work:def', sessionName: 'work', terminalId: 'terminal-b' }],
processIdentity: processIdentity(701),
})
expect(nested?.entry.agentId).toBe(tmux?.entry.agentId)
expect(nested?.entry.runtimes).toHaveLength(2)
expect(other?.entry.agentId).toBe('other-endpoint-agent')
expect(registry.list()).toHaveLength(2)
})
it('persists Herdr-only rows without a legacy tmuxPane projection', async () => {
const { registry } = await loadRegistryModule()
registry.load()
registry.openProcessAgent({
agentId: 'herdr-agent',
engine: 'codex',
runtimes: [{
backend: 'herdr',
endpointId: 'herdr:default:abc',
sessionName: 'default',
terminalId: 'terminal-1',
paneId: 'w1:p1',
}],
processIdentity: processIdentity(900),
})
const [persisted] = JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf8'))
expect(persisted).not.toHaveProperty('tmuxPane')
expect(persisted).toMatchObject({
schemaVersion: 2,
agentId: 'herdr-agent',
runtimes: [{ backend: 'herdr', endpointId: 'herdr:default:abc', paneId: 'w1:p1' }],
})
registry.load()
expect(registry.byAgent('herdr-agent')?.runtimes[0]).toMatchObject({ backend: 'herdr', terminalId: 'terminal-1' })
})
it('repairs a Codex parent registry entry overwritten with a child rollout', async () => {
const parentId = '019f7f1b-195d-70f2-861b-de5d54a3e141'
const childId = '019f8dae-e5f4-7c11-90d1-600854063b2c'
const sessionsDir = join(dataDir, 'sessions', '2026', '07', '23')
mkdirSync(sessionsDir, { recursive: true })
const parentPath = join(sessionsDir, `rollout-${parentId}.jsonl`)
const childPath = join(sessionsDir, `rollout-${childId}.jsonl`)
writeFileSync(parentPath, JSON.stringify({
type: 'session_meta',
payload: { id: parentId, source: 'cli' },
}) + '\n')
writeFileSync(childPath, JSON.stringify({
type: 'session_meta',
payload: {
id: childId,
source: { subagent: { thread_spawn: { parent_thread_id: parentId, depth: 1 } } },
},
}) + '\n')
writeLegacyStateFile(join(dataDir, 'registry.json'), JSON.stringify([{
launcherId: 'h1',
sessionId: parentId,
engine: 'codex',
transcriptPath: childPath,
projectDir: '23',
cwd: '/tmp/codex',
tmuxPane: '%8',
source: null,
title: null,
model: null,
cliVersion: '0.144.6',
processIdentity: null,
registeredAt: 1,
updatedAt: 1,
lastHookAt: 1,
lastTranscriptAt: 1,
}]))
const { registry } = await loadRegistryModule()
registry.load()
expect(registry.get(parentId)?.transcriptPath).toBe(parentPath)
expect(JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf8'))[0].transcriptPath).toBe(parentPath)
expect(registerProcess(registry, {
launcherId: 'h1',
engine: 'codex',
sessionId: parentId,
transcriptPath: childPath,
tmuxPane: '%8',
})).toBeNull()
})
it('keeps the discovered process identity when a Cursor sessionStart omits it', async () => {
const sessionId = '53d3843c-724e-47ff-ae3a-9fedfa328bba'
const transcriptPath = join(
dataDir,
'projects',
'workspace',
'agent-transcripts',
sessionId,
`${sessionId}.jsonl`,
)
mkdirSync(join(transcriptPath, '..'), { recursive: true })
writeFileSync(transcriptPath, '{}\n')
const { registry } = await loadRegistryModule()
registry.load()
registerProcess(registry, {
launcherId: 'h1',
engine: 'cursor',
sessionId,
transcriptPath,
tmuxPane: '%3',
processIdentity: { pid: 100, executable: 'agent', startMarker: 'old' },
hookEvent: 'beforeSubmitPrompt',
})
const resumed = registerProcess(registry, {
launcherId: 'h1',
engine: 'cursor',
sessionId,
transcriptPath,
tmuxPane: '%3',
hookEvent: 'sessionStart',
})
expect(resumed?.entry.processIdentity).toEqual({ pid: 100, executable: 'agent', startMarker: 'old' })
})
it('persists a pending Cursor session and attaches its exact transcript later', async () => {
const { registry } = await loadRegistryModule()
registry.load()
expect(registerProcess(registry, {
launcherId: 'h1',
engine: 'cursor',
sessionId: '12345678-1234-1234-1234-123456789abc',
tmuxPane: '%5',
cwd: '/tmp/cursor',
cliVersion: '2026.07.20-8cc9c0b',
})?.entry.transcriptPath).toBeNull()
registry.load()
expect(registry.get('12345678-1234-1234-1234-123456789abc')?.transcriptPath).toBeNull()
const transcript = join(
dataDir,
'projects',
'workspace',
'agent-transcripts',
'12345678-1234-1234-1234-123456789abc',
'12345678-1234-1234-1234-123456789abc.jsonl',
)
mkdirSync(join(transcript, '..'), { recursive: true })
writeFileSync(transcript, '{}\n')
const attached = registerProcess(registry, {
launcherId: 'h1',
engine: 'cursor',
sessionId: '12345678-1234-1234-1234-123456789abc',
transcriptPath: transcript,
tmuxPane: '%5',
})
expect(attached?.entry.transcriptPath).toBe(transcript)
})
})
describe('registry model coercion', () => {
beforeEach(() => {
vi.useFakeTimers()
dataDir = mkdtempSync(join(tmpdir(), 'adapter-registry-'))
})
afterEach(() => {
vi.useRealTimers()
rmSync(dataDir, { recursive: true, force: true })
delete process.env.ADAPTER_DATA_DIR
delete process.env.CLAUDE_PROJECTS_DIR
delete process.env.CODEX_HOME
delete process.env.CURSOR_HOME
})
// Claude Code's hooks report `model` as {id, display_name}. Persisting that object took the daemon down
// at STARTUP (runtimeProfile called .toLowerCase() on it) — and no restart could heal it, because the bad
// value was already on disk.
it('stores the id when the hook reports a model object', async () => {
const transcriptPath = join(dataDir, 'm1.jsonl')
writeFileSync(transcriptPath, '{}\n')
const { registry } = await loadRegistryModule()
registry.load()
registerProcess(registry, {
launcherId: 'h1',
sessionId: 'm1', transcriptPath, tmuxPane: '%1', cwd: '/tmp/demo',
model: { id: 'claude-opus-4-8', display_name: 'Opus 4.8' } as unknown as string,
})
expect(registry.get('m1')?.model).toBe('claude-opus-4-8')
})
it('keeps a plain string and drops anything else', async () => {
const transcriptPath = join(dataDir, 'm2.jsonl')
writeFileSync(transcriptPath, '{}\n')
const { registry } = await loadRegistryModule()
registry.load()
registerProcess(registry, { launcherId: 'h1', sessionId: 'm2', transcriptPath, tmuxPane: '%1', cwd: '/tmp/demo', model: 'gpt-5.6-sol' })
expect(registry.get('m2')?.model).toBe('gpt-5.6-sol')
// A SECOND launcher, not the same one: one launcher owns one pane owns one agent, so registering
// another session under 'h1' would be a rotation (which inherits the previous model) rather than the
// fresh record this coercion check needs.
registerProcess(registry, { launcherId: 'h2', sessionId: 'm3', transcriptPath, tmuxPane: '%2', cwd: '/tmp/demo', model: 42 as unknown as string })
expect(registry.get('m3')?.model).toBeNull()
})
})
/**
* A Command Code session announces itself BEFORE its transcript exists, so the path used to arrive only
* with the first Stop hook — after the first turn had already failed for want of a watcher.
*/
describe('a Command Code session without a transcript path', () => {
beforeEach(() => {
dataDir = mkdtempSync(join(tmpdir(), 'adapter-registry-cc-'))
})
afterEach(() => {
rmSync(dataDir, { recursive: true, force: true })
delete process.env.COMMANDCODE_HOME
})
it('gets the deterministic one derived from its cwd', async () => {
process.env.COMMANDCODE_HOME = dataDir
const { registry } = await loadRegistryModule()
registry.load()
const registered = registerProcess(registry, {
launcherId: 'h1',
engine: 'commandcode',
sessionId: 'ae93cc89-0dff-452a-a875-33b1516bbc80',
tmuxPane: '%9',
cwd: '/Users/me/Working/Tmux/Agent-6',
})
// The file does not exist yet — that is the whole point. The watcher opens at offset 0 and chokidar
// delivers the lines when the CLI finally writes them.
expect(registered?.entry.transcriptPath).toBe(
join(dataDir, 'projects', 'users-me-working-tmux-agent-6', 'ae93cc89-0dff-452a-a875-33b1516bbc80.jsonl'),
)
})
it('keeps a path the CLI reported over the derived one', async () => {
process.env.COMMANDCODE_HOME = dataDir
const { registry } = await loadRegistryModule()
registry.load()
const reported = join(dataDir, 'projects', 'somewhere-else', 'reported.jsonl')
mkdirSync(join(dataDir, 'projects', 'somewhere-else'), { recursive: true })
writeFileSync(reported, '')
const registered = registerProcess(registry, {
launcherId: 'h1',
engine: 'commandcode',
sessionId: 'reported',
tmuxPane: '%9',
cwd: '/Users/me/Working/Tmux/Agent-6',
transcriptPath: reported,
})
expect(registered?.entry.transcriptPath).toBe(reported)
})
})
/** Grok's SessionStart hook can run while its updates file is still empty or absent. Register the
* deterministic ordinary layout immediately so the first remote prompt is not held waiting for a
* UserPromptSubmit hook that only that same prompt can trigger. */
describe('a Grok session before updates.jsonl exists', () => {
beforeEach(() => {
dataDir = mkdtempSync(join(tmpdir(), 'adapter-registry-grok-'))
process.env.GROK_HOME = dataDir
})
afterEach(() => {
rmSync(dataDir, { recursive: true, force: true })
delete process.env.ADAPTER_DATA_DIR
delete process.env.CLAUDE_PROJECTS_DIR
delete process.env.CODEX_HOME
delete process.env.CURSOR_HOME
delete process.env.GROK_HOME
})
it('derives the URL-encoded cwd path at SessionStart', async () => {
const { registry } = await loadRegistryModule()
registry.load()
const registered = registerProcess(registry, {
launcherId: 'h1',
engine: 'grok',
sessionId: '8184b11d-175e-46cb-9cee-cf41cafe70d2',
tmuxPane: '%9',
cwd: '/workspace/project with spaces',
hookEvent: 'SessionStart',
})
expect(registered?.entry.transcriptPath).toBe(join(
dataDir,
'sessions',
encodeURIComponent('/workspace/project with spaces'),
'8184b11d-175e-46cb-9cee-cf41cafe70d2',
'updates.jsonl',
))
})
})
describe('agent identity: the process owns the agent, the session is bound to it', () => {
beforeEach(() => {
vi.useFakeTimers()
dataDir = mkdtempSync(join(tmpdir(), 'adapter-registry-id-'))
})
afterEach(() => {
vi.useRealTimers()
rmSync(dataDir, { recursive: true, force: true })
delete process.env.ADAPTER_DATA_DIR
delete process.env.CLAUDE_PROJECTS_DIR
delete process.env.CODEX_HOME
delete process.env.CURSOR_HOME
})
function transcript(name: string): string {
const p = join(dataDir, `${name}.jsonl`)
writeFileSync(p, '{}\n')
return p
}
it('resolves a record by EITHER id', async () => {
// Web and device address turn control with a bare sessionId (`cancel`, `question_response`) and
// everything else with the agentId; both have to land on the same record.
const { registry } = await loadRegistryModule()
registry.load()
const res = registerProcess(registry, { launcherId: 'agent-1', sessionId: 's1', transcriptPath: transcript('s1'), tmuxPane: '%1', cwd: '/tmp/demo' })
expect(res?.entry.agentId).toBe('agent-1')
expect(registry.resolve('agent-1')?.sessionId).toBe('s1')
expect(registry.resolve('s1')?.agentId).toBe('agent-1')
expect(registry.byAgent('s1')).toBeUndefined()
expect(registry.bySession('agent-1')).toBeUndefined()
})
it('a rotation rebinds the SAME agent instead of creating a second one', async () => {
// `/clear` in claude (and `/new` in opencode) ends one session id and starts another in the same pane
// under the same launcher. That is one agent with a new session underneath, not two agents.
const { registry } = await loadRegistryModule()
registry.load()
registerProcess(registry, { launcherId: 'agent-1', sessionId: 's1', transcriptPath: transcript('s1'), tmuxPane: '%1', cwd: '/tmp/demo' })
const rot = registerProcess(registry, { launcherId: 'agent-1', sessionId: 's2', transcriptPath: transcript('s2'), tmuxPane: '%1', cwd: '/tmp/demo' })
expect(rot?.rebound).toBe('s1')
expect(rot?.isNew).toBe(true) // the SESSION is new — the caller still announces it
expect(registry.list()).toHaveLength(1)
expect(registry.byAgent('agent-1')?.sessionId).toBe('s2')
expect(registry.bySession('s1')).toBeUndefined() // the dead session no longer resolves
expect(registry.resolve('agent-1')?.boundAt).toBe(Date.now())
})
it('a re-register of the same session is not a rotation, and keeps the folder the row already has', async () => {
const { registry } = await loadRegistryModule()
registry.load()
registerProcess(registry, { launcherId: 'agent-1', sessionId: 's1', transcriptPath: transcript('s1'), tmuxPane: '%1', cwd: '/tmp/demo' })
// Claude's UserPromptSubmit carries the session's tracked SHELL directory, which follows every
// Bash `cd`; the row's folder — what a resume or restore `cd`s into — must not follow it.
const again = registerProcess(registry, { launcherId: 'agent-1', sessionId: 's1', transcriptPath: transcript('s1'), tmuxPane: '%1', cwd: '/tmp/demo/cli' })
expect(again?.isNew).toBe(false)
expect(again?.rebound).toBeNull()
expect(registry.list()).toHaveLength(1)
expect(registry.byAgent('agent-1')?.cwd).toBe('/tmp/demo')
// A rotation is a new session and takes the folder it reports.
const rot = registerProcess(registry, { launcherId: 'agent-1', sessionId: 's2', transcriptPath: transcript('s2'), tmuxPane: '%1', cwd: '/tmp/demo/cli' })
expect(rot?.isNew).toBe(true)
expect(registry.byAgent('agent-1')?.cwd).toBe('/tmp/demo/cli')
})
it('a first bind whose cwd is not the transcript\'s project folder takes the folder from the transcript', async () => {
// A fork inherits its source's drifted cwd; `claude --resume` typed from a subfolder announces
// that subfolder. Claude never moves the transcript out of the project dir it was started in,
// so the file's own directory says which folder is the session's.
const { registry } = await loadRegistryModule()
registry.load()
const project = join(dataDir, 'repo')
const projectDir = join(dataDir, project.replace(/[^A-Za-z0-9]/g, '-'))
mkdirSync(projectDir, { recursive: true })
const path = join(projectDir, 's1.jsonl')
writeFileSync(path, [
JSON.stringify({ type: 'mode' }),
JSON.stringify({ type: 'user', cwd: join(project, 'cli') }),
JSON.stringify({ type: 'user', cwd: project }),
].join('\n') + '\n')
const bound = registerProcess(registry, { launcherId: 'agent-1', sessionId: 's1', transcriptPath: path, tmuxPane: '%1', cwd: join(project, 'cli') })
expect(bound?.isNew).toBe(true)
expect(registry.byAgent('agent-1')?.cwd).toBe(project)
// The folder itself, spelled as given, is accepted as is.
const rot = registerProcess(registry, { launcherId: 'agent-1', sessionId: 's2', transcriptPath: (() => { const p2 = join(projectDir, 's2.jsonl'); writeFileSync(p2, JSON.stringify({ cwd: project }) + '\n'); return p2 })(), tmuxPane: '%1', cwd: project })
expect(rot?.isNew).toBe(true)
expect(registry.byAgent('agent-1')?.cwd).toBe(project)
})
it('re-observing a pane follows the shell until a session is bound, then leaves the folder alone', async () => {
const { registry } = await loadRegistryModule()
registry.load()
registry.openProcessAgent({ agentId: 'agent-1', engine: 'terminal', tmuxPane: '%1', cwd: '/tmp/demo', processIdentity: processIdentity(101) })
registry.openProcessAgent({ engine: 'terminal', tmuxPane: '%1', cwd: '/tmp/demo/cli', processIdentity: processIdentity(101) })
expect(registry.byAgent('agent-1')?.cwd).toBe('/tmp/demo/cli')
registerProcess(registry, { launcherId: 'agent-2', sessionId: 's1', transcriptPath: transcript('s1'), tmuxPane: '%2', cwd: '/tmp/demo' })
registry.openProcessAgent({ engine: 'claude', tmuxPane: '%2', cwd: '/tmp/demo/cli', processIdentity: processIdentity(102) })
expect(registry.byAgent('agent-2')?.cwd).toBe('/tmp/demo')
})
it('one engine session cannot belong to two agents', async () => {
// `claude --resume <id>` in a second pane: the newest bind wins; both live process agents remain.
const { registry } = await loadRegistryModule()
registry.load()
registerProcess(registry, { launcherId: 'agent-1', sessionId: 's1', transcriptPath: transcript('s1'), tmuxPane: '%1', cwd: '/tmp/demo' })
registerProcess(registry, { launcherId: 'agent-2', sessionId: 's1', transcriptPath: transcript('s1'), tmuxPane: '%2', cwd: '/tmp/demo' })
expect(registry.list()).toHaveLength(2)
expect(registry.resolve('s1')?.agentId).toBe('agent-2')
expect(registry.byAgent('agent-1')?.sessionId).toBe('')
})
it('ignores a legacy launcherId and binds to the discovered pane process', async () => {
const { registry } = await loadRegistryModule()
registry.load()
registry.openProcessAgent({ agentId: 'process-agent', engine: 'claude', tmuxPane: '%1', cwd: '/tmp/demo', processIdentity: processIdentity(101) })
const res = registry.register({ launcherId: 'old-launcher', sessionId: 's1', transcriptPath: transcript('s1'), tmuxPane: '%1', cwd: '/tmp/demo' })
expect(res?.entry.agentId).toBe('process-agent')
expect(registry.resolve('old-launcher')).toBeUndefined()
const rot = registry.register({ launcherId: 'different-old-launcher', sessionId: 's2', transcriptPath: transcript('s2'), tmuxPane: '%1', cwd: '/tmp/demo' })
expect(rot?.rebound).toBe('s1')
expect(registry.list()).toHaveLength(1)
})
it('creates an agent at process discovery, before any engine session exists', async () => {
const { registry, projectDisplayName } = await loadRegistryModule()
registry.load()
const opened = registry.openProcessAgent({ agentId: 'agent-1', engine: 'claude', tmuxPane: '%1', cwd: '/tmp/demo', processIdentity: processIdentity(101) })
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
// The engine reports its session later — same agent, now bound.
const bound = registerProcess(registry, { launcherId: 'agent-1', sessionId: 's1', transcriptPath: transcript('s1'), tmuxPane: '%1', cwd: '/tmp/demo' })
expect(bound?.entry.agentId).toBe('agent-1')
expect(registry.list()).toHaveLength(1)
expect(registry.unbound()).toHaveLength(0)
expect(registry.resolve('s1')?.agentId).toBe('agent-1')
})
it('restart contract: updateProcessIdentity swaps ONLY the process, keeping agentId/sessionId/runtimes', async () => {
// This is the primitive a restart handler relies on: exit the engine process, relaunch it in the
// same pane, and rebind the SAME agent to the new process — never look like delete+create.
const { registry } = await loadRegistryModule()
registry.load()
registerProcess(registry, { launcherId: 'agent-1', sessionId: 's1', transcriptPath: transcript('s1'), tmuxPane: '%1', cwd: '/tmp/demo' })
const before = registry.resolve('agent-1')!
// Registry entries are mutated in place (resolve() returns the live object), so the "before"
// snapshot has to be copied — not just referenced — ahead of the swap.
const beforeRuntimes = [...before.runtimes]
const beforePrimary = before.primaryRuntimeKey
const beforeIdentity = { ...before.processIdentity }
const replacement = processIdentity(999)
const ok = registry.updateProcessIdentity('agent-1', replacement)
expect(ok).toBe(true)
const after = registry.resolve('agent-1')!
expect(after.agentId).toBe('agent-1')
expect(after.sessionId).toBe('s1')
expect(after.runtimes).toEqual(beforeRuntimes)
expect(after.primaryRuntimeKey).toBe(beforePrimary)
expect(after.processIdentity).toEqual(replacement)
expect(after.processIdentity).not.toEqual(beforeIdentity)
// Both lookups still resolve to the one record — swapping the process never splits the agent.
expect(registry.resolve('s1')?.agentId).toBe('agent-1')
expect(registry.list()).toHaveLength(1)
})
it('restart contract: updateProcessIdentity also resolves by bare sessionId', async () => {
const { registry } = await loadRegistryModule()
registry.load()
registerProcess(registry, { launcherId: 'agent-1', sessionId: 's1', transcriptPath: transcript('s1'), tmuxPane: '%1', cwd: '/tmp/demo' })
expect(registry.updateProcessIdentity('s1', processIdentity(999))).toBe(true)
expect(registry.byAgent('agent-1')?.processIdentity).toEqual(processIdentity(999))
})
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()
registry.openProcessAgent({
agentId: 'agent-1', engine: 'claude', tmuxPane: '%1', cwd: '/tmp/new-folder',
processIdentity: processIdentity(101),
})
const replaced = registry.openProcessAgent({
engine: 'claude', tmuxPane: '%1', cwd: '/tmp/new-folder', processIdentity: processIdentity(202),
})
expect(replaced?.entry.agentId).toBe('agent-1')
expect(replaced?.entry.sessionId).toBe('')
expect(replaced?.entry.processIdentity).toEqual(processIdentity(202))
expect(replaced?.isNew).toBe(false)
expect(registry.list()).toHaveLength(1)
})
it('does not transfer a bound session to a replacement process in the same pane', async () => {
const { registry } = await loadRegistryModule()
registry.load()
registry.openProcessAgent({
agentId: 'bound-agent', engine: 'claude', tmuxPane: '%1', cwd: '/tmp/demo',
processIdentity: processIdentity(101),
})
registerProcess(registry, {
launcherId: 'bound-agent', sessionId: 's1', transcriptPath: transcript('s1'),
tmuxPane: '%1', cwd: '/tmp/demo',
})
const replacement = registry.openProcessAgent({
agentId: 'replacement-agent', engine: 'claude', tmuxPane: '%1', cwd: '/tmp/demo',
processIdentity: processIdentity(202),
})
expect(replacement?.entry.agentId).toBe('replacement-agent')
expect(replacement?.entry.sessionId).toBe('')
// BOTH ids, because the caller has to finish a removal the registry only
// half did: the agent is already gone from here, so the agentId is the only
// thing clients can be told to drop, and the sessionId the only thing the
// daemon's own per-session state can be cleaned by.
expect(replacement?.evicted).toEqual({
agentId: 'bound-agent',
sessionId: 's1',
})
expect(registry.resolve('s1')).toBeUndefined()
})
it('removes an agent a resume left with no session and no process', async () => {
// `claude --resume` in a second pane after quitting the first: the session
// moves, and the agent it moved from has nothing left to be. Kept, it is a
// second row for the same work that can never be opened — which is exactly
// the "Terminal frozen" tile this removes.
const { registry } = await loadRegistryModule()
registry.load()
registry.openProcessAgent({
agentId: 'old-agent', engine: 'claude', tmuxPane: '%1', cwd: '/tmp/demo',
processIdentity: processIdentity(401),
})
registerProcess(registry, {
launcherId: 'old-agent', sessionId: 's-resume', transcriptPath: transcript('s-resume'),
tmuxPane: '%1', cwd: '/tmp/demo',
})
registry.setActive('old-agent', false) // its engine was quit before the resume
registry.openProcessAgent({
agentId: 'new-agent', engine: 'claude', tmuxPane: '%2', cwd: '/tmp/demo',
processIdentity: processIdentity(402),
})
const bound = registerProcess(registry, {
launcherId: 'new-agent', sessionId: 's-resume', transcriptPath: transcript('s-resume'),
tmuxPane: '%2', cwd: '/tmp/demo',
})
expect(bound?.orphaned).toEqual({ agentId: 'old-agent', sessionId: 's-resume' })
expect(registry.byAgent('old-agent')).toBeUndefined()
expect(registry.byAgent('new-agent')?.sessionId).toBe('s-resume')
})
it('leaves a still-running agent alone when its session is resumed elsewhere', async () => {
// Its engine is alive, so it is a real second agent that merely became
// unbound. Removing it would take a working tile off the screen.
const { registry } = await loadRegistryModule()
registry.load()
registry.openProcessAgent({
agentId: 'live-agent', engine: 'claude', tmuxPane: '%1', cwd: '/tmp/demo',
processIdentity: processIdentity(501),
})
registerProcess(registry, {
launcherId: 'live-agent', sessionId: 's-live', transcriptPath: transcript('s-live'),
tmuxPane: '%1', cwd: '/tmp/demo',
})
registry.openProcessAgent({
agentId: 'other-agent', engine: 'claude', tmuxPane: '%2', cwd: '/tmp/demo',
processIdentity: processIdentity(502),
})
const bound = registerProcess(registry, {
launcherId: 'other-agent', sessionId: 's-live', transcriptPath: transcript('s-live'),
tmuxPane: '%2', cwd: '/tmp/demo',
})
expect(bound?.orphaned).toBeNull()
expect(registry.byAgent('live-agent')).toBeDefined()
expect(registry.byAgent('live-agent')?.sessionId).toBe('')
})
it('reports no eviction when the displaced agent still owns another pane', async () => {
// It lost a terminal, not its life. Announcing it as deleted would take a
// working tile off every client.
const { registry } = await loadRegistryModule()
registry.load()
registry.openProcessAgent({
agentId: 'two-panes',
engine: 'claude',
runtimes: [
{ backend: 'tmux', paneId: '%1' },
{ backend: 'tmux', paneId: '%2' },
],
cwd: '/tmp/demo',
processIdentity: processIdentity(301),
})
const replacement = registry.openProcessAgent({
agentId: 'takes-pane-1', engine: 'codex', tmuxPane: '%1', cwd: '/tmp/demo',
processIdentity: processIdentity(302),
})
expect(replacement?.evicted).toBeNull()
expect(registry.byAgent('two-panes')?.runtimes).toHaveLength(1)
})
it('re-observing the same runtime keeps the session it had already bound', async () => {
const { registry } = await loadRegistryModule()
registry.load()
registry.openProcessAgent({ agentId: 'agent-1', engine: 'claude', tmuxPane: '%1', cwd: '/tmp/demo', processIdentity: processIdentity(101) })
registerProcess(registry, { launcherId: 'agent-1', sessionId: 's1', transcriptPath: transcript('s1'), tmuxPane: '%1', cwd: '/tmp/demo' })
const again = registry.openProcessAgent({ agentId: 'agent-1', engine: 'claude', tmuxPane: '%1', cwd: '/tmp/demo', processIdentity: processIdentity(101) })
expect(again?.isNew).toBe(false)
expect(again?.entry.sessionId).toBe('s1')
expect(registry.list()).toHaveLength(1)
})
it('an unbound agent survives a daemon restart', async () => {
const { registry } = await loadRegistryModule()
registry.load()
registry.openProcessAgent({ agentId: 'agent-1', engine: 'claude', tmuxPane: '%1', cwd: '/tmp/demo', processIdentity: processIdentity(101) })
const { registry: reloaded } = await loadRegistryModule()
reloaded.load()
expect(reloaded.byAgent('agent-1')?.sessionId).toBe('')
expect(reloaded.unbound()).toHaveLength(1)
})
// A row that does not leave `starting` reads as "Starting" on the desk while its engine is working,
// and the state is written from six places that cannot see each other. Each one says so, and a
// settled row says nothing — so a log from a machine where it sticks names the pair doing it.
it('names every launch change by the door it came through, and is silent when nothing changed', async () => {
const { registry } = await loadRegistryModule()
registry.load()
const lines: string[] = []
const log = vi.spyOn(console, 'log').mockImplementation((message: unknown) => {
if (typeof message === 'string' && message.startsWith('[launch]')) lines.push(message)
})
try {
const pending = registry.openPendingAgent({ engine: 'claude', runtimes: [{ backend: 'tmux', paneId: '%7' }], cwd: '/tmp/demo' })!
registry.openProcessAgent({ engine: 'claude', tmuxPane: '%7', cwd: '/tmp/demo', processIdentity: processIdentity(707) })
registry.setLaunch(pending.agentId, { state: 'ready' }) // already ready — silent
registry.setLaunch(pending.agentId, { state: 'failed', error: 'START_TIMEOUT' })
const id = pending.agentId.slice(0, 8)
expect(lines).toEqual([
`[launch] ${id} starting → ready · openProcessAgent re-observed`,
`[launch] ${id} ready → failed · setLaunch (START_TIMEOUT)`,
])
// A bind ends the launch without naming it: the rebuilt row carries none.
lines.length = 0
registry.setLaunch(pending.agentId, { state: 'starting' })
registerProcess(registry, { launcherId: pending.agentId, sessionId: 's1', transcriptPath: transcript('s1'), tmuxPane: '%7', cwd: '/tmp/demo' })
expect(lines.filter(line => line.includes('→ none'))).toHaveLength(1)
} finally {
log.mockRestore()
}
})
it('opens a route-only pending agent and adopts the engine process without changing agentId', async () => {
const { registry } = await loadRegistryModule()
registry.load()
const pending = registry.openPendingAgent({
engine: 'claude',
runtimes: [{ backend: 'tmux', paneId: '%7' }],
cwd: '/tmp/demo',
})
expect(pending).toMatchObject({ sessionId: '', processIdentity: null, launch: { state: 'starting' } })
expect(registry.terminalAvailable(pending!.agentId)).toBe(true)
const adopted = registry.openProcessAgent({
engine: 'claude', tmuxPane: '%7', cwd: '/tmp/demo', processIdentity: processIdentity(707),
})
expect(adopted?.entry.agentId).toBe(pending?.agentId)
expect(adopted?.entry.launch).toEqual({ state: 'ready' })
expect(registry.list()).toHaveLength(1)
})
describe('the name Harness gives an agent: who it is and when it started', () => {
afterEach(() => { vi.useRealTimers() })
const at = (y: number, mo: number, d: number, h: number, mi: number, sec = 0) => {
vi.useFakeTimers({ toFake: ['Date'] })
vi.setSystemTime(new Date(y, mo - 1, d, h, mi, sec))
}
it('is the engine or DSH name and the local time, with no zero where it says nothing', async () => {
const { registry } = await loadRegistryModule()
registry.load()
at(2026, 9, 17, 15, 26)
const codex = registry.openPendingAgent({ engine: 'codex', runtimes: [{ backend: 'tmux', paneId: '%3' }], cwd: '/Users/u/harnesses/codex-2026-09-17-15-26' })!
expect(registry.displayName(codex)).toBe('Codex harness 9-17 15:26')
at(2026, 9, 3, 9, 5)
const blender = registry.openPendingAgent({ engine: 'claude', runtimes: [{ backend: 'tmux', paneId: '%4' }], cwd: '/tmp/b', dsh: 'autonomous/blender', label: ' Blender ' })!
expect(registry.displayName(blender)).toBe('Blender harness 9-3 9:05')
const claude = registry.openPendingAgent({ engine: 'claude', runtimes: [{ backend: 'tmux', paneId: '%5' }], cwd: '/tmp/c', label: ' ' })!
expect(registry.displayName(claude)).toBe('Claude harness 9-3 9:05')
})
it('takes the seconds when the same agent already has that minute, and counts nothing', async () => {
const { registry } = await loadRegistryModule()
registry.load()
at(2026, 12, 25, 15, 26, 8)
const first = registry.openPendingAgent({ engine: 'codex', runtimes: [{ backend: 'tmux', paneId: '%6' }], cwd: '/tmp/a' })!
const second = registry.openPendingAgent({ engine: 'codex', runtimes: [{ backend: 'tmux', paneId: '%7' }], cwd: '/tmp/a' })!
const other = registry.openPendingAgent({ engine: 'claude', runtimes: [{ backend: 'tmux', paneId: '%8' }], cwd: '/tmp/a' })!
expect([first, second, other].map((agent) => registry.displayName(agent)))
.toEqual(['Codex harness 12-25 15:26', 'Codex harness 12-25 15:26:08', 'Claude harness 12-25 15:26'])
expect(registry.agentNamesInUse()).toEqual(expect.arrayContaining(['Codex harness 12-25 15:26', 'Codex harness 12-25 15:26:08']))
})
it('gives way to the session’s title, which moves with it, until a rename fixes a name — and survives reload', async () => {
const { registry } = await loadRegistryModule()
registry.load()
at(2026, 9, 17, 15, 30)
const first = registry.openPendingAgent({ engine: 'opencode', runtimes: [{ backend: 'tmux', paneId: '%7' }], cwd: '/tmp/demo' })!
const second = registry.openPendingAgent({ engine: 'opencode', runtimes: [{ backend: 'tmux', paneId: '%8' }], cwd: '/tmp/demo' })!
expect(registry.displayName(first)).toBe('OpenCode harness 9-17 15:30')
const bound = registry.register({ engine: 'opencode', sessionId: 'session-named-by-time', tmuxPane: '%7', title: 'OC | Greeting' })!.entry
expect(registry.displayName(bound)).toBe('Greeting')
expect(bound.defaultName).toBe('OpenCode harness 9-17 15:30')
registry.updateTitle('session-named-by-time', 'OC | Plan the launch')
expect(registry.displayName(bound)).toBe('Plan the launch')
registry.rename(second.agentId, 'My project')
registry.updateTitle(second.agentId, 'OC | Something else')
expect(registry.displayName(registry.byAgent(second.agentId)!)).toBe('My project')
const { registry: reloaded } = await loadRegistryModule()
reloaded.load()
expect(reloaded.displayName(reloaded.byAgent(first.agentId)!)).toBe('Plan the launch')
expect(reloaded.displayName(reloaded.byAgent(second.agentId)!)).toBe('My project')
})
it('treats a harness-N from an earlier daemon as a name Harness gave, and a title replaces it', async () => {
const { registry } = await loadRegistryModule()
registry.load()
const legacy = registry.openPendingAgent({ engine: 'claude', runtimes: [{ backend: 'tmux', paneId: '%9' }], cwd: '/tmp/old', defaultName: 'harness-42' })!
expect(registry.displayName(legacy)).toBe('harness-42')
registry.updateTitle(legacy.agentId, '✳ Unitree Go2 squats and wave')
expect(registry.displayName(registry.byAgent(legacy.agentId)!)).toBe('Unitree Go2 squats and wave')
})
it('keeps a name the creator asked for through titles, binding and reload; blank means Harness names it', async () => {
const { registry } = await loadRegistryModule()
registry.load()
at(2026, 9, 17, 16, 0)
const named = registry.openPendingAgent({ engine: 'opencode', runtimes: [{ backend: 'tmux', paneId: '%10' }], cwd: '/tmp/demo', defaultName: ' Local model ' })!
expect(named.defaultName).toBe('Local model')
expect(registry.displayName(named)).toBe('Local model')
// The engine reporting a session title does not retitle a pane that was named at creation.
const bound = registry.register({ engine: 'opencode', sessionId: 'session-named', tmuxPane: '%10', title: 'OC | Greeting' })!.entry
expect(registry.displayName(bound)).toBe('Local model')
const unnamed = registry.openPendingAgent({ engine: 'opencode', runtimes: [{ backend: 'tmux', paneId: '%11' }], cwd: '/tmp/demo', defaultName: ' ' })!
expect(registry.displayName(unnamed)).toBe('OpenCode harness 9-17 16:00')
const { registry: reloaded } = await loadRegistryModule()
reloaded.load()
expect(reloaded.displayName(reloaded.byAgent(named.agentId)!)).toBe('Local model')
expect(reloaded.displayName(reloaded.byAgent(unnamed.agentId)!)).toBe('OpenCode harness 9-17 16:00')
})
})
it('keeps the named agent a pane was opened as through binding and reload, and drops one that is not an identifier', async () => {
const { registry } = await loadRegistryModule()
registry.load()
const named = registry.openPendingAgent({ engine: 'opencode', runtimes: [{ backend: 'tmux', paneId: '%7' }], cwd: '/tmp/demo', agent: 'harness-compute', defaultName: 'Local model' })!
expect(named.agent).toBe('harness-compute')
// A hook-triggered bind carries it forward, like `dsh` and `codexHome`.
const bound = registry.register({ engine: 'opencode', sessionId: 'session-agent', tmuxPane: '%7', title: 'OC | Greeting' })!.entry
expect(bound.agent).toBe('harness-compute')
// Absent is a general session; a shape the engine could not look a file up by is not kept.
const plain = registry.openPendingAgent({ engine: 'opencode', runtimes: [{ backend: 'tmux', paneId: '%8' }], cwd: '/tmp/demo' })!
expect(plain.agent).toBeNull()
const odd = registry.openPendingAgent({ engine: 'opencode', runtimes: [{ backend: 'tmux', paneId: '%9' }], cwd: '/tmp/demo', agent: '../etc' })!
expect(odd.agent).toBeNull()
const { registry: reloaded } = await loadRegistryModule()
reloaded.load()
expect(reloaded.byAgent(named.agentId)!.agent).toBe('harness-compute')
expect(reloaded.byAgent(plain.agentId)!.agent).toBeNull()
})
it('keeps the selected harness runtime through process binding and disk reload', async () => {
const { registry } = await loadRegistryModule()
registry.load()
const pending = registry.openPendingAgent({ engine: 'opencode', runtimes: [{ backend: 'tmux', paneId: '%70' }],
cwd: '/tmp/drawing', dsh: 'acme/drawing', dshRuntime: 'harness-opencode-original' })!
expect(pending.dshRuntime).toBe('harness-opencode-original')
const bound = registry.register({ engine: 'opencode', sessionId: 'drawing-session', tmuxPane: '%70' })!.entry
expect(bound).toMatchObject({ engine: 'opencode', dsh: 'acme/drawing', dshRuntime: 'harness-opencode-original' })
const { registry: reloaded } = await loadRegistryModule()
reloaded.load()
expect(reloaded.byAgent(pending.agentId)).toMatchObject({ engine: 'opencode', dsh: 'acme/drawing', dshRuntime: 'harness-opencode-original' })
})
it('persists a failed launch for reconnect while keeping its terminal route', async () => {
const { registry } = await loadRegistryModule()
registry.load()
const pending = registry.openPendingAgent({
engine: 'codex', runtimes: [{ backend: 'tmux', paneId: '%8' }], cwd: '/tmp/demo',
})!
registry.setLaunch(pending.agentId, {
state: 'failed', error: 'ENGINE_DID_NOT_START', detail: 'See terminal output.',
})
const { registry: reloaded } = await loadRegistryModule()
reloaded.load()
expect(reloaded.byAgent(pending.agentId)).toMatchObject({
active: false,
launch: { state: 'failed', error: 'ENGINE_DID_NOT_START', detail: 'See terminal output.' },
tmuxPane: '%8',
})
})
it('validates a Codex transcript against the agent\'s own profile, not the daemon default', async () => {
const { validTranscriptPath } = await loadRegistryModule()
const profile = mkdtempSync(join(tmpdir(), 'adapter-codex-profile-'))
try {
const file = join(profile, 'sessions', 'rollout-x.jsonl')
mkdirSync(join(file, '..'), { recursive: true })
writeFileSync(file, '{}\n')
expect(validTranscriptPath('codex', file, profile)).toBe(true)
// Without the override this file sits outside the (default) trusted root and must be refused.
expect(validTranscriptPath('codex', file)).toBe(false)
} finally {
rmSync(profile, { recursive: true, force: true })
}
})
it('registers a codex session against the profile it was created with', async () => {
const { registry } = await loadRegistryModule()
registry.load()
const profile = mkdtempSync(join(tmpdir(), 'adapter-codex-profile-'))
try {
const pending = registry.openPendingAgent({
engine: 'codex',
runtimes: [{ backend: 'tmux', paneId: '%9' }],
cwd: '/tmp/demo',
codexHome: profile,
})!
expect(pending.codexHome).toBe(profile)
const transcriptFile = join(profile, 'sessions', 'rollout-x.jsonl')
mkdirSync(join(transcriptFile, '..'), { recursive: true })
writeFileSync(transcriptFile, '{}\n')
const result = registry.register({
engine: 'codex',
sessionId: 'sess-1',
transcriptPath: transcriptFile,
tmuxPane: '%9',
cwd: '/tmp/demo',
processIdentity: processIdentity(909),
})
expect(result?.entry.sessionId).toBe('sess-1')
expect(result?.entry.codexHome).toBe(profile)
} finally {
rmSync(profile, { recursive: true, force: true })
}
})
it('keeps a name given before the agent had a session', async () => {
// Names live under the ENGINE session id — that is what survives the launcher and comes back on a
// resume, since the agent id is minted fresh each launch. An agent renamed while still unbound has
// its name parked under the agent id, and the bind must carry it over.
const { registry, projectDisplayName } = await loadRegistryModule()
registry.load()
registry.openProcessAgent({ agentId: 'agent-1', engine: 'claude', tmuxPane: '%1', cwd: '/tmp/demo', processIdentity: processIdentity(101) })
expect(registry.rename('agent-1', 'Backend fix')).toBeTruthy()
expect(projectDisplayName(registry.byAgent('agent-1')!)).toBe('Backend fix')
const bound = registerProcess(registry, { launcherId: 'agent-1', sessionId: 's1', transcriptPath: transcript('s1'), tmuxPane: '%1', cwd: '/tmp/demo' })
registry.inheritName('agent-1', 's1')
expect(projectDisplayName(bound!.entry)).toBe('Backend fix')
// …and a LATER agent that resumes the same session inherits it, because the key is the session.
registry.removeAgent('agent-1')
const resumed = registerProcess(registry, { launcherId: 'agent-2', sessionId: 's1', transcriptPath: transcript('s1'), tmuxPane: '%1', cwd: '/tmp/demo' })
expect(projectDisplayName(resumed!.entry)).toBe('Backend fix')
})
it('loads a pre-agentId snapshot by reading launcherId as the agent id', async () => {
// No migration file and no version gate: every record already carried the launcher uuid, and that
// uuid IS the agent id.
const path = transcript('legacy')
const now = Date.now()
writeLegacyStateFile(join(dataDir, 'registry.json'), JSON.stringify([{
sessionId: 'legacy-session', engine: 'claude', launcherId: 'legacy-agent', transcriptPath: path,
projectDir: 'x', cwd: '/tmp/demo', tmuxPane: '%3', source: null, title: null, model: null,
cliVersion: null, processIdentity: null, registeredAt: now, updatedAt: now,
lastHookAt: now, lastTranscriptAt: now,
}]))
const { registry } = await loadRegistryModule()
registry.load()
expect(registry.byAgent('legacy-agent')?.sessionId).toBe('legacy-session')
expect(registry.resolve('legacy-session')?.agentId).toBe('legacy-agent')
// It is immediately rewritten without legacy ownership metadata.
const saved = JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf-8')) as Array<Record<string, unknown>>
expect(saved[0]).toMatchObject({ agentId: 'legacy-agent' })
expect(saved[0]).not.toHaveProperty('launcherId')
})
})
describe('registry across a reboot and pane loss', () => {
beforeEach(() => {
vi.useFakeTimers()
dataDir = mkdtempSync(join(tmpdir(), 'adapter-registry-reboot-'))
})
afterEach(() => {
vi.useRealTimers()
rmSync(dataDir, { recursive: true, force: true })
delete process.env.ADAPTER_DATA_DIR
delete process.env.CLAUDE_PROJECTS_DIR
delete process.env.CODEX_HOME
delete process.env.CURSOR_HOME
})
/** A row as `agent_create` + a SessionStart hook leave it: bound, with a live-looking process. */
function persistedRow(transcriptPath: string, overrides: Record<string, unknown> = {}) {
return {
schemaVersion: 2,
active: true,
launch: { state: 'ready' },
agentId: 'agent-a',
sessionId: 'session-a',
boundAt: 1,
engine: 'claude',
gateway: null,
grid: null,
codexHome: null,
bypassPermission: true,
transcriptPath,
projectDir: 'demo',
cwd: '/tmp/demo',
runtimes: [{ backend: 'tmux', paneId: '%3' }],
primaryRuntimeKey: 'tmux\u0000%3',
tmuxPane: '%3',
source: null,
title: null,
model: null,
cliVersion: null,
processIdentity: processIdentity(4242),
registeredAt: 1,
updatedAt: 1,
lastHookAt: 1,
lastTranscriptAt: 1,
...overrides,
}
}
it('keeps every agent after a reboot, clearing only what a reboot actually kills', async () => {
const transcriptPath = join(dataDir, 'session-a.jsonl')
writeFileSync(transcriptPath, '{}\n')
chmodSync(dataDir, 0o755)
writeLegacyStateFile(join(dataDir, 'registry.json'), JSON.stringify([persistedRow(transcriptPath, { codexHome: '/tmp/codex-work' })]))
// A boot marker from the distant past: whichever way the platform identifies a boot, this is not it.
writeLegacyStateFile(join(dataDir, 'registry-boot'), 'time:1')
const { registry } = await loadRegistryModule()
registry.load()
expect(registry.rebootedSinceLastRun).toBe(true)
expect(registry.byAgent('agent-a')).toMatchObject({
agentId: 'agent-a',
sessionId: 'session-a',
engine: 'claude',
cwd: '/tmp/demo',
codexHome: '/tmp/codex-work',
bypassPermission: true,
runtimes: [{ backend: 'tmux', paneId: '%3' }],
active: false,
processIdentity: null,
})
// The cleared snapshot is on disk immediately: the boot marker was already refreshed, so a crash
// before this save would otherwise leave the dead pid behind with no second reboot to notice it.
const saved = JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf-8')) as Array<Record<string, unknown>>
expect(saved[0]).toMatchObject({ agentId: 'agent-a', processIdentity: null, codexHome: '/tmp/codex-work', bypassPermission: true })
// The next start on the SAME boot is not a reboot, and finds the row as the previous save left it.
const again = await loadRegistryModule()
again.registry.load()
expect(again.registry.rebootedSinceLastRun).toBe(false)
expect(again.registry.byAgent('agent-a')).toMatchObject({ processIdentity: null, bypassPermission: true })
})
it('leaves the process identity alone when the machine did not reboot', async () => {
const transcriptPath = join(dataDir, 'session-a.jsonl')
writeFileSync(transcriptPath, '{}\n')
chmodSync(dataDir, 0o755)
writeLegacyStateFile(join(dataDir, 'registry.json'), JSON.stringify([persistedRow(transcriptPath)]))
const { registry } = await loadRegistryModule()
registry.load()
expect(registry.rebootedSinceLastRun).toBe(false)
expect(registry.byAgent('agent-a')?.processIdentity).toEqual(processIdentity(4242))
expect(registry.byProcess('claude', processIdentity(4242))?.agentId).toBe('agent-a')
})
it('keeps the permission mode from agent_create through a bind and a reload', async () => {
const transcriptPath = join(dataDir, 'session-p.jsonl')
writeFileSync(transcriptPath, '{}\n')
const { registry } = await loadRegistryModule()
registry.load()
const pending = registry.openPendingAgent({
engine: 'claude',
runtimes: [{ backend: 'tmux', paneId: '%7' }],
cwd: '/tmp/demo',
permissionMode: 'plan',
})
expect(pending?.permissionMode).toBe('plan')
const bound = registry.register({ sessionId: 'session-p', transcriptPath, tmuxPane: '%7', cwd: '/tmp/demo' })
expect(bound?.entry.permissionMode).toBe('plan')
const again = await loadRegistryModule()
again.registry.load()
expect(again.registry.byAgent(pending!.agentId)?.permissionMode).toBe('plan')
const bogus = registry.openPendingAgent({
engine: 'claude',
runtimes: [{ backend: 'tmux', paneId: '%8' }],
cwd: '/tmp/demo',
permissionMode: '--dangerously-skip-permissions',
})
expect(bogus).not.toHaveProperty('permissionMode')
})
it('carries bypassPermission from agent_create through the first hook bind', async () => {
const transcriptPath = join(dataDir, 'session-b.jsonl')
writeFileSync(transcriptPath, '{}\n')
const { registry } = await loadRegistryModule()
registry.load()
const pending = registry.openPendingAgent({
engine: 'claude',
runtimes: [{ backend: 'tmux', paneId: '%9' }],
cwd: '/tmp/demo',
bypassPermission: true,
})
expect(pending?.bypassPermission).toBe(true)
const bound = registry.register({ sessionId: 'session-b', transcriptPath, tmuxPane: '%9', cwd: '/tmp/demo' })
expect(bound?.entry.agentId).toBe(pending!.agentId)
expect(bound?.entry.bypassPermission).toBe(true)
expect(registry.setBypassPermission(pending!.agentId, false)).toBe(true)
expect(registry.byAgent(pending!.agentId)).not.toHaveProperty('bypassPermission')
const saved = JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf-8')) as Array<Record<string, unknown>>
expect(saved[0]).not.toHaveProperty('bypassPermission')
})
it('fills in the permission mode discovery read off a live argv, and keeps it across a reload', async () => {
const { registry } = await loadRegistryModule()
registry.load()
const pending = registry.openPendingAgent({
engine: 'claude',
runtimes: [{ backend: 'tmux', paneId: '%9' }],
cwd: '/tmp/demo',
bypassPermission: true,
})
expect(pending).not.toHaveProperty('permissionMode')
expect(registry.setPermissionMode(pending!.agentId, 'full')).toBe(true)
expect(registry.byAgent(pending!.agentId)?.permissionMode).toBe('full')
// Idempotent; fill-only, so the recorded mode is never re-derived into another; and a name that
// is not a mode is refused as it is on load.
expect(registry.setPermissionMode(pending!.agentId, 'full')).toBe(true)
expect(registry.setPermissionMode(pending!.agentId, 'plan')).toBe(false)
expect(registry.setPermissionMode(pending!.agentId, '--dangerously-skip-permissions')).toBe(false)
expect(registry.setPermissionMode('nope', 'full')).toBe(false)
expect(registry.byAgent(pending!.agentId)?.permissionMode).toBe('full')
const { registry: reloaded } = await loadRegistryModule()
reloaded.load()
expect(reloaded.byAgent(pending!.agentId)?.permissionMode).toBe('full')
})
const GRID_LAUNCH = {
networkId: 'grid-abc',
networkName: 'Team grid',
baseUrl: 'https://grid.example/grid-abc/relay/v1',
apiKey: 'gridkey-abc123',
model: 'gpt-5',
}
it('carries the grid — launch, key and observed assignment — through the first hook bind', async () => {
// The first SessionStart hook rebuilds the row. Before this, it rebuilt it without `grid`, so the
// agent was announced as "on no grid" until the next scan re-read the process; and without
// `gridLaunch`, so nothing could ever put it back on its grid.
const transcriptPath = join(dataDir, 'session-g.jsonl')
writeFileSync(transcriptPath, '{}\n')
const { registry } = await loadRegistryModule()
registry.load()
const pending = registry.openPendingAgent({
engine: 'claude',
runtimes: [{ backend: 'tmux', paneId: '%9' }],
cwd: '/tmp/demo',
grid: { baseUrl: GRID_LAUNCH.baseUrl, model: 'gpt-5' },
gridLaunchRecord: { override: GRID_LAUNCH, webSearch: 'on' },
})!
expect(pending.gridLaunch).toEqual(GRID_LAUNCH)
expect(pending.gridWebSearch).toBe('on')
expect(pending.launch).toEqual({ state: 'starting' })
const bound = registry.register({ sessionId: 'session-g', transcriptPath, tmuxPane: '%9', cwd: '/tmp/demo' })
expect(bound?.entry.agentId).toBe(pending.agentId)
expect(bound?.entry).toMatchObject({
grid: { baseUrl: GRID_LAUNCH.baseUrl, model: 'gpt-5' },
gridLaunch: GRID_LAUNCH,
gridWebSearch: 'on',
gateway: null,
})
// The hook is the engine reporting in: the launch is over and the frame reads ready.
expect(bound?.entry.launch).toBeUndefined()
// Moved back to the engine's own login: the launch is gone, and a bind keeps it gone.
expect(registry.setGridLaunch(pending.agentId, null)).toBe(true)
expect(registry.register({ sessionId: 'session-g', transcriptPath, tmuxPane: '%9', cwd: '/tmp/demo' })?.entry.gridLaunch).toBeNull()
expect(registry.setGridLaunch('nobody', null)).toBe(false)
})
it('keeps the remembered subscription model across a reload', async () => {
// ⚠️ REGRESSION. A row is rebuilt from an explicit field list on load, so a field added to the
// type and the setter but NOT to that list is written to disk and silently dropped by the next
// load. It reads as "the setter never ran", which is where a day went — so what is pinned here
// is survival across a RELOAD, not merely that the setter returned true.
const { registry } = await loadRegistryModule()
registry.load()
const pending = registry.openPendingAgent({
engine: 'claude',
runtimes: [{ backend: 'tmux', paneId: '%21' }],
cwd: '/tmp/demo',
})!
expect(registry.setSubscriptionModel(pending.agentId, 'opus')).toBe(true)
expect(registry.setSubscriptionModel('nobody', 'opus')).toBe(false)
// The reload is the whole test: a field missing from the rehydration list survives the write and
// dies here.
const { registry: reloaded } = await loadRegistryModule()
reloaded.load()
expect(reloaded.byAgent(pending.agentId)?.subscriptionModel).toBe('opus')
// ...and the SECOND way it was lost: a hook bind rebuilds the row from named fields, so a field
// the rebuild does not name is still on disk while memory has already forgotten it.
const transcriptPath = join(dataDir, 'session-sub.jsonl')
writeFileSync(transcriptPath, '{}\n')
const bound = reloaded.register({ sessionId: 'session-sub', transcriptPath, tmuxPane: '%21', cwd: '/tmp/demo' })
expect(bound?.entry.agentId).toBe(pending.agentId)
expect(bound?.entry.subscriptionModel).toBe('opus')
})
it('keeps strict conversation resume after the engine binds and the daemon reloads', async () => {
const transcriptPath = join(dataDir, 'session-resumed.jsonl')
writeFileSync(transcriptPath, '{}\n')
const { registry } = await loadRegistryModule()
registry.load()
const original = registerProcess(registry, {
engine: 'claude', sessionId: 'session-resumed', transcriptPath, tmuxPane: '%21', cwd: '/tmp/demo',
})!.entry
registry.removeAgent(original.agentId)
registry.resumePendingAgent(original, [{ backend: 'tmux', paneId: '%22' }])
// SessionStart rebuilds the row. It must retain the policy that prevents a
// later daemon restore from silently replacing this saved conversation.
const bound = registry.register({
engine: 'claude', sessionId: original.sessionId, transcriptPath, tmuxPane: '%22', cwd: '/tmp/demo', processIdentity: processIdentity(122),
})
expect(bound?.entry.agentId).toBe(original.agentId)
expect(bound?.entry.resumeOnly).toBe(true)
const { registry: reloaded } = await loadRegistryModule()
reloaded.load()
expect(reloaded.byAgent(original.agentId)).toMatchObject({
sessionId: original.sessionId, tmuxPane: '%22', resumeOnly: true,
})
})
it('lets process discovery start a resumed row, and still refuses the wrong conversation', async () => {
const transcriptPath = join(dataDir, 'resume-target.jsonl')
writeFileSync(transcriptPath, '{}\n')
const { registry } = await loadRegistryModule()
const original = registerProcess(registry, { engine: 'claude', sessionId: 'resume-target', transcriptPath, tmuxPane: '%21' })!.entry
registry.removeAgent(original.agentId)
registry.resumePendingAgent(original, [{ backend: 'tmux', paneId: '%22' }])
registry.openProcessAgent({ engine: 'claude', runtimes: [{ backend: 'tmux', paneId: '%22' }], processIdentity: processIdentity(122) })
// The engine is running in the row's pane, so the row has started — it no longer waits for a
// hook a resume may never send. What it has NOT yet been told is which conversation reopened.
expect(registry.byAgent(original.agentId)?.launch?.state).toBe('ready')
expect(registry.byAgent(original.agentId)?.lastHookAt).toBe(0)
expect(registry.register({ engine: 'claude', sessionId: 'unexpected-new-session', transcriptPath, tmuxPane: '%22', processIdentity: processIdentity(122) })).toBeNull()
expect(registry.byAgent(original.agentId)).toMatchObject({ sessionId: 'resume-target', launch: { state: 'failed', error: 'RESUME_SESSION_MISMATCH' } })
const confirmed = registry.register({ engine: 'claude', sessionId: 'resume-target', transcriptPath, tmuxPane: '%22', processIdentity: processIdentity(122) })
expect(confirmed?.entry).toMatchObject({ agentId: original.agentId, sessionId: 'resume-target', launch: { state: 'ready' } })
})
// The guard reads `lastHookAt`, not `launch`. A resume is now confirmed by its own live engine
// process (`resumeStoppedAgent.ts`), which marks the row ready BEFORE any hook arrives — and a
// guard keyed on `launch` would have been disarmed for exactly the resumes it protects.
it('still refuses another conversation on the first hook after the row was marked ready', async () => {
const transcriptPath = join(dataDir, 'ready-first.jsonl')
writeFileSync(transcriptPath, '{}\n')
const { registry } = await loadRegistryModule()
const original = registerProcess(registry, { engine: 'claude', sessionId: 'ready-first', transcriptPath, tmuxPane: '%31' })!.entry
registry.removeAgent(original.agentId)
registry.resumePendingAgent(original, [{ backend: 'tmux', paneId: '%32' }])
// What the resume service does the moment it sees the engine process in the pane.
registry.setLaunch(original.agentId, { state: 'ready' })
expect(registry.byAgent(original.agentId)?.lastHookAt).toBe(0)
expect(registry.register({ engine: 'claude', sessionId: 'somebody-elses-session', transcriptPath, tmuxPane: '%32', processIdentity: processIdentity(132) })).toBeNull()
expect(registry.byAgent(original.agentId)).toMatchObject({ sessionId: 'ready-first', launch: { state: 'failed', error: 'RESUME_SESSION_MISMATCH' } })
})
it('drops any launch state on the hook that proves the engine is up', async () => {
const transcriptPath = join(dataDir, 'session-f.jsonl')
writeFileSync(transcriptPath, '{}\n')
const { registry } = await loadRegistryModule()
registry.load()
const pending = registry.openPendingAgent({ engine: 'claude', runtimes: [{ backend: 'tmux', paneId: '%9' }], cwd: '/tmp/demo' })!
registry.setLaunch(pending.agentId, { state: 'failed', error: 'START_TIMEOUT' })
const bound = registry.register({ sessionId: 'session-f', transcriptPath, tmuxPane: '%9', cwd: '/tmp/demo' })
expect(bound?.entry.launch).toBeUndefined()
})
it('persists the grid launch across a reboot and forgets one it cannot trust', async () => {
const transcriptPath = join(dataDir, 'session-a.jsonl')
writeFileSync(transcriptPath, '{}\n')
chmodSync(dataDir, 0o755)
writeLegacyStateFile(join(dataDir, 'registry.json'), JSON.stringify([
persistedRow(transcriptPath, { grid: { baseUrl: GRID_LAUNCH.baseUrl, model: 'gpt-5' }, gridLaunch: GRID_LAUNCH }),
persistedRow(transcriptPath, { agentId: 'agent-b', sessionId: 'session-b', runtimes: [{ backend: 'tmux', paneId: '%4' }], primaryRuntimeKey: 'tmux\u0000%4', tmuxPane: '%4', processIdentity: processIdentity(4243), grid: { baseUrl: GRID_LAUNCH.baseUrl, model: null }, gridLaunch: { baseUrl: GRID_LAUNCH.baseUrl } }),
persistedRow(transcriptPath, { agentId: 'agent-c', sessionId: 'session-c', runtimes: [{ backend: 'tmux', paneId: '%5' }], primaryRuntimeKey: 'tmux\u0000%5', tmuxPane: '%5', processIdentity: processIdentity(4244) }),
]))
writeLegacyStateFile(join(dataDir, 'registry-boot'), 'time:1')
const { registry } = await loadRegistryModule()
registry.load()
expect(registry.rebootedSinceLastRun).toBe(true)
// Kept verbatim: this is what restore relaunches the pane with.
expect(registry.byAgent('agent-a')).toMatchObject({ processIdentity: null, gridLaunch: GRID_LAUNCH })
// A half-remembered launch is worse than none — it would look like a grid launch and fail like one.
expect(registry.byAgent('agent-b')?.gridLaunch).toBeNull()
// A row from before the field existed stays distinguishable from "vendor login".
expect(registry.byAgent('agent-c')).not.toHaveProperty('gridLaunch')
const saved = JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf-8')) as Array<Record<string, unknown>>
expect(saved[0]).toMatchObject({ gridLaunch: GRID_LAUNCH })
expect(saved[2]).not.toHaveProperty('gridLaunch')
})
it('a discovered Codex process fills in the profile it runs under, but never replaces one', async () => {
const { registry } = await loadRegistryModule()
registry.load()
const opened = registry.openProcessAgent({ engine: 'codex', tmuxPane: '%5', processIdentity: processIdentity(77), codexHome: '/tmp/codex-work' })!
expect(opened.entry.codexHome).toBe('/tmp/codex-work')
// Discovery cannot have seen the credential: a discovered grid agent is observed, never relaunched.
expect(opened.entry.gridLaunch).toBeNull()
expect(registry.setCodexHome(opened.entry.agentId, '/tmp/codex-other')).toBe(false)
expect(registry.byAgent(opened.entry.agentId)?.codexHome).toBe('/tmp/codex-work')
registry.openProcessAgent({ engine: 'codex', tmuxPane: '%5', processIdentity: processIdentity(77), codexHome: '/tmp/codex-other' })
expect(registry.byAgent(opened.entry.agentId)?.codexHome).toBe('/tmp/codex-work')
const bare = registry.openProcessAgent({ engine: 'codex', tmuxPane: '%6', processIdentity: processIdentity(78) })!
expect(bare.entry.codexHome).toBeNull()
expect(registry.setCodexHome(bare.entry.agentId, '/tmp/codex-work')).toBe(true)
expect(registry.byAgent(bare.entry.agentId)?.codexHome).toBe('/tmp/codex-work')
const claude = registry.openProcessAgent({ engine: 'claude', tmuxPane: '%7', processIdentity: processIdentity(79) })!
expect(registry.setCodexHome(claude.entry.agentId, '/tmp/codex-work')).toBe(false)
})
it('clearProcessIdentity forgets the pid everywhere it is indexed', async () => {
const { registry } = await loadRegistryModule()
registry.load()
const opened = registry.openProcessAgent({ engine: 'claude', tmuxPane: '%5', processIdentity: processIdentity(77) })
const agentId = opened!.entry.agentId
expect(registry.byProcess('claude', processIdentity(77))?.agentId).toBe(agentId)
expect(registry.clearProcessIdentity(agentId)).toBe(true)
expect(registry.byAgent(agentId)?.processIdentity).toBeNull()
expect(registry.byProcess('claude', processIdentity(77))).toBeUndefined()
expect(registry.clearProcessIdentity(agentId)).toBe(true) // idempotent
expect(registry.clearProcessIdentity('nobody')).toBe(false)
})
it('survives two restored panes swapping ids when done inside one transaction', async () => {
const { registry } = await loadRegistryModule()
registry.load()
const a = registry.openProcessAgent({ engine: 'claude', tmuxPane: '%1', processIdentity: processIdentity(11) })!.entry.agentId
const b = registry.openProcessAgent({ engine: 'claude', tmuxPane: '%2', processIdentity: processIdentity(12) })!.entry.agentId
// A new tmux server hands out %1/%2 again, in the other order. Saved between the two updates, A
// would claim %2 while B still lists it, and the save's route dedupe evicts one of them.
await registry.transaction(() => {
registry.updateRuntimes(a, [{ backend: 'tmux', paneId: '%2' }], 'tmux\u0000%2')
registry.updateRuntimes(b, [{ backend: 'tmux', paneId: '%1' }], 'tmux\u0000%1')
})
expect(registry.byAgent(a)?.tmuxPane).toBe('%2')
expect(registry.byAgent(b)?.tmuxPane).toBe('%1')
const saved = JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf-8')) as Array<Record<string, unknown>>
expect(saved.map((row) => row.agentId).sort()).toEqual([a, b].sort())
})
it('adopts a new process into an agent whose identity was cleared, keeping its id and session', async () => {
const transcriptPath = join(dataDir, 'session-c.jsonl')
writeFileSync(transcriptPath, '{}\n')
const { registry } = await loadRegistryModule()
registry.load()
const bound = registerProcess(registry, { sessionId: 'session-c', transcriptPath, tmuxPane: '%4', cwd: '/tmp/demo' })
const agentId = bound!.entry.agentId
// What restore does: forget the dead pid, point the row at the recreated pane, launch pending.
registry.clearProcessIdentity(agentId)
registry.updateRuntimes(agentId, [{ backend: 'tmux', paneId: '%0' }], 'tmux\u0000%0')
registry.setLaunch(agentId, { state: 'starting' })
const adopted = registry.openProcessAgent({ engine: 'claude', tmuxPane: '%0', processIdentity: processIdentity(500) })
expect(adopted).toMatchObject({ isNew: false, evicted: null })
expect(adopted?.entry.agentId).toBe(agentId)
expect(adopted?.entry.sessionId).toBe('session-c')
expect(registry.list()).toHaveLength(1)
})
})
describe('a terminal: a pane that becomes an engine and back', () => {
beforeEach(() => {
vi.useFakeTimers()
dataDir = mkdtempSync(join(tmpdir(), 'adapter-registry-terminal-'))
})
afterEach(() => {
vi.useRealTimers()
rmSync(dataDir, { recursive: true, force: true })
delete process.env.ADAPTER_DATA_DIR
delete process.env.CLAUDE_PROJECTS_DIR
delete process.env.CODEX_HOME
delete process.env.CURSOR_HOME
})
const pane = { backend: 'tmux' as const, paneId: '%9' }
it('opens as engine `terminal`, marked terminalHost, and survives a reload that way', async () => {
const { registry } = await loadRegistryModule()
registry.load()
const opened = registry.openPendingAgent({ engine: 'terminal', runtimes: [pane], cwd: '/tmp/work' })!
expect(opened).toMatchObject({ engine: 'terminal', terminalHost: true, sessionId: '', processIdentity: null })
expect(opened.defaultName).toMatch(/^Terminal /)
expect(registry.byRuntimeTerminal(pane)?.agentId).toBe(opened.agentId)
const { registry: reloaded } = await loadRegistryModule()
reloaded.load()
expect(reloaded.byAgent(opened.agentId)).toMatchObject({ engine: 'terminal', terminalHost: true })
})
it('adopts the engine started inside it — same agentId, process indexed under the engine — then a hook binds to it', async () => {
const transcriptPath = join(dataDir, 'session-t.jsonl')
writeFileSync(transcriptPath, '{}\n')
const { registry } = await loadRegistryModule()
registry.load()
const opened = registry.openPendingAgent({ engine: 'terminal', runtimes: [pane], cwd: '/tmp/work' })!
const adopted = registry.adoptEngine(opened.agentId, 'claude', processIdentity(909))!
expect(adopted.agentId).toBe(opened.agentId)
expect(adopted).toMatchObject({ engine: 'claude', terminalHost: true, launch: { state: 'ready' }, active: true })
expect(registry.byProcess('claude', processIdentity(909))?.agentId).toBe(opened.agentId)
expect(registry.byRuntimeTerminal(pane)).toBeUndefined()
expect(registry.byRuntimeEngine(pane, 'claude')?.agentId).toBe(opened.agentId)
// An agent already running an engine is never re-labelled.
expect(registry.adoptEngine(opened.agentId, 'codex', processIdentity(910))).toBeNull()
const bound = registry.register({ engine: 'claude', sessionId: 'session-t', transcriptPath, tmuxPane: '%9', processIdentity: processIdentity(909) })
expect(bound?.entry.agentId).toBe(opened.agentId)
expect(bound?.entry.terminalHost).toBe(true)
expect(registry.list()).toHaveLength(1)
})
it('a SessionStart hook that beats the reconciler adopts the terminal at its pane rather than minting nothing', async () => {
const transcriptPath = join(dataDir, 'session-h.jsonl')
writeFileSync(transcriptPath, '{}\n')
const { registry } = await loadRegistryModule()
registry.load()
const opened = registry.openPendingAgent({ engine: 'terminal', runtimes: [pane], cwd: '/tmp/work' })!
const bound = registry.register({ engine: 'claude', sessionId: 'session-h', transcriptPath, tmuxPane: '%9', processIdentity: processIdentity(911) })
expect(bound?.entry.agentId).toBe(opened.agentId)
expect(bound?.entry).toMatchObject({ engine: 'claude', terminalHost: true })
expect(registry.list()).toHaveLength(1)
})
it('releases the engine when it exits: a live terminal again, with nothing of the engine left on it', async () => {
const transcriptPath = join(dataDir, 'session-r.jsonl')
writeFileSync(transcriptPath, '{}\n')
const { registry } = await loadRegistryModule()
registry.load()
const opened = registry.openPendingAgent({ engine: 'terminal', runtimes: [pane], cwd: '/tmp/work' })!
registry.adoptEngine(opened.agentId, 'claude', processIdentity(912))
registry.register({ engine: 'claude', sessionId: 'session-r', transcriptPath, tmuxPane: '%9', processIdentity: processIdentity(912) })
registry.setBypassPermission(opened.agentId, true)
const released = registry.releaseEngine(opened.agentId)!
expect(released.agentId).toBe(opened.agentId)
expect(released).toMatchObject({ engine: 'terminal', terminalHost: true, active: true, launch: { state: 'ready' }, sessionId: '', processIdentity: null, transcriptPath: null, grid: null, model: null })
// The pane's launch shape survives the engine: the same flags come back with the next launch.
expect(released.bypassPermission).toBe(true)
expect(registry.bySession('session-r')).toBeUndefined()
expect(registry.byProcess('claude', processIdentity(912))).toBeUndefined()
expect(registry.byRuntimeTerminal(pane)?.agentId).toBe(opened.agentId)
expect(registry.terminalAvailable(opened.agentId)).toBe(true)
// Already a terminal? Nothing to release. A plain agent whose engine exited? A terminal from now on.
expect(registry.releaseEngine(opened.agentId)).toBeNull()
const plain = registry.openPendingAgent({ engine: 'codex', runtimes: [{ backend: 'tmux', paneId: '%10' }], cwd: '/tmp/x' })!
expect(plain.terminalHost).toBeUndefined()
expect(registry.releaseEngine(plain.agentId)).toMatchObject({ engine: 'terminal', terminalHost: true, active: true })
expect(registry.byRuntimeTerminal({ backend: 'tmux', paneId: '%10' })?.agentId).toBe(plain.agentId)
// And the next engine typed into the same shell is adopted just the same.
expect(registry.adoptEngine(opened.agentId, 'codex', processIdentity(913))).toMatchObject({ engine: 'codex' })
})
})
describe('lastOpenedAt: when an app last opened the agent, on the daemon clock', () => {
beforeEach(() => {
vi.useFakeTimers()
dataDir = mkdtempSync(join(tmpdir(), 'adapter-registry-opened-'))
})
afterEach(() => {
vi.useRealTimers()
rmSync(dataDir, { recursive: true, force: true })
delete process.env.ADAPTER_DATA_DIR
delete process.env.CLAUDE_PROJECTS_DIR
delete process.env.CODEX_HOME
delete process.env.CURSOR_HOME
})
const OPENED = Date.UTC(2026, 8, 26, 9, 30)
const onDisk = () => JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf-8')) as Array<Record<string, unknown>>
it('stamps the daemon’s own clock, persists it, and leaves the bookkeeping `touchedAt` alone', async () => {
const { registry } = await loadRegistryModule()
registry.load()
const pending = registry.openPendingAgent({ engine: 'claude', runtimes: [{ backend: 'tmux', paneId: '%41' }], cwd: '/tmp/demo' })!
expect(pending.lastOpenedAt).toBeUndefined()
expect(onDisk()[0]).not.toHaveProperty('lastOpenedAt')
const touchedAt = pending.touchedAt
vi.setSystemTime(OPENED)
const opened = registry.markOpened(pending.agentId)
expect(opened?.lastOpenedAt).toBe(OPENED)
expect(opened?.touchedAt).toBe(touchedAt)
expect(onDisk()[0]).toMatchObject({ agentId: pending.agentId, lastOpenedAt: OPENED, touchedAt })
expect(registry.markOpened('nobody')).toBeNull()
// The load rebuilds every row from a named list: a field missing there is written and then lost.
const { registry: reloaded } = await loadRegistryModule()
reloaded.load()
expect(reloaded.byAgent(pending.agentId)?.lastOpenedAt).toBe(OPENED)
})
it('survives the hook that rebuilds the row — the first prompt after an open must not erase it', async () => {
const transcriptPath = join(dataDir, 'session-opened.jsonl')
writeFileSync(transcriptPath, '{}\n')
const { registry } = await loadRegistryModule()
registry.load()
const pending = registry.openPendingAgent({ engine: 'claude', runtimes: [{ backend: 'tmux', paneId: '%42' }], cwd: '/tmp/demo' })!
vi.setSystemTime(OPENED)
registry.markOpened(pending.agentId)
vi.setSystemTime(OPENED + 60_000)
const bound = registry.register({ sessionId: 'session-opened', transcriptPath, tmuxPane: '%42', cwd: '/tmp/demo' })
expect(bound?.entry.agentId).toBe(pending.agentId)
expect(bound?.entry.lastOpenedAt).toBe(OPENED)
// ...and again on a re-register of the same session, then on disk.
const again = registry.register({ sessionId: 'session-opened', transcriptPath, tmuxPane: '%42', cwd: '/tmp/demo' })
expect(again?.entry.lastOpenedAt).toBe(OPENED)
expect(onDisk()[0]).toMatchObject({ agentId: pending.agentId, lastOpenedAt: OPENED })
})
it('never lets a hand-edited or nonsensical stamp reach the frame', async () => {
const { registry, strictPersistedRow } = await loadRegistryModule()
registry.load()
const pending = registry.openPendingAgent({ engine: 'claude', runtimes: [{ backend: 'tmux', paneId: '%43' }], cwd: '/tmp/demo' })!
const row = onDisk()[0]
expect(strictPersistedRow({ ...row, lastOpenedAt: OPENED })?.lastOpenedAt).toBe(OPENED)
for (const bad of ['yesterday', -5, 0, 1.5, Number.NaN, null]) {
expect(strictPersistedRow({ ...row, lastOpenedAt: bad })).not.toHaveProperty('lastOpenedAt')
}
writeFileSync(join(dataDir, 'registry.json'), JSON.stringify([{ ...row, lastOpenedAt: 'yesterday' }]), { mode: 0o600 })
const { registry: reloaded } = await loadRegistryModule()
reloaded.load()
expect(reloaded.byAgent(pending.agentId)).toBeTruthy()
expect(reloaded.byAgent(pending.agentId)).not.toHaveProperty('lastOpenedAt')
})
})