The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Improve Harness Monitor and add per-harness macOS GPU readings (#578)
Dee5aad6f6d86e2
diff --git a/cli/src/lib/__fixtures__/macos-gpu.m b/cli/src/lib/__fixtures__/macos-gpu.mnew file mode 100644index 000000000..3883ff139--- /dev/null+++ b/cli/src/lib/__fixtures__/macos-gpu.m@@ -0,0 +1,37 @@+// Disposable Metal workload for RUN_MACOS_GPU=1. No windows or user files.+#import <Foundation/Foundation.h>+#import <Metal/Metal.h>+#include <stdio.h>++int main(void) {+ @autoreleasepool {+ id<MTLDevice> device = MTLCreateSystemDefaultDevice();+ NSError *error = nil;+ NSString *source = @"#include <metal_stdlib>\nusing namespace metal;\n"+ "kernel void work(device float *out [[buffer(0)]], uint i [[thread_position_in_grid]]) {"+ "float x = float(i) * 0.001f; for (uint j = 0; j < 512; ++j) x = sin(x) + 0.01f; out[i] = x; }";+ id<MTLLibrary> library = [device newLibraryWithSource:source options:nil error:&error];+ id<MTLFunction> function = [library newFunctionWithName:@"work"];+ id<MTLComputePipelineState> pipeline = function ? [device newComputePipelineStateWithFunction:function error:&error] : nil;+ if (!pipeline) { fprintf(stderr, "Metal unavailable: %s\n", error.description.UTF8String); return 1; }+ id<MTLCommandQueue> queue = [device newCommandQueue];+ id<MTLBuffer> buffer = [device newBufferWithLength:65536 * sizeof(float) options:MTLResourceStorageModeShared];+ NSDate *until = [NSDate dateWithTimeIntervalSinceNow:20];+ BOOL ready = NO;+ while (until.timeIntervalSinceNow > 0) {+ @autoreleasepool {+ id<MTLCommandBuffer> command = [queue commandBuffer];+ id<MTLComputeCommandEncoder> encoder = [command computeCommandEncoder];+ [encoder setComputePipelineState:pipeline];+ [encoder setBuffer:buffer offset:0 atIndex:0];+ [encoder dispatchThreadgroups:MTLSizeMake(256, 1, 1) threadsPerThreadgroup:MTLSizeMake(256, 1, 1)];+ [encoder endEncoding];+ [command commit];+ [command waitUntilCompleted];+ if (command.status == MTLCommandBufferStatusError) return 2;+ if (!ready) { puts("ready"); fflush(stdout); ready = YES; }+ }+ }+ }+ return 0;+}diff --git a/cli/src/lib/harnessResources.spec.ts b/cli/src/lib/harnessResources.spec.tsindex f95b3c937..551185efa 100644--- a/cli/src/lib/harnessResources.spec.ts+++ b/cli/src/lib/harnessResources.spec.ts@@ -1,5 +1,6 @@import { describe, expect, it, vi } from 'vitest'import { createHarnessResourcesReader, parseResourceProcesses, type ResourceProcess } from './harnessResources.js'+import type { ProcessTelemetry } from './harnessTelemetry.js'const start = 'Wed Sep 30 10:00:00 2026'const row = (pid: number, parent = 1, memoryBytes = 100, cpuMs = 10): ResourceProcess => ({ pid, parent, memoryBytes, cpuMs, start })@@ -115,3 +116,31 @@ it('attributes GPU and disk rates only to owned trees and validates counter idennow += 5000; snapshot = [row(10), { ...row(11, 10), start: 'replacement' }]expect((await read()).agents[0].diskReadBytesPerSecond).toBeNull()})++it('attributes macOS GPU intervals to harness children and shared servers once, never other apps or reused PIDs', async () => {+ let now = 10_000, sampleAt = 1000, gpuNs = 0n+ let snapshot = [row(10), row(11, 10), row(12, 11), row(20), row(50), row(90)]+ const telemetry = vi.fn(async (pids: number[]) => new Map(pids.map(pid => [pid, {+ readBytes: null, writeBytes: null, gpuMemoryBytes: null,+ macGpu: { sampledAt: sampleAt, contexts: new Map(pid === 10 || pid === 20 ? [] : [[String(pid), gpuNs]]) },+ } satisfies ProcessTelemetry])))+ const read = createHarnessResourcesReader(() => [agent('a', 10), agent('nested', 12), agent('idle', 20)], {+ now: () => now, sample: async () => snapshot, telemetry,+ }, async () => [{ pid: 50, start, agentIds: ['a', 'idle'] }, { pid: 50, start, agentIds: ['a', 'idle'] }])+ expect((await read()).agents.every(value => value.gpuPercent === null)).toBe(true)+ now += 5000; sampleAt += 4000; gpuNs += 1000000000n+ const measured = await read()+ expect(measured.agents.map(value => value.gpuPercent)).toEqual([25, 25, 0])+ expect(measured.shared).toHaveLength(1)+ expect(measured.shared![0].gpuPercent).toBe(25)+ expect(telemetry).toHaveBeenLastCalledWith([10, 11, 12, 20, 50])+ expect(() => JSON.stringify(measured)).not.toThrow() // raw BigInt counters stay local+ now += 5000; sampleAt += 5000; gpuNs += 1000000000n+ snapshot = snapshot.map(value => value.pid === 11 ? { ...value, start: 'reused PID' } : value)+ expect((await read()).agents[0].gpuPercent).toBeNull()+ now += 5000+ telemetry.mockRejectedValueOnce(new Error('unavailable'))+ expect((await read()).agents[0].gpuPercent).toBeNull()+ now += 5000; sampleAt += 10000+ expect((await read()).agents[0].gpuPercent).toBeNull()+})diff --git a/cli/src/lib/harnessResources.ts b/cli/src/lib/harnessResources.tsindex c88f73dca..cc1103680 100644--- a/cli/src/lib/harnessResources.ts+++ b/cli/src/lib/harnessResources.ts@@ -5,6 +5,7 @@ import { env } from '../config/env.js'import { promisify } from 'node:util'import type { ProcessIdentity } from './terminalTypes.js'import { readProcessTelemetry, type ProcessTelemetry } from './harnessTelemetry.js'+import { macProcessGpuPercent } from './macosProcessGpu.js'const exec = promisify(execFile)type Agent = { agentId: string; processIdentity?: ProcessIdentity | null; engine?: string; codexHome?: string | null }@@ -152,7 +153,14 @@ export function createHarnessResourcesReader(agents: () => readonly Agent[], depconst 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 macGpu = pids.some(pid => telemetry.get(pid)?.macGpu != null)+ const gpuUsage = pids.map(pid => {+ const next = telemetry.get(pid)+ if (!macGpu) return next?.gpuPercent ?? null+ if (previous?.rows.get(pid)?.start !== byPid.get(pid)?.start) return null+ return macProcessGpuPercent(previousTelemetry.get(pid)?.macGpu, next?.macGpu)+ })+ const knownGpu = gpuUsage.filter((n): n is number => n != null)const rate = (key: 'readBytes' | 'writeBytes') => {if (!pids.length || elapsed <= 0 || elapsed > 60_000) return nulllet delta = 0@@ -164,7 +172,8 @@ export function createHarnessResourcesReader(agents: () => readonly Agent[], depreturn 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.gpuPercent = knownGpu.length && (!macGpu || knownGpu.length === pids.length)+ ? knownGpu.reduce((sum, n) => sum + n, 0) : nullvalue.diskReadBytesPerSecond = rate('readBytes')value.diskWriteBytesPerSecond = rate('writeBytes')value.processes = pids.flatMap(pid => {diff --git a/cli/src/lib/harnessTelemetry.ts b/cli/src/lib/harnessTelemetry.tsindex a90c97b09..5f6c3cdbe 100644--- a/cli/src/lib/harnessTelemetry.ts+++ b/cli/src/lib/harnessTelemetry.ts@@ -2,9 +2,10 @@ import { execFile } from 'node:child_process'import { readFile, realpath, stat } from 'node:fs/promises'import { isAbsolute } from 'node:path'import { promisify } from 'node:util'+import { readMacProcessGpu, type MacProcessGpu } from './macosProcessGpu.js'const exec = promisify(execFile)-export type ProcessTelemetry = { readBytes: number | null; writeBytes: number | null; gpuMemoryBytes: number | null; gpuPercent?: number | null }+export type ProcessTelemetry = { readBytes: number | null; writeBytes: number | null; gpuMemoryBytes: number | null; gpuPercent?: number | null; macGpu?: MacProcessGpu }const count = (value: string | undefined) => value != null && /^\d+$/.test(value.trim()) && Number.isSafeInteger(Number(value)) ? Number(value) : nullexport function parseProcessIo(text: string): Pick<ProcessTelemetry, 'readBytes' | 'writeBytes'> {@@ -60,9 +61,14 @@ async function processGpus(): Promise<{ memory: Map<number, number | null>; usag} catch { gpuRetryAfter = Date.now() + 60_000; return empty() }}-/** Only owned processes are read. No privilege escalation or whole-machine fallback. */+/** Only owned processes are returned. No privilege escalation or whole-machine fallback. */export async function readProcessTelemetry(pids: number[]): Promise<Map<number, ProcessTelemetry>> {if (!pids.length) return new Map()+ if (process.platform === 'darwin') {+ const gpu = await readMacProcessGpu(pids)+ return new Map(pids.map(pid => [pid, { readBytes: null, writeBytes: null, gpuMemoryBytes: null,+ macGpu: gpu.get(pid) ?? { sampledAt: performance.now(), contexts: null } }]))+ }const gpu = await processGpus(), result = new Map<number, ProcessTelemetry>()let index = 0await Promise.all(Array.from({ length: Math.min(8, pids.length) }, async () => {diff --git a/cli/src/lib/macosProcessGpu.integration.spec.ts b/cli/src/lib/macosProcessGpu.integration.spec.tsnew file mode 100644index 000000000..c9ed72c4e--- /dev/null+++ b/cli/src/lib/macosProcessGpu.integration.spec.ts@@ -0,0 +1,59 @@+import { execFile, spawn, type ChildProcess } from 'node:child_process'+import { mkdtemp, rm } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { fileURLToPath } from 'node:url'+import { promisify } from 'node:util'+import { setTimeout as delay } from 'node:timers/promises'+import { expect, it } from 'vitest'+import { createHarnessResourcesReader, parseResourceProcesses } from './harnessResources.js'++const exec = promisify(execFile)+const enabled = process.platform === 'darwin' && process.env.RUN_MACOS_GPU === '1'++it.skipIf(!enabled)('measures a real Metal harness while an idle harness stays at zero', async () => {+ const directory = await mkdtemp(join(tmpdir(), 'harness-metal-test-'))+ const children: ChildProcess[] = []+ const launch = async (file: string, args: string[]) => {+ const child = spawn(file, args, { stdio: ['ignore', 'pipe', 'pipe'] })+ children.push(child)+ await new Promise<void>((resolve, reject) => {+ const timeout = setTimeout(() => reject(new Error('Fixture startup timed out')), 15_000)+ const finish = (error?: Error) => { clearTimeout(timeout); error ? reject(error) : resolve() }+ child.once('error', finish)+ child.once('exit', code => finish(new Error(`Fixture exited: ${code}`)))+ child.stdout!.once('data', () => finish())+ })+ return child.pid!+ }+ try {+ const binary = join(directory, 'metal-fixture')+ await exec('/usr/bin/clang', ['-fobjc-arc', '-framework', 'Foundation', '-framework', 'Metal',+ fileURLToPath(new URL('./__fixtures__/macos-gpu.m', import.meta.url)), '-o', binary], { timeout: 30_000 })+ const gpuPid = await launch(binary, [])+ const idlePid = await launch(process.execPath, ['-e', 'console.log("ready"); setInterval(() => {}, 1000)'])+ const { stdout } = await exec('ps', ['-p', `${gpuPid},${idlePid}`, '-o', 'pid=,ppid=,rss=,time=,lstart='], {+ env: { ...process.env, LC_ALL: 'C' },+ })+ const agents = parseResourceProcesses(stdout).map(row => ({ agentId: String(row.pid),+ processIdentity: { pid: row.pid, startMarker: row.start, executable: 'test fixture' } }))+ expect(agents).toHaveLength(2)+ const read = createHarnessResourcesReader(() => agents, undefined, async () => [])+ expect((await read()).agents.every(row => row.gpuPercent === null)).toBe(true)+ await delay(3000)+ const sample = await read()+ const gpu = sample.agents.find(row => row.agentId === String(gpuPid))!+ const idle = sample.agents.find(row => row.agentId === String(idlePid))!+ expect(gpu.gpuPercent).not.toBeNull()+ expect(gpu.gpuPercent!).toBeGreaterThan(0)+ expect(idle.gpuPercent).toBe(0)+ console.log(`Metal GPU ${gpu.gpuPercent}%; idle harness GPU ${idle.gpuPercent}%`)+ } finally {+ await Promise.all(children.map(child => new Promise<void>(resolve => {+ if (child.exitCode != null || child.signalCode != null) { resolve(); return }+ child.once('exit', () => resolve())+ child.kill('SIGTERM')+ })))+ await rm(directory, { recursive: true, force: true })+ }+}, 60_000)diff --git a/cli/src/lib/macosProcessGpu.spec.ts b/cli/src/lib/macosProcessGpu.spec.tsnew file mode 100644index 000000000..29215e90c--- /dev/null+++ b/cli/src/lib/macosProcessGpu.spec.ts@@ -0,0 +1,74 @@+import { describe, expect, it } from 'vitest'+import { macProcessGpuPercent, parseMacProcessGpu, type MacProcessGpu } from './macosProcessGpu.js'++const device = (id = '0x1') => `+-o AGXAccelerator <class AGXAccelerator, id ${id}, registered, active>+ | {+ | "PerformanceStatistics" = {"Device Utilization %"=99,"GPU Activity(%)"=99}+ | }+`+const client = (id: string, pid: number, properties: string) => ` +-o GPUClient <class GPUClient, id ${id}, !registered, active>+ {+ "IOUserClientCreator" = "pid ${pid}, process"+ ${properties}+ }+`++describe('macOS process GPU counters', () => {+ it('reads Apple Silicon AppUsage by PID and API, without device usage or duplicate contexts', () => {+ const metal = client('0x2', 123, '"AppUsage" = ({"API"="Metal","accumulatedGPUTime"=9007199254740993},{"API"="OpenGL","accumulatedGPUTime"=0})')+ const parsed = parseMacProcessGpu(device() + metal + metal+ + client('0x3', 1234, '"AppUsage" = ({"API"="Metal","accumulatedGPUTime"=7000})'))+ expect(parsed.complete).toBe(true)+ expect(parsed.processes.get(123)).toEqual(new Map([['0x2/Metal', 9007199254740993n], ['0x2/OpenGL', 0n]]))+ expect(parsed.processes.get(1234)).toEqual(new Map([['0x3/Metal', 7000n]]))+ expect(parsed.processes.size).toBe(2)+ })++ it('reads Intel/AMD scalar counters across devices; prefers AppUsage when both exist', () => {+ const parsed = parseMacProcessGpu(device() + client('0x2', 20, '"accumulatedGPUTime" = 0')+ + device('0x10') + client('0x11', 20, '"accumulatedGPUTime" = 500')+ + client('0x12', 20, '"accumulatedGPUTime" = 900\n "AppUsage" = ({"API"="Metal","accumulatedGPUTime"=100})'))+ expect(parsed.complete).toBe(true)+ expect(parsed.processes.get(20)).toEqual(new Map([['0x2/context', 0n], ['0x11/context', 500n], ['0x12/Metal', 100n]]))+ })++ it.each(['-1', '1.5', 'unknown', '18446744073709551616', '"123"'])('keeps malformed counters unknown: %s', counter => {+ const parsed = parseMacProcessGpu(device() + client('0x2', 20, '"accumulatedGPUTime" = 10')+ + client('0x3', 21, `"AppUsage" = ({"API"="Metal","accumulatedGPUTime"=${counter}})`))+ expect(parsed.processes.get(21)).toBeNull()+ expect(parsed.processes.get(20)).toEqual(new Map([['0x2/context', 10n]]))+ })++ it('does not invent idle readings on unsupported devices, ownerless data or incomplete dumps', () => {+ const supported = device() + client('0x2', 20, '"accumulatedGPUTime" = 10')+ expect(parseMacProcessGpu('').complete).toBe(false)+ expect(parseMacProcessGpu(device()).complete).toBe(false)+ expect(parseMacProcessGpu(supported + device('0x10')).complete).toBe(true) // unused secondary GPU+ const mixed = parseMacProcessGpu(supported + device('0x10') + client('0x11', 21, '"unsupported" = 1'))+ expect(mixed.processes.get(21)).toBeNull()+ expect(mixed.processes.get(20)).toEqual(new Map([['0x2/context', 10n]]))+ expect(parseMacProcessGpu(supported.slice(0, -5)).complete).toBe(false)+ expect(parseMacProcessGpu(supported.replace('"pid 20, process"', '"process 20"')).processes.size).toBe(0)+ expect(parseMacProcessGpu(supported + client('0x2', 20, '"accumulatedGPUTime" = 11')).processes.get(20))+ .toEqual(new Map([['0x2/context', 10n]]))+ expect(parseMacProcessGpu(device() + client('0x2', 20, '"AppUsage" = ({"API"="Metal"})')).processes.get(20)).toBeNull()+ })++ const sample = (sampledAt: number, counters: Array<[string, bigint]> | null): MacProcessGpu => ({ sampledAt, contexts: counters == null ? null : new Map(counters) })+ it('calculates GPU time per interval, including zero and simultaneous contexts above 100%', () => {+ const before = sample(1000, [['a', 9007199254740993n], ['b', 0n]])+ expect(macProcessGpuPercent(before, sample(4000, [['a', 9007202254740993n], ['b', 1500000000n]]))).toBe(150)+ expect(macProcessGpuPercent(before, { ...before, sampledAt: 4000 })).toBe(0)+ expect(macProcessGpuPercent(sample(1000, []), sample(4000, []))).toBe(0)+ })++ it('rejects the first interval, resets, retired/replaced contexts, failures and long gaps', () => {+ const before = sample(1000, [['a', 500n]])+ for (const next of [sample(2000, [['a', 499n]]), sample(2000, []), sample(2000, [['b', 999n]]),+ sample(2000, [['a', 999n], ['b', 0n]]), sample(1000, [['a', 999n]]), sample(62000, [['a', 999n]]), sample(2000, null)]) {+ expect(macProcessGpuPercent(before, next)).toBeNull()+ }+ expect(macProcessGpuPercent(undefined, before)).toBeNull()+ expect(macProcessGpuPercent(before, undefined)).toBeNull()+ })+})diff --git a/cli/src/lib/macosProcessGpu.ts b/cli/src/lib/macosProcessGpu.tsnew file mode 100644index 000000000..2e52f1a13--- /dev/null+++ b/cli/src/lib/macosProcessGpu.ts@@ -0,0 +1,123 @@+import { execFile } from 'node:child_process'+import { promisify } from 'node:util'++const exec = promisify(execFile)+export type MacProcessGpu = { sampledAt: number; contexts: Map<string, bigint> | null }+type RegistryGpu = { processes: Map<number, Map<string, bigint> | null>; complete: boolean }++const nanoseconds = (text: string): bigint | null => {+ if (!/^\d+$/.test(text)) return null+ const value = BigInt(text)+ return value <= 0xffffffffffffffffn ? value : null+}++/** IOAccelerator clients expose cumulative nanoseconds: AppUsage on AGX+ * (Apple Silicon), or accumulatedGPUTime directly on Intel/AMD contexts.+ * Device PerformanceStatistics are deliberately ignored: those include every+ * application. Registry entry IDs preserve context identity between samples.+ */+export function parseMacProcessGpu(text: string): RegistryGpu {+ const processes: RegistryGpu['processes'] = new Map()+ const devices = new Map<string, { readable: boolean; owners: Set<number> }>()+ const seen = new Set<string>()+ let device = '', valid = true+ let node: { id: string; owner?: string; usage?: string; time?: string; closed: boolean } | undefined+ const finish = () => {+ if (!node) return+ if (!node.closed) { valid = false; return }+ // ioreg can visit the same accelerator twice. Its counters keep advancing+ // while the dump is printed, so retain the first observation of each ID.+ if (seen.has(node.id)) return+ seen.add(node.id)+ const owner = /^"pid ([1-9]\d*), [^\n]*"$/.exec(node.owner ?? '')+ if (!owner || !Number.isSafeInteger(Number(owner[1]))) return+ const pid = Number(owner[1])+ devices.get(device)?.owners.add(pid)+ if (node.usage == null && node.time == null) return+ const counters = new Map<string, bigint>()+ let known = true+ if (node.usage != null) {+ // ioreg -w 0 prints each property on one untruncated line. AppUsage is+ // an array of flat dictionaries, one per graphics API.+ const entries = node.usage.match(/\{[^{}]*\}/g) ?? []+ if (!entries.length || !/^\([\s,]*\)$/.test(node.usage.replace(/\{[^{}]*\}/g, ''))) known = false+ for (const [i, entry] of entries.entries()) {+ const api = /"API"\s*=\s*"([^"\\]+)"/.exec(entry)?.[1] ?? String(i)+ const raw = /(?:\{|,)\s*"accumulatedGPUTime"\s*=\s*([^,}]+)/.exec(entry)?.[1].trim()+ const value = raw == null ? null : nanoseconds(raw)+ if (value == null || counters.has(api)) known = false+ else counters.set(api, value)+ }+ } else {+ const value = nanoseconds(node.time!)+ if (value == null) known = false+ else counters.set('context', value)+ }+ if (!known) { processes.set(pid, null); return }+ const accelerator = devices.get(device)+ if (accelerator) accelerator.readable = true+ if (processes.get(pid) === null) return+ const previous = processes.get(pid) ?? new Map<string, bigint>()+ for (const [api, value] of counters) {+ const key = `${node.id}/${api}`+ previous.set(key, value)+ }+ processes.set(pid, previous)+ }+ for (const line of text.split('\n')) {+ const header = /^([ |]*)\+-o .+ <class [^,]+, id (0x[\da-f]+),/i.exec(line)+ if (header) {+ finish()+ if (!header[1].length) {+ device = header[2]+ if (!devices.has(device)) devices.set(device, { readable: false, owners: new Set() })+ }+ node = { id: header[2], closed: false }+ } else if (node) {+ if (/^[ |]*}\s*$/.test(line)) node.closed = true+ const property = /^[ |]*"(IOUserClientCreator|AppUsage|accumulatedGPUTime)"\s*=\s*(.*)$/.exec(line)+ if (property?.[1] === 'IOUserClientCreator') node.owner = property[2]+ else if (property?.[1] === 'AppUsage') node.usage = property[2]+ else if (property?.[1] === 'accumulatedGPUTime') node.time = property[2]+ }+ }+ finish()+ // An unused secondary GPU has no clients and must not hide a primary GPU's+ // readings. Processes using a driver without counters remain unknown.+ for (const accelerator of devices.values()) {+ if (!accelerator.readable) for (const pid of accelerator.owners) processes.set(pid, null)+ }+ return { processes, complete: valid && [...devices.values()].some(value => value.readable) }+}++let retryAfter = 0+export async function readMacProcessGpu(pids: number[]): Promise<Map<number, MacProcessGpu>> {+ if (!pids.length || Date.now() < retryAfter) return new Map()+ try {+ const { stdout } = await exec('/usr/sbin/ioreg', ['-r', '-c', 'IOAccelerator', '-l', '-w', '0'], {+ encoding: 'utf8', timeout: 2200, maxBuffer: 8 * 1024 * 1024,+ })+ const sampledAt = performance.now(), snapshot = parseMacProcessGpu(stdout)+ return new Map(pids.map(pid => [pid, { sampledAt,+ contexts: snapshot.complete ? snapshot.processes.get(pid) ?? (snapshot.processes.has(pid) ? null : new Map()) : null,+ }]))+ } catch {+ retryAfter = Date.now() + 60_000+ return new Map()+ }+}++/** First sample, counter resets and context churn are unknown for one interval.+ * The caller must also validate the process birth identity before using this. */+export function macProcessGpuPercent(before: MacProcessGpu | undefined, next: MacProcessGpu | undefined): number | null {+ if (!before?.contexts || !next?.contexts || before.contexts.size !== next.contexts.size) return null+ const elapsed = next.sampledAt - before.sampledAt+ if (elapsed <= 0 || elapsed > 60_000) return null+ let delta = 0n+ for (const [id, value] of next.contexts) {+ const previous = before.contexts.get(id)+ if (previous == null || value < previous) return null+ delta += value - previous+ }+ return Math.round(Number(delta) / (elapsed * 10_000) * 10) / 10+}diff --git a/desktop/design/desktop-ui-migration.md b/desktop/design/desktop-ui-migration.mdindex 3cd54c901..d8052fc43 100644--- a/desktop/design/desktop-ui-migration.md+++ b/desktop/design/desktop-ui-migration.md@@ -32,6 +32,32 @@ on 2026-09-30; the unmerged checkpoints below describe earlier review stages.| Native tabs / footer / menus | System-font curved tabs with names, hover close and Command-held hints; 10-point pane frames. Pane model control before an always-visible close icon. Remaining subscription usage at left and focused machine/project/branch/PR at right. Empty New Tabs hide the footer; modals isolate it, with a passive customization preview || Linux / browser presentation | Shared light/dark, narrow and enlarged-text fixtures cover responsive behavior; physical Linux/browser platform validation is not claimed |+Harness Monitor refinement (2026-10-02): the table now lists only open harnesses,+including idle and starting sessions. Saved history and Open controls are removed.+Every row has an always-visible 32-point × target, pinned to the right during+horizontal scrolling. Closing reviews one session and retains history and files.+Harness, Status, CPU, RAM, GPU and SSD lead the table, before agent and project+metadata. Footer totals remain scoped to open owned harnesses and their shared+servers. macOS GPU readings use process-owned IOAccelerator time counters;+first samples and unavailable counters show —.++Validation: 120 monitor tests, 25 daemon resource/telemetry tests and 16 Flutter+footer/session tests pass, with TypeScript and changed-file Flutter analysis+clean. An opt-in native Metal fixture on an Intel Mac verifies nonzero GPU use+for its harness and zero for a separate idle harness. Apple Silicon counters+have parser coverage, not hardware validation. The full CLI suite has 8,496+passing tests, 46 skipped and four failures in unchanged tests: the doctor+timeout and tmux buffer-size assertion reproduce on clean main; the two+local-model cleanup failures pass in isolation on both branches.++The synthetic browser preview was checked in [light appearance](images/harness-monitor-open-light.png)+and [an 800×650 dark pane](images/harness-monitor-open-narrow.png), where every+primary resource column and × fit. Closing updates counts/totals. Earlier review+also checked idle filtering, empty search, frozen updates disabling closing,+keyboard cancellation and horizontal scrolling at 640×620. This does not+establish native app, VoiceOver or enlarged-text behavior; no real harness was+stopped during review.+Legacy/test-only paths (including the old NewAgentDialog entry when`newHarnessOpensInBox` is disabled) are excluded from the visible migration.The standalone MachinesManager, old machine-link dialog, and genericdiff --git a/desktop/design/images/harness-monitor-open-light.png b/desktop/design/images/harness-monitor-open-light.pngnew file mode 100644index 000000000..8e2dd1c97Binary files /dev/null and b/desktop/design/images/harness-monitor-open-light.png differdiff --git a/desktop/design/images/harness-monitor-open-narrow.png b/desktop/design/images/harness-monitor-open-narrow.pngnew file mode 100644index 000000000..229e379a8Binary files /dev/null and b/desktop/design/images/harness-monitor-open-narrow.png differdiff --git a/desktop/design/workspace-status-bar.md b/desktop/design/workspace-status-bar.mdindex b413e53e0..de1b3942e 100644--- a/desktop/design/workspace-status-bar.md+++ b/desktop/design/workspace-status-bar.md@@ -22,14 +22,15 @@ The context follows the focused pane. The branch stays clickable in thefooter; pane headers do not repeat it. An empty New Tab keeps the footer whenthere are live sessions to inspect.-The left side shows running harnesses and their CPU, RAM, GPU and SSD consumption across connected+The left side shows open harnesses (including idle and starting sessions) and their CPU, RAM, GPU and SSD consumption across connectedowned machines, followed by subscription allowance used per account. The focused-pane contextremains 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 tabsand 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.+with only open sessions, sortable resource and AI metrics, an inspector and a visible × close+button on every row. Closing reviews one harness, ends its work and retains history and files.Use spaces of 0.75 character cells within components and two cells between complete groups,including the count. Adjacent controls contribute one cell of horizontal padding on each side;@@ -41,7 +42,8 @@ workspace ink at every usage level. Do not pad numbers or add dots, decimal figuCPU is the sum of attributable process-tree interval use; 100% is one core, so multicore and fleettotals can exceed 100%. RAM is process-tree resident memory. Nested harness roots are excluded fromthe 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 —;+process GPU time per interval on supported macOS drivers and process utilization on Linux NVIDIA.+Multiple contexts/devices can exceed 100%. First samples and unavailable counters 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).diff --git a/desktop/lib/state/harness_monitor.dart b/desktop/lib/state/harness_monitor.dartindex cd8be6005..913b6d211 100644--- a/desktop/lib/state/harness_monitor.dart+++ b/desktop/lib/state/harness_monitor.dart@@ -22,7 +22,7 @@ class HarnessMonitor extends ChangeNotifier {List<HarnessSession> get sessions => harnessSessions(app, includeLive: true);List<HarnessSession> get live => sessions- .where((row) => row.running && !row.machine.machine.isShared)+ .where((row) => row.live && !row.machine.machine.isShared).toList();HarnessResources? reading(HarnessSession row) {@@ -127,15 +127,15 @@ class HarnessMonitor extends ChangeNotifier {}String get resourceDetail =>- '${live.length} running harnesses across connected machines.\n'+ '${live.length} open harnesses across connected machines. Totals cover these harnesses only.\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'+ 'GPU: harness process GPU use on supported macOS and Linux NVIDIA drivers. First samples and unavailable counters show —. Cloud model GPU usage is not reported.\n''SSD: workspace disk space, shared and nested folders counted once per machine. Files remain after stopping.\n''Totals include available readings and may be partial. — means unavailable. Click to open Harness Monitor.';String get detail =>- '${live.length} running across connected machines. Click to open Harness Monitor.\n'+ '${live.length} open across connected machines, including idle and starting harnesses. Click to open Harness Monitor.\n''${HarnessResources.explanation}${sharedLabel == null ? '' : '\n$sharedLabel, included once in the session monitor.'}';void start() {diff --git a/desktop/lib/state/harness_sessions.dart b/desktop/lib/state/harness_sessions.dartindex 3ed83dded..fb7714a86 100644--- a/desktop/lib/state/harness_sessions.dart+++ b/desktop/lib/state/harness_sessions.dart@@ -72,6 +72,9 @@ class HarnessSession {machine.connectionStatus == ConnectionStatus.connected) &&(!machine.isLocalMachine || machine.usesLocalTransport);bool get running => online && !agent.isStopped && agent.terminalAvailable;+ bool get live =>+ running ||+ (online && !agent.isStopped && agent.launchState == 'starting');bool get canOpen =>open ||(online &&@@ -140,7 +143,7 @@ List<HarnessSession> harnessSessions((includeLive &&!machine.machine.isShared &&!agent.isStopped &&- agent.terminalAvailable))+ (agent.terminalAvailable || agent.launchState == 'starting')))HarnessSession(machine: machine,agent: agent,diff --git a/desktop/test/harness_resources_test.dart b/desktop/test/harness_resources_test.dartindex 88f540d5b..00f39e98a 100644--- a/desktop/test/harness_resources_test.dart+++ b/desktop/test/harness_resources_test.dart@@ -146,6 +146,111 @@ void main() {expect(monitor.resourceDetail, contains('Files remain after stopping'));});+ test('footer counts only open owned harnesses and never uses whole-machine totals', () 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: 'Idle', terminalAvailable: true),+ const Agent(id: 'starting', name: 'Starting', launchState: 'starting'),+ const Agent(+ id: 'saved',+ name: 'Saved',+ status: 'stopped',+ terminalAvailable: true,+ ),+ const Agent(id: 'gone', name: 'Exited'),+ ];+ for (final id in ['offline', 'shared']) {+ app.machineStates[id] =+ MachineState(+ Machine(+ machineId: id,+ authMode: MachineAuthMode.remote,+ isShared: id == 'shared',+ ),+ )+ ..nodeOnline = id != 'offline'+ ..connectionStatus = ConnectionStatus.connected+ ..agents = [+ const Agent(id: 'a0', name: 'Elsewhere', terminalAvailable: true),+ ];+ }+ connection.reply = {+ 'cpuPercent': 99,+ 'memoryBytes': 64e9,+ 'gpuPercent': 98,+ 'workspaceBytes': 900e9,+ 'harnesses': {+ 'sampledAt': '2026-10-02T12:00:00Z',+ 'agents': [+ {+ 'agentId': 'a0',+ 'cpuPercent': 5,+ 'memoryBytes': 1e9,+ 'workspaceBytes': 2e9,+ 'workspacePath': '/work',+ },+ for (final id in ['saved', 'gone', 'unregistered'])+ {+ 'agentId': id,+ 'cpuPercent': 900,+ 'memoryBytes': 80e9,+ 'gpuPercent': 95,+ 'workspaceBytes': 700e9,+ 'workspacePath': '/other',+ },+ ],+ 'shared': [+ {+ 'kind': 'codex',+ 'agentIds': ['a0'],+ 'cpuPercent': 2,+ 'memoryBytes': 0.4e9,+ },+ {+ 'kind': 'codex',+ 'agentIds': ['saved'],+ 'cpuPercent': 900,+ 'memoryBytes': 80e9,+ 'gpuPercent': 95,+ },+ ],+ },+ };+ await monitor.refresh();+ expect(monitor.live.map((r) => r.agent.id), ['a0', 'starting']);+ expect(monitor.label, 'Harnesses 2');+ expect(monitor.metricsLabel(), 'CPU 7% RAM 1 GB GPU — SSD 2 GB');+ expect(+ monitor.resourceDetail,+ contains('Totals cover these harnesses only'),+ );+ expect(monitor.resourceDetail, contains('supported macOS and Linux NVIDIA'));+ expect(connection.calls, [+ {'type': 'machine_resources', 'harnesses': true, 'storage': true},+ ]);++ app.machineStates['m']!.agents = [+ const Agent(id: 'a0', name: 'Closed', status: 'stopped'),+ ];+ expect(monitor.label, 'Harnesses 0');+ expect(monitor.metricsLabel(), 'CPU 0% RAM 0 MB GPU 0% SSD 0 MB');+ expect(monitor.sharedReadings, isEmpty);++ app.machineStates['m']!.agents = [+ const Agent(id: 'a0', name: 'Reopened', terminalAvailable: true),+ ];+ connection.reply.remove('harnesses');+ await monitor.refresh();+ expect(monitor.metricsLabel(), 'CPU — RAM — GPU — SSD —');+ });+testWidgets('uses one machine request for every session; tokens are existing data',(tester) async {diff --git a/store/agents/harness-monitor/README.md b/store/agents/harness-monitor/README.mdindex 0d6c4f19c..9664c5cad 100644--- a/store/agents/harness-monitor/README.md+++ b/store/agents/harness-monitor/README.md@@ -4,18 +4,22 @@ Inspect active harnesses across connected machines and decide what to stop. TheHarnesses, CPU, RAM, GPU and SSD controls select the existing Harness Monitor tab, creating one whenneeded. The tab uses the standard 70% viewer / 30% assistant split. Use the pane Zoom icon for a full-width table. Opening the table submits no model prompt.-Every visit starts with active sessions; RAM is the initial default sort. Filter by machine or activity, search session+The table lists only currently open harnesses on connected machines, including idle, working,+waiting and starting sessions. Closed sessions and offline history never appear in this table.+Harness, Status, CPU, RAM, GPU and SSD come first, followed by Agent, Tokens,+Machine, Project and Branch. RAM is the initial default sort. Filter by machine or activity, search sessionmetadata, and choose Overview, Resources or AI usage. Click a header to sort; unknown readings sortlast in either direction. Drag a separator or use its arrow keys to resize a column. Columns andwidths persist; search and status reset on entry. The harness name stays visible during horizontalscrolling. Arrow keys select; Enter or double-click opens the inspector. It includes process IDs,-parent IDs and resource readings. Open focuses one existing pane for the selected session, or starts stopped work in one new tab when no pane remains. The Stopped filter shows saved sessions.+parent IDs and resource readings. Each row has a visible × close button that stays available during+horizontal scrolling. Saved sessions remain available in Open Harness (Cmd-P).-Stop… reviews one selected session before asking its owning daemon to stop the validated process.+The × button reviews that harness before asking its owning daemon to stop the validated process+and close its panes. A confirmed close removes the row and updates the totals.Conversation history, launch settings and files remain. The daemon checks conversation identity againbefore stopping. Offline or disconnected sessions cannot be stopped. Freeze updates holds the displayed readings-without affecting work, and disables Stop/Open until live updates return. Offline sessions are an explicit filter;-saved history is also available in Open Harness (Cmd-P).+without affecting work, and disables closing until live updates return.## Metric definitions@@ -23,8 +27,9 @@ saved history is also available in Open Harness (Cmd-P).| --- | --- || 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. |+| GPU % | GPU use of the harness process tree. macOS reads IOAccelerator clients owned by each PID: Apple Silicon AppUsage and Intel/AMD accumulatedGPUTime counters. GPU nanoseconds divided by the sample interval give percent. Linux reads NVIDIA process utilization. Summed use can exceed 100% across contexts/devices. Initial samples, context changes, resets and unavailable drivers show —. Cloud inference is not local GPU use. |+| GPU memory | NVIDIA compute allocations on supported Linux drivers. macOS and unsupported counters show —. |+| 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. |@@ -36,14 +41,14 @@ Model, framework, machine, project, branch, folder, process count, start time anprovide context. There is no invented dollar cost: subscription plans, caching and provider pricescannot 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+Totals describe the shown open harnesses and their shared servers. ≥ marks partial totals; — means+unavailable, never measured zero. Footer totals cover the open harnesses in its count acrossconnected 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 whilevisible. 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+stop polling. The daemon coalesces process reads, verifies PID birth identity, bounds macOS IORegistry/NVIDIA commandsand directory walks, and keeps telemetry off the terminal-input queue. No extra transcript scan isstarted by the table or footer. Older daemons retain basic inventory but require updating for newmetrics. Identity and all stop actions remain machine-scoped through the paired bridge.@@ -56,6 +61,9 @@ informs sortable columns, filtering, a focused inspector and an explicit stop repausing 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).+The macOS investigation used [Stats' GPU reader](https://github.com/exelban/stats/blob/master/Modules/GPU/reader.swift)+to locate IOAccelerator data and [GPUI's process GPU probe](https://github.com/longbridge/gpui-kit/blob/main/crates/fps/src/gpu/macos.rs)+to verify the per-process counters. Stats' whole-device percentages are never included in harness totals.`npm test` uses isolated policy/state fixtures. `node test/preview.mjs` serves synthetic sessions andsimulated stops, without a daemon bridge or model call. Daemon checks live in harnessResources,@@ -63,6 +71,10 @@ harnessTelemetry, agentTokenUsage and backendSocket specs. Desktop tests cover frounding, 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 establishsupport for every driver.+On macOS, `cd cli && RUN_MACOS_GPU=1 npm test -- src/lib/macosProcessGpu.integration.spec.ts`+compiles a disposable Metal workload with the Command Line Tools and verifies that only its+harness gets nonzero GPU use while a separate idle harness stays at zero. It stops only its own+fixtures. Apple Silicon parsing is covered by fixtures; Intel/AMD has been checked on hardware.The hps CLI offers explicit stop/open and reviewed cleanup commands; old pause/resume names remain compatibility aliases.Rules/pins live in ~/.config/harness/policy.jsonc; receipts live under ~/.harness/monitor/.diff --git a/store/agents/harness-monitor/lib/inventory.mjs b/store/agents/harness-monitor/lib/inventory.mjsindex b0dbfc7cb..7674d6c1b 100644--- a/store/agents/harness-monitor/lib/inventory.mjs+++ b/store/agents/harness-monitor/lib/inventory.mjs@@ -48,7 +48,7 @@ export function mergeRows(agents, { state = {}, machine = null, local = true, noid, agentId: agent.id, sessionId: agent.sessionId || null,name: agent.name || agent.title || 'Untitled harness', title: agent.title || null,engine: agent.engine, ...parseModel(agent.selectedModel),- state: !online ? 'offline' : stopped ? 'stopped' : terminalAvailable ? (agent.engine === 'terminal' ? 'terminal' : 'running') : 'gone',+ state: !online ? 'offline' : stopped ? 'stopped' : terminalAvailable ? (agent.engine === 'terminal' ? 'terminal' : 'running') : agent.launch?.state === 'starting' ? 'starting' : 'gone',activity, activityKnown: monitor?.activityKnown === true,stateSince: lastActivity, stoppedAt: stopped ? lastActivity : null,pane: agent.tmuxPane || null, paneTarget: null,diff --git a/store/agents/harness-monitor/test/inventory.test.mjs b/store/agents/harness-monitor/test/inventory.test.mjsindex c3cf953c9..5ad2a1f24 100644--- a/store/agents/harness-monitor/test/inventory.test.mjs+++ b/store/agents/harness-monitor/test/inventory.test.mjs@@ -28,6 +28,15 @@ test('monitor cannot stop itself, and starts/failures outrank activity', () => {assert.equal(merge({ launch: { state: 'starting' } }).activity, 'starting')assert.equal(merge({ launch: { state: 'failed', error: 'RESUME_UNCONFIRMED' } }).activity, 'needsInput')})+test('starting harnesses stay live before their terminal becomes available', () => {+ const starting = merge({ terminal: { available: false }, launch: { state: 'starting' } })+ assert.equal(starting.state, 'starting')+ assert.equal(starting.live, true)+ assert.equal(starting.canStop, false)+ const exited = merge({ terminal: { available: false }, launch: { state: 'failed' } })+ assert.equal(exited.state, 'gone')+ assert.equal(exited.live, false)+})test('cached remote rows survive disconnect; reconnection refreshes and unlinked machines disappear', async () => {const remote = { at: 0, answers: new Map() }; let online = true, linked = true, reads = 0const options = { remote, remoteIntervalMs: 0, reportMachines: async () => ({ machines: linked ? [{ machineId: 'm1', name: 'Office', online }] : [] }),diff --git a/store/agents/harness-monitor/test/preview.mjs b/store/agents/harness-monitor/test/preview.mjsindex 2baae0f86..ba7fec220 100644--- a/store/agents/harness-monitor/test/preview.mjs+++ b/store/agents/harness-monitor/test/preview.mjs@@ -18,10 +18,10 @@ const rows = Array.from({ length: Number(process.env.PREVIEW_ROWS || 24) }, (_,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 ? 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 }] },+ 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 === 0 ? null : i % 2 ? 6 : i % 6 ? 0 : 24, 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, 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: [] }),+ 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: 0 }], problems: [], machines: [] }),verbs: { stop: async row => {Object.assign(row, { state: 'stopped', live: false, activity: 'stopped', canStop: false, cpu: 0, rssBytes: 0 })return { ok: true, action: 'stop', id: row.id, name: row.name }diff --git a/store/agents/harness-monitor/test/table.test.mjs b/store/agents/harness-monitor/test/table.test.mjsindex ee55b7fda..b191e0f0b 100644--- a/store/agents/harness-monitor/test/table.test.mjs+++ b/store/agents/harness-monitor/test/table.test.mjs@@ -2,9 +2,9 @@ import assert from 'node:assert/strict'import { test } from 'node:test'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', live: true, online: false, branch: 'main', machine: 'office' },+ { id: 'm1/a', name: 'Agent 10', cpu: 5, activity: 'working', live: true, branch: 'fix/hello', machine: 'office' },+ { id: 'm2/a', name: 'Agent 2', cpu: 0, activity: 'idle', live: true, branch: 'main', machine: 'studio' },+ { id: 'm1/b', name: 'Unknown', cpu: null, activity: 'unknown', live: true, branch: 'main', machine: 'office' },]test('sort is stable, numeric and keeps unknown measurements last in either direction', () => {assert.deepEqual(visibleRows(rows, { filter: 'all', sort: 'cpu', direction: -1 }).map(r => r.cpu), [5, 0, null])@@ -14,7 +14,7 @@ test('sort is stable, numeric and keeps unknown measurements last in either dire})test('search matches metadata and combines with plain status filters', () => {assert.equal(visibleRows(rows, { query: 'HELLO' })[0].id, 'm1/a')- assert.equal(visibleRows(rows, { query: 'office', filter: 'offline' })[0].id, 'm1/b')+ assert.equal(visibleRows(rows, { query: 'office', filter: 'unknown' })[0].id, 'm1/b')assert.equal(visibleRows(rows, { query: 'office', filter: 'idle' }).length, 0)})test('formatters distinguish zero from unknown and handle future timestamps', () => {@@ -23,13 +23,28 @@ test('formatters distinguish zero from unknown and handle future timestamps', ()assert.equal(age(null), '—'); assert.equal(age(1100, 1000), 'now')})-test('opens with active sessions only and never treats saved history as processes', () => {+test('every filter excludes saved history, exited processes and cached offline sessions', () => {const history = { id: 'saved', name: 'Old', state: 'stopped', activity: 'stopped', live: false }- assert.deepEqual(visibleRows([...rows, history]).map(r => r.id).sort(), ['m1/a', 'm2/a'])- assert.equal(visibleRows([...rows, history], { filter: 'all' }).length, 3)- assert.deepEqual(visibleRows([...rows, history], { filter: 'stopped' }).map(r => r.id), ['saved'])+ const closed = [history, { ...rows[0], id: 'offline', online: false },+ { ...rows[1], id: 'exited', state: 'gone', live: false },+ { ...history, id: 'stale-live-flag', live: true },+ { ...rows[0], id: 'offline-state', state: 'offline' }]+ assert.deepEqual(visibleRows([...rows, ...closed]).map(r => r.id).sort(), ['m1/a', 'm1/b', 'm2/a'])+ for (const filter of ['all', 'working', 'idle', 'stopped', 'offline']) {+ assert.equal(visibleRows(closed, { filter }).length, 0)+ }+ assert.equal(visibleRows([...rows, ...closed], { query: 'Old' }).length, 0)assert.equal(visibleRows(rows, { machine: 'missing' }).length, 0)})+test('idle, completed, waiting, failed and starting harnesses remain until they close', () => {+ const open = ['working', 'idle', 'done', 'needsInput', 'failed', 'starting', 'unknown'].map(activity => ({+ id: activity, live: true, state: activity === 'starting' ? 'starting' : 'running', activity, cpu: 0,+ }))+ assert.equal(visibleRows(open).length, open.length)+ for (const row of open) assert.deepEqual(visibleRows(open, { filter: row.activity }), [row])+ open[1] = { ...open[1], state: 'stopped', activity: 'stopped', live: false }+ assert.equal(visibleRows(open).length, open.length - 1)+})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 })diff --git a/store/agents/harness-monitor/viewer/app.css b/store/agents/harness-monitor/viewer/app.cssindex 7fbb38649..58e7a7987 100644--- a/store/agents/harness-monitor/viewer/app.css+++ b/store/agents/harness-monitor/viewer/app.css@@ -28,7 +28,6 @@ nav select { max-width:200px; background:var(--row); border-color:var(--line); }.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; }@@ -46,15 +45,19 @@ table { border-collapse:separate; border-spacing:0; table-layout:fixed; min-widt#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 td { height:40px; padding:4px 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 th.row-actions,#table td.row-actions { position:sticky; right:0; z-index:2; padding:4px 10px; text-align:center; border-left:1px solid var(--line); }+#table th.row-actions { z-index:4; }+.close-harness { display:inline-flex; align-items:center; justify-content:center; width:32px; height:32px; min-height:32px; padding:0; border:1px solid var(--line); border-radius:8px; color:var(--text); }+.close-harness span { font:22px/1 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif; }+.close-harness:hover:not(:disabled),.close-harness:focus-visible { color:var(--red); border-color:var(--red); background:var(--row); }+#table td:first-child strong { 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; }.unknown { color:var(--muted); }.status { display:inline-flex; align-items:center; gap:7px; font-size:12px; }diff --git a/store/agents/harness-monitor/viewer/app.js b/store/agents/harness-monitor/viewer/app.jsindex 4a38ff0d5..cb4d43c47 100644--- a/store/agents/harness-monitor/viewer/app.js+++ b/store/agents/harness-monitor/viewer/app.js@@ -4,19 +4,19 @@ const dom = {search: el('search'), filter: el('filter'), machine: el('machine'), columns: el('columns'), columnOptions: el('column-options'),grid: el('grid'), table: el('table'), colgroup: el('colgroup'), head: el('head'), body: el('body'),empty: el('empty'), count: el('count'), message: el('message'), updated: el('updated'), problems: el('problems'),- refresh: el('refresh'), freeze: el('freeze'), live: el('live-status'), inspect: el('inspect'), stop: el('stop'), open: el('open'),+ refresh: el('refresh'), freeze: el('freeze'), live: el('live-status'), inspect: el('inspect'),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'), inspectOpen: el('inspect-open'),+ 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'+const STORAGE_KEY = 'harness-monitor.process-table.v4'let saved = {}try { saved = JSON.parse(localStorage.getItem(STORAGE_KEY) || '{}') || {} } catch { /* optional preference storage */ }const state = {- rows: [], snapshot: null, query: '', filter: 'active', machine: 'all', // Every visit starts with active work.+ rows: [], snapshot: null, query: '', filter: 'all', machine: 'all', // Only currently open harnesses, in every view.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: {},@@ -41,26 +41,16 @@ async function post(path, payload) {if (!response.ok || result.error) throw new Error(result.error || 'Request failed. Refresh and try again.')return result}-// Native and remote viewers share a bounded navigation-only host bridge.-window.harnessHostQueue = []-function openRow(id) {- const row = state.rows.find(r => r.id === id)- if (!canOpen(row)) return- const action = { action: 'open', machineId: row.machineId, agentId: row.agentId }- if (window.HarnessHost?.postMessage) window.HarnessHost.postMessage(JSON.stringify(action))- else if (window.harnessEmbedded) {- if (window.harnessHostQueue.length < 8) window.harnessHostQueue.push(action)- } else message('Open this viewer inside Harness to use this action.')-}+const CLOSE_WIDTH = 56const 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))}function resizeColumns() {- for (const col of dom.colgroup.children) col.style.width = state.widths[col.dataset.key] + 'px'+ for (const col of dom.colgroup.children) col.style.width = (col.dataset.key === 'close' ? CLOSE_WIDTH : state.widths[col.dataset.key]) + 'px'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'+ dom.table.style.width = activeColumns().reduce((sum, c) => sum + state.widths[c.key], CLOSE_WIDTH) + 'px'}function buildColumns() {dom.colgroup.replaceChildren(); dom.head.replaceChildren(); state.nodes.clear(); dom.body.replaceChildren()@@ -83,6 +73,9 @@ function buildColumns() {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)}+ const closeWidth = element('col'); closeWidth.dataset.key = 'close'; dom.colgroup.append(closeWidth)+ const closeHeader = element('th', null, 'row-actions'); closeHeader.scope = 'col'+ closeHeader.append(element('span', 'Close harness', 'sr-only')); tr.append(closeHeader)dom.head.append(tr); resizeColumns(); render()}function columnMenu() {@@ -123,10 +116,10 @@ const engineNames = { codex: 'Codex', claude: 'Claude', opencode: 'OpenCode', cufunction createRow(row) {const tr = element('tr'); tr.dataset.id = row.idtr.onclick = () => { state.selected = row.id; select(); dom.grid.focus({ preventScroll: true }) }- tr.ondblclick = () => inspect(row.id)+ tr.ondblclick = event => { if (!event.target.closest('button')) inspect(row.id) }for (const col of activeColumns()) {const td = element('td', null, col.numeric ? 'numeric' : ''); td.dataset.key = col.key- if (col.key === 'name') td.append(element('strong'), element('small'))+ if (col.key === 'name') td.append(element('strong'))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@@ -134,13 +127,26 @@ function createRow(row) {}tr.append(td)}+ const actions = element('td', null, 'row-actions'), close = element('button', null, 'close-harness')+ close.type = 'button'+ const mark = element('span', '×'); mark.setAttribute('aria-hidden', 'true'); close.append(mark)+ close.onclick = event => { event.stopPropagation(); state.selected = row.id; select(); reviewStop(row.id) }+ actions.append(close); tr.append(actions)return tr}function updateRow(tr, row) {for (const td of tr.children) {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')+ if (td.classList.contains('row-actions')) {+ const close = td.firstChild+ close.disabled = !canStop(row)+ close.setAttribute('aria-label', 'Close ' + row.name)+ close.title = state.busy.has(row.id) ? 'Closing…' : state.frozen ? 'Turn on live updates before closing.'+ : !state.connected || !currentSnapshot() ? 'Reconnect before closing.'+ : row.unavailable || (row.canStop ? 'Close ' + row.name : 'This harness is not ready to close.')+ close.setAttribute('aria-busy', String(state.busy.has(row.id)))+ } else if (key === 'name') {+ text(td.children[0], row.name)td.title = [row.name, row.home, row.model].filter(Boolean).join('\n')} else if (key === 'activity') {const [mark, label] = ACTIVITY[row.activity] || ACTIVITY.unknown@@ -162,12 +168,10 @@ function updateRow(tr, row) {}const currentSelection = () => state.shown.find(r => r.id === state.selected)const currentSnapshot = () => ['ok', 'degraded'].includes(state.snapshot?.status)-const canOpen = row => row?.canOpen && state.connected && currentSnapshot() && !state.frozen && !state.busy.has(row.id)-const canStop = row => row?.canStop && state.connected && currentSnapshot() && !state.frozen && !state.busy.has(row.id)+const canStop = row => row?.canStop && isLive(row) && state.connected && currentSnapshot() && !state.frozen && !state.busy.has(row.id)function select() {for (const [id, node] of state.nodes) node.setAttribute('aria-selected', String(id === state.selected))- const row = currentSelection(); dom.inspect.disabled = !row; dom.stop.disabled = !canStop(row); dom.open.disabled = !canOpen(row)- dom.stop.title = row ? row.unavailable || (state.frozen ? 'Turn on live updates before stopping.' : 'Stop ' + row.name + '; keep history and files') : 'Select a harness to stop'+ dom.inspect.disabled = !currentSelection()}const totalText = (total, formatter) => total.value == null ? '—' : (total.partial ? '≥' : '') + formatter(total.value)function summary() {@@ -178,14 +182,14 @@ function summary() {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.'],+ ['GPU', sumReading(resources, 'gpuPercent'), n => Math.round(n) + '%', 'Harness process GPU use on supported macOS and Linux NVIDIA drivers. First samples and unavailable counters show —. Cloud model GPU usage is not reported.'],+ ['SSD', 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.frozen ? 'Last readings' : 'Shown sessions'} · ≥ partial · — unavailable`, 'summary-scope'); dom.summary.append(scope)+ const scope = element('p', `${(!state.connected || !currentSnapshot()) && !state.frozen ? 'Last harness readings' : 'Shown harnesses only'} · ≥ 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) {@@ -210,16 +214,18 @@ function render() {select(); dom.grid.scrollTop = scrollTop; dom.grid.scrollLeft = scrollLeftfor (const th of dom.head.querySelectorAll('th')) {const col = COLUMNS.find(c => c.key === th.dataset.key)+ if (!col) continueth.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.firstElementChild, !ready ? 'Connecting to your machines…' : state.query ? 'No matching harnesses' : state.filter === 'offline' ? 'No offline sessions' : state.filter === 'stopped' ? 'No stopped sessions' : 'No active harnesses')- text(dom.empty.lastElementChild, !ready ? 'Active sessions will appear here.' : state.query || state.machine !== 'all' || state.filter !== 'active' ? 'Try another search, machine, or status.' : 'Running sessions appear automatically. Use the Stopped filter or Open Harness to find saved sessions.')- const active = state.rows.filter(r => isLive(r) && r.online !== false).length- text(dom.count, `${state.shown.length} shown · ${active} active`)+ const filtered = state.query || state.machine !== 'all' || state.filter !== 'all'+ text(dom.empty.firstElementChild, !ready ? 'Connecting to your machines…' : filtered ? 'No matching harnesses' : 'No open harnesses')+ text(dom.empty.lastElementChild, !ready ? 'Open harnesses will appear here.' : filtered ? 'Try another search, machine, or status.' : 'Harnesses appear here while they are open, including when idle.')+ const active = state.rows.filter(isLive).length+ text(dom.count, `${filtered ? state.shown.length + ' of ' : ''}${active} open ${active === 1 ? 'harness' : 'harnesses'}`)text(dom.updated, state.frozen ? 'Updates frozen' : state.receivedAt ? 'Updated ' + age(state.receivedAt) : 'Connecting…')text(dom.live, state.frozen ? 'Frozen' : !state.connected ? 'Reconnecting' : state.snapshot?.status === 'starting' ? 'Connecting' : !currentSnapshot() ? 'Unavailable' : 'Live')dom.live.classList.toggle('inactive', state.frozen || !state.connected || !currentSnapshot())@@ -232,8 +238,8 @@ function inspect(id) {}function renderInspector() {const row = state.rows.find(r => r.id === state.inspecting)- dom.inspectStop.disabled = !canStop(row); dom.inspectOpen.disabled = !canOpen(row)- if (!row) { text(dom.inspectContext, 'This harness is no longer active.'); return }+ dom.inspectStop.disabled = !canStop(row)+ if (!row) { text(dom.inspectContext, 'This harness is no longer open.'); 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()@@ -267,14 +273,11 @@ function renderInspector() {function reviewStop(id) {const row = state.rows.find(r => r.id === id); if (!canStop(row)) returnstate.review = { id: row.id, sessionId: row.sessionId, lastActivity: row.lastActivity, name: row.name }- text(dom.stopTitle, 'Stop “' + row.name + '”?')+ text(dom.stopTitle, 'Close “' + 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 = falsedom.stopDialog.showModal()}-dom.open.onclick = () => openRow(state.selected)-dom.inspectOpen.onclick = () => openRow(state.inspecting)-dom.stop.onclick = () => reviewStop(state.selected)dom.inspect.onclick = () => inspect(state.selected)dom.inspectStop.onclick = () => reviewStop(state.inspecting)dom.inspectClose.onclick = () => dom.inspector.close()@@ -289,12 +292,15 @@ dom.stopConfirm.onclick = async () => {dom.stopConfirm.disabled = truereturn}- state.busy.add(review.id); dom.stopConfirm.disabled = true; dom.stopCancel.disabled = true; text(dom.stopResult, 'Stopping…'); select()+ state.busy.add(review.id); dom.stopConfirm.disabled = true; dom.stopCancel.disabled = true; text(dom.stopResult, 'Closing…'); render()try {const reply = await post('/api/act', { verb: 'stop', ids: [review.id], manual: true, expected: [review] })const result = reply.results?.find(r => r.id === review.id)- if (!result?.ok) { text(dom.stopResult, result?.detail || 'Stop was not confirmed. Refresh to check.'); return }- message('Stopped ' + review.name + '. History and files kept.'); dom.stopDialog.close()+ if (!result?.ok) { text(dom.stopResult, result?.detail || 'Close was not confirmed. Refresh to check.'); return }+ state.rows = state.rows.filter(r => r.id !== review.id || r.sessionId !== review.sessionId)+ message('Closed ' + review.name + '. History and files kept.'); dom.stopDialog.close()+ if (dom.inspector.open && state.inspecting === review.id) dom.inspector.close()+ dom.grid.focus({ preventScroll: true })} catch (error) { text(dom.stopResult, error.message + ' Refresh to check before trying again.') }finally { state.busy.delete(review.id); dom.stopCancel.disabled = false; render() }}@@ -326,7 +332,7 @@ dom.freeze.onclick = () => {render()}function applySnapshot(snapshot) {- state.snapshot = snapshot; state.rows = snapshot.rows ?? []; state.receivedAt = Date.now()+ state.snapshot = snapshot; state.rows = (snapshot.rows ?? []).filter(isLive); 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])@@ -337,7 +343,7 @@ function applySnapshot(snapshot) {dom.machine.value = state.machine}dom.problems.hidden = !snapshot.problems?.length- text(dom.problems, (snapshot.problems ?? []).map(p => p.machine + ': ' + p.error).join(' · '))+ text(dom.problems, (snapshot.problems ?? []).map(p => p.machine + ': ' + String(p.error ?? 'Unavailable').replace('Offline — showing the last known sessions.', 'Offline — reconnect to view open harnesses.')).join(' · '))render()}let streamdiff --git a/store/agents/harness-monitor/viewer/index.html b/store/agents/harness-monitor/viewer/index.htmlindex 23afc4ca0..d0d9c1520 100644--- a/store/agents/harness-monitor/viewer/index.html+++ b/store/agents/harness-monitor/viewer/index.html@@ -20,19 +20,18 @@<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="stopped">Stopped</option><option value="offline">Offline</option><option value="all">Including offline</option>+ <option value="all">All open harnesses</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></select><span class="spacer"></span>- <button id="open" disabled>Open</button>- <button id="inspect" disabled title="Inspect selected harness (Enter)">Inspect</button><button id="stop" class="danger" disabled>× Stop…</button>+ <button id="inspect" disabled title="Inspect selected harness (Enter)">Inspect</button><details id="columns"><summary>Columns</summary><div id="column-options" class="menu"></div></details><button id="freeze" title="Hold the displayed readings; running work continues">Freeze updates</button><button id="refresh" title="Refresh all machines">Refresh</button></nav><div id="problems" role="status" hidden></div>- <main id="grid" tabindex="0" aria-label="Active harness sessions. Arrow keys select, Enter inspects, Delete reviews stopping.">- <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 id="grid" tabindex="0" aria-label="Open harnesses. Arrow keys select, Enter inspects, Delete reviews closing.">+ <table id="table" aria-label="Open harnesses"><colgroup id="colgroup"></colgroup><thead id="head"></thead><tbody id="body"></tbody></table>+ <div id="empty"><strong>Connecting to your machines…</strong><p>Open harnesses 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>@@ -40,12 +39,12 @@<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-open" disabled>Open</button><button id="inspect-stop" class="danger">Stop harness…</button></div>+ <div class="dialog-actions"><button id="inspect-stop" class="danger">Close harness…</button></div></dialog><dialog id="stop-dialog" aria-labelledby="stop-title">- <h2 id="stop-title">Stop harness?</h2><p id="stop-context"></p><p>Its running work will end. Conversation history and workspace files are kept.</p>+ <h2 id="stop-title">Close harness?</h2><p id="stop-context"></p><p>Its running work will end and its panes will close. 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>+ <div class="dialog-actions"><button id="stop-cancel" autofocus>Cancel</button><button id="stop-confirm" class="danger filled">Close 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.jsindex 46a31e7ac..22d8be551 100644--- a/store/agents/harness-monitor/viewer/table.js+++ b/store/agents/harness-monitor/viewer/table.js@@ -6,15 +6,17 @@ export const ACTIVITY = {}export const SPINNER = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']export const COLUMNS = [- { key: 'name', label: 'Harness', width: 250, required: true, group: 'Session' },+ { key: 'name', label: 'Harness', width: 230, required: true, group: 'Session' },{ key: 'activity', label: 'Status', width: 112, group: 'Session' },+ { key: 'cpu', label: 'CPU %', width: 80, 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: 88, numeric: true, group: 'Resources', help: 'Resident memory, including child processes. Shared memory pages can overlap. Shared servers appear separately.' },+ { key: 'gpuPercent', label: 'GPU %', width: 80, numeric: true, group: 'Resources', help: 'GPU use of this process tree: GPU time per interval on supported macOS drivers, utilization on Linux NVIDIA. Can exceed 100% across processes or devices. First samples and unavailable counters show —. Cloud model GPU usage is not reported.' },+ { key: 'workspaceBytes', label: 'SSD', width: 88, 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: '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: 'machine', label: 'Machine', width: 120, group: 'Session' },+ { key: 'project', label: 'Project', width: 180, group: 'Session' },+ { key: 'branch', label: 'Branch', width: 180, group: 'Session' },{ 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 },@@ -27,8 +29,6 @@ export const COLUMNS = [{ 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 },@@ -36,14 +36,19 @@ export const COLUMNS = []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'],+ resources: ['name', 'activity', 'cpu', 'rssBytes', 'gpuPercent', 'workspaceBytes', 'gpuMemoryBytes', 'diskReadBytesPerSecond', 'diskWriteBytesPerSecond', 'processCount', 'machine'],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 } = {}) {+// Activity describes what an open harness is doing, not whether it is open.+// Saved history and cached offline inventory never become process rows.+export const isLive = row => row.online !== false+ && !['stopped', 'offline', 'gone'].includes(row.state)+ && !['stopped', 'offline'].includes(row.activity)+ && (row.live ?? ['running', 'terminal', 'starting'].includes(row.state))+export function visibleRows(rows, { query = '', filter = 'all', machine = 'all', sort = 'rssBytes', direction = -1 } = {}) {const q = query.trim().toLocaleLowerCase(), rank = Object.keys(ACTIVITY)- return rows.filter(row => (isLive(row) || (filter === 'stopped' && row.activity === 'stopped')) && (machine === 'all' || row.machineId === machine)- && (filter === 'all' || (filter === 'active' ? row.online !== false && row.activity !== 'offline' : row.activity === filter))+ return rows.filter(row => isLive(row) && (machine === 'all' || row.machineId === machine)+ && (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 => String(v ?? '').toLocaleLowerCase().includes(q)))).sort((a, b) => {