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.

Portable harnesses, launch models, and a terminal-grid New Harness form (#300)

Dee9121ca2817f6
diff --git a/cli/package.json b/cli/package.json
index 712671b0f..d05090cec 100644
--- a/cli/package.json
+++ b/cli/package.json
@@ -22,7 +22,8 @@
"test:tmux-real": "RUN_REAL_TMUX_DISCOVERY=1 vitest run src/lib/tmuxAgentDiscovery.real.spec.ts --reporter=verbose",
"test:herdr-real": "RUN_REAL_HERDR=1 vitest run src/lib/herdrBackend.real.spec.ts --reporter=verbose",
"test:resume": "vitest run src/lib/sessionRepair.spec.ts src/lib/captureResumeIdentity.spec.ts src/lib/resumeStoppedAgent.spec.ts src/lib/resumeAgentService.spec.ts src/lib/stoppedAgents.spec.ts src/lib/stopAgentService.spec.ts --coverage --coverage.include=src/lib/captureResumeIdentity.ts --coverage.include=src/lib/resumeStoppedAgent.ts --coverage.include=src/lib/resumeAgentService.ts --coverage.include=src/lib/stoppedAgents.ts --coverage.include=src/lib/stopAgentService.ts --coverage.thresholds.lines=100 --coverage.thresholds.statements=100 --coverage.thresholds.branches=100 --coverage.thresholds.functions=100 --coverage.reporter=text --coverage.reporter=json --coverage.reportsDirectory=coverage/resume",
- "test:resume-native": "tsx scripts/resume-native-e2e.ts"
+ "test:resume-native": "tsx scripts/resume-native-e2e.ts",
+ "test:portability": "vitest run --config vitest.portability.config.ts"
},
"dependencies": {
"@noble/ciphers": "^1.3.0",
diff --git a/cli/scripts/lib/dshRegistry.mjs b/cli/scripts/lib/dshRegistry.mjs
index b45f38d3c..34460b433 100644
--- a/cli/scripts/lib/dshRegistry.mjs
+++ b/cli/scripts/lib/dshRegistry.mjs
@@ -7,6 +7,11 @@ import { readdirSync, readFileSync, statSync } from 'fs'
import { join } from 'path'
import { fileURLToPath } from 'url'
+const engineSource = readFileSync(new URL('../../src/engines/types.ts', import.meta.url), 'utf8')
+const engineList = engineSource.match(/export const ENGINES = \[([\s\S]*?)\] as const/)
+if (!engineList) throw new Error('Cannot read the canonical engine list')
+const processEngines = [...engineList[1].matchAll(/'([^']+)'/g)].map(match => match[1]).filter(engine => engine !== 'terminal')
+
const HARNESS_MONOREPO = 'https://github.com/autonomous-ai/openharness'
export function storeEntry(path, manifest, facts) {
@@ -16,6 +21,8 @@ export function storeEntry(path, manifest, facts) {
Object.assign(entry, { repo: HARNESS_MONOREPO, ref: 'main', path })
for (const key of ['homepage', 'upstream', 'license', 'tagline', 'screenshots', 'examples']) if (facts[key] !== undefined) entry[key] = facts[key]
if (manifest.engine !== undefined) entry.engine = manifest.engine
+ if (manifest.engine !== undefined) entry.engines = manifest.kind === 'viewer' || manifest.engine === 'terminal'
+ ? [] : [manifest.engine, ...processEngines.filter(engine => engine !== manifest.engine)]
if (typeof manifest.viewer?.use === 'string') entry.viewerUse = manifest.viewer.use
entry.tier = manifest.viewer ? 2 : manifest.verdict ? 1 : 0
entry.verified = true
diff --git a/cli/src/backendSocket.dsh.spec.ts b/cli/src/backendSocket.dsh.spec.ts
index 76fe8cf35..babc8ca0c 100644
--- a/cli/src/backendSocket.dsh.spec.ts
+++ b/cli/src/backendSocket.dsh.spec.ts
@@ -36,6 +36,24 @@ describe('the DSH requests on the local socket', () => {
const ask = (type: string, payload: Record<string, unknown>): void => socket.handleLocalFrame('local:store', { type, payload })
const replies = (type: string): Array<Record<string, unknown>> => frames.filter((frame) => frame.type === `${type}_result`).map((frame) => frame.payload)
+ it('agent_create accepts a legacy harness on another engine and refuses a terminal', async () => {
+ const dir = dshInstallDir('acme/thing')
+ mkdirSync(dir, { recursive: true })
+ const manifest = { spec: 1, id: 'acme/thing', name: 'Thing', engine: 'claude' }
+ writeFileSync(join(dir, 'harness.json'), JSON.stringify(manifest))
+ upsertInstalledRecord({ id: 'acme/thing', dir, source: dir, ref: null, commit: null, linked: true, installedAt: 1 })
+ const create = vi.fn<NonNullable<BackendSocket['onCreateAgent']>>(async () => ({ ok: false, error: 'TEST_STOP' }))
+ socket.onCreateAgent = create
+ ask('agent_create', { requestId: 'legacy', dsh: 'acme/thing', engine: 'terminal', cwd: root })
+ await vi.waitFor(() => expect(replies('agent_create')).toHaveLength(1))
+ expect(replies('agent_create')[0]).toMatchObject({ error: 'INVALID_DSH' })
+ expect(create).not.toHaveBeenCalled()
+ ask('agent_create', { requestId: 'compatible', dsh: 'acme/thing', engine: 'codex', cwd: root })
+ await vi.waitFor(() => expect(replies('agent_create')).toHaveLength(2))
+ expect(create).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ engine: 'codex', dsh: 'acme/thing', cwd: root }))
+ expect(replies('agent_create')[1]).toMatchObject({ error: 'TEST_STOP' })
+ })
+
it('dsh_list: what is installed here, then what the registry offers', async () => {
vi.stubGlobal('__DSH_REGISTRY__', JSON.stringify([
{ id: 'acme/thing', name: 'Thing', repo: 'https://example.com/thing.git', engine: 'claude', verified: true },
diff --git a/cli/src/backendSocket.models.spec.ts b/cli/src/backendSocket.models.spec.ts
new file mode 100644
index 000000000..8c8c95e41
--- /dev/null
+++ b/cli/src/backendSocket.models.spec.ts
@@ -0,0 +1,71 @@
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+import { mkdtempSync, readFileSync, readdirSync, rmSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { BackendSocket } from './backendSocket.js'
+import { env } from './config/env.js'
+import { resolveNewAgentModel } from './lib/newAgentModel.js'
+
+vi.mock('./lib/newAgentModel.js', async (original) => ({ ...await original<typeof import('./lib/newAgentModel.js')>(), resolveNewAgentModel: vi.fn() }))
+let socket: BackendSocket, root: string, previous: string
+let frames: Array<{ type: string; payload: Record<string, unknown> }>
+const target = { networkId: 'fixture-grid', networkName: 'my-grid', baseUrl: 'https://fixture.invalid/relay/v1', apiKey: 'fixture-secret', model: 'Qwen-35B' }
+const payload = { engine: 'codex', cwd: '/tmp', gridModel: 'Qwen-35B', gridName: 'my-grid' }
+beforeEach(() => {
+ vi.resetAllMocks()
+ root = mkdtempSync(join(tmpdir(), 'launch-models-'))
+ previous = env.ADAPTER_DATA_DIR
+ env.ADAPTER_DATA_DIR = root
+ socket = new BackendSocket('token')
+ frames = []
+ socket.registerLocalClient('local:models', { sendFrame: frame => { frames.push(frame as typeof frames[number]); return true }, sendBinary: () => true })
+ socket.onCreateAgent = vi.fn(async () => ({ ok: false as const, error: 'TEST_STOP' }))
+ vi.mocked(resolveNewAgentModel).mockResolvedValue(target)
+})
+afterEach(async () => {
+ await socket.unregisterLocalClient('local:models')
+ await socket.stop()
+ env.ADAPTER_DATA_DIR = previous
+ rmSync(root, { recursive: true, force: true })
+})
+async function ask(extra: Record<string, unknown>) {
+ const requestId = String(frames.length)
+ socket.handleLocalFrame('local:models', { type: 'agent_create', payload: { ...payload, ...extra, requestId } })
+ await vi.waitFor(() => expect(frames.some(f => f.type === 'agent_create_result' && f.payload.requestId === requestId)).toBe(true))
+ return frames.find(f => f.type === 'agent_create_result' && f.payload.requestId === requestId)!.payload
+}
+it('resolves a cross-machine choice on the daemon, including clients without receipts', async () => {
+ await ask({})
+ expect(socket.onCreateAgent).toHaveBeenCalledWith(expect.objectContaining({ engine: 'codex', grid: target, cwd: '/tmp' }))
+ expect(resolveNewAgentModel).toHaveBeenCalledWith({ model: 'Qwen-35B', grid: 'my-grid' })
+ expect(JSON.stringify(frames)).not.toContain('fixture-secret')
+})
+it.each([null, new Error('private error')])('refuses resolution failure before a legacy create: %j', async value => {
+ if (value instanceof Error) vi.mocked(resolveNewAgentModel).mockRejectedValue(value)
+ else vi.mocked(resolveNewAgentModel).mockResolvedValue(value)
+ expect(await ask({})).toMatchObject({ error: 'GRID_UNAVAILABLE' })
+ expect(socket.onCreateAgent).not.toHaveBeenCalled()
+})
+it('refuses malformed model selections before creating a receipt', async () => {
+ expect(await ask({ gridName: '' })).toMatchObject({ error: 'INVALID_GRID' })
+ expect(socket.onCreateAgent).not.toHaveBeenCalled()
+ expect(resolveNewAgentModel).not.toHaveBeenCalled()
+})
+it('receipts retain semantic model identity across retries, never credentials', async () => {
+ const creationId = 'model-launch-00000001'
+ expect(await ask({ creationId })).toMatchObject({ state: 'failed', failure: { code: 'TEST_STOP' } })
+ vi.mocked(resolveNewAgentModel).mockResolvedValue({ ...target, apiKey: 'rotated-secret' })
+ expect(await ask({ creationId })).toMatchObject({ state: 'failed', failure: { code: 'TEST_STOP' } })
+ expect(socket.onCreateAgent).toHaveBeenCalledOnce()
+ expect(resolveNewAgentModel).toHaveBeenCalledOnce()
+ expect(await ask({ creationId, gridName: 'other-grid' })).toMatchObject({ error: 'CREATION_CONFLICT' })
+ const receipts = readdirSync(join(root, 'agent-creations')).map(name => readFileSync(join(root, 'agent-creations', name), 'utf8')).join('')
+ expect(receipts).not.toMatch(/fixture-secret|rotated-secret|apiKey/)
+})
+it.each([null, new Error('private error')])('records a safe model failure before folder creation: %j', async value => {
+ if (value instanceof Error) vi.mocked(resolveNewAgentModel).mockRejectedValue(value)
+ else vi.mocked(resolveNewAgentModel).mockResolvedValue(value)
+ const answer = await ask({ creationId: 'model-launch-00000002', cwd: undefined, projectSource: 'new', projectName: 'unused' })
+ expect(answer).toMatchObject({ state: 'failed', failure: { code: 'GRID_UNAVAILABLE' } })
+ expect(socket.onCreateAgent).not.toHaveBeenCalled()
+})
diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.ts
index 6cdcb61eb..8da1cbc47 100644
--- a/cli/src/backendSocket.spec.ts
+++ b/cli/src/backendSocket.spec.ts
@@ -1470,6 +1470,9 @@ describe('BackendSocket outbound queue', () => {
})
describe('desk_changed relay', () => {
+ // Other suites can leave closed sockets in the shared mock inventory. A
+ // shuffled run must send to this test's connection, not an earlier one.
+ beforeEach(() => { wsMock.instances.length = 0 })
afterEach(() => {
wsMock.instances.length = 0
vi.restoreAllMocks()
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
index 710a6b4e3..02c87a999 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -37,6 +37,7 @@ import { LocalModels } from './lib/localModels.js'
import { ApiConnections, apiConnectionsRequest } from './lib/apiConnections.js'
import { gridCapableEngines, parseGridLaunchOverride, type GridLaunchOverride } from './lib/gridLaunch.js'
import { listAllGridModels, resolveGridTarget } from './lib/gridModels.js'
+import { parseNewAgentModel, resolveNewAgentModel } from './lib/newAgentModel.js'
import { deriveHarnessGridName } from './lib/gridDerive.js'
import { AGENT_NAME_RE, FirstPromptUnsupportedError, MAX_FIRST_PROMPT_CHARS, NamedAgentUnsupportedError, permissionModeApproves, permissionModeFlags, supportsFirstPrompt, supportsNamedAgent } from './lib/engineLaunch.js'
import { readAccountUsage, type AccountUsageReading } from './lib/accountUsage.js'
@@ -57,7 +58,7 @@ import { orchestratorRequest } from './orchestrator/wire.js'
import { shellQuote } from './orchestrator/prompts.js'
import type { SessionInputDelivery } from './lib/sessionInput.js'
import { engineLabel } from './lib/agentNames.js'
-import { DSH_ID_RE } from './dsh/manifest.js'
+import { DSH_ID_RE, dshSupportedEngines } from './dsh/manifest.js'
import { refreshDshRegistry } from './dsh/catalog.js'
import type { DshInstallProgress } from './dsh/install.js'
import { dshInstallReply, dshInstallRequest, dshInstallStatus, dshListRows, dshRemoveId, dshRemoveReply } from './dsh/wire.js'
@@ -1896,6 +1897,7 @@ export class BackendSocket {
// whose retarget the daemon would refuse. An older app ignores the field; an older
// daemon omits it, which the app reads as "offer everything", as before.
localModelEngines: gridCapableEngines(),
+ supportsModelLaunch: true,
// Whether this MACHINE has a `grid` to run at all — `managed`, `path` or `missing` —
// as distinct from `gridName`, which is about the account. The Local model dialog was
// gating on the account alone and starting an agent whose second step is `grid`; this
@@ -2144,6 +2146,8 @@ export class BackendSocket {
// Absent is the ordinary case and stays indistinguishable from a client that predates grids;
// present-but-malformed is refused here rather than half-applied at launch, because an agent
// that quietly ran on the engine's own login would look like it worked.
+ const model = parseNewAgentModel(engine, payload)
+ if (model.state === 'invalid') { reply(type, requestId, { error: 'INVALID_GRID', detail: model.detail }); return }
const grid = parseGridLaunchOverride(payload.grid)
if (grid.state === 'invalid') { reply(type, requestId, { error: 'INVALID_GRID', detail: grid.reason }); return }
if (terminal && grid.state === 'ok') { reply(type, requestId, { error: 'INVALID_GRID', detail: 'a terminal has no engine to point at a grid' }); return }
@@ -2173,8 +2177,8 @@ export class BackendSocket {
if (installed.manifest.kind === 'viewer') {
reply(type, requestId, { error: 'INVALID_DSH', detail: `${payload.dsh} is a viewer package, not an agent` }); return
}
- if (installed.manifest.engine !== engine) {
- reply(type, requestId, { error: 'INVALID_DSH', detail: `${payload.dsh} runs on ${installed.manifest.engine}, not ${engine}` }); return
+ if (!dshSupportedEngines(installed.manifest).includes(engine)) {
+ reply(type, requestId, { error: 'INVALID_DSH', detail: `${payload.dsh} supports ${dshSupportedEngines(installed.manifest).join(', ')}; ${engine} is not compatible` }); return
}
dsh = installed.id
}
@@ -2232,13 +2236,19 @@ export class BackendSocket {
name,
agent,
}
+ const fingerprintInput = model.state === 'ok' ? { ...input, modelSelection: model.selection } : input
if (creationId !== undefined) {
// Reserve before spawning. A transport retry carries the SAME creationId; a deliberate
// New agent action carries a new one. Detach so a status check can pass a slow create
// on this connection, just as engines_probe is detached above.
const create = this.onCreateAgent
try {
- void this.agentCreations.run(creationId, creationFingerprint(projectFolder ? { ...input, projectFolder } : input), async () => {
+ void this.agentCreations.run(creationId, creationFingerprint(projectFolder ? { ...fingerprintInput, projectFolder } : fingerprintInput), async () => {
+ if (model.state === 'ok') {
+ const target = await resolveNewAgentModel(model.selection).catch(() => null)
+ if (!target) return { state: 'failed', error: 'GRID_UNAVAILABLE', detail: 'The selected model is unavailable. Choose another model or refresh the list.' }
+ input.grid = target
+ }
let preparedFolder: string | undefined
if (projectFolder) {
try { preparedFolder = await prepareProjectFolder(projectFolder, { label: (dsh ? installedDsh(dsh)?.manifest.name : null) ?? engineLabel(input.engine) }) }
@@ -2267,6 +2277,11 @@ export class BackendSocket {
return
}
// Clients predating receipts retain their existing response shape.
+ if (model.state === 'ok') {
+ const target = await resolveNewAgentModel(model.selection).catch(() => null)
+ if (!target) { reply(type, requestId, { error: 'GRID_UNAVAILABLE', detail: 'The selected model is unavailable. Choose another model or refresh the list.' }); return }
+ input.grid = target
+ }
const result = await this.onCreateAgent(input)
// `detail` carries the underlying cause (tmux's own message) so the person who clicked
// Create can read it, rather than having to open a log on the machine that failed.
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index cd8a0329b..e051fb827 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -107,7 +107,8 @@ import { catalogEntry } from './dsh/catalog.js'
import { removeDsh } from './dsh/install.js'
import { preTrustClaudeProject, preTrustCodexProject } from './lib/claudeTrust.js'
import { materializeWorkspace } from './dsh/materialize.js'
-import { dshLaunch, type DshAccount } from './dsh/launch.js'
+import { harnessEnvToClear, type DshAccount } from './dsh/launch.js'
+import { forkRuntimeKey, harnessLaunchOrRefusal, incompatibleHarnessEngine, prepareHarnessLaunch } from './dsh/runtime.js'
import { DshViewerManager } from './dsh/viewer.js'
import { ViewerLedger } from './dsh/viewerLedger.js'
import { DshVerdictWatcher, type DshVerdict } from './dsh/verdict.js'
@@ -4215,13 +4216,13 @@ async function runForeground(session: AuthSession | null): Promise<void> {
writeGridConfigDir,
tmuxSupportsSessionEnv,
installCodexHooks: (codexHome) => { if (!env.DISABLE_HOOK_INSTALL) installCodexHooks(hookPort, codexHome) },
- dshLaunch: (id, workspace) => {
+ dshLaunch: (id, workspace, engine, runtimeKey) => {
const installed = installedDsh(id)
if (!installed) {
- console.warn(`[dsh] ${id} is not installed on this machine · relaunching as its plain base engine`)
+ console.warn(`[dsh] ${id} is not installed on this machine · cannot restore its harness context`)
return null
}
- return dshLaunch(installed, workspace, { privateGrid: backend.gridName() })
+ return prepareHarnessLaunch(installed, workspace, engine, runtimeKey, { privateGrid: backend.gridName() })
},
}
// Whatever the source (the row itself, or a grid override the desktop just sent), the agent's DSH,
@@ -4229,7 +4230,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// agent is, or bring a pane opened as `harness-compute` back as a general session.
const relaunchOverrides = (session: RegisteredSession, source: LaunchSource = session): Promise<LaunchOverridesResult> => {
prepareApiTools(session.cwd, session.engine)
- return buildLaunchOverrides(launchOverridesDeps, session.engine, { dsh: session.dsh ?? null, cwd: session.cwd, agent: session.agent ?? null, ...source }, session.agentId)
+ return buildLaunchOverrides(launchOverridesDeps, session.engine, { dsh: session.dsh ?? null, dshRuntime: session.dshRuntime ?? null, cwd: session.cwd, agent: session.agent ?? null, ...source }, session.agentId)
}
/**
@@ -4617,8 +4618,14 @@ async function runForeground(session: AuthSession | null): Promise<void> {
console.warn(`[agent] create refused · ${engine} · ${refusal.detail}`)
return { ok: false, ...refusal }
}
- // A domain-specific harness: put its files into the workspace first (template, AGENTS.md, skill
- // links) and take its env/argv for the launch. Refused, never approximated, when it is not here.
+ // Harness-created sessions are easy to distinguish from a user's organic tmux sessions while
+ // retaining the engine and a collision-resistant creation suffix for diagnostics. Computed
+ // before the grid block because a file-configured engine keys its config directory on it.
+ // The `harness-` prefix is also discovery's whitelist (see `isHarnessSession` /
+ // `TmuxBackend.inventory()`) — every pane outside it is invisible to the daemon.
+ const label = buildHarnessSessionLabel(engine)
+ // Prepare the harness workspace, then bind its session context to the selected engine.
+ // Missing packages or invalid runtimes refuse the launch before the agent is started.
let dshEnv: Record<string, string> | undefined
let dshArgs: string[] = []
/** A DSH's own name ("Blender"), which the agent is named after instead of its engine. */
@@ -4629,8 +4636,9 @@ async function runForeground(session: AuthSession | null): Promise<void> {
const installed = installedDsh(dsh)
if (!installed) return { ok: false, error: 'INVALID_DSH', detail: `${dsh} is not installed on this machine` }
if (installed.manifest.kind === 'viewer') return { ok: false, error: 'INVALID_DSH', detail: `${dsh} is a viewer package, not an agent` }
- if (installed.manifest.engine !== engine) {
- return { ok: false, error: 'INVALID_DSH', detail: `${dsh} runs on ${installed.manifest.engine}, not ${engine}` }
+ const refusal = incompatibleHarnessEngine(dsh, installed.manifest, engine)
+ if (refusal) {
+ return { ok: false, error: 'INVALID_DSH', detail: refusal }
}
if (!(await tmuxSupportsSessionEnv())) {
const detail = `this machine's tmux is older than ${TMUX_SESSION_ENV_MIN.major}.${TMUX_SESSION_ENV_MIN.minor}, `
@@ -4641,7 +4649,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
}
try {
dshAccount = { privateGrid: await backend.privateGridName().catch(() => null) }
- const materialized = await materializeWorkspace(installed, cwd, dshAccount)
+ const materialized = await materializeWorkspace(installed, cwd, dshAccount, engine)
for (const warning of materialized.warnings) console.warn(`[dsh] ${dsh} materialize · ${warning}`)
console.log(`[dsh] ${dsh} materialized ${cwd} · created ${materialized.created.length} · kept ${materialized.kept.length}`)
// The template just went in: the folder is the harness's, and Claude Code need not ask.
@@ -4656,17 +4664,12 @@ async function runForeground(session: AuthSession | null): Promise<void> {
console.warn(`[agent] create ${dsh} refused · ${detail}`)
return { ok: false, error: 'DSH_MATERIALIZE_FAILED', detail }
}
- const launch = dshLaunch(installed, cwd, dshAccount)
- dshEnv = launch.env
- dshArgs = launch.args
+ const prepared = harnessLaunchOrRefusal(() => prepareHarnessLaunch(installed, cwd, engine, label, dshAccount))
+ if (!prepared.ok) return prepared
+ dshEnv = prepared.launch.env
+ dshArgs = prepared.launch.args
dshLabel = installed.manifest.name
}
- // Harness-created sessions are easy to distinguish from a user's organic tmux sessions while
- // retaining the engine and a collision-resistant creation suffix for diagnostics. Computed
- // before the grid block because a file-configured engine keys its config directory on it.
- // The `harness-` prefix is also discovery's whitelist (see `isHarnessSession` /
- // `TmuxBackend.inventory()`) — every pane outside it is invisible to the daemon.
- const label = buildHarnessSessionLabel(engine)
// A grid is the user's answer to "where should this run", so every way of not honouring it is a
// refusal rather than a fallback — an agent silently started on the engine's own login spends the
// wrong account and looks identical to one that worked.
@@ -4718,7 +4721,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// key wins on its own terms — OpenCode picked Anthropic over a grid it had been handed, and said
// only `invalid x-api-key`. Nothing is cleared when no grid is in play: an agent on its own login
// is supposed to use exactly these variables.
- const clearEnv = gridLaunch ? gridConflictingEnvToClear(gridLaunch) : undefined
+ const clearEnv = [...(gridLaunch ? gridConflictingEnvToClear(gridLaunch) : []), ...harnessEnvToClear(dshEnv)]
// The named agent takes the same argv slot on every relaunch (`buildLaunchOverrides` appends it
// from the row's `agent`, after the grid's and the DSH's argv, exactly as here). The engine was
// checked for a contract at the wire (AGENT_UNSUPPORTED), so this cannot throw.
@@ -4751,6 +4754,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
gridLaunchRecord: grid && gridLaunch ? { override: grid, webSearch: gridLaunch.webSearch } : null,
codexHome,
dsh,
+ dshRuntime: dsh ? label : null,
agent,
bypassPermission,
permissionMode,
@@ -4811,24 +4815,29 @@ async function runForeground(session: AuthSession | null): Promise<void> {
const plan = planFork({ engine, sessionId: source.sessionId, name: sourceName, cwd: source.cwd }, memory, prompt)
if (!plan.ok) return { ok: false, error: plan.error, detail: plan.detail }
- // The harness the source was created as: its env and argv, not a second materialisation — the
- // folder already holds the template, AGENTS.md and skill links the source got.
+ const label = buildHarnessSessionLabel(engine)
+ // Fork the source's saved harness context. Workspace templates and init are not run again.
let dshEnv: Record<string, string> | undefined
let dshArgs: string[] = []
let dshLabel: string | undefined
if (source.dsh) {
const installed = installedDsh(source.dsh)
if (!installed) return { ok: false, error: 'INVALID_DSH', detail: `${source.dsh} is no longer installed on this machine` }
- const launch = dshLaunch(installed, source.cwd, { privateGrid: backend.gridName() })
- dshEnv = launch.env
- dshArgs = launch.args
+ // Narrowed above; a closure would lose that, so the checked values are named here.
+ const cwd = source.cwd
+ const sourceKey = forkRuntimeKey({ cwd, agentId: source.agentId, dshRuntime: source.dshRuntime })
+ const prepared = harnessLaunchOrRefusal(() => prepareHarnessLaunch(installed, cwd, engine, label,
+ { privateGrid: backend.gridName() }, sourceKey))
+ if (!prepared.ok) return prepared
+ dshEnv = prepared.launch.env
+ dshArgs = prepared.launch.args
dshLabel = installed.manifest.name
}
- const label = buildHarnessSessionLabel(engine)
const installIfMissing = enginePathOverride(engine) ? undefined : engineInstallRecipe(engine)
const extraArgs = [...dshArgs, ...(source.agent ? namedAgentArgs(engine, source.agent) : [])]
const firstPrompt = plan.level === 'native' ? (prompt ?? undefined) : plan.firstPrompt
const launchOptions = {
+ clearEnv: harnessEnvToClear(dshEnv),
bypassPermission: source.bypassPermission ?? false,
...(source.permissionMode ? { permissionMode: source.permissionMode } : {}),
extraArgs: extraArgs.length ? extraArgs : undefined,
@@ -4859,6 +4868,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
grid: null,
gridLaunchRecord: null,
codexHome: source.codexHome ?? null,
+ dshRuntime: source.dsh ? label : null,
dsh: source.dsh ?? null,
agent: source.agent ?? null,
bypassPermission: source.bypassPermission ?? false,
diff --git a/cli/src/cliCommand.spec.ts b/cli/src/cliCommand.spec.ts
index e70d3bb33..114134238 100644
--- a/cli/src/cliCommand.spec.ts
+++ b/cli/src/cliCommand.spec.ts
@@ -117,7 +117,12 @@ describe('CLI login/start command contract', () => {
const child = spawn(process.execPath, [TSX, CLI_SOURCE, 'start'], {
cwd: CLI_ROOT,
detached: true,
- env: envFor(root, { PORT: String(20_000 + Math.floor(Math.random() * 20_000)) }),
+ env: envFor(root, {
+ PORT: String(20_000 + Math.floor(Math.random() * 20_000)),
+ DISABLE_HOOK_INSTALL: 'true', CABLE_DISABLE: 'true', DISABLE_GRID_INSTALL: 'true',
+ // Startup's sign-in contract does not need a runtime download or the developer's Grid.
+ HARNESS_GRID_BIN: join(root, 'grid-unavailable'),
+ }),
stdio: ['ignore', 'pipe', 'pipe'],
})
children.push(child)
@@ -125,7 +130,7 @@ describe('CLI login/start command contract', () => {
child.stdout?.on('data', (chunk: Buffer) => { said += chunk.toString() })
child.stderr?.on('data', (chunk: Buffer) => { said += chunk.toString() })
const deadline = Date.now() + 25_000
- while (Date.now() < deadline && !/serving this computer only|Not signed in|Sign in to Harness/.test(said)) {
+ while (Date.now() < deadline && !/serving this computer only|Sign in to Harness in your browser/.test(said)) {
await new Promise((r) => setTimeout(r, 100))
}
try {
diff --git a/cli/src/dsh/adapters.ts b/cli/src/dsh/adapters.ts
new file mode 100644
index 000000000..8279b465a
--- /dev/null
+++ b/cli/src/dsh/adapters.ts
@@ -0,0 +1,50 @@
+/** The portable harness ABI is files + a shell, not an engine's plugin format.
+ * Each adapter names the project instruction files its engine actually reads, in precedence order.
+ * Skills and executable tools are exposed through the session's context, so native skill/MCP
+ * support is an optional optimization rather than a condition for running a harness.
+ * Contracts and primary sources: store/spec/portability.md.
+ */
+import type { AgentEngine, ProcessEngine } from '../engines/types.js'
+
+export interface HarnessAdapter {
+ instructionFiles: readonly string[]
+ /** A session-local instruction flag, when the engine provides one. */
+ contextArgs?: (contextFile: string) => string[]
+}
+
+export const HARNESS_ADAPTERS = {
+ claude: { instructionFiles: ['CLAUDE.md'], contextArgs: (file: string) => ['--append-system-prompt', `Read the harness context at ${JSON.stringify(file)} before working.`] },
+ codex: { instructionFiles: ['AGENTS.override.md', 'AGENTS.md'] },
+ cursor: { instructionFiles: ['AGENTS.md'] },
+ opencode: { instructionFiles: ['AGENTS.md', 'CLAUDE.md'] },
+ pi: { instructionFiles: ['AGENTS.md', 'CLAUDE.md'], contextArgs: (file: string) => ['--append-system-prompt', file] },
+ hermes: { instructionFiles: ['.hermes.md', 'AGENTS.md', 'CLAUDE.md', '.cursorrules'] },
+ commandcode: { instructionFiles: ['AGENTS.md'] },
+ devin: { instructionFiles: ['AGENTS.md'] },
+ muse: { instructionFiles: ['AGENTS.md', 'CLAUDE.md'] },
+ amp: { instructionFiles: ['AGENTS.md'] },
+ kilo: { instructionFiles: ['AGENTS.md'] },
+ grok: { instructionFiles: ['AGENTS.md'] },
+ agy: { instructionFiles: ['AGENTS.md', 'GEMINI.md'] },
+ copilot: { instructionFiles: ['AGENTS.md'] },
+} satisfies Record<ProcessEngine, HarnessAdapter>
+
+/** A terminal has no instruction loader or agent tools. It remains a Coding-only choice. */
+export function harnessAdapter(engine: AgentEngine): HarnessAdapter {
+ if (engine === 'terminal') throw new Error('A harness needs an agent engine; Terminal cannot run harness instructions.')
+ return HARNESS_ADAPTERS[engine]
+}
+
+export const HARNESS_BOOTSTRAP = `<!-- harness:runtime v1 -->
+## Harness session context
+
+If HARNESS_CONTEXT_FILE is set in your environment, read that file before working:
+
+\`\`\`sh
+if [ -n "$HARNESS_CONTEXT_FILE" ]; then cat "$HARNESS_CONTEXT_FILE"; fi
+\`\`\`
+
+It contains the instructions and skill index for this session's selected harness.
+If the variable is absent, this is an ordinary coding session with no selected harness.
+<!-- /harness:runtime -->
+`
diff --git a/cli/src/dsh/compatibility.ts b/cli/src/dsh/compatibility.ts
new file mode 100644
index 000000000..496b65168
--- /dev/null
+++ b/cli/src/dsh/compatibility.ts
@@ -0,0 +1,10 @@
+import { PROCESS_ENGINES, type AgentEngine } from '../engines/types.js'
+
+/** Spec-1's engine is a default, not a binding. This daemon supplies the portable runtime for
+ * every process engine it integrates. Old daemons continue to use the same default field.
+ * Legacy argv belongs only to that default engine; the neutral content travels to every engine.
+ */
+export function compatibleHarnessEngines(manifest: { kind?: string; engine?: AgentEngine }): AgentEngine[] {
+ if (manifest.kind === 'viewer' || !manifest.engine || manifest.engine === 'terminal') return []
+ return [manifest.engine, ...PROCESS_ENGINES.filter(engine => engine !== manifest.engine)]
+}
diff --git a/cli/src/dsh/launch.spec.ts b/cli/src/dsh/launch.spec.ts
index a97673bb9..29c449b59 100644
--- a/cli/src/dsh/launch.spec.ts
+++ b/cli/src/dsh/launch.spec.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest'
import type { InstalledDsh } from './installed.js'
-import { dshLaunch } from './launch.js'
+import { dshLaunch, harnessEnvToClear, DSH_SESSION_ENV } from './launch.js'
import { buildLaunchOverrides, type LaunchOverridesDeps } from '../lib/launchOverrides.js'
import { dshFromEnv } from './probe.js'
@@ -47,7 +47,7 @@ describe('buildLaunchOverrides with a DSH', () => {
writeGridConfigDir: async () => '/cfg',
tmuxSupportsSessionEnv: async () => true,
installCodexHooks: () => undefined,
- dshLaunch: (id, workspace) => (id === installed.id ? dshLaunch(installed, workspace) : null),
+ dshLaunch: (id, workspace, engine) => (id === installed.id ? dshLaunch(installed, workspace, {}, engine) : null),
}
it('layers the DSH env and argv over a plain relaunch', async () => {
@@ -62,16 +62,17 @@ describe('buildLaunchOverrides with a DSH', () => {
it('layers it over a Codex profile too, keeping CODEX_HOME', async () => {
const built = await buildLaunchOverrides(deps, 'codex', { dsh: 'autonomous/circuit', cwd: '/ws', codexHome: '/home/u/.codex-work' }, 'agent-1')
expect(built.ok && built.overrides.env).toMatchObject({ CODEX_HOME: '/home/u/.codex-work', HARNESS_DSH: 'autonomous/circuit' })
+ expect(built.ok && built.overrides.extraArgs).not.toContain('--add-dir')
})
- it('falls back to the plain engine when the DSH is no longer installed here', async () => {
+ it('refuses a restart when the DSH is no longer installed here', async () => {
const built = await buildLaunchOverrides(deps, 'claude', { dsh: 'gone/away', cwd: '/ws' }, 'agent-1')
- expect(built.ok && built.overrides).toEqual({ env: {}, extraArgs: [], clearEnv: [] })
+ expect(built).toMatchObject({ ok: false, error: 'DSH_NOT_INSTALLED' })
})
- it('does nothing without a workspace to expand into', async () => {
+ it('refuses to silently lose a harness when its workspace is missing', async () => {
const built = await buildLaunchOverrides(deps, 'claude', { dsh: 'autonomous/circuit', cwd: null }, 'agent-1')
- expect(built.ok && built.overrides.env).toEqual({})
+ expect(built).toMatchObject({ ok: false, error: 'DSH_WORKSPACE_MISSING' })
})
})
@@ -82,3 +83,9 @@ describe('dshFromEnv', () => {
expect(dshFromEnv({})).toBeNull()
})
})
+
+it('clears inherited session facts except those explicitly supplied by this launch', () => {
+ expect(harnessEnvToClear()).toEqual(DSH_SESSION_ENV)
+ expect(harnessEnvToClear({ HARNESS_DSH: 'acme/draw' })).toEqual(DSH_SESSION_ENV.filter(name => name !== 'HARNESS_DSH'))
+ expect(harnessEnvToClear(Object.fromEntries(DSH_SESSION_ENV.map(name => [name, 'current'])))).toEqual([])
+})
diff --git a/cli/src/dsh/launch.ts b/cli/src/dsh/launch.ts
index cfa6561d2..8b6588ba2 100644
--- a/cli/src/dsh/launch.ts
+++ b/cli/src/dsh/launch.ts
@@ -14,6 +14,13 @@ export interface DshLaunch {
args: string[]
}
+/** Clear every inherited session fact that this launch does not explicitly provide. This includes
+ * all context for Coding and an old account's private grid when the new harness has none. */
+export const DSH_SESSION_ENV = ['HARNESS_DSH', 'HARNESS_DSH_DIR', 'HARNESS_WORKSPACE', 'HARNESS_CONTEXT_FILE', 'HARNESS_SKILLS_DIR', 'HARNESS_PRIVATE_GRID'] as const
+export function harnessEnvToClear(launchEnv: Record<string, string> = {}): string[] {
+ return DSH_SESSION_ENV.filter(name => !Object.hasOwn(launchEnv, name))
+}
+
/** Facts about the signed-in account a harness is told rather than left to guess or ask. */
export interface DshAccount {
/** The account's private grid — what "my grid" means to the person. */
@@ -25,7 +32,7 @@ export function dshAccountEnv(account: DshAccount): Record<string, string> {
return account.privateGrid ? { HARNESS_PRIVATE_GRID: account.privateGrid } : {}
}
-export function dshLaunch(dsh: InstalledDsh, workspace: string, account: DshAccount = {}): DshLaunch {
+export function dshLaunch(dsh: InstalledDsh, workspace: string, account: DshAccount = {}, engine = dsh.manifest.engine): DshLaunch {
const vars = { dsh: dsh.realDir, workspace }
const env: Record<string, string> = {
HARNESS_DSH: dsh.id,
@@ -37,6 +44,9 @@ export function dshLaunch(dsh: InstalledDsh, workspace: string, account: DshAcco
if (key.startsWith('HARNESS_')) continue // ours; a manifest cannot rename itself
env[key] = expandDshValue(value, vars)
}
- const args = (dsh.manifest.agent?.args ?? []).map((arg) => expandDshValue(arg, vars))
+ // A saved session keeps its engine even if a package update changes the default.
+ // Default-engine flags must never be handed to a different engine on restore.
+ const args = (engine === dsh.manifest.engine ? dsh.manifest.agent?.args ?? [] : [])
+ .map((arg) => expandDshValue(arg, vars))
return { env, args }
}
diff --git a/cli/src/dsh/manifest.spec.ts b/cli/src/dsh/manifest.spec.ts
index 9dd72f75c..c21ee361c 100644
--- a/cli/src/dsh/manifest.spec.ts
+++ b/cli/src/dsh/manifest.spec.ts
@@ -1,7 +1,8 @@
+import { PROCESS_ENGINES } from '../engines/types.js'
import { describe, expect, it } from 'vitest'
import { readFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
-import { DshManifestSchema, dshSkillsDirFor, dshTier, dshVerdictPath, dshViewerName, expandDshValue, parseDshManifest, readDshManifest , isViewerPackage, dshEngine, viewerUse} from './manifest.js'
+import { DshManifestSchema, dshSupportedEngines, dshTier, dshVerdictPath, dshViewerName, expandDshValue, parseDshManifest, readDshManifest , isViewerPackage, dshEngine, viewerUse} from './manifest.js'
const STARTER = fileURLToPath(new URL('../../../store/starter', import.meta.url))
@@ -23,6 +24,15 @@ describe('parseDshManifest', () => {
const base = { spec: 1, id: 'acme/thing', name: 'Thing', engine: 'codex' }
+ it('treats the engine as a default and keeps spec-1 manifests compatible', () => {
+ const engines = dshSupportedEngines(DshManifestSchema.parse(base))
+ expect(engines[0]).toBe('codex')
+ expect(new Set(engines)).toEqual(new Set(PROCESS_ENGINES))
+ const legacy = { ...base, agent: { env: { DSH_SUPPORTED_ENGINES: 'claude,codex' }, args: ['--add-dir', '/tmp'] } }
+ expect(parseDshManifest(JSON.stringify(legacy)).ok).toBe(true)
+ expect(dshSupportedEngines(DshManifestSchema.parse(legacy))).toEqual(engines)
+ })
+
it('refuses paths that leave the harness', () => {
for (const bad of ['../outside', '/abs/path', 'a/../../b']) {
const result = parseDshManifest(JSON.stringify({ ...base, workspace: { template: bad } }))
@@ -83,12 +93,7 @@ describe('expandDshValue', () => {
})
})
-describe('dshSkillsDirFor', () => {
- it('puts Claude skills where Claude Code reads project skills, everyone else under .agents', () => {
- expect(dshSkillsDirFor('claude')).toBe('.claude/skills')
- expect(dshSkillsDirFor('codex')).toBe('.agents/skills')
- expect(dshSkillsDirFor('cursor')).toBe('.agents/skills')
- })
+describe('legacy package identities', () => {
it('accepts the ids a harness went by before, and only well-formed ones', () => {
const base = { spec: 1, id: 'acme/solid', name: 'Solid', engine: 'codex' }
expect(DshManifestSchema.safeParse({ ...base, formerly: ['acme/workshop'] }).success).toBe(true)
diff --git a/cli/src/dsh/manifest.ts b/cli/src/dsh/manifest.ts
index c816f41f1..bb2a297d7 100644
--- a/cli/src/dsh/manifest.ts
+++ b/cli/src/dsh/manifest.ts
@@ -18,6 +18,7 @@ import { ENGINES } from '../engines/types.js'
export const DSH_ID_RE = /^[a-z0-9][a-z0-9-]{0,63}\/[a-z0-9][a-z0-9-]{0,63}$/
export const DSH_MANIFEST_FILE = 'harness.json'
export const DEFAULT_VERDICT_PATH = '.harness/verdict.json'
+export { compatibleHarnessEngines as dshSupportedEngines } from './compatibility.js'
function insideHarness(path: string): boolean {
if (isAbsolute(path)) return false
@@ -91,9 +92,11 @@ export const DshManifestSchema = z.strictObject({
} else if (!manifest.engine) {
ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['engine'], message: 'an agent package needs a base engine' })
}
+
})
export type DshManifest = z.infer<typeof DshManifestSchema>
+
export type DshViewerSpec = z.infer<typeof OwnViewerSchema>
export type DshViewerUse = z.infer<typeof UsedViewerSchema>
@@ -200,8 +203,3 @@ export function dshTier(manifest: DshManifest): 0 | 1 | 2 {
export function dshVerdictPath(manifest: DshManifest): string {
return manifest.verdict ?? DEFAULT_VERDICT_PATH
}
-
-/** Where a base engine looks for project-level skills. */
-export function dshSkillsDirFor(engine: NonNullable<DshManifest['engine']>): string {
- return engine === 'claude' ? '.claude/skills' : '.agents/skills'
-}
diff --git a/cli/src/dsh/materialize.spec.ts b/cli/src/dsh/materialize.spec.ts
index f204316c8..5616c0517 100644
--- a/cli/src/dsh/materialize.spec.ts
+++ b/cli/src/dsh/materialize.spec.ts
@@ -5,7 +5,7 @@ import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import type { InstalledDsh } from './installed.js'
import { parseDshManifest, readDshManifest } from './manifest.js'
-import { dshMarkerLine, materializeWorkspace, resolveDshCommand, skillDirsIn } from './materialize.js'
+import { materializeWorkspace, resolveDshCommand, skillDirsIn } from './materialize.js'
const STARTER = realpathSync(fileURLToPath(new URL('../../../store/starter', import.meta.url)))
@@ -30,23 +30,20 @@ describe('materializeWorkspace', () => {
beforeEach(() => { workspace = mkdtempSync(join(tmpdir(), 'dsh-ws-')) })
afterEach(() => rmSync(workspace, { recursive: true, force: true }))
- it('fills an empty workspace: template, AGENTS.md, CLAUDE.md import, skill link, .harness', async () => {
- const result = await materializeWorkspace(starter(), workspace)
+ it('prepares the workspace independently of the engine without publishing instructions or native skills', async () => {
+ const result = await materializeWorkspace(starter(), workspace, {}, 'codex')
expect(result.warnings).toEqual([])
expect(readFileSync(join(workspace, 'NOTES.md'), 'utf8')).toContain('# Notes')
- const agents = readFileSync(join(workspace, 'AGENTS.md'), 'utf8')
- expect(agents.startsWith(dshMarkerLine('autonomous/starter'))).toBe(true)
- expect(agents).toContain('Starter harness')
- expect(readFileSync(join(workspace, 'CLAUDE.md'), 'utf8').trim()).toBe('@AGENTS.md')
- const link = join(workspace, '.claude', 'skills', 'hello')
- expect(lstatSync(link).isSymbolicLink()).toBe(true)
- expect(readlinkSync(link)).toBe(join(STARTER, 'skills', 'hello'))
- expect(existsSync(join(link, 'SKILL.md'))).toBe(true)
- expect(existsSync(join(workspace, '.harness'))).toBe(true)
- expect(result.created).toContain('AGENTS.md')
- // The init ran in the workspace, found by its path inside the harness, with the contract's env.
expect(readFileSync(join(workspace, '.harness-initialized'), 'utf8')).toBe('initialized by autonomous/starter\n')
- expect(result.warnings).toEqual([])
+ expect(existsSync(join(workspace, 'AGENTS.md'))).toBe(false)
+ expect(existsSync(join(workspace, '.claude'))).toBe(false)
+ expect(existsSync(join(workspace, '.agents'))).toBe(false)
+ expect(existsSync(join(workspace, '.harness'))).toBe(true)
+ })
+
+ it('refuses a terminal before copying the template or running init', async () => {
+ await expect(materializeWorkspace(starter(), workspace, {}, 'terminal')).rejects.toThrow('does not support terminal')
+ expect(readdirSync(workspace)).toEqual([])
})
it('runs the init only once: a marked workspace is not re-initialized', async () => {
@@ -56,43 +53,17 @@ describe('materializeWorkspace', () => {
expect(existsSync(join(workspace, '.harness-initialized'))).toBe(false)
})
- it('is idempotent: a second run keeps everything and appends nothing', async () => {
+ it('is idempotent and preserves all project instructions and native skills', async () => {
+ writeFileSync(join(workspace, 'AGENTS.md'), '# Repo rules\n')
+ writeFileSync(join(workspace, 'CLAUDE.md'), '# Claude rules\n')
+ mkdirSync(join(workspace, '.claude/skills/hello'), { recursive: true })
await materializeWorkspace(starter(), workspace)
- const before = readFileSync(join(workspace, 'AGENTS.md'), 'utf8')
const again = await materializeWorkspace(starter(), workspace)
- expect(readFileSync(join(workspace, 'AGENTS.md'), 'utf8')).toBe(before)
expect(again.created).toEqual([])
- expect(again.kept).toEqual(expect.arrayContaining(['NOTES.md', 'AGENTS.md', 'CLAUDE.md', '.claude/skills/hello']))
- })
-
- it("appends under a marker to the user's own AGENTS.md and CLAUDE.md, once", async () => {
- writeFileSync(join(workspace, 'NOTES.md'), 'mine\n') // marker present → no template copy
- writeFileSync(join(workspace, 'AGENTS.md'), '# Repo rules\n\nBe kind.\n')
- writeFileSync(join(workspace, 'CLAUDE.md'), '# Claude\n')
- await materializeWorkspace(starter(), workspace)
- await materializeWorkspace(starter(), workspace)
- const agents = readFileSync(join(workspace, 'AGENTS.md'), 'utf8')
- expect(agents.startsWith('# Repo rules')).toBe(true)
- expect(agents.split(dshMarkerLine('autonomous/starter')).length).toBe(2)
- const claude = readFileSync(join(workspace, 'CLAUDE.md'), 'utf8')
- expect(claude.startsWith('# Claude')).toBe(true)
- expect(claude.split('@AGENTS.md').length).toBe(2)
- expect(readFileSync(join(workspace, 'NOTES.md'), 'utf8')).toBe('mine\n')
- })
-
- it('links Codex skills under .agents and writes no CLAUDE.md', async () => {
- await materializeWorkspace(starter('codex'), workspace)
- expect(lstatSync(join(workspace, '.agents', 'skills', 'hello')).isSymbolicLink()).toBe(true)
- expect(existsSync(join(workspace, 'CLAUDE.md'))).toBe(false)
- expect(existsSync(join(workspace, '.claude'))).toBe(false)
- })
-
- it('leaves a real directory in the skills folder alone and says so', async () => {
- const { mkdirSync } = await import('node:fs')
- mkdirSync(join(workspace, '.claude', 'skills', 'hello'), { recursive: true })
- const result = await materializeWorkspace(starter(), workspace)
- expect(lstatSync(join(workspace, '.claude', 'skills', 'hello')).isSymbolicLink()).toBe(false)
- expect(result.warnings.some((w) => w.includes('hello'))).toBe(true)
+ expect(again.kept).toEqual(['NOTES.md'])
+ expect(readFileSync(join(workspace, 'AGENTS.md'), 'utf8')).toBe('# Repo rules\n')
+ expect(readFileSync(join(workspace, 'CLAUDE.md'), 'utf8')).toBe('# Claude rules\n')
+ expect(lstatSync(join(workspace, '.claude/skills/hello')).isDirectory()).toBe(true)
})
})
@@ -179,13 +150,11 @@ describe('materializeWorkspace, on harnesses other than the starter', () => {
expect(readFileSync(join(workspace, 'init.log'), 'utf8')).toBe('init in workspace for acme/thing\ninit in workspace for acme/thing\n')
})
- it('says what it could not do: a missing template, unreadable instructions, a skills root with no skills', async () => {
+ it('reports a missing template; runtime binding validates instructions and skills separately', async () => {
const dsh = install({ engine: 'claude', workspace: { template: 'gone', marker: 'deck.md' }, agent: { instructions: 'MISSING.md', skills: ['empty'] } }, { 'empty/README.md': '' })
const result = await materializeWorkspace(dsh, workspace)
expect(result.warnings).toEqual([
`template ${join(harness, 'gone')} is missing`,
- `instructions ${join(harness, 'MISSING.md')} could not be read`,
- 'no SKILL.md under empty',
])
expect(existsSync(join(workspace, 'AGENTS.md'))).toBe(false)
expect(existsSync(join(workspace, 'CLAUDE.md'))).toBe(false)
@@ -209,22 +178,16 @@ describe('materializeWorkspace, on harnesses other than the starter', () => {
expect(result.warnings).toEqual(['init exited by timeout'])
})
- it('repoints a skill link an earlier install path left, and skips a skill entry it cannot stat', async () => {
- const dsh = install({ engine: 'codex', agent: { skills: ['skills'] } }, { 'skills/draw/SKILL.md': '---\nname: draw\n---\n' })
+ it('skips skill entries that cannot be statted', () => {
+ const dsh = install({ engine: 'codex', agent: { skills: ['skills'] } }, { 'skills/draw/SKILL.md': '# Draw' })
symlinkSync(join(root, 'nowhere'), join(harness, 'skills', 'dangling'))
- mkdirSync(join(workspace, '.agents', 'skills'), { recursive: true })
- symlinkSync(join(root, 'old-install', 'draw'), join(workspace, '.agents', 'skills', 'draw'))
- const result = await materializeWorkspace(dsh, workspace)
- expect(result.created).toEqual(['.agents/skills/draw'])
- expect(readlinkSync(join(workspace, '.agents', 'skills', 'draw'))).toBe(join(harness, 'skills', 'draw'))
- expect(existsSync(join(workspace, '.agents', 'skills', 'dangling'))).toBe(false)
+ expect(skillDirsIn(join(dsh.realDir, 'skills'))).toEqual([join(harness, 'skills/draw')])
})
- it('an agent manifest with no engine (the type allows it) is laid out for Claude Code', async () => {
+ it('refuses an agent manifest with no engine before writing workspace files', async () => {
const dsh = install({ engine: 'claude', agent: { instructions: 'AGENTS.md', skills: ['skills'] } }, { 'AGENTS.md': '# Thing\n', 'skills/draw/SKILL.md': '' })
const { engine: _engine, ...manifest } = dsh.manifest
- await materializeWorkspace({ ...dsh, manifest }, workspace)
- expect(readFileSync(join(workspace, 'CLAUDE.md'), 'utf8')).toBe('@AGENTS.md\n')
- expect(lstatSync(join(workspace, '.claude', 'skills', 'draw')).isSymbolicLink()).toBe(true)
+ await expect(materializeWorkspace({ ...dsh, manifest }, workspace)).rejects.toThrow('does not support')
+ expect(readdirSync(workspace)).toEqual([])
})
})
diff --git a/cli/src/dsh/materialize.ts b/cli/src/dsh/materialize.ts
index c35a23269..b8c281662 100644
--- a/cli/src/dsh/materialize.ts
+++ b/cli/src/dsh/materialize.ts
@@ -1,22 +1,10 @@
-/**
- * Put a DSH into a workspace, idempotently, before its engine is launched there — the four steps of
- * the contract (`store/spec/README.md` § Materialization):
- *
- * 1. an EMPTY workspace (no marker) gets the template, then the init command runs;
- * 2. `AGENTS.md` is copied in, or the DSH's text is appended under a marker line; a `claude` base
- * also gets a `CLAUDE.md` that imports it, because that is the file Claude Code reads;
- * 3. each skill directory is symlinked into the engine's project-skills folder, so a DSH update
- * is live in every workspace without a second copy;
- * 4. `.harness/` exists, so the verdict watcher has a directory to watch before the first verdict.
- *
- * Nothing here touches the user's own files beyond those: an existing AGENTS.md keeps its content,
- * an existing skill link that points elsewhere is left alone and reported.
- */
-import { cpSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, readlinkSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs'
-import { basename, join, relative } from 'node:path'
+/** Prepare a harness workspace independently of the selected agent. Templates and init belong to
+ * the harness; instructions and skills are bound per session by runtime.ts after preparation. */
+import { cpSync, existsSync, mkdirSync, readdirSync, statSync } from 'node:fs'
+import { join } from 'node:path'
import type { InstalledDsh } from './installed.js'
import { dshAccountEnv, type DshAccount } from './launch.js'
-import { dshSkillsDirFor } from './manifest.js'
+import { dshSupportedEngines } from './manifest.js'
import { runDshCommand } from './shell.js'
export interface MaterializeResult {
@@ -30,14 +18,6 @@ export interface MaterializeResult {
initLines: string[]
}
-export const AGENTS_FILE = 'AGENTS.md'
-export const CLAUDE_FILE = 'CLAUDE.md'
-export const CLAUDE_IMPORT_LINE = '@AGENTS.md'
-
-export function dshMarkerLine(id: string): string {
- return `<!-- harness:dsh ${id} -->`
-}
-
/** Subdirectories of `dir` that carry a SKILL.md, or `dir` itself when it is a single skill. */
export function skillDirsIn(dir: string): string[] {
if (existsSync(join(dir, 'SKILL.md'))) return [dir]
@@ -69,75 +49,6 @@ function copyTemplate(templateDir: string, workspace: string, result: Materializ
result.created.push(`template → ${workspace}`)
}
-function writeInstructions(dsh: InstalledDsh, workspace: string, result: MaterializeResult): void {
- const source = dsh.manifest.agent?.instructions
- if (!source) return
- const sourcePath = join(dsh.realDir, source)
- let text: string
- try {
- text = readFileSync(sourcePath, 'utf8')
- } catch {
- result.warnings.push(`instructions ${sourcePath} could not be read`)
- return
- }
- const marker = dshMarkerLine(dsh.id)
- const target = join(workspace, AGENTS_FILE)
- const body = `${marker}\n${text.trim()}\n`
- if (!existsSync(target)) {
- writeFileSync(target, body)
- result.created.push(AGENTS_FILE)
- } else {
- const existing = readFileSync(target, 'utf8')
- if (existing.includes(marker)) {
- result.kept.push(AGENTS_FILE)
- } else {
- writeFileSync(target, `${existing.replace(/\s*$/, '')}\n\n${body}`)
- result.created.push(`${AGENTS_FILE} (appended)`)
- }
- }
- if (dshBaseEngine(dsh) === 'claude') {
- const claude = join(workspace, CLAUDE_FILE)
- if (!existsSync(claude)) {
- writeFileSync(claude, `${CLAUDE_IMPORT_LINE}\n`)
- result.created.push(CLAUDE_FILE)
- } else {
- const existing = readFileSync(claude, 'utf8')
- if (existing.split('\n').some((line) => line.trim() === CLAUDE_IMPORT_LINE)) {
- result.kept.push(CLAUDE_FILE)
- } else {
- writeFileSync(claude, `${existing.replace(/\s*$/, '')}\n\n${CLAUDE_IMPORT_LINE}\n`)
- result.created.push(`${CLAUDE_FILE} (import added)`)
- }
- }
- }
-}
-
-function linkSkills(dsh: InstalledDsh, workspace: string, result: MaterializeResult): void {
- const roots = dsh.manifest.agent?.skills ?? []
- if (!roots.length) return
- const skillsDir = join(workspace, dshSkillsDirFor(dshBaseEngine(dsh)))
- ensureDir(skillsDir)
- for (const root of roots) {
- const dirs = skillDirsIn(join(dsh.realDir, root))
- if (!dirs.length) result.warnings.push(`no SKILL.md under ${root}`)
- for (const dir of dirs) {
- const link = join(skillsDir, basename(dir))
- let existing: ReturnType<typeof lstatSync> | null = null
- try { existing = lstatSync(link) } catch { existing = null }
- if (existing?.isSymbolicLink()) {
- if (readlinkSync(link) === dir) { result.kept.push(relative(workspace, link)); continue }
- // Ours from an earlier install path (a relink, a moved checkout): repoint it.
- rmSync(link)
- } else if (existing) {
- result.warnings.push(`${relative(workspace, link)} exists and is not a link; left alone`)
- continue
- }
- symlinkSync(dir, link)
- result.created.push(relative(workspace, link))
- }
- }
-}
-
/** A command that is a path inside the harness becomes that absolute path, shell-quoted. */
export function resolveDshCommand(dsh: Pick<InstalledDsh, 'realDir'>, command: string): string {
if (/[\s;&|<>$`'"\\]/.test(command)) return command
@@ -146,17 +57,15 @@ export function resolveDshCommand(dsh: Pick<InstalledDsh, 'realDir'>, command: s
return `'${inside.replace(/'/g, `'\\''`)}'`
}
-/** The engine an agent package runs on. A viewer package is refused before this is asked. */
-function dshBaseEngine(dsh: InstalledDsh): NonNullable<InstalledDsh['manifest']['engine']> {
- return dsh.manifest.engine ?? 'claude'
-}
-
-export async function materializeWorkspace(dsh: InstalledDsh, workspace: string, account: DshAccount = {}): Promise<MaterializeResult> {
+export async function materializeWorkspace(dsh: InstalledDsh, workspace: string, account: DshAccount = {}, engine = dsh.manifest.engine ?? 'claude'): Promise<MaterializeResult> {
const result: MaterializeResult = { created: [], kept: [], warnings: [], initLines: [] }
if (dsh.manifest.kind === 'viewer') {
result.warnings.push(`${dsh.id} is a viewer package; it has no workspace to lay out`)
return result
}
+ if (!dshSupportedEngines(dsh.manifest).includes(engine)) {
+ throw new Error(`${dsh.id} does not support ${engine}`)
+ }
const ws = dsh.manifest.workspace
const marker = ws?.marker ? join(workspace, ws.marker) : null
// No marker declared means nothing can say the workspace is laid out: the template is copied (never
@@ -179,8 +88,6 @@ export async function materializeWorkspace(dsh: InstalledDsh, workspace: string,
} else if (marker && !fresh) {
result.kept.push(ws!.marker!)
}
- writeInstructions(dsh, workspace, result)
- linkSkills(dsh, workspace, result)
ensureDir(join(workspace, '.harness'))
return result
}
diff --git a/cli/src/dsh/portability.integration.spec.ts b/cli/src/dsh/portability.integration.spec.ts
new file mode 100644
index 000000000..652b8dd3f
--- /dev/null
+++ b/cli/src/dsh/portability.integration.spec.ts
@@ -0,0 +1,145 @@
+/** Real filesystem and subprocess lifecycle, without provider credentials or model calls. The
+ * fixture engine reads the same bootstrap/context/env supplied to vendor engines, runs the package
+ * tool, and produces a verdict. The manifest matrix uses every real store manifest; external
+ * setup assets are represented by tiny skills so it is deterministic and offline.
+ */
+import { execFileSync } from 'node:child_process'
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import { PROCESS_ENGINES } from '../engines/types.js'
+import { buildLaunchOverrides } from '../lib/launchOverrides.js'
+import { createAndRegisterPane } from '../lib/createAgentPane.js'
+import type { RegisteredSession } from '../lib/registry.js'
+import type { InstalledDsh } from './installed.js'
+import { readDshManifest, dshSupportedEngines } from './manifest.js'
+import { materializeWorkspace, skillDirsIn } from './materialize.js'
+import { prepareHarnessLaunch } from './runtime.js'
+import { dshListRows } from './wire.js'
+
+const store = fileURLToPath(new URL('../../../store/agents', import.meta.url))
+let root: string
+const write = (path: string, body: string, executable = false) => {
+ mkdirSync(join(path, '..'), { recursive: true })
+ writeFileSync(path, body, { mode: executable ? 0o755 : 0o644 })
+}
+const installed = (dir: string): InstalledDsh => {
+ const parsed = readDshManifest(dir)
+ if (!parsed.ok) throw new Error(parsed.error)
+ return { id: parsed.manifest.id, dir, realDir: dir, manifest: parsed.manifest, source: dir,
+ ref: null, commit: null, linked: true, installedAt: 1 }
+}
+beforeEach(() => { root = realpathSync(mkdtempSync(join(tmpdir(), 'harness-portability-e2e-'))) })
+afterEach(() => rmSync(root, { recursive: true, force: true }))
+
+describe('the whole store × engine matrix', () => {
+ for (const name of readdirSync(store).sort().filter(name => existsSync(join(store, name, 'harness.json')))) {
+ it(`${name} exposes its content on every integrated engine without an opt-in`, () => {
+ const original = installed(join(store, name))
+ expect(original.manifest.agent?.args ?? []).toEqual([])
+ const dir = join(root, name)
+ write(join(dir, 'harness.json'), JSON.stringify(original.manifest))
+ if (original.manifest.agent?.instructions) {
+ const file = original.manifest.agent.instructions
+ write(join(dir, file), existsSync(join(original.realDir, file)) ? readFileSync(join(original.realDir, file), 'utf8') : '# Upstream fixture instructions\n')
+ }
+ for (const [index, skillRoot] of (original.manifest.agent?.skills ?? []).entries()) {
+ const source = join(original.realDir, skillRoot)
+ const skills = skillDirsIn(source)
+ if (skills.length) {
+ for (const skill of skills) {
+ const relative = skill.slice(original.realDir.length + 1)
+ write(join(dir, relative, 'SKILL.md'), readFileSync(join(skill, 'SKILL.md'), 'utf8'))
+ }
+ } else write(join(dir, skillRoot, `fixture-${index}/SKILL.md`), `# External setup asset ${index}\n`)
+ }
+ const pkg = installed(dir)
+ const row = dshListRows([pkg], [])[0]!
+ expect(new Set(row.engines as string[])).toEqual(new Set(PROCESS_ENGINES))
+ expect(new Set(dshSupportedEngines(pkg.manifest))).toEqual(new Set(PROCESS_ENGINES))
+ const workspace = join(root, 'workspace')
+ mkdirSync(workspace)
+ const launches = new Map()
+ for (const engine of PROCESS_ENGINES) {
+ const launch = prepareHarnessLaunch(pkg, workspace, engine, engine)
+ launches.set(engine, launch)
+ expect(launch.env.HARNESS_DSH).toBe(pkg.id)
+ const context = readFileSync(launch.env.HARNESS_CONTEXT_FILE!, 'utf8')
+ expect(context).toContain(pkg.id)
+ expect(context).toContain(`Engine: ${engine}.`)
+ for (const skillRoot of pkg.manifest.agent?.skills ?? []) {
+ for (const skill of skillDirsIn(join(dir, skillRoot))) {
+ const skillName = skill.split('/').at(-1)!
+ expect(context).toContain(`${skillName}/SKILL.md`)
+ expect(readFileSync(join(launch.env.HARNESS_SKILLS_DIR!, skillName, 'SKILL.md'), 'utf8')).toBe(readFileSync(join(skill, 'SKILL.md'), 'utf8'))
+ }
+ }
+ }
+ // Every built-in package keeps the selected engine and content on restart and fork,
+ // including after its default and instructions change. Another session cannot retarget it.
+ if (pkg.manifest.agent?.instructions) write(join(dir, pkg.manifest.agent.instructions), '# Updated package instructions\n')
+ pkg.manifest.engine = 'pi'
+ for (const engine of PROCESS_ENGINES) {
+ const originalLaunch = launches.get(engine)!
+ const context = readFileSync(originalLaunch.env.HARNESS_CONTEXT_FILE, 'utf8')
+ const restored = prepareHarnessLaunch(pkg, workspace, engine, engine)
+ expect(restored).toEqual(originalLaunch)
+ expect(readFileSync(restored.env.HARNESS_CONTEXT_FILE!, 'utf8')).toBe(context)
+ const fork = prepareHarnessLaunch(pkg, workspace, engine, `${engine}-fork`, {}, engine)
+ expect(fork.env.HARNESS_CONTEXT_FILE).not.toBe(originalLaunch.env.HARNESS_CONTEXT_FILE)
+ expect(readFileSync(fork.env.HARNESS_CONTEXT_FILE!, 'utf8').replaceAll(fork.env.HARNESS_SKILLS_DIR!, originalLaunch.env.HARNESS_SKILLS_DIR)).toBe(context)
+ }
+ })
+ }
+})
+
+for (const engine of PROCESS_ENGINES) it(`${engine}: prepare → spawn → tool → verdict → restart → fork`, async () => {
+ const dir = join(root, 'package')
+ write(join(dir, 'harness.json'), JSON.stringify({ spec: 1, id: 'test/portable', name: 'Portable', engine: 'claude',
+ workspace: { template: 'template', marker: 'scene.txt', init: 'init.sh' },
+ agent: { instructions: 'AGENTS.md', skills: ['skills'], env: { DRAW: '${dsh}/draw.sh' } },
+ verdict: '.harness/verdict.json' }))
+ write(join(dir, 'template/scene.txt'), 'blank scene\n')
+ write(join(dir, 'AGENTS.md'), '# Portable\nRead the draw skill; run "$DRAW" to produce scene.txt and the verdict.\n')
+ write(join(dir, 'skills/draw/SKILL.md'), '# Draw\nThe command "$DRAW" writes the artifact and verdict.\n')
+ write(join(dir, 'init.sh'), '#!/bin/sh\nprintf "%s" "$HARNESS_DSH" > initialized\n', true)
+ write(join(dir, 'draw.sh'), '#!/bin/sh\nprintf "drawn by %s\\n" "$HARNESS_DSH" > scene.txt\nprintf \'{"ready":true,"artifact":"scene.txt"}\\n\' > .harness/verdict.json\n', true)
+ const pkg = installed(dir)
+ const workspace = join(root, 'workspace')
+ mkdirSync(workspace)
+ await materializeWorkspace(pkg, workspace, {}, engine)
+ expect(readFileSync(join(workspace, 'initialized'), 'utf8')).toBe(pkg.id)
+ const launch = prepareHarnessLaunch(pkg, workspace, engine, 'created')
+ const fixture = join(root, 'fixture-engine.cjs')
+ write(fixture, `const fs = require('node:fs'), cp = require('node:child_process');
+ const ctx = fs.readFileSync(process.env.HARNESS_CONTEXT_FILE, 'utf8');
+ if (!ctx.includes('# Portable') || !ctx.includes('draw/SKILL.md')) throw Error('missing context');
+ const skill = fs.readFileSync(process.env.HARNESS_SKILLS_DIR + '/draw/SKILL.md', 'utf8');
+ if (!skill.includes('$DRAW')) throw Error('missing tool contract');
+ cp.execFileSync(process.env.DRAW, [], { cwd: process.env.HARNESS_WORKSPACE, env: process.env });
+ `)
+ const run = (launchEnv: Record<string, string>) => execFileSync(process.execPath, [fixture], { cwd: workspace, env: { PATH: process.env.PATH, ...launchEnv } })
+ let recorded: Record<string, unknown> | undefined
+ const created = await createAndRegisterPane({ engine, cwd: workspace, sessionLabel: 'created',
+ argv: [process.execPath, fixture], env: launch.env, dsh: pkg.id, dshRuntime: 'created',
+ tmuxBackend: { create: async input => { run(input.env!); return { state: 'succeeded', dispatch: 'executed', runtime: { backend: 'tmux', paneId: '%1' } } }, kill: async () => ({ state: 'succeeded', dispatch: 'executed' }) },
+ registry: { openPendingAgent: input => { recorded = input; return { ...input, agentId: 'registered' } as RegisteredSession } } })
+ expect(created.ok).toBe(true)
+ expect(recorded).toMatchObject({ engine, dsh: pkg.id, dshRuntime: 'created', cwd: workspace })
+ expect(JSON.parse(readFileSync(join(workspace, '.harness/verdict.json'), 'utf8'))).toEqual({ ready: true, artifact: 'scene.txt' })
+ expect(readFileSync(join(workspace, 'scene.txt'), 'utf8')).toBe('drawn by test/portable\n')
+ const restored = await buildLaunchOverrides({ machine: () => ({ hermesSystemManaged: false }), writeGridConfigDir: async () => '/unused',
+ tmuxSupportsSessionEnv: async () => true, installCodexHooks: () => {},
+ dshLaunch: (_id, ws, selected, key) => prepareHarnessLaunch(pkg, ws, selected, key) }, engine,
+ { dsh: pkg.id, cwd: workspace, dshRuntime: 'created' }, 'registered')
+ expect(restored.ok).toBe(true)
+ if (!restored.ok) throw new Error(restored.detail)
+ run(restored.overrides.env)
+ const fork = prepareHarnessLaunch(pkg, workspace, engine, 'fork', {}, 'created')
+ run(fork.env)
+ expect(fork.env.HARNESS_CONTEXT_FILE).not.toBe(launch.env.HARNESS_CONTEXT_FILE)
+ expect(readFileSync(join(workspace, 'scene.txt'), 'utf8')).toBe('drawn by test/portable\n')
+ expect((await materializeWorkspace(pkg, workspace, {}, engine)).initLines).toEqual([])
+})
diff --git a/cli/src/dsh/registry.spec.ts b/cli/src/dsh/registry.spec.ts
index b3a7bd31c..d57ee31c8 100644
--- a/cli/src/dsh/registry.spec.ts
+++ b/cli/src/dsh/registry.spec.ts
@@ -1,3 +1,4 @@
+import { dshSupportedEngines } from './manifest.js'
// The registry readers on fixture trees: the runtime's (registry.ts) and the build's
// (scripts/lib/dshRegistry.mjs), held to the same answer; the baked-in registry the release reads; and
// the store ref a branch under test moves the built-in shelf to.
@@ -72,7 +73,7 @@ describe('storeEntry', () => {
const [bare, checked, cad, pane, sim, lamp] = cases.map(([, manifest, facts]) => storeEntry('p', manifest, facts))
expect(sim.tagline).toBe('Advanced physics simulation')
expect(lamp.examples).toEqual([{ prompt: 'A desk lamp.', image: 'https://example.com/lamp.jpg', caption: 'Lamp · glTF' }])
- expect(bare).toEqual({ id: 'autonomous/bare', name: 'Bare', repo: HARNESS_MONOREPO, ref: 'main', path: 'p', engine: 'claude', tier: 0, verified: true })
+ expect(bare).toEqual({ id: 'autonomous/bare', name: 'Bare', repo: HARNESS_MONOREPO, ref: 'main', path: 'p', engine: 'claude', engines: dshSupportedEngines({ engine: 'claude' }), tier: 0, verified: true })
expect(checked.tier).toBe(1)
expect(cad).toMatchObject({ category: 'CAD', author: 'Autonomous', description: 'd', homepage: 'https://example.com', license: 'MIT', viewerUse: 'autonomous/cad-viewer', tier: 2 })
expect(pane).toMatchObject({ kind: 'viewer', upstream: 'https://example.com/up', screenshots: ['https://example.com/1.png'], tier: 2 })
diff --git a/cli/src/dsh/registry.ts b/cli/src/dsh/registry.ts
index 17c93a6ef..35ae1b595 100644
--- a/cli/src/dsh/registry.ts
+++ b/cli/src/dsh/registry.ts
@@ -18,7 +18,7 @@ import { fileURLToPath } from 'node:url'
import { z } from 'zod'
import { env } from '../config/env.js'
import { ENGINES } from '../engines/types.js'
-import { DSH_ID_RE } from './manifest.js'
+import { DSH_ID_RE, dshSupportedEngines, type DshManifest } from './manifest.js'
declare const __DSH_REGISTRY__: string | undefined
@@ -61,6 +61,7 @@ export const DshRegistryEntrySchema = z.strictObject({
*/
path: z.string().min(1).max(512).regex(PACKAGE_PATH_RE, 'path must be a relative folder inside the repo').optional(),
engine: z.enum(ENGINES).optional(),
+ engines: z.array(z.enum(ENGINES)).min(1).max(ENGINES.length).optional(),
tier: z.union([z.literal(0), z.literal(1), z.literal(2)]).optional(),
/** Shared viewer dependency, so the Store can show reverse dependencies before installation. */
viewerUse: z.string().regex(DSH_ID_RE).optional(),
@@ -118,6 +119,7 @@ export function storeEntry(path: string, manifest: Record<string, unknown>, fact
Object.assign(entry, { repo: HARNESS_MONOREPO, ref: 'main', path })
for (const key of ['homepage', 'upstream', 'license', 'tagline', 'screenshots', 'examples']) if (facts[key] !== undefined) entry[key] = facts[key]
if (manifest.engine !== undefined) entry.engine = manifest.engine
+ if (manifest.engine !== undefined) entry.engines = dshSupportedEngines(manifest as DshManifest)
const viewer = manifest.viewer as { use?: unknown } | undefined
if (typeof viewer?.use === 'string') entry.viewerUse = viewer.use
entry.tier = manifest.viewer ? 2 : manifest.verdict ? 1 : 0
diff --git a/cli/src/dsh/runtime.spec.ts b/cli/src/dsh/runtime.spec.ts
new file mode 100644
index 000000000..48a1c842a
--- /dev/null
+++ b/cli/src/dsh/runtime.spec.ts
@@ -0,0 +1,392 @@
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import { execFileSync } from 'node:child_process'
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, readlinkSync, realpathSync, rmSync, symlinkSync, unlinkSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { PROCESS_ENGINES } from '../engines/types.js'
+import { buildEngineCommandArgv, buildEngineLaunchArgv } from '../lib/engineLaunch.js'
+import { buildLaunchOverrides } from '../lib/launchOverrides.js'
+import type { InstalledDsh } from './installed.js'
+import { HARNESS_ADAPTERS, HARNESS_BOOTSTRAP, harnessAdapter } from './adapters.js'
+import { compatibleHarnessEngines } from './compatibility.js'
+import { forkRuntimeKey, harnessLaunchOrRefusal, harnessRuntimeDir, incompatibleHarnessEngine, migrateHarnessInstructions, prepareHarnessLaunch } from './runtime.js'
+
+let root: string
+let ws: string
+let pkg: InstalledDsh
+const write = (path: string, text: string) => {
+ mkdirSync(join(path, '..'), { recursive: true })
+ writeFileSync(path, text)
+}
+beforeEach(() => {
+ root = realpathSync(mkdtempSync(join(tmpdir(), 'portable harness-')))
+ ws = join(root, 'project with spaces')
+ mkdirSync(ws)
+ const dir = join(root, 'package')
+ write(join(dir, 'AGENTS.md'), '# Make a drawing\nRead the draw skill before working.\n')
+ write(join(dir, 'skills/draw/SKILL.md'), '# Draw\nRun the toolchain and write .harness/verdict.json.\n')
+ pkg = { id: 'acme/draw', dir, realDir: dir, source: dir, ref: null, commit: null, linked: true, installedAt: 1,
+ manifest: { spec: 1, id: 'acme/draw', name: 'Drawing', engine: 'claude',
+ agent: { instructions: 'AGENTS.md', skills: ['skills'], args: ['--add-dir', '${workspace}/input'],
+ env: { TOOLCHAIN: '${dsh}/tools', OLD_SKILLS: '${workspace}/.claude/skills', OTHER_SKILLS: '${workspace}/.agents/skills', HARNESS_DSH: 'spoofed' } } } }
+})
+afterEach(() => rmSync(root, { recursive: true, force: true }))
+
+describe('portable harness adapters', () => {
+ it('has a contract for every process engine, with no package allowlist', () => {
+ expect(Object.keys(HARNESS_ADAPTERS)).toEqual(PROCESS_ENGINES)
+ for (const engine of PROCESS_ENGINES) {
+ expect(compatibleHarnessEngines({ engine })[0]).toBe(engine)
+ expect(new Set(compatibleHarnessEngines({ engine }))).toEqual(new Set(PROCESS_ENGINES))
+ }
+ expect(compatibleHarnessEngines({})).toEqual([])
+ expect(compatibleHarnessEngines({ kind: 'viewer', engine: 'claude' })).toEqual([])
+ expect(compatibleHarnessEngines({ engine: 'terminal' })).toEqual([])
+ expect(() => harnessAdapter('terminal')).toThrow('Terminal cannot run')
+ })
+
+ for (const engine of PROCESS_ENGINES) it(`${engine}: binds the same harness and preserves the engine at launch`, () => {
+ const launch = prepareHarnessLaunch(pkg, ws, engine, engine)
+ const bootstrap = engine === 'claude' ? 'CLAUDE.md' : 'AGENTS.md'
+ expect(readFileSync(join(ws, bootstrap), 'utf8')).toContain(HARNESS_BOOTSTRAP)
+ expect(readFileSync(launch.env.HARNESS_CONTEXT_FILE!, 'utf8')).toContain('# Make a drawing')
+ expect(readFileSync(launch.env.HARNESS_CONTEXT_FILE!, 'utf8')).toContain(join(launch.env.HARNESS_SKILLS_DIR!, 'draw/SKILL.md'))
+ expect(readlinkSync(join(launch.env.HARNESS_SKILLS_DIR!, 'draw'))).toBe(join(pkg.realDir, 'skills/draw'))
+ expect(launch.env).toMatchObject({ HARNESS_DSH: pkg.id, HARNESS_DSH_DIR: pkg.realDir, HARNESS_WORKSPACE: ws,
+ TOOLCHAIN: join(pkg.realDir, 'tools'), OLD_SKILLS: launch.env.HARNESS_SKILLS_DIR, OTHER_SKILLS: launch.env.HARNESS_SKILLS_DIR })
+ expect(launch.args.includes('--add-dir')).toBe(engine === 'claude')
+ expect(buildEngineCommandArgv(engine, { extraArgs: launch.args }).slice(-launch.args.length || Infinity)).toEqual(launch.args)
+ expect(existsSync(join(ws, '.claude/skills'))).toBe(false)
+ expect(existsSync(join(ws, '.agents/skills'))).toBe(false)
+ })
+
+ for (const [engine, file] of [['codex', 'AGENTS.override.md'], ['pi', 'CLAUDE.md'], ['hermes', '.hermes.md'], ['hermes', '.cursorrules'], ['opencode', 'CLAUDE.md'], ['agy', 'GEMINI.md']] as const) {
+ it(`${engine}: respects existing ${file} and preserves its bytes`, () => {
+ write(join(ws, file), '# My project rules')
+ const first = prepareHarnessLaunch(pkg, ws, engine, 'session')
+ const once = readFileSync(join(ws, file), 'utf8')
+ expect(once.startsWith('# My project rules\n')).toBe(true)
+ expect(once).toContain(HARNESS_BOOTSTRAP)
+ expect(prepareHarnessLaunch(pkg, ws, engine, 'session')).toEqual(first)
+ expect(readFileSync(join(ws, file), 'utf8')).toBe(once)
+ })
+ }
+})
+
+describe('session isolation and lifecycle', () => {
+ it('makes legacy skill commands executable without redirecting upstream source paths', () => {
+ write(join(pkg.realDir, 'AGENTS.md'), 'You are Codex in this workspace.\n' +
+ '```sh\ncat .agents/skills/draw/SKILL.md\n```\n' +
+ 'Read `.claude/skills/draw/SKILL.md`. Keep `$STUDIO_UPSTREAM/.claude/skills/reference/` and `runtime/.agents/skills/source/` and `.agents/skills-other`.\n')
+ const launch = prepareHarnessLaunch(pkg, ws, 'codex', 'legacy-paths')
+ const content = readFileSync(launch.env.HARNESS_CONTEXT_FILE!, 'utf8')
+ expect(content).toContain('You are an agent in this workspace.')
+ expect(content).toContain('`"$HARNESS_SKILLS_DIR"/draw/SKILL.md`')
+ expect(content).toContain('$STUDIO_UPSTREAM/.claude/skills/reference/')
+ expect(content).toContain('runtime/.agents/skills/source/')
+ expect(content).toContain('.agents/skills-other')
+ const command = content.match(/```sh\n([^`]+)```/)![1]!
+ expect(execFileSync('/bin/sh', ['-c', command], { encoding: 'utf8', env: { PATH: process.env.PATH, ...launch.env } })).toContain('# Draw')
+ })
+
+ it('does not inherit the previous account private grid on a harness relaunch', async () => {
+ const result = await buildLaunchOverrides({ machine: () => ({ hermesSystemManaged: false }),
+ writeGridConfigDir: async () => '/unused', tmuxSupportsSessionEnv: async () => true,
+ installCodexHooks: () => {}, dshLaunch: () => prepareHarnessLaunch(pkg, ws, 'claude', 'new-account'),
+ }, 'claude', { dsh: pkg.id, cwd: ws }, 'agent')
+ if (!result.ok) throw new Error(result.detail)
+ const [, , script] = buildEngineLaunchArgv('claude', { clearEnv: result.overrides.clearEnv }, '/bin/sh', undefined, undefined, null)
+ const seen = execFileSync('/bin/sh', ['-c', script!, 'harness-engine', '/bin/sh', '-c',
+ 'test -z "${HARNESS_PRIVATE_GRID+x}" || exit 9; printf "%s" "$HARNESS_CONTEXT_FILE"'], {
+ encoding: 'utf8', env: { ...process.env, HARNESS_PRIVATE_GRID: 'another-account', ...result.overrides.env }, stdio: ['ignore', 'pipe', 'pipe'],
+ })
+ expect(seen).toBe(result.overrides.env.HARNESS_CONTEXT_FILE)
+ })
+
+ it('keeps two harnesses in one project separate, leaving no harness content in project rules', () => {
+ write(join(ws, 'AGENTS.md'), '# My project rules\n')
+ const a = prepareHarnessLaunch(pkg, ws, 'codex', 'a')
+ const second: InstalledDsh = { ...pkg, id: 'acme/music', manifest: { ...pkg.manifest, id: 'acme/music', name: 'Music' } }
+ write(join(pkg.realDir, 'AGENTS.md'), '# Make music\n')
+ const b = prepareHarnessLaunch(second, ws, 'codex', 'b')
+ expect(a.env.HARNESS_CONTEXT_FILE).not.toBe(b.env.HARNESS_CONTEXT_FILE)
+ expect(readFileSync(a.env.HARNESS_CONTEXT_FILE!, 'utf8')).toContain('# Make a drawing')
+ expect(readFileSync(b.env.HARNESS_CONTEXT_FILE!, 'utf8')).not.toContain('# Make a drawing')
+ expect(readFileSync(join(ws, 'AGENTS.md'), 'utf8')).toBe(`# My project rules\n\n${HARNESS_BOOTSTRAP}`)
+ })
+
+ it('resumes and forks the original engine/content/env/args despite package changes, refreshing account facts', async () => {
+ const first = prepareHarnessLaunch(pkg, ws, 'claude', 'original', { privateGrid: 'old-grid' })
+ pkg.manifest.engine = 'codex'
+ pkg.manifest.agent!.args = ['--new-flag']
+ pkg.manifest.agent!.env = { TOOLCHAIN: 'changed' }
+ write(join(pkg.realDir, 'AGENTS.md'), '# Updated instructions\n')
+ const deps = { machine: () => ({ hermesSystemManaged: false }), writeGridConfigDir: async () => '/cfg',
+ tmuxSupportsSessionEnv: async () => true, installCodexHooks: () => {},
+ dshLaunch: (_id: string, workspace: string, engine: typeof PROCESS_ENGINES[number] | 'terminal', key: string) =>
+ prepareHarnessLaunch(pkg, workspace, engine, key, { privateGrid: 'new-grid' }) }
+ const result = await buildLaunchOverrides(deps, 'claude', { dsh: pkg.id, cwd: ws, dshRuntime: 'original' }, 'registry-agent-id')
+ expect(result.ok && result.overrides.env.HARNESS_CONTEXT_FILE).toBe(first.env.HARNESS_CONTEXT_FILE)
+ expect(result.ok && result.overrides.env.HARNESS_PRIVATE_GRID).toBe('new-grid')
+ expect(result.ok && result.overrides.extraArgs).toEqual(first.args)
+ const fork = prepareHarnessLaunch(pkg, ws, 'claude', 'fork', {}, 'original')
+ expect(fork.env.HARNESS_CONTEXT_FILE).not.toBe(first.env.HARNESS_CONTEXT_FILE)
+ expect(readFileSync(fork.env.HARNESS_CONTEXT_FILE!, 'utf8')).toContain('# Make a drawing')
+ expect(fork.env.TOOLCHAIN).toBe(first.env.TOOLCHAIN)
+ expect(fork.env.HARNESS_PRIVATE_GRID).toBeUndefined()
+ const fresh = prepareHarnessLaunch(pkg, ws, 'codex', 'fresh')
+ expect(readFileSync(fresh.env.HARNESS_CONTEXT_FILE!, 'utf8')).toContain('# Updated instructions')
+ expect(fresh.args).toEqual(['--new-flag'])
+ })
+
+ it('keeps older rows stable using their agent id and supports package renames', async () => {
+ const deps = { machine: () => ({ hermesSystemManaged: false }), writeGridConfigDir: async () => '/cfg',
+ tmuxSupportsSessionEnv: async () => true, installCodexHooks: () => {},
+ dshLaunch: (_id: string, workspace: string, engine: typeof PROCESS_ENGINES[number] | 'terminal', key: string) => prepareHarnessLaunch(pkg, workspace, engine, key) }
+ const first = await buildLaunchOverrides(deps, 'codex', { dsh: pkg.id, cwd: ws }, 'old-agent')
+ pkg.manifest.formerly = [pkg.id]
+ pkg.id = 'acme/drawing'
+ const next = await buildLaunchOverrides(deps, 'codex', { dsh: pkg.id, cwd: ws }, 'old-agent')
+ expect(next).toEqual(first)
+ })
+
+ it('reports preparation failures, missing dependencies, or no resolver before a relaunch', async () => {
+ const deps = { machine: () => ({ hermesSystemManaged: false }), writeGridConfigDir: async () => '/cfg',
+ tmuxSupportsSessionEnv: async () => true, installCodexHooks: () => {} }
+ expect(await buildLaunchOverrides(deps, 'codex', { dsh: pkg.id, cwd: ws }, 'key')).toMatchObject({ ok: false, error: 'DSH_NOT_INSTALLED' })
+ expect(await buildLaunchOverrides({ ...deps, dshLaunch: () => { throw new Error('broken context') } }, 'codex', { dsh: pkg.id, cwd: ws }, 'key'))
+ .toMatchObject({ ok: false, error: 'DSH_RUNTIME_FAILED', detail: 'Error: broken context' })
+ })
+})
+
+describe('runtime validation and file ownership', () => {
+ it('retries the same fork without replacing an occupied destination with another snapshot', () => {
+ prepareHarnessLaunch(pkg, ws, 'codex', 'source')
+ const fork = prepareHarnessLaunch(pkg, ws, 'codex', 'fork', {}, 'source')
+ expect(prepareHarnessLaunch(pkg, ws, 'codex', 'fork', {}, 'source')).toEqual(fork)
+ const before = readFileSync(fork.env.HARNESS_CONTEXT_FILE!, 'utf8')
+ write(join(pkg.realDir, 'AGENTS.md'), '# Different instructions\n')
+ prepareHarnessLaunch(pkg, ws, 'codex', 'other-source')
+ expect(() => prepareHarnessLaunch(pkg, ws, 'codex', 'fork', {}, 'other-source')).toThrow('fork destination already has a different harness runtime')
+ expect(readFileSync(fork.env.HARNESS_CONTEXT_FILE!, 'utf8')).toBe(before)
+ const file = join(harnessRuntimeDir(ws, 'fork'), 'runtime.json')
+ const saved = readFileSync(file, 'utf8')
+ write(file, '{corrupt')
+ expect(() => prepareHarnessLaunch(pkg, ws, 'codex', 'fork', {}, 'source')).toThrow()
+ write(file, saved)
+ rmSync(file)
+ symlinkSync(join(root, 'missing'), file)
+ expect(() => prepareHarnessLaunch(pkg, ws, 'codex', 'fork', {}, 'source')).toThrow('snapshot is a symlink')
+ })
+
+ it('keeps runtime snapshots out of Git while preserving existing ignore rules', () => {
+ write(join(ws, '.harness/.gitignore'), '# User rules\nmy-data');
+ prepareHarnessLaunch(pkg, ws, 'codex', 'key');
+ expect(readFileSync(join(ws, '.harness/.gitignore'), 'utf8')).toBe('# User rules\nmy-data\nruntime/\nlegacy-AGENTS.md\n');
+ prepareHarnessLaunch(pkg, ws, 'codex', 'key');
+ expect(readFileSync(join(ws, '.harness/.gitignore'), 'utf8').match(/runtime\//g)).toHaveLength(1);
+ })
+
+ it('supports a minimal harness and deduplicates repeated skill roots', () => {
+ pkg.manifest.agent = undefined
+ const launch = prepareHarnessLaunch(pkg, ws, 'codex', '../../outside')
+ expect(launch.env.HARNESS_CONTEXT_FILE).toContain(join(ws, '.harness/runtime'))
+ expect(readFileSync(launch.env.HARNESS_CONTEXT_FILE!, 'utf8')).toContain('## Harness skills')
+ pkg.manifest.agent = { skills: ['skills', 'skills/draw'] }
+ const next = prepareHarnessLaunch(pkg, ws, 'codex', 'dedup')
+ expect(readFileSync(next.env.HARNESS_CONTEXT_FILE!, 'utf8').match(/- draw:/g)).toHaveLength(1)
+ expect(() => harnessRuntimeDir(ws, '')).toThrow('session key')
+ })
+
+ it('imports existing AGENTS rules for Claude once and normalizes legacy engine introductions', () => {
+ write(join(ws, 'AGENTS.md'), '# Repository rules\n')
+ write(join(pkg.realDir, 'AGENTS.md'), 'You are Claude Code in a drawing workspace.\n')
+ const launch = prepareHarnessLaunch(pkg, ws, 'claude', 'first')
+ expect(readFileSync(launch.env.HARNESS_CONTEXT_FILE!, 'utf8')).toContain('You are an agent in a drawing workspace.')
+ expect(readFileSync(join(ws, 'CLAUDE.md'), 'utf8')).toContain('@AGENTS.md\n')
+ write(join(ws, 'CLAUDE.md'), '# Claude project rules\[email protected]\n')
+ prepareHarnessLaunch(pkg, ws, 'claude', 'second')
+ expect(readFileSync(join(ws, 'CLAUDE.md'), 'utf8').match(/@AGENTS.md/g)).toHaveLength(1)
+ })
+
+ it('rejects terminal/viewer, missing instructions/skills, and duplicate skill names', () => {
+ expect(() => prepareHarnessLaunch(pkg, ws, 'terminal', 'key')).toThrow('Terminal cannot run')
+ pkg.manifest.kind = 'viewer'
+ expect(() => prepareHarnessLaunch(pkg, ws, 'codex', 'key')).toThrow('viewer')
+ delete pkg.manifest.kind
+ pkg.manifest.agent!.instructions = 'missing.md'
+ expect(() => prepareHarnessLaunch(pkg, ws, 'codex', 'key')).toThrow('ENOENT')
+ delete pkg.manifest.agent!.instructions
+ pkg.manifest.agent!.skills = ['missing']
+ expect(() => prepareHarnessLaunch(pkg, ws, 'codex', 'key')).toThrow('No SKILL.md')
+ write(join(pkg.realDir, 'other/draw/SKILL.md'), '# Other draw')
+ pkg.manifest.agent!.skills = ['skills', 'other']
+ expect(() => prepareHarnessLaunch(pkg, ws, 'codex', 'key')).toThrow('Duplicate harness skill')
+ expect(existsSync(join(ws, 'AGENTS.md'))).toBe(false)
+ })
+
+ it('refuses a different saved engine or package, corrupt snapshots and missing fork sources', () => {
+ prepareHarnessLaunch(pkg, ws, 'codex', 'key')
+ expect(() => prepareHarnessLaunch(pkg, ws, 'claude', 'key')).toThrow('runtime belongs')
+ expect(() => prepareHarnessLaunch({ ...pkg, id: 'acme/other' }, ws, 'codex', 'key')).toThrow('runtime belongs')
+ expect(() => prepareHarnessLaunch(pkg, ws, 'codex', 'fork', {}, 'missing')).toThrow('original harness runtime is missing')
+ const file = join(harnessRuntimeDir(ws, 'key'), 'runtime.json')
+ write(file, '{broken')
+ expect(() => prepareHarnessLaunch(pkg, ws, 'codex', 'key')).toThrow()
+ write(file, '{"version":2}')
+ expect(() => prepareHarnessLaunch(pkg, ws, 'codex', 'key')).toThrow()
+ rmSync(file)
+ symlinkSync(join(root, 'outside'), file)
+ expect(() => prepareHarnessLaunch(pkg, ws, 'codex', 'key')).toThrow('snapshot is a symlink')
+ })
+
+ for (const target of ['.harness', '.harness/runtime', 'bundle', 'skills']) it(`refuses symlinked ${target} directories`, () => {
+ const path = target === 'bundle' ? harnessRuntimeDir(ws, 'key') : target === 'skills' ? join(harnessRuntimeDir(ws, 'key'), 'skills') : join(ws, target)
+ mkdirSync(join(path, '..'), { recursive: true })
+ symlinkSync(join(root, 'does-not-exist'), path)
+ expect(() => prepareHarnessLaunch(pkg, ws, 'codex', 'key')).toThrow('not a plain directory')
+ })
+
+ it('refuses directory collisions, user links, edited bootstraps and modified context links', () => {
+ write(join(ws, '.harness'), 'user file')
+ expect(() => prepareHarnessLaunch(pkg, ws, 'codex', 'key')).toThrow('not a plain directory')
+ rmSync(join(ws, '.harness'))
+ write(join(root, 'my-rules'), '# My rules')
+ symlinkSync(join(root, 'my-rules'), join(ws, 'AGENTS.md'))
+ expect(() => prepareHarnessLaunch(pkg, ws, 'codex', 'key')).toThrow('Refusing to replace a symlink')
+ expect(readFileSync(join(root, 'my-rules'), 'utf8')).toBe('# My rules')
+ rmSync(join(ws, 'AGENTS.md'))
+ write(join(ws, 'AGENTS.md'), '<!-- harness:runtime v1 -->\nedited')
+ expect(() => prepareHarnessLaunch(pkg, ws, 'codex', 'key')).toThrow('bootstrap')
+ rmSync(join(ws, 'AGENTS.md'))
+ const launch = prepareHarnessLaunch(pkg, ws, 'codex', 'key')
+ rmSync(launch.env.HARNESS_CONTEXT_FILE!)
+ symlinkSync(join(root, 'my-rules'), launch.env.HARNESS_CONTEXT_FILE!)
+ expect(() => prepareHarnessLaunch(pkg, ws, 'codex', 'key')).toThrow('Refusing to replace a symlink')
+ })
+
+ it('refuses missing skills and occupied skill paths without touching them', () => {
+ const launch = prepareHarnessLaunch(pkg, ws, 'codex', 'key')
+ const skill = join(launch.env.HARNESS_SKILLS_DIR!, 'draw')
+ unlinkSync(skill)
+ mkdirSync(skill)
+ expect(() => prepareHarnessLaunch(pkg, ws, 'codex', 'key')).toThrow('already occupied')
+ rmSync(skill, { recursive: true })
+ symlinkSync(join(root, 'user-skill'), skill)
+ expect(() => prepareHarnessLaunch(pkg, ws, 'codex', 'key')).toThrow('already occupied')
+ rmSync(join(pkg.realDir, 'skills/draw/SKILL.md'))
+ expect(() => prepareHarnessLaunch(pkg, ws, 'codex', 'key')).toThrow('Harness skill is missing')
+ })
+})
+
+describe('non-destructive legacy migration', () => {
+ const legacy = () => `# User rules\n\n<!-- harness:dsh ${pkg.id} -->\n${readFileSync(join(pkg.realDir, 'AGENTS.md'), 'utf8').trim()}\n\n# User additions\n`
+
+ it('archives exact bytes, removes only known instructions and owned native skill links, and is idempotent', () => {
+ const before = legacy()
+ write(join(ws, 'AGENTS.md'), before)
+ for (const native of ['.claude/skills', '.agents/skills']) {
+ mkdirSync(join(ws, native), { recursive: true })
+ symlinkSync(join(pkg.realDir, 'skills/draw'), join(ws, native, 'draw'))
+ symlinkSync(join(root, 'user-owned'), join(ws, native, 'mine'))
+ }
+ migrateHarnessInstructions(ws, pkg)
+ expect(readFileSync(join(ws, 'AGENTS.md'), 'utf8')).toBe('# User rules\n\n\n# User additions\n')
+ expect(readFileSync(join(ws, '.harness/legacy-AGENTS.md'), 'utf8')).toBe(before)
+ expect(existsSync(join(ws, '.claude/skills/draw'))).toBe(false)
+ expect(readlinkSync(join(ws, '.claude/skills/mine'))).toBe(join(root, 'user-owned'))
+ write(join(ws, 'AGENTS.md'), before)
+ migrateHarnessInstructions(ws, pkg)
+ migrateHarnessInstructions(ws, pkg)
+ expect(readFileSync(join(ws, '.harness/legacy-AGENTS.md'), 'utf8')).toBe(before)
+ })
+
+ it('handles renamed and other installed harnesses and preserves non-owned skill paths', () => {
+ write(join(ws, 'AGENTS.md'), legacy())
+ const old = pkg.id
+ pkg.id = 'acme/renamed'
+ pkg.manifest.formerly = [old]
+ mkdirSync(join(ws, '.claude/skills/draw'), { recursive: true })
+ mkdirSync(join(ws, '.agents/skills'), { recursive: true })
+ symlinkSync(join(root, 'my-draw'), join(ws, '.agents/skills/draw'))
+ migrateHarnessInstructions(ws, pkg)
+ expect(readlinkSync(join(ws, '.agents/skills/draw'))).toBe(join(root, 'my-draw'))
+ write(join(ws, 'AGENTS.md'), legacy())
+ migrateHarnessInstructions(ws, { ...pkg, id: 'acme/another', manifest: { ...pkg.manifest, formerly: undefined } }, id => id === pkg.id ? pkg : null)
+ expect(readFileSync(join(ws, 'AGENTS.md'), 'utf8')).not.toContain('harness:dsh')
+ })
+
+ it('preserves native directories reached through symlinks, even when their skill links match', () => {
+ write(join(ws, 'AGENTS.md'), legacy())
+ mkdirSync(join(root, 'external/skills'), { recursive: true })
+ symlinkSync(join(pkg.realDir, 'skills/draw'), join(root, 'external/skills/draw'))
+ symlinkSync(join(root, 'external'), join(ws, '.claude'))
+ mkdirSync(join(ws, '.agents'))
+ symlinkSync(join(root, 'external/skills'), join(ws, '.agents/skills'))
+ migrateHarnessInstructions(ws, pkg)
+ expect(readlinkSync(join(root, 'external/skills/draw'))).toBe(join(pkg.realDir, 'skills/draw'))
+ })
+
+ it('leaves edited or unknown legacy sections intact and returns an actionable failure', () => {
+ write(join(ws, 'AGENTS.md'), legacy().replace('# Make a drawing', '# My edits'))
+ expect(() => migrateHarnessInstructions(ws, pkg)).toThrow('were edited')
+ write(join(ws, 'AGENTS.md'), '<!-- harness:dsh gone/away -->\n# Lost instructions\n')
+ expect(() => migrateHarnessInstructions(ws, pkg, () => null)).toThrow('restore the package')
+ expect(() => migrateHarnessInstructions(ws, pkg, () => ({ ...pkg, manifest: { ...pkg.manifest, agent: undefined } }))).toThrow('restore the package')
+ expect(readFileSync(join(ws, 'AGENTS.md'), 'utf8')).toContain('# Lost instructions')
+ })
+
+ it('migrates instruction-only harnesses without replacing an existing backup symlink', () => {
+ delete pkg.manifest.agent!.skills
+ write(join(ws, 'AGENTS.md'), legacy())
+ mkdirSync(join(ws, '.harness'))
+ symlinkSync(join(root, 'my-backup'), join(ws, '.harness/legacy-AGENTS.md'))
+ migrateHarnessInstructions(ws, pkg)
+ expect(readlinkSync(join(ws, '.harness/legacy-AGENTS.md'))).toBe(join(root, 'my-backup'))
+ })
+})
+
+// The decisions the daemon's create and fork handlers make about a harness launch. They live here,
+// not inline in cli.ts, because that file is never loaded by a unit test and these are the cases a
+// refused launch depends on.
+describe('create and fork decisions', () => {
+ it('names what WOULD run when an engine cannot run the harness', () => {
+ expect(incompatibleHarnessEngine('acme/draw', pkg.manifest, 'codex')).toBeNull()
+ expect(incompatibleHarnessEngine('acme/draw', pkg.manifest, 'claude')).toBeNull()
+ const refusal = incompatibleHarnessEngine('acme/draw', pkg.manifest, 'terminal')
+ expect(refusal).toMatch(/^acme\/draw supports claude, /)
+ expect(refusal).toMatch(/; terminal is not compatible$/)
+ })
+
+ it('refuses every engine for something that is not a runnable harness', () => {
+ for (const manifest of [{ kind: 'viewer', engine: 'claude' as const }, {}, { engine: 'terminal' as const }]) {
+ expect(incompatibleHarnessEngine('acme/view', manifest, 'claude')).toBe('acme/view cannot run as an agent')
+ }
+ })
+
+ it('forks the runtime the source recorded', () => {
+ expect(forkRuntimeKey({ cwd: ws, agentId: 'a1', dshRuntime: 'harness-claude-x' })).toBe('harness-claude-x')
+ })
+
+ it('forks a pre-key session from the bundle under its agent id, and otherwise starts fresh', () => {
+ const source = { cwd: ws, agentId: 'a1', dshRuntime: null }
+ expect(forkRuntimeKey(source)).toBeNull()
+ expect(forkRuntimeKey({ cwd: ws, agentId: 'a1' })).toBeNull()
+ prepareHarnessLaunch(pkg, ws, 'claude', 'a1')
+ expect(existsSync(join(harnessRuntimeDir(ws, 'a1'), 'runtime.json'))).toBe(true)
+ expect(forkRuntimeKey(source)).toBe('a1')
+ // An empty recorded key is no key: it must not shadow the bundle that exists.
+ expect(forkRuntimeKey({ ...source, dshRuntime: '' })).toBe('a1')
+ })
+
+ it('turns a runtime that cannot be prepared into a refusal, never a throw', () => {
+ const ok = harnessLaunchOrRefusal(() => prepareHarnessLaunch(pkg, ws, 'claude', 'k'))
+ expect(ok.ok).toBe(true)
+ rmSync(join(pkg.realDir, 'skills/draw/SKILL.md'))
+ const refused = harnessLaunchOrRefusal(() => prepareHarnessLaunch(pkg, ws, 'claude', 'fresh'))
+ expect(refused).toMatchObject({ ok: false, error: 'DSH_RUNTIME_FAILED' })
+ expect(refused.ok ? '' : refused.detail).not.toMatch(/^Error: /)
+ expect(harnessLaunchOrRefusal(() => { throw 'a bare string' })).toEqual(
+ { ok: false, error: 'DSH_RUNTIME_FAILED', detail: 'a bare string' })
+ })
+})
diff --git a/cli/src/dsh/runtime.ts b/cli/src/dsh/runtime.ts
new file mode 100644
index 000000000..bb285cde6
--- /dev/null
+++ b/cli/src/dsh/runtime.ts
@@ -0,0 +1,232 @@
+/** Session-scoped harness content. No native skill directories or shared mutable engine config.
+ * Create snapshots instructions/env/argv; resume reads that snapshot; fork copies it under a new
+ * key. Toolchains and skill assets stay at their installed package paths, as in spec 1.
+ */
+import { createHash } from 'node:crypto'
+import { existsSync, lstatSync, mkdirSync, readFileSync, readlinkSync, realpathSync, rmSync, symlinkSync, unlinkSync, writeFileSync } from 'node:fs'
+import { basename, join, resolve } from 'node:path'
+import { z } from 'zod'
+import { PROCESS_ENGINES, type AgentEngine } from '../engines/types.js'
+import { HARNESS_BOOTSTRAP, harnessAdapter } from './adapters.js'
+import { installedDsh, type InstalledDsh } from './installed.js'
+import { dshAccountEnv, dshLaunch, type DshAccount, type DshLaunch } from './launch.js'
+import { compatibleHarnessEngines } from './compatibility.js'
+import { skillDirsIn } from './materialize.js'
+
+const Snapshot = z.object({
+ version: z.literal(1),
+ id: z.string(),
+ engine: z.enum(PROCESS_ENGINES as [typeof PROCESS_ENGINES[number], ...typeof PROCESS_ENGINES[number][]]),
+ instructions: z.string(),
+ env: z.record(z.string(), z.string()),
+ args: z.array(z.string()),
+ skills: z.array(z.object({ name: z.string().regex(/^[^/\\\x00]+$/).refine(name => name !== '.' && name !== '..'), dir: z.string() })),
+})
+type RuntimeSnapshot = z.infer<typeof Snapshot>
+
+export function harnessRuntimeDir(workspace: string, key: string): string {
+ if (!key) throw new Error('A harness runtime needs a session key')
+ return join(workspace, '.harness', 'runtime', createHash('sha256').update(key).digest('hex'))
+}
+
+/** Do not follow user-created links when writing managed files. The project itself may be a link. */
+function ensureRuntimeDir(workspace: string, dir: string): void {
+ const root = resolve(workspace)
+ let path = root
+ for (const part of dir.slice(root.length + 1).split('/')) {
+ path = join(path, part)
+ if (existsSync(path) || isLink(path)) {
+ const stat = lstatSync(path)
+ if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error(`Harness runtime directory is not a plain directory: ${path}`)
+ } else mkdirSync(path)
+ }
+}
+
+function isLink(path: string): boolean {
+ try { return lstatSync(path).isSymbolicLink() } catch { return false }
+}
+
+function writeManagedFile(path: string, body: string): void {
+ if (isLink(path)) throw new Error(`Refusing to replace a symlink: ${path}`)
+ writeFileSync(path, body, { mode: 0o600 })
+}
+
+/** Older versions appended a marker without an end marker. Remove only text that exactly matches
+ * an installed package's instructions; refuse ambiguous edits instead of guessing where user text
+ * ends. Also remove only native skill links whose targets are demonstrably owned by that package.
+ */
+export function migrateHarnessInstructions(workspace: string, current: InstalledDsh,
+ lookup: (id: string) => InstalledDsh | null | undefined = installedDsh): void {
+ const path = join(workspace, 'AGENTS.md')
+ if (!existsSync(path)) return
+ const before = readFileSync(path, 'utf8')
+ let after = before
+ const packages: InstalledDsh[] = []
+ for (const match of before.matchAll(/^<!-- harness:dsh ([a-z0-9/-]+) -->\r?\n/gm)) {
+ const id = match[1]!
+ const pkg = id === current.id || current.manifest.formerly?.includes(id) ? current : lookup(id)
+ const instructions = pkg?.manifest.agent?.instructions
+ if (!pkg || !instructions) throw new Error(`Cannot safely migrate old harness instructions for ${id} in ${path}; restore the package or remove its marked section.`)
+ const body = readFileSync(join(pkg.realDir, instructions), 'utf8').trim()
+ const block = `${match[0]}${body}\n`
+ if (!after.includes(block)) throw new Error(`The old harness instructions for ${id} in ${path} were edited; move that marked section out of AGENTS.md before launching.`)
+ after = after.replace(block, '')
+ packages.push(pkg)
+ }
+ if (after === before) return
+ // Keep the exact pre-migration bytes; never replace somebody's earlier backup.
+ const backup = join(workspace, '.harness', 'legacy-AGENTS.md')
+ ensureRuntimeDir(workspace, join(resolve(workspace), '.harness'))
+ if (!existsSync(backup) && !isLink(backup)) writeFileSync(backup, before, { flag: 'wx', mode: 0o600 })
+ writeManagedFile(path, after)
+ for (const pkg of packages) {
+ for (const root of pkg.manifest.agent?.skills ?? []) {
+ for (const skill of skillDirsIn(join(pkg.realDir, root))) {
+ for (const native of ['.claude/skills', '.agents/skills']) {
+ if (isLink(join(workspace, native.split('/')[0]!)) || isLink(join(workspace, native))) continue
+ const link = join(workspace, native, basename(skill))
+ // unlinkSync, not rmSync: on current Node rmSync follows a link to a directory and
+ // throws EISDIR, which crashed the migration it exists to finish. A link is unlinked.
+ if (isLink(link) && resolve(link, '..', readlinkSync(link)) === resolve(skill)) unlinkSync(link)
+ }
+ }
+ }
+ }
+}
+
+function installBootstrap(workspace: string, engine: AgentEngine): void {
+ const adapter = harnessAdapter(engine)
+ const file = adapter.instructionFiles.find(name => existsSync(join(workspace, name)))
+ ?? (engine === 'claude' ? 'CLAUDE.md' : 'AGENTS.md')
+ const path = join(workspace, file)
+ const before = existsSync(path) ? readFileSync(path, 'utf8') : ''
+ if (before.includes(HARNESS_BOOTSTRAP)) return
+ if (before.includes('<!-- harness:runtime')) throw new Error(`The Harness bootstrap in ${path} was edited; restore it before launching.`)
+ const projectRules = engine === 'claude' && existsSync(join(workspace, 'AGENTS.md')) && !before.split('\n').some(line => line.trim() === '@AGENTS.md')
+ ? '@AGENTS.md\n' : ''
+ // Preserve all project bytes. Only the generic, env-dispatched bootstrap is shared by sessions.
+ writeManagedFile(path, `${before}${before.endsWith('\n') || !before ? '' : '\n'}\n${projectRules}${HARNESS_BOOTSTRAP}`)
+}
+
+function snapshot(dsh: InstalledDsh, workspace: string, engine: AgentEngine): RuntimeSnapshot {
+ harnessAdapter(engine)
+ const source = dsh.manifest.agent?.instructions
+ const instructions = source ? readFileSync(join(dsh.realDir, source), 'utf8') : ''
+ const skills: RuntimeSnapshot['skills'] = []
+ for (const root of dsh.manifest.agent?.skills ?? []) {
+ const dirs = skillDirsIn(join(dsh.realDir, root))
+ if (!dirs.length) throw new Error(`No SKILL.md under ${join(dsh.realDir, root)}; repair the harness installation.`)
+ for (const dir of dirs) {
+ const name = basename(dir)
+ const found = skills.find(skill => skill.name === name)
+ if (found && found.dir !== dir) throw new Error(`Duplicate harness skill name: ${name}`)
+ if (!found) skills.push({ name, dir })
+ }
+ }
+ const launch = dshLaunch(dsh, workspace, {}, engine)
+ return Snapshot.parse({ version: 1, id: dsh.id, engine, instructions, env: launch.env, args: launch.args, skills })
+}
+
+/** Prepare before spawning any engine process. `sourceKey` is a fork's original bundle. A saved
+ * bundle is authoritative: changing the store default or instructions cannot retarget a session.
+ */
+/**
+ * Why `engine` cannot run the harness `id`, or null when it can. The words are what a refused
+ * create says, so they name what WOULD work rather than only what was wrong.
+ */
+export function incompatibleHarnessEngine(id: string, manifest: { kind?: string; engine?: AgentEngine },
+ engine: AgentEngine): string | null {
+ const supported = compatibleHarnessEngines(manifest)
+ if (supported.includes(engine)) return null
+ return supported.length
+ ? `${id} supports ${supported.join(', ')}; ${engine} is not compatible`
+ : `${id} cannot run as an agent`
+}
+
+/**
+ * The runtime bundle a fork copies. A session records its key when it is created; one created
+ * before keys were recorded still has a bundle under its agent id if it ran on this version, and
+ * that is the one to copy. Neither means the fork starts a fresh bundle rather than failing.
+ */
+export function forkRuntimeKey(source: { cwd: string; agentId: string; dshRuntime?: string | null }): string | null {
+ if (source.dshRuntime) return source.dshRuntime
+ return existsSync(join(harnessRuntimeDir(source.cwd, source.agentId), 'runtime.json')) ? source.agentId : null
+}
+
+/**
+ * `prepare`, refused rather than thrown. A runtime that cannot be prepared — a missing skill, a
+ * corrupt snapshot, an occupied path — has to fail the one create or fork that asked for it, never
+ * the daemon that is serving every other session.
+ */
+export function harnessLaunchOrRefusal(prepare: () => DshLaunch):
+ { ok: true; launch: DshLaunch } | { ok: false; error: 'DSH_RUNTIME_FAILED'; detail: string } {
+ try {
+ return { ok: true, launch: prepare() }
+ } catch (error) {
+ return { ok: false, error: 'DSH_RUNTIME_FAILED', detail: error instanceof Error ? error.message : String(error) }
+ }
+}
+
+export function prepareHarnessLaunch(dsh: InstalledDsh, workspace: string, engine: AgentEngine,
+ key: string, account: DshAccount = {}, sourceKey?: string | null): DshLaunch {
+ const adapter = harnessAdapter(engine)
+ if (dsh.manifest.kind === 'viewer') throw new Error(`${dsh.id} is a viewer, not a harness`)
+ const ws = realpathSync(workspace)
+ const dir = harnessRuntimeDir(ws, key)
+ ensureRuntimeDir(ws, dir)
+ const ignoreFile = join(ws, '.harness', '.gitignore')
+ const ignored = existsSync(ignoreFile) ? readFileSync(ignoreFile, 'utf8') : ''
+ const ignoreRules = ['runtime/', 'legacy-AGENTS.md'].filter(rule => !ignored.split('\n').includes(rule))
+ if (ignoreRules.length) writeManagedFile(ignoreFile, `${ignored}${ignored && !ignored.endsWith('\n') ? '\n' : ''}${ignoreRules.join('\n')}\n`)
+ const file = join(dir, 'runtime.json')
+ const from = sourceKey ? join(harnessRuntimeDir(ws, sourceKey), 'runtime.json') : file
+ if (sourceKey) {
+ ensureRuntimeDir(ws, harnessRuntimeDir(ws, sourceKey))
+ if (!existsSync(from)) throw new Error(`The original harness runtime is missing: ${from}`)
+ }
+ if (isLink(from)) throw new Error(`Harness runtime snapshot is a symlink: ${from}`)
+ const data = existsSync(from) ? Snapshot.parse(JSON.parse(readFileSync(from, 'utf8'))) : snapshot(dsh, ws, engine)
+ if (data.engine !== engine || (data.id !== dsh.id && !dsh.manifest.formerly?.includes(data.id))) {
+ throw new Error(`Harness runtime belongs to ${data.id} / ${data.engine}, not ${dsh.id} / ${engine}`)
+ }
+ if (sourceKey && (existsSync(file) || isLink(file))) {
+ if (isLink(file)) throw new Error(`Harness runtime snapshot is a symlink: ${file}`)
+ const saved = Snapshot.parse(JSON.parse(readFileSync(file, 'utf8')))
+ if (JSON.stringify(saved) !== JSON.stringify(data)) throw new Error(`The fork destination already has a different harness runtime: ${file}`)
+ }
+ const skillsDir = join(dir, 'skills')
+ ensureRuntimeDir(ws, skillsDir)
+ // Validate before modifying project instructions or committing a snapshot.
+ for (const skill of data.skills) {
+ if (!existsSync(join(skill.dir, 'SKILL.md'))) throw new Error(`Harness skill is missing: ${skill.dir}; repair the harness installation.`)
+ const link = join(skillsDir, skill.name)
+ if (existsSync(link) || isLink(link)) {
+ if (!isLink(link) || readlinkSync(link) !== skill.dir) throw new Error(`Harness skill path is already occupied: ${link}`)
+ } else symlinkSync(skill.dir, link)
+ }
+ migrateHarnessInstructions(ws, dsh)
+ installBootstrap(ws, engine)
+ const env: Record<string, string> = { ...data.env, ...dshAccountEnv(account), HARNESS_CONTEXT_FILE: join(dir, 'CONTEXT.md'), HARNESS_SKILLS_DIR: skillsDir }
+ // Spec-1 packages used their default engine's discovery paths in env. Translate the path, not
+ // arbitrary engine names or source paths inside an upstream installation.
+ for (const [name, value] of Object.entries(env)) {
+ env[name] = value.replaceAll(`${ws}/.claude/skills`, skillsDir).replaceAll(`${ws}/.agents/skills`, skillsDir)
+ }
+ const context = [
+ `# ${dsh.manifest.name} (${data.id})`,
+ `Engine: ${engine}. Workspace: ${JSON.stringify(ws)}.`,
+ 'Use your file and shell tools for these instructions, skills, and toolchain commands.',
+ 'Legacy references to .claude/skills or .agents/skills mean HARNESS_SKILLS_DIR for this session.',
+ '', data.instructions.trim()
+ .replace(/^You are (?:Claude Code|Codex) in /gm, 'You are an agent in ')
+ // Rewrite workspace-relative examples into executable, quoted commands. Upstream paths such
+ // as $STUDIO_UPSTREAM/.claude/skills remain source paths and must not be redirected.
+ .replace(/(?<![\w/$.{}-])\.(?:claude|agents)\/skills(?![\w-])/g, '"$HARNESS_SKILLS_DIR"'),
+ '', '## Harness skills',
+ ...data.skills.map(skill => `- ${skill.name}: ${JSON.stringify(join(skillsDir, skill.name, 'SKILL.md'))}`),
+ '',
+ ].join('\n')
+ writeManagedFile(env.HARNESS_CONTEXT_FILE!, context)
+ if (!existsSync(file)) writeManagedFile(file, `${JSON.stringify(data, null, 2)}\n`)
+ return { env, args: [...data.args, ...(adapter.contextArgs?.(env.HARNESS_CONTEXT_FILE!) ?? [])] }
+}
diff --git a/cli/src/dsh/studios.integration.spec.ts b/cli/src/dsh/studios.integration.spec.ts
index 16f0c7e0b..f349656eb 100644
--- a/cli/src/dsh/studios.integration.spec.ts
+++ b/cli/src/dsh/studios.integration.spec.ts
@@ -1,3 +1,4 @@
+import { prepareHarnessLaunch } from './runtime.js'
// Explicit opt-in: these checks run the real package installers and native local simulations.
// All index entries and workspaces stay in disposable directories.
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
@@ -55,8 +56,9 @@ describe.runIf(process.env.HARNESS_STUDIO_INTEGRATION === '1')('specialist studi
mkdirSync(workspace)
const materialized = await materializeWorkspace(result.installed, workspace)
expect(materialized.warnings).toEqual([])
- expect(readFileSync(join(workspace, 'AGENTS.md'), 'utf8')).toContain(`autonomous/${name}`)
- expect(lstatSync(join(workspace, '.agents/skills', name)).isSymbolicLink()).toBe(true)
+ const launch = prepareHarnessLaunch(result.installed, workspace, 'codex', name)
+ expect(readFileSync(launch.env.HARNESS_CONTEXT_FILE!, 'utf8')).toContain(`autonomous/${name}`)
+ expect(lstatSync(join(launch.env.HARNESS_SKILLS_DIR!, name)).isSymbolicLink()).toBe(true)
const verdict = JSON.parse(readFileSync(join(workspace, '.harness/verdict.json'), 'utf8'))
expect(verdict.ready).toBe(true)
expect(existsSync(join(workspace, verdict.artifact))).toBe(true)
diff --git a/cli/src/dsh/update.spec.ts b/cli/src/dsh/update.spec.ts
index 1a0c7a359..dbf8722be 100644
--- a/cli/src/dsh/update.spec.ts
+++ b/cli/src/dsh/update.spec.ts
@@ -1,3 +1,4 @@
+import { prepareHarnessLaunch } from './runtime.js'
import { updateDsh } from './update.js'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { execFileSync } from 'node:child_process'
@@ -158,8 +159,9 @@ describe('package updates', { timeout: 30_000 }, () => {
const workspace = join(root, 'workspace')
mkdirSync(workspace)
await materializeWorkspace(before, workspace)
+ const launch = prepareHarnessLaunch(before, workspace, 'claude', 'session')
write(workspace, { 'project.txt': 'my finished work\n', 'AGENTS.md': 'my custom instructions\n', '.harness/verdict.json': '{"ready":true}', 'notes.md': 'my notes' })
- const skill = join(workspace, '.claude', 'skills', 'task')
+ const skill = join(launch.env.HARNESS_SKILLS_DIR!, 'task')
const link = readlinkSync(skill)
const dir = path ? join(repo, path) : repo
write(dir, { 'skills/task/SKILL.md': '# Updated skill\n', 'AGENTS.md': '# New instructions\n', 'template/project.txt': 'new template\n' })
diff --git a/cli/src/dsh/wire.spec.ts b/cli/src/dsh/wire.spec.ts
index 94fe4cdd2..4048a8f85 100644
--- a/cli/src/dsh/wire.spec.ts
+++ b/cli/src/dsh/wire.spec.ts
@@ -1,3 +1,4 @@
+import { dshSupportedEngines } from './manifest.js'
// The DSH wire contract (store/spec/README.md § Wire): what dsh_list rows say, and what dsh_install and
// dsh_remove accept from a payload and answer.
import { describe, expect, it, vi } from 'vitest'
@@ -15,6 +16,13 @@ const installed = (manifest: InstalledDsh['manifest'], linked = false): Installe
})
describe('dshListRows', () => {
+ it('advertises installed compatibility ahead of newer catalog compatibility', () => {
+ const manifest = { spec: 1 as const, id: 'acme/thing', name: 'Thing', engine: 'claude' as const }
+ const catalog: DshRegistryEntry[] = [{ ...manifest, repo: 'https://example.com/thing', engines: ['claude', 'codex'] }]
+ expect(dshListRows([], catalog)[0].engines).toEqual(dshSupportedEngines(manifest))
+ expect(dshListRows([installed(manifest)], catalog)[0].engines).toEqual(dshSupportedEngines(manifest))
+ expect(dshListRows([installed({ ...manifest, agent: { env: { DSH_SUPPORTED_ENGINES: 'claude,codex' } } })], catalog)[0].engines).toEqual(dshSupportedEngines(manifest))
+ })
const registry: DshRegistryEntry[] = [
{
id: 'autonomous/typst', name: 'Typst', category: 'Documents', author: 'Autonomous', description: 'Typeset.', engine: 'claude',
@@ -33,7 +41,7 @@ describe('dshListRows', () => {
], registry)
expect(rows).toEqual([
{
- id: 'autonomous/typst', kind: 'agent', name: 'Typst (local)', description: null, category: null, author: null, engine: 'claude',
+ id: 'autonomous/typst', kind: 'agent', name: 'Typst (local)', description: null, category: null, author: null, engine: 'claude', engines: dshSupportedEngines({ engine: 'claude' }),
installedCommit: null, availableCommit: null, updateAvailable: false,
installed: true, linked: true, viewer: true, viewerUse: 'autonomous/doc-viewer', tier: 2,
verified: true, repo: `${HARNESS_MONOREPO}/tree/main/store/agents/typst`, homepage: 'https://typst.example.com',
@@ -41,18 +49,18 @@ describe('dshListRows', () => {
examples: [{ prompt: 'A spec sheet for an M3 standoff.', image: 'https://example.com/spec.jpg', caption: 'Spec sheet · PDF' }],
},
{
- id: 'acme/private', kind: 'viewer', name: 'Private', description: null, category: null, author: null, engine: null,
+ id: 'acme/private', kind: 'viewer', name: 'Private', description: null, category: null, author: null, engine: null, engines: [],
installedCommit: null, availableCommit: null, updateAvailable: false,
installed: true, linked: false, viewer: true, viewerUse: null, tier: 2,
verified: false, repo: null, homepage: null, upstream: null, license: null, tagline: null, screenshots: [], examples: [],
},
{
- id: 'autonomous/doc-viewer', kind: 'viewer', name: 'Doc Viewer', description: null, category: null, author: null, engine: null,
+ id: 'autonomous/doc-viewer', kind: 'viewer', name: 'Doc Viewer', description: null, category: null, author: null, engine: null, engines: [],
installed: false, linked: false, viewer: true, viewerUse: null, tier: 2,
verified: true, repo: `${HARNESS_MONOREPO}/tree/main/store/viewers/doc-viewer`, homepage: null, upstream: null, license: null, tagline: null, screenshots: [], examples: [],
},
{
- id: 'acme/bare', kind: 'agent', name: 'Bare', description: null, category: null, author: null, engine: 'codex',
+ id: 'acme/bare', kind: 'agent', name: 'Bare', description: null, category: null, author: null, engine: 'codex', engines: dshSupportedEngines({ engine: 'codex' }),
installed: false, linked: false, viewer: false, viewerUse: null, tier: 0,
verified: false, repo: 'https://example.com/bare.git', homepage: null, upstream: null, license: null, tagline: null, screenshots: [], examples: [],
},
diff --git a/cli/src/dsh/wire.ts b/cli/src/dsh/wire.ts
index 7ff626ff1..8a95c6e14 100644
--- a/cli/src/dsh/wire.ts
+++ b/cli/src/dsh/wire.ts
@@ -5,7 +5,7 @@
*/
import type { DshInstallProgress } from './install.js'
import { listInstalledDsh, type InstalledDsh } from './installed.js'
-import { DSH_ID_RE, dshTier, viewerUse } from './manifest.js'
+import { DSH_ID_RE, dshSupportedEngines, dshTier, viewerUse } from './manifest.js'
import { registrySourceUrl, type DshRegistryEntry } from './registry.js'
import { currentDshRegistry } from './catalog.js'
import { dshUpdateInfo } from './updates.js'
@@ -46,6 +46,7 @@ export function dshListRows(
category: entry.manifest.category ?? null,
author: entry.manifest.author ?? null,
engine: entry.manifest.engine ?? null,
+ engines: dshSupportedEngines(entry.manifest),
installed: true,
linked: entry.linked === true,
viewer: !!entry.manifest.viewer,
@@ -65,6 +66,7 @@ export function dshListRows(
category: entry.category ?? null,
author: entry.author ?? null,
engine: entry.engine ?? null,
+ engines: dshSupportedEngines(entry),
installed: false,
linked: false,
viewer: (entry.tier ?? 0) >= 2,
diff --git a/cli/src/lib/createAgentPane.ts b/cli/src/lib/createAgentPane.ts
index 36e8b6f51..598dab08e 100644
--- a/cli/src/lib/createAgentPane.ts
+++ b/cli/src/lib/createAgentPane.ts
@@ -32,6 +32,7 @@ export interface CreateAgentPaneDeps {
gridLaunchRecord?: GridLaunchRecord | null
codexHome?: string | null
dsh?: string | null
+ dshRuntime?: string | null
agent?: string | null
bypassPermission?: boolean
permissionMode?: string | null
@@ -60,6 +61,7 @@ export interface CreateAgentPaneDeps {
codexHome?: string | null
/** The domain-specific harness this agent is created as, if any. */
dsh?: string | null
+ dshRuntime?: string | null
/** The engine's named agent the pane opens as (`agent_create`'s `agent`); kept on the row so a
* relaunch opens as it again. Already in `argv` — this is the record, not the launch. */
agent?: string | null
@@ -99,6 +101,7 @@ export async function createAndRegisterPane(deps: CreateAgentPaneDeps): Promise<
gridLaunchRecord: deps.gridLaunchRecord,
codexHome: deps.codexHome,
dsh: deps.dsh,
+ dshRuntime: deps.dshRuntime,
agent: deps.agent,
bypassPermission: deps.bypassPermission,
permissionMode: deps.permissionMode,
diff --git a/cli/src/lib/engineLaunch.spec.ts b/cli/src/lib/engineLaunch.spec.ts
index b45b684d2..fe858a04a 100644
--- a/cli/src/lib/engineLaunch.spec.ts
+++ b/cli/src/lib/engineLaunch.spec.ts
@@ -36,6 +36,7 @@ import { ENGINES, type AgentEngine } from '../engines/types.js'
import { engineBin } from './engineBin.js'
import type { EngineInstallRecipe } from './engineInstall.js'
import { MIN_OPEN_FILES, RAISE_OPEN_FILES_SH } from './openFiles.js'
+import { DSH_SESSION_ENV, harnessEnvToClear } from '../dsh/launch.js'
// The launch script names the `grid` the daemon resolved, and a developer's own HARNESS_GRID_BIN
// would resolve to THEIR grid. The suite's runtime dir is already a throwaway (vitest.setup.ts), so
@@ -53,6 +54,18 @@ const FALLBACK = (engine: AgentEngine, shell: string) => engineFallbackPrelude(e
const NO_TMUX = null
describe('buildEngineLaunchArgv', () => {
+ it.each(['claude', 'terminal'] as const)('clears inherited harness context before a plain %s session runs', (engine) => {
+ const argv = buildEngineLaunchArgv(engine, { clearEnv: harnessEnvToClear() }, '/bin/sh', undefined, undefined, NO_TMUX)
+ const probe = 'for name in HARNESS_DSH HARNESS_DSH_DIR HARNESS_WORKSPACE HARNESS_CONTEXT_FILE HARNESS_SKILLS_DIR HARNESS_PRIVATE_GRID; do printenv "$name" && exit 9; done; printf "%s" "$KEEP_ME"'
+ const args = engine === 'terminal' ? ['harness-terminal', ''] : ['harness-engine']
+ const out = execFileSync(argv[0], [argv[1], argv[2], ...args, '/bin/sh', '-c', probe], {
+ encoding: 'utf8',
+ env: { ...process.env, ...Object.fromEntries(DSH_SESSION_ENV.map((name) => [name, 'stale-harness'])), KEEP_ME: 'retained' },
+ stdio: ['ignore', 'pipe', 'pipe'],
+ })
+ expect(out).toBe('retained')
+ })
+
it('wraps zsh in its interactive login form and execs the resolved binary', () => {
expect(buildEngineLaunchArgv('claude', {}, '/bin/zsh', undefined, undefined, NO_TMUX)).toEqual([
'/bin/zsh', '-lic', `${RAISE_OPEN_FILES_SH}${FALLBACK('claude', '/bin/zsh')}${GRID_PRELUDE}harness_engine "$@"`, 'harness-engine', engineBin('claude'),
diff --git a/cli/src/lib/engineLaunch.ts b/cli/src/lib/engineLaunch.ts
index e5bf09ce2..92e4b5a31 100644
--- a/cli/src/lib/engineLaunch.ts
+++ b/cli/src/lib/engineLaunch.ts
@@ -534,7 +534,7 @@ export function terminalHintLines(machineName: string): string[] {
* gives the person a prompt.
*/
export function buildTerminalLaunchArgv(
- opts: Pick<LaunchCommandOptions, 'cwd' | 'terminalHint'> = {},
+ opts: Pick<LaunchCommandOptions, 'cwd' | 'terminalHint' | 'clearEnv'> = {},
shell: string | undefined = undefined,
): string[] {
const candidate = shell === undefined ? currentUserShell() : shell
@@ -546,7 +546,7 @@ export function buildTerminalLaunchArgv(
const hintPrelude = opts.terminalHint
? `printf '%s\\n' ${terminalHintLines(opts.terminalHint.machineName).map(shellSingleQuote).join(' ')}\n`
: ''
- return [path, '-c', RAISE_OPEN_FILES_SH + cwdPrelude + hintPrelude + 'shift\nexec "$@"', 'harness-terminal', opts.cwd ?? '', path, ...loginArgs]
+ return [path, '-c', RAISE_OPEN_FILES_SH + clearEnvPrelude(opts.clearEnv) + cwdPrelude + hintPrelude + 'shift\nexec "$@"', 'harness-terminal', opts.cwd ?? '', path, ...loginArgs]
}
/**
diff --git a/cli/src/lib/launchOverrides.spec.ts b/cli/src/lib/launchOverrides.spec.ts
index 0a66408d5..262575b1f 100644
--- a/cli/src/lib/launchOverrides.spec.ts
+++ b/cli/src/lib/launchOverrides.spec.ts
@@ -1,5 +1,6 @@
import { describe, expect, it, vi } from 'vitest'
import { buildLaunchOverrides, validateLaunchOverrides, type LaunchOverridesDeps } from './launchOverrides.js'
+import { DSH_SESSION_ENV } from '../dsh/launch.js'
import { GRID_CONFLICTING_ENV_VARS, type GridLaunchOverride } from './gridLaunch.js'
const GRID: GridLaunchOverride = {
@@ -68,7 +69,7 @@ describe('buildLaunchOverrides — a relaunch comes back where the agent was', (
expect(calls).toEqual([])
})
- it('a Codex profile gets its CODEX_HOME, its hooks and its own provider, and clears nothing', async () => {
+ it('a Codex profile gets its CODEX_HOME, its hooks and its own provider, and clears inherited harness context', async () => {
const { d, calls } = deps()
const result = await buildLaunchOverrides(d, 'codex', { gridLaunch: null, codexHome: '/home/u/.codex-work' }, 'agent-2')
// `model_provider` rides every own-login Codex launch, not only one that follows a grid: the
@@ -79,15 +80,15 @@ describe('buildLaunchOverrides — a relaunch comes back where the agent was', (
overrides: {
env: { CODEX_HOME: '/home/u/.codex-work' },
extraArgs: ['-c', 'model_provider="openai"'],
- clearEnv: [],
+ clearEnv: [...DSH_SESSION_ENV],
},
})
expect(calls).toEqual(['hooks:/home/u/.codex-work'])
})
- it('an agent on its own login gets nothing — its own variables are the point', async () => {
+ it('an agent on its own login keeps provider variables and clears inherited harness context', async () => {
const { d, calls } = deps()
- expect(await buildLaunchOverrides(d, 'claude', {}, 'a')).toEqual({ ok: true, overrides: { env: {}, extraArgs: [], clearEnv: [] } })
+ expect(await buildLaunchOverrides(d, 'claude', {}, 'a')).toEqual({ ok: true, overrides: { env: {}, extraArgs: [], clearEnv: [...DSH_SESSION_ENV] } })
expect(await buildLaunchOverrides(d, 'claude', { gridLaunch: null, codexHome: null }, 'a')).toMatchObject({ ok: true })
expect(calls).toEqual([])
})
@@ -203,7 +204,7 @@ describe('buildLaunchOverrides — coming back off a grid', () => {
describe('buildLaunchOverrides — a pane opened as a named agent comes back as it', () => {
it('appends opencode\'s --agent after everything else, on its own login and on a grid', async () => {
const own = await buildLaunchOverrides(deps().d, 'opencode', { agent: 'harness-compute' }, 'a')
- expect(own).toEqual({ ok: true, overrides: { env: {}, extraArgs: ['--agent', 'harness-compute'], clearEnv: [] } })
+ expect(own).toEqual({ ok: true, overrides: { env: {}, extraArgs: ['--agent', 'harness-compute'], clearEnv: [...DSH_SESSION_ENV] } })
const home = await buildLaunchOverrides(deps().d, 'opencode', { agent: 'harness-compute', subscriptionModel: 'anthropic/claude' }, 'a')
expect(home).toMatchObject({ ok: true, overrides: { extraArgs: ['-m', 'anthropic/claude', '--agent', 'harness-compute'] } })
const grid = await buildLaunchOverrides(deps().d, 'opencode', { gridLaunch: GRID, agent: 'harness-compute' }, 'a')
diff --git a/cli/src/lib/launchOverrides.ts b/cli/src/lib/launchOverrides.ts
index d17556f27..a6c20c8cc 100644
--- a/cli/src/lib/launchOverrides.ts
+++ b/cli/src/lib/launchOverrides.ts
@@ -26,7 +26,7 @@ import {
type GridLaunchRecord,
} from './gridLaunch.js'
import { TMUX_SESSION_ENV_MIN } from './tmuxVersion.js'
-import type { DshLaunch } from '../dsh/launch.js'
+import { harnessEnvToClear, type DshLaunch } from '../dsh/launch.js'
export interface LaunchOverrides {
/** Layered over the pane's inherited environment. The grid key lives here, and only here. */
@@ -69,9 +69,9 @@ export interface LaunchOverridesDeps {
* file. See `engines/codex/ownLoginProvider.ts`.
*/
readCodexConfig?: (path: string) => string | null
- /** What a DSH adds to the launch (its env and argv), or null when it is not installed here any
- * more — in which case the agent relaunches as its plain base engine and says so in the log. */
- dshLaunch?: (dsh: string, workspace: string) => DshLaunch | null
+ /** Prepare the saved harness context before restarting. Missing or broken packages refuse the
+ * relaunch: starting a plain agent would silently change the user's chosen harness. */
+ dshLaunch?: (dsh: string, workspace: string, engine: AgentEngine, runtimeKey: string) => DshLaunch | null
}
/** Where the agent should come back: the registry row, or an override the desktop just sent. */
@@ -87,6 +87,8 @@ export interface LaunchSource {
subscriptionModel?: string | null
/** The DSH the agent was created as; its env rides on every relaunch (`HARNESS_DSH` included). */
dsh?: string | null
+ /** The session-scoped runtime bundle. Older rows use their stable agent id. */
+ dshRuntime?: string | null
/** The workspace, for the DSH's `${workspace}` — the registry row's `cwd`. */
cwd?: string | null
/**
@@ -144,16 +146,21 @@ export async function buildLaunchOverrides(
const base = await buildBaseLaunchOverrides(deps, engine, source, configKey)
if (!base.ok) return base
let overrides = base.overrides
+ if (source.dsh && !source.cwd) return { ok: false, error: 'DSH_WORKSPACE_MISSING', detail: `${source.dsh} has no saved workspace` }
if (source.dsh && source.cwd) {
- const dsh = deps.dshLaunch?.(source.dsh, source.cwd) ?? null
+ let dsh: DshLaunch | null
+ try {
+ dsh = deps.dshLaunch?.(source.dsh, source.cwd, engine, source.dshRuntime ?? configKey) ?? null
+ } catch (error) {
+ return { ok: false, error: 'DSH_RUNTIME_FAILED', detail: String(error) }
+ }
+ if (!dsh) return { ok: false, error: 'DSH_NOT_INSTALLED', detail: `${source.dsh} is not installed on this machine` }
// The DSH's variables layer over the grid's or the profile's; `HARNESS_*` are the daemon's own
// and a manifest cannot set them (see `dshLaunch`), so nothing here can shadow a grid credential.
- if (dsh) {
- overrides = {
- ...overrides,
- env: { ...overrides.env, ...dsh.env },
- extraArgs: [...overrides.extraArgs, ...dsh.args],
- }
+ overrides = {
+ ...overrides,
+ env: { ...overrides.env, ...dsh.env },
+ extraArgs: [...overrides.extraArgs, ...dsh.args],
}
}
// The named agent rides every relaunch, in the same argv slot `agent_create` put it in. Only an
@@ -163,7 +170,7 @@ export async function buildLaunchOverrides(
if (source.agent && supportsNamedAgent(engine)) {
overrides = { ...overrides, extraArgs: [...overrides.extraArgs, ...namedAgentArgs(engine, source.agent)] }
}
- return { ok: true, overrides }
+ return { ok: true, overrides: { ...overrides, clearEnv: [...overrides.clearEnv, ...harnessEnvToClear(overrides.env)] } }
}
async function buildBaseLaunchOverrides(
diff --git a/cli/src/lib/newAgentModel.spec.ts b/cli/src/lib/newAgentModel.spec.ts
new file mode 100644
index 000000000..3fa65485c
--- /dev/null
+++ b/cli/src/lib/newAgentModel.spec.ts
@@ -0,0 +1,47 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { ENGINES } from '../engines/types.js'
+import { gridCapableEngines } from './gridLaunch.js'
+import { forgetGridModels, listGridModels, resolveGridTarget } from './gridModels.js'
+import { parseNewAgentModel, resolveNewAgentModel } from './newAgentModel.js'
+
+vi.mock('./gridModels.js', () => ({ forgetGridModels: vi.fn(), listGridModels: vi.fn(), resolveGridTarget: vi.fn() }))
+const choice = { gridModel: 'Qwen-35B', gridName: 'my-grid' }
+const target = { networkId: 'g', networkName: 'my-grid', baseUrl: 'https://fixture.invalid/relay/v1', apiKey: 'fixture-key', model: 'Qwen-35B' }
+beforeEach(() => vi.resetAllMocks())
+
+describe('new-session model routing', () => {
+ it('keeps ordinary launches absent and normalizes the explicit selection', () => {
+ expect(parseNewAgentModel('codex', {})).toEqual({ state: 'absent' })
+ expect(parseNewAgentModel('codex', { gridModel: ' Qwen-35B ', gridName: ' my-grid ' })).toEqual({ state: 'ok', selection: { model: 'Qwen-35B', grid: 'my-grid' } })
+ })
+ it.each(ENGINES)('uses the actual launch contract for %s', engine => {
+ expect(parseNewAgentModel(engine, choice).state).toBe(gridCapableEngines().includes(engine) ? 'ok' : 'invalid')
+ })
+ it.each([null, undefined, 4, {}, '', ' ', '\nQwen', 'a'.repeat(2049)])('refuses invalid model/grid identities: %j', bad => {
+ expect(parseNewAgentModel('codex', { ...choice, gridModel: bad }).state).toBe('invalid')
+ expect(parseNewAgentModel('codex', { ...choice, gridName: bad }).state).toBe('invalid')
+ })
+ it.each([{ grid: null }, { grid: target }, { codexHome: '/profiles/work' }])('refuses conflicting routing: %j', conflict => {
+ expect(parseNewAgentModel('codex', { ...choice, ...conflict }).state).toBe('invalid')
+ })
+ it('resolves the exact model on another machine through the chosen grid', async () => {
+ vi.mocked(listGridModels).mockResolvedValue([{ id: 'Qwen-35B', node: 'Mac Studio' }])
+ vi.mocked(resolveGridTarget).mockResolvedValue(target)
+ expect(await resolveNewAgentModel({ model: 'Qwen-35B', grid: 'my-grid' })).toEqual(target)
+ expect(forgetGridModels).toHaveBeenCalledOnce()
+ expect(listGridModels).toHaveBeenCalledWith('my-grid')
+ expect(resolveGridTarget).toHaveBeenCalledWith('my-grid', 'Qwen-35B')
+ })
+ it('refuses a stopped model without resolving a fallback', async () => {
+ vi.mocked(listGridModels).mockResolvedValue([{ id: 'Another-model', node: 'Mac Studio' }])
+ expect(await resolveNewAgentModel({ model: 'Qwen-35B', grid: 'my-grid' })).toBeNull()
+ expect(resolveGridTarget).not.toHaveBeenCalled()
+ })
+ it('preserves a missing endpoint and failures for the caller to refuse', async () => {
+ vi.mocked(listGridModels).mockResolvedValue([{ id: 'Qwen-35B', node: '' }])
+ vi.mocked(resolveGridTarget).mockResolvedValue(null)
+ expect(await resolveNewAgentModel({ model: 'Qwen-35B', grid: 'my-grid' })).toBeNull()
+ vi.mocked(listGridModels).mockRejectedValue(new Error('offline'))
+ await expect(resolveNewAgentModel({ model: 'Qwen-35B', grid: 'my-grid' })).rejects.toThrow('offline')
+ })
+})
diff --git a/cli/src/lib/newAgentModel.ts b/cli/src/lib/newAgentModel.ts
new file mode 100644
index 000000000..6e2e14007
--- /dev/null
+++ b/cli/src/lib/newAgentModel.ts
@@ -0,0 +1,33 @@
+import type { AgentEngine } from '../engines/types.js'
+import { gridCapableEngines, type GridLaunchOverride } from './gridLaunch.js'
+import { forgetGridModels, listGridModels, resolveGridTarget } from './gridModels.js'
+
+export interface NewAgentModel { model: string; grid: string }
+
+/** Model routing is resolved on the agent's machine; the model can live elsewhere.
+ * Only the semantic choice goes into the creation receipt, never a rotating key. */
+export function parseNewAgentModel(engine: AgentEngine, payload: Record<string, unknown>):
+ { state: 'absent' } | { state: 'invalid'; detail: string } | { state: 'ok'; selection: NewAgentModel } {
+ if (payload.gridModel === undefined && payload.gridName === undefined) return { state: 'absent' }
+ const valid = (value: unknown): value is string => typeof value === 'string'
+ && value.trim().length > 0 && value.length <= 2048 && !/[\x00-\x1f\x7f]/.test(value)
+ if (!valid(payload.gridModel) || !valid(payload.gridName)) {
+ return { state: 'invalid', detail: 'Choose a model and the grid serving it.' }
+ }
+ if (payload.grid !== undefined || payload.codexHome != null) {
+ return { state: 'invalid', detail: 'A model selection cannot be combined with a grid credential or a subscription profile.' }
+ }
+ if (!gridCapableEngines().includes(engine)) {
+ return { state: 'invalid', detail: `${engine} cannot use a model on your machines.` }
+ }
+ return { state: 'ok', selection: { model: payload.gridModel.trim(), grid: payload.gridName.trim() } }
+}
+
+export async function resolveNewAgentModel(selection: NewAgentModel): Promise<GridLaunchOverride | null> {
+ // Refresh at launch: a model stopped after opening the picker must not silently
+ // fall back to a subscription or to the grid's default router.
+ forgetGridModels();
+ const models = await listGridModels(selection.grid);
+ if (!models.some((model) => model.id === selection.model)) return null;
+ return resolveGridTarget(selection.grid, selection.model);
+}
diff --git a/cli/src/lib/registry.spec.ts b/cli/src/lib/registry.spec.ts
index 8cd42b078..ec01fc296 100644
--- a/cli/src/lib/registry.spec.ts
+++ b/cli/src/lib/registry.spec.ts
@@ -1197,6 +1197,19 @@ describe('agent identity: the process owns the agent, the session is bound to it
expect(reloaded.byAgent(plain.agentId)!.agent).toBeNull()
})
+ it('keeps the selected harness runtime through process binding and disk reload', async () => {
+ const { registry } = await loadRegistryModule()
+ registry.load()
+ const pending = registry.openPendingAgent({ engine: 'opencode', runtimes: [{ backend: 'tmux', paneId: '%70' }],
+ cwd: '/tmp/drawing', dsh: 'acme/drawing', dshRuntime: 'harness-opencode-original' })!
+ expect(pending.dshRuntime).toBe('harness-opencode-original')
+ const bound = registry.register({ engine: 'opencode', sessionId: 'drawing-session', tmuxPane: '%70' })!.entry
+ expect(bound).toMatchObject({ engine: 'opencode', dsh: 'acme/drawing', dshRuntime: 'harness-opencode-original' })
+ const { registry: reloaded } = await loadRegistryModule()
+ reloaded.load()
+ expect(reloaded.byAgent(pending.agentId)).toMatchObject({ engine: 'opencode', dsh: 'acme/drawing', dshRuntime: 'harness-opencode-original' })
+ })
+
it('persists a failed launch for reconnect while keeping its terminal route', async () => {
const { registry } = await loadRegistryModule()
registry.load()
diff --git a/cli/src/lib/registry.ts b/cli/src/lib/registry.ts
index 5c5794232..e8187801e 100644
--- a/cli/src/lib/registry.ts
+++ b/cli/src/lib/registry.ts
@@ -166,6 +166,8 @@ export interface RegisteredSession {
* again after a restart) is still labelled. Fill-only, like `codexHome`. See `src/dsh/`.
*/
dsh?: string | null
+ /** Stable key of the session-scoped harness runtime; preserved by bind, restore and fork. */
+ dshRuntime?: string | null
/**
* The engine's own named agent this pane was opened as (`agent_create`'s `agent`; opencode
* `--agent <name>`), or null for a general session. Chosen at creation and carried into every
@@ -907,6 +909,7 @@ class Registry {
codexHome: typeof rawCodexHome === 'string' && rawCodexHome ? rawCodexHome : null,
hermesHome: typeof raw?.hermesHome === 'string' && raw.hermesHome ? raw.hermesHome : null,
dsh: normalizedDshId((raw as { dsh?: unknown }).dsh),
+ dshRuntime: typeof raw.dshRuntime === 'string' && raw.dshRuntime ? raw.dshRuntime : null,
agent: normalizedAgentName((raw as { agent?: unknown }).agent),
...(rawGridLaunch !== undefined ? { gridLaunch: rawGridLaunch } : {}),
...(rawGridLaunch ? { gridWebSearch: normalizedGridWebSearch(raw?.gridWebSearch) } : {}),
@@ -1160,6 +1163,7 @@ class Registry {
gridLaunchRecord?: GridLaunchRecord | null
codexHome?: string | null
dsh?: string | null
+ dshRuntime?: string | null
/** The engine's named agent the pane was opened as (`agent_create`'s `agent`), validated upstream. */
agent?: string | null
bypassPermission?: boolean
@@ -1195,6 +1199,7 @@ class Registry {
// the row learns it from the session that lands in it. See RegisteredSession.hermesHome.
hermesHome: null,
dsh: input.dsh ?? null,
+ dshRuntime: input.dshRuntime ?? null,
agent: normalizedAgentName(input.agent),
...(input.bypassPermission ? { bypassPermission: true } : {}),
...(permissionModeName(input.permissionMode) ? { permissionMode: input.permissionMode } : {}),
@@ -1463,6 +1468,7 @@ class Registry {
// would send the mirror back to the default store (openharness#191).
hermesHome: input.hermesHome ?? existing?.hermesHome ?? null,
dsh: existing?.dsh ?? null,
+ dshRuntime: existing?.dshRuntime ?? null,
agent: existing?.agent ?? null,
...(existing?.bypassPermission ? { bypassPermission: true } : {}),
...(existing?.permissionMode ? { permissionMode: existing.permissionMode } : {}),
@@ -1599,7 +1605,7 @@ class Registry {
this.terminalAvailableAgents.delete(agentId)
// The archived conversation owns the original Harness ID. Preserve the physical shell under
// a new identity, without sending input, stopping processes or claiming its route twice.
- const entry = separateShell ? { ...original, agentId: randomUUID(), dsh: null, agent: null, defaultName: this.automaticName('Terminal', new Date()) } : original
+ const entry = separateShell ? { ...original, agentId: randomUUID(), dsh: null, dshRuntime: null, agent: null, defaultName: this.automaticName('Terminal', new Date()) } : original
this.releaseBinding(entry)
delete entry.resumeOnly
entry.engine = 'terminal'
diff --git a/cli/vitest.portability.config.ts b/cli/vitest.portability.config.ts
new file mode 100644
index 000000000..ca92b6f3a
--- /dev/null
+++ b/cli/vitest.portability.config.ts
@@ -0,0 +1,18 @@
+import { defineConfig } from 'vitest/config'
+import base from './vitest.config.js'
+
+export default defineConfig({
+ ...base,
+ test: {
+ ...base.test,
+ include: ['src/dsh/**/*.spec.ts', 'src/backendSocket.dsh.spec.ts', 'src/backendSocket.models.spec.ts', 'src/lib/newAgentModel.spec.ts', 'src/lib/launchOverrides.spec.ts', 'src/lib/createAgentPane.spec.ts', 'src/lib/registry.spec.ts'],
+ testTimeout: 30_000,
+ coverage: {
+ provider: 'v8', enabled: true,
+ include: ['src/lib/newAgentModel.ts', 'src/dsh/adapters.ts', 'src/dsh/compatibility.ts', 'src/dsh/runtime.ts', 'src/dsh/launch.ts', 'src/dsh/materialize.ts'],
+ thresholds: { statements: 100, branches: 100, functions: 100, lines: 100, perFile: true },
+ reporter: ['text', 'json', 'json-summary', 'lcov'],
+ reportsDirectory: 'coverage/portability',
+ },
+ },
+})
diff --git a/desktop/design/new-harness-entry-rules.md b/desktop/design/new-harness-entry-rules.md
index 46a30d79b..513511d5a 100644
--- a/desktop/design/new-harness-entry-rules.md
+++ b/desktop/design/new-harness-entry-rules.md
@@ -5,13 +5,21 @@ Escape leaves that tab open. The command dock opens only after an explicit
Cmd-N, Cmd-O, or Cmd-P action. Start Harness submits the reviewed draft;
opening or cancelling the dock never starts a harness.
-The launch form starts on Project, followed by Agent, Machine, Branch,
-Worktree, Approvals, and Profile when the chosen agent uses Codex profiles.
-The separate **+ New Harness** action submits the draft. There is no heading,
+The launch form starts on Harness, followed by Agent and Model, then Machine,
+Project and Branch; a blank row separates each group and Advanced. Machine
+always stays visible. Advanced expands Worktree, Approvals, and Profile for
+Codex subscription sessions. Its expanded state is remembered. The
+`[ New Harness ]` action stays pinned below the scrolling fields, prints the
+key bound to `picker.start` (⇧⏎ by default), and submits the draft; that key
+starts from any field, taking a value highlighted in an open list first. Plain
+Return on a value row never starts. The machine list puts this computer first,
+then usable machines, then unlinked or offline ones in dark grey. There is no heading,
Task row, or Open In row. Cmd-O and Cmd-P also omit headings and counts.
Tasks carried from search or Store examples remain part of the draft.
-Values and search use the terminal's selected font, size, and line height.
+Values and search use the terminal's selected font, size, and line height, on a
+character grid: one cell wide and one row tall, with every margin, column and
+gap a whole number of them, and text whose line height is the row.
The right pane previews choices without a selection highlight while the left
has focus. Right arrow, Return, or typing activates the list, and Left arrow
gives the keys back to the rows once the search is empty; accepting a value
@@ -19,7 +27,7 @@ returns to its field. The three project actions have icons. Clone, folder path,
project prompts return to Project after acceptance; only New Harness starts.
Project, machine, branch, and approval options occupy one line. Only the local
machine has a note, **This machine**. Approvals come from the chosen agent's
-supported modes, and Profile disappears for agents that do not use it.
+supported modes, and Profile disappears for agents or model routes that do not use it.
Narrow windows show the active list full-width with a back action.
| Entry | Initial values | Destination after a successful start |
@@ -42,6 +50,49 @@ query, selection, highlighted result, and filters, then refocuses the input.
Cmd-T closes the dock and opens a quiet blank tab. Creation remains blocked
while a pending start needs confirmation.
+## Harness and agent choices
+
+Harness contains Coding and domain harnesses, plus Browse Harness Store. Agent
+contains compatible engines only. Coding sends no `dsh` and does not remove any
+existing instructions or skills from the project. Changing an engine preserves
+the selected harness and its generated project name. Machine changes re-evaluate
+compatibility; an incompatible selection cannot start, and is never silently
+replaced at launch. The selected machine's installed-package compatibility wins
+over a newer catalog listing. Current daemons expose every integrated agent
+engine; older daemons without compatibility metadata offer the manifest default.
+Wide pickers use the available height and show a scrollbar when choices overflow.
+
+The existing local state store keeps `new_harness_preferences_v1`: separate
+engine and harness recents, the last successful engine per harness (including
+Coding), and Advanced's expanded state. Legacy `new_agent_engine` and
+`new_agent_recent` are read and split by identity; package ids never appear in
+Agent history. Legacy keys and the app data directory stay in place. Explicit
+entry choices and pending receipts take priority over remembered defaults.
+
+## Model selection
+
+Agent and Model are adjacent because the agent determines which model routes
+are supported. The Model picker reuses the Models menu's subscription usage
+source and the selected machine's model catalog. It shows the relevant
+subscription/default login, running models on the person's machines, and shared
+models grouped by grid. Each model identifies its serving machine; search matches
+that machine too. Two grids serving the same model id remain distinct choices.
+
+Machine identifies where the agent, project and tools run. The model can be
+served from a different machine. Changing Machine or Agent preserves an explicit
+model, refreshes availability, and blocks Start with an explanation if the new
+combination is unavailable. It never substitutes a subscription. Refresh models
+updates the choices; Manage Models opens the existing Models panel for lifecycle
+management and preserves the launch draft. Choosing Terminal clears model routing;
+its Model row is disabled and explains that Terminal does not use a model.
+
+An explicit model survives draft dismissal/restoration and uncertain creation
+receipts. A new session starts with the selected engine's default subscription;
+model routing is not persisted as a global preference. Start refreshes availability
+and sends only `gridModel` and `gridName`; the selected machine resolves the endpoint
+and credentials. Older daemons without `supportsModelLaunch` explain that an update
+is needed while continuing to allow ordinary subscription launches.
+
## Git projects
Git projects enable Branch and Worktree. Worktree defaults to **Yes** for a
@@ -126,8 +177,8 @@ worktree: the retry selects that worktree's branch with Worktree off.
- Store drafts belong to the explicitly requested product and machine. Opening
Blender cannot restore Workshop's agent, task, or generated project name.
- Escape preserves edits. Reopening the same source without a new task resumes
- its compatible draft. Store Open still wins if the agent or machine was
- changed inside that saved draft.
+ its compatible draft, including the selected agent. Store Open still wins if the
+ harness or machine was changed inside that saved draft.
- A newly typed search task or Store example starts from that entry's defaults.
Repeating the same request while its draft is already open keeps its edits.
- A request awaiting confirmation is an exception: restore its exact values and
@@ -169,6 +220,11 @@ never silently renamed, and existing files are never overwritten.
and existing-pane actions after changing a picker's destination.
- `test/models_menu_test.dart`: the native Models menu uses the product dock
on its explicitly chosen machine; an uninstalled product opens its Store page.
+- `test/new_harness_models_test.dart`: subscription relevance, local/shared model
+ identity, independent agent/model machines, stopped models, old/offline daemons,
+ stale asynchronous responses, pending receipts, draft restoration, and wide and
+ compact keyboard/pointer flows. `cli/src/backendSocket.models.spec.ts` and
+ `cli/src/lib/newAgentModel.spec.ts` cover daemon resolution and receipt semantics.
- `test/generated_project_launch_test.dart` and
`test/new_harness_project_context_test.dart`: generated versus edited names,
collisions, delayed replies, and machine-specific project choices.
diff --git a/desktop/lib/core/agent_preference.dart b/desktop/lib/core/agent_preference.dart
index e3e4e4798..963a1ad59 100644
--- a/desktop/lib/core/agent_preference.dart
+++ b/desktop/lib/core/agent_preference.dart
@@ -1,3 +1,5 @@
+import 'dart:convert';
+
import 'local_key_value_store.dart';
/// Remembers an agent choice, independently of a machine, profile or permission.
@@ -6,12 +8,19 @@ class AgentPreference {
final LocalKeyValueStore? storage;
static const _key = 'new_agent_engine';
static const _recentKey = 'new_agent_recent';
+ static const _launchKey = 'new_harness_preferences_v1';
/// How many agents [recent] keeps: more than the New Harness list shows, so
/// an agent that is chosen again does not push out one used last week.
static const recentCapacity = 8;
String? value;
+ String? harness;
+ bool advancedOpen = false;
+ List<String> recentHarnesses = const [];
+ final _enginesByHarness = <String, String>{};
+ String? engineFor(String? harnessId) =>
+ _enginesByHarness[harnessId ?? 'coding'];
/// The agents harnesses were created with, most recent first — what New
/// Harness lists before anything is typed.
@@ -26,55 +35,133 @@ class AgentPreference {
final revision = _revision;
try {
final stored = await storage?.read(_key);
- if (revision == _revision && revision == 0) value = stored;
+ if (revision == _revision && revision == 0) {
+ if (stored?.contains('/') == true) {
+ harness = stored;
+ } else {
+ value = stored;
+ }
+ }
} catch (_) {
/* A missing preference never blocks a new agent. */
}
try {
final stored = await storage?.read(_recentKey);
- if (stored == null) return;
final ids = [
- for (final id in stored.split('\n'))
+ for (final id in (stored ?? '').split('\n'))
if (id.trim().isNotEmpty) id.trim(),
];
// An agent remembered while this was loading is newer than the file:
// it stays first, and the stored ones follow it.
- recent = [
+ recent = <String>{
...recent,
for (final id in ids)
- if (!recent.contains(id)) id,
- ].take(recentCapacity).toList(growable: false);
+ if (!id.contains('/') && !recent.contains(id)) id,
+ }.take(recentCapacity).toList(growable: false);
+ recentHarnesses = <String>{
+ ...recentHarnesses,
+ if (harness != null && !recentHarnesses.contains(harness)) harness!,
+ for (final id in ids)
+ if (id.contains('/') && !recentHarnesses.contains(id)) id,
+ }.take(recentCapacity).toList(growable: false);
} catch (_) {
/* No history is an empty list, never an error. */
}
+ try {
+ final stored = await storage?.read(_launchKey);
+ if (stored == null || revision != _revision || revision != 0) return;
+ final data = jsonDecode(stored);
+ if (data is! Map) return;
+ List<String> ids(Object? raw, bool packages) => raw is List
+ ? raw
+ .whereType<String>()
+ .where((id) => id.isNotEmpty && id.contains('/') == packages)
+ .toSet()
+ .take(recentCapacity)
+ .toList()
+ : const [];
+ value =
+ data['engine'] is String && !(data['engine'] as String).contains('/')
+ ? data['engine'] as String
+ : value;
+ harness =
+ data['harness'] is String && (data['harness'] as String).contains('/')
+ ? data['harness'] as String
+ : null;
+ recent = ids(data['agents'], false);
+ recentHarnesses = ids(data['harnesses'], true);
+ advancedOpen = data['advancedOpen'] == true;
+ if (data['enginesByHarness'] case final Map choices) {
+ for (final entry in choices.entries) {
+ if (entry.key is String &&
+ entry.value is String &&
+ !(entry.value as String).contains('/')) {
+ _enginesByHarness[entry.key as String] = entry.value as String;
+ }
+ }
+ }
+ } catch (_) {
+ /* A malformed preference never blocks launch. */
+ }
}
- Future<void> select(String engine) {
+ Future<void> select(String engine) async {
_revision++;
- value = engine;
- return _writes = _writes.then((_) async {
- try {
- await storage?.write(_key, engine);
- } catch (_) {
- /* Keep the current choice usable if persistence fails. */
- }
- });
+ if (engine.contains('/')) {
+ harness = engine;
+ } else {
+ value = engine;
+ harness = null;
+ }
+ return _save();
}
/// [agent] was just used to create a harness: it moves to the front of
/// [recent].
- Future<void> remember(String agent) {
+ Future<void> remember(String agent, {String? harnessId}) async {
+ await load();
+ _revision++;
+ if (agent.contains('/')) {
+ harnessId = agent;
+ agent = value ?? '';
+ }
+ harness = harnessId;
+ if (agent.isNotEmpty) {
+ value = agent;
+ _enginesByHarness[harnessId ?? 'coding'] = agent;
+ }
recent = [
- agent,
+ if (agent.isNotEmpty) agent,
...recent.where((id) => id != agent),
].take(recentCapacity).toList(growable: false);
+ if (harnessId != null) {
+ recentHarnesses = [
+ harnessId,
+ ...recentHarnesses.where((id) => id != harnessId),
+ ].take(recentCapacity).toList(growable: false);
+ }
+ return _save();
+ }
+
+ Future<void> setAdvanced(bool open) async {
+ await load();
+ advancedOpen = open;
+ _revision++;
+ await _save();
+ }
+
+ Future<void> _save() {
+ final snapshot = jsonEncode({
+ 'engine': value,
+ 'harness': harness,
+ 'agents': recent,
+ 'harnesses': recentHarnesses,
+ 'enginesByHarness': _enginesByHarness,
+ 'advancedOpen': advancedOpen,
+ });
return _writes = _writes.then((_) async {
try {
- // Written after the stored list has been read and merged in behind
- // it, or an agent used before the load finished would replace the
- // whole history on disk with itself.
- await load();
- await storage?.write(_recentKey, recent.join('\n'));
+ await storage?.write(_launchKey, snapshot);
} catch (_) {
/* The list in memory still serves this session. */
}
diff --git a/desktop/lib/core/dsh_catalog.dart b/desktop/lib/core/dsh_catalog.dart
index 18f3ea545..f21db927a 100644
--- a/desktop/lib/core/dsh_catalog.dart
+++ b/desktop/lib/core/dsh_catalog.dart
@@ -68,6 +68,7 @@ class DshEntry {
required this.id,
required this.name,
required this.engine,
+ this.engines = const [],
this.description,
this.category,
this.installed = false,
@@ -95,8 +96,10 @@ class DshEntry {
/// The tile's name, as the manifest or the registry spells it.
final String name;
- /// The base engine the harness runs on: what `agent_create` must be sent.
+ /// Default engine. Older daemons only advertise this one engine.
final String engine;
+ final List<String> engines;
+ List<String> get supportedEngines => engines.isEmpty ? [engine] : engines;
final String? description;
/// The kind of thing it makes, in a word or two — the picker's second line.
@@ -191,6 +194,15 @@ class DshEntry {
? name.trim().substring(0, name.trim().length.clamp(0, 40))
: id.substring(id.indexOf('/') + 1),
engine: engine is String ? engine : '',
+ engines: raw['engines'] is List
+ ? (raw['engines'] as List)
+ .whereType<String>()
+ .where(
+ (id) => id.isNotEmpty && id.length <= 64 && !id.contains('/'),
+ )
+ .toSet()
+ .toList(growable: false)
+ : const [],
kind: kind,
description: description is String && description.trim().isNotEmpty
? description.trim().substring(
diff --git a/desktop/lib/core/harness_catalog.dart b/desktop/lib/core/harness_catalog.dart
index a81d8e8d6..4b075cabe 100644
--- a/desktop/lib/core/harness_catalog.dart
+++ b/desktop/lib/core/harness_catalog.dart
@@ -74,6 +74,7 @@ DshEntry _currentEntry(String id, List<DshEntry> entries) {
category: identity?.category ?? metadata.category,
description: metadata.description,
engine: installation.installed ? installation.engine : metadata.engine,
+ engines: installation.installed ? installation.engines : metadata.engines,
kind: metadata.kind,
author: metadata.author,
repo: metadata.repo,
diff --git a/desktop/lib/core/models.dart b/desktop/lib/core/models.dart
index dbd1ba73a..66953865f 100644
--- a/desktop/lib/core/models.dart
+++ b/desktop/lib/core/models.dart
@@ -1080,6 +1080,9 @@ class GridModels {
/// daemon is older and sends no such list — read as "offer everything", the behaviour before.
final Set<String>? localModelEngines;
+ /// New-session model selections are understood by this daemon.
+ final bool supportsModelLaunch;
+
/// Which `grid` the machine would run — see [GridCli]. Null when the daemon is older and does
/// not say, which claims nothing.
final GridCli? gridCli;
@@ -1097,6 +1100,7 @@ class GridModels {
required this.models,
this.grids = const [],
this.localModelEngines,
+ this.supportsModelLaunch = false,
this.gridCli,
this.reachable = true,
});
@@ -1116,6 +1120,7 @@ class GridModels {
models = const [],
grids = const [],
localModelEngines = null,
+ supportsModelLaunch = false,
gridCli = null,
reachable = false;
diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dart
index 09a0ce2b4..71469c4cb 100644
--- a/desktop/lib/screens/swarm_screen.dart
+++ b/desktop/lib/screens/swarm_screen.dart
@@ -1643,11 +1643,12 @@ class _SwarmScreenState extends State<SwarmScreen>
);
return;
}
- final inherited = agent?.identityEngine;
+ final inherited = agent?.engine;
_openNewHarness(
machineId: id,
// ⌘⇧T is how a shell is made; New Harness from a shell means an agent.
engine: engine ?? (isTerminalEngine(inherited) ? null : inherited),
+ harnessId: engine == null ? agent?.dsh : null,
folder: initialFolder,
projectName: projectName,
autoProject:
@@ -1732,6 +1733,7 @@ class _SwarmScreenState extends State<SwarmScreen>
void _openNewHarness({
required String machineId,
String? engine,
+ String? harnessId,
String? folder,
String? projectName,
bool autoProject = false,
@@ -1762,7 +1764,10 @@ class _SwarmScreenState extends State<SwarmScreen>
);
bool matchesSelection(NewHarnessDraft candidate) =>
origin.requestedEngine == null ||
- (candidate.engine == origin.requestedEngine &&
+ ((isHarnessId(origin.requestedEngine)
+ ? candidate.harnessId == origin.requestedEngine
+ : candidate.engine == origin.requestedEngine &&
+ candidate.harnessId == null) &&
candidate.machineId == origin.machineId);
final current = _newHarness;
if (current != null) {
@@ -1810,6 +1815,7 @@ class _SwarmScreenState extends State<SwarmScreen>
app,
machineId: machineId,
engine: engine,
+ harnessId: harnessId,
folder: folder,
projectName: projectName,
task: task,
diff --git a/desktop/lib/shortcuts/keymap_commands.dart b/desktop/lib/shortcuts/keymap_commands.dart
index 4283145c5..d5e28e71f 100644
--- a/desktop/lib/shortcuts/keymap_commands.dart
+++ b/desktop/lib/shortcuts/keymap_commands.dart
@@ -496,6 +496,14 @@ final harnessCommands = <HarnessCommand>[
extraKeys: ['enter', 'ctrl+m'],
context: KeymapContext.picker,
),
+ // Starts New Harness from any field, without walking down to its button.
+ const HarnessCommand(
+ 'picker.start',
+ 'Start the new harness from any field',
+ ShortcutGroup.actions,
+ extraKeys: ['shift+enter'],
+ context: KeymapContext.picker,
+ ),
const HarnessCommand(
'picker.refresh',
'Refresh the machine list',
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index 2aab71e1d..e23cff2f1 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -5080,6 +5080,8 @@ class AppNotifier extends ChangeNotifier {
? capable.whereType<String>().map((e) => e.toLowerCase()).toSet()
: null,
gridCli: GridCli.parse(response['gridCli']),
+ supportsModelLaunch: response['supportsModelLaunch'] == true,
+ reachable: response['error'] == null,
);
} catch (_) {
// NOT `gridName: null` with an empty list — that is the shape of "this account has no grid",
@@ -6771,6 +6773,7 @@ class AppNotifier extends ChangeNotifier {
String? permissionMode,
String? codexHome,
String? dsh,
+ GridModel? model,
String? prompt,
String? name,
String? agent,
@@ -6793,6 +6796,8 @@ class AppNotifier extends ChangeNotifier {
// The harness this agent is created from. `engine` above is its BASE —
// the machine refuses the pair when they disagree (`INVALID_DSH`).
'dsh': ?dsh,
+ 'gridModel': ?model?.id,
+ 'gridName': ?model?.grid,
// A first message the engine is opened with, and the pane's name before
// the engine reports a session title. Both absent unless asked for: a
// daemon that predates them ignores an unknown field, but one that knows
@@ -6973,6 +6978,29 @@ class AppNotifier extends ChangeNotifier {
return 'Not connected to $machineName yet.';
}
final connection = _conn(machineId);
+ if (!creation.awaitingConfirmation && choices['gridModel'] != null) {
+ final models = await gridModels(machineId);
+ if (!models.reachable) {
+ return creation._complete(
+ 'Could not verify models on $machineName. Refresh models or use your subscription.',
+ );
+ }
+ if (!models.supportsModelLaunch) {
+ return creation._complete(
+ 'Update Harness CLI on $machineName to choose a model before starting.',
+ );
+ }
+ if (!models.canRunLocally(choices['engine'] as String) ||
+ !models.sections.any(
+ (section) =>
+ section.name == choices['gridName'] &&
+ section.models.any((model) => model.id == choices['gridModel']),
+ )) {
+ return creation._complete(
+ 'The selected model is unavailable. Refresh models or use your subscription.',
+ );
+ }
+ }
var launchChoices = choices;
if (!creation.awaitingConfirmation &&
choices['projectSource'] != null &&
@@ -7084,6 +7112,7 @@ class AppNotifier extends ChangeNotifier {
'INVALID_CWD',
'INVALID_ENGINE',
'INVALID_GRID',
+ 'GRID_UNAVAILABLE',
'INVALID_CODEX_HOME',
'INVALID_DSH',
'PROMPT_UNSUPPORTED',
diff --git a/desktop/lib/state/new_harness.dart b/desktop/lib/state/new_harness.dart
index 74cb1daba..87aabff50 100644
--- a/desktop/lib/state/new_harness.dart
+++ b/desktop/lib/state/new_harness.dart
@@ -1,4 +1,5 @@
import 'dart:async';
+import 'dart:convert';
import 'dart:io';
import 'dart:isolate';
import 'dart:math';
@@ -12,6 +13,8 @@ import '../core/codex_profiles.dart';
import '../core/dsh_catalog.dart';
import '../core/harness_catalog.dart';
import '../core/first_task.dart';
+import '../core/models.dart';
+import '../usage/models_menu_controller.dart';
import '../core/fuzzy_match.dart';
import '../core/git_worktree.dart';
import '../core/permission_modes.dart';
@@ -25,8 +28,8 @@ import 'pane_arrangement.dart';
/// Whether New Harness opens as a line in the box, or as the full form.
///
-/// The app, including Store Open/Try, uses the box. Advanced options can still
-/// open the form with the same draft. Legacy form tests leave this off; dock
+/// The app, including Store Open/Try, uses the box with inline advanced options.
+/// Legacy form tests leave this off; dock
/// journeys enable it explicitly.
bool newHarnessOpensInBox = !kUnderTest;
@@ -36,7 +39,9 @@ bool newHarnessOpensInBox = !kUnderTest;
enum NewHarnessField {
launch,
task,
+ harness,
agent,
+ model,
machine,
branch,
projectMenu,
@@ -267,6 +272,9 @@ class NewHarnessDraft {
const NewHarnessDraft({
required this.machineId,
required this.engine,
+ this.harnessId,
+ this.model,
+ this.advancedOpen = false,
required this.project,
required this.task,
required this.permissionMode,
@@ -284,6 +292,9 @@ class NewHarnessDraft {
});
final String machineId, engine, task, permissionMode;
+ final String? harnessId;
+ final GridModel? model;
+ final bool advancedOpen;
final bool? worktree;
/// The branch chosen in the launcher, and the name typed for a worktree's
@@ -336,6 +347,8 @@ class NewHarnessOption {
this.engine,
this.project,
this.profile,
+ this.model,
+ this.group,
this.machineId,
this.enabled = true,
this.synthetic = false,
@@ -365,6 +378,8 @@ class NewHarnessOption {
/// A profile folder on [machineId], never on an implicitly different host.
final LocalCodexProfile? profile;
+ final GridModel? model;
+ final String? group;
/// A recent project chooses its machine and folder together.
final String? machineId;
@@ -378,6 +393,7 @@ class NewHarnessController extends ChangeNotifier {
this.app, {
required String machineId,
String? engine,
+ String? harnessId,
String? folder,
String? projectName,
bool autoProject = false,
@@ -389,6 +405,7 @@ class NewHarnessController extends ChangeNotifier {
HarnessPlacement? placement,
this.offersStore = false,
String? home,
+ ModelsMenuController? modelUsage,
Random? random,
}) : _random = random ?? Random(),
placement =
@@ -401,13 +418,27 @@ class NewHarnessController extends ChangeNotifier {
_autoProject = autoProject || draft?.project.generated != null,
_now = now ?? DateTime.now,
_home = home ?? Platform.environment['HOME'] {
- final remembered = app.agentPreference.value;
+ final explicitSelection =
+ draft != null || engine != null || harnessId != null;
engine = draft?.engine ?? engine;
- _engine = _known(engine)
- ? engine!
- : _known(remembered)
- ? remembered!
- : allEngines.first.id;
+ _harnessId =
+ draft?.harnessId ??
+ harnessId ??
+ (isHarnessId(engine)
+ ? engine
+ : explicitSelection
+ ? null
+ : app.agentPreference.harness);
+ _engine = draft != null && !isHarnessId(draft.engine)
+ ? draft.engine
+ : harnessId != null && engine != null && !isHarnessId(engine)
+ ? engine
+ : _initialEngine(isHarnessId(engine) ? null : engine);
+ _model = isTerminal ? null : draft?.model;
+ _modelUsage = modelUsage;
+ _ownsModelUsage = modelUsage == null;
+ _modelUsage?.addListener(_refresh);
+ advancedOpen = draft?.advancedOpen ?? app.agentPreference.advancedOpen;
_project = projectName != null
? NewHarnessProject.fresh(projectName)
: folder != null
@@ -454,6 +485,22 @@ class NewHarnessController extends ChangeNotifier {
}
app.addListener(_onApp);
_refresh();
+ unawaited(
+ app.agentPreference.load().then((_) {
+ if (_disposed || locked) return;
+ if (!_selectionTouched && !explicitSelection) {
+ _harnessId = app.agentPreference.harness;
+ _engine = _initialEngine(null);
+ if (_project.generated != null) _project = _generatedProject();
+ } else if (!_selectionTouched && draft == null && isHarnessId(engine)) {
+ _engine = _initialEngine(null);
+ }
+ if (!_advancedTouched && draft == null) {
+ advancedOpen = app.agentPreference.advancedOpen;
+ }
+ _refresh();
+ }),
+ );
unawaited(
app.projectHistory.load().then((_) {
if (!_disposed && !listEquals(_seen, _signature())) _refresh();
@@ -462,7 +509,25 @@ class NewHarnessController extends ChangeNotifier {
// What the machine has is asked when the box opens, as the form does: an
// engine installed in a terminal a minute ago is otherwise still "missing".
unawaited(app.probeEngines(_machineId, force: true));
- unawaited(app.probeDsh(_machineId, force: true));
+ final initialMachine = _machineId;
+ unawaited(
+ app.probeDsh(initialMachine, force: true).then((_) {
+ // Store and remembered choices can open before the machine's catalog
+ // arrives. Resolve their preferred engine once compatibility is known.
+ // An inherited session, draft, or explicit user choice keeps its engine.
+ if (_disposed ||
+ locked ||
+ _selectionTouched ||
+ draft != null ||
+ (engine != null && !isHarnessId(engine)) ||
+ _machineId != initialMachine ||
+ _harnessId == null) {
+ return;
+ }
+ _engine = _initialEngine(null);
+ _refresh();
+ }),
+ );
unawaited(_ensureHome(_machineId));
unawaited(_refreshGeneratedProject());
}
@@ -483,6 +548,52 @@ class NewHarnessController extends ChangeNotifier {
final String? _home;
late String _engine;
+ String? _harnessId;
+ String? get harnessId => _harnessId;
+ String get harnessLabel =>
+ _harnessId == null ? 'Coding' : labelOf(_harnessId!);
+ bool advancedOpen = false;
+ bool _selectionTouched = false, _advancedTouched = false;
+ void toggleAdvanced() {
+ if (locked) return;
+ advancedOpen = !advancedOpen;
+ _advancedTouched = true;
+ if (!advancedOpen &&
+ [
+ NewHarnessField.branch,
+ NewHarnessField.mode,
+ NewHarnessField.profile,
+ ].contains(field)) {
+ field = NewHarnessField.launch;
+ query = '';
+ }
+ unawaited(app.agentPreference.setAdvanced(advancedOpen));
+ _refresh();
+ }
+
+ DshEntry? get selectedHarness => _harnessId == null
+ ? null
+ : harnessForOperation(
+ _machine?.dsh.entries ?? const <DshEntry>[],
+ _harnessId!,
+ );
+ List<String> get compatibleEngines => _harnessId == null
+ ? [for (final engine in allEngines) engine.id, kTerminalEngine]
+ : selectedHarness?.supportedEngines ??
+ [knownHarnessBase[canonicalHarnessId(_harnessId!)] ?? 'claude'];
+ String _initialEngine(String? requested) {
+ final allowed = compatibleEngines;
+ for (final candidate in [
+ requested,
+ app.agentPreference.engineFor(_harnessId),
+ app.agentPreference.value,
+ selectedHarness?.engine,
+ ]) {
+ if (candidate != null && allowed.contains(candidate)) return candidate;
+ }
+ return allowed.first;
+ }
+
String _machineId;
late NewHarnessProject _project;
final _projectsByMachine = <String, NewHarnessProject>{};
@@ -746,6 +857,144 @@ class NewHarnessController extends ChangeNotifier {
}
}
+ GridModel? _model;
+ GridModel? get model => _model;
+ GridModels? _modelCatalog;
+ ModelsMenuController? _modelUsage;
+ bool _ownsModelUsage = true;
+ bool _loadingModels = false;
+ int _modelRequest = 0;
+
+ String get subscriptionLabel => switch (_engine) {
+ 'codex' => 'OpenAI',
+ 'claude' => 'Anthropic',
+ _ => '$agentLabel default',
+ };
+ String get modelLabel => _model == null
+ ? subscriptionLabel
+ : [_model!.id, if (_model!.node.isNotEmpty) _model!.node].join(' · ');
+ static String _modelId(GridModel model) =>
+ 'model:${jsonEncode([model.grid, model.id])}';
+ bool _modelAvailable(GridModel model) =>
+ !isTerminal &&
+ _modelCatalog?.supportsModelLaunch == true &&
+ _modelCatalog!.reachable &&
+ _modelCatalog!.canRunLocally(_engine) &&
+ _modelCatalog!.sections.any(
+ (section) =>
+ section.name == model.grid &&
+ section.models.any((candidate) => candidate.id == model.id),
+ );
+
+ String? get modelNotice {
+ if (_loadingModels) return 'Loading models…';
+ final catalog = _modelCatalog;
+ if (catalog == null) return null;
+ if (!catalog.reachable) {
+ return 'Could not load models from $machineLabel. Refresh to retry.';
+ }
+ if (!catalog.supportsModelLaunch) {
+ return 'Update Harness CLI on $machineLabel to choose a model before starting.';
+ }
+ if (!catalog.canRunLocally(_engine)) {
+ return '$agentLabel uses its own login.';
+ }
+ if (_model != null && !_modelAvailable(_model!)) {
+ return 'The selected model is unavailable. Choose another model or your subscription.';
+ }
+ if (catalog.sections.every((section) => section.models.isEmpty)) {
+ return 'No models are running on your machines. Open Manage Models to start one.';
+ }
+ return null;
+ }
+
+ Future<void> refreshModels() async {
+ if (_disposed) return;
+ final request = ++_modelRequest;
+ final machine = _machineId;
+ _loadingModels = true;
+ if (_modelUsage == null) {
+ _modelUsage = ModelsMenuController(remote: app.readRemoteUsage);
+ _modelUsage!.addListener(_refresh);
+ }
+ // Native credential reads stay out of fixture tests, as in the session picker.
+ if (!kUnderTest) unawaited(_modelUsage!.refresh());
+ _refresh();
+ final answer = await app.gridModels(machine);
+ if (_disposed || request != _modelRequest || machine != _machineId) return;
+ _modelCatalog = answer;
+ _loadingModels = false;
+ _refresh();
+ }
+
+ List<NewHarnessOption> _modelOptions() {
+ final catalog = _modelCatalog;
+ final subscription = _profile == null
+ ? _modelUsage?.subscriptionFor(
+ _engine,
+ local: _machine?.isLocalMachine == true,
+ machineName: machineLabel,
+ )
+ : null;
+ final groups = <NewHarnessOption>[
+ ..._ranked([
+ NewHarnessOption(
+ id: defaultModelId,
+ title: subscriptionLabel,
+ detail: [
+ '${_profile?.label ?? 'Default account'} on $machineLabel',
+ if (subscription?['status'] case final String status) status,
+ ].join(' · '),
+ group: 'Subscription',
+ engine: _engine,
+ machineId: _machineId,
+ ),
+ ]),
+ if (catalog?.supportsModelLaunch == true &&
+ catalog!.canRunLocally(_engine))
+ for (final section in catalog.sections)
+ ..._ranked([
+ for (final model in section.models)
+ NewHarnessOption(
+ id: _modelId(
+ GridModel(id: model.id, node: model.node, grid: section.name),
+ ),
+ title: model.id,
+ detail: model.node,
+ group: section.own
+ ? 'On your machines'
+ : 'Shared · ${section.name}',
+ model: GridModel(
+ id: model.id,
+ node: model.node,
+ grid: section.name,
+ ),
+ machineId: _machineId,
+ ),
+ ]),
+ NewHarnessOption(
+ id: refreshModelsId,
+ title: _loadingModels ? 'Loading models…' : 'Refresh models',
+ synthetic: true,
+ enabled: !_loadingModels,
+ ),
+ const NewHarnessOption(
+ id: manageModelsId,
+ title: 'Manage Models…',
+ synthetic: true,
+ ),
+ ];
+ total =
+ 1 +
+ (catalog?.supportsModelLaunch == true && catalog!.canRunLocally(_engine)
+ ? catalog.sections.fold<int>(
+ 0,
+ (count, section) => count + section.models.length,
+ )
+ : 0);
+ return groups;
+ }
+
LocalCodexProfile? _profile;
bool _profileChosen = false;
String? get profileLabel =>
@@ -756,6 +1005,9 @@ class NewHarnessController extends ChangeNotifier {
NewHarnessDraft get draft => NewHarnessDraft(
machineId: _machineId,
engine: _engine,
+ harnessId: _harnessId,
+ model: _model,
+ advancedOpen: advancedOpen,
project: _project,
task: task,
permissionMode: _mode,
@@ -810,7 +1062,7 @@ class NewHarnessController extends ChangeNotifier {
knownHarnessBase[canonicalHarnessId(engine)] ??
'claude'
: engine;
- String get _base => _baseOf(_engine);
+ String get _base => _engine;
// Browsing previews an engine without changing the launch draft. Keep that
// engine while its settings are open in a child picker.
@@ -834,7 +1086,7 @@ class NewHarnessController extends ChangeNotifier {
String get modeLabel =>
_modes.where((m) => m.id == mode).firstOrNull?.label ?? mode;
bool get riskyMode => _modes.any((m) => m.id == mode && m.risky);
- bool get usesProfile => _base == 'codex';
+ bool get usesProfile => _base == 'codex' && _model == null;
bool get hasProfile => _baseOf(_settingsEngine) == 'codex';
bool get supportsProfiles =>
hasProfile && _machine?.engines['codex']?.supportsCodexHome == true;
@@ -882,13 +1134,25 @@ class NewHarnessController extends ChangeNotifier {
);
}
+ void openLaunchSetting(NewHarnessField setting) {
+ if (locked) return;
+ _agentPreview = null;
+ focusField(setting);
+ }
+
/// The arguments exposed by the launch menu. Machine sets the context;
/// permissions and profiles belong to the selected agent's picker.
List<NewHarnessField> get fields => [
+ NewHarnessField.harness,
NewHarnessField.agent,
+ if (!isTerminal) NewHarnessField.model,
NewHarnessField.machine,
NewHarnessField.projectMenu,
- if (isGitProject) NewHarnessField.branch,
+ if (advancedOpen) ...[
+ if (isGitProject) NewHarnessField.branch,
+ if (hasModes) NewHarnessField.mode,
+ if (usesProfile) NewHarnessField.profile,
+ ],
];
bool _supportsField(NewHarnessField value) =>
fields.contains(value) ||
@@ -898,6 +1162,7 @@ class NewHarnessController extends ChangeNotifier {
value == NewHarnessField.projectName ||
value == NewHarnessField.projectRepository ||
value == NewHarnessField.machine ||
+ (value == NewHarnessField.branch && isGitProject) ||
(value == NewHarnessField.mode && _settingsModes.isNotEmpty) ||
(value == NewHarnessField.profile && hasProfile);
@@ -927,12 +1192,6 @@ class NewHarnessController extends ChangeNotifier {
String? _visibleFolder, folderRefreshError;
String? _listing;
- bool _known(String? id) =>
- id != null &&
- (isTerminalEngine(id) ||
- isHarnessId(id) ||
- allEngines.any((identity) => identity.id == id));
-
MachineState? get _machine => app.stateOf(_machineId);
bool get isTerminal => isTerminalEngine(_engine);
bool get needsProject =>
@@ -993,7 +1252,9 @@ class NewHarnessController extends ChangeNotifier {
NewHarnessField.launch => '',
NewHarnessField.projectMenu => 'Find a project by name or path',
NewHarnessField.task => 'What should this agent work on? (optional)',
- NewHarnessField.agent => 'Choose an agent',
+ NewHarnessField.harness => 'Search harnesses',
+ NewHarnessField.agent => 'Search agents',
+ NewHarnessField.model => 'Search subscriptions and models',
NewHarnessField.machine => 'Choose a machine',
NewHarnessField.branch => 'Search branches',
NewHarnessField.project => 'Folder path',
@@ -1023,6 +1284,7 @@ class NewHarnessController extends ChangeNotifier {
);
}
if (next == NewHarnessField.mode || next == NewHarnessField.profile) {
+ if (field != NewHarnessField.agent) _agentPreview = null;
_agentSettingsOrigin = (
field: field == NewHarnessField.agent
? NewHarnessField.agent
@@ -1056,6 +1318,7 @@ class NewHarnessController extends ChangeNotifier {
if (next == NewHarnessField.branch) {
unawaited(refreshBranches(force: false));
}
+ if (next == NewHarnessField.model) unawaited(refreshModels());
}
void nextField([int step = 1]) {
@@ -1159,7 +1422,7 @@ class NewHarnessController extends ChangeNotifier {
/// out: "Create branch x" is a real answer to the Branch row, it is only
/// not one the arrows should cycle onto.
void applyOption(NewHarnessOption option) {
- if (locked || !option.enabled) return;
+ if (locked || !option.enabled || !_optionIsCurrent(option)) return;
error = null;
_steered = true;
_apply(option);
@@ -1174,8 +1437,37 @@ class NewHarnessController extends ChangeNotifier {
if (locked || option == null || option.synthetic || !option.enabled) {
return;
}
- _apply(option);
- _refresh();
+ applyOption(option);
+ }
+
+ bool _optionIsCurrent(NewHarnessOption option) {
+ if (field == NewHarnessField.model &&
+ (option.machineId != _machineId ||
+ option.model != null && !_modelAvailable(option.model!))) {
+ warn(
+ 'This model choice is no longer available. Refresh models and choose again.',
+ );
+ return false;
+ }
+ if (field == NewHarnessField.agent &&
+ !compatibleEngines.contains(option.id)) {
+ warn('Choose an agent compatible with $harnessLabel on $machineLabel.');
+ return false;
+ }
+ if (field == NewHarnessField.profile && option.machineId != _machineId) {
+ warn('Choose a Codex profile on $machineLabel. The machine has changed.');
+ return false;
+ }
+ if ((field == NewHarnessField.projectMenu ||
+ field == NewHarnessField.project ||
+ field == NewHarnessField.projectName ||
+ field == NewHarnessField.projectRepository) &&
+ option.machineId != null &&
+ option.machineId != _machineId) {
+ warn('Choose a project on $machineLabel. The machine has changed.');
+ return false;
+ }
+ return true;
}
NewHarnessOption? get selected =>
@@ -1195,7 +1487,10 @@ class NewHarnessController extends ChangeNotifier {
/// wears the ✓, as the current folder and branch do in an editor's pickers.
bool isCurrent(NewHarnessOption option) => switch (field) {
NewHarnessField.launch || NewHarnessField.task => false,
+ NewHarnessField.harness => option.id == (_harnessId ?? codingId),
NewHarnessField.agent => option.id == _engine,
+ NewHarnessField.model =>
+ option.id == (_model == null ? defaultModelId : _modelId(_model!)),
NewHarnessField.machine => option.id == _machineId,
NewHarnessField.branch => option.id == branchRef,
NewHarnessField.project ||
@@ -1223,6 +1518,10 @@ class NewHarnessController extends ChangeNotifier {
static const existingProjectId = 'project:existing';
static const repositoryId = 'project:repository';
static const storeId = 'agent:store';
+ static const codingId = 'harness:coding';
+ static const defaultModelId = 'model:subscription';
+ static const manageModelsId = 'model:manage';
+ static const refreshModelsId = 'model:refresh';
static const permissionsId = 'agent:permissions';
static const profileId = 'agent:profile';
static const defaultProfileId = 'profile:default';
@@ -1231,8 +1530,7 @@ class NewHarnessController extends ChangeNotifier {
static const _store = NewHarnessOption(
id: storeId,
synthetic: true,
- title: 'Browse more harnesses…',
- detail: 'Harness Store',
+ title: 'Browse Harness Store…',
);
// For anyone who would rather point at a folder than type its path. It stays
@@ -1273,6 +1571,12 @@ class NewHarnessController extends ChangeNotifier {
void accept([NewHarnessOption? row]) {
final option = row ?? selected;
if (locked || option?.id == storeId) return;
+ if (field == NewHarnessField.agent &&
+ option != null &&
+ !compatibleEngines.contains(option.id)) {
+ warn('Choose an agent compatible with $harnessLabel on $machineLabel.');
+ return;
+ }
if (option?.id == permissionsId) {
focusField(NewHarnessField.mode, previewAgent: true);
return;
@@ -1323,19 +1627,7 @@ class NewHarnessController extends ChangeNotifier {
notifyListeners();
return;
}
- if (field == NewHarnessField.profile && option.machineId != _machineId) {
- warn('Choose a Codex profile on $machineLabel. The machine has changed.');
- return;
- }
- if ((field == NewHarnessField.projectMenu ||
- field == NewHarnessField.project ||
- field == NewHarnessField.projectName ||
- field == NewHarnessField.projectRepository) &&
- option.machineId != null &&
- option.machineId != _machineId) {
- warn('Choose a project on $machineLabel. The machine has changed.');
- return;
- }
+ if (!_optionIsCurrent(option)) return;
final from = field;
final previousMachine = _machineId;
_apply(option);
@@ -1414,8 +1706,12 @@ class NewHarnessController extends ChangeNotifier {
void _apply(NewHarnessOption option) {
switch (field) {
+ case NewHarnessField.harness:
+ _selectHarness(option.id == codingId ? null : option.id);
case NewHarnessField.agent:
_selectEngine(option.id);
+ case NewHarnessField.model:
+ _model = option.model;
case NewHarnessField.machine:
_selectMachine(option.id);
case NewHarnessField.branch:
@@ -1447,6 +1743,8 @@ class NewHarnessController extends ChangeNotifier {
}
void _selectEngine(String engine) {
+ if (!compatibleEngines.contains(engine)) return;
+ _selectionTouched = true;
final changed = engine != _engine;
if (_engine != engine) {
_profile = null;
@@ -1454,7 +1752,9 @@ class NewHarnessController extends ChangeNotifier {
_resetProfiles();
}
_engine = engine;
+ if (isTerminal) _model = null;
if (changed &&
+ _harnessId == null &&
_project.generated != null &&
field != NewHarnessField.projectName) {
_project = _generatedProject();
@@ -1468,10 +1768,23 @@ class NewHarnessController extends ChangeNotifier {
}
}
+ void _selectHarness(String? id) {
+ _selectionTouched = true;
+ _harnessId = id;
+ _selectEngine(_initialEngine(app.agentPreference.engineFor(id) ?? _engine));
+ if (_project.generated != null) {
+ _project = _generatedProject();
+ unawaited(_refreshGeneratedProject());
+ }
+ }
+
void _selectMachine(String id) {
if (_machineId == id) return;
_projectsByMachine[_machineId] = _project;
_machineId = id;
+ _modelCatalog = null;
+ _loadingModels = false;
+ _modelRequest++;
_projectFilter = '';
_project =
_projectsByMachine[id] ??
@@ -1495,7 +1808,7 @@ class NewHarnessController extends ChangeNotifier {
NewHarnessProject _generatedProject() => NewHarnessProject.generated(
ProjectFolderRequest.generated(
- label: _machine?.dsh[_engine]?.name ?? engineIdentity(_engine).label,
+ label: _harnessId == null ? engineIdentity(_engine).label : harnessLabel,
at: _now(),
),
);
@@ -1871,9 +2184,14 @@ class NewHarnessController extends ChangeNotifier {
entry.id,
entry.name,
entry.installed,
+ entry.engine,
+ ...entry.supportedEngines,
+ null,
],
...app.agentPreference.recent,
null,
+ ...app.agentPreference.recentHarnesses,
+ null,
// Projects can arrive after the box opens, including metadata recovered
// by the local CLI. Terminal output alone must not reorder this list.
..._recentProjectFolders(),
@@ -1915,9 +2233,14 @@ class NewHarnessController extends ChangeNotifier {
return;
}
options = switch (field) {
+ NewHarnessField.harness => [
+ ..._harnessOptions(),
+ if (offersStore) _store,
+ ],
NewHarnessField.launch ||
NewHarnessField.task ||
NewHarnessField.agent => const [],
+ NewHarnessField.model => _modelOptions(),
NewHarnessField.machine => _machineOptions(),
NewHarnessField.branch => [
..._ranked(_branchOptions()),
@@ -2009,7 +2332,7 @@ class NewHarnessController extends ChangeNotifier {
: null) ??
agents.firstOrNull;
_agentPreview = target?.id;
- options = [...agents, if (offersStore) _store];
+ options = agents;
matchCount = agents.length;
final kept = options.indexWhere((row) => row.id == current);
cursor = kept >= 0
@@ -2154,7 +2477,7 @@ class NewHarnessController extends ChangeNotifier {
return [for (final entry in scored) entry.$3];
}
- List<NewHarnessOption> _agentOptions() {
+ List<NewHarnessOption> _harnessOptions() {
final machine = _machine;
final harnesses = machine != null && machine.dsh.loaded
? [
@@ -2171,24 +2494,27 @@ class NewHarnessController extends ChangeNotifier {
final ids = <String>{
for (final id in [
// Keep the inherited choice beside the prompt, followed by recent choices.
- _engine,
- ...app.agentPreference.recent.where(_known),
- for (final identity in allEngines) identity.id,
+ ?_harnessId,
+ ...app.agentPreference.recentHarnesses.where(isHarnessId),
...harnesses,
- kTerminalEngine,
])
operationId(id),
};
return _ranked([
+ const NewHarnessOption(
+ id: codingId,
+ title: 'Coding',
+ detail: 'Work in any code project',
+ ),
for (final id in ids)
NewHarnessOption(
id: id,
title: labelOf(id),
engine: id,
detail: [
- if (isTerminalEngine(id))
- 'A shell, no agent'
- else if (isHarnessId(id))
+ // Terminal is not a harness here — it moved to the Agent list — so
+ // only a harness row carries a description.
+ if (isHarnessId(id))
machine?.dsh[id]?.tagline ??
engineIdentity(id).tagline ??
machine?.dsh[id]?.category ??
@@ -2204,8 +2530,37 @@ class NewHarnessController extends ChangeNotifier {
]);
}
+ List<NewHarnessOption> _agentOptions() => _ranked([
+ for (final id in <String>{
+ _engine,
+ ...app.agentPreference.recent,
+ for (final identity in allEngines) identity.id,
+ kTerminalEngine,
+ })
+ if (!isHarnessId(id) && compatibleEngines.contains(id))
+ NewHarnessOption(id: id, title: labelOf(id), engine: id, detail: ''),
+ ]);
+
+ /// Whether [machine] can be given work now — the same test that enables
+ /// its row below.
+ bool _machineUsable(MachineState machine) =>
+ !machine.needsLink && !machine.isOffline;
+
+ // Before any query ranks the list: this computer, then the machines that
+ // can take work now, then the ones that cannot (unlinked or offline). The
+ // local one is the choice most launches want, and an unusable machine in
+ // the middle of the usable ones made the list read as a jumble. Within
+ // each group the inventory's own order holds.
List<NewHarnessOption> _machineOptions() => _ranked([
- for (final machine in app.machineStates.values)
+ for (final machine in [
+ ...app.machineStates.values.where((m) => m.isLocalMachine),
+ ...app.machineStates.values.where(
+ (m) => !m.isLocalMachine && _machineUsable(m),
+ ),
+ ...app.machineStates.values.where(
+ (m) => !m.isLocalMachine && !_machineUsable(m),
+ ),
+ ])
if (!machine.machine.isShared)
NewHarnessOption(
id: machine.machine.machineId,
@@ -2680,13 +3035,9 @@ class NewHarnessController extends ChangeNotifier {
return NewHarnessOutcome.failed;
}
final choice = _engine;
- final harness = isHarnessId(choice) ? choice : null;
+ var harness = _harnessId;
final terminal = isTerminalEngine(choice);
- final base = harness == null
- ? choice
- : machine.dsh[choice]?.engine ??
- knownHarnessBase[canonicalHarnessId(choice)] ??
- 'claude';
+ final base = choice;
// The daemon's launch installs a missing engine inside its new terminal.
// A cached availability probe must not block that first launch.
final recheck = checking;
@@ -2699,6 +3050,15 @@ class NewHarnessController extends ChangeNotifier {
error = null;
status = recheck ? 'Checking on the harness…' : 'Starting harness…';
notifyListeners();
+ if (_model != null && !recheck) {
+ await refreshModels();
+ if (_disposed) return NewHarnessOutcome.failed;
+ if (!_modelAvailable(_model!)) {
+ return _fail(
+ 'The selected model is unavailable for $agentLabel on $machineLabel. Choose a model or use your subscription.',
+ );
+ }
+ }
if (harness != null && !recheck) {
await app.probeDsh(_machineId, force: true);
if (_disposed) return NewHarnessOutcome.failed;
@@ -2708,15 +3068,26 @@ class NewHarnessController extends ChangeNotifier {
'${labelOf(harness)} harness.',
);
}
+ harness =
+ harnessForOperation(machine.dsh.entries, harness)?.id ?? harness;
if (machine.dsh[harness]?.installed == false) {
status = 'Installing ${labelOf(harness)}… this can take a few minutes';
notifyListeners();
final failure = await app.installDsh(_machineId, harness);
if (_disposed) return NewHarnessOutcome.failed;
if (failure != null) return _fail(failure);
+ await app.probeDsh(_machineId, force: true);
+ if (_disposed) return NewHarnessOutcome.failed;
status = 'Starting harness…';
notifyListeners();
}
+ final compatible =
+ machine.dsh[harness]?.supportedEngines ?? compatibleEngines;
+ if (!compatible.contains(base)) {
+ return _fail(
+ '$harnessLabel does not support ${labelOf(base)} on $machineLabel. Choose a compatible agent.',
+ );
+ }
}
final permissionMode = hasModes ? mode : null;
final bypass =
@@ -2733,7 +3104,8 @@ class NewHarnessController extends ChangeNotifier {
placement: effectivePlacement,
bypassPermission: bypass,
permissionMode: permissionMode,
- codexHome: base == 'codex' ? _profile?.path : null,
+ codexHome: base == 'codex' && _model == null ? _profile?.path : null,
+ model: _model,
dsh: harness,
// Sent exactly as written; an agent that cannot take one is never sent it.
prompt: takesTask && firstMessage.isNotEmpty ? firstMessage : null,
@@ -2758,7 +3130,7 @@ class NewHarnessController extends ChangeNotifier {
bypassPermission: bypass,
permissionMode: permissionMode,
);
- unawaited(app.agentPreference.remember(choice));
+ unawaited(app.agentPreference.remember(choice, harnessId: _harnessId));
busy = false;
status = null;
return NewHarnessOutcome.created;
@@ -2778,6 +3150,8 @@ class NewHarnessController extends ChangeNotifier {
_appTick?.cancel();
_listDebounce?.cancel();
app.removeListener(_onApp);
+ _modelUsage?.removeListener(_refresh);
+ if (_ownsModelUsage) _modelUsage?.dispose();
super.dispose();
}
}
diff --git a/desktop/lib/usage/models_menu_controller.dart b/desktop/lib/usage/models_menu_controller.dart
index d88fe6477..e39b3484b 100644
--- a/desktop/lib/usage/models_menu_controller.dart
+++ b/desktop/lib/usage/models_menu_controller.dart
@@ -34,6 +34,22 @@ class ModelsMenuController extends ChangeNotifier {
_row(account, _now(), failed: _failed),
];
+ /// The subscription the selected agent machine can actually use. An account
+ /// seen only on another computer must not be presented as this one's login.
+ Map<String, Object?>? subscriptionFor(
+ String engine, {
+ required bool local,
+ required String machineName,
+ }) {
+ for (final account in _usage.accounts) {
+ if (account.provider.engineId == engine &&
+ (local ? account.isLocal : account.machines.contains(machineName))) {
+ return _row(account, _now(), failed: _failed);
+ }
+ }
+ return null;
+ }
+
Future<void> refresh() {
if (_disposed) return Future.value();
// Re-evaluate expired windows even if another request is already running.
diff --git a/desktop/lib/widgets/agent_picker.dart b/desktop/lib/widgets/agent_picker.dart
index 434bebe99..fc6d7df0c 100644
--- a/desktop/lib/widgets/agent_picker.dart
+++ b/desktop/lib/widgets/agent_picker.dart
@@ -75,6 +75,7 @@ class AgentPicker extends StatefulWidget {
this.height = 64,
this.width,
this.terminalStyle = false,
+ this.label = 'Agent',
});
final String value;
@@ -108,6 +109,7 @@ class AgentPicker extends StatefulWidget {
/// dialog, and Flutter orders Tab by when a focus node attached.
final double? width;
final bool terminalStyle;
+ final String label;
/// What the search input says before anything is typed.
static const hint = 'Choose an agent for what you’d like to make';
@@ -126,6 +128,8 @@ class AgentPicker extends StatefulWidget {
}
class _AgentPickerState extends State<AgentPicker> {
+ String get _hint =>
+ widget.label == 'Agent' ? AgentPicker.hint : 'Search harnesses';
final _portal = OverlayPortalController();
final _query = TextEditingController();
final _inputFocus = FocusNode(debugLabel: 'Agent search input');
@@ -359,7 +363,7 @@ class _AgentPickerState extends State<AgentPicker> {
/// section's line above it says what the box is for (owner, 2026-09-17:
/// "in the search box, just the agent name").
Widget _chosen(AgentChoice? choice) => KeyedSubtree(
- key: const Key('new-agent-agent-choice'),
+ key: Key('new-agent-${widget.label.toLowerCase()}-choice'),
child: Text(
choice?.label ?? 'Choose an agent',
maxLines: 1,
@@ -381,11 +385,11 @@ class _AgentPickerState extends State<AgentPicker> {
child: Semantics(
button: true,
label: choice == null
- ? AgentPicker.hint
- : 'Agent: ${choice.label}. Search agents',
+ ? _hint
+ : '${widget.label}: ${choice.label}. Search ${widget.label.toLowerCase()}s',
excludeSemantics: true,
child: Material(
- key: const Key('new-agent-agent-field'),
+ key: Key('new-agent-${widget.label.toLowerCase()}-field'),
color: grid.AppPalette.swarmSearchSurface,
surfaceTintColor: Colors.transparent,
elevation: 2,
@@ -583,7 +587,7 @@ class _AgentPickerState extends State<AgentPicker> {
final sideBySide = showPreview && width >= 760;
final preview = showPreview
? _AgentPreview(
- key: const ValueKey('new-agent-agent-preview'),
+ key: ValueKey('new-agent-${widget.label.toLowerCase()}-preview'),
choice: highlighted,
status: widget.statusOf?.call(highlighted.id),
current: highlighted.id == widget.value,
@@ -593,14 +597,16 @@ class _AgentPickerState extends State<AgentPicker> {
: null;
final results = ExcludeFocus(
child: ListView.builder(
- key: const ValueKey('new-agent-agent-list'),
+ key: ValueKey('new-agent-${widget.label.toLowerCase()}-list'),
controller: _scroll,
padding: const EdgeInsets.all(8),
itemExtent: rowHeight,
itemCount: lines,
itemBuilder: (context, index) => empty
? Padding(
- key: const Key('new-agent-agent-search-empty'),
+ key: Key(
+ 'new-agent-${widget.label.toLowerCase()}-search-empty',
+ ),
padding: const EdgeInsets.symmetric(horizontal: 12),
child: Align(
alignment: Alignment.centerLeft,
@@ -623,7 +629,7 @@ class _AgentPickerState extends State<AgentPicker> {
child: TextFieldTapRegion(
groupId: _tapGroup,
child: Material(
- key: const Key('new-agent-agent-panel'),
+ key: Key('new-agent-${widget.label.toLowerCase()}-panel'),
color: grid.AppPalette.swarmSearchSurface,
surfaceTintColor: Colors.transparent,
// Lifted off the dialog it covers, lightly: on the dialog's dark
@@ -643,12 +649,14 @@ class _AgentPickerState extends State<AgentPicker> {
mainAxisSize: MainAxisSize.min,
children: [
Semantics(
- label: 'Search agents',
+ label: 'Search ${widget.label.toLowerCase()}s',
child: ReadlineKeys(
controller: _query,
onChanged: _queryChanged,
child: SwarmSearchInput(
- inputKey: const Key('new-agent-agent-search'),
+ inputKey: Key(
+ 'new-agent-${widget.label.toLowerCase()}-search',
+ ),
controller: _query,
focusNode: _inputFocus,
groupId: _tapGroup,
@@ -657,7 +665,7 @@ class _AgentPickerState extends State<AgentPicker> {
onChanged: _queryChanged,
autofocus: false,
showClose: !widget.terminalStyle,
- hintText: AgentPicker.hint,
+ hintText: _hint,
rounded: !widget.terminalStyle,
prominent: !widget.terminalStyle,
prompt: widget.terminalStyle ? '>' : null,
@@ -765,7 +773,9 @@ class _AgentPickerState extends State<AgentPicker> {
}
},
child: ListTile(
- key: ValueKey('new-agent-agent-row-${choice.id}'),
+ key: ValueKey(
+ 'new-agent-${widget.label.toLowerCase()}-row-${choice.id}',
+ ),
minTileHeight: rowHeight,
selected: highlighted,
textColor: Colors.white,
@@ -811,7 +821,9 @@ class _AgentPickerState extends State<AgentPicker> {
Flexible(
child: Text(
'by $creator',
- key: ValueKey('new-agent-agent-row-by-${choice.id}'),
+ key: ValueKey(
+ 'new-agent-${widget.label.toLowerCase()}-row-by-${choice.id}',
+ ),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: widget.terminalStyle
@@ -842,7 +854,9 @@ class _AgentPickerState extends State<AgentPicker> {
grid.AppType.bodySize,
),
child: TextButton(
- key: const ValueKey('new-agent-agent-row-action'),
+ key: ValueKey(
+ 'new-agent-${widget.label.toLowerCase()}-row-action',
+ ),
onPressed: () => _choose(choice),
style: TextButton.styleFrom(foregroundColor: Colors.white),
child: SwarmSearchActionLabel(
@@ -889,7 +903,7 @@ class _AgentPickerState extends State<AgentPicker> {
// nothing else: the sections under the panel are not the target.
Positioned.fill(
child: GestureDetector(
- key: const Key('new-agent-agent-barrier'),
+ key: Key('new-agent-${widget.label.toLowerCase()}-barrier'),
behavior: HitTestBehavior.opaque,
onTap: _close,
),
diff --git a/desktop/lib/widgets/new_agent_dialog.dart b/desktop/lib/widgets/new_agent_dialog.dart
index 44b108a46..3585c75ad 100644
--- a/desktop/lib/widgets/new_agent_dialog.dart
+++ b/desktop/lib/widgets/new_agent_dialog.dart
@@ -227,7 +227,11 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
bool get _confirmationPending => _creation?.awaitingConfirmation == true;
bool get _choicesLocked => _submitting || _confirmationPending;
late String _engine = allEngines.first.id;
+ String? _harnessId;
+ final _harnessSearchFocus = FocusNode(debugLabel: 'Harness search');
bool _engineChosenByUser = false;
+ bool _selectionTouched = false;
+ bool _advancedTouched = false;
late String _machineId = widget.machineId;
int _machineRevision = 0;
late String? _folder = widget.initialFolder;
@@ -264,6 +268,7 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
_task.dispose();
_folderFocus.dispose();
_agentSearchFocus.dispose();
+ _harnessSearchFocus.dispose();
_actionFocus.dispose();
_choicesScroll.dispose();
super.dispose();
@@ -273,22 +278,26 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
void initState() {
super.initState();
_task.addListener(_onTaskChanged);
- final remembered = widget.notifier.agentPreference.value;
+ final prefs = widget.notifier.agentPreference;
final asked = widget.initialEngine;
- if (asked != null &&
- (isHarnessId(asked) ||
- isTerminalEngine(asked) ||
- allEngines.any((identity) => identity.id == asked))) {
- // Chosen before the dialog opened: counts as the person's choice, so no
- // probe or remembered preference moves it.
- _engine = asked;
- _engineChosenByUser = true;
- } else if (_knownChoice(remembered)) {
- _engine = remembered!;
- _engineChosenByUser = true;
- } else {
- _engine = _preferredInstalledEngine();
- }
+ _harnessId =
+ widget.initialDraft?.harnessId ??
+ (isHarnessId(asked)
+ ? asked
+ : asked == null
+ ? prefs.harness
+ : null);
+ final requested = isHarnessId(asked) ? null : asked;
+ _engine = widget.initialDraft?.engine ?? _compatibleEngine(requested);
+ _engineChosenByUser =
+ widget.initialDraft != null ||
+ (asked != null && !isHarnessId(asked)) ||
+ prefs.engineFor(_harnessId) != null ||
+ prefs.value != null;
+ if (!_engineChosenByUser) _engine = _preferredInstalledEngine();
+ _advancedOpen =
+ widget.initialDraft?.advancedOpen ??
+ (widget.initiallyAdvanced || prefs.advancedOpen);
// Which engines this machine actually has. Asked here rather than at
// connect because the answer costs the far side one interactive shell per
// engine and is only ever read on this screen. Deferred a frame so the
@@ -307,7 +316,7 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
// actionable control once the route and its focus tree are mounted:
// the agent search, so the dialog opens ready to type — or the
// project, when the agent was chosen before it opened (the Store).
- (widget.initialEngine == null ? _agentSearchFocus : _folderFocus)
+ (widget.initialEngine == null ? _harnessSearchFocus : _folderFocus)
.requestFocus();
unawaited(_probeEngines(initialProbe: widget.initialEngineProbe));
// And the harnesses, whatever is selected: what the machine has
@@ -318,22 +327,28 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
});
}
- /// Whether [id] is something this dialog can offer: an engine, or a harness
- /// this build ships a face for, or one the machine has named.
- bool _knownChoice(String? id) =>
- id != null &&
- (isTerminalEngine(id) ||
- allEngines.any((identity) => identity.id == id) ||
- knownHarnesses.any((identity) => identity.id == id) ||
- _harness(id) != null);
-
- /// Which harnesses this machine has or could install — asked when a harness
- /// is chosen, not on open: most creates never involve one, and the answer
- /// costs the machine a request. Forced, for the reason `_probeEngines`
- /// gives: an install this very dialog starts is what makes a stored answer
- /// stale.
- Future<void> _probeHarnesses() =>
- widget.notifier.probeDsh(_machineId, force: true);
+ /// Refresh compatibility without replacing an explicit engine choice.
+ Future<void> _probeHarnesses() async {
+ final revision = _machineRevision;
+ await widget.notifier.probeDsh(_machineId, force: true);
+ if (!mounted ||
+ _choicesLocked ||
+ revision != _machineRevision ||
+ _selectionTouched ||
+ widget.initialDraft != null ||
+ _harnessId == null ||
+ (widget.initialEngine != null && !isHarnessId(widget.initialEngine))) {
+ return;
+ }
+ final preferred = _compatibleEngine(null);
+ if (_engine == preferred) return;
+ setState(() {
+ _engine = preferred;
+ _codexProfile = null;
+ _codexProfileChosen = false;
+ _codexProfilesBusy = true;
+ });
+ }
/// The machine's row for harness [id], or null while it has not answered
/// (or does not know the request). Null is "unknown", never "absent".
@@ -343,7 +358,50 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
return harnessForOperation(machine.dsh.entries, id);
}
- bool get _engineIsHarness => isHarnessId(_engine);
+ bool get _engineIsHarness => _harnessId != null;
+ List<String> get _compatibleEngines => _harnessId == null
+ ? [for (final engine in allEngines) engine.id, kTerminalEngine]
+ : _harness(_harnessId!)?.supportedEngines ?? [_baseEngine(_harnessId!)];
+ String _compatibleEngine(String? requested) {
+ final prefs = widget.notifier.agentPreference;
+ for (final candidate in [
+ requested,
+ prefs.engineFor(_harnessId),
+ prefs.value,
+ if (_harnessId != null) _baseEngine(_harnessId!),
+ ]) {
+ if (candidate != null && _compatibleEngines.contains(candidate)) {
+ return candidate;
+ }
+ }
+ return _compatibleEngines.first;
+ }
+
+ void _chooseHarness(String id) {
+ if (_choicesLocked) return;
+ setState(() {
+ _engineChosenByUser = true;
+ _selectionTouched = true;
+ _harnessId = id == NewHarnessController.codingId ? null : id;
+ final previous = _engine;
+ _engine = _compatibleEngine(
+ widget.notifier.agentPreference.engineFor(_harnessId) ?? _engine,
+ );
+ if (previous != _engine) {
+ _codexProfile = null;
+ _codexProfileChosen = false;
+ _codexProfilesBusy = true;
+ }
+ if (_generatedProject != null) {
+ _generatedProject = ProjectFolderRequest.generated(
+ label: _labelOf(_harnessId ?? _engine),
+ at: DateTime.now(),
+ );
+ _projectName = _generatedProject!.name;
+ }
+ _error = null;
+ });
+ }
/// A shell rather than an agent: nothing to install, no task, no permission
/// mode, and a folder is a place to open in, not a project to prepare.
@@ -422,28 +480,42 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
/// flight, or the one that just failed (kept on screen so its verdict and
/// the fix it names stay readable under the Retry). Null otherwise.
DshInstallRun? get _installRun {
- final run = widget.notifier.stateOf(_machineId)?.dsh.runs[_engine];
+ final run = widget.notifier.stateOf(_machineId)?.dsh.runs[_harnessId];
if (run == null) return null;
if (_installing) return run;
- if (run.failed && _willInstallHarness(_engine)) return run;
+ if (run.failed && _harnessId != null && _willInstallHarness(_harnessId!)) {
+ return run;
+ }
return null;
}
Future<void> _loadAgentPreference() async {
await widget.notifier.agentPreference.load();
- if (!mounted || _choicesLocked || _engineChosenByUser) return;
- final remembered = widget.notifier.agentPreference.value;
- if (_knownChoice(remembered)) {
- setState(() {
- _engineChosenByUser = true;
- if (_engine != remembered) {
- _engine = remembered!;
- _codexProfile = null;
- _codexProfileChosen = false;
- _codexProfilesBusy = true;
- }
- });
+ if (!mounted || _choicesLocked) return;
+ final prefs = widget.notifier.agentPreference;
+ if (!_advancedTouched && widget.initialDraft == null) {
+ setState(
+ () => _advancedOpen = widget.initiallyAdvanced || prefs.advancedOpen,
+ );
}
+ if (_engineChosenByUser) return;
+ if (prefs.value == null &&
+ prefs.harness == null &&
+ prefs.engineFor(_harnessId) == null) {
+ return;
+ }
+ setState(() {
+ if (widget.initialEngine == null) {
+ _harnessId = widget.notifier.agentPreference.harness;
+ }
+ final remembered = _compatibleEngine(null);
+ if (_engine != remembered) {
+ _engine = remembered;
+ _codexProfile = null;
+ _codexProfileChosen = false;
+ _codexProfilesBusy = true;
+ }
+ });
}
String _preferredInstalledEngine() {
@@ -526,6 +598,7 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
/// that can launch into one, so a click cannot land before the choice does.
bool get _waitingForCodexProfile =>
_baseEngine(_engine) == 'codex' &&
+ widget.initialDraft?.model == null &&
_availability('codex')?.supportsCodexHome == true &&
_codexProfilesBusy;
@@ -580,7 +653,9 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
return;
}
final choice = _engine;
- final harness = _engineIsHarness ? (_harness(choice)?.id ?? choice) : null;
+ var harness = _harnessId == null
+ ? null
+ : (_harness(_harnessId!)?.id ?? _harnessId);
final engine = _baseEngine(choice);
final profile = _codexProfile;
final hasModes = permissionModesOf(engine).isNotEmpty;
@@ -614,7 +689,7 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
_submitting = false;
_error =
'Update Harness CLI on $_machineName to create a '
- '${_labelOf(harness)} harness.';
+ '${_labelOf(harness!)} harness.';
});
return;
}
@@ -637,6 +712,21 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
return;
}
}
+ if (harness != null && !_confirmationPending) {
+ await _probeHarnesses();
+ if (!mounted) return;
+ harness = _harness(harness)?.id ?? harness;
+ if (!(_harness(harness)?.supportedEngines ?? _compatibleEngines).contains(
+ engine,
+ )) {
+ setState(() {
+ _submitting = false;
+ _error =
+ '${_labelOf(harness!)} does not support ${_labelOf(engine)} on $_machineName. Choose a compatible agent.';
+ });
+ return;
+ }
+ }
final error = await widget.notifier.createAgent(
_machineId,
engine: engine,
@@ -649,7 +739,10 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
permissionMode: permissionMode,
// Keep the explicit choice even if machine discovery changes mid-submit.
// The notifier must reject a now-remote target, never use its default login.
- codexHome: engine == 'codex' ? profile?.path : null,
+ codexHome: engine == 'codex' && widget.initialDraft?.model == null
+ ? profile?.path
+ : null,
+ model: terminal ? null : widget.initialDraft?.model,
dsh: harness,
prompt: _firstPrompt,
attempt: _creation,
@@ -679,7 +772,9 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
permissionMode: permissionMode,
);
// What New Harness lists first next time, before anything is typed.
- unawaited(widget.notifier.agentPreference.remember(choice));
+ unawaited(
+ widget.notifier.agentPreference.remember(choice, harnessId: _harnessId),
+ );
Navigator.of(context).pop(NewAgentDialogResult.created);
}
@@ -699,7 +794,11 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
},
};
- void _toggleAdvanced() => setState(() => _advancedOpen = !_advancedOpen);
+ void _toggleAdvanced() {
+ _advancedTouched = true;
+ setState(() => _advancedOpen = !_advancedOpen);
+ unawaited(widget.notifier.agentPreference.setAdvanced(_advancedOpen));
+ }
NewHarnessDraft get _draft {
final folder =
@@ -708,6 +807,9 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
return NewHarnessDraft(
machineId: _machineId,
engine: _engine,
+ harnessId: _harnessId,
+ model: _engineIsTerminal ? null : widget.initialDraft?.model,
+ advancedOpen: _advancedOpen,
project: folder != null
? NewHarnessProject.folder(folder)
: _folderSource == _FolderSource.remote && _repository != null
@@ -885,7 +987,7 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
child: DshInstallPanel(
key: const Key('new-agent-install-status'),
run: _installRun!,
- harnessName: _labelOf(_engine),
+ harnessName: _labelOf(_harnessId ?? _engine),
machineName: _machineName,
),
),
@@ -1004,7 +1106,7 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
_preparedFolder == null
? 'Cloning and starting…'
: _installing
- ? 'Installing ${_labelOf(_engine)}…'
+ ? 'Installing ${_labelOf(_harnessId ?? _engine)}…'
: _engineIsTerminal
? 'Opening terminal…'
: 'Starting harness…',
@@ -1142,40 +1244,30 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
- // The section's line, like Machine's and Project's but with no help
- // link (owner, 2026-09-17), and the search box under it naming the
- // chosen agent.
_sectionHeader(
- 'Agent',
- 'Choose who you’ll work with.',
+ 'Harness',
+ 'Choose the workspace and tools.',
null,
compactHeight: compactHeight,
),
AgentPicker(
+ key: const Key('new-agent-harness-picker'),
+ label: 'Harness',
terminalStyle: true,
- key: const Key('new-agent-agent-picker'),
- focusNode: _agentSearchFocus,
- // A tile's height, so the bar is in proportion with the rows of
- // tiles under it.
height: tileSize.height,
width: constraints.maxWidth,
- value: _engine,
- recent: () => _recentAgents,
- installed: _installedIds,
+ focusNode: _harnessSearchFocus,
+ value: _harnessId ?? NewHarnessController.codingId,
+ recent: () => widget.notifier.agentPreference.recentHarnesses,
+ installed: {..._installedIds, NewHarnessController.codingId},
statusOf: _agentStatus,
choices: [
- for (final identity in allEngines)
- AgentChoice(
- id: identity.id,
- label: _labelOf(identity.id),
- detail: identity.tagline ?? identity.category,
- creator: identity.creator,
- keywords: identity.category,
- description: identity.blurb,
- mark: (size) => EngineMark(engine: identity.id, size: size),
- ),
- // The domain harnesses, after the engines they run on. What the
- // machine named when it has answered, else this build's own.
+ AgentChoice(
+ id: NewHarnessController.codingId,
+ label: 'Coding',
+ detail: 'Work in any code project',
+ mark: (size) => Icon(LucideIcons.code, size: size),
+ ),
for (final harness in _harnessOptions)
AgentChoice(
id: _harness(harness.id)?.id ?? harness.id,
@@ -1201,27 +1293,75 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
size: size,
),
),
+ ],
+ onChanged: _chooseHarness,
+ ),
+ TextButton(
+ onPressed: _choicesLocked
+ ? null
+ : () {
+ Navigator.of(context).pop();
+ widget.notifier.openStore();
+ },
+ child: const Text('Browse Harness Store…'),
+ ),
+ SizedBox(height: sectionGap),
+ // The section's line, like Machine's and Project's but with no help
+ // link (owner, 2026-09-17), and the search box under it naming the
+ // chosen agent.
+ _sectionHeader(
+ 'Agent',
+ 'Choose who you’ll work with.',
+ null,
+ compactHeight: compactHeight,
+ ),
+ AgentPicker(
+ terminalStyle: true,
+ key: const Key('new-agent-agent-picker'),
+ focusNode: _agentSearchFocus,
+ // A tile's height, so the bar is in proportion with the rows of
+ // tiles under it.
+ height: tileSize.height,
+ width: constraints.maxWidth,
+ value: _engine,
+ recent: () => _recentAgents,
+ installed: _installedIds,
+ statusOf: _agentStatus,
+ choices: [
+ for (final identity in allEngines)
+ if (_compatibleEngines.contains(identity.id))
+ AgentChoice(
+ id: identity.id,
+ label: _labelOf(identity.id),
+ detail: identity.tagline ?? identity.category,
+ creator: identity.creator,
+ keywords: identity.category,
+ description: identity.blurb,
+ mark: (size) => EngineMark(engine: identity.id, size: size),
+ ),
// After every agent: a plain shell, for when none of them is
// wanted — the same tile ⌘⇧T opens, from here with a machine
// and a folder chosen. Every machine has one, so the search
// lists it with what the machine has (_installedIds).
- AgentChoice(
- id: kTerminalEngine,
- label: terminalIdentity.label,
- detail: terminalIdentity.tagline,
- keywords: '${terminalIdentity.category} shell bash zsh',
- description: terminalIdentity.blurb,
- mark: (size) => EngineMark(engine: kTerminalEngine, size: size),
- ),
+ if (_harnessId == null)
+ AgentChoice(
+ id: kTerminalEngine,
+ label: terminalIdentity.label,
+ detail: terminalIdentity.tagline,
+ keywords: '${terminalIdentity.category} shell bash zsh',
+ description: terminalIdentity.blurb,
+ mark: (size) =>
+ EngineMark(engine: kTerminalEngine, size: size),
+ ),
],
onChanged: (value) {
if (_choicesLocked) return;
setState(() {
- unawaited(widget.notifier.agentPreference.select(value));
_engineChosenByUser = true;
+ _selectionTouched = true;
if (_engine != value) {
_engine = value;
- if (_generatedProject != null) {
+ if (_generatedProject != null && _harnessId == null) {
_generatedProject = ProjectFolderRequest.generated(
label:
widget.notifier
@@ -1250,7 +1390,6 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
// false, see _submit), so coming back to Claude Code finds it as it was left.
_error = null;
});
- if (isHarnessId(value)) unawaited(_probeHarnesses());
},
),
if (!_confirmationPending && _engineCheckFailed) ...[
@@ -1275,6 +1414,16 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
),
],
SizedBox(height: sectionGap),
+ if (widget.initialDraft?.model case final model?
+ when !_engineIsTerminal) ...[
+ _sectionHeader(
+ 'Model',
+ [model.id, if (model.node.isNotEmpty) model.node].join(' · '),
+ null,
+ compactHeight: compactHeight,
+ ),
+ const SizedBox(height: sectionGap),
+ ],
_sectionHeader(
'Machine',
'Where would you like your agent to run?',
@@ -1490,13 +1639,14 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
minimumSize: const Size(28, 28),
padding: const EdgeInsets.all(6),
),
- child: Text(_advancedOpen ? '[-] options' : '[+] options'),
+ child: Text(_advancedOpen ? '[-] Advanced' : '[+] Advanced'),
),
),
if (permissionModesOf(_baseEngine(_engine)) case final modes
when modes.isNotEmpty)
_setting(_permissionModeField(modes)),
- if (_baseEngine(_engine) == 'codex') _setting(_profileOptions()),
+ if (_baseEngine(_engine) == 'codex' && widget.initialDraft?.model == null)
+ _setting(_profileOptions()),
],
);
@@ -1621,6 +1771,7 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
setState(() {
_machineRevision++;
_engineChosenByUser = true;
+ _selectionTouched = true;
_machineId = id;
_folder = null;
_repository = null;
@@ -1648,7 +1799,7 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
?widget.notifier.stateOf(_machineId),
...widget.notifier.machineStates.values,
])
- for (final agent in machine.agents.reversed) ?(agent.dsh ?? agent.engine),
+ for (final agent in machine.agents.reversed) ?agent.engine,
];
/// A line for the agent search's preview: is [id] on the chosen machine, or
diff --git a/desktop/lib/widgets/new_harness_form.dart b/desktop/lib/widgets/new_harness_form.dart
index 24b2eeea9..62fca8a08 100644
--- a/desktop/lib/widgets/new_harness_form.dart
+++ b/desktop/lib/widgets/new_harness_form.dart
@@ -6,13 +6,13 @@ import 'package:lucide_icons_flutter/lucide_icons.dart';
import '../shortcuts/app_keymap.dart';
import '../shortcuts/keymap.dart';
+import '../shortcuts/keymap_commands.dart' show describeKeyBinding;
import '../shared/theme/app_theme.dart' as grid;
import '../terminal/terminal_text.dart';
import '../terminal/terminal_theme.dart';
import '../terminal/terminal_theme_store.dart';
import '../state/new_harness.dart';
import 'box_chrome.dart';
-import 'engine_identity.dart';
/// Every answer a new harness needs, on one screen, changed where it stands.
///
@@ -45,13 +45,17 @@ class NewHarnessForm extends StatefulWidget {
State<NewHarnessForm> createState() => _NewHarnessFormState();
}
-/// The items, in the order they are read. Project leads because it is what
-/// changes most; everything under it is usually already right.
+/// Core launch choices stay visible; less common settings expand in place.
enum _Row {
- project,
+ harness,
agent,
+ model,
machine,
+ project,
+ // Branch belongs to Project — which line of it to start from — so it sits
+ // under it rather than behind Advanced.
branch,
+ advanced,
worktree,
approvals,
profile,
@@ -63,13 +67,22 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
final _focus = FocusNode(debugLabel: 'new-harness-form');
final _inputFocus = FocusNode(debugLabel: 'new-harness-query');
final _queryText = TextEditingController();
- _Row _row = _Row.project;
+ final _fieldsScroll = ScrollController();
+ final _choicesScroll = ScrollController();
+ _Row _row = _Row.harness;
final _itemKeys = {for (final row in _Row.values) row: GlobalKey()};
final _choiceKey = GlobalKey();
+ static const _advancedRows = {
+ _Row.worktree,
+ _Row.approvals,
+ _Row.profile,
+ };
List<_Row> get _rows => [
for (final row in _Row.values)
- if (row != _Row.profile || box.usesProfile) row,
+ if ((!_advancedRows.contains(row) || box.advancedOpen) &&
+ (row != _Row.profile || box.usesProfile))
+ row,
];
/// Whether the focused field's choices own the keyboard. Wide windows also
@@ -96,6 +109,8 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
terminalThemeStore.removeListener(_onBox);
_inputFocus.dispose();
_queryText.dispose();
+ _fieldsScroll.dispose();
+ _choicesScroll.dispose();
_focus.dispose();
super.dispose();
}
@@ -112,7 +127,9 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
if (_observedField != box.field) {
_observedField = box.field;
final next = switch (box.field) {
+ NewHarnessField.harness => _Row.harness,
NewHarnessField.agent => _Row.agent,
+ NewHarnessField.model => _Row.model,
NewHarnessField.machine => _Row.machine,
NewHarnessField.branch => _Row.branch,
NewHarnessField.mode => _Row.approvals,
@@ -124,12 +141,16 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
NewHarnessField.launch => _Row.start,
_ => _row,
};
+ if (_advancedRows.contains(next) && !box.advancedOpen) {
+ box.toggleAdvanced();
+ }
if (next != _row) {
_row = next;
_listOpen = false;
_takeWheel();
}
}
+ if (_row == _Row.model && !_picking) _takeWheel();
setState(() {});
_revealRow();
}
@@ -150,17 +171,19 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
};
NewHarnessField? _fieldOf(_Row row) => switch (row) {
+ _Row.harness => NewHarnessField.harness,
_Row.project =>
_projectFields.contains(box.field)
? box.field
: NewHarnessField.projectMenu,
_Row.agent => NewHarnessField.agent,
+ _Row.model => NewHarnessField.model,
_Row.machine => NewHarnessField.machine,
_Row.branch => NewHarnessField.branch,
_Row.worktree => null,
_Row.approvals => NewHarnessField.mode,
_Row.profile => NewHarnessField.profile,
- _Row.start => null,
+ _Row.advanced || _Row.start => null,
};
/// Why a row cannot be changed, in the words the row will wear.
@@ -171,10 +194,13 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
_Row.worktree when box.gitError != null => box.gitError,
_Row.worktree when !box.canUseWorktree => 'Not a Git repository',
_Row.approvals when !box.hasModes => 'Not used by this agent',
+ _Row.model when box.isTerminal => 'Not used by Terminal',
_ => null,
};
String _label(_Row row) => switch (row) {
+ _Row.harness => 'Harness',
+ _Row.advanced => 'Advanced',
_Row.project => switch (box.field) {
NewHarnessField.projectName => 'New Project',
NewHarnessField.projectRepository => 'Repository',
@@ -182,6 +208,7 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
_ => 'Project',
},
_Row.agent => 'Agent',
+ _Row.model => 'Model',
_Row.machine => 'Machine',
_Row.branch => 'Branch',
_Row.worktree => 'Worktree',
@@ -195,8 +222,11 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
String _value(_Row row) => _valueOf(row);
String _valueOf(_Row row) => switch (row) {
+ _Row.harness => box.harnessLabel,
+ _Row.advanced => box.advancedOpen ? 'Hide settings' : 'Show settings',
_Row.project => box.projectLabel,
_Row.agent => box.agentLabel,
+ _Row.model => box.modelLabel,
_Row.machine => box.machineLabel,
_Row.branch => box.branchRowLabel,
_Row.worktree => box.worktree ? 'Yes' : 'No',
@@ -268,6 +298,10 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
void _stepValue(int delta) {
if (box.locked || _blocked(_row) != null) return;
+ if (_row == _Row.advanced) {
+ _toggleAdvanced();
+ return;
+ }
if (_row == _Row.worktree) {
setState(box.toggleWorktree);
return;
@@ -379,6 +413,8 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
NewHarnessController.linkProfileId,
NewHarnessController.refreshProfilesId,
NewHarnessController.storeId,
+ NewHarnessController.manageModelsId,
+ NewHarnessController.refreshModelsId,
};
bool _isDoor(NewHarnessOption option) => _doors.contains(option.id);
@@ -387,6 +423,14 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
void _openDoor(NewHarnessOption option) {
if (box.locked || !option.enabled) return;
box.setQuery('');
+ if (option.id == NewHarnessController.manageModelsId) {
+ unawaited(box.app.runLocalModel(context));
+ return;
+ }
+ if (option.id == NewHarnessController.refreshModelsId) {
+ unawaited(box.refreshModels());
+ return;
+ }
if (option.id == NewHarnessController.storeId) {
widget.onStore?.call();
return;
@@ -460,6 +504,73 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
_revealRow();
}
+ /// ⇧⏎ from anywhere: start with what is on screen, instead of walking
+ /// down every field to the button. A value highlighted in a live list is
+ /// taken first — it is what the person was looking at when they pressed
+ /// it — and a door's prompt is finished the way Return finishes it.
+ void _go() {
+ if (box.locked) return;
+ if (_prompts.contains(box.field)) {
+ box.accept();
+ } else if (_picking) {
+ final option = box.selected;
+ if (option != null && option.enabled && !_isDoor(option)) {
+ box.applyOption(option);
+ box.setQuery('');
+ }
+ }
+ setState(() => _listOpen = false);
+ unawaited(_start());
+ }
+
+ void _confirm() {
+ // Return chooses a value in the list; only the start row launches.
+ if (_picking) {
+ final option = box.selected;
+ if (option != null) {
+ _acceptChoice(option);
+ } else if (_prompts.contains(box.field)) {
+ box.accept();
+ } else {
+ box.warn('No values match this search.');
+ }
+ } else if (_row == _Row.advanced) {
+ _toggleAdvanced();
+ } else if (_row == _Row.worktree && _blocked(_row) == null) {
+ setState(box.toggleWorktree);
+ } else if (_row != _Row.start) {
+ // Return opens the row's choices. It never starts an agent from a
+ // value row — only the button does that.
+ if (_blocked(_row) == null) setState(() => _listOpen = true);
+ } else {
+ unawaited(_start());
+ }
+ }
+
+ void _cancel() {
+ // A filter first, the screen second: Escape gives back the typed
+ // text before it closes anything, as vim's wildmenu does.
+ if (box.query.isNotEmpty) {
+ _onTyped('');
+ } else if (_prompts.contains(box.field)) {
+ setState(() {
+ _listOpen = false;
+ box.focusField(NewHarnessField.projectMenu);
+ });
+ } else if (_listOpen) {
+ setState(() => _listOpen = false);
+ } else {
+ if (box.requestDismiss()) widget.onClose();
+ }
+ }
+
+ void _runCommand(VoidCallback action) {
+ if (_isComposing()) return;
+ action();
+ _focusEditor();
+ _revealRow();
+ }
+
KeyEventResult _onKey(FocusNode node, KeyEvent event) {
if (event is! KeyDownEvent && event is! KeyRepeatEvent) {
return KeyEventResult.ignored;
@@ -524,48 +635,14 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
if (!_picking) _stepValue(-1);
case LogicalKeyboardKey.enter:
case LogicalKeyboardKey.numpadEnter:
- // Return chooses a value in the list; only the start row launches.
- if (_picking) {
- final option = box.selected;
- if (option != null) {
- _acceptChoice(option);
- } else if (_prompts.contains(box.field)) {
- box.accept();
- } else {
- box.warn('No values match this search.');
- }
- } else if (box.field == NewHarnessField.projectName ||
- box.field == NewHarnessField.projectRepository) {
- // A door's own prompt: Return finishes it rather than walking off.
- box.accept();
- } else if (_row == _Row.worktree && _blocked(_row) == null) {
- setState(box.toggleWorktree);
- } else if (_row != _Row.start) {
- // Return opens the row's choices. It never starts an agent from a
- // value row — only the button does that.
- if (_blocked(_row) == null) setState(() => _listOpen = true);
- } else if (box.query.isNotEmpty && box.matchCount == 0) {
- // Return is never silent: nothing matched, so say so rather than
- // starting with a value the search did not choose.
- box.warn('Nothing matches "${box.query}".');
- } else {
- unawaited(_start());
+ // ⇧⏎ is `picker.start`, a keymap command so it can be remapped: let
+ // it past, to the region that dispatches it.
+ if (HardwareKeyboard.instance.isShiftPressed) {
+ return KeyEventResult.ignored;
}
+ _confirm();
case LogicalKeyboardKey.escape:
- // A filter first, the screen second: Escape gives back the typed
- // text before it closes anything, as vim's wildmenu does.
- if (box.query.isNotEmpty) {
- _onTyped('');
- } else if (_prompts.contains(box.field)) {
- setState(() {
- _listOpen = false;
- box.focusField(NewHarnessField.projectMenu);
- });
- } else if (_listOpen) {
- setState(() => _listOpen = false);
- } else {
- if (box.requestDismiss()) widget.onClose();
- }
+ _cancel();
case LogicalKeyboardKey.backspace:
if (_inputFocus.hasFocus) return KeyEventResult.ignored;
final query = box.query;
@@ -611,13 +688,72 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
// Only the column that owns the keys carries Open Harness's full highlight.
Color get _activeFill => Colors.white.withValues(alpha: .12);
+
+ /// A machine that cannot be picked — unlinked or offline — in dark grey,
+ /// darker than the faint of an idle list, so it recedes rather than warns.
+ Color get _unavailableInk => Colors.white.withValues(alpha: .28);
+
Color get _idleFill => Colors.white.withValues(alpha: .04);
/// One face, one size, everywhere on this screen — and it is the
/// TERMINAL's size, the one ⌘+ and ⌘− set, not the UI's fixed 13pt. A box
/// that stays small beside a zoomed terminal reads as another application.
+ ///
+ /// Its line height IS the row, so every line of every text on this form —
+ /// wrapped ones included — lands on the grid by itself. A two-line notice
+ /// is exactly two rows; nothing needs a box around it to stay in step.
TextStyle _ink([Color? color]) =>
- terminalContentStyle(color: color ?? Colors.white);
+ terminalContentStyle(color: color ?? Colors.white).copyWith(
+ height: _rowHeight / _font,
+ leadingDistribution: TextLeadingDistribution.even,
+ );
+
+ /// THE GRID. A terminal has two units and positions nothing in pixels:
+ ///
+ /// * [_cell] — one character wide, in the terminal's own face and size.
+ /// * [_rowHeight] — one row tall; a field, a name, a description line and
+ /// the gap between entries are each exactly one.
+ ///
+ /// Every margin, column and gap on this form is a whole number of one of
+ /// them. Per-widget pixel padding is what gave each pane three left edges
+ /// and let the two columns drift apart; a grid cannot drift.
+ ///
+ /// Both are measured through the text scaler, because that is what the
+ /// glyphs are drawn at.
+ double _font = 13;
+ double _cell = 8;
+ double _rowHeight = 20;
+
+ void _measureGrid(BuildContext context) {
+ final scaler = MediaQuery.textScalerOf(context);
+ _font = scaler.scale(terminalFontStore.size);
+ _rowHeight = (_font * 1.6).roundToDouble();
+ final painter = TextPainter(
+ text: TextSpan(text: '0000000000', style: terminalContentStyle()),
+ textDirection: TextDirection.ltr,
+ textScaler: scaler,
+ )..layout();
+ _cell = painter.width / 10;
+ painter.dispose();
+ }
+
+ /// Where each pane's rows sit: one cell in from the pane's edge, so the
+ /// selection bar has a column of air on either side.
+ double get _margin => _cell;
+
+ /// The fzf pointer column on the right: `>`, and the action glyphs, live
+ /// in these two cells, and every name, heading and notice starts after it.
+ double get _gutter => _cell * 2;
+
+ /// A field's label is padded to this many cells, as `ls -l` pads a column,
+ /// so every value on the left starts on the same column.
+ static const _labelCells = 12;
+
+ /// One row, with its content sitting on the line.
+ Widget _oneRow(Widget child) => SizedBox(
+ height: _rowHeight,
+ child: Align(alignment: Alignment.centerLeft, child: child),
+ );
/// Geometry follows the same size, so the columns keep their proportions.
double _scale = 1;
@@ -631,12 +767,24 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
_scale = scale;
_revealRow();
}
+ _measureGrid(context);
return KeymapRegion(
contextKind: KeymapContext.picker,
composing: _isComposing,
actions: {
+ 'picker.accept': () => _runCommand(_confirm),
+ 'picker.start': () => _runCommand(_go),
+ 'picker.cancel': () => _runCommand(_cancel),
+ 'picker.next': () =>
+ _runCommand(() => _picking ? _stepMatch(1) : _moveRow(1)),
+ 'picker.previous': () =>
+ _runCommand(() => _picking ? _stepMatch(-1) : _moveRow(-1)),
+ 'picker.complete': () =>
+ _runCommand(() => _picking ? _stepMatch(1) : _moveRow(1)),
+ 'picker.complete_back': () =>
+ _runCommand(() => _picking ? _stepMatch(-1) : _moveRow(-1)),
'picker.more_options': () {
- if (!box.locked && !box.checkingGit) widget.onNeedsForm?.call();
+ if (!box.locked) _toggleAdvanced();
},
},
child: Focus(
@@ -662,7 +810,12 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
if (!_picking &&
(box.error != null || box.status != null))
Padding(
- padding: const EdgeInsets.all(24),
+ padding: EdgeInsets.fromLTRB(
+ _margin * 2,
+ 0,
+ _margin * 2,
+ _rowHeight,
+ ),
child: _status(),
),
],
@@ -685,51 +838,94 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
}
Widget _items() => Padding(
- padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 16),
- child: SingleChildScrollView(
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- for (final row in _rows)
- if (row == _Row.start) _buildButton() else _buildRow(row),
- ],
- ),
+ padding: EdgeInsets.fromLTRB(_margin, _rowHeight, _margin, _rowHeight),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Expanded(
+ child: Scrollbar(
+ controller: _fieldsScroll,
+ thumbVisibility: true,
+ child: SingleChildScrollView(
+ controller: _fieldsScroll,
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ for (final row in _rows.where(
+ (row) => row != _Row.start,
+ )) ...[
+ // Blank rows group the fields: what runs, where it
+ // runs, then the settings most people never open.
+ if (row == _Row.machine || row == _Row.advanced)
+ SizedBox(height: _rowHeight),
+ _buildRow(row),
+ ],
+ ],
+ ),
+ ),
+ ),
+ ),
+ _buildButton(),
+ ],
),
);
- /// The only action that starts an agent, distinct from the editable fields.
+ /// The only action that starts an agent, and the one thing on this form
+ /// that is not a value. A terminal has no buttons, only text in cells, so
+ /// it is drawn the way BIOS draws `[Yes]`: bracketed, on the label column,
+ /// one row tall — with the key that reaches it from anywhere printed
+ /// beside it, so nobody has to walk down every field to find it.
Widget _buildButton() {
final on = _row == _Row.start && !_picking;
+ final label = box.checking ? 'Check status' : 'New Harness';
return Semantics(
key: const ValueKey('new-harness-field-start'),
+ container: true,
button: true,
+ // The brackets and the key are how it LOOKS; a screen reader says
+ // what it is.
+ label: label,
+ excludeSemantics: true,
selected: on,
enabled: !box.busy && !box.linkingProfile,
onTap: !box.busy && !box.linkingProfile ? _start : null,
child: Padding(
key: _itemKeys[_Row.start],
- padding: const EdgeInsets.only(top: 24),
+ // One blank row between the last field and the action.
+ padding: EdgeInsets.only(top: _rowHeight),
child: GestureDetector(
behavior: HitTestBehavior.opaque,
excludeFromSemantics: true,
onTap: !box.busy && !box.linkingProfile ? _start : null,
child: Container(
color: on ? _activeFill : Colors.transparent,
- padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
+ padding: EdgeInsets.symmetric(horizontal: _margin),
+ height: _rowHeight,
+ alignment: Alignment.centerLeft,
+ // In a narrow pane at large text the key hint gives way first,
+ // clipped like a terminal line, so the label is never what is cut.
child: Row(
children: [
- Icon(
- box.checking ? LucideIcons.refreshCw300 : LucideIcons.plus300,
- size: terminalFontStore.size * 1.25,
- color: grid.AppPalette.swarmAccent,
- ),
- const SizedBox(width: 12),
- Expanded(
+ Flexible(
+ flex: 4,
child: Text(
- box.checking ? 'Check status' : 'New Harness',
+ '[ $label ]',
+ maxLines: 1,
+ softWrap: false,
+ overflow: TextOverflow.clip,
style: _ink(grid.AppPalette.swarmAccent),
),
),
+ SizedBox(width: _cell * 2),
+ Flexible(
+ child: Text(
+ _startKeyLabel,
+ maxLines: 1,
+ softWrap: false,
+ overflow: TextOverflow.clip,
+ style: _ink(kBoxFaint),
+ ),
+ ),
],
),
),
@@ -738,6 +934,20 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
);
}
+ /// The start key as the keymap has it bound — a remap shows the new key.
+ String get _startKeyLabel {
+ final binding = KeymapTheme.of(context)
+ ?.bindings('picker.start', context: KeymapContext.picker)
+ .firstOrNull;
+ // A space after each modifier — `⇧ ⏎`, not `⇧⏎` — so the glyphs read as
+ // separate keys at terminal size rather than as one symbol.
+ final keys = binding == null ? '⇧⏎' : describeKeyBinding(binding);
+ return keys
+ .replaceAllMapped(RegExp('([⌘⌥⌃⇧])'), (m) => '${m[1]} ')
+ .replaceAll(RegExp(' +'), ' ')
+ .trim();
+ }
+
/// Wide windows preview choices beside the fields. Narrow windows give the
/// active list the full width, with Escape returning to the same field.
Widget _sidePane({bool compact = false}) => Semantics(
@@ -746,45 +956,58 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
focused: _picking,
label: '${_label(_row)} choices',
child: Padding(
- padding: const EdgeInsets.all(24),
+ padding: EdgeInsets.fromLTRB(_margin, _rowHeight, _margin, _rowHeight),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (compact)
Padding(
- padding: const EdgeInsets.only(bottom: 16),
+ // The back row, then one blank row.
+ padding: EdgeInsets.only(bottom: _rowHeight),
child: InkWell(
canRequestFocus: false,
onTap: _backToRows,
- child: Row(
- children: [
- Icon(
- LucideIcons.chevronLeft300,
- size: terminalFontStore.size,
- color: kBoxFaint,
- ),
- const SizedBox(width: 8),
- Text(_label(_row), style: _ink(kBoxFaint)),
- ],
+ child: Padding(
+ padding: EdgeInsets.symmetric(horizontal: _margin),
+ child: Row(
+ children: [
+ _inGutter(
+ Icon(
+ LucideIcons.chevronLeft300,
+ size: _font,
+ color: kBoxFaint,
+ ),
+ ),
+ Text(_label(_row), style: _ink(kBoxFaint)),
+ ],
+ ),
),
),
),
if (_hasChoices) ...[
_searchBar(),
if (box.choicesStatus case final status?)
- Padding(
- padding: const EdgeInsets.only(top: 12),
- child: Semantics(
+ _atTextColumn(
+ Semantics(
liveRegion: true,
child: Text(status, style: _ink(kBoxFaint)),
),
),
- const SizedBox(height: 24),
- Flexible(child: SingleChildScrollView(child: _matchPane())),
+ SizedBox(height: _rowHeight),
+ Flexible(
+ child: Scrollbar(
+ controller: _choicesScroll,
+ thumbVisibility: true,
+ child: SingleChildScrollView(
+ controller: _choicesScroll,
+ child: _matchPane(),
+ ),
+ ),
+ ),
],
if (box.error != null || box.status != null) ...[
- const SizedBox(height: 24),
- _status(),
+ SizedBox(height: _rowHeight),
+ _atTextColumn(_status()),
],
],
),
@@ -811,26 +1034,55 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
/// fourth row, so the doors are visible without being in the way.
Widget _matchPane() {
final shown = box.options;
+ // At most ONE blank row before an entry, whatever asks for it: a new
+ // heading, the end of a two-row entry, or the doors giving way to the
+ // projects. Adding each reason's own gap is how two blanks appeared.
+ bool blankBefore(int i) {
+ if (i == 0) return false;
+ final heading =
+ shown[i].group != null && shown[i].group != shown[i - 1].group;
+ return heading ||
+ _showsDetail(shown[i - 1]) ||
+ (shown[i - 1].synthetic && !shown[i].synthetic);
+ }
+
return Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
+ if (_row == _Row.model && box.modelNotice != null) ...[
+ _atTextColumn(Text(box.modelNotice!, style: _ink(kBoxFaint))),
+ SizedBox(height: _rowHeight),
+ ],
if (shown.isEmpty &&
!_prompts.contains(box.field) &&
!box.refreshingChoices)
- Text('No matches', style: _ink(kBoxFaint)),
+ _atTextColumn(Text('No matches', style: _ink(kBoxFaint))),
for (var i = 0; i < shown.length; i++) ...[
+ if (blankBefore(i)) SizedBox(height: _rowHeight),
+ if (shown[i].group != null &&
+ (i == 0 || shown[i].group != shown[i - 1].group))
+ _atTextColumn(Text(shown[i].group!, style: _ink(kBoxFaint))),
_matchRow(shown[i]),
- // One gap where the doors end and the projects begin.
- if (shown[i].synthetic &&
- i + 1 < shown.length &&
- !shown[i + 1].synthetic)
- const SizedBox(height: 8),
],
],
);
}
+ /// A line that is not a choice — a heading, a notice, a status — starts on
+ /// the same column as the names below it, so each pane has one left edge.
+ Widget _atTextColumn(Widget child) => Padding(
+ padding: EdgeInsets.only(left: _margin + _gutter, right: _margin),
+ child: child,
+ );
+
+ /// The pointer column's two cells, holding a glyph centred in them, so the
+ /// prompt's `>` and every row's icon share one x.
+ Widget _inGutter(Widget? child) => SizedBox(
+ width: _gutter,
+ child: child == null ? null : Center(child: child),
+ );
+
/// A prompt people can see, because "type to search" printed in a key
/// guide is a sentence nobody reads. fzf's `>` rather than a labelled box:
/// there is no second place for the caret to be, so it needs no border.
@@ -843,13 +1095,13 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
Widget _searchBar() {
return Padding(
- padding: const EdgeInsets.symmetric(horizontal: 12),
+ padding: EdgeInsets.symmetric(horizontal: _margin),
child: Row(
crossAxisAlignment: CrossAxisAlignment.baseline,
textBaseline: TextBaseline.alphabetic,
children: [
SizedBox(
- width: terminalFontStore.size * 1.25,
+ width: _gutter,
child: Text(
'>',
key: const ValueKey('new-harness-prompt'),
@@ -857,7 +1109,6 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
style: _ink(_picking ? Colors.white : kBoxFaint),
),
),
- const SizedBox(width: 12),
Expanded(
child: Actions(
actions: {
@@ -876,7 +1127,8 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
showCursor: _picking,
style: _ink(Colors.white),
cursorColor: Colors.white70,
- cursorWidth: terminalFontStore.size * .62,
+ // A block caret, one cell wide, as a terminal draws it.
+ cursorWidth: _cell,
cursorRadius: Radius.zero,
cursorOpacityAnimates: false,
autocorrect: false,
@@ -888,7 +1140,7 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
},
onTapOutside: (_) {},
decoration: InputDecoration(
- hintText: '${_picking ? ' ' : ''}$_promptHint',
+ hintText: _promptHint,
hintStyle: _ink(kBoxFaint),
hintMaxLines: 1,
isDense: true,
@@ -904,15 +1156,19 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
),
),
if (box.canRefreshChoices)
+ // Held to two cells by one row: a Material button's 48px tap
+ // target would make the prompt taller than every other line.
IconButton(
key: const ValueKey('new-harness-refresh'),
tooltip: 'Refresh results',
onPressed: box.refreshingChoices ? null : box.refreshChoices,
- icon: Icon(
- LucideIcons.refreshCw300,
- size: terminalFontStore.size,
- color: kBoxFaint,
+ padding: EdgeInsets.zero,
+ constraints: BoxConstraints.tightFor(
+ width: _gutter,
+ height: _rowHeight,
),
+ iconSize: _font,
+ icon: Icon(LucideIcons.refreshCw300, color: kBoxFaint),
),
],
),
@@ -929,33 +1185,45 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
String? _machineNote(String machineId) {
final machine = box.app.stateOf(machineId);
if (machine == null) return null;
- if (machine.needsLink) return 'Link required';
+ // Not linked: said by colour, not a word (see [_unlinked]).
+ if (machine.needsLink) return null;
if (machine.isOffline) return 'Offline';
return machine.isLocalMachine ? 'This machine' : null;
}
+ /// Whether a choice carries a description under its name.
+ bool _showsDetail(NewHarnessOption option) =>
+ (_row == _Row.harness ||
+ _row == _Row.agent ||
+ _row == _Row.model ||
+ _row == _Row.profile) &&
+ option.detail.isNotEmpty &&
+ !_isDoor(option);
+
+ /// A machine this computer has not linked yet. On screen it looks like
+ /// any other machine that cannot be picked (see [_unavailableInk]); the
+ /// difference is kept for screen readers, which hear "Link required", and
+ /// an offline machine keeps its printed word.
+ bool _unlinked(NewHarnessOption option) =>
+ box.field == NewHarnessField.machine &&
+ box.app.stateOf(option.id)?.needsLink == true;
+
Widget _matchRow(NewHarnessOption option) {
final on = identical(option, box.selected);
final note = box.field == NewHarnessField.machine
? _machineNote(option.id)
: null;
- final actionIcon = switch (option.id) {
- NewHarnessController.repositoryId => LucideIcons.gitBranch300,
- NewHarnessController.existingProjectId ||
- NewHarnessController.browseId => LucideIcons.folder300,
- NewHarnessController.newProjectId => LucideIcons.plus300,
- _ => null,
- };
- final showDetail =
- (_row == _Row.agent || _row == _Row.profile) &&
- option.detail.isNotEmpty &&
- !_isDoor(option);
+ final showDetail = _showsDetail(option);
+ final unlinked = _unlinked(option);
+ final unavailable = box.field == NewHarnessField.machine && !option.enabled;
final title = Text(
option.title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: _ink(
- !_picking || !option.enabled
+ unavailable
+ ? _unavailableInk
+ : !_picking || !option.enabled
? kBoxFaint
: option.synthetic
? grid.AppPalette.swarmAccent
@@ -966,66 +1234,63 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
);
return Semantics(
key: ValueKey('new-harness-option-${option.id}'),
+ // Colour is not announced, so the word the row no longer prints is
+ // still what a screen reader says.
+ hint: unlinked ? 'Link required' : null,
selected: on,
enabled: option.enabled && !box.locked,
button: _isDoor(option),
child: InkWell(
canRequestFocus: false,
onTap: !box.locked ? () => _acceptChoice(option) : null,
- child: Container(
+ child: Column(
key: on ? _choiceKey : null,
- color: on && _picking ? _activeFill : Colors.transparent,
- padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
- child: Row(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- if (actionIcon != null) ...[
- Icon(
- actionIcon,
- size: terminalFontStore.size * 1.25,
- color: _picking ? grid.AppPalette.swarmAccent : kBoxFaint,
- ),
- const SizedBox(width: 12),
- ] else if (option.engine != null) ...[
- EngineMark(
- engine: option.engine,
- size: terminalFontStore.size * 1.25,
- ),
- const SizedBox(width: 12),
- ],
- Expanded(
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ // The bar covers the NAME, one row, and stops there. Filling the
+ // description with it made the selection two rows tall and the
+ // list read as blocks rather than lines.
+ Container(
+ color: on && _picking ? _activeFill : Colors.transparent,
+ padding: EdgeInsets.symmetric(horizontal: _margin),
+ height: _rowHeight,
+ alignment: Alignment.centerLeft,
+ child: Row(
+ children: [
+ // The pointer column stays, empty, so names keep one edge
+ // with the prompt's text.
+ _inGutter(null),
+ Expanded(child: title),
+ // Main's note says WHY a machine cannot be chosen — offline,
+ // or never linked — which a dimmed row alone cannot.
+ if (note != null) ...[
+ SizedBox(width: _cell * 2),
+ Text(note, style: _ink(kBoxFaint)),
+ ],
+ ],
+ ),
+ ),
+ if (showDetail)
+ Padding(
+ padding: EdgeInsets.symmetric(horizontal: _margin),
+ child: Row(
children: [
- if (note != null)
- Row(
- children: [
- Expanded(child: title),
- const SizedBox(width: 12),
- Text(
- note,
- style: _ink(
- kBoxFaint,
- ).copyWith(fontSize: terminalFontStore.size * .85),
- ),
- ],
- )
- else
- title,
- if (showDetail) ...[
- const SizedBox(height: 4),
- Text(
- option.detail,
- style: _ink(kBoxFaint),
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
+ _inGutter(null),
+ Expanded(
+ child: _oneRow(
+ Text(
+ option.detail,
+ style: _ink(kBoxFaint),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ ),
),
- ],
+ ),
],
),
),
- ],
- ),
+ ],
),
),
);
@@ -1046,7 +1311,9 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
void _activateRow(_Row row) {
_selectRow(row);
- if (row == _Row.worktree) {
+ if (row == _Row.advanced) {
+ _toggleAdvanced();
+ } else if (row == _Row.worktree) {
box.toggleWorktree();
} else {
setState(() => _listOpen = true);
@@ -1055,6 +1322,17 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
_revealRow();
}
+ void _toggleAdvanced() {
+ if (box.locked) return;
+ box.toggleAdvanced();
+ setState(() {
+ _row = _Row.advanced;
+ _listOpen = false;
+ });
+ _focusEditor();
+ _revealRow();
+ }
+
Widget _buildRow(_Row row) {
final highlighted = row == _row;
final blocked = _blocked(row);
@@ -1075,36 +1353,43 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
behavior: HitTestBehavior.opaque,
excludeFromSemantics: true,
onTap: blocked == null && !box.locked ? () => _activateRow(row) : null,
- child: Container(
- key: _itemKeys[row],
- color: highlighted
- ? (_picking ? _idleFill : _activeFill)
- : Colors.transparent,
- padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
- child: LayoutBuilder(
- builder: (context, constraints) {
- final label = Text(_label(row), style: _ink(kBoxFaint));
- final content = Text(
- value,
- style: _ink(ink),
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- );
- if (constraints.maxWidth < 360 * _scale) {
- return Column(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [label, const SizedBox(height: 4), content],
- );
- }
- return Row(
- children: [
- SizedBox(width: 120 * _scale, child: label),
- const SizedBox(width: 16),
- Expanded(child: content),
- ],
- );
- },
- ),
+ // The width decision sits OUTSIDE the box it sizes. A narrow column
+ // stacks the label above its value, which needs two rows of the
+ // grid; measuring that inside a box already pinned to one is how the
+ // row overflowed at large text sizes.
+ child: LayoutBuilder(
+ builder: (context, constraints) {
+ final stacked = constraints.maxWidth < 360 * _scale;
+ final label = Text(_label(row), style: _ink(kBoxFaint));
+ final content = Text(
+ value,
+ style: _ink(ink),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ );
+ return Container(
+ key: _itemKeys[row],
+ color: highlighted
+ ? (_picking ? _idleFill : _activeFill)
+ : Colors.transparent,
+ padding: EdgeInsets.symmetric(horizontal: _margin),
+ height: _rowHeight * (stacked ? 2 : 1),
+ alignment: Alignment.centerLeft,
+ child: stacked
+ ? Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [_oneRow(label), _oneRow(content)],
+ )
+ : Row(
+ children: [
+ SizedBox(width: _cell * _labelCells, child: label),
+ SizedBox(width: _cell * 2),
+ Expanded(child: content),
+ ],
+ ),
+ );
+ },
),
),
);
diff --git a/desktop/test/advanced_agent_keyboard_test.dart b/desktop/test/advanced_agent_keyboard_test.dart
index b086ba774..264dd8966 100644
--- a/desktop/test/advanced_agent_keyboard_test.dart
+++ b/desktop/test/advanced_agent_keyboard_test.dart
@@ -1,3 +1,6 @@
+import 'support/launch_menu.dart';
+
+import 'package:harness/widgets/new_harness_form.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
@@ -108,7 +111,11 @@ void main() {
expect(connection.launches, isEmpty);
expect(agentSearch, findsNothing);
expect(
- tester.widget<AgentPicker>(find.byType(AgentPicker)).value,
+ tester
+ .widget<AgentPicker>(
+ find.byKey(const Key('new-agent-agent-picker')),
+ )
+ .value,
'opencode',
);
expect(find.byType(AlertDialog), findsOneWidget);
@@ -123,7 +130,9 @@ void main() {
if (agentSearch.evaluate().isEmpty) await openAgentSearch(tester);
final editor = tester.widget<TextField>(agentSearch);
final chosen = tester
- .widget<AgentPicker>(find.byType(AgentPicker))
+ .widget<AgentPicker>(
+ find.byKey(const Key('new-agent-agent-picker')),
+ )
.value;
tester.testTextInput.updateEditingValue(
const TextEditingValue(
@@ -140,7 +149,11 @@ void main() {
expect(editor.focusNode!.hasPrimaryFocus, isTrue);
expect(connection.launches, isEmpty);
expect(
- tester.widget<AgentPicker>(find.byType(AgentPicker)).value,
+ tester
+ .widget<AgentPicker>(
+ find.byKey(const Key('new-agent-agent-picker')),
+ )
+ .value,
chosen,
);
await tester.pumpWidget(const SizedBox());
@@ -191,7 +204,9 @@ void main() {
expect(agentSearch, findsNothing);
expect(connection.launches, isEmpty);
expect(
- tester.widget<AgentPicker>(find.byType(AgentPicker)).value,
+ tester
+ .widget<AgentPicker>(find.byKey(const Key('new-agent-agent-picker')))
+ .value,
'opencode',
);
map.apply('''{"bindings":[
@@ -220,14 +235,18 @@ void main() {
await key(tester, LogicalKeyboardKey.enter);
await key(tester, LogicalKeyboardKey.period, cmd: true);
await tester.pumpAndSettle();
- await openAgentSearch(tester);
- await tester.enterText(agentSearch, 'opencode');
+ await openLaunchRow(tester, 'agent');
+ final input = find.byKey(const ValueKey('new-harness-query'));
+ await tester.enterText(input, 'opencode');
await tester.pump();
// Ctrl-M is a configured picker alias, absent from the fallback shortcuts.
await key(tester, LogicalKeyboardKey.keyM, ctrl: true);
- expect(agentSearch, findsNothing);
+ expect(harnessChoicesActive(tester), isFalse);
expect(
- tester.widget<AgentPicker>(find.byType(AgentPicker)).value,
+ tester
+ .widget<NewHarnessForm>(find.byType(NewHarnessForm))
+ .controller
+ .engine,
'opencode',
);
expect(connection.launches, isEmpty);
diff --git a/desktop/test/agent_events_test.dart b/desktop/test/agent_events_test.dart
index a8f8599ef..acef45d13 100644
--- a/desktop/test/agent_events_test.dart
+++ b/desktop/test/agent_events_test.dart
@@ -66,6 +66,7 @@ class FakeCreateAgentNotifier extends AppNotifier {
String? permissionMode,
String? codexHome,
String? dsh,
+ GridModel? model,
String? prompt,
String? name,
String? agent,
diff --git a/desktop/test/agent_picker_test.dart b/desktop/test/agent_picker_test.dart
index e754f6a24..274c555f4 100644
--- a/desktop/test/agent_picker_test.dart
+++ b/desktop/test/agent_picker_test.dart
@@ -58,6 +58,30 @@ final _choices = [
];
void main() {
+ testWidgets('a missing selection has an accessible search label', (
+ tester,
+ ) async {
+ final semantics = tester.ensureSemantics();
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: AgentPicker(
+ value: 'removed-engine',
+ choices: _choices,
+ onChanged: (_) {},
+ width: 600,
+ ),
+ ),
+ ),
+ );
+ expect(find.bySemanticsLabel(AgentPicker.hint), findsOneWidget);
+ await openAgentSearch(tester);
+ await tester.enterText(agentSearch, 'codex');
+ await tester.pump();
+ expect(agentRows(tester), ['codex']);
+ semantics.dispose();
+ });
+
test(
'remembers the agent across launches without replacing a newer choice',
() async {
@@ -85,7 +109,8 @@ void main() {
for (final id in ['codex', 'autonomous/marp', 'claude', 'codex']) {
await preferences.remember(id);
}
- expect(preferences.recent, ['codex', 'claude', 'autonomous/marp']);
+ expect(preferences.recent, ['codex', 'claude']);
+ expect(preferences.recentHarnesses, ['autonomous/marp']);
final restored = AgentPreference(store);
await restored.remember('hermes');
await restored.load();
@@ -93,7 +118,6 @@ void main() {
'hermes',
'codex',
'claude',
- 'autonomous/marp',
], reason: 'one used while loading stays first; the stored ones follow');
for (var i = 0; i < 20; i++) {
await restored.remember('agent-$i');
diff --git a/desktop/test/first_workspace_test.dart b/desktop/test/first_workspace_test.dart
index 5207a5f34..759dc20ee 100644
--- a/desktop/test/first_workspace_test.dart
+++ b/desktop/test/first_workspace_test.dart
@@ -83,6 +83,7 @@ class _FirstUseApp extends AppNotifier {
String? permissionMode,
String? codexHome,
String? dsh,
+ GridModel? model,
String? prompt,
String? name,
String? agent,
@@ -172,6 +173,11 @@ void main() {
expect(node.hasPrimaryFocus, isTrue);
}
+ await tabTo(
+ Focus.of(tester.element(find.textContaining('[+] Advanced'))),
+ );
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
await tabTo(Focus.of(tester.element(find.text('Workshop machine'))));
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pumpAndSettle();
@@ -206,7 +212,7 @@ void main() {
// its search with that letter in it, and Return takes the first match
// without leaving the keyboard.
final bar = tester
- .widget<AgentPicker>(find.byType(AgentPicker))
+ .widget<AgentPicker>(find.byKey(const Key('new-agent-agent-picker')))
.focusNode!;
await tabTo(bar, back: true);
await tester.sendKeyEvent(LogicalKeyboardKey.keyH, character: 'h');
@@ -219,7 +225,11 @@ void main() {
await tester.pumpAndSettle();
expect(agentSearch, findsNothing, reason: 'a choice closes the search');
expect(
- tester.widget<AgentPicker>(find.byType(AgentPicker)).value,
+ tester
+ .widget<AgentPicker>(
+ find.byKey(const Key('new-agent-agent-picker')),
+ )
+ .value,
'hermes',
);
expect(bar.hasPrimaryFocus, isTrue);
@@ -364,6 +374,7 @@ void main() {
expect(picker.opened, 1);
expect(find.text('my-project'), findsOneWidget);
final localMachine = find.byKey(const ValueKey('new-agent-machine-m'));
+ await expandNewAgentAdvanced(tester);
await tester.ensureVisible(localMachine);
await tester.tap(localMachine);
await tester.pump();
@@ -429,7 +440,11 @@ void main() {
);
expect(find.text('my-project'), findsOneWidget);
expect(
- tester.widget<AgentPicker>(find.byType(AgentPicker)).value,
+ tester
+ .widget<AgentPicker>(
+ find.byKey(const Key('new-agent-agent-picker')),
+ )
+ .value,
'claude',
);
await _browseLocal(tester);
@@ -527,6 +542,7 @@ void main() {
expect(find.byType(AlertDialog), findsOneWidget);
expect(find.text('/work/existing'), findsNothing);
expect(tester.widget<AppChoiceTile>(_newProject).selected, isTrue);
+ await expandNewAgentAdvanced(tester);
final machineField = tester.widget<AppChoicePicker<String>>(
find.byKey(const Key('new-agent-machine-field')),
);
@@ -540,7 +556,11 @@ void main() {
'Remote computer',
]);
expect(
- tester.widget<AgentPicker>(find.byType(AgentPicker)).value,
+ tester
+ .widget<AgentPicker>(
+ find.byKey(const Key('new-agent-agent-picker')),
+ )
+ .value,
'codex',
);
expect(app.panes, [pane]);
@@ -582,10 +602,12 @@ void main() {
await chord(tester, LogicalKeyboardKey.keyN);
await tester.pump();
- // The dialog opens with focus on the agent bar, ready to type.
+ // The dialog opens with focus on the harness bar, ready to type.
expect(
tester
- .widget<AgentPicker>(find.byType(AgentPicker))
+ .widget<AgentPicker>(
+ find.byKey(const Key('new-agent-harness-picker')),
+ )
.focusNode!
.hasPrimaryFocus,
isTrue,
@@ -704,7 +726,9 @@ void main() {
await tester.pump();
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pump();
- final engine = tester.widget<AgentPicker>(find.byType(AgentPicker));
+ final engine = tester.widget<AgentPicker>(
+ find.byKey(const Key('new-agent-agent-picker')),
+ );
expect(engine.value, 'codex');
expect(find.byKey(const Key('new-agent-machine-field')), findsOneWidget);
expect(
@@ -826,7 +850,11 @@ void main() {
await tester.pump();
expect(find.text('chosen'), findsOneWidget);
expect(
- tester.widget<AgentPicker>(find.byType(AgentPicker)).value,
+ tester
+ .widget<AgentPicker>(
+ find.byKey(const Key('new-agent-agent-picker')),
+ )
+ .value,
'codex',
);
expect(app.probes, 1);
@@ -886,7 +914,9 @@ void main() {
await tester.pump();
await tester.pump();
expect(app.probes, 1);
- final engine = tester.widget<AgentPicker>(find.byType(AgentPicker));
+ final engine = tester.widget<AgentPicker>(
+ find.byKey(const Key('new-agent-agent-picker')),
+ );
expect(engine.value, chooseExplicitly ? 'claude' : 'codex');
expect(app.launches, isEmpty);
await tester.pumpWidget(const SizedBox());
diff --git a/desktop/test/harness_agent_selection_test.dart b/desktop/test/harness_agent_selection_test.dart
new file mode 100644
index 000000000..c83f784ce
--- /dev/null
+++ b/desktop/test/harness_agent_selection_test.dart
@@ -0,0 +1,775 @@
+import 'dart:async';
+import 'dart:convert';
+import 'dart:io';
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/agent_preference.dart';
+import 'package:harness/core/dsh_catalog.dart';
+import 'package:harness/core/harness_catalog.dart';
+import 'package:harness/core/project_folder.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/state/new_harness.dart';
+import 'package:harness/widgets/agent_picker.dart';
+import 'package:harness/widgets/engine_identity.dart';
+import 'package:harness/widgets/new_agent_dialog.dart';
+import 'package:harness/widgets/new_harness_form.dart';
+import 'package:harness/ws/ws_conn.dart';
+
+import 'box_render_preview_test.dart' show loadPreviewFonts;
+import 'support/agent_picker.dart';
+import 'support/launch_menu.dart';
+import 'support/mixed_agents.dart';
+import 'swarm_state_test.dart' show MemoryStore, createApp;
+
+class _DelayedPreferences extends MemoryStore {
+ final ready = Completer<void>();
+ @override
+ Future<String?> read(String key) async {
+ await ready.future;
+ return super.read(key);
+ }
+}
+
+Future<void> openDialog(
+ WidgetTester tester,
+ AppNotifier app, {
+ String? engine,
+ ProjectFolderRequest? project,
+ ValueChanged<NewHarnessDraft>? onBack,
+}) async {
+ tester.view.devicePixelRatio = 1;
+ tester.view.physicalSize = const Size(1300, 1100);
+ addTearDown(tester.view.reset);
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Builder(
+ builder: (context) => Scaffold(
+ body: TextButton(
+ onPressed: () => showNewAgentDialog(
+ context,
+ app,
+ 'm',
+ source: 'test',
+ initialEngine: engine,
+ initialFolder: project == null ? '/work/scene' : null,
+ initialProjectFolder: project,
+ onBack: onBack,
+ ),
+ child: const Text('open'),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.tap(find.text('open'));
+ await tester.pumpAndSettle();
+}
+
+String dialogEngine(WidgetTester tester) => tester
+ .widget<AgentPicker>(find.byKey(const Key('new-agent-agent-picker')))
+ .value;
+
+class _Connection extends WsConn {
+ _Connection()
+ : super(
+ wsBaseUrl: 'ws://fixture.invalid',
+ autonomousEnv: 'test',
+ machineId: 'm',
+ accessTokenProvider: (_, _) async => '',
+ onAuthFailure: (_) {},
+ onEvent: (_) {},
+ onStatus: (_) {},
+ );
+ List<String> engines = ['claude', 'codex'];
+ final creates = <Map<String, dynamic>>[];
+ bool installed = true;
+ bool legacyInstall = false;
+ Completer<void>? catalogGate;
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) async {
+ if (type == 'dsh_list') {
+ await catalogGate?.future;
+ return {
+ 'dsh': [
+ {
+ 'id': 'autonomous/blender',
+ 'name': 'Blender',
+ 'engine': 'claude',
+ 'engines': engines,
+ 'installed': installed,
+ },
+ {
+ 'id': 'acme/legacy',
+ 'name': 'Legacy',
+ 'engine': 'claude',
+ 'installed': true,
+ },
+ ],
+ };
+ }
+ if (type == 'dsh_install') {
+ installed = true;
+ if (legacyInstall) {
+ engines = ['claude'];
+ }
+ return {'ok': true, 'id': payload['id']};
+ }
+ if (type == 'engines_probe') return {'engines': []};
+ if (type == 'git_project_info') return {'isGit': false};
+ if (type == 'fs_list_dir') return {'path': '/home/user', 'entries': []};
+ if (type == 'agent_create') {
+ creates.add(Map.of(payload));
+ return {
+ 'creationId': payload['creationId'],
+ 'state': 'created',
+ 'agent': {
+ 'id': 'created',
+ 'name': 'Blender',
+ 'engine': payload['engine'],
+ 'dsh': payload['dsh'],
+ },
+ };
+ }
+ return {};
+ }
+}
+
+void choose(NewHarnessController box, NewHarnessField field, String id) {
+ box.focusField(field);
+ box.accept(box.options.singleWhere((option) => option.id == id));
+}
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+
+ test('malformed preferences preserve a valid legacy engine and discard mixed histories', () async {
+ final store = MemoryStore();
+ store.values['new_agent_engine'] = 'codex';
+ store.values['new_harness_preferences_v1'] = jsonEncode({
+ 'engine': 'autonomous/blender',
+ 'harness': 'codex',
+ 'agents': ['codex', 'autonomous/blender', 7, '', 'codex'],
+ 'harnesses': 'broken',
+ 'enginesByHarness': {
+ 'autonomous/blender': 'autonomous/typst',
+ 'coding': 'claude',
+ 'bad': false,
+ },
+ });
+ final prefs = AgentPreference(store);
+ await prefs.load();
+ expect(prefs.value, 'codex');
+ expect(prefs.harness, isNull);
+ expect(prefs.recent, ['codex']);
+ expect(prefs.recentHarnesses, isEmpty);
+ expect(prefs.engineFor('autonomous/blender'), isNull);
+ expect(prefs.engineFor(null), 'claude');
+ await prefs.select('autonomous/blender');
+ final restored = AgentPreference(store);
+ await restored.load();
+ expect(restored.harness, 'autonomous/blender');
+ expect(restored.value, 'codex');
+ });
+
+ test('harness changes rename only generated projects and reject stale agent options', () async {
+ final connection = _Connection();
+ final app = createApp(connectionForTest: (_) => connection);
+ seedMixedAgents(app);
+ addTearDown(app.dispose);
+ await app.probeDsh('m', force: true);
+ final box = NewHarnessController(
+ app,
+ machineId: 'm',
+ engine: 'codex',
+ autoProject: true,
+ );
+ addTearDown(box.dispose);
+ choose(box, NewHarnessField.harness, 'autonomous/blender');
+ expect(box.project.generated!.name, startsWith('blender-'));
+ box.focusField(NewHarnessField.agent);
+ box.accept(const NewHarnessOption(id: 'terminal', title: 'Terminal'));
+ expect(box.error, contains('compatible with Blender'));
+ expect(box.engine, 'codex');
+ box.toggleAdvanced();
+ box.openLaunchSetting(NewHarnessField.mode);
+ box.setQuery('ask');
+ box.toggleAdvanced();
+ expect(box.field, NewHarnessField.launch);
+ expect(box.query, isEmpty);
+ expect(box.advancedOpen, isFalse);
+ box.setFolder('/work/custom');
+ choose(box, NewHarnessField.harness, NewHarnessController.codingId);
+ expect(box.project.folder, '/work/custom');
+ });
+
+ testWidgets(
+ 'dialog applies a remembered agent when the catalog arrives late',
+ (tester) async {
+ final connection = _Connection()..catalogGate = Completer<void>();
+ final app = createApp(connectionForTest: (_) => connection);
+ seedMixedAgents(app);
+ addTearDown(app.dispose);
+ await app.agentPreference.remember(
+ 'codex',
+ harnessId: 'autonomous/blender',
+ );
+ await openDialog(tester, app, engine: 'autonomous/blender');
+ expect(dialogEngine(tester), 'claude');
+ connection.catalogGate!.complete();
+ await tester.pumpAndSettle();
+ expect(dialogEngine(tester), 'codex');
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ testWidgets(
+ 'dialog restores late preferences and returns the separate selection in its draft',
+ (tester) async {
+ final store = _DelayedPreferences();
+ store.values['new_harness_preferences_v1'] = jsonEncode({
+ 'engine': 'codex',
+ 'harness': 'autonomous/blender',
+ 'agents': ['codex'],
+ 'harnesses': ['autonomous/blender'],
+ 'enginesByHarness': {'autonomous/blender': 'codex'},
+ 'advancedOpen': true,
+ });
+ final connection = _Connection();
+ final app = createApp(store: store, connectionForTest: (_) => connection);
+ seedMixedAgents(app);
+ addTearDown(app.dispose);
+ NewHarnessDraft? draft;
+ await openDialog(tester, app, onBack: (value) => draft = value);
+ store.ready.complete();
+ await tester.pumpAndSettle();
+ expect(dialogEngine(tester), 'codex');
+ expect(
+ tester
+ .widget<AgentPicker>(
+ find.byKey(const Key('new-agent-harness-picker')),
+ )
+ .value,
+ 'autonomous/blender',
+ );
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(draft!.harnessId, 'autonomous/blender');
+ expect(draft!.engine, 'codex');
+ expect(draft!.advancedOpen, isTrue);
+ },
+ );
+
+ testWidgets(
+ 'dialog refuses an engine that becomes incompatible during installation',
+ (tester) async {
+ final connection = _Connection()
+ ..installed = false
+ ..legacyInstall = true;
+ final app = createApp(connectionForTest: (_) => connection);
+ seedMixedAgents(app);
+ addTearDown(app.dispose);
+ await app.probeDsh('m', force: true);
+ await openDialog(tester, app, engine: 'autonomous/blender');
+ await chooseAgent(tester, 'codex');
+ final submit = find.byKey(const ValueKey('create-agent-submit'));
+ await tester.ensureVisible(submit);
+ await tester.tap(submit);
+ await tester.pumpAndSettle();
+ expect(find.textContaining('does not support Codex'), findsOneWidget);
+ expect(dialogEngine(tester), 'codex');
+ expect(connection.creates, isEmpty);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ testWidgets(
+ 'dialog previews Coding and engines, updates generated projects, and opens the Store',
+ (tester) async {
+ final connection = _Connection();
+ final app = createApp(connectionForTest: (_) => connection);
+ seedMixedAgents(app);
+ addTearDown(app.dispose);
+ await app.probeDsh('m', force: true);
+ NewHarnessDraft? draft;
+ await openDialog(
+ tester,
+ app,
+ engine: 'autonomous/blender',
+ project: ProjectFolderRequest.generated(
+ label: 'Blender',
+ at: DateTime(2026),
+ ),
+ onBack: (value) => draft = value,
+ );
+ await chooseHarness(tester, NewHarnessController.codingId);
+ await openHarnessSearch(tester);
+ await tester.enterText(harnessSearch, 'Coding');
+ await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft);
+ await tester.sendKeyEvent(LogicalKeyboardKey.slash);
+ await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft);
+ await tester.pumpAndSettle();
+ expect(
+ find.byKey(const ValueKey('new-agent-harness-preview')),
+ findsOneWidget,
+ );
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ await openAgentSearch(tester);
+ await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft);
+ await tester.sendKeyEvent(LogicalKeyboardKey.slash);
+ await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft);
+ for (final engine in ['codex', 'terminal']) {
+ await tester.enterText(agentSearch, engine);
+ await tester.pumpAndSettle();
+ expect(
+ find.byKey(const ValueKey('new-agent-agent-preview')),
+ findsOneWidget,
+ );
+ }
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ final browse = find.text('Browse Harness Store…');
+ await tester.ensureVisible(browse);
+ await tester.tap(browse);
+ await tester.pumpAndSettle();
+ expect(app.activeSwarm.isStore, isTrue);
+ expect(draft!.harnessId, isNull);
+ expect(draft!.project.generated!.name, startsWith('claude-code-'));
+ },
+ );
+
+ testWidgets(
+ 'picker choices retain the correct visual identity independently of their layout',
+ (tester) async {
+ final connection = _Connection();
+ final app = createApp(connectionForTest: (_) => connection);
+ seedMixedAgents(app);
+ addTearDown(app.dispose);
+ await openDialog(tester, app);
+ final harnesses = tester
+ .widget<AgentPicker>(
+ find.byKey(const Key('new-agent-harness-picker')),
+ )
+ .choices;
+ final agents = tester
+ .widget<AgentPicker>(find.byKey(const Key('new-agent-agent-picker')))
+ .choices;
+ final coding = harnesses.singleWhere(
+ (choice) => choice.id == NewHarnessController.codingId,
+ );
+ final codex = agents.singleWhere((choice) => choice.id == 'codex');
+ final terminal = agents.singleWhere((choice) => choice.id == 'terminal');
+ expect(agents.every((choice) => !choice.id.contains('/')), isTrue);
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Row(
+ children: [coding.mark(28), codex.mark(28), terminal.mark(28)],
+ ),
+ ),
+ );
+ expect(find.byType(Icon), findsWidgets);
+ expect(
+ tester
+ .widgetList<EngineMark>(find.byType(EngineMark))
+ .map((mark) => mark.engine),
+ ['codex', 'terminal'],
+ );
+ },
+ );
+
+ testWidgets(
+ 'inline Advanced settings work by keyboard and by clicking their rows',
+ (tester) async {
+ final app = createApp();
+ seedMixedAgents(app);
+ addTearDown(app.dispose);
+ final box = NewHarnessController(
+ app,
+ machineId: 'm',
+ engine: 'codex',
+ folder: '/work/scene',
+ );
+ addTearDown(box.dispose);
+ tester.view.devicePixelRatio = 1;
+ tester.view.physicalSize = const Size(1100, 800);
+ addTearDown(tester.view.reset);
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: NewHarnessForm(
+ controller: box,
+ onClose: () {},
+ onNeedsForm: () {},
+ onCreated: () {},
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ for (final name in ['mode', 'profile']) {
+ box.focusField(NewHarnessField.launch);
+ await tester.pump();
+ await openLaunchRow(tester, name);
+ expect(box.field.name, name);
+ box.focusField(NewHarnessField.launch);
+ await tester.pump();
+ await tester.tap(
+ find.byKey(
+ ValueKey(
+ 'new-harness-field-${name == 'mode' ? 'approvals' : name}',
+ ),
+ ),
+ );
+ await tester.pump();
+ expect(box.field.name, name);
+ }
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ testWidgets(
+ 'wide dock exposes engines beyond six rows and scrolls a long harness catalog',
+ (tester) async {
+ final app = createApp();
+ seedMixedAgents(app);
+ app.machineStates['m']!.dsh.replace([
+ for (var i = 0; i < 50; i++)
+ DshEntry(
+ id: 'review/harness-$i',
+ name: 'Harness $i',
+ engine: 'claude',
+ installed: true,
+ ),
+ ]);
+ addTearDown(app.dispose);
+ final box = NewHarnessController(
+ app,
+ machineId: 'm',
+ engine: 'codex',
+ folder: '/work/scene',
+ offersStore: true,
+ );
+ addTearDown(box.dispose);
+ tester.view.devicePixelRatio = 1;
+ tester.view.physicalSize = const Size(1100, 800);
+ addTearDown(tester.view.reset);
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: NewHarnessForm(
+ controller: box,
+ onClose: () {},
+ onCreated: () {},
+ onNeedsForm: () {},
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ await openLaunchRow(tester, 'agent');
+ for (var i = 0; i < 30 && box.selected?.id != 'agy'; i++) {
+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
+ await tester.pumpAndSettle();
+ }
+ expect(
+ find.byKey(const ValueKey('new-harness-option-agy')).hitTestable(),
+ findsOneWidget,
+ );
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(box.engine, 'agy');
+ await openLaunchRow(tester, 'harness');
+ for (
+ var i = 0;
+ i < box.options.length &&
+ box.selected?.id != NewHarnessController.storeId;
+ i++
+ ) {
+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
+ await tester.pumpAndSettle();
+ }
+ expect(
+ find
+ .byKey(
+ const ValueKey(
+ 'new-harness-option-${NewHarnessController.storeId}',
+ ),
+ )
+ .hitTestable(),
+ findsOneWidget,
+ );
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ test(
+ 'legacy mixed history splits without moving or deleting its storage',
+ () async {
+ final store = MemoryStore();
+ store.values.addAll({
+ 'new_agent_engine': 'autonomous/blender',
+ 'new_agent_recent':
+ 'autonomous/blender\ncodex\nautonomous/typst\nclaude',
+ });
+ final prefs = AgentPreference(store);
+ await prefs.load();
+ expect(prefs.harness, 'autonomous/blender');
+ expect(prefs.recent, ['codex', 'claude']);
+ expect(prefs.recentHarnesses.toSet(), {
+ 'autonomous/blender',
+ 'autonomous/typst',
+ });
+ await prefs.remember('codex', harnessId: 'autonomous/blender');
+ await prefs.setAdvanced(true);
+ await prefs.remember('claude');
+ final restored = AgentPreference(store);
+ await restored.load();
+ expect(restored.harness, isNull);
+ expect(restored.engineFor('autonomous/blender'), 'codex');
+ expect(restored.engineFor(null), 'claude');
+ expect(restored.advancedOpen, isTrue);
+ expect(restored.recent, ['claude', 'codex']);
+ expect(store.values['new_agent_engine'], 'autonomous/blender');
+ },
+ );
+
+ test('old daemons and installed aliases determine compatibility', () {
+ final old = DshEntry.fromJson({
+ 'id': 'local/ollama',
+ 'name': 'Ollama',
+ 'engine': 'codex',
+ 'installed': true,
+ })!;
+ final current = DshEntry.fromJson({
+ 'id': 'autonomous/ollama',
+ 'name': 'Ollama',
+ 'engine': 'codex',
+ 'engines': ['codex', 'claude'],
+ })!;
+ expect(old.supportedEngines, ['codex']);
+ expect(currentHarnessCatalog([old, current]).single.supportedEngines, [
+ 'codex',
+ ]);
+ });
+
+ test('agent changes preserve harness and launch the exact pair', () async {
+ final connection = _Connection();
+ final app = createApp(connectionForTest: (_) => connection);
+ seedMixedAgents(app);
+ addTearDown(app.dispose);
+ await app.probeDsh('m', force: true);
+ final box = NewHarnessController(
+ app,
+ machineId: 'm',
+ engine: 'autonomous/blender',
+ folder: '/work/scene',
+ );
+ addTearDown(box.dispose);
+ box.focusField(NewHarnessField.agent);
+ expect(box.options.map((row) => row.id).toSet(), {'claude', 'codex'});
+ choose(box, NewHarnessField.agent, 'codex');
+ expect(box.harnessId, 'autonomous/blender');
+ expect(box.draft.engine, 'codex');
+ expect(box.draft.harnessId, 'autonomous/blender');
+ expect(await box.create(), NewHarnessOutcome.created);
+ expect(connection.creates.single, containsPair('engine', 'codex'));
+ expect(
+ connection.creates.single,
+ containsPair('dsh', 'autonomous/blender'),
+ );
+ await Future<void>.delayed(Duration.zero);
+ expect(app.agentPreference.engineFor('autonomous/blender'), 'codex');
+ expect(app.agentPreference.recent, isNot(contains('autonomous/blender')));
+ });
+
+ test(
+ 'Coding removes only the package choice and restores all engines',
+ () async {
+ final connection = _Connection();
+ final app = createApp(connectionForTest: (_) => connection);
+ seedMixedAgents(app);
+ addTearDown(app.dispose);
+ await app.probeDsh('m', force: true);
+ final box = NewHarnessController(
+ app,
+ machineId: 'm',
+ engine: 'autonomous/blender',
+ folder: '/work/scene',
+ );
+ addTearDown(box.dispose);
+ choose(box, NewHarnessField.harness, NewHarnessController.codingId);
+ expect(box.harnessId, isNull);
+ box.focusField(NewHarnessField.agent);
+ expect(box.options.any((row) => row.id == 'opencode'), isTrue);
+ expect(box.options.any((row) => row.id.contains('/')), isFalse);
+ choose(box, NewHarnessField.agent, 'codex');
+ expect(await box.create(), NewHarnessOutcome.created);
+ expect(connection.creates.single.containsKey('dsh'), isFalse);
+ expect(box.project.folder, '/work/scene');
+ },
+ );
+
+ for (final userChooses in [false, true]) {
+ test(
+ 'late catalog restores a remembered engine unless a user chose (chosen=$userChooses)',
+ () async {
+ final gate = Completer<void>();
+ final connection = _Connection()..catalogGate = gate;
+ final app = createApp(connectionForTest: (_) => connection);
+ seedMixedAgents(app);
+ addTearDown(app.dispose);
+ await app.agentPreference.remember(
+ 'codex',
+ harnessId: 'autonomous/blender',
+ );
+ final box = NewHarnessController(
+ app,
+ machineId: 'm',
+ engine: 'autonomous/blender',
+ folder: '/work/scene',
+ );
+ addTearDown(box.dispose);
+ await Future<void>.delayed(Duration.zero);
+ if (userChooses) choose(box, NewHarnessField.agent, 'claude');
+ gate.complete();
+ await app.probeDsh('m');
+ await Future<void>.delayed(Duration.zero);
+ expect(box.harnessId, 'autonomous/blender');
+ expect(box.engine, userChooses ? 'claude' : 'codex');
+ },
+ );
+ }
+
+ test('late installed compatibility refuses a stale pair without substituting an agent', () async {
+ final connection = _Connection()
+ ..installed = false
+ ..legacyInstall = true;
+ final app = createApp(connectionForTest: (_) => connection);
+ seedMixedAgents(app);
+ addTearDown(app.dispose);
+ await app.probeDsh('m', force: true);
+ final box = NewHarnessController(
+ app,
+ machineId: 'm',
+ engine: 'autonomous/blender',
+ folder: '/work/scene',
+ );
+ addTearDown(box.dispose);
+ choose(box, NewHarnessField.agent, 'codex');
+ expect(await box.create(), NewHarnessOutcome.failed);
+ expect(box.error, contains('does not support Codex'));
+ expect(connection.creates, isEmpty);
+ expect(box.engine, 'codex');
+ expect(box.harnessId, 'autonomous/blender');
+ box.focusField(NewHarnessField.agent);
+ expect(box.options.map((row) => row.id), ['claude']);
+ });
+
+ for (final (layout, viewport) in [
+ ('wide', const Size(1100, 720)),
+ ('compact', const Size(600, 720)),
+ ]) {
+ testWidgets(
+ '$layout form keeps Harness Agent Machine Project visible and expands Advanced inline',
+ (tester) async {
+ final renderDir = Platform.environment['HARNESS_LAUNCH_RENDER_DIR'];
+ if (renderDir != null) await tester.runAsync(loadPreviewFonts);
+ final connection = _Connection();
+ final app = createApp(connectionForTest: (_) => connection);
+ seedMixedAgents(app);
+ addTearDown(app.dispose);
+ final box = NewHarnessController(
+ app,
+ machineId: 'm',
+ engine: 'autonomous/blender',
+ folder: '/work/scene',
+ offersStore: true,
+ );
+ addTearDown(box.dispose);
+ tester.view.devicePixelRatio = 1;
+ tester.view.physicalSize = viewport;
+ addTearDown(tester.view.reset);
+ await tester.pumpWidget(
+ MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: ThemeData.dark(),
+ home: Scaffold(
+ body: Center(
+ child: SizedBox(
+ width: 1000,
+ height: 480,
+ child: NewHarnessForm(
+ controller: box,
+ onClose: () {},
+ onCreated: () {},
+ onNeedsForm: () => fail('Advanced must stay inline'),
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pump();
+ for (final row in [
+ 'harness',
+ 'agent',
+ 'model',
+ 'machine',
+ 'project',
+ 'branch',
+ ]) {
+ expect(
+ find.byKey(ValueKey('new-harness-field-$row')).hitTestable(),
+ findsOneWidget,
+ );
+ }
+ expect(
+ find.byKey(const ValueKey('new-harness-field-worktree')),
+ findsNothing,
+ );
+ await tester.tap(
+ find.byKey(const ValueKey('new-harness-field-harness')),
+ );
+ await tester.pump();
+ expect(find.text('Browse Harness Store…'), findsOneWidget);
+ if (renderDir != null) {
+ await expectLater(
+ find.byType(MaterialApp),
+ matchesGoldenFile(
+ Uri.file('$renderDir/$layout-harness-picker.png'),
+ ),
+ );
+ }
+ await openLaunchRow(tester, 'agent');
+ await tester.pump();
+ expect(find.text('Browse Harness Store…'), findsNothing);
+ expect(box.options.map((row) => row.id).toSet(), {'codex', 'claude'});
+ await openLaunchRow(tester, 'advanced');
+ await tester.pump();
+ expect(
+ find.byKey(const ValueKey('new-harness-field-machine')),
+ findsOneWidget,
+ );
+ expect(
+ find.byKey(const ValueKey('new-harness-field-approvals')),
+ findsOneWidget,
+ );
+ if (renderDir != null) {
+ await expectLater(
+ find.byType(MaterialApp),
+ matchesGoldenFile(Uri.file('$renderDir/$layout-agent-picker.png')),
+ );
+ }
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ await tester.pump(const Duration(milliseconds: 200));
+ },
+ );
+ }
+}
diff --git a/desktop/test/harness_command_bar_test.dart b/desktop/test/harness_command_bar_test.dart
index 39d701023..8309e8e9d 100644
--- a/desktop/test/harness_command_bar_test.dart
+++ b/desktop/test/harness_command_bar_test.dart
@@ -421,10 +421,11 @@ void main() {
.widget<NewHarnessForm>(find.byType(NewHarnessForm))
.controller;
expect(prompt.machineId, 'm');
- expect(prompt.engine, 'studio/arm');
+ expect(prompt.harnessId, 'studio/arm');
+ expect(prompt.engine, 'claude');
expect(prompt.project.folder, isNull);
expect(prompt.task, 'Plan the arm calibration');
- expect(prompt.field, NewHarnessField.projectMenu);
+ expect(prompt.field, NewHarnessField.harness);
expect(
find.byKey(const ValueKey('new-harness-field-project')),
findsOneWidget,
diff --git a/desktop/test/harness_placement_test.dart b/desktop/test/harness_placement_test.dart
index 7eee1229b..303838d78 100644
--- a/desktop/test/harness_placement_test.dart
+++ b/desktop/test/harness_placement_test.dart
@@ -14,7 +14,6 @@ import 'package:harness/state/pane_preset.dart';
import 'package:harness/state/swarm_navigation.dart';
import 'package:harness/state/swarm_search.dart';
import 'package:harness/widgets/new_harness_form.dart';
-import 'package:harness/widgets/codex_profile_field.dart';
import 'package:harness/ws/ws_conn.dart';
import 'swarm_interactions_test.dart' show chord;
@@ -161,10 +160,10 @@ void main() {
for (final (dismiss, profile) in [
('escape', 'Work'),
('outside', 'Default'),
- ('footer', 'Work'),
+ ('advanced', 'Work'),
]) {
testWidgets(
- 'advanced $dismiss returns the edited draft and $profile profile to the prompt',
+ 'inline advanced keeps the draft and $profile profile after $dismiss',
(tester) async {
newHarnessOpensInBox = true;
addTearDown(() => newHarnessOpensInBox = false);
@@ -179,110 +178,81 @@ void main() {
app.adoptSessionForTest(terminal('a0', []));
final original = app.activeSwarm;
await mount(tester, app);
- await chord(tester, LogicalKeyboardKey.keyT);
- await chord(tester, LogicalKeyboardKey.keyO);
- await acceptSetupOrSearch(tester);
+ await chord(tester, LogicalKeyboardKey.keyN);
+ var box = tester
+ .widget<NewHarnessForm>(find.byType(NewHarnessForm))
+ .controller;
+ box.setFolder('/work/source');
await tester.pump();
- await chord(tester, LogicalKeyboardKey.period);
- await tester.pumpAndSettle();
- await tester.enterText(
- find.byKey(const Key('new-agent-task')),
- ' Review before changing anything\nKeep the patch small ',
+ final input = find.byKey(const ValueKey('new-harness-query'));
+ box.task = ' Review before changing anything\nKeep the patch small ';
+ await tester.pump();
+ await openLaunchRow(tester, 'mode');
+ await tester.tap(
+ find.byKey(const ValueKey('new-harness-option-readOnly')),
);
- await tester.tap(find.byKey(const Key('new-agent-permission-mode')));
- await tester.pumpAndSettle();
- await tester.tap(find.text('Read only'));
+ await tester.pump();
+ await openLaunchRow(tester, 'profile');
await tester.pumpAndSettle();
- if (profile == 'Default') {
+ await tester.tap(
+ find.byKey(
+ ValueKey(
+ profile == 'Default'
+ ? 'new-harness-option-${NewHarnessController.defaultProfileId}'
+ : 'new-harness-option-profile:/work/.codex-work',
+ ),
+ ),
+ );
+ await tester.pump();
+ await openLaunchRow(tester, 'project');
+ await tester.tap(
+ find.byKey(
+ const ValueKey(
+ 'new-harness-option-${NewHarnessController.repositoryId}',
+ ),
+ ),
+ );
+ await tester.pump();
+ await tester.enterText(input, 'acme/terminal-tools');
+ await tester.pump(const Duration(milliseconds: 250));
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ expect(
+ box.project.repository?.url,
+ 'https://github.com/acme/terminal-tools.git',
+ );
+ expect(find.byType(AlertDialog), findsNothing);
+ if (dismiss == 'advanced') {
await tester.tap(
- find.byKey(const Key('new-agent-codex-profile-field')),
+ find.byKey(const ValueKey('new-harness-field-advanced')),
);
- await tester.pumpAndSettle();
- await tester.tap(find.text('Default profile'));
- await tester.pumpAndSettle();
- }
- final git = find.byKey(const Key('new-agent-project-git'));
- await tester.ensureVisible(git);
- await tester.tap(git);
- await tester.pumpAndSettle();
- await tester.enterText(
- find.byKey(const Key('new-agent-git-url')),
- 'acme/terminal-tools',
- );
- await chord(tester, LogicalKeyboardKey.enter);
- await tester.pumpAndSettle();
- switch (dismiss) {
- case 'escape':
+ await tester.pump();
+ expect(box.advancedOpen, isFalse);
+ } else {
+ if (dismiss == 'escape') {
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
- case 'outside':
- await tester.tapAt(const Offset(4, 650));
- case 'footer':
- await tester.tap(find.textContaining('esc back'));
+ } else {
+ await tester.tapAt(const Offset(4, 10));
+ }
+ await tester.pumpAndSettle();
+ expect(find.byType(NewHarnessForm), findsNothing);
+ await chord(tester, LogicalKeyboardKey.keyN);
+ box = tester
+ .widget<NewHarnessForm>(find.byType(NewHarnessForm))
+ .controller;
}
- await tester.pumpAndSettle();
- expect(find.byType(AlertDialog), findsNothing);
- var box = tester
- .widget<NewHarnessForm>(find.byType(NewHarnessForm))
- .controller;
expect(
box.task,
' Review before changing anything\nKeep the patch small ',
);
- expect(
- box.project.repository?.url,
- 'https://github.com/acme/terminal-tools.git',
- );
expect(box.mode, 'readOnly');
expect(box.profileLabel, profile);
- expect(find.text('Read only'), findsOneWidget);
- expect(find.text(profile), findsOneWidget);
- expect(find.byType(NewHarnessForm), findsOneWidget);
expect(
- FocusManager.instance.primaryFocus!.debugLabel,
- 'new-harness-form',
+ box.project.repository?.url,
+ 'https://github.com/acme/terminal-tools.git',
);
expect(connection.requests, isEmpty);
- expect(app.swarms, contains(original));
- expect(app.swarms, hasLength(2));
-
- // Returning to advanced options preserves an explicit Default choice,
- // even when discovery finds one profile and would normally select it.
- await chord(tester, LogicalKeyboardKey.period);
- await tester.pumpAndSettle();
- expect(
- tester
- .widget<CodexProfileField>(find.byType(CodexProfileField))
- .value
- ?.label,
- profile == 'Default' ? null : 'Work',
- );
- expect(find.text('terminal-tools'), findsOneWidget);
- await tester.sendKeyEvent(LogicalKeyboardKey.escape);
- await tester.pumpAndSettle();
- box = tester
- .widget<NewHarnessForm>(find.byType(NewHarnessForm))
- .controller;
- expect(box.profileLabel, profile);
- // A second Escape leaves creation entirely. Reopening from the same
- // source must retain the clone, permissions, task, and profile while
- // honoring the newly requested destination.
- await tester.sendKeyEvent(LogicalKeyboardKey.escape);
- await tester.pump();
- await chord(tester, LogicalKeyboardKey.keyW);
- final inPane = dismiss == 'outside';
- await chord(
- tester,
- inPane ? LogicalKeyboardKey.keyO : LogicalKeyboardKey.keyT,
- );
- if (!inPane) await chord(tester, LogicalKeyboardKey.keyO);
- await acceptSetupOrSearch(tester);
- await tester.pump();
- box = tester
- .widget<NewHarnessForm>(find.byType(NewHarnessForm))
- .controller;
- expect(box.profileLabel, profile);
- expect(box.placement, HarnessPlacement.currentTab);
- await acceptSetupOrSearch(tester);
+ await startHarness(tester);
await tester.pump();
final request = connection.requests.single;
expect(request.payload['permissionMode'], 'readOnly');
@@ -300,15 +270,7 @@ void main() {
);
connection.created();
await tester.pumpAndSettle();
- if (inPane) {
- expect(app.swarms, [original]);
- expect(original.panes, hasLength(2));
- } else {
- expect(app.swarms, hasLength(2));
- expect(app.activeSwarm.name, 'Made');
- }
- app.selectSwarm(original.id);
- app.focusPane(original.panes.first.id);
+ expect(app.swarms, contains(original));
await chord(tester, LogicalKeyboardKey.keyN);
expect(
tester
@@ -316,8 +278,6 @@ void main() {
.controller
.task,
isEmpty,
- reason:
- 'Successful creation consumes the draft in its source context',
);
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pumpWidget(const SizedBox());
@@ -326,7 +286,7 @@ void main() {
}
testWidgets(
- 'back from an unresolved advanced creation retains its receipt and locks the task',
+ 'an unresolved inline launch keeps its receipt and locks the draft',
(tester) async {
newHarnessOpensInBox = true;
addTearDown(() => newHarnessOpensInBox = false);
@@ -335,48 +295,34 @@ void main() {
addTearDown(app.dispose);
app.machineStates['m']!.nodeOnline = true;
app.adoptSessionForTest(terminal('a0', []));
- final original = app.activeSwarm;
await mount(tester, app);
- await chord(tester, LogicalKeyboardKey.keyT);
- await chord(tester, LogicalKeyboardKey.keyO);
- await acceptSetupOrSearch(tester);
- await tester.pump();
- final input = find.byKey(const ValueKey('new-harness-input'));
- tester
+ await chord(tester, LogicalKeyboardKey.keyN);
+ final box = tester
.widget<NewHarnessForm>(find.byType(NewHarnessForm))
- .controller
- .focusField(NewHarnessField.task);
+ .controller;
+ box.setFolder('/work/source');
await tester.pump();
- await typeHarnessQuery(tester, 'Keep this first task');
- await chord(tester, LogicalKeyboardKey.period);
- await tester.pumpAndSettle();
- await chord(tester, LogicalKeyboardKey.enter);
+ box.task = 'Keep this first task';
+ await tester.pump();
+ await startHarness(tester);
await tester.pump();
final request = connection.requests.single;
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
- await tester.tapAt(const Offset(4, 650));
+ await tester.tapAt(const Offset(4, 10));
await tester.pump();
- expect(find.byType(AlertDialog), findsOneWidget);
- expect(find.byType(NewHarnessForm), findsNothing);
+ expect(find.byType(NewHarnessForm), findsOneWidget);
request.reply.completeError(const WsRequestTimeout('agent_create'));
await tester.pumpAndSettle();
- await tester.sendKeyEvent(LogicalKeyboardKey.escape);
- await tester.pumpAndSettle();
- final box = tester
- .widget<NewHarnessForm>(find.byType(NewHarnessForm))
- .controller;
expect(box.checking, isTrue);
- expect(find.byType(NewHarnessForm), findsOneWidget);
- expect(input, findsNothing);
+ expect(box.field, NewHarnessField.launch);
+ expect(harnessChoicesActive(tester), isFalse);
await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft);
await tester.sendKeyEvent(LogicalKeyboardKey.keyW);
await tester.sendKeyEvent(LogicalKeyboardKey.keyU);
await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft);
await tester.pump();
expect(box.task, 'Keep this first task');
- expect(app.swarms, contains(original));
- expect(app.swarms, hasLength(2));
- await acceptSetupOrSearch(tester);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pump();
expect(connection.requests, hasLength(2));
expect(connection.requests.last.type, 'agent_create_status');
@@ -386,8 +332,7 @@ void main() {
);
connection.created();
await tester.pumpAndSettle();
- expect(app.swarms, hasLength(2));
- expect(app.activeSwarm.name, 'Made');
+ expect(find.byType(NewHarnessForm), findsNothing);
await tester.pumpWidget(const SizedBox());
},
);
@@ -422,53 +367,64 @@ void main() {
await mount(tester, app);
await chord(tester, LogicalKeyboardKey.keyT);
await chord(tester, LogicalKeyboardKey.keyO);
- await acceptSetupOrSearch(tester);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pump();
- final setup = tester
- .widget<NewHarnessForm>(find.byType(NewHarnessForm))
- .controller;
- setup.task = 'Review the project before changing anything';
- await openLaunchRow(tester, 'project');
- final door = projectQuery.startsWith('/')
- ? NewHarnessController.existingProjectId
- : projectQuery.contains('/')
- ? NewHarnessController.repositoryId
- : NewHarnessController.newProjectId;
- setup.move(
- setup.options.indexWhere((row) => row.id == door) - setup.cursor,
+ final input = find.byKey(const ValueKey('new-harness-query'));
+ tester
+ .widget<NewHarnessForm>(find.byType(NewHarnessForm))
+ .controller
+ .task =
+ 'Review the project before changing anything';
+ await tester.tap(
+ find.byKey(const ValueKey('new-harness-field-project')),
);
- await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pump();
- await typeHarnessQuery(tester, projectQuery);
+ await tester.tap(
+ find.byKey(
+ ValueKey(
+ projectQuery.startsWith('/')
+ ? 'new-harness-option-${NewHarnessController.existingProjectId}'
+ : projectQuery.contains('/')
+ ? 'new-harness-option-${NewHarnessController.repositoryId}'
+ : 'new-harness-option-${NewHarnessController.newProjectId}',
+ ),
+ ),
+ );
+ await tester.pump();
+ await tester.enterText(input, projectQuery);
await tester.pump(const Duration(milliseconds: 250));
- await acceptSetupOrSearch(tester);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pump();
- await chord(tester, LogicalKeyboardKey.period);
- await tester.pumpAndSettle();
- await tester.tap(find.byKey(const Key('new-agent-permission-mode')));
- await tester.pumpAndSettle();
- await tester.tap(find.text('Read only'));
- await tester.pumpAndSettle();
- await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await openLaunchRow(tester, 'mode');
+ await tester.tap(
+ find.byKey(const ValueKey('new-harness-option-readOnly')),
+ );
await tester.pumpAndSettle();
final box = tester
.widget<NewHarnessForm>(find.byType(NewHarnessForm))
.controller;
expect(box.mode, 'readOnly');
- await chord(tester, LogicalKeyboardKey.period);
- await tester.pumpAndSettle();
- expect(find.byType(NewHarnessForm), findsNothing);
- expect(find.text(detail), findsOneWidget);
- final mode = find.byKey(const Key('new-agent-permission-mode'));
+ await tester.tap(
+ find.byKey(const ValueKey('new-harness-field-advanced')),
+ );
+ await tester.pump();
+ expect(box.advancedOpen, isFalse);
+ await tester.tap(
+ find.byKey(const ValueKey('new-harness-field-advanced')),
+ );
+ await tester.pump();
+ expect(find.byType(AlertDialog), findsNothing);
+ expect(box.projectLabel, contains(detail));
expect(
- find.descendant(of: mode, matching: find.text('Read only')),
+ find.descendant(
+ of: find.byKey(const ValueKey('new-harness-field-approvals')),
+ matching: find.text('Read only'),
+ ),
findsOneWidget,
);
expect(app.swarms, contains(original));
expect(app.swarms, hasLength(2));
- final create = find.byKey(const ValueKey('create-agent-submit'));
- await tester.ensureVisible(create);
- await tester.tap(create);
+ await startHarness(tester);
await tester.pump();
final request = connection.requests.single;
for (final field in preparation.entries) {
@@ -758,7 +714,7 @@ void main() {
final search = find.byKey(const ValueKey('swarm-search-input'));
await tester.enterText(search, 'fix the login regression');
await tester.pump();
- await acceptSetupOrSearch(tester);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pump();
final box = tester
.widget<NewHarnessForm>(find.byType(NewHarnessForm))
@@ -767,7 +723,7 @@ void main() {
expect(box.placement, HarnessPlacement.currentTab);
box.setFolder('/work/project');
await tester.pump();
- await acceptSetupOrSearch(tester);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pump();
expect(box.busy, isTrue);
expect(
@@ -776,7 +732,7 @@ void main() {
);
Future<void> keepsPendingBox() async {
- expect(find.byType(NewHarnessForm), findsOneWidget);
+ expect(box.field, NewHarnessField.launch);
expect(box.locked, isTrue);
final task = box.task;
await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft);
@@ -822,7 +778,7 @@ void main() {
expect(box.checking, isTrue);
await keepsPendingBox();
expect(connection.requests, hasLength(1));
- await acceptSetupOrSearch(tester);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pump();
expect(connection.requests.last.type, 'agent_create_status');
connection.created();
@@ -852,14 +808,14 @@ void main() {
await mount(tester, app);
await chord(tester, LogicalKeyboardKey.keyT);
await chord(tester, LogicalKeyboardKey.keyO);
- await acceptSetupOrSearch(tester);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pump();
tester
.widget<NewHarnessForm>(find.byType(NewHarnessForm))
.controller
.setFolder('/work/project');
await tester.pump();
- await acceptSetupOrSearch(tester);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pump();
final request = connection.requests.single;
expect(request.payload.containsKey('prompt'), isFalse);
@@ -872,7 +828,7 @@ void main() {
await tester.pump();
expect(find.byType(NewHarnessForm), findsNothing);
await chord(tester, LogicalKeyboardKey.keyO);
- await acceptSetupOrSearch(tester);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pump();
final box = tester
.widget<NewHarnessForm>(find.byType(NewHarnessForm))
@@ -880,16 +836,19 @@ void main() {
expect(box.task, isEmpty);
expect(box.checking, isTrue);
expect(find.text('pending harness'), findsNothing);
- expect(find.text('Check status'), findsOneWidget);
+ expect(
+ find.textContaining('Check status', findRichText: true),
+ findsOneWidget,
+ );
// The restored "Escape again" warning keeps its meaning; it must not
// require another invisible acknowledgement before closing.
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pump();
expect(find.byType(NewHarnessForm), findsNothing);
await chord(tester, LogicalKeyboardKey.keyO);
- await acceptSetupOrSearch(tester);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pump();
- await acceptSetupOrSearch(tester);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pump();
expect(connection.requests, hasLength(2));
expect(connection.requests.last.type, 'agent_create_status');
@@ -966,7 +925,7 @@ void main() {
await chord(tester, LogicalKeyboardKey.keyO);
}
await tester.pump();
- await acceptSetupOrSearch(tester);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pump();
final box = tester
.widget<NewHarnessForm>(find.byType(NewHarnessForm))
diff --git a/desktop/test/harness_store_entry_test.dart b/desktop/test/harness_store_entry_test.dart
index 6c3ea02ad..94bb51a85 100644
--- a/desktop/test/harness_store_entry_test.dart
+++ b/desktop/test/harness_store_entry_test.dart
@@ -135,7 +135,7 @@ void main() {
final box = tester
.widget<NewHarnessForm>(find.byType(NewHarnessForm))
.controller;
- expect(box.engine, 'studio/arm');
+ expect(box.harnessId, 'studio/arm');
expect(box.task, prompt ?? '');
expect(box.projectLabel, startsWith('~/harnesses/robot-studio-'));
expect(box.projectFolderRequest!.isGenerated, isTrue);
@@ -152,7 +152,7 @@ void main() {
);
}
- testWidgets('browsing from agent choices retains the task and defaults', (
+ testWidgets('browsing from harness choices retains the task and defaults', (
tester,
) async {
newHarnessOpensInBox = true;
@@ -174,11 +174,11 @@ void main() {
box.task = 'Finish the login feature';
await tester.pump();
final draft = box.draft;
- await openLaunchRow(tester, 'agent');
+ await openLaunchRow(tester, 'harness');
await typeHarnessQuery(tester, 'a harness not in this catalog');
await tester.pump();
expect(box.selected?.id, NewHarnessController.storeId);
- expect(find.text('Browse more harnesses…'), findsOneWidget);
+ expect(find.text('Browse Harness Store…'), findsOneWidget);
await acceptSetupOrSearch(tester);
expect(app.activeSwarm.isStore, isTrue);
expect(find.byType(NewHarnessForm), findsNothing);
diff --git a/desktop/test/keymap_runtime_test.dart b/desktop/test/keymap_runtime_test.dart
index 1bd136a6c..49257b8d6 100644
--- a/desktop/test/keymap_runtime_test.dart
+++ b/desktop/test/keymap_runtime_test.dart
@@ -20,6 +20,7 @@ import 'package:harness/widgets/swarm_switcher.dart';
import 'package:xterm/xterm.dart';
import 'keymap_host_test.dart' show MemoryKeymap, key;
+import 'support/launch_menu.dart';
import 'swarm_screen_test.dart' show terminal;
import 'swarm_state_test.dart' show createApp;
@@ -91,6 +92,57 @@ Future<void> tabToResult(WidgetTester tester, {String? id}) async {
}
void main() {
+ testWidgets(
+ 'New Harness remapped navigation works in both fields and choices',
+ (tester) async {
+ final previousEntry = newHarnessOpensInBox;
+ newHarnessOpensInBox = true;
+ addTearDown(() => newHarnessOpensInBox = previousEntry);
+ final map = MemoryKeymap()
+ ..apply('''{"bindings":[
+ {"keys":"ctrl+j","command":"picker.next","when":"picker"},
+ {"keys":"ctrl+k","command":"picker.previous","when":"picker"},
+ {"keys":"ctrl+l","command":"picker.complete","when":"picker"},
+ {"keys":"ctrl+h","command":"picker.complete_back","when":"picker"}
+ ]}''');
+ final app = createApp();
+ addTearDown(map.dispose);
+ addTearDown(app.dispose);
+ await mount(tester, app, map);
+ await key(tester, LogicalKeyboardKey.keyN, cmd: true);
+ final box = tester
+ .widget<NewHarnessForm>(find.byType(NewHarnessForm))
+ .controller;
+ for (final (forward, backward) in [
+ (LogicalKeyboardKey.keyJ, LogicalKeyboardKey.keyK),
+ (LogicalKeyboardKey.keyL, LogicalKeyboardKey.keyH),
+ ]) {
+ await key(tester, forward, ctrl: true);
+ expect(box.field, NewHarnessField.agent);
+ await key(tester, backward, ctrl: true);
+ expect(box.field, NewHarnessField.harness);
+ await key(tester, forward, ctrl: true);
+ await key(tester, LogicalKeyboardKey.enter);
+ final cursor = box.cursor;
+ final engine = box.engine;
+ await key(tester, forward, ctrl: true);
+ expect(box.cursor, (cursor + 1) % box.options.length);
+ await key(tester, backward, ctrl: true);
+ expect(box.cursor, cursor);
+ expect(box.engine, engine);
+ await key(tester, LogicalKeyboardKey.escape);
+ await key(tester, backward, ctrl: true);
+ }
+ await focusLaunchRow(tester, 'advanced');
+ final expanded = box.advancedOpen;
+ await key(tester, LogicalKeyboardKey.arrowRight);
+ expect(box.advancedOpen, !expanded);
+ await key(tester, LogicalKeyboardKey.arrowLeft);
+ expect(box.advancedOpen, expanded);
+ expect(app.panes, isEmpty);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
for (final command in ['newAgent', 'commands']) {
testWidgets('native $command preserves composing New Harness input', (
tester,
@@ -728,11 +780,13 @@ void main() {
await tester.pumpAndSettle();
expect(find.byType(AlertDialog), findsOneWidget);
expect(find.byType(SwarmSearchResults), findsNothing);
- // The form opens with focus on its agent bar, and Escape there still
+ // The form opens with focus on its harness bar, and Escape there still
// closes the form.
expect(
tester
- .widget<AgentPicker>(find.byType(AgentPicker))
+ .widget<AgentPicker>(
+ find.byKey(const Key('new-agent-harness-picker')),
+ )
.focusNode!
.hasPrimaryFocus,
isTrue,
diff --git a/desktop/test/models_menu_test.dart b/desktop/test/models_menu_test.dart
index c9d9c0a14..70732adee 100644
--- a/desktop/test/models_menu_test.dart
+++ b/desktop/test/models_menu_test.dart
@@ -415,7 +415,7 @@ void main() {
final box = tester
.widget<NewHarnessForm>(find.byType(NewHarnessForm))
.controller;
- expect(box.engine, harness);
+ expect(box.harnessId, harness);
expect(box.machineId, machineId ?? 'm');
expect(box.projectLabel, startsWith('~/harnesses/$stem-'));
expect(box.placement, HarnessPlacement.newTab);
@@ -437,7 +437,7 @@ void main() {
tester
.widget<NewHarnessForm>(find.byType(NewHarnessForm))
.controller
- .engine,
+ .harnessId,
harness,
);
expect(app.swarms, [source]);
diff --git a/desktop/test/new_agent_choices_layout_test.dart b/desktop/test/new_agent_choices_layout_test.dart
index 00e3014b1..36b359be9 100644
--- a/desktop/test/new_agent_choices_layout_test.dart
+++ b/desktop/test/new_agent_choices_layout_test.dart
@@ -69,6 +69,7 @@ class _ChoicesApp extends AppNotifier {
String? swarmId,
PaneSplitRequest? split,
String? dsh,
+ GridModel? model,
String? prompt,
String? name,
String? agent,
@@ -209,6 +210,8 @@ void main() {
}
await capture('initial');
+ expect(find.byKey(const Key('new-agent-machine-field')), findsOneWidget);
+ await expandNewAgentAdvanced(tester);
for (final id in ['local', 'office', 'studio']) {
expect(find.byKey(ValueKey('new-agent-machine-$id')), findsOneWidget);
}
@@ -281,19 +284,22 @@ void main() {
await tester.pumpAndSettle();
if (size.width >= 900 && size.height >= 720 && scale == 1) {
- // The common desktop sizes should show every choice before scrolling.
+ // Expanded settings remain reachable without overflowing the form.
final form = find.ancestor(
of: agentBar,
matching: find.byType(SingleChildScrollView),
);
- final visible = tester.getRect(form);
for (final key in [
+ 'new-agent-harness-field',
'new-agent-agent-field',
'new-agent-machine-local',
'new-agent-folder-newProject',
'new-agent-project-recent',
]) {
final choice = find.byKey(ValueKey(key));
+ await tester.ensureVisible(choice);
+ await tester.pumpAndSettle();
+ final visible = tester.getRect(form);
final bounds = tester.getRect(choice);
expect(bounds.top, greaterThanOrEqualTo(visible.top));
expect(bounds.bottom, lessThanOrEqualTo(visible.bottom));
@@ -348,7 +354,7 @@ void main() {
expect(find.byKey(const ValueKey('create-agent-submit')), findsOneWidget);
final advanced = find.byKey(const Key('new-agent-advanced'));
await tester.ensureVisible(advanced);
- await tester.tap(advanced);
+ await expandNewAgentAdvanced(tester);
await tester.pumpAndSettle();
await tester.ensureVisible(find.text('Auto-approve'));
expect(find.text('Permissions'), findsNothing);
@@ -392,6 +398,7 @@ void main() {
// Help is a separate route: it must keep the current choices and scroll
// position, contain keyboard shortcuts, and return focus to its trigger.
+ await expandNewAgentAdvanced(tester);
for (final (topic, lastTitle) in [
('machine', 'Remote machine'),
('project', 'Recent'),
@@ -441,7 +448,11 @@ void main() {
expect(selected.selected, isTrue);
expect(selected.detail, 'repo');
expect(
- tester.widget<AgentPicker>(find.byType(AgentPicker)).value,
+ tester
+ .widget<AgentPicker>(
+ find.byKey(const Key('new-agent-agent-picker')),
+ )
+ .value,
'codex',
);
expect(
@@ -467,7 +478,11 @@ void main() {
await chooseAgent(tester, 'kilo');
await tester.pumpAndSettle();
expect(
- tester.widget<AgentPicker>(find.byType(AgentPicker)).value,
+ tester
+ .widget<AgentPicker>(
+ find.byKey(const Key('new-agent-agent-picker')),
+ )
+ .value,
'kilo',
);
expect(
diff --git a/desktop/test/new_agent_codex_profile_test.dart b/desktop/test/new_agent_codex_profile_test.dart
index be27a686a..57a0bb96b 100644
--- a/desktop/test/new_agent_codex_profile_test.dart
+++ b/desktop/test/new_agent_codex_profile_test.dart
@@ -133,6 +133,7 @@ class _Notifier extends AppNotifier {
String? permissionMode,
String? codexHome,
String? dsh,
+ GridModel? model,
String? prompt,
String? name,
String? agent,
diff --git a/desktop/test/new_agent_dsh_test.dart b/desktop/test/new_agent_dsh_test.dart
index b594c78f0..0841f3aac 100644
--- a/desktop/test/new_agent_dsh_test.dart
+++ b/desktop/test/new_agent_dsh_test.dart
@@ -105,6 +105,7 @@ class _Notifier extends AppNotifier {
String? permissionMode,
String? codexHome,
String? dsh,
+ GridModel? model,
String? prompt,
String? name,
String? agent,
@@ -193,8 +194,8 @@ void main() {
/// A harness is found by typing its name into the agent search, and taken
/// by clicking its row.
Future<void> pick(WidgetTester tester, String label) async {
- await openAgentSearch(tester);
- await tester.enterText(agentSearch, label);
+ await openHarnessSearch(tester);
+ await tester.enterText(harnessSearch, label);
await tester.pumpAndSettle();
await tester.tap(
find
@@ -212,8 +213,9 @@ void main() {
await tester.pump();
}
- String engineField(WidgetTester tester) =>
- tester.widget<AgentPicker>(find.byType(AgentPicker)).value;
+ String engineField(WidgetTester tester) => tester
+ .widget<AgentPicker>(find.byKey(const Key('new-agent-harness-picker')))
+ .value;
testWidgets(
'Circuit is one click, says what it runs on, and creates on its base engine',
@@ -229,17 +231,17 @@ void main() {
reason: 'asked once on open, so the agent search is never stale',
);
await pick(tester, 'Autonomous Circuit');
- expect(app.harnessProbes, 2);
+ expect(app.harnessProbes, 1);
expect(engineField(tester), 'autonomous/autonomous-circuit');
// Chosen, the bar shows it and the search is closed.
expect(
find.descendant(
- of: agentBar,
+ of: harnessBar,
matching: find.text('Autonomous Circuit'),
),
findsOneWidget,
);
- expect(agentSearch, findsNothing);
+ expect(harnessSearch, findsNothing);
await tester.ensureVisible(find.byKey(const Key('new-agent-advanced')));
await tester.tap(find.byKey(const Key('new-agent-advanced')));
await tester.pumpAndSettle();
@@ -356,6 +358,7 @@ void main() {
isNotNull,
reason: 'An unsupported CLI must release the form for retry or another harness.',
);
+ await chooseHarness(tester, 'harness:coding');
await chooseAgent(tester, 'claude');
await tester.pumpAndSettle();
await create(tester);
@@ -377,34 +380,30 @@ void main() {
),
]),
);
- await openAgentSearch(tester);
+ await openHarnessSearch(tester);
// Nothing typed: the choice, then what the machine has — Circuit, the
// harness it installed, ahead of Codex, an engine it has, and the
// terminal, which every machine has — then the familiar engines, and
// the Store last. Robot Arm, which it lacks, is not listed.
- expect(agentRows(tester), [
- 'claude',
+ expect(harnessRows(tester), [
+ 'harness:coding',
'autonomous/autonomous-circuit',
- 'codex',
- 'terminal',
- 'opencode',
]);
- await tester.enterText(agentSearch, 'robot');
+ await tester.enterText(harnessSearch, 'robot');
await tester.pumpAndSettle();
- expect(agentRows(tester), ['someone/robot-arm']);
+ expect(harnessRows(tester), ['someone/robot-arm']);
expect(find.text('on Codex'), findsNothing, reason: 'backend detail');
await tester.tap(
- find.byKey(const ValueKey('new-agent-agent-row-someone/robot-arm')),
+ find.byKey(const ValueKey('new-agent-harness-row-someone/robot-arm')),
);
await tester.pumpAndSettle();
expect(engineField(tester), 'someone/robot-arm');
- expect(agentSearch, findsNothing, reason: 'a choice closes the search');
+ expect(harnessSearch, findsNothing, reason: 'a choice closes the search');
// Chosen, it leads the list; what the machine has still follows.
- await openAgentSearch(tester);
- expect(agentRows(tester).take(3), [
+ await openHarnessSearch(tester);
+ expect(harnessRows(tester).take(2), [
'someone/robot-arm',
'autonomous/autonomous-circuit',
- 'claude',
]);
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pumpAndSettle();
@@ -425,11 +424,8 @@ void main() {
// Hermes is not installed, so only having used it lists it this early.
await app.agentPreference.remember('hermes');
await openAgentSearch(tester);
- expect(agentRows(tester).take(3), [
- 'claude',
- 'hermes',
- 'autonomous/autonomous-circuit',
- ]);
+ expect(agentRows(tester).take(2), ['claude', 'hermes']);
+ expect(agentRows(tester).any((id) => id.contains('/')), isFalse);
expect(tester.takeException(), isNull);
});
@@ -447,32 +443,32 @@ void main() {
),
]),
);
- await openAgentSearch(tester);
- await tester.enterText(agentSearch, 'robot');
+ await openHarnessSearch(tester);
+ await tester.enterText(harnessSearch, 'robot');
await tester.pumpAndSettle();
- expect(agentRows(tester), ['someone/robot-arm']);
+ expect(harnessRows(tester), ['someone/robot-arm']);
// Return takes the highlighted row, the first match.
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pumpAndSettle();
expect(engineField(tester), 'someone/robot-arm');
- expect(agentSearch, findsNothing);
+ expect(harnessSearch, findsNothing);
// The words under a name count: "PCB" is what Circuit makes.
- await openAgentSearch(tester);
- await tester.enterText(agentSearch, 'pcb');
+ await openHarnessSearch(tester);
+ await tester.enterText(harnessSearch, 'pcb');
await tester.pumpAndSettle();
- expect(agentRows(tester), ['autonomous/autonomous-circuit']);
+ expect(harnessRows(tester), ['autonomous/autonomous-circuit']);
// Nothing matching says so.
- await tester.enterText(agentSearch, 'welding');
+ await tester.enterText(harnessSearch, 'welding');
await tester.pumpAndSettle();
- expect(agentRows(tester), isEmpty);
+ expect(harnessRows(tester), isEmpty);
expect(
- find.byKey(const Key('new-agent-agent-search-empty')),
+ find.byKey(const Key('new-agent-harness-search-empty')),
findsOneWidget,
);
// Escape closes the search and keeps the choice; the dialog stays.
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pumpAndSettle();
- expect(agentSearch, findsNothing);
+ expect(harnessSearch, findsNothing);
expect(find.byType(AlertDialog), findsOneWidget);
expect(engineField(tester), 'someone/robot-arm');
expect(tester.takeException(), isNull);
diff --git a/desktop/test/new_agent_engine_check_test.dart b/desktop/test/new_agent_engine_check_test.dart
index d21bb8718..a62b70dc1 100644
--- a/desktop/test/new_agent_engine_check_test.dart
+++ b/desktop/test/new_agent_engine_check_test.dart
@@ -102,7 +102,7 @@ void main() {
);
expect(find.textContaining('uses an older Harness CLI'), findsNothing);
await tester.ensureVisible(find.byKey(const Key('new-agent-advanced')));
- await tester.tap(find.byKey(const Key('new-agent-advanced')));
+ await expandNewAgentAdvanced(tester);
await tester.pump();
expect(
find.textContaining('If harness-remote-box uses an older Harness CLI'),
@@ -142,7 +142,7 @@ void main() {
);
await chooseAgent(tester, 'codex');
await tester.ensureVisible(find.byKey(const Key('new-agent-advanced')));
- await tester.tap(find.byKey(const Key('new-agent-advanced')));
+ await expandNewAgentAdvanced(tester);
await tester.pumpAndSettle();
await tester.ensureVisible(
find.byKey(const Key('new-agent-permission-mode')),
@@ -184,7 +184,12 @@ void main() {
expect(retry, findsNothing);
expect(find.text('20260907'), findsOneWidget);
expect(find.text(pickedFolder), findsNothing);
- expect(tester.widget<AgentPicker>(find.byType(AgentPicker)).value, 'codex');
+ expect(
+ tester
+ .widget<AgentPicker>(find.byKey(const Key('new-agent-agent-picker')))
+ .value,
+ 'codex',
+ );
expect(app.profileChecks, ['machine-1']);
expect(
find.byKey(const Key('new-agent-codex-profile-field')),
@@ -224,6 +229,7 @@ void main() {
await tester.tap(find.byKey(const Key('new-agent-retry-check')));
await tester.pump();
await tester.pump();
+ await expandNewAgentAdvanced(tester);
final otherMachine = find.byKey(
const ValueKey('new-agent-machine-machine-2'),
);
@@ -232,7 +238,7 @@ void main() {
await tester.pumpAndSettle();
await chooseAgent(tester, 'codex');
await tester.ensureVisible(find.byKey(const Key('new-agent-advanced')));
- await tester.tap(find.byKey(const Key('new-agent-advanced')));
+ await expandNewAgentAdvanced(tester);
await tester.pumpAndSettle();
expect(
find.text('Checking whether Other computer supports Codex profiles…'),
@@ -251,7 +257,12 @@ void main() {
.value,
'machine-2',
);
- expect(tester.widget<AgentPicker>(find.byType(AgentPicker)).value, 'codex');
+ expect(
+ tester
+ .widget<AgentPicker>(find.byKey(const Key('new-agent-agent-picker')))
+ .value,
+ 'codex',
+ );
expect(find.text('20260907'), findsNothing);
expect(app.launches, isEmpty);
expect(tester.takeException(), isNull);
@@ -306,6 +317,7 @@ class _RetryNotifier extends AppNotifier {
String? permissionMode,
String? codexHome,
String? dsh,
+ GridModel? model,
String? prompt,
String? name,
String? agent,
diff --git a/desktop/test/new_agent_permission_mode_test.dart b/desktop/test/new_agent_permission_mode_test.dart
index 071c9b279..6ec3b0d12 100644
--- a/desktop/test/new_agent_permission_mode_test.dart
+++ b/desktop/test/new_agent_permission_mode_test.dart
@@ -55,6 +55,7 @@ class _Notifier extends AppNotifier {
String? permissionMode,
String? codexHome,
String? dsh,
+ GridModel? model,
String? prompt,
String? name,
String? agent,
diff --git a/desktop/test/new_agent_project_picker_test.dart b/desktop/test/new_agent_project_picker_test.dart
index 4c2522b4d..603b0a594 100644
--- a/desktop/test/new_agent_project_picker_test.dart
+++ b/desktop/test/new_agent_project_picker_test.dart
@@ -72,6 +72,7 @@ class _App extends AppNotifier {
String? swarmId,
PaneSplitRequest? split,
String? dsh,
+ GridModel? model,
String? prompt,
String? name,
String? agent,
@@ -129,6 +130,7 @@ void main() {
);
await tester.tap(find.text('Open'));
await tester.pumpAndSettle();
+ await expandNewAgentAdvanced(tester);
}
Future<void> recent(WidgetTester tester, String name) async {
@@ -200,6 +202,7 @@ void main() {
await tester.pumpAndSettle();
await tester.tap(find.text('Open'));
await tester.pumpAndSettle();
+ await expandNewAgentAdvanced(tester);
expect(tester.widget<AppChoiceTile>(newProject).selected, isTrue);
expect(
tester.widget<AppSelectField<String>>(recentProject).selected,
diff --git a/desktop/test/new_agent_rows_and_task_test.dart b/desktop/test/new_agent_rows_and_task_test.dart
index 92065ab7a..416781704 100644
--- a/desktop/test/new_agent_rows_and_task_test.dart
+++ b/desktop/test/new_agent_rows_and_task_test.dart
@@ -121,6 +121,7 @@ class _App extends AppNotifier {
String? permissionMode,
String? codexHome,
String? dsh,
+ GridModel? model,
String? prompt,
String? name,
String? agent,
@@ -188,8 +189,8 @@ Future<_App> _open(
}
Future<void> _search(WidgetTester tester, String query) async {
- if (agentSearch.evaluate().isEmpty) await openAgentSearch(tester);
- await tester.enterText(agentSearch, query);
+ if (harnessSearch.evaluate().isEmpty) await openHarnessSearch(tester);
+ await tester.enterText(harnessSearch, query);
await tester.pump();
}
@@ -206,11 +207,13 @@ Future<void> _create(WidgetTester tester) async {
await tester.pump();
}
-Finder _row(String id) => find.byKey(ValueKey('new-agent-agent-row-$id'));
+String _kind(String id) => id.contains('/') ? 'harness' : 'agent';
+Finder _row(String id) =>
+ find.byKey(ValueKey('new-agent-${_kind(id)}-row-$id'));
/// The row's byline and the line under its name, as drawn.
({String? by, String? line}) _read(WidgetTester tester, String id) {
- final by = find.byKey(ValueKey('new-agent-agent-row-by-$id'));
+ final by = find.byKey(ValueKey('new-agent-${_kind(id)}-row-by-$id'));
final subtitle = tester.widget<ListTile>(_row(id)).subtitle;
return (
by: by.evaluate().isEmpty ? null : tester.widget<Text>(by).data,
@@ -254,7 +257,11 @@ void main() {
await _search(tester, 'bare');
expect(_read(tester, 'someone/bare'), (by: null, line: null));
- await _search(tester, 'claude');
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ await openAgentSearch(tester);
+ await tester.enterText(agentSearch, 'claude');
+ await tester.pump();
expect(_read(tester, 'claude'), (
by: 'by Anthropic',
line: 'Work with Claude directly in your codebase',
@@ -272,7 +279,7 @@ void main() {
));
await _search(tester, 'earth');
expect(
- find.byKey(const ValueKey('new-agent-agent-row-someone/earth')),
+ find.byKey(const ValueKey('new-agent-harness-row-someone/earth')),
findsNothing,
reason: 'a harness this build has no face for waits for the machine',
);
@@ -283,38 +290,35 @@ void main() {
await _open(tester);
// A name, then an author, then the line under a name.
- // Among equals a harness before an engine: MuJoCo, then Antigravity,
- // both by Google.
await _search(tester, 'google');
- expect(agentRows(tester), [
+ expect(harnessRows(tester), [
'someone/earth',
'autonomous/mujoco',
- 'agy',
'someone/maps',
]);
// The Store's Simulation shelf includes physics and robotics.
await _search(tester, 'simulation');
- expect(agentRows(tester), contains('autonomous/mujoco'));
- expect(agentRows(tester), contains('someone/earth'));
+ expect(harnessRows(tester), contains('autonomous/mujoco'));
+ expect(harnessRows(tester), contains('someone/earth'));
// The domain itself, where no line under a name says it.
await _search(tester, 'documents');
- expect(agentRows(tester), ['autonomous/typst']);
+ expect(harnessRows(tester), ['autonomous/typst']);
// A package with no domain is on the Store's Other shelf.
await _search(tester, 'other');
- expect(agentRows(tester), contains('someone/maps'));
+ expect(harnessRows(tester), contains('someone/maps'));
// An author the row draws.
await _search(tester, 'gmbh');
- expect(agentRows(tester), ['autonomous/typst']);
+ expect(harnessRows(tester), ['autonomous/typst']);
});
testWidgets('the preview names whose it is and what it is', (tester) async {
await _open(tester);
await _search(tester, 'deepmind');
- expect(agentRows(tester), ['autonomous/mujoco']);
- final preview = find.byKey(const ValueKey('new-agent-agent-preview'));
+ expect(harnessRows(tester), ['autonomous/mujoco']);
+ final preview = find.byKey(const ValueKey('new-agent-harness-preview'));
expect(preview, findsNothing);
- final input = tester.widget<TextField>(agentSearch);
+ final input = tester.widget<TextField>(harnessSearch);
final value = input.controller!.value;
await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft);
await tester.sendKeyEvent(LogicalKeyboardKey.slash);
@@ -517,7 +521,7 @@ void main() {
'pushing the button out of the footer', (tester) async {
final app = await _open(tester, size: const Size(900, 720));
app.pendingInstall = Completer<String?>();
- await chooseAgent(tester, 'someone/long');
+ await chooseHarness(tester, 'someone/long');
await _pickFolder(tester);
await _create(tester);
await tester.pump();
diff --git a/desktop/test/new_agent_terminal_test.dart b/desktop/test/new_agent_terminal_test.dart
index a17181421..48ae9a1fd 100644
--- a/desktop/test/new_agent_terminal_test.dart
+++ b/desktop/test/new_agent_terminal_test.dart
@@ -63,6 +63,7 @@ class _Notifier extends AppNotifier {
String? permissionMode,
String? codexHome,
String? dsh,
+ GridModel? model,
String? prompt,
String? name,
String? agent,
@@ -138,8 +139,9 @@ void main() {
await tester.pump();
}
- String engineField(WidgetTester tester) =>
- tester.widget<AgentPicker>(find.byType(AgentPicker)).value;
+ String engineField(WidgetTester tester) => tester
+ .widget<AgentPicker>(find.byKey(const Key('new-agent-agent-picker')))
+ .value;
testWidgets(
'the terminal is listed with what the machine has, and never needs installing',
diff --git a/desktop/test/new_harness_accessibility_test.dart b/desktop/test/new_harness_accessibility_test.dart
index b3b101fb0..edf014e25 100644
--- a/desktop/test/new_harness_accessibility_test.dart
+++ b/desktop/test/new_harness_accessibility_test.dart
@@ -56,7 +56,7 @@ void main() {
expect(box.engine, 'claude');
expect(harnessChoicesActive(tester), isFalse);
await key(tester, LogicalKeyboardKey.arrowDown);
- expect(box.field, NewHarnessField.machine);
+ expect(box.field, NewHarnessField.model);
expect(input, isEmpty);
semantics.dispose();
await tester.pumpWidget(const SizedBox());
diff --git a/desktop/test/new_harness_box_test.dart b/desktop/test/new_harness_box_test.dart
index d1175090e..3b0c8234c 100644
--- a/desktop/test/new_harness_box_test.dart
+++ b/desktop/test/new_harness_box_test.dart
@@ -120,7 +120,7 @@ void main() {
},
);
- test('agent choices consolidate prototypes while preserving the actual launch id', () {
+ test('harness choices consolidate prototypes while preserving the actual launch id', () {
final app = createApp();
addTearDown(app.dispose);
final box = NewHarnessController(app, machineId: 'm', engine: 'codex');
@@ -145,7 +145,7 @@ void main() {
engine: 'claude',
),
]);
- box.focusField(NewHarnessField.agent);
+ box.focusField(NewHarnessField.harness);
final ollama = box.options.where((o) => o.title == 'Ollama').single;
expect(ollama.id, 'local/ollama');
expect(
@@ -157,8 +157,9 @@ void main() {
isFalse,
);
box.accept(ollama);
- expect(box.engine, 'local/ollama');
- expect(box.agentLabel, 'Ollama');
+ expect(box.harnessId, 'local/ollama');
+ expect(box.engine, 'codex');
+ expect(box.harnessLabel, 'Ollama');
});
test('a named new project gets that folder, and never a changed name', () async {
@@ -223,16 +224,18 @@ void main() {
expect(box.isCurrent(box.selected!), isTrue);
expect(box.returnCreates, isFalse);
box.nextField(-1);
- expect(box.field, NewHarnessField.projectMenu);
+ expect(box.field, NewHarnessField.harness);
expect(box.task, 'fix the flaky login test');
});
- test('the main loop follows Agent, Machine, Project and modes remain available to advanced drafts', () {
+ test('the main loop follows Harness, Agent, Machine, Project and modes remain available to advanced drafts', () {
final app = createApp();
final box = NewHarnessController(app, machineId: 'm', engine: 'claude');
addTearDown(box.dispose);
expect(box.fields, [
+ NewHarnessField.harness,
NewHarnessField.agent,
+ NewHarnessField.model,
NewHarnessField.machine,
NewHarnessField.projectMenu,
]);
@@ -249,6 +252,7 @@ void main() {
box.accept();
expect(box.isTerminal, isTrue);
expect(box.fields, [
+ NewHarnessField.harness,
NewHarnessField.agent,
NewHarnessField.machine,
NewHarnessField.projectMenu,
@@ -886,7 +890,7 @@ void main() {
),
);
await tester.pump();
- expect(box.field, NewHarnessField.projectMenu);
+ expect(box.field, NewHarnessField.harness);
await openLaunchRow(tester, 'agent');
await typeHarnessQuery(tester, 'clau');
expect(box.engine, 'codex');
diff --git a/desktop/test/new_harness_entry_rules_test.dart b/desktop/test/new_harness_entry_rules_test.dart
index 4375da0ce..709281eca 100644
--- a/desktop/test/new_harness_entry_rules_test.dart
+++ b/desktop/test/new_harness_entry_rules_test.dart
@@ -188,7 +188,7 @@ void main() {
findsNothing,
);
}
- expect(find.text('New Harness'), findsOneWidget);
+ expect(find.text('[ New Harness ]'), findsOneWidget);
expect(connections['m']!.starts, isEmpty);
await acceptSetupOrSearch(tester);
expect(connections['m']!.starts, hasLength(1));
@@ -223,14 +223,14 @@ void main() {
box(tester).task = 'Workshop task';
if (closeFirst) await dismiss(tester);
await product(tester, 'autonomous/blender', task: task);
- expect(box(tester).engine, 'autonomous/blender');
+ expect(box(tester).harnessId, 'autonomous/blender');
expect(box(tester).projectLabel, startsWith('~/harnesses/blender-'));
expect(box(tester).project.generated, isNotNull);
expect(box(tester).task, task ?? '');
expect(box(tester).placement, HarnessPlacement.newTab);
await dismiss(tester);
await product(tester, 'autonomous/workshop');
- expect(box(tester).engine, 'autonomous/workshop');
+ expect(box(tester).harnessId, 'autonomous/workshop');
expect(box(tester).projectLabel, '~/harnesses/workshop-design');
expect(box(tester).task, 'Workshop task');
expect(connections.values.expand((c) => c.starts), isEmpty);
@@ -331,22 +331,57 @@ void main() {
);
}
- testWidgets('Store Open overrides an agent changed inside its saved draft', (
+ testWidgets('Store Open restores its harness after switching to Coding', (
tester,
) async {
await mount(tester);
await product(tester, 'autonomous/blender');
+ box(tester).focusField(NewHarnessField.harness);
+ box(tester).accept(
+ const NewHarnessOption(
+ id: NewHarnessController.codingId,
+ title: 'Coding',
+ ),
+ );
box(tester).focusField(NewHarnessField.agent);
box(tester).accept(const NewHarnessOption(id: 'codex', title: 'Codex'));
expect(box(tester).engine, 'codex');
await dismiss(tester);
await product(tester, 'autonomous/blender');
- expect(box(tester).engine, 'autonomous/blender');
+ expect(box(tester).harnessId, 'autonomous/blender');
expect(box(tester).projectLabel, startsWith('~/harnesses/blender-'));
await dismiss(tester);
await tester.pumpWidget(const SizedBox());
});
+ testWidgets(
+ 'an explicit coding engine reopens its draft and overrides a different harness',
+ (tester) async {
+ await mount(tester);
+ await product(tester, 'codex');
+ expect(box(tester).engine, 'codex');
+ expect(box(tester).harnessId, isNull);
+ box(tester).setFolder('/work/explicit-code');
+ await dismiss(tester);
+ await product(tester, 'codex');
+ expect(box(tester).project.folder, '/work/explicit-code');
+ box(tester).focusField(NewHarnessField.harness);
+ box(tester).applyOption(
+ box(tester).options
+ .singleWhere((option) => option.id == 'autonomous/blender'),
+ );
+ await dismiss(tester);
+ await product(tester, 'codex');
+ expect(box(tester).engine, 'codex');
+ expect(box(tester).harnessId, isNull);
+ expect(
+ connections.values.expand((connection) => connection.starts),
+ isEmpty,
+ );
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
testWidgets(
'an in-flight or uncertain Store start cannot be replaced or retried as a new task',
(tester) async {
@@ -370,7 +405,7 @@ void main() {
expect(original.error, contains('Check the pending start'));
await dismiss(tester);
await product(tester, 'autonomous/blender');
- expect(box(tester).engine, 'autonomous/blender');
+ expect(box(tester).harnessId, 'autonomous/blender');
await dismiss(tester);
await product(tester, 'autonomous/workshop', task: 'A different example');
expect(box(tester).checking, isTrue);
@@ -476,7 +511,7 @@ void main() {
await tester.pump();
await key(tester, shortcut, cmd: true);
await acceptSetupOrSearch(tester);
- expect(box(tester).engine, 'autonomous/typst');
+ expect(box(tester).harnessId, 'autonomous/typst');
expect(box(tester).project.folder, '/work/release-notes');
expect(box(tester).task, isEmpty);
await dismiss(tester);
diff --git a/desktop/test/new_harness_form_test.dart b/desktop/test/new_harness_form_test.dart
index a7d39fde3..b6838823e 100644
--- a/desktop/test/new_harness_form_test.dart
+++ b/desktop/test/new_harness_form_test.dart
@@ -7,7 +7,8 @@ import 'package:harness/widgets/new_harness_form.dart';
import 'package:harness/ws/ws_conn.dart';
import 'support/mixed_agents.dart';
-import 'support/launch_menu.dart' show harnessChoicesActive;
+import 'support/launch_menu.dart'
+ show harnessChoicesActive, focusLaunchRow, openLaunchRow;
import 'swarm_state_test.dart' show createApp;
/// The setup form is driven by six keys and nothing else, so every one of
@@ -55,6 +56,7 @@ void main() {
WidgetTester tester, {
bool created = false,
String? engine,
+ String focus = 'project',
}) async {
final app = createApp(connectionForTest: (_) => _Git());
seedMixedAgents(app);
@@ -88,6 +90,7 @@ void main() {
),
);
await tester.pumpAndSettle();
+ await focusLaunchRow(tester, focus);
return box;
}
@@ -103,33 +106,39 @@ void main() {
await tester.pumpAndSettle();
}
- testWidgets('shared setup fields stay available for every agent', (
+ testWidgets('core fields stay visible and advanced fields expand', (
tester,
) async {
await mount(tester);
for (final label in [
- 'Project',
+ 'Harness',
'Agent',
'Machine',
+ 'Project',
+ // Branch belongs to Project, so it is a core field, not an advanced one.
'Branch',
- 'Worktree',
- 'Approvals',
+ 'Advanced',
]) {
- expect(find.text(label), findsOneWidget, reason: '$label must not go');
+ expect(find.text(label), findsOneWidget);
+ }
+ expect(find.text('Worktree'), findsNothing);
+ await openLaunchRow(tester, 'advanced');
+ for (final label in ['Worktree', 'Approvals']) {
+ expect(find.text(label), findsOneWidget);
}
});
testWidgets('down and up walk the rows and wrap', (tester) async {
- final box = await mount(tester);
- expect(box.field, NewHarnessField.projectMenu);
+ final box = await mount(tester, focus: 'harness');
+ expect(box.field, NewHarnessField.harness);
await press(tester, LogicalKeyboardKey.arrowDown);
expect(box.field, NewHarnessField.agent);
await press(tester, LogicalKeyboardKey.arrowDown);
- expect(box.field, NewHarnessField.machine);
+ expect(box.field, NewHarnessField.model);
await press(tester, LogicalKeyboardKey.arrowUp);
expect(box.field, NewHarnessField.agent);
await press(tester, LogicalKeyboardKey.arrowUp);
- expect(box.field, NewHarnessField.projectMenu);
+ expect(box.field, NewHarnessField.harness);
});
// Page Up/Down are where stepping a value in place lives — the arrows are
@@ -138,7 +147,7 @@ void main() {
testWidgets('page down walks every agent instead of bouncing between two', (
tester,
) async {
- final box = await mount(tester);
+ final box = await mount(tester, focus: 'harness');
await press(tester, LogicalKeyboardKey.arrowDown);
expect(box.field, NewHarnessField.agent);
final seen = <String>{box.engine};
@@ -154,7 +163,7 @@ void main() {
});
testWidgets('the page keys step opposite ways and return', (tester) async {
- final box = await mount(tester);
+ final box = await mount(tester, focus: 'harness');
await press(tester, LogicalKeyboardKey.arrowDown);
final first = box.engine;
await press(tester, LogicalKeyboardKey.pageDown);
@@ -178,7 +187,7 @@ void main() {
testWidgets('right hands the keys to the choices without taking a value', (
tester,
) async {
- final box = await mount(tester);
+ final box = await mount(tester, focus: 'harness');
await press(tester, LogicalKeyboardKey.arrowDown);
expect(box.field, NewHarnessField.agent);
final engine = box.engine;
@@ -195,7 +204,7 @@ void main() {
});
testWidgets('left gives the keys back to the rows', (tester) async {
- final box = await mount(tester);
+ final box = await mount(tester, focus: 'harness');
await press(tester, LogicalKeyboardKey.arrowDown);
await press(tester, LogicalKeyboardKey.arrowRight);
expect(harnessChoicesActive(tester), isTrue);
@@ -209,11 +218,12 @@ void main() {
reason: 'The choices stay on screen, they just stop holding the keys.',
);
await press(tester, LogicalKeyboardKey.arrowDown);
- expect(box.field, NewHarnessField.machine, reason: 'Rows move again.');
+ // Model sits between Agent and Machine on this form.
+ expect(box.field, NewHarnessField.model, reason: 'Rows move again.');
});
testWidgets('left edits the search text before it leaves it', (tester) async {
- final box = await mount(tester);
+ final box = await mount(tester, focus: 'harness');
await press(tester, LogicalKeyboardKey.arrowDown);
await type(tester, 'cod');
expect(harnessChoicesActive(tester), isTrue);
@@ -223,7 +233,7 @@ void main() {
});
testWidgets('left on the rows changes nothing', (tester) async {
- final box = await mount(tester);
+ final box = await mount(tester, focus: 'harness');
await press(tester, LogicalKeyboardKey.arrowDown);
final engine = box.engine;
await press(tester, LogicalKeyboardKey.arrowLeft);
@@ -236,9 +246,7 @@ void main() {
// browse, so there is no column to go to.
testWidgets('worktree flips on its own row, without a list', (tester) async {
final box = await mount(tester);
- for (var i = 0; i < 4; i++) {
- await press(tester, LogicalKeyboardKey.arrowDown);
- }
+ await focusLaunchRow(tester, 'worktree');
final was = box.worktree;
await press(tester, LogicalKeyboardKey.arrowRight);
expect(box.worktree, !was);
@@ -388,12 +396,16 @@ void main() {
});
testWidgets('Tab walks the rows and never escapes the form', (tester) async {
- final box = await mount(tester);
- for (var i = 0; i < 3; i++) {
+ final box = await mount(tester, focus: 'harness');
+ for (var i = 0; i < 4; i++) {
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
await tester.pumpAndSettle();
}
- expect(box.field, NewHarnessField.branch, reason: 'Tab walks the rows.');
+ expect(
+ box.field,
+ NewHarnessField.projectMenu,
+ reason: 'Tab walks the rows.',
+ );
// The real bug: traversal moved focus out and the form went deaf. Up
// rather than down, since the row under Branch edits no field at all.
await press(tester, LogicalKeyboardKey.arrowUp);
@@ -495,7 +507,7 @@ void main() {
tester,
) async {
final box = await mount(tester);
- expect(find.text('New Harness'), findsOneWidget);
+ expect(find.text('[ New Harness ]'), findsOneWidget);
expect(
find.text('Open Folder'),
findsOneWidget,
@@ -516,7 +528,7 @@ void main() {
// Escape hands the arrows back to the rows; the list stays on screen.
await press(tester, LogicalKeyboardKey.escape);
expect(find.text('Open Folder'), findsOneWidget);
- await press(tester, LogicalKeyboardKey.arrowDown);
+ await focusLaunchRow(tester, 'agent');
expect(box.field, NewHarnessField.agent);
});
@@ -583,7 +595,7 @@ void main() {
testWidgets('the right column follows the focused row', (tester) async {
await mount(tester);
expect(find.text('Open Folder'), findsOneWidget);
- await press(tester, LogicalKeyboardKey.arrowDown);
+ await focusLaunchRow(tester, 'agent');
expect(
find.text('Open Folder'),
findsNothing,
@@ -596,7 +608,7 @@ void main() {
tester,
) async {
await mount(tester);
- expect(find.text('New Harness'), findsOneWidget);
+ expect(find.text('[ New Harness ]'), findsOneWidget);
expect(
tester
.widget<Semantics>(
@@ -633,9 +645,7 @@ void main() {
expect(input().showCursor, isFalse);
// Worktree is a boolean: no list, so no prompt either.
await press(tester, LogicalKeyboardKey.escape);
- for (var i = 0; i < 4; i++) {
- await press(tester, LogicalKeyboardKey.arrowDown);
- }
+ await focusLaunchRow(tester, 'worktree');
expect(find.textContaining('Search '), findsNothing);
});
@@ -694,6 +704,7 @@ void main() {
),
);
await tester.pumpAndSettle();
+ await focusLaunchRow(tester, 'project');
await type(tester, 'harness');
// "Open Folder" in the menu opens a path prompt; the chooser itself is
// a row inside THAT list, which must be on screen before anything typed.
@@ -749,9 +760,7 @@ void main() {
tester,
) async {
final box = await mount(tester);
- for (var i = 0; i < 3; i++) {
- await press(tester, LogicalKeyboardKey.arrowDown);
- }
+ await focusLaunchRow(tester, 'branch');
expect(box.field, NewHarnessField.branch);
await type(tester, 'spike');
await highlight(
@@ -769,11 +778,9 @@ void main() {
testWidgets('the worktree row reads as a question', (tester) async {
final box = await mount(tester);
+ await focusLaunchRow(tester, 'worktree');
expect(find.text('Worktree'), findsOneWidget);
expect(find.text('Yes'), findsOneWidget);
- for (var i = 0; i < 4; i++) {
- await press(tester, LogicalKeyboardKey.arrowDown);
- }
await press(tester, LogicalKeyboardKey.arrowRight);
expect(box.worktree, isFalse);
expect(find.text('No'), findsOneWidget);
@@ -783,8 +790,9 @@ void main() {
tester,
) async {
final box = await mount(tester, engine: 'codex');
+ await openLaunchRow(tester, 'advanced');
expect(find.text('Profile'), findsOneWidget);
- await press(tester, LogicalKeyboardKey.arrowDown);
+ await focusLaunchRow(tester, 'agent');
await type(tester, 'claude');
expect(box.engine, 'codex');
expect(find.text('Profile'), findsOneWidget);
@@ -792,9 +800,7 @@ void main() {
expect(box.engine, 'claude');
expect(find.text('Profile'), findsNothing);
- for (var i = 0; i < 4; i++) {
- await press(tester, LogicalKeyboardKey.arrowDown);
- }
+ await focusLaunchRow(tester, 'approvals');
expect(box.field, NewHarnessField.mode);
await press(tester, LogicalKeyboardKey.tab);
expect(
@@ -817,9 +823,7 @@ void main() {
isTrue,
);
- for (var i = 0; i < 4; i++) {
- await press(tester, LogicalKeyboardKey.arrowUp);
- }
+ await focusLaunchRow(tester, 'agent');
await type(tester, 'codex');
expect(find.text('Profile'), findsNothing);
await press(tester, LogicalKeyboardKey.enter);
diff --git a/desktop/test/new_harness_git_test.dart b/desktop/test/new_harness_git_test.dart
index 71ba7bd94..a7e491a39 100644
--- a/desktop/test/new_harness_git_test.dart
+++ b/desktop/test/new_harness_git_test.dart
@@ -1076,7 +1076,7 @@ void main() {
);
await tester.pump();
await openLaunchRow(tester, 'start');
- expect(find.text('New Harness').hitTestable(), findsOneWidget);
+ expect(find.text('[ New Harness ]').hitTestable(), findsOneWidget);
expect(tester.takeException(), isNull);
if (renderDir != null) {
await expectLater(
@@ -1104,6 +1104,9 @@ void main() {
find.byKey(const ValueKey('new-harness-field-branch')),
findsOneWidget,
);
+ // Branch no longer lives behind Advanced, so reaching it opened nothing;
+ // Worktree still does, and is opened here to be checked.
+ await openLaunchRow(tester, 'advanced');
expect(
find.byKey(const ValueKey('new-harness-field-worktree')),
findsOneWidget,
diff --git a/desktop/test/new_harness_grid_test.dart b/desktop/test/new_harness_grid_test.dart
new file mode 100644
index 000000000..e54326a1e
--- /dev/null
+++ b/desktop/test/new_harness_grid_test.dart
@@ -0,0 +1,366 @@
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/shortcuts/app_keymap.dart';
+import 'package:harness/shortcuts/keymap_host.dart';
+import 'package:harness/state/new_harness.dart';
+import 'package:harness/widgets/new_harness_form.dart';
+import 'package:harness/ws/ws_conn.dart';
+
+import 'keymap_host_test.dart' show MemoryKeymap, key;
+import 'support/launch_menu.dart' show focusLaunchRow;
+import 'support/mixed_agents.dart';
+import 'swarm_state_test.dart' show createApp;
+
+/// Records what the form asks the daemon for, so a test can tell whether a
+/// key STARTED an agent rather than inferring it from the screen.
+class _Daemon extends WsConn {
+ _Daemon()
+ : super(
+ wsBaseUrl: 'ws://fixture.invalid',
+ autonomousEnv: 'test',
+ machineId: 'm',
+ accessTokenProvider: (_, _) async => '',
+ onAuthFailure: (_) {},
+ onEvent: (_) {},
+ onStatus: (_) {},
+ );
+
+ final requests = <String>[];
+
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) async {
+ requests.add(type);
+ if (type == 'engines_probe') return {'engines': []};
+ if (type == 'dsh_list') return {'dsh': []};
+ if (type == 'git_project_info') {
+ return {
+ 'isGit': true,
+ 'branch': 'main',
+ 'branches': [
+ {'ref': 'refs/heads/main', 'name': 'main'},
+ ],
+ };
+ }
+ return {};
+ }
+}
+
+void main() {
+ Future<(NewHarnessController, _Daemon)> mount(
+ WidgetTester tester, {
+ String focus = 'agent',
+ double width = 820,
+ MemoryKeymap? keymap,
+ }) async {
+ final daemon = _Daemon();
+ final app = createApp(connectionForTest: (_) => daemon);
+ seedMixedAgents(app);
+ final box = NewHarnessController(
+ app,
+ machineId: 'm',
+ folder: '/work/harness-app-landing-page',
+ );
+ addTearDown(app.dispose);
+ addTearDown(box.dispose);
+ keymap ??= MemoryKeymap();
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: ThemeData.dark(),
+ home: KeymapProvider(
+ keymap: keymap,
+ child: KeymapHost(
+ keymap: keymap,
+ enabled: () => true,
+ actions: const {},
+ child: Scaffold(
+ body: Center(
+ child: SizedBox(
+ width: width,
+ height: 450,
+ child: NewHarnessForm(
+ controller: box,
+ onClose: () {},
+ onCreated: () {},
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ await focusLaunchRow(tester, focus);
+ return (box, daemon);
+ }
+
+ group('⇧⏎ starts from any field', () {
+ testWidgets('from a value row, without walking to the button', (
+ tester,
+ ) async {
+ final (_, daemon) = await mount(tester);
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(
+ daemon.requests,
+ isNot(contains('agent_create')),
+ reason: 'Plain Return on a value row must still never start.',
+ );
+ await key(tester, LogicalKeyboardKey.enter, shift: true);
+ expect(daemon.requests, contains('agent_create'));
+ });
+
+ testWidgets('taking the value highlighted in a live list first', (
+ tester,
+ ) async {
+ final (box, daemon) = await mount(tester);
+ await key(tester, LogicalKeyboardKey.arrowRight);
+ await key(tester, LogicalKeyboardKey.arrowDown);
+ final wanted = box.selected!.id;
+ expect(wanted, isNot(box.engine));
+ await key(tester, LogicalKeyboardKey.enter, shift: true);
+ expect(
+ box.engine,
+ wanted,
+ reason: 'The highlight is what the person was looking at.',
+ );
+ expect(daemon.requests, contains('agent_create'));
+ });
+
+ testWidgets('the button prints the key that reaches it', (tester) async {
+ await mount(tester);
+ expect(find.text('[ New Harness ]'), findsOneWidget);
+ expect(find.textContaining('⇧'), findsWidgets);
+ });
+ });
+
+ group('one grid', () {
+ double heightOf(WidgetTester tester, String field) =>
+ tester.getSize(find.byKey(ValueKey('new-harness-field-$field'))).height;
+
+ testWidgets('every field is exactly one row', (tester) async {
+ await mount(tester);
+ final row = heightOf(tester, 'agent');
+ for (final field in ['harness', 'model', 'machine', 'project']) {
+ expect(heightOf(tester, field), row, reason: '$field drifted');
+ }
+ });
+
+ testWidgets('a wrapped notice is a whole number of rows', (tester) async {
+ final (box, _) = await mount(tester, focus: 'model');
+ final row = heightOf(tester, 'agent');
+ final notice = box.modelNotice;
+ expect(notice, isNotNull);
+ final height = tester.getSize(find.text(notice!)).height;
+ expect(height / row, closeTo((height / row).roundToDouble(), .01));
+ expect(height, greaterThan(row), reason: 'The fixture wraps it.');
+ });
+
+ testWidgets('the right pane has one text column', (tester) async {
+ final (box, _) = await mount(tester, focus: 'model');
+ double left(Finder finder) => tester.getTopLeft(finder).dx;
+ final column = left(find.byKey(const ValueKey('new-harness-query')));
+ expect(left(find.text(box.modelNotice!)), closeTo(column, .5));
+ expect(left(find.text('Subscription')), closeTo(column, .5));
+ expect(left(find.text('Refresh models')), closeTo(column, .5));
+ });
+
+ testWidgets('every value on the left starts on one column', (tester) async {
+ final (box, _) = await mount(tester);
+ // The same words can be a choice on the right; look inside each field.
+ double left(String field, String text) => tester
+ .getTopLeft(
+ find.descendant(
+ of: find.byKey(ValueKey('new-harness-field-$field')),
+ matching: find.text(text),
+ ),
+ )
+ .dx;
+ final column = left('agent', box.agentLabel);
+ expect(left('machine', box.machineLabel), closeTo(column, .5));
+ expect(left('project', box.projectLabel), closeTo(column, .5));
+ });
+
+ testWidgets('a blank row sets Advanced apart from the core fields', (
+ tester,
+ ) async {
+ await mount(tester);
+ // Branch is the last core field now, under Project.
+ final project = tester.getRect(
+ find.byKey(const ValueKey('new-harness-field-branch')),
+ );
+ final advanced = tester.getRect(
+ find.byKey(const ValueKey('new-harness-field-advanced')),
+ );
+ expect(advanced.top - project.bottom, closeTo(project.height, .5));
+ });
+ });
+
+ group('small reads', () {
+ testWidgets('the hint sits against the caret, with no space between', (
+ tester,
+ ) async {
+ final (box, _) = await mount(tester);
+ await key(tester, LogicalKeyboardKey.arrowRight);
+ final hint = tester
+ .widget<TextField>(find.byKey(const ValueKey('new-harness-query')))
+ .decoration!
+ .hintText!;
+ expect(hint, isNot(startsWith(' ')));
+ expect(hint, 'Search ${box.field.name}');
+ });
+
+ testWidgets('the key hint spaces its keys: ⇧ ⏎, not ⇧⏎', (tester) async {
+ await mount(tester);
+ final hint = find.textContaining('⇧');
+ expect(tester.widget<Text>(hint).data, startsWith('⇧ '));
+ });
+
+ testWidgets('this computer leads the machine list', (tester) async {
+ final (box, _) = await mount(tester, focus: 'machine');
+ // Make the machine that lists LAST the local one, so this passes only
+ // if the list really moves it to the top.
+ final last = box.options.lastWhere((row) => !row.synthetic);
+ expect(last.id, isNot(box.options.first.id));
+ box.app.stateOf(last.id)!.localOnly = true;
+ box.focusField(NewHarnessField.agent);
+ box.focusField(NewHarnessField.machine);
+ await tester.pumpAndSettle();
+ expect(box.options.firstWhere((row) => !row.synthetic).id, last.id);
+ });
+
+ testWidgets('usable machines come before unusable ones', (tester) async {
+ final (box, _) = await mount(tester, focus: 'machine');
+ final rows = box.options.where((row) => !row.synthetic).toList();
+ final firstUnusable = rows.indexWhere((row) => !row.enabled);
+ expect(firstUnusable, isNonNegative, reason: 'fixture has one');
+ expect(
+ rows.skip(firstUnusable).every((row) => !row.enabled),
+ isTrue,
+ reason: 'No usable machine may follow an unusable one.',
+ );
+ });
+
+ testWidgets('Terminal needs no gloss', (tester) async {
+ await mount(tester);
+ expect(find.text('A shell, no agent'), findsNothing);
+ });
+ });
+
+ // One test per behaviour a coverage run found untested among the lines this
+ // branch changed. Each names the behaviour, not the line.
+ group('reached only by less common paths', () {
+ testWidgets('a field the controller moves to opens Advanced to show it', (
+ tester,
+ ) async {
+ final (box, _) = await mount(tester);
+ expect(box.advancedOpen, isFalse);
+ box.focusField(NewHarnessField.mode);
+ await tester.pumpAndSettle();
+ expect(box.advancedOpen, isTrue);
+ expect(
+ find.byKey(const ValueKey('new-harness-field-approvals')),
+ findsOneWidget,
+ );
+ });
+
+ testWidgets('the page keys open and close Advanced from its own row', (
+ tester,
+ ) async {
+ final (box, _) = await mount(tester, focus: 'advanced');
+ await key(tester, LogicalKeyboardKey.pageDown);
+ expect(box.advancedOpen, isTrue);
+ await key(tester, LogicalKeyboardKey.pageUp);
+ expect(box.advancedOpen, isFalse);
+ });
+
+ testWidgets('clicking the Advanced row opens and closes it', (
+ tester,
+ ) async {
+ final (box, _) = await mount(tester);
+ final advanced = find.byKey(const ValueKey('new-harness-field-advanced'));
+ await tester.tap(advanced);
+ await tester.pumpAndSettle();
+ expect(box.advancedOpen, isTrue);
+ await tester.tap(advanced);
+ await tester.pumpAndSettle();
+ expect(box.advancedOpen, isFalse);
+ });
+
+ testWidgets('⇧⏎ inside a door prompt finishes it, then starts', (
+ tester,
+ ) async {
+ final (box, daemon) = await mount(tester, focus: 'project');
+ box.focusField(NewHarnessField.projectName);
+ await tester.pumpAndSettle();
+ box.setQuery('ledger');
+ await tester.pumpAndSettle();
+ await key(tester, LogicalKeyboardKey.enter, shift: true);
+ expect(
+ box.projectLabel,
+ contains('ledger'),
+ reason: 'The name typed in the prompt is the project it starts in.',
+ );
+ expect(daemon.requests, contains('agent_create'));
+ });
+
+ testWidgets(
+ 'remapped next and previous keys move the rows, then the list',
+ (tester) async {
+ final keymap = MemoryKeymap()
+ ..apply(
+ '{"bindings":['
+ '{"keys":"ctrl+l","command":"picker.complete","when":"picker"},'
+ '{"keys":"ctrl+h","command":"picker.complete_back","when":"picker"}]}',
+ );
+ final (box, _) = await mount(tester, keymap: keymap);
+ expect(box.field, NewHarnessField.agent);
+ for (final (move, back) in [
+ (LogicalKeyboardKey.keyN, LogicalKeyboardKey.keyP),
+ (LogicalKeyboardKey.keyL, LogicalKeyboardKey.keyH),
+ ]) {
+ // The list closed: they walk the rows.
+ await key(tester, move, ctrl: true);
+ expect(box.field, NewHarnessField.model);
+ await key(tester, back, ctrl: true);
+ expect(box.field, NewHarnessField.agent);
+ // The list open: they walk the choices, and the row stays put.
+ await key(tester, LogicalKeyboardKey.arrowRight);
+ final first = box.selected!.id;
+ await key(tester, move, ctrl: true);
+ expect(box.selected!.id, isNot(first));
+ expect(box.field, NewHarnessField.agent);
+ await key(tester, back, ctrl: true);
+ expect(box.selected!.id, first);
+ await key(tester, LogicalKeyboardKey.escape);
+ }
+ },
+ );
+
+ testWidgets('⌘. opens and closes Advanced from any field', (tester) async {
+ final (box, _) = await mount(tester);
+ await key(tester, LogicalKeyboardKey.period, cmd: true);
+ expect(box.advancedOpen, isTrue);
+ await key(tester, LogicalKeyboardKey.period, cmd: true);
+ expect(box.advancedOpen, isFalse);
+ });
+
+ testWidgets('a narrow window keeps a status line on the grid', (
+ tester,
+ ) async {
+ final (box, _) = await mount(tester, width: 600);
+ box.warn('Machine is busy');
+ await tester.pumpAndSettle();
+ final status = find.byKey(const ValueKey('new-harness-status'));
+ expect(status, findsOneWidget);
+ final row = tester
+ .getSize(find.byKey(const ValueKey('new-harness-field-agent')))
+ .height;
+ expect(tester.getSize(status).height / row, closeTo(1, .01));
+ });
+ });
+}
diff --git a/desktop/test/new_harness_models_test.dart b/desktop/test/new_harness_models_test.dart
new file mode 100644
index 000000000..3f7ba3f3e
--- /dev/null
+++ b/desktop/test/new_harness_models_test.dart
@@ -0,0 +1,620 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/codex_profiles.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/state/new_harness.dart';
+import 'package:harness/usage/models_menu_controller.dart';
+import 'package:harness/usage/usage_accounts.dart';
+import 'package:harness/usage/usage_controller.dart';
+import 'package:harness/usage/usage_source.dart';
+import 'package:harness/usage/usage_window.dart';
+import 'package:harness/widgets/new_agent_dialog.dart';
+import 'package:harness/widgets/new_harness_form.dart';
+import 'package:harness/ws/ws_conn.dart';
+
+import 'support/agent_picker.dart';
+import 'support/launch_menu.dart';
+import 'support/mixed_agents.dart';
+import 'swarm_state_test.dart' show createApp;
+
+Map<String, dynamic> catalog() => {
+ 'supportsModelLaunch': true,
+ 'gridName': 'my-grid',
+ 'localModelEngines': ['codex', 'claude', 'opencode'],
+ 'grids': [
+ {
+ 'name': 'my-grid',
+ 'own': true,
+ 'models': [
+ {'id': 'Qwen-35B', 'node': 'Mac Studio'},
+ ],
+ },
+ {
+ 'name': 'team-grid',
+ 'own': false,
+ 'models': [
+ {'id': 'Qwen-35B', 'node': 'GPU Server'},
+ ],
+ },
+ ],
+};
+
+class _Connection extends WsConn {
+ _Connection()
+ : super(
+ wsBaseUrl: 'ws://fixture.invalid',
+ autonomousEnv: 'test',
+ machineId: 'm',
+ accessTokenProvider: (_, _) async => '',
+ onAuthFailure: (_) {},
+ onEvent: (_) {},
+ onStatus: (_) {},
+ );
+ Map<String, dynamic> answer = catalog();
+ Future<Map<String, dynamic>>? waiting;
+ bool loseReply = false;
+ final creates = <Map<String, dynamic>>[];
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) async {
+ switch (type) {
+ case 'grid_models_list':
+ return waiting ?? answer;
+ case 'git_project_info':
+ return {'isGit': false};
+ case 'dsh_list':
+ return {
+ 'dsh': [
+ {
+ 'id': 'acme/scene',
+ 'name': 'Scene',
+ 'engine': 'claude',
+ 'engines': ['codex', 'claude'],
+ 'installed': true,
+ },
+ ],
+ };
+ case 'engines_probe':
+ return {'engines': []};
+ case 'agent_create':
+ creates.add(Map.of(payload));
+ if (loseReply) throw const WsRequestTimeout('agent_create');
+ return {
+ 'creationId': payload['creationId'],
+ 'state': 'created',
+ 'agent': {
+ 'id': 'created',
+ 'name': 'Created',
+ 'engine': payload['engine'],
+ },
+ };
+ case 'agent_create_status':
+ return {
+ 'creationId': payload['creationId'],
+ 'state': 'created',
+ 'agent': {'id': 'created', 'name': 'Created', 'engine': 'codex'},
+ };
+ default:
+ return {};
+ }
+ }
+}
+
+class _Source implements UsageSource {
+ _Source(this.provider, this.account);
+ @override
+ final UsageProvider provider;
+ final String account;
+ @override
+ Future<ProviderUsage> read() async => ProviderUsage(
+ provider: provider,
+ status: UsageStatus.ok,
+ account: account,
+ fetchedAt: DateTime.now(),
+ windows: const [UsageWindow(label: 'Session', usedPercent: 25)],
+ );
+}
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+ late Map<String, _Connection> connections;
+ late AppNotifier app;
+ NewHarnessController controller({
+ ModelsMenuController? usage,
+ NewHarnessDraft? draft,
+ }) {
+ final box = NewHarnessController(
+ app,
+ machineId: 'm',
+ engine: 'codex',
+ folder: '/work/scene',
+ modelUsage: usage,
+ draft: draft,
+ );
+ addTearDown(box.dispose);
+ return box;
+ }
+
+ Future<void> load(NewHarnessController box) async {
+ box.focusField(NewHarnessField.model);
+ await box.refreshModels();
+ }
+
+ NewHarnessOption localChoice(
+ NewHarnessController box, [
+ String grid = 'my-grid',
+ ]) => box.options.singleWhere((option) => option.model?.grid == grid);
+ void select(NewHarnessController box, NewHarnessField field, String id) {
+ box.focusField(field);
+ box.applyOption(box.options.singleWhere((option) => option.id == id));
+ }
+
+ setUp(() {
+ connections = {};
+ app = createApp(
+ connectionForTest: (machine) =>
+ connections.putIfAbsent(machine, _Connection.new),
+ );
+ seedMixedAgents(app);
+ app.gitProjectReaderForTest = (_, _) async => {'isGit': false};
+ addTearDown(app.dispose);
+ });
+ test('creation rejects an old daemon, lost connection, unsupported engine and missing model before launching', () async {
+ final connection = connections.putIfAbsent('m', _Connection.new);
+ const model = GridModel(
+ id: 'Qwen-35B',
+ node: 'Mac Studio',
+ grid: 'my-grid',
+ );
+ for (final (answer, engine, message) in [
+ ({'error': 'OFFLINE'}, 'codex', 'Could not verify models'),
+ ({'gridName': 'my-grid'}, 'codex', 'Update Harness CLI'),
+ (catalog(), 'cursor', 'selected model is unavailable'),
+ ({...catalog(), 'grids': []}, 'codex', 'selected model is unavailable'),
+ ]) {
+ connection.answer = answer;
+ expect(
+ await app.createAgent(
+ 'm',
+ engine: engine,
+ folder: '/work',
+ model: model,
+ ),
+ contains(message),
+ );
+ expect(connection.creates, isEmpty);
+ }
+ });
+
+ test('subscriptions and cross-machine models remain distinct, including duplicate model names on two grids', () async {
+ final box = controller();
+ await load(box);
+ expect(box.options.where((o) => !o.synthetic).map((o) => o.group), [
+ 'Subscription',
+ 'On your machines',
+ 'Shared · team-grid',
+ ]);
+ final remote = localChoice(box, 'team-grid');
+ box.applyOption(remote);
+ expect(box.modelLabel, 'Qwen-35B · GPU Server');
+ expect(box.machineId, 'm');
+ expect(box.project.folder, '/work/scene');
+ expect(box.isCurrent(remote), isTrue);
+ expect(box.isCurrent(localChoice(box)), isFalse);
+ expect(box.usesProfile, isFalse);
+ box.setQuery('studio');
+ expect(box.options.where((o) => !o.synthetic).single.detail, 'Mac Studio');
+ box.setQuery('');
+ box.applyOption(
+ box.options.singleWhere(
+ (o) => o.id == NewHarnessController.defaultModelId,
+ ),
+ );
+ expect(box.model, isNull);
+ expect(box.modelLabel, 'OpenAI');
+ expect(box.usesProfile, isTrue);
+ });
+ test('inline choices reject an agent invalidated by a harness change and a profile from another machine', () async {
+ final box = controller();
+ await app.probeDsh('m', force: true);
+ box.focusField(NewHarnessField.agent);
+ final cursor = box.options.singleWhere((option) => option.id == 'cursor');
+ select(box, NewHarnessField.harness, 'acme/scene');
+ box.focusField(NewHarnessField.agent);
+ box.applyOption(cursor);
+ expect(box.engine, 'codex');
+ expect(box.error, contains('compatible with Scene'));
+
+ box.focusField(NewHarnessField.profile);
+ final profile = box.options.singleWhere(
+ (option) => option.id == NewHarnessController.defaultProfileId,
+ );
+ select(box, NewHarnessField.machine, 'studio');
+ box.focusField(NewHarnessField.profile);
+ box.applyOption(profile);
+ expect(box.machineId, 'studio');
+ expect(box.error, contains('machine has changed'));
+ expect(
+ connections.values.expand((connection) => connection.creates),
+ isEmpty,
+ );
+ });
+
+ for (final terminal in [false, true]) {
+ testWidgets(
+ 'legacy model draft restores and launches correctly (terminal=$terminal)',
+ (tester) async {
+ tester.view.devicePixelRatio = 1;
+ tester.view.physicalSize = const Size(1300, 1100);
+ addTearDown(tester.view.reset);
+ final box = controller();
+ await load(box);
+ box.applyOption(localChoice(box));
+ box.toggleAdvanced();
+ NewHarnessDraft? returned;
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Builder(
+ builder: (context) => Scaffold(
+ body: TextButton(
+ onPressed: () => showNewAgentDialog(
+ context,
+ app,
+ 'm',
+ source: 'test',
+ initialDraft: box.draft,
+ initiallyAdvanced: true,
+ onBack: (draft) => returned = draft,
+ ),
+ child: const Text('open'),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.tap(find.text('open'));
+ await tester.pumpAndSettle();
+ expect(
+ find.text('Model. Qwen-35B · Mac Studio', findRichText: true),
+ findsOneWidget,
+ );
+ expect(
+ find.byKey(const Key('new-agent-codex-profile-field')),
+ findsNothing,
+ );
+ if (terminal) {
+ await chooseAgent(tester, 'terminal');
+ await tester.pumpAndSettle();
+ expect(
+ find.text('Model. Qwen-35B · Mac Studio', findRichText: true),
+ findsNothing,
+ );
+ }
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(returned?.model, terminal ? isNull : same(box.model));
+ await tester.tap(find.text('open'));
+ await tester.pumpAndSettle();
+ if (terminal) await chooseAgent(tester, 'terminal');
+ await tester.tap(find.text('New Harness').last);
+ await tester.pumpAndSettle();
+ expect(
+ connections['m']!.creates.single['engine'],
+ terminal ? 'terminal' : 'codex',
+ );
+ expect(
+ connections['m']!.creates.single['gridModel'],
+ terminal ? isNull : 'Qwen-35B',
+ );
+ expect(
+ connections['m']!.creates.single.keys,
+ isNot(contains('codexHome')),
+ );
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+ }
+ test('an explicit model reaches the selected agent machine and harness without a credential', () async {
+ final box = controller();
+ await load(box);
+ box.applyOption(localChoice(box));
+ select(box, NewHarnessField.harness, 'acme/scene');
+ expect(await box.create(), NewHarnessOutcome.created);
+ final payload = connections['m']!.creates.single;
+ expect(payload, containsPair('engine', 'codex'));
+ expect(payload, containsPair('dsh', 'acme/scene'));
+ expect(payload, containsPair('gridModel', 'Qwen-35B'));
+ expect(payload, containsPair('gridName', 'my-grid'));
+ expect(payload, containsPair('cwd', '/work/scene'));
+ expect(payload.keys, isNot(contains('grid')));
+ expect(payload.keys, isNot(contains('codexHome')));
+ });
+ test('subscription launches omit all model routing fields', () async {
+ final box = controller();
+ await load(box);
+ expect(await box.create(), NewHarnessOutcome.created);
+ expect(connections['m']!.creates.single.keys, isNot(contains('gridModel')));
+ expect(connections['m']!.creates.single.keys, isNot(contains('gridName')));
+ });
+ testWidgets(
+ 'switching from a model to Terminal clears routing and still opens a shell',
+ (tester) async {
+ final box = controller();
+ await load(box);
+ box.applyOption(localChoice(box));
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: NewHarnessForm(
+ controller: box,
+ onClose: () {},
+ onCreated: () {},
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ await openLaunchRow(tester, 'agent');
+ await typeHarnessQuery(tester, 'Terminal');
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(box.engine, 'terminal');
+ expect(box.model, isNull);
+ expect(box.draft.model, isNull);
+ expect(find.text('Not used by Terminal'), findsOneWidget);
+ await startHarness(tester);
+ await tester.pumpAndSettle();
+ final payload = connections['m']!.creates.single;
+ expect(payload['engine'], 'terminal');
+ expect(payload.keys, isNot(contains('gridModel')));
+ expect(payload.keys, isNot(contains('gridName')));
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+ test('subscription details identify the selected Codex profile and retain it when returning from a model', () async {
+ final box = controller(
+ draft: const NewHarnessDraft(
+ machineId: 'm',
+ engine: 'codex',
+ project: NewHarnessProject.folder('/work'),
+ task: '',
+ permissionMode: 'auto-approve',
+ profile: LocalCodexProfile('/profiles/work', 'Work account'),
+ profileChosen: true,
+ ),
+ );
+ await load(box);
+ final subscription = box.options.singleWhere(
+ (option) => option.id == NewHarnessController.defaultModelId,
+ );
+ expect(subscription.detail, 'Work account on M2');
+ box.applyOption(localChoice(box));
+ expect(box.usesProfile, isFalse);
+ box.applyOption(subscription);
+ expect(box.usesProfile, isTrue);
+ expect(box.draft.profile?.path, '/profiles/work');
+ });
+ test('a stopped model never falls back or creates an agent', () async {
+ final box = controller();
+ await load(box);
+ box.applyOption(localChoice(box));
+ connections['m']!.answer = {...catalog(), 'grids': []};
+ expect(await box.create(), NewHarnessOutcome.failed);
+ expect(box.error, contains('selected model is unavailable'));
+ expect(box.model?.id, 'Qwen-35B');
+ expect(connections['m']!.creates, isEmpty);
+ expect(box.modelNotice, contains('selected model is unavailable'));
+ });
+ test(
+ 'changing agent preserves a chosen model but refuses incompatible launch',
+ () async {
+ final box = controller();
+ await load(box);
+ box.applyOption(localChoice(box));
+ select(box, NewHarnessField.agent, 'cursor');
+ expect(box.subscriptionLabel, 'Cursor default');
+ expect(box.modelNotice, contains('own login'));
+ expect(await box.create(), NewHarnessOutcome.failed);
+ await load(box);
+ expect(box.options.where((o) => o.model != null), isEmpty);
+ box.applyOption(
+ box.options.firstWhere(
+ (o) => o.id == NewHarnessController.defaultModelId,
+ ),
+ );
+ expect(box.model, isNull);
+ },
+ );
+ test('machine changes reject stale options and late catalogs while retaining an explicit model', () async {
+ final box = controller();
+ await load(box);
+ final stale = localChoice(box);
+ box.applyOption(stale);
+ final delayed = Completer<Map<String, dynamic>>();
+ connections['m']!.waiting = delayed.future;
+ final pending = box.refreshModels();
+ expect(box.modelNotice, 'Loading models…');
+ select(box, NewHarnessField.machine, 'studio');
+ await load(box);
+ expect(box.model?.id, 'Qwen-35B');
+ box.applyOption(stale);
+ expect(box.error, contains('no longer available'));
+ delayed.complete({'supportsModelLaunch': false});
+ await pending;
+ expect(box.options.any((o) => o.model?.id == 'Qwen-35B'), isTrue);
+ expect(box.modelNotice, isNull);
+ box.setFolder('/work/other');
+ expect(await box.create(), NewHarnessOutcome.created);
+ expect(connections['m']!.creates, isEmpty);
+ expect(connections['studio']!.creates.single['gridName'], 'my-grid');
+ });
+ test('draft and uncertain creation retain the exact model and use status without relaunch', () async {
+ final box = controller();
+ await load(box);
+ box.applyOption(localChoice(box));
+ connections['m']!.loseReply = true;
+ expect(await box.create(), NewHarnessOutcome.failed);
+ expect(box.checking, isTrue);
+ final restored = controller(draft: box.draft);
+ expect(restored.model?.grid, 'my-grid');
+ expect(await restored.create(), NewHarnessOutcome.created);
+ expect(connections['m']!.creates, hasLength(1));
+ });
+ test('unreachable, old and empty daemons explain their state and allow a subscription', () async {
+ final box = controller();
+ expect(box.modelNotice, isNull);
+ for (final (answer, notice) in [
+ ({'error': 'OFFLINE'}, 'Could not load models'),
+ ({'gridName': 'old', 'models': []}, 'Update Harness CLI'),
+ ({...catalog(), 'grids': []}, 'No models are running'),
+ ]) {
+ connections.putIfAbsent('m', _Connection.new).answer = answer;
+ await load(box);
+ expect(box.modelNotice, contains(notice));
+ expect(
+ box.options.any((o) => o.id == NewHarnessController.defaultModelId),
+ isTrue,
+ );
+ }
+ });
+ test('disposed controllers ignore outstanding model reads', () async {
+ final box = NewHarnessController(
+ app,
+ machineId: 'm',
+ engine: 'codex',
+ folder: '/work',
+ );
+ final delayed = Completer<Map<String, dynamic>>();
+ connections.putIfAbsent('m', _Connection.new).waiting = delayed.future;
+ final pending = box.refreshModels();
+ box.dispose();
+ delayed.complete(catalog());
+ await pending;
+ await box.refreshModels();
+ });
+ test('subscription usage matches the engine and selected machine, never another account', () async {
+ final usage = UsageController(
+ sources: [
+ _Source(UsageProvider.codex, '1111111111111111'),
+ _Source(UsageProvider.claude, '2222222222222222'),
+ ],
+ remote: () async => [
+ MachineUsage(
+ machineName: 'M2',
+ readings: [
+ ProviderUsage(
+ provider: UsageProvider.codex,
+ status: UsageStatus.ok,
+ account: '3333333333333333',
+ fetchedAt: DateTime.now(),
+ windows: const [UsageWindow(label: 'Session', usedPercent: 40)],
+ ),
+ ],
+ ),
+ ],
+ autoStart: false,
+ );
+ final menu = ModelsMenuController(usage: usage);
+ addTearDown(menu.dispose);
+ addTearDown(usage.dispose);
+ await menu.refresh();
+ expect(
+ menu.subscriptionFor('codex', local: true, machineName: '')?['account'],
+ '111111',
+ );
+ expect(
+ menu.subscriptionFor(
+ 'codex',
+ local: false,
+ machineName: 'M2',
+ )?['account'],
+ '333333',
+ );
+ expect(
+ menu.subscriptionFor('claude', local: false, machineName: 'M2'),
+ isNull,
+ );
+ final box = controller(usage: menu);
+ await load(box);
+ expect(box.options.first.title, 'OpenAI');
+ expect(box.options.first.detail, contains('60% remaining'));
+ select(box, NewHarnessField.agent, 'claude');
+ await load(box);
+ expect(box.options.first.title, 'Anthropic');
+ expect(box.options.first.detail, isNot(contains('60%')));
+ });
+ for (final width in [1100.0, 600.0]) {
+ testWidgets(
+ 'Model picker keeps pairs together and launches across machines at width $width',
+ (tester) async {
+ tester.view.devicePixelRatio = 1;
+ tester.view.physicalSize = Size(width, 800);
+ addTearDown(tester.view.reset);
+ final box = controller();
+ var managed = 0;
+ final subscription = app.modelsRequests.listen((_) => managed++);
+ addTearDown(subscription.cancel);
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: NewHarnessForm(
+ controller: box,
+ onClose: () {},
+ onCreated: () {},
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ final order = ['harness', 'agent', 'model', 'machine', 'project'];
+ final positions = [
+ for (final name in order)
+ tester
+ .getTopLeft(find.byKey(ValueKey('new-harness-field-$name')))
+ .dy,
+ ];
+ expect(positions, orderedEquals([...positions]..sort()));
+ await openLaunchRow(tester, 'model');
+ expect(find.text('Subscription'), findsOneWidget);
+ expect(find.text('On your machines'), findsOneWidget);
+ expect(find.text('Shared · team-grid'), findsOneWidget);
+ await typeHarnessQuery(tester, 'studio');
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(box.modelLabel, 'Qwen-35B · Mac Studio');
+ expect(box.machineId, 'm');
+ await openLaunchRow(tester, 'advanced');
+ final start = find.byKey(const ValueKey('new-harness-field-start'));
+ expect(start.hitTestable(), findsOneWidget);
+ final semantics = tester.ensureSemantics();
+ expect(tester.getSemantics(start).rect.size, tester.getSize(start));
+ expect(tester.getSemantics(start).label, 'New Harness');
+ semantics.dispose();
+ expect(
+ find.byKey(const ValueKey('new-harness-field-profile')),
+ findsNothing,
+ );
+ await openLaunchRow(tester, 'model');
+ await tester.tap(find.text('Refresh models'));
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('Manage Models…'));
+ await tester.pumpAndSettle();
+ expect(managed, 1);
+ await startHarness(tester);
+ await tester.pumpAndSettle();
+ expect(connections['m']!.creates.single['gridModel'], 'Qwen-35B');
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+ }
+}
diff --git a/desktop/test/new_harness_project_context_test.dart b/desktop/test/new_harness_project_context_test.dart
index 9374ef1e5..c71e9a997 100644
--- a/desktop/test/new_harness_project_context_test.dart
+++ b/desktop/test/new_harness_project_context_test.dart
@@ -176,6 +176,7 @@ void main() {
),
);
await tester.pump();
+ await focusLaunchRow(tester, 'project');
}
void chooseMachine(NewHarnessController box) {
@@ -531,10 +532,7 @@ void main() {
await mount(tester, box);
final agent = find.byKey(const ValueKey('new-harness-field-agent'));
final project = find.byKey(const ValueKey('new-harness-field-project'));
- expect(
- tester.getRect(agent).top,
- greaterThan(tester.getRect(project).top),
- );
+ expect(tester.getRect(agent).top, lessThan(tester.getRect(project).top));
expect(input, findsNothing);
expect(find.text(box.projectLabel), findsOneWidget);
expect(find.text('M2'), findsOneWidget);
@@ -546,7 +544,7 @@ void main() {
find.byKey(const ValueKey('new-harness-field-mode')),
findsNothing,
);
- expect(find.text('Auto-approve'), findsOneWidget);
+ expect(find.text('Auto-approve'), findsNothing);
for (final (name, field) in [
('agent', NewHarnessField.agent),
('machine', NewHarnessField.machine),
diff --git a/desktop/test/new_harness_scenarios_test.dart b/desktop/test/new_harness_scenarios_test.dart
index 9fba21948..a490d4861 100644
--- a/desktop/test/new_harness_scenarios_test.dart
+++ b/desktop/test/new_harness_scenarios_test.dart
@@ -172,6 +172,8 @@ Future<_Scenario> _mount(
),
);
await tester.pumpAndSettle();
+ await openLaunchRow(tester, 'advanced');
+ await focusLaunchRow(tester, 'project');
return scenario;
}
@@ -207,45 +209,48 @@ void main() {
});
for (final scale in [1.0, 1.8]) {
- testWidgets(
- 'prompt shares action icon column and text baseline at $scale',
- (tester) async {
- await _mount(tester, scale: scale, size: const Size(1600, 1000));
- final prompt = find.byKey(const ValueKey('new-harness-prompt'));
- final hint = find.text('Search project');
- double baseline(Finder finder) {
- final render = tester.renderObject<RenderBox>(finder);
- return render
- .localToGlobal(
- Offset(
- 0,
- render.getDryBaseline(
- render.constraints,
- TextBaseline.alphabetic,
- )!,
- ),
- )
- .dy;
- }
+ testWidgets('prompt text, doors and names share one column at $scale', (
+ tester,
+ ) async {
+ await _mount(tester, scale: scale, size: const Size(1600, 1000));
+ final prompt = find.byKey(const ValueKey('new-harness-prompt'));
+ final hint = find.text('Search project');
+ double baseline(Finder finder) {
+ final render = tester.renderObject<RenderBox>(finder);
+ return render
+ .localToGlobal(
+ Offset(
+ 0,
+ render.getDryBaseline(
+ render.constraints,
+ TextBaseline.alphabetic,
+ )!,
+ ),
+ )
+ .dy;
+ }
- expect(baseline(prompt), closeTo(baseline(hint), .1));
- for (final id in [
- NewHarnessController.repositoryId,
- NewHarnessController.existingProjectId,
- NewHarnessController.newProjectId,
- ]) {
- final icon = find.descendant(
- of: _option(id),
- matching: find.byType(Icon),
- );
- expect(
- tester.getCenter(prompt).dx,
- closeTo(tester.getCenter(icon).dx, .1),
- );
- }
- expect(tester.takeException(), isNull);
- },
- );
+ expect(baseline(prompt), closeTo(baseline(hint), .1));
+ // The doors lost their glyphs; their names start where the typed
+ // text does, and no icon is left in the pointer column.
+ final text = tester.getTopLeft(hint).dx;
+ for (final id in [
+ NewHarnessController.repositoryId,
+ NewHarnessController.existingProjectId,
+ NewHarnessController.newProjectId,
+ ]) {
+ expect(
+ find.descendant(of: _option(id), matching: find.byType(Icon)),
+ findsNothing,
+ );
+ final name = find.descendant(
+ of: _option(id),
+ matching: find.byType(Text),
+ );
+ expect(tester.getTopLeft(name.first).dx, closeTo(text, .5));
+ }
+ expect(tester.takeException(), isNull);
+ });
}
testWidgets(
@@ -284,16 +289,27 @@ void main() {
findsNothing,
);
expect(find.text('Remote'), findsNothing);
- // Dimmed text alone reads as a theme. A row that cannot be chosen says
- // which of the two things is wrong with it, because they need different
- // answers from the person: one is a link, the other is a power button.
+ // The two things wrong with a machine need different answers — a link,
+ // or a power button — so they still look different: an unlinked one in
+ // the warning colour, an offline one with its word. The unlinked row
+ // prints no word, but a screen reader is still told.
expect(
find.descendant(
of: _option('studio'),
matching: find.text('Link required'),
),
- findsOneWidget,
+ findsNothing,
+ );
+ final studio = tester.widget<Text>(
+ find
+ .descendant(of: _option('studio'), matching: find.byType(Text))
+ .first,
);
+ // Dark grey: darker than an idle row's faint, so it recedes.
+ expect(studio.style!.color, Colors.white.withValues(alpha: .28));
+ final handle = tester.ensureSemantics();
+ expect(tester.getSemantics(_option('studio')).hint, 'Link required');
+ handle.dispose();
expect(
find.descendant(of: _option('build'), matching: find.text('Offline')),
findsOneWidget,
@@ -439,6 +455,7 @@ void main() {
tester,
) async {
final scenario = await _mount(tester, engine: 'claude');
+ await focusLaunchRow(tester, 'harness');
await key(tester, LogicalKeyboardKey.tab, shift: true);
expect(
tester.widget<Semantics>(_field('start')).properties.selected,
@@ -458,8 +475,10 @@ void main() {
await tester.sendKeyRepeatEvent(LogicalKeyboardKey.arrowUp);
await tester.sendKeyUpEvent(LogicalKeyboardKey.arrowUp);
await tester.pump();
+ // Two steps up from Approvals: Worktree, then Advanced — Branch now sits
+ // above Advanced, beside Project.
expect(
- tester.widget<Semantics>(_field('branch')).properties.selected,
+ tester.widget<Semantics>(_field('advanced')).properties.selected,
isTrue,
);
expect(FocusManager.instance.primaryFocus?.debugLabel, 'new-harness-form');
@@ -492,7 +511,7 @@ void main() {
'Store, profile linking and profile refresh are reachable by pointer',
(tester) async {
final scenario = await _mount(tester);
- await openLaunchRow(tester, 'agent');
+ await openLaunchRow(tester, 'harness');
await typeHarnessQuery(tester, 'nothing-installed-with-this-name');
await tester.tap(_option(NewHarnessController.storeId));
await tester.pump();
@@ -524,10 +543,11 @@ void main() {
expect(scenario.box.field, NewHarnessField.projectMenu);
});
- testWidgets('the three project actions have icons, project names do not', (
+ testWidgets('the three project actions carry no glyphs, and read as text', (
tester,
) async {
final scenario = await _mount(tester);
+ // A terminal has no icons: the actions are words, like every other row.
for (final id in [
NewHarnessController.repositoryId,
NewHarnessController.existingProjectId,
@@ -535,7 +555,7 @@ void main() {
]) {
expect(
find.descendant(of: _option(id), matching: find.byType(Icon)),
- findsOneWidget,
+ findsNothing,
);
}
final project = scenario.box.options.firstWhere(
@@ -699,7 +719,7 @@ void main() {
expect(_option(last.id).hitTestable(), findsOneWidget);
await tester.tap(_option(last.id));
await tester.pump();
- expect(scenario.stores, 1);
+ expect(scenario.box.engine, last.id);
expect(scenario.creates, 0);
});
@@ -741,7 +761,7 @@ void main() {
case NewHarnessController.existingProjectId:
expect(scenario.box.project.folder, '/work/my project');
}
- await key(tester, LogicalKeyboardKey.arrowDown);
+ await focusLaunchRow(tester, 'agent');
expect(scenario.box.field, NewHarnessField.agent);
expect(scenario.creates, 0);
expect(scenario.connections.values.expand((c) => c.starts), isEmpty);
@@ -759,7 +779,7 @@ void main() {
call.method == 'Clipboard.getData' ? pending.future : null,
);
await key(tester, LogicalKeyboardKey.keyV, ctrl: true);
- await key(tester, LogicalKeyboardKey.arrowDown);
+ await focusLaunchRow(tester, 'agent');
pending.complete({'text': 'stale project'});
await tester.pump();
expect(scenario.box.field, NewHarnessField.agent);
@@ -865,7 +885,7 @@ void main() {
expect(scenario.box.error, isNull);
expect(scenario.box.field, NewHarnessField.projectMenu);
expect(harnessChoicesActive(tester), isFalse);
- await key(tester, LogicalKeyboardKey.arrowDown);
+ await focusLaunchRow(tester, 'agent');
expect(scenario.box.field, NewHarnessField.agent);
expect(scenario.creates, 0);
});
diff --git a/desktop/test/remote_folder_picker_test.dart b/desktop/test/remote_folder_picker_test.dart
index c6b10126f..546836f0c 100644
--- a/desktop/test/remote_folder_picker_test.dart
+++ b/desktop/test/remote_folder_picker_test.dart
@@ -52,6 +52,7 @@ class _Folders extends AppNotifier {
String? permissionMode,
String? codexHome,
String? dsh,
+ GridModel? model,
String? prompt,
String? name,
String? agent,
diff --git a/desktop/test/store_discover_test.dart b/desktop/test/store_discover_test.dart
index a560b9c8b..b0ea52cce 100644
--- a/desktop/test/store_discover_test.dart
+++ b/desktop/test/store_discover_test.dart
@@ -1449,7 +1449,11 @@ void main() {
await tester.pumpAndSettle();
expect(find.byKey(const ValueKey('create-agent-submit')), findsOneWidget);
expect(
- tester.widget<AgentPicker>(find.byType(AgentPicker)).value,
+ tester
+ .widget<AgentPicker>(
+ find.byKey(const Key('new-agent-harness-picker')),
+ )
+ .value,
'autonomous/blender',
);
expect(app.swarms.length, count + 1);
diff --git a/desktop/test/store_page_test.dart b/desktop/test/store_page_test.dart
index 549d49850..501579d5e 100644
--- a/desktop/test/store_page_test.dart
+++ b/desktop/test/store_page_test.dart
@@ -1,3 +1,5 @@
+import 'support/agent_picker.dart';
+
// A harness's page in the Harness Store, past the happy path the screen test
// pins: this computer's install state, Get/Open/Remove
// under double clicks and pages that vanish mid-dialog, engines as the probes
@@ -1330,6 +1332,7 @@ void main() {
);
await tester.tap(_key('store-primary-action'));
await tester.pumpAndSettle();
+ await expandNewAgentAdvanced(tester);
expect(
tester
.widget<AppChoicePicker<String>>(_key('new-agent-machine-field'))
diff --git a/desktop/test/store_showcase_test.dart b/desktop/test/store_showcase_test.dart
index c94a4c753..9cf32ad28 100644
--- a/desktop/test/store_showcase_test.dart
+++ b/desktop/test/store_showcase_test.dart
@@ -83,6 +83,7 @@ class _Notifier extends AppNotifier {
String? permissionMode,
String? codexHome,
String? dsh,
+ GridModel? model,
String? prompt,
String? name,
String? agent,
diff --git a/desktop/test/support/agent_picker.dart b/desktop/test/support/agent_picker.dart
index eaa8b9c75..58ab3a21b 100644
--- a/desktop/test/support/agent_picker.dart
+++ b/desktop/test/support/agent_picker.dart
@@ -34,3 +34,36 @@ Future<void> chooseAgent(WidgetTester tester, String id) async {
await tester.tap(find.byKey(ValueKey('new-agent-agent-row-$id')));
await tester.pump();
}
+
+final harnessBar = find.byKey(const Key('new-agent-harness-field'));
+final harnessSearch = find.byKey(const Key('new-agent-harness-search'));
+List<String> harnessRows(WidgetTester tester) => [
+ for (final element in find.byType(ListTile).evaluate())
+ if (element.widget.key case ValueKey<String>(value: final key)
+ when key.startsWith('new-agent-harness-row-'))
+ key.substring('new-agent-harness-row-'.length),
+];
+Future<void> openHarnessSearch(WidgetTester tester) async {
+ await tester.ensureVisible(harnessBar);
+ await tester.pump();
+ final bar = tester.getRect(harnessBar);
+ await tester.tapAt(Offset(bar.left + 90, bar.center.dy));
+ await tester.pump();
+ await tester.pump();
+}
+
+Future<void> chooseHarness(WidgetTester tester, String id) async {
+ await openHarnessSearch(tester);
+ await tester.enterText(harnessSearch, id);
+ await tester.pump();
+ await tester.tap(find.byKey(ValueKey('new-agent-harness-row-$id')));
+ await tester.pump();
+}
+
+Future<void> expandNewAgentAdvanced(WidgetTester tester) async {
+ final collapsed = find.textContaining('[+] Advanced');
+ if (collapsed.evaluate().isEmpty) return;
+ await tester.ensureVisible(collapsed);
+ await tester.tap(collapsed);
+ await tester.pumpAndSettle();
+}
diff --git a/desktop/test/support/launch_menu.dart b/desktop/test/support/launch_menu.dart
index 179b7b5f4..6b6be8e62 100644
--- a/desktop/test/support/launch_menu.dart
+++ b/desktop/test/support/launch_menu.dart
@@ -12,24 +12,35 @@ bool harnessChoicesActive(WidgetTester tester) {
/// Open a launch row through the same navigation keys as the visible menu.
Future<void> openLaunchRow(WidgetTester tester, String name) async {
- // The setup screen starts at Project; its semantic selection also reports
- // keyboard focus, so tests drive the visible rows rather than a controller.
- final target = name == 'create' ? 'start' : name;
+ await focusLaunchRow(tester, name);
+ if (name != 'start' && name != 'create') {
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ }
+}
+
+/// Focus a visible field without opening its list or changing its value.
+Future<void> focusLaunchRow(WidgetTester tester, String name) async {
+ final target = switch (name) {
+ 'create' => 'start',
+ 'mode' => 'approvals',
+ _ => name,
+ };
for (var i = 0; i < 3 && harnessChoicesActive(tester); i++) {
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pump();
}
final row = find.byKey(ValueKey('new-harness-field-$target'));
- for (var i = 0; i < 8; i++) {
+ if (row.evaluate().isEmpty &&
+ {'branch', 'worktree', 'approvals', 'profile'}.contains(target)) {
+ await openLaunchRow(tester, 'advanced');
+ }
+ for (var i = 0; i < 12; i++) {
if (tester.widget<Semantics>(row).properties.selected == true) break;
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
await tester.pump();
}
expect(tester.widget<Semantics>(row).properties.selected, isTrue);
- if (target != 'start') {
- await tester.sendKeyEvent(LogicalKeyboardKey.enter);
- await tester.pump();
- }
await tester.pumpAndSettle();
}
diff --git a/desktop/test/swarm_interactions_test.dart b/desktop/test/swarm_interactions_test.dart
index a4dc53c86..762880116 100644
--- a/desktop/test/swarm_interactions_test.dart
+++ b/desktop/test/swarm_interactions_test.dart
@@ -1,3 +1,4 @@
+import 'support/agent_picker.dart';
import 'support/new_agent_project.dart';
import 'dart:async';
@@ -626,6 +627,7 @@ void main() {
await browseNewAgentProject(tester);
await tester.pump();
await tester.pump();
+ await expandNewAgentAdvanced(tester);
final field = find.byKey(const Key('new-agent-machine-field'));
tester.widget<AppChoicePicker<String>>(field).onChanged('b');
await tester.pump();
diff --git a/desktop/test/terminal_ui_typography_test.dart b/desktop/test/terminal_ui_typography_test.dart
index d72fefa92..6f931d0eb 100644
--- a/desktop/test/terminal_ui_typography_test.dart
+++ b/desktop/test/terminal_ui_typography_test.dart
@@ -257,11 +257,17 @@ void main() {
await key(tester, LogicalKeyboardKey.keyN, cmd: true);
expect(find.byType(NewHarnessForm), findsOneWidget);
final box = checkText(tester, atLeast: 1);
- expect(tester.widget<Text>(find.text('New Harness')).style!.fontSize, 18);
+ expect(
+ tester.widget<Text>(find.text('[ New Harness ]')).style!.fontSize,
+ 18,
+ );
selectFont(22);
await tester.pumpAndSettle();
expectSameSizes(box, checkText(tester, atLeast: 1));
- expect(tester.widget<Text>(find.text('New Harness')).style!.fontSize, 22);
+ expect(
+ tester.widget<Text>(find.text('[ New Harness ]')).style!.fontSize,
+ 22,
+ );
await key(tester, LogicalKeyboardKey.escape);
for (final shortcut in [
LogicalKeyboardKey.keyO,
diff --git a/desktop/test/workspace_start_guide_test.dart b/desktop/test/workspace_start_guide_test.dart
index 1daed26bd..b3a9084e7 100644
--- a/desktop/test/workspace_start_guide_test.dart
+++ b/desktop/test/workspace_start_guide_test.dart
@@ -98,6 +98,7 @@ class _FirstApp extends AppNotifier {
String? permissionMode,
String? codexHome,
String? dsh,
+ GridModel? model,
String? prompt,
String? name,
String? agent,
diff --git a/desktop/tool/check_portability_coverage.py b/desktop/tool/check_portability_coverage.py
new file mode 100644
index 000000000..3d91fc1b1
--- /dev/null
+++ b/desktop/tool/check_portability_coverage.py
@@ -0,0 +1,64 @@
+#!/usr/bin/env python3
+"""Require 100% LCOV line coverage of desktop production changes against --base.
+
+Run flutter test --coverage first. In CI, pass the merge base as --base; during
+development the default HEAD compares the working tree. Missing file records
+fail the check rather than silently shrinking the coverage denominator.
+"""
+import argparse
+from collections import defaultdict
+from pathlib import Path
+import re
+import subprocess
+import sys
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('--base', default='HEAD')
+ parser.add_argument('--lcov', type=Path, default=Path('desktop/coverage/lcov.info'))
+ args = parser.parse_args()
+ root = Path(__file__).resolve().parents[2]
+ coverage = defaultdict(dict)
+ source = None
+ for line in (root / args.lcov).read_text().splitlines():
+ if line.startswith('SF:'):
+ source = line[3:]
+ if source.startswith(str(root / 'desktop') + '/'):
+ source = source[len(str(root / 'desktop')) + 1:]
+ elif line.startswith('DA:'):
+ number, count, *_ = line[3:].split(',')
+ coverage[source][int(number)] = coverage[source].get(int(number), 0) + int(count)
+ changes = defaultdict(set)
+ diff = subprocess.check_output(['git', 'diff', '--no-ext-diff', '--unified=0', args.base, '--', 'desktop/lib'], cwd=root, text=True)
+ for line in diff.splitlines():
+ if line.startswith('+++ b/desktop/'):
+ source = line[len('+++ b/desktop/'):]
+ elif line.startswith('@@'):
+ match = re.search(r'\+(\d+)(?:,(\d+))?', line)
+ start, count = int(match[1]), int(match[2] or 1)
+ changes[source].update(range(start, start + count))
+ for name in subprocess.check_output(['git', 'ls-files', '--others', '--exclude-standard', 'desktop/lib'], cwd=root, text=True).splitlines():
+ if name.endswith('.dart'):
+ changes[name[len('desktop/'):]].update(range(1, len((root / name).read_text().splitlines()) + 1))
+ failed = False
+ hit = total = 0
+ for source, changed in sorted(changes.items()):
+ if not changed:
+ continue
+ if source not in coverage:
+ print(f'MISSING COVERAGE: {source}')
+ failed = True
+ continue
+ executable = changed & coverage[source].keys()
+ missing = sorted(number for number in executable if coverage[source][number] == 0)
+ total += len(executable)
+ hit += len(executable) - len(missing)
+ print(f'{source}: {len(executable) - len(missing)}/{len(executable)}' + (f' missing {missing}' if missing else ''))
+ failed |= bool(missing)
+ print(f'Desktop changed executable lines: {hit}/{total}' + (' (100%)' if total and not failed else ''))
+ return 1 if failed or not total else 0
+
+
+if __name__ == '__main__':
+ sys.exit(main())
diff --git a/desktop/tool/harness_portability_review.dart b/desktop/tool/harness_portability_review.dart
new file mode 100644
index 000000000..268703081
--- /dev/null
+++ b/desktop/tool/harness_portability_review.dart
@@ -0,0 +1,225 @@
+// Interactive QA host for the production workspace. Launch only in an isolated
+// bundle with FLUTTER_TEST=1 and HARNESS_REVIEW_CATALOG pointing at fixture JSON.
+// No provider calls, installs, credentials, or user preferences are accessed.
+import 'dart:async';
+import 'dart:convert';
+import 'dart:io';
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:harness/auth/auth_session.dart';
+import 'package:harness/core/config.dart';
+import 'package:harness/widgets/engine_identity.dart';
+import 'package:harness/core/local_key_value_store.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/core/test_run.dart';
+import 'package:harness/screens/swarm_screen.dart';
+import 'package:harness/shortcuts/app_keymap.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/state/app_state.dart';
+import 'package:harness/state/new_harness.dart';
+import 'package:harness/state/pane_layout_store.dart';
+import 'package:harness/state/swarm_catalog.dart';
+import 'package:harness/terminal/terminal_session.dart';
+import 'package:harness/ws/ws_conn.dart';
+
+class _Memory implements LocalKeyValueStore {
+ final values = <String, String>{};
+ @override
+ Future<String?> read(String key) async => values[key];
+ @override
+ Future<void> write(String key, String value) async => values[key] = value;
+ @override
+ Future<void> delete(String key) async => values.remove(key);
+}
+
+class _Connection extends WsConn {
+ _Connection(this.catalog)
+ : super(
+ wsBaseUrl: 'ws://fixture.invalid',
+ autonomousEnv: 'test',
+ machineId: 'review',
+ accessTokenProvider: (_, _) async => '',
+ onAuthFailure: (_) {},
+ onEvent: (_) {},
+ onStatus: (_) {},
+ );
+ final List<dynamic> catalog;
+ int _creates = 0;
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) async {
+ if (type == 'dsh_list') return {'dsh': catalog};
+ if (type == 'engines_probe') {
+ return {
+ 'engines': [
+ for (final engine in allEngines)
+ {'engine': engine.id, 'installed': true},
+ ],
+ };
+ }
+ if (type == 'grid_models_list') {
+ return {
+ 'supportsModelLaunch': true,
+ 'gridName': 'review-grid',
+ 'localModelEngines': [
+ 'claude',
+ 'codex',
+ 'opencode',
+ 'pi',
+ 'hermes',
+ 'grok',
+ 'commandcode',
+ ],
+ 'grids': [
+ {
+ 'name': 'review-grid',
+ 'own': true,
+ 'models': [
+ {'id': 'Qwen-35B', 'node': 'Mac Studio'},
+ {'id': 'DeepSeek', 'node': 'GPU Server'},
+ ],
+ },
+ {
+ 'name': 'Team grid',
+ 'own': false,
+ 'models': [
+ {'id': 'Qwen-35B', 'node': 'Team GPU'},
+ ],
+ },
+ ],
+ };
+ }
+ if (type == 'git_project_info') return {'isGit': false};
+ if (type == 'fs_list_dir') {
+ return {'path': '/tmp/harness-review', 'entries': []};
+ }
+ if (type == 'codex_profiles') return {'profiles': []};
+ if (type == 'agent_create') {
+ return {
+ 'creationId': payload['creationId'],
+ 'state': 'created',
+ 'agent': {
+ 'id': 'review-created-${++_creates}',
+ 'name':
+ 'Review: ${payload['dsh'] ?? 'Coding'} on ${payload['engine']} · ${payload['gridModel'] ?? 'Subscription'}',
+ 'engine': payload['engine'],
+ if (payload['gridModel'] != null)
+ 'grid': {
+ 'baseUrl': 'https://fixture.invalid',
+ 'model': payload['gridModel'],
+ },
+ 'dsh': payload['dsh'],
+ 'project': {
+ 'name': payload['projectName'] ?? 'Review project',
+ 'cwd': payload['cwd'] ?? '/tmp/harness-review',
+ },
+ },
+ };
+ }
+ return {};
+ }
+}
+
+Future<void> main() async {
+ if (!kUnderTest) {
+ throw StateError('The review host requires FLUTTER_TEST=1');
+ }
+ WidgetsFlutterBinding.ensureInitialized();
+ final catalog = jsonDecode(
+ await File(Platform.environment['HARNESS_REVIEW_CATALOG']!).readAsString(),
+ ) as List;
+ final connection = _Connection(catalog);
+ final app = AppNotifier(
+ config: const AppConfig(
+ apiBaseUrl: 'http://127.0.0.1:1',
+ localCliBaseUrl: 'http://127.0.0.1:1',
+ ),
+ authSession: AuthSession(),
+ configStore: null,
+ paneLayoutStore: PaneLayoutStore(storage: _Memory()),
+ connectionForTest: (_) => connection,
+ )..hasNavigationRail = false;
+ const machine = Machine(
+ machineId: 'review',
+ name: 'Review Mac',
+ authMode: MachineAuthMode.remote,
+ );
+ const other = Machine(
+ machineId: 'studio',
+ name: 'Remote workstation',
+ authMode: MachineAuthMode.remote,
+ );
+ app.machines = [machine, other];
+ app.machineStates['studio'] = MachineState(other)
+ ..nodeOnline = true
+ ..connectionStatus = ConnectionStatus.connected
+ ..agentLoadStatus = AgentLoadStatus.loaded;
+ app.machineStates['review'] = MachineState(machine)
+ ..nodeOnline = true
+ ..connectionStatus = ConnectionStatus.connected
+ ..agentLoadStatus = AgentLoadStatus.loaded
+ ..agents = const [
+ Agent(
+ id: 'review-coding',
+ name: 'Portability review',
+ engine: 'codex',
+ terminalAvailable: true,
+ project: AgentProject(
+ name: 'Review project',
+ cwd: '/tmp/harness-review',
+ ),
+ ),
+ ];
+ final session = TerminalSession(
+ machineId: 'review',
+ agentId: 'review-coding',
+ agentName: 'Portability review',
+ engineId: 'codex',
+ send: (_, _) async => true,
+ sendBinary: (_) async => true,
+ )..streamId = 'review-stream';
+ session.terminal.write(
+ 'Harness portability review\r\n\r\nCmd+N: choose Harness, Agent, Model, Machine, Project.\r\nAll store packages and 14 engines are fixture data.\r\nCreate reports the captured selection; it never starts an agent.\r\n',
+ );
+ // ignore: invalid_use_of_visible_for_testing_member
+ app.adoptSessionForTest(session);
+ await app.probeEngines('review', force: true);
+ await app.probeDsh('review', force: true);
+ await const MethodChannel('harness/swarm_tabs')
+ .invokeMethod<void>('configure');
+ newHarnessOpensInBox = true;
+ final keymap = AppKeymap();
+ final keyLog = Platform.environment['HARNESS_REVIEW_KEY_LOG'];
+ if (keyLog != null) {
+ HardwareKeyboard.instance.addHandler((event) {
+ final focus = FocusManager.instance.primaryFocus;
+ final context = focus?.context;
+ File(keyLog).writeAsStringSync(
+ '${event.runtimeType} ${event.logicalKey.debugName} '
+ 'focus=${focus?.debugLabel} '
+ 'keymap=${context == null ? "none" : identical(KeymapTheme.of(context, listen: false), keymap)} '
+ 'lifecycle=${WidgetsBinding.instance.lifecycleState}\n',
+ mode: FileMode.append,
+ );
+ return false;
+ });
+ }
+ runApp(
+ grid.BrightnessScope(
+ child: MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ builder: (_, child) => KeymapProvider(keymap: keymap, child: child!),
+ home: SwarmScreen(
+ notifier: app,
+ nativeTabs: true,
+ projectStore: SwarmProjectStore(),
+ ),
+ ),
+ ),
+ );
+}
diff --git a/store/spec/CHANGES.md b/store/spec/CHANGES.md
index 09809af12..60cf17aea 100644
--- a/store/spec/CHANGES.md
+++ b/store/spec/CHANGES.md
@@ -187,3 +187,47 @@ Initial contract. Lifted from the `.board.json` (Circuit) and `.episode.json` (T
- **Backward compatible:** all version fields are optional additions. Older records remain readable;
older desktop clients ignore new fields, and newer clients show their existing actions for daemons
without update metadata. Shared viewers update independently.
+
+## 2026-09-23 — choose an agent engine for a harness
+
+- **Change:** a package can opt into Claude and Codex with
+ `agent.env.DSH_SUPPORTED_ENGINES`, a comma-separated list including its default `engine`.
+ Multiple engines require engine-neutral instructions and no `agent.args`.
+ Catalog and `dsh_list` rows expose optional `engines`; installed metadata wins.
+- **Why:** Harness and Agent are separate choices. The selected engine determines launch,
+ instructions and skill placement; the package determines the workspace and tools.
+- **Backward compatible:** the manifest remains spec 1 and uses its existing env extension.
+ Older daemons keep the default engine; newer clients fall back to that engine when `engines`
+ is absent. Existing sessions keep their saved engine when resumed or forked.
+- **Mechanism:** `dshSupportedEngines`, create validation, engine-aware materialization and
+ launch arguments. Blender, Strudel, MuJoCo, RDKit, Typst and Jev Sheets opt in first.
+
+## 2026-09-23 — portable runtime for every harness and engine
+
+- **Change:** supersedes the six-package opt-in above. Every spec-1 harness is projected through
+ a shared runtime and one adapter per process engine; `DSH_SUPPORTED_ENGINES` is no longer used.
+ Harness content and engine identity are separate, including in session restore and fork.
+- **Why:** package authors ship domain instructions, skills, tools, viewers and checks once.
+ Engine discovery folders must not mix two sessions' harness content in a shared project.
+- **Backward compatible:** existing manifests and the app's preference folder remain readable.
+ Old daemons continue with the default engine. New session runtime keys are optional registry
+ fields; older rows get a context on their next launch. Legacy instruction migration backs up the
+ original file and removes only exact, known package text. Ambiguous edits are preserved and
+ reported for resolution. User-owned skill paths are never repointed.
+- **Mechanism:** `dsh/runtime.ts`, `dsh/adapters.ts`, portable skill indexes, session snapshots,
+ daemon-derived `engines`, and separate desktop harness/agent preference histories.
+
+## 2026-09-23 — choose a model when starting a harness
+
+- **Change:** New Harness shows Harness, Agent, Model, Machine and Project. Model includes the
+ relevant subscription/default login plus running owned and shared models supported by the engine.
+ The model's serving machine is independent of the machine running the agent and its project.
+- **Why:** model selection belongs beside Agent, and remote execution belongs beside Project.
+ Branch sits under Project, where it belongs; Advanced contains Worktree, Approvals and
+ subscription Profile; Machine stays visible.
+- **Backward compatible:** `grid_models_list.supportsModelLaunch` gates the new semantic
+ `agent_create.gridModel` / `gridName` pair. Ordinary launches and existing raw grid routes retain
+ their wire contracts. Older daemons explain the required update for explicit model launches.
+- **Mechanism:** the selected daemon validates compatibility, refreshes availability, and resolves
+ credentials after reserving the creation receipt and before preparing a project. Receipt identity
+ contains the model/grid pair, never a rotating credential. Unavailable models refuse launch.
diff --git a/store/spec/README.md b/store/spec/README.md
index e9706525c..724b06b75 100644
--- a/store/spec/README.md
+++ b/store/spec/README.md
@@ -39,20 +39,35 @@ Harness reads `harness.json` at its root and nothing else about its code.
}
```
-Materialization, in order, at every create (idempotent):
-
-1. If `workspace.marker` is absent: copy `workspace.template/*` into the workspace, then run
- `workspace.init` if declared.
-2. `AGENTS.md`: copy if absent; else append the DSH file under a marker line
- `<!-- harness:dsh <id> -->` if that marker is not already present. For a `claude` base also
- ensure `CLAUDE.md` contains `@AGENTS.md` (Claude Code reads `CLAUDE.md`, imports the rest).
-3. Skills: symlink each skill dir into `<workspace>/.claude/skills/<name>` (claude) or
- `<workspace>/.agents/skills/<name>` (codex). Symlinks, so a DSH update is live.
-4. Create `<workspace>/.harness/`.
-
-Launch env, always: `HARNESS_DSH=<id>`, `HARNESS_DSH_DIR=<install dir>`,
-`HARNESS_WORKSPACE=<workspace>`, plus `agent.env` expanded. Set through tmux `-e`, the same channel
-grids and Codex profiles use, on create AND on every relaunch (`buildLaunchOverrides`).
+An agent package's `engine` is its default for clients that have not chosen an engine. The
+portable runtime binds every spec-1 harness to every integrated process engine. There is no
+package allowlist or opt-in flag. Terminal is a plain shell and is offered only with Coding.
+Older daemons still read the same manifest and use its default engine. New desktop clients use the
+machine's `dsh_list.engines` and fall back to `engine` for older daemons.
+
+Materialization prepares the workspace independently of the engine:
+
+1. If `workspace.marker` is absent: copy `workspace.template/*` without overwriting existing files,
+ then run `workspace.init` if declared.
+2. Create `<workspace>/.harness/` for verdicts and runtime state.
+3. Bind the selected engine to a session-scoped context bundle under `.harness/runtime/`.
+ Its instructions and skill index are loaded through the engine adapter. A small, generic
+ bootstrap in the engine's project instruction file reads `HARNESS_CONTEXT_FILE`; it contains
+ no particular harness's instructions. Existing project text is preserved.
+
+Launch env includes `HARNESS_DSH`, `HARNESS_DSH_DIR`, `HARNESS_WORKSPACE`,
+`HARNESS_CONTEXT_FILE`, and `HARNESS_SKILLS_DIR`, plus expanded `agent.env`. Skills are readable
+files with shell commands; native skills and MCP are not prerequisites. Old workspace skill paths
+in env are translated to the session's skills directory. `agent.args` remains a legacy extension
+for the manifest's default engine only; those flags are never handed to another engine.
+
+Create records a runtime key along with the chosen engine and harness. Resume uses that bundle;
+fork copies its configuration into a new bundle. Instructions, env and argv remain stable across
+package-default changes. Installed skill assets and toolchains follow package updates, as before.
+Missing packages or damaged contexts refuse a restart with a specific error.
+
+See [the runtime contract and adapter sources](portability.md) for lifecycle, migration, compatibility,
+and the coverage gate.
## Viewer packages (spec 1.1)
@@ -107,12 +122,15 @@ writes it beside the sidecar in `circuitpy.generation`; Workshop writes it from
## Wire (daemon ↔ desktop)
- `agent_create` payload gains `dsh?: string`. Refused with `INVALID_DSH` when not installed on
- this machine or when `engine` is not the DSH's base.
+ this machine or when `engine` is not supported by the installed manifest. Saved sessions keep
+ their actual `engine` for resume, restart and fork, independently of the manifest's default.
- `AgentFrame` gains `dsh: string | null`, `dshName: string | null`, `viewerUrl: string | null`,
`verdict: { ready, summary, errors, warnings, artifact, phases, updatedAt } | null`. Null is a real answer
(see `agentFrame.ts`'s doc on erased fields).
-- `dsh_list` → `{ dsh: [{ id, name, description, category, engine, installed, viewer, tier }] }`: installed
+- `dsh_list` → `{ dsh: [{ id, name, description, category, engine, engines, installed, viewer, tier }] }`: installed
DSHs on this machine merged with the bundled registry (the `store/` folders and `store/registry/`).
+ `engines` lists supported engines. Installed metadata wins over catalog metadata; an older
+ daemon omitting `engines` supports only its advertised `engine`.
- `dsh_install { id?, url?, ref? }` → runs clone → setup → doctor; pushes
`dsh_install_status { id, phase: clone|setup|doctor|done|failed, detail? }`; replies `{ ok }` at
the end (the desktop uses a 10-minute timeout for this one request).
diff --git a/store/spec/portability.md b/store/spec/portability.md
new file mode 100644
index 000000000..c3eb94a68
--- /dev/null
+++ b/store/spec/portability.md
@@ -0,0 +1,167 @@
+# Harness portability
+
+A harness provides workspace preparation, instructions, skills, toolchain commands, a viewer and
+verdicts. An engine provides file/shell tools and a documented way to load project instructions.
+The runtime binds those two contracts. Package names never occur in an adapter.
+
+## Session lifecycle
+
+`materializeWorkspace` only prepares files and runs init. `prepareHarnessLaunch` then creates a
+bundle under `<workspace>/.harness/runtime/<sha256(session key)>/`:
+
+- `runtime.json`: the selected harness and engine, instructions, expanded environment, legacy
+ default-engine argv, and skill source paths. It contains no account credentials.
+- `CONTEXT.md`: instructions and a discoverable skill index, usable with ordinary file/shell tools.
+- `skills/<name>`: links to installed skill assets, without modifying native discovery directories.
+
+The agent process receives `HARNESS_CONTEXT_FILE` and `HARNESS_SKILLS_DIR` through its own tmux
+environment. A generic, idempotent bootstrap in its effective project instruction file loads that
+context. It does nothing for Coding when that environment variable is absent. Claude and Pi also
+receive their documented append-instruction flag. User project instructions remain in place.
+Each launch clears inherited `HARNESS_*` session variables it does not explicitly supply,
+including a previous account's private grid. Coding and Terminal therefore cannot inherit an
+unrelated session's harness context. Runtime bundles and migration backups are ignored by Git.
+
+Create stores `dshRuntime` beside `engine` and `dsh`. Resume and restart reuse the snapshot; fork
+copies the source snapshot under a new key. Legacy rows use their stable agent id. A store update
+cannot change a saved engine, argv or instructions. Installed tools and skill assets still follow
+package updates. Runtime bundles stay with the workspace, so retained sessions can resume them;
+deleting a workspace removes its runtime state. This isolates configuration, not project output:
+two sessions pointed at the same project intentionally share its artifacts and verdict file.
+
+Missing instructions, missing skills, duplicate skill names, occupied runtime paths, corrupt
+snapshots and engine/identity mismatches fail before the engine is spawned. Symlinked managed
+directories and instruction files are not overwritten. A missing installed package refuses resume
+instead of silently falling back to Coding.
+
+## Existing projects and packages
+
+The spec-1 manifest is unchanged. `engine` is a default; `agent.args` is a legacy extension applied
+only when the chosen engine is that default. The runtime converts old workspace-native skill paths
+in environment values to `HARNESS_SKILLS_DIR`, rewrites workspace-relative instruction examples
+with a quoted `"$HARNESS_SKILLS_DIR"`, and neutralizes the introductory “You are Claude Code/Codex”
+wording in legacy instruction text. It leaves upstream source paths intact.
+
+Older materializers appended package instructions under `<!-- harness:dsh owner/name -->` with no
+end marker. Migration removes an exact match to known installed package text, keeping all other
+project bytes and a `.harness/legacy-AGENTS.md` backup. It removes only native skill links whose
+targets exactly match that package. If the legacy text was edited or its package is missing, it
+remains untouched and launch explains which section needs resolution. There is no safe general
+way to infer where an edited legacy section ends.
+
+`dsh_list.engines` reflects the daemon's adapters, for installed and uninstalled packages alike.
+The desktop trusts the selected machine's answer; old daemons without the field offer the manifest
+default. The same Harness → Agent → Model → Machine → Project form handles Coding and store packages.
+Agent/Model and Machine/Project/Branch are adjacent groups. Advanced hides worktree, approvals and
+profile (Codex subscription launches only); Machine stays visible and Start stays pinned below
+the scrolling fields, reachable from any field with ⇧⏎. Preferences stay in the existing app data folder;
+`new_harness_preferences_v1` separates agent and harness recents and remembers the last engine for
+each harness. Legacy preference keys are read without being deleted.
+
+## Model routing at creation
+
+Harness compatibility and model routing are independent contracts. All integrated process engines
+can load a harness; only engines whose existing grid adapter supports a model override offer local
+and shared models. The selected machine advertises `localModelEngines` and `supportsModelLaunch`
+in `grid_models_list`. The picker includes the matching engine subscription/default login and
+running models, grouped by owned/shared grid, with each serving machine visible. Machine is where
+the agent and project run; it does not constrain where inference runs.
+
+`agent_create` accepts the semantic pair `gridModel` / `gridName`. Both are required together;
+unsupported engines, malformed values, raw grid credentials or a simultaneous Codex subscription
+profile are refused. The creation receipt fingerprints the semantic pair, not a rotating credential.
+After reserving the receipt and before preparing a project, the daemon refreshes model availability
+and resolves the target using the existing grid service. Missing targets return `GRID_UNAVAILABLE`
+without launching or silently using an engine subscription. Repeating a receipt never resolves
+or starts a second time. Clients predating receipts retain their existing response shape.
+
+Drafts and pending receipts retain the exact model/grid. A machine or agent change preserves an
+explicit model and revalidates it; choosing Terminal clears model routing. A fresh session defaults
+to the engine login. Manage Models opens
+the existing lifecycle panel and preserves the draft. Old daemons keep ordinary launches working;
+an explicit model choice requires the capability and explains when an update is needed.
+
+## Adapter evidence
+
+Contracts checked 2026-09-23. The portable baseline needs no private provider APIs or guessed flags.
+
+| Engine | Project instructions / additional context | Primary contract |
+| --- | --- | --- |
+| Claude Code | `CLAUDE.md`, `--append-system-prompt` | Installed 2.1.281 `--help`; [memory](https://code.claude.com/docs/en/memory) |
+| Codex | `AGENTS.override.md`, `AGENTS.md` | [project instructions](https://developers.openai.com/codex/guides/agents-md) |
+| Cursor | `AGENTS.md` | [CLI usage](https://docs.cursor.com/en/cli/using) |
+| OpenCode | `AGENTS.md`, existing `CLAUDE.md` fallback | [rules](https://opencode.ai/docs/rules/) |
+| Pi | `AGENTS.md`, existing `CLAUDE.md`; `--append-system-prompt <file>` | Installed CLI `--help`; [source](https://github.com/badlogic/pi-mono/tree/main/packages/coding-agent) |
+| Hermes | `.hermes.md`, `AGENTS.md`, `CLAUDE.md`, `.cursorrules` | Installed `hermes_cli/_parser.py`, `hermes_cli/tips.py`; [source](https://github.com/NousResearch/hermes-agent) |
+| Command Code | `AGENTS.md` | [project memory](https://commandcode.ai/docs/import) |
+| Devin | `AGENTS.md` | [CLI](https://devin.ai/cli) |
+| Muse | `AGENTS.md`, existing `CLAUDE.md` fallback | Public [release metadata](https://api.meta.ai/muse-code/channels/muse-stable), executable 1.3.0-R3401.1 `/init` and `/rules` contracts |
+| Amp | `AGENTS.md` | [agent instructions](https://ampcode.com/docs/customize/agents-md) |
+| Kilo | `AGENTS.md` | [custom instructions](https://kilo.ai/docs/customize/custom-instructions) |
+| Grok | `AGENTS.md` | [skills and instruction compatibility](https://docs.x.ai/build/features/skills-plugins-marketplaces) |
+| Antigravity | `AGENTS.md`, existing `GEMINI.md` | [rules](https://antigravity.google/docs/rules/) |
+| Copilot | `AGENTS.md` | [custom instructions](https://docs.github.com/en/copilot/how-tos/copilot-cli/customize-copilot/add-custom-instructions) |
+
+The Muse artifact was checksum-verified (`20c5eb32f6aea741adac032c14be2f1897432caaf35144c33279a4d2b0bd8840`,
+macOS ARM64) and inspected without installing it or using credentials. Vendor model execution is
+separate from contract testing; passing fixture tests does not claim that every provider ran a model.
+
+## Validation
+
+`cd cli && npm run test:portability` enforces **100% statements, branches, functions and lines per
+file** for the runtime, adapters, compatibility projection, launch environment and workspace
+materialization, plus semantic model selection and resolution. It also runs DSH integration,
+socket, registry and launch-override regression tests.
+The broader CLI and desktop suites check affected entry points, persistence and existing app flows.
+
+The matrix covers all 72 store agent manifests on all 14 engines (1,008 combinations), including
+restart and fork after package changes. Local instructions and skills use the repository content;
+assets normally downloaded by package setup use small fixtures. A separate subprocess lifecycle
+for every engine verifies workspace init, context and skills, tool execution, artifacts, verdicts,
+restart and fork. These tests do not call provider models or install every native toolchain.
+
+After `cd desktop && flutter test --coverage`, run
+`python3 desktop/tool/check_portability_coverage.py` from the repository root. It requires 100%
+coverage of changed executable desktop lines. Pass `--base <merge-base>` when checking committed
+changes. The interactive host at `desktop/tool/harness_portability_review.dart` uses production
+workspace widgets with an in-memory transport and records launch selections without starting agents.
+It requires an isolated native bundle, `FLUTTER_TEST=1`, and `HARNESS_REVIEW_CATALOG` pointing to a
+JSON array of `dsh_list` rows. Keep its bundle identity separate from the installed application.
+
+### Review evidence (2026-09-23)
+
+- Shuffled portability suite, seed `20260926`: 975 passed, 9 native-toolchain opt-in tests skipped.
+ Core coverage: 217/217 statements, 205/205 branches, 36/36 functions, 172/172 lines, including
+ semantic model selection and resolution.
+- Desktop, seed `20260928`: 679/679 changed executable lines covered; 3,166 passed, 11 skipped,
+ 18 failures. All 18 reproduce on unchanged `33380665` in account lifecycle, sign-out, expiry,
+ local CLI discovery, environment setup, and the machine/model acknowledgement badge test.
+ The changed-file coverage gate passes without exclusions.
+- Final CLI full shuffled regression, seed `20260926`, two workers: 4,432 passed, 63 skipped,
+ no failures. The desk relay test now resets its shared socket inventory before running; its
+ previous shuffle-order failure was independently reproduced on unchanged `33380665`.
+- Focused desktop run: all 99 model selection, form, configured keyboard and entry-rule
+ tests passed, including a correction that labels an explicit Codex subscription profile by name.
+- All 27 store packages with an npm test script passed before the rebase. Model Manager was the
+ only store package changed by the rebase; its current suite passed all 43 tests.
+- TypeScript type checking, CLI build, isolated native app build, and Dart analysis of changed
+ production files and new regression tests passed.
+- Computer-use walkthroughs exercised the actual native review app at narrow and wide widths:
+ Coding and store harnesses; engine-only Agent choices; a legacy harness's compatibility filter;
+ the complete scrollable harness catalog; relevant subscription, owned and shared model choices;
+ independent model/agent machines; search and Enter; Advanced; and fixture session creation.
+ Manage Models and reopening the launch form preserved the selected agent, model, machine and
+ project. Native File > New Harness exercises the same command as Cmd-N; synthetic modifier
+ injection did not deliver Cmd-N, so physical shortcut behavior is not claimed by that walkthrough.
+ Flutter's configured-key and native-command regression tests cover the command dispatch.
+- The native walkthrough found and fixed two layout/accessibility problems: expanding Advanced
+ could push Start below the viewport, and its semantics merged with the form after pinning it.
+ Start is now pinned and has its own accessible bounds. Wide/compact widget tests assert both;
+ a final native accessibility click created the fixture session with the chosen shared model.
+- Final review also found and fixed a model-to-Terminal transition that kept a model behind the
+ disabled Model row and blocked launch. Both forms now omit model routing for Terminal. All 22
+ model/Terminal regressions passed, and the native walkthrough selected a Mac Studio model,
+ switched to Terminal, and successfully submitted a fixture launch without model routing.
+
+Coverage percentages above describe their measured scopes, not full CLI/desktop branch coverage.
+Real provider model calls and the optional native studio installations were not exercised.