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.

Unify harness agent defaults, switching, and Stop/Open controls (#564)

Deef30380ce03bb
diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.ts
index 741d78d18..c57290fbb 100644
--- a/cli/src/backendSocket.spec.ts
+++ b/cli/src/backendSocket.spec.ts
@@ -2315,6 +2315,30 @@ describe('agent_restart RPC', () => {
await socket.stop()
})
+ it('binds an explicit resume permission choice to its operation receipt', async () => {
+ const { socket, frames } = localSocket()
+ const creationId = `resume-mode-${randomUUID()}`
+ const handler = vi.fn(async () => ({ ok: true as const, session: { ...BASE_SESSION, permissionMode: 'auto' }, resumed: true }))
+ socket.onResumeAgent = handler
+ vi.spyOn(registry, 'byAgent').mockReturnValue(BASE_SESSION)
+ for (const [requestId, permissionMode] of [['first', 'auto'], ['again', 'auto'], ['changed', 'ask']]) {
+ socket.handleLocalFrame('local:restart', { type: 'agent_resume', payload: { requestId, agentId: 'agent-1', creationId, permissionMode } })
+ await vi.waitFor(() => expect(frames.some(frame => (frame.payload as any).requestId === requestId)).toBe(true))
+ }
+ expect(handler).toHaveBeenCalledExactlyOnceWith('agent-1', 'auto')
+ expect(frames).toContainEqual({ type: 'agent_resume_result', payload: { requestId: 'changed', error: 'CREATION_CONFLICT' } })
+ await socket.unregisterLocalClient('local:restart'); await socket.stop()
+ })
+
+ it.each([7, '', 'allow', { auto: true }])('refuses invalid resume permission payload %j', async permissionMode => {
+ const { socket, frames } = localSocket()
+ socket.onResumeAgent = vi.fn()
+ socket.handleLocalFrame('local:restart', { type: 'agent_resume', payload: { requestId: 'bad-mode', agentId: 'agent-1', permissionMode } })
+ await vi.waitFor(() => expect(frames).toContainEqual({ type: 'agent_resume_result', payload: { requestId: 'bad-mode', error: 'INVALID_PERMISSION_MODE' } }))
+ expect(socket.onResumeAgent).not.toHaveBeenCalled()
+ await socket.unregisterLocalClient('local:restart'); await socket.stop()
+ })
+
it('replies MISSING_AGENT_ID when no agentId is given', async () => {
const { socket, frames } = localSocket()
socket.handleLocalFrame('local:restart', { type: 'agent_restart', payload: { requestId: 'r1' } })
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
index 64c644811..6290b3557 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -724,7 +724,7 @@ export class BackendSocket {
>) | null = null
/** Resume stopped work directly, or attach if it is already running. Never replaces a live
* process and never falls back to a fresh conversation. */
- onResumeAgent: BackendSocket['onRestartAgent'] = null
+ onResumeAgent: ((agentId: string, permissionMode?: string) => ReturnType<NonNullable<BackendSocket['onRestartAgent']>>) | null = null
/** Called on `agent_fork` — cli.ts opens a NEW agent that starts with `agentId`'s whole history
* (lib/forkAgent.ts) and returns its process-agent, exactly as `agent_create` does. `level` says
* what the new agent actually got: the engine's own fork, or a handoff message. */
@@ -3118,12 +3118,19 @@ export class BackendSocket {
const operation = type === 'agent_resume' ? 'resume' : 'restart'
const restart = operation === 'resume' ? this.onResumeAgent : this.onRestartAgent
if (!restart) { reply(type, requestId, { error: 'UNSUPPORTED_ON_REMOTE' }); return }
+ const permissionMode = payload.permissionMode
+ if (permissionMode !== undefined && (operation !== 'resume' || typeof permissionMode !== 'string'
+ || !['ask', 'auto', 'plan', 'full'].includes(permissionMode))) {
+ reply(type, requestId, { error: 'INVALID_PERMISSION_MODE' }); return
+ }
+ const invoke = () => permissionMode === undefined ? restart(target) : this.onResumeAgent!(target, permissionMode)
const creationId = payload.creationId
if (creationId !== undefined) {
if (!validCreationId(creationId)) { reply(type, requestId, { error: 'INVALID_CREATION_ID' }); return }
try {
- void this.agentCreations.run(creationId, creationFingerprint({ operation, agentId: target }), async () => {
- const result = await restart(target)
+ void this.agentCreations.run(creationId, creationFingerprint({ operation, agentId: target,
+ ...(permissionMode === undefined ? {} : { permissionMode }) }), 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
// replace that process again when a caller checks this intent.
@@ -3137,7 +3144,7 @@ export class BackendSocket {
}
return
}
- const result = await restart(target)
+ const result = await invoke()
if (!result.ok) {
reply(type, requestId, result.detail ? { error: result.error, detail: result.detail } : { error: result.error })
return
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index 10619a969..cc3f543fa 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -97,6 +97,7 @@ import { PairControl, StartedHarnesses } from './pair/control.js'
import { PairToken } from './pair/token.js'
import { pairCommand as pairControlCommand, pairRequest, pairVerb, type PairClientDeps } from './pair/client.js'
import { serveMcp } from './pair/mcp.js'
+import { DEFAULT_HARNESS_PERMISSION, freshHarnessEnvironment } from './lib/harnessDefaults.js'
import { PairHarness, type PairEngine } from './pair/pairHarness.js'
import { CompanionIntelligence } from './pair/intelligence.js'
import { CodingMemoryRuntime } from './memory/runtime.js'
@@ -4882,14 +4883,14 @@ async function runForeground(session: AuthSession | null): Promise<void> {
})
backend.pairControl = pairControl
// THE PAIR HARNESS (pair/pairHarness.ts): the daemon as a conversation, started or resumed when you talk
- // to it, paused when idle. Mode ask, the harnessd MCP server injected, a fresh token every launch.
+ // to it, stopped when idle. Automatic approvals, scoped harnessd MCP, a fresh token every launch.
const pairHarness = new PairHarness({
pairedDaemon: () => pairSensor.pairedDaemon(),
pairedName: () => pairSensor.pairedName(),
pairedUid: () => zooPair.known ? companionZoo.identity?.uid ?? null : guestCompanion?.uid ?? null,
collectionUids: () => zooPair.known ? companionZoo.uids : guestCompanion ? [guestCompanion.uid] : [],
engine: async (preferred) => {
- if (!preferred) return null // A new collection chooses its engine in the viewer.
+ preferred ??= 'opencode' // New collections share the product default.
const found = await probeEngines([preferred]).catch(() => [])
return found.some(e => e.engine === preferred && e.installed) ? preferred : null
},
@@ -4906,14 +4907,14 @@ async function runForeground(session: AuthSession | null): Promise<void> {
find: () => {
const live = registry.advertised()
return [
- ...live.filter((s) => s.dsh === PAIR_HARNESS_DSH).map((s) => ({ agentId: s.agentId, status: 'live' as const, engine: s.engine as PairEngine, hasConversation: !!s.sessionId })),
- ...stoppedAgents.available(live).filter((s) => s.dsh === PAIR_HARNESS_DSH).map((s) => ({ agentId: s.agentId, status: 'stopped' as const, engine: s.engine as PairEngine, hasConversation: !!s.sessionId })),
+ ...live.filter((s) => s.dsh === PAIR_HARNESS_DSH).map((s) => ({ agentId: s.agentId, status: 'live' as const, engine: s.engine as PairEngine, cwd: s.cwd, hasConversation: !!s.sessionId })),
+ ...stoppedAgents.available(live).filter((s) => s.dsh === PAIR_HARNESS_DSH).map((s) => ({ agentId: s.agentId, status: 'stopped' as const, engine: s.engine as PairEngine, cwd: s.cwd, hasConversation: !!s.sessionId })),
]
},
create: async ({ engine, cwd, prompt, name }) => {
if (!backend.onCreateAgent) return { ok: false, error: 'UNSUPPORTED' }
const created = await backend.onCreateAgent({
- engine, cwd, bypassPermission: false, permissionMode: 'ask', grid: null, codexHome: null,
+ engine, cwd, bypassPermission: true, permissionMode: DEFAULT_HARNESS_PERMISSION, grid: null, codexHome: null,
dsh: PAIR_HARNESS_DSH, prompt, name, agent: null,
})
return created.ok ? { ok: true, agentId: created.session.agentId } : created
@@ -4923,7 +4924,14 @@ async function runForeground(session: AuthSession | null): Promise<void> {
const resumed = await backend.onResumeAgent(agentId)
return resumed.ok ? { ok: true } : resumed
},
- stop: async (agentId) => { await backend.onDeleteAgent?.(agentId) },
+ stop: async (agentId) => {
+ const current = registry.byAgent(agentId)
+ if (!current) return
+ if (!backend.closeAgentService) throw new Error('Safe close is unavailable.')
+ const result = await backend.closeAgentService.request({ agentId, sessionId: current.sessionId,
+ createdAt: new Date(current.registeredAt).toISOString(), mode: 'now' })
+ if (!result.closed) throw new Error(result.detail ?? 'Could not save and stop the companion.')
+ },
send: (agentId, text) => backend.onMessage?.(agentId, text, randomUUID()),
working: (agentId) => {
const sessionId = registry.resolve(agentId)?.sessionId
@@ -6391,7 +6399,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {
cwd,
sessionLabel: label,
argv,
- env: mergedLaunchEnv(gridLaunch?.env ?? (codexHome ? { CODEX_HOME: codexHome } : undefined), dshEnv),
+ env: freshHarnessEnvironment(engine, mergedLaunchEnv(gridLaunch?.env ?? (codexHome ? { CODEX_HOME: codexHome } : undefined), dshEnv), !!grid || !!resumeSessionId,
+ permissionMode ?? (bypassPermission ? DEFAULT_HARNESS_PERMISSION : 'ask')),
grid: grid ? { baseUrl: grid.baseUrl, model: grid.model ?? null } : null,
gridLaunchRecord: grid && gridLaunch ? { override: grid, webSearch: gridLaunch.webSearch } : null,
codexHome,
diff --git a/cli/src/engines/opencode/tuiFlags.spec.ts b/cli/src/engines/opencode/tuiFlags.spec.ts
index e5724a849..3a2792339 100644
--- a/cli/src/engines/opencode/tuiFlags.spec.ts
+++ b/cli/src/engines/opencode/tuiFlags.spec.ts
@@ -7,7 +7,7 @@
* flag a release drops fails here instead of in someone's pane. Skipped where opencode is not
* installed.
*/
-import { execFileSync } from 'node:child_process'
+import { spawnSync } from 'node:child_process'
import { describe, expect, it } from 'vitest'
import { buildEngineCommandArgv, namedAgentArgs, supportsNamedAgent } from '../../lib/engineLaunch.js'
import { buildLaunchOverrides, type LaunchOverridesDeps, type LaunchSource } from '../../lib/launchOverrides.js'
@@ -17,7 +17,11 @@ import { opencodeMajorVersion } from './version.js'
const installed = binaryOnPath('opencode')
describe.skipIf(!installed)('the installed opencode TUI accepts every flag we pass it', () => {
- const help = installed ? execFileSync('opencode', ['--help'], { encoding: 'utf8', timeout: 15_000 }) : ''
+ const helpResult = installed ? spawnSync('opencode', ['--help'], { encoding: 'utf8', timeout: 15_000 }) : null
+ if (helpResult?.error) throw helpResult.error
+ if (helpResult && helpResult.status !== 0) throw new Error(`opencode --help exited ${helpResult.status}: ${helpResult.stderr}`)
+ // v1 writes help to stderr; v2 uses stdout. Verify the actual flags from either stream.
+ const help = helpResult ? `${helpResult.stdout}\n${helpResult.stderr}` : ''
const major = installed ? opencodeMajorVersion() : null
const deps: LaunchOverridesDeps = {
machine: () => ({ hermesSystemManaged: false, opencodeMajor: major }),
diff --git a/cli/src/lib/harnessDefaults.spec.ts b/cli/src/lib/harnessDefaults.spec.ts
new file mode 100644
index 000000000..e45f93138
--- /dev/null
+++ b/cli/src/lib/harnessDefaults.spec.ts
@@ -0,0 +1,37 @@
+import { expect, it } from 'vitest'
+import { freshHarnessEnvironment, DEFAULT_HARNESS_MODEL, DEFAULT_HARNESS_EFFORT } from './harnessDefaults.js'
+
+it('selects Muse for fresh OpenCode harnesses while retaining package tools', () => {
+ const mcp = { harnessd: { type: 'local', command: ['harness', 'pair', 'mcp'] } }
+ const env = freshHarnessEnvironment('opencode', { OPENCODE_CONFIG_CONTENT: JSON.stringify({ mcp }), TOKEN_FILE: '/token' })
+ expect(JSON.parse(env.OPENCODE_CONFIG_CONTENT!)).toMatchObject({
+ mcp, permission: 'allow', model: DEFAULT_HARNESS_MODEL, small_model: DEFAULT_HARNESS_MODEL,
+ provider: { opencode: { models: { 'muse-spark-1.3-contributor-free': { options: { reasoningEffort: DEFAULT_HARNESS_EFFORT } } } } },
+ agent: { build: { model: DEFAULT_HARNESS_MODEL, variant: 'xhigh' }, plan: { model: DEFAULT_HARNESS_MODEL, variant: 'xhigh' } },
+ })
+ expect(env.TOKEN_FILE).toBe('/token')
+})
+
+it('retains explicit tool denials and custom provider and agent settings', () => {
+ const config = {
+ permission: { bash: { 'rm *': 'deny' } },
+ provider: { opencode: { options: { timeout: 5000 }, models: { 'muse-spark-1.3-contributor-free': { options: { temperature: 0.4 } } } } },
+ agent: { build: { prompt: 'Project instructions' } },
+ }
+ const result = JSON.parse(freshHarnessEnvironment('opencode', { OPENCODE_CONFIG_CONTENT: JSON.stringify(config) }).OPENCODE_CONFIG_CONTENT!)
+ expect(result.permission).toEqual({ '*': 'allow', bash: { 'rm *': 'deny' } })
+ expect(result.provider.opencode).toMatchObject({ options: { timeout: 5000 }, models: { 'muse-spark-1.3-contributor-free': { options: { temperature: 0.4, reasoningEffort: 'xhigh' } } } })
+ expect(result.agent.build.prompt).toBe('Project instructions')
+})
+
+it('honours an explicit Ask choice instead of enabling automatic approvals', () => {
+ const result = JSON.parse(freshHarnessEnvironment('opencode', {}, false, 'ask').OPENCODE_CONFIG_CONTENT!)
+ expect(result.permission).toBe('ask')
+ expect(result.model).toBe(DEFAULT_HARNESS_MODEL)
+})
+
+it('does not replace an explicit route, a restored conversation, or another agent', () => {
+ const env = { OPENCODE_CONFIG_CONTENT: '{"model":"custom/chosen"}' }
+ expect(freshHarnessEnvironment('opencode', env, true)).toBe(env)
+ expect(freshHarnessEnvironment('codex', env)).toBe(env)
+})
diff --git a/cli/src/lib/harnessDefaults.ts b/cli/src/lib/harnessDefaults.ts
new file mode 100644
index 000000000..8e4b56a0f
--- /dev/null
+++ b/cli/src/lib/harnessDefaults.ts
@@ -0,0 +1,43 @@
+import type { AgentEngine } from '../engines/types.js'
+
+export const DEFAULT_HARNESS_ENGINE = 'opencode' as const
+export const DEFAULT_HARNESS_MODEL = 'opencode/muse-spark-1.3-contributor-free'
+export const DEFAULT_HARNESS_EFFORT = 'xhigh'
+export const DEFAULT_HARNESS_PERMISSION = 'auto'
+
+function opencodePermission(config: Record<string, any>, permissionMode: string) {
+ return permissionMode === 'ask' ? 'ask'
+ : typeof config.permission === 'object' && config.permission !== null
+ ? { '*': 'allow', ...config.permission } : 'allow'
+}
+
+/** Apply an explicit permission change without replacing the conversation's model or tools. */
+export function harnessPermissionEnvironment(engine: AgentEngine, env: Record<string, string>, permissionMode: string): Record<string, string> {
+ if (engine !== 'opencode') return env
+ const config = JSON.parse(env.OPENCODE_CONFIG_CONTENT || '{}')
+ return { ...env, OPENCODE_CONFIG_CONTENT: JSON.stringify({ ...config, permission: opencodePermission(config, permissionMode) }) }
+}
+
+/** Fresh own-provider launches only. Restores and explicit model routes keep their choices. */
+export function freshHarnessEnvironment(engine: AgentEngine, env: Record<string, string> = {},
+ explicitRoute = false, permissionMode = DEFAULT_HARNESS_PERMISSION): Record<string, string> {
+ if (engine !== DEFAULT_HARNESS_ENGINE || explicitRoute) return env
+ const config = JSON.parse(env.OPENCODE_CONFIG_CONTENT || '{}')
+ const modelId = DEFAULT_HARNESS_MODEL.split('/')[1]!
+ const provider = config.provider?.opencode ?? {}
+ const model = provider.models?.[modelId] ?? {}
+ return { ...env, OPENCODE_CONFIG_CONTENT: JSON.stringify({
+ ...config,
+ permission: opencodePermission(config, permissionMode),
+ model: DEFAULT_HARNESS_MODEL,
+ small_model: DEFAULT_HARNESS_MODEL,
+ provider: { ...config.provider, opencode: { ...provider, models: {
+ ...provider.models,
+ [modelId]: { ...model, options: { ...model.options, reasoningEffort: DEFAULT_HARNESS_EFFORT } },
+ } } },
+ agent: { ...config.agent,
+ build: { ...config.agent?.build, model: DEFAULT_HARNESS_MODEL, variant: DEFAULT_HARNESS_EFFORT },
+ plan: { ...config.agent?.plan, model: DEFAULT_HARNESS_MODEL, variant: DEFAULT_HARNESS_EFFORT },
+ },
+ }) }
+}
diff --git a/cli/src/lib/resumeAgentService.spec.ts b/cli/src/lib/resumeAgentService.spec.ts
index 45b465122..0cb8bc429 100644
--- a/cli/src/lib/resumeAgentService.spec.ts
+++ b/cli/src/lib/resumeAgentService.spec.ts
@@ -11,7 +11,7 @@ import { AgentRestartCoordinator } from './restartAgent.js'
import { checkPidRuntime } from './deleteAgentFallback.js'
import { listTmuxPanes } from './tmuxAgentDiscovery.js'
import { checkSessionRuntime, clearPaneRemainOnExit, resolvePaneEngineProcess, tmuxPaneState } from './tmux.js'
-import { buildEngineLaunchArgv } from './engineLaunch.js'
+import { buildEngineLaunchArgv, refusePermissionFlagIfUnsupported } from './engineLaunch.js'
import { enginePathOverride } from './engineBin.js'
import { installedDsh } from '../dsh/installed.js'
@@ -26,6 +26,7 @@ vi.mock('./engineLaunch.js', async importOriginal => ({
...(await importOriginal<typeof import('./engineLaunch.js')>()),
buildEngineLaunchArgv: vi.fn(() => ['fixture-engine']),
dropPermissionFlagIfUnsupported: vi.fn(async (_engine: unknown, choice: unknown) => ({ choice, droppedFlag: null })),
+ refusePermissionFlagIfUnsupported: vi.fn(async () => null),
}))
vi.mock('./engineBin.js', () => ({ enginePathOverride: vi.fn(() => undefined) }))
vi.mock('./engineInstall.js', () => ({ engineInstallRecipe: () => ({ command: 'fixture-install' }) }))
@@ -60,6 +61,7 @@ beforeEach(() => {
kill.mockReset().mockResolvedValue({ state: 'succeeded' })
vi.mocked(validTranscriptPath).mockReturnValue(true)
vi.mocked(enginePathOverride).mockReturnValue(undefined)
+ vi.mocked(refusePermissionFlagIfUnsupported).mockReset().mockResolvedValue(null)
vi.mocked(installedDsh).mockReturnValue(undefined)
vi.mocked(listTmuxPanes).mockReset().mockResolvedValue(inventory())
vi.mocked(checkPidRuntime).mockReset().mockResolvedValue({ state: 'gone', reason: 'fixture' })
@@ -82,6 +84,52 @@ beforeEach(() => {
afterEach(() => { vi.useRealTimers(); for (const row of registry.list()) registry.removeAgent(row.agentId); rmSync(dir, { recursive: true, force: true }) })
describe('production resume handler', () => {
+ it.each(['auto', 'ask'])('resumes the same conversation with an explicit %s permission choice', async permissionMode => {
+ rewrite({ engine: 'opencode', permissionMode: permissionMode === 'auto' ? 'ask' : 'auto' })
+ vi.mocked(deps.relaunchOverrides).mockResolvedValue({ ok: true, overrides: {
+ env: { OPENCODE_CONFIG_CONTENT: JSON.stringify({ model: 'custom/kept', permission: 'ask', mcp: { custom: { enabled: true } } }) },
+ extraArgs: [], clearEnv: [],
+ } })
+ const result = await createResumeAgentService(deps)(saved.agentId, permissionMode)
+ expect(result).toMatchObject({ ok: true, resumed: true, session: { agentId: saved.agentId, sessionId: saved.sessionId,
+ permissionMode, bypassPermission: permissionMode === 'auto' } })
+ expect(buildEngineLaunchArgv).toHaveBeenCalledWith('opencode', expect.objectContaining({
+ permissionMode, bypassPermission: permissionMode === 'auto', resumeSessionId: saved.sessionId,
+ }))
+ expect(JSON.parse(create.mock.calls[0][0].env.OPENCODE_CONFIG_CONTENT)).toEqual({
+ model: 'custom/kept', permission: permissionMode === 'auto' ? 'allow' : 'ask', mcp: { custom: { enabled: true } },
+ })
+ registry.load()
+ expect(registry.byAgent(saved.agentId)?.permissionMode).toBe(permissionMode)
+ })
+
+ it('refuses an unsupported explicit permission choice before allocating a pane', async () => {
+ rewrite({ engine: 'opencode', permissionMode: 'ask' })
+ expect(await createResumeAgentService(deps)(saved.agentId, 'full')).toMatchObject({ error: 'INVALID_PERMISSION_MODE' })
+ vi.mocked(refusePermissionFlagIfUnsupported).mockResolvedValue({ error: 'CODEX_CLI_TOO_OLD', detail: 'Update OpenCode.' })
+ expect(await createResumeAgentService(deps)(saved.agentId, 'auto')).toMatchObject({ error: 'CODEX_CLI_TOO_OLD' })
+ expect(create).not.toHaveBeenCalled()
+ expect(deps.stoppedAgents.get(saved.agentId)?.permissionMode).toBe('ask')
+ })
+
+ it('does not claim a permission change when Open attaches to a running process', async () => {
+ rewrite({ engine: 'opencode', permissionMode: 'ask' })
+ live({ resumeOnly: undefined, permissionMode: 'ask' })
+ vi.mocked(checkPidRuntime).mockResolvedValue({ state: 'alive' })
+ expect(await createResumeAgentService(deps)(saved.agentId, 'auto')).toMatchObject({ error: 'PERMISSION_CHANGE_REQUIRES_STOP' })
+ expect(create).not.toHaveBeenCalled()
+ expect(registry.byAgent(saved.agentId)?.permissionMode).toBe('ask')
+ })
+
+ it('does not join concurrent Open requests with different permission choices', 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, 'ask')
+ expect(await resume(saved.agentId, 'auto')).toMatchObject({ error: 'AGENT_BUSY' })
+ stop.resolve(); expect(await first).toMatchObject({ ok: true })
+ expect(create).toHaveBeenCalledTimes(1)
+ })
+
it.each(['claude', 'codex'] as const)('resumes exact %s conversation on a new route and persists it', async engine => {
rewrite({ engine, codexHome: '/profile', permissionMode: 'plan', bypassPermission: true, dsh: 'fixture' })
vi.mocked(installedDsh).mockReturnValue({} as any)
diff --git a/cli/src/lib/resumeAgentService.ts b/cli/src/lib/resumeAgentService.ts
index 859f79fe6..cb09940ef 100644
--- a/cli/src/lib/resumeAgentService.ts
+++ b/cli/src/lib/resumeAgentService.ts
@@ -9,12 +9,13 @@ import { checkSessionRuntime, clearPaneRemainOnExit, resolvePaneEngineProcess, t
import { listTmuxPanes } from './tmuxAgentDiscovery.js'
import { enginePathOverride } from './engineBin.js'
import { engineInstallRecipe } from './engineInstall.js'
-import { buildEngineLaunchArgv, dropPermissionFlagIfUnsupported } from './engineLaunch.js'
+import { buildEngineLaunchArgv, dropPermissionFlagIfUnsupported, permissionModeApproves, permissionModeFlags, refusePermissionFlagIfUnsupported } from './engineLaunch.js'
import { workspaceMissing } from './workspaceCheck.js'
import { buildHarnessSessionLabel } from './harnessSessionLabel.js'
import { createAndRegisterPane, type CreateAgentPaneDeps } from './createAgentPane.js'
import type { LaunchOverrides, LaunchOverridesResult } from './launchOverrides.js'
import type { AgentRestartCoordinator } from './restartAgent.js'
+import { harnessPermissionEnvironment } from './harnessDefaults.js'
export interface ResumeAgentServiceDeps {
registry: Pick<typeof liveRegistry, 'byAgent' | 'bySession' | 'resumePendingAgent' | 'setLaunch' | 'updateProcessIdentity'>
@@ -124,7 +125,7 @@ export function createResumeAgentService(deps: ResumeAgentServiceDeps) {
return result
}
- const resumeStopped = (agentId: string, current: () => boolean) => resumeStoppedAgent({
+ const resumeStopped = (agentId: string, current: () => boolean, permissionMode?: string) => resumeStoppedAgent({
live: () => registry.byAgent(agentId),
saved: () => stoppedAgents.get(agentId),
current,
@@ -155,6 +156,16 @@ export function createResumeAgentService(deps: ResumeAgentServiceDeps) {
},
launch: async (saved, resumeSessionId) => {
if (!tmuxBackend) return { ok: false, error: 'TMUX_UNAVAILABLE' }
+ // An explicit change is checked before allocating anything, and is persisted with the
+ // resumed row. Ordinary Open keeps the saved mode, including the older-engine fallback.
+ if (permissionMode !== undefined) {
+ if (!permissionModeFlags(saved.engine, permissionMode)) return { ok: false, error: 'INVALID_PERMISSION_MODE' }
+ const choice = { permissionMode, bypassPermission: permissionModeApproves(permissionMode) }
+ const refusal = await refusePermissionFlagIfUnsupported(saved.engine, choice)
+ if (refusal) return { ok: false, ...refusal }
+ if (!current()) return resumeChanged
+ saved = { ...saved, ...choice }
+ }
if (saved.grid && !saved.gridLaunch) return { ok: false, error: 'GRID_CREDENTIAL_REQUIRED', detail: 'The saved provider configuration is unavailable.' }
if (saved.dsh && !installedDsh(saved.dsh)) return { ok: false, error: 'INVALID_DSH', detail: 'Install this harness from the Harness Store before resuming it.' }
if (!saved.cwd) return { ok: false, error: 'CWD_NOT_FOUND', detail: 'The saved project folder is no longer available.' }
@@ -188,14 +199,19 @@ export function createResumeAgentService(deps: ResumeAgentServiceDeps) {
}
}
if (saved.sessionId && registry.bySession(saved.sessionId)) return { ok: false, error: 'AGENT_BUSY' }
- const { env: launchEnv, extraArgs, clearEnv } = built.overrides
+ const { extraArgs, 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
// the mode the way they are waiting on the harness, so the flag goes and the launch stays
// (openharness#285). The row keeps its recorded mode; discovery re-derives the live one.
- const { choice: permission, droppedFlag } = await dropPermissionFlagIfUnsupported(saved.engine, {
+ const savedPermission = {
permissionMode: saved.permissionMode ?? null,
bypassPermission: saved.bypassPermission === true,
- })
+ }
+ const { choice: permission, droppedFlag } = permissionMode === undefined
+ ? await dropPermissionFlagIfUnsupported(saved.engine, savedPermission)
+ : { choice: savedPermission, droppedFlag: null }
if (droppedFlag) {
console.warn(`[resume] ${sid(saved.agentId)} · ${saved.engine} does not take ${droppedFlag}`
+ ` · resuming in Ask · update ${saved.engine} to get ${saved.permissionMode ?? 'Auto'} back`)
@@ -259,11 +275,17 @@ export function createResumeAgentService(deps: ResumeAgentServiceDeps) {
},
})
- return (agentId: string) => restartJobs.run(agentId, async current => {
+ return (agentId: string, permissionMode?: string) => restartJobs.run(agentId, async current => {
await stopJobs.get(agentId)
if (!current()) return resumeChanged
if (pinnedControls.has(agentId)) return { ok: false, error: 'AGENT_BUSY' }
- return resumeStopped(agentId, current)
- }, 'resume')
+ const result = await resumeStopped(agentId, current, permissionMode)
+ // 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}`)
}
diff --git a/cli/src/lib/stopAgentService.ts b/cli/src/lib/stopAgentService.ts
index fb3e4e34b..be0601c21 100644
--- a/cli/src/lib/stopAgentService.ts
+++ b/cli/src/lib/stopAgentService.ts
@@ -68,7 +68,7 @@ export function createStopAgentService(deps: StopAgentServiceDeps) {
// Discovery or a hook may have updated this row while reading the native store.
// A replacement process must never be stopped using an older snapshot.
if (!sameTarget() || options.current?.() === false) {
- throw new AgentStopError('Harness changed while saving its conversation. Try pausing again.')
+ throw new AgentStopError('Harness changed while saving its conversation. Try stopping again.')
}
const current = registry.resolve(sessionId)!
const s = current.sessionId && current.sessionId !== captured.sessionId ? { ...current } : { ...current, sessionId: captured.sessionId,
@@ -78,7 +78,7 @@ export function createStopAgentService(deps: StopAgentServiceDeps) {
await options.checkpoint?.(s, 'before')
await options.beforeStop?.(s)
if (!sameTarget() || options.current?.() === false) {
- throw new AgentStopError('Harness changed while saving its conversation. Try pausing again.')
+ throw new AgentStopError('Harness changed while saving its conversation. Try stopping again.')
}
const routes = s.runtimes.map(terminalRouteKey)
for (const route of routes) agentReconciler.holdRoute(route)
@@ -99,7 +99,7 @@ export function createStopAgentService(deps: StopAgentServiceDeps) {
log: message => console.log(message),
}, 0)).catch(() => 'failed' as const)
if (termination === 'failed' || termination === 'not-ours') {
- throw new AgentStopError('Could not confirm that the harness stopped. Its saved conversation is safe. Try pausing again.')
+ throw new AgentStopError('Could not confirm that the harness stopped. Its saved conversation is safe. Try stopping again.')
}
// Never close a replacement's pane, even when our old process exited.
if (!sameTarget() || options.current?.() === false) {
@@ -114,7 +114,7 @@ export function createStopAgentService(deps: StopAgentServiceDeps) {
.map(runtime => tmuxBackend.kill(runtime)) : [])
if (panes.some(result => result.status !== 'fulfilled' || result.value.state !== 'succeeded')
|| (isTerminalEngine(s.engine) && !panes.length)) {
- throw new AgentStopError('Could not confirm that the harness stopped. Its saved conversation is safe. Try pausing again.')
+ throw new AgentStopError('Could not confirm that the harness stopped. Its saved conversation is safe. Try stopping again.')
}
if (!sameTarget()) {
throw new AgentStopError('The harness changed while pausing. Check its current state before trying again.')
diff --git a/cli/src/pair/brain.ts b/cli/src/pair/brain.ts
index 7cf2ee527..d9e6c9b6f 100644
--- a/cli/src/pair/brain.ts
+++ b/cli/src/pair/brain.ts
@@ -90,7 +90,7 @@ export interface PairBrainDeps {
/** `daemon_talk`: the person's words to the pair harness (pair/pairHarness.ts), which starts or wakes. */
talk?: (text: string, companionUid?: string) => Promise<Record<string, unknown>>
/** Open the pair's terminal without typing into it or starting a model turn. */
- open?: (companionUid?: string, engine?: 'claude' | 'codex') => Promise<Record<string, unknown>>
+ open?: (companionUid?: string, engine?: 'claude' | 'codex' | 'opencode') => Promise<Record<string, unknown>>
/** The collection's persistent agent and its observed model. Local windows only. */
companionHarness?: () => Record<string, unknown>
/** How many keys may be relayed to other machines, per window (RELAY_LIMITS unless a spec says). */
@@ -534,7 +534,7 @@ export class PairBrain {
const uid = str(payload.companionUid, 64)
if (!uid) { reply({ ok: false, error: 'STALE_COMPANION' }); return }
const engine = payload.engine
- if (engine !== undefined && engine !== 'claude' && engine !== 'codex') { reply({ ok: false, error: 'BAD_ENGINE' }); return }
+ if (engine !== undefined && engine !== 'claude' && engine !== 'codex' && engine !== 'opencode') { reply({ ok: false, error: 'BAD_ENGINE' }); return }
const result = await this.deps.open(uid, engine).catch((err): Record<string, unknown> => ({ ok: false, error: 'FAILED', detail: err instanceof Error ? err.message.slice(0, 200) : undefined }))
reply(result)
}
diff --git a/cli/src/pair/pairHarness.engine.spec.ts b/cli/src/pair/pairHarness.engine.spec.ts
index 0157c3ffd..2eea60038 100644
--- a/cli/src/pair/pairHarness.engine.spec.ts
+++ b/cli/src/pair/pairHarness.engine.spec.ts
@@ -19,9 +19,9 @@ function world() {
mcpCommand: () => ['/bin/harness'], token: new PairToken(join(dir, 'token')),
workspace: join(dir, 'workspace'), stateFile: join(dir, 'harness.json'),
install: vi.fn(() => true), find: () => rows,
- create: vi.fn<PairHarnessDeps['create']>(async ({ engine }) => {
+ create: vi.fn<PairHarnessDeps['create']>(async ({ engine, cwd }) => {
const agentId = `agent-${rows.length + 1}`
- rows.push({ agentId, engine, status: 'live', hasConversation: true })
+ rows.push({ agentId, engine, cwd, status: 'live', hasConversation: true })
return { ok: true, agentId }
}),
resume: vi.fn<PairHarnessDeps['resume']>(async id => { rows.find(r => r.agentId === id)!.status = 'live'; return { ok: true } }),
@@ -31,10 +31,8 @@ function world() {
return { deps, rows, harness: new PairHarness(deps), select: (id: string) => { uid = id } }
}
-it('asks for the first engine, remembers the choice, and resumes each engine’s own transcript', async () => {
+it('remembers the explicit choice and starts a fresh conversation when switching agents', async () => {
const w = world()
- expect(await w.harness.open('tim-one')).toMatchObject({ error: 'ENGINE_REQUIRED' })
- expect(w.deps.create).not.toHaveBeenCalled()
await w.harness.open('tim-one', 'claude')
expect(w.harness.learningScope()).toBe('agent-1')
await w.harness.open('tim-one', 'codex')
@@ -47,24 +45,25 @@ it('asks for the first engine, remembers the choice, and resumes each engine’s
await restarted.open('gnu-one')
expect(restarted.engine()).toBe('codex')
expect(w.deps.create).toHaveBeenCalledTimes(2)
- expect(await restarted.open('gnu-one', 'claude')).toMatchObject({ resumed: true, agentId: 'agent-1' })
+ expect(await restarted.open('gnu-one', 'claude')).toMatchObject({ started: true, agentId: 'agent-3' })
expect(restarted.learningScope()).toBe('agent-1')
expect(w.deps.send).not.toHaveBeenCalled()
const saved = JSON.parse(readFileSync(w.deps.stateFile, 'utf8'))
- expect(saved.collections).toHaveLength(2)
+ expect(saved.collections).toHaveLength(3)
expect(saved.engine).toBe('claude')
})
-it('keeps an unavailable or busy engine choice from interrupting the current conversation', async () => {
+it('rejects an unavailable choice, then saves and switches even during a turn', async () => {
const w = world()
await w.harness.open('tim-one', 'claude')
vi.mocked(w.deps.engine).mockResolvedValue(null)
expect(await w.harness.open('tim-one', 'codex')).toMatchObject({ error: 'NO_ENGINE' })
expect(w.deps.stop).not.toHaveBeenCalled()
w.deps.working = () => true
- expect(await w.harness.open('tim-one', 'codex')).toMatchObject({ error: 'BUSY' })
- expect(w.harness.engine()).toBe('claude')
- expect(w.deps.stop).not.toHaveBeenCalled()
+ vi.mocked(w.deps.engine).mockResolvedValue('codex')
+ expect(await w.harness.open('tim-one', 'codex')).toMatchObject({ ok: true, started: true })
+ expect(w.harness.engine()).toBe('codex')
+ expect(w.deps.stop).toHaveBeenCalledWith('agent-1')
})
it('does not substitute a different engine if discovery returns the wrong one', async () => {
@@ -98,7 +97,16 @@ it('isolates engine preferences, transcripts and review scopes between collectio
expect(w.harness.engine()).toBe('codex')
expect(w.harness.learningScope()).toBe('agent-1')
await w.harness.open('tim-one', 'claude')
- expect(w.harness.agentId()).toBe('agent-1')
+ expect(w.harness.agentId()).toBe('agent-4')
+})
+
+it('keeps the same folder when a different member of the collection changes agent', async () => {
+ const w = world()
+ await w.harness.open('tim-one', 'claude')
+ const folder = w.rows[0].cwd
+ w.select('gnu-one')
+ await w.harness.open('gnu-one', 'codex')
+ expect(w.rows[1].cwd).toBe(folder)
})
it('does not bind a late engine launch to another account', async () => {
@@ -115,3 +123,19 @@ it('does not bind a late engine launch to another account', async () => {
expect(w.deps.stop).toHaveBeenCalledWith('late-codex')
expect(w.harness.agentId()).toBeNull()
})
+
+it('uses OpenCode for a new collection without submitting a prompt', async () => {
+ const w = world()
+ expect(await w.harness.open('tim-one')).toMatchObject({ ok: true, started: true })
+ expect(w.deps.create).toHaveBeenCalledWith(expect.objectContaining({ engine: 'opencode', prompt: '' }))
+ expect(w.deps.send).not.toHaveBeenCalled()
+})
+
+it('does not create a replacement if saving and stopping fails', async () => {
+ const w = world()
+ await w.harness.open('tim-one', 'claude')
+ vi.mocked(w.deps.stop).mockRejectedValue(new Error('Could not save'))
+ await expect(w.harness.open('tim-one', 'codex')).rejects.toThrow('Could not save')
+ expect(w.deps.create).toHaveBeenCalledTimes(1)
+ expect(w.harness.engine()).toBe('claude')
+})
diff --git a/cli/src/pair/pairHarness.more.spec.ts b/cli/src/pair/pairHarness.more.spec.ts
index c63c16ad2..0aed943ce 100644
--- a/cli/src/pair/pairHarness.more.spec.ts
+++ b/cli/src/pair/pairHarness.more.spec.ts
@@ -27,7 +27,7 @@ function world(over: Partial<PairHarnessDeps> = {}) {
const token = new PairToken(join(dir, 'pair', 'token'))
const deps: PairHarnessDeps = {
pairedDaemon: () => 'tim',
- engine: async () => 'claude',
+ engine: async preferred => preferred ?? 'opencode',
mcpCommand: () => ['/bin/harness'],
token,
workspace: join(dir, 'pair', 'workspace'),
@@ -89,7 +89,7 @@ describe('the instructions and the package', () => {
let uid = 'tim-one'
let release!: () => void
const ready = new Promise<void>(resolve => { release = resolve })
- const w = world({ pairedUid: () => uid, engine: async () => { await ready; return 'claude' } })
+ const w = world({ pairedUid: () => uid, engine: async () => { await ready; return 'opencode' } })
expect(await w.harness.talk('for a different friend', 'tim-other')).toMatchObject({ error: 'STALE_COMPANION' })
const pending = w.harness.talk('for Tim', 'tim-one')
await Promise.resolve()
@@ -154,7 +154,7 @@ describe('the instructions and the package', () => {
it('keeps the package name within 40 characters', () => {
const manifest = JSON.parse(pairPackage({ daemonId: 'x'.repeat(60), engine: 'codex', mcpCommand: ['h'], tokenFile: '/t' })['harness.json']!.content)
expect(manifest.name).toBe('Companions')
- expect(manifest.agent.env.DSH_PERMISSION_MODE).toBe('ask')
+ expect(manifest.agent.env.DSH_PERMISSION_MODE).toBe('auto')
})
})
@@ -201,7 +201,7 @@ describe('talk, when something fails', () => {
})
it('discovering another engine does not replace a paused collection', async () => {
- let engine: 'claude' | 'codex' = 'claude'
+ let engine: 'opencode' | 'codex' = 'opencode'
const w = world({ engine: async () => engine })
await w.harness.talk('hi')
w.rows[0].status = 'stopped'
@@ -212,7 +212,7 @@ describe('talk, when something fails', () => {
})
it('a package revision does not attempt to stop or replace a live collection', async () => {
- let engine: 'claude' | 'codex' = 'claude'
+ let engine: 'opencode' | 'codex' = 'opencode'
const w = world({ engine: async () => engine, stop: vi.fn(async () => { throw new Error('busy') }) })
await w.harness.talk('hi')
engine = 'codex'
diff --git a/cli/src/pair/pairHarness.spec.ts b/cli/src/pair/pairHarness.spec.ts
index 38887ea97..8ce9c7696 100644
--- a/cli/src/pair/pairHarness.spec.ts
+++ b/cli/src/pair/pairHarness.spec.ts
@@ -1,7 +1,7 @@
/**
* P4 — the pair harness (pair/pairHarness.ts): a built-in `autonomous/pair` package with the harnessd MCP
* server injected the way gridWebMcp.ts injects one (Claude `--mcp-config`, Codex `-c`), the paired
- * daemon's voice and the floor in its instructions, mode ask pinned; started, resumed and paused on
+ * daemon's voice and the floor in its instructions, automatic approvals; started, resumed and paused on
* demand; hidden from the catalog.
*/
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
@@ -37,14 +37,14 @@ afterEach(() => {
const MCP = ['/usr/local/bin/node', '/opt/harness/cli.js']
describe('the package', () => {
- it('is a spec-1 harness pinned to mode ask, with the harnessd MCP server and only its read tools pre-approved', () => {
+ it('is a spec-1 harness using automatic approvals with the scoped harnessd MCP server', () => {
expect(PAIR_HARNESS_ID).toBe(PAIR_HARNESS_DSH)
const files = pairPackage({ daemonId: 'tim', engine: 'claude', mcpCommand: MCP, tokenFile: '/data/pair/token' })
const parsed = parseDshManifest(files['harness.json']!.content)
expect(parsed.ok).toBe(true)
const manifest = parsed.ok ? parsed.manifest : null
expect(manifest).toMatchObject({ id: 'autonomous/pair', engine: 'claude', agent: { instructions: 'AGENTS.md',
- env: { DSH_PERMISSION_MODE: 'ask', HARNESSD_PAIR_TOKEN_FILE: '/data/pair/token' } } })
+ env: { DSH_PERMISSION_MODE: 'auto', HARNESSD_PAIR_TOKEN_FILE: '/data/pair/token' } } })
const args = manifest!.agent!.args!
expect(args[0]).toBe('--mcp-config')
expect(JSON.parse(args[1]!)).toEqual({ mcpServers: { harnessd: { type: 'stdio', command: '/usr/local/bin/node',
@@ -63,6 +63,18 @@ describe('the package', () => {
])
})
+ it('gives OpenCode Muse Spark 1.3 and the same scoped MCP tools', () => {
+ const files = pairPackage({ daemonId: 'tim', engine: 'opencode', mcpCommand: MCP, tokenFile: '/data/pair/token' })
+ const manifest = JSON.parse(files['harness.json']!.content)
+ const config = JSON.parse(manifest.agent.env.OPENCODE_CONFIG_CONTENT)
+ expect(config.model).toBe('opencode/muse-spark-1.3-contributor-free')
+ expect(config.permission).toBe('allow')
+ expect(config.provider.opencode.models['muse-spark-1.3-contributor-free'].options.reasoningEffort).toBe('xhigh')
+ expect(config.agent.build.variant).toBe('xhigh')
+ expect(config.mcp.harnessd.command).toEqual([...MCP, 'pair', 'mcp', '--token-file', '/data/pair/token'])
+ expect(manifest.agent.args).toEqual([])
+ })
+
it('speaks as the paired daemon: its lore, first words and lines, and the floor', () => {
const agents = pairPackage({ daemonId: 'tim', engine: 'claude', mcpCommand: MCP, tokenFile: '/t' })['AGENTS.md']!.content
expect(agents).toContain('You are **tim**')
@@ -86,13 +98,13 @@ describe('the package', () => {
const launch = prepareHarnessLaunch(installed, workspace, 'claude', 'harness-claude-x')
expect(launch.args.slice(0, 3)).toEqual(JSON.parse(files['harness.json']!.content).agent.args)
expect(launch.args).toContain('--append-system-prompt')
- expect(launch.env).toMatchObject({ HARNESS_DSH: PAIR_HARNESS_ID, DSH_PERMISSION_MODE: 'ask', HARNESSD_PAIR_TOKEN_FILE: '/t' })
+ expect(launch.env).toMatchObject({ HARNESS_DSH: PAIR_HARNESS_ID, DSH_PERMISSION_MODE: 'auto', HARNESSD_PAIR_TOKEN_FILE: '/t' })
expect(readFileSync(launch.env.HARNESS_CONTEXT_FILE!, 'utf8')).toContain('You are **tim**')
})
})
describe('talking to it', () => {
- function world(opts: { engine?: 'claude' | 'codex' | null; pair?: string | null } = {}) {
+ function world(opts: { engine?: 'claude' | 'codex' | 'opencode' | null; pair?: string | null } = {}) {
let pair = opts.pair === undefined ? 'tim' : opts.pair
const rows: PairHarnessRow[] = []
let working = false
@@ -100,7 +112,7 @@ describe('talking to it', () => {
const token = new PairToken(join(dir, 'pair', 'token'))
const deps = {
pairedDaemon: () => pair,
- engine: async () => opts.engine === undefined ? 'claude' as const : opts.engine,
+ engine: async () => opts.engine === undefined ? 'opencode' as const : opts.engine,
mcpCommand: () => MCP,
token,
workspace: join(dir, 'pair', 'workspace'),
@@ -118,11 +130,11 @@ describe('talking to it', () => {
return { harness, deps, rows, token, setPair: (p: string | null) => { pair = p }, setWorking: (w: boolean) => { working = w } }
}
- it('starts it on the first words, mode ask, with a fresh token; sends to it after that', async () => {
+ it('starts it on the first words with a fresh token; sends to it after that', async () => {
const w = world()
expect(w.token.launched).toBe(false)
expect(await w.harness.talk('what needs me?')).toEqual({ ok: true, agentId: 'pair-1', started: true })
- expect(w.deps.create).toHaveBeenCalledWith({ engine: 'claude', cwd: join(dir, 'pair', 'workspace'), prompt: 'what needs me?', name: 'companions' })
+ expect(w.deps.create).toHaveBeenCalledWith({ engine: 'opencode', cwd: join(dir, 'pair', 'workspace'), prompt: 'what needs me?', name: 'companions' })
expect(w.token.launched).toBe(true)
const token = readFileSync(join(dir, 'pair', 'token'), 'utf8')
expect(await w.harness.talk('and on the laptop?')).toEqual({ ok: true, agentId: 'pair-1', sent: true })
@@ -222,7 +234,7 @@ describe('talking to it', () => {
it('says why it cannot: nothing paired, no engine, nothing said', async () => {
expect(await world({ pair: null }).harness.talk('hi')).toMatchObject({ ok: false, error: 'PAIR_OFF' })
- expect(await world({ engine: null }).harness.talk('hi')).toMatchObject({ ok: false, error: 'ENGINE_REQUIRED' })
+ expect(await world({ engine: null }).harness.talk('hi')).toMatchObject({ ok: false, error: 'NO_ENGINE' })
expect(await world().harness.talk(' ')).toMatchObject({ ok: false, error: 'EMPTY' })
})
})
diff --git a/cli/src/pair/pairHarness.ts b/cli/src/pair/pairHarness.ts
index 0e5ebf144..ab7079913 100644
--- a/cli/src/pair/pairHarness.ts
+++ b/cli/src/pair/pairHarness.ts
@@ -9,9 +9,8 @@
* conversation is kept; the next talk resumes it). Never a tile anyone picks (hidden from the catalog),
* never counted as a person's turn (zooTurns), never a notification, never watched by the sensor.
*
- * Safe by construction: mode `ask`, pinned in its manifest (`DSH_PERMISSION_MODE`), so every write tool
- * call is a permission prompt in its own pane; the control interface then asks for the per-launch token,
- * the autonomy dial and the floor. The token rotates at every launch (start or resume).
+ * New conversations use the product's automatic approvals. The control interface still checks the
+ * per-launch token, the autonomy dial and the floor. The token rotates at every launch (start or resume).
*
* "Files plus a shell; MCP optional": the instructions also teach `harness pair <verb> --json`, which the
* engine's shell can run with the same token (`HARNESSD_PAIR_TOKEN_FILE`).
@@ -24,18 +23,20 @@ import { MCP_SERVER_NAME } from './mcp.js'
import { PAIR_TOKEN_FILE_ENV, type PairToken } from './token.js'
import { rosterDaemon } from './voice.js'
import type { BundledFiles } from '../dsh/builtins.js'
+import { DEFAULT_HARNESS_ENGINE, DEFAULT_HARNESS_PERMISSION, freshHarnessEnvironment } from '../lib/harnessDefaults.js'
export const PAIR_HARNESS_ID = 'autonomous/pair'
-export type PairEngine = 'claude' | 'codex'
+export type PairEngine = 'claude' | 'codex' | 'opencode'
/** Paused after this long with no turn and no talk. */
export const PAIR_IDLE_MS = 10 * 60_000
const IDLE_CHECK_MS = 60_000
-/** The read tools, pre-approved for Claude so a conversation flows; every write still prompts (mode ask). */
+/** The read tools, pre-approved for Claude; write tools also obey the control interface's policy. */
const READ_TOOLS = CONTROL_TOOLS.filter((tool) => tool.kind !== 'write').map((tool) => `mcp__${MCP_SERVER_NAME}__${tool.name}`)
/** The engine argv that puts the harnessd MCP server in front of the pair (the gridWebMcp.ts paths). */
export function pairEngineArgs(engine: PairEngine, mcpCommand: readonly string[], tokenFile: string): string[] {
+ if (engine === 'opencode') return [] // MCP is supplied in its launch configuration.
const [command, ...prefix] = mcpCommand
const args = [...prefix, 'pair', 'mcp', '--token-file', tokenFile]
if (engine === 'claude') {
@@ -158,11 +159,14 @@ export function pairPackage(input: PairPackageInput): BundledFiles {
engine: input.engine,
agent: {
instructions: 'AGENTS.md',
- env: {
- // Mode ask, whatever launched it: every write tool call is a permission prompt in its pane.
- DSH_PERMISSION_MODE: 'ask',
+ env: freshHarnessEnvironment(input.engine, {
+ DSH_PERMISSION_MODE: DEFAULT_HARNESS_PERMISSION,
[PAIR_TOKEN_FILE_ENV]: input.tokenFile,
- },
+ ...(input.engine === 'opencode' ? { OPENCODE_CONFIG_CONTENT: JSON.stringify({
+ mcp: { [MCP_SERVER_NAME]: { type: 'local',
+ command: [...input.mcpCommand, 'pair', 'mcp', '--token-file', input.tokenFile], enabled: true } },
+ }) } : {}),
+ }),
args: pairEngineArgs(input.engine, input.mcpCommand, input.tokenFile),
},
}
@@ -180,6 +184,7 @@ export interface PairHarnessRow {
agentId: string
status: 'live' | 'stopped'
engine?: PairEngine
+ cwd?: string | null
/** False while the engine is still at first-run setup, before any session exists. */
hasConversation?: boolean
}
@@ -257,11 +262,10 @@ export class PairHarness {
if (!current()) return stale
const previous = this.saved()
const previousEngine = this.engine()
+ const previousFolder = this.deps.find().find(row => row.agentId === previous?.agentId)?.cwd
const switching = !!requested.engine && requested.engine !== previousEngine
- const saved = switching ? this.saved(requested.engine) : previous
+ const saved = switching ? null : previous
const conversation = this.deps.find().find((row) => row.agentId === saved?.agentId) ?? null
- if (switching && previous && this.deps.working(previous.agentId)) return { ok: false, error: 'BUSY',
- detail: 'Finish or stop the current turn before switching agents.' }
if (this.activeAgentId && this.activeAgentId !== previous?.agentId && this.deps.find().some(row => row.agentId === this.activeAgentId && row.status === 'live')) {
await this.deps.stop(this.activeAgentId)
if (!current()) return stale
@@ -270,10 +274,10 @@ export class PairHarness {
// character, or updating its artwork must never replace the person's conversation.
if (saved && !conversation) return { ok: false, error: 'CONVERSATION_UNAVAILABLE',
detail: 'The collection’s saved conversation is unavailable. Its history has been kept.' }
- const preferred = requested.engine ?? saved?.engine
+ const preferred = requested.engine ?? conversation?.engine ?? saved?.engine ?? DEFAULT_HARNESS_ENGINE
const engine = switching ? await this.deps.engine(preferred) : conversation?.engine ?? saved?.engine ?? await this.deps.engine(preferred)
if (!engine || (preferred && engine !== preferred)) return preferred
- ? { ok: false, error: 'NO_ENGINE', detail: `${preferred === 'codex' ? 'Codex' : 'Claude Code'} is not installed on this computer.` }
+ ? { ok: false, error: 'NO_ENGINE', detail: `${preferred === 'codex' ? 'Codex' : preferred === 'opencode' ? 'OpenCode' : 'Claude Code'} is not installed on this computer.` }
: { ok: false, error: 'ENGINE_REQUIRED', detail: 'Choose the agent that powers your companion.' }
if (!current()) return stale
const identity = this.deps.pairedUid?.()
@@ -318,7 +322,7 @@ export class PairHarness {
}
if (!current()) return stale
this.deps.token.rotate()
- const workspace = uid ? join(this.deps.workspace, `collection-${uid}`) : this.deps.workspace
+ const workspace = previousFolder ?? (uid ? join(this.deps.workspace, `collection-${uid}`) : this.deps.workspace)
mkdirSync(workspace, { recursive: true, mode: 0o700 })
const created = await this.deps.create({ engine, cwd: workspace, prompt: words, name: 'companions' })
if (!created.ok) return created
@@ -445,7 +449,7 @@ export class PairHarness {
return typeof row.agentId === 'string' && /^[A-Za-z0-9_-]{1,128}$/.test(row.agentId) && typeof row.revision === 'string'
? { agentId: row.agentId, revision: row.revision, ...(typeof row.uid === 'string' ? { uid: row.uid } : {}),
...(Array.isArray(row.members) ? { members: row.members.filter(uid => typeof uid === 'string' && /^[A-Za-z0-9_-]{1,64}$/.test(uid)) } : {}),
- ...(['claude', 'codex'].includes(row.engine ?? '') ? { engine: row.engine } : {}),
+ ...(['claude', 'codex', 'opencode'].includes(row.engine ?? '') ? { engine: row.engine } : {}),
...(typeof row.learningScope === 'string' && /^[A-Za-z0-9_-]{1,128}$/.test(row.learningScope) ? { learningScope: row.learningScope } : {}),
} : null
}
diff --git a/desktop/CLAUDE.md b/desktop/CLAUDE.md
index dc16c0b7a..c1d017b47 100644
--- a/desktop/CLAUDE.md
+++ b/desktop/CLAUDE.md
@@ -265,8 +265,8 @@ or unconfirmed close keeps the pane. Older daemons retain their existing behavio
`HarnessMonitor` supplies the global running-harness count without process sampling
in the footer. Clicking it opens the reusable `autonomous/harness-monitor` DSH tab
-through `HarnessMonitorController`, with its viewer full width and the assistant
-terminal revealed only on request. The DSH table shares the daemon's resource sampler
+through `HarnessMonitorController`, with its viewer on the left at 70% and the assistant
+terminal on the right at 30%. Only the pane zoom action expands either pane. The DSH table shares the daemon's resource sampler
and adds opt-in activity metadata to `agents_list`. RAM is process-tree RSS; CPU is
interval use, with 100% representing one core. Unknown readings remain unknown.
Shared Codex servers are listed separately and included once; token counts reuse
@@ -342,7 +342,7 @@ its headless debug timings do not establish native display or network latency.
with harness count, local hardware and subscription allowance used at the bottom left and focused machine/repo/branch/PR at the bottom right.
Tabs center their name/status group without permanent number prefixes; Command replaces
the status with the resolved shortcut beside the name. Tab and pane close marks are small
- and quiet, with larger click targets. Each pane ends with model, split down,
+ and quiet, with larger click targets. Each pane ends with agent, model, split down,
split right, zoom, close. Split opens New Harness directly for the clicked pane.
Usage has no dot separators and colors only low/exhausted
percentages. Automatic names use the strongest shared harness type,
diff --git a/desktop/design/desktop-design-system.md b/desktop/design/desktop-design-system.md
index b127991d7..55f5d7f2e 100644
--- a/desktop/design/desktop-design-system.md
+++ b/desktop/design/desktop-design-system.md
@@ -329,7 +329,7 @@ inner edge beneath their 1-point rim. Only their frame changes: terminal content
input, selection and status typography remain the terminal's own. AppKit mirrors
these shared geometry values; Flutter uses AppDesktop directly.
-**Pane header** — the right-hand controls read model, split down, split right,
+**Pane header** — the right-hand controls read agent, model, split down, split right,
zoom, close. Use the rounded 14-point `AppPaneIcon` split/zoom variants and the
shared 12-point close glyph in 28-point targets. The close target sits 4 points
inside the header's trailing edge. Resting ink is 45%; hover and keyboard focus
@@ -338,7 +338,7 @@ line; model and title text truncate before icon targets shrink. Zoom becomes
Restore while enlarged. Unavailable controls stay in place with disabled ink.
Split opens New Harness directly, inheriting the clicked pane's agent, machine,
and project; the pane is created only after submission. Clicking the model focuses that
-pane and opens the same Models picker as Cmd-:. Selection stays bound to that
+pane and opens the same Models picker as Cmd-:. The agent name and chevron open the shared Agents picker (`&` in Cmd-P). Selection stays bound to that
harness; a closed or replaced pane cannot receive a stale selection. Long model
names truncate and retain their full-name tooltip. Keep effort in the terminal,
and keep the icon targets clear at narrow widths. Tab-strip close behavior is
diff --git a/desktop/design/new-harness-entry-rules.md b/desktop/design/new-harness-entry-rules.md
index 1f0d154f7..a7f46f7e4 100644
--- a/desktop/design/new-harness-entry-rules.md
+++ b/desktop/design/new-harness-entry-rules.md
@@ -74,6 +74,19 @@ coding agent should run it, preselecting its remembered choice. The form's value
then reads `Blender · Codex`. Choosing a direct agent removes the package choice
and sends no `dsh`; it does not remove project instructions or skills.
+Fresh harnesses use OpenCode with Muse Spark 1.3, xhigh effort and Auto-approve when compatible. Explicit and
+remembered agent choices are retained; reopening a session keeps its saved agent
+and model. A package's declared agent is a compatibility fallback, not a global default.
+
+The running pane header shows the agent name with a chevron beside the model.
+Clicking it opens the shared Cmd-P picker in `&` Agents mode. All agents are
+listed; unsupported choices explain why they cannot be selected. Selecting a
+supported agent saves and stops the current session, starts a fresh conversation
+in the same folder, and replaces its references in every pane without changing
+tab positions or layout. The previous saved conversation stays in history. No
+confirmation dialog is shown. Failed saves do not start a replacement; uncertain
+creation replies retain one receipt for retry.
+
Explicit entry choices and pending receipts win over remembered defaults. A
remembered agent, package, project, or profile that is unavailable requires an
explicit replacement. A package requested explicitly keeps its identity. Packages
@@ -114,7 +127,7 @@ management and preserves the launch draft. Choosing Terminal clears model routin
its Model row is omitted.
An explicit model survives draft dismissal/restoration and uncertain creation
-receipts. A new session starts with the selected engine's default subscription;
+receipts. A new OpenCode session starts with Muse Spark 1.3; other engines use their default subscription;
model routing is not persisted as a global preference. Start refreshes availability
and sends only `gridModel` and `gridName`; the selected machine resolves the endpoint
and credentials. Older daemons without `supportsModelLaunch` explain that an update
diff --git a/desktop/design/review/2026-10-01-harness-agent-controls.png b/desktop/design/review/2026-10-01-harness-agent-controls.png
new file mode 100644
index 000000000..5790b7470
Binary files /dev/null and b/desktop/design/review/2026-10-01-harness-agent-controls.png differ
diff --git a/desktop/design/terminal-workspace.md b/desktop/design/terminal-workspace.md
index 20e121d61..d1c4697b8 100644
--- a/desktop/design/terminal-workspace.md
+++ b/desktop/design/terminal-workspace.md
@@ -32,11 +32,11 @@ Tooltips explain icon actions and resolve shortcuts from the live keymap.
The footer shows a global harness count, local host CPU/RAM/GPU and subscription
allowance used on the left, all in neutral ink with whole percentages. Its
-right-hand context follows the focused pane: machine, project, branch and PR. Each pane header ends with model, split down, split right, zoom,
+right-hand context follows the focused pane: machine, project, branch and PR. Each pane header ends with agent, model, split down, split right, zoom,
and close, in that order. The icons stay visible with quiet ink and no button
chrome. Splitting opens New Harness directly with that pane's agent, machine,
and project, then creates into the chosen split on submission. Clicking the
-model opens the shared Models picker for that harness;
+agent opens the shared `&` Agents picker; clicking the model opens the shared Models picker for that harness;
the footer does not repeat model or effort. Do not show worktree implementation
paths in everyday labels. User-selected shell/Powerline status styles remain
available, including PR state colors and the option to disable color.
diff --git a/desktop/lib/companions/companion_engine_picker.dart b/desktop/lib/companions/companion_engine_picker.dart
index fc6a34b67..b34ee7375 100644
--- a/desktop/lib/companions/companion_engine_picker.dart
+++ b/desktop/lib/companions/companion_engine_picker.dart
@@ -1,112 +1,13 @@
-import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
-import '../shared/widgets/app_menu.dart';
-import '../theme/app_theme.dart';
-import '../widgets/engine_identity.dart';
-import '../widgets/transient_menus.dart';
+import '../widgets/harness_agent_picker.dart';
-/// The collection's agent. Models and permissions remain in its real terminal.
-class CompanionEnginePicker extends StatefulWidget {
+/// The collection uses the same agent control as ordinary harness panes.
+class CompanionEnginePicker extends HarnessAgentPicker {
const CompanionEnginePicker({
super.key,
- required this.engine,
- required this.onSelected,
- this.busy = false,
- });
-
- final String? engine;
- final ValueChanged<String>? onSelected;
- final bool busy;
-
- static String label(String engine) =>
- engine == 'claude' ? 'Claude Code' : 'Codex';
-
- @override
- State<CompanionEnginePicker> createState() => _CompanionEnginePickerState();
-}
-
-class _CompanionEnginePickerState extends State<CompanionEnginePicker> {
- final _menu = MenuController();
- final _trigger = FocusNode();
- final _choices = {'codex': FocusNode(), 'claude': FocusNode()};
- VoidCallback? _unregister;
-
- @override
- void dispose() {
- _unregister?.call();
- _trigger.dispose();
- for (final focus in _choices.values) {
- focus.dispose();
- }
- super.dispose();
- }
-
- @override
- Widget build(BuildContext context) => Row(
- mainAxisSize: MainAxisSize.min,
- children: [
- Text(
- 'Powered by',
- style: Theme.of(context).textTheme.bodySmall
- ?.copyWith(color: AppColors.textSoft),
- ),
- const SizedBox(width: 4),
- MenuAnchor(
- controller: _menu,
- childFocusNode: _trigger,
- onOpen: () {
- _unregister = registerTransientMenu(_menu.close);
- WidgetsBinding.instance.addPostFrameCallback((_) {
- if (mounted && _menu.isOpen) {
- (_choices[widget.engine] ?? _choices['codex'])!.requestFocus();
- }
- });
- },
- onClose: () {
- _unregister?.call();
- _unregister = null;
- },
- menuChildren: [
- for (final choice in ['codex', 'claude'])
- AppMenuItem(
- label: CompanionEnginePicker.label(choice),
- leading: EngineMark(engine: choice),
- selected: widget.engine == choice,
- focusNode: _choices[choice],
- onPressed: () {
- _menu.close();
- widget.onSelected?.call(choice);
- },
- ),
- ],
- builder: (context, controller, child) => TextButton(
- key: const ValueKey('companion-engine-picker'),
- focusNode: _trigger,
- onPressed: widget.busy || widget.onSelected == null
- ? null
- : () =>
- controller.isOpen ? controller.close() : controller.open(),
- child: Row(
- mainAxisSize: MainAxisSize.min,
- children: [
- if (widget.engine != null) ...[
- EngineMark(engine: widget.engine, size: 16),
- const SizedBox(width: 7),
- ],
- Text(
- widget.busy
- ? 'Opening…'
- : widget.engine == null
- ? 'Choose agent'
- : CompanionEnginePicker.label(widget.engine!),
- ),
- const SizedBox(width: 4),
- const Icon(AppIcons.chevronDown, size: 16),
- ],
- ),
- ),
- ),
- ],
- );
+ required super.engine,
+ required super.onSelected,
+ super.busy,
+ }) : super(triggerKey: const ValueKey('companion-engine-picker'));
}
diff --git a/desktop/lib/core/harness_defaults.dart b/desktop/lib/core/harness_defaults.dart
new file mode 100644
index 000000000..fc0e49b6b
--- /dev/null
+++ b/desktop/lib/core/harness_defaults.dart
@@ -0,0 +1,3 @@
+/// The product default. Explicit selections and existing conversations win.
+const defaultHarnessEngine = 'opencode';
+const defaultHarnessModelLabel = 'Muse Spark 1.3';
diff --git a/desktop/lib/daemons/daemon_lessons.dart b/desktop/lib/daemons/daemon_lessons.dart
index c3a8e1a95..7e5e85018 100644
--- a/desktop/lib/daemons/daemon_lessons.dart
+++ b/desktop/lib/daemons/daemon_lessons.dart
@@ -220,10 +220,10 @@ class DaemonLearning {
return 'Learning resumes when your companion is turned on.';
}
if (state == 'unsupported') {
- return 'Background learning cannot use this agent connection yet. Your conversation and approved lessons are kept.';
+ return 'Background learning currently needs Codex or Claude Code. Change agent to enable it; your conversation and saved memories are kept.';
}
if (state == 'unopened') {
- return 'Choose Codex or Claude Code above to power your companion and its memories.';
+ return 'Open your companion with OpenCode, Codex, or Claude Code.';
}
if (state != 'ready') {
return 'Finish setting up the agent on the right. Learning follows the model you choose there.';
diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dart
index a5afc0461..783602e3b 100644
--- a/desktop/lib/screens/swarm_screen.dart
+++ b/desktop/lib/screens/swarm_screen.dart
@@ -574,6 +574,9 @@ class _SwarmScreenState extends State<SwarmScreen> {
_pullRequest = WorkspacePullRequest(app)..addListener(_statusPrefsChanged);
_harnessMonitor = HarnessMonitor(app)..addListener(_monitorChanged);
app.reviewSessionClose = _reviewSessionClose;
+ app.changeCompanionAgent = _changeCompanionAgent;
+ app.canChangeCompanionAgent = _canChangeCompanionAgent;
+ app.openAgentPicker = _openPaneAgents;
_keymap.addListener(_keymapChanged);
app.hasNavigationRail = false;
app.railFocused = false;
@@ -778,6 +781,13 @@ class _SwarmScreenState extends State<SwarmScreen> {
if (app.reviewSessionClose == _reviewSessionClose) {
app.reviewSessionClose = null;
}
+ if (app.changeCompanionAgent == _changeCompanionAgent) {
+ app.changeCompanionAgent = null;
+ }
+ if (app.canChangeCompanionAgent == _canChangeCompanionAgent) {
+ app.canChangeCompanionAgent = null;
+ }
+ if (app.openAgentPicker == _openPaneAgents) app.openAgentPicker = null;
linuxTitleBarActions.detach(this);
_closeDaemonHint();
app.foreground.removeListener(_daemonEnvironmentChanged);
@@ -3987,9 +3997,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
_companionTerminalError = switch (result['error']) {
'ENGINE_REQUIRED' => null,
'UNSUPPORTED' => 'Update Harness CLI to open the companion terminal.',
- 'NO_ENGINE' =>
- result['detail'] as String? ??
- 'Install Claude Code or Codex to talk with your companion.',
+ 'NO_ENGINE' => result['detail'] as String? ?? 'Install OpenCode, Codex, or Claude Code to talk with your companion.',
_ =>
result['detail'] as String? ??
'The terminal could not connect. Try opening it again.',
@@ -3999,9 +4007,54 @@ class _SwarmScreenState extends State<SwarmScreen> {
_scheduleCompanionWorkspace();
}
+ bool _canChangeCompanionAgent(String machineId, String agentId) =>
+ _brain.active &&
+ !_zoo.isPreview &&
+ _companionOpeningKey == null &&
+ _pairHarness?.machineId == machineId &&
+ _pairHarness?.agentId == agentId;
+
+ Future<Map<String, dynamic>> _changeCompanionAgent(
+ String sourceId,
+ String engine,
+ ) async {
+ final local = app.localMachineState;
+ final current = local?.agents
+ .where((a) => a.id == _pairHarness?.agentId)
+ .firstOrNull;
+ final source = local?.agents.where((a) => a.id == sourceId).firstOrNull;
+ // A reply can be lost after the collection has adopted its replacement.
+ // Rechecking that same choice may return it, never create another one.
+ if (_companionOpeningKey != null ||
+ _pairHarness == null ||
+ (_pairHarness?.agentId != sourceId &&
+ (source?.project?.cwd == null ||
+ current?.project?.cwd != source?.project?.cwd ||
+ current?.engine != engine))) {
+ return {
+ 'ok': false,
+ 'detail': 'The companion changed or is already opening.',
+ };
+ }
+ final result = await _brain.openConversation(engine: engine);
+ if (!mounted) {
+ return {'ok': false, 'detail': 'The companion view was closed.'};
+ }
+ _scheduleCompanionWorkspace();
+ return result;
+ }
+
void _selectCompanionEngine(String engine) {
final uid = _zoo.paired?.uid;
if (uid == null || _companionOpeningKey != null || _zoo.isPreview) return;
+ if (_pairHarness case final pair?) {
+ unawaited(
+ app.changeAgent(pair.machineId, pair.agentId, engine).then((error) {
+ if (mounted && error != null) _showPaneActionHint(error);
+ }),
+ );
+ return;
+ }
final key = '${_zoo.scope}:$uid';
setState(() {
_companionAttemptedKey = key;
@@ -4975,6 +5028,24 @@ class _SwarmScreenState extends State<SwarmScreen> {
void _togglePaneModels() => _toggleModels();
+ void _openPaneAgents(String machineId, String agentId) {
+ final pane = app.panes
+ .where((p) => p.machineId == machineId && p.agentId == agentId)
+ .firstOrNull;
+ if (pane == null) return;
+ app.focusPane(pane.id);
+ _openResourcePicker('&');
+ _search?.setAgentSelection(machineId, agentId);
+ final search = _search;
+ unawaited(
+ app.probeDsh(machineId).then((_) {
+ if (mounted && identical(search, _search)) {
+ search?.setAgentSelection(machineId, agentId);
+ }
+ }),
+ );
+ }
+
void _openPaneModels(int paneId, String machineId, String agentId) {
if (!_shortcutsEnabled) return;
final pane = app.panes.where((pane) => pane.id == paneId).firstOrNull;
@@ -5260,6 +5331,12 @@ class _SwarmScreenState extends State<SwarmScreen> {
final word = search.query.trim().toLowerCase();
if (word.length >= 3 && _zoo.isEasterWord(word)) _zoo.easter(word);
}
+ if (search.isAgentMode && search.agentSelectionId == null) {
+ final focused = WorkspacePaneContext.focused(app);
+ if (focused?.agentId case final id?) {
+ search.setAgentSelection(focused!.pane.machineId, id);
+ }
+ }
if (_machineSearchVisible != search.isMachineMode) {
_machineSearchVisible = search.isMachineMode;
if (_machineSearchVisible) unawaited(search.refreshMachineResources());
@@ -5481,6 +5558,16 @@ class _SwarmScreenState extends State<SwarmScreen> {
});
return;
}
+ if (choice.destination.agentEngine case final engine?) {
+ final search = _search!;
+ final machineId = search.agentSelectionMachineId,
+ agentId = search.agentSelectionId;
+ if (machineId == null || agentId == null) return;
+ _closeSearch(restoreFocus: true);
+ final error = await app.changeAgent(machineId, agentId, engine);
+ if (mounted && error != null) _showPaneActionHint(error);
+ return;
+ }
if (choice.destination.storeId case final storeId?) {
_closeSearch(restoreFocus: false);
_noteFound();
@@ -6224,6 +6311,14 @@ class _SwarmScreenState extends State<SwarmScreen> {
current: false,
pickerQuery: '@ ',
),
+ SwarmDestination(
+ id: 'picker:agents',
+ title: '& Agents',
+ detail: 'Change the focused harness’s agent',
+ swarmId: null,
+ current: false,
+ pickerQuery: '& ',
+ ),
SwarmDestination(
id: 'picker:models',
title: ': Models',
@@ -6247,7 +6342,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
?mode(
'harnesses.list',
'Open Harness',
- 'Manage running and paused harnesses',
+ 'Manage running and stopped harnesses',
),
?mode('terminal.new', 'New terminal', 'A shell where you are'),
?mode(
diff --git a/desktop/lib/shortcuts/keymap_commands.dart b/desktop/lib/shortcuts/keymap_commands.dart
index 1d4c6f5ed..4903db45d 100644
--- a/desktop/lib/shortcuts/keymap_commands.dart
+++ b/desktop/lib/shortcuts/keymap_commands.dart
@@ -704,7 +704,7 @@ final harnessCommands = <HarnessCommand>[
context: KeymapContext.picker,
),
for (final (name, key, label) in [
- ('toggle', 'ctrl+s', 'Pause or resume the selected harness or model'),
+ ('toggle', 'ctrl+s', 'Stop the selected harness or start/stop a model'),
('more', 'ctrl+period', 'Search actions for the selected resource'),
('rename', 'ctrl+shift+r', 'Rename the selected machine'),
('settings', 'ctrl+l', 'Open the selected machine’s connection settings'),
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index 8ea3a498f..267aeabc8 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -1,3 +1,5 @@
+import '../core/permission_modes.dart';
+
import 'dart:async';
import 'dart:io' show Directory, Platform, exit, pid;
import 'dart:math' show Random;
@@ -213,6 +215,18 @@ class AgentForkAttempt {
/// One deliberate creation, retained by the form if its reply is lost. Reusing
/// it checks the original request; opening New agent starts a fresh intent.
+class _AgentChange {
+ _AgentChange(this.source, this.engine, this.revision);
+ final Agent source;
+ final String engine;
+ final int revision;
+ final creation = AgentCreationAttempt(background: true);
+ Future<String?>? pending;
+ bool preservingViews = false;
+ String? companionTarget;
+ bool launchFailed = false;
+}
+
class AgentCreationAttempt {
AgentCreationAttempt({this.background = false});
String _id = _newCreationId();
@@ -1445,6 +1459,12 @@ class AppNotifier extends ChangeNotifier {
}
Future<void> showCompanionTerminal(String? machineId, String? agentId) async {
+ if (_agentChanges.values.any(
+ (change) =>
+ change.source.dsh == 'autonomous/pair' && change.preservingViews,
+ )) {
+ return;
+ }
final tab = swarms.where((s) => s.isCompanions).firstOrNull;
final viewer = tab?.panes.where((p) => p.isCompanion).firstOrNull;
if (tab == null || viewer == null) return;
@@ -2395,6 +2415,7 @@ class AppNotifier extends ChangeNotifier {
void _loginWaitingChanged() {
if (!_disposed) notifyListeners();
}
+
bool openingLoginBrowser = false;
String? loginBrowserError;
int _loginBrowserRevision = 0;
@@ -4468,6 +4489,7 @@ class AppNotifier extends ChangeNotifier {
/// In particular, multiple emptied tabs must not prevent the next restore.
void _clearAccountWorkspace() {
experimentalFeatures.bind(null);
+ _agentChanges.clear();
++_layoutRevision;
// Sign-out sends the desk nothing: the tabs closing here are this window
// leaving the account, not the person closing them.
@@ -4849,7 +4871,13 @@ class AppNotifier extends ChangeNotifier {
/// Sign in by a QR a signed-in phone approves, then a yes here to the account it names.
Future<void> loginWithPhone() async {
final client = cliLogin;
- if (_disposed || signingIn || signingOut || signOutError != null || client is! PhoneSignInClient) return;
+ if (_disposed ||
+ signingIn ||
+ signingOut ||
+ signOutError != null ||
+ client is! PhoneSignInClient) {
+ return;
+ }
final wasGuest = isGuest;
final revision = _invalidateAuthWork();
previousAccountEmail = currentUser?.email;
@@ -4886,7 +4914,9 @@ class AppNotifier extends ChangeNotifier {
notifyListeners();
signedIn = true;
await _finishBootstrapSignedIn();
- if (!_authWorkCurrent(revision) || status != AppStatus.authenticated) return;
+ if (!_authWorkCurrent(revision) || status != AppStatus.authenticated) {
+ return;
+ }
_guestDeskRestorePending = false;
} catch (error) {
if (!_authWorkCurrent(revision)) return;
@@ -6073,7 +6103,8 @@ class AppNotifier extends ChangeNotifier {
systemNotifications.postNotice(
id: 'harness-device:${notice.pub}',
title: 'New device on your account',
- body: '${notice.sentence} Not yours? Remove it in Settings ▸ Your devices.',
+ body:
+ '${notice.sentence} Not yours? Remove it in Settings ▸ Your devices.',
devicePub: notice.pub,
);
notifyListeners();
@@ -8053,7 +8084,10 @@ class AppNotifier extends ChangeNotifier {
if (!owned) continue;
// The explicit Close owns these panes until its disk-safe acknowledgement,
// so it can preserve recently-closed layout and composer history normally.
- if (_closingViewAgents.containsKey((machineId, agentId))) continue;
+ if (_closingViewAgents.containsKey((machineId, agentId)) ||
+ _agentChanges[(machineId, agentId)]?.preservingViews == true) {
+ continue;
+ }
for (final swarm in swarms) {
if (swarm.panes.contains(pane)) {
affected.add(swarm);
@@ -8098,6 +8132,9 @@ class AppNotifier extends ChangeNotifier {
/// belongs to. Nothing is persisted — see [PaneKind.web].
bool _syncViewerPane(MachineState machine, Agent agent) {
final machineId = machine.machine.machineId;
+ if (_agentChanges[(machineId, agent.id)]?.preservingViews == true) {
+ return false;
+ }
final url = agent.viewerUrl;
final viewerState = url ?? agent.viewerError;
final dismissed =
@@ -8154,10 +8191,6 @@ class AppNotifier extends ChangeNotifier {
ownerAgentId: agent.id,
);
swarm.panes.insert(insertion, pane);
- if (agent.dsh == harnessMonitorId) {
- swarm.zoomedPaneId = pane.id;
- swarm.focusedPaneId = pane.id;
- }
// The same bookkeeping a split does when it grows the grid by one:
// pins past the insertion slide right, and the shape is re-derived.
swarm.pinnedSlots.updateAll(
@@ -8165,9 +8198,8 @@ class AppNotifier extends ChangeNotifier {
);
swarm.arranged = null;
swarm.arrangedKey = null;
- // Alone with its terminal, the viewer takes two thirds of the tab — a
- // board or a part wants the width, and a third is the least a coding
- // agent's interface reads well at. Only when nobody has sized this pair
+ // Alone with its terminal, the viewer takes 70% of the tab and the
+ // assistant keeps 30%. Only when nobody has sized this pair
// by hand: a manual layout is the user's.
if (swarm.panes.length == 2 && swarm.paneSizes['2:manual'] == null) {
swarm.savePaneSizes('2:manual', PaneArrangement.viewerBesideTerminal);
@@ -8178,8 +8210,8 @@ class AppNotifier extends ChangeNotifier {
return changed;
}
- /// The monitor opens as a full-width table; the OpenCode terminal remains its DSH owner.
- void showHarnessMonitorTable(String machineId, String agentId) {
+ /// Opening a monitor reveals its ordinary DSH pair. Zoom is an explicit pane action.
+ void showHarnessMonitor(String machineId, String agentId) {
final pane = activeSwarm.panes
.where(
(p) =>
@@ -8188,7 +8220,7 @@ class AppNotifier extends ChangeNotifier {
.firstOrNull;
if (pane == null) return;
focusPane(pane.id);
- zoomedPaneId = pane.id;
+ zoomedPaneId = null;
_persistLayout();
notifyListeners();
}
@@ -10106,7 +10138,7 @@ class AppNotifier extends ChangeNotifier {
final agent = machine?.agents.where((a) => a.id == agentId).firstOrNull;
if (machine == null || agent == null || !agent.canPauseAndResume) {
return Future.value(
- 'This harness has no supported saved conversation to resume.',
+ 'This harness has no supported saved conversation to open.',
);
}
if (agent.isStopped) return Future.value(null);
@@ -10301,7 +10333,7 @@ class AppNotifier extends ChangeNotifier {
if (pendingAgentPause(machineId, agentId) != null) {
return Future.value(
const RestartAgentResult(
- error: 'The harness is still pausing. Try again in a moment.',
+ error: 'The harness is still stopping. Try again in a moment.',
),
);
}
@@ -10391,7 +10423,7 @@ class AppNotifier extends ChangeNotifier {
final resuming = attempt.agent?.isStopped == true;
final unknown = RestartAgentResult(
error: resuming
- ? 'Still waiting for the resume response. Select the harness again to check status.'
+ ? '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.',
);
Map<String, dynamic> result;
@@ -10691,6 +10723,217 @@ class AppNotifier extends ChangeNotifier {
);
}
+ final _agentChanges = <(String, String), _AgentChange>{};
+
+ bool _keepsSwitchPane(TerminalPane pane) =>
+ _agentChanges[(pane.machineId, pane.agentId ?? pane.ownerAgentId)]
+ ?.preservingViews ==
+ true;
+
+ Future<Map<String, dynamic>> Function(String sourceId, String engine)?
+ changeCompanionAgent;
+ bool Function(String machineId, String agentId)? canChangeCompanionAgent;
+ void Function(String machineId, String agentId)? openAgentPicker;
+
+ List<String> agentSwitchEngines(String machineId, Agent source) {
+ if (source.dsh == 'autonomous/pair') {
+ return const ['opencode', 'codex', 'claude'];
+ }
+ final supported = source.dsh == null
+ ? allEngines.map((engine) => engine.id).toList()
+ : stateOf(machineId)?.dsh[source.dsh!]?.supportedEngines ??
+ [source.engine ?? ''];
+ return [
+ if (supported.contains('opencode')) 'opencode',
+ ...supported.where((id) => id != 'opencode'),
+ ];
+ }
+
+ /// One switch intent owns its creation receipt. All views move together only
+ /// after the new agent is ready and the old conversation can be saved safely.
+ Future<String?> changeAgent(String machineId, String agentId, String engine) {
+ final source = stateOf(machineId)?.agents
+ .where((a) => a.id == agentId)
+ .firstOrNull;
+ if (source == null) {
+ return Future.value('This harness is no longer available.');
+ }
+ if (source.engine == engine) return Future.value();
+ if (stateOf(machineId)?.machine.isShared != false) {
+ return Future.value('Shared harnesses are view-only.');
+ }
+ if (!agentSwitchEngines(machineId, source).contains(engine)) {
+ return Future.value(
+ 'This agent is not supported by the installed harness.',
+ );
+ }
+ final key = (machineId, agentId);
+ if (source.dsh == 'autonomous/pair' &&
+ _agentChanges[key] == null &&
+ (changeCompanionAgent == null ||
+ canChangeCompanionAgent?.call(machineId, agentId) != true)) {
+ return Future.value(
+ 'Open this collection in Companions before changing its agent.',
+ );
+ }
+ var operation = _agentChanges[key];
+ if (operation?.pending case final pending?) {
+ return operation!.engine == engine
+ ? pending
+ : Future.value('The agent is already switching.');
+ }
+ if (operation != null &&
+ ((!operation.preservingViews) ||
+ operation.launchFailed ||
+ (operation.creation._finished &&
+ operation.creation.agentId == null))) {
+ _agentChanges.remove(key);
+ operation = null;
+ }
+ if (operation != null && operation.engine != engine) {
+ return Future.value(
+ 'Check the pending switch to ${operation.engine} before choosing another agent.',
+ );
+ }
+ final change = operation ??= _AgentChange(source, engine, _authRevision);
+ _agentChanges[key] = change;
+ return change.pending = _changeAgent(
+ machineId,
+ change,
+ ).whenComplete(() => change.pending = null);
+ }
+
+ Future<String?> _changeAgent(String machineId, _AgentChange change) async {
+ final machine = stateOf(machineId);
+ final source = change.source;
+ if (machine == null || !_machineWorkCurrent(machine, change.revision)) {
+ return 'This switch is no longer active.';
+ }
+ final current = machine.agents.where((a) => a.id == source.id).firstOrNull;
+ if (current == null ||
+ current.createdAt != source.createdAt ||
+ current.sessionId != source.sessionId) {
+ return 'The conversation changed. Reopen Change agent.';
+ }
+ final folder = source.project?.cwd ?? machine.projectOf(source)?.cwd;
+ if (folder == null) {
+ return 'This harness has no project folder to open with another agent.';
+ }
+ final close = prepareSessionClose(machineId, source);
+ change.preservingViews = true;
+ if (!current.isStopped) {
+ final saved = await close('now');
+ if (saved['closed'] != true) {
+ change.preservingViews = false;
+ return saved['detail'] as String? ??
+ 'Could not save and stop this conversation. Its agent has not been changed.';
+ }
+ }
+ if (!_machineWorkCurrent(machine, change.revision)) {
+ return 'This switch is no longer active.';
+ }
+ final modes = permissionModesOf(change.engine);
+ final mode = modes.any((mode) => mode.id == source.permissionMode)
+ ? source.permissionMode
+ : 'ask';
+ String? nextId;
+ if (source.dsh == 'autonomous/pair') {
+ if (change.companionTarget == null) {
+ final result = await changeCompanionAgent?.call(
+ source.id,
+ change.engine,
+ );
+ if (result?['ok'] != true) {
+ return result?['detail'] as String? ??
+ 'Could not change the companion agent.';
+ }
+ if (!_machineWorkCurrent(machine, change.revision)) {
+ return 'This switch is no longer active.';
+ }
+ change.companionTarget = result!['agentId'] as String?;
+ }
+ nextId = change.companionTarget;
+ await reloadMachineData(machineId);
+ } else {
+ final error = await createAgent(
+ machineId,
+ engine: change.engine,
+ folder: folder,
+ dsh: source.dsh,
+ name: source.displayName,
+ permissionMode: mode,
+ bypassPermission: mode == 'auto' || mode == 'full',
+ attempt: change.creation,
+ );
+ if (error != null) return error;
+ nextId = change.creation.agentId;
+ }
+ if (nextId == null) {
+ return 'The new agent has not confirmed its start yet. Choose it again to check.';
+ }
+ Agent? next() => machine.agents.where((a) => a.id == nextId).firstOrNull;
+ for (var i = 0; i < 60 && next()?.launchState == 'starting'; i++) {
+ await Future<void>.delayed(const Duration(milliseconds: 250));
+ if (!_machineWorkCurrent(machine, change.revision)) {
+ return 'This switch is no longer active.';
+ }
+ }
+ final target = next();
+ if (target == null ||
+ target.launchState != 'ready' ||
+ !target.terminalAvailable) {
+ change.launchFailed = target?.launchState == 'failed';
+ return target?.launchDetail ??
+ 'The new agent is still starting. Choose it again to check.';
+ }
+ final terminals = allPanes
+ .where((p) => p.machineId == machineId && p.agentId == source.id)
+ .toList();
+ final viewers = allPanes
+ .where((p) => p.machineId == machineId && p.ownerAgentId == source.id)
+ .toList();
+ if (terminals.isEmpty) {
+ return 'The original pane was closed. Open the new agent from Harness Monitor.';
+ }
+ // The old process has stopped and its panes were retained through the
+ // acknowledgement. Replace their references without changing geometry.
+ for (final pane in terminals) {
+ await _detachSession(pane, sendClose: true);
+ if (!_machineWorkCurrent(machine, change.revision)) {
+ return 'This switch is no longer active.';
+ }
+ if (allPanes.contains(pane) && pane.agentId == source.id) {
+ pane.agentId = nextId;
+ }
+ }
+ for (final pane in viewers) {
+ if (allPanes.contains(pane)) pane.ownerAgentId = nextId;
+ }
+ _agentChanges.remove((machineId, source.id));
+ _syncViewerPane(machine, target);
+ // Publish the replacement before yielding: a peer may already have
+ // pruned the stopped source from the shared desk.
+ _persistLayout();
+ notifyListeners();
+ await agentPreference.selectLaunch(change.engine, harnessId: source.dsh);
+ if (!_machineWorkCurrent(machine, change.revision)) {
+ return 'This switch is no longer active.';
+ }
+ for (final pane in terminals) {
+ if (allPanes.contains(pane)) {
+ unawaited(
+ _attachSession(
+ pane,
+ intent: panes.contains(pane) && pane.id == focusedPaneId
+ ? AttachIntent.person
+ : AttachIntent.automatic,
+ ),
+ );
+ }
+ }
+ return null;
+ }
+
/// A fork keeps the originating tab and creation receipt while its prompt is
/// closed. Reopening joins the request; checking an uncertain result never
/// sends a second agent_fork. Old daemons can still return their legacy reply.
@@ -12620,7 +12863,35 @@ class AppNotifier extends ChangeNotifier {
/// Called from [_persistLayout]: whatever just changed, said to the desk as ops.
void _deskQueueDiff() {
if (!_desk.enabled) return;
- final projection = _deskProjection();
+ // A peer can prune the stopped source while its replacement starts.
+ // Keep that pane locally, but never advertise the stopped reference
+ // again. The successful switch publishes the replacement in its slot.
+ final projection = <DeskTab>[];
+ for (final tab in _deskProjection()) {
+ final synced = _desk.synced.where((t) => t.id == tab.id).firstOrNull;
+ final known = {for (final p in synced?.panes ?? <DeskPaneRef>[]) p.key};
+ final panes = tab.panes
+ .where(
+ (p) =>
+ known.contains(p.key) ||
+ _agentChanges[(p.machineId, p.agentId)]?.preservingViews !=
+ true,
+ )
+ .toList();
+ if (panes.length == tab.panes.length) {
+ projection.add(tab);
+ } else if (synced != null || panes.isNotEmpty) {
+ projection.add(
+ DeskTab(
+ id: tab.id,
+ name: tab.name,
+ nameIsCustom: tab.nameIsCustom,
+ panes: panes,
+ layout: synced?.layout,
+ ),
+ );
+ }
+ }
final ops = deskDiff(_desk.synced, projection);
if (ops.isEmpty) return;
// Optimistic: this window believes its own edit. The desk's answer (or a
@@ -12747,8 +13018,17 @@ class AppNotifier extends ChangeNotifier {
final kept = <Swarm>[];
for (final swarm in swarms) {
if (_deskTracks(swarm) && !targetById.containsKey(swarm.id)) {
- released.addAll(swarm.panes);
- continue;
+ if (!swarm.panes.any(_keepsSwitchPane)) {
+ released.addAll(swarm.panes);
+ continue;
+ }
+ // Only the in-flight replacement owns a temporary local slot.
+ // Other panes still follow closures from another window.
+ for (final pane in swarm.panes.toList()) {
+ if (_keepsSwitchPane(pane)) continue;
+ swarm.remove(pane);
+ released.add(pane);
+ }
}
kept.add(swarm);
}
@@ -12775,6 +13055,7 @@ class AppNotifier extends ChangeNotifier {
for (final pane in swarm.panes.toList()) {
if (pane.agentId == null) continue;
if (wanted.contains('${pane.machineId}\u0000${pane.agentId}')) continue;
+ if (_keepsSwitchPane(pane)) continue;
swarm.remove(pane);
released.add(pane);
for (final viewer in swarm.panes.toList()) {
@@ -12864,7 +13145,14 @@ class AppNotifier extends ChangeNotifier {
// At the join a desk that holds no layout for a tab this window has one
// for learns this window's (the diff sends it up); it does not wipe it.
final deskHasOne = tab.layout != null && !tab.layout!.isEmpty;
+ final holdingSlot = swarm.panes.any(
+ (pane) =>
+ pane.agentId != null &&
+ _keepsSwitchPane(pane) &&
+ !wanted.contains('${pane.machineId}\u0000${pane.agentId}'),
+ );
if (layoutMoved &&
+ !holdingSlot &&
(deskHasOne || !joining) &&
_layoutFingerprintOf(tab.layout) !=
_layoutFingerprintOf(_deskLayoutOf(swarm))) {
@@ -12882,7 +13170,9 @@ class AppNotifier extends ChangeNotifier {
// Tab order: the desk's, with this window's local-only tabs where they were.
final localOnly = <(int, Swarm)>[];
for (var i = 0; i < kept.length; i++) {
- if (!_deskTracks(kept[i])) localOnly.add((i, kept[i]));
+ if (!_deskTracks(kept[i]) || !targetById.containsKey(kept[i].id)) {
+ localOnly.add((i, kept[i]));
+ }
}
final ordered = <Swarm>[
for (final tab in target) swarms.firstWhere((s) => s.id == tab.id),
diff --git a/desktop/lib/state/device_finder.dart b/desktop/lib/state/device_finder.dart
index 971fb00fe..0e6463369 100644
--- a/desktop/lib/state/device_finder.dart
+++ b/desktop/lib/state/device_finder.dart
@@ -72,7 +72,7 @@ class DeviceFinder {
'total': search.rows.length, 'busy': false,
'enabled': enabled && !composing, 'canQuery': supported && !composing,
'query': search.query, 'status': '',
- 'action': search.actionLabel(row) == 'Resume & open' ? 'resume' : 'open',
+ 'action': 'open',
'error': _error.isNotEmpty
? _error
: !supported
diff --git a/desktop/lib/state/harness_activity.dart b/desktop/lib/state/harness_activity.dart
index c3ecea145..bcd30831e 100644
--- a/desktop/lib/state/harness_activity.dart
+++ b/desktop/lib/state/harness_activity.dart
@@ -14,7 +14,7 @@ enum HarnessActivity {
starting('◌', 'Starting'),
unknown('◌', 'Status unavailable'),
idle('', 'Idle'),
- paused('||', 'Paused'),
+ paused('×', 'Stopped'),
offline('⊘', 'Offline');
const HarnessActivity(this.mark, this.label);
diff --git a/desktop/lib/state/harness_monitor_controller.dart b/desktop/lib/state/harness_monitor_controller.dart
index 83e90d405..23cca5818 100644
--- a/desktop/lib/state/harness_monitor_controller.dart
+++ b/desktop/lib/state/harness_monitor_controller.dart
@@ -1,4 +1,5 @@
import '../core/models.dart';
+import '../core/harness_defaults.dart';
import '../core/project_folder.dart';
import 'app_state.dart';
@@ -50,7 +51,7 @@ class HarnessMonitorController {
await app.toggleViewerPane(machineId, agent.id);
if (!_current(owner)) return null;
}
- app.showHarnessMonitorTable(machineId, agent.id);
+ app.showHarnessMonitor(machineId, agent.id);
} catch (_) {
return _current(owner)
? 'Could not open Harness Monitor. Try again.'
@@ -91,9 +92,13 @@ class HarnessMonitorController {
label: 'harness-monitor',
at: DateTime.now(),
);
+ await app.agentPreference.load();
+ if (!_current(owner)) return null;
final error = await app.createAgent(
machineId,
- engine: 'opencode',
+ engine:
+ app.agentPreference.engineFor(harnessMonitorId) ??
+ defaultHarnessEngine,
folder: null,
projectFolder: _folder,
dsh: harnessMonitorId,
@@ -133,7 +138,7 @@ class HarnessMonitorController {
if (!app.viewerPaneShown(machineId, agent.id)) {
await app.toggleViewerPane(machineId, agent.id);
}
- app.showHarnessMonitorTable(machineId, agent.id);
+ app.showHarnessMonitor(machineId, agent.id);
return null;
} catch (_) {
return _current(owner)
diff --git a/desktop/lib/state/harness_sessions.dart b/desktop/lib/state/harness_sessions.dart
index dfb5f3892..3ed83dded 100644
--- a/desktop/lib/state/harness_sessions.dart
+++ b/desktop/lib/state/harness_sessions.dart
@@ -90,7 +90,7 @@ class HarnessSession {
: machine.machine.isShared
? 'View only'
: agent.isStopped
- ? (agent.canPauseAndResume ? 'Saved' : 'Resume unavailable')
+ ? (agent.canPauseAndResume ? 'Saved' : 'Open unavailable')
: agent.launchState == 'failed'
? 'Start failed'
: agent.launchState == 'starting'
@@ -111,11 +111,11 @@ class HarnessSession {
: machine.machine.isShared
? 'Shared harnesses are view-only.'
// Only reachable against a daemon too old to report what its engines can
- // resume; a current one offers Pause for every harness it runs.
+ // resume; a current one offers Stop for every harness it runs.
: !agent.canPauseAndResume
? (agent.engine == 'claude' || agent.engine == 'codex'
- ? 'Waiting for a saved conversation before enabling pause and resume.'
- : 'Update the harness CLI on this machine to pause and resume this engine.')
+ ? 'Waiting for a saved conversation before enabling Stop and Open.'
+ : 'Update the harness CLI on this machine to stop and reopen this agent.')
: !canControl
? agent.launchDetail ??
agent.terminalUnavailableReason ??
diff --git a/desktop/lib/state/new_harness.dart b/desktop/lib/state/new_harness.dart
index 5f7dd487f..1fa52f364 100644
--- a/desktop/lib/state/new_harness.dart
+++ b/desktop/lib/state/new_harness.dart
@@ -1,3 +1,5 @@
+import '../core/harness_defaults.dart';
+
import 'dart:async';
import 'dart:convert';
import 'dart:io';
@@ -613,7 +615,9 @@ class NewHarnessController extends ChangeNotifier {
? app.agentPreference.value
: null);
if (remembered != null) return remembered;
- final preferred = selectedHarness?.engine;
+ final preferred = allowed.contains(defaultHarnessEngine)
+ ? defaultHarnessEngine
+ : selectedHarness?.engine;
if (preferred != null && allowed.contains(preferred)) return preferred;
return allowed.first;
}
@@ -888,6 +892,7 @@ class NewHarnessController extends ChangeNotifier {
String get subscriptionLabel => switch (_engine) {
'codex' => 'OpenAI',
'claude' => 'Anthropic',
+ 'opencode' => defaultHarnessModelLabel,
_ => agentLabel,
};
String get modelLabel => _model == null
diff --git a/desktop/lib/state/pane_arrangement.dart b/desktop/lib/state/pane_arrangement.dart
index 9386a2e8b..008b1582f 100644
--- a/desktop/lib/state/pane_arrangement.dart
+++ b/desktop/lib/state/pane_arrangement.dart
@@ -9,15 +9,13 @@ class PaneArrangement {
PaneArrangement(Iterable<Rect> tiles) : tiles = List.unmodifiable(tiles);
final List<Rect> tiles;
- /// The split a harness tab opens with: the viewer on the left at two
- /// thirds, its terminal on the right. A third of a laptop window is the
- /// narrowest a coding agent's interface reads well at (they are laid out
- /// for 80 columns); a board, a part or a slide has enough at two thirds.
+ /// The split a harness tab opens with: 70% viewer on the left, 30% assistant
+ /// terminal on the right. Either pane can be zoomed explicitly.
/// One shared instance, so the code that opened the pair can tell its own
/// split from one the user dragged.
static final viewerBesideTerminal = PaneArrangement(const [
- Rect.fromLTRB(0, 0, 2 / 3, 1),
- Rect.fromLTRB(2 / 3, 0, 1, 1),
+ Rect.fromLTRB(0, 0, .7, 1),
+ Rect.fromLTRB(.7, 0, 1, 1),
]);
static const _epsilon = 0.000001;
diff --git a/desktop/lib/state/swarm_navigation.dart b/desktop/lib/state/swarm_navigation.dart
index 0cc336208..69f9c2bd8 100644
--- a/desktop/lib/state/swarm_navigation.dart
+++ b/desktop/lib/state/swarm_navigation.dart
@@ -316,6 +316,7 @@ class SwarmDestination {
this.machineLabel = '',
this.agentId,
this.modelId,
+ this.agentEngine,
this.storeId,
this.engine,
this.closedId,
@@ -361,6 +362,8 @@ class SwarmDestination {
final DateTime? lastActivityAt;
final String? swarmId, machineId, agentId, engine;
final String? modelId;
+ final String? agentEngine;
+ bool get isAgentChoice => agentEngine != null;
bool get isModel => modelId != null;
final String? storeId;
bool get isStoreEntry => storeId != null;
@@ -414,6 +417,7 @@ class SwarmDestination {
!isNote &&
!isModel &&
!isStoreEntry &&
+ !isAgentChoice &&
pickerQuery == null &&
external == null;
bool get hasView => swarmId != null;
diff --git a/desktop/lib/state/swarm_search.dart b/desktop/lib/state/swarm_search.dart
index 6e0fe19fb..4281503f4 100644
--- a/desktop/lib/state/swarm_search.dart
+++ b/desktop/lib/state/swarm_search.dart
@@ -1,3 +1,5 @@
+import '../widgets/engine_identity.dart';
+
import 'dart:async';
import 'package:flutter/foundation.dart';
@@ -831,7 +833,12 @@ class SwarmSearchController extends ChangeNotifier {
/// The words sent to the session indexes: plain harness search only.
String get _contentQuery =>
- isCommandMode || isHelpMode || isGroupMode || isModelMode || isStoreMode
+ isCommandMode ||
+ isHelpMode ||
+ isGroupMode ||
+ isModelMode ||
+ isStoreMode ||
+ isAgentMode
? ''
: matchQuery;
@@ -934,15 +941,38 @@ class SwarmSearchController extends ChangeNotifier {
String get helpQuery => query.trimLeft().replaceFirst(_helpPrefix, '');
bool get isProjectMode =>
allowsCommands && !commandsOnly && query.trimLeft().startsWith('#');
- static final _quickAccessPrefix = RegExp(r'^[>@#?:*]');
+ static final _quickAccessPrefix = RegExp(r'^[>@#?:*&]');
bool get isMachineMode =>
allowsCommands && !commandsOnly && query.trimLeft().startsWith('@');
bool get isModelMode =>
allowsCommands && !commandsOnly && query.trimLeft().startsWith(':');
+ bool get isAgentMode =>
+ allowsCommands && !commandsOnly && query.trimLeft().startsWith('&');
+ String? agentSelectionMachineId, agentSelectionId;
+ Agent? get agentSelection => app
+ .stateOf(agentSelectionMachineId ?? '')
+ ?.agents
+ .where((a) => a.id == agentSelectionId)
+ .firstOrNull;
+ void setAgentSelection(String machineId, String agentId) {
+ agentSelectionMachineId = machineId;
+ agentSelectionId = agentId;
+ _filter();
+ notifyListeners();
+ }
+
+ bool canSelectAgent(String engine) =>
+ agentSelection != null &&
+ app.stateOf(agentSelectionMachineId!)?.machine.isShared == false &&
+ app
+ .agentSwitchEngines(agentSelectionMachineId!, agentSelection!)
+ .contains(engine);
bool get isStoreMode =>
allowsCommands && !commandsOnly && query.trimLeft().startsWith('*');
bool get isGroupMode => isProjectMode || isMachineMode;
- String get scopePrefix => isMachineMode
+ String get scopePrefix => isAgentMode
+ ? '&'
+ : isMachineMode
? '@'
: isProjectMode
? '#'
@@ -1004,10 +1034,12 @@ class SwarmSearchController extends ChangeNotifier {
? commandQuery
: isHelpMode
? helpQuery
- : isGroupMode || isModelMode || isStoreMode
+ : isGroupMode || isModelMode || isStoreMode || isAgentMode
? query.trimLeft().substring(1).trimLeft()
: query;
- String get title => isCommandMode
+ String get title => isAgentMode
+ ? 'Agents'
+ : isCommandMode
? 'Commands'
: isHelpMode
? 'Quick access'
@@ -1155,7 +1187,9 @@ class SwarmSearchController extends ChangeNotifier {
sessionFilter == SessionFilter.all &&
query.trim().isEmpty;
bool get showsTypeHints => _emptyFinder && selected == null;
- String get hint => isCommandMode
+ String get hint => isAgentMode
+ ? 'Search agents'
+ : isCommandMode
? 'Search commands'
: isHelpMode
? 'Search help'
@@ -1254,7 +1288,9 @@ class SwarmSearchController extends ChangeNotifier {
null => 'Open Harness',
};
- String actionLabel(SwarmDestination? row) => row?.isCreate == true
+ String actionLabel(SwarmDestination? row) => row?.isAgentChoice == true
+ ? 'Change agent'
+ : row?.isCreate == true
? isModelMode
? 'Add'
: row!.title
@@ -1296,7 +1332,7 @@ class SwarmSearchController extends ChangeNotifier {
(agent) => agent.id == row.agentId && agent.isStopped,
) ==
true
- ? 'Resume & open'
+ ? 'Open'
: sessionFilter == SessionFilter.needsInput && row?.agentId != null
? 'Answer'
: placement != null && row != null && alreadyHere(row)
@@ -1330,6 +1366,11 @@ class SwarmSearchController extends ChangeNotifier {
: 'No room for another harness.';
void _refresh({bool force = false}) {
+ if (isAgentMode) {
+ _filter();
+ notifyListeners();
+ return;
+ }
final storeChanged = isStoreMode && _refreshStore();
final next = navigating
? _locations.read(app, projects?.projects ?? const [])
@@ -1486,6 +1527,46 @@ class SwarmSearchController extends ChangeNotifier {
void _filter({bool keepOrder = false}) {
final previous = rows;
+ if (isAgentMode) {
+ final engines = [...allEngines]
+ ..sort(
+ (a, b) => a.id == b.id
+ ? 0
+ : a.id == 'opencode'
+ ? -1
+ : b.id == 'opencode'
+ ? 1
+ : a.label.compareTo(b.label),
+ );
+ rows = [
+ for (final engine in engines)
+ if ('${engine.label} ${engine.id}'.toLowerCase().contains(
+ matchQuery.toLowerCase(),
+ ))
+ SwarmDestination(
+ id: 'engine:${engine.id}',
+ agentEngine: engine.id,
+ engine: engine.id,
+ title: engine.id == 'claude' ? 'Claude Code' : engine.label,
+ detail: agentSelection == null
+ ? 'Focus a harness to change its agent'
+ : !canSelectAgent(engine.id)
+ ? 'Not supported by this harness'
+ : agentSelection?.engine == engine.id
+ ? 'Current agent'
+ : engine.id == 'opencode'
+ ? 'Muse Spark 1.3 · new conversation'
+ : 'New conversation in the same project',
+ swarmId: null,
+ current: agentSelection?.engine == engine.id,
+ ),
+ ];
+ total = engines.length;
+ matchCount = rows.length;
+ cursor = rows.isEmpty ? 0 : cursor.clamp(0, rows.length - 1);
+ _selectedId = selected?.id;
+ return;
+ }
if (isHelpMode) {
// The modes keep the order they are taught in; what follows `?` only
// narrows them, the way a quick-open's own `?` does.
@@ -2066,11 +2147,12 @@ class SwarmSearchController extends ChangeNotifier {
return harnessSessionUnavailable(machine, agent);
}
- bool canSubmit(SwarmDestination? row) =>
- row?.isNote == true ||
- sessionUnavailable(row) != null ||
- sessionFilter == SessionFilter.needsInput &&
- _unavailableAttentionIds.contains(row?.id)
+ bool canSubmit(SwarmDestination? row) => row?.agentEngine != null
+ ? canSelectAgent(row!.agentEngine!)
+ : row?.isNote == true ||
+ sessionUnavailable(row) != null ||
+ sessionFilter == SessionFilter.needsInput &&
+ _unavailableAttentionIds.contains(row?.id)
? false
: isModelDownloadsRow(row)
? true
@@ -2151,7 +2233,9 @@ class SwarmSearchController extends ChangeNotifier {
? SwarmSearchSelection(selected!, SwarmSearchAction.addHere)
: null;
- static String action(SwarmDestination row) => row.isCommand
+ static String action(SwarmDestination row) => row.isAgentChoice
+ ? 'Change agent'
+ : row.isCommand
? 'Run command'
: row.isCreate
? row.title
diff --git a/desktop/lib/store/store_harness_actions.dart b/desktop/lib/store/store_harness_actions.dart
index 15725a92c..65e31ca98 100644
--- a/desktop/lib/store/store_harness_actions.dart
+++ b/desktop/lib/store/store_harness_actions.dart
@@ -206,7 +206,7 @@ class _StoreHarnessActionsState extends State<StoreHarnessActions> {
// Measure the longer label at the user's text size. Matching fixed widths
// keep the pair balanced, while Wrap stacks them on narrow pages.
final label = TextPainter(
- text: TextSpan(text: 'Resume Harness', style: textStyle),
+ text: TextSpan(text: 'Open Harness', style: textStyle),
textDirection: Directionality.of(context),
textScaler: MediaQuery.textScalerOf(context),
)..layout();
@@ -321,7 +321,7 @@ class _StoreHarnessActionsState extends State<StoreHarnessActions> {
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
- const Flexible(child: Text('Resume Harness')),
+ const Flexible(child: Text('Open Harness')),
if (multiple) ...[
const SizedBox(width: 6),
Icon(
diff --git a/desktop/lib/widgets/desktop_search_panel.dart b/desktop/lib/widgets/desktop_search_panel.dart
index 7058e2148..8f5170fa2 100644
--- a/desktop/lib/widgets/desktop_search_panel.dart
+++ b/desktop/lib/widgets/desktop_search_panel.dart
@@ -47,12 +47,15 @@ class DesktopSearchPanel extends StatelessWidget {
('Harnesses', ''),
('Machines', '@'),
('Projects', '#'),
+ ('Agents', '&'),
('Models', ':'),
('Store', '*'),
('Commands', '>'),
];
- String get _prefix => search.isProjectMode
+ String get _prefix => search.isAgentMode
+ ? '&'
+ : search.isProjectMode
? '#'
: search.isMachineMode
? '@'
diff --git a/desktop/lib/widgets/harness_agent_control.dart b/desktop/lib/widgets/harness_agent_control.dart
new file mode 100644
index 000000000..44c95735c
--- /dev/null
+++ b/desktop/lib/widgets/harness_agent_control.dart
@@ -0,0 +1,50 @@
+import 'package:flutter/material.dart';
+
+import '../shared/theme/app_icons.dart';
+import '../core/models.dart';
+import '../state/app_state.dart';
+import 'harness_agent_picker.dart';
+
+/// The agent name, immediately beside the model, opens the shared & picker.
+class HarnessAgentControl extends StatelessWidget {
+ const HarnessAgentControl({
+ super.key,
+ required this.app,
+ required this.machineId,
+ required this.agent,
+ this.enabled = true,
+ });
+ final AppNotifier app;
+ final String machineId;
+ final Agent agent;
+ final bool enabled;
+
+ @override
+ Widget build(BuildContext context) => Tooltip(
+ message: 'Change agent',
+ child: TextButton(
+ key: const ValueKey('pane-agent-control'),
+ style: TextButton.styleFrom(
+ minimumSize: Size.zero,
+ padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 4),
+ ),
+ onPressed: !enabled || app.openAgentPicker == null
+ ? null
+ : () => app.openAgentPicker!(machineId, agent.id),
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Flexible(
+ child: Text(
+ HarnessAgentPicker.label(agent.engine ?? ''),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ ),
+ ),
+ const SizedBox(width: 3),
+ const Icon(AppIcons.chevronDown, size: 12),
+ ],
+ ),
+ ),
+ );
+}
diff --git a/desktop/lib/widgets/harness_agent_picker.dart b/desktop/lib/widgets/harness_agent_picker.dart
new file mode 100644
index 000000000..d531fe941
--- /dev/null
+++ b/desktop/lib/widgets/harness_agent_picker.dart
@@ -0,0 +1,131 @@
+import 'package:harness/shared/theme/app_icons.dart';
+import 'package:flutter/material.dart';
+
+import '../shared/widgets/app_menu.dart';
+import '../theme/app_theme.dart';
+import 'engine_identity.dart';
+import 'transient_menus.dart';
+
+/// The collection's agent. Models and permissions remain in its real terminal.
+class HarnessAgentPicker extends StatefulWidget {
+ const HarnessAgentPicker({
+ super.key,
+ required this.engine,
+ required this.onSelected,
+ this.busy = false,
+ this.engines = const ['opencode', 'codex', 'claude'],
+ this.compact = false,
+ this.showPrefix = true,
+ this.triggerKey,
+ });
+
+ final String? engine;
+ final ValueChanged<String>? onSelected;
+ final bool busy;
+ final List<String> engines;
+ final bool compact, showPrefix;
+ final Key? triggerKey;
+
+ static String label(String engine) =>
+ engine == 'claude' ? 'Claude Code' : engineIdentity(engine).label;
+
+ @override
+ State<HarnessAgentPicker> createState() => _HarnessAgentPickerState();
+}
+
+class _HarnessAgentPickerState extends State<HarnessAgentPicker> {
+ final _menu = MenuController();
+ final _trigger = FocusNode();
+ final _choices = <String, FocusNode>{};
+ FocusNode _choice(String engine) =>
+ _choices.putIfAbsent(engine, FocusNode.new);
+ VoidCallback? _unregister;
+
+ @override
+ void dispose() {
+ _unregister?.call();
+ _trigger.dispose();
+ for (final focus in _choices.values) {
+ focus.dispose();
+ }
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) => Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ if (widget.showPrefix)
+ Text(
+ 'Powered by',
+ style: Theme.of(context).textTheme.bodySmall
+ ?.copyWith(color: AppColors.textSoft),
+ ),
+ if (widget.showPrefix) const SizedBox(width: 4),
+ MenuAnchor(
+ controller: _menu,
+ childFocusNode: _trigger,
+ onOpen: () {
+ _unregister = registerTransientMenu(_menu.close);
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted && _menu.isOpen) {
+ _choice(
+ widget.engines.contains(widget.engine)
+ ? widget.engine!
+ : widget.engines.first,
+ ).requestFocus();
+ }
+ });
+ },
+ onClose: () {
+ _unregister?.call();
+ _unregister = null;
+ },
+ menuChildren: [
+ for (final choice in widget.engines)
+ AppMenuItem(
+ label: HarnessAgentPicker.label(choice),
+ leading: EngineMark(engine: choice),
+ selected: widget.engine == choice,
+ focusNode: _choice(choice),
+ onPressed: () {
+ _menu.close();
+ widget.onSelected?.call(choice);
+ },
+ ),
+ ],
+ builder: (context, controller, child) => TextButton(
+ key: widget.triggerKey ?? const ValueKey('harness-agent-picker'),
+ style: TextButton.styleFrom(
+ minimumSize: Size.zero,
+ padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 5),
+ ),
+ focusNode: _trigger,
+ onPressed: widget.busy || widget.onSelected == null
+ ? null
+ : () =>
+ controller.isOpen ? controller.close() : controller.open(),
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ if (widget.engine != null) ...[
+ EngineMark(engine: widget.engine, size: 16),
+ if (!widget.compact) const SizedBox(width: 7),
+ ],
+ if (!widget.compact)
+ Text(
+ widget.busy
+ ? 'Opening…'
+ : widget.engine == null
+ ? 'Choose agent'
+ : HarnessAgentPicker.label(widget.engine!),
+ ),
+ const SizedBox(width: 4),
+ const Icon(AppIcons.chevronDown, size: 16),
+ ],
+ ),
+ ),
+ ),
+ ],
+ );
+}
diff --git a/desktop/lib/widgets/pane_header_actions.dart b/desktop/lib/widgets/pane_header_actions.dart
index 888471c52..d3d31d8f1 100644
--- a/desktop/lib/widgets/pane_header_actions.dart
+++ b/desktop/lib/widgets/pane_header_actions.dart
@@ -8,9 +8,10 @@ class PaneHeaderActions extends StatelessWidget {
this.details,
this.trailing,
this.modelPicker,
+ this.agentPicker,
});
- final Widget? details, trailing, modelPicker;
+ final Widget? details, trailing, modelPicker, agentPicker;
@override
Widget build(BuildContext context) => LayoutBuilder(
@@ -30,6 +31,16 @@ class PaneHeaderActions extends StatelessWidget {
],
),
),
+ if (agentPicker != null)
+ ConstrainedBox(
+ constraints: BoxConstraints(
+ maxWidth: constraints.maxWidth.isFinite
+ ? constraints.maxWidth *
+ (details != null || trailing != null ? .3 : .5)
+ : 140,
+ ),
+ child: agentPicker!,
+ ),
if (modelPicker != null) ...[
if (details != null || trailing != null) const SizedBox(width: 8),
// Let a short model use only its natural width, leaving the remaining
@@ -38,7 +49,11 @@ class PaneHeaderActions extends StatelessWidget {
constraints: BoxConstraints(
maxWidth: constraints.maxWidth.isFinite
? constraints.maxWidth *
- (details != null || trailing != null ? .4 : 1)
+ (details != null || trailing != null
+ ? .4
+ : agentPicker != null
+ ? .5
+ : 1)
: 232,
),
child: modelPicker!,
diff --git a/desktop/lib/widgets/swarm_resource_preview.dart b/desktop/lib/widgets/swarm_resource_preview.dart
index 29486dd4a..d44bf9bc0 100644
--- a/desktop/lib/widgets/swarm_resource_preview.dart
+++ b/desktop/lib/widgets/swarm_resource_preview.dart
@@ -462,7 +462,7 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
SessionFilter.all => 'Show all harnesses',
SessionFilter.needsInput => 'Show harnesses needing input',
SessionFilter.running => 'Show running harnesses',
- SessionFilter.paused => 'Show paused harnesses',
+ SessionFilter.paused => 'Show stopped harnesses',
},
() => widget.search.setSessionFilter(filter),
command: 'picker.filter.${filter.name}',
@@ -565,17 +565,15 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
void _toggleHarness() {
final session = _session;
if (session == null || !session.canControl) return;
+ if (session.agent.isStopped) {
+ _open();
+ return;
+ }
final search = widget.search;
search.holdRow(row!);
unawaited(
_run(() async {
try {
- if (session.agent.isStopped) {
- return (await app.resumeAgent(
- session.machineId,
- session.agent.id,
- )).error;
- }
return await app.pauseAgent(session.machineId, session.agent.id);
} finally {
search.releaseRow(session.id);
@@ -773,6 +771,15 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
final selected = row;
if (selected == null) return const [];
final busy = _pending.contains(selected.id);
+ if (selected.isAgentChoice) {
+ return [
+ _ResourceAction(
+ search.actionLabel(selected),
+ search.canAccept && !busy ? _open : null,
+ command: 'picker.accept',
+ ),
+ ];
+ }
if (search.isModelDownloadsRow(selected)) {
return [
_ResourceAction(
@@ -961,19 +968,13 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
? 'Answer'
: selected.isProject
? 'Harnesses'
- : session?.agent.isStopped == true
- ? 'Resume & open'
: 'Open',
search.canAccept && !busy && !pendingControl ? _open : null,
command: 'picker.accept',
),
- if (session != null)
+ if (session != null && !session.agent.isStopped)
_ResourceAction(
- busy || pendingControl
- ? 'Working…'
- : session.agent.isStopped
- ? 'Resume'
- : 'Pause',
+ busy || pendingControl ? 'Working…' : 'Stop',
!busy && !pendingControl && session.canControl
? _toggleHarness
: null,
@@ -981,7 +982,7 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
hint:
session.controlUnavailable ??
(session.agent.resumesFreshConversation
- ? 'Resumes as a new conversation.'
+ ? 'Opens as a new conversation.'
: null),
),
];
@@ -1113,7 +1114,7 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
SessionFilter.all => 'All',
SessionFilter.needsInput => 'Needs input',
SessionFilter.running => 'Running',
- SessionFilter.paused => 'Paused',
+ SessionFilter.paused => 'Stopped',
}}',
() => search.setSessionFilter(
SessionFilter.values[(search.sessionFilter.index + 1) %
@@ -1858,6 +1859,15 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
)
: widget.search.showsTypeHints
? _typeHints()
+ : row?.isAgentChoice == true
+ ? _details([
+ row!.title,
+ row!.detail,
+ if (widget.search.canAccept && !row!.current) ...[
+ '',
+ 'Saves the current conversation, then starts a new one in the same folder. Your panes stay in place.',
+ ],
+ ])
: row?.isCreate == true
? _details([
...widget.search.createDescription.split('\n'),
diff --git a/desktop/lib/widgets/swarm_switcher.dart b/desktop/lib/widgets/swarm_switcher.dart
index e7c6cf1ce..609d887cd 100644
--- a/desktop/lib/widgets/swarm_switcher.dart
+++ b/desktop/lib/widgets/swarm_switcher.dart
@@ -969,7 +969,8 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
: desktop
? row.isStore
? StoreMark(size: 28, enabled: canSubmit)
- : row.agentId != null ||
+ : row.isAgentChoice ||
+ row.agentId != null ||
row.isStoreEntry ||
(row.isSwarm && row.members.length == 1)
? EngineMark(
@@ -1019,7 +1020,8 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
)
: row.isStore
? StoreMark(size: 20, enabled: canSubmit)
- : row.agentId != null ||
+ : row.isAgentChoice ||
+ row.agentId != null ||
(row.isSwarm && row.members.length == 1)
? EngineMark(
engine: row.engine,
diff --git a/desktop/lib/widgets/terminal_panel.dart b/desktop/lib/widgets/terminal_panel.dart
index cac26cfeb..e299f8829 100644
--- a/desktop/lib/widgets/terminal_panel.dart
+++ b/desktop/lib/widgets/terminal_panel.dart
@@ -44,6 +44,7 @@ import '../shared/theme/app_theme.dart' as grid;
import '../shared/theme/workspace_bar_style.dart';
import '../theme/app_theme.dart';
import 'engine_identity.dart';
+import 'harness_agent_control.dart';
import 'harness_activity_mark.dart';
import 'grid_model_picker.dart';
import 'pane_header_actions.dart';
@@ -2732,7 +2733,8 @@ class _TerminalHeader extends StatelessWidget {
// Engines without a picker keep their existing header width.
final showModelPicker = modelPickerSupports(session.engineId);
// The picker: a model id up to 220px and its padding.
- final pickerWidth = showModelPicker ? 250.0 : 0.0;
+ final pickerWidth =
+ (showModelPicker ? 250.0 : 0.0) + (agent != null ? 90.0 : 0.0);
final showSplit = compact || onSplitDown != null || onSplitRight != null;
final showZoom = compact || onToggleZoom != null;
final controlsWidth =
@@ -2809,7 +2811,10 @@ class _TerminalHeader extends StatelessWidget {
final desiredRightWidth = narrow
? math.max(
- controlsWidth + (showModelPicker ? 96.0 : 0.0) + badgeWidth,
+ controlsWidth +
+ (showModelPicker ? 96.0 : 0.0) +
+ (agent != null ? 90.0 : 0.0) +
+ badgeWidth,
constraints.maxWidth * .36,
)
: math.max(
@@ -2825,7 +2830,7 @@ class _TerminalHeader extends StatelessWidget {
math.min(
pickerWidth,
math.max(
- 56.0,
+ agent != null ? 180.0 : 56.0,
(constraints.maxWidth - controlsWidth) * .38,
),
)
@@ -3006,6 +3011,16 @@ class _TerminalHeader extends StatelessWidget {
maxWidth: math.max(0, rightWidth - controlsWidth),
),
child: PaneHeaderActions(
+ agentPicker: agent == null
+ ? null
+ : HarnessAgentControl(
+ app: notifier,
+ machineId: session.machineId,
+ agent: agent,
+ enabled:
+ machine?.machine.isShared == false &&
+ machine?.nodeOnline != false,
+ ),
trailing: showPr
? ConstrainedBox(
constraints: BoxConstraints(maxWidth: badgeWidth),
diff --git a/desktop/lib/widgets/web_pane_panel.dart b/desktop/lib/widgets/web_pane_panel.dart
index 926bef47e..9fa6136f8 100644
--- a/desktop/lib/widgets/web_pane_panel.dart
+++ b/desktop/lib/widgets/web_pane_panel.dart
@@ -1,4 +1,5 @@
import 'package:harness/shared/theme/app_icons.dart';
+
import 'dart:async';
import 'dart:convert';
@@ -197,7 +198,7 @@ class _WebPanePanelState extends State<WebPanePanel> {
if (!mounted ||
current == null ||
Uri.tryParse(current)?.origin !=
- Uri.tryParse(widget.pane.url ?? '')?.origin) {
+ Uri.tryParse(widget.pane.url ?? '')?.origin) {
return;
}
final action = jsonDecode(message.message);
@@ -389,14 +390,6 @@ class _WebPanePanelState extends State<WebPanePanel> {
),
),
const SizedBox(width: 8),
- if (_isMonitor && !widget.zoomed)
- TextButton(
- onPressed: () => widget.notifier.showHarnessMonitorTable(
- widget.pane.machineId,
- widget.pane.ownerAgentId!,
- ),
- child: const Text('Hide assistant'),
- ),
// coverage:ignore-start
// Only a real webview's navigation sets _loading; none under test.
if (_loading)
diff --git a/desktop/test/agent_change_test.dart b/desktop/test/agent_change_test.dart
new file mode 100644
index 000000000..b6f5c6293
--- /dev/null
+++ b/desktop/test/agent_change_test.dart
@@ -0,0 +1,418 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/api/api_client.dart';
+import 'package:harness/auth/auth_session.dart';
+import 'package:harness/core/config.dart';
+import 'package:harness/state/desk_sync.dart';
+import 'package:harness/core/dsh_catalog.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/state/swarm_search.dart';
+import 'package:harness/widgets/engine_identity.dart';
+
+import 'support/harness_monitor.dart';
+import 'swarm_screen_test.dart' show mount, terminal;
+import 'swarm_state_test.dart' show createApp;
+
+class SwitchConnection extends MonitorConnection {
+ late AppNotifier app;
+ final events = <String>[];
+ String? closeError;
+ Completer<void>? holdClose;
+
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) async {
+ if (type == 'agent_close') {
+ events.add('save/stop');
+ expect(payload['mode'], 'now');
+ expect(payload['sessionId'], 'saved-conversation');
+ await holdClose?.future;
+ if (closeError != null) {
+ return {'error': 'SAVE_FAILED', 'detail': closeError};
+ }
+ await app.handleEventForTest('m', {
+ 'type': 'agent_deleted',
+ 'agentId': 'a0',
+ 'payload': {'agentId': 'a0'},
+ });
+ return {'closed': true};
+ }
+ if (type == 'agent_create') events.add('start');
+ final result = await super.request(
+ type,
+ payload: payload,
+ timeout: timeout,
+ );
+ if (result['agent'] case final Map<String, dynamic> agent) {
+ return {
+ ...result,
+ 'agent': {
+ ...agent,
+ 'engine': creations.last['engine'],
+ 'project': {'name': 'work', 'cwd': '/projects/work'},
+ if (creations.last['dsh'] != null)
+ 'viewerUrl': 'http://127.0.0.1:4179/',
+ },
+ };
+ }
+ return result;
+ }
+}
+
+AppNotifier fixture(
+ SwitchConnection connection, {
+ bool viewer = false,
+ bool companion = false,
+}) {
+ final app = createApp(connectionForTest: (_) => connection, connected: true);
+ connection.app = app;
+ final source = Agent(
+ id: 'a0',
+ name: 'Work',
+ engine: 'codex',
+ sessionId: 'saved-conversation',
+ createdAt: DateTime.utc(2026, 10, 1),
+ closeSupported: true,
+ terminalAvailable: true,
+ permissionMode: 'ask',
+ project: const AgentProject(name: 'work', cwd: '/projects/work'),
+ dsh: companion
+ ? 'autonomous/pair'
+ : viewer
+ ? 'test/viewer'
+ : null,
+ viewerUrl: viewer ? 'http://127.0.0.1:4179/' : null,
+ );
+ app.stateOf('m')!.agents = [source, app.stateOf('m')!.agents[1]];
+ if (viewer) {
+ app.stateOf('m')!.dsh.replace([
+ const DshEntry(
+ id: 'test/viewer',
+ name: 'Viewer',
+ description: '',
+ engine: 'codex',
+ engines: ['codex', 'opencode', 'claude'],
+ installed: true,
+ ),
+ ]);
+ }
+ return app;
+}
+
+class SwitchDeskApi extends ApiClient {
+ SwitchDeskApi() : super(config: AppConfig.dev, session: AuthSession());
+ DeskDoc doc = const DeskDoc(revision: 0, tabs: []);
+ final batches = <List<Map<String, dynamic>>>[];
+ Map<String, dynamic> get json => {
+ 'revision': doc.revision,
+ 'tabs': [for (final tab in doc.tabs) tab.toJson()],
+ };
+ @override
+ Future<Map<String, dynamic>?> desk() async => json;
+ @override
+ Future<Map<String, dynamic>?> deskOps(List<Map<String, dynamic>> ops) async {
+ batches.add(ops);
+ doc = DeskDoc(
+ revision: doc.revision + 1,
+ tabs: applyDeskOps(doc.tabs, ops),
+ );
+ return json;
+ }
+}
+
+void main() {
+ for (final entireTab in [true, false]) {
+ test(
+ 'switch keeps its slot when a peer prunes ${entireTab ? 'the tab' : 'the pane'}',
+ () async {
+ final connection = SwitchConnection()..holdCreation = Completer<void>();
+ final app = fixture(connection);
+ final api = SwitchDeskApi();
+ app.api = api;
+ addTearDown(app.dispose);
+ await app.addAgentToSwarm('m', 'a0');
+ if (!entireTab) await app.addAgentToSwarm('m', 'a1');
+ app.newSwarm(name: 'Peer tab');
+ await app.addAgentToSwarm('m', 'a1');
+ await app.deskStartForTest();
+ final original = app.swarms.first;
+ app.selectSwarm(original.id);
+ final pane = original.panes.first;
+ final sizes = Map.of(original.paneSizes);
+ final switching = app.changeAgent('m', 'a0', 'claude');
+ // The close is acknowledged but creation has not returned yet.
+ for (var i = 0; i < 20 && connection.creations.isEmpty; i++) {
+ await Future<void>.delayed(Duration.zero);
+ }
+ expect(connection.creations, hasLength(1));
+ api.doc = DeskDoc(
+ revision: api.doc.revision + 1,
+ tabs: [
+ for (final tab in api.doc.tabs)
+ if (tab.id != original.id)
+ tab.copyWith(name: 'Renamed remotely', nameIsCustom: true)
+ else if (!entireTab)
+ DeskTab(
+ id: tab.id,
+ name: tab.name,
+ nameIsCustom: tab.nameIsCustom,
+ panes: tab.panes.where((p) => p.agentId != 'a0').toList(),
+ ),
+ ],
+ );
+ api.batches.clear();
+ await app.deskFetchForTest();
+ await app.deskFlushForTest();
+ expect(app.swarms.first, same(original));
+ expect(original.panes.first, same(pane));
+ expect(original.paneSizes, sizes);
+ expect(app.activeSwarmId, original.id);
+ expect(app.swarms.last.name, 'Renamed remotely');
+ expect(
+ api.doc.tabs.expand((t) => t.panes).where((p) => p.agentId == 'a0'),
+ isEmpty,
+ );
+ connection.holdCreation!.complete();
+ expect(await switching, isNull);
+ await app.deskFlushForTest();
+ expect(original.panes.first, same(pane));
+ expect(pane.agentId, 'local-session');
+ expect(
+ api.doc.tabs
+ .firstWhere((t) => t.id == original.id)
+ .panes
+ .map((p) => p.agentId),
+ contains('local-session'),
+ );
+ expect(
+ api.doc.tabs.expand((t) => t.panes).where((p) => p.agentId == 'a0'),
+ isEmpty,
+ );
+ },
+ );
+ }
+
+ test('saves before starting, then replaces every view without changing tabs or layout', () async {
+ final connection = SwitchConnection();
+ final app = fixture(connection, viewer: true);
+ addTearDown(app.dispose);
+ await app.addAgentToSwarm('m', 'a0');
+ app.newSwarm(name: 'Second tab');
+ await app.addAgentToSwarm('m', 'a0', swarmId: app.activeSwarmId);
+ await app.addAgentToSwarm('m', 'a1');
+ final panes = [...app.allPanes];
+ final tabs = [...app.swarms];
+ final active = app.activeSwarmId;
+ final focus = app.focusedPaneId;
+ final sizes = [for (final tab in tabs) Map.of(tab.paneSizes)];
+
+ expect(await app.changeAgent('m', 'a0', 'opencode'), isNull);
+ expect(connection.events, ['save/stop', 'start']);
+ expect(connection.creations.single, containsPair('engine', 'opencode'));
+ expect(connection.creations.single, containsPair('cwd', '/projects/work'));
+ expect(connection.creations.single, containsPair('dsh', 'test/viewer'));
+ expect(connection.creations.single, containsPair('permissionMode', 'ask'));
+ expect(app.swarms, tabs);
+ expect(app.allPanes, panes);
+ expect(app.activeSwarmId, active);
+ expect(app.focusedPaneId, focus);
+ expect([for (final tab in tabs) tab.paneSizes], sizes);
+ expect(
+ app.swarms.where((s) => s.panes.any((p) => p.agentId == 'manager')),
+ hasLength(2),
+ );
+ expect(
+ app.allPanes.where((p) => p.ownerAgentId == 'manager'),
+ hasLength(2),
+ );
+ expect(
+ app.stateOf('m')!.agents.firstWhere((a) => a.id == 'a0').isStopped,
+ isTrue,
+ );
+ expect(app.agentPreference.engineFor('test/viewer'), 'opencode');
+ });
+
+ test(
+ 'stopping one shared session removes its views from every tab',
+ () async {
+ final connection = SwitchConnection();
+ final app = fixture(connection, viewer: true);
+ addTearDown(app.dispose);
+ await app.addAgentToSwarm('m', 'a0');
+ app.newSwarm(name: 'Second tab');
+ await app.addAgentToSwarm('m', 'a0');
+ await app.addAgentToSwarm('m', 'a1');
+ await app.handleEventForTest('m', {
+ 'type': 'agent_deleted',
+ 'agentId': 'a0',
+ 'payload': {'agentId': 'a0'},
+ });
+ expect(
+ app.swarms
+ .expand((s) => s.panes)
+ .where((p) => p.agentId == 'a0' || p.ownerAgentId == 'a0'),
+ isEmpty,
+ );
+ expect(app.allPanes.single.agentId, 'a1');
+ },
+ );
+
+ test('Companions saves first and keeps every pane in place', () async {
+ final connection = SwitchConnection();
+ final app = fixture(connection, companion: true);
+ addTearDown(app.dispose);
+ await app.addAgentToSwarm('m', 'a0');
+ app.newSwarm(name: 'Another view');
+ await app.addAgentToSwarm('m', 'a0');
+ final panes = [...app.allPanes];
+ expect(await app.changeAgent('m', 'a0', 'opencode'), isNotNull);
+ expect(
+ connection.events,
+ isEmpty,
+ reason: 'Bind the collection before stopping it.',
+ );
+ app.canChangeCompanionAgent = (machine, id) => machine == 'm' && id == 'a0';
+ app.changeCompanionAgent = (source, engine) async {
+ expect(connection.events, ['save/stop']);
+ expect(source, 'a0');
+ expect(engine, 'opencode');
+ connection.inventory = [
+ {
+ 'id': 'a0',
+ 'engine': 'codex',
+ 'dsh': 'autonomous/pair',
+ 'sessionId': 'saved-conversation',
+ 'createdAt': '2026-10-01T00:00:00.000Z',
+ 'status': 'stopped',
+ 'terminal': {'available': false},
+ 'project': {'cwd': '/projects/work', 'name': 'work'},
+ },
+ {
+ 'id': 'next-pair',
+ 'engine': engine,
+ 'dsh': 'autonomous/pair',
+ 'terminal': {'available': true},
+ 'project': {'cwd': '/projects/work', 'name': 'work'},
+ },
+ ];
+ return {'ok': true, 'agentId': 'next-pair'};
+ };
+ expect(await app.changeAgent('m', 'a0', 'opencode'), isNull);
+ expect(app.allPanes, panes);
+ expect(
+ app.swarms.where((s) => s.panes.any((p) => p.agentId == 'next-pair')),
+ hasLength(2),
+ );
+ expect(
+ connection.creations,
+ isEmpty,
+ reason: 'Companions owns its collection history.',
+ );
+ });
+
+ test('a failed save leaves the agent and every pane alone; another choice can retry', () async {
+ final connection = SwitchConnection()..closeError = 'Disk is full';
+ final app = fixture(connection);
+ addTearDown(app.dispose);
+ await app.addAgentToSwarm('m', 'a0');
+ final pane = app.panes.single;
+ expect(await app.changeAgent('m', 'a0', 'opencode'), 'Disk is full');
+ expect(connection.creations, isEmpty);
+ expect(app.panes.single, same(pane));
+ expect(pane.agentId, 'a0');
+ connection.closeError = null;
+ expect(await app.changeAgent('m', 'a0', 'claude'), isNull);
+ expect(connection.creations.single['engine'], 'claude');
+ });
+
+ test('a failed launch preserves the stopped session and permits a different agent', () async {
+ final connection = SwitchConnection()
+ ..creationError = 'OpenCode is missing';
+ final app = fixture(connection);
+ addTearDown(app.dispose);
+ await app.addAgentToSwarm('m', 'a0');
+ final pane = app.panes.single;
+ expect(
+ await app.changeAgent('m', 'a0', 'opencode'),
+ contains('OpenCode is missing'),
+ );
+ expect(pane.agentId, 'a0');
+ expect(
+ app.stateOf('m')!.agents.firstWhere((a) => a.id == 'a0').isStopped,
+ isTrue,
+ );
+ connection.creationError = null;
+ expect(await app.changeAgent('m', 'a0', 'claude'), isNull);
+ expect(connection.events, ['save/stop', 'start', 'start']);
+ });
+
+ test(
+ 'concurrent switches and a lost creation reply cannot start duplicates',
+ () async {
+ final connection = SwitchConnection()
+ ..holdClose = Completer<void>()
+ ..loseFirstReply = true;
+ final app = fixture(connection);
+ addTearDown(app.dispose);
+ await app.addAgentToSwarm('m', 'a0');
+ final first = app.changeAgent('m', 'a0', 'opencode');
+ final repeated = app.changeAgent('m', 'a0', 'opencode');
+ expect(identical(first, repeated), isTrue);
+ connection.holdClose!.complete();
+ await first;
+ if (app.panes.single.agentId == 'a0') {
+ expect(await app.changeAgent('m', 'a0', 'opencode'), isNull);
+ }
+ expect(connection.creations, hasLength(1));
+ expect(app.panes.single.agentId, 'local-session');
+ },
+ );
+
+ test('& searches all agents and only submits supported choices for its exact source', () {
+ final connection = SwitchConnection();
+ final app = fixture(connection, viewer: true);
+ addTearDown(app.dispose);
+ final search = SwarmSearchController(app, []);
+ addTearDown(search.dispose);
+ search.setQuery('&');
+ expect(search.isAgentMode, isTrue);
+ expect(search.rows, hasLength(allEngines.length));
+ expect(search.submit(), isNull);
+ search.setAgentSelection('m', 'a0');
+ expect(search.rows.first.agentEngine, 'opencode');
+ expect(search.submit()?.destination.agentEngine, 'opencode');
+ search.setQuery('& claude');
+ expect(search.rows.single.title, 'Claude Code');
+ search.setQuery(
+ '& ${allEngines.firstWhere((e) => !['codex', 'opencode', 'claude'].contains(e.id)).id}',
+ );
+ expect(search.rows.single.detail, 'Not supported by this harness');
+ expect(search.submit(), isNull);
+ });
+
+ testWidgets(
+ 'the pane agent name opens the shared picker and cancellation leaves input alone',
+ (tester) async {
+ final app = createApp();
+ app.stateOf('m')!.nodeOnline = true;
+ app.adoptSessionForTest(terminal('a0', []));
+ await mount(tester, app);
+ await tester.tap(find.byKey(const ValueKey('pane-agent-control')));
+ await tester.pump();
+ final field = tester.widget<TextField>(
+ find.byKey(const ValueKey('swarm-search-input')),
+ );
+ expect(field.controller!.text.trim(), '&');
+ expect(find.text('OpenCode'), findsWidgets);
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ },
+ );
+}
diff --git a/desktop/test/companion_engine_picker_test.dart b/desktop/test/companion_engine_picker_test.dart
index 600778ce4..b88992133 100644
--- a/desktop/test/companion_engine_picker_test.dart
+++ b/desktop/test/companion_engine_picker_test.dart
@@ -80,7 +80,7 @@ void main() {
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pumpAndSettle();
- expect(find.byType(AppMenuItem), findsNWidgets(2));
+ expect(find.byType(AppMenuItem), findsNWidgets(3));
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pumpAndSettle();
diff --git a/desktop/test/harness_monitor_test.dart b/desktop/test/harness_monitor_test.dart
index 42e384ce5..acdfd8398 100644
--- a/desktop/test/harness_monitor_test.dart
+++ b/desktop/test/harness_monitor_test.dart
@@ -23,7 +23,7 @@ void main() {
tearDown(() => app.dispose());
test(
- 'one monitor tab, full width by default, with no unsolicited prompt',
+ 'one monitor tab, 70/30 viewer and assistant, with no unsolicited prompt',
() async {
app.installed = false;
app.stateOf('m')!.agents = [
@@ -35,8 +35,10 @@ void main() {
final monitorTab = app.activeSwarmId, count = app.swarms.length;
final viewer = app.panes.singleWhere((p) => p.isWeb);
expect(monitorTab, isNot(original));
- expect(app.zoomedPaneId, viewer.id);
+ expect(app.zoomedPaneId, isNull);
expect(app.focusedPane, viewer);
+ expect(app.activeSwarm.paneSizes['2:manual']!.tiles.first.width, .7);
+ expect(app.panes.map((p) => p.isWeb), [true, false]);
expect(app.activeSwarm.name, harnessMonitorName);
expect(app.installs, 1);
expect(connection.creations.single['engine'], 'opencode');
@@ -98,8 +100,8 @@ void main() {
expect(app.zoomedPaneId, isNull);
expect(app.focusedPane, terminal);
expect(app.sent, isEmpty);
- app.showHarnessMonitorTable('m', 'manager');
- expect(app.zoomedPaneId, viewer.id);
+ app.showHarnessMonitor('m', 'manager');
+ expect(app.zoomedPaneId, isNull);
expect(
await app.handleHarnessMonitorAction(viewer, {
'action': 'open',
@@ -126,7 +128,7 @@ void main() {
expect(app.viewerPaneShown('m', 'manager'), isFalse);
expect(await app.harnessMonitor.open(), isNull);
expect(app.viewerPaneShown('m', 'manager'), isTrue);
- expect(app.zoomedPaneId, app.panes.singleWhere((p) => p.isWeb).id);
+ expect(app.zoomedPaneId, isNull);
expect(connection.creations, hasLength(1));
});
@@ -240,6 +242,100 @@ void main() {
},
);
+ test('Open a stopped session with no pane selects a new tab', () async {
+ app.stateOf('other')!
+ ..connectionStatus = ConnectionStatus.connected
+ ..nodeOnline = true;
+ await app.harnessMonitor.open();
+ final monitorTab = app.activeSwarmId;
+ final source = app.panes.singleWhere((p) => p.isWeb);
+ connection.inventory = [
+ {
+ 'id': 'closed',
+ 'name': 'Closed work',
+ 'engine': 'codex',
+ 'status': 'stopped',
+ 'resumeMode': 'conversation',
+ 'terminal': {'available': false},
+ },
+ ];
+ app.onReopen = (machineId, agentId) {
+ expect(machineId, 'other');
+ expect(agentId, 'closed');
+ connection.inventory = [
+ {
+ 'id': 'closed',
+ 'name': 'Closed work',
+ 'engine': 'codex',
+ 'terminal': {'available': true},
+ },
+ ];
+ app.stateOf(machineId)!.agents = [
+ ...app.stateOf(machineId)!.agents.where((a) => a.id != agentId),
+ Agent.fromJson(connection.inventory!.single),
+ ];
+ };
+ expect(
+ await app.handleHarnessMonitorAction(source, {
+ 'action': 'open',
+ 'machineId': 'other',
+ 'agentId': 'closed',
+ }),
+ isNull,
+ );
+ expect(app.resumes, 1);
+ expect(app.activeSwarmId, isNot(monitorTab));
+ expect(app.focusedPane?.agentId, 'closed');
+ expect(app.focusedPane?.machineId, 'other');
+ final reopenedTab = app.activeSwarmId;
+ final count = app.swarms.length;
+ app.selectSwarm(monitorTab);
+ expect(
+ await app.handleHarnessMonitorAction(source, {
+ 'action': 'open',
+ 'machineId': 'other',
+ 'agentId': 'closed',
+ }),
+ isNull,
+ );
+ expect(app.activeSwarmId, reopenedTab);
+ expect(app.swarms, hasLength(count));
+ expect(app.resumes, 1);
+ });
+
+ test(
+ 'a failed Open leaves the monitor selected and creates no empty tab',
+ () async {
+ app.stateOf('other')!
+ ..connectionStatus = ConnectionStatus.connected
+ ..nodeOnline = true;
+ await app.harnessMonitor.open();
+ final source = app.panes.singleWhere((p) => p.isWeb);
+ final tab = app.activeSwarmId, count = app.swarms.length;
+ connection.inventory = [
+ {
+ 'id': 'closed',
+ 'engine': 'codex',
+ 'status': 'stopped',
+ 'resumeMode': 'conversation',
+ 'terminal': {'available': false},
+ },
+ ];
+ app.resumeError = 'Reconnect and try again.';
+ expect(
+ await app.handleHarnessMonitorAction(source, {
+ 'action': 'open',
+ 'machineId': 'other',
+ 'agentId': 'closed',
+ }),
+ app.resumeError,
+ );
+ expect(app.activeSwarmId, tab);
+ expect(app.swarms, hasLength(count));
+ expect(app.allPanes.any((p) => p.agentId == 'closed'), isFalse);
+ },
+ );
+
for (final nativeTabs in [false, true]) {
for (final resources in [false, true]) {
testWidgets(
@@ -271,26 +367,33 @@ void main() {
} else {
await openWorkspaceManagement(tester, 'harnesses');
}
- await tester.pumpAndSettle();
+ await tester.pump();
+ await tester.pump(const Duration(milliseconds: 350));
}
await open();
expect(app.activeSwarm.name, harnessMonitorName);
expect(find.byType(WebPanePanel), findsOneWidget);
- expect(app.zoomedPaneId, app.panes.singleWhere((p) => p.isWeb).id);
+ expect(app.zoomedPaneId, isNull);
final count = app.swarms.length;
app.selectedMachineId = 'other';
await open();
expect(app.swarms, hasLength(count));
expect(connection.creations, hasLength(1));
final viewer = app.panes.singleWhere((p) => p.isWeb);
- await app.handleHarnessMonitorAction(viewer, {'action': 'assistant'});
- // The fixture terminal has no daemon to finish its attachment animation.
+ expect(find.text('Hide assistant'), findsNothing);
+ tester
+ .widget<WebPanePanel>(find.byType(WebPanePanel))
+ .onToggleZoom!();
+ await tester.pump();
await tester.pump(const Duration(milliseconds: 350));
- expect(find.text('Hide assistant'), findsOneWidget);
- await tester.tap(find.text('Hide assistant'));
- await tester.pumpAndSettle();
expect(app.zoomedPaneId, viewer.id);
+ tester
+ .widget<WebPanePanel>(find.byType(WebPanePanel))
+ .onToggleZoom!();
+ await tester.pump(const Duration(milliseconds: 350));
+ expect(app.zoomedPaneId, isNull);
+ expect(app.activeSwarm.paneSizes['2:manual']!.tiles.first.width, .7);
expect(tester.takeException(), isNull);
final monitorTab = app.activeSwarm;
if (nativeTabs) {
diff --git a/desktop/test/harness_session_picker_test.dart b/desktop/test/harness_session_picker_test.dart
index fa5384abd..edf37c4ec 100644
--- a/desktop/test/harness_session_picker_test.dart
+++ b/desktop/test/harness_session_picker_test.dart
@@ -103,7 +103,7 @@ void main() {
);
await tester.enterText(resourceField, '');
await selectResource(tester, 'a0');
- await runResourceCommand(tester, 'Show paused harnesses');
+ await runResourceCommand(tester, 'Show stopped harnesses');
expect(
resourceSearch(tester).rows.where((row) => !row.isCreate).single.agentId,
'saved',
@@ -126,7 +126,7 @@ void main() {
for (final withKeymap in [false, true]) {
testWidgets(
- 'direct pause and resume preserve search; Enter still opens the session ($withKeymap)',
+ 'Stop preserves search; Open reopens the session and focuses its pane ($withKeymap)',
(tester) async {
app.adoptSessionForTest(terminal('a0', []));
final keymap = MemoryKeymap();
@@ -189,18 +189,13 @@ void main() {
find.byKey(const ValueKey('resource-action:picker.accept')),
findsOneWidget,
);
- final panes = app.panes.map((pane) => pane.id).toList();
- expect(
- tester.widget<TextField>(resourceField).focusNode!.hasFocus,
- isTrue,
- );
expect(
tester.widget<TextField>(resourceField).controller!.text,
'Font styling',
);
- await key(tester, LogicalKeyboardKey.keyS, ctrl: true);
+ await key(tester, LogicalKeyboardKey.enter);
expect(connection.types, ['agent_resume']);
- expect(find.text('Working…'), findsOneWidget);
+ expect(resourceField, findsNothing);
connection.restartReplies.single.complete(
restartReceipt(
connection.requests.single['creationId'] as String,
@@ -209,34 +204,7 @@ void main() {
),
);
await tester.pumpAndSettle();
- expect(
- app
- .stateOf('m')!
- .agents
- .firstWhere((agent) => agent.id == 'a0')
- .isStopped,
- isFalse,
- );
- expect(app.panes.map((pane) => pane.id), panes);
- expect(
- tester.widget<TextField>(resourceField).focusNode!.hasFocus,
- isTrue,
- );
- await key(tester, LogicalKeyboardKey.period, ctrl: true);
- expect(
- find.byKey(const ValueKey('resource-command-input')),
- findsOneWidget,
- );
- await key(tester, LogicalKeyboardKey.escape);
- expect(
- tester.widget<TextField>(resourceField).focusNode!.hasFocus,
- isTrue,
- );
- expect(
- tester.widget<TextField>(resourceField).controller!.text,
- 'Font styling',
- );
- await key(tester, LogicalKeyboardKey.enter);
+ expect(app.focusedPane?.agentId, 'a0');
expect(resourceField, findsNothing);
expect(connection.types, ['agent_resume']);
expect(tester.takeException(), isNull);
@@ -290,7 +258,7 @@ void main() {
keymap.dispose();
});
- testWidgets('pause errors stay in the selected preview', (tester) async {
+ testWidgets('Stop errors stay in the selected preview', (tester) async {
connection.inventory = Completer<Map<String, dynamic>>()
..complete({
'agents': [
@@ -304,7 +272,7 @@ void main() {
],
});
await open(tester);
- await press(tester, 'Pause');
+ await press(tester, 'Stop');
connection.stopReplies.single.complete({
'error': 'REFUSED',
'detail': 'Machine busy. Try again.',
@@ -313,17 +281,20 @@ void main() {
expect(find.textContaining('Machine busy. Try again.'), findsOneWidget);
expect(app.stateOf('m')!.agents.first.isStopped, isFalse);
await key(tester, LogicalKeyboardKey.keyP, cmd: true, shift: true);
- expect(find.text('Pause “Font styling review”'), findsOneWidget);
+ expect(
+ resourceSearch(tester).rows.map((row) => row.title),
+ contains('Stop “Font styling review”'),
+ );
await key(tester, LogicalKeyboardKey.escape);
await tester.pumpWidget(const SizedBox());
});
- testWidgets('closing and reopening cannot duplicate a pending pause', (
+ testWidgets('closing and reopening cannot duplicate a pending Stop', (
tester,
) async {
connection.inventory = Completer<Map<String, dynamic>>();
await open(tester);
- await press(tester, 'Pause');
+ await press(tester, 'Stop');
await key(tester, LogicalKeyboardKey.escape);
await key(tester, LogicalKeyboardKey.escape);
await openWorkspaceTool(tester, 'harnesses');
@@ -339,18 +310,22 @@ void main() {
await tester.pumpWidget(const SizedBox());
});
- testWidgets('uncertain resume checks the existing receipt', (tester) async {
+ testWidgets('uncertain Open checks the existing receipt', (tester) async {
await open(tester, id: 'saved');
- await press(tester, 'Resume');
+ await key(tester, LogicalKeyboardKey.enter);
connection.restartReplies.single.completeError(
const WsRequestTimeout('agent_resume'),
);
await tester.pumpAndSettle();
expect(
- find.textContaining('Still waiting for the resume response'),
+ find.textContaining('Still waiting for the Open response'),
findsOneWidget,
);
- await press(tester, 'Resume');
+ ScaffoldMessenger.of(tester.element(find.byType(Scaffold).first))
+ .clearSnackBars();
+ await openHarnessPicker(tester);
+ await selectResource(tester, 'saved');
+ await key(tester, LogicalKeyboardKey.enter);
expect(connection.requests, hasLength(1));
expect(
connection.checks.single['creationId'],
@@ -365,7 +340,7 @@ void main() {
);
await tester.pumpAndSettle();
expect(
- find.textContaining('Still waiting for the resume response'),
+ find.textContaining('Still waiting for the Open response'),
findsNothing,
);
await tester.pumpWidget(const SizedBox());
@@ -380,7 +355,7 @@ void main() {
await selectResource(tester, id);
await key(tester, LogicalKeyboardKey.keyP, cmd: true, shift: true);
expect(
- find.textContaining(id == 'a0' ? 'Pause “' : 'Resume “'),
+ find.textContaining(id == 'a0' ? 'Stop “' : 'Open “'),
findsNothing,
);
await key(tester, LogicalKeyboardKey.escape);
diff --git a/desktop/test/launch_preferences_test.dart b/desktop/test/launch_preferences_test.dart
index 652a6ccd3..3d3e803c2 100644
--- a/desktop/test/launch_preferences_test.dart
+++ b/desktop/test/launch_preferences_test.dart
@@ -177,6 +177,18 @@ String _storedWorktrees(Map<String, Map<String, Object?>> machines) =>
});
void main() {
+ test('new harnesses default to OpenCode and Muse without changing explicit choices', () async {
+ final fixture = _Fixture();
+ final fresh = fixture.open(engine: null);
+ expect(fresh.engine, 'opencode');
+ expect(fresh.modelLabel, 'Muse Spark 1.3');
+ final explicit = fixture.open(engine: 'claude');
+ expect(explicit.engine, 'claude');
+ await fixture.app.agentPreference.selectLaunch('codex');
+ final remembered = fixture.open(engine: null);
+ expect(remembered.engine, 'codex');
+ });
+
test(
'explicit agent defaults persist without inventing a recent launch',
() async {
diff --git a/desktop/test/stopped_harness_test.dart b/desktop/test/stopped_harness_test.dart
index bbdc43432..6ac1b3ea9 100644
--- a/desktop/test/stopped_harness_test.dart
+++ b/desktop/test/stopped_harness_test.dart
@@ -52,7 +52,7 @@ void main() {
expect(SwarmSearchController.action(row()), 'Open Harness');
final picker = SwarmSearchController(app, const [], adding: true);
addTearDown(picker.dispose);
- expect(picker.actionLabel(row()), 'Resume & open');
+ expect(picker.actionLabel(row()), 'Open');
expect(rankSwarmDestinations(rows, 'saved').single.agentId, 'saved');
expect(app.allPanes, isEmpty);
expect(connection.requests, isEmpty);
@@ -459,7 +459,7 @@ void main() {
await tester.pump();
// The preview offers the same action for pointer users; Return submits
// directly from search without first opening a confirmation dialog.
- expect(find.widgetWithText(TextButton, 'Resume & open'), findsOneWidget);
+ expect(find.widgetWithText(TextButton, 'Open'), findsOneWidget);
expect(find.byType(AlertDialog), findsNothing);
expect(connection.types, isEmpty);
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
diff --git a/desktop/test/store_discover_test.dart b/desktop/test/store_discover_test.dart
index f96f6cf56..54abc399b 100644
--- a/desktop/test/store_discover_test.dart
+++ b/desktop/test/store_discover_test.dart
@@ -1444,7 +1444,7 @@ void main() {
findsOneWidget,
);
expect(app.swarms.length, count);
- expect(find.text('Resume Harness'), findsNothing);
+ expect(find.text('Open Harness'), findsNothing);
await tester.tap(find.byKey(const ValueKey('store-primary-action')));
await tester.pumpAndSettle();
expect(find.byKey(const ValueKey('create-agent-submit')), findsOneWidget);
diff --git a/desktop/test/store_harness_actions_test.dart b/desktop/test/store_harness_actions_test.dart
index e7de5df1d..ecb6f6eab 100644
--- a/desktop/test/store_harness_actions_test.dart
+++ b/desktop/test/store_harness_actions_test.dart
@@ -254,7 +254,7 @@ void main() {
tester.getSize(find.byKey(ValueKey('store-resume:$id'))).width,
tester.getSize(find.byKey(ValueKey('store-new:$id'))).width,
);
- await tester.tap(find.text('Resume Harness'));
+ await tester.tap(find.text('Open Harness'));
await tester.pumpAndSettle();
expect(find.text('Recent harnesses'), findsNothing);
expect(app.focusedPane?.agentId, 'one');
@@ -290,7 +290,7 @@ void main() {
tester.getSize(find.byKey(const ValueKey('store-resume:codex'))).width,
tester.getSize(find.byKey(const ValueKey('store-new:codex'))).width,
);
- await tester.tap(find.text('Resume Harness'));
+ await tester.tap(find.text('Open Harness'));
await tester.pumpAndSettle();
expect(
app.activeSwarm,
@@ -357,7 +357,7 @@ void main() {
app.machineStates['m']!.agents = [_agent('a'), _agent('b')];
await showActions(tester, app, onNew: () async {}, width: 360, scale: 2);
expect(tester.takeException(), isNull);
- await tester.tap(find.text('Resume Harness'));
+ await tester.tap(find.text('Open Harness'));
await tester.pumpAndSettle();
expect(tester.takeException(), isNull);
expect(find.text('Recent harnesses'), findsOneWidget);
diff --git a/desktop/test/store_page_test.dart b/desktop/test/store_page_test.dart
index 58eff2627..9c688f38a 100644
--- a/desktop/test/store_page_test.dart
+++ b/desktop/test/store_page_test.dart
@@ -296,7 +296,7 @@ void main() {
);
expect(find.text('Your projects and files are kept.'), findsOneWidget);
expect(find.text('aaaaaaaa'), findsOneWidget);
- expect(find.text('Resume Harness'), findsNothing);
+ expect(find.text('Open Harness'), findsNothing);
expect(find.text('New Harness'), findsNothing);
app.updateGate = Completer<String?>();
await tester.tap(_key('store-primary-action'));
@@ -1453,7 +1453,7 @@ void main() {
);
void expectBrowseOnly() {
expect(_key('store-card:$id'), findsOneWidget);
- expect(find.text('Resume Harness'), findsNothing);
+ expect(find.text('Open Harness'), findsNothing);
expect(find.text('New Harness'), findsNothing);
expect(find.text('Get'), findsNothing);
}
diff --git a/desktop/test/store_screen_test.dart b/desktop/test/store_screen_test.dart
index 6f5ffa8ff..b28d5477e 100644
--- a/desktop/test/store_screen_test.dart
+++ b/desktop/test/store_screen_test.dart
@@ -311,7 +311,7 @@ void main() {
findsOneWidget,
);
expect(find.text('New Harness'), findsNothing);
- expect(find.text('Resume Harness'), findsNothing);
+ expect(find.text('Open Harness'), findsNothing);
final action = find.byKey(const ValueKey('store-primary-action'));
expect(
find.descendant(of: action, matching: find.text('Update')),
diff --git a/desktop/test/support/harness_monitor.dart b/desktop/test/support/harness_monitor.dart
index 082ef7984..bf20cf31d 100644
--- a/desktop/test/support/harness_monitor.dart
+++ b/desktop/test/support/harness_monitor.dart
@@ -1,4 +1,5 @@
import 'package:harness/core/dsh_catalog.dart';
+import 'package:harness/state/app_state.dart';
import 'package:harness/state/harness_monitor_controller.dart';
import 'model_manager.dart';
@@ -51,6 +52,17 @@ class MonitorConnection extends ModelManagerConnection {
class MonitorTestApp extends ModelManagerTestApp {
MonitorTestApp(MonitorConnection super.connection);
+ void Function(String machineId, String agentId)? onReopen;
+
+ @override
+ Future<RestartAgentResult> resumeAgent(
+ String machineId,
+ String agentId,
+ ) async {
+ final result = await super.resumeAgent(machineId, agentId);
+ if (result.error == null) onReopen?.call(machineId, agentId);
+ return result;
+ }
@override
Future<void> probeDsh(String machineId, {bool force = false}) async {
diff --git a/desktop/test/terminal_panel_header_test.dart b/desktop/test/terminal_panel_header_test.dart
index e41456b7d..17e5397d0 100644
--- a/desktop/test/terminal_panel_header_test.dart
+++ b/desktop/test/terminal_panel_header_test.dart
@@ -176,7 +176,11 @@ void main() {
tester.getRect(find.byKey(ValueKey(key))),
tester.getRect(find.byType(PaneCloseButton)),
];
- expect(rect.right, closeTo(model.left, 1));
+ final agent = tester.getRect(
+ find.byKey(const ValueKey('pane-agent-control')),
+ );
+ expect(rect.right, closeTo(agent.left, 1));
+ expect(agent.right, closeTo(model.left, 1));
expect(model.right, closeTo(controls.first.left, 1));
for (var i = 1; i < controls.length; i++) {
expect(controls[i - 1].right, closeTo(controls[i].left, 1));
@@ -210,7 +214,8 @@ void main() {
(tester) async {
final session = sessionNamed('Desktop');
addTearDown(session.dispose);
- await pump(tester, session);
+ // Keep the full project readable beside both agent and model controls.
+ await pump(tester, session, width: 1100);
final project = find.text('autonomous-harness');
final projectRect = tester.getRect(project);
for (final (status, label) in [
@@ -220,7 +225,7 @@ void main() {
(TerminalSessionStatus.error, 'Reconnect'),
]) {
session.status = status;
- await pump(tester, session);
+ await pump(tester, session, width: 1100);
final nameRect = tester.getRect(find.text('Desktop'));
final statusRect = tester.getRect(
find.widgetWithText(TextButton, label),
diff --git a/desktop/test/web_pane_test.dart b/desktop/test/web_pane_test.dart
index 93f2fffa0..0d2dc2a86 100644
--- a/desktop/test/web_pane_test.dart
+++ b/desktop/test/web_pane_test.dart
@@ -166,7 +166,11 @@ void main() {
app.addListener(() => updates++);
await _synced(app, 'a0', viewerUrl: 'http://127.0.0.1:4179/');
expect(_viewers(app).single.id, viewer.id);
- expect(updates, 0, reason: 'an unchanged viewer must not repaint the workspace');
+ expect(
+ updates,
+ 0,
+ reason: 'an unchanged viewer must not repaint the workspace',
+ );
await _synced(app, 'a0', viewerUrl: 'http://127.0.0.1:4179/?file=a.step');
expect(_viewers(app).single.id, viewer.id);
expect(_viewers(app).single.url, 'http://127.0.0.1:4179/?file=a.step');
@@ -178,7 +182,7 @@ void main() {
expect(app.panes.map((p) => p.id), [first.id, second.id]);
});
- test('alone with its terminal, the viewer takes two thirds', () async {
+ test('alone with its terminal, the viewer takes 70 percent', () async {
final app = createApp();
addTearDown(app.dispose);
final input = <TerminalBinaryFrame>[];
@@ -188,8 +192,8 @@ void main() {
expect(app.panes.map((p) => p.id), [viewer.id, terminalPane.id]);
final split = app.activeSwarm.paneSizes['2:manual'];
expect(split, isNotNull);
- expect(split!.tiles.map((t) => t.left), [0, 2 / 3]);
- expect(split.tiles.map((t) => t.right), [2 / 3, 1]);
+ expect(split!.tiles.map((t) => t.left), [0, .7]);
+ expect(split.tiles.map((t) => t.right), [.7, 1]);
expect(split.tiles.map((t) => t.height), [1, 1]);
// The viewer going away takes the pair's layout with it, the way any
// removal does; a new viewer starts the split afresh.
@@ -254,7 +258,11 @@ void main() {
app.addListener(() => updates++);
await _synced(app, 'a0', viewerUrl: 'http://127.0.0.1:4179/');
expect(_viewers(app), hasLength(1));
- expect(updates, greaterThan(0), reason: 'restoring a viewer is a visible change');
+ expect(
+ updates,
+ greaterThan(0),
+ reason: 'restoring a viewer is a visible change',
+ );
});
test('the header control hides the viewer and brings it back', () async {
diff --git a/docs/keyboard.md b/docs/keyboard.md
index 8c47c4e4b..9cf897422 100644
--- a/docs/keyboard.md
+++ b/docs/keyboard.md
@@ -11,7 +11,7 @@ The defaults, in the workspace:
|---|---|
| ⌘T | New Swarm — opens the same quiet welcome page shown at startup. Use ⌘N to create a harness, ⌘P to open one, or ⌘S for the store |
| ⌘O / Ctrl+O (Linux) | Open Project — the unified picker starts in projects (`#`), with projects containing open panes first and alphabetical order within each group |
-| ⌘P / Ctrl+P (Linux) | Open Harness — the unified picker for harnesses, machines (`@`), projects (`#`), models (`:`), and Store (`*`). Opens in the current tab and tiles its panes, or focuses the harness if already here |
+| ⌘P / Ctrl+P (Linux) | Open Harness — the unified picker for harnesses, machines (`@`), projects (`#`), agents (`&`), models (`:`), and Store (`*`). Opens in the current tab and tiles its panes, or focuses the harness if already here |
| ⇧⌘P / Ctrl+Shift+P (Linux) | Search commands; from a selected picker result, search actions for that item |
| ⌘R / ⌘D | Split right / down — open the New Pane picker with the requested direction, then choose an existing harness or create one |
| ⌘N | New Harness — choose an Agent or Harness, Project, and Options, then activate New Harness. Lists filter as you type; Return chooses and Escape returns to the form. Project accepts a folder, a new project name, or a repository. Options include model, permissions, agent profile, branch, and worktree |
@@ -42,6 +42,7 @@ A harness can have views in several swarms, with one view per swarm; closing a p
The view closes immediately, without a minimize animation.
Cmd-P opens an empty search field. Cmd-O inserts an editable `#` for projects.
+Type `&` to choose a different agent for the focused harness. The pane header's agent name opens the same picker.
Delete the prefix to return to harness search. These fields use a thin caret and
no separate prompt character.
diff --git a/store/agents/harness-monitor/AGENTS.md b/store/agents/harness-monitor/AGENTS.md
index 5f2f87b86..c24188362 100644
--- a/store/agents/harness-monitor/AGENTS.md
+++ b/store/agents/harness-monitor/AGENTS.md
@@ -1,22 +1,21 @@
# Harness Monitor
-You are the optional assistant in a Harness Monitor workspace. The table is the primary interface;
-reading, searching, sorting, inspecting and stopping sessions do not require a model. Open and resume
-belong in Open Harness (Cmd-P); the process table has no assistant or cleanup action. Act only on the
+You are the assistant in the right-hand 30% of a Harness Monitor workspace. The table is the primary interface;
+reading, searching, sorting, opening and stopping sessions do not require a model. Act only on the
person's request. Use the installed engine; do not assume Claude Code.
Use `"$HPS_CLI" --json --all` to inspect the local machine, adding `--machines` for linked machines.
The daemon is authoritative for activity, process identity and stopped sessions. Never signal a PID,
-write a resume command into tmux, or reconstruct a saved launch yourself.
+write an open command into tmux, or reconstruct a saved launch yourself.
- `hps show <ref>` inspects one session.
-- `hps pause <ref>` stops its process and retains its history and saved configuration.
-- `hps resume <ref>` asks the owning daemon to restore it. Respect `resumeMode`: some engines reopen a
+- `hps stop <ref>` stops its process and retains its history and saved configuration.
+- `hps open <ref>` asks the owning daemon to restore it. Respect `resumeMode`: some engines reopen a
conversation, some start a fresh one, and terminals reopen a shell.
-- `hps pause --policy` previews cleanup. `--apply` executes the reviewed plan.
+- `hps stop --policy` previews cleanup. `--apply` executes the reviewed plan.
- `hps cleanup --machines` previews harnesses outside every open tab; `--apply` closes them, saving
history. Background tabs and local utility tabs such as Companions stay open.
-- `hps resume --paused` is a dry run until `--apply`.
+- `hps open --stopped` is a dry run until `--apply`.
- `--machines` includes linked machines for reads and actions. Use the full composite machine/agent ID
in JSON output when a name, pane or agent ID is ambiguous. Never assume IDs are global.
@@ -27,7 +26,7 @@ Never bypass its tab or history guards. Policy cleanup keeps Working, Needs you,
activity protected. `--force` is for the person to request explicitly. Never change rules simply because the table is open.
Rules and pins live in `~/.config/harness/policy.jsonc`; preserve comments when editing it.
-A timed-out resume is uncertain. Check its original receipt; never launch another process to compensate.
+A timed-out open is uncertain. Check its original receipt; never launch another process to compensate.
An offline machine is not a stopped session. Unknown CPU, RAM or tokens are not zero. RAM sums process
resident sets (shared pages can be counted twice); CPU is interval process-tree use, with 100% meaning
one core. GPU readings are attributable driver counters; missing counters are unavailable. Storage
@@ -36,8 +35,8 @@ daemon conversation activity, not file mtime.
The default OpenCode model is Muse Spark 1.3 Contributor Free. It is a limited-time offer and allows
Meta to train on prompts and responses. Both the main and small model are explicitly configured to
-that ID. Never silently switch to a paid model. If the person opens the optional terminal separately,
-disclose this before accepting prompts; they can choose another model with OpenCode's `/models` command.
+that ID. Never silently switch to a paid model. The viewer includes an Assistant model disclosure; users can choose another model with
+OpenCode's `/models` command.
Never start another viewer: Harness already manages this one. Never delete transcripts or projects.
Report actual tool results, including refusals and uncertain outcomes, without inventing activity.
diff --git a/store/agents/harness-monitor/README.md b/store/agents/harness-monitor/README.md
index 255cf35bd..0d6c4f19c 100644
--- a/store/agents/harness-monitor/README.md
+++ b/store/agents/harness-monitor/README.md
@@ -2,21 +2,20 @@
Inspect active harnesses across connected machines and decide what to stop. The workspace footer's
Harnesses, CPU, RAM, GPU and SSD controls select the existing Harness Monitor tab, creating one when
-needed. Opening the table submits no model prompt. Open and resume belong in Open Harness (Cmd-P).
+needed. The tab uses the standard 70% viewer / 30% assistant split. Use the pane Zoom icon for a full-width table. Opening the table submits no model prompt.
Every visit starts with active sessions; RAM is the initial default sort. Filter by machine or activity, search session
metadata, and choose Overview, Resources or AI usage. Click a header to sort; unknown readings sort
last in either direction. Drag a separator or use its arrow keys to resize a column. Columns and
widths persist; search and status reset on entry. The harness name stays visible during horizontal
scrolling. Arrow keys select; Enter or double-click opens the inspector. It includes process IDs,
-parent IDs and resource readings. No navigation, resume, assistant or bulk cleanup actions appear in
-the process table.
+parent IDs and resource readings. Open focuses one existing pane for the selected session, or starts stopped work in one new tab when no pane remains. The Stopped filter shows saved sessions.
Stop… reviews one selected session before asking its owning daemon to stop the validated process.
Conversation history, launch settings and files remain. The daemon checks conversation identity again
-before stopping. Offline or disconnected sessions cannot be stopped. Pause updates freezes the table
-without pausing work and disables Stop until updates resume. Offline sessions are an explicit filter;
-saved, stopped history remains in Open Harness.
+before stopping. Offline or disconnected sessions cannot be stopped. Freeze updates holds the displayed readings
+without affecting work, and disables Stop/Open until live updates return. Offline sessions are an explicit filter;
+saved history is also available in Open Harness (Cmd-P).
## Metric definitions
@@ -65,10 +64,11 @@ rounding, hidden polling and tab reuse; `tool/check_swarm_titlebar.sh` checks na
Real Linux NVIDIA counters still require hardware validation; parser fixtures do not establish
support for every driver.
-The backward-compatible hps CLI retains explicit pause/resume and reviewed cleanup commands.
+The hps CLI offers explicit stop/open and reviewed cleanup commands; old pause/resume names remain compatibility aliases.
Rules/pins live in ~/.config/harness/policy.jsonc; receipts live under ~/.harness/monitor/.
-Nothing automatically stops sessions. The package's optional terminal keeps its saved OpenCode
-configuration; the viewer neither exposes an assistant action nor submits prompts.
+Nothing automatically stops sessions. The assistant keeps its saved configuration, and its header offers the shared agent and model controls.
+
+New OpenCode sessions use `opencode/muse-spark-1.3-contributor-free` with automatic approvals and xhigh effort. **Contributor permits Meta to train on prompts and responses.** The Assistant model disclosure keeps this visible. There is no automatic paid fallback, and existing sessions retain their saved agent/model settings.
## Credit and stewardship
diff --git a/store/agents/harness-monitor/lib/actions.mjs b/store/agents/harness-monitor/lib/actions.mjs
index 242ca82ce..683da89c2 100644
--- a/store/agents/harness-monitor/lib/actions.mjs
+++ b/store/agents/harness-monitor/lib/actions.mjs
@@ -1,6 +1,6 @@
/** The daemon owns process identity, stopping and saved runtime configuration, on every machine. */
import { randomUUID } from 'node:crypto'
-import { readFile, mkdir, open, unlink } from 'node:fs/promises'
+import { readFile, mkdir, open as openFile, unlink } from 'node:fs/promises'
import { join } from 'node:path'
import { createHash } from 'node:crypto'
import { listAgents, request } from './bridge.mjs'
@@ -15,59 +15,60 @@ async function fresh(row, list) {
const agents = await list(row.machineId)
const agent = agents.find(a => a.id === row.agentId)
if (!agent) throw new Error('This harness is no longer in the daemon inventory. Refresh and try again.')
- // A stopped/resumed or rotated conversation is a different target from the one the person reviewed.
+ // A stopped/reopened or rotated conversation is a different target from the one the person reviewed.
if ((agent.sessionId || null) !== (row.sessionId || null)) throw new Error('This conversation changed. Refresh and review it before acting.')
return mergeRows([agent], { machine: { machineId: row.machineId, name: row.machine }, local: row.local,
state: { pins: row.pinned ? [row.id] : [] } })[0]
}
-export async function pause(row, { policy = normalizePolicy({}), force = false, list = listAgents, rpc = request } = {}) {
+export async function stop(row, { policy = normalizePolicy({}), force = false, list = listAgents, rpc = request } = {}) {
try {
const current = await fresh(row, list)
- if (current.state === 'paused') return receipt(row, 'pause', 'Already stopped; history retained.', { ok: true, refused: false })
- if (!current.canStop) return receipt(row, 'pause', current.unavailable || 'This harness cannot be stopped yet.')
+ if (current.state === 'stopped') return receipt(row, 'stop', 'Already stopped; history retained.', { ok: true, refused: false })
+ if (!current.canStop) return receipt(row, 'stop', current.unavailable || 'This harness cannot be stopped yet.')
if (!force) {
- if (!current.activityKnown) return receipt(row, 'pause', 'Update the owning daemon before automatic cleanup; activity is unknown.')
+ if (!current.activityKnown) return receipt(row, 'stop', 'Update the owning daemon before automatic cleanup; activity is unknown.')
const guard = protectionFor(current, policy)
- if (guard) return receipt(row, 'pause', guard.why)
- if (current.lastActivity !== row.lastActivity) return receipt(row, 'pause', 'Activity changed since the cleanup preview. Review the new plan.')
+ if (guard) return receipt(row, 'stop', guard.why)
+ if (current.lastActivity !== row.lastActivity) return receipt(row, 'stop', 'Activity changed since the cleanup preview. Review the new plan.')
}
const reply = await rpc(row.machineId, 'agent_delete', { agentId: row.agentId, expectedSessionId: row.sessionId || null })
- if (reply.deleted !== true) return receipt(row, 'pause', 'Stop was not confirmed. Refresh before trying again.')
- return receipt(row, 'pause', 'Stopped; history and launch configuration retained.', { ok: true, refused: false, freed: current.rssBytes })
- } catch (error) { return receipt(row, 'pause', error.message) }
+ if (reply.deleted !== true) return receipt(row, 'stop', 'Stop was not confirmed. Refresh before trying again.')
+ return receipt(row, 'stop', 'Stopped; history and launch configuration retained.', { ok: true, refused: false, freed: current.rssBytes })
+ } catch (error) { return receipt(row, 'stop', error.message) }
}
/** Persist the intent before sending. A new viewer/CLI checks the same durable daemon receipt after
- * a lost reply, rather than issuing another resume. Exclusive file creation also coalesces callers. */
-async function resumeIntent(row) {
+ * a lost reply, rather than issuing another open. Exclusive file creation also coalesces callers. */
+async function openIntent(row) {
const directory = stateDir(), key = createHash('sha256').update(row.id).digest('hex')
await mkdir(directory, { recursive: true })
+ // Keep the existing receipt filename so an update cannot duplicate an uncertain launch.
const path = join(directory, 'resume-' + key + '.json')
try {
- const file = await open(path, 'wx', 0o600)
+ const file = await openFile(path, 'wx', 0o600)
const value = { creationId: randomUUID(), agentId: row.agentId, sessionId: row.sessionId }
try { await file.writeFile(JSON.stringify(value)) } finally { await file.close() }
return { ...value, path, existing: false }
} catch (error) {
if (error.code !== 'EEXIST') throw error
const value = JSON.parse(await readFile(path, 'utf8'))
- if (value.agentId !== row.agentId || value.sessionId !== row.sessionId || typeof value.creationId !== 'string') throw new Error('An earlier resume needs review before retrying.')
+ if (value.agentId !== row.agentId || value.sessionId !== row.sessionId || typeof value.creationId !== 'string') throw new Error('An earlier open needs review before retrying.')
return { ...value, path, existing: true }
}
}
-export function resume(row, options = {}) {
+export function open(row, options = {}) {
if (pending.has(row.id)) return pending.get(row.id)
- const result = resumeOnce(row, options).finally(() => pending.delete(row.id))
+ const result = openOnce(row, options).finally(() => pending.delete(row.id))
pending.set(row.id, result)
return result
}
-async function resumeOnce(row, { list = listAgents, rpc = request, intent = resumeIntent, clearIntent = path => unlink(path).catch(() => {}) } = {}) {
+async function openOnce(row, { list = listAgents, rpc = request, intent = openIntent, clearIntent = path => unlink(path).catch(() => {}) } = {}) {
try {
const current = await fresh(row, list)
- if (current.state !== 'paused') return receipt(row, 'resume', current.canOpen ? 'Already running.' : 'This harness is not ready to open.', { ok: current.canOpen, refused: !current.canOpen })
- if (!current.canOpen) return receipt(row, 'resume', 'This harness cannot be resumed yet.')
+ if (current.state !== 'stopped') return receipt(row, 'open', current.canOpen ? 'Already running.' : 'This harness is not ready to open.', { ok: current.canOpen, refused: !current.canOpen })
+ if (!current.canOpen) return receipt(row, 'open', 'This harness cannot be reopened yet.')
const operation = await intent(row)
let reply
if (operation.existing) reply = await rpc(row.machineId, 'agent_create_status', { creationId: operation.creationId })
@@ -77,13 +78,13 @@ async function resumeOnce(row, { list = listAgents, rpc = request, intent = resu
}
if (reply.state === 'created' && reply.agent?.id === row.agentId) {
await clearIntent(operation.path)
- if (reply.agent.status === 'stopped' || reply.agent.terminal?.available === false) return receipt(row, 'resume', 'The earlier resume completed, but this session is no longer running. Review it and try again.')
- return receipt(row, 'resume', 'Resumed with its saved configuration.', { ok: true, refused: false })
+ if (reply.agent.status === 'stopped' || reply.agent.terminal?.available === false) return receipt(row, 'open', 'The earlier open completed, but this session is no longer running. Review it and try again.')
+ return receipt(row, 'open', 'Opened with its saved configuration.', { ok: true, refused: false })
}
if (reply.state === 'failed') {
await clearIntent(operation.path)
- return receipt(row, 'resume', reply.failure?.detail || reply.failure?.code || reply.detail || reply.error || 'Resume failed.')
+ return receipt(row, 'open', reply.failure?.detail || reply.failure?.code || reply.detail || reply.error || 'Open failed.')
}
- return receipt(row, 'resume', 'Resume is not confirmed yet. Check again to read the same operation.', { creationId: operation.creationId, unconfirmed: true })
- } catch (error) { return receipt(row, 'resume', error.message) }
+ return receipt(row, 'open', 'Open is not confirmed yet. Check again to read the same operation.', { creationId: operation.creationId, unconfirmed: true })
+ } catch (error) { return receipt(row, 'open', error.message) }
}
diff --git a/store/agents/harness-monitor/lib/activity.mjs b/store/agents/harness-monitor/lib/activity.mjs
index 58355a31e..eb1e34733 100644
--- a/store/agents/harness-monitor/lib/activity.mjs
+++ b/store/agents/harness-monitor/lib/activity.mjs
@@ -1,7 +1,7 @@
/**
* When did this harness last actually do something?
*
- * The obvious answers are all wrong, and each one is wrong in a way that would pause the fleet's living
+ * The obvious answers are all wrong, and each one is wrong in a way that would stop the fleet's living
* agents or keep its dead ones running:
*
* the registry's `updatedAt` the daemon reconciles every five seconds, so every row reads "now"
diff --git a/store/agents/harness-monitor/lib/config.mjs b/store/agents/harness-monitor/lib/config.mjs
index 89a729a6c..ce795c024 100644
--- a/store/agents/harness-monitor/lib/config.mjs
+++ b/store/agents/harness-monitor/lib/config.mjs
@@ -3,11 +3,11 @@
*
* ~/.config/harness/policy.jsonc the rules, and `pins`. Written for a person: commented, hand-edited,
* next to `keybindings.jsonc`. $XDG_CONFIG_HOME is respected.
- * ~/.harness/monitor/paused.json the resume tickets. Written by the program, never by a person.
- * ~/.harness/monitor/log.jsonl one line per pause and resume, with the rule that caused it.
+ * ~/.harness/monitor/paused.json (legacy filename) the open tickets. Written by the program, never by a person.
+ * ~/.harness/monitor/log.jsonl one line per stop and open, with the rule that caused it.
*
* Machine-wide on purpose. The first version kept all three inside the Harness Monitor workspace, which
- * meant a second workspace got a second policy, and a harness paused from one could not be resumed from
+ * meant a second workspace got a second policy, and a harness stopped from one could not be reopened from
* the other because its ticket was in the wrong folder. There is one fleet per machine; there is one
* policy and one ticket book per machine.
*/
@@ -56,26 +56,26 @@ export function template(policy = DEFAULT_POLICY) {
return `// Harness Monitor — the rules for this machine's harnesses.
//
// Edit this file and review Cleanup in the Harness Monitor table. It is read on every refresh, so a
-// save takes effect within seconds. Preview any change without moving anything: hps pause --policy
+// save takes effect within seconds. Preview any change without moving anything: hps stop --policy
//
// Rules only propose stopping sessions. Apply a reviewed plan explicitly; nothing runs automatically.
-// The daemon retains history and launch settings. Resume behavior depends on the engine's resumeMode.
+// The daemon retains history and launch settings. Open behavior depends on the engine's resumeMode.
{
// Most engines running at once on each machine. Cleanup proposes stopping the least recently active.
// Lower it on a machine that swaps: free memory divided by ~300 MB per harness.
"runningCeiling": ${policy.runningCeiling},
- // Untouched this long (time since the last real turn) and a harness is paused.
- "pauseAfterIdle": "${policy.pauseAfterIdle}",
+ // Untouched this long (time since the last real turn) and a harness is stopped.
+ "stopAfterIdle": "${policy.stopAfterIdle}",
- // Untouched this long and it drops out of the default list. Still there under --all; nothing is paused
+ // Untouched this long and it drops out of the default list. Still there under --all; nothing is stopped
// or removed by this — it only decides what you see.
"hideAfterIdle": "${policy.hideAfterIdle}",
- // A harness whose folder no longer exists is paused, whatever its idle time.
- "pauseWhenWorkspaceGone": ${policy.pauseWhenWorkspaceGone},
+ // A harness whose folder no longer exists is stopped, whatever its idle time.
+ "stopWhenWorkspaceGone": ${policy.stopWhenWorkspaceGone},
- // What is never paused, by any rule.
+ // What is never stopped, by any rule.
"protect": {
"needsInput": ${policy.protect.needsInput}, // daemon reports a pending question
"working": ${policy.protect.working}, // daemon reports an open turn
@@ -83,7 +83,7 @@ export function template(policy = DEFAULT_POLICY) {
"pinned": ${policy.protect.pinned} // listed in "pins" below
},
- // Composite machine/agent ids the rules must never pause. \`hps --json --all --machines\` shows each id.
+ // Composite machine/agent ids the rules must never stop. \`hps --json --all --machines\` shows each id.
"pins": []
}
`
@@ -161,7 +161,7 @@ export async function readLogFile({ limit = 200 } = {}, env = process.env) {
/**
* Carry the old per-workspace file forward, once.
*
- * Tickets and pins are DATA — a harness paused under the old layout must still be resumable — so they are
+ * Tickets and pins are DATA — a harness stopped under the old layout must still be openable — so they are
* merged into the machine files. The old POLICY is not carried over: it was the stricter default, and a
* machine-wide file starting from it would undo the reason the file moved.
*/
@@ -173,7 +173,7 @@ export async function migrateWorkspace(workspace, env = process.env) {
if (parsed?.migrated) return null
const tickets = await readTickets(env)
let moved = 0
- for (const [id, ticket] of Object.entries(parsed?.paused ?? {})) {
+ for (const [id, ticket] of Object.entries(parsed?.stopped ?? parsed?.paused ?? {})) {
if (!tickets[id]) { tickets[id] = ticket; moved += 1 }
}
if (moved) await writeTickets(tickets, env)
diff --git a/store/agents/harness-monitor/lib/format.mjs b/store/agents/harness-monitor/lib/format.mjs
index 654f492e8..b05499c3f 100644
--- a/store/agents/harness-monitor/lib/format.mjs
+++ b/store/agents/harness-monitor/lib/format.mjs
@@ -18,12 +18,12 @@ export function painter({ tty = false } = {}) {
return { ...Object.fromEntries(Object.entries(CODES).map(([key, code]) => [key, paint(code)])), plain: (text) => String(text) }
}
-/** ● running · ◐ working · ○ paused · $ shell · ✕ gone · ! waiting on you. Two characters wide so the
+/** ● running · ◐ working · ○ stopped · $ shell · ✕ gone · ! waiting on you. Two characters wide so the
* column never shifts when a glyph is double-width on someone's font. */
export function glyph(row, c) {
if (row.needsInput) return c.amber('! ')
if (row.state === 'running') return row.working ? c.gold('◐ ') : c.green('● ')
- if (row.state === 'paused') return c.dim('○ ')
+ if (row.state === 'stopped') return c.dim('○ ')
if (row.state === 'terminal') return c.dim('$ ')
return c.dim('✕ ')
}
@@ -92,7 +92,7 @@ export function footer(summary, policy, { tty = false, problems = [] } = {}) {
const parts = [
`${summary.total} ${summary.total === 1 ? 'harness' : 'harnesses'}`,
`${c.green(summary.running)} running`,
- summary.paused ? `${summary.paused} paused` : null,
+ summary.stopped ? `${summary.stopped} stopped` : null,
summary.gone ? `${summary.gone} gone` : null,
summary.terminals ? `${summary.terminals} ${summary.terminals === 1 ? 'shell' : 'shells'}` : null,
summary.needsInput ? c.amber(`${summary.needsInput} waiting on you`) : null,
@@ -101,18 +101,18 @@ export function footer(summary, policy, { tty = false, problems = [] } = {}) {
summary.machines > 1 ? `${summary.machines} machines` : null,
].filter(Boolean)
const lines = [parts.join(c.dim(' · '))]
- if (policy) lines.push(c.dim(`policy: pause after ${policy.pauseAfterIdle} · hide after ${policy.hideAfterIdle} · ceiling ${policy.runningCeiling} running`))
+ if (policy) lines.push(c.dim(`policy: stop after ${policy.stopAfterIdle} · hide after ${policy.hideAfterIdle} · ceiling ${policy.runningCeiling} running`))
for (const problem of problems) lines.push(c.red(`${problem.machine}: ${problem.error}`))
return lines.join('\n')
}
-/** `hps prune --explain` and `hps pause --dry-run`: the plan, one line each, longest reason last. */
+/** `hps prune --explain` and `hps stop --dry-run`: the plan, one line each, longest reason last. */
export function planLines(entries, { tty = false, verb = null } = {}) {
const c = painter({ tty })
const shown = entries.filter((entry) => entry.action !== 'keep' && (!verb || entry.action === verb))
if (!shown.length) return c.dim('Nothing to do — every harness is where the policy wants it.')
const width = Math.max(...shown.map((entry) => entry.name.length), 4)
- // Both columns are measured, never guessed: a hardcoded action width silently truncated `pause`
+ // Both columns are measured, never guessed: a hardcoded action width silently truncated `stop`
// to `hiberna`, which is the kind of thing only a test notices.
const verbWidth = Math.max(...shown.map((entry) => entry.action.length))
return shown.map((entry) => `${c.bold(pad(entry.action, verbWidth))} ${pad(entry.name, width)} ${c.dim(entry.why)}`).join('\n')
diff --git a/store/agents/harness-monitor/lib/inventory.mjs b/store/agents/harness-monitor/lib/inventory.mjs
index 244aa1106..b0dbfc7cb 100644
--- a/store/agents/harness-monitor/lib/inventory.mjs
+++ b/store/agents/harness-monitor/lib/inventory.mjs
@@ -48,9 +48,9 @@ export function mergeRows(agents, { state = {}, machine = null, local = true, no
id, agentId: agent.id, sessionId: agent.sessionId || null,
name: agent.name || agent.title || 'Untitled harness', title: agent.title || null,
engine: agent.engine, ...parseModel(agent.selectedModel),
- state: !online ? 'offline' : stopped ? 'paused' : terminalAvailable ? (agent.engine === 'terminal' ? 'terminal' : 'running') : 'gone',
+ state: !online ? 'offline' : stopped ? 'stopped' : terminalAvailable ? (agent.engine === 'terminal' ? 'terminal' : 'running') : 'gone',
activity, activityKnown: monitor?.activityKnown === true,
- stateSince: lastActivity, pausedAt: stopped ? lastActivity : null,
+ stateSince: lastActivity, stoppedAt: stopped ? lastActivity : null,
pane: agent.tmuxPane || null, paneTarget: null,
project, cwd, home: local ? tilde(cwd, home) : cwd, branch, remote,
lastActivity, idleMs, idle: idleMs == null ? '—' : humanIdle(idleMs), createdAt: time(agent.createdAt),
@@ -153,7 +153,7 @@ export async function collect({
export function summarize(rows) {
const by = state => rows.filter(row => row.state === state).length
- return { total: rows.length, running: by('running'), paused: by('paused'), gone: by('gone'), terminals: by('terminal'),
+ return { total: rows.length, running: by('running'), stopped: by('stopped'), gone: by('gone'), terminals: by('terminal'),
needsInput: rows.filter(row => row.needsInput).length, working: rows.filter(row => row.working).length,
held: rows.reduce((sum, row) => sum + (row.rssBytes ?? 0), 0),
projects: new Set(rows.map(row => row.project)).size, machines: new Set(rows.map(row => row.machineId)).size }
diff --git a/store/agents/harness-monitor/lib/panes.mjs b/store/agents/harness-monitor/lib/panes.mjs
index 80073699f..0f222de5f 100644
--- a/store/agents/harness-monitor/lib/panes.mjs
+++ b/store/agents/harness-monitor/lib/panes.mjs
@@ -43,7 +43,7 @@ const FIELDS = [
* Every pane on this tmux server, by pane id.
*
* `dead` is a pane whose process exited while tmux was told to keep it — its scrollback is still there
- * and `respawn-pane` brings it back, which is what makes pausing lossless. `engineExit` is the status
+ * and `respawn-pane` brings it back, which is what makes stopping lossless. `engineExit` is the status
* Harness's own launch wrapper records when an engine leaves and the pane falls back to a shell: its
* presence is the difference between "the engine is gone" and "the install is still running".
*/
@@ -108,7 +108,7 @@ const SHELLS = new Set(['zsh', 'bash', 'sh', 'fish', 'dash', 'ksh', '-zsh', '-ba
* Walk a pane's process subtree: the engine process to signal, the subtree's memory, its CPU.
*
* Memory is the whole subtree because an engine's helpers are its cost too — the number a person is
- * deciding about is "what do I get back if I pause this", not "how big is one pid".
+ * deciding about is "what do I get back if I stop this", not "how big is one pid".
*
* The engine is matched at the ROOT as well as below it. tmux's `pane_pid` is the engine itself for
* every agent whose pane was started on the engine directly (most of them); it is a shell only when the
@@ -131,7 +131,7 @@ export function engineProcess(pane, table, engine) {
walk(pane.pid, 0)
const self = table.byPid.get(pane.pid)
// The pane's own shell is not the agent's cost; subtract it when the engine is gone and all that is
- // left is the fallback shell, so a paused row reads 0 rather than a few megabytes of zsh.
+ // left is the fallback shell, so a stopped row reads 0 rather than a few megabytes of zsh.
if (!pid && self && SHELLS.has(self.comm.split('/').pop())) return { pid: null, rss: 0, cpu: 0, procs, engineAlive: false }
return { pid, rss, cpu, procs, engineAlive: pid !== null }
}
@@ -149,7 +149,7 @@ export async function capture(pane, { lines = 40, run = tmux } = {}) {
* Best effort, and deliberately loud about it: the app's own **Agents needing input** (⇧⌘I) is the
* authority, and the daemon does not put pending questions on the local bridge. What is available is
* the pane's last screen, and an engine waiting for an answer draws a recognizable prompt on it. A
- * false positive costs a harness that stays running; a false negative costs a question paused before it
+ * false positive costs a harness that stays running; a false negative costs a question stopped before it
* was read — so the patterns are broad on purpose, and the policy protects anything that matches.
*/
const BLOCKED_PATTERNS = [
@@ -172,7 +172,7 @@ const BLOCKED_PATTERNS = [
*
* `❯ ` alone is NOT enough, and that mistake is worth keeping a note about: Claude Code echoes the
* prompt you just submitted as `❯ your text`, so matching a lone cursor line marked every recently used
- * harness as blocked and refused to pause any of them. A menu has a second option under the cursor —
+ * harness as blocked and refused to stop any of them. A menu has a second option under the cursor —
* short, indented, and not a separator — and that is what this looks for.
*/
function looksLikeMenu(lines) {
@@ -185,7 +185,7 @@ function looksLikeMenu(lines) {
}
/** The prompt an idle engine draws when it is waiting for a TASK, not for an answer. Subtracted before
- * anything else runs — otherwise every quiet harness looks blocked and nothing would ever be paused. */
+ * anything else runs — otherwise every quiet harness looks blocked and nothing would ever be stopped. */
const IDLE_PROMPTS = [
/^\s*❯\s*$/,
/^\s*>\s*$/,
@@ -207,7 +207,7 @@ export function looksBlocked(screen) {
}
/** Hold a pane open across its process exiting, and hand it back to tmux's own disposal afterwards —
- * the same pair the daemon uses around a restart (`holdOpen` / `clearPaneRemainOnExit`). Pausing sets
+ * the same pair the daemon uses around a restart (`holdOpen` / `clearPaneRemainOnExit`). Stopping sets
* it before the engine is asked to leave, so a pane whose launch wrapper predates the fallback shell
* keeps its scrollback instead of taking its window down with it. */
export async function holdOpen(pane, on, { run = tmux } = {}) {
@@ -225,7 +225,7 @@ export async function paneState(pane, { run = tmux } = {}) {
} catch { return null }
}
-/** Type a line into a pane's shell. Used for one thing only: the local resume path, when the daemon is
+/** Type a line into a pane's shell. Used for one thing only: the local open path, when the daemon is
* not reachable and the pane has already fallen back to a shell that adopts an engine when told to. */
export async function sendLine(pane, line, { run = tmux } = {}) {
assertPane(pane)
diff --git a/store/agents/harness-monitor/lib/policy.mjs b/store/agents/harness-monitor/lib/policy.mjs
index fe6461ea4..cb5b19248 100644
--- a/store/agents/harness-monitor/lib/policy.mjs
+++ b/store/agents/harness-monitor/lib/policy.mjs
@@ -9,7 +9,7 @@
*
* The vocabulary, kept identical everywhere:
* running the engine process is alive — a normal Harness agent
- * paused the daemon retains history and launch settings, but the process is stopped
+ * stopped the daemon retains history and launch settings, but the process is stopped
* gone the daemon knows the row but its terminal is unavailable
*/
@@ -21,20 +21,20 @@ export const DEFAULT_POLICY = {
* day with more harnesses going than anyone plans for; the idle rule does the everyday work. Lower it on a
* machine that swaps: ~300 MB each is the number to divide into your free memory. */
runningCeiling: 100,
- /** Idle this long and the engine is paused. A day, because a day survives an overnight break: yesterday
+ /** Idle this long and the engine is stopped. A day, because a day survives an overnight break: yesterday
* afternoon's work is still there, warm, in the morning. The first default was 4h, and on a real fleet the
* only thing it caught that a day does not was eight harnesses from the previous afternoon. */
- pauseAfterIdle: '1d',
- /** Idle this long and the row drops below the fold — still there under `--all`, still resumable, just
+ stopAfterIdle: '1d',
+ /** Idle this long and the row drops below the fold — still there under `--all`, still openable, just
* not in the way. A LIST rule, not a state: an earlier version made this a `retire` verb with its own
* state, mark and grace window, and none of that earned its keep. */
hideAfterIdle: '14d',
/** A workspace that no longer exists on disk has no work left in it. */
- pauseWhenWorkspaceGone: true,
+ stopWhenWorkspaceGone: true,
protect: {
/** An agent waiting on a person is not idle; it is blocked on us. */
needsInput: true,
- /** Mid-turn. Pausing here would throw away work in flight. */
+ /** Mid-turn. Stopping here would throw away work in flight. */
working: true,
/** Reserved for inventories that report attachment; current daemon inventory does not. */
attached: true,
@@ -46,7 +46,7 @@ export const DEFAULT_POLICY = {
const UNITS = { s: 1000, m: 60_000, h: 3_600_000, d: 86_400_000, w: 604_800_000 }
/** `"4h"`, `"90m"`, `"14d"`, `"1w"`, or a plain number of milliseconds. Throws on anything else —
- * a policy with a typo in it must fail loudly at load, not quietly pause the fleet. */
+ * a policy with a typo in it must fail loudly at load, not quietly stop the fleet. */
export function parseDuration(value) {
if (typeof value === 'number' && Number.isFinite(value) && value >= 0) return Math.floor(value)
const match = /^(\d+(?:\.\d+)?)\s*([smhdw])$/.exec(String(value ?? '').trim().toLowerCase())
@@ -85,14 +85,20 @@ function expandHome(path, home) {
* one rather than being silently rewritten without its rules. */
export function normalizePolicy(raw, { home = '' } = {}) {
const policy = { ...DEFAULT_POLICY, ...(raw && typeof raw === 'object' ? raw : {}) }
+ // Read existing policies without changing the owner's thresholds or comments.
+ policy.stopAfterIdle = raw?.stopAfterIdle ?? raw?.pauseAfterIdle ?? DEFAULT_POLICY.stopAfterIdle
+ policy.stopWhenWorkspaceGone = raw?.stopWhenWorkspaceGone ?? raw?.pauseWhenWorkspaceGone ?? DEFAULT_POLICY.stopWhenWorkspaceGone
+ delete policy.pauseAfterIdle
+ delete policy.pauseAfterIdleMs
+ delete policy.pauseWhenWorkspaceGone
policy.protect = { ...DEFAULT_POLICY.protect, ...(raw?.protect && typeof raw.protect === 'object' ? raw.protect : {}) }
const ceiling = Number(policy.runningCeiling)
if (!Number.isInteger(ceiling) || ceiling < 0 || ceiling > 512) throw new Error('runningCeiling must be a whole number of agents between 0 and 512.')
policy.runningCeiling = ceiling
- policy.pauseAfterIdleMs = parseDuration(policy.pauseAfterIdle)
+ policy.stopAfterIdleMs = parseDuration(policy.stopAfterIdle)
policy.hideAfterIdleMs = parseDuration(policy.hideAfterIdle)
- if (policy.hideAfterIdleMs < policy.pauseAfterIdleMs) {
- throw new Error('hideAfterIdle must be at least pauseAfterIdle — a row cannot drop out of the list before it is even paused.')
+ if (policy.hideAfterIdleMs < policy.stopAfterIdleMs) {
+ throw new Error('hideAfterIdle must be at least stopAfterIdle — a row cannot drop out of the list before it is even stopped.')
}
return policy
}
@@ -123,11 +129,11 @@ const RUNNING = new Set(['running'])
/**
* The plan. One entry per row, in the order given, plus the rules' own totals.
*
- * `action` is what the row should become: `pause` or `keep`. Nothing here decides
+ * `action` is what the row should become: `stop` or `keep`. Nothing here decides
* how — `actions.mjs` asks the owning daemon. Nothing deletes history.
*/
export function decide(rows, rawPolicy, { now = Date.now(), home = '' } = {}) {
- const policy = rawPolicy?.pauseAfterIdleMs ? rawPolicy : normalizePolicy(rawPolicy, { home })
+ const policy = rawPolicy?.stopAfterIdleMs ? rawPolicy : normalizePolicy(rawPolicy, { home })
const entries = []
const keep = (row, why, extra = {}) => ({ id: row.id, name: row.name, action: 'keep', rule: 'keep', why, ...extra })
@@ -137,27 +143,27 @@ export function decide(rows, rawPolicy, { now = Date.now(), home = '' } = {}) {
entries.push(keep(row, 'terminal unavailable; retained in daemon inventory'))
continue
}
- // A shell somebody opened is not an agent: no conversation, nothing to resume, no rule applies.
- if (row.state === 'terminal') { entries.push(keep(row, 'a shell, not an engine — nothing to pause')); continue }
+ // A shell somebody opened is not an agent: no conversation, nothing to open, no rule applies.
+ if (row.state === 'terminal') { entries.push(keep(row, 'a shell, not an engine — nothing to stop')); continue }
const protection = protectionFor(row, policy)
if (protection) {
entries.push(keep(row, protection.why, { protectedBy: protection.by }))
continue
}
- if (policy.pauseWhenWorkspaceGone && row.workspaceGone && RUNNING.has(row.state)) {
- entries.push({ id: row.id, name: row.name, action: 'pause', rule: 'workspaceGone', why: `its folder is gone (${row.cwd || 'unknown'})`, frees: row.rssBytes ?? 0 })
+ if (policy.stopWhenWorkspaceGone && row.workspaceGone && RUNNING.has(row.state)) {
+ entries.push({ id: row.id, name: row.name, action: 'stop', rule: 'workspaceGone', why: `its folder is gone (${row.cwd || 'unknown'})`, frees: row.rssBytes ?? 0 })
continue
}
- if (RUNNING.has(row.state) && idle >= policy.pauseAfterIdleMs) {
- entries.push({ id: row.id, name: row.name, action: 'pause', rule: 'pauseAfterIdle', why: `idle ${humanIdle(idle)}, past ${said(policy, 'pauseAfterIdle')}`, frees: row.rssBytes ?? 0 })
+ if (RUNNING.has(row.state) && idle >= policy.stopAfterIdleMs) {
+ entries.push({ id: row.id, name: row.name, action: 'stop', rule: 'stopAfterIdle', why: `idle ${humanIdle(idle)}, past ${said(policy, 'stopAfterIdle')}`, frees: row.rssBytes ?? 0 })
continue
}
- entries.push(keep(row, RUNNING.has(row.state) ? `active ${humanIdle(idle)} ago` : 'paused'))
+ entries.push(keep(row, RUNNING.has(row.state) ? `active ${humanIdle(idle)} ago` : 'stopped'))
}
// The ceiling runs last, over whatever is still running after the idle rules. Protected rows hold a
- // slot but are never paused: a person with 20 pinned agents has said what they want, and a rule
+ // slot but are never stopped: a person with 20 pinned agents has said what they want, and a rule
// that overruled that would make pinning worthless. Freshest activity keeps its slot (LRU out).
const survivors = rows.filter((row, i) => RUNNING.has(row.state) && entries[i].action === 'keep')
const byId = new Map(rows.map((row, i) => [row.id, entries[i]]))
@@ -169,7 +175,7 @@ export function decide(rows, rawPolicy, { now = Date.now(), home = '' } = {}) {
if (remaining > 0) continue
const entry = byId.get(row.id)
if (entry.protectedBy) continue
- entry.action = 'pause'
+ entry.action = 'stop'
entry.rule = 'runningCeiling'
entry.why = `over the ceiling of ${policy.runningCeiling} running, and the least recently active (idle ${humanIdle(row.idleMs ?? 0)})`
entry.frees = row.rssBytes ?? 0
@@ -181,15 +187,15 @@ export function decide(rows, rawPolicy, { now = Date.now(), home = '' } = {}) {
function totals(entries, rows) {
const rss = new Map(rows.map((row) => [row.id, Number(row.rssBytes) || 0]))
const count = (action) => entries.filter((entry) => entry.action === action).length
- const frees = entries.filter((entry) => entry.action === 'pause')
+ const frees = entries.filter((entry) => entry.action === 'stop')
.reduce((sum, entry) => sum + (rss.get(entry.id) || 0), 0)
const runningNow = rows.filter((row) => row.state === 'running').length
return {
rows: rows.length,
- pause: count('pause'),
+ stop: count('stop'),
keep: count('keep'),
runningNow,
- runningAfter: runningNow - entries.filter((e) => e.action === 'pause' && rows.find((r) => r.id === e.id)?.state === 'running').length,
+ runningAfter: runningNow - entries.filter((e) => e.action === 'stop' && rows.find((r) => r.id === e.id)?.state === 'running').length,
frees,
}
}
diff --git a/store/agents/harness-monitor/lib/registry.mjs b/store/agents/harness-monitor/lib/registry.mjs
index f3fe4b810..180b4bc66 100644
--- a/store/agents/harness-monitor/lib/registry.mjs
+++ b/store/agents/harness-monitor/lib/registry.mjs
@@ -7,7 +7,7 @@
* file — never writes it. The registry is the daemon's; this is a reader with no lock and no repair.
*
* It is also the fallback when the daemon cannot be reached at all: a fleet you can still SEE when the
- * app is not running is worth more than an error, and pausing is pure tmux, so most of Harness Monitor keeps
+ * app is not running is worth more than an error, and stopping is pure tmux, so most of Harness Monitor keeps
* working from this file alone.
*/
diff --git a/store/agents/harness-monitor/lib/state.mjs b/store/agents/harness-monitor/lib/state.mjs
index 334c21ce2..61d3949d4 100644
--- a/store/agents/harness-monitor/lib/state.mjs
+++ b/store/agents/harness-monitor/lib/state.mjs
@@ -2,7 +2,7 @@
* What a person decided, and what Harness Monitor did about it — read and written through one module so
* the CLI and the pane can never disagree about where anything lives.
*
- * The rules and pins are `~/.config/harness/policy.jsonc`; the resume tickets and the log are under
+ * The rules and pins are `~/.config/harness/policy.jsonc`; the open tickets and the log are under
* `~/.harness/monitor/` (lib/config.mjs has why). The only file left in the WORKSPACE is the verdict,
* because that is the one file Harness itself reads, and it reads it from the workspace.
*/
@@ -14,7 +14,7 @@ import { DEFAULT_POLICY, normalizePolicy } from './policy.mjs'
export function verdictPath(workspace) { return join(workspace, '.harness', 'verdict.json') }
-export const EMPTY_STATE = { spec: 1, policy: { ...DEFAULT_POLICY }, pins: [], paused: {} }
+export const EMPTY_STATE = { spec: 1, policy: { ...DEFAULT_POLICY }, pins: [], stopped: {} }
/** Write through a temp file in the same directory: a reader must never see half of it. */
export async function atomicJson(path, value) {
@@ -29,17 +29,17 @@ export async function atomicJson(path, value) {
export async function readState(workspace, env = process.env) {
if (workspace) await migrateWorkspace(workspace, env).catch(() => null)
const { path, policy, pins } = await readConfig(env)
- const merged = { ...DEFAULT_POLICY, ...policy, protect: { ...DEFAULT_POLICY.protect, ...(policy.protect ?? {}) } }
// A typo must fail here, at the edge, where the message can name the file — not three layers down inside
// a rule while the fleet waits.
- try { normalizePolicy(merged) } catch (error) { throw new Error(`${path}: ${error.message}`) }
- return { spec: 1, policy: merged, pins, paused: await readTickets(env), configPath: path }
+ let merged
+ try { merged = normalizePolicy(policy) } catch (error) { throw new Error(`${path}: ${error.message}`) }
+ return { spec: 1, policy: merged, pins, stopped: await readTickets(env), configPath: path }
}
/** Persist what the program changed: the tickets always, the pins only when they moved. The rules are
* never rewritten from here — a person's file is changed key by key through `updateConfig`, or not at all. */
export async function writeState(workspace, state, env = process.env) {
- await writeTickets(state.paused ?? {}, env)
+ await writeTickets(state.stopped ?? {}, env)
const { pins } = await readConfig(env)
const next = [...new Set(state.pins ?? [])]
if (next.length !== pins.length || next.some((id) => !pins.includes(id))) await updateConfig({ pins: next }, env)
@@ -59,20 +59,20 @@ export async function readLog(workspace, { limit = 200 } = {}, env = process.env
/**
* The pane header, in Harness's own words.
*
- * `ready` means the fleet is inside its policy: nothing is waiting to be paused, nothing is
+ * `ready` means the fleet is inside its policy: nothing is waiting to be stopped, nothing is
* over the ceiling. That makes the header a live answer to "is my machine tidy?" rather than a build
* status, which is the only useful reading for a harness that manages other harnesses.
*/
export async function writeVerdict(workspace, { summary, rows, plan, problems = [] }) {
const findings = []
- const overdue = plan.filter((entry) => entry.action === 'pause').length
- if (overdue) findings.push({ severity: 'warn', kind: 'idle', message: `${overdue} running ${overdue === 1 ? 'harness is' : 'harnesses are'} past the pause threshold, holding ${gb(plan.filter((e) => e.action === 'pause').reduce((sum, e) => sum + (e.frees || 0), 0))}` })
+ const overdue = plan.filter((entry) => entry.action === 'stop').length
+ if (overdue) findings.push({ severity: 'warn', kind: 'idle', message: `${overdue} running ${overdue === 1 ? 'harness is' : 'harnesses are'} past the stop threshold, holding ${gb(plan.filter((e) => e.action === 'stop').reduce((sum, e) => sum + (e.frees || 0), 0))}` })
if (summary.needsInput) findings.push({ severity: 'warn', kind: 'attention', message: `${summary.needsInput} ${summary.needsInput === 1 ? 'harness looks' : 'harnesses look'} like they are waiting on you` })
for (const problem of problems) findings.push({ severity: 'error', kind: 'machine', message: `${problem.machine}: ${problem.error}` })
const verdict = {
spec: 1,
ready: overdue === 0 && problems.length === 0,
- summary: `${summary.total} harnesses · ${summary.running} running · ${summary.paused} paused · ${gb(summary.held)} held`,
+ summary: `${summary.total} harnesses · ${summary.running} running · ${summary.stopped} stopped · ${gb(summary.held)} held`,
findings,
updatedAt: new Date().toISOString(),
}
@@ -88,22 +88,22 @@ export function gb(bytes) {
}
/**
- * The ticket back, written the moment a harness is paused.
+ * The ticket back, written the moment a harness is stopped.
*
* The daemon releases an engine from its row when the process leaves, and the row's session id goes with
* it — the transcript is still on disk, but nothing would know which conversation belonged to this agent.
- * So pause's receipt is kept here, and resume reads it. This is the one piece of state Harness Monitor cannot afford
+ * So stop's receipt is kept here, and open reads it. This is the one piece of state Harness Monitor cannot afford
* to lose, which is why it is written before the success is reported.
*/
-export function markPaused(state, row, ticket) {
+export function markStopped(state, row, ticket) {
if (!ticket?.sessionId) return state
- return { ...state, paused: { ...state.paused, [row.id]: { at: Date.now(), ...ticket } } }
+ return { ...state, stopped: { ...state.stopped, [row.id]: { at: Date.now(), ...ticket } } }
}
-export function clearPaused(state, id) {
- const paused = { ...state.paused }
- delete paused[id]
- return { ...state, paused }
+export function clearStopped(state, id) {
+ const stopped = { ...state.stopped }
+ delete stopped[id]
+ return { ...state, stopped }
}
/** Pin and unpin — the only edits a person makes to this file by hand, kept here so the CLI and
@@ -117,5 +117,5 @@ export function pin(state, id, on) {
/** Forget is the hps's own bookkeeping and nothing else: the row leaves `monitor.json`. No transcript,
* no tmux session, no registry entry is touched here — those belong to the engine and the daemon. */
export function forget(state, id) {
- return clearPaused(pin(state, id, false), id)
+ return clearStopped(pin(state, id, false), id)
}
diff --git a/store/agents/harness-monitor/skills/fleet-operations/SKILL.md b/store/agents/harness-monitor/skills/fleet-operations/SKILL.md
index bf9f64863..63af44111 100644
--- a/store/agents/harness-monitor/skills/fleet-operations/SKILL.md
+++ b/store/agents/harness-monitor/skills/fleet-operations/SKILL.md
@@ -1,6 +1,6 @@
---
name: fleet-operations
-description: Inspect Harness sessions, explain activity and resource readings, preview cleanup, and stop or resume explicitly selected sessions through their owning daemons.
+description: Inspect Harness sessions, explain activity and resource readings, preview cleanup, and stop or open explicitly selected sessions through their owning daemons.
---
# Fleet operations
@@ -15,22 +15,22 @@ are ambiguous. Missing measurements are unknown; an offline machine is not a sto
## Actions
- `hps show <ref> --machines --json` reads one session.
-- `hps pause <ref> --machines --json` asks its owning daemon to stop the process and retain history.
-- `hps resume <ref> --machines --json` restores saved launch settings. Check `resumeMode`: conversation,
+- `hps stop <ref> --machines --json` asks its owning daemon to stop the process and retain history.
+- `hps open <ref> --machines --json` restores saved launch settings. Check `resumeMode`: conversation,
fresh conversation, or shell. Do not promise every engine resumes the same conversation.
-- `hps pause --policy --machines --json` previews cleanup; `--apply` applies the current plan.
+- `hps stop --policy --machines --json` previews cleanup; `--apply` applies the current plan.
- `hps cleanup --machines --json` previews harnesses outside all open tabs; `--apply` closes them.
Background tabs and local utility tabs such as Companions stay open.
-- `hps resume --paused --machines --json` previews reopening stopped sessions; `--apply` executes it.
+- `hps open --stopped --machines --json` previews reopening stopped sessions; `--apply` executes it.
For more than two sessions, show the dry run with reasons and obtain approval before applying it, unless those targets are already authorized.
Recheck the plan after approval; if the targets changed, present the new targets. Named actions must
still correspond to the person's request. Never use `--force` unless explicitly requested for those
sessions. The row's × button is an explicit single-session stop and may interrupt work in progress.
-The daemon owns process identity, stopping and resume configuration on local and linked machines.
+The daemon owns process identity, stopping and open configuration on local and linked machines.
Do not signal PIDs, reconstruct engine flags, respawn a tmux pane, or edit the registry. After a timeout,
-read the original resume receipt; do not invent a new operation to compensate. Explain refusals and
+read the original open receipt; do not invent a new operation to compensate. Explain refusals and
uncertain outcomes. Receipts are recorded in `~/.harness/monitor/log.jsonl`.
## Close harnesses outside tabs
diff --git a/store/agents/harness-monitor/skills/fleet-operations/references/policy.md b/store/agents/harness-monitor/skills/fleet-operations/references/policy.md
index c8564efc5..a29f6779e 100644
--- a/store/agents/harness-monitor/skills/fleet-operations/references/policy.md
+++ b/store/agents/harness-monitor/skills/fleet-operations/references/policy.md
@@ -6,17 +6,17 @@ applied to each linked machine in the monitor. They produce a preview, never a b
| Rule | Default | Meaning |
|---|---|---|
| runningCeiling | 100 | Per machine, propose stopping least recently active unprotected sessions above the ceiling. |
-| pauseAfterIdle | 1d | Propose stopping a running session whose last conversation activity is older than this. |
+| stopAfterIdle | 1d | Propose stopping a running session whose last conversation activity is older than this. |
| hideAfterIdle | 14d | CLI list filter only; --all includes older rows. The monitor table includes all rows. |
-| pauseWhenWorkspaceGone | true | Propose stopping a local session whose folder no longer exists. Remote paths are not checked locally. |
+| stopWhenWorkspaceGone | true | Propose stopping a local session whose folder no longer exists. Remote paths are not checked locally. |
| protect.needsInput / working / pinned | true | Exclude questions, open turns and pinned sessions. |
| protect.attached | true | Reserved for inventories that report attachment; current daemon inventory does not. |
Offline sessions, unknown activity, the monitor itself and unavailable controls are also protected.
-A stopped session is retained by its daemon and remains openable when that engine supports resume.
+A stopped session is retained by its daemon and remains openable when that engine supports open.
There is no retire/forget rule and no transcript deletion.
-To review a threshold, edit the file while preserving comments, then run `hps pause --policy --machines`.
+To review a threshold, edit the file while preserving comments, then run `hps stop --policy --machines`.
`--apply` is an explicit action. The viewer's Cleanup button shows eligible rows and reasons before
Stop reviewed sessions. If activity changes, the action refuses the stale target. Keep bulk operations
within the person's approved scope; changing rules is a separate decision.
diff --git a/store/agents/harness-monitor/store.json b/store/agents/harness-monitor/store.json
index 0ed7584ff..2e137bfac 100644
--- a/store/agents/harness-monitor/store.json
+++ b/store/agents/harness-monitor/store.json
@@ -3,7 +3,7 @@
"tagline": "Monitor resources and AI usage across your machines",
"examples": [
{
- "prompt": "Show me every harness on this machine, then pause everything nobody has touched in a day.",
+ "prompt": "Show me every harness on this machine, then stop everything nobody has touched in a day.",
"caption": "Review idle sessions, then stop the approved ones while keeping their history"
},
{
@@ -11,7 +11,7 @@
"caption": "Running, waiting on you, and idle — with what each one holds"
},
{
- "prompt": "Which harnesses are on a branch that already merged? Pause those and tell me what you kept.",
+ "prompt": "Which harnesses are on a branch that already merged? Stop those and tell me what you kept.",
"caption": "Stopped with the reason recorded and saved launch settings retained"
}
]
diff --git a/store/agents/harness-monitor/template/NOTES.md b/store/agents/harness-monitor/template/NOTES.md
index 0ed7f8957..d264cabd2 100644
--- a/store/agents/harness-monitor/template/NOTES.md
+++ b/store/agents/harness-monitor/template/NOTES.md
@@ -1,6 +1,6 @@
# Harness Monitor
-The session table works without sending a prompt. Use Ask assistant to reveal OpenCode when needed.
+The session table works without sending a prompt. The assistant stays beside the table. Use the viewer’s zoom icon when you want a full-width table.
New monitors default to Muse Spark 1.3 Contributor Free for both main and auxiliary requests. This is a
limited-time free offer whose prompts and responses may train Meta models. Choose another model with
diff --git a/store/agents/harness-monitor/test/actions.test.mjs b/store/agents/harness-monitor/test/actions.test.mjs
index 8d78a8e1b..7b8f66b6e 100644
--- a/store/agents/harness-monitor/test/actions.test.mjs
+++ b/store/agents/harness-monitor/test/actions.test.mjs
@@ -1,6 +1,6 @@
import assert from 'node:assert/strict'
import { test } from 'node:test'
-import { pause, resume } from '../lib/actions.mjs'
+import { stop, open } from '../lib/actions.mjs'
import { mergeRows } from '../lib/inventory.mjs'
import { frame } from './fixtures.mjs'
const observed = Date.now()
@@ -11,33 +11,33 @@ const clearIntent = async () => {}
test('remote stop uses daemon identity, never a signal or tmux command', async () => {
const calls = []
- const result = await pause(row(), { list: async () => [agent()], rpc: async (...args) => { calls.push(args); return { deleted: true } } })
+ const result = await stop(row(), { list: async () => [agent()], rpc: async (...args) => { calls.push(args); return { deleted: true } } })
assert.equal(result.ok, true)
assert.deepEqual(calls, [['remote', 'agent_delete', { agentId: 'a1', expectedSessionId: 's1' }]])
})
test('cleanup rechecks live questions, working and unknown activity', async () => {
for (const activity of ['needsInput', 'working', null]) {
let wrote = false
- const result = await pause(row(), { list: async () => [agent({ monitor: activity ? { activity, activityKnown: true } : null })], rpc: async () => { wrote = true } })
+ const result = await stop(row(), { list: async () => [agent({ monitor: activity ? { activity, activityKnown: true } : null })], rpc: async () => { wrote = true } })
assert.equal(result.ok, false); assert.equal(wrote, false)
}
})
test('explicit single stop can stop work; self and rotated sessions remain protected', async () => {
- assert.equal((await pause(row(), { force: true, list: async () => [agent({ monitor: { activity: 'working', activityKnown: true } })], rpc: async () => ({ deleted: true }) })).ok, true)
+ assert.equal((await stop(row(), { force: true, list: async () => [agent({ monitor: { activity: 'working', activityKnown: true } })], rpc: async () => ({ deleted: true }) })).ok, true)
for (const changed of [{ sessionId: 'another-conversation' }, { dsh: 'autonomous/harness-monitor' }]) {
let wrote = false
- assert.equal((await pause(row(), { force: true, list: async () => [agent(changed)], rpc: async () => { wrote = true } })).ok, false)
+ assert.equal((await stop(row(), { force: true, list: async () => [agent(changed)], rpc: async () => { wrote = true } })).ok, false)
assert.equal(wrote, false)
}
})
test('a lost stop reply is uncertain, not retried', async () => {
let writes = 0
- const result = await pause(row(), { list: async () => [agent()], rpc: async () => { writes++; throw Error('Reply lost') } })
+ const result = await stop(row(), { list: async () => [agent()], rpc: async () => { writes++; throw Error('Reply lost') } })
assert.equal(writes, 1); assert.equal(result.ok, false)
})
-test('resume checks the same durable receipt after a lost reply', async () => {
+test('open checks the same durable receipt after a lost reply', async () => {
const calls = []
- const result = await resume(row({ status: 'stopped' }), { intent, clearIntent, list: async () => [agent({ status: 'stopped' })], rpc: async (machine, type, payload) => {
+ const result = await open(row({ status: 'stopped' }), { intent, clearIntent, list: async () => [agent({ status: 'stopped' })], rpc: async (machine, type, payload) => {
calls.push([machine, type, payload]); if (type === 'agent_resume') throw Error('Disconnected')
return { state: 'created', agent: { id: 'a1' } }
} })
@@ -47,13 +47,13 @@ test('resume checks the same durable receipt after a lost reply', async () => {
})
test('unconfirmed saved intent is only checked, never launched again', async () => {
const calls = []
- const result = await resume(row({ status: 'stopped' }), { intent: async () => ({ ...await intent(), existing: true }), clearIntent,
+ const result = await open(row({ status: 'stopped' }), { intent: async () => ({ ...await intent(), existing: true }), clearIntent,
list: async () => [agent({ status: 'stopped' })], rpc: async (_, type) => { calls.push(type); return { state: 'unconfirmed' } } })
assert.equal(result.unconfirmed, true); assert.deepEqual(calls, ['agent_create_status'])
})
test('a reservation that never reached the daemon retries with the same receipt', async () => {
const calls = []
- const result = await resume(row({ status: 'stopped' }), { intent: async () => ({ ...await intent(), existing: true }), clearIntent,
+ const result = await open(row({ status: 'stopped' }), { intent: async () => ({ ...await intent(), existing: true }), clearIntent,
list: async () => [agent({ status: 'stopped' })], rpc: async (_, type, payload) => {
calls.push([type, payload.creationId]); return type === 'agent_create_status' ? { state: 'missing' } : { state: 'created', agent: { id: 'a1' } }
} })
@@ -64,20 +64,20 @@ test('completed receipts are cleared, including old resumes followed by another
for (const reply of [{ state: 'failed', failure: { code: 'NO_ENGINE', detail: 'Install OpenCode first.' } },
{ state: 'created', agent: { id: 'a1', terminal: { available: false } } }]) {
let cleared = false
- const result = await resume(row({ status: 'stopped' }), { intent: async () => ({ ...await intent(), existing: true }),
+ const result = await open(row({ status: 'stopped' }), { intent: async () => ({ ...await intent(), existing: true }),
clearIntent: async () => { cleared = true }, list: async () => [agent({ status: 'stopped' })], rpc: async () => reply })
assert.equal(result.ok, false); assert.equal(cleared, true)
if (reply.failure) assert.equal(result.detail, reply.failure.detail)
}
})
test('cleanup refuses a session with activity after the reviewed snapshot', async () => {
- const result = await pause(row(), { list: async () => [agent({ updatedAt: observed + 1 })], rpc: async () => { throw Error('Must not stop') } })
+ const result = await stop(row(), { list: async () => [agent({ updatedAt: observed + 1 })], rpc: async () => { throw Error('Must not stop') } })
assert.match(result.detail, /Activity changed/)
})
-test('concurrent resume calls share one operation; running sessions need no launch', async () => {
+test('concurrent open calls share one operation; running sessions need no launch', async () => {
let writes = 0
const target = row({ status: 'stopped' }), options = { intent, clearIntent, list: async () => [agent({ status: 'stopped' })], rpc: async () => { writes++; return { state: 'created', agent: { id: 'a1' } } } }
- const [a,b] = await Promise.all([resume(target, options), resume(target, options)])
+ const [a,b] = await Promise.all([open(target, options), open(target, options)])
assert.equal(a.ok, true); assert.equal(b.ok, true); assert.equal(writes, 1)
- assert.equal((await resume(row(), { list: async () => [agent()], rpc: async () => { throw Error('Must not send') } })).ok, true)
+ assert.equal((await open(row(), { list: async () => [agent()], rpc: async () => { throw Error('Must not send') } })).ok, true)
})
diff --git a/store/agents/harness-monitor/test/format.test.mjs b/store/agents/harness-monitor/test/format.test.mjs
index 9bd63cdf7..cdb488a87 100644
--- a/store/agents/harness-monitor/test/format.test.mjs
+++ b/store/agents/harness-monitor/test/format.test.mjs
@@ -8,11 +8,11 @@ import { DAY, HOUR, row } from './fixtures.mjs'
const rows = [
row({ id: 'a', name: 'widgets', title: 'Fix the reconciler', idleMs: 2 * 60_000, working: true }),
row({ id: 'b', name: 'gadgets', title: 'Ship the thing', idleMs: 2 * DAY, rssBytes: 1.4 * 1024 ** 3 }),
- row({ id: 'c', name: 'old', state: 'paused', idleMs: 20 * DAY, rssBytes: 0, machine: 'studio', local: false }),
+ row({ id: 'c', name: 'old', state: 'stopped', idleMs: 20 * DAY, rssBytes: 0, machine: 'studio', local: false }),
]
test('without a terminal listening there are no escape codes anywhere', () => {
- const text = [table(rows), footer(summarize(rows), normalizePolicy({})), receiptLine({ ok: true, action: 'pause', name: 'x', detail: 'done' })].join('\n')
+ const text = [table(rows), footer(summarize(rows), normalizePolicy({})), receiptLine({ ok: true, action: 'stop', name: 'x', detail: 'done' })].join('\n')
assert.equal(/\u001b\[/.test(text), false)
})
@@ -41,31 +41,31 @@ test('a machine column appears only when there is more than one machine', () =>
test('every state has its own glyph, and waiting beats all of them', () => {
const c = painter({})
- const seen = new Set(['running', 'paused', 'terminal', 'gone'].map((state) => glyph(row({ state }), c).trim()))
+ const seen = new Set(['running', 'stopped', 'terminal', 'gone'].map((state) => glyph(row({ state }), c).trim()))
assert.equal(seen.size, 4)
assert.equal(glyph(row({ state: 'running', working: true }), c).trim(), '◐')
assert.equal(glyph(row({ state: 'running', needsInput: true }), c).trim(), '!')
})
test('the footer says what the fleet is and what the policy is', () => {
- const line = footer(summarize(rows), normalizePolicy({ pauseAfterIdle: '8h' }), { problems: [{ machine: 'studio', error: 'asleep' }] })
+ const line = footer(summarize(rows), normalizePolicy({ stopAfterIdle: '8h' }), { problems: [{ machine: 'studio', error: 'asleep' }] })
assert.match(line, /3 harnesses/)
assert.match(line, /2 running/)
- assert.match(line, /1 paused/)
- assert.match(line, /pause after 8h/)
+ assert.match(line, /1 stopped/)
+ assert.match(line, /stop after 8h/)
assert.match(line, /studio: asleep/)
})
test('a plan reads as one line per row, with nothing to do said plainly', () => {
const plan = decide(rows, { runningCeiling: 12 })
const lines = planLines(plan.entries)
- assert.match(lines, /pause\s+gadgets/)
+ assert.match(lines, /stop\s+gadgets/)
assert.equal(lines.includes('widgets'), false)
assert.match(planLines(decide([rows[0]], {}).entries), /Nothing to do/)
})
test('a receipt shows what happened, including what was refused', () => {
- assert.match(receiptLine({ ok: true, action: 'pause', name: 'x', detail: 'engine stopped', freed: 4e8 }), /✓ pause x \(\+381 MB\)/)
- assert.match(receiptLine({ ok: false, refused: true, action: 'pause', name: 'y', detail: 'pinned' }), /· pause y/)
- assert.match(receiptLine({ ok: true, already: true, action: 'pause', name: 'z', detail: 'already paused' }), /= pause z/)
+ assert.match(receiptLine({ ok: true, action: 'stop', name: 'x', detail: 'engine stopped', freed: 4e8 }), /✓ stop x \(\+381 MB\)/)
+ assert.match(receiptLine({ ok: false, refused: true, action: 'stop', name: 'y', detail: 'pinned' }), /· stop y/)
+ assert.match(receiptLine({ ok: true, already: true, action: 'stop', name: 'z', detail: 'already stopped' }), /= stop z/)
})
diff --git a/store/agents/harness-monitor/test/inventory.test.mjs b/store/agents/harness-monitor/test/inventory.test.mjs
index 8614f10fe..c3cf953c9 100644
--- a/store/agents/harness-monitor/test/inventory.test.mjs
+++ b/store/agents/harness-monitor/test/inventory.test.mjs
@@ -9,7 +9,7 @@ const merge = (extra = {}, options = {}) => mergeRows([agent(extra)], { machine,
test('machine and agent form the identity, including stopped work', () => {
const a = merge({ status: 'stopped' }), b = merge({}, { machine: { machineId: 'm2' } })
assert.equal(a.id, rowId('m1', 'a1')); assert.notEqual(a.id, b.id)
- assert.equal(a.state, 'paused'); assert.equal(a.activity, 'stopped'); assert.equal(a.canStop, false); assert.equal(a.canOpen, true)
+ assert.equal(a.state, 'stopped'); assert.equal(a.activity, 'stopped'); assert.equal(a.canStop, false); assert.equal(a.canOpen, true)
assert.equal(a.engine, 'claude'); assert.equal(a.sessionId, 's1')
})
test('activity and last active use owning daemon facts, not process guesses', () => {
diff --git a/store/agents/harness-monitor/test/page.test.mjs b/store/agents/harness-monitor/test/page.test.mjs
index 2ad3fafab..7da558d87 100644
--- a/store/agents/harness-monitor/test/page.test.mjs
+++ b/store/agents/harness-monitor/test/page.test.mjs
@@ -63,7 +63,7 @@ test('the stylesheet defines dark in both the ways the app can ask for it', asyn
test('the verbs the pane offers are the verbs the server accepts', async () => {
const [js, server] = await Promise.all([read('viewer/app.js'), read('viewer.mjs')])
const allowed = new Set(server.match(/const VERBS = new Set\(\[([^\]]+)\]\)/)[1].match(/'[a-z]+'/g).map((word) => word.slice(1, -1)))
- for (const match of js.matchAll(/\['(pause|resume|retire|resume|pin|unpin|clear)', '/g)) {
+ for (const match of js.matchAll(/\bverb:\s*'([a-z]+)'/g)) {
if (match[1] !== 'clear') assert.ok(allowed.has(match[1]), `the server does not accept ${match[1]}`)
}
for (const forbidden of ['delete', 'kill', 'remove']) assert.equal(allowed.has(forbidden), false)
diff --git a/store/agents/harness-monitor/test/policy.test.mjs b/store/agents/harness-monitor/test/policy.test.mjs
index fc52b93c5..1fc8eceb7 100644
--- a/store/agents/harness-monitor/test/policy.test.mjs
+++ b/store/agents/harness-monitor/test/policy.test.mjs
@@ -30,8 +30,8 @@ test('humanIdle never shows two units', () => {
test('a policy with a bad number fails at load, not mid-fleet', () => {
assert.throws(() => normalizePolicy({ runningCeiling: -1 }), /runningCeiling/)
assert.throws(() => normalizePolicy({ runningCeiling: 1.5 }), /runningCeiling/)
- assert.throws(() => normalizePolicy({ pauseAfterIdle: 'ages' }), /Not a duration/)
- assert.throws(() => normalizePolicy({ pauseAfterIdle: '2d', hideAfterIdle: '1d' }), /at least pauseAfterIdle/)
+ assert.throws(() => normalizePolicy({ stopAfterIdle: 'ages' }), /Not a duration/)
+ assert.throws(() => normalizePolicy({ stopAfterIdle: '2d', hideAfterIdle: '1d' }), /at least stopAfterIdle/)
})
test('a policy keeps keys it does not know about', () => {
@@ -49,25 +49,25 @@ test('protections are reported in the order a person would say them', () => {
assert.equal(protectionFor(row(), policy), null)
})
-test('the idle rules pause what has gone quiet and leave the fresh alone', () => {
+test('the idle rules stop what has gone quiet and leave the fresh alone', () => {
const rows = [
row({ id: 'fresh', idleMs: 5 * 60_000 }),
row({ id: 'stale', idleMs: 2 * DAY }),
row({ id: 'ancient', idleMs: 20 * DAY }),
- row({ id: 'paused-stale', state: 'paused', idleMs: 20 * DAY, rssBytes: 0 }),
+ row({ id: 'stopped-stale', state: 'stopped', idleMs: 20 * DAY, rssBytes: 0 }),
]
const { entries, totals } = decide(rows, { runningCeiling: 99 })
const byId = Object.fromEntries(entries.map((entry) => [entry.id, entry]))
assert.equal(byId.fresh.action, 'keep')
- assert.equal(byId.stale.action, 'pause')
- assert.equal(byId.stale.rule, 'pauseAfterIdle')
- assert.equal(byId.ancient.action, 'pause')
- assert.equal(byId['paused-stale'].action, 'keep', 'already paused: there is nothing left to do to it')
- assert.equal(totals.pause, 2)
+ assert.equal(byId.stale.action, 'stop')
+ assert.equal(byId.stale.rule, 'stopAfterIdle')
+ assert.equal(byId.ancient.action, 'stop')
+ assert.equal(byId['stopped-stale'].action, 'keep', 'already stopped: there is nothing left to do to it')
+ assert.equal(totals.stop, 2)
})
test('the reason echoes the threshold as it was written, not as the clock reads it back', () => {
- const { entries } = decide([row({ idleMs: 20 * DAY })], { pauseAfterIdle: '90m' })
+ const { entries } = decide([row({ idleMs: 20 * DAY })], { stopAfterIdle: '90m' })
assert.match(entries[0].why, /past 90m/)
})
@@ -82,7 +82,7 @@ test('the ceiling pauses the least recently active, and never a protected row',
const byId = Object.fromEntries(entries.map((entry) => [entry.id, entry]))
assert.equal(byId.a.action, 'keep')
assert.equal(byId.b.action, 'keep')
- assert.equal(byId.c.action, 'pause')
+ assert.equal(byId.c.action, 'stop')
assert.equal(byId.c.rule, 'runningCeiling')
assert.equal(byId.pinned.action, 'keep')
assert.equal(totals.runningAfter, 3) // the pinned one still counts as running
@@ -90,30 +90,30 @@ test('the ceiling pauses the least recently active, and never a protected row',
test('each machine has its own ceiling', () => {
const plan = decide([row({ id: 'local', machineId: 'm1' }), row({ id: 'remote', machineId: 'm2' })], { runningCeiling: 1 })
- assert.equal(plan.totals.pause, 0)
+ assert.equal(plan.totals.stop, 0)
})
-test('a ceiling of zero still cannot pause what is protected', () => {
+test('a ceiling of zero still cannot stop what is protected', () => {
const { entries } = decide([row({ id: 'p', pinned: true, idleMs: 3 * HOUR })], { runningCeiling: 0 })
assert.equal(entries[0].action, 'keep')
})
-test('a workspace that no longer exists is paused, whatever its idle time', () => {
+test('a workspace that no longer exists is stopped, whatever its idle time', () => {
const { entries } = decide([row({ idleMs: 2 * HOUR, workspaceGone: true })], {})
- assert.equal(entries[0].action, 'pause')
+ assert.equal(entries[0].action, 'stop')
assert.equal(entries[0].rule, 'workspaceGone')
})
test('the loosened defaults leave yesterday afternoon alone', () => {
const { entries } = decide([row({ id: 'yesterday', idleMs: 18 * HOUR }), row({ id: 'last-week', idleMs: 6 * DAY })], {})
assert.equal(entries[0].action, 'keep')
- assert.equal(entries[1].action, 'pause')
+ assert.equal(entries[1].action, 'stop')
})
test('simulate is the same plan, without the keeps', () => {
const rows = [row({ id: 'a', idleMs: 2 * DAY }), row({ id: 'b', idleMs: 60_000 })]
const result = simulate(rows, {})
- assert.equal(result.pause, 1)
+ assert.equal(result.stop, 1)
assert.equal(result.plan.length, 1)
assert.equal(result.plan[0].id, 'a')
assert.equal(result.frees, rows[0].rssBytes)
@@ -123,11 +123,18 @@ test('a shell is left alone by every rule, however old it is', () => {
const { entries, totals } = decide([row({ state: 'terminal', idleMs: 40 * DAY, rssBytes: 0 })], { runningCeiling: 0 })
assert.equal(entries[0].action, 'keep')
assert.match(entries[0].why, /a shell, not an engine/)
- assert.equal(totals.pause, 0)
+ assert.equal(totals.stop, 0)
})
test('the default ceiling is a backstop: a normal busy day never reaches it', () => {
const rows = Array.from({ length: 60 }, (_, i) => row({ id: `h${i}`, name: `h${i}`, idleMs: (i + 2) * HOUR / 4 }))
const { totals } = decide(rows, {})
- assert.equal(totals.pause, 0, 'sixty harnesses used today, and the default pauses none of them')
+ assert.equal(totals.stop, 0, 'sixty harnesses used today, and the default pauses none of them')
+})
+test('legacy policy names preserve owner thresholds while exposing stop terminology', () => {
+ const policy = normalizePolicy({ pauseAfterIdle: '8h', pauseWhenWorkspaceGone: false })
+ assert.equal(policy.stopAfterIdle, '8h')
+ assert.equal(policy.stopWhenWorkspaceGone, false)
+ assert.equal('pauseAfterIdle' in policy, false)
+ assert.equal(normalizePolicy({ pauseAfterIdle: '8h', stopAfterIdle: '2d' }).stopAfterIdle, '2d')
})
diff --git a/store/agents/harness-monitor/test/preview.mjs b/store/agents/harness-monitor/test/preview.mjs
index b9938418b..2baae0f86 100644
--- a/store/agents/harness-monitor/test/preview.mjs
+++ b/store/agents/harness-monitor/test/preview.mjs
@@ -22,10 +22,10 @@ const rows = Array.from({ length: Number(process.env.PREVIEW_ROWS || 24) }, (_,
}], { machine: { machineId: i % 2 ? 'office' : 'm2', name: i % 2 ? 'Linux · 4090' : 'MacBook Pro' }, local: false, online: i % 17 !== 16 })[0])
const viewer = createViewer({ workspace, port: Number(process.env.PREVIEW_PORT || 0), intervalMs: 3000,
collect: async () => ({ rows, shared: [{ id: 'shared-codex', name: 'Shared Codex server', machine: 'MacBook Pro', machineId: 'm2', agentIds: ['session-0', 'session-4'], online: true, cpu: 2, rssBytes: 340000000, gpuPercent: null }], problems: [], machines: [] }),
- verbs: { pause: async row => {
- Object.assign(row, { state: 'paused', live: false, activity: 'stopped', canStop: false, cpu: 0, rssBytes: 0 })
- return { ok: true, action: 'pause', id: row.id, name: row.name }
- }, resume: async () => ({ ok: false, detail: 'Use the host integration fixture to resume.' }) },
+ verbs: { stop: async row => {
+ Object.assign(row, { state: 'stopped', live: false, activity: 'stopped', canStop: false, cpu: 0, rssBytes: 0 })
+ return { ok: true, action: 'stop', id: row.id, name: row.name }
+ }, open: async () => ({ ok: false, detail: 'Use the host integration fixture to open.' }) },
})
console.log('Synthetic preview: http://127.0.0.1:' + await viewer.start())
for (const signal of ['SIGINT', 'SIGTERM']) process.once(signal, () => viewer.close().then(() => process.exit(0)))
diff --git a/store/agents/harness-monitor/test/scale.test.mjs b/store/agents/harness-monitor/test/scale.test.mjs
index 96f703b3e..d3bad7757 100644
--- a/store/agents/harness-monitor/test/scale.test.mjs
+++ b/store/agents/harness-monitor/test/scale.test.mjs
@@ -1,6 +1,6 @@
import assert from 'node:assert/strict'
import { test } from 'node:test'
-import { CEIL, FLOOR, PAUSE_STEPS, HIDE_STEPS, bytes, humanIdle as pageIdle, idleOfX, parseDuration, snap, xOf } from '../viewer/scale.js'
+import { CEIL, FLOOR, STOP_STEPS, HIDE_STEPS, bytes, humanIdle as pageIdle, idleOfX, parseDuration, snap, xOf } from '../viewer/scale.js'
import { humanIdle as cliIdle } from '../lib/policy.mjs'
import { DAY, HOUR } from './fixtures.mjs'
@@ -22,10 +22,10 @@ test('the scale is monotonic and its inverse round-trips', () => {
})
test('a dragged rule lands on a threshold a person would type', () => {
- assert.equal(snap(4.2 * HOUR, PAUSE_STEPS), '4h')
- assert.equal(snap(70 * 60_000, PAUSE_STEPS), '1h')
+ assert.equal(snap(4.2 * HOUR, STOP_STEPS), '4h')
+ assert.equal(snap(70 * 60_000, STOP_STEPS), '1h')
assert.equal(snap(13 * DAY, HIDE_STEPS), '14d')
- assert.equal(snap(1, PAUSE_STEPS), '15m')
+ assert.equal(snap(1, STOP_STEPS), '15m')
assert.equal(snap(99 * DAY, HIDE_STEPS), '30d')
})
diff --git a/store/agents/harness-monitor/test/server.test.mjs b/store/agents/harness-monitor/test/server.test.mjs
index 68085062a..5a1054cf0 100644
--- a/store/agents/harness-monitor/test/server.test.mjs
+++ b/store/agents/harness-monitor/test/server.test.mjs
@@ -9,7 +9,7 @@ import { createViewer } from '../viewer.mjs'
import { cleanupReviews } from '../lib/cleanup.mjs'
/** A viewer over a fleet that is entirely made up: no daemon, no tmux, no processes. */
-async function serve(rows = [row({ id: 'a1', idleMs: 2 * DAY }), row({ id: 'a2', state: 'paused', idleMs: 20 * DAY, rssBytes: 0 })], options = {}) {
+async function serve(rows = [row({ id: 'a1', idleMs: 2 * DAY }), row({ id: 'a2', state: 'stopped', idleMs: 20 * DAY, rssBytes: 0 })], options = {}) {
const workspace = await mkdtemp(join(tmpdir(), 'hps-server-'))
// A fresh rules file and ticket book per test: tests in one file run in one process, and a pin left by
// one test must not decide what the next one sees.
@@ -22,8 +22,8 @@ async function serve(rows = [row({ id: 'a1', idleMs: 2 * DAY }), row({ id: 'a2',
collect: async () => ({ rows, machines: [], problems: [], observedAt: Date.now() }),
scan: async () => '$ ',
verbs: {
- pause: async (target) => { done.push(['pause', target.id]); return { ok: true, id: target.id, name: target.name, action: 'pause', detail: 'engine stopped', freed: target.rssBytes, ticket: { sessionId: 'sess-0123456789ab', engine: target.engine } } },
- resume: async (target) => { done.push(['resume', target.id]); return { ok: true, id: target.id, name: target.name, action: 'resume', resumed: true, detail: 'resumed' } },
+ stop: async (target) => { done.push(['stop', target.id]); return { ok: true, id: target.id, name: target.name, action: 'stop', detail: 'engine stopped', freed: target.rssBytes, ticket: { sessionId: 'sess-0123456789ab', engine: target.engine } } },
+ open: async (target) => { done.push(['open', target.id]); return { ok: true, id: target.id, name: target.name, action: 'open', reopened: true, detail: 'reopened' } },
},
...options,
})
@@ -41,8 +41,8 @@ test('the snapshot carries the fleet, the policy and the plan', async (t) => {
assert.equal(snapshot.summary.running, 1)
assert.equal(snapshot.policy.runningCeiling, 100)
assert.match(snapshot.configPath, /policy\.jsonc$/, 'the pane can tell a person where the file is')
- assert.ok(snapshot.plan.find((entry) => entry.id === 'a1' && entry.action === 'pause'))
- assert.equal(snapshot.plan.find((entry) => entry.id === 'a2').action, 'keep', 'already paused: nothing left to do')
+ assert.ok(snapshot.plan.find((entry) => entry.id === 'a1' && entry.action === 'stop'))
+ assert.equal(snapshot.plan.find((entry) => entry.id === 'a2').action, 'keep', 'already stopped: nothing left to do')
})
test('the page is served with a token in it and a CSP that forbids inline script', async (t) => {
@@ -79,7 +79,7 @@ test('a request for another host is refused, whatever it asks for', async (t) =>
test('a write without the token does nothing', async (t) => {
const { viewer, base, done } = await serve()
t.after(() => viewer.close())
- const response = await fetch(`${base}/api/act`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ verb: 'pause', ids: ['a1'] }) })
+ const response = await fetch(`${base}/api/act`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ verb: 'stop', ids: ['a1'] }) })
assert.equal(response.status, 403)
assert.deepEqual(done, [])
})
@@ -108,9 +108,9 @@ test('a verb Harness Monitor does not have is refused by name', async (t) => {
t.after(() => viewer.close())
const reply = await post(base, viewer.token, '/api/act', { verb: 'retire', ids: ['a1'] })
assert.match(reply.error, /Not a verb/)
- const empty = await post(base, viewer.token, '/api/act', { verb: 'pause', ids: [] })
+ const empty = await post(base, viewer.token, '/api/act', { verb: 'stop', ids: [] })
assert.match(empty.error, /at least one/)
- const unknown = await post(base, viewer.token, '/api/act', { verb: 'pause', ids: ['nope'] })
+ const unknown = await post(base, viewer.token, '/api/act', { verb: 'stop', ids: ['nope'] })
assert.match(unknown.error, /not in the current view/)
assert.deepEqual(done, [])
})
@@ -118,10 +118,10 @@ test('a verb Harness Monitor does not have is refused by name', async (t) => {
test('a verb with the token acts, records a receipt, and refreshes', async (t) => {
const { viewer, base, workspace, done } = await serve()
t.after(() => viewer.close())
- const reply = await post(base, viewer.token, '/api/act', { verb: 'pause', ids: ['a1'] })
+ const reply = await post(base, viewer.token, '/api/act', { verb: 'stop', ids: ['a1'] })
assert.equal(reply.results.length, 1)
- assert.deepEqual(done, [['pause', 'a1']])
- const tickets = await readFile(join(process.env.HARNESS_MONITOR_STATE, 'paused.json'), 'utf8').catch(() => '{}')
+ assert.deepEqual(done, [['stop', 'a1']])
+ const tickets = await readFile(join(process.env.HARNESS_MONITOR_STATE, 'stopped.json'), 'utf8').catch(() => '{}')
assert.deepEqual(JSON.parse(tickets), {}, 'saved lifecycle belongs to the daemon, not a second ticket book')
const log = await readFile(join(process.env.HARNESS_MONITOR_STATE, 'log.jsonl'), 'utf8')
assert.match(log, /"by":"pane"/)
@@ -140,17 +140,17 @@ test('cleanup rechecks the plan while explicit row stops remain explicit', async
let reads = 0
const { viewer, base, done } = await serve(undefined, { collect: async () => ({ rows: [row({ id: 'a1', idleMs: reads++ ? 0 : 2 * DAY })], problems: [] }) })
t.after(() => viewer.close())
- const refused = await post(base, viewer.token, '/api/act', { verb: 'pause', ids: ['a1'] })
+ const refused = await post(base, viewer.token, '/api/act', { verb: 'stop', ids: ['a1'] })
assert.equal(refused.results[0].ok, false); assert.deepEqual(done, [])
- const explicit = await post(base, viewer.token, '/api/act', { verb: 'pause', ids: ['a1'], manual: true })
- assert.equal(explicit.results[0].ok, true); assert.deepEqual(done, [['pause', 'a1']])
+ const explicit = await post(base, viewer.token, '/api/act', { verb: 'stop', ids: ['a1'], manual: true })
+ assert.equal(explicit.results[0].ok, true); assert.deepEqual(done, [['stop', 'a1']])
})
test('the reviewed conversation cannot be replaced by a newly eligible conversation', async (t) => {
const current = row({ id: 'a1', idleMs: 2 * DAY, sessionId: 'new-conversation' })
const { viewer, base, done } = await serve([current])
t.after(() => viewer.close())
for (const manual of [false, true]) {
- const reply = await post(base, viewer.token, '/api/act', { verb: 'pause', ids: ['a1'], manual,
+ const reply = await post(base, viewer.token, '/api/act', { verb: 'stop', ids: ['a1'], manual,
expected: [{ id: 'a1', sessionId: 'reviewed-conversation', lastActivity: current.lastActivity }] })
assert.equal(reply.results[0].ok, false)
assert.match(reply.results[0].detail, /changed since you reviewed/)
@@ -161,14 +161,14 @@ test('the reviewed conversation cannot be replaced by a newly eligible conversat
test('a policy is validated before it is written', async (t) => {
const { viewer, base, workspace } = await serve()
t.after(() => viewer.close())
- const bad = await post(base, viewer.token, '/api/policy', { policy: { pauseAfterIdle: 'whenever' } })
+ const bad = await post(base, viewer.token, '/api/policy', { policy: { stopAfterIdle: 'whenever' } })
assert.match(bad.error, /Not a duration/)
- const worse = await post(base, viewer.token, '/api/policy', { policy: { pauseAfterIdle: '2d', hideAfterIdle: '1d' } })
- assert.match(worse.error, /at least pauseAfterIdle/)
- const good = await post(base, viewer.token, '/api/policy', { policy: { pauseAfterIdle: '8h', protect: { pinned: false } } })
- assert.equal(good.policy.pauseAfterIdle, '8h')
+ const worse = await post(base, viewer.token, '/api/policy', { policy: { stopAfterIdle: '2d', hideAfterIdle: '1d' } })
+ assert.match(worse.error, /at least stopAfterIdle/)
+ const good = await post(base, viewer.token, '/api/policy', { policy: { stopAfterIdle: '8h', protect: { pinned: false } } })
+ assert.equal(good.policy.stopAfterIdle, '8h')
const rules = await readFile(process.env.HARNESS_MONITOR_CONFIG, 'utf8')
- assert.match(rules, /"pauseAfterIdle": "8h"/)
+ assert.match(rules, /"stopAfterIdle": "8h"/)
assert.match(rules, /"pinned": true/, 'the pane may only change the thresholds it draws, never a guard')
})
diff --git a/store/agents/harness-monitor/test/state.test.mjs b/store/agents/harness-monitor/test/state.test.mjs
index 0d3727021..4dbe9aeab 100644
--- a/store/agents/harness-monitor/test/state.test.mjs
+++ b/store/agents/harness-monitor/test/state.test.mjs
@@ -5,7 +5,7 @@ import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { DAY, row } from './fixtures.mjs'
import { stripJsonc, updateConfig } from '../lib/config.mjs'
-import { EMPTY_STATE, clearPaused, forget, gb, markPaused, pin, readLog, readState, record, writeState, writeVerdict } from '../lib/state.mjs'
+import { EMPTY_STATE, clearStopped, forget, gb, markStopped, pin, readLog, readState, record, writeState, writeVerdict } from '../lib/state.mjs'
import { decide } from '../lib/policy.mjs'
const workspace = () => mkdtemp(join(tmpdir(), 'hps-state-'))
@@ -20,18 +20,18 @@ test('a machine with no rules file gets the commented default, and reads it', as
const { env } = await machine()
const state = await readState(null, env)
assert.equal(state.policy.runningCeiling, EMPTY_STATE.policy.runningCeiling)
- assert.equal(state.policy.pauseAfterIdle, '1d')
+ assert.equal(state.policy.stopAfterIdle, '1d')
const text = await readFile(env.HARNESS_MONITOR_CONFIG, 'utf8')
assert.match(text, /\/\/ Most engines running at once/, 'the file explains itself')
- assert.match(text, /hps pause --policy/, 'and says how to preview a change')
+ assert.match(text, /hps stop --policy/, 'and says how to preview a change')
})
test('a rules file with a typo in it names the file it is in', async () => {
const { env } = await machine()
await mkdir(join(env.HARNESS_MONITOR_CONFIG, '..'), { recursive: true })
- await writeFile(env.HARNESS_MONITOR_CONFIG, '{ "pauseAfterIdle": "whenever" }')
+ await writeFile(env.HARNESS_MONITOR_CONFIG, '{ "stopAfterIdle": "whenever" }')
await assert.rejects(() => readState(null, env), /policy\.jsonc: Not a duration/)
- await writeFile(env.HARNESS_MONITOR_CONFIG, '{ "pauseAfterIdle": ')
+ await writeFile(env.HARNESS_MONITOR_CONFIG, '{ "stopAfterIdle": ')
await assert.rejects(() => readState(null, env), /policy\.jsonc: not valid JSON/)
})
@@ -48,21 +48,21 @@ test('changing a value leaves every comment in the person\'s file exactly where
const { env } = await machine()
await readState(null, env)
const before = await readFile(env.HARNESS_MONITOR_CONFIG, 'utf8')
- await updateConfig({ pauseAfterIdle: '3d', runningCeiling: 30 }, env)
+ await updateConfig({ stopAfterIdle: '3d', runningCeiling: 30 }, env)
const after = await readFile(env.HARNESS_MONITOR_CONFIG, 'utf8')
assert.equal(after.split('//').length, before.split('//').length, 'no comment was lost')
- assert.match(after, /"pauseAfterIdle": "3d"/)
+ assert.match(after, /"stopAfterIdle": "3d"/)
assert.match(after, /"runningCeiling": 30/)
- assert.equal((await readState(null, env)).policy.pauseAfterIdle, '3d')
+ assert.equal((await readState(null, env)).policy.stopAfterIdle, '3d')
})
test('tickets and pins are written where the program keeps them, and read back', async () => {
const { env } = await machine()
const state = await readState(null, env)
- await writeState(null, { ...state, pins: ['a1'], paused: { a2: { sessionId: 'sess-0123456789ab', engine: 'claude' } } }, env)
+ await writeState(null, { ...state, pins: ['a1'], stopped: { a2: { sessionId: 'sess-0123456789ab', engine: 'claude' } } }, env)
const back = await readState(null, env)
assert.deepEqual(back.pins, ['a1'])
- assert.equal(back.paused.a2.sessionId, 'sess-0123456789ab')
+ assert.equal(back.stopped.a2.sessionId, 'sess-0123456789ab')
assert.match(await readFile(env.HARNESS_MONITOR_CONFIG, 'utf8'), /"pins": \["a1"\]/)
})
@@ -70,42 +70,42 @@ test('an old per-workspace file is carried forward once: its data yes, its stric
const { env } = await machine()
const workspace = await mkdtemp(join(tmpdir(), 'hps-old-workspace-'))
await writeFile(join(workspace, 'monitor.json'), JSON.stringify({
- policy: { pauseAfterIdle: '4h', runningCeiling: 12 },
+ policy: { stopAfterIdle: '4h', runningCeiling: 12 },
pins: ['keep-me'],
- paused: { p1: { sessionId: 'sess-0123456789ab', engine: 'claude' }, p2: { sessionId: 'sess-abcdef012345', engine: 'codex' } },
+ stopped: { p1: { sessionId: 'sess-0123456789ab', engine: 'claude' }, p2: { sessionId: 'sess-abcdef012345', engine: 'codex' } },
}))
const state = await readState(workspace, env)
- assert.equal(Object.keys(state.paused).length, 2, 'every paused harness is still resumable')
+ assert.equal(Object.keys(state.stopped).length, 2, 'every stopped harness is still openable')
assert.deepEqual(state.pins, ['keep-me'])
- assert.equal(state.policy.pauseAfterIdle, '1d', 'the old 4h did not come along')
+ assert.equal(state.policy.stopAfterIdle, '1d', 'the old 4h did not come along')
const marker = JSON.parse(await readFile(join(workspace, 'monitor.json'), 'utf8'))
assert.equal(marker.migrated, true)
const again = await readState(workspace, env)
- assert.equal(Object.keys(again.paused).length, 2, 'running it twice does not double anything')
+ assert.equal(Object.keys(again.stopped).length, 2, 'running it twice does not double anything')
})
-test('pin and the resume ticket are the only edits, and each is reversible', () => {
+test('pin and the open ticket are the only edits, and each is reversible', () => {
let state = { ...EMPTY_STATE }
state = pin(state, 'a1', true)
assert.deepEqual(state.pins, ['a1'])
state = pin(state, 'a1', true)
assert.deepEqual(state.pins, ['a1'], 'pinning twice is still one pin')
- state = markPaused(state, row(), { sessionId: 'sess-0123456789ab', engine: 'claude' })
- assert.equal(state.paused.a1.sessionId, 'sess-0123456789ab')
- state = clearPaused(state, 'a1')
- assert.equal(state.paused.a1, undefined)
- state = forget(markPaused(pin(state, 'a1', true), row(), { sessionId: 'sess-0123456789ab', engine: 'claude' }), 'a1')
+ state = markStopped(state, row(), { sessionId: 'sess-0123456789ab', engine: 'claude' })
+ assert.equal(state.stopped.a1.sessionId, 'sess-0123456789ab')
+ state = clearStopped(state, 'a1')
+ assert.equal(state.stopped.a1, undefined)
+ state = forget(markStopped(pin(state, 'a1', true), row(), { sessionId: 'sess-0123456789ab', engine: 'claude' }), 'a1')
assert.deepEqual(state.pins, [])
- assert.equal(state.paused.a1, undefined)
+ assert.equal(state.stopped.a1, undefined)
})
test('every action leaves a receipt, newest first', async () => {
const { dir, env } = await machine()
- await record(dir, { action: 'pause', id: 'a1', name: 'widgets', ok: true, detail: 'engine stopped' }, env)
- await record(dir, { action: 'resume', id: 'a1', name: 'widgets', ok: true, detail: 'resumed' }, env)
+ await record(dir, { action: 'stop', id: 'a1', name: 'widgets', ok: true, detail: 'engine stopped' }, env)
+ await record(dir, { action: 'open', id: 'a1', name: 'widgets', ok: true, detail: 'reopened' }, env)
const log = await readLog(dir, {}, env)
assert.equal(log.length, 2)
- assert.equal(log[0].action, 'resume')
+ assert.equal(log[0].action, 'open')
assert.ok(log[0].at)
})
@@ -113,19 +113,19 @@ test('a log that cannot be written does not undo the action', async () => {
const { dir, env } = await machine()
const blocked = join(dir, 'file')
await writeFile(blocked, 'not a directory')
- await record(null, { action: 'pause', ok: true }, { ...env, HARNESS_MONITOR_STATE: join(blocked, 'state') })
+ await record(null, { action: 'stop', ok: true }, { ...env, HARNESS_MONITOR_STATE: join(blocked, 'state') })
})
test('the pane header is ready only when the fleet is inside its policy', async () => {
const dir = await workspace()
const tidy = [row({ idleMs: 60_000 })]
const tidyPlan = decide(tidy, { runningCeiling: 12 })
- const good = await writeVerdict(dir, { summary: { total: 1, running: 1, paused: 0, held: 0, needsInput: 0 }, rows: tidy, plan: tidyPlan.entries })
+ const good = await writeVerdict(dir, { summary: { total: 1, running: 1, stopped: 0, held: 0, needsInput: 0 }, rows: tidy, plan: tidyPlan.entries })
assert.equal(good.ready, true)
const messy = [row({ id: 'a', idleMs: 9 * DAY }), row({ id: 'b', idleMs: 40 * DAY })]
const messyPlan = decide(messy, { runningCeiling: 12 })
- const bad = await writeVerdict(dir, { summary: { total: 2, running: 2, paused: 0, held: 8e8, needsInput: 1 }, rows: messy, plan: messyPlan.entries, problems: [{ machine: 'studio', error: 'asleep' }] })
+ const bad = await writeVerdict(dir, { summary: { total: 2, running: 2, stopped: 0, held: 8e8, needsInput: 1 }, rows: messy, plan: messyPlan.entries, problems: [{ machine: 'studio', error: 'asleep' }] })
assert.equal(bad.ready, false)
assert.ok(bad.findings.some((finding) => finding.kind === 'idle'))
assert.ok(bad.findings.some((finding) => finding.kind === 'attention'))
diff --git a/store/agents/harness-monitor/test/table.test.mjs b/store/agents/harness-monitor/test/table.test.mjs
index 280bf82a5..ee55b7fda 100644
--- a/store/agents/harness-monitor/test/table.test.mjs
+++ b/store/agents/harness-monitor/test/table.test.mjs
@@ -24,9 +24,10 @@ test('formatters distinguish zero from unknown and handle future timestamps', ()
})
test('opens with active sessions only and never treats saved history as processes', () => {
- const history = { id: 'saved', name: 'Old', state: 'paused', activity: 'stopped', live: false }
+ const history = { id: 'saved', name: 'Old', state: 'stopped', activity: 'stopped', live: false }
assert.deepEqual(visibleRows([...rows, history]).map(r => r.id).sort(), ['m1/a', 'm2/a'])
assert.equal(visibleRows([...rows, history], { filter: 'all' }).length, 3)
+ assert.deepEqual(visibleRows([...rows, history], { filter: 'stopped' }).map(r => r.id), ['saved'])
assert.equal(visibleRows(rows, { machine: 'missing' }).length, 0)
})
test('shared and nested workspace paths count once on each owning machine', () => {
diff --git a/store/agents/harness-monitor/toolchain/hps.mjs b/store/agents/harness-monitor/toolchain/hps.mjs
index 3b33017b8..1b7360ea1 100755
--- a/store/agents/harness-monitor/toolchain/hps.mjs
+++ b/store/agents/harness-monitor/toolchain/hps.mjs
@@ -4,7 +4,7 @@
*
* Everything the agent does, a person can do by hand, with the same words and the same receipts: this
* file is the only entry point, and the viewer calls the same library underneath. Verbs are the ones a
- * developer already has muscle memory for — `ls`, `pause`, `resume`, `gc`, `log` — and every one of them
+ * developer already has muscle memory for — `ls`, `stop`, `open`, `gc`, `log` — and every one of them
* takes `--json` so the agent beside it never has to parse a table meant for eyes.
*
* Explicit cleanup closes hidden harnesses through the owning daemon and preserves history.
@@ -12,7 +12,7 @@
import { homedir } from 'node:os'
import { resolve } from 'node:path'
-import { pause, resume } from '../lib/actions.mjs'
+import { stop, open } from '../lib/actions.mjs'
import { closeHidden, previewCleanup } from '../lib/cleanup.mjs'
import { closeBridges } from '../lib/bridge.mjs'
import { collect, resolveRef, summarize } from '../lib/inventory.mjs'
@@ -29,23 +29,23 @@ const USAGE = `hps — sessions on this machine, running or stopped
hps the list, freshest first (like \`docker ps\`)
hps top the same list, refreshing
- hps [--all] [--state running|paused|shell|gone] [--project NAME] [--engine NAME]
+ hps [--all] [--state running|stopped|shell|gone] [--project NAME] [--engine NAME]
[--idle 4h] [--sort idle|mem|name|project] [--limit N] [--watch [SECONDS]]
[--machines] include linked machines for reads and actions
hps show <ref> one harness in full, with the last thing on its pane
- hps pause <ref…> stop the process and retain history and launch settings
- hps resume <ref…> reopen with the saved engine configuration
- hps pause --policy what the rules would do to the fleet right now, and why
- hps pause --policy --apply do it
- hps pause --idle 8h one threshold instead of all of them
- hps resume --paused everything that is paused, back in one line
+ hps stop <ref…> stop the process and retain history and launch settings
+ hps open <ref…> reopen with the saved engine configuration
+ hps stop --policy what the rules would do to the fleet right now, and why
+ hps stop --policy --apply do it
+ hps stop --idle 8h one threshold instead of all of them
+ hps open --stopped everything that is stopped, back in one line
hps attach <ref> hand this terminal to that pane (tmux attach, screen -r)
hps cleanup [--machines] preview harnesses outside all open tabs
hps cleanup [--machines] --apply close them and keep history; ends unfinished work
<ref> is a row number from the last list, a %pane, an agent-id prefix, or part of a name.
Add --json to any command. --force gets past a guard; --dry-run shows what would happen.
- \`park\`/\`wake\` alias pause/resume. \`prune\`, \`gc\` and \`policy\` alias \`pause --policy\`.
+ \`prune\`, \`gc\` and \`policy\` alias \`stop --policy\`.
The rules are a config file: ~/.config/harness/policy.jsonc. Edit it and review Cleanup in the table.
Nothing here writes it for you — a setter subcommand was only ever a worse text editor. To exempt one
@@ -118,13 +118,9 @@ function pick(refs, rows) {
return { picked, errors }
}
-// `park`/`wake` stay as aliases: muscle memory is real and an alias costs nothing.
-// `park`/`wake` and `hibernate` stay as aliases: an alias costs nothing, and muscle memory is real.
-// `stop` is deliberately NOT an alias: `harness stop` already means "stop the daemon", and teaching the
-// wrong habit here would collide the day these verbs move into the real CLI.
-const ALIASES = { park: 'pause', wake: 'resume', revive: 'resume', unpause: 'resume', hibernate: 'pause', top: 'ls', ps: 'ls', prune: 'pause', gc: 'pause', policy: 'pause' }
+const ALIASES = { top: 'ls', ps: 'ls', prune: 'stop', gc: 'stop', policy: 'stop' }
// `observe` is plumbing: the workspace init script calls it to write the first verdict. Not in the help.
-const COMMANDS = new Set(['ls', 'show', 'pause', 'resume', 'attach', 'cleanup', 'observe', 'help', ...Object.keys(ALIASES)])
+const COMMANDS = new Set(['ls', 'show', 'stop', 'open', 'attach', 'cleanup', 'observe', 'help', ...Object.keys(ALIASES)])
async function main() {
// `hps` on its own is the list — `docker ps`, not `docker ps ls`. A leading flag is a flag, not a verb,
@@ -134,16 +130,16 @@ async function main() {
let command = ALIASES[typed] ?? typed
const argv = args
const { flags, rest } = parseArgs(argv)
- // `prune`, `gc` and `policy` all arrive as `pause`; what they meant was "the whole plan".
+ // `prune`, `gc` and `policy` all arrive as `stop`; what they meant was "the whole plan".
if (['prune', 'gc', 'policy'].includes(typed)) {
flags.policy = true
if (rest[0] === 'apply') { rest.shift(); flags.apply = true }
}
// ANY BULK SELECTION IS A DRY RUN UNTIL `--apply`. A named ref acts at once — you typed the name, so you
// meant that one — but `--policy` and `--idle` can select forty harnesses from one line. The first
- // version of this defaulted the other way and paused thirty-five of them on a live machine; reversible
+ // version of this defaulted the other way and stopped thirty-five of them on a live machine; reversible
// is not the same as asked for.
- if ((flags.policy || flags.idle || flags['over-ceiling'] || flags.paused) && !flags.apply) flags['dry-run'] = true
+ if ((flags.policy || flags.idle || flags['over-ceiling'] || flags.stopped) && !flags.apply) flags['dry-run'] = true
if (flags.help || command === 'help' || command === '--help') { out(USAGE); return }
if (command === 'cleanup') {
@@ -211,13 +207,13 @@ async function main() {
return
}
- if (['pause', 'resume'].includes(command)) {
+ if (['stop', 'open'].includes(command)) {
const { rows, policy, plan, summary, problems } = await world({ includeRemote: Boolean(flags.machines) })
let targets = []
- // `resume --paused` is the undo button: everything this ever paused, back in one line. A dry run first,
+ // `open --stopped` is the undo button: everything this ever stopped, back in one line. A dry run first,
// like every other bulk selection.
- if (command === 'resume' && flags.paused) {
- targets = rows.filter((row) => row.state === 'paused')
+ if (command === 'open' && flags.stopped) {
+ targets = rows.filter((row) => row.state === 'stopped')
} else if (flags.policy || flags.idle || flags['over-ceiling']) {
// The rules select the rows. `--idle` is the same shape with one threshold instead of all of them.
const chosen = flags.idle
@@ -242,7 +238,7 @@ async function main() {
if (flags.policy) {
out(planLines(plan.entries, { tty: TTY }))
out('')
- out(`Would ${command} ${plan.totals.pause} — handing back ${gb(plan.totals.frees)} and leaving ${plan.totals.runningAfter} running.`)
+ out(`Would ${command} ${plan.totals.stop} — handing back ${gb(plan.totals.frees)} and leaving ${plan.totals.runningAfter} running.`)
out(`Nothing has moved. Run \`hps ${command} --policy --apply\` to do it.`)
} else {
out(targets.map((row) => `${command} ${row.name} — idle ${humanIdle(row.idleMs)}, ${row.state}${row.rssBytes ? `, ${gb(row.rssBytes)}` : ''}`).join('\n') || 'Nothing matches.')
@@ -253,7 +249,7 @@ async function main() {
const options = { policy, force: Boolean(flags.force) }
const results = []
for (const row of targets) {
- const result = command === 'pause' ? await pause(row, options) : await resume(row)
+ const result = command === 'stop' ? await stop(row, options) : await open(row)
results.push(result)
}
await commit(results.map((result) => ({ ...result, by: flags.by ?? 'cli' })))
diff --git a/store/agents/harness-monitor/viewer.mjs b/store/agents/harness-monitor/viewer.mjs
index 68bc5e329..913476e1f 100644
--- a/store/agents/harness-monitor/viewer.mjs
+++ b/store/agents/harness-monitor/viewer.mjs
@@ -6,7 +6,7 @@ import { readFile } from 'node:fs/promises'
import { homedir } from 'node:os'
import { dirname, join, resolve } from 'node:path'
import { fileURLToPath, pathToFileURL } from 'node:url'
-import { pause, resume } from './lib/actions.mjs'
+import { stop, open } from './lib/actions.mjs'
import { cleanupReviews } from './lib/cleanup.mjs'
import { closeBridges } from './lib/bridge.mjs'
import { collect as collectFleet, summarize, tilde } from './lib/inventory.mjs'
@@ -14,9 +14,9 @@ import { DEFAULT_POLICY, decide, normalizePolicy } from './lib/policy.mjs'
import { pin, readLog, readState, record, savePolicyValues, writeState, writeVerdict } from './lib/state.mjs'
const PACKAGE = dirname(fileURLToPath(import.meta.url))
-const VERBS = new Set(['pause', 'resume', 'pin', 'unpin'])
+const VERBS = new Set(['stop', 'open', 'pin', 'unpin'])
-export function createViewer({ workspace, port = 0, intervalMs = 4000, remoteIntervalMs = 15_000, now = () => Date.now(), collect = collectFleet, verbs = { pause, resume }, cleanup = cleanupReviews() }) {
+export function createViewer({ workspace, port = 0, intervalMs = 4000, remoteIntervalMs = 15_000, now = () => Date.now(), collect = collectFleet, verbs = { stop, open }, cleanup = cleanupReviews() }) {
const token = randomBytes(24).toString('base64url')
const clients = new Set()
const cache = new Map()
@@ -119,7 +119,7 @@ export function createViewer({ workspace, port = 0, intervalMs = 4000, remoteInt
const explicit = manual === true && targets.length === 1
const reviewed = new Map((Array.isArray(expected) ? expected : snapshot.rows).filter(row => row && typeof row.id === 'string').map(({ id, sessionId, lastActivity }) => [id, { sessionId, lastActivity }]))
// Bulk actions are restricted to what is still in the reviewed cleanup plan.
- if (verb === 'pause' && !explicit) {
+ if (verb === 'stop' && !explicit) {
await polling
await poll({ immediate: true, forceRemote: true })
}
@@ -130,23 +130,23 @@ export function createViewer({ workspace, port = 0, intervalMs = 4000, remoteInt
let next = state
const results = targets.filter(id => !rows.some(row => row.id === id)).map(id => ({ id, name: id, action: verb, ok: false, refused: true, detail: 'This session is no longer in the current view.' }))
- const eligible = new Set(snapshot.plan.filter(entry => entry.action === 'pause').map(entry => entry.id))
+ const eligible = new Set(snapshot.plan.filter(entry => entry.action === 'stop').map(entry => entry.id))
for (const row of rows) {
const review = reviewed.get(row.id)
- if (verb === 'pause' && (!review || review.sessionId !== row.sessionId || (!explicit && review.lastActivity !== row.lastActivity))) {
+ if (verb === 'stop' && (!review || review.sessionId !== row.sessionId || (!explicit && review.lastActivity !== row.lastActivity))) {
results.push({ id: row.id, name: row.name, action: verb, ok: false, refused: true, detail: 'This session changed since you reviewed it. Refresh and review it again.' })
continue
}
- if (verb === 'pause' && !explicit && !eligible.has(row.id)) {
+ if (verb === 'stop' && !explicit && !eligible.has(row.id)) {
results.push({ id: row.id, name: row.name, action: verb, ok: false, refused: true, detail: 'This session is no longer eligible for cleanup. Review the new plan.' })
continue
}
if (verb === 'pin' || verb === 'unpin') {
next = pin(next, row.id, verb === 'pin')
- results.push({ ok: true, action: verb, id: row.id, name: row.name, detail: verb === 'pin' ? 'never paused by the policy' : 'the policy may pause it again' })
+ results.push({ ok: true, action: verb, id: row.id, name: row.name, detail: verb === 'pin' ? 'never stopped by the policy' : 'the policy may stop it again' })
continue
}
- const result = verb === 'pause' ? await verbs.pause(row, { policy, force: explicit }) : await verbs.resume(row)
+ const result = verb === 'stop' ? await verbs.stop(row, { policy, force: explicit }) : await verbs.open(row)
results.push(result)
}
if (verb === 'pin' || verb === 'unpin') await writeState(workspace, next)
@@ -159,7 +159,7 @@ export function createViewer({ workspace, port = 0, intervalMs = 4000, remoteInt
async function savePolicy(raw) {
// Only the keys the pane can change, and only valid values: the file is a person's, and the pane is a
// guest in it. Everything else in it — comments included — is left exactly as it was.
- const allowed = ['pauseAfterIdle', 'hideAfterIdle', 'runningCeiling']
+ const allowed = ['stopAfterIdle', 'hideAfterIdle', 'runningCeiling']
const values = Object.fromEntries(Object.entries(raw ?? {}).filter(([key]) => allowed.includes(key)))
const state = await readState(workspace)
let policy
diff --git a/store/agents/harness-monitor/viewer/app.css b/store/agents/harness-monitor/viewer/app.css
index 4acad3b0d..7fbb38649 100644
--- a/store/agents/harness-monitor/viewer/app.css
+++ b/store/agents/harness-monitor/viewer/app.css
@@ -109,3 +109,8 @@ p { line-height:1.5; }
@media (max-width:540px) { header { flex-wrap:wrap; gap:12px; padding:14px 12px; } .search-field { width:100%; margin:0; } nav { padding:0 8px 10px; } .segmented { width:100%; margin:0 0 5px; } .segmented button { flex:1; } #inspect-content { grid-template-columns:1fr; } #summary { padding:12px; } footer { padding:8px 12px; } }
@media (prefers-contrast: more) { :root { --muted:var(--text); --line:var(--text); } button,select,summary { border-color:var(--line); } }
@media (prefers-reduced-motion: reduce) { *,*::before,*::after { animation:none !important; transition:none !important; } }
+
+#assistant-info { position:relative; flex:none; }
+#assistant-info .menu { position:absolute; right:0; z-index:5; width:310px; padding:12px; white-space:normal; line-height:1.5; }
+#assistant-info .menu p { margin:0 0 8px; }
+#assistant-info .menu p:last-child { margin-bottom:0; }
diff --git a/store/agents/harness-monitor/viewer/app.js b/store/agents/harness-monitor/viewer/app.js
index 239f27f3a..4a38ff0d5 100644
--- a/store/agents/harness-monitor/viewer/app.js
+++ b/store/agents/harness-monitor/viewer/app.js
@@ -4,10 +4,10 @@ const dom = {
search: el('search'), filter: el('filter'), machine: el('machine'), columns: el('columns'), columnOptions: el('column-options'),
grid: el('grid'), table: el('table'), colgroup: el('colgroup'), head: el('head'), body: el('body'),
empty: el('empty'), count: el('count'), message: el('message'), updated: el('updated'), problems: el('problems'),
- refresh: el('refresh'), pause: el('pause'), live: el('live-status'), inspect: el('inspect'), stop: el('stop'),
+ refresh: el('refresh'), freeze: el('freeze'), live: el('live-status'), inspect: el('inspect'), stop: el('stop'), open: el('open'),
summary: el('summary'), shared: el('shared'), sharedTitle: el('shared-title'), sharedBody: el('shared-body'),
inspector: el('inspector'), inspectTitle: el('inspect-title'), inspectContext: el('inspect-context'),
- inspectContent: el('inspect-content'), inspectClose: el('inspect-close'), inspectStop: el('inspect-stop'),
+ inspectContent: el('inspect-content'), inspectClose: el('inspect-close'), inspectStop: el('inspect-stop'), inspectOpen: el('inspect-open'),
stopDialog: el('stop-dialog'), stopTitle: el('stop-title'), stopContext: el('stop-context'), stopResult: el('stop-result'),
stopCancel: el('stop-cancel'), stopConfirm: el('stop-confirm'),
}
@@ -21,7 +21,7 @@ const state = {
preset: Object.hasOwn(PRESETS, saved.preset) ? saved.preset : 'overview',
visible: new Set(Array.isArray(saved.visible) ? saved.visible : PRESETS.overview), widths: {},
selected: null, inspecting: null, busy: new Set(), nodes: new Map(), shown: [],
- paused: false, pending: null, connected: false, receivedAt: 0, review: null,
+ frozen: false, pending: null, connected: false, receivedAt: 0, review: null,
}
for (const col of COLUMNS) state.widths[col.key] = Math.max(64, Math.min(600, Number(saved.widths?.[col.key]) || col.width))
const text = (node, value) => { if (node.textContent !== String(value)) node.textContent = value }
@@ -41,6 +41,17 @@ async function post(path, payload) {
if (!response.ok || result.error) throw new Error(result.error || 'Request failed. Refresh and try again.')
return result
}
+// Native and remote viewers share a bounded navigation-only host bridge.
+window.harnessHostQueue = []
+function openRow(id) {
+ const row = state.rows.find(r => r.id === id)
+ if (!canOpen(row)) return
+ const action = { action: 'open', machineId: row.machineId, agentId: row.agentId }
+ if (window.HarnessHost?.postMessage) window.HarnessHost.postMessage(JSON.stringify(action))
+ else if (window.harnessEmbedded) {
+ if (window.harnessHostQueue.length < 8) window.harnessHostQueue.push(action)
+ } else message('Open this viewer inside Harness to use this action.')
+}
const activeColumns = () => {
const ordered = PRESETS[state.preset]
return ordered ? ordered.map(key => COLUMNS.find(c => c.key === key))
@@ -151,11 +162,12 @@ function updateRow(tr, row) {
}
const currentSelection = () => state.shown.find(r => r.id === state.selected)
const currentSnapshot = () => ['ok', 'degraded'].includes(state.snapshot?.status)
-const canStop = row => row?.canStop && state.connected && currentSnapshot() && !state.paused && !state.busy.has(row.id)
+const canOpen = row => row?.canOpen && state.connected && currentSnapshot() && !state.frozen && !state.busy.has(row.id)
+const canStop = row => row?.canStop && state.connected && currentSnapshot() && !state.frozen && !state.busy.has(row.id)
function select() {
for (const [id, node] of state.nodes) node.setAttribute('aria-selected', String(id === state.selected))
- const row = currentSelection(); dom.inspect.disabled = !row; dom.stop.disabled = !canStop(row)
- dom.stop.title = row ? row.unavailable || (state.paused ? 'Resume live updates before stopping.' : 'Stop ' + row.name + '; keep history and files') : 'Select a harness to stop'
+ const row = currentSelection(); dom.inspect.disabled = !row; dom.stop.disabled = !canStop(row); dom.open.disabled = !canOpen(row)
+ dom.stop.title = row ? row.unavailable || (state.frozen ? 'Turn on live updates before stopping.' : 'Stop ' + row.name + '; keep history and files') : 'Select a harness to stop'
}
const totalText = (total, formatter) => total.value == null ? '—' : (total.partial ? '≥' : '') + formatter(total.value)
function summary() {
@@ -173,7 +185,7 @@ function summary() {
const item = element('div', null, 'total'); item.title = hint + ' ≥ means a partial total.'
item.append(element('span', label), element('strong', totalText(total, format))); dom.summary.append(item)
}
- const scope = element('p', `${(!state.connected || !currentSnapshot()) && !state.paused ? 'Last readings' : 'Shown sessions'} · ≥ partial · — unavailable`, 'summary-scope'); dom.summary.append(scope)
+ const scope = element('p', `${(!state.connected || !currentSnapshot()) && !state.frozen ? 'Last readings' : 'Shown sessions'} · ≥ partial · — unavailable`, 'summary-scope'); dom.summary.append(scope)
dom.shared.hidden = !shared.length; text(dom.sharedTitle, shared.length + ' shared ' + (shared.length === 1 ? 'server' : 'servers') + ' included once')
dom.sharedBody.replaceChildren()
for (const server of shared) {
@@ -204,13 +216,13 @@ function render() {
for (const button of document.querySelectorAll('[data-preset]')) button.setAttribute('aria-pressed', String(button.dataset.preset === state.preset))
const ready = state.snapshot && state.snapshot.status !== 'starting'
dom.empty.hidden = state.shown.length > 0
- text(dom.empty.firstElementChild, !ready ? 'Connecting to your machines…' : state.query ? 'No matching harnesses' : state.filter === 'offline' ? 'No offline sessions' : 'No active harnesses')
- text(dom.empty.lastElementChild, !ready ? 'Active sessions will appear here.' : state.query || state.machine !== 'all' || state.filter !== 'active' ? 'Try another search, machine, or status.' : 'Running sessions appear automatically. Saved sessions are in Open Harness.')
+ text(dom.empty.firstElementChild, !ready ? 'Connecting to your machines…' : state.query ? 'No matching harnesses' : state.filter === 'offline' ? 'No offline sessions' : state.filter === 'stopped' ? 'No stopped sessions' : 'No active harnesses')
+ text(dom.empty.lastElementChild, !ready ? 'Active sessions will appear here.' : state.query || state.machine !== 'all' || state.filter !== 'active' ? 'Try another search, machine, or status.' : 'Running sessions appear automatically. Use the Stopped filter or Open Harness to find saved sessions.')
const active = state.rows.filter(r => isLive(r) && r.online !== false).length
text(dom.count, `${state.shown.length} shown · ${active} active`)
- text(dom.updated, state.paused ? 'Updates paused' : state.receivedAt ? 'Updated ' + age(state.receivedAt) : 'Connecting…')
- text(dom.live, state.paused ? 'Paused' : !state.connected ? 'Reconnecting' : state.snapshot?.status === 'starting' ? 'Connecting' : !currentSnapshot() ? 'Unavailable' : 'Live')
- dom.live.classList.toggle('inactive', state.paused || !state.connected || !currentSnapshot())
+ text(dom.updated, state.frozen ? 'Updates frozen' : state.receivedAt ? 'Updated ' + age(state.receivedAt) : 'Connecting…')
+ text(dom.live, state.frozen ? 'Frozen' : !state.connected ? 'Reconnecting' : state.snapshot?.status === 'starting' ? 'Connecting' : !currentSnapshot() ? 'Unavailable' : 'Live')
+ dom.live.classList.toggle('inactive', state.frozen || !state.connected || !currentSnapshot())
if (ready) summary()
if (dom.inspector.open) renderInspector()
}
@@ -220,7 +232,7 @@ function inspect(id) {
}
function renderInspector() {
const row = state.rows.find(r => r.id === state.inspecting)
- dom.inspectStop.disabled = !canStop(row)
+ dom.inspectStop.disabled = !canStop(row); dom.inspectOpen.disabled = !canOpen(row)
if (!row) { text(dom.inspectContext, 'This harness is no longer active.'); return }
text(dom.inspectTitle, row.name)
text(dom.inspectContext, [engineNames[row.engine] || row.engine, row.machine, ACTIVITY[row.activity]?.[1]].filter(Boolean).join(' · '))
@@ -260,6 +272,8 @@ function reviewStop(id) {
text(dom.stopResult, ''); dom.stopConfirm.disabled = false; dom.stopCancel.disabled = false
dom.stopDialog.showModal()
}
+dom.open.onclick = () => openRow(state.selected)
+dom.inspectOpen.onclick = () => openRow(state.inspecting)
dom.stop.onclick = () => reviewStop(state.selected)
dom.inspect.onclick = () => inspect(state.selected)
dom.inspectStop.onclick = () => reviewStop(state.inspecting)
@@ -277,7 +291,7 @@ dom.stopConfirm.onclick = async () => {
}
state.busy.add(review.id); dom.stopConfirm.disabled = true; dom.stopCancel.disabled = true; text(dom.stopResult, 'Stopping…'); select()
try {
- const reply = await post('/api/act', { verb: 'pause', ids: [review.id], manual: true, expected: [review] })
+ const reply = await post('/api/act', { verb: 'stop', ids: [review.id], manual: true, expected: [review] })
const result = reply.results?.find(r => r.id === review.id)
if (!result?.ok) { text(dom.stopResult, result?.detail || 'Stop was not confirmed. Refresh to check.'); return }
message('Stopped ' + review.name + '. History and files kept.'); dom.stopDialog.close()
@@ -303,12 +317,12 @@ document.addEventListener('keydown', event => {
document.addEventListener('pointerdown', event => { if (!dom.columns.contains(event.target)) dom.columns.open = false })
dom.refresh.onclick = async () => {
dom.refresh.disabled = true
- try { await post('/api/refresh', {}); message(state.paused ? 'New readings ready. Resume updates to display them.' : '') } catch (error) { message(error.message) }
+ try { await post('/api/refresh', {}); message(state.frozen ? 'New readings ready. Live updates to display them.' : '') } catch (error) { message(error.message) }
finally { dom.refresh.disabled = false }
}
-dom.pause.onclick = () => {
- state.paused = !state.paused; text(dom.pause, state.paused ? 'Resume updates' : 'Pause updates'); dom.pause.setAttribute('aria-pressed', String(state.paused))
- if (!state.paused && state.pending) { applySnapshot(state.pending); state.pending = null }
+dom.freeze.onclick = () => {
+ state.frozen = !state.frozen; text(dom.freeze, state.frozen ? 'Live updates' : 'Freeze updates'); dom.freeze.setAttribute('aria-pressed', String(state.frozen))
+ if (!state.frozen && state.pending) { applySnapshot(state.pending); state.pending = null }
render()
}
function applySnapshot(snapshot) {
@@ -334,7 +348,7 @@ function connect() {
try {
const snapshot = JSON.parse(event.data); state.connected = true
if (dom.message.textContent.startsWith('Readings are stale.')) message('')
- if (state.paused) state.pending = snapshot; else applySnapshot(snapshot)
+ if (state.frozen) state.pending = snapshot; else applySnapshot(snapshot)
} catch { message('Could not read the monitor update. Refresh and try again.') }
})
stream.onerror = () => { state.connected = false; message('Connection interrupted. Showing last readings; reconnecting…'); render() }
@@ -343,12 +357,12 @@ function connect() {
document.addEventListener('visibilitychange', () => { if (document.hidden) { stream?.close(); stream = null; state.connected = false } else connect() })
const reducedMotion = matchMedia('(prefers-reduced-motion: reduce)')
setInterval(() => {
- if (document.hidden || reducedMotion.matches || state.paused || !state.connected) return
+ if (document.hidden || reducedMotion.matches || state.frozen || !state.connected) return
const mark = SPINNER[Math.floor(Date.now() / 100) % SPINNER.length]
for (const node of dom.body.querySelectorAll('.working .mark')) text(node, mark)
}, 100)
setInterval(() => {
- if (document.hidden || state.paused || !state.receivedAt) return
+ if (document.hidden || state.frozen || !state.receivedAt) return
if (state.connected && Date.now() - state.receivedAt > 45_000) {
state.connected = false; message('Readings are stale. Showing the last update; refresh to reconnect.')
}
diff --git a/store/agents/harness-monitor/viewer/index.html b/store/agents/harness-monitor/viewer/index.html
index a4c29012f..23afc4ca0 100644
--- a/store/agents/harness-monitor/viewer/index.html
+++ b/store/agents/harness-monitor/viewer/index.html
@@ -11,18 +11,23 @@
<header>
<div class="heading"><h1>Harness Monitor</h1><span id="live-status" class="live">Connecting</span></div>
<div class="search-field"><svg aria-hidden="true" viewBox="0 0 24 24"><circle cx="10.5" cy="10.5" r="6.5"/><path d="m16 16 4 4"/></svg><input id="search" type="search" placeholder="Search harnesses, agents, machines…" aria-label="Search harnesses" autocomplete="off" spellcheck="false"></div>
+ <details id="assistant-info"><summary>Assistant model</summary><div class="menu">
+ <p>New monitors use OpenCode with Muse Spark 1.3 Contributor Free. This limited-time free model allows Meta to use prompts and responses for training. Existing sessions keep their selected agent and model.</p>
+ <p>Use the assistant’s model menu to choose a different model. No prompt is sent when the table opens, and there is no automatic paid fallback.</p>
+ </div></details>
</header>
<nav aria-label="Monitor controls">
<div class="segmented" role="group" aria-label="Column presets"><button data-preset="overview" aria-pressed="true">Overview</button><button data-preset="resources" aria-pressed="false">Resources</button><button data-preset="ai" aria-pressed="false">AI usage</button></div>
<label class="sr-only" for="machine">Machine</label><select id="machine"><option value="all">All machines</option></select>
<label class="sr-only" for="filter">Status</label><select id="filter">
<option value="active">All active</option><option value="working">Working</option><option value="needsInput">Needs you</option>
- <option value="idle">Idle</option><option value="done">Done</option><option value="starting">Starting</option><option value="failed">Failed</option><option value="unknown">Unknown</option><option value="offline">Offline</option><option value="all">Including offline</option>
+ <option value="idle">Idle</option><option value="done">Done</option><option value="starting">Starting</option><option value="failed">Failed</option><option value="unknown">Unknown</option><option value="stopped">Stopped</option><option value="offline">Offline</option><option value="all">Including offline</option>
</select>
<span class="spacer"></span>
- <button id="inspect" disabled title="Inspect selected harness (Enter)">Inspect</button><button id="stop" class="danger" disabled>Stop…</button>
+ <button id="open" disabled>Open</button>
+ <button id="inspect" disabled title="Inspect selected harness (Enter)">Inspect</button><button id="stop" class="danger" disabled>× Stop…</button>
<details id="columns"><summary>Columns</summary><div id="column-options" class="menu"></div></details>
- <button id="pause" title="Freeze the table without pausing any harness">Pause updates</button><button id="refresh" title="Refresh all machines">Refresh</button>
+ <button id="freeze" title="Hold the displayed readings; running work continues">Freeze updates</button><button id="refresh" title="Refresh all machines">Refresh</button>
</nav>
<div id="problems" role="status" hidden></div>
<main id="grid" tabindex="0" aria-label="Active harness sessions. Arrow keys select, Enter inspects, Delete reviews stopping.">
@@ -35,7 +40,7 @@
<dialog id="inspector" aria-labelledby="inspect-title">
<div class="dialog-heading"><h2 id="inspect-title">Harness details</h2><button id="inspect-close" aria-label="Close details">Close</button></div>
<p id="inspect-context" class="muted"></p><div id="inspect-content"></div>
- <div class="dialog-actions"><button id="inspect-stop" class="danger">Stop harness…</button></div>
+ <div class="dialog-actions"><button id="inspect-open" disabled>Open</button><button id="inspect-stop" class="danger">Stop harness…</button></div>
</dialog>
<dialog id="stop-dialog" aria-labelledby="stop-title">
<h2 id="stop-title">Stop harness?</h2><p id="stop-context"></p><p>Its running work will end. Conversation history and workspace files are kept.</p>
diff --git a/store/agents/harness-monitor/viewer/scale.js b/store/agents/harness-monitor/viewer/scale.js
index 98d795d01..96f658241 100644
--- a/store/agents/harness-monitor/viewer/scale.js
+++ b/store/agents/harness-monitor/viewer/scale.js
@@ -15,7 +15,7 @@ const SPAN = Math.log(CEIL / FLOOR)
export const UNITS = { s: 1000, m: 60_000, h: 3_600_000, d: 86_400_000, w: 604_800_000 }
/** Thresholds a person would actually type, and the only values a dragged rule can land on. */
-export const PAUSE_STEPS = ['15m', '30m', '1h', '2h', '4h', '6h', '8h', '12h', '1d', '2d', '3d', '7d']
+export const STOP_STEPS = ['15m', '30m', '1h', '2h', '4h', '6h', '8h', '12h', '1d', '2d', '3d', '7d']
export const HIDE_STEPS = ['1d', '2d', '3d', '5d', '7d', '10d', '14d', '21d', '30d']
export function parseDuration(value) {
diff --git a/store/agents/harness-monitor/viewer/table.js b/store/agents/harness-monitor/viewer/table.js
index a5d21ee6f..46a31e7ac 100644
--- a/store/agents/harness-monitor/viewer/table.js
+++ b/store/agents/harness-monitor/viewer/table.js
@@ -2,7 +2,7 @@
export const ACTIVITY = {
needsInput: ['?', 'Needs you'], failed: ['✗', 'Failed'], working: ['⠋', 'Working'],
starting: ['◌', 'Starting'], done: ['✓', 'Done'], idle: ['', 'Idle'],
- stopped: ['Ⅱ', 'Stopped'], offline: ['⊘', 'Offline'], unknown: ['—', 'Unknown'],
+ stopped: ['×', 'Stopped'], offline: ['⊘', 'Offline'], unknown: ['—', 'Unknown'],
}
export const SPINNER = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']
export const COLUMNS = [
@@ -42,7 +42,7 @@ export const PRESETS = {
export const isLive = row => row.live ?? (['running', 'terminal'].includes(row.state) || (!row.state && !['stopped', 'offline'].includes(row.activity)))
export function visibleRows(rows, { query = '', filter = 'active', machine = 'all', sort = 'rssBytes', direction = -1 } = {}) {
const q = query.trim().toLocaleLowerCase(), rank = Object.keys(ACTIVITY)
- return rows.filter(row => isLive(row) && (machine === 'all' || row.machineId === machine)
+ return rows.filter(row => (isLive(row) || (filter === 'stopped' && row.activity === 'stopped')) && (machine === 'all' || row.machineId === machine)
&& (filter === 'all' || (filter === 'active' ? row.online !== false && row.activity !== 'offline' : row.activity === filter))
&& (!q || [row.name, row.title, row.engine, row.machine, row.project, row.branch, row.model, row.agentId, row.sessionId, row.home]
.some(v => String(v ?? '').toLocaleLowerCase().includes(q))))
diff --git a/tui/src/new_harness.rs b/tui/src/new_harness.rs
index 2821b105b..ee14f021e 100644
--- a/tui/src/new_harness.rs
+++ b/tui/src/new_harness.rs
@@ -411,7 +411,7 @@ pub fn open(app: &mut App, machine: Option<String>, cwd: Option<String>) {
.and_then(|p| app.fleet.agent(&p.machine_id, &p.agent_id));
let engine = saved["engine"]
.as_str()
- .unwrap_or_else(|| current.map(|a| a.engine.as_str()).unwrap_or("codex"))
+ .unwrap_or("opencode")
.to_string();
let what = What {
label: saved["label"]
@@ -2069,6 +2069,10 @@ mod tests {
let Some(Modal::NewHarness(mut f)) = app.modal.take() else {
panic!()
};
+ assert_eq!(f.draft.what.engine, "opencode");
+ assert_eq!(f.draft.permission, "auto");
+ // Exercise remembered per-engine choices independently of the launch default.
+ set_engine(&mut f, "codex");
f.draft.permission = "readOnly".into();
set_engine(&mut f, "claude");
assert_eq!(f.draft.permission, "auto");