Skip to content

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

harnessd: workspaces can run in their own process (#782)

Deee209e40f048a
diff --git a/cli/e2e/workspacesProcess.e2e.ts b/cli/e2e/workspacesProcess.e2e.ts
new file mode 100644
index 000000000..ff5dca720
--- /dev/null
+++ b/cli/e2e/workspacesProcess.e2e.ts
@@ -0,0 +1,236 @@
+/**
+ * Workspaces in their own process, on the real daemon (`HARNESSD_SERVICES=workspaces`, here also with
+ * search and the viewers): the branch Harness made up for a worktree takes its session's name, renamed by the workspaces
+ * process and shown on the agent's frame by the core; and the worktree sweep runs there, when the core's
+ * timer says. Whatever happens to the process costs workspaces alone. Stopped, hung, killed or crashing on
+ * every start, the core never restarts, agents keep working, and frames keep their branch names, which
+ * the core reads itself. A sweep the core decides while the process is down is skipped and never run
+ * later. A core that restarts leaves the process running.
+ */
+import { execFileSync } from 'node:child_process'
+import { existsSync, mkdirSync, utimesSync, writeFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { afterEach, describe, expect, it, onTestFailed } from 'vitest'
+import { LocalClient, type Frame } from './harness/client.js'
+import { IsolatedDaemon, until } from './harness/daemon.js'
+
+/** Git as the test runs it: the daemon's throwaway home, never this machine's configuration. */
+const git = (d: IsolatedDaemon, cwd: string, ...args: string[]): string =>
+ execFileSync('git', ['-C', cwd, ...args], { env: { ...process.env, HOME: d.env.HOME, GIT_CONFIG_NOSYSTEM: '1' }, encoding: 'utf8' }).trim()
+
+/** A repository with one commit, in the daemon's projects folder. */
+function repository(d: IsolatedDaemon): string {
+ const dir = join(d.projectsDir, 'repo')
+ mkdirSync(dir, { recursive: true })
+ git(d, dir, 'init', '-q', '-b', 'main')
+ writeFileSync(join(dir, 'README.md'), 'a repository\n')
+ git(d, dir, 'add', 'README.md')
+ git(d, dir, '-c', 'user.name=e2e', '-c', '[email protected]', 'commit', '-q', '-m', 'start')
+ return dir
+}
+/** A worktree where Harness keeps them (`~/harnesses/worktrees/<repo>/<name>`), on its own branch;
+ * `placeholder` marks the branch as the made-up name Harness gives one at Start. */
+function worktree(d: IsolatedDaemon, repo: string, name: string, placeholder = false): string {
+ const path = join(d.env.HOME!, 'harnesses', 'worktrees', 'repo', name)
+ git(d, repo, 'worktree', 'add', '-q', '-b', name, path)
+ if (placeholder) git(d, repo, 'config', `branch.${name}.harness`, 'placeholder')
+ return path
+}
+/** Nothing in it changed for eight days: past the sweep's week. */
+function idle(d: IsolatedDaemon, path: string): void {
+ const gitDir = git(d, path, 'rev-parse', '--absolute-git-dir')
+ const then = new Date(Date.now() - 8 * 24 * 3600_000)
+ for (const file of [path, join(gitDir, 'HEAD'), join(gitDir, 'index'), join(gitDir, 'logs', 'HEAD')]) {
+ if (existsSync(file)) utimesSync(file, then, then)
+ }
+}
+
+/** The workspaces process the master runs now: the last one it said it started. Read from its log,
+ * never from the process table, where another daemon's services could be. */
+const workspacesPid = (d: IsolatedDaemon): number | null => {
+ const started = [...d.log().matchAll(/\[harnessd\] service workspaces started \(pid (\d+)\)/g)]
+ return started.length ? Number(started[started.length - 1][1]) : null
+}
+const restarts = (d: IsolatedDaemon) => [...d.log().matchAll(/\[harnessd\] service workspaces started .* restart \d+/g)].length
+const ready = (d: IsolatedDaemon) => [...d.log().matchAll(/\[cli\] ready/g)].length
+const connected = (d: IsolatedDaemon) => d.log().split('[services] workspaces connected').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)
+async function create(d: IsolatedDaemon, client: LocalClient, cwd: string, engine = 'claude'): Promise<Record<string, any>> {
+ mkdirSync(cwd, { recursive: true })
+ const created = await client.request('agent_create', { engine, cwd, bypassPermission: true }, 90_000)
+ expect(created.error, `${cwd}: ${JSON.stringify(created)}`).toBeUndefined()
+ return until(`${cwd} to bind its conversation`, async () => {
+ const agent = await row(client, created.agent.id)
+ return agent?.sessionId && agent.status === 'active' && agent.tmuxPane ? agent : null
+ }, 60_000, 500)
+}
+async function turn(client: LocalClient, agentId: string, content: string): Promise<void> {
+ const ended = client.next((frame: Frame) => frame.type === 'turn_ended' && frame.agentId === agentId, 45_000, `turn_ended (${content})`)
+ client.send('message', { agentId, content })
+ await ended
+}
+/** The agent's session gets a name: its terminal's title, as Claude Code sets it. */
+const name = (d: IsolatedDaemon, agent: Record<string, any>, title: string) => d.tmux.run('select-pane', '-t', agent.tmuxPane, '-T', title)
+const branchOf = async (client: LocalClient, agentId: string) => (await row(client, agentId))?.project?.branch ?? null
+/** The agent's branch is `login` on its frame, pushed to the window, and in git. */
+async function named(d: IsolatedDaemon, client: LocalClient, agent: Record<string, any>, cwd: string): Promise<void> {
+ await client.waitFor((frame) => frame.type === 'agent_synced' && frame.payload?.agent?.id === agent.id && frame.payload.agent.project?.branch === 'login',
+ 45_000, 'the agent\'s frame with its branch named after its session')
+ expect(await branchOf(client, agent.id)).toBe('login')
+ expect(git(d, cwd, 'symbolic-ref', '--short', 'HEAD')).toBe('login')
+}
+
+describe('workspaces in their own process', () => {
+ let daemon: IsolatedDaemon | undefined
+ afterEach(async () => { await daemon?.close(); daemon = undefined })
+ const fresh = async (env: Record<string, string> = {}, prepare: (d: IsolatedDaemon) => void = () => {}) => {
+ const d = await IsolatedDaemon.create({ env: {
+ HARNESSD_SERVICES: 'workspaces',
+ HARNESSD_SERVICE_INITIAL_BACKOFF_MS: '200',
+ HARNESSD_SERVICE_MAX_BACKOFF_MS: '1000',
+ ...env,
+ } })
+ daemon = d
+ prepare(d)
+ onTestFailed(() => { console.log(`---- daemon log\n${d.log().split('\n').slice(-150).join('\n')}`) })
+ await d.start()
+ await until('workspaces to connect to the core', () => connected(d) >= 1 || null, 30_000, 100)
+ return d
+ }
+
+ it('the made-up branch takes the session\'s name in the workspaces process, never in the core, and reaches the frame; search and the viewers run beside it', async () => {
+ const d = await fresh({ HARNESSD_SERVICES: 'search,viewers,workspaces' })
+ for (const service of ['search', 'viewers']) {
+ await until(`${service} to connect to the core`, () => d.log().includes(`[services] ${service} connected`) || null, 30_000, 200)
+ }
+ const client = await LocalClient.connect(d)
+ const cwd = worktree(d, repository(d), 'brave-otter', true)
+ const agent = await create(d, client, cwd)
+ expect((await row(client, agent.id))?.project).toMatchObject({ branch: 'brave-otter', branchPending: true, worktree: true })
+ // Stopped: the core neither renames the branch nor stops building frames that show it.
+ const pid = workspacesPid(d)!
+ process.kill(pid, 'SIGSTOP')
+ try {
+ await name(d, agent, 'Fix the login page')
+ await turn(client, agent.id, 'while workspaces is stopped')
+ await new Promise((done) => setTimeout(done, 11_000))
+ expect(await branchOf(client, agent.id)).toBe('brave-otter')
+ } finally {
+ process.kill(pid, 'SIGCONT')
+ }
+ await named(d, client, agent, cwd)
+ expect((await client.request('session_search', { query: 'login' }, 30_000)).error).toBeUndefined()
+ expect(restarts(d)).toBe(0)
+ expect(d.coresStarted()).toBe(1)
+ client.close()
+ })
+
+ it('hung, it is killed at the heartbeat watch and started again; the core goes on, and the new process names the branch', async () => {
+ const d = await fresh({ HARNESSD_SERVICE_HEARTBEAT_TIMEOUT_MS: '2000' })
+ const client = await LocalClient.connect(d)
+ const cwd = worktree(d, repository(d), 'brave-otter', true)
+ const agent = await create(d, client, cwd)
+ const first = workspacesPid(d)!
+ process.kill(first, 'SIGSTOP')
+ await until('the master to find workspaces hung', () => d.log().includes('[harnessd] service workspaces sent no heartbeat') || null, 30_000, 200)
+ await until('workspaces to be started again', () => restarts(d) >= 1 || null, 30_000, 200)
+ expect(workspacesPid(d)).not.toBe(first)
+ await turn(client, agent.id, 'the core never waited on workspaces')
+ expect(await branchOf(client, agent.id)).toBe('brave-otter')
+ await name(d, agent, 'Fix the login page')
+ await named(d, client, agent, cwd)
+ expect(d.coresStarted()).toBe(1)
+ client.close()
+ })
+
+ it('killed outright, it is brought back; a sweep the core decides meanwhile is skipped and never run later', async () => {
+ let repo = ''
+ let unused = ''
+ let cwd = ''
+ const d = await fresh({ HARNESSD_TEST_SWEEP_AFTER_MS: '10000', HARNESSD_SERVICE_INITIAL_BACKOFF_MS: '15000' }, (d) => {
+ repo = repository(d)
+ unused = worktree(d, repo, 'old-idea')
+ idle(d, unused)
+ cwd = worktree(d, repo, 'brave-otter', true)
+ })
+ await until('the core to be ready', () => ready(d) >= 1 || null, 30_000, 100)
+ const first = workspacesPid(d)!
+ process.kill(first, 'SIGKILL')
+ const client = await LocalClient.connect(d)
+ const agent = await create(d, client, cwd)
+ await turn(client, agent.id, 'while workspaces was gone')
+ await until('the core to skip the sweep it decided while workspaces was down',
+ () => d.log().includes('[worktrees] sweep skipped: the workspaces process is not running') || null, 30_000, 200)
+ await until('workspaces to be back', () => restarts(d) >= 1 && connected(d) >= 2 || null, 60_000, 200)
+ await name(d, agent, 'Fix the login page')
+ await named(d, client, agent, cwd)
+ // Back, it never ran the sweep it missed: the idle worktree nothing uses is still there.
+ expect(existsSync(unused)).toBe(true)
+ expect(d.log()).not.toContain('[worktrees] removed')
+ expect(d.coresStarted()).toBe(1)
+ client.close()
+ })
+
+ it('crashing on every start, it is parked; agents work, and their frames keep their branches', async () => {
+ const d = await IsolatedDaemon.create({ env: {
+ HARNESSD_SERVICES: 'workspaces', HARNESSD_TEST_FAULTS: 'workspaces.crash', HARNESSD_SERVICE_PARK_CRASHES: '3',
+ HARNESSD_SERVICE_INITIAL_BACKOFF_MS: '200', HARNESSD_SERVICE_MAX_BACKOFF_MS: '1000',
+ } })
+ daemon = d
+ onTestFailed(() => { console.log(`---- daemon log\n${d.log().split('\n').slice(-150).join('\n')}`) })
+ await d.start()
+ const client = await LocalClient.connect(d)
+ const cwd = worktree(d, repository(d), 'brave-otter', true)
+ const agent = await create(d, client, cwd)
+ await until('the master to park workspaces', () => d.log().includes('[harnessd] service workspaces ended 3 times') || null, 60_000, 250)
+ await turn(client, agent.id, 'workspaces is parked and nothing else cares')
+ expect(await branchOf(client, agent.id)).toBe('brave-otter')
+ expect(d.coresStarted()).toBe(1)
+ client.close()
+ })
+
+ it('a core that restarts leaves the workspaces process running: it names the branch for the new core', async () => {
+ const d = await fresh()
+ let client = await LocalClient.connect(d)
+ const cwd = worktree(d, repository(d), 'brave-otter', true)
+ const agent = await create(d, client, cwd)
+ const workspaces = workspacesPid(d)
+ const wired = ready(d)
+ process.kill(d.corePid()!, 'SIGKILL')
+ await until('a new core to finish starting', () => ready(d) > wired || null, 60_000, 200)
+ await until('workspaces to reach the new core', () => connected(d) >= 2 || null, 30_000, 200)
+ client.close()
+ client = await LocalClient.connect(d)
+ await until('the agent to be live again', async () => (await row(client, agent.id))?.status === 'active' || null, 60_000, 250)
+ await name(d, agent, 'Fix the login page')
+ await named(d, client, agent, cwd)
+ expect(workspacesPid(d)).toBe(workspaces)
+ expect(restarts(d)).toBe(0)
+ client.close()
+ })
+
+ it('the sweep runs in the workspaces process when the core says: it removes a week-idle worktree nothing uses, and keeps one an agent works in', async () => {
+ let unused = ''
+ let used = ''
+ const d = await fresh({ HARNESSD_TEST_SWEEP_AFTER_MS: '20000' }, (d) => {
+ const repo = repository(d)
+ unused = worktree(d, repo, 'old-idea')
+ used = worktree(d, repo, 'still-going')
+ })
+ const client = await LocalClient.connect(d)
+ const agent = await create(d, client, used)
+ // Both idle for a week: only the agent working in one keeps it.
+ idle(d, unused)
+ idle(d, used)
+ await until('the sweep to remove the unused worktree', () => d.log().includes('[worktrees] removed 1 unused worktree(s)') || null, 60_000, 250)
+ expect(existsSync(unused)).toBe(false)
+ expect(existsSync(used)).toBe(true)
+ expect(d.log().split('[worktrees] removed').length - 1).toBe(1)
+ await turn(client, agent.id, 'my worktree is still here')
+ expect(d.coresStarted()).toBe(1)
+ client.close()
+ })
+})
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index 117a880fb..6b1afe6ad 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -167,9 +167,11 @@ import { createCoreApi, emptyPorts, MODELS_FALLBACKS, SEARCH_FALLBACKS, TEAMS_FA
import { createServiceHost, testFaults } from './core/serviceHost.js'
import { createServiceLinks } from './core/serviceLinks.js'
import { createViewersLink } from './core/viewersLink.js'
+import { createWorkspacesLink } from './core/workspacesLink.js'
import { KNOWN_SERVICES, serviceSpecs } from './harnessd/services.js'
import { runSearchService } from './services/searchProcess.js'
import { runViewersService } from './services/viewersProcess.js'
+import { runWorkspacesService } from './services/workspacesProcess.js'
import { SEARCH_REQUESTS, startSearch } from './services/search.js'
import { STORE_REQUESTS, startStore } from './services/store.js'
import { startViewers } from './services/viewers.js'
@@ -220,6 +222,7 @@ import { loadCursorPendingTasks } from './engines/cursor/pendingTasks.js'
import { opencodeMajorVersion } from './engines/opencode/version.js'
import { hermesDbForSession } from './lib/hermesHome.js'
import { agentFrame, lastActivityAt, type AgentFrame } from './lib/agentFrame.js'
+import { forgetAgentProject } from './lib/agentProject.js'
import { agentTokenUsage } from './lib/agentTokenUsage.js'
import { DeviceResultJournal } from './lib/autonomous-device/resultJournal.js'
import { adaptSlashCommand } from './lib/goalCommand.js'
@@ -1838,8 +1841,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
const attachDsh = (s: RegisteredSession): void => ports.viewers?.attach(s)
const detachDsh = (agentId: string): void => ports.viewers?.detach(agentId)
- // The folders agents work in: branch names and unused worktrees (services/workspaces.ts).
- serviceHost.start('workspaces', startWorkspaces, coreApi, WORKSPACES_FALLBACKS)
+ // The folders agents work in: branch names and unused worktrees (services/workspaces.ts), started below.
const syncTerminalTitles = async (): Promise<void> => {
ports.workspaces?.nameBranches()
const titles = await terminals.titles()
@@ -2209,11 +2211,14 @@ async function runForeground(session: AuthSession | null): Promise<void> {
const requestsOf: Record<string, readonly string[]> = { search: SEARCH_REQUESTS }
// What the core keeps of the viewers in their own process, for the frames it builds (core/viewersLink.ts).
const viewersLink = createViewersLink(coreApi, (frame, opts) => serviceLinks.notify('viewers', frame, opts))
+ // 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)
const serviceLinks = createServiceLinks({
token: serviceToken,
owned: Object.fromEntries([...outOfProcess].map((name) => [name, requestsOf[name] ?? []])),
// Search asks for every agent, live then stopped, with the name the apps show for it: what it indexes.
- answer: (service, query, payload) => service === 'viewers' ? viewersLink.answer(query, payload) : query === 'agents'
+ answer: (service, query, payload) => service === 'viewers' ? viewersLink.answer(query, payload)
+ : service === 'workspaces' ? workspacesLink.answer(query, payload) : query === 'agents'
? { agents: coreApi.agents.all().map((session) => ({ ...session, displayName: coreApi.agents.displayName(session) })) }
: { error: 'UNKNOWN_QUERY' },
})
@@ -2238,6 +2243,9 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// The DSH viewers: in this process, or in its own (services/viewersProcess.ts), told of each agent.
if (outOfProcess.has('viewers')) ports.viewers = viewersLink.port
else serviceHost.start('viewers', startViewers, coreApi, VIEWERS_FALLBACKS)
+ // Workspaces: in this process, or in its own (services/workspacesProcess.ts), told what to do and when.
+ if (outOfProcess.has('workspaces')) ports.workspaces = workspacesLink.port
+ else serviceHost.start('workspaces', startWorkspaces, coreApi, WORKSPACES_FALLBACKS)
// The harnesses installed here, and installing, updating and removing one (services/store.ts).
serviceHost.serve('store', startStore, coreApi, STORE_REQUESTS)
@@ -4163,8 +4171,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// Worktrees Harness made that no live or stopped harness uses and nothing would miss
// (services/workspaces.ts): a few minutes after start, once restored agents are back in the
- // registry, then twice a day.
- setTimeout(() => ports.workspaces?.sweepUnused(), 5 * 60_000).unref()
+ // registry, then twice a day. Only the end-to-end harness shortens the first wait.
+ setTimeout(() => ports.workspaces?.sweepUnused(), Number(process.env.HARNESSD_TEST_SWEEP_AFTER_MS) || 5 * 60_000).unref()
setInterval(() => ports.workspaces?.sweepUnused(), 12 * 3600_000).unref()
@@ -5617,7 +5625,8 @@ switch (cmd) {
break
case '__service': { // internal: a service harnessd's master runs in its own process (services/process.ts)
const socketPath = localSocketPath(env.ADAPTER_DATA_DIR, env.PORT)
- const runService = rest[0] === 'search' ? runSearchService : rest[0] === 'viewers' ? runViewersService : null
+ const runService = rest[0] === 'search' ? runSearchService : rest[0] === 'viewers' ? runViewersService
+ : rest[0] === 'workspaces' ? runWorkspacesService : null
if (!runService || !socketPath) {
console.error(`[service] ${rest[0] ?? '(none)'}: ${socketPath ? 'no such service in this build' : 'the core has no local socket to reach'}`)
process.exit(2)
diff --git a/cli/src/core/AGENTS.md b/cli/src/core/AGENTS.md
index a3002b431..58dddb995 100644
--- a/cli/src/core/AGENTS.md
+++ b/cli/src/core/AGENTS.md
@@ -31,4 +31,4 @@ questions. Everything else is a service ([../services/AGENTS.md](../services/AGE
- `input.ts`, `questions.ts`: messages into a pane; an agent's question and its answer.
- `api.ts`: the contract with services. `serviceHost.ts`: services in this process.
`serviceLinks.ts`: services in their own processes. `viewersLink.ts`: what the core keeps of the
- viewers when they run in theirs.
+ viewers when they run in theirs. `workspacesLink.ts`: what the core tells workspaces in theirs.
diff --git a/cli/src/core/workspacesLink.spec.ts b/cli/src/core/workspacesLink.spec.ts
new file mode 100644
index 000000000..56cd5feb1
--- /dev/null
+++ b/cli/src/core/workspacesLink.spec.ts
@@ -0,0 +1,90 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import type { RegisteredSession } from '../lib/registry.js'
+import { fakeCore } from '../testing/fakeCore.js'
+import { createWorkspacesLink } from './workspacesLink.js'
+
+const agent = (agentId = 'a1', over: Partial<RegisteredSession> = {}) =>
+ ({ agentId, sessionId: `s-${agentId}`, engine: 'claude', cwd: `/h/worktrees/repo/${agentId}`, title: 'Fix the login page', ...over }) as RegisteredSession
+
+function setup(connected = true) {
+ const live = [agent('a1'), agent('a2')]
+ const stopped = agent('old', { active: false })
+ const core = fakeCore({
+ agents: {
+ live: vi.fn(() => live),
+ all: vi.fn(() => [...live, stopped]),
+ byAgent: vi.fn((agentId: string) => live.find((session) => session.agentId === agentId)),
+ },
+ })
+ const notify = vi.fn(() => connected)
+ const forgetProject = vi.fn()
+ const lines: string[] = []
+ const link = createWorkspacesLink(core, notify, forgetProject, (line) => lines.push(line))
+ return { core, notify, forgetProject, lines, link, port: link.port, live, stopped }
+}
+
+describe('workspaces in their own process, as the core tells them', () => {
+ afterEach(() => vi.restoreAllMocks())
+
+ it('tells the process to name branches with the live agents on each pass, and holds nothing it misses', () => {
+ const { notify, port, live } = setup(false)
+ port.nameBranches()
+ // Not held: the next title pass says it again, with the agents as they are then.
+ expect(notify.mock.calls).toEqual([[{ type: 'service_event', payload: { kind: 'nameBranches', agents: live } }]])
+ })
+
+ it('tells the process to sweep now, with nothing that could go stale: it asks for the folders in use as it starts', () => {
+ const { notify, port, lines, core } = setup()
+ port.sweepUnused()
+ expect(notify.mock.calls).toEqual([[{ type: 'service_event', payload: { kind: 'sweep' } }]])
+ expect(core.agents.all).not.toHaveBeenCalled()
+ expect(lines).toEqual([])
+ })
+
+ it('skips a sweep it decides while the process is not running, and says so: never held for later', () => {
+ const { notify, port, lines } = setup(false)
+ port.sweepUnused()
+ expect(notify).toHaveBeenCalledOnce()
+ expect(notify.mock.calls[0]).toHaveLength(1)
+ expect(lines).toEqual(['[worktrees] sweep skipped: the workspaces process is not running; the next one is on its timer'])
+ })
+
+ it('answers the process every agent, live then stopped, when it starts a sweep', () => {
+ const { link, live, stopped } = setup()
+ expect(link.answer('agents', {})).toEqual({ agents: [...live, stopped] })
+ })
+
+ it('lets a failure to list the agents fail the question, so nothing is swept', () => {
+ const { link, core } = setup()
+ vi.mocked(core.agents.all).mockImplementationOnce(() => { throw new Error('a stopped agent could not be read') })
+ expect(() => link.answer('agents', {})).toThrow('a stopped agent could not be read')
+ })
+
+ it('sends a renamed agent\'s frame again, read fresh', () => {
+ const { link, core, forgetProject, live } = setup()
+ expect(link.answer('branchNamed', { agentId: 'a2', requestId: 'q1', query: 'branchNamed' })).toEqual({ synced: true })
+ expect(forgetProject).toHaveBeenCalledWith(live[1].cwd)
+ expect(core.agents.sync).toHaveBeenCalledWith(live[1])
+ })
+
+ it('has no frame to send for an agent that is gone, or one it cannot name; one with no folder is only sent again', () => {
+ const { link, core, forgetProject, live } = setup()
+ expect(link.answer('branchNamed', { agentId: 'gone' })).toEqual({ synced: false })
+ expect(link.answer('branchNamed', { agentId: 7 })).toEqual({ synced: false })
+ expect(core.agents.sync).not.toHaveBeenCalled()
+ live[0].cwd = undefined as never
+ expect(link.answer('branchNamed', { agentId: 'a1' })).toEqual({ synced: true })
+ expect(forgetProject).not.toHaveBeenCalled()
+ expect(core.agents.sync).toHaveBeenCalledWith(live[0])
+ })
+
+ it('refuses a question it does not know', () => {
+ expect(setup().link.answer('context', {})).toEqual({ error: 'UNKNOWN_QUERY' })
+ })
+
+ it('logs on the console by default', () => {
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {})
+ createWorkspacesLink(fakeCore(), () => false, vi.fn()).port.sweepUnused()
+ expect(log).toHaveBeenCalledWith(expect.stringContaining('sweep skipped'))
+ })
+})
diff --git a/cli/src/core/workspacesLink.ts b/cli/src/core/workspacesLink.ts
new file mode 100644
index 000000000..ddc0bb146
--- /dev/null
+++ b/cli/src/core/workspacesLink.ts
@@ -0,0 +1,70 @@
+/**
+ * Workspaces in their own process, as the core sees them (`HARNESSD_SERVICES=workspaces`; the process's
+ * side is services/workspacesProcess.ts).
+ *
+ * The core asks workspaces nothing it must have answered: both calls are commands. So unlike the
+ * viewers (core/viewersLink.ts) there is nothing to keep for while the process is down. An agent's
+ * frame reads its branch from git in the core (lib/agentProject.ts), so a frame built meanwhile still
+ * names the branch; only renaming a made-up branch waits for the process to come back.
+ *
+ * Nothing is held for the process either:
+ * - Each terminal-title pass (every few seconds) tells it to name branches, with the live agents.
+ * One it misses is followed by the next.
+ * - A sweep is never held or replayed. The core's timers decide when one runs, as in its own process.
+ * A sweep decided while the process is not connected is skipped, and the next timer decides again:
+ * a held one would run at a time nobody chose, possibly beside the next.
+ * - When the process starts the sweep, it asks for every agent, live and stopped (`agents`), and sweeps
+ * only with that answer. So the folders in use are read when the sweep begins, as in the core's
+ * process, never from a list that waited in a buffer while the process was stopped. A core that
+ * cannot list them (an unreadable stopped agent) answers QUERY_FAILED, and nothing is swept.
+ *
+ * After it renames a branch, the process asks the core to send the agent's frame again
+ * (`branchNamed`): the core forgets what it read of the folder, and the frame shows the new name now
+ * rather than when that read expires.
+ */
+import type { CoreApi, WorkspacesPort } from './api.js'
+import type { ServiceFrame } from './serviceLinks.js'
+
+/** Tell the workspaces' process something (core/serviceLinks.ts `notify`, for `workspaces`). */
+export type NotifyWorkspaces = (frame: ServiceFrame) => boolean
+
+export function createWorkspacesLink(
+ core: Pick<CoreApi, 'agents'>,
+ notify: NotifyWorkspaces,
+ /** Forget what the core read of a folder's project (lib/agentProject.ts `forgetAgentProject`). */
+ forgetProject: (cwd: string) => void,
+ log: (line: string) => void = (line) => console.log(line),
+) {
+ const port: WorkspacesPort = {
+ nameBranches: () => {
+ notify({ type: 'service_event', payload: { kind: 'nameBranches', agents: core.agents.live() } })
+ },
+ sweepUnused: () => {
+ if (!notify({ type: 'service_event', payload: { kind: 'sweep' } })) {
+ log('[worktrees] sweep skipped: the workspaces process is not running; the next one is on its timer')
+ }
+ },
+ }
+
+ /** The process renamed an agent's branch: its frame goes out again, read fresh. */
+ const branchNamed = (payload: Record<string, unknown>): Record<string, unknown> => {
+ const session = typeof payload.agentId === 'string' ? core.agents.byAgent(payload.agentId) : undefined
+ if (!session) return { synced: false }
+ if (session.cwd) forgetProject(session.cwd)
+ core.agents.sync(session)
+ return { synced: true }
+ }
+
+ return {
+ port,
+ /** The core's answers to the workspaces' questions (core/serviceLinks.ts `answer`, for `workspaces`). */
+ answer(query: string, payload: Record<string, unknown>): Record<string, unknown> {
+ // Every agent, live then stopped: the folders a sweep starting now must keep.
+ if (query === 'agents') return { agents: core.agents.all() }
+ if (query === 'branchNamed') return branchNamed(payload)
+ return { error: 'UNKNOWN_QUERY' }
+ },
+ }
+}
+
+export type WorkspacesLink = ReturnType<typeof createWorkspacesLink>
diff --git a/cli/src/harnessd/services.ts b/cli/src/harnessd/services.ts
index de15a3b4a..a191fd663 100644
--- a/cli/src/harnessd/services.ts
+++ b/cli/src/harnessd/services.ts
@@ -288,14 +288,16 @@ export class ServiceSupervisor {
/**
* The services this build can run in their own processes, with their memory budgets. Which of them do
- * is `HARNESSD_SERVICES` (`search,viewers`): off until named, while each one beds in, and the core runs a
- * service that is not out here in its own process, as before.
+ * is `HARNESSD_SERVICES` (`search,viewers,workspaces`): off until named, while each one beds in, and the
+ * core runs a service that is not out here in its own process, as before.
*/
export const KNOWN_SERVICES: Readonly<Record<string, Omit<ServiceSpec, 'name'>>> = {
search: { heapLimitMiB: 1_024, rssLimitMiB: 2_048 },
// Its file watches on every harness's workspace; the viewer servers it starts are processes of their
// own, outside this budget.
viewers: { heapLimitMiB: 512, rssLimitMiB: 1_024 },
+ // The git work runs in git's own processes; this one only holds the agents the core sent it.
+ workspaces: { heapLimitMiB: 256, rssLimitMiB: 512 },
}
/** Service timings from the environment (for tests and support); anything unset or invalid keeps its default. */
diff --git a/cli/src/services/AGENTS.md b/cli/src/services/AGENTS.md
index 92e51ed29..0d500afd5 100644
--- a/cli/src/services/AGENTS.md
+++ b/cli/src/services/AGENTS.md
@@ -39,7 +39,8 @@ let several people build features at once without touching the core or each othe
## Running in its own process
A service that can crash natively, hang or leak should run in its own process, where it costs only
-itself. Search and the viewers do: `HARNESSD_SERVICES=search,viewers` (either alone, too).
+itself. Search, the viewers and workspaces do: `HARNESSD_SERVICES=search,viewers,workspaces` (any of
+them alone, too).
- `src/harnessd/services.ts` runs it (`KNOWN_SERVICES`, with its memory budget). The core routes the
requests it declared (its `<NAME>_REQUESTS`) to its process, and the same handlers answer them there.
@@ -55,6 +56,11 @@ itself. Search and the viewers do: `HARNESSD_SERVICES=search,viewers` (either al
the last ones and its port answers from them, or from the fallbacks before it has heard any. The
process asks the core for everything it should hold each time it connects, which a restarted
process needs anyway. `e2e/viewersProcess.e2e.ts` proves it with a real harness agent's viewer.
+- A service the core only gives commands to needs nothing kept for it while it is down. Workspaces
+ (`src/services/workspacesProcess.ts`, `src/core/workspacesLink.ts`) is told to name branches and
+ when to sweep. A command that destroys something is never held or replayed, and what it must know
+ (the folders in use) is asked for when it starts, never sent ahead where it could go stale.
+ `e2e/workspacesProcess.e2e.ts` proves it.
## Do not
diff --git a/cli/src/services/workspaces.spec.ts b/cli/src/services/workspaces.spec.ts
index b62553638..65a1c574e 100644
--- a/cli/src/services/workspaces.spec.ts
+++ b/cli/src/services/workspaces.spec.ts
@@ -84,12 +84,38 @@ describe('the workspaces service', () => {
it('says nothing when it removed nothing, and nothing when the sweep fails', async () => {
const { port } = setup()
port.sweepUnused()
+ await settle()
vi.mocked(sweepWorktrees).mockRejectedValueOnce(new Error('EACCES'))
port.sweepUnused()
await settle()
+ expect(sweepWorktrees).toHaveBeenCalledTimes(2)
expect(console.log).not.toHaveBeenCalled()
})
+ it('never runs a second sweep beside one still going, and sweeps again once it is done', async () => {
+ let finish: (removed: string[]) => void = () => {}
+ vi.mocked(sweepWorktrees).mockImplementationOnce(() => new Promise((done) => { finish = done }))
+ const { core, port } = setup([agent({ cwd: '/h/live' })])
+ port.sweepUnused()
+ port.sweepUnused()
+ expect(sweepWorktrees).toHaveBeenCalledTimes(1)
+ // Not even asked what is in use: the sweep going on already knows.
+ expect(core.agents.all).toHaveBeenCalledTimes(1)
+ finish([])
+ await settle()
+ port.sweepUnused()
+ expect(sweepWorktrees).toHaveBeenCalledTimes(2)
+ })
+
+ it('sweeps again after a sweep that failed', async () => {
+ vi.mocked(sweepWorktrees).mockRejectedValueOnce(new Error('EACCES'))
+ const { port } = setup()
+ port.sweepUnused()
+ await settle()
+ port.sweepUnused()
+ expect(sweepWorktrees).toHaveBeenCalledTimes(2)
+ })
+
it('does not sweep at all when it cannot list what is in use', () => {
const { core, port } = setup()
vi.mocked(core.agents.all).mockImplementationOnce(() => { throw new Error('registry not loaded') })
diff --git a/cli/src/services/workspaces.ts b/cli/src/services/workspaces.ts
index 6abeb6037..f0f3f6387 100644
--- a/cli/src/services/workspaces.ts
+++ b/cli/src/services/workspaces.ts
@@ -37,12 +37,20 @@ export function startWorkspaces(core: CoreApi, ports: CorePorts): void {
// Worktrees Harness made that no live or stopped harness uses and nothing would miss
// (lib/worktreeSweep.ts). The core decides when: a few minutes after start, once restored agents
// are back in the registry, then twice a day.
+ //
+ // One sweep at a time: a sweep still going is never joined by a second over the same folders. In the
+ // core's process its timers are hours apart; in this service's own process, a core that restarted
+ // asks again on its own timer while a long sweep from the last core may still be running.
+ let sweeping = false
const sweepUnusedWorktrees = () => {
+ if (sweeping) return
let inUse: Array<string | null>
try { inUse = core.agents.all().map(s => s.cwd) } catch { return }
+ sweeping = true
void sweepWorktrees({ root: join(homedir(), 'harnesses'), inUse })
.then(removed => { if (removed.length) console.log(`[worktrees] removed ${removed.length} unused worktree(s)`) })
.catch(() => {})
+ .finally(() => { sweeping = false })
}
ports.workspaces = { nameBranches: nameSessionBranches, sweepUnused: sweepUnusedWorktrees }
}
diff --git a/cli/src/services/workspacesProcess.spec.ts b/cli/src/services/workspacesProcess.spec.ts
new file mode 100644
index 000000000..310b9ee3a
--- /dev/null
+++ b/cli/src/services/workspacesProcess.spec.ts
@@ -0,0 +1,180 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import type { CoreApi, CorePorts, WorkspacesPort } from '../core/api.js'
+import type { RegisteredSession } from '../lib/registry.js'
+import { runServiceProcess, type CoreConnection, type ServiceProcessOptions } from './process.js'
+import { runWorkspacesService, workspacesCoreApi } from './workspacesProcess.js'
+
+// The real default reaches a real socket and this process's own channel: never in a test.
+vi.mock('./process.js', () => ({ runServiceProcess: vi.fn(() => ({ stop: vi.fn() })) }))
+
+const agent = (agentId = 'a1', over: Partial<RegisteredSession> = {}) =>
+ ({ agentId, sessionId: `s-${agentId}`, engine: 'claude', cwd: `/h/worktrees/repo/${agentId}`, title: 'Fix the login page', ...over }) as RegisteredSession
+
+const flush = () => new Promise((done) => setTimeout(done, 0))
+
+describe('workspaces in their own process', () => {
+ afterEach(() => vi.clearAllMocks())
+
+ const setup = (over: Partial<Parameters<typeof runWorkspacesService>[0]> = {}) => {
+ let api: CoreApi | null = null
+ let options: ServiceProcessOptions | null = null
+ /** What `all()` answered when the service swept, each time. */
+ const swept: RegisteredSession[][] = []
+ const port = {
+ nameBranches: vi.fn(),
+ sweepUnused: vi.fn(() => { swept.push(api!.agents.all()) }),
+ } satisfies WorkspacesPort
+ const service = { stop: vi.fn() }
+ const handle = runWorkspacesService({
+ dataDir: '/data', socketPath: '/data/daemon-1.sock', machineId: 'm', token: 't',
+ run: (given) => { options = given; return service },
+ start: (core: CoreApi, ports: CorePorts) => { api = core; ports.workspaces = port },
+ ...over,
+ })
+ return { api: api!, options: options!, port, service, handle, swept }
+ }
+ /** A core that answers `agents` with `answer`, and records the rest. */
+ const connection = (answer: () => Promise<Record<string, unknown>> = async () => ({ agents: [agent()] })) => {
+ const query = vi.fn((name: string, _payload?: Record<string, unknown>) => (name === 'agents' ? answer() : Promise.resolve({ synced: true })))
+ return { core: { query } satisfies CoreConnection, query }
+ }
+
+ it('reaches the core as `workspaces`, through the socket and token it was given, and answers the apps nothing', () => {
+ const { options } = setup()
+ expect(options).toMatchObject({ name: 'workspaces', socketPath: '/data/daemon-1.sock', machineId: 'm', token: 't' })
+ expect(options.requests).toEqual({})
+ })
+
+ it('names branches when the core says, with the live agents it sent', () => {
+ const { api, options, port } = setup()
+ options.onEvent!({ kind: 'nameBranches', agents: [agent('a1'), { not: 'an agent' }, agent('a2')] })
+ expect(port.nameBranches).toHaveBeenCalledOnce()
+ expect(api.agents.live().map((session) => session.agentId)).toEqual(['a1', 'a2'])
+ expect(api.agents.byAgent('a2')).toEqual(agent('a2'))
+ // Told without agents, or told something else: nothing to do.
+ options.onEvent!({ kind: 'nameBranches' })
+ options.onEvent!({ kind: 'touch', sessionId: 's1' })
+ expect(port.nameBranches).toHaveBeenCalledOnce()
+ })
+
+ it('asks the core to send a renamed agent\'s frame again, once connected; a lost word costs nothing', async () => {
+ const { api, options } = setup()
+ api.agents.sync(agent('a1'))
+ const core = connection()
+ options.onConnected!(core.core)
+ api.agents.sync(agent('a1'))
+ expect(core.query).toHaveBeenCalledWith('branchNamed', { agentId: 'a1' })
+ options.onConnected!({ query: vi.fn(async () => { throw new Error('the core went away') }) })
+ api.agents.sync(agent('a1'))
+ await flush()
+ })
+
+ it('sweeps when the core says, with every agent the core names at that moment, and knows them only then', async () => {
+ const { api, options, port, swept } = setup()
+ const everyone = [agent('a1'), agent('old', { active: false, cwd: null as never })]
+ const core = connection(async () => ({ agents: everyone, requestId: 'r1' }))
+ options.onConnected!(core.core)
+ expect(() => api.agents.all()).toThrow('the core has not said which folders are in use')
+ options.onEvent!({ kind: 'sweep' })
+ await flush()
+ expect(core.query).toHaveBeenCalledWith('agents')
+ expect(port.sweepUnused).toHaveBeenCalledOnce()
+ // Exactly as the core sent them, the one with no folder too.
+ expect(swept).toEqual([everyone])
+ expect(() => api.agents.all()).toThrow()
+ })
+
+ it('does not sweep when the core cannot name every agent, or names something that is not one', async () => {
+ const { options, port } = setup()
+ options.onConnected!(connection(async () => ({ error: 'QUERY_FAILED' })).core)
+ options.onEvent!({ kind: 'sweep' })
+ await flush()
+ options.onConnected!(connection(async () => ({ agents: [agent('a1'), null] })).core)
+ options.onEvent!({ kind: 'sweep' })
+ await flush()
+ options.onConnected!(connection(async () => { throw new Error('the core went away') }).core)
+ options.onEvent!({ kind: 'sweep' })
+ await flush()
+ expect(port.sweepUnused).not.toHaveBeenCalled()
+ })
+
+ it('asks once for a sweep however often it is told meanwhile, and again for the next', async () => {
+ const { options, port } = setup()
+ let answer: (value: Record<string, unknown>) => void = () => {}
+ const core = connection(() => new Promise((done) => { answer = done }))
+ options.onConnected!(core.core)
+ options.onEvent!({ kind: 'sweep' })
+ options.onEvent!({ kind: 'sweep' })
+ expect(core.query).toHaveBeenCalledOnce()
+ answer({ agents: [agent()] })
+ await flush()
+ expect(port.sweepUnused).toHaveBeenCalledOnce()
+ options.onEvent!({ kind: 'sweep' })
+ expect(core.query).toHaveBeenCalledTimes(2)
+ })
+
+ it('cannot sweep before it is connected: only the core it reaches can say what is in use', () => {
+ const { options, port } = setup()
+ options.onEvent!({ kind: 'sweep' })
+ expect(port.sweepUnused).not.toHaveBeenCalled()
+ })
+
+ it('survives a sweep that fails, and forgets the agents it was given for it', async () => {
+ const { api, options, port } = setup()
+ port.sweepUnused.mockImplementationOnce(() => { throw new Error('boom') })
+ options.onConnected!(connection().core)
+ options.onEvent!({ kind: 'sweep' })
+ await flush()
+ expect(() => api.agents.all()).toThrow()
+ options.onEvent!({ kind: 'sweep' })
+ await flush()
+ expect(port.sweepUnused).toHaveBeenCalledTimes(2)
+ })
+
+ it('stops its connection when stopped', () => {
+ const { handle, service } = setup()
+ handle.stop()
+ expect(service.stop).toHaveBeenCalledOnce()
+ })
+
+ it('does not run without workspaces: the master starts it again, or parks it', () => {
+ expect(() => setup({ start: () => {} })).toThrow('workspaces did not start')
+ })
+
+ it('runs on a core API of the agents the core sent, answering what workspaces never ask as nothing', async () => {
+ const renamed = vi.fn()
+ let everyone: RegisteredSession[] | null = null
+ const api = workspacesCoreApi('/data', { live: () => [agent('a1')], inUse: () => everyone }, renamed)
+ expect(api.dataDir).toBe('/data')
+ expect(api.agents.live()).toEqual([agent('a1')])
+ expect(() => api.agents.all()).toThrow()
+ everyone = [agent('a1'), agent('old')]
+ expect(api.agents.all()).toEqual(everyone)
+ expect(api.agents.byAgent('a1')).toEqual(agent('a1'))
+ expect(api.agents.byAgent('old')).toBeUndefined()
+ expect(api.agents.displayName(agent())).toBe('')
+ expect(api.agents.advertised()).toEqual([])
+ expect(api.agents.terminalAvailable('a1')).toBe(false)
+ api.agents.sync(agent('a1'))
+ expect(renamed).toHaveBeenCalledWith('a1')
+ expect(api.transcripts.databaseHistory(agent())).toBeUndefined()
+ expect(api.external.sessions.list()).toEqual([])
+ await expect(api.external.sessions.scan()).resolves.toEqual([])
+ expect(api.external.open.known().size).toBe(0)
+ await expect(api.external.open.fresh()).resolves.toEqual(new Map())
+ await expect(api.account.mintGridName()).resolves.toBeNull()
+ await expect(api.account.accessToken()).rejects.toThrow('workspaces hold no credential')
+ await expect(api.account.privateGridName()).resolves.toBeNull()
+ expect(api.account.machineName()).toBeNull()
+ await expect(api.agents.runtimeModels()).resolves.toEqual([])
+ api.clients.gridModelsChanged()
+ api.clients.viewerChanged('a1')
+ api.clients.gridNamed('grid')
+ api.clients.dshInstallStatus({ phase: 'clone' })
+ })
+
+ it('runs as a real service process, with the real workspaces, by default', () => {
+ runWorkspacesService({ dataDir: '/data', socketPath: '/data/daemon-1.sock', machineId: 'm', token: 't' })
+ expect(runServiceProcess).toHaveBeenCalledWith(expect.objectContaining({ name: 'workspaces', socketPath: '/data/daemon-1.sock' }))
+ })
+})
diff --git a/cli/src/services/workspacesProcess.ts b/cli/src/services/workspacesProcess.ts
new file mode 100644
index 000000000..b9d771f2e
--- /dev/null
+++ b/cli/src/services/workspacesProcess.ts
@@ -0,0 +1,125 @@
+/**
+ * Workspaces in their own process (`harness __service workspaces`, with `HARNESSD_SERVICES=workspaces`).
+ *
+ * The same branch naming and worktree sweep as in the core's process (services/workspaces.ts), on a core
+ * API built here. It acts only when the core says so (core/workspacesLink.ts):
+ * - It names branches when told to, with the live agents the core sends on each terminal-title pass.
+ * - It sweeps when the core's timer says, asking the core at that moment for every agent, live and
+ * stopped, and sweeping with exactly that answer.
+ *
+ * It never sweeps on its own, never with agents it kept from earlier, never when the core cannot answer,
+ * and never two sweeps at once (services/workspaces.ts). After a rename it asks the core to send the
+ * agent's frame again. The git work (renames, worktree removals, their timeouts) is this process's
+ * alone: a hang or a crash in it costs workspaces, and the master starts them again.
+ */
+import type { CoreApi } from '../core/api.js'
+import { emptyPorts } from '../core/api.js'
+import type { RegisteredSession } from '../lib/registry.js'
+import { runServiceProcess, type CoreConnection, type ServiceProcess } from './process.js'
+import { startWorkspaces } from './workspaces.js'
+
+export interface WorkspacesServiceOptions {
+ dataDir: string
+ socketPath: string
+ machineId: string
+ token: string
+ /** Swapped in tests for one that does not touch the real socket or process. */
+ run?: typeof runServiceProcess
+ /** Swapped in tests for workspaces that touch no repository. */
+ start?: typeof startWorkspaces
+}
+
+const isSession = (value: unknown): value is RegisteredSession =>
+ !!value && typeof value === 'object' && typeof (value as { agentId?: unknown }).agentId === 'string'
+
+/**
+ * The core API workspaces run on in their own process. The live agents are the ones the core last sent.
+ * Every agent, live and stopped, is known only while a sweep the core asked for starts; asked at any
+ * other time it throws, and a sweep that cannot list the folders in use sweeps nothing. A frame sent
+ * again (after a rename) is the core's to send: `renamed` asks it to.
+ */
+export function workspacesCoreApi(
+ dataDir: string,
+ view: { live(): RegisteredSession[]; inUse(): RegisteredSession[] | null },
+ renamed: (agentId: string) => void,
+): CoreApi {
+ return {
+ dataDir,
+ agents: {
+ all: () => {
+ const agents = view.inUse()
+ if (!agents) throw new Error('the core has not said which folders are in use')
+ return agents
+ },
+ live: () => view.live(),
+ displayName: () => '',
+ byAgent: (agentId) => view.live().find((session) => session.agentId === agentId),
+ advertised: () => [],
+ terminalAvailable: () => false,
+ sync: (session) => renamed(session.agentId),
+ runtimeModels: async () => [],
+ },
+ transcripts: { databaseHistory: () => undefined },
+ external: {
+ sessions: { list: () => [], scan: async () => [] },
+ open: { known: () => new Map(), fresh: async () => new Map() },
+ },
+ account: {
+ mintGridName: async () => null,
+ accessToken: () => Promise.reject(new Error('workspaces hold no credential')),
+ privateGridName: async () => null,
+ machineName: () => null,
+ },
+ clients: { viewerChanged: () => {}, gridNamed: () => {}, gridModelsChanged: () => {}, dshInstallStatus: () => {} },
+ }
+}
+
+export function runWorkspacesService(options: WorkspacesServiceOptions): ServiceProcess {
+ let live: RegisteredSession[] = []
+ /** Every agent the core named for the sweep starting now; null at every other moment. */
+ let inUse: RegisteredSession[] | null = null
+ let core: CoreConnection | null = null
+ /** A sweep's question to the core is out: a second request meanwhile is the same sweep. */
+ let asking = false
+ const ports = emptyPorts()
+ // Lost only with the connection: the frame then shows the new branch when the core's read of the
+ // folder expires (lib/agentProject.ts), seconds later.
+ const renamed = (agentId: string): void => { void core?.query('branchNamed', { agentId }).catch(() => {}) }
+ ;(options.start ?? startWorkspaces)(workspacesCoreApi(options.dataDir, { live: () => live, inUse: () => inUse }, renamed), ports)
+ if (!ports.workspaces) throw new Error('workspaces did not start')
+ const workspaces = ports.workspaces
+
+ /** The core's timer says it is time: ask it for every agent now, and sweep with exactly that answer. */
+ const sweep = (): void => {
+ const connection = core
+ if (!connection || asking) return
+ asking = true
+ void connection.query('agents').then((answer) => {
+ // Every entry, as the core sent it: one left out would be a folder in use that looks unused. An
+ // answer that is not a list of agents (QUERY_FAILED, when the core could not read them all) is no
+ // sweep at all.
+ const agents = answer.agents
+ if (!Array.isArray(agents) || !agents.every(isSession)) return
+ inUse = agents
+ try { workspaces.sweepUnused() } catch { /* its own failure: the next timer tries again */ } finally { inUse = null }
+ }, () => {}).finally(() => { asking = false })
+ }
+
+ const run = options.run ?? runServiceProcess
+ const service = run({
+ name: 'workspaces',
+ socketPath: options.socketPath,
+ machineId: options.machineId,
+ token: options.token,
+ // The apps ask workspaces nothing yet: only the core tells it what to do.
+ requests: {},
+ onEvent: (payload) => {
+ if (payload.kind === 'nameBranches' && Array.isArray(payload.agents)) {
+ live = payload.agents.filter(isSession)
+ workspaces.nameBranches()
+ } else if (payload.kind === 'sweep') sweep()
+ },
+ onConnected: (connection) => { core = connection },
+ })
+ return { stop: () => service.stop() }
+}
diff --git a/docs/design/2026-10-03-harnessd.md b/docs/design/2026-10-03-harnessd.md
index 48f5cd29c..a5d05f148 100644
--- a/docs/design/2026-10-03-harnessd.md
+++ b/docs/design/2026-10-03-harnessd.md
@@ -480,6 +480,17 @@ Done so far:
servers are the process's own: a crash costs only them (the new process stops the ones the old one
left running, then starts its own), and a core restart no longer restarts them.
`cli/e2e/viewersProcess.e2e.ts` proves it on the real daemon with a real harness agent's viewer.
+- **Workspaces in their own process** (`HARNESSD_SERVICES=workspaces`, alone or beside search and the
+ viewers). The core only gives workspaces commands: name the made-up branches, and sweep when its
+ timer says. So nothing is kept or held for it while it is down, and frames keep their branch names
+ meanwhile, because the core reads them itself (`cli/src/core/workspacesLink.ts`). The sweep's timers stay in
+ the core and its rules (#711) are unchanged. A sweep the core decides while the process is down is
+ skipped, never replayed. When the process starts one, it asks the core for every agent at that
+ moment and sweeps only with that answer, and a sweep still going is never joined by a second.
+ `cli/e2e/workspacesProcess.e2e.ts` proves on the real daemon that a stop, a hang, a kill, a crash
+ loop and a core restart each cost workspaces alone. It also proves that only the process renames a
+ branch and the new name reaches the agent's frame, and that the sweep removes an idle unused
+ worktree, keeps one an agent works in, and skips the one decided while the process was down.
- **Services answer their own requests** (core/serviceHost.ts `route`). A service declares the frame
types it answers (`<NAME>_REQUESTS`) and returns their handlers from its start. The socket hands
such a request to it before its own switch, with who asked (`Asker`: local, owner), and never