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.

harnessd: rounds 21 and 22, the person's tmux configuration and shell startup files (#772)

Deea4e29f5c25bf
diff --git a/cli/e2e/dotfiles.e2e.ts b/cli/e2e/dotfiles.e2e.ts
new file mode 100644
index 000000000..5eaa36f35
--- /dev/null
+++ b/cli/e2e/dotfiles.e2e.ts
@@ -0,0 +1,85 @@
+/**
+ * The person's shell startup files, for Claude Code and Codex. The daemon reads the login shell's
+ * environment and launches each engine through the person's interactive login shell, so their
+ * `.zshrc` runs first, and people's are noisy: a banner on stdout, warnings on stderr, a command that
+ * fails, a slow plugin manager, and a `cd` to where they keep their code. An agent must still start
+ * in its own folder, take turns, come back after a restart and be closed.
+ */
+import { mkdirSync, realpathSync, writeFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { afterEach, describe, expect, it, onTestFailed } from 'vitest'
+import { LocalClient, type Frame } from './harness/client.js'
+import { IsolatedDaemon, until } from './harness/daemon.js'
+
+type Engine = 'claude' | 'codex'
+type Row = Record<string, any>
+
+const rows = async (client: LocalClient): Promise<Row[]> =>
+ (await client.request<{ agents: Row[] }>('agents_list', { includeStopped: true }, 30_000)).agents
+const row = async (client: LocalClient, agentId: string) => (await rows(client)).find((agent) => agent.id === agentId)
+async function create(d: IsolatedDaemon, client: LocalClient, engine: Engine, folder: string): Promise<Row> {
+ const cwd = join(d.projectsDir, folder)
+ mkdirSync(cwd, { recursive: true })
+ const created = await client.request('agent_create', { engine, cwd, bypassPermission: true }, 120_000)
+ expect(created.error, `${folder}: ${JSON.stringify(created)}`).toBeUndefined()
+ return until(`${folder} to bind its conversation`, async () => {
+ const agent = await row(client, created.agent.id)
+ return agent?.sessionId && agent.status === 'active' ? agent : null
+ }, 90_000, 500)
+}
+const isTurn = (type: string, agentId: string) => (frame: Frame) => frame.type === type && frame.agentId === agentId
+async function turn(client: LocalClient, agentId: string, content: string): Promise<void> {
+ const started = client.next(isTurn('turn_started', agentId), 45_000, `turn_started (${content})`)
+ const ended = client.next(isTurn('turn_ended', agentId), 45_000, `turn_ended (${content})`)
+ client.send('message', { agentId, content })
+ expect((await started).payload?.userMessage).toBe(content)
+ await ended
+}
+
+describe('the person\'s shell startup files', () => {
+ let daemon: IsolatedDaemon | undefined
+ afterEach(async () => { await daemon?.close(); daemon = undefined })
+
+ it.each(['claude', 'codex'] as const)('%s: under a noisy, slow .zshrc that changes folder, an agent starts in its own folder and works', async (engine) => {
+ const d = await IsolatedDaemon.create()
+ daemon = d
+ onTestFailed(() => { console.log(`---- daemon log\n${d.log().split('\n').slice(-150).join('\n')}`) })
+ const elsewhere = join(d.root, 'where-i-keep-code')
+ mkdirSync(elsewhere, { recursive: true })
+ // ZDOTDIR is the throwaway home: this is the .zshrc every shell the daemon starts reads.
+ writeFileSync(join(d.env.ZDOTDIR!, '.zshrc'), [
+ 'echo "Welcome back! Today is a good day to code."',
+ 'echo "warning: nvm is slow" >&2',
+ 'sleep 1',
+ 'this-command-does-not-exist 2>/dev/null',
+ `cd ${JSON.stringify(elsewhere)}`,
+ 'PS1="%n@%m %~ %# "',
+ '',
+ ].join('\n'))
+ writeFileSync(join(d.env.ZDOTDIR!, '.zprofile'), 'echo "zprofile says hello"\n')
+ await d.start()
+ let client = await LocalClient.connect(d)
+ const agent = await create(d, client, engine, `dotfiles-${engine}`)
+ // The .zshrc did run: its banner is in the pane's history, above the engine.
+ const pane = String(agent.terminal?.runtimes?.[0]?.paneId ?? agent.tmuxPane)
+ expect(await d.tmux.run('capture-pane', '-p', '-S', '-500', '-t', pane)).toContain('Welcome back! Today is a good day to code.')
+ // The engine runs in the agent's folder, not where the .zshrc went.
+ const info = await client.request('terminal_info', { agentId: agent.id }, 10_000)
+ expect(info.error, JSON.stringify(info)).toBeUndefined()
+ expect(realpathSync(info.path)).toBe(realpathSync(join(d.projectsDir, `dotfiles-${engine}`)))
+ await turn(client, agent.id, 'under a noisy shell')
+ client.close()
+ await d.restart()
+ client = await LocalClient.connect(d)
+ await until('the agent back after the restart', async () => {
+ const now = await row(client, agent.id)
+ return now?.status === 'active' && now.sessionId === agent.sessionId ? now : null
+ }, 90_000, 500)
+ const back = await client.request('terminal_info', { agentId: agent.id }, 10_000)
+ expect(realpathSync(back.path)).toBe(realpathSync(join(d.projectsDir, `dotfiles-${engine}`)))
+ await turn(client, agent.id, 'after the restart')
+ const now = (await row(client, agent.id))!
+ expect(await client.request('agent_close', { agentId: agent.id, sessionId: now.sessionId, createdAt: now.createdAt, mode: 'now' }, 60_000)).toMatchObject({ closed: true })
+ client.close()
+ }, 300_000)
+})
diff --git a/cli/e2e/tmuxconf.e2e.ts b/cli/e2e/tmuxconf.e2e.ts
new file mode 100644
index 000000000..9523ce52c
--- /dev/null
+++ b/cli/e2e/tmuxconf.e2e.ts
@@ -0,0 +1,116 @@
+/**
+ * The person's own tmux configuration, for Claude Code and Codex. The daemon's agents live on the
+ * person's default tmux server, so that server loads their `~/.tmux.conf`, and people configure tmux
+ * heavily: windows and panes numbered from 1, another prefix, vi keys, a long or a tiny history,
+ * renamed and renumbered windows, the mouse, activity alerts. Some options would end an agent the
+ * moment it was made if they applied to it: `destroy-unattached` ends any session no client is
+ * attached to (every agent's), and `exit-empty` and session hooks have their say too. An agent must be
+ * made, take turns, be closed and come back after a restart under any of them.
+ */
+import { mkdirSync, writeFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { afterEach, describe, expect, it, onTestFailed } from 'vitest'
+import { LocalClient, type Frame } from './harness/client.js'
+import { IsolatedDaemon, until } from './harness/daemon.js'
+
+type Engine = 'claude' | 'codex'
+type Row = Record<string, any>
+
+const rows = async (client: LocalClient): Promise<Row[]> =>
+ (await client.request<{ agents: Row[] }>('agents_list', { includeStopped: true }, 30_000)).agents
+const row = async (client: LocalClient, agentId: string) => (await rows(client)).find((agent) => agent.id === agentId)
+async function create(d: IsolatedDaemon, client: LocalClient, engine: Engine, folder: string): Promise<Row> {
+ const cwd = join(d.projectsDir, folder)
+ mkdirSync(cwd, { recursive: true })
+ const created = await client.request('agent_create', { engine, cwd, bypassPermission: true }, 90_000)
+ expect(created.error, `${folder}: ${JSON.stringify(created)}`).toBeUndefined()
+ return until(`${folder} to bind its conversation`, async () => {
+ const agent = await row(client, created.agent.id)
+ return agent?.sessionId && agent.status === 'active' ? agent : null
+ }, 60_000, 500)
+}
+const isTurn = (type: string, agentId: string) => (frame: Frame) => frame.type === type && frame.agentId === agentId
+async function turn(client: LocalClient, agentId: string, content: string): Promise<void> {
+ const started = client.next(isTurn('turn_started', agentId), 45_000, `turn_started (${content})`)
+ const ended = client.next(isTurn('turn_ended', agentId), 45_000, `turn_ended (${content})`)
+ client.send('message', { agentId, content })
+ expect((await started).payload?.userMessage).toBe(content)
+ await ended
+}
+
+// What a heavily configured tmux looks like: every line here is common in published dotfiles.
+const EVERYDAY = `
+set -g prefix C-a
+unbind C-b
+bind C-a send-prefix
+set -g base-index 1
+setw -g pane-base-index 1
+set -g renumber-windows on
+set -g history-limit 100
+setw -g mode-keys vi
+set -g mouse on
+set -g escape-time 0
+set -g default-terminal "tmux-256color"
+set -g status-position top
+set -g status-interval 1
+set -g allow-rename off
+setw -g automatic-rename off
+set -g set-titles on
+setw -g monitor-activity on
+set -g visual-activity on
+set -g focus-events on
+set -g remain-on-exit off
+`
+
+// Options that would end an agent the moment it was made, if the daemon let them apply to its own.
+const DANGEROUS = `
+set -g destroy-unattached on
+set -g exit-empty on
+set -g detach-on-destroy on
+set-hook -g session-created 'set -g status off'
+`
+
+describe('the person\'s own tmux configuration', () => {
+ let daemon: IsolatedDaemon | undefined
+ afterEach(async () => { await daemon?.close(); daemon = undefined })
+ const withConfig = async (config: string) => {
+ const d = await IsolatedDaemon.create()
+ daemon = d
+ onTestFailed(() => { console.log(`---- daemon log\n${d.log().split('\n').slice(-150).join('\n')}`) })
+ // The daemon's server is the person's default one, and loads their configuration from home.
+ writeFileSync(join(d.env.HOME!, '.tmux.conf'), config)
+ await d.start()
+ return d
+ }
+
+ it.each([['an everyday configuration', EVERYDAY], ['options that would end a session no client watches', DANGEROUS]] as const)(
+ 'under %s, agents are made, take turns, come back after a restart and are closed',
+ async (_name, config) => {
+ const d = await withConfig(config)
+ let client = await LocalClient.connect(d)
+ const agents = [await create(d, client, 'claude', 'conf-claude'), await create(d, client, 'codex', 'conf-codex')]
+ // Still there a moment later: nothing in the configuration ended them once they were made.
+ await new Promise((resolve) => setTimeout(resolve, 3_000))
+ for (const agent of agents) {
+ expect((await row(client, agent.id))?.status, agent.engine).toBe('active')
+ await turn(client, agent.id, `under the configuration (${agent.engine})`)
+ }
+ client.close()
+ await d.restart()
+ client = await LocalClient.connect(d)
+ for (const agent of agents) {
+ await until(`${agent.engine} back after the restart`, async () => {
+ const now = await row(client, agent.id)
+ return now?.status === 'active' && now.sessionId === agent.sessionId ? now : null
+ }, 60_000, 500)
+ await turn(client, agent.id, `after the restart (${agent.engine})`)
+ }
+ for (const agent of agents) {
+ const now = (await row(client, agent.id))!
+ expect(await client.request('agent_close', { agentId: agent.id, sessionId: now.sessionId, createdAt: now.createdAt, mode: 'now' }, 60_000)).toMatchObject({ closed: true })
+ }
+ expect(d.coresStarted()).toBe(2)
+ client.close()
+ },
+ )
+})
diff --git a/cli/src/lib/tmuxBackend.spec.ts b/cli/src/lib/tmuxBackend.spec.ts
index 8ced2e043..e7e71e6fb 100644
--- a/cli/src/lib/tmuxBackend.spec.ts
+++ b/cli/src/lib/tmuxBackend.spec.ts
@@ -54,7 +54,7 @@ esac
// and its error text with it.
// `window-style` rides the same invocation for the same reason: the engine asks its
// terminal for its colours (OSC 10/11) once, at startup, and never again.
- 'new-session -d -P -F #{pane_id} -c /tmp/work -s harness-test ; set-option -w remain-on-exit on ; set-option -w window-style bg=#181818,fg=#f5f5f5',
+ 'new-session -d -P -F #{pane_id} -c /tmp/work -s harness-test ; set-option -w remain-on-exit on ; set-option destroy-unattached off ; set-option -w window-style bg=#181818,fg=#f5f5f5',
'set-option -t %42 mouse on',
'kill-pane -t %42',
])
@@ -109,7 +109,7 @@ esac
await backend.inventory()
const styleCalls = () => readFileSync(calls, 'utf8').trim().split('\n').filter((line) => line.includes('window-style'))
await vi.waitFor(() => expect(styleCalls()).toEqual([
- 'new-session -d -P -F #{pane_id} -c /tmp/work -s harness-codex-1 ; set-option -w remain-on-exit on ; set-option -w window-style bg=#171b29,fg=#f5f5f5',
+ 'new-session -d -P -F #{pane_id} -c /tmp/work -s harness-codex-1 ; set-option -w remain-on-exit on ; set-option destroy-unattached off ; set-option -w window-style bg=#171b29,fg=#f5f5f5',
// The pane this daemon did not create is styled on the first scan; %7 already was.
'set-option -w -t %9 window-style bg=#171b29,fg=#f5f5f5',
// The app changed its palette: every live pane, once.
@@ -318,7 +318,7 @@ printf '%%42\\n'
'new-session -d -P -F #{pane_id} -c /tmp/work -s harness-test'
+ ' -e ANTHROPIC_BASE_URL=https://relay.example/relay -e ANTHROPIC_AUTH_TOKEN=gridkey-abc123'
+ ' /bin/zsh -lic exec "$@" harness-engine claude ; set-option -w remain-on-exit on'
- + ' ; set-option -w window-style bg=#181818,fg=#f5f5f5',
+ + ' ; set-option destroy-unattached off ; set-option -w window-style bg=#181818,fg=#f5f5f5',
)
})
it('respawns a pane in place with a new environment, keeping the pane id', async () => {
diff --git a/cli/src/lib/tmuxBackend.ts b/cli/src/lib/tmuxBackend.ts
index fda7aa994..286cae342 100644
--- a/cli/src/lib/tmuxBackend.ts
+++ b/cli/src/lib/tmuxBackend.ts
@@ -122,6 +122,11 @@ export class TmuxBackend implements TerminalBackend<TmuxRuntimeRef> {
// already gone before the follow-up command could reach the server.
// Whoever created the pane owns turning this back off; see `clearPaneRemainOnExit`.
args.push(';', 'set-option', '-w', 'remain-on-exit', 'on')
+ // An agent's session never has a client attached, so a person's `set -g destroy-unattached on`
+ // (in their ~/.tmux.conf, which this server loads) ended every agent the moment it was made, and
+ // Harness could not run at all on their machine (found end to end, e2e/tmuxconf.e2e.ts). Turned
+ // off for this session only, in this same invocation, before the server can act on it.
+ args.push(';', 'set-option', 'destroy-unattached', 'off')
// Same invocation, same reason: an engine asks its terminal for its colours (OSC 10/11) in its
// first milliseconds and never again, so the style has to be there before the engine is.
const style = windowStyleOf(this.hostTheme())