Skip to content

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

An agent is no longer named after the machine when its name changes; compat re-checked after #805 (#813)

Dee3e67738fe48e
diff --git a/cli/e2e/compat.e2e.ts b/cli/e2e/compat.e2e.ts
index c41671664..894cc2e51 100644
--- a/cli/e2e/compat.e2e.ts
+++ b/cli/e2e/compat.e2e.ts
@@ -18,7 +18,7 @@
*/
import { execFileSync } from 'node:child_process'
import { copyFileSync, mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
-import { tmpdir } from 'node:os'
+import { hostname, tmpdir } from 'node:os'
import { dirname, join } from 'node:path'
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
import { LocalClient, type Frame } from './harness/client.js'
@@ -37,6 +37,14 @@ const CHANGED: Record<string, string> = {
'terminal_info codex': 'answered now; the released build left it unanswered',
'terminal_info with nothing': 'answered now; the released build left it unanswered',
'terminal_info for no such agent': 'answered now; the released build left it unanswered',
+ // A permission dialog's question says it is one (#764): `permission` carries the dialog and that the
+ // desktop resolves it, so a device shows a notice rather than a question to answer. A field added,
+ // nothing taken away; a frame's keys are compared as one line, so the addition reads as a change.
+ 'frames of a permission on claude[3]': 'commander_question adds permission (#764); every key it had stays',
+ 'frames of a permission on codex[2]': 'commander_question adds permission (#764); every key it had stays',
+ // A conversation the daemon keeps as a stopped one reads like a live one (#797, round 24). The released
+ // build said NOT_FOUND, so a conversation the daemon had to leave for a new one could not be read at all.
+ 'session_get codex while stopped': 'answered now; the released build said NOT_FOUND for a stopped conversation',
}
type Engine = 'claude' | 'codex'
@@ -202,6 +210,8 @@ async function scenario(d: IsolatedDaemon): Promise<Answers> {
await ask(`sessions_list ${engine}`, 'sessions_list', { agentId: agent[engine] })
await ask(`session_get ${engine}`, 'session_get', { sessionId: session[engine] })
await ask(`session_get ${engine}, one turn`, 'session_get', { sessionId: session[engine], limit: 1 })
+ // The registry finds an agent by its agent id too; the reply names the id it was asked by.
+ await ask(`session_get ${engine} by its agent id, one turn`, 'session_get', { sessionId: agent[engine], limit: 1 })
await ask(`agent_recent ${engine}`, 'agent_recent', { agentId: agent[engine] })
await ask(`terminal_info ${engine}`, 'terminal_info', { agentId: agent[engine] })
await ask(`agent_read_file ${engine}`, 'agent_read_file', { agentId: agent[engine], path: 'README.md' })
@@ -216,13 +226,17 @@ async function scenario(d: IsolatedDaemon): Promise<Answers> {
await ask('harness_devices_list', 'harness_devices_list')
await ask('theme_set', 'theme_set', { background: '#000000', foreground: '#ffffff' })
await ask('a request nobody answers', 'compat_unknown_request')
+ await ask('agent_create_status for no such creation', 'agent_create_status', { creationId: 'compat-no-such-creation' })
- // The same requests, malformed: what each refuses with.
+ // The same requests, malformed: what each refuses with. Each core request that takes arguments is here:
+ // #805 moved every one of them out of the socket's switch into the core module that owns it.
const malformed = ['session_get', 'sessions_list', 'agent_recent', 'terminal_info', 'agent_read_file', 'agent_update', 'agent_fork',
'agent_restart', 'agent_delete', 'agent_resume', 'agent_purge', 'agent_retarget', 'agent_close', 'cancel', 'question_response',
- 'git_project_info', 'fs_list_dir', 'project_preview', 'session_tail', 'dsh_remove', 'dsh_install', 'dsh_update', 'theme_set']
+ 'git_project_info', 'fs_list_dir', 'project_preview', 'session_tail', 'dsh_remove', 'dsh_install', 'dsh_update', 'theme_set',
+ 'agent_create', 'agent_create_status', 'agent_handoff_prepare', 'agent_worktree_delete', 'message']
for (const type of malformed) {
- const ms = type === 'cancel' ? 5_000 : 60_000
+ // `cancel` and `message` are fire-and-forget: no build answers them, so waiting a minute shows nothing more.
+ const ms = type === 'cancel' || type === 'message' ? 5_000 : 60_000
await ask(`${type} with nothing`, type, {}, ms)
await ask(`${type} for no such agent`, type, { agentId: 'compat-no-such-agent', sessionId: 'compat-no-such-session', path: '/compat/no/such/path' }, ms)
}
@@ -239,7 +253,18 @@ async function scenario(d: IsolatedDaemon): Promise<Answers> {
}, 60_000, 500)
await ask('agent_delete (stop)', 'agent_delete', { agentId: agent.codex })
await ask('agents_list after a stop', 'agents_list', { includeStopped: true })
- await ask('agent_resume', 'agent_resume', { agentId: agent.codex })
+ // What the apps read of an agent while it is stopped: its conversation, its list and its recaps.
+ await ask('session_get codex while stopped', 'session_get', { sessionId: session.codex, limit: 1 })
+ await ask('sessions_list codex while stopped', 'sessions_list', { agentId: agent.codex })
+ await ask('agent_recent codex while stopped', 'agent_recent', { agentId: agent.codex })
+ // The model a resumed agent runs is what its engine reports once it is back, a race with the reply
+ // on either build: v0.3.58 and this build each answered null in some runs and the model in others.
+ // It is compared settled, in the rows read at the end.
+ const resumed = await ask('agent_resume', 'agent_resume', { agentId: agent.codex })
+ if (resumed.agent) {
+ const { selectedModel: _model, ...settledLater } = resumed.agent
+ answers['agent_resume'] = walk({ ...resumed, agent: settledLater })
+ }
await until('codex to be back after its resume', async () => {
const row = (await rows()).find((one) => one.id === agent.codex)
return row?.sessionId && row.status === 'active' ? row : null
@@ -272,10 +297,17 @@ describe.skipIf(!FROM)('what the apps see, compared with the released build', ()
['this', { scriptPath: join(build, 'cli.js'), env: { ADAPTER_CLI_DIR: build } }],
] as const) {
const d = await IsolatedDaemon.create(options)
+ // tmux titles each new pane with the machine's name as it is then, and a daemon refuses that title
+ // as an agent's name. Released builds up to v0.3.58 read the name once, at start, so when a
+ // laptop's network name changed mid-run (`MacBook.lan` to `MacBook.local`) the panes made after
+ // it came out named after the machine, on that side alone: a difference the change made, not
+ // the build. This build reads it at every title sweep and keeps each name (lib/machineNames.ts).
+ const host = hostname()
try {
await d.start({ ready: 'port' })
const version = execFileSync(process.execPath, [options.scriptPath, 'version'], { encoding: 'utf8' }).trim()
sides[side] = { version, answers: await scenario(d) }
+ if (hostname() !== host) throw new Error(`this machine's name changed from ${host} to ${hostname()} during the ${side} build's run; run it again`)
} catch (error) {
console.error(`---- ${side} daemon log\n${d.log().split('\n').slice(-120).join('\n')}`)
throw error
diff --git a/cli/e2e/hostname.e2e.ts b/cli/e2e/hostname.e2e.ts
new file mode 100644
index 000000000..ee2f31bcb
--- /dev/null
+++ b/cli/e2e/hostname.e2e.ts
@@ -0,0 +1,90 @@
+/**
+ * An agent is never named after the machine, whatever the machine is called by then.
+ *
+ * tmux titles each new pane with the machine's name of that moment (`gethostname`); an engine that sets
+ * no title of its own keeps it, and the daemon refuses it as the agent's name. A laptop's name follows
+ * its network, and the daemon read it once, at start: after a change, an agent whose pane was made under
+ * the new name was named after the machine (found comparing with v0.3.58, e2e/compat.e2e.ts). The name
+ * is now read on every title sweep, and every name the machine has had counts (lib/machineNames.ts).
+ *
+ * A test cannot change the computer's name, and must not. HARNESSD_TEST_HOSTNAME_FILE stands in for it:
+ * the daemon reads that file where it would ask the operating system. The agent's pane is titled as
+ * tmux titles a pane made under the name, with `select-pane -T`: the daemon reads a pane's title the
+ * same way however it was set. That a pane the daemon makes reads the name as tmux titles it is proved
+ * in lib/tmuxBackend.spec.ts: no test here can make the name change between two sweeps.
+ */
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
+import { LocalClient } from './harness/client.js'
+import { IsolatedDaemon, until } from './harness/daemon.js'
+
+describe('an agent is never named after the machine', () => {
+ let scratch = ''
+ let hostFile = ''
+ let daemon: IsolatedDaemon | undefined
+
+ beforeAll(async () => {
+ scratch = mkdtempSync(join(tmpdir(), 'harnessd-hostname-'))
+ // Not written yet: until it is, the machine's name is the computer's own, as at any start.
+ hostFile = join(scratch, 'hostname')
+ daemon = await IsolatedDaemon.create({ env: { HARNESSD_TEST_HOSTNAME_FILE: hostFile } })
+ await daemon.start()
+ })
+
+ afterAll(async () => {
+ await daemon?.close()
+ if (scratch) rmSync(scratch, { recursive: true, force: true })
+ })
+
+ it('when the machine\'s name changes, and after it changes again', async () => {
+ const d = daemon!
+ onTestFailed(() => { console.log(`---- daemon log\n${d.log().split('\n').slice(-120).join('\n')}`) })
+ const client = await LocalClient.connect(d)
+ const cwd = join(d.projectsDir, 'roaming')
+ mkdirSync(cwd, { recursive: true })
+ const created = await client.request('agent_create', { engine: 'codex', cwd, bypassPermission: true }, 90_000)
+ expect(created.error, JSON.stringify(created)).toBeUndefined()
+ const row = async () => (await client.request<{ agents: Array<Record<string, any>> }>('agents_list', {}, 30_000)).agents
+ .find((one) => one.id === created.agent.id)
+ const agent = await until('codex to bind', async () => {
+ const now = await row()
+ return now?.sessionId && now.status === 'active' && now.tmuxPane ? now : null
+ }, 60_000, 500)
+ // Its own name: the fake Codex sets no title, so its pane has tmux's, the machine's name at start.
+ const own = agent.name as string
+ expect(agent.title).toBeNull()
+
+ const title = (text: string) => d.tmux.run('select-pane', '-t', agent.tmuxPane, '-T', text)
+ /** A title about the conversation becomes the agent's name: a sweep has run since it was set. */
+ const named = async (text: string) => {
+ await title(text)
+ await until(`the agent to be named "${text}"`, async () => (await row())?.name === text || null, 30_000, 250)
+ }
+ /** A title that is the machine's name: the agent goes back to its own name, never the machine's. */
+ const refused = async (text: string) => {
+ await title(text)
+ const now = await until(`a sweep to read "${text}"`, async () => {
+ const current = await row()
+ return current?.name === text || (current?.name === own && current.title === null) ? current : null
+ }, 30_000, 250)
+ expect(now.name, `the agent was named after the machine: ${text}`).toBe(own)
+ expect(now.title).toBeNull()
+ }
+
+ // The machine joins a network that calls it laptop-one.lan, and a pane is made under that name.
+ writeFileSync(hostFile, 'laptop-one.lan')
+ await named('Fix the login page')
+ await refused('laptop-one.lan')
+
+ // Then one that calls it laptop-two.local. The pane made under laptop-one.lan keeps that title.
+ writeFileSync(hostFile, 'laptop-two.local')
+ await named('Fix the login page')
+ await refused('laptop-one.lan')
+ // The first part of a name, in any case, is the same machine.
+ await named('Ship the settings page')
+ await refused('LAPTOP-TWO')
+ client.close()
+ }, 180_000)
+})
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index b657f3308..47a1fb1a8 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -48,6 +48,7 @@ import { terminalActivity } from './cable/terminalActivity.js'
import { MachineListCache, machineListCachePath, withStaleMarker } from './device/machineList.js'
import { registry, projectDisplayName, validTranscriptPath, type RegisteredSession } from './lib/registry.js'
import { engineSessionTitle } from './lib/sessionTitle.js'
+import { machineNames } from './lib/machineNames.js'
import { installCodexHooks } from './lib/hooks.js'
import { DAEMON_LOG_FILE, HARNESSD_STATUS_FILE, PID_FILE, daemonPort, isAlive, isDaemonRunning, readPid } from './lib/daemonState.js'
import { clearSafeModeMarker, readSafeModeMarker, runBootHandoff, safeModeDisposition, safeModeStatusBody, SafeModeRequest, writeSafeModeMarker } from './lib/daemonSafeMode.js'
@@ -1883,6 +1884,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {
const syncTerminalTitles = async (): Promise<void> => {
ports.workspaces?.nameBranches()
const titles = await terminals.titles()
+ // The machine's name now, beside every name it has had: a title that is one of them is refused.
+ machineNames.observe()
if (titles.size === 0) return
for (const session of registry.list()) {
// Codex's own thread name when it has one; otherwise what the engine put on its terminal.
diff --git a/cli/src/lib/machineNames.spec.ts b/cli/src/lib/machineNames.spec.ts
new file mode 100644
index 000000000..1ece555b5
--- /dev/null
+++ b/cli/src/lib/machineNames.spec.ts
@@ -0,0 +1,118 @@
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { hostname, tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { createMachineNames, hostnameReader, MACHINE_NAMES_KEPT } from './machineNames.js'
+
+/** A machine whose name is whatever the test last set. */
+function machine(first: string) {
+ let name = first
+ const read = vi.fn(() => name)
+ return { read, rename: (next: string) => { name = next } }
+}
+
+const dirs: string[] = []
+afterEach(() => {
+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true })
+ delete process.env.HARNESSD_TEST_HOSTNAME_FILE
+ vi.resetModules()
+})
+
+describe('the names a machine has gone by', () => {
+ it('owns the name it has at start, in full and as its first part, in any case', () => {
+ const names = createMachineNames(() => 'MacBook.lan')
+ for (const title of ['macbook.lan', 'MacBook.lan', 'MACBOOK', 'macbook']) expect(names.owns(title), title).toBe(true)
+ for (const title of ['MacBook.local', 'Fix the login page', 'lan']) expect(names.owns(title), title).toBe(false)
+ })
+
+ it('keeps the name it had after it moves on: a pane made under it still carries it', () => {
+ const laptop = machine('MacBook.lan')
+ const names = createMachineNames(laptop.read)
+ laptop.rename('Studio.local')
+ expect(names.owns('studio.local')).toBe(false) // read again only when asked
+ names.observe()
+ for (const title of ['MacBook.lan', 'MacBook', 'Studio.local', 'Studio']) expect(names.owns(title), title).toBe(true)
+ })
+
+ it('reads the name when asked and never per title', () => {
+ const laptop = machine('MacBook.lan')
+ const names = createMachineNames(laptop.read)
+ for (let i = 0; i < 10; i++) names.owns(`title ${i}`)
+ expect(laptop.read).toHaveBeenCalledTimes(1)
+ names.observe()
+ expect(laptop.read).toHaveBeenCalledTimes(2)
+ })
+
+ it('keeps the last names it saw, a name seen again counting as just seen', () => {
+ const laptop = machine('home.lan')
+ const names = createMachineNames(laptop.read, 2)
+ laptop.rename('cafe.lan')
+ names.observe()
+ laptop.rename('home.lan')
+ names.observe() // seen again: now the most recent
+ laptop.rename('office.local')
+ names.observe() // a third name: the least recently seen, cafe.lan, goes
+ for (const title of ['home.lan', 'home', 'office.local', 'office']) expect(names.owns(title), title).toBe(true)
+ for (const title of ['cafe.lan', 'cafe']) expect(names.owns(title), title).toBe(false)
+ })
+
+ it('holds no more than its limit, however many networks the machine roams', () => {
+ const laptop = machine('network-0.lan')
+ const names = createMachineNames(laptop.read)
+ for (let i = 1; i <= 100; i++) {
+ laptop.rename(`network-${i}.lan`)
+ names.observe()
+ }
+ expect(names.owns('network-100.lan')).toBe(true)
+ expect(names.owns(`network-${101 - MACHINE_NAMES_KEPT}.lan`)).toBe(true)
+ expect(names.owns(`network-${100 - MACHINE_NAMES_KEPT}.lan`)).toBe(false)
+ })
+
+ it('forgets nothing when the name cannot be read, or reads as nothing', () => {
+ const laptop = machine('MacBook.lan')
+ const names = createMachineNames(laptop.read)
+ laptop.read.mockImplementationOnce(() => { throw new Error('EPERM') })
+ names.observe()
+ laptop.rename(' ')
+ names.observe()
+ expect(names.owns('MacBook.lan')).toBe(true)
+ expect(names.owns('')).toBe(false)
+ })
+
+ it('owns nothing when no name was ever read', () => {
+ const names = createMachineNames(() => { throw new Error('EPERM') })
+ expect(names.owns('localhost')).toBe(false)
+ })
+})
+
+describe('where the machine\'s name is read', () => {
+ it('asks the operating system', () => {
+ expect(hostnameReader(undefined)).toBe(hostname)
+ })
+
+ it('end to end, reads a file that stands in for it, and the system\'s own until the file holds a name', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'machine-names-'))
+ dirs.push(dir)
+ const file = join(dir, 'hostname')
+ const read = hostnameReader(file)
+ expect(read()).toBe(hostname())
+ writeFileSync(file, '')
+ expect(read()).toBe(hostname())
+ writeFileSync(file, 'laptop-one.lan\n')
+ expect(read()).toBe('laptop-one.lan')
+ })
+
+ it('the daemon\'s own reads the file HARNESSD_TEST_HOSTNAME_FILE names, from its first read', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'machine-names-'))
+ dirs.push(dir)
+ process.env.HARNESSD_TEST_HOSTNAME_FILE = join(dir, 'hostname')
+ writeFileSync(process.env.HARNESSD_TEST_HOSTNAME_FILE, 'laptop-one.lan')
+ vi.resetModules()
+ const { machineNames } = await import('./machineNames.js')
+ expect(machineNames.owns('laptop-one.lan')).toBe(true)
+ writeFileSync(process.env.HARNESSD_TEST_HOSTNAME_FILE, 'laptop-two.local')
+ machineNames.observe()
+ expect(machineNames.owns('laptop-one.lan')).toBe(true)
+ expect(machineNames.owns('laptop-two')).toBe(true)
+ })
+})
diff --git a/cli/src/lib/machineNames.ts b/cli/src/lib/machineNames.ts
new file mode 100644
index 000000000..8e8836877
--- /dev/null
+++ b/cli/src/lib/machineNames.ts
@@ -0,0 +1,75 @@
+/**
+ * The names this machine has gone by while this daemon has run: a pane title that is one of them says
+ * nothing about the agent, and is refused as its name (`titleDisplayName` in lib/registry.ts).
+ *
+ * tmux titles every new pane with the machine's name as it is at that moment (`gethostname`), and an
+ * engine that sets no title of its own keeps it; Hermes sets its title to the hostname itself. A
+ * laptop's name follows its network (`MacBook.lan` at home, `MacBook.local` where the network names
+ * nothing). The daemon read the name once, at start, so after a change every pane made under the new
+ * name gave its agent the machine's name: found comparing with v0.3.58 (e2e/compat.e2e.ts), when the
+ * name changed during a run.
+ *
+ * So the name is read again on every title sweep and whenever the daemon has tmux make a pane, both a
+ * syscall, and every name read is kept: a pane made under the old name still carries it after the
+ * machine has moved on. Kept to the last MACHINE_NAMES_KEPT names seen, so a machine that roams many
+ * networks over weeks holds a few dozen strings, not one per network forever.
+ */
+import { readFileSync } from 'node:fs'
+import { hostname } from 'node:os'
+
+export const MACHINE_NAMES_KEPT = 16
+
+export interface MachineNames {
+ /** Reads the machine's name now and keeps it among the names it has had. */
+ observe(): void
+ /** Whether `title` is one of the machine's names, or the first part of one, in any case. */
+ owns(title: string): boolean
+}
+
+export function createMachineNames(read: () => string, kept = MACHINE_NAMES_KEPT): MachineNames {
+ // Each name in full and lower-cased, least recently seen first; and every form a title carries it in.
+ const names = new Set<string>()
+ let forms = new Set<string>()
+ const observe = (): void => {
+ let name = ''
+ try {
+ name = read().trim().toLowerCase()
+ } catch {
+ // No name now is no reason to forget the ones already seen.
+ }
+ if (!name) return
+ // Seen again: the most recent once more, so it is the last to go.
+ if (names.delete(name)) { names.add(name); return }
+ names.add(name)
+ for (const oldest of names) {
+ if (names.size <= kept) break
+ names.delete(oldest)
+ }
+ // `MacBookPro2021.local` and `MacBookPro2021` are the same machine wearing two names, and an
+ // engine may print either.
+ forms = new Set([...names].flatMap((full) => [full, full.split('.')[0]!]).filter(Boolean))
+ }
+ observe()
+ return { observe, owns: (title) => forms.has(title.toLowerCase()) }
+}
+
+/**
+ * The machine's name as the operating system has it. End to end, `file` (HARNESSD_TEST_HOSTNAME_FILE)
+ * stands in for it while the file holds a name: a test cannot change the computer's name, and must
+ * not. A file not written yet, or empty, is the computer's own name.
+ */
+export function hostnameReader(file: string | undefined): () => string {
+ if (!file) return hostname
+ return () => {
+ try {
+ const name = readFileSync(file, 'utf8').trim()
+ if (name) return name
+ } catch {
+ // Not written yet.
+ }
+ return hostname()
+ }
+}
+
+/** The daemon's: what its title sweep and its tmux panes read, and what titles are refused as. */
+export const machineNames = createMachineNames(hostnameReader(process.env.HARNESSD_TEST_HOSTNAME_FILE))
diff --git a/cli/src/lib/registry.spec.ts b/cli/src/lib/registry.spec.ts
index ff7673e05..495e44973 100644
--- a/cli/src/lib/registry.spec.ts
+++ b/cli/src/lib/registry.spec.ts
@@ -216,6 +216,43 @@ describe('registry remote display names', () => {
expect(registry.updateTitle('session-host', 'Ship settings page')?.title).toBe('Ship settings page')
})
+ it('refuses every name the machine has had while the daemon ran, not only the one it started with', async () => {
+ // A laptop's name follows its network, and tmux titles each new pane with the name of the moment.
+ // Read once at start, a pane made after the machine was renamed gave its agent the machine's name.
+ const hostFile = join(dataDir, 'hostname')
+ writeFileSync(hostFile, 'laptop-one.lan')
+ process.env.HARNESSD_TEST_HOSTNAME_FILE = hostFile
+ try {
+ const transcriptPath = join(dataDir, 'session-roam.jsonl')
+ writeFileSync(transcriptPath, '{}\n')
+ const { registry, projectDisplayName } = await loadRegistryModule()
+ const { machineNames } = await import('./machineNames.js')
+ registry.load()
+ const registered = registerProcess(registry, {
+ launcherId: 'h8', sessionId: 'session-roam', transcriptPath, tmuxPane: '%8', cwd: '/tmp/demo', title: 'laptop-one.lan',
+ })
+ expect(registered?.entry.title).toBeNull()
+
+ // The machine joins another network; the title sweep reads its name again.
+ writeFileSync(hostFile, 'laptop-two.local')
+ machineNames.observe()
+ expect(registry.updateTitle('session-roam', 'laptop-two.local')?.title).toBeNull()
+ expect(registry.updateTitle('session-roam', 'laptop-two')?.title).toBeNull()
+ // A pane made under the old name keeps it.
+ expect(registry.updateTitle('session-roam', 'laptop-one.lan')?.title).toBeNull()
+ expect(registry.updateTitle('session-roam', 'Ship settings page')?.title).toBe('Ship settings page')
+
+ // A title taken before the machine had that name stops showing once it has it.
+ const retitled = registry.updateTitle('session-roam', 'laptop-three.lan')!
+ expect(projectDisplayName(retitled)).toBe('laptop-three.lan')
+ writeFileSync(hostFile, 'laptop-three.lan')
+ machineNames.observe()
+ expect(projectDisplayName(retitled)).toBe('demo · sess')
+ } finally {
+ delete process.env.HARNESSD_TEST_HOSTNAME_FILE
+ }
+ })
+
it('only adds or updates agent-names.json entries', async () => {
const transcriptPath = join(dataDir, 'session-3.jsonl')
writeFileSync(transcriptPath, '{}\n')
diff --git a/cli/src/lib/registry.ts b/cli/src/lib/registry.ts
index 09b210765..f7f04411f 100644
--- a/cli/src/lib/registry.ts
+++ b/cli/src/lib/registry.ts
@@ -37,7 +37,7 @@ import {
} from 'fs'
import { randomUUID } from 'crypto'
import { join, basename, dirname, relative, isAbsolute } from 'path'
-import { hostname } from 'os'
+import { machineNames } from './machineNames.js'
import { cursorDataDir } from '../engines/cursor/home.js'
import { env } from '../config/env.js'
import { claudeProjectsRoots, codexHomeRoots } from './engineHomes.js'
@@ -2292,29 +2292,6 @@ function defaultProjectDisplayName(s: RegisteredSession): string {
return `${folder} · ${(s.sessionId || s.agentId).slice(0, 4)}`
}
-/**
- * The machine's own name, in the forms a terminal title is likely to carry it.
- *
- * Computed once: a rename mid-run would at worst let one title through, and reading it per title
- * would run a syscall for every agent on every title sweep.
- */
-const SELF_NAMES: ReadonlySet<string> = (() => {
- const names = new Set<string>()
- try {
- const host = hostname().trim().toLowerCase()
- if (host) {
- names.add(host)
- // `MacBookPro2021.local` and `MacBookPro2021` are the same machine wearing two names, and an
- // engine may print either.
- const short = host.split('.')[0]
- if (short) names.add(short)
- }
- } catch {
- // No hostname is not a reason to reject nothing else; the set simply stays empty.
- }
- return names
-})()
-
/**
* A pane title, as an agent NAME — or null when the title says nothing about this agent.
*
@@ -2326,7 +2303,10 @@ const SELF_NAMES: ReadonlySet<string> = (() => {
* identically for every one of them. A name that is the same for every agent on a machine is worse
* than no name: `defaultProjectDisplayName` at least says which folder and which session. This is
* about the machine, not the engine, so it is refused by what it SAYS rather than by who sent it —
- * any engine that adopts the same convention is covered without a table to keep in step.
+ * any engine that adopts the same convention is covered without a table to keep in step. tmux titles
+ * a new pane with the machine's name too, kept by any engine that sets no title of its own. Every
+ * name the machine has had while the daemon ran counts (lib/machineNames.ts): a laptop's name follows
+ * its network, and a pane keeps the name it was made under.
*/
export function titleDisplayName(title: string | null | undefined): string | null {
const cleaned = title
@@ -2335,7 +2315,7 @@ export function titleDisplayName(title: string | null | undefined): string | nul
.trim()
.slice(0, 80)
if (!cleaned) return null
- return SELF_NAMES.has(cleaned.toLowerCase()) ? null : cleaned
+ return machineNames.owns(cleaned) ? null : cleaned
}
function validProcessIdentity(value: unknown): value is ProcessIdentity {
diff --git a/cli/src/lib/tmuxBackend.spec.ts b/cli/src/lib/tmuxBackend.spec.ts
index 03d5f175e..e88f5eb43 100644
--- a/cli/src/lib/tmuxBackend.spec.ts
+++ b/cli/src/lib/tmuxBackend.spec.ts
@@ -1,4 +1,4 @@
-import { chmodSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { delimiter, join } from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
@@ -61,6 +61,21 @@ esac
])
})
+ it('reads the machine\'s name before tmux makes a pane, the name tmux titles it with', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'tmux-backend-name-'))
+ dirs.push(dir)
+ const calls = join(dir, 'calls')
+ writeFileSync(join(dir, 'tmux'), `#!/bin/sh\nprintf '%s\\n' "$*" >> "$TMUX_BACKEND_CALLS"\nprintf '%%42\\n'\n`, { mode: 0o700 })
+ process.env.PATH = `${dir}${delimiter}${originalPath ?? ''}`
+ process.env.TMUX_BACKEND_CALLS = calls
+ // Whether tmux had run yet, each time the backend read the machine's name.
+ const tmuxHadRun: boolean[] = []
+ const backend = new TmuxBackend(undefined, () => 'daemon-a', () => { tmuxHadRun.push(existsSync(calls)) })
+ expect((await backend.create({ cwd: '/tmp/work' })).state).toBe('succeeded')
+ expect(tmuxHadRun).toEqual([false])
+ expect(readFileSync(calls, 'utf8')).toContain('new-session')
+ })
+
it.each(['gone', 'present', 'unknown', 'malformed', 'no server', 'no socket', 'empty'] as const)('verifies %s inventory after a failed pane-close reply', async mode => {
const dir = mkdtempSync(join(tmpdir(), 'tmux-backend-close-'))
dirs.push(dir)
diff --git a/cli/src/lib/tmuxBackend.ts b/cli/src/lib/tmuxBackend.ts
index 3157b4d13..669ac5efa 100644
--- a/cli/src/lib/tmuxBackend.ts
+++ b/cli/src/lib/tmuxBackend.ts
@@ -36,6 +36,7 @@ import {
import { env } from '../config/env.js'
import { HARNESS_OWNER_OPTION, harnessPaneOwner } from './harnessSessionLabel.js'
import { DEFAULT_HOST_THEME, windowStyleOf, type HostTheme } from './hostTheme.js'
+import { machineNames } from './machineNames.js'
import { isNoTmuxServerError, listTmuxPanes } from './tmuxAgentDiscovery.js'
import { terminalRouteKey } from './terminalRuntime.js'
@@ -110,13 +111,19 @@ export class TmuxBackend implements TerminalBackend<TmuxRuntimeRef> {
* use rather than captured, so a theme the app sends later reaches sessions created after it.
* [owner] is the tag this daemon's panes carry (`HARNESS_OWNER_OPTION`), read at every create for
* the same reason as the theme: the data folder is the daemon's to move.
+ * [observeMachineName] reads the machine's name as tmux titles the new pane with it (lib/machineNames.ts).
*/
constructor(
private readonly hostTheme: () => HostTheme = () => DEFAULT_HOST_THEME,
private readonly owner: () => string = () => harnessPaneOwner(env.ADAPTER_DATA_DIR),
+ private readonly observeMachineName: () => void = () => machineNames.observe(),
) {}
async create(request: TerminalCreateRequest): Promise<TerminalCreateResult<TmuxRuntimeRef>> {
+ // tmux titles the pane it is about to make with the machine's name as it is now, and an engine
+ // that sets no title keeps it. Read here, that name is refused even if the machine has another
+ // by the next title sweep: a name it had only between two sweeps would otherwise never be seen.
+ this.observeMachineName()
const args = ['new-session', '-d', '-P', '-F', '#{pane_id}']
if (request.cwd) args.push('-c', request.cwd)
if (request.label) args.push('-s', request.label)
diff --git a/docs/design/2026-10-03-harnessd.md b/docs/design/2026-10-03-harnessd.md
index 8f3a8844c..4053b7e4e 100644
--- a/docs/design/2026-10-03-harnessd.md
+++ b/docs/design/2026-10-03-harnessd.md
@@ -953,6 +953,26 @@ Found while mapping, and fixed on their own rather than inside a move:
this one over, and the socket dropped it there instead of answering it, so hn waited out three
seconds each time. It is answered now (`e2e/terminal.e2e.ts`), and the comparison lists it as
changed on purpose.
+
+ Compared again with v0.3.58 and v0.3.57 once #805 had moved every core request into its module.
+ The scenario now also sends each moved request malformed, and reads a stopped agent's
+ conversation, list and recaps. Against v0.3.58 three things differ, each on purpose and listed
+ as changed:
+ - `terminal_info` is answered;
+ - a permission dialog's question carries `permission` (#764);
+ - `session_get` reads a stopped conversation (#797).
+
+ Against v0.3.57, `agent_handoff_prepare` differs too: that release did not have the request.
+ One run differed in agent titles. The machine's network name had changed during it, and the
+ released daemon had read its own name once, at start. The panes made after the change took the
+ new name as their title, on that side only. The test now fails such a run with that reason,
+ rather than reporting a difference.
+
+ The same thing happens to anyone whose laptop changes network: tmux titles a new pane with the
+ machine's name, and an agent whose engine sets no title was named after the machine. The daemon
+ now reads the name at every title sweep and whenever it has tmux make a pane, and every name the
+ machine has had while it ran is refused, the last 16 kept (`lib/machineNames.ts`). End to end
+ (`e2e/hostname.e2e.ts`), `HARNESSD_TEST_HOSTNAME_FILE` stands in for the machine's name.
- The sixteenth round (`e2e/ends.e2e.ts`), how an agent's life ends, for both engines:
- closed now, then opened again with its conversation;
- closed only when idle, which leaves a working agent working;