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.

Core boundary, part 9: models and workspaces become services (#733)

Dee92dff8a9cce4
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index 1d4ea3ec5..b7139066a 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -49,7 +49,7 @@ import { terminalActivity } from './cable/terminalActivity.js'
import { MachineListCache, machineListCachePath, withStaleMarker } from './device/machineList.js'
import { DeviceLink } from './device/deviceLink.js'
import { DeviceFleet } from './device/deviceFleet.js'
-import { registry, projectDisplayName, sessionDisplayTitle, validTranscriptPath, type RegisteredSession } from './lib/registry.js'
+import { registry, projectDisplayName, validTranscriptPath, type RegisteredSession } from './lib/registry.js'
import { engineSessionTitle } from './lib/sessionTitle.js'
import { installCodexHooks } from './lib/hooks.js'
import { PID_FILE, daemonPort, isAlive, isDaemonRunning, readPid } from './lib/daemonState.js'
@@ -70,15 +70,11 @@ import { qrSignIn } from './lib/qrSignIn.js'
import { pickSignInMethod, signInMethodFlag, signInProviderName, withSignInProvider, type SignInMethod, type SignInProvider } from './lib/signInMethodPicker.js'
import { watchJsonDriver, type JsonDriver } from './lib/jsonDriver.js'
import { terminalQr } from './lib/terminalQr.js'
-import { ensureGridInstalled } from './lib/gridInstall.js'
import { ensureHarnessGrid, type EnsureStatus } from './lib/gridEnsure.js'
import { passThroughToGridLogout } from './lib/gridLogout.js'
-import { clearGridMcpUrlCache } from './lib/gridMcpUrl.js'
import { warnIfGridSignInRemains } from './lib/gridCredentials.js'
-import { reconcileGridAttach, gridNamesLocal, createGridAccess } from './lib/gridAttach.js'
-import { signedInGridEmail, resetGridDeriveMemo } from './lib/gridDerive.js'
-import { forgetGridModels, gridAnnotation, keystrokePrewarm, observeMachineList, onGridModelsChanged, warmGridModels } from './lib/gridModels.js'
-import { gridAvailable, managedGridPath } from './lib/gridExec.js'
+import { observeMachineList } from './lib/gridModels.js'
+import { managedGridPath } from './lib/gridExec.js'
import { ENGINE_CLI_COMMANDS, ENGINES, PROCESS_ENGINES, enginePathOverride } from './lib/engineBin.js'
import { isTerminalEngine } from './engines/types.js'
import { engineInstallRecipe } from './lib/engineInstall.js'
@@ -103,9 +99,6 @@ import { prepareAgentHandoff } from './lib/agentHandoff.js'
import { ExternalSessions, OpenSessions } from './lib/sessionSearch/external.js'
import { externalProviders } from './lib/sessionSearch/externals/index.js'
import { SESSION_SEARCH_FILE, searchCommand } from './lib/sessionSearch/command.js'
-import { sweepWorktrees } from './lib/worktreeSweep.js'
-import { nameBranchAfterSession } from './lib/branchNaming.js'
-import { forgetAgentProject } from './lib/agentProject.js'
import { type LaunchOverridesDeps } from './lib/launchOverrides.js'
import { buildHarnessSessionLabel } from './lib/harnessSessionLabel.js'
import { adoptLegacyHarnessSessions, listTmuxPanes } from './lib/tmuxAgentDiscovery.js'
@@ -170,6 +163,8 @@ import { databaseHistory } from './core/transcripts/databaseHistory.js'
import { createCoreApi, emptyPorts } from './core/api.js'
import { startSearch } from './services/search.js'
import { startViewers } from './services/viewers.js'
+import { startModels } from './services/models.js'
+import { startWorkspaces } from './services/workspaces.js'
import { describeMasterStatus, readStatusFile, runMaster } from './harnessd/master.js'
import { CORE_EXIT_STOP, CORE_EXIT_UPDATE } from './harnessd/protocol.js'
import { isLocalSocketName, localSocketPath, type LocalSocketServer } from './lib/localSocket.js'
@@ -1772,6 +1767,15 @@ async function runForeground(session: AuthSession | null): Promise<void> {
backendRef?.viewerForwarder.refresh(agentId)
backendRef?.interactiveViewers.refresh(agentId)
},
+ gridNamed: (name) => backendRef?.setHarnessGridName(name),
+ // The backend mints and remembers the account's grid name; this CLI holds neither the account's
+ // email nor its id. An older backend (no route) answers nothing, which the grid reconcile treats as
+ // "no grid yet". Bounded so a stalled control-plane connection cannot hold the attempt open.
+ mintGridName: async () => {
+ const { headers } = await controlPlaneAuth()
+ return (await postJson<{ gridName?: string }>('/api/grid/name', {}, headers, AbortSignal.timeout(GRID_MINT_TIMEOUT_MS))).gridName ?? null
+ },
+ accessToken: () => new AuthSessionManager(backendHttpBase()).accessToken(),
})
const ports = emptyPorts()
// The DSH companions: each harness agent's viewer and verdict watch (services/viewers.ts).
@@ -1780,26 +1784,10 @@ 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)
- // A worktree branch Harness made up at Start takes its session's name once it has one
- // (lib/branchNaming.ts). Each agent is looked at once per daemon; the git reads are the cost.
- const branchNamed = new Set<string>()
- const nameSessionBranches = (): void => {
- for (const session of registry.list()) {
- const title = sessionDisplayTitle(session)
- if (!title || !session.cwd || branchNamed.has(session.agentId)) continue
- branchNamed.add(session.agentId)
- const cwd = session.cwd
- void nameBranchAfterSession(cwd, title).then((renamed) => {
- if (!renamed) return
- console.log(`[worktrees] agent ${sid(session.agentId)} branch named ${renamed}`)
- forgetAgentProject(cwd)
- const current = registry.byAgent(session.agentId)
- if (current) syncSession(current)
- }).catch(() => {})
- }
- }
+ // The folders agents work in: branch names and unused worktrees (services/workspaces.ts).
+ startWorkspaces(coreApi, ports)
const syncTerminalTitles = async (): Promise<void> => {
- nameSessionBranches()
+ ports.workspaces?.nameBranches()
const titles = await terminals.titles()
if (titles.size === 0) return
for (const session of registry.list()) {
@@ -1862,52 +1850,13 @@ async function runForeground(session: AuthSession | null): Promise<void> {
ensureBundledCoreHarnesses()
- // Grid is an add-on (`lib/gridAttach.ts`): nothing on this path installs `grid`, signs this machine in
- // to it or creates a grid. The first grid feature a person uses — the models picker's Set up, a local
- // model's Get or Use, an agent moved onto a grid model, the Model Manager — asks `backend.ensureGrid`,
- // which does it then, with this machine's harness token (no second browser) and, only for what needs
- // one, the account's own grid. It used to run here on every start and every reconnect.
- const gridLog = (line: string): void => console.log(`[grid-attach] ${line}`)
- const gridAccess = createGridAccess({
- signedIn: () => signedInGridEmail() !== null,
- log: gridLog,
- attempt: ({ ownGrid, signedInThisRun }) => reconcileGridAttach({
- // The pinned managed runtime first; grid's own installer when there is none to follow.
- installCli: async () => {
- await ensureManagedGrid((m) => console.log(`[grid-runtime] ${m}`))
- if (gridAvailable()) return
- const installed = await ensureGridInstalled()
- if (installed.status !== 'present') gridLog(installed.message)
- },
- gridAvailable: () => gridAvailable(),
- // The backend mints and remembers the name; this CLI holds neither the account's email nor its
- // id. An older backend (no route) answers nothing, which the reconcile treats as "no grid yet".
- // Bounded so a stalled control-plane connection cannot hold the attempt open indefinitely.
- mintName: async () => {
- const { headers } = await controlPlaneAuth()
- return (await postJson<{ gridName?: string }>('/api/grid/name', {}, headers, AbortSignal.timeout(GRID_MINT_TIMEOUT_MS))).gridName ?? null
- },
- accessToken: () => new AuthSessionManager(backendHttpBase()).accessToken(),
- signedInEmail: () => signedInGridEmail(),
- gridNames: () => gridNamesLocal(),
- handoff: (token) => handOffToGrid(token, { json: true }),
- ensure: (name) => ensureHarnessGrid(name),
- onName: (name) => {
- // Answer the picker with this account's grid at once, and drop the memos a stale or absent
- // sign-in may have filled — the model list, the derived name, and the web-tools URL.
- backend.setHarnessGridName(name)
- forgetGridModels()
- resetGridDeriveMemo()
- clearGridMcpUrlCache()
- },
- log: gridLog,
- }, { ownGrid, signedInThisRun }),
- })
-
- backend.ensureGrid = (request) => gridAccess.ensure(request)
+ // Models: grid access, the model pictures on agents' frames, the keystroke prewarm (services/models.ts).
+ startModels(coreApi, ports)
+ const models = ports.models
+ backend.ensureGrid = models ? (request) => models.ensure(request) : null
// Offline, for every list read: is there a `grid` here holding a sign-in? What decides whether the
// picker offers local and shared models or a Set up row.
- backend.gridSetUp = () => gridAvailable() && signedInGridEmail() !== null
+ backend.gridSetUp = models ? () => models.setUp() : null
/**
* Is ANY device surface watching this machine?
@@ -1972,29 +1921,10 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// an older desktop and typing from a phone get it too; an agent on its own login has no `grid`.
onInput: (agentId) => {
const grid = registry.resolve(agentId)?.grid
- if (grid) void keystrokePrewarm(grid).catch(() => {})
+ if (grid) ports.models?.prewarm(grid)
},
})
backend.setTerminalStreamManager(terminalStreams)
- // An agent's frame says what its grid's picture says (`grid.state`, and a `grid.note` when its model
- // will not answer). The picture changes on reads nobody waited for, so the frames of the agents whose
- // annotation moved are pushed again — only those, and only when it moved.
- const announcedGrid = new Map<string, string>()
- onGridModelsChanged(() => {
- const onGrid = registry.advertised().filter((s) => s.grid)
- const present = new Set(onGrid.map((s) => s.agentId))
- for (const agentId of [...announcedGrid.keys()]) if (!present.has(agentId)) announcedGrid.delete(agentId)
- for (const s of onGrid) {
- const said = JSON.stringify(gridAnnotation(s.grid))
- if (announcedGrid.get(s.agentId) === said) continue
- announcedGrid.set(s.agentId, said)
- syncSession(s)
- }
- })
- // The pictures saved before this start, back in memory with nothing read from any grid: an agent's
- // frame carries its grid's state and note, and a keystroke can start its grid, before any window asks
- // for the list (after a self-update, a phone may be the only one typing).
- void warmGridModels().catch(() => {})
// `agentReconciler` is declared further down; this closure only ever runs for a frame, and no
// socket is connected until well after that declaration (backend.connect() is the last thing
// this function does).
@@ -3865,7 +3795,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
clearAuthSession()
// The web-tools cache lives exactly as long as the sign-in. `harness logout` and `reset` stop
// the daemon outright; this is the one sign-out the daemon learns of from inside.
- clearGridMcpUrlCache()
+ ports.models?.signedOut()
void shutdown('revoked')
}
@@ -4090,17 +4020,10 @@ async function runForeground(session: AuthSession | null): Promise<void> {
autonomousDeviceDirect.start()
// Worktrees Harness made that no live or stopped harness uses and nothing would miss
- // (lib/worktreeSweep.ts): a few minutes after start, once restored agents are back in the
+ // (services/workspaces.ts): a few minutes after start, once restored agents are back in the
// registry, then twice a day.
- const sweepUnusedWorktrees = () => {
- let inUse: Array<string | null>
- try { inUse = [...registry.list().map(s => s.cwd), ...stoppedAgents.list().map(s => s.cwd)] } catch { return }
- void sweepWorktrees({ root: join(homedir(), 'harnesses'), inUse })
- .then(removed => { if (removed.length) console.log(`[worktrees] removed ${removed.length} unused worktree(s)`) })
- .catch(() => {})
- }
- setTimeout(sweepUnusedWorktrees, 5 * 60_000).unref()
- setInterval(sweepUnusedWorktrees, 12 * 3600_000).unref()
+ setTimeout(() => ports.workspaces?.sweepUnused(), 5 * 60_000).unref()
+ setInterval(() => ports.workspaces?.sweepUnused(), 12 * 3600_000).unref()
// Every card bound for the WiFi device goes down the cable too, translated once. Teeing beats emitting
diff --git a/cli/src/core/api.spec.ts b/cli/src/core/api.spec.ts
index 3184e6266..cfa005a16 100644
--- a/cli/src/core/api.spec.ts
+++ b/cli/src/core/api.spec.ts
@@ -11,6 +11,7 @@ describe('the core API services stand on', () => {
registry: {
list: vi.fn(() => [row('live')]),
byAgent: vi.fn((agentId: string) => (agentId === 'live' ? row('live') : undefined)),
+ advertised: vi.fn(() => [row('live')]),
terminalAvailable: vi.fn((agentId: string) => agentId === 'live'),
} as unknown as CoreApiDeps['registry'],
stoppedAgents: { list: vi.fn(() => [row('stopped')]) } as unknown as CoreApiDeps['stoppedAgents'],
@@ -19,10 +20,14 @@ describe('the core API services stand on', () => {
openSessions: { known: vi.fn(), fresh: vi.fn() } as unknown as CoreApiDeps['openSessions'],
syncSession: vi.fn(),
viewerChanged: vi.fn(),
+ gridNamed: vi.fn(),
+ mintGridName: vi.fn(async () => 'grid-1'),
+ accessToken: vi.fn(async () => 'token'),
}
const core = createCoreApi(deps)
expect(core.dataDir).toBe('/data')
expect(core.agents.all().map((s) => s.agentId)).toEqual(['live', 'stopped'])
+ expect(core.agents.live().map((s) => s.agentId)).toEqual(['live'])
expect(core.agents.displayName).toBe(projectDisplayName)
expect(core.transcripts.databaseHistory).toBe(deps.databaseHistory)
expect(core.external.sessions).toBe(deps.externalSessions)
@@ -32,10 +37,14 @@ describe('the core API services stand on', () => {
expect(core.agents.terminalAvailable('live')).toBe(true)
expect(core.agents.sync).toBe(deps.syncSession)
expect(core.clients.viewerChanged).toBe(deps.viewerChanged)
+ expect(core.agents.advertised().map((s) => s.agentId)).toEqual(['live'])
+ expect(core.clients.gridNamed).toBe(deps.gridNamed)
+ expect(core.account.mintGridName).toBe(deps.mintGridName)
+ expect(core.account.accessToken).toBe(deps.accessToken)
})
it('starts with every port empty: a service fills its own when it starts', () => {
- expect(emptyPorts()).toEqual({ search: null, viewers: null })
+ expect(emptyPorts()).toEqual({ search: null, viewers: null, models: null, workspaces: null })
expect(emptyPorts()).not.toBe(emptyPorts())
})
})
diff --git a/cli/src/core/api.ts b/cli/src/core/api.ts
index b95764e93..7396b13fe 100644
--- a/cli/src/core/api.ts
+++ b/cli/src/core/api.ts
@@ -8,6 +8,8 @@
* never a generic `call(name, args)`.
*/
import type { AgentDshContext } from '../lib/agentFrame.js'
+import type { GridAccess } from '../lib/gridAttach.js'
+import type { AgentGridTarget } from '../lib/gridModels.js'
import type { LiveEvent } from '../lib/normalize.js'
import { projectDisplayName, type registry, type RegisteredSession } from '../lib/registry.js'
import type { ExternalSessions, OpenSessions } from '../lib/sessionSearch/external.js'
@@ -20,10 +22,14 @@ export interface CoreApi {
agents: {
/** Every agent on this machine: the live ones, then the stopped ones. */
all(): RegisteredSession[]
+ /** The live agents. */
+ live(): RegisteredSession[]
/** The name the apps show for an agent. */
displayName(session: RegisteredSession): string
/** A live agent, by its agent id. */
byAgent(agentId: string): RegisteredSession | undefined
+ /** The live agents the apps are shown. */
+ advertised(): RegisteredSession[]
/** Whether the agent's terminal is attached: a frame without one reads to the apps as "agent gone". */
terminalAvailable(agentId: string): boolean
/** Send the agent's frame to the apps again. */
@@ -39,9 +45,19 @@ export interface CoreApi {
sessions: Pick<ExternalSessions, 'list' | 'scan'>
open: Pick<OpenSessions, 'known' | 'fresh'>
}
+ /** The sign-in the core holds for every service: a service never holds a credential itself. */
+ account: {
+ /** The account's private grid name, minted and remembered by the backend; null when an older
+ * backend issues none. Bounded in time. */
+ mintGridName(): Promise<string | null>
+ /** This machine's harness access token, for handing a sign-in to grid. Rejects when signed out. */
+ accessToken(): Promise<string>
+ }
clients: {
/** An agent's viewer moved: the windows' viewer panes forward to the new one. */
viewerChanged(agentId: string): void
+ /** The account's grid has a name: the models picker answers with it at once. */
+ gridNamed(name: string): void
}
}
@@ -65,42 +81,71 @@ export interface ViewersPort {
stop(): Promise<void>
}
+/** The core's calls into models (grid): have grid ready, whether it is set up, and the two things
+ * the core tells it — someone is typing to an agent on a grid, and the sign-in ended. */
+export interface ModelsPort {
+ /** Have grid ready for what the caller is about to do; resolves with what happened, never rejects. */
+ ensure: GridAccess['ensure']
+ /** Offline: is there a `grid` here holding a sign-in? */
+ setUp(): boolean
+ /** Start the agent's sleeping grid while someone types to it. */
+ prewarm(grid: AgentGridTarget): void
+ /** The sign-in ended: drop what lives exactly as long as it. */
+ signedOut(): void
+}
+
+/** The core's calls into workspaces: name made-up worktree branches after their sessions, on each
+ * terminal-title pass, and sweep the worktrees nothing uses, when the core says it is time. */
+export interface WorkspacesPort {
+ nameBranches(): void
+ sweepUnused(): void
+}
+
/** Each port is filled by the service that owns it when that service starts, and is null while the
* service is off: the core never waits on one. */
export interface CorePorts {
search: SearchPort | null
viewers: ViewersPort | null
+ models: ModelsPort | null
+ workspaces: WorkspacesPort | null
}
export function emptyPorts(): CorePorts {
- return { search: null, viewers: null }
+ return { search: null, viewers: null, models: null, workspaces: null }
}
export interface CoreApiDeps {
dataDir: string
- registry: Pick<typeof registry, 'list' | 'byAgent' | 'terminalAvailable'>
+ registry: Pick<typeof registry, 'list' | 'byAgent' | 'advertised' | 'terminalAvailable'>
stoppedAgents: Pick<StoppedAgentStore, 'list'>
databaseHistory: CoreApi['transcripts']['databaseHistory']
externalSessions: CoreApi['external']['sessions']
openSessions: CoreApi['external']['open']
syncSession: CoreApi['agents']['sync']
viewerChanged: CoreApi['clients']['viewerChanged']
+ gridNamed: CoreApi['clients']['gridNamed']
+ mintGridName: CoreApi['account']['mintGridName']
+ accessToken: CoreApi['account']['accessToken']
}
export function createCoreApi({
dataDir, registry, stoppedAgents, databaseHistory, externalSessions, openSessions, syncSession, viewerChanged,
+ gridNamed, mintGridName, accessToken,
}: CoreApiDeps): CoreApi {
return {
dataDir,
agents: {
all: () => [...registry.list(), ...stoppedAgents.list()],
+ live: () => registry.list(),
displayName: projectDisplayName,
byAgent: (agentId) => registry.byAgent(agentId),
+ advertised: () => registry.advertised(),
terminalAvailable: (agentId) => registry.terminalAvailable(agentId),
sync: syncSession,
},
transcripts: { databaseHistory },
external: { sessions: externalSessions, open: openSessions },
- clients: { viewerChanged },
+ account: { mintGridName, accessToken },
+ clients: { viewerChanged, gridNamed },
}
}
diff --git a/cli/src/services/models.spec.ts b/cli/src/services/models.spec.ts
new file mode 100644
index 000000000..f7dbb6a24
--- /dev/null
+++ b/cli/src/services/models.spec.ts
@@ -0,0 +1,175 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { emptyPorts, type ModelsPort } from '../core/api.js'
+import { createGridAccess, gridNamesLocal, reconcileGridAttach } from '../lib/gridAttach.js'
+import { resetGridDeriveMemo, signedInGridEmail } from '../lib/gridDerive.js'
+import { ensureHarnessGrid } from '../lib/gridEnsure.js'
+import { gridAvailable } from '../lib/gridExec.js'
+import { handOffToGrid } from '../lib/gridHandoff.js'
+import { ensureGridInstalled } from '../lib/gridInstall.js'
+import { clearGridMcpUrlCache } from '../lib/gridMcpUrl.js'
+import { forgetGridModels, gridAnnotation, keystrokePrewarm, onGridModelsChanged, warmGridModels } from '../lib/gridModels.js'
+import type { RegisteredSession } from '../lib/registry.js'
+import { ensureManagedGrid } from '../lib/runtimeInstall.js'
+import { fakeCore } from '../testing/fakeCore.js'
+import { startModels } from './models.js'
+
+const access = vi.hoisted(() => ({ ensure: vi.fn(async () => ({ status: 'converged', name: 'grid-1', detail: 'ok' })) }))
+vi.mock('../lib/gridAttach.js', () => ({
+ createGridAccess: vi.fn(() => access),
+ gridNamesLocal: vi.fn(() => ['grid-1']),
+ reconcileGridAttach: vi.fn(async () => ({ status: 'signed-in', name: 'grid-1', detail: 'ok' })),
+}))
+vi.mock('../lib/gridDerive.js', () => ({ resetGridDeriveMemo: vi.fn(), signedInGridEmail: vi.fn(() => '[email protected]') }))
+vi.mock('../lib/gridEnsure.js', () => ({ ensureHarnessGrid: vi.fn(async () => 'converged') }))
+vi.mock('../lib/gridExec.js', () => ({ gridAvailable: vi.fn(() => true) }))
+vi.mock('../lib/gridHandoff.js', () => ({ handOffToGrid: vi.fn(async () => ({ ok: true })) }))
+vi.mock('../lib/gridInstall.js', () => ({ ensureGridInstalled: vi.fn(async () => ({ status: 'present', message: '' })) }))
+vi.mock('../lib/gridMcpUrl.js', () => ({ clearGridMcpUrlCache: vi.fn() }))
+vi.mock('../lib/gridModels.js', () => ({
+ forgetGridModels: vi.fn(),
+ gridAnnotation: vi.fn((grid: { state: string }) => ({ state: grid.state })),
+ keystrokePrewarm: vi.fn(async () => 'started'),
+ onGridModelsChanged: vi.fn(),
+ warmGridModels: vi.fn(async () => {}),
+}))
+vi.mock('../lib/runtimeInstall.js', () => ({ ensureManagedGrid: vi.fn(async () => {}) }))
+
+type AttemptDeps = Parameters<typeof reconcileGridAttach>[0]
+const onGrid = (agentId: string, state: string) => ({ agentId, grid: { state } }) as unknown as RegisteredSession
+
+function setup(advertised: RegisteredSession[] = []) {
+ const list = [...advertised]
+ const core = fakeCore({ agents: { advertised: vi.fn(() => list), sync: vi.fn() } })
+ const ports = emptyPorts()
+ startModels(core, ports)
+ const options = vi.mocked(createGridAccess).mock.calls.at(-1)![0]
+ const changed = vi.mocked(onGridModelsChanged).mock.calls.at(-1)![0]
+ return { core, list, port: ports.models as ModelsPort, options, changed }
+}
+
+/** The reconcile deps the access attempt builds, for one attempt. */
+async function attemptDeps(options: ReturnType<typeof setup>['options']): Promise<AttemptDeps> {
+ await options.attempt({ ownGrid: true, signedInThisRun: false })
+ const [deps, request] = vi.mocked(reconcileGridAttach).mock.calls.at(-1)!
+ expect(request).toEqual({ ownGrid: true, signedInThisRun: false })
+ return deps
+}
+
+describe('the models service', () => {
+ beforeEach(() => { vi.spyOn(console, 'log').mockImplementation(() => {}) })
+ afterEach(() => { vi.restoreAllMocks(); vi.clearAllMocks() })
+
+ describe('grid access, on first use', () => {
+ it('knows grid holds a sign-in from the file grid keeps, and logs as grid-attach', () => {
+ const { options } = setup()
+ expect(options.signedIn()).toBe(true)
+ vi.mocked(signedInGridEmail).mockReturnValueOnce(null)
+ expect(options.signedIn()).toBe(false)
+ options.log('attached')
+ expect(console.log).toHaveBeenCalledWith('[grid-attach] attached')
+ })
+
+ it('installs the pinned managed runtime first, and grid\'s own installer only when there is none', async () => {
+ const deps = await attemptDeps(setup().options)
+ await deps.installCli()
+ const [runtimeLog] = vi.mocked(ensureManagedGrid).mock.calls[0]
+ runtimeLog!('pinned 1.2.3')
+ expect(console.log).toHaveBeenCalledWith('[grid-runtime] pinned 1.2.3')
+ expect(ensureGridInstalled).not.toHaveBeenCalled()
+ vi.mocked(gridAvailable).mockReturnValueOnce(false)
+ await deps.installCli()
+ expect(ensureGridInstalled).toHaveBeenCalledTimes(1)
+ expect(console.log).not.toHaveBeenCalledWith(expect.stringContaining('[grid-attach]'))
+ vi.mocked(gridAvailable).mockReturnValueOnce(false)
+ vi.mocked(ensureGridInstalled).mockResolvedValueOnce({ status: 'failed', message: 'no network' } as never)
+ await deps.installCli()
+ expect(console.log).toHaveBeenCalledWith('[grid-attach] no network')
+ })
+
+ it('asks the core for the grid name and the token, and grid for the rest', async () => {
+ const { core, options } = setup()
+ const deps = await attemptDeps(options)
+ expect(deps.gridAvailable()).toBe(true)
+ expect(await deps.mintName()).toBeNull()
+ expect(core.account.mintGridName).toHaveBeenCalled()
+ expect(await deps.accessToken()).toBe('token')
+ expect(deps.signedInEmail()).toBe('[email protected]')
+ expect(deps.gridNames()).toEqual(['grid-1'])
+ expect(gridNamesLocal).toHaveBeenCalled()
+ await deps.handoff('t1')
+ expect(handOffToGrid).toHaveBeenCalledWith('t1', { json: true })
+ await deps.ensure('grid-1')
+ expect(ensureHarnessGrid).toHaveBeenCalledWith('grid-1')
+ deps.log('handed off')
+ expect(console.log).toHaveBeenCalledWith('[grid-attach] handed off')
+ })
+
+ it('once the account\'s grid has a name, answers the picker with it and drops what a stale sign-in filled', async () => {
+ const { core, options } = setup()
+ const deps = await attemptDeps(options)
+ deps.onName('grid-7')
+ expect(core.clients.gridNamed).toHaveBeenCalledWith('grid-7')
+ expect(forgetGridModels).toHaveBeenCalled()
+ expect(resetGridDeriveMemo).toHaveBeenCalled()
+ expect(clearGridMcpUrlCache).toHaveBeenCalled()
+ })
+ })
+
+ describe('the model pictures on agents\' frames', () => {
+ it('pushes again the frames of agents on a grid whose annotation moved, only those and only when it moved', () => {
+ const plain = { agentId: 'plain' } as RegisteredSession
+ const { core, list, changed } = setup([onGrid('a1', 'awake'), onGrid('a2', 'asleep'), plain])
+ changed()
+ expect(core.agents.sync).toHaveBeenCalledTimes(2)
+ changed()
+ expect(core.agents.sync).toHaveBeenCalledTimes(2)
+ list[0] = onGrid('a1', 'asleep')
+ changed()
+ expect(core.agents.sync).toHaveBeenCalledTimes(3)
+ expect(core.agents.sync).toHaveBeenLastCalledWith(list[0])
+ expect(gridAnnotation).not.toHaveBeenCalledWith(undefined)
+ })
+
+ it('forgets an agent that left a grid, so its next appearance is announced', () => {
+ const { core, list, changed } = setup([onGrid('a1', 'awake')])
+ changed()
+ list.length = 0
+ changed()
+ list.push(onGrid('a1', 'awake'))
+ changed()
+ expect(core.agents.sync).toHaveBeenCalledTimes(2)
+ })
+
+ it('brings back the saved pictures at start, and a failure to is not fatal', async () => {
+ vi.mocked(warmGridModels).mockRejectedValueOnce(new Error('unreadable'))
+ setup()
+ expect(warmGridModels).toHaveBeenCalled()
+ await Promise.resolve()
+ })
+ })
+
+ describe('its port', () => {
+ it('has grid ready through the one access, and says offline whether grid is set up', async () => {
+ const { port } = setup()
+ expect(await port.ensure({ ownGrid: true })).toMatchObject({ status: 'converged' })
+ expect(access.ensure).toHaveBeenCalledWith({ ownGrid: true })
+ expect(port.setUp()).toBe(true)
+ vi.mocked(signedInGridEmail).mockReturnValueOnce(null)
+ expect(port.setUp()).toBe(false)
+ vi.mocked(gridAvailable).mockReturnValueOnce(false)
+ expect(port.setUp()).toBe(false)
+ })
+
+ it('starts a sleeping grid while someone types, ignoring a prewarm that fails, and forgets the web tools on sign-out', async () => {
+ const { port } = setup()
+ const grid = { networkId: 'n1', model: 'big' } as never
+ port.prewarm(grid)
+ expect(keystrokePrewarm).toHaveBeenCalledWith(grid)
+ vi.mocked(keystrokePrewarm).mockRejectedValueOnce(new Error('asleep'))
+ port.prewarm(grid)
+ await Promise.resolve()
+ port.signedOut()
+ expect(clearGridMcpUrlCache).toHaveBeenCalledTimes(1)
+ })
+ })
+})
diff --git a/cli/src/services/models.ts b/cli/src/services/models.ts
new file mode 100644
index 000000000..cba4fc9f9
--- /dev/null
+++ b/cli/src/services/models.ts
@@ -0,0 +1,88 @@
+/**
+ * Models: grid, how Harness runs local AI models with Codex, Claude Code and the other engines
+ * (docs/design/2026-10-03-harnessd.md, "Models"). Grid access on first use, the model pictures an
+ * agent's frame carries, and starting a sleeping grid while someone types to its agent.
+ *
+ * A service on the core boundary (step 13): it reads the core only through `CoreApi`, and the core
+ * reaches it only through `ports.models`.
+ */
+import type { CoreApi, CorePorts } from '../core/api.js'
+import { createGridAccess, gridNamesLocal, reconcileGridAttach } from '../lib/gridAttach.js'
+import { resetGridDeriveMemo, signedInGridEmail } from '../lib/gridDerive.js'
+import { ensureHarnessGrid } from '../lib/gridEnsure.js'
+import { gridAvailable } from '../lib/gridExec.js'
+import { handOffToGrid } from '../lib/gridHandoff.js'
+import { ensureGridInstalled } from '../lib/gridInstall.js'
+import { clearGridMcpUrlCache } from '../lib/gridMcpUrl.js'
+import { forgetGridModels, gridAnnotation, keystrokePrewarm, onGridModelsChanged, warmGridModels } from '../lib/gridModels.js'
+import { ensureManagedGrid } from '../lib/runtimeInstall.js'
+
+export function startModels(core: CoreApi, ports: CorePorts): void {
+ // Grid is an add-on (`lib/gridAttach.ts`): nothing on this path installs `grid`, signs this machine in
+ // to it or creates a grid. The first grid feature a person uses — the models picker's Set up, a local
+ // model's Get or Use, an agent moved onto a grid model, the Model Manager — asks `ports.models.ensure`,
+ // which does it then, with this machine's harness token (no second browser) and, only for what needs
+ // one, the account's own grid. It used to run here on every start and every reconnect.
+ const gridLog = (line: string): void => console.log(`[grid-attach] ${line}`)
+ const gridAccess = createGridAccess({
+ signedIn: () => signedInGridEmail() !== null,
+ log: gridLog,
+ attempt: ({ ownGrid, signedInThisRun }) => reconcileGridAttach({
+ // The pinned managed runtime first; grid's own installer when there is none to follow.
+ installCli: async () => {
+ await ensureManagedGrid((m) => console.log(`[grid-runtime] ${m}`))
+ if (gridAvailable()) return
+ const installed = await ensureGridInstalled()
+ if (installed.status !== 'present') gridLog(installed.message)
+ },
+ gridAvailable: () => gridAvailable(),
+ // The backend mints and remembers the name, through the core, which holds the sign-in.
+ mintName: () => core.account.mintGridName(),
+ accessToken: () => core.account.accessToken(),
+ signedInEmail: () => signedInGridEmail(),
+ gridNames: () => gridNamesLocal(),
+ handoff: (token) => handOffToGrid(token, { json: true }),
+ ensure: (name) => ensureHarnessGrid(name),
+ onName: (name) => {
+ // Answer the picker with this account's grid at once, and drop the memos a stale or absent
+ // sign-in may have filled — the model list, the derived name, and the web-tools URL.
+ core.clients.gridNamed(name)
+ forgetGridModels()
+ resetGridDeriveMemo()
+ clearGridMcpUrlCache()
+ },
+ log: gridLog,
+ }, { ownGrid, signedInThisRun }),
+ })
+
+ // An agent's frame says what its grid's picture says (`grid.state`, and a `grid.note` when its model
+ // will not answer). The picture changes on reads nobody waited for, so the frames of the agents whose
+ // annotation moved are pushed again — only those, and only when it moved.
+ const announcedGrid = new Map<string, string>()
+ onGridModelsChanged(() => {
+ const onGrid = core.agents.advertised().filter((s) => s.grid)
+ const present = new Set(onGrid.map((s) => s.agentId))
+ for (const agentId of [...announcedGrid.keys()]) if (!present.has(agentId)) announcedGrid.delete(agentId)
+ for (const s of onGrid) {
+ const said = JSON.stringify(gridAnnotation(s.grid))
+ if (announcedGrid.get(s.agentId) === said) continue
+ announcedGrid.set(s.agentId, said)
+ core.agents.sync(s)
+ }
+ })
+ // The pictures saved before this start, back in memory with nothing read from any grid: an agent's
+ // frame carries its grid's state and note, and a keystroke can start its grid, before any window asks
+ // for the list (after a self-update, a phone may be the only one typing).
+ void warmGridModels().catch(() => {})
+ ports.models = {
+ ensure: (request) => gridAccess.ensure(request),
+ // Offline, for every list read: is there a `grid` here holding a sign-in? What decides whether the
+ // picker offers local and shared models or a Set up row.
+ setUp: () => gridAvailable() && signedInGridEmail() !== null,
+ // The keystroke prewarm (grid-reads-without-waking issue 03): typing into a pane whose agent runs on
+ // a sleeping grid starts that grid while the person types.
+ prewarm: (grid) => { void keystrokePrewarm(grid).catch(() => {}) },
+ // The web-tools cache lives exactly as long as the sign-in.
+ signedOut: () => clearGridMcpUrlCache(),
+ }
+}
diff --git a/cli/src/services/workspaces.spec.ts b/cli/src/services/workspaces.spec.ts
new file mode 100644
index 000000000..b62553638
--- /dev/null
+++ b/cli/src/services/workspaces.spec.ts
@@ -0,0 +1,100 @@
+import { homedir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { emptyPorts, type WorkspacesPort } from '../core/api.js'
+import { forgetAgentProject } from '../lib/agentProject.js'
+import { nameBranchAfterSession } from '../lib/branchNaming.js'
+import type { RegisteredSession } from '../lib/registry.js'
+import { sweepWorktrees } from '../lib/worktreeSweep.js'
+import { fakeCore } from '../testing/fakeCore.js'
+import { startWorkspaces } from './workspaces.js'
+
+// Nothing here may touch a real folder or a real repository: the sweep and the rename are fakes.
+vi.mock('../lib/worktreeSweep.js', () => ({ sweepWorktrees: vi.fn(async () => []) }))
+vi.mock('../lib/branchNaming.js', () => ({ nameBranchAfterSession: vi.fn(async () => null) }))
+vi.mock('../lib/agentProject.js', () => ({ forgetAgentProject: vi.fn() }))
+vi.mock('../lib/registry.js', async (real) => ({
+ ...await real<object>(),
+ sessionDisplayTitle: vi.fn((s: { title?: string }) => s.title ?? null),
+}))
+
+const agent = (over: Partial<RegisteredSession>) => ({ agentId: 'a1', sessionId: 's1', cwd: '/work/tree', title: 'Fix login', ...over }) as RegisteredSession
+const settle = () => new Promise((resolve) => setImmediate(resolve))
+
+function setup(live: RegisteredSession[] = [], all: RegisteredSession[] = live, current: RegisteredSession | null = live[0] ?? null) {
+ const core = fakeCore({
+ agents: { live: vi.fn(() => live), all: vi.fn(() => all), byAgent: vi.fn(() => current ?? undefined), sync: vi.fn() },
+ })
+ const ports = emptyPorts()
+ startWorkspaces(core, ports)
+ return { core, port: ports.workspaces as WorkspacesPort }
+}
+
+describe('the workspaces service', () => {
+ beforeEach(() => { vi.spyOn(console, 'log').mockImplementation(() => {}) })
+ afterEach(() => { vi.restoreAllMocks(); vi.clearAllMocks() })
+
+ describe('naming made-up branches after their sessions', () => {
+ it('renames once per agent, then forgets the cached project and re-sends the agent\'s frame', async () => {
+ vi.mocked(nameBranchAfterSession).mockResolvedValueOnce('fix-login')
+ const { core, port } = setup([agent({})])
+ port.nameBranches()
+ await settle()
+ expect(nameBranchAfterSession).toHaveBeenCalledWith('/work/tree', 'Fix login')
+ expect(console.log).toHaveBeenCalledWith('[worktrees] agent a1 branch named fix-login')
+ expect(forgetAgentProject).toHaveBeenCalledWith('/work/tree')
+ expect(core.agents.sync).toHaveBeenCalledWith(agent({}))
+ port.nameBranches()
+ expect(nameBranchAfterSession).toHaveBeenCalledTimes(1)
+ })
+
+ it('leaves alone a branch that keeps its name, and an agent that left meanwhile', async () => {
+ const kept = setup([agent({})])
+ kept.port.nameBranches()
+ await settle()
+ expect(forgetAgentProject).not.toHaveBeenCalled()
+ vi.mocked(nameBranchAfterSession).mockResolvedValueOnce('fix-login')
+ const gone = setup([agent({})], [], null)
+ gone.port.nameBranches()
+ await settle()
+ expect(forgetAgentProject).toHaveBeenCalled()
+ expect(gone.core.agents.sync).not.toHaveBeenCalled()
+ })
+
+ it('waits for a title and a folder, and survives a rename that fails', async () => {
+ vi.mocked(nameBranchAfterSession).mockRejectedValueOnce(new Error('not a git repo'))
+ const { port } = setup([agent({ agentId: 'untitled', title: undefined }), agent({ agentId: 'nowhere', cwd: undefined }), agent({})])
+ port.nameBranches()
+ await settle()
+ expect(nameBranchAfterSession).toHaveBeenCalledTimes(1)
+ expect(nameBranchAfterSession).toHaveBeenCalledWith('/work/tree', 'Fix login')
+ })
+ })
+
+ describe('sweeping unused worktrees', () => {
+ it('keeps every folder a live or stopped harness uses, and says how many it removed', async () => {
+ vi.mocked(sweepWorktrees).mockResolvedValueOnce(['/h/old-1', '/h/old-2'] as never)
+ const { port } = setup([agent({ cwd: '/h/live' })], [agent({ cwd: '/h/live' }), agent({ agentId: 'stopped', cwd: null as never })])
+ port.sweepUnused()
+ await settle()
+ expect(sweepWorktrees).toHaveBeenCalledWith({ root: join(homedir(), 'harnesses'), inUse: ['/h/live', null] })
+ expect(console.log).toHaveBeenCalledWith('[worktrees] removed 2 unused worktree(s)')
+ })
+
+ it('says nothing when it removed nothing, and nothing when the sweep fails', async () => {
+ const { port } = setup()
+ port.sweepUnused()
+ vi.mocked(sweepWorktrees).mockRejectedValueOnce(new Error('EACCES'))
+ port.sweepUnused()
+ await settle()
+ expect(console.log).not.toHaveBeenCalled()
+ })
+
+ 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') })
+ port.sweepUnused()
+ expect(sweepWorktrees).not.toHaveBeenCalled()
+ })
+ })
+})
diff --git a/cli/src/services/workspaces.ts b/cli/src/services/workspaces.ts
new file mode 100644
index 000000000..6abeb6037
--- /dev/null
+++ b/cli/src/services/workspaces.ts
@@ -0,0 +1,48 @@
+/**
+ * Workspaces: everything about the folder an agent works in (docs/design/2026-10-03-harnessd.md,
+ * "Workspaces"). Here so far: a worktree branch Harness made up takes its session's name, and the
+ * worktrees Harness made that nothing uses are swept.
+ *
+ * A service on the core boundary (step 13): it reads the core only through `CoreApi`, and the core
+ * reaches it only through `ports.workspaces`.
+ */
+import { homedir } from 'node:os'
+import { join } from 'node:path'
+import type { CoreApi, CorePorts } from '../core/api.js'
+import { forgetAgentProject } from '../lib/agentProject.js'
+import { nameBranchAfterSession } from '../lib/branchNaming.js'
+import { sid } from '../lib/log.js'
+import { sessionDisplayTitle } from '../lib/registry.js'
+import { sweepWorktrees } from '../lib/worktreeSweep.js'
+
+export function startWorkspaces(core: CoreApi, ports: CorePorts): void {
+ // A worktree branch Harness made up at Start takes its session's name once it has one
+ // (lib/branchNaming.ts). Each agent is looked at once per daemon; the git reads are the cost.
+ const branchNamed = new Set<string>()
+ const nameSessionBranches = (): void => {
+ for (const session of core.agents.live()) {
+ const title = sessionDisplayTitle(session)
+ if (!title || !session.cwd || branchNamed.has(session.agentId)) continue
+ branchNamed.add(session.agentId)
+ const cwd = session.cwd
+ void nameBranchAfterSession(cwd, title).then((renamed) => {
+ if (!renamed) return
+ console.log(`[worktrees] agent ${sid(session.agentId)} branch named ${renamed}`)
+ forgetAgentProject(cwd)
+ const current = core.agents.byAgent(session.agentId)
+ if (current) core.agents.sync(current)
+ }).catch(() => {})
+ }
+ }
+ // 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.
+ const sweepUnusedWorktrees = () => {
+ let inUse: Array<string | null>
+ try { inUse = core.agents.all().map(s => s.cwd) } catch { return }
+ void sweepWorktrees({ root: join(homedir(), 'harnesses'), inUse })
+ .then(removed => { if (removed.length) console.log(`[worktrees] removed ${removed.length} unused worktree(s)`) })
+ .catch(() => {})
+ }
+ ports.workspaces = { nameBranches: nameSessionBranches, sweepUnused: sweepUnusedWorktrees }
+}
diff --git a/cli/src/testing/fakeCore.ts b/cli/src/testing/fakeCore.ts
index f279864fb..777ec4f40 100644
--- a/cli/src/testing/fakeCore.ts
+++ b/cli/src/testing/fakeCore.ts
@@ -13,8 +13,10 @@ export function fakeCore(over: Overrides = {}): CoreApi {
dataDir: over.dataDir ?? '/data',
agents: {
all: vi.fn(() => []),
+ live: vi.fn(() => []),
displayName: vi.fn(() => ''),
byAgent: vi.fn(() => undefined),
+ advertised: vi.fn(() => []),
terminalAvailable: vi.fn(() => false),
sync: vi.fn(),
...over.agents,
@@ -25,6 +27,7 @@ export function fakeCore(over: Overrides = {}): CoreApi {
open: { known: vi.fn(() => new Map()), fresh: vi.fn(async () => new Map()) },
...over.external,
},
- clients: { viewerChanged: vi.fn(), ...over.clients },
+ account: { mintGridName: vi.fn(async () => null), accessToken: vi.fn(async () => 'token'), ...over.account },
+ clients: { viewerChanged: vi.fn(), gridNamed: vi.fn(), ...over.clients },
}
}
diff --git a/docs/design/2026-10-03-harnessd.md b/docs/design/2026-10-03-harnessd.md
index aeae57621..2c1979b36 100644
--- a/docs/design/2026-10-03-harnessd.md
+++ b/docs/design/2026-10-03-harnessd.md
@@ -399,12 +399,14 @@ Done so far:
fork, the pane swap, retarget, restart, stop, purge, resume, close) and the engines' hooks (which
agent a hook belongs to, Cursor's Task hooks, installing every engine's hooks). Each file is held
to 100% by `npm run test:core`, which CI runs; the unit and e2e suites pass at every step.
-- **Services in process, the first two** (step 13, part 8): `cli/src/core/api.ts` holds the
- boundary itself. `CoreApi` is what a service may ask of the core; `CorePorts` is what the core
- asks of services, each port filled by its service when it starts and null while it is off, so
- the core never waits on one. Session search (`services/search.ts`) and the DSH viewers
- (`services/viewers.ts`) stand on it, held to 100% beside the core. The rest of step 13 and
- step 14 remain.
+- **Services in process** (step 13, parts 8 and 9): `cli/src/core/api.ts` holds the boundary
+ itself. `CoreApi` is what a service may ask of the core; `CorePorts` is what the core asks of
+ services, each port filled by its service when it starts and null while it is off, so the core
+ never waits on one. Session search, the DSH viewers, models (grid access, the model pictures on
+ agents' frames, the keystroke prewarm) and workspaces (branch names, the worktree sweep) stand on
+ it under `cli/src/services`, held to 100% beside the core. A service holds no credential: minting
+ the grid name and the access token go through `CoreApi.account`. Relay, sharing, teams and
+ devices, and step 14, remain.
Next, in order:
@@ -473,8 +475,8 @@ start-up lint stay as they are; each is checked by `tsc`, the unit suites and th
10. Agent discovery and binding.
11. The agent lifecycle.
12. Engine hooks.
-13. Services in process, each behind `start(core, ports)`: search and viewers first, then models,
- workspaces, teams, the light host, relay and devices.
+13. Services in process, each behind `start(core, ports)`: search, viewers, models and workspaces
+ first, then relay, sharing, teams and devices.
14. One `bindBackendSocket` for all 53 assignments.
Moving the request switch's case bodies into a file per owner comes after.