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.

Simplify the desktop dock with local CPU, RAM, and GPU readings (#550)

Dee04cb3d11e1a6
diff --git a/cli/src/lib/machineHardware.spec.ts b/cli/src/lib/machineHardware.spec.ts
new file mode 100644
index 000000000..4b03bdf87
--- /dev/null
+++ b/cli/src/lib/machineHardware.spec.ts
@@ -0,0 +1,95 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { parseDarwinGpus, parseDarwinMemory, parseLinuxMemory, parseNvidiaGpus,
+ readMachineDisk, readMachineGpus, readMachineMemory } from './machineHardware.js'
+
+const mocks = vi.hoisted(() => ({ command: vi.fn(), readFile: vi.fn(), statfs: vi.fn() }))
+vi.mock('node:child_process', () => {
+ const execFile = Object.assign(vi.fn(), { [Symbol.for('nodejs.util.promisify.custom')]: mocks.command })
+ return { execFile }
+})
+vi.mock('node:fs/promises', () => ({ readFile: mocks.readFile, statfs: mocks.statfs }))
+vi.mock('node:os', () => ({ totalmem: () => 8 * 1024 ** 3, freemem: () => 1024 ** 3, homedir: () => '/fixture' }))
+
+const platform = Object.getOwnPropertyDescriptor(process, 'platform')!
+const vm = `Mach Virtual Memory Statistics: (page size of 16384 bytes)
+Pages active: 100.
+Pages inactive: 80.
+Pages speculative: 20.
+Pages wired down: 50.
+Pages occupied by compressor: 30.
+Pages purgeable: 10.
+File-backed pages: 90.
+`
+afterEach(() => {
+ Object.defineProperty(process, 'platform', platform)
+ vi.resetAllMocks()
+})
+
+describe('host memory counters', () => {
+ it('subtracts reclaimable cache on macOS and reads pressure and swap separately', () => {
+ expect(parseDarwinMemory(vm, 8 * 1024 ** 3, '2\ntotal = 2048.00M used = 512.50M free = 1535.50M')).toEqual({
+ total: 8 * 1024 ** 3, available: 8 * 1024 ** 3 - 180 * 16384,
+ pressure: 'warning', swapUsedBytes: 512.5 * 1024 ** 2,
+ })
+ expect(parseDarwinMemory(vm, 8 * 1024 ** 3, '4')?.pressure).toBe('critical')
+ expect(parseDarwinMemory(vm, 8 * 1024 ** 3, '')?.swapUsedBytes).toBeNull()
+ expect(parseDarwinMemory(vm.replace('File-backed pages', 'missing'), 8 * 1024 ** 3, '')).toBeNull()
+ expect(parseDarwinMemory(vm, 10, '')).toBeNull()
+ })
+
+ it('uses Linux available memory rather than counting cache as used', () => {
+ expect(parseLinuxMemory('MemAvailable: 4096 kB\nSwapTotal: 1024 kB\nSwapFree: 512 kB\n', 8 * 1024 ** 2))
+ .toEqual({ total: 8 * 1024 ** 2, available: 4 * 1024 ** 2, swapUsedBytes: 512 * 1024 })
+ expect(parseLinuxMemory('MemFree: 4096 kB\n', 8 * 1024 ** 2)).toBeNull()
+ })
+
+ it.each(['darwin', 'linux'])('retains a portable memory reading when %s counters are inaccessible', async system => {
+ Object.defineProperty(process, 'platform', { ...platform, value: system })
+ mocks.command.mockRejectedValue(new Error('denied'))
+ mocks.readFile.mockRejectedValue(new Error('denied'))
+ expect(await readMachineMemory()).toEqual({ total: 8 * 1024 ** 3, available: 1024 ** 3 })
+ })
+})
+
+describe('optional hardware readings', () => {
+ it('preserves separate NVIDIA devices, zero usage and unavailable counters', () => {
+ const readings = parseNvidiaGpus('GPU-aaa, NVIDIA RTX 4090, 0, 1024, 24576\nGPU-bbb, NVIDIA RTX 4090, 90, 2048, 24576\nGPU-ccc, NVIDIA, [N/A], [N/A], [N/A]\nerror')
+ expect(readings.map(gpu => gpu.utilizationPercent)).toEqual([0, 90, null])
+ expect(readings[0].memoryUsedBytes).toBe(1024 ** 3)
+ expect(readings[2].memoryUsedBytes).toBeNull()
+ expect(parseNvidiaGpus('GPU-aaa, NVIDIA, 101, 2, 1')[0]).toMatchObject({ utilizationPercent: null, memoryUsedBytes: null })
+ })
+
+ it('reads Apple and Intel/AMD driver counters without counting registry aliases twice', () => {
+ const readings = parseDarwinGpus(`+-o AGX <class AGXAcceleratorG13X, id 0x123, registered>
+ "PerformanceStatistics" = {"Device Utilization %"=47}
+ +-o AMD <class AMDRadeonX5000, id 0x456, registered>
+ "PerformanceStatistics" = {"GPU Activity(%)"=65}
+ +-o AMD <class AMDRadeonX5000, id 0x456, registered>
+ "PerformanceStatistics" = {"GPU Activity(%)"=66}
+ +-o Intel <class IntelAccelerator, id 0x789, registered>
+ "PerformanceStatistics" = {"Device Utilization %"=0}
+ "poweredOffByAGC"=1`)
+ expect(readings).toEqual([
+ { id: '0x123', name: 'Apple GPU', utilizationPercent: 47 },
+ { id: '0x456', name: 'AMD GPU', utilizationPercent: 66 },
+ { id: '0x789', name: 'Intel GPU', utilizationPercent: null },
+ ])
+ expect(parseDarwinGpus('no driver counters')).toEqual([])
+ })
+
+ it.each(['darwin', 'linux', 'win32'])('missing GPU telemetry on %s stays unknown and commands are bounded', async system => {
+ Object.defineProperty(process, 'platform', { ...platform, value: system })
+ mocks.command.mockRejectedValue(new Error('not supported'))
+ expect(await readMachineGpus()).toEqual([])
+ expect(mocks.command.mock.calls[0][2]).toMatchObject({ timeout: 1200, maxBuffer: 2 * 1024 ** 2 })
+ expect(mocks.command.mock.calls[0][2].shell).toBeUndefined()
+ })
+
+ it('reports usable root disk space, preserving zero and unavailable readings', async () => {
+ mocks.statfs.mockResolvedValueOnce({ bsize: 4096, bavail: 0, blocks: 100 })
+ expect(await readMachineDisk()).toEqual({ diskFreeBytes: 0, diskTotalBytes: 409600 })
+ mocks.statfs.mockRejectedValueOnce(new Error('denied'))
+ expect(await readMachineDisk()).toEqual({ diskFreeBytes: null, diskTotalBytes: null })
+ })
+})
diff --git a/cli/src/lib/machineHardware.ts b/cli/src/lib/machineHardware.ts
new file mode 100644
index 000000000..50f1958de
--- /dev/null
+++ b/cli/src/lib/machineHardware.ts
@@ -0,0 +1,145 @@
+import { execFile } from 'node:child_process'
+import { readFile, statfs } from 'node:fs/promises'
+import { freemem, homedir, totalmem } from 'node:os'
+import { parse } from 'node:path'
+import { promisify } from 'node:util'
+
+const exec = promisify(execFile)
+const KiB = 1024
+const MiB = KiB ** 2
+export type MemoryPressure = 'normal' | 'warning' | 'critical'
+export interface GpuResource {
+ id: string
+ name: string
+ utilizationPercent: number | null
+ memoryUsedBytes?: number | null
+ memoryTotalBytes?: number | null
+}
+export interface MemoryReading {
+ total: number
+ available: number
+ pressure?: MemoryPressure | null
+ swapUsedBytes?: number | null
+}
+
+// Fixed arguments, bounded output and no shell, privileges, helper installation,
+// persistent process or timer. A missing driver/counter stays unavailable.
+async function command(file: string, args: string[]): Promise<string> {
+ const { stdout } = await exec(file, args, {
+ encoding: 'utf8', timeout: 1200, maxBuffer: 2 * MiB,
+ windowsHide: true, env: { ...process.env, LC_ALL: 'C' },
+ })
+ return stdout
+}
+function number(value: string | undefined): number | null {
+ if (value == null || !/^\d+(?:\.\d+)?$/.test(value.trim())) return null
+ const n = Number(value)
+ return Number.isFinite(n) && n >= 0 ? n : null
+}
+function percent(value: string | undefined): number | null {
+ const n = number(value)
+ return n != null && n <= 100 ? n : null
+}
+
+export function parseDarwinMemory(vm: string, total: number, sysctl: string): MemoryReading | null {
+ const pageSize = number(/page size of\s+(\d+)\s+bytes/.exec(vm)?.[1])
+ if (!pageSize || !Number.isFinite(total) || total <= 0) return null
+ const counts = new Map<string, number>()
+ for (const match of vm.matchAll(/^([^:\n]+):\s+(\d+)\.?\s*$/gm)) counts.set(match[1].trim(), Number(match[2]))
+ const keys = ['Pages active', 'Pages inactive', 'Pages speculative', 'Pages wired down',
+ 'Pages occupied by compressor', 'Pages purgeable', 'File-backed pages']
+ if (keys.some(key => !counts.has(key))) return null
+ const used = (keys.slice(0, 5).reduce((sum, key) => sum + counts.get(key)!, 0)
+ - counts.get('Pages purgeable')! - counts.get('File-backed pages')!) * pageSize
+ if (!Number.isFinite(used) || used < 0 || used > total) return null
+ const pressureLevel = /^\s*([124])\s*$/m.exec(sysctl)?.[1]
+ const swap = /used\s*=\s*([\d.]+)([KMG])\b/.exec(sysctl)
+ const swapValue = number(swap?.[1])
+ return { total, available: total - used,
+ pressure: pressureLevel === '1' ? 'normal' : pressureLevel === '2' ? 'warning' : pressureLevel === '4' ? 'critical' : null,
+ swapUsedBytes: swap && swapValue != null ? swapValue * ({ K: KiB, M: MiB, G: KiB ** 3 }[swap[2]]!) : null,
+ }
+}
+
+export function parseLinuxMemory(text: string, total: number): MemoryReading | null {
+ const values = new Map([...text.matchAll(/^(\w+):\s+(\d+)\s+kB$/gm)].map(m => [m[1], Number(m[2]) * KiB]))
+ const available = values.get('MemAvailable')
+ if (available == null || available > total || !Number.isFinite(total) || total <= 0) return null
+ const swapTotal = values.get('SwapTotal'), swapFree = values.get('SwapFree')
+ return { total, available,
+ swapUsedBytes: swapTotal != null && swapFree != null && swapFree <= swapTotal ? swapTotal - swapFree : null,
+ }
+}
+
+export async function readMachineMemory(): Promise<MemoryReading> {
+ const total = totalmem()
+ try {
+ if (process.platform === 'darwin') {
+ const [vm, pressure] = await Promise.all([
+ command('/usr/bin/vm_stat', []),
+ command('/usr/sbin/sysctl', ['-n', 'kern.memorystatus_vm_pressure_level', 'vm.swapusage']).catch(() => ''),
+ ])
+ const reading = parseDarwinMemory(vm, total, pressure)
+ if (reading) return reading
+ } else if (process.platform === 'linux') {
+ const reading = parseLinuxMemory(await readFile('/proc/meminfo', 'utf8'), total)
+ if (reading) return reading
+ }
+ } catch { /* Older/restricted hosts retain the portable OS reading. */ }
+ return { total, available: freemem() }
+}
+
+export function parseNvidiaGpus(text: string): GpuResource[] {
+ return text.split('\n').flatMap(line => {
+ const fields = line.split(',').map(s => s.trim())
+ if (fields.length !== 5 || !/^GPU-[\w-]+$/.test(fields[0]) || !fields[1]) return []
+ const used = number(fields[3]), total = number(fields[4])
+ const validMemory = used != null && total != null && total > 0 && used <= total
+ return [{ id: fields[0], name: fields[1], utilizationPercent: percent(fields[2]),
+ memoryUsedBytes: validMemory ? used * MiB : null,
+ memoryTotalBytes: validMemory ? total * MiB : null }]
+ })
+}
+
+export function parseDarwinGpus(text: string): GpuResource[] {
+ const devices = text.split(/(?=\+-o )/)
+ const readings = devices.flatMap(device => {
+ const header = /^\+-o (.+?)\s+<class ([^,]+), id (0x[\da-f]+)/i.exec(device)
+ const stats = /"PerformanceStatistics"\s*=\s*\{([^\n]+)\}/.exec(device)?.[1]
+ if (!header || !stats) return []
+ const read = (key: string) => new RegExp('"' + key + '"\\s*=\\s*(\\d+(?:\\.\\d+)?)').exec(stats)?.[1]
+ const poweredOff = /"poweredOffByAGC"\s*=\s*1\b/.test(device)
+ const utilizationPercent = poweredOff ? null : percent(read('Device Utilization %') ?? read('GPU Activity\\(%\\)'))
+ const model = /"model"\s*=\s*"([^"\n]+)"/.exec(device)?.[1]
+ const name = model ?? (/AGX/i.test(header[2]) ? 'Apple GPU' : /Intel/i.test(header[2]) ? 'Intel GPU'
+ : /AMD/i.test(header[2]) ? 'AMD GPU' : header[1])
+ return [{ id: header[3], name, utilizationPercent }]
+ })
+ // IORegistry may expose the same accelerator under multiple parents.
+ return [...new Map(readings.map(gpu => [gpu.id, gpu])).values()]
+}
+
+export async function readMachineGpus(): Promise<GpuResource[]> {
+ try {
+ if (process.platform === 'darwin') {
+ return parseDarwinGpus(await command('/usr/sbin/ioreg', ['-r', '-c', 'IOAccelerator', '-d', '1', '-l']))
+ }
+ if (process.platform === 'linux' || process.platform === 'win32') {
+ return parseNvidiaGpus(await command('nvidia-smi', [
+ '--query-gpu=uuid,name,utilization.gpu,memory.used,memory.total', '--format=csv,noheader,nounits',
+ ]))
+ }
+ } catch { /* GPU telemetry is optional; lack of it must never fail CPU/RAM. */ }
+ return []
+}
+
+export async function readMachineDisk(): Promise<{ diskFreeBytes: number | null; diskTotalBytes: number | null }> {
+ try {
+ const disk = await statfs(parse(homedir()).root)
+ const free = disk.bavail * disk.bsize, total = disk.blocks * disk.bsize
+ if (Number.isSafeInteger(free) && Number.isSafeInteger(total) && total > 0 && free >= 0 && free <= total) {
+ return { diskFreeBytes: free, diskTotalBytes: total }
+ }
+ } catch { /* Filesystem information is optional. */ }
+ return { diskFreeBytes: null, diskTotalBytes: null }
+}
diff --git a/cli/src/lib/machineResources.spec.ts b/cli/src/lib/machineResources.spec.ts
index 32b3de722..8b0e36894 100644
--- a/cli/src/lib/machineResources.spec.ts
+++ b/cli/src/lib/machineResources.spec.ts
@@ -1,49 +1,7 @@
-import { afterEach, describe, expect, it, vi } from 'vitest'
-import { cpus, freemem, totalmem } from 'node:os'
-import { readFile } from 'node:fs/promises'
-import { setTimeout as delay } from 'node:timers/promises'
+import { describe, expect, it, vi } from 'vitest'
import { createMachineResourcesReader } from './machineResources.js'
import { encryptDownFrame, encryptRpcResult } from './e2ee/applicationFrames.js'
-vi.mock('node:os', () => ({ cpus: vi.fn(), freemem: vi.fn(), totalmem: vi.fn() }))
-vi.mock('node:fs/promises', () => ({ readFile: vi.fn() }))
-vi.mock('node:timers/promises', () => ({ setTimeout: vi.fn(async () => {}) }))
-
-describe('OS resource sampling', () => {
- const platform = Object.getOwnPropertyDescriptor(process, 'platform')!
- afterEach(() => {
- Object.defineProperty(process, 'platform', platform)
- vi.clearAllMocks()
- })
-
- for (const system of ['darwin', 'linux']) {
- for (const proc of ['available', 'missing', 'denied']) {
- it(`${system}: ${proc} available-memory information`, async () => {
- Object.defineProperty(process, 'platform', { ...platform, value: system })
- vi.mocked(totalmem).mockReturnValue(8 * 1024 ** 3)
- vi.mocked(freemem).mockReturnValue(1024 ** 3)
- vi.mocked(readFile).mockReset()
- if (proc === 'denied') vi.mocked(readFile).mockRejectedValue(new Error('EACCES'))
- else vi.mocked(readFile).mockResolvedValue(proc === 'available'
- ? 'MemFree: 1048576 kB\nMemAvailable: 4194304 kB\n' : 'MemFree: 1048576 kB\n')
- const cpu = (idle: number, user: number) => ({
- model: 'fixture', speed: 3200, times: { user, idle, nice: 0, sys: 0, irq: 0 },
- })
- vi.mocked(cpus).mockReset()
- vi.mocked(cpus).mockReturnValueOnce([cpu(100, 50), cpu(100, 50)])
- .mockReturnValue([cpu(200, 150), cpu(200, 150)])
- expect(await createMachineResourcesReader()()).toEqual({
- cpuPercent: 50,
- memoryUsedBytes: (system === 'linux' && proc === 'available' ? 4 : 7) * 1024 ** 3,
- memoryTotalBytes: 8 * 1024 ** 3,
- })
- expect(delay).toHaveBeenCalledWith(200)
- expect(readFile).toHaveBeenCalledTimes(system === 'linux' ? 1 : 0)
- })
- }
- }
-})
-
function fixture() {
return {
cpuTimes: vi.fn()
@@ -117,6 +75,22 @@ describe('on-demand machine resources', () => {
expect(deps.wait).toHaveBeenCalledTimes(2)
})
+ it('keeps CPU/RAM available when optional hardware probes fail', async () => {
+ const hardware = vi.fn().mockRejectedValue(new Error('unsupported'))
+ expect(await createMachineResourcesReader({ ...fixture(), hardware })()).toEqual({
+ cpuPercent: 25, memoryUsedBytes: 20 * 1024 ** 3, memoryTotalBytes: 32 * 1024 ** 3,
+ })
+ })
+
+ it('returns optional hardware readings without combining GPUs', async () => {
+ const gpus = [
+ { id: 'a', name: 'First', utilizationPercent: 80 },
+ { id: 'b', name: 'Second', utilizationPercent: 60 },
+ ]
+ const deps = { ...fixture(), hardware: async () => ({ gpus, diskFreeBytes: 4000 }) }
+ expect(await createMachineResourcesReader(deps)()).toMatchObject({ gpus, diskFreeBytes: 4000 })
+ })
+
it('encrypts both the request and response between machines', () => {
expect(encryptDownFrame('machine_resources')).toBe(true)
expect(encryptRpcResult('machine_resources_result')).toBe(true)
diff --git a/cli/src/lib/machineResources.ts b/cli/src/lib/machineResources.ts
index 99f36b83f..4bcf58403 100644
--- a/cli/src/lib/machineResources.ts
+++ b/cli/src/lib/machineResources.ts
@@ -1,11 +1,16 @@
-import { cpus, freemem, totalmem } from 'node:os'
-import { readFile } from 'node:fs/promises'
+import { cpus } from 'node:os'
import { setTimeout as delay } from 'node:timers/promises'
+import { readMachineMemory, readMachineGpus, readMachineDisk, type GpuResource, type MemoryPressure, type MemoryReading } from './machineHardware.js'
export interface MachineResources {
cpuPercent: number | null
memoryUsedBytes: number | null
memoryTotalBytes: number | null
+ memoryPressure?: MemoryPressure | null
+ swapUsedBytes?: number | null
+ diskFreeBytes?: number | null
+ diskTotalBytes?: number | null
+ gpus?: GpuResource[]
}
type CpuTimes = { idle: number; total: number }
@@ -16,42 +21,43 @@ function cpuTimes(): CpuTimes {
}), { idle: 0, total: 0 })
}
-async function memory(): Promise<{ total: number; available: number }> {
- const total = totalmem()
- if (process.platform === 'linux') {
- try {
- // Reclaimable cache is available for work; MemFree alone counts it as used.
- const info = await readFile('/proc/meminfo', 'utf8')
- const available = /^MemAvailable:\s+(\d+)\s+kB$/m.exec(info)?.[1]
- if (available != null) return { total, available: Number(available) * 1024 }
- } catch { /* Older/restricted hosts still have the portable OS reading. */ }
- }
- return { total, available: freemem() }
-}
-
/** Demand-driven system readings. Concurrent panels share one sample, with no
* background timer or shell process while nobody is asking for machine stats. */
-export function createMachineResourcesReader(deps = {
- cpuTimes, memory, wait: () => delay(200), now: Date.now,
+export function createMachineResourcesReader(deps: {
+ cpuTimes: () => CpuTimes
+ memory: () => Promise<MemoryReading>
+ wait: () => Promise<void>
+ now: () => number
+ hardware?: () => Promise<Partial<MachineResources>>
+} = {
+ cpuTimes, memory: readMachineMemory, wait: () => delay(200), now: Date.now,
+ hardware: async () => {
+ const [gpus, disk] = await Promise.all([readMachineGpus(), readMachineDisk()])
+ return { gpus, ...disk }
+ },
}): () => Promise<MachineResources> {
let cached: { at: number; value: MachineResources } | undefined
let pending: Promise<MachineResources> | undefined
async function sample(): Promise<MachineResources> {
const before = deps.cpuTimes()
- await deps.wait()
+ const [, mem, hardware] = await Promise.all([
+ deps.wait(), deps.memory(), deps.hardware?.().catch(() => ({})) ?? Promise.resolve({}),
+ ])
const after = deps.cpuTimes()
const elapsed = after.total - before.total
const idle = after.idle - before.idle
const cpuPercent = Number.isFinite(elapsed) && Number.isFinite(idle)
&& elapsed > 0 && idle >= 0 && idle <= elapsed
? Math.round((1 - idle / elapsed) * 1000) / 10 : null
- const mem = await deps.memory()
const validMemory = Number.isFinite(mem.total) && mem.total > 0
&& Number.isFinite(mem.available) && mem.available >= 0 && mem.available <= mem.total
const value = {
+ ...hardware,
cpuPercent,
memoryUsedBytes: validMemory ? mem.total - mem.available : null,
memoryTotalBytes: validMemory ? mem.total : null,
+ ...(mem.pressure === undefined ? {} : { memoryPressure: mem.pressure }),
+ ...(mem.swapUsedBytes === undefined ? {} : { swapUsedBytes: mem.swapUsedBytes }),
}
cached = { at: deps.now(), value }
return value
diff --git a/desktop/CLAUDE.md b/desktop/CLAUDE.md
index 6c9ae46ee..ae51be2cd 100644
--- a/desktop/CLAUDE.md
+++ b/desktop/CLAUDE.md
@@ -261,13 +261,23 @@ there is no title or deferred-close button. Cancel is the default. Previously qu
plans remain compatible. Layout cleanup, moving panes, switching tabs, and sign-out retain their view-only behavior. A failed save
or unconfirmed close keeps the pane. Older daemons retain their existing behavior until updated.
-`HarnessMonitor` drives the bottom-left resource summary. It samples connected owned sessions
-every 15 seconds and never while the app is hidden. Clicking it opens the reusable
-`autonomous/harness-monitor` DSH tab through `HarnessMonitorController`, with its viewer full width
-and the assistant terminal revealed only on request. The DSH table shares the daemon's resource
-sampler and adds opt-in activity metadata to `agents_list`. RAM is process-tree RSS; CPU is interval use, with 100% representing one core. Unknown
-readings remain unknown. Shared Codex servers are listed separately and included once in totals;
-token counts reuse existing agent data. The monitor never resumes sessions or scans transcripts.
+`HarnessMonitor` supplies the global running-harness count without process sampling
+in the footer. Clicking it opens the reusable `autonomous/harness-monitor` DSH tab
+through `HarnessMonitorController`, with its viewer full width and the assistant
+terminal revealed only on request. The DSH table shares the daemon's resource sampler
+and adds opt-in activity metadata to `agents_list`. RAM is process-tree RSS; CPU is
+interval use, with 100% representing one core. Unknown readings remain unknown.
+Shared Codex servers are listed separately and included once; token counts reuse
+existing agent data. The monitor never resumes sessions or scans transcripts.
+
+`MachineResourceMonitor` always scopes CPU/RAM/GPU to this computer, even when the
+focused pane is remote. Hardware is passive text, with no filter or popover. It
+samples only the local host every 15 seconds while foreground. Readings expire in
+45 seconds and clear on disconnect, replacement or hide. CPU is normalized host
+utilization; RAM excludes reclaimable cache where available. GPU is the busiest
+reported device. Missing telemetry is `-`. Additive `machine_resources` RPC fields
+allow mixed old/new CLIs. See `design/workspace-status-bar.md` for the complete
+scope and format contract.
### Command dock
@@ -327,7 +337,7 @@ its headless debug timings do not establish native display or network latency.
Chrome widgets call `grid.AppTheme.watch(context)` at the top of `build` so `const` subtrees still
repaint on a theme flip.
- The [workspace status bar](design/workspace-status-bar.md) places system-font tabs and global actions at the top,
- with subscription usage remaining at the bottom left and focused machine/repo/branch/PR at the bottom right.
+ with harness count, local hardware and subscription allowance used at the bottom left and focused machine/repo/branch/PR at the bottom right.
Tabs center their name/status group without permanent number prefixes; Command replaces
the status with the resolved shortcut beside the name. Tab and pane close marks are small
and quiet, with larger click targets. Each pane ends with model, split down,
@@ -371,7 +381,7 @@ its headless debug timings do not establish native display or network latency.
have spent. Each account shows its `tightest` window, the limit that stops the work first.
The shared controller reads ahead at startup and every five minutes; opening a menu requests
a fresh reading, capped at once per minute. The footer uses these same deduplicated accounts
- and freshness rules, displaying the remaining percentage rather than the amount spent.
+ and freshness rules, displaying whole allowance-used percentages (100 − remaining) in neutral ink.
**Remote machines' accounts arrive through `usage_read`** (`AppNotifier.readRemoteUsage`,
`usage/remote_usage.dart`, `usage/usage_accounts.dart`; CLI side `cli/src/lib/accountUsage.ts`).
A remote machine may be signed in to a DIFFERENT subscription, and the only honest way to read
diff --git a/desktop/design/desktop-design-system.md b/desktop/design/desktop-design-system.md
index 463ed02a3..db5cbd0e0 100644
--- a/desktop/design/desktop-design-system.md
+++ b/desktop/design/desktop-design-system.md
@@ -341,23 +341,26 @@ 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** — remaining subscription usage at the left,
-with machine, project, branch and PR together at the right following the focused pane. Each
-context field keeps its existing action, including the branch/PR chooser.
-Titles stay quiet when several panes are visible; do not repeat branches in
-pane headers. Do not repeat model or effort in the footer. Context honors Customize Harness's selected
-status face, fields, colors and shell/Powerline treatment. Recent-harness
-context uses that same renderer's monochrome presentation to stay secondary.
-Use compact labels such as “Claude 0% Codex 50%”, separated by whitespace only.
-Provider names stay neutral. Color only the remaining percentage: quiet amber
-from 0% through 20%, neutral above 20% or when unavailable. Use shared
-semantic ink adjusted to remain readable on the selected workspace surface;
-the number always conveys the state independently of color. These percentages are
-remaining, not used. Use the same deduplicated accounts, limiting window and
-freshness rules as Models. Separate subscriptions remain separate; unknown or
-expired values show “—”, never a fabricated zero. Hover explains reset windows
-and account identity; clicking opens Subscriptions without switching a model.
-Companion and sharing controls sit after usage without shifting the context.
+**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.
+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
at page scale. Related settings use grouping and whitespace. Existing artwork,
diff --git a/desktop/design/desktop-ui-migration.md b/desktop/design/desktop-ui-migration.md
index e39f371e5..f3b20d2a7 100644
--- a/desktop/design/desktop-ui-migration.md
+++ b/desktop/design/desktop-ui-migration.md
@@ -236,11 +236,12 @@ The experimental branch remains unmerged for the user's visual review.
The model opens the shared Models picker for that exact harness. Narrow panes
retain the close target; stale or unavailable targets cannot switch an agent.
Tab-strip close still appears on hover and yields to Command-held hints.
-- The footer's left side shows remaining subscription usage, such as
- “Claude 0% · Codex 50%”, from the same deduplicated accounts and limiting
- windows as Models. Unknown readings show “—”; distinct accounts remain
- distinct. Hover explains the reading; click opens Subscriptions. The right
- side retains the focused machine/project/branch/PR and their actions.
+- The footer originally showed remaining subscription usage. The current
+ [status-bar contract](workspace-status-bar.md) uses global harness count,
+ local host CPU/RAM/GPU and neutral allowance-used percentages, separated by
+ whitespace. Deduplicated accounts, limiting windows and Subscriptions actions
+ stay shared with Models. Unknown readings show `-`. The right side retains
+ the focused machine/project/branch/PR and their actions.
- Final suite: **4,702 passed, 16 skipped**. New Harness has **3,948/3,948**
covered executable lines and the resource picker **1,271/1,271** (both 100%).
App, test and integration source analysis is clean. A whole-directory analysis
diff --git a/desktop/design/icon-design-system.md b/desktop/design/icon-design-system.md
index 3a5565801..a97c22ffa 100644
--- a/desktop/design/icon-design-system.md
+++ b/desktop/design/icon-design-system.md
@@ -65,11 +65,10 @@ to compensate for excess container padding.
- Keep a selected state legible without color: checkmarks, labels and shape
changes carry meaning. Zoom becomes Restore; loading can animate only while
work is actually pending, respecting Reduce Motion.
-- Reserve red for errors and destructive actions. Workspace subscription
- allowance at **0–20%** uses quiet amber (`AppPalette.usageLow`), including
- exhausted allowance. Names and healthy/unknown percentages stay neutral.
- The figure and tooltip explain the limit; color is secondary. The same
- contrast-adjusted ink is sent to Flutter and the native footer.
+- Reserve red for errors and destructive actions. Workspace hardware and
+ subscription figures use neutral ink at every percentage, including exhausted
+ allowance. The figure and tooltip explain usage; the footer is not an alarm.
+ The same contrast-adjusted ink goes to Flutter and the native footer.
## Deliberate exceptions
diff --git a/desktop/design/images/workspace-resources.png b/desktop/design/images/workspace-resources.png
new file mode 100644
index 000000000..a6c7e808a
Binary files /dev/null and b/desktop/design/images/workspace-resources.png differ
diff --git a/desktop/design/terminal-workspace.md b/desktop/design/terminal-workspace.md
index 2dee2639c..775aae94f 100644
--- a/desktop/design/terminal-workspace.md
+++ b/desktop/design/terminal-workspace.md
@@ -30,8 +30,9 @@ system menu bar; the window keeps Search and Store. Linux and browser bars
retain their notification bell. Show a count badge only when something is unread.
Tooltips explain icon actions and resolve shortcuts from the live keymap.
-The footer shows remaining subscription usage on the left. Its right-hand context follows the focused pane: machine, project, branch, and PR
-at the right. Each pane header ends with model, split down, split right, zoom,
+The footer shows a global harness count, local host CPU/RAM/GPU and subscription
+allowance used on the left, all in neutral ink with whole percentages. Its
+right-hand context follows the focused pane: machine, project, branch and PR. Each pane header ends with model, split down, split right, zoom,
and close, in that order. The icons stay visible with quiet ink and no button
chrome. Splitting opens New Harness directly with that pane's agent, machine,
and project, then creates into the chosen split on submission. Clicking the
diff --git a/desktop/design/workspace-status-bar.md b/desktop/design/workspace-status-bar.md
index 1558bd34e..9df6555aa 100644
--- a/desktop/design/workspace-status-bar.md
+++ b/desktop/design/workspace-status-bar.md
@@ -14,32 +14,88 @@ api ? web ⠹ blender ✓ + Search Bell (✿ Harness
panes
-10 live · 1.4 GB · 12% CPU M2 > openharness > branch-name > #439
+Harnesses 118 CPU 20% RAM 50% GPU 10% Claude 100% Codex 90%
+ M2 > project > branch > #439
```
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.
-Harness Monitor sits at the bottom left. Its counter opens the existing session
-manager above it, filtered to live sessions. RAM and CPU can be sorted highest
-first; tokens use the counts already carried by agent updates. Include live
-sessions on connected owned machines even when none of this window's tabs show
-them. Discovery must not open panes or start an engine. Saved history remains
-in the All and Saved views.
-
-Each owning daemon takes one process snapshot for the whole list. Count nested
-registered engines once, retain process birth identities, and report missing
-readings as unknown. RAM is estimated resident memory including child processes;
-CPU measures the interval, with 100% representing one core. A `+` after a total
-means some session readings are unavailable. The tooltip explains these limits.
-Do not show GPU use, disk activity or token cost inferred from unrelated totals.
-
-The footer samples every 15 seconds while the app is foreground; an open monitor
-uses three seconds. Requests coalesce in the daemon. Hidden apps run no monitor
-polling, and inspecting tokens never starts another transcript scan. The native
-and Flutter controls share labels and behavior. Subscription usage remains
-beside the monitor in wide windows and accessible through Models at every size.
+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 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.
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
@@ -172,17 +228,13 @@ 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 remaining subscription usage on the left and the focused
-harness's machine, project, branch and PR at the right. It does not repeat model
-or effort. Read the same deduplicated account rows as Models: each percentage
-uses the limiting window and expires under the same rules. Different accounts
-remain distinct. Unknown usage shows “—”; exhausted usage shows “0%”. Hover
-explains remaining percentages and reset windows; click opens Subscriptions.
-Separate accounts with whitespace, without dot separators. Provider names stay
-neutral; only percentages carry quiet amber ink from zero through 20%,
-neutral above 20% or when unavailable. Resolve the same readable colors for the
-Flutter and native footers against the chosen workspace background.
-No account or usage reading is invented for this footer.
+The footer shows subscription allowance **used**, alongside local hardware.
+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
+usage shows `-`; exhausted allowance shows `100%`. Names and percentages use
+the same neutral ink. Hover explains usage, account identity and reset windows;
+click opens Subscriptions. Do not invent account or usage readings.
For the model label, prefer
its local model ID or the daemon's observed subscription model (`selectedModel`),
@@ -334,7 +386,7 @@ rather than extra padding only above it. Native and Flutter reserve 37.5 pt and
keep the same pane height, with equal space above and below the footer content.
Show `machine project`, then `(branch)` and PR when known at the right. Put the
-remaining subscription usage at the far left. The status row has one-cell outer gutters and no background fill or divider;
+harness count, local resources and subscription usage at the left. The status row has one-cell outer gutters and no background fill or divider;
its controls sit directly on the workspace surface. The right side follows the
focused pane; usage at the left covers all subscriptions independently of focus.
Each context field preserves its existing action.
diff --git a/desktop/lib/core/machine_resources.dart b/desktop/lib/core/machine_resources.dart
index 8514c31bf..73c9e38fc 100644
--- a/desktop/lib/core/machine_resources.dart
+++ b/desktop/lib/core/machine_resources.dart
@@ -4,9 +4,36 @@ class MachineResources {
this.cpuPercent,
this.memoryUsedBytes,
this.memoryTotalBytes,
+ this.memoryPressure,
+ this.swapUsedBytes,
+ this.diskFreeBytes,
+ this.diskTotalBytes,
+ this.gpus = const [],
});
final double? cpuPercent, memoryUsedBytes, memoryTotalBytes;
+ final String? memoryPressure;
+ final double? swapUsedBytes, diskFreeBytes, diskTotalBytes;
+ final List<MachineGpu> gpus;
+
+ double? get memoryPercent =>
+ memoryUsedBytes != null &&
+ memoryTotalBytes != null &&
+ memoryTotalBytes! > 0
+ ? memoryUsedBytes! / memoryTotalBytes! * 100
+ : null;
+
+ MachineGpu? get busiestGpu {
+ MachineGpu? result;
+ for (final gpu in gpus) {
+ if (gpu.utilizationPercent != null &&
+ (result == null ||
+ gpu.utilizationPercent! > result.utilizationPercent!)) {
+ result = gpu;
+ }
+ }
+ return result;
+ }
factory MachineResources.fromJson(Map<String, dynamic> json) {
double? number(String key) {
@@ -21,10 +48,64 @@ class MachineResources {
final total = number('memoryTotalBytes');
final memoryValid =
used != null && total != null && total > 0 && used <= total;
+ final diskFree = number('diskFreeBytes'),
+ diskTotal = number('diskTotalBytes');
+ final diskValid =
+ diskFree != null &&
+ diskTotal != null &&
+ diskTotal > 0 &&
+ diskFree <= diskTotal;
+ final pressure = json['memoryPressure'];
return MachineResources(
cpuPercent: cpu != null && cpu <= 100 ? cpu : null,
memoryUsedBytes: memoryValid ? used : null,
memoryTotalBytes: memoryValid ? total : null,
+ memoryPressure: const ['normal', 'warning', 'critical'].contains(pressure)
+ ? pressure as String
+ : null,
+ swapUsedBytes: number('swapUsedBytes'),
+ diskFreeBytes: diskValid ? diskFree : null,
+ diskTotalBytes: diskValid ? diskTotal : null,
+ gpus: List.unmodifiable([
+ if (json['gpus'] is List)
+ for (final gpu in (json['gpus'] as List).take(32))
+ if (gpu is Map<String, dynamic> &&
+ gpu['id'] is String &&
+ gpu['name'] is String)
+ MachineGpu.fromJson(gpu),
+ ]),
+ );
+ }
+}
+
+class MachineGpu {
+ const MachineGpu({
+ required this.id,
+ required this.name,
+ this.utilizationPercent,
+ });
+ final String id, name;
+ final double? utilizationPercent;
+
+ factory MachineGpu.fromJson(Map<String, dynamic> json) {
+ final value = json['utilizationPercent'];
+ return MachineGpu(
+ id: json['id'] as String,
+ name: json['name'] as String,
+ utilizationPercent:
+ value is num && value.isFinite && value >= 0 && value <= 100
+ ? value.toDouble()
+ : null,
);
}
}
+
+String resourcePercent(double? value) =>
+ value == null ? '-' : '${value.round()}%';
+
+String resourceBytes(double? value) {
+ if (value == null) return '-';
+ if (value == 0) return '0 GB';
+ if (value < 1000000000) return '${(value / 1000000).round()} MB';
+ return '${(value / 1000000000).round()} GB';
+}
diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dart
index e4bbf7957..b765f080e 100644
--- a/desktop/lib/screens/swarm_screen.dart
+++ b/desktop/lib/screens/swarm_screen.dart
@@ -52,6 +52,8 @@ 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 '../state/harness_activity.dart';
import '../state/harness_attachments.dart';
import '../state/harness_placement.dart';
@@ -572,6 +574,8 @@ 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;
@@ -713,6 +717,7 @@ 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) {
@@ -774,6 +779,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
@override
void dispose() {
_harnessMonitor.dispose();
+ _machineResources.dispose();
if (app.reviewSessionClose == _reviewSessionClose) {
app.reviewSessionClose = null;
}
@@ -1475,6 +1481,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
}
late final HarnessMonitor _harnessMonitor;
+ late final MachineResourceMonitor _machineResources;
void _monitorChanged() {
if (!mounted) return;
if (_menuHost) _syncNative();
@@ -1775,6 +1782,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
'family': barStyle.fontFamily,
'fallback': barStyle.fontFamilyFallback,
'size': workspaceBarFontSize,
+ 'groupGapCells': workspaceBarGroupGapCells,
'foreground': terminalTheme.foreground.toARGB32(),
'selection': terminalTheme.selection.toARGB32(),
},
@@ -1800,6 +1808,21 @@ class _SwarmScreenState extends State<SwarmScreen> {
],
'interactive': _shortcutsEnabled,
},
+ 'machineResources': {
+ 'text': _machineResources.label,
+ 'label': _machineResources.detail,
+ 'detail': _machineResources.detail,
+ 'segments': [
+ {'text': _machineResources.metricsLabel()},
+ ],
+ 'compactSegments': [
+ {'text': _machineResources.metricsLabel(gpu: false)},
+ ],
+ 'minimalSegments': [
+ {'text': _machineResources.metricsLabel(ram: false, gpu: false)},
+ ],
+ 'interactive': false,
+ },
'footerCovered':
!_showWorkspaceFooter ||
(!_routeIsCurrent && !_footerPreviewCurrent) ||
@@ -6993,26 +7016,25 @@ class _SwarmScreenState extends State<SwarmScreen> {
final download = kIsWeb && !_compact(context);
final downloadWidth = download ? available * .16 : 0.0;
final usage = _subscriptionUsage;
+ final resourceGap = cell.width * (workspaceBarGroupGapCells - 2);
final resourceBudget = math.max(
0.0,
available -
shareWidth -
downloadWidth -
(!kIsWeb && _slotShown ? 44 : 0) -
- cell.width * 5,
+ cell.width * 5 -
+ resourceGap * 2,
);
- final monitorWidth = resourceBudget * .55;
+ final monitorWidth = math.min(
+ workspaceBarTextSizeOf(context, _harnessMonitor.label).width +
+ cell.width * 2,
+ resourceBudget * .4,
+ );
+ final hardwareWidth = resourceBudget * .42;
final usageWidth = constraints.maxWidth < 1050
? 0.0
- : math.max(
- 0.0,
- available -
- shareWidth -
- downloadWidth -
- (!kIsWeb && _slotShown ? 44 : 0) -
- cell.width * 5,
- ) *
- .22;
+ : resourceBudget * .22;
final paneContext = Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
@@ -7090,7 +7112,16 @@ class _SwarmScreenState extends State<SwarmScreen> {
),
),
),
- if (usageWidth > 0)
+ SizedBox(width: resourceGap),
+ ConstrainedBox(
+ constraints: BoxConstraints(maxWidth: hardwareWidth),
+ child: WorkspaceMachineResources(
+ key: const ValueKey('workspace-machine-resources'),
+ monitor: _machineResources,
+ ),
+ ),
+ if (usageWidth > 0) ...[
+ SizedBox(width: resourceGap),
ConstrainedBox(
constraints: BoxConstraints(maxWidth: usageWidth),
child: WorkspaceBarControl(
@@ -7115,8 +7146,9 @@ class _SwarmScreenState extends State<SwarmScreen> {
foreground: theme.foreground,
surface: grid.AppPalette.swarmField,
))
- TextSpan(
- text: part.text,
+ workspaceBarGroupTextSpan(
+ part.text,
+ cellWidth: cell.width,
style: TextStyle(color: part.foreground),
),
],
@@ -7132,6 +7164,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
),
),
),
+ ],
SizedBox(width: cell.width * 2),
if (!kIsWeb && _slotShown) _daemonTabButton(),
if (download) ...[
diff --git a/desktop/lib/shared/theme/workspace_bar_style.dart b/desktop/lib/shared/theme/workspace_bar_style.dart
index 9aee25f1b..467a78bf4 100644
--- a/desktop/lib/shared/theme/workspace_bar_style.dart
+++ b/desktop/lib/shared/theme/workspace_bar_style.dart
@@ -8,6 +8,40 @@ import '../../terminal/terminal_typography.dart';
/// SF Mono on macOS, with the platform's monospace stack elsewhere.
const workspaceBarFontSize = 13.0;
+/// One space inside a label–value pair, 2.5 cells between complete components.
+/// Neighboring controls already contribute one padded cell on either side.
+const workspaceBarGroupGapCells = 2.5;
+
+/// Text retains ordinary spaces; rendering uses the measured group gap above.
+const workspaceBarGroupSeparator = ' ';
+
+TextSpan workspaceBarGroupTextSpan(
+ String text, {
+ required double cellWidth,
+ TextStyle? style,
+}) {
+ final groups = text.split(workspaceBarGroupSeparator);
+ return TextSpan(
+ style: style,
+ children: [
+ for (var i = 0; i < groups.length; i++) ...[
+ if (i > 0)
+ TextSpan(
+ text: workspaceBarGroupSeparator,
+ style: TextStyle(
+ letterSpacing:
+ cellWidth *
+ (workspaceBarGroupGapCells -
+ workspaceBarGroupSeparator.length) /
+ workspaceBarGroupSeparator.length,
+ ),
+ ),
+ TextSpan(text: groups[i]),
+ ],
+ ],
+ );
+}
+
TextStyle workspaceBarTextStyle({Color? color, bool emphasized = false}) =>
TextStyle(
fontFamily: terminalFontFamily,
@@ -30,16 +64,26 @@ Size workspaceBarCellSizeOf(BuildContext context) {
double workspaceBarControlHeight(BuildContext context) =>
math.max(28, workspaceBarCellSizeOf(context).height);
-Size workspaceBarTextSizeOf(BuildContext context, String text) {
+Size workspaceBarTextSizeOf(
+ BuildContext context,
+ String text, {
+ bool grouped = false,
+}) {
// Reserve both weights, including fallback glyphs, so hover never resizes a
// control or moves a neighboring segment.
var size = Size.zero;
for (final emphasized in [false, true]) {
final painter = TextPainter(
- text: TextSpan(
- text: text,
- style: workspaceBarTextStyle(emphasized: emphasized),
- ),
+ text: grouped
+ ? workspaceBarGroupTextSpan(
+ text,
+ cellWidth: workspaceBarCellSizeOf(context).width,
+ style: workspaceBarTextStyle(emphasized: emphasized),
+ )
+ : TextSpan(
+ text: text,
+ style: workspaceBarTextStyle(emphasized: emphasized),
+ ),
textDirection: TextDirection.ltr,
textScaler: MediaQuery.textScalerOf(context),
maxLines: 1,
diff --git a/desktop/lib/state/harness_monitor.dart b/desktop/lib/state/harness_monitor.dart
index 30d154206..9053a5159 100644
--- a/desktop/lib/state/harness_monitor.dart
+++ b/desktop/lib/state/harness_monitor.dart
@@ -54,40 +54,11 @@ class HarnessMonitor extends ChangeNotifier {
return 'Shared Codex servers · ${formatHarnessMemory(known.isEmpty ? null : memory)}${known.isNotEmpty && known.length < rows.length ? '+' : ''} RAM';
}
- String get label {
- final rows = live;
- if (rows.isEmpty) return '0 live';
- (double?, bool) sum(double? Function(HarnessResources) value) {
- double total = 0;
- int known = 0;
- for (final row in rows) {
- final sample = reading(row);
- final n = sample == null ? null : value(sample);
- if (n != null) {
- total += n;
- known++;
- }
- }
- final shared = sharedReadings;
- for (final sample in shared) {
- final n = value(sample);
- if (n != null) {
- total += n;
- known++;
- }
- }
- return (
- known == 0 ? null : total,
- known > 0 && known < rows.length + shared.length,
- );
- }
-
- final memory = sum((r) => r.memoryBytes), cpu = sum((r) => r.cpuPercent);
- return '${rows.length} live · ${formatHarnessMemory(memory.$1)}${memory.$2 ? '+' : ''} · ${cpu.$1 == null ? '—' : cpu.$1!.toStringAsFixed(0)}%${cpu.$2 ? '+' : ''} CPU';
- }
+ String get label => 'Harnesses ${live.length}';
String get detail =>
- 'Harness Monitor — $label\nLive sessions on connected machines. + means some readings are unavailable. ${HarnessResources.explanation}${sharedLabel == null ? '' : '\n$sharedLabel, included once in the total. These servers may also serve sessions outside Harness.'}';
+ '${live.length} running across connected machines. Click to view harnesses.\n'
+ '${HarnessResources.explanation}${sharedLabel == null ? '' : '\n$sharedLabel, included once in the session monitor.'}';
void start() {
if (_started || _disposed) return;
@@ -101,7 +72,7 @@ class HarnessMonitor extends ChangeNotifier {
if (_expanded == value) return;
_expanded = value;
_timer?.cancel();
- if (_started && app.foreground.value) unawaited(refresh());
+ if (_started && _expanded && app.foreground.value) unawaited(refresh());
}
void _inventoryChanged() {
@@ -115,16 +86,14 @@ class HarnessMonitor extends ChangeNotifier {
for (final id in removed) {
_samples.remove(id);
}
- if (removed.isNotEmpty) {
- _revision++;
- notifyListeners();
- }
+ if (removed.isNotEmpty) _revision++;
+ notifyListeners();
}
void _environmentChanged() {
_revision++;
_timer?.cancel();
- if (app.foreground.value) unawaited(refresh());
+ if (_expanded && app.foreground.value) unawaited(refresh());
}
Future<void> refresh() async {
@@ -153,8 +122,8 @@ class HarnessMonitor extends ChangeNotifier {
notifyListeners();
} finally {
_busy = false;
- if (!_disposed && _started && app.foreground.value) {
- _timer = Timer(Duration(seconds: _expanded ? 3 : 15), refresh);
+ if (!_disposed && _started && _expanded && app.foreground.value) {
+ _timer = Timer(const Duration(seconds: 3), refresh);
}
}
}
diff --git a/desktop/lib/state/machine_resource_monitor.dart b/desktop/lib/state/machine_resource_monitor.dart
new file mode 100644
index 000000000..e8dfef2ef
--- /dev/null
+++ b/desktop/lib/state/machine_resource_monitor.dart
@@ -0,0 +1,156 @@
+import 'dart:async';
+
+import 'package:flutter/foundation.dart';
+
+import '../core/machine_resources.dart';
+import '../core/models.dart';
+import '../shared/theme/workspace_bar_style.dart'
+ show workspaceBarGroupSeparator;
+import 'app_state.dart';
+
+/// The footer always describes this computer, independently of pane focus.
+/// Sample only the local machine while the app is visible.
+/// These optional reads never connect a machine or launch a harness.
+class MachineResourceMonitor extends ChangeNotifier {
+ MachineResourceMonitor(this.app);
+ final AppNotifier app;
+ final _samples = <String, (MachineState, MachineResources, DateTime)>{};
+ Timer? _timer;
+ String? _lastScope;
+ bool _started = false, _disposed = false, _busy = false, _again = false;
+ int _revision = 0;
+
+ MachineState? get localMachine => app.machineStates.values
+ .where((state) => state.isLocalMachine && !state.machine.isShared)
+ .firstOrNull;
+
+ String get _scopeIdentity {
+ final state = localMachine;
+ return '${state?.machine.machineId}/${state != null && available(state)}';
+ }
+
+ bool available(MachineState state) =>
+ !state.machine.isShared &&
+ !state.needsLink &&
+ state.nodeOnline != false &&
+ state.connectionStatus == ConnectionStatus.connected;
+
+ MachineResources? reading(MachineState? state) {
+ if (state == null || !available(state)) return null;
+ final sample = _samples[state.machine.machineId];
+ return identical(sample?.$1, state) &&
+ DateTime.now().difference(sample!.$3) <= const Duration(seconds: 45)
+ ? sample.$2
+ : null;
+ }
+
+ String get scopeName => localMachine?.machine.displayName ?? 'This computer';
+ String metricsLabel({bool ram = true, bool gpu = true}) {
+ final value = reading(localMachine);
+ return 'CPU ${resourcePercent(value?.cpuPercent)}'
+ '${ram ? '${workspaceBarGroupSeparator}RAM ${resourcePercent(value?.memoryPercent)}' : ''}'
+ '${gpu ? '${workspaceBarGroupSeparator}GPU ${resourcePercent(value?.busiestGpu?.utilizationPercent)}' : ''}';
+ }
+
+ String get label => metricsLabel();
+
+ String get detail {
+ final state = localMachine, value = reading(state);
+ return '$scopeName $label\n'
+ 'This computer’s CPU and RAM usage, including other apps.\n'
+ '${value?.busiestGpu == null ? 'GPU reading unavailable.' : 'GPU shows the busiest device: ${value!.busiestGpu!.name}.'}\n'
+ '${state != null && !available(state) ? 'Machine disconnected. ' : ''}'
+ 'Unavailable readings use a dash.';
+ }
+
+ void start() {
+ if (_started || _disposed) return;
+ _started = true;
+ app.addListener(_inventoryChanged);
+ app.foreground.addListener(_environmentChanged);
+ _environmentChanged();
+ }
+
+ void _inventoryChanged() {
+ final removed = _samples.keys.where((id) {
+ final state = app.stateOf(id);
+ return state == null ||
+ !identical(state, _samples[id]!.$1) ||
+ !available(state);
+ }).toList();
+ for (final id in removed) {
+ _samples.remove(id);
+ }
+ if (removed.isNotEmpty) _revision++;
+ final scope = _scopeIdentity;
+ final changed = scope != _lastScope;
+ _lastScope = scope;
+ notifyListeners();
+ if (_started && (changed || removed.isNotEmpty)) unawaited(refresh());
+ }
+
+ void _environmentChanged() {
+ _revision++;
+ _timer?.cancel();
+ _samples.clear();
+ _lastScope = _scopeIdentity;
+ notifyListeners();
+ if (app.foreground.value) unawaited(refresh());
+ }
+
+ Future<void> refresh() async {
+ if (_disposed || !app.foreground.value) return;
+ if (_busy) {
+ _again = true;
+ return;
+ }
+ _timer?.cancel();
+ _busy = true;
+ final revision = _revision;
+ final scope = localMachine;
+ final targets = [?scope].where(available);
+ try {
+ await Future.wait(
+ targets.map((state) async {
+ final id = state.machine.machineId;
+ final value = await app.readMachineResources(id);
+ if (_disposed ||
+ revision != _revision ||
+ !identical(app.stateOf(id), state) ||
+ !available(state)) {
+ return;
+ }
+ if (value == null) {
+ _samples.remove(id);
+ } else {
+ _samples[id] = (state, value, DateTime.now());
+ }
+ notifyListeners();
+ }),
+ );
+ } finally {
+ _busy = false;
+ if (!_disposed && _started && app.foreground.value) {
+ if (_again) {
+ _again = false;
+ unawaited(refresh());
+ } else {
+ _timer = Timer(const Duration(seconds: 15), refresh);
+ }
+ }
+ }
+ }
+
+ @override
+ void dispose() {
+ _disposed = true;
+ _revision++;
+ _timer?.cancel();
+ if (_started) {
+ app.removeListener(_inventoryChanged);
+ app.foreground.removeListener(_environmentChanged);
+ }
+ _samples.clear();
+ super.dispose();
+ }
+}
diff --git a/desktop/lib/widgets/workspace_machine_resources.dart b/desktop/lib/widgets/workspace_machine_resources.dart
new file mode 100644
index 000000000..738478228
--- /dev/null
+++ b/desktop/lib/widgets/workspace_machine_resources.dart
@@ -0,0 +1,56 @@
+import 'package:flutter/material.dart';
+
+import '../shared/theme/workspace_bar_style.dart';
+import '../state/machine_resource_monitor.dart';
+
+/// Reduce complete metric groups at tight widths; never cut a percentage in half.
+class WorkspaceMachineResources extends StatelessWidget {
+ const WorkspaceMachineResources({super.key, required this.monitor});
+ final MachineResourceMonitor monitor;
+
+ @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);
+ for (final candidate in [
+ monitor.metricsLabel(),
+ monitor.metricsLabel(gpu: false),
+ ]) {
+ if (workspaceBarTextSizeOf(context, candidate, grouped: true).width +
+ cell * 2 <=
+ constraints.maxWidth) {
+ label = candidate;
+ break;
+ }
+ }
+ return Tooltip(
+ message: monitor.detail,
+ excludeFromSemantics: true,
+ waitDuration: const Duration(milliseconds: 500),
+ child: Semantics(
+ label: monitor.detail,
+ excludeSemantics: true,
+ child: 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.ellipsis,
+ style: workspaceBarTextStyle(),
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ },
+ ),
+ );
+}
diff --git a/desktop/lib/widgets/workspace_subscription_usage.dart b/desktop/lib/widgets/workspace_subscription_usage.dart
index 584be0f52..e4990cfe4 100644
--- a/desktop/lib/widgets/workspace_subscription_usage.dart
+++ b/desktop/lib/widgets/workspace_subscription_usage.dart
@@ -1,7 +1,8 @@
import 'package:flutter/painting.dart';
import '../shared/theme/status_line_style.dart';
-import '../shared/theme/app_theme.dart';
+import '../shared/theme/workspace_bar_style.dart'
+ show workspaceBarGroupSeparator;
enum WorkspaceUsageTone { normal, low, exhausted }
@@ -14,8 +15,8 @@ class WorkspaceSubscriptionUsage {
String get text => segments.map((part) => part.text).join();
final String detail;
- /// Names stay neutral. Low and exhausted allowance share quiet amber;
- /// a subscription limit is not an application error.
+ /// All footer figures report usage in the same neutral ink. Limit state and
+ /// reset windows remain available in the subscriptions panel and tooltip.
List<StatusLinePaintSegment> paintSegments({
required Color foreground,
required Color surface,
@@ -23,11 +24,7 @@ class WorkspaceSubscriptionUsage {
for (final part in segments)
StatusLinePaintSegment(
part.text,
- statusLineInkOnSurface(switch (part.tone) {
- WorkspaceUsageTone.normal => foreground,
- WorkspaceUsageTone.low ||
- WorkspaceUsageTone.exhausted => AppPalette.usageLow,
- }, surface),
+ statusLineInkOnSurface(foreground, surface),
null,
),
];
@@ -41,7 +38,7 @@ class WorkspaceSubscriptionUsage {
counts.update(row['engine'], (count) => count + 1, ifAbsent: () => 1);
}
final segments = <({String text, WorkspaceUsageTone tone})>[];
- final details = <String>['Remaining subscription usage'];
+ final details = <String>['Subscription allowance used'];
final positions = <Object?, int>{};
for (final row in accounts) {
final engine = row['engine'];
@@ -62,24 +59,15 @@ class WorkspaceSubscriptionUsage {
final status = row['status'] as String? ?? 'Usage unavailable';
final remaining = row['remainingPercent'];
final figure = remaining is num && remaining.isFinite
- ? status.replaceFirst(RegExp(r' remaining$'), '')
- : '—';
+ ? '${(100 - remaining).clamp(0, 100).round()}%'
+ : '-';
segments.add((
- text: '${segments.isEmpty ? '' : ' '}$name ',
+ text: '${segments.isEmpty ? '' : workspaceBarGroupSeparator}$name ',
tone: WorkspaceUsageTone.normal,
));
- segments.add((
- text: figure,
- tone: remaining is! num || !remaining.isFinite
- ? WorkspaceUsageTone.normal
- : remaining <= 0
- ? WorkspaceUsageTone.exhausted
- : remaining <= 20
- ? WorkspaceUsageTone.low
- : WorkspaceUsageTone.normal,
- ));
+ segments.add((text: figure, tone: WorkspaceUsageTone.normal));
details.add(
- '$name${account.isNotEmpty && counts[engine] == 1 ? ' ($account)' : ''}: $status',
+ '$name${account.isNotEmpty && counts[engine] == 1 ? ' ($account)' : ''}: ${figure == '-' ? status : '$figure used'}',
);
final windows = row['details'];
if (windows is List) details.addAll(windows.whereType<String>());
@@ -89,7 +77,7 @@ class WorkspaceSubscriptionUsage {
? const [(text: 'Subscriptions', tone: WorkspaceUsageTone.normal)]
: List.unmodifiable(segments),
segments.isEmpty
- ? 'View subscriptions and remaining usage'
+ ? 'View subscription usage and reset times'
: details.join('\n'),
);
}
diff --git a/desktop/macos/Runner/SwarmTitlebar.swift b/desktop/macos/Runner/SwarmTitlebar.swift
index 2b4dc6a8c..29368feba 100644
--- a/desktop/macos/Runner/SwarmTitlebar.swift
+++ b/desktop/macos/Runner/SwarmTitlebar.swift
@@ -977,6 +977,8 @@ private func workspaceBarTextWidth(_ text: String, font: NSFont) -> CGFloat {
(text as NSString).size(withAttributes: [.font: workspaceBarEmphasisFont(font)]).width)
}
+private let workspaceBarGroupSeparator = " "
+
/// Plain toolbar icons emphasize the glyph without a button well.
private class SwarmPlainIconButton: SwarmIconButton {
var foreground = NSColor.white { didSet { needsDisplay = true } }
@@ -1259,6 +1261,7 @@ private final class SwarmContextButton: SwarmIconButton {
private var text = ""
var textAlignment: NSTextAlignment = .right
var contentPadding: CGFloat = 0
+ var groupGapCells: CGFloat?
private var detail: String?
private var iconAsset: String?
private var iconColor = NSColor.white
@@ -1275,9 +1278,14 @@ private final class SwarmContextButton: SwarmIconButton {
fileprivate var actionURL: String?
private var textFont: NSFont { font ?? NSFont.monospacedSystemFont(ofSize: 13, weight: .regular) }
private var cellWidth: CGFloat { ("m" as NSString).size(withAttributes: [.font: textFont]).width }
+ private var groupSpacingAdjustment: CGFloat {
+ guard let groupGapCells else { return 0 }
+ return cellWidth * (groupGapCells - CGFloat(workspaceBarGroupSeparator.count))
+ }
private var naturalWidths: [CGFloat] {
segments.enumerated().map { index, segment in
workspaceBarTextWidth(segment.text, font: textFont) + (segment.branchSymbol ? cellWidth * 2 : 0)
+ + CGFloat(segment.text.components(separatedBy: workspaceBarGroupSeparator).count - 1) * groupSpacingAdjustment
+ (index == 0 ? iconWidth : 0)
}
}
@@ -1385,11 +1393,22 @@ private final class SwarmContextButton: SwarmIconButton {
let paragraph = NSMutableParagraphStyle()
paragraph.lineBreakMode = field == "branch" ? .byTruncatingMiddle : .byTruncatingTail
paragraph.alignment = alignment
- return NSAttributedString(string: value, attributes: [
+ let line = NSMutableAttributedString(string: value, attributes: [
.font: isEnabled && (hovered || hasKeyboardFocus || isHighlighted)
? workspaceBarEmphasisFont(textFont) : textFont,
.foregroundColor: color, .paragraphStyle: paragraph,
])
+ if groupGapCells != nil {
+ let text = value as NSString
+ var search = NSRange(location: 0, length: text.length)
+ while search.length > 0 {
+ let range = text.range(of: workspaceBarGroupSeparator, options: [], range: search)
+ if range.location == NSNotFound { break }
+ line.addAttribute(.kern, value: groupSpacingAdjustment / CGFloat(range.length), range: range)
+ search = NSRange(location: NSMaxRange(range), length: text.length - NSMaxRange(range))
+ }
+ }
+ return line
}
private func branchAttachment(_ color: NSColor) -> NSAttributedString {
let width = cellWidth, height = textFont.pointSize * 0.84
@@ -1757,6 +1776,8 @@ private final class SwarmTabStrip: NSView {
fileprivate let contextButton = SwarmContextButton()
fileprivate let subscriptionUsageButton = SwarmContextButton()
fileprivate let harnessMonitorButton = SwarmContextButton()
+ fileprivate let machineResourcesLabel = SwarmContextButton()
+ private var machineResourcesState: [String: Any]?
private var subscriptionUsageState: [String: Any]?
fileprivate let pullRequestButton = SwarmContextButton()
fileprivate let shareButton = SwarmShareButton()
@@ -1764,6 +1785,7 @@ private final class SwarmTabStrip: NSView {
fileprivate let storeButton = SwarmStoreButton()
private var shareTarget: [String: Any]?
private var barFont = NSFont.monospacedSystemFont(ofSize: 13, weight: .regular)
+ private var resourceGroupGapCells: CGFloat = 2.5
private let navigationFont = NSFont.systemFont(ofSize: 13, weight: .regular)
fileprivate let daemonButton = SwarmSymbolButton()
private var daemonArt = SwarmDaemonArt()
@@ -1822,7 +1844,7 @@ private final class SwarmTabStrip: NSView {
subscriptionUsageButton.textAlignment = .center
subscriptionUsageButton.target = self
subscriptionUsageButton.action = #selector(openSubscriptions)
- subscriptionUsageButton.setAccessibilityLabel("Remaining subscription usage")
+ subscriptionUsageButton.setAccessibilityLabel("Subscription allowance used")
subscriptionUsageButton.isHidden = true
statusBar.addSubview(subscriptionUsageButton)
harnessMonitorButton.isBordered = false
@@ -1832,6 +1854,12 @@ private final class SwarmTabStrip: NSView {
harnessMonitorButton.setAccessibilityLabel("Harness Monitor")
harnessMonitorButton.isHidden = true
statusBar.addSubview(harnessMonitorButton)
+ machineResourcesLabel.isBordered = false
+ machineResourcesLabel.textAlignment = .left
+ machineResourcesLabel.setAccessibilityRole(.staticText)
+ machineResourcesLabel.setAccessibilityLabel("Machine resources")
+ machineResourcesLabel.isHidden = true
+ statusBar.addSubview(machineResourcesLabel)
pullRequestButton.isBordered = false
pullRequestButton.target = self
pullRequestButton.action = #selector(openFocusedPullRequest)
@@ -1896,7 +1924,7 @@ private final class SwarmTabStrip: NSView {
statusBar.setAccessibilityLabel("Focused pane status")
statusBar.setAccessibilityParent(self)
setAccessibilityChildren([scroll, newButton, searchButton, storeButton, statusBar])
- statusBar.setAccessibilityChildren([harnessMonitorButton, subscriptionUsageButton, daemonButton, shareButton, voiceLabel, contextButton, pullRequestButton])
+ statusBar.setAccessibilityChildren([harnessMonitorButton, machineResourcesLabel, subscriptionUsageButton, daemonButton, shareButton, voiceLabel, contextButton, pullRequestButton])
registerForDraggedTypes([swarmPasteboardType])
scroll.contentView.postsBoundsChangedNotifications = true
for name in [NSApplication.didBecomeActiveNotification, NSApplication.didResignActiveNotification,
@@ -2024,6 +2052,7 @@ private final class SwarmTabStrip: NSView {
barFont = families.lazy.compactMap { NSFont(name: $0, size: size) }.first
?? NSFont.monospacedSystemFont(ofSize: size, weight: .regular)
terminalForeground = statusColor(style["foreground"], fallback: terminalForeground)
+ resourceGroupGapCells = CGFloat(max(2, (style["groupGapCells"] as? NSNumber)?.doubleValue ?? 2.5))
}
for control in [newButton] {
control.font = navigationFont
@@ -2041,6 +2070,7 @@ private final class SwarmTabStrip: NSView {
subscriptionUsageButton.font = barFont
subscriptionUsageButton.foreground = terminalForeground
subscriptionUsageButton.contentPadding = ("m" as NSString).size(withAttributes: [.font: barFont]).width
+ subscriptionUsageButton.groupGapCells = resourceGroupGapCells
subscriptionUsageState = state["subscriptionUsage"] as? [String: Any]
subscriptionUsageButton.update(subscriptionUsageState, enabled: actionsEnabled)
hasSubscriptionUsage = subscriptionUsageState != nil
@@ -2049,6 +2079,13 @@ private final class SwarmTabStrip: NSView {
harnessMonitorButton.contentPadding = ("m" as NSString).size(withAttributes: [.font: barFont]).width
harnessMonitorButton.update(state["harnessMonitor"] as? [String: Any], enabled: actionsEnabled)
harnessMonitorButton.isHidden = state["harnessMonitor"] == nil
+ machineResourcesState = state["machineResources"] as? [String: Any]
+ machineResourcesLabel.font = barFont
+ machineResourcesLabel.foreground = terminalForeground
+ machineResourcesLabel.contentPadding = harnessMonitorButton.contentPadding
+ machineResourcesLabel.groupGapCells = resourceGroupGapCells
+ machineResourcesLabel.update(machineResourcesState, enabled: false)
+ machineResourcesLabel.isHidden = machineResourcesState == nil
contextButton.font = barFont
contextButton.foreground = terminalForeground
contextButton.update(state["focusedContext"] as? [String: Any], enabled: actionsEnabled)
@@ -2281,18 +2318,32 @@ private final class SwarmTabStrip: NSView {
}
private func layoutStatusBar() {
let cell = ceil(("m" as NSString).size(withAttributes: [.font: barFont]).width)
+ // Each adjacent control already supplies one padded character cell.
+ let resourceGap = ("m" as NSString).size(withAttributes: [.font: barFont]).width * (resourceGroupGapCells - 2)
let height = workspaceBarControlHeight(barFont)
let y = (statusBar.bounds.height - height) / 2
let available = max(0, statusBar.bounds.width - cell * 2)
let daemonWidth = daemonButton.isHidden ? 0 : min(daemonButton.preferredWidth, available * 0.5)
let shareWidth = shareButton.isHidden ? 0 : min(shareButton.preferredWidth, available * 0.3)
- let usageBudget = max(0, available - daemonWidth - shareWidth - cell * 4)
- let monitorWidth = harnessMonitorButton.isHidden ? 0 : min(harnessMonitorButton.preferredWidth, usageBudget * 0.55)
+ 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
+ if var resource = machineResourcesState {
+ for key in ["segments", "compactSegments", "minimalSegments"] {
+ guard let segments = machineResourcesState?[key] else { continue }
+ resource["segments"] = segments
+ machineResourcesLabel.update(resource, enabled: false)
+ if machineResourcesLabel.preferredWidth <= hardwareBudget { break }
+ }
+ }
+ let hardwareWidth = machineResourcesLabel.isHidden ? 0 : min(machineResourcesLabel.preferredWidth, hardwareBudget)
harnessMonitorButton.frame = NSRect(x: cell, y: y, width: monitorWidth, height: height)
let usageWidth = hasSubscriptionUsage && (monitorWidth == 0 || statusBar.bounds.width >= 1050)
? min(subscriptionUsageButton.preferredWidth, usageBudget * (monitorWidth == 0 ? 0.45 : 0.22)) : 0
subscriptionUsageButton.isHidden = usageWidth == 0
- subscriptionUsageButton.frame = NSRect(x: cell + monitorWidth,
+ machineResourcesLabel.frame = NSRect(x: cell + monitorWidth + (monitorWidth > 0 && hardwareWidth > 0 ? resourceGap : 0),
+ y: y, width: hardwareWidth, height: height)
+ subscriptionUsageButton.frame = NSRect(x: machineResourcesLabel.frame.maxX + (usageWidth > 0 && (monitorWidth > 0 || hardwareWidth > 0) ? resourceGap : 0),
y: y, width: usageWidth, height: height)
let daemonLeft = subscriptionUsageButton.frame.maxX + (usageWidth > 0 ? cell * 2 : 0)
daemonButton.frame = NSRect(x: daemonLeft, y: y, width: daemonWidth, height: height)
@@ -2317,6 +2368,7 @@ private final class SwarmTabStrip: NSView {
pullRequestButton.layoutSubtreeIfNeeded()
subscriptionUsageButton.layoutSubtreeIfNeeded()
harnessMonitorButton.layoutSubtreeIfNeeded()
+ machineResourcesLabel.layoutSubtreeIfNeeded()
}
override func draw(_ dirtyRect: NSRect) {
// A fine rule joins the active tab's outward shoulders to the workspace.
diff --git a/desktop/test/desktop_welcome_composer_test.dart b/desktop/test/desktop_welcome_composer_test.dart
index d96946edc..3553e3e94 100644
--- a/desktop/test/desktop_welcome_composer_test.dart
+++ b/desktop/test/desktop_welcome_composer_test.dart
@@ -443,7 +443,7 @@ void main() {
(tester) async {
await setup(tester, mac: true);
expect(updates.last['footerCovered'], isFalse);
- expect(updates.last['harnessMonitor']['text'], startsWith('2 live'));
+ expect(updates.last['harnessMonitor']['text'], startsWith('Harnesses 2'));
for (final machine in app.machineStates.values) {
machine.agents = [];
}
diff --git a/desktop/test/harness_resources_test.dart b/desktop/test/harness_resources_test.dart
index 7a056c482..9b48e0f12 100644
--- a/desktop/test/harness_resources_test.dart
+++ b/desktop/test/harness_resources_test.dart
@@ -103,7 +103,7 @@ void main() {
},
];
await monitor.refresh();
- expect(monitor.label, '1 live · 2.0 GB · 130% CPU');
+ expect(monitor.label, 'Harnesses 1');
expect(monitor.sharedLabel, 'Shared Codex servers · 600 MB RAM');
expect(monitor.detail, contains('included once'));
((connection.reply['harnesses'] as Map)['shared'] as List).first.remove(
@@ -111,9 +111,9 @@ void main() {
);
await monitor.refresh();
expect(monitor.sharedLabel, 'Shared Codex servers · — RAM');
- expect(monitor.label, '1 live · 1.4 GB+ · 130% CPU');
+ expect(monitor.label, 'Harnesses 1');
app.machineStates['m']!.agents = [];
- expect(monitor.label, '0 live');
+ expect(monitor.label, 'Harnesses 0');
expect(monitor.sharedLabel, isNull);
});
@@ -150,17 +150,17 @@ void main() {
expect(connection.calls, [
{'type': 'machine_resources', 'harnesses': true},
]);
- expect(monitor.label, '2 live · 1.4 GB+ · 126%+ CPU');
+ expect(monitor.label, 'Harnesses 2');
expect(monitor.reading(monitor.live.first)!.processCount, 3);
expect(app.allPanes, isEmpty);
connection.reply = {};
await monitor.refresh();
- expect(monitor.label, '2 live · — · —% CPU');
+ expect(monitor.label, 'Harnesses 2');
},
);
testWidgets(
- 'polls slowly in the footer, faster only while open, and never while hidden',
+ 'samples process trees only while the session manager is open and visible',
(tester) async {
final connection = _Connection();
final app = createApp(
@@ -172,25 +172,25 @@ void main() {
const Agent(id: 'a0', name: 'Work', terminalAvailable: true),
];
monitor.start();
- await tester.pump();
- expect(connection.calls, hasLength(1));
- await tester.pump(const Duration(seconds: 14));
- expect(connection.calls, hasLength(1));
- await tester.pump(const Duration(seconds: 1));
- expect(connection.calls, hasLength(2));
+ 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));
- expect(connection.calls, hasLength(4));
+ expect(connection.calls, hasLength(2));
app.appLifecycleChanged(AppLifecycleState.hidden);
await tester.pump(const Duration(minutes: 2));
- expect(connection.calls, hasLength(4));
+ expect(connection.calls, hasLength(2));
app.appLifecycleChanged(AppLifecycleState.resumed);
await tester.pump();
- expect(connection.calls, hasLength(5));
+ expect(connection.calls, hasLength(3));
+ monitor.setExpanded(false);
+ await tester.pump(const Duration(minutes: 2));
+ expect(connection.calls, hasLength(3));
monitor.dispose();
await tester.pump(const Duration(minutes: 2));
- expect(connection.calls, hasLength(5));
+ expect(connection.calls, hasLength(3));
app.dispose();
},
);
@@ -218,12 +218,12 @@ void main() {
];
connection.pending!.complete(connection.reply);
await pending;
- expect(monitor.label, '1 live · — · —% CPU');
+ expect(monitor.label, 'Harnesses 1');
app.machineStates['m']!.connectionStatus = ConnectionStatus.disconnected;
final before = connection.calls.length;
await monitor.refresh();
expect(connection.calls.length, before);
- expect(monitor.label, '0 live');
+ expect(monitor.label, 'Harnesses 0');
},
);
diff --git a/desktop/test/machine_resource_monitor_test.dart b/desktop/test/machine_resource_monitor_test.dart
new file mode 100644
index 000000000..c5e01a323
--- /dev/null
+++ b/desktop/test/machine_resource_monitor_test.dart
@@ -0,0 +1,249 @@
+import 'dart:async';
+import 'dart:io';
+
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/auth/auth_session.dart';
+import 'package:harness/core/config.dart';
+import 'package:harness/core/machine_resources.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/state/machine_resource_monitor.dart';
+import 'package:harness/state/terminal_pane.dart';
+import 'package:harness/widgets/workspace_machine_resources.dart';
+
+import 'support/real_fonts.dart';
+
+class _App extends AppNotifier {
+ _App()
+ : super(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ ) {
+ for (final (id, name) in [
+ ('m', 'M2'),
+ ('o', 'office'),
+ ('r', '4090 Rig'),
+ ]) {
+ machineStates[id] =
+ MachineState(
+ Machine(
+ machineId: id,
+ name: name,
+ authMode: MachineAuthMode.remote,
+ ),
+ )
+ ..nodeOnline = true
+ ..connectionStatus = ConnectionStatus.connected;
+ }
+ machineStates['shared'] = MachineState(
+ const Machine(
+ machineId: 'shared',
+ name: 'Shared',
+ isShared: true,
+ authMode: MachineAuthMode.remote,
+ ),
+ )..connectionStatus = ConnectionStatus.connected;
+ selectedMachineId = 'm';
+ machineStates['m']!.localOnly = true;
+ }
+ final calls = <String>[];
+ final values = <String, MachineResources?>{
+ 'm': const MachineResources(
+ cpuPercent: 20,
+ memoryUsedBytes: 16000000000,
+ memoryTotalBytes: 32000000000,
+ memoryPressure: 'normal',
+ swapUsedBytes: 0,
+ diskFreeBytes: 320000000000,
+ diskTotalBytes: 500000000000,
+ gpus: [
+ MachineGpu(id: 'apple', name: 'Apple GPU', utilizationPercent: 10),
+ ],
+ ),
+ 'o': const MachineResources(
+ cpuPercent: 35,
+ memoryUsedBytes: 48000000000,
+ memoryTotalBytes: 64000000000,
+ ),
+ 'r': const MachineResources(
+ cpuPercent: 40,
+ memoryUsedBytes: 32000000000,
+ memoryTotalBytes: 64000000000,
+ gpus: [
+ MachineGpu(id: 'a', name: 'RTX 4090 #1', utilizationPercent: 80),
+ MachineGpu(id: 'b', name: 'RTX 4090 #2', utilizationPercent: 60),
+ ],
+ ),
+ };
+ Completer<MachineResources?>? pending;
+ @override
+ Future<MachineResources?> readMachineResources(String machineId) async {
+ calls.add(machineId);
+ return pending?.future ?? values[machineId];
+ }
+
+ void changed() => notifyListeners();
+}
+
+void main() {
+ setUpAll(() async {
+ if (Platform.environment['HARNESS_WORKSPACE_CONTROLS_CAPTURE_DIR'] !=
+ null) {
+ await loadRealFonts();
+ }
+ });
+
+ testWidgets(
+ 'local hardware stays fixed when focus and selection move to remote harnesses',
+ (tester) async {
+ final app = _App();
+ final monitor = MachineResourceMonitor(app);
+ app.activeSwarm.panes.addAll([
+ TerminalPane(id: 1, machineId: 'm', agentId: 'a'),
+ TerminalPane(id: 2, machineId: 'o', agentId: 'b'),
+ TerminalPane(id: 3, machineId: 'r', agentId: 'c'),
+ ]);
+ app.focusedPaneId = 2;
+ monitor.start();
+ await tester.pump();
+ expect(monitor.scopeName, 'M2');
+ expect(monitor.label, 'CPU 20% RAM 50% GPU 10%');
+ expect(monitor.detail, startsWith('M2 CPU 20%'));
+ app.focusedPaneId = 2;
+ app.selectedMachineId = 'o';
+ app.changed();
+ await tester.pump();
+ expect(monitor.scopeName, 'M2');
+ expect(monitor.label, 'CPU 20% RAM 50% GPU 10%');
+ app.focusedPaneId = 3;
+ app.changed();
+ await tester.pump();
+ expect(
+ monitor.reading(monitor.localMachine)!.busiestGpu!.utilizationPercent,
+ 10,
+ );
+ expect(app.focusedPaneId, 3);
+ app.focusedPaneId = 1;
+ app.changed();
+ await tester.pump();
+ expect(monitor.scopeName, 'M2');
+ expect(app.calls, ['m']);
+ expect(app.allPanes, hasLength(3));
+ app.machineStates.remove('m');
+ app.changed();
+ await tester.pump();
+ expect(monitor.localMachine, isNull);
+ expect(monitor.label, 'CPU - RAM - GPU -');
+ monitor.dispose();
+ app.dispose();
+ },
+ );
+
+ testWidgets(
+ 'polls only the local host every 15 seconds and stops while hidden',
+ (tester) async {
+ final app = _App();
+ final monitor = MachineResourceMonitor(app)..start();
+ await tester.pump();
+ expect(app.calls, ['m']);
+ await tester.pump(const Duration(seconds: 14));
+ expect(app.calls, ['m']);
+ await tester.pump(const Duration(seconds: 1));
+ expect(app.calls, ['m', 'm']);
+ await tester.pump(const Duration(seconds: 15));
+ expect(app.calls, ['m', 'm', 'm']);
+ app.appLifecycleChanged(AppLifecycleState.hidden);
+ expect(monitor.reading(monitor.localMachine), isNull);
+ await tester.pump(const Duration(minutes: 2));
+ expect(app.calls, hasLength(3));
+ app.appLifecycleChanged(AppLifecycleState.resumed);
+ await tester.pump();
+ expect(app.calls, ['m', 'm', 'm', 'm']);
+ final count = app.calls.length;
+ await tester.pump(const Duration(seconds: 3));
+ expect(app.calls, hasLength(count));
+ expect(app.allPanes, isEmpty);
+ monitor.dispose();
+ await tester.pump(const Duration(minutes: 1));
+ expect(app.calls, hasLength(count));
+ app.dispose();
+ },
+ );
+
+ testWidgets(
+ 'offline, removed and replacement machines cannot retain a stale reading',
+ (tester) async {
+ final app = _App();
+ final monitor = MachineResourceMonitor(app)..start();
+ await tester.pump();
+ expect(monitor.reading(monitor.localMachine), isNotNull);
+ app.machineStates['m']!.connectionStatus = ConnectionStatus.disconnected;
+ app.changed();
+ await tester.pump();
+ expect(monitor.scopeName, 'M2');
+ expect(monitor.reading(monitor.localMachine), isNull);
+ expect(monitor.detail, contains('Machine disconnected'));
+ final before = app.calls.length;
+ await monitor.refresh();
+ expect(app.calls, hasLength(before));
+ app.machineStates['m']!.connectionStatus = ConnectionStatus.connected;
+ app.pending = Completer();
+ app.changed();
+ await tester.pump();
+ app.machineStates['m'] = MachineState(app.machineStates['m']!.machine)
+ ..localOnly = true
+ ..connectionStatus = ConnectionStatus.connected;
+ app.pending!.complete(const MachineResources(cpuPercent: 99));
+ await tester.pump();
+ expect(monitor.reading(monitor.localMachine), isNull);
+ app.pending = null;
+ app.machineStates.remove('m');
+ app.changed();
+ await tester.pump();
+ expect(monitor.localMachine, isNull);
+ monitor.dispose();
+ app.dispose();
+ },
+ );
+
+ testWidgets(
+ 'footer hides complete groups at narrow widths and retains full details in its tooltip',
+ (tester) async {
+ final app = _App();
+ final monitor = MachineResourceMonitor(app);
+ await monitor.refresh();
+ addTearDown(monitor.dispose);
+ addTearDown(app.dispose);
+ for (final width in [500.0, 270.0, 120.0]) {
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: Center(
+ child: SizedBox(
+ width: width,
+ child: WorkspaceMachineResources(monitor: monitor),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pump();
+ expect(tester.takeException(), isNull);
+ expect(find.text('M2'), findsNothing);
+ expect(
+ tester.widget<Tooltip>(find.byType(Tooltip).first).message,
+ contains('GPU 10%'),
+ );
+ final metricText = tester
+ .widgetList<Text>(find.byType(Text))
+ .map((w) => w.data ?? w.textSpan?.toPlainText() ?? '')
+ .join();
+ if (width == 500) expect(metricText, contains('GPU'));
+ if (width == 120) expect(metricText, 'CPU 20%');
+ }
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+}
diff --git a/desktop/test/machine_resources_test.dart b/desktop/test/machine_resources_test.dart
index 18e899bfd..9c402609f 100644
--- a/desktop/test/machine_resources_test.dart
+++ b/desktop/test/machine_resources_test.dart
@@ -83,6 +83,51 @@ void main() {
}
});
+ test(
+ 'optional hardware fields tolerate old daemons and invalid readings',
+ () {
+ final legacy = MachineResources.fromJson({
+ 'cpuPercent': 20,
+ 'memoryUsedBytes': 4,
+ 'memoryTotalBytes': 8,
+ });
+ expect(legacy.memoryPercent, 50);
+ expect(legacy.busiestGpu, isNull);
+ expect(legacy.diskFreeBytes, isNull);
+ final sample = MachineResources.fromJson({
+ 'memoryPressure': 'normal',
+ 'swapUsedBytes': 0,
+ 'diskFreeBytes': 0,
+ 'diskTotalBytes': 10,
+ 'gpus': [
+ {'id': '1', 'name': 'First GPU', 'utilizationPercent': 80},
+ {'id': '2', 'name': 'Second GPU', 'utilizationPercent': 60},
+ {'id': '3', 'name': 'Unknown GPU', 'utilizationPercent': 101},
+ {'invalid': true},
+ null,
+ ],
+ });
+ expect(sample.busiestGpu!.utilizationPercent, 80);
+ expect(sample.gpus, hasLength(3));
+ expect(sample.gpus.last.utilizationPercent, isNull);
+ expect(sample.swapUsedBytes, 0);
+ expect(sample.diskFreeBytes, 0);
+ expect(sample.memoryPressure, 'normal');
+ final invalid = MachineResources.fromJson({
+ 'memoryPressure': 'invented',
+ 'swapUsedBytes': -1,
+ 'diskFreeBytes': 11,
+ 'diskTotalBytes': 10,
+ });
+ expect(invalid.memoryPressure, isNull);
+ expect(invalid.swapUsedBytes, isNull);
+ expect(invalid.diskFreeBytes, isNull);
+ expect(resourcePercent(19.8), '20%');
+ expect(resourcePercent(null), '-');
+ expect(resourcePercent(0), '0%');
+ },
+ );
+
group('reading over the existing machine connection', () {
test(
'closing the app ignores pending stats and a closing link prompt',
diff --git a/desktop/test/workspace_status_test.dart b/desktop/test/workspace_status_test.dart
index 2fe2caf32..8938b0aae 100644
--- a/desktop/test/workspace_status_test.dart
+++ b/desktop/test/workspace_status_test.dart
@@ -380,20 +380,20 @@ void main() {
subscription('claude', 'aaaaaa', 0),
subscription('codex', 'bbbbbb', 50),
]).text,
- 'Claude 0% Codex 50%',
+ 'Claude 100% Codex 50%',
);
final all = WorkspaceSubscriptionUsage.fromRows([
subscription('claude', 'aaaaaa', 0),
subscription('claude', 'cccccc', .3, status: '<1% remaining'),
subscription('codex', 'bbbbbb', null, status: 'Usage unavailable'),
]);
- expect(all.text, 'Claude aaaaaa 0% Claude cccccc <1% Codex —');
+ expect(all.text, 'Claude aaaaaa 100% Claude cccccc 100% Codex -');
expect(all.detail, contains('Codex (bbbbbb): Usage unavailable'));
expect(all.segments.map((part) => part.tone), [
WorkspaceUsageTone.normal,
- WorkspaceUsageTone.exhausted,
WorkspaceUsageTone.normal,
- WorkspaceUsageTone.low,
+ WorkspaceUsageTone.normal,
+ WorkspaceUsageTone.normal,
WorkspaceUsageTone.normal,
WorkspaceUsageTone.normal,
]);
@@ -407,7 +407,7 @@ void main() {
},
);
- test('only low and exhausted percentages carry readable warning ink', () {
+ test('all subscription percentages use neutral readable ink', () {
final oldBrightness = grid.AppTheme.brightness.value;
addTearDown(() => grid.AppTheme.brightness.value = oldBrightness);
final usage = WorkspaceSubscriptionUsage.fromRows([
@@ -422,15 +422,8 @@ void main() {
foreground: palette.foreground,
surface: palette.workspace,
);
- expect(parts[1].foreground, isNot(palette.foreground));
- expect(parts[3].foreground, isNot(palette.foreground));
- expect(
- parts[1].foreground,
- parts[3].foreground,
- reason: 'Exhausted allowance shares quiet amber with low allowance.',
- );
- for (final index in [0, 2, 4, 5]) {
- expect(parts[index].foreground, palette.foreground);
+ for (final part in parts) {
+ expect(part.foreground, palette.foreground);
}
for (final part in parts) {
final ink = part.foreground.computeLuminance();
@@ -464,6 +457,7 @@ void main() {
subscription('codex', 'bbbbbb', 13),
];
final app = createApp();
+ app.machineStates['m']!.localOnly = true;
final pane = app.adoptSessionForTest(terminal('a0', []));
addTearDown(app.dispose);
addTearDown(subscriptions.dispose);
@@ -481,23 +475,20 @@ void main() {
),
);
await tester.pumpAndSettle();
- const label = 'Claude 0% Codex 13%';
+ const label = 'Claude 100% Codex 87%';
if (native) {
expect(updates.last['subscriptionUsage']['text'], label);
final parts = updates.last['subscriptionUsage']['segments'] as List;
expect(parts.map((part) => part['text']), [
'Claude ',
- '0%',
- ' Codex ',
- '13%',
+ '100%',
+ ' Codex ',
+ '87%',
]);
expect(parts[0]['foreground'], parts[2]['foreground']);
- expect(parts[1]['foreground'], isNot(parts[0]['foreground']));
- expect(parts[3]['foreground'], isNot(parts[0]['foreground']));
- expect(
- updates.last['subscriptionUsage']['detail'],
- contains('remaining'),
- );
+ expect(parts[1]['foreground'], parts[0]['foreground']);
+ expect(parts[3]['foreground'], parts[0]['foreground']);
+ expect(updates.last['subscriptionUsage']['detail'], contains('used'));
} else {
expect(find.text(label), findsOneWidget);
final usage = find.byKey(
@@ -524,10 +515,39 @@ void main() {
}
tester.view.physicalSize = const Size(1280, 800);
}
+ if (native) {
+ expect(
+ updates.last['machineResources']['text'],
+ 'CPU - RAM - GPU -',
+ );
+ expect(
+ updates.last['machineResources']['detail'],
+ startsWith('Test host'),
+ );
+ 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;
+ } else {
+ await tester.tap(
+ find.byKey(const ValueKey('workspace-machine-resources')),
+ );
+ await tester.pumpAndSettle();
+ }
+ expect(find.text('Memory pressure'), findsNothing);
+ expect(app.focusedPane, same(pane));
+ expect(app.panes, [pane]);
subscriptions.update([subscription('codex', 'bbbbbb', 27)]);
await tester.pump();
if (native) {
- expect(updates.last['subscriptionUsage']['text'], 'Codex 27%');
+ expect(updates.last['subscriptionUsage']['text'], 'Codex 73%');
final done = Completer<void>();
messenger.handlePlatformMessage(
channel.name,
@@ -539,7 +559,7 @@ void main() {
await tester.pumpAndSettle();
await done.future;
} else {
- expect(find.text('Codex 27%'), findsOneWidget);
+ expect(find.text('Codex 73%'), findsOneWidget);
await tester.tap(
find.byKey(const ValueKey('workspace-subscription-usage')),
);
diff --git a/desktop/tool/swarm_titlebar_checks.swift b/desktop/tool/swarm_titlebar_checks.swift
index 3eaf24279..6cd1be135 100644
--- a/desktop/tool/swarm_titlebar_checks.swift
+++ b/desktop/tool/swarm_titlebar_checks.swift
@@ -1542,7 +1542,7 @@ private extension SwarmTabStrip {
newButton.frame.maxX < searchButton.frame.minX, "Tabs precede the search and Store controls")
try checkTitlebar(tabs[0].frame.width < 136 && tabs[0].displayLabel == "code",
"Overflow tabs keep readable names without persistent number prefixes")
- try checkTitlebar(subviews.count == 4 && statusBar.subviews.count == 7 && pullRequestButton.isHidden && subscriptionUsageButton.isHidden && harnessMonitorButton.isHidden && daemonButton.isHidden && voiceLabel.isHidden && shareButton.isHidden,
+ try checkTitlebar(subviews.count == 4 && statusBar.subviews.count == 8 && machineResourcesLabel.isHidden && pullRequestButton.isHidden && subscriptionUsageButton.isHidden && harnessMonitorButton.isHidden && daemonButton.isHidden && voiceLabel.isHidden && shareButton.isHidden,
"Navigation lives in the titlebar and focused context lives in the footer")
let controls = [newButton]
for control in controls {
@@ -2508,9 +2508,13 @@ do {
private extension SwarmTabStrip {
func checkHarnessMonitor() throws {
var state: [String: Any] = ["enabled": true,
- "harnessMonitor": ["text": "10 live · 1.4 GB · 12% CPU", "segments": [["text": "10 live · 1.4 GB · 12% CPU"]], "label": "Harness Monitor", "detail": "RAM includes child processes", "interactive": true],
- "subscriptionUsage": ["text": "Claude 12% Codex 30%", "interactive": true],
- "focusedContext": ["text": "Computer > project > branch", "interactive": 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%"]],
+ "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) }
@@ -2521,19 +2525,33 @@ private extension SwarmTabStrip {
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 &&
+ machineResourcesLabel.frame.minX >= harnessMonitorButton.frame.maxX &&
+ machineResourcesLabel.frame.maxX <= contextButton.frame.minX,
+ "Read-only hardware never overlaps count or focused context at width \(width)")
try checkTitlebar(harnessMonitorButton.accessibilityLabel() == "Harness Monitor",
"The resource counter names its action for VoiceOver")
try checkTitlebar(subscriptionUsageButton.isHidden == (width < 1050),
"Narrow footers retain the monitor while subscriptions remain accessible through Models")
+ if let capture = ProcessInfo.processInfo.environment["HARNESS_RESOURCE_CAPTURE_DIR"] {
+ let root = URL(fileURLWithPath: capture)
+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
+ try statusBar.renderedTree(background: NSColor(white: 0.12, alpha: 1))
+ .representation(using: .png, properties: [:])!.write(to:
+ root.appendingPathComponent("native-resources-\(Int(width)).png"))
+ }
}
+ machineResourcesLabel.performClick(nil)
harnessMonitorButton.performClick(nil)
- try checkTitlebar(calls == ["resourceMonitor"], "The footer opens the session monitor, never a new agent")
+ try checkTitlebar(calls == ["resourceMonitor"], "Only the session count opens a panel; hardware stays read-only")
state["enabled"] = false
update(state)
harnessMonitorButton.performClick(nil)
- try checkTitlebar(calls.count == 1, "A covered or modal footer cannot open its monitor")
+ machineResourcesLabel.performClick(nil)
+ try checkTitlebar(calls.count == 1, "A covered or modal footer cannot open the session monitor")
update([:])
- try checkTitlebar(harnessMonitorButton.isHidden && !harnessMonitorButton.isEnabled,
- "Clearing workspace state clears the counter and action")
+ try checkTitlebar(harnessMonitorButton.isHidden && !harnessMonitorButton.isEnabled && machineResourcesLabel.isHidden && !machineResourcesLabel.isEnabled,
+ "Clearing workspace state clears the counter, hardware and actions")
}
}