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.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
feat: close hidden harnesses from Harness Monitor (#555)
Dee3717f4d1196d
diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.tsindex 3b50858e1..a5254daaa 100644--- a/cli/src/backendSocket.spec.ts+++ b/cli/src/backendSocket.spec.ts@@ -31,6 +31,24 @@ import { STRICT_DOWN_TYPES, encryptDownFrame, encryptRpcResult } from './lib/e2eimport { CloseAgentService } from './lib/closeAgentService.js'describe('safe session close RPC', () => {+ it('seals cleanup previews and passes the open-tab condition to Close', async () => {+ const socket = new BackendSocket('fixture'), frames: any[] = []+ socket.registerLocalClient('local:cleanup', { sendFrame: frame => { frames.push(frame); return true }, sendBinary: () => true })+ socket.cleanupPreview = vi.fn(async () => ({ version: 1, agents: [], kept: 2 }))+ const request = vi.fn(async () => ({ error: 'SESSION_IN_TAB' }))+ socket.closeAgentService = { request, dispose() {} } as unknown as CloseAgentService+ expect(encryptDownFrame('agents_cleanup_preview')).toBe(true)+ expect(encryptRpcResult('agents_cleanup_preview_result')).toBe(true)+ await (socket as any).dispatchDown({ type: 'agents_cleanup_preview', payload: { requestId: 'unsealed' } }, 'remote')+ expect(socket.cleanupPreview).not.toHaveBeenCalled()+ socket.handleLocalFrame('local:cleanup', { type: 'agents_cleanup_preview', payload: { requestId: 'preview' } })+ const target = { agentId: 'a', sessionId: 's', createdAt: '2026-10-01T00:00:00.000Z', mode: 'now', onlyIfHidden: true }+ socket.handleLocalFrame('local:cleanup', { type: 'agent_close', payload: { ...target, requestId: 'close' } })+ await vi.waitFor(() => expect(frames.some(f => f.payload?.requestId === 'close')).toBe(true))+ expect(request).toHaveBeenCalledWith(target)+ expect(frames.find(f => f.payload?.requestId === 'preview').payload).toMatchObject({ version: 1, kept: 2 })+ await socket.stop()+ })it.each([{ activity: 'idle', sessionId: 'close-history' },{ activity: 'working', sessionId: 'close-history' },diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.tsindex 4407aeadc..1ee320e20 100644--- a/cli/src/backendSocket.ts+++ b/cli/src/backendSocket.ts@@ -502,6 +502,7 @@ export class BackendSocket {* process and forgets the session. Keeps recap + agent name. */onDeleteAgent: ((sessionId: string) => void | Promise<void>) | null = nullcloseAgentService: CloseAgentService | null = null+ cleanupPreview: (() => Promise<Record<string, unknown>>) | null = null/** Called on `agent_create` — cli.ts spawns a fresh tmux session running the requested engine in the* requested folder and returns its process-agent. Session metadata may bind later through hooks. */onCreateAgent: ((input: {@@ -3047,6 +3048,13 @@ export class BackendSocket {// Delete an agent: signal its validated engine process and drop it from the list. Idempotent — an already// gone target still acks + re-emits agent_deleted so the web/device converge. E2EE-gated (the// frame arrived decrypted). Keeps the persisted recap + agent name for a later resume.+ case 'agents_cleanup_preview': {+ if (!this.cleanupPreview) { reply(type, requestId, { error: 'UNSUPPORTED' }); return }+ void this.cleanupPreview().then(result => reply(type, requestId, result), error => reply(type, requestId, {+ error: error?.code ?? 'TABS_UNAVAILABLE', detail: error instanceof Error ? error.message : 'Could not check open tabs.',+ }))+ return+ }case 'agent_close': {if (!this.closeAgentService) { reply(type, requestId, { error: 'UNSUPPORTED' }); return }const { agentId, sessionId, createdAt, mode } = payload@@ -3055,7 +3063,8 @@ export class BackendSocket {reply(type, requestId, { error: 'INVALID_CLOSE_REQUEST' }); return}// Saving/exit may take seconds; terminal input and unrelated agents keep flowing.- void this.closeAgentService.request({ agentId, sessionId, createdAt, mode: mode as CloseMode })+ void this.closeAgentService.request({ agentId, sessionId, createdAt, mode: mode as CloseMode,+ ...(payload.onlyIfHidden === true ? { onlyIfHidden: true } : {}) }).then(result => reply(type, requestId, result), () => reply(type, requestId, { error: 'CLOSE_FAILED' }))return}diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex 6c227107c..fcd7ce99f 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -145,6 +145,7 @@ import { forkName, planFork } from './lib/forkAgent.js'import { restoreAgents } from './lib/restoreAgents.js'import { createRetainExitedSession } from './lib/retainExitedSession.js'import { CloseAgentService, inspectCloseActivity } from './lib/closeAgentService.js'+import { OpenTabProtection } from './lib/openTabProtection.js'import { sessionCheckpoints } from './lib/sessionCheckpoint.js'import { repairClaudeCwd } from './lib/cwdRepair.js'import { stoppedAgents } from './lib/stoppedAgents.js'@@ -2281,6 +2282,11 @@ async function runForeground(session: AuthSession | null): Promise<void> {// machine's at once, so this computer's tiles are on screen whichever machine the wheel last landed on// and skipping the recap here would leave them permanently blank./** Agents with a tile open in the desktop window right now. Empty when no window is attached. */+ const cleanupTabs = new OpenTabProtection({+ machineId: () => backend.machineId,+ sessions: () => registry.list(),+ readDesk: () => proxyBackend('GET', '/api/desk'),+ })let openPaneAgents = new Set<string>()/** Whether the window those tiles belong to is actually in front. See onAppPanes. */let appWindowForeground = true@@ -5230,6 +5236,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {void cableRef?.syncSwarms()void cableRef?.syncAgents()},+ onAppTabAgents: (connection, ids) => cleanupTabs.updateWindow(connection, ids),onAppPanes: (agentIds, foreground) => {// ORDER matters here, not just membership. The dial's carousel is built// around these — tiles first, in tile order — so the thumb walks the same@@ -6823,6 +6830,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {backend.onDeleteAgent = stopAgentbackend.closeAgentService = new CloseAgentService({registry,+ openTabs: cleanupTabs,activity: async s => {if (s.sessionId) await watcher.pollSession(s.sessionId)const screen = await captureTerminal(s.agentId, 80)@@ -6835,6 +6843,19 @@ async function runForeground(session: AuthSession | null): Promise<void> {changed: announceSession,})backend.closeAgentService.start()+ backend.cleanupPreview = async () => {+ await cleanupTabs.refresh()+ const sessions = registry.advertised()+ const agents = []+ for (const s of sessions) {+ if (!cleanupTabs.isHidden(s)) continue+ const target = { agentId: s.agentId, sessionId: s.sessionId, createdAt: new Date(s.registeredAt).toISOString() }+ const inspected = await backend.closeAgentService!.request({ ...target, mode: 'inspect' })+ if (inspected.error) continue // A changing session is never added to a reviewed batch.+ agents.push({ ...target, name: projectDisplayName(s), engine: s.engine, activity: inspected.activity ?? 'unknown' })+ }+ return { version: 1, agents, kept: sessions.length - agents.length }+ }backend.onResumeAgent = createResumeAgentService({registry, stoppedAgents, tmuxBackend, restartJobs, stopJobs, pinnedControls,diff --git a/cli/src/lib/closeAgentService.spec.ts b/cli/src/lib/closeAgentService.spec.tsindex 2fdf29210..167dbae02 100644--- a/cli/src/lib/closeAgentService.spec.ts+++ b/cli/src/lib/closeAgentService.spec.ts@@ -64,6 +64,34 @@ it('checkpoint failure retains the session and reports the failure', async () =>expect(await service.request(request())).toMatchObject({ error: 'HISTORY_NOT_SAVED', detail: 'Disk full' })expect(registry.byAgent(row.agentId)).toBe(row)})+it('cleanup requires open-tab support and checks again after history is saved', async () => {+ const close = { ...request('now'), onlyIfHidden: true }+ expect(await service.request(close)).toMatchObject({ error: 'UNSUPPORTED' })+ deps.openTabs = { isHidden: () => true, assertHidden: vi.fn().mockResolvedValueOnce(undefined)+ .mockRejectedValueOnce(Object.assign(new Error('Now in a tab'), { code: 'SESSION_IN_TAB' })) }+ expect(await service.request(close)).toMatchObject({ error: 'SESSION_IN_TAB' })+ expect(deps.checkpoint).toHaveBeenCalledOnce()+ expect(registry.byAgent(row.agentId)).toBe(row)+})+it('a new local tab cancels cleanup at the final process fence', async () => {+ let hidden = true+ deps.openTabs = { isHidden: () => hidden, assertHidden: vi.fn(async () => {}) }+ vi.mocked(deps.stop).mockImplementation(async (_id, options) => {+ await options.beforeStop?.(row)+ hidden = false+ expect(options.current?.()).toBe(false)+ throw new Error('Opened while closing')+ })+ expect(await service.request({ ...request('now'), onlyIfHidden: true })).toMatchObject({ error: 'CLOSE_FAILED' })+ expect(registry.byAgent(row.agentId)).toBe(row)+})+it('an explicitly reviewed cleanup closes unknown activity through the history checkpoint', async () => {+ deps.openTabs = { isHidden: () => true, assertHidden: vi.fn(async () => {}) }+ vi.mocked(deps.activity).mockResolvedValue('unknown')+ expect(await service.request({ ...request('now'), onlyIfHidden: true })).toEqual({ closed: true })+ expect(deps.checkpoint).toHaveBeenCalledOnce()+ expect(deps.openTabs.assertHidden).toHaveBeenCalledTimes(2)+})it('joins repeated clicks and cancels a pending close when reopened during its backup', async () => {let finish!: () => voidvi.mocked(deps.checkpoint).mockImplementation(() => new Promise(resolve => { finish = resolve }))diff --git a/cli/src/lib/closeAgentService.ts b/cli/src/lib/closeAgentService.tsindex b13851e68..1bd5330cf 100644--- a/cli/src/lib/closeAgentService.ts+++ b/cli/src/lib/closeAgentService.ts@@ -17,7 +17,7 @@ export type AgentClosePlan = {state: 'waiting' | 'failed'detail?: string}-export type AgentCloseRequest = { agentId: string; sessionId: string; createdAt: string; mode: CloseMode }+export type AgentCloseRequest = { agentId: string; sessionId: string; createdAt: string; mode: CloseMode; onlyIfHidden?: boolean }export type AgentCloseResult = { closed?: true; deferred?: true; cancelled?: true; error?: string; detail?: string; activity?: CloseActivity }type CloseSession = Pick<RegisteredSession, 'engine' | 'sessionId' | 'transcriptPath' | 'launch' | 'resumeOnly'>@@ -58,6 +58,7 @@ export interface CloseAgentServiceDeps {checkpoint(s: RegisteredSession, phase: 'before' | 'after'): Promise<void>stop(agentId: string, options: StopAgentOptions): Promise<void>changed(s: RegisteredSession): void+ openTabs?: { assertHidden(s: RegisteredSession): Promise<void>; isHidden(s: RegisteredSession): boolean }now?: () => number}@@ -109,9 +110,16 @@ export class CloseAgentService {const current = () => {const s = this.deps.registry.byAgent(request.agentId)return !this.disposed && (this.revisions.get(request.agentId) ?? 0) === revision- && s && identity(s) === target ? s : undefined+ && s && identity(s) === target+ && (!request.onlyIfHidden || this.deps.openTabs?.isHidden(s)) ? s : undefined}try {+ if (request.onlyIfHidden) {+ if (!this.deps.openTabs || request.mode !== 'now') return { error: 'UNSUPPORTED' }+ const s = this.deps.registry.byAgent(request.agentId)+ if (!s) return { error: 'AGENT_CHANGED' }+ await this.deps.openTabs.assertHidden(s)+ }const s = current()if (!s) return { error: 'AGENT_CHANGED' }const observed = await this.deps.activity(s)@@ -135,6 +143,7 @@ export class CloseAgentService {beforeStop: async () => {const latest = current()if (!latest) throw new Error('The session changed while saving. Please try again.')+ if (request.onlyIfHidden) await this.deps.openTabs!.assertHidden(latest)if (request.mode !== 'now') {const activity = await this.deps.activity(latest)if (activity !== 'idle') throw new CloseRefused(activity)diff --git a/cli/src/lib/e2ee/applicationFrames.ts b/cli/src/lib/e2ee/applicationFrames.tsindex 910c9f1e4..a924b7f8b 100644--- a/cli/src/lib/e2ee/applicationFrames.ts+++ b/cli/src/lib/e2ee/applicationFrames.ts@@ -18,7 +18,7 @@ const FLEET_REQUESTS = new Set(['grid_fleet_capabilities', 'grid_fleet_run', 'gr'grid_fleet_models_list', 'grid_fleet_model_download', 'grid_fleet_model_start', 'grid_fleet_model_stop'])const FLEET_RESULTS = new Set([...FLEET_REQUESTS].map(type => `${type}_result`))// `group_sync`: the trust-group roster exchange (groupSyncer.ts) — keys, so always sealed.-const MACHINE_REQUESTS = new Set(['agent_close', 'git_project_info', 'git_pull_request', 'machine_resources', 'api_connections', 'group_sync', 'phone_pair', 'viewer_surface', 'orchestrator', ...OWNER_COMMAND_TYPES])+const MACHINE_REQUESTS = new Set(['agents_cleanup_preview', 'agent_close', 'git_project_info', 'git_pull_request', 'machine_resources', 'api_connections', 'group_sync', 'phone_pair', 'viewer_surface', 'orchestrator', ...OWNER_COMMAND_TYPES])const MACHINE_RESULTS = new Set([...MACHINE_REQUESTS].map(type => `${type}_result`))/** The pair brain, machine to machine (daemons/BRAIN.md). A watch carries question text and recaps; the* writes (answer, send, stop, start, pause, resume) act on a harness through the owning machine's floordiff --git a/cli/src/lib/openTabProtection.spec.ts b/cli/src/lib/openTabProtection.spec.tsnew file mode 100644index 000000000..44fbdcfee--- /dev/null+++ b/cli/src/lib/openTabProtection.spec.ts@@ -0,0 +1,43 @@+import { expect, it } from 'vitest'+import { OpenTabProtection } from './openTabProtection.js'+import type { RegisteredSession } from './registry.js'++const session = (agentId: string, paneId = `%${agentId}`) => ({ agentId, runtimes: [{ backend: 'tmux', paneId }] }) as RegisteredSession+function fixture(tabs: unknown[] = []) {+ const sessions = [session('foreground'), session('background'), session('companion'), session('hidden'), session('alias', '%background')]+ let reply = { status: 200, body: { success: true, data: { revision: 1, tabs } } }+ const guard = new OpenTabProtection({ machineId: () => 'here', sessions: () => sessions, readDesk: async () => reply })+ return { guard, sessions, setReply: (value: any) => { reply = value } }+}+it('keeps foreground, background, local utility tabs and aliases of their terminal', async () => {+ const { guard, sessions } = fixture([{ panes: [{ machineId: 'here', agentId: 'foreground' }] },+ { panes: [{ machineId: 'here', agentId: 'background' }, { machineId: 'elsewhere', agentId: 'hidden' }] }])+ guard.updateWindow('window', ['companion'])+ await guard.refresh()+ expect(sessions.filter(s => guard.isHidden(s)).map(s => s.agentId)).toEqual(['hidden'])+})+it('keeps another window’s tabs when one window disconnects', async () => {+ const { guard } = fixture()+ guard.updateWindow('one', ['companion']); guard.updateWindow('two', ['companion'])+ guard.updateWindow('one', null)+ await expect(guard.assertHidden(session('companion'))).rejects.toMatchObject({ code: 'SESSION_IN_TAB' })+ guard.updateWindow('two', null)+ await expect(guard.assertHidden(session('companion'))).resolves.toBeUndefined()+})+it.each([+ { status: 503, body: {} },+ { status: 200, body: { success: true, data: {} } },+ { status: 200, body: { success: true, data: { revision: 2, tabs: [{ panes: [{}] }] } } },+])('refuses cleanup when the shared workspace cannot be read completely', async reply => {+ const { guard, setReply } = fixture(); setReply(reply)+ await expect(guard.assertHidden(session('hidden'))).rejects.toMatchObject({ code: 'TABS_UNAVAILABLE' })+})+it('rechecks shared tabs and rejects late reads from an older revision', async () => {+ const { guard, setReply } = fixture()+ await guard.assertHidden(session('hidden'))+ setReply({ status: 200, body: { success: true, data: { revision: 2, tabs: [{ panes: [{ machineId: 'here', agentId: 'hidden' }] }] } } })+ await expect(guard.assertHidden(session('hidden'))).rejects.toMatchObject({ code: 'SESSION_IN_TAB' })+ setReply({ status: 200, body: { success: true, data: { revision: 1, tabs: [] } } })+ await expect(guard.refresh()).rejects.toMatchObject({ code: 'TABS_UNAVAILABLE' })+ expect(guard.isHidden(session('hidden'))).toBe(false)+})diff --git a/cli/src/lib/openTabProtection.ts b/cli/src/lib/openTabProtection.tsnew file mode 100644index 000000000..a5f8a1199--- /dev/null+++ b/cli/src/lib/openTabProtection.ts@@ -0,0 +1,58 @@+/** Cleanup keeps every open tab, including background tabs and local utility panes. */+import type { RegisteredSession } from './registry.js'+import { terminalRouteKey } from './terminalRuntime.js'++export class OpenTabError extends Error {+ constructor(readonly code: string, message: string) { super(message) }+}++export class OpenTabProtection {+ private readonly windows = new Map<string, Set<string>>()+ private shared = new Set<string>()+ private revision = -1+ constructor(private readonly deps: {+ machineId(): string+ sessions(): RegisteredSession[]+ readDesk(): Promise<{ status: number; body: Record<string, unknown> }>+ }) {}++ /** Each window owns its roster. Closing one window must not clear another one's tabs. */+ updateWindow(connection: string, ids: string[] | null): void {+ if (ids === null) this.windows.delete(connection)+ else this.windows.set(connection, new Set(ids))+ }++ async refresh(): Promise<void> {+ const unavailable = () => new OpenTabError('TABS_UNAVAILABLE', 'Could not check your open tabs. Nothing was closed.')+ const reply = await this.deps.readDesk()+ const data = reply.body.data as { revision?: unknown; tabs?: unknown } | undefined+ if (reply.status !== 200 || reply.body.success !== true || !data || !Array.isArray(data.tabs)+ || typeof data.revision !== 'number' || !Number.isSafeInteger(data.revision)) throw unavailable()+ const ids = new Set<string>()+ for (const tab of data.tabs) {+ if (!tab || !Array.isArray(tab.panes)) throw unavailable()+ for (const pane of tab.panes) {+ if (!pane || typeof pane.machineId !== 'string' || !pane.machineId+ || typeof pane.agentId !== 'string' || !pane.agentId) throw unavailable()+ if (pane.machineId === this.deps.machineId()) ids.add(pane.agentId)+ }+ }+ // Concurrent preview/close reads can finish out of order.+ if (data.revision < this.revision) throw unavailable()+ this.shared = ids+ this.revision = data.revision+ }++ isHidden(session: RegisteredSession): boolean {+ const ids = new Set([...this.shared, ...[...this.windows.values()].flatMap(ids => [...ids])])+ if (ids.has(session.agentId)) return false+ // Two registry aliases can describe one terminal. Keep the entire placement if either is open.+ const routes = new Set(this.deps.sessions().filter(s => ids.has(s.agentId)).flatMap(s => s.runtimes.map(terminalRouteKey)))+ return !session.runtimes.some(r => routes.has(terminalRouteKey(r)))+ }++ async assertHidden(session: RegisteredSession): Promise<void> {+ await this.refresh()+ if (!this.isHidden(session)) throw new OpenTabError('SESSION_IN_TAB', 'This harness is in an open tab. Kept open.')+ }+}diff --git a/cli/src/localWsServer.spec.ts b/cli/src/localWsServer.spec.tsindex 797740d98..701bf5d29 100644--- a/cli/src/localWsServer.spec.ts+++ b/cli/src/localWsServer.spec.ts@@ -359,11 +359,13 @@ describe('local CLI WebSocket', () => {it('takes the window\'s swarms, drops what is not a swarm, and forgets them on close', async () => {const backend = new FakeBackend()const seen: unknown[] = []+ const tabs = vi.fn()server = http.createServer((_req, res) => { res.statusCode = 404; res.end() })local = attachLocalWsServer(server, {machineId,backend,onAppSwarms: (swarms) => seen.push(swarms),+ onAppTabAgents: tabs,})await new Promise<void>((resolve) => server!.listen(0, '127.0.0.1', resolve))const url = `ws://127.0.0.1:${(server.address() as AddressInfo).port}/api/local-ws`@@ -398,10 +400,13 @@ describe('local CLI WebSocket', () => {// Like app_panes: a fact about this desk, so the machine never sees it.expect(backend.frames.map((frame) => frame.type)).toEqual([])+ expect(tabs).toHaveBeenCalledExactlyOnceWith(backend.connId, ['a1', 'a2'])+ws.close()// The window is gone, and so are its tabs.await vi.waitFor(() => expect(seen).toHaveLength(2))expect(seen[1]).toBeNull()+ expect(tabs).toHaveBeenLastCalledWith(backend.connId, null)})it('follows an explicit app_focus, and keeps it off the wire', async () => {diff --git a/cli/src/localWsServer.ts b/cli/src/localWsServer.tsindex d6863c008..5d370b89e 100644--- a/cli/src/localWsServer.ts+++ b/cli/src/localWsServer.ts@@ -78,6 +78,8 @@ export interface LocalWsServerOptions {* Consumed like app_panes: a fact about this desk, never forwarded to the machine.*/onAppSwarms?: (swarms: AppSwarms | null) => void+ /** Tab membership for cleanup, scoped to the reporting window, including local utility tabs. */+ onAppTabAgents?: (connection: string, agentIds: string[] | null) => void/*** The window asked WHICH AGENT a typed task belongs to (⌘K). Answers, and sends NOTHING.*@@ -567,7 +569,11 @@ export function attachLocalWsServer(server: http.Server, options: LocalWsServerOif (!isBinary && options.onAppSwarms) {if (parsed?.type === 'app_swarms') {const swarms = appSwarmsFrom(parsed.payload)- if (swarms) { sentSwarms = true; options.onAppSwarms(swarms) }+ if (swarms) {+ sentSwarms = true+ options.onAppSwarms(swarms)+ options.onAppTabAgents?.(connId, swarms.swarms.flatMap(s => s.agentIds))+ }return}}@@ -762,6 +768,7 @@ export function attachLocalWsServer(server: http.Server, options: LocalWsServerO// exactly backwards, and permanently.if (sentPanes) options.onAppPanes?.([], false)if (sentSwarms) options.onAppSwarms?.(null)+ if (sentSwarms) options.onAppTabAgents?.(connId, null)if (relay) { relay.detach(); relay = null }else if (selected) void options.backend.unregisterLocalClient(connId)selected = falsediff --git a/store/agents/harness-monitor/AGENTS.md b/store/agents/harness-monitor/AGENTS.mdindex 34992cadc..4b80968f5 100644--- a/store/agents/harness-monitor/AGENTS.md+++ b/store/agents/harness-monitor/AGENTS.md@@ -13,13 +13,17 @@ write a resume command into tmux, or reconstruct a saved launch yourself.- `hps resume <ref>` asks the owning daemon to restore it. Respect `resumeMode`: some engines reopen aconversation, some start a fresh one, and terminals reopen a shell.- `hps pause --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`.- `--machines` includes linked machines for reads and actions. Use the full composite machine/agent IDin JSON output when a name, pane or agent ID is ambiguous. Never assume IDs are global.For changes to more than two sessions, show the dry run with reasons and obtain the person's approval-before applying. Never force cleanup of Working, Needs you, pinned or unknown-activity sessions.-`--force` is for the person to request explicitly. Never change rules simply because the table is open.+before applying, unless the person has already authorized those targets. Explicit `hps cleanup` may+include working or unknown activity only when the person asks to close harnesses outside their tabs.+Never bypass its tab or history guards. Policy cleanup keeps Working, Needs you, pinned and unknown+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.diff --git a/store/agents/harness-monitor/README.md b/store/agents/harness-monitor/README.mdindex 505933764..2c559e751 100644--- a/store/agents/harness-monitor/README.md+++ b/store/agents/harness-monitor/README.md@@ -20,7 +20,17 @@ CPU uses the daemon's shared process sampler, measuring interval use; multiple cexceed 100%. RAM is subtree resident memory and can double-count shared pages. Token counts are theowning daemon's conversation ledger. Last active is conversation activity, never file mtime.-**Cleanup…** previews the current policy and requires an explicit apply. Working, waiting, pinned,+**Clean up…** defaults to harnesses outside every open tab on your linked machines. **Cancel** keeps+them running; **Close** saves history and closes their processes and terminals. Background tabs and+local utility tabs, including Companions, stay open. Working and unknown activity appear in the preview:+closing them ends unfinished work. Each owning machine checks tabs and session identity again before+closing. Offline machines, older Harness versions and save failures are reported separately. Reopen+saved sessions through Open Harness. This requires an updated Harness CLI on each machine.++`hps cleanup --machines --json` previews the same action; `hps cleanup --machines --apply --json`+closes it. Without `--machines`, it checks this machine only. Nothing runs automatically.++**Clean up… → By cleanup rules** previews the current policy and requires an explicit apply. Working, waiting, pinned,offline and unknown-activity sessions are protected and rechecked at execution. There is no automaticcleanup timer. The same tools are available to the assistant as `$HPS_CLI` (`toolchain/hps --help`).Rules/pins remain in `~/.config/harness/policy.jsonc`; receipts are under `~/.harness/monitor/`.diff --git a/store/agents/harness-monitor/lib/bridge.mjs b/store/agents/harness-monitor/lib/bridge.mjsindex b2c66f617..53618ab17 100644--- a/store/agents/harness-monitor/lib/bridge.mjs+++ b/store/agents/harness-monitor/lib/bridge.mjs@@ -99,7 +99,7 @@ function openSession(machineId, { env, timeoutMs, WebSocketImpl, forceReconnectconst deadline = setTimeout(() => { const m = 'The Harness daemon did not answer on the local bridge. Is Harness running?'; fail(m); reject(new Error(m)) }, Math.min(timeoutMs, 15_000))// `forceReconnect` tells Harness the session it kept for this machine is dead (the machine's own// Harness restarted under it) and must be dialled fresh rather than handed back once more.- socket.addEventListener('open', () => socket.send(JSON.stringify({ type: 'machine_select', payload: { machineId, localProtocolVersion: 1, relayIsolation: true, ...(forceReconnect ? { forceReconnect: true } : {}) } })))+ socket.addEventListener('open', () => socket.send(JSON.stringify({ type: 'machine_select', payload: { machineId, localProtocolVersion: 1, relayIsolation: true, tool: true, ...(forceReconnect ? { forceReconnect: true } : {}) } })))socket.addEventListener('error', () => { clearTimeout(deadline); const m = 'Could not open the local Harness bridge. Start Harness and try again.'; fail(m); reject(new Error(m)) })socket.addEventListener('close', (event) => {clearTimeout(deadline)diff --git a/store/agents/harness-monitor/lib/cleanup.mjs b/store/agents/harness-monitor/lib/cleanup.mjsnew file mode 100644index 000000000..1d5fa1f57--- /dev/null+++ b/store/agents/harness-monitor/lib/cleanup.mjs@@ -0,0 +1,57 @@+/** Explicit cleanup uses each owning daemon's open-tab guard and durable Close path. */+import { randomUUID } from 'node:crypto'+import { machinesReport, request } from './bridge.mjs'++export async function previewCleanup({ includeRemote = true, reportMachines = machinesReport, rpc = request } = {}) {+ const report = await reportMachines()+ if (report.error) throw new Error(report.error)+ const answers = await Promise.all(report.machines.filter(m => includeRemote || m.current).map(async machine => {+ if (!machine.online) return { problem: { machine: machine.name, error: 'Offline. Kept unchanged.' } }+ try {+ const reply = await rpc(machine.machineId, 'agents_cleanup_preview', {}, { timeoutMs: 60_000 })+ if (reply.version !== 1 || !Array.isArray(reply.agents)) throw new Error('Update Harness on this machine to use cleanup.')+ const rows = reply.agents.map(agent => {+ if (!agent || typeof agent.agentId !== 'string' || !agent.agentId || typeof agent.sessionId !== 'string'+ || typeof agent.createdAt !== 'string' || !Number.isFinite(Date.parse(agent.createdAt))) throw new Error('Could not read this machine’s cleanup preview.')+ return { id: JSON.stringify([machine.machineId, agent.agentId]), machineId: machine.machineId, machine: machine.name,+ agentId: agent.agentId, sessionId: agent.sessionId, createdAt: agent.createdAt,+ name: String(agent.name || agent.agentId), activity: agent.activity ?? 'unknown' }+ })+ return { rows, kept: Number.isSafeInteger(reply.kept) && reply.kept >= 0 ? reply.kept : 0 }+ } catch (error) { return { problem: { machine: machine.name,+ error: error.code === 'UNSUPPORTED' ? 'Update Harness on this machine to use cleanup.' : error.message } } }+ }))+ return { rows: answers.flatMap(a => a.rows ?? []), kept: answers.reduce((n, a) => n + (a.kept ?? 0), 0),+ problems: answers.flatMap(a => a.problem ? [a.problem] : []) }+}++export async function closeHidden(row, { rpc = request } = {}) {+ const receipt = { id: row.id, name: row.name, machine: row.machine, action: 'close' }+ try {+ const reply = await rpc(row.machineId, 'agent_close', { agentId: row.agentId, sessionId: row.sessionId,+ createdAt: row.createdAt, mode: 'now', onlyIfHidden: true }, { timeoutMs: 60_000 })+ return { ...receipt, ok: reply.closed === true,+ detail: reply.closed === true ? 'Closed. History kept.' : reply.detail || reply.error || 'Close was not confirmed. Refresh to check.' }+ } catch (error) { return { ...receipt, ok: false, detail: error.message } }+}++/** Only server-held preview targets can be submitted. Repeated clicks read the same result. */+export function cleanupReviews({ preview = previewCleanup, close = closeHidden, now = Date.now } = {}) {+ const reviews = new Map()+ return {+ async preview() {+ const plan = await preview()+ const reviewId = randomUUID()+ for (const [id, review] of reviews) if (now() - review.at > 30 * 60_000) reviews.delete(id)+ if (reviews.size >= 10) reviews.delete(reviews.keys().next().value)+ reviews.set(reviewId, { at: now(), rows: new Map(plan.rows.map(row => [row.id, row])), results: new Map() })+ return { ...plan, reviewId }+ },+ async close(reviewId, id) {+ const review = reviews.get(reviewId), row = review?.rows.get(id)+ if (!row || now() - review.at > 30 * 60_000) throw Object.assign(new Error('Refresh the cleanup preview and try again.'), { code: 'INVALID_REVIEW' })+ if (!review.results.has(id)) review.results.set(id, Promise.resolve().then(() => close(row)))+ return review.results.get(id)+ },+ }+}diff --git a/store/agents/harness-monitor/skills/fleet-operations/SKILL.md b/store/agents/harness-monitor/skills/fleet-operations/SKILL.mdindex 4f449dc20..bf9f64863 100644--- a/store/agents/harness-monitor/skills/fleet-operations/SKILL.md+++ b/store/agents/harness-monitor/skills/fleet-operations/SKILL.md@@ -19,9 +19,11 @@ are ambiguous. Missing measurements are unknown; an offline machine is not a sto- `hps resume <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 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.-For more than two sessions, show the dry run with reasons and obtain approval before applying 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 muststill correspond to the person's request. Never use `--force` unless explicitly requested for thosesessions. The row's × button is an explicit single-session stop and may interrupt work in progress.@@ -31,11 +33,18 @@ Do not signal PIDs, reconstruct engine flags, respawn a tmux pane, or edit the rread the original resume receipt; do not invent a new operation to compensate. Explain refusals anduncertain outcomes. Receipts are recorded in `~/.harness/monitor/log.jsonl`.+## Close harnesses outside tabs++Use `hps cleanup` only when the person asks to close harnesses outside their tabs. Review the names+and activity first: it includes working and unknown activity and can end unfinished work. The owning+daemon rechecks open tabs and session identity and saves history before closing. Never bypass those+guards. Report offline machines, unsupported versions, save failures and unconfirmed closes.+## Cleanup rules[references/policy.md](references/policy.md) explains the proposal rules. They never run automatically.Working sessions, questions, pins, unavailable controls and unknown activity are protected by default.-Attachment is not currently reported; do not promise protection merely because a pane is visible.+These policy rules do not use the open-tab guard of the separate `hps cleanup` command.Rules and pins live in `~/.config/harness/policy.jsonc`. Preserve comments and simulate a proposedchange before applying it. Do not change thresholds to make a refused cleanup succeed.diff --git a/store/agents/harness-monitor/test/cleanup.test.mjs b/store/agents/harness-monitor/test/cleanup.test.mjsnew file mode 100644index 000000000..cd6ef00c7--- /dev/null+++ b/store/agents/harness-monitor/test/cleanup.test.mjs@@ -0,0 +1,46 @@+import assert from 'node:assert/strict'+import { test } from 'node:test'+import { cleanupReviews, closeHidden, previewCleanup } from '../lib/cleanup.mjs'++const agent = { agentId: 'a', sessionId: 'conversation', createdAt: '2026-09-01T00:00:00.000Z', name: 'Same name', activity: 'unknown' }+const reportMachines = async () => ({ machines: [{ machineId: 'one', name: 'Office', current: true, online: true },+ { machineId: 'two', name: 'Laptop', online: true }, { machineId: 'offline', name: 'Offline', online: false }] })+test('preview only reads; identical IDs on different machines stay distinct, and offline machines are reported', async () => {+ const calls = []+ const plan = await previewCleanup({ reportMachines, rpc: async (machine, type) => {+ calls.push([machine, type]); return { version: 1, agents: [agent], kept: 3 }+ } })+ assert.deepEqual(calls, [['one', 'agents_cleanup_preview'], ['two', 'agents_cleanup_preview']])+ assert.equal(plan.rows.length, 2); assert.notEqual(plan.rows[0].id, plan.rows[1].id)+ assert.equal(plan.kept, 6); assert.match(plan.problems[0].error, /Offline/)+})+test('unsupported, unreadable and malformed previews never become close targets', async () => {+ for (const reply of [{}, { version: 1, agents: [{ ...agent, createdAt: null }] }]) {+ const plan = await previewCleanup({ reportMachines, rpc: async () => reply })+ assert.deepEqual(plan.rows, []); assert.equal(plan.problems.length, 3)+ }+ await assert.rejects(previewCleanup({ reportMachines: async () => ({ error: 'Unavailable' }) }), /Unavailable/)+})+test('close carries the reviewed conversation and requires the owner’s open-tab guard', async () => {+ const row = { ...agent, id: 'one/a', machineId: 'one' }, calls = []+ const result = await closeHidden(row, { rpc: async (...args) => { calls.push(args); return { closed: true } } })+ assert.equal(result.ok, true)+ assert.deepEqual(calls[0].slice(0, 3), ['one', 'agent_close', { agentId: 'a', sessionId: 'conversation',+ createdAt: agent.createdAt, mode: 'now', onlyIfHidden: true }])+})+test('a lost close reply is uncertain and is never automatically retried', async () => {+ let calls = 0+ const result = await closeHidden({ ...agent, machineId: 'one' }, { rpc: async () => { calls++; throw new Error('Connection lost') } })+ assert.equal(calls, 1); assert.equal(result.ok, false); assert.match(result.detail, /Connection lost/)+})+test('only reviewed rows can close; duplicate clicks join, and expired reviews require a new preview', async () => {+ let now = 0, calls = 0+ const reviews = cleanupReviews({ now: () => now, preview: async () => ({ rows: [{ ...agent, id: 'reviewed' }] }),+ close: async row => { calls++; return { ok: true, id: row.id } } })+ const plan = await reviews.preview()+ await assert.rejects(reviews.close(plan.reviewId, 'forged'), /Refresh/)+ const results = await Promise.all([reviews.close(plan.reviewId, 'reviewed'), reviews.close(plan.reviewId, 'reviewed')])+ assert.equal(calls, 1); assert.deepEqual(results[0], results[1])+ now = 31 * 60_000+ await assert.rejects(reviews.close(plan.reviewId, 'reviewed'), /Refresh/)+})diff --git a/store/agents/harness-monitor/test/server.test.mjs b/store/agents/harness-monitor/test/server.test.mjsindex b45c0b330..68085062a 100644--- a/store/agents/harness-monitor/test/server.test.mjs+++ b/store/agents/harness-monitor/test/server.test.mjs@@ -6,6 +6,7 @@ import { tmpdir } from 'node:os'import { join } from 'node:path'import { DAY, HOUR, row } from './fixtures.mjs'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 = {}) {@@ -83,6 +84,25 @@ test('a write without the token does nothing', async (t) => {assert.deepEqual(done, [])})+test('cleanup requires the page token, a reviewed target, and retains per-row results', async t => {+ let previews = 0, closed = 0+ const cleanup = cleanupReviews({ preview: async () => {+ previews++; return { rows: [{ id: 'hidden', name: 'Hidden session' }], kept: 2, problems: [] }+ }, close: async row => { closed++; return { ...row, ok: true, action: 'close', detail: 'Closed. History kept.' } } })+ const { viewer, base } = await serve(undefined, { cleanup })+ t.after(() => viewer.close())+ assert.equal((await fetch(`${base}/api/cleanup/preview`, { method: 'POST', body: '{}' })).status, 403)+ assert.equal(previews, 0)+ const plan = await post(base, viewer.token, '/api/cleanup/preview', {})+ assert.equal(closed, 0)+ const wrong = await post(base, viewer.token, '/api/cleanup/close', { reviewId: plan.reviewId, id: 'visible' })+ assert.match(wrong.error, /Refresh/); assert.equal(closed, 0)+ const result = await post(base, viewer.token, '/api/cleanup/close', { reviewId: plan.reviewId, id: 'hidden' })+ assert.equal(result.ok, true)+ await post(base, viewer.token, '/api/cleanup/close', { reviewId: plan.reviewId, id: 'hidden' })+ assert.equal(closed, 1)+})+test('a verb Harness Monitor does not have is refused by name', async (t) => {const { viewer, base, done } = await serve()t.after(() => viewer.close())diff --git a/store/agents/harness-monitor/toolchain/hps.mjs b/store/agents/harness-monitor/toolchain/hps.mjsindex d50b4d767..3b33017b8 100755--- a/store/agents/harness-monitor/toolchain/hps.mjs+++ b/store/agents/harness-monitor/toolchain/hps.mjs@@ -7,12 +7,13 @@* developer already has muscle memory for — `ls`, `pause`, `resume`, `gc`, `log` — and every one of them* takes `--json` so the agent beside it never has to parse a table meant for eyes.*- * Nothing here deletes a harness. See lib/actions.mjs for why that boundary is the point.+ * Explicit cleanup closes hidden harnesses through the owning daemon and preserves history.*/import { homedir } from 'node:os'import { resolve } from 'node:path'import { pause, resume } 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'import { capture, panes } from '../lib/panes.mjs'@@ -39,6 +40,8 @@ const USAGE = `hps — sessions on this machine, running or stoppedhps pause --idle 8h one threshold instead of all of themhps resume --paused everything that is paused, back in one linehps 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.@@ -121,7 +124,7 @@ function pick(refs, rows) {// 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' }// `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', 'observe', 'help', ...Object.keys(ALIASES)])+const COMMANDS = new Set(['ls', 'show', 'pause', 'resume', '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,@@ -143,6 +146,32 @@ async function main() {if ((flags.policy || flags.idle || flags['over-ceiling'] || flags.paused) && !flags.apply) flags['dry-run'] = trueif (flags.help || command === 'help' || command === '--help') { out(USAGE); return }+ if (command === 'cleanup') {+ try {+ const plan = await previewCleanup({ includeRemote: Boolean(flags.machines) })+ const results = []+ if (flags.apply === true && !flags['dry-run']) {+ for (const row of plan.rows) {+ const result = await closeHidden(row)+ results.push(result)+ await record(WORKSPACE, { ...result, by: 'cli' })+ }+ }+ const applied = flags.apply === true && !flags['dry-run']+ if (flags.json) out(JSON.stringify({ ...plan, dryRun: !applied, results }, null, 2))+ else {+ for (const row of plan.rows) out(`${row.machine} · ${row.name} · ${row.activity}`)+ for (const problem of plan.problems) out(`${problem.machine}: ${problem.error}`)+ if (applied) {+ for (const result of results) out(`${result.machine} · ${result.name}: ${result.detail}`)+ out(`${results.filter(r => r.ok).length} closed. History kept.`)+ } else out(`${plan.rows.length} harnesses outside your tabs. --apply closes them, ends unfinished work, and keeps history.`)+ }+ if (plan.problems.length || results.some(r => !r.ok)) process.exitCode = 1+ } finally { closeBridges() }+ return+ }+if (command === 'ls' || command === 'ps') {const watch = flags.watch !== undefinedconst every = Math.max(1, Number(flags.watch) || Number(flags.every) || 3) * 1000diff --git a/store/agents/harness-monitor/viewer.mjs b/store/agents/harness-monitor/viewer.mjsindex 07479176f..877c7d1a3 100644--- a/store/agents/harness-monitor/viewer.mjs+++ b/store/agents/harness-monitor/viewer.mjs@@ -7,6 +7,7 @@ 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 { cleanupReviews } from './lib/cleanup.mjs'import { closeBridges } from './lib/bridge.mjs'import { collect as collectFleet, summarize, tilde } from './lib/inventory.mjs'import { DEFAULT_POLICY, decide, normalizePolicy } from './lib/policy.mjs'@@ -15,7 +16,7 @@ import { pin, readLog, readState, record, savePolicyValues, writeState, writeVerconst PACKAGE = dirname(fileURLToPath(import.meta.url))const VERBS = new Set(['pause', 'resume', 'pin', 'unpin'])-export function createViewer({ workspace, port = 0, intervalMs = 4000, remoteIntervalMs = 15_000, now = () => Date.now(), collect = collectFleet, verbs = { pause, resume } }) {+export function createViewer({ workspace, port = 0, intervalMs = 4000, remoteIntervalMs = 15_000, now = () => Date.now(), collect = collectFleet, verbs = { pause, resume }, cleanup = cleanupReviews() }) {const token = randomBytes(24).toString('base64url')const clients = new Set()const cache = new Map()@@ -181,6 +182,18 @@ export function createViewer({ workspace, port = 0, intervalMs = 4000, remoteIntfor await (const chunk of req) { body += chunk; if (body.length > 64 * 1024) { json(res, 413, { error: 'Too large.' }); return } }let payload; try { payload = JSON.parse(body || '{}') } catch { json(res, 400, { error: 'Send JSON.' }); return }if (url.pathname === '/api/act') { json(res, 200, await act(payload)); return }+ if (url.pathname === '/api/cleanup/preview') { json(res, 200, await cleanup.preview()); return }+ if (url.pathname === '/api/cleanup/close') {+ let result+ try { result = await write(() => cleanup.close(payload.reviewId, payload.id)) }+ catch (error) {+ if (error.code !== 'INVALID_REVIEW') throw error+ json(res, 409, { error: error.message }); return+ }+ await record(workspace, { ...result, by: 'pane' })+ json(res, 200, result)+ return+ }if (url.pathname === '/api/policy') { json(res, 200, await write(() => savePolicy(payload.policy ?? {}))); return }if (url.pathname === '/api/refresh') { await polling; await poll({ immediate: true, forceRemote: true }); json(res, 200, { ok: true }); return }json(res, 404, { error: 'Not found' }); returndiff --git a/store/agents/harness-monitor/viewer/app.css b/store/agents/harness-monitor/viewer/app.cssindex b8a482a90..a11c8de23 100644--- a/store/agents/harness-monitor/viewer/app.css+++ b/store/agents/harness-monitor/viewer/app.css@@ -59,3 +59,10 @@ h2 { font-size:16px; margin:0 0 18px; } p { line-height:1.6; }.plan-row { padding:9px 0; border-bottom:1px solid var(--line); }.plan-row small { display:block; color:var(--muted); margin-top:5px; }@media (max-width:650px) { header { gap:10px; padding:12px; } h1 { width:100%; } input[type=search] { margin:0; } nav { padding-inline:6px; } footer { gap:10px; } }++.cleanup-mode { display:flex; align-items:center; flex-wrap:wrap; gap:8px; color:var(--muted); }+.cleanup-mode select { border-color:var(--line); background:var(--row); }+#cleanup-summary { font-size:16px; font-weight:600; }+#cleanup-plan .plan-row { overflow-wrap:anywhere; }+#cleanup-problems { color:var(--yellow); white-space:pre-line; }+#cleanup-apply { background:var(--red); color:var(--bg); border-color:var(--red); }diff --git a/store/agents/harness-monitor/viewer/app.js b/store/agents/harness-monitor/viewer/app.jsindex b1d7dd752..72eefea93 100644--- a/store/agents/harness-monitor/viewer/app.js+++ b/store/agents/harness-monitor/viewer/app.js@@ -6,6 +6,7 @@ const dom = {empty: el('empty'), count: el('count'), message: el('message'), updated: el('updated'), problems: el('problems'),assistant: el('assistant'), choice: el('assistant-choice'), free: el('assistant-free'), other: el('assistant-other'), cancel: el('assistant-cancel'),refresh: el('refresh'), cleanup: el('cleanup'), cleanupDialog: el('cleanup-dialog'), cleanupPlan: el('cleanup-plan'),+ cleanupMode: el('cleanup-mode'), cleanupExplanation: el('cleanup-explanation'), cleanupProblems: el('cleanup-problems'),cleanupSummary: el('cleanup-summary'), cleanupCancel: el('cleanup-cancel'), cleanupApply: el('cleanup-apply'),}const token = document.querySelector('meta[name="hps-token"]').content@@ -16,7 +17,7 @@ const state = {filter: ['all', ...Object.keys(ACTIVITY)].includes(saved.filter) ? saved.filter : 'all',sort: COLUMNS.some(c => c.key === saved.sort && c.key !== 'actions') ? saved.sort : 'lastActivity', direction: saved.direction === 1 ? 1 : -1,visible: new Set(Array.isArray(saved.visible) ? saved.visible : COLUMNS.filter(c => !c.optional).map(c => c.key)),- widths: {}, selected: null, busy: new Set(), cleanupIds: [], cleanupRows: [], nodes: new Map(), shown: [], assistantIntroSeen: saved.assistantIntroSeen === true,+ widths: {}, selected: null, busy: new Set(), nodes: new Map(), shown: [], assistantIntroSeen: saved.assistantIntroSeen === true,}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 }@@ -52,7 +53,7 @@ function openRow(id) {host({ action: 'open', machineId: row.machineId, agentId: row.agentId })}async function stopRows(ids, manual) {- const expected = (manual ? state.rows : state.cleanupRows).filter(row => ids.includes(row.id)).map(({ id, sessionId, lastActivity }) => ({ id, sessionId, lastActivity }))+ const expected = state.rows.filter(row => ids.includes(row.id)).map(({ id, sessionId, lastActivity }) => ({ id, sessionId, lastActivity }))ids.forEach(id => state.busy.add(id)); render()try {const reply = await post('/api/act', { verb: 'pause', ids, manual, expected })@@ -212,17 +213,82 @@ dom.assistant.onclick = () => state.assistantIntroSeen ? showAssistant() : dom.cdom.cancel.onclick = () => dom.choice.close()dom.free.onclick = () => showAssistant()dom.other.onclick = () => showAssistant(true)-dom.cleanup.onclick = () => {- const entries = (state.snapshot?.plan ?? []).filter(e => e.action === 'pause').slice(0, 64)- state.cleanupIds = entries.map(e => e.id)- state.cleanupRows = state.rows.filter(row => state.cleanupIds.includes(row.id))- dom.cleanupPlan.replaceChildren()- for (const entry of entries) { const node = element('div', entry.name, 'plan-row'); node.append(element('small', entry.why)); dom.cleanupPlan.append(node) }- text(dom.cleanupSummary, entries.length ? entries.length + ' sessions are eligible under your current cleanup rules.' : 'No sessions are eligible under your current cleanup rules.')- dom.cleanupApply.disabled = !entries.length; dom.cleanupDialog.showModal()-}-dom.cleanupCancel.onclick = () => dom.cleanupDialog.close()-dom.cleanupApply.onclick = async () => { const ids = [...state.cleanupIds]; dom.cleanupDialog.close(); await stopRows(ids, false) }+let cleanupReview = null, cleanupBusy = false, cleanupGeneration = 0+const cleanupActivity = { working: 'Working', needs_input: 'Needs you', draft: 'Unsent text', unknown: 'Activity unknown', idle: 'Idle' }+async function previewCleanup() {+ if (cleanupBusy) return+ const generation = ++cleanupGeneration, mode = dom.cleanupMode.value+ cleanupReview = null+ dom.cleanupApply.disabled = true; dom.cleanupApply.hidden = false+ text(dom.cleanupCancel, 'Cancel'); text(dom.cleanupSummary, 'Checking your open tabs…')+ text(dom.cleanupExplanation, mode === 'hidden'+ ? 'Harnesses in open tabs stay open. Work in the others will end. History is kept.'+ : 'Your cleanup rules are checked again before closing. Working sessions, questions, pins and unknown activity stay open. History is kept.')+ dom.cleanupPlan.replaceChildren(); dom.cleanupProblems.hidden = true+ try {+ let plan+ if (mode === 'hidden') plan = await post('/api/cleanup/preview', {})+ else {+ const entries = (state.snapshot?.plan ?? []).filter(e => e.action === 'pause').slice(0, 64)+ const eligible = new Map(entries.map(e => [e.id, e]))+ plan = { rows: state.rows.filter(row => eligible.has(row.id)).map(row => ({ ...row, why: eligible.get(row.id).why })), problems: state.snapshot?.problems ?? [] }+ }+ if (generation !== cleanupGeneration || !dom.cleanupDialog.open) return+ cleanupReview = { ...plan, mode }+ text(dom.cleanupSummary, plan.rows.length+ ? `Close ${plan.rows.length} ${plan.rows.length === 1 ? 'harness' : 'harnesses'}${mode === 'hidden' ? ' outside your tabs' : ''}?`+ : mode === 'hidden' ? 'No harnesses to close.' : 'No harnesses match your cleanup rules.')+ for (const row of plan.rows) {+ const node = element('div', null, 'plan-row')+ node.dataset.id = row.id+ node.append(element('strong', row.name), element('small', `${row.machine} · ${row.why || cleanupActivity[row.activity] || 'Activity unknown'}`))+ dom.cleanupPlan.append(node)+ }+ text(dom.cleanupProblems, plan.problems.map(p => `${p.machine}: ${p.error}`).join('\n'))+ dom.cleanupProblems.hidden = !plan.problems.length; dom.cleanupApply.disabled = !plan.rows.length+ } catch (error) { if (generation === cleanupGeneration) text(dom.cleanupSummary, error.message) }+}+dom.cleanup.onclick = () => { dom.cleanupMode.value = 'hidden'; dom.cleanupDialog.showModal(); void previewCleanup() }+dom.cleanupMode.onchange = () => void previewCleanup()+dom.cleanupCancel.onclick = () => { if (!cleanupBusy) { cleanupGeneration++; dom.cleanupDialog.close() } }+dom.cleanupDialog.addEventListener('cancel', event => { if (cleanupBusy) event.preventDefault(); else cleanupGeneration++ })+dom.cleanupApply.onclick = async () => {+ if (cleanupBusy || !cleanupReview?.rows.length) return+ const review = cleanupReview+ cleanupBusy = true; dom.cleanupApply.disabled = true; dom.cleanupCancel.disabled = true+ dom.cleanup.disabled = true; dom.cleanupMode.disabled = true+ let closed = 0, checked = 0+ function result(row, receipt) {+ if (receipt.ok) closed+++ const node = [...dom.cleanupPlan.children].find(node => node.dataset.id === row.id)+ text(node.lastElementChild, `${row.machine} · ${receipt.detail}`)+ }+ try {+ if (review.mode === 'hidden') {+ for (const row of review.rows) {+ text(dom.cleanupSummary, `Closing ${++checked} of ${review.rows.length}…`)+ let receipt+ try { receipt = await post('/api/cleanup/close', { reviewId: review.reviewId, id: row.id }) }+ catch (error) { receipt = { ok: false, detail: error.message + ' Refresh to check.' } }+ result(row, receipt)+ }+ } else {+ text(dom.cleanupSummary, 'Closing…')+ let receipts+ try {+ const expected = review.rows.map(({ id, sessionId, lastActivity }) => ({ id, sessionId, lastActivity }))+ const reply = await post('/api/act', { verb: 'pause', ids: expected.map(r => r.id), manual: false, expected })+ receipts = new Map(reply.results.map(r => [r.id, r]))+ } catch (error) { receipts = new Map(review.rows.map(row => [row.id, { ok: false, detail: error.message + ' Refresh to check.' }])) }+ for (const row of review.rows) result(row, receipts.get(row.id) || { ok: false, detail: 'Close was not confirmed. Refresh to check.' })+ }+ text(dom.cleanupSummary, closed === review.rows.length ? `${closed} closed. History kept.` : `${closed} closed. ${review.rows.length - closed} left open or unconfirmed.`)+ await post('/api/refresh', {}).catch(() => message('Refresh to check the latest sessions.'))+ } finally {+ cleanupBusy = false; dom.cleanup.disabled = false; dom.cleanupCancel.disabled = false; dom.cleanupMode.disabled = false+ dom.cleanupApply.hidden = true; text(dom.cleanupCancel, 'Done')+ }+}let streamfunction connect() {if (stream || document.hidden) returndiff --git a/store/agents/harness-monitor/viewer/index.html b/store/agents/harness-monitor/viewer/index.htmlindex bd50108a5..d70a33e0a 100644--- a/store/agents/harness-monitor/viewer/index.html+++ b/store/agents/harness-monitor/viewer/index.html@@ -22,7 +22,7 @@</select></label><span class="spacer"></span><details id="columns"><summary>Columns</summary><div id="column-options" class="menu"></div></details>- <button id="cleanup">Cleanup…</button>+ <button id="cleanup">Clean up…</button><button id="refresh" title="Refresh all machines">Refresh</button></nav><div id="problems" role="status" hidden></div>@@ -38,12 +38,15 @@<p class="muted">OpenCode may require a Zen login. If the free model is unavailable, choose a model yourself; Harness Monitor does not switch to a paid model automatically.</p><div class="dialog-actions"><button id="assistant-cancel">Cancel</button><button id="assistant-other">Choose another model</button><button id="assistant-free">Open assistant</button></div></dialog>- <dialog id="cleanup-dialog" aria-labelledby="cleanup-title">- <h2 id="cleanup-title">Review cleanup</h2>- <p id="cleanup-summary"></p>+ <dialog id="cleanup-dialog" aria-label="Clean up harnesses">+ <label class="cleanup-mode">Choose harnesses <select id="cleanup-mode">+ <option value="hidden">Outside open tabs</option><option value="policy">By cleanup rules</option>+ </select></label>+ <p id="cleanup-summary" role="status" aria-live="polite"></p>+ <p id="cleanup-explanation" class="muted"></p><div id="cleanup-plan"></div>- <p class="muted">Cleanup rechecks your rules and current activity. By default, working sessions, questions and pins are protected. Unknown activity is always protected. History and launch settings are retained. Nothing runs automatically.</p>- <div class="dialog-actions"><button id="cleanup-cancel">Cancel</button><button id="cleanup-apply">Stop reviewed sessions</button></div>+ <p id="cleanup-problems" class="muted" hidden></p>+ <div class="dialog-actions"><button id="cleanup-cancel">Cancel</button><button id="cleanup-apply">Close</button></div></dialog><script type="module" src="app.js"></script></body>