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.

Agent Messages runs in the edge host: no process of its own, and off costs nothing (#1274)

Deeda01517528ca
diff --git a/cli/AGENTS.md b/cli/AGENTS.md
index 7147a306e..e0eea6328 100644
--- a/cli/AGENTS.md
+++ b/cli/AGENTS.md
@@ -28,12 +28,12 @@ they show as `harnessd`, `harnessd-core` and `harnessd-<process>` (`src/harnessd
| engine-claude, engine-codex | history, last-turn readers, live transcript parsers, runtime profiles/catalogs, screen interpretation, submission verification readings, model control, question navigation, and (Codex) the shared app-server connection | on demand: an attach or read for that engine |
| search | session search | always |
| viewers | the harness viewers, their remote streams and rendered surfaces, and the Store | on demand: a harness here (an agent with a DSH at start, or attached since), a Store or viewers request (the list, an install, a harness's create or restore, a client's viewer stream or rendered frame), or at start when the release's own harnesses are to be put in place or an earlier process left viewer servers running |
-| edge | the shell service, workspaces, usage, the monitor, the project readers, the change-agent handoff, the recaps, the agent cleanup | always |
+| edge | the shell service, workspaces, usage, the monitor, the project readers, the change-agent handoff, the recaps, the agent cleanup, Agent Messages (which runs no timer while it is off or the computer is signed out) | always |
| gateway | the relay and its E2EE (`src/gateway/`) | on demand: as the core starts when signed in or anything is paired here, or when something needs it (a pairing, a window's E2EE request, a key command, the Wi-Fi device) |
| models | grid, local models, the Model Manager | on demand: once grid is in use here (a managed grid, saved grid pictures, local models), or on a models request |
| updater | checks, downloads and stages a new build (`src/services/updaterProcess.ts`) | by the master, for the installed copy only |
| devices | the dials, the window bridges, the fleet, the voice router, the Wi-Fi device | on demand: once there is a device |
-| orchestrator, messages (Agent Messages), sharing, memory, router | the experiments | on demand: on a request, or saved state at start; messages also at start while Settings ▸ Agents has it on (the default) |
+| orchestrator, sharing, memory, router | the experiments | on demand: on a request, or saved state at start |
`HARNESSD_SERVICES` names a subset to run in their own processes, by service or by process.
`HARNESSD_SERVICES=none` runs every service in the core's process, for debugging or a quick way back. How
diff --git a/cli/e2e/agentMessages.e2e.ts b/cli/e2e/agentMessages.e2e.ts
index 86fecd2e3..6956ff2ba 100644
--- a/cli/e2e/agentMessages.e2e.ts
+++ b/cli/e2e/agentMessages.e2e.ts
@@ -1,15 +1,16 @@
/**
- * Agent Messages on the real daemon (docs/design/2026-10-10-agent-messages.md): its own process, started with the
- * core while Settings ▸ Agents has it on (the default), and otherwise only once it is used; a message typed into an
- * idle agent through the core's safe input; and a message reaching a working agent through its PostToolUse hook at
- * its next tool call, with nothing typed into its pane. The fake engines run the hooks the daemon installed, as both
+ * Agent Messages on the real daemon (docs/design/2026-10-10-agent-messages.md): a service in the edge host, with no
+ * process of its own, that reads the account's tabs only while Settings ▸ Agents has it on and wakes when it is turned
+ * on, through the daemon or by the file; a message typed into an idle agent through the core's safe input,
+ * in the edge host and in the core's own process; and a message reaching a working agent through its PostToolUse hook
+ * at its next tool call, with nothing typed into its pane. The fake engines run the hooks the daemon installed, as both
* CLIs do (harness/fakeEngine.mjs, `!work`).
*
* The directory of tabs comes from the account: the daemon is signed in to the fake backend, which answers it. Each
* tab's own flag, which older windows still turn, is no part of it: one switch per computer decides (owner,
* 2026-10-12).
*/
-import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
+import { mkdirSync, readFileSync, 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'
@@ -19,6 +20,8 @@ import { writeAgentSettings } from '../src/lib/agentSettings.js'
/** Signed in to the fake backend, which answers the account's tabs (`GET /api/agent-messages`). */
const ME: FakeMachine = { machineId: 'a7'.repeat(16), computerId: 'e2e-computer-0000-0000-0000000000a7', name: 'studio', token: 'e2e-token-messages' }
+/** Signed in, with Agent Messages turned on in Settings ▸ Agents: never left to the default. */
+const on = (d: IsolatedDaemon) => { signIn(d); writeAgentSettings(d.dataDir, { agentMessages: true }) }
const signIn = (d: IsolatedDaemon) => writeFileSync(join(d.root, 'auth', 'session.json'), JSON.stringify({
version: 1, accessToken: ME.token, autonomousEnv: 'prod', computerId: ME.computerId,
machineId: ME.machineId, expiresAt: Date.now() + 30 * 24 * 3600_000, updatedAt: Date.now(), signInEpoch: 'e2e',
@@ -37,7 +40,11 @@ async function create(d: IsolatedDaemon, client: LocalClient, folder: string, en
return agent?.sessionId && agent.status === 'active' ? agent : null
}, 60_000, 500)
}
+/** A process of its own, as it had while it was an experiment: none now. */
const starts = (d: IsolatedDaemon) => [...d.log().matchAll(/\[harnessd\] service messages started/g)].length
+const connected = (d: IsolatedDaemon) => d.log().split('[services] messages connected').length - 1
+/** How often it read the account's tabs. */
+const reads = (relay: FakeBackend) => relay.seen.filter((line) => line.split('?')[0] === 'GET /api/agent-messages').length
/** Settings ▸ Agents, as the window turns a switch: through the daemon, which wakes what it turned on. */
const settings = (d: IsolatedDaemon, body: Record<string, boolean>) => fetch(`http://127.0.0.1:${d.port}/api/agent-settings`, {
method: 'PATCH', headers: { 'x-adapter-local': '1', 'content-type': 'application/json' }, body: JSON.stringify(body) })
@@ -72,34 +79,24 @@ describe('Agent Messages, end to end', () => {
return d
}
- it('turned off in Settings ▸ Agents, it has no process; its first request starts it, and is answered', async () => {
+ it('runs in the edge host, with no process of its own, and answers there whether it is on or off', async () => {
+ // As an experiment it was a process of its own on every computer it was on, 62 MiB at idle (2026-10-12).
const d = await fresh((daemon) => writeAgentSettings(daemon.dataDir, { agentMessages: false }))
const client = await LocalClient.connect(d)
- await until('the services to connect', () => d.log().includes('[services] search connected') || null, 30_000, 200)
- expect(starts(d), 'an experiment no one used').toBe(0)
+ await until('Agent Messages to connect from the edge host', () => connected(d) || null, 30_000, 200)
+ expect(d.log()).toMatch(/\[harnessd\] service edge started/)
+ expect(starts(d)).toBe(0)
expect(await client.request('agent_messages', { action: 'history' }, 40_000)).toMatchObject({ messages: [] })
- expect(starts(d)).toBe(1)
- await until('Agent Messages to connect', () => d.log().includes('[services] messages connected') || null, 30_000, 200)
expect(d.coresStarted()).toBe(1)
client.close()
})
- it('its saved state turns it on as the daemon starts, even turned off in Settings ▸ Agents', async () => {
- // What waits there is held, then failed, rather than left behind.
- const d = await fresh((daemon) => {
- mkdirSync(join(daemon.dataDir, 'agent-messages'), { recursive: true })
- writeAgentSettings(daemon.dataDir, { agentMessages: false })
- })
- await until('Agent Messages to start for its saved state', () => d.log().includes('[services] messages connected') || null, 30_000, 200)
- expect(starts(d)).toBe(1)
- })
-
/** Signed in to the fake backend, with lead and api in one tab. */
- const team = async (engine = 'claude') => {
+ const team = async (engine = 'claude', env: Record<string, string> = {}) => {
const relay = await FakeBackend.start()
backend = relay
relay.addMachine(ME)
- const d = await fresh(signIn, { BACKEND_WS_URL: relay.wsUrl, WEB_URL: relay.httpUrl, ADAPTER_COMPUTER_ID: ME.computerId })
+ const d = await fresh(on, { BACKEND_WS_URL: relay.wsUrl, WEB_URL: relay.httpUrl, ADAPTER_COMPUTER_ID: ME.computerId, ...env })
const client = await LocalClient.connect(d, { machineId: ME.machineId })
const lead = await create(d, client, 'lead')
const api = await create(d, client, `api-${engine}`, engine)
@@ -112,16 +109,14 @@ describe('Agent Messages, end to end', () => {
return { d, relay, client, lead, api, apiName, send }
}
- it('on by default, it starts with a fresh daemon, with no request and no saved state, and gives two agents in one tab their note', async () => {
- // Each tab had a switch of its own, off by default, which the owner hit by mistake: one setting replaced it, on by
- // default (2026-10-12). Started only by a request or saved state, on one machine nothing started it, and no agent
- // heard of `harness send` (a fresh Mac, 2026-10-12).
+ it('on in Settings ▸ Agents, it runs with a fresh daemon, with no request and no saved state, and gives two agents in one tab their note', async () => {
+ // Started only by a request or saved state, on one machine nothing started it, and no agent heard of `harness send`
+ // (a fresh Mac, 2026-10-12).
const relay = await FakeBackend.start()
backend = relay
relay.addMachine(ME)
- const d = await fresh(signIn, { BACKEND_WS_URL: relay.wsUrl, WEB_URL: relay.httpUrl, ADAPTER_COMPUTER_ID: ME.computerId })
- expect(existsSync(join(d.dataDir, 'agent-settings.json')), 'the default, never written').toBe(false)
- await until('Agent Messages to start for its setting', () => starts(d) === 1 || null, 30_000, 200)
+ const d = await fresh(on, { BACKEND_WS_URL: relay.wsUrl, WEB_URL: relay.httpUrl, ADAPTER_COMPUTER_ID: ME.computerId })
+ await until('Agent Messages to read the account\'s tabs', () => reads(relay) >= 1 || null, 30_000, 200)
const client = await LocalClient.connect(d, { machineId: ME.machineId })
const lead = await create(d, client, 'lead')
const api = await create(d, client, 'api')
@@ -131,11 +126,12 @@ describe('Agent Messages, end to end', () => {
// Each agent's note waits in its inbox for its next tool call; read again at its 15-second look.
const notes = await notesFor(d, 2)
expect(Object.keys(notes).sort()).toEqual([lead.id, api.id].sort())
- expect(starts(d)).toBe(1)
+ expect(starts(d)).toBe(0)
client.close()
})
- it('starts once Settings ▸ Agents turns it on, with no other request; an older window\'s tab switch starts nothing', async () => {
+ it('off, reads no tabs; wakes once Settings ▸ Agents turns it on, or `harness settings` writes the file; an older window\'s tab switch wakes nothing', async () => {
+ // Off costs nothing: on every computer, off or not, it read the account's tabs every 15 s (2026-10-12).
const relay = await FakeBackend.start()
backend = relay
relay.addMachine(ME)
@@ -146,24 +142,35 @@ describe('Agent Messages, end to end', () => {
const api = await create(d, client, 'api')
relay.agentMessages = { revision: 1, machines: [{ machineId: ME.machineId, name: 'studio' }],
tabs: [{ id: 'app', name: 'app', enabled: false, panes: [lead, api].map((agent) => ({ machineId: ME.machineId, agentId: agent.id })) }] }
- await until('the services to connect', () => d.log().includes('[services] search connected') || null, 30_000, 200)
+ await until('Agent Messages to connect from the edge host', () => connected(d) || null, 30_000, 200)
// An older window's chat icon still reaches the backend, and decides nothing here.
const tab = await fetch(`http://127.0.0.1:${d.port}/api/agent-messages/tabs/app`, {
method: 'PATCH', headers: { 'x-adapter-local': '1', 'content-type': 'application/json' }, body: JSON.stringify({ enabled: true }) })
expect(tab.status).toBe(200)
expect((await settings(d, { pullRequestLine: true })).status).toBe(200)
- await new Promise((settle) => setTimeout(settle, 1_000))
- expect(starts(d), 'off in Settings ▸ Agents, nothing starts').toBe(0)
+ // Longer than its 15-second read: off, there is none.
+ await new Promise((settle) => setTimeout(settle, 17_000))
+ expect(reads(relay), 'off in Settings ▸ Agents, the tabs are never read').toBe(0)
const on = await settings(d, { agentMessages: true })
expect(await on.json()).toMatchObject({ agentMessages: true })
- await until('Agent Messages to start for the setting turned on', () => starts(d) === 1 || null, 30_000, 200)
+ await until('Agent Messages to wake for the setting turned on', () => reads(relay) >= 1 || null, 30_000, 200)
const notes = await notesFor(d, 2)
expect(Object.keys(notes).sort()).toEqual([lead.id, api.id].sort())
+ // Off again, then on from a terminal: `harness settings` writes the file and tells no one.
+ expect((await settings(d, { agentMessages: false })).status).toBe(200)
+ await notesFor(d, 0)
+ await new Promise((settle) => setTimeout(settle, 1_000))
+ const before = reads(relay)
+ writeAgentSettings(d.dataDir, { agentMessages: true })
+ await until('Agent Messages to wake for the file', () => reads(relay) > before || null, 30_000, 200)
+ await notesFor(d, 2)
+ expect(starts(d)).toBe(0)
client.close()
})
- it('types a message into an idle agent, under its sender\'s header, through the core\'s safe input', async () => {
- const { client, api, send } = await team()
+ it.each([['the edge host', {}], ['the core\'s process (HARNESSD_SERVICES=none)', { HARNESSD_SERVICES: 'none' }],
+ ['a process of its own (HARNESSD_SERVICES=messages)', { HARNESSD_SERVICES: 'messages' }]])('types a message into an idle agent, under its sender\'s header, through the core\'s safe input, from %s', async (_where, env) => {
+ const { client, api, send } = await team('claude', env)
const started = client.next((frame: Frame) => frame.type === 'turn_started' && frame.agentId === api.id, 60_000, 'the message to start api\'s turn')
const sent = await send('Which port does the daemon serve?')
expect(sent.error, JSON.stringify(sent)).toBeUndefined()
diff --git a/cli/e2e/endurance.e2e.ts b/cli/e2e/endurance.e2e.ts
index 8390de4c9..6cda5938b 100644
--- a/cli/e2e/endurance.e2e.ts
+++ b/cli/e2e/endurance.e2e.ts
@@ -84,10 +84,9 @@ const PROBES: Record<string, { type: string; payload: Record<string, unknown> }>
models: { type: 'models_list', payload: {} },
devices: { type: 'harness_devices_list', payload: {} },
orchestrator: { type: 'orchestrator', payload: { action: 'list' } },
- messages: { type: 'agent_messages', payload: { action: 'history' } },
}
/** The service names a process's comings and goings are logged under (`[services] <name> connected`). */
-const LINKS: Record<string, string> = { 'engine-claude': 'engine-claude', 'engine-codex': 'engine-codex', search: 'search', viewers: 'viewers', edge: 'monitor', gateway: 'gateway', models: 'models', devices: 'devices', orchestrator: 'orchestrator', messages: 'messages', sharing: 'sharing' }
+const LINKS: Record<string, string> = { 'engine-claude': 'engine-claude', 'engine-codex': 'engine-codex', search: 'search', viewers: 'viewers', edge: 'monitor', gateway: 'gateway', models: 'models', devices: 'devices', orchestrator: 'orchestrator', sharing: 'sharing' }
const down = (answer: Record<string, unknown>) => answer.error === 'SERVICE_UNAVAILABLE' || answer.error === 'SERVICE_FAILED' || answer.error === 'GATEWAY_UNAVAILABLE' || answer.error === 'ENGINE_UNAVAILABLE' || answer.error === 'ENGINE_STALE_REPLY' || answer.error === 'ENGINE_BUSY'
const acceptable = (name: string, answer: Record<string, unknown>): boolean => answer.error === undefined
@@ -242,7 +241,7 @@ async function deskLoop(d: IsolatedDaemon, agentIds: string[], deadline: () => b
if (drawn.length) window.send('terminal_ack', { streamId, lastSeq: drawn[drawn.length - 1].seq })
}
const service = Object.keys(PROBES)[Math.floor(rand() * Object.keys(PROBES).length)]
- if (rand() < 0.4 && !['orchestrator', 'messages'].includes(service)) await ask(window, service)
+ if (rand() < 0.4 && service !== 'orchestrator') await ask(window, service)
forget(window)
await sleep(2_000)
}
diff --git a/cli/e2e/footprint.e2e.ts b/cli/e2e/footprint.e2e.ts
new file mode 100644
index 000000000..643312c70
--- /dev/null
+++ b/cli/e2e/footprint.e2e.ts
@@ -0,0 +1,201 @@
+/**
+ * FOOTPRINT=1 E2E_BUNDLE=1: what the daemon costs in memory at idle, every process of it.
+ *
+ * FOOTPRINT=1 E2E_BUNDLE=1 npx vitest run --config vitest.e2e.config.ts e2e/footprint.e2e.ts
+ *
+ * An isolated daemon from the run's bundle (as a release ships it), signed in to the fake backend, with two agents
+ * (Claude Code and Codex) in one tab, measured once for each state of Agent Messages (FOOTPRINT_SCENARIOS, all three
+ * by default): `on`, written so in Settings ▸ Agents, and active (it has given both agents their note); `off`, written
+ * so; and `defaults`, with no Settings ▸ Agents written at all, as most computers are. After a warm-up
+ * (FOOTPRINT_WARMUP_SECONDS, 20) each stays idle for FOOTPRINT_SECONDS (30) while `ps` reads, every second, the
+ * resident memory of every process under the master: the master (`harnessd`), the core (`harnessd-core`), each
+ * service process (`harnessd-<name>`) and the engine workers. Each is named by its process title, or by the pid the
+ * master logged it under. Reported per process as the mean over the window, and in total: a readable table on stdout
+ * for each, and JSON of all of them to FOOTPRINT_REPORT when it is set. Processes that are not the daemon's own (a `ps`
+ * the monitor ran at that moment) are listed apart and left out of the total.
+ *
+ * Measurement only, no limit: it was written to answer what Agent Messages costs in a process of its own against in
+ * the edge host (2026-10-12). Run it on two builds on the same machine, one after the other, and compare.
+ */
+import { execFile, execFileSync } from 'node:child_process'
+import { createHash } from 'node:crypto'
+import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
+import { cpus, platform, release, totalmem } from 'node:os'
+import { basename, dirname, join, resolve } from 'node:path'
+import { describe, expect, it } from 'vitest'
+import { writeAgentSettings } from '../src/lib/agentSettings.js'
+import { LocalClient } from './harness/client.js'
+import { CLI_ROOT, IsolatedDaemon, until } from './harness/daemon.js'
+import { harnessdProcesses } from './harness/endurance.js'
+import { FakeBackend, type FakeMachine } from './harness/fakeBackend.js'
+
+const ME: FakeMachine = { machineId: 'f0'.repeat(16), computerId: 'e2e-computer-0000-0000-0000000000f0', name: 'footprint', token: 'e2e-token-footprint' }
+const MIB = 1024 * 1024
+const sleep = (ms: number) => new Promise<void>((done) => setTimeout(done, ms))
+
+function knob(name: string, fallback: number, min: number, max: number): number {
+ const n = Number(process.env[name] ?? fallback)
+ if (!Number.isInteger(n) || n < min || n > max) throw new Error(`${name} must be an integer from ${min} to ${max}`)
+ return n
+}
+
+interface Row { pid: number; ppid: number; rssBytes: number; command: string }
+
+/** Every process on the machine, as `ps` sees it: pid, parent, resident memory and command line. */
+const table = () => new Promise<Row[]>((done, fail) => {
+ execFile('ps', ['-axo', 'pid=,ppid=,rss=,command='], { timeout: 5_000, maxBuffer: 16 * MIB }, (error, stdout) => {
+ if (error) { fail(error); return }
+ done(String(stdout).split('\n').flatMap((line) => {
+ const match = /^\s*(\d+)\s+(\d+)\s+(\d+)\s+(.*)$/.exec(line)
+ return match ? [{ pid: Number(match[1]), ppid: Number(match[2]), rssBytes: Number(match[3]) * 1024, command: match[4].trim() }] : []
+ }))
+ })
+})
+
+/** The processes under [root], [root] included. */
+function tree(rows: Row[], root: number): Row[] {
+ const children = new Map<number, Row[]>()
+ for (const row of rows) children.set(row.ppid, [...(children.get(row.ppid) ?? []), row])
+ const found: Row[] = []
+ const pending = rows.filter((row) => row.pid === root)
+ while (pending.length) {
+ const row = pending.pop()!
+ found.push(row)
+ pending.push(...(children.get(row.pid) ?? []))
+ }
+ return found
+}
+
+/**
+ * What a process is called: its title (`harnessd`, `harnessd-core`, `harnessd-edge`…), which the master's hard links
+ * give it in a release (harnessd/processName.ts) and a service sets itself (serviceProcess.ts); else the name the
+ * master logged its pid under; else `other: <program>`.
+ */
+function nameOf(row: Row, logged: ReadonlyMap<number, string>): string {
+ const program = basename(row.command.split(/\s+/)[0] ?? '')
+ if (/^harnessd(-[\w-]+)?$/.test(program)) return program
+ const known = logged.get(row.pid)
+ if (known) return known === 'master' ? 'harnessd' : `harnessd-${known}`
+ return `other: ${program}`
+}
+
+type Scenario = 'on' | 'off' | 'defaults'
+const SCENARIOS: Record<Scenario, string> = {
+ on: 'Agent Messages on in Settings ▸ Agents, active: both agents have their note',
+ off: 'Agent Messages off in Settings ▸ Agents',
+ defaults: 'Settings ▸ Agents never written: every switch at its default',
+}
+const chosen = (process.env.FOOTPRINT_SCENARIOS ?? 'on,off,defaults').split(',').map((name) => name.trim()).filter((name): name is Scenario => name in SCENARIOS)
+/** Every scenario measured in this run, written whole to FOOTPRINT_REPORT after each. */
+const reports: Record<string, unknown> = {}
+
+describe.runIf(process.env.FOOTPRINT === '1')('the daemon\'s memory at idle', () => {
+ it.each(chosen)('reports every process\'s resident memory, and the total, with two agents in a tab: Agent Messages %s', async (scenario) => {
+ const seconds = knob('FOOTPRINT_SECONDS', 30, 5, 3_600)
+ const warmup = knob('FOOTPRINT_WARMUP_SECONDS', 20, 0, 600)
+ const bundle = process.env.E2E_BUNDLE_PATH
+ if (!bundle) throw new Error('FOOTPRINT requires E2E_BUNDLE=1: every process runs the bundle a release ships')
+ const git = (...args: string[]) => execFileSync('git', args, { cwd: CLI_ROOT, encoding: 'utf8', timeout: 5_000 }).trim()
+ const backend = await FakeBackend.start()
+ backend.addMachine(ME)
+ let daemon: IsolatedDaemon | undefined
+ let client: LocalClient | undefined
+ try {
+ const d = daemon = await IsolatedDaemon.create({ env: { BACKEND_WS_URL: backend.wsUrl, WEB_URL: backend.httpUrl, ADAPTER_COMPUTER_ID: ME.computerId } })
+ writeFileSync(join(d.root, 'auth', 'session.json'), JSON.stringify({
+ version: 1, accessToken: ME.token, autonomousEnv: 'prod', computerId: ME.computerId,
+ machineId: ME.machineId, expiresAt: Date.now() + 30 * 24 * 3600_000, updatedAt: Date.now(), signInEpoch: 'e2e',
+ }), { mode: 0o600 })
+ // Written as the person turns it on or off; never left to a build's default but in `defaults`.
+ if (scenario !== 'defaults') writeAgentSettings(d.dataDir, { agentMessages: scenario === 'on' })
+ await d.start()
+ await until('signed in to the fake backend', () => backend.nodeUp(ME.machineId) || null, 60_000, 250)
+ client = await LocalClient.connect(d, { machineId: ME.machineId })
+ const agents: Array<Record<string, any>> = []
+ for (const engine of ['claude', 'codex']) {
+ const cwd = join(d.projectsDir, `footprint-${engine}`)
+ mkdirSync(cwd, { recursive: true })
+ const created = await client.request('agent_create', { engine, cwd, bypassPermission: true }, 90_000)
+ expect(created.error, JSON.stringify(created)).toBeUndefined()
+ agents.push(await until(`the ${engine} agent to bind its conversation`, async () => {
+ const rows = (await client!.request<{ agents: Array<Record<string, any>> }>('agents_list', { includeStopped: true }, 30_000)).agents
+ const agent = rows.find((row) => row.id === created.agent.id)
+ return agent?.sessionId && agent.status === 'active' ? agent : null
+ }, 60_000, 500))
+ }
+ // One tab holds both: on, Agent Messages reads it from the account and gives each its note.
+ backend.agentMessages = { revision: 1, machines: [{ machineId: ME.machineId, name: ME.name }],
+ tabs: [{ id: 'footprint', name: 'footprint', panes: agents.map((agent) => ({ machineId: ME.machineId, agentId: agent.id })) }] }
+ if (scenario === 'on') {
+ await until('Agent Messages to give both agents their note', () => {
+ try {
+ const state = JSON.parse(readFileSync(join(d.dataDir, 'agent-messages', 'state.json'), 'utf8')) as { notes: Record<string, unknown> }
+ return Object.keys(state.notes).length === agents.length || null
+ } catch { return null }
+ }, 60_000, 500)
+ }
+ client.close()
+ client = undefined
+ await sleep(warmup * 1_000)
+
+ const master = d.pid!
+ const samples: Array<{ at: number; processes: Array<{ name: string; pid: number; rssBytes: number }> }> = []
+ const reads = backend.seen.filter((line) => line.split('?')[0] === 'GET /api/agent-messages').length
+ const started = Date.now()
+ while (Date.now() - started < seconds * 1_000) {
+ const at = Date.now()
+ const logged = new Map([...harnessdProcesses(d)].map(([name, pid]) => [pid, name] as const))
+ samples.push({ at, processes: tree(await table(), master).map((row) => ({ name: nameOf(row, logged), pid: row.pid, rssBytes: row.rssBytes })) })
+ await sleep(Math.max(0, 1_000 - (Date.now() - at)))
+ }
+ expect(d.coresStarted(), 'the core never restarted while it was measured').toBe(1)
+
+ const ours = (name: string) => name.startsWith('harnessd')
+ const names = [...new Set(samples.flatMap((sample) => sample.processes.map((p) => p.name)))]
+ const byName = names.map((name) => {
+ const seen = samples.flatMap((sample) => sample.processes.filter((p) => p.name === name))
+ const sums = samples.map((sample) => sample.processes.filter((p) => p.name === name).reduce((sum, p) => sum + p.rssBytes, 0)).filter((sum) => sum > 0)
+ return {
+ name, pids: [...new Set(seen.map((p) => p.pid))], samples: sums.length,
+ rssMeanMiB: sums.length ? sums.reduce((a, b) => a + b, 0) / sums.length / MIB : 0,
+ rssMaxMiB: sums.length ? Math.max(...sums) / MIB : 0,
+ }
+ }).sort((a, b) => b.rssMeanMiB - a.rssMeanMiB)
+ const totals = samples.map((sample) => sample.processes.filter((p) => ours(p.name)).reduce((sum, p) => sum + p.rssBytes, 0))
+ const report = {
+ schema: 1, scenario, measuredAt: new Date(started).toISOString(),
+ source: { commit: git('rev-parse', 'HEAD'), dirty: Boolean(git('status', '--porcelain')),
+ bundleSha256: createHash('sha256').update(readFileSync(bundle)).digest('hex') },
+ machine: { platform: platform(), release: release(), node: process.version, logicalCpus: cpus().length, cpu: cpus()[0]?.model, ramBytes: totalmem() },
+ workload: { signedIn: true, agents: agents.map((agent) => agent.engine), tab: 'one tab, both agents', agentMessages: SCENARIOS[scenario], warmupSeconds: warmup, seconds, sampleEveryMs: 1_000 },
+ // How often Agent Messages read the account's tabs while it was measured: every 15 s while it runs.
+ tabReadsInWindow: backend.seen.filter((line) => line.split('?')[0] === 'GET /api/agent-messages').length - reads,
+ processes: byName.filter((p) => ours(p.name)),
+ others: byName.filter((p) => !ours(p.name)),
+ total: { rssMeanMiB: totals.reduce((a, b) => a + b, 0) / totals.length / MIB, rssMaxMiB: Math.max(...totals) / MIB, samples: totals.length },
+ }
+ expect(report.processes.map((p) => p.name)).toEqual(expect.arrayContaining(['harnessd', 'harnessd-core']))
+ reports[scenario] = report
+ if (process.env.FOOTPRINT_REPORT) {
+ const file = resolve(process.env.FOOTPRINT_REPORT)
+ mkdirSync(dirname(file), { recursive: true })
+ writeFileSync(file, JSON.stringify(reports, null, 2) + '\n')
+ }
+ const width = Math.max(...report.processes.map((p) => p.name.length), 'total'.length) + 2
+ const line = (name: string, mean: number, max: number, pids: string) => `${name.padEnd(width)}${mean.toFixed(1).padStart(10)}${max.toFixed(1).padStart(10)} ${pids}`
+ // Straight to stdout: the run's reporter keeps a passing test's console to itself.
+ process.stdout.write([
+ `FOOTPRINT ${scenario} · ${report.source.commit.slice(0, 10)}${report.source.dirty ? ' (dirty)' : ''} · ${SCENARIOS[scenario]}`,
+ `${seconds} s idle after ${warmup} s · RSS MiB, mean and max · the tabs read ${report.tabReadsInWindow} times in the window`,
+ `${'process'.padEnd(width)}${'mean'.padStart(10)}${'max'.padStart(10)} pid`,
+ ...report.processes.map((p) => line(p.name, p.rssMeanMiB, p.rssMaxMiB, p.pids.join(','))),
+ line('total', report.total.rssMeanMiB, report.total.rssMaxMiB, ''),
+ ...(report.others.length ? [`not the daemon's own, left out: ${report.others.map((p) => `${p.name} (${p.samples} samples)`).join(', ')}`] : []),
+ ].join('\n') + '\n\n')
+ } finally {
+ client?.close()
+ await daemon?.close().catch(() => {})
+ await backend.close()
+ }
+ }, 900_000)
+})
diff --git a/cli/e2e/harness/noExecve.cjs b/cli/e2e/harness/noExecve.cjs
new file mode 100644
index 000000000..7dfd06596
--- /dev/null
+++ b/cli/e2e/harness/noExecve.cjs
@@ -0,0 +1,4 @@
+// A Node without `process.execve`, as before Node 22.15: a master that finds another bundle on disk cannot
+// re-execute on it, keeps its own code and starts the core on the bundle on disk (src/harnessd/reexec.ts). That is
+// how a core of one build comes to run under a master of another, which e2e/messagesSkew.e2e.ts needs.
+delete process.execve
diff --git a/cli/e2e/messagesSkew.e2e.ts b/cli/e2e/messagesSkew.e2e.ts
new file mode 100644
index 000000000..dbf4a7528
--- /dev/null
+++ b/cli/e2e/messagesSkew.e2e.ts
@@ -0,0 +1,168 @@
+/**
+ * Agent Messages between a core and a master of different builds. It left a process of its own, started on demand,
+ * for the edge host on 2026-10-12. Where it runs is the master's to say, by service (harnessd/services.ts
+ * `serviceProcessesEnv`), and a core routes it there and runs none of it itself: two at once would both type the same
+ * message into the same pane. A core is left under a master of another build when that master cannot re-execute on
+ * the bundle on disk (harnessd/reexec.ts); here, a Node without `process.execve` (harness/noExecve.cjs), the bundle
+ * swapped under a running master, and its core killed for the master to start again from the bundle on disk.
+ *
+ * - This build's core under a master from before: that master's own Agent Messages process, asked for as the core
+ * starts, carries a message typed into an idle agent, once; started again on this build, it carries the next.
+ * - A core from before under this build's master: the edge host carries it; no process of its own is started.
+ *
+ * Opt-in, since it needs a build from before the move (`SKEW_FROM=<that build>/cli.js`, its notify.mjs beside it), and
+ * runs this checkout's from the run's bundle:
+ * SKEW_FROM=<build>/cli.js E2E_BUNDLE=1 npx vitest run --config vitest.e2e.config.ts e2e/messagesSkew.e2e.ts
+ */
+import { execFileSync } from 'node:child_process'
+import { copyFileSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { dirname, join } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { afterAll, afterEach, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
+import { LocalClient, type Frame } from './harness/client.js'
+import { IsolatedDaemon, until } from './harness/daemon.js'
+import { FakeBackend, type FakeMachine } from './harness/fakeBackend.js'
+import { writeAgentSettings } from '../src/lib/agentSettings.js'
+
+const FROM = process.env.SKEW_FROM
+const ME: FakeMachine = { machineId: 'c3'.repeat(16), computerId: 'e2e-computer-0000-0000-0000000000c3', name: 'skew', token: 'e2e-token-skew' }
+const NO_EXECVE = fileURLToPath(new URL('./harness/noExecve.cjs', import.meta.url))
+
+const count = (text: string, part: string): number => text.split(part).length - 1
+const row = async (client: LocalClient, agentId: string) =>
+ ((await client.request<{ agents: Array<Record<string, any>> }>('agents_list', { includeStopped: true }, 30_000)).agents).find((agent) => agent.id === agentId)
+
+describe.skipIf(!FROM)('Agent Messages between a core and a master of different builds', () => {
+ let scratch = ''
+ let daemon: IsolatedDaemon | undefined
+ let backend: FakeBackend | undefined
+ beforeAll(() => { scratch = mkdtempSync(join(tmpdir(), 'messages-skew-')) })
+ afterAll(() => rmSync(scratch, { recursive: true, force: true }))
+ afterEach(async () => {
+ await daemon?.close(); daemon = undefined
+ await backend?.close(); backend = undefined
+ })
+
+ /** The two builds: the one from before, and this checkout's (the run's bundle). */
+ const builds = () => {
+ const now = process.env.E2E_BUNDLE_PATH
+ if (!now) throw new Error('E2E_BUNDLE=1: this checkout runs from the bundle it ships')
+ return { before: FROM!, now }
+ }
+ /** Put [bundle] (and the notify.mjs beside it) where the daemon's master runs from. */
+ const install = (dir: string, bundle: string) => {
+ copyFileSync(bundle, join(dir, 'cli.js'))
+ copyFileSync(join(dirname(bundle), 'notify.mjs'), join(dir, 'notify.mjs'))
+ }
+
+ /** A master on [first], signed in to the fake backend, on a Node that cannot re-execute. */
+ const start = async (name: string, first: string) => {
+ const dir = join(scratch, name)
+ mkdirSync(dir, { recursive: true })
+ install(dir, first)
+ writeFileSync(join(dir, 'package.json'), '{"type":"module"}\n')
+ backend = await FakeBackend.start()
+ backend.addMachine(ME)
+ const d = daemon = await IsolatedDaemon.create({ scriptPath: join(dir, 'cli.js'), env: {
+ BACKEND_WS_URL: backend.wsUrl, WEB_URL: backend.httpUrl, ADAPTER_COMPUTER_ID: ME.computerId,
+ NODE_OPTIONS: `--require=${JSON.stringify(NO_EXECVE)}`, HARNESSD_INITIAL_BACKOFF_MS: '100',
+ HARNESSD_SERVICE_INITIAL_BACKOFF_MS: '200', HARNESSD_SERVICE_MAX_BACKOFF_MS: '1000',
+ } })
+ onTestFailed(() => { console.log(`---- daemon log\n${d.log().split('\n').slice(-200).join('\n')}`) })
+ // On in Settings ▸ Agents, written as the person turns it on: never left to either build's default.
+ writeAgentSettings(d.dataDir, { agentMessages: true })
+ writeFileSync(join(d.root, 'auth', 'session.json'), JSON.stringify({
+ version: 1, accessToken: ME.token, autonomousEnv: 'prod', computerId: ME.computerId,
+ machineId: ME.machineId, expiresAt: Date.now() + 30 * 24 * 3600_000, updatedAt: Date.now(), signInEpoch: 'e2e',
+ }), { mode: 0o600 })
+ await d.start()
+ return { d, dir, relay: backend }
+ }
+
+ /** The bundle on disk becomes [next], and the core is killed: the master, which cannot re-execute, starts the next
+ * core from it. Resolves with that core's pid once Agent Messages has connected to it. */
+ const swapCore = async (d: IsolatedDaemon, dir: string, next: string) => {
+ const links = count(d.log(), '[services] messages connected')
+ install(dir, next)
+ process.kill(d.corePid()!, 'SIGKILL')
+ await until('a core on the bundle on disk', () => d.coresStarted() === 2 || null, 60_000, 100)
+ expect(d.log()).toContain('this Node cannot re-execute a process: the master keeps its code')
+ const core = d.corePid()!
+ // Started from the bundle on disk, never the master's own lean copy: the other build.
+ expect(execFileSync('ps', ['-o', 'command=', '-p', String(core)], { encoding: 'utf8' })).toContain(join(dir, 'cli.js'))
+ await until('Agent Messages to reach the new core', () => count(d.log(), '[services] messages connected') > links || null, 60_000, 200)
+ return core
+ }
+
+ /** Two idle agents in one tab, and a message from one to the other typed into it, once. */
+ const message = async (d: IsolatedDaemon, relay: FakeBackend, client: LocalClient, agents: Array<Record<string, any>>, text: string) => {
+ if (!agents.length) {
+ for (const folder of ['lead', 'api']) {
+ const cwd = join(d.projectsDir, folder)
+ mkdirSync(cwd, { recursive: true })
+ const created = await client.request('agent_create', { engine: 'claude', cwd, bypassPermission: true }, 90_000)
+ expect(created.error, JSON.stringify(created)).toBeUndefined()
+ agents.push(await 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))
+ }
+ relay.agentMessages = { revision: 1, machines: [{ machineId: ME.machineId, name: ME.name }],
+ tabs: [{ id: 'app', name: 'app', panes: agents.map((agent) => ({ machineId: ME.machineId, agentId: agent.id })) }] }
+ }
+ const [lead, api] = agents
+ const roster = await until('the roster', async () => {
+ const answer = await client.request('agent_messages', { action: 'send', pane: lead.tmuxPane }, 40_000)
+ return String(answer.roster ?? '').includes('Teammates:') ? answer : null
+ }, 60_000, 1_000)
+ const apiName = String(roster.roster).split('\n')[1].trim().split(/\s{2,}/)[0]
+ const sent = await client.request('agent_messages', { action: 'send', pane: lead.tmuxPane, to: [apiName], text }, 40_000)
+ expect(sent.error, JSON.stringify(sent)).toBeUndefined()
+ const status = await until('the message to be typed into the idle agent', async () => {
+ const history = await client.request<{ messages?: Array<{ id: string; statuses: Array<Record<string, unknown>> }> }>('agent_messages', { action: 'history' }, 30_000)
+ const s = history.messages?.find((m) => m.id === sent.id)?.statuses[0]
+ return s?.state === 'delivered' ? s : null
+ }, 90_000, 500)
+ expect(status).toMatchObject({ via: 'prompt' })
+ // Once: a second service would have typed it again.
+ await new Promise((settle) => setTimeout(settle, 5_000))
+ const turns = client.frames.filter((frame: Frame) => frame.type === 'turn_started' && frame.agentId === api.id
+ && String(frame.payload?.userMessage ?? '').includes(String(sent.id)))
+ expect(turns).toHaveLength(1)
+ }
+
+ it('this build\'s core under a master from before: that master\'s own process carries it, once, and on this build after a restart', async () => {
+ const { before, now } = builds()
+ const { d, dir, relay } = await start('new-core', before)
+ // The master from before runs it in a process of its own, which its core asks for while it is on.
+ await until('its own process to connect', () => count(d.log(), '[services] messages connected') >= 1 || null, 60_000, 200)
+ expect(count(d.log(), '[harnessd] service messages started')).toBe(1)
+ await swapCore(d, dir, now)
+ const client = await LocalClient.connect(d, { machineId: ME.machineId })
+ const agents: Array<Record<string, any>> = []
+ await message(d, relay, client, agents, 'Which port does the daemon serve?')
+ // Its process started again: on the bundle on disk, this build's, still alone.
+ const pid = Number([...d.log().matchAll(/\[harnessd\] service messages started \(pid (\d+)\)/g)].at(-1)![1])
+ const links = count(d.log(), '[services] messages connected')
+ process.kill(pid, 'SIGKILL')
+ await until('it to start again and connect', () => count(d.log(), '[services] messages connected') > links || null, 60_000, 200)
+ expect(count(d.log(), '[harnessd] service messages started')).toBe(2)
+ await message(d, relay, client, agents, 'And the hook port?')
+ expect(d.coresStarted()).toBe(2)
+ client.close()
+ }, 600_000)
+
+ it('a core from before under this build\'s master: the edge host carries it, once, and no process of its own starts', async () => {
+ const { before, now } = builds()
+ const { d, dir, relay } = await start('old-core', now)
+ await until('the edge host to connect it', () => count(d.log(), '[services] messages connected') >= 1 || null, 60_000, 200)
+ await swapCore(d, dir, before)
+ const client = await LocalClient.connect(d, { machineId: ME.machineId })
+ await message(d, relay, client, [], 'Which port does the daemon serve?')
+ // The core from before asks for it as an experiment, at start: this master runs it in the edge host already.
+ expect(count(d.log(), '[harnessd] service messages started')).toBe(0)
+ expect(d.coresStarted()).toBe(2)
+ client.close()
+ }, 600_000)
+})
diff --git a/cli/src/core/AGENTS.md b/cli/src/core/AGENTS.md
index 131662d2c..4244f7983 100644
--- a/cli/src/core/AGENTS.md
+++ b/cli/src/core/AGENTS.md
@@ -43,7 +43,7 @@ questions. Everything else is a service ([../services/AGENTS.md](../services/AGE
worker through a revocable grant (`engines/questionControls.ts`).
`deviceInput.ts`: the pane writer lock every write takes, and a device's queued turns behind it.
`cardText.ts`: an engine's error, rewritten for a device's card.
-- `deliveries.ts`: delivered turns, the Wi-Fi device's, a team's and the orchestrator's: text written into an
+- `deliveries.ts`: delivered turns, the Wi-Fi device's, Agent Messages' and the orchestrator's: text written into an
agent under a delivery id of its maker's, and what became of it, told back to that maker in its process.
- `updateHandoff.ts`: the core handing over to a build the updater staged (exit 75, when the master asks),
and a core with no master handing itself to one. `updaterBeside.ts`: the updater started beside a core whose
@@ -58,7 +58,10 @@ questions. Everything else is a service ([../services/AGENTS.md](../services/AGE
in this process. `serviceLinks.ts`: services in their own processes. `viewersLink.ts`: what the core
keeps of the viewers when they run in theirs. `viewerStreams.ts`: a client's viewer stream and rendered
frames, handed to the viewers, refused at once while they are down, and held while they first start. `workspacesLink.ts`: what the core tells workspaces in
- theirs. `messagesLink.ts`: which of Agent Messages' deliveries may be written, as its process last said.
+ theirs. `messagesLink.ts`: Agent Messages out of this process (the edge host): which of its deliveries may be
+ written, as it last said, the few things it may ask (the agents, this daemon and its sign-in, the account's tabs,
+ its log's notice for the windows), the desk's changes and Settings ▸ Agents' writes, and the ask for it as the core
+ starts.
`monitorLink.ts`: the monitor's port, asked of its process. `recapsLink.ts`: the recaps in their process,
told each turn's lifecycle and never waited on, and read back from what they last said
(`turns/recaps.ts` is the core's whole side of them). `storeLink.ts`: what the Store in its
@@ -67,7 +70,7 @@ questions. Everything else is a service ([../services/AGENTS.md](../services/AGE
keystrokes, and how it asks it the rest. `agentQueries.ts`: what a service in its own process may ask of the agents;
`accountQueries.ts`: of the account (a token, and the fleet's lane's sealing), so it holds no credential.
`experimentQueries.ts`: what an experiment acts on the core through; `experiments.ts`: which are on as the
- core starts; `orchestratorLink.ts`: what the core keeps of the orchestrator in its own process;
+ core starts, by their saved state; `orchestratorLink.ts`: what the core keeps of the orchestrator in its own process;
`sharingLink.ts`: Share's observers' frames to its process; `terminalWatch.ts`: a read-only view of the
agents' terminals, which Share shows its observers. `conversationQueries.ts`: the conversation facts the
change-agent handoff in the edge host asks for, one at a time.
diff --git a/cli/src/core/api.ts b/cli/src/core/api.ts
index 1b61e9fd2..133b0be0b 100644
--- a/cli/src/core/api.ts
+++ b/cli/src/core/api.ts
@@ -17,7 +17,6 @@ import type { RecentTurn } from '../cable/cableHost.js'
import type { ReviewedAnswer } from '../cable/questionInbox.js'
import type { AgentEngine } from '../engines/types.js'
import type { AppSwarms } from '../cable/cableSession.js'
-import type { AgentSettings } from '../lib/agentSettings.js'
import type { UnreadNotification } from '../lib/notificationRead.js'
import type { AutonomousDeviceAgent, AutonomousDeviceDelivery, AutonomousDeviceReceipt } from '../lib/autonomous-device/service.js'
import type { StoreAgent } from '../lib/autonomous-device/store.js'
@@ -251,7 +250,7 @@ export interface CoreApi {
* until the first one lands. */
machineName(): string | null
/** A read or write of the account's backend, signed in by the core (`proxyBackend`): an experiment's
- * account-wide settings (Agent Messages' tabs). A failure is an answer: 502, 504, 401. */
+ * account-wide settings, and Agent Messages' tabs. A failure is an answer: 502, 504, 401. */
backend(method: string, path: string, body?: unknown): Promise<{ status: number; body: Record<string, unknown> }>
/** Hear the account's changes the backend announces (`desk_changed`, …). Returns how to stop hearing. */
onNotice(listener: (notice: BackendNotice) => void): () => void
@@ -568,15 +567,28 @@ export const SHARE_REQUESTS = [
] as const
/** Agent Messages (services/messages.ts, messages/service.ts): from `harness send` in an agent's pane, from the
- * owner's other machines and from the windows. */
+ * owner's other machines and from the windows. A service in the edge host since 2026-10-12, no longer an
+ * experiment: its own process cost every computer it was on 62 MiB at idle for a few MiB of messaging. */
export const MESSAGES_REQUESTS = ['agent_messages'] as const
+/**
+ * What Agent Messages in a process of its own may do through the core, and nothing more (core/messagesLink.ts
+ * answers it, and checks each): the agents as the apps are shown them (`shown`) and how an agent's shell reaches
+ * this daemon (`daemon`), which its roster and its `harness send` read; the account's tabs, the one backend read it
+ * makes (`backend`, GET of `MESSAGES_BACKEND_PATH`); its log's change notice for the windows (`windows`, only
+ * `MESSAGES_WINDOW_FRAME`); and which of its typed deliveries may be written (`writable`). It writes turns into
+ * agents (core/deliveries.ts, `TURN_DELIVERERS`) and hears the account's `desk_changed`. The same questions the
+ * experiment asked, so a core of either version answers the process of the other (harnessd/services.ts).
+ */
+export const MESSAGES_QUERIES = ['writable', 'shown', 'daemon', 'backend', 'windows'] as const
+export const MESSAGES_BACKEND_PATH = '/api/agent-messages'
+export const MESSAGES_WINDOW_FRAME = 'messages_changed'
+
/**
* The experiments: services that cost nothing until they are on (docs/design/2026-10-06-core-boundary-next.md,
* "Experimental features: move only"). Each runs in a process of its own that the master starts only once the
* core asks for it (harnessd/services.ts `onDemand`): when one of its `requests` arrives, or at start when its
- * saved `state` is in the data folder (paths under it; `dir/*.ext` for a file of that kind in that folder), or
- * while its Settings ▸ Agents `setting` is on (lib/agentSettings.ts).
+ * saved `state` is in the data folder (paths under it; `dir/*.ext` for a file of that kind in that folder).
* Off, it has no process and none of its code is loaded anywhere. Each may act on the core through the hooks
* an experiment has (core/experimentQueries.ts, core/deliveries.ts), and no other process may.
*
@@ -585,11 +597,8 @@ export const MESSAGES_REQUESTS = ['agent_messages'] as const
* entry here; and its start for the core's own process (services/inline.ts `EXPERIMENT_STARTS`). Removing
* one is deleting those.
*/
-export const EXPERIMENTS: Readonly<Record<string, { requests: readonly string[]; state: readonly string[]; setting?: keyof AgentSettings }>> = {
+export const EXPERIMENTS: Readonly<Record<string, { requests: readonly string[]; state: readonly string[] }>> = {
orchestrator: { requests: ORCHESTRATOR_REQUESTS, state: ['orchestrator/*.json'] },
- // Agent Messages. Its history and waiting deliveries: a message was sent from here or delivered to an agent here.
- // On by default (Settings ▸ Agents), so it starts with the core: its agents hear of `harness send` from it.
- messages: { requests: MESSAGES_REQUESTS, state: ['agent-messages'], setting: 'agentMessages' },
// Its invitations and links: a harness was shared from here.
sharing: { requests: SHARE_REQUESTS, state: ['harness-shares.json', 'harness-collaboration.json'] },
// Request-only, on from its first request until the daemon stops: another machine's Memories pane asks, and
@@ -599,6 +608,11 @@ export const EXPERIMENTS: Readonly<Record<string, { requests: readonly string[];
router: { requests: ROUTER_REQUESTS, state: [] },
}
+/** The services that may write turns into agents from a process of their own (core/deliveries.ts): the experiments,
+ * and Agent Messages, which left them for the edge host and still types a message into an idle agent. No other
+ * process may: writing into a pane is no other service's to ask. */
+export const TURN_DELIVERERS: readonly string[] = [...Object.keys(EXPERIMENTS), 'messages']
+
/** The core's calls into Share: an observer's frame as the relay handed it over, the relay gone (every observer
* with it), and stopping it. */
export interface SharingPort {
@@ -860,14 +874,18 @@ export interface WorkspacesPort {
/** What the core gets when workspaces fails: branches keep their names and nothing is swept. */
export const WORKSPACES_FALLBACKS: PortFallbacks<WorkspacesPort> = { nameBranches: undefined, sweepUnused: undefined }
-/** The core's call into Agent Messages: whether one of its typed deliveries (a `team:` id) may still be written,
- * asked in line as it is written (core/input.ts). */
+/** The core's calls into Agent Messages: whether one of its typed deliveries (a `team:` id) may still be written,
+ * asked in line as it is written (core/input.ts); and that Settings ▸ Agents was written through the daemon, which
+ * wakes it when its switch is turned on: off, it runs no timer that would read the file again, and a file never
+ * written has nothing to watch (messages/settingWatch.ts). */
export interface MessagesPort {
canWrite(deliveryId: string): boolean
+ settingsChanged(): void
}
-/** What the core gets when Agent Messages fails: none of its deliveries may be written (each waits, unwritten). */
-export const MESSAGES_FALLBACKS: PortFallbacks<MessagesPort> = { canWrite: false }
+/** What the core gets when Agent Messages fails: none of its deliveries may be written (each waits, unwritten), and
+ * a settings write tells it nothing. */
+export const MESSAGES_FALLBACKS: PortFallbacks<MessagesPort> = { canWrite: false, settingsChanged: undefined }
/** What a delivered turn answers: delivered, or refused with the machine's name and a reason a person can read. */
export type SendResult = { ok: true } | { ok: false; machine: string; reason: string }
diff --git a/cli/src/core/experimentQueries.ts b/cli/src/core/experimentQueries.ts
index 281976256..1f4a42324 100644
--- a/cli/src/core/experimentQueries.ts
+++ b/cli/src/core/experimentQueries.ts
@@ -10,13 +10,14 @@
* - `windows`: a change notice for every window on this computer (`orchestrator_changed`);
* - `daemon`: how an agent's shell reaches this daemon, for the prompts the experiment writes;
* - `backend`: a read or write of the account's backend under `/api/`, signed in by the core, which holds the
- * sign-in (Agent Messages' tabs);
+ * sign-in (Share's links);
* - `observer_key`: this machine's public key, or its signature on a welcome to one observer of one share, by
* the gateway, which holds the identity (Share's owner);
* - `observer_send`: a frame Share sealed for one of its observers, to the relay through the gateway.
* The core answers them only for the experiments (core/api.ts `EXPERIMENTS`): creating an agent or
* telling the windows something is no other process's to ask. The process's side is
- * services/processCoreApi.ts.
+ * services/processCoreApi.ts. Agent Messages, an experiment until 2026-10-12, asks a few of the same and is
+ * answered by its own link, for what it uses alone (core/messagesLink.ts).
*/
import type { BackendSocket } from '../backendSocket.js'
import type { AgentCreateRequest, CoreApi } from './api.js'
@@ -28,20 +29,31 @@ const QUERIES: ReadonlySet<string> = new Set(['shown', 'create', 'stop_turn', 'w
const METHODS: ReadonlySet<string> = new Set(['GET', 'POST', 'PUT', 'PATCH', 'DELETE'])
const text = (value: unknown): string => (typeof value === 'string' ? value : '')
+/** The live agents as the apps are shown them (`shown`): each with its name, whether its terminal is there and
+ * what its frame says about its harness. */
+export function shownAgents(core: Pick<CoreApi, 'agents'>): Payload {
+ return {
+ agents: core.agents.live().map((session) => ({
+ ...session,
+ displayName: core.agents.displayName(session),
+ terminalAvailable: core.agents.terminalAvailable(session.agentId),
+ dshContext: core.agents.dsh(session),
+ })),
+ }
+}
+
+/** How an agent's shell reaches this daemon (`daemon`). */
+export function daemonAddress(core: Pick<CoreApi, 'daemon'>): Payload {
+ return { command: core.daemon.command, port: core.daemon.port, machineId: core.daemon.machineId(), autonomousEnv: core.daemon.autonomousEnv }
+}
+
/** The answer to an experiment's query, or null when it is not one of these. */
export async function answerExperimentQuery(core: Core, experiments: ReadonlySet<string>, service: string, query: string, payload: Payload): Promise<Payload | null> {
if (!QUERIES.has(query)) return null
if (!experiments.has(service)) return { error: 'NOT_AN_EXPERIMENT' }
switch (query) {
case 'shown':
- return {
- agents: core.agents.live().map((session) => ({
- ...session,
- displayName: core.agents.displayName(session),
- terminalAvailable: core.agents.terminalAvailable(session.agentId),
- dshContext: core.agents.dsh(session),
- })),
- }
+ return shownAgents(core)
case 'create': {
if (!text(payload.engine) || !text(payload.cwd) || typeof payload.prompt !== 'string' || typeof payload.name !== 'string') return { ok: false, error: 'INVALID_REQUEST' }
const request: AgentCreateRequest = {
@@ -82,7 +94,7 @@ export async function answerExperimentQuery(core: Core, experiments: ReadonlySet
return { sent: core.clients.observer(connId, type, payload.payload as Payload) }
}
default:
- return { command: core.daemon.command, port: core.daemon.port, machineId: core.daemon.machineId(), autonomousEnv: core.daemon.autonomousEnv }
+ return daemonAddress(core)
}
}
diff --git a/cli/src/core/experiments.spec.ts b/cli/src/core/experiments.spec.ts
index af8ef57bc..5a33f7893 100644
--- a/cli/src/core/experiments.spec.ts
+++ b/cli/src/core/experiments.spec.ts
@@ -4,15 +4,12 @@ import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { writeAgentSettings } from '../lib/agentSettings.js'
import { EXPERIMENTS } from './api.js'
-import { createAccountNotices, createExperimentHooks, stateIsThere, wakeExperiments, writeAgentSettingsAndWake } from './experiments.js'
+import { createAccountNotices, createExperimentHooks, stateIsThere, wakeExperiments } from './experiments.js'
describe('the experiments on as the core starts', () => {
let dataDir: string
beforeEach(() => { dataDir = mkdtempSync(join(tmpdir(), 'experiments-')) })
afterEach(() => rmSync(dataDir, { recursive: true, force: true }))
- /** Agent Messages as core/api.ts declares it: on by its Settings ▸ Agents switch, or by its saved state. */
- const experiments = { messages: { state: ['agent-messages'], setting: 'agentMessages' as const }, orchestrator: { state: ['orchestrator/*.json'] } }
-
it('finds saved state by path, or by a file of its kind in its folder', () => {
expect(stateIsThere(dataDir, ['agent-messages'])).toBe(false)
expect(stateIsThere(dataDir, ['orchestrator/*.json'])).toBe(false)
@@ -43,28 +40,17 @@ describe('the experiments on as the core starts', () => {
expect(want.mock.calls).toEqual([['orchestrator']])
})
- it('asks for an experiment whose Settings ▸ Agents switch is on, with no saved state, and not once it is off', () => {
- // Agent Messages is on by default: its agents hear of `harness send` only from its process, which nothing else
- // starts on a machine where no one has sent yet (owner, 2026-10-12).
- const wake = (outOfProcess = new Set(['messages', 'orchestrator'])) => {
+ it('asks for none on a fresh data folder, whatever Settings ▸ Agents says: no switch starts an experiment', () => {
+ // Agent Messages was the one a switch started, and left the experiments for the edge host (2026-10-12): its
+ // agents' note no longer needs a process of its own started for it.
+ expect(Object.keys(EXPERIMENTS)).not.toContain('messages')
+ const outOfProcess = new Set([...Object.keys(EXPERIMENTS), 'messages'])
+ for (const agentMessages of [true, false]) {
+ writeAgentSettings(dataDir, { agentMessages })
const want = vi.fn()
- return { woken: wakeExperiments({ dataDir, experiments, outOfProcess, want }), want }
+ expect(wakeExperiments({ dataDir, experiments: EXPERIMENTS, outOfProcess, want })).toEqual([])
+ expect(want).not.toHaveBeenCalled()
}
- const first = wake()
- expect(first.woken).toEqual(['messages'])
- expect(first.want.mock.calls).toEqual([['messages']])
- // As core/api.ts declares the experiments: on a fresh data folder, Agent Messages alone.
- const outOfProcess = new Set(Object.keys(EXPERIMENTS))
- expect(wakeExperiments({ dataDir, experiments: EXPERIMENTS, outOfProcess, want: vi.fn() })).toEqual(['messages'])
- // In the core's process it is started there, not asked for.
- expect(wake(new Set()).woken).toEqual([])
- writeAgentSettings(dataDir, { agentMessages: false })
- const off = wake()
- expect(off.woken).toEqual([])
- expect(off.want).not.toHaveBeenCalled()
- // Off, its saved state still wakes it: what waits there is held, then failed, rather than left behind.
- mkdirSync(join(dataDir, 'agent-messages'))
- expect(wake().woken).toEqual(['messages'])
})
it('hands the account\'s notices to each listener here, guarded, and to the experiments\' processes', () => {
@@ -100,33 +86,16 @@ describe('the experiments on as the core starts', () => {
const order: string[] = []
const notify = vi.fn(() => true)
const hooks = createExperimentHooks({
- want: (service) => order.push(`want ${service}`), notify, outOfProcess: new Set(['messages']), experiments: ['orchestrator', 'messages'],
+ want: (service) => order.push(`want ${service}`), notify, outOfProcess: new Set(['sharing']), experiments: ['orchestrator', 'sharing'],
})
- hooks.want('messages')
+ hooks.want('sharing')
hooks.want('orchestrator')
- expect(order).toEqual(['want messages', 'want orchestrator'])
+ expect(order).toEqual(['want sharing', 'want orchestrator'])
const heard = vi.fn()
hooks.onNotice(heard)
hooks.notice({ type: 'desk_changed', revision: 5 })
expect(heard).toHaveBeenCalledWith({ type: 'desk_changed', revision: 5 })
- expect(notify.mock.calls).toEqual([['messages', { type: 'service_event', payload: { kind: 'notice', notice: { type: 'desk_changed', revision: 5 } } }]])
+ expect(notify.mock.calls).toEqual([['sharing', { type: 'service_event', payload: { kind: 'notice', notice: { type: 'desk_changed', revision: 5 } } }]])
createExperimentHooks({ want: vi.fn(), notify, outOfProcess: new Set(), experiments: [] }).want('x')
})
-
- it('asks for an experiment once a Settings ▸ Agents write leaves its switch on, and not when off or refused', async () => {
- // On one machine nothing else starts it: no agent heard of `harness send` (a fresh Mac, 2026-10-12).
- const want = vi.fn()
- const settings = (body: Record<string, unknown>, status = 200) => async () => ({ status, body })
- const on = { agentsStartAgents: true, pullRequestLine: true, agentMessages: true }
- const answer = await writeAgentSettingsAndWake(settings(on), experiments, want)
- expect(answer).toEqual({ status: 200, body: on })
- expect(want.mock.calls).toEqual([['messages']])
- // Another switch written, this one left on: asked for again, which changes nothing for one already running.
- await writeAgentSettingsAndWake(settings({ ...on, pullRequestLine: false }), experiments, want)
- expect(want).toHaveBeenCalledTimes(2)
- await writeAgentSettingsAndWake(settings({ ...on, agentMessages: false }), experiments, want)
- await writeAgentSettingsAndWake(settings({ error: { code: 'BAD_REQUEST' } }, 400), experiments, want)
- await writeAgentSettingsAndWake(settings(on, 199), experiments, want)
- expect(want).toHaveBeenCalledTimes(2)
- })
})
diff --git a/cli/src/core/experiments.ts b/cli/src/core/experiments.ts
index 9091069ce..86058e1a2 100644
--- a/cli/src/core/experiments.ts
+++ b/cli/src/core/experiments.ts
@@ -1,16 +1,17 @@
/**
* Which experiments are on as the core starts (core/api.ts `EXPERIMENTS`): one whose saved state is in the
* data folder is asked for at once, so that what it does on its own (a saved project's queued work) goes on
- * after a restart, as it did when it ran in the core's process; so is one whose Settings ▸ Agents switch is on
- * (Agent Messages, on by default). One with neither waits for its first request: off, it has no process. Read
- * once, at start, and bounded: a name or a folder listing, and the one small settings file.
+ * after a restart, as it did when it ran in the core's process. One without waits for its first request: off,
+ * it has no process. Read once, at start, and bounded: a name or a folder listing.
+ *
+ * Agent Messages was the one experiment a Settings ▸ Agents switch started, and it is no longer one: it runs in the
+ * edge host and sleeps while it is off (messages/service.ts, 2026-10-12).
*/
import { readdirSync, existsSync } from 'node:fs'
import { join } from 'node:path'
-import { readAgentSettings, type AgentSettings } from '../lib/agentSettings.js'
import type { BackendNotice } from './api.js'
-type Experiments = Readonly<Record<string, { state: readonly string[]; setting?: keyof AgentSettings }>>
+type Experiments = Readonly<Record<string, { state: readonly string[] }>>
/** Whether any of `state` is in `dataDir`: a path under it, or `dir/*.ext` for a file of that kind in that folder. */
export function stateIsThere(dataDir: string, state: readonly string[]): boolean {
@@ -26,43 +27,24 @@ export function stateIsThere(dataDir: string, state: readonly string[]): boolean
})
}
-/** Ask for each experiment that runs in its own process and has saved state here, or whose Settings ▸ Agents switch
- * is on (Agent Messages, on by default: its agents hear of `harness send` only from its process). */
+/** Ask for each experiment that runs in its own process and has saved state here. */
export function wakeExperiments(options: {
dataDir: string
experiments: Experiments
outOfProcess: ReadonlySet<string>
want: (service: string) => void
}): string[] {
- const settings = readAgentSettings(options.dataDir)
const woken = Object.entries(options.experiments)
- .filter(([name, experiment]) => options.outOfProcess.has(name)
- && (stateIsThere(options.dataDir, experiment.state) || (experiment.setting !== undefined && settings[experiment.setting])))
+ .filter(([name, experiment]) => options.outOfProcess.has(name) && stateIsThere(options.dataDir, experiment.state))
.map(([name]) => name)
for (const name of woken) options.want(name)
return woken
}
/**
- * A Settings ▸ Agents change, written by the core. An experiment whose switch it leaves on is asked for at once, so it
- * acts now (Agent Messages' agents get its note) rather than at its first request or the next start: on one machine
- * neither came, and no agent heard of `harness send` (a fresh Mac, 2026-10-12). Asking again for one already running
- * changes nothing. A tab's own switch, which older windows still write, decides nothing and wakes nothing.
- */
-export async function writeAgentSettingsAndWake<T extends { status: number; body: Record<string, unknown> }>(
- write: () => Promise<T>, experiments: Experiments, want: (service: string) => void,
-): Promise<T> {
- const result = await write()
- if (result.status >= 200 && result.status < 300) {
- for (const [name, experiment] of Object.entries(experiments)) if (experiment.setting && result.body[experiment.setting] === true) want(name)
- }
- return result
-}
-
-/**
- * The account's notices the backend announces (`desk_changed`, …), for the experiments that hear them: each
- * listener in this process (`core.account.onNotice`), guarded, and each experiment's process (`tell`). Agent
- * Messages reads its tabs again at `desk_changed`.
+ * The account's notices the backend announces (`desk_changed`, …), for the services that hear them: each
+ * listener in this process (`core.account.onNotice`, Agent Messages' among them when it runs here, which reads its
+ * tabs again at `desk_changed`), guarded, and each experiment's process (`tell`).
*/
export function createAccountNotices(tell: (notice: BackendNotice) => void, log: (line: string) => void = (line) => console.warn(line)) {
const listeners = new Set<(notice: BackendNotice) => void>()
diff --git a/cli/src/core/main.ts b/cli/src/core/main.ts
index 1119a4ae9..e266add5d 100644
--- a/cli/src/core/main.ts
+++ b/cli/src/core/main.ts
@@ -162,7 +162,7 @@ import { createEngineHooks, installEngineHooks, installOpencodePluginBeforeSpawn
import { createCursorDiscovery } from './engines/cursorDiscovery.js'
import { createCursorTaskHooks, loadPendingCursorTasks } from './engines/cursorTasks.js'
import { databaseHistory, hermesDb } from './transcripts/databaseHistory.js'
-import { CONNECTORS_REQUESTS, MEMORY_REQUESTS, ROUTER_REQUESTS, createCoreApi, DEVICES_FALLBACKS, DEVICES_REQUESTS, emptyPorts, HANDOFF_REQUESTS, EXPERIMENTS, LONG_ANSWERS, MODELS_FALLBACKS, MODELS_OFF, MODELS_REQUESTS, MONITOR_FALLBACKS, MONITOR_OFF, MONITOR_REQUESTS, ORCHESTRATOR_FALLBACKS, ORCHESTRATOR_REQUESTS, SHARE_REQUESTS, SHARING_FALLBACKS, PROJECTS_REQUESTS, SEARCH_FALLBACKS, SEARCH_REQUESTS, STORE_FALLBACKS, STORE_OFF, STORE_REQUESTS, MESSAGES_FALLBACKS, MESSAGES_REQUESTS, USAGE_FALLBACKS, USAGE_REQUESTS, VIEWERS_FALLBACKS, WIFI_FALLBACKS, WINDOW_NAMES_REQUESTS, WORKSPACES_FALLBACKS, type GatewayAccount, type GatewayOps, type GatewayStatus, type RouteAnswer, type WindowFocus } from './api.js'
+import { CONNECTORS_REQUESTS, MEMORY_REQUESTS, ROUTER_REQUESTS, createCoreApi, DEVICES_FALLBACKS, DEVICES_REQUESTS, emptyPorts, HANDOFF_REQUESTS, EXPERIMENTS, LONG_ANSWERS, MODELS_FALLBACKS, MODELS_OFF, MODELS_REQUESTS, MONITOR_FALLBACKS, MONITOR_OFF, MONITOR_REQUESTS, ORCHESTRATOR_FALLBACKS, ORCHESTRATOR_REQUESTS, SHARE_REQUESTS, SHARING_FALLBACKS, PROJECTS_REQUESTS, SEARCH_FALLBACKS, SEARCH_REQUESTS, STORE_FALLBACKS, STORE_OFF, STORE_REQUESTS, MESSAGES_FALLBACKS, MESSAGES_REQUESTS, TURN_DELIVERERS, USAGE_FALLBACKS, USAGE_REQUESTS, VIEWERS_FALLBACKS, WIFI_FALLBACKS, WINDOW_NAMES_REQUESTS, WORKSPACES_FALLBACKS, type GatewayAccount, type GatewayOps, type GatewayStatus, type RouteAnswer, type WindowFocus } from './api.js'
import { createServiceHost, testFaults } from './serviceHost.js'
import { startStalls } from './stall.js'
import { createServiceLinks, type ServiceLinks } from './serviceLinks.js'
@@ -179,13 +179,13 @@ import { answerAgentQuery } from './agentQueries.js'
import { createDeliveries } from './deliveries.js'
import { createTerminalWatch } from './terminalWatch.js'
import { createSharingLink } from './sharingLink.js'
-import { createExperimentHooks, wakeExperiments, writeAgentSettingsAndWake } from './experiments.js'
+import { createExperimentHooks, wakeExperiments } from './experiments.js'
import { answerExperimentQuery, createForExperiment } from './experimentQueries.js'
import { answerConnectorsQuery } from './connectorsQueries.js'
import { createOrchestratorLink } from './orchestratorLink.js'
import { daemonCommand } from '../lib/daemonCommand.js'
import { KNOWN_SERVICES, masterRunsEngineRuntime, masterRunsLiveEngines, servicesTheMasterRuns } from '../harnessd/services.js'
-import { createMessagesLink } from './messagesLink.js'
+import { askForMessages, createMessagesLink, writeSettingsAndTell } from './messagesLink.js'
import { createDevicesLink } from './devicesLink.js'
import { CORE_EXIT_STOP, CORE_EXIT_UPDATE, PROBE_COMMAND } from '../harnessd/protocol.js'
import { localSocketPath, refuseServedDataFolder, type LocalSocketServer } from '../lib/localSocket.js'
@@ -717,8 +717,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {
submit: (agentId, text, deliveryId) => backendRef?.onMessage?.(agentId, text, deliveryId),
cancel: (deliveryId) => backendRef?.onCancelOrchestratorMessage?.(deliveryId) ?? false,
tell: (service, event) => { serviceLinksRef?.notify(service, { type: 'service_event', payload: { kind: 'delivery', event } }, { untilDelivered: true }) },
- // The experiments: the orchestrator's turns, and those of the experiments after it.
- deliverers: new Set(Object.keys(EXPERIMENTS)),
+ // The experiments' turns (the orchestrator's first), and Agent Messages' typed messages (core/api.ts).
+ deliverers: new Set(TURN_DELIVERERS),
})
const ports = emptyPorts()
// The Wi-Fi device's service runs with the dials (services/wifi.ts); what the core reads in line of it
@@ -760,7 +760,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
gridModelsChanged: () => { void backendRef?.pushGridModels() },
privateGridName: async () => backendRef?.gridName() ?? null,
machineName: () => backendRef?.machineName() ?? null,
- // An experiment's account-wide settings (Agent Messages' tabs), signed in by this core.
+ // An experiment's account-wide settings, and Agent Messages' tabs, signed in by this core.
backend: (method, path, body) => proxyBackend(method, path, body),
onNotice: (listener) => experimentHooks.onNotice(listener),
dshInstallStatus: (status) => backendRef?.send({ type: 'dsh_install_status', payload: status }),
@@ -1251,7 +1251,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// The requests each service that can run in its own process answers, as core/api.ts declares them.
const requestsOf: Record<string, readonly string[]> = {
search: SEARCH_REQUESTS, store: STORE_REQUESTS, usage: USAGE_REQUESTS, monitor: MONITOR_REQUESTS, projects: PROJECTS_REQUESTS, models: MODELS_REQUESTS, handoff: HANDOFF_REQUESTS, connectors: CONNECTORS_REQUESTS,
- devices: DEVICES_REQUESTS, windowNames: WINDOW_NAMES_REQUESTS, shell: SHELL_REQUESTS,
+ devices: DEVICES_REQUESTS, windowNames: WINDOW_NAMES_REQUESTS, shell: SHELL_REQUESTS, messages: MESSAGES_REQUESTS,
...Object.fromEntries(Object.entries(EXPERIMENTS).map(([name, experiment]) => [name, experiment.requests])),
}
// The experiments (core/api.ts `EXPERIMENTS`): each may act on the core through the hooks an experiment has.
@@ -1265,13 +1265,17 @@ async function runForeground(session: AuthSession | null): Promise<void> {
{ wake: (why) => viewersWake.ask('viewers', why) })
// How the core tells workspaces in their own process what to do, and answers them (core/workspacesLink.ts).
const workspacesLink = createWorkspacesLink(coreApi, (frame) => serviceLinks.notify('workspaces', frame), forgetAgentProject)
- // Agent Messages in its own process: which of its deliveries may be written, as it last said (core/messagesLink.ts).
- const messagesLink = createMessagesLink()
+ // Agent Messages in its own process: which of its deliveries may be written, as it last said, and what it may ask
+ // and hear of the core (core/messagesLink.ts).
+ const messagesLink = createMessagesLink({ core: coreApi, notify: (frame) => serviceLinks.notify('messages', frame) })
// An experiment asked for, and the account's notices for those that hear them (core/experiments.ts).
const experimentHooks = createExperimentHooks({ want: (service) => coreLink.want(service), notify: (service, frame) => serviceLinks.notify(service, frame),
outOfProcess, experiments })
backend.onAccountNotice = (notice) => {
experimentHooks.notice(notice)
+ // Agent Messages reads its tabs again at `desk_changed`: told here in its own process, heard through
+ // `account.onNotice` in this one.
+ messagesLink.notice(notice)
// The connectors service merges the account's sealed connections again (services/connectors.ts); in
// the core's process it hears this through `account.onNotice` like any listener.
// A device key added or confirmed (`device_keys_changed`) may be a machine to seal them for as well.
@@ -1314,12 +1318,15 @@ async function runForeground(session: AuthSession | null): Promise<void> {
owned: Object.fromEntries([...outOfProcess].map((name) => [name, requestsOf[name] ?? []])),
waits: LONG_ANSWERS,
// An experiment's process runs once on, the devices' once there is one, models', the gateway's and the viewers'
- // once needed: a request asks. Shell is in the always-running edge host, but its first request can beat that
- // host's connection. Hold it through the same bounded startup gate; after any disconnect, fail promptly as before.
- onDemand: new Set([...experiments, ...DEVICES_ON_DEMAND, ...VIEWERS_ON_DEMAND, ...Object.values(READER_SERVICES), 'models', 'gateway', 'shell']),
+ // once needed: a request asks. Shell and Agent Messages are in the always-running edge host, but a first request
+ // can beat that host's connection. Hold it through the same bounded startup gate; after any disconnect, fail
+ // promptly as before. Under a master from before, Agent Messages' own process starts at its first request this way.
+ onDemand: new Set([...experiments, ...DEVICES_ON_DEMAND, ...VIEWERS_ON_DEMAND, ...Object.values(READER_SERVICES), 'models', 'gateway', 'shell', 'messages']),
want: (service) => experimentHooks.want(service),
// The gateway's first: its `backend` reads (the device key log) were refused below as NOT_AN_EXPERIMENT.
answer: async (service, query, payload, authority) => await questionControls.answer(service, query, payload) ?? await modelControls.answer(service, query, payload) ?? await nativeControls.answer(service, query, payload) ?? engineReaders.answer(service) ?? (service === 'gateway' && gatewayLink ? gatewayLink.answer(query, payload) : null) ?? deliveries.answer(service, query, payload)
+ // Agent Messages is answered what it uses and nothing more, never what an experiment may ask (core/messagesLink.ts).
+ ?? (service === 'messages' ? await messagesLink.answer(query, payload) : null)
?? await answerConnectorsQuery(coreApi, service, query, payload)
?? await answerExperimentQuery(coreApi, experiments, service, query, payload)
?? await terminalWatch.answer(service, query, payload)
@@ -1328,7 +1335,6 @@ async function runForeground(session: AuthSession | null): Promise<void> {
: service === 'workspaces' ? workspacesLink.answer(query, payload)
: service === 'store' ? storeLink.answer(query, payload)
: service === 'models' ? modelsLink.answer(query, payload)
- : service === 'messages' ? messagesLink.answer(query, payload)
: service === 'devices' ? devicesLink.answer(query, payload)
: service === 'wifi' ? wifiLink.answer(query, payload)
: service === 'handoff' ? answerConversationQuery(coreApi, query, payload, authority)
@@ -1415,8 +1421,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {
if (outOfProcess.has('sharing')) ports.sharing = createSharingLink({ call: (type, payload) => serviceLinks.call('sharing', type, payload), notify: (frame) => serviceLinks.notify('sharing', frame) })
else serviceHost.start('sharing', inline!.startSharing, coreApi, SHARING_FALLBACKS, SHARE_REQUESTS)
backend.observers = { receive: (connId, type, payload) => ports.sharing?.observer(connId, type, payload), closeAll: () => ports.sharing?.linkDown() }
- // Agent Messages (services/messages.ts): in its own process once it is on, or in this one behind the service
- // host's guard (a fault there costs no message its write).
+ // Agent Messages (services/messages.ts): in the edge host, or in this process behind the service host's guard (a
+ // fault there costs no message its write).
if (outOfProcess.has('messages')) ports.messages = messagesLink.port
else serviceHost.start('messages', inline!.startMessagesInCore, coreApi, MESSAGES_FALLBACKS, MESSAGES_REQUESTS)
// The harnesses installed here, and installing, updating and removing one (services/store.ts): in this
@@ -1829,13 +1835,14 @@ async function runForeground(session: AuthSession | null): Promise<void> {
onDeskRead: () => proxyBackend('GET', '/api/desk'),
onDeskOps: (body) => proxyBackend('POST', '/api/desk/ops', body),
// The account's tabs for Agent Messages (backend routes/agentMessages.ts). A tab's flag is an older window's only:
- // Settings ▸ Agents decides, so its switch is passed on and wakes nothing.
+ // Settings ▸ Agents decides, so its switch is passed on and decides nothing.
onAgentMessagesRead: () => proxyBackend('GET', '/api/agent-messages'),
onAgentMessagesWrite: (tabId, body) => proxyBackend('PATCH', `/api/agent-messages/tabs/${tabId}`, body),
onExperimentalRead: () => proxyBackend('GET', '/api/experimental-settings'),
onExperimentalWrite: (body) => proxyBackend('PATCH', '/api/experimental-settings', body),
onAgentSettingsRead: agentSettings.read,
- onAgentSettingsWrite: (body) => writeAgentSettingsAndWake(() => agentSettings.write(body), EXPERIMENTS, (service) => experimentHooks.want(service)),
+ // Agent Messages is told, wherever it runs: off, it reads its switch again only when told or its file changes.
+ onAgentSettingsWrite: (body) => writeSettingsAndTell(() => agentSettings.write(body), () => ports.messages?.settingsChanged()),
onStore: (method, path, body) => proxyBackend(method, path, body),
}, { socketPath: localSocketPath(env.ADAPTER_DATA_DIR, env.PORT), allowPortFallback: true })
try { saveDaemonPort(env.ADAPTER_DATA_DIR, env.PORT, hookPort) } catch (error) {
@@ -1854,10 +1861,11 @@ async function runForeground(session: AuthSession | null): Promise<void> {
if (coreLink.supervised) {
coreLink.bound(hookPort)
coreLink.startHeartbeat()
- // The experiments with saved state, or with their Settings ▸ Agents switch on, are on: their processes are
- // asked for now, the master heeding a bound core alone (core/experiments.ts). The others wait for their first
- // request.
+ // The experiments with saved state are on: their processes are asked for now, the master heeding a bound core
+ // alone (core/experiments.ts). The others wait for their first request. Agent Messages is asked for too, which
+ // starts a process only under a master from before it joined the edge host (core/messagesLink.ts).
wakeExperiments({ dataDir: env.ADAPTER_DATA_DIR, experiments: EXPERIMENTS, outOfProcess, want: (service) => experimentHooks.want(service) })
+ askForMessages(outOfProcess, (service) => coreLink.want(service))
devicesWake.start(outOfProcess)
wakeModels({ outOfProcess, dataDir: env.ADAPTER_DATA_DIR, runtimeDir: env.ADAPTER_RUNTIME_DIR, want: (service) => coreLink.want(service) })
wakeViewers({ wake: viewersWake, agents: () => registry.list(), dataDir: env.ADAPTER_DATA_DIR })
diff --git a/cli/src/core/messagesLink.spec.ts b/cli/src/core/messagesLink.spec.ts
index 67965bd02..54cff1558 100644
--- a/cli/src/core/messagesLink.spec.ts
+++ b/cli/src/core/messagesLink.spec.ts
@@ -1,27 +1,119 @@
-import { describe, expect, it } from 'vitest'
-import { createMessagesLink } from './messagesLink.js'
+import { describe, expect, it, vi } from 'vitest'
+import type { RegisteredSession } from '../lib/registry.js'
+import { fakeCore } from '../testing/fakeCore.js'
+import { MESSAGES_QUERIES } from './api.js'
+import { askForMessages, createMessagesLink, writeSettingsAndTell } from './messagesLink.js'
+
+const agent = (agentId: string) => ({ agentId, sessionId: `s-${agentId}`, engine: 'claude', cwd: '/w' }) as RegisteredSession
describe('Agent Messages in its own process, as the core keeps it', () => {
+ const link = (over: Parameters<typeof fakeCore>[0] = {}, now?: () => number) => {
+ const notify = vi.fn(() => true)
+ return { notify, link: createMessagesLink({ core: fakeCore(over), notify, now }) }
+ }
+
it('says a delivery may be written only while the process last said so, and not past when it said', () => {
let clock = 1_000
- const link = createMessagesLink(() => clock)
- expect(link.port.canWrite('team:d1')).toBe(false)
- expect(link.answer('writable', { deliveries: { 'team:d1': 1_000 + 3_000, 'team:d2': 'soon' } })).toEqual({})
- expect(link.port.canWrite('team:d1')).toBe(true)
- expect(link.port.canWrite('team:d2')).toBe(false)
+ const { link: l } = link({}, () => clock)
+ expect(l.port.canWrite('team:d1')).toBe(false)
+ expect(l.answer('writable', { deliveries: { 'team:d1': 1_000 + 3_000, 'team:d2': 'soon' } })).toEqual({})
+ expect(l.port.canWrite('team:d1')).toBe(true)
+ expect(l.port.canWrite('team:d2')).toBe(false)
clock += 3_000
- expect(link.port.canWrite('team:d1')).toBe(false)
- link.answer('writable', { deliveries: { 'team:d1': 99_999 } })
- expect(link.port.canWrite('team:d1')).toBe(true)
+ expect(l.port.canWrite('team:d1')).toBe(false)
+ l.answer('writable', { deliveries: { 'team:d1': 99_999 } })
+ expect(l.port.canWrite('team:d1')).toBe(true)
// A report replaces the last whole.
- link.answer('writable', {})
- expect(link.port.canWrite('team:d1')).toBe(false)
+ l.answer('writable', {})
+ expect(l.port.canWrite('team:d1')).toBe(false)
+ })
+
+ it('reads the real clock by default', () => {
+ const { link: l } = link()
+ l.answer('writable', { deliveries: { 'team:d1': Date.now() + 60_000 } })
+ expect(l.port.canWrite('team:d1')).toBe(true)
+ })
+
+ it('shows it the agents as the apps are shown them, and how this daemon is reached and whether it is signed in', async () => {
+ let signedIn = true
+ const { link: l } = link({
+ agents: { live: () => [agent('a1')], displayName: (s) => `name of ${s.agentId}`, terminalAvailable: () => true, dsh: () => null },
+ daemon: { command: `'node' 'cli.js'`, port: 18473, machineId: () => 'machine-7', autonomousEnv: 'prod' },
+ account: { signedIn: () => signedIn },
+ })
+ expect(await l.answer('shown', {})).toEqual({ agents: [{ ...agent('a1'), displayName: 'name of a1', terminalAvailable: true, dshContext: null }] })
+ expect(await l.answer('daemon', {})).toEqual({ command: `'node' 'cli.js'`, port: 18473, machineId: 'machine-7', autonomousEnv: 'prod', signedIn: true })
+ signedIn = false
+ expect(await l.answer('daemon', {})).toMatchObject({ signedIn: false })
+ })
+
+ it('reads the account\'s tabs for it, and nothing else of the backend', async () => {
+ const backend = vi.fn(async () => ({ status: 200, body: { success: true, data: { tabs: [] } } }))
+ const { link: l } = link({ account: { backend } })
+ expect(await l.answer('backend', { method: 'GET', path: '/api/agent-messages' })).toEqual({ status: 200, body: { success: true, data: { tabs: [] } } })
+ expect(backend.mock.calls).toEqual([['GET', '/api/agent-messages']])
+ // An experiment may write the account's settings or read anything under /api/; Agent Messages reads its tabs.
+ for (const asked of [{ method: 'PATCH', path: '/api/agent-messages' }, { method: 'GET', path: '/api/machines' }, { method: 'GET', path: '/api/agent-messages?all=1' }, {}]) {
+ expect(await l.answer('backend', asked)).toEqual({ error: 'INVALID_REQUEST' })
+ }
+ expect(backend).toHaveBeenCalledOnce()
+ })
+
+ it('tells the windows its log changed, and nothing else', async () => {
+ const windows = vi.fn()
+ const { link: l } = link({ clients: { windows } })
+ expect(await l.answer('windows', { frame: { type: 'messages_changed', payload: { tabId: 'app' }, extra: 1 } })).toEqual({})
+ expect(windows.mock.calls).toEqual([[{ type: 'messages_changed', payload: { tabId: 'app' } }]])
+ for (const frame of [undefined, { type: 'orchestrator_changed', payload: {} }, { type: 'agents_list', payload: {} }, { type: 'messages_changed' }, { type: 'messages_changed', payload: 'x' }]) {
+ expect(await l.answer('windows', { frame })).toEqual({ error: 'INVALID_FRAME' })
+ }
+ expect(windows).toHaveBeenCalledOnce()
})
- it('answers no other question, and reads the real clock by default', () => {
- const link = createMessagesLink()
- expect(link.answer('agents', {})).toEqual({ error: 'UNKNOWN_QUERY' })
- link.answer('writable', { deliveries: { 'team:d1': Date.now() + 60_000 } })
- expect(link.port.canWrite('team:d1')).toBe(true)
+ it('answers what it uses alone: never what an experiment acts on the core through', async () => {
+ const create = vi.fn()
+ const stop = vi.fn()
+ const { link: l } = link({ agents: { create }, turns: { stop } })
+ for (const query of ['create', 'stop_turn', 'observer_key', 'observer_send', 'live', 'agents', 'connector_vault']) {
+ expect(await l.answer(query, { engine: 'claude', cwd: '/w', prompt: 'p', name: 'n', agentId: 'a1' })).toEqual({ error: 'UNKNOWN_QUERY' })
+ }
+ expect(create).not.toHaveBeenCalled()
+ expect(stop).not.toHaveBeenCalled()
+ expect([...MESSAGES_QUERIES].sort()).toEqual(['backend', 'daemon', 'shown', 'windows', 'writable'])
+ })
+
+ it('tells the process Settings ▸ Agents was written through the daemon', () => {
+ const { link: l, notify } = link()
+ l.port.settingsChanged()
+ expect(notify.mock.calls).toEqual([[{ type: 'service_event', payload: { kind: 'settings' } }]])
+ })
+
+ it('tells the process the desk changed, and no other notice', () => {
+ const { link: l, notify } = link()
+ l.notice({ type: 'desk_changed', revision: 7 })
+ l.notice({ type: 'machines_changed', reason: 'renamed' })
+ l.notice({ type: 'connectors_changed', revision: 1 })
+ expect(notify.mock.calls).toEqual([[{ type: 'service_event', payload: { kind: 'notice', notice: { type: 'desk_changed', revision: 7 } } }]])
+ })
+})
+
+describe('a Settings ▸ Agents write through the daemon', () => {
+ it('tells Agent Messages once it is written, and not when it was refused', async () => {
+ const tell = vi.fn()
+ expect(await writeSettingsAndTell(async () => ({ status: 200, body: { agentMessages: true } }), tell)).toEqual({ status: 200, body: { agentMessages: true } })
+ expect(tell).toHaveBeenCalledOnce()
+ await writeSettingsAndTell(async () => ({ status: 400, body: {} }), tell)
+ await writeSettingsAndTell(async () => ({ status: 199, body: {} }), tell)
+ expect(tell).toHaveBeenCalledOnce()
+ })
+})
+
+describe('Agent Messages asked for as the core starts', () => {
+ it('is asked for when it runs out of the core\'s process, which starts a process only under a master from before', () => {
+ const want = vi.fn()
+ expect(askForMessages(new Set(['search', 'messages']), want)).toBe(true)
+ expect(want.mock.calls).toEqual([['messages']])
+ expect(askForMessages(new Set(['search']), want)).toBe(false)
+ expect(want).toHaveBeenCalledOnce()
})
})
diff --git a/cli/src/core/messagesLink.ts b/cli/src/core/messagesLink.ts
index f60ed935c..f4d7fe0b7 100644
--- a/cli/src/core/messagesLink.ts
+++ b/cli/src/core/messagesLink.ts
@@ -1,27 +1,100 @@
/**
- * Agent Messages in its own process, as the core sees it (`HARNESSD_SERVICES=messages`; the process's side is
- * services/messagesProcess.ts): which of its typed deliveries may be written now.
+ * Agent Messages in a process of its own, as the core sees it (the process's side is services/messagesProcess.ts). It
+ * runs in the edge host since 2026-10-12; a master from before runs it in a process of its own, on demand, which this
+ * core asks for as it starts (`askForMessages`).
*
- * The core asks in line, as it writes a `team:` delivery into an idle agent's pane (core/input.ts), and never
- * calls into the process or waits on it for that. The process tells the core instead (`writable`): each
- * delivery it still wants written, until a deadline a few seconds off, told again while it may. A process that
- * stops telling, hung or gone, leaves none writable, and a delivery waits rather than being written against
- * its mailbox's word.
+ * - Which of its typed deliveries may be written now. The core asks in line, as it writes a `team:` delivery into
+ * an idle agent's pane (core/input.ts), and never calls into the process or waits on it for that. The process
+ * tells the core instead (`writable`): each delivery it still wants written, until a deadline a few seconds off,
+ * told again while it may. A process that stops telling, hung or gone, leaves none writable, and a delivery
+ * waits rather than being written against its mailbox's word.
+ * - What it may ask of the core, and no more (core/api.ts `MESSAGES_QUERIES`). As an experiment it could ask for
+ * anything an experiment acts on the core through (core/experimentQueries.ts); as a service it is given what it
+ * uses: the agents as the apps are shown them, how this daemon is reached and whether it is signed in, the one
+ * backend read of the account's tabs, and its log's change notice for the windows. Writing turns into agents is
+ * core/deliveries.ts's to allow (`TURN_DELIVERERS`).
+ * - The account's `desk_changed`, told as the backend announces it: its tabs are read again then.
+ * - That Settings ▸ Agents was written through the daemon (`writeSettingsAndTell`), so that turning it on wakes it.
*/
-import type { MessagesPort } from './api.js'
+import { MESSAGES_BACKEND_PATH, MESSAGES_WINDOW_FRAME, type BackendNotice, type CoreApi, type MessagesPort } from './api.js'
+import { daemonAddress, shownAgents } from './experimentQueries.js'
-export function createMessagesLink(now: () => number = Date.now) {
+type Payload = Record<string, unknown>
+
+export interface MessagesLinkDeps {
+ core: Pick<CoreApi, 'agents' | 'daemon' | 'account' | 'clients'>
+ /** Tell the process something (core/serviceLinks.ts `notify`, for `messages`); false when it is not connected. */
+ notify(frame: { type: string; payload: Payload }): boolean
+ now?: () => number
+}
+
+export function createMessagesLink(deps: MessagesLinkDeps) {
+ const now = deps.now ?? Date.now
+ const { core } = deps
/** Each delivery the process says may be written now, and until when. */
let writable = new Map<string, number>()
- const port: MessagesPort = { canWrite: (deliveryId) => (writable.get(deliveryId) ?? 0) > now() }
+ const port: MessagesPort = {
+ canWrite: (deliveryId) => (writable.get(deliveryId) ?? 0) > now(),
+ // Told, never asked: a process that is down reads the file as it starts anyway.
+ settingsChanged: () => { deps.notify({ type: 'service_event', payload: { kind: 'settings' } }) },
+ }
return {
port,
- /** The core's answers to the process's questions (core/serviceLinks.ts `answer`, for `messages`). */
- answer(query: string, payload: Record<string, unknown>): Record<string, unknown> {
- if (query !== 'writable') return { error: 'UNKNOWN_QUERY' }
- const reported = payload.deliveries && typeof payload.deliveries === 'object' ? payload.deliveries as Record<string, unknown> : {}
- writable = new Map(Object.entries(reported).flatMap(([id, until]) => (typeof until === 'number' ? [[id, until] as const] : [])))
- return {}
+ /** The core's answers to the process's questions (core/serviceLinks.ts `answer`, for `messages`): those in
+ * `MESSAGES_QUERIES`, each checked, and `UNKNOWN_QUERY` for any other. */
+ answer(query: string, payload: Payload): Payload | Promise<Payload> {
+ switch (query) {
+ case 'writable': {
+ const reported = payload.deliveries && typeof payload.deliveries === 'object' ? payload.deliveries as Payload : {}
+ writable = new Map(Object.entries(reported).flatMap(([id, until]) => (typeof until === 'number' ? [[id, until] as const] : [])))
+ return {}
+ }
+ case 'shown':
+ return shownAgents(core)
+ // Signed out, it reads no tabs and runs no timer: there is no account to read them from (messages/service.ts).
+ case 'daemon':
+ return { ...daemonAddress(core), signedIn: core.account.signedIn() }
+ case 'backend':
+ if (payload.method !== 'GET' || payload.path !== MESSAGES_BACKEND_PATH) return { error: 'INVALID_REQUEST' }
+ return core.account.backend('GET', MESSAGES_BACKEND_PATH).then((answer) => ({ ...answer }))
+ case 'windows': {
+ const frame = payload.frame as Payload | undefined
+ // Its log changed, and nothing else: what the windows hear from the core itself is the core's to say.
+ if (frame?.type !== MESSAGES_WINDOW_FRAME || !frame.payload || typeof frame.payload !== 'object') return { error: 'INVALID_FRAME' }
+ core.clients.windows({ type: MESSAGES_WINDOW_FRAME, payload: frame.payload as Payload })
+ return {}
+ }
+ default:
+ return { error: 'UNKNOWN_QUERY' }
+ }
+ },
+ /** The backend announced a change to the account: the desk's is the one Agent Messages reads its tabs again for. */
+ notice(notice: BackendNotice): void {
+ if (notice.type === 'desk_changed') deps.notify({ type: 'service_event', payload: { kind: 'notice', notice } })
},
}
}
+
+/**
+ * A Settings ▸ Agents write through the daemon (`PATCH /api/agent-settings`), and Agent Messages told of it once it is
+ * written. Off, it runs no timer that would read its switch again, and where the file was never written (every switch
+ * at its default) there is no file for it to watch: this is how turning it on in Settings ▸ Agents wakes it at once.
+ */
+export async function writeSettingsAndTell<T extends { status: number }>(write: () => Promise<T>, tell: () => void): Promise<T> {
+ const result = await write()
+ if (result.status >= 200 && result.status < 300) tell()
+ return result
+}
+
+/**
+ * Ask the master for Agent Messages as the core starts, when it runs out of the core's process. This build's master
+ * runs it in the edge host, which is always running, so the ask starts nothing. A master from before runs it in a
+ * process of its own that starts only when asked: a core is left under one when that master could not re-execute on
+ * the update (harnessd/reexec.ts), and without the ask no agent would get its note, and no waiting message would
+ * move, until a request came. Asked whether it is on or off: off, it runs no timer either way (messages/service.ts).
+ */
+export function askForMessages(outOfProcess: ReadonlySet<string>, want: (service: string) => void): boolean {
+ if (!outOfProcess.has('messages')) return false
+ want('messages')
+ return true
+}
diff --git a/cli/src/harnessd/services.spec.ts b/cli/src/harnessd/services.spec.ts
index 7be703ec0..900250bf1 100644
--- a/cli/src/harnessd/services.spec.ts
+++ b/cli/src/harnessd/services.spec.ts
@@ -494,7 +494,46 @@ describe('ServiceSupervisor', () => {
const hosted = Object.values(SERVICE_HOSTS).flatMap((host) => host.services)
expect(KNOWN_SERVICES).toEqual(hosted)
expect(new Set(hosted).size).toBe(hosted.length)
- expect(SERVICE_HOSTS.edge.services).toEqual(['workspaces', 'usage', 'monitor', 'projects', 'handoff', 'recaps', 'windowNames', 'shell', 'connectors', 'agentCleanup'])
+ expect(SERVICE_HOSTS.edge.services).toEqual(['workspaces', 'usage', 'monitor', 'projects', 'handoff', 'recaps', 'windowNames', 'shell', 'connectors', 'agentCleanup', 'messages'])
+ // Agent Messages has no process of its own: one cost every computer it was on 62 MiB at idle (2026-10-12).
+ expect(Object.keys(SERVICE_HOSTS)).not.toContain('messages')
+ })
+
+ // Agent Messages left a process of its own, started on demand, for the edge host (2026-10-12). Where it runs is the
+ // master's to say, by service (`serviceProcessesEnv`), and a core routes it there and runs none of it itself, whichever
+ // build each is: two at once would both type the same messages into the same panes.
+ it('Agent Messages under a master of this build: in the edge host from the start; a core of either build routes it there, and its ask starts nothing', () => {
+ const specs = serviceSpecs({}, SERVICE_HOSTS)
+ const hosts = specs.filter((spec) => spec.services.includes('messages'))
+ expect(hosts.map((spec) => [spec.name, spec.onDemand])).toEqual([['edge', undefined]])
+ const env = { HARNESSD_SUPERVISED: '1', HARNESSD_SERVICE_TOKEN: 'token', ...serviceProcessesEnv(specs, 42) }
+ // Both builds know the name: a core from before, which ran it as an experiment, routes it to the link the edge
+ // host opens as `messages` and starts none of it in its own process; so does a core of this build.
+ expect(servicesTheMasterRuns(env, KNOWN_SERVICES).has('messages')).toBe(true)
+ const supervisor = make(specs)
+ supervisor.start()
+ const started = children.length
+ expect(children.filter((child) => child.spec.services.includes('messages')).map((child) => child.spec.name)).toEqual(['edge'])
+ // Either core asks for it as it starts (core/messagesLink.ts, core/experiments.ts): no second process.
+ supervisor.want('messages')
+ supervisor.want('messages')
+ expect(children).toHaveLength(started)
+ })
+
+ it('Agent Messages under a master from before: its own process, started once when a core of this build asks, and routed there', () => {
+ // The master as 3cff043360 ran it: a process of its own on demand, and the edge host without it.
+ const before = { ...SERVICE_HOSTS, edge: { ...SERVICE_HOSTS.edge, services: SERVICE_HOSTS.edge.services.filter((name) => name !== 'messages') },
+ messages: { services: ['messages'], heapLimitMiB: 256, rssLimitMiB: 512, onDemand: true } }
+ const specs = serviceSpecs({}, before)
+ const env = { HARNESSD_SUPERVISED: '1', HARNESSD_SERVICE_TOKEN: 'token', ...serviceProcessesEnv(specs, 42) }
+ expect(servicesTheMasterRuns(env, KNOWN_SERVICES).has('messages')).toBe(true)
+ const supervisor = make(specs)
+ supervisor.start()
+ expect(children.filter((child) => child.spec.services.includes('messages'))).toHaveLength(0)
+ // This build's core asks for it as it starts, whatever its setting says: once, one process.
+ supervisor.want('messages')
+ supervisor.want('messages')
+ expect(children.filter((child) => child.spec.services.includes('messages')).map((child) => [child.spec.name, child.spec.services])).toEqual([['messages', ['messages']]])
})
})
@@ -510,8 +549,8 @@ describe('which services the core leaves to its master', () => {
expect(serviceProcessesEnv(serviceSpecs({ HARNESSD_SERVICES: 'store' }, SERVICE_HOSTS), 42)).toMatchObject({ [SERVICE_PROCESSES_ENV]: 'store' })
// By service, not by process: a core from before the edge host routes the services it knows of it.
const hosted = serviceSpecs({ HARNESSD_SERVICES: 'edge' }, SERVICE_HOSTS)
- expect(serviceProcessesEnv(hosted, 42)).toEqual({ [SERVICE_PROCESSES_ENV]: 'workspaces,usage,monitor,projects,handoff,recaps,windowNames,shell,connectors,agentCleanup', HARNESSD_SERVICES: 'workspaces,usage,monitor,projects,handoff,recaps,windowNames,shell,connectors,agentCleanup', [ENGINE_LIVE_ENV]: '42:1', [ENGINE_RUNTIME_ENV]: '42:1', [ENGINE_SCREEN_ENV]: '42:1', [ENGINE_MODEL_CONTROL_ENV]: '42:1', [ENGINE_QUESTION_CONTROL_ENV]: '42:1', [ENGINE_SUBMISSION_ENV]: '42:1', [ENGINE_NATIVE_CONTROL_ENV]: '42:1' })
- expect([...servicesTheMasterRuns({ ...supervised, ...serviceProcessesEnv(hosted, 42) }, known)]).toEqual(['workspaces'])
+ expect(serviceProcessesEnv(hosted, 42)).toEqual({ [SERVICE_PROCESSES_ENV]: 'workspaces,usage,monitor,projects,handoff,recaps,windowNames,shell,connectors,agentCleanup,messages', HARNESSD_SERVICES: 'workspaces,usage,monitor,projects,handoff,recaps,windowNames,shell,connectors,agentCleanup,messages', [ENGINE_LIVE_ENV]: '42:1', [ENGINE_RUNTIME_ENV]: '42:1', [ENGINE_SCREEN_ENV]: '42:1', [ENGINE_MODEL_CONTROL_ENV]: '42:1', [ENGINE_QUESTION_CONTROL_ENV]: '42:1', [ENGINE_SUBMISSION_ENV]: '42:1', [ENGINE_NATIVE_CONTROL_ENV]: '42:1' })
+ expect([...servicesTheMasterRuns({ ...supervised, ...serviceProcessesEnv(hosted, 42) }, known)]).toEqual(['workspaces', 'messages'])
expect(serviceProcessesEnv([], 42)).toEqual({ [SERVICE_PROCESSES_ENV]: '', HARNESSD_SERVICES: 'none', [ENGINE_LIVE_ENV]: '42:1', [ENGINE_RUNTIME_ENV]: '42:1', [ENGINE_SCREEN_ENV]: '42:1', [ENGINE_MODEL_CONTROL_ENV]: '42:1', [ENGINE_QUESTION_CONTROL_ENV]: '42:1', [ENGINE_SUBMISSION_ENV]: '42:1', [ENGINE_NATIVE_CONTROL_ENV]: '42:1' })
expect([...servicesTheMasterRuns({ ...supervised, ...serviceProcessesEnv(specs, 42) }, known)]).toEqual(['search', 'workspaces'])
expect([...servicesTheMasterRuns({ ...supervised, ...serviceProcessesEnv([], 42) }, known)]).toEqual([])
diff --git a/cli/src/harnessd/services.ts b/cli/src/harnessd/services.ts
index 79fcd8024..0df1411a1 100644
--- a/cli/src/harnessd/services.ts
+++ b/cli/src/harnessd/services.ts
@@ -386,7 +386,12 @@ export const SERVICE_HOSTS: Readonly<Record<string, ServiceHostSpec>> = {
// most) and asks, as the core did while they ran in it, and a few timers per open turn. The window
// names hold at most 400 short names; their model runs in its own process (lib/oneshot.ts). The agent cleanup
// holds the harnesses the person joined (a thousand ids at most) and looks at the live ones once a minute.
- edge: { services: ['workspaces', 'usage', 'monitor', 'projects', 'handoff', 'recaps', 'windowNames', 'shell', 'connectors', 'agentCleanup'], heapLimitMiB: 384, rssLimitMiB: 768 },
+ // Agent Messages (services/messagesProcess.ts) holds its mailbox, the last 2,000 messages of each tab and the
+ // account's tabs, and runs no timer while it is off here or this computer is signed out. It had a process of its
+ // own as an experiment, 62 MiB resident at idle on every computer it was on, nearly all of it a second Node and
+ // the bundle rather than messaging: here it costs the edge host about 1 MiB on, and 0.4 MiB off
+ // (e2e/footprint.e2e.ts, 2026-10-12).
+ edge: { services: ['workspaces', 'usage', 'monitor', 'projects', 'handoff', 'recaps', 'windowNames', 'shell', 'connectors', 'agentCleanup', 'messages'], heapLimitMiB: 384, rssLimitMiB: 768 },
// The orchestrator (services/orchestratorProcess.ts), an experiment: started only once it is on, for a
// saved project or a request (core/api.ts `EXPERIMENTS`). Its projects' files and the frames of their
// Directors; the agents it runs are the core's.
@@ -398,10 +403,6 @@ export const SERVICE_HOSTS: Readonly<Record<string, ServiceHostSpec>> = {
// The router (services/routerProcess.ts), an experiment: started at its first request. A few decisions in
// flight, each one bounded Jev answer.
router: { services: ['router'], heapLimitMiB: 128, rssLimitMiB: 384, onDemand: true },
- // Agent Messages (services/messagesProcess.ts), an experiment: its mailbox, history and the account's tabs.
- // Started with the core while Settings ▸ Agents has it on, the default; else at its first request or for its
- // saved state (core/api.ts `EXPERIMENTS`).
- messages: { services: ['messages'], heapLimitMiB: 256, rssLimitMiB: 512, onDemand: true },
// Share, an experiment (services/sharingProcess.ts): its invitations, its observers' sessions and their
// ciphers; the headless Chrome it captures a shared viewer in is a process of its own, outside this budget.
sharing: { services: ['sharing'], heapLimitMiB: 256, rssLimitMiB: 512, onDemand: true },
diff --git a/cli/src/messages/directory.ts b/cli/src/messages/directory.ts
index 3fc6199c2..aa2fa606b 100644
--- a/cli/src/messages/directory.ts
+++ b/cli/src/messages/directory.ts
@@ -5,9 +5,9 @@
* Each tab's own flag, which the backend still answers for older windows, is not read: the tab's switch was a chat
* icon beside its × that was easy to hit by mistake, and the owner made it one setting, on by default (2026-10-12).
*
- * Read when the service starts, every 15 seconds while it runs, again on the account's `desk_changed`, and fresh
- * before a send. An unreadable directory never clears what was read: a failed read keeps the last one, and before
- * any read nothing may be sent.
+ * Read every 15 seconds while this computer is signed in with Agent Messages on (`start`, `stop`: service.ts runs it
+ * only then), again on the account's `desk_changed`, and fresh before a send. An unreadable directory never clears
+ * what was read: a failed read keeps the last one, and before any read nothing may be sent.
*/
export interface Member { machineId: string; agentId: string }
diff --git a/cli/src/messages/mailbox.spec.ts b/cli/src/messages/mailbox.spec.ts
index a78561028..66cfae9fa 100644
--- a/cli/src/messages/mailbox.spec.ts
+++ b/cli/src/messages/mailbox.spec.ts
@@ -459,6 +459,43 @@ describe('Agent Messages\' mailbox', () => {
expect(pump).toHaveBeenCalledTimes(2)
})
+ it('asleep, looks only until nothing waits, then stops by itself; paused, looks at nothing until resumed', () => {
+ // Off costs nothing: Agent Messages run in the edge host on every computer, and a look every two seconds at a
+ // mailbox with nothing in it was a timer for nothing (2026-10-12).
+ vi.useFakeTimers()
+ let asleep = false
+ const t = setup({ asleep: () => asleep })
+ t.mailbox.resume()
+ const pump = vi.spyOn(t.mailbox, 'pump')
+ vi.advanceTimersByTime(PUMP_MS * 2)
+ expect(pump, 'not started: nothing to look at').not.toHaveBeenCalled()
+ t.mailbox.start()
+ t.mailbox.resume()
+ t.setAgent(null)
+ const delivery = t.accept()
+ pump.mockClear()
+ asleep = true
+ expect(t.mailbox.waiting()).toBe(true)
+ vi.advanceTimersByTime(PUMP_MS * 2)
+ expect(pump).toHaveBeenCalledTimes(2)
+ // What waited has settled: one more look, and none after it.
+ t.refuse('Agent Messages were turned off on its computer')
+ vi.advanceTimersByTime(PUMP_MS)
+ expect(delivery.state).toBe('failed')
+ expect(t.mailbox.waiting()).toBe(false)
+ vi.advanceTimersByTime(PUMP_MS * 5)
+ expect(pump).toHaveBeenCalledTimes(3)
+ // Awake, it looks with nothing waiting too; paused, not at all.
+ asleep = false
+ t.mailbox.resume()
+ vi.advanceTimersByTime(PUMP_MS * 2)
+ expect(pump).toHaveBeenCalledTimes(5)
+ t.mailbox.pause()
+ t.mailbox.pause()
+ vi.advanceTimersByTime(PUMP_MS * 2)
+ expect(pump).toHaveBeenCalledTimes(5)
+ })
+
it('keeps going when the inbox cannot be written or the store saved', () => {
const t = setup()
vi.spyOn(t.inbox, 'put').mockImplementation(() => { throw new Error('disk full') })
diff --git a/cli/src/messages/mailbox.ts b/cli/src/messages/mailbox.ts
index facdf4d24..172e69daf 100644
--- a/cli/src/messages/mailbox.ts
+++ b/cli/src/messages/mailbox.ts
@@ -77,6 +77,8 @@ export interface MailboxDeps {
changed(status: DeliveryStatus, delivery: LocalDelivery): void
/** Whether a typed attempt may be written changed: its process tells the core (services/messagesProcess.ts). */
writable?(): void
+ /** Whether Agent Messages sleep here (off, or signed out): then the pump stops once nothing waits. */
+ asleep?(): boolean
now?(): number
}
@@ -127,15 +129,39 @@ export class Mailbox {
// Finished deliveries are only kept a day: their outcome is in the history.
this.deps.store.state.local = this.local.filter((d) => d.state === 'queued' || this.now() - d.at < FINISHED_KEEP_MS)
this.save()
- this.timer = setInterval(() => { try { this.pump() } catch { /* the next pump looks again */ } }, PUMP_MS)
- this.timer.unref?.()
+ this.resume()
}
stop(): void {
+ this.pause()
+ }
+
+ /**
+ * Look every PUMP_MS from now on, unless it already does: while Agent Messages are on, and while they sleep with a
+ * delivery still waiting here, which the pump holds out of the hook's reach and fails once it has waited
+ * HELD_OUTSIDE_MS (messages/service.ts). Then it stops by itself.
+ */
+ resume(): void {
+ if (!this.started || this.timer) return
+ this.timer = setInterval(() => {
+ try { this.pump() } catch { /* the next pump looks again */ }
+ // Off costs nothing: once what waited has settled, nothing is looked at until Agent Messages wake.
+ if (this.deps.asleep?.() && !this.waiting()) this.pause()
+ }, PUMP_MS)
+ this.timer.unref?.()
+ }
+
+ /** Look no more until resumed: Agent Messages sleep, with nothing here to settle or no account to settle it by. */
+ pause(): void {
if (this.timer) clearInterval(this.timer)
this.timer = null
}
+ /** Whether any delivery here still waits to be delivered or failed. */
+ waiting(): boolean {
+ return this.local.some((d) => d.state === 'queued')
+ }
+
/**
* Forget every typed attempt in flight, giving its message back to the hook: as the service starts, and when
* it reaches a new core, which holds none of them (an update restarts the core, not this process). Whatever
diff --git a/cli/src/messages/service.spec.ts b/cli/src/messages/service.spec.ts
index cc87fcd07..e9e1dbc10 100644
--- a/cli/src/messages/service.spec.ts
+++ b/cli/src/messages/service.spec.ts
@@ -28,6 +28,7 @@ interface Setup {
agents?: RegisteredSession[]
rpc?: Rpc
backendStatus?: number
+ signedIn?: () => boolean
}
function setup(over: Setup = {}) {
@@ -48,6 +49,8 @@ function setup(over: Setup = {}) {
return { statuses: [] }
})
const changed = vi.fn()
+ /** The watches on Settings ▸ Agents' file, armed while Agent Messages are off (settingWatch.ts): heard at a write. */
+ const watchers = new Set<() => void>()
const core = fakeCore({
dataDir: root,
daemon: { machineId: () => 'm1', port: 18473 },
@@ -63,18 +66,24 @@ function setup(over: Setup = {}) {
account: {
backend,
onNotice: (listener) => { noticeListeners.add(listener); return () => noticeListeners.delete(listener) },
+ ...(over.signedIn ? { signedIn: over.signedIn } : {}),
},
clients: { windows: (frame) => { windows.push(frame) } },
})
- const service = startAgentMessages(core, { stateDir: join(root, 'state'), inboxRoot: join(root, 'inbox-root'), rpc: over.rpc ? over.rpc : rpc, now: () => clock, changed })
+ const service = startAgentMessages(core, { stateDir: join(root, 'state'), inboxRoot: join(root, 'inbox-root'), rpc: over.rpc ? over.rpc : rpc, now: () => clock, changed,
+ watchSetting: (_path, heard) => { watchers.add(heard); return () => { watchers.delete(heard) } } })
const ask = (payload: Record<string, unknown>, asker = OWNER_LOCAL) => service.requests.agent_messages!(payload, asker)
return {
- service, ask, delivered, windows, backend, rpcCalls, agents, tabs, directory, changed,
+ service, ask, delivered, windows, backend, rpcCalls, agents, tabs, directory, changed, watchers,
inbox: new PaneInbox(join(root, 'inbox-root')),
tick: (ms: number) => { clock += ms },
/** Settings ▸ Agents on this computer, as the person turns Agent Messages on or off: read at the service's next
- * look, once what it read last is no longer fresh. */
- setting: (on: boolean) => { writeAgentSettings(root, { agentMessages: on }); clock += SETTING_FRESH_MS },
+ * look, once what it read last is no longer fresh, and heard by the watch on its file while they are off. */
+ setting: (on: boolean) => {
+ writeAgentSettings(root, { agentMessages: on })
+ clock += SETTING_FRESH_MS
+ for (const heard of [...watchers]) heard()
+ },
deliveryEvent: (event: TurnDelivery) => { for (const l of deliveryListeners) l(event) },
notice: (notice: BackendNotice) => { for (const l of noticeListeners) l(notice) },
}
@@ -709,3 +718,149 @@ describe('the roster note and the directory', () => {
t.service.stop()
})
})
+
+describe('off costs nothing', () => {
+ // It runs in the edge host on every computer (2026-10-12). Off, or signed out, a read of the account's tabs every
+ // 15 s and three timers carried messages it never could.
+ const waitingFromBefore = (id = 'm0000w01') => {
+ const store = new MessageStore(join(root, 'state'))
+ store.record({ id, tabId: 'app', at: 1, text: 'from before',
+ from: { machineId: 'm2', agentId: 'phone', name: 'phone', engine: 'claude', machine: 'laptop' }, to: [{ machineId: 'm1', agentId: 'api', name: 'api' }] })
+ store.status({ messageId: id, machineId: 'm1', agentId: 'api', state: 'queued', at: 1 })
+ store.state.local.push({ key: deliveryKey(id, 'api'), messageId: id, agentId: 'api', pane: '%2', session: 's-api', state: 'queued', tries: 0, nextTryAt: 0, at: 1 })
+ new PaneInbox(join(root, 'inbox-root')).put('%2', deliveryKey(id, 'api'), { session: 's-api', text: 'from before' })
+ store.save()
+ return deliveryKey(id, 'api')
+ }
+ const statusOf = async (t: ReturnType<typeof setup>, id: string) =>
+ ((await t.ask({ action: 'history' })).messages as Array<{ id: string; statuses: Array<{ state: string; reason?: string }> }>).find((m) => m.id === id)!.statuses[0]
+
+ it('off from the start: reads no tabs and puts no note; holds what waits, fails it later, then runs no timer; on, it wakes', async () => {
+ vi.useFakeTimers()
+ const key = waitingFromBefore()
+ const t = setup()
+ t.setting(false)
+ t.service.start()
+ await vi.advanceTimersByTimeAsync(0)
+ // Held out of the hook's reach at once, the tabs unread: off, no tab carries a message, whatever they say.
+ expect(t.inbox.waiting('%2', key)).toBe(false)
+ expect(await statusOf(t, 'm0000w01')).toMatchObject({ state: 'queued', reason: HELD_OFF_REASON })
+ t.notice({ type: 'desk_changed', revision: 9 })
+ t.notice({ type: 'machines_changed', reason: 'renamed' })
+ await vi.advanceTimersByTimeAsync(PUMP_MS)
+ expect(await statusOf(t, 'm0000w01')).toMatchObject({ state: 'queued', reason: HELD_OFF_REASON })
+ t.tick(HELD_OUTSIDE_MS)
+ await vi.advanceTimersByTimeAsync(PUMP_MS)
+ expect(await statusOf(t, 'm0000w01')).toMatchObject({ state: 'failed', reason: 'Agent Messages were turned off on its computer' })
+ // Settled: nothing runs, and a minute goes by with no read and no note.
+ await vi.advanceTimersByTimeAsync(PUMP_MS)
+ expect(vi.getTimerCount()).toBe(0)
+ await vi.advanceTimersByTimeAsync(60_000)
+ expect(t.backend).not.toHaveBeenCalled()
+ expect(t.inbox.waiting('%1', 'anything')).toBe(false)
+ expect(t.watchers.size).toBe(1)
+ // The file is heard more than once before it is read: read once.
+ for (const heard of [...t.watchers]) { heard(); heard() }
+ await vi.advanceTimersByTimeAsync(0)
+ expect(t.backend).not.toHaveBeenCalled()
+ // Turned on in Settings ▸ Agents: the watch wakes it, and the notes go out at its next look.
+ t.setting(true)
+ await vi.advanceTimersByTimeAsync(0)
+ expect(t.backend).toHaveBeenCalledOnce()
+ expect(t.watchers.size).toBe(0)
+ await vi.advanceTimersByTimeAsync(TICK_MS)
+ const notes = (pane: string) => (require('node:fs').readdirSync(t.inbox.paneDir(pane)!) as string[]).filter((n) => n.startsWith('0note-'))
+ expect(notes('%1')).toHaveLength(1)
+ expect(notes('%2')).toHaveLength(1)
+ // Its tabs every 15 s, its deliveries every 2 s, its notes and outbox every 5 s.
+ expect(vi.getTimerCount()).toBe(3)
+ t.service.stop()
+ expect(vi.getTimerCount()).toBe(0)
+ expect(t.watchers.size).toBe(0)
+ })
+
+ it('signed out: reads no tabs, runs no timer and watches nothing; signed in at its next core, it wakes', async () => {
+ vi.useFakeTimers()
+ let signedIn = false
+ const t = setup({ signedIn: () => signedIn })
+ t.service.start()
+ await vi.advanceTimersByTimeAsync(TICK_MS * 4)
+ expect(t.backend).not.toHaveBeenCalled()
+ expect(t.watchers.size).toBe(0)
+ expect(vi.getTimerCount()).toBe(0)
+ // Its requests are answered all the same.
+ expect(await t.ask({ action: 'history' })).toEqual({ messages: [] })
+ signedIn = true
+ t.service.reconnected!()
+ await vi.advanceTimersByTimeAsync(0)
+ expect(t.backend).toHaveBeenCalledOnce()
+ expect(vi.getTimerCount()).toBe(3)
+ // Turned off at its next look, then signed out: the watch goes with the rest.
+ t.setting(false)
+ await vi.advanceTimersByTimeAsync(TICK_MS)
+ expect(t.watchers.size).toBe(1)
+ signedIn = false
+ t.service.reconnected!()
+ expect(t.watchers.size).toBe(0)
+ expect(vi.getTimerCount()).toBe(0)
+ t.service.stop()
+ })
+
+ it('hands over what it sent another machine once it is on again, not while it is off', async () => {
+ vi.useFakeTimers()
+ let away = true
+ const handed: string[] = []
+ const t = setup({ rpc: async (_target, payload) => {
+ if (payload.action === 'who') return { agents: [{ agentId: 'phone', name: 'phone', engine: 'claude' }] }
+ if (payload.action === 'deliver') {
+ handed.push((payload.message as { id: string }).id)
+ if (away) throw new MessageError('DISCONNECTED', 'away')
+ return { statuses: [{ messageId: (payload.message as { id: string }).id, agentId: 'phone', state: 'queued' }] }
+ }
+ return { statuses: [] }
+ } })
+ t.service.start()
+ const reply = await t.ask({ action: 'send', pane: '%1', to: 'phone', text: 'when you are back' })
+ expect(handed).toEqual([reply.id])
+ t.setting(false)
+ await vi.advanceTimersByTimeAsync(TICK_MS)
+ away = false
+ t.tick(10 * 60_000)
+ await vi.advanceTimersByTimeAsync(TICK_MS * 3)
+ expect(handed).toEqual([reply.id])
+ t.setting(true)
+ await vi.advanceTimersByTimeAsync(TICK_MS)
+ expect(handed).toEqual([reply.id, reply.id])
+ t.service.stop()
+ })
+
+ it('wakes when told Settings ▸ Agents was written through the daemon, with no file to hear', async () => {
+ // A computer whose switches are all at their defaults has no file to watch: the daemon's write tells it.
+ vi.useFakeTimers()
+ const t = setup()
+ t.setting(false)
+ t.service.start()
+ await vi.advanceTimersByTimeAsync(0)
+ t.service.settingsChanged()
+ await vi.advanceTimersByTimeAsync(0)
+ expect(t.backend).not.toHaveBeenCalled()
+ // Written on, with no watch to hear it: told, it reads its switch again and wakes.
+ writeAgentSettings(root, { agentMessages: true })
+ t.service.settingsChanged()
+ await vi.advanceTimersByTimeAsync(0)
+ expect(t.backend).toHaveBeenCalledOnce()
+ expect(vi.getTimerCount()).toBe(3)
+ t.service.stop()
+ })
+
+ it('hears its setting\'s own file while off, with no watch given', async () => {
+ writeAgentSettings(root, { agentMessages: false })
+ const backend = vi.fn(async () => ({ status: 503, body: {} }))
+ const real = startAgentMessages(fakeCore({ dataDir: root, account: { backend } }), { stateDir: join(root, 's3'), inboxRoot: join(root, 'i3') })
+ real.start()
+ writeAgentSettings(root, { agentMessages: true })
+ for (let i = 0; i < 250 && !backend.mock.calls.length; i++) await new Promise((settle) => setTimeout(settle, 20))
+ expect(backend).toHaveBeenCalled()
+ real.stop()
+ })
+})
diff --git a/cli/src/messages/service.ts b/cli/src/messages/service.ts
index 0251e43cd..2c74b976c 100644
--- a/cli/src/messages/service.ts
+++ b/cli/src/messages/service.ts
@@ -9,13 +9,23 @@
* (agentClient/ledger.ts). It lets no one message anyone: only sharing a tab does.
* Deliveries to this machine's agents are the mailbox's (mailbox.ts); a message for another machine's agent is
* handed to that machine's daemon, which owns its delivery and is asked what became of it.
+ *
+ * Off costs nothing. It runs in the edge host on every computer, and only while this computer is signed in and has
+ * Agent Messages on does it read the account's tabs (every 15 s), look at its deliveries (every 2 s) and at its notes,
+ * its outbox and other machines' deliveries (every 5 s). Turned off, it withdraws the notes, holds what waits here out
+ * of the hook's reach and fails it once it has waited HELD_OUTSIDE_MS, as while on, and then runs nothing until it is
+ * turned on again: a Settings ▸ Agents write through the daemon tells it (`settingsChanged`), and a watch on the
+ * setting's file hears `harness settings` (settingWatch.ts); what this computer sent that waits for another machine is
+ * handed over once it is on again. Signed out it runs nothing: there is no account to read tabs from, and signing in
+ * starts a new core, which it reconnects to (`reconnected`). Its requests are answered either way, and read the switch
+ * again as they come.
*/
import { createHash } from 'node:crypto'
import { hostname } from 'node:os'
import { basename, join } from 'node:path'
import type { CoreApi, ServiceRequests, TurnDelivery } from '../core/api.js'
import { env } from '../config/env.js'
-import { readAgentSettings } from '../lib/agentSettings.js'
+import { agentSettingsPath, readAgentSettings } from '../lib/agentSettings.js'
import type { RegisteredSession } from '../lib/registry.js'
import { MessageDirectory, type Member } from './directory.js'
import { PaneInbox } from './inbox.js'
@@ -23,6 +33,7 @@ import { Mailbox, type MailboxAgent } from './mailbox.js'
import { type DeliveryStatus, LIMITS, LONG_TEXT, longAdvice, type Message, MessageError, messageId, note, parseMessage, type Recipient, rendered, type Teammate } from './model.js'
import { messagesRpc, type Rpc } from './rpc.js'
import { Ledger, ledgerPath, parseStarted } from '../agentClient/ledger.js'
+import { watchSettingFile } from './settingWatch.js'
import { MessageStore, type LocalDelivery } from './store.js'
export interface MessagesOptions {
@@ -38,6 +49,8 @@ export interface MessagesOptions {
ledgerFile?: string
/** Something that decides whether a typed delivery may be written changed: the process tells the core. */
changed?: () => void
+ /** How it hears Settings ▸ Agents' file change while Agent Messages are off (settingWatch.ts); a test's own. */
+ watchSetting?: (path: string, changed: () => void) => () => void
now?: () => number
}
@@ -45,8 +58,11 @@ export interface AgentMessages {
requests: ServiceRequests
/** Whether the core may write a typed delivery now: the mailbox's word, in line. */
canWrite(deliveryId: string): boolean
- /** The service reached a core again, perhaps a new one: typed attempts in flight go back to the hook. */
+ /** The service reached a core again, perhaps a new one: typed attempts in flight go back to the hook, and what
+ * runs follows whether this computer is signed in now. */
reconnected?(): void
+ /** Settings ▸ Agents was written through the daemon: its switch is read again, and it wakes if it is on now. */
+ settingsChanged(): void
start(): void
stop(): void
}
@@ -101,15 +117,39 @@ export function startAgentMessages(core: CoreApi, options: MessagesOptions = {})
const sent = new Map<string, number[]>()
let timer: ReturnType<typeof setInterval> | null = null
let lastRemoteStatus = -Infinity
+ /**
+ * What runs (`wake`): everything while this computer is signed in and has Agent Messages on (`awake`); while they are
+ * off, only the mailbox's look until what waited has settled, and the watch on the setting's file; signed out,
+ * nothing. Null before it starts and once it stops.
+ */
+ let mode: 'awake' | 'off' | 'signedOut' | null = null
+ const asleep = (): boolean => mode === 'off' || mode === 'signedOut'
+ let running = false
+ let unwatch: (() => void) | null = null
+ const settingsFile = agentSettingsPath(options.dataDir ?? core.dataDir)
// Settings ▸ Agents, kept by the core in the data folder (lib/agentSettings.ts) and written by `harness settings`
// too, which tells no one: a small file, read again at most every SETTING_FRESH_MS, so a switch turned off takes
- // effect at the next look.
+ // effect at the next look; while off, nothing looks, and the file's watch wakes it (settingWatch.ts).
let setting = { on: true, at: -Infinity }
+ const readSetting = (): boolean => {
+ setting = { on: readAgentSettings(options.dataDir ?? core.dataDir).agentMessages, at: now() }
+ return setting.on
+ }
const messagingOn = (): boolean => {
- if (now() - setting.at >= SETTING_FRESH_MS) setting = { on: readAgentSettings(options.dataDir ?? core.dataDir).agentMessages, at: now() }
+ if (now() - setting.at >= SETTING_FRESH_MS) {
+ const was = setting.on
+ // Turned on or off since the last look: what runs follows, once whatever asked has its answer.
+ if (readSetting() !== was) later()
+ }
return setting.on
}
+ let waking = false
+ const later = (): void => {
+ if (waking) return
+ waking = true
+ queueMicrotask(() => { waking = false; wake() })
+ }
const directory = new MessageDirectory({
on: messagingOn,
@@ -139,7 +179,9 @@ export function startAgentMessages(core: CoreApi, options: MessagesOptions = {})
refused: (delivery) => { const v = verdict(delivery); return v && 'refused' in v ? v.refused : null },
held: (delivery) => { const v = verdict(delivery); return v && 'held' in v ? v.held : null },
forbidden: (delivery) => forbidden(delivery),
- ready: () => directory.current() !== null,
+ // Off, no tab carries a message, whatever the tabs say: known without reading them.
+ ready: () => directory.current() !== null || !directory.on(),
+ asleep,
text: (delivery, message) => {
const roster = rosterOf(delivery.agentId)
return roster && store.state.noted[delivery.agentId] !== roster.signature ? `${roster.text}\n\n${rendered(message)}` : rendered(message)
@@ -174,7 +216,7 @@ export function startAgentMessages(core: CoreApi, options: MessagesOptions = {})
if (!entry) return { refused: 'the message is no longer kept' }
const never = forbidden(delivery)
if (never) return { refused: never }
- if (!directory.current()) return null
+ if (!directory.current() && directory.on()) return null
const key = `${delivery.messageId} ${delivery.agentId}`
const recipient = { machineId: self(), agentId: delivery.agentId }
// Only a tab the two share carries a message, and none while Agent Messages are off here.
@@ -311,9 +353,9 @@ export function startAgentMessages(core: CoreApi, options: MessagesOptions = {})
saveQuietly()
}
- /** Give each local agent the roster note it has not read: through its hook only, never typed. */
+ /** Give each local agent the roster note it has not read: through its hook only, never typed. Off, take each back. */
function notesPump(): void {
- if (!directory.current()) return
+ if (!directory.current() && directory.on()) return
const unknown: Member[] = []
const alive = new Set(live().map((s) => s.agentId))
// A note for a harness that is gone or stopped is withdrawn: its pane number may be another's next.
@@ -503,7 +545,8 @@ export function startAgentMessages(core: CoreApi, options: MessagesOptions = {})
if (!message) throw new MessageError('INVALID_MESSAGE', 'That is not a message.')
// This machine's own harnesses send through `send`, which names them by their pane: never as another's.
if (message.from.machineId === self()) throw new MessageError('NOT_FROM_THERE', 'A message from this machine is sent here, not handed over.')
- if (!await directory.refresh()) throw new MessageError('DIRECTORY_UNAVAILABLE', 'Harness could not read who is in which tab. It is handed over again later.')
+ // Off here, it fails below whatever the tabs say: they are not read for it.
+ if (directory.on() && !await directory.refresh()) throw new MessageError('DIRECTORY_UNAVAILABLE', 'Harness could not read who is in which tab. It is handed over again later.')
if (store.state.local.filter((d) => d.state === 'queued').length >= LIMITS.waiting) {
throw new MessageError('MAILBOX_FULL', 'Too many messages are waiting on that machine. It is handed over again later.')
}
@@ -569,7 +612,59 @@ export function startAgentMessages(core: CoreApi, options: MessagesOptions = {})
}
const stopHearing = core.turns.onDelivery((event: TurnDelivery) => mailbox.observe(event))
- const stopNotices = core.account.onNotice((notice) => { if (notice.type === 'desk_changed') void directory.refresh(true) })
+ // Asleep, a changed desk is read when it wakes, not now.
+ const stopNotices = core.account.onNotice((notice) => { if (notice.type === 'desk_changed' && !asleep()) void directory.refresh(true) })
+
+ // Started only as it wakes, when it is stopped: never twice.
+ const startTick = (): void => {
+ timer = setInterval(() => {
+ notesPump()
+ void handOver()
+ if (now() - lastRemoteStatus >= REMOTE_STATUS_MS) { lastRemoteStatus = now(); void remoteStatus() }
+ }, TICK_MS)
+ timer.unref?.()
+ }
+ const stopTick = (): void => {
+ if (timer) clearInterval(timer)
+ timer = null
+ }
+
+ /**
+ * Run what this computer calls for now: everything while it is signed in with Agent Messages on; while they are off,
+ * the notes withdrawn, what waits held and then failed by the mailbox's look, which stops once nothing waits, and
+ * a watch on the setting's file to wake it; signed out, nothing. Every computer runs this service: one with it off,
+ * or never signed in, paid a read of the account's tabs every 15 s and three timers for messages it could never
+ * carry (2026-10-12).
+ */
+ function wake(): void {
+ if (!running) return
+ const next = !core.account.signedIn() ? 'signedOut' : readSetting() ? 'awake' : 'off'
+ if (next === mode) return
+ mode = next
+ if (next === 'awake') {
+ unwatch?.()
+ unwatch = null
+ directory.start()
+ mailbox.resume()
+ startTick()
+ return
+ }
+ directory.stop()
+ stopTick()
+ if (next === 'signedOut') {
+ unwatch?.()
+ unwatch = null
+ mailbox.pause()
+ return
+ }
+ // Never watching yet: it was awake, signed out or not running, and none of those watches.
+ unwatch = (options.watchSetting ?? watchSettingFile)(settingsFile, later)
+ mailbox.refuseAll()
+ notesPump()
+ // The mailbox looks on only while something here waits to be held and then failed; it stops itself after.
+ if (mailbox.waiting()) mailbox.resume()
+ else mailbox.pause()
+ }
return {
requests: {
@@ -595,21 +690,23 @@ export function startAgentMessages(core: CoreApi, options: MessagesOptions = {})
: { error: 'MESSAGES_UNAVAILABLE', detail: 'Agent Messages are unavailable right now. Nothing was sent.' })),
},
canWrite: (deliveryId) => mailbox.canWrite(deliveryId),
- reconnected: () => mailbox.takeBackAttempts(),
+ reconnected: () => {
+ mailbox.takeBackAttempts()
+ wake()
+ },
+ settingsChanged: later,
start: () => {
- directory.start()
+ running = true
mailbox.start()
sweep()
- timer = setInterval(() => {
- notesPump()
- void handOver()
- if (now() - lastRemoteStatus >= REMOTE_STATUS_MS) { lastRemoteStatus = now(); void remoteStatus() }
- }, TICK_MS)
- timer.unref?.()
+ wake()
},
stop: () => {
- if (timer) clearInterval(timer)
- timer = null
+ running = false
+ mode = null
+ unwatch?.()
+ unwatch = null
+ stopTick()
stopHearing()
stopNotices()
mailbox.stop()
diff --git a/cli/src/messages/settingWatch.spec.ts b/cli/src/messages/settingWatch.spec.ts
new file mode 100644
index 000000000..b14274342
--- /dev/null
+++ b/cli/src/messages/settingWatch.spec.ts
@@ -0,0 +1,126 @@
+import { EventEmitter } from 'node:events'
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { agentSettingsPath, writeAgentSettings } from '../lib/agentSettings.js'
+import { POLL_MS, watchSettingFile } from './settingWatch.js'
+
+let root: string
+beforeEach(() => { root = mkdtempSync(join(tmpdir(), 'setting-watch-')) })
+afterEach(() => rmSync(root, { recursive: true, force: true }))
+
+/** Wait for [check], looking every 20 ms, up to [ms]. */
+const until = async (check: () => boolean, ms = 5_000): Promise<void> => {
+ const end = Date.now() + ms
+ while (!check()) {
+ if (Date.now() > end) throw new Error('timed out')
+ await new Promise((settle) => setTimeout(settle, 20))
+ }
+}
+
+/** A watch a test drives: its listener, its close, and its error. */
+class FakeWatch extends EventEmitter {
+ closed = false
+ constructor(readonly listener: () => void) { super() }
+ close(): void { this.closed = true }
+}
+
+describe('the watch on Settings ▸ Agents while Agent Messages are off', () => {
+ it('hears every write to the file, each a rename over the one it watched, until it is stopped', async () => {
+ writeAgentSettings(root, { agentMessages: false })
+ const changed = vi.fn()
+ const stop = watchSettingFile(agentSettingsPath(root), changed)
+ // Read once more as the watch takes hold, for a write it could not yet hear.
+ await until(() => changed.mock.calls.length === 1)
+ // As Settings ▸ Agents and `harness settings` write it: whole, renamed into place.
+ writeAgentSettings(root, { agentMessages: true })
+ await until(() => changed.mock.calls.length >= 2)
+ const heard = changed.mock.calls.length
+ writeAgentSettings(root, { agentMessages: false })
+ await until(() => changed.mock.calls.length > heard)
+ stop()
+ stop()
+ const after = changed.mock.calls.length
+ writeAgentSettings(root, { agentMessages: true })
+ await new Promise((settle) => setTimeout(settle, 300))
+ expect(changed).toHaveBeenCalledTimes(after)
+ })
+
+ it('watches nothing and polls nothing for a file that is not there: every switch is at its default', async () => {
+ // Polling for the file would be the timer off must not cost; the daemon's write tells the service instead.
+ const changed = vi.fn()
+ const poll = vi.fn(() => () => {})
+ const stop = watchSettingFile(agentSettingsPath(root), changed, { poll })
+ writeAgentSettings(root, { agentMessages: true })
+ await new Promise((settle) => setTimeout(settle, 300))
+ expect(poll).not.toHaveBeenCalled()
+ expect(changed).not.toHaveBeenCalled()
+ stop()
+ })
+
+ it('looks at the file\'s time where it cannot be watched for another reason, and stops looking once stopped', async () => {
+ const changed = vi.fn()
+ const path = agentSettingsPath(root)
+ const noWatches = () => { throw Object.assign(new Error('ENOSPC: no inotify watches left'), { code: 'ENOSPC' }) }
+ // Looked at by time, the real way: the file appears, and is heard within a few looks.
+ const stop = watchSettingFile(path, changed, { watch: noWatches })
+ writeFileSync(path, '{"agentMessages":true}\n')
+ await until(() => changed.mock.calls.length >= 1, POLL_MS * 4)
+ stop()
+ const polls = vi.fn(() => () => {})
+ const stopped = vi.fn()
+ watchSettingFile(path, changed, { watch: noWatches, poll: (_p, listener) => { polls(); listener(); return stopped } })()
+ expect(polls).toHaveBeenCalledOnce()
+ expect(stopped).toHaveBeenCalledOnce()
+ }, 20_000)
+
+ it('re-arms before it says the file changed, and never hears a watch it replaced or stopped', async () => {
+ const watches: FakeWatch[] = []
+ const changed = vi.fn()
+ const stop = watchSettingFile('/data/agent-settings.json', changed, {
+ watch: (_path, listener) => { const w = new FakeWatch(listener); watches.push(w); return w },
+ poll: () => () => {},
+ })
+ expect(watches).toHaveLength(1)
+ // Its read for the next turn, once the watch holds.
+ await new Promise((settle) => setImmediate(settle))
+ expect(changed).toHaveBeenCalledOnce()
+ changed.mockClear()
+ changed.mockImplementation(() => { expect(watches).toHaveLength(2) })
+ watches[0].listener()
+ expect(watches[0].closed).toBe(true)
+ expect(changed).toHaveBeenCalledOnce()
+ // The replaced watch says something late: not heard.
+ watches[0].listener()
+ watches[0].emit('error', new Error('late'))
+ expect(changed).toHaveBeenCalledOnce()
+ stop()
+ expect(watches[1].closed).toBe(true)
+ watches[1].listener()
+ watches[1].emit('error', new Error('after stop'))
+ // Stopped before its next turn: its read for it is not made.
+ await new Promise((settle) => setImmediate(settle))
+ expect(changed).toHaveBeenCalledOnce()
+ })
+
+ it('falls back to looking by time when a watch fails later, and says the file may have changed', async () => {
+ const watches: FakeWatch[] = []
+ const changed = vi.fn()
+ const stopPolling = vi.fn()
+ const poll = vi.fn(() => stopPolling)
+ const stop = watchSettingFile('/data/agent-settings.json', changed, {
+ watch: (_path, listener) => { const w = new FakeWatch(listener); watches.push(w); return w },
+ poll,
+ })
+ watches[0].emit('error', new Error('the folder went'))
+ expect(watches[0].closed).toBe(true)
+ expect(poll).toHaveBeenCalledOnce()
+ expect(changed).toHaveBeenCalledOnce()
+ // The failed watch's read for its next turn is not made: the polling has the file now.
+ await new Promise((settle) => setImmediate(settle))
+ expect(changed).toHaveBeenCalledOnce()
+ stop()
+ expect(stopPolling).toHaveBeenCalledOnce()
+ })
+})
diff --git a/cli/src/messages/settingWatch.ts b/cli/src/messages/settingWatch.ts
new file mode 100644
index 000000000..acb519d60
--- /dev/null
+++ b/cli/src/messages/settingWatch.ts
@@ -0,0 +1,80 @@
+/**
+ * Hearing `harness settings` turn Agent Messages on again, while it is off (messages/service.ts). Off, the service runs
+ * no timer, so nothing of it would read the setting again: it watches the one file the setting is kept in
+ * (lib/agentSettings.ts `agent-settings.json`), which `harness settings` writes on its own and tells no one of.
+ * Settings ▸ Agents writes it through the daemon, which tells the service as well (core/messagesLink.ts).
+ *
+ * The file itself, not the data folder it is in: the daemon's log, the search index and the registry are written there
+ * many times a second, and every write would wake this process for nothing. A write replaces the file (a rename over
+ * it), which ends a watch on the one it replaced, so every event re-arms the watch on the path before it says the file
+ * changed. A watch only follows the file from the event loop's next turn (its kernel registration is made then): a
+ * write in the same turn would go unheard, found by its own test, so each watch says the file may have changed once
+ * more, on that next turn, and the reader reads it again.
+ *
+ * A file that is not there is not watched, and not looked for: every switch is then at its default, and polling for
+ * the file would be the timer off must not cost. The daemon's write tells the service; a `harness settings` that writes
+ * the file for the first time is heard at the service's next request (`harness send` reads the switch) or the core's
+ * next start. Where a watch cannot be had for another reason (no inotify watches left), or fails later, it falls back
+ * to looking at the file's time every `POLL_MS`: degraded, still no backend and no pump.
+ */
+import { unwatchFile, watch, watchFile } from 'node:fs'
+
+/** How often the fallback looks at the file, where it cannot be watched. */
+export const POLL_MS = 2_000
+
+/** What a watch gives back: closing it, and hearing it fail. */
+export interface Watching {
+ close(): void
+ on(event: 'error', listener: (error: Error) => void): unknown
+}
+
+export interface SettingWatchDeps {
+ watch?: (path: string, listener: () => void) => Watching
+ poll?: (path: string, listener: () => void) => () => void
+}
+
+const watchPath = (path: string, listener: () => void): Watching => watch(path, { persistent: false }, listener)
+const pollPath = (path: string, listener: () => void): (() => void) => {
+ watchFile(path, { persistent: false, interval: POLL_MS }, listener)
+ return () => unwatchFile(path, listener)
+}
+
+/** Call [changed] whenever the file at [path] may have changed, until the returned function is called. */
+export function watchSettingFile(path: string, changed: () => void, deps: SettingWatchDeps = {}): () => void {
+ const watchOne = deps.watch ?? watchPath
+ const poll = deps.poll ?? pollPath
+ let watcher: Watching | null = null
+ let stopPolling: (() => void) | null = null
+ let stopped = false
+ const arm = (): void => {
+ try {
+ const armed: Watching = watchOne(path, () => {
+ if (stopped || watcher !== armed) return
+ armed.close()
+ arm()
+ changed()
+ })
+ watcher = armed
+ setImmediate(() => { if (!stopped && watcher === armed) changed() }).unref()
+ // A watch that fails later (the folder gone) says the file may have changed, and is looked at by time from then.
+ armed.on('error', () => {
+ if (stopped || watcher !== armed) return
+ armed.close()
+ watcher = null
+ stopPolling = poll(path, changed)
+ changed()
+ })
+ } catch (error) {
+ watcher = null
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') stopPolling = poll(path, changed)
+ }
+ }
+ arm()
+ return () => {
+ stopped = true
+ watcher?.close()
+ watcher = null
+ stopPolling?.()
+ stopPolling = null
+ }
+}
diff --git a/cli/src/serviceProcess.ts b/cli/src/serviceProcess.ts
index 87a025ccb..55d04d484 100644
--- a/cli/src/serviceProcess.ts
+++ b/cli/src/serviceProcess.ts
@@ -44,6 +44,7 @@ export const SERVICE_RUNNERS: ReadonlyMap<string, () => Promise<Runner>> = new M
['recaps', async () => (await import('./services/recapsProcess.js')).runRecapsService],
['agentCleanup', async () => (await import('./services/agentCleanupProcess.js')).runAgentCleanupService],
['store', async () => (await import('./services/storeProcess.js')).runStoreService],
+ // In the edge host since 2026-10-12; alone in a process of its own when a master from before starts it on this build.
['messages', async () => (await import('./services/messagesProcess.js')).runMessagesService],
['sharing', async () => (await import('./services/sharingProcess.js')).runSharingService],
['orchestrator', async () => (await import('./services/orchestratorProcess.js')).runOrchestratorService],
diff --git a/cli/src/services/AGENTS.md b/cli/src/services/AGENTS.md
index 2c23277c9..148aac911 100644
--- a/cli/src/services/AGENTS.md
+++ b/cli/src/services/AGENTS.md
@@ -54,12 +54,11 @@ that process. A process per risk, not per feature (`SERVICE_HOSTS` in `src/harne
| `engine-claude`, `engine-codex` | history, live parsers, runtime profiles, screens, submission readings, model control, question navigation and Codex's app-server connection (`src/engines/worker/`) | engine behavior outside core; snapshots and revocable model- and question-control grants | on demand |
| `search` | search | native `node:sqlite`, the index's memory | always |
| `viewers` | viewers, store | the viewer servers, the remote viewer streams and rendered surfaces, minutes-long installs | on demand |
-| `edge` | workspaces, usage, monitor, projects, handoff, recaps, windowNames, shell, connectors, agentCleanup | light pure-JS services: isolated from the core, not from each other | always |
+| `edge` | workspaces, usage, monitor, projects, handoff, recaps, windowNames, shell, connectors, agentCleanup, messages | light pure-JS services: isolated from the core, not from each other | always |
| `gateway` | gateway | network, crypto and pure-JS WebRTC: the attack surface | on demand |
| `models` | models | grid's installs, downloads and commands | on demand |
| `devices` | devices, wifi | the dials' serial ports, the fleet's lane, the voice router's worker, the Wi-Fi device | on demand |
| `orchestrator` | orchestrator | an experiment | on demand |
-| `messages` | messages | an experiment: Agent Messages | on demand |
| `sharing` | sharing | an experiment: Share | on demand |
| `memory` | memory | an experiment: Memories across machines | on demand |
| `router` | router | an experiment: where ⌘B sends a task, decided by Jev | on demand |
@@ -145,11 +144,19 @@ master too old to run it starts it beside itself, still in its own process (`src
The core retains its reported list for stale replies during a restart, bound to the current account.
The Store prepares bundled harnesses before reporting `prepared`; package agents wait held until
preparation is available, after the core reports ready. The lean bundle shares one asset file, loaded by the Store and never by the core.
-- A service that writes turns into agents (a team's question, the orchestrator's guidance) delivers each
- under an id of its own through `core.turns.deliver`, hears what became of it through `onDelivery`, and
+- A service that writes turns into agents (Agent Messages' typed messages, the orchestrator's guidance) delivers
+ each under an id of its own through `core.turns.deliver`, hears what became of it through `onDelivery`, and
takes one back with `cancelDelivery` (core/deliveries.ts). In its own process `services/turnsLink.ts`
asks the core over its link, in order, and hears only its own deliveries; the core lets a process deliver
- only when it is an experiment (below).
+ only when `TURN_DELIVERERS` (`src/core/api.ts`) names it: the experiments (below) and Agent Messages.
+- A service that graduates from an experiment keeps the same questions to the core and is answered by a link of its
+ own, for what it uses alone, never by the experiments' hooks: Agent Messages in the edge host
+ (`src/core/messagesLink.ts`, `MESSAGES_QUERIES` in `src/core/api.ts`) is shown the agents, told how this daemon is
+ reached and whether it is signed in, reads the account's tabs and nothing else of the backend, sends the windows
+ its log's change notice and nothing else, and hears `desk_changed`. It never creates an agent, stops a turn or
+ watches a terminal. Off on this computer, or signed out, it runs no timer: a Settings ▸ Agents write through the
+ daemon wakes it (`MessagesPort.settingsChanged`), so does `harness settings` through a watch on the setting's file
+ when there is one (`src/messages/settingWatch.ts`), and so does a core it reconnects to signed in.
- A service that drives hardware: the devices (src/services/devicesProcess.ts, src/core/devicesLink.ts).
The dial reads a dozen facts in line while it builds each frame, so the process keeps a copy of what it
reads (this computer's agents, its name, the sign-in, whether a window is there), asked of the core as
@@ -184,9 +191,10 @@ like any other. Named in `HARNESSD_SERVICES`, it starts with the others.
- **What asks.** A request for a service that has not connected yet (`serviceLinks` `onDemand`, in
`src/core/main.ts`) asks for it and waits for it, within the request's own wait. The service is welcomed
- before its queued requests are delivered. Each experiment with saved state in the data folder, or with its
- Settings ▸ Agents switch on (Agent Messages, on by default), is asked for as the core starts, and when a
- Settings ▸ Agents write leaves that switch on (`src/core/experiments.ts`). The devices are asked for once there is a device:
+ before its queued requests are delivered. Each experiment with saved state in the data folder is asked for as the
+ core starts (`src/core/experiments.ts`). So is Agent Messages, which starts nothing under this build's master (it is
+ in the edge host) and starts its own process under a master from before it moved there (`src/core/messagesLink.ts`).
+ The devices are asked for once there is a device:
a dial's port in /dev, a paired Wi-Fi device, or its session (`src/core/devicesWake.ts`). Models is asked
for as the core starts when grid is in use here: a managed grid, whose pin it follows, saved grid pictures,
which agents' grid notes are read from, or local models (`src/core/modelsWake.ts`); otherwise its first
@@ -214,12 +222,14 @@ like any other. Named in `HARNESSD_SERVICES`, it starts with the others.
## Experiments
-An experiment (the orchestrator, Agent Messages, Share, memory, the router) is a service that costs nothing until it is
-on: its own process, which the master starts only when the core asks for it (`want`), when one of
-its requests arrives or, as the core starts, when its saved state is in the data folder or its Settings ▸ Agents
-switch is on (Agent Messages, on by default since 2026-10-12, so its agents get its note). Off, nothing of it runs or
-is loaded anywhere; one failing costs its own process and nothing else. `e2e/experiments.e2e.ts` proves it:
-off, on by request, on by saved state, killed, hung and crashing on every start.
+An experiment (the orchestrator, Share, memory, the router) is a service that costs nothing until it is on: its own
+process, which the master starts only when the core asks for it (`want`), when one of its requests arrives or, as the
+core starts, when its saved state is in the data folder. Off, nothing of it runs or is loaded anywhere; one failing
+costs its own process and nothing else. `e2e/experiments.e2e.ts` proves it: off, on by request, on by saved state,
+killed, hung and crashing on every start.
+
+Agent Messages was one until 2026-10-12: a process of its own on every computer it was on, 62 MiB resident at idle for
+a few MiB of messaging. It is a service in the edge host now (above), off costing nothing there.
To add one:
@@ -232,8 +242,7 @@ To add one:
also reads the backend as the account (`core.account.backend`) and has its welcomes signed by the gateway
(`core.account.observerKey`), so it holds no credential, and watches terminals read-only
(`core.terminals.watch`, `services/watchLink.ts`).
-2. Its entry in `EXPERIMENTS` (`src/core/api.ts`): its requests, its saved state, and its Settings ▸ Agents
- `setting` if the person turns it on and off there (`src/lib/agentSettings.ts`).
+2. Its entry in `EXPERIMENTS` (`src/core/api.ts`): its requests and its saved state.
3. Its process in `SERVICE_HOSTS` (`src/harnessd/services.ts`) with `onDemand: true`, and its runner in
`SERVICE_RUNNERS` (`src/serviceProcess.ts`).
4. Its start for the core's own process, in `services/inline.ts`, and one line in `core/main.ts` that starts
@@ -245,6 +254,12 @@ from what the process last reported (`src/core/orchestratorLink.ts`), as the vie
the core asks as it writes it, is reported for a few seconds at a time, so a process that stops reporting
leaves none writable (`messagesProcess.ts`, `core/messagesLink.ts`).
+Graduating one to a service is moving it into a host that is always running (`SERVICE_HOSTS`), taking it out of
+`EXPERIMENTS` and answering what it asks with a link of its own, as Agent Messages did. Where it runs is the master's
+to say, by service name (`serviceProcessesEnv`), so a core of either build routes it to the one process that runs it
+and runs none of it itself; the new core still asks for it as it starts, which starts its old process under a master
+from before (`src/harnessd/services.spec.ts`, `e2e/messagesSkew.e2e.ts`).
+
## Do not
- Do not keep state the core needs. If the core would break without your data, it is not a service.
diff --git a/cli/src/services/messages.spec.ts b/cli/src/services/messages.spec.ts
index e12aa628c..aa8ede481 100644
--- a/cli/src/services/messages.spec.ts
+++ b/cli/src/services/messages.spec.ts
@@ -16,6 +16,7 @@ vi.mock('../messages/service.js', () => ({
return {
requests: { agent_messages: async () => ({ ok: true }) },
canWrite: (id: string) => id === 'team:msg:yes',
+ settingsChanged: () => made.calls.push('settings'),
start: () => made.calls.push('start'),
stop: () => made.calls.push('stop'),
}
@@ -42,8 +43,9 @@ describe('Agent Messages in the core\'s process', () => {
expect(await requests.agent_messages!({ action: 'history' }, { local: true, owner: true })).toEqual({ ok: true })
expect(ports.messages!.canWrite('team:msg:yes')).toBe(true)
expect(ports.messages!.canWrite('team:msg:no')).toBe(false)
+ ports.messages!.settingsChanged()
;(ports.messages as unknown as { stop(): void }).stop()
- expect(made.calls).toEqual(['start', 'stop'])
+ expect(made.calls).toEqual(['start', 'settings', 'stop'])
startMessagesInCore(fakeCore({ dataDir: dir }), emptyPorts(), { dataDir: dir })
expect(made.options.at(-1)).toEqual({ dataDir: dir })
})
diff --git a/cli/src/services/messages.ts b/cli/src/services/messages.ts
index 26823a17f..64a6213ce 100644
--- a/cli/src/services/messages.ts
+++ b/cli/src/services/messages.ts
@@ -1,11 +1,11 @@
/**
- * Agent Messages (`messages`), an experiment: harnesses in one tab message each other with `harness send`, while
- * Settings ▸ Agents has it on, the default (messages/service.ts, docs/design/2026-10-10-agent-messages.md). Its typed deliveries go
- * through `core.turns.deliver` under `team:` ids, which the core writes only into an idle, empty composer, and
- * the core asks in line whether one may still be written (`canWrite`).
+ * Agent Messages (`messages`), a service in the edge host: harnesses in one tab message each other with `harness
+ * send`, while Settings ▸ Agents has it on (messages/service.ts, docs/design/2026-10-10-agent-messages.md).
+ * Its typed deliveries go through `core.turns.deliver` under `team:` ids, which the core writes only into an idle,
+ * empty composer, and the core asks in line whether one may still be written (`canWrite`).
* - The `agent_messages` request: `harness send` in an agent's pane, the owner's other machines, the windows.
- * - In the core's process (`HARNESSD_SERVICES=none`) it starts here, at once; in its own process,
- * services/messagesProcess.ts starts the same service.
+ * - In the core's process (`HARNESSD_SERVICES=none`, or a subset without it) it starts here, at once; out of it,
+ * services/messagesProcess.ts starts the same service in the edge host.
*/
import type { CoreApi, CorePorts, ServiceRequests } from '../core/api.js'
import { startAgentMessages, type MessagesOptions } from '../messages/service.js'
@@ -16,7 +16,7 @@ export { MESSAGES_REQUESTS } from '../core/api.js'
/** Agent Messages in the core's process (`HARNESSD_SERVICES=none`): its port is whether a delivery may be written. */
export function startMessagesInCore(core: CoreApi, ports: CorePorts, options: MessagesOptions = {}): ServiceRequests {
const messages = startAgentMessages(core, options)
- ports.messages = Object.assign({ canWrite: (deliveryId: string) => messages.canWrite(deliveryId) }, { stop: () => messages.stop() })
+ ports.messages = Object.assign({ canWrite: (deliveryId: string) => messages.canWrite(deliveryId), settingsChanged: () => messages.settingsChanged() }, { stop: () => messages.stop() })
messages.start()
return messages.requests
}
diff --git a/cli/src/services/messagesProcess.spec.ts b/cli/src/services/messagesProcess.spec.ts
index b42eb093a..37916d80c 100644
--- a/cli/src/services/messagesProcess.spec.ts
+++ b/cli/src/services/messagesProcess.spec.ts
@@ -38,6 +38,7 @@ describe('Agent Messages in its own process', () => {
agent_messages: async (payload) => ({ action: payload.action, agents: core.agents.live().map((a) => a.agentId), command: core.daemon.command }),
},
canWrite: (id) => writable.has(id),
+ settingsChanged: () => calls.push('settings'),
start: () => calls.push('start'),
stop: () => calls.push('stop'),
} satisfies AgentMessages
@@ -96,6 +97,32 @@ describe('Agent Messages in its own process', () => {
expect(calls).toEqual([])
})
+ it('says whether this daemon is signed in as each core says it; a core from before says nothing, and the last word stands', async () => {
+ // Signed out, the service runs nothing (messages/service.ts); a core from before 2026-10-12 never said, and the
+ // service ran then as it does signed in.
+ const { options, api } = setup()
+ expect(api().account.signedIn()).toBe(true)
+ options.onConnected!(core({ daemon: { command: 'x', port: 1, machineId: 'm', signedIn: false } }).connection)
+ await flush()
+ expect(api().account.signedIn()).toBe(false)
+ options.onConnected!(core({ daemon: { command: 'x', port: 1, machineId: 'm', signedIn: true } }).connection)
+ await flush()
+ expect(api().account.signedIn()).toBe(true)
+ options.onConnected!(core({ daemon: { command: 'x', port: 1, machineId: 'm' } }).connection)
+ await flush()
+ expect(api().account.signedIn()).toBe(true)
+ })
+
+ it('passes on a Settings ▸ Agents write once its service runs, and before then has nothing to tell', async () => {
+ const { options, calls } = setup()
+ options.onEvent!({ kind: 'settings' })
+ expect(calls).toEqual([])
+ options.onConnected!(core({ daemon: { command: 'x', port: 1, machineId: 'm' } }).connection)
+ await flush()
+ options.onEvent!({ kind: 'settings' })
+ expect(calls).toEqual(['start', 'settings'])
+ })
+
it('gives the service its data folder, and hears from it when what may be written changed', async () => {
const { options, given, writable } = setup()
const link = core()
@@ -219,7 +246,7 @@ describe('Agent Messages in its own process', () => {
dataDir: '/data', socketPath: '/s', machineId: 'm', token: 't',
start: (given) => {
api = given
- return { requests: { agent_messages: async () => ({}) }, canWrite: (id) => writable.has(id), start: () => {}, stop: () => {} }
+ return { requests: { agent_messages: async () => ({}) }, canWrite: (id) => writable.has(id), settingsChanged: () => {}, start: () => {}, stop: () => {} }
},
})
const options = vi.mocked(runServiceProcess).mock.calls.at(-1)![0]
diff --git a/cli/src/services/messagesProcess.ts b/cli/src/services/messagesProcess.ts
index abc0ddcb2..992810074 100644
--- a/cli/src/services/messagesProcess.ts
+++ b/cli/src/services/messagesProcess.ts
@@ -1,14 +1,19 @@
/**
- * Agent Messages in its own process (`harness __service messages`): an experiment, started only once it is on
- * (core/api.ts `EXPERIMENTS`). The same service as in the core's process (services/messages.ts,
- * messages/service.ts), on the core's API as a process reaches it (services/processCoreApi.ts), and what a mailbox
- * in another process needs besides:
+ * Agent Messages out of the core's process: in the edge host (`harness __service …,messages`, harnessd/services.ts),
+ * or, under a master from before 2026-10-12, in a process of its own (`harness __service messages`) that the core
+ * asks for as it starts. The same service as in the core's process (services/messages.ts, messages/service.ts), on
+ * the core's API as a process reaches it (services/processCoreApi.ts), asking only what core/messagesLink.ts answers
+ * it, and what a mailbox in another process needs besides:
* - The core asks in line, as it writes a typed delivery, whether it may still be written. This process tells the
* core which may (`writable`), before each is handed over and whenever that can change, each for a few seconds
* at a time: a process that stops telling, hung or gone, leaves none writable, and a delivery waits rather than
* being written against its mailbox's word.
* - The agents it reads as the apps are shown them, asked again as each request starts and whenever its
* mailbox reads them and they are a second old.
+ * - Whether this daemon is signed in, as the core says it with its address: signed out, the service runs nothing.
+ * A core from before says nothing of it, and is taken as signed in, as the service took every core then.
+ * - That Settings ▸ Agents was written through the daemon (`service_event` kind `settings`), which a core from before
+ * never says: off, the service then hears it only from the setting's file.
*/
import type { BackendNotice, DaemonAddress } from '../core/api.js'
import { startAgentMessages } from '../messages/service.js'
@@ -49,6 +54,7 @@ export function runMessagesService(options: MessagesServiceOptions): ServiceProc
let live: ShownAgent[] = []
let readAt = -Infinity
let daemon: DaemonAddress | null = null
+ let signedIn = true
let reading: Promise<void> | null = null
const ask = (query: string, payload: Payload): Promise<Payload> =>
core ? core.query(query, payload) : Promise.reject(new Error('not connected to the core'))
@@ -66,7 +72,9 @@ export function runMessagesService(options: MessagesServiceOptions): ServiceProc
await readAgents()
if (daemon && askedOn === core) return
const on = core
- daemon = daemonIn(await ask('daemon', {}).catch(() => null)) ?? daemon
+ const answer = await ask('daemon', {}).catch(() => null)
+ daemon = daemonIn(answer) ?? daemon
+ if (typeof answer?.signedIn === 'boolean') signedIn = answer.signedIn
askedOn = on
}
@@ -84,6 +92,7 @@ export function runMessagesService(options: MessagesServiceOptions): ServiceProc
})
const api = {
...base,
+ account: { ...base.account, signedIn: () => signedIn },
turns: {
...base.turns,
deliver: (agentId: string, text: string, deliveryId: string) => {
@@ -147,6 +156,8 @@ export function runMessagesService(options: MessagesServiceOptions): ServiceProc
},
onEvent: (payload) => {
if (deliveries.heard(payload)) { tell(); return }
+ // Settings ▸ Agents written through the daemon: the running service reads its switch again.
+ if (payload.kind === 'settings') { if (started) messages.settingsChanged(); return }
// Heard once the service runs for a known machine: the tabs it would read are that machine's.
if (started && payload.kind === 'notice' && payload.notice && typeof payload.notice === 'object') {
for (const listener of noticeListeners) listener(payload.notice as BackendNotice)
@@ -157,7 +168,7 @@ export function runMessagesService(options: MessagesServiceOptions): ServiceProc
told = ''
// Its queues resume once it knows the agents and the daemon, and the core hears what may be written.
void ready().then(() => {
- // A core that restarted holds none of the typed attempts handed to the last one.
+ // A core that restarted holds none of the typed attempts handed to the last one, and may be signed in or out.
current().reconnected?.()
tell()
})
diff --git a/docs/design/2026-10-03-harnessd.md b/docs/design/2026-10-03-harnessd.md
index 5fce47d89..119f0b6da 100644
--- a/docs/design/2026-10-03-harnessd.md
+++ b/docs/design/2026-10-03-harnessd.md
@@ -150,7 +150,7 @@ models — get their own processes, and the light ones share one host.
| Grid access, local models, fleet RPC, API connections | models |
| Session search, external sessions, open sessions | search |
| Harness viewers, verdict watcher, Store installs, interactive and shared viewers (headless Chrome) | viewers |
-| Tab channels, team service and mailbox, orchestrator | teams |
+| Tab channels, team service and mailbox, orchestrator | teams; since replaced by Agent Messages, a service in the edge host (2026-10-12), and the orchestrator, an experiment in a process of its own |
| Token and account usage, machine resources | light host |
| The worktree sweep (deletes idle worktrees on a timer) | removed: cleanup becomes an app action ([#711](https://github.com/autonomous-ai/openharness/issues/711)) |
| Companion, Memory | their own services, off until used |
diff --git a/docs/design/2026-10-10-agent-messages.md b/docs/design/2026-10-10-agent-messages.md
index 3024eace9..629f80ed0 100644
--- a/docs/design/2026-10-10-agent-messages.md
+++ b/docs/design/2026-10-10-agent-messages.md
@@ -168,18 +168,52 @@ while the send was under way.
## How it works
-Agent Messages is the `messages` experiment, in a process of its own (`messages`). Its contract with the core is
-the one Swarm's had: `core.turns.deliver` under `team:` delivery ids, and `MessagesPort.canWrite`, asked in line
-as one is written. Its process starts with the core while the setting is on (`EXPERIMENTS.messages.setting`,
-core/experiments.ts), and when Settings ▸ Agents leaves it on through the daemon (`PATCH /api/agent-settings`): on
-one machine nothing else would start it, and its agents would never get the note or hear of `harness send` (a
-fresh Mac, 2026-10-12). That is the price of on by default: one more process at idle on every computer, signed in
-or not (61 MiB resident after 20 idle seconds, from the release bundle on a Mac, beside search's 78; 2026-10-12).
-Off, it costs nothing until its first request or its saved state (`agent-messages/`) starts it; another machine's
-window starts it with its first request for the tab's log. `harness settings` writes the file without the daemon:
-a running service reads it within 2 seconds, and one that is not running starts at its next request or the next
-start. (It began as Swarm's `collaboration` experiment in the `teams` process, rewritten in place; both were
-renamed when Swarm's last code went.)
+Agent Messages is the `messages` service, in the edge host (`SERVICE_HOSTS` in cli/src/harnessd/services.ts), beside
+workspaces, usage, the monitor and the other light services. Its contract with the core is the one Swarm's had:
+`core.turns.deliver` under `team:` delivery ids, and `MessagesPort.canWrite`, asked in line as one is written. Out of
+the core's process it asks the core for what it uses and nothing more (core/messagesLink.ts, `MESSAGES_QUERIES`): the
+agents as the apps are shown them, how this daemon is reached and whether it is signed in, the account's tabs (one
+GET), and its log's change notice for the windows; and it may write turns into agents (`TURN_DELIVERERS`).
+
+It was the `messages` experiment, in a process of its own, until October 12. That process ran on every computer that
+had it on, signed in or not: 61 MiB resident after 20 idle seconds, from the release bundle on a Mac, nearly all of it a
+second Node and the bundle rather than messaging. The owner agreed to move it into the edge host, which always runs.
+
+Measured from the bundle, signed in, with a Claude Code and a Codex agent in one tab, 30 idle seconds after a warm-up
+(`cli/e2e/footprint.e2e.ts`, one Mac, 2026-10-12; runs of one build differ by about 3 MiB), every process of the daemon:
+
+| Agent Messages | before (3cff043360) | in the edge host | the tabs read in 30 s |
+|---|---|---|---|
+| on, active (both agents have their note) | 683 MiB | 614 MiB | 2, both builds |
+| off | 600 MiB | 599 MiB | 0, both builds |
+| never written (on by that day's default) | 679 MiB | 611 MiB | 2, both builds |
+
+On, it costs 69 MiB less: the messages process's 62 MiB is gone, the edge host holds it for 1 MiB more (73 MiB), and the
+master is 4 to 8 MiB smaller, which this measurement does not explain (it was 81 MiB with the experiment off as well).
+Off, it costs what no process costs: the edge host is 0.4 MiB larger for its code, and nothing reads the tabs. On costs
+the gateway 15 MiB too (72 to 87 MiB), for the account requests the tabs are read through.
+
+Off costs nothing there. Only while this computer is signed in and has Agent Messages on does it read the tabs (every
+15 s), look at its deliveries (every 2 s) and at its notes, its outbox and other machines' deliveries (every 5 s).
+Turned off, it takes the notes back, holds what waits for this computer's agents out of the hook's reach and fails it
+after 5 minutes, as before, and then runs no timer at all; what this computer sent that still waits for another
+machine is handed over once it is on again. It hears the switch turned on two ways. Settings ▸ Agents writes it
+through the daemon, which tells the service (`MessagesPort.settingsChanged`). `harness settings` writes the file
+(`agent-settings.json`) on its own, and a watch on that one file hears it, never on the data folder, whose log and
+indexes are written many times a second (messages/settingWatch.ts). A file that was never written is not watched, nor
+polled for: the first `harness settings` that writes it is heard at the service's next request (`harness send`) or
+the core's next start. Signed
+out, it runs nothing either: there is no account to read tabs from, and signing in starts a new core, which it
+reconnects to and wakes for. Its requests are answered on or off. With `HARNESSD_SERVICES=none` it runs in the core's
+process, and named alone (`HARNESSD_SERVICES=messages`) in an edge host of its own. (It began as Swarm's
+`collaboration` experiment in the `teams` process, rewritten in place; both were renamed when Swarm's last code
+went.)
+
+A core and a master of different builds still carry each message once. Where it runs is the master's to say, by
+service name (`serviceProcessesEnv`), so a core of either build routes it to the one process that runs it and runs
+none of it itself; the questions it asks the core are the experiment's, so either core answers either process. This
+build's core asks for it as it starts, which starts its own process under a master from before (a master that could
+not re-execute on the update) and nothing under this build's (`cli/e2e/messagesSkew.e2e.ts`).
### Identity
@@ -192,10 +226,11 @@ already type into any pane.
### Who may message whom
`GET /api/agent-messages` answers the account's tabs, each with its owned panes (`machineId`, `agentId`), and the
-machines' names. The service reads it as Swarm did: polled every 15 s, read again on the account's
-`desk_changed`, and fresh before each send. It reads this computer's setting from the data folder at most every
-2 seconds; a change counts as a change of the directory at its next read, and the notes and waiting deliveries
-heed it at their next look.
+machines' names. The service reads it as Swarm did, while it is on and signed in: polled every 15 s, read again on the
+account's `desk_changed`, and fresh before each send. It reads this computer's setting from the data folder at most
+every 2 seconds while it runs, and through the file's watch while it is off; a change counts as a change of the
+directory at its next read, and the notes and waiting deliveries heed it at their next look. Off, no tab carries a
+message, so what waits is held, and a hand-over from another machine fails, without reading the tabs.
The backend still keeps one record per tab, `agent_message_tabs` (`{userId, tabId, enabled}`), answers each
tab's flag beside its panes, and sets it at `PATCH /api/agent-messages/tabs/:tabId`, for older windows that draw
@@ -281,17 +316,22 @@ Experimental → Swarm collaboration, the Swarm conversation views on desktop an
by default, and no tab's flag; the desktop drops the tab's 💬 and its **Agent Messages** menu item, keeps
**Show Agent Messages**, and shows the switch in Settings ▸ Agents. The backend's per-tab records stay, unread,
for older windows.
+5. Into the edge host (2026-10-12): no process of its own, and off or signed out it runs nothing (How it works).
## Verification
-- Unit: the service, directory, store, mailbox and both delivery routes (`messages/*.spec.ts`); which experiments
- start with the core, by saved state or setting, at 100% (`npm run test:core`); the hook script; the backend routes.
-- End to end on the real daemon with the fake engines (`e2e/agentMessages.e2e.ts`): on by default, a fresh daemon
- starts it with no request and gives two agents in one tab their note; turned off, no process until used, or until
- Settings ▸ Agents turns it on (an older window's tab switch starts nothing); on by saved state; `send` from a pane
- through a signed-in daemon whose directory the fake backend answers; an idle recipient gets a typed prompt;
- working Claude Code and Codex agents get the hook's context at the next tool call with nothing typed; turned off
- in Settings ▸ Agents, it refuses; a hand-over from a process on this machine is refused.
+- Unit: the service, directory, store, mailbox and both delivery routes (`messages/*.spec.ts`), off and signed out
+ running nothing (`messages/service.spec.ts`, "off costs nothing"), the setting's watch (`settingWatch.spec.ts`);
+ what the core answers it and the ask at start, at 100% (`core/messagesLink.spec.ts`, `npm run test:core`); where the
+ master runs it under either build (`harnessd/services.spec.ts`); the hook script; the backend routes.
+- End to end on the real daemon with the fake engines (`e2e/agentMessages.e2e.ts`): in the edge host with no process
+ of its own; on, a fresh daemon reads the tabs with no request and gives two agents in one tab their note; turned
+ off, it never reads them, and wakes when Settings ▸ Agents turns it on or `harness settings` writes the file (an older window's tab switch wakes nothing); `send` from a pane through a signed-in daemon whose directory the
+ fake backend answers; an idle recipient gets a typed prompt, from the edge host, from the core's process and from an
+ edge host of its own; working Claude Code and Codex agents get the hook's context at the next tool call with nothing
+ typed; turned off in Settings ▸ Agents, it refuses; a hand-over from a process on this machine is refused.
+- A core and a master of different builds (`e2e/messagesSkew.e2e.ts`, opt-in with a build from before): each message
+ typed once, under either.
- In unit tests (`messages/*.spec.ts`): drafts, dialogs and refusals that may have typed; parking; restarts and a
new core giving attempts back; a moved, stopped or restarted harness; the hand-over to another machine and its
status over a fake relay. Not yet end to end: two daemons over the real relay.