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.

Improve Harness Monitor and show harness resource totals in footer (#561)

Dee6c4a39f39de8
diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.ts
index a5254daaa..741d78d18 100644
--- a/cli/src/backendSocket.spec.ts
+++ b/cli/src/backendSocket.spec.ts
@@ -2279,12 +2279,27 @@ describe('agent_restart RPC', () => {
await vi.waitFor(() => expect(frames.filter(f => f.type === 'agents_list_result')).toHaveLength(2))
const response = (id: string) => (frames.find(frame => (frame.payload as any).requestId === id)?.payload as any).agents
expect(response('plain').every((agent: any) => agent.monitor === undefined)).toBe(true)
- expect(response('monitor').find((a: any) => a.id === 'agent-1').monitor).toEqual({ activity: 'needsInput', activityKnown: true, rssBytes: 123, cpu: 2, pid: BASE_SESSION.processIdentity?.pid ?? null })
+ expect(response('monitor').find((a: any) => a.id === 'agent-1').monitor).toMatchObject({ activity: 'needsInput', activityKnown: true, rssBytes: 123, cpu: 2, pid: BASE_SESSION.processIdentity?.pid ?? null })
expect(response('monitor').find((a: any) => a.id === 'stopped').monitor).toMatchObject({ rssBytes: 0, cpu: 0, pid: null })
expect(socket.harnessResourcesReader).toHaveBeenCalledOnce()
await socket.unregisterLocalClient('local:restart'); await socket.stop()
})
+ it('rejects a stop when the reviewed conversation rotated before the command arrived', async () => {
+ const { socket, frames } = localSocket()
+ const stop = vi.fn(async () => {})
+ socket.onDeleteAgent = stop
+ vi.spyOn(registry, 'byAgent').mockReturnValue({ ...BASE_SESSION, sessionId: 'replacement' })
+ socket.handleLocalFrame('local:restart', { type: 'agent_delete', payload: {
+ requestId: 'stale-stop', agentId: BASE_SESSION.agentId, expectedSessionId: BASE_SESSION.sessionId,
+ } })
+ await vi.waitFor(() => expect(frames).toContainEqual({ type: 'agent_delete_result', payload: {
+ requestId: 'stale-stop', error: 'SESSION_CHANGED', detail: 'This conversation changed. Refresh and review it before stopping.',
+ } }))
+ expect(stop).not.toHaveBeenCalled()
+ await socket.unregisterLocalClient('local:restart'); await socket.stop()
+ })
+
it('delegates a resume-only intent and retains its original receipt', async () => {
const { socket, frames } = localSocket()
const creationId = `resume-${randomUUID()}`
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
index 1ee320e20..64c644811 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -56,6 +56,7 @@ import { readAccountUsage, type AccountUsageReading } from './lib/accountUsage.j
import { probeEngines } from './lib/engineProbe.js'
import { readMachineResources } from './lib/machineResources.js'
import { createHarnessResourcesReader } from './lib/harnessResources.js'
+import { createHarnessStorageReader } from './lib/harnessTelemetry.js'
import { AgentCreationReceipts, AgentCreationReceiptError, creationFingerprint, validCreationId, type AgentCreationStatus } from './lib/agentCreationReceipt.js'
import { engineInstallRecipe } from './lib/engineInstall.js'
import { parseProjectFolder, prepareProjectFolder, projectsRoot, ProjectFolderError } from './lib/projectFolder.js'
@@ -766,6 +767,7 @@ export class BackendSocket {
* rather than a direct call so a spec answers it without a real home, Keychain or network. */
accountUsageReader: () => Promise<AccountUsageReading[]> = readAccountUsage
harnessResourcesReader = createHarnessResourcesReader(() => registry.advertised())
+ harnessStorageReader = createHarnessStorageReader()
/** The grid listing currently out, shared by every `grid_models_list` for the same own grid
* that lands meanwhile. */
private gridModelsInFlight: { gridName: string | null; grids: ReturnType<typeof listAllGridModels> } | null = null
@@ -2090,7 +2092,11 @@ export class BackendSocket {
case 'machine_resources':
// Sampling CPU must not hold up typing or other machine requests.
void (payload.harnesses === true
- ? this.harnessResourcesReader().then(harnesses => ({ harnesses }))
+ ? this.harnessResourcesReader().then(async harnesses => {
+ if (payload.storage !== true) return { harnesses }
+ const storage = await this.harnessStorageReader(registry.advertised())
+ return { harnesses: { ...harnesses, agents: harnesses.agents.map(row => ({ ...row, ...storage.get(row.agentId) })) } }
+ })
: readMachineResources())
.then(resources => reply(type, requestId, { ...resources }))
.catch(() => reply(type, requestId, { error: 'UNAVAILABLE' }))
@@ -2184,21 +2190,35 @@ export class BackendSocket {
return
}
if (payload.monitor === true) {
- const snapshot = await this.harnessResourcesReader().catch(() => ({ agents: [] }))
- const resources = new Map(snapshot.agents.map(row => [row.agentId, row]))
- const byId = new Map(sessions.map(s => [s.agentId, s]))
- reply(type, requestId, { agents: projects.map(agent => {
- const session = byId.get(agent.id)
- const activity = session ? this.monitorActivityProvider?.(session.sessionId) : null
- const reading = resources.get(agent.id)
- return { ...agent, monitor: {
- activity: activity && activity !== 'idle' ? activity : session ? this.monitorCompletions.state(session) : 'idle',
- activityKnown: this.monitorActivityProvider !== null,
- rssBytes: agent.status === 'stopped' ? 0 : reading?.memoryBytes ?? null,
- cpu: agent.status === 'stopped' ? 0 : reading?.cpuPercent ?? null,
- pid: reading?.processCount != null ? session?.processIdentity?.pid ?? null : null,
- } }
- }) })
+ // Optional telemetry must never hold the ordered terminal-input queue.
+ void (async () => {
+ const [snapshot, storage] = await Promise.all([
+ this.harnessResourcesReader().catch(() => ({ agents: [], sampledAt: null, shared: [] })),
+ this.harnessStorageReader(sessions).catch(() => new Map()),
+ ])
+ const resources = new Map(snapshot.agents.map(row => [row.agentId, row]))
+ const byId = new Map(sessions.map(s => [s.agentId, s]))
+ reply(type, requestId, { agents: projects.map(agent => {
+ const session = byId.get(agent.id)
+ const activity = session ? this.monitorActivityProvider?.(session.sessionId) : null
+ const reading = resources.get(agent.id)
+ return { ...agent, monitor: {
+ activity: activity && activity !== 'idle' ? activity : session ? this.monitorCompletions.state(session) : 'idle',
+ activityKnown: this.monitorActivityProvider !== null,
+ rssBytes: agent.status === 'stopped' ? 0 : reading?.memoryBytes ?? null,
+ cpu: agent.status === 'stopped' ? 0 : reading?.cpuPercent ?? null,
+ pid: reading?.processCount != null ? session?.processIdentity?.pid ?? null : null,
+ sampledAt: snapshot.sampledAt,
+ processCount: reading?.processCount ?? null,
+ gpuMemoryBytes: reading?.gpuMemoryBytes ?? null,
+ gpuPercent: reading?.gpuPercent ?? null,
+ diskReadBytesPerSecond: reading?.diskReadBytesPerSecond ?? null,
+ diskWriteBytesPerSecond: reading?.diskWriteBytesPerSecond ?? null,
+ processes: reading?.processes ?? [],
+ ...(storage.get(agent.id) ?? {}),
+ } }
+ }), sharedResources: snapshot.shared ?? [], sampledAt: snapshot.sampledAt })
+ })().catch(() => reply(type, requestId, { error: 'UNAVAILABLE' }))
} else reply(type, requestId, { agents: projects })
return
}
@@ -3072,6 +3092,13 @@ export class BackendSocket {
const target = (payload.agentId as string | undefined) || (payload.sessionId as string | undefined)
if (!target) { reply(type, requestId, { error: 'MISSING_AGENT_ID' }); return }
if (!this.onDeleteAgent) { reply(type, requestId, { error: 'UNSUPPORTED' }); return }
+ if (Object.hasOwn(payload, 'expectedSessionId')) {
+ const current = registry.byAgent(target)
+ if (!current || (current.sessionId || null) !== payload.expectedSessionId) {
+ reply(type, requestId, { error: 'SESSION_CHANGED', detail: 'This conversation changed. Refresh and review it before stopping.' })
+ return
+ }
+ }
try { await this.onDeleteAgent(target) }
catch (error) {
if (!(error instanceof AgentStopError)) throw error
diff --git a/cli/src/lib/agentFrame.ts b/cli/src/lib/agentFrame.ts
index ce03ec2dd..7146574b0 100644
--- a/cli/src/lib/agentFrame.ts
+++ b/cli/src/lib/agentFrame.ts
@@ -212,7 +212,11 @@ export async function agentFrame(
// the open an earlier frame had reported.
lastOpenedAt: s.lastOpenedAt ? new Date(s.lastOpenedAt).toISOString() : null,
tokenUsage: tokenUsage?.totalTokens != null
- ? { totalTokens: tokenUsage.totalTokens, updatedAt: tokenUsage.updatedAt } : null,
+ ? { totalTokens: tokenUsage.totalTokens, updatedAt: tokenUsage.updatedAt,
+ ...(tokenUsage.inputTokens == null ? {} : { inputTokens: tokenUsage.inputTokens }),
+ ...(tokenUsage.outputTokens == null ? {} : { outputTokens: tokenUsage.outputTokens }),
+ ...(tokenUsage.cachedTokens == null ? {} : { cachedTokens: tokenUsage.cachedTokens }),
+ } : null,
outputStats: tokenUsage?.output ? { ...tokenUsage.output, updatedAt: tokenUsage.updatedAt } : null,
tmuxPane: s.tmuxPane || null,
terminal: { available: terminalAvailable, primary: s.primaryRuntimeKey, runtimes: s.runtimes },
diff --git a/cli/src/lib/agentTokenUsage.spec.ts b/cli/src/lib/agentTokenUsage.spec.ts
index 3e7f2cfdc..487b44f2f 100644
--- a/cli/src/lib/agentTokenUsage.spec.ts
+++ b/cli/src/lib/agentTokenUsage.spec.ts
@@ -266,3 +266,15 @@ describe('owning-machine token cache', () => {
expect(await read()).toMatchObject({ totalTokens: null, output: { linesAdded: 1, linesRemoved: 0, pullRequestsCreated: null } })
})
})
+
+it('exports normalized input, output and cached input without double-counting', async () => {
+ const dir = await mkdtemp(join(tmpdir(), 'harness-usage-breakdown-'))
+ const path = join(dir, 'session.jsonl')
+ const store = new AgentTokenUsageCache(join(dir, 'cache'))
+ const target = { agentId: 'a', sessionId: 'conversation', engine: 'claude' as const, transcriptPath: path, registeredAt: 1 }
+ try {
+ await writeFile(path, claude('one') + claude('one') + claude('two'))
+ store.get(target); await store.settled()
+ expect(store.get(target)).toMatchObject({ totalTokens: 420, inputTokens: 380, outputTokens: 40, cachedTokens: 160 })
+ } finally { store.dispose(); await store.settled(); await rm(dir, { recursive: true, force: true }) }
+})
diff --git a/cli/src/lib/agentTokenUsage.ts b/cli/src/lib/agentTokenUsage.ts
index 30b72ac9f..77c0a2470 100644
--- a/cli/src/lib/agentTokenUsage.ts
+++ b/cli/src/lib/agentTokenUsage.ts
@@ -10,17 +10,18 @@ import { sqliteReadAll } from './sqliteRead.js'
import { emptyOutputLedger, ingestOutput, outputSnapshot, validOutputLedger, type AgentOutputStats, type OutputLedger } from './agentOutputStats.js'
import { emptySessionWork, ingestSessionWork, sessionWorkSnapshot, validSessionWork, type SessionWork, type SessionWorkLedger } from './sessionWork.js'
-export type AgentTokenUsage = { totalTokens: number | null; updatedAt: string; output?: AgentOutputStats; work?: SessionWork }
+export type AgentTokenUsage = { totalTokens: number | null; updatedAt: string; inputTokens?: number; outputTokens?: number; cachedTokens?: number; output?: AgentOutputStats; work?: SessionWork }
type Target = Pick<RegisteredSession, 'engine' | 'sessionId' | 'transcriptPath' | 'codexHome' | 'agentId' | 'forkedFrom' | 'registeredAt'>
& Partial<Pick<RegisteredSession, 'cwd'>>
type Buckets = [number, number, number, number]
type CodexTotals = [number, number, number, number]
type Checkpoint = {
- version: 4; key: string; offset: number; size: number; mtime: number; inode: string;
+ version: 5; key: string; offset: number; size: number; mtime: number; inode: string;
boundary: string; total: number; observed: boolean; updatedAt: string | null;
claude: Record<string, Buckets>; codex: CodexTotals | null; seen: Record<string, true>;
output: OutputLedger;
work: SessionWorkLedger; sourceSession: string | null;
+ usage: [number, number, number];
}
type Entry = {
target: Target; value: AgentTokenUsage | null; checked: number; pending: Promise<void> | null;
@@ -50,7 +51,7 @@ function targetSnapshot(s: Target): Target {
codexHome: s.codexHome, cwd: s.cwd, registeredAt: s.registeredAt, forkedFrom: s.forkedFrom ? { ...s.forkedFrom } : null }
}
function empty(key: string): Checkpoint {
- return { version: 4, key, offset: 0, size: 0, mtime: 0, inode: '', boundary: '', total: 0,
+ return { version: 5, key, offset: 0, size: 0, mtime: 0, inode: '', boundary: '', total: 0, usage: [0, 0, 0],
observed: false, updatedAt: null, claude: {}, codex: null, seen: {}, output: emptyOutputLedger(),
work: emptySessionWork(), sourceSession: null }
}
@@ -97,6 +98,9 @@ function ingest(state: Checkpoint, line: string, target: Target): void {
const merged = next.map((value, i) => Math.max(value, old[i])) as Buckets
state.claude[key] = merged
state.total += sum(merged) - sum(old)
+ state.usage[0] += merged[0] + merged[2] + merged[3] - old[0] - old[2] - old[3]
+ state.usage[1] += merged[1] - old[1]
+ state.usage[2] += merged[2] - old[2]
state.observed = true
} else {
const payload = object(row.payload)
@@ -120,6 +124,9 @@ function ingest(state: Checkpoint, line: string, target: Target): void {
if (delta) {
// Codex input includes cache reads; output includes reasoning.
state.total += Math.max(delta[0], delta[1]) + delta[2]
+ state.usage[0] += Math.max(delta[0], delta[1])
+ state.usage[1] += delta[2]
+ state.usage[2] += delta[1]
state.observed = true
}
}
@@ -213,6 +220,7 @@ export class AgentTokenUsageCache {
return
}
entry.value = { totalTokens: state.observed ? state.total : null, updatedAt: state.updatedAt,
+ ...(state.observed ? { inputTokens: state.usage[0], outputTokens: state.usage[1], cachedTokens: state.usage[2] } : {}),
...(output ? { output } : {}), ...(work ? { work } : {}) }
if (previous?.totalTokens !== entry.value.totalTokens
|| JSON.stringify(previous?.output) !== JSON.stringify(output ?? undefined)
@@ -224,7 +232,7 @@ export class AgentTokenUsageCache {
if ((await stat(file)).size > MAX_CACHE_BYTES) return empty(key)
const raw = JSON.parse(await readFile(file, 'utf8')) as Checkpoint
const version: number = raw.version
- if (version === 3 && raw.key === key) {
+ if ((version === 3 || version === 4) && raw.key === key) {
const work = { ...raw.work, currentOrder: 0, failedOrder: 0 }
if (validSessionWork(work)) {
// Receipts may already have been compacted out of the transcript. Replay the available
@@ -238,7 +246,8 @@ export class AgentTokenUsageCache {
}
}
// Replay old transcripts once: v3 skipped ordinary batched code-mode receipts, including PRs.
- if (raw.version === 4 && raw.key === key && Number.isSafeInteger(raw.total) && raw.total >= 0
+ if (raw.version === 5 && raw.key === key && Number.isSafeInteger(raw.total) && raw.total >= 0
+ && Array.isArray(raw.usage) && raw.usage.length === 3 && raw.usage.every(n => Number.isSafeInteger(n) && n >= 0)
&& typeof raw.observed === 'boolean'
&& (raw.updatedAt === null || typeof raw.updatedAt === 'string' && Number.isFinite(Date.parse(raw.updatedAt)))
&& Number.isSafeInteger(raw.size) && raw.size >= 0 && Number.isFinite(raw.mtime)
@@ -286,6 +295,8 @@ export class AgentTokenUsageCache {
if (!['tokens_input', 'tokens_output', 'tokens_reasoning', 'tokens_cache_read', 'tokens_cache_write']
.every(key => typeof row[key] === 'number' && Number.isSafeInteger(row[key]) && Number(row[key]) >= 0)) return
state.total = sum(Object.values(row).map(tokens))
+ state.usage = [tokens(row.tokens_input) + tokens(row.tokens_cache_read) + tokens(row.tokens_cache_write),
+ tokens(row.tokens_output) + tokens(row.tokens_reasoning), tokens(row.tokens_cache_read)]
state.observed = true
} else {
const path = entry.target.transcriptPath!
diff --git a/cli/src/lib/harnessResources.spec.ts b/cli/src/lib/harnessResources.spec.ts
index 3e214a49e..f95b3c937 100644
--- a/cli/src/lib/harnessResources.spec.ts
+++ b/cli/src/lib/harnessResources.spec.ts
@@ -98,3 +98,20 @@ it('counts a detached shared server once, without assigning its whole RAM to eve
time += 3000
expect((await read()).shared![0].cpuPercent).toBe(0)
})
+
+it('attributes GPU and disk rates only to owned trees and validates counter identity', async () => {
+ let now = 10_000, readBytes = 1000
+ const telemetry = vi.fn(async () => new Map([
+ [10, { readBytes, writeBytes: readBytes * 2, gpuMemoryBytes: null, gpuPercent: null }],
+ [11, { readBytes: 0, writeBytes: 0, gpuMemoryBytes: 200, gpuPercent: 15 }],
+ [90, { readBytes: 9000, writeBytes: 9000, gpuMemoryBytes: 9000, gpuPercent: 80 }],
+ ]))
+ let snapshot = [row(10), row(11, 10), row(90)]
+ const read = createHarnessResourcesReader(() => [agent('a', 10)], { now: () => now, sample: async () => snapshot, telemetry })
+ expect((await read()).agents[0]).toMatchObject({ gpuMemoryBytes: 200, gpuPercent: 15, diskReadBytesPerSecond: null })
+ expect(telemetry).toHaveBeenCalledWith([10, 11])
+ now += 5000; readBytes += 1000
+ expect((await read()).agents[0]).toMatchObject({ diskReadBytesPerSecond: 200, diskWriteBytesPerSecond: 400, processCount: 2 })
+ now += 5000; snapshot = [row(10), { ...row(11, 10), start: 'replacement' }]
+ expect((await read()).agents[0].diskReadBytesPerSecond).toBeNull()
+})
diff --git a/cli/src/lib/harnessResources.ts b/cli/src/lib/harnessResources.ts
index 17f5dfd7d..c88f73dca 100644
--- a/cli/src/lib/harnessResources.ts
+++ b/cli/src/lib/harnessResources.ts
@@ -4,6 +4,7 @@ import { join } from 'node:path'
import { env } from '../config/env.js'
import { promisify } from 'node:util'
import type { ProcessIdentity } from './terminalTypes.js'
+import { readProcessTelemetry, type ProcessTelemetry } from './harnessTelemetry.js'
const exec = promisify(execFile)
type Agent = { agentId: string; processIdentity?: ProcessIdentity | null; engine?: string; codexHome?: string | null }
@@ -20,6 +21,11 @@ export interface HarnessResource {
memoryBytes: number | null
cpuPercent: number | null
processCount: number | null
+ gpuMemoryBytes?: number | null
+ gpuPercent?: number | null
+ diskReadBytesPerSecond?: number | null
+ diskWriteBytesPerSecond?: number | null
+ processes?: Array<{ pid: number; parent: number; memoryBytes: number; cpuPercent: number | null }>
}
export interface HarnessResources {
sampledAt: string
@@ -80,10 +86,14 @@ async function sharedCodexRoots(agents: readonly Agent[]): Promise<SharedResourc
}
/** No timer, no retained history and no work until an owning client asks. */
-export function createHarnessResourcesReader(agents: () => readonly Agent[], deps = {
- sample: sampleProcesses, now: Date.now,
+export function createHarnessResourcesReader(agents: () => readonly Agent[], deps: {
+ sample: () => Promise<ResourceProcess[]>; now: () => number
+ telemetry?: (pids: number[]) => Promise<Map<number, ProcessTelemetry>>
+} = {
+ sample: sampleProcesses, now: Date.now, telemetry: readProcessTelemetry,
}, sharedRoots: (agents: readonly Agent[]) => Promise<SharedResourceRoot[]> = sharedCodexRoots) {
let previous: { at: number; rows: Map<number, ResourceProcess> } | undefined
+ let previousTelemetry = new Map<number, ProcessTelemetry>()
let cached: { at: number; value: HarnessResources } | undefined
let pending: Promise<HarnessResources> | undefined
async function read(): Promise<HarnessResources> {
@@ -105,13 +115,14 @@ export function createHarnessResourcesReader(agents: () => readonly Agent[], dep
}
const elapsed = previous ? at - previous.at : 0
const counted = new Set<number>()
+ const trees = new Map<number, number[]>()
const measure = (root: number) => {
let memoryBytes = 0, cpuMs = 0, processCount = 0
let cpuKnown = elapsed > 0 && elapsed <= 60_000
const queue = [root], seen = new Set<number>()
while (queue.length) {
const pid = queue.pop()!
- if (seen.has(pid) || (pid !== root && owners.has(pid))) continue
+ if (seen.has(pid) || counted.has(pid) || (pid !== root && owners.has(pid))) continue
seen.add(pid); counted.add(pid)
const row = byPid.get(pid)
if (!row) continue
@@ -122,6 +133,7 @@ export function createHarnessResourcesReader(agents: () => readonly Agent[], dep
else cpuKnown = false
queue.push(...children.get(pid) ?? [])
}
+ trees.set(root, [...seen])
return { memoryBytes, processCount, cpuPercent: cpuKnown ? Math.round(cpuMs / elapsed * 1000) / 10 : null }
}
const readings = current.map(agent => {
@@ -136,6 +148,42 @@ export function createHarnessResourcesReader(agents: () => readonly Agent[], dep
if (counted.has(root.pid) || byPid.get(root.pid)?.start !== root.start) continue
shared.push({ kind: 'codex', agentIds: root.agentIds, ...measure(root.pid) })
}
+ if (deps.telemetry) {
+ const telemetry = await deps.telemetry([...counted]).catch(() => new Map<number, ProcessTelemetry>())
+ const enrich = (value: HarnessResource | NonNullable<HarnessResources['shared']>[number], pids: number[]) => {
+ const gpu = pids.map(pid => telemetry.get(pid)?.gpuMemoryBytes).filter((n): n is number => n != null)
+ const gpuUsage = pids.map(pid => telemetry.get(pid)?.gpuPercent).filter((n): n is number => n != null)
+ const rate = (key: 'readBytes' | 'writeBytes') => {
+ if (!pids.length || elapsed <= 0 || elapsed > 60_000) return null
+ let delta = 0
+ for (const pid of pids) {
+ const before = previousTelemetry.get(pid)?.[key], next = telemetry.get(pid)?.[key]
+ if (before == null || next == null || next < before || previous?.rows.get(pid)?.start !== byPid.get(pid)?.start) return null
+ delta += next - before
+ }
+ return delta * 1000 / elapsed
+ }
+ value.gpuMemoryBytes = gpu.length ? gpu.reduce((sum, n) => sum + n, 0) : null
+ value.gpuPercent = gpuUsage.length ? gpuUsage.reduce((sum, n) => sum + n, 0) : null
+ value.diskReadBytesPerSecond = rate('readBytes')
+ value.diskWriteBytesPerSecond = rate('writeBytes')
+ value.processes = pids.flatMap(pid => {
+ const row = byPid.get(pid), before = previous?.rows.get(pid)
+ if (!row) return []
+ return [{ pid, parent: row.parent, memoryBytes: row.memoryBytes,
+ cpuPercent: before?.start === row.start && elapsed > 0 && elapsed <= 60_000 && row.cpuMs >= before.cpuMs
+ ? Math.round((row.cpuMs - before.cpuMs) / elapsed * 1000) / 10 : null }]
+ }).slice(0, 256)
+ }
+ for (const value of readings) {
+ const root = current.find(a => a.agentId === value.agentId)?.processIdentity?.pid
+ enrich(value, root && value.processCount != null ? trees.get(root) ?? [] : [])
+ }
+ // Shared roots were measured after agent trees, in the same insertion order.
+ const sharedTrees = [...trees].filter(([pid]) => !owners.has(pid)).map(([, pids]) => pids)
+ shared.forEach((value, i) => enrich(value, sharedTrees[i] ?? []))
+ previousTelemetry = telemetry
+ }
previous = { at, rows: byPid }
const value = { sampledAt: new Date(at).toISOString(), agents: readings, ...(shared.length ? { shared } : {}) }
cached = { at, value }
diff --git a/cli/src/lib/harnessTelemetry.spec.ts b/cli/src/lib/harnessTelemetry.spec.ts
new file mode 100644
index 000000000..3fe607af2
--- /dev/null
+++ b/cli/src/lib/harnessTelemetry.spec.ts
@@ -0,0 +1,51 @@
+import { expect, it, vi } from 'vitest'
+import { createHarnessStorageReader, parseProcessGpuMemory, parseProcessGpuUsage, parseProcessIo } from './harnessTelemetry.js'
+
+it('keeps Linux physical I/O distinct from logical byte counts, preserving zero and unknown', () => {
+ expect(parseProcessIo('rchar: 99999\nwchar: 50000\nread_bytes: 0\nwrite_bytes: 8192\n')).toEqual({ readBytes: 0, writeBytes: 8192 })
+ expect(parseProcessIo('read_bytes: -1\nwrite_bytes: 999999999999999999999')).toEqual({ readBytes: null, writeBytes: null })
+})
+it('counts multi-GPU allocations once per device and never substitutes GPU capacity', () => {
+ const memory = parseProcessGpuMemory('10, GPU-one, 200\n10, GPU-one, 200\n10, GPU-two, 300\n20, GPU-one, [N/A]\n30, GPU-one, 0')
+ expect(memory.get(10)).toBe(500 * 1024 ** 2)
+ expect(memory.get(20)).toBeNull()
+ expect(memory.get(30)).toBe(0)
+ expect(memory.has(40)).toBe(false)
+})
+it('reads per-process GPU compute utilization by header, not device-level utilization', () => {
+ const result = parseProcessGpuUsage('# gpu pid type sm mem enc dec command\n# Idx # C/G % % % % name\n0 10 C 25 90 0 0 python\n1 10 C 40 10 0 0 python\n0 20 C - - - - model\n0 30 C 0 0 0 0 model')
+ expect([...result]).toEqual([[10, 65], [20, null], [30, 0]])
+ expect(parseProcessGpuUsage('unavailable').size).toBe(0)
+})
+it('storage sampling coalesces shared paths, bounds concurrency and never stalls inventory', async () => {
+ let now = 100_000
+ const pending: Array<(size: number) => void> = []
+ const size = vi.fn(() => new Promise<number>(resolve => pending.push(resolve)))
+ const read = createHarnessStorageReader({ now: () => now, size, transcript: async () => 70, canonical: async path => path === '/alias' ? '/project' : path })
+ const agents = [{ agentId: 'a', cwd: '/project', transcriptPath: '/log' }, { agentId: 'b', cwd: '/alias' }, { agentId: 'c', cwd: '/other' }, { agentId: 'd', cwd: '/third' }]
+ const first = await read(agents)
+ expect(first.get('a')).toMatchObject({ workspaceBytes: null, transcriptBytes: 70, workspacePath: '/project' })
+ expect(size).toHaveBeenCalledTimes(2)
+ pending[0](1000); pending[1](2000)
+ await vi.waitFor(() => expect(size).toHaveBeenCalledTimes(3))
+ pending[2](3000)
+ await Promise.resolve()
+ expect((await read(agents)).get('b')?.workspaceBytes).toBe(1000)
+ expect(size).toHaveBeenCalledTimes(3)
+ now += 61_000
+ await read(agents)
+ expect(size).toHaveBeenCalledTimes(5)
+ pending[3](1100); pending[4](2100)
+ await vi.waitFor(() => expect(size).toHaveBeenCalledTimes(6))
+ pending[5](3100)
+})
+it('storage failures and unknown transcripts remain unknown and do not immediately retry', async () => {
+ const size = vi.fn(async () => { throw Error('denied') })
+ const read = createHarnessStorageReader({ now: () => 10000, size, transcript: async () => { throw Error('missing') }, canonical: async p => p })
+ const rows = [{ agentId: 'a', cwd: '/project', transcriptPath: '/unreadable' }, { agentId: 'b', cwd: '/' }]
+ await read(rows)
+ const values = await read(rows)
+ expect(values.get('a')).toMatchObject({ workspaceBytes: null, transcriptBytes: null })
+ expect(values.get('b')?.workspaceBytes).toBeNull()
+ expect(size).toHaveBeenCalledTimes(1)
+})
diff --git a/cli/src/lib/harnessTelemetry.ts b/cli/src/lib/harnessTelemetry.ts
new file mode 100644
index 000000000..a90c97b09
--- /dev/null
+++ b/cli/src/lib/harnessTelemetry.ts
@@ -0,0 +1,132 @@
+import { execFile } from 'node:child_process'
+import { readFile, realpath, stat } from 'node:fs/promises'
+import { isAbsolute } from 'node:path'
+import { promisify } from 'node:util'
+
+const exec = promisify(execFile)
+export type ProcessTelemetry = { readBytes: number | null; writeBytes: number | null; gpuMemoryBytes: number | null; gpuPercent?: number | null }
+const count = (value: string | undefined) => value != null && /^\d+$/.test(value.trim()) && Number.isSafeInteger(Number(value)) ? Number(value) : null
+
+export function parseProcessIo(text: string): Pick<ProcessTelemetry, 'readBytes' | 'writeBytes'> {
+ return { readBytes: count(/^read_bytes:\s*(\d+)\s*$/m.exec(text)?.[1]),
+ writeBytes: count(/^write_bytes:\s*(\d+)\s*$/m.exec(text)?.[1]) }
+}
+
+/** NVIDIA reports compute allocations, not the remote GPU used by a cloud model.
+ * Keep unavailable counters unknown, including processes absent from the report:
+ * a graphics-only process or an unsupported GPU must not become a measured zero. */
+export function parseProcessGpuMemory(text: string): Map<number, number | null> {
+ const devices = new Map<string, { pid: number; bytes: number | null }>()
+ for (const line of text.split('\n')) {
+ const [pidText, uuid, memory, ...extra] = line.split(',').map(v => v.trim())
+ const pid = count(pidText), mib = count(memory)
+ if (!pid || !/^GPU-[\w-]+$/.test(uuid ?? '') || extra.length) continue
+ devices.set(`${pid}/${uuid}`, { pid, bytes: mib == null ? null : mib * 1024 ** 2 })
+ }
+ const result = new Map<number, number | null>()
+ for (const { pid, bytes } of devices.values()) {
+ const before = result.get(pid)
+ result.set(pid, bytes == null || before === null ? null : (before ?? 0) + bytes)
+ }
+ return result
+}
+
+export function parseProcessGpuUsage(text: string): Map<number, number | null> {
+ const result = new Map<number, number | null>()
+ let header: string[] = []
+ for (const line of text.split('\n')) {
+ const cells = line.trim().split(/\s+/)
+ if (cells[0] === '#' && cells.includes('pid') && cells.includes('sm')) { header = cells.slice(1); continue }
+ if (!header.length || cells[0] === '#') continue
+ const pid = count(cells[header.indexOf('pid')]), sm = count(cells[header.indexOf('sm')])
+ if (!pid) continue
+ const before = result.get(pid)
+ result.set(pid, sm == null || sm > 100 || before === null ? null : (before ?? 0) + sm)
+ }
+ return result
+}
+
+let gpuRetryAfter = 0
+async function processGpus(): Promise<{ memory: Map<number, number | null>; usage: Map<number, number | null> }> {
+ const empty = () => ({ memory: new Map<number, number | null>(), usage: new Map<number, number | null>() })
+ if (process.platform !== 'linux' || Date.now() < gpuRetryAfter) return empty()
+ try {
+ const options = { timeout: 2200, maxBuffer: 1024 * 1024, env: { ...process.env, LC_ALL: 'C' } }
+ const [memory, usage] = await Promise.all([
+ exec('nvidia-smi', ['--query-compute-apps=pid,gpu_uuid,used_gpu_memory', '--format=csv,noheader,nounits'], options),
+ exec('nvidia-smi', ['pmon', '-s', 'u', '-c', '1'], options).catch(() => ({ stdout: '' })),
+ ])
+ return { memory: parseProcessGpuMemory(memory.stdout), usage: parseProcessGpuUsage(usage.stdout) }
+ } catch { gpuRetryAfter = Date.now() + 60_000; return empty() }
+}
+
+/** Only owned processes are read. No privilege escalation or whole-machine fallback. */
+export async function readProcessTelemetry(pids: number[]): Promise<Map<number, ProcessTelemetry>> {
+ if (!pids.length) return new Map()
+ const gpu = await processGpus(), result = new Map<number, ProcessTelemetry>()
+ let index = 0
+ await Promise.all(Array.from({ length: Math.min(8, pids.length) }, async () => {
+ while (index < pids.length) {
+ const pid = pids[index++]
+ const io = process.platform === 'linux'
+ ? await readFile(`/proc/${pid}/io`, 'utf8').then(parseProcessIo).catch(() => null) : null
+ result.set(pid, { readBytes: io?.readBytes ?? null, writeBytes: io?.writeBytes ?? null,
+ gpuMemoryBytes: gpu.memory.get(pid) ?? null, gpuPercent: gpu.usage.get(pid) ?? null })
+ }
+ }))
+ return result
+}
+
+export type StorageReading = { workspaceBytes: number | null; workspacePath: string | null; workspaceSampledAt: string | null; transcriptBytes: number | null }
+type Target = { agentId: string; cwd?: string | null; transcriptPath?: string | null }
+
+/** Directory sizes are shared by path and read in a bounded queue, at most once
+ * a minute. A process sample never waits for du, and failure is not a zero. */
+export function createHarnessStorageReader(deps = {
+ now: Date.now,
+ size: async (path: string): Promise<number | null> => {
+ if (!isAbsolute(path) || path === '/') return null
+ const { stdout } = await exec('du', ['-sk', '-P', path], { timeout: 2500, maxBuffer: 4096 })
+ const kb = count(/^(\d+)\s/.exec(stdout)?.[1])
+ return kb == null ? null : kb * 1024
+ },
+ transcript: async (path: string) => { const info = await stat(path); return info.isFile() ? info.size : null },
+ canonical: async (path: string): Promise<string> => realpath(path),
+}) {
+ const cache = new Map<string, { at: number; bytes: number | null; pending: boolean }>()
+ let active = 0
+ const queue: Array<() => Promise<void>> = []
+ function drain() {
+ while (active < 2 && queue.length) {
+ active++
+ void queue.shift()!().finally(() => { active--; drain() })
+ }
+ }
+ return async (agents: readonly Target[]): Promise<Map<string, StorageReading>> => {
+ const canonical = new Map(await Promise.all([...new Set(agents.map(a => a.cwd).filter((p): p is string => !!p && isAbsolute(p) && p !== '/'))]
+ .map(async path => [path, await deps.canonical(path).catch(() => path)] as const)))
+ const paths = new Set(canonical.values())
+ for (const [path, entry] of cache) if (!paths.has(path) && !entry.pending) cache.delete(path)
+ for (const path of paths) {
+ let entry = cache.get(path)
+ if (entry?.pending || entry && deps.now() - entry.at < 60_000) continue
+ if (!entry) { entry = { at: 0, bytes: null, pending: false }; cache.set(path, entry) }
+ entry.pending = true
+ const target = entry
+ queue.push(async () => {
+ try { target.bytes = await deps.size(path) } catch { target.bytes = null }
+ finally { target.at = deps.now(); target.pending = false }
+ })
+ }
+ drain()
+ const result = new Map<string, StorageReading>()
+ await Promise.all(agents.map(async agent => {
+ const workspacePath = agent.cwd ? canonical.get(agent.cwd) ?? null : null
+ const workspace = workspacePath ? cache.get(workspacePath) : null
+ const transcriptBytes = agent.transcriptPath ? await deps.transcript(agent.transcriptPath).catch(() => null) : null
+ result.set(agent.agentId, { workspaceBytes: workspace?.bytes ?? null, workspacePath,
+ workspaceSampledAt: workspace?.at ? new Date(workspace.at).toISOString() : null, transcriptBytes })
+ }))
+ return result
+ }
+}
diff --git a/desktop/design/desktop-design-system.md b/desktop/design/desktop-design-system.md
index 25edae5d7..b127991d7 100644
--- a/desktop/design/desktop-design-system.md
+++ b/desktop/design/desktop-design-system.md
@@ -344,25 +344,24 @@ 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
separate and remains hover-revealed.
-**Focused workspace footer** — global harness count, local CPU/RAM/GPU,
-then subscription allowance used at the left; focused machine, project, branch
-and PR at the right. Each context field keeps its existing action. The hardware
-scope always stays on the computer running the app, even when a remote pane is
-focused. Hardware is plain status text, with no machine filter, selection or
-resource panel. Never sum percentages across machines.
-Titles stay quiet when several panes are visible. Do not repeat branches in pane
-headers, or model/effort in the footer. Context honors the selected status face,
-fields, colors and shell/Powerline treatment. Recent-harness context uses its
-monochrome presentation.
-Use whole percentages, one space between title and value, and 2.5 character cells between parts:
-`Harnesses 118 CPU 20% RAM 50% GPU 10% Claude 100% Codex 90%`.
-All labels and numbers use neutral readable ink;
-no severity color, dot separators, trailing plus or decimal figures. Subscription
-figures mean allowance used. Preserve Models' deduplicated accounts, limiting
-window and freshness rules. Unknown values show `-`, never fabricated zero.
-Hover explains scope, account identity and reset windows. Hardware has no click
-action. Clicking subscription usage opens Subscriptions without switching a model.
-At narrow widths hide complete metric groups rather than clipping percentages.
+**Focused workspace footer** — running harness count and attributable CPU/RAM/GPU/SSD across
+connected owned machines, then subscription allowance used at the left; focused machine, project,
+branch and PR at the right. Each context field keeps its action. Harness count and every resource
+metric select the existing Harness Monitor tab or create it if absent. Process-tree CPU uses 100%
+per core; GPU sums reported process utilization, which can exceed 100%. Shared servers count once. Unsupported GPU
+attribution stays unknown. RAM/SSD are absolute, rounded whole MB/GB; shared/nested workspace
+folders count once per machine. See [workspace status bar](workspace-status-bar.md) for accounting.
+Titles stay quiet when several panes are visible. Do not repeat branches in pane headers or
+model/effort in the footer. Context honors the selected status face, fields, colors and shell/
+Powerline treatment. Recent-harness context uses its monochrome presentation.
+Use whole figures, one space between title and value, and 2.5 character cells between parts:
+`Harnesses 118 CPU 20% RAM 10 GB GPU 10% SSD 1 GB Claude 100% Codex 90%`.
+Labels and numbers use neutral readable ink; no severity color, dot separators, trailing plus or
+decimal figures. Harness metrics show — when unavailable and ≥ for partial totals. Subscription
+figures mean allowance used and preserve Models' deduplicated accounts, limiting window and
+freshness rules. Hover explains scope and units. Clicking subscription usage opens Subscriptions
+without switching a model. Narrow widths hide complete groups: SSD, then GPU, then RAM.
+
Companion and sharing controls follow usage. See the full [status bar contract](workspace-status-bar.md).
**Settings, Store and supporting screens** — the same type, colors and controls
diff --git a/desktop/design/desktop-ui-migration.md b/desktop/design/desktop-ui-migration.md
index f3b20d2a7..951420a21 100644
--- a/desktop/design/desktop-ui-migration.md
+++ b/desktop/design/desktop-ui-migration.md
@@ -458,3 +458,27 @@ unmerged.
[narrow dark](../../docs/research/2026-10-01-session-close/dark-2.0x.png),
[narrow light](../../docs/research/2026-10-01-session-close/light-2.0x.png).
Live native interaction and VoiceOver are not claimed by these widget renders.
+
+
+### Harness Monitor and resource footer, 2026-10-01
+
+- The process table starts with active sessions, with machine/status filters, saved sortable and
+ resizable columns, resource/AI presets, an inspector and a reviewed Stop action. Open/resume and
+ assistant/cleanup controls are absent from the table. Stopping keeps history and files and checks
+ conversation identity on the owning daemon.
+- The footer now totals the counted harnesses across connected owned machines. CPU/GPU are whole
+ percentages; RAM/SSD are whole MB/GB. Shared servers and canonical workspace folders count once;
+ partial totals use ≥ and missing metrics use —. Every metric opens the same reusable monitor tab.
+ Foreground sampling runs every fifteen seconds and stops while hidden.
+- Synthetic browser review covered machine/status filters, selection, inspection, a confirmed stop,
+ paused/offline action availability, keyboard resizing, and light/dark layouts at 880×560. A 440×560
+ check found and fixed the Columns menu overflowing the left edge. No real harness was stopped.
+- Validation: 117 monitor tests, 214 focused daemon tests, 43 desktop tests and 4,221 native titlebar
+ checks passed. TypeScript checking, changed-file Flutter analysis and the macOS debug build passed.
+ The full CLI suite had 8,292 passing and 39 skipped tests; five unchanged installed-OpenCode flag
+ checks failed because the local binary did not advertise --auto/--agent. An isolated real macOS
+ process/folder smoke check measured CPU, RAM and disk and kept unsupported GPU readings unknown.
+- Linux NVIDIA utilization/allocation and procfs I/O parsing have fixtures; actual NVIDIA hardware
+ remains unverified. macOS per-process GPU and restricted driver counters display —. Token totals
+ and breakdowns currently come from Claude, Codex and OpenCode ledgers; other engines show missing
+ metrics explicitly. See the Harness Monitor README for definitions and research references.
diff --git a/desktop/design/images/harness-monitor-footer.png b/desktop/design/images/harness-monitor-footer.png
new file mode 100644
index 000000000..fc88d21b9
Binary files /dev/null and b/desktop/design/images/harness-monitor-footer.png differ
diff --git a/desktop/design/workspace-status-bar.md b/desktop/design/workspace-status-bar.md
index 9df6555aa..f56286748 100644
--- a/desktop/design/workspace-status-bar.md
+++ b/desktop/design/workspace-status-bar.md
@@ -14,7 +14,7 @@ api ? web ⠹ blender ✓ + Search Bell (✿ Harness
panes
-Harnesses 118 CPU 20% RAM 50% GPU 10% Claude 100% Codex 90%
+Harnesses 118 CPU 20% RAM 10 GB GPU 10% SSD 1 GB Claude 100% Codex 90%
M2 > project > branch > #439
```
@@ -22,80 +22,62 @@ The context follows the focused pane. The branch stays clickable in the
footer; pane headers do not repeat it. An empty New Tab keeps the footer when
there are live sessions to inspect.
-The left side has three independent scopes: a global count of running harnesses,
-hardware for the computer running the app, and subscription allowance used per
-account.
-Use one space between each title and value, and 2.5 character cells between complete
-parts, including the harness count. Put the title before the value. Do not pad
-numbers to a fixed width. No dots, decimal percentages or `+` suffixes. Adjacent controls each
-contribute one cell of horizontal padding plus half a cell between controls,
-matching the group gap inside each control. The shared
-`workspaceBarGroupGapCells` sets this spacing in Flutter and native views.
-Keep the plain-text separator readable; measure and render its precise width.
-Use neutral workspace ink at every usage level. The context on the right still
-follows the focused pane; it may identify a remote machine while hardware remains
-local.
-
-`Harnesses 118` opens the reusable Harness Monitor tab. Count running sessions on
-connected owned machines even when none of this window's tabs show them. The
-monitor's process table retains its own resource sampling and session actions.
-Saved history remains available through session search.
-
-CPU, RAM and GPU always describe the local computer, independently of pane focus
-or machine selection. Never substitute a remote host if local readings are
-unavailable. The dock has no machine name or filter. Hover identifies the source.
-Hardware is plain status text: no click action, machine selection, or resource
-panel. It never opens a pane, changes focus, or connects a remote machine.
-
-CPU is total host utilization normalized to 0–100%, not a sum of per-process
-percentages. RAM is used physical memory divided by capacity, excluding
-reclaimable cache where the OS reports it. GPU is the busiest device with a
-valid utilization counter; never add percentages across heterogeneous devices.
-All three include other applications on that machine. No cross-machine average
-or total appears in the footer.
-
-Keep disk capacity, swap and memory pressure out of the dock. macOS uses
-IORegistry GPU counters; Linux/Windows use NVIDIA driver telemetry where
-available. Unsupported/expired/invalid readings
-show a single `-`, including older daemons' missing fields. Keep the pair
-visible so unavailable data is distinct from 0%; do not hide it when a reading
-temporarily disappears. Preserve valid zero. An offline or missing local machine
-shows unknown values, never another host's cached readings. Hardware freshness
-expires after 45 seconds.
-
-Sample only the local host every 15 seconds. Do not poll remote hosts for
-this display. Coalesce daemon requests for two seconds. Clear hardware readings
-and stop polling when the app is hidden;
-refresh on return. Session process-tree sampling runs only while its own monitor
-is open (three seconds). A closed count requires no process scan. Inspecting
-tokens never starts a transcript scan.
-
-Each owning daemon's session snapshot counts nested engines once and retains
-process birth identities. Those session-manager figures remain process-tree
-resident memory and interval CPU, where 100% means one core. Shared Codex servers
-appear once, separately. Keep this distinct from the normalized host CPU in the
-footer. Unknown session readings retain the monitor's existing explanation.
-
-![Status bar with synthetic readings and focused-pane context](images/workspace-resources.png)
-
-Native and Flutter footers share data and behavior. At narrow widths remove GPU,
-then RAM as complete groups, keeping CPU and the full tooltip. Subscription usage
-remains visible in wide windows and accessible through Models at every size.
-Preserve room for focused context.
-
-Validation covers local scope, unavailable and late responses, hidden-app
-polling, native and Flutter status text, narrow windows and subscription actions.
-Run `machine_resources_test.dart`, `machine_resource_monitor_test.dart`,
-`harness_resources_test.dart` and `workspace_status_test.dart`.
-Set `HARNESS_WORKSPACE_CONTROLS_CAPTURE_DIR` to capture Flutter footer fixtures;
-`HARNESS_RESOURCE_CAPTURE_DIR` enables native footer captures in
-`tool/check_swarm_titlebar.sh`. CLI parser/failure/cache checks live in
-`machineHardware.spec.ts` and `machineResources.spec.ts`.
+The left side shows running harnesses and their CPU, RAM, GPU and SSD consumption across connected
+owned machines, followed by subscription allowance used per account. The focused-pane context
+remains at the right. Count each live session even when no tab currently displays it.
+
+Clicking Harnesses or any resource metric selects the existing Harness Monitor tab across all tabs
+and machines. Create one only when absent. Clicking does not open a separate resource popover.
+Saved sessions and open/resume actions belong in Open Harness (Cmd-P). The monitor itself starts
+with active sessions, sortable resource and AI metrics, an inspector and a reviewed Stop action.
+
+Use one space between title and value and 2.5 character cells between complete groups, including
+the count. Adjacent controls contribute one cell of horizontal padding plus half a cell between
+controls. The shared `workspaceBarGroupGapCells` keeps Flutter and native views aligned. Use neutral
+workspace ink at every usage level. Do not pad numbers or add dots, decimal figures or plus suffixes.
+
+CPU is the sum of attributable process-tree interval use; 100% is one core, so multicore and fleet
+totals can exceed 100%. RAM is process-tree resident memory. Nested harness roots are excluded from
+the parent and shared Codex servers count once; shared memory pages may still overlap. GPU uses
+summed reported process utilization; multiple processes/devices can exceed 100%. macOS and unsupported drivers show —;
+whole-host GPU activity is not a substitute for attribution. Cloud inference is not local GPU use.
+
+RAM and SSD use rounded whole MB/GB, such as `RAM 10 GB` and `SSD 1 GB` (10.4 rounds to 10).
+SSD means allocated workspace disk space, including existing files. Shared and nested canonical
+folders count once per machine. It is not free space, capacity or a claim that every host uses an
+SSD. Stopping a process keeps its files. Directory sizes use bounded reads cached for one minute.
+
+Unknown readings show —, with valid zero preserved. A partial total is prefixed ≥. The tooltip
+explains scope, units and shared accounting. Samples expire after 45 seconds. The count and resource
+totals cover the same connected owned sessions and never substitute whole-machine utilization.
+
+Sample connected owners every fifteen seconds while the app is foregrounded. Clear readings and
+stop polling when hidden; refresh on return. Coalesce process samples in the owning daemon, verify
+PID birth identity and keep telemetry off the terminal-input queue. The viewer samples local
+inventory every four seconds and linked machines every fifteen seconds while visible. Reading
+token usage uses the existing incremental ledger and does not trigger a new transcript scan.
+
+Native and Flutter footers share data, tooltips and button behavior. At narrow widths remove SSD,
+then GPU, then RAM as complete groups, keeping CPU and the full tooltip. Subscription usage remains
+visible in wide windows and accessible through Models at every size. Preserve focused context.
+
+![Harness resource footer with synthetic readings](images/harness-monitor-footer.png)
+
+The previous capture below documents spacing; its whole-machine percentages have been superseded:
+
+![Historical status spacing with synthetic readings](images/workspace-resources.png)
+
+Validation covers harness scope, shared/nested totals, unavailable/late responses, rounding, hidden
+polling, tab reuse and native/Flutter clicks. Run `harness_resources_test.dart`,
+`harness_monitor_test.dart` and `workspace_status_test.dart`. Set
+`HARNESS_WORKSPACE_CONTROLS_CAPTURE_DIR` for Flutter fixtures and `HARNESS_RESOURCE_CAPTURE_DIR` for
+native captures from `tool/check_swarm_titlebar.sh`. CLI ownership, telemetry and failure checks live
+in `harnessResources.spec.ts` and `harnessTelemetry.spec.ts`.
The layout takes cues from [Stats' combined view](https://github.com/exelban/stats/blob/master/Stats/Views/CombinedView.swift)
-and [Mini widget](https://github.com/exelban/stats/blob/master/Kit/Widgets/Mini.swift):
-compact independent modules and whole percentages. Harness keeps the dock to
-local hardware, a global harness count and account usage.
+and [Mini widget](https://github.com/exelban/stats/blob/master/Kit/Widgets/Mini.swift): compact modules
+and whole figures. Metric definitions and process-monitor references are documented in the
+[Harness Monitor README](../../store/agents/harness-monitor/README.md).
The optional Experimental creature sits after Store in a fixed 44pt slot.
Tim and eggs use bundled bitmap art; hovering opens a full-size preview without
@@ -228,7 +210,7 @@ truncate without moving or covering the close target. Clicking the model focuses
that pane and opens the same unified Models picker as Cmd-:, preserving the
existing target and availability guards.
-The footer shows subscription allowance **used**, alongside local hardware.
+The footer shows subscription allowance **used**, alongside harness resource totals.
Read the same deduplicated account rows as Models: each percentage uses the
limiting window and expires under the same rules. Compute used = 100 − remaining
and round to a whole percentage. Different accounts remain distinct. Unknown
diff --git a/desktop/lib/core/harness_resources.dart b/desktop/lib/core/harness_resources.dart
index 0859acd94..d9867ad3b 100644
--- a/desktop/lib/core/harness_resources.dart
+++ b/desktop/lib/core/harness_resources.dart
@@ -6,9 +6,14 @@ class HarnessResources {
this.memoryBytes,
this.cpuPercent,
this.processCount,
+ this.gpuPercent,
+ this.workspaceBytes,
+ this.workspacePath,
});
final double? memoryBytes, cpuPercent;
final int? processCount;
+ final double? gpuPercent, workspaceBytes;
+ final String? workspacePath;
factory HarnessResources.fromJson(Map<String, dynamic> json) {
double? number(String key) {
@@ -23,6 +28,11 @@ class HarnessResources {
memoryBytes: number('memoryBytes'),
cpuPercent: number('cpuPercent'),
processCount: count is int && count >= 0 ? count : null,
+ gpuPercent: number('gpuPercent'),
+ workspaceBytes: number('workspaceBytes'),
+ workspacePath: json['workspacePath'] is String
+ ? json['workspacePath'] as String
+ : null,
);
}
diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dart
index b765f080e..a5afc0461 100644
--- a/desktop/lib/screens/swarm_screen.dart
+++ b/desktop/lib/screens/swarm_screen.dart
@@ -52,8 +52,7 @@ import '../widgets/notification_inbox.dart';
import '../widgets/workspace_notifications_button.dart';
import '../state/harness_sessions.dart';
import '../state/harness_monitor.dart';
-import '../state/machine_resource_monitor.dart';
-import '../widgets/workspace_machine_resources.dart';
+import '../widgets/workspace_harness_resources.dart';
import '../state/harness_activity.dart';
import '../state/harness_attachments.dart';
import '../state/harness_placement.dart';
@@ -574,8 +573,6 @@ class _SwarmScreenState extends State<SwarmScreen> {
app.deviceFormCommand = _deviceFormCommand;
_pullRequest = WorkspacePullRequest(app)..addListener(_statusPrefsChanged);
_harnessMonitor = HarnessMonitor(app)..addListener(_monitorChanged);
- _machineResources = MachineResourceMonitor(app)
- ..addListener(_monitorChanged);
app.reviewSessionClose = _reviewSessionClose;
_keymap.addListener(_keymapChanged);
app.hasNavigationRail = false;
@@ -717,7 +714,6 @@ class _SwarmScreenState extends State<SwarmScreen> {
// Subscription usage is read ahead, so opening a menu shows it without waiting.
_modelsMenu!.start();
_harnessMonitor.start();
- _machineResources.start();
});
}
if (_menuHost) {
@@ -779,7 +775,6 @@ class _SwarmScreenState extends State<SwarmScreen> {
@override
void dispose() {
_harnessMonitor.dispose();
- _machineResources.dispose();
if (app.reviewSessionClose == _reviewSessionClose) {
app.reviewSessionClose = null;
}
@@ -1481,7 +1476,6 @@ class _SwarmScreenState extends State<SwarmScreen> {
}
late final HarnessMonitor _harnessMonitor;
- late final MachineResourceMonitor _machineResources;
void _monitorChanged() {
if (!mounted) return;
if (_menuHost) _syncNative();
@@ -1809,19 +1803,28 @@ class _SwarmScreenState extends State<SwarmScreen> {
'interactive': _shortcutsEnabled,
},
'machineResources': {
- 'text': _machineResources.label,
- 'label': _machineResources.detail,
- 'detail': _machineResources.detail,
+ 'text': _harnessMonitor.metricsLabel(),
+ 'label': _harnessMonitor.resourceDetail,
+ 'detail': _harnessMonitor.resourceDetail,
'segments': [
- {'text': _machineResources.metricsLabel()},
+ {'text': _harnessMonitor.metricsLabel()},
+ ],
+ 'noStorageSegments': [
+ {'text': _harnessMonitor.metricsLabel(storage: false)},
],
'compactSegments': [
- {'text': _machineResources.metricsLabel(gpu: false)},
+ {'text': _harnessMonitor.metricsLabel(gpu: false, storage: false)},
],
'minimalSegments': [
- {'text': _machineResources.metricsLabel(ram: false, gpu: false)},
+ {
+ 'text': _harnessMonitor.metricsLabel(
+ ram: false,
+ gpu: false,
+ storage: false,
+ ),
+ },
],
- 'interactive': false,
+ 'interactive': _shortcutsEnabled,
},
'footerCovered':
!_showWorkspaceFooter ||
@@ -7031,7 +7034,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
cell.width * 2,
resourceBudget * .4,
);
- final hardwareWidth = resourceBudget * .42;
+ final hardwareWidth = resourceBudget * .52;
final usageWidth = constraints.maxWidth < 1050
? 0.0
: resourceBudget * .22;
@@ -7115,9 +7118,12 @@ class _SwarmScreenState extends State<SwarmScreen> {
SizedBox(width: resourceGap),
ConstrainedBox(
constraints: BoxConstraints(maxWidth: hardwareWidth),
- child: WorkspaceMachineResources(
+ child: WorkspaceHarnessResources(
key: const ValueKey('workspace-machine-resources'),
- monitor: _machineResources,
+ monitor: _harnessMonitor,
+ onPressed: _shortcutsEnabled
+ ? _toggleHarnessControls
+ : null,
),
),
if (usageWidth > 0) ...[
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index 4dc178176..8ea3a498f 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -7035,7 +7035,7 @@ class AppNotifier extends ChangeNotifier {
if (!connection.isReady) return null;
final reply = await connection.request(
'machine_resources',
- payload: harnesses ? const {'harnesses': true} : const {},
+ payload: harnesses ? const {'harnesses': true, 'storage': true} : const {},
timeout: const Duration(seconds: 3),
);
if (!_machineDiscoveryCurrent(machine, revision, discoveryRevision) ||
diff --git a/desktop/lib/state/harness_monitor.dart b/desktop/lib/state/harness_monitor.dart
index 9053a5159..fa1981952 100644
--- a/desktop/lib/state/harness_monitor.dart
+++ b/desktop/lib/state/harness_monitor.dart
@@ -4,6 +4,8 @@ import 'package:flutter/foundation.dart';
import '../core/harness_resources.dart';
import '../core/models.dart';
+import '../shared/theme/workspace_bar_style.dart'
+ show workspaceBarGroupSeparator;
import 'app_state.dart';
import 'harness_sessions.dart';
@@ -15,6 +17,7 @@ class HarnessMonitor extends ChangeNotifier {
final _samples = <String, (MachineState, MachineHarnessResources)>{};
Timer? _timer;
bool _started = false, _disposed = false, _busy = false, _expanded = false;
+ final _receivedAt = <String, DateTime>{};
int _revision = 0;
List<HarnessSession> get sessions => harnessSessions(app, includeLive: true);
@@ -24,18 +27,26 @@ class HarnessMonitor extends ChangeNotifier {
HarnessResources? reading(HarnessSession row) {
final snapshot = _samples[row.machineId];
- return row.running && identical(snapshot?.$1, row.machine)
+ return row.running &&
+ identical(snapshot?.$1, row.machine) &&
+ _fresh(row.machineId)
? snapshot?.$2.agents[row.agent.id]
: null;
}
+ bool _fresh(String id) =>
+ _receivedAt[id] != null &&
+ DateTime.now().difference(_receivedAt[id]!) <=
+ const Duration(seconds: 45);
+
/// Shared-server RSS belongs to the server, not to each conversation.
/// Count it once per machine/profile and label it separately in the panel.
List<HarnessResources> get sharedReadings {
final rows = live;
return [
for (final entry in _samples.entries)
- if (identical(app.stateOf(entry.key), entry.value.$1))
+ if (identical(app.stateOf(entry.key), entry.value.$1) &&
+ _fresh(entry.key))
for (final shared in entry.value.$2.shared)
if (rows.any(
(row) =>
@@ -56,8 +67,77 @@ class HarnessMonitor extends ChangeNotifier {
String get label => 'Harnesses ${live.length}';
+ /// CPU percentages share a denominator (one core), not host capacities.
+ /// Missing sessions make a known sum a lower bound, never a complete total.
+ String metricsLabel({bool ram = true, bool gpu = true, bool storage = true}) {
+ final readings = [...live.map(reading), ...sharedReadings];
+ String total(
+ double? Function(HarnessResources) value,
+ String Function(double) format,
+ ) {
+ final known = readings
+ .map((r) => r == null ? null : value(r))
+ .whereType<double>()
+ .toList();
+ if (readings.isEmpty) return format(0);
+ if (known.isEmpty) return '—';
+ return '${known.length < readings.length ? '≥' : ''}${format(known.fold(0, (a, b) => a + b))}';
+ }
+
+ final cpu = total((r) => r.cpuPercent, (v) => '${v.round()}%');
+ final memory = total((r) => r.memoryBytes, _wholeBytes);
+ final graphics = total((r) => r.gpuPercent, (v) => '${v.round()}%');
+ return 'CPU $cpu'
+ '${ram ? '${workspaceBarGroupSeparator}RAM $memory' : ''}'
+ '${gpu ? '${workspaceBarGroupSeparator}GPU $graphics' : ''}'
+ '${storage ? '${workspaceBarGroupSeparator}SSD ${_storageLabel()}' : ''}';
+ }
+
+ static String _wholeBytes(double bytes) => bytes >= 1e9
+ ? '${(bytes / 1e9).round()} GB'
+ : '${(bytes / 1e6).round()} MB';
+
+ String _storageLabel() {
+ final folders = <String, Map<String, double?>>{};
+ var missing = false;
+ for (final row in live) {
+ final resource = reading(row), path = resource?.workspacePath;
+ if (path == null || resource?.workspaceBytes == null) {
+ missing = true;
+ continue;
+ }
+ (folders[row.machineId] ??= {})[path] = resource!.workspaceBytes;
+ }
+ var bytes = 0.0, count = 0;
+ for (final machine in folders.values) {
+ final included = <String>[];
+ for (final path
+ in machine.keys.toList()
+ ..sort((a, b) => a.length.compareTo(b.length))) {
+ if (included.any(
+ (parent) => path == parent || path.startsWith('$parent/'),
+ )) {
+ continue;
+ }
+ included.add(path);
+ count++;
+ bytes += machine[path]!;
+ }
+ }
+ if (live.isNotEmpty && count == 0) return '—';
+ return '${missing ? '≥' : ''}${_wholeBytes(bytes)}';
+ }
+
+ String get resourceDetail =>
+ '${live.length} running harnesses across connected machines.\n'
+ '${metricsLabel()}\n'
+ 'CPU: 100% is one core. RAM includes child processes and shared servers counted once; shared memory pages can overlap.\n'
+ 'GPU: summed process utilization; can exceed 100% across processes or devices. Unsupported counters are unavailable. Cloud inference is not local GPU usage.\n'
+ 'SSD: workspace disk space, shared and nested folders counted once per machine. Files remain after stopping.\n'
+ '≥ means a partial total. — means unavailable. Click to open Harness Monitor.';
+
String get detail =>
- '${live.length} running across connected machines. Click to view harnesses.\n'
+ '${live.length} running across connected machines. Click to open Harness Monitor.\n'
'${HarnessResources.explanation}${sharedLabel == null ? '' : '\n$sharedLabel, included once in the session monitor.'}';
void start() {
@@ -72,7 +152,7 @@ class HarnessMonitor extends ChangeNotifier {
if (_expanded == value) return;
_expanded = value;
_timer?.cancel();
- if (_started && _expanded && app.foreground.value) unawaited(refresh());
+ if (_started && app.foreground.value) unawaited(refresh());
}
void _inventoryChanged() {
@@ -85,6 +165,7 @@ class HarnessMonitor extends ChangeNotifier {
}).toList();
for (final id in removed) {
_samples.remove(id);
+ _receivedAt.remove(id);
}
if (removed.isNotEmpty) _revision++;
notifyListeners();
@@ -93,7 +174,10 @@ class HarnessMonitor extends ChangeNotifier {
void _environmentChanged() {
_revision++;
_timer?.cancel();
- if (_expanded && app.foreground.value) unawaited(refresh());
+ _samples.clear();
+ _receivedAt.clear();
+ notifyListeners();
+ if (app.foreground.value) unawaited(refresh());
}
Future<void> refresh() async {
@@ -117,13 +201,14 @@ class HarnessMonitor extends ChangeNotifier {
for (final (id, machine, result) in readings) {
if (result != null && identical(machine, app.stateOf(id))) {
_samples[id] = (machine, result);
+ _receivedAt[id] = DateTime.now();
}
}
notifyListeners();
} finally {
_busy = false;
- if (!_disposed && _started && _expanded && app.foreground.value) {
- _timer = Timer(const Duration(seconds: 3), refresh);
+ if (!_disposed && _started && app.foreground.value) {
+ _timer = Timer(Duration(seconds: _expanded ? 3 : 15), refresh);
}
}
}
diff --git a/desktop/lib/state/harness_monitor_controller.dart b/desktop/lib/state/harness_monitor_controller.dart
index 7c0e38d77..83e90d405 100644
--- a/desktop/lib/state/harness_monitor_controller.dart
+++ b/desktop/lib/state/harness_monitor_controller.dart
@@ -22,6 +22,43 @@ class HarnessMonitorController {
!_disposed && identical(app.stateOf(owner.machine.machineId), owner);
Future<String?> _open() async {
+ if (_disposed) return null;
+ // The footer has fleet scope. Reuse the tab even after focus moves to a
+ // different machine, including an offline monitor that is still open.
+ for (final tab in app.swarms) {
+ for (final pane in tab.panes) {
+ final machine = app.stateOf(pane.machineId);
+ final agent = machine?.agents
+ .where(
+ (a) =>
+ a.dsh == harnessMonitorId &&
+ (a.id == pane.agentId || a.id == pane.ownerAgentId),
+ )
+ .firstOrNull;
+ if (agent == null) continue;
+ app.selectSwarm(tab.id);
+ final owner = machine!;
+ final machineId = owner.machine.machineId;
+ try {
+ if (agent.isStopped &&
+ owner.connectionStatus == ConnectionStatus.connected) {
+ final result = await app.resumeAgent(machineId, agent.id);
+ if (!_current(owner)) return null;
+ if (result.error != null) return result.error;
+ }
+ if (!app.viewerPaneShown(machineId, agent.id)) {
+ await app.toggleViewerPane(machineId, agent.id);
+ if (!_current(owner)) return null;
+ }
+ app.showHarnessMonitorTable(machineId, agent.id);
+ } catch (_) {
+ return _current(owner)
+ ? 'Could not open Harness Monitor. Try again.'
+ : null;
+ }
+ return null;
+ }
+ }
final owner = app.ownedActionMachine;
if (owner == null) return 'Connect a machine to open Harness Monitor.';
if (!identical(_owner, owner)) {
diff --git a/desktop/lib/widgets/workspace_harness_resources.dart b/desktop/lib/widgets/workspace_harness_resources.dart
new file mode 100644
index 000000000..1eb48b6d0
--- /dev/null
+++ b/desktop/lib/widgets/workspace_harness_resources.dart
@@ -0,0 +1,63 @@
+import 'package:flutter/material.dart';
+
+import '../shared/theme/workspace_bar_style.dart';
+import '../state/harness_monitor.dart';
+import 'workspace_bar_control.dart';
+
+/// Every resource opens the same monitor. Hide whole groups at narrow widths.
+class WorkspaceHarnessResources extends StatelessWidget {
+ const WorkspaceHarnessResources({
+ super.key,
+ required this.monitor,
+ this.onPressed,
+ });
+ final HarnessMonitor monitor;
+ final VoidCallback? onPressed;
+
+ @override
+ Widget build(BuildContext context) => ListenableBuilder(
+ listenable: monitor,
+ builder: (context, _) => LayoutBuilder(
+ builder: (context, constraints) {
+ final cell = workspaceBarCellSizeOf(context).width;
+ var label = monitor.metricsLabel(
+ ram: false,
+ gpu: false,
+ storage: false,
+ );
+ for (final candidate in [
+ monitor.metricsLabel(),
+ monitor.metricsLabel(storage: false),
+ monitor.metricsLabel(gpu: false, storage: false),
+ ]) {
+ if (workspaceBarTextSizeOf(context, candidate, grouped: true).width +
+ cell * 2 <=
+ constraints.maxWidth) {
+ label = candidate;
+ break;
+ }
+ }
+ return WorkspaceBarControl(
+ label: monitor.resourceDetail,
+ tooltip: monitor.resourceDetail,
+ onPressed: onPressed,
+ builder: (context, emphasized) => Padding(
+ padding: EdgeInsets.symmetric(horizontal: cell),
+ child: SizedBox(
+ height: workspaceBarControlHeight(context),
+ child: Center(
+ widthFactor: 1,
+ child: Text.rich(
+ workspaceBarGroupTextSpan(label, cellWidth: cell),
+ maxLines: 1,
+ overflow: TextOverflow.clip,
+ style: workspaceBarTextStyle(emphasized: emphasized),
+ ),
+ ),
+ ),
+ ),
+ );
+ },
+ ),
+ );
+}
diff --git a/desktop/macos/Runner/SwarmTitlebar.swift b/desktop/macos/Runner/SwarmTitlebar.swift
index 02ed5677d..020542e5d 100644
--- a/desktop/macos/Runner/SwarmTitlebar.swift
+++ b/desktop/macos/Runner/SwarmTitlebar.swift
@@ -128,7 +128,7 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
}
private func sendTabAction(_ method: String, arguments: Any?) {
- guard ["daemon", "subscriptions", "focusedContext", "harnessControls", "machineControls", "modelControls", "select", "close", "new", "rename", "commands", "notifications", "notificationInbox", "openStatusHarness", "store", "sessions", "models", "addAgent", "newAgent", "newTerminal", "cloneAgent", "restartAgent", "shareAgent", "toggleViewer", "toggleComposer", "movePaneToTab", "runLocalModel", "splitRight", "splitDown", "zoomPane", "pinPane", "machineDestination", "machineAgent", "manageMachines", "machineList"].contains(method) else {
+ guard ["daemon", "subscriptions", "focusedContext", "harnessControls", "resourceMonitor", "machineControls", "modelControls", "select", "close", "new", "rename", "commands", "notifications", "notificationInbox", "openStatusHarness", "store", "sessions", "models", "addAgent", "newAgent", "newTerminal", "cloneAgent", "restartAgent", "shareAgent", "toggleViewer", "toggleComposer", "movePaneToTab", "runLocalModel", "splitRight", "splitDown", "zoomPane", "pinPane", "machineDestination", "machineAgent", "manageMachines", "machineList"].contains(method) else {
channel.invokeMethod(method, arguments: arguments)
return
}
@@ -1856,8 +1856,10 @@ private final class SwarmTabStrip: NSView {
statusBar.addSubview(harnessMonitorButton)
machineResourcesLabel.isBordered = false
machineResourcesLabel.textAlignment = .left
- machineResourcesLabel.setAccessibilityRole(.staticText)
- machineResourcesLabel.setAccessibilityLabel("Machine resources")
+ machineResourcesLabel.target = self
+ machineResourcesLabel.action = #selector(openHarnessMonitor)
+ machineResourcesLabel.setAccessibilityRole(.button)
+ machineResourcesLabel.setAccessibilityLabel("Harness resources — Open Harness Monitor")
machineResourcesLabel.isHidden = true
statusBar.addSubview(machineResourcesLabel)
pullRequestButton.isBordered = false
@@ -2084,7 +2086,7 @@ private final class SwarmTabStrip: NSView {
machineResourcesLabel.foreground = terminalForeground
machineResourcesLabel.contentPadding = harnessMonitorButton.contentPadding
machineResourcesLabel.groupGapCells = resourceGroupGapCells
- machineResourcesLabel.update(machineResourcesState, enabled: false)
+ machineResourcesLabel.update(machineResourcesState, enabled: actionsEnabled)
machineResourcesLabel.isHidden = machineResourcesState == nil
contextButton.font = barFont
contextButton.foreground = terminalForeground
@@ -2327,12 +2329,12 @@ private final class SwarmTabStrip: NSView {
let shareWidth = shareButton.isHidden ? 0 : min(shareButton.preferredWidth, available * 0.3)
let usageBudget = max(0, available - daemonWidth - shareWidth - cell * 4 - resourceGap * 2)
let monitorWidth = harnessMonitorButton.isHidden ? 0 : min(harnessMonitorButton.preferredWidth, usageBudget * 0.4)
- let hardwareBudget = usageBudget * 0.42
+ let hardwareBudget = usageBudget * 0.52
if var resource = machineResourcesState {
- for key in ["segments", "compactSegments", "minimalSegments"] {
+ for key in ["segments", "noStorageSegments", "compactSegments", "minimalSegments"] {
guard let segments = machineResourcesState?[key] else { continue }
resource["segments"] = segments
- machineResourcesLabel.update(resource, enabled: false)
+ machineResourcesLabel.update(resource, enabled: actionsEnabled)
if machineResourcesLabel.preferredWidth <= hardwareBudget { break }
}
}
diff --git a/desktop/test/harness_monitor_test.dart b/desktop/test/harness_monitor_test.dart
index b3694cc94..42e384ce5 100644
--- a/desktop/test/harness_monitor_test.dart
+++ b/desktop/test/harness_monitor_test.dart
@@ -157,6 +157,51 @@ void main() {
expect(app.resumes, 0);
});
+ test(
+ 'an existing stopped monitor reopens in the same tab after focus changes',
+ () async {
+ await app.harnessMonitor.open();
+ final monitorTab = app.activeSwarmId;
+ app.stateOf('m')!.agents = [
+ const Agent(
+ id: 'manager',
+ name: harnessMonitorName,
+ engine: 'opencode',
+ dsh: harnessMonitorId,
+ status: 'stopped',
+ ),
+ ];
+ app.newSwarm(name: 'Other work');
+ app.selectedMachineId = 'other';
+ final count = app.swarms.length;
+ expect(await app.harnessMonitor.open(), isNull);
+ expect(app.resumes, 1);
+ expect(app.activeSwarmId, monitorTab);
+ expect(app.swarms, hasLength(count));
+ expect(connection.creations, hasLength(1));
+ app.resumeThrows = true;
+ expect(
+ await app.harnessMonitor.open(),
+ 'Could not open Harness Monitor. Try again.',
+ );
+ },
+ );
+
+ test(
+ 'an existing offline monitor is selected without creating another one',
+ () async {
+ await app.harnessMonitor.open();
+ final monitorTab = app.activeSwarmId;
+ app.stateOf('m')!.connectionStatus = ConnectionStatus.disconnected;
+ app.newSwarm(name: 'Other work');
+ app.selectedMachineId = 'other';
+ expect(await app.harnessMonitor.open(), isNull);
+ expect(app.activeSwarmId, monitorTab);
+ expect(app.resumes, 0);
+ expect(connection.creations, hasLength(1));
+ },
+ );
+
test(
'Open refreshes the owning machine and reveals an existing tab',
() async {
@@ -196,79 +241,87 @@ void main() {
);
for (final nativeTabs in [false, true]) {
- testWidgets('management opens and reuses a DSH tab (native=$nativeTabs)', (
- tester,
- ) async {
- const channel = MethodChannel('harness/swarm_tabs');
- tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
- channel,
- (_) async => null,
- );
- addTearDown(
- () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
- channel,
- null,
- ),
- );
- await mount(tester, app, nativeTabs: nativeTabs);
- Future<void> open() async {
- if (nativeTabs) {
- tester.binding.defaultBinaryMessenger.handlePlatformMessage(
- channel.name,
- const StandardMethodCodec().encodeMethodCall(
- const MethodCall('harnessControls'),
- ),
- (_) {},
+ for (final resources in [false, true]) {
+ testWidgets(
+ 'footer opens and reuses monitor (native=$nativeTabs resources=$resources)',
+ (tester) async {
+ const channel = MethodChannel('harness/swarm_tabs');
+ tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
+ channel,
+ (_) async => null,
);
- } else {
- await openWorkspaceManagement(tester, 'harnesses');
- }
- await tester.pumpAndSettle();
- }
+ addTearDown(
+ () => tester.binding.defaultBinaryMessenger
+ .setMockMethodCallHandler(channel, null),
+ );
+ await mount(tester, app, nativeTabs: nativeTabs);
+ Future<void> open() async {
+ if (nativeTabs) {
+ tester.binding.defaultBinaryMessenger.handlePlatformMessage(
+ channel.name,
+ const StandardMethodCodec().encodeMethodCall(
+ MethodCall(resources ? 'resourceMonitor' : 'harnessControls'),
+ ),
+ (_) {},
+ );
+ } else if (resources) {
+ await tester.tap(
+ find.byKey(const ValueKey('workspace-machine-resources')),
+ );
+ } else {
+ await openWorkspaceManagement(tester, 'harnesses');
+ }
+ await tester.pumpAndSettle();
+ }
- await open();
- expect(app.activeSwarm.name, harnessMonitorName);
- expect(find.byType(WebPanePanel), findsOneWidget);
- expect(app.zoomedPaneId, app.panes.singleWhere((p) => p.isWeb).id);
- final count = app.swarms.length;
- 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.
- 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);
- expect(tester.takeException(), isNull);
- final monitorTab = app.activeSwarm;
- if (nativeTabs) {
- tester.binding.defaultBinaryMessenger.handlePlatformMessage(
- channel.name,
- const StandardMethodCodec().encodeMethodCall(
- MethodCall('close', {'id': monitorTab.id}),
- ),
- (_) {},
- );
- } else {
- final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);
- await mouse.addPointer(location: const Offset(1200, 700));
- await mouse.moveTo(
- tester.getCenter(find.byKey(ValueKey(monitorTab.id))),
- );
- await tester.pump();
- await tester.tap(
- find.byKey(ValueKey('tab-close:${monitorTab.id}')).hitTestable(),
- );
- await mouse.removePointer();
- }
- await tester.pumpAndSettle();
- expect(app.swarms, isNot(contains(monitorTab)));
- expect(connection.closes, isEmpty);
- expect(find.text('OK'), findsNothing);
- await tester.pumpWidget(const SizedBox());
- });
+ await open();
+ expect(app.activeSwarm.name, harnessMonitorName);
+ expect(find.byType(WebPanePanel), findsOneWidget);
+ expect(app.zoomedPaneId, app.panes.singleWhere((p) => p.isWeb).id);
+ 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.
+ 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);
+ expect(tester.takeException(), isNull);
+ final monitorTab = app.activeSwarm;
+ if (nativeTabs) {
+ tester.binding.defaultBinaryMessenger.handlePlatformMessage(
+ channel.name,
+ const StandardMethodCodec().encodeMethodCall(
+ MethodCall('close', {'id': monitorTab.id}),
+ ),
+ (_) {},
+ );
+ } else {
+ final mouse = await tester.createGesture(
+ kind: PointerDeviceKind.mouse,
+ );
+ await mouse.addPointer(location: const Offset(1200, 700));
+ await mouse.moveTo(
+ tester.getCenter(find.byKey(ValueKey(monitorTab.id))),
+ );
+ await tester.pump();
+ await tester.tap(
+ find.byKey(ValueKey('tab-close:${monitorTab.id}')).hitTestable(),
+ );
+ await mouse.removePointer();
+ }
+ await tester.pumpAndSettle();
+ expect(app.swarms, isNot(contains(monitorTab)));
+ expect(connection.closes, isEmpty);
+ expect(find.text('OK'), findsNothing);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+ }
}
}
diff --git a/desktop/test/harness_resources_test.dart b/desktop/test/harness_resources_test.dart
index 9b48e0f12..8a235bc4e 100644
--- a/desktop/test/harness_resources_test.dart
+++ b/desktop/test/harness_resources_test.dart
@@ -117,6 +117,35 @@ void main() {
expect(monitor.sharedLabel, isNull);
});
+ test('footer totals round bytes, include shared servers once, and deduplicate storage', () async {
+ final connection = _Connection();
+ final app = createApp(connected: true, connectionForTest: (_) => connection);
+ final monitor = HarnessMonitor(app);
+ addTearDown(monitor.dispose);
+ addTearDown(app.dispose);
+ app.machineStates['m']!.agents = [
+ const Agent(id: 'a0', name: 'First', terminalAvailable: true),
+ const Agent(id: 'b', name: 'Second', terminalAvailable: true),
+ ];
+ final data = connection.reply['harnesses'] as Map;
+ data['agents'] = [
+ {'agentId': 'a0', 'memoryBytes': 10.4e9, 'cpuPercent': 125.5,
+ 'gpuPercent': 24.4, 'workspaceBytes': 1.4e9, 'workspacePath': '/project'},
+ {'agentId': 'b', 'memoryBytes': 0.2e9, 'cpuPercent': 0,
+ 'gpuPercent': 0, 'workspaceBytes': 0.4e9, 'workspacePath': '/project/child'},
+ ];
+ data['shared'] = [
+ {'kind': 'codex', 'agentIds': ['a0', 'b'], 'memoryBytes': 0.4e9,
+ 'cpuPercent': 4.5, 'gpuPercent': 0},
+ ];
+ await monitor.refresh();
+ expect(monitor.metricsLabel(), 'CPU 130% RAM 11 GB GPU 24% SSD 1 GB');
+ app.machineStates['m']!.agents.add(
+ const Agent(id: 'unknown', name: 'Unknown', terminalAvailable: true));
+ expect(monitor.metricsLabel(), 'CPU ≥130% RAM ≥11 GB GPU ≥24% SSD ≥1 GB');
+ expect(monitor.resourceDetail, contains('Files remain after stopping'));
+ });
+
testWidgets(
'uses one machine request for every session; tokens are existing data',
(tester) async {
@@ -148,7 +177,7 @@ void main() {
); // Inventory appears without starting or opening anything.
await monitor.refresh();
expect(connection.calls, [
- {'type': 'machine_resources', 'harnesses': true},
+ {'type': 'machine_resources', 'harnesses': true, 'storage': true},
]);
expect(monitor.label, 'Harnesses 2');
expect(monitor.reading(monitor.live.first)!.processCount, 3);
@@ -160,7 +189,7 @@ void main() {
);
testWidgets(
- 'samples process trees only while the session manager is open and visible',
+ 'samples harness resources for the visible footer and stops while the app is hidden',
(tester) async {
final connection = _Connection();
final app = createApp(
@@ -172,25 +201,22 @@ void main() {
const Agent(id: 'a0', name: 'Work', terminalAvailable: true),
];
monitor.start();
- await tester.pump(const Duration(seconds: 30));
- expect(connection.calls, isEmpty);
- monitor.setExpanded(true);
await tester.pump();
expect(connection.calls, hasLength(1));
- await tester.pump(const Duration(seconds: 3));
+ await tester.pump(const Duration(seconds: 15));
expect(connection.calls, hasLength(2));
app.appLifecycleChanged(AppLifecycleState.hidden);
+ expect(monitor.metricsLabel(), 'CPU — RAM — GPU — SSD —');
await tester.pump(const Duration(minutes: 2));
expect(connection.calls, hasLength(2));
app.appLifecycleChanged(AppLifecycleState.resumed);
await tester.pump();
expect(connection.calls, hasLength(3));
- monitor.setExpanded(false);
- await tester.pump(const Duration(minutes: 2));
- expect(connection.calls, hasLength(3));
+ await tester.pump(const Duration(seconds: 15));
+ expect(connection.calls, hasLength(4));
monitor.dispose();
await tester.pump(const Duration(minutes: 2));
- expect(connection.calls, hasLength(3));
+ expect(connection.calls, hasLength(4));
app.dispose();
},
);
@@ -226,5 +252,4 @@ void main() {
expect(monitor.label, 'Harnesses 0');
},
);
-
}
diff --git a/desktop/test/workspace_status_test.dart b/desktop/test/workspace_status_test.dart
index 8938b0aae..a6c760f68 100644
--- a/desktop/test/workspace_status_test.dart
+++ b/desktop/test/workspace_status_test.dart
@@ -518,30 +518,20 @@ void main() {
if (native) {
expect(
updates.last['machineResources']['text'],
- 'CPU - RAM - GPU -',
+ 'CPU 0% RAM 0 MB GPU 0% SSD 0 MB',
);
expect(
updates.last['machineResources']['detail'],
- startsWith('Test host'),
+ contains('running harnesses across connected machines'),
);
- expect(updates.last['machineResources']['interactive'], isFalse);
- final done = Completer<void>();
- messenger.handlePlatformMessage(
- channel.name,
- const StandardMethodCodec().encodeMethodCall(
- const MethodCall('machineResources'),
- ),
- (_) => done.complete(),
- );
- await tester.pumpAndSettle();
- await done.future;
+ expect(updates.last['machineResources']['interactive'], isTrue);
} else {
- await tester.tap(
+ expect(
find.byKey(const ValueKey('workspace-machine-resources')),
+ findsOneWidget,
);
- await tester.pumpAndSettle();
}
- expect(find.text('Memory pressure'), findsNothing);
+ // Monitor navigation is exercised with its daemon fixture in harness_monitor_test.
expect(app.focusedPane, same(pane));
expect(app.panes, [pane]);
subscriptions.update([subscription('codex', 'bbbbbb', 27)]);
diff --git a/desktop/tool/swarm_titlebar_checks.swift b/desktop/tool/swarm_titlebar_checks.swift
index 9eddcffd6..bb6880f93 100644
--- a/desktop/tool/swarm_titlebar_checks.swift
+++ b/desktop/tool/swarm_titlebar_checks.swift
@@ -2592,27 +2592,28 @@ private extension SwarmTabStrip {
func checkHarnessMonitor() throws {
var state: [String: Any] = ["enabled": true,
"harnessMonitor": ["text": "Harnesses 10", "segments": [["text": "Harnesses 10"]], "label": "Harness Monitor", "detail": "View running harnesses", "interactive": true],
- "machineResources": ["text": "CPU 20% RAM 50% GPU 10%", "label": "M2 machine resources", "detail": "This computer's resources", "interactive": false,
- "segments": [["text": "CPU 20% RAM 50% GPU 10%"]],
- "compactSegments": [["text": "CPU 20% RAM 50%"]],
+ "machineResources": ["text": "CPU 20% RAM 10 GB GPU 10% SSD 1 GB", "label": "Harness resources", "detail": "Resources used by active harnesses", "interactive": true,
+ "segments": [["text": "CPU 20% RAM 10 GB GPU 10% SSD 1 GB"]],
+ "noStorageSegments": [["text": "CPU 20% RAM 10 GB GPU 10%"]],
+ "compactSegments": [["text": "CPU 20% RAM 10 GB"]],
"minimalSegments": [["text": "CPU 20%"]]],
"subscriptionUsage": ["text": "Claude 100% Codex 90%", "segments": [["text": "Claude 100% Codex 90%"]], "interactive": true],
"focusedContext": ["text": "M2 > openharness > main", "segments": [["text": "M2 > openharness > main"]], "interactive": true],
"tabs": [["id": "work", "name": "Work"]], "activeId": "work"]
var calls: [String] = []
emit = { method, _ in calls.append(method) }
- for width in [CGFloat(360), CGFloat(520), CGFloat(1280)] {
+ for width in [CGFloat(360), CGFloat(520), CGFloat(760), CGFloat(1280)] {
setFrameSize(NSSize(width: width, height: 40))
update(state)
try checkTitlebar(!harnessMonitorButton.isHidden && harnessMonitorButton.isEnabled &&
harnessMonitorButton.frame.minX > 0 && harnessMonitorButton.frame.width > 0 &&
harnessMonitorButton.frame.maxX <= contextButton.frame.minX,
"Resource monitor stays at bottom left without overlapping context at width \(width)")
- try checkTitlebar(!machineResourcesLabel.isHidden && !machineResourcesLabel.isEnabled &&
- machineResourcesLabel.accessibilityRole() == .staticText &&
+ try checkTitlebar(!machineResourcesLabel.isHidden && machineResourcesLabel.isEnabled &&
+ machineResourcesLabel.accessibilityRole() == .button &&
machineResourcesLabel.frame.minX >= harnessMonitorButton.frame.maxX &&
machineResourcesLabel.frame.maxX <= contextButton.frame.minX,
- "Read-only hardware never overlaps count or focused context at width \(width)")
+ "Harness resources never overlap count or focused context at width \(width): hidden=\(machineResourcesLabel.isHidden), enabled=\(machineResourcesLabel.isEnabled), role=\(String(describing: machineResourcesLabel.accessibilityRole())), resources=\(machineResourcesLabel.frame), count=\(harnessMonitorButton.frame), context=\(contextButton.frame)")
try checkTitlebar(harnessMonitorButton.accessibilityLabel() == "Harness Monitor",
"The resource counter names its action for VoiceOver")
try checkTitlebar(subscriptionUsageButton.isHidden == (width < 1050),
@@ -2627,12 +2628,12 @@ private extension SwarmTabStrip {
}
machineResourcesLabel.performClick(nil)
harnessMonitorButton.performClick(nil)
- try checkTitlebar(calls == ["resourceMonitor"], "Only the session count opens a panel; hardware stays read-only")
+ try checkTitlebar(calls == ["resourceMonitor", "resourceMonitor"], "Count and every resource open the same Harness Monitor tab")
state["enabled"] = false
update(state)
harnessMonitorButton.performClick(nil)
machineResourcesLabel.performClick(nil)
- try checkTitlebar(calls.count == 1, "A covered or modal footer cannot open the session monitor")
+ try checkTitlebar(calls.count == 2, "A covered or modal footer cannot open the session monitor")
update([:])
try checkTitlebar(harnessMonitorButton.isHidden && !harnessMonitorButton.isEnabled && machineResourcesLabel.isHidden && !machineResourcesLabel.isEnabled,
"Clearing workspace state clears the counter, hardware and actions")
diff --git a/store/agents/harness-monitor/AGENTS.md b/store/agents/harness-monitor/AGENTS.md
index 4b80968f5..5f2f87b86 100644
--- a/store/agents/harness-monitor/AGENTS.md
+++ b/store/agents/harness-monitor/AGENTS.md
@@ -1,7 +1,8 @@
# Harness Monitor
You are the optional assistant in 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
+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
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.
@@ -28,13 +29,15 @@ Rules and pins live in `~/.config/harness/policy.jsonc`; preserve comments when
A timed-out resume 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 the process-tree percentage reported by ps,
-whose averaging varies by OS. Last active comes from real daemon conversation activity, not file mtime.
+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
+includes existing workspace files and remains when a session stops. Last active comes from real
+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. The viewer offers a model choice before showing the
-assistant; users can choose another model with OpenCode's `/models` command.
+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.
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 2c559e751..255cf35bd 100644
--- a/store/agents/harness-monitor/README.md
+++ b/store/agents/harness-monitor/README.md
@@ -1,52 +1,77 @@
# Harness Monitor
-The dock opens one reusable Harness Monitor tab. Its DSH viewer starts as a full-width session table;
-**Ask assistant** reveals its OpenCode terminal beside it. No prompt is submitted when the table opens.
-
-The default columns are Harness, Status, Agent, Machine, Project, Branch, CPU %, RAM, Tokens and Last
-active, followed by **Open** and **×**. Headers sort; drag their separators to resize. Columns offers
-Model, PID, Harness ID, Conversation ID and Folder. Search covers metadata. Names and actions remain visible while
-scrolling horizontally. Refreshes preserve selection, controls, column widths and scroll. Arrow keys
-select and Enter opens. Engine images are copied from the desktop's existing icon assets; status marks
-and the reduced-motion-aware spinner follow its notification/tab/pane activity marks.
-
-Open navigates to an existing session or resumes stopped work through the app's receipt coordinator.
-× stops the owning daemon's validated process, retaining history and the saved DSH/runtime settings.
-The daemon reports whether resume restores a conversation, a shell or a fresh conversation. Remote
-machines use the same paired bridge and lifecycle APIs. Cached offline rows remain visible with disabled
-actions. Unknown readings show a dash. Older daemons need updating for activity and resource readings.
-
-CPU uses the daemon's shared process sampler, measuring interval use; multiple cores can
-exceed 100%. RAM is subtree resident memory and can double-count shared pages. Token counts are the
-owning daemon's conversation ledger. Last active is conversation activity, never file mtime.
-
-**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 automatic
-cleanup 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/`.
-
-OpenCode defaults both `model` and `small_model` to
-`opencode/muse-spark-1.3-contributor-free`. [OpenCode Zen](https://opencode.ai/docs/zen/) currently lists
-this as a limited-time free offer. **Contributor permits Meta to train on prompts and responses.**
-The first assistant choice discloses this and offers choosing another model with `/models`. Zen login
-may be needed. There is no automatic paid fallback. Existing sessions retain their saved runtime and
-model configuration; changing the package default does not retarget them.
-
-`npm test` runs with isolated policy/state fixtures. Browser review: `node test/preview.mjs` serves
-synthetic sessions and records simulated actions; it cannot touch real harnesses.
+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).
+
+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.
+
+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.
+
+## Metric definitions
+
+| Metric | Meaning and availability |
+| --- | --- |
+| CPU % | Interval CPU across owned processes and children; 100% is one core, so totals can exceed 100%. macOS and Linux. The first sample is unknown. |
+| RAM | Process-tree resident memory, in rounded MB/GB. Shared pages can overlap. Nested harness roots are excluded from their parent. Shared Codex servers appear separately and count once. |
+| GPU % / GPU memory | Attributable NVIDIA process utilization and compute allocations on supported Linux drivers. Summed utilization can exceed 100% across processes or devices. macOS and unsupported drivers show —. Cloud inference is not local GPU use. |
+| Storage / footer SSD | Allocated workspace disk space, including pre-existing files, from bounded du reads cached for one minute. Shared and nested canonical folders count once per machine in totals. Stopping does not release this space. SSD is a display label, not a hardware-media probe. |
+| Disk read/s / write/s | Physical process-tree I/O deltas from Linux /proc/<pid>/io. Restricted counters, resets and macOS show —. |
+| Transcript | Individual conversation-file size when reported. Shared databases show —. |
+| Tokens | Conversation input plus output, with cached input counted once. Claude, Codex and OpenCode use the existing incremental daemon ledger. Other frameworks remain visible with unavailable token fields. |
+| Input / output / cached input | Input includes cache reads/writes. Cached input is a subset, not an extra charge. Reasoning is included in output once. |
+| Tokens/min | Recent change in conversation totals across distinct ledger updates, measured using local receipt time. Includes input/cache; not model generation speed. Session changes, counter resets or stale updates clear it. |
+| Last active | Daemon conversation activity, not filesystem modification time. |
+
+Model, framework, machine, project, branch, folder, process count, start time and identity columns
+provide context. There is no invented dollar cost: subscription plans, caching and provider prices
+cannot be inferred reliably from total tokens.
+
+Totals describe the shown sessions and their shared servers. ≥ marks partial totals; — means
+unavailable, never measured zero. Footer totals cover the running harnesses in its count across
+connected owned machines. CPU/GPU use whole percentages; RAM/SSD use whole MB/GB (10.4 GB → 10 GB).
+They do not include unrelated applications or whole-machine utilization.
+
+The viewer polls local inventory every four seconds and linked machines every fifteen seconds while
+visible. The foreground desktop footer samples every fifteen seconds; hidden apps clear readings and
+stop polling. The daemon coalesces process reads, verifies PID birth identity, bounds NVIDIA commands
+and directory walks, and keeps telemetry off the terminal-input queue. No extra transcript scan is
+started by the table or footer. Older daemons retain basic inventory but require updating for new
+metrics. Identity and all stop actions remain machine-scoped through the paired bridge.
+
+## Design references and checks
+
+[Activity Monitor](https://support.apple.com/guide/activity-monitor/view-information-about-processes-actmntr1001/mac)
+informs sortable columns, filtering, a focused inspector and an explicit stop review.
+[btop](https://github.com/aristocratos/btop) informs process-tree accounting, resource sorting and
+pausing display updates. This monitor adds conversation usage and machine identity to those patterns.
+GPU and I/O definitions follow [NVIDIA's process telemetry](https://docs.nvidia.com/deploy/nvidia-smi/index.html)
+and [Linux procfs](https://www.kernel.org/doc/html/latest/filesystems/proc.html).
+
+`npm test` uses isolated policy/state fixtures. `node test/preview.mjs` serves synthetic sessions and
+simulated stops, without a daemon bridge or model call. Daemon checks live in harnessResources,
+harnessTelemetry, agentTokenUsage and backendSocket specs. Desktop tests cover footer scope,
+rounding, hidden polling and tab reuse; `tool/check_swarm_titlebar.sh` checks native clicks/layout.
+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.
+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.
## Credit and stewardship
-Built by Autonomous for Harness, MIT. See [LICENSE](LICENSE). Process identity and lifecycle belong to
-the Harness CLI; the table, cleanup proposals and `hps` live in this package. Engine artwork is reused
-from the desktop; attribution is included beside the copied icons.
+Built by Autonomous for Harness, MIT. See [LICENSE](LICENSE). The Harness CLI owns process identity,
+telemetry and lifecycle; this package owns the table and hps. Engine artwork is reused from the
+desktop; attribution is included beside the copied icons.
diff --git a/store/agents/harness-monitor/harness.json b/store/agents/harness-monitor/harness.json
index 8a745e959..2eec0b840 100644
--- a/store/agents/harness-monitor/harness.json
+++ b/store/agents/harness-monitor/harness.json
@@ -4,7 +4,7 @@
"name": "Harness Monitor",
"category": "Compute",
"author": "Autonomous",
- "description": "Manage sessions across your machines in a sortable table. Open sessions, stop processes while keeping history, and ask an optional OpenCode assistant to help review cleanup.",
+ "description": "Inspect active harnesses across your machines. Sort CPU, RAM, GPU, storage and conversation usage, inspect processes, and stop selected work while keeping history and files.",
"engine": "opencode",
"workspace": {
"template": "template",
diff --git a/store/agents/harness-monitor/lib/actions.mjs b/store/agents/harness-monitor/lib/actions.mjs
index c24ad1501..242ca82ce 100644
--- a/store/agents/harness-monitor/lib/actions.mjs
+++ b/store/agents/harness-monitor/lib/actions.mjs
@@ -32,7 +32,7 @@ export async function pause(row, { policy = normalizePolicy({}), force = false,
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.')
}
- const reply = await rpc(row.machineId, 'agent_delete', { agentId: row.agentId })
+ 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) }
diff --git a/store/agents/harness-monitor/lib/bridge.mjs b/store/agents/harness-monitor/lib/bridge.mjs
index 53618ab17..d79e50979 100644
--- a/store/agents/harness-monitor/lib/bridge.mjs
+++ b/store/agents/harness-monitor/lib/bridge.mjs
@@ -175,10 +175,11 @@ export async function withBridge(machineId, fn, { env = process.env, timeoutMs =
/** The fleet as the daemon sees it, for one machine — on the kept session. A kept socket that has
* gone quiet (the daemon behind it restarted without closing it) is dropped and the read retried
* ONCE on a fresh one before the machine is reported silent. */
-export async function listAgents(machineId, options = {}) {
+export async function listInventory(machineId, options = {}) {
const ask = async ({ session }) => {
const reply = await session.rpc('agents_list', { includeStopped: true, monitor: true })
- return Array.isArray(reply.agents) ? reply.agents : []
+ return { agents: Array.isArray(reply.agents) ? reply.agents : [],
+ shared: Array.isArray(reply.sharedResources) ? reply.sharedResources : [], sampledAt: reply.sampledAt ?? null }
}
const first = await bridgeSession(machineId, options)
try {
@@ -192,6 +193,10 @@ export async function listAgents(machineId, options = {}) {
}
}
+export async function listAgents(machineId, options = {}) {
+ return (await listInventory(machineId, options)).agents
+}
+
/** A single owner RPC. Only reads above reconnect/retry; callers reconcile uncertain writes by receipt. */
export async function request(machineId, type, payload = {}, options = {}) {
const { session } = await bridgeSession(machineId, options)
diff --git a/store/agents/harness-monitor/lib/inventory.mjs b/store/agents/harness-monitor/lib/inventory.mjs
index 9fc156145..244aa1106 100644
--- a/store/agents/harness-monitor/lib/inventory.mjs
+++ b/store/agents/harness-monitor/lib/inventory.mjs
@@ -2,7 +2,7 @@
import { homedir } from 'node:os'
import { basename, dirname } from 'node:path'
import { existsSync } from 'node:fs'
-import { listAgents, machinesReport } from './bridge.mjs'
+import { listInventory, machinesReport } from './bridge.mjs'
import { humanIdle } from './policy.mjs'
export function parseModel(selected) {
@@ -60,6 +60,21 @@ export function mergeRows(agents, { state = {}, machine = null, local = true, no
rssBytes: online ? stopped ? 0 : reading(monitor?.rssBytes) : null,
cpu: online ? stopped ? 0 : reading(monitor?.cpu) : null,
enginePid: online && !stopped ? reading(monitor?.pid) : null,
+ live: !stopped && (terminalAvailable || agent.launch?.state === 'starting'),
+ sampledAt: time(monitor?.sampledAt),
+ processCount: online && !stopped ? reading(monitor?.processCount) : null,
+ gpuMemoryBytes: online && !stopped ? reading(monitor?.gpuMemoryBytes) : null,
+ gpuPercent: online && !stopped ? reading(monitor?.gpuPercent) : null,
+ diskReadBytesPerSecond: online && !stopped ? reading(monitor?.diskReadBytesPerSecond) : null,
+ diskWriteBytesPerSecond: online && !stopped ? reading(monitor?.diskWriteBytesPerSecond) : null,
+ workspaceBytes: reading(monitor?.workspaceBytes), workspacePath: monitor?.workspacePath ?? cwd, workspaceSampledAt: time(monitor?.workspaceSampledAt),
+ transcriptBytes: reading(monitor?.transcriptBytes),
+ processes: online && !stopped && Array.isArray(monitor?.processes) ? monitor.processes : [],
+ tokenUpdatedAt: time(agent.tokenUsage?.updatedAt),
+ inputTokens: reading(agent.tokenUsage?.inputTokens), outputTokens: reading(agent.tokenUsage?.outputTokens),
+ cachedTokens: reading(agent.tokenUsage?.cachedTokens),
+ linesAdded: reading(agent.outputStats?.linesAdded), linesRemoved: reading(agent.outputStats?.linesRemoved),
+ parentAgentId: agent.parentAgentId ?? null,
tokens: reading(agent.tokenUsage?.totalTokens), dsh: agent.dsh ?? null, dshName: agent.dshName ?? null,
verdict: agent.verdict?.ready ?? null,
machine: machine?.name ?? 'This machine', machineId: machine?.machineId ?? null,
@@ -74,7 +89,7 @@ export function mergeRows(agents, { state = {}, machine = null, local = true, no
export async function collect({
state = {}, now = Date.now(), includeRemote = true, timeoutMs = 8000, home = homedir(),
remoteIntervalMs = 15_000, remote = { at: 0, answers: new Map() },
- reportMachines = machinesReport, agentsFor = listAgents,
+ reportMachines = machinesReport, agentsFor = null, inventoryFor = listInventory,
} = {}) {
const report = await reportMachines()
const machines = report.machines.filter(m => includeRemote || m.current)
@@ -84,7 +99,11 @@ export async function collect({
const previouslyOnline = remote.online ??= new Set()
const due = remoteIntervalMs <= 0 || !remote.at || now - remote.at >= remoteIntervalMs
await Promise.all(machines.filter(m => m.online && (m.current || due || !answers.has(m.machineId) || !previouslyOnline.has(m.machineId) || failed.has(m.machineId))).map(async machine => {
- try { answers.set(machine.machineId, await agentsFor(machine.machineId, { timeoutMs })); failed.delete(machine.machineId) }
+ try {
+ const answer = agentsFor ? { agents: await agentsFor(machine.machineId, { timeoutMs }), shared: [] }
+ : await inventoryFor(machine.machineId, { timeoutMs })
+ answers.set(machine.machineId, { ...answer, receivedAt: now }); failed.delete(machine.machineId)
+ }
catch (error) { failed.add(machine.machineId); problems.push({ machine: machine.name, error: error.message }) }
}))
if (due) remote.at = now
@@ -95,12 +114,41 @@ export async function collect({
remote.machines = machines
}
const visibleMachines = report.error ? (remote.machines ?? []) : machines
- const rows = visibleMachines.flatMap(machine => mergeRows(answers.get(machine.machineId) ?? [], {
+ const rows = visibleMachines.flatMap(machine => mergeRows(answers.get(machine.machineId)?.agents ?? answers.get(machine.machineId) ?? [], {
state, machine, local: machine.current, online: !report.error && machine.online && !remote.failed.has(machine.machineId), now, home,
}))
+ const shared = visibleMachines.flatMap(machine => {
+ const answer = answers.get(machine.machineId)
+ const online = !report.error && machine.online && !failed.has(machine.machineId)
+ return (answer?.shared ?? []).map((resource, index) => ({
+ id: rowId(machine.machineId, `shared-${resource.kind}-${index}`), machine: machine.name, machineId: machine.machineId,
+ name: `Shared ${resource.kind === 'codex' ? 'Codex' : resource.kind} server`, agentIds: resource.agentIds ?? [], online,
+ rssBytes: online ? reading(resource.memoryBytes) : null, cpu: online ? reading(resource.cpuPercent) : null,
+ gpuMemoryBytes: online ? reading(resource.gpuMemoryBytes) : null, processCount: online ? reading(resource.processCount) : null,
+ gpuPercent: online ? reading(resource.gpuPercent) : null,
+ processes: online ? resource.processes ?? [] : [], sampledAt: time(answer.sampledAt),
+ }))
+ })
+ // Token velocity uses distinct ledger updates over the last minute, never the
+ // viewer's polling frequency. Conversation changes and counter resets start anew.
+ const history = remote.tokens ??= new Map()
+ for (const row of rows) {
+ const samples = history.get(row.id) ?? []
+ const last = samples.at(-1)
+ if (!row.online || !row.live || row.tokens == null || !row.tokenUpdatedAt) { row.tokensPerMinute = null; history.delete(row.id); continue }
+ if (last && (last.session !== row.sessionId || last.tokens > row.tokens || row.tokenUpdatedAt < last.sourceAt || now - last.at > 60_000)) samples.length = 0
+ // Measure elapsed time on this viewer, not by comparing clocks on two machines.
+ if (samples.at(-1)?.sourceAt !== row.tokenUpdatedAt) samples.push({ at: now, sourceAt: row.tokenUpdatedAt, tokens: row.tokens, session: row.sessionId })
+ while (samples.length > 2 && samples[1].at < now - 60_000) samples.shift()
+ const first = samples[0], latest = samples.at(-1)
+ row.tokensPerMinute = first && latest.at > first.at && now - latest.at <= 60_000
+ ? (latest.tokens - first.tokens) * 60_000 / (latest.at - first.at) : null
+ history.set(row.id, samples)
+ }
+ for (const id of history.keys()) if (!rows.some(row => row.id === id)) history.delete(id)
for (const machine of visibleMachines.filter(m => !m.online)) problems.push({ machine: machine.name, error: 'Offline — showing the last known sessions.' })
rows.sort((a, b) => (a.idleMs ?? Infinity) - (b.idleMs ?? Infinity) || a.id.localeCompare(b.id))
- return { rows, machines: visibleMachines, problems, observedAt: now, degraded: problems.length > 0 }
+ return { rows, shared, machines: visibleMachines, problems, observedAt: now, degraded: problems.length > 0 }
}
export function summarize(rows) {
diff --git a/store/agents/harness-monitor/store.json b/store/agents/harness-monitor/store.json
index 616b45d39..0ed7584ff 100644
--- a/store/agents/harness-monitor/store.json
+++ b/store/agents/harness-monitor/store.json
@@ -1,6 +1,6 @@
{
"license": "MIT",
- "tagline": "Manage sessions across your machines",
+ "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.",
diff --git a/store/agents/harness-monitor/test/actions.test.mjs b/store/agents/harness-monitor/test/actions.test.mjs
index 1d9289fde..8d78a8e1b 100644
--- a/store/agents/harness-monitor/test/actions.test.mjs
+++ b/store/agents/harness-monitor/test/actions.test.mjs
@@ -13,7 +13,7 @@ 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 } } })
assert.equal(result.ok, true)
- assert.deepEqual(calls, [['remote', 'agent_delete', { agentId: 'a1' }]])
+ 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]) {
diff --git a/store/agents/harness-monitor/test/inventory.test.mjs b/store/agents/harness-monitor/test/inventory.test.mjs
index ca7b1c4ed..8614f10fe 100644
--- a/store/agents/harness-monitor/test/inventory.test.mjs
+++ b/store/agents/harness-monitor/test/inventory.test.mjs
@@ -64,3 +64,30 @@ test('model and home parsing preserve provider IDs and directory boundaries', ()
assert.deepEqual(parseModel('runtime-v1:a1:opencode:opencode/muse-spark-1.3-contributor-free@auto'), { model: 'opencode/muse-spark-1.3-contributor-free', effort: 'auto' })
assert.equal(tilde(HOME + 'other/x', HOME), HOME + 'other/x'); assert.equal(tilde(HOME + '/x', HOME), '~/x')
})
+
+test('resource data and shared servers retain owning machine scope', async () => {
+ const result = await collect({ reportMachines: async () => ({ machines: [{ ...machine, online: true }] }),
+ inventoryFor: async () => ({ agents: [agent({ monitor: { activity: 'working', activityKnown: true, gpuPercent: 35, gpuMemoryBytes: 900, workspaceBytes: 1200, processCount: 2 } })],
+ shared: [{ kind: 'codex', agentIds: ['a1'], memoryBytes: 300, cpuPercent: 4 }] }) })
+ assert.equal(result.rows[0].gpuPercent, 35)
+ assert.equal(result.rows[0].workspaceBytes, 1200)
+ assert.equal(result.rows[0].live, true)
+ assert.equal(result.shared[0].machineId, 'm1')
+ assert.equal(result.shared[0].rssBytes, 300)
+})
+test('token velocity uses fresh ledger updates, survives clock skew, and resets on conversation changes', async () => {
+ let tokenCount = 100, sourceTime = 9_000_000, sessionId = 's1', now = 100_000
+ const remote = { at: 0, answers: new Map() }
+ const options = { remote, remoteIntervalMs: 0, reportMachines: async () => ({ machines: [{ ...machine, online: true }] }),
+ agentsFor: async () => [agent({ sessionId, tokenUsage: { totalTokens: tokenCount, updatedAt: sourceTime } })] }
+ const read = async () => (await collect({ ...options, now })).rows[0].tokensPerMinute
+ assert.equal(await read(), null)
+ now += 4000; assert.equal(await read(), null)
+ now += 6000; sourceTime += 10000; tokenCount += 1000
+ assert.equal(await read(), 6000)
+ now += 4000; assert.equal(await read(), 6000)
+ sessionId = 'new'; assert.equal(await read(), null)
+ now += 10000; sourceTime += 10000; tokenCount = 1; assert.equal(await read(), null)
+ now += 120000; sourceTime += 120000; tokenCount += 1000; assert.equal(await read(), null)
+ now += 10000; sourceTime += 10000; tokenCount += 1000; assert.equal(await read(), 6000)
+})
diff --git a/store/agents/harness-monitor/test/preview.mjs b/store/agents/harness-monitor/test/preview.mjs
index 5be82698c..b9938418b 100644
--- a/store/agents/harness-monitor/test/preview.mjs
+++ b/store/agents/harness-monitor/test/preview.mjs
@@ -10,20 +10,20 @@ process.env.HARNESS_MONITOR_STATE = join(workspace, 'state')
const names = ['Replace Harness menu icon', 'Clarify completed-task form logic', 'Local debug', 'Ship workspace search', 'Review terminal reconnect', 'Add project browser', 'Render report', 'Fix session recovery']
const activities = ['working', 'needsInput', 'done', 'idle', 'working', 'idle', 'failed', 'idle']
const engines = ['codex', 'claude', 'opencode', 'cursor']
-const rows = Array.from({ length: 202 }, (_, i) => mergeRows([{
+const rows = Array.from({ length: Number(process.env.PREVIEW_ROWS || 24) }, (_, i) => mergeRows([{
id: 'session-' + i, sessionId: 'conversation-' + i, name: names[i % names.length] + (i > 7 ? ' ' + (i + 1) : ''),
engine: engines[i % engines.length], status: i % 7 === 6 ? 'stopped' : 'active',
terminal: { available: true }, resumeMode: 'conversation', launch: { state: 'ready' },
project: { name: i % 2 ? 'openharness' : 'autonomous-harness', cwd: '/home/demo/code/openharness', branch: i % 3 ? 'fix/session-recovery' : 'main' },
- selectedModel: i % 2 ? 'muse-spark-1.3-contributor-free' : 'gpt-6',
+ selectedModel: ['gpt-6', 'claude-sonnet-4-6', 'muse-spark-1.3-contributor-free', 'auto'][i % 4],
createdAt: new Date(Date.now() - 86400000 * 3).toISOString(), updatedAt: new Date(Date.now() - i * 85000).toISOString(),
- tokenUsage: { totalTokens: i % 3 ? 57800000 : 3500000 },
- monitor: { activity: activities[i % activities.length], activityKnown: true, cpu: i % 6 ? 3.4 : null, rssBytes: (i % 6 + 1) * 260 * 1024 ** 2, pid: 3400 + i },
-}], { machine: { machineId: i % 2 ? 'office' : 'm2', name: i % 2 ? 'office' : 'M2' }, local: false, online: i % 17 !== 16 })[0])
+ tokenUsage: { totalTokens: i % 3 ? 578000 : 3500000, inputTokens: i % 3 ? 420000 : 3200000, outputTokens: i % 3 ? 158000 : 300000, cachedTokens: i % 3 ? 190000 : 2100000, updatedAt: new Date().toISOString() },
+ monitor: { activity: activities[i % activities.length], activityKnown: true, cpu: [126, 3, 0, 12, 64, 0][i % 6], rssBytes: (i % 6 + 1) * 460 * 1024 ** 2, pid: 3400 + i, processCount: 2, gpuPercent: i % 2 ? 6 : null, gpuMemoryBytes: i % 2 ? 2400000000 : null, workspaceBytes: (i % 3 + 1) * 1700000000, workspacePath: '/home/demo/project-' + (i % 3), transcriptBytes: 2400000, sampledAt: new Date().toISOString(), processes: [{ pid: 3400 + i, parent: 1, cpuPercent: [126, 3, 0, 12, 64, 0][i % 6], memoryBytes: (i % 6 + 1) * 460 * 1024 ** 2 - 80000000 }, { pid: 4400 + i, parent: 3400 + i, cpuPercent: 0, memoryBytes: 80000000 }] },
+}], { 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, problems: [], machines: [] }),
+ 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', activity: 'stopped', canStop: false, cpu: 0, rssBytes: 0 })
+ 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.' }) },
})
diff --git a/store/agents/harness-monitor/test/table.test.mjs b/store/agents/harness-monitor/test/table.test.mjs
index ac50e67ee..280bf82a5 100644
--- a/store/agents/harness-monitor/test/table.test.mjs
+++ b/store/agents/harness-monitor/test/table.test.mjs
@@ -1,15 +1,15 @@
import assert from 'node:assert/strict'
import { test } from 'node:test'
-import { visibleRows, memory, number, age } from '../viewer/table.js'
+import { visibleRows, memory, number, age, storageTotal, sumReading, formatValue } from '../viewer/table.js'
const rows = [
{ id: 'm1/a', name: 'Agent 10', cpu: 5, activity: 'working', branch: 'fix/hello', machine: 'office' },
{ id: 'm2/a', name: 'Agent 2', cpu: 0, activity: 'idle', branch: 'main', machine: 'studio' },
- { id: 'm1/b', name: 'Unknown', cpu: null, activity: 'offline', branch: 'main', machine: 'office' },
+ { id: 'm1/b', name: 'Unknown', cpu: null, activity: 'offline', live: true, online: false, branch: 'main', machine: 'office' },
]
test('sort is stable, numeric and keeps unknown measurements last in either direction', () => {
- assert.deepEqual(visibleRows(rows, { sort: 'cpu', direction: -1 }).map(r => r.cpu), [5, 0, null])
- assert.deepEqual(visibleRows(rows, { sort: 'cpu', direction: 1 }).map(r => r.cpu), [0, 5, null])
- assert.deepEqual(visibleRows(rows, { sort: 'name', direction: 1 }).map(r => r.name), ['Agent 2', 'Agent 10', 'Unknown'])
+ assert.deepEqual(visibleRows(rows, { filter: 'all', sort: 'cpu', direction: -1 }).map(r => r.cpu), [5, 0, null])
+ assert.deepEqual(visibleRows(rows, { filter: 'all', sort: 'cpu', direction: 1 }).map(r => r.cpu), [0, 5, null])
+ assert.deepEqual(visibleRows(rows, { filter: 'all', sort: 'name', direction: 1 }).map(r => r.name), ['Agent 2', 'Agent 10', 'Unknown'])
assert.equal(rows[0].name, 'Agent 10')
})
test('search matches metadata and combines with plain status filters', () => {
@@ -22,3 +22,19 @@ test('formatters distinguish zero from unknown and handle future timestamps', ()
assert.equal(number(null), '—'); assert.equal(number(0), '0')
assert.equal(age(null), '—'); assert.equal(age(1100, 1000), 'now')
})
+
+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 }
+ assert.deepEqual(visibleRows([...rows, history]).map(r => r.id).sort(), ['m1/a', 'm2/a'])
+ assert.equal(visibleRows([...rows, history], { filter: 'all' }).length, 3)
+ assert.equal(visibleRows(rows, { machine: 'missing' }).length, 0)
+})
+test('shared and nested workspace paths count once on each owning machine', () => {
+ const row = (machineId, workspacePath, workspaceBytes) => ({ machineId, workspacePath, workspaceBytes })
+ assert.deepEqual(storageTotal([row('m', '/a', 100), row('m', '/a', 100), row('m', '/a/b', 50), row('m', '/abc', 25), row('n', '/a', 100)]), { value: 225, partial: false })
+ assert.deepEqual(storageTotal([row('m', '/a', 100), row('m', '/other', null)]), { value: 100, partial: true })
+ assert.deepEqual(sumReading([{ cpu: null }, { cpu: 0 }], 'cpu'), { value: 0, partial: true })
+ assert.deepEqual(sumReading([{ cpu: null }], 'cpu'), { value: null, partial: true })
+ assert.equal(formatValue('rssBytes', 10.4e9), '10 GB')
+ assert.equal(formatValue('cpu', 126.4), '126%')
+})
diff --git a/store/agents/harness-monitor/viewer.mjs b/store/agents/harness-monitor/viewer.mjs
index 877c7d1a3..68bc5e329 100644
--- a/store/agents/harness-monitor/viewer.mjs
+++ b/store/agents/harness-monitor/viewer.mjs
@@ -49,7 +49,7 @@ export function createViewer({ workspace, port = 0, intervalMs = 4000, remoteInt
return
}
const policy = normalizePolicy(state.policy, { home: homedir() })
- const { rows, problems, degraded } = await collect({ state, now: now(), includeRemote: true, cache, remote, remoteIntervalMs: forceRemote ? 0 : remoteIntervalMs })
+ const { rows, shared = [], machines = [], problems, degraded } = await collect({ state, now: now(), includeRemote: true, cache, remote, remoteIntervalMs: forceRemote ? 0 : remoteIntervalMs })
const plan = decide(rows, policy, { home: homedir(), now: now() })
const summary = summarize(rows)
@@ -57,6 +57,8 @@ export function createViewer({ workspace, port = 0, intervalMs = 4000, remoteInt
spec: 1,
status: degraded ? 'degraded' : 'ok',
rows,
+ shared,
+ machines,
summary,
policy: { ...policy },
defaults: DEFAULT_POLICY,
diff --git a/store/agents/harness-monitor/viewer/app.css b/store/agents/harness-monitor/viewer/app.css
index a11c8de23..4acad3b0d 100644
--- a/store/agents/harness-monitor/viewer/app.css
+++ b/store/agents/harness-monitor/viewer/app.css
@@ -1,68 +1,111 @@
-:root { color-scheme: light; --bg:#fafafa; --row:#fff; --alt:#f4f4f5; --text:#242428; --muted:#71717a; --line:#dedee3; --hover:#ececf2; --selection:#e6edff; --accent:#4464cb; --yellow:#926000; --red:#b84141; --green:#347848; --cyan:#187593; font:13px ui-monospace,SFMono-Regular,Menlo,Consolas,monospace; }
-@media (prefers-color-scheme: dark) { :root:not([data-theme="light"]) { color-scheme:dark; --bg:#202124; --row:#242528; --alt:#27282c; --text:#eeeef0; --muted:#a1a1aa; --line:#393a41; --hover:#32343b; --selection:#303c58; --accent:#9fb5ff; --yellow:#eac56b; --red:#f28b82; --green:#9dce9c; --cyan:#7ec6de; } }
-:root[data-theme="dark"] { color-scheme:dark; --bg:#202124; --row:#242528; --alt:#27282c; --text:#eeeef0; --muted:#a1a1aa; --line:#393a41; --hover:#32343b; --selection:#303c58; --accent:#9fb5ff; --yellow:#eac56b; --red:#f28b82; --green:#9dce9c; --cyan:#7ec6de; }
+:root { color-scheme:light; --bg:#f5f5f7; --row:#fff; --alt:#f8f8fa; --text:#25262a; --muted:#666970; --line:#dcdee3; --hover:#eceef2; --selection:#dce9fb; --accent:#1764cc; --yellow:#885b0b; --red:#b4232a; --green:#277345; --cyan:#266d91; font:13px -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif; }
+@media (prefers-color-scheme: dark) { :root:not([data-theme="light"]) { color-scheme:dark; --bg:#242528; --row:#1d1e21; --alt:#222326; --text:#eeeff2; --muted:#aaadb5; --line:#393b40; --hover:#303238; --selection:#243e60; --accent:#8dbaff; --yellow:#e5bf70; --red:#ff949a; --green:#8bcc9e; --cyan:#8dc7e4; } }
+:root[data-theme="dark"] { color-scheme:dark; --bg:#242528; --row:#1d1e21; --alt:#222326; --text:#eeeff2; --muted:#aaadb5; --line:#393b40; --hover:#303238; --selection:#243e60; --accent:#8dbaff; --yellow:#e5bf70; --red:#ff949a; --green:#8bcc9e; --cyan:#8dc7e4; }
* { box-sizing:border-box; }
-body { margin:0; background: var(--bg); color:var(--text); height:100vh; display:flex; flex-direction:column; overflow:hidden; }
+[hidden] { display:none !important; }
+body { margin:0; background: var(--bg); color:var(--text); height:100dvh; display:flex; flex-direction:column; overflow:hidden; }
button,input,select,summary { font:inherit; color:inherit; }
-button,select,summary { background:transparent; border:1px solid transparent; border-radius:4px; padding:6px 9px; cursor:pointer; white-space:nowrap; }
-button:hover,summary:hover { background:var(--hover); }
-button:disabled { color:var(--muted); opacity:.45; cursor:default; }
+button,select,summary { min-height:32px; background:transparent; border:1px solid transparent; border-radius:16px; padding:6px 11px; cursor:pointer; white-space:nowrap; }
+button:hover,summary:hover,select:hover { background:var(--hover); }
+button:disabled { opacity:.4; cursor:default; }
+button:disabled:hover { background:transparent; }
button:focus-visible,input:focus-visible,select:focus-visible,summary:focus-visible,[tabindex]:focus-visible { outline:2px solid var(--accent); outline-offset:-2px; }
-header { display:flex; align-items:center; gap:20px; padding:18px 20px 10px; flex-wrap:wrap; }
-h1 { font-size:16px; font-weight:600; margin:0; white-space:nowrap; }
-input[type=search] { min-width:180px; flex:1; max-width:500px; margin-left:auto; padding:8px 10px; border:1px solid var(--line); border-radius:5px; background:var(--row); }
+header { display:flex; align-items:center; gap:24px; padding:18px 20px 14px; }
+.heading { display:flex; align-items:center; gap:12px; }
+h1 { font-size:17px; font-weight:600; letter-spacing:-.25px; margin:0; white-space:nowrap; }
+.live { display:inline-flex; align-items:center; gap:6px; color:var(--muted); font-size:12px; }
+.live::before { content:""; width:6px; height:6px; border-radius:50%; background:var(--green); }
+.live.inactive::before { background:var(--yellow); }
+.search-field { display:flex; align-items:center; gap:6px; margin-left:auto; width:340px; min-width:200px; border:1px solid var(--line); border-radius:10px; background:var(--row); padding:0 10px; }
+.search-field svg { width:16px; height:16px; fill:none; stroke:var(--muted); stroke-width:1.7; stroke-linecap:round; flex-shrink:0; }
+input[type=search] { min-width:0; width:100%; padding:8px 0; border:0; background:transparent; outline:none; }
+.search-field:focus-within { outline:2px solid var(--accent); outline-offset:-1px; }
input::placeholder { color:var(--muted); }
-#assistant { border-color:var(--line); }
-nav { display:flex; align-items:center; gap:6px; padding:0 14px 10px; border-bottom:1px solid var(--line); }
-nav label { display:flex; gap:5px; align-items:center; color:var(--muted); }
-select { color:var(--text); }
-.spacer { flex:1; }
+nav { display:flex; align-items:center; gap:6px; padding:0 16px 12px; border-bottom:1px solid var(--line); flex-wrap:wrap; }
+nav select { max-width:200px; background:var(--row); border-color:var(--line); }
+.spacer { flex:1; min-width:0; }
+.segmented { display:flex; border:1px solid var(--line); border-radius:8px; padding:2px; margin-right:8px; background:var(--hover); }
+.segmented button { min-height:28px; border-radius:6px; padding:4px 12px; color:var(--muted); }
+.segmented button[aria-pressed=true] { background:var(--row); color:var(--text); box-shadow:0 1px 3px #0002; }
+.danger { color:var(--red); }
+#stop { border-color:var(--line); background:var(--row); }
+.danger.filled { background:#b4232a; color:#fff; border-color:transparent; }
details { position:relative; }
summary { list-style:none; } summary::-webkit-details-marker { display:none; }
-.menu { position:absolute; z-index:10; right:0; top:34px; width:200px; padding:8px; background:var(--row); border:1px solid var(--line); border-radius:6px; box-shadow:0 8px 24px #0003; }
-.menu label { color:var(--text); padding:5px; gap:10px; }
-#problems { padding:8px 20px; color:var(--yellow); border-bottom:1px solid var(--line); font-size:12px; }
-#grid { flex:1; min-height:0; overflow:auto; position:relative; }
+#columns[open] > summary { background:var(--hover); }
+.menu { position:fixed; z-index:10; width:min(230px,calc(100vw - 16px)); max-height:65vh; overflow:auto; padding:12px; background:var(--row); border:1px solid var(--line); border-radius:16px; box-shadow:0 12px 30px #0003; }
+.menu strong { display:block; font-size:11px; color:var(--muted); font-weight:600; margin:10px 8px 4px; }
+.menu strong:first-child { margin-top:0; }
+.menu label { display:flex; align-items:center; padding:5px; gap:8px; cursor:pointer; border-radius:5px; }
+.menu label:hover { background:var(--hover); }
+.menu input { accent-color:var(--accent); }
+#problems { padding:9px 20px; color:var(--yellow); border-bottom:1px solid var(--line); font-size:12px; max-height:72px; overflow:auto; }
+#grid { flex:1; min-height:100px; overflow:auto; position:relative; background:var(--row); }
table { border-collapse:separate; border-spacing:0; table-layout:fixed; min-width:100%; font-variant-numeric:tabular-nums; }
-th { text-align:left; position:sticky; top:0; z-index:3; background:var(--bg); border-bottom:1px solid var(--line); height:36px; padding:0; color:var(--muted); font-weight:400; }
-th button { width:100%; text-align:left; padding:9px 12px; border-radius:0; overflow:hidden; text-overflow:ellipsis; }
-th.numeric button { text-align:right; }
-.resize { position:absolute; width:7px; right:0; top:6px; bottom:6px; cursor:col-resize; border-right:1px solid var(--line); touch-action:none; }
-td { height:36px; padding:0 12px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; background:var(--row); }
-tr:nth-child(even) td { background:var(--alt); }
-tr:hover td { background:var(--hover); }
-tr[aria-selected=true] td { background:var(--selection); }
-th:first-child,td:first-child { position:sticky; left:0; z-index:2; border-right:1px solid var(--line); }
-th:last-child,td:last-child { position:sticky; right:0; z-index:2; border-left:1px solid var(--line); }
-th:first-child,th:last-child { z-index:4; }
-td:first-child { font-weight:500; }
+#table th { text-align:left; position:sticky; top:0; z-index:3; background:var(--bg); border-bottom:1px solid var(--line); height:34px; padding:0; color:var(--muted); font-weight:500; font-size:12px; }
+#table th button { width:100%; text-align:left; padding:8px 12px; border-radius:0; overflow:hidden; text-overflow:ellipsis; }
+#table th.numeric button { text-align:right; }
+.resize { position:absolute; width:7px; right:0; top:9px; bottom:9px; cursor:col-resize; border-right:1px solid var(--line); touch-action:none; }
+#table td { height:46px; padding:6px 12px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; background:var(--row); }
+#table tr:nth-child(even) td { background:var(--alt); }
+#table tr:hover td { background:var(--hover); }
+#table tr[aria-selected=true] td { background:var(--selection); }
+#table th:first-child,#table td:first-child { position:sticky; left:0; z-index:2; border-right:1px solid var(--line); }
+#table th:first-child { z-index:4; }
+#table td:first-child strong,#table td:first-child small { display:block; overflow:hidden; text-overflow:ellipsis; }
+#table td:first-child strong { font-weight:500; }
+#table td:first-child small { color:var(--muted); font-size:11px; margin-top:3px; }
.numeric { text-align:right; }
-.status { display:inline-flex; align-items:center; gap:7px; }
-.mark { display:inline-block; width:12px; text-align:center; }
+.unknown { color:var(--muted); }
+.status { display:inline-flex; align-items:center; gap:7px; font-size:12px; }
+.mark { display:inline-block; width:12px; text-align:center; font-family:ui-monospace,SFMono-Regular,monospace; }
.working { color:var(--cyan); } .needsInput,.starting { color:var(--yellow); } .failed { color:var(--red); } .done { color:var(--green); } .idle,.offline,.stopped { color:var(--muted); }
-.engine { display:inline-flex; gap:7px; align-items:center; }
+.engine { display:inline-flex; gap:7px; align-items:center; font-size:12px; }
.engine img { width:16px; height:16px; object-fit:contain; }
.engine img.dark-tile { background:#29322f; border-radius:3px; padding:1px; }
-.actions { padding:0 4px; text-align:center; }
-.actions button { padding:5px 7px; } .actions .stop { font-size:18px; line-height:16px; }
-.actions .stop:not(:disabled):hover { color:var(--red); }
-#empty { padding:36px 20px; color:var(--muted); text-align:center; }
-footer { min-height:32px; padding:7px 18px; display:flex; gap:20px; align-items:center; color:var(--muted); border-top:1px solid var(--line); font-size:11px; }
+#empty { padding:70px 20px; color:var(--muted); text-align:center; }
+#empty strong { font-size:16px; color:var(--text); font-weight:500; }
+#empty p { margin:10px 0; }
+#summary { display:flex; align-items:center; flex-wrap:wrap; gap:12px 32px; padding:14px 20px; border-top:1px solid var(--line); }
+#summary:empty { display:none; }
+.total { display:flex; flex-direction:column; gap:4px; min-width:75px; }
+.total span { font-size:11px; color:var(--muted); }
+.total strong { font-size:17px; font-weight:500; font-variant-numeric:tabular-nums; }
+.summary-scope { margin:0 0 0 auto; font-size:11px; color:var(--muted); }
+#shared { padding:0 14px 6px; border-top:1px solid var(--line); color:var(--muted); font-size:12px; }
+#shared > summary::before { content:'›'; margin-right:8px; display:inline-block; }
+#shared[open] > summary::before { transform:rotate(90deg); }
+#shared-body { max-height:120px; overflow:auto; }
+.shared-row { display:flex; flex-wrap:wrap; gap:8px 24px; padding:6px 12px; }
+.shared-row strong { color:var(--text); font-weight:500; }
+footer { min-height:30px; padding:7px 20px; display:flex; flex-wrap:wrap; gap:8px 20px; align-items:center; color:var(--muted); border-top:1px solid var(--line); font-size:11px; }
#message { flex:1; color:var(--text); } #updated { white-space:nowrap; }
-dialog { background:var(--bg); color:var(--text); border:1px solid var(--line); border-radius:8px; padding:24px; max-width:600px; width:calc(100% - 40px); max-height:85vh; }
-dialog::backdrop { background:#0007; }
-h2 { font-size:16px; margin:0 0 18px; } p { line-height:1.6; }
+dialog { background:var(--bg); color:var(--text); border:1px solid var(--line); border-radius:20px; padding:24px; max-width:580px; width:calc(100% - 32px); max-height:90dvh; overflow:auto; box-shadow:0 20px 80px #0004; }
+dialog::backdrop { background:#0009; }
+#inspector { max-width:840px; }
+h2 { font-size:17px; line-height:1.4; font-weight:600; margin:0; overflow-wrap:anywhere; }
+h3 { font-size:13px; font-weight:600; margin:0 0 12px; }
+p { line-height:1.5; }
.muted { color:var(--muted); }
+.dialog-heading { display:flex; align-items:flex-start; gap:20px; justify-content:space-between; }
+.dialog-heading button { margin-top:-5px; }
.dialog-actions { display:flex; justify-content:flex-end; flex-wrap:wrap; gap:8px; margin-top:24px; }
-.dialog-actions button { border-color:var(--line); }
-#cleanup-plan { max-height:35vh; overflow:auto; }
-.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); }
+.dialog-actions button { border-color:var(--line); background:var(--row); }
+.dialog-actions .filled { background:#b4232a; }
+#inspect-content { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:24px 32px; }
+.inspect-section { border-top:1px solid var(--line); padding-top:16px; }
+.inspect-section dl { display:grid; grid-template-columns:minmax(90px,auto) 1fr; gap:8px 20px; font-size:12px; margin:0; }
+.inspect-section dt { color:var(--muted); }
+.inspect-section dd { margin:0; overflow-wrap:anywhere; text-align:right; font-variant-numeric:tabular-nums; }
+.processes { overflow:auto; max-height:300px; }
+.processes p { color:var(--muted); font-size:12px; }
+.processes table { font-size:12px; text-align:right; }
+.processes th,.processes td { padding:6px 4px; border-bottom:1px solid var(--line); font-weight:400; }
+.processes th { color:var(--muted); }
+.metric-note { grid-column:1/-1; font-size:12px; margin:0; }
+#stop-result { color:var(--yellow); }
+.sr-only { position:absolute; width:1px; height:1px; padding:0; margin:-1px; overflow:hidden; clip:rect(0,0,0,0); white-space:nowrap; border:0; }
+@media (max-width:800px) { nav { gap:5px; } .spacer { display:none; } .summary-scope { width:100%; margin:0; } #summary { gap:12px 22px; } }
+@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; } }
diff --git a/store/agents/harness-monitor/viewer/app.js b/store/agents/harness-monitor/viewer/app.js
index 72eefea93..239f27f3a 100644
--- a/store/agents/harness-monitor/viewer/app.js
+++ b/store/agents/harness-monitor/viewer/app.js
@@ -1,35 +1,39 @@
-import { ACTIVITY, SPINNER, COLUMNS, visibleRows, number, memory, age } from './table.js'
+import { ACTIVITY, SPINNER, COLUMNS, PRESETS, isLive, visibleRows, number, memory, bytes, age, formatValue, sumReading, storageTotal } from './table.js'
const el = id => document.getElementById(id)
const dom = {
- search: el('search'), filter: el('filter'), columns: el('columns'), columnOptions: el('column-options'),
+ 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'),
- 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'),
+ refresh: el('refresh'), pause: el('pause'), live: el('live-status'), inspect: el('inspect'), stop: el('stop'),
+ 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'),
+ stopDialog: el('stop-dialog'), stopTitle: el('stop-title'), stopContext: el('stop-context'), stopResult: el('stop-result'),
+ stopCancel: el('stop-cancel'), stopConfirm: el('stop-confirm'),
}
const token = document.querySelector('meta[name="hps-token"]').content
+const STORAGE_KEY = 'harness-monitor.process-table.v3'
let saved = {}
-try { saved = JSON.parse(localStorage.getItem('harness-monitor.table.v2') || '{}') } catch { /* private browsing */ }
+try { saved = JSON.parse(localStorage.getItem(STORAGE_KEY) || '{}') || {} } catch { /* optional preference storage */ }
const state = {
- rows: [], snapshot: null, query: typeof saved.query === 'string' ? saved.query : '',
- 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(), nodes: new Map(), shown: [], assistantIntroSeen: saved.assistantIntroSeen === true,
+ rows: [], snapshot: null, query: '', filter: 'active', machine: 'all', // Every visit starts with active work.
+ sort: COLUMNS.some(c => c.key === saved.sort) ? saved.sort : 'rssBytes', direction: saved.direction === 1 ? 1 : -1,
+ 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,
}
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 }
-function persist() {
- try { localStorage.setItem('harness-monitor.table.v2', JSON.stringify({ query: state.query, filter: state.filter, sort: state.sort, direction: state.direction, visible: [...state.visible], widths: state.widths, assistantIntroSeen: state.assistantIntroSeen })) } catch { /* optional */ }
-}
function element(tag, value, className) {
const node = document.createElement(tag)
if (value != null) node.textContent = value
if (className) node.className = className
return node
}
+function persist() {
+ try { localStorage.setItem(STORAGE_KEY, JSON.stringify({ sort: state.sort, direction: state.direction, preset: state.preset, visible: [...state.visible], widths: state.widths })) } catch { /* private browsing */ }
+}
function message(value) { text(dom.message, value) }
async function post(path, payload) {
const response = await fetch(path, { method: 'POST', headers: { 'content-type': 'application/json', 'x-hps-token': token }, body: JSON.stringify(payload) })
@@ -37,38 +41,14 @@ async function post(path, payload) {
if (!response.ok || result.error) throw new Error(result.error || 'Request failed. Refresh and try again.')
return result
}
-// Both the native webview and the remote viewer renderer consume this small, bounded navigation queue.
-// No scripts, prompts, process controls or paths cross the host bridge.
-window.harnessHostQueue = []
-function host(action) {
- 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.'); return false }
- return true
-}
-function openRow(id) {
- const row = state.rows.find(r => r.id === id)
- if (!row?.canOpen || state.busy.has(id)) return
- host({ action: 'open', machineId: row.machineId, agentId: row.agentId })
+const activeColumns = () => {
+ const ordered = PRESETS[state.preset]
+ return ordered ? ordered.map(key => COLUMNS.find(c => c.key === key))
+ : COLUMNS.filter(c => c.required || state.visible.has(c.key))
}
-async function stopRows(ids, manual) {
- 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 })
- const failures = reply.results.filter(r => !r.ok)
- message(failures.length ? failures.map(r => r.name + ': ' + r.detail).join(' · ') : (reply.results.length === 1 ? 'Stopped. History retained.' : reply.results.length + ' sessions stopped.'))
- } catch (error) { message(error.message) }
- finally { ids.forEach(id => state.busy.delete(id)); render() }
-}
-const activeColumns = () => COLUMNS.filter(c => c.required || state.visible.has(c.key))
function resizeColumns() {
for (const col of dom.colgroup.children) col.style.width = state.widths[col.dataset.key] + 'px'
- for (const header of dom.head.querySelectorAll('th[data-key]')) {
- const grip = header.querySelector('.resize')
- if (grip) { grip.setAttribute('aria-valuemin', '64'); grip.setAttribute('aria-valuemax', '600'); grip.setAttribute('aria-valuenow', String(state.widths[header.dataset.key])) }
- }
+ for (const header of dom.head.querySelectorAll('th')) header.querySelector('.resize')?.setAttribute('aria-valuenow', String(state.widths[header.dataset.key]))
dom.table.style.width = activeColumns().reduce((sum, c) => sum + state.widths[c.key], 0) + 'px'
}
function buildColumns() {
@@ -77,50 +57,69 @@ function buildColumns() {
for (const col of activeColumns()) {
const width = element('col'); width.dataset.key = col.key; dom.colgroup.append(width)
const th = element('th', null, col.numeric ? 'numeric' : ''); th.scope = 'col'; th.dataset.key = col.key
- if (col.key !== 'actions') {
- const sort = element('button', col.label); sort.type = 'button'; sort.title = col.help || 'Sort by ' + col.label
- sort.onclick = () => { state.direction = state.sort === col.key ? -state.direction : col.numeric ? -1 : 1; state.sort = col.key; persist(); render() }
- th.append(sort)
- const grip = element('span', null, 'resize'); grip.tabIndex = 0; grip.role = 'separator'; grip.setAttribute('aria-orientation', 'vertical'); grip.setAttribute('aria-label', 'Resize ' + col.label)
- const change = width => { state.widths[col.key] = Math.max(64, Math.min(600, width)); resizeColumns() }
- grip.onpointerdown = event => {
- event.preventDefault(); const start = event.clientX, width = state.widths[col.key]
- grip.setPointerCapture(event.pointerId)
- grip.onpointermove = move => change(width + move.clientX - start)
- grip.onpointerup = () => { grip.onpointermove = null; persist() }
- grip.onpointercancel = () => { grip.onpointermove = null; persist() }
- }
- grip.onkeydown = event => { if (['ArrowLeft', 'ArrowRight'].includes(event.key)) { event.preventDefault(); change(state.widths[col.key] + (event.key === 'ArrowLeft' ? -16 : 16)); persist() } }
- th.append(grip)
+ const sort = element('button', col.label); sort.type = 'button'; sort.title = col.help || 'Sort by ' + col.label
+ sort.onclick = () => { state.direction = state.sort === col.key ? -state.direction : col.numeric ? -1 : 1; state.sort = col.key; persist(); render() }
+ const grip = element('span', null, 'resize'); grip.tabIndex = 0; grip.role = 'separator'
+ grip.setAttribute('aria-orientation', 'vertical'); grip.setAttribute('aria-label', 'Resize ' + col.label)
+ grip.setAttribute('aria-valuemin', '64'); grip.setAttribute('aria-valuemax', '600')
+ const change = value => { state.widths[col.key] = Math.max(64, Math.min(600, value)); resizeColumns() }
+ grip.onpointerdown = event => {
+ event.preventDefault(); const start = event.clientX, width = state.widths[col.key]
+ grip.setPointerCapture(event.pointerId)
+ grip.onpointermove = move => change(width + move.clientX - start)
+ grip.onpointerup = grip.onpointercancel = () => { grip.onpointermove = null; persist() }
}
- tr.append(th)
+ grip.onkeydown = event => { if (['ArrowLeft', 'ArrowRight'].includes(event.key)) { event.preventDefault(); change(state.widths[col.key] + (event.key === 'ArrowLeft' ? -16 : 16)); persist() } }
+ th.append(sort, grip); tr.append(th)
}
dom.head.append(tr); resizeColumns(); render()
}
-for (const col of COLUMNS.filter(c => !c.required)) {
- const label = element('label'), check = element('input'); check.type = 'checkbox'; check.checked = state.visible.has(col.key)
- check.onchange = () => { if (check.checked) state.visible.add(col.key); else state.visible.delete(col.key); persist(); buildColumns() }
- label.append(check, document.createTextNode(col.label)); dom.columnOptions.append(label)
+function columnMenu() {
+ dom.columnOptions.replaceChildren()
+ for (const group of ['Session', 'Resources', 'AI usage']) {
+ dom.columnOptions.append(element('strong', group))
+ for (const col of COLUMNS.filter(c => c.group === group && !c.required)) {
+ const label = element('label'), check = element('input'); check.type = 'checkbox'; check.checked = state.visible.has(col.key)
+ label.title = col.help || col.label
+ check.onchange = () => { if (check.checked) state.visible.add(col.key); else state.visible.delete(col.key); state.preset = null; persist(); buildColumns() }
+ label.append(check, document.createTextNode(col.label)); dom.columnOptions.append(label)
+ }
+ }
+ const reset = element('button', 'Reset columns'); reset.onclick = () => setPreset('overview'); dom.columnOptions.append(reset)
+}
+function positionColumnMenu() {
+ if (!dom.columns.open) return
+ const anchor = dom.columns.querySelector('summary').getBoundingClientRect()
+ const height = Math.min(innerHeight * .65, 500)
+ const below = innerHeight - anchor.bottom - 14
+ const top = below < 160 && anchor.top > below ? Math.max(8, anchor.top - height - 6) : anchor.bottom + 6
+ dom.columnOptions.style.left = Math.max(8, Math.min(anchor.right - 230, innerWidth - 238)) + 'px'
+ dom.columnOptions.style.top = top + 'px'
+ dom.columnOptions.style.maxHeight = Math.max(0, Math.min(height, innerHeight - top - 8)) + 'px'
+}
+dom.columns.addEventListener('toggle', positionColumnMenu)
+window.addEventListener('resize', positionColumnMenu)
+function setPreset(preset) {
+ state.preset = preset; state.visible = new Set(PRESETS[preset]);
+ for (const col of COLUMNS) state.widths[col.key] = col.width
+ if (preset === 'ai') { state.sort = 'tokens'; state.direction = -1 }
+ else { state.sort = 'rssBytes'; state.direction = -1 }
+ persist(); columnMenu(); buildColumns()
}
+for (const button of document.querySelectorAll('[data-preset]')) button.onclick = () => setPreset(button.dataset.preset)
const iconNames = new Set(['codex', 'opencode', 'cursor', 'pi', 'hermes', 'commandcode', 'devin', 'muse', 'amp', 'kilo', 'grok', 'copilot', 'agy', 'claude'])
const engineNames = { codex: 'Codex', claude: 'Claude', opencode: 'OpenCode', cursor: 'Cursor', terminal: 'Terminal', pi: 'Pi', hermes: 'Hermes', copilot: 'Copilot', gemini: 'Gemini' }
function createRow(row) {
const tr = element('tr'); tr.dataset.id = row.id
tr.onclick = () => { state.selected = row.id; select(); dom.grid.focus({ preventScroll: true }) }
- tr.ondblclick = event => { if (!event.target.closest('button')) openRow(row.id) }
+ tr.ondblclick = () => inspect(row.id)
for (const col of activeColumns()) {
const td = element('td', null, col.numeric ? 'numeric' : ''); td.dataset.key = col.key
- if (col.key === 'actions') {
- td.className = 'actions'
- const open = element('button', 'Open'), stop = element('button', '×', 'stop')
- open.onclick = event => { event.stopPropagation(); openRow(row.id) }
- stop.onclick = event => { event.stopPropagation(); void stopRows([row.id], true) }
- td.append(open, stop)
- } else if (col.key === 'activity') {
- const status = element('span', null, 'status'); status.append(element('span', null, 'mark'), element('span')); td.append(status)
- } else if (col.key === 'engine') {
- const span = element('span', null, 'engine'), img = element('img'), label = element('span'); img.alt = ''; img.hidden = true
- span.append(img, label); td.append(span)
+ if (col.key === 'name') td.append(element('strong'), element('small'))
+ if (col.key === 'activity') { const span = element('span', null, 'status'); span.append(element('span', null, 'mark'), element('span')); td.append(span) }
+ if (col.key === 'engine') {
+ const span = element('span', null, 'engine'), img = element('img'); img.alt = ''; img.hidden = true
+ span.append(img, element('span')); td.append(span)
}
tr.append(td)
}
@@ -128,166 +127,204 @@ function createRow(row) {
}
function updateRow(tr, row) {
for (const td of tr.children) {
- const key = td.dataset.key
- if (key === 'activity') {
- const [mark, label] = ACTIVITY[row.activity] || ['—', 'Unknown']
- const status = td.firstChild; status.className = 'status ' + row.activity
- text(status.children[0], mark); text(status.children[1], label)
- td.title = row.activityKnown || ['offline', 'stopped', 'starting', 'failed'].includes(row.activity) ? label : 'Update this machine’s Harness daemon to report activity.'
+ const key = td.dataset.key, col = COLUMNS.find(c => c.key === key)
+ if (key === 'name') {
+ text(td.children[0], row.name); text(td.children[1], [row.project === '—' ? null : row.project, row.branch].filter(Boolean).join(' · ') || row.engine || 'Harness')
+ td.title = [row.name, row.home, row.model].filter(Boolean).join('\n')
+ } else if (key === 'activity') {
+ const [mark, label] = ACTIVITY[row.activity] || ACTIVITY.unknown
+ td.firstChild.className = 'status ' + row.activity; text(td.firstChild.children[0], mark); text(td.firstChild.children[1], label)
+ td.title = row.activityKnown || ['offline', 'starting', 'failed'].includes(row.activity) ? label : 'The owning daemon has not reported activity.'
} else if (key === 'engine') {
- const img = td.firstChild.children[0]; const icon = iconNames.has(row.engine) ? row.engine : null
- img.hidden = !icon
- img.className = ['cursor', 'opencode', 'grok', 'copilot'].includes(icon) ? 'dark-tile' : ''
+ const img = td.firstChild.children[0], icon = iconNames.has(row.engine) ? row.engine : null
+ img.hidden = !icon; img.className = ['cursor', 'opencode', 'grok', 'copilot'].includes(icon) ? 'dark-tile' : ''
if (icon && img.getAttribute('src') !== 'icons/' + icon + '.png') img.src = 'icons/' + icon + '.png'
text(td.firstChild.children[1], engineNames[row.engine] || row.engine || '—')
- } else if (key === 'actions') {
- const [open, stop] = td.children
- open.disabled = !row.canOpen || state.busy.has(row.id); stop.disabled = !row.canStop || state.busy.has(row.id)
- open.title = row.canOpen ? (row.state === 'paused' ? (row.resumeMode === 'fresh' ? 'Open a new conversation with the saved settings' : 'Resume this session') : 'Open this session') : row.unavailable || 'Session unavailable'
- stop.title = row.canStop ? 'Stop session; keep history' : row.unavailable || 'Already stopped or unavailable'
- stop.setAttribute('aria-label', 'Stop ' + row.name)
- open.setAttribute('aria-label', 'Open ' + row.name)
} else {
- const value = key === 'cpu' ? (row.cpu == null ? '—' : row.cpu.toFixed(1)) : key === 'rssBytes' ? memory(row.rssBytes)
- : key === 'tokens' ? number(row.tokens) : key === 'lastActivity' ? age(row.lastActivity) : row[key] ?? '—'
- text(td, value); td.title = key === 'lastActivity' && row.lastActivity ? new Date(row.lastActivity).toLocaleString() : String(row[key] ?? '')
+ text(td, formatValue(key, row[key]))
+ td.classList.toggle('unknown', row[key] == null)
+ td.title = row[key] == null ? (col.help || col.label) + '\nThis reading is unavailable.'
+ : ['lastActivity', 'createdAt'].includes(key) ? new Date(row[key]).toLocaleString()
+ : col.numeric ? Number(row[key]).toLocaleString() + '\n' + (col.help || col.label) : String(row[key])
}
}
}
+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)
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 totalText = (total, formatter) => total.value == null ? '—' : (total.partial ? '≥' : '') + formatter(total.value)
+function summary() {
+ const rows = state.shown
+ const shared = (state.snapshot?.shared ?? []).filter(s => s.online && rows.some(r => r.machineId === s.machineId && s.agentIds.includes(r.agentId)))
+ const resources = [...rows, ...shared]
+ dom.summary.replaceChildren()
+ for (const [label, total, format, hint] of [
+ ['CPU', sumReading(resources, 'cpu'), n => Math.round(n) + '%', '100% is one core. Shared servers count once.'],
+ ['RAM', sumReading(resources, 'rssBytes'), memory, 'Resident memory including child processes and shared servers once. Shared memory pages can overlap.'],
+ ['GPU', sumReading(resources, 'gpuPercent'), n => Math.round(n) + '%', 'Reported process utilization. Unsupported counters stay unknown.'],
+ ['Storage', storageTotal(rows.map(r => r.online === false ? { ...r, workspaceBytes: null } : r)), bytes, 'Workspace disk space. Shared and nested folders count once per machine. Stopping does not delete files.'],
+ ['Tokens', sumReading(rows, 'tokens'), number, 'Conversation totals for shown sessions. Cached input is included once.'],
+ ]) {
+ 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)
+ 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) {
+ const row = element('div', null, 'shared-row')
+ row.append(element('strong', server.name), element('span', server.machine), element('span', `${server.agentIds.length} sessions`),
+ element('span', formatValue('cpu', server.cpu) + ' CPU'), element('span', memory(server.rssBytes) + ' RAM'))
+ dom.sharedBody.append(row)
+ }
}
function render() {
- const focused = dom.body.contains(document.activeElement) ? document.activeElement : null
const { scrollTop, scrollLeft } = dom.grid
state.shown = visibleRows(state.rows, state)
const ids = new Set(state.shown.map(r => r.id))
for (const [id, node] of state.nodes) if (!ids.has(id)) { node.remove(); state.nodes.delete(id) }
- // Keyed updates preserve row buttons, focus, selection and the scroll container on every sample.
+ if (state.selected && !ids.has(state.selected)) state.selected = null
let at = dom.body.firstChild
for (const row of state.shown) {
let node = state.nodes.get(row.id)
if (!node) { node = createRow(row); state.nodes.set(row.id, node) }
- updateRow(node, row)
- if (at !== node) dom.body.insertBefore(node, at)
- at = node.nextSibling
+ updateRow(node, row); if (at !== node) dom.body.insertBefore(node, at); at = node.nextSibling
}
- select()
- if (focused?.isConnected && document.activeElement !== focused) focused.focus({ preventScroll: true })
- dom.grid.scrollTop = scrollTop; dom.grid.scrollLeft = scrollLeft
+ select(); dom.grid.scrollTop = scrollTop; dom.grid.scrollLeft = scrollLeft
for (const th of dom.head.querySelectorAll('th')) {
const col = COLUMNS.find(c => c.key === th.dataset.key)
- if (!col || col.key === 'actions') continue
th.setAttribute('aria-sort', state.sort === col.key ? (state.direction === 1 ? 'ascending' : 'descending') : 'none')
text(th.firstChild, col.label + (state.sort === col.key ? (state.direction === 1 ? ' ↑' : ' ↓') : ''))
}
+ 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, state.snapshot?.status === 'starting' ? 'Connecting to your machines…' : state.rows.length ? 'No harnesses match this search.' : 'No harnesses found on your connected machines.')
- text(dom.count, state.shown.length + (state.shown.length === state.rows.length ? '' : ' of ' + state.rows.length) + ' harnesses')
- text(dom.updated, state.snapshot?.observedAt ? 'Updated ' + age(state.snapshot.observedAt) : 'Connecting…')
+ 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.')
+ 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())
+ if (ready) summary()
+ if (dom.inspector.open) renderInspector()
+}
+function inspect(id) {
+ const row = state.rows.find(r => r.id === id); if (!row) return
+ state.inspecting = id; renderInspector(); dom.inspector.showModal()
}
-dom.search.value = state.query; dom.filter.value = state.filter
-dom.search.oninput = () => { state.query = dom.search.value; persist(); render() }
-dom.filter.onchange = () => { state.filter = dom.filter.value; persist(); render() }
+function renderInspector() {
+ const row = state.rows.find(r => r.id === state.inspecting)
+ dom.inspectStop.disabled = !canStop(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(' · '))
+ dom.inspectContent.replaceChildren()
+ for (const group of ['Resources', 'AI usage', 'Session']) {
+ const section = element('section', null, 'inspect-section'); section.append(element('h3', group)); const dl = element('dl')
+ for (const col of COLUMNS.filter(c => c.group === group && !['name', 'activity', 'engine', 'machine'].includes(c.key))) {
+ const label = element('dt', col.label), value = element('dd', formatValue(col.key, row[col.key])); label.title = col.help || col.label
+ dl.append(label, value)
+ }
+ section.append(dl); dom.inspectContent.append(section)
+ }
+ const processes = element('section', null, 'inspect-section processes'); processes.append(element('h3', 'Process tree'))
+ processes.append(element('p', 'Owned processes and children; nested harnesses and shared servers are counted separately.'))
+ if (!row.processes?.length) processes.append(element('p', 'Process details are unavailable on this machine.', 'muted'))
+ else {
+ const table = element('table'), head = element('tr')
+ for (const title of ['PID', 'Parent PID', 'CPU', 'RAM']) head.append(element('th', title))
+ const tbody = element('tbody'); table.append(head, tbody)
+ for (const process of row.processes) {
+ const tr = element('tr')
+ for (const value of [process.pid, process.parent, formatValue('cpu', process.cpuPercent), memory(process.memoryBytes)]) tr.append(element('td', value))
+ tbody.append(tr)
+ }
+ processes.append(table)
+ if (row.processCount > row.processes.length) processes.append(element('p', `Showing ${row.processes.length} of ${row.processCount} processes.`, 'muted'))
+ }
+ dom.inspectContent.append(processes)
+ const notes = element('p', 'GPU readings describe attributable processes on the owning machine, not a cloud model. Storage includes existing workspace files and remains after stopping. Missing readings are unavailable, not zero.', 'muted metric-note')
+ dom.inspectContent.append(notes)
+}
+function reviewStop(id) {
+ const row = state.rows.find(r => r.id === id); if (!canStop(row)) return
+ state.review = { id: row.id, sessionId: row.sessionId, lastActivity: row.lastActivity, name: row.name }
+ text(dom.stopTitle, 'Stop “' + row.name + '”?')
+ text(dom.stopContext, `${row.machine} · ${ACTIVITY[row.activity]?.[1] || 'Unknown'} · ${memory(row.rssBytes)} RAM · ${number(row.tokens)} tokens`)
+ text(dom.stopResult, ''); dom.stopConfirm.disabled = false; dom.stopCancel.disabled = false
+ dom.stopDialog.showModal()
+}
+dom.stop.onclick = () => reviewStop(state.selected)
+dom.inspect.onclick = () => inspect(state.selected)
+dom.inspectStop.onclick = () => reviewStop(state.inspecting)
+dom.inspectClose.onclick = () => dom.inspector.close()
+dom.stopCancel.onclick = () => dom.stopDialog.close()
+dom.stopDialog.addEventListener('cancel', event => { if (state.busy.has(state.review?.id)) event.preventDefault() })
+dom.stopConfirm.onclick = async () => {
+ const review = state.review
+ if (!review || state.busy.has(review.id)) return
+ const row = state.rows.find(r => r.id === review.id)
+ if (!canStop(row) || row.sessionId !== review.sessionId) {
+ text(dom.stopResult, 'This session or connection changed. Cancel, refresh and review it again.')
+ dom.stopConfirm.disabled = true
+ return
+ }
+ 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 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()
+ } catch (error) { text(dom.stopResult, error.message + ' Refresh to check before trying again.') }
+ finally { state.busy.delete(review.id); dom.stopCancel.disabled = false; render() }
+}
+dom.search.oninput = () => { state.query = dom.search.value; render() }
+dom.filter.onchange = () => { state.filter = dom.filter.value; render() }
+dom.machine.onchange = () => { state.machine = dom.machine.value; render() }
dom.grid.onkeydown = event => {
if (event.target.closest('button') || event.target.classList.contains('resize')) return
if (['ArrowUp', 'ArrowDown', 'Home', 'End'].includes(event.key)) {
event.preventDefault(); const index = state.shown.findIndex(r => r.id === state.selected)
const next = event.key === 'Home' ? 0 : event.key === 'End' ? state.shown.length - 1 : Math.max(0, Math.min(state.shown.length - 1, index + (event.key === 'ArrowUp' ? -1 : 1)))
state.selected = state.shown[next]?.id ?? null; select(); state.nodes.get(state.selected)?.scrollIntoView({ block: 'nearest', inline: 'nearest' })
- } else if (event.key === 'Enter' && state.selected) { event.preventDefault(); openRow(state.selected) }
+ } else if (event.key === 'Enter' && state.selected) { event.preventDefault(); inspect(state.selected) }
+ else if (['Delete', 'Backspace'].includes(event.key) && state.selected) { event.preventDefault(); reviewStop(state.selected) }
}
document.addEventListener('keydown', event => {
- if ((event.key === '/' || ((event.metaKey || event.ctrlKey) && event.key === 'f')) && !document.querySelector('dialog[open]') && !['INPUT', 'TEXTAREA'].includes(event.target.tagName)) { event.preventDefault(); dom.search.focus() }
+ if (event.key === 'Escape' && dom.columns.open) { dom.columns.open = false; dom.columns.querySelector('summary').focus() }
+ if ((event.key === '/' || ((event.metaKey || event.ctrlKey) && event.key === 'f')) && !document.querySelector('dialog[open]') && !['INPUT', 'TEXTAREA', 'SELECT'].includes(event.target.tagName)) { event.preventDefault(); dom.search.focus() }
})
+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('') } catch (error) { message(error.message) }
+ try { await post('/api/refresh', {}); message(state.paused ? 'New readings ready. Resume updates to display them.' : '') } catch (error) { message(error.message) }
finally { dom.refresh.disabled = false }
}
-function showAssistant(chooseModel = false) {
- if (!host({ action: 'assistant', chooseModel })) return
- state.assistantIntroSeen = true; persist(); dom.choice.close()
+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 }
+ render()
}
-dom.assistant.onclick = () => state.assistantIntroSeen ? showAssistant() : dom.choice.showModal()
-dom.cancel.onclick = () => dom.choice.close()
-dom.free.onclick = () => showAssistant()
-dom.other.onclick = () => showAssistant(true)
-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')
+function applySnapshot(snapshot) {
+ state.snapshot = snapshot; state.rows = snapshot.rows ?? []; state.receivedAt = Date.now()
+ const machines = new Map((snapshot.machines ?? []).map(m => [m.machineId, m.name]))
+ for (const row of state.rows) machines.set(row.machineId, row.machine)
+ const signature = JSON.stringify([...machines])
+ if (dom.machine.dataset.signature !== signature) {
+ dom.machine.dataset.signature = signature; dom.machine.replaceChildren(new Option('All machines', 'all'))
+ for (const [id, name] of machines) dom.machine.append(new Option(name, id))
+ if (!machines.has(state.machine)) state.machine = 'all'
+ dom.machine.value = state.machine
}
+ dom.problems.hidden = !snapshot.problems?.length
+ text(dom.problems, (snapshot.problems ?? []).map(p => p.machine + ': ' + p.error).join(' · '))
+ render()
}
let stream
function connect() {
@@ -295,20 +332,26 @@ function connect() {
stream = new EventSource('/events')
stream.addEventListener('snapshot', event => {
try {
- const snapshot = JSON.parse(event.data)
- state.snapshot = snapshot; state.rows = snapshot.rows ?? []
- dom.problems.hidden = !snapshot.problems?.length
- text(dom.problems, (snapshot.problems ?? []).map(p => p.machine + ': ' + p.error).join(' · ')); render()
+ 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)
} catch { message('Could not read the monitor update. Refresh and try again.') }
})
- stream.onerror = () => { message('Connection interrupted. Reconnecting…') }
- stream.onopen = () => { if (dom.message.textContent === 'Connection interrupted. Reconnecting…') message('') }
+ stream.onerror = () => { state.connected = false; message('Connection interrupted. Showing last readings; reconnecting…'); render() }
+ stream.onopen = () => { if (dom.message.textContent.startsWith('Connection interrupted.')) message('') }
}
-document.addEventListener('visibilitychange', () => { if (document.hidden) { stream?.close(); stream = null } else 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) return
+ if (document.hidden || reducedMotion.matches || state.paused || !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)
-buildColumns(); connect()
+setInterval(() => {
+ if (document.hidden || state.paused || !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.')
+ }
+ render()
+}, 10_000)
+columnMenu(); buildColumns(); connect()
diff --git a/store/agents/harness-monitor/viewer/index.html b/store/agents/harness-monitor/viewer/index.html
index d70a33e0a..a4c29012f 100644
--- a/store/agents/harness-monitor/viewer/index.html
+++ b/store/agents/harness-monitor/viewer/index.html
@@ -9,44 +9,38 @@
</head>
<body>
<header>
- <h1>Harness Monitor</h1>
- <input id="search" type="search" placeholder="Search harnesses" aria-label="Search harnesses" autocomplete="off" spellcheck="false">
- <button id="assistant">Ask assistant</button>
+ <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>
</header>
<nav aria-label="Monitor controls">
- <label>Status <select id="filter" aria-label="Filter by status">
- <option value="all">All</option><option value="needsInput">Needs you</option>
- <option value="working">Working</option><option value="done">Done</option>
- <option value="idle">Idle</option><option value="starting">Starting</option>
- <option value="failed">Failed</option><option value="stopped">Stopped</option><option value="offline">Offline</option><option value="unknown">Unknown</option>
- </select></label>
+ <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>
+ </select>
<span class="spacer"></span>
+ <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="cleanup">Clean up…</button>
- <button id="refresh" title="Refresh all machines">Refresh</button>
+ <button id="pause" title="Freeze the table without pausing any harness">Pause 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="Harness sessions. Arrow keys select, Enter opens.">
- <table id="table" aria-label="Harness sessions"><colgroup id="colgroup"></colgroup><thead id="head"></thead><tbody id="body"></tbody></table>
- <p id="empty">Connecting to your machines…</p>
+ <main id="grid" tabindex="0" aria-label="Active harness sessions. Arrow keys select, Enter inspects, Delete reviews stopping.">
+ <table id="table" aria-label="Active harness sessions"><colgroup id="colgroup"></colgroup><thead id="head"></thead><tbody id="body"></tbody></table>
+ <div id="empty"><strong>Connecting to your machines…</strong><p>Active sessions will appear here.</p></div>
</main>
+ <section id="summary" aria-label="Resource totals for shown sessions"></section>
+ <details id="shared" hidden><summary id="shared-title">Shared servers</summary><div id="shared-body"></div></details>
<footer><span id="count"></span><span id="message" role="status" aria-live="polite"></span><span id="updated"></span></footer>
- <dialog id="assistant-choice" aria-labelledby="assistant-title">
- <h2 id="assistant-title">Ask assistant</h2>
- <p>New monitors use OpenCode with <strong>Muse Spark 1.3 Contributor Free</strong>. This limited-time free model allows Meta to use prompts and responses for training. Existing sessions keep their selected engine and model.</p>
- <p>Only what you send to the assistant, and information its tools read, enters the conversation. The table works without the assistant.</p>
- <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 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>
</dialog>
- <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 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 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>
+ <p id="stop-result" role="status" aria-live="polite"></p>
+ <div class="dialog-actions"><button id="stop-cancel" autofocus>Cancel</button><button id="stop-confirm" class="danger filled">Stop harness</button></div>
</dialog>
<script type="module" src="app.js"></script>
</body>
diff --git a/store/agents/harness-monitor/viewer/table.js b/store/agents/harness-monitor/viewer/table.js
index 9150fadc2..a5d21ee6f 100644
--- a/store/agents/harness-monitor/viewer/table.js
+++ b/store/agents/harness-monitor/viewer/table.js
@@ -1,43 +1,89 @@
-/** UI contracts mirror desktop HarnessActivity/EngineMark; pure sorting is shared with tests. */
+/** Process-monitor presentation. Unknown readings always sort last. */
export const ACTIVITY = {
- needsInput: ['?', 'Needs you'], failed: ['✗', 'Failed'], done: ['✓', 'Done'], working: ['⠋', 'Working'],
- starting: ['◌', 'Starting'], idle: ['', 'Idle'], stopped: ['Ⅱ', 'Stopped'], offline: ['⊘', 'Offline'], unknown: ['—', 'Unknown'],
+ needsInput: ['?', 'Needs you'], failed: ['✗', 'Failed'], working: ['⠋', 'Working'],
+ starting: ['◌', 'Starting'], done: ['✓', 'Done'], idle: ['', 'Idle'],
+ stopped: ['Ⅱ', 'Stopped'], offline: ['⊘', 'Offline'], unknown: ['—', 'Unknown'],
}
export const SPINNER = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']
export const COLUMNS = [
- { key: 'name', label: 'Harness', width: 280, required: true },
- { key: 'activity', label: 'Status', width: 116 }, { key: 'engine', label: 'Agent', width: 114 },
- { key: 'machine', label: 'Machine', width: 104 }, { key: 'project', label: 'Project', width: 180 },
- { key: 'branch', label: 'Branch', width: 184 },
- { key: 'cpu', label: 'CPU %', width: 86, numeric: true, help: 'Process tree CPU, as reported by ps. Can exceed 100% across cores; averaging varies by OS.' },
- { key: 'rssBytes', label: 'RAM', width: 92, numeric: true, help: 'Resident memory of the engine and its child processes. Shared pages may be counted more than once.' },
- { key: 'tokens', label: 'Tokens', width: 86, numeric: true },
- { key: 'lastActivity', label: 'Last active', width: 128, numeric: true },
- { key: 'model', label: 'Model', width: 190, optional: true },
- { key: 'enginePid', label: 'PID', width: 80, numeric: true, optional: true },
- { key: 'agentId', label: 'Harness ID', width: 220, optional: true },
- { key: 'sessionId', label: 'Conversation ID', width: 220, optional: true },
- { key: 'home', label: 'Folder', width: 240, optional: true },
- { key: 'actions', label: '', width: 100, required: true },
+ { key: 'name', label: 'Harness', width: 250, required: true, group: 'Session' },
+ { key: 'activity', label: 'Status', width: 112, group: 'Session' },
+ { key: 'engine', label: 'Agent', width: 118, group: 'Session' },
+ { key: 'machine', label: 'Machine', width: 120, group: 'Session' },
+ { key: 'cpu', label: 'CPU %', width: 84, numeric: true, group: 'Resources', help: 'Interval CPU of this process tree. 100% is one core; multiple cores can exceed 100%.' },
+ { key: 'rssBytes', label: 'RAM', width: 94, numeric: true, group: 'Resources', help: 'Resident memory, including child processes. Shared memory pages can overlap. Shared servers appear separately.' },
+ { key: 'gpuPercent', label: 'GPU %', width: 84, numeric: true, group: 'Resources', help: 'Summed process GPU utilization; can exceed 100% across processes or devices. NVIDIA on Linux where supported; — means unavailable. Cloud model GPU usage is not local usage.' },
+ { key: 'workspaceBytes', label: 'Storage', width: 98, numeric: true, group: 'Resources', help: 'Workspace disk space, including existing files. Shared folders repeat per row but count once in totals. Updated at most once a minute; stopping keeps these files.' },
+ { key: 'tokens', label: 'Tokens', width: 98, numeric: true, group: 'AI usage', help: 'Total conversation input and output, including cached input once. Reported by the owning agent; — means unreported.' },
+ { key: 'tokensPerMinute', label: 'Tokens/min', width: 110, numeric: true, group: 'AI usage', help: 'Change in total conversation tokens per minute across recent ledger updates. Includes input and cache; not model output speed.' },
+ { key: 'lastActivity', label: 'Last active', width: 110, numeric: true, group: 'Session', help: 'Last conversation activity reported by the daemon, not a file modification time.' },
+ { key: 'model', label: 'Model', width: 190, group: 'AI usage', optional: true },
+ { key: 'inputTokens', label: 'Input tokens', width: 116, numeric: true, group: 'AI usage', optional: true, help: 'Conversation input, including cache reads and cache writes.' },
+ { key: 'outputTokens', label: 'Output tokens', width: 124, numeric: true, group: 'AI usage', optional: true, help: 'Conversation output, including reasoning once.' },
+ { key: 'cachedTokens', label: 'Cached input', width: 124, numeric: true, group: 'AI usage', optional: true, help: 'Input read from cache. A subset of Input tokens; do not add it again.' },
+ { key: 'gpuMemoryBytes', label: 'GPU memory', width: 122, numeric: true, group: 'Resources', optional: true, help: 'Reported NVIDIA compute allocations in this process tree. — means unavailable, not zero. Shared model servers are not charged to every conversation.' },
+ { key: 'diskReadBytesPerSecond', label: 'Disk read/s', width: 112, numeric: true, group: 'Resources', optional: true, help: 'Process-tree physical disk reads per second on Linux. macOS or restricted counters show —.' },
+ { key: 'diskWriteBytesPerSecond', label: 'Disk write/s', width: 116, numeric: true, group: 'Resources', optional: true, help: 'Process-tree physical disk writes per second on Linux. Counter resets show —.' },
+ { key: 'transcriptBytes', label: 'Transcript', width: 108, numeric: true, group: 'Resources', optional: true, help: 'Size of the conversation file, where the agent uses an individual transcript. Shared databases show —.' },
+ { key: 'processCount', label: 'Processes', width: 100, numeric: true, group: 'Resources', optional: true },
+ { key: 'createdAt', label: 'Started', width: 110, numeric: true, group: 'Session', optional: true, help: 'When this harness was registered, including time before a resume.' },
+ { key: 'project', label: 'Project', width: 180, group: 'Session', optional: true },
+ { key: 'branch', label: 'Branch', width: 180, group: 'Session', optional: true },
+ { key: 'enginePid', label: 'PID', width: 80, numeric: true, group: 'Session', optional: true },
+ { key: 'agentId', label: 'Harness ID', width: 220, group: 'Session', optional: true },
+ { key: 'sessionId', label: 'Conversation ID', width: 220, group: 'Session', optional: true },
+ { key: 'home', label: 'Folder', width: 240, group: 'Session', optional: true },
]
-export function visibleRows(rows, { query = '', filter = 'all', sort = 'lastActivity', direction = -1 } = {}) {
- const q = query.trim().toLocaleLowerCase()
- const rank = Object.keys(ACTIVITY)
- return rows.filter(row => (filter === 'all' || 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 => v?.toLocaleLowerCase().includes(q))))
+export const PRESETS = {
+ overview: COLUMNS.filter(c => !c.optional).map(c => c.key),
+ resources: ['name', 'activity', 'machine', 'cpu', 'rssBytes', 'gpuPercent', 'gpuMemoryBytes', 'workspaceBytes', 'diskReadBytesPerSecond', 'diskWriteBytesPerSecond', 'processCount'],
+ ai: ['name', 'activity', 'engine', 'machine', 'model', 'tokens', 'tokensPerMinute', 'inputTokens', 'outputTokens', 'cachedTokens', 'lastActivity'],
+}
+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)
+ && (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))))
.sort((a, b) => {
let av = a[sort], bv = b[sort]
if (av == null && bv != null) return 1
if (bv == null && av != null) return -1
if (sort === 'activity') { av = rank.indexOf(av); bv = rank.indexOf(bv) }
- const compared = typeof av === 'number' && typeof bv === 'number' ? av - bv : String(av ?? '').localeCompare(String(bv ?? ''), undefined, { numeric: true })
+ const compared = typeof av === 'number' && typeof bv === 'number' ? av - bv
+ : String(av ?? '').localeCompare(String(bv ?? ''), undefined, { numeric: true })
return compared * direction || a.id.localeCompare(b.id)
})
}
export const number = n => n == null ? '—' : Intl.NumberFormat('en', { notation: 'compact', maximumFractionDigits: 1 }).format(n)
-export const memory = n => n == null ? '—' : n >= 1024 ** 3 ? (n / 1024 ** 3).toFixed(1) + ' GB' : Math.round(n / 1024 ** 2) + ' MB'
+export const memory = n => n == null ? '—' : n >= 1e9 ? Math.round(n / 1e9) + ' GB' : Math.round(n / 1e6) + ' MB'
+export const bytes = n => n == null ? '—' : n >= 1e6 ? memory(n) : n >= 1e3 ? Math.round(n / 1e3) + ' KB' : Math.round(n) + ' B'
+export const percent = n => n == null ? '—' : Math.round(n) + '%'
export const age = (stamp, now = Date.now()) => {
if (stamp == null) return '—'
const s = Math.max(0, (now - stamp) / 1000)
return s < 60 ? 'now' : s < 3600 ? Math.floor(s / 60) + 'm ago' : s < 86400 ? Math.floor(s / 3600) + 'h ago' : Math.floor(s / 86400) + 'd ago'
}
+export function formatValue(key, value) {
+ if (['cpu', 'gpuPercent'].includes(key)) return percent(value)
+ if (['rssBytes', 'workspaceBytes', 'gpuMemoryBytes', 'transcriptBytes'].includes(key)) return bytes(value)
+ if (key.endsWith('PerSecond')) return value == null ? '—' : bytes(value) + '/s'
+ if (['tokens', 'inputTokens', 'outputTokens', 'cachedTokens', 'tokensPerMinute'].includes(key)) return number(value)
+ if (['lastActivity', 'createdAt'].includes(key)) return age(value)
+ return value ?? '—'
+}
+export function sumReading(rows, key) {
+ const known = rows.map(r => r[key]).filter(n => typeof n === 'number' && Number.isFinite(n) && n >= 0)
+ return { value: rows.length && !known.length ? null : known.reduce((a, b) => a + b, 0), partial: known.length < rows.length }
+}
+export function storageTotal(rows) {
+ const included = [], known = rows.filter(r => r.workspaceBytes != null && (r.workspacePath || r.cwd))
+ .sort((a, b) => (a.workspacePath || a.cwd).length - (b.workspacePath || b.cwd).length)
+ for (const row of known) {
+ const path = row.workspacePath || row.cwd
+ if (!included.some(r => r.machineId === row.machineId && (path === r.path || path.startsWith(r.path + '/')))) included.push({ ...row, path })
+ }
+ return { value: included.length ? included.reduce((n, r) => n + r.workspaceBytes, 0) : rows.length ? null : 0,
+ partial: known.length < rows.length }
+}