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.

Run a local model: one entry, one dialog, one agent that starts it

Tim5c2f8e3f7c4e
diff --git a/cli/build-bundle.mjs b/cli/build-bundle.mjs
index 3497538a2..83f9a63f9 100644
--- a/cli/build-bundle.mjs
+++ b/cli/build-bundle.mjs
@@ -53,5 +53,7 @@ copyFileSync('hook/notify.mjs', 'dist/notify.mjs')
// the source file documents.
mkdirSync('dist/skills', { recursive: true })
copyFileSync('../docs/skills/harness-compute.md', 'dist/skills/harness-compute.md')
+// The `harness-compute` agent definition the same module installs beside the skill (opencode `--agent`).
+copyFileSync('../docs/skills/harness-compute.agent.md', 'dist/skills/harness-compute.agent.md')
console.log(`✓ Bundled dist/cli.js (v${version}) + dist/notify.mjs + dist/skills/`)
diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.ts
index 67c9316b1..78da4ab1a 100644
--- a/cli/src/backendSocket.spec.ts
+++ b/cli/src/backendSocket.spec.ts
@@ -645,12 +645,12 @@ describe('BackendSocket outbound queue', () => {
})).toBe(true)
socket.handleLocalFrame('local:test', {
- type: 'models_list', payload: { requestId: 'local-models' },
+ type: 'models_list', payload: { requestId: 'harness-computes' },
})
await vi.waitFor(() => expect(frames).toContainEqual({
type: 'models_list_result',
payload: {
- requestId: 'local-models',
+ requestId: 'harness-computes',
models: [{ id: 'runtime-v1:s1:codex:gpt-5.6-sol@high', displayName: 'Sol / High' }],
},
}))
@@ -1378,6 +1378,99 @@ describe('agent_retarget onto a Local model resolves web tools', () => {
})
})
+/**
+ * `agent_create` carrying a first prompt, a name and a named agent — the fields the run-a-harness-compute
+ * entry can send (it sends `name` and `agent`). All are validated at the wire, before any pane
+ * exists; what reaches `onCreateAgent` is exactly what cli.ts hands to the launch and the registry.
+ */
+describe('agent_create with a prompt, a name and a named agent', () => {
+ afterEach(() => {
+ vi.restoreAllMocks()
+ })
+
+ const pending: RegisteredSession = {
+ schemaVersion: 2, active: true, launch: { state: 'starting' },
+ agentId: 'named-1', sessionId: '', boundAt: null, engine: 'opencode',
+ transcriptPath: null, projectDir: 'home', cwd: '/home/someone', defaultName: 'Local model',
+ runtimes: [{ backend: 'tmux', paneId: '%11' }], primaryRuntimeKey: 'tmux/%11', tmuxPane: '%11',
+ source: null, title: null, model: null, cliVersion: null, processIdentity: null,
+ registeredAt: 1, updatedAt: 1, lastHookAt: 1, lastTranscriptAt: 1,
+ }
+
+ async function create(choices: Record<string, unknown>) {
+ const socket = new BackendSocket('token')
+ const frames: Array<Record<string, unknown>> = []
+ socket.registerLocalClient('local:named', { sendFrame: (frame) => { frames.push(frame); return true }, sendBinary: () => true })
+ const seen: unknown[] = []
+ socket.onCreateAgent = async (input) => { seen.push(input); return { ok: true, session: pending } }
+ try {
+ socket.handleLocalFrame('local:named', { type: 'agent_create', payload: { requestId: 'r', engine: 'opencode', cwd: '/home/someone', ...choices } })
+ await vi.waitFor(() => expect(frames.some((frame) => frame.type === 'agent_create_result')).toBe(true))
+ } finally {
+ await socket.unregisterLocalClient('local:named')
+ await socket.stop()
+ }
+ const reply = frames.find((frame) => frame.type === 'agent_create_result')?.payload as Record<string, unknown>
+ return { seen, reply }
+ }
+
+ it('passes both through, trimmed, and the name becomes the row\'s defaultName', async () => {
+ const { seen, reply } = await create({ prompt: ' Start a local model on this machine ', name: ' Local model ' })
+ expect(seen).toEqual([expect.objectContaining({ engine: 'opencode', prompt: 'Start a local model on this machine', name: 'Local model' })])
+ expect(reply).toMatchObject({ agent: expect.objectContaining({ id: 'named-1', name: 'Local model' }) })
+ })
+
+ it('sends null for both when neither was given, or when they are blank', async () => {
+ expect((await create({})).seen).toEqual([expect.objectContaining({ prompt: null, name: null })])
+ expect((await create({ prompt: ' ', name: '' })).seen).toEqual([expect.objectContaining({ prompt: null, name: null })])
+ })
+
+ it('refuses an over-long prompt before any pane exists', async () => {
+ const { seen, reply } = await create({ prompt: 'x'.repeat(2001) })
+ expect(reply).toMatchObject({ error: 'PROMPT_TOO_LONG' })
+ expect(seen).toHaveLength(0)
+ expect((await create({ prompt: 'x'.repeat(2000) })).seen).toHaveLength(1)
+ })
+
+ it('refuses a prompt for an engine with no documented mechanism, naming the engine', async () => {
+ const { seen, reply } = await create({ engine: 'cursor', prompt: 'Start a local model on this machine' })
+ expect(reply).toMatchObject({ error: 'PROMPT_UNSUPPORTED', detail: expect.stringContaining('cursor') })
+ expect(seen).toHaveLength(0)
+ })
+
+ it('refuses a prompt that is not text', async () => {
+ const { seen, reply } = await create({ prompt: ['Start a local model'] })
+ expect(reply).toMatchObject({ error: 'INVALID_PROMPT' })
+ expect(seen).toHaveLength(0)
+ })
+
+ it('passes the named agent through for opencode, and null when none was given', async () => {
+ const { seen, reply } = await create({ agent: 'harness-compute', name: 'Local model' })
+ expect(seen).toEqual([expect.objectContaining({ engine: 'opencode', agent: 'harness-compute', name: 'Local model', prompt: null })])
+ expect(reply).toMatchObject({ agent: expect.objectContaining({ id: 'named-1' }) })
+ expect((await create({})).seen).toEqual([expect.objectContaining({ agent: null })])
+ expect((await create({ agent: null })).seen).toEqual([expect.objectContaining({ agent: null })])
+ })
+
+ it('refuses a named agent for an engine with no documented mechanism, naming the engine, before any pane exists', async () => {
+ for (const engine of ['claude', 'codex', 'cursor']) {
+ const { seen, reply } = await create({ engine, agent: 'harness-compute' })
+ expect(reply).toMatchObject({ error: 'AGENT_UNSUPPORTED', detail: expect.stringContaining(engine) })
+ expect(seen).toHaveLength(0)
+ }
+ })
+
+ it('refuses a named agent that is not an identifier — a path, prose, blank, over-long, or not text', async () => {
+ for (const agent of ['', ' ', 'local model', '../etc/passwd', 'a/b', 'x'.repeat(65), ['harness-compute'], 7]) {
+ const { seen, reply } = await create({ agent })
+ expect(reply).toMatchObject({ error: 'INVALID_AGENT' })
+ expect(seen).toHaveLength(0)
+ }
+ })
+})
+
+/** The read-only hardware line for the run-a-harness-compute dialog, answered next to `grid_models_list`. */
+
describe('Autonomous direct isolation from existing relay/browser behavior', () => {
it('permits offline PAKE only for the exact live direct pending connection', async () => {
const backend = new BackendSocket('direct-offline-test')
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
index 19f7f9e95..356fc91ce 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -29,6 +29,7 @@ import { listDir } from './lib/fsBrowse.js'
import { linkCodexProfile, listCodexProfiles } from './lib/codexProfiles.js'
import { parseGridLaunchOverride, type GridLaunchOverride } from './lib/gridLaunch.js'
import { listGridModels, resolveGridTarget } from './lib/gridModels.js'
+import { AGENT_NAME_RE, FirstPromptUnsupportedError, MAX_FIRST_PROMPT_CHARS, NamedAgentUnsupportedError, supportsFirstPrompt, supportsNamedAgent } from './lib/engineLaunch.js'
import { readAccountUsage, type AccountUsageReading } from './lib/accountUsage.js'
import { probeEngines } from './lib/engineProbe.js'
import { AgentCreationReceipts, AgentCreationReceiptError, creationFingerprint, validCreationId, type AgentCreationStatus } from './lib/agentCreationReceipt.js'
@@ -340,6 +341,16 @@ export class BackendSocket {
codexHome: string | null
/** The domain-specific harness to create this agent as (installed here, base engine = `engine`). */
dsh: string | null
+ /** The message the session opens with, already submitted (`FIRST_PROMPT_ARGS` in engineLaunch.ts);
+ * null when the pane opens on an empty input. Validated here — length, and that the engine has a
+ * contract for it — so cli.ts never sees one it cannot hand over. Never logged. */
+ prompt: string | null
+ /** The name the pane opens under, instead of the next `agent-N`; null to number it. */
+ name: string | null
+ /** The engine's named agent the pane opens AS (`NAMED_AGENT_ARGS` in engineLaunch.ts; opencode
+ * `--agent <name>`); null for a general session. Validated here — shape, and that the engine has
+ * a contract for it. Unlike `prompt`, kept on the row so a relaunch opens as it again. */
+ agent: string | null
}) =>
Promise<{ ok: true; session: RegisteredSession } | { ok: false; error: string; detail?: string }>) | null = null
/** Called on `dsh_install` — cli.ts clones/sets up/doctors the harness and reports each phase. */
@@ -1471,6 +1482,7 @@ export class BackendSocket {
return
}
+
case 'models_list': {
const sessionId = typeof payload.agentId === 'string' && payload.agentId
? payload.agentId
@@ -1723,6 +1735,37 @@ export class BackendSocket {
}
dsh = installed.id
}
+ // A first prompt is refused BEFORE any pane exists: an engine with no way to take one would
+ // otherwise open on an empty input and look like the person's request had been heard. The
+ // length bound is a first message's, not a document's. The text itself is never logged.
+ let prompt: string | null = null
+ if (payload.prompt !== undefined && payload.prompt !== null) {
+ if (typeof payload.prompt !== 'string') { reply(type, requestId, { error: 'INVALID_PROMPT', detail: 'prompt must be a string' }); return }
+ const trimmed = payload.prompt.trim()
+ if (trimmed.length > MAX_FIRST_PROMPT_CHARS) {
+ reply(type, requestId, { error: 'PROMPT_TOO_LONG', detail: `prompt is longer than ${MAX_FIRST_PROMPT_CHARS} characters` }); return
+ }
+ if (trimmed && !supportsFirstPrompt(engine)) {
+ reply(type, requestId, { error: 'PROMPT_UNSUPPORTED', detail: new FirstPromptUnsupportedError(engine).message }); return
+ }
+ prompt = trimmed || null
+ }
+ // Blank is "number it", the same as absent — a client that sends an empty field is not
+ // asking for an agent with no name.
+ const name = typeof payload.name === 'string' && payload.name.trim() ? payload.name.trim() : null
+ // The engine's named agent is refused BEFORE any pane exists, like the prompt: an engine with
+ // no way to open as one would otherwise come up as a general session under that agent's
+ // name. The shape is an identifier the engine looks a file up by — never a path.
+ let agent: string | null = null
+ if (payload.agent !== undefined && payload.agent !== null) {
+ if (typeof payload.agent !== 'string' || !AGENT_NAME_RE.test(payload.agent)) {
+ reply(type, requestId, { error: 'INVALID_AGENT', detail: 'agent must be 1-64 letters, digits, `-` or `_`' }); return
+ }
+ if (!supportsNamedAgent(engine)) {
+ reply(type, requestId, { error: 'AGENT_UNSUPPORTED', detail: new NamedAgentUnsupportedError(engine).message }); return
+ }
+ agent = payload.agent
+ }
const input = {
engine,
cwd: typeof cwd === 'string' ? cwd : '',
@@ -1730,6 +1773,9 @@ export class BackendSocket {
grid: grid.state === 'ok' ? grid.override : null,
codexHome,
dsh,
+ prompt,
+ name,
+ agent,
}
if (creationId !== undefined) {
// Reserve before spawning. A transport retry carries the SAME creationId; a deliberate
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index 336df3f1e..96594a700 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -27,6 +27,7 @@ import { homedir, hostname } from 'os'
import { env } from './config/env.js'
import { VERSION } from './version.js'
import { sqlitePreflightMessage } from './lib/sqliteAvailability.js'
+import { binaryOnPath } from './lib/binaryOnPath.js'
import { warmLoginShellEnvironment } from './lib/loginShellEnv.js'
import { ensureUtf8Locale } from './lib/childLocale.js'
import { DialLog } from './cable/dialLog.js'
@@ -59,8 +60,8 @@ import { warnIfGridSignInRemains } from './lib/gridCredentials.js'
import { ENGINE_CLI_COMMANDS, ENGINES, engineBin, enginePathOverride } from './lib/engineBin.js'
import type { AgentEngine } from './engines/types.js'
import { engineInstallRecipe } from './lib/engineInstall.js'
-import { buildEngineCommandArgv, buildEngineLaunchArgv, commandAvailableInInteractiveShell } from './lib/engineLaunch.js'
-import { buildGridEngineLaunch, describeGridLaunch, gridConflictingEnvToClear, gridEnvVarNames, gridProviderId, type GridLaunchMachine, type GridWebSearchStatus } from './lib/gridLaunch.js'
+import { buildEngineCommandArgv, buildEngineLaunchArgv, commandAvailableInInteractiveShell, namedAgentArgs } from './lib/engineLaunch.js'
+import { buildGridEngineLaunch, describeGridLaunch, gridConflictingEnvToClear, gridEnvVarNames, type GridLaunchMachine, type GridWebSearchStatus } from './lib/gridLaunch.js'
import { HERMES_SYSTEM_MANAGED_DIR } from './lib/gridWebMcp.js'
import { writeGridConfigDir } from './lib/gridConfigDir.js'
import { tmuxSupportsSessionEnv, TMUX_SESSION_ENV_MIN } from './lib/tmuxVersion.js'
@@ -157,6 +158,7 @@ import { CursorSubagentManager } from './engines/cursor/subagent.js'
import { CursorTaskHookQueue } from './engines/cursor/taskHookQueue.js'
import { loadCursorPendingTasks, removeCursorPendingTasks } from './engines/cursor/pendingTasks.js'
import { OpencodeReader, readOpencodeMessages } from './engines/opencode/reader.js'
+import { opencodeModelFromArgv, setOpencodeSessionModel } from './engines/opencode/sessionModel.js'
import { lastOpencodeTurnText } from './engines/opencode/normalizer.js'
import { KiloReader, readKiloMessages } from './engines/kilo/reader.js'
import { lastKiloTurnText } from './engines/kilo/normalizer.js'
@@ -186,7 +188,7 @@ import { agentFrame, type AgentFrame } from './lib/agentFrame.js'
import { SessionInputController } from './lib/sessionInput.js'
import { adaptSlashCommand } from './lib/goalCommand.js'
import { RuntimeProfileManager, parseRuntimeProfile } from './lib/runtimeProfile.js'
-import { RuntimeProfileControlError, RuntimeProfileController, inspectRuntimePane } from './lib/runtimeProfileController.js'
+import { RuntimeProfileController, inspectRuntimePane } from './lib/runtimeProfileController.js'
import { deviceErrorText } from './lib/deviceErrors.js'
import { correlateAgentEvent, turnHeartbeatFrame } from './lib/agentEvent.js'
@@ -3578,10 +3580,11 @@ async function runForeground(session: AuthSession): Promise<void> {
return dshLaunch(installed, workspace)
},
}
- // Whatever the source (the row itself, or a grid override the desktop just sent), the agent's DSH
- // and workspace come from the row: a retarget must not silently drop the harness the agent is.
+ // Whatever the source (the row itself, or a grid override the desktop just sent), the agent's DSH,
+ // workspace and named agent come from the row: a retarget must not silently drop the harness the
+ // agent is, or bring a pane opened as `harness-compute` back as a general session.
const relaunchOverrides = (session: RegisteredSession, source: LaunchSource = session): Promise<LaunchOverridesResult> =>
- buildLaunchOverrides(launchOverridesDeps, session.engine, { dsh: session.dsh ?? null, cwd: session.cwd, ...source }, session.agentId)
+ buildLaunchOverrides(launchOverridesDeps, session.engine, { dsh: session.dsh ?? null, cwd: session.cwd, agent: session.agent ?? null, ...source }, session.agentId)
/**
* A restart or a post-reboot restore rebuilds the ROW's own launch, and the machine may decide
@@ -3814,7 +3817,7 @@ async function runForeground(session: AuthSession): Promise<void> {
* pass can miss it — retry `triggerHint` a few times with backoff before giving up.
*/
- backend.onCreateAgent = async ({ engine, cwd, bypassPermission, grid, codexHome, dsh }) => {
+ backend.onCreateAgent = async ({ engine, cwd, bypassPermission, grid, codexHome, dsh, prompt, name, agent }) => {
if (!tmuxBackend) return { ok: false, error: 'TMUX_UNAVAILABLE' }
try {
if (!statSync(cwd).isDirectory()) return { ok: false, error: 'CWD_NOT_FOUND' }
@@ -3909,8 +3912,13 @@ async function runForeground(session: AuthSession): Promise<void> {
// 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 extraArgs = [...(gridLaunch?.args ?? []), ...dshArgs]
- const launchOptions = { bypassPermission, extraArgs: extraArgs.length ? extraArgs : undefined, installIfMissing, clearEnv, cwd }
+ // 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.
+ const extraArgs = [...(gridLaunch?.args ?? []), ...dshArgs, ...(agent ? namedAgentArgs(engine, agent) : [])]
+ // The first prompt is a launch option only — never part of `extraArgs`, which the registry row
+ // carries into a relaunch (engineLaunch.ts, `firstPrompt`).
+ const launchOptions = { bypassPermission, extraArgs: extraArgs.length ? extraArgs : undefined, installIfMissing, clearEnv, cwd, ...(prompt ? { firstPrompt: prompt } : {}) }
const command = buildEngineCommandArgv(engine, launchOptions)
const argv = buildEngineLaunchArgv(engine, launchOptions)
// A tmux route is enough to stream its screen. Register it before looking for a process so both
@@ -3935,7 +3943,9 @@ async function runForeground(session: AuthSession): Promise<void> {
gridLaunchRecord: grid && gridLaunch ? { override: grid, webSearch: gridLaunch.webSearch } : null,
codexHome,
dsh,
+ agent,
bypassPermission,
+ defaultName: name,
})
if (!result.ok) return { ok: false, error: result.error, detail: result.detail }
const { spawned, pending } = result
@@ -4142,6 +4152,22 @@ async function runForeground(session: AuthSession): Promise<void> {
}
const valid = await validateLaunchOverrides(launchOverridesDeps, session.engine, target)
if (!valid.ok) return { ok: false, error: valid.error, detail: valid.detail }
+ // A resumed opencode session takes its model from its own rows in opencode.db, not from `-m`
+ // (see below), and those rows are written through the `sqlite3` CLI. Without it the respawn
+ // would land the right provider, key and argv on a pane that then answers on the OLD model —
+ // the failure this handler exists to refuse — so it is refused here, before the pane is touched.
+ // Only when the launch will name a model: a grid launch always does; a move home does only when
+ // the remembered model carries its provider (`subscriptionModel.ts`), and otherwise the engine
+ // decides, as it always did.
+ const rewritesOpencodeSession = session.engine === 'opencode' && !!session.sessionId
+ && (!!grid || !!remembered?.includes('/'))
+ if (rewritesOpencodeSession && !binaryOnPath('sqlite3')) {
+ return {
+ ok: false,
+ error: 'OPENCODE_SQLITE_MISSING',
+ detail: 'the sqlite3 CLI is not on PATH, and a resumed opencode session keeps its model unless its store is rewritten — install sqlite3 and retry',
+ }
+ }
// Mid-turn is the one state where restarting costs real work: the conversation comes back but
// whatever the engine was doing does not. The app is told which agents these are so the user can
// move them once they are done, rather than being asked to choose between losing a turn and losing
@@ -4186,6 +4212,26 @@ async function runForeground(session: AuthSession): Promise<void> {
// already cleared but its live process untouched would leave that process still talking to the
// grid while the retarget reports failed — the exact half-applied state this handler exists to
// refuse.
+ //
+ // OpenCode's TUI drops `-m` when it RESUMES a session: it restores the model from the session's
+ // LAST USER MESSAGE (`data.model`), and its server falls back to the `session.model` column
+ // (measured on 1.18.31; upstream anomalyco/opencode #26901). Nothing else — config, model.json,
+ // `--fork` — changes a resumed session's model; the picker is the only writer opencode ships,
+ // and those two rows are what it writes. So they are written here, through SQL, before the
+ // respawn, with the exact `provider/model` the respawn's own `-m` names — and the TUI opens
+ // already on it, with nothing typed into the pane. Before the live process is touched, so a
+ // write that fails refuses the move with that process still on its old target. A session with
+ // no user message yet has nothing to restore from and takes `-m` on launch, so it is skipped.
+ if (rewritesOpencodeSession) {
+ const model = opencodeModelFromArgv(built.overrides.extraArgs)
+ if (model) {
+ const written = await setOpencodeSessionModel(OPENCODE_DB, session.sessionId, model)
+ if (!written.ok && written.code !== 'OPENCODE_SESSION_NOT_FOUND') {
+ console.warn(`[grid] retarget ${sid(session.agentId)} refused · ${written.code} · ${written.detail}`)
+ return { ok: false, error: written.code, detail: written.detail }
+ }
+ }
+ }
if (!grid) {
const cleared = await tmuxBackend.clearEnv(pane, gridEnvVarNames(session.engine))
if (cleared.state !== 'succeeded') {
@@ -4227,41 +4273,9 @@ async function runForeground(session: AuthSession): Promise<void> {
? describeGridLaunch(session.engine, record.override, record.webSearch)
: `${session.engine} on its own login`
console.log(`${where} · retargeted ${sid(session.agentId)} · ${how}`)
- // OpenCode's TUI drops `-m` when it RESUMES a session — it restores the model stored on that
- // session instead — so the respawn above lands the right provider, key and argv on a pane that
- // then answers on the OLD model. Nothing else here can tell: the process is correct, and only
- // the engine's own footer says otherwise. Selecting through its `/models` picker is what makes
- // the move real; see [RuntimeProfileController.selectOpencodeModel] for the measurements.
- //
- // Only on a RESUME, and only when a model was actually named: a fresh session takes `-m`, and
- // with nothing named there is nothing to select — the engine's own default is the right answer.
- //
- // ⚠️ The picker needs a `provider/model` id, and a grid override carries the model BARE
- // (`Qwen3.6-35B-A3B`) — the provider is derived from the network name, exactly as the `-m` this
- // same launch passes derives it. Handing the bare id over refused instantly as MODEL_UNAVAILABLE,
- // which read as "the grid is not serving it" for a grid that was serving it fine.
- const selecting = session.engine === 'opencode' && outcome.resumed
- ? (grid
- ? (grid.model ? `${gridProviderId(grid.networkName)}/${grid.model}` : null)
- : remembered)
- : null
- if (selecting) {
- try {
- await runtimeController.selectOpencodeModel(session, selecting)
- } catch (err) {
- // The move HAPPENED — the registry above records the process that is really running — so
- // this reports what is true rather than pretending either way: the agent is where it was
- // asked to go, on a model it was not asked to be on. Saying `ok` here is the failure this
- // handler exists to refuse; it would read as a working switch and bill the wrong account.
- const detail = err instanceof RuntimeProfileControlError ? err.code : String(err)
- console.warn(`[grid] ${sid(session.agentId)} moved but could not select ${selecting} · ${detail}`)
- return {
- ok: false,
- error: 'MODEL_SELECT_FAILED',
- detail: `moved, but opencode stayed on its previous model (${detail}) — pick ${selecting} from /models in the pane`,
- }
- }
- }
+ // Nothing is typed into the pane after the respawn. A resumed opencode session used to be put
+ // on its model through the `/models` picker here (MODEL_SELECT_FAILED); its store is rewritten
+ // before the respawn instead, see above.
return { ok: true }
} finally {
release()
diff --git a/cli/src/config/env.ts b/cli/src/config/env.ts
index 7894ef686..6a7bf2942 100644
--- a/cli/src/config/env.ts
+++ b/cli/src/config/env.ts
@@ -174,6 +174,11 @@ const envSchema = z.object({
OPENCODE_SKILL_DIR: z
.string()
.default(join(process.env.XDG_CONFIG_HOME || join(homedir(), '.config'), 'opencode', 'skills')),
+ // OpenCode agents dir (honors XDG_CONFIG_HOME) — where the adapter drops the `harness-compute` agent
+ // definition, so `opencode --agent harness-compute` opens a pane AS the agent that starts a local model.
+ OPENCODE_AGENT_DIR: z
+ .string()
+ .default(join(process.env.XDG_CONFIG_HOME || join(homedir(), '.config'), 'opencode', 'agents')),
// Kilo state root — the SQLite store lives at <KILO_DATA_DIR>/kilo.db. Kilo is an opencode fork and
// keeps the same layout, but NOT the same overrides: measured on 7.4.20 via `kilo debug paths`, it
// honours XDG_DATA_HOME and ignores both `KILO_DATA_DIR` and `OPENCODE_DATA_DIR`. So this variable
diff --git a/cli/src/engines/opencode/sessionModel.spec.ts b/cli/src/engines/opencode/sessionModel.spec.ts
new file mode 100644
index 000000000..9aa168e05
--- /dev/null
+++ b/cli/src/engines/opencode/sessionModel.spec.ts
@@ -0,0 +1,181 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { execFileSync } from 'child_process'
+import { mkdtempSync, rmSync } from 'fs'
+import { tmpdir } from 'os'
+import { join } from 'path'
+import { opencodeModelFromArgv, setOpencodeSessionModel } from './sessionModel.js'
+
+const hasSqlite = (() => {
+ try { execFileSync('sqlite3', ['-version'], { stdio: 'ignore' }); return true } catch { return false }
+})()
+const d = hasSqlite ? describe : describe.skip
+
+const SID = 'ses_testABC123'
+const OTHER = 'ses_otherXYZ789'
+const OLD = { providerID: 'opencode', modelID: 'big-pickle' }
+const NEW = { providerID: 'minhduccm90-cecb9724', modelID: 'Qwen3.6-35B-A3B' }
+
+function run(db: string, sql: string): string {
+ return execFileSync('sqlite3', [db, sql], { stdio: ['ignore', 'pipe', 'inherit'] }).toString()
+}
+function esc(v: unknown): string {
+ return JSON.stringify(v).replace(/'/g, "''")
+}
+/** The columns the writer touches, in the shape opencode 1.18.x keeps them. */
+function schema(db: string, opts: { sessionModelColumn?: boolean } = {}): void {
+ const model = opts.sessionModelColumn === false ? '' : ', model TEXT'
+ run(db,
+ `CREATE TABLE session (id TEXT PRIMARY KEY, title TEXT${model});` +
+ 'CREATE TABLE message (id TEXT PRIMARY KEY, session_id TEXT, time_created INTEGER, data TEXT);')
+}
+function insertSession(db: string, id: string, model: Record<string, unknown> | null): void {
+ run(db, `INSERT INTO session (id, title, model) VALUES ('${id}', 'a title', ${model ? `'${esc(model)}'` : 'NULL'});`)
+}
+function insertMessage(db: string, sid: string, mid: string, tc: number, data: Record<string, unknown>): void {
+ run(db, `INSERT INTO message VALUES ('${mid}','${sid}',${tc},'${esc(data)}');`)
+}
+function messageData(db: string, mid: string): Record<string, unknown> {
+ return JSON.parse(run(db, `SELECT data FROM message WHERE id = '${mid}';`).trim())
+}
+function sessionModel(db: string, sid: string): Record<string, unknown> | null {
+ const raw = run(db, `SELECT model FROM session WHERE id = '${sid}';`).trim()
+ return raw ? JSON.parse(raw) : null
+}
+const userMsg = (text: string, model = OLD) => ({ role: 'user', model, text })
+const assistantMsg = (model = OLD) => ({ role: 'assistant', providerID: model.providerID, modelID: model.modelID })
+
+/** A conversation as opencode leaves it: user, assistant, user, assistant — plus a stranger. */
+function seed(db: string): void {
+ insertSession(db, SID, { id: OLD.modelID, providerID: OLD.providerID, variant: 'default' })
+ insertSession(db, OTHER, { id: OLD.modelID, providerID: OLD.providerID, variant: 'default' })
+ insertMessage(db, SID, 'u1', 1, userMsg('first'))
+ insertMessage(db, SID, 'a1', 2, assistantMsg())
+ insertMessage(db, SID, 'u2', 3, userMsg('second'))
+ insertMessage(db, SID, 'a2', 4, assistantMsg())
+ insertMessage(db, OTHER, 'o1', 5, userMsg('elsewhere'))
+}
+
+d('setOpencodeSessionModel (sqlite3 CLI)', () => {
+ let dir = ''
+ let db = ''
+ const realPath = process.env.PATH
+ beforeEach(() => {
+ dir = mkdtempSync(join(tmpdir(), 'oc-session-model-'))
+ db = join(dir, 'opencode.db')
+ vi.spyOn(console, 'log').mockImplementation(() => {})
+ })
+ afterEach(() => {
+ process.env.PATH = realPath
+ vi.restoreAllMocks()
+ rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 })
+ })
+
+ it('rewrites only the latest user message and the session row', async () => {
+ schema(db)
+ seed(db)
+
+ await expect(setOpencodeSessionModel(db, SID, NEW)).resolves.toEqual({ ok: true })
+
+ // The row the resumed TUI reads its model from (prompt/index.tsx) — and only that row.
+ expect(messageData(db, 'u2')).toEqual({ role: 'user', model: NEW, text: 'second' })
+ // What the server's prompt path falls back to, in the shape opencode's own picker writes.
+ expect(sessionModel(db, SID)).toEqual({ id: NEW.modelID, providerID: NEW.providerID, variant: 'default' })
+ // An older user message, both assistant rows, and the other session are exactly as seeded.
+ expect(messageData(db, 'u1')).toEqual({ role: 'user', model: OLD, text: 'first' })
+ expect(messageData(db, 'a1')).toEqual(assistantMsg())
+ expect(messageData(db, 'a2')).toEqual(assistantMsg())
+ expect(messageData(db, 'o1')).toEqual({ role: 'user', model: OLD, text: 'elsewhere' })
+ expect(sessionModel(db, OTHER)).toEqual({ id: OLD.modelID, providerID: OLD.providerID, variant: 'default' })
+ })
+
+ it('keeps the rest of the user message, and a variant it carried', async () => {
+ schema(db)
+ insertSession(db, SID, null)
+ insertMessage(db, SID, 'u1', 1, { role: 'user', model: { ...OLD, variant: 'high' }, agent: 'build', time: { created: 1 } })
+
+ await expect(setOpencodeSessionModel(db, SID, NEW)).resolves.toEqual({ ok: true })
+
+ expect(messageData(db, 'u1')).toEqual({ role: 'user', model: { ...NEW, variant: 'high' }, agent: 'build', time: { created: 1 } })
+ expect(sessionModel(db, SID)).toEqual({ id: NEW.modelID, providerID: NEW.providerID, variant: 'default' })
+ })
+
+ it('passes ids through as values, never as SQL', async () => {
+ schema(db)
+ seed(db)
+ const odd = { providerID: "grid'; DROP TABLE session; --", modelID: 'a/b "c" d' }
+
+ await expect(setOpencodeSessionModel(db, SID, odd)).resolves.toEqual({ ok: true })
+
+ expect(messageData(db, 'u2')).toEqual({ role: 'user', model: odd, text: 'second' })
+ expect(sessionModel(db, SID)).toEqual({ id: odd.modelID, providerID: odd.providerID, variant: 'default' })
+ })
+
+ it('is one transaction: a failing session UPDATE leaves the message UPDATE unapplied', async () => {
+ // No `model` column on `session` makes the SECOND statement fail after the first has run.
+ schema(db, { sessionModelColumn: false })
+ run(db, `INSERT INTO session (id, title) VALUES ('${SID}', 'a title');`)
+ insertMessage(db, SID, 'u1', 1, userMsg('first'))
+
+ const result = await setOpencodeSessionModel(db, SID, NEW)
+
+ expect(result).toMatchObject({ ok: false, code: 'OPENCODE_DB_WRITE_FAILED' })
+ expect((result as { detail: string }).detail).toMatch(/no such column: model/)
+ expect(messageData(db, 'u1')).toEqual(userMsg('first'))
+ })
+
+ it('reports OPENCODE_SESSION_NOT_FOUND for a session with no user message, and writes nothing', async () => {
+ schema(db)
+ insertSession(db, SID, { id: OLD.modelID, providerID: OLD.providerID, variant: 'default' })
+ // An assistant row alone (never happens in practice) must not be rewritten either.
+ insertMessage(db, SID, 'a1', 1, assistantMsg())
+ insertMessage(db, OTHER, 'o1', 2, userMsg('elsewhere'))
+
+ await expect(setOpencodeSessionModel(db, SID, NEW)).resolves.toMatchObject({ ok: false, code: 'OPENCODE_SESSION_NOT_FOUND' })
+
+ expect(sessionModel(db, SID)).toEqual({ id: OLD.modelID, providerID: OLD.providerID, variant: 'default' })
+ expect(messageData(db, 'a1')).toEqual(assistantMsg())
+ expect(messageData(db, 'o1')).toEqual(userMsg('elsewhere'))
+ // An unknown session is the same answer — nothing to rewrite.
+ await expect(setOpencodeSessionModel(db, 'ses_nobody', NEW)).resolves.toMatchObject({ ok: false, code: 'OPENCODE_SESSION_NOT_FOUND' })
+ // And so is an id that is not an opencode session id at all; it never reaches sqlite3.
+ await expect(setOpencodeSessionModel(db, "ses_x'; --", NEW)).resolves.toMatchObject({ ok: false, code: 'OPENCODE_SESSION_NOT_FOUND' })
+ })
+
+ it('reports OPENCODE_SQLITE_MISSING when the CLI is not on PATH, and writes nothing', async () => {
+ schema(db)
+ seed(db)
+ const empty = mkdtempSync(join(tmpdir(), 'no-sqlite-'))
+ try {
+ process.env.PATH = empty
+ await expect(setOpencodeSessionModel(db, SID, NEW)).resolves.toMatchObject({ ok: false, code: 'OPENCODE_SQLITE_MISSING' })
+ } finally {
+ process.env.PATH = realPath
+ rmSync(empty, { recursive: true, force: true })
+ }
+ expect(messageData(db, 'u2')).toEqual({ role: 'user', model: OLD, text: 'second' })
+ expect(sessionModel(db, SID)).toEqual({ id: OLD.modelID, providerID: OLD.providerID, variant: 'default' })
+ })
+
+ it('reports OPENCODE_DB_WRITE_FAILED when the DB cannot be opened', async () => {
+ await expect(setOpencodeSessionModel(join(dir, 'missing', 'opencode.db'), SID, NEW))
+ .resolves.toMatchObject({ ok: false, code: 'OPENCODE_DB_WRITE_FAILED' })
+ })
+})
+
+describe('opencodeModelFromArgv', () => {
+ it('reads the last -m and splits provider from model at the first slash', () => {
+ expect(opencodeModelFromArgv(['-m', 'minhduccm90-cecb9724/Qwen3.6-35B-A3B'])).toEqual(NEW)
+ expect(opencodeModelFromArgv(['--model', 'vibe/minimax/minimax-m3'])).toEqual({ providerID: 'vibe', modelID: 'minimax/minimax-m3' })
+ expect(opencodeModelFromArgv(['--model=opencode/big-pickle'])).toEqual(OLD)
+ expect(opencodeModelFromArgv(['-m', 'a/b', '--agent', 'build', '-m', 'c/d'])).toEqual({ providerID: 'c', modelID: 'd' })
+ })
+
+ it('answers null when the argv names no usable model', () => {
+ expect(opencodeModelFromArgv([])).toBeNull()
+ expect(opencodeModelFromArgv(['--agent', 'build'])).toBeNull()
+ expect(opencodeModelFromArgv(['-m'])).toBeNull()
+ expect(opencodeModelFromArgv(['-m', 'bare-model'])).toBeNull()
+ expect(opencodeModelFromArgv(['-m', '/x'])).toBeNull()
+ expect(opencodeModelFromArgv(['-m', 'x/'])).toBeNull()
+ })
+})
diff --git a/cli/src/engines/opencode/sessionModel.ts b/cli/src/engines/opencode/sessionModel.ts
new file mode 100644
index 000000000..0cf8e2086
--- /dev/null
+++ b/cli/src/engines/opencode/sessionModel.ts
@@ -0,0 +1,152 @@
+/**
+ * Put a RESUMED opencode session on a model, by writing what its own picker writes.
+ *
+ * ## Why a session launched with `-m` needs this at all
+ *
+ * When `opencode --session <id>` loads, the TUI sets its current model from the LAST USER MESSAGE's
+ * `data.model` (`{providerID, modelID, variant?}` — `packages/tui/src/component/prompt/index.tsx`,
+ * v1.18.31), which overrides `-m`; the server's prompt path falls back to the `session.model` column
+ * (`{"id","providerID","variant":"default"}`). Nothing else — config `model`, `model.json`, `--fork`
+ * — changes a resumed session's model (upstream: anomalyco/opencode #26901, #26351, #45204). So a
+ * retarget that respawns with `--session` lands the right provider, key and argv on a pane that then
+ * answers on the OLD model, and only the engine's own footer says so.
+ *
+ * The picker is the only writer opencode ships, and what it writes is those two rows. This writes the
+ * same two rows, through SQL, in one transaction, before the respawn — so the TUI opens already on
+ * the model, with nothing typed into it and no dependence on the picker's layout.
+ *
+ * ## Access
+ *
+ * The `sqlite3` CLI, exactly as `reader.ts` reads this DB: same binary, same `ENOENT` → "sqlite3
+ * missing", no native dependency. opencode opens the DB in WAL mode with its own `busy_timeout 5000`,
+ * so a concurrent UPDATE from here is safe; `PRAGMA busy_timeout` on this side covers a write that
+ * lands during its checkpoint. ⚠️ Never copy, replace or delete the DB or its `-wal` / `-shm` files:
+ * other opencode processes have them open, and that is how this DB was damaged during research.
+ *
+ * ## Rows
+ *
+ * Only the session's latest user message and its `session` row. Assistant messages, older user
+ * messages, `event` rows and every other session are left alone. A session with no user message yet
+ * has nothing to rewrite — and does not need it: with no message to restore from, the TUI takes `-m`
+ * on the respawn. That case is reported as `OPENCODE_SESSION_NOT_FOUND` and the caller proceeds.
+ */
+
+import { execFile } from 'child_process'
+import { promisify } from 'util'
+
+const execFileAsync = promisify(execFile)
+
+/** Same shape `reader.ts` accepts — an opencode session id is `ses_` + base62. */
+const ID_RE = /^[A-Za-z0-9_]+$/
+
+export interface OpencodeSessionModel {
+ /** opencode's provider key, e.g. `opencode` or a grid's `gridProviderId(networkName)`. */
+ providerID: string
+ /** The model id under that provider, e.g. `big-pickle` or `Qwen3.6-35B-A3B`. */
+ modelID: string
+}
+
+export type SetOpencodeSessionModelResult =
+ | { ok: true }
+ | {
+ ok: false
+ code: 'OPENCODE_SQLITE_MISSING' | 'OPENCODE_SESSION_NOT_FOUND' | 'OPENCODE_DB_WRITE_FAILED'
+ detail: string
+ }
+
+/** A SQL string literal — the only way a value reaches the statement. */
+function lit(value: string): string {
+ return `'${value.replace(/'/g, "''")}'`
+}
+
+/**
+ * The `provider/model` an opencode argv names, split the way opencode splits it: the provider is
+ * everything before the FIRST slash, the model is the rest (`vibe/minimax/minimax-m3` → `vibe` +
+ * `minimax/minimax-m3`). Reads the LAST `-m`/`--model`, which is the one opencode honours.
+ * Null when the argv names no model — then there is nothing to write and the engine decides.
+ */
+export function opencodeModelFromArgv(args: readonly string[]): OpencodeSessionModel | null {
+ let id: string | null = null
+ for (let i = 0; i < args.length; i++) {
+ const arg = args[i]
+ if ((arg === '-m' || arg === '--model') && i + 1 < args.length) { id = args[i + 1]; i++ }
+ else if (arg.startsWith('--model=')) id = arg.slice('--model='.length)
+ }
+ if (!id) return null
+ const slash = id.indexOf('/')
+ if (slash <= 0 || slash === id.length - 1) return null
+ return { providerID: id.slice(0, slash), modelID: id.slice(slash + 1) }
+}
+
+/**
+ * Rewrite `sessionId`'s model in `dbPath` so that resuming it opens on `model`.
+ *
+ * One transaction: both rows or neither. Refuses without writing when `sqlite3` is absent, when the
+ * id is not an opencode session id, or when the session has no user message yet (see the header).
+ */
+export async function setOpencodeSessionModel(
+ dbPath: string,
+ sessionId: string,
+ model: OpencodeSessionModel,
+): Promise<SetOpencodeSessionModelResult> {
+ if (!ID_RE.test(sessionId)) {
+ return { ok: false, code: 'OPENCODE_SESSION_NOT_FOUND', detail: `not an opencode session id: ${sessionId}` }
+ }
+ if (!model.providerID || !model.modelID) {
+ return { ok: false, code: 'OPENCODE_DB_WRITE_FAILED', detail: 'refusing to write an empty provider or model id' }
+ }
+ const sid = lit(sessionId)
+ const provider = lit(model.providerID)
+ const modelId = lit(model.modelID)
+ // The user-message guard is repeated on the session UPDATE so a session with no user message is
+ // touched by neither statement: the transaction then commits with nothing changed, which is how
+ // "no user message yet" is told apart from a failed write. `changes()` after each UPDATE is the
+ // only stdout this reads.
+ const hasUser =
+ `EXISTS (SELECT 1 FROM message WHERE session_id = ${sid} AND json_extract(data, '$.role') = 'user')`
+ const sql = [
+ 'PRAGMA busy_timeout = 5000;',
+ 'BEGIN IMMEDIATE;',
+ `UPDATE message SET data = json_set(data, '$.model.providerID', ${provider}, '$.model.modelID', ${modelId}) ` +
+ `WHERE id = (SELECT id FROM message WHERE session_id = ${sid} AND json_extract(data, '$.role') = 'user' ` +
+ 'ORDER BY time_created DESC LIMIT 1);',
+ 'SELECT changes();',
+ `UPDATE session SET model = json_object('id', ${modelId}, 'providerID', ${provider}, 'variant', 'default') ` +
+ `WHERE id = ${sid} AND ${hasUser};`,
+ 'SELECT changes();',
+ 'COMMIT;',
+ ].join('\n')
+
+ let stdout: string
+ try {
+ // `-bail` stops at the first failing statement; the shell then exits with the transaction still
+ // open, and SQLite rolls it back on close — so a failing second UPDATE leaves the first unapplied.
+ ({ stdout } = await execFileAsync('sqlite3', ['-batch', '-bail', dbPath, sql]))
+ } catch (err) {
+ const error = err as NodeJS.ErrnoException & { stderr?: string }
+ if (error?.code === 'ENOENT') {
+ return { ok: false, code: 'OPENCODE_SQLITE_MISSING', detail: 'sqlite3 CLI not found on PATH' }
+ }
+ const stderr = String(error?.stderr ?? '').trim()
+ return { ok: false, code: 'OPENCODE_DB_WRITE_FAILED', detail: stderr || String(error?.message ?? err) }
+ }
+ const lines = stdout.trim().split('\n').map((line) => line.trim()).filter(Boolean)
+ // Lines: the pragma's echo, then the two change counts.
+ const messages = Number(lines[lines.length - 2])
+ const sessions = Number(lines[lines.length - 1])
+ if (!Number.isFinite(messages) || !Number.isFinite(sessions)) {
+ return { ok: false, code: 'OPENCODE_DB_WRITE_FAILED', detail: `unexpected sqlite3 output: ${stdout.trim().slice(0, 200)}` }
+ }
+ if (messages === 0) {
+ return {
+ ok: false,
+ code: 'OPENCODE_SESSION_NOT_FOUND',
+ detail: `session ${sessionId} has no user message yet — nothing to rewrite; -m applies on launch`,
+ }
+ }
+ console.log(
+ `[opencode] session model set to ${model.providerID}/${model.modelID} · ` +
+ `${messages} message row, ${sessions} session row`,
+ )
+ return { ok: true }
+}
diff --git a/cli/src/lib/createAgentPane.spec.ts b/cli/src/lib/createAgentPane.spec.ts
index 4f9c04879..27b44900c 100644
--- a/cli/src/lib/createAgentPane.spec.ts
+++ b/cli/src/lib/createAgentPane.spec.ts
@@ -98,6 +98,22 @@ describe('createAndRegisterPane', () => {
expect(tmuxBackend.kill).toHaveBeenCalledTimes(3)
})
+ it('records the named agent and the requested name on the row it opens', async () => {
+ const { registry } = await loadRegistryModule()
+ registry.load()
+ const tmuxBackend = fakeTmux([succeeded('%1')])
+
+ const result = await createAndRegisterPane({
+ tmuxBackend, registry, engine: 'opencode', cwd: '/home/someone', sessionLabel: 'harness-opencode-1',
+ argv: ['opencode', '--agent', 'harness-compute'], agent: 'harness-compute', defaultName: 'Local model',
+ })
+
+ expect(result.ok).toBe(true)
+ if (!result.ok) return
+ expect(result.pending).toMatchObject({ engine: 'opencode', agent: 'harness-compute', defaultName: 'Local model' })
+ expect(registry.byAgent(result.pending.agentId)).toMatchObject({ agent: 'harness-compute' })
+ })
+
it('does not retry a tmux spawn failure', async () => {
const { registry } = await loadRegistryModule()
registry.load()
diff --git a/cli/src/lib/createAgentPane.ts b/cli/src/lib/createAgentPane.ts
index ada795248..9b5c4d494 100644
--- a/cli/src/lib/createAgentPane.ts
+++ b/cli/src/lib/createAgentPane.ts
@@ -32,11 +32,15 @@ export interface CreateAgentPaneDeps {
gridLaunchRecord?: GridLaunchRecord | null
codexHome?: string | null
dsh?: string | null
+ agent?: string | null
bypassPermission?: boolean
+ defaultName?: string | null
}) => RegisteredSession | null }
engine: AgentEngine
cwd?: string | null
bypassPermission?: boolean
+ /** The name the creator asked for (`agent_create`'s `name`); the registry numbers the agent without one. */
+ defaultName?: string | null
/** Base tmux session name (`-s`). Retries append `-r<attempt>` — see module doc. */
sessionLabel: string
argv: string[]
@@ -49,6 +53,9 @@ export interface CreateAgentPaneDeps {
codexHome?: string | null
/** The domain-specific harness this agent is created as, if any. */
dsh?: 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
maxAttempts?: number
}
@@ -83,7 +90,9 @@ export async function createAndRegisterPane(deps: CreateAgentPaneDeps): Promise<
gridLaunchRecord: deps.gridLaunchRecord,
codexHome: deps.codexHome,
dsh: deps.dsh,
+ agent: deps.agent,
bypassPermission: deps.bypassPermission,
+ defaultName: deps.defaultName,
})
if (pending) return { ok: true, spawned, pending }
console.warn(`[agent] create ${deps.engine} registration failed · pane ${spawned.runtime.paneId} · `
diff --git a/cli/src/lib/engineLaunch.spec.ts b/cli/src/lib/engineLaunch.spec.ts
index edc4053d4..0b5177d2c 100644
--- a/cli/src/lib/engineLaunch.spec.ts
+++ b/cli/src/lib/engineLaunch.spec.ts
@@ -3,11 +3,20 @@ import { chmodSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import {
+ AGENT_NAME_RE,
BYPASS_PERMISSION_FLAGS,
+ FIRST_PROMPT_ARGS,
+ FirstPromptUnsupportedError,
LAUNCH_RESUME_FLAG,
+ NAMED_AGENT_ARGS,
+ NamedAgentUnsupportedError,
buildEngineCommandArgv,
buildEngineLaunchArgv,
commandAvailableInInteractiveShell,
+ firstPromptArgs,
+ namedAgentArgs,
+ supportsFirstPrompt,
+ supportsNamedAgent,
unreadableCwdGuard,
} from './engineLaunch.js'
import { ENGINES } from '../engines/types.js'
@@ -207,6 +216,104 @@ describe('buildEngineLaunchArgv', () => {
})
})
+describe('a first prompt on launch', () => {
+ const PROMPT = 'Start a local model on this machine'
+
+ it('hands opencode the text through its TUI flag', () => {
+ expect(buildEngineCommandArgv('opencode', { firstPrompt: PROMPT }))
+ .toEqual([engineBin('opencode'), '--prompt', PROMPT])
+ })
+
+ it('hands claude and codex the text positionally', () => {
+ expect(buildEngineCommandArgv('claude', { firstPrompt: PROMPT })).toEqual([engineBin('claude'), PROMPT])
+ expect(buildEngineCommandArgv('codex', { firstPrompt: PROMPT })).toEqual([engineBin('codex'), PROMPT])
+ })
+
+ it('puts the text LAST, after every flag, so a positional is never read as an option value', () => {
+ expect(buildEngineCommandArgv('claude', { firstPrompt: PROMPT, bypassPermission: true, extraArgs: ['--allowedTools=WebSearch'] }))
+ .toEqual([engineBin('claude'), '--dangerously-skip-permissions', '--allowedTools=WebSearch', PROMPT])
+ expect(buildEngineCommandArgv('opencode', { firstPrompt: PROMPT, bypassPermission: true, extraArgs: ['-m', 'local/qwen'] }))
+ .toEqual([engineBin('opencode'), '--auto', '-m', 'local/qwen', '--prompt', PROMPT])
+ })
+
+ it('refuses an engine with no documented mechanism, naming the engine, rather than dropping the text', () => {
+ expect(supportsFirstPrompt('cursor')).toBe(false)
+ expect(() => firstPromptArgs('cursor', PROMPT)).toThrow(FirstPromptUnsupportedError)
+ let refusal: unknown
+ try { buildEngineCommandArgv('cursor', { firstPrompt: PROMPT }) } catch (error) { refusal = error }
+ expect(refusal).toBeInstanceOf(FirstPromptUnsupportedError)
+ expect((refusal as FirstPromptUnsupportedError).code).toBe('PROMPT_UNSUPPORTED')
+ expect((refusal as FirstPromptUnsupportedError).message).toContain('cursor')
+ })
+
+ it('leaves the argv unchanged with no prompt, or an empty one', () => {
+ expect(buildEngineCommandArgv('opencode', {})).toEqual([engineBin('opencode')])
+ expect(buildEngineCommandArgv('opencode', { firstPrompt: '' })).toEqual([engineBin('opencode')])
+ expect(buildEngineCommandArgv('cursor', { firstPrompt: '' })).toEqual([engineBin('cursor')])
+ })
+
+ it('reaches the engine as ONE positional argument through the pane shell, however it is spelled', async () => {
+ // The pane script execs "$@": the prompt must arrive as a single argv entry, spaces, quotes and
+ // all, rather than being re-split by the shell.
+ const spelled = `Start a local model on "this" machine; it's $HOME`
+ const [, , paneScript, marker, ...command] = buildEngineLaunchArgv('claude', { firstPrompt: spelled }, '/bin/sh')
+ expect(marker).toBe('harness-engine')
+ expect(command).toEqual([engineBin('claude'), spelled])
+ const { execFile } = await import('node:child_process')
+ const seen = await new Promise<string>((resolve, reject) => {
+ execFile('/bin/sh', ['-c', paneScript, 'harness-engine', '/bin/sh', '-c', 'printf "%s" "$1"', 'engine', spelled],
+ { timeout: 10_000 }, (error, stdout) => (error ? reject(error) : resolve(stdout)))
+ })
+ expect(seen).toBe(spelled)
+ })
+
+ it('has an entry (possibly null) for every known engine — no engine silently falls through', () => {
+ for (const engine of ENGINES) {
+ expect(Object.prototype.hasOwnProperty.call(FIRST_PROMPT_ARGS, engine)).toBe(true)
+ }
+ expect(supportsFirstPrompt('opencode')).toBe(true)
+ expect(supportsFirstPrompt('claude')).toBe(true)
+ expect(supportsFirstPrompt('codex')).toBe(true)
+ })
+})
+
+describe('opening as a named agent', () => {
+ it('hands opencode the name through --agent, in the extraArgs slot a relaunch also uses', () => {
+ expect(namedAgentArgs('opencode', 'harness-compute')).toEqual(['--agent', 'harness-compute'])
+ expect(buildEngineCommandArgv('opencode', { bypassPermission: true, extraArgs: ['-m', 'local/qwen', ...namedAgentArgs('opencode', 'harness-compute')] }))
+ .toEqual([engineBin('opencode'), '--auto', '-m', 'local/qwen', '--agent', 'harness-compute'])
+ // Resume keeps it too — the flag rides `extraArgs`, which every relaunch rebuilds from the row.
+ expect(buildEngineCommandArgv('opencode', { resumeSessionId: 'ses_1', extraArgs: namedAgentArgs('opencode', 'harness-compute') }))
+ .toEqual([engineBin('opencode'), '--session', 'ses_1', '--agent', 'harness-compute'])
+ })
+
+ it('refuses every other engine, naming it, rather than dropping the name', () => {
+ for (const engine of ENGINES) {
+ if (engine === 'opencode') continue
+ expect(supportsNamedAgent(engine)).toBe(false)
+ let refusal: unknown
+ try { namedAgentArgs(engine, 'harness-compute') } catch (error) { refusal = error }
+ expect(refusal).toBeInstanceOf(NamedAgentUnsupportedError)
+ expect((refusal as NamedAgentUnsupportedError).code).toBe('AGENT_UNSUPPORTED')
+ expect((refusal as NamedAgentUnsupportedError).message).toContain(engine)
+ }
+ })
+
+ it('has an entry (possibly null) for every known engine — no engine silently falls through', () => {
+ for (const engine of ENGINES) {
+ expect(Object.prototype.hasOwnProperty.call(NAMED_AGENT_ARGS, engine)).toBe(true)
+ }
+ expect(supportsNamedAgent('opencode')).toBe(true)
+ })
+
+ it('accepts an identifier and nothing that could be a path or prose', () => {
+ for (const ok of ['harness-compute', 'build', 'A_b-1', 'x'.repeat(64)]) expect(AGENT_NAME_RE.test(ok)).toBe(true)
+ for (const bad of ['', ' harness-compute', 'local model', '../etc', 'a/b', 'name.md', 'x'.repeat(65), 'nämn']) {
+ expect(AGENT_NAME_RE.test(bad)).toBe(false)
+ }
+ })
+})
+
const dirs: string[] = []
const originalProbePath = process.env.HARNESS_ENGINE_TEST_PATH
diff --git a/cli/src/lib/engineLaunch.ts b/cli/src/lib/engineLaunch.ts
index 28ae17906..dc5323eab 100644
--- a/cli/src/lib/engineLaunch.ts
+++ b/cli/src/lib/engineLaunch.ts
@@ -31,10 +31,131 @@ export const BYPASS_PERMISSION_FLAGS: Readonly<Record<AgentEngine, string[] | nu
copilot: null,
}
+/**
+ * How each engine takes a FIRST prompt on launch: the interactive session opens with that message
+ * already submitted, so the pane's first visible thing is the agent's answer rather than an empty
+ * input waiting for one. `null` = no documented mechanism; the caller refuses (`PROMPT_UNSUPPORTED`)
+ * rather than guess, the way `gridLaunch.ts` refuses an engine with no endpoint contract.
+ *
+ * An entry is the argv placed BEFORE the text: a flag (`['--prompt']`) or nothing at all for an
+ * engine that reads a bare positional. Each entry cites where it was read from.
+ */
+export const FIRST_PROMPT_ARGS: Readonly<Record<AgentEngine, readonly string[] | null>> = {
+ // `opencode --help`: `--prompt prompt to use`, a TUI flag — the interactive session starts with
+ // the message submitted. A flag rather than a positional because opencode's own positional is
+ // `[project]`, a directory: handed the text bare, it would try to open a folder by that name.
+ opencode: ['--prompt'],
+ // `claude --help`: `Usage: claude [options] [command] [prompt]`, "prompt: Your prompt".
+ claude: [],
+ // Per vendor CLI help: `codex [OPTIONS] [PROMPT]`, the optional positional the interactive TUI
+ // opens with. Not verified on a local install when this entry was written.
+ codex: [],
+ // No documented first-prompt argument for an interactive launch. Not guessed.
+ cursor: null,
+ pi: null,
+ hermes: null,
+ commandcode: null,
+ devin: null,
+ muse: null,
+ amp: null,
+ kilo: null,
+ grok: null,
+ agy: null,
+ copilot: null,
+}
+
+/** A first prompt is a message, not a document. Enforced at the wire (`agent_create`) before any pane
+ * exists, so an over-long one is refused rather than truncated into something the agent was not asked. */
+export const MAX_FIRST_PROMPT_CHARS = 2000
+
+/** The refusal for an engine with no entry in [FIRST_PROMPT_ARGS]. `code` is the wire error. */
+export class FirstPromptUnsupportedError extends Error {
+ readonly code = 'PROMPT_UNSUPPORTED' as const
+ constructor(readonly engine: AgentEngine) {
+ super(`${engine} has no documented way to start with a first prompt, so the agent was not created.`)
+ this.name = 'FirstPromptUnsupportedError'
+ }
+}
+
+export function supportsFirstPrompt(engine: AgentEngine): boolean {
+ return FIRST_PROMPT_ARGS[engine] !== null
+}
+
+/** The argv that hands `prompt` to `engine` as its first message. Throws [FirstPromptUnsupportedError]
+ * for an engine with no contract, so a caller cannot build an argv that silently drops the prompt. */
+export function firstPromptArgs(engine: AgentEngine, prompt: string): string[] {
+ const lead = FIRST_PROMPT_ARGS[engine]
+ if (lead === null) throw new FirstPromptUnsupportedError(engine)
+ return [...lead, prompt]
+}
+
+/**
+ * How each engine opens AS one of its named agents — its own name in the footer, its own system
+ * prompt — rather than as a general session. `null` = no documented mechanism; the caller refuses
+ * (`AGENT_UNSUPPORTED`) before a pane exists, the way [FIRST_PROMPT_ARGS] does for a prompt.
+ *
+ * An entry is the argv placed BEFORE the name. Unlike a first prompt, the agent IS part of the
+ * relaunch record (`RegisteredSession.agent`, carried by `launchOverrides.ts`): a pane opened as
+ * `harness-compute` comes back as `harness-compute`.
+ */
+export const NAMED_AGENT_ARGS: Readonly<Record<AgentEngine, readonly string[] | null>> = {
+ // `opencode --help`: `--agent agent to use`. The name is one of opencode's own agents
+ // (`~/.config/opencode/agents/<name>.md`, `mode: primary`).
+ opencode: ['--agent'],
+ // No documented "open as this named agent" argument for an interactive launch. Not guessed.
+ claude: null,
+ codex: null,
+ cursor: null,
+ pi: null,
+ hermes: null,
+ commandcode: null,
+ devin: null,
+ muse: null,
+ amp: null,
+ kilo: null,
+ grok: null,
+ agy: null,
+ copilot: null,
+}
+
+/** An agent name is an identifier the engine looks a file up by — never a path, never prose. */
+export const AGENT_NAME_RE = /^[A-Za-z0-9_-]{1,64}$/
+
+/** The refusal for an engine with no entry in [NAMED_AGENT_ARGS]. `code` is the wire error. */
+export class NamedAgentUnsupportedError extends Error {
+ readonly code = 'AGENT_UNSUPPORTED' as const
+ constructor(readonly engine: AgentEngine) {
+ super(`${engine} has no documented way to open as a named agent, so the agent was not created.`)
+ this.name = 'NamedAgentUnsupportedError'
+ }
+}
+
+export function supportsNamedAgent(engine: AgentEngine): boolean {
+ return NAMED_AGENT_ARGS[engine] !== null
+}
+
+/** The argv that opens `engine` as its named agent `agent`. Throws [NamedAgentUnsupportedError] for
+ * an engine with no contract, so a caller cannot build an argv that silently drops the name. */
+export function namedAgentArgs(engine: AgentEngine, agent: string): string[] {
+ const lead = NAMED_AGENT_ARGS[engine]
+ if (lead === null) throw new NamedAgentUnsupportedError(engine)
+ return [...lead, agent]
+}
+
export interface LaunchCommandOptions {
bypassPermission?: boolean
/** Resume this engine session id on launch, when a launch-resume flag is known for the engine. */
resumeSessionId?: string
+ /**
+ * The message the session opens with, already submitted — see [FIRST_PROMPT_ARGS]. Appended LAST,
+ * after every flag, because two of the three engines take it positionally and a positional is only
+ * unambiguous once the options are exhausted.
+ *
+ * A launch option and nothing more: it is never written to the registry row, so a relaunch (which
+ * resumes a session that already has its first turn) never repeats it. Never logged either — it is
+ * what the user typed.
+ */
+ firstPrompt?: string
/**
* Extra argv the caller has already composed, appended last.
*
@@ -134,6 +255,7 @@ export function buildEngineCommandArgv(engine: AgentEngine, opts: LaunchCommandO
argv.push(...resumeFlag, opts.resumeSessionId)
}
if (opts.extraArgs?.length) argv.push(...opts.extraArgs)
+ if (opts.firstPrompt) argv.push(...firstPromptArgs(engine, opts.firstPrompt))
return argv
}
diff --git a/cli/src/lib/harnessComputeSkill.spec.ts b/cli/src/lib/harnessComputeSkill.spec.ts
new file mode 100644
index 000000000..5fe39c9fb
--- /dev/null
+++ b/cli/src/lib/harnessComputeSkill.spec.ts
@@ -0,0 +1,99 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from 'fs'
+import { join } from 'path'
+import { tmpdir } from 'os'
+
+/**
+ * `harness start` drops two files for opencode: the Harness Compute skill (frontmatter + the doc)
+ * and the `harness-compute` agent definition (the doc verbatim — its frontmatter is the agent's). Both
+ * land under XDG_CONFIG_HOME, both are idempotent, and neither may fail the start.
+ */
+describe('installOpencodeHarnessComputeSkill', () => {
+ let configHome = ''
+ const docs = join(__dirname, '..', '..', '..', 'docs', 'skills')
+
+ async function load() {
+ vi.resetModules()
+ process.env.XDG_CONFIG_HOME = configHome
+ delete process.env.OPENCODE_SKILL_DIR
+ delete process.env.OPENCODE_AGENT_DIR
+ return import('./harnessComputeSkill.js')
+ }
+
+ beforeEach(() => {
+ configHome = mkdtempSync(join(tmpdir(), 'adapter-opencode-skill-'))
+ vi.spyOn(console, 'log').mockImplementation(() => {})
+ vi.spyOn(console, 'error').mockImplementation(() => {})
+ })
+
+ afterEach(() => {
+ rmSync(configHome, { recursive: true, force: true })
+ delete process.env.XDG_CONFIG_HOME
+ vi.restoreAllMocks()
+ })
+
+ it('installs the skill with its frontmatter and the agent definition verbatim, under XDG_CONFIG_HOME', async () => {
+ const { installOpencodeHarnessComputeSkill } = await load()
+ installOpencodeHarnessComputeSkill()
+
+ const skill = readFileSync(join(configHome, 'opencode', 'skills', 'harness-compute', 'SKILL.md'), 'utf-8')
+ expect(skill.startsWith('---\nname: harness-compute\n')).toBe(true)
+ expect(skill).toContain(readFileSync(join(docs, 'harness-compute.md'), 'utf-8').trimEnd())
+
+ const agent = readFileSync(join(configHome, 'opencode', 'agents', 'harness-compute.md'), 'utf-8')
+ // Byte-for-byte: the source file carries the exact frontmatter opencode reads, nothing is added.
+ expect(agent).toBe(readFileSync(join(docs, 'harness-compute.agent.md'), 'utf-8'))
+ expect(agent.startsWith("---\nname: 'harness-compute'\n")).toBe(true)
+ expect(agent).toContain('mode: primary')
+ expect(agent).toContain('question: allow')
+ expect(console.error).not.toHaveBeenCalled()
+ })
+
+ it('is a no-op the second time: nothing rewritten, no temp file left behind', async () => {
+ const { installOpencodeHarnessComputeSkill } = await load()
+ installOpencodeHarnessComputeSkill()
+ const skillPath = join(configHome, 'opencode', 'skills', 'harness-compute', 'SKILL.md')
+ const agentPath = join(configHome, 'opencode', 'agents', 'harness-compute.md')
+ const before = [statSync(skillPath).mtimeMs, statSync(agentPath).mtimeMs]
+ vi.mocked(console.log).mockClear()
+
+ await new Promise((resolve) => setTimeout(resolve, 20))
+ installOpencodeHarnessComputeSkill()
+
+ expect([statSync(skillPath).mtimeMs, statSync(agentPath).mtimeMs]).toEqual(before)
+ expect(vi.mocked(console.log).mock.calls.map(([line]) => String(line))).toEqual([
+ '[hooks] Harness Compute opencode skill already installed',
+ '[hooks] harness-compute opencode agent already installed',
+ ])
+ expect(readdirSync(join(configHome, 'opencode', 'agents'))).toEqual(['harness-compute.md'])
+ expect(readdirSync(join(configHome, 'opencode', 'skills', 'harness-compute'))).toEqual(['SKILL.md'])
+ })
+
+ it('rewrites a file that drifted from the source', async () => {
+ const { installOpencodeHarnessComputeSkill } = await load()
+ installOpencodeHarnessComputeSkill()
+ const agentPath = join(configHome, 'opencode', 'agents', 'harness-compute.md')
+ writeFileSync(agentPath, '---\nname: harness-compute\n---\nedited by hand\n')
+
+ installOpencodeHarnessComputeSkill()
+
+ expect(readFileSync(agentPath, 'utf-8')).toBe(readFileSync(join(docs, 'harness-compute.agent.md'), 'utf-8'))
+ })
+
+ it('honours OPENCODE_AGENT_DIR and OPENCODE_SKILL_DIR over the XDG default', async () => {
+ vi.resetModules()
+ process.env.XDG_CONFIG_HOME = configHome
+ process.env.OPENCODE_SKILL_DIR = join(configHome, 'custom-skills')
+ process.env.OPENCODE_AGENT_DIR = join(configHome, 'custom-agents')
+ try {
+ const { installOpencodeHarnessComputeSkill } = await import('./harnessComputeSkill.js')
+ installOpencodeHarnessComputeSkill()
+ expect(existsSync(join(configHome, 'custom-skills', 'harness-compute', 'SKILL.md'))).toBe(true)
+ expect(existsSync(join(configHome, 'custom-agents', 'harness-compute.md'))).toBe(true)
+ expect(existsSync(join(configHome, 'opencode'))).toBe(false)
+ } finally {
+ delete process.env.OPENCODE_SKILL_DIR
+ delete process.env.OPENCODE_AGENT_DIR
+ }
+ })
+})
diff --git a/cli/src/lib/harnessComputeSkill.ts b/cli/src/lib/harnessComputeSkill.ts
index 29ea75850..98f20af63 100644
--- a/cli/src/lib/harnessComputeSkill.ts
+++ b/cli/src/lib/harnessComputeSkill.ts
@@ -5,8 +5,15 @@
* ever being told what the underlying CLI it shells out to is called.
*
* The skill's own prose is not duplicated here: it lives in `docs/skills/harness-compute.md`,
- * one file for every agent — it tells the agent to add a custom provider to itself, which every
- * coding agent knows how to do, rather than carrying a page per agent's config format. This just adds the frontmatter opencode's skill loader requires.
+ * one file for every agent — it starts the model and then points the user at the app's model
+ * picker, which is what actually switches an agent (agent_retarget); the skill never touches an
+ * agent's own config. This just adds the frontmatter opencode's skill loader requires.
+ *
+ * Beside the skill goes the `harness-compute` AGENT definition (`docs/skills/harness-compute.agent.md` →
+ * ~/.config/opencode/agents/harness-compute.md): the thing `opencode --agent harness-compute` opens a pane
+ * AS, whose whole job is to load that skill and follow it. The source file already carries the exact
+ * frontmatter opencode reads (`name`, `mode: primary`, `permission: question: allow`), so it is
+ * installed verbatim.
*/
import { readFileSync, writeFileSync, mkdirSync, existsSync, renameSync } from 'fs'
import { join, dirname } from 'path'
@@ -28,10 +35,11 @@ function skillSourcePath(name: string): string {
}
const SKILL_PATH = join(env.OPENCODE_SKILL_DIR, 'harness-compute', 'SKILL.md')
+const AGENT_PATH = join(env.OPENCODE_AGENT_DIR, 'harness-compute.md')
const FRONTMATTER = `---
name: harness-compute
-description: Run AI models on the user's own machines under their Harness account and chat with them from this agent. Use when the user asks to start or serve a local model, run a model on this machine, add a custom provider for those models, or check what their machines are currently serving.
+description: Run AI models on the user's own machines under their Harness account, so any agent can switch to them from its model picker. Use when the user asks to start or serve a local model, run a model on this machine, stop one, or check what their machines are currently serving.
license: MIT
compatibility: opencode
metadata:
@@ -40,32 +48,48 @@ metadata:
`
-/** Idempotently drop the assembled Harness Compute skill into ~/.config/opencode/skills/. */
-export function installOpencodeHarnessComputeSkill(): void {
- let core: string
- try {
- core = readFileSync(skillSourcePath('harness-compute.md'), 'utf-8')
- } catch (err) {
- // Best-effort, same posture as every other engine install in hooks.ts: a missing or unreadable
- // source must never fail `harness start`, only skip this one skill.
- console.error('[hooks] failed to read Harness Compute skill sources:', err)
- return
- }
- const source = FRONTMATTER + core.trimEnd() + '\n'
+/**
+ * Write `source` to `target` unless it is already there byte-for-byte. Atomic (temp + rename), so a
+ * session that reads the file mid-install sees the old one or the new one, never half of either.
+ * Best-effort: a failure is logged and skipped, never thrown — nothing here may fail `harness start`.
+ */
+function installFile(label: string, target: string, source: string): void {
try {
- if (existsSync(SKILL_PATH) && readFileSync(SKILL_PATH, 'utf-8') === source) {
- console.log('[hooks] Harness Compute opencode skill already installed')
+ if (existsSync(target) && readFileSync(target, 'utf-8') === source) {
+ console.log(`[hooks] ${label} already installed`)
return
}
} catch { /* unreadable — rewrite it */ }
try {
- mkdirSync(dirname(SKILL_PATH), { recursive: true })
- const tmp = `${SKILL_PATH}.${process.pid}.tmp`
+ mkdirSync(dirname(target), { recursive: true })
+ const tmp = `${target}.${process.pid}.tmp`
writeFileSync(tmp, source)
- renameSync(tmp, SKILL_PATH)
- console.log(`[hooks] installed Harness Compute opencode skill → ${SKILL_PATH}`)
+ renameSync(tmp, target)
+ console.log(`[hooks] installed ${label} → ${target}`)
console.log('[hooks] (a NEW opencode session picks this up automatically)')
} catch (err) {
- console.error('[hooks] failed to write Harness Compute opencode skill:', err)
+ console.error(`[hooks] failed to write ${label}:`, err)
}
}
+
+/** The doc at `name` under docs/skills/, or null (logged) when it cannot be read. */
+function readSkillSource(label: string, name: string): string | null {
+ try {
+ return readFileSync(skillSourcePath(name), 'utf-8')
+ } catch (err) {
+ // Best-effort, same posture as every other engine install in hooks.ts: a missing or unreadable
+ // source must never fail `harness start`, only skip this one file.
+ console.error(`[hooks] failed to read ${label} sources:`, err)
+ return null
+ }
+}
+
+/** Idempotently drop the assembled Harness Compute skill into ~/.config/opencode/skills/, and the
+ * `harness-compute` agent that follows it into ~/.config/opencode/agents/. */
+export function installOpencodeHarnessComputeSkill(): void {
+ const core = readSkillSource('Harness Compute skill', 'harness-compute.md')
+ if (core !== null) installFile('Harness Compute opencode skill', SKILL_PATH, FRONTMATTER + core.trimEnd() + '\n')
+ // Verbatim: the source file IS the agent definition, frontmatter included.
+ const agent = readSkillSource('harness-compute agent', 'harness-compute.agent.md')
+ if (agent !== null) installFile('harness-compute opencode agent', AGENT_PATH, agent)
+}
diff --git a/cli/src/lib/launchOverrides.spec.ts b/cli/src/lib/launchOverrides.spec.ts
index 7327c24fd..70ef1e894 100644
--- a/cli/src/lib/launchOverrides.spec.ts
+++ b/cli/src/lib/launchOverrides.spec.ts
@@ -118,6 +118,25 @@ 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: [] } })
+ 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')
+ expect(grid.ok).toBe(true)
+ if (!grid.ok) return
+ expect(grid.overrides.extraArgs.slice(-2)).toEqual(['--agent', 'harness-compute'])
+ expect(grid.overrides.gridLaunchRecord).toBeDefined()
+ })
+
+ it('adds nothing for a general session, or for an engine with no contract on a hand-edited row', async () => {
+ expect(await buildLaunchOverrides(deps().d, 'opencode', { agent: null }, 'a')).toMatchObject({ ok: true, overrides: { extraArgs: [] } })
+ expect(await buildLaunchOverrides(deps().d, 'claude', { agent: 'harness-compute' }, 'a')).toMatchObject({ ok: true, overrides: { extraArgs: [] } })
+ })
+})
+
describe('buildLaunchOverrides — what the app is told about web search', () => {
const WITH_MCP: GridLaunchOverride = { ...GRID, mcpUrl: 'https://api-grid.example/v1/grid/web-mcp/' }
diff --git a/cli/src/lib/launchOverrides.ts b/cli/src/lib/launchOverrides.ts
index 5cd4ba9b9..aa1a3a4de 100644
--- a/cli/src/lib/launchOverrides.ts
+++ b/cli/src/lib/launchOverrides.ts
@@ -15,6 +15,7 @@
import { join } from 'node:path'
import type { AgentEngine } from '../engines/types.js'
import { subscriptionModelLaunch } from './subscriptionModel.js'
+import { namedAgentArgs, supportsNamedAgent } from './engineLaunch.js'
import {
buildGridEngineLaunch,
gridConflictingEnvToClear,
@@ -78,6 +79,12 @@ export interface LaunchSource {
dsh?: string | null
/** The workspace, for the DSH's `${workspace}` — the registry row's `cwd`. */
cwd?: string | null
+ /**
+ * The engine's named agent this pane was opened as (`agent_create`'s `agent`, opencode
+ * `--agent <name>`). Part of every relaunch, unlike a first prompt: a pane opened as `harness-compute`
+ * comes back as `harness-compute`, not as a general session with that agent's history.
+ */
+ agent?: string | null
}
/** Fresh each time: callers hand `env` to tmux and may extend it, and a shared object would carry
@@ -125,19 +132,28 @@ export async function buildLaunchOverrides(
configKey: string,
): Promise<LaunchOverridesResult> {
const base = await buildBaseLaunchOverrides(deps, engine, source, configKey)
- if (!base.ok || !source.dsh || !source.cwd) return base
- const dsh = deps.dshLaunch?.(source.dsh, source.cwd) ?? null
- if (!dsh) return base
- // 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.
- return {
- ok: true,
- overrides: {
- env: { ...base.overrides.env, ...dsh.env },
- extraArgs: [...base.overrides.extraArgs, ...dsh.args],
- clearEnv: base.overrides.clearEnv,
- },
+ if (!base.ok) return base
+ let overrides = base.overrides
+ if (source.dsh && source.cwd) {
+ const dsh = deps.dshLaunch?.(source.dsh, source.cwd) ?? null
+ // 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],
+ }
+ }
+ }
+ // The named agent rides every relaunch, in the same argv slot `agent_create` put it in. Only an
+ // engine with a contract could have had it recorded (create refuses the rest, AGENT_UNSUPPORTED),
+ // so the guard is for a row edited by hand — it relaunches as a general session rather than
+ // handing the engine a flag it does not know.
+ if (source.agent && supportsNamedAgent(engine)) {
+ overrides = { ...overrides, extraArgs: [...overrides.extraArgs, ...namedAgentArgs(engine, source.agent)] }
}
+ return { ok: true, overrides }
}
async function buildBaseLaunchOverrides(
diff --git a/cli/src/lib/registry.spec.ts b/cli/src/lib/registry.spec.ts
index 5dc6c7419..7c4c5badb 100644
--- a/cli/src/lib/registry.spec.ts
+++ b/cli/src/lib/registry.spec.ts
@@ -1045,6 +1045,43 @@ describe('agent identity: the process owns the agent, the session is bound to it
expect(reloaded.displayName(fourth)).toBe('agent-11')
})
+ it('opens a pane under the name its creator asked for, keeps it through binding and reload, and does not spend a number on it', async () => {
+ const { registry } = await loadRegistryModule()
+ registry.load()
+ const named = registry.openPendingAgent({ engine: 'opencode', runtimes: [{ backend: 'tmux', paneId: '%7' }], cwd: '/tmp/demo', defaultName: ' Local model ' })!
+ expect(named.defaultName).toBe('Local model')
+ expect(registry.displayName(named)).toBe('Local model')
+ // The engine reporting a session title does not retitle a pane that was named at creation.
+ const bound = registry.register({ engine: 'opencode', sessionId: 'session-named', tmuxPane: '%7', title: 'OC | Greeting' })!.entry
+ expect(registry.displayName(bound)).toBe('Local model')
+ // Blank means "number it", the same as absent — and the named agent took no number.
+ const numbered = registry.openPendingAgent({ engine: 'opencode', runtimes: [{ backend: 'tmux', paneId: '%8' }], cwd: '/tmp/demo', defaultName: ' ' })!
+ expect(registry.displayName(numbered)).toBe('agent-1')
+ const { registry: reloaded } = await loadRegistryModule()
+ reloaded.load()
+ expect(reloaded.displayName(reloaded.byAgent(named.agentId)!)).toBe('Local model')
+ expect(reloaded.displayName(reloaded.byAgent(numbered.agentId)!)).toBe('agent-1')
+ })
+
+ it('keeps the named agent a pane was opened as through binding and reload, and drops one that is not an identifier', async () => {
+ const { registry } = await loadRegistryModule()
+ registry.load()
+ const named = registry.openPendingAgent({ engine: 'opencode', runtimes: [{ backend: 'tmux', paneId: '%7' }], cwd: '/tmp/demo', agent: 'harness-compute', defaultName: 'Local model' })!
+ expect(named.agent).toBe('harness-compute')
+ // A hook-triggered bind carries it forward, like `dsh` and `codexHome`.
+ const bound = registry.register({ engine: 'opencode', sessionId: 'session-agent', tmuxPane: '%7', title: 'OC | Greeting' })!.entry
+ expect(bound.agent).toBe('harness-compute')
+ // Absent is a general session; a shape the engine could not look a file up by is not kept.
+ const plain = registry.openPendingAgent({ engine: 'opencode', runtimes: [{ backend: 'tmux', paneId: '%8' }], cwd: '/tmp/demo' })!
+ expect(plain.agent).toBeNull()
+ const odd = registry.openPendingAgent({ engine: 'opencode', runtimes: [{ backend: 'tmux', paneId: '%9' }], cwd: '/tmp/demo', agent: '../etc' })!
+ expect(odd.agent).toBeNull()
+ const { registry: reloaded } = await loadRegistryModule()
+ reloaded.load()
+ expect(reloaded.byAgent(named.agentId)!.agent).toBe('harness-compute')
+ expect(reloaded.byAgent(plain.agentId)!.agent).toBeNull()
+ })
+
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 9090fe25c..ea1232106 100644
--- a/cli/src/lib/registry.ts
+++ b/cli/src/lib/registry.ts
@@ -14,6 +14,7 @@
*/
import { DSH_ID_RE } from '../dsh/manifest.js'
+import { AGENT_NAME_RE } from './engineLaunch.js'
import {
closeSync,
constants,
@@ -145,6 +146,13 @@ export interface RegisteredSession {
* again after a restart) is still labelled. Fill-only, like `codexHome`. See `src/dsh/`.
*/
dsh?: 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
+ * relaunch (`launchOverrides.ts`), so a pane opened as `harness-compute` comes back as `harness-compute`.
+ * Like `codexHome`, never re-derived from the live process.
+ */
+ agent?: string | null
/**
* Whether the engine was launched with its permission prompts bypassed (`--dangerously-skip-permissions`
* and friends, `BYPASS_PERMISSION_FLAGS`). Recorded at launch because it is otherwise only readable
@@ -156,7 +164,8 @@ export interface RegisteredSession {
launcherId?: string
transcriptPath: string | null
projectDir: string
- /** Stable default for agents created by Harness; discovered agents keep their existing names. */
+ /** Stable default for agents created by Harness — the next `agent-N`, or the name the creator asked
+ * for (`agent_create`'s `name`). Discovered agents keep their existing names. */
defaultName?: string
cwd: string | null
/** Authoritative backend-neutral terminal placements for this one process-owned agent. */
@@ -214,11 +223,32 @@ const PANE_RE = /^%\d+$/
const GROK_SESSION_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
const AGENT_ENGINES: ReadonlySet<string> = new Set(ENGINES)
+/**
+ * A persisted `defaultName`, or undefined for anything that is not one.
+ *
+ * Used to be `agent-N` only. A creator can now name the agent (`agent_create`'s `name`), and a row
+ * validated against the numbered shape alone dropped that name on the next load — the pane came
+ * back titled `agent-3` after a daemon restart. Trimmed and bounded, so a row cannot carry a name
+ * the header would draw as nothing, or one long enough to be a document.
+ */
+const MAX_DEFAULT_NAME_CHARS = 200
+function normalizedDefaultName(value: unknown): string | undefined {
+ if (typeof value !== 'string') return undefined
+ const name = value.trim()
+ return name && name.length <= MAX_DEFAULT_NAME_CHARS ? name : undefined
+}
+
/** A persisted DSH id, or null for anything that is not one (older rows have no field at all). */
function normalizedDshId(value: unknown): string | null {
return typeof value === 'string' && DSH_ID_RE.test(value) ? value : null
}
+/** A persisted named agent, or null for anything that is not one — the same shape `agent_create`
+ * accepts, so a hand-edited row cannot put a path or prose into the relaunch argv. */
+function normalizedAgentName(value: unknown): string | null {
+ return typeof value === 'string' && AGENT_NAME_RE.test(value) ? value : null
+}
+
function normalizedAgentEngine(value: unknown): AgentEngine {
return typeof value === 'string' && AGENT_ENGINES.has(value)
? value as AgentEngine
@@ -404,8 +434,8 @@ function strictPersistedRow(value: unknown): RegisteredSession | null {
engine: row.engine as AgentEngine,
transcriptPath: typeof row.transcriptPath === 'string' ? row.transcriptPath : null,
projectDir: row.projectDir,
- defaultName: typeof row.defaultName === 'string' && /^agent-[1-9]\d*$/.test(row.defaultName)
- ? row.defaultName : undefined,
+ defaultName: normalizedDefaultName(row.defaultName),
+ agent: normalizedAgentName((row as { agent?: unknown }).agent),
cwd: typeof row.cwd === 'string' ? row.cwd : null,
runtimes,
primaryRuntimeKey: normalizedPrimary,
@@ -784,6 +814,7 @@ class Registry {
grid: normalizedGridAssignment(raw.grid),
codexHome: typeof rawCodexHome === 'string' && rawCodexHome ? rawCodexHome : null,
dsh: normalizedDshId((raw as { dsh?: unknown }).dsh),
+ agent: normalizedAgentName((raw as { agent?: unknown }).agent),
...(rawGridLaunch !== undefined ? { gridLaunch: rawGridLaunch } : {}),
...(rawGridLaunch ? { gridWebSearch: normalizedGridWebSearch(raw?.gridWebSearch) } : {}),
// ⚠️ Rehydrated EXPLICITLY, like every field above it. A row is rebuilt from this list on
@@ -795,8 +826,7 @@ class Registry {
: {}),
...(raw.bypassPermission === true ? { bypassPermission: true } : {}),
transcriptPath,
- defaultName: typeof raw.defaultName === 'string' && /^agent-[1-9]\d*$/.test(raw.defaultName)
- ? raw.defaultName : undefined,
+ defaultName: normalizedDefaultName(raw.defaultName),
title: titleDisplayName(typeof raw.title === 'string' ? raw.title : null),
sessionId: bound ? rawSessionId : '',
projectDir: !repairedCodexTranscript && typeof raw.projectDir === 'string' && raw.projectDir
@@ -983,6 +1013,9 @@ class Registry {
gridWebSearch: null,
codexHome: input.codexHome ?? null,
dsh: input.dsh ?? null,
+ // A discovered pane's named agent is only visible in its argv; nothing here reads it, so the
+ // row cannot relaunch it as one. Fill-only, like `dsh`.
+ agent: null,
transcriptPath: null,
projectDir: basename(input.cwd ?? '') || agentId,
cwd: input.cwd ?? null,
@@ -1016,7 +1049,11 @@ class Registry {
gridLaunchRecord?: GridLaunchRecord | null
codexHome?: string | null
dsh?: string | null
+ /** The engine's named agent the pane was opened as (`agent_create`'s `agent`), validated upstream. */
+ agent?: string | null
bypassPermission?: boolean
+ /** The name the creator asked for, instead of the next `agent-N`. Blank means "number it". */
+ defaultName?: string | null
}): RegisteredSession | null {
if (this.writeBlocked) return null
const runtimes = normalizedRuntimes(input.runtimes)
@@ -1028,7 +1065,7 @@ class Registry {
schemaVersion: 2,
active: true,
launch: { state: 'starting' },
- defaultName: this.nextAgentName(),
+ defaultName: normalizedDefaultName(input.defaultName) ?? this.nextAgentName(),
agentId,
sessionId: '',
boundAt: null,
@@ -1039,6 +1076,7 @@ class Registry {
gridWebSearch: input.gridLaunchRecord?.webSearch ?? null,
codexHome: input.codexHome ?? null,
dsh: input.dsh ?? null,
+ agent: normalizedAgentName(input.agent),
...(input.bypassPermission ? { bypassPermission: true } : {}),
transcriptPath: null,
projectDir: basename(input.cwd ?? '') || agentId,
@@ -1225,6 +1263,7 @@ class Registry {
// forward or the very first SessionStart hook would silently wipe the agent's chosen profile.
codexHome: existing?.codexHome ?? null,
dsh: existing?.dsh ?? null,
+ agent: existing?.agent ?? null,
...(existing?.bypassPermission ? { bypassPermission: true } : {}),
processIdentity: validProcessIdentity(input.processIdentity) ? input.processIdentity : existing?.processIdentity ?? null,
registeredAt: existing?.registeredAt ?? now,
diff --git a/cli/src/lib/runtimeProfileController.spec.ts b/cli/src/lib/runtimeProfileController.spec.ts
index f75090d46..26ce80e47 100644
--- a/cli/src/lib/runtimeProfileController.spec.ts
+++ b/cli/src/lib/runtimeProfileController.spec.ts
@@ -340,152 +340,6 @@ describe('runtime pane parsing', () => {
})
describe('RuntimeProfileController', () => {
- it('selects a grid model through OpenCode\'s own picker, which a resumed pane needs', async () => {
- // OpenCode's TUI honours `-m` only when it STARTS a session; resuming one restores the model
- // stored on that session and drops the flag. Measured on 1.18.31 outside the harness:
- // opencode -m <grid>/Qwen3.6-35B-A3B → Build · Qwen3.6-35B-A3B <grid>
- // opencode --session <id> -m <grid>/Qwen3.6-35B-A3B → Build · Big Pickle OpenCode Zen
- // So a retarget landed the right provider, key and argv and the engine answered on the OLD
- // model. The grid's models are in that pane's picker — the provider block is in the config the
- // respawn points OPENCODE_CONFIG at — so the picker is what makes the move real.
- const value = session('opencode')
- const footer = (model: string) => ` ┃ Build · ${model}\n`
- let model = 'Big Pickle OpenCode Zen'
- let picker = ''
- let filter = ''
- const controller = new RuntimeProfileController({
- manager: new RuntimeProfileManager(),
- getSession: () => value,
- validateRuntime: async () => true,
- capture: async () => footer(model) + picker,
- sendText: async (_pane, command) => {
- // The picker lists BOTH the subscription model and the grid one, as the live pane does.
- if (command === '/models') {
- picker = [
- 'Select model esc',
- '● Big Pickle OpenCode Zen Free',
- `Qwen3.6-35B-A3B ${'minhduccm90-cecb9724'}`,
- 'Connect provider ctrl+a Favorite ctrl+f',
- ].join('\n')
- }
- return true
- },
- sendLiteral: async (_pane, text) => {
- filter = text
- // Typing narrows it to the one row, which is the only state this drive ever acts on.
- picker = [
- 'Select model esc',
- text,
- `Qwen3.6-35B-A3B ${'minhduccm90-cecb9724'}`,
- 'Connect provider ctrl+a Favorite ctrl+f',
- ].join('\n')
- return true
- },
- sendKey: async (_pane, key) => {
- if (key === 'Enter') { model = 'Qwen3.6-35B-A3B minhduccm90-cecb9724'; picker = '' }
- return true
- },
- acquireInput: () => () => {},
- })
-
- await expect(controller.selectOpencodeModel(value, 'minhduccm90-cecb9724/Qwen3.6-35B-A3B'))
- .resolves.toBeUndefined()
- // The filter is built from the model's last segment plus the provider, the same rule the
- // subscription drive uses — a second rule here would drift from the one the picker was measured
- // against.
- expect(filter).toBe('qwen3.6 35b a3b minhduccm90 cecb9724')
- expect(model).toBe('Qwen3.6-35B-A3B minhduccm90-cecb9724')
- })
-
- it('falls back to the model-only filter when a row carries no provider', async () => {
- // Measured on a live picker with ONE provider connected: the row is bare (`Big Pickle · Free`),
- // the provider name is only the heading above it, and `big pickle opencode` matches NOTHING while
- // `big pickle` returns the row. This is the way HOME from a grid — the subscription model named
- // here — and it refused with MODEL_UNAVAILABLE until the filter dropped its provider half.
- const value = session('opencode')
- let pane = ' ┃ Build · Qwen3.6-35B-A3B minhduccm90-cecb9724\n'
- const filters: string[] = []
- let chosen: string | null = null
- const rowsFor = (filter: string) => (
- // OpenCode's own matcher: the provider is not in the row, so a filter naming it finds nothing.
- 'bigpickle'.startsWith(filter.replace(/[^a-z0-9]/g, '')) || filter.replace(/[^a-z0-9]/g, '') === 'bigpickle'
- ? ['● Big Pickle Free']
- : []
- )
- const controller = new RuntimeProfileController({
- manager: new RuntimeProfileManager(),
- getSession: () => value,
- validateRuntime: async () => true,
- capture: async () => pane,
- sendText: async () => {
- pane += '\nSelect model esc\nConnect provider ctrl+a'
- return true
- },
- sendLiteral: async (_pane, text) => {
- filters.push(text)
- pane = pane.slice(0, pane.lastIndexOf('Select model'))
- + ['Select model esc', text, ...rowsFor(text), 'Connect provider ctrl+a'].join('\n')
- return true
- },
- sendKey: async (_pane, key) => {
- if (key !== 'Enter') return true
- chosen = 'opencode/big-pickle'
- // Selecting repaints the footer, which is what the drive confirms from.
- pane = ' ┃ Build · Big Pickle OpenCode Zen\n'
- return true
- },
- acquireInput: () => () => {},
- })
-
- await controller.selectOpencodeModel(value, 'opencode/big-pickle')
- // The qualified filter is tried FIRST — dropping it would lose the only thing that tells two
- // same-named models apart when the provider IS rendered.
- expect(filters).toEqual(['big pickle opencode', 'big pickle'])
- expect(chosen).toBe('opencode/big-pickle')
- }, 15_000)
-
- it('refuses when OpenCode\'s picker never offers the grid model', async () => {
- // The confirmation is read from the FOOTER, not from the manager's observed profile: that
- // resolves what it sees against `opencode models`, which cannot list a provider written for one
- // agent — so it would answer null for a switch that had actually worked.
- const value = session('opencode')
- // Scrollback ACCUMULATES, the way a real capture does: a closed picker stays on screen above, which
- // is why the drive counts openings rather than asking whether one is open.
- let pane = ' ┃ Build · Big Pickle OpenCode Zen\n'
- let opens = 0
- const picker = (filter: string) => [
- 'Select model esc',
- filter,
- '● Big Pickle OpenCode Zen Free',
- 'Connect provider ctrl+a Favorite ctrl+f',
- ].join('\n')
- const controller = new RuntimeProfileController({
- manager: new RuntimeProfileManager(),
- getSession: () => value,
- validateRuntime: async () => true,
- capture: async () => pane,
- sendText: async () => {
- // The picker opens, and the grid's provider is not in it — the config the respawn points at
- // did not take, or the provider names no models.
- opens += 1
- pane += '\n' + picker('')
- return true
- },
- sendLiteral: async (_pane, text) => {
- pane = pane.slice(0, pane.lastIndexOf('Select model')) + picker(text)
- return true
- },
- sendKey: async () => true,
- acquireInput: () => () => {},
- })
-
- await expect(controller.selectOpencodeModel(value, 'minhduccm90-cecb9724/Qwen3.6-35B-A3B'))
- .rejects.toMatchObject({ code: 'MODEL_UNAVAILABLE' })
- // Both filters were tried — the provider-qualified one and the model-only fallback — before it gave
- // up, and neither pressed Enter on a row that was not the target.
- expect(opens).toBe(2)
- })
-
it('sets Claude model and effort only after transcript confirmations', async () => {
const value = session('claude')
const manager = new RuntimeProfileManager()
diff --git a/cli/src/lib/runtimeProfileController.ts b/cli/src/lib/runtimeProfileController.ts
index 6e17d9e56..ecffaf83a 100644
--- a/cli/src/lib/runtimeProfileController.ts
+++ b/cli/src/lib/runtimeProfileController.ts
@@ -5,10 +5,8 @@ import { parseHermesPickerPage } from '../engines/hermes/runtimeProfile.js'
import { parsePiFooterProfile, parsePiThinkingSelection, piThinkingSteps } from '../engines/pi/runtimeProfile.js'
import {
countOpencodePickers,
- opencodeModelTarget,
opencodeRowMatches,
opencodeRowNamesModel,
- parseOpencodeFooter,
parseOpencodePickerRows,
type OpencodeModelTarget,
type OpencodePickerRow,
@@ -29,17 +27,6 @@ const PICKER_STEP_MS = 2_000
const PI_LADDER_MAX_STEPS = 14
/** Hermes' longest picker page is a provider's model list; twice its size still terminates. */
const HERMES_PAGE_MAX_STEPS = 60
-/**
- * How long a freshly respawned OpenCode TUI gets to draw its composer before the model is selected.
- * Generous next to the picker steps because this one spans a process start, not a keystroke.
- */
-const OPENCODE_BOOT_MS = 20_000
-
-/** Compare model names the way OpenCode's own picker matcher does — punctuation and case are noise. */
-function squashModel(value: string): string {
- return value.replace(/[^a-z0-9]+/gi, '').toLowerCase()
-}
-
/** "Anthropic (13 models)" names provider key `anthropic`; "GitHub Copilot (17 models)" names `copilot`. */
function hermesProviderMatches(row: string, provider: string): boolean {
const name = row.replace(/\s*\([^)]*\)\s*$/, '').trim().toLowerCase()
@@ -918,55 +905,6 @@ export class RuntimeProfileController {
* same model name) the switch is refused rather than guessed — picking the wrong model silently is worse
* than not switching, and blind arrow-driving is what sank the Command Code attempt.
*/
- /**
- * Put a RESUMED OpenCode pane on an exact `provider/model`, through OpenCode's own picker.
- *
- * ## Why a pane that was just launched with `-m` needs this at all
- *
- * OpenCode's TUI honours `-m` only when it STARTS a session. Resuming one (`--session <id>`, which
- * is how a retarget keeps the conversation) restores the model stored on that session and the flag
- * is dropped. Measured on 1.18.31, outside the harness, against the same config file this daemon
- * writes:
- *
- * opencode -m <grid>/Qwen3.6-35B-A3B → `Build · Qwen3.6-35B-A3B <grid>` ✅
- * opencode --session <id> -m <grid>/Qwen3.6-35B-A3B → `Build · Big Pickle OpenCode Zen` ❌
- * opencode run --session <id> -m <model> → honoured ✅ (a different command)
- *
- * A top-level `"model"` in the config file loses to the stored model the same way. So the move
- * landed — right provider, right key, right argv — and the engine answered on the OLD model, which
- * is the failure this whole module exists to prevent: it looks like it worked, and it bills the
- * wrong account.
- *
- * The grid's models ARE in that pane's picker, because the provider block naming them is in the
- * config the respawn points `OPENCODE_CONFIG` at. So the same `/models` drive [setOpencode] uses
- * for a subscription model selects a grid one, and this is that drive with the catalogue check
- * removed — the catalogue is `opencode models`, which cannot know about a provider written for one
- * agent.
- *
- * ⚠️ The caller must ALREADY hold this pane's input. This types into the pane and does not take the
- * lock itself, because the only caller is mid-retarget and is holding it for the respawn.
- */
- async selectOpencodeModel(session: RegisteredSession, id: string): Promise<void> {
- const entry = opencodeModelTarget(id)
- if (!entry) throw new RuntimeProfileControlError('MODEL_UNAVAILABLE')
- // A pane that has just been respawned is still drawing. Typing `/models` into a TUI that has not
- // put its composer up yet loses the keystrokes — or worse, lands them somewhere else — so wait
- // for the footer, which is the first thing that proves the composer is live.
- if (!await this.waitPane(session.agentId, (v) => parseOpencodeFooter(stripAnsi(v)) !== null, OPENCODE_BOOT_MS)) {
- throw new RuntimeProfileControlError('CONFIRM_TIMEOUT')
- }
- await this.driveOpencodePicker(session, entry)
- // Confirmed from the footer rather than from the manager's observed profile: the manager resolves
- // what it sees against `opencode models`, and a grid model is not in it — so its answer would be
- // null here for a switch that actually worked.
- const leaf = entry.model.slice(entry.model.lastIndexOf('/') + 1)
- const landed = await this.waitPane(session.agentId, (v) => {
- const footer = parseOpencodeFooter(stripAnsi(v))
- return !!footer && squashModel(footer.target).startsWith(squashModel(leaf))
- }, COMMAND_CONFIRM_MS)
- if (!landed) throw new RuntimeProfileControlError('CONFIRM_TIMEOUT')
- }
-
private async setOpencode(session: RegisteredSession, target: RuntimeProfile): Promise<void> {
const entry = (await this.deps.manager.opencodeCatalog()).find((item) => item.id === target.model)
if (!entry) throw new RuntimeProfileControlError('MODEL_UNAVAILABLE')
@@ -977,7 +915,7 @@ export class RuntimeProfileController {
}
/**
- * `/models`, filter, act only once exactly one row is left. Shared by both OpenCode callers.
+ * `/models`, filter, act only once exactly one row is left.
*
* Two attempts, because one filter does not fit both renders. With several providers connected a
* row carries its provider (`Big Pickle OpenCode Zen`) and the provider-qualified filter is what
diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dart
index dd4d9b321..13841e4f2 100644
--- a/desktop/lib/screens/swarm_screen.dart
+++ b/desktop/lib/screens/swarm_screen.dart
@@ -609,6 +609,11 @@ class _SwarmScreenState extends State<SwarmScreen> {
await _addAgent();
case 'newAgent':
unawaited(_newAgent(swarmId: app.activeSwarmId));
+ case 'runLocalModel':
+ // The native Models menu's one command. Wrapped like Link Machine…
+ // because the notifier may open its dialog here, and the pane it then
+ // creates takes focus the same way a New Agent does.
+ await _dialog(() => app.runLocalModel(context));
case 'splitRight':
unawaited(_splitAgent(PaneResizeAxis.x));
case 'splitDown':
diff --git a/desktop/lib/settings/config_store.dart b/desktop/lib/settings/config_store.dart
index 722b7f680..a60d83c5c 100644
--- a/desktop/lib/settings/config_store.dart
+++ b/desktop/lib/settings/config_store.dart
@@ -9,6 +9,11 @@ class ConfigStore {
static const _environmentKey = 'app_autonomous_environment';
static const _skippedDesktopUpdateVersionKey =
'skipped_desktop_update_version';
+ // "Don't show this again" on the Run a local model dialog. Here rather than
+ // beside the pane layout because it is a choice about the PERSON, not about
+ // a machine or a tab: somebody who has watched the explanation once does not
+ // need it again for their second computer either.
+ static const _runLocalModelSkipDialogKey = 'runLocalModel.skipDialog';
// No longer read or written: live pre-flight runs on every launch. Kept only
// so Reset can clean state written by older desktop builds.
static const _legacyEnvironmentSetupVersionKey = 'environment_setup_version';
@@ -24,22 +29,39 @@ class ConfigStore {
String? _cachedBaseUrl;
String? _cachedEnvironment;
String? _cachedSkippedDesktopUpdateVersion;
+ bool _cachedRunLocalModelSkipDialog = false;
String? get skippedDesktopUpdateVersion => _cachedSkippedDesktopUpdateVersion;
+ /// Whether the Run a local model dialog has been waved off for good. False
+ /// until [load] or [saveRunLocalModelSkipDialog] says otherwise, so a store
+ /// that was never read still shows the explanation — the safe direction.
+ bool get runLocalModelSkipDialog => _cachedRunLocalModelSkipDialog;
+
Future<AppConfig> load() async {
// Keep the tiny startup path sequential and predictable.
final baseUrl = await _storage.read(_baseUrlKey);
final environment = await _storage.read(_environmentKey);
final skippedUpdate = await _storage.read(_skippedDesktopUpdateVersionKey);
+ final skipRunLocalModel = await _storage.read(_runLocalModelSkipDialogKey);
_cachedBaseUrl = baseUrl ?? defaultBaseUrl;
_cachedEnvironment = environment == 'stag' ? 'stag' : 'prod';
_cachedSkippedDesktopUpdateVersion = skippedUpdate?.trim().isEmpty ?? true
? null
: skippedUpdate!.trim();
+ _cachedRunLocalModelSkipDialog = skipRunLocalModel == 'true';
return config;
}
+ Future<void> saveRunLocalModelSkipDialog(bool value) async {
+ _cachedRunLocalModelSkipDialog = value;
+ if (value) {
+ await _storage.write(_runLocalModelSkipDialogKey, 'true');
+ } else {
+ await _storage.delete(_runLocalModelSkipDialogKey);
+ }
+ }
+
Future<void> save(String baseUrl) async {
_cachedBaseUrl = baseUrl;
await _storage.write(_baseUrlKey, baseUrl);
@@ -68,10 +90,12 @@ class ConfigStore {
_cachedBaseUrl = null;
_cachedEnvironment = null;
_cachedSkippedDesktopUpdateVersion = null;
+ _cachedRunLocalModelSkipDialog = false;
await Future.wait([
_storage.delete(_baseUrlKey),
_storage.delete(_environmentKey),
_storage.delete(_skippedDesktopUpdateVersionKey),
+ _storage.delete(_runLocalModelSkipDialogKey),
_storage.delete(_legacyEnvironmentSetupVersionKey),
]);
}
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index 7668bc5b9..e9ee13614 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -1,5 +1,5 @@
import 'dart:async';
-import 'dart:io' show exit, pid;
+import 'dart:io' show Platform, exit, pid;
import 'dart:math' show Random;
import 'package:dio/dio.dart';
@@ -7,6 +7,7 @@ import 'package:dio/dio.dart';
import 'dart:ui' show Color;
import 'package:flutter/foundation.dart';
+import 'package:flutter/widgets.dart' show BuildContext;
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:url_launcher/url_launcher.dart';
@@ -38,6 +39,7 @@ import '../logging/app_log.dart';
import '../shared/theme/app_theme.dart' as grid;
import '../terminal/remote_media_download.dart';
import '../widgets/engine_identity.dart' show allEngines, engineIdentity;
+import '../widgets/run_local_model_dialog.dart' show showRunLocalModelDialog;
import 'dial_status.dart';
import 'pane_layout_store.dart';
import 'terminal_pane.dart';
@@ -3344,24 +3346,130 @@ class AppNotifier extends ChangeNotifier {
/// that timed out are all "nothing to offer", which is what the picker shows.
Future<GridModels> gridModels(String machineId) async {
try {
- final response = await _conn(machineId).request(
- 'grid_models_list',
- timeout: const Duration(seconds: 12),
- );
+ final response = await _conn(machineId)
+ .request('grid_models_list', timeout: const Duration(seconds: 12));
final models = (response['models'] as List<dynamic>? ?? [])
.whereType<Map<String, dynamic>>()
- .map((m) => GridModel(
- id: (m['id'] as String?) ?? '',
- node: (m['node'] as String?) ?? '',
- ))
+ .map(
+ (m) => GridModel(
+ id: (m['id'] as String?) ?? '',
+ node: (m['node'] as String?) ?? '',
+ ),
+ )
.where((m) => m.id.isNotEmpty)
.toList();
- return GridModels(gridName: response['gridName'] as String?, models: models);
+ return GridModels(
+ gridName: response['gridName'] as String?,
+ models: models,
+ );
} catch (_) {
return const GridModels(gridName: null, models: []);
}
}
+ /// The opencode agent the pane is opened AS (`opencode --agent harness-compute`):
+ /// the definition `harness start` installs beside the harness-compute skill,
+ /// whose whole job is that skill. Not a first prompt — the person opens the
+ /// conversation, and the agent's identity is what makes the pane read as
+ /// "the thing that starts a local model" rather than a terminal that happens
+ /// to be running opencode.
+ static const localModelAgent = 'harness-compute';
+
+ /// What the pane is called before, and if never, the engine names its
+ /// session.
+ static const localModelAgentName = 'Local models manager';
+
+ /// The one action behind every "Run a local model" entry: explain once,
+ /// then open opencode as the agent that starts one.
+ ///
+ /// Runs on the computer the app is on ([MachineState.isLocalMachine]) — a
+ /// local model is about THIS hardware — and falls back to the focused
+ /// machine only when there is no local one, in which case the dialog's
+ /// machine line says so by naming it. With the dialog waved off for good
+ /// ([ConfigStore.runLocalModelSkipDialog]) the agent is created straight
+ /// away; otherwise the dialog decides, and Start is what creates. Nothing
+ /// here reports progress: the pane appearing is the confirmation, and a
+ /// refusal lands in [lastError] like any other create.
+ ///
+ /// Takes the caller's [context] because the dialog needs one and this
+ /// notifier holds none — the same shape as every other dialog a door opens.
+ Future<void> runLocalModel(BuildContext context) async {
+ final machine = _localModelMachine();
+ if (machine == null) {
+ _lastError = 'Connect a machine before starting a local model.';
+ _lastErrorRetryable = false;
+ notifyListeners();
+ return;
+ }
+ final machineId = machine.machine.machineId;
+ if (_store?.runLocalModelSkipDialog != true) {
+ final decision = await showRunLocalModelDialog(context, this, machineId);
+ if (decision == null) return;
+ if (decision.skipNextTime) {
+ try {
+ await _store?.saveRunLocalModelSkipDialog(true);
+ } catch (_) {
+ // A state file that cannot be written costs one more look at the
+ // dialog next time, not the agent being asked for now.
+ }
+ }
+ }
+ final error = await _startLocalModelAgent(machineId);
+ if (error != null) {
+ _lastError = error;
+ _lastErrorRetryable = false;
+ notifyListeners();
+ }
+ }
+
+ /// The machine a local model belongs on: this computer's own when the app
+ /// has one, else whatever the person is looking at.
+ MachineState? _localModelMachine() {
+ final local = machineStates.values
+ .where((state) => state.isLocalMachine)
+ .firstOrNull;
+ if (local != null) return local;
+ final focused = focusedPane?.machineId ?? selectedMachineId;
+ return (focused == null ? null : machineStates[focused]) ??
+ machineStates.values.firstOrNull;
+ }
+
+ /// What Start stands for: opencode, in the user's home, opened as the
+ /// `harness-compute` agent and waiting for the person to type. Home rather than
+ /// a project because the model is not about any one repo; no first prompt,
+ /// because the person opens the conversation. Null on success, else the
+ /// sentence for the person.
+ Future<String?> _startLocalModelAgent(String machineId) async {
+ final machine = machineStates[machineId];
+ if (machine == null) return 'Machine not found';
+ final home = await _homeFolderOf(machine);
+ if (home == null) {
+ return 'Could not find the home folder on ${machine.machine.displayName}.';
+ }
+ return createAgent(
+ machineId,
+ engine: 'opencode',
+ folder: home,
+ agent: localModelAgent,
+ name: localModelAgentName,
+ );
+ }
+
+ /// The user's home on [machine]. This computer's is in the environment; a
+ /// remote machine's is known only to that machine, which is what
+ /// `fs_list_dir` with no path answers from (its `listDir` defaults to the
+ /// home directory).
+ Future<String?> _homeFolderOf(MachineState machine) async {
+ if (machine.isLocalMachine) {
+ final home =
+ Platform.environment['HOME'] ?? Platform.environment['USERPROFILE'];
+ if (home != null && home.isNotEmpty) return home;
+ }
+ final listing = await listRemoteFolder(machine.machine.machineId, null);
+ final path = listing['path'];
+ return path is String && path.isNotEmpty ? path : null;
+ }
+
WsConn _conn(String machineId) {
final testConnection = connectionForTest;
if (testConnection != null) return testConnection(machineId);
@@ -4419,6 +4527,9 @@ class AppNotifier extends ChangeNotifier {
bool bypassPermission = false,
String? codexHome,
String? dsh,
+ String? prompt,
+ String? name,
+ String? agent,
String? swarmId,
PaneSplitRequest? split,
AgentCreationAttempt? attempt,
@@ -4433,6 +4544,19 @@ 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,
+ // 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
+ // them refuses a prompt for an engine with no way to take one
+ // (`PROMPT_UNSUPPORTED`), and an empty field would trip that for every
+ // ordinary create.
+ 'prompt': ?prompt,
+ 'name': ?name,
+ // The engine's own named agent to open AS (opencode `--agent <name>`):
+ // the pane is that agent, with its name and system prompt, rather than
+ // a general session. Same absent-unless-asked rule as `prompt`, and the
+ // same refusal for an engine that has no such thing (`AGENT_UNSUPPORTED`).
+ 'agent': ?agent,
};
if (creation._choices != null &&
(creation._machineId != machineId ||
@@ -4505,6 +4629,10 @@ class AppNotifier extends ChangeNotifier {
'INVALID_DSH' =>
'This harness is not installed on $machine. '
'${detail ?? 'Install it there, then try again.'}',
+ 'PROMPT_UNSUPPORTED' =>
+ 'This engine cannot be opened with a first message on $machine.',
+ 'AGENT_UNSUPPORTED' =>
+ 'This engine cannot be opened as a named agent on $machine.',
_ => 'Create agent failed: ${detail ?? code}',
};
@@ -4608,6 +4736,8 @@ class AppNotifier extends ChangeNotifier {
'INVALID_GRID',
'INVALID_CODEX_HOME',
'INVALID_DSH',
+ 'PROMPT_UNSUPPORTED',
+ 'AGENT_UNSUPPORTED',
'TMUX_UNAVAILABLE',
'TMUX_TOO_OLD_FOR_GRID',
'GRID_CONFIG_FAILED',
diff --git a/desktop/lib/widgets/grid_model_picker.dart b/desktop/lib/widgets/grid_model_picker.dart
index 224b8b9cf..02e61c728 100644
--- a/desktop/lib/widgets/grid_model_picker.dart
+++ b/desktop/lib/widgets/grid_model_picker.dart
@@ -35,6 +35,12 @@ class GridModelPicker extends StatefulWidget {
/// have to know a command for.
final VoidCallback? onUseOwnLogin;
+ /// Called when the last row under Local — "Run a local model" — is chosen. An action, not a
+ /// destination: it opens the flow that puts a model on the user's own computer, which is the
+ /// answer to the empty section this menu otherwise stops at. Always offered, whether or not
+ /// anything is being served yet: a person with no Local models is exactly who needs the door.
+ final VoidCallback? onRunLocalModel;
+
/// The grid model this agent is on right now, or null when it is on its own login. Drives the
/// filled row, so the menu answers "where am I" as well as "where could I go".
final String? currentModel;
@@ -55,6 +61,7 @@ class GridModelPicker extends StatefulWidget {
required this.machineId,
this.onSelected,
this.onUseOwnLogin,
+ this.onRunLocalModel,
this.currentModel,
this.webSearch,
this.engineLabel,
@@ -191,10 +198,10 @@ class _GridModelPickerState extends State<GridModelPicker> {
),
const PopupMenuDivider(),
_header('Local'),
- // An empty grid and no grid at all are different facts, and each gets its own sentence: one
- // is "nobody is serving yet", the other "there is nothing to serve on". A single "no models"
- // would send a person looking in the wrong place.
- if (answer.models.isEmpty)
+ // Nothing served is not a sentence here: the "Run a local model" row at the end of this
+ // section IS the answer, and a line saying the list is empty above an empty list is noise.
+ // No grid at all is a different fact the row cannot fix, so that one is said.
+ if (answer.models.isEmpty && answer.gridName == null)
PopupMenuItem<_Choice>(
enabled: false,
height: 30,
@@ -202,9 +209,7 @@ class _GridModelPickerState extends State<GridModelPicker> {
child: Text(
// "Local models", in the user's own vocabulary: the grid is how a Local model is
// served, not a thing this menu asks anyone to know about.
- answer.gridName == null
- ? 'No local models on this account yet — sign in again to set them up.'
- : 'Nothing is being served yet.',
+ 'No local models on this account yet — sign in again to set them up.',
style: TextStyle(fontSize: 11, color: AppColors.textSoft),
),
),
@@ -224,9 +229,22 @@ class _GridModelPickerState extends State<GridModelPicker> {
subtitle: _subtitleFor(model),
),
),
+ // The last row under Local, drawn as one of the models: it is what a person picks when the
+ // model they want is not there yet, so it belongs in the same list, not in a section of its
+ // own. Never filled — the fill means "the agent is here", and this row starts something.
+ PopupMenuItem<_Choice>(
+ value: const _Choice.runLocalModel(),
+ height: 32,
+ padding: EdgeInsets.zero,
+ child: const _Row(selected: false, title: 'Run a local model'),
+ ),
],
);
if (chosen == null) return;
+ if (chosen.runLocalModel) {
+ widget.onRunLocalModel?.call();
+ return;
+ }
// Selecting what is already selected respawns the pane for no reason — do nothing instead.
if (chosen.model == null) {
if (widget.currentModel != null) widget.onUseOwnLogin?.call();
@@ -397,10 +415,14 @@ class _Row extends StatelessWidget {
const double _menuInset = 6;
const double _rowPadding = 8;
-/// One row's meaning: a grid model, or the engine's own login. A sealed pair rather than a nullable
-/// `GridModel`, because `null` already means "the menu was dismissed" in `showMenu`'s own result.
+/// One row's meaning: a grid model, the engine's own login, or the action that starts a local
+/// model. A sealed set rather than a nullable `GridModel`, because `null` already means "the menu
+/// was dismissed" in `showMenu`'s own result — and the action is neither a model nor a login, so
+/// it carries its own flag rather than borrowing `model == null` from the login row.
class _Choice {
final GridModel? model;
- const _Choice.model(GridModel this.model);
- const _Choice.ownLogin() : model = null;
+ final bool runLocalModel;
+ const _Choice.model(GridModel this.model) : runLocalModel = false;
+ const _Choice.ownLogin() : model = null, runLocalModel = false;
+ const _Choice.runLocalModel() : model = null, runLocalModel = true;
}
diff --git a/desktop/lib/widgets/run_local_model_dialog.dart b/desktop/lib/widgets/run_local_model_dialog.dart
new file mode 100644
index 000000000..9f03ad7ed
--- /dev/null
+++ b/desktop/lib/widgets/run_local_model_dialog.dart
@@ -0,0 +1,217 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+
+import '../shared/theme/app_theme.dart' as grid;
+import '../shared/widgets/app_checkbox.dart';
+import '../shared/widgets/app_dialog.dart';
+import '../state/app_state.dart';
+
+/// The one place the "Run a local model" flow is explained.
+///
+/// Both doors — the pane picker's last row and the window's Models menu — go
+/// through [AppNotifier.runLocalModel], which opens this and creates the agent
+/// on Start. The dialog itself creates nothing: it answers with what the
+/// person decided, and the notifier does the rest, so the two doors cannot
+/// drift into two definitions of what Start means.
+///
+/// Null is Not now (or Escape, or a click outside). A record is Start, with
+/// whether the person asked not to see this again — persisted by the caller,
+/// not here, because the store belongs to the notifier.
+Future<({bool skipNextTime})?> showRunLocalModelDialog(
+ BuildContext context,
+ AppNotifier notifier,
+ String machineId,
+) => showAppDialog<({bool skipNextTime})>(
+ context: context,
+ builder: (_) =>
+ _RunLocalModelDialog(notifier: notifier, machineId: machineId),
+);
+
+/// Prerequisites are said only when one is missing, as one sentence in the
+/// machine line's place, with Start disabled. Present and satisfied, nothing
+/// is said — a checklist of green ticks would make a two-second decision look
+/// like a setup screen.
+enum _Prerequisite { opencode, grid }
+
+class _RunLocalModelDialog extends StatefulWidget {
+ const _RunLocalModelDialog({required this.notifier, required this.machineId});
+
+ final AppNotifier notifier;
+ final String machineId;
+
+ @override
+ State<_RunLocalModelDialog> createState() => _RunLocalModelDialogState();
+}
+
+class _RunLocalModelDialogState extends State<_RunLocalModelDialog> {
+ /// Whether the machine has a private grid to serve on. Null until the
+ /// machine answers; the sentence is only earned by an answer, the same rule
+ /// New Agent keeps for a missing engine.
+ bool? _hasGrid;
+
+ bool _skipNextTime = false;
+ bool _skipHovered = false;
+
+ @override
+ void initState() {
+ super.initState();
+ // Two reads, fired on open and not waited for: the dialog is readable at
+ // once, and a missing prerequisite appears as it is found. Deferred a frame
+ // so a probe's first notifyListeners() does not land mid-build. `force` on
+ // the engine probe for the reason New Agent gives — opencode arrives and
+ // leaves through a terminal this app never sees, and a stored answer is
+ // worth nothing here.
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (!mounted) return;
+ unawaited(widget.notifier.probeEngines(widget.machineId, force: true));
+ unawaited(_readGrid());
+ });
+ }
+
+ Future<void> _readGrid() async {
+ final models = await widget.notifier.gridModels(widget.machineId);
+ if (!mounted) return;
+ setState(() => _hasGrid = models.gridName != null);
+ }
+
+ /// The first missing prerequisite, or null when nothing has been found
+ /// missing — which includes "not answered yet".
+ _Prerequisite? get _missing {
+ final machine = widget.notifier.stateOf(widget.machineId);
+ if (machine != null && machine.engines.loaded) {
+ final opencode = machine.engines['opencode'];
+ if (opencode != null && !opencode.installed) {
+ return _Prerequisite.opencode;
+ }
+ }
+ if (_hasGrid == false) return _Prerequisite.grid;
+ return null;
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ // Lives in an Overlay, so a theme flip never reaches it top-down.
+ grid.AppTheme.watch(context);
+ return ListenableBuilder(
+ listenable: widget.notifier,
+ builder: (context, _) {
+ final missing = _missing;
+ // Said only when something is missing. Satisfied, the dialog says
+ // nothing about the machine: the body is the whole message.
+ final status = switch (missing) {
+ _Prerequisite.opencode => 'Needs opencode on this machine first.',
+ _Prerequisite.grid => 'Sign in to Harness again to set this up.',
+ null => null,
+ };
+ return AlertDialog(
+ title: const Text('A model that lives on your machine'),
+ content: SizedBox(
+ width: 440,
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ "Say what you'll use it for. Harness picks one that fits "
+ "this computer, brings it down, and starts it. Once it's "
+ "running, switch to it in any agent you want, right from "
+ "that agent's model picker.",
+ style: TextStyle(
+ fontFamily: grid.AppFont.sans,
+ fontSize: 13.5,
+ height: 1.5,
+ color: grid.AppPalette.textPrimary,
+ ),
+ ),
+ if (status != null) ...[
+ const SizedBox(height: 16),
+ Text(
+ status,
+ key: const Key('run-local-model-status'),
+ style: TextStyle(
+ fontFamily: grid.AppFont.sans,
+ fontSize: 12.5,
+ color: grid.AppPalette.textPrimary,
+ ),
+ ),
+ ],
+ const SizedBox(height: 16),
+ _SkipCheck(
+ value: _skipNextTime,
+ hovered: _skipHovered,
+ onHover: (value) => setState(() => _skipHovered = value),
+ onChanged: (value) => setState(() => _skipNextTime = value),
+ ),
+ ],
+ ),
+ ),
+ actions: [
+ TextButton(
+ key: const Key('run-local-model-not-now'),
+ onPressed: () => Navigator.of(context).pop(),
+ child: const Text('Not now'),
+ ),
+ FilledButton(
+ key: const Key('run-local-model-start'),
+ onPressed: missing == null
+ ? () =>
+ Navigator.of(context).pop((skipNextTime: _skipNextTime))
+ : null,
+ child: const Text('Start'),
+ ),
+ ],
+ );
+ },
+ );
+ }
+}
+
+/// "Don't show this again", box and label under one tap target — the rule
+/// [AppCheckbox] states for every row that carries one.
+class _SkipCheck extends StatelessWidget {
+ const _SkipCheck({
+ required this.value,
+ required this.hovered,
+ required this.onHover,
+ required this.onChanged,
+ });
+
+ final bool value;
+ final bool hovered;
+ final ValueChanged<bool> onHover;
+ final ValueChanged<bool> onChanged;
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ return MouseRegion(
+ cursor: SystemMouseCursors.click,
+ onEnter: (_) => onHover(true),
+ onExit: (_) => onHover(false),
+ child: GestureDetector(
+ key: const Key('run-local-model-skip'),
+ onTap: () => onChanged(!value),
+ behavior: HitTestBehavior.opaque,
+ child: Padding(
+ padding: const EdgeInsets.symmetric(vertical: 6),
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ AppCheckbox(value: value, hovered: hovered, onChanged: onChanged),
+ const SizedBox(width: 10),
+ Text(
+ "Don't show this again",
+ style: TextStyle(
+ fontFamily: grid.AppFont.sans,
+ fontSize: 13,
+ color: grid.AppPalette.textPrimary,
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ );
+ }
+}
diff --git a/desktop/lib/widgets/terminal_panel.dart b/desktop/lib/widgets/terminal_panel.dart
index dad8ce9d6..f7cc3c3eb 100644
--- a/desktop/lib/widgets/terminal_panel.dart
+++ b/desktop/lib/widgets/terminal_panel.dart
@@ -1640,6 +1640,10 @@ class _TerminalHeader extends StatelessWidget {
onUseOwnLogin: () => unawaited(
notifier.clearAgentGrid(session.machineId, session.agentId),
),
+ // The pane's own context, because the flow opens a dialog before it opens a
+ // pane. Which machine it runs on is the notifier's call, not this pane's: a
+ // local model is about the computer the app is on, whatever this agent is on.
+ onRunLocalModel: () => unawaited(notifier.runLocalModel(context)),
),
],
const SizedBox(width: 8),
diff --git a/desktop/macos/Runner/SwarmTitlebar.swift b/desktop/macos/Runner/SwarmTitlebar.swift
index c22b660c2..ca126f614 100644
--- a/desktop/macos/Runner/SwarmTitlebar.swift
+++ b/desktop/macos/Runner/SwarmTitlebar.swift
@@ -434,11 +434,9 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
// section returns when there is a real source for it, not before.
modelsMenu.addItem(.separator())
section("Local")
- if localModels.isEmpty {
- // Says what is true rather than naming something plausible. An empty grid and an unreachable
- // one read the same from here, and both mean "nothing to pick".
- label("No models being served", in: modelsMenu)
- } else {
+ // Nothing served is not said: the "Run a local model" row that ends this section is the
+ // answer, and an empty-list sentence above an empty list is noise.
+ do {
for (id, node) in localModels {
// Same row view as the subscriptions above: the model id reads at full strength where an
// account name would, and the node — which of the user's own machines answers, the detail
@@ -456,8 +454,15 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
modelsMenu.addItem(item)
}
}
- // No `Add Model` either: it dispatched nothing. An action that looks available and does nothing
- // is worse than its absence.
+ // The last row of Local, drawn as one of its models: the thing a person picks when the model
+ // they want is not there yet, so it sits in the same list rather than in a section of its own.
+ // It replaces the `Add Model` placeholder that dispatched nothing, and is wired like Link
+ // Machine…, through the guarded channel handler. Present whether or not anything is served.
+ let run = NSMenuItem(title: "Run a local model", action: #selector(menuAction(_:)), keyEquivalent: "")
+ run.target = self
+ run.representedObject = "runLocalModel"
+ run.identifier = NSUserInterfaceItemIdentifier(HarnessKeymapMenu.actionPrefix + "runLocalModel")
+ modelsMenu.addItem(run)
}
private func updateHistory(_ rows: [[String: Any]], closed: [[String: Any]] = []) {
diff --git a/desktop/test/agent_events_test.dart b/desktop/test/agent_events_test.dart
index 0405c4c38..3a667d8d0 100644
--- a/desktop/test/agent_events_test.dart
+++ b/desktop/test/agent_events_test.dart
@@ -64,6 +64,9 @@ class FakeCreateAgentNotifier extends AppNotifier {
bool bypassPermission = false,
String? codexHome,
String? dsh,
+ String? prompt,
+ String? name,
+ String? agent,
String? swarmId,
PaneSplitRequest? split,
AgentCreationAttempt? attempt,
diff --git a/desktop/test/first_workspace_test.dart b/desktop/test/first_workspace_test.dart
index 9eeeb69f9..cf39b39f4 100644
--- a/desktop/test/first_workspace_test.dart
+++ b/desktop/test/first_workspace_test.dart
@@ -68,6 +68,9 @@ class _FirstUseApp extends AppNotifier {
bool bypassPermission = false,
String? codexHome,
String? dsh,
+ String? prompt,
+ String? name,
+ String? agent,
String? swarmId,
PaneSplitRequest? split,
AgentCreationAttempt? attempt,
diff --git a/desktop/test/grid_model_picker_test.dart b/desktop/test/grid_model_picker_test.dart
index 632fd6555..6caed92d2 100644
--- a/desktop/test/grid_model_picker_test.dart
+++ b/desktop/test/grid_model_picker_test.dart
@@ -55,6 +55,7 @@ void main() {
GridWebSearch? webSearch,
VoidCallback? onOwnLogin,
ValueChanged<GridModel>? onSelected,
+ VoidCallback? onRunLocalModel,
}) async {
tester.view.physicalSize = const Size(1200, 900);
tester.view.devicePixelRatio = 1;
@@ -70,6 +71,7 @@ void main() {
webSearch: webSearch,
onUseOwnLogin: onOwnLogin,
onSelected: onSelected,
+ onRunLocalModel: onRunLocalModel,
),
),
),
@@ -97,10 +99,10 @@ void main() {
expect(find.textContaining('usage'), findsOneWidget);
});
- testWidgets('an empty grid says nobody is serving, not that there is no grid', (tester) async {
- // The daemon answers `{gridName: null, models: []}` when it cannot reach a grid at all, and
- // these two facts need different sentences — one sends you to sign in, the other to serve a
- // model. A single "no models" would send a person looking in the wrong place.
+ testWidgets('no grid at all says so; an empty grid says nothing — the run row is the answer', (tester) async {
+ // The daemon answers `{gridName: null, models: []}` when it cannot reach a grid at all: that
+ // sends you to sign in, which the run row cannot do for you. An empty grid gets no sentence —
+ // the "Run a local model" row under Local is what a person does about it.
await open(tester);
expect(find.textContaining('sign in again'), findsOneWidget);
// The user's vocabulary is "Local models", never "grid" — the grid is how a Local model is
@@ -177,6 +179,69 @@ void main() {
expect(calls, 1);
});
+ group('the last row under Local starts a local model', () {
+ const served = [
+ {'id': 'Qwen-Test', 'node': 'macbook-m1max'},
+ ];
+
+ testWidgets('is there after the served models', (tester) async {
+ build(models: served);
+ await open(tester);
+ expect(find.text('Run a local model'), findsOneWidget);
+ // After the models, not among them: it is the way to get another one, and a row that
+ // started something sitting between two places the agent could go would read as a third.
+ final row = tester.getTopLeft(find.text('Run a local model'));
+ final model = tester.getTopLeft(find.text('Qwen-Test'));
+ expect(row.dy, greaterThan(model.dy));
+ });
+
+ testWidgets('is there when nothing is served, and when there is no grid at all', (tester) async {
+ // The empty-state sentence is the sentence this row answers, so the row is under it — and it
+ // is there even with no grid, because a person with no Local models is exactly who needs it.
+ await open(tester);
+ expect(find.text('Run a local model'), findsOneWidget);
+ final row = tester.getTopLeft(find.text('Run a local model'));
+ final sentence = tester.getTopLeft(find.textContaining('sign in again'));
+ expect(row.dy, greaterThan(sentence.dy));
+ // Never the plumbing's name, in this row as in the rest of the menu.
+ expect(find.textContaining('grid'), findsNothing);
+ });
+
+ testWidgets('is never filled: an action is nowhere, so it cannot be the current row', (tester) async {
+ build(models: served);
+ await open(tester, currentModel: 'Qwen-Test');
+ expect(find.byIcon(Icons.check), findsNothing);
+ Container rowFor(String text) => tester.widget<Container>(
+ find.ancestor(of: find.text(text), matching: find.byType(Container)).first,
+ );
+ expect((rowFor('Qwen-Test').decoration as BoxDecoration?)?.color, isNotNull);
+ expect(rowFor('Run a local model').decoration, isNull);
+ });
+
+ testWidgets('fires onRunLocalModel and nothing else', (tester) async {
+ build(models: served);
+ var runs = 0;
+ var logins = 0;
+ GridModel? picked;
+ await open(
+ tester,
+ currentModel: 'Qwen-Test',
+ onRunLocalModel: () => runs++,
+ onOwnLogin: () => logins++,
+ onSelected: (m) => picked = m,
+ );
+ await tester.tap(find.text('Run a local model'));
+ await tester.pumpAndSettle();
+ expect(runs, 1);
+ // Not a move: the agent stays where it was. `currentModel` is set so a stray own-login call
+ // would have fired — the case where it is silent for its own reason is not the one tested.
+ expect(logins, 0);
+ expect(picked, isNull);
+ // The menu closed on the choice, like any other row.
+ expect(find.text('Run a local model'), findsNothing);
+ });
+ });
+
group('web search on the current Local model', () {
const served = [
{'id': 'Qwen-Test', 'node': 'macbook-m1max'},
diff --git a/desktop/test/models_menu_test.dart b/desktop/test/models_menu_test.dart
index 45e5ddba3..7f781e2f8 100644
--- a/desktop/test/models_menu_test.dart
+++ b/desktop/test/models_menu_test.dart
@@ -4,15 +4,73 @@ import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/screens/swarm_screen.dart';
+import 'package:harness/state/app_state.dart';
import 'package:harness/state/swarm_catalog.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/ws/ws_conn.dart';
import 'swarm_state_test.dart' show createApp;
+/// Answers what the Run a local model dialog reads on opening and records the
+/// create it sends on Start. Anything else asked (the terminal the new pane
+/// opens, say) is left pending, which is what a machine that has not answered
+/// yet looks like — the same shape as the dialog's own test.
+class _LocalModelConn extends WsConn {
+ _LocalModelConn()
+ : super(
+ wsBaseUrl: 'ws://fixture.invalid',
+ autonomousEnv: 'test',
+ machineId: 'm',
+ accessTokenProvider: (_, _) async => '',
+ onAuthFailure: (_) {},
+ onEvent: (_) {},
+ onStatus: (_) {},
+ );
+
+ final creates = <Map<String, dynamic>>[];
+
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) {
+ switch (type) {
+ case 'engines_probe':
+ return Future.value({
+ 'engines': [
+ {'engine': 'opencode', 'installed': true},
+ ],
+ });
+ case 'grid_models_list':
+ return Future.value({'gridName': 'someone-7f3a91c4', 'models': []});
+ case 'fs_list_dir':
+ return Future.value({
+ 'path': '/home/remote',
+ 'entries': [],
+ 'truncated': false,
+ });
+ case 'agent_create':
+ creates.add(Map.of(payload));
+ return Future.value({
+ 'creationId': payload['creationId'],
+ 'state': 'created',
+ 'agent': {
+ 'id': 'lm1',
+ 'name': 'Local models manager',
+ 'engine': 'opencode',
+ },
+ });
+ default:
+ return Completer<Map<String, dynamic>>().future;
+ }
+ }
+}
+
class _Source implements UsageSource {
_Source(this.provider, this.answer);
@override
@@ -255,4 +313,67 @@ void main() {
projects.dispose();
},
);
+
+ testWidgets(
+ 'native runLocalModel opens the dialog, and Start creates the agent',
+ (tester) async {
+ // The Models menu's one command arrives as a bare method call with no
+ // arguments, the way Link Machine… does. It must reach the notifier's
+ // action through this screen's context — the dialog is the proof the
+ // door is wired, and the create is the proof it leads somewhere.
+ tester.view.physicalSize = const Size(1200, 900);
+ tester.view.devicePixelRatio = 1;
+ addTearDown(tester.view.reset);
+ const channel = MethodChannel('harness/swarm_tabs');
+ final messenger = tester.binding.defaultBinaryMessenger;
+ messenger.setMockMethodCallHandler(channel, (call) async => true);
+ addTearDown(() => messenger.setMockMethodCallHandler(channel, null));
+ final conn = _LocalModelConn();
+ final app = createApp(connectionForTest: (_) => conn);
+ // A create on a machine the app believes offline parks the agent and
+ // polls for the node — a timer that never lets the frame settle. The
+ // fixture host is answering, so say so.
+ app.machineStates['m']!.nodeOnline = true;
+ final projects = SwarmProjectStore();
+ await tester.pumpWidget(
+ MaterialApp(
+ home: SwarmScreen(
+ notifier: app,
+ nativeTabs: true,
+ projectStore: projects,
+ ),
+ ),
+ );
+ final reply = Completer<void>();
+ messenger.handlePlatformMessage(
+ channel.name,
+ const StandardMethodCodec().encodeMethodCall(
+ const MethodCall('runLocalModel'),
+ ),
+ (_) => reply.complete(),
+ );
+ await tester.pumpAndSettle();
+ expect(find.text('A model that lives on your machine'), findsOneWidget);
+ // Nothing is missing on this machine, so nothing about it is said.
+ expect(find.byKey(const Key('run-local-model-status')), findsNothing);
+ expect(conn.creates, isEmpty);
+
+ await tester.tap(find.byKey(const Key('run-local-model-start')));
+ await tester.pumpAndSettle();
+ // The handler answers only once the dialog is done, the way every
+ // dialog door does, so native focus is not handed back mid-dialog.
+ await reply.future;
+ expect(find.text('A model that lives on your machine'), findsNothing);
+ final create = conn.creates.single;
+ expect(create['engine'], 'opencode');
+ expect(create['agent'], AppNotifier.localModelAgent);
+ expect(create['name'], AppNotifier.localModelAgentName);
+ expect(create.containsKey('prompt'), isFalse);
+ expect(create['cwd'], '/home/remote');
+
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ projects.dispose();
+ },
+ );
}
diff --git a/desktop/test/new_agent_codex_profile_test.dart b/desktop/test/new_agent_codex_profile_test.dart
index 05dc1775c..6e47c6b0f 100644
--- a/desktop/test/new_agent_codex_profile_test.dart
+++ b/desktop/test/new_agent_codex_profile_test.dart
@@ -129,6 +129,9 @@ class _Notifier extends AppNotifier {
bool bypassPermission = false,
String? codexHome,
String? dsh,
+ String? prompt,
+ String? name,
+ String? agent,
String? swarmId,
PaneSplitRequest? split,
AgentCreationAttempt? attempt,
diff --git a/desktop/test/new_agent_dsh_test.dart b/desktop/test/new_agent_dsh_test.dart
index c6e243741..fdb69fe1e 100644
--- a/desktop/test/new_agent_dsh_test.dart
+++ b/desktop/test/new_agent_dsh_test.dart
@@ -100,6 +100,9 @@ class _Notifier extends AppNotifier {
bool bypassPermission = false,
String? codexHome,
String? dsh,
+ String? prompt,
+ String? name,
+ String? agent,
ProjectFolderRequest? projectFolder,
String? swarmId,
PaneSplitRequest? split,
diff --git a/desktop/test/new_agent_engine_check_test.dart b/desktop/test/new_agent_engine_check_test.dart
index 6b9bb59c8..ecbb5b787 100644
--- a/desktop/test/new_agent_engine_check_test.dart
+++ b/desktop/test/new_agent_engine_check_test.dart
@@ -312,6 +312,9 @@ class _RetryNotifier extends AppNotifier {
bool bypassPermission = false,
String? codexHome,
String? dsh,
+ String? prompt,
+ String? name,
+ String? agent,
String? swarmId,
PaneSplitRequest? split,
AgentCreationAttempt? attempt,
diff --git a/desktop/test/new_agent_project_picker_test.dart b/desktop/test/new_agent_project_picker_test.dart
index 869af0d91..19b2c1f6a 100644
--- a/desktop/test/new_agent_project_picker_test.dart
+++ b/desktop/test/new_agent_project_picker_test.dart
@@ -67,6 +67,9 @@ class _App extends AppNotifier {
String? swarmId,
PaneSplitRequest? split,
String? dsh,
+ String? prompt,
+ String? name,
+ String? agent,
AgentCreationAttempt? attempt,
}) async {
calls.add({
diff --git a/desktop/test/remote_folder_picker_test.dart b/desktop/test/remote_folder_picker_test.dart
index 65823231b..9cf2825df 100644
--- a/desktop/test/remote_folder_picker_test.dart
+++ b/desktop/test/remote_folder_picker_test.dart
@@ -48,6 +48,9 @@ class _Folders extends AppNotifier {
bool bypassPermission = false,
String? codexHome,
String? dsh,
+ String? prompt,
+ String? name,
+ String? agent,
String? swarmId,
PaneSplitRequest? split,
AgentCreationAttempt? attempt,
diff --git a/desktop/test/run_local_model_dialog_test.dart b/desktop/test/run_local_model_dialog_test.dart
new file mode 100644
index 000000000..f404ffb3d
--- /dev/null
+++ b/desktop/test/run_local_model_dialog_test.dart
@@ -0,0 +1,310 @@
+// The Run a local model dialog and the one action behind it: the copy, the machine line, the
+// prerequisites that replace it, and what Start actually sends.
+import 'dart:async';
+import 'dart:io' show Platform;
+
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/auth/auth_session.dart';
+import 'package:harness/core/config.dart';
+import 'package:harness/core/local_key_value_store.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/settings/config_store.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/ws/ws_conn.dart';
+
+class _MemoryStore 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);
+ }
+}
+
+/// A connection that answers the dialog's three reads and the create at once. Without it the
+/// dialog would wait out each request's own timeout, and `pumpAndSettle` would be measuring those
+/// rather than the dialog. Anything else asked of it (a terminal open after the create, say) is
+/// left pending, which is what a machine that has not answered yet looks like.
+class _Conn extends WsConn {
+ _Conn({required this.engines, required this.gridName})
+ : super(
+ wsBaseUrl: 'ws://fixture.invalid',
+ autonomousEnv: 'test',
+ machineId: 'local',
+ accessTokenProvider: (_, _) async => '',
+ onAuthFailure: (_) {},
+ onEvent: (_) {},
+ onStatus: (_) {},
+ );
+
+ final List<Map<String, Object?>> engines;
+ final String? gridName;
+
+ /// Every `agent_create` payload, verbatim — the wire is what the plan specifies.
+ final creates = <Map<String, dynamic>>[];
+
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) {
+ switch (type) {
+ case 'engines_probe':
+ return Future.value({'engines': engines});
+ case 'grid_models_list':
+ return Future.value({'gridName': gridName, 'models': <Object?>[]});
+ case 'fs_list_dir':
+ return Future.value({
+ 'path': '/home/remote',
+ 'entries': <Object?>[],
+ 'truncated': false,
+ });
+ case 'agent_create':
+ creates.add(Map.of(payload));
+ return Future.value({
+ 'creationId': payload['creationId'],
+ 'state': 'created',
+ 'agent': {
+ 'id': 'lm1',
+ 'name': 'Local models manager',
+ 'engine': 'opencode',
+ },
+ });
+ default:
+ return Completer<Map<String, dynamic>>().future;
+ }
+ }
+}
+
+const _installed = [
+ {'engine': 'opencode', 'installed': true},
+];
+
+void main() {
+ late AppNotifier notifier;
+ late _Conn conn;
+
+ void build({
+ List<Map<String, Object?>> engines = _installed,
+ String? gridName = 'someone-7f3a91c4',
+ ConfigStore? configStore,
+ bool local = true,
+ }) {
+ conn = _Conn(engines: engines, gridName: gridName);
+ notifier = AppNotifier(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: configStore,
+ connectionForTest: (_) => conn,
+ )..hasNavigationRail = false;
+ const machine = Machine(
+ machineId: 'local',
+ authMode: MachineAuthMode.remote,
+ name: 'studio-7',
+ );
+ notifier.machines = [machine];
+ notifier.machineStates['local'] = MachineState(machine)
+ ..localOnly = local
+ ..agentLoadStatus = AgentLoadStatus.loaded;
+ if (!local) notifier.selectedMachineId = 'local';
+ }
+
+ setUp(() => build());
+ tearDown(() => notifier.dispose());
+
+ /// Mounts a door — one button that calls the action every real door calls — and presses it.
+ Future<void> open(WidgetTester tester) async {
+ tester.view.physicalSize = const Size(1200, 900);
+ tester.view.devicePixelRatio = 1;
+ addTearDown(tester.view.reset);
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: Builder(
+ builder: (context) => Center(
+ child: TextButton(
+ key: const Key('door'),
+ onPressed: () => notifier.runLocalModel(context),
+ child: const Text('Run a local model'),
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.tap(find.byKey(const Key('door')));
+ await tester.pumpAndSettle();
+ }
+
+ final start = find.byKey(const Key('run-local-model-start'));
+ final status = find.byKey(const Key('run-local-model-status'));
+ String statusText(WidgetTester tester) => tester.widget<Text>(status).data!;
+ bool startEnabled(WidgetTester tester) =>
+ tester.widget<FilledButton>(start).onPressed != null;
+
+ testWidgets('the copy is the plan\'s, and names no plumbing', (tester) async {
+ await open(tester);
+
+ expect(find.text('A model that lives on your machine'), findsOneWidget);
+ expect(
+ find.text(
+ "Say what you'll use it for. Harness picks one that fits this computer, brings it down, "
+ "and starts it. Once it's running, switch to it in any agent you want, right from that "
+ "agent's model picker.",
+ ),
+ findsOneWidget,
+ );
+ expect(find.text("Don't show this again"), findsOneWidget);
+ expect(find.text('Not now'), findsOneWidget);
+ expect(find.text('Start'), findsOneWidget);
+ // The product's two rules for this dialog: never the CLI's name, never one vendor's noun for
+ // a computer. The app runs on Linux too.
+ expect(find.textContaining('grid'), findsNothing);
+ expect(find.textContaining('this Mac'), findsNothing);
+ expect(find.textContaining('!'), findsNothing);
+ // No dashes of any kind in the copy: the owner's rule for this dialog.
+ expect(find.textContaining('—'), findsNothing);
+ expect(find.textContaining('–'), findsNothing);
+ // Nothing about the machine when nothing is missing: the body is the whole message.
+ expect(status, findsNothing);
+ });
+
+ testWidgets('missing opencode is said, and disables Start', (tester) async {
+ build(
+ engines: const [
+ {'engine': 'opencode', 'installed': false},
+ ],
+ );
+ await open(tester);
+
+ expect(statusText(tester), 'Needs opencode on this machine first.');
+ expect(find.textContaining('studio-7'), findsNothing);
+ expect(startEnabled(tester), isFalse);
+ await tester.tap(start, warnIfMissed: false);
+ await tester.pumpAndSettle();
+ expect(find.text('Start'), findsOneWidget);
+ expect(conn.creates, isEmpty);
+ });
+
+ testWidgets('no private grid yet sends the person back to sign in', (
+ tester,
+ ) async {
+ // `gridName: null` is the daemon saying the backend has not minted one, which a new sign-in
+ // fixes; the sentence says that and, like the picker, never says "grid".
+ build(gridName: null);
+ await open(tester);
+
+ expect(statusText(tester), 'Sign in to Harness again to set this up.');
+ expect(find.textContaining('grid'), findsNothing);
+ expect(startEnabled(tester), isFalse);
+ });
+
+ testWidgets('Not now creates nothing', (tester) async {
+ await open(tester);
+ await tester.tap(find.byKey(const Key('run-local-model-not-now')));
+ await tester.pumpAndSettle();
+
+ expect(find.text('A model that lives on your machine'), findsNothing);
+ expect(conn.creates, isEmpty);
+ expect(notifier.panes, isEmpty);
+ });
+
+ testWidgets(
+ 'Start opens opencode in the home folder as the harness-compute agent, named',
+ (tester) async {
+ await open(tester);
+ await tester.tap(start);
+ await tester.pumpAndSettle();
+
+ expect(find.text('A model that lives on your machine'), findsNothing);
+ final payload = conn.creates.single;
+ expect(payload['engine'], 'opencode');
+ // The pane IS the agent (`opencode --agent harness-compute`), and is titled before opencode
+ // reports a session title.
+ expect(payload['agent'], 'harness-compute');
+ expect(payload['name'], 'Local models manager');
+ // No first message: the person opens the conversation, and the dialog says so.
+ expect(payload.containsKey('prompt'), isFalse);
+ // Home, not a project: a local model is not about any one repo.
+ expect(payload['cwd'], Platform.environment['HOME']);
+ expect(payload.containsKey('dsh'), isFalse);
+ // The pane appearing IS the confirmation — created, placed and focused the way New Agent does.
+ expect(notifier.panes.single.agentId, 'lm1');
+ expect(notifier.focusedPane?.agentId, 'lm1');
+ },
+ );
+
+ testWidgets('an ordinary create sends neither prompt, name nor agent', (
+ tester,
+ ) async {
+ // A daemon that knows the fields refuses a prompt or an agent for an engine with no way to
+ // take one, so the fields must be ABSENT — not empty — on every create that did not ask.
+ await notifier.createAgent('local', engine: 'claude', folder: '/work');
+ final payload = conn.creates.single;
+ expect(payload.containsKey('prompt'), isFalse);
+ expect(payload.containsKey('name'), isFalse);
+ expect(payload.containsKey('agent'), isFalse);
+ });
+
+ testWidgets('the tick is remembered, and the next entry skips the dialog', (
+ tester,
+ ) async {
+ final storage = _MemoryStore();
+ build(configStore: ConfigStore(storage: storage));
+ await open(tester);
+ await tester.tap(find.byKey(const Key('run-local-model-skip')));
+ await tester.pump();
+ await tester.tap(start);
+ await tester.pumpAndSettle();
+ expect(conn.creates, hasLength(1));
+
+ // Persisted under the plan's key, and read back by a fresh store — the choice is about the
+ // person, and it has to survive a relaunch to be one.
+ expect(storage.values['runLocalModel.skipDialog'], 'true');
+ final reopened = ConfigStore(storage: storage);
+ await reopened.load();
+ expect(reopened.runLocalModelSkipDialog, isTrue);
+
+ await tester.tap(find.byKey(const Key('door')));
+ await tester.pumpAndSettle();
+ expect(find.text('A model that lives on your machine'), findsNothing);
+ expect(conn.creates, hasLength(2));
+ expect(conn.creates.last['agent'], 'harness-compute');
+ expect(conn.creates.last.containsKey('prompt'), isFalse);
+ });
+
+ testWidgets('Start without the tick keeps asking', (tester) async {
+ final storage = _MemoryStore();
+ build(configStore: ConfigStore(storage: storage));
+ await open(tester);
+ await tester.tap(start);
+ await tester.pumpAndSettle();
+ expect(storage.values.containsKey('runLocalModel.skipDialog'), isFalse);
+
+ await tester.tap(find.byKey(const Key('door')));
+ await tester.pumpAndSettle();
+ expect(find.text('A model that lives on your machine'), findsOneWidget);
+ });
+
+ testWidgets(
+ 'with no local machine the focused one is used, and its own home',
+ (tester) async {
+ // The app can be signed in on a computer whose own daemon is not a machine yet. The model then
+ // goes where the person is looking, and the folder is the home THAT machine reports — this
+ // computer's `$HOME` means nothing there.
+ build(local: false);
+ await open(tester);
+ await tester.tap(start);
+ await tester.pumpAndSettle();
+ expect(conn.creates.single['cwd'], '/home/remote');
+ },
+ );
+}
diff --git a/desktop/tool/swarm_titlebar_checks.swift b/desktop/tool/swarm_titlebar_checks.swift
index 108d3f222..8947862ce 100644
--- a/desktop/tool/swarm_titlebar_checks.swift
+++ b/desktop/tool/swarm_titlebar_checks.swift
@@ -30,6 +30,7 @@ private extension NSButton {
NSGraphicsContext.restoreGraphicsState()
return Data(bytes: bitmap.bitmapData!, count: count)
}
+}
private extension SwarmSubscriptionView {
// `icon` is private to the row view; a same-file extension reads it without widening the app API.
@@ -780,14 +781,35 @@ private extension SwarmTitlebar {
let models = main.item(withTitle: "Models")!.submenu!
try checkTitlebar(models.items.filter { !$0.isSeparatorItem }.map(\.title) == [
"Subscription", "Anthropic, aabbcc, 12% remaining", "OpenAI, Not signed in",
- "Local", "No models being served"
- ], "Models carries only the two sections with something behind them")
+ "Local", "Run a local model"
+ ], "Models carries the two sections with something behind them, ending on the row that starts a model")
try checkTitlebar(models.items.filter(\.isSeparatorItem).count == 1,
- "One native separator, between the two sections")
+ "One native separator, between the sections — the run row is a Local row, not a section")
for gone in ["API", "OpenRouter", "fal.ai", "Add Model"] {
try checkTitlebar(models.item(withTitle: gone) == nil,
"\(gone) is gone — it named nothing this app can reach or do")
}
+ // The row that took Add Model's place is the one item in this menu that does something: the
+ // last row of Local, in the same list as the models, enabled with nothing served, and dispatched
+ // through the same guarded handler as Link Machine… so a modal still swallows it.
+ let runLocal = models.items.last!
+ try checkTitlebar(runLocal.title == "Run a local model",
+ "the last item in Models is the row that runs a local model")
+ try checkTitlebar(!models.items[models.items.count - 2].isSeparatorItem,
+ "the run row sits directly under the Local rows, with no separator of its own")
+ try checkTitlebar(runLocal.isEnabled && runLocal.submenu == nil,
+ "Run a local model is enabled even when nothing is served, and opens no submenu")
+ try checkTitlebar(runLocal.target === self && runLocal.action == #selector(menuAction(_:))
+ && runLocal.representedObject as? String == "runLocalModel",
+ "Run a local model dispatches runLocalModel through the guarded channel handler")
+ try checkTitlebar(runLocal.identifier?.rawValue == HarnessKeymapMenu.actionPrefix + "runLocalModel",
+ "Run a local model is identified for the keymap like every other Harness command")
+ try checkTitlebar(validateMenuItem(runLocal), "Run a local model validates with the workspace live")
+ actionsEnabled = false
+ try checkTitlebar(!validateMenuItem(runLocal), "Run a local model cannot run behind a modal")
+ actionsEnabled = true
+ try checkTitlebar(!runLocal.title.lowercased().contains("grid") && !runLocal.title.contains("Mac"),
+ "the command names neither the plumbing nor one vendor's computer")
// The Local section is DATA, not two hardcoded names. A menu naming a model nobody serves is
// worse than one admitting it has none, which is what the empty case above asserts.
@@ -800,8 +822,10 @@ private extension SwarmTitlebar {
"a served model names the machine answering it")
try checkTitlebar(served.item(withTitle: "DeepSeek-V4-Flash") != nil,
"a model with no node named is listed on its own")
- try checkTitlebar(served.item(withTitle: "No models being served") == nil,
- "the empty-state line is gone once something is served")
+ try checkTitlebar(served.items.last?.title == "Run a local model"
+ && !served.items[served.items.count - 2].isSeparatorItem
+ && served.items.filter(\.isSeparatorItem).count == 1,
+ "the run row stays last in Local, directly under the served models, once models are served")
// A local row is built by the same view as a subscription row, which is what makes the two
// sections read as one menu. A plain disabled NSMenuItem greys its whole title, so a served
@@ -821,11 +845,8 @@ private extension SwarmTitlebar {
try checkTitlebar(localRows.allSatisfy { $0.identity.frame.minX == served.items.compactMap({ $0.view as? SwarmSubscriptionView }).first!.identity.frame.minX },
"local and subscription titles start in the same column")
updateModels(modelRows)
- for title in ["No models being served"] {
- let item = models.item(withTitle: title)!
- try checkTitlebar(!item.isEnabled && item.action == nil && item.target == nil && item.submenu == nil,
- "\(title) is greyed out and cannot dispatch or open anything")
- }
+ try checkTitlebar(models.item(withTitle: "No models being served") == nil,
+ "an empty Local says nothing — the run row is the answer, not a sentence")
let subscription = models.items.first(where: { $0.view is SwarmSubscriptionView })!
let row = subscription.view as! SwarmSubscriptionView
try checkTitlebar(subscription.submenu == nil && subscription.action == nil && !subscription.isEnabled,
diff --git a/docs/plans/2026-09-16-001-run-local-model-entry-plan.md b/docs/plans/2026-09-16-001-run-local-model-entry-plan.md
new file mode 100644
index 000000000..bb9c499d5
--- /dev/null
+++ b/docs/plans/2026-09-16-001-run-local-model-entry-plan.md
@@ -0,0 +1,250 @@
+# Run a local model: one button, one dialog, one agent that starts it
+
+Status: proposed · 2026-09-16
+Builds on: `2026-09-14-004-harness-grid-plan.md` (the private grid), `docs/skills/harness-compute.md`
+(the skill an agent follows), commits `9dc4232`/`2d0cdf7` (the two model pickers) and `6bf3569`
+(an opencode pane actually switching model).
+
+## Context
+
+A person can already end up with a model running on their own machine — but only by knowing to open
+opencode and *ask* for it. The skill triggers on the ask; nothing in the app makes the ask. The
+owner's brief: a visible entry — in the Models menu and in every pane's model picker — that opens
+a short, honest dialog and then starts an agent which does the whole thing, so the user never has
+to know what to type.
+
+### What already works, and must not be rebuilt
+
+- **The skill.** `docs/skills/harness-compute.md`, installed by `harness start` into
+ `~/.config/opencode/skills/harness-compute/SKILL.md`. Triggered by "start a local model", it asks
+ two questions through the agent's own question tool (what for, how much context), reads
+ `grid catalog --json` for what fits this machine, pulls, joins, proves the model answers with
+ `grid chat`, then tells the user to pick it from the model picker. It never says "grid".
+- **Switching a pane to a Local model — the launch half.** `agent_retarget` writes a per-agent
+ `opencode.json` under `~/.harness/cli/data/grid-engine-config/<key>/` (one provider, one model)
+ and respawns the pane with `OPENCODE_CONFIG=<file> -m <provider>/<model> --session <id>`. The
+ global `~/.config/opencode/opencode.json` is never opened. **Kept.** What changes is the second
+ half — how the resumed session is made to *use* that model (Change 5).
+- **Two pickers.** The pane header's (`grid_model_picker.dart`, opens on the daemon's 15s memo, refreshes
+ behind itself) and the native Models menu's Local section (`SwarmTitlebar.swift`, data pushed from
+ `swarm_screen.dart`). Both already say "Nothing is being served yet." when Local is empty — the
+ sentence the new entry is the answer to.
+- **Creating an agent with a launch shape.** `agent_create` (`backendSocket.ts`) takes `engine, cwd,
+ codexHome, grid, dsh, creationId`; `engineLaunch.ts` turns that into argv/env. A DSH (main's
+ domain-specific harnesses) already contributes `agent.args`/`agent.env` from its manifest and is
+ drawn as its own identity in the header (`isHarnessId`), with a tile in New Agent.
+
+### What is missing
+
+1. An entry point. The native menu's "Add Model" was a placeholder and is gone; the pickers list what
+ is served and stop there.
+2. A first prompt. Nothing can open an agent *already asked* to start a local model — `agent_create`
+ carries no prompt, and opencode's `--prompt <text>` (a TUI flag: starts the interactive TUI with
+ that message submitted) is not used anywhere.
+3. A moment of explanation. Opening an opencode pane with no framing reads as "why is a terminal
+ here?". The owner wants a dialog that says what is about to happen, in the product's voice.
+
+## Design principles
+
+1. **Never the plumbing's name.** No "grid", no CLI, no model id the user did not pick, anywhere in
+ the dialog, the menu items or the pane's name.
+2. **Device-agnostic.** The product runs on macOS and Linux. "This computer" or the machine's own
+ display name — never "this Mac".
+3. **The agent does the work; the app only opens the door.** The dialog explains and starts. Every
+ decision after that (what for, which model, go ahead on the slow steps) is the skill's, through the
+ agent's question tool, in the pane.
+4. **Same words in both doors.** Menu item and picker row read identically; both open the same dialog;
+ the dialog is the only place the flow is explained.
+5. **Say it once.** A "Don't show this again" tick: a person who has done this before goes straight
+ to the pane. Stored in the app's config store, per user, not per machine.
+
+## The dialog
+
+Built on `showAppDialog` (`lib/shared/widgets/app_dialog.dart`), the app's one dialog recipe. Copy is
+final unless the owner edits it; it is written the way the README is written — short, declarative,
+second person, no exclamation marks, and no dashes of any kind:
+
+```
+A model that lives on your machine
+
+Say what you'll use it for. Harness picks one that fits this computer,
+brings it down, and starts it. Once it's running, switch to it in any
+agent you want, right from that agent's model picker.
+
+[ ] Don't show this again
+
+ [ Not now ] [ Start ]
+```
+
+- **Nothing about the machine.** An earlier draft carried a machine line (name, chip, usable
+ memory) and a hint ("Type anything in the pane to begin"); the owner cut both — the body is the
+ whole message, and the agent's first question in the pane is the instruction.
+- **Prerequisites appear only when one is missing**, as one sentence under the body, with Start
+ disabled: *"Needs opencode on this machine first."* (the same engine probe New Agent uses) or
+ *"Sign in to Harness again to set this up."* (the machine's grid name is absent). Satisfied,
+ nothing is said.
+- **Buttons.** *Not now* dismisses. *Start* closes the dialog and creates the agent. No spinner: the
+ pane appearing is the confirmation.
+- **"Don't show this again"** — when ticked and Start pressed, `runLocalModel.skipDialog = true` in the
+ config store. Every later entry goes straight to creating the agent. It is a checkbox in the
+ dialog, not a menu setting, because the moment a person decides "I know this" is the moment they
+ are looking at it.
+
+## The pane
+
+`Start` calls `AppNotifier.createAgent` on the local machine with `engine: 'opencode'`, `cwd` = the
+user's home (a local model is not about a project), `agent: 'harness-compute'`, and the name
+**"Local model"**. The daemon launches `opencode --agent harness-compute`: the pane opens *as* that
+agent — its own name in the footer, its own system prompt — not as a general opencode session.
+The user types anything ("go", "hi", a question) and the agent's first visible act is the skill's
+first question, through its question tool.
+
+**The agent definition** ships with Harness, beside the skill: `docs/skills/harness-compute.agent.md`,
+installed by `harness start` into `~/.config/opencode/agents/harness-compute.md` the way the skill is
+(idempotent, best-effort). It is short on purpose — everything it knows is the `harness-compute`
+skill, which it loads first and follows; it declares `mode: primary` (so `--agent` and the TUI's
+agent cycle can reach it) and `permission: question: allow` — measured: opencode denies the
+`question` tool to custom agents by default, and without it the agent falls back to asking in prose,
+which the skill forbids. It refuses unrelated coding asks in one line.
+
+Why `--agent` and not a first prompt: a prompt would make the agent speak first, but the owner
+wants the person to open the conversation; and the agent identity is what makes the pane read as
+"the thing that starts a local model" rather than "a terminal that happens to be running opencode."
+`agent_create`'s `prompt` (Change 1) stays as a generic capability; this flow does not send one.
+
+## Changes
+
+### Change 1 — CLI: `agent_create` carries `prompt`, `name` and `agent`
+
+`cli/src/backendSocket.ts` (`agent_create`), `cli/src/lib/engineLaunch.ts`, `cli/src/lib/registry.ts`.
+
+- `prompt?: string` — optional, trimmed, at most 2000 chars (a first message, not a document).
+ `engineLaunch` appends the engine's own first-prompt argument: opencode `--prompt <text>`; Claude
+ Code and Codex take it positionally; an engine with no documented mechanism gets
+ `PROMPT_UNSUPPORTED` back **before** any pane is created, naming the engine. Only opencode is
+ exercised by this plan; the others are wired because the flag is generic and the contract is
+ documented per engine, the way `gridLaunch.ts` does it.
+- `name?: string` — the row's `defaultName` (main added the field), so the pane is titled before the
+ engine reports a session title, and stays titled if it never does.
+- `agent?: string` — the engine's named agent to open as: opencode `--agent <name>` (verified:
+ `opencode --help`); validated `^[A-Za-z0-9_-]{1,64}$`; any other engine with `agent` set →
+ `AGENT_UNSUPPORTED` before a pane exists, naming the engine. Unlike `prompt`, the agent IS part of
+ the relaunch record: a pane that was opened as `harness-compute` comes back as `harness-compute`.
+- `prompt` is not persisted for relaunch: a relaunch resumes a session that already has its first turn.
+ ⚠️ The prompt is user-visible text, but it still goes through argv only — never a log line — and it
+ is not a secret; the rule is "don't log what the user typed", same as any prompt.
+
+### Change 1b — CLI: install the `harness-compute` agent definition beside the skill
+
+`cli/src/lib/harnessComputeSkill.ts`, `cli/build-bundle.mjs`, `cli/src/config/env.ts`
+(`OPENCODE_AGENT_DIR`, default `$XDG_CONFIG_HOME/opencode/agents`), new `docs/skills/harness-compute.agent.md`.
+Same installer, same idempotent write, same "never fails `harness start`" posture; the bundle ships
+the file next to the skill. The source file carries the exact frontmatter opencode reads
+(`name`, `description`, `mode: primary`, `color`, `permission: { question: allow }`).
+
+### Change 2 — (dropped) hardware RPC
+
+A `local_model_hardware` RPC fed the dialog's machine line; with that line cut, the RPC went too
+rather than stay as unused plumbing. The skill reads `grid device-info` itself when it matters.
+
+### Change 3 — Desktop: the dialog and the action
+
+New `lib/widgets/run_local_model_dialog.dart`; `lib/state/app_state.dart` gains `runLocalModel()`
+and `localModelHardware(machineId)`; config store gains `runLocalModel.skipDialog`.
+
+`runLocalModel()` is the one action both doors call: if `skipDialog`, create the agent; else show the
+dialog and create on Start. It picks the local machine (`isLocalMachine`) — a local model runs on the
+computer the app is on; with no local machine it falls back to the focused one, and the machine line
+says which.
+
+### Change 4 — Desktop: the two doors
+
+- **Pane picker** (`lib/widgets/grid_model_picker.dart`): a last row under Local, always present,
+ after the models or after the empty-state sentence: **Run a local model** — drawn as a row, not a
+ header, and not tickable. Calls `onRunLocalModel`, a new callback `terminal_panel.dart` wires to
+ `notifier.runLocalModel()`.
+- **Native Models menu** (`desktop/macos/Runner/SwarmTitlebar.swift`, `lib/screens/swarm_screen.dart`):
+ after the Local section, a separator and an enabled item **Run a local model** dispatching
+ `menuAction` `runLocalModel`; Dart maps it to `notifier.runLocalModel()` beside `newAgent`. The
+ macOS check script (`desktop/tool/swarm_titlebar_checks.swift`) asserts the item exists, is enabled,
+ and carries that action.
+
+### Change 5 — opencode: a resumed session takes the model it was moved to
+
+`cli/src/engines/opencode/sessionModel.ts` (new), `cli/src/cli.ts` (the retarget path around
+`selectOpencodeModel`), `cli/src/lib/runtimeProfileController.ts` (the `/models` drive, removed).
+
+**What opencode does, measured on 1.18.30 in a real TUI.** A resumed session ignores `-m`, ignores
+`--fork -m`, ignores a top-level `model` in the config it is launched with, and ignores
+`~/.local/state/opencode/model.json`. Its current model is the session's own: the last
+`session.model.selected` event or, failing that, the last assistant message — both rows in
+`~/.local/share/opencode/opencode.db`. Editing `session.model` alone changes nothing; rewriting the
+session's last user message (`data.model`) and last assistant message (`data.modelID`/`providerID`)
+plus `session.model` makes the resumed TUI open on the new model (footer confirmed). There is no
+flag, config key or HTTP route (`/session/{id}/*`, `/api/model/*`, `/tui/*`) that sets a session's
+model — the picker is the only writer opencode ships, which is why `6bf3569` drove it.
+
+**The change.** Before the respawn, write what the picker writes — in the session, through SQL, one
+transaction — then respawn with `--session <id>` as today. The TUI opens already on the model, no
+typing into it, no dependence on its picker's layout. The `/models` drive and its
+`MODEL_SELECT_FAILED` path go, along with their measurements; the launch record still carries the
+model so `gridAssignment` reads the truth back off the process as before.
+
+- **Access:** the `sqlite3` CLI, exactly as `engines/opencode/reader.ts` already reads this DB —
+ same binary, same `OpencodeSqliteMissing` when absent, no new dependency. A missing `sqlite3`
+ refuses the retarget *before* the pane is touched (`OPENCODE_SQLITE_MISSING`), since a respawn
+ that then lands on the old model is the failure `6bf3569` was written against.
+- **Write:** `UPDATE` only, never file operations. WAL mode is opencode's own; other opencode
+ instances holding the DB keep working through a concurrent writer, and `PRAGMA busy_timeout` covers
+ a write that lands during their checkpoint. ⚠️ Never copy, replace or delete the DB or its `-wal`
+ / `-shm` — that is how this DB was damaged during research on 2026-09-16, and the recovery for that
+ is a separate, owner-approved step.
+- **Rows:** the session's `session.model` (`{"id","providerID","variant":"default"}`), and the model
+ fields of its latest user and assistant messages — the exact set measured to take effect. If the
+ source review (in flight) shows a `session.model.selected` event row is what the picker writes and
+ is sufficient on its own, write that instead of touching message history; the plan's contract is
+ "what the picker writes", not "these three rows".
+- **Scope:** opencode only; the other engines' retarget contracts (`gridLaunch.ts`) are untouched.
+- **Verify:** on a real served model, retarget an opencode pane from the picker; the footer shows the
+ model, the conversation is still there, `gridAssignment` reports the new endpoint.
+
+Upstream: file an issue with opencode asking that `-m` override a resumed session's model (or a
+`--session-model` flag). When that ships, this change shrinks to passing `-m`.
+
+## Testing
+
+1. `engineLaunch.spec.ts`: opencode gets `--prompt <text>`; claude/codex get it positionally; an
+ engine without a mechanism refuses with `PROMPT_UNSUPPORTED`; no prompt → argv unchanged; the
+ prompt never appears in the launch record written to disk.
+2. `backendSocket.spec.ts`: `agent_create` with `prompt`+`name` passes both through; `name` lands as
+ `defaultName`; over-long prompt refused.
+3. (dropped with Change 2)
+4. `run_local_model_dialog_test.dart`: the copy (no dashes), nothing said when nothing is missing,
+ the missing-opencode sentence disabling Start, the tick writing `skipDialog`, Not now creating nothing,
+ Start creating an opencode agent as `harness-compute` with the name "Local model" and no prompt.
+5. `grid_model_picker_test.dart`: the last row is present with models and with none, is not ticked,
+ and fires `onRunLocalModel`; `models_menu_test.dart`: the native payload / `runLocalModel` command
+ round-trips to `runLocalModel()`.
+7. `sessionModel.spec.ts` (fixture `opencode.db` built in a temp dir with `sqlite3`): rewrites
+ the session's model and the latest user/assistant messages only, leaves older messages and other
+ sessions alone, is one transaction, and reports `OPENCODE_SQLITE_MISSING` when the CLI is absent.
+ `cli.ts` retarget spec: no `/models` text is ever sent to the pane.
+6. `swarm_titlebar_checks.swift` (`--window-layout`): the menu item exists after Local, enabled, action
+ `runLocalModel`.
+
+## Sequencing
+
+| Phase | Contents | Parallel? |
+|---|---|---|
+| 1a | Change 1 (CLI `prompt`/`name`) | yes — its own files |
+| 1c | Change 3 (dialog + action) | yes — new widget; touches `app_state.dart` for two methods |
+| 1d | Change 4 (two doors) | after 1c's `runLocalModel()` signature exists; picker row and Swift item are independent of each other |
+| 1e | Change 5 (opencode session model) | yes — its own files; the `/models` removal touches `cli.ts`/`runtimeProfileController.ts` |
+| 1f | e2e on a served model, then build and hand to the owner | last |
+| 2 | **Local model as a harness.** Promote to a DSH `autonomous/harness-compute` (`dsh/registry/…json`, a repo carrying the manifest with `engine: opencode`, `agent.args: ["--prompt", …]`): it then appears as a tile in New Agent and is drawn as its own identity in the header, with no opencode chip — an agent that *is* the thing, which is what the owner is asking to see. Phase 1's dialog and doors stay and simply create that harness. Needs a repo and the install step; recorded, not started. | follow-up |
+
+## Open questions
+
+None blocking. Recorded: whether "Local model" should be created in the user's home or in the focused
+pane's project — home for now (the model is not project-scoped); revisit if people expect the agent
+in their repo.
diff --git a/docs/skills/harness-compute.agent.md b/docs/skills/harness-compute.agent.md
new file mode 100644
index 000000000..b2b1b06c6
--- /dev/null
+++ b/docs/skills/harness-compute.agent.md
@@ -0,0 +1,16 @@
+---
+name: 'harness-compute'
+description: 'Starts a model on this computer and makes it available to Harness Compute. Use when the user wants a local model running.'
+mode: primary
+color: '#7C9CFF'
+permission:
+ question: allow
+---
+
+You are **Local models manager** — the agent that gets a model running on this computer, under the user's Harness account, so every coding agent can switch to it from its model picker.
+
+Everything you know about doing that is in the `harness-compute` skill. Load it before you do anything else, and follow it exactly: its ground rules (talk the way Harness talks; never say "grid" or hand the user a command; ask through a tool, not prose), its section 1 (start a local model, ending with where to pick it), and its section 2 (show what's running) when asked. You never edit this agent's config or add a provider: once the model answers, the picker is the hand-off.
+
+**Whatever the user's first message is, begin section 1 at step 1.** "hi", "go", "start", a question — all of them mean "let's do this." Don't explain who you are or what will happen; the app already did. Your first visible act is section 1's first question, through the question tool, with its options. If the user's first message already answers that question (or the context one), skip what was answered.
+
+You are not a general coding assistant. If asked for something outside starting, checking or stopping a local model, say so in one line and offer the one thing you do.
diff --git a/docs/skills/harness-compute.md b/docs/skills/harness-compute.md
index c004dae52..cf15fb412 100644
--- a/docs/skills/harness-compute.md
+++ b/docs/skills/harness-compute.md
@@ -3,22 +3,25 @@
Harness Compute is models running on the user's own machines, under their Harness account,
reachable by any coding agent Harness drives. This file is the same for every agent — Claude
Code, Codex, Cursor, opencode — because they all read the same state through the same `grid`
-commands. The one thing that differs per agent, how it registers a custom provider, is the
-agent's own business; section 2 only hands it what to register.
+commands.
The user does exactly one thing by hand: `harness login`, browser and SSO. That already signs
them into Harness Compute — there is no second sign-in, no second credential, nothing else to set
up first. Everything below, you do for them in conversation. Don't ask them to run something you
-can run yourself, and don't ask them for a base URL, an API key, or a model list — all three are
-discoverable from the commands here.
+can run yourself, and don't ask them for a base URL, an API key, or a model list — nothing here
+needs any of them.
-Three things the user asks for:
+Once a model is running, Harness itself puts it in every agent's **model picker** — the dropdown
+at the top of an agent's pane, and the Models menu in the window. Picking it there switches that
+agent to the model. You never edit an agent's config, never add a provider, never hand over a URL
+or a key: the picker is the whole hand-off.
- 1. Start a local model on this machine, so it joins Harness Compute
- 2. Add it to this agent as a custom provider, so they can chat with it here
- 3. Show what Harness Compute is doing right now
+Two things the user asks for:
-Read the section for what was asked. Don't do the others unprompted.
+ 1. Start a local model on this machine, so it shows up in the model picker
+ 2. Show what Harness Compute is doing right now
+
+Read the section for what was asked. Don't do the other unprompted.
## Ground rules — apply everywhere, in every agent
@@ -83,8 +86,8 @@ followed by the command that answers it.
## 1. Start a local model on this machine
-Goal: this computer serves a model that becomes available to Harness Compute, so any agent it
-is added to as a custom provider (section 2) can chat with it. Five steps, in order.
+Goal: this computer serves a model that becomes available to Harness Compute, so it appears in
+every agent's model picker and the user can switch to it there. Five steps, in order.
**Steps 3 and 4 are a real stop, not a narrated one.** Each downloads or compiles something
multi-gigabyte-to-multi-minute on the user's machine. Ask a direct question ("this will build
@@ -158,8 +161,8 @@ for "fast"). Offer 2–3, through a tool, each with size, context and speed. Pul
What each flag means, because two of them are easy to confuse:
- `--serve` is the **file** step 4 saved, exactly as saved.
- - `--advertise-as` is the **model name the user picks** in whichever agent they connect. Without
- it, the raw filename shows up instead, which nobody wants to type.
+ - `--advertise-as` is the **model name the user sees in the picker**. Without it, the raw
+ filename shows up instead, which nobody wants to read.
- `--name` is **this machine's** display name. A different thing from `--advertise-as`: one
names the model, the other names the computer.
- `--max-concurrency` is how many requests this box takes at once. Keep it low (2) on a shared
@@ -180,9 +183,11 @@ The `-m` is the `--advertise-as` name. A reply means the whole path works. No re
about context size, means it is not ready — fix it (see "When something fails") before telling
the user anything succeeded.
-Once the chat check passes, say it's ready, then ask through a tool: "Add it to this agent as a
-custom provider now, so you can pick the model here?" — section 2 on a yes, nothing on a no.
-Never as a side effect of starting a model.
+Once the chat check passes, say it's ready and where to find it — the `--advertise-as` name is
+what the picker shows: "Qwen3.8-27B is running on this machine. Pick it from the model dropdown
+at the top of any agent's pane, or from the Models menu, and that agent switches to it." That's
+the end of this section. Don't offer to wire it into this agent, edit its config, or add a
+provider — Harness has already done the connecting, and the picker is the only step left.
**To stop it, don't name the command — offer to do it.** Say something like "tell me when you
want it stopped and I'll turn it off," never "stop it with `grid leave`." The user asking you to
@@ -191,40 +196,7 @@ is serving more than one model), and confirm in plain words that it's stopped. T
something you run, never something you hand the user to type.
-## 2. Add it to this agent as a custom provider
-
-**Add a custom provider** to the agent the user is in — opencode, Claude Code, Codex, whichever —
-the way that agent itself adds one; every coding agent has its own flow for a custom
-OpenAI-compatible provider, and it knows its own config better than this file does. This file
-only supplies the values to put in:
-
- eval "$(grid info <grid> --env)" && curl -s -H "Authorization: Bearer $OPENAI_API_KEY" \
- "$OPENAI_BASE_URL/models"
-
-One invocation, never split: each shell command is its own process, so an export in one dies
-before the next. That gives the three inputs:
-
- - **Base URL** — `$OPENAI_BASE_URL`, exactly as printed. It already ends in the versioned path;
- don't append `/v1` or trim it — the client adds `/chat/completions` itself.
- - **API key** — `$OPENAI_API_KEY`, as a literal. It goes in the agent's **global** config, never
- a project file that lands in a repo. Never write it anywhere else, and never echo it back to
- the user in chat.
- - **Models** — the `/models` list. Skip any entry whose `owned_by` is a router (`Auto` and
- friends); everything else is a real model, keyed by its exact `id`, case included.
- `context_window`, when present, is the model's context limit; when absent, leave the limit
- out rather than inventing one.
-
-Name the provider whatever the agent's flow asks for, so the user recognises it in the picker.
-
-Don't make it the agent's default model; leave whatever default was there. The agent needs a
-restart to load a new provider — say so, then which models are now available and how the agent
-picks one. Don't claim it's usable until after the restart.
-
-If the agent later answers `Unauthorized` and nothing else changed, the key went stale (a
-sign-in mints a new one): redo this section, which rewrites it.
-
-
-## 3. Show what's running
+## 2. Show what's running
Read-only, safe to run any time. `<grid>` is the name derived in the ground rules.
@@ -258,8 +230,12 @@ repeat a raw line that names the underlying CLI.
shows what each machine actually has loaded.
- **`exceeds the available context size`** (an agent may show it as a garbled "expected array
`choices`") → the model was served with too small a window, usually `--ctx-size` left off.
- Stop it and join again with the context the user asked for; then redo section 2 so the
- agent's context limit matches. The model is fine; only its window was too small.
+ Stop it and join again with the context the user asked for. The model is fine; only its
+ window was too small.
+ - **The user says it isn't in the picker** → it is only there while it is being served. Run
+ `grid stats <grid> --verbose`; if this machine no longer lists it, start it again (section 1,
+ step 5 — the weights are still on disk, nothing to pull). If it is listed, tell them to open
+ the picker again; it refreshes on open.
---
@@ -274,8 +250,10 @@ the account this runs against, no grid matches the name rule — this file tells
stop and say so rather than inventing a network name, since names
are globally unique and a guessed one can collide with another user's account.
-There is deliberately no per-agent page and no fixed provider name: section 2 says "add a custom
-provider" and hands over the base URL, key and model list, because every coding agent already
-knows how to add a custom OpenAI-compatible provider to itself — better than a page here could,
-and without drifting when its config format changes. The words "add a custom provider" are the
-hook those agents' own skills recognise; keep them, and don't decorate them.*
+There is deliberately no "add a custom provider" section any more. The Harness app lists what the
+account's grid is serving in every pane's model picker and the window's Models menu
+(`grid_models_list`), and picking one retargets that agent itself (`agent_retarget` — for
+opencode, by writing the model into its session and respawning). So the agent that started the
+model has nothing to wire up: no base URL, no key, no config edit. Reintroducing that section
+would put two paths to the same model in front of the user, and only one of them survives a
+sign-in that rotates the key.*