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.

Restart a Buddy with extra launch flags (e.g. Claude Code --chrome) (#3351)

0xdiego25f82ba14f8530
diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.ts
index 162d45718..6aa7c8617 100644
--- a/cli/src/backendSocket.spec.ts
+++ b/cli/src/backendSocket.spec.ts
@@ -4465,6 +4465,30 @@ describe('relay down-frames are default-deny: sealed, or the backend\'s own', ()
expect(core.terminals.open).not.toHaveBeenCalled()
})
+ // Launch flags run as the owner: only the owner's own app may send them (core/agents/launches.ts decides from this).
+ it.each(['agent_restart', 'agent_resume'])('tells the launch provider whether a %s came from the owner\'s own app, never a device or an agent\'s own CLI', async type => {
+ const { socket, dispatch } = harness()
+ const provider = vi.fn(async (_type: string, _payload: Record<string, unknown>, reply: (result: Record<string, unknown>) => void, _asker: { ownerApp: boolean }) => reply({}))
+ socket.restartProvider = provider
+ const role = vi.spyOn(gatewayOf(socket).e2ee, 'sessionRole')
+ role.mockReturnValue('web')
+ await dispatch(sealedDown(socket, 'web-1', type, { requestId: 'r', agentId: 'a1', launchArgs: '--chrome' }).frame, 'web-1')
+ await vi.waitFor(() => expect(provider).toHaveBeenCalledTimes(1))
+ expect(provider.mock.calls[0]![3]).toEqual({ ownerApp: true })
+ role.mockReturnValue('device')
+ await dispatch(sealedDown(socket, 'device-1', type, { requestId: 'r', agentId: 'a1', launchArgs: '--chrome' }).frame, 'device-1')
+ await vi.waitFor(() => expect(provider).toHaveBeenCalledTimes(2))
+ const sink = { sendFrame: () => true, sendBinary: () => true }
+ expect(socket.registerLocalClient('local:app', sink)).toBe(true)
+ expect(socket.registerLocalClient('local:tool', sink, { tool: true })).toBe(true)
+ socket.handleLocalFrame('local:app', { type, payload: { requestId: 'r', agentId: 'a1' } })
+ socket.handleLocalFrame('local:tool', { type, payload: { requestId: 'r', agentId: 'a1' } })
+ await vi.waitFor(() => expect(provider).toHaveBeenCalledTimes(4))
+ expect(provider.mock.calls.slice(1).map(call => call[3])).toEqual([{ ownerApp: false }, { ownerApp: true }, { ownerApp: false }])
+ await socket.unregisterLocalClient('local:app')
+ await socket.unregisterLocalClient('local:tool')
+ })
+
it('hands a sealed dsh_install from a paired client to the service that answers it', async () => {
const { socket, dispatch } = harness()
const serviceRouter = vi.fn(() => true)
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
index f7bce43c4..0db44cd78 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -265,7 +265,9 @@ export class BackendSocket {
createProvider: ((payload: Record<string, unknown>, asker: Pick<Asker, 'local' | 'owner' | 'guest'>, reply: (result: Record<string, unknown>) => void) => Promise<void>) | null = null
createStatusProvider: ((payload: Record<string, unknown>, asker: Pick<Asker, 'local' | 'guest'>, reply: (result: Record<string, unknown>) => void) => Promise<void>) | null = null
cancelCreateProvider: ((payload: Record<string, unknown>, asker: Pick<Asker, 'local' | 'guest'>, reply: (result: Record<string, unknown>) => void) => Promise<void>) | null = null
- restartProvider: ((type: string, payload: Record<string, unknown>, reply: (result: Record<string, unknown>) => void) => Promise<void>) | null = null
+ /** `asker.ownerApp`: the request is from the machine owner's own app (the Desktop, a paired app or browser), not a
+ * device, an agent's own CLI or a guest: only that one may change an agent's launch flags. */
+ restartProvider: ((type: string, payload: Record<string, unknown>, reply: (result: Record<string, unknown>) => void, asker: { ownerApp: boolean }) => Promise<void>) | null = null
forkProvider: ((payload: Record<string, unknown>, reply: (result: Record<string, unknown>) => void) => Promise<void>) | null = null
/** Opens a NEW agent that starts with `agentId`'s whole history (lib/forkAgent.ts), exactly as
* `agent_create` does, for the fork requests and the cable. `level` says what the new agent actually
@@ -1357,7 +1359,7 @@ export class BackendSocket {
// A saved conversation resumed, or a live process relaunched in its pane (core/agents/launches.ts).
case 'agent_resume':
case 'agent_restart':
- if (this.restartProvider) await this.restartProvider(type, payload, answer)
+ if (this.restartProvider) await this.restartProvider(type, payload, answer, { ownerApp: owner && !this.toolClients.has(connId) })
else answer({ error: 'UNSUPPORTED_ON_REMOTE' })
return
diff --git a/cli/src/core/agents/launch.spec.ts b/cli/src/core/agents/launch.spec.ts
index 9677837f7..914097a6a 100644
--- a/cli/src/core/agents/launch.spec.ts
+++ b/cli/src/core/agents/launch.spec.ts
@@ -115,6 +115,15 @@ describe('relaunch helpers', () => {
expect(buildLaunchOverrides).toHaveBeenLastCalledWith(deps.launchOverridesDeps, 'claude', expect.objectContaining({ dsh: null, agent: null, startedBy: null, gridLaunch: grid }), 'a1', expect.any(Function), undefined)
})
+ it('carries the row\'s launch flags into the build, so restart, restore and retarget all apply them', async () => {
+ const { deps, helpers } = setup()
+ await helpers.relaunchOverrides(session({ launchArgs: ['--chrome'] }))
+ expect(buildLaunchOverrides).toHaveBeenLastCalledWith(deps.launchOverridesDeps, 'claude', expect.objectContaining({ launchArgs: ['--chrome'] }), 'a1', expect.any(Function), undefined)
+ // A retarget's source does not carry them; the row's still do.
+ await helpers.relaunchOverrides(session({ launchArgs: ['--chrome'] }), { gridLaunch: null } as never)
+ expect(buildLaunchOverrides).toHaveBeenLastCalledWith(deps.launchOverridesDeps, 'claude', expect.objectContaining({ launchArgs: ['--chrome'] }), 'a1', expect.any(Function), undefined)
+ })
+
it('keeps who started it from the row, so a harness another agent started keeps its pull request line', async () => {
const { deps, helpers } = setup()
const grid = { networkId: 'grid-1', networkName: 'Home grid' }
diff --git a/cli/src/core/agents/launch.ts b/cli/src/core/agents/launch.ts
index 0da0b9359..aa4d900cb 100644
--- a/cli/src/core/agents/launch.ts
+++ b/cli/src/core/agents/launch.ts
@@ -58,7 +58,7 @@ export function createLaunchHelpers({ authority, prepareApiTools, launchOverride
session = structuredClone(session)
const changed = { ok: false, error: 'AGENT_CHANGED', detail: 'The harness changed or stopped during launch preparation.' } as const
if (!current()) return changed
- const result = await buildLaunchOverrides(launchOverridesDeps, session.engine, { dsh: session.dsh ?? null, dshRuntime: session.dshRuntime ?? null, swarmSkill: session.swarmSkill, cwd: session.cwd, agent: session.agent ?? null, scmLaunch: session.scmLaunch ?? null, startedBy: session.startedBy ?? null, ...source, gridLaunch: source.gridLaunch ?? null }, configKey, current, native)
+ const result = await buildLaunchOverrides(launchOverridesDeps, session.engine, { dsh: session.dsh ?? null, dshRuntime: session.dshRuntime ?? null, swarmSkill: session.swarmSkill, cwd: session.cwd, agent: session.agent ?? null, scmLaunch: session.scmLaunch ?? null, startedBy: session.startedBy ?? null, launchArgs: session.launchArgs, ...source, gridLaunch: source.gridLaunch ?? null }, configKey, current, native)
if (!current()) return changed
if (!result.ok && (result.unavailable || result.error === 'AGENT_CHANGED')) return result
// Saved-API instructions remain available after an ordinary semantic refusal, as before.
diff --git a/cli/src/core/agents/launchRequests.golden.spec.ts b/cli/src/core/agents/launchRequests.golden.spec.ts
index 8dcd2eee7..a1402f2f8 100644
--- a/cli/src/core/agents/launchRequests.golden.spec.ts
+++ b/cli/src/core/agents/launchRequests.golden.spec.ts
@@ -69,6 +69,7 @@ it.each(['linux', 'darwin'])('preserves healthy launch requests and durable rece
resumeAgent: () => (agentId, permissionMode) => dispatch('resume', { agentId, permissionMode }),
restartAgent: () => agentId => dispatch('restart', { agentId }),
byAgent: agentId => agentId === session.agentId ? session : undefined,
+ stoppedAgent: () => undefined,
// The frame formatter is another boundary; retain recognizable fields
// to detect a wrong agent or a dropped reply without invoking services.
toProject: async row => ({ id: row.agentId, engine: row.engine, cwd: row.cwd } as unknown as AgentFrame),
@@ -87,7 +88,7 @@ it.each(['linux', 'darwin'])('preserves healthy launch requests and durable rece
...(kind === 'project' ? { projectSource: 'new', projectName: 'Fixture' } : { cwd }),
...(kind === 'model' ? { gridModel: 'fixture-model', gridName: 'fixture-grid' } : {}) }
const invoke = () => kind === 'fork' ? requests.fork(payload, reply)
- : kind === 'resume' || kind === 'restart' ? requests.relaunch(`agent_${kind}`, payload, reply)
+ : kind === 'resume' || kind === 'restart' ? requests.relaunch(`agent_${kind}`, payload, reply, { ownerApp: true })
: requests.create(payload, { local: true }, reply)
await invoke()
await vi.waitFor(() => expect(finish).toBeTypeOf('function'))
diff --git a/cli/src/core/agents/launches.spec.ts b/cli/src/core/agents/launches.spec.ts
index 5568c88fb..57d0bae24 100644
--- a/cli/src/core/agents/launches.spec.ts
+++ b/cli/src/core/agents/launches.spec.ts
@@ -93,6 +93,7 @@ function setup(over: Partial<LaunchRequestDeps> = {}, launches: { create?: Creat
byAgent: (id) => known.get(id), toProject: vi.fn(async (s: RegisteredSession) => frameOf(s)),
modelTarget: resolveNewAgentModel,
swarmLaunch: SWARM_LAUNCH,
+ stoppedAgent: () => undefined,
...over,
}
const requests = createLaunchRequests(deps)
@@ -103,7 +104,8 @@ function setup(over: Partial<LaunchRequestDeps> = {}, launches: { create?: Creat
deps, create, fork, resume, restart, replies, requests,
ask: async (payload: Record<string, unknown>, local = true) => { await requests.create(payload, { local }, reply); return replies.at(-1) },
status: async (payload: Record<string, unknown>) => { await requests.createStatus(payload, { local: true }, reply); return replies.at(-1) },
- relaunch: async (type: string, payload: Record<string, unknown>) => { await requests.relaunch(type, payload, reply); return replies.at(-1) },
+ // An app of the owner's own unless a test says otherwise: only that asker may change an agent's launch flags.
+ relaunch: async (type: string, payload: Record<string, unknown>, asker: { ownerApp: boolean } = { ownerApp: true }) => { await requests.relaunch(type, payload, reply, asker); return replies.at(-1) },
forkAsk: async (payload: Record<string, unknown>) => { await requests.fork(payload, reply); return replies.at(-1) },
}
}
@@ -1193,6 +1195,117 @@ describe('agent_resume and agent_restart', () => {
})
})
+describe('agent_restart with launchArgs', () => {
+ /** A record the launch itself writes, as a real restart does once the engine is back: the daemon saves on success. */
+ const records = (flags?: string[]) => {
+ const row = { ...session('a1'), ...(flags ? { launchArgs: flags } : {}) }
+ return { row, byAgent: (id: string) => id === 'a1' ? row : undefined }
+ }
+
+ it('hands the parsed words to the restart, saving nothing itself, and echoes what the record then holds, directly and through a receipt', async () => {
+ const store = records()
+ const restart = vi.fn(async (_id: string, words?: string[]) => { store.row.launchArgs = words; return { ok: true as const, session: store.row, resumed: false } })
+ const run = setup({ byAgent: store.byAgent }, { restart })
+ expect(await run.relaunch('agent_restart', { agentId: 'a1', launchArgs: '--chrome' })).toStrictEqual({ agent: { id: 'a1' }, resumed: false, launchArgs: ['--chrome'] })
+ expect(restart).toHaveBeenCalledWith('a1', ['--chrome'])
+ run.replies.length = 0
+ await run.relaunch('agent_restart', { agentId: 'a1', launchArgs: '--chrome', creationId: CREATION })
+ await vi.waitFor(() => expect(run.replies).toHaveLength(1))
+ expect(run.replies[0]).toMatchObject({ creationId: CREATION, state: 'created', launchArgs: ['--chrome'] })
+ // The same receipt asked again does not restart a second time.
+ await run.relaunch('agent_restart', { agentId: 'a1', launchArgs: '--chrome', creationId: CREATION })
+ expect(run.replies.at(-1)).toMatchObject({ launchArgs: ['--chrome'] })
+ expect(restart).toHaveBeenCalledTimes(2)
+ })
+
+ it('clears with an empty string and echoes an empty list', async () => {
+ const store = records(['--old'])
+ const restart = vi.fn(async (_id: string, words?: string[]) => { store.row.launchArgs = words?.length ? words : undefined; return { ok: true as const, session: store.row, resumed: false } })
+ const run = setup({ byAgent: store.byAgent }, { restart })
+ expect(await run.relaunch('agent_restart', { agentId: 'a1', launchArgs: '' })).toMatchObject({ launchArgs: [] })
+ expect(restart).toHaveBeenCalledWith('a1', [])
+ })
+
+ it('refuses a flag Harness sets, a non-string, a Team-written agent, an unknown agent and a non-owner, restarting nothing', async () => {
+ const run = setup({ byAgent: (id: string) => id === 'written' ? { ...session('written'), permissionMode: 'teamWritten' } : id === 'a1' ? session('a1') : undefined })
+ expect(await run.relaunch('agent_restart', { agentId: 'a1', launchArgs: '--model x' }))
+ .toStrictEqual({ error: 'INVALID_LAUNCH_ARGS', detail: '--model is set by Harness and can\'t be added here.' })
+ expect(await run.relaunch('agent_restart', { agentId: 'a1', launchArgs: 5 })).toMatchObject({ error: 'INVALID_LAUNCH_ARGS' })
+ expect(await run.relaunch('agent_restart', { agentId: 'written', launchArgs: '--chrome' })).toMatchObject({ error: 'INVALID_LAUNCH_ARGS' })
+ expect(await run.relaunch('agent_restart', { agentId: 'gone', launchArgs: '--chrome' })).toStrictEqual({ error: 'AGENT_NOT_FOUND' })
+ expect(run.restart).not.toHaveBeenCalled()
+ })
+
+ // The words are run by the engine as the owner: a device (dial, Pro), an agent's own CLI and a guest may not set them.
+ it('takes them only from the owner\'s own app, whichever way the others ask', async () => {
+ const run = setup()
+ for (const type of ['agent_restart', 'agent_resume']) {
+ expect(await run.relaunch(type, { agentId: 'a1', launchArgs: '--chrome' }, { ownerApp: false }))
+ .toStrictEqual({ error: 'INVALID_LAUNCH_ARGS', detail: 'Launch flags can only be changed from your own Harness app.' })
+ expect(await run.relaunch(type, { agentId: 'a1', launchArgs: '--chrome', creationId: CREATION }, { ownerApp: false })).toMatchObject({ error: 'INVALID_LAUNCH_ARGS' })
+ }
+ expect(run.restart).not.toHaveBeenCalled()
+ expect(run.resume).not.toHaveBeenCalled()
+ // The same asker still restarts and resumes without them.
+ expect(await run.relaunch('agent_restart', { agentId: 'a1' }, { ownerApp: false })).toMatchObject({ resumed: false })
+ expect(await run.relaunch('agent_restart', { agentId: 'a1', launchArgs: '--chrome' })).toMatchObject({ resumed: false })
+ expect(run.restart).toHaveBeenCalledTimes(2)
+ })
+
+ it('takes them on a resume too, validated, handed over and fingerprinted, with a permission mode beside them', async () => {
+ const store = records()
+ const resume = vi.fn(async (_id: string, _mode?: string, words?: string[]) => { store.row.launchArgs = words; return { ok: true as const, session: store.row, resumed: true } })
+ const run = setup({ byAgent: store.byAgent }, { resume })
+ expect(await run.relaunch('agent_resume', { agentId: 'a1', launchArgs: '--chrome' })).toStrictEqual({ agent: { id: 'a1' }, resumed: true, launchArgs: ['--chrome'] })
+ expect(resume).toHaveBeenLastCalledWith('a1', undefined, ['--chrome'])
+ await run.relaunch('agent_resume', { agentId: 'a1', launchArgs: '--chrome', permissionMode: 'plan' })
+ expect(resume).toHaveBeenLastCalledWith('a1', 'plan', ['--chrome'])
+ expect(await run.relaunch('agent_resume', { agentId: 'a1', launchArgs: '--model x' })).toMatchObject({ error: 'INVALID_LAUNCH_ARGS' })
+ run.replies.length = 0
+ await run.relaunch('agent_resume', { agentId: 'a1', launchArgs: '--chrome', creationId: CREATION })
+ await vi.waitFor(() => expect(run.replies).toHaveLength(1))
+ await run.relaunch('agent_resume', { agentId: 'a1', launchArgs: '--other', creationId: CREATION })
+ expect(run.replies.at(-1)).toStrictEqual({ error: 'CREATION_CONFLICT' })
+ })
+
+ // A harness a bad flag left stopped lives in the stopped-agents store, not the registry (resumeAgentService.ts).
+ it('resumes a stopped agent with them: its engine and Team-written mode are read from the stopped store', async () => {
+ const stopped = { ...session('a1'), engine: 'codex' as const }
+ const resume = vi.fn(async () => ({ ok: true as const, session: stopped, resumed: true }))
+ const run = setup({ byAgent: () => undefined, stoppedAgent: (id) => id === 'a1' ? stopped : undefined }, { resume })
+ // Codex's own -c is the owner's to use; a key Harness sets is not, and the engine is the stopped row's.
+ expect(await run.relaunch('agent_resume', { agentId: 'a1', launchArgs: '-c model=x' })).toMatchObject({ error: 'INVALID_LAUNCH_ARGS' })
+ expect(await run.relaunch('agent_resume', { agentId: 'a1', launchArgs: '-c model_reasoning_effort=high' })).toMatchObject({ resumed: true })
+ expect(resume).toHaveBeenCalledExactlyOnceWith('a1', undefined, ['-c', 'model_reasoning_effort=high'])
+ const written = setup({ byAgent: () => undefined, stoppedAgent: () => ({ ...stopped, permissionMode: 'teamWritten' }) })
+ expect(await written.relaunch('agent_resume', { agentId: 'a1', launchArgs: '--chrome' })).toMatchObject({ error: 'INVALID_LAUNCH_ARGS' })
+ expect(await run.relaunch('agent_resume', { agentId: 'nowhere', launchArgs: '--chrome' })).toStrictEqual({ error: 'AGENT_NOT_FOUND' })
+ })
+
+ // Nothing is saved here: the launch saves on success. A refusal, a missing process or an engine that does not start
+ // carries no echo, because there is nothing new on the record to report.
+ it('echoes nothing on a failed reply, directly or through a receipt, whatever the failure', async () => {
+ for (const error of ['AGENT_BUSY', 'NO_ACTIVE_PROCESS', 'RESTART_FAILED', 'RESUME_UNCONFIRMED']) {
+ for (const creationId of [undefined, CREATION]) {
+ const run = setup({}, { restart: vi.fn(async () => ({ ok: false as const, error })) })
+ await run.relaunch('agent_restart', { agentId: 'a1', launchArgs: '--chrome', ...(creationId ? { creationId } : {}) })
+ await vi.waitFor(() => expect(run.replies).toHaveLength(1))
+ expect(run.replies[0], `${error} ${creationId}`).not.toHaveProperty('launchArgs')
+ expect(run.replies[0]).not.toHaveProperty('agent')
+ }
+ }
+ })
+
+ it('treats the same receipt with different flags as a different request', async () => {
+ const run = setup()
+ await run.relaunch('agent_restart', { agentId: 'a1', launchArgs: '--chrome', creationId: CREATION })
+ await vi.waitFor(() => expect(run.replies).toHaveLength(1))
+ await run.relaunch('agent_restart', { agentId: 'a1', launchArgs: '--other', creationId: CREATION })
+ expect(run.replies.at(-1)).toStrictEqual({ error: 'CREATION_CONFLICT' })
+ expect(run.restart).toHaveBeenCalledOnce()
+ })
+})
+
describe('agent_fork', () => {
it('forks the agent named, with a name and a first message when given, and answers with the new one\'s frame and what it got', async () => {
const { forkAsk, fork } = setup()
diff --git a/cli/src/core/agents/launches.ts b/cli/src/core/agents/launches.ts
index 682208ea8..11ce573f1 100644
--- a/cli/src/core/agents/launches.ts
+++ b/cli/src/core/agents/launches.ts
@@ -19,6 +19,7 @@ import { folderTrust } from '../../engines/launchPrep.js'
import type { NativeLaunchResult, NativeLaunchSource } from '../../engines/nativeLaunch.js'
import * as opencodeLaunch from '../../engines/launchControl.js'
import { ENGINES, isTerminalEngine, type AgentEngine } from '../../engines/types.js'
+import { parseLaunchArgs } from '../../lib/launchArgs.js'
import { AgentCreationReceiptError, creationFingerprint, validCreationId, type AgentCreationOutcome, type AgentCreationReceipts, type AgentCreationStatus, type CreationAuthority } from '../../lib/agentCreationReceipt.js'
import type { AgentFrame } from '../../lib/agentFrame.js'
import { engineLabel } from '../../lib/agentNames.js'
@@ -45,14 +46,16 @@ export type CreateAgent = NonNullable<BackendSocket['onCreateAgent']>
export type ForkAgent = NonNullable<BackendSocket['onForkAgent']>
/** Stops an agent's live engine process and relaunches it in the SAME tmux pane, keeping the SAME
* agentId and (best-effort) resuming the same engine session. `resumed` says whether the relaunch
- * actually resumed the prior conversation or had to fall back to a fresh one (core/agents/restart.ts). */
-export type RestartAgent = (agentId: string) => Promise<
+ * actually resumed the prior conversation or had to fall back to a fresh one (core/agents/restart.ts). `launchArgs` are
+ * the owner's new launch words (an empty list clears them): the relaunch is built with them and saves them on the record
+ * only once the engine is back, so a refused or failed restart saves nothing. */
+export type RestartAgent = (agentId: string, launchArgs?: string[]) => Promise<
{ ok: true; session: RegisteredSession; resumed: boolean }
| { ok: false; error: string; detail?: string; reason?: string }
>
/** Resumes stopped work directly, or attaches if it is already running. Never replaces a live process
* and never falls back to a fresh conversation (core/agents/lifecycle.ts). */
-export type ResumeAgent = (agentId: string, permissionMode?: string) => ReturnType<RestartAgent>
+export type ResumeAgent = (agentId: string, permissionMode?: string, launchArgs?: string[]) => ReturnType<RestartAgent>
export interface LaunchRequestDeps {
/** The receipts of launches asked for with a `creationId`. */
@@ -67,6 +70,8 @@ export interface LaunchRequestDeps {
resumeAgent: () => ResumeAgent | null
restartAgent: () => RestartAgent | null
byAgent: (agentId: string) => RegisteredSession | undefined
+ /** A stopped agent's saved row (the stopped-agents store): a resume may bring it back with new launch words. */
+ stoppedAgent: (agentId: string) => RegisteredSession | undefined
/** An agent's frame, as the socket builds it for every reply. */
toProject: (s: RegisteredSession) => Promise<AgentFrame>
/** Where a new agent on a grid model sends its inference: the models service's to resolve, on this
@@ -84,7 +89,7 @@ export interface LaunchRequestDeps {
type Reply = (result: Record<string, unknown>) => void
type CreateInput = Parameters<CreateAgent>[0]
-export function createLaunchRequests({ receipts, createAgent, prepareCreate, prepareEngine, forkAgent, resumeAgent, restartAgent, byAgent, toProject, modelTarget, guestCreate, swarmLaunch, claudeHomeOffered }: LaunchRequestDeps) {
+export function createLaunchRequests({ receipts, createAgent, prepareCreate, prepareEngine, forkAgent, resumeAgent, restartAgent, byAgent, stoppedAgent, toProject, modelTarget, guestCreate, swarmLaunch, claudeHomeOffered }: LaunchRequestDeps) {
const validateInstalled = async (input: CreateInput, known?: ReturnType<typeof installedDsh>): Promise<{ error: string; detail: string } | null> => {
if (input.dsh) {
const installed = known ?? installedDsh(input.dsh)
@@ -597,7 +602,7 @@ export function createLaunchRequests({ receipts, createAgent, prepareCreate, pre
// Resume attaches or restores a saved conversation; restart replaces a live process in its
// existing pane. Both keep the agentId and use the same durable operation receipt protocol.
- const relaunch = async (type: string, payload: Record<string, unknown>, reply: Reply): Promise<void> => {
+ const relaunch = async (type: string, payload: Record<string, unknown>, reply: Reply, asker: { ownerApp: boolean }): Promise<void> => {
const target = payload.agentId as string | undefined
if (!target) { reply({ error: 'MISSING_AGENT_ID' }); return }
const operation = type === 'agent_resume' ? 'resume' : 'restart'
@@ -612,13 +617,37 @@ export function createLaunchRequests({ receipts, createAgent, prepareCreate, pre
if (permissionMode !== undefined && byAgent(target)?.permissionMode === 'teamWritten') {
reply({ error: 'INVALID_PERMISSION_MODE' }); return
}
- const invoke = () => permissionMode === undefined ? restart(target) : resumeAgent()!(target, permissionMode)
+ // Extra launch flags ride a restart or a resume of an agent the owner may change, and are checked with the engine's
+ // own refused list before anything is relaunched. The engine runs them as the owner, so only the owner's own app
+ // may send them (a device, an agent's own CLI and a guest may not), as only it may change a permission.
+ let launchArgs: string[] | undefined
+ if (payload.launchArgs !== undefined) {
+ if (!asker.ownerApp) { reply({ error: 'INVALID_LAUNCH_ARGS', detail: 'Launch flags can only be changed from your own Harness app.' }); return }
+ // A harness a bad flag left stopped is in the stopped store, not the registry: the way back is to resume it.
+ const known = byAgent(target) ?? stoppedAgent(target)
+ if (typeof payload.launchArgs !== 'string' || known?.permissionMode === 'teamWritten') {
+ reply({ error: 'INVALID_LAUNCH_ARGS' }); return
+ }
+ if (!known) { reply({ error: 'AGENT_NOT_FOUND' }); return }
+ const parsed = parseLaunchArgs(known.engine, payload.launchArgs)
+ if (!parsed.ok) { reply({ error: 'INVALID_LAUNCH_ARGS', detail: parsed.detail }); return }
+ launchArgs = parsed.args
+ }
+ // The words travel with the relaunch and the launch saves them once the engine is back (core/agents/restart.ts,
+ // lib/resumeAgentService.ts): a restart refused, a process gone or an engine that did not start leaves the record as
+ // it was, and nothing here has to be undone.
+ const invoke = () => operation === 'resume'
+ ? (launchArgs ? resumeAgent()!(target, permissionMode as string | undefined, launchArgs)
+ : permissionMode === undefined ? restart(target) : resumeAgent()!(target, permissionMode as string))
+ : (launchArgs ? restartAgent()!(target, launchArgs) : restart(target))
+ // What the record holds now: the words a successful launch saved, `[]` once cleared. Never on a failure.
+ const echo = () => launchArgs ? { launchArgs: byAgent(target)?.launchArgs ?? [] } : {}
const creationId = payload.creationId
if (creationId !== undefined) {
if (!validCreationId(creationId)) { reply({ error: 'INVALID_CREATION_ID' }); return }
try {
void receipts.run(creationId, creationFingerprint({ operation, agentId: target,
- ...(permissionMode === undefined ? {} : { permissionMode }) }), async () => {
+ ...(permissionMode === undefined ? {} : { permissionMode }), ...(launchArgs ? { launchArgs } : {}) }), async () => {
const result = await invoke()
if (result.ok) return { state: 'created', agentId: result.session.agentId, resumed: result.resumed }
// RESTART_FAILED can follow an unobserved relaunch. Never silently
@@ -627,7 +656,7 @@ export function createLaunchRequests({ receipts, createAgent, prepareCreate, pre
return { state: 'failed', error: result.error, ...(result.reason ? { reason: result.reason } : {}),
...(result.detail ? { detail: result.detail.slice(0, 2000) } : {}) }
}).then(async (status) => {
- reply({ creationId, ...await creationStatusPayload(status) })
+ reply({ creationId, ...await creationStatusPayload(status), ...(status.state === 'created' ? echo() : {}) })
}).catch(() => reply({ error: 'INTERNAL' }))
} catch (error) {
reply({ error: error instanceof AgentCreationReceiptError ? error.code : 'INTERNAL' })
@@ -639,7 +668,7 @@ export function createLaunchRequests({ receipts, createAgent, prepareCreate, pre
reply({ error: result.error, ...(result.reason ? { reason: result.reason } : {}), ...(result.detail ? { detail: result.detail } : {}) })
return
}
- reply({ agent: await toProject(result.session), resumed: result.resumed })
+ reply({ agent: await toProject(result.session), resumed: result.resumed, ...echo() })
}
// Fork an agent: a second one with the first one's history — see lib/forkAgent.ts. The reply
diff --git a/cli/src/core/agents/lifecycle.spec.ts b/cli/src/core/agents/lifecycle.spec.ts
index 18e5f9a5e..8417453d2 100644
--- a/cli/src/core/agents/lifecycle.spec.ts
+++ b/cli/src/core/agents/lifecycle.spec.ts
@@ -192,10 +192,16 @@ describe('stopping, purging and resuming an agent', () => {
const { deps, lifecycle } = setup()
expect(await lifecycle.resumeAgent('a1', 'plan')).toEqual({ ok: true })
const resume = vi.mocked(createResumeAgentService).mock.results[0].value
- expect(resume).toHaveBeenCalledWith('a1', 'plan')
+ expect(resume).toHaveBeenCalledWith('a1', 'plan', undefined)
expect(deps.stoppedAgents.get).toHaveBeenCalledWith('a1')
})
+ it('carries the owner\'s new launch words to the resume', async () => {
+ const { lifecycle } = setup()
+ await lifecycle.resumeAgent('a1', undefined, ['--chrome'])
+ expect(vi.mocked(createResumeAgentService).mock.results[0].value).toHaveBeenCalledWith('a1', undefined, ['--chrome'])
+ })
+
it('resumes no guest\'s harness, stopped or running: it would run as the owner', async () => {
const stopped = setup({ stoppedAgents: { list: () => [], get: vi.fn(() => row({ guest: '[email protected]' })) } as never })
expect(await stopped.lifecycle.resumeAgent('a1')).toEqual(GUEST_HARNESS_REFUSAL)
diff --git a/cli/src/core/agents/lifecycle.ts b/cli/src/core/agents/lifecycle.ts
index 015ccd2bb..0dc847bf4 100644
--- a/cli/src/core/agents/lifecycle.ts
+++ b/cli/src/core/agents/lifecycle.ts
@@ -116,7 +116,7 @@ export function createAgentLifecycle({
retainExitedSession, announceSession, relaunchOverrides, prepareSessionResume, adoptSwarmSkill,
refreshGridWebSearch, clearDeleted, attachDsh, attachSession, relaunchMarks,
})
- const resumeAgent: ResumeAgent = (id, permissionMode) => {
+ const resumeAgent: ResumeAgent = (id, permissionMode, launchArgs) => {
// A pane a stopped move left may still run this conversation's engine, which no record names (its pid was never
// the row's), so a resume would find the engine gone and start a second one beside it: not this start.
const heldId = (stoppedAgents.get(id) ?? registry.byAgent(id))?.agentId ?? id
@@ -124,12 +124,12 @@ export function createAgentLifecycle({
console.warn(moveHeldLine(heldId))
return Promise.resolve({ ok: false, error: 'AGENT_BUSY', detail: 'This harness is held until the daemon restarts.' })
}
- return resumeChecked(id, permissionMode)
+ return resumeChecked(id, permissionMode, launchArgs)
}
- const resumeChecked: ResumeAgent = (id, permissionMode) => (stoppedAgents.get(id) ?? registry.byAgent(id))?.guest
+ const resumeChecked: ResumeAgent = (id, permissionMode, launchArgs) => (stoppedAgents.get(id) ?? registry.byAgent(id))?.guest
? Promise.resolve(GUEST_HARNESS_REFUSAL)
: purgeAgentService.busy(id) || purgeAgentService.blocksFolder(stoppedAgents.get(id)?.cwd)
- ? Promise.resolve({ ok: false, error: 'AGENT_BUSY' }) : resume(id, permissionMode)
+ ? Promise.resolve({ ok: false, error: 'AGENT_BUSY' }) : resume(id, permissionMode, launchArgs)
return { stopJobs, stopAgent, purgeAgentService, resumeAgent }
}
diff --git a/cli/src/core/agents/nativeCreate.spec.ts b/cli/src/core/agents/nativeCreate.spec.ts
index 349d12dde..34f53cae1 100644
--- a/cli/src/core/agents/nativeCreate.spec.ts
+++ b/cli/src/core/agents/nativeCreate.spec.ts
@@ -68,7 +68,7 @@ it.each([true, false])('completes native Codex preparation before its dispatch c
const receipts = new AgentCreationReceipts(join(root, 'receipts'))
const requests = createLaunchRequests({ receipts, createAgent: () => creator, prepareCreate: creator.prepare,
forkAgent: () => null, resumeAgent: () => null, restartAgent: () => null,
- byAgent: () => pending, toProject: async () => ({ agentId: pending.agentId }) as never, modelTarget: async () => null })
+ byAgent: () => pending, stoppedAgent: () => undefined, toProject: async () => ({ agentId: pending.agentId }) as never, modelTarget: async () => null })
stop = requests.stop
const replies: Record<string, unknown>[] = []
const input = { creationId: 'native_trust_fixture_1', engine: 'codex', cwd, bypassPermission: false, prompt: 'original prompt' }
diff --git a/cli/src/core/agents/restart.spec.ts b/cli/src/core/agents/restart.spec.ts
index f309bf0b9..d7720289a 100644
--- a/cli/src/core/agents/restart.spec.ts
+++ b/cli/src/core/agents/restart.spec.ts
@@ -58,6 +58,7 @@ function setup(row: RegisteredSession | null = agent(), over: Partial<RestartDep
byAgent: vi.fn(() => refreshed ?? undefined),
updateProcessIdentity: vi.fn(),
setActive: vi.fn(),
+ setLaunchArgs: vi.fn(() => true),
} as unknown as RestartDeps['registry'],
purgeBusy: vi.fn(() => false),
stopJobs: new Map(),
@@ -253,6 +254,76 @@ describe('restarting an agent', () => {
expect(run.deps.registry.updateProcessIdentity).not.toHaveBeenCalled()
})
+ describe('with new launch words', () => {
+ const WORDS = ['--chrome']
+
+ it('builds the relaunch with them and saves them on the record only after the engine is back', async () => {
+ const order: string[] = []
+ const run = setup(agent(), {
+ relaunchOverrides: vi.fn(async () => { order.push('build'); return { ok: true as const, overrides: { env: {}, extraArgs: [], clearEnv: [] } } }),
+ })
+ vi.mocked(run.deps.registry.setLaunchArgs).mockImplementation(() => { order.push('save'); return true })
+ vi.mocked(restartAgent).mockImplementationOnce(async () => { order.push('restart'); return { ok: true, resumed: true, processIdentity: newProcess } })
+ expect(await run.restart('a1', WORDS)).toMatchObject({ ok: true })
+ expect(run.deps.relaunchOverrides).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ agentId: 'a1', launchArgs: WORDS }), expect.any(Function), undefined)
+ expect(order).toEqual(['build', 'restart', 'save'])
+ expect(run.deps.registry.setLaunchArgs).toHaveBeenCalledExactlyOnceWith('a1', WORDS)
+ // Asked as its own variant of a restart, so another ask with other words is not answered by this launch.
+ expect(run.deps.restartJobs.run).toHaveBeenCalledWith('a1', expect.any(Function), 'restart', JSON.stringify(WORDS))
+ })
+
+ it('clears them with an empty list: built without, and removed from the record once the engine is back', async () => {
+ const run = setup(agent({ launchArgs: ['--old'] } as Partial<RegisteredSession>))
+ expect(await run.restart('a1', [])).toMatchObject({ ok: true })
+ expect(run.deps.relaunchOverrides).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ launchArgs: [] }), expect.any(Function), undefined)
+ expect(run.deps.registry.setLaunchArgs).toHaveBeenCalledExactlyOnceWith('a1', [])
+ })
+
+ it('without them, relaunches from the row itself and never writes the record', async () => {
+ const row = agent({ launchArgs: ['--saved'] } as Partial<RegisteredSession>)
+ const run = setup(row)
+ expect(await run.restart('a1')).toMatchObject({ ok: true })
+ expect(run.deps.relaunchOverrides).toHaveBeenCalledWith(row, row, expect.any(Function), undefined)
+ expect(run.deps.registry.setLaunchArgs).not.toHaveBeenCalled()
+ expect(run.deps.restartJobs.run).toHaveBeenCalledWith('a1', expect.any(Function), 'restart', undefined)
+ })
+
+ // Every way a restart can end without the engine back saves nothing: the record keeps the flags that last worked.
+ it.each([
+ ['busy', () => setup(agent(), { purgeBusy: () => true })],
+ ['no live process', () => setup(agent({ processIdentity: undefined } as Partial<RegisteredSession>))],
+ ['the agent changed under it', () => setup(agent(), { sameRestartTarget: vi.fn(() => false) })],
+ ['launch preparation refused', () => setup(agent(), { relaunchOverrides: vi.fn(async () => ({ ok: false as const, error: 'GRID_UNAVAILABLE', detail: 'x' })) })],
+ ['the engine did not start', () => {
+ vi.mocked(restartAgent).mockResolvedValueOnce({ ok: false, error: 'RESTART_FAILED', detail: 'did not come up' } as never)
+ return setup(agent())
+ }],
+ ])('saves nothing when the restart ends %s', async (_why, make) => {
+ const run = make()
+ expect(await run.restart('a1', WORDS)).toMatchObject({ ok: false })
+ expect(run.deps.registry.setLaunchArgs).not.toHaveBeenCalled()
+ })
+
+ // The coordinator joins asks of the same words and refuses the others, so the record is what the one launch used.
+ it('two overlapping restarts with different words: one launches and is saved, the other is refused and saves nothing', async () => {
+ let release!: () => void
+ vi.mocked(restartAgent).mockImplementationOnce(async () => {
+ await new Promise<void>((resolve) => { release = resolve })
+ return { ok: true, resumed: true, processIdentity: newProcess }
+ })
+ const run = setup(agent(), { restartJobs: new AgentRestartCoordinator() })
+ const first = run.restart('a1', ['--first'])
+ await vi.waitFor(() => expect(release).toBeDefined())
+ expect(await run.restart('a1', ['--second'])).toMatchObject({ ok: false, error: 'AGENT_BUSY' })
+ const joined = run.restart('a1', ['--first'])
+ release()
+ expect(await first).toMatchObject({ ok: true })
+ expect(await joined).toMatchObject({ ok: true })
+ expect(run.deps.registry.setLaunchArgs).toHaveBeenCalledExactlyOnceWith('a1', ['--first'])
+ expect(restartAgent).toHaveBeenCalledOnce()
+ })
+ })
+
describe('refusals before anything is touched', () => {
it('for an agent being purged, stopped or answered, and for one that is not there', async () => {
expect(await setup(agent(), { purgeBusy: () => true }).restart('a1')).toEqual({ ok: false, error: 'AGENT_BUSY' })
@@ -376,10 +447,10 @@ describe('restarting an agent', () => {
it('keyed by the agent a session id resolves to, or by the id as given when nothing resolves', async () => {
const run = setup(agent())
await run.restart('s1')
- expect(run.deps.restartJobs.run).toHaveBeenCalledWith('a1', expect.any(Function))
+ expect(run.deps.restartJobs.run).toHaveBeenCalledWith('a1', expect.any(Function), 'restart', undefined)
const missing = setup(null)
await missing.restart('ghost')
- expect(missing.deps.restartJobs.run).toHaveBeenCalledWith('ghost', expect.any(Function))
+ expect(missing.deps.restartJobs.run).toHaveBeenCalledWith('ghost', expect.any(Function), 'restart', undefined)
})
it('so a second restart of the same agent joins the first through the real coordinator', async () => {
diff --git a/cli/src/core/agents/restart.ts b/cli/src/core/agents/restart.ts
index bb9accec1..eb432a286 100644
--- a/cli/src/core/agents/restart.ts
+++ b/cli/src/core/agents/restart.ts
@@ -133,8 +133,13 @@ export function createAgentRestarter({
* neither, and before anything is signalled. The sessionId to resume comes from the registry's
* live-synced field, not from the original launch argv (the user may have resumed/switched sessions
* from inside the engine's own terminal since launch).
+ *
+ * [launchArgs] are the owner's new launch words: the relaunch is built with them as its source and the row keeps them
+ * only once the engine is back, so any refusal or failure before that leaves the flags that last worked. Another ask
+ * with other words is refused while this one runs (`restartJobs.run`'s variant), so the row is never left with words
+ * a different launch used.
*/
- const restartAgentHandler: RestartAgentHandler = (agentId) => restartJobs.run(registry.resolve(agentId)?.agentId ?? agentId, async (operationCurrent) => {
+ const restartAgentHandler: RestartAgentHandler = (agentId, launchArgs) => restartJobs.run(registry.resolve(agentId)?.agentId ?? agentId, async (operationCurrent) => {
if (purgeBusy(agentId) || stopJobs.has(agentId) || pinnedControls.has(agentId)) return { ok: false, error: 'AGENT_BUSY' }
// A pane a stopped move left may still run this conversation's engine: neither a swap nor a held launch starts
// another beside it (core/main.ts, `removeOrphanMovePanes`).
@@ -223,7 +228,7 @@ export function createAgentRestarter({
// half, and an agent moved here by a retarget has nothing in the session env at all), or its
// Codex profile. Refused before anything is killed, so a restart that cannot honour the grid
// leaves the running process alone.
- const built = await relaunchOverrides(session, session, current, native)
+ const built = await relaunchOverrides(session, launchArgs ? { ...session, launchArgs } : session, current, native)
if (!current()) return changed
if (!built.ok) return built
@@ -245,6 +250,8 @@ export function createAgentRestarter({
// A refused relaunch (Windows: a batch-file engine cmd.exe would misread) stopped nothing: its own code.
if (!outcome.ok) return { ok: false, error: outcome.error ?? 'RESTART_FAILED', detail: outcome.detail }
refreshGridWebSearch(session.agentId, built.overrides)
+ // The engine is back with the words: now they are the record's, as `launchModel` is committed.
+ if (launchArgs) registry.setLaunchArgs(session.agentId, launchArgs)
// Address the CANONICAL agentId from the resolved session, not the raw RPC input — `resolve()`
// accepts either an agentId or a bare sessionId, but `setActive`/`byAgent` only ever key on the
@@ -258,6 +265,6 @@ export function createAgentRestarter({
} finally {
releaseRoute()
}
- })
+ }, 'restart', launchArgs && JSON.stringify(launchArgs))
return restartAgentHandler
}
diff --git a/cli/src/core/agents/swap.spec.ts b/cli/src/core/agents/swap.spec.ts
index b00aa2cbc..bcece4b69 100644
--- a/cli/src/core/agents/swap.spec.ts
+++ b/cli/src/core/agents/swap.spec.ts
@@ -60,6 +60,13 @@ describe('the pane-process swap', () => {
prepared.buildArgv({ resumeSessionId: 's1', bypassPermission: false })
expect(buildEngineLaunchArgv).toHaveBeenCalledWith('claude', expect.objectContaining({ native, resumeSessionId: 's1' }))
})
+ it('hands the owner\'s launch words to the argv builder, which puts them last, for a restart, a retarget and a host move alike', () => {
+ const prepared = setup().swap.paneSwapDeps(session(), place(), { ownerArgs: ['--chrome'] })
+ prepared.buildArgv({ resumeSessionId: 's1', bypassPermission: false })
+ expect(buildEngineLaunchArgv).toHaveBeenLastCalledWith('claude', expect.objectContaining({ ownerArgs: ['--chrome'] }))
+ setup().swap.paneSwapDeps(session(), place(), {}).buildArgv({ bypassPermission: false })
+ expect(vi.mocked(buildEngineLaunchArgv).mock.lastCall![1]).not.toHaveProperty('ownerArgs')
+ })
it('wires a background-job check for a plain Claude pane restart, with its own session and env', async () => {
const prepared = setup().swap.paneSwapDeps(session(), place(), { env: { CLAUDE_CONFIG_DIR: '/custom' } })
expect(prepared.stopConflictingJob).toBeDefined()
diff --git a/cli/src/core/agents/swap.ts b/cli/src/core/agents/swap.ts
index 9ab31d9d3..fdc507633 100644
--- a/cli/src/core/agents/swap.ts
+++ b/cli/src/core/agents/swap.ts
@@ -57,7 +57,7 @@ export function createPaneSwap({ byAgent, prepareSessionResume, keepAbandonedCon
session: RegisteredSession,
/** The row's own pane and the backend it is on (`restartTargetOf`): a swap runs where the row is. */
{ backend, runtime }: RestartTarget,
- launch: { native?: import('../../engines/nativeLaunch.js').NativeLaunch; env?: Record<string, string>; extraArgs?: readonly string[]; clearEnv?: readonly string[]
+ launch: { native?: import('../../engines/nativeLaunch.js').NativeLaunch; env?: Record<string, string>; extraArgs?: readonly string[]; ownerArgs?: readonly string[]; clearEnv?: readonly string[]
/** Names the respawn takes out of what the pane was created with, on a backend with no `clearEnv()` of its own
* (the pty host): a retarget home's grid variables. */
clearPaneEnv?: readonly string[] } = {},
@@ -83,6 +83,8 @@ export function createPaneSwap({ byAgent, prepareSessionResume, keepAbandonedCon
...(permissionMode ? { permissionMode } : {}),
...(session.cwd ? { cwd: session.cwd } : {}),
...(launch.extraArgs?.length ? { extraArgs: launch.extraArgs } : {}),
+ // The owner's own words, which the argv builder puts last (engineLaunch.ts `ownerArgs`).
+ ...(launch.ownerArgs?.length ? { ownerArgs: launch.ownerArgs } : {}),
// A pane swap onto a grid has to clear the same vendor credentials a fresh create does, for the
// same reason and against the same failure: an engine re-exec'd with the grid's variables still
// sees whatever else the pane inherited, and picks its provider from all of it. This was the
diff --git a/cli/src/core/main.ts b/cli/src/core/main.ts
index ad2228d89..774d35a73 100644
--- a/cli/src/core/main.ts
+++ b/cli/src/core/main.ts
@@ -2515,7 +2515,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
workspaceMissing, relaunchOverrides, prepareSessionResume, refreshGridWebSearch,
downgradedPermission: (entry, native) => downgradedPermission(entry, entry.bypassPermission === true, 'restore', native),
launch: (entry, opts, overrides, permission) => {
- const { env: launchEnv, extraArgs, clearEnv } = overrides
+ const { env: launchEnv, extraArgs, ownerArgs, clearEnv } = overrides
const argv = buildEngineLaunchArgv(entry.engine, {
...opts,
...(overrides.native ? { native: overrides.native } : {}),
@@ -2525,6 +2525,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {
installIfMissing: enginePathOverride(entry.engine) ? undefined : engineInstallRecipe(entry.engine),
...(entry.cwd ? { cwd: entry.cwd } : {}),
...(extraArgs.length ? { extraArgs } : {}),
+ // The owner's own launch words, last on the command line (engineLaunch.ts `ownerArgs`).
+ ...(ownerArgs?.length ? { ownerArgs } : {}),
...(clearEnv.length ? { clearEnv } : {}),
...(launchEnv.HARNESS_DSH ? { harnessNode: true } : {}),
})
@@ -3056,7 +3058,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
createAgent: () => backend.onCreateAgent, forkAgent: () => backend.onForkAgent,
prepareCreate: creator.prepare, prepareEngine: prepareNativeLaunch,
resumeAgent: () => lifecycle.resumeAgent, restartAgent: () => restartAgent,
- byAgent: (id) => registry.byAgent(id), toProject: (s) => backend.toProject(s),
+ byAgent: (id) => registry.byAgent(id), stoppedAgent: (id) => stoppedAgents.get(id) ?? undefined, toProject: (s) => backend.toProject(s),
modelTarget: (selection) => (ports.models ?? MODELS_OFF).launchTarget(selection),
// A guest's New Harness: built by shared machines, as the guest's own OS user (core/agents/guestCreate.ts).
guestCreate: () => guestCreate,
diff --git a/cli/src/engines/otherLaunch.golden.spec.ts b/cli/src/engines/otherLaunch.golden.spec.ts
index 3d705d3ca..2b7d741cb 100644
--- a/cli/src/engines/otherLaunch.golden.spec.ts
+++ b/cli/src/engines/otherLaunch.golden.spec.ts
@@ -74,7 +74,7 @@ describe('which OpenCode the core asks for, for a named agent', () => {
return { ok: false, error: 'RECORDED' }
},
forkAgent: () => null, resumeAgent: () => null, restartAgent: () => null,
- byAgent: () => undefined, toProject: async () => ({}) as never, modelTarget: async () => null as never,
+ byAgent: () => undefined, stoppedAgent: () => undefined, toProject: async () => ({}) as never, modelTarget: async () => null as never,
})
const results: unknown[] = []
for (const engine of ['opencode', 'claude', 'pi', 'cursor'] as const) {
diff --git a/cli/src/lib/agentFrame.spec.ts b/cli/src/lib/agentFrame.spec.ts
index d3f82c597..79f28d52d 100644
--- a/cli/src/lib/agentFrame.spec.ts
+++ b/cli/src/lib/agentFrame.spec.ts
@@ -160,6 +160,12 @@ describe('agentFrame', () => {
expect(frame).not.toHaveProperty('agent')
})
+ it('carries the owner\'s extra launch flags only when it has some', async () => {
+ const withArgs = { ...session(null), launchArgs: ['--chrome'] }
+ expect(await agentFrame(withArgs, { selectedModel: null, terminalAvailable: true })).toMatchObject({ launchArgs: ['--chrome'] })
+ expect(await agentFrame(session(null), { selectedModel: null, terminalAvailable: true })).not.toHaveProperty('launchArgs')
+ })
+
// The global "last used" order. Null — never an absent key — until an app opens the agent: a push
// without the key would erase an open an earlier frame reported, and a client reads "absent" as a
// daemon too old to keep the stamp.
diff --git a/cli/src/lib/agentFrame.ts b/cli/src/lib/agentFrame.ts
index ec8892cb2..14e73f249 100644
--- a/cli/src/lib/agentFrame.ts
+++ b/cli/src/lib/agentFrame.ts
@@ -94,6 +94,8 @@ export type AgentFrame = {
codexHome: string | null
/** The Claude profile folder (CLAUDE_CONFIG_DIR) this agent launched against; absent or null for the default account. */
claudeHome?: string | null
+ /** The extra launch words the owner saved for this agent (`agent_restart`'s `launchArgs`); absent when it has none. */
+ launchArgs?: string[]
/** The workspace as its SCM describes it, with `kind` (`git`, or `none` for a folder no SCM claims);
* every other field is exactly what `agentProject` reports (scm/types.ts). */
project: ScmDescription | null
@@ -267,6 +269,7 @@ export async function agentFrame(
// `grid: null` is above.
codexHome: s.codexHome ?? null,
claudeHome: s.claudeHome ?? null,
+ ...(s.launchArgs?.length ? { launchArgs: [...s.launchArgs] } : {}),
project,
gitContext,
// All five are real answers when null, for the reason the module doc gives: a frame that omits
diff --git a/cli/src/lib/engineLaunch.spec.ts b/cli/src/lib/engineLaunch.spec.ts
index c5c76b6e2..fe4df9cc6 100644
--- a/cli/src/lib/engineLaunch.spec.ts
+++ b/cli/src/lib/engineLaunch.spec.ts
@@ -970,6 +970,21 @@ describe('a model and effort on launch', () => {
})
})
+describe('the owner\'s own launch words', () => {
+ it('go last: after the extra arguments, the model and the first prompt, so a trailing flag cannot swallow Harness\'s own', () => {
+ const argv = buildEngineCommandArgv('claude', {
+ extraArgs: ['--append-system-prompt', 'be brief'], launchModel: { model: 'opus', effort: null }, firstPrompt: 'go', ownerArgs: ['--chrome', '--add-dir'],
+ })
+ expect(argv).toEqual([engineBin('claude'), '--append-system-prompt', 'be brief', '--model', 'opus', 'go', '--chrome', '--add-dir'])
+ expect(buildEngineCommandArgv('claude', { ownerArgs: [] })).toEqual([engineBin('claude')])
+ })
+
+ it('reach the pane\'s command line through the shell wrapper as separate items', () => {
+ const argv = buildEngineLaunchArgv('claude', { cwd: '/work', ownerArgs: ['--add-dir', 'a b'] })
+ expect(argv.slice(-2)).toEqual(['--add-dir', 'a b'])
+ })
+})
+
describe('a first prompt on launch', () => {
const PROMPT = 'Start a local model on this machine'
diff --git a/cli/src/lib/engineLaunch.ts b/cli/src/lib/engineLaunch.ts
index 4757e70d4..3b9db0ea0 100644
--- a/cli/src/lib/engineLaunch.ts
+++ b/cli/src/lib/engineLaunch.ts
@@ -256,6 +256,13 @@ export interface LaunchCommandOptions {
* never travels this way.
*/
extraArgs?: readonly string[]
+ /**
+ * The words the machine's owner added to this agent (`registry` `launchArgs`), appended after everything else: the
+ * extra arguments, the model and the first prompt. Last, so a trailing flag that takes a value fails loudly at
+ * startup instead of swallowing an argument Harness itself added, and a flag of theirs cannot be read as a value of
+ * Harness's. Checked by `checkLaunchWords` before they get here.
+ */
+ ownerArgs?: readonly string[]
/**
* A shell line to run in the pane BEFORE the engine, from `engineInstall.ts` — the engine is not on
* this machine yet and the user agreed to fetch it.
@@ -402,6 +409,7 @@ export function buildEngineCommandArgv(engine: AgentEngine, opts: LaunchCommandO
if (opts.extraArgs?.length) argv.push(...opts.extraArgs)
if (opts.launchModel) argv.push(...launchModelArgs(engine, opts.launchModel))
if (opts.firstPrompt) argv.push(...firstPromptArgs(engine, opts.firstPrompt))
+ if (opts.ownerArgs?.length) argv.push(...opts.ownerArgs)
// Windows: the engine's .exe, or the node script its npm shim runs; never the .ps1 PowerShell would pick, and never
// a batch file cmd.exe would read the first message through (lib/windows/launch.ts).
return windowsEngineArgv(engine, argv)
diff --git a/cli/src/lib/launchArgs.spec.ts b/cli/src/lib/launchArgs.spec.ts
new file mode 100644
index 000000000..6031f5ec6
--- /dev/null
+++ b/cli/src/lib/launchArgs.spec.ts
@@ -0,0 +1,128 @@
+import { describe, expect, it } from 'vitest'
+import { checkLaunchWords, LAUNCH_ARGS_MAX_CHARS, LAUNCH_ARGS_MAX_WORDS, parseLaunchArgs } from './launchArgs.js'
+
+const refusal = (flag: string) => ({ ok: false, detail: `${flag} is set by Harness and can't be added here.` })
+
+describe('parseLaunchArgs', () => {
+ it('splits words like a shell would, without running one', () => {
+ expect(parseLaunchArgs('claude', '--chrome')).toEqual({ ok: true, args: ['--chrome'] })
+ expect(parseLaunchArgs('claude', ' ')).toEqual({ ok: true, args: [] })
+ expect(parseLaunchArgs('claude', `--add-dir "/a b" --x='y z' c\\ d`)).toEqual({ ok: true, args: ['--add-dir', '/a b', '--x=y z', 'c d'] })
+ expect(parseLaunchArgs('claude', `--x "a\\"b\\\\c" 'd\\e'`)).toEqual({ ok: true, args: ['--x', 'a"b\\c', 'd\\e'] })
+ expect(parseLaunchArgs('claude', `"" a`)).toEqual({ ok: true, args: ['', 'a'] })
+ })
+
+ it('refuses an unclosed quote or a trailing backslash', () => {
+ const quote = parseLaunchArgs('claude', '--x "a')
+ expect(quote.ok).toBe(false)
+ expect(!quote.ok && quote.detail).toContain('quote')
+ const single = parseLaunchArgs('claude', `--x 'a`)
+ expect(!single.ok && single.detail).toContain('quote')
+ const slash = parseLaunchArgs('claude', 'a\\')
+ expect(slash.ok).toBe(false)
+ })
+
+ it('refuses too many words, too many characters, and NUL or newline', () => {
+ const words = parseLaunchArgs('claude', Array.from({ length: LAUNCH_ARGS_MAX_WORDS + 1 }, () => 'a').join(' '))
+ expect(words.ok).toBe(false)
+ expect(!words.ok && words.detail).toContain('20')
+ expect(parseLaunchArgs('claude', Array.from({ length: 20 }, () => 'a').join(' ')).ok).toBe(true)
+ const long = parseLaunchArgs('claude', 'a'.repeat(LAUNCH_ARGS_MAX_CHARS + 1))
+ expect(long.ok).toBe(false)
+ expect(!long.ok && long.detail).toContain('1024')
+ expect(parseLaunchArgs('claude', 'a'.repeat(LAUNCH_ARGS_MAX_CHARS)).ok).toBe(true)
+ expect(parseLaunchArgs('claude', 'a\nb').ok).toBe(false)
+ expect(parseLaunchArgs('claude', 'a\0b').ok).toBe(false)
+ })
+
+ it('refuses the flags Harness sets for Claude, bare, with =value, and quoted', () => {
+ const flags = ['--resume', '-r', '--continue', '-c', '--model', '--permission-mode', '--dangerously-skip-permissions', '--session-id',
+ '--settings', '--append-system-prompt', '--system-prompt', '--mcp-config', '--fork-session',
+ // Added after the audit: each one replaces what Harness tells the agent or where its settings come from.
+ '--setting-sources', '--append-system-prompt-file', '--system-prompt-file', '--effort']
+ for (const flag of flags) {
+ expect(parseLaunchArgs('claude', flag)).toEqual(refusal(flag))
+ expect(parseLaunchArgs('claude', `${flag}=x`)).toEqual(refusal(flag))
+ }
+ expect(parseLaunchArgs('claude', '"--model"')).toEqual(refusal('--model'))
+ expect(parseLaunchArgs('claude', '--chrome --model=opus')).toEqual(refusal('--model'))
+ })
+
+ it('allows a word that is only = or -, and Codex\'s -c', () => {
+ expect(parseLaunchArgs('claude', '= -')).toEqual({ ok: true, args: ['=', '-'] })
+ expect(parseLaunchArgs('codex', '-c model_reasoning_effort=high')).toEqual({ ok: true, args: ['-c', 'model_reasoning_effort=high'] })
+ })
+
+ it('refuses the flags Harness sets for Codex, and resume or fork as the first word', () => {
+ const flags = ['--model', '-m', '--dangerously-bypass-approvals-and-sandbox', '--yolo', '--full-auto', '--ask-for-approval', '-a', '--sandbox', '-s', '--profile', '-p']
+ for (const flag of flags) expect(parseLaunchArgs('codex', `${flag}=x`)).toEqual(refusal(flag))
+ expect(parseLaunchArgs('codex', 'resume').ok).toBe(false)
+ expect(parseLaunchArgs('codex', 'fork --x').ok).toBe(false)
+ expect(parseLaunchArgs('codex', '--continue')).toEqual({ ok: true, args: ['--continue'] })
+ })
+
+ it('refuses -- for every engine, since it would make Harness\'s own later arguments positional', () => {
+ for (const engine of ['claude', 'codex', 'opencode'] as const) {
+ expect(parseLaunchArgs(engine, '--chrome -- x').ok).toBe(false)
+ }
+ })
+
+ it('refuses a refused short flag with its value attached, and still allows Codex -c k=v', () => {
+ for (const word of ['-rabc', '-cfoo']) expect(parseLaunchArgs('claude', word).ok).toBe(false)
+ for (const word of ['-mo3', '-sdanger-full-access', '-aon-request', '-pfoo']) expect(parseLaunchArgs('codex', word).ok).toBe(false)
+ expect(parseLaunchArgs('claude', '-mo3').ok).toBe(true)
+ expect(parseLaunchArgs('codex', '-c k=v')).toEqual({ ok: true, args: ['-c', 'k=v'] })
+ expect(parseLaunchArgs('codex', '-cfoo=1').ok).toBe(true)
+ expect(parseLaunchArgs('codex', '--search')).toEqual({ ok: true, args: ['--search'] })
+ })
+
+ it('refuses Codex resume or fork anywhere in the words', () => {
+ expect(parseLaunchArgs('codex', '--search resume').ok).toBe(false)
+ expect(parseLaunchArgs('codex', '-c k=v fork').ok).toBe(false)
+ expect(parseLaunchArgs('claude', '--search resume').ok).toBe(true)
+ })
+
+ it('applies only the generic rules to other engines', () => {
+ expect(parseLaunchArgs('opencode', '--model x')).toEqual({ ok: true, args: ['--model', 'x'] })
+ expect(parseLaunchArgs('opencode', '-rabc')).toEqual({ ok: true, args: ['-rabc'] })
+ })
+})
+
+describe('Codex config overrides', () => {
+ const keys = ['model', 'model_provider', 'profile', 'sandbox_mode', 'approval_policy', 'developer_instructions', 'mcp_servers', 'mcp_servers.x.command', 'model_providers', 'model_providers.y.base_url']
+
+ it('refuses a key Harness sets, as `k=v`, with the value as the next word, and attached', () => {
+ for (const key of keys) {
+ const detail = `-c ${key} is set by Harness and can't be added here.`
+ for (const text of [`-c ${key}=x`, `--config ${key}=x`, `--config=${key}=x`, `-c${key}=x`, `-c=${key}=x`, `-c "${key}=x"`, `--search -c ${key}="a b"`]) {
+ expect(parseLaunchArgs('codex', text), text).toEqual({ ok: false, detail })
+ }
+ }
+ })
+
+ it('allows every other key, and the same key for Claude, where -c is another flag', () => {
+ for (const text of ['-c model_reasoning_effort=high', '--config=tools.web_search=true', '-cshell_environment_policy.inherit=all', '-c models=x', '-c modelx=1']) {
+ expect(parseLaunchArgs('codex', text).ok, text).toBe(true)
+ }
+ // A trailing -c has no value to check; the engine itself refuses it at startup.
+ expect(parseLaunchArgs('codex', '-c').ok).toBe(true)
+ expect(parseLaunchArgs('claude', '--config model=x')).toEqual({ ok: true, args: ['--config', 'model=x'] })
+ })
+})
+
+describe('checkLaunchWords', () => {
+ it('accepts words the parser accepts and refuses the ones it refuses, with the same detail', () => {
+ expect(checkLaunchWords('claude', ['--chrome', 'a b'])).toEqual({ ok: true })
+ expect(checkLaunchWords('claude', [])).toEqual({ ok: true })
+ expect(checkLaunchWords('claude', ['--settings', 'x'])).toEqual(refusal('--settings'))
+ expect(checkLaunchWords('codex', ['-c', 'model=x'])).toEqual({ ok: false, detail: `-c model is set by Harness and can't be added here.` })
+ expect(checkLaunchWords('codex', ['resume'])).toEqual(refusal('resume'))
+ expect(checkLaunchWords('claude', ['a', '--', 'b']).ok).toBe(false)
+ })
+
+ it('refuses a hand-edited row the parser could never have produced', () => {
+ expect(checkLaunchWords('claude', Array.from({ length: LAUNCH_ARGS_MAX_WORDS + 1 }, () => 'a')).ok).toBe(false)
+ expect(checkLaunchWords('claude', ['a\nb']).ok).toBe(false)
+ expect(checkLaunchWords('claude', ['a\0b']).ok).toBe(false)
+ })
+})
diff --git a/cli/src/lib/launchArgs.ts b/cli/src/lib/launchArgs.ts
new file mode 100644
index 000000000..27a6dfa9b
--- /dev/null
+++ b/cli/src/lib/launchArgs.ts
@@ -0,0 +1,113 @@
+import type { AgentEngine } from '../engines/types.js'
+
+/** Extra launch flags an owner adds to a Buddy: parsed into argv words and checked, never run through a shell. */
+
+export const LAUNCH_ARGS_MAX_CHARS = 1024
+export const LAUNCH_ARGS_MAX_WORDS = 20
+
+export type LaunchArgsResult = { ok: true; args: string[] } | { ok: false; detail: string }
+
+// Flags Harness sets itself for an engine: the session, the model, the permission mode and the instructions. The same
+// short flag means different things per engine (`-c` is Claude Code's --continue but Codex's config override, which an
+// owner may want), so the sets are per engine.
+const CLAUDE_REFUSED = new Set([
+ '--resume', '-r', '--continue', '-c', '--model', '--permission-mode', '--dangerously-skip-permissions', '--session-id',
+ '--settings', '--setting-sources', '--append-system-prompt', '--append-system-prompt-file', '--system-prompt', '--system-prompt-file',
+ '--mcp-config', '--fork-session', '--effort',
+])
+const CODEX_REFUSED = new Set([
+ '--model', '-m', '--dangerously-bypass-approvals-and-sandbox', '--yolo', '--full-auto', '--ask-for-approval', '-a', '--sandbox', '-s', '--profile', '-p',
+])
+
+// Codex's `-c k=v` overrides its config for one run, and the keys below are what Harness sets itself: the model, the
+// provider, the sandbox and approvals, the instructions and the MCP servers. Every other key stays the owner's.
+const CODEX_REFUSED_KEYS = new Set(['model', 'model_provider', 'profile', 'sandbox_mode', 'approval_policy', 'developer_instructions'])
+const CODEX_REFUSED_KEY_PREFIXES = ['mcp_servers', 'model_providers']
+
+/** The refused key a Codex `-c` override names, or null. `override` is the `k=v` part. */
+function refusedCodexKey(override: string): string | null {
+ const key = override.split('=')[0]!.trim()
+ return CODEX_REFUSED_KEYS.has(key) || CODEX_REFUSED_KEY_PREFIXES.some((prefix) => key.startsWith(prefix)) ? key : null
+}
+
+/** POSIX word splitting without expansion: whitespace separates words, single quotes are literal, double quotes allow
+ * `\"` and `\\`, and a backslash outside quotes escapes the next character. Null when a quote or escape is left open. */
+function splitWords(text: string): string[] | null {
+ const words: string[] = []
+ let word = ''
+ let started = false
+ let quote: '"' | "'" | null = null
+ for (let i = 0; i < text.length; i++) {
+ const c = text[i]!
+ if (quote === "'") {
+ if (c === "'") quote = null
+ else word += c
+ } else if (quote === '"') {
+ if (c === '"') quote = null
+ else if (c === '\\' && (text[i + 1] === '"' || text[i + 1] === '\\')) word += text[++i]
+ else word += c
+ } else if (c === "'" || c === '"') {
+ quote = c
+ started = true
+ } else if (c === '\\') {
+ if (i + 1 >= text.length) return null
+ word += text[++i]
+ started = true
+ } else if (/\s/.test(c)) {
+ if (started) words.push(word)
+ word = ''
+ started = false
+ } else {
+ word += c
+ started = true
+ }
+ }
+ if (quote) return null
+ if (started) words.push(word)
+ return words
+}
+
+export function parseLaunchArgs(engine: AgentEngine, text: string): LaunchArgsResult {
+ if (text.length > LAUNCH_ARGS_MAX_CHARS) return { ok: false, detail: `Launch flags can be at most ${LAUNCH_ARGS_MAX_CHARS} characters.` }
+ if (/[\0\n\r]/.test(text)) return { ok: false, detail: 'Launch flags can’t contain a new line or a NUL character.' }
+ const args = splitWords(text)
+ if (!args) return { ok: false, detail: 'Launch flags have an unclosed quote or a trailing backslash.' }
+ const checked = checkLaunchWords(engine, args)
+ return checked.ok ? { ok: true, args } : checked
+}
+
+/**
+ * The rules every saved word list must meet, checked again where the words are applied: a row edited by hand, or a flag
+ * a later release refuses, must not reach an engine because it was fine when saved. `parseLaunchArgs` runs the same
+ * rules on what an owner just typed, so the two cannot drift.
+ */
+export function checkLaunchWords(engine: AgentEngine, args: readonly string[]): { ok: true } | { ok: false; detail: string } {
+ if (args.length > LAUNCH_ARGS_MAX_WORDS) return { ok: false, detail: `Launch flags can be at most ${LAUNCH_ARGS_MAX_WORDS} words.` }
+ if (args.some((word) => /[\0\n\r]/.test(word))) return { ok: false, detail: 'Launch flags can’t contain a new line or a NUL character.' }
+ if (args.includes('--')) return { ok: false, detail: `-- is set by Harness and can't be added here.` }
+ const refused = engine === 'claude' ? CLAUDE_REFUSED : engine === 'codex' ? CODEX_REFUSED : null
+ if (refused) {
+ // Checked after unquoting, so `"--model"` is the flag it spells.
+ for (const [index, word] of args.entries()) {
+ const flag = word.split('=')[0]!
+ if (refused.has(flag)) return { ok: false, detail: `${flag} is set by Harness and can't be added here.` }
+ // `-r<id>` is `-r <id>` to these CLIs: a single-dash word whose first letter is a refused short flag.
+ if (/^-[^-]/.test(word) && refused.has(word.slice(0, 2))) return { ok: false, detail: `${word.slice(0, 2)} is set by Harness and can't be added here.` }
+ if (engine === 'codex') {
+ // `-c k=v`, `--config k=v`, `--config=k=v`, and `-ck=v` (or `-c=k=v`): the override is the next word, or what follows the flag.
+ const override = word === '-c' || word === '--config' ? args[index + 1]
+ : word.startsWith('--config=') ? word.slice('--config='.length)
+ : /^-c[^-]/.test(word) ? word.slice(2).replace(/^=/, '') : undefined
+ const key = override === undefined ? null : refusedCodexKey(override)
+ if (key) return { ok: false, detail: `-c ${key} is set by Harness and can't be added here.` }
+ }
+ }
+ }
+ // Codex's `resume` and `fork` are subcommands, and Codex reads them after other flags too, so anywhere they would turn
+ // the launch into another one.
+ if (engine === 'codex') {
+ const sub = args.find((word) => word === 'resume' || word === 'fork')
+ if (sub) return { ok: false, detail: `${sub} is set by Harness and can't be added here.` }
+ }
+ return { ok: true }
+}
diff --git a/cli/src/lib/launchOverrides.spec.ts b/cli/src/lib/launchOverrides.spec.ts
index 4db736e67..15b0ee168 100644
--- a/cli/src/lib/launchOverrides.spec.ts
+++ b/cli/src/lib/launchOverrides.spec.ts
@@ -477,6 +477,30 @@ describe('buildLaunchOverrides — machine MCP servers (#1872)', () => {
expect(JSON.stringify(buddy)).toContain('lamp-mcp')
})
+ it('hands the owner\'s saved launch flags over in a slot of their own, leaving the other arguments exactly as they were', async () => {
+ const cwd = mkdtempSync(join(tmpdir(), 'overrides-buddy-'))
+ const source = { startedBy: null, cwd, swarmSkill: { role: 'buddy' as const, key: 'harness-claude-buddy' } }
+ const plain = await buildLaunchOverrides(deps({ readAttribution: () => null }).d, 'claude', source, 'a', () => true)
+ const flagged = await buildLaunchOverrides(deps({ readAttribution: () => null }).d, 'claude', { ...source, launchArgs: ['--chrome'] }, 'a', () => true)
+ if (!plain.ok || !flagged.ok) throw new Error('Fixture launch failed')
+ expect(flagged.overrides.ownerArgs).toEqual(['--chrome'])
+ expect(flagged.overrides.extraArgs).toEqual(plain.overrides.extraArgs)
+ expect(plain.overrides.ownerArgs ?? []).toEqual([])
+ })
+
+ // Each launch checks the saved words again (a row edited by hand, or a flag a later release refuses): none is applied.
+ it('applies none of the saved launch flags when one is now refused, and says so once with the agent and why', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
+ const built = await buildLaunchOverrides(deps({ readAttribution: () => null }).d, 'claude',
+ { startedBy: null, cwd: null, launchArgs: ['--chrome', '--settings', 'x'] }, 'agent-12345678-rest', () => true)
+ if (!built.ok) throw new Error('Fixture launch failed')
+ expect(built.overrides.ownerArgs ?? []).toEqual([])
+ expect(built.overrides.extraArgs).not.toContain('--chrome')
+ expect(warn).toHaveBeenCalledOnce()
+ expect(warn.mock.calls[0]![0]).toContain('agent-12')
+ expect(warn.mock.calls[0]![0]).toContain('--settings is set by Harness')
+ })
+
// A Buddy moved onto a grid model keeps the grid's web tools, as its owner's own session would, and everything that makes it a
// Buddy (task #2832; before it, #2354 dropped them).
it('a Buddy moved onto a grid keeps its web MCP and its Buddy launch', async () => {
diff --git a/cli/src/lib/launchOverrides.ts b/cli/src/lib/launchOverrides.ts
index b242e4c51..f78ffea5b 100644
--- a/cli/src/lib/launchOverrides.ts
+++ b/cli/src/lib/launchOverrides.ts
@@ -39,6 +39,7 @@ import { scmLaunchEnv } from '../scm/scmProjects.js'
import type { ScmLaunchRecord } from '../scm/types.js'
import { agentLaunchArgs, joinedInstructions, type StartedBy } from './agentAttribution.js'
import { machineMcpLaunchArgs } from './machineMcp.js'
+import { checkLaunchWords } from './launchArgs.js'
import type { CreationAuthority } from './agentCreationReceipt.js'
import type { publishGridConfigDir } from './publishedGridConfig.js'
import { nativeHookLocations } from '../engines/kit/nativeLocations.js'
@@ -49,6 +50,9 @@ export interface LaunchOverrides {
env: Record<string, string>
/** Appended to the engine's argv (`-c model_providers…`, `-m …`, `--mcp-config …`). */
extraArgs: string[]
+ /** The owner's own launch words, checked at this launch: they go LAST on the command line (`ownerArgs` of
+ * engineLaunch.ts), not into `extraArgs`. Absent when there are none, or when one is now refused. */
+ ownerArgs?: string[]
/** Vendor credentials the launch must hide from the engine — see `gridConflictingEnvToClear`. */
clearEnv: string[]
/**
@@ -167,6 +171,9 @@ export interface LaunchSource extends NativeLaunchSource {
agent?: string | null
/** `agent` when another agent started it (the row's `startedBy`): every relaunch keeps its pull request line. */
startedBy?: StartedBy | null
+ /** The owner's extra launch words (the registry row's `launchArgs`). Checked again at each launch (`checkLaunchWords`):
+ * a row edited by hand, or a flag a later release refuses, applies none. */
+ launchArgs?: string[]
}
/** Fresh each time: callers hand `env` to tmux and may extend it, and a shared object would carry
@@ -319,6 +326,14 @@ export async function prepareLaunchOverrides(
if (machineMcp.length) overrides = { ...overrides, extraArgs: [...overrides.extraArgs, ...machineMcp] }
// What the Swarm adds for its own sessions (core/api.ts `SwarmLaunch.args`), in the slot `agent_create` gave it.
if (source.swarmSkill) overrides = { ...overrides, extraArgs: [...overrides.extraArgs, ...swarm!.args(engine)] }
+ // The owner's own flags (`agent_restart`'s `launchArgs`) are the owner's, so they come last on the command line, in a
+ // slot of their own (`ownerArgs`). Checked again here, as they were when typed: a row edited by hand, or a flag a
+ // later release refuses, applies none, and the log says why.
+ if (source.launchArgs?.length) {
+ const checked = checkLaunchWords(engine, source.launchArgs)
+ if (checked.ok) overrides = { ...overrides, ownerArgs: [...source.launchArgs] }
+ else console.warn(`[launch] ${configKey.slice(0, 8)} saved launch flags not applied · ${checked.detail}`)
+ }
// What Harness tells the agent rides every relaunch, in the slot `agent_create` gave it: last. Read again each
// time, with the person's switches and settings as they are now.
let swarmInstructions: string | undefined
diff --git a/cli/src/lib/productUsageSignals.ts b/cli/src/lib/productUsageSignals.ts
index 553a746dc..da4d56d5b 100644
--- a/cli/src/lib/productUsageSignals.ts
+++ b/cli/src/lib/productUsageSignals.ts
@@ -21,7 +21,7 @@ const unavailable = new Set(['SERVICE_UNAVAILABLE', 'SERVICE_FAILED', 'GRID_UNAV
// A history page read for no session, or one this computer's index does not hold (services/search.ts): until
// 2026-10-28 both were `other`, 2,225 that day, a Desktop list re-reading a conversation that had left the index.
const invalid = new Set(['INVALID_ENGINE', 'INVALID_CWD', 'CWD_NOT_FOUND', 'INVALID_GRID', 'INVALID_DSH', 'INVALID_SWARM_ROLE',
- 'INVALID_MODEL', 'INVALID_PERMISSION_MODE', 'INVALID_CREATION_ID', 'INVALID_PROJECT_SOURCE', 'WORKTREE_BUSY',
+ 'INVALID_MODEL', 'INVALID_PERMISSION_MODE', 'INVALID_LAUNCH_ARGS', 'INVALID_CREATION_ID', 'INVALID_PROJECT_SOURCE', 'WORKTREE_BUSY',
'BAD_SESSION', 'NOT_INDEXED'])
/** A Store install's or update's own refusals (dsh/install.ts, dsh/update.ts), by kind. Until 2026-10-28 every one was
* `other`: that day's 11 failed installs, all on Windows, said nothing of why. For the Store's requests only, so a
diff --git a/cli/src/lib/registry.spec.ts b/cli/src/lib/registry.spec.ts
index 945d24e4e..e30c36776 100644
--- a/cli/src/lib/registry.spec.ts
+++ b/cli/src/lib/registry.spec.ts
@@ -1941,6 +1941,43 @@ describe('registry across a reboot and pane loss', () => {
expect(plain.launchModel).toBeUndefined()
})
+ it('keeps an agent\'s launch flags across a reload, a hook bind and a stopped row, and drops an empty or malformed list', async () => {
+ const { registry, strictPersistedRow } = await loadRegistryModule()
+ registry.load()
+ const pending = registry.openPendingAgent({ engine: 'claude', runtimes: [{ backend: 'tmux', paneId: '%41' }], cwd: '/tmp/demo' })!
+ expect(registry.setLaunchArgs('nobody', ['--chrome'])).toBe(false)
+ expect(registry.setLaunchArgs(pending.agentId, ['--chrome'])).toBe(true)
+ const { registry: reloaded, strictPersistedRow: strict } = await loadRegistryModule()
+ reloaded.load()
+ expect(reloaded.byAgent(pending.agentId)?.launchArgs).toEqual(['--chrome'])
+ // A hook bind rebuilds the row from named fields; the flags must survive it.
+ const transcriptPath = join(dataDir, 'session-args.jsonl')
+ writeFileSync(transcriptPath, '{}\n')
+ const bound = reloaded.register({ sessionId: 'session-args', transcriptPath, tmuxPane: '%41', cwd: '/tmp/demo' })
+ expect(bound?.entry.launchArgs).toEqual(['--chrome'])
+ // A stopped row goes through the normaliser on its way back from disk.
+ const row = JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf8')).find((r: { agentId: string }) => r.agentId === pending.agentId)
+ expect(strict(row)?.launchArgs).toEqual(['--chrome'])
+ expect(strict({ ...row, launchArgs: [1, '--x'] })).not.toHaveProperty('launchArgs')
+ expect(strict({ ...row, launchArgs: 'x' })).not.toHaveProperty('launchArgs')
+ expect(strict({ ...row, launchArgs: [] })).not.toHaveProperty('launchArgs')
+ // Empty clears the field rather than writing an empty array.
+ expect(reloaded.setLaunchArgs(pending.agentId, [])).toBe(true)
+ expect('launchArgs' in reloaded.byAgent(pending.agentId)!).toBe(false)
+ // A hand-edited record on disk loads without the field.
+ const file = join(dataDir, 'registry.json')
+ const rows = JSON.parse(readFileSync(file, 'utf8')) as Array<Record<string, unknown>>
+ writeFileSync(file, JSON.stringify(rows.map(r => ({ ...r, launchArgs: [1, '--x'] }))), { mode: 0o600 })
+ const { registry: hand } = await loadRegistryModule()
+ hand.load()
+ expect(hand.byAgent(pending.agentId)).not.toHaveProperty('launchArgs')
+ writeFileSync(file, JSON.stringify(rows.map(r => ({ ...r, launchArgs: 'x' }))), { mode: 0o600 })
+ const { registry: hand2 } = await loadRegistryModule()
+ hand2.load()
+ expect(hand2.byAgent(pending.agentId)).not.toHaveProperty('launchArgs')
+ void registry; void strictPersistedRow
+ })
+
// The conversation a fresh move onto a grid left (core/agents/retarget.ts): the way home reopens it.
it('keeps the remembered subscription session across a reload and the binds on the grid', async () => {
const { registry } = await loadRegistryModule()
diff --git a/cli/src/lib/registry.ts b/cli/src/lib/registry.ts
index 696fdf7cb..b759d4c0d 100644
--- a/cli/src/lib/registry.ts
+++ b/cli/src/lib/registry.ts
@@ -183,6 +183,12 @@ export interface RegisteredSession {
* 11-05). Absent for a session launched with none.
*/
launchModel?: LaunchModel
+ /**
+ * Extra command-line words an owner asked for on this agent (`agent_restart`'s `launchArgs`, lib/launchArgs.ts),
+ * appended to every relaunch so they hold across a restart, a reboot and a daemon update until cleared. Never an
+ * empty array: clearing deletes the field. Absent for an agent with none.
+ */
+ launchArgs?: string[]
/**
* The conversation this agent was in on its own login when a fresh move took it onto a grid
* (`agent_retarget` with `fresh`: a conversation too long for the grid model's window). The way
@@ -686,7 +692,7 @@ export function strictPersistedRow(raw: unknown): RegisteredSession | null {
// Taken out of the spread and put back only when it is a real moment: the spread would otherwise
// carry a hand-edited string or a negative number straight into the frame's `toISOString()`.
// `forkedFrom` is out too, so an invalid one is dropped rather than spread back in as-is.
- const { identityHold: _identityHold, evidenceRevision: _revision, interpretationHold: _interpretation, admissionHold: _admission, lastOpenedAt: rawOpenedAt, closePlan: rawClosePlan, forkedFrom: rawForkedFrom, scmLaunch: rawScmLaunch, launchModel: rawLaunchModel, externalResume: _externalResume, startedBy: rawStartedBy, parentAgentId: rawParentAgentId, swarmSkill: rawSwarmSkill, ...rest } = row
+ const { identityHold: _identityHold, evidenceRevision: _revision, interpretationHold: _interpretation, admissionHold: _admission, lastOpenedAt: rawOpenedAt, closePlan: rawClosePlan, forkedFrom: rawForkedFrom, scmLaunch: rawScmLaunch, launchModel: rawLaunchModel, externalResume: _externalResume, startedBy: rawStartedBy, parentAgentId: rawParentAgentId, swarmSkill: rawSwarmSkill, launchArgs: rawLaunchArgs, ...rest } = row
const lastOpenedAt = normalizedOpenedAt(rawOpenedAt)
// Out of the spread for the same reason: a half-formed record is dropped, never relaunched with.
const scmLaunch = parseScmLaunchRecord(rawScmLaunch)
@@ -694,12 +700,14 @@ export function strictPersistedRow(raw: unknown): RegisteredSession | null {
// Read as load() reads it: a stopped harness an older CLI saved names its Swarm role in the wire's values (lead, dev,
// review), and is kept as this release keeps it (project instructions, phase 4).
const swarmSkill = parseSwarmSkill(rawSwarmSkill)
+ const launchArgs = storedLaunchArgs(rawLaunchArgs)
return {
...rest,
...(externalResume ? { externalResume } : {}),
...(scmLaunch ? { scmLaunch } : {}),
...(launchModel ? { launchModel } : {}),
...(swarmSkill ? { swarmSkill } : {}),
+ ...(launchArgs ? { launchArgs } : {}),
...(normalizedClosePlan(rawClosePlan) ? { closePlan: normalizedClosePlan(rawClosePlan)! } : {}),
schemaVersion: 2,
active,
@@ -742,6 +750,11 @@ export function parentAgentIdOf(value: unknown): string | null {
return typeof value === 'string' && /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(value) ? value : null
}
+/** Only a non-empty array of strings is a saved flag list; anything else on disk is dropped, never launched with. */
+function storedLaunchArgs(value: unknown): string[] | undefined {
+ return Array.isArray(value) && value.length > 0 && value.every(w => typeof w === 'string') ? [...value] : undefined
+}
+
/** `parentAgentId` as a row keeps it: only beside `startedBy: 'agent'`, and only an agent id. */
function normalizedParent(startedBy: unknown, value: unknown): { parentAgentId: string } | Record<string, never> {
const parentAgentId = startedBy === 'agent' ? parentAgentIdOf(value) : null
@@ -1384,6 +1397,7 @@ class Registry {
...(rawGridLaunch !== undefined ? { gridLaunch: rawGridLaunch } : {}),
...(rawGridLaunch ? { gridWebSearch: normalizedGridWebSearch(raw?.gridWebSearch) } : {}),
...(rawScmLaunch ? { scmLaunch: rawScmLaunch } : {}),
+ ...(storedLaunchArgs(raw.launchArgs) ? { launchArgs: storedLaunchArgs(raw.launchArgs) } : {}),
...(storedLaunchModel((raw as { launchModel?: unknown }).launchModel) ? { launchModel: storedLaunchModel((raw as { launchModel?: unknown }).launchModel) } : {}),
// ⚠️ Rehydrated EXPLICITLY, like every field above it. A row is rebuilt from this list on
// load, so a field added to the type and the setter but not to this list is written to
@@ -2079,6 +2093,8 @@ class Registry {
// And the model it launches with, for the same reason: a hook bind that forgot it reopened a Product Manager on its
// engine's own default (task #3395).
...(existing?.launchModel ? { launchModel: existing.launchModel } : {}),
+ // And the owner's extra launch flags: a hook bind that forgot them would drop them at the first relaunch.
+ ...(existing?.launchArgs ? { launchArgs: existing.launchArgs } : {}),
// And for the conversation a fresh move left: the grid's first hook would otherwise forget the way home.
...(existing?.subscriptionSessionId ? { subscriptionSessionId: existing.subscriptionSessionId } : {}),
defaultName: existing?.defaultName,
@@ -2282,6 +2298,7 @@ class Registry {
entry.grid = null
entry.subscriptionModel = null
delete entry.launchModel
+ delete entry.launchArgs
entry.model = null
entry.title = null
entry.touchedAt = Date.now()
@@ -2598,6 +2615,17 @@ class Registry {
return true
}
+ /** Save the extra launch words [agentId] relaunches with (RegisteredSession.launchArgs); an empty list removes them. */
+ setLaunchArgs(agentId: string, args: string[]): boolean {
+ const session = this.agents.get(agentId)
+ if (!session) return false
+ if (args.length) session.launchArgs = [...args]
+ else delete session.launchArgs
+ session.touchedAt = Date.now()
+ this.save()
+ return true
+ }
+
/** Remember the conversation a fresh move onto a grid left on the own login, or forget it (null) once
* the agent is back in it. Kept while the agent is on a grid, across moves between grids. */
setSubscriptionSession(agentId: string, sessionId: string | null): boolean {
diff --git a/cli/src/lib/restartAgent.spec.ts b/cli/src/lib/restartAgent.spec.ts
index 143b1a2bc..bc674f962 100644
--- a/cli/src/lib/restartAgent.spec.ts
+++ b/cli/src/lib/restartAgent.spec.ts
@@ -311,6 +311,22 @@ describe('restart cancellation', () => {
expect(coordinator.revision('next observed')).toBe(before + 1)
})
+ // Asked with other launch words, a second restart would be answered by the first's launch and its words would be lost
+ // (or, saved beside it, differ from what launched): it is refused instead, and only the same words join.
+ it('joins an overlapping restart only when it asks for the same launch words, and refuses one that asks for others', async () => {
+ const coordinator = new AgentRestartCoordinator()
+ let finish!: () => void
+ const handler = vi.fn(async () => { await new Promise<void>((resolve) => { finish = resolve }); return { ok: false, error: 'fixture' } as const })
+ const first = coordinator.run('a', handler, 'restart', '["--chrome"]')
+ expect(coordinator.run('a', handler, 'restart', '["--chrome"]')).toBe(first)
+ expect(await coordinator.run('a', handler, 'restart', '["--other"]')).toMatchObject({ ok: false, error: 'AGENT_BUSY' })
+ expect(await coordinator.run('a', handler, 'restart')).toMatchObject({ ok: false, error: 'AGENT_BUSY' })
+ expect(coordinator.operation('a')).toBe('restart')
+ finish()
+ await first
+ expect(handler).toHaveBeenCalledTimes(1)
+ })
+
it('joins overlapping restarts but leaves other agents independent', async () => {
const coordinator = new AgentRestartCoordinator()
const initial = coordinator.revision('a')
diff --git a/cli/src/lib/restartAgent.ts b/cli/src/lib/restartAgent.ts
index cf675f458..72b5186ef 100644
--- a/cli/src/lib/restartAgent.ts
+++ b/cli/src/lib/restartAgent.ts
@@ -54,14 +54,17 @@ export class AgentRestartCoordinator {
}
forget(agentId: string): void { this.revisions.delete(agentId) }
operation(agentId: string): string | undefined { return this.jobs.get(agentId)?.operation }
- private readonly jobs = new Map<string, { operation: string; cancelled: boolean; result: Promise<RestartAgentReply> }>()
+ private readonly jobs = new Map<string, { operation: string; variant: string; cancelled: boolean; result: Promise<RestartAgentReply> }>()
- run(agentId: string, restart: (current: () => boolean) => Promise<RestartAgentReply>, operation = 'restart'): Promise<RestartAgentReply> {
+ /** [variant] tells apart two asks of the same operation that must not share one launch: the launch words a restart
+ * was given. Only the same variant joins a running one; any other is refused, never answered by a launch that did
+ * not carry its words. */
+ run(agentId: string, restart: (current: () => boolean) => Promise<RestartAgentReply>, operation = 'restart', variant = ''): Promise<RestartAgentReply> {
const existing = this.jobs.get(agentId)
- if (existing) return existing.operation === operation ? existing.result
+ if (existing) return existing.operation === operation && existing.variant === variant ? existing.result
: Promise.resolve({ ok: false, error: 'AGENT_BUSY', detail: 'Another lifecycle operation is changing this harness.' })
if (this.revisions.has(agentId)) this.revisions.set(agentId, ++this.sequence)
- const job = { operation, cancelled: false, result: null! as Promise<RestartAgentReply> }
+ const job = { operation, variant, cancelled: false, result: null! as Promise<RestartAgentReply> }
const current = () => !job.cancelled && this.jobs.get(agentId) === job
job.result = Promise.resolve().then(async () => {
if (!current()) return { ok: false, error: 'AGENT_CHANGED' } as const
diff --git a/cli/src/lib/resumeAgentService.spec.ts b/cli/src/lib/resumeAgentService.spec.ts
index 0d008f3e4..99748a415 100644
--- a/cli/src/lib/resumeAgentService.spec.ts
+++ b/cli/src/lib/resumeAgentService.spec.ts
@@ -141,6 +141,79 @@ beforeEach(() => {
})
afterEach(() => { vi.useRealTimers(); for (const row of registry.list()) registry.removeAgent(row.agentId); rmSync(dir, { recursive: true, force: true }) })
+describe('resuming a stopped harness with new launch words', () => {
+ const WORDS = ['--chrome']
+ const resumeWith = (launchArgs?: string[], mode?: string) => createResumeAgentService(deps)(saved.agentId, mode, launchArgs)
+
+ it('builds the launch with them, applies them to the argv, and the resumed row keeps them', async () => {
+ rewrite({ launchArgs: ['--old'] })
+ vi.mocked(deps.relaunchOverrides).mockImplementation(async (_row, source) => ({ ok: true, overrides: { env: {}, extraArgs: [], clearEnv: [], ownerArgs: source.launchArgs } }))
+ expect(await resumeWith(WORDS)).toMatchObject({ ok: true, session: { launchArgs: WORDS } })
+ expect(deps.relaunchOverrides).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ agentId: saved.agentId, launchArgs: WORDS }), expect.any(Function))
+ expect(buildEngineLaunchArgv).toHaveBeenCalledWith('codex', expect.objectContaining({ ownerArgs: WORDS }))
+ expect(registry.byAgent(saved.agentId)?.launchArgs).toEqual(WORDS)
+ registry.load()
+ expect(registry.byAgent(saved.agentId)?.launchArgs).toEqual(WORDS)
+ })
+
+ it('clears them with an empty list', async () => {
+ rewrite({ launchArgs: ['--old'] })
+ expect(await resumeWith([])).toMatchObject({ ok: true })
+ expect(deps.relaunchOverrides).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ launchArgs: [] }), expect.any(Function))
+ expect(registry.byAgent(saved.agentId)?.launchArgs).toBeUndefined()
+ })
+
+ it('without them, relaunches from the saved row and leaves its words as they were', async () => {
+ rewrite({ launchArgs: ['--old'] })
+ expect(await resumeWith()).toMatchObject({ ok: true })
+ expect(deps.relaunchOverrides).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ launchArgs: ['--old'] }), expect.any(Function))
+ expect(registry.byAgent(saved.agentId)?.launchArgs).toEqual(['--old'])
+ })
+
+ // The new row exists as soon as the pane does, but the words are only the record's once the engine is confirmed.
+ it('saves nothing when the engine does not come back, and the retained row keeps the words that last worked', async () => {
+ rewrite({ launchArgs: ['--old'] })
+ live()
+ vi.mocked(resolvePaneEngineProcess).mockResolvedValue(null)
+ paneState.mockResolvedValueOnce({ dead: false, engineExit: 1 } as any).mockResolvedValueOnce('gone')
+ expect(await resumeWith(WORDS)).toMatchObject({ ok: false, error: 'RESUME_FAILED' })
+ expect(deps.stoppedAgents.get(saved.agentId)?.launchArgs).toEqual(['--old'])
+ })
+
+ it('saves nothing when the launch is refused before a pane exists', async () => {
+ rewrite({ launchArgs: ['--old'] })
+ vi.mocked(deps.relaunchOverrides).mockResolvedValue({ ok: false, error: 'GRID_UNAVAILABLE', detail: 'x' })
+ expect(await resumeWith(WORDS)).toMatchObject({ ok: false, error: 'GRID_UNAVAILABLE' })
+ expect(create).not.toHaveBeenCalled()
+ expect(deps.stoppedAgents.get(saved.agentId)?.launchArgs).toEqual(['--old'])
+ expect(registry.byAgent(saved.agentId)).toBeUndefined()
+ })
+
+ it('keeps the terminal engine\'s resume, which has no launch to confirm, saving them as well', async () => {
+ rewrite({ engine: 'terminal' })
+ expect(await resumeWith(WORDS)).toMatchObject({ ok: true })
+ expect(registry.byAgent(saved.agentId)?.launchArgs).toEqual(WORDS)
+ })
+
+ it('asked with other words, an overlapping resume is refused rather than answered by the first launch', async () => {
+ const stop = deferred<void>(); (deps.stopJobs as Map<string, Promise<void>>).set(saved.agentId, stop.promise)
+ const resume = createResumeAgentService(deps)
+ const first = resume(saved.agentId, undefined, WORDS)
+ expect(await resume(saved.agentId, undefined, ['--other'])).toMatchObject({ ok: false, error: 'AGENT_BUSY' })
+ stop.resolve()
+ expect(await first).toMatchObject({ ok: true })
+ expect(registry.byAgent(saved.agentId)?.launchArgs).toEqual(WORDS)
+ })
+
+ it('does not claim to have applied them to a harness that was already running', async () => {
+ live({ processIdentity: identity, lastHookAt: Date.now(), launch: { state: 'ready' } })
+ vi.mocked(checkPidRuntime).mockResolvedValue({ state: 'alive' })
+ expect(await resumeWith(WORDS)).toMatchObject({ ok: true })
+ expect(create).not.toHaveBeenCalled()
+ expect(registry.byAgent(saved.agentId)?.launchArgs).toBeUndefined()
+ })
+})
+
describe('production resume handler', () => {
it('holds the reservation and restores cold history before checking its control identity', async () => {
const restored = join(dir, 'restored.jsonl')
diff --git a/cli/src/lib/resumeAgentService.ts b/cli/src/lib/resumeAgentService.ts
index 77cb73fd9..2c67fd829 100644
--- a/cli/src/lib/resumeAgentService.ts
+++ b/cli/src/lib/resumeAgentService.ts
@@ -30,7 +30,7 @@ import { harnessPermissionEnvironment } from './harnessDefaults.js'
export interface ResumeAgentServiceDeps {
adoptSwarmSkill?: AdoptSwarmSkill
- registry: Pick<typeof liveRegistry, 'byAgent' | 'bySession' | 'resumePendingAgent' | 'setLaunch' | 'updateProcessIdentity'>
+ registry: Pick<typeof liveRegistry, 'byAgent' | 'bySession' | 'resumePendingAgent' | 'setLaunch' | 'setLaunchArgs' | 'updateProcessIdentity'>
stoppedAgents: StoppedAgentStore
/** Where a resumed harness's new pane is made (main.ts `createBackend`); null with no backend ready. */
createBackend: (CreateAgentPaneDeps['tmuxBackend'] & Pick<TerminalBackend, 'releaseHold'>) | null
@@ -182,7 +182,12 @@ export function createResumeAgentService(deps: ResumeAgentServiceDeps) {
return result
}
- const resumeStopped = (agentId: string, current: () => boolean, permissionMode?: string) => resumeStoppedAgent({
+ /** [launchArgs]: the owner's new launch words (an empty list clears them). They build this launch, and become the record's
+ * only once the engine is confirmed back, so a resume that fails anywhere keeps the words that last worked. */
+ const resumeStopped = (agentId: string, current: () => boolean, permissionMode?: string, launchArgs?: string[]) => {
+ // The registry's own row, so the reply and the frame carry the words too.
+ const keepLaunchArgs = (row: RegisteredSession) => { if (launchArgs) registry.setLaunchArgs(row.agentId, launchArgs) }
+ return resumeStoppedAgent({
live: () => registry.byAgent(agentId),
saved: () => stoppedAgents.get(agentId),
current,
@@ -275,7 +280,7 @@ export function createResumeAgentService(deps: ResumeAgentServiceDeps) {
try { transcript?.verify(); return true }
catch (error) { sourceError = error; return false }
}
- const built = await relaunchOverrides(saved, saved, sourceCurrent)
+ const built = await relaunchOverrides(saved, launchArgs ? { ...saved, launchArgs } : saved, sourceCurrent)
if (sourceError) throw sourceError
transcript?.verify()
if (!built.ok) return built
@@ -303,7 +308,7 @@ export function createResumeAgentService(deps: ResumeAgentServiceDeps) {
// A resume always starts a new engine: a turn left open before it is over.
if (offset !== null) relaunchMarks?.note(saved.sessionId, offset, true)
}
- const { extraArgs, clearEnv } = built.overrides
+ const { extraArgs, ownerArgs, clearEnv } = built.overrides
const launchEnv = permissionMode === undefined ? built.overrides.env
: harnessPermissionEnvironment(saved.engine, built.overrides.env, permissionMode)
// The engine may have been downgraded since this harness was paused. Nobody is waiting on
@@ -348,6 +353,7 @@ export function createResumeAgentService(deps: ResumeAgentServiceDeps) {
...(permission.permissionMode ? { permissionMode: permission.permissionMode } : {}),
cwd,
...(extraArgs.length ? { extraArgs } : {}),
+ ...(ownerArgs?.length ? { ownerArgs } : {}),
...(clearEnv.length ? { clearEnv } : {}),
...(launchEnv.HARNESS_DSH ? { harnessNode: true } : {}),
installIfMissing: enginePathOverride(saved.engine) ? undefined : engineInstallRecipe(saved.engine),
@@ -407,11 +413,14 @@ export function createResumeAgentService(deps: ResumeAgentServiceDeps) {
if (!current()) return resumeChanged
const ready = registry.setLaunch(pending.agentId, { state: 'ready' })!
stoppedAgents.finishResume(agentId, token)
+ keepLaunchArgs(ready)
announceSession(ready)
return { ok: true, session: ready, resumed: true }
}
if (pending.dsh) attachDsh(pending)
- return await waitForResume(pending, current)
+ const waited = await waitForResume(pending, current)
+ if (waited.ok) keepLaunchArgs(waited.session)
+ return waited
} catch (error) {
if (error instanceof IdentityReadUnavailable) return { ok: false,
error: allocationAttempted ? 'RESUME_UNCONFIRMED' : error.code, detail: error.message }
@@ -422,18 +431,19 @@ export function createResumeAgentService(deps: ResumeAgentServiceDeps) {
}
},
})
+ }
- return (agentId: string, permissionMode?: string) => restartJobs.run(agentId, async current => {
+ return (agentId: string, permissionMode?: string, launchArgs?: string[]) => restartJobs.run(agentId, async current => {
await stopJobs.get(agentId)
if (!current()) return resumeChanged
if (pinnedControls.has(agentId)) return { ok: false, error: 'AGENT_BUSY' }
- const result = await resumeStopped(agentId, current, permissionMode)
+ const result = await resumeStopped(agentId, current, permissionMode, launchArgs)
// Open may attach to an already running session. It must never claim to have changed that
// process's permissions, including when another client started it during this request.
if (result.ok && permissionMode !== undefined && result.session.permissionMode !== permissionMode) {
return { ok: false, error: 'PERMISSION_CHANGE_REQUIRES_STOP', detail: 'Stop this harness before changing its permission mode.' }
}
return result
- }, permissionMode === undefined ? 'resume' : `resume:${permissionMode}`)
+ }, permissionMode === undefined ? 'resume' : `resume:${permissionMode}`, launchArgs && JSON.stringify(launchArgs))
}
diff --git a/cli/src/testing/socketCore.ts b/cli/src/testing/socketCore.ts
index 818da45a3..2f18169ef 100644
--- a/cli/src/testing/socketCore.ts
+++ b/cli/src/testing/socketCore.ts
@@ -147,7 +147,7 @@ export function bindLaunchRequests(socket: BackendSocket, over: Partial<Launcher
receipts: new AgentCreationReceipts(join(env.ADAPTER_DATA_DIR, 'agent-creations')),
createAgent: () => socket.onCreateAgent, forkAgent: () => socket.onForkAgent,
resumeAgent: () => state.resume, restartAgent: () => state.restart,
- byAgent: (id) => registry.byAgent(id), toProject: (s) => socket.toProject(s),
+ byAgent: (id) => registry.byAgent(id), stoppedAgent: (id) => stoppedAgents.get(id) ?? undefined, toProject: (s) => socket.toProject(s),
modelTarget: (selection) => (state.modelTarget ?? MODELS_OFF.launchTarget)(selection),
})
socket.createProvider = launches.create
diff --git a/desktop/lib/core/models.dart b/desktop/lib/core/models.dart
index af6821654..d06490e96 100644
--- a/desktop/lib/core/models.dart
+++ b/desktop/lib/core/models.dart
@@ -572,6 +572,10 @@ class Agent {
/// agent that runs on a computer (docs/design/2026-10-11-cloud-agents.md).
final AgentCloud? cloud;
+ /// Extra launch flags saved on the machine for this agent (a Buddy's `--chrome`), as words.
+ /// Empty from an older daemon or an agent with none.
+ final List<String> launchArgs;
+
bool get isCloud => cloud != null;
const Agent({
@@ -626,6 +630,7 @@ class Agent {
this.bypassPermission,
this.namedAgent,
this.cloud,
+ this.launchArgs = const [],
});
bool get isStopped => status == 'stopped';
@@ -819,6 +824,9 @@ class Agent {
: null,
namedAgent: _safeNamedAgent(j['namedAgent']),
cloud: j['location'] == 'cloud' ? AgentCloud.fromJson(j['cloud']) : null,
+ launchArgs: j['launchArgs'] is List
+ ? [for (final w in j['launchArgs'] as List) if (w is String) w]
+ : const [],
);
}
@@ -881,6 +889,7 @@ class Agent {
bypassPermission: bypassPermission,
namedAgent: namedAgent,
cloud: cloud,
+ launchArgs: launchArgs,
);
/// A mode id as `PERMISSION_MODES` spells them (`acceptEdits`, `readOnly`):
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index ce8edc288..ae22d2069 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -198,10 +198,24 @@ class RestartAgentResult {
final bool resumed;
final bool retryable;
+ /// The daemon restarted without the requested launch flags and said nothing of them: it is older
+ /// than the field. Never set by a status check, which does not echo them.
+ final bool launchArgsIgnored;
+
+ /// The daemon refused the requested launch flags (`INVALID_LAUNCH_ARGS`); [error] is its detail.
+ final bool launchArgsRefused;
+
+ /// The daemon answered but the engine did not come back (`unconfirmed`, `RESTART_FAILED` or
+ /// `RESUME_UNCONFIRMED`). With launch flags in the request, the likeliest cause is the flags.
+ final bool engineNotStarted;
+
const RestartAgentResult({
this.error,
this.resumed = true,
this.retryable = true,
+ this.launchArgsIgnored = false,
+ this.launchArgsRefused = false,
+ this.engineNotStarted = false,
});
}
@@ -18081,9 +18095,16 @@ class AppNotifier extends ChangeNotifier {
(!beforeSend || current.sessionId == agent.sessionId);
}
- AgentRestartAttempt restartAttempt(String machineId, String agentId) {
+ /// [fresh] starts a new intent with its own receipt, even while an earlier attempt is pending or
+ /// awaiting confirmation; the earlier one keeps running on its own object.
+ AgentRestartAttempt restartAttempt(
+ String machineId,
+ String agentId, {
+ bool fresh = false,
+ }) {
final previous = _agentRestarts[(machineId, agentId)];
- if (previous != null &&
+ if (!fresh &&
+ previous != null &&
_restartCurrent(
previous,
beforeSend: !previous.busy && !previous.awaitingConfirmation,
@@ -18210,6 +18231,7 @@ class AppNotifier extends ChangeNotifier {
String machineId,
String agentId, {
AgentRestartAttempt? attempt,
+ String? launchArgs,
}) {
final operation = attempt ?? restartAttempt(machineId, agentId);
if (operation.result case final result? when result.error == null) {
@@ -18217,7 +18239,7 @@ class AppNotifier extends ChangeNotifier {
}
if (operation.pending case final pending?) return pending;
late final Future<RestartAgentResult> request;
- request = _runAgentRestart(machineId, agentId, operation)
+ request = _runAgentRestart(machineId, agentId, operation, launchArgs)
.then((result) {
operation.result = result;
return result;
@@ -18234,6 +18256,7 @@ class AppNotifier extends ChangeNotifier {
String machineId,
String agentId,
AgentRestartAttempt attempt,
+ String? launchArgs,
) async {
final machine = attempt._machine;
if (machine == null) {
@@ -18313,6 +18336,7 @@ class AppNotifier extends ChangeNotifier {
ProductFlow.resumeRecovery,
);
}
+ final sendsLaunchArgs = launchArgs != null && !checking;
RestartAgentResult refused(String code, Object? detail) {
attempt._awaitingConfirmation = false;
if (resuming && code == 'AGENT_BUSY') {
@@ -18328,6 +18352,7 @@ class AppNotifier extends ChangeNotifier {
_measurementResumes.remove(measurementKey)?.call(ProductOutcome.failed);
return RestartAgentResult(
error: _restartFailure(code, detail, resuming: resuming),
+ launchArgsRefused: code == 'INVALID_LAUNCH_ARGS',
);
}
@@ -18336,6 +18361,10 @@ class AppNotifier extends ChangeNotifier {
? 'Still waiting for the Open response. Select the harness again to check status.'
: 'The restart is not confirmed yet. Check status, or close this prompt to inspect the terminal before restarting again.',
);
+ final notStarted = RestartAgentResult(
+ error: unknown.error,
+ engineNotStarted: true,
+ );
Map<String, dynamic> result;
try {
result = await _conn(machineId).request(
@@ -18344,7 +18373,11 @@ class AppNotifier extends ChangeNotifier {
: resuming
? 'agent_resume'
: 'agent_restart',
- payload: {'creationId': attempt._id, if (!checking) 'agentId': agentId},
+ payload: {
+ 'creationId': attempt._id,
+ if (!checking) 'agentId': agentId,
+ if (sendsLaunchArgs) 'launchArgs': launchArgs,
+ },
);
if (checking &&
resuming &&
@@ -18359,7 +18392,11 @@ class AppNotifier extends ChangeNotifier {
checking = false;
result = await _conn(machineId).request(
'agent_resume',
- payload: {'creationId': attempt._id, 'agentId': agentId},
+ payload: {
+ 'creationId': attempt._id,
+ 'agentId': agentId,
+ 'launchArgs': ?launchArgs,
+ },
);
}
} on WsRequestFailure catch (failure) {
@@ -18388,12 +18425,10 @@ class AppNotifier extends ChangeNotifier {
return unknown;
}
if (result['error'] case final String code) {
- if (checking ||
- [
- 'INTERNAL',
- 'CREATION_STORAGE_FAILED',
- 'RESTART_FAILED',
- ].contains(code)) {
+ if (code == 'RESTART_FAILED' || code == 'RESUME_UNCONFIRMED') {
+ return notStarted;
+ }
+ if (checking || ['INTERNAL', 'CREATION_STORAGE_FAILED'].contains(code)) {
return unknown;
}
return refused(code, result['detail']);
@@ -18406,8 +18441,9 @@ class AppNotifier extends ChangeNotifier {
: 'The machine is still restarting the harness. Check again in a moment.',
);
case 'missing':
- case 'unconfirmed':
return unknown;
+ case 'unconfirmed':
+ return notStarted;
case 'unavailable':
attempt._awaitingConfirmation = false;
return const RestartAgentResult(
@@ -18479,6 +18515,8 @@ class AppNotifier extends ChangeNotifier {
}
return RestartAgentResult(
resumed: result['resumed'] is bool ? result['resumed'] as bool : true,
+ // Only a fresh restart is echoed; a status check never carries the words.
+ launchArgsIgnored: sendsLaunchArgs && result['launchArgs'] == null,
);
}
diff --git a/desktop/lib/super_tabs/buddy_restart.dart b/desktop/lib/super_tabs/buddy_restart.dart
new file mode 100644
index 000000000..18e6511c5
--- /dev/null
+++ b/desktop/lib/super_tabs/buddy_restart.dart
@@ -0,0 +1,205 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+
+import '../core/models.dart' show Agent;
+import '../shared/theme/app_theme.dart' as grid;
+import '../shared/widgets/app_dialog.dart';
+import '../state/app_state.dart';
+import '../state/swarm_navigation.dart' show externalEngineName;
+import '../widgets/desktop_chrome.dart';
+import 'buddies.dart' show buddyMachineName;
+import 'controller.dart';
+import 'dialog_scope.dart';
+
+/// Restart the reader's Buddy in [projectId] with extra launch flags, which the
+/// machine keeps and applies on every later start of it (spec
+/// 2026-11-06-buddy-launch-flags). The restart goes to the Buddy's machine
+/// through [app]; the Buddy keeps its conversation.
+Future<void> showRestartBuddy(
+ BuildContext context,
+ SuperTabController c,
+ String projectId, {
+ AppNotifier? app,
+}) => showAppDialog<void>(
+ context: context,
+ builder: (context) {
+ final swarm = projectId == SuperTabController.kSwarmBuddyKey;
+ return SuperTabDialogScope(
+ controller: c,
+ projectId: swarm ? null : projectId,
+ conversationId: swarm ? c.buddyChat(projectId)?.id : null,
+ child: _RestartBuddyDialog(controller: c, projectId: projectId, app: app),
+ );
+ },
+);
+
+/// [words] as one line the daemon's parser reads back as the same words: a word
+/// with a space, quote or backslash is single-quoted.
+String launchArgsLine(Iterable<String> words) => words
+ .map(
+ (w) => w.isNotEmpty && !RegExp(r'''[\s'"\\]''').hasMatch(w)
+ ? w
+ : "'${w.replaceAll("'", r"'\''")}'",
+ )
+ .join(' ');
+
+class _RestartBuddyDialog extends StatefulWidget {
+ const _RestartBuddyDialog({
+ required this.controller,
+ required this.projectId,
+ required this.app,
+ });
+ final SuperTabController controller;
+ final String projectId;
+ final AppNotifier? app;
+
+ @override
+ State<_RestartBuddyDialog> createState() => _RestartBuddyDialogState();
+}
+
+class _RestartBuddyDialogState extends State<_RestartBuddyDialog> {
+ SuperTabController get c => widget.controller;
+ AppNotifier? get app => widget.app;
+
+ Agent? get _machineAgent {
+ final buddy = c.buddy(widget.projectId);
+ if (buddy == null) return null;
+ return app
+ ?.stateOf(buddy.machineId)
+ ?.agents
+ .where((a) => a.id == buddy.harnessId)
+ .firstOrNull;
+ }
+
+ late final _flags = TextEditingController(
+ text: launchArgsLine(_machineAgent?.launchArgs ?? const []),
+ );
+ late final String _saved = launchArgsLine(
+ _machineAgent?.launchArgs ?? const [],
+ );
+ bool _busy = false;
+ String? _error;
+
+ @override
+ void dispose() {
+ _flags.dispose();
+ super.dispose();
+ }
+
+ Future<void> _submit() async {
+ final buddy = c.buddy(widget.projectId);
+ final app = this.app;
+ if (_busy) return;
+ if (buddy == null || app == null) {
+ setState(() => _error = 'Restart is not available here.');
+ return;
+ }
+ setState(() {
+ _busy = true;
+ _error = null;
+ });
+ final text = _flags.text.trim();
+ // Nothing to clear and nothing to add is a plain restart, which an older
+ // daemon does it as well as a new one.
+ final result = await app.restartAgent(
+ buddy.machineId,
+ buddy.harnessId,
+ // Every press is a new intent: an earlier attempt that never confirmed
+ // must not turn this one into a status check without the flags.
+ attempt: app.restartAttempt(
+ buddy.machineId,
+ buddy.harnessId,
+ fresh: true,
+ ),
+ launchArgs: text.isEmpty && _saved.isEmpty ? null : text,
+ );
+ if (!mounted) return;
+ if (result.error == null && !result.launchArgsIgnored) {
+ Navigator.pop(context);
+ return;
+ }
+ final machine = buddyMachineName(c, buddy.machineId, app: app);
+ setState(() {
+ _busy = false;
+ _error = result.launchArgsIgnored
+ ? 'Update Harness on $machine to use launch flags.'
+ : result.launchArgsRefused
+ ? result.error
+ : !result.engineNotStarted
+ ? result.error
+ : "The Buddy didn't start with these flags. Fix or clear them and "
+ 'restart.';
+ });
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ final buddy = c.buddy(widget.projectId);
+ final engine = externalEngineName(
+ _machineAgent?.engine ?? buddy?.engine ?? '',
+ );
+ final machine = buddy == null
+ ? 'its machine'
+ : buddyMachineName(c, buddy.machineId, app: app);
+ return AlertDialog(
+ title: const Text('Restart Buddy'),
+ content: SizedBox(
+ width: 440,
+ child: SingleChildScrollView(
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ TextField(
+ key: const ValueKey('super-buddy-launch-args'),
+ controller: _flags,
+ autofocus: true,
+ readOnly: _busy,
+ style: grid.AppType.mono(),
+ decoration: const InputDecoration(
+ labelText: 'Extra launch flags',
+ hintText: '--chrome',
+ ),
+ onSubmitted: (_) => unawaited(_submit()),
+ ),
+ const SizedBox(height: 8),
+ Text(
+ "Added to $engine's command line each time this Buddy starts "
+ 'on $machine. Your Buddy runs with full permissions. Don\'t put '
+ 'secrets here: other people on that computer can see them. '
+ 'Clear the field to remove them.',
+ style: DesktopChrome.control(color: DesktopChrome.muted),
+ ),
+ if (_error case final error?) ...[
+ const SizedBox(height: 12),
+ Text(
+ error,
+ key: const ValueKey('super-buddy-launch-args-error'),
+ style: DesktopChrome.control(),
+ ),
+ ],
+ ],
+ ),
+ ),
+ ),
+ actions: [
+ TextButton(
+ onPressed: _busy ? null : () => Navigator.pop(context),
+ child: const Text('Cancel'),
+ ),
+ FilledButton(
+ onPressed: _busy ? null : () => unawaited(_submit()),
+ child: _busy
+ ? const SizedBox(
+ width: 16,
+ height: 16,
+ child: CircularProgressIndicator(strokeWidth: 2),
+ )
+ : const Text('Restart'),
+ ),
+ ],
+ );
+ }
+}
diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dart
index 9df80e20e..83b093eb9 100644
--- a/desktop/lib/super_tabs/view.dart
+++ b/desktop/lib/super_tabs/view.dart
@@ -80,6 +80,7 @@ import 'message_row.dart';
import 'message_receipt.dart';
import 'notifications.dart';
import 'buddies.dart';
+import 'buddy_restart.dart';
import 'decisions.dart';
import 'day_pill.dart';
import 'decisions_view.dart';
@@ -3962,6 +3963,20 @@ class _SuperTabViewState extends State<SuperTabView>
'Rename Buddy…',
() => unawaited(showRenameBuddy(context, c, group.projectId)),
),
+ if (editable &&
+ (c.buddy(group.projectId)?.harnessId.isNotEmpty ?? false) &&
+ c.buddy(group.projectId)!.machineId.isNotEmpty)
+ item(
+ 'Restart Buddy…',
+ () => unawaited(
+ showRestartBuddy(
+ context,
+ c,
+ group.projectId,
+ app: widget.app,
+ ),
+ ),
+ ),
if (editable && c.buddy(group.projectId) != null)
item(
'Remove Buddy',
diff --git a/desktop/test/agent_restart_launch_args_test.dart b/desktop/test/agent_restart_launch_args_test.dart
new file mode 100644
index 000000000..911c46a87
--- /dev/null
+++ b/desktop/test/agent_restart_launch_args_test.dart
@@ -0,0 +1,132 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/ws/ws_conn.dart';
+
+import 'support/restart_connection.dart';
+import 'swarm_state_test.dart' show createApp;
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+ late RestartConnection connection;
+ late AppNotifier app;
+ setUp(() {
+ connection = RestartConnection();
+ app = createApp(connectionForTest: (_) => connection);
+ });
+ tearDown(() => app.dispose());
+ String id() => connection.requests.last['creationId'] as String;
+
+ test('restart sends launchArgs and reads the echo as honoured', () async {
+ final request = app.restartAgent('m', 'a0', launchArgs: '--chrome');
+ expect(connection.requests.single['launchArgs'], '--chrome');
+ connection.restartReplies.single.complete({
+ ...restartReceipt(id()),
+ 'launchArgs': ['--chrome'],
+ });
+ final result = await request;
+ expect(result.error, isNull);
+ expect(result.launchArgsIgnored, isFalse);
+ });
+
+ test('an empty string is still sent, to clear the saved flags', () async {
+ final request = app.restartAgent('m', 'a0', launchArgs: '');
+ expect(connection.requests.single['launchArgs'], '');
+ connection.restartReplies.single.complete({
+ ...restartReceipt(id()),
+ 'launchArgs': <String>[],
+ });
+ expect((await request).launchArgsIgnored, isFalse);
+ });
+
+ test('a created reply with no echo means an old daemon', () async {
+ final request = app.restartAgent('m', 'a0', launchArgs: '--chrome');
+ connection.restartReplies.single.complete(restartReceipt(id()));
+ final result = await request;
+ expect(result.error, isNull);
+ expect(result.launchArgsIgnored, isTrue);
+ });
+
+ test(
+ 'without launchArgs the payload has none and nothing is ignored',
+ () async {
+ final request = app.restartAgent('m', 'a0');
+ expect(connection.requests.single.containsKey('launchArgs'), isFalse);
+ connection.restartReplies.single.complete(restartReceipt(id()));
+ expect((await request).launchArgsIgnored, isFalse);
+ },
+ );
+
+ test('a status check never sends launchArgs or reports ignored', () async {
+ final attempt = app.restartAttempt('m', 'a0');
+ var request = app.restartAgent(
+ 'm',
+ 'a0',
+ attempt: attempt,
+ launchArgs: '--chrome',
+ );
+ connection.restartReplies.single.completeError(
+ const WsRequestTimeout('agent_restart'),
+ );
+ expect((await request).error, contains('not confirmed'));
+ request = app.restartAgent(
+ 'm',
+ 'a0',
+ attempt: attempt,
+ launchArgs: '--chrome',
+ );
+ expect(connection.checks.single.containsKey('launchArgs'), isFalse);
+ connection.checkReplies.single.complete(restartReceipt(id()));
+ final result = await request;
+ expect(result.error, isNull);
+ expect(result.launchArgsIgnored, isFalse);
+ expect(connection.requests, hasLength(1));
+ });
+
+ test('a refusal carries the daemon detail and is marked', () async {
+ final request = app.restartAgent('m', 'a0', launchArgs: '--model x');
+ connection.restartReplies.single.completeError(
+ const WsRequestFailure(
+ responseType: 'agent_restart_result',
+ code: 'INVALID_LAUNCH_ARGS',
+ detail: "--model is set by Harness and can't be added here.",
+ ),
+ );
+ final result = await request;
+ expect(result.error, "--model is set by Harness and can't be added here.");
+ expect(result.launchArgsRefused, isTrue);
+ });
+
+ for (final code in ['RESTART_FAILED', 'RESUME_UNCONFIRMED']) {
+ test(
+ '$code and an unconfirmed receipt mean the engine did not start',
+ () async {
+ final request = app.restartAgent('m', 'a0', launchArgs: '--bad');
+ connection.restartReplies.single.completeError(
+ WsRequestFailure(responseType: 'agent_restart_result', code: code),
+ );
+ expect((await request).engineNotStarted, isTrue);
+ },
+ );
+ }
+
+ test('a lost reply is not read as the engine not starting', () async {
+ final request = app.restartAgent('m', 'a0', launchArgs: '--bad');
+ connection.restartReplies.single.completeError(
+ const WsRequestTimeout('agent_restart'),
+ );
+ final result = await request;
+ expect(result.error, isNotNull);
+ expect(result.engineNotStarted, isFalse);
+ });
+
+ test('Agent.fromJson keeps only string launchArgs', () {
+ final agent = Agent.fromJson({
+ 'id': 'a1',
+ 'launchArgs': ['--chrome', 3],
+ });
+ expect(agent.launchArgs, ['--chrome']);
+ expect(Agent.fromJson({'id': 'a1'}).launchArgs, isEmpty);
+ expect(Agent.fromJson({'id': 'a1', 'launchArgs': 'x'}).launchArgs, isEmpty);
+ });
+}
diff --git a/desktop/test/super_tab_buddy_restart_test.dart b/desktop/test/super_tab_buddy_restart_test.dart
new file mode 100644
index 000000000..1518e833d
--- /dev/null
+++ b/desktop/test/super_tab_buddy_restart_test.dart
@@ -0,0 +1,446 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/state/app_state.dart';
+import 'package:harness/super_tabs/buddy_restart.dart' show launchArgsLine;
+import 'package:harness/super_tabs/controller.dart';
+import 'package:harness/super_tabs/view.dart';
+import 'package:harness/ws/ws_conn.dart';
+
+import 'support/buddy_fixture.dart';
+import 'support/restart_connection.dart';
+import 'support/super_tab_fixture.dart';
+import 'swarm_state_test.dart' show createApp;
+
+/// "Restart Buddy…" in the Buddy chat's menu (spec 2026-11-06-buddy-launch-flags).
+void main() {
+ late RestartConnection connection;
+ late AppNotifier app;
+
+ setUp(() {
+ connection = RestartConnection();
+ app = createApp(connected: true, connectionForTest: (_) => connection);
+ app.stateOf('m')!.agents = [
+ const Agent(
+ id: 'h-wren',
+ name: 'Wren',
+ engine: 'claude',
+ terminalAvailable: true,
+ launchArgs: ['--chrome'],
+ ),
+ ];
+ });
+ tearDown(() => app.dispose());
+
+ Future<SuperTabController> show(
+ WidgetTester tester,
+ ConversationServer server,
+ ) async {
+ await tester.binding.setSurfaceSize(const Size(1280, 800));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ final c = server.controller(account: 'peer');
+ await c.refresh();
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(),
+ home: Scaffold(
+ body: SuperTabView(
+ controller: c,
+ app: app,
+ onInvite: () {},
+ onAddAgent: (_) {},
+ onOpenTerminal: (_) {},
+ machineName: (_) => 'Team Mac',
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ return c;
+ }
+
+ Future<void> close(WidgetTester tester, SuperTabController c) async {
+ await tester.pumpWidget(const SizedBox());
+ await c.flush();
+ c.dispose();
+ }
+
+ final buddyEntry = find.byKey(const ValueKey('super-buddy-lead'));
+ final field = find.byKey(const ValueKey('super-buddy-launch-args'));
+ final error = find.byKey(const ValueKey('super-buddy-launch-args-error'));
+ final restart = find.widgetWithText(FilledButton, 'Restart');
+
+ ConversationServer swarm() {
+ final server = buddySwarm();
+ giveBuddy(server, machineId: 'm');
+ return server;
+ }
+
+ Future<void> openMenu(WidgetTester tester) async {
+ await tester.tap(buddyEntry);
+ await tester.pumpAndSettle();
+ await tester.tap(find.byTooltip('Buddy options'));
+ await tester.pumpAndSettle();
+ }
+
+ Future<void> openDialog(WidgetTester tester) async {
+ await openMenu(tester);
+ await tester.tap(find.text('Restart Buddy…'));
+ await tester.pumpAndSettle();
+ }
+
+ String creationId() => connection.requests.last['creationId'] as String;
+
+ testWidgets("the menu has Restart Buddy… on the reader's own Buddy chat", (
+ tester,
+ ) async {
+ final c = await show(tester, swarm());
+ await openMenu(tester);
+ expect(find.text('Restart Buddy…'), findsOneWidget);
+ await close(tester, c);
+ });
+
+ testWidgets('the menu has none on a workgroup chat', (tester) async {
+ final server = swarm();
+ (server.state['conversations'] as List).add({
+ ...conversationFixture('side-work', 'Side work'),
+ 'projectId': 'lead',
+ });
+ final c = await show(tester, server);
+ await c.select('side-work');
+ await tester.pumpAndSettle();
+ await tester.tap(find.byTooltip('Workgroup options'));
+ await tester.pumpAndSettle();
+ expect(find.text('Restart Buddy…'), findsNothing);
+ await close(tester, c);
+ });
+
+ testWidgets("the menu has none on someone else's Buddy chat", (tester) async {
+ final server = swarm();
+ final c = server.controller(account: 'someone-else');
+ await c.refresh();
+ await tester.binding.setSurfaceSize(const Size(1280, 800));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(),
+ home: Scaffold(
+ body: SuperTabView(
+ controller: c,
+ app: app,
+ onInvite: () {},
+ onAddAgent: (_) {},
+ onOpenTerminal: (_) {},
+ machineName: (_) => 'Team Mac',
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ expect(c.buddy('lead'), isNull);
+ expect(find.text('Restart Buddy…'), findsNothing);
+ await close(tester, c);
+ });
+
+ testWidgets('the menu has none on a Buddy chat whose Buddy is gone', (
+ tester,
+ ) async {
+ // The chat is there, the Buddy is not: an older project chat, read only.
+ final server = swarm();
+ (server.state['agents'] as List).clear();
+ final c = await show(tester, server);
+ await openMenu(tester);
+ expect(find.text('Rename Buddy…'), findsOneWidget);
+ expect(find.text('Restart Buddy…'), findsNothing);
+ await close(tester, c);
+ });
+
+ testWidgets('the menu has none on a Buddy with no agent on a machine', (
+ tester,
+ ) async {
+ final server = swarm();
+ for (final agent in server.state['agents'] as List) {
+ if ((agent as Map)['buddyOf'] != null) agent['harnessId'] = '';
+ }
+ final c = await show(tester, server);
+ await openMenu(tester);
+ expect(find.text('Rename Buddy…'), findsOneWidget);
+ expect(find.text('Restart Buddy…'), findsNothing);
+ await close(tester, c);
+ });
+
+ testWidgets('the dialog prefills the saved flags and says where they apply', (
+ tester,
+ ) async {
+ final c = await show(tester, swarm());
+ await openDialog(tester);
+ expect(find.text('Restart Buddy'), findsOneWidget);
+ expect(find.text('Extra launch flags'), findsOneWidget);
+ expect(tester.widget<TextField>(field).controller!.text, '--chrome');
+ expect(
+ find.text(
+ "Added to Claude Code's command line each time this Buddy starts on "
+ 'Test host. Your Buddy runs with full permissions. Don\'t put secrets '
+ 'here: other people on that computer can see them. Clear the field to '
+ 'remove them.',
+ ),
+ findsOneWidget,
+ );
+ await close(tester, c);
+ });
+
+ testWidgets('Restart sends the flags and the dialog closes on success', (
+ tester,
+ ) async {
+ final c = await show(tester, swarm());
+ await openDialog(tester);
+ await tester.enterText(field, '--chrome --x');
+ await tester.tap(restart);
+ await tester.pump();
+ expect(connection.requests.single['agentId'], 'h-wren');
+ expect(connection.requests.single['launchArgs'], '--chrome --x');
+ // Busy: the field is read-only and the button shows progress.
+ expect(tester.widget<TextField>(field).readOnly, isTrue);
+ expect(find.byType(CircularProgressIndicator), findsOneWidget);
+ connection.restartReplies.single.complete({
+ ...restartReceipt(creationId(), agentId: 'h-wren'),
+ 'launchArgs': ['--chrome', '--x'],
+ });
+ await tester.pumpAndSettle();
+ expect(find.text('Restart Buddy'), findsNothing);
+ await close(tester, c);
+ });
+
+ testWidgets('Enter in the field restarts', (tester) async {
+ final c = await show(tester, swarm());
+ await openDialog(tester);
+ await tester.testTextInput.receiveAction(TextInputAction.done);
+ await tester.pump();
+ expect(connection.requests.single['launchArgs'], '--chrome');
+ connection.restartReplies.single.complete({
+ ...restartReceipt(creationId(), agentId: 'h-wren'),
+ 'launchArgs': ['--chrome'],
+ });
+ await tester.pumpAndSettle();
+ expect(find.text('Restart Buddy'), findsNothing);
+ await close(tester, c);
+ });
+
+ testWidgets("a refusal shows the daemon's words and keeps the dialog", (
+ tester,
+ ) async {
+ final c = await show(tester, swarm());
+ await openDialog(tester);
+ await tester.enterText(field, '--model x');
+ await tester.tap(restart);
+ await tester.pump();
+ connection.restartReplies.single.completeError(
+ const WsRequestFailure(
+ responseType: 'agent_restart_result',
+ code: 'INVALID_LAUNCH_ARGS',
+ detail: "--model is set by Harness and can't be added here.",
+ ),
+ );
+ await tester.pumpAndSettle();
+ expect(
+ tester.widget<Text>(error).data,
+ "--model is set by Harness and can't be added here.",
+ );
+ expect(find.text('Restart Buddy'), findsOneWidget);
+ expect(tester.widget<TextField>(field).readOnly, isFalse);
+ await close(tester, c);
+ });
+
+ testWidgets('an engine that did not start says to fix or clear the flags', (
+ tester,
+ ) async {
+ final c = await show(tester, swarm());
+ await openDialog(tester);
+ await tester.tap(restart);
+ await tester.pump();
+ connection.restartReplies.single.complete({
+ 'creationId': creationId(),
+ 'state': 'unconfirmed',
+ });
+ await tester.pumpAndSettle();
+ expect(
+ tester.widget<Text>(error).data,
+ "The Buddy didn't start with these flags. Fix or clear them and restart.",
+ );
+ expect(find.text('Restart Buddy'), findsOneWidget);
+ await close(tester, c);
+ });
+
+ testWidgets('after a bad flag, clearing the field restarts anew', (
+ tester,
+ ) async {
+ final c = await show(tester, swarm());
+ await openDialog(tester);
+ await tester.enterText(field, '--bad');
+ await tester.tap(restart);
+ await tester.pump();
+ final first = creationId();
+ connection.restartReplies.single.complete({
+ 'creationId': first,
+ 'state': 'unconfirmed',
+ });
+ await tester.pumpAndSettle();
+ expect(error, findsOneWidget);
+ await tester.enterText(field, '');
+ await tester.tap(restart);
+ await tester.pump();
+ expect(connection.checks, isEmpty);
+ expect(connection.requests, hasLength(2));
+ expect(connection.requests.last['launchArgs'], '');
+ expect(creationId(), isNot(first));
+ connection.restartReplies.last.complete({
+ ...restartReceipt(creationId(), agentId: 'h-wren'),
+ 'launchArgs': <String>[],
+ });
+ await tester.pumpAndSettle();
+ expect(find.text('Restart Buddy'), findsNothing);
+ await close(tester, c);
+ });
+
+ testWidgets('a stopped Buddy resumes with the flags', (tester) async {
+ app.stateOf('m')!.agents = [
+ const Agent(
+ id: 'h-wren',
+ name: 'Wren',
+ engine: 'claude',
+ status: 'stopped',
+ launchArgs: ['--chrome'],
+ ),
+ ];
+ final c = await show(tester, swarm());
+ await openDialog(tester);
+ await tester.tap(restart);
+ await tester.pump();
+ expect(connection.types.single, 'agent_resume');
+ expect(connection.requests.single['launchArgs'], '--chrome');
+ connection.restartReplies.single.complete({
+ ...restartReceipt(creationId(), agentId: 'h-wren'),
+ 'launchArgs': ['--chrome'],
+ });
+ await tester.pumpAndSettle();
+ expect(find.text('Restart Buddy'), findsNothing);
+ await close(tester, c);
+ });
+
+ testWidgets('a restart started elsewhere is not the dialog\'s result', (
+ tester,
+ ) async {
+ final c = await show(tester, swarm());
+ final other = app.restartAgent('m', 'h-wren');
+ await openDialog(tester);
+ await tester.tap(restart);
+ await tester.pump();
+ expect(connection.requests, hasLength(2));
+ expect(connection.requests.last['launchArgs'], '--chrome');
+ connection.restartReplies.first.complete(
+ restartReceipt(
+ connection.requests.first['creationId'] as String,
+ agentId: 'h-wren',
+ ),
+ );
+ await other;
+ await tester.pump();
+ expect(find.text('Restart Buddy'), findsOneWidget);
+ connection.restartReplies.last.complete({
+ ...restartReceipt(creationId(), agentId: 'h-wren'),
+ 'launchArgs': ['--chrome'],
+ });
+ await tester.pumpAndSettle();
+ expect(find.text('Restart Buddy'), findsNothing);
+ await close(tester, c);
+ });
+
+ testWidgets('a busy Buddy shows its own failure, not the flags text', (
+ tester,
+ ) async {
+ final c = await show(tester, swarm());
+ await openDialog(tester);
+ await tester.tap(restart);
+ await tester.pump();
+ connection.restartReplies.single.completeError(
+ const WsRequestFailure(
+ responseType: 'agent_restart_result',
+ code: 'AGENT_BUSY',
+ ),
+ );
+ await tester.pumpAndSettle();
+ final text = tester.widget<Text>(error).data!;
+ expect(text, isNot(contains("didn't start")));
+ expect(text, isNotEmpty);
+ await close(tester, c);
+ });
+
+ testWidgets('an offline machine shows the connection failure', (
+ tester,
+ ) async {
+ app.stateOf('m')!.agents = [
+ const Agent(
+ id: 'h-wren',
+ name: 'Wren',
+ engine: 'claude',
+ status: 'stopped',
+ ),
+ ];
+ app.stateOf('m')!.connectionStatus = ConnectionStatus.disconnected;
+ final c = await show(tester, swarm());
+ await openDialog(tester);
+ await tester.tap(restart);
+ await tester.pumpAndSettle();
+ final text = tester.widget<Text>(error).data!;
+ expect(text, isNot(contains("didn't start")));
+ expect(text, contains('not connected'));
+ await close(tester, c);
+ });
+
+ testWidgets('a reply with no echo says to update Harness on the machine', (
+ tester,
+ ) async {
+ final c = await show(tester, swarm());
+ await openDialog(tester);
+ await tester.tap(restart);
+ await tester.pump();
+ connection.restartReplies.single.complete(
+ restartReceipt(creationId(), agentId: 'h-wren'),
+ );
+ await tester.pumpAndSettle();
+ expect(
+ tester.widget<Text>(error).data,
+ 'Update Harness on Test host to use launch flags.',
+ );
+ expect(find.text('Restart Buddy'), findsOneWidget);
+ await close(tester, c);
+ });
+
+ testWidgets('an empty field with nothing saved is a plain restart', (
+ tester,
+ ) async {
+ app.stateOf('m')!.agents = [
+ const Agent(id: 'h-wren', name: 'Wren', engine: 'claude'),
+ ];
+ final c = await show(tester, swarm());
+ await openDialog(tester);
+ await tester.tap(restart);
+ await tester.pump();
+ expect(connection.requests.single.containsKey('launchArgs'), isFalse);
+ connection.restartReplies.single.complete(
+ restartReceipt(creationId(), agentId: 'h-wren'),
+ );
+ await tester.pumpAndSettle();
+ expect(find.text('Restart Buddy'), findsNothing);
+ await close(tester, c);
+ });
+
+ test('words with spaces or quotes are quoted so they read back whole', () {
+ expect(launchArgsLine(['--chrome']), '--chrome');
+ expect(
+ launchArgsLine(['--add-dir', '/a b', "it's", '']),
+ "--add-dir '/a b' 'it'\\''s' ''",
+ );
+ });
+}
diff --git a/docs/plans/2026-11-06-buddy-launch-flags-plan.md b/docs/plans/2026-11-06-buddy-launch-flags-plan.md
new file mode 100644
index 000000000..a2cbeb790
--- /dev/null
+++ b/docs/plans/2026-11-06-buddy-launch-flags-plan.md
@@ -0,0 +1,281 @@
+# Buddy launch flags Implementation Plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** Let the owner restart their Buddy from Desktop with free-form extra launch flags (for example `--chrome`). The flags are
+saved on the daemon's agent record and applied on every later launch.
+
+**Architecture:**
+- The CLI gains a pure parser and validator (`lib/launchArgs.ts`), an optional `launchArgs` on the registry row, and an append in
+ `buildLaunchOverrides`.
+- `agent_restart` takes an optional `launchArgs` string, saves it, and echoes the saved words.
+- Desktop gains a "Restart Buddy…" dialog in the Buddy chat's menu, sending through `AppNotifier.restartAgent`.
+
+**Tech Stack:** TypeScript (cli, vitest), Dart/Flutter (desktop, flutter_test).
+
+**Spec:** `docs/specs/2026-11-06-buddy-launch-flags.md`
+
+## Global Constraints
+
+- Limits: at most 1024 characters and 20 words; no NUL or newline; an unclosed quote is refused.
+- The error code is `INVALID_LAUNCH_ARGS`, with a `detail` naming the problem.
+- Refused flags (the part before `=`):
+ - **Claude:** `--resume`, `-r`, `--continue`, `-c`, `--model`, `--permission-mode`, `--dangerously-skip-permissions`,
+ `--session-id`, `--settings`, `--append-system-prompt`, `--system-prompt`, `--mcp-config`, `--fork-session`.
+ - **Codex:** `--model`, `-m`, `--dangerously-bypass-approvals-and-sandbox`, `--ask-for-approval`, `-a`, `--sandbox`, `-s`,
+ `--profile`, `-p`, plus `resume` or `fork` as the first word.
+ - **Other engines:** only the length, word-count and character rules.
+- Never run a shell. The words go into argv as they are.
+- The record field is `launchArgs?: string[]`, never written when empty.
+- Argv order: after the Swarm's args, before Harness's instructions.
+- Desktop copy, exactly:
+ - menu item "Restart Buddy…";
+ - title "Restart Buddy";
+ - field label "Extra launch flags", hint `--chrome`;
+ - detail "Added to <engine>'s command line each time this Buddy starts on <machine name>. Your Buddy runs with full
+ permissions. Clear the field to remove them.";
+ - buttons "Restart" and "Cancel";
+ - engine did not start: "The Buddy didn't start with these flags. Fix or clear them and restart.";
+ - old daemon: "Update Harness on <machine name> to use launch flags."
+- Code, comments and UI text are in English.
+
+## Review Focus
+
+1. **A status re-check after a lost reply.** Desktop re-asks `agent_create_status`, which never echoes `launchArgs`. It must
+ not show "Update Harness". Pinned in Task 5.
+2. **A repeated Restart with the same receipt but different flags.** The receipt fingerprint must include `launchArgs`, so the
+ second request is not treated as the first one. Pinned in Task 3.
+3. **A stopped Buddy brought back after a reboot.** The stopped row must keep `launchArgs`, and the restored argv must carry
+ them. Pinned in Task 2.
+4. **A word that is only `=` or `-`, or a quoted flag such as `"--model"`.** The flag is checked after unquoting, so
+ `"--model"` is refused. Pinned in Task 1.
+5. **Clearing the field on an agent with no saved flags.** It is a no-op restart, writes no empty array, and echoes `[]`.
+ Pinned in Task 3.
+
+---
+
+### Task 1: Parse and validate launch flags (CLI)
+
+**Files:**
+- Create: `cli/src/lib/launchArgs.ts`
+- Test: `cli/src/lib/launchArgs.spec.ts`
+
+**Interfaces:**
+- Produces:
+ - `parseLaunchArgs(engine: AgentEngine, text: string): { ok: true; args: string[] } | { ok: false; detail: string }`;
+ - `LAUNCH_ARGS_MAX_CHARS = 1024`;
+ - `LAUNCH_ARGS_MAX_WORDS = 20`.
+
+- [ ] **Step 1: Write the failing tests** in `launchArgs.spec.ts`:
+ - `parseLaunchArgs('claude', '--chrome')` → `{ ok: true, args: ['--chrome'] }`.
+ - `parseLaunchArgs('claude', ' ')` → `{ ok: true, args: [] }`.
+ - `parseLaunchArgs('claude', `--add-dir "/a b" --x='y z' c\\ d`)` → args `['--add-dir', '/a b', "--x=y z", 'c d']`.
+ - Unclosed quote `'--x "a'` → `ok: false`, detail contains `quote`.
+ - 21 words → `ok: false`, detail contains `20`.
+ - 1025 characters → `ok: false`, detail contains `1024`.
+ - Text containing `\n` or `\0` → `ok: false`.
+ - Claude: each refused flag, bare and as `--model=opus`, plus the quoted `'"--model"'`, gives `ok: false` with detail
+ `--model is set by Harness and can't be added here.`.
+ - Claude `-c` → refused. Codex `-c model_reasoning_effort=high` → `ok: true`.
+ - Codex `resume` as the first word → refused. Codex `--search resume` → `ok: true`.
+ - `parseLaunchArgs('opencode', '--model x')` → `ok: true`.
+- [ ] **Step 2: Run** `cd cli && npx vitest run src/lib/launchArgs.spec.ts`. Expected: FAIL (module not found).
+- [ ] **Step 3: Implement `parseLaunchArgs`.**
+ - A small POSIX word splitter: whitespace separates words; single quotes are literal; double quotes allow `\"` and `\\`;
+ a backslash outside quotes escapes the next character.
+ - Then the limits, then the per-engine refused sets from Global Constraints. Compare `word.split('=')[0]`.
+ - Detail for a refused flag is `` `${flag} is set by Harness and can't be added here.` ``.
+- [ ] **Step 4: Run** the same command. Expected: PASS.
+- [ ] **Step 5: Commit**
+ ```bash
+ git add cli/src/lib/launchArgs.ts cli/src/lib/launchArgs.spec.ts
+ git commit -m "cli: parse and validate a Buddy's extra launch flags"
+ ```
+
+### Task 2: Save launch flags on the agent record and apply them on every launch (CLI)
+
+**Files:**
+- Modify: `cli/src/lib/registry.ts`:
+ - `RegisteredSession` near `swarmSkill`;
+ - the row normaliser near line 689 (`const { … swarmSkill: rawSwarmSkill, ...rest } = row`);
+ - the load near line 1387;
+ - add `setLaunchArgs` beside `setLaunchModel` (~2590).
+- Modify: `cli/src/lib/launchOverrides.ts`: `LaunchSource` gets `launchArgs?: string[]`; append it after
+ `swarm!.args(engine)` (~line 323) and before `swarmInstructions`.
+- Modify: `cli/src/core/agents/launch.ts:61`: pass `launchArgs: session.launchArgs` into `buildLaunchOverrides`.
+- Test: `cli/src/lib/registry.spec.ts`, `cli/src/lib/launchOverrides.spec.ts`
+
+**Interfaces:**
+- Consumes: none.
+- Produces:
+ - `RegisteredSession.launchArgs?: string[]`;
+ - `registry.setLaunchArgs(agentId: string, args: string[]): boolean`. An empty array deletes the field; it returns false
+ for an unknown agent.
+
+- [ ] **Step 1: Write the failing tests.**
+ - registry.spec:
+ - `setLaunchArgs('a1', ['--chrome'])` then reload from disk → `byAgent('a1').launchArgs` equals `['--chrome']`.
+ - `setLaunchArgs('a1', [])` → the field is absent (`'launchArgs' in row` is false).
+ - A row with `launchArgs: [1, '--x']` or `launchArgs: 'x'` on disk loads with no `launchArgs`. Only an array of strings
+ is kept.
+ - A stopped-row round trip through the normaliser keeps `['--chrome']`.
+ - launchOverrides.spec: a Buddy source (`swarmSkill` role `buddy`) with `launchArgs: ['--chrome']` gives `extraArgs` where
+ `--chrome` comes after the Swarm args and before the instruction args (`--append-system-prompt` for Claude). With no
+ `launchArgs`, `extraArgs` is unchanged from today.
+- [ ] **Step 2: Run** `cd cli && npx vitest run src/lib/registry.spec.ts src/lib/launchOverrides.spec.ts`. Expected: the new
+ cases FAIL.
+- [ ] **Step 3: Implement.**
+ - Parse with a guard `Array.isArray(v) && v.every(w => typeof w === 'string') && v.length > 0`, in both the normaliser and
+ the load.
+ - `setLaunchArgs` mirrors `setLaunchModel`, persisting the same way.
+ - Pass the field through `launch.ts`.
+- [ ] **Step 4: Run** the same command. Expected: PASS. Also run `cd cli && npx tsc --noEmit -p .`. Expected: clean.
+- [ ] **Step 5: Commit**
+ ```bash
+ git add cli/src/lib/registry.ts cli/src/lib/registry.spec.ts cli/src/lib/launchOverrides.ts cli/src/lib/launchOverrides.spec.ts cli/src/core/agents/launch.ts
+ git commit -m "cli: an agent's saved launch flags ride every relaunch"
+ ```
+
+### Task 3: `agent_restart` takes `launchArgs` (CLI)
+
+**Files:**
+- Modify: `cli/src/core/agents/launches.ts`: `relaunch` (~line 600). The deps type gains `setLaunchArgs`.
+- Modify: `cli/src/core/main.ts`: wire `setLaunchArgs: (id, a) => registry.setLaunchArgs(id, a)` where `launches` is built
+ (the block with `byAgent: (id) => registry.byAgent(id), toProject: …` near line 3059).
+- Test: `cli/src/core/agents/launches.spec.ts`
+
+**Interfaces:**
+- Consumes: `parseLaunchArgs` (Task 1) and `registry.setLaunchArgs` (Task 2).
+- Produces:
+ - Request `agent_restart { agentId, creationId?, launchArgs?: string }`.
+ - Reply: today's shape plus `launchArgs: string[]` whenever the request carried `launchArgs`. That holds for the direct
+ reply and for the receipt reply.
+ - Error `{ error: 'INVALID_LAUNCH_ARGS', detail }`.
+
+- [ ] **Step 1: Write the failing tests** in launches.spec, using its existing `setup()`:
+ - Restart with `launchArgs: '--chrome'` calls `setLaunchArgs('agent-1', ['--chrome'])` before the restart runs. The reply
+ contains `launchArgs: ['--chrome']`, both with and without `creationId`.
+ - `launchArgs: ''` calls `setLaunchArgs(id, [])` and echoes `[]`.
+ - `launchArgs: '--model x'` replies `INVALID_LAUNCH_ARGS` with detail `--model is set by Harness and can't be added here.`,
+ and neither restarts nor saves.
+ - A non-string `launchArgs` (for example `5`) → `INVALID_LAUNCH_ARGS`.
+ - `agent_resume` with `launchArgs` → `INVALID_LAUNCH_ARGS`. Only restart takes them.
+ - A team-written agent (`permissionMode: 'teamWritten'`) with `launchArgs` → `INVALID_LAUNCH_ARGS`.
+ - Two requests with the same `creationId` and different `launchArgs` → the second is refused as a mismatched receipt.
+ Use the error the receipt store already gives a different fingerprint.
+- [ ] **Step 2: Run** `cd cli && npx vitest run src/core/agents/launches.spec.ts`. Expected: the new cases FAIL.
+- [ ] **Step 3: Implement in `relaunch`.**
+ - Before `invoke`: when `payload.launchArgs !== undefined`:
+ - refuse unless `operation === 'restart'` and it is a string;
+ - refuse a team-written target;
+ - parse it with the target's engine (`byAgent(target)!.engine`);
+ - then `setLaunchArgs(target, parsed.args)`.
+ - Add `launchArgs` (the parsed words) to `creationFingerprint(...)` when present.
+ - Add `launchArgs: parsed.args` to both reply paths when present.
+- [ ] **Step 4: Run** the same command plus `cd cli && npx tsc --noEmit -p .`. Expected: PASS, clean.
+- [ ] **Step 5: Commit**
+ ```bash
+ git add cli/src/core/agents/launches.ts cli/src/core/agents/launches.spec.ts cli/src/core/main.ts
+ git commit -m "cli: agent_restart saves and echoes extra launch flags"
+ ```
+
+### Task 4: The agent frame carries `launchArgs` (CLI)
+
+**Files:**
+- Modify: `cli/src/lib/agentFrame.ts`: the `AgentFrame` interface and `agentFrame(s, …)` add `launchArgs?: string[]` when
+ the session has any.
+- Test: `cli/src/lib/agentFrame.spec.ts`
+
+**Interfaces:**
+- Produces: `AgentFrame.launchArgs?: string[]`. It is absent when the session has none.
+
+- [ ] **Step 1: Write the failing tests.**
+ - `agentFrame({ ...session, launchArgs: ['--chrome'] }, ctx)` has `launchArgs: ['--chrome']`.
+ - A session without the field gives a frame with no `launchArgs` key.
+- [ ] **Step 2: Run** `cd cli && npx vitest run src/lib/agentFrame.spec.ts`. Expected: FAIL.
+- [ ] **Step 3: Implement** the conditional spread in `agentFrame`.
+- [ ] **Step 4: Run** the same command, then `cd cli && npx vitest run src/core src/lib && npx tsc --noEmit -p . && npm run test:core`.
+ Expected: PASS, clean, 100% coverage for `src/core`.
+- [ ] **Step 5: Commit**
+ ```bash
+ git add cli/src/lib/agentFrame.ts cli/src/lib/agentFrame.spec.ts
+ git commit -m "cli: an agent's frame names its extra launch flags"
+ ```
+
+### Task 5: Desktop sends `launchArgs` and reads them back
+
+**Files:**
+- Modify: `desktop/lib/core/models.dart`:
+ - `Agent` gains `final List<String> launchArgs` (default `const []`);
+ - `Agent.fromJson` reads `j['launchArgs']`, keeping only strings.
+- Modify: `desktop/lib/state/app_state.dart`:
+ - `RestartAgentResult` gains `final bool launchArgsIgnored` (default false);
+ - `restartAgent(machineId, agentId, {AgentRestartAttempt? attempt, String? launchArgs})` and `_runAgentRestart` add
+ `'launchArgs': launchArgs` to the `agent_restart` payload when it is non-null and the request is not a status check.
+- Test: `desktop/test/agent_restart_launch_args_test.dart`
+
+**Interfaces:**
+- Produces:
+ - `AppNotifier.restartAgent(String machineId, String agentId, {AgentRestartAttempt? attempt, String? launchArgs})`;
+ - `RestartAgentResult.launchArgsIgnored`;
+ - `Agent.launchArgs`.
+
+- [ ] **Step 1: Write the failing tests.** Use the recording fake connection the existing restart tests use.
+ - `restartAgent('m1', 'a1', launchArgs: '--chrome')` sends an `agent_restart` payload with `launchArgs: '--chrome'`.
+ - A reply that echoes `launchArgs` gives `launchArgsIgnored == false`.
+ - A created reply with no `launchArgs` gives `launchArgsIgnored == true`.
+ - A status check (`agent_create_status`) path never sends `launchArgs` and never sets `launchArgsIgnored`.
+ - `Agent.fromJson({... 'launchArgs': ['--chrome', 3]})` gives `launchArgs == ['--chrome']`.
+- [ ] **Step 2: Run** `cd desktop && flutter test test/agent_restart_launch_args_test.dart`. Expected: FAIL.
+- [ ] **Step 3: Implement.**
+ - `launchArgsIgnored` = `launchArgs != null && !checking && result['launchArgs'] == null && no error`.
+ - The status-check request keeps its payload unchanged.
+- [ ] **Step 4: Run** the same command plus `flutter analyze`. Expected: PASS, no issues.
+- [ ] **Step 5: Commit**
+ ```bash
+ git add desktop/lib/core/models.dart desktop/lib/state/app_state.dart desktop/test/agent_restart_launch_args_test.dart
+ git commit -m "desktop: restart an agent with extra launch flags"
+ ```
+
+### Task 6: "Restart Buddy…" in the Buddy chat's menu (Desktop)
+
+**Files:**
+- Create: `desktop/lib/super_tabs/buddy_restart.dart`:
+ - `Future<void> showRestartBuddy(BuildContext context, SuperTabController c, String projectId, {AppNotifier? app})`;
+ - its dialog widget, following `showRenameBuddy`'s dialog style.
+- Modify: `desktop/lib/super_tabs/view.dart` (~line 3960): after "Rename Buddy…", add `item('Restart Buddy…', …)` when
+ `editable && c.buddy(group.projectId) != null`.
+- Test: `desktop/test/super_tab_buddy_restart_test.dart`
+
+**Interfaces:**
+- Consumes:
+ - `AppNotifier.restartAgent(..., launchArgs:)`, `RestartAgentResult.launchArgsIgnored` and `Agent.launchArgs` (Task 5);
+ - `c.buddy(projectId)` (`SuperTabAgent` with `machineId`, `harnessId`);
+ - `buddyMachineName(c, machineId, app: app)` (`buddies.dart`).
+
+- [ ] **Step 1: Write the failing widget tests.**
+ - The menu shows "Restart Buddy…" on the reader's own Buddy chat, and not on a project chat or a read-only Buddy history
+ chat.
+ - The dialog prefills `--chrome` from the machine agent's `launchArgs` and shows the exact detail line with the engine and
+ machine name.
+ - Pressing Restart calls `restartAgent(machineId, harnessId, launchArgs: '--chrome --x')`; on success the dialog closes.
+ - An `INVALID_LAUNCH_ARGS` result shows the daemon's detail under the field, and the dialog stays open.
+ - A failed restart shows "The Buddy didn't start with these flags. Fix or clear them and restart."
+ - `launchArgsIgnored` shows "Update Harness on <machine name> to use launch flags."
+ - Enter in the field restarts. While the request runs, the field is read-only and Restart shows progress.
+- [ ] **Step 2: Run** `cd desktop && flutter test test/super_tab_buddy_restart_test.dart`. Expected: FAIL.
+- [ ] **Step 3: Implement** the dialog and the menu item, using the copy from Global Constraints. The restart error text for
+ `INVALID_LAUNCH_ARGS` is the daemon's `detail`.
+- [ ] **Step 4: Run** the same command plus `flutter analyze`. Expected: PASS, no issues.
+- [ ] **Step 5: Commit**
+ ```bash
+ git add desktop/lib/super_tabs/buddy_restart.dart desktop/lib/super_tabs/view.dart desktop/test/super_tab_buddy_restart_test.dart
+ git commit -m "desktop: Restart Buddy with extra launch flags"
+ ```
+
+### Final checks
+
+- `cd cli && npx tsc --noEmit -p . && npx vitest run src/lib src/core && npm run test:core`
+- `cd desktop && flutter analyze && flutter test test/agent_restart_launch_args_test.dart test/super_tab_buddy_restart_test.dart`
+- Manual: on Diego's Mac, restart his Claude Buddy with `--chrome` and confirm the pane's process argv contains `--chrome`
+ (`ps`). Then restart with an empty field and confirm it is gone.
diff --git a/docs/specs/2026-11-06-buddy-launch-flags.md b/docs/specs/2026-11-06-buddy-launch-flags.md
new file mode 100644
index 000000000..5cd989cc4
--- /dev/null
+++ b/docs/specs/2026-11-06-buddy-launch-flags.md
@@ -0,0 +1,149 @@
+# Restart a Buddy with extra launch flags (Diego, 2026-11-06)
+
+## What Diego asked
+
+Restart his Buddy with extra launch flags ("extensions") that stay on, for example Claude Code's `--chrome`, so the Buddy can
+use Claude in Chrome to read his browser's tabs and their content.
+
+His choices:
+- **Free-form flags:** a text field, not a curated list.
+- **Kept:** the flags stay on every later launch of that Buddy (restart, reboot, daemon update, model switch) until he clears
+ them.
+- **Where:** a "Restart Buddy…" item in the Buddy chat's menu in Desktop.
+- **Stored on the machine** that runs the Buddy (the daemon's agent record), not in the backend.
+
+## How it works today (main 96b30cf0d)
+
+- A Buddy is an agent on the person's machine, started by the Swarm host with `agent_create` (`cli/src/superTabs/start.ts`).
+ Claude runs it with `--dangerously-skip-permissions` (`cli/src/engines/claude/launch.ts`, mode `buddy`).
+- Every relaunch rebuilds its argv from the saved record. `buildLaunchOverrides` (`cli/src/lib/launchOverrides.ts`) appends,
+ in order, the DSH args, the named agent, machine MCP servers, the Swarm's args, and last Harness's instructions (joined by
+ `joinedInstructions`). The record holds no free-form flag list. The one exception is `externalResume.session.launchArgs`,
+ the argv of an adopted outside session (`cli/src/core/agents/launch.ts`).
+- `agent_restart` (`cli/src/backendSocket.ts`, then `relaunch` in `cli/src/core/agents/launches.ts`) kills and respawns the
+ process in its pane and resumes the conversation. It takes only `agentId`.
+- Desktop: `AppNotifier.restartAgent(machineId, agentId)` sends it. The Buddy chat's menu has "Rename Buddy…" and
+ "Remove Buddy" (`desktop/lib/super_tabs/view.dart`). The Buddy bar's "Start again" removes and re-adds the Buddy.
+- Nothing in the repo uses `--chrome`.
+
+## Behaviour
+
+### Desktop
+
+- The Buddy chat's menu gains **"Restart Buddy…"** after "Rename Buddy…". It shows only on the reader's own Buddy chat
+ (`editable`), only when the Buddy has an agent on a machine.
+- It opens a dialog in the app's dialog style:
+ - Title "Restart Buddy".
+ - Field **"Extra launch flags"**, monospace, one line, prefilled with the Buddy's current flags (empty when none). Hint:
+ `--chrome`.
+ - Detail line: "Added to <engine>'s command line each time this Buddy starts on <machine name>. Your Buddy runs with full
+ permissions. Don't put secrets here: other people on that computer can see them. Clear the field to remove them."
+ - The item shows only when the Buddy has an agent on a machine (`harnessId` and `machineId` set).
+ - Buttons **Restart** (primary) and Cancel. Enter restarts.
+- Restart sends `agent_restart` with `launchArgs` to the Buddy's machine. While it runs, the button shows progress and the field
+ is read-only.
+- Results:
+ - **Restarted:** the dialog closes. The Buddy keeps its conversation.
+ - **Refused** (`INVALID_LAUNCH_ARGS`): the dialog stays open with the daemon's message under the field, for example
+ "--model is set by Harness and can't be added here.".
+ - **The engine did not start** (the restart's or resume's unconfirmed or `RESTART_FAILED` outcome): the dialog stays open with
+ "The Buddy didn't start with these flags. Fix or clear them and restart." Nothing was saved, so the Buddy keeps the flags that last worked. Each press of
+ Restart in the dialog is a new intent with its own receipt and always sends the field, so clearing it and pressing Restart
+ recovers.
+ - **Any other failure** (offline, busy, not installed, a lost reply): the dialog stays open with that failure's own text.
+ - **A stopped Buddy:** Restart resumes it with `launchArgs` (`agent_resume`).
+ - **Older daemon:** an answer with no `launchArgs` echo means that computer's Harness does not know the field and restarted
+ without the flags. The dialog stays open with "Update Harness on <machine name> to use launch flags."
+
+### Daemon (CLI)
+
+- `agent_restart` and `agent_resume` take an optional `launchArgs: string` (resume too, so a Buddy that a bad flag left
+ stopped can be brought back with the flags fixed or cleared; review of the first build):
+ - Absent: a restart as today, and the saved flags still apply.
+ - Present: parse it, validate it, save it on the agent's record (empty clears it), then restart.
+- **Parsing:** split as a POSIX shell would split words: whitespace, single and double quotes, and backslash escapes. No
+ expansion and no shell. An unclosed quote is refused.
+- **Validation** (`INVALID_LAUNCH_ARGS`, with a message naming the problem):
+ - at most 1024 characters and 20 words;
+ - no NUL or newline;
+ - every word that starts with `-` and names a flag Harness sets itself for that engine is refused. The flag is the part
+ before any `=`. The list is per engine, because the same short flag means different things: `-c` is Claude Code's
+ `--continue` but Codex's config override, which stays allowed.
+ - **Claude Code:** `--resume`, `-r`, `--continue`, `-c`, `--model`, `--permission-mode`,
+ `--dangerously-skip-permissions`, `--session-id`, `--settings`, `--setting-sources`, `--append-system-prompt`,
+ `--append-system-prompt-file`, `--system-prompt`, `--system-prompt-file`, `--mcp-config`, `--fork-session`, `--effort`.
+ - **Codex:** `--model`, `-m`, `--dangerously-bypass-approvals-and-sandbox`, `--yolo`, `--full-auto`,
+ `--ask-for-approval`, `-a`, `--sandbox`, `-s`, `--profile`, `-p`, the words `resume` and `fork`, and a `-c` /
+ `--config` whose key (before `=`, also when the value is the next word) is `model`, `model_provider`, `profile`,
+ `sandbox_mode`, `approval_policy`, `developer_instructions`, or starts with `mcp_servers` or `model_providers`.
+ - **Any other engine:** only the length, word-count and character rules.
+ - For every engine, the word `--` is refused (it would turn Harness's own later arguments into positional ones).
+ - A refused short flag with its value attached is refused too: a single-dash word whose first letter is a refused short
+ flag (Claude `-r<id>`, Codex `-mo3`, `-sdanger-full-access`).
+ - For Codex, a bare `resume` or `fork` word is refused anywhere, not only first: Codex reads it as its subcommand after
+ other flags too.
+- **Saving (audit):** the new words travel with the relaunch (in its launch source, as a retarget carries its target) and are
+ saved on the record only when the relaunch succeeds, the way `launchModel` is. A refused or failed restart or resume
+ (busy, no live process, the engine not starting with them) saves nothing, so the record keeps the flags that last worked
+ and nothing is rolled back. The record field is `launchArgs?: string[]`, never written when empty.
+- **Stopped agents:** `agent_resume` with `launchArgs` finds a stopped agent in the stopped-agents store as resume does,
+ and resumes it with the new words; the resumed row keeps them.
+- **Applying (audit):** the owner's words go LAST on the command line, after Harness's instructions, the model and the first
+ prompt, in their own slot (`ownerArgs`), so a trailing flag that takes a value fails loudly at startup instead of
+ swallowing Harness's own arguments. Each launch checks the saved words again with the same validator; if any is refused
+ (a hand-edited row, or a flag a later release refuses), none is applied and the daemon logs why. The first `agent_create`
+ never carries them.
+- **Answer:** a successful restart answers as today plus `launchArgs: string[]`, the words now saved (`[]` when cleared).
+ Desktop reads the echo to tell a new daemon from an old one.
+- **Reading them back:** the agent's frame (`agents_list` and agent pushes) carries `launchArgs` when it has any, so the
+ dialog can prefill.
+- **Audience (audit):** `launchArgs` is taken only from the machine owner's own app clients (Desktop, the web viewer); a
+ device (dial, Pro), a local tool client (an agent's own harness CLI) or anyone else gets `INVALID_LAUNCH_ARGS`. A
+ team-written agent refuses it too, as it refuses a permission change.
+
+## Design
+
+- **Growth:** at most 1 KB more on one agent record. No new files.
+- **Concurrency:** the save and the restart run in the existing restart operation, under its receipt (`creationId`). A
+ repeated request with the same receipt does not save twice.
+- **Read cost:** none. The flags are read with the record each launch.
+- **Scale:** per agent, so 10x Buddies is 10x one small field.
+- **Compatibility:**
+ - An old daemon ignores `launchArgs` and restarts without it. Desktop sees no echo and says to update Harness.
+ - An old Desktop never sends it, and the saved flags still apply.
+ - The record field is optional, so an old daemon reading a record from a newer one ignores it.
+- **Migration and rollback:** none. Rolling back the daemon leaves the field unused.
+- **Security:**
+ - The flags go to the engine as argv words, never through a shell.
+ - The Buddy already runs with full permissions on the owner's own machine, and only the owner can set its flags.
+ - The refused list keeps Harness's own session, model, permission and instruction flags from being overridden. Other flags
+ are the owner's choice and the dialog says so.
+ - The flags are logged as words only where launches are already logged.
+- **Failure:** a flag the engine rejects means the engine does not start, the restart fails as today, and the saved flags stay
+ for the owner to fix or clear.
+- **Platforms:** the CLI on macOS, Linux and Windows (Windows refuses batch-file engines' risky argv through the existing
+ `launchRefusal`), and Desktop. The web viewer gets the same menu item.
+- **Not in scope:** flags for agents other than Buddies in the UI, a curated extension list, the backend, the dial and the
+ phone.
+
+## Test
+
+- **CLI parsing and validation:**
+ - quotes, escapes and an unclosed quote;
+ - over 20 words and over 1024 characters;
+ - NUL and newline;
+ - each refused flag per engine, alone and with `=value`;
+ - Codex's `-c key=value` is allowed and Claude's `-c` is refused;
+ - empty clears.
+- **CLI restart:**
+ - `agent_restart` with `launchArgs` saves them, answers with the echo, and the respawned argv contains them after the
+ Swarm args and before the instructions;
+ - a later plain restart, a restore after daemon start, and an `agent_retarget` model switch still contain them;
+ - an empty string removes them;
+ - a team-written agent is refused;
+ - `agents_list` carries them.
+- **Desktop:**
+ - the menu item shows on the reader's own Buddy chat only;
+ - the dialog prefills the current flags;
+ - Restart sends `launchArgs`;
+ - each result above shows the text named there: refusal, did not start, and no echo means update Harness.